diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/_virtualenv.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/_virtualenv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33a0fac1eda600d7a2e3a3a628da127c281000f0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/_virtualenv.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/six.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/six.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca7f2b816128fb96eda340f9756df1c791d4565b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/six.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/threadpoolctl.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/threadpoolctl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2be2930e67fdea3acc216bf2214558a12bc73cc8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/__pycache__/threadpoolctl.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb123b8bbe1985ef58c86eec996b8b100261ae71 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__init__.py @@ -0,0 +1,66 @@ +"""A logging formatter for colored output.""" + +import sys +import warnings + +from colorlog.formatter import ( + ColoredFormatter, + LevelFormatter, + TTYColoredFormatter, + default_log_colors, +) +from colorlog.wrappers import ( + CRITICAL, + DEBUG, + ERROR, + FATAL, + INFO, + NOTSET, + StreamHandler, + WARN, + WARNING, + basicConfig, + critical, + debug, + error, + exception, + getLogger, + info, + log, + root, + warning, +) + +__all__ = ( + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "INFO", + "NOTSET", + "WARN", + "WARNING", + "ColoredFormatter", + "LevelFormatter", + "StreamHandler", + "TTYColoredFormatter", + "basicConfig", + "critical", + "debug", + "default_log_colors", + "error", + "exception", + "exception", + "getLogger", + "info", + "log", + "root", + "warning", +) + +if sys.version_info < (3, 6): + warnings.warn( + "Colorlog requires Python 3.6 or above. Pin 'colorlog<5' to your dependencies " + "if you require compatibility with older versions of Python. See " + "https://github.com/borntyping/python-colorlog#status for more information." + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c91d2b55bd7281cad965055affd738a07e5009a6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/escape_codes.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/escape_codes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0df9357eacb7fc7d825777ee3fa3539dec1cce0f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/escape_codes.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/formatter.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/formatter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc05e568f7b2e55cb522575ec46be49555153518 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/formatter.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/wrappers.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/wrappers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4d9251300c99fdbb46fa671420ef26b81afe025 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/__pycache__/wrappers.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/escape_codes.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/escape_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..185b947353fbd973728018e78ed4751d9129f083 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/escape_codes.py @@ -0,0 +1,105 @@ +""" +Generates a dictionary of ANSI escape codes. + +http://en.wikipedia.org/wiki/ANSI_escape_code + +Uses colorama as an optional dependency to support color on Windows +""" + +import sys + +try: + import colorama +except ImportError: + pass +else: + if sys.platform == "win32": + colorama.init(strip=False) + +__all__ = ("escape_codes", "parse_colors") + + +# Returns escape codes from format codes +def esc(*codes: int) -> str: + return "\033[" + ";".join(str(code) for code in codes) + "m" + + +escape_codes = { + "reset": esc(0), + "bold": esc(1), + "thin": esc(2), +} + +escape_codes_foreground = { + "black": 30, + "red": 31, + "green": 32, + "yellow": 33, + "blue": 34, + "purple": 35, + "cyan": 36, + "white": 37, + "light_black": 90, + "light_red": 91, + "light_green": 92, + "light_yellow": 93, + "light_blue": 94, + "light_purple": 95, + "light_cyan": 96, + "light_white": 97, +} + +escape_codes_background = { + "black": 40, + "red": 41, + "green": 42, + "yellow": 43, + "blue": 44, + "purple": 45, + "cyan": 46, + "white": 47, + "light_black": 100, + "light_red": 101, + "light_green": 102, + "light_yellow": 103, + "light_blue": 104, + "light_purple": 105, + "light_cyan": 106, + "light_white": 107, + # Bold background colors don't exist, + # but we used to provide these names. + "bold_black": 100, + "bold_red": 101, + "bold_green": 102, + "bold_yellow": 103, + "bold_blue": 104, + "bold_purple": 105, + "bold_cyan": 106, + "bold_white": 107, +} + +# Foreground without prefix +for name, code in escape_codes_foreground.items(): + escape_codes["%s" % name] = esc(code) + escape_codes["bold_%s" % name] = esc(1, code) + escape_codes["thin_%s" % name] = esc(2, code) + +# Foreground with fg_ prefix +for name, code in escape_codes_foreground.items(): + escape_codes["fg_%s" % name] = esc(code) + escape_codes["fg_bold_%s" % name] = esc(1, code) + escape_codes["fg_thin_%s" % name] = esc(2, code) + +# Background with bg_ prefix +for name, code in escape_codes_background.items(): + escape_codes["bg_%s" % name] = esc(code) + +# 256 colour support +for code in range(256): + escape_codes["fg_%d" % code] = esc(38, 5, code) + escape_codes["bg_%d" % code] = esc(48, 5, code) + + +def parse_colors(string: str) -> str: + """Return escape codes from a color sequence string.""" + return "".join(escape_codes[n] for n in string.split(",") if n) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/formatter.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..e4fb14d71778c08567f5dbab559cea2b48da1795 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/formatter.py @@ -0,0 +1,239 @@ +"""The ColoredFormatter class.""" + +import logging +import os +import sys +import typing +import traceback +import io + +import colorlog.escape_codes + +__all__ = ( + "default_log_colors", + "ColoredFormatter", + "LevelFormatter", + "TTYColoredFormatter", +) + +# Type aliases used in function signatures. +EscapeCodes = typing.Mapping[str, str] +LogColors = typing.Mapping[str, str] +SecondaryLogColors = typing.Mapping[str, LogColors] +if sys.version_info >= (3, 8): + _FormatStyle = typing.Literal["%", "{", "$"] +else: + _FormatStyle = str + +# The default colors to use for the debug levels +default_log_colors = { + "DEBUG": "white", + "INFO": "green", + "WARNING": "yellow", + "ERROR": "red", + "CRITICAL": "bold_red", +} + +# The default format to use for each style +default_formats = { + "%": "%(log_color)s%(levelname)s:%(name)s:%(message)s", + "{": "{log_color}{levelname}:{name}:{message}", + "$": "${log_color}${levelname}:${name}:${message}", +} + + +class ColoredRecord: + """ + Wraps a LogRecord, adding escape codes to the internal dict. + + The internal dict is used when formatting the message (by the PercentStyle, + StrFormatStyle, and StringTemplateStyle classes). + """ + + def __init__(self, record: logging.LogRecord, escapes: EscapeCodes) -> None: + self.__dict__.update(record.__dict__) + self.__dict__.update(escapes) + + +class ColoredFormatter(logging.Formatter): + """ + A formatter that allows colors to be placed in the format string. + + Intended to help in creating more readable logging output. + """ + + def __init__( + self, + fmt: typing.Optional[str] = None, + datefmt: typing.Optional[str] = None, + style: _FormatStyle = "%", + log_colors: typing.Optional[LogColors] = None, + reset: bool = True, + secondary_log_colors: typing.Optional[SecondaryLogColors] = None, + validate: bool = True, + stream: typing.Optional[typing.IO] = None, + no_color: bool = False, + force_color: bool = False, + defaults: typing.Optional[typing.Mapping[str, typing.Any]] = None, + ) -> None: + """ + Set the format and colors the ColoredFormatter will use. + + The ``fmt``, ``datefmt``, ``style``, and ``default`` args are passed on to the + ``logging.Formatter`` constructor. + + The ``secondary_log_colors`` argument can be used to create additional + ``log_color`` attributes. Each key in the dictionary will set + ``{key}_log_color``, using the value to select from a different + ``log_colors`` set. + + :Parameters: + - fmt (str): The format string to use. + - datefmt (str): A format string for the date. + - log_colors (dict): + A mapping of log level names to color names. + - reset (bool): + Implicitly append a color reset to all records unless False. + - style ('%' or '{' or '$'): + The format style to use. + - secondary_log_colors (dict): + Map secondary ``log_color`` attributes. (*New in version 2.6.*) + - validate (bool) + Validate the format string. + - stream (typing.IO) + The stream formatted messages will be printed to. Used to toggle colour + on non-TTY outputs. Optional. + - no_color (bool): + Disable color output. + - force_color (bool): + Enable color output. Takes precedence over `no_color`. + """ + + # Select a default format if `fmt` is not provided. + fmt = default_formats[style] if fmt is None else fmt + + if sys.version_info >= (3, 10): + super().__init__(fmt, datefmt, style, validate, defaults=defaults) + elif sys.version_info >= (3, 8): + super().__init__(fmt, datefmt, style, validate) + else: + super().__init__(fmt, datefmt, style) + + self.log_colors = log_colors if log_colors is not None else default_log_colors + self.secondary_log_colors = ( + secondary_log_colors if secondary_log_colors is not None else {} + ) + self.reset = reset + self.stream = stream + self.no_color = no_color + self.force_color = force_color + + def formatMessage(self, record: logging.LogRecord) -> str: + """Format a message from a record object.""" + escapes = self._escape_code_map(record.levelname) + wrapper = ColoredRecord(record, escapes) + message = super().formatMessage(wrapper) # type: ignore + message = self._append_reset(message, escapes) + return message + + def _escape_code_map(self, item: str) -> EscapeCodes: + """ + Build a map of keys to escape codes for use in message formatting. + + If _color() returns False, all values will be an empty string. + """ + codes = {**colorlog.escape_codes.escape_codes} + codes.setdefault("log_color", self._get_escape_code(self.log_colors, item)) + for name, colors in self.secondary_log_colors.items(): + codes.setdefault("%s_log_color" % name, self._get_escape_code(colors, item)) + if not self._colorize(): + codes = {key: "" for key in codes.keys()} + return codes + + def _colorize(self): + """Return False if we should be prevented from printing escape codes.""" + if self.force_color or "FORCE_COLOR" in os.environ: + return True + + if self.no_color or "NO_COLOR" in os.environ: + return False + + if self.stream is not None and not self.stream.isatty(): + return False + + return True + + @staticmethod + def _get_escape_code(log_colors: LogColors, item: str) -> str: + """Extract a color sequence from a mapping, and return escape codes.""" + return colorlog.escape_codes.parse_colors(log_colors.get(item, "")) + + def _append_reset(self, message: str, escapes: EscapeCodes) -> str: + """Add a reset code to the end of the message, if it's not already there.""" + reset_escape_code = escapes["reset"] + + if self.reset and not message.endswith(reset_escape_code): + message += reset_escape_code + + return message + + if sys.version_info >= (3, 13): + + def formatException(self, ei) -> str: + """ + Format and return the specified exception information as a string. + + This is a copy of logging.Formatter.formatException that passes in + an appropriate value for colorize to print_exception. + """ + kwargs = dict(colorize=self._colorize()) + + sio = io.StringIO() + tb = ei[2] + traceback.print_exception(ei[0], ei[1], tb, limit=None, file=sio, **kwargs) + s = sio.getvalue() + sio.close() + if s[-1:] == "\n": + s = s[:-1] + return s + + +class LevelFormatter: + """An extension of ColoredFormatter that uses per-level format strings.""" + + def __init__(self, fmt: typing.Mapping[str, str], **kwargs: typing.Any) -> None: + """ + Configure a ColoredFormatter with its own format string for each log level. + + Supports fmt as a dict. All other args are passed on to the + ``colorlog.ColoredFormatter`` constructor. + + :Parameters: + - fmt (dict): + A mapping of log levels (represented as strings, e.g. 'WARNING') to + format strings. (*New in version 2.7.0) + (All other parameters are the same as in colorlog.ColoredFormatter) + + Example: + + formatter = colorlog.LevelFormatter( + fmt={ + "DEBUG": "%(log_color)s%(message)s (%(module)s:%(lineno)d)", + "INFO": "%(log_color)s%(message)s", + "WARNING": "%(log_color)sWRN: %(message)s (%(module)s:%(lineno)d)", + "ERROR": "%(log_color)sERR: %(message)s (%(module)s:%(lineno)d)", + "CRITICAL": "%(log_color)sCRT: %(message)s (%(module)s:%(lineno)d)", + } + ) + """ + self.formatters = { + level: ColoredFormatter(fmt=f, **kwargs) for level, f in fmt.items() + } + + def format(self, record: logging.LogRecord) -> str: + return self.formatters[record.levelname].format(record) + + +# Provided for backwards compatibility. The features provided by this subclass are now +# included directly in the `ColoredFormatter` class. +TTYColoredFormatter = ColoredFormatter diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/py.typed b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/wrappers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..e05756fbac347d215d2f6732f00f2e9fab991381 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/colorlog/wrappers.py @@ -0,0 +1,101 @@ +"""Wrappers around the logging module.""" + +import functools +import logging +import sys +import typing +from logging import ( + CRITICAL, + DEBUG, + ERROR, + FATAL, + INFO, + NOTSET, + StreamHandler, + WARN, + WARNING, + getLogger, + root, +) + +import colorlog.formatter + +__all__ = ( + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "INFO", + "NOTSET", + "WARN", + "WARNING", + "StreamHandler", + "basicConfig", + "critical", + "debug", + "error", + "exception", + "getLogger", + "info", + "log", + "root", + "warning", +) + + +def basicConfig( + style: colorlog.formatter._FormatStyle = "%", + log_colors: typing.Optional[colorlog.formatter.LogColors] = None, + reset: bool = True, + secondary_log_colors: typing.Optional[colorlog.formatter.SecondaryLogColors] = None, + format: str = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s", + datefmt: typing.Optional[str] = None, + **kwargs +) -> None: + """Call ``logging.basicConfig`` and override the formatter it creates.""" + logging.basicConfig(**kwargs) + + def _basicConfig(): + handler = logging.root.handlers[0] + handler.setFormatter( + colorlog.formatter.ColoredFormatter( + fmt=format, + datefmt=datefmt, + style=style, + log_colors=log_colors, + reset=reset, + secondary_log_colors=secondary_log_colors, + stream=kwargs.get("stream", None), + ) + ) + + if sys.version_info >= (3, 13): + with logging._lock: # type: ignore + _basicConfig() + else: + logging._acquireLock() # type: ignore + try: + _basicConfig() + finally: + logging._releaseLock() # type: ignore + + +def ensure_configured(func): + """Modify a function to call our basicConfig() first if no handlers exist.""" + + @functools.wraps(func) + def wrapper(*args, **kwargs): + if len(logging.root.handlers) == 0: + basicConfig() + return func(*args, **kwargs) + + return wrapper + + +debug = ensure_configured(logging.debug) +info = ensure_configured(logging.info) +warning = ensure_configured(logging.warning) +error = ensure_configured(logging.error) +critical = ensure_configured(logging.critical) +log = ensure_configured(logging.log) +exception = ensure_configured(logging.exception) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5a5dff2816e1f9d945fd296f04cf69117603e43b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/METADATA @@ -0,0 +1,2228 @@ +Metadata-Version: 2.4 +Name: fonttools +Version: 4.60.1 +Summary: Tools to manipulate font files +Home-page: http://github.com/fonttools/fonttools +Author: Just van Rossum +Author-email: just@letterror.com +Maintainer: Behdad Esfahbod +Maintainer-email: behdad@behdad.org +License: MIT +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Environment :: Other Environment +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: End Users/Desktop +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Text Processing :: Fonts +Classifier: Topic :: Multimedia :: Graphics +Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.external +Provides-Extra: ufo +Provides-Extra: lxml +Requires-Dist: lxml>=4.0; extra == "lxml" +Provides-Extra: woff +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "woff" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "woff" +Requires-Dist: zopfli>=0.1.4; extra == "woff" +Provides-Extra: unicode +Requires-Dist: unicodedata2>=15.1.0; python_version <= "3.12" and extra == "unicode" +Provides-Extra: graphite +Requires-Dist: lz4>=1.7.4.2; extra == "graphite" +Provides-Extra: interpolatable +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "interpolatable" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "interpolatable" +Requires-Dist: pycairo; extra == "interpolatable" +Provides-Extra: plot +Requires-Dist: matplotlib; extra == "plot" +Provides-Extra: symfont +Requires-Dist: sympy; extra == "symfont" +Provides-Extra: type1 +Requires-Dist: xattr; sys_platform == "darwin" and extra == "type1" +Provides-Extra: pathops +Requires-Dist: skia-pathops>=0.5.0; extra == "pathops" +Provides-Extra: repacker +Requires-Dist: uharfbuzz>=0.23.0; extra == "repacker" +Provides-Extra: all +Requires-Dist: lxml>=4.0; extra == "all" +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "all" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "all" +Requires-Dist: zopfli>=0.1.4; extra == "all" +Requires-Dist: unicodedata2>=15.1.0; python_version <= "3.12" and extra == "all" +Requires-Dist: lz4>=1.7.4.2; extra == "all" +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "all" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "all" +Requires-Dist: pycairo; extra == "all" +Requires-Dist: matplotlib; extra == "all" +Requires-Dist: sympy; extra == "all" +Requires-Dist: xattr; sys_platform == "darwin" and extra == "all" +Requires-Dist: skia-pathops>=0.5.0; extra == "all" +Requires-Dist: uharfbuzz>=0.23.0; extra == "all" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: platform +Dynamic: provides-extra +Dynamic: requires-python +Dynamic: summary + +|CI Build Status| |Coverage Status| |PyPI| |Gitter Chat| + +What is this? +~~~~~~~~~~~~~ + +| fontTools is a library for manipulating fonts, written in Python. The + project includes the TTX tool, that can convert TrueType and OpenType + fonts to and from an XML text format, which is also called TTX. It + supports TrueType, OpenType, AFM and to an extent Type 1 and some + Mac-specific formats. The project has an `MIT open-source + license `__. +| Among other things this means you can use it free of charge. + +`User documentation `_ and +`developer documentation `_ +are available at `Read the Docs `_. + +Installation +~~~~~~~~~~~~ + +FontTools requires `Python `__ 3.9 +or later. We try to follow the same schedule of minimum Python version support as +NumPy (see `NEP 29 `__). + +The package is listed in the Python Package Index (PyPI), so you can +install it with `pip `__: + +.. code:: sh + + pip install fonttools + +If you would like to contribute to its development, you can clone the +repository from GitHub, install the package in 'editable' mode and +modify the source code in place. We recommend creating a virtual +environment, using `virtualenv `__ or +Python 3 `venv `__ module. + +.. code:: sh + + # download the source code to 'fonttools' folder + git clone https://github.com/fonttools/fonttools.git + cd fonttools + + # create new virtual environment called e.g. 'fonttools-venv', or anything you like + python -m virtualenv fonttools-venv + + # source the `activate` shell script to enter the environment (Unix-like); to exit, just type `deactivate` + . fonttools-venv/bin/activate + + # to activate the virtual environment in Windows `cmd.exe`, do + fonttools-venv\Scripts\activate.bat + + # install in 'editable' mode + pip install -e . + +Optional Requirements +--------------------- + +The ``fontTools`` package currently has no (required) external dependencies +besides the modules included in the Python Standard Library. +However, a few extra dependencies are required by some of its modules, which +are needed to unlock optional features. +The ``fonttools`` PyPI distribution also supports so-called "extras", i.e. a +set of keywords that describe a group of additional dependencies, which can be +used when installing via pip, or when specifying a requirement. +For example: + +.. code:: sh + + pip install fonttools[ufo,lxml,woff,unicode] + +This command will install fonttools, as well as the optional dependencies that +are required to unlock the extra features named "ufo", etc. + +- ``Lib/fontTools/misc/etree.py`` + + The module exports a ElementTree-like API for reading/writing XML files, and + allows to use as the backend either the built-in ``xml.etree`` module or + `lxml `__. The latter is preferred whenever present, + as it is generally faster and more secure. + + *Extra:* ``lxml`` + +- ``Lib/fontTools/ttLib/woff2.py`` + + Module to compress/decompress WOFF 2.0 web fonts; it requires: + + * `brotli `__: Python bindings of + the Brotli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/ttLib/sfnt.py`` + + To better compress WOFF 1.0 web fonts, the following module can be used + instead of the built-in ``zlib`` library: + + * `zopfli `__: Python bindings of + the Zopfli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/unicode.py`` + + To display the Unicode character names when dumping the ``cmap`` table + with ``ttx`` we use the ``unicodedata`` module in the Standard Library. + The version included in there varies between different Python versions. + To use the latest available data, you can install: + + * `unicodedata2 `__: + ``unicodedata`` backport for Python 3.x updated to the latest Unicode + version 15.0. + + *Extra:* ``unicode`` + +- ``Lib/fontTools/varLib/interpolatable.py`` + + Module for finding wrong contour/component order between different masters. + It requires one of the following packages in order to solve the so-called + "minimum weight perfect matching problem in bipartite graphs", or + the Assignment problem: + + * `scipy `__: the Scientific Library + for Python, which internally uses `NumPy `__ + arrays and hence is very fast; + * `munkres `__: a pure-Python + module that implements the Hungarian or Kuhn-Munkres algorithm. Slower than + SciPy, but useful for minimalistic systems where adding SciPy is undesirable. + + This ensures both performance (via SciPy) and minimal footprint (via Munkres) + are possible. + + To plot the results to a PDF or HTML format, you also need to install: + + * `pycairo `__: Python bindings for the + Cairo graphics library. Note that wheels are currently only available for + Windows, for other platforms see pycairo's `installation instructions + `__. + + *Extra:* ``interpolatable`` + +- ``Lib/fontTools/varLib/plot.py`` + + Module for visualizing DesignSpaceDocument and resulting VariationModel. + + * `matplotlib `__: 2D plotting library. + + *Extra:* ``plot`` + +- ``Lib/fontTools/misc/symfont.py`` + + Advanced module for symbolic font statistics analysis; it requires: + + * `sympy `__: the Python library for + symbolic mathematics. + + *Extra:* ``symfont`` + +- ``Lib/fontTools/t1Lib.py`` + + To get the file creator and type of Macintosh PostScript Type 1 fonts + on Python 3 you need to install the following module, as the old ``MacOS`` + module is no longer included in Mac Python: + + * `xattr `__: Python wrapper for + extended filesystem attributes (macOS platform only). + + *Extra:* ``type1`` + +- ``Lib/fontTools/ttLib/removeOverlaps.py`` + + Simplify TrueType glyphs by merging overlapping contours and components. + + * `skia-pathops `__: Python + bindings for the Skia library's PathOps module, performing boolean + operations on paths (union, intersection, etc.). + + *Extra:* ``pathops`` + +- ``Lib/fontTools/ufoLib`` + + Package for reading and writing UFO source files; if available, it will use: + + * `fs `__: (aka ``pyfilesystem2``) filesystem abstraction layer + + for reading and writing UFOs to the local filesystem or zip files (.ufoz), instead of + the built-in ``fontTools.misc.filesystem`` package. + The reader and writer classes can in theory also accept any object compatible the + ``fs.base.FS`` interface, although not all have been tested. + +- ``Lib/fontTools/pens/cocoaPen.py`` and ``Lib/fontTools/pens/quartzPen.py`` + + Pens for drawing glyphs with Cocoa ``NSBezierPath`` or ``CGPath`` require: + + * `PyObjC `__: the bridge between + Python and the Objective-C runtime (macOS platform only). + +- ``Lib/fontTools/pens/qtPen.py`` + + Pen for drawing glyphs with Qt's ``QPainterPath``, requires: + + * `PyQt5 `__: Python bindings for + the Qt cross platform UI and application toolkit. + +- ``Lib/fontTools/pens/reportLabPen.py`` + + Pen to drawing glyphs as PNG images, requires: + + * `reportlab `__: Python toolkit + for generating PDFs and graphics. + +- ``Lib/fontTools/pens/freetypePen.py`` + + Pen to drawing glyphs with FreeType as raster images, requires: + + * `freetype-py `__: Python binding + for the FreeType library. + +- ``Lib/fontTools/ttLib/tables/otBase.py`` + + Use the Harfbuzz library to serialize GPOS/GSUB using ``hb_repack`` method, requires: + + * `uharfbuzz `__: Streamlined Cython + bindings for the harfbuzz shaping engine + + *Extra:* ``repacker`` + +How to make a new release +~~~~~~~~~~~~~~~~~~~~~~~~~ + +1) Update ``NEWS.rst`` with all the changes since the last release. Write a + changelog entry for each PR, with one or two short sentences summarizing it, + as well as links to the PR and relevant issues addressed by the PR. Do not + put a new title, the next command will do it for you. +2) Use semantic versioning to decide whether the new release will be a 'major', + 'minor' or 'patch' release. It's usually one of the latter two, depending on + whether new backward compatible APIs were added, or simply some bugs were fixed. +3) From inside a venv, first do ``pip install -r dev-requirements.txt``, then run + the ``python setup.py release`` command from the tip of the ``main`` branch. + By default this bumps the third or 'patch' digit only, unless you pass ``--major`` + or ``--minor`` to bump respectively the first or second digit. + This bumps the package version string, extracts the changes since the latest + version from ``NEWS.rst``, and uses that text to create an annotated git tag + (or a signed git tag if you pass the ``--sign`` option and your git and Github + account are configured for `signing commits `__ + using a GPG key). + It also commits an additional version bump which opens the main branch for + the subsequent developmental cycle +4) Push both the tag and commit to the upstream repository, by running the command + ``git push --follow-tags``. Note: it may push other local tags as well, be + careful. +5) Let the CI build the wheel and source distribution packages and verify both + get uploaded to the Python Package Index (PyPI). +6) [Optional] Go to fonttools `Github Releases `__ + page and create a new release, copy-pasting the content of the git tag + message. This way, the release notes are nicely formatted as markdown, and + users watching the repo will get an email notification. One day we shall + automate that too. + + +Acknowledgments +~~~~~~~~~~~~~~~~ + +In alphabetical order: + +aschmitz, Olivier Berten, Samyak Bhuta, Erik van Blokland, Petr van Blokland, +Jelle Bosma, Sascha Brawer, Tom Byrer, Antonio Cavedoni, Frédéric Coiffier, +Vincent Connare, David Corbett, Simon Cozens, Dave Crossland, Simon Daniels, +Peter Dekkers, Behdad Esfahbod, Behnam Esfahbod, Hannes Famira, Sam Fishman, +Matt Fontaine, Takaaki Fuji, Rob Hagemans, Yannis Haralambous, Greg Hitchcock, +Jeremie Hornus, Khaled Hosny, John Hudson, Denis Moyogo Jacquerye, Jack Jansen, +Tom Kacvinsky, Jens Kutilek, Antoine Leca, Werner Lemberg, Tal Leming, Liang Hai, Peter +Lofting, Cosimo Lupo, Olli Meier, Masaya Nakamura, Dave Opstad, Laurence Penney, +Roozbeh Pournader, Garret Rieger, Read Roberts, Colin Rofls, Guido van Rossum, +Just van Rossum, Andreas Seidel, Georg Seifert, Chris Simpkins, Miguel Sousa, +Adam Twardoch, Adrien Tétar, Vitaly Volkov, Paul Wise. + +Copyrights +~~~~~~~~~~ + +| Copyright (c) 1999-2004 Just van Rossum, LettError + (just@letterror.com) +| See `LICENSE `__ for the full license. + +Copyright (c) 2000 BeOpen.com. All Rights Reserved. + +Copyright (c) 1995-2001 Corporation for National Research Initiatives. +All Rights Reserved. + +Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All +Rights Reserved. + +Have fun! + +.. |CI Build Status| image:: https://github.com/fonttools/fonttools/workflows/Test/badge.svg + :target: https://github.com/fonttools/fonttools/actions?query=workflow%3ATest +.. |Coverage Status| image:: https://codecov.io/gh/fonttools/fonttools/branch/main/graph/badge.svg + :target: https://codecov.io/gh/fonttools/fonttools +.. |PyPI| image:: https://img.shields.io/pypi/v/fonttools.svg + :target: https://pypi.org/project/FontTools +.. |Gitter Chat| image:: https://badges.gitter.im/fonttools-dev/Lobby.svg + :alt: Join the chat at https://gitter.im/fonttools-dev/Lobby + :target: https://gitter.im/fonttools-dev/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge + +Changelog +~~~~~~~~~ + +4.60.1 (released 2025-09-29) +---------------------------- + +- [ufoLib] Reverted accidental method name change in ``UFOReader.getKerningGroupConversionRenameMaps`` + that broke compatibility with downstream projects like defcon (#3948, #3947, robotools/defcon#478). +- [ufoLib] Added test coverage for ``getKerningGroupConversionRenameMaps`` method (#3950). +- [subset] Don't try to subset BASE table; pass it through by default instead (#3949). +- [subset] Remove empty BaseRecord entries in MarkBasePos lookups (#3897, #3892). +- [subset] Add pruning for MarkLigPos and MarkMarkPos lookups (#3946). +- [subset] Remove duplicate features when subsetting (#3945). +- [Docs] Added documentation for the visitor module (#3944). + +4.60.0 (released 2025-09-17) +---------------------------- + +- [pointPen] Allow ``reverseFlipped`` parameter of ``DecomposingPointPen`` to take a ``ReverseFlipped`` + enum value to control whether/how to reverse contour direction of flipped components, in addition to + the existing True/False. This allows to set ``ReverseFlipped.ON_CURVE_FIRST`` to ensure that + the decomposed outline starts with an on-curve point before being reversed, for better consistency + with other segment-oriented contour transformations. The change is backward compatible, and the + default behavior hasn't changed (#3934). +- [filterPen] Added ``ContourFilterPointPen``, base pen for buffered contour operations, and + ``OnCurveStartPointPen`` filter to ensure contours start with an on-curve point (#3934). +- [cu2qu] Fixed difference in cython vs pure-python complex division by real number (#3930). +- [varLib.avar] Refactored and added some new sub-modules and scripts (#3926). + * ``varLib.avar.build`` module to build avar (and a missing fvar) binaries into a possibly empty TTFont, + * ``varLib.avar.unbuild`` module to print a .designspace snippet that would generate the same avar binary, + * ``varLib.avar.map`` module to take TTFont and do the mapping, in user/normalized space, + * ``varLib.avar.plan`` module moved from ``varLib.avarPlanner``. + The bare ``fonttools varLib.avar`` script is deprecated, in favour of ``fonttools varLib.avar.build`` (or ``unbuild``). +- [interpolatable] Clarify ``linear_sum_assignment`` backend options and minimal dependency + usage (#3927). +- [post] Speed up ``build_psNameMapping`` (#3923). +- [ufoLib] Added typing annotations to fontTools.ufoLib (#3875). + +4.59.2 (released 2025-08-27) +---------------------------- + +- [varLib] Clear ``USE_MY_METRICS`` component flags when inconsistent across masters (#3912). +- [varLib.instancer] Avoid negative advance width/height values when instatiating HVAR/VVAR, + (unlikely in well-behaved fonts) (#3918). +- [subset] Fix shaping behaviour when pruning empty mark sets (#3915, harfbuzz/harfbuzz#5499). +- [cu2qu] Fixed ``dot()`` product of perpendicular vectors not always returning exactly 0.0 + in all Python implementations (#3911) +- [varLib.instancer] Implemented fully-instantiating ``avar2`` fonts (#3909). +- [feaLib] Allow float values in ``VariableScalar``'s axis locations (#3906, #3907). +- [cu2qu] Handle special case in ``calc_intersect`` for degenerate cubic curves where 3 to 4 + control points are equal (#3904). + +4.59.1 (released 2025-08-14) +---------------------------- + +- [featureVars] Update OS/2.usMaxContext if possible after addFeatureVariationsRaw (#3894). +- [vhmtx] raise TTLibError('not enough data...') when hmtx/vmtx are truncated (#3843, #3901). +- [feaLib] Combine duplicate features that have the same set of lookups regardless of the order in which those lookups are added to the feature (#3895). +- [varLib] Deprecate ``varLib.mutator`` in favor of ``varLib.instancer``. The latter + provides equivalent full (static font) instancing in addition to partial VF instancing. + CLI users should replace ``fonttools varLib.mutator`` with ``fonttools varLib.instancer``. + API users should migrate to ``fontTools.varLib.instancer.instantiateVariableFont`` (#2680). + + +4.59.0 (released 2025-07-16) +---------------------------- + +- Removed hard-dependency on pyfilesystem2 (``fs`` package) from ``fonttools[ufo]`` extra. + This is replaced by the `fontTools.misc.filesystem` package, a stdlib-only, drop-in + replacement for the subset of the pyfilesystem2's API used by ``fontTools.ufoLib``. + The latter should continue to work with the upstream ``fs`` (we even test with/without). + Clients who wish to continue using ``fs`` can do so by depending on it directly instead + of via the ``fonttools[ufo]`` extra (#3885, #3620). +- [xmlWriter] Replace illegal XML characters (e.g. control or non-characters) with "?" + when dumping to ttx (#3868, #71). +- [varLib.hvar] Fixed vertical metrics fields copy/pasta error (#3884). +- Micro optimizations in ttLib and sstruct modules (#3878, #3879). +- [unicodedata] Add Garay script to RTL_SCRIPTS (#3882). +- [roundingPen] Remove unreliable kwarg usage. Argument names aren’t consistent among + point pens’ ``.addComponent()`` implementations, in particular ``baseGlyphName`` + vs ``glyphName`` (#3880). + +4.58.5 (released 2025-07-03) +---------------------------- + +- [feaLib] Don't try to combine ligature & multisub rules (#3874). +- [feaLib/ast] Use weakref proxies to avoid cycles in visitor (#3873). +- [varLib.instancer] Fixed instancing CFF2 fonts where VarData contains more than 64k items (#3858). + +4.58.4 (released 2025-06-13) +---------------------------- + +- [feaLib] Allow for empty MarkFilter & MarkAttach sets (#3856). + +4.58.3 (released 2025-06-13) +---------------------------- + +- [feaLib] Fixed iterable check for Python 3.13.4 and newer (#3854, #3855). + +4.58.2 (released 2025-06-06) +---------------------------- + +- [ttLib.reorderGlyphs] Handle CFF2 when reordering glyphs (#3852) +- [subset] Copy name IDs in use before scrapping or scrambling them for webfonts (#3853) + +4.58.1 (released 2025-05-28) +---------------------------- + +- [varLib] Make sure that fvar named instances only reuse name ID 2 or 17 if they are at the default location across all axes, to match OT spec requirement (#3831). +- [feaLib] Improve single substitution promotion to multiple/ligature substitutions, fixing a few bugs as well (#3849). +- [loggingTools] Make ``Timer._time`` a static method that doesn't take self, makes it easier to override (#3836). +- [featureVars] Use ``None`` for empty ConditionSet, which translates to a null offset in the compiled table (#3850). +- [feaLib] Raise an error on conflicting ligature substitution rules instead of silently taking the last one (#3835). +- Add typing annotations to T2CharStringPen (#3837). +- [feaLib] Add single substitutions that were promoted to multiple or ligature substitutions to ``aalt`` feature (#3847). +- [featureVars] Create a default ``LangSys`` in a ``ScriptRecord`` if missing when adding feature variations to existing GSUB later in the build (#3838). +- [symfont] Added a ``main()``. +- [cffLib.specializer] Fix rmoveto merging when blends used (#3839, #3840). +- [pyftmerge] Add support for cmap format 14 in the merge tool (#3830). +- [varLib.instancer/cff2] Fix vsindex of Private dicts when instantiating (#3828, #3232). +- Update text file read to use UTF-8 with optional BOM so it works with e.g. Windows Notepad.exe (#3824). +- [varLib] Ensure that instances only reuse name ID 2 or 17 if they are at the default location across all axes (#3831). +- [varLib] Create a dflt LangSys in a ScriptRecord when adding variations later, to fix an avoidable crash in an edge case (#3838). + +4.58.0 (released 2025-05-10) +---------------------------- + +- Drop Python 3.8, require 3.9+ (#3819) +- [HVAR, VVAR] Prune unused regions when using a direct mapping (#3797) +- [Docs] Improvements to ufoLib documentation (#3721) +- [Docs] Improvements to varLib documentation (#3727) +- [Docs] Improvements to Pens and pen-module documentation (#3724) +- [Docs] Miscellany updates to docs (misc modules and smaller modules) (#3730) +- [subset] Close codepoints over BiDi mirror variants. (#3801) +- [feaLib] Fix serializing ChainContextPosStatement and + ChainContextSubstStatement in some rare cases (#3788) +- [designspaceLib] Clarify user expectations for getStatNames (#2892) +- [GVAR] Add support for new `GVAR` table (#3728) +- [TSI0, TSI5] Derive number of entries to decompile from data length (#2477) +- [ttLib] Fix `AttributeError` when reporting table overflow (#3808) +- [ttLib] Apply rounding more often in getCoordinates (#3798) +- [ttLib] Ignore component bounds if empty (#3799) +- [ttLib] Change the separator for duplicate glyph names from "#" to "." (#3809) +- [feaLib] Support subtable breaks in CursivePos, MarkBasePos, MarkToLigPos and + MarkToMarkPos lookups (#3800, #3807) +- [feaLib] If the same lookup has single substitutions and ligature + substitutions, upgrade single substitutions to ligature substitutions with + one input glyph (#3805) +- [feaLib] Correctly handle in single pos lookups (#3803) +- [feaLib] Remove duplicates from class pair pos classes instead of raising an + error (#3804) +- [feaLib] Support creating extension lookups using useExtenion lookup flag + instead of silently ignoring it (#3811) +- [STAT] Add typing for the simpler STAT arguments (#3812) +- [otlLib.builder] Add future import for annotations (#3814) +- [cffLib] Fix reading supplement encoding (#3813) +- [voltLib] Add some missing functionality and fixes to voltLib and VoltToFea, + making the conversion to feature files more robust. Add also `fonttools + voltLib` command line tool to compile VOLT sources directly (doing an + intermediate fea conversion internally) (#3818) +- [pens] Add some PointPen annotations (#3820) + +4.57.0 (released 2025-04-03) +---------------------------- + +- [ttLib.__main__] Add `--no-recalc-timestamp` flag (#3771) +- [ttLib.__main__] Add `-b` (recalcBBoxes=False) flag (#3772) +- [cmap] Speed up glyphOrder loading from cmap (#3774) +- [ttLib.__main__] Improvements around the `-t` flag (#3776) +- [Debg] Fix parsing from XML; add roundtrip tests (#3781) +- [fealib] Support \*Base.MinMax tables (#3783, #3786) +- [config] Add OPTIMIZE_FONT_SPEED (#3784) +- [varLib.hvar] New module to add HVAR table to the font (#3780) +- [otlLib.optimize] Fix crash when the provided TTF does not contain a `GPOS` (#3794) + +4.56.0 (released 2025-02-07) +---------------------------- + +- [varStore] Sort the input todo list with the same sorting key used for the opimizer's output (#3767). +- [otData] Fix DeviceTable's ``DeltaValue`` repeat value which caused a crash after importing from XML and then compiling a GPOS containing Device tables (#3758). +- [feaLib] Make ``FeatureLibError`` pickleable, so client can e.g. use feaLib to can compile features in parallel with multiprocessing (#3762). +- [varLib/gvar] Removed workaround for old, long-fixed macOS bug about composite glyphs with all zero deltas (#1381, #1788). +- [Docs] Updated ttLib documentation, beefed up TTFont and TTGlyphSet explanations (#3720). + +4.55.8 (released 2025-01-29) +---------------------------- + +- [MetaTools] Fixed bug in buildUCD.py script whereby the first non-header line of some UCD text file was being skipped. This affected in particular the U+00B7 (MIDDLE DOT) entry of ScriptExtensions.txt (#3756). + +4.55.7 (released 2025-01-28) +---------------------------- + +- Shorten the changelog included in PyPI package description to accommodate maximum length limit imposed by Azure DevOps. No actual code changes since v4.55.6 (#3754). + +4.55.6 (released 2025-01-24) +---------------------------- + +- [glyf] Fixed regression introduced in 4.55.5 when computing bounds of nested composite glyphs with transformed components (#3752). + +4.55.5 (released 2025-01-23) +---------------------------- + +- [glyf] Fixed recalcBounds of transformed components with unrounded coordinates (#3750). +- [feaLib] Allow duplicate script/language statements (#3749). + +4.55.4 (released 2025-01-21) +---------------------------- + +- [bezierTools] Fixed ``splitCubicAtT`` sometimes not returning identical start/end points as result of numerical precision (#3742, #3743). +- [feaLib/ast] Fixed docstring of ``AlternateSubstStatement`` (#3735). +- [transform] Typing fixes (#3734). + +4.55.3 (released 2024-12-10) +---------------------------- + +- [Docs] fill out ttLib table section [#3716] +- [feaLib] More efficient inline format 4 lookups [#3726] + +4.55.2 (released 2024-12-05) +---------------------------- + +- [Docs] update Sphinx config (#3712) +- [designspaceLib] Allow axisOrdering to be set to zero (#3715) +- [feaLib] Don’t modify variable anchors in place (#3717) + +4.55.1 (released 2024-12-02) +---------------------------- + +- [ttGlyphSet] Support VARC CFF2 fonts (#3683) +- [DecomposedTransform] Document and implement always skewY == 0 (#3697) +- [varLib] "Fix" cython iup issue? (#3704) +- Cython minor refactor (#3705) + + +4.55.0 (released 2024-11-14) +---------------------------- + +- [cffLib.specializer] Adjust stack use calculation (#3689) +- [varLib] Lets not add mac names if the rest of name doesn't have them (#3688) +- [ttLib.reorderGlyphs] Update CFF table charstrings and charset (#3682) +- [cffLib.specializer] Add cmdline to specialize a CFF2 font (#3675, #3679) +- [CFF2] Lift uint16 VariationStore.length limitation (#3674) +- [subset] consider variation selectors subsetting cmap14 (#3672) +- [varLib.interpolatable] Support CFF2 fonts (#3670) +- Set isfinal to true in XML parser for proper resource cleanup (#3669) +- [removeOverlaps] Fix CFF CharString width (#3659) +- [glyf] Add optimizeSize option (#3657) +- Python 3.13 support (#3656) +- [TupleVariation] Optimize for loading speed, not size (#3650, #3653) + + +4.54.1 (released 2024-09-24) +---------------------------- + +- [unicodedata] Update to Unicode 16 +- [subset] Escape ``\\`` in doc string + +4.54.0 (released 2024-09-23) +---------------------------- + +- [Docs] Small docs cleanups by @n8willis (#3611) +- [Docs] cleanup code blocks by @n8willis (#3627) +- [Docs] fix Sphinx builds by @n8willis (#3625) +- [merge] Minor fixes to documentation for merge by @drj11 (#3588) +- [subset] Small tweaks to pyftsubset documentation by @RoelN (#3633) +- [Tests] Do not require fonttools command to be available by @behdad (#3612) +- [Tests] subset_test: add failing test to reproduce issue #3616 by @anthrotype (#3622) +- [ttLib] NameRecordVisitor: include whole sequence of character variants' UI labels, not just the first by @anthrotype (#3617) +- [varLib.avar] Reconstruct mappings from binary by @behdad (#3598) +- [varLib.instancer] Fix visual artefacts with partial L2 instancing by @Hoolean (#3635) +- [varLib.interpolatable] Support discrete axes in .designspace by @behdad (#3599) +- [varLib.models] By default, assume OpenType-like normalized space by @behdad (#3601) + +4.53.1 (released 2024-07-05) +---------------------------- + +- [feaLib] Improve the sharing of inline chained lookups (#3559) +- [otlLib] Correct the calculation of OS/2.usMaxContext with reversed chaining contextual single substitutions (#3569) +- [misc.visitor] Visitors search the inheritance chain of objects they are visiting (#3581) + +4.53.0 (released 2024-05-31) +---------------------------- + +- [ttLib.removeOverlaps] Support CFF table to aid in downconverting CFF2 fonts (#3528) +- [avar] Fix crash when accessing not-yet-existing attribute (#3550) +- [docs] Add buildMathTable to otlLib.builder documentation (#3540) +- [feaLib] Allow UTF-8 with BOM when reading features (#3495) +- [SVGPathPen] Revert rounding coordinates to two decimal places by default (#3543) +- [varLib.instancer] Refix output filename decision-making (#3545, #3544, #3548) + +4.52.4 (released 2024-05-27) +---------------------------- + +- [varLib.cff] Restore and deprecate convertCFFtoCFF2 that was removed in 4.52.0 + release as it is used by downstream projects (#3535). + +4.52.3 (released 2024-05-27) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.2. No other code changes. + +4.52.2 (released 2024-05-27) +---------------------------- + +- [varLib.interpolatable] Ensure that scipy/numpy output is JSON-serializable + (#3522, #3526). +- [housekeeping] Regenerate table lists, to fix pyinstaller packaging of the new + ``VARC`` table (#3531, #3529). +- [cffLib] Make CFFToCFF2 and CFF2ToCFF more robust (#3521, #3525). + +4.52.1 (released 2024-05-24) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.0. No other code changes. + +4.52.0 (released 2024-05-24) +---------------------------- + +- Added support for the new ``VARC`` (Variable Composite) table that is being + proposed to OpenType spec (#3395). For more info: + https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md +- [ttLib.__main__] Fixed decompiling all tables (90fed08). +- [feaLib] Don't reference the same lookup index multiple times within the same + feature record, it is only applied once anyway (#3520). +- [cffLib] Moved methods to desubroutinize, remove hints and unused subroutines + from subset module to cffLib (#3517). +- [varLib.instancer] Added support for partial-instancing CFF2 tables! Also, added + method to down-convert from CFF2 to CFF 1.0, and CLI entry points to convert + CFF<->CFF2 (#3506). +- [subset] Prune unused user name IDs even with --name-IDs='*' (#3410). +- [ttx] use GNU-style getopt to intermix options and positional arguments (#3509). +- [feaLib.variableScalar] Fixed ``value_at_location()`` method (#3491) +- [psCharStrings] Shorten output of ``encodeFloat`` (#3492). +- [bezierTools] Fix infinite-recursion in ``calcCubicArcLength`` (#3502). +- [avar2] Implement ``avar2`` support in ``TTFont.getGlyphSet()`` (#3473). + +4.51.0 (released 2024-04-05) +---------------------------- + +- [ttLib] Optimization on loading aux fields (#3464). +- [ttFont] Add reorderGlyphs (#3468). + +4.50.0 (released 2024-03-15) +---------------------------- + +- [pens] Added decomposing filter pens that draw components as regular contours (#3460). +- [instancer] Drop explicit no-op axes from TupleVariations (#3457). +- [cu2qu/ufo] Return set of modified glyph names from fonts_to_quadratic (#3456). + +4.49.0 (released 2024-02-15) +---------------------------- + +- [otlLib] Add API for building ``MATH`` table (#3446) + +4.48.1 (released 2024-02-06) +---------------------------- + +- Fixed uploading wheels to PyPI, no code changes since v4.48.0. + +4.48.0 (released 2024-02-06) +---------------------------- + +- [varLib] Do not log when there are no OTL tables to be merged. +- [setup.py] Do not restrict lxml<5 any more, tests pass just fine with lxml>=5. +- [feaLib] Remove glyph and class names length restrictions in FEA (#3424). +- [roundingPens] Added ``transformRoundFunc`` parameter to the rounding pens to allow + for custom rounding of the components' transforms (#3426). +- [feaLib] Keep declaration order of ligature components within a ligature set, instead + of sorting by glyph name (#3429). +- [feaLib] Fixed ordering of alternates in ``aalt`` lookups, following the declaration + order of feature references within the ``aalt`` feature block (#3430). +- [varLib.instancer] Fixed a bug in the instancer's IUP optimization (#3432). +- [sbix] Support sbix glyphs with new graphicType "flip" (#3433). +- [svgPathPen] Added ``--glyphs`` option to dump the SVG paths for the named glyphs + in the font (0572f78). +- [designspaceLib] Added "description" attribute to ```` and ```` + elements, and allow multiple ```` elements to group ```` elements + that are logically related (#3435, #3437). +- [otlLib] Correctly choose the most compact GSUB contextual lookup format (#3439). + +4.47.2 (released 2024-01-11) +---------------------------- + +Minor release to fix uploading wheels to PyPI. + +4.47.1 (released 2024-01-11) +---------------------------- + +- [merge] Improve help message and add standard command line options (#3408) +- [otlLib] Pass ``ttFont`` to ``name.addName`` in ``buildStatTable`` (#3406) +- [featureVars] Re-use ``FeatureVariationRecord``'s when possible (#3413) + +4.47.0 (released 2023-12-18) +---------------------------- + +- [varLib.models] New API for VariationModel: ``getMasterScalars`` and + ``interpolateFromValuesAndScalars``. +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + add a Summary page in the front, and an Index and Table-of-Contents in the back. + Change the page size to Letter. +- [Docs/designspaceLib] Defined a new ``public.fontInfo`` lib key, not used anywhere yet (#3358). + +4.46.0 (released 2023-12-02) +---------------------------- + +- [featureVars] Allow to register the same set of substitution rules to multiple features. + The ``addFeatureVariations`` function can now take a list of featureTags; similarly, the + lib key 'com.github.fonttools.varLib.featureVarsFeatureTag' can now take a + comma-separateed string of feature tags (e.g. "salt,ss01") instead of a single tag (#3360). +- [featureVars] Don't overwrite GSUB FeatureVariations, but append new records to it + for features which are not already there. But raise ``VarLibError`` if the feature tag + already has feature variations associated with it (#3363). +- [varLib] Added ``addGSUBFeatureVariations`` function to add GSUB Feature Variations + to an existing variable font from rules defined in a DesignSpace document (#3362). +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + a new test for "underweight" glyphs. The new test reports quite a few false-positives + though. Please send feedback. + +4.45.1 (released 2023-11-23) +---------------------------- + +- [varLib.interpolatable] Various bugfixes and improvements, better reporting, reduced + false positives. +- [ttGlyphSet] Added option to not recalculate glyf bounds (#3348). + +4.45.0 (released 2023-11-20) +---------------------------- + +- [varLib.interpolatable] Vastly improved algorithms. Also available now is ``--pdf`` + and ``--html`` options to generate a PDF or HTML report of the interpolation issues. + The PDF/HTML report showcases the problematic masters, the interpolated broken + glyph, as well as the proposed fixed version. + +4.44.3 (released 2023-11-15) +---------------------------- + +- [subset] Only prune codepage ranges for OS/2.version >= 1, ignore otherwise (#3334). +- [instancer] Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing + MVAR table containing 'hasc', 'hdsc' or 'hlgp' tags (#3297). + +4.44.2 (released 2023-11-14) +---------------------------- + +- [glyf] Have ``Glyph.recalcBounds`` skip empty components (base glyph with no contours) + when computing the bounding box of composite glyphs. This simply restores the existing + behavior before some changes were introduced in fonttools 4.44.0 (#3333). + +4.44.1 (released 2023-11-14) +---------------------------- + +- [feaLib] Ensure variable mark anchors are deep-copied while building since they + get modified in-place and later reused (#3330). +- [OS/2|subset] Added method to ``recalcCodePageRanges`` to OS/2 table class; added + ``--prune-codepage-ranges`` to `fonttools subset` command (#3328, #2607). + +4.44.0 (released 2023-11-03) +---------------------------- + +- [instancer] Recalc OS/2 AvgCharWidth after instancing if default changes (#3317). +- [otlLib] Make ClassDefBuilder class order match varLib.merger's, i.e. large + classes first, then glyph lexicographic order (#3321, #3324). +- [instancer] Allow not specifying any of min:default:max values and let be filled + up with fvar's values (#3322, #3323). +- [instancer] When running --update-name-table ignore axes that have no STAT axis + values (#3318, #3319). +- [Debg] When dumping to ttx, write the embedded JSON as multi-line string with + indentation (92cbfee0d). +- [varStore] Handle > 65535 items per encoding by splitting VarData subtable (#3310). +- [subset] Handle null-offsets in MarkLigPos subtables. +- [subset] Keep East Asian spacing fatures vhal, halt, chws, vchw by default (#3305). +- [instancer.solver] Fixed case where axisDef < lower and upper < axisMax (#3304). +- [glyf] Speed up compilation, mostly around ``recalcBounds`` (#3301). +- [varLib.interpolatable] Speed it up when working on variable fonts, plus various + micro-optimizations (#3300). +- Require unicodedata2 >= 15.1.0 when installed with 'unicode' extra, contains UCD 15.1. + +4.43.1 (released 2023-10-06) +---------------------------- + +- [EBDT] Fixed TypeError exception in `_reverseBytes` method triggered when dumping + some bitmap fonts with `ttx -z bitwise` option (#3162). +- [v/hhea] Fixed UnboundLocalError exception in ``recalc`` method when no vmtx or hmtx + tables are present (#3290). +- [bezierTools] Fixed incorrectly typed cython local variable leading to TypeError when + calling ``calcQuadraticArcLength`` (#3288). +- [feaLib/otlLib] Better error message when building Coverage table with missing glyph (#3286). + +4.43.0 (released 2023-09-29) +---------------------------- + +- [subset] Set up lxml ``XMLParser(resolve_entities=False)`` when parsing OT-SVG documents + to prevent XML External Entity (XXE) attacks (9f61271dc): + https://codeql.github.com/codeql-query-help/python/py-xxe/ +- [varLib.iup] Added workaround for a Cython bug in ``iup_delta_optimize`` that was + leading to IUP tolerance being incorrectly initialised, resulting in sub-optimal deltas + (60126435d, cython/cython#5732). +- [varLib] Added new command-line entry point ``fonttools varLib.avar`` to add an + ``avar`` table to an existing VF from axes mappings in a .designspace file (0a3360e52). +- [instancer] Fixed bug whereby no longer used variation regions were not correctly pruned + after VarData optimization (#3268). +- Added support for Python 3.12 (#3283). + +4.42.1 (released 2023-08-20) +---------------------------- + +- [t1Lib] Fixed several Type 1 issues (#3238, #3240). +- [otBase/packer] Allow sharing tables reached by different offset sizes (#3241, #3236). +- [varLib/merger] Fix Cursive attachment merging error when all anchors are NULL (#3248, #3247). +- [ttLib] Fixed warning when calling ``addMultilingualName`` and ``ttFont`` parameter was not + passed on to ``findMultilingualName`` (#3253). + +4.42.0 (released 2023-08-02) +---------------------------- + +- [varLib] Use sentinel value 0xFFFF to mark a glyph advance in hmtx/vmtx as non + participating, allowing sparse masters to contain glyphs for variation purposes other + than {H,V}VAR (#3235). +- [varLib/cff] Treat empty glyphs in non-default masters as missing, thus not participating + in CFF2 delta computation, similarly to how varLib already treats them for gvar (#3234). +- Added varLib.avarPlanner script to deduce 'correct' avar v1 axis mappings based on + glyph average weights (#3223). + +4.41.1 (released 2023-07-21) +---------------------------- + +- [subset] Fixed perf regression in v4.41.0 by making ``NameRecordVisitor`` only visit + tables that do contain nameID references (#3213, #3214). +- [varLib.instancer] Support instancing fonts containing null ConditionSet offsets in + FeatureVariationRecords (#3211, #3212). +- [statisticsPen] Report font glyph-average weight/width and font-wide slant. +- [fontBuilder] Fixed head.created date incorrectly set to 0 instead of the current + timestamp, regression introduced in v4.40.0 (#3210). +- [varLib.merger] Support sparse ``CursivePos`` masters (#3209). + +4.41.0 (released 2023-07-12) +---------------------------- + +- [fontBuilder] Fixed bug in setupOS2 with default panose attribute incorrectly being + set to a dict instead of a Panose object (#3201). +- [name] Added method to ``removeUnusedNameRecords`` in the user range (#3185). +- [varLib.instancer] Fixed issue with L4 instancing (moving default) (#3179). +- [cffLib] Use latin1 so we can roundtrip non-ASCII in {Full,Font,Family}Name (#3202). +- [designspaceLib] Mark as optional in docs (as it is in the code). +- [glyf-1] Fixed drawPoints() bug whereby last cubic segment becomes quadratic (#3189, #3190). +- [fontBuilder] Propagate the 'hidden' flag to the fvar Axis instance (#3184). +- [fontBuilder] Update setupAvar() to also support avar 2, fixing ``_add_avar()`` call + site (#3183). +- Added new ``voltLib.voltToFea`` submodule (originally Tiro Typeworks' "Volto") for + converting VOLT OpenType Layout sources to FEA format (#3164). + +4.40.0 (released 2023-06-12) +---------------------------- + +- Published native binary wheels to PyPI for all the python minor versions and platform + and architectures currently supported that would benefit from this. They will include + precompiled Cython-accelerated modules (e.g. cu2qu) without requiring to compile them + from source. The pure-python wheel and source distribution will continue to be + published as always (pip will automatically chose them when no binary wheel is + available for the given platform, e.g. pypy). Use ``pip install --no-binary=fonttools fonttools`` + to expliclity request pip to install from the pure-python source. +- [designspaceLib|varLib] Add initial support for specifying axis mappings and build + ``avar2`` table from those (#3123). +- [feaLib] Support variable ligature caret position (#3130). +- [varLib|glyf] Added option to --drop-implied-oncurves; test for impliable oncurve + points either before or after rounding (#3146, #3147, #3155, #3156). +- [TTGlyphPointPen] Don't error with empty contours, simply ignore them (#3145). +- [sfnt] Fixed str vs bytes remnant of py3 transition in code dealing with de/compiling + WOFF metadata (#3129). +- [instancer-solver] Fixed bug when moving default instance with sparse masters (#3139, #3140). +- [feaLib] Simplify variable scalars that don’t vary (#3132). +- [pens] Added filter pen that explicitly emits closing line when lastPt != movePt (#3100). +- [varStore] Improve optimize algorithm and better document the algorithm (#3124, #3127). + Added ``quantization`` option (#3126). +- Added CI workflow config file for building native binary wheels (#3121). +- [fontBuilder] Added glyphDataFormat=0 option; raise error when glyphs contain cubic + outlines but glyphDataFormat was not explicitly set to 1 (#3113, #3119). +- [subset] Prune emptied GDEF.MarkGlyphSetsDef and remap indices; ensure GDEF is + subsetted before GSUB and GPOS (#3114, #3118). +- [xmlReader] Fixed issue whereby DSIG table data was incorrectly parsed (#3115, #2614). +- [varLib/merger] Fixed merging of SinglePos with pos=0 (#3111, #3112). +- [feaLib] Demote "Feature has not been defined" error to a warning when building aalt + and referenced feature is empty (#3110). +- [feaLib] Dedupe multiple substitutions with classes (#3105). + +4.39.4 (released 2023-05-10) +---------------------------- + +- [varLib.interpolatable] Allow for sparse masters (#3075) +- [merge] Handle differing default/nominalWidthX in CFF (#3070) +- [ttLib] Add missing main.py file to ttLib package (#3088) +- [ttx] Fix missing composite instructions in XML (#3092) +- [ttx] Fix split tables option to work on filenames containing '%' (#3096) +- [featureVars] Process lookups for features other than rvrn last (#3099) +- [feaLib] support multiple substitution with classes (#3103) + +4.39.3 (released 2023-03-28) +---------------------------- + +- [sbix] Fixed TypeError when compiling empty glyphs whose imageData is None, regression + was introduced in v4.39 (#3059). +- [ttFont] Fixed AttributeError on python <= 3.10 when opening a TTFont from a tempfile + SpooledTemporaryFile, seekable method only added on python 3.11 (#3052). + +4.39.2 (released 2023-03-16) +---------------------------- + +- [varLib] Fixed regression introduced in 4.39.1 whereby an incomplete 'STAT' table + would be built even though a DesignSpace v5 did contain 'STAT' definitions (#3045, #3046). + +4.39.1 (released 2023-03-16) +---------------------------- + +- [avar2] Added experimental support for reading/writing avar version 2 as specified in + this draft proposal: https://github.com/harfbuzz/boring-expansion-spec/blob/main/avar2.md +- [glifLib] Wrap underlying XML library exceptions with GlifLibError when parsing GLIFs, + and also print the name and path of the glyph that fails to be parsed (#3042). +- [feaLib] Consult avar for normalizing user-space values in ConditionSets and in + VariableScalars (#3042, #3043). +- [ttProgram] Handle string input to Program.fromAssembly() (#3038). +- [otlLib] Added a config option to emit GPOS 7 lookups, currently disabled by default + because of a macOS bug (#3034). +- [COLRv1] Added method to automatically compute ClipBoxes (#3027). +- [ttFont] Fixed getGlyphID to raise KeyError on missing glyphs instead of returning + None. The regression was introduced in v4.27.0 (#3032). +- [sbix] Fixed UnboundLocalError: cannot access local variable 'rawdata' (#3031). +- [varLib] When building VF, do not overwrite a pre-existing ``STAT`` table that was built + with feaLib from FEA feature file. Also, added support for building multiple VFs + defined in Designspace v5 from ``fonttools varLib`` script (#3024). +- [mtiLib] Only add ``Debg`` table with lookup names when ``FONTTOOLS_LOOKUP_DEBUGGING`` + env variable is set (#3023). + +4.39.0 (released 2023-03-06) +---------------------------- + +- [mtiLib] Optionally add `Debg` debug info for MTI feature builds (#3018). +- [ttx] Support reading input file from standard input using special `-` character, + similar to existing `-o -` option to write output to standard output (#3020). +- [cython] Prevent ``cython.compiled`` raise AttributeError if cython not installed + properly (#3017). +- [OS/2] Guard against ZeroDivisionError when calculating xAvgCharWidth in the unlikely + scenario no glyph has non-zero advance (#3015). +- [subset] Recompute xAvgCharWidth independently of --no-prune-unicode-ranges, + previously the two options were involuntarily bundled together (#3012). +- [fontBuilder] Add ``debug`` parameter to addOpenTypeFeatures method to add source + debugging information to the font in the ``Debg`` private table (#3008). +- [name] Make NameRecord `__lt__` comparison not fail on Unicode encoding errors (#3006). +- [featureVars] Fixed bug in ``overlayBox`` (#3003, #3005). +- [glyf] Added experimental support for cubic bezier curves in TrueType glyf table, as + outlined in glyf v1 proposal (#2988): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-cubicOutlines.md +- Added new qu2cu module and related qu2cuPen, the reverse of cu2qu for converting + TrueType quadratic splines to cubic bezier curves (#2993). +- [glyf] Added experimental support for reading and writing Variable Composites/Components + as defined in glyf v1 spec proposal (#2958): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-varComposites.md. +- [pens]: Added `addVarComponent` method to pen protocols' base classes, which pens can implement + to handle varcomponents (by default they get decomposed) (#2958). +- [misc.transform] Added DecomposedTransform class which implements an affine transformation + with separate translate, rotation, scale, skew, and transformation-center components (#2598) +- [sbix] Ensure Glyph.referenceGlyphName is set; fixes error after dumping and + re-compiling sbix table with 'dupe' glyphs (#2984). +- [feaLib] Be cleverer when merging chained single substitutions into same lookup + when they are specified using the inline notation (#2150, #2974). +- [instancer] Clamp user-inputted axis ranges to those of fvar (#2959). +- [otBase/subset] Define ``__getstate__`` for BaseTable so that a copied/pickled 'lazy' + object gets its own OTTableReader to read from; incidentally fixes a bug while + subsetting COLRv1 table containing ClipBoxes on python 3.11 (#2965, #2968). +- [sbix] Handle glyphs with "dupe" graphic type on compile correctly (#2963). +- [glyf] ``endPointsOfContours`` field should be unsigned! Kudos to behdad for + spotting one of the oldest bugs in FT. Probably nobody has ever dared to make + glyphs with more than 32767 points... (#2957). +- [feaLib] Fixed handling of ``ignore`` statements with unmarked glyphs to match + makeotf behavior, which assumes the first glyph is marked (#2950). +- Reformatted code with ``black`` and enforce new code style via CI check (#2925). +- [feaLib] Sort name table entries following OT spec prescribed order in the builder (#2927). +- [cu2quPen] Add Cu2QuMultiPen that converts multiple outlines at a time in + interpolation compatible way; its methods take a list of tuples arguments + that would normally be passed to individual segment pens, and at the end it + dispatches the converted outlines to each pen (#2912). +- [reverseContourPen/ttGlyphPen] Add outputImpliedClosingLine option (#2913, #2914, + #2921, #2922, #2995). +- [gvar] Avoid expanding all glyphs unnecessarily upon compile (#2918). +- [scaleUpem] Fixed bug whereby CFF2 vsindex was scaled; it should not (#2893, #2894). +- [designspaceLib] Add DS.getAxisByTag and refactor getAxis (#2891). +- [unicodedata] map Zmth<->math in ot_tag_{to,from}_script (#1737, #2889). +- [woff2] Support encoding/decoding OVERLAP_SIMPLE glyf flags (#2576, #2884). +- [instancer] Update OS/2 class and post.italicAngle when default moved (L4) +- Dropped support for Python 3.7 which reached EOL, fontTools requires 3.8+. +- [instancer] Fixed instantiateFeatureVariations logic when a rule range becomes + default-applicable (#2737, #2880). +- [ttLib] Add main to ttFont and ttCollection that just decompile and re-compile the + input font (#2869). +- [featureVars] Insert 'rvrn' lookup at the beginning of LookupList, to work around bug + in Apple implementation of 'rvrn' feature which the spec says it should be processed + early whereas on macOS 10.15 it follows lookup order (#2140, #2867). +- [instancer/mutator] Remove 'DSIG' table if present. +- [svgPathPen] Don't close path in endPath(), assume open unless closePath() (#2089, #2865). + +4.38.0 (released 2022-10-21) +---------------------------- + +- [varLib.instancer] Added support for L4 instancing, i.e. moving the default value of + an axis while keeping it variable. Thanks Behdad! (#2728, #2861). + It's now also possible to restrict an axis min/max values beyond the current default + value, e.g. a font wght has min=100, def=400, max=900 and you want a partial VF that + only varies between 500 and 700, you can now do that. + You can either specify two min/max values (wght=500:700), and the new default will be + set to either the minimum or maximum, depending on which one is closer to the current + default (e.g. 500 in this case). Or you can specify three values (e.g. wght=500:600:700) + to specify the new default value explicitly. +- [otlLib/featureVars] Set a few Count values so one doesn't need to compile the font + to update them (#2860). +- [varLib.models] Make extrapolation work for 2-master models as well where one master + is at the default location (#2843, #2846). + Add optional extrapolate=False to normalizeLocation() (#2847, #2849). +- [varLib.cff] Fixed sub-optimal packing of CFF2 deltas by no longer rounding them to + integer (#2838). +- [scaleUpem] Calculate numShorts in VarData after scale; handle CFF hintmasks (#2840). + +4.37.4 (released 2022-09-30) +---------------------------- + +- [subset] Keep nameIDs used by CPAL palette entry labels (#2837). +- [varLib] Avoid negative hmtx values when creating font from variable CFF2 font (#2827). +- [instancer] Don't prune stat.ElidedFallbackNameID (#2828). +- [unicodedata] Update Scripts/Blocks to Unicode 15.0 (#2833). + +4.37.3 (released 2022-09-20) +---------------------------- + +- Fix arguments in calls to (glyf) glyph.draw() and drawPoints(), whereby offset wasn't + correctly passed down; this fix also exposed a second bug, where lsb and tsb were not + set (#2824, #2825, adobe-type-tools/afdko#1560). + +4.37.2 (released 2022-09-15) +---------------------------- + +- [subset] Keep CPAL table and don't attempt to prune unused color indices if OT-SVG + table is present even if COLR table was subsetted away; OT-SVG may be referencing the + CPAL table; for now we assume that's the case (#2814, #2815). +- [varLib.instancer] Downgrade GPOS/GSUB version if there are no more FeatureVariations + after instancing (#2812). +- [subset] Added ``--no-lazy`` to optionally load fonts eagerly (mostly to ease + debugging of table lazy loading, no practical effects) (#2807). +- [varLib] Avoid building empty COLR.DeltaSetIndexMap with only identity mappings (#2803). +- [feaLib] Allow multiple value record types (by promoting to the most general format) + within the same PairPos subtable; e.g. this allows variable and non variable kerning + rules to share the same subtable. This also fixes a bug whereby some kerning pairs + would become unreachable while shapiong because of premature subtable splitting (#2772, #2776). +- [feaLib] Speed up ``VarScalar`` by caching models for recurring master locations (#2798). +- [feaLib] Optionally cythonize ``feaLib.lexer``, speeds up parsing FEA a bit (#2799). +- [designspaceLib] Avoid crash when handling unbounded rule conditions (#2797). +- [post] Don't crash if ``post`` legacy format 1 is malformed/improperly used (#2786) +- [gvar] Don't be "lazy" (load all glyph variations up front) when TTFont.lazy=False (#2771). +- [TTFont] Added ``normalizeLocation`` method to normalize a location dict from the + font's defined axes space (also known as "user space") into the normalized (-1..+1) + space. It applies ``avar`` mapping if the font contains an ``avar`` table (#2789). +- [TTVarGlyphSet] Support drawing glyph instances from CFF2 variable glyph set (#2784). +- [fontBuilder] Do not error when building cmap if there are zero code points (#2785). +- [varLib.plot] Added ability to plot a variation model and set of accompaning master + values corresponding to the model's master locations into a pyplot figure (#2767). +- [Snippets] Added ``statShape.py`` script to draw statistical shape of a glyph as an + ellips (requires pycairo) (baecd88). +- [TTVarGlyphSet] implement drawPoints natively, avoiding going through + SegmentToPointPen (#2778). +- [TTVarGlyphSet] Fixed bug whereby drawing a composite glyph multiple times, its + components would shif; needed an extra copy (#2774). + +4.37.1 (released 2022-08-24) +---------------------------- + +- [subset] Fixed regression introduced with v4.37.0 while subsetting the VarStore of + ``HVAR`` and ``VVAR`` tables, whereby an ``AttributeError: subset_varidxes`` was + thrown because an apparently unused import statement (with the side-effect of + dynamically binding that ``subset_varidxes`` method to the VarStore class) had been + accidentally deleted in an unrelated PR (#2679, #2773). +- [pens] Added ``cairoPen`` (#2678). +- [gvar] Read ``gvar`` more lazily by not parsing all of the ``glyf`` table (#2771). +- [ttGlyphSet] Make ``drawPoints(pointPen)`` method work for CFF fonts as well via + adapter pen (#2770). + +4.37.0 (released 2022-08-23) +---------------------------- + +- [varLib.models] Reverted PR #2717 which added support for "narrow tents" in v4.36.0, + as it introduced a regression (#2764, #2765). It will be restored in upcoming release + once we found a solution to the bug. +- [cff.specializer] Fixed issue in charstring generalizer with the ``blend`` operator + (#2750, #1975). +- [varLib.models] Added support for extrapolation (#2757). +- [ttGlyphSet] Ensure the newly added ``_TTVarGlyphSet`` inherits from ``_TTGlyphSet`` + to keep backward compatibility with existing API (#2762). +- [kern] Allow compiling legacy kern tables with more than 64k entries (d21cfdede). +- [visitor] Added new visitor API to traverse tree of objects and dispatch based + on the attribute type: cf. ``fontTools.misc.visitor`` and ``fontTools.ttLib.ttVisitor``. Added ``fontTools.ttLib.scaleUpem`` module that uses the latter to + change a font's units-per-em and scale all the related fields accordingly (#2718, + #2755). + +4.36.0 (released 2022-08-17) +---------------------------- + +- [varLib.models] Use a simpler model that generates narrower "tents" (regions, master + supports) whenever possible: specifically when any two axes that actively "cooperate" + (have masters at non-zero positions for both axes) have a complete set of intermediates. + The simpler algorithm produces fewer overlapping regions and behaves better with + respect to rounding at the peak positions than the generic solver, always matching + intermediate masters exactly, instead of maximally 0.5 units off. This may be useful + when 100% metrics compatibility is desired (#2218, #2717). +- [feaLib] Remove warning when about ``GDEF`` not being built when explicitly not + requested; don't build one unconditonally even when not requested (#2744, also works + around #2747). +- [ttFont] ``TTFont.getGlyphSet`` method now supports selecting a location that + represents an instance of a variable font (supports both user-scale and normalized + axes coordinates via the ``normalized=False`` parameter). Currently this only works + for TrueType-flavored variable fonts (#2738). + +4.35.0 (released 2022-08-15) +---------------------------- + +- [otData/otConverters] Added support for 'biased' PaintSweepGradient start/end angles + to match latest COLRv1 spec (#2743). +- [varLib.instancer] Fixed bug in ``_instantiateFeatureVariations`` when at the same + time pinning one axis and restricting the range of a subsequent axis; the wrong axis + tag was being used in the latter step (as the records' axisIdx was updated in the + preceding step but looked up using the old axes order in the following step) (#2733, + #2734). +- [mtiLib] Pad script tags with space when less than 4 char long (#1727). +- [merge] Use ``'.'`` instead of ``'#'`` in duplicate glyph names (#2742). +- [gvar] Added support for lazily loading glyph variations (#2741). +- [varLib] In ``build_many``, we forgot to pass on ``colr_layer_reuse`` parameter to + the ``build`` method (#2730). +- [svgPathPen] Add a main that prints SVG for input text (6df779fd). +- [cffLib.width] Fixed off-by-one in optimized values; previous code didn't match the + code block above it (2963fa50). +- [varLib.interpolatable] Support reading .designspace and .glyphs files (via optional + ``glyphsLib``). +- Compile some modules with Cython when available and building/installing fonttools + from source: ``varLib.iup`` (35% faster), ``pens.momentsPen`` (makes + ``varLib.interpolatable`` 3x faster). +- [feaLib] Allow features to be built for VF without also building a GDEF table (e.g. + only build GSUB); warn when GDEF would be needed but isn't requested (#2705, 2694). +- [otBase] Fixed ``AttributeError`` when uharfbuzz < 0.23.0 and 'repack' method is + missing (32aa8eaf). Use new ``uharfbuzz.repack_with_tag`` when available (since + uharfbuzz>=0.30.0), enables table-specific optimizations to be performed during + repacking (#2724). +- [statisticsPen] By default report all glyphs (4139d891). Avoid division-by-zero + (52b28f90). +- [feaLib] Added missing required argument to FeatureLibError exception (#2693) +- [varLib.merge] Fixed error during error reporting (#2689). Fixed undefined + ``NotANone`` variable (#2714). + +4.34.4 (released 2022-07-07) +---------------------------- + +- Fixed typo in varLib/merger.py that causes NameError merging COLR glyphs + containing more than 255 layers (#2685). + +4.34.3 (released 2022-07-07) +---------------------------- + +- [designspaceLib] Don't make up bad PS names when no STAT data (#2684) + +4.34.2 (released 2022-07-06) +---------------------------- + +- [varStore/subset] fixed KeyError exception to do with NO_VARIATION_INDEX while + subsetting varidxes in GPOS/GDEF (a08140d). + +4.34.1 (released 2022-07-06) +---------------------------- + +- [instancer] When optimizing HVAR/VVAR VarStore, use_NO_VARIATION_INDEX=False to avoid + including NO_VARIATION_INDEX in AdvWidthMap, RsbMap, LsbMap mappings, which would + push the VarIdx width to maximum (4bytes), which is not desirable. This also fixes + a hard crash when attempting to subset a varfont after it had been partially instanced + with use_NO_VARIATION_INDEX=True. + +4.34.0 (released 2022-07-06) +---------------------------- + +- [instancer] Set RIBBI bits in head and OS/2 table when cutting instances and the + subfamily nameID=2 contains strings like 'Italic' or 'Bold' (#2673). +- [otTraverse] Addded module containing methods for traversing trees of otData tables + (#2660). +- [otTables] Made DeltaSetIndexMap TTX dump less verbose by omitting no-op entries + (#2660). +- [colorLib.builder] Added option to disable PaintColrLayers's reuse of layers from + LayerList (#2660). +- [varLib] Added support for merging multiple master COLRv1 tables into a variable + COLR table (#2660, #2328). Base color glyphs of same name in different masters must have + identical paint graph structure (incl. number of layers, palette indices, number + of color line stops, corresponding paint formats at each level of the graph), + but can differ in the variable fields (e.g. PaintSolid.Alpha). PaintVar* tables + are produced when this happens and a VarStore/DeltaSetIndexMap is added to the + variable COLR table. It is possible for non-default masters to be 'sparse', i.e. + omit some of the color glyphs present in the default master. +- [feaLib] Let the Parser set nameIDs 1 through 6 that were previously reserved (#2675). +- [varLib.varStore] Support NO_VARIATION_INDEX in optimizer and instancer. +- [feaLib] Show all missing glyphs at once at end of parsing (#2665). +- [varLib.iup] Rewrite force-set conditions and limit DP loopback length (#2651). + For Noto Sans, IUP time drops from 23s down to 9s, with only a slight size increase + in the final font. This basically turns the algorithm from O(n^3) into O(n). +- [featureVars] Report about missing glyphs in substitution rules (#2654). +- [mutator/instancer] Added CLI flag to --no-recalc-timestamp (#2649). +- [SVG] Allow individual SVG documents in SVG OT table to be compressed on uncompressed, + and remember that when roundtripping to/from ttx. The SVG.docList is now a list + of SVGDocument namedtuple-like dataclass containing an extra ``compressed`` field, + and no longer a bare 3-tuple (#2645). +- [designspaceLib] Check for descriptor types with hasattr() to allow custom classes + that don't inherit the default descriptors (#2634). +- [subset] Enable sharing across subtables of extension lookups for harfbuzz packing + (#2626). Updated how table packing falls back to fontTools from harfbuzz (#2668). +- [subset] Updated default feature tags following current Harfbuzz (#2637). +- [svgLib] Fixed regex for real number to support e.g. 1e-4 in addition to 1.0e-4. + Support parsing negative rx, ry on arc commands (#2596, #2611). +- [subset] Fixed subsetting SinglePosFormat2 when ValueFormat=0 (#2603). + +4.33.3 (released 2022-04-26) +---------------------------- + +- [designspaceLib] Fixed typo in ``deepcopyExceptFonts`` method, preventing font + references to be transferred (#2600). Fixed another typo in the name of ``Range`` + dataclass's ``__post_init__`` magic method (#2597). + +4.33.2 (released 2022-04-22) +---------------------------- + +- [otBase] Make logging less verbose when harfbuzz fails to serialize. Do not exit + at the first failure but continue attempting to fix offset overflow error using + the pure-python serializer even when the ``USE_HARFBUZZ_REPACKER`` option was + explicitly set to ``True``. This is normal with fonts with relatively large + tables, at least until hb.repack implements proper table splitting. + +4.33.1 (released 2022-04-22) +---------------------------- + +- [otlLib] Put back the ``FONTTOOLS_GPOS_COMPACT_MODE`` environment variable to fix + regression in ufo2ft (and thus fontmake) introduced with v4.33.0 (#2592, #2593). + This is deprecated and will be removed one ufo2ft gets updated to use the new + config setup. + +4.33.0 (released 2022-04-21) +---------------------------- + +- [OS/2 / merge] Automatically recalculate ``OS/2.xAvgCharWidth`` after merging + fonts with ``fontTools.merge`` (#2591, #2538). +- [misc/config] Added ``fontTools.misc.configTools`` module, a generic configuration + system (#2416, #2439). + Added ``fontTools.config`` module, a fontTools-specific configuration + system using ``configTools`` above. + Attached a ``Config`` object to ``TTFont``. +- [otlLib] Replaced environment variable for GPOS compression level with an + equivalent option using the new config system. +- [designspaceLib] Incremented format version to 5.0 (#2436). + Added discrete axes, variable fonts, STAT information, either design- or + user-space location on instances. + Added ``fontTools.designspaceLib.split`` module to split a designspace + into sub-spaces that interpolate and that represent the variable fonts + listed in the document. + Made instance names optional and allow computing them from STAT data instead. + Added ``fontTools.designspaceLib.statNames`` module. + Allow instances to have the same location as a previously defined STAT label. + Deprecated some attributes: + ``SourceDescriptor``: ``copyLib``, ``copyInfo``, ``copyGroups``, ``copyFeatures``. + ``InstanceDescriptor``: ``kerning``, ``info``; ``glyphs``: use rules or sparse + sources. + For both, ``location``: use the more explicit designLocation. + Note: all are soft deprecations and existing code should keep working. + Updated documentation for Python methods and the XML format. +- [varLib] Added ``build_many`` to build several variable fonts from a single + designspace document (#2436). + Added ``fontTools.varLib.stat`` module to build STAT tables from a designspace + document. +- [otBase] Try to use the Harfbuzz Repacker for packing GSUB/GPOS tables when + ``uharfbuzz`` python bindings are available (#2552). Disable it by setting the + "fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER" config option to ``False``. + If the option is set explicitly to ``True`` but ``uharfbuzz`` can't be imported + or fails to serialize for any reasons, an error will be raised (ImportError or + uharfbuzz errors). +- [CFF/T2] Ensure that ``pen.closePath()`` gets called for CFF2 charstrings (#2577). + Handle implicit CFF2 closePath within ``T2OutlineExtractor`` (#2580). + +4.32.0 (released 2022-04-08) +---------------------------- + +- [otlLib] Disable GPOS7 optimization to work around bug in Apple CoreText. + Always force Chaining GPOS8 for now (#2540). +- [glifLib] Added ``outputImpliedClosingLine=False`` parameter to ``Glyph.draw()``, + to control behaviour of ``PointToSegmentPen`` (6b4e2e7). +- [varLib.interpolatable] Check for wrong contour starting point (#2571). +- [cffLib] Remove leftover ``GlobalState`` class and fix calls to ``TopDictIndex()`` + (#2569, #2570). +- [instancer] Clear ``AxisValueArray`` if it is empty after instantiating (#2563). + +4.31.2 (released 2022-03-22) +---------------------------- + +- [varLib] fix instantiation of GPOS SinglePos values (#2555). + +4.31.1 (released 2022-03-18) +---------------------------- + +- [subset] fix subsetting OT-SVG when glyph id attribute is on the root ```` + element (#2553). + +4.31.0 (released 2022-03-18) +---------------------------- + +- [ttCollection] Fixed 'ResourceWarning: unclosed file' warning (#2549). +- [varLib.merger] Handle merging SinglePos with valueformat=0 (#2550). +- [ttFont] Update glyf's glyphOrder when calling TTFont.setGlyphOrder() (#2544). +- [ttFont] Added ``ensureDecompiled`` method to load all tables irrespective + of the ``lazy`` attribute (#2551). +- [otBase] Added ``iterSubTable`` method to iterate over BaseTable's children of + type BaseTable; useful for traversing a tree of otTables (#2551). + +4.30.0 (released 2022-03-10) +---------------------------- + +- [varLib] Added debug logger showing the glyph name for which ``gvar`` is built (#2542). +- [varLib.errors] Fixed undefined names in ``FoundANone`` and ``UnsupportedFormat`` + exceptions (ac4d5611). +- [otlLib.builder] Added ``windowsNames`` and ``macNames`` (bool) parameters to the + ``buildStatTabe`` function, so that one can select whether to only add one or both + of the two sets (#2528). +- [t1Lib] Added the ability to recreate PostScript stream (#2504). +- [name] Added ``getFirstDebugName``, ``getBest{Family,SubFamily,Full}Name`` methods (#2526). + +4.29.1 (released 2022-02-01) +---------------------------- + +- [colorLib] Fixed rounding issue with radial gradient's start/end circles inside + one another (#2521). +- [freetypePen] Handle rotate/skew transform when auto-computing width/height of the + buffer; raise PenError wen missing moveTo (#2517) + +4.29.0 (released 2022-01-24) +---------------------------- + +- [ufoLib] Fixed illegal characters and expanded reserved filenames (#2506). +- [COLRv1] Don't emit useless PaintColrLayers of lenght=1 in LayerListBuilder (#2513). +- [ttx] Removed legacy ``waitForKeyPress`` method on Windows (#2509). +- [pens] Added FreeTypePen that uses ``freetype-py`` and the pen protocol for + rasterizating outline paths (#2494). +- [unicodedata] Updated the script direction list to Unicode 14.0 (#2484). + Bumped unicodedata2 dependency to 14.0 (#2499). +- [psLib] Fixed type of ``fontName`` in ``suckfont`` (#2496). + +4.28.5 (released 2021-12-19) +---------------------------- + +- [svgPathPen] Continuation of #2471: make sure all occurrences of ``str()`` are now + replaced with user-defined ``ntos`` callable. +- [merge] Refactored code into submodules, plus several bugfixes and improvements: + fixed duplicate-glyph-resolution GSUB-lookup generation code; use tolerance in glyph + comparison for empty glyph's width; ignore space of default ignorable glyphs; + downgrade duplicates-resolution missing-GSUB from assert to warn; added --drop-tables + option (#2473, #2475, #2476). + +4.28.4 (released 2021-12-15) +---------------------------- + +- [merge] Merge GDEF marksets in Lookups properly (#2474). +- [feaLib] Have ``fontTools feaLib`` script exit with error code when build fails (#2459) +- [svgPathPen] Added ``ntos`` option to customize number formatting (e.g. rounding) (#2471). +- [subset] Speed up subsetting of large CFF fonts (#2467). +- [otTables] Speculatively promote lookups to extension to speed up compilation. If the + offset to lookup N is too big to fit in a ushort, the offset to lookup N+1 is going to + be too big as well, so we promote to extension all lookups from lookup N onwards (#2465). + +4.28.3 (released 2021-12-03) +---------------------------- + +- [subset] Fixed bug while subsetting ``COLR`` table, whereby incomplete layer records + pointing to missing glyphs were being retained leading to ``struct.error`` upon + compiling. Make it so that ``glyf`` glyph closure, which follows the ``COLR`` glyph + closure, does not influence the ``COLR`` table subsetting (#2461, #2462). +- [docs] Fully document the ``cmap`` and ``glyf`` tables (#2454, #2457). +- [colorLib.unbuilder] Fixed CLI by deleting no longer existing parameter (180bb1867). + +4.28.2 (released 2021-11-22) +---------------------------- + +- [otlLib] Remove duplicates when building coverage (#2433). +- [docs] Add interrogate configuration (#2443). +- [docs] Remove comment about missing “start” optional argument to ``calcChecksum`` (#2448). +- [cu2qu/cli] Adapt to the latest ufoLib2. +- [subset] Support subsetting SVG table and remove it from the list of drop by default tables (#534). +- [subset] add ``--pretty-svg`` option to pretty print SVG table contents (#2452). +- [merge] Support merging ``CFF`` tables (CID-keyed ``CFF`` is still not supported) (#2447). +- [merge] Support ``--output-file`` (#2447). +- [docs] Split table docs into individual pages (#2444). +- [feaLib] Forbid empty classes (#2446). +- [docs] Improve documentation for ``fontTools.ttLib.ttFont`` (#2442). + +4.28.1 (released 2021-11-08) +---------------------------- + +- [subset] Fixed AttributeError while traversing a color glyph's Paint graph when there is no + LayerList, which is optional (#2441). + +4.28.0 (released 2021-11-05) +---------------------------- + +- Dropped support for EOL Python 3.6, require Python 3.7 (#2417). +- [ufoLib/glifLib] Make filename-clash checks faster by using a set instead of a list (#2422). +- [subset] Don't crash if optional ClipList and LayerList are ``None`` (empty) (#2424, 2439). +- [OT-SVG] Removed support for old deprecated version 1 and embedded color palettes, + which were never officially part of the OpenType SVG spec. Upon compile, reuse offsets + to SVG documents that are identical (#2430). +- [feaLib] Added support for Variable Feature File syntax. This is experimental and subject + to change until it is finalized in the Adobe FEA spec (#2432). +- [unicodedata] Update Scripts/ScriptExtensions/Blocks to UnicodeData 14.0 (#2437). + +4.27.1 (released 2021-09-23) +---------------------------- + +- [otlLib] Fixed error when chained contextual lookup builder overflows (#2404, #2411). +- [bezierTools] Fixed two floating-point bugs: one when computing `t` for a point + lying on an almost horizontal/vertical line; another when computing the intersection + point between a curve and a line (#2413). + +4.27.0 (released 2021-09-14) +---------------------------- + +- [ttLib/otTables] Cleaned up virtual GID handling: allow virtual GIDs in ``Coverage`` + and ``ClassDef`` readers; removed unused ``allowVID`` argument from ``TTFont`` + constructor, and ``requireReal`` argument in ``TTFont.getGlyphID`` method. + Make ``TTFont.setGlyphOrder`` clear reverse glyphOrder map, and assume ``glyphOrder`` + internal attribute is never modified outside setGlyphOrder; added ``TTFont.getGlyphNameMany`` + and ``getGlyphIDMany`` (#1536, #1654, #2334, #2398). +- [py23] Dropped internal use of ``fontTools.py23`` module to fix deprecation warnings + in client code that imports from fontTools (#2234, #2399, #2400). +- [subset] Fix subsetting COLRv1 clip boxes when font is loaded lazily (#2408). + +4.26.2 (released 2021-08-09) +---------------------------- + +- [otTables] Added missing ``CompositeMode.PLUS`` operator (#2390). + +4.26.1 (released 2021-08-03) +---------------------------- + +- [transform] Added ``transformVector`` and ``transformVectors`` methods to the + ``Transform`` class. Similar to ``transformPoint`` but ignore the translation + part (#2386). + +4.26.0 (released 2021-08-03) +---------------------------- + +- [xmlWriter] Default to ``"\n"`` for ``newlinestr`` instead of platform-specific + ``os.linesep`` (#2384). +- [otData] Define COLRv1 ClipList and ClipBox (#2379). +- [removeOverlaps/instancer] Added --ignore-overlap-errors option to work around + Skia PathOps.Simplify bug (#2382, #2363, google/fonts#3365). +- NOTE: This will be the last version to support Python 3.6. FontTools will require + Python 3.7 or above from the next release (#2350) + +4.25.2 (released 2021-07-26) +---------------------------- + +- [COLRv1] Various changes to sync with the latest CORLv1 draft spec. In particular: + define COLR.VarIndexMap, remove/inline ColorIndex struct, add VarIndexBase to ``PaintVar*`` tables (#2372); + add reduced-precicion specialized transform Paints; + define Angle as fraction of half circle encoded as F2Dot14; + use FWORD (int16) for all Paint center coordinates; + change PaintTransform to have an offset to Affine2x3; +- [ttLib] when importing XML, only set sfntVersion if the font has no reader and is empty (#2376) + +4.25.1 (released 2021-07-16) +---------------------------- + +- [ttGlyphPen] Fixed bug in ``TTGlyphPointPen``, whereby open contours (i.e. starting + with segmentType "move") would throw ``NotImplementedError``. They are now treated + as if they are closed, like with the ``TTGlyphPen`` (#2364, #2366). + +4.25.0 (released 2021-07-05) +---------------------------- + +- [tfmLib] Added new library for parsing TeX Font Metric (TFM) files (#2354). +- [TupleVariation] Make shared tuples order deterministic on python < 3.7 where + Counter (subclass of dict) doesn't remember insertion order (#2351, #2353). +- [otData] Renamed COLRv1 structs to remove 'v1' suffix and match the updated draft + spec: 'LayerV1List' -> 'LayerList', 'BaseGlyphV1List' -> 'BaseGlyphList', + 'BaseGlyphV1Record' -> 'BaseGlyphPaintRecord' (#2346). + Added 8 new ``PaintScale*`` tables: with/without centers, uniform vs non-uniform. + Added ``*AroundCenter`` variants to ``PaintRotate`` and ``PaintSkew``: the default + versions no longer have centerX/Y, but default to origin. + ``PaintRotate``, ``PaintSkew`` and ``PaintComposite`` formats were re-numbered. + NOTE: these are breaking changes; clients using the experimental COLRv1 API will + have to be updated (#2348). +- [pointPens] Allow ``GuessSmoothPointPen`` to accept a tolerance. Fixed call to + ``math.atan2`` with x/y parameters inverted. Sync the code with fontPens (#2344). +- [post] Fixed parsing ``post`` table format 2.0 when it contains extra garbage + at the end of the stringData array (#2314). +- [subset] drop empty features unless 'size' with FeatureParams table (#2324). +- [otlLib] Added ``otlLib.optimize`` module; added GPOS compaction algorithm. + The compaction can be run on existing fonts with ``fonttools otlLib.optimize`` + or using the snippet ``compact_gpos.py``. There's experimental support for + compacting fonts at compilation time using an environment variable, but that + might be removed later (#2326). + +4.24.4 (released 2021-05-25) +---------------------------- + +- [subset/instancer] Fixed ``AttributeError`` when instantiating a VF that + contains GPOS ValueRecords with ``Device`` tables but without the respective + non-Device values (e.g. ``XAdvDevice`` without ``XAdvance``). When not + explicitly set, the latter are assumed to be 0 (#2323). + +4.24.3 (released 2021-05-20) +---------------------------- + +- [otTables] Fixed ``AttributeError`` in methods that split LigatureSubst, + MultipleSubst and AlternateSubst subtables when an offset overflow occurs. + The ``Format`` attribute was removed in v4.22.0 (#2319). + +4.24.2 (released 2021-05-20) +---------------------------- + +- [ttGlyphPen] Fixed typing annotation of TTGlyphPen glyphSet parameter (#2315). +- Fixed two instances of DeprecationWarning: invalid escape sequence (#2311). + +4.24.1 (released 2021-05-20) +---------------------------- + +- [subset] Fixed AttributeError when SinglePos subtable has None Value (ValueFormat 0) + (#2312, #2313). + +4.24.0 (released 2021-05-17) +---------------------------- + +- [pens] Add ``ttGlyphPen.TTGlyphPointPen`` similar to ``TTGlyphPen`` (#2205). + +4.23.1 (released 2021-05-14) +---------------------------- + +- [subset] Fix ``KeyError`` after subsetting ``COLR`` table that initially contains + both v0 and v1 color glyphs when the subset only requested v1 glyphs; we were + not pruning the v0 portion of the table (#2308). +- [colorLib] Set ``LayerV1List`` attribute to ``None`` when empty, it's optional + in CORLv1 (#2308). + +4.23.0 (released 2021-05-13) +---------------------------- + +- [designspaceLib] Allow to use ``\\UNC`` absolute paths on Windows (#2299, #2306). +- [varLib.merger] Fixed bug where ``VarLibMergeError`` was raised with incorrect + parameters (#2300). +- [feaLib] Allow substituting a glyph class with ``NULL`` to delete multiple glyphs + (#2303). +- [glyf] Fixed ``NameError`` exception in ``getPhantomPoints`` (#2295, #2305). +- [removeOverlaps] Retry pathops.simplify after rounding path coordinates to integers + if it fails the first time using floats, to work around a rare and hard to debug + Skia bug (#2288). +- [varLib] Added support for building, reading, writing and optimizing 32-bit + ``ItemVariationStore`` as used in COLRv1 table (#2285). +- [otBase/otConverters] Add array readers/writers for int types (#2285). +- [feaLib] Allow more than one lookahead glyph/class in contextual positioning with + "value at end" (#2293, #2294). +- [COLRv1] Default varIdx should be 0xFFFFFFFF (#2297, #2298). +- [pens] Make RecordingPointPen actually pass on identifiers; replace asserts with + explicit ``PenError`` exception (#2284). +- [mutator] Round lsb for CF2 fonts as well (#2286). + +4.22.1 (released 2021-04-26) +---------------------------- + +- [feaLib] Skip references to named lookups if the lookup block definition + is empty, similarly to makeotf. This also fixes an ``AttributeError`` while + generating ``aalt`` feature (#2276, #2277). +- [subset] Fixed bug with ``--no-hinting`` implementation for Device tables (#2272, + #2275). The previous code was alwyas dropping Device tables if no-hinting was + requested, but some Device tables (DeltaFormat=0x8000) are also used to encode + variation indices and need to be retained. +- [otBase] Fixed bug in getting the ValueRecordSize when decompiling ``MVAR`` + table with ``lazy=True`` (#2273, #2274). +- [varLib/glyf/gvar] Optimized and simplified ``GlyphCoordinates`` and + ``TupleVariation`` classes, use ``bytearray`` where possible, refactored + phantom-points calculations. We measured about 30% speedup in total time + of loading master ttfs, building gvar, and saving (#2261, #2266). +- [subset] Fixed ``AssertionError`` while pruning unused CPAL palettes when + ``0xFFFF`` is present (#2257, #2259). + +4.22.0 (released 2021-04-01) +---------------------------- + +- [ttLib] Remove .Format from Coverage, ClassDef, SingleSubst, LigatureSubst, + AlternateSubst, MultipleSubst (#2238). + ATTENTION: This will change your TTX dumps! +- [misc.arrayTools] move Vector to its own submodule, and rewrite as a tuple + subclass (#2201). +- [docs] Added a terminology section for varLib (#2209). +- [varLib] Move rounding to VariationModel, to avoid error accumulation from + multiple deltas (#2214) +- [varLib] Explain merge errors in more human-friendly terms (#2223, #2226) +- [otlLib] Correct some documentation (#2225) +- [varLib/otlLib] Allow merging into VariationFont without first saving GPOS + PairPos2 (#2229) +- [subset] Improve PairPosFormat2 subsetting (#2221) +- [ttLib] TTFont.save: create file on disk as late as possible (#2253) +- [cffLib] Add missing CFF2 dict operators LanguageGroup and ExpansionFactor + (#2249) + ATTENTION: This will change your TTX dumps! + +4.21.1 (released 2021-02-26) +---------------------------- + +- [pens] Reverted breaking change that turned ``AbstractPen`` and ``AbstractPointPen`` + into abstract base classes (#2164, #2198). + +4.21.0 (released 2021-02-26) +---------------------------- + +- [feaLib] Indent anchor statements in ``asFea()`` to make them more legible and + diff-able (#2193). +- [pens] Turn ``AbstractPen`` and ``AbstractPointPen`` into abstract base classes + (#2164). +- [feaLib] Added support for parsing and building ``STAT`` table from AFDKO feature + files (#2039). +- [instancer] Added option to update name table of generated instance using ``STAT`` + table's axis values (#2189). +- [bezierTools] Added functions to compute bezier point-at-time, as well as line-line, + curve-line and curve-curve intersections (#2192). + +4.20.0 (released 2021-02-15) +---------------------------- + +- [COLRv1] Added ``unbuildColrV1`` to deconstruct COLRv1 otTables to raw json-able + data structure; it does the reverse of ``buildColrV1`` (#2171). +- [feaLib] Allow ``sub X by NULL`` sequence to delete a glyph (#2170). +- [arrayTools] Fixed ``Vector`` division (#2173). +- [COLRv1] Define new ``PaintSweepGradient`` (#2172). +- [otTables] Moved ``Paint.Format`` enum class outside of ``Paint`` class definition, + now named ``PaintFormat``. It was clashing with paint instance ``Format`` attribute + and thus was breaking lazy load of COLR table which relies on magic ``__getattr__`` + (#2175). +- [COLRv1] Replace hand-coded builder functions with otData-driven dynamic + implementation (#2181). +- [COLRv1] Define additional static (non-variable) Paint formats (#2181). +- [subset] Added support for subsetting COLR v1 and CPAL tables (#2174, #2177). +- [fontBuilder] Allow ``setupFvar`` to optionally take ``designspaceLib.AxisDescriptor`` + objects. Added new ``setupAvar`` method. Support localised names for axes and + named instances (#2185). + +4.19.1 (released 2021-01-28) +---------------------------- + +- [woff2] An initial off-curve point with an overlap flag now stays an off-curve + point after compression. + +4.19.0 (released 2021-01-25) +---------------------------- + +- [codecs] Handle ``errors`` parameter different from 'strict' for the custom + extended mac encodings (#2137, #2132). +- [featureVars] Raise better error message when a script is missing the required + default language system (#2154). +- [COLRv1] Avoid abrupt change caused by rounding ``PaintRadialGradient.c0`` when + the start circle almost touches the end circle's perimeter (#2148). +- [COLRv1] Support building unlimited lists of paints as 255-ary trees of + ``PaintColrLayers`` tables (#2153). +- [subset] Prune redundant format-12 cmap subtables when all non-BMP characters + are dropped (#2146). +- [basePen] Raise ``MissingComponentError`` instead of bare ``KeyError`` when a + referenced component is missing (#2145). + +4.18.2 (released 2020-12-16) +---------------------------- + +- [COLRv1] Implemented ``PaintTranslate`` paint format (#2129). +- [varLib.cff] Fixed unbound local variable error (#1787). +- [otlLib] Don't crash when creating OpenType class definitions if some glyphs + occur more than once (#2125). + +4.18.1 (released 2020-12-09) +---------------------------- + +- [colorLib] Speed optimization for ``LayerV1ListBuilder`` (#2119). +- [mutator] Fixed missing tab in ``interpolate_cff2_metrics`` (0957dc7a). + +4.18.0 (released 2020-12-04) +---------------------------- + +- [COLRv1] Update to latest draft: added ``PaintRotate`` and ``PaintSkew`` (#2118). +- [woff2] Support new ``brotlicffi`` bindings for PyPy (#2117). +- [glifLib] Added ``expectContentsFile`` parameter to ``GlyphSet``, for use when + reading existing UFOs, to comply with the specification stating that a + ``contents.plist`` file must exist in a glyph set (#2114). +- [subset] Allow ``LangSys`` tags in ``--layout-scripts`` option (#2112). For example: + ``--layout-scripts=arab.dflt,arab.URD,latn``; this will keep ``DefaultLangSys`` + and ``URD`` language for ``arab`` script, and all languages for ``latn`` script. +- [varLib.interpolatable] Allow UFOs to be checked; report open paths, non existant + glyphs; add a ``--json`` option to produce a machine-readable list of + incompatibilities +- [pens] Added ``QuartzPen`` to create ``CGPath`` from glyph outlines on macOS. + Requires pyobjc (#2107). +- [feaLib] You can export ``FONTTOOLS_LOOKUP_DEBUGGING=1`` to enable feature file + debugging info stored in ``Debg`` table (#2106). +- [otlLib] Build more efficient format 1 and format 2 contextual lookups whenever + possible (#2101). + +4.17.1 (released 2020-11-16) +---------------------------- + +- [colorLib] Fixed regression in 4.17.0 when building COLR v0 table; when color + layers are stored in UFO lib plist, we can't distinguish tuples from lists so + we need to accept either types (e5439eb9, googlefonts/ufo2ft/issues#426). + +4.17.0 (released 2020-11-12) +---------------------------- + +- [colorLib/otData] Updated to latest draft ``COLR`` v1 spec (#2092). +- [svgLib] Fixed parsing error when arc commands' boolean flags are not separated + by space or comma (#2094). +- [varLib] Interpret empty non-default glyphs as 'missing', if the default glyph is + not empty (#2082). +- [feaLib.builder] Only stash lookup location for ``Debg`` if ``Builder.buildLookups_`` + has cooperated (#2065, #2067). +- [varLib] Fixed bug in VarStore optimizer (#2073, #2083). +- [varLib] Add designspace lib key for custom feavar feature tag (#2080). +- Add HashPointPen adapted from psautohint. With this pen, a hash value of a glyph + can be computed, which can later be used to detect glyph changes (#2005). + +4.16.1 (released 2020-10-05) +---------------------------- + +- [varLib.instancer] Fixed ``TypeError`` exception when instantiating a VF with + a GSUB table 1.1 in which ``FeatureVariations`` attribute is present but set to + ``None`` -- indicating that optional ``FeatureVariations`` is missing (#2077). +- [glifLib] Make ``x`` and ``y`` attributes of the ``point`` element required + even when validation is turned off, and raise a meaningful ``GlifLibError`` + message when that happens (#2075). + +4.16.0 (released 2020-09-30) +---------------------------- + +- [removeOverlaps] Added new module and ``removeOverlaps`` function that merges + overlapping contours and components in TrueType glyphs. It requires the + `skia-pathops `__ module. + Note that removing overlaps invalidates the TrueType hinting (#2068). +- [varLib.instancer] Added ``--remove-overlaps`` command-line option. + The ``overlap`` option in ``instantiateVariableFont`` now takes an ``OverlapMode`` + enum: 0: KEEP_AND_DONT_SET_FLAGS, 1: KEEP_AND_SET_FLAGS (default), and 2: REMOVE. + The latter is equivalent to calling ``removeOverlaps`` on the generated static + instance. The option continues to accept ``bool`` value for backward compatibility. + + +4.15.0 (released 2020-09-21) +---------------------------- + +- [plistlib] Added typing annotations to plistlib module. Set up mypy static + typechecker to run automatically on CI (#2061). +- [ttLib] Implement private ``Debg`` table, a reverse-DNS namespaced JSON dict. +- [feaLib] Optionally add an entry into the ``Debg`` table with the original + lookup name (if any), feature name / script / language combination (if any), + and original source filename and line location. Annotate the ttx output for + a lookup with the information from the Debg table (#2052). +- [sfnt] Disabled checksum checking by default in ``SFNTReader`` (#2058). +- [Docs] Document ``mtiLib`` module (#2027). +- [varLib.interpolatable] Added checks for contour node count and operation type + of each node (#2054). +- [ttLib] Added API to register custom table packer/unpacker classes (#2055). + +4.14.0 (released 2020-08-19) +---------------------------- + +- [feaLib] Allow anonymous classes in LookupFlags definitions (#2037). +- [Docs] Better document DesignSpace rules processing order (#2041). +- [ttLib] Fixed 21-year old bug in ``maxp.maxComponentDepth`` calculation (#2044, + #2045). +- [varLib.models] Fixed misspelled argument name in CLI entry point (81d0042a). +- [subset] When subsetting GSUB v1.1, fixed TypeError by checking whether the + optional FeatureVariations table is present (e63ecc5b). +- [Snippets] Added snippet to show how to decompose glyphs in a TTF (#2030). +- [otlLib] Generate GSUB type 5 and GPOS type 7 contextual lookups where appropriate + (#2016). + +4.13.0 (released 2020-07-10) +---------------------------- + +- [feaLib/otlLib] Moved lookup subtable builders from feaLib to otlLib; refactored + some common code (#2004, #2007). +- [docs] Document otlLib module (#2009). +- [glifLib] Fixed bug with some UFO .glif filenames clashing on case-insensitive + filesystems (#2001, #2002). +- [colorLib] Updated COLRv1 implementation following changes in the draft spec: + (#2008, googlefonts/colr-gradients-spec#24). + +4.12.1 (released 2020-06-16) +---------------------------- + +- [_n_a_m_e] Fixed error in ``addMultilingualName`` with one-character names. + Only attempt to recovered malformed UTF-16 data from a ``bytes`` string, + not from unicode ``str`` (#1997, #1998). + +4.12.0 (released 2020-06-09) +---------------------------- + +- [otlLib/varLib] Ensure that the ``AxisNameID`` in the ``STAT`` and ``fvar`` + tables is grater than 255 as per OpenType spec (#1985, #1986). +- [docs] Document more modules in ``fontTools.misc`` package: ``filenames``, + ``fixedTools``, ``intTools``, ``loggingTools``, ``macCreatorType``, ``macRes``, + ``plistlib`` (#1981). +- [OS/2] Don't calculate whole sets of unicode codepoints, use faster and more memory + efficient ranges and bisect lookups (#1984). +- [voltLib] Support writing back abstract syntax tree as VOLT data (#1983). +- [voltLib] Accept DO_NOT_TOUCH_CMAP keyword (#1987). +- [subset/merge] Fixed a namespace clash involving a private helper class (#1955). + +4.11.0 (released 2020-05-28) +---------------------------- + +- [feaLib] Introduced ``includeDir`` parameter on Parser and IncludingLexer to + explicitly specify the directory to search when ``include()`` statements are + encountered (#1973). +- [ufoLib] Silently delete duplicate glyphs within the same kerning group when reading + groups (#1970). +- [ttLib] Set version of COLR table when decompiling COLRv1 (commit 9d8a7e2). + +4.10.2 (released 2020-05-20) +---------------------------- + +- [sfnt] Fixed ``NameError: SimpleNamespace`` while reading TTC header. The regression + was introduced with 4.10.1 after removing ``py23`` star import. + +4.10.1 (released 2020-05-19) +---------------------------- + +- [sfnt] Make ``SFNTReader`` pickleable even when TTFont is loaded with lazy=True + option and thus keeps a reference to an external file (#1962, #1967). +- [feaLib.ast] Restore backward compatibility (broken in 4.10 with #1905) for + ``ChainContextPosStatement`` and ``ChainContextSubstStatement`` classes. + Make them accept either list of lookups or list of lists of lookups (#1961). +- [docs] Document some modules in ``fontTools.misc`` package: ``arrayTools``, + ``bezierTools`` ``cliTools`` and ``eexec`` (#1956). +- [ttLib._n_a_m_e] Fixed ``findMultilingualName()`` when name record's ``string`` is + encoded as bytes sequence (#1963). + +4.10.0 (released 2020-05-15) +---------------------------- + +- [varLib] Allow feature variations to be active across the entire space (#1957). +- [ufoLib] Added support for ``formatVersionMinor`` in UFO's ``fontinfo.plist`` and for + ``formatMinor`` attribute in GLIF file as discussed in unified-font-object/ufo-spec#78. + No changes in reading or writing UFOs until an upcoming (non-0) minor update of the + UFO specification is published (#1786). +- [merge] Fixed merging fonts with different versions of ``OS/2`` table (#1865, #1952). +- [subset] Fixed ``AttributeError`` while subsetting ``ContextSubst`` and ``ContextPos`` + Format 3 subtable (#1879, #1944). +- [ttLib.table._m_e_t_a] if data happens to be ascii, emit comment in TTX (#1938). +- [feaLib] Support multiple lookups per glyph position (#1905). +- [psCharStrings] Use inheritance to avoid repeated code in initializer (#1932). +- [Doc] Improved documentation for the following modules: ``afmLib`` (#1933), ``agl`` + (#1934), ``cffLib`` (#1935), ``cu2qu`` (#1937), ``encodings`` (#1940), ``feaLib`` + (#1941), ``merge`` (#1949). +- [Doc] Split off developer-centric info to new page, making front page of docs more + user-focused. List all utilities and sub-modules with brief descriptions. + Make README more concise and focused (#1914). +- [otlLib] Add function to build STAT table from high-level description (#1926). +- [ttLib._n_a_m_e] Add ``findMultilingualName()`` method (#1921). +- [unicodedata] Update ``RTL_SCRIPTS`` for Unicode 13.0 (#1925). +- [gvar] Sort ``gvar`` XML output by glyph name, not glyph order (#1907, #1908). +- [Doc] Added help options to ``fonttools`` command line tool (#1913, #1920). + Ensure all fonttools CLI tools have help documentation (#1948). +- [ufoLib] Only write fontinfo.plist when there actually is content (#1911). + +4.9.0 (released 2020-04-29) +--------------------------- + +- [subset] Fixed subsetting of FeatureVariations table. The subsetter no longer drops + FeatureVariationRecords that have empty substitutions as that will keep the search + going and thus change the logic. It will only drop empty records that occur at the + end of the FeatureVariationRecords array (#1881). +- [subset] Remove FeatureVariations table and downgrade GSUB/GPOS to version 0x10000 + when FeatureVariations contain no FeatureVariationRecords after subsetting (#1903). +- [agl] Add support for legacy Adobe Glyph List of glyph names in ``fontTools.agl`` + (#1895). +- [feaLib] Ignore superfluous script statements (#1883). +- [feaLib] Hide traceback by default on ``fonttools feaLib`` command line. + Use ``--traceback`` option to show (#1898). +- [feaLib] Check lookup index in chaining sub/pos lookups and print better error + message (#1896, #1897). +- [feaLib] Fix building chained alt substitutions (#1902). +- [Doc] Included all fontTools modules in the sphinx-generated documentation, and + published it to ReadTheDocs for continuous documentation of the fontTools project + (#1333). Check it out at https://fonttools.readthedocs.io/. Thanks to Chris Simpkins! +- [transform] The ``Transform`` class is now subclass of ``typing.NamedTuple``. No + change in functionality (#1904). + + +4.8.1 (released 2020-04-17) +--------------------------- + +- [feaLib] Fixed ``AttributeError: 'NoneType' has no attribute 'getAlternateGlyphs'`` + when ``aalt`` feature references a chain contextual substitution lookup + (googlefonts/fontmake#648, #1878). + +4.8.0 (released 2020-04-16) +--------------------------- + +- [feaLib] If Parser is initialized without a ``glyphNames`` parameter, it cannot + distinguish between a glyph name containing an hyphen, or a range of glyph names; + instead of raising an error, it now interprets them as literal glyph names, while + also outputting a logging warning to alert user about the ambiguity (#1768, #1870). +- [feaLib] When serializing AST to string, emit spaces around hyphens that denote + ranges. Also, fixed an issue with CID ranges when round-tripping AST->string->AST + (#1872). +- [Snippets/otf2ttf] In otf2ttf.py script update LSB in hmtx to match xMin (#1873). +- [colorLib] Added experimental support for building ``COLR`` v1 tables as per + the `colr-gradients-spec `__ + draft proposal. **NOTE**: both the API and the XML dump of ``COLR`` v1 are + susceptible to change while the proposal is being discussed and formalized (#1822). + +4.7.0 (released 2020-04-03) +--------------------------- + +- [cu2qu] Added ``fontTools.cu2qu`` package, imported from the original + `cu2qu `__ project. The ``cu2qu.pens`` module + was moved to ``fontTools.pens.cu2quPen``. The optional cu2qu extension module + can be compiled by installing `Cython `__ before installing + fonttools from source (i.e. git repo or sdist tarball). The wheel package that + is published on PyPI (i.e. the one ``pip`` downloads, unless ``--no-binary`` + option is used), will continue to be pure-Python for now (#1868). + +4.6.0 (released 2020-03-24) +--------------------------- + +- [varLib] Added support for building variable ``BASE`` table version 1.1 (#1858). +- [CPAL] Added ``fromRGBA`` method to ``Color`` class (#1861). + + +4.5.0 (released 2020-03-20) +--------------------------- + +- [designspaceLib] Added ``add{Axis,Source,Instance,Rule}Descriptor`` methods to + ``DesignSpaceDocument`` class, to initialize new descriptor objects using keyword + arguments, and at the same time append them to the current document (#1860). +- [unicodedata] Update to Unicode 13.0 (#1859). + +4.4.3 (released 2020-03-13) +--------------------------- + +- [varLib] Always build ``gvar`` table for TrueType-flavored Variable Fonts, + even if it contains no variation data. The table is required according to + the OpenType spec (#1855, #1857). + +4.4.2 (released 2020-03-12) +--------------------------- + +- [ttx] Annotate ``LookupFlag`` in XML dump with comment explaining what bits + are set and what they mean (#1850). +- [feaLib] Added more descriptive message to ``IncludedFeaNotFound`` error (#1842). + +4.4.1 (released 2020-02-26) +--------------------------- + +- [woff2] Skip normalizing ``glyf`` and ``loca`` tables if these are missing from + a font (e.g. in NotoColorEmoji using ``CBDT/CBLC`` tables). +- [timeTools] Use non-localized date parsing in ``timestampFromString``, to fix + error when non-English ``LC_TIME`` locale is set (#1838, #1839). +- [fontBuilder] Make sure the CFF table generated by fontBuilder can be used by varLib + without having to compile and decompile the table first. This was breaking in + converting the CFF table to CFF2 due to some unset attributes (#1836). + +4.4.0 (released 2020-02-18) +--------------------------- + +- [colorLib] Added ``fontTools.colorLib.builder`` module, initially with ``buildCOLR`` + and ``buildCPAL`` public functions. More color font formats will follow (#1827). +- [fontBuilder] Added ``setupCOLR`` and ``setupCPAL`` methods (#1826). +- [ttGlyphPen] Quantize ``GlyphComponent.transform`` floats to ``F2Dot14`` to fix + round-trip issue when computing bounding boxes of transformed components (#1830). +- [glyf] If a component uses reference points (``firstPt`` and ``secondPt``) for + alignment (instead of X and Y offsets), compute the effective translation offset + *after* having applied any transform (#1831). +- [glyf] When all glyphs have zero contours, compile ``glyf`` table data as a single + null byte in order to pass validation by OTS and Windows (#1829). +- [feaLib] Parsing feature code now ensures that referenced glyph names are part of + the known glyph set, unless a glyph set was not provided. +- [varLib] When filling in the default axis value for a missing location of a source or + instance, correctly map the value forward. +- [varLib] The avar table can now contain mapping output values that are greater than + OR EQUAL to the preceeding value, as the avar specification allows this. +- [varLib] The errors of the module are now ordered hierarchically below VarLibError. + See #1821. + +4.3.0 (released 2020-02-03) +--------------------------- + +- [EBLC/CBLC] Fixed incorrect padding length calculation for Format 3 IndexSubTable + (#1817, #1818). +- [varLib] Fixed error when merging OTL tables and TTFonts were loaded as ``lazy=True`` + (#1808, #1809). +- [varLib] Allow to use master fonts containing ``CFF2`` table when building VF (#1816). +- [ttLib] Make ``recalcBBoxes`` option work also with ``CFF2`` table (#1816). +- [feaLib] Don't reset ``lookupflag`` in lookups defined inside feature blocks. + They will now inherit the current ``lookupflag`` of the feature. This is what + Adobe ``makeotf`` also does in this case (#1815). +- [feaLib] Fixed bug with mixed single/multiple substitutions. If a single substitution + involved a glyph class, we were incorrectly using only the first glyph in the class + (#1814). + +4.2.5 (released 2020-01-29) +--------------------------- + +- [feaLib] Do not fail on duplicate multiple substitutions, only warn (#1811). +- [subset] Optimize SinglePos subtables to Format 1 if all ValueRecords are the same + (#1802). + +4.2.4 (released 2020-01-09) +--------------------------- + +- [unicodedata] Update RTL_SCRIPTS for Unicode 11 and 12. + +4.2.3 (released 2020-01-07) +--------------------------- + +- [otTables] Fixed bug when splitting `MarkBasePos` subtables as offsets overflow. + The mark class values in the split subtable were not being updated, leading to + invalid mark-base attachments (#1797, googlefonts/noto-source#145). +- [feaLib] Only log a warning instead of error when features contain duplicate + substitutions (#1767). +- [glifLib] Strip XML comments when parsing with lxml (#1784, #1785). + +4.2.2 (released 2019-12-12) +--------------------------- + +- [subset] Fixed issue with subsetting FeatureVariations table when the index + of features changes as features get dropped. The feature index need to be + remapped to point to index of the remaining features (#1777, #1782). +- [fontBuilder] Added `addFeatureVariations` method to `FontBuilder` class. This + is a shorthand for calling `featureVars.addFeatureVariations` on the builder's + TTFont object (#1781). +- [glyf] Fixed the flags bug in glyph.drawPoints() like we did for glyph.draw() + (#1771, #1774). + +4.2.1 (released 2019-12-06) +--------------------------- + +- [glyf] Use the ``flagOnCurve`` bit mask in ``glyph.draw()``, so that we ignore + the ``overlap`` flag that may be set when instantiating variable fonts (#1771). + +4.2.0 (released 2019-11-28) +--------------------------- + +- [pens] Added the following pens: + + * ``roundingPen.RoundingPen``: filter pen that rounds coordinates and components' + offsets to integer; + * ``roundingPen.RoundingPointPen``: like the above, but using PointPen protocol. + * ``filterPen.FilterPointPen``: base class for filter point pens; + * ``transformPen.TransformPointPen``: filter point pen to apply affine transform; + * ``recordingPen.RecordingPointPen``: records and replays point-pen commands. + +- [ttGlyphPen] Always round float coordinates and component offsets to integers + (#1763). +- [ufoLib] When converting kerning groups from UFO2 to UFO3, avoid confusing + groups with the same name as one of the glyphs (#1761, #1762, + unified-font-object/ufo-spec#98). + +4.1.0 (released 2019-11-18) +--------------------------- + +- [instancer] Implemented restricting axis ranges (level 3 partial instancing). + You can now pass ``{axis_tag: (min, max)}`` tuples as input to the + ``instantiateVariableFont`` function. Note that changing the default axis + position is not supported yet. The command-line script also accepts axis ranges + in the form of colon-separated float values, e.g. ``wght=400:700`` (#1753, #1537). +- [instancer] Never drop STAT ``DesignAxis`` records, but only prune out-of-range + ``AxisValue`` records. +- [otBase/otTables] Enforce that VarStore.RegionAxisCount == fvar.axisCount, even + when regions list is empty to appease OTS < v8.0 (#1752). +- [designspaceLib] Defined new ``processing`` attribute for ```` element, + with values "first" or "last", plus other editorial changes to DesignSpace + specification. Bumped format version to 4.1 (#1750). +- [varLib] Improved error message when masters' glyph orders do not match (#1758, + #1759). +- [featureVars] Allow to specify custom feature tag in ``addFeatureVariations``; + allow said feature to already exist, in which case we append new lookup indices + to existing features. Implemented ```` attribute ``processing`` according to + DesignSpace specification update in #1750. Depending on this flag, we generate + either an 'rvrn' (always processed first) or a 'rclt' feature (follows lookup order, + therefore last) (#1747, #1625, #1371). +- [ttCollection] Added support for context manager auto-closing via ``with`` statement + like with ``TTFont`` (#1751). +- [unicodedata] Require unicodedata2 >= 12.1.0. +- [py2.py3] Removed yet more PY2 vestiges (#1743). +- [_n_a_m_e] Fixed issue when comparing NameRecords with different string types (#1742). +- [fixedTools] Changed ``fixedToFloat`` to not do any rounding but simply return + ``value / (1 << precisionBits)``. Added ``floatToFixedToStr`` and + ``strToFixedToFloat`` functions to be used when loading from or dumping to XML. + Fixed values (e.g. fvar axes and instance coordinates, avar mappings, etc.) are + are now stored as un-rounded decimal floats upon decompiling (#1740, #737). +- [feaLib] Fixed handling of multiple ``LigatureCaret`` statements for the same glyph. + Only the first rule per glyph is used, additional ones are ignored (#1733). + +4.0.2 (released 2019-09-26) +--------------------------- + +- [voltLib] Added support for ``ALL`` and ``NONE`` in ``PROCESS_MARKS`` (#1732). +- [Silf] Fixed issue in ``Silf`` table compilation and decompilation regarding str vs + bytes in python3 (#1728). +- [merge] Handle duplicate glyph names better: instead of appending font index to + all glyph names, use similar code like we use in ``post`` and ``CFF`` tables (#1729). + +4.0.1 (released 2019-09-11) +--------------------------- + +- [otTables] Support fixing offset overflows in ``MultipleSubst`` lookup subtables + (#1706). +- [subset] Prune empty strikes in ``EBDT`` and ``CBDT`` table data (#1698, #1633). +- [pens] Fixed issue in ``PointToSegmentPen`` when last point of closed contour has + same coordinates as the starting point and was incorrectly dropped (#1720). +- [Graphite] Fixed ``Sill`` table output to pass OTS (#1705). +- [name] Added ``removeNames`` method to ``table__n_a_m_e`` class (#1719). +- [ttLib] Added aliases for renamed entries ``ascender`` and ``descender`` in + ``hhea`` table (#1715). + +4.0.0 (released 2019-08-22) +--------------------------- + +- NOTE: The v4.x version series only supports Python 3.6 or greater. You can keep + using fonttools 3.x if you need support for Python 2. +- [py23] Removed all the python2-only code since it is no longer reachable, thus + unused; only the Python3 symbols were kept, but these are no-op. The module is now + DEPRECATED and will removed in the future. +- [ttLib] Fixed UnboundLocalError for empty loca/glyph tables (#1680). Also, allow + the glyf table to be incomplete when dumping to XML (#1681). +- [varLib.models] Fixed KeyError while sorting masters and there are no on-axis for + a given axis (38a8eb0e). +- [cffLib] Make sure glyph names are unique (#1699). +- [feaLib] Fix feature parser to correctly handle octal numbers (#1700). + +\... see `here `__ for earlier changes diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6887be2ea45aef2a839ef90612b8422c0014e7e1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/RECORD @@ -0,0 +1,359 @@ +../../../bin/fonttools,sha256=Uk6eYJ5nIg1i_X0BdskUh6APfGQ5QCBoeIr_9kksGYc,375 +../../../bin/pyftmerge,sha256=B4N-L19EpKbipETELlbVXOyBcTm-82uJ89SVh3as_2k,372 +../../../bin/pyftsubset,sha256=ADQUCfSPCI2iJjzrKeNHJ3emPHkbLByFxXUUDE3d47U,373 +../../../bin/ttx,sha256=bF-hnug5CcaQRpo7-Q18eOK5eBJyhnyKclOHjdtCiQc,370 +../../../share/man/man1/ttx.1,sha256=cLbm_pOOj1C76T2QXvDxzwDj9gk-GTd5RztvTMsouFw,5377 +fontTools/__init__.py,sha256=MfqTqdwYD_P2HKtnQkjibL8iy5ln62P1VIO9tT5epww,183 +fontTools/__main__.py,sha256=VjkGh1UD-i1zTDA1dXo1uecSs6PxHdGQ5vlCk_mCCYs,925 +fontTools/afmLib.py,sha256=1MagIItOzRV4vV5kKPxeDZbPJsfxLB3wdHLFkQvl0uk,13164 +fontTools/agl.py,sha256=05bm8Uq45uVWW8nPbP6xbNgmFyxQr8sWhYAiP0VSjnI,112975 +fontTools/annotations.py,sha256=BdIIriNYDzBfgniwWFg_u71qLZnV0sCcn4-VAkXkYNM,1225 +fontTools/cffLib/CFF2ToCFF.py,sha256=nc7eTW8NDMLHCQzpFMJKXJnDCD5NAwEeztHSHt_xES0,7424 +fontTools/cffLib/CFFToCFF2.py,sha256=Qnk7lYlsTRHnlZQ6NXNdr_f4MJwZQ21kcS08KFbsyY8,10119 +fontTools/cffLib/__init__.py,sha256=62vpcR7u8cE407kXduAwnFttHnsoCpDQ7IBK-qOYFQ8,107886 +fontTools/cffLib/specializer.py,sha256=vsOPkR_jHNe6tESQEjmm0i76y7sWI5MKo3bsTmI3sNM,32609 +fontTools/cffLib/transforms.py,sha256=SEIZc1XxWYiVXVBsoNm6LTvM9SUN7Z76QOaSAlR1ZCo,17455 +fontTools/cffLib/width.py,sha256=IqGL0CLyCZqi_hvsHySG08qpYxS3kaqW-tsAT-bjHV4,6074 +fontTools/colorLib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fontTools/colorLib/builder.py,sha256=kmO7OuudQQb3fEOS7aLzgTDVjqS9i2xIQmk9p1uBe8A,23008 +fontTools/colorLib/errors.py,sha256=CsaviiRxxrpgVX4blm7KCyK8553ljwL44xkJOeC5U7U,41 +fontTools/colorLib/geometry.py,sha256=3ScySrR2YDJa7d5K5_xM5Yt1-3NCV-ry8ikYA5VwVbI,5518 +fontTools/colorLib/table_builder.py,sha256=ZeltWY6n-YPiJv_hQ1iBXoEFAG70EKxZyScgsMKUFGU,7469 +fontTools/colorLib/unbuilder.py,sha256=iW-E5I39WsV82K3NgCO4Cjzwm1WqzGrtypHt8epwbHM,2142 +fontTools/config/__init__.py,sha256=JICOHIz06KuHCiBmrxj-ga19P6ZTuLXh0lHmPh-Ra1w,3154 +fontTools/cu2qu/__init__.py,sha256=Cuc7Uglb0nSgaraTxXY5J8bReznH5wApW0uakN7MycY,618 +fontTools/cu2qu/__main__.py,sha256=kTUI-jczsHeelULLlory74QEeFjZWp9zigCc7PrdVQY,92 +fontTools/cu2qu/benchmark.py,sha256=wasPJmf8q9k9UHjpHChC3WQAGbBAyHN9PvJzXvWC0Fw,1296 +fontTools/cu2qu/cli.py,sha256=MbAQnOpZwrUFe_tjAP3Tgf6uLdOgHlONUcPNeTXwH0Y,6076 +fontTools/cu2qu/cu2qu.c,sha256=-7JwWBSeJ3I4vIs6ZaSVHzfBf46MSx25lG05NRqA6Zg,637967 +fontTools/cu2qu/cu2qu.cpython-310-x86_64-linux-gnu.so,sha256=Lps_g6V3ZtfJOUq6HMhvgQFdaglxPWCwRZ2typB94sk,1032920 +fontTools/cu2qu/cu2qu.py,sha256=6LTe1ZI-jxW8y79s_UFjbkeFoFleIekTLm2jAE-uqGQ,17986 +fontTools/cu2qu/errors.py,sha256=PyJNMy8lHDtKpfFkc0nkM8F4jNLZAC4lPQCN1Km4bpg,2441 +fontTools/cu2qu/ufo.py,sha256=qZR70uWdCia19Ff8GLn5NeItscvvn69DegjDZVF4eNI,11794 +fontTools/designspaceLib/__init__.py,sha256=NGIC5zaq0NDdSkOyl6-i327cAzgCS3jeayEDvMEXRwY,129263 +fontTools/designspaceLib/__main__.py,sha256=xhtYXo1T1tsykhQDD0tcconSNYgWL5hoTBORpVDUYrc,103 +fontTools/designspaceLib/split.py,sha256=FB1NuvhUO453UXveQZi9oyrW_caoCPM3RADp1rYWkDs,19239 +fontTools/designspaceLib/statNames.py,sha256=gXGKWVr1ju2_oL-R_DkyoZ3GlI7mfLORovpk1Ebgmvc,9237 +fontTools/designspaceLib/types.py,sha256=ofK65qXNADqcpl7zI72Pa5s07-cm7G41iEmLVV44-Es,5320 +fontTools/encodings/MacRoman.py,sha256=4vEooUDm2gLCG8KIIDhRxm5-A64w7XrhP9cjDRr2Eo0,3576 +fontTools/encodings/StandardEncoding.py,sha256=Eo3AGE8FE_p-IVYYuV097KouSsF3UrXoRRN0XyvYbrs,3581 +fontTools/encodings/__init__.py,sha256=DJBWmoX_Haau7qlgmvWyfbhSzrX2qL636Rns7CG01pk,75 +fontTools/encodings/codecs.py,sha256=u50ruwz9fcRsrUrRGpR17Cr55Ovn1fvCHCKrElVumDE,4721 +fontTools/feaLib/__init__.py,sha256=jlIru2ghxvb1HhC5Je2BCXjFJmFQlYKpruorPoz3BvQ,213 +fontTools/feaLib/__main__.py,sha256=Df2PA6LXwna98lSXiL7R4as_ZEdWCIk3egSM5w7GpvM,2240 +fontTools/feaLib/ast.py,sha256=48Y6vpSD_wYfucWyh_bQtzf2AQFX-pOwBvsxdcpVDz0,74158 +fontTools/feaLib/builder.py,sha256=jIJVmaLwrNGFBO7mQDNpchiGBiv70nNpZ4LVRVaaIUM,73757 +fontTools/feaLib/error.py,sha256=Bz_5tNcNVcY7_nrAmFlQNhQldtqZWd8WUGQ2E3PWhZo,648 +fontTools/feaLib/lexer.c,sha256=UaY5Hy0WYsGF9UMJnA2tMx0k5DwYA72N2IKxpRsAcCc,754285 +fontTools/feaLib/lexer.cpython-310-x86_64-linux-gnu.so,sha256=vs8JAqS3qGNhzWJaAWJu6Ql1UEnVdDTA88S2GX6UunI,1401640 +fontTools/feaLib/lexer.py,sha256=emyMPmRoqNZkzxnJyI6JRCCtXrbCOFofwa9O6ABGLiw,11121 +fontTools/feaLib/location.py,sha256=JXzHqGV56EHdcq823AwA5oaK05hf_1ySWpScbo3zGC0,234 +fontTools/feaLib/lookupDebugInfo.py,sha256=gVRr5-APWfT_a5-25hRuawSVX8fEvXVsOSLWkH91T2w,304 +fontTools/feaLib/parser.py,sha256=E8Ey_Ft2TUbbleRJkCQ9Nmjn1VZ4SCt3UtLACcZqr2s,99716 +fontTools/feaLib/variableScalar.py,sha256=f6sOg9cfFJRI3fw04uRohDeFux0xnZanaPT_lcxAVOw,4200 +fontTools/fontBuilder.py,sha256=yF2-IYl_hao-Zy_FWSI4R-HnlFpzFrz0YBGQO8zfaOs,34130 +fontTools/help.py,sha256=bAjatvIhV7TJyXI7WhsxdYO4YVlhScZXu_kRtHANEPo,1125 +fontTools/merge/__init__.py,sha256=8i6ownyQTAOBKWnTEHvvCYFw64Mv7Z1HPBgJI-ZiuKo,8256 +fontTools/merge/__main__.py,sha256=hDx3gfbUBO83AJKumSEhiV-xqNTJNNgK2uFjazOGTmw,94 +fontTools/merge/base.py,sha256=l0G1Px98E9ZdVuFLMUBKWdtr7Jb8JX8vxcjeaDUUnzY,2389 +fontTools/merge/cmap.py,sha256=HpthxVH5lA7VegJ8yHoBjd9vrFBV7UB5OknKGYpxWY8,6728 +fontTools/merge/layout.py,sha256=fkMPGPLxEdxohS3scVM4W7LmNthSz-UPyocsffe2KqE,16075 +fontTools/merge/options.py,sha256=xko_1-WErcNQkirECzIOOYxSJR_bRtdQYQYOtmgccYI,2501 +fontTools/merge/tables.py,sha256=7SzXYL04awDEDhvU2-9T_8A2gAjvgGyYAHUICUJOpZg,10958 +fontTools/merge/unicode.py,sha256=kb1Jrfuoq1KUcVhhSKnflAED_wMZxXDjVwB-CI9k05Y,4273 +fontTools/merge/util.py,sha256=BH3bZWNFy-Tsj1cth7aSpGVJ18YXKXqDakPn6Wzku6U,3378 +fontTools/misc/__init__.py,sha256=DJBWmoX_Haau7qlgmvWyfbhSzrX2qL636Rns7CG01pk,75 +fontTools/misc/arrayTools.py,sha256=jZk__GE-K9VViZE_H-LPPj0smWbKng-yfPE8BfGp8HI,11483 +fontTools/misc/bezierTools.c,sha256=mFo2nrmrIq11WJ8Tj_cxR4M6U3tx75RVPcU-ODkHrbg,1821732 +fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so,sha256=R1k1rhbCbGMbQoY4Taqy5HzgK0E7yCXTii6JiM1_GYQ,4719904 +fontTools/misc/bezierTools.py,sha256=OmR3pzCGExNvZyTPrByH7gQHpAJsYOl1cmvfYQIVfQA,45038 +fontTools/misc/classifyTools.py,sha256=zcg3EM4GOerBW9c063ljaLllgeeZ772EpFZjp9CdgLI,5613 +fontTools/misc/cliTools.py,sha256=qCznJMLCQu3ZHQD_4ctUnr3TkfAUdkGl-UuxZUrppy0,1862 +fontTools/misc/configTools.py,sha256=YXBE_vL2dMWCnK4oY3vtU15B79q82DtKp7h7XRqJc1Q,11188 +fontTools/misc/cython.py,sha256=eyLcL2Bw-SSToYro8f44dkkYRlQfiFbhcza0afS-qHE,682 +fontTools/misc/dictTools.py,sha256=VxjarsGJuk_wa3z29FSCtKZNCFfXtMBiNEu0RPAlpDk,2417 +fontTools/misc/eexec.py,sha256=GNn2OCRvO1HbbIeDPxk9i0glO7cux_AQaoVMXhBR8y8,3331 +fontTools/misc/encodingTools.py,sha256=hCv5PFfnXQJVCZA8Wyn1vr3vzLBbUuEPtGk5CzWM9RY,2073 +fontTools/misc/enumTools.py,sha256=YQZW-d2ES9KFFkAXOUMIBbRUk6v_3BT6Q7lXE1ufhxA,502 +fontTools/misc/etree.py,sha256=ZzJc6TvAS579deAgZLVDvTY_HeTm-ZsKJ5s3LYhZSSY,16304 +fontTools/misc/filenames.py,sha256=MMCO3xjk1pcDc-baobcKd8IdoFPt-bcGqu8t8HUGAkI,8223 +fontTools/misc/filesystem/__init__.py,sha256=iwoOj6DpXKk8q-NRRHqOfRxFF6lcXIhsIA46j-cZswU,2011 +fontTools/misc/filesystem/_base.py,sha256=p74O7xREadfPQgzPJ9mP3ehu0ZHDgsmXlpsL9CnTRso,4010 +fontTools/misc/filesystem/_copy.py,sha256=ifMSs-A_bz1Aa4tIQrlUd9HtdJQ5fp5M3B6mbYuDtXI,1361 +fontTools/misc/filesystem/_errors.py,sha256=-YziRB1BT1I80ypmufvCR-M_4XoerCHyBVqX-cRnIzU,641 +fontTools/misc/filesystem/_info.py,sha256=pbV7bDTJ5F8ms6alK34J0FZYWzmRO7FT0NM3yRA3czo,2013 +fontTools/misc/filesystem/_osfs.py,sha256=RkKCE2IxcRaj7gyqFW10LhEm_-VJYtXxsS5s0DCXihM,5737 +fontTools/misc/filesystem/_path.py,sha256=frP6ZLmMeP9E3NiwoCbbgBPWpQbLBRh7T-0vOE-EuPo,1745 +fontTools/misc/filesystem/_subfs.py,sha256=vRotQwyLVfINbR88xIBQUbq9j4Kmg1_mJvEhnpvK_t4,3028 +fontTools/misc/filesystem/_tempfs.py,sha256=9FUXdCBTwFtZMFx8ghYuZVYoQdDb0tDB-jXNu3D-Qy0,924 +fontTools/misc/filesystem/_tools.py,sha256=r75dpadp7C9EdQ6r7pJQKZlCZDUJzVq2ikb_LXN-wCI,972 +fontTools/misc/filesystem/_walk.py,sha256=KMQ-GavWYr4SsA5V8ohLPmz3boilvY2P0JKrLoxW6NU,1655 +fontTools/misc/filesystem/_zipfs.py,sha256=i3qolbkDRntB_oL3v79KuEgfVlVojecPBnBA0X04PWc,6301 +fontTools/misc/fixedTools.py,sha256=gsotTCOJLyMis13M4_jQJ8-QPob2Gl2TtNJhW6FER1I,7647 +fontTools/misc/intTools.py,sha256=l6pjk4UYlXcyLtfC0DdOC5RL6UJ8ihRR0zRiYow5xA8,586 +fontTools/misc/iterTools.py,sha256=17H6LPZszp32bTKoNorp6uZF1PKj47BAbe5QG8irUjo,390 +fontTools/misc/lazyTools.py,sha256=BC6MmF-OzJ3GrBD8TYDZ-VCSN4UOx0pN0r3oF4GSoiw,1020 +fontTools/misc/loggingTools.py,sha256=NOYROsLK5TzONK5967OGdVonNyXC6kP_CmPr7M2PW_c,19933 +fontTools/misc/macCreatorType.py,sha256=Je9jtqUr7EPbpH3QxlVl3pizoQ-1AOPMBIctHIMTM3k,1593 +fontTools/misc/macRes.py,sha256=GT_pnfPw2NCvvOF86nHLAnOtZ6SMHqEuLntaplXzvHM,8579 +fontTools/misc/plistlib/__init__.py,sha256=1HfhHPt3As6u2eRSlFfl6XdnXv_ypQImeQdWIw6wK7Y,21113 +fontTools/misc/plistlib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fontTools/misc/psCharStrings.py,sha256=Zn8mr7NRTfEJbnaXbOnSarrFBPcvPM0AupAxF2C80LY,43468 +fontTools/misc/psLib.py,sha256=ioIPm5x3MHkBXF2vzNkC4iVZYobrkWcyvFhmYsjOrPY,12099 +fontTools/misc/psOperators.py,sha256=9SLl5PPBulLo0Xxg_dqlJMitNIBdiGKdkXhOWsNSYZE,15700 +fontTools/misc/py23.py,sha256=aPVCEUz_deggwLBCeTSsccX6QgJavZqvdVtuhpzrPvA,2238 +fontTools/misc/roundTools.py,sha256=1RSXZ0gyi1qW42tz6WSBMJD1FlPdtgqKfWixVN9bd78,3173 +fontTools/misc/sstruct.py,sha256=vUODd2CKvHLtjr7yn1K94Hui_yxOPWKmlgAmBMm3KDQ,7009 +fontTools/misc/symfont.py,sha256=x5ZwqK9Ik9orG6qSftgVGygBFE1wTSngrMK2We1Z5AM,6977 +fontTools/misc/testTools.py,sha256=3vj_KllUQVEiVFbS0SzTmeuKv44-L-disI1dZ4XhOfw,7052 +fontTools/misc/textTools.py,sha256=wNjH5zl1v9qNfmTl4BL52IO2IG1H5xY3o_pslqPPRjc,3483 +fontTools/misc/timeTools.py,sha256=e9h5pgzL04tBDXmCv_8eRGB4boFV8GKXlS6dq3ggEpw,2234 +fontTools/misc/transform.py,sha256=OR8dPsAw87z77gkZQMq00iUkDWLIxYv-12XiKH1-erk,15798 +fontTools/misc/treeTools.py,sha256=tLWkwyDHeZUPVOGNnJeD4Pn7x2bQeZetwJKaEAW2J2M,1269 +fontTools/misc/vector.py,sha256=6lqZcDjAgHJFQgjzD-ULQ_PrigAMfeZKaBZmAfcC0ig,4062 +fontTools/misc/visitor.py,sha256=zwBAVfZ3MTsrbhNFj03pSSjNRyT6oGkare-kfWkN5ns,5754 +fontTools/misc/xmlReader.py,sha256=igut4_d13RT4WarliqVvuuPybO1uSXVeoBOeW4j0_e4,6580 +fontTools/misc/xmlWriter.py,sha256=CrNXQfNJRdt5CHKAZ4-qy3h1yJeL63ot17kXkNbeI_E,6829 +fontTools/mtiLib/__init__.py,sha256=EzYwNaENLf906h1THBeq6nSRHUKpOAYxuzO9x9PHzh8,46602 +fontTools/mtiLib/__main__.py,sha256=gd8X89jnZOe-752k7uaR1lWoiju-2zIT5Yx35Kl0Xek,94 +fontTools/otlLib/__init__.py,sha256=D2leUW-3gsUTOFcJYGC18edBYjIJ804ut4qitJYWsaQ,45 +fontTools/otlLib/builder.py,sha256=MHuQKul3Nl3vzXmY7Wb6x54ZNbJGUzRUD7-VKpOG7lE,128727 +fontTools/otlLib/error.py,sha256=cthuhBuOwZYpkTLi5gFPupUxkXkCHe-L_YgkE7N1wCI,335 +fontTools/otlLib/maxContextCalc.py,sha256=3es4Kt84TaZ49sA2ev1zrlwPJikJCAECx5KavwhyB-I,3175 +fontTools/otlLib/optimize/__init__.py,sha256=UUQRpNkHU2RczCRt-Gz7sEiYE9AQq9BHLXZEOyvsnX4,1530 +fontTools/otlLib/optimize/__main__.py,sha256=BvP472kA9KxBb9RMyyehPNevAfpmgW9MfdazkUiAO3M,104 +fontTools/otlLib/optimize/gpos.py,sha256=htOgSP743DZDUKF3eWAeJ-kdqNYOnpGXdlV-rbEXJ1A,17668 +fontTools/pens/__init__.py,sha256=DJBWmoX_Haau7qlgmvWyfbhSzrX2qL636Rns7CG01pk,75 +fontTools/pens/areaPen.py,sha256=Y1WkmqzcC4z_bpGAR0IZUKrtHFtxKUQBmr5-64_zCOk,1472 +fontTools/pens/basePen.py,sha256=eIGSKrKm6w4LLHuG6XJoQZ3eObtoKV5P6aF4gT4sk7U,17073 +fontTools/pens/boundsPen.py,sha256=wE3owOQA8DfhH-zBGC3lJvnVwp-oyIt0KZrEqXbmS9I,3129 +fontTools/pens/cairoPen.py,sha256=wuuOJ1qQDSt_K3zscM2nukRyHZTZMwMzzCXCirfq_qQ,592 +fontTools/pens/cocoaPen.py,sha256=IJRQcAxRuVOTQ90bB_Bgjnmz7px_ST5uLF9CW-Y0KPY,612 +fontTools/pens/cu2quPen.py,sha256=gMUwFUsm_-WzBlDjTMQiNnEuI2heomGeOJBX81zYXPo,13007 +fontTools/pens/explicitClosingLinePen.py,sha256=kKKtdZiwaf8Cj4_ytrIDdGB2GMpPPDXm5Nwbw5WDgwU,3219 +fontTools/pens/filterPen.py,sha256=REgspXaaSvF3XUwqe40abe3X_E7-WbBP13IqLUUBLCw,14703 +fontTools/pens/freetypePen.py,sha256=HD-gXJSbgImJdBc8sIBk0HWBdjv3WKFofs6PgCCsGOY,19908 +fontTools/pens/hashPointPen.py,sha256=gElrFyQoOQp3ZbpKHRWPwC61A9OgT2Js8crVUD8BQAY,3573 +fontTools/pens/momentsPen.c,sha256=nXlaxy9cejy1MWW6NCDck71BKCfnc_E25BrmYXXPC18,565310 +fontTools/pens/momentsPen.cpython-310-x86_64-linux-gnu.so,sha256=WjjjE3iugVD9FbhCHbiJaMtDQsw_Yv7R_roN6jSRC2k,916480 +fontTools/pens/momentsPen.py,sha256=kjLVXhGe55Abl__Yr1gob0bl0dHe7fPSwyr7TRJnbug,25658 +fontTools/pens/perimeterPen.py,sha256=lr6NzrIWxi4TXBJPbcJsKzqABWfQeil2Bgm9BgUD3N4,2153 +fontTools/pens/pointInsidePen.py,sha256=noEUvBQIeAheDMJwzvvfnEiKhmwbS1i0RQE9jik6Gl4,6355 +fontTools/pens/pointPen.py,sha256=oeE_uabVCNJ1Lpk5Hn3eBmafaao3QqKMjK6FAy0hKBo,24197 +fontTools/pens/qtPen.py,sha256=QRNLIry2rQl4E_7ct2tu10-qLHneQp0XV7FfaZ-tcL8,634 +fontTools/pens/qu2cuPen.py,sha256=pRST43-rUpzlOP83Z_Rr0IvIQBCx6RWI6nnNaitQcLk,3985 +fontTools/pens/quartzPen.py,sha256=EH482Kz_xsqYhVRovv6N_T1CXaSvOzUKPLxTaN956tU,1287 +fontTools/pens/recordingPen.py,sha256=VgFZ4NMhnZt1qSTzFEU0cma-gw3kBe47bfSxPYH73rs,12489 +fontTools/pens/reportLabPen.py,sha256=kpfMfOLXt2vOQ5smPsU82ft80FpCPWJzQLl7ENOH8Ew,2066 +fontTools/pens/reverseContourPen.py,sha256=oz64ZRhLAvT7DYMAwGKoLzZXQK8l81jRiYnTZkW6a-Y,4022 +fontTools/pens/roundingPen.py,sha256=vh_FjikRd82-S4I8glgGMGEuGrj5IkCjRT_wmZ8jfqY,4620 +fontTools/pens/statisticsPen.py,sha256=piWK6NjjWqk9MLROjeE2-4EsxVYMyNU7UQFGD_trE9g,9808 +fontTools/pens/svgPathPen.py,sha256=T3b6SZS9B9sVWMK9mSFDtjHeviQs_yOJOZKq5Sg5Zdg,8572 +fontTools/pens/t2CharStringPen.py,sha256=GgGklb5XsCer0w37ujgRLRXx-EuzdFsyCYuzCx4n-Qs,2931 +fontTools/pens/teePen.py,sha256=P1ARJOCMJ6MxK-PB1yZ-ips3CUfnadWYnQ_do6VIasQ,1290 +fontTools/pens/transformPen.py,sha256=s0kUyQdnemUwHvYr2SFboFmh4WY1S9OHBL8L4PJKRwE,4056 +fontTools/pens/ttGlyphPen.py,sha256=yLtB-E5pTQR59OKVYySttWBu1xC2vR8ezSaRhIMtVwg,11870 +fontTools/pens/wxPen.py,sha256=W9RRHlBWHp-CVC4Exvk3ytBmRaB4-LgJPP5Bv7o9BA0,680 +fontTools/qu2cu/__init__.py,sha256=Jfm1JljXbt91w4gyvZn6jzEmVnhRx50sh2fDongrOsE,618 +fontTools/qu2cu/__main__.py,sha256=9FWf6SIZaRaC8SiL0LhjAWC2yIdY9N_9wlRko8m1l2Q,93 +fontTools/qu2cu/benchmark.py,sha256=GMcr_4r7L6K9SmJ13itt-_XKhnKqSVUDPlXUG6IZmmM,1400 +fontTools/qu2cu/cli.py,sha256=U2rooYnVVEalGRAWGFHk-Kp6Okys8wtzdaWLjw1bngY,3714 +fontTools/qu2cu/qu2cu.c,sha256=k-6C2e2_m_1cBuYoSiHCY1ZBcSqtZjiffLCghiJCYDM,690421 +fontTools/qu2cu/qu2cu.cpython-310-x86_64-linux-gnu.so,sha256=eEL8aLCm-rF7vWJipECNKlQfIJJEu_DPYY0U4Ho0mQw,1120824 +fontTools/qu2cu/qu2cu.py,sha256=IYtpkwHdfKOXJr65Y_pJ9Lrt_MgJaISAKGMAs5ilFSM,12288 +fontTools/subset/__init__.py,sha256=R9VoZ2QWhqENHC5Ct1wyhLhEU-xo4mUXwCWl6EZGgwQ,143263 +fontTools/subset/__main__.py,sha256=bhtfP2SqP4k799pxtksFgnC-XGNQDr3LcO4lc8T5e5g,95 +fontTools/subset/cff.py,sha256=rqMRJOlX5FacV1LW8aDlVOglgEM87TkMA9bdsYenask,6145 +fontTools/subset/svg.py,sha256=8dLBzQlnIt4_fOKEFDAVlKTucdHvcbCcyG9-a6UBZZ0,9384 +fontTools/subset/util.py,sha256=9SXFYb5Ef9Z58uXmYPCQil8B2i3Q7aFB_1fFDFSppdU,754 +fontTools/svgLib/__init__.py,sha256=IGCLwSbU8jLhq6HI2vSdPQgNs6zDUi5774TgX5MCXPY,75 +fontTools/svgLib/path/__init__.py,sha256=C82fh7xH6ZHsSFVnV848-xeDezpokx1EwTmayJCouFU,1996 +fontTools/svgLib/path/arc.py,sha256=-f5Ym6q4tDWQ76sMNSTUTWgL_7AfgXojvBhtBS7bWwQ,5812 +fontTools/svgLib/path/parser.py,sha256=8T6okMstvgM9ufb2zBcwSzsuuoYbqfnUjNYgb6kjznU,10788 +fontTools/svgLib/path/shapes.py,sha256=xvBUIckKyT9JLy7q_ZP50r6TjvZANyHdZP7wFDzErcI,5322 +fontTools/t1Lib/__init__.py,sha256=p42y70wEIbuX0IIxZG7-b_I-gHto1VLy0gLsDvxCfkw,20865 +fontTools/tfmLib.py,sha256=UMbkM73JXRJVS9t2B-BJc13rSjImaWBuzCoehLwHFhs,14270 +fontTools/ttLib/__init__.py,sha256=1k7qp9z04gA3m6GvxDaINjqrKbzOkdTA_4RnqW_-LrA,661 +fontTools/ttLib/__main__.py,sha256=lHMPWsnzjKPuMFavf6i1gpk9KexiAk4qzgDd50Mbby0,4733 +fontTools/ttLib/macUtils.py,sha256=lj3oeFpyjV7ko_JqnluneITmAtlc119J-vwTTg2s73A,1737 +fontTools/ttLib/removeOverlaps.py,sha256=YBtj1PX-d2jMgCiWGuI6ibghWApUWqH2trJGXNxrbjQ,12612 +fontTools/ttLib/reorderGlyphs.py,sha256=TbxLxqPTUGiKRX3ulGFCwVm2lEisFYlX6caONJr_4oY,10371 +fontTools/ttLib/scaleUpem.py,sha256=U_-NGkwfS9GRIackdEXjGYZ-wSomcUPXQahDneLeArI,14618 +fontTools/ttLib/sfnt.py,sha256=wemkfz93dlAoyo-VVzmg5OLoSSyMFQNzBTTP3Kem-xk,22792 +fontTools/ttLib/standardGlyphOrder.py,sha256=7AY_fVWdtwZ4iv5uWdyKAUcbEQiSDt1lN4sqx9xXwE0,5785 +fontTools/ttLib/tables/B_A_S_E_.py,sha256=H71A9pJ850mvjbrWHqy8iFI2Dxg7102YRtAkfdCooig,369 +fontTools/ttLib/tables/BitmapGlyphMetrics.py,sha256=9gcGPVzsxEYnVBO7YLWfeOuht9PaCl09GmbAqDYqKi0,1769 +fontTools/ttLib/tables/C_B_D_T_.py,sha256=5LNdc8FMir1kC5fvp5iHwWfeuE-RuqdxAArFXaqPjQ0,3646 +fontTools/ttLib/tables/C_B_L_C_.py,sha256=YXlwovoCHYx8THLQD9iBU_VGoaB9LFObEKtL6ddD320,520 +fontTools/ttLib/tables/C_F_F_.py,sha256=yg3mUtYBudgmpG7Bz475j_DNnCelsgrTsM8DH1uR4ek,1978 +fontTools/ttLib/tables/C_F_F__2.py,sha256=YoHfJQdF-ezx4OwRQ2Y2O7rRJEPjOkf3Hx5Y11Xq0AM,807 +fontTools/ttLib/tables/C_O_L_R_.py,sha256=SHwFVNVmoUQR2e87KuTSe-J9LfeegS4f2hEpee29_2o,5993 +fontTools/ttLib/tables/C_P_A_L_.py,sha256=odFjqM4GnjXyQYGEC-e0Gvqms1jQ5zHHG3SDg7y-BI0,11942 +fontTools/ttLib/tables/D_S_I_G_.py,sha256=AgQPM9Cdro1P-ehJjTfsC9mRTTtSc16At0nnpb1XOGI,5517 +fontTools/ttLib/tables/D__e_b_g.py,sha256=KDnfkNOUnm3F13wD_j3YNBOvYadZ40Gf_0170hFkJp0,1134 +fontTools/ttLib/tables/DefaultTable.py,sha256=cOtgkLWPY9qmOH2BSPt4c4IUSdANWTKx2rK1CTxQ4h0,1487 +fontTools/ttLib/tables/E_B_D_T_.py,sha256=uOpmt25gOJQeO1u1IGAyPWgVmh-4vSZqrQEHvOYwbwg,32534 +fontTools/ttLib/tables/E_B_L_C_.py,sha256=LfEVzBg_yWr9dhChzS0U2G-7wNOwzwB0LWoXIUYNKKM,30054 +fontTools/ttLib/tables/F_F_T_M_.py,sha256=_450vdbEH7Y-0_rOwb3Q0hg-Qq2W8C_sHljy7rZtqqM,1683 +fontTools/ttLib/tables/F__e_a_t.py,sha256=ct79Gf__5ALlqfSBn6wvw6fazb31Od71R6vIp6o9XF4,5483 +fontTools/ttLib/tables/G_D_E_F_.py,sha256=QXiILFCRnPNZcwpub6ojN5S9WP6y56LsXi25pUWLgp4,299 +fontTools/ttLib/tables/G_M_A_P_.py,sha256=fvIQumokOCLa8DFeq_xi069F9RROsXSVmDvWtxgyacQ,4720 +fontTools/ttLib/tables/G_P_K_G_.py,sha256=Xi4Hj2OxZ2IZgVyBQ-Qyiie0hPZjpXZkrao-E5EdTWM,4646 +fontTools/ttLib/tables/G_P_O_S_.py,sha256=UkP3mlnyvQg-jj6ZBOh6j-OieVg_goJQ31nlLvoLGSI,397 +fontTools/ttLib/tables/G_S_U_B_.py,sha256=cwFMKO-pgwsn1H8Q9Jb58Z6ZrBrCoN0sqJB0YunBfSk,294 +fontTools/ttLib/tables/G_V_A_R_.py,sha256=13oO2dD-L4yfkrBuR-KN2rc40wh5lLIlx_khwMz5GH4,94 +fontTools/ttLib/tables/G__l_a_t.py,sha256=Xh3IzFgYlvNjrAOn7Ja73DrWrQTJgJxmDFSUKS6yHdM,8645 +fontTools/ttLib/tables/G__l_o_c.py,sha256=5DsxGzaG7HyJVvLlKQeff1lXt-XPWaHNNaf-EYwsKh4,2685 +fontTools/ttLib/tables/H_V_A_R_.py,sha256=6kPLDUGT8EussA3y9gKr_mrgY5PNv7YaK1V0keMXD9w,313 +fontTools/ttLib/tables/J_S_T_F_.py,sha256=Q9TEf3OuyDIxZlmoz9a3c-mDMlJK6YBQ9KcYmiwFRbU,315 +fontTools/ttLib/tables/L_T_S_H_.py,sha256=Iu6syJFuhJj0_7Aan2NPlDuQDIq-AzLwsOQbXVTnlL0,2189 +fontTools/ttLib/tables/M_A_T_H_.py,sha256=-TVu9Nlcs-1shkElbIk-CWtUwXUMdycHFkjvPE8C_fs,342 +fontTools/ttLib/tables/M_E_T_A_.py,sha256=sA6ookcjchw8UYVEuS8QEXc62I9_Rms9cu_jKA6MkNI,11989 +fontTools/ttLib/tables/M_V_A_R_.py,sha256=67cEuiTw5y5W1Zk98L_S_SmJINIfy_mzWCkyHcujz94,308 +fontTools/ttLib/tables/O_S_2f_2.py,sha256=1Pq2Xu4oYOJePTHC_hTKg3RIfKely3j6T1u_lMTEpD8,28030 +fontTools/ttLib/tables/S_I_N_G_.py,sha256=CFDy8R2fDeYn7ocfrZr7Ui7U9D0h4G55CdPfY55g-Bk,3317 +fontTools/ttLib/tables/S_T_A_T_.py,sha256=y9NiWCtnlZtMjw4K9_SdA84Xa-dJk7G5eb2dSe6ciWc,498 +fontTools/ttLib/tables/S_V_G_.py,sha256=vT6QTW5ArtskVUxnPEH_ZxKz4DF4v1pKbylN6DG0R3o,7676 +fontTools/ttLib/tables/S__i_l_f.py,sha256=lPQV2RdhcJRgfDzHp_dkgSxVUUdkcAnY1Bz7V18Gt9U,34985 +fontTools/ttLib/tables/S__i_l_l.py,sha256=Vjtn7SI83vaLGIuQf2e-jhZSFOXb9vXB4jwqznjqnMc,3224 +fontTools/ttLib/tables/T_S_I_B_.py,sha256=3WhEtyNnjYumcowD0GpjubrgnS-RzouZxCxEe4yLDo8,341 +fontTools/ttLib/tables/T_S_I_C_.py,sha256=hAV9Hq_ALsWaducDpw1tDRREvFL7hx7onnUF0sXTelU,381 +fontTools/ttLib/tables/T_S_I_D_.py,sha256=TsdX-G2xxVQO9sSE1wE_xDRx-gor5YiXTHeUthMwCPY,341 +fontTools/ttLib/tables/T_S_I_J_.py,sha256=x8Tlvi6aTxoQcI12UL7muoWF1Q61iBDseAS1mRdOYrg,341 +fontTools/ttLib/tables/T_S_I_P_.py,sha256=-il2ucTBOghVBY7cmleHdLZc3W3CKh7-iPPT0A3KBzk,341 +fontTools/ttLib/tables/T_S_I_S_.py,sha256=tVBnl63vyZUIq93oM6dEjHCXvPn9vt5vvL3jG59b0Lg,341 +fontTools/ttLib/tables/T_S_I_V_.py,sha256=iUWxz2MSrtw7mzuQZj30QAJrCPnyJ4GincFfySFUNAg,855 +fontTools/ttLib/tables/T_S_I__0.py,sha256=O-2oI0eBgt4mP15-UwH0_0r7YWi3EEEhG-4etqDueGI,2505 +fontTools/ttLib/tables/T_S_I__1.py,sha256=nSUhni-fvYmeKXW4zLfP3FG_3LQU2QKPKS1_gKY5lYg,6971 +fontTools/ttLib/tables/T_S_I__2.py,sha256=q2rub-d77iWWiBM6awO0-TCl-Xq7kalPobHYC2QEOfc,496 +fontTools/ttLib/tables/T_S_I__3.py,sha256=0LcvvCzVZJzyz7i4zjIkUuYXEqXwOCs9WeCsgDFqKJ8,543 +fontTools/ttLib/tables/T_S_I__5.py,sha256=hhvJn6jiXs8kuBtun8krNUTXTljH-eKxaxXM1T-7SXM,1905 +fontTools/ttLib/tables/T_T_F_A_.py,sha256=LuT0w__AMtawnsBMobhEMW9gp2yk0mA5ZRzwF45c0UI,392 +fontTools/ttLib/tables/TupleVariation.py,sha256=4XTDTRPZWPg9_1K5SVgdNoxtgQvahtiO4LNO7fk1cK4,32235 +fontTools/ttLib/tables/V_A_R_C_.py,sha256=3jFX50J6X-Cc4dwwiztKKsDTRXVHTXlVdQH328UN1-k,289 +fontTools/ttLib/tables/V_D_M_X_.py,sha256=RbHl7vvO9pcjT_kKvcCmcByQj39n4PmVeq55wD5C14g,10437 +fontTools/ttLib/tables/V_O_R_G_.py,sha256=Cn3OxjVtcO-Uvp61P5c2336V9iEbuGr6vWAXnSIaihk,5965 +fontTools/ttLib/tables/V_V_A_R_.py,sha256=Cstw6tc_U4-EmTriRItBSpvTJODAjMFQjfyTaxLzsbI,319 +fontTools/ttLib/tables/__init__.py,sha256=eQPcuHCfRuGtt6nOa0KwV6vtUNKHnwuQyA7xSN8SPoc,2651 +fontTools/ttLib/tables/_a_n_k_r.py,sha256=MpAzIifmIi_3gx2oP6PC3R2lu36Ewsr2-W1rXjsz2Ug,483 +fontTools/ttLib/tables/_a_v_a_r.py,sha256=YodAzCsIywAKV48P4jQSrrUnYYWWuY6SDnNURAbM6fU,7175 +fontTools/ttLib/tables/_b_s_l_n.py,sha256=_848o7SQqztzBDfHYei-80u9ltxIHVBzXu1dYHLV57M,465 +fontTools/ttLib/tables/_c_i_d_g.py,sha256=yt8rVIadpJSDUCoVH4dZetNiy0Azm5ESAxHjB2BX_eA,913 +fontTools/ttLib/tables/_c_m_a_p.py,sha256=r8-bB_E0EQh5h4TGX5nTnDnwTUtXuRB3iuqEDoN_IOM,62202 +fontTools/ttLib/tables/_c_v_a_r.py,sha256=35ayk2kX1pcLGwyx0y4I1l-r7LHgdKv0ulVx8oBPteI,3527 +fontTools/ttLib/tables/_c_v_t.py,sha256=1_RhEcTmhWQWQp7Hsj8UsByKmXCIppZyIbIArGywEEM,1618 +fontTools/ttLib/tables/_f_e_a_t.py,sha256=Fi1XnjhkCG0tp43AcvpIaivD-YRFpufo6feGIrenQDo,469 +fontTools/ttLib/tables/_f_p_g_m.py,sha256=uZHZzqL6OdLn_Hxskv-xf3XuE4fyaSv_jbALEjwXYug,1633 +fontTools/ttLib/tables/_f_v_a_r.py,sha256=rV33H2BgHUl3Wuydsou1G-Hi4uASBppWaLj3FMmiLjs,8837 +fontTools/ttLib/tables/_g_a_s_p.py,sha256=YvhAVDvdssN2fjPMTfSrO4WBCfTuh9T2cU5zquDVnSw,2203 +fontTools/ttLib/tables/_g_c_i_d.py,sha256=AJ4uV7PTHbnsw4Tfw8c2Ezh0VMox3oAH0qhhq7y8hdM,362 +fontTools/ttLib/tables/_g_l_y_f.py,sha256=dDV65llsEDI9fKcVKC5TOiaXpXSyMHNEytuYOGt7adM,85584 +fontTools/ttLib/tables/_g_v_a_r.py,sha256=E9WCKjeITUfd5hcJLQ0rjQFBtZdxw1eswFlWp1U6bD4,12196 +fontTools/ttLib/tables/_h_d_m_x.py,sha256=wMrO4D04QNT8u30p8AV-aG3bndXCq4wlPNvtbd8ip7c,4252 +fontTools/ttLib/tables/_h_e_a_d.py,sha256=yY2GTFq6Mn6nN8EegbMVJRMUWIqDYFln3FhTk3ziw6s,4926 +fontTools/ttLib/tables/_h_h_e_a.py,sha256=X4t1aF1MZMuz3phCVSFwKcNTeoZdx-042wFtHc-nK9w,4767 +fontTools/ttLib/tables/_h_m_t_x.py,sha256=rbxr3cy9-9Jm0HCGIWQiX6fGH5iu6yojp9kfgWrW2Ks,6192 +fontTools/ttLib/tables/_k_e_r_n.py,sha256=DQNLmD_HEdDKPfp4tamOd9W3T5a1lXFM5tDaWrKl164,10794 +fontTools/ttLib/tables/_l_c_a_r.py,sha256=8W6xFOj-sm003MCXX4bIHxs9ntfVvT0FXYllPxa3z4I,390 +fontTools/ttLib/tables/_l_o_c_a.py,sha256=yxiwLKXLZjNju5XYmLb6EhNLec1d7ezEDDe1dszceHo,2180 +fontTools/ttLib/tables/_l_t_a_g.py,sha256=9YpApjI-rZ4e3HeT8Pj-osiHl3uALD9JXg5O7pqk9L0,2552 +fontTools/ttLib/tables/_m_a_x_p.py,sha256=cIDIZWse9czwwsnlxIh3qwgwaXbt7PQAjXKAcmMDspY,5264 +fontTools/ttLib/tables/_m_e_t_a.py,sha256=A0CZPEAVxYrpytjXUGQJCTddwG8KrvUVbtBe3A1MqgI,3913 +fontTools/ttLib/tables/_m_o_r_t.py,sha256=u35tYqn3cjzKxeCF0FUFeLtaf36mjDDSN08uuk0Kme8,487 +fontTools/ttLib/tables/_m_o_r_x.py,sha256=OwamVpIO7REDnFr95HuFPoY_0U6i9zQPb11K1sFTvDY,548 +fontTools/ttLib/tables/_n_a_m_e.py,sha256=86_0fUeA5_c-GY5ZnkqUI0jyWwMh1mn6yVOf6KKqIlU,41266 +fontTools/ttLib/tables/_o_p_b_d.py,sha256=TNZv_2YTrj4dGzd6wA9Jb-KGZ99un177s5p3LlfxQ74,448 +fontTools/ttLib/tables/_p_o_s_t.py,sha256=9siVXSisWGdTfj_mC1E9dUDz9Jdm1i3QzI-l3i3VWME,11671 +fontTools/ttLib/tables/_p_r_e_p.py,sha256=CcKr4HrswkupLmbJdrJLTM-z9XgLefQyv8467j9V0zs,427 +fontTools/ttLib/tables/_p_r_o_p.py,sha256=Eg8x5qWyXDzPezMafFu0s0qyPDHj-sPsFxGtE6h29qo,427 +fontTools/ttLib/tables/_s_b_i_x.py,sha256=tkkKbNKNYkUhZJuN0kl7q37x5KK5OovB06y28obPV6A,4865 +fontTools/ttLib/tables/_t_r_a_k.py,sha256=rrrPZLELFYA5F8PERoafIS9cb_d_i6xtpAzHEbsFHSw,11379 +fontTools/ttLib/tables/_v_h_e_a.py,sha256=FuULIBl4OQyUeLPOFEY8buB0pAnQhGa1-5a6kN9i5Sc,4459 +fontTools/ttLib/tables/_v_m_t_x.py,sha256=AUuxtyQvMWrTBNbOIaL6uKcB_DNpNb0YX28JIuTHw_Y,500 +fontTools/ttLib/tables/asciiTable.py,sha256=4c69jsAirUnDEpylf9CYBoCKTzwbmfbtUAOrtPnpHjY,637 +fontTools/ttLib/tables/grUtils.py,sha256=hcOJ5oJPOd2uJWnWA7qwR7AfL37YZ5zUT7g8o5BBV80,2270 +fontTools/ttLib/tables/otBase.py,sha256=cHdoYX-ICa8GeI-tVhFy1K9-CHaExiKO-HBjmH0OkbU,53330 +fontTools/ttLib/tables/otConverters.py,sha256=ihE_WMSKAKSaBbMvnFYDj2eMxf7PvRMMa8zGwfoYuYc,74202 +fontTools/ttLib/tables/otData.py,sha256=-XXRwdVfP-Wz7oBjMPpku0A0QH9lw_fFGNzZlt9N0mo,197262 +fontTools/ttLib/tables/otTables.py,sha256=2U04ot_2ITlBZx2QtpnIOtBGftPFs9ZX2FWfz4vz1G0,96987 +fontTools/ttLib/tables/otTraverse.py,sha256=HznEVAlVf_8eyqjsO2edgELtMlXnjnUqccK3PytvVUE,5518 +fontTools/ttLib/tables/sbixGlyph.py,sha256=tjEUPVRfx6gr5yme8UytGTtVrimKN5qmbzT1GZPjXiM,5796 +fontTools/ttLib/tables/sbixStrike.py,sha256=dL8O9K8R4S6RVQDP-PVjIPBrvbqbE9zwra0uRL0nLq0,6651 +fontTools/ttLib/tables/table_API_readme.txt,sha256=eZlRTLUkLzc_9Ot3pdfhyMb3ahU0_Iipx0vSbzOVGy8,2748 +fontTools/ttLib/tables/ttProgram.py,sha256=tgtxgd-EnOq-2PUlYEihp-6NHu_7HnE5rxeSAtmXOtU,35888 +fontTools/ttLib/ttCollection.py,sha256=aRph2MkBK3kd9-JCLqhJ1EN9pffN_lVX6WWmOTTewc8,3963 +fontTools/ttLib/ttFont.py,sha256=8I79ksIdtfMf8GV_nhawEhlzOvQMTyB98lrWzoJADh0,40669 +fontTools/ttLib/ttGlyphSet.py,sha256=cUBhMGa5hszeVqOm2KpOdeJh-LsiqE7RNdyIUPZ2vO8,17476 +fontTools/ttLib/ttVisitor.py,sha256=_tah4C42Tv6Pm9QeLNQwwVCxqI4VNEAqYCbmThp6cvY,1025 +fontTools/ttLib/woff2.py,sha256=6LPISeBQ1dubzKjWrUcYm_vgETC46BTLY4XkG52qvSA,60921 +fontTools/ttx.py,sha256=FxuGubujWCGJWSTrJEjoNH--25fVIPy-ZRtYy9H6iTk,17277 +fontTools/ufoLib/__init__.py,sha256=nKG8gu6NEvqGJoZ781IARoQ7ii4LoWfMMvX3Yf5TsVw,98981 +fontTools/ufoLib/converters.py,sha256=YnBKr8kmyjwLcq8LdD46ubGOgyL9Pxt9avlvZn9anKI,13444 +fontTools/ufoLib/errors.py,sha256=9f8l5NaFAj3BZPa6Bbqt06FL4afffLuMzy4nPf-eOlE,845 +fontTools/ufoLib/etree.py,sha256=T3sjLTgjMAq6VyYRicWPaMIVBJ2YSuwZxV6Vc5yZtQI,231 +fontTools/ufoLib/filenames.py,sha256=hoyUhzzQMDaeckT7UdreISANq4-gLR2jGyk5yAyYtOA,10654 +fontTools/ufoLib/glifLib.py,sha256=Y-xzf4qbTIOl3-dVLXvu3iFCIDtAEu_klId2_UNngWs,77170 +fontTools/ufoLib/kerning.py,sha256=o1BeJDVZ_CZZPzmOPwRKTqglYmhA_JZPjwq2JLgdQIk,4836 +fontTools/ufoLib/plistlib.py,sha256=jzMGOGvHO6XvS-IO8hS04ur7r8-v2dnVq-vKMoJZvqQ,1510 +fontTools/ufoLib/pointPen.py,sha256=CuREcm3IYteZNBDAd_ZRAV4XqBsy0s07jdWc4en9r-8,244 +fontTools/ufoLib/utils.py,sha256=nZoJJqHXQSL-LXYE58_WHA97XlbTkEbYkdH3GL32SmQ,3192 +fontTools/ufoLib/validators.py,sha256=MWBqcLThGyYpst61QothA_BSlc6jGVhPvFiay-pobCY,32387 +fontTools/unicode.py,sha256=ZZ7OMmWvIyV1IL1k6ioTzaRAh3tUvm6gvK7QgFbOIHY,1237 +fontTools/unicodedata/Blocks.py,sha256=6BL66vrr5UWylVx3bicy6U2kO-QcNNKpmPKQTGggUEU,32415 +fontTools/unicodedata/Mirrored.py,sha256=kdhwCWOWaArmfNkDah0Thv-67M9wWz45R5IMPhqyzFM,9242 +fontTools/unicodedata/OTTags.py,sha256=wOPpbMsNcp_gdvPFeITtgVMnTN8TJSNAsVEdu_nuPXE,1196 +fontTools/unicodedata/ScriptExtensions.py,sha256=YTZr2bOteHiz_7I4108PRy0Is4kFof-32yFuoKjFHjc,28207 +fontTools/unicodedata/Scripts.py,sha256=I0nY08ovsZ4pHU5wYchjat9DjnxcpoTzaXAn5oFaKNI,130271 +fontTools/unicodedata/__init__.py,sha256=ht5cIwvgKSonvRADzijXzBp6uZjhTvFobBwaba4ogaM,9033 +fontTools/varLib/__init__.py,sha256=SeAVSol0qvmw4Io5hvuVWxwx_onKadqr_1eXwjNUGkk,57322 +fontTools/varLib/__main__.py,sha256=wbdYC5bPjWCxA0I4SKcLO88gl-UMtsYS8MxdW9ySTkY,95 +fontTools/varLib/avar/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fontTools/varLib/avar/__main__.py,sha256=ew1fJpg81GpYbdkrp4I7ntWdbhkDeg5fNn1SrpF254k,1770 +fontTools/varLib/avar/build.py,sha256=YSMsRMjGkNW2zhKn29HgovNNG-jgiFSsK7zYH4un2Ws,2087 +fontTools/varLib/avar/map.py,sha256=UBeElT40SHXvJrQ7SflH5MNYKTTom7RLHwq2varb_oE,2867 +fontTools/varLib/avar/plan.py,sha256=qDKZjQq6OfeXBr3T3DZnrmauyMm5ek0rm5YVosAO_UA,27354 +fontTools/varLib/avar/unbuild.py,sha256=h3qb0JBN7SngijPrwjTjGEjueeENlhPYY9FyN02FLEk,10467 +fontTools/varLib/avarPlanner.py,sha256=CabG5xB57FMdwmN1acpVMvyOucVPxCdRdJSK2gu7gb4,109 +fontTools/varLib/builder.py,sha256=mSKOCcnnw-WzmZs15FayoqCDh77Ts7o9Tre9psh8CUc,6609 +fontTools/varLib/cff.py,sha256=EVgaQcoROIrYQsRuftnxFuGGldEPYbrIh5yBckylJC4,22901 +fontTools/varLib/errors.py,sha256=dMo8eGj76I7H4hrBEiNbYrGs2J1K1SwdsUyTHpkVOrQ,6934 +fontTools/varLib/featureVars.py,sha256=kp4gPjKyyGRu7yBWxgd1N4OkKnU9V45QwiWSHs6OWd0,26180 +fontTools/varLib/hvar.py,sha256=1IvL5BneTkg8jJYicH0TSQViB6D0vBEesLdlfqoLBX4,3695 +fontTools/varLib/instancer/__init__.py,sha256=fHd864WfEDyFH3zXGldT34aw3524143dZPIDqA95V5A,75554 +fontTools/varLib/instancer/__main__.py,sha256=zfULwcP01FhplS1IlcMgNQnLxk5RVfmOuinWjqeid-g,104 +fontTools/varLib/instancer/featureVars.py,sha256=oPqSlnHLMDTtOsmQMi6gkzLox7ymCrqlRAkvC_EJ4bc,7110 +fontTools/varLib/instancer/names.py,sha256=IPRqel_M8zVU0jl30WsfgufxUm9PBBQDQCY3VHapeHc,14950 +fontTools/varLib/instancer/solver.py,sha256=uMePwX0BVT5F94kUvDglsI4_F0nEH67F7RFuJ6tQwQ0,11002 +fontTools/varLib/interpolatable.py,sha256=Bhlq_LhEZ-sXfLNY8aFEChFrsKuT2kzmnuMfG5qi0v4,45221 +fontTools/varLib/interpolatableHelpers.py,sha256=cTFgTqDjggSCqNfTM77__5b9Sja_g7xWWMiB-pXDx84,11672 +fontTools/varLib/interpolatablePlot.py,sha256=w393P6mGLRhYkIjSxMww3qyoYxAUZzCXlmPBbI_84C0,44375 +fontTools/varLib/interpolatableTestContourOrder.py,sha256=mHJ9Ry7Rm7H3zHDwEUQEtEIDseiUzOxjg4MveW_FSiU,3021 +fontTools/varLib/interpolatableTestStartingPoint.py,sha256=K6OYKBspim6BXc91pfLTbGLyi5XZukfMuBc6hRpENG8,4296 +fontTools/varLib/interpolate_layout.py,sha256=22VjGZuV2YiAe2MpdTf0xPVz1x2G84bcOL0vOeBpGQM,3689 +fontTools/varLib/iup.c,sha256=I7snrACi_wloZDL67Fypk-7Dff5pxJhaVmluAXBUW_4,827723 +fontTools/varLib/iup.cpython-310-x86_64-linux-gnu.so,sha256=kidEB2aI9mC1V_EmfZJuz08TNpKhxygY89ioR0erX10,1565056 +fontTools/varLib/iup.py,sha256=mKq_GRWuUg4yTmw2V32nu0v2r-SzzN7xS7rIbV0mYuc,14984 +fontTools/varLib/merger.py,sha256=E59oli4AwqWZ-FgnuStMSBvsB-FHe-55esXTYUqGeJ8,60802 +fontTools/varLib/models.py,sha256=sj_ENljh_qcMbfYzRIOlRgHq6tFOmL02Wv6WO8uofis,22398 +fontTools/varLib/multiVarStore.py,sha256=eQEuWNY01YF5zDpy1UwNtvOYyD6c0FLxpH-QFpX1i78,8305 +fontTools/varLib/mutator.py,sha256=kzXiLFxRLgU2pcHzOzh9u0n0KkO3DuBk06xZ_RPhWz8,19804 +fontTools/varLib/mvar.py,sha256=LTV77vH_3Ecg_qKBO5xQzjLOlJir_ppEr7mPVZRgad8,2449 +fontTools/varLib/plot.py,sha256=NoSZkJ5ndxNcDvJIvd5pQ9_jX6X1oM1K2G_tR4sdPVs,7494 +fontTools/varLib/stat.py,sha256=XuNKKZxGlBrl4OGFDAwVXhpBwJi23U3BdHmNTKoJnvE,4811 +fontTools/varLib/varStore.py,sha256=2QA9SDI6jQyQ_zq82OOwa3FBkfl-ksaSo1KGmVFpa9Q,24069 +fontTools/voltLib/__init__.py,sha256=ZZ1AsTx1VlDn40Kupce-fM3meOWugy3RZraBW9LG-9M,151 +fontTools/voltLib/__main__.py,sha256=uVtABLzMeHtvKL8zetf4rpC4aB8BkYr5QLSegNjZZZI,5928 +fontTools/voltLib/ast.py,sha256=arA9W3Gqo6OqljwNNKnMAojz-C5LStbC5SgjJh7buKk,13300 +fontTools/voltLib/error.py,sha256=phcQOQj-xOspCXu9hBJQRhSOBDzxHRgZd3fWQOFNJzw,395 +fontTools/voltLib/lexer.py,sha256=OvuETOSvlS6v7iCVeJ3IdH2Cg71n3OJoEyiB3-h6vhE,3368 +fontTools/voltLib/parser.py,sha256=rkw2IHBZPsrhGVC7Kw7V501m0u52kh1JSM5HXp-xchM,25396 +fontTools/voltLib/voltToFea.py,sha256=Z2yvnaZLQXzPLT86Uta0zRsXIYgj6NnvZtSWt5xmw2s,36549 +fonttools-4.60.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +fonttools-4.60.1.dist-info/METADATA,sha256=CIZ3DxcKqkgjQVIa68ndWbeo4HP-yrkBlOLu-dmZygM,112334 +fonttools-4.60.1.dist-info/RECORD,, +fonttools-4.60.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fonttools-4.60.1.dist-info/WHEEL,sha256=DTnKjM5OInJxWADod3iQyWxWcdG-eRwxzGww236swpY,151 +fonttools-4.60.1.dist-info/entry_points.txt,sha256=8kVHddxfFWA44FSD4mBpmC-4uCynQnkoz_9aNJb227Y,147 +fonttools-4.60.1.dist-info/licenses/LICENSE,sha256=Z4cgj4P2Wcy8IiOy_elS_6b36KymLxqKK_W8UbsbI4M,1072 +fonttools-4.60.1.dist-info/licenses/LICENSE.external,sha256=lKg6ruBymg8wLTSsxKzsvZ1YNm8mJCkHX-VX5KVLLmk,20022 +fonttools-4.60.1.dist-info/top_level.txt,sha256=rRgRylrXzekqWOsrhygzib12pQ7WILf7UGjqEwkIFDM,10 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d170d6d9582d145f12244c4135d9446d597e1029 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/entry_points.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..87ae781f169a63f0cf672a9050474035bfa5add4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +fonttools = fontTools.__main__:main +pyftmerge = fontTools.merge:main +pyftsubset = fontTools.subset:main +ttx = fontTools.ttx:main diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/licenses/LICENSE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cc633905d333c4b42c1a0c8b34e9f734adeb6e1e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Just van Rossum + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/licenses/LICENSE.external b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/licenses/LICENSE.external new file mode 100644 index 0000000000000000000000000000000000000000..5c45052f870940119ee6bc2b51ab3a7bc43d01d7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/licenses/LICENSE.external @@ -0,0 +1,388 @@ +FontTools includes the following font projects for testing purposes, which are +under SIL Open Font License, Version 1.1: + +Lobster + Copyright (c) 2010, Pablo Impallari (www.impallari.com|impallari@gmail.com), + with Reserved Font Name Lobster. + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +Noto Fonts + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +XITS font project + Copyright (c) 2001-2010 by the STI Pub Companies, consisting of the American + Institute of Physics, the American Chemical Society, the American + Mathematical Society, the American Physical Society, Elsevier, Inc., and The + Institute of Electrical and Electronic Engineers, Inc. (www.stixfonts.org), + with Reserved Font Name STIX Fonts, STIX Fonts (TM) is a trademark of The + Institute of Electrical and Electronics Engineers, Inc. + + Portions copyright (c) 1998-2003 by MicroPress, Inc. + (www.micropress-inc.com), with Reserved Font Name TM Math. To obtain + additional mathematical fonts, please contact MicroPress, Inc., 68-30 Harrow + Street, Forest Hills, NY 11375, USA, Phone: (718) 575-1816. + + Portions copyright (c) 1990 by Elsevier, Inc. + + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +Iosevka + Copyright (c) 2015-2020 Belleve Invis (belleve@typeof.net). + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +===== + +FontTools includes Adobe AGL & AGLFN, which is under 3-clauses BSD license: + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +Neither the name of Adobe Systems Incorporated nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +===== + +FontTools includes cu2qu, which is Copyright 2016 Google Inc. All Rights Reserved. +Licensed under the Apache License, Version 2.0, a copy of which is reproduced below: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +===== + +FontTools includes code in `fontTools.misc.filesystem` which is derived from: + +PyFilesystem2 (i.e. the `fs` package) by Will McGugan +Licensed under the MIT License +https://github.com/PyFilesystem/pyfilesystem2 + +Copyright (c) 2017-2021 The PyFilesystem2 contributors +Copyright (c) 2016-2019 Will McGugan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..9af65ba39d292309497df4accdc44bd6f8143d10 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fonttools-4.60.1.dist-info/top_level.txt @@ -0,0 +1 @@ +fontTools diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/License.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/License.txt @@ -0,0 +1,1568 @@ +End User License Agreement +-------------------------- + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA software. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +This package includes over 100+ CUDA examples that demonstrate +various CUDA programming principles, and efficient CUDA +implementation of algorithms in specific application domains. + + +Default Install Location of CUDA Samples + +Windows platform: + +%ProgramData%\NVIDIA Corporation\CUDA Samples\v#.# + +Linux platform: + +/usr/local/cuda-#.#/samples + +and + +$HOME/NVIDIA_CUDA-#.#_Samples + +Mac platform: + +/Developer/NVIDIA/CUDA-#.#/samples + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Release Date: July 26, 2018 +--------------------------- + + +Important NoticeRead before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Third Party Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, third party software licensed by a NVIDIA +supplier and/or open source software provided under an open +source license. Use of third party software is subject to the +third-party license terms, or in the absence of third party +terms, the terms of this Agreement. Copyright to third party +software is held by the copyright holders indicated in the +third-party software or license. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. Unless you have an agreement with NVIDIA for this + purpose, you may not use the SDK with any system or + application where the use or failure of the system or + application can reasonably be expected to threaten or + result in personal injury, death, or catastrophic loss. + Examples include use in avionics, navigation, military, + medical, life support or other life critical applications. + NVIDIA does not design, test or manufacture the SDK for + these critical uses and NVIDIA shall not be liable to you + or any third party, in whole or in part, for any claims or + damages arising from such uses. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to your use of + the SDK outside of the scope of this Agreement, or not in + compliance with its terms. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights described in this + section. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights described in this section. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS +OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF +PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION +WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, +WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH +OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), +PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF +LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware as those laws +are applied to contracts entered into and performed entirely +within Delaware by Delaware residents, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not a resident or citizen of any country +currently embargoed by the U.S. and that you are not otherwise +prohibited from receiving the SDK. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + + +Release date: August 16, 2018 +----------------------------- + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following portions of the SDK are distributable under the +Agreement: + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +CUDA Accelerated Graph Library + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-fatbinaryloader.so, +libnvidia-ptxjitcompiler.so + +The NVIDIA CUDA Driver Libraries are only distributable in +applications that meet this criteria: + + 1. The application was developed starting from a NVIDIA CUDA + container obtained from Docker Hub or the NVIDIA GPU + Cloud, and + + 2. The resulting application is packaged as a Docker + container and distributed to users on Docker Hub or the + NVIDIA GPU Cloud only. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. + + 5. Licensee's use (e.g. nvprof) of the PCRE third party + component is subject to the following terms and + conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the name of Google + Inc. nor the names of their contributors may be used to endorse or + promote products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the University of California, Berkeley nor + the names of its contributors may be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer listed in this license in the documentation and/or + other materials provided with the distribution. + * Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the STFC nor the names of its contributors + may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE STFC BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the King Abdullah University of Science and + Technology nor the names of its contributors may be used to endorse + or promote products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the Hiroshima University nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions, and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of D. E. Shaw Research nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license . + +----------------- diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..132da4d3c2e9e8c3a1ef56f482a283a26849c2cb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/METADATA @@ -0,0 +1,44 @@ +Metadata-Version: 2.2 +Name: nvidia-nvjitlink-cu12 +Version: 12.8.93 +Summary: Nvidia JIT LTO Library +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: requires-python +Dynamic: summary + +NVIDIA compiler library for JIT LTO functionality. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4baa7e5a30ea1053fecd63f90797f90367a24797 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/RECORD @@ -0,0 +1,13 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvjitlink/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvjitlink/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvjitlink/include/nvJitLink.h,sha256=Vv2Dhlpuwssu2ebjRIU37clsSggc96F7X-A77UTjd_c,17081 +nvidia/nvjitlink/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvjitlink/lib/libnvJitLink.so.12,sha256=A2nmhn1EuABDfeThRtcsZa_Gx1rfZ3oVwuzY5qesE18,94101392 +nvidia_nvjitlink_cu12-12.8.93.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +nvidia_nvjitlink_cu12-12.8.93.dist-info/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_nvjitlink_cu12-12.8.93.dist-info/METADATA,sha256=d2_qsBLB8-_OiRiXXcCKoBeTqjODLYezd8qgRIytRDU,1695 +nvidia_nvjitlink_cu12-12.8.93.dist-info/RECORD,, +nvidia_nvjitlink_cu12-12.8.93.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia_nvjitlink_cu12-12.8.93.dist-info/WHEEL,sha256=6VN0zCSXVxqaCfAW-ySp_g8N0rln0iqt25pKNCbVzrk,144 +nvidia_nvjitlink_cu12-12.8.93.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1ce22213ca080d1066f9438436aabd77121bada0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.0) +Root-Is-Purelib: true +Tag: py3-none-manylinux2010_x86_64 +Tag: py3-none-manylinux_2_12_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvjitlink_cu12-12.8.93.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..f6670289d9f5db4390e2ee9ca0de459fa38ae629 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/METADATA @@ -0,0 +1,45 @@ +Metadata-Version: 2.4 +Name: nvidia-nvshmem-cu12 +Version: 3.3.20 +Summary: NVSHMEM creates a global address space that provides efficient and scalable communication for NVIDIA GPU clusters. +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: BSD-3-Clause +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + +NVSHMEM is a parallel programming interface based on OpenSHMEM that provides efficient and scalable communication for NVIDIA GPU clusters. NVSHMEM creates a global address space for data that spans the memory of multiple GPUs and can be accessed with fine-grained GPU-initiated operations, CPU-initiated operations, and operations on CUDA streams. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0f6cd0964fff20a743a78af422c811fbf47f0735 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/RECORD @@ -0,0 +1,66 @@ +nvidia/nvshmem/include/bootstrap_device_host/nvshmem_uniqueid.h,sha256=dkn1MOgwyOWCN0njxYA70vf4T3EItLW5OO1m0eL8wXY,1534 +nvidia/nvshmem/include/device/nvshmem_coll_defines.cuh,sha256=6rzjF7IuBZc29hVPuvHFv3Ak7GUI3cZOJnYgZR0hJIQ,7787 +nvidia/nvshmem/include/device/nvshmem_defines.h,sha256=RNtwW8PQX0ZQJKeYSz9YvUZj3kBuhE7ioPzryIetrpw,84915 +nvidia/nvshmem/include/device/nvshmem_device_macros.h,sha256=8H4P0HvTVOF2ejvTZCypbuCTlpuMjyOzZGK6K_NEoFw,1438 +nvidia/nvshmem/include/device/nvshmemx_coll_defines.cuh,sha256=_mZj6ueqsQ2-mQYuNZ_FPtLF-FPOyWoK_kC09BUuLyM,13391 +nvidia/nvshmem/include/device/nvshmemx_collective_launch_apis.h,sha256=CJgnQ0LIvsLz27t6fMEkpTM-bMsr4KlN7OEreYnj3K0,985 +nvidia/nvshmem/include/device/nvshmemx_defines.h,sha256=Ia8S-ypXJlE5e8lwOw-VChlNKaei-uPooT8ZLhlct48,29150 +nvidia/nvshmem/include/device/tile/nvshmemx_tile_api.hpp,sha256=lgDJehC23uX0b2btvBOGKnykFvswZC8oTuwjv1jn7l8,4789 +nvidia/nvshmem/include/device/tile/nvshmemx_tile_api_defines.cuh,sha256=gQ_VzV9pnFB0UPLujSkMVkR-RRuiF2L58p7FuXzX4ao,6695 +nvidia/nvshmem/include/device_host/nvshmem_common.cuh,sha256=sMDsqWAqmPlJLfZFBRx0vGIUh3fy6sxuCOKLYZ-xtHw,28601 +nvidia/nvshmem/include/device_host/nvshmem_proxy_channel.h,sha256=7IVHfqjYvO46rqLyEijabBfXqd0xGWIodVHQZ9DNMYs,3798 +nvidia/nvshmem/include/device_host/nvshmem_tensor.h,sha256=1qVYprQysc5jPaVP28AvP7EwBjatoVkvPOmeZ9se0IE,3464 +nvidia/nvshmem/include/device_host/nvshmem_types.h,sha256=vhk-9EzFJ_Vez_iLyFqth2wzq12TvQYaZ4MtdOlX-yY,23598 +nvidia/nvshmem/include/device_host_transport/nvshmem_common_ibgda.h,sha256=_CrXhqmX1ESmcKvAe2MLEjZp2L3huTKKwNwQn6kHQbU,13441 +nvidia/nvshmem/include/device_host_transport/nvshmem_common_transport.h,sha256=58U5bWulCrF1FlbTrCgOrgGfLqNYtE4OAcCZjBmOtgs,1553 +nvidia/nvshmem/include/device_host_transport/nvshmem_constants.h,sha256=GBW7ECdTigA5oA8RVWJb9YuKYkBuvN396lwhYrc8k1Y,2577 +nvidia/nvshmem/include/host/nvshmem_api.h,sha256=oTjijUwUbE4H436vPJvVZYc5QMxcE_WVTd3hNlf7jqs,23330 +nvidia/nvshmem/include/host/nvshmem_coll_api.h,sha256=yua0cNOGXzbjr5UhKH_xOaUmKQYB0ERUktvu7RlsCRU,5069 +nvidia/nvshmem/include/host/nvshmem_macros.h,sha256=kpy49KF5YJltPQ10aw09v0JgMpRW3RCgpLFRiqP37hQ,502 +nvidia/nvshmem/include/host/nvshmemx_api.h,sha256=XMd3PtsLZsQq0h3cuiwwMujdMEDsev8YRL-wPFgD-5w,25564 +nvidia/nvshmem/include/host/nvshmemx_coll_api.h,sha256=t7PT7KDtGEsjf63BEGG-lnvzR9MmiS395mzo1WgTAXw,11814 +nvidia/nvshmem/include/non_abi/device/coll/alltoall.cuh,sha256=Q1MITu6uZDyBhFEzCnMHg-ults-eYObfdrvoKid9HCI,7528 +nvidia/nvshmem/include/non_abi/device/coll/barrier.cuh,sha256=pid3GRkHI8QMoKYA_Vvb6NUIflUpEWZz8C52OUkU4N8,11340 +nvidia/nvshmem/include/non_abi/device/coll/broadcast.cuh,sha256=oxw9BlAH8avnoA0EGGAcfgLiKtu_wqTV0GxOTlXy7Cg,20275 +nvidia/nvshmem/include/non_abi/device/coll/defines.cuh,sha256=Rmf9eXjvIwCA0GpcTWWe-eqnqD72N1lTM0nJa45J3jw,445 +nvidia/nvshmem/include/non_abi/device/coll/fcollect.cuh,sha256=UdMBF2AE5T588CMAfLbhpWw9F0QMFdJnhPDei6_o_HY,55584 +nvidia/nvshmem/include/non_abi/device/coll/reduce.cuh,sha256=gDHcDNK1Moh4rMDRW9CZ3GJ8K0JG1ijKkAOdGe3Z1Vs,134681 +nvidia/nvshmem/include/non_abi/device/coll/reducescatter.cuh,sha256=5qXss5pz3_u9n3yv61b463K0S1GSrZ78NK0FKqLTl2w,8863 +nvidia/nvshmem/include/non_abi/device/coll/utils.cuh,sha256=0hBhTWdOu8yLt2O08qimgbToeofmFg5HLRQXIUMt3pg,2217 +nvidia/nvshmem/include/non_abi/device/common/nvshmemi_common_device.cuh,sha256=gbTo8MwxYl8xpofrBluR55yjkoEIBasa1r2qt2jzclA,45438 +nvidia/nvshmem/include/non_abi/device/common/nvshmemi_tile_utils.cuh,sha256=a6ate9pJ5eZ2jYUFo_TbP0XgmABf22AdS1E2qaLfauU,11551 +nvidia/nvshmem/include/non_abi/device/pt-to-pt/ibgda_device.cuh,sha256=09GJw2gqTqfZOYlKUeHjDKJWWY8o7ZHJ291RIqwhk7w,135851 +nvidia/nvshmem/include/non_abi/device/pt-to-pt/nvshmemi_transfer_api.cuh,sha256=2Gops_z4ZwET3rkY8764so_DOjiYnFzWz10MFHERqNk,1614 +nvidia/nvshmem/include/non_abi/device/pt-to-pt/proxy_device.cuh,sha256=BOcWdK04tYI34492D3cJka_t47BdYQc35yUpecdkq74,25417 +nvidia/nvshmem/include/non_abi/device/pt-to-pt/transfer_device.cuh,sha256=KbytXjiCSqSYv9-5YArqE85ouoboUByiL_10dYctYls,11924 +nvidia/nvshmem/include/non_abi/device/pt-to-pt/utils_device.h,sha256=9skm4sKqn4xLKJQ9IgZ5THVuIfz7YV8C0ZnEEm2VxFo,3269 +nvidia/nvshmem/include/non_abi/device/team/nvshmemi_team_defines.cuh,sha256=hRtQVabpfEQHGel2BqhcRKIgytFzykNcQfokD6BMvbM,7267 +nvidia/nvshmem/include/non_abi/device/threadgroup/nvshmemi_common_device_defines.cuh,sha256=90hQ9euQUrTQDczD2PqAMtyljNFpiPEIi904HNC4ams,4051 +nvidia/nvshmem/include/non_abi/device/wait/nvshmemi_wait_until_apis.cuh,sha256=dC6V1Lx0GNqxbgbZREJBWfw_jSOMLZWClPZQ86uuPtc,5866 +nvidia/nvshmem/include/non_abi/nvshmem_build_options.h,sha256=bGli2qy93AKK1vpo-hZc2Vh1kOAv380bOMimND3Ml-o,1109 +nvidia/nvshmem/include/non_abi/nvshmem_version.h,sha256=jUvwRJDQ_rGEZzEMCmkgnZwC0mpfvGJ0uJx2sKFXEEI,1685 +nvidia/nvshmem/include/non_abi/nvshmemx_error.h,sha256=FR7mgsMhMo0fVlL_dhOVCLJKnp934-hcFNxk6EdgdKE,8885 +nvidia/nvshmem/include/nvshmem.h,sha256=k7HeqLlQvwsO38tDtvUadO3eCw7dsEufpvWslU_ex8g,1000 +nvidia/nvshmem/include/nvshmem_host.h,sha256=6_78oo3I_OT7gmNNrAxpaL5GWwAo1pUUL_6rsQgUSp8,236 +nvidia/nvshmem/include/nvshmemx.h,sha256=XXplDGxuI9usiP0m6fNXwJmb1Pqf_OhrYERsdPK7hwA,1028 +nvidia/nvshmem/lib/libnvshmem_device.a,sha256=e_IaASFU-yWu_BPf1ewpcjtNRQSfJNw219Qh8iZDxaE,7051126 +nvidia/nvshmem/lib/libnvshmem_device.bc,sha256=1YL01Vo1yK2GWtz37-ajbX0cA_kemqoSv-X1eykBrqU,31199892 +nvidia/nvshmem/lib/libnvshmem_host.so.3,sha256=gzfSUeYWpuE3UMGjIunbq_qGevRICtx34TpgeSaduTY,144177272 +nvidia/nvshmem/lib/nvshmem_bootstrap_mpi.so.3,sha256=nrTTCCKrEy3vR3oSl1ZP7qcFb6LHNdKmKEx0jvQPY9w,23952 +nvidia/nvshmem/lib/nvshmem_bootstrap_pmi.so.3,sha256=C1miYJGAKsRW2FunCTPBTzdiAFjkzhemYEFUSmk91BQ,39456 +nvidia/nvshmem/lib/nvshmem_bootstrap_pmi2.so.3,sha256=FY0kvwDwrxQphKkD3ZFTP2mfPSFq3MG16XZ8NrwEY8U,54112 +nvidia/nvshmem/lib/nvshmem_bootstrap_pmix.so.3,sha256=L_mKchRw0ZL1XxzmZgLP2jm2oQgpaHVQcRHsL3R4L7o,56504 +nvidia/nvshmem/lib/nvshmem_bootstrap_shmem.so.3,sha256=gy0jEgnezZ9hjJm8fAVJp-jk5pq8qrJAhYpblIu6PlI,19704 +nvidia/nvshmem/lib/nvshmem_bootstrap_uid.so.3,sha256=UuUfw1obWSAErX7Cu5lfZuUP377OljIowRlKw9L9bvs,73704 +nvidia/nvshmem/lib/nvshmem_transport_ibdevx.so.3,sha256=lIRgTXwfVVGGcfKn5uS83n_KEp4FokSqMP4XVVRnxLg,1048624 +nvidia/nvshmem/lib/nvshmem_transport_ibgda.so.3,sha256=VD-fXeI1e4i2RqQ76Y6yqWar6uyYfx7IBUjEmqlygsU,1087544 +nvidia/nvshmem/lib/nvshmem_transport_ibrc.so.3,sha256=yUXZKaCWkEGaTCK0OTwjZbieAPFgGrEIh2mrebBbvAI,1053496 +nvidia/nvshmem/lib/nvshmem_transport_libfabric.so.3,sha256=w0EoipdemY4kE34hAH4cnEwM5WxDgWltvs-Ts9S0TMk,1041984 +nvidia/nvshmem/lib/nvshmem_transport_ucx.so.3,sha256=RL7QEnMMz20MN7W9tD_PkS7WQEWx2XdaO2UmRxCxCbQ,55912 +nvidia_nvshmem_cu12-3.3.20.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +nvidia_nvshmem_cu12-3.3.20.dist-info/METADATA,sha256=XuzrYl0mBONC5yanWL7pvhY5trR9s0YMfqrgvMTyvm4,2088 +nvidia_nvshmem_cu12-3.3.20.dist-info/RECORD,, +nvidia_nvshmem_cu12-3.3.20.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia_nvshmem_cu12-3.3.20.dist-info/WHEEL,sha256=gy6FWQgpujK_dnYc155G2NL32NQjpi5ebTEXjh8SGZQ,144 +nvidia_nvshmem_cu12-3.3.20.dist-info/licenses/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_nvshmem_cu12-3.3.20.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..29738220b339f398b2cbbc9ac8ccb38a39bdd7b2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-manylinux2014_x86_64 +Tag: py3-none-manylinux_2_17_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/licenses/License.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/licenses/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/licenses/License.txt @@ -0,0 +1,1568 @@ +End User License Agreement +-------------------------- + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA software. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +This package includes over 100+ CUDA examples that demonstrate +various CUDA programming principles, and efficient CUDA +implementation of algorithms in specific application domains. + + +Default Install Location of CUDA Samples + +Windows platform: + +%ProgramData%\NVIDIA Corporation\CUDA Samples\v#.# + +Linux platform: + +/usr/local/cuda-#.#/samples + +and + +$HOME/NVIDIA_CUDA-#.#_Samples + +Mac platform: + +/Developer/NVIDIA/CUDA-#.#/samples + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Release Date: July 26, 2018 +--------------------------- + + +Important NoticeRead before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Third Party Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, third party software licensed by a NVIDIA +supplier and/or open source software provided under an open +source license. Use of third party software is subject to the +third-party license terms, or in the absence of third party +terms, the terms of this Agreement. Copyright to third party +software is held by the copyright holders indicated in the +third-party software or license. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. Unless you have an agreement with NVIDIA for this + purpose, you may not use the SDK with any system or + application where the use or failure of the system or + application can reasonably be expected to threaten or + result in personal injury, death, or catastrophic loss. + Examples include use in avionics, navigation, military, + medical, life support or other life critical applications. + NVIDIA does not design, test or manufacture the SDK for + these critical uses and NVIDIA shall not be liable to you + or any third party, in whole or in part, for any claims or + damages arising from such uses. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to your use of + the SDK outside of the scope of this Agreement, or not in + compliance with its terms. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights described in this + section. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights described in this section. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS +OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF +PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION +WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, +WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH +OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), +PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF +LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware as those laws +are applied to contracts entered into and performed entirely +within Delaware by Delaware residents, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not a resident or citizen of any country +currently embargoed by the U.S. and that you are not otherwise +prohibited from receiving the SDK. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + + +Release date: August 16, 2018 +----------------------------- + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following portions of the SDK are distributable under the +Agreement: + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +CUDA Accelerated Graph Library + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-fatbinaryloader.so, +libnvidia-ptxjitcompiler.so + +The NVIDIA CUDA Driver Libraries are only distributable in +applications that meet this criteria: + + 1. The application was developed starting from a NVIDIA CUDA + container obtained from Docker Hub or the NVIDIA GPU + Cloud, and + + 2. The resulting application is packaged as a Docker + container and distributed to users on Docker Hub or the + NVIDIA GPU Cloud only. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. + + 5. Licensee's use (e.g. nvprof) of the PCRE third party + component is subject to the following terms and + conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the name of Google + Inc. nor the names of their contributors may be used to endorse or + promote products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the University of California, Berkeley nor + the names of its contributors may be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer listed in this license in the documentation and/or + other materials provided with the distribution. + * Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the STFC nor the names of its contributors + may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE STFC BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the King Abdullah University of Science and + Technology nor the names of its contributors may be used to endorse + or promote products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the Hiroshima University nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions, and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of D. E. Shaw Research nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license . + +----------------- diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvshmem_cu12-3.3.20.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..10b290a6cd1770506ae281a5fa469f6c110c364c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/METADATA @@ -0,0 +1,105 @@ +Metadata-Version: 2.4 +Name: packaging +Version: 25.0 +Summary: Core utilities for Python packages +Author-email: Donald Stufft +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +License-File: LICENSE +License-File: LICENSE.APACHE +License-File: LICENSE.BSD +Project-URL: Documentation, https://packaging.pypa.io/ +Project-URL: Source, https://github.com/pypa/packaging + +packaging +========= + +.. start-intro + +Reusable core utilities for various Python Packaging +`interoperability specifications `_. + +This library provides utilities that implement the interoperability +specifications which have clearly one correct behaviour (eg: :pep:`440`) +or benefit greatly from having a single shared implementation (eg: :pep:`425`). + +.. end-intro + +The ``packaging`` project includes the following: version handling, specifiers, +markers, requirements, tags, utilities. + +Documentation +------------- + +The `documentation`_ provides information and the API for the following: + +- Version Handling +- Specifiers +- Markers +- Requirements +- Tags +- Utilities + +Installation +------------ + +Use ``pip`` to install these utilities:: + + pip install packaging + +The ``packaging`` library uses calendar-based versioning (``YY.N``). + +Discussion +---------- + +If you run into bugs, you can file them in our `issue tracker`_. + +You can also join ``#pypa`` on Freenode to ask questions or get involved. + + +.. _`documentation`: https://packaging.pypa.io/ +.. _`issue tracker`: https://github.com/pypa/packaging/issues + + +Code of Conduct +--------------- + +Everyone interacting in the packaging project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + +Contributing +------------ + +The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as +well as how to report a potential security issue. The documentation for this +project also covers information about `project development`_ and `security`_. + +.. _`project development`: https://packaging.pypa.io/en/latest/development/ +.. _`security`: https://packaging.pypa.io/en/latest/security/ + +Project History +--------------- + +Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for +recent changes and project history. + +.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..08a804a1afe26f889b18e09de0bb62cfc3ad36f1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/RECORD @@ -0,0 +1,25 @@ +packaging-25.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +packaging-25.0.dist-info/METADATA,sha256=W2EaYJw4_vw9YWv0XSCuyY-31T8kXayp4sMPyFx6woI,3281 +packaging-25.0.dist-info/RECORD,, +packaging-25.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging-25.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +packaging-25.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +packaging-25.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +packaging-25.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +packaging/__init__.py,sha256=_0cDiPVf2S-bNfVmZguxxzmrIYWlyASxpqph4qsJWUc,494 +packaging/_elffile.py,sha256=UkrbDtW7aeq3qqoAfU16ojyHZ1xsTvGke_WqMTKAKd0,3286 +packaging/_manylinux.py,sha256=t4y_-dTOcfr36gLY-ztiOpxxJFGO2ikC11HgfysGxiM,9596 +packaging/_musllinux.py,sha256=p9ZqNYiOItGee8KcZFeHF_YcdhVwGHdK6r-8lgixvGQ,2694 +packaging/_parser.py,sha256=gYfnj0pRHflVc4RHZit13KNTyN9iiVcU2RUCGi22BwM,10221 +packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +packaging/_tokenizer.py,sha256=OYzt7qKxylOAJ-q0XyK1qAycyPRYLfMPdGQKRXkZWyI,5310 +packaging/licenses/__init__.py,sha256=VsK4o27CJXWfTi8r2ybJmsBoCdhpnBWuNrskaCVKP7U,5715 +packaging/licenses/_spdx.py,sha256=oAm1ztPFwlsmCKe7lAAsv_OIOfS1cWDu9bNBkeu-2ns,48398 +packaging/markers.py,sha256=P0we27jm1xUzgGMJxBjtUFCIWeBxTsMeJTOJ6chZmAY,12049 +packaging/metadata.py,sha256=8IZErqQQnNm53dZZuYq4FGU4_dpyinMeH1QFBIWIkfE,34739 +packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging/requirements.py,sha256=gYyRSAdbrIyKDY66ugIDUQjRMvxkH2ALioTmX3tnL6o,2947 +packaging/specifiers.py,sha256=gtPu5DTc-F9baLq3FTGEK6dPhHGCuwwZetaY0PSV2gs,40055 +packaging/tags.py,sha256=41s97W9Zatrq2Ed7Rc3qeBDaHe8pKKvYq2mGjwahfXk,22745 +packaging/utils.py,sha256=0F3Hh9OFuRgrhTgGZUl5K22Fv1YP2tZl1z_2gO6kJiA,5050 +packaging/version.py,sha256=olfyuk_DPbflNkJ4wBWetXQ17c74x3DB501degUv7DY,16676 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6f62d44e4ef733c0e713afcd2371fed7f2b3de67 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the licenses +found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made +under the terms of *both* these licenses. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE.APACHE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE.APACHE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE.APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE.BSD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/packaging-25.0.dist-info/licenses/LICENSE.BSD @@ -0,0 +1,23 @@ +Copyright (c) Donald Stufft and individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libXau-154567c4.so.6.0.0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libXau-154567c4.so.6.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..ff06a58be7b9ff80cee9b8eb45d5e9a28cf67d1b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libXau-154567c4.so.6.0.0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libbrotlidec-2ced2f3a.so.1.1.0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libbrotlidec-2ced2f3a.so.1.1.0 new file mode 100644 index 0000000000000000000000000000000000000000..2d8d8b9c679d2225a7e9be93be105b15171219e2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libbrotlidec-2ced2f3a.so.1.1.0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libsharpyuv-95d8a097.so.0.1.2 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libsharpyuv-95d8a097.so.0.1.2 new file mode 100644 index 0000000000000000000000000000000000000000..5d17bd4900510a0893df00445053806999c26f32 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libsharpyuv-95d8a097.so.0.1.2 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libwebpdemux-747f2b49.so.2.0.17 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libwebpdemux-747f2b49.so.2.0.17 new file mode 100644 index 0000000000000000000000000000000000000000..7a4f0eb0adbcbf06c2da4bbcaeb55e47199c4792 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libwebpdemux-747f2b49.so.2.0.17 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libwebpmux-7f11e5ce.so.3.1.2 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libwebpmux-7f11e5ce.so.3.1.2 new file mode 100644 index 0000000000000000000000000000000000000000..cc0012869e0ca876ebcc853b2349b4469c5b4360 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow.libs/libwebpmux-7f11e5ce.so.3.1.2 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..702ee6da5865b50b297705b077ea7d5904fead58 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/METADATA @@ -0,0 +1,59 @@ +Metadata-Version: 2.4 +Name: PyYAML +Version: 6.0.3 +Summary: YAML parser and emitter for Python +Home-page: https://pyyaml.org/ +Download-URL: https://pypi.org/project/PyYAML/ +Author: Kirill Simonov +Author-email: xi@resolvent.net +License: MIT +Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues +Project-URL: CI, https://github.com/yaml/pyyaml/actions +Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation +Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core +Project-URL: Source Code, https://github.com/yaml/pyyaml +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup +Requires-Python: >=3.8 +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: download-url +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: project-url +Dynamic: requires-python +Dynamic: summary + +YAML is a data serialization format designed for human readability +and interaction with scripting languages. PyYAML is a YAML parser +and emitter for Python. + +PyYAML features a complete YAML 1.1 parser, Unicode support, pickle +support, capable extension API, and sensible error messages. PyYAML +supports standard YAML tags and provides Python-specific tags that +allow to represent an arbitrary Python object. + +PyYAML is applicable for a broad range of tasks from complex +configuration files to object serialization and persistence. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..95ef5742f5c26e86ed60bd11825a8a796a47b393 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/RECORD @@ -0,0 +1,26 @@ +_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402 +pyyaml-6.0.3.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +pyyaml-6.0.3.dist-info/METADATA,sha256=A8O0Fe040J-u3Ek2DpMHabQMWPaFhebeAOLkkWqFjTQ,2351 +pyyaml-6.0.3.dist-info/RECORD,, +pyyaml-6.0.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pyyaml-6.0.3.dist-info/WHEEL,sha256=DZl4yYurviXJJQsilHH1qAzCRDsdz--oNtDZ-hUrZUk,190 +pyyaml-6.0.3.dist-info/licenses/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101 +pyyaml-6.0.3.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11 +yaml/__init__.py,sha256=sZ38wzPWp139cwc5ARZFByUvJxtB07X32FUQAzoFR6c,12311 +yaml/_yaml.cpython-310-x86_64-linux-gnu.so,sha256=ElkP4R54aTj5ZkNtRZ4IO6ai8lLpq7rGNFITZMWNRn0,2508080 +yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883 +yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639 +yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851 +yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837 +yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006 +yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533 +yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445 +yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061 +yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440 +yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495 +yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794 +yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190 +yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004 +yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279 +yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165 +yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..6d6bf82d678c683effaf22b612f4dea70dd9933d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/WHEEL @@ -0,0 +1,7 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 +Tag: cp310-cp310-manylinux_2_28_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2f1b8e15e5627d92f0521605c9870bc8e5505cb4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6475e911f628412049bc4090d86f23ac403adde --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyyaml-6.0.3.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_yaml +yaml diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b7784969a573d05cc6b98ee9066c42720156d1d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/__init__.py @@ -0,0 +1,31 @@ +""" +========================================= +Clustering package (:mod:`scipy.cluster`) +========================================= + +.. currentmodule:: scipy.cluster + +Clustering algorithms are useful in information theory, target detection, +communications, compression, and other areas. The `vq` module only +supports vector quantization and the k-means algorithms. + +The `hierarchy` module provides functions for hierarchical and +agglomerative clustering. Its features include generating hierarchical +clusters from distance matrices, +calculating statistics on clusters, cutting linkages +to generate flat clusters, and visualizing clusters with dendrograms. + +.. toctree:: + :maxdepth: 1 + + cluster.vq + cluster.hierarchy + +""" +__all__ = ['vq', 'hierarchy'] + +from . import vq, hierarchy + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/hierarchy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/hierarchy.py new file mode 100644 index 0000000000000000000000000000000000000000..522e63d8e6f2904c73c704897f715721509c819c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/hierarchy.py @@ -0,0 +1,4178 @@ +""" +Hierarchical clustering (:mod:`scipy.cluster.hierarchy`) +======================================================== + +.. currentmodule:: scipy.cluster.hierarchy + +These functions cut hierarchical clusterings into flat clusterings +or find the roots of the forest formed by a cut by providing the flat +cluster ids of each observation. + +.. autosummary:: + :toctree: generated/ + + fcluster + fclusterdata + leaders + +These are routines for agglomerative clustering. + +.. autosummary:: + :toctree: generated/ + + linkage + single + complete + average + weighted + centroid + median + ward + +These routines compute statistics on hierarchies. + +.. autosummary:: + :toctree: generated/ + + cophenet + from_mlab_linkage + inconsistent + maxinconsts + maxdists + maxRstat + to_mlab_linkage + +Routines for visualizing flat clusters. + +.. autosummary:: + :toctree: generated/ + + dendrogram + +These are data structures and routines for representing hierarchies as +tree objects. + +.. autosummary:: + :toctree: generated/ + + ClusterNode + leaves_list + to_tree + cut_tree + optimal_leaf_ordering + +These are predicates for checking the validity of linkage and +inconsistency matrices as well as for checking isomorphism of two +flat cluster assignments. + +.. autosummary:: + :toctree: generated/ + + is_valid_im + is_valid_linkage + is_isomorphic + is_monotonic + correspond + num_obs_linkage + +Utility routines for plotting: + +.. autosummary:: + :toctree: generated/ + + set_link_color_palette + +Utility classes: + +.. autosummary:: + :toctree: generated/ + + DisjointSet -- data structure for incremental connectivity queries + +""" +# Copyright (C) Damian Eads, 2007-2008. New BSD License. + +# hierarchy.py (derived from cluster.py, http://scipy-cluster.googlecode.com) +# +# Author: Damian Eads +# Date: September 22, 2007 +# +# Copyright (c) 2007, 2008, Damian Eads +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# - Redistributions of source code must retain the above +# copyright notice, this list of conditions and the +# following disclaimer. +# - Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# - Neither the name of the author nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import warnings +import bisect +from collections import deque + +import numpy as np +from . import _hierarchy, _optimal_leaf_ordering +import scipy.spatial.distance as distance +from scipy._lib._array_api import array_namespace, _asarray, xp_copy, is_jax +from scipy._lib._disjoint_set import DisjointSet + + +_LINKAGE_METHODS = {'single': 0, 'complete': 1, 'average': 2, 'centroid': 3, + 'median': 4, 'ward': 5, 'weighted': 6} +_EUCLIDEAN_METHODS = ('centroid', 'median', 'ward') + +__all__ = ['ClusterNode', 'DisjointSet', 'average', 'centroid', 'complete', + 'cophenet', 'correspond', 'cut_tree', 'dendrogram', 'fcluster', + 'fclusterdata', 'from_mlab_linkage', 'inconsistent', + 'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage', + 'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists', + 'maxinconsts', 'median', 'num_obs_linkage', 'optimal_leaf_ordering', + 'set_link_color_palette', 'single', 'to_mlab_linkage', 'to_tree', + 'ward', 'weighted'] + + +class ClusterWarning(UserWarning): + pass + + +def _warning(s): + warnings.warn(f'scipy.cluster: {s}', ClusterWarning, stacklevel=3) + + +def int_floor(arr, xp): + # array_api_strict is strict about not allowing `int()` on a float array. + # That's typically not needed, here it is - so explicitly convert + return int(xp.astype(xp.asarray(arr), xp.int64)) + + +def single(y): + """ + Perform single/min/nearest linkage on the condensed distance matrix ``y``. + + Parameters + ---------- + y : ndarray + The upper triangular of the distance matrix. The result of + ``pdist`` is returned in this form. + + Returns + ------- + Z : ndarray + The linkage matrix. + + See Also + -------- + linkage : for advanced creation of hierarchical clusterings. + scipy.spatial.distance.pdist : pairwise distance metrics + + Examples + -------- + >>> from scipy.cluster.hierarchy import single, fcluster + >>> from scipy.spatial.distance import pdist + + First, we need a toy dataset to play with:: + + x x x x + x x + + x x + x x x x + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + Then, we get a condensed distance matrix from this dataset: + + >>> y = pdist(X) + + Finally, we can perform the clustering: + + >>> Z = single(y) + >>> Z + array([[ 0., 1., 1., 2.], + [ 2., 12., 1., 3.], + [ 3., 4., 1., 2.], + [ 5., 14., 1., 3.], + [ 6., 7., 1., 2.], + [ 8., 16., 1., 3.], + [ 9., 10., 1., 2.], + [11., 18., 1., 3.], + [13., 15., 2., 6.], + [17., 20., 2., 9.], + [19., 21., 2., 12.]]) + + The linkage matrix ``Z`` represents a dendrogram - see + `scipy.cluster.hierarchy.linkage` for a detailed explanation of its + contents. + + We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster + each initial point would belong given a distance threshold: + + >>> fcluster(Z, 0.9, criterion='distance') + array([ 7, 8, 9, 10, 11, 12, 4, 5, 6, 1, 2, 3], dtype=int32) + >>> fcluster(Z, 1, criterion='distance') + array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32) + >>> fcluster(Z, 2, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a + plot of the dendrogram. + """ + return linkage(y, method='single', metric='euclidean') + + +def complete(y): + """ + Perform complete/max/farthest point linkage on a condensed distance matrix. + + Parameters + ---------- + y : ndarray + The upper triangular of the distance matrix. The result of + ``pdist`` is returned in this form. + + Returns + ------- + Z : ndarray + A linkage matrix containing the hierarchical clustering. See + the `linkage` function documentation for more information + on its structure. + + See Also + -------- + linkage : for advanced creation of hierarchical clusterings. + scipy.spatial.distance.pdist : pairwise distance metrics + + Examples + -------- + >>> from scipy.cluster.hierarchy import complete, fcluster + >>> from scipy.spatial.distance import pdist + + First, we need a toy dataset to play with:: + + x x x x + x x + + x x + x x x x + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + Then, we get a condensed distance matrix from this dataset: + + >>> y = pdist(X) + + Finally, we can perform the clustering: + + >>> Z = complete(y) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.41421356, 3. ], + [ 5. , 13. , 1.41421356, 3. ], + [ 8. , 14. , 1.41421356, 3. ], + [11. , 15. , 1.41421356, 3. ], + [16. , 17. , 4.12310563, 6. ], + [18. , 19. , 4.12310563, 6. ], + [20. , 21. , 5.65685425, 12. ]]) + + The linkage matrix ``Z`` represents a dendrogram - see + `scipy.cluster.hierarchy.linkage` for a detailed explanation of its + contents. + + We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster + each initial point would belong given a distance threshold: + + >>> fcluster(Z, 0.9, criterion='distance') + array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=int32) + >>> fcluster(Z, 1.5, criterion='distance') + array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32) + >>> fcluster(Z, 4.5, criterion='distance') + array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32) + >>> fcluster(Z, 6, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a + plot of the dendrogram. + """ + return linkage(y, method='complete', metric='euclidean') + + +def average(y): + """ + Perform average/UPGMA linkage on a condensed distance matrix. + + Parameters + ---------- + y : ndarray + The upper triangular of the distance matrix. The result of + ``pdist`` is returned in this form. + + Returns + ------- + Z : ndarray + A linkage matrix containing the hierarchical clustering. See + `linkage` for more information on its structure. + + See Also + -------- + linkage : for advanced creation of hierarchical clusterings. + scipy.spatial.distance.pdist : pairwise distance metrics + + Examples + -------- + >>> from scipy.cluster.hierarchy import average, fcluster + >>> from scipy.spatial.distance import pdist + + First, we need a toy dataset to play with:: + + x x x x + x x + + x x + x x x x + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + Then, we get a condensed distance matrix from this dataset: + + >>> y = pdist(X) + + Finally, we can perform the clustering: + + >>> Z = average(y) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.20710678, 3. ], + [ 5. , 13. , 1.20710678, 3. ], + [ 8. , 14. , 1.20710678, 3. ], + [11. , 15. , 1.20710678, 3. ], + [16. , 17. , 3.39675184, 6. ], + [18. , 19. , 3.39675184, 6. ], + [20. , 21. , 4.09206523, 12. ]]) + + The linkage matrix ``Z`` represents a dendrogram - see + `scipy.cluster.hierarchy.linkage` for a detailed explanation of its + contents. + + We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster + each initial point would belong given a distance threshold: + + >>> fcluster(Z, 0.9, criterion='distance') + array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=int32) + >>> fcluster(Z, 1.5, criterion='distance') + array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32) + >>> fcluster(Z, 4, criterion='distance') + array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32) + >>> fcluster(Z, 6, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a + plot of the dendrogram. + + """ + return linkage(y, method='average', metric='euclidean') + + +def weighted(y): + """ + Perform weighted/WPGMA linkage on the condensed distance matrix. + + See `linkage` for more information on the return + structure and algorithm. + + Parameters + ---------- + y : ndarray + The upper triangular of the distance matrix. The result of + ``pdist`` is returned in this form. + + Returns + ------- + Z : ndarray + A linkage matrix containing the hierarchical clustering. See + `linkage` for more information on its structure. + + See Also + -------- + linkage : for advanced creation of hierarchical clusterings. + scipy.spatial.distance.pdist : pairwise distance metrics + + Examples + -------- + >>> from scipy.cluster.hierarchy import weighted, fcluster + >>> from scipy.spatial.distance import pdist + + First, we need a toy dataset to play with:: + + x x x x + x x + + x x + x x x x + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + Then, we get a condensed distance matrix from this dataset: + + >>> y = pdist(X) + + Finally, we can perform the clustering: + + >>> Z = weighted(y) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 9. , 11. , 1. , 2. ], + [ 2. , 12. , 1.20710678, 3. ], + [ 8. , 13. , 1.20710678, 3. ], + [ 5. , 14. , 1.20710678, 3. ], + [10. , 15. , 1.20710678, 3. ], + [18. , 19. , 3.05595762, 6. ], + [16. , 17. , 3.32379407, 6. ], + [20. , 21. , 4.06357713, 12. ]]) + + The linkage matrix ``Z`` represents a dendrogram - see + `scipy.cluster.hierarchy.linkage` for a detailed explanation of its + contents. + + We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster + each initial point would belong given a distance threshold: + + >>> fcluster(Z, 0.9, criterion='distance') + array([ 7, 8, 9, 1, 2, 3, 10, 11, 12, 4, 6, 5], dtype=int32) + >>> fcluster(Z, 1.5, criterion='distance') + array([3, 3, 3, 1, 1, 1, 4, 4, 4, 2, 2, 2], dtype=int32) + >>> fcluster(Z, 4, criterion='distance') + array([2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1], dtype=int32) + >>> fcluster(Z, 6, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a + plot of the dendrogram. + + """ + return linkage(y, method='weighted', metric='euclidean') + + +def centroid(y): + """ + Perform centroid/UPGMC linkage. + + See `linkage` for more information on the input matrix, + return structure, and algorithm. + + The following are common calling conventions: + + 1. ``Z = centroid(y)`` + + Performs centroid/UPGMC linkage on the condensed distance + matrix ``y``. + + 2. ``Z = centroid(X)`` + + Performs centroid/UPGMC linkage on the observation matrix ``X`` + using Euclidean distance as the distance metric. + + Parameters + ---------- + y : ndarray + A condensed distance matrix. A condensed + distance matrix is a flat array containing the upper + triangular of the distance matrix. This is the form that + ``pdist`` returns. Alternatively, a collection of + m observation vectors in n dimensions may be passed as + an m by n array. + + Returns + ------- + Z : ndarray + A linkage matrix containing the hierarchical clustering. See + the `linkage` function documentation for more information + on its structure. + + See Also + -------- + linkage : for advanced creation of hierarchical clusterings. + scipy.spatial.distance.pdist : pairwise distance metrics + + Examples + -------- + >>> from scipy.cluster.hierarchy import centroid, fcluster + >>> from scipy.spatial.distance import pdist + + First, we need a toy dataset to play with:: + + x x x x + x x + + x x + x x x x + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + Then, we get a condensed distance matrix from this dataset: + + >>> y = pdist(X) + + Finally, we can perform the clustering: + + >>> Z = centroid(y) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 2. , 12. , 1.11803399, 3. ], + [ 5. , 13. , 1.11803399, 3. ], + [ 8. , 15. , 1.11803399, 3. ], + [11. , 14. , 1.11803399, 3. ], + [18. , 19. , 3.33333333, 6. ], + [16. , 17. , 3.33333333, 6. ], + [20. , 21. , 3.33333333, 12. ]]) # may vary + + The linkage matrix ``Z`` represents a dendrogram - see + `scipy.cluster.hierarchy.linkage` for a detailed explanation of its + contents. + + We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster + each initial point would belong given a distance threshold: + + >>> fcluster(Z, 0.9, criterion='distance') + array([ 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6], dtype=int32) # may vary + >>> fcluster(Z, 1.1, criterion='distance') + array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32) # may vary + >>> fcluster(Z, 2, criterion='distance') + array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32) # may vary + >>> fcluster(Z, 4, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a + plot of the dendrogram. + + """ + return linkage(y, method='centroid', metric='euclidean') + + +def median(y): + """ + Perform median/WPGMC linkage. + + See `linkage` for more information on the return structure + and algorithm. + + The following are common calling conventions: + + 1. ``Z = median(y)`` + + Performs median/WPGMC linkage on the condensed distance matrix + ``y``. See ``linkage`` for more information on the return + structure and algorithm. + + 2. ``Z = median(X)`` + + Performs median/WPGMC linkage on the observation matrix ``X`` + using Euclidean distance as the distance metric. See `linkage` + for more information on the return structure and algorithm. + + Parameters + ---------- + y : ndarray + A condensed distance matrix. A condensed + distance matrix is a flat array containing the upper + triangular of the distance matrix. This is the form that + ``pdist`` returns. Alternatively, a collection of + m observation vectors in n dimensions may be passed as + an m by n array. + + Returns + ------- + Z : ndarray + The hierarchical clustering encoded as a linkage matrix. + + See Also + -------- + linkage : for advanced creation of hierarchical clusterings. + scipy.spatial.distance.pdist : pairwise distance metrics + + Examples + -------- + >>> from scipy.cluster.hierarchy import median, fcluster + >>> from scipy.spatial.distance import pdist + + First, we need a toy dataset to play with:: + + x x x x + x x + + x x + x x x x + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + Then, we get a condensed distance matrix from this dataset: + + >>> y = pdist(X) + + Finally, we can perform the clustering: + + >>> Z = median(y) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 2. , 12. , 1.11803399, 3. ], + [ 5. , 13. , 1.11803399, 3. ], + [ 8. , 15. , 1.11803399, 3. ], + [11. , 14. , 1.11803399, 3. ], + [18. , 19. , 3. , 6. ], + [16. , 17. , 3.5 , 6. ], + [20. , 21. , 3.25 , 12. ]]) + + The linkage matrix ``Z`` represents a dendrogram - see + `scipy.cluster.hierarchy.linkage` for a detailed explanation of its + contents. + + We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster + each initial point would belong given a distance threshold: + + >>> fcluster(Z, 0.9, criterion='distance') + array([ 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6], dtype=int32) + >>> fcluster(Z, 1.1, criterion='distance') + array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32) + >>> fcluster(Z, 2, criterion='distance') + array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32) + >>> fcluster(Z, 4, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a + plot of the dendrogram. + + """ + return linkage(y, method='median', metric='euclidean') + + +def ward(y): + """ + Perform Ward's linkage on a condensed distance matrix. + + See `linkage` for more information on the return structure + and algorithm. + + The following are common calling conventions: + + 1. ``Z = ward(y)`` + Performs Ward's linkage on the condensed distance matrix ``y``. + + 2. ``Z = ward(X)`` + Performs Ward's linkage on the observation matrix ``X`` using + Euclidean distance as the distance metric. + + Parameters + ---------- + y : ndarray + A condensed distance matrix. A condensed + distance matrix is a flat array containing the upper + triangular of the distance matrix. This is the form that + ``pdist`` returns. Alternatively, a collection of + m observation vectors in n dimensions may be passed as + an m by n array. + + Returns + ------- + Z : ndarray + The hierarchical clustering encoded as a linkage matrix. See + `linkage` for more information on the return structure and + algorithm. + + See Also + -------- + linkage : for advanced creation of hierarchical clusterings. + scipy.spatial.distance.pdist : pairwise distance metrics + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, fcluster + >>> from scipy.spatial.distance import pdist + + First, we need a toy dataset to play with:: + + x x x x + x x + + x x + x x x x + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + Then, we get a condensed distance matrix from this dataset: + + >>> y = pdist(X) + + Finally, we can perform the clustering: + + >>> Z = ward(y) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [11. , 15. , 1.29099445, 3. ], + [16. , 17. , 5.77350269, 6. ], + [18. , 19. , 5.77350269, 6. ], + [20. , 21. , 8.16496581, 12. ]]) + + The linkage matrix ``Z`` represents a dendrogram - see + `scipy.cluster.hierarchy.linkage` for a detailed explanation of its + contents. + + We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster + each initial point would belong given a distance threshold: + + >>> fcluster(Z, 0.9, criterion='distance') + array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=int32) + >>> fcluster(Z, 1.1, criterion='distance') + array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32) + >>> fcluster(Z, 3, criterion='distance') + array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32) + >>> fcluster(Z, 9, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a + plot of the dendrogram. + + """ + return linkage(y, method='ward', metric='euclidean') + + +def linkage(y, method='single', metric='euclidean', optimal_ordering=False): + """ + Perform hierarchical/agglomerative clustering. + + The input y may be either a 1-D condensed distance matrix + or a 2-D array of observation vectors. + + If y is a 1-D condensed distance matrix, + then y must be a :math:`\\binom{n}{2}` sized + vector, where n is the number of original observations paired + in the distance matrix. The behavior of this function is very + similar to the MATLAB linkage function. + + A :math:`(n-1)` by 4 matrix ``Z`` is returned. At the + :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and + ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A + cluster with an index less than :math:`n` corresponds to one of + the :math:`n` original observations. The distance between + clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The + fourth value ``Z[i, 3]`` represents the number of original + observations in the newly formed cluster. + + The following linkage methods are used to compute the distance + :math:`d(s, t)` between two clusters :math:`s` and + :math:`t`. The algorithm begins with a forest of clusters that + have yet to be used in the hierarchy being formed. When two + clusters :math:`s` and :math:`t` from this forest are combined + into a single cluster :math:`u`, :math:`s` and :math:`t` are + removed from the forest, and :math:`u` is added to the + forest. When only one cluster remains in the forest, the algorithm + stops, and this cluster becomes the root. + + A distance matrix is maintained at each iteration. The ``d[i,j]`` + entry corresponds to the distance between cluster :math:`i` and + :math:`j` in the original forest. + + At each iteration, the algorithm must update the distance matrix + to reflect the distance of the newly formed cluster u with the + remaining clusters in the forest. + + Suppose there are :math:`|u|` original observations + :math:`u[0], \\ldots, u[|u|-1]` in cluster :math:`u` and + :math:`|v|` original objects :math:`v[0], \\ldots, v[|v|-1]` in + cluster :math:`v`. Recall, :math:`s` and :math:`t` are + combined to form cluster :math:`u`. Let :math:`v` be any + remaining cluster in the forest that is not :math:`u`. + + The following are methods for calculating the distance between the + newly formed cluster :math:`u` and each :math:`v`. + + * method='single' assigns + + .. math:: + d(u,v) = \\min(dist(u[i],v[j])) + + for all points :math:`i` in cluster :math:`u` and + :math:`j` in cluster :math:`v`. This is also known as the + Nearest Point Algorithm. + + * method='complete' assigns + + .. math:: + d(u, v) = \\max(dist(u[i],v[j])) + + for all points :math:`i` in cluster u and :math:`j` in + cluster :math:`v`. This is also known by the Farthest Point + Algorithm or Voor Hees Algorithm. + + * method='average' assigns + + .. math:: + d(u,v) = \\sum_{ij} \\frac{d(u[i], v[j])} + {(|u|*|v|)} + + for all points :math:`i` and :math:`j` where :math:`|u|` + and :math:`|v|` are the cardinalities of clusters :math:`u` + and :math:`v`, respectively. This is also called the UPGMA + algorithm. + + * method='weighted' assigns + + .. math:: + d(u,v) = (dist(s,v) + dist(t,v))/2 + + where cluster u was formed with cluster s and t and v + is a remaining cluster in the forest (also called WPGMA). + + * method='centroid' assigns + + .. math:: + dist(s,t) = ||c_s-c_t||_2 + + where :math:`c_s` and :math:`c_t` are the centroids of + clusters :math:`s` and :math:`t`, respectively. When two + clusters :math:`s` and :math:`t` are combined into a new + cluster :math:`u`, the new centroid is computed over all the + original objects in clusters :math:`s` and :math:`t`. The + distance then becomes the Euclidean distance between the + centroid of :math:`u` and the centroid of a remaining cluster + :math:`v` in the forest. This is also known as the UPGMC + algorithm. + + * method='median' assigns :math:`d(s,t)` like the ``centroid`` + method. When two clusters :math:`s` and :math:`t` are combined + into a new cluster :math:`u`, the average of centroids s and t + give the new centroid :math:`u`. This is also known as the + WPGMC algorithm. + + * method='ward' uses the Ward variance minimization algorithm. + The new entry :math:`d(u,v)` is computed as follows, + + .. math:: + + d(u,v) = \\sqrt{\\frac{|v|+|s|} + {T}d(v,s)^2 + + \\frac{|v|+|t|} + {T}d(v,t)^2 + - \\frac{|v|} + {T}d(s,t)^2} + + where :math:`u` is the newly joined cluster consisting of + clusters :math:`s` and :math:`t`, :math:`v` is an unused + cluster in the forest, :math:`T=|v|+|s|+|t|`, and + :math:`|*|` is the cardinality of its argument. This is also + known as the incremental algorithm. + + Warning: When the minimum distance pair in the forest is chosen, there + may be two or more pairs with the same minimum distance. This + implementation may choose a different minimum than the MATLAB + version. + + Parameters + ---------- + y : ndarray + A condensed distance matrix. A condensed distance matrix + is a flat array containing the upper triangular of the distance matrix. + This is the form that ``pdist`` returns. Alternatively, a collection of + :math:`m` observation vectors in :math:`n` dimensions may be passed as + an :math:`m` by :math:`n` array. All elements of the condensed distance + matrix must be finite, i.e., no NaNs or infs. + method : str, optional + The linkage algorithm to use. See the ``Linkage Methods`` section below + for full descriptions. + metric : str or function, optional + The distance metric to use in the case that y is a collection of + observation vectors; ignored otherwise. See the ``pdist`` + function for a list of valid distance metrics. A custom distance + function can also be used. + optimal_ordering : bool, optional + If True, the linkage matrix will be reordered so that the distance + between successive leaves is minimal. This results in a more intuitive + tree structure when the data are visualized. defaults to False, because + this algorithm can be slow, particularly on large datasets [2]_. See + also the `optimal_leaf_ordering` function. + + .. versionadded:: 1.0.0 + + Returns + ------- + Z : ndarray + The hierarchical clustering encoded as a linkage matrix. + + Notes + ----- + 1. For method 'single', an optimized algorithm based on minimum spanning + tree is implemented. It has time complexity :math:`O(n^2)`. + For methods 'complete', 'average', 'weighted' and 'ward', an algorithm + called nearest-neighbors chain is implemented. It also has time + complexity :math:`O(n^2)`. + For other methods, a naive algorithm is implemented with :math:`O(n^3)` + time complexity. + All algorithms use :math:`O(n^2)` memory. + Refer to [1]_ for details about the algorithms. + 2. Methods 'centroid', 'median', and 'ward' are correctly defined only if + Euclidean pairwise metric is used. If `y` is passed as precomputed + pairwise distances, then it is the user's responsibility to assure that + these distances are in fact Euclidean, otherwise the produced result + will be incorrect. + + See Also + -------- + scipy.spatial.distance.pdist : pairwise distance metrics + + References + ---------- + .. [1] Daniel Mullner, "Modern hierarchical, agglomerative clustering + algorithms", :arXiv:`1109.2378v1`. + .. [2] Ziv Bar-Joseph, David K. Gifford, Tommi S. Jaakkola, "Fast optimal + leaf ordering for hierarchical clustering", 2001. Bioinformatics + :doi:`10.1093/bioinformatics/17.suppl_1.S22` + + Examples + -------- + >>> from scipy.cluster.hierarchy import dendrogram, linkage + >>> from matplotlib import pyplot as plt + >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]] + + >>> Z = linkage(X, 'ward') + >>> fig = plt.figure(figsize=(25, 10)) + >>> dn = dendrogram(Z) + + >>> Z = linkage(X, 'single') + >>> fig = plt.figure(figsize=(25, 10)) + >>> dn = dendrogram(Z) + >>> plt.show() + """ + xp = array_namespace(y) + y = _asarray(y, order='C', dtype=xp.float64, xp=xp) + + if method not in _LINKAGE_METHODS: + raise ValueError(f"Invalid method: {method}") + + if method in _EUCLIDEAN_METHODS and metric != 'euclidean' and y.ndim == 2: + msg = f"`method={method}` requires the distance metric to be Euclidean" + raise ValueError(msg) + + if y.ndim == 1: + distance.is_valid_y(y, throw=True, name='y') + elif y.ndim == 2: + if (y.shape[0] == y.shape[1] and np.allclose(np.diag(y), 0) and + xp.all(y >= 0) and np.allclose(y, y.T)): + warnings.warn('The symmetric non-negative hollow observation ' + 'matrix looks suspiciously like an uncondensed ' + 'distance matrix', + ClusterWarning, stacklevel=2) + y = distance.pdist(y, metric) + y = xp.asarray(y) + else: + raise ValueError("`y` must be 1 or 2 dimensional.") + + if not xp.all(xp.isfinite(y)): + raise ValueError("The condensed distance matrix must contain only " + "finite values.") + + n = int(distance.num_obs_y(y)) + method_code = _LINKAGE_METHODS[method] + + y = np.asarray(y) + if method == 'single': + result = _hierarchy.mst_single_linkage(y, n) + elif method in ['complete', 'average', 'weighted', 'ward']: + result = _hierarchy.nn_chain(y, n, method_code) + else: + result = _hierarchy.fast_linkage(y, n, method_code) + result = xp.asarray(result) + + if optimal_ordering: + y = xp.asarray(y) + return optimal_leaf_ordering(result, y) + else: + return result + + +class ClusterNode: + """ + A tree node class for representing a cluster. + + Leaf nodes correspond to original observations, while non-leaf nodes + correspond to non-singleton clusters. + + The `to_tree` function converts a matrix returned by the linkage + function into an easy-to-use tree representation. + + All parameter names are also attributes. + + Parameters + ---------- + id : int + The node id. + left : ClusterNode instance, optional + The left child tree node. + right : ClusterNode instance, optional + The right child tree node. + dist : float, optional + Distance for this cluster in the linkage matrix. + count : int, optional + The number of samples in this cluster. + + See Also + -------- + to_tree : for converting a linkage matrix ``Z`` into a tree object. + + """ + + def __init__(self, id, left=None, right=None, dist=0.0, count=1): + if id < 0: + raise ValueError('The id must be non-negative.') + if dist < 0: + raise ValueError('The distance must be non-negative.') + if (left is None and right is not None) or \ + (left is not None and right is None): + raise ValueError('Only full or proper binary trees are permitted.' + ' This node has one child.') + if count < 1: + raise ValueError('A cluster must contain at least one original ' + 'observation.') + self.id = id + self.left = left + self.right = right + self.dist = dist + if self.left is None: + self.count = count + else: + self.count = left.count + right.count + + def __lt__(self, node): + if not isinstance(node, ClusterNode): + raise ValueError("Can't compare ClusterNode " + f"to type {type(node)}") + return self.dist < node.dist + + def __gt__(self, node): + if not isinstance(node, ClusterNode): + raise ValueError("Can't compare ClusterNode " + f"to type {type(node)}") + return self.dist > node.dist + + def __eq__(self, node): + if not isinstance(node, ClusterNode): + raise ValueError("Can't compare ClusterNode " + f"to type {type(node)}") + return self.dist == node.dist + + def get_id(self): + """ + The identifier of the target node. + + For ``0 <= i < n``, `i` corresponds to original observation i. + For ``n <= i < 2n-1``, `i` corresponds to non-singleton cluster formed + at iteration ``i-n``. + + Returns + ------- + id : int + The identifier of the target node. + + """ + return self.id + + def get_count(self): + """ + The number of leaf nodes (original observations) belonging to + the cluster node nd. If the target node is a leaf, 1 is + returned. + + Returns + ------- + get_count : int + The number of leaf nodes below the target node. + + """ + return self.count + + def get_left(self): + """ + Return a reference to the left child tree object. + + Returns + ------- + left : ClusterNode + The left child of the target node. If the node is a leaf, + None is returned. + + """ + return self.left + + def get_right(self): + """ + Return a reference to the right child tree object. + + Returns + ------- + right : ClusterNode + The left child of the target node. If the node is a leaf, + None is returned. + + """ + return self.right + + def is_leaf(self): + """ + Return True if the target node is a leaf. + + Returns + ------- + leafness : bool + True if the target node is a leaf node. + + """ + return self.left is None + + def pre_order(self, func=(lambda x: x.id)): + """ + Perform pre-order traversal without recursive function calls. + + When a leaf node is first encountered, ``func`` is called with + the leaf node as its argument, and its result is appended to + the list. + + For example, the statement:: + + ids = root.pre_order(lambda x: x.id) + + returns a list of the node ids corresponding to the leaf nodes + of the tree as they appear from left to right. + + Parameters + ---------- + func : function + Applied to each leaf ClusterNode object in the pre-order traversal. + Given the ``i``-th leaf node in the pre-order traversal ``n[i]``, + the result of ``func(n[i])`` is stored in ``L[i]``. If not + provided, the index of the original observation to which the node + corresponds is used. + + Returns + ------- + L : list + The pre-order traversal. + + """ + # Do a preorder traversal, caching the result. To avoid having to do + # recursion, we'll store the previous index we've visited in a vector. + n = self.count + + curNode = [None] * (2 * n) + lvisited = set() + rvisited = set() + curNode[0] = self + k = 0 + preorder = [] + while k >= 0: + nd = curNode[k] + ndid = nd.id + if nd.is_leaf(): + preorder.append(func(nd)) + k = k - 1 + else: + if ndid not in lvisited: + curNode[k + 1] = nd.left + lvisited.add(ndid) + k = k + 1 + elif ndid not in rvisited: + curNode[k + 1] = nd.right + rvisited.add(ndid) + k = k + 1 + # If we've visited the left and right of this non-leaf + # node already, go up in the tree. + else: + k = k - 1 + + return preorder + + +_cnode_bare = ClusterNode(0) +_cnode_type = type(ClusterNode) + + +def _order_cluster_tree(Z): + """ + Return clustering nodes in bottom-up order by distance. + + Parameters + ---------- + Z : scipy.cluster.linkage array + The linkage matrix. + + Returns + ------- + nodes : list + A list of ClusterNode objects. + """ + q = deque() + tree = to_tree(Z) + q.append(tree) + nodes = [] + + while q: + node = q.popleft() + if not node.is_leaf(): + bisect.insort_left(nodes, node) + q.append(node.get_right()) + q.append(node.get_left()) + return nodes + + +def cut_tree(Z, n_clusters=None, height=None): + """ + Given a linkage matrix Z, return the cut tree. + + Parameters + ---------- + Z : scipy.cluster.linkage array + The linkage matrix. + n_clusters : array_like, optional + Number of clusters in the tree at the cut point. + height : array_like, optional + The height at which to cut the tree. Only possible for ultrametric + trees. + + Returns + ------- + cutree : array + An array indicating group membership at each agglomeration step. I.e., + for a full cut tree, in the first column each data point is in its own + cluster. At the next step, two nodes are merged. Finally, all + singleton and non-singleton clusters are in one group. If `n_clusters` + or `height` are given, the columns correspond to the columns of + `n_clusters` or `height`. + + Examples + -------- + >>> from scipy import cluster + >>> import numpy as np + >>> from numpy.random import default_rng + >>> rng = default_rng() + >>> X = rng.random((50, 4)) + >>> Z = cluster.hierarchy.ward(X) + >>> cutree = cluster.hierarchy.cut_tree(Z, n_clusters=[5, 10]) + >>> cutree[:10] + array([[0, 0], + [1, 1], + [2, 2], + [3, 3], + [3, 4], + [2, 2], + [0, 0], + [1, 5], + [3, 6], + [4, 7]]) # random + + """ + xp = array_namespace(Z) + nobs = num_obs_linkage(Z) + nodes = _order_cluster_tree(Z) + + if height is not None and n_clusters is not None: + raise ValueError("At least one of either height or n_clusters " + "must be None") + elif height is None and n_clusters is None: # return the full cut tree + cols_idx = xp.arange(nobs) + elif height is not None: + height = xp.asarray(height) + heights = xp.asarray([x.dist for x in nodes]) + cols_idx = xp.searchsorted(heights, height) + else: + n_clusters = xp.asarray(n_clusters) + cols_idx = nobs - xp.searchsorted(xp.arange(nobs), n_clusters) + + try: + n_cols = len(cols_idx) + except TypeError: # scalar + n_cols = 1 + cols_idx = xp.asarray([cols_idx]) + + groups = xp.zeros((n_cols, nobs), dtype=xp.int64) + last_group = xp.arange(nobs) + if 0 in cols_idx: + groups[0] = last_group + + for i, node in enumerate(nodes): + idx = node.pre_order() + this_group = xp_copy(last_group, xp=xp) + # TODO ARRAY_API complex indexing not supported + this_group[idx] = xp.min(last_group[idx]) + this_group[this_group > xp.max(last_group[idx])] -= 1 + if i + 1 in cols_idx: + groups[np.nonzero(i + 1 == cols_idx)[0]] = this_group + last_group = this_group + + return groups.T + + +def to_tree(Z, rd=False): + """ + Convert a linkage matrix into an easy-to-use tree object. + + The reference to the root `ClusterNode` object is returned (by default). + + Each `ClusterNode` object has a ``left``, ``right``, ``dist``, ``id``, + and ``count`` attribute. The left and right attributes point to + ClusterNode objects that were combined to generate the cluster. + If both are None then the `ClusterNode` object is a leaf node, its count + must be 1, and its distance is meaningless but set to 0. + + *Note: This function is provided for the convenience of the library + user. ClusterNodes are not used as input to any of the functions in this + library.* + + Parameters + ---------- + Z : ndarray + The linkage matrix in proper form (see the `linkage` + function documentation). + rd : bool, optional + When False (default), a reference to the root `ClusterNode` object is + returned. Otherwise, a tuple ``(r, d)`` is returned. ``r`` is a + reference to the root node while ``d`` is a list of `ClusterNode` + objects - one per original entry in the linkage matrix plus entries + for all clustering steps. If a cluster id is + less than the number of samples ``n`` in the data that the linkage + matrix describes, then it corresponds to a singleton cluster (leaf + node). + See `linkage` for more information on the assignment of cluster ids + to clusters. + + Returns + ------- + tree : ClusterNode or tuple (ClusterNode, list of ClusterNode) + If ``rd`` is False, a `ClusterNode`. + If ``rd`` is True, a list of length ``2*n - 1``, with ``n`` the number + of samples. See the description of `rd` above for more details. + + See Also + -------- + linkage, is_valid_linkage, ClusterNode + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster import hierarchy + >>> rng = np.random.default_rng() + >>> x = rng.random((5, 2)) + >>> Z = hierarchy.linkage(x) + >>> hierarchy.to_tree(Z) + >> rootnode, nodelist = hierarchy.to_tree(Z, rd=True) + >>> rootnode + >> len(nodelist) + 9 + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='c', xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + # Number of original objects is equal to the number of rows plus 1. + n = Z.shape[0] + 1 + + # Create a list full of None's to store the node objects + d = [None] * (n * 2 - 1) + + # Create the nodes corresponding to the n original objects. + for i in range(0, n): + d[i] = ClusterNode(i) + + nd = None + + for i in range(Z.shape[0]): + row = Z[i, :] + + fi = int_floor(row[0], xp) + fj = int_floor(row[1], xp) + if fi > i + n: + raise ValueError(('Corrupt matrix Z. Index to derivative cluster ' + 'is used before it is formed. See row %d, ' + 'column 0') % fi) + if fj > i + n: + raise ValueError(('Corrupt matrix Z. Index to derivative cluster ' + 'is used before it is formed. See row %d, ' + 'column 1') % fj) + + nd = ClusterNode(i + n, d[fi], d[fj], row[2]) + # ^ id ^ left ^ right ^ dist + if row[3] != nd.count: + raise ValueError(('Corrupt matrix Z. The count Z[%d,3] is ' + 'incorrect.') % i) + d[n + i] = nd + + if rd: + return (nd, d) + else: + return nd + + +def optimal_leaf_ordering(Z, y, metric='euclidean'): + """ + Given a linkage matrix Z and distance, reorder the cut tree. + + Parameters + ---------- + Z : ndarray + The hierarchical clustering encoded as a linkage matrix. See + `linkage` for more information on the return structure and + algorithm. + y : ndarray + The condensed distance matrix from which Z was generated. + Alternatively, a collection of m observation vectors in n + dimensions may be passed as an m by n array. + metric : str or function, optional + The distance metric to use in the case that y is a collection of + observation vectors; ignored otherwise. See the ``pdist`` + function for a list of valid distance metrics. A custom distance + function can also be used. + + Returns + ------- + Z_ordered : ndarray + A copy of the linkage matrix Z, reordered to minimize the distance + between adjacent leaves. + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster import hierarchy + >>> rng = np.random.default_rng() + >>> X = rng.standard_normal((10, 10)) + >>> Z = hierarchy.ward(X) + >>> hierarchy.leaves_list(Z) + array([0, 3, 1, 9, 2, 5, 7, 4, 6, 8], dtype=int32) + >>> hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, X)) + array([3, 0, 2, 5, 7, 4, 8, 6, 9, 1], dtype=int32) + + """ + xp = array_namespace(Z, y) + Z = _asarray(Z, order='C', xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + y = _asarray(y, order='C', dtype=xp.float64, xp=xp) + + if y.ndim == 1: + distance.is_valid_y(y, throw=True, name='y') + elif y.ndim == 2: + if (y.shape[0] == y.shape[1] and np.allclose(np.diag(y), 0) and + np.all(y >= 0) and np.allclose(y, y.T)): + warnings.warn('The symmetric non-negative hollow observation ' + 'matrix looks suspiciously like an uncondensed ' + 'distance matrix', + ClusterWarning, stacklevel=2) + y = distance.pdist(y, metric) + y = xp.asarray(y) + else: + raise ValueError("`y` must be 1 or 2 dimensional.") + + if not xp.all(xp.isfinite(y)): + raise ValueError("The condensed distance matrix must contain only " + "finite values.") + + Z = np.asarray(Z) + y = np.asarray(y) + return xp.asarray(_optimal_leaf_ordering.optimal_leaf_ordering(Z, y)) + + +def cophenet(Z, Y=None): + """ + Calculate the cophenetic distances between each observation in + the hierarchical clustering defined by the linkage ``Z``. + + Suppose ``p`` and ``q`` are original observations in + disjoint clusters ``s`` and ``t``, respectively and + ``s`` and ``t`` are joined by a direct parent cluster + ``u``. The cophenetic distance between observations + ``i`` and ``j`` is simply the distance between + clusters ``s`` and ``t``. + + Parameters + ---------- + Z : ndarray + The hierarchical clustering encoded as an array + (see `linkage` function). + Y : ndarray (optional) + Calculates the cophenetic correlation coefficient ``c`` of a + hierarchical clustering defined by the linkage matrix `Z` + of a set of :math:`n` observations in :math:`m` + dimensions. `Y` is the condensed distance matrix from which + `Z` was generated. + + Returns + ------- + c : ndarray + The cophentic correlation distance (if ``Y`` is passed). + d : ndarray + The cophenetic distance matrix in condensed form. The + :math:`ij` th entry is the cophenetic distance between + original observations :math:`i` and :math:`j`. + + See Also + -------- + linkage : + for a description of what a linkage matrix is. + scipy.spatial.distance.squareform : + transforming condensed matrices into square ones. + + Examples + -------- + >>> from scipy.cluster.hierarchy import single, cophenet + >>> from scipy.spatial.distance import pdist, squareform + + Given a dataset ``X`` and a linkage matrix ``Z``, the cophenetic distance + between two points of ``X`` is the distance between the largest two + distinct clusters that each of the points: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + ``X`` corresponds to this dataset :: + + x x x x + x x + + x x + x x x x + + >>> Z = single(pdist(X)) + >>> Z + array([[ 0., 1., 1., 2.], + [ 2., 12., 1., 3.], + [ 3., 4., 1., 2.], + [ 5., 14., 1., 3.], + [ 6., 7., 1., 2.], + [ 8., 16., 1., 3.], + [ 9., 10., 1., 2.], + [11., 18., 1., 3.], + [13., 15., 2., 6.], + [17., 20., 2., 9.], + [19., 21., 2., 12.]]) + >>> cophenet(Z) + array([1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 2., 2., 2., 2., 2., + 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 2., 2., + 2., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., + 1., 1., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 1., 1., 1.]) + + The output of the `scipy.cluster.hierarchy.cophenet` method is + represented in condensed form. We can use + `scipy.spatial.distance.squareform` to see the output as a + regular matrix (where each element ``ij`` denotes the cophenetic distance + between each ``i``, ``j`` pair of points in ``X``): + + >>> squareform(cophenet(Z)) + array([[0., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.], + [1., 0., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.], + [1., 1., 0., 2., 2., 2., 2., 2., 2., 2., 2., 2.], + [2., 2., 2., 0., 1., 1., 2., 2., 2., 2., 2., 2.], + [2., 2., 2., 1., 0., 1., 2., 2., 2., 2., 2., 2.], + [2., 2., 2., 1., 1., 0., 2., 2., 2., 2., 2., 2.], + [2., 2., 2., 2., 2., 2., 0., 1., 1., 2., 2., 2.], + [2., 2., 2., 2., 2., 2., 1., 0., 1., 2., 2., 2.], + [2., 2., 2., 2., 2., 2., 1., 1., 0., 2., 2., 2.], + [2., 2., 2., 2., 2., 2., 2., 2., 2., 0., 1., 1.], + [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 0., 1.], + [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 0.]]) + + In this example, the cophenetic distance between points on ``X`` that are + very close (i.e., in the same corner) is 1. For other pairs of points is 2, + because the points will be located in clusters at different + corners - thus, the distance between these clusters will be larger. + + """ + xp = array_namespace(Z, Y) + # Ensure float64 C-contiguous array. Cython code doesn't deal with striding. + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + n = Z.shape[0] + 1 + zz = np.zeros((n * (n-1)) // 2, dtype=np.float64) + + Z = np.asarray(Z) + _hierarchy.cophenetic_distances(Z, zz, int(n)) + zz = xp.asarray(zz) + if Y is None: + return zz + + Y = _asarray(Y, order='C', xp=xp) + distance.is_valid_y(Y, throw=True, name='Y') + + z = xp.mean(zz) + y = xp.mean(Y) + Yy = Y - y + Zz = zz - z + numerator = (Yy * Zz) + denomA = Yy**2 + denomB = Zz**2 + c = xp.sum(numerator) / xp.sqrt(xp.sum(denomA) * xp.sum(denomB)) + return (c, zz) + + +def inconsistent(Z, d=2): + r""" + Calculate inconsistency statistics on a linkage matrix. + + Parameters + ---------- + Z : ndarray + The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical + clustering). See `linkage` documentation for more information on its + form. + d : int, optional + The number of links up to `d` levels below each non-singleton cluster. + + Returns + ------- + R : ndarray + A :math:`(n-1)` by 4 matrix where the ``i``'th row contains the link + statistics for the non-singleton cluster ``i``. The link statistics are + computed over the link heights for links :math:`d` levels below the + cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard + deviation of the link heights, respectively; ``R[i,2]`` is the number + of links included in the calculation; and ``R[i,3]`` is the + inconsistency coefficient, + + .. math:: \frac{\mathtt{Z[i,2]} - \mathtt{R[i,0]}} {R[i,1]} + + Notes + ----- + This function behaves similarly to the MATLAB(TM) ``inconsistent`` + function. + + Examples + -------- + >>> from scipy.cluster.hierarchy import inconsistent, linkage + >>> from matplotlib import pyplot as plt + >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]] + >>> Z = linkage(X, 'ward') + >>> print(Z) + [[ 5. 6. 0. 2. ] + [ 2. 7. 0. 2. ] + [ 0. 4. 1. 2. ] + [ 1. 8. 1.15470054 3. ] + [ 9. 10. 2.12132034 4. ] + [ 3. 12. 4.11096096 5. ] + [11. 13. 14.07183949 8. ]] + >>> inconsistent(Z) + array([[ 0. , 0. , 1. , 0. ], + [ 0. , 0. , 1. , 0. ], + [ 1. , 0. , 1. , 0. ], + [ 0.57735027, 0.81649658, 2. , 0.70710678], + [ 1.04044011, 1.06123822, 3. , 1.01850858], + [ 3.11614065, 1.40688837, 2. , 0.70710678], + [ 6.44583366, 6.76770586, 3. , 1.12682288]]) + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + if (not d == np.floor(d)) or d < 0: + raise ValueError('The second argument d must be a nonnegative ' + 'integer value.') + + n = Z.shape[0] + 1 + R = np.zeros((n - 1, 4), dtype=np.float64) + + Z = np.asarray(Z) + _hierarchy.inconsistent(Z, R, int(n), int(d)) + R = xp.asarray(R) + return R + + +def from_mlab_linkage(Z): + """ + Convert a linkage matrix generated by MATLAB(TM) to a new + linkage matrix compatible with this module. + + The conversion does two things: + + * the indices are converted from ``1..N`` to ``0..(N-1)`` form, + and + + * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the + number of original observations (leaves) in the non-singleton + cluster ``i``. + + This function is useful when loading in linkages from legacy data + files generated by MATLAB. + + Parameters + ---------- + Z : ndarray + A linkage matrix generated by MATLAB(TM). + + Returns + ------- + ZS : ndarray + A linkage matrix compatible with ``scipy.cluster.hierarchy``. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + to_mlab_linkage : transform from SciPy to MATLAB format. + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster.hierarchy import ward, from_mlab_linkage + + Given a linkage matrix in MATLAB format ``mZ``, we can use + `scipy.cluster.hierarchy.from_mlab_linkage` to import + it into SciPy format: + + >>> mZ = np.array([[1, 2, 1], [4, 5, 1], [7, 8, 1], + ... [10, 11, 1], [3, 13, 1.29099445], + ... [6, 14, 1.29099445], + ... [9, 15, 1.29099445], + ... [12, 16, 1.29099445], + ... [17, 18, 5.77350269], + ... [19, 20, 5.77350269], + ... [21, 22, 8.16496581]]) + + >>> Z = from_mlab_linkage(mZ) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [ 11. , 15. , 1.29099445, 3. ], + [ 16. , 17. , 5.77350269, 6. ], + [ 18. , 19. , 5.77350269, 6. ], + [ 20. , 21. , 8.16496581, 12. ]]) + + As expected, the linkage matrix ``Z`` returned includes an + additional column counting the number of original samples in + each cluster. Also, all cluster indices are reduced by 1 + (MATLAB format uses 1-indexing, whereas SciPy uses 0-indexing). + + """ + xp = array_namespace(Z) + Z = _asarray(Z, dtype=xp.float64, order='C', xp=xp) + Zs = Z.shape + + # If it's empty, return it. + if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0): + return xp_copy(Z, xp=xp) + + if len(Zs) != 2: + raise ValueError("The linkage array must be rectangular.") + + # If it contains no rows, return it. + if Zs[0] == 0: + return xp_copy(Z, xp=xp) + + if xp.min(Z[:, 0:2]) != 1.0 and xp.max(Z[:, 0:2]) != 2 * Zs[0]: + raise ValueError('The format of the indices is not 1..N') + + Zpart = xp.concat((Z[:, 0:2] - 1.0, Z[:, 2:]), axis=1) + CS = np.zeros((Zs[0],), dtype=np.float64) + if is_jax(xp): + # calculate_cluster_sizes doesn't accept read-only arrays + Zpart = np.array(Zpart, copy=True) + else: + Zpart = np.asarray(Zpart) + _hierarchy.calculate_cluster_sizes(Zpart, CS, int(Zs[0]) + 1) + res = np.hstack([Zpart, CS.reshape(Zs[0], 1)]) + return xp.asarray(res) + + +def to_mlab_linkage(Z): + """ + Convert a linkage matrix to a MATLAB(TM) compatible one. + + Converts a linkage matrix ``Z`` generated by the linkage function + of this module to a MATLAB(TM) compatible one. The return linkage + matrix has the last column removed and the cluster indices are + converted to ``1..N`` indexing. + + Parameters + ---------- + Z : ndarray + A linkage matrix generated by ``scipy.cluster.hierarchy``. + + Returns + ------- + to_mlab_linkage : ndarray + A linkage matrix compatible with MATLAB(TM)'s hierarchical + clustering functions. + + The return linkage matrix has the last column removed + and the cluster indices are converted to ``1..N`` indexing. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + from_mlab_linkage : transform from Matlab to SciPy format. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, to_mlab_linkage + >>> from scipy.spatial.distance import pdist + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [11. , 15. , 1.29099445, 3. ], + [16. , 17. , 5.77350269, 6. ], + [18. , 19. , 5.77350269, 6. ], + [20. , 21. , 8.16496581, 12. ]]) + + After a linkage matrix ``Z`` has been created, we can use + `scipy.cluster.hierarchy.to_mlab_linkage` to convert it + into MATLAB format: + + >>> mZ = to_mlab_linkage(Z) + >>> mZ + array([[ 1. , 2. , 1. ], + [ 4. , 5. , 1. ], + [ 7. , 8. , 1. ], + [ 10. , 11. , 1. ], + [ 3. , 13. , 1.29099445], + [ 6. , 14. , 1.29099445], + [ 9. , 15. , 1.29099445], + [ 12. , 16. , 1.29099445], + [ 17. , 18. , 5.77350269], + [ 19. , 20. , 5.77350269], + [ 21. , 22. , 8.16496581]]) + + The new linkage matrix ``mZ`` uses 1-indexing for all the + clusters (instead of 0-indexing). Also, the last column of + the original linkage matrix has been dropped. + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + Zs = Z.shape + if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0): + return xp_copy(Z, xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + return xp.concat((Z[:, :2] + 1.0, Z[:, 2:3]), axis=1) + + +def is_monotonic(Z): + """ + Return True if the linkage passed is monotonic. + + The linkage is monotonic if for every cluster :math:`s` and :math:`t` + joined, the distance between them is no less than the distance + between any previously joined clusters. + + Parameters + ---------- + Z : ndarray + The linkage matrix to check for monotonicity. + + Returns + ------- + b : bool + A boolean indicating whether the linkage is monotonic. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + + Examples + -------- + >>> from scipy.cluster.hierarchy import median, ward, is_monotonic + >>> from scipy.spatial.distance import pdist + + By definition, some hierarchical clustering algorithms - such as + `scipy.cluster.hierarchy.ward` - produce monotonic assignments of + samples to clusters; however, this is not always true for other + hierarchical methods - e.g. `scipy.cluster.hierarchy.median`. + + Given a linkage matrix ``Z`` (as the result of a hierarchical clustering + method) we can test programmatically whether it has the monotonicity + property or not, using `scipy.cluster.hierarchy.is_monotonic`: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [11. , 15. , 1.29099445, 3. ], + [16. , 17. , 5.77350269, 6. ], + [18. , 19. , 5.77350269, 6. ], + [20. , 21. , 8.16496581, 12. ]]) + >>> is_monotonic(Z) + True + + >>> Z = median(pdist(X)) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 2. , 12. , 1.11803399, 3. ], + [ 5. , 13. , 1.11803399, 3. ], + [ 8. , 15. , 1.11803399, 3. ], + [11. , 14. , 1.11803399, 3. ], + [18. , 19. , 3. , 6. ], + [16. , 17. , 3.5 , 6. ], + [20. , 21. , 3.25 , 12. ]]) + >>> is_monotonic(Z) + False + + Note that this method is equivalent to just verifying that the distances + in the third column of the linkage matrix appear in a monotonically + increasing order. + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='c', xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + # We expect the i'th value to be greater than its successor. + return xp.all(Z[1:, 2] >= Z[:-1, 2]) + + +def is_valid_im(R, warning=False, throw=False, name=None): + """Return True if the inconsistency matrix passed is valid. + + It must be a :math:`n` by 4 array of doubles. The standard + deviations ``R[:,1]`` must be nonnegative. The link counts + ``R[:,2]`` must be positive and no greater than :math:`n-1`. + + Parameters + ---------- + R : ndarray + The inconsistency matrix to check for validity. + warning : bool, optional + When True, issues a Python warning if the linkage + matrix passed is invalid. + throw : bool, optional + When True, throws a Python exception if the linkage + matrix passed is invalid. + name : str, optional + This string refers to the variable name of the invalid + linkage matrix. + + Returns + ------- + b : bool + True if the inconsistency matrix is valid. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + inconsistent : for the creation of a inconsistency matrix. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, inconsistent, is_valid_im + >>> from scipy.spatial.distance import pdist + + Given a data set ``X``, we can apply a clustering method to obtain a + linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can + be also used to obtain the inconsistency matrix ``R`` associated to + this clustering process: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + >>> R = inconsistent(Z) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [11. , 15. , 1.29099445, 3. ], + [16. , 17. , 5.77350269, 6. ], + [18. , 19. , 5.77350269, 6. ], + [20. , 21. , 8.16496581, 12. ]]) + >>> R + array([[1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1.14549722, 0.20576415, 2. , 0.70710678], + [1.14549722, 0.20576415, 2. , 0.70710678], + [1.14549722, 0.20576415, 2. , 0.70710678], + [1.14549722, 0.20576415, 2. , 0.70710678], + [2.78516386, 2.58797734, 3. , 1.15470054], + [2.78516386, 2.58797734, 3. , 1.15470054], + [6.57065706, 1.38071187, 3. , 1.15470054]]) + + Now we can use `scipy.cluster.hierarchy.is_valid_im` to verify that + ``R`` is correct: + + >>> is_valid_im(R) + True + + However, if ``R`` is wrongly constructed (e.g., one of the standard + deviations is set to a negative value), then the check will fail: + + >>> R[-1,1] = R[-1,1] * -1 + >>> is_valid_im(R) + False + + """ + xp = array_namespace(R) + R = _asarray(R, order='c', xp=xp) + valid = True + name_str = f"{name!r} " if name else '' + try: + if R.dtype != xp.float64: + raise TypeError(f'Inconsistency matrix {name_str}must contain doubles ' + '(double).') + if len(R.shape) != 2: + raise ValueError(f'Inconsistency matrix {name_str}must have shape=2 (i.e. ' + 'be two-dimensional).') + if R.shape[1] != 4: + raise ValueError(f'Inconsistency matrix {name_str}' + 'must have 4 columns.') + if R.shape[0] < 1: + raise ValueError(f'Inconsistency matrix {name_str}' + 'must have at least one row.') + if xp.any(R[:, 0] < 0): + raise ValueError(f'Inconsistency matrix {name_str}' + 'contains negative link height means.') + if xp.any(R[:, 1] < 0): + raise ValueError(f'Inconsistency matrix {name_str}' + 'contains negative link height standard deviations.') + if xp.any(R[:, 2] < 0): + raise ValueError(f'Inconsistency matrix {name_str}' + 'contains negative link counts.') + except Exception as e: + if throw: + raise + if warning: + _warning(str(e)) + valid = False + + return valid + + +def is_valid_linkage(Z, warning=False, throw=False, name=None): + """ + Check the validity of a linkage matrix. + + A linkage matrix is valid if it is a 2-D array (type double) + with :math:`n` rows and 4 columns. The first two columns must contain + indices between 0 and :math:`2n-1`. For a given row ``i``, the following + two expressions have to hold: + + .. math:: + + 0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1 + 0 \\leq Z[i,1] \\leq i+n-1 + + I.e., a cluster cannot join another cluster unless the cluster being joined + has been generated. + + The fourth column of `Z` represents the number of original observations + in a cluster, so a valid ``Z[i, 3]`` value may not exceed the number of + original observations. + + Parameters + ---------- + Z : array_like + Linkage matrix. + warning : bool, optional + When True, issues a Python warning if the linkage + matrix passed is invalid. + throw : bool, optional + When True, throws a Python exception if the linkage + matrix passed is invalid. + name : str, optional + This string refers to the variable name of the invalid + linkage matrix. + + Returns + ------- + b : bool + True if the inconsistency matrix is valid. + + See Also + -------- + linkage: for a description of what a linkage matrix is. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, is_valid_linkage + >>> from scipy.spatial.distance import pdist + + All linkage matrices generated by the clustering methods in this module + will be valid (i.e., they will have the appropriate dimensions and the two + required expressions will hold for all the rows). + + We can check this using `scipy.cluster.hierarchy.is_valid_linkage`: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [11. , 15. , 1.29099445, 3. ], + [16. , 17. , 5.77350269, 6. ], + [18. , 19. , 5.77350269, 6. ], + [20. , 21. , 8.16496581, 12. ]]) + >>> is_valid_linkage(Z) + True + + However, if we create a linkage matrix in a wrong way - or if we modify + a valid one in a way that any of the required expressions don't hold + anymore, then the check will fail: + + >>> Z[3][1] = 20 # the cluster number 20 is not defined at this point + >>> is_valid_linkage(Z) + False + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='c', xp=xp) + valid = True + name_str = f"{name!r} " if name else '' + try: + if Z.dtype != xp.float64: + raise TypeError(f'Linkage matrix {name_str}must contain doubles.') + if len(Z.shape) != 2: + raise ValueError(f'Linkage matrix {name_str}must have shape=2 (i.e. be' + ' two-dimensional).') + if Z.shape[1] != 4: + raise ValueError(f'Linkage matrix {name_str}must have 4 columns.') + if Z.shape[0] == 0: + raise ValueError('Linkage must be computed on at least two ' + 'observations.') + n = Z.shape[0] + if n > 1: + if (xp.any(Z[:, 0] < 0) or xp.any(Z[:, 1] < 0)): + raise ValueError(f'Linkage {name_str}contains negative indices.') + if xp.any(Z[:, 2] < 0): + raise ValueError(f'Linkage {name_str}contains negative distances.') + if xp.any(Z[:, 3] < 0): + raise ValueError(f'Linkage {name_str}contains negative counts.') + if xp.any(Z[:, 3] > (Z.shape[0] + 1)): + raise ValueError('Linkage matrix contains excessive observations' + 'in a cluster') + if _check_hierarchy_uses_cluster_before_formed(Z): + raise ValueError(f'Linkage {name_str}uses non-singleton cluster before' + ' it is formed.') + if _check_hierarchy_uses_cluster_more_than_once(Z): + raise ValueError(f'Linkage {name_str}uses the same cluster more than once.') + except Exception as e: + if throw: + raise + if warning: + _warning(str(e)) + valid = False + + return valid + + +def _check_hierarchy_uses_cluster_before_formed(Z): + n = Z.shape[0] + 1 + for i in range(0, n - 1): + if Z[i, 0] >= n + i or Z[i, 1] >= n + i: + return True + return False + + +def _check_hierarchy_uses_cluster_more_than_once(Z): + n = Z.shape[0] + 1 + chosen = set() + for i in range(0, n - 1): + used_more_than_once = ( + (float(Z[i, 0]) in chosen) + or (float(Z[i, 1]) in chosen) + or Z[i, 0] == Z[i, 1] + ) + if used_more_than_once: + return True + chosen.add(float(Z[i, 0])) + chosen.add(float(Z[i, 1])) + return False + + +def _check_hierarchy_not_all_clusters_used(Z): + n = Z.shape[0] + 1 + chosen = set() + for i in range(0, n - 1): + chosen.add(int(Z[i, 0])) + chosen.add(int(Z[i, 1])) + must_chosen = set(range(0, 2 * n - 2)) + return len(must_chosen.difference(chosen)) > 0 + + +def num_obs_linkage(Z): + """ + Return the number of original observations of the linkage matrix passed. + + Parameters + ---------- + Z : ndarray + The linkage matrix on which to perform the operation. + + Returns + ------- + n : int + The number of original observations in the linkage. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, num_obs_linkage + >>> from scipy.spatial.distance import pdist + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + + ``Z`` is a linkage matrix obtained after using the Ward clustering method + with ``X``, a dataset with 12 data points. + + >>> num_obs_linkage(Z) + 12 + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='c', xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + return (Z.shape[0] + 1) + + +def correspond(Z, Y): + """ + Check for correspondence between linkage and condensed distance matrices. + + They must have the same number of original observations for + the check to succeed. + + This function is useful as a sanity check in algorithms that make + extensive use of linkage and distance matrices that must + correspond to the same set of original observations. + + Parameters + ---------- + Z : array_like + The linkage matrix to check for correspondence. + Y : array_like + The condensed distance matrix to check for correspondence. + + Returns + ------- + b : bool + A boolean indicating whether the linkage matrix and distance + matrix could possibly correspond to one another. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, correspond + >>> from scipy.spatial.distance import pdist + + This method can be used to check if a given linkage matrix ``Z`` has been + obtained from the application of a cluster method over a dataset ``X``: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + >>> X_condensed = pdist(X) + >>> Z = ward(X_condensed) + + Here, we can compare ``Z`` and ``X`` (in condensed form): + + >>> correspond(Z, X_condensed) + True + + """ + is_valid_linkage(Z, throw=True) + distance.is_valid_y(Y, throw=True) + xp = array_namespace(Z, Y) + Z = _asarray(Z, order='c', xp=xp) + Y = _asarray(Y, order='c', xp=xp) + return distance.num_obs_y(Y) == num_obs_linkage(Z) + + +def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None): + """ + Form flat clusters from the hierarchical clustering defined by + the given linkage matrix. + + Parameters + ---------- + Z : ndarray + The hierarchical clustering encoded with the matrix returned + by the `linkage` function. + t : scalar + For criteria 'inconsistent', 'distance' or 'monocrit', + this is the threshold to apply when forming flat clusters. + For 'maxclust' or 'maxclust_monocrit' criteria, + this would be max number of clusters requested. + criterion : str, optional + The criterion to use in forming flat clusters. This can + be any of the following values: + + ``inconsistent`` : + If a cluster node and all its + descendants have an inconsistent value less than or equal + to `t`, then all its leaf descendants belong to the + same flat cluster. When no non-singleton cluster meets + this criterion, every node is assigned to its own + cluster. (Default) + + ``distance`` : + Forms flat clusters so that the original + observations in each flat cluster have no greater a + cophenetic distance than `t`. + + ``maxclust`` : + Finds a minimum threshold ``r`` so that + the cophenetic distance between any two original + observations in the same flat cluster is no more than + ``r`` and no more than `t` flat clusters are formed. + + ``monocrit`` : + Forms a flat cluster from a cluster node c + with index i when ``monocrit[j] <= t``. + + For example, to threshold on the maximum mean distance + as computed in the inconsistency matrix R with a + threshold of 0.8 do:: + + MR = maxRstat(Z, R, 3) + fcluster(Z, t=0.8, criterion='monocrit', monocrit=MR) + + ``maxclust_monocrit`` : + Forms a flat cluster from a + non-singleton cluster node ``c`` when ``monocrit[i] <= + r`` for all cluster indices ``i`` below and including + ``c``. ``r`` is minimized such that no more than ``t`` + flat clusters are formed. monocrit must be + monotonic. For example, to minimize the threshold t on + maximum inconsistency values so that no more than 3 flat + clusters are formed, do:: + + MI = maxinconsts(Z, R) + fcluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI) + depth : int, optional + The maximum depth to perform the inconsistency calculation. + It has no meaning for the other criteria. Default is 2. + R : ndarray, optional + The inconsistency matrix to use for the ``'inconsistent'`` + criterion. This matrix is computed if not provided. + monocrit : ndarray, optional + An array of length n-1. `monocrit[i]` is the + statistics upon which non-singleton i is thresholded. The + monocrit vector must be monotonic, i.e., given a node c with + index i, for all node indices j corresponding to nodes + below c, ``monocrit[i] >= monocrit[j]``. + + Returns + ------- + fcluster : ndarray + An array of length ``n``. ``T[i]`` is the flat cluster number to + which original observation ``i`` belongs. + + See Also + -------- + linkage : for information about hierarchical clustering methods work. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, fcluster + >>> from scipy.spatial.distance import pdist + + All cluster linkage methods - e.g., `scipy.cluster.hierarchy.ward` + generate a linkage matrix ``Z`` as their output: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [11. , 15. , 1.29099445, 3. ], + [16. , 17. , 5.77350269, 6. ], + [18. , 19. , 5.77350269, 6. ], + [20. , 21. , 8.16496581, 12. ]]) + + This matrix represents a dendrogram, where the first and second elements + are the two clusters merged at each step, the third element is the + distance between these clusters, and the fourth element is the size of + the new cluster - the number of original data points included. + + `scipy.cluster.hierarchy.fcluster` can be used to flatten the + dendrogram, obtaining as a result an assignation of the original data + points to single clusters. + + This assignation mostly depends on a distance threshold ``t`` - the maximum + inter-cluster distance allowed: + + >>> fcluster(Z, t=0.9, criterion='distance') + array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=int32) + + >>> fcluster(Z, t=1.1, criterion='distance') + array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32) + + >>> fcluster(Z, t=3, criterion='distance') + array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32) + + >>> fcluster(Z, t=9, criterion='distance') + array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) + + In the first case, the threshold ``t`` is too small to allow any two + samples in the data to form a cluster, so 12 different clusters are + returned. + + In the second case, the threshold is large enough to allow the first + 4 points to be merged with their nearest neighbors. So, here, only 8 + clusters are returned. + + The third case, with a much higher threshold, allows for up to 8 data + points to be connected - so 4 clusters are returned here. + + Lastly, the threshold of the fourth case is large enough to allow for + all data points to be merged together - so a single cluster is returned. + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + n = Z.shape[0] + 1 + T = np.zeros((n,), dtype='i') + + if monocrit is not None: + monocrit = np.asarray(monocrit, order='C', dtype=np.float64) + + Z = np.asarray(Z) + monocrit = np.asarray(monocrit) + if criterion == 'inconsistent': + if R is None: + R = inconsistent(Z, depth) + else: + R = _asarray(R, order='C', dtype=xp.float64, xp=xp) + is_valid_im(R, throw=True, name='R') + # Since the C code does not support striding using strides. + # The dimensions are used instead. + R = np.asarray(R) + _hierarchy.cluster_in(Z, R, T, float(t), int(n)) + elif criterion == 'distance': + _hierarchy.cluster_dist(Z, T, float(t), int(n)) + elif criterion == 'maxclust': + _hierarchy.cluster_maxclust_dist(Z, T, int(n), t) + elif criterion == 'monocrit': + _hierarchy.cluster_monocrit(Z, monocrit, T, float(t), int(n)) + elif criterion == 'maxclust_monocrit': + _hierarchy.cluster_maxclust_monocrit(Z, monocrit, T, int(n), int(t)) + else: + raise ValueError(f'Invalid cluster formation criterion: {str(criterion)}') + return xp.asarray(T) + + +def fclusterdata(X, t, criterion='inconsistent', + metric='euclidean', depth=2, method='single', R=None): + """ + Cluster observation data using a given metric. + + Clusters the original observations in the n-by-m data + matrix X (n observations in m dimensions), using the euclidean + distance metric to calculate distances between original observations, + performs hierarchical clustering using the single linkage algorithm, + and forms flat clusters using the inconsistency method with `t` as the + cut-off threshold. + + A 1-D array ``T`` of length ``n`` is returned. ``T[i]`` is + the index of the flat cluster to which the original observation ``i`` + belongs. + + Parameters + ---------- + X : (N, M) ndarray + N by M data matrix with N observations in M dimensions. + t : scalar + For criteria 'inconsistent', 'distance' or 'monocrit', + this is the threshold to apply when forming flat clusters. + For 'maxclust' or 'maxclust_monocrit' criteria, + this would be max number of clusters requested. + criterion : str, optional + Specifies the criterion for forming flat clusters. Valid + values are 'inconsistent' (default), 'distance', or 'maxclust' + cluster formation algorithms. See `fcluster` for descriptions. + metric : str or function, optional + The distance metric for calculating pairwise distances. See + ``distance.pdist`` for descriptions and linkage to verify + compatibility with the linkage method. + depth : int, optional + The maximum depth for the inconsistency calculation. See + `inconsistent` for more information. + method : str, optional + The linkage method to use (single, complete, average, + weighted, median centroid, ward). See `linkage` for more + information. Default is "single". + R : ndarray, optional + The inconsistency matrix. It will be computed if necessary + if it is not passed. + + Returns + ------- + fclusterdata : ndarray + A vector of length n. T[i] is the flat cluster number to + which original observation i belongs. + + See Also + -------- + scipy.spatial.distance.pdist : pairwise distance metrics + + Notes + ----- + This function is similar to the MATLAB function ``clusterdata``. + + Examples + -------- + >>> from scipy.cluster.hierarchy import fclusterdata + + This is a convenience method that abstracts all the steps to perform in a + typical SciPy's hierarchical clustering workflow. + + * Transform the input data into a condensed matrix with + `scipy.spatial.distance.pdist`. + + * Apply a clustering method. + + * Obtain flat clusters at a user defined distance threshold ``t`` using + `scipy.cluster.hierarchy.fcluster`. + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> fclusterdata(X, t=1) + array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32) + + The output here (for the dataset ``X``, distance threshold ``t``, and the + default settings) is four clusters with three data points each. + + """ + xp = array_namespace(X) + X = _asarray(X, order='C', dtype=xp.float64, xp=xp) + + if X.ndim != 2: + raise TypeError('The observation matrix X must be an n by m ' + 'array.') + + Y = distance.pdist(X, metric=metric) + Y = xp.asarray(Y) + Z = linkage(Y, method=method) + if R is None: + R = inconsistent(Z, d=depth) + else: + R = _asarray(R, order='c', xp=xp) + T = fcluster(Z, criterion=criterion, depth=depth, R=R, t=t) + return T + + +def leaves_list(Z): + """ + Return a list of leaf node ids. + + The return corresponds to the observation vector index as it appears + in the tree from left to right. Z is a linkage matrix. + + Parameters + ---------- + Z : ndarray + The hierarchical clustering encoded as a matrix. `Z` is + a linkage matrix. See `linkage` for more information. + + Returns + ------- + leaves_list : ndarray + The list of leaf node ids. + + See Also + -------- + dendrogram : for information about dendrogram structure. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, dendrogram, leaves_list + >>> from scipy.spatial.distance import pdist + >>> from matplotlib import pyplot as plt + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + + The linkage matrix ``Z`` represents a dendrogram, that is, a tree that + encodes the structure of the clustering performed. + `scipy.cluster.hierarchy.leaves_list` shows the mapping between + indices in the ``X`` dataset and leaves in the dendrogram: + + >>> leaves_list(Z) + array([ 2, 0, 1, 5, 3, 4, 8, 6, 7, 11, 9, 10], dtype=int32) + + >>> fig = plt.figure(figsize=(25, 10)) + >>> dn = dendrogram(Z) + >>> plt.show() + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='C', xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + n = Z.shape[0] + 1 + ML = np.zeros((n,), dtype='i') + Z = np.asarray(Z) + _hierarchy.prelist(Z, ML, n) + return xp.asarray(ML) + + +# Maps number of leaves to text size. +# +# p <= 20, size="12" +# 20 < p <= 30, size="10" +# 30 < p <= 50, size="8" +# 50 < p <= np.inf, size="6" + +_dtextsizes = {20: 12, 30: 10, 50: 8, 85: 6, np.inf: 5} +_drotation = {20: 0, 40: 45, np.inf: 90} +_dtextsortedkeys = list(_dtextsizes.keys()) +_dtextsortedkeys.sort() +_drotationsortedkeys = list(_drotation.keys()) +_drotationsortedkeys.sort() + + +def _remove_dups(L): + """ + Remove duplicates AND preserve the original order of the elements. + + The set class is not guaranteed to do this. + """ + seen_before = set() + L2 = [] + for i in L: + if i not in seen_before: + seen_before.add(i) + L2.append(i) + return L2 + + +def _get_tick_text_size(p): + for k in _dtextsortedkeys: + if p <= k: + return _dtextsizes[k] + + +def _get_tick_rotation(p): + for k in _drotationsortedkeys: + if p <= k: + return _drotation[k] + + +def _plot_dendrogram(icoords, dcoords, ivl, p, n, mh, orientation, + no_labels, color_list, leaf_font_size=None, + leaf_rotation=None, contraction_marks=None, + ax=None, above_threshold_color='C0'): + # Import matplotlib here so that it's not imported unless dendrograms + # are plotted. Raise an informative error if importing fails. + try: + # if an axis is provided, don't use pylab at all + if ax is None: + import matplotlib.pylab + import matplotlib.patches + import matplotlib.collections + except ImportError as e: + raise ImportError("You must install the matplotlib library to plot " + "the dendrogram. Use no_plot=True to calculate the " + "dendrogram without plotting.") from e + + if ax is None: + ax = matplotlib.pylab.gca() + # if we're using pylab, we want to trigger a draw at the end + trigger_redraw = True + else: + trigger_redraw = False + + # Independent variable plot width + ivw = len(ivl) * 10 + # Dependent variable plot height + dvw = mh + mh * 0.05 + + iv_ticks = np.arange(5, len(ivl) * 10 + 5, 10) + if orientation in ('top', 'bottom'): + if orientation == 'top': + ax.set_ylim([0, dvw]) + ax.set_xlim([0, ivw]) + else: + ax.set_ylim([dvw, 0]) + ax.set_xlim([0, ivw]) + + xlines = icoords + ylines = dcoords + if no_labels: + ax.set_xticks([]) + ax.set_xticklabels([]) + else: + ax.set_xticks(iv_ticks) + + if orientation == 'top': + ax.xaxis.set_ticks_position('bottom') + else: + ax.xaxis.set_ticks_position('top') + + # Make the tick marks invisible because they cover up the links + for line in ax.get_xticklines(): + line.set_visible(False) + + leaf_rot = (float(_get_tick_rotation(len(ivl))) + if (leaf_rotation is None) else leaf_rotation) + leaf_font = (float(_get_tick_text_size(len(ivl))) + if (leaf_font_size is None) else leaf_font_size) + ax.set_xticklabels(ivl, rotation=leaf_rot, size=leaf_font) + + elif orientation in ('left', 'right'): + if orientation == 'left': + ax.set_xlim([dvw, 0]) + ax.set_ylim([0, ivw]) + else: + ax.set_xlim([0, dvw]) + ax.set_ylim([0, ivw]) + + xlines = dcoords + ylines = icoords + if no_labels: + ax.set_yticks([]) + ax.set_yticklabels([]) + else: + ax.set_yticks(iv_ticks) + + if orientation == 'left': + ax.yaxis.set_ticks_position('right') + else: + ax.yaxis.set_ticks_position('left') + + # Make the tick marks invisible because they cover up the links + for line in ax.get_yticklines(): + line.set_visible(False) + + leaf_font = (float(_get_tick_text_size(len(ivl))) + if (leaf_font_size is None) else leaf_font_size) + + if leaf_rotation is not None: + ax.set_yticklabels(ivl, rotation=leaf_rotation, size=leaf_font) + else: + ax.set_yticklabels(ivl, size=leaf_font) + + # Let's use collections instead. This way there is a separate legend item + # for each tree grouping, rather than stupidly one for each line segment. + colors_used = _remove_dups(color_list) + color_to_lines = {} + for color in colors_used: + color_to_lines[color] = [] + for (xline, yline, color) in zip(xlines, ylines, color_list): + color_to_lines[color].append(list(zip(xline, yline))) + + colors_to_collections = {} + # Construct the collections. + for color in colors_used: + coll = matplotlib.collections.LineCollection(color_to_lines[color], + colors=(color,)) + colors_to_collections[color] = coll + + # Add all the groupings below the color threshold. + for color in colors_used: + if color != above_threshold_color: + ax.add_collection(colors_to_collections[color]) + # If there's a grouping of links above the color threshold, it goes last. + if above_threshold_color in colors_to_collections: + ax.add_collection(colors_to_collections[above_threshold_color]) + + if contraction_marks is not None: + Ellipse = matplotlib.patches.Ellipse + for (x, y) in contraction_marks: + if orientation in ('left', 'right'): + e = Ellipse((y, x), width=dvw / 100, height=1.0) + else: + e = Ellipse((x, y), width=1.0, height=dvw / 100) + ax.add_artist(e) + e.set_clip_box(ax.bbox) + e.set_alpha(0.5) + e.set_facecolor('k') + + if trigger_redraw: + matplotlib.pylab.draw_if_interactive() + + +# C0 is used for above threshold color +_link_line_colors_default = ('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9') +_link_line_colors = list(_link_line_colors_default) + + +def set_link_color_palette(palette): + """ + Set list of matplotlib color codes for use by dendrogram. + + Note that this palette is global (i.e., setting it once changes the colors + for all subsequent calls to `dendrogram`) and that it affects only the + the colors below ``color_threshold``. + + Note that `dendrogram` also accepts a custom coloring function through its + ``link_color_func`` keyword, which is more flexible and non-global. + + Parameters + ---------- + palette : list of str or None + A list of matplotlib color codes. The order of the color codes is the + order in which the colors are cycled through when color thresholding in + the dendrogram. + + If ``None``, resets the palette to its default (which are matplotlib + default colors C1 to C9). + + Returns + ------- + None + + See Also + -------- + dendrogram + + Notes + ----- + Ability to reset the palette with ``None`` added in SciPy 0.17.0. + + Thread safety: using this function in a multi-threaded fashion may + result in `dendrogram` producing plots with unexpected colors. + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster import hierarchy + >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268., + ... 400., 754., 564., 138., 219., 869., 669.]) + >>> Z = hierarchy.linkage(ytdist, 'single') + >>> dn = hierarchy.dendrogram(Z, no_plot=True) + >>> dn['color_list'] + ['C1', 'C0', 'C0', 'C0', 'C0'] + >>> hierarchy.set_link_color_palette(['c', 'm', 'y', 'k']) + >>> dn = hierarchy.dendrogram(Z, no_plot=True, above_threshold_color='b') + >>> dn['color_list'] + ['c', 'b', 'b', 'b', 'b'] + >>> dn = hierarchy.dendrogram(Z, no_plot=True, color_threshold=267, + ... above_threshold_color='k') + >>> dn['color_list'] + ['c', 'm', 'm', 'k', 'k'] + + Now, reset the color palette to its default: + + >>> hierarchy.set_link_color_palette(None) + + """ + if palette is None: + # reset to its default + palette = _link_line_colors_default + elif not isinstance(palette, (list, tuple)): + raise TypeError("palette must be a list or tuple") + _ptypes = [isinstance(p, str) for p in palette] + + if False in _ptypes: + raise TypeError("all palette list elements must be color strings") + + global _link_line_colors + _link_line_colors = palette + + +def dendrogram(Z, p=30, truncate_mode=None, color_threshold=None, + get_leaves=True, orientation='top', labels=None, + count_sort=False, distance_sort=False, show_leaf_counts=True, + no_plot=False, no_labels=False, leaf_font_size=None, + leaf_rotation=None, leaf_label_func=None, + show_contracted=False, link_color_func=None, ax=None, + above_threshold_color='C0'): + """ + Plot the hierarchical clustering as a dendrogram. + + The dendrogram illustrates how each cluster is + composed by drawing a U-shaped link between a non-singleton + cluster and its children. The top of the U-link indicates a + cluster merge. The two legs of the U-link indicate which clusters + were merged. The length of the two legs of the U-link represents + the distance between the child clusters. It is also the + cophenetic distance between original observations in the two + children clusters. + + Parameters + ---------- + Z : ndarray + The linkage matrix encoding the hierarchical clustering to + render as a dendrogram. See the ``linkage`` function for more + information on the format of ``Z``. + p : int, optional + The ``p`` parameter for ``truncate_mode``. + truncate_mode : str, optional + The dendrogram can be hard to read when the original + observation matrix from which the linkage is derived is + large. Truncation is used to condense the dendrogram. There + are several modes: + + ``None`` + No truncation is performed (default). + Note: ``'none'`` is an alias for ``None`` that's kept for + backward compatibility. + + ``'lastp'`` + The last ``p`` non-singleton clusters formed in the linkage are the + only non-leaf nodes in the linkage; they correspond to rows + ``Z[n-p-2:end]`` in ``Z``. All other non-singleton clusters are + contracted into leaf nodes. + + ``'level'`` + No more than ``p`` levels of the dendrogram tree are displayed. + A "level" includes all nodes with ``p`` merges from the final merge. + + Note: ``'mtica'`` is an alias for ``'level'`` that's kept for + backward compatibility. + + color_threshold : double, optional + For brevity, let :math:`t` be the ``color_threshold``. + Colors all the descendent links below a cluster node + :math:`k` the same color if :math:`k` is the first node below + the cut threshold :math:`t`. All links connecting nodes with + distances greater than or equal to the threshold are colored + with de default matplotlib color ``'C0'``. If :math:`t` is less + than or equal to zero, all nodes are colored ``'C0'``. + If ``color_threshold`` is None or 'default', + corresponding with MATLAB(TM) behavior, the threshold is set to + ``0.7*max(Z[:,2])``. + + get_leaves : bool, optional + Includes a list ``R['leaves']=H`` in the result + dictionary. For each :math:`i`, ``H[i] == j``, cluster node + ``j`` appears in position ``i`` in the left-to-right traversal + of the leaves, where :math:`j < 2n-1` and :math:`i < n`. + orientation : str, optional + The direction to plot the dendrogram, which can be any + of the following strings: + + ``'top'`` + Plots the root at the top, and plot descendent links going downwards. + (default). + + ``'bottom'`` + Plots the root at the bottom, and plot descendent links going + upwards. + + ``'left'`` + Plots the root at the left, and plot descendent links going right. + + ``'right'`` + Plots the root at the right, and plot descendent links going left. + + labels : ndarray, optional + By default, ``labels`` is None so the index of the original observation + is used to label the leaf nodes. Otherwise, this is an :math:`n`-sized + sequence, with ``n == Z.shape[0] + 1``. The ``labels[i]`` value is the + text to put under the :math:`i` th leaf node only if it corresponds to + an original observation and not a non-singleton cluster. + count_sort : str or bool, optional + For each node n, the order (visually, from left-to-right) n's + two descendent links are plotted is determined by this + parameter, which can be any of the following values: + + ``False`` + Nothing is done. + + ``'ascending'`` or ``True`` + The child with the minimum number of original objects in its cluster + is plotted first. + + ``'descending'`` + The child with the maximum number of original objects in its cluster + is plotted first. + + Note, ``distance_sort`` and ``count_sort`` cannot both be True. + distance_sort : str or bool, optional + For each node n, the order (visually, from left-to-right) n's + two descendent links are plotted is determined by this + parameter, which can be any of the following values: + + ``False`` + Nothing is done. + + ``'ascending'`` or ``True`` + The child with the minimum distance between its direct descendents is + plotted first. + + ``'descending'`` + The child with the maximum distance between its direct descendents is + plotted first. + + Note ``distance_sort`` and ``count_sort`` cannot both be True. + show_leaf_counts : bool, optional + When True, leaf nodes representing :math:`k>1` original + observation are labeled with the number of observations they + contain in parentheses. + no_plot : bool, optional + When True, the final rendering is not performed. This is + useful if only the data structures computed for the rendering + are needed or if matplotlib is not available. + no_labels : bool, optional + When True, no labels appear next to the leaf nodes in the + rendering of the dendrogram. + leaf_rotation : double, optional + Specifies the angle (in degrees) to rotate the leaf + labels. When unspecified, the rotation is based on the number of + nodes in the dendrogram (default is 0). + leaf_font_size : int, optional + Specifies the font size (in points) of the leaf labels. When + unspecified, the size based on the number of nodes in the + dendrogram. + leaf_label_func : lambda or function, optional + When ``leaf_label_func`` is a callable function, for each + leaf with cluster index :math:`k < 2n-1`. The function + is expected to return a string with the label for the + leaf. + + Indices :math:`k < n` correspond to original observations + while indices :math:`k \\geq n` correspond to non-singleton + clusters. + + For example, to label singletons with their node id and + non-singletons with their id, count, and inconsistency + coefficient, simply do:: + + # First define the leaf label function. + def llf(id): + if id < n: + return str(id) + else: + return '[%d %d %1.2f]' % (id, count, R[n-id,3]) + + # The text for the leaf nodes is going to be big so force + # a rotation of 90 degrees. + dendrogram(Z, leaf_label_func=llf, leaf_rotation=90) + + # leaf_label_func can also be used together with ``truncate_mode``, + # in which case you will get your leaves labeled after truncation: + dendrogram(Z, leaf_label_func=llf, leaf_rotation=90, + truncate_mode='level', p=2) + + show_contracted : bool, optional + When True the heights of non-singleton nodes contracted + into a leaf node are plotted as crosses along the link + connecting that leaf node. This really is only useful when + truncation is used (see ``truncate_mode`` parameter). + link_color_func : callable, optional + If given, `link_color_function` is called with each non-singleton id + corresponding to each U-shaped link it will paint. The function is + expected to return the color to paint the link, encoded as a matplotlib + color string code. For example:: + + dendrogram(Z, link_color_func=lambda k: colors[k]) + + colors the direct links below each untruncated non-singleton node + ``k`` using ``colors[k]``. + ax : matplotlib Axes instance, optional + If None and `no_plot` is not True, the dendrogram will be plotted + on the current axes. Otherwise if `no_plot` is not True the + dendrogram will be plotted on the given ``Axes`` instance. This can be + useful if the dendrogram is part of a more complex figure. + above_threshold_color : str, optional + This matplotlib color string sets the color of the links above the + color_threshold. The default is ``'C0'``. + + Returns + ------- + R : dict + A dictionary of data structures computed to render the + dendrogram. Its has the following keys: + + ``'color_list'`` + A list of color names. The k'th element represents the color of the + k'th link. + + ``'icoord'`` and ``'dcoord'`` + Each of them is a list of lists. Let ``icoord = [I1, I2, ..., Ip]`` + where ``Ik = [xk1, xk2, xk3, xk4]`` and ``dcoord = [D1, D2, ..., Dp]`` + where ``Dk = [yk1, yk2, yk3, yk4]``, then the k'th link painted is + ``(xk1, yk1)`` - ``(xk2, yk2)`` - ``(xk3, yk3)`` - ``(xk4, yk4)``. + + ``'ivl'`` + A list of labels corresponding to the leaf nodes. + + ``'leaves'`` + For each i, ``H[i] == j``, cluster node ``j`` appears in position + ``i`` in the left-to-right traversal of the leaves, where + :math:`j < 2n-1` and :math:`i < n`. If ``j`` is less than ``n``, the + ``i``-th leaf node corresponds to an original observation. + Otherwise, it corresponds to a non-singleton cluster. + + ``'leaves_color_list'`` + A list of color names. The k'th element represents the color of the + k'th leaf. + + See Also + -------- + linkage, set_link_color_palette + + Notes + ----- + It is expected that the distances in ``Z[:,2]`` be monotonic, otherwise + crossings appear in the dendrogram. + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster import hierarchy + >>> import matplotlib.pyplot as plt + + A very basic example: + + >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268., + ... 400., 754., 564., 138., 219., 869., 669.]) + >>> Z = hierarchy.linkage(ytdist, 'single') + >>> plt.figure() + >>> dn = hierarchy.dendrogram(Z) + + Now, plot in given axes, improve the color scheme and use both vertical and + horizontal orientations: + + >>> hierarchy.set_link_color_palette(['m', 'c', 'y', 'k']) + >>> fig, axes = plt.subplots(1, 2, figsize=(8, 3)) + >>> dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y', + ... orientation='top') + >>> dn2 = hierarchy.dendrogram(Z, ax=axes[1], + ... above_threshold_color='#bcbddc', + ... orientation='right') + >>> hierarchy.set_link_color_palette(None) # reset to default after use + >>> plt.show() + + """ + # This feature was thought about but never implemented (still useful?): + # + # ... = dendrogram(..., leaves_order=None) + # + # Plots the leaves in the order specified by a vector of + # original observation indices. If the vector contains duplicates + # or results in a crossing, an exception will be thrown. Passing + # None orders leaf nodes based on the order they appear in the + # pre-order traversal. + xp = array_namespace(Z) + Z = _asarray(Z, order='c', xp=xp) + + if orientation not in ["top", "left", "bottom", "right"]: + raise ValueError("orientation must be one of 'top', 'left', " + "'bottom', or 'right'") + + if labels is not None: + try: + len_labels = len(labels) + except (TypeError, AttributeError): + len_labels = labels.shape[0] + if Z.shape[0] + 1 != len_labels: + raise ValueError("Dimensions of Z and labels must be consistent.") + + is_valid_linkage(Z, throw=True, name='Z') + Zs = Z.shape + n = Zs[0] + 1 + if isinstance(p, (int, float)): + p = int(p) + else: + raise TypeError('The second argument must be a number') + + if truncate_mode not in ('lastp', 'mtica', 'level', 'none', None): + # 'mtica' is kept working for backwards compat. + raise ValueError('Invalid truncation mode.') + + if truncate_mode == 'lastp': + if p > n or p == 0: + p = n + + if truncate_mode == 'mtica': + # 'mtica' is an alias + truncate_mode = 'level' + + if truncate_mode == 'level': + if p <= 0: + p = np.inf + + if get_leaves: + lvs = [] + else: + lvs = None + + icoord_list = [] + dcoord_list = [] + color_list = [] + current_color = [0] + currently_below_threshold = [False] + ivl = [] # list of leaves + + if color_threshold is None or (isinstance(color_threshold, str) and + color_threshold == 'default'): + color_threshold = xp.max(Z[:, 2]) * 0.7 + + R = {'icoord': icoord_list, 'dcoord': dcoord_list, 'ivl': ivl, + 'leaves': lvs, 'color_list': color_list} + + # Empty list will be filled in _dendrogram_calculate_info + contraction_marks = [] if show_contracted else None + + _dendrogram_calculate_info( + Z=Z, p=p, + truncate_mode=truncate_mode, + color_threshold=color_threshold, + get_leaves=get_leaves, + orientation=orientation, + labels=labels, + count_sort=count_sort, + distance_sort=distance_sort, + show_leaf_counts=show_leaf_counts, + i=2*n - 2, + iv=0.0, + ivl=ivl, + n=n, + icoord_list=icoord_list, + dcoord_list=dcoord_list, + lvs=lvs, + current_color=current_color, + color_list=color_list, + currently_below_threshold=currently_below_threshold, + leaf_label_func=leaf_label_func, + contraction_marks=contraction_marks, + link_color_func=link_color_func, + above_threshold_color=above_threshold_color) + + if not no_plot: + mh = xp.max(Z[:, 2]) + _plot_dendrogram(icoord_list, dcoord_list, ivl, p, n, mh, orientation, + no_labels, color_list, + leaf_font_size=leaf_font_size, + leaf_rotation=leaf_rotation, + contraction_marks=contraction_marks, + ax=ax, + above_threshold_color=above_threshold_color) + + R["leaves_color_list"] = _get_leaves_color_list(R) + + return R + + +def _get_leaves_color_list(R): + leaves_color_list = [None] * len(R['leaves']) + for link_x, link_y, link_color in zip(R['icoord'], + R['dcoord'], + R['color_list']): + for (xi, yi) in zip(link_x, link_y): + if yi == 0.0 and (xi % 5 == 0 and xi % 2 == 1): + # if yi is 0.0 and xi is divisible by 5 and odd, + # the point is a leaf + # xi of leaves are 5, 15, 25, 35, ... (see `iv_ticks`) + # index of leaves are 0, 1, 2, 3, ... as below + leaf_index = (int(xi) - 5) // 10 + # each leaf has a same color of its link. + leaves_color_list[leaf_index] = link_color + return leaves_color_list + + +def _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, + i, labels): + # If the leaf id structure is not None and is a list then the caller + # to dendrogram has indicated that cluster id's corresponding to the + # leaf nodes should be recorded. + + if lvs is not None: + lvs.append(int(i)) + + # If leaf node labels are to be displayed... + if ivl is not None: + # If a leaf_label_func has been provided, the label comes from the + # string returned from the leaf_label_func, which is a function + # passed to dendrogram. + if leaf_label_func: + ivl.append(leaf_label_func(int(i))) + else: + # Otherwise, if the dendrogram caller has passed a labels list + # for the leaf nodes, use it. + if labels is not None: + ivl.append(labels[int(i - n)]) + else: + # Otherwise, use the id as the label for the leaf.x + ivl.append(str(int(i))) + + +def _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func, + i, labels, show_leaf_counts): + # If the leaf id structure is not None and is a list then the caller + # to dendrogram has indicated that cluster id's corresponding to the + # leaf nodes should be recorded. + + if lvs is not None: + lvs.append(int(i)) + if ivl is not None: + if leaf_label_func: + ivl.append(leaf_label_func(int(i))) + else: + if show_leaf_counts: + ivl.append("(" + str(np.asarray(Z[i - n, 3], dtype=np.int64)) + ")") + else: + ivl.append("") + + +def _append_contraction_marks(Z, iv, i, n, contraction_marks, xp): + _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp), + n, contraction_marks, xp) + _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp), + n, contraction_marks, xp) + + +def _append_contraction_marks_sub(Z, iv, i, n, contraction_marks, xp): + if i >= n: + contraction_marks.append((iv, Z[i - n, 2])) + _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp), + n, contraction_marks, xp) + _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp), + n, contraction_marks, xp) + + +def _dendrogram_calculate_info(Z, p, truncate_mode, + color_threshold=np.inf, get_leaves=True, + orientation='top', labels=None, + count_sort=False, distance_sort=False, + show_leaf_counts=False, i=-1, iv=0.0, + ivl=None, n=0, icoord_list=None, dcoord_list=None, + lvs=None, mhr=False, + current_color=None, color_list=None, + currently_below_threshold=None, + leaf_label_func=None, level=0, + contraction_marks=None, + link_color_func=None, + above_threshold_color='C0'): + """ + Calculate the endpoints of the links as well as the labels for the + the dendrogram rooted at the node with index i. iv is the independent + variable value to plot the left-most leaf node below the root node i + (if orientation='top', this would be the left-most x value where the + plotting of this root node i and its descendents should begin). + + ivl is a list to store the labels of the leaf nodes. The leaf_label_func + is called whenever ivl != None, labels == None, and + leaf_label_func != None. When ivl != None and labels != None, the + labels list is used only for labeling the leaf nodes. When + ivl == None, no labels are generated for leaf nodes. + + When get_leaves==True, a list of leaves is built as they are visited + in the dendrogram. + + Returns a tuple with l being the independent variable coordinate that + corresponds to the midpoint of cluster to the left of cluster i if + i is non-singleton, otherwise the independent coordinate of the leaf + node if i is a leaf node. + + Returns + ------- + A tuple (left, w, h, md), where: + * left is the independent variable coordinate of the center of the + the U of the subtree + + * w is the amount of space used for the subtree (in independent + variable units) + + * h is the height of the subtree in dependent variable units + + * md is the ``max(Z[*,2]``) for all nodes ``*`` below and including + the target node. + + """ + xp = array_namespace(Z) + if n == 0: + raise ValueError("Invalid singleton cluster count n.") + + if i == -1: + raise ValueError("Invalid root cluster index i.") + + if truncate_mode == 'lastp': + # If the node is a leaf node but corresponds to a non-singleton + # cluster, its label is either the empty string or the number of + # original observations belonging to cluster i. + if 2*n - p > i >= n: + d = Z[i - n, 2] + _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, + leaf_label_func, i, labels, + show_leaf_counts) + if contraction_marks is not None: + _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp) + return (iv + 5.0, 10.0, 0.0, d) + elif i < n: + _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, + leaf_label_func, i, labels) + return (iv + 5.0, 10.0, 0.0, 0.0) + elif truncate_mode == 'level': + if i > n and level > p: + d = Z[i - n, 2] + _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, + leaf_label_func, i, labels, + show_leaf_counts) + if contraction_marks is not None: + _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp) + return (iv + 5.0, 10.0, 0.0, d) + elif i < n: + _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, + leaf_label_func, i, labels) + return (iv + 5.0, 10.0, 0.0, 0.0) + + # Otherwise, only truncate if we have a leaf node. + # + # Only place leaves if they correspond to original observations. + if i < n: + _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, + leaf_label_func, i, labels) + return (iv + 5.0, 10.0, 0.0, 0.0) + + # !!! Otherwise, we don't have a leaf node, so work on plotting a + # non-leaf node. + # Actual indices of a and b + aa = int_floor(Z[i - n, 0], xp) + ab = int_floor(Z[i - n, 1], xp) + if aa >= n: + # The number of singletons below cluster a + na = Z[aa - n, 3] + # The distance between a's two direct children. + da = Z[aa - n, 2] + else: + na = 1 + da = 0.0 + if ab >= n: + nb = Z[ab - n, 3] + db = Z[ab - n, 2] + else: + nb = 1 + db = 0.0 + + if count_sort == 'ascending' or count_sort is True: + # If a has a count greater than b, it and its descendents should + # be drawn to the right. Otherwise, to the left. + if na > nb: + # The cluster index to draw to the left (ua) will be ab + # and the one to draw to the right (ub) will be aa + ua = ab + ub = aa + else: + ua = aa + ub = ab + elif count_sort == 'descending': + # If a has a count less than or equal to b, it and its + # descendents should be drawn to the left. Otherwise, to + # the right. + if na > nb: + ua = aa + ub = ab + else: + ua = ab + ub = aa + elif distance_sort == 'ascending' or distance_sort is True: + # If a has a distance greater than b, it and its descendents should + # be drawn to the right. Otherwise, to the left. + if da > db: + ua = ab + ub = aa + else: + ua = aa + ub = ab + elif distance_sort == 'descending': + # If a has a distance less than or equal to b, it and its + # descendents should be drawn to the left. Otherwise, to + # the right. + if da > db: + ua = aa + ub = ab + else: + ua = ab + ub = aa + else: + ua = aa + ub = ab + + # Updated iv variable and the amount of space used. + (uiva, uwa, uah, uamd) = \ + _dendrogram_calculate_info( + Z=Z, p=p, + truncate_mode=truncate_mode, + color_threshold=color_threshold, + get_leaves=get_leaves, + orientation=orientation, + labels=labels, + count_sort=count_sort, + distance_sort=distance_sort, + show_leaf_counts=show_leaf_counts, + i=ua, iv=iv, ivl=ivl, n=n, + icoord_list=icoord_list, + dcoord_list=dcoord_list, lvs=lvs, + current_color=current_color, + color_list=color_list, + currently_below_threshold=currently_below_threshold, + leaf_label_func=leaf_label_func, + level=level + 1, contraction_marks=contraction_marks, + link_color_func=link_color_func, + above_threshold_color=above_threshold_color) + + h = Z[i - n, 2] + if h >= color_threshold or color_threshold <= 0: + c = above_threshold_color + + if currently_below_threshold[0]: + current_color[0] = (current_color[0] + 1) % len(_link_line_colors) + currently_below_threshold[0] = False + else: + currently_below_threshold[0] = True + c = _link_line_colors[current_color[0]] + + (uivb, uwb, ubh, ubmd) = \ + _dendrogram_calculate_info( + Z=Z, p=p, + truncate_mode=truncate_mode, + color_threshold=color_threshold, + get_leaves=get_leaves, + orientation=orientation, + labels=labels, + count_sort=count_sort, + distance_sort=distance_sort, + show_leaf_counts=show_leaf_counts, + i=ub, iv=iv + uwa, ivl=ivl, n=n, + icoord_list=icoord_list, + dcoord_list=dcoord_list, lvs=lvs, + current_color=current_color, + color_list=color_list, + currently_below_threshold=currently_below_threshold, + leaf_label_func=leaf_label_func, + level=level + 1, contraction_marks=contraction_marks, + link_color_func=link_color_func, + above_threshold_color=above_threshold_color) + + max_dist = max(uamd, ubmd, h) + + icoord_list.append([uiva, uiva, uivb, uivb]) + dcoord_list.append([uah, h, h, ubh]) + if link_color_func is not None: + v = link_color_func(int(i)) + if not isinstance(v, str): + raise TypeError("link_color_func must return a matplotlib " + "color string!") + color_list.append(v) + else: + color_list.append(c) + + return (((uiva + uivb) / 2), uwa + uwb, h, max_dist) + + +def is_isomorphic(T1, T2): + """ + Determine if two different cluster assignments are equivalent. + + Parameters + ---------- + T1 : array_like + An assignment of singleton cluster ids to flat cluster ids. + T2 : array_like + An assignment of singleton cluster ids to flat cluster ids. + + Returns + ------- + b : bool + Whether the flat cluster assignments `T1` and `T2` are + equivalent. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + fcluster : for the creation of flat cluster assignments. + + Examples + -------- + >>> from scipy.cluster.hierarchy import fcluster, is_isomorphic + >>> from scipy.cluster.hierarchy import single, complete + >>> from scipy.spatial.distance import pdist + + Two flat cluster assignments can be isomorphic if they represent the same + cluster assignment, with different labels. + + For example, we can use the `scipy.cluster.hierarchy.single`: method + and flatten the output to four clusters: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = single(pdist(X)) + >>> T = fcluster(Z, 1, criterion='distance') + >>> T + array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32) + + We can then do the same using the + `scipy.cluster.hierarchy.complete`: method: + + >>> Z = complete(pdist(X)) + >>> T_ = fcluster(Z, 1.5, criterion='distance') + >>> T_ + array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32) + + As we can see, in both cases we obtain four clusters and all the data + points are distributed in the same way - the only thing that changes + are the flat cluster labels (3 => 1, 4 =>2, 2 =>3 and 4 =>1), so both + cluster assignments are isomorphic: + + >>> is_isomorphic(T, T_) + True + + """ + T1 = np.asarray(T1, order='c') + T2 = np.asarray(T2, order='c') + + T1S = T1.shape + T2S = T2.shape + + if len(T1S) != 1: + raise ValueError('T1 must be one-dimensional.') + if len(T2S) != 1: + raise ValueError('T2 must be one-dimensional.') + if T1S[0] != T2S[0]: + raise ValueError('T1 and T2 must have the same number of elements.') + n = T1S[0] + d1 = {} + d2 = {} + for i in range(0, n): + if T1[i] in d1: + if T2[i] not in d2: + return False + if d1[T1[i]] != T2[i] or d2[T2[i]] != T1[i]: + return False + elif T2[i] in d2: + return False + else: + d1[T1[i]] = T2[i] + d2[T2[i]] = T1[i] + return True + + +def maxdists(Z): + """ + Return the maximum distance between any non-singleton cluster. + + Parameters + ---------- + Z : ndarray + The hierarchical clustering encoded as a matrix. See + ``linkage`` for more information. + + Returns + ------- + maxdists : ndarray + A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents + the maximum distance between any cluster (including + singletons) below and including the node with index i. More + specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the + set of all node indices below and including node i. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + is_monotonic : for testing for monotonicity of a linkage matrix. + + Examples + -------- + >>> from scipy.cluster.hierarchy import median, maxdists + >>> from scipy.spatial.distance import pdist + + Given a linkage matrix ``Z``, `scipy.cluster.hierarchy.maxdists` + computes for each new cluster generated (i.e., for each row of the linkage + matrix) what is the maximum distance between any two child clusters. + + Due to the nature of hierarchical clustering, in many cases this is going + to be just the distance between the two child clusters that were merged + to form the current one - that is, Z[:,2]. + + However, for non-monotonic cluster assignments such as + `scipy.cluster.hierarchy.median` clustering this is not always the + case: There may be cluster formations were the distance between the two + clusters merged is smaller than the distance between their children. + + We can see this in an example: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = median(pdist(X)) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 2. , 12. , 1.11803399, 3. ], + [ 5. , 13. , 1.11803399, 3. ], + [ 8. , 15. , 1.11803399, 3. ], + [11. , 14. , 1.11803399, 3. ], + [18. , 19. , 3. , 6. ], + [16. , 17. , 3.5 , 6. ], + [20. , 21. , 3.25 , 12. ]]) + >>> maxdists(Z) + array([1. , 1. , 1. , 1. , 1.11803399, + 1.11803399, 1.11803399, 1.11803399, 3. , 3.5 , + 3.5 ]) + + Note that while the distance between the two clusters merged when creating the + last cluster is 3.25, there are two children (clusters 16 and 17) whose distance + is larger (3.5). Thus, `scipy.cluster.hierarchy.maxdists` returns 3.5 in + this case. + + """ + xp = array_namespace(Z) + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + n = Z.shape[0] + 1 + MD = np.zeros((n - 1,)) + Z = np.asarray(Z) + _hierarchy.get_max_dist_for_each_cluster(Z, MD, int(n)) + MD = xp.asarray(MD) + return MD + + +def maxinconsts(Z, R): + """ + Return the maximum inconsistency coefficient for each + non-singleton cluster and its children. + + Parameters + ---------- + Z : ndarray + The hierarchical clustering encoded as a matrix. See + `linkage` for more information. + R : ndarray + The inconsistency matrix. + + Returns + ------- + MI : ndarray + A monotonic ``(n-1)``-sized numpy array of doubles. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + inconsistent : for the creation of a inconsistency matrix. + + Examples + -------- + >>> from scipy.cluster.hierarchy import median, inconsistent, maxinconsts + >>> from scipy.spatial.distance import pdist + + Given a data set ``X``, we can apply a clustering method to obtain a + linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can + be also used to obtain the inconsistency matrix ``R`` associated to + this clustering process: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = median(pdist(X)) + >>> R = inconsistent(Z) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 2. , 12. , 1.11803399, 3. ], + [ 5. , 13. , 1.11803399, 3. ], + [ 8. , 15. , 1.11803399, 3. ], + [11. , 14. , 1.11803399, 3. ], + [18. , 19. , 3. , 6. ], + [16. , 17. , 3.5 , 6. ], + [20. , 21. , 3.25 , 12. ]]) + >>> R + array([[1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.74535599, 1.08655358, 3. , 1.15470054], + [1.91202266, 1.37522872, 3. , 1.15470054], + [3.25 , 0.25 , 3. , 0. ]]) + + Here, `scipy.cluster.hierarchy.maxinconsts` can be used to compute + the maximum value of the inconsistency statistic (the last column of + ``R``) for each non-singleton cluster and its children: + + >>> maxinconsts(Z, R) + array([0. , 0. , 0. , 0. , 0.70710678, + 0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054, + 1.15470054]) + + """ + xp = array_namespace(Z, R) + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + R = _asarray(R, order='C', dtype=xp.float64, xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + is_valid_im(R, throw=True, name='R') + + n = Z.shape[0] + 1 + if Z.shape[0] != R.shape[0]: + raise ValueError("The inconsistency matrix and linkage matrix each " + "have a different number of rows.") + MI = np.zeros((n - 1,)) + Z = np.asarray(Z) + R = np.asarray(R) + _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, int(n), 3) + MI = xp.asarray(MI) + return MI + + +def maxRstat(Z, R, i): + """ + Return the maximum statistic for each non-singleton cluster and its + children. + + Parameters + ---------- + Z : array_like + The hierarchical clustering encoded as a matrix. See `linkage` for more + information. + R : array_like + The inconsistency matrix. + i : int + The column of `R` to use as the statistic. + + Returns + ------- + MR : ndarray + Calculates the maximum statistic for the i'th column of the + inconsistency matrix `R` for each non-singleton cluster + node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]``, where + ``Q(j)`` the set of all node ids corresponding to nodes below + and including ``j``. + + See Also + -------- + linkage : for a description of what a linkage matrix is. + inconsistent : for the creation of a inconsistency matrix. + + Examples + -------- + >>> from scipy.cluster.hierarchy import median, inconsistent, maxRstat + >>> from scipy.spatial.distance import pdist + + Given a data set ``X``, we can apply a clustering method to obtain a + linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can + be also used to obtain the inconsistency matrix ``R`` associated to + this clustering process: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = median(pdist(X)) + >>> R = inconsistent(Z) + >>> R + array([[1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1. , 0. , 1. , 0. ], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.05901699, 0.08346263, 2. , 0.70710678], + [1.74535599, 1.08655358, 3. , 1.15470054], + [1.91202266, 1.37522872, 3. , 1.15470054], + [3.25 , 0.25 , 3. , 0. ]]) + + `scipy.cluster.hierarchy.maxRstat` can be used to compute + the maximum value of each column of ``R``, for each non-singleton + cluster and its children: + + >>> maxRstat(Z, R, 0) + array([1. , 1. , 1. , 1. , 1.05901699, + 1.05901699, 1.05901699, 1.05901699, 1.74535599, 1.91202266, + 3.25 ]) + >>> maxRstat(Z, R, 1) + array([0. , 0. , 0. , 0. , 0.08346263, + 0.08346263, 0.08346263, 0.08346263, 1.08655358, 1.37522872, + 1.37522872]) + >>> maxRstat(Z, R, 3) + array([0. , 0. , 0. , 0. , 0.70710678, + 0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054, + 1.15470054]) + + """ + xp = array_namespace(Z, R) + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + R = _asarray(R, order='C', dtype=xp.float64, xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + is_valid_im(R, throw=True, name='R') + + if not isinstance(i, int): + raise TypeError('The third argument must be an integer.') + + if i < 0 or i > 3: + raise ValueError('i must be an integer between 0 and 3 inclusive.') + + if Z.shape[0] != R.shape[0]: + raise ValueError("The inconsistency matrix and linkage matrix each " + "have a different number of rows.") + + n = Z.shape[0] + 1 + MR = np.zeros((n - 1,)) + Z = np.asarray(Z) + R = np.asarray(R) + _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MR, int(n), i) + MR = xp.asarray(MR) + return MR + + +def leaders(Z, T): + """ + Return the root nodes in a hierarchical clustering. + + Returns the root nodes in a hierarchical clustering corresponding + to a cut defined by a flat cluster assignment vector ``T``. See + the ``fcluster`` function for more information on the format of ``T``. + + For each flat cluster :math:`j` of the :math:`k` flat clusters + represented in the n-sized flat cluster assignment vector ``T``, + this function finds the lowest cluster node :math:`i` in the linkage + tree Z, such that: + + * leaf descendants belong only to flat cluster j + (i.e., ``T[p]==j`` for all :math:`p` in :math:`S(i)`, where + :math:`S(i)` is the set of leaf ids of descendant leaf nodes + with cluster node :math:`i`) + + * there does not exist a leaf that is not a descendant with + :math:`i` that also belongs to cluster :math:`j` + (i.e., ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`). If + this condition is violated, ``T`` is not a valid cluster + assignment vector, and an exception will be thrown. + + Parameters + ---------- + Z : ndarray + The hierarchical clustering encoded as a matrix. See + `linkage` for more information. + T : ndarray + The flat cluster assignment vector. + + Returns + ------- + L : ndarray + The leader linkage node id's stored as a k-element 1-D array, + where ``k`` is the number of flat clusters found in ``T``. + + ``L[j]=i`` is the linkage cluster node id that is the + leader of flat cluster with id M[j]. If ``i < n``, ``i`` + corresponds to an original observation, otherwise it + corresponds to a non-singleton cluster. + M : ndarray + The leader linkage node id's stored as a k-element 1-D array, where + ``k`` is the number of flat clusters found in ``T``. This allows the + set of flat cluster ids to be any arbitrary set of ``k`` integers. + + For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with + id 8's leader is linkage node 2. + + See Also + -------- + fcluster : for the creation of flat cluster assignments. + + Examples + -------- + >>> from scipy.cluster.hierarchy import ward, fcluster, leaders + >>> from scipy.spatial.distance import pdist + + Given a linkage matrix ``Z`` - obtained after apply a clustering method + to a dataset ``X`` - and a flat cluster assignment array ``T``: + + >>> X = [[0, 0], [0, 1], [1, 0], + ... [0, 4], [0, 3], [1, 4], + ... [4, 0], [3, 0], [4, 1], + ... [4, 4], [3, 4], [4, 3]] + + >>> Z = ward(pdist(X)) + >>> Z + array([[ 0. , 1. , 1. , 2. ], + [ 3. , 4. , 1. , 2. ], + [ 6. , 7. , 1. , 2. ], + [ 9. , 10. , 1. , 2. ], + [ 2. , 12. , 1.29099445, 3. ], + [ 5. , 13. , 1.29099445, 3. ], + [ 8. , 14. , 1.29099445, 3. ], + [11. , 15. , 1.29099445, 3. ], + [16. , 17. , 5.77350269, 6. ], + [18. , 19. , 5.77350269, 6. ], + [20. , 21. , 8.16496581, 12. ]]) + + >>> T = fcluster(Z, 3, criterion='distance') + >>> T + array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32) + + `scipy.cluster.hierarchy.leaders` returns the indices of the nodes + in the dendrogram that are the leaders of each flat cluster: + + >>> L, M = leaders(Z, T) + >>> L + array([16, 17, 18, 19], dtype=int32) + + (remember that indices 0-11 point to the 12 data points in ``X``, + whereas indices 12-22 point to the 11 rows of ``Z``) + + `scipy.cluster.hierarchy.leaders` also returns the indices of + the flat clusters in ``T``: + + >>> M + array([1, 2, 3, 4], dtype=int32) + + """ + xp = array_namespace(Z, T) + Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp) + T = _asarray(T, order='C', xp=xp) + is_valid_linkage(Z, throw=True, name='Z') + + if T.dtype != xp.int32: + raise TypeError('T must be a 1-D array of dtype int32.') + + if T.shape[0] != Z.shape[0] + 1: + raise ValueError('Mismatch: len(T)!=Z.shape[0] + 1.') + + n_clusters = int(xp.unique_values(T).shape[0]) + n_obs = int(Z.shape[0] + 1) + L = np.zeros(n_clusters, dtype=np.int32) + M = np.zeros(n_clusters, dtype=np.int32) + Z = np.asarray(Z) + T = np.asarray(T, dtype=np.int32) + s = _hierarchy.leaders(Z, T, L, M, n_clusters, n_obs) + if s >= 0: + raise ValueError(('T is not a valid assignment vector. Error found ' + 'when examining linkage node %d (< 2n-1).') % s) + L, M = xp.asarray(L), xp.asarray(M) + return (L, M) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/hierarchy_test_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/hierarchy_test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..7d874ca5eb7141a44559307d1c28dd412171396f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/hierarchy_test_data.py @@ -0,0 +1,145 @@ +from numpy import array + + +Q_X = array([[5.26563660e-01, 3.14160190e-01, 8.00656370e-02], + [7.50205180e-01, 4.60299830e-01, 8.98696460e-01], + [6.65461230e-01, 6.94011420e-01, 9.10465700e-01], + [9.64047590e-01, 1.43082200e-03, 7.39874220e-01], + [1.08159060e-01, 5.53028790e-01, 6.63804780e-02], + [9.31359130e-01, 8.25424910e-01, 9.52315440e-01], + [6.78086960e-01, 3.41903970e-01, 5.61481950e-01], + [9.82730940e-01, 7.04605210e-01, 8.70978630e-02], + [6.14691610e-01, 4.69989230e-02, 6.02406450e-01], + [5.80161260e-01, 9.17354970e-01, 5.88163850e-01], + [1.38246310e+00, 1.96358160e+00, 1.94437880e+00], + [2.10675860e+00, 1.67148730e+00, 1.34854480e+00], + [1.39880070e+00, 1.66142050e+00, 1.32224550e+00], + [1.71410460e+00, 1.49176380e+00, 1.45432170e+00], + [1.54102340e+00, 1.84374950e+00, 1.64658950e+00], + [2.08512480e+00, 1.84524350e+00, 2.17340850e+00], + [1.30748740e+00, 1.53801650e+00, 2.16007740e+00], + [1.41447700e+00, 1.99329070e+00, 1.99107420e+00], + [1.61943490e+00, 1.47703280e+00, 1.89788160e+00], + [1.59880600e+00, 1.54988980e+00, 1.57563350e+00], + [3.37247380e+00, 2.69635310e+00, 3.39981700e+00], + [3.13705120e+00, 3.36528090e+00, 3.06089070e+00], + [3.29413250e+00, 3.19619500e+00, 2.90700170e+00], + [2.65510510e+00, 3.06785900e+00, 2.97198540e+00], + [3.30941040e+00, 2.59283970e+00, 2.57714110e+00], + [2.59557220e+00, 3.33477370e+00, 3.08793190e+00], + [2.58206180e+00, 3.41615670e+00, 3.26441990e+00], + [2.71127000e+00, 2.77032450e+00, 2.63466500e+00], + [2.79617850e+00, 3.25473720e+00, 3.41801560e+00], + [2.64741750e+00, 2.54538040e+00, 3.25354110e+00]]) + +ytdist = array([662., 877., 255., 412., 996., 295., 468., 268., 400., 754., + 564., 138., 219., 869., 669.]) + +linkage_ytdist_single = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 255., 3.], + [1., 8., 268., 4.], + [6., 9., 295., 6.]]) + +linkage_ytdist_complete = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [1., 6., 400., 3.], + [0., 7., 412., 3.], + [8., 9., 996., 6.]]) + +linkage_ytdist_average = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 333.5, 3.], + [1., 6., 347.5, 3.], + [8., 9., 680.77777778, 6.]]) + +linkage_ytdist_weighted = array([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 333.5, 3.], + [1., 6., 347.5, 3.], + [8., 9., 670.125, 6.]]) + +# the optimal leaf ordering of linkage_ytdist_single +linkage_ytdist_single_olo = array([[5., 2., 138., 2.], + [4., 3., 219., 2.], + [7., 0., 255., 3.], + [1., 8., 268., 4.], + [6., 9., 295., 6.]]) + +X = array([[1.43054825, -7.5693489], + [6.95887839, 6.82293382], + [2.87137846, -9.68248579], + [7.87974764, -6.05485803], + [8.24018364, -6.09495602], + [7.39020262, 8.54004355]]) + +linkage_X_centroid = array([[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 6.43614494, 4.], + [7., 9., 15.17363237, 6.]]) + +linkage_X_median = array([[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 6.43614494, 4.], + [7., 9., 15.17363237, 6.]]) + +linkage_X_ward = array([[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 9.10208346, 4.], + [7., 9., 24.7784379, 6.]]) + +# the optimal leaf ordering of linkage_X_ward +linkage_X_ward_olo = array([[4., 3., 0.36265956, 2.], + [5., 1., 1.77045373, 2.], + [2., 0., 2.55760419, 2.], + [6., 8., 9.10208346, 4.], + [7., 9., 24.7784379, 6.]]) + +inconsistent_ytdist = { + 1: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [255., 0., 1., 0.], + [268., 0., 1., 0.], + [295., 0., 1., 0.]]), + 2: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [237., 25.45584412, 2., 0.70710678], + [261.5, 9.19238816, 2., 0.70710678], + [233.66666667, 83.9424406, 3., 0.7306594]]), + 3: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [237., 25.45584412, 2., 0.70710678], + [247.33333333, 25.38372182, 3., 0.81417007], + [239., 69.36377537, 4., 0.80733783]]), + 4: array([[138., 0., 1., 0.], + [219., 0., 1., 0.], + [237., 25.45584412, 2., 0.70710678], + [247.33333333, 25.38372182, 3., 0.81417007], + [235., 60.73302232, 5., 0.98793042]])} + +fcluster_inconsistent = { + 0.8: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 1.0: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1])} + +fcluster_distance = { + 0.6: array([4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 3, + 1, 1, 1, 2, 1, 1, 1, 1, 1]), + 1.0: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1])} + +fcluster_maxclust = { + 8.0: array([5, 5, 5, 5, 5, 5, 5, 6, 5, 5, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 4, + 1, 1, 1, 3, 1, 1, 1, 1, 2]), + 4.0: array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 1]), + 1.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1])} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_disjoint_set.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..a73512d35eef168f625a1942a87d248e73a71aa2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_disjoint_set.py @@ -0,0 +1,202 @@ +import pytest +from pytest import raises as assert_raises +import numpy as np +from scipy.cluster.hierarchy import DisjointSet +import string + + +def generate_random_token(): + k = len(string.ascii_letters) + tokens = list(np.arange(k, dtype=int)) + tokens += list(np.arange(k, dtype=float)) + tokens += list(string.ascii_letters) + tokens += [None for i in range(k)] + tokens = np.array(tokens, dtype=object) + rng = np.random.RandomState(seed=0) + + while 1: + size = rng.randint(1, 3) + element = rng.choice(tokens, size) + if size == 1: + yield element[0] + else: + yield tuple(element) + + +def get_elements(n): + # dict is deterministic without difficulty of comparing numpy ints + elements = {} + for element in generate_random_token(): + if element not in elements: + elements[element] = len(elements) + if len(elements) >= n: + break + return list(elements.keys()) + + +def test_init(): + n = 10 + elements = get_elements(n) + dis = DisjointSet(elements) + assert dis.n_subsets == n + assert list(dis) == elements + + +def test_len(): + n = 10 + elements = get_elements(n) + dis = DisjointSet(elements) + assert len(dis) == n + + dis.add("dummy") + assert len(dis) == n + 1 + + +@pytest.mark.parametrize("n", [10, 100]) +def test_contains(n): + elements = get_elements(n) + dis = DisjointSet(elements) + for x in elements: + assert x in dis + + assert "dummy" not in dis + + +@pytest.mark.parametrize("n", [10, 100]) +def test_add(n): + elements = get_elements(n) + dis1 = DisjointSet(elements) + + dis2 = DisjointSet() + for i, x in enumerate(elements): + dis2.add(x) + assert len(dis2) == i + 1 + + # test idempotency by adding element again + dis2.add(x) + assert len(dis2) == i + 1 + + assert list(dis1) == list(dis2) + + +def test_element_not_present(): + elements = get_elements(n=10) + dis = DisjointSet(elements) + + with assert_raises(KeyError): + dis["dummy"] + + with assert_raises(KeyError): + dis.merge(elements[0], "dummy") + + with assert_raises(KeyError): + dis.connected(elements[0], "dummy") + + +@pytest.mark.parametrize("direction", ["forwards", "backwards"]) +@pytest.mark.parametrize("n", [10, 100]) +def test_linear_union_sequence(n, direction): + elements = get_elements(n) + dis = DisjointSet(elements) + assert elements == list(dis) + + indices = list(range(n - 1)) + if direction == "backwards": + indices = indices[::-1] + + for it, i in enumerate(indices): + assert not dis.connected(elements[i], elements[i + 1]) + assert dis.merge(elements[i], elements[i + 1]) + assert dis.connected(elements[i], elements[i + 1]) + assert dis.n_subsets == n - 1 - it + + roots = [dis[i] for i in elements] + if direction == "forwards": + assert all(elements[0] == r for r in roots) + else: + assert all(elements[-2] == r for r in roots) + assert not dis.merge(elements[0], elements[-1]) + + +@pytest.mark.parametrize("n", [10, 100]) +def test_self_unions(n): + elements = get_elements(n) + dis = DisjointSet(elements) + + for x in elements: + assert dis.connected(x, x) + assert not dis.merge(x, x) + assert dis.connected(x, x) + assert dis.n_subsets == len(elements) + + assert elements == list(dis) + roots = [dis[x] for x in elements] + assert elements == roots + + +@pytest.mark.parametrize("order", ["ab", "ba"]) +@pytest.mark.parametrize("n", [10, 100]) +def test_equal_size_ordering(n, order): + elements = get_elements(n) + dis = DisjointSet(elements) + + rng = np.random.RandomState(seed=0) + indices = np.arange(n) + rng.shuffle(indices) + + for i in range(0, len(indices), 2): + a, b = elements[indices[i]], elements[indices[i + 1]] + if order == "ab": + assert dis.merge(a, b) + else: + assert dis.merge(b, a) + + expected = elements[min(indices[i], indices[i + 1])] + assert dis[a] == expected + assert dis[b] == expected + + +@pytest.mark.parametrize("kmax", [5, 10]) +def test_binary_tree(kmax): + n = 2**kmax + elements = get_elements(n) + dis = DisjointSet(elements) + rng = np.random.RandomState(seed=0) + + for k in 2**np.arange(kmax): + for i in range(0, n, 2 * k): + r1, r2 = rng.randint(0, k, size=2) + a, b = elements[i + r1], elements[i + k + r2] + assert not dis.connected(a, b) + assert dis.merge(a, b) + assert dis.connected(a, b) + + assert elements == list(dis) + roots = [dis[i] for i in elements] + expected_indices = np.arange(n) - np.arange(n) % (2 * k) + expected = [elements[i] for i in expected_indices] + assert roots == expected + + +@pytest.mark.parametrize("n", [10, 100]) +def test_subsets(n): + elements = get_elements(n) + dis = DisjointSet(elements) + + rng = np.random.RandomState(seed=0) + for i, j in rng.randint(0, n, (n, 2)): + x = elements[i] + y = elements[j] + + expected = {element for element in dis if {dis[element]} == {dis[x]}} + assert dis.subset_size(x) == len(dis.subset(x)) + assert expected == dis.subset(x) + + expected = {dis[element]: set() for element in dis} + for element in dis: + expected[dis[element]].add(element) + expected = list(expected.values()) + assert expected == dis.subsets() + + dis.merge(x, y) + assert dis.subset(x) == dis.subset(y) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_hierarchy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_hierarchy.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd0e37c59f3b004b09ce1662a98b53505398453 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_hierarchy.py @@ -0,0 +1,1300 @@ +# +# Author: Damian Eads +# Date: April 17, 2008 +# +# Copyright (C) 2008 Damian Eads +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import numpy as np +from numpy.testing import (assert_allclose, assert_equal, assert_array_equal, assert_, + assert_warns) +import pytest +from pytest import raises as assert_raises + +import scipy.cluster.hierarchy +from scipy.cluster.hierarchy import ( + ClusterWarning, linkage, from_mlab_linkage, to_mlab_linkage, + num_obs_linkage, inconsistent, cophenet, fclusterdata, fcluster, + is_isomorphic, single, leaders, + correspond, is_monotonic, maxdists, maxinconsts, maxRstat, + is_valid_linkage, is_valid_im, to_tree, leaves_list, dendrogram, + set_link_color_palette, cut_tree, optimal_leaf_ordering, + _order_cluster_tree, _hierarchy, _LINKAGE_METHODS) +from scipy.spatial.distance import pdist +from scipy.cluster._hierarchy import Heap +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import xp_assert_close, xp_assert_equal + +from threading import Lock + +from . import hierarchy_test_data + + +# Matplotlib is not a scipy dependency but is optionally used in dendrogram, so +# check if it's available +try: + import matplotlib + # and set the backend to be Agg (no gui) + matplotlib.use('Agg') + # before importing pyplot + import matplotlib.pyplot as plt + have_matplotlib = True +except Exception: + have_matplotlib = False + + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + + +class TestLinkage: + + @skip_xp_backends(cpu_only=True) + def test_linkage_non_finite_elements_in_distance_matrix(self, xp): + # Tests linkage(Y) where Y contains a non-finite element (e.g. NaN or Inf). + # Exception expected. + y = xp.asarray([xp.nan] + [0.0]*5) + assert_raises(ValueError, linkage, y) + + @skip_xp_backends(cpu_only=True) + def test_linkage_empty_distance_matrix(self, xp): + # Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected. + y = xp.zeros((0,)) + assert_raises(ValueError, linkage, y) + + @skip_xp_backends(cpu_only=True) + def test_linkage_tdist(self, xp): + for method in ['single', 'complete', 'average', 'weighted']: + self.check_linkage_tdist(method, xp) + + def check_linkage_tdist(self, method, xp): + # Tests linkage(Y, method) on the tdist data set. + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), method) + expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_' + method) + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10) + + @skip_xp_backends(cpu_only=True) + def test_linkage_X(self, xp): + for method in ['centroid', 'median', 'ward']: + self.check_linkage_q(method, xp) + + def check_linkage_q(self, method, xp): + # Tests linkage(Y, method) on the Q data set. + Z = linkage(xp.asarray(hierarchy_test_data.X), method) + expectedZ = getattr(hierarchy_test_data, 'linkage_X_' + method) + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06) + + y = scipy.spatial.distance.pdist(hierarchy_test_data.X, + metric="euclidean") + Z = linkage(xp.asarray(y), method) + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06) + + @skip_xp_backends(cpu_only=True) + def test_compare_with_trivial(self, xp): + rng = np.random.RandomState(0) + n = 20 + X = rng.rand(n, 2) + d = pdist(X) + + for method, code in _LINKAGE_METHODS.items(): + Z_trivial = _hierarchy.linkage(d, n, code) + Z = linkage(xp.asarray(d), method) + xp_assert_close(Z, xp.asarray(Z_trivial), rtol=1e-14, atol=1e-15) + + @skip_xp_backends(cpu_only=True) + def test_optimal_leaf_ordering(self, xp): + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), optimal_ordering=True) + expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_single_olo') + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10) + + +@skip_xp_backends(cpu_only=True) +class TestLinkageTies: + + _expectations = { + 'single': np.array([[0, 1, 1.41421356, 2], + [2, 3, 1.41421356, 3]]), + 'complete': np.array([[0, 1, 1.41421356, 2], + [2, 3, 2.82842712, 3]]), + 'average': np.array([[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + 'weighted': np.array([[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + 'centroid': np.array([[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + 'median': np.array([[0, 1, 1.41421356, 2], + [2, 3, 2.12132034, 3]]), + 'ward': np.array([[0, 1, 1.41421356, 2], + [2, 3, 2.44948974, 3]]), + } + + def test_linkage_ties(self, xp): + for method in ['single', 'complete', 'average', 'weighted', + 'centroid', 'median', 'ward']: + self.check_linkage_ties(method, xp) + + def check_linkage_ties(self, method, xp): + X = xp.asarray([[-1, -1], [0, 0], [1, 1]]) + Z = linkage(X, method=method) + expectedZ = self._expectations[method] + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06) + + +@skip_xp_backends(cpu_only=True) +class TestInconsistent: + + def test_inconsistent_tdist(self, xp): + for depth in hierarchy_test_data.inconsistent_ytdist: + self.check_inconsistent_tdist(depth, xp) + + def check_inconsistent_tdist(self, depth, xp): + Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single) + xp_assert_close(inconsistent(Z, depth), + xp.asarray(hierarchy_test_data.inconsistent_ytdist[depth])) + + +@skip_xp_backends(cpu_only=True) +class TestCopheneticDistance: + + def test_linkage_cophenet_tdist_Z(self, xp): + # Tests cophenet(Z) on tdist data set. + expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, + 295, 138, 219, 295, 295]) + Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single) + M = cophenet(Z) + xp_assert_close(M, xp.asarray(expectedM, dtype=xp.float64), atol=1e-10) + + def test_linkage_cophenet_tdist_Z_Y(self, xp): + # Tests cophenet(Z, Y) on tdist data set. + Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single) + (c, M) = cophenet(Z, xp.asarray(hierarchy_test_data.ytdist)) + expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, + 295, 138, 219, 295, 295], dtype=xp.float64) + expectedc = xp.asarray(0.639931296433393415057366837573, dtype=xp.float64)[()] + xp_assert_close(c, expectedc, atol=1e-10) + xp_assert_close(M, expectedM, atol=1e-10) + + def test_gh_22183(self, xp): + # check for lack of segfault + # (out of bounds memory access) + # and correct interception of + # invalid linkage matrix + arr=[[0.0, 1.0, 1.0, 2.0], + [2.0, 12.0, 1.0, 3.0], + [3.0, 4.0, 1.0, 2.0], + [5.0, 14.0, 1.0, 3.0], + [6.0, 7.0, 1.0, 2.0], + [8.0, 16.0, 1.0, 3.0], + [9.0, 10.0, 1.0, 2.0], + [11.0, 18.0, 1.0, 3.0], + [13.0, 15.0, 2.0, 6.0], + [17.0, 20.0, 2.0, 32.0], + [19.0, 21.0, 2.0, 12.0]] + with pytest.raises(ValueError, match="excessive observations"): + cophenet(xp.asarray(arr)) + + +class TestMLabLinkageConversion: + + def test_mlab_linkage_conversion_empty(self, xp): + # Tests from/to_mlab_linkage on empty linkage array. + X = xp.asarray([], dtype=xp.float64) + xp_assert_equal(from_mlab_linkage(X), X) + xp_assert_equal(to_mlab_linkage(X), X) + + @skip_xp_backends(cpu_only=True) + def test_mlab_linkage_conversion_single_row(self, xp): + # Tests from/to_mlab_linkage on linkage array with single row. + Z = xp.asarray([[0., 1., 3., 2.]]) + Zm = xp.asarray([[1, 2, 3]]) + xp_assert_close(from_mlab_linkage(Zm), xp.asarray(Z, dtype=xp.float64), + rtol=1e-15) + xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64), + rtol=1e-15) + + @skip_xp_backends(cpu_only=True) + def test_mlab_linkage_conversion_multiple_rows(self, xp): + # Tests from/to_mlab_linkage on linkage array with multiple rows. + Zm = xp.asarray([[3, 6, 138], [4, 5, 219], + [1, 8, 255], [2, 9, 268], [7, 10, 295]]) + Z = xp.asarray([[2., 5., 138., 2.], + [3., 4., 219., 2.], + [0., 7., 255., 3.], + [1., 8., 268., 4.], + [6., 9., 295., 6.]], + dtype=xp.float64) + xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15) + xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64), + rtol=1e-15) + + +@skip_xp_backends(cpu_only=True) +class TestFcluster: + + def test_fclusterdata(self, xp): + for t in hierarchy_test_data.fcluster_inconsistent: + self.check_fclusterdata(t, 'inconsistent', xp) + for t in hierarchy_test_data.fcluster_distance: + self.check_fclusterdata(t, 'distance', xp) + for t in hierarchy_test_data.fcluster_maxclust: + self.check_fclusterdata(t, 'maxclust', xp) + + def check_fclusterdata(self, t, criterion, xp): + # Tests fclusterdata(X, criterion=criterion, t=t) on a random 3-cluster data set + expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t]) + X = xp.asarray(hierarchy_test_data.Q_X) + T = fclusterdata(X, criterion=criterion, t=t) + assert_(is_isomorphic(T, expectedT)) + + def test_fcluster(self, xp): + for t in hierarchy_test_data.fcluster_inconsistent: + self.check_fcluster(t, 'inconsistent', xp) + for t in hierarchy_test_data.fcluster_distance: + self.check_fcluster(t, 'distance', xp) + for t in hierarchy_test_data.fcluster_maxclust: + self.check_fcluster(t, 'maxclust', xp) + + def check_fcluster(self, t, criterion, xp): + # Tests fcluster(Z, criterion=criterion, t=t) on a random 3-cluster data set. + expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t]) + Z = single(xp.asarray(hierarchy_test_data.Q_X)) + T = fcluster(Z, criterion=criterion, t=t) + assert_(is_isomorphic(T, expectedT)) + + def test_fcluster_monocrit(self, xp): + for t in hierarchy_test_data.fcluster_distance: + self.check_fcluster_monocrit(t, xp) + for t in hierarchy_test_data.fcluster_maxclust: + self.check_fcluster_maxclust_monocrit(t, xp) + + def check_fcluster_monocrit(self, t, xp): + expectedT = xp.asarray(hierarchy_test_data.fcluster_distance[t]) + Z = single(xp.asarray(hierarchy_test_data.Q_X)) + T = fcluster(Z, t, criterion='monocrit', monocrit=maxdists(Z)) + assert_(is_isomorphic(T, expectedT)) + + def check_fcluster_maxclust_monocrit(self, t, xp): + expectedT = xp.asarray(hierarchy_test_data.fcluster_maxclust[t]) + Z = single(xp.asarray(hierarchy_test_data.Q_X)) + T = fcluster(Z, t, criterion='maxclust_monocrit', monocrit=maxdists(Z)) + assert_(is_isomorphic(T, expectedT)) + + def test_fcluster_maxclust_gh_12651(self, xp): + y = xp.asarray([[1], [4], [5]]) + Z = single(y) + assert_array_equal(fcluster(Z, t=1, criterion="maxclust"), + xp.asarray([1, 1, 1])) + assert_array_equal(fcluster(Z, t=2, criterion="maxclust"), + xp.asarray([2, 1, 1])) + assert_array_equal(fcluster(Z, t=3, criterion="maxclust"), + xp.asarray([1, 2, 3])) + assert_array_equal(fcluster(Z, t=5, criterion="maxclust"), + xp.asarray([1, 2, 3])) + + +@skip_xp_backends(cpu_only=True) +class TestLeaders: + + def test_leaders_single(self, xp): + # Tests leaders using a flat clustering generated by single linkage. + X = hierarchy_test_data.Q_X + Y = pdist(X) + Y = xp.asarray(Y) + Z = linkage(Y) + T = fcluster(Z, criterion='maxclust', t=3) + Lright = (xp.asarray([53, 55, 56]), xp.asarray([2, 3, 1])) + T = xp.asarray(T, dtype=xp.int32) + L = leaders(Z, T) + assert_allclose(np.concatenate(L), np.concatenate(Lright), rtol=1e-15) + + +@skip_xp_backends(np_only=True, + reason='`is_isomorphic` only supports NumPy backend') +class TestIsIsomorphic: + + @skip_xp_backends(np_only=True, + reason='array-likes only supported for NumPy backend') + def test_array_like(self, xp): + assert is_isomorphic([1, 1, 1], [2, 2, 2]) + assert is_isomorphic([], []) + + def test_is_isomorphic_1(self, xp): + # Tests is_isomorphic on test case #1 (one flat cluster, different labellings) + a = xp.asarray([1, 1, 1]) + b = xp.asarray([2, 2, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + def test_is_isomorphic_2(self, xp): + # Tests is_isomorphic on test case #2 (two flat clusters, different labelings) + a = xp.asarray([1, 7, 1]) + b = xp.asarray([2, 3, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + def test_is_isomorphic_3(self, xp): + # Tests is_isomorphic on test case #3 (no flat clusters) + a = xp.asarray([]) + b = xp.asarray([]) + assert is_isomorphic(a, b) + + def test_is_isomorphic_4A(self, xp): + # Tests is_isomorphic on test case #4A + # (3 flat clusters, different labelings, isomorphic) + a = xp.asarray([1, 2, 3]) + b = xp.asarray([1, 3, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + def test_is_isomorphic_4B(self, xp): + # Tests is_isomorphic on test case #4B + # (3 flat clusters, different labelings, nonisomorphic) + a = xp.asarray([1, 2, 3, 3]) + b = xp.asarray([1, 3, 2, 3]) + assert is_isomorphic(a, b) is False + assert is_isomorphic(b, a) is False + + def test_is_isomorphic_4C(self, xp): + # Tests is_isomorphic on test case #4C + # (3 flat clusters, different labelings, isomorphic) + a = xp.asarray([7, 2, 3]) + b = xp.asarray([6, 3, 2]) + assert is_isomorphic(a, b) + assert is_isomorphic(b, a) + + def test_is_isomorphic_5(self, xp): + # Tests is_isomorphic on test case #5 (1000 observations, 2/3/5 random + # clusters, random permutation of the labeling). + for nc in [2, 3, 5]: + self.help_is_isomorphic_randperm(1000, nc, xp=xp) + + def test_is_isomorphic_6(self, xp): + # Tests is_isomorphic on test case #5A (1000 observations, 2/3/5 random + # clusters, random permutation of the labeling, slightly + # nonisomorphic.) + for nc in [2, 3, 5]: + self.help_is_isomorphic_randperm(1000, nc, True, 5, xp=xp) + + def test_is_isomorphic_7(self, xp): + # Regression test for gh-6271 + a = xp.asarray([1, 2, 3]) + b = xp.asarray([1, 1, 1]) + assert not is_isomorphic(a, b) + + def help_is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0, + *, xp): + for k in range(3): + a = (np.random.rand(nobs) * nclusters).astype(int) + b = np.zeros(a.size, dtype=int) + P = np.random.permutation(nclusters) + for i in range(0, a.shape[0]): + b[i] = P[a[i]] + if noniso: + Q = np.random.permutation(nobs) + b[Q[0:nerrors]] += 1 + b[Q[0:nerrors]] %= nclusters + a = xp.asarray(a) + b = xp.asarray(b) + assert is_isomorphic(a, b) == (not noniso) + assert is_isomorphic(b, a) == (not noniso) + + +@skip_xp_backends(cpu_only=True) +class TestIsValidLinkage: + + def test_is_valid_linkage_various_size(self, xp): + for nrow, ncol, valid in [(2, 5, False), (2, 3, False), + (1, 4, True), (2, 4, True)]: + self.check_is_valid_linkage_various_size(nrow, ncol, valid, xp) + + def check_is_valid_linkage_various_size(self, nrow, ncol, valid, xp): + # Tests is_valid_linkage(Z) with linkage matrices of various sizes + Z = xp.asarray([[0, 1, 3.0, 2, 5], + [3, 2, 4.0, 3, 3]], dtype=xp.float64) + Z = Z[:nrow, :ncol] + assert_(is_valid_linkage(Z) == valid) + if not valid: + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_int_type(self, xp): + # Tests is_valid_linkage(Z) with integer type. + Z = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.int64) + assert_(is_valid_linkage(Z) is False) + assert_raises(TypeError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_empty(self, xp): + # Tests is_valid_linkage(Z) with empty linkage. + Z = xp.zeros((0, 4), dtype=xp.float64) + assert_(is_valid_linkage(Z) is False) + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_4_and_up(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + assert_(is_valid_linkage(Z) is True) + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_is_valid_linkage_4_and_up_neg_index_left(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative indices (left). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + Z[i//2,0] = -2 + assert_(is_valid_linkage(Z) is False) + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_is_valid_linkage_4_and_up_neg_index_right(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative indices (right). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + Z[i//2,1] = -2 + assert_(is_valid_linkage(Z) is False) + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_is_valid_linkage_4_and_up_neg_dist(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative distances. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + Z[i//2,2] = -0.5 + assert_(is_valid_linkage(Z) is False) + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_is_valid_linkage_4_and_up_neg_counts(self, xp): + # Tests is_valid_linkage(Z) on linkage on observation sets between + # sizes 4 and 15 (step size 3) with negative counts. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + Z[i//2,3] = -2 + assert_(is_valid_linkage(Z) is False) + assert_raises(ValueError, is_valid_linkage, Z, throw=True) + + +@skip_xp_backends(cpu_only=True) +class TestIsValidInconsistent: + + def test_is_valid_im_int_type(self, xp): + # Tests is_valid_im(R) with integer type. + R = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.int64) + assert_(is_valid_im(R) is False) + assert_raises(TypeError, is_valid_im, R, throw=True) + + def test_is_valid_im_various_size(self, xp): + for nrow, ncol, valid in [(2, 5, False), (2, 3, False), + (1, 4, True), (2, 4, True)]: + self.check_is_valid_im_various_size(nrow, ncol, valid, xp) + + def check_is_valid_im_various_size(self, nrow, ncol, valid, xp): + # Tests is_valid_im(R) with linkage matrices of various sizes + R = xp.asarray([[0, 1, 3.0, 2, 5], + [3, 2, 4.0, 3, 3]], dtype=xp.float64) + R = R[:nrow, :ncol] + assert_(is_valid_im(R) == valid) + if not valid: + assert_raises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_empty(self, xp): + # Tests is_valid_im(R) with empty inconsistency matrix. + R = xp.zeros((0, 4), dtype=xp.float64) + assert_(is_valid_im(R) is False) + assert_raises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_4_and_up(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + R = inconsistent(Z) + assert_(is_valid_im(R) is True) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment') + def test_is_valid_im_4_and_up_neg_index_left(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3) with negative link height means. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + R = inconsistent(Z) + R[i//2,0] = -2.0 + assert_(is_valid_im(R) is False) + assert_raises(ValueError, is_valid_im, R, throw=True) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment') + def test_is_valid_im_4_and_up_neg_index_right(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3) with negative link height standard deviations. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + R = inconsistent(Z) + R[i//2,1] = -2.0 + assert_(is_valid_im(R) is False) + assert_raises(ValueError, is_valid_im, R, throw=True) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment') + def test_is_valid_im_4_and_up_neg_dist(self, xp): + # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 + # (step size 3) with negative link counts. + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + R = inconsistent(Z) + R[i//2,2] = -0.5 + assert_(is_valid_im(R) is False) + assert_raises(ValueError, is_valid_im, R, throw=True) + + +class TestNumObsLinkage: + + @skip_xp_backends(cpu_only=True) + def test_num_obs_linkage_empty(self, xp): + # Tests num_obs_linkage(Z) with empty linkage. + Z = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, num_obs_linkage, Z) + + def test_num_obs_linkage_1x4(self, xp): + # Tests num_obs_linkage(Z) on linkage over 2 observations. + Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64) + assert_equal(num_obs_linkage(Z), 2) + + def test_num_obs_linkage_2x4(self, xp): + # Tests num_obs_linkage(Z) on linkage over 3 observations. + Z = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.float64) + assert_equal(num_obs_linkage(Z), 3) + + @skip_xp_backends(cpu_only=True) + def test_num_obs_linkage_4_and_up(self, xp): + # Tests num_obs_linkage(Z) on linkage on observation sets between sizes + # 4 and 15 (step size 3). + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + assert_equal(num_obs_linkage(Z), i) + + +@skip_xp_backends(cpu_only=True) +class TestLeavesList: + + def test_leaves_list_1x4(self, xp): + # Tests leaves_list(Z) on a 1x4 linkage. + Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64) + to_tree(Z) + assert_allclose(leaves_list(Z), [0, 1], rtol=1e-15) + + def test_leaves_list_2x4(self, xp): + # Tests leaves_list(Z) on a 2x4 linkage. + Z = xp.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=xp.float64) + to_tree(Z) + assert_allclose(leaves_list(Z), [0, 1, 2], rtol=1e-15) + + def test_leaves_list_Q(self, xp): + for method in ['single', 'complete', 'average', 'weighted', 'centroid', + 'median', 'ward']: + self.check_leaves_list_Q(method, xp) + + def check_leaves_list_Q(self, method, xp): + # Tests leaves_list(Z) on the Q data set + X = xp.asarray(hierarchy_test_data.Q_X) + Z = linkage(X, method) + node = to_tree(Z) + assert_allclose(node.pre_order(), leaves_list(Z), rtol=1e-15) + + def test_Q_subtree_pre_order(self, xp): + # Tests that pre_order() works when called on sub-trees. + X = xp.asarray(hierarchy_test_data.Q_X) + Z = linkage(X, 'single') + node = to_tree(Z) + assert_allclose(node.pre_order(), (node.get_left().pre_order() + + node.get_right().pre_order()), + rtol=1e-15) + + +@skip_xp_backends(cpu_only=True) +class TestCorrespond: + + def test_correspond_empty(self, xp): + # Tests correspond(Z, y) with empty linkage and condensed distance matrix. + y = xp.zeros((0,), dtype=xp.float64) + Z = xp.zeros((0,4), dtype=xp.float64) + assert_raises(ValueError, correspond, Z, y) + + def test_correspond_2_and_up(self, xp): + # Tests correspond(Z, y) on linkage and CDMs over observation sets of + # different sizes. + for i in range(2, 4): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + assert_(correspond(Z, y)) + for i in range(4, 15, 3): + y = np.random.rand(i*(i-1)//2) + y = xp.asarray(y) + Z = linkage(y) + assert_(correspond(Z, y)) + + def test_correspond_4_and_up(self, xp): + # Tests correspond(Z, y) on linkage and CDMs over observation sets of + # different sizes. Correspondence should be false. + for (i, j) in (list(zip(list(range(2, 4)), list(range(3, 5)))) + + list(zip(list(range(3, 5)), list(range(2, 4))))): + y = np.random.rand(i*(i-1)//2) + y2 = np.random.rand(j*(j-1)//2) + y = xp.asarray(y) + y2 = xp.asarray(y2) + Z = linkage(y) + Z2 = linkage(y2) + assert not correspond(Z, y2) + assert not correspond(Z2, y) + + def test_correspond_4_and_up_2(self, xp): + # Tests correspond(Z, y) on linkage and CDMs over observation sets of + # different sizes. Correspondence should be false. + for (i, j) in (list(zip(list(range(2, 7)), list(range(16, 21)))) + + list(zip(list(range(2, 7)), list(range(16, 21))))): + y = np.random.rand(i*(i-1)//2) + y2 = np.random.rand(j*(j-1)//2) + y = xp.asarray(y) + y2 = xp.asarray(y2) + Z = linkage(y) + Z2 = linkage(y2) + assert not correspond(Z, y2) + assert not correspond(Z2, y) + + def test_num_obs_linkage_multi_matrix(self, xp): + # Tests num_obs_linkage with observation matrices of multiple sizes. + for n in range(2, 10): + X = np.random.rand(n, 4) + Y = pdist(X) + Y = xp.asarray(Y) + Z = linkage(Y) + assert_equal(num_obs_linkage(Z), n) + + +@skip_xp_backends(cpu_only=True) +class TestIsMonotonic: + + def test_is_monotonic_empty(self, xp): + # Tests is_monotonic(Z) on an empty linkage. + Z = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, is_monotonic, Z) + + def test_is_monotonic_1x4(self, xp): + # Tests is_monotonic(Z) on 1x4 linkage. Expecting True. + Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64) + assert is_monotonic(Z) + + def test_is_monotonic_2x4_T(self, xp): + # Tests is_monotonic(Z) on 2x4 linkage. Expecting True. + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 3]], dtype=xp.float64) + assert is_monotonic(Z) + + def test_is_monotonic_2x4_F(self, xp): + # Tests is_monotonic(Z) on 2x4 linkage. Expecting False. + Z = xp.asarray([[0, 1, 0.4, 2], + [2, 3, 0.3, 3]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_3x4_T(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage. Expecting True. + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 2], + [4, 5, 0.6, 4]], dtype=xp.float64) + assert is_monotonic(Z) + + def test_is_monotonic_3x4_F1(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False. + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.2, 2], + [4, 5, 0.6, 4]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_3x4_F2(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False. + Z = xp.asarray([[0, 1, 0.8, 2], + [2, 3, 0.4, 2], + [4, 5, 0.6, 4]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_3x4_F3(self, xp): + # Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False + Z = xp.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 2], + [4, 5, 0.2, 4]], dtype=xp.float64) + assert not is_monotonic(Z) + + def test_is_monotonic_tdist_linkage1(self, xp): + # Tests is_monotonic(Z) on clustering generated by single linkage on + # tdist data set. Expecting True. + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + assert is_monotonic(Z) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment') + def test_is_monotonic_tdist_linkage2(self, xp): + # Tests is_monotonic(Z) on clustering generated by single linkage on + # tdist data set. Perturbing. Expecting False. + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + Z[2,2] = 0.0 + assert not is_monotonic(Z) + + def test_is_monotonic_Q_linkage(self, xp): + # Tests is_monotonic(Z) on clustering generated by single linkage on + # Q data set. Expecting True. + X = xp.asarray(hierarchy_test_data.Q_X) + Z = linkage(X, 'single') + assert is_monotonic(Z) + + +@skip_xp_backends(cpu_only=True) +class TestMaxDists: + + def test_maxdists_empty_linkage(self, xp): + # Tests maxdists(Z) on empty linkage. Expecting exception. + Z = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, maxdists, Z) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment') + def test_maxdists_one_cluster_linkage(self, xp): + # Tests maxdists(Z) on linkage with one cluster. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + MD = maxdists(Z) + expectedMD = calculate_maximum_distances(Z, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment') + def test_maxdists_Q_linkage(self, xp): + for method in ['single', 'complete', 'ward', 'centroid', 'median']: + self.check_maxdists_Q_linkage(method, xp) + + def check_maxdists_Q_linkage(self, method, xp): + # Tests maxdists(Z) on the Q data set + X = xp.asarray(hierarchy_test_data.Q_X) + Z = linkage(X, method) + MD = maxdists(Z) + expectedMD = calculate_maximum_distances(Z, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + +class TestMaxInconsts: + + @skip_xp_backends(cpu_only=True) + def test_maxinconsts_empty_linkage(self, xp): + # Tests maxinconsts(Z, R) on empty linkage. Expecting exception. + Z = xp.zeros((0, 4), dtype=xp.float64) + R = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, maxinconsts, Z, R) + + def test_maxinconsts_difrow_linkage(self, xp): + # Tests maxinconsts(Z, R) on linkage and inconsistency matrices with + # different numbers of clusters. Expecting exception. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = np.random.rand(2, 4) + R = xp.asarray(R) + assert_raises(ValueError, maxinconsts, Z, R) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment', + cpu_only=True) + def test_maxinconsts_one_cluster_linkage(self, xp): + # Tests maxinconsts(Z, R) on linkage with one cluster. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64) + MD = maxinconsts(Z, R) + expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment', + cpu_only=True) + def test_maxinconsts_Q_linkage(self, xp): + for method in ['single', 'complete', 'ward', 'centroid', 'median']: + self.check_maxinconsts_Q_linkage(method, xp) + + def check_maxinconsts_Q_linkage(self, method, xp): + # Tests maxinconsts(Z, R) on the Q data set + X = xp.asarray(hierarchy_test_data.Q_X) + Z = linkage(X, method) + R = inconsistent(Z) + MD = maxinconsts(Z, R) + expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + +class TestMaxRStat: + + def test_maxRstat_invalid_index(self, xp): + for i in [3.3, -1, 4]: + self.check_maxRstat_invalid_index(i, xp) + + def check_maxRstat_invalid_index(self, i, xp): + # Tests maxRstat(Z, R, i). Expecting exception. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64) + if isinstance(i, int): + assert_raises(ValueError, maxRstat, Z, R, i) + else: + assert_raises(TypeError, maxRstat, Z, R, i) + + @skip_xp_backends(cpu_only=True) + def test_maxRstat_empty_linkage(self, xp): + for i in range(4): + self.check_maxRstat_empty_linkage(i, xp) + + def check_maxRstat_empty_linkage(self, i, xp): + # Tests maxRstat(Z, R, i) on empty linkage. Expecting exception. + Z = xp.zeros((0, 4), dtype=xp.float64) + R = xp.zeros((0, 4), dtype=xp.float64) + assert_raises(ValueError, maxRstat, Z, R, i) + + def test_maxRstat_difrow_linkage(self, xp): + for i in range(4): + self.check_maxRstat_difrow_linkage(i, xp) + + def check_maxRstat_difrow_linkage(self, i, xp): + # Tests maxRstat(Z, R, i) on linkage and inconsistency matrices with + # different numbers of clusters. Expecting exception. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = np.random.rand(2, 4) + R = xp.asarray(R) + assert_raises(ValueError, maxRstat, Z, R, i) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment', + cpu_only=True) + def test_maxRstat_one_cluster_linkage(self, xp): + for i in range(4): + self.check_maxRstat_one_cluster_linkage(i, xp) + + def check_maxRstat_one_cluster_linkage(self, i, xp): + # Tests maxRstat(Z, R, i) on linkage with one cluster. + Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) + R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64) + MD = maxRstat(Z, R, 1) + expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment', + cpu_only=True) + def test_maxRstat_Q_linkage(self, xp): + for method in ['single', 'complete', 'ward', 'centroid', 'median']: + for i in range(4): + self.check_maxRstat_Q_linkage(method, i, xp) + + def check_maxRstat_Q_linkage(self, method, i, xp): + # Tests maxRstat(Z, R, i) on the Q data set + X = xp.asarray(hierarchy_test_data.Q_X) + Z = linkage(X, method) + R = inconsistent(Z) + MD = maxRstat(Z, R, 1) + expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp) + xp_assert_close(MD, expectedMD, atol=1e-15) + + +@skip_xp_backends(cpu_only=True) +class TestDendrogram: + + def test_dendrogram_single_linkage_tdist(self, xp): + # Tests dendrogram calculation on single linkage of the tdist data set. + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + R = dendrogram(Z, no_plot=True) + leaves = R["leaves"] + assert_equal(leaves, [2, 5, 1, 0, 3, 4]) + + def test_valid_orientation(self, xp): + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + assert_raises(ValueError, dendrogram, Z, orientation="foo") + + def test_labels_as_array_or_list(self, xp): + # test for gh-12418 + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + labels = [1, 3, 2, 6, 4, 5] + result1 = dendrogram(Z, labels=xp.asarray(labels), no_plot=True) + result2 = dendrogram(Z, labels=labels, no_plot=True) + assert result1 == result2 + + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_valid_label_size(self, xp): + link = xp.asarray([ + [0, 1, 1.0, 4], + [2, 3, 1.0, 5], + [4, 5, 2.0, 6], + ]) + plt.figure() + with pytest.raises(ValueError) as exc_info: + dendrogram(link, labels=list(range(100))) + assert "Dimensions of Z and labels must be consistent."\ + in str(exc_info.value) + + with pytest.raises( + ValueError, + match="Dimensions of Z and labels must be consistent."): + dendrogram(link, labels=[]) + + plt.close() + + @skip_xp_backends('torch', + reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__' + ' and NumPy 2.0' + ) + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_dendrogram_plot(self, xp): + for orientation in ['top', 'bottom', 'left', 'right']: + self.check_dendrogram_plot(orientation, xp) + + def check_dendrogram_plot(self, orientation, xp): + # Tests dendrogram plotting. + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + expected = {'color_list': ['C1', 'C0', 'C0', 'C0', 'C0'], + 'dcoord': [[0.0, 138.0, 138.0, 0.0], + [0.0, 219.0, 219.0, 0.0], + [0.0, 255.0, 255.0, 219.0], + [0.0, 268.0, 268.0, 255.0], + [138.0, 295.0, 295.0, 268.0]], + 'icoord': [[5.0, 5.0, 15.0, 15.0], + [45.0, 45.0, 55.0, 55.0], + [35.0, 35.0, 50.0, 50.0], + [25.0, 25.0, 42.5, 42.5], + [10.0, 10.0, 33.75, 33.75]], + 'ivl': ['2', '5', '1', '0', '3', '4'], + 'leaves': [2, 5, 1, 0, 3, 4], + 'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0', 'C0'], + } + + fig = plt.figure() + ax = fig.add_subplot(221) + + # test that dendrogram accepts ax keyword + R1 = dendrogram(Z, ax=ax, orientation=orientation) + R1['dcoord'] = np.asarray(R1['dcoord']) + assert_equal(R1, expected) + + # test that dendrogram accepts and handle the leaf_font_size and + # leaf_rotation keywords + dendrogram(Z, ax=ax, orientation=orientation, + leaf_font_size=20, leaf_rotation=90) + testlabel = ( + ax.get_xticklabels()[0] + if orientation in ['top', 'bottom'] + else ax.get_yticklabels()[0] + ) + assert_equal(testlabel.get_rotation(), 90) + assert_equal(testlabel.get_size(), 20) + dendrogram(Z, ax=ax, orientation=orientation, + leaf_rotation=90) + testlabel = ( + ax.get_xticklabels()[0] + if orientation in ['top', 'bottom'] + else ax.get_yticklabels()[0] + ) + assert_equal(testlabel.get_rotation(), 90) + dendrogram(Z, ax=ax, orientation=orientation, + leaf_font_size=20) + testlabel = ( + ax.get_xticklabels()[0] + if orientation in ['top', 'bottom'] + else ax.get_yticklabels()[0] + ) + assert_equal(testlabel.get_size(), 20) + plt.close() + + # test plotting to gca (will import pylab) + R2 = dendrogram(Z, orientation=orientation) + plt.close() + R2['dcoord'] = np.asarray(R2['dcoord']) + assert_equal(R2, expected) + + @skip_xp_backends('torch', + reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__' + ' and NumPy 2.0' + ) + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_dendrogram_truncate_mode(self, xp): + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + + R = dendrogram(Z, 2, 'lastp', show_contracted=True) + plt.close() + R['dcoord'] = np.asarray(R['dcoord']) + assert_equal(R, {'color_list': ['C0'], + 'dcoord': [[0.0, 295.0, 295.0, 0.0]], + 'icoord': [[5.0, 5.0, 15.0, 15.0]], + 'ivl': ['(2)', '(4)'], + 'leaves': [6, 9], + 'leaves_color_list': ['C0', 'C0'], + }) + + R = dendrogram(Z, 2, 'mtica', show_contracted=True) + plt.close() + R['dcoord'] = np.asarray(R['dcoord']) + assert_equal(R, {'color_list': ['C1', 'C0', 'C0', 'C0'], + 'dcoord': [[0.0, 138.0, 138.0, 0.0], + [0.0, 255.0, 255.0, 0.0], + [0.0, 268.0, 268.0, 255.0], + [138.0, 295.0, 295.0, 268.0]], + 'icoord': [[5.0, 5.0, 15.0, 15.0], + [35.0, 35.0, 45.0, 45.0], + [25.0, 25.0, 40.0, 40.0], + [10.0, 10.0, 32.5, 32.5]], + 'ivl': ['2', '5', '1', '0', '(2)'], + 'leaves': [2, 5, 1, 0, 7], + 'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0'], + }) + + @pytest.fixture + def dendrogram_lock(self): + return Lock() + + def test_dendrogram_colors(self, xp, dendrogram_lock): + # Tests dendrogram plots with alternate colors + Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single') + + with dendrogram_lock: + # Global color palette might be changed concurrently + set_link_color_palette(['c', 'm', 'y', 'k']) + R = dendrogram(Z, no_plot=True, + above_threshold_color='g', color_threshold=250) + set_link_color_palette(['g', 'r', 'c', 'm', 'y', 'k']) + + color_list = R['color_list'] + assert_equal(color_list, ['c', 'm', 'g', 'g', 'g']) + + # reset color palette (global list) + set_link_color_palette(None) + + def test_dendrogram_leaf_colors_zero_dist(self, xp): + # tests that the colors of leafs are correct for tree + # with two identical points + x = xp.asarray([[1, 0, 0], + [0, 0, 1], + [0, 2, 0], + [0, 0, 1], + [0, 1, 0], + [0, 1, 0]]) + z = linkage(x, "single") + d = dendrogram(z, no_plot=True) + exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2'] + colors = d["leaves_color_list"] + assert_equal(colors, exp_colors) + + def test_dendrogram_leaf_colors(self, xp): + # tests that the colors are correct for a tree + # with two near points ((0, 0, 1.1) and (0, 0, 1)) + x = xp.asarray([[1, 0, 0], + [0, 0, 1.1], + [0, 2, 0], + [0, 0, 1], + [0, 1, 0], + [0, 1, 0]]) + z = linkage(x, "single") + d = dendrogram(z, no_plot=True) + exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2'] + colors = d["leaves_color_list"] + assert_equal(colors, exp_colors) + + +def calculate_maximum_distances(Z, xp): + # Used for testing correctness of maxdists. + n = Z.shape[0] + 1 + B = xp.zeros((n-1,), dtype=Z.dtype) + q = xp.zeros((3,)) + for i in range(0, n - 1): + q[:] = 0.0 + left = Z[i, 0] + right = Z[i, 1] + if left >= n: + q[0] = B[xp.asarray(left, dtype=xp.int64) - n] + if right >= n: + q[1] = B[xp.asarray(right, dtype=xp.int64) - n] + q[2] = Z[i, 2] + B[i] = xp.max(q) + return B + + +def calculate_maximum_inconsistencies(Z, R, k=3, xp=np): + # Used for testing correctness of maxinconsts. + n = Z.shape[0] + 1 + dtype = xp.result_type(Z, R) + B = xp.zeros((n-1,), dtype=dtype) + q = xp.zeros((3,)) + for i in range(0, n - 1): + q[:] = 0.0 + left = Z[i, 0] + right = Z[i, 1] + if left >= n: + q[0] = B[xp.asarray(left, dtype=xp.int64) - n] + if right >= n: + q[1] = B[xp.asarray(right, dtype=xp.int64) - n] + q[2] = R[i, k] + B[i] = xp.max(q) + return B + + +@pytest.mark.thread_unsafe +@skip_xp_backends(cpu_only=True) +def test_unsupported_uncondensed_distance_matrix_linkage_warning(xp): + assert_warns(ClusterWarning, linkage, xp.asarray([[0, 1], [1, 0]])) + + +def test_euclidean_linkage_value_error(xp): + for method in scipy.cluster.hierarchy._EUCLIDEAN_METHODS: + assert_raises(ValueError, linkage, xp.asarray([[1, 1], [1, 1]]), + method=method, metric='cityblock') + + +@skip_xp_backends(cpu_only=True) +def test_2x2_linkage(xp): + Z1 = linkage(xp.asarray([1]), method='single', metric='euclidean') + Z2 = linkage(xp.asarray([[0, 1], [0, 0]]), method='single', metric='euclidean') + xp_assert_close(Z1, Z2, rtol=1e-15) + + +@skip_xp_backends(cpu_only=True) +def test_node_compare(xp): + np.random.seed(23) + nobs = 50 + X = np.random.randn(nobs, 4) + X = xp.asarray(X) + Z = scipy.cluster.hierarchy.ward(X) + tree = to_tree(Z) + assert_(tree > tree.get_left()) + assert_(tree.get_right() > tree.get_left()) + assert_(tree.get_right() == tree.get_right()) + assert_(tree.get_right() != tree.get_left()) + + +@skip_xp_backends(np_only=True, reason='`cut_tree` uses non-standard indexing') +def test_cut_tree(xp): + np.random.seed(23) + nobs = 50 + X = np.random.randn(nobs, 4) + X = xp.asarray(X) + Z = scipy.cluster.hierarchy.ward(X) + cutree = cut_tree(Z) + + # cutree.dtype varies between int32 and int64 over platforms + xp_assert_close(cutree[:, 0], xp.arange(nobs), rtol=1e-15, check_dtype=False) + xp_assert_close(cutree[:, -1], xp.zeros(nobs), rtol=1e-15, check_dtype=False) + assert_equal(np.asarray(cutree).max(0), np.arange(nobs - 1, -1, -1)) + + xp_assert_close(cutree[:, [-5]], cut_tree(Z, n_clusters=5), rtol=1e-15) + xp_assert_close(cutree[:, [-5, -10]], cut_tree(Z, n_clusters=[5, 10]), rtol=1e-15) + xp_assert_close(cutree[:, [-10, -5]], cut_tree(Z, n_clusters=[10, 5]), rtol=1e-15) + + nodes = _order_cluster_tree(Z) + heights = xp.asarray([node.dist for node in nodes]) + + xp_assert_close(cutree[:, np.searchsorted(heights, [5])], + cut_tree(Z, height=5), rtol=1e-15) + xp_assert_close(cutree[:, np.searchsorted(heights, [5, 10])], + cut_tree(Z, height=[5, 10]), rtol=1e-15) + xp_assert_close(cutree[:, np.searchsorted(heights, [10, 5])], + cut_tree(Z, height=[10, 5]), rtol=1e-15) + + +@skip_xp_backends(cpu_only=True) +def test_optimal_leaf_ordering(xp): + # test with the distance vector y + Z = optimal_leaf_ordering(linkage(xp.asarray(hierarchy_test_data.ytdist)), + xp.asarray(hierarchy_test_data.ytdist)) + expectedZ = hierarchy_test_data.linkage_ytdist_single_olo + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10) + + # test with the observation matrix X + Z = optimal_leaf_ordering(linkage(xp.asarray(hierarchy_test_data.X), 'ward'), + xp.asarray(hierarchy_test_data.X)) + expectedZ = hierarchy_test_data.linkage_X_ward_olo + xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06) + + +@skip_xp_backends(np_only=True, reason='`Heap` only supports NumPy backend') +def test_Heap(xp): + values = xp.asarray([2, -1, 0, -1.5, 3]) + heap = Heap(values) + + pair = heap.get_min() + assert_equal(pair['key'], 3) + assert_equal(pair['value'], -1.5) + + heap.remove_min() + pair = heap.get_min() + assert_equal(pair['key'], 1) + assert_equal(pair['value'], -1) + + heap.change_value(1, 2.5) + pair = heap.get_min() + assert_equal(pair['key'], 2) + assert_equal(pair['value'], 0) + + heap.remove_min() + heap.remove_min() + + heap.change_value(1, 10) + pair = heap.get_min() + assert_equal(pair['key'], 4) + assert_equal(pair['value'], 3) + + heap.remove_min() + pair = heap.get_min() + assert_equal(pair['key'], 1) + assert_equal(pair['value'], 10) + + +@skip_xp_backends(cpu_only=True) +def test_centroid_neg_distance(xp): + # gh-21011 + values = xp.asarray([0, 0, -1]) + with pytest.raises(ValueError): + # This is just checking that this doesn't crash + linkage(values, method='centroid') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_vq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_vq.py new file mode 100644 index 0000000000000000000000000000000000000000..d0321e7d81d79472ffc773baeee806aad14212fc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/tests/test_vq.py @@ -0,0 +1,450 @@ +import warnings +import sys +from copy import deepcopy +from threading import Lock + +import numpy as np +from numpy.testing import ( + assert_array_equal, assert_equal, assert_, suppress_warnings +) +import pytest +from pytest import raises as assert_raises + +from scipy.cluster.vq import (kmeans, kmeans2, py_vq, vq, whiten, + ClusterError, _krandinit) +from scipy.cluster import _vq +from scipy.conftest import array_api_compatible +from scipy.sparse._sputils import matrix + +from scipy._lib import array_api_extra as xpx +from scipy._lib._array_api import ( + SCIPY_ARRAY_API, array_namespace, xp_copy, xp_assert_close, xp_assert_equal +) + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + +TESTDATA_2D = np.array([ + -2.2, 1.17, -1.63, 1.69, -2.04, 4.38, -3.09, 0.95, -1.7, 4.79, -1.68, 0.68, + -2.26, 3.34, -2.29, 2.55, -1.72, -0.72, -1.99, 2.34, -2.75, 3.43, -2.45, + 2.41, -4.26, 3.65, -1.57, 1.87, -1.96, 4.03, -3.01, 3.86, -2.53, 1.28, + -4.0, 3.95, -1.62, 1.25, -3.42, 3.17, -1.17, 0.12, -3.03, -0.27, -2.07, + -0.55, -1.17, 1.34, -2.82, 3.08, -2.44, 0.24, -1.71, 2.48, -5.23, 4.29, + -2.08, 3.69, -1.89, 3.62, -2.09, 0.26, -0.92, 1.07, -2.25, 0.88, -2.25, + 2.02, -4.31, 3.86, -2.03, 3.42, -2.76, 0.3, -2.48, -0.29, -3.42, 3.21, + -2.3, 1.73, -2.84, 0.69, -1.81, 2.48, -5.24, 4.52, -2.8, 1.31, -1.67, + -2.34, -1.18, 2.17, -2.17, 2.82, -1.85, 2.25, -2.45, 1.86, -6.79, 3.94, + -2.33, 1.89, -1.55, 2.08, -1.36, 0.93, -2.51, 2.74, -2.39, 3.92, -3.33, + 2.99, -2.06, -0.9, -2.83, 3.35, -2.59, 3.05, -2.36, 1.85, -1.69, 1.8, + -1.39, 0.66, -2.06, 0.38, -1.47, 0.44, -4.68, 3.77, -5.58, 3.44, -2.29, + 2.24, -1.04, -0.38, -1.85, 4.23, -2.88, 0.73, -2.59, 1.39, -1.34, 1.75, + -1.95, 1.3, -2.45, 3.09, -1.99, 3.41, -5.55, 5.21, -1.73, 2.52, -2.17, + 0.85, -2.06, 0.49, -2.54, 2.07, -2.03, 1.3, -3.23, 3.09, -1.55, 1.44, + -0.81, 1.1, -2.99, 2.92, -1.59, 2.18, -2.45, -0.73, -3.12, -1.3, -2.83, + 0.2, -2.77, 3.24, -1.98, 1.6, -4.59, 3.39, -4.85, 3.75, -2.25, 1.71, -3.28, + 3.38, -1.74, 0.88, -2.41, 1.92, -2.24, 1.19, -2.48, 1.06, -1.68, -0.62, + -1.3, 0.39, -1.78, 2.35, -3.54, 2.44, -1.32, 0.66, -2.38, 2.76, -2.35, + 3.95, -1.86, 4.32, -2.01, -1.23, -1.79, 2.76, -2.13, -0.13, -5.25, 3.84, + -2.24, 1.59, -4.85, 2.96, -2.41, 0.01, -0.43, 0.13, -3.92, 2.91, -1.75, + -0.53, -1.69, 1.69, -1.09, 0.15, -2.11, 2.17, -1.53, 1.22, -2.1, -0.86, + -2.56, 2.28, -3.02, 3.33, -1.12, 3.86, -2.18, -1.19, -3.03, 0.79, -0.83, + 0.97, -3.19, 1.45, -1.34, 1.28, -2.52, 4.22, -4.53, 3.22, -1.97, 1.75, + -2.36, 3.19, -0.83, 1.53, -1.59, 1.86, -2.17, 2.3, -1.63, 2.71, -2.03, + 3.75, -2.57, -0.6, -1.47, 1.33, -1.95, 0.7, -1.65, 1.27, -1.42, 1.09, -3.0, + 3.87, -2.51, 3.06, -2.6, 0.74, -1.08, -0.03, -2.44, 1.31, -2.65, 2.99, + -1.84, 1.65, -4.76, 3.75, -2.07, 3.98, -2.4, 2.67, -2.21, 1.49, -1.21, + 1.22, -5.29, 2.38, -2.85, 2.28, -5.6, 3.78, -2.7, 0.8, -1.81, 3.5, -3.75, + 4.17, -1.29, 2.99, -5.92, 3.43, -1.83, 1.23, -1.24, -1.04, -2.56, 2.37, + -3.26, 0.39, -4.63, 2.51, -4.52, 3.04, -1.7, 0.36, -1.41, 0.04, -2.1, 1.0, + -1.87, 3.78, -4.32, 3.59, -2.24, 1.38, -1.99, -0.22, -1.87, 1.95, -0.84, + 2.17, -5.38, 3.56, -1.27, 2.9, -1.79, 3.31, -5.47, 3.85, -1.44, 3.69, + -2.02, 0.37, -1.29, 0.33, -2.34, 2.56, -1.74, -1.27, -1.97, 1.22, -2.51, + -0.16, -1.64, -0.96, -2.99, 1.4, -1.53, 3.31, -2.24, 0.45, -2.46, 1.71, + -2.88, 1.56, -1.63, 1.46, -1.41, 0.68, -1.96, 2.76, -1.61, + 2.11]).reshape((200, 2)) + + +# Global data +X = np.array([[3.0, 3], [4, 3], [4, 2], + [9, 2], [5, 1], [6, 2], [9, 4], + [5, 2], [5, 4], [7, 4], [6, 5]]) + +CODET1 = np.array([[3.0000, 3.0000], + [6.2000, 4.0000], + [5.8000, 1.8000]]) + +CODET2 = np.array([[11.0/3, 8.0/3], + [6.7500, 4.2500], + [6.2500, 1.7500]]) + +LABEL1 = np.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1]) + + +class TestWhiten: + + def test_whiten(self, xp): + desired = xp.asarray([[5.08738849, 2.97091878], + [3.19909255, 0.69660580], + [4.51041982, 0.02640918], + [4.38567074, 0.95120889], + [2.32191480, 1.63195503]]) + + obs = xp.asarray([[0.98744510, 0.82766775], + [0.62093317, 0.19406729], + [0.87545741, 0.00735733], + [0.85124403, 0.26499712], + [0.45067590, 0.45464607]]) + xp_assert_close(whiten(obs), desired, rtol=1e-5) + + @pytest.fixture + def whiten_lock(self): + return Lock() + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_whiten_zero_std(self, xp, whiten_lock): + desired = xp.asarray([[0., 1.0, 2.86666544], + [0., 1.0, 1.32460034], + [0., 1.0, 3.74382172]]) + + obs = xp.asarray([[0., 1., 0.74109533], + [0., 1., 0.34243798], + [0., 1., 0.96785929]]) + + with whiten_lock: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + + xp_assert_close(whiten(obs), desired, rtol=1e-5) + + assert_equal(len(w), 1) + assert_(issubclass(w[-1].category, RuntimeWarning)) + + def test_whiten_not_finite(self, xp): + for bad_value in xp.nan, xp.inf, -xp.inf: + obs = xp.asarray([[0.98744510, bad_value], + [0.62093317, 0.19406729], + [0.87545741, 0.00735733], + [0.85124403, 0.26499712], + [0.45067590, 0.45464607]]) + assert_raises(ValueError, whiten, obs) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_whiten_not_finite_matrix(self, xp): + for bad_value in np.nan, np.inf, -np.inf: + obs = matrix([[0.98744510, bad_value], + [0.62093317, 0.19406729], + [0.87545741, 0.00735733], + [0.85124403, 0.26499712], + [0.45067590, 0.45464607]]) + assert_raises(ValueError, whiten, obs) + + +class TestVq: + + @skip_xp_backends(cpu_only=True) + def test_py_vq(self, xp): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + # label1.dtype varies between int32 and int64 over platforms + label1 = py_vq(xp.asarray(X), xp.asarray(initc))[0] + xp_assert_equal(label1, xp.asarray(LABEL1, dtype=xp.int64), + check_dtype=False) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_py_vq_matrix(self, xp): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + # label1.dtype varies between int32 and int64 over platforms + label1 = py_vq(matrix(X), matrix(initc))[0] + assert_array_equal(label1, LABEL1) + + @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend') + def test_vq(self, xp): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + label1, _ = _vq.vq(xp.asarray(X), xp.asarray(initc)) + assert_array_equal(label1, LABEL1) + _, _ = vq(xp.asarray(X), xp.asarray(initc)) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_vq_matrix(self, xp): + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + label1, _ = _vq.vq(matrix(X), matrix(initc)) + assert_array_equal(label1, LABEL1) + _, _ = vq(matrix(X), matrix(initc)) + + @skip_xp_backends(cpu_only=True) + def test_vq_1d(self, xp): + # Test special rank 1 vq algo, python implementation. + data = X[:, 0] + initc = data[:3] + a, b = _vq.vq(data, initc) + data = xp.asarray(data) + initc = xp.asarray(initc) + ta, tb = py_vq(data[:, np.newaxis], initc[:, np.newaxis]) + # ta.dtype varies between int32 and int64 over platforms + xp_assert_equal(ta, xp.asarray(a, dtype=xp.int64), check_dtype=False) + xp_assert_equal(tb, xp.asarray(b)) + + @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend') + def test__vq_sametype(self, xp): + a = xp.asarray([1.0, 2.0], dtype=xp.float64) + b = a.astype(xp.float32) + assert_raises(TypeError, _vq.vq, a, b) + + @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend') + def test__vq_invalid_type(self, xp): + a = xp.asarray([1, 2], dtype=int) + assert_raises(TypeError, _vq.vq, a, a) + + @skip_xp_backends(cpu_only=True) + def test_vq_large_nfeat(self, xp): + X = np.random.rand(20, 20) + code_book = np.random.rand(3, 20) + + codes0, dis0 = _vq.vq(X, code_book) + codes1, dis1 = py_vq( + xp.asarray(X), xp.asarray(code_book) + ) + xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5) + # codes1.dtype varies between int32 and int64 over platforms + xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False) + + X = X.astype(np.float32) + code_book = code_book.astype(np.float32) + + codes0, dis0 = _vq.vq(X, code_book) + codes1, dis1 = py_vq( + xp.asarray(X), xp.asarray(code_book) + ) + xp_assert_close(dis1, xp.asarray(dis0, dtype=xp.float64), rtol=1e-5) + # codes1.dtype varies between int32 and int64 over platforms + xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False) + + @skip_xp_backends(cpu_only=True) + def test_vq_large_features(self, xp): + X = np.random.rand(10, 5) * 1000000 + code_book = np.random.rand(2, 5) * 1000000 + + codes0, dis0 = _vq.vq(X, code_book) + codes1, dis1 = py_vq( + xp.asarray(X), xp.asarray(code_book) + ) + xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5) + # codes1.dtype varies between int32 and int64 over platforms + xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False) + + +# Whole class skipped on GPU for now; +# once pdist/cdist are hooked up for CuPy, more tests will work +@skip_xp_backends(cpu_only=True) +class TestKMean: + + def test_large_features(self, xp): + # Generate a data set with large values, and run kmeans on it to + # (regression for 1077). + d = 300 + n = 100 + + m1 = np.random.randn(d) + m2 = np.random.randn(d) + x = 10000 * np.random.randn(n, d) - 20000 * m1 + y = 10000 * np.random.randn(n, d) + 20000 * m2 + + data = np.empty((x.shape[0] + y.shape[0], d), np.float64) + data[:x.shape[0]] = x + data[x.shape[0]:] = y + + # use `seed` to ensure backwards compatibility after SPEC7 + kmeans(xp.asarray(data), 2, seed=1) + + def test_kmeans_simple(self, xp): + rng = np.random.default_rng(54321) + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + code1 = kmeans(xp.asarray(X), xp.asarray(initc), iter=1, rng=rng)[0] + xp_assert_close(code1, xp.asarray(CODET2)) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_kmeans_simple_matrix(self, xp): + rng = np.random.default_rng(54321) + initc = np.concatenate([[X[0]], [X[1]], [X[2]]]) + code1 = kmeans(matrix(X), matrix(initc), iter=1, rng=rng)[0] + xp_assert_close(code1, CODET2) + + def test_kmeans_lost_cluster(self, xp): + # This will cause kmeans to have a cluster with no points. + data = xp.asarray(TESTDATA_2D) + initk = xp.asarray([[-1.8127404, -0.67128041], + [2.04621601, 0.07401111], + [-2.31149087, -0.05160469]]) + + kmeans(data, initk) + with suppress_warnings() as sup: + sup.filter(UserWarning, + "One of the clusters is empty. Re-run kmeans with a " + "different initialization") + kmeans2(data, initk, missing='warn') + + assert_raises(ClusterError, kmeans2, data, initk, missing='raise') + + def test_kmeans2_simple(self, xp): + rng = np.random.default_rng(12345678) + initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]])) + arrays = [xp.asarray] if SCIPY_ARRAY_API else [np.asarray, matrix] + for tp in arrays: + code1 = kmeans2(tp(X), tp(initc), iter=1, rng=rng)[0] + code2 = kmeans2(tp(X), tp(initc), iter=2, rng=rng)[0] + + xp_assert_close(code1, xp.asarray(CODET1)) + xp_assert_close(code2, xp.asarray(CODET2)) + + @pytest.mark.skipif(SCIPY_ARRAY_API, + reason='`np.matrix` unsupported in array API mode') + def test_kmeans2_simple_matrix(self, xp): + rng = np.random.default_rng(12345678) + initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]])) + code1 = kmeans2(matrix(X), matrix(initc), iter=1, rng=rng)[0] + code2 = kmeans2(matrix(X), matrix(initc), iter=2, rng=rng)[0] + + xp_assert_close(code1, CODET1) + xp_assert_close(code2, CODET2) + + def test_kmeans2_rank1(self, xp): + data = xp.asarray(TESTDATA_2D) + data1 = data[:, 0] + + initc = data1[:3] + code = xp_copy(initc, xp=xp) + + # use `seed` to ensure backwards compatibility after SPEC7 + kmeans2(data1, code, iter=1, seed=1)[0] + kmeans2(data1, code, iter=2)[0] + + def test_kmeans2_rank1_2(self, xp): + data = xp.asarray(TESTDATA_2D) + data1 = data[:, 0] + kmeans2(data1, 2, iter=1) + + def test_kmeans2_high_dim(self, xp): + # test kmeans2 when the number of dimensions exceeds the number + # of input points + data = xp.asarray(TESTDATA_2D) + data = xp.reshape(data, (20, 20))[:10, :] + kmeans2(data, 2) + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_kmeans2_init(self, xp): + rng = np.random.default_rng(12345678) + data = xp.asarray(TESTDATA_2D) + k = 3 + + kmeans2(data, k, minit='points', rng=rng) + kmeans2(data[:, 1], k, minit='points', rng=rng) # special case (1-D) + + kmeans2(data, k, minit='++', rng=rng) + kmeans2(data[:, 1], k, minit='++', rng=rng) # special case (1-D) + + # minit='random' can give warnings, filter those + with suppress_warnings() as sup: + sup.filter(message="One of the clusters is empty. Re-run.") + kmeans2(data, k, minit='random', rng=rng) + kmeans2(data[:, 1], k, minit='random', rng=rng) # special case (1-D) + + @pytest.fixture + def krand_lock(self): + return Lock() + + @pytest.mark.skipif(sys.platform == 'win32', + reason='Fails with MemoryError in Wine.') + def test_krandinit(self, xp, krand_lock): + data = xp.asarray(TESTDATA_2D) + datas = [xp.reshape(data, (200, 2)), + xp.reshape(data, (20, 20))[:10, :]] + k = int(1e6) + xp_test = array_namespace(data) + with krand_lock: + for data in datas: + rng = np.random.default_rng(1234) + init = _krandinit(data, k, rng, xp_test) + orig_cov = xpx.cov(data.T, xp=xp_test) + init_cov = xpx.cov(init.T, xp=xp_test) + xp_assert_close(orig_cov, init_cov, atol=1.1e-2) + + def test_kmeans2_empty(self, xp): + # Regression test for gh-1032. + assert_raises(ValueError, kmeans2, xp.asarray([]), 2) + + def test_kmeans_0k(self, xp): + # Regression test for gh-1073: fail when k arg is 0. + assert_raises(ValueError, kmeans, xp.asarray(X), 0) + assert_raises(ValueError, kmeans2, xp.asarray(X), 0) + assert_raises(ValueError, kmeans2, xp.asarray(X), xp.asarray([])) + + def test_kmeans_large_thres(self, xp): + # Regression test for gh-1774 + x = xp.asarray([1, 2, 3, 4, 10], dtype=xp.float64) + res = kmeans(x, 1, thresh=1e16) + xp_assert_close(res[0], xp.asarray([4.], dtype=xp.float64)) + xp_assert_close(res[1], xp.asarray(2.3999999999999999, dtype=xp.float64)[()]) + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_kmeans2_kpp_low_dim(self, xp): + # Regression test for gh-11462 + rng = np.random.default_rng(2358792345678234568) + prev_res = xp.asarray([[-1.95266667, 0.898], + [-3.153375, 3.3945]], dtype=xp.float64) + res, _ = kmeans2(xp.asarray(TESTDATA_2D), 2, minit='++', rng=rng) + xp_assert_close(res, prev_res) + + @pytest.mark.thread_unsafe + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_kmeans2_kpp_high_dim(self, xp): + # Regression test for gh-11462 + rng = np.random.default_rng(23587923456834568) + n_dim = 100 + size = 10 + centers = np.vstack([5 * np.ones(n_dim), + -5 * np.ones(n_dim)]) + + data = np.vstack([ + rng.multivariate_normal(centers[0], np.eye(n_dim), size=size), + rng.multivariate_normal(centers[1], np.eye(n_dim), size=size) + ]) + + data = xp.asarray(data) + res, _ = kmeans2(data, 2, minit='++', rng=rng) + xp_assert_equal(xp.sign(res), xp.sign(xp.asarray(centers))) + + def test_kmeans_diff_convergence(self, xp): + # Regression test for gh-8727 + obs = xp.asarray([-3, -1, 0, 1, 1, 8], dtype=xp.float64) + res = kmeans(obs, xp.asarray([-3., 0.99])) + xp_assert_close(res[0], xp.asarray([-0.4, 8.], dtype=xp.float64)) + xp_assert_close(res[1], xp.asarray(1.0666666666666667, dtype=xp.float64)[()]) + + @skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment') + def test_kmeans_and_kmeans2_random_seed(self, xp): + + seed_list = [ + 1234, np.random.RandomState(1234), np.random.default_rng(1234) + ] + + for seed in seed_list: + seed1 = deepcopy(seed) + seed2 = deepcopy(seed) + data = xp.asarray(TESTDATA_2D) + # test for kmeans + res1, _ = kmeans(data, 2, seed=seed1) + res2, _ = kmeans(data, 2, seed=seed2) + xp_assert_close(res1, res2) # should be same results + # test for kmeans2 + for minit in ["random", "points", "++"]: + res1, _ = kmeans2(data, 2, minit=minit, seed=seed1) + res2, _ = kmeans2(data, 2, minit=minit, seed=seed2) + xp_assert_close(res1, res2) # should be same results diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/vq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/vq.py new file mode 100644 index 0000000000000000000000000000000000000000..a791e2956070d0785556dd9c4f877004ae50cd9f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/cluster/vq.py @@ -0,0 +1,828 @@ +""" +K-means clustering and vector quantization (:mod:`scipy.cluster.vq`) +==================================================================== + +Provides routines for k-means clustering, generating code books +from k-means models and quantizing vectors by comparing them with +centroids in a code book. + +.. autosummary:: + :toctree: generated/ + + whiten -- Normalize a group of observations so each feature has unit variance + vq -- Calculate code book membership of a set of observation vectors + kmeans -- Perform k-means on a set of observation vectors forming k clusters + kmeans2 -- A different implementation of k-means with more methods + -- for initializing centroids + +Background information +---------------------- +The k-means algorithm takes as input the number of clusters to +generate, k, and a set of observation vectors to cluster. It +returns a set of centroids, one for each of the k clusters. An +observation vector is classified with the cluster number or +centroid index of the centroid closest to it. + +A vector v belongs to cluster i if it is closer to centroid i than +any other centroid. If v belongs to i, we say centroid i is the +dominating centroid of v. The k-means algorithm tries to +minimize distortion, which is defined as the sum of the squared distances +between each observation vector and its dominating centroid. +The minimization is achieved by iteratively reclassifying +the observations into clusters and recalculating the centroids until +a configuration is reached in which the centroids are stable. One can +also define a maximum number of iterations. + +Since vector quantization is a natural application for k-means, +information theory terminology is often used. The centroid index +or cluster index is also referred to as a "code" and the table +mapping codes to centroids and, vice versa, is often referred to as a +"code book". The result of k-means, a set of centroids, can be +used to quantize vectors. Quantization aims to find an encoding of +vectors that reduces the expected distortion. + +All routines expect obs to be an M by N array, where the rows are +the observation vectors. The codebook is a k by N array, where the +ith row is the centroid of code word i. The observation vectors +and centroids have the same feature dimension. + +As an example, suppose we wish to compress a 24-bit color image +(each pixel is represented by one byte for red, one for blue, and +one for green) before sending it over the web. By using a smaller +8-bit encoding, we can reduce the amount of data by two +thirds. Ideally, the colors for each of the 256 possible 8-bit +encoding values should be chosen to minimize distortion of the +color. Running k-means with k=256 generates a code book of 256 +codes, which fills up all possible 8-bit sequences. Instead of +sending a 3-byte value for each pixel, the 8-bit centroid index +(or code word) of the dominating centroid is transmitted. The code +book is also sent over the wire so each 8-bit code can be +translated back to a 24-bit pixel value representation. If the +image of interest was of an ocean, we would expect many 24-bit +blues to be represented by 8-bit codes. If it was an image of a +human face, more flesh-tone colors would be represented in the +code book. + +""" +import warnings +import numpy as np +from collections import deque +from scipy._lib._array_api import ( + _asarray, array_namespace, xp_size, xp_copy +) +from scipy._lib._util import (check_random_state, rng_integers, + _transition_to_rng) +from scipy._lib import array_api_extra as xpx +from scipy.spatial.distance import cdist + +from . import _vq + +__docformat__ = 'restructuredtext' + +__all__ = ['whiten', 'vq', 'kmeans', 'kmeans2'] + + +class ClusterError(Exception): + pass + + +def whiten(obs, check_finite=True): + """ + Normalize a group of observations on a per feature basis. + + Before running k-means, it is beneficial to rescale each feature + dimension of the observation set by its standard deviation (i.e. "whiten" + it - as in "white noise" where each frequency has equal power). + Each feature is divided by its standard deviation across all observations + to give it unit variance. + + Parameters + ---------- + obs : ndarray + Each row of the array is an observation. The + columns are the features seen during each observation. + + >>> # f0 f1 f2 + >>> obs = [[ 1., 1., 1.], #o0 + ... [ 2., 2., 2.], #o1 + ... [ 3., 3., 3.], #o2 + ... [ 4., 4., 4.]] #o3 + + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default: True + + Returns + ------- + result : ndarray + Contains the values in `obs` scaled by the standard deviation + of each column. + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster.vq import whiten + >>> features = np.array([[1.9, 2.3, 1.7], + ... [1.5, 2.5, 2.2], + ... [0.8, 0.6, 1.7,]]) + >>> whiten(features) + array([[ 4.17944278, 2.69811351, 7.21248917], + [ 3.29956009, 2.93273208, 9.33380951], + [ 1.75976538, 0.7038557 , 7.21248917]]) + + """ + xp = array_namespace(obs) + obs = _asarray(obs, check_finite=check_finite, xp=xp) + std_dev = xp.std(obs, axis=0) + zero_std_mask = std_dev == 0 + if xp.any(zero_std_mask): + std_dev[zero_std_mask] = 1.0 + warnings.warn("Some columns have standard deviation zero. " + "The values of these columns will not change.", + RuntimeWarning, stacklevel=2) + return obs / std_dev + + +def vq(obs, code_book, check_finite=True): + """ + Assign codes from a code book to observations. + + Assigns a code from a code book to each observation. Each + observation vector in the 'M' by 'N' `obs` array is compared with the + centroids in the code book and assigned the code of the closest + centroid. + + The features in `obs` should have unit variance, which can be + achieved by passing them through the whiten function. The code + book can be created with the k-means algorithm or a different + encoding algorithm. + + Parameters + ---------- + obs : ndarray + Each row of the 'M' x 'N' array is an observation. The columns are + the "features" seen during each observation. The features must be + whitened first using the whiten function or something equivalent. + code_book : ndarray + The code book is usually generated using the k-means algorithm. + Each row of the array holds a different code, and the columns are + the features of the code. + + >>> # f0 f1 f2 f3 + >>> code_book = [ + ... [ 1., 2., 3., 4.], #c0 + ... [ 1., 2., 3., 4.], #c1 + ... [ 1., 2., 3., 4.]] #c2 + + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default: True + + Returns + ------- + code : ndarray + A length M array holding the code book index for each observation. + dist : ndarray + The distortion (distance) between the observation and its nearest + code. + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster.vq import vq + >>> code_book = np.array([[1., 1., 1.], + ... [2., 2., 2.]]) + >>> features = np.array([[1.9, 2.3, 1.7], + ... [1.5, 2.5, 2.2], + ... [0.8, 0.6, 1.7]]) + >>> vq(features, code_book) + (array([1, 1, 0], dtype=int32), array([0.43588989, 0.73484692, 0.83066239])) + + """ + xp = array_namespace(obs, code_book) + obs = _asarray(obs, xp=xp, check_finite=check_finite) + code_book = _asarray(code_book, xp=xp, check_finite=check_finite) + ct = xp.result_type(obs, code_book) + + c_obs = xp.astype(obs, ct, copy=False) + c_code_book = xp.astype(code_book, ct, copy=False) + + if xp.isdtype(ct, kind='real floating'): + c_obs = np.asarray(c_obs) + c_code_book = np.asarray(c_code_book) + result = _vq.vq(c_obs, c_code_book) + return xp.asarray(result[0]), xp.asarray(result[1]) + return py_vq(obs, code_book, check_finite=False) + + +def py_vq(obs, code_book, check_finite=True): + """ Python version of vq algorithm. + + The algorithm computes the Euclidean distance between each + observation and every frame in the code_book. + + Parameters + ---------- + obs : ndarray + Expects a rank 2 array. Each row is one observation. + code_book : ndarray + Code book to use. Same format than obs. Should have same number of + features (e.g., columns) than obs. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default: True + + Returns + ------- + code : ndarray + code[i] gives the label of the ith obversation; its code is + code_book[code[i]]. + mind_dist : ndarray + min_dist[i] gives the distance between the ith observation and its + corresponding code. + + Notes + ----- + This function is slower than the C version but works for + all input types. If the inputs have the wrong types for the + C versions of the function, this one is called as a last resort. + + It is about 20 times slower than the C version. + + """ + xp = array_namespace(obs, code_book) + obs = _asarray(obs, xp=xp, check_finite=check_finite) + code_book = _asarray(code_book, xp=xp, check_finite=check_finite) + + if obs.ndim != code_book.ndim: + raise ValueError("Observation and code_book should have the same rank") + + if obs.ndim == 1: + obs = obs[:, xp.newaxis] + code_book = code_book[:, xp.newaxis] + + # Once `cdist` has array API support, this `xp.asarray` call can be removed + dist = xp.asarray(cdist(obs, code_book)) + code = xp.argmin(dist, axis=1) + min_dist = xp.min(dist, axis=1) + return code, min_dist + + +def _kmeans(obs, guess, thresh=1e-5, xp=None): + """ "raw" version of k-means. + + Returns + ------- + code_book + The lowest distortion codebook found. + avg_dist + The average distance a observation is from a code in the book. + Lower means the code_book matches the data better. + + See Also + -------- + kmeans : wrapper around k-means + + Examples + -------- + Note: not whitened in this example. + + >>> import numpy as np + >>> from scipy.cluster.vq import _kmeans + >>> features = np.array([[ 1.9,2.3], + ... [ 1.5,2.5], + ... [ 0.8,0.6], + ... [ 0.4,1.8], + ... [ 1.0,1.0]]) + >>> book = np.array((features[0],features[2])) + >>> _kmeans(features,book) + (array([[ 1.7 , 2.4 ], + [ 0.73333333, 1.13333333]]), 0.40563916697728591) + + """ + xp = np if xp is None else xp + code_book = guess + diff = xp.inf + prev_avg_dists = deque([diff], maxlen=2) + while diff > thresh: + # compute membership and distances between obs and code_book + obs_code, distort = vq(obs, code_book, check_finite=False) + prev_avg_dists.append(xp.mean(distort, axis=-1)) + # recalc code_book as centroids of associated obs + obs = np.asarray(obs) + obs_code = np.asarray(obs_code) + code_book, has_members = _vq.update_cluster_means(obs, obs_code, + code_book.shape[0]) + obs = xp.asarray(obs) + obs_code = xp.asarray(obs_code) + code_book = xp.asarray(code_book) + has_members = xp.asarray(has_members) + code_book = code_book[has_members] + diff = xp.abs(prev_avg_dists[0] - prev_avg_dists[1]) + + return code_book, prev_avg_dists[1] + + +@_transition_to_rng("seed") +def kmeans(obs, k_or_guess, iter=20, thresh=1e-5, check_finite=True, + *, rng=None): + """ + Performs k-means on a set of observation vectors forming k clusters. + + The k-means algorithm adjusts the classification of the observations + into clusters and updates the cluster centroids until the position of + the centroids is stable over successive iterations. In this + implementation of the algorithm, the stability of the centroids is + determined by comparing the absolute value of the change in the average + Euclidean distance between the observations and their corresponding + centroids against a threshold. This yields + a code book mapping centroids to codes and vice versa. + + Parameters + ---------- + obs : ndarray + Each row of the M by N array is an observation vector. The + columns are the features seen during each observation. + The features must be whitened first with the `whiten` function. + + k_or_guess : int or ndarray + The number of centroids to generate. A code is assigned to + each centroid, which is also the row index of the centroid + in the code_book matrix generated. + + The initial k centroids are chosen by randomly selecting + observations from the observation matrix. Alternatively, + passing a k by N array specifies the initial k centroids. + + iter : int, optional + The number of times to run k-means, returning the codebook + with the lowest distortion. This argument is ignored if + initial centroids are specified with an array for the + ``k_or_guess`` parameter. This parameter does not represent the + number of iterations of the k-means algorithm. + + thresh : float, optional + Terminates the k-means algorithm if the change in + distortion since the last k-means iteration is less than + or equal to threshold. + + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default: True + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + codebook : ndarray + A k by N array of k centroids. The ith centroid + codebook[i] is represented with the code i. The centroids + and codes generated represent the lowest distortion seen, + not necessarily the globally minimal distortion. + Note that the number of centroids is not necessarily the same as the + ``k_or_guess`` parameter, because centroids assigned to no observations + are removed during iterations. + + distortion : float + The mean (non-squared) Euclidean distance between the observations + passed and the centroids generated. Note the difference to the standard + definition of distortion in the context of the k-means algorithm, which + is the sum of the squared distances. + + See Also + -------- + kmeans2 : a different implementation of k-means clustering + with more methods for generating initial centroids but without + using a distortion change threshold as a stopping criterion. + + whiten : must be called prior to passing an observation matrix + to kmeans. + + Notes + ----- + For more functionalities or optimal performance, you can use + `sklearn.cluster.KMeans `_. + `This `_ + is a benchmark result of several implementations. + + Examples + -------- + >>> import numpy as np + >>> from scipy.cluster.vq import vq, kmeans, whiten + >>> import matplotlib.pyplot as plt + >>> features = np.array([[ 1.9,2.3], + ... [ 1.5,2.5], + ... [ 0.8,0.6], + ... [ 0.4,1.8], + ... [ 0.1,0.1], + ... [ 0.2,1.8], + ... [ 2.0,0.5], + ... [ 0.3,1.5], + ... [ 1.0,1.0]]) + >>> whitened = whiten(features) + >>> book = np.array((whitened[0],whitened[2])) + >>> kmeans(whitened,book) + (array([[ 2.3110306 , 2.86287398], # random + [ 0.93218041, 1.24398691]]), 0.85684700941625547) + + >>> codes = 3 + >>> kmeans(whitened,codes) + (array([[ 2.3110306 , 2.86287398], # random + [ 1.32544402, 0.65607529], + [ 0.40782893, 2.02786907]]), 0.5196582527686241) + + >>> # Create 50 datapoints in two clusters a and b + >>> pts = 50 + >>> rng = np.random.default_rng() + >>> a = rng.multivariate_normal([0, 0], [[4, 1], [1, 4]], size=pts) + >>> b = rng.multivariate_normal([30, 10], + ... [[10, 2], [2, 1]], + ... size=pts) + >>> features = np.concatenate((a, b)) + >>> # Whiten data + >>> whitened = whiten(features) + >>> # Find 2 clusters in the data + >>> codebook, distortion = kmeans(whitened, 2) + >>> # Plot whitened data and cluster centers in red + >>> plt.scatter(whitened[:, 0], whitened[:, 1]) + >>> plt.scatter(codebook[:, 0], codebook[:, 1], c='r') + >>> plt.show() + + """ + if isinstance(k_or_guess, int): + xp = array_namespace(obs) + else: + xp = array_namespace(obs, k_or_guess) + obs = _asarray(obs, xp=xp, check_finite=check_finite) + guess = _asarray(k_or_guess, xp=xp, check_finite=check_finite) + if iter < 1: + raise ValueError(f"iter must be at least 1, got {iter}") + + # Determine whether a count (scalar) or an initial guess (array) was passed. + if xp_size(guess) != 1: + if xp_size(guess) < 1: + raise ValueError(f"Asked for 0 clusters. Initial book was {guess}") + return _kmeans(obs, guess, thresh=thresh, xp=xp) + + # k_or_guess is a scalar, now verify that it's an integer + k = int(guess) + if k != guess: + raise ValueError("If k_or_guess is a scalar, it must be an integer.") + if k < 1: + raise ValueError("Asked for %d clusters." % k) + + rng = check_random_state(rng) + + # initialize best distance value to a large value + best_dist = xp.inf + for i in range(iter): + # the initial code book is randomly selected from observations + guess = _kpoints(obs, k, rng, xp) + book, dist = _kmeans(obs, guess, thresh=thresh, xp=xp) + if dist < best_dist: + best_book = book + best_dist = dist + return best_book, best_dist + + +def _kpoints(data, k, rng, xp): + """Pick k points at random in data (one row = one observation). + + Parameters + ---------- + data : ndarray + Expect a rank 1 or 2 array. Rank 1 are assumed to describe one + dimensional data, rank 2 multidimensional data, in which case one + row is one observation. + k : int + Number of samples to generate. + rng : `numpy.random.Generator` or `numpy.random.RandomState` + Random number generator. + + Returns + ------- + x : ndarray + A 'k' by 'N' containing the initial centroids + + """ + idx = rng.choice(data.shape[0], size=int(k), replace=False) + # convert to array with default integer dtype (avoids numpy#25607) + idx = xp.asarray(idx, dtype=xp.asarray([1]).dtype) + return xp.take(data, idx, axis=0) + + +def _krandinit(data, k, rng, xp): + """Returns k samples of a random variable whose parameters depend on data. + + More precisely, it returns k observations sampled from a Gaussian random + variable whose mean and covariances are the ones estimated from the data. + + Parameters + ---------- + data : ndarray + Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D + data, rank 2 multidimensional data, in which case one + row is one observation. + k : int + Number of samples to generate. + rng : `numpy.random.Generator` or `numpy.random.RandomState` + Random number generator. + + Returns + ------- + x : ndarray + A 'k' by 'N' containing the initial centroids + + """ + mu = xp.mean(data, axis=0) + k = np.asarray(k) + + if data.ndim == 1: + _cov = xpx.cov(data, xp=xp) + x = rng.standard_normal(size=k) + x = xp.asarray(x) + x *= xp.sqrt(_cov) + elif data.shape[1] > data.shape[0]: + # initialize when the covariance matrix is rank deficient + _, s, vh = xp.linalg.svd(data - mu, full_matrices=False) + x = rng.standard_normal(size=(k, xp_size(s))) + x = xp.asarray(x) + sVh = s[:, None] * vh / xp.sqrt(data.shape[0] - xp.asarray(1.)) + x = x @ sVh + else: + _cov = xpx.atleast_nd(xpx.cov(data.T, xp=xp), ndim=2, xp=xp) + + # k rows, d cols (one row = one obs) + # Generate k sample of a random variable ~ Gaussian(mu, cov) + x = rng.standard_normal(size=(k, xp_size(mu))) + x = xp.asarray(x) + x = x @ xp.linalg.cholesky(_cov).T + + x += mu + return x + + +def _kpp(data, k, rng, xp): + """ Picks k points in the data based on the kmeans++ method. + + Parameters + ---------- + data : ndarray + Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D + data, rank 2 multidimensional data, in which case one + row is one observation. + k : int + Number of samples to generate. + rng : `numpy.random.Generator` or `numpy.random.RandomState` + Random number generator. + + Returns + ------- + init : ndarray + A 'k' by 'N' containing the initial centroids. + + References + ---------- + .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of + careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium + on Discrete Algorithms, 2007. + """ + + ndim = len(data.shape) + if ndim == 1: + data = data[:, None] + + dims = data.shape[1] + + init = xp.empty((int(k), dims)) + + for i in range(k): + if i == 0: + init[i, :] = data[rng_integers(rng, data.shape[0]), :] + + else: + D2 = cdist(init[:i,:], data, metric='sqeuclidean').min(axis=0) + probs = D2/D2.sum() + cumprobs = probs.cumsum() + r = rng.uniform() + cumprobs = np.asarray(cumprobs) + init[i, :] = data[np.searchsorted(cumprobs, r), :] + + if ndim == 1: + init = init[:, 0] + return init + + +_valid_init_meth = {'random': _krandinit, 'points': _kpoints, '++': _kpp} + + +def _missing_warn(): + """Print a warning when called.""" + warnings.warn("One of the clusters is empty. " + "Re-run kmeans with a different initialization.", + stacklevel=3) + + +def _missing_raise(): + """Raise a ClusterError when called.""" + raise ClusterError("One of the clusters is empty. " + "Re-run kmeans with a different initialization.") + + +_valid_miss_meth = {'warn': _missing_warn, 'raise': _missing_raise} + + +@_transition_to_rng("seed") +def kmeans2(data, k, iter=10, thresh=1e-5, minit='random', + missing='warn', check_finite=True, *, rng=None): + """ + Classify a set of observations into k clusters using the k-means algorithm. + + The algorithm attempts to minimize the Euclidean distance between + observations and centroids. Several initialization methods are + included. + + Parameters + ---------- + data : ndarray + A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length + 'M' array of 'M' 1-D observations. + k : int or ndarray + The number of clusters to form as well as the number of + centroids to generate. If `minit` initialization string is + 'matrix', or if a ndarray is given instead, it is + interpreted as initial cluster to use instead. + iter : int, optional + Number of iterations of the k-means algorithm to run. Note + that this differs in meaning from the iters parameter to + the kmeans function. + thresh : float, optional + (not used yet) + minit : str, optional + Method for initialization. Available methods are 'random', + 'points', '++' and 'matrix': + + 'random': generate k centroids from a Gaussian with mean and + variance estimated from the data. + + 'points': choose k observations (rows) at random from data for + the initial centroids. + + '++': choose k observations accordingly to the kmeans++ method + (careful seeding) + + 'matrix': interpret the k parameter as a k by M (or length k + array for 1-D data) array of initial centroids. + missing : str, optional + Method to deal with empty clusters. Available methods are + 'warn' and 'raise': + + 'warn': give a warning and continue. + + 'raise': raise an ClusterError and terminate the algorithm. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default: True + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + centroid : ndarray + A 'k' by 'N' array of centroids found at the last iteration of + k-means. + label : ndarray + label[i] is the code or index of the centroid the + ith observation is closest to. + + See Also + -------- + kmeans + + References + ---------- + .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of + careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium + on Discrete Algorithms, 2007. + + Examples + -------- + >>> from scipy.cluster.vq import kmeans2 + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + Create z, an array with shape (100, 2) containing a mixture of samples + from three multivariate normal distributions. + + >>> rng = np.random.default_rng() + >>> a = rng.multivariate_normal([0, 6], [[2, 1], [1, 1.5]], size=45) + >>> b = rng.multivariate_normal([2, 0], [[1, -1], [-1, 3]], size=30) + >>> c = rng.multivariate_normal([6, 4], [[5, 0], [0, 1.2]], size=25) + >>> z = np.concatenate((a, b, c)) + >>> rng.shuffle(z) + + Compute three clusters. + + >>> centroid, label = kmeans2(z, 3, minit='points') + >>> centroid + array([[ 2.22274463, -0.61666946], # may vary + [ 0.54069047, 5.86541444], + [ 6.73846769, 4.01991898]]) + + How many points are in each cluster? + + >>> counts = np.bincount(label) + >>> counts + array([29, 51, 20]) # may vary + + Plot the clusters. + + >>> w0 = z[label == 0] + >>> w1 = z[label == 1] + >>> w2 = z[label == 2] + >>> plt.plot(w0[:, 0], w0[:, 1], 'o', alpha=0.5, label='cluster 0') + >>> plt.plot(w1[:, 0], w1[:, 1], 'd', alpha=0.5, label='cluster 1') + >>> plt.plot(w2[:, 0], w2[:, 1], 's', alpha=0.5, label='cluster 2') + >>> plt.plot(centroid[:, 0], centroid[:, 1], 'k*', label='centroids') + >>> plt.axis('equal') + >>> plt.legend(shadow=True) + >>> plt.show() + + """ + if int(iter) < 1: + raise ValueError(f"Invalid iter ({iter}), must be a positive integer.") + try: + miss_meth = _valid_miss_meth[missing] + except KeyError as e: + raise ValueError(f"Unknown missing method {missing!r}") from e + + if isinstance(k, int): + xp = array_namespace(data) + else: + xp = array_namespace(data, k) + data = _asarray(data, xp=xp, check_finite=check_finite) + code_book = xp_copy(k, xp=xp) + if data.ndim == 1: + d = 1 + elif data.ndim == 2: + d = data.shape[1] + else: + raise ValueError("Input of rank > 2 is not supported.") + + if xp_size(data) < 1 or xp_size(code_book) < 1: + raise ValueError("Empty input is not supported.") + + # If k is not a single value, it should be compatible with data's shape + if minit == 'matrix' or xp_size(code_book) > 1: + if data.ndim != code_book.ndim: + raise ValueError("k array doesn't match data rank") + nc = code_book.shape[0] + if data.ndim > 1 and code_book.shape[1] != d: + raise ValueError("k array doesn't match data dimension") + else: + nc = int(code_book) + + if nc < 1: + raise ValueError("Cannot ask kmeans2 for %d clusters" + " (k was %s)" % (nc, code_book)) + elif nc != code_book: + warnings.warn("k was not an integer, was converted.", stacklevel=2) + + try: + init_meth = _valid_init_meth[minit] + except KeyError as e: + raise ValueError(f"Unknown init method {minit!r}") from e + else: + rng = check_random_state(rng) + code_book = init_meth(data, code_book, rng, xp) + + data = np.asarray(data) + code_book = np.asarray(code_book) + for i in range(iter): + # Compute the nearest neighbor for each obs using the current code book + label = vq(data, code_book, check_finite=check_finite)[0] + # Update the code book by computing centroids + new_code_book, has_members = _vq.update_cluster_means(data, label, nc) + if not has_members.all(): + miss_meth() + # Set the empty clusters to their previous positions + new_code_book[~has_members] = code_book[~has_members] + code_book = new_code_book + + return xp.asarray(code_book), xp.asarray(label) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c545a00b9fd63427088ac873fa3fa65678b77f71 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py @@ -0,0 +1,114 @@ +""" +============================================== +Discrete Fourier transforms (:mod:`scipy.fft`) +============================================== + +.. currentmodule:: scipy.fft + +Fast Fourier Transforms (FFTs) +============================== + +.. autosummary:: + :toctree: generated/ + + fft - Fast (discrete) Fourier Transform (FFT) + ifft - Inverse FFT + fft2 - 2-D FFT + ifft2 - 2-D inverse FFT + fftn - N-D FFT + ifftn - N-D inverse FFT + rfft - FFT of strictly real-valued sequence + irfft - Inverse of rfft + rfft2 - 2-D FFT of real sequence + irfft2 - Inverse of rfft2 + rfftn - N-D FFT of real sequence + irfftn - Inverse of rfftn + hfft - FFT of a Hermitian sequence (real spectrum) + ihfft - Inverse of hfft + hfft2 - 2-D FFT of a Hermitian sequence + ihfft2 - Inverse of hfft2 + hfftn - N-D FFT of a Hermitian sequence + ihfftn - Inverse of hfftn + +Discrete Sin and Cosine Transforms (DST and DCT) +================================================ + +.. autosummary:: + :toctree: generated/ + + dct - Discrete cosine transform + idct - Inverse discrete cosine transform + dctn - N-D Discrete cosine transform + idctn - N-D Inverse discrete cosine transform + dst - Discrete sine transform + idst - Inverse discrete sine transform + dstn - N-D Discrete sine transform + idstn - N-D Inverse discrete sine transform + +Fast Hankel Transforms +====================== + +.. autosummary:: + :toctree: generated/ + + fht - Fast Hankel transform + ifht - Inverse of fht + +Helper functions +================ + +.. autosummary:: + :toctree: generated/ + + fftshift - Shift the zero-frequency component to the center of the spectrum + ifftshift - The inverse of `fftshift` + fftfreq - Return the Discrete Fourier Transform sample frequencies + rfftfreq - DFT sample frequencies (for usage with rfft, irfft) + fhtoffset - Compute an optimal offset for the Fast Hankel Transform + next_fast_len - Find the optimal length to zero-pad an FFT for speed + prev_fast_len - Find the maximum slice length that results in a fast FFT + set_workers - Context manager to set default number of workers + get_workers - Get the current default number of workers + +Backend control +=============== + +.. autosummary:: + :toctree: generated/ + + set_backend - Context manager to set the backend within a fixed scope + skip_backend - Context manager to skip a backend within a fixed scope + set_global_backend - Sets the global fft backend + register_backend - Register a backend for permanent use + +""" + +from ._basic import ( + fft, ifft, fft2, ifft2, fftn, ifftn, + rfft, irfft, rfft2, irfft2, rfftn, irfftn, + hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn) +from ._realtransforms import dct, idct, dst, idst, dctn, idctn, dstn, idstn +from ._fftlog import fht, ifht, fhtoffset +from ._helper import ( + next_fast_len, prev_fast_len, fftfreq, + rfftfreq, fftshift, ifftshift) +from ._backend import (set_backend, skip_backend, set_global_backend, + register_backend) +from ._pocketfft.helper import set_workers, get_workers + +__all__ = [ + 'fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn', + 'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn', + 'hfft', 'ihfft', 'hfft2', 'ihfft2', 'hfftn', 'ihfftn', + 'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift', + 'next_fast_len', 'prev_fast_len', + 'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn', + 'fht', 'ifht', + 'fhtoffset', + 'set_backend', 'skip_backend', 'set_global_backend', 'register_backend', + 'get_workers', 'set_workers'] + + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fa4b2c0316e352a8c7445eee03905afadbc5dc7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a5f13f020d60ccd8821bd6e1a37c9d079c9faf8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89498cae2bc563a61a0861c9abb896395e6f4d1f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c22460cd8b1a615c09b16a572a5305565238b838 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33fae48564ee03dbe4d51a444191b0f6fa42af29 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d080f2c38e2795658ed6fcd8b2c443cfa7bbac0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..040c85dbb2aa60547828e35e3122f4547c235879 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f19e77ec09b2da9b7d2b1213fd866e2d59dd7ccc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68449ecd4beb1c4409432188a95dfbd9c57a0b37 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e5cfcad5c4cbc43276e151d2da33039368630d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py @@ -0,0 +1,196 @@ +import scipy._lib.uarray as ua +from . import _basic_backend +from . import _realtransforms_backend +from . import _fftlog_backend + + +class _ScipyBackend: + """The default backend for fft calculations + + Notes + ----- + We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray`` + treats the domain as a hierarchy. This means the user can install a single + backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well. + """ + __ua_domain__ = "numpy.scipy.fft" + + @staticmethod + def __ua_function__(method, args, kwargs): + + fn = getattr(_basic_backend, method.__name__, None) + if fn is None: + fn = getattr(_realtransforms_backend, method.__name__, None) + if fn is None: + fn = getattr(_fftlog_backend, method.__name__, None) + if fn is None: + return NotImplemented + return fn(*args, **kwargs) + + +_named_backends = { + 'scipy': _ScipyBackend, +} + + +def _backend_from_arg(backend): + """Maps strings to known backends and validates the backend""" + + if isinstance(backend, str): + try: + backend = _named_backends[backend] + except KeyError as e: + raise ValueError(f'Unknown backend {backend}') from e + + if backend.__ua_domain__ != 'numpy.scipy.fft': + raise ValueError('Backend does not implement "numpy.scipy.fft"') + + return backend + + +def set_global_backend(backend, coerce=False, only=False, try_last=False): + """Sets the global fft backend + + This utility method replaces the default backend for permanent use. It + will be tried in the list of backends automatically, unless the + ``only`` flag is set on a backend. This will be the first tried + backend outside the :obj:`set_backend` context manager. + + Parameters + ---------- + backend : {object, 'scipy'} + The backend to use. + Can either be a ``str`` containing the name of a known backend + {'scipy'} or an object that implements the uarray protocol. + coerce : bool + Whether to coerce input types when trying this backend. + only : bool + If ``True``, no more backends will be tried if this fails. + Implied by ``coerce=True``. + try_last : bool + If ``True``, the global backend is tried after registered backends. + + Raises + ------ + ValueError: If the backend does not implement ``numpy.scipy.fft``. + + Notes + ----- + This will overwrite the previously set global backend, which, by default, is + the SciPy implementation. + + Examples + -------- + We can set the global fft backend: + + >>> from scipy.fft import fft, set_global_backend + >>> set_global_backend("scipy") # Sets global backend (default is "scipy"). + >>> fft([1]) # Calls the global backend + array([1.+0.j]) + """ + backend = _backend_from_arg(backend) + ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last) + + +def register_backend(backend): + """ + Register a backend for permanent use. + + Registered backends have the lowest priority and will be tried after the + global backend. + + Parameters + ---------- + backend : {object, 'scipy'} + The backend to use. + Can either be a ``str`` containing the name of a known backend + {'scipy'} or an object that implements the uarray protocol. + + Raises + ------ + ValueError: If the backend does not implement ``numpy.scipy.fft``. + + Examples + -------- + We can register a new fft backend: + + >>> from scipy.fft import fft, register_backend, set_global_backend + >>> class NoopBackend: # Define an invalid Backend + ... __ua_domain__ = "numpy.scipy.fft" + ... def __ua_function__(self, func, args, kwargs): + ... return NotImplemented + >>> set_global_backend(NoopBackend()) # Set the invalid backend as global + >>> register_backend("scipy") # Register a new backend + # The registered backend is called because + # the global backend returns `NotImplemented` + >>> fft([1]) + array([1.+0.j]) + >>> set_global_backend("scipy") # Restore global backend to default + + """ + backend = _backend_from_arg(backend) + ua.register_backend(backend) + + +def set_backend(backend, coerce=False, only=False): + """Context manager to set the backend within a fixed scope. + + Upon entering the ``with`` statement, the given backend will be added to + the list of available backends with the highest priority. Upon exit, the + backend is reset to the state before entering the scope. + + Parameters + ---------- + backend : {object, 'scipy'} + The backend to use. + Can either be a ``str`` containing the name of a known backend + {'scipy'} or an object that implements the uarray protocol. + coerce : bool, optional + Whether to allow expensive conversions for the ``x`` parameter. e.g., + copying a NumPy array to the GPU for a CuPy backend. Implies ``only``. + only : bool, optional + If only is ``True`` and this backend returns ``NotImplemented``, then a + BackendNotImplemented error will be raised immediately. Ignoring any + lower priority backends. + + Examples + -------- + >>> import scipy.fft as fft + >>> with fft.set_backend('scipy', only=True): + ... fft.fft([1]) # Always calls the scipy implementation + array([1.+0.j]) + """ + backend = _backend_from_arg(backend) + return ua.set_backend(backend, coerce=coerce, only=only) + + +def skip_backend(backend): + """Context manager to skip a backend within a fixed scope. + + Within the context of a ``with`` statement, the given backend will not be + called. This covers backends registered both locally and globally. Upon + exit, the backend will again be considered. + + Parameters + ---------- + backend : {object, 'scipy'} + The backend to skip. + Can either be a ``str`` containing the name of a known backend + {'scipy'} or an object that implements the uarray protocol. + + Examples + -------- + >>> import scipy.fft as fft + >>> fft.fft([1]) # Calls default SciPy backend + array([1.+0.j]) + >>> with fft.skip_backend('scipy'): # We explicitly skip the SciPy backend + ... fft.fft([1]) # leaving no implementation available + Traceback (most recent call last): + ... + BackendNotImplementedError: No selected backends had an implementation ... + """ + backend = _backend_from_arg(backend) + return ua.skip_backend(backend) + + +set_global_backend('scipy', try_last=True) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..a3fc021c9ef9b7c2a40bf7b5138158df8e276ae6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py @@ -0,0 +1,1630 @@ +from scipy._lib.uarray import generate_multimethod, Dispatchable +import numpy as np + + +def _x_replacer(args, kwargs, dispatchables): + """ + uarray argument replacer to replace the transform input array (``x``) + """ + if len(args) > 0: + return (dispatchables[0],) + args[1:], kwargs + kw = kwargs.copy() + kw['x'] = dispatchables[0] + return args, kw + + +def _dispatch(func): + """ + Function annotation that creates a uarray multimethod from the function + """ + return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft") + + +@_dispatch +def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 1-D discrete Fourier Transform. + + This function computes the 1-D *n*-point discrete Fourier + Transform (DFT) with the efficient Fast Fourier Transform (FFT) + algorithm [1]_. + + Parameters + ---------- + x : array_like + Input array, can be complex. + n : int, optional + Length of the transformed axis of the output. + If `n` is smaller than the length of the input, the input is cropped. + If it is larger, the input is padded with zeros. If `n` is not given, + the length of the input along the axis specified by `axis` is used. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode. Default is "backward", meaning no normalization on + the forward transforms and scaling by ``1/n`` on the `ifft`. + "forward" instead applies the ``1/n`` factor on the forward transform. + For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``. + + .. versionadded:: 1.6.0 + ``norm={"forward", "backward"}`` options were added + + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See the notes below for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. See below for more + details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + + Raises + ------ + IndexError + if `axes` is larger than the last axis of `x`. + + See Also + -------- + ifft : The inverse of `fft`. + fft2 : The 2-D FFT. + fftn : The N-D FFT. + rfftn : The N-D FFT of real input. + fftfreq : Frequency bins for given FFT parameters. + next_fast_len : Size to pad input to for most efficient transforms + + Notes + ----- + FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform + (DFT) can be calculated efficiently, by using symmetries in the calculated + terms. The symmetry is highest when `n` is a power of 2, and the transform + is therefore most efficient for these sizes. For poorly factorizable sizes, + `scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than + O(`n` log `n`). Further performance improvements may be seen by zero-padding + the input using `next_fast_len`. + + If ``x`` is a 1d array, then the `fft` is equivalent to :: + + y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n)) + + The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach + the Nyquist frequency and wrap around to the negative-frequency terms. So, + for an 8-point transform, the frequencies of the result are + [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the + zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3], + use `fftshift`. + + Transforms can be done in single, double, or extended precision (long + double) floating point. Half precision inputs will be converted to single + precision and non-floating-point inputs will be converted to double + precision. + + If the data type of ``x`` is real, a "real FFT" algorithm is automatically + used, which roughly halves the computation time. To increase efficiency + a little further, use `rfft`, which does the same calculation, but only + outputs half of the symmetrical spectrum. If the data are both real and + symmetrical, the `dct` can again double the efficiency, by generating + half of the spectrum from half of the signal. + + When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may + be used by the implementation in any way. This may include reusing the + memory for the result, but this is in no way guaranteed. You should not + rely on the contents of ``x`` after the transform as this may change in + future without warning. + + The ``workers`` argument specifies the maximum number of parallel jobs to + split the FFT computation into. This will execute independent 1-D + FFTs within ``x``. So, ``x`` must be at least 2-D and the + non-transformed axes must be large enough to split into chunks. If ``x`` is + too small, fewer jobs may be used than requested. + + References + ---------- + .. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the + machine calculation of complex Fourier series," *Math. Comput.* + 19: 297-301. + .. [2] Bluestein, L., 1970, "A linear filtering approach to the + computation of discrete Fourier transform". *IEEE Transactions on + Audio and Electroacoustics.* 18 (4): 451-455. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8)) + array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j, + 2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j, + -1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j, + 1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j]) + + In this example, real input has an FFT which is Hermitian, i.e., symmetric + in the real part and anti-symmetric in the imaginary part: + + >>> from scipy.fft import fft, fftfreq, fftshift + >>> import matplotlib.pyplot as plt + >>> t = np.arange(256) + >>> sp = fftshift(fft(np.sin(t))) + >>> freq = fftshift(fftfreq(t.shape[-1])) + >>> plt.plot(freq, sp.real, freq, sp.imag) + [, + ] + >>> plt.show() + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 1-D inverse discrete Fourier Transform. + + This function computes the inverse of the 1-D *n*-point + discrete Fourier transform computed by `fft`. In other words, + ``ifft(fft(x)) == x`` to within numerical accuracy. + + The input should be ordered in the same way as is returned by `fft`, + i.e., + + * ``x[0]`` should contain the zero frequency term, + * ``x[1:n//2]`` should contain the positive-frequency terms, + * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in + increasing order starting from the most negative frequency. + + For an even number of input points, ``x[n//2]`` represents the sum of + the values at the positive and negative Nyquist frequencies, as the two + are aliased together. See `fft` for details. + + Parameters + ---------- + x : array_like + Input array, can be complex. + n : int, optional + Length of the transformed axis of the output. + If `n` is smaller than the length of the input, the input is cropped. + If it is larger, the input is padded with zeros. If `n` is not given, + the length of the input along the axis specified by `axis` is used. + See notes about padding issues. + axis : int, optional + Axis over which to compute the inverse DFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + + Raises + ------ + IndexError + If `axes` is larger than the last axis of `x`. + + See Also + -------- + fft : The 1-D (forward) FFT, of which `ifft` is the inverse. + ifft2 : The 2-D inverse FFT. + ifftn : The N-D inverse FFT. + + Notes + ----- + If the input parameter `n` is larger than the size of the input, the input + is padded by appending zeros at the end. Even though this is the common + approach, it might lead to surprising results. If a different padding is + desired, it must be performed before calling `ifft`. + + If ``x`` is a 1-D array, then the `ifft` is equivalent to :: + + y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x) + + As with `fft`, `ifft` has support for all floating point types and is + optimized for real input. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> scipy.fft.ifft([0, 4, 0, 0]) + array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary + + Create and plot a band-limited signal with random phases: + + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> t = np.arange(400) + >>> n = np.zeros((400,), dtype=complex) + >>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,))) + >>> s = scipy.fft.ifft(n) + >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--') + [, ] + >>> plt.legend(('real', 'imaginary')) + + >>> plt.show() + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 1-D discrete Fourier Transform for real input. + + This function computes the 1-D *n*-point discrete Fourier + Transform (DFT) of a real-valued array by means of an efficient algorithm + called the Fast Fourier Transform (FFT). + + Parameters + ---------- + x : array_like + Input array + n : int, optional + Number of points along transformation axis in the input to use. + If `n` is smaller than the length of the input, the input is cropped. + If it is larger, the input is padded with zeros. If `n` is not given, + the length of the input along the axis specified by `axis` is used. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + If `n` is even, the length of the transformed axis is ``(n/2)+1``. + If `n` is odd, the length is ``(n+1)/2``. + + Raises + ------ + IndexError + If `axis` is larger than the last axis of `a`. + + See Also + -------- + irfft : The inverse of `rfft`. + fft : The 1-D FFT of general (complex) input. + fftn : The N-D FFT. + rfft2 : The 2-D FFT of real input. + rfftn : The N-D FFT of real input. + + Notes + ----- + When the DFT is computed for purely real input, the output is + Hermitian-symmetric, i.e., the negative frequency terms are just the complex + conjugates of the corresponding positive-frequency terms, and the + negative-frequency terms are therefore redundant. This function does not + compute the negative frequency terms, and the length of the transformed + axis of the output is therefore ``n//2 + 1``. + + When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains + the zero-frequency term 0*fs, which is real due to Hermitian symmetry. + + If `n` is even, ``A[-1]`` contains the term representing both positive + and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely + real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains + the largest positive frequency (fs/2*(n-1)/n), and is complex in the + general case. + + If the input `a` contains an imaginary part, it is silently discarded. + + Examples + -------- + >>> import scipy.fft + >>> scipy.fft.fft([0, 1, 0, 0]) + array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary + >>> scipy.fft.rfft([0, 1, 0, 0]) + array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary + + Notice how the final element of the `fft` output is the complex conjugate + of the second element, for real input. For `rfft`, this symmetry is + exploited to compute only the non-negative frequency terms. + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Computes the inverse of `rfft`. + + This function computes the inverse of the 1-D *n*-point + discrete Fourier Transform of real input computed by `rfft`. + In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical + accuracy. (See Notes below for why ``len(a)`` is necessary here.) + + The input is expected to be in the form returned by `rfft`, i.e., the + real zero-frequency term followed by the complex positive frequency terms + in order of increasing frequency. Since the discrete Fourier Transform of + real input is Hermitian-symmetric, the negative frequency terms are taken + to be the complex conjugates of the corresponding positive frequency terms. + + Parameters + ---------- + x : array_like + The input array. + n : int, optional + Length of the transformed axis of the output. + For `n` output points, ``n//2+1`` input points are necessary. If the + input is longer than this, it is cropped. If it is shorter than this, + it is padded with zeros. If `n` is not given, it is taken to be + ``2*(m-1)``, where ``m`` is the length of the input along the axis + specified by `axis`. + axis : int, optional + Axis over which to compute the inverse FFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + The length of the transformed axis is `n`, or, if `n` is not given, + ``2*(m-1)`` where ``m`` is the length of the transformed axis of the + input. To get an odd number of output points, `n` must be specified. + + Raises + ------ + IndexError + If `axis` is larger than the last axis of `x`. + + See Also + -------- + rfft : The 1-D FFT of real input, of which `irfft` is inverse. + fft : The 1-D FFT. + irfft2 : The inverse of the 2-D FFT of real input. + irfftn : The inverse of the N-D FFT of real input. + + Notes + ----- + Returns the real valued `n`-point inverse discrete Fourier transform + of `x`, where `x` contains the non-negative frequency terms of a + Hermitian-symmetric sequence. `n` is the length of the result, not the + input. + + If you specify an `n` such that `a` must be zero-padded or truncated, the + extra/removed values will be added/removed at high frequencies. One can + thus resample a series to `m` points via Fourier interpolation by: + ``a_resamp = irfft(rfft(a), m)``. + + The default value of `n` assumes an even output length. By the Hermitian + symmetry, the last imaginary component must be 0 and so is ignored. To + avoid losing information, the correct length of the real input *must* be + given. + + Examples + -------- + >>> import scipy.fft + >>> scipy.fft.ifft([1, -1j, -1, 1j]) + array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary + >>> scipy.fft.irfft([1, -1j, -1]) + array([0., 1., 0., 0.]) + + Notice how the last term in the input to the ordinary `ifft` is the + complex conjugate of the second term, and the output has zero imaginary + part everywhere. When calling `irfft`, the negative frequencies are not + specified, and the output array is purely real. + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the FFT of a signal that has Hermitian symmetry, i.e., a real + spectrum. + + Parameters + ---------- + x : array_like + The input array. + n : int, optional + Length of the transformed axis of the output. For `n` output + points, ``n//2 + 1`` input points are necessary. If the input is + longer than this, it is cropped. If it is shorter than this, it is + padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``, + where ``m`` is the length of the input along the axis specified by + `axis`. + axis : int, optional + Axis over which to compute the FFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See `fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + The length of the transformed axis is `n`, or, if `n` is not given, + ``2*m - 2``, where ``m`` is the length of the transformed axis of + the input. To get an odd number of output points, `n` must be + specified, for instance, as ``2*m - 1`` in the typical case, + + Raises + ------ + IndexError + If `axis` is larger than the last axis of `a`. + + See Also + -------- + rfft : Compute the 1-D FFT for real input. + ihfft : The inverse of `hfft`. + hfftn : Compute the N-D FFT of a Hermitian signal. + + Notes + ----- + `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the + opposite case: here the signal has Hermitian symmetry in the time + domain and is real in the frequency domain. So, here, it's `hfft`, for + which you must supply the length of the result if it is to be odd. + * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error, + * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error. + + Examples + -------- + >>> from scipy.fft import fft, hfft + >>> import numpy as np + >>> a = 2 * np.pi * np.arange(10) / 10 + >>> signal = np.cos(a) + 3j * np.sin(3 * a) + >>> fft(signal).round(10) + array([ -0.+0.j, 5.+0.j, -0.+0.j, 15.-0.j, 0.+0.j, 0.+0.j, + -0.+0.j, -15.-0.j, 0.+0.j, 5.+0.j]) + >>> hfft(signal[:6]).round(10) # Input first half of signal + array([ 0., 5., 0., 15., -0., 0., 0., -15., -0., 5.]) + >>> hfft(signal, 10) # Input entire signal and truncate + array([ 0., 5., 0., 15., -0., 0., 0., -15., -0., 5.]) + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the inverse FFT of a signal that has Hermitian symmetry. + + Parameters + ---------- + x : array_like + Input array. + n : int, optional + Length of the inverse FFT, the number of points along + transformation axis in the input to use. If `n` is smaller than + the length of the input, the input is cropped. If it is larger, + the input is padded with zeros. If `n` is not given, the length of + the input along the axis specified by `axis` is used. + axis : int, optional + Axis over which to compute the inverse FFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See `fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + The length of the transformed axis is ``n//2 + 1``. + + See Also + -------- + hfft, irfft + + Notes + ----- + `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the + opposite case: here, the signal has Hermitian symmetry in the time + domain and is real in the frequency domain. So, here, it's `hfft`, for + which you must supply the length of the result if it is to be odd: + * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error, + * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error. + + Examples + -------- + >>> from scipy.fft import ifft, ihfft + >>> import numpy as np + >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4]) + >>> ifft(spectrum) + array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary + >>> ihfft(spectrum) + array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the N-D discrete Fourier Transform. + + This function computes the N-D discrete Fourier Transform over + any number of axes in an M-D array by means of the Fast Fourier + Transform (FFT). + + Parameters + ---------- + x : array_like + Input array, can be complex. + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``fft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` and `x`, + as explained in the parameters section above. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + ifftn : The inverse of `fftn`, the inverse N-D FFT. + fft : The 1-D FFT, with definitions and conventions used. + rfftn : The N-D FFT of real input. + fft2 : The 2-D FFT. + fftshift : Shifts zero-frequency terms to centre of array. + + Notes + ----- + The output, analogously to `fft`, contains the term for zero frequency in + the low-order corner of all axes, the positive frequency terms in the + first half of all axes, the term for the Nyquist frequency in the middle + of all axes and the negative frequency terms in the second half of all + axes, in order of decreasingly negative frequency. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = np.mgrid[:3, :3, :3][0] + >>> scipy.fft.fftn(x, axes=(1, 2)) + array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary + [ 0.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]], + [[ 9.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]], + [[18.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]]]) + >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1)) + array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary + [ 0.+0.j, 0.+0.j, 0.+0.j]], + [[-2.+0.j, -2.+0.j, -2.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]]]) + + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12, + ... 2 * np.pi * np.arange(200) / 34) + >>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape) + >>> FS = scipy.fft.fftn(S) + >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2)) + + >>> plt.show() + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the N-D inverse discrete Fourier Transform. + + This function computes the inverse of the N-D discrete + Fourier Transform over any number of axes in an M-D array by + means of the Fast Fourier Transform (FFT). In other words, + ``ifftn(fftn(x)) == x`` to within numerical accuracy. + + The input, analogously to `ifft`, should be ordered in the same way as is + returned by `fftn`, i.e., it should have the term for zero frequency + in all axes in the low-order corner, the positive frequency terms in the + first half of all axes, the term for the Nyquist frequency in the middle + of all axes and the negative frequency terms in the second half of all + axes, in order of decreasingly negative frequency. + + Parameters + ---------- + x : array_like + Input array, can be complex. + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``ifft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. See notes for issue on `ifft` zero padding. + axes : sequence of ints, optional + Axes over which to compute the IFFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` or `x`, + as explained in the parameters section above. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + fftn : The forward N-D FFT, of which `ifftn` is the inverse. + ifft : The 1-D inverse FFT. + ifft2 : The 2-D inverse FFT. + ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning + of array. + + Notes + ----- + Zero-padding, analogously with `ifft`, is performed by appending zeros to + the input along the specified dimension. Although this is the common + approach, it might lead to surprising results. If another form of zero + padding is desired, it must be performed before `ifftn` is called. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = np.eye(4) + >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,)) + array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary + [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]]) + + + Create and plot an image with band-limited frequency content: + + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> n = np.zeros((200,200), dtype=complex) + >>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20))) + >>> im = scipy.fft.ifftn(n).real + >>> plt.imshow(im) + + >>> plt.show() + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 2-D discrete Fourier Transform + + This function computes the N-D discrete Fourier Transform + over any axes in an M-D array by means of the + Fast Fourier Transform (FFT). By default, the transform is computed over + the last two axes of the input array, i.e., a 2-dimensional FFT. + + Parameters + ---------- + x : array_like + Input array, can be complex + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``fft(x, n)``. + Along each axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last two axes are + used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or the last two axes if `axes` is not given. + + Raises + ------ + ValueError + If `s` and `axes` have different length, or `axes` not given and + ``len(s) != 2``. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + ifft2 : The inverse 2-D FFT. + fft : The 1-D FFT. + fftn : The N-D FFT. + fftshift : Shifts zero-frequency terms to the center of the array. + For 2-D input, swaps first and third quadrants, and second + and fourth quadrants. + + Notes + ----- + `fft2` is just `fftn` with a different default for `axes`. + + The output, analogously to `fft`, contains the term for zero frequency in + the low-order corner of the transformed axes, the positive frequency terms + in the first half of these axes, the term for the Nyquist frequency in the + middle of the axes and the negative frequency terms in the second half of + the axes, in order of decreasingly negative frequency. + + See `fftn` for details and a plotting example, and `fft` for + definitions and conventions used. + + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = np.mgrid[:5, :5][0] + >>> scipy.fft.fft2(x) + array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary + 0. +0.j , 0. +0.j ], + [-12.5+17.20477401j, 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ], + [-12.5 +4.0614962j , 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ], + [-12.5 -4.0614962j , 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ], + [-12.5-17.20477401j, 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ]]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 2-D inverse discrete Fourier Transform. + + This function computes the inverse of the 2-D discrete Fourier + Transform over any number of axes in an M-D array by means of + the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x`` + to within numerical accuracy. By default, the inverse transform is + computed over the last two axes of the input array. + + The input, analogously to `ifft`, should be ordered in the same way as is + returned by `fft2`, i.e., it should have the term for zero frequency + in the low-order corner of the two axes, the positive frequency terms in + the first half of these axes, the term for the Nyquist frequency in the + middle of the axes and the negative frequency terms in the second half of + both axes, in order of decreasingly negative frequency. + + Parameters + ---------- + x : array_like + Input array, can be complex. + s : sequence of ints, optional + Shape (length of each axis) of the output (``s[0]`` refers to axis 0, + ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``. + Along each axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. See notes for issue on `ifft` zero padding. + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last two + axes are used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or the last two axes if `axes` is not given. + + Raises + ------ + ValueError + If `s` and `axes` have different length, or `axes` not given and + ``len(s) != 2``. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + fft2 : The forward 2-D FFT, of which `ifft2` is the inverse. + ifftn : The inverse of the N-D FFT. + fft : The 1-D FFT. + ifft : The 1-D inverse FFT. + + Notes + ----- + `ifft2` is just `ifftn` with a different default for `axes`. + + See `ifftn` for details and a plotting example, and `fft` for + definition and conventions used. + + Zero-padding, analogously with `ifft`, is performed by appending zeros to + the input along the specified dimension. Although this is the common + approach, it might lead to surprising results. If another form of zero + padding is desired, it must be performed before `ifft2` is called. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = 4 * np.eye(4) + >>> scipy.fft.ifft2(x) + array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary + [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], + [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], + [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the N-D discrete Fourier Transform for real input. + + This function computes the N-D discrete Fourier Transform over + any number of axes in an M-D real array by means of the Fast + Fourier Transform (FFT). By default, all axes are transformed, with the + real transform performed over the last axis, while the remaining + transforms are complex. + + Parameters + ---------- + x : array_like + Input array, taken to be real. + s : sequence of ints, optional + Shape (length along each transformed axis) to use from the input. + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + The final element of `s` corresponds to `n` for ``rfft(x, n)``, while + for the remaining axes, it corresponds to `n` for ``fft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` and `x`, + as explained in the parameters section above. + The length of the last axis transformed will be ``s[-1]//2+1``, + while the remaining transformed axes will have lengths according to + `s`, or unchanged from the input. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT + of real input. + fft : The 1-D FFT, with definitions and conventions used. + rfft : The 1-D FFT of real input. + fftn : The N-D FFT. + rfft2 : The 2-D FFT of real input. + + Notes + ----- + The transform for real input is performed over the last transformation + axis, as by `rfft`, then the transform over the remaining axes is + performed as by `fftn`. The order of the output is as for `rfft` for the + final transformation axis, and as for `fftn` for the remaining + transformation axes. + + See `fft` for details, definitions and conventions used. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = np.ones((2, 2, 2)) + >>> scipy.fft.rfftn(x) + array([[[8.+0.j, 0.+0.j], # may vary + [0.+0.j, 0.+0.j]], + [[0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j]]]) + + >>> scipy.fft.rfftn(x, axes=(2, 0)) + array([[[4.+0.j, 0.+0.j], # may vary + [4.+0.j, 0.+0.j]], + [[0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j]]]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 2-D FFT of a real array. + + Parameters + ---------- + x : array + Input array, taken to be real. + s : sequence of ints, optional + Shape of the FFT. + axes : sequence of ints, optional + Axes over which to compute the FFT. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The result of the real 2-D FFT. + + See Also + -------- + irfft2 : The inverse of the 2-D FFT of real input. + rfft : The 1-D FFT of real input. + rfftn : Compute the N-D discrete Fourier Transform for real + input. + + Notes + ----- + This is really just `rfftn` with different default behavior. + For more details see `rfftn`. + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Computes the inverse of `rfftn` + + This function computes the inverse of the N-D discrete + Fourier Transform for real input over any number of axes in an + M-D array by means of the Fast Fourier Transform (FFT). In + other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical + accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`, + and for the same reason.) + + The input should be ordered in the same way as is returned by `rfftn`, + i.e., as for `irfft` for the final transformation axis, and as for `ifftn` + along all the other axes. + + Parameters + ---------- + x : array_like + Input array. + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the + number of input points used along this axis, except for the last axis, + where ``s[-1]//2+1`` points of the input are used. + Along any axis, if the shape indicated by `s` is smaller than that of + the input, the input is cropped. If it is larger, the input is padded + with zeros. If `s` is not given, the shape of the input along the axes + specified by axes is used. Except for the last axis which is taken to be + ``2*(m-1)``, where ``m`` is the length of the input along that axis. + axes : sequence of ints, optional + Axes over which to compute the inverse FFT. If not given, the last + `len(s)` axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` or `x`, + as explained in the parameters section above. + The length of each transformed axis is as given by the corresponding + element of `s`, or the length of the input in every axis except for the + last one if `s` is not given. In the final transformed axis the length + of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the + length of the final transformed axis of the input. To get an odd + number of output points in the final axis, `s` must be specified. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + rfftn : The forward N-D FFT of real input, + of which `ifftn` is the inverse. + fft : The 1-D FFT, with definitions and conventions used. + irfft : The inverse of the 1-D FFT of real input. + irfft2 : The inverse of the 2-D FFT of real input. + + Notes + ----- + See `fft` for definitions and conventions used. + + See `rfft` for definitions and conventions used for real input. + + The default value of `s` assumes an even output length in the final + transformation axis. When performing the final complex to real + transformation, the Hermitian symmetry requires that the last imaginary + component along that axis must be 0 and so it is ignored. To avoid losing + information, the correct length of the real input *must* be given. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = np.zeros((3, 2, 2)) + >>> x[0, 0, 0] = 3 * 2 * 2 + >>> scipy.fft.irfftn(x) + array([[[1., 1.], + [1., 1.]], + [[1., 1.], + [1., 1.]], + [[1., 1.], + [1., 1.]]]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Computes the inverse of `rfft2` + + Parameters + ---------- + x : array_like + The input array + s : sequence of ints, optional + Shape of the real output to the inverse FFT. + axes : sequence of ints, optional + The axes over which to compute the inverse fft. + Default is the last two axes. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The result of the inverse real 2-D FFT. + + See Also + -------- + rfft2 : The 2-D FFT of real input. + irfft : The inverse of the 1-D FFT of real input. + irfftn : The inverse of the N-D FFT of real input. + + Notes + ----- + This is really `irfftn` with different defaults. + For more details see `irfftn`. + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the N-D FFT of Hermitian symmetric complex input, i.e., a + signal with a real spectrum. + + This function computes the N-D discrete Fourier Transform for a + Hermitian symmetric complex input over any number of axes in an + M-D array by means of the Fast Fourier Transform (FFT). In other + words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s`` + here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary + for the same reason ``x.shape`` would be necessary for `irfft`.) + + Parameters + ---------- + x : array_like + Input array. + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the + number of input points used along this axis, except for the last axis, + where ``s[-1]//2+1`` points of the input are used. + Along any axis, if the shape indicated by `s` is smaller than that of + the input, the input is cropped. If it is larger, the input is padded + with zeros. If `s` is not given, the shape of the input along the axes + specified by axes is used. Except for the last axis which is taken to be + ``2*(m-1)`` where ``m`` is the length of the input along that axis. + axes : sequence of ints, optional + Axes over which to compute the inverse FFT. If not given, the last + `len(s)` axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` or `x`, + as explained in the parameters section above. + The length of each transformed axis is as given by the corresponding + element of `s`, or the length of the input in every axis except for the + last one if `s` is not given. In the final transformed axis the length + of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the + length of the final transformed axis of the input. To get an odd + number of output points in the final axis, `s` must be specified. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`. + fft : The 1-D FFT, with definitions and conventions used. + rfft : Forward FFT of real input. + + Notes + ----- + For a 1-D signal ``x`` to have a real spectrum, it must satisfy + the Hermitian property:: + + x[i] == np.conj(x[-i]) for all i + + This generalizes into higher dimensions by reflecting over each axis in + turn:: + + x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ... + + This should not be confused with a Hermitian matrix, for which the + transpose is its own conjugate:: + + x[i, j] == np.conj(x[j, i]) for all i, j + + + The default value of `s` assumes an even output length in the final + transformation axis. When performing the final complex to real + transformation, the Hermitian symmetry requires that the last imaginary + component along that axis must be 0 and so it is ignored. To avoid losing + information, the correct length of the real input *must* be given. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = np.ones((3, 2, 2)) + >>> scipy.fft.hfftn(x) + array([[[12., 0.], + [ 0., 0.]], + [[ 0., 0.], + [ 0., 0.]], + [[ 0., 0.], + [ 0., 0.]]]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 2-D FFT of a Hermitian complex array. + + Parameters + ---------- + x : array + Input array, taken to be Hermitian complex. + s : sequence of ints, optional + Shape of the real output. + axes : sequence of ints, optional + Axes over which to compute the FFT. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See `fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The real result of the 2-D Hermitian complex real FFT. + + See Also + -------- + hfftn : Compute the N-D discrete Fourier Transform for Hermitian + complex input. + + Notes + ----- + This is really just `hfftn` with different default behavior. + For more details see `hfftn`. + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the N-D inverse discrete Fourier Transform for a real + spectrum. + + This function computes the N-D inverse discrete Fourier Transform + over any number of axes in an M-D real array by means of the Fast + Fourier Transform (FFT). By default, all axes are transformed, with the + real transform performed over the last axis, while the remaining transforms + are complex. + + Parameters + ---------- + x : array_like + Input array, taken to be real. + s : sequence of ints, optional + Shape (length along each transformed axis) to use from the input. + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` and `x`, + as explained in the parameters section above. + The length of the last axis transformed will be ``s[-1]//2+1``, + while the remaining transformed axes will have lengths according to + `s`, or unchanged from the input. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than the number of axes of `x`. + + See Also + -------- + hfftn : The forward N-D FFT of Hermitian input. + hfft : The 1-D FFT of Hermitian input. + fft : The 1-D FFT, with definitions and conventions used. + fftn : The N-D FFT. + hfft2 : The 2-D FFT of Hermitian input. + + Notes + ----- + The transform for real input is performed over the last transformation + axis, as by `ihfft`, then the transform over the remaining axes is + performed as by `ifftn`. The order of the output is the positive part of + the Hermitian output signal, in the same format as `rfft`. + + Examples + -------- + >>> import scipy.fft + >>> import numpy as np + >>> x = np.ones((2, 2, 2)) + >>> scipy.fft.ihfftn(x) + array([[[1.+0.j, 0.+0.j], # may vary + [0.+0.j, 0.+0.j]], + [[0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j]]]) + >>> scipy.fft.ihfftn(x, axes=(2, 0)) + array([[[1.+0.j, 0.+0.j], # may vary + [1.+0.j, 0.+0.j]], + [[0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j]]]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *, + plan=None): + """ + Compute the 2-D inverse FFT of a real spectrum. + + Parameters + ---------- + x : array_like + The input array + s : sequence of ints, optional + Shape of the real input to the inverse FFT. + axes : sequence of ints, optional + The axes over which to compute the inverse fft. + Default is the last two axes. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `fft`). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + See :func:`fft` for more details. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + plan : object, optional + This argument is reserved for passing in a precomputed plan provided + by downstream FFT vendors. It is currently not used in SciPy. + + .. versionadded:: 1.5.0 + + Returns + ------- + out : ndarray + The result of the inverse real 2-D FFT. + + See Also + -------- + ihfftn : Compute the inverse of the N-D FFT of Hermitian input. + + Notes + ----- + This is really `ihfftn` with different defaults. + For more details see `ihfftn`. + + """ + return (Dispatchable(x, np.ndarray),) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..775b26a8bf5922f7fa3634ad6c8c708a96820931 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py @@ -0,0 +1,197 @@ +from scipy._lib._array_api import ( + array_namespace, is_numpy, xp_unsupported_param_msg, is_complex, xp_float_to_complex +) +from . import _pocketfft +import numpy as np + + +def _validate_fft_args(workers, plan, norm): + if workers is not None: + raise ValueError(xp_unsupported_param_msg("workers")) + if plan is not None: + raise ValueError(xp_unsupported_param_msg("plan")) + if norm is None: + norm = 'backward' + return norm + + +# these functions expect complex input in the fft standard extension +complex_funcs = {'fft', 'ifft', 'fftn', 'ifftn', 'hfft', 'irfft', 'irfftn'} + +# pocketfft is used whenever SCIPY_ARRAY_API is not set, +# or x is a NumPy array or array-like. +# When SCIPY_ARRAY_API is set, we try to use xp.fft for CuPy arrays, +# PyTorch arrays and other array API standard supporting objects. +# If xp.fft does not exist, we attempt to convert to np and back to use pocketfft. + +def _execute_1D(func_str, pocketfft_func, x, n, axis, norm, overwrite_x, workers, plan): + xp = array_namespace(x) + + if is_numpy(xp): + x = np.asarray(x) + return pocketfft_func(x, n=n, axis=axis, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + norm = _validate_fft_args(workers, plan, norm) + if hasattr(xp, 'fft'): + xp_func = getattr(xp.fft, func_str) + if func_str in complex_funcs: + try: + res = xp_func(x, n=n, axis=axis, norm=norm) + except: # backends may require complex input # noqa: E722 + x = xp_float_to_complex(x, xp) + res = xp_func(x, n=n, axis=axis, norm=norm) + return res + return xp_func(x, n=n, axis=axis, norm=norm) + + x = np.asarray(x) + y = pocketfft_func(x, n=n, axis=axis, norm=norm) + return xp.asarray(y) + + +def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan): + xp = array_namespace(x) + + if is_numpy(xp): + x = np.asarray(x) + return pocketfft_func(x, s=s, axes=axes, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + norm = _validate_fft_args(workers, plan, norm) + if hasattr(xp, 'fft'): + xp_func = getattr(xp.fft, func_str) + if func_str in complex_funcs: + try: + res = xp_func(x, s=s, axes=axes, norm=norm) + except: # backends may require complex input # noqa: E722 + x = xp_float_to_complex(x, xp) + res = xp_func(x, s=s, axes=axes, norm=norm) + return res + return xp_func(x, s=s, axes=axes, norm=norm) + + x = np.asarray(x) + y = pocketfft_func(x, s=s, axes=axes, norm=norm) + return xp.asarray(y) + + +def fft(x, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_1D('fft', _pocketfft.fft, x, n=n, axis=axis, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *, + plan=None): + return _execute_1D('ifft', _pocketfft.ifft, x, n=n, axis=axis, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def rfft(x, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_1D('rfft', _pocketfft.rfft, x, n=n, axis=axis, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def irfft(x, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_1D('irfft', _pocketfft.irfft, x, n=n, axis=axis, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def hfft(x, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_1D('hfft', _pocketfft.hfft, x, n=n, axis=axis, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def ihfft(x, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_1D('ihfft', _pocketfft.ihfft, x, n=n, axis=axis, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def fftn(x, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_nD('fftn', _pocketfft.fftn, x, s=s, axes=axes, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + + +def ifftn(x, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_nD('ifftn', _pocketfft.ifftn, x, s=s, axes=axes, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def fft2(x, s=None, axes=(-2, -1), norm=None, + overwrite_x=False, workers=None, *, plan=None): + return fftn(x, s, axes, norm, overwrite_x, workers, plan=plan) + + +def ifft2(x, s=None, axes=(-2, -1), norm=None, + overwrite_x=False, workers=None, *, plan=None): + return ifftn(x, s, axes, norm, overwrite_x, workers, plan=plan) + + +def rfftn(x, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_nD('rfftn', _pocketfft.rfftn, x, s=s, axes=axes, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def rfft2(x, s=None, axes=(-2, -1), norm=None, + overwrite_x=False, workers=None, *, plan=None): + return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan) + + +def irfftn(x, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, plan=None): + return _execute_nD('irfftn', _pocketfft.irfftn, x, s=s, axes=axes, norm=norm, + overwrite_x=overwrite_x, workers=workers, plan=plan) + + +def irfft2(x, s=None, axes=(-2, -1), norm=None, + overwrite_x=False, workers=None, *, plan=None): + return irfftn(x, s, axes, norm, overwrite_x, workers, plan=plan) + + +def _swap_direction(norm): + if norm in (None, 'backward'): + norm = 'forward' + elif norm == 'forward': + norm = 'backward' + elif norm != 'ortho': + raise ValueError(f'Invalid norm value {norm}; should be "backward", ' + '"ortho", or "forward".') + return norm + + +def hfftn(x, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, plan=None): + xp = array_namespace(x) + if is_numpy(xp): + x = np.asarray(x) + return _pocketfft.hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan) + if is_complex(x, xp): + x = xp.conj(x) + return irfftn(x, s, axes, _swap_direction(norm), + overwrite_x, workers, plan=plan) + + +def hfft2(x, s=None, axes=(-2, -1), norm=None, + overwrite_x=False, workers=None, *, plan=None): + return hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan) + + +def ihfftn(x, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, plan=None): + xp = array_namespace(x) + if is_numpy(xp): + x = np.asarray(x) + return _pocketfft.ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan) + return xp.conj(rfftn(x, s, axes, _swap_direction(norm), + overwrite_x, workers, plan=plan)) + +def ihfft2(x, s=None, axes=(-2, -1), norm=None, + overwrite_x=False, workers=None, *, plan=None): + return ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..c9647c5d6ceddc73b97d95f562662ada02c1ae74 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py @@ -0,0 +1,22 @@ +import numpy as np + +class NumPyBackend: + """Backend that uses numpy.fft""" + __ua_domain__ = "numpy.scipy.fft" + + @staticmethod + def __ua_function__(method, args, kwargs): + kwargs.pop("overwrite_x", None) + + fn = getattr(np.fft, method.__name__, None) + return (NotImplemented if fn is None + else fn(*args, **kwargs)) + + +class EchoBackend: + """Backend that just prints the __ua_function__ arguments""" + __ua_domain__ = "numpy.scipy.fft" + + @staticmethod + def __ua_function__(method, args, kwargs): + print(method, args, kwargs, sep='\n') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py new file mode 100644 index 0000000000000000000000000000000000000000..61bbe802bbb4a40df8ca3b653c693105b29c6578 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py @@ -0,0 +1,223 @@ +"""Fast Hankel transforms using the FFTLog algorithm. + +The implementation closely follows the Fortran code of Hamilton (2000). + +added: 14/11/2020 Nicolas Tessore +""" + +from ._basic import _dispatch +from scipy._lib.uarray import Dispatchable +from ._fftlog_backend import fhtoffset +import numpy as np + +__all__ = ['fht', 'ifht', 'fhtoffset'] + + +@_dispatch +def fht(a, dln, mu, offset=0.0, bias=0.0): + r'''Compute the fast Hankel transform. + + Computes the discrete Hankel transform of a logarithmically spaced periodic + sequence using the FFTLog algorithm [1]_, [2]_. + + Parameters + ---------- + a : array_like (..., n) + Real periodic input array, uniformly logarithmically spaced. For + multidimensional input, the transform is performed over the last axis. + dln : float + Uniform logarithmic spacing of the input array. + mu : float + Order of the Hankel transform, any positive or negative real number. + offset : float, optional + Offset of the uniform logarithmic spacing of the output array. + bias : float, optional + Exponent of power law bias, any positive or negative real number. + + Returns + ------- + A : array_like (..., n) + The transformed output array, which is real, periodic, uniformly + logarithmically spaced, and of the same shape as the input array. + + See Also + -------- + ifht : The inverse of `fht`. + fhtoffset : Return an optimal offset for `fht`. + + Notes + ----- + This function computes a discrete version of the Hankel transform + + .. math:: + + A(k) = \int_{0}^{\infty} \! a(r) \, J_\mu(kr) \, k \, dr \;, + + where :math:`J_\mu` is the Bessel function of order :math:`\mu`. The index + :math:`\mu` may be any real number, positive or negative. Note that the + numerical Hankel transform uses an integrand of :math:`k \, dr`, while the + mathematical Hankel transform is commonly defined using :math:`r \, dr`. + + The input array `a` is a periodic sequence of length :math:`n`, uniformly + logarithmically spaced with spacing `dln`, + + .. math:: + + a_j = a(r_j) \;, \quad + r_j = r_c \exp[(j-j_c) \, \mathtt{dln}] + + centred about the point :math:`r_c`. Note that the central index + :math:`j_c = (n-1)/2` is half-integral if :math:`n` is even, so that + :math:`r_c` falls between two input elements. Similarly, the output + array `A` is a periodic sequence of length :math:`n`, also uniformly + logarithmically spaced with spacing `dln` + + .. math:: + + A_j = A(k_j) \;, \quad + k_j = k_c \exp[(j-j_c) \, \mathtt{dln}] + + centred about the point :math:`k_c`. + + The centre points :math:`r_c` and :math:`k_c` of the periodic intervals may + be chosen arbitrarily, but it would be usual to choose the product + :math:`k_c r_c = k_j r_{n-1-j} = k_{n-1-j} r_j` to be unity. This can be + changed using the `offset` parameter, which controls the logarithmic offset + :math:`\log(k_c) = \mathtt{offset} - \log(r_c)` of the output array. + Choosing an optimal value for `offset` may reduce ringing of the discrete + Hankel transform. + + If the `bias` parameter is nonzero, this function computes a discrete + version of the biased Hankel transform + + .. math:: + + A(k) = \int_{0}^{\infty} \! a_q(r) \, (kr)^q \, J_\mu(kr) \, k \, dr + + where :math:`q` is the value of `bias`, and a power law bias + :math:`a_q(r) = a(r) \, (kr)^{-q}` is applied to the input sequence. + Biasing the transform can help approximate the continuous transform of + :math:`a(r)` if there is a value :math:`q` such that :math:`a_q(r)` is + close to a periodic sequence, in which case the resulting :math:`A(k)` will + be close to the continuous transform. + + References + ---------- + .. [1] Talman J. D., 1978, J. Comp. Phys., 29, 35 + .. [2] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191) + + Examples + -------- + + This example is the adapted version of ``fftlogtest.f`` which is provided + in [2]_. It evaluates the integral + + .. math:: + + \int^\infty_0 r^{\mu+1} \exp(-r^2/2) J_\mu(kr) k dr + = k^{\mu+1} \exp(-k^2/2) . + + >>> import numpy as np + >>> from scipy import fft + >>> import matplotlib.pyplot as plt + + Parameters for the transform. + + >>> mu = 0.0 # Order mu of Bessel function + >>> r = np.logspace(-7, 1, 128) # Input evaluation points + >>> dln = np.log(r[1]/r[0]) # Step size + >>> offset = fft.fhtoffset(dln, initial=-6*np.log(10), mu=mu) + >>> k = np.exp(offset)/r[::-1] # Output evaluation points + + Define the analytical function. + + >>> def f(x, mu): + ... """Analytical function: x^(mu+1) exp(-x^2/2).""" + ... return x**(mu + 1)*np.exp(-x**2/2) + + Evaluate the function at ``r`` and compute the corresponding values at + ``k`` using FFTLog. + + >>> a_r = f(r, mu) + >>> fht = fft.fht(a_r, dln, mu=mu, offset=offset) + + For this example we can actually compute the analytical response (which in + this case is the same as the input function) for comparison and compute the + relative error. + + >>> a_k = f(k, mu) + >>> rel_err = abs((fht-a_k)/a_k) + + Plot the result. + + >>> figargs = {'sharex': True, 'sharey': True, 'constrained_layout': True} + >>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), **figargs) + >>> ax1.set_title(r'$r^{\mu+1}\ \exp(-r^2/2)$') + >>> ax1.loglog(r, a_r, 'k', lw=2) + >>> ax1.set_xlabel('r') + >>> ax2.set_title(r'$k^{\mu+1} \exp(-k^2/2)$') + >>> ax2.loglog(k, a_k, 'k', lw=2, label='Analytical') + >>> ax2.loglog(k, fht, 'C3--', lw=2, label='FFTLog') + >>> ax2.set_xlabel('k') + >>> ax2.legend(loc=3, framealpha=1) + >>> ax2.set_ylim([1e-10, 1e1]) + >>> ax2b = ax2.twinx() + >>> ax2b.loglog(k, rel_err, 'C0', label='Rel. Error (-)') + >>> ax2b.set_ylabel('Rel. Error (-)', color='C0') + >>> ax2b.tick_params(axis='y', labelcolor='C0') + >>> ax2b.legend(loc=4, framealpha=1) + >>> ax2b.set_ylim([1e-9, 1e-3]) + >>> plt.show() + + ''' + return (Dispatchable(a, np.ndarray),) + + +@_dispatch +def ifht(A, dln, mu, offset=0.0, bias=0.0): + r"""Compute the inverse fast Hankel transform. + + Computes the discrete inverse Hankel transform of a logarithmically spaced + periodic sequence. This is the inverse operation to `fht`. + + Parameters + ---------- + A : array_like (..., n) + Real periodic input array, uniformly logarithmically spaced. For + multidimensional input, the transform is performed over the last axis. + dln : float + Uniform logarithmic spacing of the input array. + mu : float + Order of the Hankel transform, any positive or negative real number. + offset : float, optional + Offset of the uniform logarithmic spacing of the output array. + bias : float, optional + Exponent of power law bias, any positive or negative real number. + + Returns + ------- + a : array_like (..., n) + The transformed output array, which is real, periodic, uniformly + logarithmically spaced, and of the same shape as the input array. + + See Also + -------- + fht : Definition of the fast Hankel transform. + fhtoffset : Return an optimal offset for `ifht`. + + Notes + ----- + This function computes a discrete version of the Hankel transform + + .. math:: + + a(r) = \int_{0}^{\infty} \! A(k) \, J_\mu(kr) \, r \, dk \;, + + where :math:`J_\mu` is the Bessel function of order :math:`\mu`. The index + :math:`\mu` may be any real number, positive or negative. Note that the + numerical inverse Hankel transform uses an integrand of :math:`r \, dk`, while the + mathematical inverse Hankel transform is commonly defined using :math:`k \, dk`. + + See `fht` for further details. + """ + return (Dispatchable(A, np.ndarray),) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..0b38733aaa349c301ba7d5b83691c55204dc8991 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py @@ -0,0 +1,200 @@ +import numpy as np +from warnings import warn +from ._basic import rfft, irfft +from ..special import loggamma, poch + +from scipy._lib._array_api import array_namespace + +__all__ = ['fht', 'ifht', 'fhtoffset'] + +# constants +LN_2 = np.log(2) + + +def fht(a, dln, mu, offset=0.0, bias=0.0): + xp = array_namespace(a) + a = xp.asarray(a) + + # size of transform + n = a.shape[-1] + + # bias input array + if bias != 0: + # a_q(r) = a(r) (r/r_c)^{-q} + j_c = (n-1)/2 + j = xp.arange(n, dtype=xp.float64) + a = a * xp.exp(-bias*(j - j_c)*dln) + + # compute FHT coefficients + u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias)) + + # transform + A = _fhtq(a, u, xp=xp) + + # bias output array + if bias != 0: + # A(k) = A_q(k) (k/k_c)^{-q} (k_c r_c)^{-q} + A *= xp.exp(-bias*((j - j_c)*dln + offset)) + + return A + + +def ifht(A, dln, mu, offset=0.0, bias=0.0): + xp = array_namespace(A) + A = xp.asarray(A) + + # size of transform + n = A.shape[-1] + + # bias input array + if bias != 0: + # A_q(k) = A(k) (k/k_c)^{q} (k_c r_c)^{q} + j_c = (n-1)/2 + j = xp.arange(n, dtype=xp.float64) + A = A * xp.exp(bias*((j - j_c)*dln + offset)) + + # compute FHT coefficients + u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias, inverse=True)) + + # transform + a = _fhtq(A, u, inverse=True, xp=xp) + + # bias output array + if bias != 0: + # a(r) = a_q(r) (r/r_c)^{q} + a /= xp.exp(-bias*(j - j_c)*dln) + + return a + + +def fhtcoeff(n, dln, mu, offset=0.0, bias=0.0, inverse=False): + """Compute the coefficient array for a fast Hankel transform.""" + lnkr, q = offset, bias + + # Hankel transform coefficients + # u_m = (kr)^{-i 2m pi/(n dlnr)} U_mu(q + i 2m pi/(n dlnr)) + # with U_mu(x) = 2^x Gamma((mu+1+x)/2)/Gamma((mu+1-x)/2) + xp = (mu+1+q)/2 + xm = (mu+1-q)/2 + y = np.linspace(0, np.pi*(n//2)/(n*dln), n//2+1) + u = np.empty(n//2+1, dtype=complex) + v = np.empty(n//2+1, dtype=complex) + u.imag[:] = y + u.real[:] = xm + loggamma(u, out=v) + u.real[:] = xp + loggamma(u, out=u) + y *= 2*(LN_2 - lnkr) + u.real -= v.real + u.real += LN_2*q + u.imag += v.imag + u.imag += y + np.exp(u, out=u) + + # fix last coefficient to be real + if n % 2 == 0: + u.imag[-1] = 0 + + # deal with special cases + if not np.isfinite(u[0]): + # write u_0 = 2^q Gamma(xp)/Gamma(xm) = 2^q poch(xm, xp-xm) + # poch() handles special cases for negative integers correctly + u[0] = 2**q * poch(xm, xp-xm) + # the coefficient may be inf or 0, meaning the transform or the + # inverse transform, respectively, is singular + + # check for singular transform or singular inverse transform + if np.isinf(u[0]) and not inverse: + warn('singular transform; consider changing the bias', stacklevel=3) + # fix coefficient to obtain (potentially correct) transform anyway + u = np.copy(u) + u[0] = 0 + elif u[0] == 0 and inverse: + warn('singular inverse transform; consider changing the bias', stacklevel=3) + # fix coefficient to obtain (potentially correct) inverse anyway + u = np.copy(u) + u[0] = np.inf + + return u + + +def fhtoffset(dln, mu, initial=0.0, bias=0.0): + """Return optimal offset for a fast Hankel transform. + + Returns an offset close to `initial` that fulfils the low-ringing + condition of [1]_ for the fast Hankel transform `fht` with logarithmic + spacing `dln`, order `mu` and bias `bias`. + + Parameters + ---------- + dln : float + Uniform logarithmic spacing of the transform. + mu : float + Order of the Hankel transform, any positive or negative real number. + initial : float, optional + Initial value for the offset. Returns the closest value that fulfils + the low-ringing condition. + bias : float, optional + Exponent of power law bias, any positive or negative real number. + + Returns + ------- + offset : float + Optimal offset of the uniform logarithmic spacing of the transform that + fulfils a low-ringing condition. + + Examples + -------- + >>> from scipy.fft import fhtoffset + >>> dln = 0.1 + >>> mu = 2.0 + >>> initial = 0.5 + >>> bias = 0.0 + >>> offset = fhtoffset(dln, mu, initial, bias) + >>> offset + 0.5454581477676637 + + See Also + -------- + fht : Definition of the fast Hankel transform. + + References + ---------- + .. [1] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191) + + """ + + lnkr, q = initial, bias + + xp = (mu+1+q)/2 + xm = (mu+1-q)/2 + y = np.pi/(2*dln) + zp = loggamma(xp + 1j*y) + zm = loggamma(xm + 1j*y) + arg = (LN_2 - lnkr)/dln + (zp.imag + zm.imag)/np.pi + return lnkr + (arg - np.round(arg))*dln + + +def _fhtq(a, u, inverse=False, *, xp=None): + """Compute the biased fast Hankel transform. + + This is the basic FFTLog routine. + """ + if xp is None: + xp = np + + # size of transform + n = a.shape[-1] + + # biased fast Hankel transform via real FFT + A = rfft(a, axis=-1) + if not inverse: + # forward transform + A *= u + else: + # backward transform + A /= xp.conj(u) + A = irfft(A, n, axis=-1) + A = xp.flip(A, axis=-1) + + return A diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..76e08c4f61c854f9bfb9407a1951f2cf5a2af123 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py @@ -0,0 +1,379 @@ +from functools import update_wrapper, lru_cache +import inspect + +from ._pocketfft import helper as _helper + +import numpy as np +from scipy._lib._array_api import array_namespace + + +def next_fast_len(target, real=False): + """Find the next fast size of input data to ``fft``, for zero-padding, etc. + + SciPy's FFT algorithms gain their speed by a recursive divide and conquer + strategy. This relies on efficient functions for small prime factors of the + input length. Thus, the transforms are fastest when using composites of the + prime factors handled by the fft implementation. If there are efficient + functions for all radices <= `n`, then the result will be a number `x` + >= ``target`` with only prime factors < `n`. (Also known as `n`-smooth + numbers) + + Parameters + ---------- + target : int + Length to start searching from. Must be a positive integer. + real : bool, optional + True if the FFT involves real input or output (e.g., `rfft` or `hfft` + but not `fft`). Defaults to False. + + Returns + ------- + out : int + The smallest fast length greater than or equal to ``target``. + + Notes + ----- + The result of this function may change in future as performance + considerations change, for example, if new prime factors are added. + + Calling `fft` or `ifft` with real input data performs an ``'R2C'`` + transform internally. + + Examples + -------- + On a particular machine, an FFT of prime length takes 11.4 ms: + + >>> from scipy import fft + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> min_len = 93059 # prime length is worst case for speed + >>> a = rng.standard_normal(min_len) + >>> b = fft.fft(a) + + Zero-padding to the next regular length reduces computation time to + 1.6 ms, a speedup of 7.3 times: + + >>> fft.next_fast_len(min_len, real=True) + 93312 + >>> b = fft.fft(a, 93312) + + Rounding up to the next power of 2 is not optimal, taking 3.0 ms to + compute; 1.9 times longer than the size given by ``next_fast_len``: + + >>> b = fft.fft(a, 131072) + + """ + pass + + +# Directly wrap the c-function good_size but take the docstring etc., from the +# next_fast_len function above +_sig = inspect.signature(next_fast_len) +next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len) +next_fast_len.__wrapped__ = _helper.good_size +next_fast_len.__signature__ = _sig + + +def prev_fast_len(target, real=False): + """Find the previous fast size of input data to ``fft``. + Useful for discarding a minimal number of samples before FFT. + + SciPy's FFT algorithms gain their speed by a recursive divide and conquer + strategy. This relies on efficient functions for small prime factors of the + input length. Thus, the transforms are fastest when using composites of the + prime factors handled by the fft implementation. If there are efficient + functions for all radices <= `n`, then the result will be a number `x` + <= ``target`` with only prime factors <= `n`. (Also known as `n`-smooth + numbers) + + Parameters + ---------- + target : int + Maximum length to search until. Must be a positive integer. + real : bool, optional + True if the FFT involves real input or output (e.g., `rfft` or `hfft` + but not `fft`). Defaults to False. + + Returns + ------- + out : int + The largest fast length less than or equal to ``target``. + + Notes + ----- + The result of this function may change in future as performance + considerations change, for example, if new prime factors are added. + + Calling `fft` or `ifft` with real input data performs an ``'R2C'`` + transform internally. + + In the current implementation, prev_fast_len assumes radices of + 2,3,5,7,11 for complex FFT and 2,3,5 for real FFT. + + Examples + -------- + On a particular machine, an FFT of prime length takes 16.2 ms: + + >>> from scipy import fft + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> max_len = 93059 # prime length is worst case for speed + >>> a = rng.standard_normal(max_len) + >>> b = fft.fft(a) + + Performing FFT on the maximum fast length less than max_len + reduces the computation time to 1.5 ms, a speedup of 10.5 times: + + >>> fft.prev_fast_len(max_len, real=True) + 92160 + >>> c = fft.fft(a[:92160]) # discard last 899 samples + + """ + pass + + +# Directly wrap the c-function prev_good_size but take the docstring etc., +# from the prev_fast_len function above +_sig_prev_fast_len = inspect.signature(prev_fast_len) +prev_fast_len = update_wrapper(lru_cache()(_helper.prev_good_size), prev_fast_len) +prev_fast_len.__wrapped__ = _helper.prev_good_size +prev_fast_len.__signature__ = _sig_prev_fast_len + + +def _init_nd_shape_and_axes(x, shape, axes): + """Handle shape and axes arguments for N-D transforms. + + Returns the shape and axes in a standard form, taking into account negative + values and checking for various potential errors. + + Parameters + ---------- + x : array_like + The input array. + shape : int or array_like of ints or None + The shape of the result. If both `shape` and `axes` (see below) are + None, `shape` is ``x.shape``; if `shape` is None but `axes` is + not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``. + If `shape` is -1, the size of the corresponding dimension of `x` is + used. + axes : int or array_like of ints or None + Axes along which the calculation is computed. + The default is over all axes. + Negative indices are automatically converted to their positive + counterparts. + + Returns + ------- + shape : tuple + The shape of the result as a tuple of integers. + axes : list + Axes along which the calculation is computed, as a list of integers. + + """ + x = np.asarray(x) + return _helper._init_nd_shape_and_axes(x, shape, axes) + + +def fftfreq(n, d=1.0, *, xp=None, device=None): + """Return the Discrete Fourier Transform sample frequencies. + + The returned float array `f` contains the frequency bin centers in cycles + per unit of the sample spacing (with zero at the start). For instance, if + the sample spacing is in seconds, then the frequency unit is cycles/second. + + Given a window length `n` and a sample spacing `d`:: + + f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even + f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd + + Parameters + ---------- + n : int + Window length. + d : scalar, optional + Sample spacing (inverse of the sampling rate). Defaults to 1. + xp : array_namespace, optional + The namespace for the return array. Default is None, where NumPy is used. + device : device, optional + The device for the return array. + Only valid when `xp.fft.fftfreq` implements the device parameter. + + Returns + ------- + f : ndarray + Array of length `n` containing the sample frequencies. + + Examples + -------- + >>> import numpy as np + >>> import scipy.fft + >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) + >>> fourier = scipy.fft.fft(signal) + >>> n = signal.size + >>> timestep = 0.1 + >>> freq = scipy.fft.fftfreq(n, d=timestep) + >>> freq + array([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25]) + + """ + xp = np if xp is None else xp + # numpy does not yet support the `device` keyword + # `xp.__name__ != 'numpy'` should be removed when numpy is compatible + if hasattr(xp, 'fft') and xp.__name__ != 'numpy': + return xp.fft.fftfreq(n, d=d, device=device) + if device is not None: + raise ValueError('device parameter is not supported for input array type') + return np.fft.fftfreq(n, d=d) + + +def rfftfreq(n, d=1.0, *, xp=None, device=None): + """Return the Discrete Fourier Transform sample frequencies + (for usage with rfft, irfft). + + The returned float array `f` contains the frequency bin centers in cycles + per unit of the sample spacing (with zero at the start). For instance, if + the sample spacing is in seconds, then the frequency unit is cycles/second. + + Given a window length `n` and a sample spacing `d`:: + + f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even + f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd + + Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`) + the Nyquist frequency component is considered to be positive. + + Parameters + ---------- + n : int + Window length. + d : scalar, optional + Sample spacing (inverse of the sampling rate). Defaults to 1. + xp : array_namespace, optional + The namespace for the return array. Default is None, where NumPy is used. + device : device, optional + The device for the return array. + Only valid when `xp.fft.rfftfreq` implements the device parameter. + + Returns + ------- + f : ndarray + Array of length ``n//2 + 1`` containing the sample frequencies. + + Examples + -------- + >>> import numpy as np + >>> import scipy.fft + >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float) + >>> fourier = scipy.fft.rfft(signal) + >>> n = signal.size + >>> sample_rate = 100 + >>> freq = scipy.fft.fftfreq(n, d=1./sample_rate) + >>> freq + array([ 0., 10., 20., ..., -30., -20., -10.]) + >>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate) + >>> freq + array([ 0., 10., 20., 30., 40., 50.]) + + """ + xp = np if xp is None else xp + # numpy does not yet support the `device` keyword + # `xp.__name__ != 'numpy'` should be removed when numpy is compatible + if hasattr(xp, 'fft') and xp.__name__ != 'numpy': + return xp.fft.rfftfreq(n, d=d, device=device) + if device is not None: + raise ValueError('device parameter is not supported for input array type') + return np.fft.rfftfreq(n, d=d) + + +def fftshift(x, axes=None): + """Shift the zero-frequency component to the center of the spectrum. + + This function swaps half-spaces for all axes listed (defaults to all). + Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. + + Parameters + ---------- + x : array_like + Input array. + axes : int or shape tuple, optional + Axes over which to shift. Default is None, which shifts all axes. + + Returns + ------- + y : ndarray + The shifted array. + + See Also + -------- + ifftshift : The inverse of `fftshift`. + + Examples + -------- + >>> import numpy as np + >>> freqs = np.fft.fftfreq(10, 0.1) + >>> freqs + array([ 0., 1., 2., ..., -3., -2., -1.]) + >>> np.fft.fftshift(freqs) + array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) + + Shift the zero-frequency component only along the second axis: + + >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) + >>> freqs + array([[ 0., 1., 2.], + [ 3., 4., -4.], + [-3., -2., -1.]]) + >>> np.fft.fftshift(freqs, axes=(1,)) + array([[ 2., 0., 1.], + [-4., 3., 4.], + [-1., -3., -2.]]) + + """ + xp = array_namespace(x) + if hasattr(xp, 'fft'): + return xp.fft.fftshift(x, axes=axes) + x = np.asarray(x) + y = np.fft.fftshift(x, axes=axes) + return xp.asarray(y) + + +def ifftshift(x, axes=None): + """The inverse of `fftshift`. Although identical for even-length `x`, the + functions differ by one sample for odd-length `x`. + + Parameters + ---------- + x : array_like + Input array. + axes : int or shape tuple, optional + Axes over which to calculate. Defaults to None, which shifts all axes. + + Returns + ------- + y : ndarray + The shifted array. + + See Also + -------- + fftshift : Shift zero-frequency component to the center of the spectrum. + + Examples + -------- + >>> import numpy as np + >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) + >>> freqs + array([[ 0., 1., 2.], + [ 3., 4., -4.], + [-3., -2., -1.]]) + >>> np.fft.ifftshift(np.fft.fftshift(freqs)) + array([[ 0., 1., 2.], + [ 3., 4., -4.], + [-3., -2., -1.]]) + + """ + xp = array_namespace(x) + if hasattr(xp, 'fft'): + return xp.fft.ifftshift(x, axes=axes) + x = np.asarray(x) + y = np.fft.ifftshift(x, axes=axes) + return xp.asarray(y) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..1b5163d8435976c24988afbd39ded304947178cb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md @@ -0,0 +1,25 @@ +Copyright (C) 2010-2019 Max-Planck-Society +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0671484c9a0780df353b9b783813b6fa7492d38d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py @@ -0,0 +1,9 @@ +""" FFT backend using pypocketfft """ + +from .basic import * +from .realtransforms import * +from .helper import * + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..153eecc278ae2c4e151043081d20883f5870d3e7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82403d7e6eae7486d737e574a9ff7a3e883b7317 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..142b6f19cad286c9186036ad57453e7466e06b7b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d44e7e62f17f479ee5823c3e779d188cb6e125d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2d0d33958021c431171b72f72c37363ac98e03 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py @@ -0,0 +1,251 @@ +""" +Discrete Fourier Transforms - basic.py +""" +import numpy as np +import functools +from . import pypocketfft as pfft +from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied, + _fix_shape, _fix_shape_1d, _normalization, + _workers) + +def c2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ Return discrete Fourier transform of real or complex sequence. """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + overwrite_x = overwrite_x or _datacopied(tmp, x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if n is not None: + tmp, copied = _fix_shape_1d(tmp, n, axis) + overwrite_x = overwrite_x or copied + elif tmp.shape[axis] < 1: + message = f"invalid number of data points ({tmp.shape[axis]}) specified" + raise ValueError(message) + + out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None) + + return pfft.c2c(tmp, (axis,), forward, norm, out, workers) + + +fft = functools.partial(c2c, True) +fft.__name__ = 'fft' +ifft = functools.partial(c2c, False) +ifft.__name__ = 'ifft' + + +def r2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ + Discrete Fourier transform of a real sequence. + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if not np.isrealobj(tmp): + raise TypeError("x must be a real sequence") + + if n is not None: + tmp, _ = _fix_shape_1d(tmp, n, axis) + elif tmp.shape[axis] < 1: + raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified") + + # Note: overwrite_x is not utilised + return pfft.r2c(tmp, (axis,), forward, norm, None, workers) + + +rfft = functools.partial(r2c, True) +rfft.__name__ = 'rfft' +ihfft = functools.partial(r2c, False) +ihfft.__name__ = 'ihfft' + + +def c2r(forward, x, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ + Return inverse discrete Fourier transform of real sequence x. + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + # TODO: Optimize for hermitian and real? + if np.isrealobj(tmp): + tmp = tmp + 0.j + + # Last axis utilizes hermitian symmetry + if n is None: + n = (tmp.shape[axis] - 1) * 2 + if n < 1: + raise ValueError(f"Invalid number of data points ({n}) specified") + else: + tmp, _ = _fix_shape_1d(tmp, (n//2) + 1, axis) + + # Note: overwrite_x is not utilized + return pfft.c2r(tmp, (axis,), n, forward, norm, None, workers) + + +hfft = functools.partial(c2r, True) +hfft.__name__ = 'hfft' +irfft = functools.partial(c2r, False) +irfft.__name__ = 'irfft' + + +def hfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None, + *, plan=None): + """ + 2-D discrete Fourier transform of a Hermitian sequence + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + return hfftn(x, s, axes, norm, overwrite_x, workers) + + +def ihfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None, + *, plan=None): + """ + 2-D discrete inverse Fourier transform of a Hermitian sequence + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + return ihfftn(x, s, axes, norm, overwrite_x, workers) + + +def c2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """ + Return multidimensional discrete Fourier transform. + """ + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + overwrite_x = overwrite_x or _datacopied(tmp, x) + workers = _workers(workers) + + if len(axes) == 0: + return x + + tmp, copied = _fix_shape(tmp, shape, axes) + overwrite_x = overwrite_x or copied + + norm = _normalization(norm, forward) + out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None) + + return pfft.c2c(tmp, axes, forward, norm, out, workers) + + +fftn = functools.partial(c2cn, True) +fftn.__name__ = 'fftn' +ifftn = functools.partial(c2cn, False) +ifftn.__name__ = 'ifftn' + +def r2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """Return multidimensional discrete Fourier transform of real input""" + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + + if not np.isrealobj(tmp): + raise TypeError("x must be a real sequence") + + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + tmp, _ = _fix_shape(tmp, shape, axes) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if len(axes) == 0: + raise ValueError("at least 1 axis must be transformed") + + # Note: overwrite_x is not utilized + return pfft.r2c(tmp, axes, forward, norm, None, workers) + + +rfftn = functools.partial(r2cn, True) +rfftn.__name__ = 'rfftn' +ihfftn = functools.partial(r2cn, False) +ihfftn.__name__ = 'ihfftn' + + +def c2rn(forward, x, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, *, plan=None): + """Multidimensional inverse discrete fourier transform with real output""" + if plan is not None: + raise NotImplementedError('Passing a precomputed plan is not yet ' + 'supported by scipy.fft functions') + tmp = _asfarray(x) + + # TODO: Optimize for hermitian and real? + if np.isrealobj(tmp): + tmp = tmp + 0.j + + noshape = s is None + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + + if len(axes) == 0: + raise ValueError("at least 1 axis must be transformed") + + shape = list(shape) + if noshape: + shape[-1] = (x.shape[axes[-1]] - 1) * 2 + + norm = _normalization(norm, forward) + workers = _workers(workers) + + # Last axis utilizes hermitian symmetry + lastsize = shape[-1] + shape[-1] = (shape[-1] // 2) + 1 + + tmp, _ = tuple(_fix_shape(tmp, shape, axes)) + + # Note: overwrite_x is not utilized + return pfft.c2r(tmp, axes, lastsize, forward, norm, None, workers) + + +hfftn = functools.partial(c2rn, True) +hfftn.__name__ = 'hfftn' +irfftn = functools.partial(c2rn, False) +irfftn.__name__ = 'irfftn' + + +def r2r_fftpack(forward, x, n=None, axis=-1, norm=None, overwrite_x=False): + """FFT of a real sequence, returning fftpack half complex format""" + tmp = _asfarray(x) + overwrite_x = overwrite_x or _datacopied(tmp, x) + norm = _normalization(norm, forward) + workers = _workers(None) + + if tmp.dtype.kind == 'c': + raise TypeError('x must be a real sequence') + + if n is not None: + tmp, copied = _fix_shape_1d(tmp, n, axis) + overwrite_x = overwrite_x or copied + elif tmp.shape[axis] < 1: + raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified") + + out = (tmp if overwrite_x else None) + + return pfft.r2r_fftpack(tmp, (axis,), forward, forward, norm, out, workers) + + +rfft_fftpack = functools.partial(r2r_fftpack, True) +rfft_fftpack.__name__ = 'rfft_fftpack' +irfft_fftpack = functools.partial(r2r_fftpack, False) +irfft_fftpack.__name__ = 'irfft_fftpack' diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2fbc553ccc46a4b337060a62702ec28cb8b254 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py @@ -0,0 +1,221 @@ +from numbers import Number +import operator +import os +import threading +import contextlib + +import numpy as np + +from scipy._lib._util import copy_if_needed + +# good_size is exposed (and used) from this import +from .pypocketfft import good_size, prev_good_size + + +__all__ = ['good_size', 'prev_good_size', 'set_workers', 'get_workers'] + +_config = threading.local() +_cpu_count = os.cpu_count() + + +def _iterable_of_int(x, name=None): + """Convert ``x`` to an iterable sequence of int + + Parameters + ---------- + x : value, or sequence of values, convertible to int + name : str, optional + Name of the argument being converted, only used in the error message + + Returns + ------- + y : ``List[int]`` + """ + if isinstance(x, Number): + x = (x,) + + try: + x = [operator.index(a) for a in x] + except TypeError as e: + name = name or "value" + raise ValueError(f"{name} must be a scalar or iterable of integers") from e + + return x + + +def _init_nd_shape_and_axes(x, shape, axes): + """Handles shape and axes arguments for nd transforms""" + noshape = shape is None + noaxes = axes is None + + if not noaxes: + axes = _iterable_of_int(axes, 'axes') + axes = [a + x.ndim if a < 0 else a for a in axes] + + if any(a >= x.ndim or a < 0 for a in axes): + raise ValueError("axes exceeds dimensionality of input") + if len(set(axes)) != len(axes): + raise ValueError("all axes must be unique") + + if not noshape: + shape = _iterable_of_int(shape, 'shape') + + if axes and len(axes) != len(shape): + raise ValueError("when given, axes and shape arguments" + " have to be of the same length") + if noaxes: + if len(shape) > x.ndim: + raise ValueError("shape requires more axes than are present") + axes = range(x.ndim - len(shape), x.ndim) + + shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)] + elif noaxes: + shape = list(x.shape) + axes = range(x.ndim) + else: + shape = [x.shape[a] for a in axes] + + if any(s < 1 for s in shape): + raise ValueError( + f"invalid number of data points ({shape}) specified") + + return tuple(shape), list(axes) + + +def _asfarray(x): + """ + Convert to array with floating or complex dtype. + + float16 values are also promoted to float32. + """ + if not hasattr(x, "dtype"): + x = np.asarray(x) + + if x.dtype == np.float16: + return np.asarray(x, np.float32) + elif x.dtype.kind not in 'fc': + return np.asarray(x, np.float64) + + # Require native byte order + dtype = x.dtype.newbyteorder('=') + # Always align input + copy = True if not x.flags['ALIGNED'] else copy_if_needed + return np.array(x, dtype=dtype, copy=copy) + +def _datacopied(arr, original): + """ + Strict check for `arr` not sharing any data with `original`, + under the assumption that arr = asarray(original) + """ + if arr is original: + return False + if not isinstance(original, np.ndarray) and hasattr(original, '__array__'): + return False + return arr.base is None + + +def _fix_shape(x, shape, axes): + """Internal auxiliary function for _raw_fft, _raw_fftnd.""" + must_copy = False + + # Build an nd slice with the dimensions to be read from x + index = [slice(None)]*x.ndim + for n, ax in zip(shape, axes): + if x.shape[ax] >= n: + index[ax] = slice(0, n) + else: + index[ax] = slice(0, x.shape[ax]) + must_copy = True + + index = tuple(index) + + if not must_copy: + return x[index], False + + s = list(x.shape) + for n, axis in zip(shape, axes): + s[axis] = n + + z = np.zeros(s, x.dtype) + z[index] = x[index] + return z, True + + +def _fix_shape_1d(x, n, axis): + if n < 1: + raise ValueError( + f"invalid number of data points ({n}) specified") + + return _fix_shape(x, (n,), (axis,)) + + +_NORM_MAP = {None: 0, 'backward': 0, 'ortho': 1, 'forward': 2} + + +def _normalization(norm, forward): + """Returns the pypocketfft normalization mode from the norm argument""" + try: + inorm = _NORM_MAP[norm] + return inorm if forward else (2 - inorm) + except KeyError: + raise ValueError( + f'Invalid norm value {norm!r}, should ' + 'be "backward", "ortho" or "forward"') from None + + +def _workers(workers): + if workers is None: + return getattr(_config, 'default_workers', 1) + + if workers < 0: + if workers >= -_cpu_count: + workers += 1 + _cpu_count + else: + raise ValueError(f"workers value out of range; got {workers}, must not be" + f" less than {-_cpu_count}") + elif workers == 0: + raise ValueError("workers must not be zero") + + return workers + + +@contextlib.contextmanager +def set_workers(workers): + """Context manager for the default number of workers used in `scipy.fft` + + Parameters + ---------- + workers : int + The default number of workers to use + + Examples + -------- + >>> import numpy as np + >>> from scipy import fft, signal + >>> rng = np.random.default_rng() + >>> x = rng.standard_normal((128, 64)) + >>> with fft.set_workers(4): + ... y = signal.fftconvolve(x, x) + + """ + old_workers = get_workers() + _config.default_workers = _workers(operator.index(workers)) + try: + yield + finally: + _config.default_workers = old_workers + + +def get_workers(): + """Returns the default number of workers within the current context + + Examples + -------- + >>> from scipy import fft + >>> fft.get_workers() + 1 + >>> with fft.set_workers(4): + ... fft.get_workers() + 4 + """ + return getattr(_config, 'default_workers', 1) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py new file mode 100644 index 0000000000000000000000000000000000000000..5a0c616742305444d51258e650344c060129dfab --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py @@ -0,0 +1,109 @@ +import numpy as np +from . import pypocketfft as pfft +from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied, + _fix_shape, _fix_shape_1d, _normalization, _workers) +import functools + + +def _r2r(forward, transform, x, type=2, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + """Forward or backward 1-D DCT/DST + + Parameters + ---------- + forward : bool + Transform direction (determines type and normalisation) + transform : {pypocketfft.dct, pypocketfft.dst} + The transform to perform + """ + tmp = _asfarray(x) + overwrite_x = overwrite_x or _datacopied(tmp, x) + norm = _normalization(norm, forward) + workers = _workers(workers) + + if not forward: + if type == 2: + type = 3 + elif type == 3: + type = 2 + + if n is not None: + tmp, copied = _fix_shape_1d(tmp, n, axis) + overwrite_x = overwrite_x or copied + elif tmp.shape[axis] < 1: + raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified") + + out = (tmp if overwrite_x else None) + + # For complex input, transform real and imaginary components separably + if np.iscomplexobj(x): + out = np.empty_like(tmp) if out is None else out + transform(tmp.real, type, (axis,), norm, out.real, workers) + transform(tmp.imag, type, (axis,), norm, out.imag, workers) + return out + + return transform(tmp, type, (axis,), norm, out, workers, orthogonalize) + + +dct = functools.partial(_r2r, True, pfft.dct) +dct.__name__ = 'dct' +idct = functools.partial(_r2r, False, pfft.dct) +idct.__name__ = 'idct' + +dst = functools.partial(_r2r, True, pfft.dst) +dst.__name__ = 'dst' +idst = functools.partial(_r2r, False, pfft.dst) +idst.__name__ = 'idst' + + +def _r2rn(forward, transform, x, type=2, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + """Forward or backward nd DCT/DST + + Parameters + ---------- + forward : bool + Transform direction (determines type and normalisation) + transform : {pypocketfft.dct, pypocketfft.dst} + The transform to perform + """ + tmp = _asfarray(x) + + shape, axes = _init_nd_shape_and_axes(tmp, s, axes) + overwrite_x = overwrite_x or _datacopied(tmp, x) + + if len(axes) == 0: + return x + + tmp, copied = _fix_shape(tmp, shape, axes) + overwrite_x = overwrite_x or copied + + if not forward: + if type == 2: + type = 3 + elif type == 3: + type = 2 + + norm = _normalization(norm, forward) + workers = _workers(workers) + out = (tmp if overwrite_x else None) + + # For complex input, transform real and imaginary components separably + if np.iscomplexobj(x): + out = np.empty_like(tmp) if out is None else out + transform(tmp.real, type, axes, norm, out.real, workers) + transform(tmp.imag, type, axes, norm, out.imag, workers) + return out + + return transform(tmp, type, axes, norm, out, workers, orthogonalize) + + +dctn = functools.partial(_r2rn, True, pfft.dct) +dctn.__name__ = 'dctn' +idctn = functools.partial(_r2rn, False, pfft.dct) +idctn.__name__ = 'idctn' + +dstn = functools.partial(_r2rn, True, pfft.dst) +dstn.__name__ = 'dstn' +idstn = functools.partial(_r2rn, False, pfft.dst) +idstn.__name__ = 'idstn' diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..feffc37944c24f81bba3352329cbf75743e4e280 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py @@ -0,0 +1,1013 @@ +# Created by Pearu Peterson, September 2002 + +from numpy.testing import (assert_, assert_equal, assert_array_almost_equal, + assert_array_almost_equal_nulp, assert_array_less, + assert_allclose) +import pytest +from pytest import raises as assert_raises +from scipy.fft._pocketfft import (ifft, fft, fftn, ifftn, + rfft, irfft, rfftn, irfftn, + hfft, ihfft, hfftn, ihfftn) + +from numpy import (arange, array, asarray, zeros, dot, exp, pi, + swapaxes, cdouble) +import numpy as np +import numpy.fft +from numpy.random import rand + +# "large" composite numbers supported by FFT._PYPOCKETFFT +LARGE_COMPOSITE_SIZES = [ + 2**13, + 2**5 * 3**5, + 2**3 * 3**3 * 5**2, +] +SMALL_COMPOSITE_SIZES = [ + 2, + 2*3*5, + 2*2*3*3, +] +# prime +LARGE_PRIME_SIZES = [ + 2011 +] +SMALL_PRIME_SIZES = [ + 29 +] + + +def _assert_close_in_norm(x, y, rtol, size, rdt): + # helper function for testing + err_msg = f"size: {size} rdt: {rdt}" + assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg) + + +def random(size): + return rand(*size) + +def swap_byteorder(arr): + """Returns the same array with swapped byteorder""" + dtype = arr.dtype.newbyteorder('S') + return arr.astype(dtype) + +def direct_dft(x): + x = asarray(x) + n = len(x) + y = zeros(n, dtype=cdouble) + w = -arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w), x) + return y + + +def direct_idft(x): + x = asarray(x) + n = len(x) + y = zeros(n, dtype=cdouble) + w = arange(n)*(2j*pi/n) + for i in range(n): + y[i] = dot(exp(i*w), x)/n + return y + + +def direct_dftn(x): + x = asarray(x) + for axis in range(x.ndim): + x = fft(x, axis=axis) + return x + + +def direct_idftn(x): + x = asarray(x) + for axis in range(x.ndim): + x = ifft(x, axis=axis) + return x + + +def direct_rdft(x): + x = asarray(x) + n = len(x) + w = -arange(n)*(2j*pi/n) + y = zeros(n//2+1, dtype=cdouble) + for i in range(n//2+1): + y[i] = dot(exp(i*w), x) + return y + + +def direct_irdft(x, n): + x = asarray(x) + x1 = zeros(n, dtype=cdouble) + for i in range(n//2+1): + x1[i] = x[i] + if i > 0 and 2*i < n: + x1[n-i] = np.conj(x[i]) + return direct_idft(x1).real + + +def direct_rdftn(x): + return fftn(rfft(x), axes=range(x.ndim - 1)) + + +class _TestFFTBase: + def setup_method(self): + self.cdt = None + self.rdt = None + np.random.seed(1234) + + def test_definition(self): + x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt) + y = fft(x) + assert_equal(y.dtype, self.cdt) + y1 = direct_dft(x) + assert_array_almost_equal(y,y1) + x = np.array([1,2,3,4+0j,5], dtype=self.cdt) + assert_array_almost_equal(fft(x),direct_dft(x)) + + def test_n_argument_real(self): + x1 = np.array([1,2,3,4], dtype=self.rdt) + x2 = np.array([1,2,3,4], dtype=self.rdt) + y = fft([x1,x2],n=4) + assert_equal(y.dtype, self.cdt) + assert_equal(y.shape,(2,4)) + assert_array_almost_equal(y[0],direct_dft(x1)) + assert_array_almost_equal(y[1],direct_dft(x2)) + + def _test_n_argument_complex(self): + x1 = np.array([1,2,3,4+1j], dtype=self.cdt) + x2 = np.array([1,2,3,4+1j], dtype=self.cdt) + y = fft([x1,x2],n=4) + assert_equal(y.dtype, self.cdt) + assert_equal(y.shape,(2,4)) + assert_array_almost_equal(y[0],direct_dft(x1)) + assert_array_almost_equal(y[1],direct_dft(x2)) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(n) + y = fft(x.astype(complex)) + y2 = numpy.fft.fft(x) + assert_array_almost_equal(y,y2) + y = fft(x) + assert_array_almost_equal(y,y2) + + def test_invalid_sizes(self): + assert_raises(ValueError, fft, []) + assert_raises(ValueError, fft, [[1,1],[2,2]], -5) + + +class TestLongDoubleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.clongdouble + self.rdt = np.longdouble + + +class TestDoubleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.cdouble + self.rdt = np.float64 + + +class TestSingleFFT(_TestFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + + +class TestFloat16FFT: + + def test_1_argument_real(self): + x1 = np.array([1, 2, 3, 4], dtype=np.float16) + y = fft(x1, n=4) + assert_equal(y.dtype, np.complex64) + assert_equal(y.shape, (4, )) + assert_array_almost_equal(y, direct_dft(x1.astype(np.float32))) + + def test_n_argument_real(self): + x1 = np.array([1, 2, 3, 4], dtype=np.float16) + x2 = np.array([1, 2, 3, 4], dtype=np.float16) + y = fft([x1, x2], n=4) + assert_equal(y.dtype, np.complex64) + assert_equal(y.shape, (2, 4)) + assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32))) + assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32))) + + +class _TestIFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt) + y = ifft(x) + y1 = direct_idft(x) + assert_equal(y.dtype, self.cdt) + assert_array_almost_equal(y,y1) + + x = np.array([1,2,3,4+0j,5], self.cdt) + assert_array_almost_equal(ifft(x),direct_idft(x)) + + def test_definition_real(self): + x = np.array([1,2,3,4,1,2,3,4], self.rdt) + y = ifft(x) + assert_equal(y.dtype, self.cdt) + y1 = direct_idft(x) + assert_array_almost_equal(y,y1) + + x = np.array([1,2,3,4,5], dtype=self.rdt) + assert_equal(y.dtype, self.cdt) + assert_array_almost_equal(ifft(x),direct_idft(x)) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(n) + y = ifft(x.astype(self.cdt)) + y2 = numpy.fft.ifft(x.astype(self.cdt)) + assert_allclose(y,y2, rtol=self.rtol, atol=self.atol) + y = ifft(x) + assert_allclose(y,y2, rtol=self.rtol, atol=self.atol) + + def test_random_complex(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.cdt) + x = random([size]).astype(self.cdt) + 1j*x + y1 = ifft(fft(x)) + y2 = fft(ifft(x)) + assert_equal(y1.dtype, self.cdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x) + assert_array_almost_equal(y2, x) + + def test_random_real(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.rdt) + y1 = ifft(fft(x)) + y2 = fft(ifft(x)) + assert_equal(y1.dtype, self.cdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x) + assert_array_almost_equal(y2, x) + + def test_size_accuracy(self): + # Sanity check for the accuracy for prime and non-prime sized inputs + for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: + np.random.seed(1234) + x = np.random.rand(size).astype(self.rdt) + y = ifft(fft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + y = fft(ifft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + + x = (x + 1j*np.random.rand(size)).astype(self.cdt) + y = ifft(fft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + y = fft(ifft(x)) + _assert_close_in_norm(x, y, self.rtol, size, self.rdt) + + def test_invalid_sizes(self): + assert_raises(ValueError, ifft, []) + assert_raises(ValueError, ifft, [[1,1],[2,2]], -5) + + +@pytest.mark.skipif(np.longdouble is np.float64, + reason="Long double is aliased to double") +class TestLongDoubleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.clongdouble + self.rdt = np.longdouble + self.rtol = 1e-10 + self.atol = 1e-10 + + +class TestDoubleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + self.rtol = 1e-10 + self.atol = 1e-10 + + +class TestSingleIFFT(_TestIFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + self.rtol = 1e-5 + self.atol = 1e-4 + + +class _TestRFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]: + x = np.array(t, dtype=self.rdt) + y = rfft(x) + y1 = direct_rdft(x) + assert_array_almost_equal(y,y1) + assert_equal(y.dtype, self.cdt) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(n) + y1 = np.fft.rfft(x) + y = rfft(x) + assert_array_almost_equal(y,y1) + + def test_invalid_sizes(self): + assert_raises(ValueError, rfft, []) + assert_raises(ValueError, rfft, [[1,1],[2,2]], -5) + + def test_complex_input(self): + x = np.zeros(10, dtype=self.cdt) + with assert_raises(TypeError, match="x must be a real sequence"): + rfft(x) + + # See gh-5790 + class MockSeries: + def __init__(self, data): + self.data = np.asarray(data) + + def __getattr__(self, item): + try: + return getattr(self.data, item) + except AttributeError as e: + raise AttributeError("'MockSeries' object " + f"has no attribute '{item}'") from e + + def test_non_ndarray_with_dtype(self): + x = np.array([1., 2., 3., 4., 5.]) + xs = _TestRFFTBase.MockSeries(x) + + expected = [1, 2, 3, 4, 5] + rfft(xs) + + # Data should not have been overwritten + assert_equal(x, expected) + assert_equal(xs.data, expected) + +@pytest.mark.skipif(np.longdouble is np.float64, + reason="Long double is aliased to double") +class TestRFFTLongDouble(_TestRFFTBase): + def setup_method(self): + self.cdt = np.clongdouble + self.rdt = np.longdouble + + +class TestRFFTDouble(_TestRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + + +class TestRFFTSingle(_TestRFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + + +class _TestIRFFTBase: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x1 = [1,2+3j,4+1j,1+2j,3+4j] + x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j] + x1 = x1_1[:5] + x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j] + x2 = x2_1[:5] + + def _test(x, xr): + y = irfft(np.array(x, dtype=self.cdt), n=len(xr)) + y1 = direct_irdft(x, len(xr)) + assert_equal(y.dtype, self.rdt) + assert_array_almost_equal(y,y1, decimal=self.ndec) + assert_array_almost_equal(y,ifft(xr), decimal=self.ndec) + + _test(x1, x1_1) + _test(x2, x2_1) + + def test_djbfft(self): + for i in range(2,14): + n = 2**i + x = np.arange(-1, n, 2) + 1j * np.arange(0, n+1, 2) + x[0] = 0 + if n % 2 == 0: + x[-1] = np.real(x[-1]) + y1 = np.fft.irfft(x) + y = irfft(x) + assert_array_almost_equal(y,y1) + + def test_random_real(self): + for size in [1,51,111,100,200,64,128,256,1024]: + x = random([size]).astype(self.rdt) + y1 = irfft(rfft(x), n=size) + y2 = rfft(irfft(x, n=(size*2-1))) + assert_equal(y1.dtype, self.rdt) + assert_equal(y2.dtype, self.cdt) + assert_array_almost_equal(y1, x, decimal=self.ndec, + err_msg="size=%d" % size) + assert_array_almost_equal(y2, x, decimal=self.ndec, + err_msg="size=%d" % size) + + def test_size_accuracy(self): + # Sanity check for the accuracy for prime and non-prime sized inputs + if self.rdt == np.float32: + rtol = 1e-5 + elif self.rdt == np.float64: + rtol = 1e-10 + + for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: + np.random.seed(1234) + x = np.random.rand(size).astype(self.rdt) + y = irfft(rfft(x), len(x)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + y = rfft(irfft(x, 2 * len(x) - 1)) + _assert_close_in_norm(x, y, rtol, size, self.rdt) + + def test_invalid_sizes(self): + assert_raises(ValueError, irfft, []) + assert_raises(ValueError, irfft, [[1,1],[2,2]], -5) + + +# self.ndec is bogus; we should have a assert_array_approx_equal for number of +# significant digits + +@pytest.mark.skipif(np.longdouble is np.float64, + reason="Long double is aliased to double") +class TestIRFFTLongDouble(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + self.ndec = 14 + + +class TestIRFFTDouble(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex128 + self.rdt = np.float64 + self.ndec = 14 + + +class TestIRFFTSingle(_TestIRFFTBase): + def setup_method(self): + self.cdt = np.complex64 + self.rdt = np.float32 + self.ndec = 5 + + +class TestFftnSingle: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(np.array(x, np.float32)) + assert_(y.dtype == np.complex64, + msg="double precision output with single precision") + + y_r = np.array(fftn(x), np.complex64) + assert_array_almost_equal_nulp(y, y_r) + + @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES) + def test_size_accuracy_small(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, size)) + 1j * rng.random((size, size)) + y1 = fftn(x.real.astype(np.float32)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2000) + + @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES) + def test_size_accuracy_large(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, 3)) + 1j * rng.random((size, 3)) + y1 = fftn(x.real.astype(np.float32)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2000) + + def test_definition_float16(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(np.array(x, np.float16)) + assert_equal(y.dtype, np.complex64) + y_r = np.array(fftn(x), np.complex64) + assert_array_almost_equal_nulp(y, y_r) + + @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES) + def test_float16_input_small(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, size)) + 1j*rng.random((size, size)) + y1 = fftn(x.real.astype(np.float16)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 5e5) + + @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES) + def test_float16_input_large(self, size): + rng = np.random.default_rng(1234) + x = rng.random((size, 3)) + 1j*rng.random((size, 3)) + y1 = fftn(x.real.astype(np.float16)) + y2 = fftn(x.real.astype(np.float64)).astype(np.complex64) + + assert_equal(y1.dtype, np.complex64) + assert_array_almost_equal_nulp(y1, y2, 2e6) + + +class TestFftn: + def setup_method(self): + np.random.seed(1234) + + def test_definition(self): + x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + y = fftn(x) + assert_array_almost_equal(y, direct_dftn(x)) + + x = random((20, 26)) + assert_array_almost_equal(fftn(x), direct_dftn(x)) + + x = random((5, 4, 3, 20)) + assert_array_almost_equal(fftn(x), direct_dftn(x)) + + def test_axes_argument(self): + # plane == ji_plane, x== kji_space + plane1 = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + plane2 = [[10, 11, 12], + [13, 14, 15], + [16, 17, 18]] + plane3 = [[19, 20, 21], + [22, 23, 24], + [25, 26, 27]] + ki_plane1 = [[1, 2, 3], + [10, 11, 12], + [19, 20, 21]] + ki_plane2 = [[4, 5, 6], + [13, 14, 15], + [22, 23, 24]] + ki_plane3 = [[7, 8, 9], + [16, 17, 18], + [25, 26, 27]] + jk_plane1 = [[1, 10, 19], + [4, 13, 22], + [7, 16, 25]] + jk_plane2 = [[2, 11, 20], + [5, 14, 23], + [8, 17, 26]] + jk_plane3 = [[3, 12, 21], + [6, 15, 24], + [9, 18, 27]] + kj_plane1 = [[1, 4, 7], + [10, 13, 16], [19, 22, 25]] + kj_plane2 = [[2, 5, 8], + [11, 14, 17], [20, 23, 26]] + kj_plane3 = [[3, 6, 9], + [12, 15, 18], [21, 24, 27]] + ij_plane1 = [[1, 4, 7], + [2, 5, 8], + [3, 6, 9]] + ij_plane2 = [[10, 13, 16], + [11, 14, 17], + [12, 15, 18]] + ij_plane3 = [[19, 22, 25], + [20, 23, 26], + [21, 24, 27]] + ik_plane1 = [[1, 10, 19], + [2, 11, 20], + [3, 12, 21]] + ik_plane2 = [[4, 13, 22], + [5, 14, 23], + [6, 15, 24]] + ik_plane3 = [[7, 16, 25], + [8, 17, 26], + [9, 18, 27]] + ijk_space = [jk_plane1, jk_plane2, jk_plane3] + ikj_space = [kj_plane1, kj_plane2, kj_plane3] + jik_space = [ik_plane1, ik_plane2, ik_plane3] + jki_space = [ki_plane1, ki_plane2, ki_plane3] + kij_space = [ij_plane1, ij_plane2, ij_plane3] + x = array([plane1, plane2, plane3]) + + assert_array_almost_equal(fftn(x), + fftn(x, axes=(-3, -2, -1))) # kji_space + assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2))) + assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1))) + y = fftn(x, axes=(2, 1, 0)) # ijk_space + assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space)) + y = fftn(x, axes=(2, 0, 1)) # ikj_space + assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2), + fftn(ikj_space)) + y = fftn(x, axes=(1, 2, 0)) # jik_space + assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2), + fftn(jik_space)) + y = fftn(x, axes=(1, 0, 2)) # jki_space + assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space)) + y = fftn(x, axes=(0, 2, 1)) # kij_space + assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space)) + + y = fftn(x, axes=(-2, -1)) # ji_plane + assert_array_almost_equal(fftn(plane1), y[0]) + assert_array_almost_equal(fftn(plane2), y[1]) + assert_array_almost_equal(fftn(plane3), y[2]) + + y = fftn(x, axes=(1, 2)) # ji_plane + assert_array_almost_equal(fftn(plane1), y[0]) + assert_array_almost_equal(fftn(plane2), y[1]) + assert_array_almost_equal(fftn(plane3), y[2]) + + y = fftn(x, axes=(-3, -2)) # kj_plane + assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0]) + assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1]) + assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2]) + + y = fftn(x, axes=(-3, -1)) # ki_plane + assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :]) + assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :]) + assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :]) + + y = fftn(x, axes=(-1, -2)) # ij_plane + assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1)) + assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1)) + assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1)) + + y = fftn(x, axes=(-1, -3)) # ik_plane + assert_array_almost_equal(fftn(ik_plane1), + swapaxes(y[:, 0, :], -1, -2)) + assert_array_almost_equal(fftn(ik_plane2), + swapaxes(y[:, 1, :], -1, -2)) + assert_array_almost_equal(fftn(ik_plane3), + swapaxes(y[:, 2, :], -1, -2)) + + y = fftn(x, axes=(-2, -3)) # jk_plane + assert_array_almost_equal(fftn(jk_plane1), + swapaxes(y[:, :, 0], -1, -2)) + assert_array_almost_equal(fftn(jk_plane2), + swapaxes(y[:, :, 1], -1, -2)) + assert_array_almost_equal(fftn(jk_plane3), + swapaxes(y[:, :, 2], -1, -2)) + + y = fftn(x, axes=(-1,)) # i_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :]) + y = fftn(x, axes=(-2,)) # j_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j]) + y = fftn(x, axes=(0,)) # k_line + for i in range(3): + for j in range(3): + assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j]) + + y = fftn(x, axes=()) # point + assert_array_almost_equal(y, x) + + def test_shape_argument(self): + small_x = [[1, 2, 3], + [4, 5, 6]] + large_x1 = [[1, 2, 3, 0], + [4, 5, 6, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]] + + y = fftn(small_x, s=(4, 4)) + assert_array_almost_equal(y, fftn(large_x1)) + + y = fftn(small_x, s=(3, 4)) + assert_array_almost_equal(y, fftn(large_x1[:-1])) + + def test_shape_axes_argument(self): + small_x = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + large_x1 = array([[1, 2, 3, 0], + [4, 5, 6, 0], + [7, 8, 9, 0], + [0, 0, 0, 0]]) + y = fftn(small_x, s=(4, 4), axes=(-2, -1)) + assert_array_almost_equal(y, fftn(large_x1)) + y = fftn(small_x, s=(4, 4), axes=(-1, -2)) + + assert_array_almost_equal(y, swapaxes( + fftn(swapaxes(large_x1, -1, -2)), -1, -2)) + + def test_shape_axes_argument2(self): + # Change shape of the last axis + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-1,), s=(8,)) + assert_array_almost_equal(y, fft(x, axis=-1, n=8)) + + # Change shape of an arbitrary axis which is not the last one + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-2,), s=(8,)) + assert_array_almost_equal(y, fft(x, axis=-2, n=8)) + + # Change shape of axes: cf #244, where shape and axes were mixed up + x = numpy.random.random((4, 4, 2)) + y = fftn(x, axes=(-3, -2), s=(8, 8)) + assert_array_almost_equal(y, + numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8))) + + def test_shape_argument_more(self): + x = zeros((4, 4, 2)) + with assert_raises(ValueError, + match="shape requires more axes than are present"): + fftn(x, s=(8, 8, 2, 1)) + + def test_invalid_sizes(self): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + fftn([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + fftn([[1, 1], [2, 2]], (4, -3)) + + def test_no_axes(self): + x = numpy.random.random((2,2,2)) + assert_allclose(fftn(x, axes=[]), x, atol=1e-7) + + def test_regression_244(self): + """FFT returns wrong result with axes parameter.""" + # fftn (and hence fft2) used to break when both axes and shape were used + x = numpy.ones((4, 4, 2)) + y = fftn(x, s=(8, 8), axes=(-3, -2)) + y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2)) + assert_allclose(y, y_r) + + +class TestIfftn: + dtype = None + cdtype = None + + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.parametrize('dtype,cdtype,maxnlp', + [(np.float64, np.complex128, 2000), + (np.float32, np.complex64, 3500)]) + def test_definition(self, dtype, cdtype, maxnlp): + rng = np.random.default_rng(1234) + x = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], dtype=dtype) + y = ifftn(x) + assert_equal(y.dtype, cdtype) + assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp) + + x = rng.random((20, 26)) + assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp) + + x = rng.random((5, 4, 3, 20)) + assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp) + + @pytest.mark.parametrize('maxnlp', [2000, 3500]) + @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92]) + def test_random_complex(self, maxnlp, size): + rng = np.random.default_rng(1234) + x = rng.random([size, size]) + 1j * rng.random([size, size]) + assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp) + assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp) + + def test_invalid_sizes(self): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + ifftn([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + ifftn([[1, 1], [2, 2]], (4, -3)) + + def test_no_axes(self): + x = numpy.random.random((2,2,2)) + assert_allclose(ifftn(x, axes=[]), x, atol=1e-7) + +class TestRfftn: + dtype = None + cdtype = None + + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.parametrize('dtype,cdtype,maxnlp', + [(np.float64, np.complex128, 2000), + (np.float32, np.complex64, 3500)]) + def test_definition(self, dtype, cdtype, maxnlp): + rng = np.random.default_rng(1234) + x = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], dtype=dtype) + y = rfftn(x) + assert_equal(y.dtype, cdtype) + assert_array_almost_equal_nulp(y, direct_rdftn(x), maxnlp) + + x = rng.random((20, 26)) + assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp) + + x = rng.random((5, 4, 3, 20)) + assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp) + + @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92]) + def test_random(self, size): + rng = np.random.default_rng(1234) + x = rng.random([size, size]) + assert_allclose(irfftn(rfftn(x), x.shape), x, atol=1e-10) + + @pytest.mark.parametrize('func', [rfftn, irfftn]) + def test_invalid_sizes(self, func): + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[1, 0\]\) specified"): + func([[]]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[4, -3\]\) specified"): + func([[1, 1], [2, 2]], (4, -3)) + + @pytest.mark.parametrize('func', [rfftn, irfftn]) + def test_no_axes(self, func): + with assert_raises(ValueError, + match="at least 1 axis must be transformed"): + func([], axes=[]) + + def test_complex_input(self): + with assert_raises(TypeError, match="x must be a real sequence"): + rfftn(np.zeros(10, dtype=np.complex64)) + + +class FakeArray: + def __init__(self, data): + self._data = data + self.__array_interface__ = data.__array_interface__ + + +class FakeArray2: + def __init__(self, data): + self._data = data + + def __array__(self, dtype=None, copy=None): + return self._data + +# TODO: Is this test actually valuable? The behavior it's testing shouldn't be +# relied upon by users except for overwrite_x = False +class TestOverwrite: + """Check input overwrite behavior of the FFT functions.""" + + real_dtypes = [np.float32, np.float64, np.longdouble] + dtypes = real_dtypes + [np.complex64, np.complex128, np.clongdouble] + fftsizes = [8, 16, 32] + + def _check(self, x, routine, fftsize, axis, overwrite_x, should_overwrite): + x2 = x.copy() + for fake in [lambda x: x, FakeArray, FakeArray2]: + routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x) + + sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, " + f"axis={axis!r}, overwrite_x={overwrite_x!r})") + if not should_overwrite: + assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}") + + def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes, + fftsize, overwrite_x): + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + data = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + data = np.random.randn(*shape) + data = data.astype(dtype) + + should_overwrite = (overwrite_x + and dtype in overwritable_dtypes + and fftsize <= shape[axis]) + self._check(data, routine, fftsize, axis, + overwrite_x=overwrite_x, + should_overwrite=should_overwrite) + + @pytest.mark.parametrize('dtype', dtypes) + @pytest.mark.parametrize('fftsize', fftsizes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), -1), + ((16, 2), 0), + ((2, 16), 1)]) + def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes): + overwritable = (np.clongdouble, np.complex128, np.complex64) + self._check_1d(fft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + self._check_1d(ifft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + + @pytest.mark.parametrize('dtype', real_dtypes) + @pytest.mark.parametrize('fftsize', fftsizes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), -1), + ((16, 2), 0), + ((2, 16), 1)]) + def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes): + overwritable = self.real_dtypes + self._check_1d(irfft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + self._check_1d(rfft, dtype, shape, axes, overwritable, + fftsize, overwrite_x) + + def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes, + overwrite_x): + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + data = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + data = np.random.randn(*shape) + data = data.astype(dtype) + + def fftshape_iter(shp): + if len(shp) <= 0: + yield () + else: + for j in (shp[0]//2, shp[0], shp[0]*2): + for rest in fftshape_iter(shp[1:]): + yield (j,) + rest + + def part_shape(shape, axes): + if axes is None: + return shape + else: + return tuple(np.take(shape, axes)) + + def should_overwrite(data, shape, axes): + s = part_shape(data.shape, axes) + return (overwrite_x and + np.prod(shape) <= np.prod(s) + and dtype in overwritable_dtypes) + + for fftshape in fftshape_iter(part_shape(shape, axes)): + self._check(data, routine, fftshape, axes, + overwrite_x=overwrite_x, + should_overwrite=should_overwrite(data, fftshape, axes)) + if data.ndim > 1: + # check fortran order + self._check(data.T, routine, fftshape, axes, + overwrite_x=overwrite_x, + should_overwrite=should_overwrite( + data.T, fftshape, axes)) + + @pytest.mark.parametrize('dtype', dtypes) + @pytest.mark.parametrize('overwrite_x', [True, False]) + @pytest.mark.parametrize('shape,axes', [((16,), None), + ((16,), (0,)), + ((16, 2), (0,)), + ((2, 16), (1,)), + ((8, 16), None), + ((8, 16), (0, 1)), + ((8, 16, 2), (0, 1)), + ((8, 16, 2), (1, 2)), + ((8, 16, 2), (0,)), + ((8, 16, 2), (1,)), + ((8, 16, 2), (2,)), + ((8, 16, 2), None), + ((8, 16, 2), (0, 1, 2))]) + def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes): + overwritable = (np.clongdouble, np.complex128, np.complex64) + self._check_nd_one(fftn, dtype, shape, axes, overwritable, + overwrite_x) + self._check_nd_one(ifftn, dtype, shape, axes, overwritable, + overwrite_x) + + +@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn, + rfft, irfft, rfftn, irfftn]) +def test_invalid_norm(func): + x = np.arange(10, dtype=float) + with assert_raises(ValueError, + match='Invalid norm value \'o\', should be' + ' "backward", "ortho" or "forward"'): + func(x, norm='o') + + +@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn, + irfft, irfftn, hfft, hfftn]) +def test_swapped_byte_order_complex(func): + rng = np.random.RandomState(1234) + x = rng.rand(10) + 1j * rng.rand(10) + assert_allclose(func(swap_byteorder(x)), func(x)) + + +@pytest.mark.parametrize('func', [ihfft, ihfftn, rfft, rfftn]) +def test_swapped_byte_order_real(func): + rng = np.random.RandomState(1234) + x = rng.rand(10) + assert_allclose(func(swap_byteorder(x)), func(x)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..38b3f0a7367a9e97a97133f62ddb5dfb223581ed --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py @@ -0,0 +1,505 @@ +from os.path import join, dirname +from collections.abc import Callable +from threading import Lock + +import numpy as np +from numpy.testing import ( + assert_array_almost_equal, assert_equal, assert_allclose) +import pytest +from pytest import raises as assert_raises + +from scipy.fft._pocketfft.realtransforms import ( + dct, idct, dst, idst, dctn, idctn, dstn, idstn) + +fftpack_test_dir = join(dirname(__file__), '..', '..', '..', 'fftpack', 'tests') + +MDATA_COUNT = 8 +FFTWDATA_COUNT = 14 + +def is_longdouble_binary_compatible(): + try: + one = np.frombuffer( + b'\x00\x00\x00\x00\x00\x00\x00\x80\xff\x3f\x00\x00\x00\x00\x00\x00', + dtype=' decimal +dec_map: DecMapType = { + # DCT + (dct, np.float64, 1): 13, + (dct, np.float32, 1): 6, + + (dct, np.float64, 2): 14, + (dct, np.float32, 2): 5, + + (dct, np.float64, 3): 14, + (dct, np.float32, 3): 5, + + (dct, np.float64, 4): 13, + (dct, np.float32, 4): 6, + + # IDCT + (idct, np.float64, 1): 14, + (idct, np.float32, 1): 6, + + (idct, np.float64, 2): 14, + (idct, np.float32, 2): 5, + + (idct, np.float64, 3): 14, + (idct, np.float32, 3): 5, + + (idct, np.float64, 4): 14, + (idct, np.float32, 4): 6, + + # DST + (dst, np.float64, 1): 13, + (dst, np.float32, 1): 6, + + (dst, np.float64, 2): 14, + (dst, np.float32, 2): 6, + + (dst, np.float64, 3): 14, + (dst, np.float32, 3): 7, + + (dst, np.float64, 4): 13, + (dst, np.float32, 4): 5, + + # IDST + (idst, np.float64, 1): 14, + (idst, np.float32, 1): 6, + + (idst, np.float64, 2): 14, + (idst, np.float32, 2): 6, + + (idst, np.float64, 3): 14, + (idst, np.float32, 3): 6, + + (idst, np.float64, 4): 14, + (idst, np.float32, 4): 6, +} + +for k,v in dec_map.copy().items(): + if k[1] == np.float64: + dec_map[(k[0], np.longdouble, k[2])] = v + elif k[1] == np.float32: + dec_map[(k[0], int, k[2])] = v + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +class TestDCT: + def test_definition(self, rdt, type, fftwdata_size, + reference_data, ref_lock): + with ref_lock: + x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data) + y = dct(x, type=type) + assert_equal(y.dtype, dt) + dec = dec_map[(dct, rdt, type)] + assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec)) + + @pytest.mark.parametrize('size', [7, 8, 9, 16, 32, 64]) + def test_axis(self, rdt, type, size): + nt = 2 + dec = dec_map[(dct, rdt, type)] + x = np.random.randn(nt, size) + y = dct(x, type=type) + for j in range(nt): + assert_array_almost_equal(y[j], dct(x[j], type=type), + decimal=dec) + + x = x.T + y = dct(x, axis=0, type=type) + for j in range(nt): + assert_array_almost_equal(y[:,j], dct(x[:,j], type=type), + decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct1_definition_ortho(rdt, mdata_x): + # Test orthornomal mode. + dec = dec_map[(dct, rdt, 1)] + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dct(x, norm='ortho', type=1) + y2 = naive_dct1(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct2_definition_matlab(mdata_xy, rdt): + # Test correspondence with matlab (orthornomal mode). + dt = np.result_type(np.float32, rdt) + x = np.array(mdata_xy[0], dtype=dt) + + yr = mdata_xy[1] + y = dct(x, norm="ortho", type=2) + dec = dec_map[(dct, rdt, 2)] + assert_equal(y.dtype, dt) + assert_array_almost_equal(y, yr, decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct3_definition_ortho(mdata_x, rdt): + # Test orthornomal mode. + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dct(x, norm='ortho', type=2) + xi = dct(y, norm="ortho", type=3) + dec = dec_map[(dct, rdt, 3)] + assert_equal(xi.dtype, dt) + assert_array_almost_equal(xi, x, decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dct4_definition_ortho(mdata_x, rdt): + # Test orthornomal mode. + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dct(x, norm='ortho', type=4) + y2 = naive_dct4(x, norm='ortho') + dec = dec_map[(dct, rdt, 4)] + assert_equal(y.dtype, dt) + assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +def test_idct_definition(fftwdata_size, rdt, type, reference_data, ref_lock): + with ref_lock: + xr, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data) + x = idct(yr, type=type) + dec = dec_map[(idct, rdt, type)] + assert_equal(x.dtype, dt) + assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +def test_definition(fftwdata_size, rdt, type, reference_data, ref_lock): + with ref_lock: + xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data) + y = dst(xr, type=type) + dec = dec_map[(dst, rdt, type)] + assert_equal(y.dtype, dt) + assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dst1_definition_ortho(rdt, mdata_x): + # Test orthornomal mode. + dec = dec_map[(dst, rdt, 1)] + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dst(x, norm='ortho', type=1) + y2 = naive_dst1(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec)) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +def test_dst4_definition_ortho(rdt, mdata_x): + # Test orthornomal mode. + dec = dec_map[(dst, rdt, 4)] + x = np.array(mdata_x, dtype=rdt) + dt = np.result_type(np.float32, rdt) + y = dst(x, norm='ortho', type=4) + y2 = naive_dst4(x, norm='ortho') + assert_equal(y.dtype, dt) + assert_array_almost_equal(y, y2, decimal=dec) + + +@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +def test_idst_definition(fftwdata_size, rdt, type, reference_data, ref_lock): + with ref_lock: + xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data) + x = idst(yr, type=type) + dec = dec_map[(idst, rdt, type)] + assert_equal(x.dtype, dt) + assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec)) + + +@pytest.mark.parametrize('routine', [dct, dst, idct, idst]) +@pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble]) +@pytest.mark.parametrize('shape, axis', [ + ((16,), -1), ((16, 2), 0), ((2, 16), 1) +]) +@pytest.mark.parametrize('type', [1, 2, 3, 4]) +@pytest.mark.parametrize('overwrite_x', [True, False]) +@pytest.mark.parametrize('norm', [None, 'ortho']) +def test_overwrite(routine, dtype, shape, axis, type, norm, overwrite_x): + # Check input overwrite behavior + np.random.seed(1234) + if np.issubdtype(dtype, np.complexfloating): + x = np.random.randn(*shape) + 1j*np.random.randn(*shape) + else: + x = np.random.randn(*shape) + x = x.astype(dtype) + x2 = x.copy() + routine(x2, type, None, axis, norm, overwrite_x=overwrite_x) + + sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {None!r}, axis={axis!r}, " + f"overwrite_x={overwrite_x!r})") + if not overwrite_x: + assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}") + + +class Test_DCTN_IDCTN: + dec = 14 + dct_type = [1, 2, 3, 4] + norms = [None, 'backward', 'ortho', 'forward'] + rstate = np.random.RandomState(1234) + shape = (32, 16) + data = rstate.randn(*shape) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + @pytest.mark.parametrize('axes', [None, + 1, (1,), [1], + 0, (0,), [0], + (0, 1), [0, 1], + (-2, -1), [-2, -1]]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', ['ortho']) + def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm): + tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm) + tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm) + assert_array_almost_equal(self.data, tmp, decimal=12) + + @pytest.mark.parametrize('funcn,func', [(dctn, dct), (dstn, dst)]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', norms) + def test_dctn_vs_2d_reference(self, funcn, func, dct_type, norm): + y1 = funcn(self.data, type=dct_type, axes=None, norm=norm) + y2 = ref_2d(func, self.data, type=dct_type, norm=norm) + assert_array_almost_equal(y1, y2, decimal=11) + + @pytest.mark.parametrize('funcn,func', [(idctn, idct), (idstn, idst)]) + @pytest.mark.parametrize('dct_type', dct_type) + @pytest.mark.parametrize('norm', norms) + def test_idctn_vs_2d_reference(self, funcn, func, dct_type, norm): + fdata = dctn(self.data, type=dct_type, norm=norm) + y1 = funcn(fdata, type=dct_type, norm=norm) + y2 = ref_2d(func, fdata, type=dct_type, norm=norm) + assert_array_almost_equal(y1, y2, decimal=11) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + def test_axes_and_shape(self, fforward, finverse): + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fforward(self.data, s=self.data.shape[0], axes=(0, 1)) + + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + fforward(self.data, s=self.data.shape, axes=0) + + @pytest.mark.parametrize('fforward', [dctn, dstn]) + def test_shape(self, fforward): + tmp = fforward(self.data, s=(128, 128), axes=None) + assert_equal(tmp.shape, (128, 128)) + + @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn), + (dstn, idstn)]) + @pytest.mark.parametrize('axes', [1, (1,), [1], + 0, (0,), [0]]) + def test_shape_is_none_with_axes(self, fforward, finverse, axes): + tmp = fforward(self.data, s=None, axes=axes, norm='ortho') + tmp = finverse(tmp, s=None, axes=axes, norm='ortho') + assert_array_almost_equal(self.data, tmp, decimal=self.dec) + + +@pytest.mark.parametrize('func', [dct, dctn, idct, idctn, + dst, dstn, idst, idstn]) +def test_swapped_byte_order(func): + rng = np.random.RandomState(1234) + x = rng.rand(10) + swapped_dt = x.dtype.newbyteorder('S') + assert_allclose(func(x.astype(swapped_dt)), func(x)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py new file mode 100644 index 0000000000000000000000000000000000000000..1c7a3d683dd78d3227a7de88f5c47569d2f4e17f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py @@ -0,0 +1,693 @@ +from ._basic import _dispatch +from scipy._lib.uarray import Dispatchable +import numpy as np + +__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'] + + +@_dispatch +def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, *, orthogonalize=None): + """ + Return multidimensional Discrete Cosine Transform along the specified axes. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are None, + `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is + ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length + ``s[i]``. + If any element of `s` is -1, the size of the corresponding dimension of + `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the DCT is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized DCT variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + y : ndarray of real + The transformed input array. + + See Also + -------- + idctn : Inverse multidimensional DCT + + Notes + ----- + For full details of the DCT types and normalization modes, as well as + references, see `dct`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.fft import dctn, idctn + >>> rng = np.random.default_rng() + >>> y = rng.standard_normal((16, 16)) + >>> np.allclose(y, idctn(dctn(y))) + True + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, orthogonalize=None): + """ + Return multidimensional Inverse Discrete Cosine Transform along the specified axes. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are + None, `s` is ``x.shape``; if `s` is None but `axes` is + not None, then `s` is ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length + ``s[i]``. + If any element of `s` is -1, the size of the corresponding dimension of + `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the IDCT is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized IDCT variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + y : ndarray of real + The transformed input array. + + See Also + -------- + dctn : multidimensional DCT + + Notes + ----- + For full details of the IDCT types and normalization modes, as well as + references, see `idct`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.fft import dctn, idctn + >>> rng = np.random.default_rng() + >>> y = rng.standard_normal((16, 16)) + >>> np.allclose(y, idctn(dctn(y))) + True + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, orthogonalize=None): + """ + Return multidimensional Discrete Sine Transform along the specified axes. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are None, + `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is + ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length + ``s[i]``. + If any element of `shape` is -1, the size of the corresponding dimension + of `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the DST is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized DST variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + y : ndarray of real + The transformed input array. + + See Also + -------- + idstn : Inverse multidimensional DST + + Notes + ----- + For full details of the DST types and normalization modes, as well as + references, see `dst`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.fft import dstn, idstn + >>> rng = np.random.default_rng() + >>> y = rng.standard_normal((16, 16)) + >>> np.allclose(y, idstn(dstn(y))) + True + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, + workers=None, orthogonalize=None): + """ + Return multidimensional Inverse Discrete Sine Transform along the specified axes. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are None, + `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is + ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length + ``s[i]``. + If any element of `s` is -1, the size of the corresponding dimension of + `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the IDST is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized IDST variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + y : ndarray of real + The transformed input array. + + See Also + -------- + dstn : multidimensional DST + + Notes + ----- + For full details of the IDST types and normalization modes, as well as + references, see `idst`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.fft import dstn, idstn + >>> rng = np.random.default_rng() + >>> y = rng.standard_normal((16, 16)) + >>> np.allclose(y, idstn(dstn(y))) + True + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, + orthogonalize=None): + r"""Return the Discrete Cosine Transform of arbitrary type sequence x. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. + n : int, optional + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The + default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the dct is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized DCT variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + y : ndarray of real + The transformed input array. + + See Also + -------- + idct : Inverse DCT + + Notes + ----- + For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to + MATLAB ``dct(x)``. + + .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct + correspondence with the direct Fourier transform. To recover + it you must specify ``orthogonalize=False``. + + For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same + overall factor in both directions. By default, the transform is also + orthogonalized which for types 1, 2 and 3 means the transform definition is + modified to give orthogonality of the DCT matrix (see below). + + For ``norm="backward"``, there is no scaling on `dct` and the `idct` is + scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For + ``norm="forward"`` the ``1/N`` normalization is applied to the forward + `dct` instead and the `idct` is unnormalized. + + There are, theoretically, 8 types of the DCT, only the first 4 types are + implemented in SciPy.'The' DCT generally refers to DCT type 2, and 'the' + Inverse DCT generally refers to DCT type 3. + + **Type I** + + There are several definitions of the DCT-I; we use the following + (for ``norm="backward"``) + + .. math:: + + y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left( + \frac{\pi k n}{N-1} \right) + + If ``orthogonalize=True``, ``x[0]`` and ``x[N-1]`` are multiplied by a + scaling factor of :math:`\sqrt{2}`, and ``y[0]`` and ``y[N-1]`` are divided + by :math:`\sqrt{2}`. When combined with ``norm="ortho"``, this makes the + corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``). + + .. note:: + The DCT-I is only supported for input size > 1. + + **Type II** + + There are several definitions of the DCT-II; we use the following + (for ``norm="backward"``) + + .. math:: + + y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right) + + If ``orthogonalize=True``, ``y[0]`` is divided by :math:`\sqrt{2}` which, + when combined with ``norm="ortho"``, makes the corresponding matrix of + coefficients orthonormal (``O @ O.T = np.eye(N)``). + + **Type III** + + There are several definitions, we use the following (for + ``norm="backward"``) + + .. math:: + + y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right) + + If ``orthogonalize=True``, ``x[0]`` terms are multiplied by + :math:`\sqrt{2}` which, when combined with ``norm="ortho"``, makes the + corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``). + + The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up + to a factor `2N`. The orthonormalized DCT-III is exactly the inverse of + the orthonormalized DCT-II. + + **Type IV** + + There are several definitions of the DCT-IV; we use the following + (for ``norm="backward"``) + + .. math:: + + y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right) + + ``orthogonalize`` has no effect here, as the DCT-IV matrix is already + orthogonal up to a scale factor of ``2N``. + + References + ---------- + .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J. + Makhoul, `IEEE Transactions on acoustics, speech and signal + processing` vol. 28(1), pp. 27-34, + :doi:`10.1109/TASSP.1980.1163351` (1980). + .. [2] Wikipedia, "Discrete cosine transform", + https://en.wikipedia.org/wiki/Discrete_cosine_transform + + Examples + -------- + The Type 1 DCT is equivalent to the FFT (though faster) for real, + even-symmetrical inputs. The output is also real and even-symmetrical. + Half of the FFT input is used to generate half of the FFT output: + + >>> from scipy.fft import fft, dct + >>> import numpy as np + >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real + array([ 30., -8., 6., -2., 6., -8.]) + >>> dct(np.array([4., 3., 5., 10.]), 1) + array([ 30., -8., 6., -2.]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, orthogonalize=None): + """ + Return the Inverse Discrete Cosine Transform of an arbitrary type sequence. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. + n : int, optional + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The + default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the idct is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized IDCT variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + idct : ndarray of real + The transformed input array. + + See Also + -------- + dct : Forward DCT + + Notes + ----- + For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to + MATLAB ``idct(x)``. + + .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct + correspondence with the inverse direct Fourier transform. To + recover it you must specify ``orthogonalize=False``. + + For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same + overall factor in both directions. By default, the transform is also + orthogonalized which for types 1, 2 and 3 means the transform definition is + modified to give orthogonality of the IDCT matrix (see `dct` for the full + definitions). + + 'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III. + + The IDCT is equivalent to a normal DCT except for the normalization and + type. DCT type 1 and 4 are their own inverse and DCTs 2 and 3 are each + other's inverses. + + Examples + -------- + The Type 1 DCT is equivalent to the DFT for real, even-symmetrical + inputs. The output is also real and even-symmetrical. Half of the IFFT + input is used to generate half of the IFFT output: + + >>> from scipy.fft import ifft, idct + >>> import numpy as np + >>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real + array([ 4., 3., 5., 10., 5., 3.]) + >>> idct(np.array([ 30., -8., 6., -2.]), 1) + array([ 4., 3., 5., 10.]) + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, + orthogonalize=None): + r""" + Return the Discrete Sine Transform of arbitrary type sequence x. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + n : int, optional + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The + default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the dst is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized DST variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + dst : ndarray of reals + The transformed input array. + + See Also + -------- + idst : Inverse DST + + Notes + ----- + .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct + correspondence with the direct Fourier transform. To recover + it you must specify ``orthogonalize=False``. + + For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same + overall factor in both directions. By default, the transform is also + orthogonalized which for types 2 and 3 means the transform definition is + modified to give orthogonality of the DST matrix (see below). + + For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is + scaled by ``1/N`` where ``N`` is the "logical" size of the DST. + + There are, theoretically, 8 types of the DST for different combinations of + even/odd boundary conditions and boundary off sets [1]_, only the first + 4 types are implemented in SciPy. + + **Type I** + + There are several definitions of the DST-I; we use the following for + ``norm="backward"``. DST-I assumes the input is odd around :math:`n=-1` and + :math:`n=N`. + + .. math:: + + y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right) + + Note that the DST-I is only supported for input size > 1. + The (unnormalized) DST-I is its own inverse, up to a factor :math:`2(N+1)`. + The orthonormalized DST-I is exactly its own inverse. + + ``orthogonalize`` has no effect here, as the DST-I matrix is already + orthogonal up to a scale factor of ``2N``. + + **Type II** + + There are several definitions of the DST-II; we use the following for + ``norm="backward"``. DST-II assumes the input is odd around :math:`n=-1/2` and + :math:`n=N-1/2`; the output is odd around :math:`k=-1` and even around :math:`k=N-1` + + .. math:: + + y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right) + + If ``orthogonalize=True``, ``y[-1]`` is divided :math:`\sqrt{2}` which, when + combined with ``norm="ortho"``, makes the corresponding matrix of + coefficients orthonormal (``O @ O.T = np.eye(N)``). + + **Type III** + + There are several definitions of the DST-III, we use the following (for + ``norm="backward"``). DST-III assumes the input is odd around :math:`n=-1` and + even around :math:`n=N-1` + + .. math:: + + y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left( + \frac{\pi(2k+1)(n+1)}{2N}\right) + + If ``orthogonalize=True``, ``x[-1]`` is multiplied by :math:`\sqrt{2}` + which, when combined with ``norm="ortho"``, makes the corresponding matrix + of coefficients orthonormal (``O @ O.T = np.eye(N)``). + + The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up + to a factor :math:`2N`. The orthonormalized DST-III is exactly the inverse of the + orthonormalized DST-II. + + **Type IV** + + There are several definitions of the DST-IV, we use the following (for + ``norm="backward"``). DST-IV assumes the input is odd around :math:`n=-0.5` and + even around :math:`n=N-0.5` + + .. math:: + + y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right) + + ``orthogonalize`` has no effect here, as the DST-IV matrix is already + orthogonal up to a scale factor of ``2N``. + + The (unnormalized) DST-IV is its own inverse, up to a factor :math:`2N`. The + orthonormalized DST-IV is exactly its own inverse. + + References + ---------- + .. [1] Wikipedia, "Discrete sine transform", + https://en.wikipedia.org/wiki/Discrete_sine_transform + + """ + return (Dispatchable(x, np.ndarray),) + + +@_dispatch +def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, + workers=None, orthogonalize=None): + """ + Return the Inverse Discrete Sine Transform of an arbitrary type sequence. + + Parameters + ---------- + x : array_like + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + n : int, optional + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The + default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the idst is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + workers : int, optional + Maximum number of workers to use for parallel computation. If negative, + the value wraps around from ``os.cpu_count()``. + See :func:`~scipy.fft.fft` for more details. + orthogonalize : bool, optional + Whether to use the orthogonalized IDST variant (see Notes). + Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise. + + .. versionadded:: 1.8.0 + + Returns + ------- + idst : ndarray of real + The transformed input array. + + See Also + -------- + dst : Forward DST + + Notes + ----- + .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct + correspondence with the inverse direct Fourier transform. + + For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same + overall factor in both directions. By default, the transform is also + orthogonalized which for types 2 and 3 means the transform definition is + modified to give orthogonality of the DST matrix (see `dst` for the full + definitions). + + 'The' IDST is the IDST-II, which is the same as the normalized DST-III. + + The IDST is equivalent to a normal DST except for the normalization and + type. DST type 1 and 4 are their own inverse and DSTs 2 and 3 are each + other's inverses. + + """ + return (Dispatchable(x, np.ndarray),) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..2042453733bec54860974cc1e20ba908e8c9b94d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py @@ -0,0 +1,63 @@ +from scipy._lib._array_api import array_namespace +import numpy as np +from . import _pocketfft + +__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'] + + +def _execute(pocketfft_func, x, type, s, axes, norm, + overwrite_x, workers, orthogonalize): + xp = array_namespace(x) + x = np.asarray(x) + y = pocketfft_func(x, type, s, axes, norm, + overwrite_x=overwrite_x, workers=workers, + orthogonalize=orthogonalize) + return xp.asarray(y) + + +def dctn(x, type=2, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, orthogonalize=None): + return _execute(_pocketfft.dctn, x, type, s, axes, norm, + overwrite_x, workers, orthogonalize) + + +def idctn(x, type=2, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, orthogonalize=None): + return _execute(_pocketfft.idctn, x, type, s, axes, norm, + overwrite_x, workers, orthogonalize) + + +def dstn(x, type=2, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + return _execute(_pocketfft.dstn, x, type, s, axes, norm, + overwrite_x, workers, orthogonalize) + + +def idstn(x, type=2, s=None, axes=None, norm=None, + overwrite_x=False, workers=None, *, orthogonalize=None): + return _execute(_pocketfft.idstn, x, type, s, axes, norm, + overwrite_x, workers, orthogonalize) + + +def dct(x, type=2, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + return _execute(_pocketfft.dct, x, type, n, axis, norm, + overwrite_x, workers, orthogonalize) + + +def idct(x, type=2, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + return _execute(_pocketfft.idct, x, type, n, axis, norm, + overwrite_x, workers, orthogonalize) + + +def dst(x, type=2, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + return _execute(_pocketfft.dst, x, type, n, axis, norm, + overwrite_x, workers, orthogonalize) + + +def idst(x, type=2, n=None, axis=-1, norm=None, + overwrite_x=False, workers=None, orthogonalize=None): + return _execute(_pocketfft.idst, x, type, n, axis, norm, + overwrite_x, workers, orthogonalize) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..48a7d2b3b50501b84f7c18e366ad2e66782b4ab6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py @@ -0,0 +1,96 @@ +import numpy as np +import scipy.fft +import threading + +class _MockFunction: + def __init__(self, return_value = None): + self.number_calls = threading.local() + self.return_value = return_value + self.last_args = threading.local() + + def __call__(self, *args, **kwargs): + if not hasattr(self.number_calls, 'c'): + self.number_calls.c = 0 + + self.number_calls.c += 1 + self.last_args.l = (args, kwargs) + return self.return_value + + +fft = _MockFunction(np.random.random(10)) +fft2 = _MockFunction(np.random.random(10)) +fftn = _MockFunction(np.random.random(10)) + +ifft = _MockFunction(np.random.random(10)) +ifft2 = _MockFunction(np.random.random(10)) +ifftn = _MockFunction(np.random.random(10)) + +rfft = _MockFunction(np.random.random(10)) +rfft2 = _MockFunction(np.random.random(10)) +rfftn = _MockFunction(np.random.random(10)) + +irfft = _MockFunction(np.random.random(10)) +irfft2 = _MockFunction(np.random.random(10)) +irfftn = _MockFunction(np.random.random(10)) + +hfft = _MockFunction(np.random.random(10)) +hfft2 = _MockFunction(np.random.random(10)) +hfftn = _MockFunction(np.random.random(10)) + +ihfft = _MockFunction(np.random.random(10)) +ihfft2 = _MockFunction(np.random.random(10)) +ihfftn = _MockFunction(np.random.random(10)) + +dct = _MockFunction(np.random.random(10)) +idct = _MockFunction(np.random.random(10)) +dctn = _MockFunction(np.random.random(10)) +idctn = _MockFunction(np.random.random(10)) + +dst = _MockFunction(np.random.random(10)) +idst = _MockFunction(np.random.random(10)) +dstn = _MockFunction(np.random.random(10)) +idstn = _MockFunction(np.random.random(10)) + +fht = _MockFunction(np.random.random(10)) +ifht = _MockFunction(np.random.random(10)) + + +__ua_domain__ = "numpy.scipy.fft" + + +_implements = { + scipy.fft.fft: fft, + scipy.fft.fft2: fft2, + scipy.fft.fftn: fftn, + scipy.fft.ifft: ifft, + scipy.fft.ifft2: ifft2, + scipy.fft.ifftn: ifftn, + scipy.fft.rfft: rfft, + scipy.fft.rfft2: rfft2, + scipy.fft.rfftn: rfftn, + scipy.fft.irfft: irfft, + scipy.fft.irfft2: irfft2, + scipy.fft.irfftn: irfftn, + scipy.fft.hfft: hfft, + scipy.fft.hfft2: hfft2, + scipy.fft.hfftn: hfftn, + scipy.fft.ihfft: ihfft, + scipy.fft.ihfft2: ihfft2, + scipy.fft.ihfftn: ihfftn, + scipy.fft.dct: dct, + scipy.fft.idct: idct, + scipy.fft.dctn: dctn, + scipy.fft.idctn: idctn, + scipy.fft.dst: dst, + scipy.fft.idst: idst, + scipy.fft.dstn: dstn, + scipy.fft.idstn: idstn, + scipy.fft.fht: fht, + scipy.fft.ifht: ifht +} + + +def __ua_function__(method, args, kwargs): + fn = _implements.get(method) + return (fn(*args, **kwargs) if fn is not None + else NotImplemented) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..933e9c0302d46faf33b3dc015d58996e3e46c058 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py @@ -0,0 +1,98 @@ +from functools import partial + +import numpy as np +import scipy.fft +from scipy.fft import _fftlog, _pocketfft, set_backend +from scipy.fft.tests import mock_backend + +from numpy.testing import assert_allclose, assert_equal +import pytest + +fnames = ('fft', 'fft2', 'fftn', + 'ifft', 'ifft2', 'ifftn', + 'rfft', 'rfft2', 'rfftn', + 'irfft', 'irfft2', 'irfftn', + 'dct', 'idct', 'dctn', 'idctn', + 'dst', 'idst', 'dstn', 'idstn', + 'fht', 'ifht') + +np_funcs = (np.fft.fft, np.fft.fft2, np.fft.fftn, + np.fft.ifft, np.fft.ifft2, np.fft.ifftn, + np.fft.rfft, np.fft.rfft2, np.fft.rfftn, + np.fft.irfft, np.fft.irfft2, np.fft.irfftn, + np.fft.hfft, _pocketfft.hfft2, _pocketfft.hfftn, # np has no hfftn + np.fft.ihfft, _pocketfft.ihfft2, _pocketfft.ihfftn, + _pocketfft.dct, _pocketfft.idct, _pocketfft.dctn, _pocketfft.idctn, + _pocketfft.dst, _pocketfft.idst, _pocketfft.dstn, _pocketfft.idstn, + # must provide required kwargs for fht, ifht + partial(_fftlog.fht, dln=2, mu=0.5), + partial(_fftlog.ifht, dln=2, mu=0.5)) + +funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn, + scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn, + scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn, + scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn, + scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn, + scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn, + scipy.fft.dct, scipy.fft.idct, scipy.fft.dctn, scipy.fft.idctn, + scipy.fft.dst, scipy.fft.idst, scipy.fft.dstn, scipy.fft.idstn, + # must provide required kwargs for fht, ifht + partial(scipy.fft.fht, dln=2, mu=0.5), + partial(scipy.fft.ifht, dln=2, mu=0.5)) + +mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn, + mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn, + mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn, + mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn, + mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn, + mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn, + mock_backend.dct, mock_backend.idct, + mock_backend.dctn, mock_backend.idctn, + mock_backend.dst, mock_backend.idst, + mock_backend.dstn, mock_backend.idstn, + mock_backend.fht, mock_backend.ifht) + + +@pytest.mark.parametrize("func, np_func, mock", zip(funcs, np_funcs, mocks)) +def test_backend_call(func, np_func, mock): + x = np.arange(20).reshape((10,2)) + answer = np_func(x.astype(np.float64)) + assert_allclose(func(x), answer, atol=1e-10) + + with set_backend(mock_backend, only=True): + mock.number_calls.c = 0 + y = func(x) + assert_equal(y, mock.return_value) + assert_equal(mock.number_calls.c, 1) + + assert_allclose(func(x), answer, atol=1e-10) + + +plan_funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn, + scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn, + scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn, + scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn, + scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn, + scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn) + +plan_mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn, + mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn, + mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn, + mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn, + mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn, + mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn) + + +@pytest.mark.parametrize("func, mock", zip(plan_funcs, plan_mocks)) +def test_backend_plan(func, mock): + x = np.arange(20).reshape((10, 2)) + + with pytest.raises(NotImplementedError, match='precomputed plan'): + func(x, plan='foo') + + with set_backend(mock_backend, only=True): + mock.number_calls.c = 0 + y = func(x, plan='foo') + assert_equal(y, mock.return_value) + assert_equal(mock.number_calls.c, 1) + assert_equal(mock.last_args.l[1]['plan'], 'foo') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..4ed32d54c8936b8b36ff52ef7b639d05338a783c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py @@ -0,0 +1,502 @@ +import queue +import threading +import multiprocessing +import numpy as np +import pytest +from numpy.random import random +from numpy.testing import assert_array_almost_equal, assert_allclose +from pytest import raises as assert_raises +import scipy.fft as fft +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import ( + array_namespace, xp_size, xp_assert_close, xp_assert_equal +) + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + + +# Expected input dtypes. Note that `scipy.fft` is more flexible for numpy, +# but for C2C transforms like `fft.fft`, the array API standard only mandates +# that complex dtypes should work, float32/float64 aren't guaranteed to. +def get_expected_input_dtype(func, xp): + if func in [fft.fft, fft.fftn, fft.fft2, + fft.ifft, fft.ifftn, fft.ifft2, + fft.hfft, fft.hfftn, fft.hfft2, + fft.irfft, fft.irfftn, fft.irfft2]: + dtype = xp.complex128 + elif func in [fft.rfft, fft.rfftn, fft.rfft2, + fft.ihfft, fft.ihfftn, fft.ihfft2]: + dtype = xp.float64 + else: + raise ValueError(f'Unknown FFT function: {func}') + + return dtype + + +def fft1(x): + L = len(x) + phase = -2j*np.pi*(np.arange(L)/float(L)) + phase = np.arange(L).reshape(-1, 1) * phase + return np.sum(x*np.exp(phase), axis=1) + +class TestFFT: + + def test_identity(self, xp): + maxlen = 512 + x = xp.asarray(random(maxlen) + 1j*random(maxlen)) + xr = xp.asarray(random(maxlen)) + # Check some powers of 2 and some primes + for i in [1, 2, 16, 128, 512, 53, 149, 281, 397]: + xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i]) + xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i]) + + @skip_xp_backends(np_only=True, reason='significant overhead for some backends') + def test_identity_extensive(self, xp): + maxlen = 512 + x = xp.asarray(random(maxlen) + 1j*random(maxlen)) + xr = xp.asarray(random(maxlen)) + for i in range(1, maxlen): + xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i]) + xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i]) + + def test_fft(self, xp): + x = random(30) + 1j*random(30) + expect = xp.asarray(fft1(x)) + x = xp.asarray(x) + xp_assert_close(fft.fft(x), expect) + xp_assert_close(fft.fft(x, norm="backward"), expect) + xp_assert_close(fft.fft(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)),) + xp_assert_close(fft.fft(x, norm="forward"), expect / 30) + + @skip_xp_backends(np_only=True, reason='some backends allow `n=0`') + def test_fft_n(self, xp): + x = xp.asarray([1, 2, 3], dtype=xp.complex128) + assert_raises(ValueError, fft.fft, x, 0) + + def test_ifft(self, xp): + x = xp.asarray(random(30) + 1j*random(30)) + xp_assert_close(fft.ifft(fft.fft(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.ifft(fft.fft(x, norm=norm), norm=norm), x) + + def test_fft2(self, xp): + x = xp.asarray(random((30, 20)) + 1j*random((30, 20))) + expect = fft.fft(fft.fft(x, axis=1), axis=0) + xp_assert_close(fft.fft2(x), expect) + xp_assert_close(fft.fft2(x, norm="backward"), expect) + xp_assert_close(fft.fft2(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))) + xp_assert_close(fft.fft2(x, norm="forward"), expect / (30 * 20)) + + def test_ifft2(self, xp): + x = xp.asarray(random((30, 20)) + 1j*random((30, 20))) + expect = fft.ifft(fft.ifft(x, axis=1), axis=0) + xp_assert_close(fft.ifft2(x), expect) + xp_assert_close(fft.ifft2(x, norm="backward"), expect) + xp_assert_close(fft.ifft2(x, norm="ortho"), + expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))) + xp_assert_close(fft.ifft2(x, norm="forward"), expect * (30 * 20)) + + def test_fftn(self, xp): + x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10))) + expect = fft.fft(fft.fft(fft.fft(x, axis=2), axis=1), axis=0) + xp_assert_close(fft.fftn(x), expect) + xp_assert_close(fft.fftn(x, norm="backward"), expect) + xp_assert_close(fft.fftn(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))) + xp_assert_close(fft.fftn(x, norm="forward"), expect / (30 * 20 * 10)) + + def test_ifftn(self, xp): + x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10))) + expect = fft.ifft(fft.ifft(fft.ifft(x, axis=2), axis=1), axis=0) + xp_assert_close(fft.ifftn(x), expect, rtol=1e-7) + xp_assert_close(fft.ifftn(x, norm="backward"), expect, rtol=1e-7) + xp_assert_close( + fft.ifftn(x, norm="ortho"), + fft.ifftn(x) * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)) + ) + xp_assert_close(fft.ifftn(x, norm="forward"), + expect * (30 * 20 * 10), + rtol=1e-7) + + def test_rfft(self, xp): + x = xp.asarray(random(29), dtype=xp.float64) + for n in [xp_size(x), 2*xp_size(x)]: + for norm in [None, "backward", "ortho", "forward"]: + xp_assert_close(fft.rfft(x, n=n, norm=norm), + fft.fft(xp.asarray(x, dtype=xp.complex128), + n=n, norm=norm)[:(n//2 + 1)]) + xp_assert_close( + fft.rfft(x, n=n, norm="ortho"), + fft.rfft(x, n=n) / xp.sqrt(xp.asarray(n, dtype=xp.float64)) + ) + + def test_irfft(self, xp): + x = xp.asarray(random(30)) + xp_assert_close(fft.irfft(fft.rfft(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.irfft(fft.rfft(x, norm=norm), norm=norm), x) + + def test_rfft2(self, xp): + x = xp.asarray(random((30, 20)), dtype=xp.float64) + expect = fft.fft2(xp.asarray(x, dtype=xp.complex128))[:, :11] + xp_assert_close(fft.rfft2(x), expect) + xp_assert_close(fft.rfft2(x, norm="backward"), expect) + xp_assert_close(fft.rfft2(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))) + xp_assert_close(fft.rfft2(x, norm="forward"), expect / (30 * 20)) + + def test_irfft2(self, xp): + x = xp.asarray(random((30, 20))) + xp_assert_close(fft.irfft2(fft.rfft2(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.irfft2(fft.rfft2(x, norm=norm), norm=norm), x) + + def test_rfftn(self, xp): + x = xp.asarray(random((30, 20, 10)), dtype=xp.float64) + expect = fft.fftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6] + xp_assert_close(fft.rfftn(x), expect) + xp_assert_close(fft.rfftn(x, norm="backward"), expect) + xp_assert_close(fft.rfftn(x, norm="ortho"), + expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))) + xp_assert_close(fft.rfftn(x, norm="forward"), expect / (30 * 20 * 10)) + + def test_irfftn(self, xp): + x = xp.asarray(random((30, 20, 10))) + xp_assert_close(fft.irfftn(fft.rfftn(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.irfftn(fft.rfftn(x, norm=norm), norm=norm), x) + + def test_hfft(self, xp): + x = random(14) + 1j*random(14) + x_herm = np.concatenate((random(1), x, random(1))) + x = np.concatenate((x_herm, x[::-1].conj())) + x = xp.asarray(x) + x_herm = xp.asarray(x_herm) + expect = xp.real(fft.fft(x)) + xp_assert_close(fft.hfft(x_herm), expect) + xp_assert_close(fft.hfft(x_herm, norm="backward"), expect) + xp_assert_close(fft.hfft(x_herm, norm="ortho"), + expect / xp.sqrt(xp.asarray(30, dtype=xp.float64))) + xp_assert_close(fft.hfft(x_herm, norm="forward"), expect / 30) + + def test_ihfft(self, xp): + x = random(14) + 1j*random(14) + x_herm = np.concatenate((random(1), x, random(1))) + x = np.concatenate((x_herm, x[::-1].conj())) + x = xp.asarray(x) + x_herm = xp.asarray(x_herm) + xp_assert_close(fft.ihfft(fft.hfft(x_herm)), x_herm) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.ihfft(fft.hfft(x_herm, norm=norm), norm=norm), x_herm) + + def test_hfft2(self, xp): + x = xp.asarray(random((30, 20))) + xp_assert_close(fft.hfft2(fft.ihfft2(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.hfft2(fft.ihfft2(x, norm=norm), norm=norm), x) + + def test_ihfft2(self, xp): + x = xp.asarray(random((30, 20)), dtype=xp.float64) + expect = fft.ifft2(xp.asarray(x, dtype=xp.complex128))[:, :11] + xp_assert_close(fft.ihfft2(x), expect) + xp_assert_close(fft.ihfft2(x, norm="backward"), expect) + xp_assert_close( + fft.ihfft2(x, norm="ortho"), + expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)) + ) + xp_assert_close(fft.ihfft2(x, norm="forward"), expect * (30 * 20)) + + def test_hfftn(self, xp): + x = xp.asarray(random((30, 20, 10))) + xp_assert_close(fft.hfftn(fft.ihfftn(x)), x) + for norm in ["backward", "ortho", "forward"]: + xp_assert_close(fft.hfftn(fft.ihfftn(x, norm=norm), norm=norm), x) + + def test_ihfftn(self, xp): + x = xp.asarray(random((30, 20, 10)), dtype=xp.float64) + expect = fft.ifftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6] + xp_assert_close(expect, fft.ihfftn(x)) + xp_assert_close(expect, fft.ihfftn(x, norm="backward")) + xp_assert_close( + fft.ihfftn(x, norm="ortho"), + expect * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)) + ) + xp_assert_close(fft.ihfftn(x, norm="forward"), expect * (30 * 20 * 10)) + + def _check_axes(self, op, xp): + dtype = get_expected_input_dtype(op, xp) + x = xp.asarray(random((30, 20, 10)), dtype=dtype) + axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] + xp_test = array_namespace(x) + for a in axes: + op_tr = op(xp_test.permute_dims(x, axes=a)) + tr_op = xp_test.permute_dims(op(x, axes=a), axes=a) + xp_assert_close(op_tr, tr_op) + + @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn, fft.rfftn, fft.irfftn]) + def test_axes_standard(self, op, xp): + self._check_axes(op, xp) + + @pytest.mark.parametrize("op", [fft.hfftn, fft.ihfftn]) + def test_axes_non_standard(self, op, xp): + self._check_axes(op, xp) + + @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn, + fft.rfftn, fft.irfftn]) + def test_axes_subset_with_shape_standard(self, op, xp): + dtype = get_expected_input_dtype(op, xp) + x = xp.asarray(random((16, 8, 4)), dtype=dtype) + axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)] + xp_test = array_namespace(x) + for a in axes: + # different shape on the first two axes + shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax] + for ax in range(x.ndim)]) + # transform only the first two axes + op_tr = op(xp_test.permute_dims(x, axes=a), + s=shape[:2], axes=(0, 1)) + tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]), + axes=a) + xp_assert_close(op_tr, tr_op) + + @pytest.mark.parametrize("op", [fft.fft2, fft.ifft2, + fft.rfft2, fft.irfft2, + fft.hfft2, fft.ihfft2, + fft.hfftn, fft.ihfftn]) + def test_axes_subset_with_shape_non_standard(self, op, xp): + dtype = get_expected_input_dtype(op, xp) + x = xp.asarray(random((16, 8, 4)), dtype=dtype) + axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)] + xp_test = array_namespace(x) + for a in axes: + # different shape on the first two axes + shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax] + for ax in range(x.ndim)]) + # transform only the first two axes + op_tr = op(xp_test.permute_dims(x, axes=a), s=shape[:2], axes=(0, 1)) + tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]), axes=a) + xp_assert_close(op_tr, tr_op) + + def test_all_1d_norm_preserving(self, xp): + # verify that round-trip transforms are norm-preserving + x = xp.asarray(random(30), dtype=xp.float64) + xp_test = array_namespace(x) + x_norm = xp_test.linalg.vector_norm(x) + n = xp_size(x) * 2 + func_pairs = [(fft.rfft, fft.irfft), + # hfft: order so the first function takes x.size samples + # (necessary for comparison to x_norm above) + (fft.ihfft, fft.hfft), + # functions that expect complex dtypes at the end + (fft.fft, fft.ifft), + ] + for forw, back in func_pairs: + if forw == fft.fft: + x = xp.asarray(x, dtype=xp.complex128) + x_norm = xp_test.linalg.vector_norm(x) + for n in [xp_size(x), 2*xp_size(x)]: + for norm in ['backward', 'ortho', 'forward']: + tmp = forw(x, n=n, norm=norm) + tmp = back(tmp, n=n, norm=norm) + xp_assert_close(xp_test.linalg.vector_norm(tmp), x_norm) + + @skip_xp_backends(np_only=True) + @pytest.mark.parametrize("dtype", [np.float16, np.longdouble]) + def test_dtypes_nonstandard(self, dtype): + x = random(30).astype(dtype) + out_dtypes = {np.float16: np.complex64, np.longdouble: np.clongdouble} + x_complex = x.astype(out_dtypes[dtype]) + + res_fft = fft.ifft(fft.fft(x)) + res_rfft = fft.irfft(fft.rfft(x)) + res_hfft = fft.hfft(fft.ihfft(x), x.shape[0]) + # Check both numerical results and exact dtype matches + assert_array_almost_equal(res_fft, x_complex) + assert_array_almost_equal(res_rfft, x) + assert_array_almost_equal(res_hfft, x) + assert res_fft.dtype == x_complex.dtype + assert res_rfft.dtype == np.result_type(np.float32, x.dtype) + assert res_hfft.dtype == np.result_type(np.float32, x.dtype) + + @pytest.mark.parametrize("dtype", ["float32", "float64"]) + def test_dtypes_real(self, dtype, xp): + x = xp.asarray(random(30), dtype=getattr(xp, dtype)) + + res_rfft = fft.irfft(fft.rfft(x)) + res_hfft = fft.hfft(fft.ihfft(x), x.shape[0]) + # Check both numerical results and exact dtype matches + xp_assert_close(res_rfft, x) + xp_assert_close(res_hfft, x) + + @pytest.mark.parametrize("dtype", ["complex64", "complex128"]) + def test_dtypes_complex(self, dtype, xp): + rng = np.random.default_rng(1234) + x = xp.asarray(rng.random(30), dtype=getattr(xp, dtype)) + + res_fft = fft.ifft(fft.fft(x)) + # Check both numerical results and exact dtype matches + xp_assert_close(res_fft, x) + + @skip_xp_backends(np_only=True, + reason='array-likes only supported for NumPy backend') + @pytest.mark.parametrize("op", [fft.fft, fft.ifft, + fft.fft2, fft.ifft2, + fft.fftn, fft.ifftn, + fft.rfft, fft.irfft, + fft.rfft2, fft.irfft2, + fft.rfftn, fft.irfftn, + fft.hfft, fft.ihfft, + fft.hfft2, fft.ihfft2, + fft.hfftn, fft.ihfftn,]) + def test_array_like(self, xp, op): + x = [[[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]]] + xp_assert_close(op(x), op(xp.asarray(x))) + + +@skip_xp_backends(np_only=True) +@pytest.mark.parametrize( + "dtype", + [np.float32, np.float64, np.longdouble, + np.complex64, np.complex128, np.clongdouble]) +@pytest.mark.parametrize("order", ["F", 'non-contiguous']) +@pytest.mark.parametrize( + "fft", + [fft.fft, fft.fft2, fft.fftn, + fft.ifft, fft.ifft2, fft.ifftn]) +def test_fft_with_order(dtype, order, fft): + # Check that FFT/IFFT produces identical results for C, Fortran and + # non contiguous arrays + rng = np.random.RandomState(42) + X = rng.rand(8, 7, 13).astype(dtype, copy=False) + if order == 'F': + Y = np.asfortranarray(X) + else: + # Make a non contiguous array + Y = X[::-1] + X = np.ascontiguousarray(X[::-1]) + + if fft.__name__.endswith('fft'): + for axis in range(3): + X_res = fft(X, axis=axis) + Y_res = fft(Y, axis=axis) + assert_array_almost_equal(X_res, Y_res) + elif fft.__name__.endswith(('fft2', 'fftn')): + axes = [(0, 1), (1, 2), (0, 2)] + if fft.__name__.endswith('fftn'): + axes.extend([(0,), (1,), (2,), None]) + for ax in axes: + X_res = fft(X, axes=ax) + Y_res = fft(Y, axes=ax) + assert_array_almost_equal(X_res, Y_res) + else: + raise ValueError + + +@skip_xp_backends(cpu_only=True) +class TestFFTThreadSafe: + threads = 16 + input_shape = (800, 200) + + def _test_mtsame(self, func, *args, xp=None): + def worker(args, q): + q.put(func(*args)) + + q = queue.Queue() + expected = func(*args) + + # Spin off a bunch of threads to call the same function simultaneously + t = [threading.Thread(target=worker, args=(args, q)) + for i in range(self.threads)] + [x.start() for x in t] + + [x.join() for x in t] + + # Make sure all threads returned the correct value + for i in range(self.threads): + xp_assert_equal( + q.get(timeout=5), expected, + err_msg='Function returned wrong value in multithreaded context' + ) + + def test_fft(self, xp): + a = xp.ones(self.input_shape, dtype=xp.complex128) + self._test_mtsame(fft.fft, a, xp=xp) + + def test_ifft(self, xp): + a = xp.full(self.input_shape, 1+0j) + self._test_mtsame(fft.ifft, a, xp=xp) + + def test_rfft(self, xp): + a = xp.ones(self.input_shape) + self._test_mtsame(fft.rfft, a, xp=xp) + + def test_irfft(self, xp): + a = xp.full(self.input_shape, 1+0j) + self._test_mtsame(fft.irfft, a, xp=xp) + + def test_hfft(self, xp): + a = xp.ones(self.input_shape, dtype=xp.complex64) + self._test_mtsame(fft.hfft, a, xp=xp) + + def test_ihfft(self, xp): + a = xp.ones(self.input_shape) + self._test_mtsame(fft.ihfft, a, xp=xp) + + +@skip_xp_backends(np_only=True) +@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft]) +def test_multiprocess(func): + # Test that fft still works after fork (gh-10422) + + with multiprocessing.Pool(2) as p: + res = p.map(func, [np.ones(100) for _ in range(4)]) + + expect = func(np.ones(100)) + for x in res: + assert_allclose(x, expect) + + +class TestIRFFTN: + + def test_not_last_axis_success(self, xp): + ar, ai = np.random.random((2, 16, 8, 32)) + a = ar + 1j*ai + a = xp.asarray(a) + + axes = (-2,) + + # Should not raise error + fft.irfftn(a, axes=axes) + + +@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft, + fft.fftn, fft.ifftn, + fft.rfftn, fft.irfftn, fft.hfft, fft.ihfft]) +def test_non_standard_params(func, xp): + if func in [fft.rfft, fft.rfftn, fft.ihfft]: + dtype = xp.float64 + else: + dtype = xp.complex128 + + if xp.__name__ != 'numpy': + x = xp.asarray([1, 2, 3], dtype=dtype) + # func(x) should not raise an exception + func(x) + assert_raises(ValueError, func, x, workers=2) + # `plan` param is not tested since SciPy does not use it currently + # but should be tested if it comes into use + + +@pytest.mark.parametrize("dtype", ['float32', 'float64']) +@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.irfft, + fft.fftn, fft.ifftn, + fft.irfftn, fft.hfft,]) +def test_real_input(func, dtype, xp): + x = xp.asarray([1, 2, 3], dtype=getattr(xp, dtype)) + # func(x) should not raise an exception + func(x) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py new file mode 100644 index 0000000000000000000000000000000000000000..3480e165180baf3866ca7c99a313996a2dbbca49 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py @@ -0,0 +1,206 @@ +import warnings +import math + +import numpy as np +import pytest + +from scipy.fft._fftlog import fht, ifht, fhtoffset +from scipy.special import poch + +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import xp_assert_close, xp_assert_less, array_namespace + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),] +skip_xp_backends = pytest.mark.skip_xp_backends + + +def test_fht_agrees_with_fftlog(xp): + # check that fht numerically agrees with the output from Fortran FFTLog, + # the results were generated with the provided `fftlogtest` program, + # after fixing how the k array is generated (divide range by n-1, not n) + + # test function, analytical Hankel transform is of the same form + def f(r, mu): + return r**(mu+1)*np.exp(-r**2/2) + + r = np.logspace(-4, 4, 16) + + dln = np.log(r[1]/r[0]) + mu = 0.3 + offset = 0.0 + bias = 0.0 + + a = xp.asarray(f(r, mu)) + + # test 1: compute as given + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02, + -0.1949518286432330E-02, +0.3789220182554077E-02, + +0.5093959119952945E-03, +0.2785387803618774E-01, + +0.9944952700848897E-01, +0.4599202164586588E+00, + +0.3157462160881342E+00, -0.8201236844404755E-03, + -0.7834031308271878E-03, +0.3931444945110708E-03, + -0.2697710625194777E-03, +0.3568398050238820E-03, + -0.5554454827797206E-03, +0.8286331026468585E-03] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + # test 2: change to optimal offset + offset = fhtoffset(dln, mu, bias=bias) + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05, + +0.3150140927838524E-03, +0.9149121960963704E-03, + +0.5808089753959363E-02, +0.2548065256377240E-01, + +0.1339477692089897E+00, +0.4821530509479356E+00, + +0.2659899781579785E+00, -0.1116475278448113E-01, + +0.1791441617592385E-02, -0.4181810476548056E-03, + +0.1314963536765343E-03, -0.5422057743066297E-04, + +0.3208681804170443E-04, -0.2696849476008234E-04] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + # test 3: positive bias + bias = 0.8 + offset = fhtoffset(dln, mu, bias=bias) + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00, + +0.1065374386206564E+00, -0.5121739602708132E-01, + +0.2636649319269470E-01, +0.1697209218849693E-01, + +0.1250215614723183E+00, +0.4739583261486729E+00, + +0.2841149874912028E+00, -0.8312764741645729E-02, + +0.1024233505508988E-02, -0.1644902767389120E-03, + +0.3305775476926270E-04, -0.7786993194882709E-05, + +0.1962258449520547E-05, -0.8977895734909250E-06] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + # test 4: negative bias + bias = -0.8 + offset = fhtoffset(dln, mu, bias=bias) + ours = fht(a, dln, mu, offset=offset, bias=bias) + theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04, + +0.2123969254700955E-03, +0.1009558244834628E-02, + +0.5131386375222176E-02, +0.2461678673516286E-01, + +0.1235812845384476E+00, +0.4719570096404403E+00, + +0.2893487490631317E+00, -0.1686570611318716E-01, + +0.2231398155172505E-01, -0.1480742256379873E-01, + +0.1692387813500801E+00, +0.3097490354365797E+00, + +2.7593607182401860E+00, 10.5251075070045800E+00] + theirs = xp.asarray(theirs, dtype=xp.float64) + xp_assert_close(ours, theirs) + + +@pytest.mark.parametrize('optimal', [True, False]) +@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0]) +@pytest.mark.parametrize('bias', [0, 0.1, -0.1]) +@pytest.mark.parametrize('n', [64, 63]) +def test_fht_identity(n, bias, offset, optimal, xp): + rng = np.random.RandomState(3491349965) + + a = xp.asarray(rng.standard_normal(n)) + dln = rng.uniform(-1, 1) + mu = rng.uniform(-2, 2) + + if optimal: + offset = fhtoffset(dln, mu, initial=offset, bias=bias) + + A = fht(a, dln, mu, offset=offset, bias=bias) + a_ = ifht(A, dln, mu, offset=offset, bias=bias) + + xp_assert_close(a_, a, rtol=1.5e-7) + + + + +@pytest.mark.thread_unsafe +def test_fht_special_cases(xp): + rng = np.random.RandomState(3491349965) + + a = xp.asarray(rng.standard_normal(64)) + dln = rng.uniform(-1, 1) + + # let x = (mu+1+q)/2, y = (mu+1-q)/2, M = {0, -1, -2, ...} + + # case 1: x in M, y in M => well-defined transform + mu, bias = -4.0, 1.0 + with warnings.catch_warnings(record=True) as record: + fht(a, dln, mu, bias=bias) + assert not record, 'fht warned about a well-defined transform' + + # case 2: x not in M, y in M => well-defined transform + mu, bias = -2.5, 0.5 + with warnings.catch_warnings(record=True) as record: + fht(a, dln, mu, bias=bias) + assert not record, 'fht warned about a well-defined transform' + + # with fht_lock: + # case 3: x in M, y not in M => singular transform + mu, bias = -3.5, 0.5 + with pytest.warns(Warning) as record: + fht(a, dln, mu, bias=bias) + assert record, 'fht did not warn about a singular transform' + + # with fht_lock: + # case 4: x not in M, y in M => singular inverse transform + mu, bias = -2.5, 0.5 + with pytest.warns(Warning) as record: + ifht(a, dln, mu, bias=bias) + assert record, 'ifht did not warn about a singular transform' + + +@pytest.mark.parametrize('n', [64, 63]) +def test_fht_exact(n, xp): + rng = np.random.RandomState(3491349965) + + # for a(r) a power law r^\gamma, the fast Hankel transform produces the + # exact continuous Hankel transform if biased with q = \gamma + + mu = rng.uniform(0, 3) + + # convergence of HT: -1-mu < gamma < 1/2 + gamma = rng.uniform(-1-mu, 1/2) + + r = np.logspace(-2, 2, n) + a = xp.asarray(r**gamma) + + dln = np.log(r[1]/r[0]) + + offset = fhtoffset(dln, mu, initial=0.0, bias=gamma) + + A = fht(a, dln, mu, offset=offset, bias=gamma) + + k = np.exp(offset)/r[::-1] + + # analytical result + At = xp.asarray((2/k)**gamma * poch((mu+1-gamma)/2, gamma)) + + xp_assert_close(A, At) + +@skip_xp_backends(np_only=True, + reason='array-likes only supported for NumPy backend') +@pytest.mark.parametrize("op", [fht, ifht]) +def test_array_like(xp, op): + x = [[[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]]] + xp_assert_close(op(x, 1.0, 2.0), op(xp.asarray(x), 1.0, 2.0)) + +@pytest.mark.parametrize('n', [128, 129]) +def test_gh_21661(xp, n): + one = xp.asarray(1.0) + xp_test = array_namespace(one) + mu = 0.0 + r = np.logspace(-7, 1, n) + dln = math.log(r[1] / r[0]) + offset = fhtoffset(dln, initial=-6 * np.log(10), mu=mu) + r = xp.asarray(r, dtype=one.dtype) + k = math.exp(offset) / xp_test.flip(r, axis=-1) + + def f(x, mu): + return x**(mu + 1)*xp.exp(-x**2/2) + + a_r = f(r, mu) + fht_val = fht(a_r, dln, mu=mu, offset=offset) + a_k = f(k, mu) + rel_err = xp.max(xp.abs((fht_val - a_k) / a_k)) + xp_assert_less(rel_err, xp.asarray(7.28e+16)[()]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..4333886555ffbbb0831f830456a3290f32e317fa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py @@ -0,0 +1,574 @@ +"""Includes test functions for fftpack.helper module + +Copied from fftpack.helper by Pearu Peterson, October 2005 +Modified for Array API, 2023 + +""" +from scipy.fft._helper import next_fast_len, prev_fast_len, _init_nd_shape_and_axes +from numpy.testing import assert_equal +from pytest import raises as assert_raises +import pytest +import numpy as np +import sys +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import ( + xp_assert_close, get_xp_devices, xp_device, array_namespace +) +from scipy import fft + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + +_5_smooth_numbers = [ + 2, 3, 4, 5, 6, 8, 9, 10, + 2 * 3 * 5, + 2**3 * 3**5, + 2**3 * 3**3 * 5**2, +] + +def test_next_fast_len(): + for n in _5_smooth_numbers: + assert_equal(next_fast_len(n), n) + + +def _assert_n_smooth(x, n): + x_orig = x + if n < 2: + assert False + + while True: + q, r = divmod(x, 2) + if r != 0: + break + x = q + + for d in range(3, n+1, 2): + while True: + q, r = divmod(x, d) + if r != 0: + break + x = q + + assert x == 1, \ + f'x={x_orig} is not {n}-smooth, remainder={x}' + + +@skip_xp_backends(np_only=True) +class TestNextFastLen: + + def test_next_fast_len(self): + np.random.seed(1234) + + def nums(): + yield from range(1, 1000) + yield 2**5 * 3**5 * 4**5 + 1 + + for n in nums(): + m = next_fast_len(n) + _assert_n_smooth(m, 11) + assert m == next_fast_len(n, False) + + m = next_fast_len(n, True) + _assert_n_smooth(m, 5) + + def test_np_integers(self): + ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, np.uint64] + for ityp in ITYPES: + x = ityp(12345) + testN = next_fast_len(x) + assert_equal(testN, next_fast_len(int(x))) + + def testnext_fast_len_small(self): + hams = { + 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8, 8: 8, 14: 15, 15: 15, + 16: 16, 17: 18, 1021: 1024, 1536: 1536, 51200000: 51200000 + } + for x, y in hams.items(): + assert_equal(next_fast_len(x, True), y) + + @pytest.mark.xfail(sys.maxsize < 2**32, + reason="Hamming Numbers too large for 32-bit", + raises=ValueError, strict=True) + def testnext_fast_len_big(self): + hams = { + 510183360: 510183360, 510183360 + 1: 512000000, + 511000000: 512000000, + 854296875: 854296875, 854296875 + 1: 859963392, + 196608000000: 196608000000, 196608000000 + 1: 196830000000, + 8789062500000: 8789062500000, 8789062500000 + 1: 8796093022208, + 206391214080000: 206391214080000, + 206391214080000 + 1: 206624260800000, + 470184984576000: 470184984576000, + 470184984576000 + 1: 470715894135000, + 7222041363087360: 7222041363087360, + 7222041363087360 + 1: 7230196133913600, + # power of 5 5**23 + 11920928955078125: 11920928955078125, + 11920928955078125 - 1: 11920928955078125, + # power of 3 3**34 + 16677181699666569: 16677181699666569, + 16677181699666569 - 1: 16677181699666569, + # power of 2 2**54 + 18014398509481984: 18014398509481984, + 18014398509481984 - 1: 18014398509481984, + # above this, int(ceil(n)) == int(ceil(n+1)) + 19200000000000000: 19200000000000000, + 19200000000000000 + 1: 19221679687500000, + 288230376151711744: 288230376151711744, + 288230376151711744 + 1: 288325195312500000, + 288325195312500000 - 1: 288325195312500000, + 288325195312500000: 288325195312500000, + 288325195312500000 + 1: 288555831593533440, + } + for x, y in hams.items(): + assert_equal(next_fast_len(x, True), y) + + def test_keyword_args(self): + assert next_fast_len(11, real=True) == 12 + assert next_fast_len(target=7, real=False) == 7 + +@skip_xp_backends(np_only=True) +class TestPrevFastLen: + + def test_prev_fast_len(self): + np.random.seed(1234) + + def nums(): + yield from range(1, 1000) + yield 2**5 * 3**5 * 4**5 + 1 + + for n in nums(): + m = prev_fast_len(n) + _assert_n_smooth(m, 11) + assert m == prev_fast_len(n, False) + + m = prev_fast_len(n, True) + _assert_n_smooth(m, 5) + + def test_np_integers(self): + ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, + np.uint64] + for ityp in ITYPES: + x = ityp(12345) + testN = prev_fast_len(x) + assert_equal(testN, prev_fast_len(int(x))) + + testN = prev_fast_len(x, real=True) + assert_equal(testN, prev_fast_len(int(x), real=True)) + + def testprev_fast_len_small(self): + hams = { + 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 8, 14: 12, 15: 15, + 16: 16, 17: 16, 1021: 1000, 1536: 1536, 51200000: 51200000 + } + for x, y in hams.items(): + assert_equal(prev_fast_len(x, True), y) + + hams = { + 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, + 11: 11, 12: 12, 13: 12, 14: 14, 15: 15, 16: 16, 17: 16, 18: 18, + 19: 18, 20: 20, 21: 21, 22: 22, 120: 120, 121: 121, 122: 121, + 1021: 1008, 1536: 1536, 51200000: 51200000 + } + for x, y in hams.items(): + assert_equal(prev_fast_len(x, False), y) + + @pytest.mark.xfail(sys.maxsize < 2**32, + reason="Hamming Numbers too large for 32-bit", + raises=ValueError, strict=True) + def testprev_fast_len_big(self): + hams = { + # 2**6 * 3**13 * 5**1 + 510183360: 510183360, + 510183360 + 1: 510183360, + 510183360 - 1: 509607936, # 2**21 * 3**5 + # 2**6 * 5**6 * 7**1 * 73**1 + 511000000: 510183360, + 511000000 + 1: 510183360, + 511000000 - 1: 510183360, # 2**6 * 3**13 * 5**1 + # 3**7 * 5**8 + 854296875: 854296875, + 854296875 + 1: 854296875, + 854296875 - 1: 850305600, # 2**6 * 3**12 * 5**2 + # 2**22 * 3**1 * 5**6 + 196608000000: 196608000000, + 196608000000 + 1: 196608000000, + 196608000000 - 1: 195910410240, # 2**13 * 3**14 * 5**1 + # 2**5 * 3**2 * 5**15 + 8789062500000: 8789062500000, + 8789062500000 + 1: 8789062500000, + 8789062500000 - 1: 8748000000000, # 2**11 * 3**7 * 5**9 + # 2**24 * 3**9 * 5**4 + 206391214080000: 206391214080000, + 206391214080000 + 1: 206391214080000, + 206391214080000 - 1: 206158430208000, # 2**39 * 3**1 * 5**3 + # 2**18 * 3**15 * 5**3 + 470184984576000: 470184984576000, + 470184984576000 + 1: 470184984576000, + 470184984576000 - 1: 469654673817600, # 2**33 * 3**7 **5**2 + # 2**25 * 3**16 * 5**1 + 7222041363087360: 7222041363087360, + 7222041363087360 + 1: 7222041363087360, + 7222041363087360 - 1: 7213895789838336, # 2**40 * 3**8 + # power of 5 5**23 + 11920928955078125: 11920928955078125, + 11920928955078125 + 1: 11920928955078125, + 11920928955078125 - 1: 11901557422080000, # 2**14 * 3**19 * 5**4 + # power of 3 3**34 + 16677181699666569: 16677181699666569, + 16677181699666569 + 1: 16677181699666569, + 16677181699666569 - 1: 16607531250000000, # 2**7 * 3**12 * 5**12 + # power of 2 2**54 + 18014398509481984: 18014398509481984, + 18014398509481984 + 1: 18014398509481984, + 18014398509481984 - 1: 18000000000000000, # 2**16 * 3**2 * 5**15 + # 2**20 * 3**1 * 5**14 + 19200000000000000: 19200000000000000, + 19200000000000000 + 1: 19200000000000000, + 19200000000000000 - 1: 19131876000000000, # 2**11 * 3**14 * 5**9 + # 2**58 + 288230376151711744: 288230376151711744, + 288230376151711744 + 1: 288230376151711744, + 288230376151711744 - 1: 288000000000000000, # 2**20 * 3**2 * 5**15 + # 2**5 * 3**10 * 5**16 + 288325195312500000: 288325195312500000, + 288325195312500000 + 1: 288325195312500000, + 288325195312500000 - 1: 288230376151711744, # 2**58 + } + for x, y in hams.items(): + assert_equal(prev_fast_len(x, True), y) + + def test_keyword_args(self): + assert prev_fast_len(11, real=True) == 10 + assert prev_fast_len(target=7, real=False) == 7 + + +@skip_xp_backends(cpu_only=True) +class Test_init_nd_shape_and_axes: + + def test_py_0d_defaults(self, xp): + x = xp.asarray(4) + shape = None + axes = None + + shape_expected = () + axes_expected = [] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_0d_defaults(self, xp): + x = xp.asarray(7.) + shape = None + axes = None + + shape_expected = () + axes_expected = [] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_py_1d_defaults(self, xp): + x = xp.asarray([1, 2, 3]) + shape = None + axes = None + + shape_expected = (3,) + axes_expected = [0] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_1d_defaults(self, xp): + x = xp.arange(0, 1, .1) + shape = None + axes = None + + shape_expected = (10,) + axes_expected = [0] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_py_2d_defaults(self, xp): + x = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8]]) + shape = None + axes = None + + shape_expected = (2, 4) + axes_expected = [0, 1] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_2d_defaults(self, xp): + x = xp.arange(0, 1, .1) + x = xp.reshape(x, (5, 2)) + shape = None + axes = None + + shape_expected = (5, 2) + axes_expected = [0, 1] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_defaults(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = None + axes = None + + shape_expected = (6, 2, 5, 3, 4) + axes_expected = [0, 1, 2, 3, 4] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_set_shape(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = [10, -1, -1, 1, 4] + axes = None + + shape_expected = (10, 2, 5, 1, 4) + axes_expected = [0, 1, 2, 3, 4] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_set_axes(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = None + axes = [4, 1, 2] + + shape_expected = (4, 2, 5) + axes_expected = [4, 1, 2] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_xp_5d_set_shape_axes(self, xp): + x = xp.zeros([6, 2, 5, 3, 4]) + shape = [10, -1, 2] + axes = [1, 0, 3] + + shape_expected = (10, 6, 2) + axes_expected = [1, 0, 3] + + shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) + + assert shape_res == shape_expected + assert axes_res == axes_expected + + def test_shape_axes_subset(self, xp): + x = xp.zeros((2, 3, 4, 5)) + shape, axes = _init_nd_shape_and_axes(x, shape=(5, 5, 5), axes=None) + + assert shape == (5, 5, 5) + assert axes == [1, 2, 3] + + def test_errors(self, xp): + x = xp.zeros(1) + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=None, axes=[[1, 2], [3, 4]]) + + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=None, axes=[1., 2., 3., 4.]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + _init_nd_shape_and_axes(x, shape=None, axes=[1]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + _init_nd_shape_and_axes(x, shape=None, axes=[-2]) + + with assert_raises(ValueError, + match="all axes must be unique"): + _init_nd_shape_and_axes(x, shape=None, axes=[0, 0]) + + with assert_raises(ValueError, match="shape must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=[[1, 2], [3, 4]], axes=None) + + with assert_raises(ValueError, match="shape must be a scalar or " + "iterable of integers"): + _init_nd_shape_and_axes(x, shape=[1., 2., 3., 4.], axes=None) + + with assert_raises(ValueError, + match="when given, axes and shape arguments" + " have to be of the same length"): + _init_nd_shape_and_axes(xp.zeros([1, 1, 1, 1]), + shape=[1, 2, 3], axes=[1]) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[0\]\) specified"): + _init_nd_shape_and_axes(x, shape=[0], axes=None) + + with assert_raises(ValueError, + match="invalid number of data points" + r" \(\[-2\]\) specified"): + _init_nd_shape_and_axes(x, shape=-2, axes=None) + + +class TestFFTShift: + + def test_definition(self, xp): + x = xp.asarray([0., 1, 2, 3, 4, -4, -3, -2, -1]) + y = xp.asarray([-4., -3, -2, -1, 0, 1, 2, 3, 4]) + xp_assert_close(fft.fftshift(x), y) + xp_assert_close(fft.ifftshift(y), x) + x = xp.asarray([0., 1, 2, 3, 4, -5, -4, -3, -2, -1]) + y = xp.asarray([-5., -4, -3, -2, -1, 0, 1, 2, 3, 4]) + xp_assert_close(fft.fftshift(x), y) + xp_assert_close(fft.ifftshift(y), x) + + def test_inverse(self, xp): + for n in [1, 4, 9, 100, 211]: + x = xp.asarray(np.random.random((n,))) + xp_assert_close(fft.ifftshift(fft.fftshift(x)), x) + + @skip_xp_backends('cupy', reason='cupy/cupy#8393') + def test_axes_keyword(self, xp): + freqs = xp.asarray([[0., 1, 2], [3, 4, -4], [-3, -2, -1]]) + shifted = xp.asarray([[-1., -3, -2], [2, 0, 1], [-4, 3, 4]]) + xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shifted) + xp_assert_close(fft.fftshift(freqs, axes=0), fft.fftshift(freqs, axes=(0,))) + xp_assert_close(fft.ifftshift(shifted, axes=(0, 1)), freqs) + xp_assert_close(fft.ifftshift(shifted, axes=0), + fft.ifftshift(shifted, axes=(0,))) + xp_assert_close(fft.fftshift(freqs), shifted) + xp_assert_close(fft.ifftshift(shifted), freqs) + + @skip_xp_backends('cupy', reason='cupy/cupy#8393') + def test_uneven_dims(self, xp): + """ Test 2D input, which has uneven dimension sizes """ + freqs = xp.asarray([ + [0, 1], + [2, 3], + [4, 5] + ], dtype=xp.float64) + + # shift in dimension 0 + shift_dim0 = xp.asarray([ + [4, 5], + [0, 1], + [2, 3] + ], dtype=xp.float64) + xp_assert_close(fft.fftshift(freqs, axes=0), shift_dim0) + xp_assert_close(fft.ifftshift(shift_dim0, axes=0), freqs) + xp_assert_close(fft.fftshift(freqs, axes=(0,)), shift_dim0) + xp_assert_close(fft.ifftshift(shift_dim0, axes=[0]), freqs) + + # shift in dimension 1 + shift_dim1 = xp.asarray([ + [1, 0], + [3, 2], + [5, 4] + ], dtype=xp.float64) + xp_assert_close(fft.fftshift(freqs, axes=1), shift_dim1) + xp_assert_close(fft.ifftshift(shift_dim1, axes=1), freqs) + + # shift in both dimensions + shift_dim_both = xp.asarray([ + [5, 4], + [1, 0], + [3, 2] + ], dtype=xp.float64) + xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs) + xp_assert_close(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs) + + # axes=None (default) shift in all dimensions + xp_assert_close(fft.fftshift(freqs, axes=None), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both, axes=None), freqs) + xp_assert_close(fft.fftshift(freqs), shift_dim_both) + xp_assert_close(fft.ifftshift(shift_dim_both), freqs) + + +@skip_xp_backends("cupy", + reason="CuPy has not implemented the `device` param") +@skip_xp_backends("jax.numpy", + reason="JAX has not implemented the `device` param") +class TestFFTFreq: + + def test_definition(self, xp): + x = xp.asarray([0, 1, 2, 3, 4, -4, -3, -2, -1], dtype=xp.float64) + x2 = xp.asarray([0, 1, 2, 3, 4, -5, -4, -3, -2, -1], dtype=xp.float64) + + # default dtype varies across backends + + y = 9 * fft.fftfreq(9, xp=xp) + xp_assert_close(y, x, check_dtype=False, check_namespace=True) + + y = 9 * xp.pi * fft.fftfreq(9, xp.pi, xp=xp) + xp_assert_close(y, x, check_dtype=False) + + y = 10 * fft.fftfreq(10, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + y = 10 * xp.pi * fft.fftfreq(10, xp.pi, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + def test_device(self, xp): + xp_test = array_namespace(xp.empty(0)) + devices = get_xp_devices(xp) + for d in devices: + y = fft.fftfreq(9, xp=xp, device=d) + x = xp_test.empty(0, device=d) + assert xp_device(y) == xp_device(x) + + +@skip_xp_backends("cupy", + reason="CuPy has not implemented the `device` param") +@skip_xp_backends("jax.numpy", + reason="JAX has not implemented the `device` param") +class TestRFFTFreq: + + def test_definition(self, xp): + x = xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64) + x2 = xp.asarray([0, 1, 2, 3, 4, 5], dtype=xp.float64) + + # default dtype varies across backends + + y = 9 * fft.rfftfreq(9, xp=xp) + xp_assert_close(y, x, check_dtype=False, check_namespace=True) + + y = 9 * xp.pi * fft.rfftfreq(9, xp.pi, xp=xp) + xp_assert_close(y, x, check_dtype=False) + + y = 10 * fft.rfftfreq(10, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + y = 10 * xp.pi * fft.rfftfreq(10, xp.pi, xp=xp) + xp_assert_close(y, x2, check_dtype=False) + + def test_device(self, xp): + xp_test = array_namespace(xp.empty(0)) + devices = get_xp_devices(xp) + for d in devices: + y = fft.rfftfreq(9, xp=xp, device=d) + x = xp_test.empty(0, device=d) + assert xp_device(y) == xp_device(x) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py new file mode 100644 index 0000000000000000000000000000000000000000..1a6b71b830211f8bcbe56e97ff71098be75021c8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py @@ -0,0 +1,84 @@ +from scipy import fft +import numpy as np +import pytest +from numpy.testing import assert_allclose +import multiprocessing +import os + + +@pytest.fixture(scope='module') +def x(): + return np.random.randn(512, 128) # Must be large enough to qualify for mt + + +@pytest.mark.parametrize("func", [ + fft.fft, fft.ifft, fft.fft2, fft.ifft2, fft.fftn, fft.ifftn, + fft.rfft, fft.irfft, fft.rfft2, fft.irfft2, fft.rfftn, fft.irfftn, + fft.hfft, fft.ihfft, fft.hfft2, fft.ihfft2, fft.hfftn, fft.ihfftn, + fft.dct, fft.idct, fft.dctn, fft.idctn, + fft.dst, fft.idst, fft.dstn, fft.idstn, +]) +@pytest.mark.parametrize("workers", [2, -1]) +def test_threaded_same(x, func, workers): + expected = func(x, workers=1) + actual = func(x, workers=workers) + assert_allclose(actual, expected) + + +def _mt_fft(x): + return fft.fft(x, workers=2) + + +@pytest.mark.slow +def test_mixed_threads_processes(x): + # Test that the fft threadpool is safe to use before & after fork + + expect = fft.fft(x, workers=2) + + with multiprocessing.Pool(2) as p: + res = p.map(_mt_fft, [x for _ in range(4)]) + + for r in res: + assert_allclose(r, expect) + + fft.fft(x, workers=2) + + +def test_invalid_workers(x): + cpus = os.cpu_count() + + fft.ifft([1], workers=-cpus) + + with pytest.raises(ValueError, match='workers must not be zero'): + fft.fft(x, workers=0) + + with pytest.raises(ValueError, match='workers value out of range'): + fft.ifft(x, workers=-cpus-1) + + +def test_set_get_workers(): + cpus = os.cpu_count() + assert fft.get_workers() == 1 + with fft.set_workers(4): + assert fft.get_workers() == 4 + + with fft.set_workers(-1): + assert fft.get_workers() == cpus + + assert fft.get_workers() == 4 + + assert fft.get_workers() == 1 + + with fft.set_workers(-cpus): + assert fft.get_workers() == 1 + + +def test_set_workers_invalid(): + + with pytest.raises(ValueError, match='workers must not be zero'): + with fft.set_workers(0): + pass + + with pytest.raises(ValueError, match='workers value out of range'): + with fft.set_workers(-os.cpu_count()-1): + pass diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..890dc79640aff571262f5a12f721f62f5c907069 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py @@ -0,0 +1,249 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal +import pytest +import math + +from scipy.fft import dct, idct, dctn, idctn, dst, idst, dstn, idstn +import scipy.fft as fft +from scipy import fftpack +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import xp_copy, xp_assert_close + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + +SQRT_2 = math.sqrt(2) + +# scipy.fft wraps the fftpack versions but with normalized inverse transforms. +# So, the forward transforms and definitions are already thoroughly tested in +# fftpack/test_real_transforms.py + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("n", [2, 3, 4, 5, 10, 16]) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("orthogonalize", [False, True]) +def test_identity_1d(forward, backward, type, n, axis, norm, orthogonalize, xp): + # Test the identity f^-1(f(x)) == x + x = xp.asarray(np.random.rand(n, n)) + + y = forward(x, type, axis=axis, norm=norm, orthogonalize=orthogonalize) + z = backward(y, type, axis=axis, norm=norm, orthogonalize=orthogonalize) + xp_assert_close(z, x) + + pad = [(0, 0)] * 2 + pad[axis] = (0, 4) + + y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge')) + z2 = backward(y2, type, n, axis, norm, orthogonalize=orthogonalize) + xp_assert_close(z2, x) + + +@skip_xp_backends(np_only=True, + reason='`overwrite_x` only supported for NumPy backend.') +@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64, + np.complex64, np.complex128]) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("overwrite_x", [True, False]) +def test_identity_1d_overwrite(forward, backward, type, dtype, axis, norm, + overwrite_x): + # Test the identity f^-1(f(x)) == x + x = np.random.rand(7, 8).astype(dtype) + x_orig = x.copy() + + y = forward(x, type, axis=axis, norm=norm, overwrite_x=overwrite_x) + y_orig = y.copy() + z = backward(y, type, axis=axis, norm=norm, overwrite_x=overwrite_x) + if not overwrite_x: + assert_allclose(z, x, rtol=1e-6, atol=1e-6) + assert_array_equal(x, x_orig) + assert_array_equal(y, y_orig) + else: + assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("shape, axes", + [ + ((4, 4), 0), + ((4, 4), 1), + ((4, 4), None), + ((4, 4), (0, 1)), + ((10, 12), None), + ((10, 12), (0, 1)), + ((4, 5, 6), None), + ((4, 5, 6), 1), + ((4, 5, 6), (0, 2)), + ]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("orthogonalize", [False, True]) +def test_identity_nd(forward, backward, type, shape, axes, norm, + orthogonalize, xp): + # Test the identity f^-1(f(x)) == x + + x = xp.asarray(np.random.random(shape)) + + if axes is not None: + shape = np.take(shape, axes) + + y = forward(x, type, axes=axes, norm=norm, orthogonalize=orthogonalize) + z = backward(y, type, axes=axes, norm=norm, orthogonalize=orthogonalize) + xp_assert_close(z, x) + + if axes is None: + pad = [(0, 4)] * x.ndim + elif isinstance(axes, int): + pad = [(0, 0)] * x.ndim + pad[axes] = (0, 4) + else: + pad = [(0, 0)] * x.ndim + + for a in axes: + pad[a] = (0, 4) + + # TODO write an array-agnostic pad + y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge')) + z2 = backward(y2, type, shape, axes, norm, orthogonalize=orthogonalize) + xp_assert_close(z2, x) + + +@skip_xp_backends(np_only=True, + reason='`overwrite_x` only supported for NumPy backend.') +@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("shape, axes", + [ + ((4, 5), 0), + ((4, 5), 1), + ((4, 5), None), + ]) +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64, + np.complex64, np.complex128]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("overwrite_x", [False, True]) +def test_identity_nd_overwrite(forward, backward, type, shape, axes, dtype, + norm, overwrite_x): + # Test the identity f^-1(f(x)) == x + + x = np.random.random(shape).astype(dtype) + x_orig = x.copy() + + if axes is not None: + shape = np.take(shape, axes) + + y = forward(x, type, axes=axes, norm=norm) + y_orig = y.copy() + z = backward(y, type, axes=axes, norm=norm) + if overwrite_x: + assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6) + else: + assert_allclose(z, x, rtol=1e-6, atol=1e-6) + assert_array_equal(x, x_orig) + assert_array_equal(y, y_orig) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("func", ['dct', 'dst', 'dctn', 'dstn']) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +def test_fftpack_equivalience(func, type, norm, xp): + x = np.random.rand(8, 16) + fftpack_res = xp.asarray(getattr(fftpack, func)(x, type, norm=norm)) + x = xp.asarray(x) + fft_res = getattr(fft, func)(x, type, norm=norm) + + xp_assert_close(fft_res, fftpack_res) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("func", [dct, dst, dctn, dstn]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +def test_orthogonalize_default(func, type, xp): + # Test orthogonalize is the default when norm="ortho", but not otherwise + x = xp.asarray(np.random.rand(100)) + + for norm, ortho in [ + ("forward", False), + ("backward", False), + ("ortho", True), + ]: + a = func(x, type=type, norm=norm, orthogonalize=ortho) + b = func(x, type=type, norm=norm) + xp_assert_close(a, b) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func, type", [ + (dct, 4), (dst, 1), (dst, 4)]) +def test_orthogonalize_noop(func, type, norm, xp): + # Transforms where orthogonalize is a no-op + x = xp.asarray(np.random.rand(100)) + y1 = func(x, type=type, norm=norm, orthogonalize=True) + y2 = func(x, type=type, norm=norm, orthogonalize=False) + xp_assert_close(y1, y2) + + +@skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment', + cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +def test_orthogonalize_dct1(norm, xp): + x = xp.asarray(np.random.rand(100)) + + x2 = xp_copy(x, xp=xp) + x2[0] *= SQRT_2 + x2[-1] *= SQRT_2 + + y1 = dct(x, type=1, norm=norm, orthogonalize=True) + y2 = dct(x2, type=1, norm=norm, orthogonalize=False) + + y2[0] /= SQRT_2 + y2[-1] /= SQRT_2 + xp_assert_close(y1, y2) + + +@skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment', + cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func", [dct, dst]) +def test_orthogonalize_dcst2(func, norm, xp): + x = xp.asarray(np.random.rand(100)) + y1 = func(x, type=2, norm=norm, orthogonalize=True) + y2 = func(x, type=2, norm=norm, orthogonalize=False) + + y2[0 if func == dct else -1] /= SQRT_2 + xp_assert_close(y1, y2) + + +@skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment', + cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func", [dct, dst]) +def test_orthogonalize_dcst3(func, norm, xp): + x = xp.asarray(np.random.rand(100)) + x2 = xp_copy(x, xp=xp) + x2[0 if func == dct else -1] *= SQRT_2 + + y1 = func(x, type=3, norm=norm, orthogonalize=True) + y2 = func(x2, type=3, norm=norm, orthogonalize=False) + xp_assert_close(y1, y2) + +@skip_xp_backends(np_only=True, + reason='array-likes only supported for NumPy backend') +@pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn]) +def test_array_like(xp, func): + x = [[[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]]] + xp_assert_close(func(x), func(xp.asarray(x))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4f97134d20b8d3acb1bea54c8384c510314aaa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py @@ -0,0 +1,216 @@ +""" +======================================== +Interpolation (:mod:`scipy.interpolate`) +======================================== + +.. currentmodule:: scipy.interpolate + +Sub-package for objects used in interpolation. + +As listed below, this sub-package contains spline functions and classes, +1-D and multidimensional (univariate and multivariate) +interpolation classes, Lagrange and Taylor polynomial interpolators, and +wrappers for `FITPACK `__ +and DFITPACK functions. + +Univariate interpolation +======================== + +.. autosummary:: + :toctree: generated/ + + interp1d + BarycentricInterpolator + KroghInterpolator + barycentric_interpolate + krogh_interpolate + pchip_interpolate + CubicHermiteSpline + PchipInterpolator + Akima1DInterpolator + CubicSpline + PPoly + BPoly + FloaterHormannInterpolator + + +Multivariate interpolation +========================== + +Unstructured data: + +.. autosummary:: + :toctree: generated/ + + griddata + LinearNDInterpolator + NearestNDInterpolator + CloughTocher2DInterpolator + RBFInterpolator + Rbf + interp2d + +For data on a grid: + +.. autosummary:: + :toctree: generated/ + + interpn + RegularGridInterpolator + RectBivariateSpline + +.. seealso:: + + `scipy.ndimage.map_coordinates` + +Tensor product polynomials: + +.. autosummary:: + :toctree: generated/ + + NdPPoly + NdBSpline + +1-D Splines +=========== + +.. autosummary:: + :toctree: generated/ + + BSpline + make_interp_spline + make_lsq_spline + make_smoothing_spline + generate_knots + make_splrep + make_splprep + +Functional interface to FITPACK routines: + +.. autosummary:: + :toctree: generated/ + + splrep + splprep + splev + splint + sproot + spalde + splder + splantider + insert + +Object-oriented FITPACK interface: + +.. autosummary:: + :toctree: generated/ + + UnivariateSpline + InterpolatedUnivariateSpline + LSQUnivariateSpline + + + +2-D Splines +=========== + +For data on a grid: + +.. autosummary:: + :toctree: generated/ + + RectBivariateSpline + RectSphereBivariateSpline + +For unstructured data: + +.. autosummary:: + :toctree: generated/ + + BivariateSpline + SmoothBivariateSpline + SmoothSphereBivariateSpline + LSQBivariateSpline + LSQSphereBivariateSpline + +Low-level interface to FITPACK functions: + +.. autosummary:: + :toctree: generated/ + + bisplrep + bisplev + +Rational Approximation +====================== + +.. autosummary:: + :toctree: generated/ + + pade + AAA + +Additional tools +================ + +.. autosummary:: + :toctree: generated/ + + lagrange + approximate_taylor_polynomial + +.. seealso:: + + `scipy.ndimage.map_coordinates`, + `scipy.ndimage.spline_filter`, + `scipy.signal.resample`, + `scipy.signal.bspline`, + `scipy.signal.gauss_spline`, + `scipy.signal.qspline1d`, + `scipy.signal.cspline1d`, + `scipy.signal.qspline1d_eval`, + `scipy.signal.cspline1d_eval`, + `scipy.signal.qspline2d`, + `scipy.signal.cspline2d`. + +``pchip`` is an alias of `PchipInterpolator` for backward compatibility +(should not be used in new code). +""" +from ._interpolate import * +from ._fitpack_py import * + +# New interface to fitpack library: +from ._fitpack2 import * + +from ._rbf import Rbf + +from ._rbfinterp import * + +from ._polyint import * + +from ._cubic import * + +from ._ndgriddata import * + +from ._bsplines import * +from ._fitpack_repro import generate_knots, make_splrep, make_splprep + +from ._pade import * + +from ._rgi import * + +from ._ndbspline import NdBSpline + +from ._bary_rational import * + +# Deprecated namespaces, to be removed in v2.0.0 +from . import fitpack, fitpack2, interpolate, ndgriddata, polyint, rbf, interpnd + +__all__ = [s for s in dir() if not s.startswith('_')] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester + +# Backward compatibility +pchip = PchipInterpolator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf510169f9189d4bb46e102cb31b80e96aa57c37 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..760835aaebd03668c5e2a10e48645a4796d65b3e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bsplines.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bsplines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d9dde1e93ab6cbf65dbe796e40fea51e5e9003d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bsplines.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3db15e06d9ba521555a820f801683df3d2e20d80 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8114f98e7b3da51a34a8931b1e1398e3e61971d1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85817f6ab60c60eaf3026ca5e156342123c41ad3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c96f9ffbbbc0804516792148fadf30435a8a3e2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a693fc66c0fa575d42f863af5761402775b2c2d7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d29520a5d0183770eb42acda87a8511513b7abb7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..138c1c8bff283075e94cf7cfb0cf6b80b48c5527 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00b051c903dbcdab5a5172b4de6b1102e461cbeb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f30a0b11dea6322184b9e5e6ee3d55f585748536 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44424eab57d82f41434e9399c23b16c6f1ad846b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca8c4d25ed80290311efd65a8f6e508b2cb06e8f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..700c26abcd369d205d58584509aa6b31556602b4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30d4ea98f8398ebfc7a946a8e63693369e6a0db2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb858b33ff152a1f89260ca2875e7f201633718a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df96330967af730d9d2f0e95fbf5951c37e8759a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bbee4976c4b749b48d28517205adc05f791e46e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..775b1ae4a61d8d7f46996f18b2151d136d5e4a0b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4135aa6f0a53912b79015326897fddf5b884ac7f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd0c4d48ccc19ecd13372397cef2232cd98ca6cf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf0251ec76a6686f4e8798f4e897220e1743df5c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py new file mode 100644 index 0000000000000000000000000000000000000000..be13c06e27cb8df7ec4c55993dd3937e867429e5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py @@ -0,0 +1,715 @@ +# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University +# of Oxford, and the Chebfun Developers. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the University of Oxford nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import warnings +import operator + +import numpy as np +import scipy + + +__all__ = ["AAA", "FloaterHormannInterpolator"] + + +class _BarycentricRational: + """Base class for Barycentric representation of a rational function.""" + def __init__(self, x, y, **kwargs): + # input validation + z = np.asarray(x) + f = np.asarray(y) + + self._input_validation(z, f, **kwargs) + + # Remove infinite or NaN function values and repeated entries + to_keep = np.logical_and.reduce( + ((np.isfinite(f)) & (~np.isnan(f))).reshape(f.shape[0], -1), + axis=-1 + ) + f = f[to_keep, ...] + z = z[to_keep] + z, uni = np.unique(z, return_index=True) + f = f[uni, ...] + + self._shape = f.shape[1:] + self._support_points, self._support_values, self.weights = ( + self._compute_weights(z, f, **kwargs) + ) + + # only compute once + self._poles = None + self._residues = None + self._roots = None + + def _input_validation(self, x, y, **kwargs): + if x.ndim != 1: + raise ValueError("`x` must be 1-D.") + + if not y.ndim >= 1: + raise ValueError("`y` must be at least 1-D.") + + if x.size != y.shape[0]: + raise ValueError("`x` be the same size as the first dimension of `y`.") + + if not np.all(np.isfinite(x)): + raise ValueError("`x` must be finite.") + + def _compute_weights(z, f, **kwargs): + raise NotImplementedError + + def __call__(self, z): + """Evaluate the rational approximation at given values. + + Parameters + ---------- + z : array_like + Input values. + """ + # evaluate rational function in barycentric form. + z = np.asarray(z) + zv = np.ravel(z) + + support_values = self._support_values.reshape( + (self._support_values.shape[0], -1) + ) + weights = self.weights[..., np.newaxis] + + # Cauchy matrix + # Ignore errors due to inf/inf at support points, these will be fixed later + with np.errstate(invalid="ignore", divide="ignore"): + CC = 1 / np.subtract.outer(zv, self._support_points) + # Vector of values + r = CC @ (weights * support_values) / (CC @ weights) + + # Deal with input inf: `r(inf) = lim r(z) = sum(w*f) / sum(w)` + if np.any(np.isinf(zv)): + r[np.isinf(zv)] = (np.sum(weights * support_values) + / np.sum(weights)) + + # Deal with NaN + ii = np.nonzero(np.isnan(r))[0] + for jj in ii: + if np.isnan(zv[jj]) or not np.any(zv[jj] == self._support_points): + # r(NaN) = NaN is fine. + # The second case may happen if `r(zv[ii]) = 0/0` at some point. + pass + else: + # Clean up values `NaN = inf/inf` at support points. + # Find the corresponding node and set entry to correct value: + r[jj] = support_values[zv[jj] == self._support_points].squeeze() + + return np.reshape(r, z.shape + self._shape) + + def poles(self): + """Compute the poles of the rational approximation. + + Returns + ------- + poles : array + Poles of the AAA approximation, repeated according to their multiplicity + but not in any specific order. + """ + if self._poles is None: + # Compute poles via generalized eigenvalue problem + m = self.weights.size + B = np.eye(m + 1, dtype=self.weights.dtype) + B[0, 0] = 0 + + E = np.zeros_like(B, dtype=np.result_type(self.weights, + self._support_points)) + E[0, 1:] = self.weights + E[1:, 0] = 1 + np.fill_diagonal(E[1:, 1:], self._support_points) + + pol = scipy.linalg.eigvals(E, B) + self._poles = pol[np.isfinite(pol)] + return self._poles + + def residues(self): + """Compute the residues of the poles of the approximation. + + Returns + ------- + residues : array + Residues associated with the `poles` of the approximation + """ + if self._residues is None: + # Compute residues via formula for res of quotient of analytic functions + with np.errstate(divide="ignore", invalid="ignore"): + N = (1/(np.subtract.outer(self.poles(), self._support_points))) @ ( + self._support_values * self.weights + ) + Ddiff = ( + -((1/np.subtract.outer(self.poles(), self._support_points))**2) + @ self.weights + ) + self._residues = N / Ddiff + return self._residues + + def roots(self): + """Compute the zeros of the rational approximation. + + Returns + ------- + zeros : array + Zeros of the AAA approximation, repeated according to their multiplicity + but not in any specific order. + """ + if self._roots is None: + # Compute zeros via generalized eigenvalue problem + m = self.weights.size + B = np.eye(m + 1, dtype=self.weights.dtype) + B[0, 0] = 0 + E = np.zeros_like(B, dtype=np.result_type(self.weights, + self._support_values, + self._support_points)) + E[0, 1:] = self.weights * self._support_values + E[1:, 0] = 1 + np.fill_diagonal(E[1:, 1:], self._support_points) + + zer = scipy.linalg.eigvals(E, B) + self._roots = zer[np.isfinite(zer)] + return self._roots + + +class AAA(_BarycentricRational): + r""" + AAA real or complex rational approximation. + + As described in [1]_, the AAA algorithm is a greedy algorithm for approximation by + rational functions on a real or complex set of points. The rational approximation is + represented in a barycentric form from which the roots (zeros), poles, and residues + can be computed. + + Parameters + ---------- + x : 1D array_like, shape (n,) + 1-D array containing values of the independent variable. Values may be real or + complex but must be finite. + y : 1D array_like, shape (n,) + Function values ``f(x)``. Infinite and NaN values of `values` and + corresponding values of `points` will be discarded. + rtol : float, optional + Relative tolerance, defaults to ``eps**0.75``. If a small subset of the entries + in `values` are much larger than the rest the default tolerance may be too + loose. If the tolerance is too tight then the approximation may contain + Froissart doublets or the algorithm may fail to converge entirely. + max_terms : int, optional + Maximum number of terms in the barycentric representation, defaults to ``100``. + Must be greater than or equal to one. + clean_up : bool, optional + Automatic removal of Froissart doublets, defaults to ``True``. See notes for + more details. + clean_up_tol : float, optional + Poles with residues less than this number times the geometric mean + of `values` times the minimum distance to `points` are deemed spurious by the + cleanup procedure, defaults to 1e-13. See notes for more details. + + Attributes + ---------- + support_points : array + Support points of the approximation. These are a subset of the provided `x` at + which the approximation strictly interpolates `y`. + See notes for more details. + support_values : array + Value of the approximation at the `support_points`. + weights : array + Weights of the barycentric approximation. + errors : array + Error :math:`|f(z) - r(z)|_\infty` over `points` in the successive iterations + of AAA. + + Warns + ----- + RuntimeWarning + If `rtol` is not achieved in `max_terms` iterations. + + See Also + -------- + FloaterHormannInterpolator : Floater-Hormann barycentric rational interpolation. + pade : Padé approximation. + + Notes + ----- + At iteration :math:`m` (at which point there are :math:`m` terms in the both the + numerator and denominator of the approximation), the + rational approximation in the AAA algorithm takes the barycentric form + + .. math:: + + r(z) = n(z)/d(z) = + \frac{\sum_{j=1}^m\ w_j f_j / (z - z_j)}{\sum_{j=1}^m w_j / (z - z_j)}, + + where :math:`z_1,\dots,z_m` are real or complex support points selected from + `x`, :math:`f_1,\dots,f_m` are the corresponding real or complex data values + from `y`, and :math:`w_1,\dots,w_m` are real or complex weights. + + Each iteration of the algorithm has two parts: the greedy selection the next support + point and the computation of the weights. The first part of each iteration is to + select the next support point to be added :math:`z_{m+1}` from the remaining + unselected `x`, such that the nonlinear residual + :math:`|f(z_{m+1}) - n(z_{m+1})/d(z_{m+1})|` is maximised. The algorithm terminates + when this maximum is less than ``rtol * np.linalg.norm(f, ord=np.inf)``. This means + the interpolation property is only satisfied up to a tolerance, except at the + support points where approximation exactly interpolates the supplied data. + + In the second part of each iteration, the weights :math:`w_j` are selected to solve + the least-squares problem + + .. math:: + + \text{minimise}_{w_j}|fd - n| \quad \text{subject to} \quad + \sum_{j=1}^{m+1} w_j = 1, + + over the unselected elements of `x`. + + One of the challenges with working with rational approximations is the presence of + Froissart doublets, which are either poles with vanishingly small residues or + pole-zero pairs that are close enough together to nearly cancel, see [2]_. The + greedy nature of the AAA algorithm means Froissart doublets are rare. However, if + `rtol` is set too tight then the approximation will stagnate and many Froissart + doublets will appear. Froissart doublets can usually be removed by removing support + points and then resolving the least squares problem. The support point :math:`z_j`, + which is the closest support point to the pole :math:`a` with residue + :math:`\alpha`, is removed if the following is satisfied + + .. math:: + + |\alpha| / |z_j - a| < \verb|clean_up_tol| \cdot \tilde{f}, + + where :math:`\tilde{f}` is the geometric mean of `support_values`. + + + References + ---------- + .. [1] Y. Nakatsukasa, O. Sete, and L. N. Trefethen, "The AAA algorithm for + rational approximation", SIAM J. Sci. Comp. 40 (2018), A1494-A1522. + :doi:`10.1137/16M1106122` + .. [2] J. Gilewicz and M. Pindor, Pade approximants and noise: rational functions, + J. Comp. Appl. Math. 105 (1999), pp. 285-297. + :doi:`10.1016/S0377-0427(02)00674-X` + + Examples + -------- + + Here we reproduce a number of the numerical examples from [1]_ as a demonstration + of the functionality offered by this method. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import AAA + >>> import warnings + + For the first example we approximate the gamma function on ``[-3.5, 4.5]`` by + extrapolating from 100 samples in ``[-1.5, 1.5]``. + + >>> from scipy.special import gamma + >>> sample_points = np.linspace(-1.5, 1.5, num=100) + >>> r = AAA(sample_points, gamma(sample_points)) + >>> z = np.linspace(-3.5, 4.5, num=1000) + >>> fig, ax = plt.subplots() + >>> ax.plot(z, gamma(z), label="Gamma") + >>> ax.plot(sample_points, gamma(sample_points), label="Sample points") + >>> ax.plot(z, r(z).real, '--', label="AAA approximation") + >>> ax.set(xlabel="z", ylabel="r(z)", ylim=[-8, 8], xlim=[-3.5, 4.5]) + >>> ax.legend() + >>> plt.show() + + We can also view the poles of the rational approximation and their residues: + + >>> order = np.argsort(r.poles()) + >>> r.poles()[order] + array([-3.81591039e+00+0.j , -3.00269049e+00+0.j , + -1.99999988e+00+0.j , -1.00000000e+00+0.j , + 5.85842812e-17+0.j , 4.77485458e+00-3.06919376j, + 4.77485458e+00+3.06919376j, 5.29095868e+00-0.97373072j, + 5.29095868e+00+0.97373072j]) + >>> r.residues()[order] + array([ 0.03658074 +0.j , -0.16915426 -0.j , + 0.49999915 +0.j , -1. +0.j , + 1. +0.j , -0.81132013 -2.30193429j, + -0.81132013 +2.30193429j, 0.87326839+10.70148546j, + 0.87326839-10.70148546j]) + + For the second example, we call `AAA` with a spiral of 1000 points that wind 7.5 + times around the origin in the complex plane. + + >>> z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, 1000)) + >>> r = AAA(z, np.tan(np.pi*z/2), rtol=1e-13) + + We see that AAA takes 12 steps to converge with the following errors: + + >>> r.errors.size + 12 + >>> r.errors + array([2.49261500e+01, 4.28045609e+01, 1.71346935e+01, 8.65055336e-02, + 1.27106444e-02, 9.90889874e-04, 5.86910543e-05, 1.28735561e-06, + 3.57007424e-08, 6.37007837e-10, 1.67103357e-11, 1.17112299e-13]) + + We can also plot the computed poles: + + >>> fig, ax = plt.subplots() + >>> ax.plot(z.real, z.imag, '.', markersize=2, label="Sample points") + >>> ax.plot(r.poles().real, r.poles().imag, '.', markersize=5, + ... label="Computed poles") + >>> ax.set(xlim=[-3.5, 3.5], ylim=[-3.5, 3.5], aspect="equal") + >>> ax.legend() + >>> plt.show() + + We now demonstrate the removal of Froissart doublets using the `clean_up` method + using an example from [1]_. Here we approximate the function + :math:`f(z)=\log(2 + z^4)/(1 + 16z^4)` by sampling it at 1000 roots of unity. The + algorithm is run with ``rtol=0`` and ``clean_up=False`` to deliberately cause + Froissart doublets to appear. + + >>> z = np.exp(1j*2*np.pi*np.linspace(0,1, num=1000)) + >>> def f(z): + ... return np.log(2 + z**4)/(1 - 16*z**4) + >>> with warnings.catch_warnings(): # filter convergence warning due to rtol=0 + ... warnings.simplefilter('ignore', RuntimeWarning) + ... r = AAA(z, f(z), rtol=0, max_terms=50, clean_up=False) + >>> mask = np.abs(r.residues()) < 1e-13 + >>> fig, axs = plt.subplots(ncols=2) + >>> axs[0].plot(r.poles().real[~mask], r.poles().imag[~mask], '.') + >>> axs[0].plot(r.poles().real[mask], r.poles().imag[mask], 'r.') + + Now we call the `clean_up` method to remove Froissart doublets. + + >>> with warnings.catch_warnings(): + ... warnings.simplefilter('ignore', RuntimeWarning) + ... r.clean_up() + 4 + >>> mask = np.abs(r.residues()) < 1e-13 + >>> axs[1].plot(r.poles().real[~mask], r.poles().imag[~mask], '.') + >>> axs[1].plot(r.poles().real[mask], r.poles().imag[mask], 'r.') + >>> plt.show() + + The left image shows the poles prior of the approximation ``clean_up=False`` with + poles with residue less than ``10^-13`` in absolute value shown in red. The right + image then shows the poles after the `clean_up` method has been called. + """ + def __init__(self, x, y, *, rtol=None, max_terms=100, clean_up=True, + clean_up_tol=1e-13): + super().__init__(x, y, rtol=rtol, max_terms=max_terms) + + if clean_up: + self.clean_up(clean_up_tol) + + def _input_validation(self, x, y, rtol=None, max_terms=100, clean_up=True, + clean_up_tol=1e-13): + max_terms = operator.index(max_terms) + if max_terms < 1: + raise ValueError("`max_terms` must be an integer value greater than or " + "equal to one.") + + if y.ndim != 1: + raise ValueError("`y` must be 1-D.") + + super()._input_validation(x, y) + + @property + def support_points(self): + return self._support_points + + @property + def support_values(self): + return self._support_values + + def _compute_weights(self, z, f, rtol, max_terms): + # Initialization for AAA iteration + M = np.size(z) + mask = np.ones(M, dtype=np.bool_) + dtype = np.result_type(z, f, 1.0) + rtol = np.finfo(dtype).eps**0.75 if rtol is None else rtol + atol = rtol * np.linalg.norm(f, ord=np.inf) + zj = np.empty(max_terms, dtype=dtype) + fj = np.empty(max_terms, dtype=dtype) + # Cauchy matrix + C = np.empty((M, max_terms), dtype=dtype) + # Loewner matrix + A = np.empty((M, max_terms), dtype=dtype) + errors = np.empty(max_terms, dtype=A.real.dtype) + R = np.repeat(np.mean(f), M) + + # AAA iteration + for m in range(max_terms): + # Introduce next support point + # Select next support point + jj = np.argmax(np.abs(f[mask] - R[mask])) + # Update support points + zj[m] = z[mask][jj] + # Update data values + fj[m] = f[mask][jj] + # Next column of Cauchy matrix + # Ignore errors as we manually interpolate at support points + with np.errstate(divide="ignore", invalid="ignore"): + C[:, m] = 1 / (z - z[mask][jj]) + # Update mask + mask[np.nonzero(mask)[0][jj]] = False + # Update Loewner matrix + # Ignore errors as inf values will be masked out in SVD call + with np.errstate(invalid="ignore"): + A[:, m] = (f - fj[m]) * C[:, m] + + # Compute weights + rows = mask.sum() + if rows >= m + 1: + # The usual tall-skinny case + _, s, V = scipy.linalg.svd( + A[mask, : m + 1], full_matrices=False, check_finite=False, + ) + # Treat case of multiple min singular values + mm = s == np.min(s) + # Aim for non-sparse weight vector + wj = (V.conj()[mm, :].sum(axis=0) / np.sqrt(mm.sum())).astype(dtype) + else: + # Fewer rows than columns + V = scipy.linalg.null_space(A[mask, : m + 1], check_finite=False) + nm = V.shape[-1] + # Aim for non-sparse wt vector + wj = V.sum(axis=-1) / np.sqrt(nm) + + # Compute rational approximant + # Omit columns with `wj == 0` + i0 = wj != 0 + # Ignore errors as we manually interpolate at support points + with np.errstate(invalid="ignore"): + # Numerator + N = C[:, : m + 1][:, i0] @ (wj[i0] * fj[: m + 1][i0]) + # Denominator + D = C[:, : m + 1][:, i0] @ wj[i0] + # Interpolate at support points with `wj !=0` + D_inf = np.isinf(D) | np.isnan(D) + D[D_inf] = 1 + N[D_inf] = f[D_inf] + R = N / D + + # Check if converged + max_error = np.linalg.norm(f - R, ord=np.inf) + errors[m] = max_error + if max_error <= atol: + break + + if m == max_terms - 1: + warnings.warn(f"AAA failed to converge within {max_terms} iterations.", + RuntimeWarning, stacklevel=2) + + # Trim off unused array allocation + zj = zj[: m + 1] + fj = fj[: m + 1] + + # Remove support points with zero weight + i_non_zero = wj != 0 + self.errors = errors[: m + 1] + self._points = z + self._values = f + return zj[i_non_zero], fj[i_non_zero], wj[i_non_zero] + + def clean_up(self, cleanup_tol=1e-13): + """Automatic removal of Froissart doublets. + + Parameters + ---------- + cleanup_tol : float, optional + Poles with residues less than this number times the geometric mean + of `values` times the minimum distance to `points` are deemed spurious by + the cleanup procedure, defaults to 1e-13. + + Returns + ------- + int + Number of Froissart doublets detected + """ + # Find negligible residues + geom_mean_abs_f = scipy.stats.gmean(np.abs(self._values)) + + Z_distances = np.min( + np.abs(np.subtract.outer(self.poles(), self._points)), axis=1 + ) + + with np.errstate(divide="ignore", invalid="ignore"): + ii = np.nonzero( + np.abs(self.residues()) / Z_distances < cleanup_tol * geom_mean_abs_f + ) + + ni = ii[0].size + if ni == 0: + return ni + + warnings.warn(f"{ni} Froissart doublets detected.", RuntimeWarning, + stacklevel=2) + + # For each spurious pole find and remove closest support point + closest_spt_point = np.argmin( + np.abs(np.subtract.outer(self._support_points, self.poles()[ii])), axis=0 + ) + self._support_points = np.delete(self._support_points, closest_spt_point) + self._support_values = np.delete(self._support_values, closest_spt_point) + + # Remove support points z from sample set + mask = np.logical_and.reduce( + np.not_equal.outer(self._points, self._support_points), axis=1 + ) + f = self._values[mask] + z = self._points[mask] + + # recompute weights, we resolve the least squares problem for the remaining + # support points + + m = self._support_points.size + + # Cauchy matrix + C = 1 / np.subtract.outer(z, self._support_points) + # Loewner matrix + A = f[:, np.newaxis] * C - C * self._support_values + + # Solve least-squares problem to obtain weights + _, _, V = scipy.linalg.svd(A, check_finite=False) + self.weights = np.conj(V[m - 1,:]) + + # reset roots, poles, residues as cached values will be wrong with new weights + self._poles = None + self._residues = None + self._roots = None + + return ni + + +class FloaterHormannInterpolator(_BarycentricRational): + r""" + Floater-Hormann barycentric rational interpolation. + + As described in [1]_, the method of Floater and Hormann computes weights for a + Barycentric rational interpolant with no poles on the real axis. + + Parameters + ---------- + x : 1D array_like, shape (n,) + 1-D array containing values of the independent variable. Values may be real or + complex but must be finite. + y : array_like, shape (n, ...) + Array containing values of the dependent variable. Infinite and NaN values + of `values` and corresponding values of `x` will be discarded. + d : int, optional + Blends ``n - d`` degree `d` polynomials together. For ``d = n - 1`` it is + equivalent to polynomial interpolation. Must satisfy ``0 <= d < n``, + defaults to 3. + + Attributes + ---------- + weights : array + Weights of the barycentric approximation. + + See Also + -------- + AAA : Barycentric rational approximation of real and complex functions. + pade : Padé approximation. + + Notes + ----- + The Floater-Hormann interpolant is a rational function that interpolates the data + with approximation order :math:`O(h^{d+1})`. The rational function blends ``n - d`` + polynomials of degree `d` together to produce a rational interpolant that contains + no poles on the real axis, unlike `AAA`. The interpolant is given + by + + .. math:: + + r(x) = \frac{\sum_{i=0}^{n-d} \lambda_i(x) p_i(x)} + {\sum_{i=0}^{n-d} \lambda_i(x)}, + + where :math:`p_i(x)` is an interpolating polynomials of at most degree `d` through + the points :math:`(x_i,y_i),\dots,(x_{i+d},y_{i+d}), and :math:`\lambda_i(z)` are + blending functions defined by + + .. math:: + + \lambda_i(x) = \frac{(-1)^i}{(x - x_i)\cdots(x - x_{i+d})}. + + When ``d = n - 1`` this reduces to polynomial interpolation. + + Due to its stability following barycentric representation of the above equation + is used instead for computation + + .. math:: + + r(z) = \frac{\sum_{k=1}^m\ w_k f_k / (x - x_k)}{\sum_{k=1}^m w_k / (x - x_k)}, + + where the weights :math:`w_j` are computed as + + .. math:: + + w_k &= (-1)^{k - d} \sum_{i \in J_k} \prod_{j = i, j \neq k}^{i + d} + 1/|x_k - x_j|, \\ + J_k &= \{ i \in I: k - d \leq i \leq k\},\\ + I &= \{0, 1, \dots, n - d\}. + + References + ---------- + .. [1] M.S. Floater and K. Hormann, "Barycentric rational interpolation with no + poles and high rates of approximation", Numer. Math. 107, 315 (2007). + :doi:`10.1007/s00211-007-0093-y` + + Examples + -------- + + Here we compare the method against polynomial interpolation for an example where + the polynomial interpolation fails due to Runge's phenomenon. + + >>> import numpy as np + >>> from scipy.interpolate import (FloaterHormannInterpolator, + ... BarycentricInterpolator) + >>> def f(z): + ... return 1/(1 + z**2) + >>> z = np.linspace(-5, 5, num=15) + >>> r = FloaterHormannInterpolator(z, f(z)) + >>> p = BarycentricInterpolator(z, f(z)) + >>> zz = np.linspace(-5, 5, num=1000) + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.plot(zz, r(zz), label="Floater=Hormann") + >>> ax.plot(zz, p(zz), label="Polynomial") + >>> ax.legend() + >>> plt.show() + """ + def __init__(self, points, values, *, d=3): + super().__init__(points, values, d=d) + + def _input_validation(self, x, y, d): + d = operator.index(d) + if not (0 <= d < len(x)): + raise ValueError("`d` must satisfy 0 <= d < n") + + super()._input_validation(x, y) + + def _compute_weights(self, z, f, d): + # Floater and Hormann 2007 Eqn. (18) 3 equations later + w = np.zeros_like(z, dtype=np.result_type(z, 1.0)) + n = w.size + for k in range(n): + for i in range(max(k-d, 0), min(k+1, n-d)): + w[k] += 1/np.prod(np.abs(np.delete(z[k] - z[i : i + d + 1], k - i))) + w *= (-1.)**(np.arange(n) - d) + + return z, f, w diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..3d68e8d532100f4926328d68cb68d1048f4290e8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py @@ -0,0 +1,2416 @@ +import operator +from math import prod + +import numpy as np +from scipy._lib._util import normalize_axis_index +from scipy.linalg import (get_lapack_funcs, LinAlgError, + cholesky_banded, cho_solve_banded, + solve, solve_banded) +from scipy.optimize import minimize_scalar +from . import _dierckx +from . import _fitpack_impl +from scipy.sparse import csr_array +from scipy.special import poch +from itertools import combinations + + +__all__ = ["BSpline", "make_interp_spline", "make_lsq_spline", + "make_smoothing_spline"] + + +def _get_dtype(dtype): + """Return np.complex128 for complex dtypes, np.float64 otherwise.""" + if np.issubdtype(dtype, np.complexfloating): + return np.complex128 + else: + return np.float64 + + +def _as_float_array(x, check_finite=False): + """Convert the input into a C contiguous float array. + + NB: Upcasts half- and single-precision floats to double precision. + """ + x = np.ascontiguousarray(x) + dtyp = _get_dtype(x.dtype) + x = x.astype(dtyp, copy=False) + if check_finite and not np.isfinite(x).all(): + raise ValueError("Array must not contain infs or nans.") + return x + + +def _dual_poly(j, k, t, y): + """ + Dual polynomial of the B-spline B_{j,k,t} - + polynomial which is associated with B_{j,k,t}: + $p_{j,k}(y) = (y - t_{j+1})(y - t_{j+2})...(y - t_{j+k})$ + """ + if k == 0: + return 1 + return np.prod([(y - t[j + i]) for i in range(1, k + 1)]) + + +def _diff_dual_poly(j, k, y, d, t): + """ + d-th derivative of the dual polynomial $p_{j,k}(y)$ + """ + if d == 0: + return _dual_poly(j, k, t, y) + if d == k: + return poch(1, k) + comb = list(combinations(range(j + 1, j + k + 1), d)) + res = 0 + for i in range(len(comb) * len(comb[0])): + res += np.prod([(y - t[j + p]) for p in range(1, k + 1) + if (j + p) not in comb[i//d]]) + return res + + +class BSpline: + r"""Univariate spline in the B-spline basis. + + .. math:: + + S(x) = \sum_{j=0}^{n-1} c_j B_{j, k; t}(x) + + where :math:`B_{j, k; t}` are B-spline basis functions of degree `k` + and knots `t`. + + Parameters + ---------- + t : ndarray, shape (n+k+1,) + knots + c : ndarray, shape (>=n, ...) + spline coefficients + k : int + B-spline degree + extrapolate : bool or 'periodic', optional + whether to extrapolate beyond the base interval, ``t[k] .. t[n]``, + or to return nans. + If True, extrapolates the first and last polynomial pieces of b-spline + functions active on the base interval. + If 'periodic', periodic extrapolation is used. + Default is True. + axis : int, optional + Interpolation axis. Default is zero. + + Attributes + ---------- + t : ndarray + knot vector + c : ndarray + spline coefficients + k : int + spline degree + extrapolate : bool + If True, extrapolates the first and last polynomial pieces of b-spline + functions active on the base interval. + axis : int + Interpolation axis. + tck : tuple + A read-only equivalent of ``(self.t, self.c, self.k)`` + + Methods + ------- + __call__ + basis_element + derivative + antiderivative + integrate + insert_knot + construct_fast + design_matrix + from_power_basis + + Notes + ----- + B-spline basis elements are defined via + + .. math:: + + B_{i, 0}(x) = 1, \textrm{if $t_i \le x < t_{i+1}$, otherwise $0$,} + + B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x) + + \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x) + + **Implementation details** + + - At least ``k+1`` coefficients are required for a spline of degree `k`, + so that ``n >= k+1``. Additional coefficients, ``c[j]`` with + ``j > n``, are ignored. + + - B-spline basis elements of degree `k` form a partition of unity on the + *base interval*, ``t[k] <= x <= t[n]``. + + + Examples + -------- + + Translating the recursive definition of B-splines into Python code, we have: + + >>> def B(x, k, i, t): + ... if k == 0: + ... return 1.0 if t[i] <= x < t[i+1] else 0.0 + ... if t[i+k] == t[i]: + ... c1 = 0.0 + ... else: + ... c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t) + ... if t[i+k+1] == t[i+1]: + ... c2 = 0.0 + ... else: + ... c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t) + ... return c1 + c2 + + >>> def bspline(x, t, c, k): + ... n = len(t) - k - 1 + ... assert (n >= k+1) and (len(c) >= n) + ... return sum(c[i] * B(x, k, i, t) for i in range(n)) + + Note that this is an inefficient (if straightforward) way to + evaluate B-splines --- this spline class does it in an equivalent, + but much more efficient way. + + Here we construct a quadratic spline function on the base interval + ``2 <= x <= 4`` and compare with the naive way of evaluating the spline: + + >>> from scipy.interpolate import BSpline + >>> k = 2 + >>> t = [0, 1, 2, 3, 4, 5, 6] + >>> c = [-1, 2, 0, -1] + >>> spl = BSpline(t, c, k) + >>> spl(2.5) + array(1.375) + >>> bspline(2.5, t, c, k) + 1.375 + + Note that outside of the base interval results differ. This is because + `BSpline` extrapolates the first and last polynomial pieces of B-spline + functions active on the base interval. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> fig, ax = plt.subplots() + >>> xx = np.linspace(1.5, 4.5, 50) + >>> ax.plot(xx, [bspline(x, t, c ,k) for x in xx], 'r-', lw=3, label='naive') + >>> ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline') + >>> ax.grid(True) + >>> ax.legend(loc='best') + >>> plt.show() + + + References + ---------- + .. [1] Tom Lyche and Knut Morken, Spline methods, + http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/ + .. [2] Carl de Boor, A practical guide to splines, Springer, 2001. + + """ + + def __init__(self, t, c, k, extrapolate=True, axis=0): + super().__init__() + + self.k = operator.index(k) + self.c = np.asarray(c) + self.t = np.ascontiguousarray(t, dtype=np.float64) + + if extrapolate == 'periodic': + self.extrapolate = extrapolate + else: + self.extrapolate = bool(extrapolate) + + n = self.t.shape[0] - self.k - 1 + + axis = normalize_axis_index(axis, self.c.ndim) + + # Note that the normalized axis is stored in the object. + self.axis = axis + if axis != 0: + # roll the interpolation axis to be the first one in self.c + # More specifically, the target shape for self.c is (n, ...), + # and axis !=0 means that we have c.shape (..., n, ...) + # ^ + # axis + self.c = np.moveaxis(self.c, axis, 0) + + if k < 0: + raise ValueError("Spline order cannot be negative.") + if self.t.ndim != 1: + raise ValueError("Knot vector must be one-dimensional.") + if n < self.k + 1: + raise ValueError("Need at least %d knots for degree %d" % + (2*k + 2, k)) + if (np.diff(self.t) < 0).any(): + raise ValueError("Knots must be in a non-decreasing order.") + if len(np.unique(self.t[k:n+1])) < 2: + raise ValueError("Need at least two internal knots.") + if not np.isfinite(self.t).all(): + raise ValueError("Knots should not have nans or infs.") + if self.c.ndim < 1: + raise ValueError("Coefficients must be at least 1-dimensional.") + if self.c.shape[0] < n: + raise ValueError("Knots, coefficients and degree are inconsistent.") + + dt = _get_dtype(self.c.dtype) + self.c = np.ascontiguousarray(self.c, dtype=dt) + + @classmethod + def construct_fast(cls, t, c, k, extrapolate=True, axis=0): + """Construct a spline without making checks. + + Accepts same parameters as the regular constructor. Input arrays + `t` and `c` must of correct shape and dtype. + """ + self = object.__new__(cls) + self.t, self.c, self.k = t, c, k + self.extrapolate = extrapolate + self.axis = axis + return self + + @property + def tck(self): + """Equivalent to ``(self.t, self.c, self.k)`` (read-only). + """ + return self.t, self.c, self.k + + @classmethod + def basis_element(cls, t, extrapolate=True): + """Return a B-spline basis element ``B(x | t[0], ..., t[k+1])``. + + Parameters + ---------- + t : ndarray, shape (k+2,) + internal knots + extrapolate : bool or 'periodic', optional + whether to extrapolate beyond the base interval, ``t[0] .. t[k+1]``, + or to return nans. + If 'periodic', periodic extrapolation is used. + Default is True. + + Returns + ------- + basis_element : callable + A callable representing a B-spline basis element for the knot + vector `t`. + + Notes + ----- + The degree of the B-spline, `k`, is inferred from the length of `t` as + ``len(t)-2``. The knot vector is constructed by appending and prepending + ``k+1`` elements to internal knots `t`. + + Examples + -------- + + Construct a cubic B-spline: + + >>> import numpy as np + >>> from scipy.interpolate import BSpline + >>> b = BSpline.basis_element([0, 1, 2, 3, 4]) + >>> k = b.k + >>> b.t[k:-k] + array([ 0., 1., 2., 3., 4.]) + >>> k + 3 + + Construct a quadratic B-spline on ``[0, 1, 1, 2]``, and compare + to its explicit form: + + >>> t = [0, 1, 1, 2] + >>> b = BSpline.basis_element(t) + >>> def f(x): + ... return np.where(x < 1, x*x, (2. - x)**2) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> x = np.linspace(0, 2, 51) + >>> ax.plot(x, b(x), 'g', lw=3) + >>> ax.plot(x, f(x), 'r', lw=8, alpha=0.4) + >>> ax.grid(True) + >>> plt.show() + + """ + k = len(t) - 2 + t = _as_float_array(t) + t = np.r_[(t[0]-1,) * k, t, (t[-1]+1,) * k] + c = np.zeros_like(t) + c[k] = 1. + return cls.construct_fast(t, c, k, extrapolate) + + @classmethod + def design_matrix(cls, x, t, k, extrapolate=False): + """ + Returns a design matrix as a CSR format sparse array. + + Parameters + ---------- + x : array_like, shape (n,) + Points to evaluate the spline at. + t : array_like, shape (nt,) + Sorted 1D array of knots. + k : int + B-spline degree. + extrapolate : bool or 'periodic', optional + Whether to extrapolate based on the first and last intervals + or raise an error. If 'periodic', periodic extrapolation is used. + Default is False. + + .. versionadded:: 1.10.0 + + Returns + ------- + design_matrix : `csr_array` object + Sparse matrix in CSR format where each row contains all the basis + elements of the input row (first row = basis elements of x[0], + ..., last row = basis elements x[-1]). + + Examples + -------- + Construct a design matrix for a B-spline + + >>> from scipy.interpolate import make_interp_spline, BSpline + >>> import numpy as np + >>> x = np.linspace(0, np.pi * 2, 4) + >>> y = np.sin(x) + >>> k = 3 + >>> bspl = make_interp_spline(x, y, k=k) + >>> design_matrix = bspl.design_matrix(x, bspl.t, k) + >>> design_matrix.toarray() + [[1. , 0. , 0. , 0. ], + [0.2962963 , 0.44444444, 0.22222222, 0.03703704], + [0.03703704, 0.22222222, 0.44444444, 0.2962963 ], + [0. , 0. , 0. , 1. ]] + + Construct a design matrix for some vector of knots + + >>> k = 2 + >>> t = [-1, 0, 1, 2, 3, 4, 5, 6] + >>> x = [1, 2, 3, 4] + >>> design_matrix = BSpline.design_matrix(x, t, k).toarray() + >>> design_matrix + [[0.5, 0.5, 0. , 0. , 0. ], + [0. , 0.5, 0.5, 0. , 0. ], + [0. , 0. , 0.5, 0.5, 0. ], + [0. , 0. , 0. , 0.5, 0.5]] + + This result is equivalent to the one created in the sparse format + + >>> c = np.eye(len(t) - k - 1) + >>> design_matrix_gh = BSpline(t, c, k)(x) + >>> np.allclose(design_matrix, design_matrix_gh, atol=1e-14) + True + + Notes + ----- + .. versionadded:: 1.8.0 + + In each row of the design matrix all the basis elements are evaluated + at the certain point (first row - x[0], ..., last row - x[-1]). + + `nt` is a length of the vector of knots: as far as there are + `nt - k - 1` basis elements, `nt` should be not less than `2 * k + 2` + to have at least `k + 1` basis element. + + Out of bounds `x` raises a ValueError. + """ + x = _as_float_array(x, True) + t = _as_float_array(t, True) + + if extrapolate != 'periodic': + extrapolate = bool(extrapolate) + + if k < 0: + raise ValueError("Spline order cannot be negative.") + if t.ndim != 1 or np.any(t[1:] < t[:-1]): + raise ValueError(f"Expect t to be a 1-D sorted array_like, but " + f"got t={t}.") + # There are `nt - k - 1` basis elements in a BSpline built on the + # vector of knots with length `nt`, so to have at least `k + 1` basis + # elements we need to have at least `2 * k + 2` elements in the vector + # of knots. + if len(t) < 2 * k + 2: + raise ValueError(f"Length t is not enough for k={k}.") + + if extrapolate == 'periodic': + # With periodic extrapolation we map x to the segment + # [t[k], t[n]]. + n = t.size - k - 1 + x = t[k] + (x - t[k]) % (t[n] - t[k]) + extrapolate = False + elif not extrapolate and ( + (min(x) < t[k]) or (max(x) > t[t.shape[0] - k - 1]) + ): + # Checks from `find_interval` function + raise ValueError(f'Out of bounds w/ x = {x}.') + + # Compute number of non-zeros of final CSR array in order to determine + # the dtype of indices and indptr of the CSR array. + n = x.shape[0] + nnz = n * (k + 1) + if nnz < np.iinfo(np.int32).max: + int_dtype = np.int32 + else: + int_dtype = np.int64 + + # Get the non-zero elements of the design matrix and per-row `offsets`: + # In row `i`, k+1 nonzero elements are consecutive, and start from `offset[i]` + data, offsets, _ = _dierckx.data_matrix(x, t, k, np.ones_like(x), extrapolate) + data = data.ravel() + + if offsets.dtype != int_dtype: + offsets = offsets.astype(int_dtype) + + # Convert from per-row offsets to the CSR indices/indptr format + indices = np.repeat(offsets, k+1).reshape(-1, k+1) + indices = indices + np.arange(k+1, dtype=int_dtype) + indices = indices.ravel() + + indptr = np.arange(0, (n + 1) * (k + 1), k + 1, dtype=int_dtype) + + return csr_array( + (data, indices, indptr), + shape=(x.shape[0], t.shape[0] - k - 1) + ) + + def __call__(self, x, nu=0, extrapolate=None): + """ + Evaluate a spline function. + + Parameters + ---------- + x : array_like + points to evaluate the spline at. + nu : int, optional + derivative to evaluate (default is 0). + extrapolate : bool or 'periodic', optional + whether to extrapolate based on the first and last intervals + or return nans. If 'periodic', periodic extrapolation is used. + Default is `self.extrapolate`. + + Returns + ------- + y : array_like + Shape is determined by replacing the interpolation axis + in the coefficient array with the shape of `x`. + + """ + if extrapolate is None: + extrapolate = self.extrapolate + x = np.asarray(x) + x_shape, x_ndim = x.shape, x.ndim + x = np.ascontiguousarray(x.ravel(), dtype=np.float64) + + # With periodic extrapolation we map x to the segment + # [self.t[k], self.t[n]]. + if extrapolate == 'periodic': + n = self.t.size - self.k - 1 + x = self.t[self.k] + (x - self.t[self.k]) % (self.t[n] - + self.t[self.k]) + extrapolate = False + + out = np.empty((len(x), prod(self.c.shape[1:])), dtype=self.c.dtype) + self._ensure_c_contiguous() + + # if self.c is complex, so is `out`; cython code in _bspl.pyx expectes + # floats though, so make a view---this expands the last axis, and + # the view is C contiguous if the original is. + # if c.dtype is complex of shape (n,), c.view(float).shape == (2*n,) + # if c.dtype is complex of shape (n, m), c.view(float).shape == (n, 2*m) + + cc = self.c.view(float) + if self.c.ndim == 1 and self.c.dtype.kind == 'c': + cc = cc.reshape(self.c.shape[0], 2) + + _dierckx.evaluate_spline(self.t, cc.reshape(cc.shape[0], -1), + self.k, x, nu, extrapolate, out.view(float)) + + out = out.reshape(x_shape + self.c.shape[1:]) + if self.axis != 0: + # transpose to move the calculated values to the interpolation axis + l = list(range(out.ndim)) + l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:] + out = out.transpose(l) + return out + + def _ensure_c_contiguous(self): + """ + c and t may be modified by the user. The Cython code expects + that they are C contiguous. + + """ + if not self.t.flags.c_contiguous: + self.t = self.t.copy() + if not self.c.flags.c_contiguous: + self.c = self.c.copy() + + def derivative(self, nu=1): + """Return a B-spline representing the derivative. + + Parameters + ---------- + nu : int, optional + Derivative order. + Default is 1. + + Returns + ------- + b : BSpline object + A new instance representing the derivative. + + See Also + -------- + splder, splantider + + """ + c = self.c.copy() + # pad the c array if needed + ct = len(self.t) - len(c) + if ct > 0: + c = np.r_[c, np.zeros((ct,) + c.shape[1:])] + tck = _fitpack_impl.splder((self.t, c, self.k), nu) + return self.construct_fast(*tck, extrapolate=self.extrapolate, + axis=self.axis) + + def antiderivative(self, nu=1): + """Return a B-spline representing the antiderivative. + + Parameters + ---------- + nu : int, optional + Antiderivative order. Default is 1. + + Returns + ------- + b : BSpline object + A new instance representing the antiderivative. + + Notes + ----- + If antiderivative is computed and ``self.extrapolate='periodic'``, + it will be set to False for the returned instance. This is done because + the antiderivative is no longer periodic and its correct evaluation + outside of the initially given x interval is difficult. + + See Also + -------- + splder, splantider + + """ + c = self.c.copy() + # pad the c array if needed + ct = len(self.t) - len(c) + if ct > 0: + c = np.r_[c, np.zeros((ct,) + c.shape[1:])] + tck = _fitpack_impl.splantider((self.t, c, self.k), nu) + + if self.extrapolate == 'periodic': + extrapolate = False + else: + extrapolate = self.extrapolate + + return self.construct_fast(*tck, extrapolate=extrapolate, + axis=self.axis) + + def integrate(self, a, b, extrapolate=None): + """Compute a definite integral of the spline. + + Parameters + ---------- + a : float + Lower limit of integration. + b : float + Upper limit of integration. + extrapolate : bool or 'periodic', optional + whether to extrapolate beyond the base interval, + ``t[k] .. t[-k-1]``, or take the spline to be zero outside of the + base interval. If 'periodic', periodic extrapolation is used. + If None (default), use `self.extrapolate`. + + Returns + ------- + I : array_like + Definite integral of the spline over the interval ``[a, b]``. + + Examples + -------- + Construct the linear spline ``x if x < 1 else 2 - x`` on the base + interval :math:`[0, 2]`, and integrate it + + >>> from scipy.interpolate import BSpline + >>> b = BSpline.basis_element([0, 1, 2]) + >>> b.integrate(0, 1) + array(0.5) + + If the integration limits are outside of the base interval, the result + is controlled by the `extrapolate` parameter + + >>> b.integrate(-1, 1) + array(0.0) + >>> b.integrate(-1, 1, extrapolate=False) + array(0.5) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.grid(True) + >>> ax.axvline(0, c='r', lw=5, alpha=0.5) # base interval + >>> ax.axvline(2, c='r', lw=5, alpha=0.5) + >>> xx = [-1, 1, 2] + >>> ax.plot(xx, b(xx)) + >>> plt.show() + + """ + if extrapolate is None: + extrapolate = self.extrapolate + + # Prepare self.t and self.c. + self._ensure_c_contiguous() + + # Swap integration bounds if needed. + sign = 1 + if b < a: + a, b = b, a + sign = -1 + n = self.t.size - self.k - 1 + + if extrapolate != "periodic" and not extrapolate: + # Shrink the integration interval, if needed. + a = max(a, self.t[self.k]) + b = min(b, self.t[n]) + + if self.c.ndim == 1: + # Fast path: use FITPACK's routine + # (cf _fitpack_impl.splint). + integral = _fitpack_impl.splint(a, b, self.tck) + return np.asarray(integral * sign) + + out = np.empty((2, prod(self.c.shape[1:])), dtype=self.c.dtype) + + # Compute the antiderivative. + c = self.c + ct = len(self.t) - len(c) + if ct > 0: + c = np.r_[c, np.zeros((ct,) + c.shape[1:])] + ta, ca, ka = _fitpack_impl.splantider((self.t, c, self.k), 1) + + if extrapolate == 'periodic': + # Split the integral into the part over period (can be several + # of them) and the remaining part. + + ts, te = self.t[self.k], self.t[n] + period = te - ts + interval = b - a + n_periods, left = divmod(interval, period) + + if n_periods > 0: + # Evaluate the difference of antiderivatives. + x = np.asarray([ts, te], dtype=np.float64) + _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral = out[1] - out[0] + integral *= n_periods + else: + integral = np.zeros((1, prod(self.c.shape[1:])), + dtype=self.c.dtype) + + # Map a to [ts, te], b is always a + left. + a = ts + (a - ts) % period + b = a + left + + # If b <= te then we need to integrate over [a, b], otherwise + # over [a, te] and from xs to what is remained. + if b <= te: + x = np.asarray([a, b], dtype=np.float64) + _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral += out[1] - out[0] + else: + x = np.asarray([a, te], dtype=np.float64) + _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral += out[1] - out[0] + + x = np.asarray([ts, ts + b - te], dtype=np.float64) + _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral += out[1] - out[0] + else: + # Evaluate the difference of antiderivatives. + x = np.asarray([a, b], dtype=np.float64) + _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, extrapolate, out) + integral = out[1] - out[0] + + integral *= sign + return integral.reshape(ca.shape[1:]) + + @classmethod + def from_power_basis(cls, pp, bc_type='not-a-knot'): + r""" + Construct a polynomial in the B-spline basis + from a piecewise polynomial in the power basis. + + For now, accepts ``CubicSpline`` instances only. + + Parameters + ---------- + pp : CubicSpline + A piecewise polynomial in the power basis, as created + by ``CubicSpline`` + bc_type : string, optional + Boundary condition type as in ``CubicSpline``: one of the + ``not-a-knot``, ``natural``, ``clamped``, or ``periodic``. + Necessary for construction an instance of ``BSpline`` class. + Default is ``not-a-knot``. + + Returns + ------- + b : BSpline object + A new instance representing the initial polynomial + in the B-spline basis. + + Notes + ----- + .. versionadded:: 1.8.0 + + Accepts only ``CubicSpline`` instances for now. + + The algorithm follows from differentiation + the Marsden's identity [1]: each of coefficients of spline + interpolation function in the B-spline basis is computed as follows: + + .. math:: + + c_j = \sum_{m=0}^{k} \frac{(k-m)!}{k!} + c_{m,i} (-1)^{k-m} D^m p_{j,k}(x_i) + + :math:`c_{m, i}` - a coefficient of CubicSpline, + :math:`D^m p_{j, k}(x_i)` - an m-th defivative of a dual polynomial + in :math:`x_i`. + + ``k`` always equals 3 for now. + + First ``n - 2`` coefficients are computed in :math:`x_i = x_j`, e.g. + + .. math:: + + c_1 = \sum_{m=0}^{k} \frac{(k-1)!}{k!} c_{m,1} D^m p_{j,3}(x_1) + + Last ``nod + 2`` coefficients are computed in ``x[-2]``, + ``nod`` - number of derivatives at the ends. + + For example, consider :math:`x = [0, 1, 2, 3, 4]`, + :math:`y = [1, 1, 1, 1, 1]` and bc_type = ``natural`` + + The coefficients of CubicSpline in the power basis: + + :math:`[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], [1, 1, 1, 1, 1]]` + + The knot vector: :math:`t = [0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]` + + In this case + + .. math:: + + c_j = \frac{0!}{k!} c_{3, i} k! = c_{3, i} = 1,~j = 0, ..., 6 + + References + ---------- + .. [1] Tom Lyche and Knut Morken, Spline Methods, 2005, Section 3.1.2 + + """ + from ._cubic import CubicSpline + if not isinstance(pp, CubicSpline): + raise NotImplementedError(f"Only CubicSpline objects are accepted " + f"for now. Got {type(pp)} instead.") + x = pp.x + coef = pp.c + k = pp.c.shape[0] - 1 + n = x.shape[0] + + if bc_type == 'not-a-knot': + t = _not_a_knot(x, k) + elif bc_type == 'natural' or bc_type == 'clamped': + t = _augknt(x, k) + elif bc_type == 'periodic': + t = _periodic_knots(x, k) + else: + raise TypeError(f'Unknown boundary condition: {bc_type}') + + nod = t.shape[0] - (n + k + 1) # number of derivatives at the ends + c = np.zeros(n + nod, dtype=pp.c.dtype) + for m in range(k + 1): + for i in range(n - 2): + c[i] += poch(k + 1, -m) * coef[m, i]\ + * np.power(-1, k - m)\ + * _diff_dual_poly(i, k, x[i], m, t) + for j in range(n - 2, n + nod): + c[j] += poch(k + 1, -m) * coef[m, n - 2]\ + * np.power(-1, k - m)\ + * _diff_dual_poly(j, k, x[n - 2], m, t) + return cls.construct_fast(t, c, k, pp.extrapolate, pp.axis) + + def insert_knot(self, x, m=1): + """Insert a new knot at `x` of multiplicity `m`. + + Given the knots and coefficients of a B-spline representation, create a + new B-spline with a knot inserted `m` times at point `x`. + + Parameters + ---------- + x : float + The position of the new knot + m : int, optional + The number of times to insert the given knot (its multiplicity). + Default is 1. + + Returns + ------- + spl : BSpline object + A new BSpline object with the new knot inserted. + + Notes + ----- + Based on algorithms from [1]_ and [2]_. + + In case of a periodic spline (``self.extrapolate == "periodic"``) + there must be either at least k interior knots t(j) satisfying + ``t(k+1)>> import numpy as np + >>> from scipy.interpolate import BSpline, make_interp_spline + >>> x = np.linspace(0, 10, 5) + >>> y = np.sin(x) + >>> spl = make_interp_spline(x, y, k=3) + >>> spl.t + array([ 0., 0., 0., 0., 5., 10., 10., 10., 10.]) + + Insert a single knot + + >>> spl_1 = spl.insert_knot(3) + >>> spl_1.t + array([ 0., 0., 0., 0., 3., 5., 10., 10., 10., 10.]) + + Insert a multiple knot + + >>> spl_2 = spl.insert_knot(8, m=3) + >>> spl_2.t + array([ 0., 0., 0., 0., 5., 8., 8., 8., 10., 10., 10., 10.]) + + """ + if x < self.t[self.k] or x > self.t[-self.k-1]: + raise ValueError(f"Cannot insert a knot at {x}.") + if m <= 0: + raise ValueError(f"`m` must be positive, got {m = }.") + + tt = self.t.copy() + cc = self.c.copy() + + for _ in range(m): + tt, cc = _insert(x, tt, cc, self.k, self.extrapolate == "periodic") + return self.construct_fast(tt, cc, self.k, self.extrapolate, self.axis) + + +def _insert(xval, t, c, k, periodic=False): + """Insert a single knot at `xval`.""" + # + # This is a port of the FORTRAN `insert` routine by P. Dierckx, + # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/insert.f + # which carries the following comment: + # + # subroutine insert inserts a new knot x into a spline function s(x) + # of degree k and calculates the b-spline representation of s(x) with + # respect to the new set of knots. in addition, if iopt.ne.0, s(x) + # will be considered as a periodic spline with period per=t(n-k)-t(k+1) + # satisfying the boundary constraints + # t(i+n-2*k-1) = t(i)+per ,i=1,2,...,2*k+1 + # c(i+n-2*k-1) = c(i) ,i=1,2,...,k + # in that case, the knots and b-spline coefficients returned will also + # satisfy these boundary constraints, i.e. + # tt(i+nn-2*k-1) = tt(i)+per ,i=1,2,...,2*k+1 + # cc(i+nn-2*k-1) = cc(i) ,i=1,2,...,k + interval = _dierckx.find_interval(t, k, float(xval), k, False) + if interval < 0: + # extrapolated values are guarded for in BSpline.insert_knot + raise ValueError(f"Cannot insert the knot at {xval}.") + + # super edge case: a knot with multiplicity > k+1 + # see https://github.com/scipy/scipy/commit/037204c3e91 + if t[interval] == t[interval + k + 1]: + interval -= 1 + + if periodic: + if (interval + 1 <= 2*k) and (interval + 1 >= t.shape[0] - 2*k): + # in case of a periodic spline (iopt.ne.0) there must be + # either at least k interior knots t(j) satisfying t(k+1)= nk - k: + # adjust the left-hand boundary knots & coefs + tt[:k] = tt[nk - k:nk] - T + cc[:k, ...] = cc[n2k:n2k + k, ...] + + if interval <= 2*k-1: + # adjust the right-hand boundary knots & coefs + tt[n-k:] = tt[k+1:k+1+k] + T + cc[n2k:n2k + k, ...] = cc[:k, ...] + + return tt, cc + + +################################# +# Interpolating spline helpers # +################################# + +def _not_a_knot(x, k): + """Given data x, construct the knot vector w/ not-a-knot BC. + cf de Boor, XIII(12). + + For even k, it's a bit ad hoc: Greville sites + omit 2nd and 2nd-to-last + data points, a la not-a-knot. + This seems to match what Dierckx does, too: + https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L63-L80 + """ + x = np.asarray(x) + if k % 2 == 1: + k2 = (k + 1) // 2 + t = x.copy() + else: + k2 = k // 2 + t = (x[1:] + x[:-1]) / 2 + + t = t[k2:-k2] + t = np.r_[(x[0],)*(k+1), t, (x[-1],)*(k+1)] + return t + + +def _augknt(x, k): + """Construct a knot vector appropriate for the order-k interpolation.""" + return np.r_[(x[0],)*k, x, (x[-1],)*k] + + +def _convert_string_aliases(deriv, target_shape): + if isinstance(deriv, str): + if deriv == "clamped": + deriv = [(1, np.zeros(target_shape))] + elif deriv == "natural": + deriv = [(2, np.zeros(target_shape))] + else: + raise ValueError(f"Unknown boundary condition : {deriv}") + return deriv + + +def _process_deriv_spec(deriv): + if deriv is not None: + try: + ords, vals = zip(*deriv) + except TypeError as e: + msg = ("Derivatives, `bc_type`, should be specified as a pair of " + "iterables of pairs of (order, value).") + raise ValueError(msg) from e + else: + ords, vals = [], [] + return np.atleast_1d(ords, vals) + + +def _woodbury_algorithm(A, ur, ll, b, k): + ''' + Solve a cyclic banded linear system with upper right + and lower blocks of size ``(k-1) / 2`` using + the Woodbury formula + + Parameters + ---------- + A : 2-D array, shape(k, n) + Matrix of diagonals of original matrix (see + ``solve_banded`` documentation). + ur : 2-D array, shape(bs, bs) + Upper right block matrix. + ll : 2-D array, shape(bs, bs) + Lower left block matrix. + b : 1-D array, shape(n,) + Vector of constant terms of the system of linear equations. + k : int + B-spline degree. + + Returns + ------- + c : 1-D array, shape(n,) + Solution of the original system of linear equations. + + Notes + ----- + This algorithm works only for systems with banded matrix A plus + a correction term U @ V.T, where the matrix U @ V.T gives upper right + and lower left block of A + The system is solved with the following steps: + 1. New systems of linear equations are constructed: + A @ z_i = u_i, + u_i - column vector of U, + i = 1, ..., k - 1 + 2. Matrix Z is formed from vectors z_i: + Z = [ z_1 | z_2 | ... | z_{k - 1} ] + 3. Matrix H = (1 + V.T @ Z)^{-1} + 4. The system A' @ y = b is solved + 5. x = y - Z @ (H @ V.T @ y) + Also, ``n`` should be greater than ``k``, otherwise corner block + elements will intersect with diagonals. + + Examples + -------- + Consider the case of n = 8, k = 5 (size of blocks - 2 x 2). + The matrix of a system: U: V: + x x x * * a b a b 0 0 0 0 1 0 + x x x x * * c 0 c 0 0 0 0 0 1 + x x x x x * * 0 0 0 0 0 0 0 0 + * x x x x x * 0 0 0 0 0 0 0 0 + * * x x x x x 0 0 0 0 0 0 0 0 + d * * x x x x 0 0 d 0 1 0 0 0 + e f * * x x x 0 0 e f 0 1 0 0 + + References + ---------- + .. [1] William H. Press, Saul A. Teukolsky, William T. Vetterling + and Brian P. Flannery, Numerical Recipes, 2007, Section 2.7.3 + + ''' + k_mod = k - k % 2 + bs = int((k - 1) / 2) + (k + 1) % 2 + + n = A.shape[1] + 1 + U = np.zeros((n - 1, k_mod)) + VT = np.zeros((k_mod, n - 1)) # V transpose + + # upper right block + U[:bs, :bs] = ur + VT[np.arange(bs), np.arange(bs) - bs] = 1 + + # lower left block + U[-bs:, -bs:] = ll + VT[np.arange(bs) - bs, np.arange(bs)] = 1 + + Z = solve_banded((bs, bs), A, U) + + H = solve(np.identity(k_mod) + VT @ Z, np.identity(k_mod)) + + y = solve_banded((bs, bs), A, b) + c = y - Z @ (H @ (VT @ y)) + + return c + + +def _periodic_knots(x, k): + ''' + returns vector of nodes on circle + ''' + xc = np.copy(x) + n = len(xc) + if k % 2 == 0: + dx = np.diff(xc) + xc[1: -1] -= dx[:-1] / 2 + dx = np.diff(xc) + t = np.zeros(n + 2 * k) + t[k: -k] = xc + for i in range(0, k): + # filling first `k` elements in descending order + t[k - i - 1] = t[k - i] - dx[-(i % (n - 1)) - 1] + # filling last `k` elements in ascending order + t[-k + i] = t[-k + i - 1] + dx[i % (n - 1)] + return t + + +def _make_interp_per_full_matr(x, y, t, k): + ''' + Returns a solution of a system for B-spline interpolation with periodic + boundary conditions. First ``k - 1`` rows of matrix are conditions of + periodicity (continuity of ``k - 1`` derivatives at the boundary points). + Last ``n`` rows are interpolation conditions. + RHS is ``k - 1`` zeros and ``n`` ordinates in this case. + + Parameters + ---------- + x : 1-D array, shape (n,) + Values of x - coordinate of a given set of points. + y : 1-D array, shape (n,) + Values of y - coordinate of a given set of points. + t : 1-D array, shape(n+2*k,) + Vector of knots. + k : int + The maximum degree of spline + + Returns + ------- + c : 1-D array, shape (n+k-1,) + B-spline coefficients + + Notes + ----- + ``t`` is supposed to be taken on circle. + + ''' + + x, y, t = map(np.asarray, (x, y, t)) + + n = x.size + # LHS: the colocation matrix + derivatives at edges + matr = np.zeros((n + k - 1, n + k - 1)) + + # derivatives at x[0] and x[-1]: + for i in range(k - 1): + bb = _dierckx.evaluate_all_bspl(t, k, x[0], k, i + 1) + matr[i, : k + 1] += bb + bb = _dierckx.evaluate_all_bspl(t, k, x[-1], n + k - 1, i + 1)[:-1] + matr[i, -k:] -= bb + + # colocation matrix + for i in range(n): + xval = x[i] + # find interval + if xval == t[k]: + left = k + else: + left = np.searchsorted(t, xval) - 1 + + # fill a row + bb = _dierckx.evaluate_all_bspl(t, k, xval, left) + matr[i + k - 1, left-k:left+1] = bb + + # RHS + b = np.r_[[0] * (k - 1), y] + + c = solve(matr, b) + return c + + +def _handle_lhs_derivatives(t, k, xval, ab, kl, ku, deriv_ords, offset=0): + """ Fill in the entries of the colocation matrix corresponding to known + derivatives at `xval`. + + The colocation matrix is in the banded storage, as prepared by _coloc. + No error checking. + + Parameters + ---------- + t : ndarray, shape (nt + k + 1,) + knots + k : integer + B-spline order + xval : float + The value at which to evaluate the derivatives at. + ab : ndarray, shape(2*kl + ku + 1, nt), Fortran order + B-spline colocation matrix. + This argument is modified *in-place*. + kl : integer + Number of lower diagonals of ab. + ku : integer + Number of upper diagonals of ab. + deriv_ords : 1D ndarray + Orders of derivatives known at xval + offset : integer, optional + Skip this many rows of the matrix ab. + + """ + # find where `xval` is in the knot vector, `t` + left = _dierckx.find_interval(t, k, float(xval), k, False) + + # compute and fill in the derivatives @ xval + for row in range(deriv_ords.shape[0]): + nu = deriv_ords[row] + wrk = _dierckx.evaluate_all_bspl(t, k, xval, left, nu) + + # if A were a full matrix, it would be just + # ``A[row + offset, left-k:left+1] = bb``. + for a in range(k+1): + clmn = left - k + a + ab[kl + ku + offset + row - clmn, clmn] = wrk[a] + + +def _make_periodic_spline(x, y, t, k, axis): + ''' + Compute the (coefficients of) interpolating B-spline with periodic + boundary conditions. + + Parameters + ---------- + x : array_like, shape (n,) + Abscissas. + y : array_like, shape (n,) + Ordinates. + k : int + B-spline degree. + t : array_like, shape (n + 2 * k,). + Knots taken on a circle, ``k`` on the left and ``k`` on the right + of the vector ``x``. + + Returns + ------- + b : a BSpline object of the degree ``k`` and with knots ``t``. + + Notes + ----- + The original system is formed by ``n + k - 1`` equations where the first + ``k - 1`` of them stand for the ``k - 1`` derivatives continuity on the + edges while the other equations correspond to an interpolating case + (matching all the input points). Due to a special form of knot vector, it + can be proved that in the original system the first and last ``k`` + coefficients of a spline function are the same, respectively. It follows + from the fact that all ``k - 1`` derivatives are equal term by term at ends + and that the matrix of the original system of linear equations is + non-degenerate. So, we can reduce the number of equations to ``n - 1`` + (first ``k - 1`` equations could be reduced). Another trick of this + implementation is cyclic shift of values of B-splines due to equality of + ``k`` unknown coefficients. With this we can receive matrix of the system + with upper right and lower left blocks, and ``k`` diagonals. It allows + to use Woodbury formula to optimize the computations. + + ''' + n = y.shape[0] + + extradim = prod(y.shape[1:]) + y_new = y.reshape(n, extradim) + c = np.zeros((n + k - 1, extradim)) + + # n <= k case is solved with full matrix + if n <= k: + for i in range(extradim): + c[:, i] = _make_interp_per_full_matr(x, y_new[:, i], t, k) + c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:])) + return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis) + + nt = len(t) - k - 1 + + # size of block elements + kul = int(k / 2) + + # kl = ku = k + ab = np.zeros((3 * k + 1, nt), dtype=np.float64, order='F') + + # upper right and lower left blocks + ur = np.zeros((kul, kul)) + ll = np.zeros_like(ur) + + # `offset` is made to shift all the non-zero elements to the end of the + # matrix + # NB: 1. drop the last element of `x` because `x[0] = x[-1] + T` & `y[0] == y[-1]` + # 2. pass ab.T to _coloc to make it C-ordered; below it'll be fed to banded + # LAPACK, which needs F-ordered arrays + _dierckx._coloc(x[:-1], t, k, ab.T, k) + + # remove zeros before the matrix + ab = ab[-k - (k + 1) % 2:, :] + + # The least elements in rows (except repetitions) are diagonals + # of block matrices. Upper right matrix is an upper triangular + # matrix while lower left is a lower triangular one. + for i in range(kul): + ur += np.diag(ab[-i - 1, i: kul], k=i) + ll += np.diag(ab[i, -kul - (k % 2): n - 1 + 2 * kul - i], k=-i) + + # remove elements that occur in the last point + # (first and last points are equivalent) + A = ab[:, kul: -k + kul] + + for i in range(extradim): + cc = _woodbury_algorithm(A, ur, ll, y_new[:, i][:-1], k) + c[:, i] = np.concatenate((cc[-kul:], cc, cc[:kul + k % 2])) + c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:])) + return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis) + + +def make_interp_spline(x, y, k=3, t=None, bc_type=None, axis=0, + check_finite=True): + """Compute the (coefficients of) interpolating B-spline. + + Parameters + ---------- + x : array_like, shape (n,) + Abscissas. + y : array_like, shape (n, ...) + Ordinates. + k : int, optional + B-spline degree. Default is cubic, ``k = 3``. + t : array_like, shape (nt + k + 1,), optional. + Knots. + The number of knots needs to agree with the number of data points and + the number of derivatives at the edges. Specifically, ``nt - n`` must + equal ``len(deriv_l) + len(deriv_r)``. + bc_type : 2-tuple or None + Boundary conditions. + Default is None, which means choosing the boundary conditions + automatically. Otherwise, it must be a length-two tuple where the first + element (``deriv_l``) sets the boundary conditions at ``x[0]`` and + the second element (``deriv_r``) sets the boundary conditions at + ``x[-1]``. Each of these must be an iterable of pairs + ``(order, value)`` which gives the values of derivatives of specified + orders at the given edge of the interpolation interval. + Alternatively, the following string aliases are recognized: + + * ``"clamped"``: The first derivatives at the ends are zero. This is + equivalent to ``bc_type=([(1, 0.0)], [(1, 0.0)])``. + * ``"natural"``: The second derivatives at ends are zero. This is + equivalent to ``bc_type=([(2, 0.0)], [(2, 0.0)])``. + * ``"not-a-knot"`` (default): The first and second segments are the + same polynomial. This is equivalent to having ``bc_type=None``. + * ``"periodic"``: The values and the first ``k-1`` derivatives at the + ends are equivalent. + + axis : int, optional + Interpolation axis. Default is 0. + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default is True. + + Returns + ------- + b : a BSpline object of the degree ``k`` and with knots ``t``. + + See Also + -------- + BSpline : base class representing the B-spline objects + CubicSpline : a cubic spline in the polynomial basis + make_lsq_spline : a similar factory function for spline fitting + UnivariateSpline : a wrapper over FITPACK spline fitting routines + splrep : a wrapper over FITPACK spline fitting routines + + Examples + -------- + + Use cubic interpolation on Chebyshev nodes: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> def cheb_nodes(N): + ... jj = 2.*np.arange(N) + 1 + ... x = np.cos(np.pi * jj / 2 / N)[::-1] + ... return x + + >>> x = cheb_nodes(20) + >>> y = np.sqrt(1 - x**2) + + >>> from scipy.interpolate import BSpline, make_interp_spline + >>> b = make_interp_spline(x, y) + >>> np.allclose(b(x), y) + True + + Note that the default is a cubic spline with a not-a-knot boundary condition + + >>> b.k + 3 + + Here we use a 'natural' spline, with zero 2nd derivatives at edges: + + >>> l, r = [(2, 0.0)], [(2, 0.0)] + >>> b_n = make_interp_spline(x, y, bc_type=(l, r)) # or, bc_type="natural" + >>> np.allclose(b_n(x), y) + True + >>> x0, x1 = x[0], x[-1] + >>> np.allclose([b_n(x0, 2), b_n(x1, 2)], [0, 0]) + True + + Interpolation of parametric curves is also supported. As an example, we + compute a discretization of a snail curve in polar coordinates + + >>> phi = np.linspace(0, 2.*np.pi, 40) + >>> r = 0.3 + np.cos(phi) + >>> x, y = r*np.cos(phi), r*np.sin(phi) # convert to Cartesian coordinates + + Build an interpolating curve, parameterizing it by the angle + + >>> spl = make_interp_spline(phi, np.c_[x, y]) + + Evaluate the interpolant on a finer grid (note that we transpose the result + to unpack it into a pair of x- and y-arrays) + + >>> phi_new = np.linspace(0, 2.*np.pi, 100) + >>> x_new, y_new = spl(phi_new).T + + Plot the result + + >>> plt.plot(x, y, 'o') + >>> plt.plot(x_new, y_new, '-') + >>> plt.show() + + Build a B-spline curve with 2 dimensional y + + >>> x = np.linspace(0, 2*np.pi, 10) + >>> y = np.array([np.sin(x), np.cos(x)]) + + Periodic condition is satisfied because y coordinates of points on the ends + are equivalent + + >>> ax = plt.axes(projection='3d') + >>> xx = np.linspace(0, 2*np.pi, 100) + >>> bspl = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1) + >>> ax.plot3D(xx, *bspl(xx)) + >>> ax.scatter3D(x, *y, color='red') + >>> plt.show() + + """ + # convert string aliases for the boundary conditions + if bc_type is None or bc_type == 'not-a-knot' or bc_type == 'periodic': + deriv_l, deriv_r = None, None + elif isinstance(bc_type, str): + deriv_l, deriv_r = bc_type, bc_type + else: + try: + deriv_l, deriv_r = bc_type + except TypeError as e: + raise ValueError(f"Unknown boundary condition: {bc_type}") from e + + y = np.asarray(y) + + axis = normalize_axis_index(axis, y.ndim) + + x = _as_float_array(x, check_finite) + y = _as_float_array(y, check_finite) + + y = np.moveaxis(y, axis, 0) # now internally interp axis is zero + + # sanity check the input + if bc_type == 'periodic' and not np.allclose(y[0], y[-1], atol=1e-15): + raise ValueError("First and last points does not match while " + "periodic case expected") + if x.size != y.shape[0]: + raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible') + if np.any(x[1:] == x[:-1]): + raise ValueError("Expect x to not have duplicates") + if x.ndim != 1 or np.any(x[1:] < x[:-1]): + raise ValueError("Expect x to be a 1D strictly increasing sequence.") + + # special-case k=0 right away + if k == 0: + if any(_ is not None for _ in (t, deriv_l, deriv_r)): + raise ValueError("Too much info for k=0: t and bc_type can only " + "be None.") + t = np.r_[x, x[-1]] + c = np.asarray(y) + c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype)) + return BSpline.construct_fast(t, c, k, axis=axis) + + # special-case k=1 (e.g., Lyche and Morken, Eq.(2.16)) + if k == 1 and t is None: + if not (deriv_l is None and deriv_r is None): + raise ValueError("Too much info for k=1: bc_type can only be None.") + t = np.r_[x[0], x, x[-1]] + c = np.asarray(y) + c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype)) + return BSpline.construct_fast(t, c, k, axis=axis) + + k = operator.index(k) + + if bc_type == 'periodic' and t is not None: + raise NotImplementedError("For periodic case t is constructed " + "automatically and can not be passed " + "manually") + + # come up with a sensible knot vector, if needed + if t is None: + if deriv_l is None and deriv_r is None: + if bc_type == 'periodic': + t = _periodic_knots(x, k) + else: + t = _not_a_knot(x, k) + else: + t = _augknt(x, k) + + t = _as_float_array(t, check_finite) + + if k < 0: + raise ValueError("Expect non-negative k.") + if t.ndim != 1 or np.any(t[1:] < t[:-1]): + raise ValueError("Expect t to be a 1-D sorted array_like.") + if t.size < x.size + k + 1: + raise ValueError('Got %d knots, need at least %d.' % + (t.size, x.size + k + 1)) + if (x[0] < t[k]) or (x[-1] > t[-k]): + raise ValueError(f'Out of bounds w/ x = {x}.') + + if bc_type == 'periodic': + return _make_periodic_spline(x, y, t, k, axis) + + # Here : deriv_l, r = [(nu, value), ...] + deriv_l = _convert_string_aliases(deriv_l, y.shape[1:]) + deriv_l_ords, deriv_l_vals = _process_deriv_spec(deriv_l) + nleft = deriv_l_ords.shape[0] + + deriv_r = _convert_string_aliases(deriv_r, y.shape[1:]) + deriv_r_ords, deriv_r_vals = _process_deriv_spec(deriv_r) + nright = deriv_r_ords.shape[0] + + if not all(0 <= i <= k for i in deriv_l_ords): + raise ValueError(f"Bad boundary conditions at {x[0]}.") + + if not all(0 <= i <= k for i in deriv_r_ords): + raise ValueError(f"Bad boundary conditions at {x[-1]}.") + + # have `n` conditions for `nt` coefficients; need nt-n derivatives + n = x.size + nt = t.size - k - 1 + + if nt - n != nleft + nright: + raise ValueError("The number of derivatives at boundaries does not " + f"match: expected {nt-n}, got {nleft}+{nright}") + + # bail out if the `y` array is zero-sized + if y.size == 0: + c = np.zeros((nt,) + y.shape[1:], dtype=float) + return BSpline.construct_fast(t, c, k, axis=axis) + + # set up the LHS: the colocation matrix + derivatives at boundaries + # NB: ab is in F order for banded LAPACK; _coloc needs C-ordered arrays, + # this pass ab.T into _coloc + kl = ku = k + ab = np.zeros((2*kl + ku + 1, nt), dtype=np.float64, order='F') + _dierckx._coloc(x, t, k, ab.T, nleft) + if nleft > 0: + _handle_lhs_derivatives(t, k, x[0], ab, kl, ku, deriv_l_ords) + if nright > 0: + _handle_lhs_derivatives(t, k, x[-1], ab, kl, ku, deriv_r_ords, + offset=nt-nright) + + # set up the RHS: values to interpolate (+ derivative values, if any) + extradim = prod(y.shape[1:]) + rhs = np.empty((nt, extradim), dtype=y.dtype) + if nleft > 0: + rhs[:nleft] = deriv_l_vals.reshape(-1, extradim) + rhs[nleft:nt - nright] = y.reshape(-1, extradim) + if nright > 0: + rhs[nt - nright:] = deriv_r_vals.reshape(-1, extradim) + + # solve Ab @ x = rhs; this is the relevant part of linalg.solve_banded + if check_finite: + ab, rhs = map(np.asarray_chkfinite, (ab, rhs)) + gbsv, = get_lapack_funcs(('gbsv',), (ab, rhs)) + lu, piv, c, info = gbsv(kl, ku, ab, rhs, + overwrite_ab=True, overwrite_b=True) + + if info > 0: + raise LinAlgError("Colocation matrix is singular.") + elif info < 0: + raise ValueError('illegal value in %d-th argument of internal gbsv' % -info) + + c = np.ascontiguousarray(c.reshape((nt,) + y.shape[1:])) + return BSpline.construct_fast(t, c, k, axis=axis) + + +def make_lsq_spline(x, y, t, k=3, w=None, axis=0, check_finite=True, *, method="qr"): + r"""Compute the (coefficients of) an LSQ (Least SQuared) based + fitting B-spline. + + The result is a linear combination + + .. math:: + + S(x) = \sum_j c_j B_j(x; t) + + of the B-spline basis elements, :math:`B_j(x; t)`, which minimizes + + .. math:: + + \sum_{j} \left( w_j \times (S(x_j) - y_j) \right)^2 + + Parameters + ---------- + x : array_like, shape (m,) + Abscissas. + y : array_like, shape (m, ...) + Ordinates. + t : array_like, shape (n + k + 1,). + Knots. + Knots and data points must satisfy Schoenberg-Whitney conditions. + k : int, optional + B-spline degree. Default is cubic, ``k = 3``. + w : array_like, shape (m,), optional + Weights for spline fitting. Must be positive. If ``None``, + then weights are all equal. + Default is ``None``. + axis : int, optional + Interpolation axis. Default is zero. + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default is True. + method : str, optional + Method for solving the linear LSQ problem. Allowed values are "norm-eq" + (Explicitly construct and solve the normal system of equations), and + "qr" (Use the QR factorization of the design matrix). + Default is "qr". + + Returns + ------- + b : a BSpline object of the degree ``k`` with knots ``t``. + + See Also + -------- + BSpline : base class representing the B-spline objects + make_interp_spline : a similar factory function for interpolating splines + LSQUnivariateSpline : a FITPACK-based spline fitting routine + splrep : a FITPACK-based fitting routine + + Notes + ----- + The number of data points must be larger than the spline degree ``k``. + + Knots ``t`` must satisfy the Schoenberg-Whitney conditions, + i.e., there must be a subset of data points ``x[j]`` such that + ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``. + + Examples + -------- + Generate some noisy data: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + + Now fit a smoothing cubic spline with a pre-defined internal knots. + Here we make the knot vector (k+1)-regular by adding boundary knots: + + >>> from scipy.interpolate import make_lsq_spline, BSpline + >>> t = [-1, 0, 1] + >>> k = 3 + >>> t = np.r_[(x[0],)*(k+1), + ... t, + ... (x[-1],)*(k+1)] + >>> spl = make_lsq_spline(x, y, t, k) + + For comparison, we also construct an interpolating spline for the same + set of data: + + >>> from scipy.interpolate import make_interp_spline + >>> spl_i = make_interp_spline(x, y) + + Plot both: + + >>> xs = np.linspace(-3, 3, 100) + >>> plt.plot(x, y, 'ro', ms=5) + >>> plt.plot(xs, spl(xs), 'g-', lw=3, label='LSQ spline') + >>> plt.plot(xs, spl_i(xs), 'b-', lw=3, alpha=0.7, label='interp spline') + >>> plt.legend(loc='best') + >>> plt.show() + + **NaN handling**: If the input arrays contain ``nan`` values, the result is + not useful since the underlying spline fitting routines cannot deal with + ``nan``. A workaround is to use zero weights for not-a-number data points: + + >>> y[8] = np.nan + >>> w = np.isnan(y) + >>> y[w] = 0. + >>> tck = make_lsq_spline(x, y, t, w=~w) + + Notice the need to replace a ``nan`` by a numerical value (precise value + does not matter as long as the corresponding weight is zero.) + + """ + x = _as_float_array(x, check_finite) + y = _as_float_array(y, check_finite) + t = _as_float_array(t, check_finite) + if w is not None: + w = _as_float_array(w, check_finite) + else: + w = np.ones_like(x) + k = operator.index(k) + + axis = normalize_axis_index(axis, y.ndim) + + y = np.moveaxis(y, axis, 0) # now internally interp axis is zero + + if x.ndim != 1: + raise ValueError("Expect x to be a 1-D sequence.") + if x.shape[0] < k+1: + raise ValueError("Need more x points.") + if k < 0: + raise ValueError("Expect non-negative k.") + if t.ndim != 1 or np.any(t[1:] - t[:-1] < 0): + raise ValueError("Expect t to be a 1D strictly increasing sequence.") + if x.size != y.shape[0]: + raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible') + if k > 0 and np.any((x < t[k]) | (x > t[-k])): + raise ValueError(f'Out of bounds w/ x = {x}.') + if x.size != w.size: + raise ValueError(f'Shapes of x {x.shape} and w {w.shape} are incompatible') + if method == "norm-eq" and np.any(x[1:] - x[:-1] <= 0): + raise ValueError("Expect x to be a 1D strictly increasing sequence.") + if method == "qr" and any(x[1:] - x[:-1] < 0): + raise ValueError("Expect x to be a 1D non-decreasing sequence.") + + # number of coefficients + n = t.size - k - 1 + + # complex y: view as float, preserve the length + was_complex = y.dtype.kind == 'c' + yy = y.view(float) + if was_complex and y.ndim == 1: + yy = yy.reshape(y.shape[0], 2) + + # multiple r.h.s + extradim = prod(yy.shape[1:]) + yy = yy.reshape(-1, extradim) + + # complex y: view as float, preserve the length + was_complex = y.dtype.kind == 'c' + yy = y.view(float) + if was_complex and y.ndim == 1: + yy = yy.reshape(y.shape[0], 2) + + # multiple r.h.s + extradim = prod(yy.shape[1:]) + yy = yy.reshape(-1, extradim) + + if method == "norm-eq": + # construct A.T @ A and rhs with A the colocation matrix, and + # rhs = A.T @ y for solving the LSQ problem ``A.T @ A @ c = A.T @ y`` + lower = True + ab = np.zeros((k+1, n), dtype=np.float64, order='F') + rhs = np.zeros((n, extradim), dtype=np.float64) + _dierckx._norm_eq_lsq(x, t, k, + yy, + w, + ab.T, rhs) + + # undo complex -> float and flattening the trailing dims + if was_complex: + rhs = rhs.view(complex) + + rhs = rhs.reshape((n,) + y.shape[1:]) + + # have observation matrix & rhs, can solve the LSQ problem + cho_decomp = cholesky_banded(ab, overwrite_ab=True, lower=lower, + check_finite=check_finite) + c = cho_solve_banded((cho_decomp, lower), rhs, overwrite_b=True, + check_finite=check_finite) + elif method == "qr": + _, _, c = _lsq_solve_qr(x, yy, t, k, w) + + if was_complex: + c = c.view(complex) + + else: + raise ValueError(f"Unknown {method =}.") + + + # restore the shape of `c` for both single and multiple r.h.s. + c = c.reshape((n,) + y.shape[1:]) + c = np.ascontiguousarray(c) + return BSpline.construct_fast(t, c, k, axis=axis) + + +###################### +# LSQ spline helpers # +###################### + +def _lsq_solve_qr(x, y, t, k, w): + """Solve for the LSQ spline coeffs given x, y and knots. + + `y` is always 2D: for 1D data, the shape is ``(m, 1)``. + `w` is always 1D: one weight value per `x` value. + + """ + assert y.ndim == 2 + + y_w = y * w[:, None] + A, offset, nc = _dierckx.data_matrix(x, t, k, w) + _dierckx.qr_reduce(A, offset, nc, y_w) # modifies arguments in-place + c = _dierckx.fpback(A, nc, y_w) + + return A, y_w, c + + +############################# +# Smoothing spline helpers # +############################# + +def _compute_optimal_gcv_parameter(X, wE, y, w): + """ + Returns an optimal regularization parameter from the GCV criteria [1]. + + Parameters + ---------- + X : array, shape (5, n) + 5 bands of the design matrix ``X`` stored in LAPACK banded storage. + wE : array, shape (5, n) + 5 bands of the penalty matrix :math:`W^{-1} E` stored in LAPACK banded + storage. + y : array, shape (n,) + Ordinates. + w : array, shape (n,) + Vector of weights. + + Returns + ------- + lam : float + An optimal from the GCV criteria point of view regularization + parameter. + + Notes + ----- + No checks are performed. + + References + ---------- + .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models + for observational data, Philadelphia, Pennsylvania: Society for + Industrial and Applied Mathematics, 1990, pp. 45-65. + :doi:`10.1137/1.9781611970128` + + """ + + def compute_banded_symmetric_XT_W_Y(X, w, Y): + """ + Assuming that the product :math:`X^T W Y` is symmetric and both ``X`` + and ``Y`` are 5-banded, compute the unique bands of the product. + + Parameters + ---------- + X : array, shape (5, n) + 5 bands of the matrix ``X`` stored in LAPACK banded storage. + w : array, shape (n,) + Array of weights + Y : array, shape (5, n) + 5 bands of the matrix ``Y`` stored in LAPACK banded storage. + + Returns + ------- + res : array, shape (4, n) + The result of the product :math:`X^T Y` stored in the banded way. + + Notes + ----- + As far as the matrices ``X`` and ``Y`` are 5-banded, their product + :math:`X^T W Y` is 7-banded. It is also symmetric, so we can store only + unique diagonals. + + """ + # compute W Y + W_Y = np.copy(Y) + + W_Y[2] *= w + for i in range(2): + W_Y[i, 2 - i:] *= w[:-2 + i] + W_Y[3 + i, :-1 - i] *= w[1 + i:] + + n = X.shape[1] + res = np.zeros((4, n)) + for i in range(n): + for j in range(min(n-i, 4)): + res[-j-1, i + j] = sum(X[j:, i] * W_Y[:5-j, i + j]) + return res + + def compute_b_inv(A): + """ + Inverse 3 central bands of matrix :math:`A=U^T D^{-1} U` assuming that + ``U`` is a unit upper triangular banded matrix using an algorithm + proposed in [1]. + + Parameters + ---------- + A : array, shape (4, n) + Matrix to inverse, stored in LAPACK banded storage. + + Returns + ------- + B : array, shape (4, n) + 3 unique bands of the symmetric matrix that is an inverse to ``A``. + The first row is filled with zeros. + + Notes + ----- + The algorithm is based on the cholesky decomposition and, therefore, + in case matrix ``A`` is close to not positive defined, the function + raises LinalgError. + + Both matrices ``A`` and ``B`` are stored in LAPACK banded storage. + + References + ---------- + .. [1] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with + spline functions," Numerische Mathematik, vol. 47, no. 1, + pp. 99-106, 1985. + :doi:`10.1007/BF01389878` + + """ + + def find_b_inv_elem(i, j, U, D, B): + rng = min(3, n - i - 1) + rng_sum = 0. + if j == 0: + # use 2-nd formula from [1] + for k in range(1, rng + 1): + rng_sum -= U[-k - 1, i + k] * B[-k - 1, i + k] + rng_sum += D[i] + B[-1, i] = rng_sum + else: + # use 1-st formula from [1] + for k in range(1, rng + 1): + diag = abs(k - j) + ind = i + min(k, j) + rng_sum -= U[-k - 1, i + k] * B[-diag - 1, ind + diag] + B[-j - 1, i + j] = rng_sum + + U = cholesky_banded(A) + for i in range(2, 5): + U[-i, i-1:] /= U[-1, :-i+1] + D = 1. / (U[-1])**2 + U[-1] /= U[-1] + + n = U.shape[1] + + B = np.zeros(shape=(4, n)) + for i in range(n - 1, -1, -1): + for j in range(min(3, n - i - 1), -1, -1): + find_b_inv_elem(i, j, U, D, B) + # the first row contains garbage and should be removed + B[0] = [0.] * n + return B + + def _gcv(lam, X, XtWX, wE, XtE): + r""" + Computes the generalized cross-validation criteria [1]. + + Parameters + ---------- + lam : float, (:math:`\lambda \geq 0`) + Regularization parameter. + X : array, shape (5, n) + Matrix is stored in LAPACK banded storage. + XtWX : array, shape (4, n) + Product :math:`X^T W X` stored in LAPACK banded storage. + wE : array, shape (5, n) + Matrix :math:`W^{-1} E` stored in LAPACK banded storage. + XtE : array, shape (4, n) + Product :math:`X^T E` stored in LAPACK banded storage. + + Returns + ------- + res : float + Value of the GCV criteria with the regularization parameter + :math:`\lambda`. + + Notes + ----- + Criteria is computed from the formula (1.3.2) [3]: + + .. math: + + GCV(\lambda) = \dfrac{1}{n} \sum\limits_{k = 1}^{n} \dfrac{ \left( + y_k - f_{\lambda}(x_k) \right)^2}{\left( 1 - \Tr{A}/n\right)^2}$. + The criteria is discussed in section 1.3 [3]. + + The numerator is computed using (2.2.4) [3] and the denominator is + computed using an algorithm from [2] (see in the ``compute_b_inv`` + function). + + References + ---------- + .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models + for observational data, Philadelphia, Pennsylvania: Society for + Industrial and Applied Mathematics, 1990, pp. 45-65. + :doi:`10.1137/1.9781611970128` + .. [2] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with + spline functions," Numerische Mathematik, vol. 47, no. 1, + pp. 99-106, 1985. + :doi:`10.1007/BF01389878` + .. [3] E. Zemlyanoy, "Generalized cross-validation smoothing splines", + BSc thesis, 2022. Might be available (in Russian) + `here `_ + + """ + # Compute the numerator from (2.2.4) [3] + n = X.shape[1] + c = solve_banded((2, 2), X + lam * wE, y) + res = np.zeros(n) + # compute ``W^{-1} E c`` with respect to banded-storage of ``E`` + tmp = wE * c + for i in range(n): + for j in range(max(0, i - n + 3), min(5, i + 3)): + res[i] += tmp[j, i + 2 - j] + numer = np.linalg.norm(lam * res)**2 / n + + # compute the denominator + lhs = XtWX + lam * XtE + try: + b_banded = compute_b_inv(lhs) + # compute the trace of the product b_banded @ XtX + tr = b_banded * XtWX + tr[:-1] *= 2 + # find the denominator + denom = (1 - sum(sum(tr)) / n)**2 + except LinAlgError: + # cholesky decomposition cannot be performed + raise ValueError('Seems like the problem is ill-posed') + + res = numer / denom + + return res + + n = X.shape[1] + + XtWX = compute_banded_symmetric_XT_W_Y(X, w, X) + XtE = compute_banded_symmetric_XT_W_Y(X, w, wE) + + def fun(lam): + return _gcv(lam, X, XtWX, wE, XtE) + + gcv_est = minimize_scalar(fun, bounds=(0, n), method='Bounded') + if gcv_est.success: + return gcv_est.x + raise ValueError(f"Unable to find minimum of the GCV " + f"function: {gcv_est.message}") + + +def _coeff_of_divided_diff(x): + """ + Returns the coefficients of the divided difference. + + Parameters + ---------- + x : array, shape (n,) + Array which is used for the computation of divided difference. + + Returns + ------- + res : array_like, shape (n,) + Coefficients of the divided difference. + + Notes + ----- + Vector ``x`` should have unique elements, otherwise an error division by + zero might be raised. + + No checks are performed. + + """ + n = x.shape[0] + res = np.zeros(n) + for i in range(n): + pp = 1. + for k in range(n): + if k != i: + pp *= (x[i] - x[k]) + res[i] = 1. / pp + return res + + +def make_smoothing_spline(x, y, w=None, lam=None): + r""" + Compute the (coefficients of) smoothing cubic spline function using + ``lam`` to control the tradeoff between the amount of smoothness of the + curve and its proximity to the data. In case ``lam`` is None, using the + GCV criteria [1] to find it. + + A smoothing spline is found as a solution to the regularized weighted + linear regression problem: + + .. math:: + + \sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2 + + \lambda\int\limits_{x_1}^{x_n} (f^{(2)}(u))^2 d u + + where :math:`f` is a spline function, :math:`w` is a vector of weights and + :math:`\lambda` is a regularization parameter. + + If ``lam`` is None, we use the GCV criteria to find an optimal + regularization parameter, otherwise we solve the regularized weighted + linear regression problem with given parameter. The parameter controls + the tradeoff in the following way: the larger the parameter becomes, the + smoother the function gets. + + Parameters + ---------- + x : array_like, shape (n,) + Abscissas. `n` must be at least 5. + y : array_like, shape (n,) + Ordinates. `n` must be at least 5. + w : array_like, shape (n,), optional + Vector of weights. Default is ``np.ones_like(x)``. + lam : float, (:math:`\lambda \geq 0`), optional + Regularization parameter. If ``lam`` is None, then it is found from + the GCV criteria. Default is None. + + Returns + ------- + func : a BSpline object. + A callable representing a spline in the B-spline basis + as a solution of the problem of smoothing splines using + the GCV criteria [1] in case ``lam`` is None, otherwise using the + given parameter ``lam``. + + Notes + ----- + This algorithm is a clean room reimplementation of the algorithm + introduced by Woltring in FORTRAN [2]. The original version cannot be used + in SciPy source code because of the license issues. The details of the + reimplementation are discussed here (available only in Russian) [4]. + + If the vector of weights ``w`` is None, we assume that all the points are + equal in terms of weights, and vector of weights is vector of ones. + + Note that in weighted residual sum of squares, weights are not squared: + :math:`\sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2` while in + ``splrep`` the sum is built from the squared weights. + + In cases when the initial problem is ill-posed (for example, the product + :math:`X^T W X` where :math:`X` is a design matrix is not a positive + defined matrix) a ValueError is raised. + + References + ---------- + .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models for + observational data, Philadelphia, Pennsylvania: Society for Industrial + and Applied Mathematics, 1990, pp. 45-65. + :doi:`10.1137/1.9781611970128` + .. [2] H. J. Woltring, A Fortran package for generalized, cross-validatory + spline smoothing and differentiation, Advances in Engineering + Software, vol. 8, no. 2, pp. 104-113, 1986. + :doi:`10.1016/0141-1195(86)90098-7` + .. [3] T. Hastie, J. Friedman, and R. Tisbshirani, "Smoothing Splines" in + The elements of Statistical Learning: Data Mining, Inference, and + prediction, New York: Springer, 2017, pp. 241-249. + :doi:`10.1007/978-0-387-84858-7` + .. [4] E. Zemlyanoy, "Generalized cross-validation smoothing splines", + BSc thesis, 2022. + ``_ (in + Russian) + + Examples + -------- + Generate some noisy data + + >>> import numpy as np + >>> np.random.seed(1234) + >>> n = 200 + >>> def func(x): + ... return x**3 + x**2 * np.sin(4 * x) + >>> x = np.sort(np.random.random_sample(n) * 4 - 2) + >>> y = func(x) + np.random.normal(scale=1.5, size=n) + + Make a smoothing spline function + + >>> from scipy.interpolate import make_smoothing_spline + >>> spl = make_smoothing_spline(x, y) + + Plot both + + >>> import matplotlib.pyplot as plt + >>> grid = np.linspace(x[0], x[-1], 400) + >>> plt.plot(grid, spl(grid), label='Spline') + >>> plt.plot(grid, func(grid), label='Original function') + >>> plt.scatter(x, y, marker='.') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + + x = np.ascontiguousarray(x, dtype=float) + y = np.ascontiguousarray(y, dtype=float) + + if any(x[1:] - x[:-1] <= 0): + raise ValueError('``x`` should be an ascending array') + + if x.ndim != 1 or y.ndim != 1 or x.shape[0] != y.shape[0]: + raise ValueError('``x`` and ``y`` should be one dimensional and the' + ' same size') + + if w is None: + w = np.ones(len(x)) + else: + w = np.ascontiguousarray(w) + if any(w <= 0): + raise ValueError('Invalid vector of weights') + + t = np.r_[[x[0]] * 3, x, [x[-1]] * 3] + n = x.shape[0] + + if n <= 4: + raise ValueError('``x`` and ``y`` length must be at least 5') + + # It is known that the solution to the stated minimization problem exists + # and is a natural cubic spline with vector of knots equal to the unique + # elements of ``x`` [3], so we will solve the problem in the basis of + # natural splines. + + # create design matrix in the B-spline basis + X_bspl = BSpline.design_matrix(x, t, 3) + # move from B-spline basis to the basis of natural splines using equations + # (2.1.7) [4] + # central elements + X = np.zeros((5, n)) + for i in range(1, 4): + X[i, 2: -2] = X_bspl[i: i - 4, 3: -3][np.diag_indices(n - 4)] + + # first elements + X[1, 1] = X_bspl[0, 0] + X[2, :2] = ((x[2] + x[1] - 2 * x[0]) * X_bspl[0, 0], + X_bspl[1, 1] + X_bspl[1, 2]) + X[3, :2] = ((x[2] - x[0]) * X_bspl[1, 1], X_bspl[2, 2]) + + # last elements + X[1, -2:] = (X_bspl[-3, -3], (x[-1] - x[-3]) * X_bspl[-2, -2]) + X[2, -2:] = (X_bspl[-2, -3] + X_bspl[-2, -2], + (2 * x[-1] - x[-2] - x[-3]) * X_bspl[-1, -1]) + X[3, -2] = X_bspl[-1, -1] + + # create penalty matrix and divide it by vector of weights: W^{-1} E + wE = np.zeros((5, n)) + wE[2:, 0] = _coeff_of_divided_diff(x[:3]) / w[:3] + wE[1:, 1] = _coeff_of_divided_diff(x[:4]) / w[:4] + for j in range(2, n - 2): + wE[:, j] = (x[j+2] - x[j-2]) * _coeff_of_divided_diff(x[j-2:j+3])\ + / w[j-2: j+3] + + wE[:-1, -2] = -_coeff_of_divided_diff(x[-4:]) / w[-4:] + wE[:-2, -1] = _coeff_of_divided_diff(x[-3:]) / w[-3:] + wE *= 6 + + if lam is None: + lam = _compute_optimal_gcv_parameter(X, wE, y, w) + elif lam < 0.: + raise ValueError('Regularization parameter should be non-negative') + + # solve the initial problem in the basis of natural splines + c = solve_banded((2, 2), X + lam * wE, y) + # move back to B-spline basis using equations (2.2.10) [4] + c_ = np.r_[c[0] * (t[5] + t[4] - 2 * t[3]) + c[1], + c[0] * (t[5] - t[3]) + c[1], + c[1: -1], + c[-1] * (t[-4] - t[-6]) + c[-2], + c[-1] * (2 * t[-4] - t[-5] - t[-6]) + c[-2]] + + return BSpline.construct_fast(t, c_, 3) + + +######################## +# FITPACK look-alikes # +######################## + +def fpcheck(x, t, k): + """ Check consistency of the data vector `x` and the knot vector `t`. + + Return None if inputs are consistent, raises a ValueError otherwise. + """ + # This routine is a clone of the `fpchec` Fortran routine, + # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f + # which carries the following comment: + # + # subroutine fpchec verifies the number and the position of the knots + # t(j),j=1,2,...,n of a spline of degree k, in relation to the number + # and the position of the data points x(i),i=1,2,...,m. if all of the + # following conditions are fulfilled, the error parameter ier is set + # to zero. if one of the conditions is violated ier is set to ten. + # 1) k+1 <= n-k-1 <= m + # 2) t(1) <= t(2) <= ... <= t(k+1) + # t(n-k) <= t(n-k+1) <= ... <= t(n) + # 3) t(k+1) < t(k+2) < ... < t(n-k) + # 4) t(k+1) <= x(i) <= t(n-k) + # 5) the conditions specified by schoenberg and whitney must hold + # for at least one subset of data points, i.e. there must be a + # subset of data points y(j) such that + # t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 + x = np.asarray(x) + t = np.asarray(t) + + if x.ndim != 1 or t.ndim != 1: + raise ValueError(f"Expect `x` and `t` be 1D sequences. Got {x = } and {t = }") + + m = x.shape[0] + n = t.shape[0] + nk1 = n - k - 1 + + # check condition no 1 + # c 1) k+1 <= n-k-1 <= m + if not (k + 1 <= nk1 <= m): + raise ValueError(f"Need k+1 <= n-k-1 <= m. Got {m = }, {n = } and {k = }.") + + # check condition no 2 + # c 2) t(1) <= t(2) <= ... <= t(k+1) + # c t(n-k) <= t(n-k+1) <= ... <= t(n) + if (t[:k+1] > t[1:k+2]).any(): + raise ValueError(f"First k knots must be ordered; got {t = }.") + + if (t[nk1:] < t[nk1-1:-1]).any(): + raise ValueError(f"Last k knots must be ordered; got {t = }.") + + # c check condition no 3 + # c 3) t(k+1) < t(k+2) < ... < t(n-k) + if (t[k+1:n-k] <= t[k:n-k-1]).any(): + raise ValueError(f"Internal knots must be distinct. Got {t = }.") + + # c check condition no 4 + # c 4) t(k+1) <= x(i) <= t(n-k) + # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow. + if (x[0] < t[k]) or (x[-1] > t[n-k-1]): + raise ValueError(f"Out of bounds: {x = } and {t = }.") + + # c check condition no 5 + # c 5) the conditions specified by schoenberg and whitney must hold + # c for at least one subset of data points, i.e. there must be a + # c subset of data points y(j) such that + # c t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 + mesg = f"Schoenberg-Whitney condition is violated with {t = } and {x =}." + + if (x[0] >= t[k+1]) or (x[-1] <= t[n-k-2]): + raise ValueError(mesg) + + m = x.shape[0] + l = k+1 + nk3 = n - k - 3 + if nk3 < 2: + return + for j in range(1, nk3+1): + tj = t[j] + l += 1 + tl = t[l] + i = np.argmax(x > tj) + if i >= m-1: + raise ValueError(mesg) + if x[i] >= tl: + raise ValueError(mesg) + return diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py new file mode 100644 index 0000000000000000000000000000000000000000..3139e145916fa0637552331974ce531da625836f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py @@ -0,0 +1,958 @@ +"""Interpolation algorithms using piecewise cubic polynomials.""" + +from typing import Literal + +import numpy as np + +from scipy.linalg import solve, solve_banded + +from . import PPoly +from ._polyint import _isscalar + +__all__ = ["CubicHermiteSpline", "PchipInterpolator", "pchip_interpolate", + "Akima1DInterpolator", "CubicSpline"] + + +def prepare_input(x, y, axis, dydx=None): + """Prepare input for cubic spline interpolators. + + All data are converted to numpy arrays and checked for correctness. + Axes equal to `axis` of arrays `y` and `dydx` are moved to be the 0th + axis. The value of `axis` is converted to lie in + [0, number of dimensions of `y`). + """ + + x, y = map(np.asarray, (x, y)) + if np.issubdtype(x.dtype, np.complexfloating): + raise ValueError("`x` must contain real values.") + x = x.astype(float) + + if np.issubdtype(y.dtype, np.complexfloating): + dtype = complex + else: + dtype = float + + if dydx is not None: + dydx = np.asarray(dydx) + if y.shape != dydx.shape: + raise ValueError("The shapes of `y` and `dydx` must be identical.") + if np.issubdtype(dydx.dtype, np.complexfloating): + dtype = complex + dydx = dydx.astype(dtype, copy=False) + + y = y.astype(dtype, copy=False) + axis = axis % y.ndim + if x.ndim != 1: + raise ValueError("`x` must be 1-dimensional.") + if x.shape[0] < 2: + raise ValueError("`x` must contain at least 2 elements.") + if x.shape[0] != y.shape[axis]: + raise ValueError(f"The length of `y` along `axis`={axis} doesn't " + "match the length of `x`") + + if not np.all(np.isfinite(x)): + raise ValueError("`x` must contain only finite values.") + if not np.all(np.isfinite(y)): + raise ValueError("`y` must contain only finite values.") + + if dydx is not None and not np.all(np.isfinite(dydx)): + raise ValueError("`dydx` must contain only finite values.") + + dx = np.diff(x) + if np.any(dx <= 0): + raise ValueError("`x` must be strictly increasing sequence.") + + y = np.moveaxis(y, axis, 0) + if dydx is not None: + dydx = np.moveaxis(dydx, axis, 0) + + return x, dx, y, axis, dydx + + +class CubicHermiteSpline(PPoly): + """Piecewise-cubic interpolator matching values and first derivatives. + + The result is represented as a `PPoly` instance. + + Parameters + ---------- + x : array_like, shape (n,) + 1-D array containing values of the independent variable. + Values must be real, finite and in strictly increasing order. + y : array_like + Array containing values of the dependent variable. It can have + arbitrary number of dimensions, but the length along ``axis`` + (see below) must match the length of ``x``. Values must be finite. + dydx : array_like + Array containing derivatives of the dependent variable. It can have + arbitrary number of dimensions, but the length along ``axis`` + (see below) must match the length of ``x``. Values must be finite. + axis : int, optional + Axis along which `y` is assumed to be varying. Meaning that for + ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``. + Default is 0. + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. If 'periodic', + periodic extrapolation is used. If None (default), it is set to True. + + Attributes + ---------- + x : ndarray, shape (n,) + Breakpoints. The same ``x`` which was passed to the constructor. + c : ndarray, shape (4, n-1, ...) + Coefficients of the polynomials on each segment. The trailing + dimensions match the dimensions of `y`, excluding ``axis``. + For example, if `y` is 1-D, then ``c[k, i]`` is a coefficient for + ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``. + axis : int + Interpolation axis. The same axis which was passed to the + constructor. + + Methods + ------- + __call__ + derivative + antiderivative + integrate + roots + + See Also + -------- + Akima1DInterpolator : Akima 1D interpolator. + PchipInterpolator : PCHIP 1-D monotonic cubic interpolator. + CubicSpline : Cubic spline data interpolator. + PPoly : Piecewise polynomial in terms of coefficients and breakpoints + + Notes + ----- + If you want to create a higher-order spline matching higher-order + derivatives, use `BPoly.from_derivatives`. + + References + ---------- + .. [1] `Cubic Hermite spline + `_ + on Wikipedia. + """ + + def __init__(self, x, y, dydx, axis=0, extrapolate=None): + if extrapolate is None: + extrapolate = True + + x, dx, y, axis, dydx = prepare_input(x, y, axis, dydx) + + dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1)) + slope = np.diff(y, axis=0) / dxr + t = (dydx[:-1] + dydx[1:] - 2 * slope) / dxr + + c = np.empty((4, len(x) - 1) + y.shape[1:], dtype=t.dtype) + c[0] = t / dxr + c[1] = (slope - dydx[:-1]) / dxr - t + c[2] = dydx[:-1] + c[3] = y[:-1] + + super().__init__(c, x, extrapolate=extrapolate) + self.axis = axis + + +class PchipInterpolator(CubicHermiteSpline): + r"""PCHIP 1-D monotonic cubic interpolation. + + ``x`` and ``y`` are arrays of values used to approximate some function f, + with ``y = f(x)``. The interpolant uses monotonic cubic splines + to find the value of new points. (PCHIP stands for Piecewise Cubic + Hermite Interpolating Polynomial). + + Parameters + ---------- + x : ndarray, shape (npoints, ) + A 1-D array of monotonically increasing real values. ``x`` cannot + include duplicate values (otherwise f is overspecified) + y : ndarray, shape (..., npoints, ...) + A N-D array of real values. ``y``'s length along the interpolation + axis must be equal to the length of ``x``. Use the ``axis`` + parameter to select the interpolation axis. + axis : int, optional + Axis in the ``y`` array corresponding to the x-coordinate values. Defaults + to ``axis=0``. + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. + + Methods + ------- + __call__ + derivative + antiderivative + roots + + See Also + -------- + CubicHermiteSpline : Piecewise-cubic interpolator. + Akima1DInterpolator : Akima 1D interpolator. + CubicSpline : Cubic spline data interpolator. + PPoly : Piecewise polynomial in terms of coefficients and breakpoints. + + Notes + ----- + The interpolator preserves monotonicity in the interpolation data and does + not overshoot if the data is not smooth. + + The first derivatives are guaranteed to be continuous, but the second + derivatives may jump at :math:`x_k`. + + Determines the derivatives at the points :math:`x_k`, :math:`f'_k`, + by using PCHIP algorithm [1]_. + + Let :math:`h_k = x_{k+1} - x_k`, and :math:`d_k = (y_{k+1} - y_k) / h_k` + are the slopes at internal points :math:`x_k`. + If the signs of :math:`d_k` and :math:`d_{k-1}` are different or either of + them equals zero, then :math:`f'_k = 0`. Otherwise, it is given by the + weighted harmonic mean + + .. math:: + + \frac{w_1 + w_2}{f'_k} = \frac{w_1}{d_{k-1}} + \frac{w_2}{d_k} + + where :math:`w_1 = 2 h_k + h_{k-1}` and :math:`w_2 = h_k + 2 h_{k-1}`. + + The end slopes are set using a one-sided scheme [2]_. + + + References + ---------- + .. [1] F. N. Fritsch and J. Butland, + A method for constructing local + monotone piecewise cubic interpolants, + SIAM J. Sci. Comput., 5(2), 300-304 (1984). + :doi:`10.1137/0905021`. + .. [2] see, e.g., C. Moler, Numerical Computing with Matlab, 2004. + :doi:`10.1137/1.9780898717952` + + """ + + def __init__(self, x, y, axis=0, extrapolate=None): + x, _, y, axis, _ = prepare_input(x, y, axis) + if np.iscomplexobj(y): + msg = ("`PchipInterpolator` only works with real values for `y`. " + "If you are trying to use the real components of the passed array, " + "use `np.real` on the array before passing to `PchipInterpolator`.") + raise ValueError(msg) + xp = x.reshape((x.shape[0],) + (1,)*(y.ndim-1)) + dk = self._find_derivatives(xp, y) + super().__init__(x, y, dk, axis=0, extrapolate=extrapolate) + self.axis = axis + + @staticmethod + def _edge_case(h0, h1, m0, m1): + # one-sided three-point estimate for the derivative + d = ((2*h0 + h1)*m0 - h0*m1) / (h0 + h1) + + # try to preserve shape + mask = np.sign(d) != np.sign(m0) + mask2 = (np.sign(m0) != np.sign(m1)) & (np.abs(d) > 3.*np.abs(m0)) + mmm = (~mask) & mask2 + + d[mask] = 0. + d[mmm] = 3.*m0[mmm] + + return d + + @staticmethod + def _find_derivatives(x, y): + # Determine the derivatives at the points y_k, d_k, by using + # PCHIP algorithm is: + # We choose the derivatives at the point x_k by + # Let m_k be the slope of the kth segment (between k and k+1) + # If m_k=0 or m_{k-1}=0 or sgn(m_k) != sgn(m_{k-1}) then d_k == 0 + # else use weighted harmonic mean: + # w_1 = 2h_k + h_{k-1}, w_2 = h_k + 2h_{k-1} + # 1/d_k = 1/(w_1 + w_2)*(w_1 / m_k + w_2 / m_{k-1}) + # where h_k is the spacing between x_k and x_{k+1} + y_shape = y.shape + if y.ndim == 1: + # So that _edge_case doesn't end up assigning to scalars + x = x[:, None] + y = y[:, None] + + hk = x[1:] - x[:-1] + mk = (y[1:] - y[:-1]) / hk + + if y.shape[0] == 2: + # edge case: only have two points, use linear interpolation + dk = np.zeros_like(y) + dk[0] = mk + dk[1] = mk + return dk.reshape(y_shape) + + smk = np.sign(mk) + condition = (smk[1:] != smk[:-1]) | (mk[1:] == 0) | (mk[:-1] == 0) + + w1 = 2*hk[1:] + hk[:-1] + w2 = hk[1:] + 2*hk[:-1] + + # values where division by zero occurs will be excluded + # by 'condition' afterwards + with np.errstate(divide='ignore', invalid='ignore'): + whmean = (w1/mk[:-1] + w2/mk[1:]) / (w1 + w2) + + dk = np.zeros_like(y) + dk[1:-1][condition] = 0.0 + dk[1:-1][~condition] = 1.0 / whmean[~condition] + + # special case endpoints, as suggested in + # Cleve Moler, Numerical Computing with MATLAB, Chap 3.6 (pchiptx.m) + dk[0] = PchipInterpolator._edge_case(hk[0], hk[1], mk[0], mk[1]) + dk[-1] = PchipInterpolator._edge_case(hk[-1], hk[-2], mk[-1], mk[-2]) + + return dk.reshape(y_shape) + + +def pchip_interpolate(xi, yi, x, der=0, axis=0): + """ + Convenience function for pchip interpolation. + + xi and yi are arrays of values used to approximate some function f, + with ``yi = f(xi)``. The interpolant uses monotonic cubic splines + to find the value of new points x and the derivatives there. + + See `scipy.interpolate.PchipInterpolator` for details. + + Parameters + ---------- + xi : array_like + A sorted list of x-coordinates, of length N. + yi : array_like + A 1-D array of real values. `yi`'s length along the interpolation + axis must be equal to the length of `xi`. If N-D array, use axis + parameter to select correct axis. + + .. deprecated:: 1.13.0 + Complex data is deprecated and will raise an error in + SciPy 1.15.0. If you are trying to use the real components of + the passed array, use ``np.real`` on `yi`. + + x : scalar or array_like + Of length M. + der : int or list, optional + Derivatives to extract. The 0th derivative can be included to + return the function value. + axis : int, optional + Axis in the yi array corresponding to the x-coordinate values. + + Returns + ------- + y : scalar or array_like + The result, of length R or length M or M by R. + + See Also + -------- + PchipInterpolator : PCHIP 1-D monotonic cubic interpolator. + + Examples + -------- + We can interpolate 2D observed data using pchip interpolation: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import pchip_interpolate + >>> x_observed = np.linspace(0.0, 10.0, 11) + >>> y_observed = np.sin(x_observed) + >>> x = np.linspace(min(x_observed), max(x_observed), num=100) + >>> y = pchip_interpolate(x_observed, y_observed, x) + >>> plt.plot(x_observed, y_observed, "o", label="observation") + >>> plt.plot(x, y, label="pchip interpolation") + >>> plt.legend() + >>> plt.show() + + """ + P = PchipInterpolator(xi, yi, axis=axis) + + if der == 0: + return P(x) + elif _isscalar(der): + return P.derivative(der)(x) + else: + return [P.derivative(nu)(x) for nu in der] + + +class Akima1DInterpolator(CubicHermiteSpline): + r""" + Akima interpolator + + Fit piecewise cubic polynomials, given vectors x and y. The interpolation + method by Akima uses a continuously differentiable sub-spline built from + piecewise cubic polynomials. The resultant curve passes through the given + data points and will appear smooth and natural. + + Parameters + ---------- + x : ndarray, shape (npoints, ) + 1-D array of monotonically increasing real values. + y : ndarray, shape (..., npoints, ...) + N-D array of real values. The length of ``y`` along the interpolation axis + must be equal to the length of ``x``. Use the ``axis`` parameter to + select the interpolation axis. + axis : int, optional + Axis in the ``y`` array corresponding to the x-coordinate values. Defaults + to ``axis=0``. + method : {'akima', 'makima'}, optional + If ``"makima"``, use the modified Akima interpolation [2]_. + Defaults to ``"akima"``, use the Akima interpolation [1]_. + + .. versionadded:: 1.13.0 + + extrapolate : {bool, None}, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. If None, + ``extrapolate`` is set to False. + + Methods + ------- + __call__ + derivative + antiderivative + roots + + See Also + -------- + PchipInterpolator : PCHIP 1-D monotonic cubic interpolator. + CubicSpline : Cubic spline data interpolator. + PPoly : Piecewise polynomial in terms of coefficients and breakpoints + + Notes + ----- + .. versionadded:: 0.14 + + Use only for precise data, as the fitted curve passes through the given + points exactly. This routine is useful for plotting a pleasingly smooth + curve through a few given points for purposes of plotting. + + Let :math:`\delta_i = (y_{i+1} - y_i) / (x_{i+1} - x_i)` be the slopes of + the interval :math:`\left[x_i, x_{i+1}\right)`. Akima's derivative at + :math:`x_i` is defined as: + + .. math:: + + d_i = \frac{w_1}{w_1 + w_2}\delta_{i-1} + \frac{w_2}{w_1 + w_2}\delta_i + + In the Akima interpolation [1]_ (``method="akima"``), the weights are: + + .. math:: + + \begin{aligned} + w_1 &= |\delta_{i+1} - \delta_i| \\ + w_2 &= |\delta_{i-1} - \delta_{i-2}| + \end{aligned} + + In the modified Akima interpolation [2]_ (``method="makima"``), + to eliminate overshoot and avoid edge cases of both numerator and + denominator being equal to 0, the weights are modified as follows: + + .. math:: + + \begin{align*} + w_1 &= |\delta_{i+1} - \delta_i| + |\delta_{i+1} + \delta_i| / 2 \\ + w_2 &= |\delta_{i-1} - \delta_{i-2}| + |\delta_{i-1} + \delta_{i-2}| / 2 + \end{align*} + + Examples + -------- + Comparison of ``method="akima"`` and ``method="makima"``: + + >>> import numpy as np + >>> from scipy.interpolate import Akima1DInterpolator + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(1, 7, 7) + >>> y = np.array([-1, -1, -1, 0, 1, 1, 1]) + >>> xs = np.linspace(min(x), max(x), num=100) + >>> y_akima = Akima1DInterpolator(x, y, method="akima")(xs) + >>> y_makima = Akima1DInterpolator(x, y, method="makima")(xs) + + >>> fig, ax = plt.subplots() + >>> ax.plot(x, y, "o", label="data") + >>> ax.plot(xs, y_akima, label="akima") + >>> ax.plot(xs, y_makima, label="makima") + >>> ax.legend() + >>> fig.show() + + The overshoot that occurred in ``"akima"`` has been avoided in ``"makima"``. + + References + ---------- + .. [1] A new method of interpolation and smooth curve fitting based + on local procedures. Hiroshi Akima, J. ACM, October 1970, 17(4), + 589-602. :doi:`10.1145/321607.321609` + .. [2] Makima Piecewise Cubic Interpolation. Cleve Moler and Cosmin Ionita, 2019. + https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/ + + """ + + def __init__(self, x, y, axis=0, *, method: Literal["akima", "makima"]="akima", + extrapolate:bool | None = None): + if method not in {"akima", "makima"}: + raise NotImplementedError(f"`method`={method} is unsupported.") + # Original implementation in MATLAB by N. Shamsundar (BSD licensed), see + # https://www.mathworks.com/matlabcentral/fileexchange/1814-akima-interpolation + x, dx, y, axis, _ = prepare_input(x, y, axis) + + if np.iscomplexobj(y): + msg = ("`Akima1DInterpolator` only works with real values for `y`. " + "If you are trying to use the real components of the passed array, " + "use `np.real` on the array before passing to " + "`Akima1DInterpolator`.") + raise ValueError(msg) + + # Akima extrapolation historically False; parent class defaults to True. + extrapolate = False if extrapolate is None else extrapolate + + # determine slopes between breakpoints + m = np.empty((x.size + 3, ) + y.shape[1:]) + dx = dx[(slice(None), ) + (None, ) * (y.ndim - 1)] + m[2:-2] = np.diff(y, axis=0) / dx + + # add two additional points on the left ... + m[1] = 2. * m[2] - m[3] + m[0] = 2. * m[1] - m[2] + # ... and on the right + m[-2] = 2. * m[-3] - m[-4] + m[-1] = 2. * m[-2] - m[-3] + + # if m1 == m2 != m3 == m4, the slope at the breakpoint is not + # defined. This is the fill value: + t = .5 * (m[3:] + m[:-3]) + # get the denominator of the slope t + dm = np.abs(np.diff(m, axis=0)) + if method == "makima": + pm = np.abs(m[1:] + m[:-1]) + f1 = dm[2:] + 0.5 * pm[2:] + f2 = dm[:-2] + 0.5 * pm[:-2] + else: + f1 = dm[2:] + f2 = dm[:-2] + f12 = f1 + f2 + # These are the mask of where the slope at breakpoint is defined: + ind = np.nonzero(f12 > 1e-9 * np.max(f12, initial=-np.inf)) + x_ind, y_ind = ind[0], ind[1:] + # Set the slope at breakpoint + t[ind] = (f1[ind] * m[(x_ind + 1,) + y_ind] + + f2[ind] * m[(x_ind + 2,) + y_ind]) / f12[ind] + + super().__init__(x, y, t, axis=0, extrapolate=extrapolate) + self.axis = axis + + def extend(self, c, x, right=True): + raise NotImplementedError("Extending a 1-D Akima interpolator is not " + "yet implemented") + + # These are inherited from PPoly, but they do not produce an Akima + # interpolator. Hence stub them out. + @classmethod + def from_spline(cls, tck, extrapolate=None): + raise NotImplementedError("This method does not make sense for " + "an Akima interpolator.") + + @classmethod + def from_bernstein_basis(cls, bp, extrapolate=None): + raise NotImplementedError("This method does not make sense for " + "an Akima interpolator.") + + +class CubicSpline(CubicHermiteSpline): + """Cubic spline data interpolator. + + Interpolate data with a piecewise cubic polynomial which is twice + continuously differentiable [1]_. The result is represented as a `PPoly` + instance with breakpoints matching the given data. + + Parameters + ---------- + x : array_like, shape (n,) + 1-D array containing values of the independent variable. + Values must be real, finite and in strictly increasing order. + y : array_like + Array containing values of the dependent variable. It can have + arbitrary number of dimensions, but the length along ``axis`` + (see below) must match the length of ``x``. Values must be finite. + axis : int, optional + Axis along which `y` is assumed to be varying. Meaning that for + ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``. + Default is 0. + bc_type : string or 2-tuple, optional + Boundary condition type. Two additional equations, given by the + boundary conditions, are required to determine all coefficients of + polynomials on each segment [2]_. + + If `bc_type` is a string, then the specified condition will be applied + at both ends of a spline. Available conditions are: + + * 'not-a-knot' (default): The first and second segment at a curve end + are the same polynomial. It is a good default when there is no + information on boundary conditions. + * 'periodic': The interpolated functions is assumed to be periodic + of period ``x[-1] - x[0]``. The first and last value of `y` must be + identical: ``y[0] == y[-1]``. This boundary condition will result in + ``y'[0] == y'[-1]`` and ``y''[0] == y''[-1]``. + * 'clamped': The first derivative at curves ends are zero. Assuming + a 1D `y`, ``bc_type=((1, 0.0), (1, 0.0))`` is the same condition. + * 'natural': The second derivative at curve ends are zero. Assuming + a 1D `y`, ``bc_type=((2, 0.0), (2, 0.0))`` is the same condition. + + If `bc_type` is a 2-tuple, the first and the second value will be + applied at the curve start and end respectively. The tuple values can + be one of the previously mentioned strings (except 'periodic') or a + tuple ``(order, deriv_values)`` allowing to specify arbitrary + derivatives at curve ends: + + * `order`: the derivative order, 1 or 2. + * `deriv_value`: array_like containing derivative values, shape must + be the same as `y`, excluding ``axis`` dimension. For example, if + `y` is 1-D, then `deriv_value` must be a scalar. If `y` is 3-D with + the shape (n0, n1, n2) and axis=2, then `deriv_value` must be 2-D + and have the shape (n0, n1). + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. If 'periodic', + periodic extrapolation is used. If None (default), ``extrapolate`` is + set to 'periodic' for ``bc_type='periodic'`` and to True otherwise. + + Attributes + ---------- + x : ndarray, shape (n,) + Breakpoints. The same ``x`` which was passed to the constructor. + c : ndarray, shape (4, n-1, ...) + Coefficients of the polynomials on each segment. The trailing + dimensions match the dimensions of `y`, excluding ``axis``. + For example, if `y` is 1-d, then ``c[k, i]`` is a coefficient for + ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``. + axis : int + Interpolation axis. The same axis which was passed to the + constructor. + + Methods + ------- + __call__ + derivative + antiderivative + integrate + roots + + See Also + -------- + Akima1DInterpolator : Akima 1D interpolator. + PchipInterpolator : PCHIP 1-D monotonic cubic interpolator. + PPoly : Piecewise polynomial in terms of coefficients and breakpoints. + + Notes + ----- + Parameters `bc_type` and ``extrapolate`` work independently, i.e. the + former controls only construction of a spline, and the latter only + evaluation. + + When a boundary condition is 'not-a-knot' and n = 2, it is replaced by + a condition that the first derivative is equal to the linear interpolant + slope. When both boundary conditions are 'not-a-knot' and n = 3, the + solution is sought as a parabola passing through given points. + + When 'not-a-knot' boundary conditions is applied to both ends, the + resulting spline will be the same as returned by `splrep` (with ``s=0``) + and `InterpolatedUnivariateSpline`, but these two methods use a + representation in B-spline basis. + + .. versionadded:: 0.18.0 + + Examples + -------- + In this example the cubic spline is used to interpolate a sampled sinusoid. + You can see that the spline continuity property holds for the first and + second derivatives and violates only for the third derivative. + + >>> import numpy as np + >>> from scipy.interpolate import CubicSpline + >>> import matplotlib.pyplot as plt + >>> x = np.arange(10) + >>> y = np.sin(x) + >>> cs = CubicSpline(x, y) + >>> xs = np.arange(-0.5, 9.6, 0.1) + >>> fig, ax = plt.subplots(figsize=(6.5, 4)) + >>> ax.plot(x, y, 'o', label='data') + >>> ax.plot(xs, np.sin(xs), label='true') + >>> ax.plot(xs, cs(xs), label="S") + >>> ax.plot(xs, cs(xs, 1), label="S'") + >>> ax.plot(xs, cs(xs, 2), label="S''") + >>> ax.plot(xs, cs(xs, 3), label="S'''") + >>> ax.set_xlim(-0.5, 9.5) + >>> ax.legend(loc='lower left', ncol=2) + >>> plt.show() + + In the second example, the unit circle is interpolated with a spline. A + periodic boundary condition is used. You can see that the first derivative + values, ds/dx=0, ds/dy=1 at the periodic point (1, 0) are correctly + computed. Note that a circle cannot be exactly represented by a cubic + spline. To increase precision, more breakpoints would be required. + + >>> theta = 2 * np.pi * np.linspace(0, 1, 5) + >>> y = np.c_[np.cos(theta), np.sin(theta)] + >>> cs = CubicSpline(theta, y, bc_type='periodic') + >>> print("ds/dx={:.1f} ds/dy={:.1f}".format(cs(0, 1)[0], cs(0, 1)[1])) + ds/dx=0.0 ds/dy=1.0 + >>> xs = 2 * np.pi * np.linspace(0, 1, 100) + >>> fig, ax = plt.subplots(figsize=(6.5, 4)) + >>> ax.plot(y[:, 0], y[:, 1], 'o', label='data') + >>> ax.plot(np.cos(xs), np.sin(xs), label='true') + >>> ax.plot(cs(xs)[:, 0], cs(xs)[:, 1], label='spline') + >>> ax.axes.set_aspect('equal') + >>> ax.legend(loc='center') + >>> plt.show() + + The third example is the interpolation of a polynomial y = x**3 on the + interval 0 <= x<= 1. A cubic spline can represent this function exactly. + To achieve that we need to specify values and first derivatives at + endpoints of the interval. Note that y' = 3 * x**2 and thus y'(0) = 0 and + y'(1) = 3. + + >>> cs = CubicSpline([0, 1], [0, 1], bc_type=((1, 0), (1, 3))) + >>> x = np.linspace(0, 1) + >>> np.allclose(x**3, cs(x)) + True + + References + ---------- + .. [1] `Cubic Spline Interpolation + `_ + on Wikiversity. + .. [2] Carl de Boor, "A Practical Guide to Splines", Springer-Verlag, 1978. + """ + + def __init__(self, x, y, axis=0, bc_type='not-a-knot', extrapolate=None): + x, dx, y, axis, _ = prepare_input(x, y, axis) + n = len(x) + + bc, y = self._validate_bc(bc_type, y, y.shape[1:], axis) + + if extrapolate is None: + if bc[0] == 'periodic': + extrapolate = 'periodic' + else: + extrapolate = True + + if y.size == 0: + # bail out early for zero-sized arrays + s = np.zeros_like(y) + else: + dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1)) + slope = np.diff(y, axis=0) / dxr + + # If bc is 'not-a-knot' this change is just a convention. + # If bc is 'periodic' then we already checked that y[0] == y[-1], + # and the spline is just a constant, we handle this case in the + # same way by setting the first derivatives to slope, which is 0. + if n == 2: + if bc[0] in ['not-a-knot', 'periodic']: + bc[0] = (1, slope[0]) + if bc[1] in ['not-a-knot', 'periodic']: + bc[1] = (1, slope[0]) + + # This is a special case, when both conditions are 'not-a-knot' + # and n == 3. In this case 'not-a-knot' can't be handled regularly + # as the both conditions are identical. We handle this case by + # constructing a parabola passing through given points. + if n == 3 and bc[0] == 'not-a-knot' and bc[1] == 'not-a-knot': + A = np.zeros((3, 3)) # This is a standard matrix. + b = np.empty((3,) + y.shape[1:], dtype=y.dtype) + + A[0, 0] = 1 + A[0, 1] = 1 + A[1, 0] = dx[1] + A[1, 1] = 2 * (dx[0] + dx[1]) + A[1, 2] = dx[0] + A[2, 1] = 1 + A[2, 2] = 1 + + b[0] = 2 * slope[0] + b[1] = 3 * (dxr[0] * slope[1] + dxr[1] * slope[0]) + b[2] = 2 * slope[1] + + s = solve(A, b, overwrite_a=True, overwrite_b=True, + check_finite=False) + elif n == 3 and bc[0] == 'periodic': + # In case when number of points is 3 we compute the derivatives + # manually + t = (slope / dxr).sum(0) / (1. / dxr).sum(0) + s = np.broadcast_to(t, (n,) + y.shape[1:]) + else: + # Find derivative values at each x[i] by solving a tridiagonal + # system. + A = np.zeros((3, n)) # This is a banded matrix representation. + b = np.empty((n,) + y.shape[1:], dtype=y.dtype) + + # Filling the system for i=1..n-2 + # (x[i-1] - x[i]) * s[i-1] +\ + # 2 * ((x[i] - x[i-1]) + (x[i+1] - x[i])) * s[i] +\ + # (x[i] - x[i-1]) * s[i+1] =\ + # 3 * ((x[i+1] - x[i])*(y[i] - y[i-1])/(x[i] - x[i-1]) +\ + # (x[i] - x[i-1])*(y[i+1] - y[i])/(x[i+1] - x[i])) + + A[1, 1:-1] = 2 * (dx[:-1] + dx[1:]) # The diagonal + A[0, 2:] = dx[:-1] # The upper diagonal + A[-1, :-2] = dx[1:] # The lower diagonal + + b[1:-1] = 3 * (dxr[1:] * slope[:-1] + dxr[:-1] * slope[1:]) + + bc_start, bc_end = bc + + if bc_start == 'periodic': + # Due to the periodicity, and because y[-1] = y[0], the + # linear system has (n-1) unknowns/equations instead of n: + A = A[:, 0:-1] + A[1, 0] = 2 * (dx[-1] + dx[0]) + A[0, 1] = dx[-1] + + b = b[:-1] + + # Also, due to the periodicity, the system is not tri-diagonal. + # We need to compute a "condensed" matrix of shape (n-2, n-2). + # See https://web.archive.org/web/20151220180652/http://www.cfm.brown.edu/people/gk/chap6/node14.html + # for more explanations. + # The condensed matrix is obtained by removing the last column + # and last row of the (n-1, n-1) system matrix. The removed + # values are saved in scalar variables with the (n-1, n-1) + # system matrix indices forming their names: + a_m1_0 = dx[-2] # lower left corner value: A[-1, 0] + a_m1_m2 = dx[-1] + a_m1_m1 = 2 * (dx[-1] + dx[-2]) + a_m2_m1 = dx[-3] + a_0_m1 = dx[0] + + b[0] = 3 * (dxr[0] * slope[-1] + dxr[-1] * slope[0]) + b[-1] = 3 * (dxr[-1] * slope[-2] + dxr[-2] * slope[-1]) + + Ac = A[:, :-1] + b1 = b[:-1] + b2 = np.zeros_like(b1) + b2[0] = -a_0_m1 + b2[-1] = -a_m2_m1 + + # s1 and s2 are the solutions of (n-2, n-2) system + s1 = solve_banded((1, 1), Ac, b1, overwrite_ab=False, + overwrite_b=False, check_finite=False) + + s2 = solve_banded((1, 1), Ac, b2, overwrite_ab=False, + overwrite_b=False, check_finite=False) + + # computing the s[n-2] solution: + s_m1 = ((b[-1] - a_m1_0 * s1[0] - a_m1_m2 * s1[-1]) / + (a_m1_m1 + a_m1_0 * s2[0] + a_m1_m2 * s2[-1])) + + # s is the solution of the (n, n) system: + s = np.empty((n,) + y.shape[1:], dtype=y.dtype) + s[:-2] = s1 + s_m1 * s2 + s[-2] = s_m1 + s[-1] = s[0] + else: + if bc_start == 'not-a-knot': + A[1, 0] = dx[1] + A[0, 1] = x[2] - x[0] + d = x[2] - x[0] + b[0] = ((dxr[0] + 2*d) * dxr[1] * slope[0] + + dxr[0]**2 * slope[1]) / d + elif bc_start[0] == 1: + A[1, 0] = 1 + A[0, 1] = 0 + b[0] = bc_start[1] + elif bc_start[0] == 2: + A[1, 0] = 2 * dx[0] + A[0, 1] = dx[0] + b[0] = -0.5 * bc_start[1] * dx[0]**2 + 3 * (y[1] - y[0]) + + if bc_end == 'not-a-knot': + A[1, -1] = dx[-2] + A[-1, -2] = x[-1] - x[-3] + d = x[-1] - x[-3] + b[-1] = ((dxr[-1]**2*slope[-2] + + (2*d + dxr[-1])*dxr[-2]*slope[-1]) / d) + elif bc_end[0] == 1: + A[1, -1] = 1 + A[-1, -2] = 0 + b[-1] = bc_end[1] + elif bc_end[0] == 2: + A[1, -1] = 2 * dx[-1] + A[-1, -2] = dx[-1] + b[-1] = 0.5 * bc_end[1] * dx[-1]**2 + 3 * (y[-1] - y[-2]) + + s = solve_banded((1, 1), A, b, overwrite_ab=True, + overwrite_b=True, check_finite=False) + + super().__init__(x, y, s, axis=0, extrapolate=extrapolate) + self.axis = axis + + @staticmethod + def _validate_bc(bc_type, y, expected_deriv_shape, axis): + """Validate and prepare boundary conditions. + + Returns + ------- + validated_bc : 2-tuple + Boundary conditions for a curve start and end. + y : ndarray + y casted to complex dtype if one of the boundary conditions has + complex dtype. + """ + if isinstance(bc_type, str): + if bc_type == 'periodic': + if not np.allclose(y[0], y[-1], rtol=1e-15, atol=1e-15): + raise ValueError( + f"The first and last `y` point along axis {axis} must " + "be identical (within machine precision) when " + "bc_type='periodic'.") + + bc_type = (bc_type, bc_type) + + else: + if len(bc_type) != 2: + raise ValueError("`bc_type` must contain 2 elements to " + "specify start and end conditions.") + + if 'periodic' in bc_type: + raise ValueError("'periodic' `bc_type` is defined for both " + "curve ends and cannot be used with other " + "boundary conditions.") + + validated_bc = [] + for bc in bc_type: + if isinstance(bc, str): + if bc == 'clamped': + validated_bc.append((1, np.zeros(expected_deriv_shape))) + elif bc == 'natural': + validated_bc.append((2, np.zeros(expected_deriv_shape))) + elif bc in ['not-a-knot', 'periodic']: + validated_bc.append(bc) + else: + raise ValueError(f"bc_type={bc} is not allowed.") + else: + try: + deriv_order, deriv_value = bc + except Exception as e: + raise ValueError( + "A specified derivative value must be " + "given in the form (order, value)." + ) from e + + if deriv_order not in [1, 2]: + raise ValueError("The specified derivative order must " + "be 1 or 2.") + + deriv_value = np.asarray(deriv_value) + if deriv_value.shape != expected_deriv_shape: + raise ValueError( + f"`deriv_value` shape {deriv_value.shape} is not " + f"the expected one {expected_deriv_shape}." + ) + + if np.issubdtype(deriv_value.dtype, np.complexfloating): + y = y.astype(complex, copy=False) + + validated_bc.append((deriv_order, deriv_value)) + + return validated_bc, y diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5f1de8a506d90631543927894cd35196744a879a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..daa7773a0f3be6590ea9c0ab328d610efa745859 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py @@ -0,0 +1,2394 @@ +""" +fitpack --- curve and surface fitting with splines + +fitpack is based on a collection of Fortran routines DIERCKX +by P. Dierckx (see http://www.netlib.org/dierckx/) transformed +to double routines by Pearu Peterson. +""" +# Created by Pearu Peterson, June,August 2003 +__all__ = [ + 'UnivariateSpline', + 'InterpolatedUnivariateSpline', + 'LSQUnivariateSpline', + 'BivariateSpline', + 'LSQBivariateSpline', + 'SmoothBivariateSpline', + 'LSQSphereBivariateSpline', + 'SmoothSphereBivariateSpline', + 'RectBivariateSpline', + 'RectSphereBivariateSpline'] + + +import warnings +from threading import Lock + +from numpy import zeros, concatenate, ravel, diff, array +import numpy as np + +from . import _fitpack_impl +from . import _dfitpack as dfitpack + + +dfitpack_int = dfitpack.types.intvar.dtype +FITPACK_LOCK = Lock() + + +# ############### Univariate spline #################### + +_curfit_messages = {1: """ +The required storage space exceeds the available storage space, as +specified by the parameter nest: nest too small. If nest is already +large (say nest > m/2), it may also indicate that s is too small. +The approximation returned is the weighted least-squares spline +according to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp +gives the corresponding weighted sum of squared residuals (fp>s). +""", + 2: """ +A theoretically impossible result was found during the iteration +process for finding a smoothing spline with fp = s: s too small. +There is an approximation returned but the corresponding weighted sum +of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""", + 3: """ +The maximal number of iterations maxit (set to 20 by the program) +allowed for finding a smoothing spline with fp=s has been reached: s +too small. +There is an approximation returned but the corresponding weighted sum +of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""", + 10: """ +Error on entry, no approximation returned. The following conditions +must hold: +xb<=x[0]0, i=0..m-1 +if iopt=-1: + xb>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4]) + >>> w = np.isnan(y) + >>> y[w] = 0. + >>> spl = UnivariateSpline(x, y, w=~w) + + Notice the need to replace a ``nan`` by a numerical value (precise value + does not matter as long as the corresponding weight is zero.) + + References + ---------- + Based on algorithms described in [1]_, [2]_, [3]_, and [4]_: + + .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and + integration of experimental data using spline functions", + J.Comp.Appl.Maths 1 (1975) 165-184. + .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular + grid while using spline functions", SIAM J.Numer.Anal. 19 (1982) + 1286-1304. + .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline + functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981. + .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on + Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import UnivariateSpline + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + >>> plt.plot(x, y, 'ro', ms=5) + + Use the default value for the smoothing parameter: + + >>> spl = UnivariateSpline(x, y) + >>> xs = np.linspace(-3, 3, 1000) + >>> plt.plot(xs, spl(xs), 'g', lw=3) + + Manually change the amount of smoothing: + + >>> spl.set_smoothing_factor(0.5) + >>> plt.plot(xs, spl(xs), 'b', lw=3) + >>> plt.show() + + """ + + def __init__(self, x, y, w=None, bbox=[None]*2, k=3, s=None, + ext=0, check_finite=False): + + x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, s, ext, + check_finite) + + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + with FITPACK_LOCK: + data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0], + xe=bbox[1], s=s) + if data[-1] == 1: + # nest too small, setting to maximum bound + data = self._reset_nest(data) + self._data = data + self._reset_class() + + @staticmethod + def validate_input(x, y, w, bbox, k, s, ext, check_finite): + x, y, bbox = np.asarray(x), np.asarray(y), np.asarray(bbox) + if w is not None: + w = np.asarray(w) + if check_finite: + w_finite = np.isfinite(w).all() if w is not None else True + if (not np.isfinite(x).all() or not np.isfinite(y).all() or + not w_finite): + raise ValueError("x and y array must not contain " + "NaNs or infs.") + if s is None or s > 0: + if not np.all(diff(x) >= 0.0): + raise ValueError("x must be increasing if s > 0") + else: + if not np.all(diff(x) > 0.0): + raise ValueError("x must be strictly increasing if s = 0") + if x.size != y.size: + raise ValueError("x and y should have a same length") + elif w is not None and not x.size == y.size == w.size: + raise ValueError("x, y, and w should have a same length") + elif bbox.shape != (2,): + raise ValueError("bbox shape should be (2,)") + elif not (1 <= k <= 5): + raise ValueError("k should be 1 <= k <= 5") + elif s is not None and not s >= 0.0: + raise ValueError("s should be s >= 0.0") + + try: + ext = _extrap_modes[ext] + except KeyError as e: + raise ValueError(f"Unknown extrapolation mode {ext}.") from e + + return x, y, w, bbox, ext + + @classmethod + def _from_tck(cls, tck, ext=0): + """Construct a spline object from given tck""" + self = cls.__new__(cls) + t, c, k = tck + self._eval_args = tck + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + self._data = (None, None, None, None, None, k, None, len(t), t, + c, None, None, None, None) + self.ext = ext + return self + + def _reset_class(self): + data = self._data + n, t, c, k, ier = data[7], data[8], data[9], data[5], data[-1] + self._eval_args = t[:n], c[:n], k + if ier == 0: + # the spline returned has a residual sum of squares fp + # such that abs(fp-s)/s <= tol with tol a relative + # tolerance set to 0.001 by the program + pass + elif ier == -1: + # the spline returned is an interpolating spline + self._set_class(InterpolatedUnivariateSpline) + elif ier == -2: + # the spline returned is the weighted least-squares + # polynomial of degree k. In this extreme case fp gives + # the upper bound fp0 for the smoothing factor s. + self._set_class(LSQUnivariateSpline) + else: + # error + if ier == 1: + self._set_class(LSQUnivariateSpline) + message = _curfit_messages.get(ier, f'ier={ier}') + warnings.warn(message, stacklevel=3) + + def _set_class(self, cls): + self._spline_class = cls + if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline, + LSQUnivariateSpline): + self.__class__ = cls + else: + # It's an unknown subclass -- don't change class. cf. #731 + pass + + def _reset_nest(self, data, nest=None): + n = data[10] + if nest is None: + k, m = data[5], len(data[0]) + nest = m+k+1 # this is the maximum bound for nest + else: + if not n <= nest: + raise ValueError("`nest` can only be increased") + t, c, fpint, nrdata = (np.resize(data[j], nest) for j in + [8, 9, 11, 12]) + + args = data[:8] + (t, c, n, fpint, nrdata, data[13]) + with FITPACK_LOCK: + data = dfitpack.fpcurf1(*args) + return data + + def set_smoothing_factor(self, s): + """ Continue spline computation with the given smoothing + factor s and with the knots found at the last call. + + This routine modifies the spline in place. + + """ + data = self._data + if data[6] == -1: + warnings.warn('smoothing factor unchanged for' + 'LSQ spline with fixed knots', + stacklevel=2) + return + args = data[:6] + (s,) + data[7:] + with FITPACK_LOCK: + data = dfitpack.fpcurf1(*args) + if data[-1] == 1: + # nest too small, setting to maximum bound + data = self._reset_nest(data) + self._data = data + self._reset_class() + + def __call__(self, x, nu=0, ext=None): + """ + Evaluate spline (or its nu-th derivative) at positions x. + + Parameters + ---------- + x : array_like + A 1-D array of points at which to return the value of the smoothed + spline or its derivatives. Note: `x` can be unordered but the + evaluation is more efficient if `x` is (partially) ordered. + nu : int + The order of derivative of the spline to compute. + ext : int + Controls the value returned for elements of `x` not in the + interval defined by the knot sequence. + + * if ext=0 or 'extrapolate', return the extrapolated value. + * if ext=1 or 'zeros', return 0 + * if ext=2 or 'raise', raise a ValueError + * if ext=3 or 'const', return the boundary value. + + The default value is 0, passed from the initialization of + UnivariateSpline. + + """ + x = np.asarray(x) + # empty input yields empty output + if x.size == 0: + return array([]) + if ext is None: + ext = self.ext + else: + try: + ext = _extrap_modes[ext] + except KeyError as e: + raise ValueError(f"Unknown extrapolation mode {ext}.") from e + with FITPACK_LOCK: + return _fitpack_impl.splev(x, self._eval_args, der=nu, ext=ext) + + def get_knots(self): + """ Return positions of interior knots of the spline. + + Internally, the knot vector contains ``2*k`` additional boundary knots. + """ + data = self._data + k, n = data[5], data[7] + return data[8][k:n-k] + + def get_coeffs(self): + """Return spline coefficients.""" + data = self._data + k, n = data[5], data[7] + return data[9][:n-k-1] + + def get_residual(self): + """Return weighted sum of squared residuals of the spline approximation. + + This is equivalent to:: + + sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) + + """ + return self._data[10] + + def integral(self, a, b): + """ Return definite integral of the spline between two given points. + + Parameters + ---------- + a : float + Lower limit of integration. + b : float + Upper limit of integration. + + Returns + ------- + integral : float + The value of the definite integral of the spline between limits. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, 3, 11) + >>> y = x**2 + >>> spl = UnivariateSpline(x, y) + >>> spl.integral(0, 3) + 9.0 + + which agrees with :math:`\\int x^2 dx = x^3 / 3` between the limits + of 0 and 3. + + A caveat is that this routine assumes the spline to be zero outside of + the data limits: + + >>> spl.integral(-1, 4) + 9.0 + >>> spl.integral(-1, 0) + 0.0 + + """ + with FITPACK_LOCK: + return _fitpack_impl.splint(a, b, self._eval_args) + + def derivatives(self, x): + """ Return all derivatives of the spline at the point x. + + Parameters + ---------- + x : float + The point to evaluate the derivatives at. + + Returns + ------- + der : ndarray, shape(k+1,) + Derivatives of the orders 0 to k. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, 3, 11) + >>> y = x**2 + >>> spl = UnivariateSpline(x, y) + >>> spl.derivatives(1.5) + array([2.25, 3.0, 2.0, 0]) + + """ + with FITPACK_LOCK: + return _fitpack_impl.spalde(x, self._eval_args) + + def roots(self): + """ Return the zeros of the spline. + + Notes + ----- + Restriction: only cubic splines are supported by FITPACK. For non-cubic + splines, use `PPoly.root` (see below for an example). + + Examples + -------- + + For some data, this method may miss a root. This happens when one of + the spline knots (which FITPACK places automatically) happens to + coincide with the true root. A workaround is to convert to `PPoly`, + which uses a different root-finding algorithm. + + For example, + + >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05] + >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03, + ... 4.440892e-16, 1.616930e-03, 3.243000e-03, 4.877670e-03, + ... 6.520430e-03, 8.170770e-03] + >>> from scipy.interpolate import UnivariateSpline + >>> spl = UnivariateSpline(x, y, s=0) + >>> spl.roots() + array([], dtype=float64) + + Converting to a PPoly object does find the roots at `x=2`: + + >>> from scipy.interpolate import splrep, PPoly + >>> tck = splrep(x, y, s=0) + >>> ppoly = PPoly.from_spline(tck) + >>> ppoly.roots(extrapolate=False) + array([2.]) + + See Also + -------- + sproot + PPoly.roots + + """ + k = self._data[5] + if k == 3: + t = self._eval_args[0] + mest = 3 * (len(t) - 7) + with FITPACK_LOCK: + return _fitpack_impl.sproot(self._eval_args, mest=mest) + raise NotImplementedError('finding roots unsupported for ' + 'non-cubic splines') + + def derivative(self, n=1): + """ + Construct a new spline representing the derivative of this spline. + + Parameters + ---------- + n : int, optional + Order of derivative to evaluate. Default: 1 + + Returns + ------- + spline : UnivariateSpline + Spline of order k2=k-n representing the derivative of this + spline. + + See Also + -------- + splder, antiderivative + + Notes + ----- + + .. versionadded:: 0.13.0 + + Examples + -------- + This can be used for finding maxima of a curve: + + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, 10, 70) + >>> y = np.sin(x) + >>> spl = UnivariateSpline(x, y, k=4, s=0) + + Now, differentiate the spline and find the zeros of the + derivative. (NB: `sproot` only works for order 3 splines, so we + fit an order 4 spline): + + >>> spl.derivative().roots() / np.pi + array([ 0.50000001, 1.5 , 2.49999998]) + + This agrees well with roots :math:`\\pi/2 + n\\pi` of + :math:`\\cos(x) = \\sin'(x)`. + + """ + with FITPACK_LOCK: + tck = _fitpack_impl.splder(self._eval_args, n) + # if self.ext is 'const', derivative.ext will be 'zeros' + ext = 1 if self.ext == 3 else self.ext + return UnivariateSpline._from_tck(tck, ext=ext) + + def antiderivative(self, n=1): + """ + Construct a new spline representing the antiderivative of this spline. + + Parameters + ---------- + n : int, optional + Order of antiderivative to evaluate. Default: 1 + + Returns + ------- + spline : UnivariateSpline + Spline of order k2=k+n representing the antiderivative of this + spline. + + Notes + ----- + + .. versionadded:: 0.13.0 + + See Also + -------- + splantider, derivative + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, np.pi/2, 70) + >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2) + >>> spl = UnivariateSpline(x, y, s=0) + + The derivative is the inverse operation of the antiderivative, + although some floating point error accumulates: + + >>> spl(1.7), spl.antiderivative().derivative()(1.7) + (array(2.1565429877197317), array(2.1565429877201865)) + + Antiderivative can be used to evaluate definite integrals: + + >>> ispl = spl.antiderivative() + >>> ispl(np.pi/2) - ispl(0) + 2.2572053588768486 + + This is indeed an approximation to the complete elliptic integral + :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`: + + >>> from scipy.special import ellipk + >>> ellipk(0.8) + 2.2572053268208538 + + """ + with FITPACK_LOCK: + tck = _fitpack_impl.splantider(self._eval_args, n) + return UnivariateSpline._from_tck(tck, self.ext) + + +class InterpolatedUnivariateSpline(UnivariateSpline): + """ + 1-D interpolating spline for a given set of data points. + + .. legacy:: class + + Specifically, we recommend using `make_interp_spline` instead. + + Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. + Spline function passes through all provided points. Equivalent to + `UnivariateSpline` with `s` = 0. + + Parameters + ---------- + x : (N,) array_like + Input dimension of data points -- must be strictly increasing + y : (N,) array_like + input dimension of data points + w : (N,) array_like, optional + Weights for spline fitting. Must be positive. If None (default), + weights are all 1. + bbox : (2,) array_like, optional + 2-sequence specifying the boundary of the approximation interval. If + None (default), ``bbox=[x[0], x[-1]]``. + k : int, optional + Degree of the smoothing spline. Must be ``1 <= k <= 5``. Default is + ``k = 3``, a cubic spline. + ext : int or str, optional + Controls the extrapolation mode for elements + not in the interval defined by the knot sequence. + + * if ext=0 or 'extrapolate', return the extrapolated value. + * if ext=1 or 'zeros', return 0 + * if ext=2 or 'raise', raise a ValueError + * if ext=3 of 'const', return the boundary value. + + The default value is 0. + + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination or non-sensical results) if the inputs + do contain infinities or NaNs. + Default is False. + + See Also + -------- + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + LSQUnivariateSpline : + a spline for which knots are user-selected + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + splrep : + a function to find the B-spline representation of a 1-D curve + splev : + a function to evaluate a B-spline or its derivatives + sproot : + a function to find the roots of a cubic B-spline + splint : + a function to evaluate the definite integral of a B-spline between two + given points + spalde : + a function to evaluate all derivatives of a B-spline + + Notes + ----- + The number of data points must be larger than the spline degree `k`. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import InterpolatedUnivariateSpline + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + >>> spl = InterpolatedUnivariateSpline(x, y) + >>> plt.plot(x, y, 'ro', ms=5) + >>> xs = np.linspace(-3, 3, 1000) + >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7) + >>> plt.show() + + Notice that the ``spl(x)`` interpolates `y`: + + >>> spl.get_residual() + 0.0 + + """ + + def __init__(self, x, y, w=None, bbox=[None]*2, k=3, + ext=0, check_finite=False): + + x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None, + ext, check_finite) + if not np.all(diff(x) > 0.0): + raise ValueError('x must be strictly increasing') + + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + with FITPACK_LOCK: + self._data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0], + xe=bbox[1], s=0) + self._reset_class() + + +_fpchec_error_string = """The input parameters have been rejected by fpchec. \ +This means that at least one of the following conditions is violated: + +1) k+1 <= n-k-1 <= m +2) t(1) <= t(2) <= ... <= t(k+1) + t(n-k) <= t(n-k+1) <= ... <= t(n) +3) t(k+1) < t(k+2) < ... < t(n-k) +4) t(k+1) <= x(i) <= t(n-k) +5) The conditions specified by Schoenberg and Whitney must hold + for at least one subset of data points, i.e., there must be a + subset of data points y(j) such that + t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 +""" + + +class LSQUnivariateSpline(UnivariateSpline): + """ + 1-D spline with explicit internal knots. + + .. legacy:: class + + Specifically, we recommend using `make_lsq_spline` instead. + + + Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. `t` + specifies the internal knots of the spline + + Parameters + ---------- + x : (N,) array_like + Input dimension of data points -- must be increasing + y : (N,) array_like + Input dimension of data points + t : (M,) array_like + interior knots of the spline. Must be in ascending order and:: + + bbox[0] < t[0] < ... < t[-1] < bbox[-1] + + w : (N,) array_like, optional + weights for spline fitting. Must be positive. If None (default), + weights are all 1. + bbox : (2,) array_like, optional + 2-sequence specifying the boundary of the approximation interval. If + None (default), ``bbox = [x[0], x[-1]]``. + k : int, optional + Degree of the smoothing spline. Must be 1 <= `k` <= 5. + Default is `k` = 3, a cubic spline. + ext : int or str, optional + Controls the extrapolation mode for elements + not in the interval defined by the knot sequence. + + * if ext=0 or 'extrapolate', return the extrapolated value. + * if ext=1 or 'zeros', return 0 + * if ext=2 or 'raise', raise a ValueError + * if ext=3 of 'const', return the boundary value. + + The default value is 0. + + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination or non-sensical results) if the inputs + do contain infinities or NaNs. + Default is False. + + Raises + ------ + ValueError + If the interior knots do not satisfy the Schoenberg-Whitney conditions + + See Also + -------- + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + InterpolatedUnivariateSpline : + a interpolating univariate spline for a given set of data points. + splrep : + a function to find the B-spline representation of a 1-D curve + splev : + a function to evaluate a B-spline or its derivatives + sproot : + a function to find the roots of a cubic B-spline + splint : + a function to evaluate the definite integral of a B-spline between two + given points + spalde : + a function to evaluate all derivatives of a B-spline + + Notes + ----- + The number of data points must be larger than the spline degree `k`. + + Knots `t` must satisfy the Schoenberg-Whitney conditions, + i.e., there must be a subset of data points ``x[j]`` such that + ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + + Fit a smoothing spline with a pre-defined internal knots: + + >>> t = [-1, 0, 1] + >>> spl = LSQUnivariateSpline(x, y, t) + + >>> xs = np.linspace(-3, 3, 1000) + >>> plt.plot(x, y, 'ro', ms=5) + >>> plt.plot(xs, spl(xs), 'g-', lw=3) + >>> plt.show() + + Check the knot vector: + + >>> spl.get_knots() + array([-3., -1., 0., 1., 3.]) + + Constructing lsq spline using the knots from another spline: + + >>> x = np.arange(10) + >>> s = UnivariateSpline(x, x, s=0) + >>> s.get_knots() + array([ 0., 2., 3., 4., 5., 6., 7., 9.]) + >>> knt = s.get_knots() + >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1]) # Chop 1st and last knot + >>> s1.get_knots() + array([ 0., 2., 3., 4., 5., 6., 7., 9.]) + + """ + + def __init__(self, x, y, t, w=None, bbox=[None]*2, k=3, + ext=0, check_finite=False): + + x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None, + ext, check_finite) + if not np.all(diff(x) >= 0.0): + raise ValueError('x must be increasing') + + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + xb = bbox[0] + xe = bbox[1] + if xb is None: + xb = x[0] + if xe is None: + xe = x[-1] + t = concatenate(([xb]*(k+1), t, [xe]*(k+1))) + n = len(t) + if not np.all(t[k+1:n-k]-t[k:n-k-1] > 0, axis=0): + raise ValueError('Interior knots t must satisfy ' + 'Schoenberg-Whitney conditions') + with FITPACK_LOCK: + if not dfitpack.fpchec(x, t, k) == 0: + raise ValueError(_fpchec_error_string) + data = dfitpack.fpcurfm1(x, y, k, t, w=w, xb=xb, xe=xe) + self._data = data[:-3] + (None, None, data[-1]) + self._reset_class() + + +# ############### Bivariate spline #################### + +class _BivariateSplineBase: + """ Base class for Bivariate spline s(x,y) interpolation on the rectangle + [xb,xe] x [yb, ye] calculated from a given set of data points + (x,y,z). + + See Also + -------- + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + BivariateSpline : + a base class for bivariate splines. + SphereBivariateSpline : + a bivariate spline on a spherical grid + """ + + @classmethod + def _from_tck(cls, tck): + """Construct a spline object from given tck and degree""" + self = cls.__new__(cls) + if len(tck) != 5: + raise ValueError("tck should be a 5 element tuple of tx," + " ty, c, kx, ky") + self.tck = tck[:3] + self.degrees = tck[3:] + return self + + def get_residual(self): + """ Return weighted sum of squared residuals of the spline + approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0) + """ + return self.fp + + def get_knots(self): + """ Return a tuple (tx,ty) where tx,ty contain knots positions + of the spline with respect to x-, y-variable, respectively. + The position of interior and additional knots are given as + t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively. + """ + return self.tck[:2] + + def get_coeffs(self): + """ Return spline coefficients.""" + return self.tck[2] + + def __call__(self, x, y, dx=0, dy=0, grid=True): + """ + Evaluate the spline or its derivatives at given positions. + + Parameters + ---------- + x, y : array_like + Input coordinates. + + If `grid` is False, evaluate the spline at points ``(x[i], + y[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting + is obeyed. + + If `grid` is True: evaluate spline at the grid points + defined by the coordinate arrays x, y. The arrays must be + sorted to increasing order. + + The ordering of axes is consistent with + ``np.meshgrid(..., indexing="ij")`` and inconsistent with the + default ordering ``np.meshgrid(..., indexing="xy")``. + dx : int + Order of x-derivative + + .. versionadded:: 0.14.0 + dy : int + Order of y-derivative + + .. versionadded:: 0.14.0 + grid : bool + Whether to evaluate the results on a grid spanned by the + input arrays, or at points specified by the input arrays. + + .. versionadded:: 0.14.0 + + Examples + -------- + Suppose that we want to bilinearly interpolate an exponentially decaying + function in 2 dimensions. + + >>> import numpy as np + >>> from scipy.interpolate import RectBivariateSpline + + We sample the function on a coarse grid. Note that the default indexing="xy" + of meshgrid would result in an unexpected (transposed) result after + interpolation. + + >>> xarr = np.linspace(-3, 3, 100) + >>> yarr = np.linspace(-3, 3, 100) + >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij") + + The function to interpolate decays faster along one axis than the other. + + >>> zdata = np.exp(-np.sqrt((xgrid / 2) ** 2 + ygrid**2)) + + Next we sample on a finer grid using interpolation (kx=ky=1 for bilinear). + + >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1) + >>> xarr_fine = np.linspace(-3, 3, 200) + >>> yarr_fine = np.linspace(-3, 3, 200) + >>> xgrid_fine, ygrid_fine = np.meshgrid(xarr_fine, yarr_fine, indexing="ij") + >>> zdata_interp = rbs(xgrid_fine, ygrid_fine, grid=False) + + And check that the result agrees with the input by plotting both. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 2, 1, aspect="equal") + >>> ax2 = fig.add_subplot(1, 2, 2, aspect="equal") + >>> ax1.imshow(zdata) + >>> ax2.imshow(zdata_interp) + >>> plt.show() + """ + x = np.asarray(x) + y = np.asarray(y) + + tx, ty, c = self.tck[:3] + kx, ky = self.degrees + if grid: + if x.size == 0 or y.size == 0: + return np.zeros((x.size, y.size), dtype=self.tck[2].dtype) + + if (x.size >= 2) and (not np.all(np.diff(x) >= 0.0)): + raise ValueError("x must be strictly increasing when `grid` is True") + if (y.size >= 2) and (not np.all(np.diff(y) >= 0.0)): + raise ValueError("y must be strictly increasing when `grid` is True") + + if dx or dy: + with FITPACK_LOCK: + z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y) + if not ier == 0: + raise ValueError(f"Error code returned by parder: {ier}") + else: + with FITPACK_LOCK: + z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y) + if not ier == 0: + raise ValueError(f"Error code returned by bispev: {ier}") + else: + # standard Numpy broadcasting + if x.shape != y.shape: + x, y = np.broadcast_arrays(x, y) + + shape = x.shape + x = x.ravel() + y = y.ravel() + + if x.size == 0 or y.size == 0: + return np.zeros(shape, dtype=self.tck[2].dtype) + + if dx or dy: + with FITPACK_LOCK: + z, ier = dfitpack.pardeu(tx, ty, c, kx, ky, dx, dy, x, y) + if not ier == 0: + raise ValueError(f"Error code returned by pardeu: {ier}") + else: + with FITPACK_LOCK: + z, ier = dfitpack.bispeu(tx, ty, c, kx, ky, x, y) + if not ier == 0: + raise ValueError(f"Error code returned by bispeu: {ier}") + + z = z.reshape(shape) + return z + + def partial_derivative(self, dx, dy): + """Construct a new spline representing a partial derivative of this + spline. + + Parameters + ---------- + dx, dy : int + Orders of the derivative in x and y respectively. They must be + non-negative integers and less than the respective degree of the + original spline (self) in that direction (``kx``, ``ky``). + + Returns + ------- + spline : + A new spline of degrees (``kx - dx``, ``ky - dy``) representing the + derivative of this spline. + + Notes + ----- + + .. versionadded:: 1.9.0 + + """ + if dx == 0 and dy == 0: + return self + else: + kx, ky = self.degrees + if not (dx >= 0 and dy >= 0): + raise ValueError("order of derivative must be positive or" + " zero") + if not (dx < kx and dy < ky): + raise ValueError("order of derivative must be less than" + " degree of spline") + tx, ty, c = self.tck[:3] + with FITPACK_LOCK: + newc, ier = dfitpack.pardtc(tx, ty, c, kx, ky, dx, dy) + if ier != 0: + # This should not happen under normal conditions. + raise ValueError("Unexpected error code returned by" + " pardtc: %d" % ier) + nx = len(tx) + ny = len(ty) + newtx = tx[dx:nx - dx] + newty = ty[dy:ny - dy] + newkx, newky = kx - dx, ky - dy + newclen = (nx - dx - kx - 1) * (ny - dy - ky - 1) + return _DerivedBivariateSpline._from_tck((newtx, newty, + newc[:newclen], + newkx, newky)) + + +_surfit_messages = {1: """ +The required storage space exceeds the available storage space: nxest +or nyest too small, or s too small. +The weighted least-squares spline corresponds to the current set of +knots.""", + 2: """ +A theoretically impossible result was found during the iteration +process for finding a smoothing spline with fp = s: s too small or +badly chosen eps. +Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""", + 3: """ +the maximal number of iterations maxit (set to 20 by the program) +allowed for finding a smoothing spline with fp=s has been reached: +s too small. +Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""", + 4: """ +No more knots can be added because the number of b-spline coefficients +(nx-kx-1)*(ny-ky-1) already exceeds the number of data points m: +either s or m too small. +The weighted least-squares spline corresponds to the current set of +knots.""", + 5: """ +No more knots can be added because the additional knot would (quasi) +coincide with an old one: s too small or too large a weight to an +inaccurate data point. +The weighted least-squares spline corresponds to the current set of +knots.""", + 10: """ +Error on entry, no approximation returned. The following conditions +must hold: +xb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1 +If iopt==-1, then + xb>> import numpy as np + >>> from scipy.interpolate import RectBivariateSpline + >>> def f(x, y): + ... return np.exp(-np.sqrt((x / 2) ** 2 + y**2)) + + We sample the function on a coarse grid and set up the interpolator. Note that + the default ``indexing="xy"`` of meshgrid would result in an unexpected + (transposed) result after interpolation. + + >>> xarr = np.linspace(-3, 3, 21) + >>> yarr = np.linspace(-3, 3, 21) + >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij") + >>> zdata = f(xgrid, ygrid) + >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1) + + Next we sample the function along a diagonal slice through the coordinate space + on a finer grid using interpolation. + + >>> xinterp = np.linspace(-3, 3, 201) + >>> yinterp = np.linspace(3, -3, 201) + >>> zinterp = rbs.ev(xinterp, yinterp) + + And check that the interpolation passes through the function evaluations as a + function of the distance from the origin along the slice. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 1, 1) + >>> ax1.plot(np.sqrt(xarr**2 + yarr**2), np.diag(zdata), "or") + >>> ax1.plot(np.sqrt(xinterp**2 + yinterp**2), zinterp, "-b") + >>> plt.show() + """ + return self.__call__(xi, yi, dx=dx, dy=dy, grid=False) + + def integral(self, xa, xb, ya, yb): + """ + Evaluate the integral of the spline over area [xa,xb] x [ya,yb]. + + Parameters + ---------- + xa, xb : float + The end-points of the x integration interval. + ya, yb : float + The end-points of the y integration interval. + + Returns + ------- + integ : float + The value of the resulting integral. + + """ + tx, ty, c = self.tck[:3] + kx, ky = self.degrees + with FITPACK_LOCK: + return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb) + + @staticmethod + def _validate_input(x, y, z, w, kx, ky, eps): + x, y, z = np.asarray(x), np.asarray(y), np.asarray(z) + if not x.size == y.size == z.size: + raise ValueError('x, y, and z should have a same length') + + if w is not None: + w = np.asarray(w) + if x.size != w.size: + raise ValueError('x, y, z, and w should have a same length') + elif not np.all(w >= 0.0): + raise ValueError('w should be positive') + if (eps is not None) and (not 0.0 < eps < 1.0): + raise ValueError('eps should be between (0, 1)') + if not x.size >= (kx + 1) * (ky + 1): + raise ValueError('The length of x, y and z should be at least' + ' (kx+1) * (ky+1)') + return x, y, z, w + + +class _DerivedBivariateSpline(_BivariateSplineBase): + """Bivariate spline constructed from the coefficients and knots of another + spline. + + Notes + ----- + The class is not meant to be instantiated directly from the data to be + interpolated or smoothed. As a result, its ``fp`` attribute and + ``get_residual`` method are inherited but overridden; ``AttributeError`` is + raised when they are accessed. + + The other inherited attributes can be used as usual. + """ + _invalid_why = ("is unavailable, because _DerivedBivariateSpline" + " instance is not constructed from data that are to be" + " interpolated or smoothed, but derived from the" + " underlying knots and coefficients of another spline" + " object") + + @property + def fp(self): + raise AttributeError(f"attribute \"fp\" {self._invalid_why}") + + def get_residual(self): + raise AttributeError(f"method \"get_residual\" {self._invalid_why}") + + +class SmoothBivariateSpline(BivariateSpline): + """ + Smooth bivariate spline approximation. + + Parameters + ---------- + x, y, z : array_like + 1-D sequences of data points (order is not important). + w : array_like, optional + Positive 1-D sequence of weights, of same length as `x`, `y` and `z`. + bbox : array_like, optional + Sequence of length 4 specifying the boundary of the rectangular + approximation domain. By default, + ``bbox=[min(x), max(x), min(y), max(y)]``. + kx, ky : ints, optional + Degrees of the bivariate spline. Default is 3. + s : float, optional + Positive smoothing factor defined for estimation condition: + ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s`` + Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an + estimate of the standard deviation of ``z[i]``. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the open + interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``. + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + This routine constructs spline knot vectors automatically via the FITPACK + algorithm. The spline knots may be placed away from the data points. For + some data sets, this routine may fail to construct an interpolating spline, + even if one is requested via ``s=0`` parameter. In such situations, it is + recommended to use `bisplrep` / `bisplev` directly instead of this routine + and, if needed, increase the values of ``nxest`` and ``nyest`` parameters + of `bisplrep`. + + For linear interpolation, prefer `LinearNDInterpolator`. + See ``https://gist.github.com/ev-br/8544371b40f414b7eaf3fe6217209bff`` + for discussion. + + """ + + def __init__(self, x, y, z, w=None, bbox=[None] * 4, kx=3, ky=3, s=None, + eps=1e-16): + + x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps) + bbox = ravel(bbox) + if not bbox.shape == (4,): + raise ValueError('bbox shape should be (4,)') + if s is not None and not s >= 0.0: + raise ValueError("s should be s >= 0.0") + + xb, xe, yb, ye = bbox + with FITPACK_LOCK: + nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth( + x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps, lwrk2=1) + if ier > 10: # lwrk2 was to small, re-run + nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth( + x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps, + lwrk2=ier) + if ier in [0, -1, -2]: # normal return + pass + else: + message = _surfit_messages.get(ier, f'ier={ier}') + warnings.warn(message, stacklevel=2) + + self.fp = fp + self.tck = tx[:nx], ty[:ny], c[:(nx-kx-1)*(ny-ky-1)] + self.degrees = kx, ky + + +class LSQBivariateSpline(BivariateSpline): + """ + Weighted least-squares bivariate spline approximation. + + Parameters + ---------- + x, y, z : array_like + 1-D sequences of data points (order is not important). + tx, ty : array_like + Strictly ordered 1-D sequences of knots coordinates. + w : array_like, optional + Positive 1-D array of weights, of the same length as `x`, `y` and `z`. + bbox : (4,) array_like, optional + Sequence of length 4 specifying the boundary of the rectangular + approximation domain. By default, + ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``. + kx, ky : ints, optional + Degrees of the bivariate spline. Default is 3. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the open + interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``. + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + """ + + def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3, + eps=None): + + x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps) + bbox = ravel(bbox) + if not bbox.shape == (4,): + raise ValueError('bbox shape should be (4,)') + + nx = 2*kx+2+len(tx) + ny = 2*ky+2+len(ty) + # The Fortran subroutine "surfit" (called as dfitpack.surfit_lsq) + # requires that the knot arrays passed as input should be "real + # array(s) of dimension nmax" where "nmax" refers to the greater of nx + # and ny. We pad the tx1/ty1 arrays here so that this is satisfied, and + # slice them to the desired sizes upon return. + nmax = max(nx, ny) + tx1 = zeros((nmax,), float) + ty1 = zeros((nmax,), float) + tx1[kx+1:nx-kx-1] = tx + ty1[ky+1:ny-ky-1] = ty + + xb, xe, yb, ye = bbox + with FITPACK_LOCK: + tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1, + w, xb, xe, yb, ye, + kx, ky, eps, lwrk2=1) + if ier > 10: + tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, + nx, tx1, ny, ty1, w, + xb, xe, yb, ye, + kx, ky, eps, lwrk2=ier) + if ier in [0, -1, -2]: # normal return + pass + else: + if ier < -2: + deficiency = (nx-kx-1)*(ny-ky-1)+ier + message = _surfit_messages.get(-3) % (deficiency) + else: + message = _surfit_messages.get(ier, f'ier={ier}') + warnings.warn(message, stacklevel=2) + self.fp = fp + self.tck = tx1[:nx], ty1[:ny], c + self.degrees = kx, ky + + +class RectBivariateSpline(BivariateSpline): + """ + Bivariate spline approximation over a rectangular mesh. + + Can be used for both smoothing and interpolating data. + + Parameters + ---------- + x,y : array_like + 1-D arrays of coordinates in strictly ascending order. + Evaluated points outside the data range will be extrapolated. + z : array_like + 2-D array of data with shape (x.size,y.size). + bbox : array_like, optional + Sequence of length 4 specifying the boundary of the rectangular + approximation domain, which means the start and end spline knots of + each dimension are set by these values. By default, + ``bbox=[min(x), max(x), min(y), max(y)]``. + kx, ky : ints, optional + Degrees of the bivariate spline. Default is 3. + s : float, optional + Positive smoothing factor defined for estimation condition: + ``sum((z[i]-f(x[i], y[i]))**2, axis=0) <= s`` where f is a spline + function. Default is ``s=0``, which is for interpolation. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + """ + + def __init__(self, x, y, z, bbox=[None] * 4, kx=3, ky=3, s=0): + x, y, bbox = ravel(x), ravel(y), ravel(bbox) + z = np.asarray(z) + if not np.all(diff(x) > 0.0): + raise ValueError('x must be strictly increasing') + if not np.all(diff(y) > 0.0): + raise ValueError('y must be strictly increasing') + if not x.size == z.shape[0]: + raise ValueError('x dimension of z must have same number of ' + 'elements as x') + if not y.size == z.shape[1]: + raise ValueError('y dimension of z must have same number of ' + 'elements as y') + if not bbox.shape == (4,): + raise ValueError('bbox shape should be (4,)') + if s is not None and not s >= 0.0: + raise ValueError("s should be s >= 0.0") + + z = ravel(z) + xb, xe, yb, ye = bbox + with FITPACK_LOCK: + nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth(x, y, z, xb, xe, yb, + ye, kx, ky, s) + + if ier not in [0, -1, -2]: + msg = _surfit_messages.get(ier, f'ier={ier}') + raise ValueError(msg) + + self.fp = fp + self.tck = tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)] + self.degrees = kx, ky + + +_spherefit_messages = _surfit_messages.copy() +_spherefit_messages[10] = """ +ERROR. On entry, the input data are controlled on validity. The following + restrictions must be satisfied: + -1<=iopt<=1, m>=2, ntest>=8 ,npest >=8, 00, i=1,...,m + lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m + kwrk >= m+(ntest-7)*(npest-7) + if iopt=-1: 8<=nt<=ntest , 9<=np<=npest + 0=0: s>=0 + if one of these conditions is found to be violated,control + is immediately repassed to the calling program. in that + case there is no approximation returned.""" +_spherefit_messages[-3] = """ +WARNING. The coefficients of the spline returned have been computed as the + minimal norm least-squares solution of a (numerically) rank + deficient system (deficiency=%i, rank=%i). Especially if the rank + deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large, + the results may be inaccurate. They could also seriously depend on + the value of eps.""" + + +class SphereBivariateSpline(_BivariateSplineBase): + """ + Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a + given set of data points (theta,phi,r). + + .. versionadded:: 0.11.0 + + See Also + -------- + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQUnivariateSpline : + a univariate spline using weighted least-squares fitting + """ + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + """ + Evaluate the spline or its derivatives at given positions. + + Parameters + ---------- + theta, phi : array_like + Input coordinates. + + If `grid` is False, evaluate the spline at points + ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard + Numpy broadcasting is obeyed. + + If `grid` is True: evaluate spline at the grid points + defined by the coordinate arrays theta, phi. The arrays + must be sorted to increasing order. + The ordering of axes is consistent with + ``np.meshgrid(..., indexing="ij")`` and inconsistent with the + default ordering ``np.meshgrid(..., indexing="xy")``. + dtheta : int, optional + Order of theta-derivative + + .. versionadded:: 0.14.0 + dphi : int + Order of phi-derivative + + .. versionadded:: 0.14.0 + grid : bool + Whether to evaluate the results on a grid spanned by the + input arrays, or at points specified by the input arrays. + + .. versionadded:: 0.14.0 + + Examples + -------- + + Suppose that we want to use splines to interpolate a bivariate function on a + sphere. The value of the function is known on a grid of longitudes and + colatitudes. + + >>> import numpy as np + >>> from scipy.interpolate import RectSphereBivariateSpline + >>> def f(theta, phi): + ... return np.sin(theta) * np.cos(phi) + + We evaluate the function on the grid. Note that the default indexing="xy" + of meshgrid would result in an unexpected (transposed) result after + interpolation. + + >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] + >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] + >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") + >>> zdata = f(thetagrid, phigrid) + + We next set up the interpolator and use it to evaluate the function + on a finer grid. + + >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) + >>> thetaarr_fine = np.linspace(0, np.pi, 200) + >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200) + >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine) + + Finally we plot the coarsly-sampled input data alongside the + finely-sampled interpolated data to check that they agree. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 2, 1) + >>> ax2 = fig.add_subplot(1, 2, 2) + >>> ax1.imshow(zdata) + >>> ax2.imshow(zdata_fine) + >>> plt.show() + """ + theta = np.asarray(theta) + phi = np.asarray(phi) + + if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi): + raise ValueError("requested theta out of bounds.") + + return _BivariateSplineBase.__call__(self, theta, phi, + dx=dtheta, dy=dphi, grid=grid) + + def ev(self, theta, phi, dtheta=0, dphi=0): + """ + Evaluate the spline at points + + Returns the interpolated value at ``(theta[i], phi[i]), + i=0,...,len(theta)-1``. + + Parameters + ---------- + theta, phi : array_like + Input coordinates. Standard Numpy broadcasting is obeyed. + The ordering of axes is consistent with + np.meshgrid(..., indexing="ij") and inconsistent with the + default ordering np.meshgrid(..., indexing="xy"). + dtheta : int, optional + Order of theta-derivative + + .. versionadded:: 0.14.0 + dphi : int, optional + Order of phi-derivative + + .. versionadded:: 0.14.0 + + Examples + -------- + Suppose that we want to use splines to interpolate a bivariate function on a + sphere. The value of the function is known on a grid of longitudes and + colatitudes. + + >>> import numpy as np + >>> from scipy.interpolate import RectSphereBivariateSpline + >>> def f(theta, phi): + ... return np.sin(theta) * np.cos(phi) + + We evaluate the function on the grid. Note that the default indexing="xy" + of meshgrid would result in an unexpected (transposed) result after + interpolation. + + >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] + >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] + >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") + >>> zdata = f(thetagrid, phigrid) + + We next set up the interpolator and use it to evaluate the function + at points not on the original grid. + + >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) + >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200) + >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200) + >>> zinterp = rsbs.ev(thetainterp, phiinterp) + + Finally we plot the original data for a diagonal slice through the + initial grid, and the spline approximation along the same slice. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 1, 1) + >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or") + >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b") + >>> plt.show() + """ + return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False) + + +class SmoothSphereBivariateSpline(SphereBivariateSpline): + """ + Smooth bivariate spline approximation in spherical coordinates. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + theta, phi, r : array_like + 1-D sequences of data points (order is not important). Coordinates + must be given in radians. Theta must lie within the interval + ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``. + w : array_like, optional + Positive 1-D sequence of weights. + s : float, optional + Positive smoothing factor defined for estimation condition: + ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s`` + Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an + estimate of the standard deviation of ``r[i]``. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the open + interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + For more information, see the FITPACK_ site about this function. + + .. _FITPACK: http://www.netlib.org/dierckx/sphere.f + + Examples + -------- + Suppose we have global data on a coarse grid (the input data does not + have to be on a grid): + + >>> import numpy as np + >>> theta = np.linspace(0., np.pi, 7) + >>> phi = np.linspace(0., 2*np.pi, 9) + >>> data = np.empty((theta.shape[0], phi.shape[0])) + >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0. + >>> data[1:-1,1], data[1:-1,-1] = 1., 1. + >>> data[1,1:-1], data[-2,1:-1] = 1., 1. + >>> data[2:-2,2], data[2:-2,-2] = 2., 2. + >>> data[2,2:-2], data[-3,2:-2] = 2., 2. + >>> data[3,3:-2] = 3. + >>> data = np.roll(data, 4, 1) + + We need to set up the interpolator object + + >>> lats, lons = np.meshgrid(theta, phi) + >>> from scipy.interpolate import SmoothSphereBivariateSpline + >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(), + ... data.T.ravel(), s=3.5) + + As a first test, we'll see what the algorithm returns when run on the + input coordinates + + >>> data_orig = lut(theta, phi) + + Finally we interpolate the data to a finer grid + + >>> fine_lats = np.linspace(0., np.pi, 70) + >>> fine_lons = np.linspace(0., 2 * np.pi, 90) + + >>> data_smth = lut(fine_lats, fine_lons) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(131) + >>> ax1.imshow(data, interpolation='nearest') + >>> ax2 = fig.add_subplot(132) + >>> ax2.imshow(data_orig, interpolation='nearest') + >>> ax3 = fig.add_subplot(133) + >>> ax3.imshow(data_smth, interpolation='nearest') + >>> plt.show() + + """ + + def __init__(self, theta, phi, r, w=None, s=0., eps=1E-16): + + theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r) + + # input validation + if not ((0.0 <= theta).all() and (theta <= np.pi).all()): + raise ValueError('theta should be between [0, pi]') + if not ((0.0 <= phi).all() and (phi <= 2.0 * np.pi).all()): + raise ValueError('phi should be between [0, 2pi]') + if w is not None: + w = np.asarray(w) + if not (w >= 0.0).all(): + raise ValueError('w should be positive') + if not s >= 0.0: + raise ValueError('s should be positive') + if not 0.0 < eps < 1.0: + raise ValueError('eps should be between (0, 1)') + + with FITPACK_LOCK: + nt_, tt_, np_, tp_, c, fp, ier = dfitpack.spherfit_smth(theta, phi, + r, w=w, s=s, + eps=eps) + if ier not in [0, -1, -2]: + message = _spherefit_messages.get(ier, f'ier={ier}') + raise ValueError(message) + + self.fp = fp + self.tck = tt_[:nt_], tp_[:np_], c[:(nt_ - 4) * (np_ - 4)] + self.degrees = (3, 3) + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + + theta = np.asarray(theta) + phi = np.asarray(phi) + + if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi): + raise ValueError("requested phi out of bounds.") + + return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta, + dphi=dphi, grid=grid) + + +class LSQSphereBivariateSpline(SphereBivariateSpline): + """ + Weighted least-squares bivariate spline approximation in spherical + coordinates. + + Determines a smoothing bicubic spline according to a given + set of knots in the `theta` and `phi` directions. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + theta, phi, r : array_like + 1-D sequences of data points (order is not important). Coordinates + must be given in radians. Theta must lie within the interval + ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``. + tt, tp : array_like + Strictly ordered 1-D sequences of knots coordinates. + Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``. + w : array_like, optional + Positive 1-D sequence of weights, of the same length as `theta`, `phi` + and `r`. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the + open interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + For more information, see the FITPACK_ site about this function. + + .. _FITPACK: http://www.netlib.org/dierckx/sphere.f + + Examples + -------- + Suppose we have global data on a coarse grid (the input data does not + have to be on a grid): + + >>> from scipy.interpolate import LSQSphereBivariateSpline + >>> import numpy as np + >>> import matplotlib.pyplot as plt + + >>> theta = np.linspace(0, np.pi, num=7) + >>> phi = np.linspace(0, 2*np.pi, num=9) + >>> data = np.empty((theta.shape[0], phi.shape[0])) + >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0. + >>> data[1:-1,1], data[1:-1,-1] = 1., 1. + >>> data[1,1:-1], data[-2,1:-1] = 1., 1. + >>> data[2:-2,2], data[2:-2,-2] = 2., 2. + >>> data[2,2:-2], data[-3,2:-2] = 2., 2. + >>> data[3,3:-2] = 3. + >>> data = np.roll(data, 4, 1) + + We need to set up the interpolator object. Here, we must also specify the + coordinates of the knots to use. + + >>> lats, lons = np.meshgrid(theta, phi) + >>> knotst, knotsp = theta.copy(), phi.copy() + >>> knotst[0] += .0001 + >>> knotst[-1] -= .0001 + >>> knotsp[0] += .0001 + >>> knotsp[-1] -= .0001 + >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + ... data.T.ravel(), knotst, knotsp) + + As a first test, we'll see what the algorithm returns when run on the + input coordinates + + >>> data_orig = lut(theta, phi) + + Finally we interpolate the data to a finer grid + + >>> fine_lats = np.linspace(0., np.pi, 70) + >>> fine_lons = np.linspace(0., 2*np.pi, 90) + >>> data_lsq = lut(fine_lats, fine_lons) + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(131) + >>> ax1.imshow(data, interpolation='nearest') + >>> ax2 = fig.add_subplot(132) + >>> ax2.imshow(data_orig, interpolation='nearest') + >>> ax3 = fig.add_subplot(133) + >>> ax3.imshow(data_lsq, interpolation='nearest') + >>> plt.show() + + """ + + def __init__(self, theta, phi, r, tt, tp, w=None, eps=1E-16): + + theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r) + tt, tp = np.asarray(tt), np.asarray(tp) + + if not ((0.0 <= theta).all() and (theta <= np.pi).all()): + raise ValueError('theta should be between [0, pi]') + if not ((0.0 <= phi).all() and (phi <= 2*np.pi).all()): + raise ValueError('phi should be between [0, 2pi]') + if not ((0.0 < tt).all() and (tt < np.pi).all()): + raise ValueError('tt should be between (0, pi)') + if not ((0.0 < tp).all() and (tp < 2*np.pi).all()): + raise ValueError('tp should be between (0, 2pi)') + if w is not None: + w = np.asarray(w) + if not (w >= 0.0).all(): + raise ValueError('w should be positive') + if not 0.0 < eps < 1.0: + raise ValueError('eps should be between (0, 1)') + + nt_, np_ = 8 + len(tt), 8 + len(tp) + tt_, tp_ = zeros((nt_,), float), zeros((np_,), float) + tt_[4:-4], tp_[4:-4] = tt, tp + tt_[-4:], tp_[-4:] = np.pi, 2. * np.pi + with FITPACK_LOCK: + tt_, tp_, c, fp, ier = dfitpack.spherfit_lsq(theta, phi, r, tt_, tp_, + w=w, eps=eps) + if ier > 0: + message = _spherefit_messages.get(ier, f'ier={ier}') + raise ValueError(message) + + self.fp = fp + self.tck = tt_, tp_, c + self.degrees = (3, 3) + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + + theta = np.asarray(theta) + phi = np.asarray(phi) + + if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi): + raise ValueError("requested phi out of bounds.") + + return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta, + dphi=dphi, grid=grid) + + +_spfit_messages = _surfit_messages.copy() +_spfit_messages[10] = """ +ERROR: on entry, the input data are controlled on validity + the following restrictions must be satisfied. + -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1, + -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0. + -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0. + mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8, + kwrk>=5+mu+mv+nuest+nvest, + lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest) + 0< u(i-1)=0: s>=0 + if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7 + if one of these conditions is found to be violated,control is + immediately repassed to the calling program. in that case there is no + approximation returned.""" + + +class RectSphereBivariateSpline(SphereBivariateSpline): + """ + Bivariate spline approximation over a rectangular mesh on a sphere. + + Can be used for smoothing data. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + u : array_like + 1-D array of colatitude coordinates in strictly ascending order. + Coordinates must be given in radians and lie within the open interval + ``(0, pi)``. + v : array_like + 1-D array of longitude coordinates in strictly ascending order. + Coordinates must be given in radians. First element (``v[0]``) must lie + within the interval ``[-pi, pi)``. Last element (``v[-1]``) must satisfy + ``v[-1] <= v[0] + 2*pi``. + r : array_like + 2-D array of data with shape ``(u.size, v.size)``. + s : float, optional + Positive smoothing factor defined for estimation condition + (``s=0`` is for interpolation). + pole_continuity : bool or (bool, bool), optional + Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and + ``u=pi`` (``pole_continuity[1]``). The order of continuity at the pole + will be 1 or 0 when this is True or False, respectively. + Defaults to False. + pole_values : float or (float, float), optional + Data values at the poles ``u=0`` and ``u=pi``. Either the whole + parameter or each individual element can be None. Defaults to None. + pole_exact : bool or (bool, bool), optional + Data value exactness at the poles ``u=0`` and ``u=pi``. If True, the + value is considered to be the right function value, and it will be + fitted exactly. If False, the value will be considered to be a data + value just like the other data values. Defaults to False. + pole_flat : bool or (bool, bool), optional + For the poles at ``u=0`` and ``u=pi``, specify whether or not the + approximation has vanishing derivatives. Defaults to False. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + Currently, only the smoothing spline approximation (``iopt[0] = 0`` and + ``iopt[0] = 1`` in the FITPACK routine) is supported. The exact + least-squares spline approximation is not implemented yet. + + When actually performing the interpolation, the requested `v` values must + lie within the same length 2pi interval that the original `v` values were + chosen from. + + For more information, see the FITPACK_ site about this function. + + .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f + + Examples + -------- + Suppose we have global data on a coarse grid + + >>> import numpy as np + >>> lats = np.linspace(10, 170, 9) * np.pi / 180. + >>> lons = np.linspace(0, 350, 18) * np.pi / 180. + >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T, + ... np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T + + We want to interpolate it to a global one-degree grid + + >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180 + >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180 + >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons) + + We need to set up the interpolator object + + >>> from scipy.interpolate import RectSphereBivariateSpline + >>> lut = RectSphereBivariateSpline(lats, lons, data) + + Finally we interpolate the data. The `RectSphereBivariateSpline` object + only takes 1-D arrays as input, therefore we need to do some reshaping. + + >>> data_interp = lut.ev(new_lats.ravel(), + ... new_lons.ravel()).reshape((360, 180)).T + + Looking at the original and the interpolated data, one can see that the + interpolant reproduces the original data very well: + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(211) + >>> ax1.imshow(data, interpolation='nearest') + >>> ax2 = fig.add_subplot(212) + >>> ax2.imshow(data_interp, interpolation='nearest') + >>> plt.show() + + Choosing the optimal value of ``s`` can be a delicate task. Recommended + values for ``s`` depend on the accuracy of the data values. If the user + has an idea of the statistical errors on the data, she can also find a + proper estimate for ``s``. By assuming that, if she specifies the + right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly + reproduces the function underlying the data, she can evaluate + ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``. + For example, if she knows that the statistical errors on her + ``r(i,j)``-values are not greater than 0.1, she may expect that a good + ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``. + + If nothing is known about the statistical error in ``r(i,j)``, ``s`` must + be determined by trial and error. The best is then to start with a very + large value of ``s`` (to determine the least-squares polynomial and the + corresponding upper bound ``fp0`` for ``s``) and then to progressively + decrease the value of ``s`` (say by a factor 10 in the beginning, i.e. + ``s = fp0 / 10, fp0 / 100, ...`` and more carefully as the approximation + shows more detail) to obtain closer fits. + + The interpolation results for different values of ``s`` give some insight + into this process: + + >>> fig2 = plt.figure() + >>> s = [3e9, 2e9, 1e9, 1e8] + >>> for idx, sval in enumerate(s, 1): + ... lut = RectSphereBivariateSpline(lats, lons, data, s=sval) + ... data_interp = lut.ev(new_lats.ravel(), + ... new_lons.ravel()).reshape((360, 180)).T + ... ax = fig2.add_subplot(2, 2, idx) + ... ax.imshow(data_interp, interpolation='nearest') + ... ax.set_title(f"s = {sval:g}") + >>> plt.show() + + """ + + def __init__(self, u, v, r, s=0., pole_continuity=False, pole_values=None, + pole_exact=False, pole_flat=False): + iopt = np.array([0, 0, 0], dtype=dfitpack_int) + ider = np.array([-1, 0, -1, 0], dtype=dfitpack_int) + if pole_values is None: + pole_values = (None, None) + elif isinstance(pole_values, (float, np.float32, np.float64)): + pole_values = (pole_values, pole_values) + if isinstance(pole_continuity, bool): + pole_continuity = (pole_continuity, pole_continuity) + if isinstance(pole_exact, bool): + pole_exact = (pole_exact, pole_exact) + if isinstance(pole_flat, bool): + pole_flat = (pole_flat, pole_flat) + + r0, r1 = pole_values + iopt[1:] = pole_continuity + if r0 is None: + ider[0] = -1 + else: + ider[0] = pole_exact[0] + + if r1 is None: + ider[2] = -1 + else: + ider[2] = pole_exact[1] + + ider[1], ider[3] = pole_flat + + u, v = np.ravel(u), np.ravel(v) + r = np.asarray(r) + + if not (0.0 < u[0] and u[-1] < np.pi): + raise ValueError('u should be between (0, pi)') + if not -np.pi <= v[0] < np.pi: + raise ValueError('v[0] should be between [-pi, pi)') + if not v[-1] <= v[0] + 2*np.pi: + raise ValueError('v[-1] should be v[0] + 2pi or less ') + + if not np.all(np.diff(u) > 0.0): + raise ValueError('u must be strictly increasing') + if not np.all(np.diff(v) > 0.0): + raise ValueError('v must be strictly increasing') + + if not u.size == r.shape[0]: + raise ValueError('u dimension of r must have same number of ' + 'elements as u') + if not v.size == r.shape[1]: + raise ValueError('v dimension of r must have same number of ' + 'elements as v') + + if pole_continuity[1] is False and pole_flat[1] is True: + raise ValueError('if pole_continuity is False, so must be ' + 'pole_flat') + if pole_continuity[0] is False and pole_flat[0] is True: + raise ValueError('if pole_continuity is False, so must be ' + 'pole_flat') + + if not s >= 0.0: + raise ValueError('s should be positive') + + r = np.ravel(r) + with FITPACK_LOCK: + nu, tu, nv, tv, c, fp, ier = dfitpack.regrid_smth_spher(iopt, ider, + u.copy(), + v.copy(), + r.copy(), + r0, r1, s) + + if ier not in [0, -1, -2]: + msg = _spfit_messages.get(ier, f'ier={ier}') + raise ValueError(msg) + + self.fp = fp + self.tck = tu[:nu], tv[:nv], c[:(nu - 4) * (nv-4)] + self.degrees = (3, 3) + self.v0 = v[0] + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + + theta = np.asarray(theta) + phi = np.asarray(phi) + + return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta, + dphi=dphi, grid=grid) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..a00ca101b591dd69b6b590278083f0bdafbd3a01 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py @@ -0,0 +1,805 @@ +""" +fitpack (dierckx in netlib) --- A Python-C wrapper to FITPACK (by P. Dierckx). + FITPACK is a collection of FORTRAN programs for curve and surface + fitting with splines and tensor product splines. + +See + https://web.archive.org/web/20010524124604/http://www.cs.kuleuven.ac.be:80/cwis/research/nalag/research/topics/fitpack.html +or + http://www.netlib.org/dierckx/ + +Copyright 2002 Pearu Peterson all rights reserved, +Pearu Peterson +Permission to use, modify, and distribute this software is given under the +terms of the SciPy (BSD style) license. See LICENSE.txt that came with +this distribution for specifics. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + +TODO: Make interfaces to the following fitpack functions: + For univariate splines: cocosp, concon, fourco, insert + For bivariate splines: profil, regrid, parsur, surev +""" + +__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde', + 'bisplrep', 'bisplev', 'insert', 'splder', 'splantider'] + +import warnings +import numpy as np +from . import _fitpack +from numpy import (atleast_1d, array, ones, zeros, sqrt, ravel, transpose, + empty, iinfo, asarray) + +# Try to replace _fitpack interface with +# f2py-generated version +from . import _dfitpack as dfitpack + + +dfitpack_int = dfitpack.types.intvar.dtype + + +def _int_overflow(x, exception, msg=None): + """Cast the value to an dfitpack_int and raise an OverflowError if the value + cannot fit. + """ + if x > iinfo(dfitpack_int).max: + if msg is None: + msg = f'{x!r} cannot fit into an {dfitpack_int!r}' + raise exception(msg) + return dfitpack_int.type(x) + + +_iermess = { + 0: ["The spline has a residual sum of squares fp such that " + "abs(fp-s)/s<=0.001", None], + -1: ["The spline is an interpolating spline (fp=0)", None], + -2: ["The spline is weighted least-squares polynomial of degree k.\n" + "fp gives the upper bound fp0 for the smoothing factor s", None], + 1: ["The required storage space exceeds the available storage space.\n" + "Probable causes: data (x,y) size is too small or smoothing parameter" + "\ns is too small (fp>s).", ValueError], + 2: ["A theoretically impossible result when finding a smoothing spline\n" + "with fp = s. Probable cause: s too small. (abs(fp-s)/s>0.001)", + ValueError], + 3: ["The maximal number of iterations (20) allowed for finding smoothing\n" + "spline with fp=s has been reached. Probable cause: s too small.\n" + "(abs(fp-s)/s>0.001)", ValueError], + 10: ["Error on input data", ValueError], + 'unknown': ["An error occurred", TypeError] +} + +_iermess2 = { + 0: ["The spline has a residual sum of squares fp such that " + "abs(fp-s)/s<=0.001", None], + -1: ["The spline is an interpolating spline (fp=0)", None], + -2: ["The spline is weighted least-squares polynomial of degree kx and ky." + "\nfp gives the upper bound fp0 for the smoothing factor s", None], + -3: ["Warning. The coefficients of the spline have been computed as the\n" + "minimal norm least-squares solution of a rank deficient system.", + None], + 1: ["The required storage space exceeds the available storage space.\n" + "Probable causes: nxest or nyest too small or s is too small. (fp>s)", + ValueError], + 2: ["A theoretically impossible result when finding a smoothing spline\n" + "with fp = s. Probable causes: s too small or badly chosen eps.\n" + "(abs(fp-s)/s>0.001)", ValueError], + 3: ["The maximal number of iterations (20) allowed for finding smoothing\n" + "spline with fp=s has been reached. Probable cause: s too small.\n" + "(abs(fp-s)/s>0.001)", ValueError], + 4: ["No more knots can be added because the number of B-spline\n" + "coefficients already exceeds the number of data points m.\n" + "Probable causes: either s or m too small. (fp>s)", ValueError], + 5: ["No more knots can be added because the additional knot would\n" + "coincide with an old one. Probable cause: s too small or too large\n" + "a weight to an inaccurate data point. (fp>s)", ValueError], + 10: ["Error on input data", ValueError], + 11: ["rwrk2 too small, i.e., there is not enough workspace for computing\n" + "the minimal least-squares solution of a rank deficient system of\n" + "linear equations.", ValueError], + 'unknown': ["An error occurred", TypeError] +} + +_parcur_cache = {'t': array([], float), 'wrk': array([], float), + 'iwrk': array([], dfitpack_int), 'u': array([], float), + 'ub': 0, 'ue': 1} + + +def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None, + full_output=0, nest=None, per=0, quiet=1): + # see the docstring of `_fitpack_py/splprep` + if task <= 0: + _parcur_cache = {'t': array([], float), 'wrk': array([], float), + 'iwrk': array([], dfitpack_int), 'u': array([], float), + 'ub': 0, 'ue': 1} + x = atleast_1d(x) + idim, m = x.shape + if per: + for i in range(idim): + if x[i][0] != x[i][-1]: + if not quiet: + warnings.warn(RuntimeWarning('Setting x[%d][%d]=x[%d][0]' % + (i, m, i)), + stacklevel=2) + x[i][-1] = x[i][0] + if not 0 < idim < 11: + raise TypeError('0 < idim < 11 must hold') + if w is None: + w = ones(m, float) + else: + w = atleast_1d(w) + ipar = (u is not None) + if ipar: + _parcur_cache['u'] = u + if ub is None: + _parcur_cache['ub'] = u[0] + else: + _parcur_cache['ub'] = ub + if ue is None: + _parcur_cache['ue'] = u[-1] + else: + _parcur_cache['ue'] = ue + else: + _parcur_cache['u'] = zeros(m, float) + if not (1 <= k <= 5): + raise TypeError('1 <= k= %d <=5 must hold' % k) + if not (-1 <= task <= 1): + raise TypeError('task must be -1, 0 or 1') + if (not len(w) == m) or (ipar == 1 and (not len(u) == m)): + raise TypeError('Mismatch of input dimensions') + if s is None: + s = m - sqrt(2*m) + if t is None and task == -1: + raise TypeError('Knots must be given for task=-1') + if t is not None: + _parcur_cache['t'] = atleast_1d(t) + n = len(_parcur_cache['t']) + if task == -1 and n < 2*k + 2: + raise TypeError('There must be at least 2*k+2 knots for task=-1') + if m <= k: + raise TypeError('m > k must hold') + if nest is None: + nest = m + 2*k + + if (task >= 0 and s == 0) or (nest < 0): + if per: + nest = m + 2*k + else: + nest = m + k + 1 + nest = max(nest, 2*k + 3) + u = _parcur_cache['u'] + ub = _parcur_cache['ub'] + ue = _parcur_cache['ue'] + t = _parcur_cache['t'] + wrk = _parcur_cache['wrk'] + iwrk = _parcur_cache['iwrk'] + t, c, o = _fitpack._parcur(ravel(transpose(x)), w, u, ub, ue, k, + task, ipar, s, t, nest, wrk, iwrk, per) + _parcur_cache['u'] = o['u'] + _parcur_cache['ub'] = o['ub'] + _parcur_cache['ue'] = o['ue'] + _parcur_cache['t'] = t + _parcur_cache['wrk'] = o['wrk'] + _parcur_cache['iwrk'] = o['iwrk'] + ier = o['ier'] + fp = o['fp'] + n = len(t) + u = o['u'] + c.shape = idim, n - k - 1 + tcku = [t, list(c), k], u + if ier <= 0 and not quiet: + warnings.warn(RuntimeWarning(_iermess[ier][0] + + "\tk=%d n=%d m=%d fp=%f s=%f" % + (k, len(t), m, fp, s)), + stacklevel=2) + if ier > 0 and not full_output: + if ier in [1, 2, 3]: + warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2) + else: + try: + raise _iermess[ier][1](_iermess[ier][0]) + except KeyError as e: + raise _iermess['unknown'][1](_iermess['unknown'][0]) from e + if full_output: + try: + return tcku, fp, ier, _iermess[ier][0] + except KeyError: + return tcku, fp, ier, _iermess['unknown'][0] + else: + return tcku + + +_curfit_cache = {'t': array([], float), 'wrk': array([], float), + 'iwrk': array([], dfitpack_int)} + + +def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None, + full_output=0, per=0, quiet=1): + # see the docstring of `_fitpack_py/splrep` + if task <= 0: + _curfit_cache = {} + x, y = map(atleast_1d, [x, y]) + m = len(x) + if w is None: + w = ones(m, float) + if s is None: + s = 0.0 + else: + w = atleast_1d(w) + if s is None: + s = m - sqrt(2*m) + if not len(w) == m: + raise TypeError('len(w)=%d is not equal to m=%d' % (len(w), m)) + if (m != len(y)) or (m != len(w)): + raise TypeError('Lengths of the first three arguments (x,y,w) must ' + 'be equal') + if not (1 <= k <= 5): + raise TypeError('Given degree of the spline (k=%d) is not supported. ' + '(1<=k<=5)' % k) + if m <= k: + raise TypeError('m > k must hold') + if xb is None: + xb = x[0] + if xe is None: + xe = x[-1] + if not (-1 <= task <= 1): + raise TypeError('task must be -1, 0 or 1') + if t is not None: + task = -1 + if task == -1: + if t is None: + raise TypeError('Knots must be given for task=-1') + numknots = len(t) + _curfit_cache['t'] = empty((numknots + 2*k + 2,), float) + _curfit_cache['t'][k+1:-k-1] = t + nest = len(_curfit_cache['t']) + elif task == 0: + if per: + nest = max(m + 2*k, 2*k + 3) + else: + nest = max(m + k + 1, 2*k + 3) + t = empty((nest,), float) + _curfit_cache['t'] = t + if task <= 0: + if per: + _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(8 + 5*k),), float) + else: + _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(7 + 3*k),), float) + _curfit_cache['iwrk'] = empty((nest,), dfitpack_int) + try: + t = _curfit_cache['t'] + wrk = _curfit_cache['wrk'] + iwrk = _curfit_cache['iwrk'] + except KeyError as e: + raise TypeError("must call with task=1 only after" + " call with task=0,-1") from e + if not per: + n, c, fp, ier = dfitpack.curfit(task, x, y, w, t, wrk, iwrk, + xb, xe, k, s) + else: + n, c, fp, ier = dfitpack.percur(task, x, y, w, t, wrk, iwrk, k, s) + tck = (t[:n], c[:n], k) + if ier <= 0 and not quiet: + _mess = (_iermess[ier][0] + "\tk=%d n=%d m=%d fp=%f s=%f" % + (k, len(t), m, fp, s)) + warnings.warn(RuntimeWarning(_mess), stacklevel=2) + if ier > 0 and not full_output: + if ier in [1, 2, 3]: + warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2) + else: + try: + raise _iermess[ier][1](_iermess[ier][0]) + except KeyError as e: + raise _iermess['unknown'][1](_iermess['unknown'][0]) from e + if full_output: + try: + return tck, fp, ier, _iermess[ier][0] + except KeyError: + return tck, fp, ier, _iermess['unknown'][0] + else: + return tck + + +def splev(x, tck, der=0, ext=0): + # see the docstring of `_fitpack_py/splev` + t, c, k = tck + try: + c[0][0] + parametric = True + except Exception: + parametric = False + if parametric: + return list(map(lambda c, x=x, t=t, k=k, der=der: + splev(x, [t, c, k], der, ext), c)) + else: + if not (0 <= der <= k): + raise ValueError("0<=der=%d<=k=%d must hold" % (der, k)) + if ext not in (0, 1, 2, 3): + raise ValueError(f"ext = {ext} not in (0, 1, 2, 3) ") + + x = asarray(x) + shape = x.shape + x = atleast_1d(x).ravel() + if der == 0: + y, ier = dfitpack.splev(t, c, k, x, ext) + else: + y, ier = dfitpack.splder(t, c, k, x, der, ext) + + if ier == 10: + raise ValueError("Invalid input data") + if ier == 1: + raise ValueError("Found x value not in the domain") + if ier: + raise TypeError("An error occurred") + + return y.reshape(shape) + + +def splint(a, b, tck, full_output=0): + # see the docstring of `_fitpack_py/splint` + t, c, k = tck + try: + c[0][0] + parametric = True + except Exception: + parametric = False + if parametric: + return list(map(lambda c, a=a, b=b, t=t, k=k: + splint(a, b, [t, c, k]), c)) + else: + aint, wrk = dfitpack.splint(t, c, k, a, b) + if full_output: + return aint, wrk + else: + return aint + + +def sproot(tck, mest=10): + # see the docstring of `_fitpack_py/sproot` + t, c, k = tck + if k != 3: + raise ValueError("sproot works only for cubic (k=3) splines") + try: + c[0][0] + parametric = True + except Exception: + parametric = False + if parametric: + return list(map(lambda c, t=t, k=k, mest=mest: + sproot([t, c, k], mest), c)) + else: + if len(t) < 8: + raise TypeError(f"The number of knots {len(t)}>=8") + z, m, ier = dfitpack.sproot(t, c, mest) + if ier == 10: + raise TypeError("Invalid input data. " + "t1<=..<=t4 1: + return list(map(lambda x, tck=tck: spalde(x, tck), x)) + d, ier = dfitpack.spalde(t, c, k+1, x[0]) + if ier == 0: + return d + if ier == 10: + raise TypeError("Invalid input data. t(k)<=x<=t(n-k+1) must hold.") + raise TypeError("Unknown error") + +# def _curfit(x,y,w=None,xb=None,xe=None,k=3,task=0,s=None,t=None, +# full_output=0,nest=None,per=0,quiet=1): + + +_surfit_cache = {'tx': array([], float), 'ty': array([], float), + 'wrk': array([], float), 'iwrk': array([], dfitpack_int)} + + +def bisplrep(x, y, z, w=None, xb=None, xe=None, yb=None, ye=None, + kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None, + full_output=0, nxest=None, nyest=None, quiet=1): + """ + Find a bivariate B-spline representation of a surface. + + Given a set of data points (x[i], y[i], z[i]) representing a surface + z=f(x,y), compute a B-spline representation of the surface. Based on + the routine SURFIT from FITPACK. + + Parameters + ---------- + x, y, z : ndarray + Rank-1 arrays of data points. + w : ndarray, optional + Rank-1 array of weights. By default ``w=np.ones(len(x))``. + xb, xe : float, optional + End points of approximation interval in `x`. + By default ``xb = x.min(), xe=x.max()``. + yb, ye : float, optional + End points of approximation interval in `y`. + By default ``yb=y.min(), ye = y.max()``. + kx, ky : int, optional + The degrees of the spline (1 <= kx, ky <= 5). + Third order (kx=ky=3) is recommended. + task : int, optional + If task=0, find knots in x and y and coefficients for a given + smoothing factor, s. + If task=1, find knots and coefficients for another value of the + smoothing factor, s. bisplrep must have been previously called + with task=0 or task=1. + If task=-1, find coefficients for a given set of knots tx, ty. + s : float, optional + A non-negative smoothing factor. If weights correspond + to the inverse of the standard-deviation of the errors in z, + then a good s-value should be found in the range + ``(m-sqrt(2*m),m+sqrt(2*m))`` where m=len(x). + eps : float, optional + A threshold for determining the effective rank of an + over-determined linear system of equations (0 < eps < 1). + `eps` is not likely to need changing. + tx, ty : ndarray, optional + Rank-1 arrays of the knots of the spline for task=-1 + full_output : int, optional + Non-zero to return optional outputs. + nxest, nyest : int, optional + Over-estimates of the total number of knots. If None then + ``nxest = max(kx+sqrt(m/2),2*kx+3)``, + ``nyest = max(ky+sqrt(m/2),2*ky+3)``. + quiet : int, optional + Non-zero to suppress printing of messages. + + Returns + ------- + tck : array_like + A list [tx, ty, c, kx, ky] containing the knots (tx, ty) and + coefficients (c) of the bivariate B-spline representation of the + surface along with the degree of the spline. + fp : ndarray + The weighted sum of squared residuals of the spline approximation. + ier : int + An integer flag about splrep success. Success is indicated if + ier<=0. If ier in [1,2,3] an error occurred but was not raised. + Otherwise an error is raised. + msg : str + A message corresponding to the integer flag, ier. + + See Also + -------- + splprep, splrep, splint, sproot, splev + UnivariateSpline, BivariateSpline + + Notes + ----- + See `bisplev` to evaluate the value of the B-spline given its tck + representation. + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolation. + + References + ---------- + .. [1] Dierckx P.:An algorithm for surface fitting with spline functions + Ima J. Numer. Anal. 1 (1981) 267-283. + .. [2] Dierckx P.:An algorithm for surface fitting with spline functions + report tw50, Dept. Computer Science,K.U.Leuven, 1980. + .. [3] Dierckx P.:Curve and surface fitting with splines, Monographs on + Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + Examples are given :ref:`in the tutorial `. + + """ + x, y, z = map(ravel, [x, y, z]) # ensure 1-d arrays. + m = len(x) + if not (m == len(y) == len(z)): + raise TypeError('len(x)==len(y)==len(z) must hold.') + if w is None: + w = ones(m, float) + else: + w = atleast_1d(w) + if not len(w) == m: + raise TypeError('len(w)=%d is not equal to m=%d' % (len(w), m)) + if xb is None: + xb = x.min() + if xe is None: + xe = x.max() + if yb is None: + yb = y.min() + if ye is None: + ye = y.max() + if not (-1 <= task <= 1): + raise TypeError('task must be -1, 0 or 1') + if s is None: + s = m - sqrt(2*m) + if tx is None and task == -1: + raise TypeError('Knots_x must be given for task=-1') + if tx is not None: + _surfit_cache['tx'] = atleast_1d(tx) + nx = len(_surfit_cache['tx']) + if ty is None and task == -1: + raise TypeError('Knots_y must be given for task=-1') + if ty is not None: + _surfit_cache['ty'] = atleast_1d(ty) + ny = len(_surfit_cache['ty']) + if task == -1 and nx < 2*kx+2: + raise TypeError('There must be at least 2*kx+2 knots_x for task=-1') + if task == -1 and ny < 2*ky+2: + raise TypeError('There must be at least 2*ky+2 knots_x for task=-1') + if not ((1 <= kx <= 5) and (1 <= ky <= 5)): + raise TypeError('Given degree of the spline (kx,ky=%d,%d) is not ' + 'supported. (1<=k<=5)' % (kx, ky)) + if m < (kx + 1)*(ky + 1): + raise TypeError('m >= (kx+1)(ky+1) must hold') + if nxest is None: + nxest = int(kx + sqrt(m/2)) + if nyest is None: + nyest = int(ky + sqrt(m/2)) + nxest, nyest = max(nxest, 2*kx + 3), max(nyest, 2*ky + 3) + if task >= 0 and s == 0: + nxest = int(kx + sqrt(3*m)) + nyest = int(ky + sqrt(3*m)) + if task == -1: + _surfit_cache['tx'] = atleast_1d(tx) + _surfit_cache['ty'] = atleast_1d(ty) + tx, ty = _surfit_cache['tx'], _surfit_cache['ty'] + wrk = _surfit_cache['wrk'] + u = nxest - kx - 1 + v = nyest - ky - 1 + km = max(kx, ky) + 1 + ne = max(nxest, nyest) + bx, by = kx*v + ky + 1, ky*u + kx + 1 + b1, b2 = bx, bx + v - ky + if bx > by: + b1, b2 = by, by + u - kx + msg = "Too many data points to interpolate" + lwrk1 = _int_overflow(u*v*(2 + b1 + b2) + + 2*(u + v + km*(m + ne) + ne - kx - ky) + b2 + 1, + OverflowError, + msg=msg) + lwrk2 = _int_overflow(u*v*(b2 + 1) + b2, OverflowError, msg=msg) + tx, ty, c, o = _fitpack._surfit(x, y, z, w, xb, xe, yb, ye, kx, ky, + task, s, eps, tx, ty, nxest, nyest, + wrk, lwrk1, lwrk2) + _curfit_cache['tx'] = tx + _curfit_cache['ty'] = ty + _curfit_cache['wrk'] = o['wrk'] + ier, fp = o['ier'], o['fp'] + tck = [tx, ty, c, kx, ky] + + ierm = min(11, max(-3, ier)) + if ierm <= 0 and not quiet: + _mess = (_iermess2[ierm][0] + + "\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" % + (kx, ky, len(tx), len(ty), m, fp, s)) + warnings.warn(RuntimeWarning(_mess), stacklevel=2) + if ierm > 0 and not full_output: + if ier in [1, 2, 3, 4, 5]: + _mess = ("\n\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" % + (kx, ky, len(tx), len(ty), m, fp, s)) + warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess), stacklevel=2) + else: + try: + raise _iermess2[ierm][1](_iermess2[ierm][0]) + except KeyError as e: + raise _iermess2['unknown'][1](_iermess2['unknown'][0]) from e + if full_output: + try: + return tck, fp, ier, _iermess2[ierm][0] + except KeyError: + return tck, fp, ier, _iermess2['unknown'][0] + else: + return tck + + +def bisplev(x, y, tck, dx=0, dy=0): + """ + Evaluate a bivariate B-spline and its derivatives. + + Return a rank-2 array of spline function values (or spline derivative + values) at points given by the cross-product of the rank-1 arrays `x` and + `y`. In special cases, return an array or just a float if either `x` or + `y` or both are floats. Based on BISPEV and PARDER from FITPACK. + + Parameters + ---------- + x, y : ndarray + Rank-1 arrays specifying the domain over which to evaluate the + spline or its derivative. + tck : tuple + A sequence of length 5 returned by `bisplrep` containing the knot + locations, the coefficients, and the degree of the spline: + [tx, ty, c, kx, ky]. + dx, dy : int, optional + The orders of the partial derivatives in `x` and `y` respectively. + + Returns + ------- + vals : ndarray + The B-spline or its derivative evaluated over the set formed by + the cross-product of `x` and `y`. + + See Also + -------- + splprep, splrep, splint, sproot, splev + UnivariateSpline, BivariateSpline + + Notes + ----- + See `bisplrep` to generate the `tck` representation. + + References + ---------- + .. [1] Dierckx P. : An algorithm for surface fitting + with spline functions + Ima J. Numer. Anal. 1 (1981) 267-283. + .. [2] Dierckx P. : An algorithm for surface fitting + with spline functions + report tw50, Dept. Computer Science,K.U.Leuven, 1980. + .. [3] Dierckx P. : Curve and surface fitting with splines, + Monographs on Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + Examples are given :ref:`in the tutorial `. + + """ + tx, ty, c, kx, ky = tck + if not (0 <= dx < kx): + raise ValueError("0 <= dx = %d < kx = %d must hold" % (dx, kx)) + if not (0 <= dy < ky): + raise ValueError("0 <= dy = %d < ky = %d must hold" % (dy, ky)) + x, y = map(atleast_1d, [x, y]) + if (len(x.shape) != 1) or (len(y.shape) != 1): + raise ValueError("First two entries should be rank-1 arrays.") + + msg = "Too many data points to interpolate." + + _int_overflow(x.size * y.size, MemoryError, msg=msg) + + if dx != 0 or dy != 0: + _int_overflow((tx.size - kx - 1)*(ty.size - ky - 1), + MemoryError, msg=msg) + z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y) + else: + z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y) + + if ier == 10: + raise ValueError("Invalid input data") + if ier: + raise TypeError("An error occurred") + z.shape = len(x), len(y) + if len(z) > 1: + return z + if len(z[0]) > 1: + return z[0] + return z[0][0] + + +def dblint(xa, xb, ya, yb, tck): + """Evaluate the integral of a spline over area [xa,xb] x [ya,yb]. + + Parameters + ---------- + xa, xb : float + The end-points of the x integration interval. + ya, yb : float + The end-points of the y integration interval. + tck : list [tx, ty, c, kx, ky] + A sequence of length 5 returned by bisplrep containing the knot + locations tx, ty, the coefficients c, and the degrees kx, ky + of the spline. + + Returns + ------- + integ : float + The value of the resulting integral. + """ + tx, ty, c, kx, ky = tck + return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb) + + +def insert(x, tck, m=1, per=0): + # see the docstring of `_fitpack_py/insert` + t, c, k = tck + try: + c[0][0] + parametric = True + except Exception: + parametric = False + if parametric: + cc = [] + for c_vals in c: + tt, cc_val, kk = insert(x, [t, c_vals, k], m) + cc.append(cc_val) + return (tt, cc, kk) + else: + tt, cc, ier = _fitpack._insert(per, t, c, k, x, m) + if ier == 10: + raise ValueError("Invalid input data") + if ier: + raise TypeError("An error occurred") + return (tt, cc, k) + + +def splder(tck, n=1): + # see the docstring of `_fitpack_py/splder` + if n < 0: + return splantider(tck, -n) + + t, c, k = tck + + if n > k: + raise ValueError(f"Order of derivative (n = {n!r}) must be <= " + f"order of spline (k = {tck[2]!r})") + + # Extra axes for the trailing dims of the `c` array: + sh = (slice(None),) + ((None,)*len(c.shape[1:])) + + with np.errstate(invalid='raise', divide='raise'): + try: + for j in range(n): + # See e.g. Schumaker, Spline Functions: Basic Theory, Chapter 5 + + # Compute the denominator in the differentiation formula. + # (and append trailing dims, if necessary) + dt = t[k+1:-1] - t[1:-k-1] + dt = dt[sh] + # Compute the new coefficients + c = (c[1:-1-k] - c[:-2-k]) * k / dt + # Pad coefficient array to same size as knots (FITPACK + # convention) + c = np.r_[c, np.zeros((k,) + c.shape[1:])] + # Adjust knots + t = t[1:-1] + k -= 1 + except FloatingPointError as e: + raise ValueError(("The spline has internal repeated knots " + "and is not differentiable %d times") % n) from e + + return t, c, k + + +def splantider(tck, n=1): + # see the docstring of `_fitpack_py/splantider` + if n < 0: + return splder(tck, -n) + + t, c, k = tck + + # Extra axes for the trailing dims of the `c` array: + sh = (slice(None),) + (None,)*len(c.shape[1:]) + + for j in range(n): + # This is the inverse set of operations to splder. + + # Compute the multiplier in the antiderivative formula. + dt = t[k+1:] - t[:-k-1] + dt = dt[sh] + # Compute the new coefficients + c = np.cumsum(c[:-k-1] * dt, axis=0) / (k + 1) + c = np.r_[np.zeros((1,) + c.shape[1:]), + c, + [c[-1]] * (k+2)] + # New knots + t = np.r_[t[0], t, t[-1]] + k += 1 + + return t, c, k diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7a2ded7e46885b4e0e0e4ccdb8065c25742e6a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py @@ -0,0 +1,898 @@ +__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde', + 'bisplrep', 'bisplev', 'insert', 'splder', 'splantider'] + + +import numpy as np + +# These are in the API for fitpack even if not used in fitpack.py itself. +from ._fitpack_impl import bisplrep, bisplev, dblint # noqa: F401 +from . import _fitpack_impl as _impl +from ._bsplines import BSpline + + +def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None, + full_output=0, nest=None, per=0, quiet=1): + """ + Find the B-spline representation of an N-D curve. + + .. legacy:: function + + Specifically, we recommend using `make_splprep` in new code. + + Given a list of N rank-1 arrays, `x`, which represent a curve in + N-dimensional space parametrized by `u`, find a smooth approximating + spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK. + + Parameters + ---------- + x : array_like + A list of sample vector arrays representing the curve. + w : array_like, optional + Strictly positive rank-1 array of weights the same length as `x[0]`. + The weights are used in computing the weighted least-squares spline + fit. If the errors in the `x` values have standard-deviation given by + the vector d, then `w` should be 1/d. Default is ``ones(len(x[0]))``. + u : array_like, optional + An array of parameter values. If not given, these values are + calculated automatically as ``M = len(x[0])``, where + + v[0] = 0 + + v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`) + + u[i] = v[i] / v[M-1] + + ub, ue : int, optional + The end-points of the parameters interval. Defaults to + u[0] and u[-1]. + k : int, optional + Degree of the spline. Cubic splines are recommended. + Even values of `k` should be avoided especially with a small s-value. + ``1 <= k <= 5``, default is 3. + task : int, optional + If task==0 (default), find t and c for a given smoothing factor, s. + If task==1, find t and c for another value of the smoothing factor, s. + There must have been a previous call with task=0 or task=1 + for the same set of data. + If task=-1 find the weighted least square spline for a given set of + knots, t. + s : float, optional + A smoothing condition. The amount of smoothness is determined by + satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s``, + where g(x) is the smoothed interpolation of (x,y). The user can + use `s` to control the trade-off between closeness and smoothness + of fit. Larger `s` means more smoothing while smaller values of `s` + indicate less smoothing. Recommended values of `s` depend on the + weights, w. If the weights represent the inverse of the + standard-deviation of y, then a good `s` value should be found in + the range ``(m-sqrt(2*m),m+sqrt(2*m))``, where m is the number of + data points in x, y, and w. + t : array, optional + The knots needed for ``task=-1``. + There must be at least ``2*k+2`` knots. + full_output : int, optional + If non-zero, then return optional outputs. + nest : int, optional + An over-estimate of the total number of knots of the spline to + help in determining the storage space. By default nest=m/2. + Always large enough is nest=m+k+1. + per : int, optional + If non-zero, data points are considered periodic with period + ``x[m-1] - x[0]`` and a smooth periodic spline approximation is + returned. Values of ``y[m-1]`` and ``w[m-1]`` are not used. + quiet : int, optional + Non-zero to suppress messages. + + Returns + ------- + tck : tuple + A tuple, ``(t,c,k)`` containing the vector of knots, the B-spline + coefficients, and the degree of the spline. + u : array + An array of the values of the parameter. + fp : float + The weighted sum of squared residuals of the spline approximation. + ier : int + An integer flag about splrep success. Success is indicated + if ier<=0. If ier in [1,2,3] an error occurred but was not raised. + Otherwise an error is raised. + msg : str + A message corresponding to the integer flag, ier. + + See Also + -------- + splrep, splev, sproot, spalde, splint, + bisplrep, bisplev + UnivariateSpline, BivariateSpline + BSpline + make_interp_spline + + Notes + ----- + See `splev` for evaluation of the spline and its derivatives. + The number of dimensions N must be smaller than 11. + + The number of coefficients in the `c` array is ``k+1`` less than the number + of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads + the array of coefficients to have the same length as the array of knots. + These additional coefficients are ignored by evaluation routines, `splev` + and `BSpline`. + + References + ---------- + .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and + parametric splines, Computer Graphics and Image Processing", + 20 (1982) 171-184. + .. [2] P. Dierckx, "Algorithms for smoothing data with periodic and + parametric splines", report tw55, Dept. Computer Science, + K.U.Leuven, 1981. + .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on + Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + Generate a discretization of a limacon curve in the polar coordinates: + + >>> import numpy as np + >>> phi = np.linspace(0, 2.*np.pi, 40) + >>> r = 0.5 + np.cos(phi) # polar coords + >>> x, y = r * np.cos(phi), r * np.sin(phi) # convert to cartesian + + And interpolate: + + >>> from scipy.interpolate import splprep, splev + >>> tck, u = splprep([x, y], s=0) + >>> new_points = splev(u, tck) + + Notice that (i) we force interpolation by using ``s=0``, + (ii) the parameterization, ``u``, is generated automatically. + Now plot the result: + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.plot(x, y, 'ro') + >>> ax.plot(new_points[0], new_points[1], 'r-') + >>> plt.show() + + """ + + res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per, + quiet) + return res + + +def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None, + full_output=0, per=0, quiet=1): + """ + Find the B-spline representation of a 1-D curve. + + .. legacy:: function + + Specifically, we recommend using `make_splrep` in new code. + + + Given the set of data points ``(x[i], y[i])`` determine a smooth spline + approximation of degree k on the interval ``xb <= x <= xe``. + + Parameters + ---------- + x, y : array_like + The data points defining a curve ``y = f(x)``. + w : array_like, optional + Strictly positive rank-1 array of weights the same length as `x` and `y`. + The weights are used in computing the weighted least-squares spline + fit. If the errors in the `y` values have standard-deviation given by the + vector ``d``, then `w` should be ``1/d``. Default is ``ones(len(x))``. + xb, xe : float, optional + The interval to fit. If None, these default to ``x[0]`` and ``x[-1]`` + respectively. + k : int, optional + The degree of the spline fit. It is recommended to use cubic splines. + Even values of `k` should be avoided especially with small `s` values. + ``1 <= k <= 5``. + task : {1, 0, -1}, optional + If ``task==0``, find ``t`` and ``c`` for a given smoothing factor, `s`. + + If ``task==1`` find ``t`` and ``c`` for another value of the smoothing factor, + `s`. There must have been a previous call with ``task=0`` or ``task=1`` for + the same set of data (``t`` will be stored an used internally) + + If ``task=-1`` find the weighted least square spline for a given set of + knots, ``t``. These should be interior knots as knots on the ends will be + added automatically. + s : float, optional + A smoothing condition. The amount of smoothness is determined by + satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s`` where ``g(x)`` + is the smoothed interpolation of ``(x,y)``. The user can use `s` to control + the tradeoff between closeness and smoothness of fit. Larger `s` means + more smoothing while smaller values of `s` indicate less smoothing. + Recommended values of `s` depend on the weights, `w`. If the weights + represent the inverse of the standard-deviation of `y`, then a good `s` + value should be found in the range ``(m-sqrt(2*m),m+sqrt(2*m))`` where ``m`` is + the number of datapoints in `x`, `y`, and `w`. default : ``s=m-sqrt(2*m)`` if + weights are supplied. ``s = 0.0`` (interpolating) if no weights are + supplied. + t : array_like, optional + The knots needed for ``task=-1``. If given then task is automatically set + to ``-1``. + full_output : bool, optional + If non-zero, then return optional outputs. + per : bool, optional + If non-zero, data points are considered periodic with period ``x[m-1]`` - + ``x[0]`` and a smooth periodic spline approximation is returned. Values of + ``y[m-1]`` and ``w[m-1]`` are not used. + The default is zero, corresponding to boundary condition 'not-a-knot'. + quiet : bool, optional + Non-zero to suppress messages. + + Returns + ------- + tck : tuple + A tuple ``(t,c,k)`` containing the vector of knots, the B-spline + coefficients, and the degree of the spline. + fp : array, optional + The weighted sum of squared residuals of the spline approximation. + ier : int, optional + An integer flag about splrep success. Success is indicated if ``ier<=0``. + If ``ier in [1,2,3]``, an error occurred but was not raised. Otherwise an + error is raised. + msg : str, optional + A message corresponding to the integer flag, `ier`. + + See Also + -------- + UnivariateSpline, BivariateSpline + splprep, splev, sproot, spalde, splint + bisplrep, bisplev + BSpline + make_interp_spline + + Notes + ----- + See `splev` for evaluation of the spline and its derivatives. Uses the + FORTRAN routine ``curfit`` from FITPACK. + + The user is responsible for assuring that the values of `x` are unique. + Otherwise, `splrep` will not return sensible results. + + If provided, knots `t` must satisfy the Schoenberg-Whitney conditions, + i.e., there must be a subset of data points ``x[j]`` such that + ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``. + + This routine zero-pads the coefficients array ``c`` to have the same length + as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored + by the evaluation routines, `splev` and `BSpline`.) This is in contrast with + `splprep`, which does not zero-pad the coefficients. + + The default boundary condition is 'not-a-knot', i.e. the first and second + segment at a curve end are the same polynomial. More boundary conditions are + available in `CubicSpline`. + + References + ---------- + Based on algorithms described in [1]_, [2]_, [3]_, and [4]_: + + .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and + integration of experimental data using spline functions", + J.Comp.Appl.Maths 1 (1975) 165-184. + .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular + grid while using spline functions", SIAM J.Numer.Anal. 19 (1982) + 1286-1304. + .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline + functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981. + .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on + Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + You can interpolate 1-D points with a B-spline curve. + Further examples are given in + :ref:`in the tutorial `. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import splev, splrep + >>> x = np.linspace(0, 10, 10) + >>> y = np.sin(x) + >>> spl = splrep(x, y) + >>> x2 = np.linspace(0, 10, 200) + >>> y2 = splev(x2, spl) + >>> plt.plot(x, y, 'o', x2, y2) + >>> plt.show() + + """ + res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet) + return res + + +def splev(x, tck, der=0, ext=0): + """ + Evaluate a B-spline or its derivatives. + + .. legacy:: function + + Specifically, we recommend constructing a `BSpline` object and using + its ``__call__`` method. + + Given the knots and coefficients of a B-spline representation, evaluate + the value of the smoothing polynomial and its derivatives. This is a + wrapper around the FORTRAN routines splev and splder of FITPACK. + + Parameters + ---------- + x : array_like + An array of points at which to return the value of the smoothed + spline or its derivatives. If `tck` was returned from `splprep`, + then the parameter values, u should be given. + tck : BSpline instance or tuple + If a tuple, then it should be a sequence of length 3 returned by + `splrep` or `splprep` containing the knots, coefficients, and degree + of the spline. (Also see Notes.) + der : int, optional + The order of derivative of the spline to compute (must be less than + or equal to k, the degree of the spline). + ext : int, optional + Controls the value returned for elements of ``x`` not in the + interval defined by the knot sequence. + + * if ext=0, return the extrapolated value. + * if ext=1, return 0 + * if ext=2, raise a ValueError + * if ext=3, return the boundary value. + + The default value is 0. + + Returns + ------- + y : ndarray or list of ndarrays + An array of values representing the spline function evaluated at + the points in `x`. If `tck` was returned from `splprep`, then this + is a list of arrays representing the curve in an N-D space. + + See Also + -------- + splprep, splrep, sproot, spalde, splint + bisplrep, bisplev + BSpline + + Notes + ----- + Manipulating the tck-tuples directly is not recommended. In new code, + prefer using `BSpline` objects. + + References + ---------- + .. [1] C. de Boor, "On calculating with b-splines", J. Approximation + Theory, 6, p.50-62, 1972. + .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths + Applics, 10, p.134-149, 1972. + .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs + on Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + Examples are given :ref:`in the tutorial `. + + A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a + B-spline can be found in the `spalde` examples section. + + """ + if isinstance(tck, BSpline): + if tck.c.ndim > 1: + mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is " + "not allowed. Use BSpline.__call__(x) instead.") + raise ValueError(mesg) + + # remap the out-of-bounds behavior + try: + extrapolate = {0: True, }[ext] + except KeyError as e: + raise ValueError(f"Extrapolation mode {ext} is not supported " + "by BSpline.") from e + + return tck(x, der, extrapolate=extrapolate) + else: + return _impl.splev(x, tck, der, ext) + + +def splint(a, b, tck, full_output=0): + """ + Evaluate the definite integral of a B-spline between two given points. + + .. legacy:: function + + Specifically, we recommend constructing a `BSpline` object and using its + ``integrate`` method. + + Parameters + ---------- + a, b : float + The end-points of the integration interval. + tck : tuple or a BSpline instance + If a tuple, then it should be a sequence of length 3, containing the + vector of knots, the B-spline coefficients, and the degree of the + spline (see `splev`). + full_output : int, optional + Non-zero to return optional output. + + Returns + ------- + integral : float + The resulting integral. + wrk : ndarray + An array containing the integrals of the normalized B-splines + defined on the set of knots. + (Only returned if `full_output` is non-zero) + + See Also + -------- + splprep, splrep, sproot, spalde, splev + bisplrep, bisplev + BSpline + + Notes + ----- + `splint` silently assumes that the spline function is zero outside the data + interval (`a`, `b`). + + Manipulating the tck-tuples directly is not recommended. In new code, + prefer using the `BSpline` objects. + + References + ---------- + .. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines", + J. Inst. Maths Applics, 17, p.37-41, 1976. + .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs + on Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + Examples are given :ref:`in the tutorial `. + + """ + if isinstance(tck, BSpline): + if tck.c.ndim > 1: + mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is " + "not allowed. Use BSpline.integrate() instead.") + raise ValueError(mesg) + + if full_output != 0: + mesg = (f"full_output = {full_output} is not supported. Proceeding as if " + "full_output = 0") + + return tck.integrate(a, b, extrapolate=False) + else: + return _impl.splint(a, b, tck, full_output) + + +def sproot(tck, mest=10): + """ + Find the roots of a cubic B-spline. + + .. legacy:: function + + Specifically, we recommend constructing a `BSpline` object and using the + following pattern: `PPoly.from_spline(spl).roots()`. + + Given the knots (>=8) and coefficients of a cubic B-spline return the + roots of the spline. + + Parameters + ---------- + tck : tuple or a BSpline object + If a tuple, then it should be a sequence of length 3, containing the + vector of knots, the B-spline coefficients, and the degree of the + spline. + The number of knots must be >= 8, and the degree must be 3. + The knots must be a montonically increasing sequence. + mest : int, optional + An estimate of the number of zeros (Default is 10). + + Returns + ------- + zeros : ndarray + An array giving the roots of the spline. + + See Also + -------- + splprep, splrep, splint, spalde, splev + bisplrep, bisplev + BSpline + + Notes + ----- + Manipulating the tck-tuples directly is not recommended. In new code, + prefer using the `BSpline` objects. + + References + ---------- + .. [1] C. de Boor, "On calculating with b-splines", J. Approximation + Theory, 6, p.50-62, 1972. + .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths + Applics, 10, p.134-149, 1972. + .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs + on Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + + For some data, this method may miss a root. This happens when one of + the spline knots (which FITPACK places automatically) happens to + coincide with the true root. A workaround is to convert to `PPoly`, + which uses a different root-finding algorithm. + + For example, + + >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05] + >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03, + ... 4.440892e-16, 1.616930e-03, 3.243000e-03, 4.877670e-03, + ... 6.520430e-03, 8.170770e-03] + >>> from scipy.interpolate import splrep, sproot, PPoly + >>> tck = splrep(x, y, s=0) + >>> sproot(tck) + array([], dtype=float64) + + Converting to a PPoly object does find the roots at ``x=2``: + + >>> ppoly = PPoly.from_spline(tck) + >>> ppoly.roots(extrapolate=False) + array([2.]) + + + Further examples are given :ref:`in the tutorial + `. + + """ + if isinstance(tck, BSpline): + if tck.c.ndim > 1: + mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is " + "not allowed.") + raise ValueError(mesg) + + t, c, k = tck.tck + + # _impl.sproot expects the interpolation axis to be last, so roll it. + # NB: This transpose is a no-op if c is 1D. + sh = tuple(range(c.ndim)) + c = c.transpose(sh[1:] + (0,)) + return _impl.sproot((t, c, k), mest) + else: + return _impl.sproot(tck, mest) + + +def spalde(x, tck): + """ + Evaluate a B-spline and all its derivatives at one point (or set of points) up + to order k (the degree of the spline), being 0 the spline itself. + + .. legacy:: function + + Specifically, we recommend constructing a `BSpline` object and evaluate + its derivative in a loop or a list comprehension. + + Parameters + ---------- + x : array_like + A point or a set of points at which to evaluate the derivatives. + Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`. + tck : tuple + A tuple (t,c,k) containing the vector of knots, + the B-spline coefficients, and the degree of the spline whose + derivatives to compute. + + Returns + ------- + results : {ndarray, list of ndarrays} + An array (or a list of arrays) containing all derivatives + up to order k inclusive for each point `x`, being the first element the + spline itself. + + See Also + -------- + splprep, splrep, splint, sproot, splev, bisplrep, bisplev, + UnivariateSpline, BivariateSpline + + References + ---------- + .. [1] de Boor C : On calculating with b-splines, J. Approximation Theory + 6 (1972) 50-62. + .. [2] Cox M.G. : The numerical evaluation of b-splines, J. Inst. Maths + applics 10 (1972) 134-149. + .. [3] Dierckx P. : Curve and surface fitting with splines, Monographs on + Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + To calculate the derivatives of a B-spline there are several aproaches. + In this example, we will demonstrate that `spalde` is equivalent to + calling `splev` and `splder`. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import BSpline, spalde, splder, splev + + >>> # Store characteristic parameters of a B-spline + >>> tck = ((-2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2), # knots + ... (0, 0, 0, 6, 0, 0, 0), # coefficients + ... 3) # degree (cubic) + >>> # Instance a B-spline object + >>> # `BSpline` objects are preferred, except for spalde() + >>> bspl = BSpline(tck[0], tck[1], tck[2]) + >>> # Generate extra points to get a smooth curve + >>> x = np.linspace(min(tck[0]), max(tck[0]), 100) + + Evaluate the curve and all derivatives + + >>> # The order of derivative must be less or equal to k, the degree of the spline + >>> # Method 1: spalde() + >>> f1_y_bsplin = [spalde(i, tck)[0] for i in x ] # The B-spline itself + >>> f1_y_deriv1 = [spalde(i, tck)[1] for i in x ] # 1st derivative + >>> f1_y_deriv2 = [spalde(i, tck)[2] for i in x ] # 2nd derivative + >>> f1_y_deriv3 = [spalde(i, tck)[3] for i in x ] # 3rd derivative + >>> # You can reach the same result by using `splev`and `splder` + >>> f2_y_deriv3 = splev(x, bspl, der=3) + >>> f3_y_deriv3 = splder(bspl, n=3)(x) + + >>> # Generate a figure with three axes for graphic comparison + >>> fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(16, 5)) + >>> suptitle = fig.suptitle(f'Evaluate a B-spline and all derivatives') + >>> # Plot B-spline and all derivatives using the three methods + >>> orders = range(4) + >>> linetypes = ['-', '--', '-.', ':'] + >>> labels = ['B-Spline', '1st deriv.', '2nd deriv.', '3rd deriv.'] + >>> functions = ['splev()', 'splder()', 'spalde()'] + >>> for order, linetype, label in zip(orders, linetypes, labels): + ... ax1.plot(x, splev(x, bspl, der=order), linetype, label=label) + ... ax2.plot(x, splder(bspl, n=order)(x), linetype, label=label) + ... ax3.plot(x, [spalde(i, tck)[order] for i in x], linetype, label=label) + >>> for ax, function in zip((ax1, ax2, ax3), functions): + ... ax.set_title(function) + ... ax.legend() + >>> plt.tight_layout() + >>> plt.show() + + """ + if isinstance(tck, BSpline): + raise TypeError("spalde does not accept BSpline instances.") + else: + return _impl.spalde(x, tck) + + +def insert(x, tck, m=1, per=0): + """ + Insert knots into a B-spline. + + .. legacy:: function + + Specifically, we recommend constructing a `BSpline` object and using + its ``insert_knot`` method. + + Given the knots and coefficients of a B-spline representation, create a + new B-spline with a knot inserted `m` times at point `x`. + This is a wrapper around the FORTRAN routine insert of FITPACK. + + Parameters + ---------- + x (u) : float + A knot value at which to insert a new knot. If `tck` was returned + from ``splprep``, then the parameter values, u should be given. + tck : a `BSpline` instance or a tuple + If tuple, then it is expected to be a tuple (t,c,k) containing + the vector of knots, the B-spline coefficients, and the degree of + the spline. + m : int, optional + The number of times to insert the given knot (its multiplicity). + Default is 1. + per : int, optional + If non-zero, the input spline is considered periodic. + + Returns + ------- + BSpline instance or a tuple + A new B-spline with knots t, coefficients c, and degree k. + ``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline. + In case of a periodic spline (``per != 0``) there must be + either at least k interior knots t(j) satisfying ``t(k+1)>> from scipy.interpolate import splrep, insert + >>> import numpy as np + >>> x = np.linspace(0, 10, 5) + >>> y = np.sin(x) + >>> tck = splrep(x, y) + >>> tck[0] + array([ 0., 0., 0., 0., 5., 10., 10., 10., 10.]) + + A knot is inserted: + + >>> tck_inserted = insert(3, tck) + >>> tck_inserted[0] + array([ 0., 0., 0., 0., 3., 5., 10., 10., 10., 10.]) + + Some knots are inserted: + + >>> tck_inserted2 = insert(8, tck, m=3) + >>> tck_inserted2[0] + array([ 0., 0., 0., 0., 5., 8., 8., 8., 10., 10., 10., 10.]) + + """ + if isinstance(tck, BSpline): + + t, c, k = tck.tck + + # FITPACK expects the interpolation axis to be last, so roll it over + # NB: if c array is 1D, transposes are no-ops + sh = tuple(range(c.ndim)) + c = c.transpose(sh[1:] + (0,)) + t_, c_, k_ = _impl.insert(x, (t, c, k), m, per) + + # and roll the last axis back + c_ = np.asarray(c_) + c_ = c_.transpose((sh[-1],) + sh[:-1]) + return BSpline(t_, c_, k_) + else: + return _impl.insert(x, tck, m, per) + + +def splder(tck, n=1): + """ + Compute the spline representation of the derivative of a given spline + + .. legacy:: function + + Specifically, we recommend constructing a `BSpline` object and using its + ``derivative`` method. + + Parameters + ---------- + tck : BSpline instance or tuple + BSpline instance or a tuple (t,c,k) containing the vector of knots, + the B-spline coefficients, and the degree of the spline whose + derivative to compute + n : int, optional + Order of derivative to evaluate. Default: 1 + + Returns + ------- + `BSpline` instance or tuple + Spline of order k2=k-n representing the derivative + of the input spline. + A tuple is returned if the input argument `tck` is a tuple, otherwise + a BSpline object is constructed and returned. + + See Also + -------- + splantider, splev, spalde + BSpline + + Notes + ----- + + .. versionadded:: 0.13.0 + + Examples + -------- + This can be used for finding maxima of a curve: + + >>> from scipy.interpolate import splrep, splder, sproot + >>> import numpy as np + >>> x = np.linspace(0, 10, 70) + >>> y = np.sin(x) + >>> spl = splrep(x, y, k=4) + + Now, differentiate the spline and find the zeros of the + derivative. (NB: `sproot` only works for order 3 splines, so we + fit an order 4 spline): + + >>> dspl = splder(spl) + >>> sproot(dspl) / np.pi + array([ 0.50000001, 1.5 , 2.49999998]) + + This agrees well with roots :math:`\\pi/2 + n\\pi` of + :math:`\\cos(x) = \\sin'(x)`. + + A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a + B-spline can be found in the `spalde` examples section. + + """ + if isinstance(tck, BSpline): + return tck.derivative(n) + else: + return _impl.splder(tck, n) + + +def splantider(tck, n=1): + """ + Compute the spline for the antiderivative (integral) of a given spline. + + .. legacy:: function + + Specifically, we recommend constructing a `BSpline` object and using its + ``antiderivative`` method. + + Parameters + ---------- + tck : BSpline instance or a tuple of (t, c, k) + Spline whose antiderivative to compute + n : int, optional + Order of antiderivative to evaluate. Default: 1 + + Returns + ------- + BSpline instance or a tuple of (t2, c2, k2) + Spline of order k2=k+n representing the antiderivative of the input + spline. + A tuple is returned iff the input argument `tck` is a tuple, otherwise + a BSpline object is constructed and returned. + + See Also + -------- + splder, splev, spalde + BSpline + + Notes + ----- + The `splder` function is the inverse operation of this function. + Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo + rounding error. + + .. versionadded:: 0.13.0 + + Examples + -------- + >>> from scipy.interpolate import splrep, splder, splantider, splev + >>> import numpy as np + >>> x = np.linspace(0, np.pi/2, 70) + >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2) + >>> spl = splrep(x, y) + + The derivative is the inverse operation of the antiderivative, + although some floating point error accumulates: + + >>> splev(1.7, spl), splev(1.7, splder(splantider(spl))) + (array(2.1565429877197317), array(2.1565429877201865)) + + Antiderivative can be used to evaluate definite integrals: + + >>> ispl = splantider(spl) + >>> splev(np.pi/2, ispl) - splev(0, ispl) + 2.2572053588768486 + + This is indeed an approximation to the complete elliptic integral + :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`: + + >>> from scipy.special import ellipk + >>> ellipk(0.8) + 2.2572053268208538 + + """ + if isinstance(tck, BSpline): + return tck.antiderivative(n) + else: + return _impl.splantider(tck, n) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py new file mode 100644 index 0000000000000000000000000000000000000000..f5697f3ad716500f6557175e88adead6b3b4caac --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py @@ -0,0 +1,992 @@ +""" Replicate FITPACK's logic for constructing smoothing spline functions and curves. + + Currently provides analogs of splrep and splprep python routines, i.e. + curfit.f and parcur.f routines (the drivers are fpcurf.f and fppara.f, respectively) + + The Fortran sources are from + https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/ + + .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and + parametric splines, Computer Graphics and Image Processing", + 20 (1982) 171-184. + :doi:`10.1016/0146-664X(82)90043-0`. + .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on + Numerical Analysis, Oxford University Press, 1993. + .. [3] P. Dierckx, "An algorithm for smoothing, differentiation and integration + of experimental data using spline functions", + Journal of Computational and Applied Mathematics, vol. I, no 3, p. 165 (1975). + https://doi.org/10.1016/0771-050X(75)90034-0 +""" +import warnings +import operator +import numpy as np + +from ._bsplines import ( + _not_a_knot, make_interp_spline, BSpline, fpcheck, _lsq_solve_qr +) +from . import _dierckx # type: ignore[attr-defined] + + +# cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc +# c part 1: determination of the number of knots and their position c +# c ************************************************************** c +# +# https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L31 + + +# Hardcoded in curfit.f +TOL = 0.001 +MAXIT = 20 + + +def _get_residuals(x, y, t, k, w): + # FITPACK has (w*(spl(x)-y))**2; make_lsq_spline has w*(spl(x)-y)**2 + w2 = w**2 + + # inline the relevant part of + # >>> spl = make_lsq_spline(x, y, w=w2, t=t, k=k) + # NB: + # 1. y is assumed to be 2D here. For 1D case (parametric=False), + # the call must have been preceded by y = y[:, None] (cf _validate_inputs) + # 2. We always sum the squares across axis=1: + # * For 1D (parametric=False), the last dimension has size one, + # so the summation is a no-op. + # * For 2D (parametric=True), the summation is actually how the + # 'residuals' are defined, see Eq. (42) in Dierckx1982 + # (the reference is in the docstring of `class F`) below. + _, _, c = _lsq_solve_qr(x, y, t, k, w) + c = np.ascontiguousarray(c) + spl = BSpline(t, c, k) + return _compute_residuals(w2, spl(x), y) + + +def _compute_residuals(w2, splx, y): + delta = ((splx - y)**2).sum(axis=1) + return w2 * delta + + +def add_knot(x, t, k, residuals): + """Add a new knot. + + (Approximately) replicate FITPACK's logic: + 1. split the `x` array into knot intervals, ``t(j+k) <= x(i) <= t(j+k+1)`` + 2. find the interval with the maximum sum of residuals + 3. insert a new knot into the middle of that interval. + + NB: a new knot is in fact an `x` value at the middle of the interval. + So *the knots are a subset of `x`*. + + This routine is an analog of + https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpcurf.f#L190-L215 + (cf _split function) + + and https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpknot.f + """ + new_knot = _dierckx.fpknot(x, t, k, residuals) + + idx_t = np.searchsorted(t, new_knot) + t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]] + return t_new + + +def _validate_inputs(x, y, w, k, s, xb, xe, parametric): + """Common input validations for generate_knots and make_splrep. + """ + x = np.asarray(x, dtype=float) + y = np.asarray(y, dtype=float) + + if w is None: + w = np.ones_like(x, dtype=float) + else: + w = np.asarray(w, dtype=float) + if w.ndim != 1: + raise ValueError(f"{w.ndim = } not implemented yet.") + if (w < 0).any(): + raise ValueError("Weights must be non-negative") + + if y.ndim == 0 or y.ndim > 2: + raise ValueError(f"{y.ndim = } not supported (must be 1 or 2.)") + + parametric = bool(parametric) + if parametric: + if y.ndim != 2: + raise ValueError(f"{y.ndim = } != 2 not supported with {parametric =}.") + else: + if y.ndim != 1: + raise ValueError(f"{y.ndim = } != 1 not supported with {parametric =}.") + # all _impl functions expect y.ndim = 2 + y = y[:, None] + + if w.shape[0] != x.shape[0]: + raise ValueError(f"Weights is incompatible: {w.shape =} != {x.shape}.") + + if x.shape[0] != y.shape[0]: + raise ValueError(f"Data is incompatible: {x.shape = } and {y.shape = }.") + if x.ndim != 1 or (x[1:] < x[:-1]).any(): + raise ValueError("Expect `x` to be an ordered 1D sequence.") + + k = operator.index(k) + + if s < 0: + raise ValueError(f"`s` must be non-negative. Got {s = }") + + if xb is None: + xb = min(x) + if xe is None: + xe = max(x) + + return x, y, w, k, s, xb, xe + + +def generate_knots(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None): + """Replicate FITPACK's constructing the knot vector. + + Parameters + ---------- + x, y : array_like + The data points defining the curve ``y = f(x)``. + w : array_like, optional + Weights. + xb : float, optional + The boundary of the approximation interval. If None (default), + is set to ``x[0]``. + xe : float, optional + The boundary of the approximation interval. If None (default), + is set to ``x[-1]``. + k : int, optional + The spline degree. Default is cubic, ``k = 3``. + s : float, optional + The smoothing factor. Default is ``s = 0``. + nest : int, optional + Stop when at least this many knots are placed. + + Yields + ------ + t : ndarray + Knot vectors with an increasing number of knots. + The generator is finite: it stops when the smoothing critetion is + satisfied, or when then number of knots exceeds the maximum value: + the user-provided `nest` or `x.size + k + 1` --- which is the knot vector + for the interpolating spline. + + Examples + -------- + Generate some noisy data and fit a sequence of LSQ splines: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import make_lsq_spline, generate_knots + >>> rng = np.random.default_rng(12345) + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(size=50) + + >>> knots = list(generate_knots(x, y, s=1e-10)) + >>> for t in knots[::3]: + ... spl = make_lsq_spline(x, y, t) + ... xs = xs = np.linspace(-3, 3, 201) + ... plt.plot(xs, spl(xs), '-', label=f'n = {len(t)}', lw=3, alpha=0.7) + >>> plt.plot(x, y, 'o', label='data') + >>> plt.plot(xs, np.exp(-xs**2), '--') + >>> plt.legend() + + Note that increasing the number of knots make the result follow the data + more and more closely. + + Also note that a step of the generator may add multiple knots: + + >>> [len(t) for t in knots] + [8, 9, 10, 12, 16, 24, 40, 48, 52, 54] + + Notes + ----- + The routine generates successive knots vectors of increasing length, starting + from ``2*(k+1)`` to ``len(x) + k + 1``, trying to make knots more dense + in the regions where the deviation of the LSQ spline from data is large. + + When the maximum number of knots, ``len(x) + k + 1`` is reached + (this happens when ``s`` is small and ``nest`` is large), the generator + stops, and the last output is the knots for the interpolation with the + not-a-knot boundary condition. + + Knots are located at data sites, unless ``k`` is even and the number of knots + is ``len(x) + k + 1``. In that case, the last output of the generator + has internal knots at Greville sites, ``(x[1:] + x[:-1]) / 2``. + + .. versionadded:: 1.15.0 + + """ + if s == 0: + if nest is not None or w is not None: + raise ValueError("s == 0 is interpolation only") + t = _not_a_knot(x, k) + yield t + return + + x, y, w, k, s, xb, xe = _validate_inputs( + x, y, w, k, s, xb, xe, parametric=np.ndim(y) == 2 + ) + + yield from _generate_knots_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, nest=nest) + + +def _generate_knots_impl(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None): + + acc = s * TOL + m = x.size # the number of data points + + if nest is None: + # the max number of knots. This is set in _fitpack_impl.py line 274 + # and fitpack.pyf line 198 + nest = max(m + k + 1, 2*k + 3) + else: + if nest < 2*(k + 1): + raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.") + + nmin = 2*(k + 1) # the number of knots for an LSQ polynomial approximation + nmax = m + k + 1 # the number of knots for the spline interpolation + + # start from no internal knots + t = np.asarray([xb]*(k+1) + [xe]*(k+1), dtype=float) + n = t.shape[0] + fp = 0.0 + fpold = 0.0 + + # c main loop for the different sets of knots. m is a safe upper bound + # c for the number of trials. + for _ in range(m): + yield t + + # construct the LSQ spline with this set of knots + fpold = fp + residuals = _get_residuals(x, y, t, k, w=w) + fp = residuals.sum() + fpms = fp - s + + # c test whether the approximation sinf(x) is an acceptable solution. + # c if f(p=inf) < s accept the choice of knots. + if (abs(fpms) < acc) or (fpms < 0): + return + + # ### c increase the number of knots. ### + + # c determine the number of knots nplus we are going to add. + if n == nmin: + # the first iteration + nplus = 1 + else: + delta = fpold - fp + npl1 = int(nplus * fpms / delta) if delta > acc else nplus*2 + nplus = min(nplus*2, max(npl1, nplus//2, 1)) + + # actually add knots + for j in range(nplus): + t = add_knot(x, t, k, residuals) + + # check if we have enough knots already + + n = t.shape[0] + # c if n = nmax, sinf(x) is an interpolating spline. + # c if n=nmax we locate the knots as for interpolation. + if n >= nmax: + t = _not_a_knot(x, k) + yield t + return + + # c if n=nest we cannot increase the number of knots because of + # c the storage capacity limitation. + if n >= nest: + yield t + return + + # recompute if needed + if j < nplus - 1: + residuals = _get_residuals(x, y, t, k, w=w) + + # this should never be reached + return + + +# cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc +# c part 2: determination of the smoothing spline sp(x). c +# c *************************************************** c +# c we have determined the number of knots and their position. c +# c we now compute the b-spline coefficients of the smoothing spline c +# c sp(x). the observation matrix a is extended by the rows of matrix c +# c b expressing that the kth derivative discontinuities of sp(x) at c +# c the interior knots t(k+2),...t(n-k-1) must be zero. the corres- c +# c ponding weights of these additional rows are set to 1/p. c +# c iteratively we then have to determine the value of p such that c +# c f(p)=sum((w(i)*(y(i)-sp(x(i))))**2) be = s. we already know that c +# c the least-squares kth degree polynomial corresponds to p=0, and c +# c that the least-squares spline corresponds to p=infinity. the c +# c iteration process which is proposed here, makes use of rational c +# c interpolation. since f(p) is a convex and strictly decreasing c +# c function of p, it can be approximated by a rational function c +# c r(p) = (u*p+v)/(p+w). three values of p(p1,p2,p3) with correspond- c +# c ing values of f(p) (f1=f(p1)-s,f2=f(p2)-s,f3=f(p3)-s) are used c +# c to calculate the new value of p such that r(p)=s. convergence is c +# c guaranteed by taking f1>0 and f3<0. c +# cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + + +def prodd(t, i, j, k): + res = 1.0 + for s in range(k+2): + if i + s != j: + res *= (t[j] - t[i+s]) + return res + + +def disc(t, k): + """Discontinuity matrix: jumps of k-th derivatives of b-splines at internal knots. + + See Eqs. (9)-(10) of Ref. [1], or, equivalently, Eq. (3.43) of Ref. [2]. + + This routine assumes internal knots are all simple (have multiplicity =1). + + Parameters + ---------- + t : ndarray, 1D, shape(n,) + Knots. + k : int + The spline degree + + Returns + ------- + disc : ndarray, shape(n-2*k-1, k+2) + The jumps of the k-th derivatives of b-splines at internal knots, + ``t[k+1], ...., t[n-k-1]``. + offset : ndarray, shape(2-2*k-1,) + Offsets + nc : int + + Notes + ----- + + The normalization here follows FITPACK: + (https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpdisc.f#L36) + + The k-th derivative jumps are multiplied by a factor:: + + (delta / nrint)**k / k! + + where ``delta`` is the length of the interval spanned by internal knots, and + ``nrint`` is one less the number of internal knots (i.e., the number of + subintervals between them). + + References + ---------- + .. [1] Paul Dierckx, Algorithms for smoothing data with periodic and parametric + splines, Computer Graphics and Image Processing, vol. 20, p. 171 (1982). + :doi:`10.1016/0146-664X(82)90043-0` + + .. [2] Tom Lyche and Knut Morken, Spline methods, + http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/ + + """ + n = t.shape[0] + + # the length of the base interval spanned by internal knots & the number + # of subintervas between these internal knots + delta = t[n - k - 1] - t[k] + nrint = n - 2*k - 1 + + matr = np.empty((nrint - 1, k + 2), dtype=float) + for jj in range(nrint - 1): + j = jj + k + 1 + for ii in range(k + 2): + i = jj + ii + matr[jj, ii] = (t[i + k + 1] - t[i]) / prodd(t, i, j, k) + # NB: equivalent to + # row = [(t[i + k + 1] - t[i]) / prodd(t, i, j, k) for i in range(j-k-1, j+1)] + # assert (matr[j-k-1, :] == row).all() + + # follow FITPACK + matr *= (delta/ nrint)**k + + # make it packed + offset = np.array([i for i in range(nrint-1)], dtype=np.int64) + nc = n - k - 1 + return matr, offset, nc + + +class F: + """ The r.h.s. of ``f(p) = s``. + + Given scalar `p`, we solve the system of equations in the LSQ sense: + + | A | @ | c | = | y | + | B / p | | 0 | | 0 | + + where `A` is the matrix of b-splines and `b` is the discontinuity matrix + (the jumps of the k-th derivatives of b-spline basis elements at knots). + + Since we do that repeatedly while minimizing over `p`, we QR-factorize + `A` only once and update the QR factorization only of the `B` rows of the + augmented matrix |A, B/p|. + + The system of equations is Eq. (15) Ref. [1]_, the strategy and implementation + follows that of FITPACK, see specific links below. + + References + ---------- + [1] P. Dierckx, Algorithms for Smoothing Data with Periodic and Parametric Splines, + COMPUTER GRAPHICS AND IMAGE PROCESSING vol. 20, pp 171-184 (1982.) + https://doi.org/10.1016/0146-664X(82)90043-0 + + """ + def __init__(self, x, y, t, k, s, w=None, *, R=None, Y=None): + self.x = x + self.y = y + self.t = t + self.k = k + w = np.ones_like(x, dtype=float) if w is None else w + if w.ndim != 1: + raise ValueError(f"{w.ndim = } != 1.") + self.w = w + self.s = s + + if y.ndim != 2: + raise ValueError(f"F: expected y.ndim == 2, got {y.ndim = } instead.") + + # ### precompute what we can ### + + # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L250 + # c evaluate the discontinuity jump of the kth derivative of the + # c b-splines at the knots t(l),l=k+2,...n-k-1 and store in b. + b, b_offset, b_nc = disc(t, k) + + # the QR factorization of the data matrix, if not provided + # NB: otherwise, must be consistent with x,y & s, but this is not checked + if R is None and Y is None: + R, Y, _ = _lsq_solve_qr(x, y, t, k, w) + + # prepare to combine R and the discontinuity matrix (AB); also r.h.s. (YY) + # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L269 + # c the rows of matrix b with weight 1/p are rotated into the + # c triangularised observation matrix a which is stored in g. + nc = t.shape[0] - k - 1 + nz = k + 1 + if R.shape[1] != nz: + raise ValueError(f"Internal error: {R.shape[1] =} != {k+1 =}.") + + # r.h.s. of the augmented system + z = np.zeros((b.shape[0], Y.shape[1]), dtype=float) + self.YY = np.r_[Y[:nc], z] + + # l.h.s. of the augmented system + AA = np.zeros((nc + b.shape[0], self.k+2), dtype=float) + AA[:nc, :nz] = R[:nc, :] + # AA[nc:, :] = b.a / p # done in __call__(self, p) + self.AA = AA + self.offset = np.r_[np.arange(nc, dtype=np.int64), b_offset] + + self.nc = nc + self.b = b + + def __call__(self, p): + # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L279 + # c the row of matrix b is rotated into triangle by givens transformation + + # copy the precomputed matrices over for in-place work + # R = PackedMatrix(self.AB.a.copy(), self.AB.offset.copy(), nc) + AB = self.AA.copy() + offset = self.offset.copy() + nc = self.nc + + AB[nc:, :] = self.b / p + QY = self.YY.copy() + + # heavy lifting happens here, in-place + _dierckx.qr_reduce(AB, offset, nc, QY, startrow=nc) + + # solve for the coefficients + c = _dierckx.fpback(AB, nc, QY) + + spl = BSpline(self.t, c, self.k) + residuals = _compute_residuals(self.w**2, spl(self.x), self.y) + fp = residuals.sum() + + self.spl = spl # store it + + return fp - self.s + + +def fprati(p1, f1, p2, f2, p3, f3): + """The root of r(p) = (u*p + v) / (p + w) given three points and values, + (p1, f2), (p2, f2) and (p3, f3). + + The FITPACK analog adjusts the bounds, and we do not + https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fprati.f + + NB: FITPACK uses p < 0 to encode p=infinity. We just use the infinity itself. + Since the bracket is ``p1 <= p2 <= p3``, ``p3`` can be infinite (in fact, + this is what the minimizer starts with, ``p3=inf``). + """ + h1 = f1 * (f2 - f3) + h2 = f2 * (f3 - f1) + h3 = f3 * (f1 - f2) + if p3 == np.inf: + return -(p2*h1 + p1*h2) / h3 + return -(p1*p2*h3 + p2*p3*h1 + p1*p3*h2) / (p1*h1 + p2*h2 + p3*h3) + + +class Bunch: + def __init__(self, **kwargs): + self.__dict__.update(**kwargs) + + +_iermesg = { +2: """error. a theoretically impossible result was found during +the iteration process for finding a smoothing spline with +fp = s. probably causes : s too small. +there is an approximation returned but the corresponding +weighted sum of squared residuals does not satisfy the +condition abs(fp-s)/s < tol. +""", +3: """error. the maximal number of iterations maxit (set to 20 +by the program) allowed for finding a smoothing spline +with fp=s has been reached. probably causes : s too small +there is an approximation returned but the corresponding +weighted sum of squared residuals does not satisfy the +condition abs(fp-s)/s < tol. +""" +} + + +def root_rati(f, p0, bracket, acc): + """Solve `f(p) = 0` using a rational function approximation. + + In a nutshell, since the function f(p) is known to be monotonically decreasing, we + - maintain the bracket (p1, f1), (p2, f2) and (p3, f3) + - at each iteration step, approximate f(p) by a rational function + r(p) = (u*p + v) / (p + w) + and make a step to p_new to the root of f(p): r(p_new) = 0. + The coefficients u, v and w are found from the bracket values p1..3 and f1...3 + + The algorithm and implementation follows + https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L229 + and + https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L290 + + Note that the latter is for parametric splines and the former is for 1D spline + functions. The minimization is indentical though [modulo a summation over the + dimensions in the computation of f(p)], so we reuse the minimizer for both + d=1 and d>1. + """ + # Magic values from + # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L27 + con1 = 0.1 + con9 = 0.9 + con4 = 0.04 + + # bracketing flags (follow FITPACK) + # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L365 + ich1, ich3 = 0, 0 + + (p1, f1), (p3, f3) = bracket + p = p0 + + for it in range(MAXIT): + p2, f2 = p, f(p) + + # c test whether the approximation sp(x) is an acceptable solution. + if abs(f2) < acc: + ier, converged = 0, True + break + + # c carry out one more step of the iteration process. + if ich3 == 0: + if f2 - f3 <= acc: + # c our initial choice of p is too large. + p3 = p2 + f3 = f2 + p = p*con4 + if p <= p1: + p = p1*con9 + p2*con1 + continue + else: + if f2 < 0: + ich3 = 1 + + if ich1 == 0: + if f1 - f2 <= acc: + # c our initial choice of p is too small + p1 = p2 + f1 = f2 + p = p/con4 + if p3 != np.inf and p <= p3: + p = p2*con1 + p3*con9 + continue + else: + if f2 > 0: + ich1 = 1 + + # c test whether the iteration process proceeds as theoretically expected. + # [f(p) should be monotonically decreasing] + if f1 <= f2 or f2 <= f3: + ier, converged = 2, False + break + + # actually make the iteration step + p = fprati(p1, f1, p2, f2, p3, f3) + + # c adjust the value of p1,f1,p3 and f3 such that f1 > 0 and f3 < 0. + if f2 < 0: + p3, f3 = p2, f2 + else: + p1, f1 = p2, f2 + + else: + # not converged in MAXIT iterations + ier, converged = 3, False + + if ier != 0: + warnings.warn(RuntimeWarning(_iermesg[ier]), stacklevel=2) + + return Bunch(converged=converged, root=p, iterations=it, ier=ier) + + +def _make_splrep_impl(x, y, *, w=None, xb=None, xe=None, k=3, s=0, t=None, nest=None): + """Shared infra for make_splrep and make_splprep. + """ + acc = s * TOL + m = x.size # the number of data points + + if nest is None: + # the max number of knots. This is set in _fitpack_impl.py line 274 + # and fitpack.pyf line 198 + nest = max(m + k + 1, 2*k + 3) + else: + if nest < 2*(k + 1): + raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.") + if t is not None: + raise ValueError("Either supply `t` or `nest`.") + + if t is None: + gen = _generate_knots_impl(x, y, w=w, k=k, s=s, xb=xb, xe=xe, nest=nest) + t = list(gen)[-1] + else: + fpcheck(x, t, k) + + if t.shape[0] == 2 * (k + 1): + # nothing to optimize + _, _, c = _lsq_solve_qr(x, y, t, k, w) + return BSpline(t, c, k) + + ### solve ### + + # c initial value for p. + # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L253 + R, Y, _ = _lsq_solve_qr(x, y, t, k, w) + nc = t.shape[0] -k -1 + p = nc / R[:, 0].sum() + + # ### bespoke solver #### + # initial conditions + # f(p=inf) : LSQ spline with knots t (XXX: reuse R, c) + residuals = _get_residuals(x, y, t, k, w=w) + fp = residuals.sum() + fpinf = fp - s + + # f(p=0): LSQ spline without internal knots + residuals = _get_residuals(x, y, np.array([xb]*(k+1) + [xe]*(k+1)), k, w) + fp0 = residuals.sum() + fp0 = fp0 - s + + # solve + bracket = (0, fp0), (np.inf, fpinf) + f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y) + _ = root_rati(f, p, bracket, acc) + + # solve ALTERNATIVE: is roughly equivalent, gives slightly different results + # starting from scratch, that would have probably been tolerable; + # backwards compatibility dictates that we replicate the FITPACK minimizer though. + # f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y) + # from scipy.optimize import root_scalar + # res_ = root_scalar(f, x0=p, rtol=acc) + # assert res_.converged + + # f.spl is the spline corresponding to the found `p` value + return f.spl + + +def make_splrep(x, y, *, w=None, xb=None, xe=None, k=3, s=0, t=None, nest=None): + r"""Find the B-spline representation of a 1D function. + + Given the set of data points ``(x[i], y[i])``, determine a smooth spline + approximation of degree ``k`` on the interval ``xb <= x <= xe``. + + Parameters + ---------- + x, y : array_like, shape (m,) + The data points defining a curve ``y = f(x)``. + w : array_like, shape (m,), optional + Strictly positive 1D array of weights, of the same length as `x` and `y`. + The weights are used in computing the weighted least-squares spline + fit. If the errors in the y values have standard-deviation given by the + vector ``d``, then `w` should be ``1/d``. + Default is ``np.ones(m)``. + xb, xe : float, optional + The interval to fit. If None, these default to ``x[0]`` and ``x[-1]``, + respectively. + k : int, optional + The degree of the spline fit. It is recommended to use cubic splines, + ``k=3``, which is the default. Even values of `k` should be avoided, + especially with small `s` values. + s : float, optional + The smoothing condition. The amount of smoothness is determined by + satisfying the conditions:: + + sum((w * (g(x) - y))**2 ) <= s + + where ``g(x)`` is the smoothed fit to ``(x, y)``. The user can use `s` + to control the tradeoff between closeness to data and smoothness of fit. + Larger `s` means more smoothing while smaller values of `s` indicate less + smoothing. + Recommended values of `s` depend on the weights, `w`. If the weights + represent the inverse of the standard deviation of `y`, then a good `s` + value should be found in the range ``(m-sqrt(2*m), m+sqrt(2*m))`` where + ``m`` is the number of datapoints in `x`, `y`, and `w`. + Default is ``s = 0.0``, i.e. interpolation. + t : array_like, optional + The spline knots. If None (default), the knots will be constructed + automatically. + There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots. + nest : int, optional + The target length of the knot vector. Should be between ``2*(k + 1)`` + (the minimum number of knots for a degree-``k`` spline), and + ``m + k + 1`` (the number of knots of the interpolating spline). + The actual number of knots returned by this routine may be slightly + larger than `nest`. + Default is None (no limit, add up to ``m + k + 1`` knots). + + Returns + ------- + spl : a `BSpline` instance + For `s=0`, ``spl(x) == y``. + For non-zero values of `s` the `spl` represents the smoothed approximation + to `(x, y)`, generally with fewer knots. + + See Also + -------- + generate_knots : is used under the hood for generating the knots + make_splprep : the analog of this routine for parametric curves + make_interp_spline : construct an interpolating spline (``s = 0``) + make_lsq_spline : construct the least-squares spline given the knot vector + splrep : a FITPACK analog of this routine + + References + ---------- + .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and + parametric splines, Computer Graphics and Image Processing", + 20 (1982) 171-184. + .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on + Numerical Analysis, Oxford University Press, 1993. + + Notes + ----- + This routine constructs the smoothing spline function, :math:`g(x)`, to + minimize the sum of jumps, :math:`D_j`, of the ``k``-th derivative at the + internal knots (:math:`x_b < t_i < x_e`), where + + .. math:: + + D_i = g^{(k)}(t_i + 0) - g^{(k)}(t_i - 0) + + Specifically, the routine constructs the spline function :math:`g(x)` which + minimizes + + .. math:: + + \sum_i | D_i |^2 \to \mathrm{min} + + provided that + + .. math:: + + \sum_{j=1}^m (w_j \times (g(x_j) - y_j))^2 \leqslant s , + + where :math:`s > 0` is the input parameter. + + In other words, we balance maximizing the smoothness (measured as the jumps + of the derivative, the first criterion), and the deviation of :math:`g(x_j)` + from the data :math:`y_j` (the second criterion). + + Note that the summation in the second criterion is over all data points, + and in the first criterion it is over the internal spline knots (i.e. + those with ``xb < t[i] < xe``). The spline knots are in general a subset + of data, see `generate_knots` for details. + + Also note the difference of this routine to `make_lsq_spline`: the latter + routine does not consider smoothness and simply solves a least-squares + problem + + .. math:: + + \sum w_j \times (g(x_j) - y_j)^2 \to \mathrm{min} + + for a spline function :math:`g(x)` with a _fixed_ knot vector ``t``. + + .. versionadded:: 1.15.0 + """ + if s == 0: + if t is not None or w is not None or nest is not None: + raise ValueError("s==0 is for interpolation only") + return make_interp_spline(x, y, k=k) + + x, y, w, k, s, xb, xe = _validate_inputs(x, y, w, k, s, xb, xe, parametric=False) + + spl = _make_splrep_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, t=t, nest=nest) + + # postprocess: squeeze out the last dimension: was added to simplify the internals. + spl.c = spl.c[:, 0] + return spl + + +def make_splprep(x, *, w=None, u=None, ub=None, ue=None, k=3, s=0, t=None, nest=None): + r""" + Find a smoothed B-spline representation of a parametric N-D curve. + + Given a list of N 1D arrays, `x`, which represent a curve in + N-dimensional space parametrized by `u`, find a smooth approximating + spline curve ``g(u)``. + + Parameters + ---------- + x : array_like, shape (m, ndim) + Sampled data points representing the curve in ``ndim`` dimensions. + The typical use is a list of 1D arrays, each of length ``m``. + w : array_like, shape(m,), optional + Strictly positive 1D array of weights. + The weights are used in computing the weighted least-squares spline + fit. If the errors in the `x` values have standard deviation given by + the vector d, then `w` should be 1/d. Default is ``np.ones(m)``. + u : array_like, optional + An array of parameter values for the curve in the parametric form. + If not given, these values are calculated automatically, according to:: + + v[0] = 0 + v[i] = v[i-1] + distance(x[i], x[i-1]) + u[i] = v[i] / v[-1] + + ub, ue : float, optional + The end-points of the parameters interval. Default to ``u[0]`` and ``u[-1]``. + k : int, optional + Degree of the spline. Cubic splines, ``k=3``, are recommended. + Even values of `k` should be avoided especially with a small ``s`` value. + Default is ``k=3`` + s : float, optional + A smoothing condition. The amount of smoothness is determined by + satisfying the conditions:: + + sum((w * (g(u) - x))**2) <= s, + + where ``g(u)`` is the smoothed approximation to ``x``. The user can + use `s` to control the trade-off between closeness and smoothness + of fit. Larger ``s`` means more smoothing while smaller values of ``s`` + indicate less smoothing. + Recommended values of ``s`` depend on the weights, ``w``. If the weights + represent the inverse of the standard deviation of ``x``, then a good + ``s`` value should be found in the range ``(m - sqrt(2*m), m + sqrt(2*m))``, + where ``m`` is the number of data points in ``x`` and ``w``. + t : array_like, optional + The spline knots. If None (default), the knots will be constructed + automatically. + There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots. + nest : int, optional + The target length of the knot vector. Should be between ``2*(k + 1)`` + (the minimum number of knots for a degree-``k`` spline), and + ``m + k + 1`` (the number of knots of the interpolating spline). + The actual number of knots returned by this routine may be slightly + larger than `nest`. + Default is None (no limit, add up to ``m + k + 1`` knots). + + Returns + ------- + spl : a `BSpline` instance + For `s=0`, ``spl(u) == x``. + For non-zero values of ``s``, `spl` represents the smoothed approximation + to ``x``, generally with fewer knots. + u : ndarray + The values of the parameters + + See Also + -------- + generate_knots : is used under the hood for generating the knots + make_splrep : the analog of this routine 1D functions + make_interp_spline : construct an interpolating spline (``s = 0``) + make_lsq_spline : construct the least-squares spline given the knot vector + splprep : a FITPACK analog of this routine + + Notes + ----- + Given a set of :math:`m` data points in :math:`D` dimensions, :math:`\vec{x}_j`, + with :math:`j=1, ..., m` and :math:`\vec{x}_j = (x_{j; 1}, ..., x_{j; D})`, + this routine constructs the parametric spline curve :math:`g_a(u)` with + :math:`a=1, ..., D`, to minimize the sum of jumps, :math:`D_{i; a}`, of the + ``k``-th derivative at the internal knots (:math:`u_b < t_i < u_e`), where + + .. math:: + + D_{i; a} = g_a^{(k)}(t_i + 0) - g_a^{(k)}(t_i - 0) + + Specifically, the routine constructs the spline function :math:`g(u)` which + minimizes + + .. math:: + + \sum_i \sum_{a=1}^D | D_{i; a} |^2 \to \mathrm{min} + + provided that + + .. math:: + + \sum_{j=1}^m \sum_{a=1}^D (w_j \times (g_a(u_j) - x_{j; a}))^2 \leqslant s + + where :math:`u_j` is the value of the parameter corresponding to the data point + :math:`(x_{j; 1}, ..., x_{j; D})`, and :math:`s > 0` is the input parameter. + + In other words, we balance maximizing the smoothness (measured as the jumps + of the derivative, the first criterion), and the deviation of :math:`g(u_j)` + from the data :math:`x_j` (the second criterion). + + Note that the summation in the second criterion is over all data points, + and in the first criterion it is over the internal spline knots (i.e. + those with ``ub < t[i] < ue``). The spline knots are in general a subset + of data, see `generate_knots` for details. + + .. versionadded:: 1.15.0 + + References + ---------- + .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and + parametric splines, Computer Graphics and Image Processing", + 20 (1982) 171-184. + .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on + Numerical Analysis, Oxford University Press, 1993. + """ + x = np.stack(x, axis=1) + + # construct the default parametrization of the curve + if u is None: + dp = (x[1:, :] - x[:-1, :])**2 + u = np.sqrt((dp).sum(axis=1)).cumsum() + u = np.r_[0, u / u[-1]] + + if s == 0: + if t is not None or w is not None or nest is not None: + raise ValueError("s==0 is for interpolation only") + return make_interp_spline(u, x.T, k=k, axis=1), u + + u, x, w, k, s, ub, ue = _validate_inputs(u, x, w, k, s, ub, ue, parametric=True) + + spl = _make_splrep_impl(u, x, w=w, xb=ub, xe=ue, k=k, s=s, t=t, nest=nest) + + # posprocess: `axis=1` so that spl(u).shape == np.shape(x) + # when `x` is a list of 1D arrays (cf original splPrep) + cc = spl.c.T + spl1 = BSpline(spl.t, cc, spl.k, axis=1) + + return spl1, u + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..7558bd7db25cbd60206f908aabbcb6dc9c567fa4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py @@ -0,0 +1,2248 @@ +__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly'] + +from math import prod + +import numpy as np +from numpy import array, asarray, intp, poly1d, searchsorted + +import scipy.special as spec +from scipy._lib._util import copy_if_needed +from scipy.special import comb + +from . import _fitpack_py +from ._polyint import _Interpolator1D +from . import _ppoly +from ._interpnd import _ndim_coords_from_arrays +from ._bsplines import make_interp_spline, BSpline + + +def lagrange(x, w): + r""" + Return a Lagrange interpolating polynomial. + + Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating + polynomial through the points ``(x, w)``. + + Warning: This implementation is numerically unstable. Do not expect to + be able to use more than about 20 points even if they are chosen optimally. + + Parameters + ---------- + x : array_like + `x` represents the x-coordinates of a set of datapoints. + w : array_like + `w` represents the y-coordinates of a set of datapoints, i.e., f(`x`). + + Returns + ------- + lagrange : `numpy.poly1d` instance + The Lagrange interpolating polynomial. + + Examples + -------- + Interpolate :math:`f(x) = x^3` by 3 points. + + >>> import numpy as np + >>> from scipy.interpolate import lagrange + >>> x = np.array([0, 1, 2]) + >>> y = x**3 + >>> poly = lagrange(x, y) + + Since there are only 3 points, Lagrange polynomial has degree 2. Explicitly, + it is given by + + .. math:: + + \begin{aligned} + L(x) &= 1\times \frac{x (x - 2)}{-1} + 8\times \frac{x (x-1)}{2} \\ + &= x (-2 + 3x) + \end{aligned} + + >>> from numpy.polynomial.polynomial import Polynomial + >>> Polynomial(poly.coef[::-1]).coef + array([ 0., -2., 3.]) + + >>> import matplotlib.pyplot as plt + >>> x_new = np.arange(0, 2.1, 0.1) + >>> plt.scatter(x, y, label='data') + >>> plt.plot(x_new, Polynomial(poly.coef[::-1])(x_new), label='Polynomial') + >>> plt.plot(x_new, 3*x_new**2 - 2*x_new + 0*x_new, + ... label=r"$3 x^2 - 2 x$", linestyle='-.') + >>> plt.legend() + >>> plt.show() + + """ + + M = len(x) + p = poly1d(0.0) + for j in range(M): + pt = poly1d(w[j]) + for k in range(M): + if k == j: + continue + fac = x[j]-x[k] + pt *= poly1d([1.0, -x[k]])/fac + p += pt + return p + + +# !! Need to find argument for keeping initialize. If it isn't +# !! found, get rid of it! + + +err_mesg = """\ +`interp2d` has been removed in SciPy 1.14.0. + +For legacy code, nearly bug-for-bug compatible replacements are +`RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for +scattered 2D data. + +In new code, for regular grids use `RegularGridInterpolator` instead. +For scattered data, prefer `LinearNDInterpolator` or +`CloughTocher2DInterpolator`. + +For more details see +https://scipy.github.io/devdocs/tutorial/interpolate/interp_transition_guide.html +""" + +class interp2d: + """ + interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, + fill_value=None) + + .. versionremoved:: 1.14.0 + + `interp2d` has been removed in SciPy 1.14.0. + + For legacy code, nearly bug-for-bug compatible replacements are + `RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for + scattered 2D data. + + In new code, for regular grids use `RegularGridInterpolator` instead. + For scattered data, prefer `LinearNDInterpolator` or + `CloughTocher2DInterpolator`. + + For more details see :ref:`interp-transition-guide`. + """ + def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, + fill_value=None): + raise NotImplementedError(err_mesg) + + +def _check_broadcast_up_to(arr_from, shape_to, name): + """Helper to check that arr_from broadcasts up to shape_to""" + shape_from = arr_from.shape + if len(shape_to) >= len(shape_from): + for t, f in zip(shape_to[::-1], shape_from[::-1]): + if f != 1 and f != t: + break + else: # all checks pass, do the upcasting that we need later + if arr_from.size != 1 and arr_from.shape != shape_to: + arr_from = np.ones(shape_to, arr_from.dtype) * arr_from + return arr_from.ravel() + # at least one check failed + raise ValueError(f'{name} argument must be able to broadcast up ' + f'to shape {shape_to} but had shape {shape_from}') + + +def _do_extrapolate(fill_value): + """Helper to check if fill_value == "extrapolate" without warnings""" + return (isinstance(fill_value, str) and + fill_value == 'extrapolate') + + +class interp1d(_Interpolator1D): + """ + Interpolate a 1-D function. + + .. legacy:: class + + For a guide to the intended replacements for `interp1d` see + :ref:`tutorial-interpolate_1Dsection`. + + `x` and `y` are arrays of values used to approximate some function f: + ``y = f(x)``. This class returns a function whose call method uses + interpolation to find the value of new points. + + Parameters + ---------- + x : (npoints, ) array_like + A 1-D array of real values. + y : (..., npoints, ...) array_like + A N-D array of real values. The length of `y` along the interpolation + axis must be equal to the length of `x`. Use the ``axis`` parameter + to select correct axis. Unlike other interpolators, the default + interpolation axis is the last axis of `y`. + kind : str or int, optional + Specifies the kind of interpolation as a string or as an integer + specifying the order of the spline interpolator to use. + The string has to be one of 'linear', 'nearest', 'nearest-up', 'zero', + 'slinear', 'quadratic', 'cubic', 'previous', or 'next'. 'zero', + 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of + zeroth, first, second or third order; 'previous' and 'next' simply + return the previous or next value of the point; 'nearest-up' and + 'nearest' differ when interpolating half-integers (e.g. 0.5, 1.5) + in that 'nearest-up' rounds up and 'nearest' rounds down. Default + is 'linear'. + axis : int, optional + Axis in the ``y`` array corresponding to the x-coordinate values. Unlike + other interpolators, defaults to ``axis=-1``. + copy : bool, optional + If ``True``, the class makes internal copies of x and y. If ``False``, + references to ``x`` and ``y`` are used if possible. The default is to copy. + bounds_error : bool, optional + If True, a ValueError is raised any time interpolation is attempted on + a value outside of the range of x (where extrapolation is + necessary). If False, out of bounds values are assigned `fill_value`. + By default, an error is raised unless ``fill_value="extrapolate"``. + fill_value : array-like or (array-like, array_like) or "extrapolate", optional + - if a ndarray (or float), this value will be used to fill in for + requested points outside of the data range. If not provided, then + the default is NaN. The array-like must broadcast properly to the + dimensions of the non-interpolation axes. + - If a two-element tuple, then the first element is used as a + fill value for ``x_new < x[0]`` and the second element is used for + ``x_new > x[-1]``. Anything that is not a 2-element tuple (e.g., + list or ndarray, regardless of shape) is taken to be a single + array-like argument meant to be used for both bounds as + ``below, above = fill_value, fill_value``. Using a two-element tuple + or ndarray requires ``bounds_error=False``. + + .. versionadded:: 0.17.0 + - If "extrapolate", then points outside the data range will be + extrapolated. + + .. versionadded:: 0.17.0 + assume_sorted : bool, optional + If False, values of `x` can be in any order and they are sorted first. + If True, `x` has to be an array of monotonically increasing values. + + Attributes + ---------- + fill_value + + Methods + ------- + __call__ + + See Also + -------- + splrep, splev + Spline interpolation/smoothing based on FITPACK. + UnivariateSpline : An object-oriented wrapper of the FITPACK routines. + interp2d : 2-D interpolation + + Notes + ----- + Calling `interp1d` with NaNs present in input values results in + undefined behaviour. + + Input values `x` and `y` must be convertible to `float` values like + `int` or `float`. + + If the values in `x` are not unique, the resulting behavior is + undefined and specific to the choice of `kind`, i.e., changing + `kind` will change the behavior for duplicates. + + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import interpolate + >>> x = np.arange(0, 10) + >>> y = np.exp(-x/3.0) + >>> f = interpolate.interp1d(x, y) + + >>> xnew = np.arange(0, 9, 0.1) + >>> ynew = f(xnew) # use interpolation function returned by `interp1d` + >>> plt.plot(x, y, 'o', xnew, ynew, '-') + >>> plt.show() + """ + + def __init__(self, x, y, kind='linear', axis=-1, + copy=True, bounds_error=None, fill_value=np.nan, + assume_sorted=False): + """ Initialize a 1-D linear interpolation class.""" + _Interpolator1D.__init__(self, x, y, axis=axis) + + self.bounds_error = bounds_error # used by fill_value setter + + # `copy` keyword semantics changed in NumPy 2.0, once that is + # the minimum version this can use `copy=None`. + self.copy = copy + if not copy: + self.copy = copy_if_needed + + if kind in ['zero', 'slinear', 'quadratic', 'cubic']: + order = {'zero': 0, 'slinear': 1, + 'quadratic': 2, 'cubic': 3}[kind] + kind = 'spline' + elif isinstance(kind, int): + order = kind + kind = 'spline' + elif kind not in ('linear', 'nearest', 'nearest-up', 'previous', + 'next'): + raise NotImplementedError(f"{kind} is unsupported: Use fitpack " + "routines for other types.") + x = array(x, copy=self.copy) + y = array(y, copy=self.copy) + + if not assume_sorted: + ind = np.argsort(x, kind="mergesort") + x = x[ind] + y = np.take(y, ind, axis=axis) + + if x.ndim != 1: + raise ValueError("the x array must have exactly one dimension.") + if y.ndim == 0: + raise ValueError("the y array must have at least one dimension.") + + # Force-cast y to a floating-point type, if it's not yet one + if not issubclass(y.dtype.type, np.inexact): + y = y.astype(np.float64) + + # Backward compatibility + self.axis = axis % y.ndim + + # Interpolation goes internally along the first axis + self.y = y + self._y = self._reshape_yi(self.y) + self.x = x + del y, x # clean up namespace to prevent misuse; use attributes + self._kind = kind + + # Adjust to interpolation kind; store reference to *unbound* + # interpolation methods, in order to avoid circular references to self + # stored in the bound instance methods, and therefore delayed garbage + # collection. See: https://docs.python.org/reference/datamodel.html + if kind in ('linear', 'nearest', 'nearest-up', 'previous', 'next'): + # Make a "view" of the y array that is rotated to the interpolation + # axis. + minval = 1 + if kind == 'nearest': + # Do division before addition to prevent possible integer + # overflow + self._side = 'left' + self.x_bds = self.x / 2.0 + self.x_bds = self.x_bds[1:] + self.x_bds[:-1] + + self._call = self.__class__._call_nearest + elif kind == 'nearest-up': + # Do division before addition to prevent possible integer + # overflow + self._side = 'right' + self.x_bds = self.x / 2.0 + self.x_bds = self.x_bds[1:] + self.x_bds[:-1] + + self._call = self.__class__._call_nearest + elif kind == 'previous': + # Side for np.searchsorted and index for clipping + self._side = 'left' + self._ind = 0 + # Move x by one floating point value to the left + self._x_shift = np.nextafter(self.x, -np.inf) + self._call = self.__class__._call_previousnext + if _do_extrapolate(fill_value): + self._check_and_update_bounds_error_for_extrapolation() + # assume y is sorted by x ascending order here. + fill_value = (np.nan, np.take(self.y, -1, axis)) + elif kind == 'next': + self._side = 'right' + self._ind = 1 + # Move x by one floating point value to the right + self._x_shift = np.nextafter(self.x, np.inf) + self._call = self.__class__._call_previousnext + if _do_extrapolate(fill_value): + self._check_and_update_bounds_error_for_extrapolation() + # assume y is sorted by x ascending order here. + fill_value = (np.take(self.y, 0, axis), np.nan) + else: + # Check if we can delegate to numpy.interp (2x-10x faster). + np_dtypes = (np.dtype(np.float64), np.dtype(int)) + cond = self.x.dtype in np_dtypes and self.y.dtype in np_dtypes + cond = cond and self.y.ndim == 1 + cond = cond and not _do_extrapolate(fill_value) + + if cond: + self._call = self.__class__._call_linear_np + else: + self._call = self.__class__._call_linear + else: + minval = order + 1 + + rewrite_nan = False + xx, yy = self.x, self._y + if order > 1: + # Quadratic or cubic spline. If input contains even a single + # nan, then the output is all nans. We cannot just feed data + # with nans to make_interp_spline because it calls LAPACK. + # So, we make up a bogus x and y with no nans and use it + # to get the correct shape of the output, which we then fill + # with nans. + # For slinear or zero order spline, we just pass nans through. + mask = np.isnan(self.x) + if mask.any(): + sx = self.x[~mask] + if sx.size == 0: + raise ValueError("`x` array is all-nan") + xx = np.linspace(np.nanmin(self.x), + np.nanmax(self.x), + len(self.x)) + rewrite_nan = True + if np.isnan(self._y).any(): + yy = np.ones_like(self._y) + rewrite_nan = True + + self._spline = make_interp_spline(xx, yy, k=order, + check_finite=False) + if rewrite_nan: + self._call = self.__class__._call_nan_spline + else: + self._call = self.__class__._call_spline + + if len(self.x) < minval: + raise ValueError("x and y arrays must have at " + "least %d entries" % minval) + + self.fill_value = fill_value # calls the setter, can modify bounds_err + + @property + def fill_value(self): + """The fill value.""" + # backwards compat: mimic a public attribute + return self._fill_value_orig + + @fill_value.setter + def fill_value(self, fill_value): + # extrapolation only works for nearest neighbor and linear methods + if _do_extrapolate(fill_value): + self._check_and_update_bounds_error_for_extrapolation() + self._extrapolate = True + else: + broadcast_shape = (self.y.shape[:self.axis] + + self.y.shape[self.axis + 1:]) + if len(broadcast_shape) == 0: + broadcast_shape = (1,) + # it's either a pair (_below_range, _above_range) or a single value + # for both above and below range + if isinstance(fill_value, tuple) and len(fill_value) == 2: + below_above = [np.asarray(fill_value[0]), + np.asarray(fill_value[1])] + names = ('fill_value (below)', 'fill_value (above)') + for ii in range(2): + below_above[ii] = _check_broadcast_up_to( + below_above[ii], broadcast_shape, names[ii]) + else: + fill_value = np.asarray(fill_value) + below_above = [_check_broadcast_up_to( + fill_value, broadcast_shape, 'fill_value')] * 2 + self._fill_value_below, self._fill_value_above = below_above + self._extrapolate = False + if self.bounds_error is None: + self.bounds_error = True + # backwards compat: fill_value was a public attr; make it writeable + self._fill_value_orig = fill_value + + def _check_and_update_bounds_error_for_extrapolation(self): + if self.bounds_error: + raise ValueError("Cannot extrapolate and raise " + "at the same time.") + self.bounds_error = False + + def _call_linear_np(self, x_new): + # Note that out-of-bounds values are taken care of in self._evaluate + return np.interp(x_new, self.x, self.y) + + def _call_linear(self, x_new): + # 2. Find where in the original data, the values to interpolate + # would be inserted. + # Note: If x_new[n] == x[m], then m is returned by searchsorted. + x_new_indices = searchsorted(self.x, x_new) + + # 3. Clip x_new_indices so that they are within the range of + # self.x indices and at least 1. Removes mis-interpolation + # of x_new[n] = x[0] + x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int) + + # 4. Calculate the slope of regions that each x_new value falls in. + lo = x_new_indices - 1 + hi = x_new_indices + + x_lo = self.x[lo] + x_hi = self.x[hi] + y_lo = self._y[lo] + y_hi = self._y[hi] + + # Note that the following two expressions rely on the specifics of the + # broadcasting semantics. + slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None] + + # 5. Calculate the actual value for each entry in x_new. + y_new = slope*(x_new - x_lo)[:, None] + y_lo + + return y_new + + def _call_nearest(self, x_new): + """ Find nearest neighbor interpolated y_new = f(x_new).""" + + # 2. Find where in the averaged data the values to interpolate + # would be inserted. + # Note: use side='left' (right) to searchsorted() to define the + # halfway point to be nearest to the left (right) neighbor + x_new_indices = searchsorted(self.x_bds, x_new, side=self._side) + + # 3. Clip x_new_indices so that they are within the range of x indices. + x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp) + + # 4. Calculate the actual value for each entry in x_new. + y_new = self._y[x_new_indices] + + return y_new + + def _call_previousnext(self, x_new): + """Use previous/next neighbor of x_new, y_new = f(x_new).""" + + # 1. Get index of left/right value + x_new_indices = searchsorted(self._x_shift, x_new, side=self._side) + + # 2. Clip x_new_indices so that they are within the range of x indices. + x_new_indices = x_new_indices.clip(1-self._ind, + len(self.x)-self._ind).astype(intp) + + # 3. Calculate the actual value for each entry in x_new. + y_new = self._y[x_new_indices+self._ind-1] + + return y_new + + def _call_spline(self, x_new): + return self._spline(x_new) + + def _call_nan_spline(self, x_new): + out = self._spline(x_new) + out[...] = np.nan + return out + + def _evaluate(self, x_new): + # 1. Handle values in x_new that are outside of x. Throw error, + # or return a list of mask array indicating the outofbounds values. + # The behavior is set by the bounds_error variable. + x_new = asarray(x_new) + y_new = self._call(self, x_new) + if not self._extrapolate: + below_bounds, above_bounds = self._check_bounds(x_new) + if len(y_new) > 0: + # Note fill_value must be broadcast up to the proper size + # and flattened to work here + y_new[below_bounds] = self._fill_value_below + y_new[above_bounds] = self._fill_value_above + return y_new + + def _check_bounds(self, x_new): + """Check the inputs for being in the bounds of the interpolated data. + + Parameters + ---------- + x_new : array + + Returns + ------- + out_of_bounds : bool array + The mask on x_new of values that are out of the bounds. + """ + + # If self.bounds_error is True, we raise an error if any x_new values + # fall outside the range of x. Otherwise, we return an array indicating + # which values are outside the boundary region. + below_bounds = x_new < self.x[0] + above_bounds = x_new > self.x[-1] + + if self.bounds_error and below_bounds.any(): + below_bounds_value = x_new[np.argmax(below_bounds)] + raise ValueError(f"A value ({below_bounds_value}) in x_new is below " + f"the interpolation range's minimum value ({self.x[0]}).") + if self.bounds_error and above_bounds.any(): + above_bounds_value = x_new[np.argmax(above_bounds)] + raise ValueError(f"A value ({above_bounds_value}) in x_new is above " + f"the interpolation range's maximum value ({self.x[-1]}).") + + # !! Should we emit a warning if some values are out of bounds? + # !! matlab does not. + return below_bounds, above_bounds + + +class _PPolyBase: + """Base class for piecewise polynomials.""" + __slots__ = ('c', 'x', 'extrapolate', 'axis') + + def __init__(self, c, x, extrapolate=None, axis=0): + self.c = np.asarray(c) + self.x = np.ascontiguousarray(x, dtype=np.float64) + + if extrapolate is None: + extrapolate = True + elif extrapolate != 'periodic': + extrapolate = bool(extrapolate) + self.extrapolate = extrapolate + + if self.c.ndim < 2: + raise ValueError("Coefficients array must be at least " + "2-dimensional.") + + if not (0 <= axis < self.c.ndim - 1): + raise ValueError(f"axis={axis} must be between 0 and {self.c.ndim-1}") + + self.axis = axis + if axis != 0: + # move the interpolation axis to be the first one in self.c + # More specifically, the target shape for self.c is (k, m, ...), + # and axis !=0 means that we have c.shape (..., k, m, ...) + # ^ + # axis + # So we roll two of them. + self.c = np.moveaxis(self.c, axis+1, 0) + self.c = np.moveaxis(self.c, axis+1, 0) + + if self.x.ndim != 1: + raise ValueError("x must be 1-dimensional") + if self.x.size < 2: + raise ValueError("at least 2 breakpoints are needed") + if self.c.ndim < 2: + raise ValueError("c must have at least 2 dimensions") + if self.c.shape[0] == 0: + raise ValueError("polynomial must be at least of order 0") + if self.c.shape[1] != self.x.size-1: + raise ValueError("number of coefficients != len(x)-1") + dx = np.diff(self.x) + if not (np.all(dx >= 0) or np.all(dx <= 0)): + raise ValueError("`x` must be strictly increasing or decreasing.") + + dtype = self._get_dtype(self.c.dtype) + self.c = np.ascontiguousarray(self.c, dtype=dtype) + + def _get_dtype(self, dtype): + if np.issubdtype(dtype, np.complexfloating) \ + or np.issubdtype(self.c.dtype, np.complexfloating): + return np.complex128 + else: + return np.float64 + + @classmethod + def construct_fast(cls, c, x, extrapolate=None, axis=0): + """ + Construct the piecewise polynomial without making checks. + + Takes the same parameters as the constructor. Input arguments + ``c`` and ``x`` must be arrays of the correct shape and type. The + ``c`` array can only be of dtypes float and complex, and ``x`` + array must have dtype float. + """ + self = object.__new__(cls) + self.c = c + self.x = x + self.axis = axis + if extrapolate is None: + extrapolate = True + self.extrapolate = extrapolate + return self + + def _ensure_c_contiguous(self): + """ + c and x may be modified by the user. The Cython code expects + that they are C contiguous. + """ + if not self.x.flags.c_contiguous: + self.x = self.x.copy() + if not self.c.flags.c_contiguous: + self.c = self.c.copy() + + def extend(self, c, x): + """ + Add additional breakpoints and coefficients to the polynomial. + + Parameters + ---------- + c : ndarray, size (k, m, ...) + Additional coefficients for polynomials in intervals. Note that + the first additional interval will be formed using one of the + ``self.x`` end points. + x : ndarray, size (m,) + Additional breakpoints. Must be sorted in the same order as + ``self.x`` and either to the right or to the left of the current + breakpoints. + + Notes + ----- + This method is not thread safe and must not be executed concurrently + with other methods available in this class. Doing so may cause + unexpected errors or numerical output mismatches. + """ + + c = np.asarray(c) + x = np.asarray(x) + + if c.ndim < 2: + raise ValueError("invalid dimensions for c") + if x.ndim != 1: + raise ValueError("invalid dimensions for x") + if x.shape[0] != c.shape[1]: + raise ValueError(f"Shapes of x {x.shape} and c {c.shape} are incompatible") + if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim: + raise ValueError( + f"Shapes of c {c.shape} and self.c {self.c.shape} are incompatible" + ) + + if c.size == 0: + return + + dx = np.diff(x) + if not (np.all(dx >= 0) or np.all(dx <= 0)): + raise ValueError("`x` is not sorted.") + + if self.x[-1] >= self.x[0]: + if not x[-1] >= x[0]: + raise ValueError("`x` is in the different order " + "than `self.x`.") + + if x[0] >= self.x[-1]: + action = 'append' + elif x[-1] <= self.x[0]: + action = 'prepend' + else: + raise ValueError("`x` is neither on the left or on the right " + "from `self.x`.") + else: + if not x[-1] <= x[0]: + raise ValueError("`x` is in the different order " + "than `self.x`.") + + if x[0] <= self.x[-1]: + action = 'append' + elif x[-1] >= self.x[0]: + action = 'prepend' + else: + raise ValueError("`x` is neither on the left or on the right " + "from `self.x`.") + + dtype = self._get_dtype(c.dtype) + + k2 = max(c.shape[0], self.c.shape[0]) + c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:], + dtype=dtype) + + if action == 'append': + c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c + c2[k2-c.shape[0]:, self.c.shape[1]:] = c + self.x = np.r_[self.x, x] + elif action == 'prepend': + c2[k2-self.c.shape[0]:, :c.shape[1]] = c + c2[k2-c.shape[0]:, c.shape[1]:] = self.c + self.x = np.r_[x, self.x] + + self.c = c2 + + def __call__(self, x, nu=0, extrapolate=None): + """ + Evaluate the piecewise polynomial or its derivative. + + Parameters + ---------- + x : array_like + Points to evaluate the interpolant at. + nu : int, optional + Order of derivative to evaluate. Must be non-negative. + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. + If None (default), use `self.extrapolate`. + + Returns + ------- + y : array_like + Interpolated values. Shape is determined by replacing + the interpolation axis in the original array with the shape of x. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals are considered half-open, + ``[a, b)``, except for the last interval which is closed + ``[a, b]``. + """ + if extrapolate is None: + extrapolate = self.extrapolate + x = np.asarray(x) + x_shape, x_ndim = x.shape, x.ndim + x = np.ascontiguousarray(x.ravel(), dtype=np.float64) + + # With periodic extrapolation we map x to the segment + # [self.x[0], self.x[-1]]. + if extrapolate == 'periodic': + x = self.x[0] + (x - self.x[0]) % (self.x[-1] - self.x[0]) + extrapolate = False + + out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype) + self._ensure_c_contiguous() + self._evaluate(x, nu, extrapolate, out) + out = out.reshape(x_shape + self.c.shape[2:]) + if self.axis != 0: + # transpose to move the calculated values to the interpolation axis + l = list(range(out.ndim)) + l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:] + out = out.transpose(l) + return out + + +class PPoly(_PPolyBase): + """ + Piecewise polynomial in terms of coefficients and breakpoints + + The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the + local power basis:: + + S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1)) + + where ``k`` is the degree of the polynomial. + + Parameters + ---------- + c : ndarray, shape (k, m, ...) + Polynomial coefficients, order `k` and `m` intervals. + x : ndarray, shape (m+1,) + Polynomial breakpoints. Must be sorted in either increasing or + decreasing order. + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. If 'periodic', + periodic extrapolation is used. Default is True. + axis : int, optional + Interpolation axis. Default is zero. + + Attributes + ---------- + x : ndarray + Breakpoints. + c : ndarray + Coefficients of the polynomials. They are reshaped + to a 3-D array with the last dimension representing + the trailing dimensions of the original coefficient array. + axis : int + Interpolation axis. + + Methods + ------- + __call__ + derivative + antiderivative + integrate + solve + roots + extend + from_spline + from_bernstein_basis + construct_fast + + See also + -------- + BPoly : piecewise polynomials in the Bernstein basis + + Notes + ----- + High-order polynomials in the power basis can be numerically + unstable. Precision problems can start to appear for orders + larger than 20-30. + """ + + def _evaluate(self, x, nu, extrapolate, out): + _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, x, nu, bool(extrapolate), out) + + def derivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the derivative. + + Parameters + ---------- + nu : int, optional + Order of derivative to evaluate. Default is 1, i.e., compute the + first derivative. If negative, the antiderivative is returned. + + Returns + ------- + pp : PPoly + Piecewise polynomial of order k2 = k - n representing the derivative + of this polynomial. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals are considered half-open, + ``[a, b)``, except for the last interval which is closed + ``[a, b]``. + """ + if nu < 0: + return self.antiderivative(-nu) + + # reduce order + if nu == 0: + c2 = self.c.copy() + else: + c2 = self.c[:-nu, :].copy() + + if c2.shape[0] == 0: + # derivative of order 0 is zero + c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) + + # multiply by the correct rising factorials + factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu) + c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)] + + # construct a compatible polynomial + return self.construct_fast(c2, self.x, self.extrapolate, self.axis) + + def antiderivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the antiderivative. + + Antiderivative is also the indefinite integral of the function, + and derivative is its inverse operation. + + Parameters + ---------- + nu : int, optional + Order of antiderivative to evaluate. Default is 1, i.e., compute + the first integral. If negative, the derivative is returned. + + Returns + ------- + pp : PPoly + Piecewise polynomial of order k2 = k + n representing + the antiderivative of this polynomial. + + Notes + ----- + The antiderivative returned by this function is continuous and + continuously differentiable to order n-1, up to floating point + rounding error. + + If antiderivative is computed and ``self.extrapolate='periodic'``, + it will be set to False for the returned instance. This is done because + the antiderivative is no longer periodic and its correct evaluation + outside of the initially given x interval is difficult. + """ + if nu <= 0: + return self.derivative(-nu) + + c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:], + dtype=self.c.dtype) + c[:-nu] = self.c + + # divide by the correct rising factorials + factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu) + c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] + + # fix continuity of added degrees of freedom + self._ensure_c_contiguous() + _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1), + self.x, nu - 1) + + if self.extrapolate == 'periodic': + extrapolate = False + else: + extrapolate = self.extrapolate + + # construct a compatible polynomial + return self.construct_fast(c, self.x, extrapolate, self.axis) + + def integrate(self, a, b, extrapolate=None): + """ + Compute a definite integral over a piecewise polynomial. + + Parameters + ---------- + a : float + Lower integration bound + b : float + Upper integration bound + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. + If None (default), use `self.extrapolate`. + + Returns + ------- + ig : array_like + Definite integral of the piecewise polynomial over [a, b] + """ + if extrapolate is None: + extrapolate = self.extrapolate + + # Swap integration bounds if needed + sign = 1 + if b < a: + a, b = b, a + sign = -1 + + range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype) + self._ensure_c_contiguous() + + # Compute the integral. + if extrapolate == 'periodic': + # Split the integral into the part over period (can be several + # of them) and the remaining part. + + xs, xe = self.x[0], self.x[-1] + period = xe - xs + interval = b - a + n_periods, left = divmod(interval, period) + + if n_periods > 0: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, xs, xe, False, out=range_int) + range_int *= n_periods + else: + range_int.fill(0) + + # Map a to [xs, xe], b is always a + left. + a = xs + (a - xs) % period + b = a + left + + # If b <= xe then we need to integrate over [a, b], otherwise + # over [a, xe] and from xs to what is remained. + remainder_int = np.empty_like(range_int) + if b <= xe: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, a, b, False, out=remainder_int) + range_int += remainder_int + else: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, a, xe, False, out=remainder_int) + range_int += remainder_int + + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, xs, xs + left + a - xe, False, out=remainder_int) + range_int += remainder_int + else: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, a, b, bool(extrapolate), out=range_int) + + # Return + range_int *= sign + return range_int.reshape(self.c.shape[2:]) + + def solve(self, y=0., discontinuity=True, extrapolate=None): + """ + Find real solutions of the equation ``pp(x) == y``. + + Parameters + ---------- + y : float, optional + Right-hand side. Default is zero. + discontinuity : bool, optional + Whether to report sign changes across discontinuities at + breakpoints as roots. + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to return roots from the polynomial + extrapolated based on first and last intervals, 'periodic' works + the same as False. If None (default), use `self.extrapolate`. + + Returns + ------- + roots : ndarray + Roots of the polynomial(s). + + If the PPoly object describes multiple polynomials, the + return value is an object array whose each element is an + ndarray containing the roots. + + Notes + ----- + This routine works only on real-valued polynomials. + + If the piecewise polynomial contains sections that are + identically zero, the root list will contain the start point + of the corresponding interval, followed by a ``nan`` value. + + If the polynomial is discontinuous across a breakpoint, and + there is a sign change across the breakpoint, this is reported + if the `discont` parameter is True. + + Examples + -------- + + Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals + ``[-2, 1], [1, 2]``: + + >>> import numpy as np + >>> from scipy.interpolate import PPoly + >>> pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2]) + >>> pp.solve() + array([-1., 1.]) + """ + if extrapolate is None: + extrapolate = self.extrapolate + + self._ensure_c_contiguous() + + if np.issubdtype(self.c.dtype, np.complexfloating): + raise ValueError("Root finding is only for " + "real-valued polynomials") + + y = float(y) + r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, y, bool(discontinuity), + bool(extrapolate)) + if self.c.ndim == 2: + return r[0] + else: + r2 = np.empty(prod(self.c.shape[2:]), dtype=object) + # this for-loop is equivalent to ``r2[...] = r``, but that's broken + # in NumPy 1.6.0 + for ii, root in enumerate(r): + r2[ii] = root + + return r2.reshape(self.c.shape[2:]) + + def roots(self, discontinuity=True, extrapolate=None): + """ + Find real roots of the piecewise polynomial. + + Parameters + ---------- + discontinuity : bool, optional + Whether to report sign changes across discontinuities at + breakpoints as roots. + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to return roots from the polynomial + extrapolated based on first and last intervals, 'periodic' works + the same as False. If None (default), use `self.extrapolate`. + + Returns + ------- + roots : ndarray + Roots of the polynomial(s). + + If the PPoly object describes multiple polynomials, the + return value is an object array whose each element is an + ndarray containing the roots. + + See Also + -------- + PPoly.solve + """ + return self.solve(0, discontinuity, extrapolate) + + @classmethod + def from_spline(cls, tck, extrapolate=None): + """ + Construct a piecewise polynomial from a spline + + Parameters + ---------- + tck + A spline, as returned by `splrep` or a BSpline object. + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + + Examples + -------- + Construct an interpolating spline and convert it to a `PPoly` instance + + >>> import numpy as np + >>> from scipy.interpolate import splrep, PPoly + >>> x = np.linspace(0, 1, 11) + >>> y = np.sin(2*np.pi*x) + >>> tck = splrep(x, y, s=0) + >>> p = PPoly.from_spline(tck) + >>> isinstance(p, PPoly) + True + + Note that this function only supports 1D splines out of the box. + + If the ``tck`` object represents a parametric spline (e.g. constructed + by `splprep` or a `BSpline` with ``c.ndim > 1``), you will need to loop + over the dimensions manually. + + >>> from scipy.interpolate import splprep, splev + >>> t = np.linspace(0, 1, 11) + >>> x = np.sin(2*np.pi*t) + >>> y = np.cos(2*np.pi*t) + >>> (t, c, k), u = splprep([x, y], s=0) + + Note that ``c`` is a list of two arrays of length 11. + + >>> unew = np.arange(0, 1.01, 0.01) + >>> out = splev(unew, (t, c, k)) + + To convert this spline to the power basis, we convert each + component of the list of b-spline coefficients, ``c``, into the + corresponding cubic polynomial. + + >>> polys = [PPoly.from_spline((t, cj, k)) for cj in c] + >>> polys[0].c.shape + (4, 14) + + Note that the coefficients of the polynomials `polys` are in the + power basis and their dimensions reflect just that: here 4 is the order + (degree+1), and 14 is the number of intervals---which is nothing but + the length of the knot array of the original `tck` minus one. + + Optionally, we can stack the components into a single `PPoly` along + the third dimension: + + >>> cc = np.dstack([p.c for p in polys]) # has shape = (4, 14, 2) + >>> poly = PPoly(cc, polys[0].x) + >>> np.allclose(poly(unew).T, # note the transpose to match `splev` + ... out, atol=1e-15) + True + + """ + if isinstance(tck, BSpline): + t, c, k = tck.tck + if extrapolate is None: + extrapolate = tck.extrapolate + else: + t, c, k = tck + + cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype) + for m in range(k, -1, -1): + y = _fitpack_py.splev(t[:-1], tck, der=m) + cvals[k - m, :] = y/spec.gamma(m+1) + + return cls.construct_fast(cvals, t, extrapolate) + + @classmethod + def from_bernstein_basis(cls, bp, extrapolate=None): + """ + Construct a piecewise polynomial in the power basis + from a polynomial in Bernstein basis. + + Parameters + ---------- + bp : BPoly + A Bernstein basis polynomial, as created by BPoly + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + """ + if not isinstance(bp, BPoly): + raise TypeError(f".from_bernstein_basis only accepts BPoly instances. " + f"Got {type(bp)} instead.") + + dx = np.diff(bp.x) + k = bp.c.shape[0] - 1 # polynomial order + + rest = (None,)*(bp.c.ndim-2) + + c = np.zeros_like(bp.c) + for a in range(k+1): + factor = (-1)**a * comb(k, a) * bp.c[a] + for s in range(a, k+1): + val = comb(k-a, s-a) * (-1)**s + c[k-s] += factor * val / dx[(slice(None),)+rest]**s + + if extrapolate is None: + extrapolate = bp.extrapolate + + return cls.construct_fast(c, bp.x, extrapolate, bp.axis) + + +class BPoly(_PPolyBase): + """Piecewise polynomial in terms of coefficients and breakpoints. + + The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the + Bernstein polynomial basis:: + + S = sum(c[a, i] * b(a, k; x) for a in range(k+1)), + + where ``k`` is the degree of the polynomial, and:: + + b(a, k; x) = binom(k, a) * t**a * (1 - t)**(k - a), + + with ``t = (x - x[i]) / (x[i+1] - x[i])`` and ``binom`` is the binomial + coefficient. + + Parameters + ---------- + c : ndarray, shape (k, m, ...) + Polynomial coefficients, order `k` and `m` intervals + x : ndarray, shape (m+1,) + Polynomial breakpoints. Must be sorted in either increasing or + decreasing order. + extrapolate : bool, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. If 'periodic', + periodic extrapolation is used. Default is True. + axis : int, optional + Interpolation axis. Default is zero. + + Attributes + ---------- + x : ndarray + Breakpoints. + c : ndarray + Coefficients of the polynomials. They are reshaped + to a 3-D array with the last dimension representing + the trailing dimensions of the original coefficient array. + axis : int + Interpolation axis. + + Methods + ------- + __call__ + extend + derivative + antiderivative + integrate + construct_fast + from_power_basis + from_derivatives + + See also + -------- + PPoly : piecewise polynomials in the power basis + + Notes + ----- + Properties of Bernstein polynomials are well documented in the literature, + see for example [1]_ [2]_ [3]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Bernstein_polynomial + + .. [2] Kenneth I. Joy, Bernstein polynomials, + http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf + + .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems, + vol 2011, article ID 829546, :doi:`10.1155/2011/829543`. + + Examples + -------- + >>> from scipy.interpolate import BPoly + >>> x = [0, 1] + >>> c = [[1], [2], [3]] + >>> bp = BPoly(c, x) + + This creates a 2nd order polynomial + + .. math:: + + B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3 + \\times b_{2, 2}(x) \\\\ + = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2 + + """ # noqa: E501 + + def _evaluate(self, x, nu, extrapolate, out): + _ppoly.evaluate_bernstein( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, x, nu, bool(extrapolate), out) + + def derivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the derivative. + + Parameters + ---------- + nu : int, optional + Order of derivative to evaluate. Default is 1, i.e., compute the + first derivative. If negative, the antiderivative is returned. + + Returns + ------- + bp : BPoly + Piecewise polynomial of order k - nu representing the derivative of + this polynomial. + + """ + if nu < 0: + return self.antiderivative(-nu) + + if nu > 1: + bp = self + for k in range(nu): + bp = bp.derivative() + return bp + + # reduce order + if nu == 0: + c2 = self.c.copy() + else: + # For a polynomial + # B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x), + # we use the fact that + # b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ), + # which leads to + # B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1} + # + # finally, for an interval [y, y + dy] with dy != 1, + # we need to correct for an extra power of dy + + rest = (None,)*(self.c.ndim-2) + + k = self.c.shape[0] - 1 + dx = np.diff(self.x)[(None, slice(None))+rest] + c2 = k * np.diff(self.c, axis=0) / dx + + if c2.shape[0] == 0: + # derivative of order 0 is zero + c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) + + # construct a compatible polynomial + return self.construct_fast(c2, self.x, self.extrapolate, self.axis) + + def antiderivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the antiderivative. + + Parameters + ---------- + nu : int, optional + Order of antiderivative to evaluate. Default is 1, i.e., compute + the first integral. If negative, the derivative is returned. + + Returns + ------- + bp : BPoly + Piecewise polynomial of order k + nu representing the + antiderivative of this polynomial. + + Notes + ----- + If antiderivative is computed and ``self.extrapolate='periodic'``, + it will be set to False for the returned instance. This is done because + the antiderivative is no longer periodic and its correct evaluation + outside of the initially given x interval is difficult. + """ + if nu <= 0: + return self.derivative(-nu) + + if nu > 1: + bp = self + for k in range(nu): + bp = bp.antiderivative() + return bp + + # Construct the indefinite integrals on individual intervals + c, x = self.c, self.x + k = c.shape[0] + c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype) + + c2[1:, ...] = np.cumsum(c, axis=0) / k + delta = x[1:] - x[:-1] + c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)] + + # Now fix continuity: on the very first interval, take the integration + # constant to be zero; on an interval [x_j, x_{j+1}) with j>0, + # the integration constant is then equal to the jump of the `bp` at x_j. + # The latter is given by the coefficient of B_{n+1, n+1} + # *on the previous interval* (other B. polynomials are zero at the + # breakpoint). Finally, use the fact that BPs form a partition of unity. + c2[:,1:] += np.cumsum(c2[k, :], axis=0)[:-1] + + if self.extrapolate == 'periodic': + extrapolate = False + else: + extrapolate = self.extrapolate + + return self.construct_fast(c2, x, extrapolate, axis=self.axis) + + def integrate(self, a, b, extrapolate=None): + """ + Compute a definite integral over a piecewise polynomial. + + Parameters + ---------- + a : float + Lower integration bound + b : float + Upper integration bound + extrapolate : {bool, 'periodic', None}, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. If 'periodic', periodic + extrapolation is used. If None (default), use `self.extrapolate`. + + Returns + ------- + array_like + Definite integral of the piecewise polynomial over [a, b] + + """ + # XXX: can probably use instead the fact that + # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1) + ib = self.antiderivative() + if extrapolate is None: + extrapolate = self.extrapolate + + # ib.extrapolate shouldn't be 'periodic', it is converted to + # False for 'periodic. in antiderivative() call. + if extrapolate != 'periodic': + ib.extrapolate = extrapolate + + if extrapolate == 'periodic': + # Split the integral into the part over period (can be several + # of them) and the remaining part. + + # For simplicity and clarity convert to a <= b case. + if a <= b: + sign = 1 + else: + a, b = b, a + sign = -1 + + xs, xe = self.x[0], self.x[-1] + period = xe - xs + interval = b - a + n_periods, left = divmod(interval, period) + res = n_periods * (ib(xe) - ib(xs)) + + # Map a and b to [xs, xe]. + a = xs + (a - xs) % period + b = a + left + + # If b <= xe then we need to integrate over [a, b], otherwise + # over [a, xe] and from xs to what is remained. + if b <= xe: + res += ib(b) - ib(a) + else: + res += ib(xe) - ib(a) + ib(xs + left + a - xe) - ib(xs) + + return sign * res + else: + return ib(b) - ib(a) + + def extend(self, c, x): + k = max(self.c.shape[0], c.shape[0]) + self.c = self._raise_degree(self.c, k - self.c.shape[0]) + c = self._raise_degree(c, k - c.shape[0]) + return _PPolyBase.extend(self, c, x) + extend.__doc__ = _PPolyBase.extend.__doc__ + + @classmethod + def from_power_basis(cls, pp, extrapolate=None): + """ + Construct a piecewise polynomial in Bernstein basis + from a power basis polynomial. + + Parameters + ---------- + pp : PPoly + A piecewise polynomial in the power basis + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + """ + if not isinstance(pp, PPoly): + raise TypeError(f".from_power_basis only accepts PPoly instances. " + f"Got {type(pp)} instead.") + + dx = np.diff(pp.x) + k = pp.c.shape[0] - 1 # polynomial order + + rest = (None,)*(pp.c.ndim-2) + + c = np.zeros_like(pp.c) + for a in range(k+1): + factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a) + for j in range(k-a, k+1): + c[j] += factor * comb(j, k-a) + + if extrapolate is None: + extrapolate = pp.extrapolate + + return cls.construct_fast(c, pp.x, extrapolate, pp.axis) + + @classmethod + def from_derivatives(cls, xi, yi, orders=None, extrapolate=None): + """Construct a piecewise polynomial in the Bernstein basis, + compatible with the specified values and derivatives at breakpoints. + + Parameters + ---------- + xi : array_like + sorted 1-D array of x-coordinates + yi : array_like or list of array_likes + ``yi[i][j]`` is the ``j``\\ th derivative known at ``xi[i]`` + orders : None or int or array_like of ints. Default: None. + Specifies the degree of local polynomials. If not None, some + derivatives are ignored. + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + + Notes + ----- + If ``k`` derivatives are specified at a breakpoint ``x``, the + constructed polynomial is exactly ``k`` times continuously + differentiable at ``x``, unless the ``order`` is provided explicitly. + In the latter case, the smoothness of the polynomial at + the breakpoint is controlled by the ``order``. + + Deduces the number of derivatives to match at each end + from ``order`` and the number of derivatives available. If + possible it uses the same number of derivatives from + each end; if the number is odd it tries to take the + extra one from y2. In any case if not enough derivatives + are available at one end or another it draws enough to + make up the total from the other end. + + If the order is too high and not enough derivatives are available, + an exception is raised. + + Examples + -------- + + >>> from scipy.interpolate import BPoly + >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]]) + + Creates a polynomial `f(x)` of degree 3, defined on ``[0, 1]`` + such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4` + + >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]]) + + Creates a piecewise polynomial `f(x)`, such that + `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`. + Based on the number of derivatives provided, the order of the + local polynomials is 2 on ``[0, 1]`` and 1 on ``[1, 2]``. + Notice that no restriction is imposed on the derivatives at + ``x = 1`` and ``x = 2``. + + Indeed, the explicit form of the polynomial is:: + + f(x) = | x * (1 - x), 0 <= x < 1 + | 2 * (x - 1), 1 <= x <= 2 + + So that f'(1-0) = -1 and f'(1+0) = 2 + + """ + xi = np.asarray(xi) + if len(xi) != len(yi): + raise ValueError("xi and yi need to have the same length") + if np.any(xi[1:] - xi[:1] <= 0): + raise ValueError("x coordinates are not in increasing order") + + # number of intervals + m = len(xi) - 1 + + # global poly order is k-1, local orders are <=k and can vary + try: + k = max(len(yi[i]) + len(yi[i+1]) for i in range(m)) + except TypeError as e: + raise ValueError( + "Using a 1-D array for y? Please .reshape(-1, 1)." + ) from e + + if orders is None: + orders = [None] * m + else: + if isinstance(orders, (int, np.integer)): + orders = [orders] * m + k = max(k, max(orders)) + + if any(o <= 0 for o in orders): + raise ValueError("Orders must be positive.") + + c = [] + for i in range(m): + y1, y2 = yi[i], yi[i+1] + if orders[i] is None: + n1, n2 = len(y1), len(y2) + else: + n = orders[i]+1 + n1 = min(n//2, len(y1)) + n2 = min(n - n1, len(y2)) + n1 = min(n - n2, len(y2)) + if n1+n2 != n: + mesg = ("Point %g has %d derivatives, point %g" + " has %d derivatives, but order %d requested" % ( + xi[i], len(y1), xi[i+1], len(y2), orders[i])) + raise ValueError(mesg) + + if not (n1 <= len(y1) and n2 <= len(y2)): + raise ValueError("`order` input incompatible with" + " length y1 or y2.") + + b = BPoly._construct_from_derivatives(xi[i], xi[i+1], + y1[:n1], y2[:n2]) + if len(b) < k: + b = BPoly._raise_degree(b, k - len(b)) + c.append(b) + + c = np.asarray(c) + return cls(c.swapaxes(0, 1), xi, extrapolate) + + @staticmethod + def _construct_from_derivatives(xa, xb, ya, yb): + r"""Compute the coefficients of a polynomial in the Bernstein basis + given the values and derivatives at the edges. + + Return the coefficients of a polynomial in the Bernstein basis + defined on ``[xa, xb]`` and having the values and derivatives at the + endpoints `xa` and `xb` as specified by `ya` and `yb`. + The polynomial constructed is of the minimal possible degree, i.e., + if the lengths of `ya` and `yb` are `na` and `nb`, the degree + of the polynomial is ``na + nb - 1``. + + Parameters + ---------- + xa : float + Left-hand end point of the interval + xb : float + Right-hand end point of the interval + ya : array_like + Derivatives at `xa`. ``ya[0]`` is the value of the function, and + ``ya[i]`` for ``i > 0`` is the value of the ``i``\ th derivative. + yb : array_like + Derivatives at `xb`. + + Returns + ------- + array + coefficient array of a polynomial having specified derivatives + + Notes + ----- + This uses several facts from life of Bernstein basis functions. + First of all, + + .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1}) + + If B(x) is a linear combination of the form + + .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n}, + + then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}. + Iterating the latter one, one finds for the q-th derivative + + .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q}, + + with + + .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a} + + This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and + `c_q` are found one by one by iterating `q = 0, ..., na`. + + At ``x = xb`` it's the same with ``a = n - q``. + + """ + ya, yb = np.asarray(ya), np.asarray(yb) + if ya.shape[1:] != yb.shape[1:]: + raise ValueError( + f"Shapes of ya {ya.shape} and yb {yb.shape} are incompatible" + ) + + dta, dtb = ya.dtype, yb.dtype + if (np.issubdtype(dta, np.complexfloating) or + np.issubdtype(dtb, np.complexfloating)): + dt = np.complex128 + else: + dt = np.float64 + + na, nb = len(ya), len(yb) + n = na + nb + + c = np.empty((na+nb,) + ya.shape[1:], dtype=dt) + + # compute coefficients of a polynomial degree na+nb-1 + # walk left-to-right + for q in range(0, na): + c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q + for j in range(0, q): + c[q] -= (-1)**(j+q) * comb(q, j) * c[j] + + # now walk right-to-left + for q in range(0, nb): + c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q + for j in range(0, q): + c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j] + + return c + + @staticmethod + def _raise_degree(c, d): + r"""Raise a degree of a polynomial in the Bernstein basis. + + Given the coefficients of a polynomial degree `k`, return (the + coefficients of) the equivalent polynomial of degree `k+d`. + + Parameters + ---------- + c : array_like + coefficient array, 1-D + d : integer + + Returns + ------- + array + coefficient array, 1-D array of length `c.shape[0] + d` + + Notes + ----- + This uses the fact that a Bernstein polynomial `b_{a, k}` can be + identically represented as a linear combination of polynomials of + a higher degree `k+d`: + + .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \ + comb(d, j) / comb(k+d, a+j) + + """ + if d == 0: + return c + + k = c.shape[0] - 1 + out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype) + + for a in range(c.shape[0]): + f = c[a] * comb(k, a) + for j in range(d+1): + out[a+j] += f * comb(d, j) / comb(k+d, a+j) + return out + + +class NdPPoly: + """ + Piecewise tensor product polynomial + + The value at point ``xp = (x', y', z', ...)`` is evaluated by first + computing the interval indices `i` such that:: + + x[0][i[0]] <= x' < x[0][i[0]+1] + x[1][i[1]] <= y' < x[1][i[1]+1] + ... + + and then computing:: + + S = sum(c[k0-m0-1,...,kn-mn-1,i[0],...,i[n]] + * (xp[0] - x[0][i[0]])**m0 + * ... + * (xp[n] - x[n][i[n]])**mn + for m0 in range(k[0]+1) + ... + for mn in range(k[n]+1)) + + where ``k[j]`` is the degree of the polynomial in dimension j. This + representation is the piecewise multivariate power basis. + + Parameters + ---------- + c : ndarray, shape (k0, ..., kn, m0, ..., mn, ...) + Polynomial coefficients, with polynomial order `kj` and + `mj+1` intervals for each dimension `j`. + x : ndim-tuple of ndarrays, shapes (mj+1,) + Polynomial breakpoints for each dimension. These must be + sorted in increasing order. + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. Default: True. + + Attributes + ---------- + x : tuple of ndarrays + Breakpoints. + c : ndarray + Coefficients of the polynomials. + + Methods + ------- + __call__ + derivative + antiderivative + integrate + integrate_1d + construct_fast + + See also + -------- + PPoly : piecewise polynomials in 1D + + Notes + ----- + High-order polynomials in the power basis can be numerically + unstable. + + """ + + def __init__(self, c, x, extrapolate=None): + self.x = tuple(np.ascontiguousarray(v, dtype=np.float64) for v in x) + self.c = np.asarray(c) + if extrapolate is None: + extrapolate = True + self.extrapolate = bool(extrapolate) + + ndim = len(self.x) + if any(v.ndim != 1 for v in self.x): + raise ValueError("x arrays must all be 1-dimensional") + if any(v.size < 2 for v in self.x): + raise ValueError("x arrays must all contain at least 2 points") + if c.ndim < 2*ndim: + raise ValueError("c must have at least 2*len(x) dimensions") + if any(np.any(v[1:] - v[:-1] < 0) for v in self.x): + raise ValueError("x-coordinates are not in increasing order") + if any(a != b.size - 1 for a, b in zip(c.shape[ndim:2*ndim], self.x)): + raise ValueError("x and c do not agree on the number of intervals") + + dtype = self._get_dtype(self.c.dtype) + self.c = np.ascontiguousarray(self.c, dtype=dtype) + + @classmethod + def construct_fast(cls, c, x, extrapolate=None): + """ + Construct the piecewise polynomial without making checks. + + Takes the same parameters as the constructor. Input arguments + ``c`` and ``x`` must be arrays of the correct shape and type. The + ``c`` array can only be of dtypes float and complex, and ``x`` + array must have dtype float. + + """ + self = object.__new__(cls) + self.c = c + self.x = x + if extrapolate is None: + extrapolate = True + self.extrapolate = extrapolate + return self + + def _get_dtype(self, dtype): + if np.issubdtype(dtype, np.complexfloating) \ + or np.issubdtype(self.c.dtype, np.complexfloating): + return np.complex128 + else: + return np.float64 + + def _ensure_c_contiguous(self): + if not self.c.flags.c_contiguous: + self.c = self.c.copy() + if not isinstance(self.x, tuple): + self.x = tuple(self.x) + + def __call__(self, x, nu=None, extrapolate=None): + """ + Evaluate the piecewise polynomial or its derivative + + Parameters + ---------- + x : array-like + Points to evaluate the interpolant at. + nu : tuple, optional + Orders of derivatives to evaluate. Each must be non-negative. + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. + + Returns + ------- + y : array-like + Interpolated values. Shape is determined by replacing + the interpolation axis in the original array with the shape of x. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals are considered half-open, + ``[a, b)``, except for the last interval which is closed + ``[a, b]``. + + """ + if extrapolate is None: + extrapolate = self.extrapolate + else: + extrapolate = bool(extrapolate) + + ndim = len(self.x) + + x = _ndim_coords_from_arrays(x) + x_shape = x.shape + x = np.ascontiguousarray(x.reshape(-1, x.shape[-1]), dtype=np.float64) + + if nu is None: + nu = np.zeros((ndim,), dtype=np.intc) + else: + nu = np.asarray(nu, dtype=np.intc) + if nu.ndim != 1 or nu.shape[0] != ndim: + raise ValueError("invalid number of derivative orders nu") + + dim1 = prod(self.c.shape[:ndim]) + dim2 = prod(self.c.shape[ndim:2*ndim]) + dim3 = prod(self.c.shape[2*ndim:]) + ks = np.array(self.c.shape[:ndim], dtype=np.intc) + + out = np.empty((x.shape[0], dim3), dtype=self.c.dtype) + self._ensure_c_contiguous() + + _ppoly.evaluate_nd(self.c.reshape(dim1, dim2, dim3), + self.x, + ks, + x, + nu, + bool(extrapolate), + out) + + return out.reshape(x_shape[:-1] + self.c.shape[2*ndim:]) + + def _derivative_inplace(self, nu, axis): + """ + Compute 1-D derivative along a selected dimension in-place + May result to non-contiguous c array. + """ + if nu < 0: + return self._antiderivative_inplace(-nu, axis) + + ndim = len(self.x) + axis = axis % ndim + + # reduce order + if nu == 0: + # noop + return + else: + sl = [slice(None)]*ndim + sl[axis] = slice(None, -nu, None) + c2 = self.c[tuple(sl)] + + if c2.shape[axis] == 0: + # derivative of order 0 is zero + shp = list(c2.shape) + shp[axis] = 1 + c2 = np.zeros(shp, dtype=c2.dtype) + + # multiply by the correct rising factorials + factor = spec.poch(np.arange(c2.shape[axis], 0, -1), nu) + sl = [None]*c2.ndim + sl[axis] = slice(None) + c2 *= factor[tuple(sl)] + + self.c = c2 + + def _antiderivative_inplace(self, nu, axis): + """ + Compute 1-D antiderivative along a selected dimension + May result to non-contiguous c array. + """ + if nu <= 0: + return self._derivative_inplace(-nu, axis) + + ndim = len(self.x) + axis = axis % ndim + + perm = list(range(ndim)) + perm[0], perm[axis] = perm[axis], perm[0] + perm = perm + list(range(ndim, self.c.ndim)) + + c = self.c.transpose(perm) + + c2 = np.zeros((c.shape[0] + nu,) + c.shape[1:], + dtype=c.dtype) + c2[:-nu] = c + + # divide by the correct rising factorials + factor = spec.poch(np.arange(c.shape[0], 0, -1), nu) + c2[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] + + # fix continuity of added degrees of freedom + perm2 = list(range(c2.ndim)) + perm2[1], perm2[ndim+axis] = perm2[ndim+axis], perm2[1] + + c2 = c2.transpose(perm2) + c2 = c2.copy() + _ppoly.fix_continuity(c2.reshape(c2.shape[0], c2.shape[1], -1), + self.x[axis], nu-1) + + c2 = c2.transpose(perm2) + c2 = c2.transpose(perm) + + # Done + self.c = c2 + + def derivative(self, nu): + """ + Construct a new piecewise polynomial representing the derivative. + + Parameters + ---------- + nu : ndim-tuple of int + Order of derivatives to evaluate for each dimension. + If negative, the antiderivative is returned. + + Returns + ------- + pp : NdPPoly + Piecewise polynomial of orders (k[0] - nu[0], ..., k[n] - nu[n]) + representing the derivative of this polynomial. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals in each dimension are + considered half-open, ``[a, b)``, except for the last interval + which is closed ``[a, b]``. + + """ + p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) + + for axis, n in enumerate(nu): + p._derivative_inplace(n, axis) + + p._ensure_c_contiguous() + return p + + def antiderivative(self, nu): + """ + Construct a new piecewise polynomial representing the antiderivative. + + Antiderivative is also the indefinite integral of the function, + and derivative is its inverse operation. + + Parameters + ---------- + nu : ndim-tuple of int + Order of derivatives to evaluate for each dimension. + If negative, the derivative is returned. + + Returns + ------- + pp : PPoly + Piecewise polynomial of order k2 = k + n representing + the antiderivative of this polynomial. + + Notes + ----- + The antiderivative returned by this function is continuous and + continuously differentiable to order n-1, up to floating point + rounding error. + + """ + p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) + + for axis, n in enumerate(nu): + p._antiderivative_inplace(n, axis) + + p._ensure_c_contiguous() + return p + + def integrate_1d(self, a, b, axis, extrapolate=None): + r""" + Compute NdPPoly representation for one dimensional definite integral + + The result is a piecewise polynomial representing the integral: + + .. math:: + + p(y, z, ...) = \int_a^b dx\, p(x, y, z, ...) + + where the dimension integrated over is specified with the + `axis` parameter. + + Parameters + ---------- + a, b : float + Lower and upper bound for integration. + axis : int + Dimension over which to compute the 1-D integrals + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. + + Returns + ------- + ig : NdPPoly or array-like + Definite integral of the piecewise polynomial over [a, b]. + If the polynomial was 1D, an array is returned, + otherwise, an NdPPoly object. + + """ + if extrapolate is None: + extrapolate = self.extrapolate + else: + extrapolate = bool(extrapolate) + + ndim = len(self.x) + axis = int(axis) % ndim + + # reuse 1-D integration routines + c = self.c + swap = list(range(c.ndim)) + swap.insert(0, swap[axis]) + del swap[axis + 1] + swap.insert(1, swap[ndim + axis]) + del swap[ndim + axis + 1] + + c = c.transpose(swap) + p = PPoly.construct_fast(c.reshape(c.shape[0], c.shape[1], -1), + self.x[axis], + extrapolate=extrapolate) + out = p.integrate(a, b, extrapolate=extrapolate) + + # Construct result + if ndim == 1: + return out.reshape(c.shape[2:]) + else: + c = out.reshape(c.shape[2:]) + x = self.x[:axis] + self.x[axis+1:] + return self.construct_fast(c, x, extrapolate=extrapolate) + + def integrate(self, ranges, extrapolate=None): + """ + Compute a definite integral over a piecewise polynomial. + + Parameters + ---------- + ranges : ndim-tuple of 2-tuples float + Sequence of lower and upper bounds for each dimension, + ``[(a[0], b[0]), ..., (a[ndim-1], b[ndim-1])]`` + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. + + Returns + ------- + ig : array_like + Definite integral of the piecewise polynomial over + [a[0], b[0]] x ... x [a[ndim-1], b[ndim-1]] + + """ + + ndim = len(self.x) + + if extrapolate is None: + extrapolate = self.extrapolate + else: + extrapolate = bool(extrapolate) + + if not hasattr(ranges, '__len__') or len(ranges) != ndim: + raise ValueError("Range not a sequence of correct length") + + self._ensure_c_contiguous() + + # Reuse 1D integration routine + c = self.c + for n, (a, b) in enumerate(ranges): + swap = list(range(c.ndim)) + swap.insert(1, swap[ndim - n]) + del swap[ndim - n + 1] + + c = c.transpose(swap) + + p = PPoly.construct_fast(c, self.x[n], extrapolate=extrapolate) + out = p.integrate(a, b, extrapolate=extrapolate) + c = out.reshape(c.shape[2:]) + + return c diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py new file mode 100644 index 0000000000000000000000000000000000000000..51ac566ed5ff1271a46ffafcc04c0e180f2ec3f1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py @@ -0,0 +1,420 @@ +import itertools +import functools +import operator +import numpy as np + +from math import prod + +from . import _bspl # type: ignore[attr-defined] + +import scipy.sparse.linalg as ssl +from scipy.sparse import csr_array + +from ._bsplines import _not_a_knot + +__all__ = ["NdBSpline"] + + +def _get_dtype(dtype): + """Return np.complex128 for complex dtypes, np.float64 otherwise.""" + if np.issubdtype(dtype, np.complexfloating): + return np.complex128 + else: + return np.float64 + + +class NdBSpline: + """Tensor product spline object. + + The value at point ``xp = (x1, x2, ..., xN)`` is evaluated as a linear + combination of products of one-dimensional b-splines in each of the ``N`` + dimensions:: + + c[i1, i2, ..., iN] * B(x1; i1, t1) * B(x2; i2, t2) * ... * B(xN; iN, tN) + + + Here ``B(x; i, t)`` is the ``i``-th b-spline defined by the knot vector + ``t`` evaluated at ``x``. + + Parameters + ---------- + t : tuple of 1D ndarrays + knot vectors in directions 1, 2, ... N, + ``len(t[i]) == n[i] + k + 1`` + c : ndarray, shape (n1, n2, ..., nN, ...) + b-spline coefficients + k : int or length-d tuple of integers + spline degrees. + A single integer is interpreted as having this degree for + all dimensions. + extrapolate : bool, optional + Whether to extrapolate out-of-bounds inputs, or return `nan`. + Default is to extrapolate. + + Attributes + ---------- + t : tuple of ndarrays + Knots vectors. + c : ndarray + Coefficients of the tensor-product spline. + k : tuple of integers + Degrees for each dimension. + extrapolate : bool, optional + Whether to extrapolate or return nans for out-of-bounds inputs. + Defaults to true. + + Methods + ------- + __call__ + design_matrix + + See Also + -------- + BSpline : a one-dimensional B-spline object + NdPPoly : an N-dimensional piecewise tensor product polynomial + + """ + def __init__(self, t, c, k, *, extrapolate=None): + self._k, self._indices_k1d, (self._t, self._len_t) = _preprocess_inputs(k, t) + + if extrapolate is None: + extrapolate = True + self.extrapolate = bool(extrapolate) + + self.c = np.asarray(c) + + ndim = self._t.shape[0] # == len(self.t) + if self.c.ndim < ndim: + raise ValueError(f"Coefficients must be at least {ndim}-dimensional.") + + for d in range(ndim): + td = self.t[d] + kd = self.k[d] + n = td.shape[0] - kd - 1 + + if self.c.shape[d] != n: + raise ValueError(f"Knots, coefficients and degree in dimension" + f" {d} are inconsistent:" + f" got {self.c.shape[d]} coefficients for" + f" {len(td)} knots, need at least {n} for" + f" k={k}.") + + dt = _get_dtype(self.c.dtype) + self.c = np.ascontiguousarray(self.c, dtype=dt) + + @property + def k(self): + return tuple(self._k) + + @property + def t(self): + # repack the knots into a tuple + return tuple(self._t[d, :self._len_t[d]] for d in range(self._t.shape[0])) + + def __call__(self, xi, *, nu=None, extrapolate=None): + """Evaluate the tensor product b-spline at ``xi``. + + Parameters + ---------- + xi : array_like, shape(..., ndim) + The coordinates to evaluate the interpolator at. + This can be a list or tuple of ndim-dimensional points + or an array with the shape (num_points, ndim). + nu : array_like, optional, shape (ndim,) + Orders of derivatives to evaluate. Each must be non-negative. + Defaults to the zeroth derivivative. + extrapolate : bool, optional + Whether to exrapolate based on first and last intervals in each + dimension, or return `nan`. Default is to ``self.extrapolate``. + + Returns + ------- + values : ndarray, shape ``xi.shape[:-1] + self.c.shape[ndim:]`` + Interpolated values at ``xi`` + """ + ndim = self._t.shape[0] # == len(self.t) + + if extrapolate is None: + extrapolate = self.extrapolate + extrapolate = bool(extrapolate) + + if nu is None: + nu = np.zeros((ndim,), dtype=np.intc) + else: + nu = np.asarray(nu, dtype=np.intc) + if nu.ndim != 1 or nu.shape[0] != ndim: + raise ValueError( + f"invalid number of derivative orders {nu = } for " + f"ndim = {len(self.t)}.") + if any(nu < 0): + raise ValueError(f"derivatives must be positive, got {nu = }") + + # prepare xi : shape (..., m1, ..., md) -> (1, m1, ..., md) + xi = np.asarray(xi, dtype=float) + xi_shape = xi.shape + xi = xi.reshape(-1, xi_shape[-1]) + xi = np.ascontiguousarray(xi) + + if xi_shape[-1] != ndim: + raise ValueError(f"Shapes: xi.shape={xi_shape} and ndim={ndim}") + + # complex -> double + was_complex = self.c.dtype.kind == 'c' + cc = self.c + if was_complex and self.c.ndim == ndim: + # make sure that core dimensions are intact, and complex->float + # size doubling only adds a trailing dimension + cc = self.c[..., None] + cc = cc.view(float) + + # prepare the coefficients: flatten the trailing dimensions + c1 = cc.reshape(cc.shape[:ndim] + (-1,)) + c1r = c1.ravel() + + # replacement for np.ravel_multi_index for indexing of `c1`: + _strides_c1 = np.asarray([s // c1.dtype.itemsize + for s in c1.strides], dtype=np.intp) + + num_c_tr = c1.shape[-1] # # of trailing coefficients + out = np.empty(xi.shape[:-1] + (num_c_tr,), dtype=c1.dtype) + + _bspl.evaluate_ndbspline(xi, + self._t, + self._len_t, + self._k, + nu, + extrapolate, + c1r, + num_c_tr, + _strides_c1, + self._indices_k1d, + out,) + out = out.view(self.c.dtype) + return out.reshape(xi_shape[:-1] + self.c.shape[ndim:]) + + @classmethod + def design_matrix(cls, xvals, t, k, extrapolate=True): + """Construct the design matrix as a CSR format sparse array. + + Parameters + ---------- + xvals : ndarray, shape(npts, ndim) + Data points. ``xvals[j, :]`` gives the ``j``-th data point as an + ``ndim``-dimensional array. + t : tuple of 1D ndarrays, length-ndim + Knot vectors in directions 1, 2, ... ndim, + k : int + B-spline degree. + extrapolate : bool, optional + Whether to extrapolate out-of-bounds values of raise a `ValueError` + + Returns + ------- + design_matrix : a CSR array + Each row of the design matrix corresponds to a value in `xvals` and + contains values of b-spline basis elements which are non-zero + at this value. + + """ + xvals = np.asarray(xvals, dtype=float) + ndim = xvals.shape[-1] + if len(t) != ndim: + raise ValueError( + f"Data and knots are inconsistent: len(t) = {len(t)} for " + f" {ndim = }." + ) + + # tabulate the flat indices for iterating over the (k+1)**ndim subarray + k, _indices_k1d, (_t, len_t) = _preprocess_inputs(k, t) + + # Precompute the shape and strides of the 'coefficients array'. + # This would have been the NdBSpline coefficients; in the present context + # this is a helper to compute the indices into the colocation matrix. + c_shape = tuple(len_t[d] - k[d] - 1 for d in range(ndim)) + + # The strides of the coeffs array: the computation is equivalent to + # >>> cstrides = [s // 8 for s in np.empty(c_shape).strides] + cs = c_shape[1:] + (1,) + cstrides = np.cumprod(cs[::-1], dtype=np.intp)[::-1].copy() + + # heavy lifting happens here + data, indices, indptr = _bspl._colloc_nd(xvals, + _t, + len_t, + k, + _indices_k1d, + cstrides) + return csr_array((data, indices, indptr)) + + +def _preprocess_inputs(k, t_tpl): + """Helpers: validate and preprocess NdBSpline inputs. + + Parameters + ---------- + k : int or tuple + Spline orders + t_tpl : tuple or array-likes + Knots. + """ + # 1. Make sure t_tpl is a tuple + if not isinstance(t_tpl, tuple): + raise ValueError(f"Expect `t` to be a tuple of array-likes. " + f"Got {t_tpl} instead." + ) + + # 2. Make ``k`` a tuple of integers + ndim = len(t_tpl) + try: + len(k) + except TypeError: + # make k a tuple + k = (k,)*ndim + + k = np.asarray([operator.index(ki) for ki in k], dtype=np.int32) + + if len(k) != ndim: + raise ValueError(f"len(t) = {len(t_tpl)} != {len(k) = }.") + + # 3. Validate inputs + ndim = len(t_tpl) + for d in range(ndim): + td = np.asarray(t_tpl[d]) + kd = k[d] + n = td.shape[0] - kd - 1 + if kd < 0: + raise ValueError(f"Spline degree in dimension {d} cannot be" + f" negative.") + if td.ndim != 1: + raise ValueError(f"Knot vector in dimension {d} must be" + f" one-dimensional.") + if n < kd + 1: + raise ValueError(f"Need at least {2*kd + 2} knots for degree" + f" {kd} in dimension {d}.") + if (np.diff(td) < 0).any(): + raise ValueError(f"Knots in dimension {d} must be in a" + f" non-decreasing order.") + if len(np.unique(td[kd:n + 1])) < 2: + raise ValueError(f"Need at least two internal knots in" + f" dimension {d}.") + if not np.isfinite(td).all(): + raise ValueError(f"Knots in dimension {d} should not have" + f" nans or infs.") + + # 4. tabulate the flat indices for iterating over the (k+1)**ndim subarray + # non-zero b-spline elements + shape = tuple(kd + 1 for kd in k) + indices = np.unravel_index(np.arange(prod(shape)), shape) + _indices_k1d = np.asarray(indices, dtype=np.intp).T.copy() + + # 5. pack the knots into a single array: + # ([1, 2, 3, 4], [5, 6], (7, 8, 9)) --> + # array([[1, 2, 3, 4], + # [5, 6, nan, nan], + # [7, 8, 9, nan]]) + ndim = len(t_tpl) + len_t = [len(ti) for ti in t_tpl] + _t = np.empty((ndim, max(len_t)), dtype=float) + _t.fill(np.nan) + for d in range(ndim): + _t[d, :len(t_tpl[d])] = t_tpl[d] + len_t = np.asarray(len_t, dtype=np.int32) + + return k, _indices_k1d, (_t, len_t) + + +def _iter_solve(a, b, solver=ssl.gcrotmk, **solver_args): + # work around iterative solvers not accepting multiple r.h.s. + + # also work around a.dtype == float64 and b.dtype == complex128 + # cf https://github.com/scipy/scipy/issues/19644 + if np.issubdtype(b.dtype, np.complexfloating): + real = _iter_solve(a, b.real, solver, **solver_args) + imag = _iter_solve(a, b.imag, solver, **solver_args) + return real + 1j*imag + + if b.ndim == 2 and b.shape[1] !=1: + res = np.empty_like(b) + for j in range(b.shape[1]): + res[:, j], info = solver(a, b[:, j], **solver_args) + if info != 0: + raise ValueError(f"{solver = } returns {info =} for column {j}.") + return res + else: + res, info = solver(a, b, **solver_args) + if info != 0: + raise ValueError(f"{solver = } returns {info = }.") + return res + + +def make_ndbspl(points, values, k=3, *, solver=ssl.gcrotmk, **solver_args): + """Construct an interpolating NdBspline. + + Parameters + ---------- + points : tuple of ndarrays of float, with shapes (m1,), ... (mN,) + The points defining the regular grid in N dimensions. The points in + each dimension (i.e. every element of the `points` tuple) must be + strictly ascending or descending. + values : ndarray of float, shape (m1, ..., mN, ...) + The data on the regular grid in n dimensions. + k : int, optional + The spline degree. Must be odd. Default is cubic, k=3 + solver : a `scipy.sparse.linalg` solver (iterative or direct), optional. + An iterative solver from `scipy.sparse.linalg` or a direct one, + `sparse.sparse.linalg.spsolve`. + Used to solve the sparse linear system + ``design_matrix @ coefficients = rhs`` for the coefficients. + Default is `scipy.sparse.linalg.gcrotmk` + solver_args : dict, optional + Additional arguments for the solver. The call signature is + ``solver(csr_array, rhs_vector, **solver_args)`` + + Returns + ------- + spl : NdBSpline object + + Notes + ----- + Boundary conditions are not-a-knot in all dimensions. + """ + ndim = len(points) + xi_shape = tuple(len(x) for x in points) + + try: + len(k) + except TypeError: + # make k a tuple + k = (k,)*ndim + + for d, point in enumerate(points): + numpts = len(np.atleast_1d(point)) + if numpts <= k[d]: + raise ValueError(f"There are {numpts} points in dimension {d}," + f" but order {k[d]} requires at least " + f" {k[d]+1} points per dimension.") + + t = tuple(_not_a_knot(np.asarray(points[d], dtype=float), k[d]) + for d in range(ndim)) + xvals = np.asarray([xv for xv in itertools.product(*points)], dtype=float) + + # construct the colocation matrix + matr = NdBSpline.design_matrix(xvals, t, k) + + # Solve for the coefficients given `values`. + # Trailing dimensions: first ndim dimensions are data, the rest are batch + # dimensions, so stack `values` into a 2D array for `spsolve` to undestand. + v_shape = values.shape + vals_shape = (prod(v_shape[:ndim]), prod(v_shape[ndim:])) + vals = values.reshape(vals_shape) + + if solver != ssl.spsolve: + solver = functools.partial(_iter_solve, solver=solver) + if "atol" not in solver_args: + # avoid a DeprecationWarning, grumble grumble + solver_args["atol"] = 1e-6 + + coef = solver(matr, vals, **solver_args) + coef = coef.reshape(xi_shape + v_shape[ndim:]) + return NdBSpline(t, coef, k) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py new file mode 100644 index 0000000000000000000000000000000000000000..78fe9d6995141ad238002e0b48feb94017dc272a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py @@ -0,0 +1,332 @@ +""" +Convenience interface to N-D interpolation + +.. versionadded:: 0.9 + +""" +import numpy as np +from ._interpnd import (LinearNDInterpolator, NDInterpolatorBase, + CloughTocher2DInterpolator, _ndim_coords_from_arrays) +from scipy.spatial import cKDTree + +__all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator', + 'CloughTocher2DInterpolator'] + +#------------------------------------------------------------------------------ +# Nearest-neighbor interpolation +#------------------------------------------------------------------------------ + + +class NearestNDInterpolator(NDInterpolatorBase): + """NearestNDInterpolator(x, y). + + Nearest-neighbor interpolator in N > 1 dimensions. + + .. versionadded:: 0.9 + + Methods + ------- + __call__ + + Parameters + ---------- + x : (npoints, ndims) 2-D ndarray of floats + Data point coordinates. + y : (npoints, ) 1-D ndarray of float or complex + Data values. + rescale : boolean, optional + Rescale points to unit cube before performing interpolation. + This is useful if some of the input dimensions have + incommensurable units and differ by many orders of magnitude. + + .. versionadded:: 0.14.0 + tree_options : dict, optional + Options passed to the underlying ``cKDTree``. + + .. versionadded:: 0.17.0 + + See Also + -------- + griddata : + Interpolate unstructured D-D data. + LinearNDInterpolator : + Piecewise linear interpolator in N dimensions. + CloughTocher2DInterpolator : + Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D. + interpn : Interpolation on a regular grid or rectilinear grid. + RegularGridInterpolator : Interpolator on a regular or rectilinear grid + in arbitrary dimensions (`interpn` wraps this + class). + + Notes + ----- + Uses ``scipy.spatial.cKDTree`` + + .. note:: For data on a regular grid use `interpn` instead. + + Examples + -------- + We can interpolate values on a 2D plane: + + >>> from scipy.interpolate import NearestNDInterpolator + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = rng.random(10) - 0.5 + >>> y = rng.random(10) - 0.5 + >>> z = np.hypot(x, y) + >>> X = np.linspace(min(x), max(x)) + >>> Y = np.linspace(min(y), max(y)) + >>> X, Y = np.meshgrid(X, Y) # 2D grid for interpolation + >>> interp = NearestNDInterpolator(list(zip(x, y)), z) + >>> Z = interp(X, Y) + >>> plt.pcolormesh(X, Y, Z, shading='auto') + >>> plt.plot(x, y, "ok", label="input point") + >>> plt.legend() + >>> plt.colorbar() + >>> plt.axis("equal") + >>> plt.show() + + """ + + def __init__(self, x, y, rescale=False, tree_options=None): + NDInterpolatorBase.__init__(self, x, y, rescale=rescale, + need_contiguous=False, + need_values=False) + if tree_options is None: + tree_options = dict() + self.tree = cKDTree(self.points, **tree_options) + self.values = np.asarray(y) + + def __call__(self, *args, **query_options): + """ + Evaluate interpolator at given points. + + Parameters + ---------- + x1, x2, ... xn : array-like of float + Points where to interpolate data at. + x1, x2, ... xn can be array-like of float with broadcastable shape. + or x1 can be array-like of float with shape ``(..., ndim)`` + **query_options + This allows ``eps``, ``p``, ``distance_upper_bound``, and ``workers`` + being passed to the cKDTree's query function to be explicitly set. + See `scipy.spatial.cKDTree.query` for an overview of the different options. + + .. versionadded:: 1.12.0 + + """ + # For the sake of enabling subclassing, NDInterpolatorBase._set_xi performs + # some operations which are not required by NearestNDInterpolator.__call__, + # hence here we operate on xi directly, without calling a parent class function. + xi = _ndim_coords_from_arrays(args, ndim=self.points.shape[1]) + xi = self._check_call_shape(xi) + xi = self._scale_x(xi) + + # We need to handle two important cases: + # (1) the case where xi has trailing dimensions (..., ndim), and + # (2) the case where y has trailing dimensions + # We will first flatten xi to deal with case (1), + # do the computation in flattened array while retaining y's dimensionality, + # and then reshape the interpolated values back to match xi's shape. + + # Flatten xi for the query + xi_flat = xi.reshape(-1, xi.shape[-1]) + original_shape = xi.shape + flattened_shape = xi_flat.shape + + # if distance_upper_bound is set to not be infinite, + # then we need to consider the case where cKDtree + # does not find any points within distance_upper_bound to return. + # It marks those points as having infinte distance, which is what will be used + # below to mask the array and return only the points that were deemed + # to have a close enough neighbor to return something useful. + dist, i = self.tree.query(xi_flat, **query_options) + valid_mask = np.isfinite(dist) + + # create a holder interp_values array and fill with nans. + if self.values.ndim > 1: + interp_shape = flattened_shape[:-1] + self.values.shape[1:] + else: + interp_shape = flattened_shape[:-1] + + if np.issubdtype(self.values.dtype, np.complexfloating): + interp_values = np.full(interp_shape, np.nan, dtype=self.values.dtype) + else: + interp_values = np.full(interp_shape, np.nan) + + interp_values[valid_mask] = self.values[i[valid_mask], ...] + + if self.values.ndim > 1: + new_shape = original_shape[:-1] + self.values.shape[1:] + else: + new_shape = original_shape[:-1] + interp_values = interp_values.reshape(new_shape) + + return interp_values + + +#------------------------------------------------------------------------------ +# Convenience interface function +#------------------------------------------------------------------------------ + + +def griddata(points, values, xi, method='linear', fill_value=np.nan, + rescale=False): + """ + Interpolate unstructured D-D data. + + Parameters + ---------- + points : 2-D ndarray of floats with shape (n, D), or length D tuple of 1-D ndarrays with shape (n,). + Data point coordinates. + values : ndarray of float or complex, shape (n,) + Data values. + xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape. + Points at which to interpolate data. + method : {'linear', 'nearest', 'cubic'}, optional + Method of interpolation. One of + + ``nearest`` + return the value at the data point closest to + the point of interpolation. See `NearestNDInterpolator` for + more details. + + ``linear`` + tessellate the input point set to N-D + simplices, and interpolate linearly on each simplex. See + `LinearNDInterpolator` for more details. + + ``cubic`` (1-D) + return the value determined from a cubic + spline. + + ``cubic`` (2-D) + return the value determined from a + piecewise cubic, continuously differentiable (C1), and + approximately curvature-minimizing polynomial surface. See + `CloughTocher2DInterpolator` for more details. + fill_value : float, optional + Value used to fill in for requested points outside of the + convex hull of the input points. If not provided, then the + default is ``nan``. This option has no effect for the + 'nearest' method. + rescale : bool, optional + Rescale points to unit cube before performing interpolation. + This is useful if some of the input dimensions have + incommensurable units and differ by many orders of magnitude. + + .. versionadded:: 0.14.0 + + Returns + ------- + ndarray + Array of interpolated values. + + See Also + -------- + LinearNDInterpolator : + Piecewise linear interpolator in N dimensions. + NearestNDInterpolator : + Nearest-neighbor interpolator in N dimensions. + CloughTocher2DInterpolator : + Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D. + interpn : Interpolation on a regular grid or rectilinear grid. + RegularGridInterpolator : Interpolator on a regular or rectilinear grid + in arbitrary dimensions (`interpn` wraps this + class). + + Notes + ----- + + .. versionadded:: 0.9 + + .. note:: For data on a regular grid use `interpn` instead. + + Examples + -------- + + Suppose we want to interpolate the 2-D function + + >>> import numpy as np + >>> def func(x, y): + ... return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2 + + on a grid in [0, 1]x[0, 1] + + >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j] + + but we only know its values at 1000 data points: + + >>> rng = np.random.default_rng() + >>> points = rng.random((1000, 2)) + >>> values = func(points[:,0], points[:,1]) + + This can be done with `griddata` -- below we try out all of the + interpolation methods: + + >>> from scipy.interpolate import griddata + >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest') + >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear') + >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic') + + One can see that the exact result is reproduced by all of the + methods to some degree, but for this smooth function the piecewise + cubic interpolant gives the best results: + + >>> import matplotlib.pyplot as plt + >>> plt.subplot(221) + >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower') + >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1) + >>> plt.title('Original') + >>> plt.subplot(222) + >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower') + >>> plt.title('Nearest') + >>> plt.subplot(223) + >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower') + >>> plt.title('Linear') + >>> plt.subplot(224) + >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower') + >>> plt.title('Cubic') + >>> plt.gcf().set_size_inches(6, 6) + >>> plt.show() + + """ # numpy/numpydoc#87 # noqa: E501 + + points = _ndim_coords_from_arrays(points) + + if points.ndim < 2: + ndim = points.ndim + else: + ndim = points.shape[-1] + + if ndim == 1 and method in ('nearest', 'linear', 'cubic'): + from ._interpolate import interp1d + points = points.ravel() + if isinstance(xi, tuple): + if len(xi) != 1: + raise ValueError("invalid number of dimensions in xi") + xi, = xi + # Sort points/values together, necessary as input for interp1d + idx = np.argsort(points) + points = points[idx] + values = values[idx] + if method == 'nearest': + fill_value = 'extrapolate' + ip = interp1d(points, values, kind=method, axis=0, bounds_error=False, + fill_value=fill_value) + return ip(xi) + elif method == 'nearest': + ip = NearestNDInterpolator(points, values, rescale=rescale) + return ip(xi) + elif method == 'linear': + ip = LinearNDInterpolator(points, values, fill_value=fill_value, + rescale=rescale) + return ip(xi) + elif method == 'cubic' and ndim == 2: + ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value, + rescale=rescale) + return ip(xi) + else: + raise ValueError("Unknown interpolation method %r for " + "%d dimensional data" % (method, ndim)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py new file mode 100644 index 0000000000000000000000000000000000000000..387ef11dde5d3ace8a15324058c10fa31899c92c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py @@ -0,0 +1,67 @@ +from numpy import zeros, asarray, eye, poly1d, hstack, r_ +from scipy import linalg + +__all__ = ["pade"] + +def pade(an, m, n=None): + """ + Return Pade approximation to a polynomial as the ratio of two polynomials. + + Parameters + ---------- + an : (N,) array_like + Taylor series coefficients. + m : int + The order of the returned approximating polynomial `q`. + n : int, optional + The order of the returned approximating polynomial `p`. By default, + the order is ``len(an)-1-m``. + + Returns + ------- + p, q : Polynomial class + The Pade approximation of the polynomial defined by `an` is + ``p(x)/q(x)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import pade + >>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0] + >>> p, q = pade(e_exp, 2) + + >>> e_exp.reverse() + >>> e_poly = np.poly1d(e_exp) + + Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)`` + + >>> e_poly(1) + 2.7166666666666668 + + >>> p(1)/q(1) + 2.7179487179487181 + + """ + an = asarray(an) + if n is None: + n = len(an) - 1 - m + if n < 0: + raise ValueError("Order of q must be smaller than len(an)-1.") + if n < 0: + raise ValueError("Order of p must be greater than 0.") + N = m + n + if N > len(an)-1: + raise ValueError("Order of q+p must be smaller than len(an).") + an = an[:N+1] + Akj = eye(N+1, n+1, dtype=an.dtype) + Bkj = zeros((N+1, m), dtype=an.dtype) + for row in range(1, m+1): + Bkj[row,:row] = -(an[:row])[::-1] + for row in range(m+1, N+1): + Bkj[row,:] = -(an[row-m:row])[::-1] + C = hstack((Akj, Bkj)) + pq = linalg.solve(C, an) + p = pq[:n+1] + q = r_[1.0, pq[n+1:]] + return poly1d(p[::-1]), poly1d(q[::-1]) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py new file mode 100644 index 0000000000000000000000000000000000000000..9cec3eb9939abba36505010334911c167797b750 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py @@ -0,0 +1,961 @@ +import warnings + +import numpy as np +from scipy.special import factorial +from scipy._lib._util import (_asarray_validated, float_factorial, check_random_state, + _transition_to_rng) + + +__all__ = ["KroghInterpolator", "krogh_interpolate", + "BarycentricInterpolator", "barycentric_interpolate", + "approximate_taylor_polynomial"] + + +def _isscalar(x): + """Check whether x is if a scalar type, or 0-dim""" + return np.isscalar(x) or hasattr(x, 'shape') and x.shape == () + + +class _Interpolator1D: + """ + Common features in univariate interpolation + + Deal with input data type and interpolation axis rolling. The + actual interpolator can assume the y-data is of shape (n, r) where + `n` is the number of x-points, and `r` the number of variables, + and use self.dtype as the y-data type. + + Attributes + ---------- + _y_axis + Axis along which the interpolation goes in the original array + _y_extra_shape + Additional trailing shape of the input arrays, excluding + the interpolation axis. + dtype + Dtype of the y-data arrays. Can be set via _set_dtype, which + forces it to be float or complex. + + Methods + ------- + __call__ + _prepare_x + _finish_y + _reshape_yi + _set_yi + _set_dtype + _evaluate + + """ + + __slots__ = ('_y_axis', '_y_extra_shape', 'dtype') + + def __init__(self, xi=None, yi=None, axis=None): + self._y_axis = axis + self._y_extra_shape = None + self.dtype = None + if yi is not None: + self._set_yi(yi, xi=xi, axis=axis) + + def __call__(self, x): + """ + Evaluate the interpolant + + Parameters + ---------- + x : array_like + Point or points at which to evaluate the interpolant. + + Returns + ------- + y : array_like + Interpolated values. Shape is determined by replacing + the interpolation axis in the original array with the shape of `x`. + + Notes + ----- + Input values `x` must be convertible to `float` values like `int` + or `float`. + + """ + x, x_shape = self._prepare_x(x) + y = self._evaluate(x) + return self._finish_y(y, x_shape) + + def _evaluate(self, x): + """ + Actually evaluate the value of the interpolator. + """ + raise NotImplementedError() + + def _prepare_x(self, x): + """Reshape input x array to 1-D""" + x = _asarray_validated(x, check_finite=False, as_inexact=True) + x_shape = x.shape + return x.ravel(), x_shape + + def _finish_y(self, y, x_shape): + """Reshape interpolated y back to an N-D array similar to initial y""" + y = y.reshape(x_shape + self._y_extra_shape) + if self._y_axis != 0 and x_shape != (): + nx = len(x_shape) + ny = len(self._y_extra_shape) + s = (list(range(nx, nx + self._y_axis)) + + list(range(nx)) + list(range(nx+self._y_axis, nx+ny))) + y = y.transpose(s) + return y + + def _reshape_yi(self, yi, check=False): + yi = np.moveaxis(np.asarray(yi), self._y_axis, 0) + if check and yi.shape[1:] != self._y_extra_shape: + ok_shape = (f"{self._y_extra_shape[-self._y_axis:]!r} + (N,) + " + f"{self._y_extra_shape[:-self._y_axis]!r}") + raise ValueError(f"Data must be of shape {ok_shape}") + return yi.reshape((yi.shape[0], -1)) + + def _set_yi(self, yi, xi=None, axis=None): + if axis is None: + axis = self._y_axis + if axis is None: + raise ValueError("no interpolation axis specified") + + yi = np.asarray(yi) + + shape = yi.shape + if shape == (): + shape = (1,) + if xi is not None and shape[axis] != len(xi): + raise ValueError("x and y arrays must be equal in length along " + "interpolation axis.") + + self._y_axis = (axis % yi.ndim) + self._y_extra_shape = yi.shape[:self._y_axis] + yi.shape[self._y_axis+1:] + self.dtype = None + self._set_dtype(yi.dtype) + + def _set_dtype(self, dtype, union=False): + if np.issubdtype(dtype, np.complexfloating) \ + or np.issubdtype(self.dtype, np.complexfloating): + self.dtype = np.complex128 + else: + if not union or self.dtype != np.complex128: + self.dtype = np.float64 + + +class _Interpolator1DWithDerivatives(_Interpolator1D): + def derivatives(self, x, der=None): + """ + Evaluate several derivatives of the polynomial at the point `x` + + Produce an array of derivatives evaluated at the point `x`. + + Parameters + ---------- + x : array_like + Point or points at which to evaluate the derivatives + der : int or list or None, optional + How many derivatives to evaluate, or None for all potentially + nonzero derivatives (that is, a number equal to the number + of points), or a list of derivatives to evaluate. This number + includes the function value as the '0th' derivative. + + Returns + ------- + d : ndarray + Array with derivatives; ``d[j]`` contains the jth derivative. + Shape of ``d[j]`` is determined by replacing the interpolation + axis in the original array with the shape of `x`. + + Examples + -------- + >>> from scipy.interpolate import KroghInterpolator + >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives(0) + array([1.0,2.0,3.0]) + >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives([0,0]) + array([[1.0,1.0], + [2.0,2.0], + [3.0,3.0]]) + + """ + x, x_shape = self._prepare_x(x) + y = self._evaluate_derivatives(x, der) + + y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape) + if self._y_axis != 0 and x_shape != (): + nx = len(x_shape) + ny = len(self._y_extra_shape) + s = ([0] + list(range(nx+1, nx + self._y_axis+1)) + + list(range(1, nx+1)) + + list(range(nx+1+self._y_axis, nx+ny+1))) + y = y.transpose(s) + return y + + def derivative(self, x, der=1): + """ + Evaluate a single derivative of the polynomial at the point `x`. + + Parameters + ---------- + x : array_like + Point or points at which to evaluate the derivatives + + der : integer, optional + Which derivative to evaluate (default: first derivative). + This number includes the function value as 0th derivative. + + Returns + ------- + d : ndarray + Derivative interpolated at the x-points. Shape of `d` is + determined by replacing the interpolation axis in the + original array with the shape of `x`. + + Notes + ----- + This may be computed by evaluating all derivatives up to the desired + one (using self.derivatives()) and then discarding the rest. + + """ + x, x_shape = self._prepare_x(x) + y = self._evaluate_derivatives(x, der+1) + return self._finish_y(y[der], x_shape) + + def _evaluate_derivatives(self, x, der=None): + """ + Actually evaluate the derivatives. + + Parameters + ---------- + x : array_like + 1D array of points at which to evaluate the derivatives + der : integer, optional + The number of derivatives to evaluate, from 'order 0' (der=1) + to order der-1. If omitted, return all possibly-non-zero + derivatives, ie 0 to order n-1. + + Returns + ------- + d : ndarray + Array of shape ``(der, x.size, self.yi.shape[1])`` containing + the derivatives from 0 to der-1 + """ + raise NotImplementedError() + + +class KroghInterpolator(_Interpolator1DWithDerivatives): + """ + Interpolating polynomial for a set of points. + + The polynomial passes through all the pairs ``(xi, yi)``. One may + additionally specify a number of derivatives at each point `xi`; + this is done by repeating the value `xi` and specifying the + derivatives as successive `yi` values. + + Allows evaluation of the polynomial and all its derivatives. + For reasons of numerical stability, this function does not compute + the coefficients of the polynomial, although they can be obtained + by evaluating all the derivatives. + + Parameters + ---------- + xi : array_like, shape (npoints, ) + Known x-coordinates. Must be sorted in increasing order. + yi : array_like, shape (..., npoints, ...) + Known y-coordinates. When an xi occurs two or more times in + a row, the corresponding yi's represent derivative values. The length of `yi` + along the interpolation axis must be equal to the length of `xi`. Use the + `axis` parameter to select the correct axis. + axis : int, optional + Axis in the `yi` array corresponding to the x-coordinate values. Defaults to + ``axis=0``. + + Notes + ----- + Be aware that the algorithms implemented here are not necessarily + the most numerically stable known. Moreover, even in a world of + exact computation, unless the x coordinates are chosen very + carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice - + polynomial interpolation itself is a very ill-conditioned process + due to the Runge phenomenon. In general, even with well-chosen + x values, degrees higher than about thirty cause problems with + numerical instability in this code. + + Based on [1]_. + + References + ---------- + .. [1] Krogh, "Efficient Algorithms for Polynomial Interpolation + and Numerical Differentiation", 1970. + + Examples + -------- + To produce a polynomial that is zero at 0 and 1 and has + derivative 2 at 0, call + + >>> from scipy.interpolate import KroghInterpolator + >>> KroghInterpolator([0,0,1],[0,2,0]) + + This constructs the quadratic :math:`2x^2-2x`. The derivative condition + is indicated by the repeated zero in the `xi` array; the corresponding + yi values are 0, the function value, and 2, the derivative value. + + For another example, given `xi`, `yi`, and a derivative `ypi` for each + point, appropriate arrays can be constructed as: + + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> xi = np.linspace(0, 1, 5) + >>> yi, ypi = rng.random((2, 5)) + >>> xi_k, yi_k = np.repeat(xi, 2), np.ravel(np.dstack((yi,ypi))) + >>> KroghInterpolator(xi_k, yi_k) + + To produce a vector-valued polynomial, supply a higher-dimensional + array for `yi`: + + >>> KroghInterpolator([0,1],[[2,3],[4,5]]) + + This constructs a linear polynomial giving (2,3) at 0 and (4,5) at 1. + + """ + + def __init__(self, xi, yi, axis=0): + super().__init__(xi, yi, axis) + + self.xi = np.asarray(xi) + self.yi = self._reshape_yi(yi) + self.n, self.r = self.yi.shape + + if (deg := self.xi.size) > 30: + warnings.warn(f"{deg} degrees provided, degrees higher than about" + " thirty cause problems with numerical instability " + "with 'KroghInterpolator'", stacklevel=2) + + c = np.zeros((self.n+1, self.r), dtype=self.dtype) + c[0] = self.yi[0] + Vk = np.zeros((self.n, self.r), dtype=self.dtype) + for k in range(1, self.n): + s = 0 + while s <= k and xi[k-s] == xi[k]: + s += 1 + s -= 1 + Vk[0] = self.yi[k]/float_factorial(s) + for i in range(k-s): + if xi[i] == xi[k]: + raise ValueError("Elements of `xi` can't be equal.") + if s == 0: + Vk[i+1] = (c[i]-Vk[i])/(xi[i]-xi[k]) + else: + Vk[i+1] = (Vk[i+1]-Vk[i])/(xi[i]-xi[k]) + c[k] = Vk[k-s] + self.c = c + + def _evaluate(self, x): + pi = 1 + p = np.zeros((len(x), self.r), dtype=self.dtype) + p += self.c[0,np.newaxis,:] + for k in range(1, self.n): + w = x - self.xi[k-1] + pi = w*pi + p += pi[:,np.newaxis] * self.c[k] + return p + + def _evaluate_derivatives(self, x, der=None): + n = self.n + r = self.r + + if der is None: + der = self.n + + pi = np.zeros((n, len(x))) + w = np.zeros((n, len(x))) + pi[0] = 1 + p = np.zeros((len(x), self.r), dtype=self.dtype) + p += self.c[0, np.newaxis, :] + + for k in range(1, n): + w[k-1] = x - self.xi[k-1] + pi[k] = w[k-1] * pi[k-1] + p += pi[k, :, np.newaxis] * self.c[k] + + cn = np.zeros((max(der, n+1), len(x), r), dtype=self.dtype) + cn[:n+1, :, :] += self.c[:n+1, np.newaxis, :] + cn[0] = p + for k in range(1, n): + for i in range(1, n-k+1): + pi[i] = w[k+i-1]*pi[i-1] + pi[i] + cn[k] = cn[k] + pi[i, :, np.newaxis]*cn[k+i] + cn[k] *= float_factorial(k) + + cn[n, :, :] = 0 + return cn[:der] + + +def krogh_interpolate(xi, yi, x, der=0, axis=0): + """ + Convenience function for polynomial interpolation. + + See `KroghInterpolator` for more details. + + Parameters + ---------- + xi : array_like + Interpolation points (known x-coordinates). + yi : array_like + Known y-coordinates, of shape ``(xi.size, R)``. Interpreted as + vectors of length R, or scalars if R=1. + x : array_like + Point or points at which to evaluate the derivatives. + der : int or list or None, optional + How many derivatives to evaluate, or None for all potentially + nonzero derivatives (that is, a number equal to the number + of points), or a list of derivatives to evaluate. This number + includes the function value as the '0th' derivative. + axis : int, optional + Axis in the `yi` array corresponding to the x-coordinate values. + + Returns + ------- + d : ndarray + If the interpolator's values are R-D then the + returned array will be the number of derivatives by N by R. + If `x` is a scalar, the middle dimension will be dropped; if + the `yi` are scalars then the last dimension will be dropped. + + See Also + -------- + KroghInterpolator : Krogh interpolator + + Notes + ----- + Construction of the interpolating polynomial is a relatively expensive + process. If you want to evaluate it repeatedly consider using the class + KroghInterpolator (which is what this function uses). + + Examples + -------- + We can interpolate 2D observed data using Krogh interpolation: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import krogh_interpolate + >>> x_observed = np.linspace(0.0, 10.0, 11) + >>> y_observed = np.sin(x_observed) + >>> x = np.linspace(min(x_observed), max(x_observed), num=100) + >>> y = krogh_interpolate(x_observed, y_observed, x) + >>> plt.plot(x_observed, y_observed, "o", label="observation") + >>> plt.plot(x, y, label="krogh interpolation") + >>> plt.legend() + >>> plt.show() + """ + + P = KroghInterpolator(xi, yi, axis=axis) + if der == 0: + return P(x) + elif _isscalar(der): + return P.derivative(x, der=der) + else: + return P.derivatives(x, der=np.amax(der)+1)[der] + + +def approximate_taylor_polynomial(f,x,degree,scale,order=None): + """ + Estimate the Taylor polynomial of f at x by polynomial fitting. + + Parameters + ---------- + f : callable + The function whose Taylor polynomial is sought. Should accept + a vector of `x` values. + x : scalar + The point at which the polynomial is to be evaluated. + degree : int + The degree of the Taylor polynomial + scale : scalar + The width of the interval to use to evaluate the Taylor polynomial. + Function values spread over a range this wide are used to fit the + polynomial. Must be chosen carefully. + order : int or None, optional + The order of the polynomial to be used in the fitting; `f` will be + evaluated ``order+1`` times. If None, use `degree`. + + Returns + ------- + p : poly1d instance + The Taylor polynomial (translated to the origin, so that + for example p(0)=f(x)). + + Notes + ----- + The appropriate choice of "scale" is a trade-off; too large and the + function differs from its Taylor polynomial too much to get a good + answer, too small and round-off errors overwhelm the higher-order terms. + The algorithm used becomes numerically unstable around order 30 even + under ideal circumstances. + + Choosing order somewhat larger than degree may improve the higher-order + terms. + + Examples + -------- + We can calculate Taylor approximation polynomials of sin function with + various degrees: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import approximate_taylor_polynomial + >>> x = np.linspace(-10.0, 10.0, num=100) + >>> plt.plot(x, np.sin(x), label="sin curve") + >>> for degree in np.arange(1, 15, step=2): + ... sin_taylor = approximate_taylor_polynomial(np.sin, 0, degree, 1, + ... order=degree + 2) + ... plt.plot(x, sin_taylor(x), label=f"degree={degree}") + >>> plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', + ... borderaxespad=0.0, shadow=True) + >>> plt.tight_layout() + >>> plt.axis([-10, 10, -10, 10]) + >>> plt.show() + + """ + if order is None: + order = degree + + n = order+1 + # Choose n points that cluster near the endpoints of the interval in + # a way that avoids the Runge phenomenon. Ensure, by including the + # endpoint or not as appropriate, that one point always falls at x + # exactly. + xs = scale*np.cos(np.linspace(0,np.pi,n,endpoint=n % 1)) + x + + P = KroghInterpolator(xs, f(xs)) + d = P.derivatives(x,der=degree+1) + + return np.poly1d((d/factorial(np.arange(degree+1)))[::-1]) + + +class BarycentricInterpolator(_Interpolator1DWithDerivatives): + r"""Interpolating polynomial for a set of points. + + Constructs a polynomial that passes through a given set of points. + Allows evaluation of the polynomial and all its derivatives, + efficient changing of the y-values to be interpolated, + and updating by adding more x- and y-values. + + For reasons of numerical stability, this function does not compute + the coefficients of the polynomial. + + The values `yi` need to be provided before the function is + evaluated, but none of the preprocessing depends on them, so rapid + updates are possible. + + Parameters + ---------- + xi : array_like, shape (npoints, ) + 1-D array of x coordinates of the points the polynomial + should pass through + yi : array_like, shape (..., npoints, ...), optional + N-D array of y coordinates of the points the polynomial should pass through. + If None, the y values will be supplied later via the `set_y` method. + The length of `yi` along the interpolation axis must be equal to the length + of `xi`. Use the ``axis`` parameter to select correct axis. + axis : int, optional + Axis in the yi array corresponding to the x-coordinate values. Defaults + to ``axis=0``. + wi : array_like, optional + The barycentric weights for the chosen interpolation points `xi`. + If absent or None, the weights will be computed from `xi` (default). + This allows for the reuse of the weights `wi` if several interpolants + are being calculated using the same nodes `xi`, without re-computation. + rng : {None, int, `numpy.random.Generator`}, optional + If `rng` is passed by keyword, types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + If `rng` is already a ``Generator`` instance, then the provided instance is + used. Specify `rng` for repeatable interpolation. + + If this argument `random_state` is passed by keyword, + legacy behavior for the argument `random_state` applies: + + - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState` + singleton is used. + - If `random_state` is an int, a new ``RandomState`` instance is used, + seeded with `random_state`. + - If `random_state` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + .. versionchanged:: 1.15.0 + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator` this keyword was changed from `random_state` to `rng`. + For an interim period, both keywords will continue to work (only specify + one of them). After the interim period using the `random_state` keyword will emit + warnings. The behavior of the `random_state` and `rng` keywords is outlined above. + + Notes + ----- + This class uses a "barycentric interpolation" method that treats + the problem as a special case of rational function interpolation. + This algorithm is quite stable, numerically, but even in a world of + exact computation, unless the x coordinates are chosen very + carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice - + polynomial interpolation itself is a very ill-conditioned process + due to the Runge phenomenon. + + Based on Berrut and Trefethen 2004, "Barycentric Lagrange Interpolation". + + Examples + -------- + To produce a quintic barycentric interpolant approximating the function + :math:`\sin x`, and its first four derivatives, using six randomly-spaced + nodes in :math:`(0, \frac{\pi}{2})`: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import BarycentricInterpolator + >>> rng = np.random.default_rng() + >>> xi = rng.random(6) * np.pi/2 + >>> f, f_d1, f_d2, f_d3, f_d4 = np.sin, np.cos, lambda x: -np.sin(x), lambda x: -np.cos(x), np.sin + >>> P = BarycentricInterpolator(xi, f(xi), random_state=rng) + >>> fig, axs = plt.subplots(5, 1, sharex=True, layout='constrained', figsize=(7,10)) + >>> x = np.linspace(0, np.pi, 100) + >>> axs[0].plot(x, P(x), 'r:', x, f(x), 'k--', xi, f(xi), 'xk') + >>> axs[1].plot(x, P.derivative(x), 'r:', x, f_d1(x), 'k--', xi, f_d1(xi), 'xk') + >>> axs[2].plot(x, P.derivative(x, 2), 'r:', x, f_d2(x), 'k--', xi, f_d2(xi), 'xk') + >>> axs[3].plot(x, P.derivative(x, 3), 'r:', x, f_d3(x), 'k--', xi, f_d3(xi), 'xk') + >>> axs[4].plot(x, P.derivative(x, 4), 'r:', x, f_d4(x), 'k--', xi, f_d4(xi), 'xk') + >>> axs[0].set_xlim(0, np.pi) + >>> axs[4].set_xlabel(r"$x$") + >>> axs[4].set_xticks([i * np.pi / 4 for i in range(5)], + ... ["0", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$", r"$\frac{3\pi}{4}$", r"$\pi$"]) + >>> axs[0].set_ylabel("$f(x)$") + >>> axs[1].set_ylabel("$f'(x)$") + >>> axs[2].set_ylabel("$f''(x)$") + >>> axs[3].set_ylabel("$f^{(3)}(x)$") + >>> axs[4].set_ylabel("$f^{(4)}(x)$") + >>> labels = ['Interpolation nodes', 'True function $f$', 'Barycentric interpolation'] + >>> axs[0].legend(axs[0].get_lines()[::-1], labels, bbox_to_anchor=(0., 1.02, 1., .102), + ... loc='lower left', ncols=3, mode="expand", borderaxespad=0., frameon=False) + >>> plt.show() + """ # numpy/numpydoc#87 # noqa: E501 + + @_transition_to_rng("random_state", replace_doc=False) + def __init__(self, xi, yi=None, axis=0, *, wi=None, rng=None): + super().__init__(xi, yi, axis) + + rng = check_random_state(rng) + + self.xi = np.asarray(xi, dtype=np.float64) + self.set_yi(yi) + self.n = len(self.xi) + + # cache derivative object to avoid re-computing the weights with every call. + self._diff_cij = None + + if wi is not None: + self.wi = wi + else: + # See page 510 of Berrut and Trefethen 2004 for an explanation of the + # capacity scaling and the suggestion of using a random permutation of + # the input factors. + # At the moment, the permutation is not performed for xi that are + # appended later through the add_xi interface. It's not clear to me how + # to implement that and it seems that most situations that require + # these numerical stability improvements will be able to provide all + # the points to the constructor. + self._inv_capacity = 4.0 / (np.max(self.xi) - np.min(self.xi)) + permute = rng.permutation(self.n, ) + inv_permute = np.zeros(self.n, dtype=np.int32) + inv_permute[permute] = np.arange(self.n) + self.wi = np.zeros(self.n) + + for i in range(self.n): + dist = self._inv_capacity * (self.xi[i] - self.xi[permute]) + dist[inv_permute[i]] = 1.0 + prod = np.prod(dist) + if prod == 0.0: + raise ValueError("Interpolation points xi must be" + " distinct.") + self.wi[i] = 1.0 / prod + + def set_yi(self, yi, axis=None): + """ + Update the y values to be interpolated + + The barycentric interpolation algorithm requires the calculation + of weights, but these depend only on the `xi`. The `yi` can be changed + at any time. + + Parameters + ---------- + yi : array_like + The y-coordinates of the points the polynomial will pass through. + If None, the y values must be supplied later. + axis : int, optional + Axis in the `yi` array corresponding to the x-coordinate values. + + """ + if yi is None: + self.yi = None + return + self._set_yi(yi, xi=self.xi, axis=axis) + self.yi = self._reshape_yi(yi) + self.n, self.r = self.yi.shape + self._diff_baryint = None + + def add_xi(self, xi, yi=None): + """ + Add more x values to the set to be interpolated + + The barycentric interpolation algorithm allows easy updating by + adding more points for the polynomial to pass through. + + Parameters + ---------- + xi : array_like + The x coordinates of the points that the polynomial should pass + through. + yi : array_like, optional + The y coordinates of the points the polynomial should pass through. + Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is + vector-valued. + If `yi` is not given, the y values will be supplied later. `yi` + should be given if and only if the interpolator has y values + specified. + + Notes + ----- + The new points added by `add_xi` are not randomly permuted + so there is potential for numerical instability, + especially for a large number of points. If this + happens, please reconstruct interpolation from scratch instead. + """ + if yi is not None: + if self.yi is None: + raise ValueError("No previous yi value to update!") + yi = self._reshape_yi(yi, check=True) + self.yi = np.vstack((self.yi,yi)) + else: + if self.yi is not None: + raise ValueError("No update to yi provided!") + old_n = self.n + self.xi = np.concatenate((self.xi,xi)) + self.n = len(self.xi) + self.wi **= -1 + old_wi = self.wi + self.wi = np.zeros(self.n) + self.wi[:old_n] = old_wi + for j in range(old_n, self.n): + self.wi[:j] *= self._inv_capacity * (self.xi[j]-self.xi[:j]) + self.wi[j] = np.multiply.reduce( + self._inv_capacity * (self.xi[:j]-self.xi[j]) + ) + self.wi **= -1 + self._diff_cij = None + self._diff_baryint = None + + def __call__(self, x): + """Evaluate the interpolating polynomial at the points x + + Parameters + ---------- + x : array_like + Point or points at which to evaluate the interpolant. + + Returns + ------- + y : array_like + Interpolated values. Shape is determined by replacing + the interpolation axis in the original array with the shape of `x`. + + Notes + ----- + Currently the code computes an outer product between `x` and the + weights, that is, it constructs an intermediate array of size + ``(N, len(x))``, where N is the degree of the polynomial. + """ + return _Interpolator1D.__call__(self, x) + + def _evaluate(self, x): + if x.size == 0: + p = np.zeros((0, self.r), dtype=self.dtype) + else: + c = x[..., np.newaxis] - self.xi + z = c == 0 + c[z] = 1 + c = self.wi / c + with np.errstate(divide='ignore'): + p = np.dot(c, self.yi) / np.sum(c, axis=-1)[..., np.newaxis] + # Now fix where x==some xi + r = np.nonzero(z) + if len(r) == 1: # evaluation at a scalar + if len(r[0]) > 0: # equals one of the points + p = self.yi[r[0][0]] + else: + p[r[:-1]] = self.yi[r[-1]] + return p + + def derivative(self, x, der=1): + """ + Evaluate a single derivative of the polynomial at the point x. + + Parameters + ---------- + x : array_like + Point or points at which to evaluate the derivatives + der : integer, optional + Which derivative to evaluate (default: first derivative). + This number includes the function value as 0th derivative. + + Returns + ------- + d : ndarray + Derivative interpolated at the x-points. Shape of `d` is + determined by replacing the interpolation axis in the + original array with the shape of `x`. + """ + x, x_shape = self._prepare_x(x) + y = self._evaluate_derivatives(x, der+1, all_lower=False) + return self._finish_y(y, x_shape) + + def _evaluate_derivatives(self, x, der=None, all_lower=True): + # NB: der here is not the order of the highest derivative; + # instead, it is the size of the derivatives matrix that + # would be returned with all_lower=True, including the + # '0th' derivative (the undifferentiated function). + # E.g. to evaluate the 5th derivative alone, call + # _evaluate_derivatives(x, der=6, all_lower=False). + + if (not all_lower) and (x.size == 0 or self.r == 0): + return np.zeros((0, self.r), dtype=self.dtype) + + if (not all_lower) and der == 1: + return self._evaluate(x) + + if (not all_lower) and (der > self.n): + return np.zeros((len(x), self.r), dtype=self.dtype) + + if der is None: + der = self.n + + if all_lower and (x.size == 0 or self.r == 0): + return np.zeros((der, len(x), self.r), dtype=self.dtype) + + if self._diff_cij is None: + # c[i,j] = xi[i] - xi[j] + c = self.xi[:, np.newaxis] - self.xi + + # avoid division by 0 (diagonal entries are so far zero by construction) + np.fill_diagonal(c, 1) + + # c[i,j] = (w[j] / w[i]) / (xi[i] - xi[j]) (equation 9.4) + c = self.wi/ (c * self.wi[..., np.newaxis]) + + # fill in correct diagonal entries: each column sums to 0 + np.fill_diagonal(c, 0) + + # calculate diagonal + # c[j,j] = -sum_{i != j} c[i,j] (equation 9.5) + d = -c.sum(axis=1) + # c[i,j] = l_j(x_i) + np.fill_diagonal(c, d) + + self._diff_cij = c + + if self._diff_baryint is None: + # initialise and cache derivative interpolator and cijs; + # reuse weights wi (which depend only on interpolation points xi), + # to avoid unnecessary re-computation + self._diff_baryint = BarycentricInterpolator(xi=self.xi, + yi=self._diff_cij @ self.yi, + wi=self.wi) + self._diff_baryint._diff_cij = self._diff_cij + + if all_lower: + # assemble matrix of derivatives from order 0 to order der-1, + # in the format required by _Interpolator1DWithDerivatives. + cn = np.zeros((der, len(x), self.r), dtype=self.dtype) + for d in range(der): + cn[d, :, :] = self._evaluate_derivatives(x, d+1, all_lower=False) + return cn + + # recursively evaluate only the derivative requested + return self._diff_baryint._evaluate_derivatives(x, der-1, all_lower=False) + + +def barycentric_interpolate(xi, yi, x, axis=0, *, der=0, rng=None): + """ + Convenience function for polynomial interpolation. + + Constructs a polynomial that passes through a given set of points, + then evaluates the polynomial. For reasons of numerical stability, + this function does not compute the coefficients of the polynomial. + + This function uses a "barycentric interpolation" method that treats + the problem as a special case of rational function interpolation. + This algorithm is quite stable, numerically, but even in a world of + exact computation, unless the `x` coordinates are chosen very + carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice - + polynomial interpolation itself is a very ill-conditioned process + due to the Runge phenomenon. + + Parameters + ---------- + xi : array_like + 1-D array of x coordinates of the points the polynomial should + pass through + yi : array_like + The y coordinates of the points the polynomial should pass through. + x : scalar or array_like + Point or points at which to evaluate the interpolant. + axis : int, optional + Axis in the `yi` array corresponding to the x-coordinate values. + der : int or list or None, optional + How many derivatives to evaluate, or None for all potentially + nonzero derivatives (that is, a number equal to the number + of points), or a list of derivatives to evaluate. This number + includes the function value as the '0th' derivative. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + y : scalar or array_like + Interpolated values. Shape is determined by replacing + the interpolation axis in the original array with the shape of `x`. + + See Also + -------- + BarycentricInterpolator : Barycentric interpolator + + Notes + ----- + Construction of the interpolation weights is a relatively slow process. + If you want to call this many times with the same xi (but possibly + varying yi or x) you should use the class `BarycentricInterpolator`. + This is what this function uses internally. + + Examples + -------- + We can interpolate 2D observed data using barycentric interpolation: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import barycentric_interpolate + >>> x_observed = np.linspace(0.0, 10.0, 11) + >>> y_observed = np.sin(x_observed) + >>> x = np.linspace(min(x_observed), max(x_observed), num=100) + >>> y = barycentric_interpolate(x_observed, y_observed, x) + >>> plt.plot(x_observed, y_observed, "o", label="observation") + >>> plt.plot(x, y, label="barycentric interpolation") + >>> plt.legend() + >>> plt.show() + + """ + P = BarycentricInterpolator(xi, yi, axis=axis, rng=rng) + if der == 0: + return P(x) + elif _isscalar(der): + return P.derivative(x, der=der) + else: + return P.derivatives(x, der=np.amax(der)+1)[der] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py new file mode 100644 index 0000000000000000000000000000000000000000..ed52230dd1cce678e56ca4427e10bafd07e501c0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py @@ -0,0 +1,290 @@ +"""rbf - Radial basis functions for interpolation/smoothing scattered N-D data. + +Written by John Travers , February 2007 +Based closely on Matlab code by Alex Chirokov +Additional, large, improvements by Robert Hetland +Some additional alterations by Travis Oliphant +Interpolation with multi-dimensional target domain by Josua Sassen + +Permission to use, modify, and distribute this software is given under the +terms of the SciPy (BSD style) license. See LICENSE.txt that came with +this distribution for specifics. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + +Copyright (c) 2006-2007, Robert Hetland +Copyright (c) 2007, John Travers + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of Robert Hetland nor the names of any + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" +import numpy as np + +from scipy import linalg +from scipy.special import xlogy +from scipy.spatial.distance import cdist, pdist, squareform + +__all__ = ['Rbf'] + + +class Rbf: + """ + Rbf(*args, **kwargs) + + A class for radial basis function interpolation of functions from + N-D scattered data to an M-D domain. + + .. legacy:: class + + `Rbf` is legacy code, for new usage please use `RBFInterpolator` + instead. + + Parameters + ---------- + *args : arrays + x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes + and d is the array of values at the nodes + function : str or callable, optional + The radial basis function, based on the radius, r, given by the norm + (default is Euclidean distance); the default is 'multiquadric':: + + 'multiquadric': sqrt((r/self.epsilon)**2 + 1) + 'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1) + 'gaussian': exp(-(r/self.epsilon)**2) + 'linear': r + 'cubic': r**3 + 'quintic': r**5 + 'thin_plate': r**2 * log(r) + + If callable, then it must take 2 arguments (self, r). The epsilon + parameter will be available as self.epsilon. Other keyword + arguments passed in will be available as well. + + epsilon : float, optional + Adjustable constant for gaussian or multiquadrics functions + - defaults to approximate average distance between nodes (which is + a good start). + smooth : float, optional + Values greater than zero increase the smoothness of the + approximation. 0 is for interpolation (default), the function will + always go through the nodal points in this case. + norm : str, callable, optional + A function that returns the 'distance' between two points, with + inputs as arrays of positions (x, y, z, ...), and an output as an + array of distance. E.g., the default: 'euclidean', such that the result + is a matrix of the distances from each point in ``x1`` to each point in + ``x2``. For more options, see documentation of + `scipy.spatial.distances.cdist`. + mode : str, optional + Mode of the interpolation, can be '1-D' (default) or 'N-D'. When it is + '1-D' the data `d` will be considered as 1-D and flattened + internally. When it is 'N-D' the data `d` is assumed to be an array of + shape (n_samples, m), where m is the dimension of the target domain. + + + Attributes + ---------- + N : int + The number of data points (as determined by the input arrays). + di : ndarray + The 1-D array of data values at each of the data coordinates `xi`. + xi : ndarray + The 2-D array of data coordinates. + function : str or callable + The radial basis function. See description under Parameters. + epsilon : float + Parameter used by gaussian or multiquadrics functions. See Parameters. + smooth : float + Smoothing parameter. See description under Parameters. + norm : str or callable + The distance function. See description under Parameters. + mode : str + Mode of the interpolation. See description under Parameters. + nodes : ndarray + A 1-D array of node values for the interpolation. + A : internal property, do not use + + See Also + -------- + RBFInterpolator + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import Rbf + >>> rng = np.random.default_rng() + >>> x, y, z, d = rng.random((4, 50)) + >>> rbfi = Rbf(x, y, z, d) # radial basis function interpolator instance + >>> xi = yi = zi = np.linspace(0, 1, 20) + >>> di = rbfi(xi, yi, zi) # interpolated values + >>> di.shape + (20,) + + """ + # Available radial basis functions that can be selected as strings; + # they all start with _h_ (self._init_function relies on that) + def _h_multiquadric(self, r): + return np.sqrt((1.0/self.epsilon*r)**2 + 1) + + def _h_inverse_multiquadric(self, r): + return 1.0/np.sqrt((1.0/self.epsilon*r)**2 + 1) + + def _h_gaussian(self, r): + return np.exp(-(1.0/self.epsilon*r)**2) + + def _h_linear(self, r): + return r + + def _h_cubic(self, r): + return r**3 + + def _h_quintic(self, r): + return r**5 + + def _h_thin_plate(self, r): + return xlogy(r**2, r) + + # Setup self._function and do smoke test on initial r + def _init_function(self, r): + if isinstance(self.function, str): + self.function = self.function.lower() + _mapped = {'inverse': 'inverse_multiquadric', + 'inverse multiquadric': 'inverse_multiquadric', + 'thin-plate': 'thin_plate'} + if self.function in _mapped: + self.function = _mapped[self.function] + + func_name = "_h_" + self.function + if hasattr(self, func_name): + self._function = getattr(self, func_name) + else: + functionlist = [x[3:] for x in dir(self) + if x.startswith('_h_')] + raise ValueError("function must be a callable or one of " + + ", ".join(functionlist)) + self._function = getattr(self, "_h_"+self.function) + elif callable(self.function): + allow_one = False + if hasattr(self.function, 'func_code') or \ + hasattr(self.function, '__code__'): + val = self.function + allow_one = True + elif hasattr(self.function, "__call__"): + val = self.function.__call__.__func__ + else: + raise ValueError("Cannot determine number of arguments to " + "function") + + argcount = val.__code__.co_argcount + if allow_one and argcount == 1: + self._function = self.function + elif argcount == 2: + self._function = self.function.__get__(self, Rbf) + else: + raise ValueError("Function argument must take 1 or 2 " + "arguments.") + + a0 = self._function(r) + if a0.shape != r.shape: + raise ValueError("Callable must take array and return array of " + "the same shape") + return a0 + + def __init__(self, *args, **kwargs): + # `args` can be a variable number of arrays; we flatten them and store + # them as a single 2-D array `xi` of shape (n_args-1, array_size), + # plus a 1-D array `di` for the values. + # All arrays must have the same number of elements + self.xi = np.asarray([np.asarray(a, dtype=np.float64).flatten() + for a in args[:-1]]) + self.N = self.xi.shape[-1] + + self.mode = kwargs.pop('mode', '1-D') + + if self.mode == '1-D': + self.di = np.asarray(args[-1]).flatten() + self._target_dim = 1 + elif self.mode == 'N-D': + self.di = np.asarray(args[-1]) + self._target_dim = self.di.shape[-1] + else: + raise ValueError("Mode has to be 1-D or N-D.") + + if not all([x.size == self.di.shape[0] for x in self.xi]): + raise ValueError("All arrays must be equal length.") + + self.norm = kwargs.pop('norm', 'euclidean') + self.epsilon = kwargs.pop('epsilon', None) + if self.epsilon is None: + # default epsilon is the "the average distance between nodes" based + # on a bounding hypercube + ximax = np.amax(self.xi, axis=1) + ximin = np.amin(self.xi, axis=1) + edges = ximax - ximin + edges = edges[np.nonzero(edges)] + self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size) + + self.smooth = kwargs.pop('smooth', 0.0) + self.function = kwargs.pop('function', 'multiquadric') + + # attach anything left in kwargs to self for use by any user-callable + # function or to save on the object returned. + for item, value in kwargs.items(): + setattr(self, item, value) + + # Compute weights + if self._target_dim > 1: # If we have more than one target dimension, + # we first factorize the matrix + self.nodes = np.zeros((self.N, self._target_dim), dtype=self.di.dtype) + lu, piv = linalg.lu_factor(self.A) + for i in range(self._target_dim): + self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i]) + else: + self.nodes = linalg.solve(self.A, self.di) + + @property + def A(self): + # this only exists for backwards compatibility: self.A was available + # and, at least technically, public. + r = squareform(pdist(self.xi.T, self.norm)) # Pairwise norm + return self._init_function(r) - np.eye(self.N)*self.smooth + + def _call_norm(self, x1, x2): + return cdist(x1.T, x2.T, self.norm) + + def __call__(self, *args): + args = [np.asarray(x) for x in args] + if not all([x.shape == y.shape for x in args for y in args]): + raise ValueError("Array lengths must be equal") + if self._target_dim > 1: + shp = args[0].shape + (self._target_dim,) + else: + shp = args[0].shape + xa = np.asarray([a.flatten() for a in args], dtype=np.float64) + r = self._call_norm(xa, self.xi) + return np.dot(self._function(r), self.nodes).reshape(shp) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py new file mode 100644 index 0000000000000000000000000000000000000000..6690e6ccf7d5499db10efffb0ef1c0139a90d2ba --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py @@ -0,0 +1,550 @@ +"""Module for RBF interpolation.""" +import warnings +from itertools import combinations_with_replacement + +import numpy as np +from numpy.linalg import LinAlgError +from scipy.spatial import KDTree +from scipy.special import comb +from scipy.linalg.lapack import dgesv # type: ignore[attr-defined] + +from ._rbfinterp_pythran import (_build_system, + _build_evaluation_coefficients, + _polynomial_matrix) + + +__all__ = ["RBFInterpolator"] + + +# These RBFs are implemented. +_AVAILABLE = { + "linear", + "thin_plate_spline", + "cubic", + "quintic", + "multiquadric", + "inverse_multiquadric", + "inverse_quadratic", + "gaussian" + } + + +# The shape parameter does not need to be specified when using these RBFs. +_SCALE_INVARIANT = {"linear", "thin_plate_spline", "cubic", "quintic"} + + +# For RBFs that are conditionally positive definite of order m, the interpolant +# should include polynomial terms with degree >= m - 1. Define the minimum +# degrees here. These values are from Chapter 8 of Fasshauer's "Meshfree +# Approximation Methods with MATLAB". The RBFs that are not in this dictionary +# are positive definite and do not need polynomial terms. +_NAME_TO_MIN_DEGREE = { + "multiquadric": 0, + "linear": 0, + "thin_plate_spline": 1, + "cubic": 1, + "quintic": 2 + } + + +def _monomial_powers(ndim, degree): + """Return the powers for each monomial in a polynomial. + + Parameters + ---------- + ndim : int + Number of variables in the polynomial. + degree : int + Degree of the polynomial. + + Returns + ------- + (nmonos, ndim) int ndarray + Array where each row contains the powers for each variable in a + monomial. + + """ + nmonos = comb(degree + ndim, ndim, exact=True) + out = np.zeros((nmonos, ndim), dtype=np.dtype("long")) + count = 0 + for deg in range(degree + 1): + for mono in combinations_with_replacement(range(ndim), deg): + # `mono` is a tuple of variables in the current monomial with + # multiplicity indicating power (e.g., (0, 1, 1) represents x*y**2) + for var in mono: + out[count, var] += 1 + + count += 1 + + return out + + +def _build_and_solve_system(y, d, smoothing, kernel, epsilon, powers): + """Build and solve the RBF interpolation system of equations. + + Parameters + ---------- + y : (P, N) float ndarray + Data point coordinates. + d : (P, S) float ndarray + Data values at `y`. + smoothing : (P,) float ndarray + Smoothing parameter for each data point. + kernel : str + Name of the RBF. + epsilon : float + Shape parameter. + powers : (R, N) int ndarray + The exponents for each monomial in the polynomial. + + Returns + ------- + coeffs : (P + R, S) float ndarray + Coefficients for each RBF and monomial. + shift : (N,) float ndarray + Domain shift used to create the polynomial matrix. + scale : (N,) float ndarray + Domain scaling used to create the polynomial matrix. + + """ + lhs, rhs, shift, scale = _build_system( + y, d, smoothing, kernel, epsilon, powers + ) + _, _, coeffs, info = dgesv(lhs, rhs, overwrite_a=True, overwrite_b=True) + if info < 0: + raise ValueError(f"The {-info}-th argument had an illegal value.") + elif info > 0: + msg = "Singular matrix." + nmonos = powers.shape[0] + if nmonos > 0: + pmat = _polynomial_matrix((y - shift)/scale, powers) + rank = np.linalg.matrix_rank(pmat) + if rank < nmonos: + msg = ( + "Singular matrix. The matrix of monomials evaluated at " + "the data point coordinates does not have full column " + f"rank ({rank}/{nmonos})." + ) + + raise LinAlgError(msg) + + return shift, scale, coeffs + + +class RBFInterpolator: + """Radial basis function (RBF) interpolation in N dimensions. + + Parameters + ---------- + y : (npoints, ndims) array_like + 2-D array of data point coordinates. + d : (npoints, ...) array_like + N-D array of data values at `y`. The length of `d` along the first + axis must be equal to the length of `y`. Unlike some interpolators, the + interpolation axis cannot be changed. + neighbors : int, optional + If specified, the value of the interpolant at each evaluation point + will be computed using only this many nearest data points. All the data + points are used by default. + smoothing : float or (npoints, ) array_like, optional + Smoothing parameter. The interpolant perfectly fits the data when this + is set to 0. For large values, the interpolant approaches a least + squares fit of a polynomial with the specified degree. Default is 0. + kernel : str, optional + Type of RBF. This should be one of + + - 'linear' : ``-r`` + - 'thin_plate_spline' : ``r**2 * log(r)`` + - 'cubic' : ``r**3`` + - 'quintic' : ``-r**5`` + - 'multiquadric' : ``-sqrt(1 + r**2)`` + - 'inverse_multiquadric' : ``1/sqrt(1 + r**2)`` + - 'inverse_quadratic' : ``1/(1 + r**2)`` + - 'gaussian' : ``exp(-r**2)`` + + Default is 'thin_plate_spline'. + epsilon : float, optional + Shape parameter that scales the input to the RBF. If `kernel` is + 'linear', 'thin_plate_spline', 'cubic', or 'quintic', this defaults to + 1 and can be ignored because it has the same effect as scaling the + smoothing parameter. Otherwise, this must be specified. + degree : int, optional + Degree of the added polynomial. For some RBFs the interpolant may not + be well-posed if the polynomial degree is too small. Those RBFs and + their corresponding minimum degrees are + + - 'multiquadric' : 0 + - 'linear' : 0 + - 'thin_plate_spline' : 1 + - 'cubic' : 1 + - 'quintic' : 2 + + The default value is the minimum degree for `kernel` or 0 if there is + no minimum degree. Set this to -1 for no added polynomial. + + Notes + ----- + An RBF is a scalar valued function in N-dimensional space whose value at + :math:`x` can be expressed in terms of :math:`r=||x - c||`, where :math:`c` + is the center of the RBF. + + An RBF interpolant for the vector of data values :math:`d`, which are from + locations :math:`y`, is a linear combination of RBFs centered at :math:`y` + plus a polynomial with a specified degree. The RBF interpolant is written + as + + .. math:: + f(x) = K(x, y) a + P(x) b, + + where :math:`K(x, y)` is a matrix of RBFs with centers at :math:`y` + evaluated at the points :math:`x`, and :math:`P(x)` is a matrix of + monomials, which span polynomials with the specified degree, evaluated at + :math:`x`. The coefficients :math:`a` and :math:`b` are the solution to the + linear equations + + .. math:: + (K(y, y) + \\lambda I) a + P(y) b = d + + and + + .. math:: + P(y)^T a = 0, + + where :math:`\\lambda` is a non-negative smoothing parameter that controls + how well we want to fit the data. The data are fit exactly when the + smoothing parameter is 0. + + The above system is uniquely solvable if the following requirements are + met: + + - :math:`P(y)` must have full column rank. :math:`P(y)` always has full + column rank when `degree` is -1 or 0. When `degree` is 1, + :math:`P(y)` has full column rank if the data point locations are not + all collinear (N=2), coplanar (N=3), etc. + - If `kernel` is 'multiquadric', 'linear', 'thin_plate_spline', + 'cubic', or 'quintic', then `degree` must not be lower than the + minimum value listed above. + - If `smoothing` is 0, then each data point location must be distinct. + + When using an RBF that is not scale invariant ('multiquadric', + 'inverse_multiquadric', 'inverse_quadratic', or 'gaussian'), an appropriate + shape parameter must be chosen (e.g., through cross validation). Smaller + values for the shape parameter correspond to wider RBFs. The problem can + become ill-conditioned or singular when the shape parameter is too small. + + The memory required to solve for the RBF interpolation coefficients + increases quadratically with the number of data points, which can become + impractical when interpolating more than about a thousand data points. + To overcome memory limitations for large interpolation problems, the + `neighbors` argument can be specified to compute an RBF interpolant for + each evaluation point using only the nearest data points. + + .. versionadded:: 1.7.0 + + See Also + -------- + NearestNDInterpolator + LinearNDInterpolator + CloughTocher2DInterpolator + + References + ---------- + .. [1] Fasshauer, G., 2007. Meshfree Approximation Methods with Matlab. + World Scientific Publishing Co. + + .. [2] http://amadeus.math.iit.edu/~fass/603_ch3.pdf + + .. [3] Wahba, G., 1990. Spline Models for Observational Data. SIAM. + + .. [4] http://pages.stat.wisc.edu/~wahba/stat860public/lect/lect8/lect8.pdf + + Examples + -------- + Demonstrate interpolating scattered data to a grid in 2-D. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import RBFInterpolator + >>> from scipy.stats.qmc import Halton + + >>> rng = np.random.default_rng() + >>> xobs = 2*Halton(2, seed=rng).random(100) - 1 + >>> yobs = np.sum(xobs, axis=1)*np.exp(-6*np.sum(xobs**2, axis=1)) + + >>> xgrid = np.mgrid[-1:1:50j, -1:1:50j] + >>> xflat = xgrid.reshape(2, -1).T + >>> yflat = RBFInterpolator(xobs, yobs)(xflat) + >>> ygrid = yflat.reshape(50, 50) + + >>> fig, ax = plt.subplots() + >>> ax.pcolormesh(*xgrid, ygrid, vmin=-0.25, vmax=0.25, shading='gouraud') + >>> p = ax.scatter(*xobs.T, c=yobs, s=50, ec='k', vmin=-0.25, vmax=0.25) + >>> fig.colorbar(p) + >>> plt.show() + + """ + + def __init__(self, y, d, + neighbors=None, + smoothing=0.0, + kernel="thin_plate_spline", + epsilon=None, + degree=None): + y = np.asarray(y, dtype=float, order="C") + if y.ndim != 2: + raise ValueError("`y` must be a 2-dimensional array.") + + ny, ndim = y.shape + + d_dtype = complex if np.iscomplexobj(d) else float + d = np.asarray(d, dtype=d_dtype, order="C") + if d.shape[0] != ny: + raise ValueError( + f"Expected the first axis of `d` to have length {ny}." + ) + + d_shape = d.shape[1:] + d = d.reshape((ny, -1)) + # If `d` is complex, convert it to a float array with twice as many + # columns. Otherwise, the LHS matrix would need to be converted to + # complex and take up 2x more memory than necessary. + d = d.view(float) + + if np.isscalar(smoothing): + smoothing = np.full(ny, smoothing, dtype=float) + else: + smoothing = np.asarray(smoothing, dtype=float, order="C") + if smoothing.shape != (ny,): + raise ValueError( + "Expected `smoothing` to be a scalar or have shape " + f"({ny},)." + ) + + kernel = kernel.lower() + if kernel not in _AVAILABLE: + raise ValueError(f"`kernel` must be one of {_AVAILABLE}.") + + if epsilon is None: + if kernel in _SCALE_INVARIANT: + epsilon = 1.0 + else: + raise ValueError( + "`epsilon` must be specified if `kernel` is not one of " + f"{_SCALE_INVARIANT}." + ) + else: + epsilon = float(epsilon) + + min_degree = _NAME_TO_MIN_DEGREE.get(kernel, -1) + if degree is None: + degree = max(min_degree, 0) + else: + degree = int(degree) + if degree < -1: + raise ValueError("`degree` must be at least -1.") + elif -1 < degree < min_degree: + warnings.warn( + f"`degree` should not be below {min_degree} except -1 " + f"when `kernel` is '{kernel}'." + f"The interpolant may not be uniquely " + f"solvable, and the smoothing parameter may have an " + f"unintuitive effect.", + UserWarning, stacklevel=2 + ) + + if neighbors is None: + nobs = ny + else: + # Make sure the number of nearest neighbors used for interpolation + # does not exceed the number of observations. + neighbors = int(min(neighbors, ny)) + nobs = neighbors + + powers = _monomial_powers(ndim, degree) + # The polynomial matrix must have full column rank in order for the + # interpolant to be well-posed, which is not possible if there are + # fewer observations than monomials. + if powers.shape[0] > nobs: + raise ValueError( + f"At least {powers.shape[0]} data points are required when " + f"`degree` is {degree} and the number of dimensions is {ndim}." + ) + + if neighbors is None: + shift, scale, coeffs = _build_and_solve_system( + y, d, smoothing, kernel, epsilon, powers + ) + + # Make these attributes private since they do not always exist. + self._shift = shift + self._scale = scale + self._coeffs = coeffs + + else: + self._tree = KDTree(y) + + self.y = y + self.d = d + self.d_shape = d_shape + self.d_dtype = d_dtype + self.neighbors = neighbors + self.smoothing = smoothing + self.kernel = kernel + self.epsilon = epsilon + self.powers = powers + + def _chunk_evaluator( + self, + x, + y, + shift, + scale, + coeffs, + memory_budget=1000000 + ): + """ + Evaluate the interpolation while controlling memory consumption. + We chunk the input if we need more memory than specified. + + Parameters + ---------- + x : (Q, N) float ndarray + array of points on which to evaluate + y: (P, N) float ndarray + array of points on which we know function values + shift: (N, ) ndarray + Domain shift used to create the polynomial matrix. + scale : (N,) float ndarray + Domain scaling used to create the polynomial matrix. + coeffs: (P+R, S) float ndarray + Coefficients in front of basis functions + memory_budget: int + Total amount of memory (in units of sizeof(float)) we wish + to devote for storing the array of coefficients for + interpolated points. If we need more memory than that, we + chunk the input. + + Returns + ------- + (Q, S) float ndarray + Interpolated array + """ + nx, ndim = x.shape + if self.neighbors is None: + nnei = len(y) + else: + nnei = self.neighbors + # in each chunk we consume the same space we already occupy + chunksize = memory_budget // (self.powers.shape[0] + nnei) + 1 + if chunksize <= nx: + out = np.empty((nx, self.d.shape[1]), dtype=float) + for i in range(0, nx, chunksize): + vec = _build_evaluation_coefficients( + x[i:i + chunksize, :], + y, + self.kernel, + self.epsilon, + self.powers, + shift, + scale) + out[i:i + chunksize, :] = np.dot(vec, coeffs) + else: + vec = _build_evaluation_coefficients( + x, + y, + self.kernel, + self.epsilon, + self.powers, + shift, + scale) + out = np.dot(vec, coeffs) + return out + + def __call__(self, x): + """Evaluate the interpolant at `x`. + + Parameters + ---------- + x : (Q, N) array_like + Evaluation point coordinates. + + Returns + ------- + (Q, ...) ndarray + Values of the interpolant at `x`. + + """ + x = np.asarray(x, dtype=float, order="C") + if x.ndim != 2: + raise ValueError("`x` must be a 2-dimensional array.") + + nx, ndim = x.shape + if ndim != self.y.shape[1]: + raise ValueError("Expected the second axis of `x` to have length " + f"{self.y.shape[1]}.") + + # Our memory budget for storing RBF coefficients is + # based on how many floats in memory we already occupy + # If this number is below 1e6 we just use 1e6 + # This memory budget is used to decide how we chunk + # the inputs + memory_budget = max(x.size + self.y.size + self.d.size, 1000000) + + if self.neighbors is None: + out = self._chunk_evaluator( + x, + self.y, + self._shift, + self._scale, + self._coeffs, + memory_budget=memory_budget) + else: + # Get the indices of the k nearest observation points to each + # evaluation point. + _, yindices = self._tree.query(x, self.neighbors) + if self.neighbors == 1: + # `KDTree` squeezes the output when neighbors=1. + yindices = yindices[:, None] + + # Multiple evaluation points may have the same neighborhood of + # observation points. Make the neighborhoods unique so that we only + # compute the interpolation coefficients once for each + # neighborhood. + yindices = np.sort(yindices, axis=1) + yindices, inv = np.unique(yindices, return_inverse=True, axis=0) + inv = np.reshape(inv, (-1,)) # flatten, we need 1-D indices + # `inv` tells us which neighborhood will be used by each evaluation + # point. Now we find which evaluation points will be using each + # neighborhood. + xindices = [[] for _ in range(len(yindices))] + for i, j in enumerate(inv): + xindices[j].append(i) + + out = np.empty((nx, self.d.shape[1]), dtype=float) + for xidx, yidx in zip(xindices, yindices): + # `yidx` are the indices of the observations in this + # neighborhood. `xidx` are the indices of the evaluation points + # that are using this neighborhood. + xnbr = x[xidx] + ynbr = self.y[yidx] + dnbr = self.d[yidx] + snbr = self.smoothing[yidx] + shift, scale, coeffs = _build_and_solve_system( + ynbr, + dnbr, + snbr, + self.kernel, + self.epsilon, + self.powers, + ) + out[xidx] = self._chunk_evaluator( + xnbr, + ynbr, + shift, + scale, + coeffs, + memory_budget=memory_budget) + + out = out.view(self.d_dtype) + out = out.reshape((nx, ) + self.d_shape) + return out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py new file mode 100644 index 0000000000000000000000000000000000000000..8e20200568ed961849b5510e8626cdbe6e5b9643 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py @@ -0,0 +1,759 @@ +__all__ = ['RegularGridInterpolator', 'interpn'] + +import itertools + +import numpy as np + +import scipy.sparse.linalg as ssl + +from ._interpnd import _ndim_coords_from_arrays +from ._cubic import PchipInterpolator +from ._rgi_cython import evaluate_linear_2d, find_indices +from ._bsplines import make_interp_spline +from ._fitpack2 import RectBivariateSpline +from ._ndbspline import make_ndbspl + + +def _check_points(points): + descending_dimensions = [] + grid = [] + for i, p in enumerate(points): + # early make points float + # see https://github.com/scipy/scipy/pull/17230 + p = np.asarray(p, dtype=float) + if not np.all(p[1:] > p[:-1]): + if np.all(p[1:] < p[:-1]): + # input is descending, so make it ascending + descending_dimensions.append(i) + p = np.flip(p) + else: + raise ValueError( + "The points in dimension %d must be strictly " + "ascending or descending" % i) + # see https://github.com/scipy/scipy/issues/17716 + p = np.ascontiguousarray(p) + grid.append(p) + return tuple(grid), tuple(descending_dimensions) + + +def _check_dimensionality(points, values): + if len(points) > values.ndim: + raise ValueError("There are %d point arrays, but values has %d " + "dimensions" % (len(points), values.ndim)) + for i, p in enumerate(points): + if not np.asarray(p).ndim == 1: + raise ValueError("The points in dimension %d must be " + "1-dimensional" % i) + if not values.shape[i] == len(p): + raise ValueError("There are %d points and %d values in " + "dimension %d" % (len(p), values.shape[i], i)) + + +class RegularGridInterpolator: + """ + Interpolator on a regular or rectilinear grid in arbitrary dimensions. + + The data must be defined on a rectilinear grid; that is, a rectangular + grid with even or uneven spacing. Linear, nearest-neighbor, spline + interpolations are supported. After setting up the interpolator object, + the interpolation method may be chosen at each evaluation. + + Parameters + ---------- + points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) + The points defining the regular grid in n dimensions. The points in + each dimension (i.e. every elements of the points tuple) must be + strictly ascending or descending. + + values : array_like, shape (m1, ..., mn, ...) + The data on the regular grid in n dimensions. Complex data is + accepted. + + method : str, optional + The method of interpolation to perform. Supported are "linear", + "nearest", "slinear", "cubic", "quintic" and "pchip". This + parameter will become the default for the object's ``__call__`` + method. Default is "linear". + + bounds_error : bool, optional + If True, when interpolated values are requested outside of the + domain of the input data, a ValueError is raised. + If False, then `fill_value` is used. + Default is True. + + fill_value : float or None, optional + The value to use for points outside of the interpolation domain. + If None, values outside the domain are extrapolated. + Default is ``np.nan``. + + solver : callable, optional + Only used for methods "slinear", "cubic" and "quintic". + Sparse linear algebra solver for construction of the NdBSpline instance. + Default is the iterative solver `scipy.sparse.linalg.gcrotmk`. + + .. versionadded:: 1.13 + + solver_args: dict, optional + Additional arguments to pass to `solver`, if any. + + .. versionadded:: 1.13 + + Methods + ------- + __call__ + + Attributes + ---------- + grid : tuple of ndarrays + The points defining the regular grid in n dimensions. + This tuple defines the full grid via + ``np.meshgrid(*grid, indexing='ij')`` + values : ndarray + Data values at the grid. + method : str + Interpolation method. + fill_value : float or ``None`` + Use this value for out-of-bounds arguments to `__call__`. + bounds_error : bool + If ``True``, out-of-bounds argument raise a ``ValueError``. + + Notes + ----- + Contrary to `LinearNDInterpolator` and `NearestNDInterpolator`, this class + avoids expensive triangulation of the input data by taking advantage of the + regular grid structure. + + In other words, this class assumes that the data is defined on a + *rectilinear* grid. + + .. versionadded:: 0.14 + + The 'slinear'(k=1), 'cubic'(k=3), and 'quintic'(k=5) methods are + tensor-product spline interpolators, where `k` is the spline degree, + If any dimension has fewer points than `k` + 1, an error will be raised. + + .. versionadded:: 1.9 + + If the input data is such that dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + **Choosing a solver for spline methods** + + Spline methods, "slinear", "cubic" and "quintic" involve solving a + large sparse linear system at instantiation time. Depending on data, + the default solver may or may not be adequate. When it is not, you may + need to experiment with an optional `solver` argument, where you may + choose between the direct solver (`scipy.sparse.linalg.spsolve`) or + iterative solvers from `scipy.sparse.linalg`. You may need to supply + additional parameters via the optional `solver_args` parameter (for instance, + you may supply the starting value or target tolerance). See the + `scipy.sparse.linalg` documentation for the full list of available options. + + Alternatively, you may instead use the legacy methods, "slinear_legacy", + "cubic_legacy" and "quintic_legacy". These methods allow faster construction + but evaluations will be much slower. + + Examples + -------- + **Evaluate a function on the points of a 3-D grid** + + As a first example, we evaluate a simple example function on the points of + a 3-D grid: + + >>> from scipy.interpolate import RegularGridInterpolator + >>> import numpy as np + >>> def f(x, y, z): + ... return 2 * x**3 + 3 * y**2 - z + >>> x = np.linspace(1, 4, 11) + >>> y = np.linspace(4, 7, 22) + >>> z = np.linspace(7, 9, 33) + >>> xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True) + >>> data = f(xg, yg, zg) + + ``data`` is now a 3-D array with ``data[i, j, k] = f(x[i], y[j], z[k])``. + Next, define an interpolating function from this data: + + >>> interp = RegularGridInterpolator((x, y, z), data) + + Evaluate the interpolating function at the two points + ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``: + + >>> pts = np.array([[2.1, 6.2, 8.3], + ... [3.3, 5.2, 7.1]]) + >>> interp(pts) + array([ 125.80469388, 146.30069388]) + + which is indeed a close approximation to + + >>> f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1) + (125.54200000000002, 145.894) + + **Interpolate and extrapolate a 2D dataset** + + As a second example, we interpolate and extrapolate a 2D data set: + + >>> x, y = np.array([-2, 0, 4]), np.array([-2, 0, 2, 5]) + >>> def ff(x, y): + ... return x**2 + y**2 + + >>> xg, yg = np.meshgrid(x, y, indexing='ij') + >>> data = ff(xg, yg) + >>> interp = RegularGridInterpolator((x, y), data, + ... bounds_error=False, fill_value=None) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax = fig.add_subplot(projection='3d') + >>> ax.scatter(xg.ravel(), yg.ravel(), data.ravel(), + ... s=60, c='k', label='data') + + Evaluate and plot the interpolator on a finer grid + + >>> xx = np.linspace(-4, 9, 31) + >>> yy = np.linspace(-4, 9, 31) + >>> X, Y = np.meshgrid(xx, yy, indexing='ij') + + >>> # interpolator + >>> ax.plot_wireframe(X, Y, interp((X, Y)), rstride=3, cstride=3, + ... alpha=0.4, color='m', label='linear interp') + + >>> # ground truth + >>> ax.plot_wireframe(X, Y, ff(X, Y), rstride=3, cstride=3, + ... alpha=0.4, label='ground truth') + >>> plt.legend() + >>> plt.show() + + Other examples are given + :ref:`in the tutorial `. + + See Also + -------- + NearestNDInterpolator : Nearest neighbor interpolator on *unstructured* + data in N dimensions + + LinearNDInterpolator : Piecewise linear interpolator on *unstructured* data + in N dimensions + + interpn : a convenience function which wraps `RegularGridInterpolator` + + scipy.ndimage.map_coordinates : interpolation on grids with equal spacing + (suitable for e.g., N-D image resampling) + + References + ---------- + .. [1] Python package *regulargrid* by Johannes Buchner, see + https://pypi.python.org/pypi/regulargrid/ + .. [2] Wikipedia, "Trilinear interpolation", + https://en.wikipedia.org/wiki/Trilinear_interpolation + .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear + and multilinear table interpolation in many dimensions." MATH. + COMPUT. 50.181 (1988): 189-196. + https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf + :doi:`10.1090/S0025-5718-1988-0917826-0` + + """ + # this class is based on code originally programmed by Johannes Buchner, + # see https://github.com/JohannesBuchner/regulargrid + + _SPLINE_DEGREE_MAP = {"slinear": 1, "cubic": 3, "quintic": 5, 'pchip': 3, + "slinear_legacy": 1, "cubic_legacy": 3, "quintic_legacy": 5,} + _SPLINE_METHODS_recursive = {"slinear_legacy", "cubic_legacy", + "quintic_legacy", "pchip"} + _SPLINE_METHODS_ndbspl = {"slinear", "cubic", "quintic"} + _SPLINE_METHODS = list(_SPLINE_DEGREE_MAP.keys()) + _ALL_METHODS = ["linear", "nearest"] + _SPLINE_METHODS + + def __init__(self, points, values, method="linear", bounds_error=True, + fill_value=np.nan, *, solver=None, solver_args=None): + if method not in self._ALL_METHODS: + raise ValueError(f"Method '{method}' is not defined") + elif method in self._SPLINE_METHODS: + self._validate_grid_dimensions(points, method) + self.method = method + self._spline = None + self.bounds_error = bounds_error + self.grid, self._descending_dimensions = _check_points(points) + self.values = self._check_values(values) + self._check_dimensionality(self.grid, self.values) + self.fill_value = self._check_fill_value(self.values, fill_value) + if self._descending_dimensions: + self.values = np.flip(values, axis=self._descending_dimensions) + if self.method == "pchip" and np.iscomplexobj(self.values): + msg = ("`PchipInterpolator` only works with real values. If you are trying " + "to use the real components of the passed array, use `np.real` on " + "the array before passing to `RegularGridInterpolator`.") + raise ValueError(msg) + if method in self._SPLINE_METHODS_ndbspl: + if solver_args is None: + solver_args = {} + self._spline = self._construct_spline(method, solver, **solver_args) + else: + if solver is not None or solver_args: + raise ValueError( + f"{method =} does not accept the 'solver' argument. Got " + f" {solver = } and with arguments {solver_args}." + ) + + def _construct_spline(self, method, solver=None, **solver_args): + if solver is None: + solver = ssl.gcrotmk + spl = make_ndbspl( + self.grid, self.values, self._SPLINE_DEGREE_MAP[method], + solver=solver, **solver_args + ) + return spl + + def _check_dimensionality(self, grid, values): + _check_dimensionality(grid, values) + + def _check_points(self, points): + return _check_points(points) + + def _check_values(self, values): + if not hasattr(values, 'ndim'): + # allow reasonable duck-typed values + values = np.asarray(values) + + if hasattr(values, 'dtype') and hasattr(values, 'astype'): + if not np.issubdtype(values.dtype, np.inexact): + values = values.astype(float) + + return values + + def _check_fill_value(self, values, fill_value): + if fill_value is not None: + fill_value_dtype = np.asarray(fill_value).dtype + if (hasattr(values, 'dtype') and not + np.can_cast(fill_value_dtype, values.dtype, + casting='same_kind')): + raise ValueError("fill_value must be either 'None' or " + "of a type compatible with values") + return fill_value + + def __call__(self, xi, method=None, *, nu=None): + """ + Interpolation at coordinates. + + Parameters + ---------- + xi : ndarray of shape (..., ndim) + The coordinates to evaluate the interpolator at. + + method : str, optional + The method of interpolation to perform. Supported are "linear", + "nearest", "slinear", "cubic", "quintic" and "pchip". Default is + the method chosen when the interpolator was created. + + nu : sequence of ints, length ndim, optional + If not None, the orders of the derivatives to evaluate. + Each entry must be non-negative. + Only allowed for methods "slinear", "cubic" and "quintic". + + .. versionadded:: 1.13 + + Returns + ------- + values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] + Interpolated values at `xi`. See notes for behaviour when + ``xi.ndim == 1``. + + Notes + ----- + In the case that ``xi.ndim == 1`` a new axis is inserted into + the 0 position of the returned array, values_x, so its shape is + instead ``(1,) + values.shape[ndim:]``. + + Examples + -------- + Here we define a nearest-neighbor interpolator of a simple function + + >>> import numpy as np + >>> x, y = np.array([0, 1, 2]), np.array([1, 3, 7]) + >>> def f(x, y): + ... return x**2 + y**2 + >>> data = f(*np.meshgrid(x, y, indexing='ij', sparse=True)) + >>> from scipy.interpolate import RegularGridInterpolator + >>> interp = RegularGridInterpolator((x, y), data, method='nearest') + + By construction, the interpolator uses the nearest-neighbor + interpolation + + >>> interp([[1.5, 1.3], [0.3, 4.5]]) + array([2., 9.]) + + We can however evaluate the linear interpolant by overriding the + `method` parameter + + >>> interp([[1.5, 1.3], [0.3, 4.5]], method='linear') + array([ 4.7, 24.3]) + """ + _spline = self._spline + method = self.method if method is None else method + is_method_changed = self.method != method + if method not in self._ALL_METHODS: + raise ValueError(f"Method '{method}' is not defined") + if is_method_changed and method in self._SPLINE_METHODS_ndbspl: + _spline = self._construct_spline(method) + + if nu is not None and method not in self._SPLINE_METHODS_ndbspl: + raise ValueError( + f"Can only compute derivatives for methods " + f"{self._SPLINE_METHODS_ndbspl}, got {method =}." + ) + + xi, xi_shape, ndim, nans, out_of_bounds = self._prepare_xi(xi) + + if method == "linear": + indices, norm_distances = self._find_indices(xi.T) + if (ndim == 2 and hasattr(self.values, 'dtype') and + self.values.ndim == 2 and self.values.flags.writeable and + self.values.dtype in (np.float64, np.complex128) and + self.values.dtype.byteorder == '='): + # until cython supports const fused types, the fast path + # cannot support non-writeable values + # a fast path + out = np.empty(indices.shape[1], dtype=self.values.dtype) + result = evaluate_linear_2d(self.values, + indices, + norm_distances, + self.grid, + out) + else: + result = self._evaluate_linear(indices, norm_distances) + elif method == "nearest": + indices, norm_distances = self._find_indices(xi.T) + result = self._evaluate_nearest(indices, norm_distances) + elif method in self._SPLINE_METHODS: + if is_method_changed: + self._validate_grid_dimensions(self.grid, method) + if method in self._SPLINE_METHODS_recursive: + result = self._evaluate_spline(xi, method) + else: + result = _spline(xi, nu=nu) + + if not self.bounds_error and self.fill_value is not None: + result[out_of_bounds] = self.fill_value + + # f(nan) = nan, if any + if np.any(nans): + result[nans] = np.nan + return result.reshape(xi_shape[:-1] + self.values.shape[ndim:]) + + def _prepare_xi(self, xi): + ndim = len(self.grid) + xi = _ndim_coords_from_arrays(xi, ndim=ndim) + if xi.shape[-1] != len(self.grid): + raise ValueError("The requested sample points xi have dimension " + f"{xi.shape[-1]} but this " + f"RegularGridInterpolator has dimension {ndim}") + + xi_shape = xi.shape + xi = xi.reshape(-1, xi_shape[-1]) + xi = np.asarray(xi, dtype=float) + + # find nans in input + nans = np.any(np.isnan(xi), axis=-1) + + if self.bounds_error: + for i, p in enumerate(xi.T): + if not np.logical_and(np.all(self.grid[i][0] <= p), + np.all(p <= self.grid[i][-1])): + raise ValueError("One of the requested xi is out of bounds " + "in dimension %d" % i) + out_of_bounds = None + else: + out_of_bounds = self._find_out_of_bounds(xi.T) + + return xi, xi_shape, ndim, nans, out_of_bounds + + def _evaluate_linear(self, indices, norm_distances): + # slice for broadcasting over trailing dimensions in self.values + vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices)) + + # Compute shifting up front before zipping everything together + shift_norm_distances = [1 - yi for yi in norm_distances] + shift_indices = [i + 1 for i in indices] + + # The formula for linear interpolation in 2d takes the form: + # values = self.values[(i0, i1)] * (1 - y0) * (1 - y1) + \ + # self.values[(i0, i1 + 1)] * (1 - y0) * y1 + \ + # self.values[(i0 + 1, i1)] * y0 * (1 - y1) + \ + # self.values[(i0 + 1, i1 + 1)] * y0 * y1 + # We pair i with 1 - yi (zipped1) and i + 1 with yi (zipped2) + zipped1 = zip(indices, shift_norm_distances) + zipped2 = zip(shift_indices, norm_distances) + + # Take all products of zipped1 and zipped2 and iterate over them + # to get the terms in the above formula. This corresponds to iterating + # over the vertices of a hypercube. + hypercube = itertools.product(*zip(zipped1, zipped2)) + value = np.array([0.]) + for h in hypercube: + edge_indices, weights = zip(*h) + weight = np.array([1.]) + for w in weights: + weight = weight * w + term = np.asarray(self.values[edge_indices]) * weight[vslice] + value = value + term # cannot use += because broadcasting + return value + + def _evaluate_nearest(self, indices, norm_distances): + idx_res = [np.where(yi <= .5, i, i + 1) + for i, yi in zip(indices, norm_distances)] + return self.values[tuple(idx_res)] + + def _validate_grid_dimensions(self, points, method): + k = self._SPLINE_DEGREE_MAP[method] + for i, point in enumerate(points): + ndim = len(np.atleast_1d(point)) + if ndim <= k: + raise ValueError(f"There are {ndim} points in dimension {i}," + f" but method {method} requires at least " + f" {k+1} points per dimension.") + + def _evaluate_spline(self, xi, method): + # ensure xi is 2D list of points to evaluate (`m` is the number of + # points and `n` is the number of interpolation dimensions, + # ``n == len(self.grid)``.) + if xi.ndim == 1: + xi = xi.reshape((1, xi.size)) + m, n = xi.shape + + # Reorder the axes: n-dimensional process iterates over the + # interpolation axes from the last axis downwards: E.g. for a 4D grid + # the order of axes is 3, 2, 1, 0. Each 1D interpolation works along + # the 0th axis of its argument array (for 1D routine it's its ``y`` + # array). Thus permute the interpolation axes of `values` *and keep + # trailing dimensions trailing*. + axes = tuple(range(self.values.ndim)) + axx = axes[:n][::-1] + axes[n:] + values = self.values.transpose(axx) + + if method == 'pchip': + _eval_func = self._do_pchip + else: + _eval_func = self._do_spline_fit + k = self._SPLINE_DEGREE_MAP[method] + + # Non-stationary procedure: difficult to vectorize this part entirely + # into numpy-level operations. Unfortunately this requires explicit + # looping over each point in xi. + + # can at least vectorize the first pass across all points in the + # last variable of xi. + last_dim = n - 1 + first_values = _eval_func(self.grid[last_dim], + values, + xi[:, last_dim], + k) + + # the rest of the dimensions have to be on a per point-in-xi basis + shape = (m, *self.values.shape[n:]) + result = np.empty(shape, dtype=self.values.dtype) + for j in range(m): + # Main process: Apply 1D interpolate in each dimension + # sequentially, starting with the last dimension. + # These are then "folded" into the next dimension in-place. + folded_values = first_values[j, ...] + for i in range(last_dim-1, -1, -1): + # Interpolate for each 1D from the last dimensions. + # This collapses each 1D sequence into a scalar. + folded_values = _eval_func(self.grid[i], + folded_values, + xi[j, i], + k) + result[j, ...] = folded_values + + return result + + @staticmethod + def _do_spline_fit(x, y, pt, k): + local_interp = make_interp_spline(x, y, k=k, axis=0) + values = local_interp(pt) + return values + + @staticmethod + def _do_pchip(x, y, pt, k): + local_interp = PchipInterpolator(x, y, axis=0) + values = local_interp(pt) + return values + + def _find_indices(self, xi): + return find_indices(self.grid, xi) + + def _find_out_of_bounds(self, xi): + # check for out of bounds xi + out_of_bounds = np.zeros((xi.shape[1]), dtype=bool) + # iterate through dimensions + for x, grid in zip(xi, self.grid): + out_of_bounds += x < grid[0] + out_of_bounds += x > grid[-1] + return out_of_bounds + + +def interpn(points, values, xi, method="linear", bounds_error=True, + fill_value=np.nan): + """ + Multidimensional interpolation on regular or rectilinear grids. + + Strictly speaking, not all regular grids are supported - this function + works on *rectilinear* grids, that is, a rectangular grid with even or + uneven spacing. + + Parameters + ---------- + points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) + The points defining the regular grid in n dimensions. The points in + each dimension (i.e. every elements of the points tuple) must be + strictly ascending or descending. + + values : array_like, shape (m1, ..., mn, ...) + The data on the regular grid in n dimensions. Complex data is + accepted. + + .. deprecated:: 1.13.0 + Complex data is deprecated with ``method="pchip"`` and will raise an + error in SciPy 1.15.0. This is because ``PchipInterpolator`` only + works with real values. If you are trying to use the real components of + the passed array, use ``np.real`` on ``values``. + + xi : ndarray of shape (..., ndim) + The coordinates to sample the gridded data at + + method : str, optional + The method of interpolation to perform. Supported are "linear", + "nearest", "slinear", "cubic", "quintic", "pchip", and "splinef2d". + "splinef2d" is only supported for 2-dimensional data. + + bounds_error : bool, optional + If True, when interpolated values are requested outside of the + domain of the input data, a ValueError is raised. + If False, then `fill_value` is used. + + fill_value : number, optional + If provided, the value to use for points outside of the + interpolation domain. If None, values outside + the domain are extrapolated. Extrapolation is not supported by method + "splinef2d". + + Returns + ------- + values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] + Interpolated values at `xi`. See notes for behaviour when + ``xi.ndim == 1``. + + See Also + -------- + NearestNDInterpolator : Nearest neighbor interpolation on unstructured + data in N dimensions + LinearNDInterpolator : Piecewise linear interpolant on unstructured data + in N dimensions + RegularGridInterpolator : interpolation on a regular or rectilinear grid + in arbitrary dimensions (`interpn` wraps this + class). + RectBivariateSpline : Bivariate spline approximation over a rectangular mesh + scipy.ndimage.map_coordinates : interpolation on grids with equal spacing + (suitable for e.g., N-D image resampling) + + Notes + ----- + + .. versionadded:: 0.14 + + In the case that ``xi.ndim == 1`` a new axis is inserted into + the 0 position of the returned array, values_x, so its shape is + instead ``(1,) + values.shape[ndim:]``. + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolation. + + Examples + -------- + Evaluate a simple example function on the points of a regular 3-D grid: + + >>> import numpy as np + >>> from scipy.interpolate import interpn + >>> def value_func_3d(x, y, z): + ... return 2 * x + 3 * y - z + >>> x = np.linspace(0, 4, 5) + >>> y = np.linspace(0, 5, 6) + >>> z = np.linspace(0, 6, 7) + >>> points = (x, y, z) + >>> values = value_func_3d(*np.meshgrid(*points, indexing='ij')) + + Evaluate the interpolating function at a point + + >>> point = np.array([2.21, 3.12, 1.15]) + >>> print(interpn(points, values, point)) + [12.63] + + """ + # sanity check 'method' kwarg + if method not in ["linear", "nearest", "cubic", "quintic", "pchip", + "splinef2d", "slinear", + "slinear_legacy", "cubic_legacy", "quintic_legacy"]: + raise ValueError("interpn only understands the methods 'linear', " + "'nearest', 'slinear', 'cubic', 'quintic', 'pchip', " + f"and 'splinef2d'. You provided {method}.") + + if not hasattr(values, 'ndim'): + values = np.asarray(values) + + ndim = values.ndim + if ndim > 2 and method == "splinef2d": + raise ValueError("The method splinef2d can only be used for " + "2-dimensional input data") + if not bounds_error and fill_value is None and method == "splinef2d": + raise ValueError("The method splinef2d does not support extrapolation.") + + # sanity check consistency of input dimensions + if len(points) > ndim: + raise ValueError("There are %d point arrays, but values has %d " + "dimensions" % (len(points), ndim)) + if len(points) != ndim and method == 'splinef2d': + raise ValueError("The method splinef2d can only be used for " + "scalar data with one point per coordinate") + + grid, descending_dimensions = _check_points(points) + _check_dimensionality(grid, values) + + # sanity check requested xi + xi = _ndim_coords_from_arrays(xi, ndim=len(grid)) + if xi.shape[-1] != len(grid): + raise ValueError("The requested sample points xi have dimension " + "%d, but this RegularGridInterpolator has " + "dimension %d" % (xi.shape[-1], len(grid))) + + if bounds_error: + for i, p in enumerate(xi.T): + if not np.logical_and(np.all(grid[i][0] <= p), + np.all(p <= grid[i][-1])): + raise ValueError("One of the requested xi is out of bounds " + "in dimension %d" % i) + + # perform interpolation + if method in RegularGridInterpolator._ALL_METHODS: + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=bounds_error, + fill_value=fill_value) + return interp(xi) + elif method == "splinef2d": + xi_shape = xi.shape + xi = xi.reshape(-1, xi.shape[-1]) + + # RectBivariateSpline doesn't support fill_value; we need to wrap here + idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1], + grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]), + axis=0) + result = np.empty_like(xi[:, 0]) + + # make a copy of values for RectBivariateSpline + interp = RectBivariateSpline(points[0], points[1], values[:]) + result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1]) + result[np.logical_not(idx_valid)] = fill_value + + return result.reshape(xi_shape[:-1]) + else: + raise ValueError(f"unknown {method = }") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py new file mode 100644 index 0000000000000000000000000000000000000000..e10da3b3fd0c69dede4767dc17b62c327818ecce --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py @@ -0,0 +1,44 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'bispeu', + 'bispev', + 'curfit', + 'dblint', + 'fpchec', + 'fpcurf0', + 'fpcurf1', + 'fpcurfm1', + 'parcur', + 'parder', + 'pardeu', + 'pardtc', + 'percur', + 'regrid_smth', + 'regrid_smth_spher', + 'spalde', + 'spherfit_lsq', + 'spherfit_smth', + 'splder', + 'splev', + 'splint', + 'sproot', + 'surfit_lsq', + 'surfit_smth', + 'types', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="dfitpack", + private_modules=["_dfitpack"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py new file mode 100644 index 0000000000000000000000000000000000000000..6490c93fe02b4c665b032d09e2ad3c269e1f7970 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py @@ -0,0 +1,31 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BSpline', + 'bisplev', + 'bisplrep', + 'insert', + 'spalde', + 'splantider', + 'splder', + 'splev', + 'splint', + 'splprep', + 'splrep', + 'sproot', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="fitpack", + private_modules=["_fitpack_py"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..f993961f94d913d632aa3d2cc7b1348659a6a613 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py @@ -0,0 +1,29 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BivariateSpline', + 'InterpolatedUnivariateSpline', + 'LSQBivariateSpline', + 'LSQSphereBivariateSpline', + 'LSQUnivariateSpline', + 'RectBivariateSpline', + 'RectSphereBivariateSpline', + 'SmoothBivariateSpline', + 'SmoothSphereBivariateSpline', + 'UnivariateSpline', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="fitpack2", + private_modules=["_fitpack2"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py new file mode 100644 index 0000000000000000000000000000000000000000..4288ac233fdde98dbb19aed84b916cfd15302f4c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'CloughTocher2DInterpolator', + 'GradientEstimationWarning', + 'LinearNDInterpolator', + 'NDInterpolatorBase', + 'estimate_gradients_2d_global', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="interpnd", + private_modules=["_interpnd"], all=__all__, + attribute=name) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..341d13954c81130cceb8afe070db023a82550e7a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py @@ -0,0 +1,30 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BPoly', + 'BSpline', + 'NdPPoly', + 'PPoly', + 'RectBivariateSpline', + 'RegularGridInterpolator', + 'interp1d', + 'interp2d', + 'interpn', + 'lagrange', + 'make_interp_spline', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="interpolate", + private_modules=["_interpolate", "fitpack2", "_rgi"], + all=__all__, attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py new file mode 100644 index 0000000000000000000000000000000000000000..20373eaaedaa1cdec6c7a4bc12639d9658bfa85b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'CloughTocher2DInterpolator', + 'LinearNDInterpolator', + 'NearestNDInterpolator', + 'griddata', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="ndgriddata", + private_modules=["_ndgriddata"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py new file mode 100644 index 0000000000000000000000000000000000000000..e81306304abffb313ab5abe09116a162642a9d67 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py @@ -0,0 +1,24 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BarycentricInterpolator', + 'KroghInterpolator', + 'approximate_taylor_polynomial', + 'barycentric_interpolate', + 'krogh_interpolate', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="polyint", + private_modules=["_polyint"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py new file mode 100644 index 0000000000000000000000000000000000000000..772752ef536f4a3b47fb6f9b5d250c5d7f198d85 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py @@ -0,0 +1,18 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = ["Rbf"] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="rbf", + private_modules=["_rbf"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bary_rational.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bary_rational.py new file mode 100644 index 0000000000000000000000000000000000000000..fbeea868ea24292693ced4cfb230badc3a551a89 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bary_rational.py @@ -0,0 +1,368 @@ +# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University +# of Oxford, and the Chebfun Developers. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the University of Oxford nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from math import factorial + +import numpy as np +from numpy.testing import assert_allclose, assert_equal, assert_array_less +import pytest +import scipy +from scipy.interpolate import AAA, FloaterHormannInterpolator, BarycentricInterpolator + +TOL = 1e4 * np.finfo(np.float64).eps +UNIT_INTERVAL = np.linspace(-1, 1, num=1000) +PTS = np.logspace(-15, 0, base=10, num=500) +PTS = np.concatenate([-PTS[::-1], [0], PTS]) + + +@pytest.mark.parametrize("method", [AAA, FloaterHormannInterpolator]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.complex64, np.complex128]) +def test_dtype_preservation(method, dtype): + rtol = np.finfo(dtype).eps ** 0.75 * 100 + if method is FloaterHormannInterpolator: + rtol *= 100 + rng = np.random.default_rng(59846294526092468) + + z = np.linspace(-1, 1, dtype=dtype) + r = method(z, np.sin(z)) + + z2 = rng.uniform(-1, 1, size=100).astype(dtype) + assert_allclose(r(z2), np.sin(z2), rtol=rtol) + assert r(z2).dtype == dtype + + if method is AAA: + assert r.support_points.dtype == dtype + assert r.support_values.dtype == dtype + assert r.errors.dtype == z.real.dtype + assert r.weights.dtype == dtype + assert r.poles().dtype == np.result_type(dtype, 1j) + assert r.residues().dtype == np.result_type(dtype, 1j) + assert r.roots().dtype == np.result_type(dtype, 1j) + + +@pytest.mark.parametrize("method", [AAA, FloaterHormannInterpolator]) +@pytest.mark.parametrize("dtype", [np.int16, np.int32, np.int64]) +def test_integer_promotion(method, dtype): + z = np.arange(10, dtype=dtype) + r = method(z, z) + assert r.weights.dtype == np.result_type(dtype, 1.0) + if method is AAA: + assert r.support_points.dtype == np.result_type(dtype, 1.0) + assert r.support_values.dtype == np.result_type(dtype, 1.0) + assert r.errors.dtype == np.result_type(dtype, 1.0) + assert r.poles().dtype == np.result_type(dtype, 1j) + assert r.residues().dtype == np.result_type(dtype, 1j) + assert r.roots().dtype == np.result_type(dtype, 1j) + + assert r(z).dtype == np.result_type(dtype, 1.0) + + +class TestAAA: + def test_input_validation(self): + with pytest.raises(ValueError, match="same size"): + AAA([0], [1, 1]) + with pytest.raises(ValueError, match="1-D"): + AAA([[0], [0]], [[1], [1]]) + with pytest.raises(ValueError, match="finite"): + AAA([np.inf], [1]) + with pytest.raises(TypeError): + AAA([1], [1], max_terms=1.0) + with pytest.raises(ValueError, match="greater"): + AAA([1], [1], max_terms=-1) + + @pytest.mark.thread_unsafe + def test_convergence_error(self): + with pytest.warns(RuntimeWarning, match="AAA failed"): + AAA(UNIT_INTERVAL, np.exp(UNIT_INTERVAL), max_terms=1) + + # The following tests are based on: + # https://github.com/chebfun/chebfun/blob/master/tests/chebfun/test_aaa.m + def test_exp(self): + f = np.exp(UNIT_INTERVAL) + r = AAA(UNIT_INTERVAL, f) + + assert_allclose(r(UNIT_INTERVAL), f, atol=TOL) + assert_equal(r(np.nan), np.nan) + assert np.isfinite(r(np.inf)) + + m1 = r.support_points.size + r = AAA(UNIT_INTERVAL, f, rtol=1e-3) + assert r.support_points.size < m1 + + def test_tan(self): + f = np.tan(np.pi * UNIT_INTERVAL) + r = AAA(UNIT_INTERVAL, f) + + assert_allclose(r(UNIT_INTERVAL), f, atol=10 * TOL, rtol=1.4e-7) + assert_allclose(np.min(np.abs(r.roots())), 0, atol=3e-10) + assert_allclose(np.min(np.abs(r.poles() - 0.5)), 0, atol=TOL) + # Test for spurious poles (poles with tiny residue are likely spurious) + assert np.min(np.abs(r.residues())) > 1e-13 + + def test_short_cases(self): + # Computed using Chebfun: + # >> format long + # >> [r, pol, res, zer, zj, fj, wj, errvec] = aaa([1 2], [0 1]) + z = np.array([0, 1]) + f = np.array([1, 2]) + r = AAA(z, f, rtol=1e-13) + assert_allclose(r(z), f, atol=TOL) + assert_allclose(r.poles(), 0.5) + assert_allclose(r.residues(), 0.25) + assert_allclose(r.roots(), 1/3) + assert_equal(r.support_points, z) + assert_equal(r.support_values, f) + assert_allclose(r.weights, [0.707106781186547, 0.707106781186547]) + assert_equal(r.errors, [1, 0]) + + # >> format long + # >> [r, pol, res, zer, zj, fj, wj, errvec] = aaa([1 0 0], [0 1 2]) + z = np.array([0, 1, 2]) + f = np.array([1, 0, 0]) + r = AAA(z, f, rtol=1e-13) + assert_allclose(r(z), f, atol=TOL) + assert_allclose(np.sort(r.poles()), + np.sort([1.577350269189626, 0.422649730810374])) + assert_allclose(np.sort(r.residues()), + np.sort([-0.070441621801729, -0.262891711531604])) + assert_allclose(np.sort(r.roots()), np.sort([2, 1])) + assert_equal(r.support_points, z) + assert_equal(r.support_values, f) + assert_allclose(r.weights, [0.577350269189626, 0.577350269189626, + 0.577350269189626]) + assert_equal(r.errors, [1, 1, 0]) + + def test_scale_invariance(self): + z = np.linspace(0.3, 1.5) + f = np.exp(z) / (1 + 1j) + r1 = AAA(z, f) + r2 = AAA(z, (2**311 * f).astype(np.complex128)) + r3 = AAA(z, (2**-311 * f).astype(np.complex128)) + assert_equal(r1(0.2j), 2**-311 * r2(0.2j)) + assert_equal(r1(1.4), 2**311 * r3(1.4)) + + def test_log_func(self): + rng = np.random.default_rng(1749382759832758297) + z = rng.standard_normal(10000) + 3j * rng.standard_normal(10000) + + def f(z): + return np.log(5 - z) / (1 + z**2) + + r = AAA(z, f(z)) + assert_allclose(r(0), f(0), atol=TOL) + + def test_infinite_data(self): + z = np.linspace(-1, 1) + r = AAA(z, scipy.special.gamma(z)) + assert_allclose(r(0.63), scipy.special.gamma(0.63), atol=1e-15) + + def test_nan(self): + x = np.linspace(0, 20) + with np.errstate(invalid="ignore"): + f = np.sin(x) / x + r = AAA(x, f) + assert_allclose(r(2), np.sin(2) / 2, atol=1e-15) + + def test_residues(self): + x = np.linspace(-1.337, 2, num=537) + r = AAA(x, np.exp(x) / x) + ii = np.flatnonzero(np.abs(r.poles()) < 1e-8) + assert_allclose(r.residues()[ii], 1, atol=1e-15) + + r = AAA(x, (1 + 1j) * scipy.special.gamma(x)) + ii = np.flatnonzero(abs(r.poles() - (-1)) < 1e-8) + assert_allclose(r.residues()[ii], -1 - 1j, atol=1e-15) + + # The following tests are based on: + # https://github.com/complexvariables/RationalFunctionApproximation.jl/blob/main/test/interval.jl + @pytest.mark.parametrize("func,atol,rtol", + [(lambda x: np.abs(x + 0.5 + 0.01j), 5e-13, 1e-7), + (lambda x: np.sin(1/(1.05 - x)), 2e-13, 1e-7), + (lambda x: np.exp(-1/(x**2)), 3.5e-13, 0), + (lambda x: np.exp(-100*x**2), 8e-13, 0), + (lambda x: np.exp(-10/(1.2 - x)), 1e-14, 0), + (lambda x: 1/(1+np.exp(100*(x + 0.5))), 2e-13, 1e-7), + (lambda x: np.abs(x - 0.95), 1e-6, 1e-7)]) + def test_basic_functions(self, func, atol, rtol): + with np.errstate(divide="ignore"): + f = func(PTS) + assert_allclose(AAA(UNIT_INTERVAL, func(UNIT_INTERVAL))(PTS), + f, atol=atol, rtol=rtol) + + def test_poles_zeros_residues(self): + def f(z): + return (z+1) * (z+2) / ((z+3) * (z+4)) + r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL)) + assert_allclose(np.sum(r.poles() + r.roots()), -10, atol=1e-12) + + def f(z): + return 2/(3 + z) + 5/(z - 2j) + r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL)) + assert_allclose(r.residues().prod(), 10, atol=1e-8) + + r = AAA(UNIT_INTERVAL, np.sin(10*np.pi*UNIT_INTERVAL)) + assert_allclose(np.sort(np.abs(r.roots()))[18], 0.9, atol=1e-12) + + def f(z): + return (z - (3 + 3j))/(z + 2) + r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL)) + assert_allclose(r.poles()[0]*r.roots()[0], -6-6j, atol=1e-12) + + @pytest.mark.parametrize("func", + [lambda z: np.zeros_like(z), lambda z: z, lambda z: 1j*z, + lambda z: z**2 + z, lambda z: z**3 + z, + lambda z: 1/(1.1 + z), lambda z: 1/(1 + 1j*z), + lambda z: 1/(3 + z + z**2), lambda z: 1/(1.01 + z**3)]) + def test_polynomials_and_reciprocals(self, func): + assert_allclose(AAA(UNIT_INTERVAL, func(UNIT_INTERVAL))(PTS), + func(PTS), atol=2e-13) + + # The following tests are taken from: + # https://github.com/macd/BaryRational.jl/blob/main/test/test_aaa.jl + def test_spiral(self): + z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, num=1000)) + r = AAA(z, np.tan(np.pi*z/2)) + assert_allclose(np.sort(np.abs(r.poles()))[:4], [1, 1, 3, 3], rtol=9e-7) + + @pytest.mark.thread_unsafe + def test_spiral_cleanup(self): + z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, num=1000)) + # here we set `rtol=0` to force froissart doublets, without cleanup there + # are many spurious poles + with pytest.warns(RuntimeWarning): + r = AAA(z, np.tan(np.pi*z/2), rtol=0, max_terms=60, clean_up=False) + n_spurious = np.sum(np.abs(r.residues()) < 1e-14) + with pytest.warns(RuntimeWarning): + assert r.clean_up() >= 1 + # check there are less potentially spurious poles than before + assert np.sum(np.abs(r.residues()) < 1e-14) < n_spurious + # check accuracy + assert_allclose(r(z), np.tan(np.pi*z/2), atol=6e-12, rtol=3e-12) + + +class TestFloaterHormann: + def runge(self, z): + return 1/(1 + z**2) + + def scale(self, n, d): + return (-1)**(np.arange(n) + d) * factorial(d) + + def test_iv(self): + with pytest.raises(ValueError, match="`x`"): + FloaterHormannInterpolator([[0]], [0], d=0) + with pytest.raises(ValueError, match="`y`"): + FloaterHormannInterpolator([0], 0, d=0) + with pytest.raises(ValueError, match="dimension"): + FloaterHormannInterpolator([0], [[1, 1], [1, 1]], d=0) + with pytest.raises(ValueError, match="finite"): + FloaterHormannInterpolator([np.inf], [1], d=0) + with pytest.raises(ValueError, match="`d`"): + FloaterHormannInterpolator([0], [0], d=-1) + with pytest.raises(ValueError, match="`d`"): + FloaterHormannInterpolator([0], [0], d=10) + with pytest.raises(TypeError): + FloaterHormannInterpolator([0], [0], d=0.0) + + # reference values from Floater and Hormann 2007 page 8. + @pytest.mark.parametrize("d,expected", [ + (0, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + (1, [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]), + (2, [1, 3, 4, 4, 4, 4, 4, 4, 4, 3, 1]), + (3, [1, 4, 7, 8, 8, 8, 8, 8, 7, 4, 1]), + (4, [1, 5, 11, 15, 16, 16, 16, 15, 11, 5, 1]) + ]) + def test_uniform_grid(self, d, expected): + # Check against explicit results on an uniform grid + x = np.arange(11) + r = FloaterHormannInterpolator(x, 0.0*x, d=d) + assert_allclose(r.weights.ravel()*self.scale(x.size, d), expected, + rtol=1e-15, atol=1e-15) + + @pytest.mark.parametrize("d", range(10)) + def test_runge(self, d): + x = np.linspace(0, 1, 51) + rng = np.random.default_rng(802754237598370893) + xx = rng.uniform(0, 1, size=1000) + y = self.runge(x) + h = x[1] - x[0] + + r = FloaterHormannInterpolator(x, y, d=d) + + tol = 10*h**(d+1) + assert_allclose(r(xx), self.runge(xx), atol=1e-10, rtol=tol) + # check interpolation property + assert_equal(r(x), self.runge(x)) + + def test_complex(self): + x = np.linspace(-1, 1) + z = x + x*1j + r = FloaterHormannInterpolator(z, np.sin(z), d=12) + xx = np.linspace(-1, 1, num=1000) + zz = xx + xx*1j + assert_allclose(r(zz), np.sin(zz), rtol=1e-12) + + def test_polyinterp(self): + # check that when d=n-1 FH gives a polynomial interpolant + x = np.linspace(0, 1, 11) + xx = np.linspace(0, 1, 1001) + y = np.sin(x) + r = FloaterHormannInterpolator(x, y, d=x.size-1) + p = BarycentricInterpolator(x, y) + assert_allclose(r(xx), p(xx), rtol=1e-12, atol=1e-12) + + @pytest.mark.parametrize("y_shape", [(2,), (2, 3, 1), (1, 5, 6, 4)]) + @pytest.mark.parametrize("xx_shape", [(100), (10, 10)]) + def test_trailing_dim(self, y_shape, xx_shape): + x = np.linspace(0, 1) + y = np.broadcast_to( + np.expand_dims(np.sin(x), tuple(range(1, len(y_shape) + 1))), + x.shape + y_shape + ) + + r = FloaterHormannInterpolator(x, y) + + rng = np.random.default_rng(897138947238097528091759187597) + xx = rng.random(xx_shape) + yy = np.broadcast_to( + np.expand_dims(np.sin(xx), tuple(range(xx.ndim, len(y_shape) + xx.ndim))), + xx.shape + y_shape + ) + rr = r(xx) + assert rr.shape == xx.shape + y_shape + assert_allclose(rr, yy, rtol=1e-6) + + def test_zeros(self): + x = np.linspace(0, 10, num=100) + r = FloaterHormannInterpolator(x, np.sin(np.pi*x)) + + err = np.abs(np.subtract.outer(r.roots(), np.arange(11))).min(axis=0) + assert_array_less(err, 1e-5) + + def test_no_poles(self): + x = np.linspace(-1, 1) + r = FloaterHormannInterpolator(x, 1/x**2) + p = r.poles() + mask = (p.real >= -1) & (p.real <= 1) & (np.abs(p.imag) < 1.e-12) + assert np.sum(mask) == 0 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bsplines.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b1b2b58afcf5ad5a34babe65fff96bf268df03 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bsplines.py @@ -0,0 +1,3658 @@ +import os +import operator +import itertools +import math +import threading + +import numpy as np +from numpy.testing import suppress_warnings +from scipy._lib._array_api import xp_assert_equal, xp_assert_close +from pytest import raises as assert_raises +import pytest + +from scipy.interpolate import ( + BSpline, BPoly, PPoly, make_interp_spline, make_lsq_spline, + splev, splrep, splprep, splder, splantider, sproot, splint, insert, + CubicSpline, NdBSpline, make_smoothing_spline, RegularGridInterpolator, +) +import scipy.linalg as sl +import scipy.sparse.linalg as ssl + +from scipy.interpolate._bsplines import (_not_a_knot, _augknt, + _woodbury_algorithm, _periodic_knots, + _make_interp_per_full_matr) + +from scipy.interpolate import generate_knots, make_splrep, make_splprep + +import scipy.interpolate._fitpack_impl as _impl +from scipy._lib._util import AxisError +from scipy._lib._testutils import _run_concurrent_barrier + +# XXX: move to the interpolate namespace +from scipy.interpolate._ndbspline import make_ndbspl + +from scipy.interpolate import _dfitpack as dfitpack +from scipy.interpolate import _bsplines as _b +from scipy.interpolate import _dierckx + + +class TestBSpline: + + def test_ctor(self): + # knots should be an ordered 1-D array of finite real numbers + assert_raises((TypeError, ValueError), BSpline, + **dict(t=[1, 1.j], c=[1.], k=0)) + with np.errstate(invalid='ignore'): + assert_raises(ValueError, BSpline, **dict(t=[1, np.nan], c=[1.], k=0)) + assert_raises(ValueError, BSpline, **dict(t=[1, np.inf], c=[1.], k=0)) + assert_raises(ValueError, BSpline, **dict(t=[1, -1], c=[1.], k=0)) + assert_raises(ValueError, BSpline, **dict(t=[[1], [1]], c=[1.], k=0)) + + # for n+k+1 knots and degree k need at least n coefficients + assert_raises(ValueError, BSpline, **dict(t=[0, 1, 2], c=[1], k=0)) + assert_raises(ValueError, BSpline, + **dict(t=[0, 1, 2, 3, 4], c=[1., 1.], k=2)) + + # non-integer orders + assert_raises(TypeError, BSpline, + **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k="cubic")) + assert_raises(TypeError, BSpline, + **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k=2.5)) + + # basic interval cannot have measure zero (here: [1..1]) + assert_raises(ValueError, BSpline, + **dict(t=[0., 0, 1, 1, 2, 3], c=[1., 1, 1], k=2)) + + # tck vs self.tck + n, k = 11, 3 + t = np.arange(n+k+1, dtype=np.float64) + c = np.random.random(n) + b = BSpline(t, c, k) + + xp_assert_close(t, b.t) + xp_assert_close(c, b.c) + assert k == b.k + + def test_tck(self): + b = _make_random_spline() + tck = b.tck + + xp_assert_close(b.t, tck[0], atol=1e-15, rtol=1e-15) + xp_assert_close(b.c, tck[1], atol=1e-15, rtol=1e-15) + assert b.k == tck[2] + + # b.tck is read-only + with pytest.raises(AttributeError): + b.tck = 'foo' + + def test_degree_0(self): + xx = np.linspace(0, 1, 10) + + b = BSpline(t=[0, 1], c=[3.], k=0) + xp_assert_close(b(xx), np.ones_like(xx) * 3.0) + + b = BSpline(t=[0, 0.35, 1], c=[3, 4], k=0) + xp_assert_close(b(xx), np.where(xx < 0.35, 3.0, 4.0)) + + def test_degree_1(self): + t = [0, 1, 2, 3, 4] + c = [1, 2, 3] + k = 1 + b = BSpline(t, c, k) + + x = np.linspace(1, 3, 50) + xp_assert_close(c[0]*B_012(x) + c[1]*B_012(x-1) + c[2]*B_012(x-2), + b(x), atol=1e-14) + xp_assert_close(splev(x, (t, c, k)), b(x), atol=1e-14) + + def test_bernstein(self): + # a special knot vector: Bernstein polynomials + k = 3 + t = np.asarray([0]*(k+1) + [1]*(k+1)) + c = np.asarray([1., 2., 3., 4.]) + bp = BPoly(c.reshape(-1, 1), [0, 1]) + bspl = BSpline(t, c, k) + + xx = np.linspace(-1., 2., 10) + xp_assert_close(bp(xx, extrapolate=True), + bspl(xx, extrapolate=True), atol=1e-14) + xp_assert_close(splev(xx, (t, c, k)), + bspl(xx), atol=1e-14) + + def test_rndm_naive_eval(self): + # test random coefficient spline *on the base interval*, + # t[k] <= x < t[-k-1] + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[k], t[-k-1], 50) + y_b = b(xx) + + y_n = [_naive_eval(x, t, c, k) for x in xx] + xp_assert_close(y_b, y_n, atol=1e-14) + + y_n2 = [_naive_eval_2(x, t, c, k) for x in xx] + xp_assert_close(y_b, y_n2, atol=1e-14) + + def test_rndm_splev(self): + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[k], t[-k-1], 50) + xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14) + + def test_rndm_splrep(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(20)) + y = rng.random(20) + + tck = splrep(x, y) + b = BSpline(*tck) + + t, k = b.t, b.k + xx = np.linspace(t[k], t[-k-1], 80) + xp_assert_close(b(xx), splev(xx, tck), atol=1e-14) + + def test_rndm_unity(self): + b = _make_random_spline() + b.c = np.ones_like(b.c) + xx = np.linspace(b.t[b.k], b.t[-b.k-1], 100) + xp_assert_close(b(xx), np.ones_like(xx)) + + def test_vectorization(self): + rng = np.random.RandomState(1234) + n, k = 22, 3 + t = np.sort(rng.random(n)) + c = rng.random(size=(n, 6, 7)) + b = BSpline(t, c, k) + tm, tp = t[k], t[-k-1] + xx = tm + (tp - tm) * rng.random((3, 4, 5)) + assert b(xx).shape == (3, 4, 5, 6, 7) + + def test_len_c(self): + # for n+k+1 knots, only first n coefs are used. + # and BTW this is consistent with FITPACK + rng = np.random.RandomState(1234) + n, k = 33, 3 + t = np.sort(rng.random(n+k+1)) + c = rng.random(n) + + # pad coefficients with random garbage + c_pad = np.r_[c, rng.random(k+1)] + + b, b_pad = BSpline(t, c, k), BSpline(t, c_pad, k) + + dt = t[-1] - t[0] + xx = np.linspace(t[0] - dt, t[-1] + dt, 50) + xp_assert_close(b(xx), b_pad(xx), atol=1e-14) + xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14) + xp_assert_close(b(xx), splev(xx, (t, c_pad, k)), atol=1e-14) + + def test_endpoints(self, num_parallel_threads): + # base interval is closed + b = _make_random_spline() + t, _, k = b.tck + tm, tp = t[k], t[-k-1] + # atol = 1e-9 if num_parallel_threads == 1 else 1e-7 + for extrap in (True, False): + xp_assert_close(b([tm, tp], extrap), + b([tm + 1e-10, tp - 1e-10], extrap), atol=1e-9, rtol=1e-7) + + def test_continuity(self, num_parallel_threads): + # assert continuity at internal knots + b = _make_random_spline() + t, _, k = b.tck + xp_assert_close(b(t[k+1:-k-1] - 1e-10), b(t[k+1:-k-1] + 1e-10), + atol=1e-9) + + def test_extrap(self): + b = _make_random_spline() + t, c, k = b.tck + dt = t[-1] - t[0] + xx = np.linspace(t[k] - dt, t[-k-1] + dt, 50) + mask = (t[k] < xx) & (xx < t[-k-1]) + + # extrap has no effect within the base interval + xp_assert_close(b(xx[mask], extrapolate=True), + b(xx[mask], extrapolate=False)) + + # extrapolated values agree with FITPACK + xp_assert_close(b(xx, extrapolate=True), + splev(xx, (t, c, k), ext=0)) + + def test_default_extrap(self): + # BSpline defaults to extrapolate=True + b = _make_random_spline() + t, _, k = b.tck + xx = [t[0] - 1, t[-1] + 1] + yy = b(xx) + assert not np.all(np.isnan(yy)) + + def test_periodic_extrap(self): + rng = np.random.RandomState(1234) + t = np.sort(rng.random(8)) + c = rng.random(4) + k = 3 + b = BSpline(t, c, k, extrapolate='periodic') + n = t.size - (k + 1) + + dt = t[-1] - t[0] + xx = np.linspace(t[k] - dt, t[n] + dt, 50) + xy = t[k] + (xx - t[k]) % (t[n] - t[k]) + xp_assert_close(b(xx), splev(xy, (t, c, k))) + + # Direct check + xx = [-1, 0, 0.5, 1] + xy = t[k] + (xx - t[k]) % (t[n] - t[k]) + xp_assert_equal(b(xx, extrapolate='periodic'), b(xy, extrapolate=True)) + + def test_ppoly(self): + b = _make_random_spline() + t, c, k = b.tck + pp = PPoly.from_spline((t, c, k)) + + xx = np.linspace(t[k], t[-k], 100) + xp_assert_close(b(xx), pp(xx), atol=1e-14, rtol=1e-14) + + def test_derivative_rndm(self): + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[0], t[-1], 50) + xx = np.r_[xx, t] + + for der in range(1, k+1): + yd = splev(xx, (t, c, k), der=der) + xp_assert_close(yd, b(xx, nu=der), atol=1e-14) + + # higher derivatives all vanish + xp_assert_close(b(xx, nu=k+1), np.zeros_like(xx), atol=1e-14) + + def test_derivative_jumps(self): + # example from de Boor, Chap IX, example (24) + # NB: knots augmented & corresp coefs are zeroed out + # in agreement with the convention (29) + k = 2 + t = [-1, -1, 0, 1, 1, 3, 4, 6, 6, 6, 7, 7] + rng = np.random.RandomState(1234) + c = np.r_[0, 0, rng.random(5), 0, 0] + b = BSpline(t, c, k) + + # b is continuous at x != 6 (triple knot) + x = np.asarray([1, 3, 4, 6]) + xp_assert_close(b(x[x != 6] - 1e-10), + b(x[x != 6] + 1e-10)) + assert not np.allclose(b(6.-1e-10), b(6+1e-10)) + + # 1st derivative jumps at double knots, 1 & 6: + x0 = np.asarray([3, 4]) + xp_assert_close(b(x0 - 1e-10, nu=1), + b(x0 + 1e-10, nu=1)) + x1 = np.asarray([1, 6]) + assert not np.allclose(b(x1 - 1e-10, nu=1), b(x1 + 1e-10, nu=1)) + + # 2nd derivative is not guaranteed to be continuous either + assert not np.allclose(b(x - 1e-10, nu=2), b(x + 1e-10, nu=2)) + + def test_basis_element_quadratic(self): + xx = np.linspace(-1, 4, 20) + b = BSpline.basis_element(t=[0, 1, 2, 3]) + xp_assert_close(b(xx), + splev(xx, (b.t, b.c, b.k)), atol=1e-14) + xp_assert_close(b(xx), + B_0123(xx), atol=1e-14) + + b = BSpline.basis_element(t=[0, 1, 1, 2]) + xx = np.linspace(0, 2, 10) + xp_assert_close(b(xx), + np.where(xx < 1, xx*xx, (2.-xx)**2), atol=1e-14) + + def test_basis_element_rndm(self): + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[k], t[-k-1], 20) + xp_assert_close(b(xx), _sum_basis_elements(xx, t, c, k), atol=1e-14) + + def test_cmplx(self): + b = _make_random_spline() + t, c, k = b.tck + cc = c * (1. + 3.j) + + b = BSpline(t, cc, k) + b_re = BSpline(t, b.c.real, k) + b_im = BSpline(t, b.c.imag, k) + + xx = np.linspace(t[k], t[-k-1], 20) + xp_assert_close(b(xx).real, b_re(xx), atol=1e-14) + xp_assert_close(b(xx).imag, b_im(xx), atol=1e-14) + + def test_nan(self): + # nan in, nan out. + b = BSpline.basis_element([0, 1, 1, 2]) + assert np.isnan(b(np.nan)) + + def test_derivative_method(self): + b = _make_random_spline(k=5) + t, c, k = b.tck + b0 = BSpline(t, c, k) + xx = np.linspace(t[k], t[-k-1], 20) + for j in range(1, k): + b = b.derivative() + xp_assert_close(b0(xx, j), b(xx), atol=1e-12, rtol=1e-12) + + def test_antiderivative_method(self): + b = _make_random_spline() + t, c, k = b.tck + xx = np.linspace(t[k], t[-k-1], 20) + xp_assert_close(b.antiderivative().derivative()(xx), + b(xx), atol=1e-14, rtol=1e-14) + + # repeat with N-D array for c + c = np.c_[c, c, c] + c = np.dstack((c, c)) + b = BSpline(t, c, k) + xp_assert_close(b.antiderivative().derivative()(xx), + b(xx), atol=1e-14, rtol=1e-14) + + def test_integral(self): + b = BSpline.basis_element([0, 1, 2]) # x for x < 1 else 2 - x + xp_assert_close(b.integrate(0, 1), np.asarray(0.5)) + xp_assert_close(b.integrate(1, 0), np.asarray(-1 * 0.5)) + xp_assert_close(b.integrate(1, 0), np.asarray(-0.5)) + + # extrapolate or zeros outside of [0, 2]; default is yes + xp_assert_close(b.integrate(-1, 1), np.asarray(0.0)) + xp_assert_close(b.integrate(-1, 1, extrapolate=True), np.asarray(0.0)) + xp_assert_close(b.integrate(-1, 1, extrapolate=False), np.asarray(0.5)) + xp_assert_close(b.integrate(1, -1, extrapolate=False), np.asarray(-1 * 0.5)) + + # Test ``_fitpack._splint()`` + xp_assert_close(b.integrate(1, -1, extrapolate=False), + np.asarray(_impl.splint(1, -1, b.tck))) + + # Test ``extrapolate='periodic'``. + b.extrapolate = 'periodic' + i = b.antiderivative() + period_int = np.asarray(i(2) - i(0)) + + xp_assert_close(b.integrate(0, 2), period_int) + xp_assert_close(b.integrate(2, 0), np.asarray(-1 * period_int)) + xp_assert_close(b.integrate(-9, -7), period_int) + xp_assert_close(b.integrate(-8, -4), np.asarray(2 * period_int)) + + xp_assert_close(b.integrate(0.5, 1.5), + np.asarray(i(1.5) - i(0.5))) + xp_assert_close(b.integrate(1.5, 3), + np.asarray(i(1) - i(0) + i(2) - i(1.5))) + xp_assert_close(b.integrate(1.5 + 12, 3 + 12), + np.asarray(i(1) - i(0) + i(2) - i(1.5))) + xp_assert_close(b.integrate(1.5, 3 + 12), + np.asarray(i(1) - i(0) + i(2) - i(1.5) + 6 * period_int)) + + xp_assert_close(b.integrate(0, -1), np.asarray(i(0) - i(1))) + xp_assert_close(b.integrate(-9, -10), np.asarray(i(0) - i(1))) + xp_assert_close(b.integrate(0, -9), + np.asarray(i(1) - i(2) - 4 * period_int)) + + def test_integrate_ppoly(self): + # test .integrate method to be consistent with PPoly.integrate + x = [0, 1, 2, 3, 4] + b = make_interp_spline(x, x) + b.extrapolate = 'periodic' + p = PPoly.from_spline(b) + + for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]: + xp_assert_close(b.integrate(x0, x1), + p.integrate(x0, x1)) + + def test_integrate_0D_always(self): + # make sure the result is always a 0D array (not a python scalar) + b = BSpline.basis_element([0, 1, 2]) + for extrapolate in (True, False): + res = b.integrate(0, 1, extrapolate=extrapolate) + assert isinstance(res, np.ndarray) + assert res.ndim == 0 + + def test_subclassing(self): + # classmethods should not decay to the base class + class B(BSpline): + pass + + b = B.basis_element([0, 1, 2, 2]) + assert b.__class__ == B + assert b.derivative().__class__ == B + assert b.antiderivative().__class__ == B + + @pytest.mark.parametrize('axis', range(-4, 4)) + def test_axis(self, axis): + n, k = 22, 3 + t = np.linspace(0, 1, n + k + 1) + sh = [6, 7, 8] + # We need the positive axis for some of the indexing and slices used + # in this test. + pos_axis = axis % 4 + sh.insert(pos_axis, n) # [22, 6, 7, 8] etc + sh = tuple(sh) + rng = np.random.RandomState(1234) + c = rng.random(size=sh) + b = BSpline(t, c, k, axis=axis) + assert b.c.shape == (sh[pos_axis],) + sh[:pos_axis] + sh[pos_axis+1:] + + xp = rng.random((3, 4, 5)) + assert b(xp).shape == sh[:pos_axis] + xp.shape + sh[pos_axis+1:] + + # -c.ndim <= axis < c.ndim + for ax in [-c.ndim - 1, c.ndim]: + assert_raises(AxisError, BSpline, + **dict(t=t, c=c, k=k, axis=ax)) + + # derivative, antiderivative keeps the axis + for b1 in [BSpline(t, c, k, axis=axis).derivative(), + BSpline(t, c, k, axis=axis).derivative(2), + BSpline(t, c, k, axis=axis).antiderivative(), + BSpline(t, c, k, axis=axis).antiderivative(2)]: + assert b1.axis == b.axis + + def test_neg_axis(self): + k = 2 + t = [0, 1, 2, 3, 4, 5, 6] + c = np.array([[-1, 2, 0, -1], [2, 0, -3, 1]]) + + spl = BSpline(t, c, k, axis=-1) + spl0 = BSpline(t, c[0], k) + spl1 = BSpline(t, c[1], k) + xp_assert_equal(spl(2.5), [spl0(2.5), spl1(2.5)]) + + @pytest.mark.thread_unsafe + def test_design_matrix_bc_types(self): + ''' + Splines with different boundary conditions are built on different + types of vectors of knots. As far as design matrix depends only on + vector of knots, `k` and `x` it is useful to make tests for different + boundary conditions (and as following different vectors of knots). + ''' + def run_design_matrix_tests(n, k, bc_type): + ''' + To avoid repetition of code the following function is provided. + ''' + rng = np.random.RandomState(1234) + x = np.sort(rng.random_sample(n) * 40 - 20) + y = rng.random_sample(n) * 40 - 20 + if bc_type == "periodic": + y[0] = y[-1] + + bspl = make_interp_spline(x, y, k=k, bc_type=bc_type) + + c = np.eye(len(bspl.t) - k - 1) + des_matr_def = BSpline(bspl.t, c, k)(x) + des_matr_csr = BSpline.design_matrix(x, + bspl.t, + k).toarray() + xp_assert_close(des_matr_csr @ bspl.c, y, atol=1e-14) + xp_assert_close(des_matr_def, des_matr_csr, atol=1e-14) + + # "clamped" and "natural" work only with `k = 3` + n = 11 + k = 3 + for bc in ["clamped", "natural"]: + run_design_matrix_tests(n, k, bc) + + # "not-a-knot" works with odd `k` + for k in range(3, 8, 2): + run_design_matrix_tests(n, k, "not-a-knot") + + # "periodic" works with any `k` (even more than `n`) + n = 5 # smaller `n` to test `k > n` case + for k in range(2, 7): + run_design_matrix_tests(n, k, "periodic") + + @pytest.mark.parametrize('extrapolate', [False, True, 'periodic']) + @pytest.mark.parametrize('degree', range(5)) + def test_design_matrix_same_as_BSpline_call(self, extrapolate, degree): + """Test that design_matrix(x) is equivalent to BSpline(..)(x).""" + rng = np.random.RandomState(1234) + x = rng.random_sample(10 * (degree + 1)) + xmin, xmax = np.amin(x), np.amax(x) + k = degree + t = np.r_[np.linspace(xmin - 2, xmin - 1, degree), + np.linspace(xmin, xmax, 2 * (degree + 1)), + np.linspace(xmax + 1, xmax + 2, degree)] + c = np.eye(len(t) - k - 1) + bspline = BSpline(t, c, k, extrapolate) + xp_assert_close( + bspline(x), BSpline.design_matrix(x, t, k, extrapolate).toarray() + ) + + # extrapolation regime + x = np.array([xmin - 10, xmin - 1, xmax + 1.5, xmax + 10]) + if not extrapolate: + with pytest.raises(ValueError): + BSpline.design_matrix(x, t, k, extrapolate) + else: + xp_assert_close( + bspline(x), + BSpline.design_matrix(x, t, k, extrapolate).toarray() + ) + + def test_design_matrix_x_shapes(self): + # test for different `x` shapes + rng = np.random.RandomState(1234) + n = 10 + k = 3 + x = np.sort(rng.random_sample(n) * 40 - 20) + y = rng.random_sample(n) * 40 - 20 + + bspl = make_interp_spline(x, y, k=k) + for i in range(1, 4): + xc = x[:i] + yc = y[:i] + des_matr_csr = BSpline.design_matrix(xc, + bspl.t, + k).toarray() + xp_assert_close(des_matr_csr @ bspl.c, yc, atol=1e-14) + + def test_design_matrix_t_shapes(self): + # test for minimal possible `t` shape + t = [1., 1., 1., 2., 3., 4., 4., 4.] + des_matr = BSpline.design_matrix(2., t, 3).toarray() + xp_assert_close(des_matr, + [[0.25, 0.58333333, 0.16666667, 0.]], + atol=1e-14) + + def test_design_matrix_asserts(self): + rng = np.random.RandomState(1234) + n = 10 + k = 3 + x = np.sort(rng.random_sample(n) * 40 - 20) + y = rng.random_sample(n) * 40 - 20 + bspl = make_interp_spline(x, y, k=k) + # invalid vector of knots (should be a 1D non-descending array) + # here the actual vector of knots is reversed, so it is invalid + with assert_raises(ValueError): + BSpline.design_matrix(x, bspl.t[::-1], k) + k = 2 + t = [0., 1., 2., 3., 4., 5.] + x = [1., 2., 3., 4.] + # out of bounds + with assert_raises(ValueError): + BSpline.design_matrix(x, t, k) + + @pytest.mark.parametrize('bc_type', ['natural', 'clamped', + 'periodic', 'not-a-knot']) + def test_from_power_basis(self, bc_type): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(20)) + y = rng.random(20) + if bc_type == 'periodic': + y[-1] = y[0] + cb = CubicSpline(x, y, bc_type=bc_type) + bspl = BSpline.from_power_basis(cb, bc_type=bc_type) + xx = np.linspace(0, 1, 20) + xp_assert_close(cb(xx), bspl(xx), atol=1e-15) + bspl_new = make_interp_spline(x, y, bc_type=bc_type) + xp_assert_close(bspl.c, bspl_new.c, atol=1e-15) + + @pytest.mark.parametrize('bc_type', ['natural', 'clamped', + 'periodic', 'not-a-knot']) + def test_from_power_basis_complex(self, bc_type): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(20)) + y = rng.random(20) + rng.random(20) * 1j + if bc_type == 'periodic': + y[-1] = y[0] + cb = CubicSpline(x, y, bc_type=bc_type) + bspl = BSpline.from_power_basis(cb, bc_type=bc_type) + bspl_new_real = make_interp_spline(x, y.real, bc_type=bc_type) + bspl_new_imag = make_interp_spline(x, y.imag, bc_type=bc_type) + xp_assert_close(bspl.c, bspl_new_real.c + 1j * bspl_new_imag.c, atol=1e-15) + + def test_from_power_basis_exmp(self): + ''' + For x = [0, 1, 2, 3, 4] and y = [1, 1, 1, 1, 1] + the coefficients of Cubic Spline in the power basis: + + $[[0, 0, 0, 0, 0],\\$ + $[0, 0, 0, 0, 0],\\$ + $[0, 0, 0, 0, 0],\\$ + $[1, 1, 1, 1, 1]]$ + + It could be shown explicitly that coefficients of the interpolating + function in B-spline basis are c = [1, 1, 1, 1, 1, 1, 1] + ''' + x = np.array([0, 1, 2, 3, 4]) + y = np.array([1, 1, 1, 1, 1]) + bspl = BSpline.from_power_basis(CubicSpline(x, y, bc_type='natural'), + bc_type='natural') + xp_assert_close(bspl.c, [1.0, 1, 1, 1, 1, 1, 1], atol=1e-15) + + def test_read_only(self): + # BSpline must work on read-only knots and coefficients. + t = np.array([0, 1]) + c = np.array([3.0]) + t.setflags(write=False) + c.setflags(write=False) + + xx = np.linspace(0, 1, 10) + xx.setflags(write=False) + + b = BSpline(t=t, c=c, k=0) + xp_assert_close(b(xx), np.ones_like(xx) * 3.0) + + @pytest.mark.thread_unsafe + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to BSpline + b = _make_random_spline() + + def worker_fn(_, b): + t, _, k = b.tck + xx = np.linspace(t[k], t[-k-1], 10000) + b(xx) + + _run_concurrent_barrier(10, worker_fn, b) + + + def test_memmap(self, tmpdir): + # Make sure that memmaps can be used as t and c atrributes after the + # spline has been constructed. This is similar to what happens in a + # scikit-learn context, where joblib can create read-only memmap to + # share objects between workers. For more details, see + # https://github.com/scipy/scipy/issues/22143 + b = _make_random_spline() + xx = np.linspace(0, 1, 10) + + expected = b(xx) + + tid = threading.get_native_id() + t_mm = np.memmap(str(tmpdir.join(f't{tid}.dat')), mode='w+', + dtype=b.t.dtype, shape=b.t.shape) + t_mm[:] = b.t + c_mm = np.memmap(str(tmpdir.join(f'c{tid}.dat')), mode='w+', + dtype=b.c.dtype, shape=b.c.shape) + c_mm[:] = b.c + b.t = t_mm + b.c = c_mm + + xp_assert_close(b(xx), expected) + +class TestInsert: + + @pytest.mark.parametrize('xval', [0.0, 1.0, 2.5, 4, 6.5, 7.0]) + def test_insert(self, xval): + # insert a knot, incl edges (0.0, 7.0) and exactly at an existing knot (4.0) + x = np.arange(8) + y = np.sin(x)**3 + spl = make_interp_spline(x, y, k=3) + + spl_1f = insert(xval, spl) # FITPACK + spl_1 = spl.insert_knot(xval) + + xp_assert_close(spl_1.t, spl_1f.t, atol=1e-15) + xp_assert_close(spl_1.c, spl_1f.c[:-spl.k-1], atol=1e-15) + + # knot insertion preserves values, unless multiplicity >= k+1 + xx = x if xval != x[-1] else x[:-1] + xx = np.r_[xx, 0.5*(x[1:] + x[:-1])] + xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) + + # ... repeat with ndim > 1 + y1 = np.cos(x)**3 + spl_y1 = make_interp_spline(x, y1, k=3) + spl_yy = make_interp_spline(x, np.c_[y, y1], k=3) + spl_yy1 = spl_yy.insert_knot(xval) + + xp_assert_close(spl_yy1.t, spl_1.t, atol=1e-15) + xp_assert_close(spl_yy1.c, np.c_[spl.insert_knot(xval).c, + spl_y1.insert_knot(xval).c], atol=1e-15) + + xx = x if xval != x[-1] else x[:-1] + xx = np.r_[xx, 0.5*(x[1:] + x[:-1])] + xp_assert_close(spl_yy(xx), spl_yy1(xx), atol=1e-15) + + + @pytest.mark.parametrize( + 'xval, m', [(0.0, 2), (1.0, 3), (1.5, 5), (4, 2), (7.0, 2)] + ) + def test_insert_multi(self, xval, m): + x = np.arange(8) + y = np.sin(x)**3 + spl = make_interp_spline(x, y, k=3) + + spl_1f = insert(xval, spl, m=m) + spl_1 = spl.insert_knot(xval, m) + + xp_assert_close(spl_1.t, spl_1f.t, atol=1e-15) + xp_assert_close(spl_1.c, spl_1f.c[:-spl.k-1], atol=1e-15) + + xx = x if xval != x[-1] else x[:-1] + xx = np.r_[xx, 0.5*(x[1:] + x[:-1])] + xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) + + def test_insert_random(self): + rng = np.random.default_rng(12345) + n, k = 11, 3 + + t = np.sort(rng.uniform(size=n+k+1)) + c = rng.uniform(size=(n, 3, 2)) + spl = BSpline(t, c, k) + + xv = rng.uniform(low=t[k+1], high=t[-k-1]) + spl_1 = spl.insert_knot(xv) + + xx = rng.uniform(low=t[k+1], high=t[-k-1], size=33) + xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) + + @pytest.mark.parametrize('xv', [0, 0.1, 2.0, 4.0, 4.5, # l.h. edge + 5.5, 6.0, 6.1, 7.0] # r.h. edge + ) + def test_insert_periodic(self, xv): + x = np.arange(8) + y = np.sin(x)**3 + tck = splrep(x, y, k=3) + spl = BSpline(*tck, extrapolate="periodic") + + spl_1 = spl.insert_knot(xv) + tf, cf, k = insert(xv, spl.tck, per=True) + + xp_assert_close(spl_1.t, tf, atol=1e-15) + xp_assert_close(spl_1.c[:-k-1], cf[:-k-1], atol=1e-15) + + xx = np.random.default_rng(1234).uniform(low=0, high=7, size=41) + xp_assert_close(spl_1(xx), splev(xx, (tf, cf, k)), atol=1e-15) + + @pytest.mark.parametrize('extrapolate', [None, 'periodic']) + def test_complex(self, extrapolate): + x = np.arange(8)*2*np.pi + y_re, y_im = np.sin(x), np.cos(x) + + spl = make_interp_spline(x, y_re + 1j*y_im, k=3) + spl.extrapolate = extrapolate + + spl_re = make_interp_spline(x, y_re, k=3) + spl_re.extrapolate = extrapolate + + spl_im = make_interp_spline(x, y_im, k=3) + spl_im.extrapolate = extrapolate + + xv = 3.5 + spl_1 = spl.insert_knot(xv) + spl_1re = spl_re.insert_knot(xv) + spl_1im = spl_im.insert_knot(xv) + + xp_assert_close(spl_1.t, spl_1re.t, atol=1e-15) + xp_assert_close(spl_1.t, spl_1im.t, atol=1e-15) + xp_assert_close(spl_1.c, spl_1re.c + 1j*spl_1im.c, atol=1e-15) + + def test_insert_periodic_too_few_internal_knots(self): + # both FITPACK and spl.insert_knot raise when there's not enough + # internal knots to make a periodic extension. + # Below the internal knots are 2, 3, , 4, 5 + # ^ + # 2, 3, 3.5, 4, 5 + # so two knots from each side from the new one, while need at least + # from either left or right. + xv = 3.5 + k = 3 + t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1)) + c = np.ones(len(t) - k - 1) + spl = BSpline(t, c, k, extrapolate="periodic") + + with assert_raises(ValueError): + insert(xv, (t, c, k), per=True) + + with assert_raises(ValueError): + spl.insert_knot(xv) + + def test_insert_no_extrap(self): + k = 3 + t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1)) + c = np.ones(len(t) - k - 1) + spl = BSpline(t, c, k) + + with assert_raises(ValueError): + spl.insert_knot(-1) + + with assert_raises(ValueError): + spl.insert_knot(8) + + with assert_raises(ValueError): + spl.insert_knot(3, m=0) + + +def test_knots_multiplicity(): + # Take a spline w/ random coefficients, throw in knots of varying + # multiplicity. + + def check_splev(b, j, der=0, atol=1e-14, rtol=1e-14): + # check evaluations against FITPACK, incl extrapolations + t, c, k = b.tck + x = np.unique(t) + x = np.r_[t[0]-0.1, 0.5*(x[1:] + x[:1]), t[-1]+0.1] + xp_assert_close(splev(x, (t, c, k), der), b(x, der), + atol=atol, rtol=rtol, err_msg=f'der = {der} k = {b.k}') + + # test loop itself + # [the index `j` is for interpreting the traceback in case of a failure] + for k in [1, 2, 3, 4, 5]: + b = _make_random_spline(k=k) + for j, b1 in enumerate(_make_multiples(b)): + check_splev(b1, j) + for der in range(1, k+1): + check_splev(b1, j, der, 1e-12, 1e-12) + + +### stolen from @pv, verbatim +def _naive_B(x, k, i, t): + """ + Naive way to compute B-spline basis functions. Useful only for testing! + computes B(x; t[i],..., t[i+k+1]) + """ + if k == 0: + return 1.0 if t[i] <= x < t[i+1] else 0.0 + if t[i+k] == t[i]: + c1 = 0.0 + else: + c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t) + if t[i+k+1] == t[i+1]: + c2 = 0.0 + else: + c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t) + return (c1 + c2) + + +### stolen from @pv, verbatim +def _naive_eval(x, t, c, k): + """ + Naive B-spline evaluation. Useful only for testing! + """ + if x == t[k]: + i = k + else: + i = np.searchsorted(t, x) - 1 + assert t[i] <= x <= t[i+1] + assert i >= k and i < len(t) - k + return sum(c[i-j] * _naive_B(x, k, i-j, t) for j in range(0, k+1)) + + +def _naive_eval_2(x, t, c, k): + """Naive B-spline evaluation, another way.""" + n = len(t) - (k+1) + assert n >= k+1 + assert len(c) >= n + assert t[k] <= x <= t[n] + return sum(c[i] * _naive_B(x, k, i, t) for i in range(n)) + + +def _sum_basis_elements(x, t, c, k): + n = len(t) - (k+1) + assert n >= k+1 + assert len(c) >= n + s = 0. + for i in range(n): + b = BSpline.basis_element(t[i:i+k+2], extrapolate=False)(x) + s += c[i] * np.nan_to_num(b) # zero out out-of-bounds elements + return s + + +def B_012(x): + """ A linear B-spline function B(x | 0, 1, 2).""" + x = np.atleast_1d(x) + return np.piecewise(x, [(x < 0) | (x > 2), + (x >= 0) & (x < 1), + (x >= 1) & (x <= 2)], + [lambda x: 0., lambda x: x, lambda x: 2.-x]) + + +def B_0123(x, der=0): + """A quadratic B-spline function B(x | 0, 1, 2, 3).""" + x = np.atleast_1d(x) + conds = [x < 1, (x > 1) & (x < 2), x > 2] + if der == 0: + funcs = [lambda x: x*x/2., + lambda x: 3./4 - (x-3./2)**2, + lambda x: (3.-x)**2 / 2] + elif der == 2: + funcs = [lambda x: 1., + lambda x: -2., + lambda x: 1.] + else: + raise ValueError(f'never be here: der={der}') + pieces = np.piecewise(x, conds, funcs) + return pieces + + +def _make_random_spline(n=35, k=3): + rng = np.random.RandomState(123) + t = np.sort(rng.random(n+k+1)) + c = rng.random(n) + return BSpline.construct_fast(t, c, k) + + +def _make_multiples(b): + """Increase knot multiplicity.""" + c, k = b.c, b.k + + t1 = b.t.copy() + t1[17:19] = t1[17] + t1[22] = t1[21] + yield BSpline(t1, c, k) + + t1 = b.t.copy() + t1[:k+1] = t1[0] + yield BSpline(t1, c, k) + + t1 = b.t.copy() + t1[-k-1:] = t1[-1] + yield BSpline(t1, c, k) + + +class TestInterop: + # + # Test that FITPACK-based spl* functions can deal with BSpline objects + # + def setup_method(self): + xx = np.linspace(0, 4.*np.pi, 41) + yy = np.cos(xx) + b = make_interp_spline(xx, yy) + self.tck = (b.t, b.c, b.k) + self.xx, self.yy, self.b = xx, yy, b + + self.xnew = np.linspace(0, 4.*np.pi, 21) + + c2 = np.c_[b.c, b.c, b.c] + self.c2 = np.dstack((c2, c2)) + self.b2 = BSpline(b.t, self.c2, b.k) + + def test_splev(self): + xnew, b, b2 = self.xnew, self.b, self.b2 + + # check that splev works with 1-D array of coefficients + # for array and scalar `x` + xp_assert_close(splev(xnew, b), + b(xnew), atol=1e-15, rtol=1e-15) + xp_assert_close(splev(xnew, b.tck), + b(xnew), atol=1e-15, rtol=1e-15) + xp_assert_close(np.asarray([splev(x, b) for x in xnew]), + b(xnew), atol=1e-15, rtol=1e-15) + + # With N-D coefficients, there's a quirck: + # splev(x, BSpline) is equivalent to BSpline(x) + with assert_raises(ValueError, match="Calling splev.. with BSpline"): + splev(xnew, b2) + + # However, splev(x, BSpline.tck) needs some transposes. This is because + # BSpline interpolates along the first axis, while the legacy FITPACK + # wrapper does list(map(...)) which effectively interpolates along the + # last axis. Like so: + sh = tuple(range(1, b2.c.ndim)) + (0,) # sh = (1, 2, 0) + cc = b2.c.transpose(sh) + tck = (b2.t, cc, b2.k) + xp_assert_close(np.asarray(splev(xnew, tck)), + b2(xnew).transpose(sh), atol=1e-15, rtol=1e-15) + + def test_splrep(self): + x, y = self.xx, self.yy + # test that "new" splrep is equivalent to _impl.splrep + tck = splrep(x, y) + t, c, k = _impl.splrep(x, y) + xp_assert_close(tck[0], t, atol=1e-15) + xp_assert_close(tck[1], c, atol=1e-15) + assert tck[2] == k + + # also cover the `full_output=True` branch + tck_f, _, _, _ = splrep(x, y, full_output=True) + xp_assert_close(tck_f[0], t, atol=1e-15) + xp_assert_close(tck_f[1], c, atol=1e-15) + assert tck_f[2] == k + + # test that the result of splrep roundtrips with splev: + # evaluate the spline on the original `x` points + yy = splev(x, tck) + xp_assert_close(y, yy, atol=1e-15) + + # ... and also it roundtrips if wrapped in a BSpline + b = BSpline(*tck) + xp_assert_close(y, b(x), atol=1e-15) + + def test_splrep_errors(self): + # test that both "old" and "new" splrep raise for an N-D ``y`` array + # with n > 1 + x, y = self.xx, self.yy + y2 = np.c_[y, y] + with assert_raises(ValueError): + splrep(x, y2) + with assert_raises(ValueError): + _impl.splrep(x, y2) + + # input below minimum size + with assert_raises(TypeError, match="m > k must hold"): + splrep(x[:3], y[:3]) + with assert_raises(TypeError, match="m > k must hold"): + _impl.splrep(x[:3], y[:3]) + + def test_splprep(self): + x = np.arange(15, dtype=np.float64).reshape((3, 5)) + b, u = splprep(x) + tck, u1 = _impl.splprep(x) + + # test the roundtrip with splev for both "old" and "new" output + xp_assert_close(u, u1, atol=1e-15) + xp_assert_close(np.asarray(splev(u, b)), x, atol=1e-15) + xp_assert_close(np.asarray(splev(u, tck)), x, atol=1e-15) + + # cover the ``full_output=True`` branch + (b_f, u_f), _, _, _ = splprep(x, s=0, full_output=True) + xp_assert_close(u, u_f, atol=1e-15) + xp_assert_close(np.asarray(splev(u_f, b_f)), x, atol=1e-15) + + def test_splprep_errors(self): + # test that both "old" and "new" code paths raise for x.ndim > 2 + x = np.arange(3*4*5).reshape((3, 4, 5)) + with assert_raises(ValueError, match="too many values to unpack"): + splprep(x) + with assert_raises(ValueError, match="too many values to unpack"): + _impl.splprep(x) + + # input below minimum size + x = np.linspace(0, 40, num=3) + with assert_raises(TypeError, match="m > k must hold"): + splprep([x]) + with assert_raises(TypeError, match="m > k must hold"): + _impl.splprep([x]) + + # automatically calculated parameters are non-increasing + # see gh-7589 + x = [-50.49072266, -50.49072266, -54.49072266, -54.49072266] + with assert_raises(ValueError, match="Invalid inputs"): + splprep([x]) + with assert_raises(ValueError, match="Invalid inputs"): + _impl.splprep([x]) + + # given non-increasing parameter values u + x = [1, 3, 2, 4] + u = [0, 0.3, 0.2, 1] + with assert_raises(ValueError, match="Invalid inputs"): + splprep(*[[x], None, u]) + + def test_sproot(self): + b, b2 = self.b, self.b2 + roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi + # sproot accepts a BSpline obj w/ 1-D coef array + xp_assert_close(sproot(b), roots, atol=1e-7, rtol=1e-7) + xp_assert_close(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7) + + # ... and deals with trailing dimensions if coef array is N-D + with assert_raises(ValueError, match="Calling sproot.. with BSpline"): + sproot(b2, mest=50) + + # and legacy behavior is preserved for a tck tuple w/ N-D coef + c2r = b2.c.transpose(1, 2, 0) + rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50)) + assert rr.shape == (3, 2, 4) + xp_assert_close(rr - roots, np.zeros_like(rr), atol=1e-12) + + def test_splint(self): + # test that splint accepts BSpline objects + b, b2 = self.b, self.b2 + + xp_assert_close(splint(0, 1, b), + splint(0, 1, b.tck), atol=1e-14, check_0d=False) + xp_assert_close(splint(0, 1, b), + b.integrate(0, 1), atol=1e-14, check_0d=False) + + # ... and deals with N-D arrays of coefficients + with assert_raises(ValueError, match="Calling splint.. with BSpline"): + splint(0, 1, b2) + + # and the legacy behavior is preserved for a tck tuple w/ N-D coef + c2r = b2.c.transpose(1, 2, 0) + integr = np.asarray(splint(0, 1, (b2.t, c2r, b2.k))) + assert integr.shape == (3, 2) + xp_assert_close(integr, + splint(0, 1, b), atol=1e-14, check_shape=False) + + def test_splder(self): + for b in [self.b, self.b2]: + # pad the c array (FITPACK convention) + ct = len(b.t) - len(b.c) + b_c = b.c.copy() + if ct > 0: + b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])] + + for n in [1, 2, 3]: + bd = splder(b) + tck_d = _impl.splder((b.t.copy(), b_c, b.k)) + xp_assert_close(bd.t, tck_d[0], atol=1e-15) + xp_assert_close(bd.c, tck_d[1], atol=1e-15) + assert bd.k == tck_d[2] + assert isinstance(bd, BSpline) + assert isinstance(tck_d, tuple) # back-compat: tck in and out + + def test_splantider(self): + for b in [self.b, self.b2]: + # pad the c array (FITPACK convention) + ct = len(b.t) - len(b.c) + b_c = b.c.copy() + if ct > 0: + b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])] + + for n in [1, 2, 3]: + bd = splantider(b) + tck_d = _impl.splantider((b.t.copy(), b_c, b.k)) + xp_assert_close(bd.t, tck_d[0], atol=1e-15) + xp_assert_close(bd.c, tck_d[1], atol=1e-15) + assert bd.k == tck_d[2] + assert isinstance(bd, BSpline) + assert isinstance(tck_d, tuple) # back-compat: tck in and out + + def test_insert(self): + b, b2, xx = self.b, self.b2, self.xx + + j = b.t.size // 2 + tn = 0.5*(b.t[j] + b.t[j+1]) + + bn, tck_n = insert(tn, b), insert(tn, (b.t, b.c, b.k)) + xp_assert_close(splev(xx, bn), + splev(xx, tck_n), atol=1e-15) + assert isinstance(bn, BSpline) + assert isinstance(tck_n, tuple) # back-compat: tck in, tck out + + # for N-D array of coefficients, BSpline.c needs to be transposed + # after that, the results are equivalent. + sh = tuple(range(b2.c.ndim)) + c_ = b2.c.transpose(sh[1:] + (0,)) + tck_n2 = insert(tn, (b2.t, c_, b2.k)) + + bn2 = insert(tn, b2) + + # need a transpose for comparing the results, cf test_splev + xp_assert_close(np.asarray(splev(xx, tck_n2)).transpose(2, 0, 1), + bn2(xx), atol=1e-15) + assert isinstance(bn2, BSpline) + assert isinstance(tck_n2, tuple) # back-compat: tck in, tck out + + +class TestInterp: + # + # Test basic ways of constructing interpolating splines. + # + xx = np.linspace(0., 2.*np.pi) + yy = np.sin(xx) + + def test_non_int_order(self): + with assert_raises(TypeError): + make_interp_spline(self.xx, self.yy, k=2.5) + + def test_order_0(self): + b = make_interp_spline(self.xx, self.yy, k=0) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + b = make_interp_spline(self.xx, self.yy, k=0, axis=-1) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + + def test_linear(self): + b = make_interp_spline(self.xx, self.yy, k=1) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + b = make_interp_spline(self.xx, self.yy, k=1, axis=-1) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + + @pytest.mark.parametrize('k', [0, 1, 2, 3]) + def test_incompatible_x_y(self, k): + x = [0, 1, 2, 3, 4, 5] + y = [0, 1, 2, 3, 4, 5, 6, 7] + with assert_raises(ValueError, match="Shapes of x"): + make_interp_spline(x, y, k=k) + + @pytest.mark.parametrize('k', [0, 1, 2, 3]) + def test_broken_x(self, k): + x = [0, 1, 1, 2, 3, 4] # duplicates + y = [0, 1, 2, 3, 4, 5] + with assert_raises(ValueError, match="x to not have duplicates"): + make_interp_spline(x, y, k=k) + + x = [0, 2, 1, 3, 4, 5] # unsorted + with assert_raises(ValueError, match="Expect x to be a 1D strictly"): + make_interp_spline(x, y, k=k) + + x = [0, 1, 2, 3, 4, 5] + x = np.asarray(x).reshape((1, -1)) # 1D + with assert_raises(ValueError, match="Expect x to be a 1D strictly"): + make_interp_spline(x, y, k=k) + + def test_not_a_knot(self): + for k in [2, 3, 4, 5, 6, 7]: + b = make_interp_spline(self.xx, self.yy, k) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + + def test_periodic(self): + # k = 5 here for more derivatives + b = make_interp_spline(self.xx, self.yy, k=5, bc_type='periodic') + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + # in periodic case it is expected equality of k-1 first + # derivatives at the boundaries + for i in range(1, 5): + xp_assert_close(b(self.xx[0], nu=i), b(self.xx[-1], nu=i), atol=1e-11) + # tests for axis=-1 + b = make_interp_spline(self.xx, self.yy, k=5, bc_type='periodic', axis=-1) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + for i in range(1, 5): + xp_assert_close(b(self.xx[0], nu=i), b(self.xx[-1], nu=i), atol=1e-11) + + @pytest.mark.parametrize('k', [2, 3, 4, 5, 6, 7]) + def test_periodic_random(self, k): + # tests for both cases (k > n and k <= n) + n = 5 + rng = np.random.RandomState(1234) + x = np.sort(rng.random_sample(n) * 10) + y = rng.random_sample(n) * 100 + y[0] = y[-1] + b = make_interp_spline(x, y, k=k, bc_type='periodic') + xp_assert_close(b(x), y, atol=1e-14) + + def test_periodic_axis(self): + n = self.xx.shape[0] + rng = np.random.RandomState(1234) + x = rng.random_sample(n) * 2 * np.pi + x = np.sort(x) + x[0] = 0. + x[-1] = 2 * np.pi + y = np.zeros((2, n)) + y[0] = np.sin(x) + y[1] = np.cos(x) + b = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1) + for i in range(n): + xp_assert_close(b(x[i]), y[:, i], atol=1e-14) + xp_assert_close(b(x[0]), b(x[-1]), atol=1e-14) + + def test_periodic_points_exception(self): + # first and last points should match when periodic case expected + rng = np.random.RandomState(1234) + k = 5 + n = 8 + x = np.sort(rng.random_sample(n)) + y = rng.random_sample(n) + y[0] = y[-1] - 1 # to be sure that they are not equal + with assert_raises(ValueError): + make_interp_spline(x, y, k=k, bc_type='periodic') + + def test_periodic_knots_exception(self): + # `periodic` case does not work with passed vector of knots + rng = np.random.RandomState(1234) + k = 3 + n = 7 + x = np.sort(rng.random_sample(n)) + y = rng.random_sample(n) + t = np.zeros(n + 2 * k) + with assert_raises(ValueError): + make_interp_spline(x, y, k, t, 'periodic') + + @pytest.mark.parametrize('k', [2, 3, 4, 5]) + def test_periodic_splev(self, k): + # comparison values of periodic b-spline with splev + b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic') + tck = splrep(self.xx, self.yy, per=True, k=k) + spl = splev(self.xx, tck) + xp_assert_close(spl, b(self.xx), atol=1e-14) + + # comparison derivatives of periodic b-spline with splev + for i in range(1, k): + spl = splev(self.xx, tck, der=i) + xp_assert_close(spl, b(self.xx, nu=i), atol=1e-10) + + def test_periodic_cubic(self): + # comparison values of cubic periodic b-spline with CubicSpline + b = make_interp_spline(self.xx, self.yy, k=3, bc_type='periodic') + cub = CubicSpline(self.xx, self.yy, bc_type='periodic') + xp_assert_close(b(self.xx), cub(self.xx), atol=1e-14) + + # edge case: Cubic interpolation on 3 points + rng = np.random.RandomState(1234) + n = 3 + x = np.sort(rng.random_sample(n) * 10) + y = rng.random_sample(n) * 100 + y[0] = y[-1] + b = make_interp_spline(x, y, k=3, bc_type='periodic') + cub = CubicSpline(x, y, bc_type='periodic') + xp_assert_close(b(x), cub(x), atol=1e-14) + + def test_periodic_full_matrix(self): + # comparison values of cubic periodic b-spline with + # solution of the system with full matrix + k = 3 + b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic') + t = _periodic_knots(self.xx, k) + c = _make_interp_per_full_matr(self.xx, self.yy, t, k) + b1 = np.vectorize(lambda x: _naive_eval(x, t, c, k)) + xp_assert_close(b(self.xx), b1(self.xx), atol=1e-14) + + def test_quadratic_deriv(self): + der = [(1, 8.)] # order, value: f'(x) = 8. + + # derivative at right-hand edge + b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(None, der)) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + xp_assert_close( + b(self.xx[-1], 1), der[0][1], atol=1e-14, rtol=1e-14, check_0d=False + ) + + # derivative at left-hand edge + b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(der, None)) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + xp_assert_close( + b(self.xx[0], 1), der[0][1], atol=1e-14, rtol=1e-14, check_0d=False + ) + + def test_cubic_deriv(self): + k = 3 + + # first derivatives at left & right edges: + der_l, der_r = [(1, 3.)], [(1, 4.)] + b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r)) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + xp_assert_close(np.asarray([b(self.xx[0], 1), b(self.xx[-1], 1)]), + np.asarray([der_l[0][1], der_r[0][1]]), atol=1e-14, rtol=1e-14) + + # 'natural' cubic spline, zero out 2nd derivatives at the boundaries + der_l, der_r = [(2, 0)], [(2, 0)] + b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r)) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + + def test_quintic_derivs(self): + k, n = 5, 7 + x = np.arange(n).astype(np.float64) + y = np.sin(x) + der_l = [(1, -12.), (2, 1)] + der_r = [(1, 8.), (2, 3.)] + b = make_interp_spline(x, y, k=k, bc_type=(der_l, der_r)) + xp_assert_close(b(x), y, atol=1e-14, rtol=1e-14) + xp_assert_close(np.asarray([b(x[0], 1), b(x[0], 2)]), + np.asarray([val for (nu, val) in der_l])) + xp_assert_close(np.asarray([b(x[-1], 1), b(x[-1], 2)]), + np.asarray([val for (nu, val) in der_r])) + + @pytest.mark.xfail(reason='unstable') + def test_cubic_deriv_unstable(self): + # 1st and 2nd derivative at x[0], no derivative information at x[-1] + # The problem is not that it fails [who would use this anyway], + # the problem is that it fails *silently*, and I've no idea + # how to detect this sort of instability. + # In this particular case: it's OK for len(t) < 20, goes haywire + # at larger `len(t)`. + k = 3 + t = _augknt(self.xx, k) + + der_l = [(1, 3.), (2, 4.)] + b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None)) + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + + def test_knots_not_data_sites(self): + # Knots need not coincide with the data sites. + # use a quadratic spline, knots are at data averages, + # two additional constraints are zero 2nd derivatives at edges + k = 2 + t = np.r_[(self.xx[0],)*(k+1), + (self.xx[1:] + self.xx[:-1]) / 2., + (self.xx[-1],)*(k+1)] + b = make_interp_spline(self.xx, self.yy, k, t, + bc_type=([(2, 0)], [(2, 0)])) + + xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14) + xp_assert_close(b(self.xx[0], 2), np.asarray(0.0), atol=1e-14) + xp_assert_close(b(self.xx[-1], 2), np.asarray(0.0), atol=1e-14) + + def test_minimum_points_and_deriv(self): + # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and + # f'(0) = 0, f'(1) = 3. + k = 3 + x = [0., 1.] + y = [0., 1.] + b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)])) + + xx = np.linspace(0., 1.) + yy = xx**3 + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + def test_deriv_spec(self): + # If one of the derivatives is omitted, the spline definition is + # incomplete. + x = y = [1.0, 2, 3, 4, 5, 6] + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=([(1, 0.)], None)) + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=(1, 0.)) + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=[(1, 0.)]) + + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=42) + + # CubicSpline expects`bc_type=(left_pair, right_pair)`, while + # here we expect `bc_type=(iterable, iterable)`. + l, r = (1, 0.0), (1, 0.0) + with assert_raises(ValueError): + make_interp_spline(x, y, bc_type=(l, r)) + + def test_deriv_order_too_large(self): + x = np.arange(7) + y = x**2 + l, r = [(6, 0)], [(1, 0)] # 6th derivative = 0 at x[0] for k=3 + with assert_raises(ValueError, match="Bad boundary conditions at 0."): + # cannot fix 6th derivative at x[0]: does not segfault + make_interp_spline(x, y, bc_type=(l, r)) + + l, r = [(1, 0)], [(-6, 0)] # derivative order < 0 at x[-1] + with assert_raises(ValueError, match="Bad boundary conditions at 6."): + # does not segfault + make_interp_spline(x, y, bc_type=(l, r)) + + def test_complex(self): + k = 3 + xx = self.xx + yy = self.yy + 1.j*self.yy + + # first derivatives at left & right edges: + der_l, der_r = [(1, 3.j)], [(1, 4.+2.j)] + b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r)) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + xp_assert_close( + b(xx[0], 1), der_l[0][1], atol=1e-14, rtol=1e-14, check_0d=False + ) + xp_assert_close( + b(xx[-1], 1), der_r[0][1], atol=1e-14, rtol=1e-14, check_0d=False + ) + + # also test zero and first order + for k in (0, 1): + b = make_interp_spline(xx, yy, k=k) + xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14) + + def test_int_xy(self): + x = np.arange(10).astype(int) + y = np.arange(10).astype(int) + + # Cython chokes on "buffer type mismatch" (construction) or + # "no matching signature found" (evaluation) + for k in (0, 1, 2, 3): + b = make_interp_spline(x, y, k=k) + b(x) + + def test_sliced_input(self): + # Cython code chokes on non C contiguous arrays + xx = np.linspace(-1, 1, 100) + + x = xx[::5] + y = xx[::5] + + for k in (0, 1, 2, 3): + make_interp_spline(x, y, k=k) + + def test_check_finite(self): + # check_finite defaults to True; nans and such trigger a ValueError + x = np.arange(10).astype(float) + y = x**2 + + for z in [np.nan, np.inf, -np.inf]: + y[-1] = z + assert_raises(ValueError, make_interp_spline, x, y) + + @pytest.mark.parametrize('k', [1, 2, 3, 5]) + def test_list_input(self, k): + # regression test for gh-8714: TypeError for x, y being lists and k=2 + x = list(range(10)) + y = [a**2 for a in x] + make_interp_spline(x, y, k=k) + + def test_multiple_rhs(self): + yy = np.c_[np.sin(self.xx), np.cos(self.xx)] + der_l = [(1, [1., 2.])] + der_r = [(1, [3., 4.])] + + b = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r)) + xp_assert_close(b(self.xx), yy, atol=1e-14, rtol=1e-14) + xp_assert_close(b(self.xx[0], 1), der_l[0][1], atol=1e-14, rtol=1e-14) + xp_assert_close(b(self.xx[-1], 1), der_r[0][1], atol=1e-14, rtol=1e-14) + + def test_shapes(self): + rng = np.random.RandomState(1234) + k, n = 3, 22 + x = np.sort(rng.random(size=n)) + y = rng.random(size=(n, 5, 6, 7)) + + b = make_interp_spline(x, y, k) + assert b.c.shape == (n, 5, 6, 7) + + # now throw in some derivatives + d_l = [(1, rng.random((5, 6, 7)))] + d_r = [(1, rng.random((5, 6, 7)))] + b = make_interp_spline(x, y, k, bc_type=(d_l, d_r)) + assert b.c.shape == (n + k - 1, 5, 6, 7) + + def test_string_aliases(self): + yy = np.sin(self.xx) + + # a single string is duplicated + b1 = make_interp_spline(self.xx, yy, k=3, bc_type='natural') + b2 = make_interp_spline(self.xx, yy, k=3, bc_type=([(2, 0)], [(2, 0)])) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # two strings are handled + b1 = make_interp_spline(self.xx, yy, k=3, + bc_type=('natural', 'clamped')) + b2 = make_interp_spline(self.xx, yy, k=3, + bc_type=([(2, 0)], [(1, 0)])) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # one-sided BCs are OK + b1 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, 'clamped')) + b2 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, [(1, 0.0)])) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # 'not-a-knot' is equivalent to None + b1 = make_interp_spline(self.xx, yy, k=3, bc_type='not-a-knot') + b2 = make_interp_spline(self.xx, yy, k=3, bc_type=None) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # unknown strings do not pass + with assert_raises(ValueError): + make_interp_spline(self.xx, yy, k=3, bc_type='typo') + + # string aliases are handled for 2D values + yy = np.c_[np.sin(self.xx), np.cos(self.xx)] + der_l = [(1, [0., 0.])] + der_r = [(2, [0., 0.])] + b2 = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r)) + b1 = make_interp_spline(self.xx, yy, k=3, + bc_type=('clamped', 'natural')) + xp_assert_close(b1.c, b2.c, atol=1e-15) + + # ... and for N-D values: + rng = np.random.RandomState(1234) + k, n = 3, 22 + x = np.sort(rng.random(size=n)) + y = rng.random(size=(n, 5, 6, 7)) + + # now throw in some derivatives + d_l = [(1, np.zeros((5, 6, 7)))] + d_r = [(1, np.zeros((5, 6, 7)))] + b1 = make_interp_spline(x, y, k, bc_type=(d_l, d_r)) + b2 = make_interp_spline(x, y, k, bc_type='clamped') + xp_assert_close(b1.c, b2.c, atol=1e-15) + + def test_full_matrix(self): + rng = np.random.RandomState(1234) + k, n = 3, 7 + x = np.sort(rng.random(size=n)) + y = rng.random(size=n) + t = _not_a_knot(x, k) + + b = make_interp_spline(x, y, k, t) + cf = make_interp_full_matr(x, y, t, k) + xp_assert_close(b.c, cf, atol=1e-14, rtol=1e-14) + + def test_woodbury(self): + ''' + Random elements in diagonal matrix with blocks in the + left lower and right upper corners checking the + implementation of Woodbury algorithm. + ''' + rng = np.random.RandomState(1234) + n = 201 + for k in range(3, 32, 2): + offset = int((k - 1) / 2) + a = np.diagflat(rng.random((1, n))) + for i in range(1, offset + 1): + a[:-i, i:] += np.diagflat(rng.random((1, n - i))) + a[i:, :-i] += np.diagflat(rng.random((1, n - i))) + ur = rng.random((offset, offset)) + a[:offset, -offset:] = ur + ll = rng.random((offset, offset)) + a[-offset:, :offset] = ll + d = np.zeros((k, n)) + for i, j in enumerate(range(offset, -offset - 1, -1)): + if j < 0: + d[i, :j] = np.diagonal(a, offset=j) + else: + d[i, j:] = np.diagonal(a, offset=j) + b = rng.random(n) + xp_assert_close(_woodbury_algorithm(d, ur, ll, b, k), + np.linalg.solve(a, b), atol=1e-14) + + +def make_interp_full_matr(x, y, t, k): + """Assemble an spline order k with knots t to interpolate + y(x) using full matrices. + Not-a-knot BC only. + + This routine is here for testing only (even though it's functional). + """ + assert x.size == y.size + assert t.size == x.size + k + 1 + n = x.size + + A = np.zeros((n, n), dtype=np.float64) + + for j in range(n): + xval = x[j] + if xval == t[k]: + left = k + else: + left = np.searchsorted(t, xval) - 1 + + # fill a row + bb = _dierckx.evaluate_all_bspl(t, k, xval, left) + A[j, left-k:left+1] = bb + + c = sl.solve(A, y) + return c + + +def make_lsq_full_matrix(x, y, t, k=3): + """Make the least-square spline, full matrices.""" + x, y, t = map(np.asarray, (x, y, t)) + m = x.size + n = t.size - k - 1 + + A = np.zeros((m, n), dtype=np.float64) + + for j in range(m): + xval = x[j] + # find interval + if xval == t[k]: + left = k + else: + left = np.searchsorted(t, xval) - 1 + + # fill a row + bb = _dierckx.evaluate_all_bspl(t, k, xval, left) + A[j, left-k:left+1] = bb + + # have observation matrix, can solve the LSQ problem + B = np.dot(A.T, A) + Y = np.dot(A.T, y) + c = sl.solve(B, Y) + + return c, (A, Y) + + +parametrize_lsq_methods = pytest.mark.parametrize("method", ["norm-eq", "qr"]) + +class TestLSQ: + # + # Test make_lsq_spline + # + rng = np.random.RandomState(1234) + n, k = 13, 3 + x = np.sort(rng.random(n)) + y = rng.random(n) + t = _augknt(np.linspace(x[0], x[-1], 7), k) + + @parametrize_lsq_methods + def test_lstsq(self, method): + # check LSQ construction vs a full matrix version + x, y, t, k = self.x, self.y, self.t, self.k + + c0, AY = make_lsq_full_matrix(x, y, t, k) + b = make_lsq_spline(x, y, t, k, method=method) + + xp_assert_close(b.c, c0) + assert b.c.shape == (t.size - k - 1,) + + # also check against numpy.lstsq + aa, yy = AY + c1, _, _, _ = np.linalg.lstsq(aa, y, rcond=-1) + xp_assert_close(b.c, c1) + + @parametrize_lsq_methods + def test_weights(self, method): + # weights = 1 is same as None + x, y, t, k = self.x, self.y, self.t, self.k + w = np.ones_like(x) + + b = make_lsq_spline(x, y, t, k, method=method) + b_w = make_lsq_spline(x, y, t, k, w=w, method=method) + + xp_assert_close(b.t, b_w.t, atol=1e-14) + xp_assert_close(b.c, b_w.c, atol=1e-14) + assert b.k == b_w.k + + def test_weights_same(self): + # both methods treat weights + x, y, t, k = self.x, self.y, self.t, self.k + w = np.random.default_rng(1234).uniform(size=x.shape[0]) + + b_ne = make_lsq_spline(x, y, t, k, w=w, method="norm-eq") + b_qr = make_lsq_spline(x, y, t, k, w=w, method="qr") + b_no_w = make_lsq_spline(x, y, t, k, method="qr") + + xp_assert_close(b_ne.c, b_qr.c, atol=1e-14) + assert not np.allclose(b_no_w.c, b_qr.c, atol=1e-14) + + @parametrize_lsq_methods + def test_multiple_rhs(self, method): + x, t, k, n = self.x, self.t, self.k, self.n + rng = np.random.RandomState(1234) + y = rng.random(size=(n, 5, 6, 7)) + b = make_lsq_spline(x, y, t, k, method=method) + assert b.c.shape == (t.size-k-1, 5, 6, 7) + + @parametrize_lsq_methods + def test_multiple_rhs_2(self, method): + x, t, k, n = self.x, self.t, self.k, self.n + nrhs = 3 + rng = np.random.RandomState(1234) + y = rng.random(size=(n, nrhs)) + b = make_lsq_spline(x, y, t, k, method=method) + + bb = [make_lsq_spline(x, y[:, i], t, k, method=method) + for i in range(nrhs)] + coefs = np.vstack([bb[i].c for i in range(nrhs)]).T + + xp_assert_close(coefs, b.c, atol=1e-15) + + def test_multiple_rhs_3(self): + x, t, k, n = self.x, self.t, self.k, self.n + nrhs = 3 + y = np.random.random(size=(n, nrhs)) + b_qr = make_lsq_spline(x, y, t, k, method="qr") + b_neq = make_lsq_spline(x, y, t, k, method="norm-eq") + xp_assert_close(b_qr.c, b_neq.c, atol=1e-15) + + @parametrize_lsq_methods + def test_complex(self, method): + # cmplx-valued `y` + x, t, k = self.x, self.t, self.k + yc = self.y * (1. + 2.j) + + b = make_lsq_spline(x, yc, t, k, method=method) + b_re = make_lsq_spline(x, yc.real, t, k, method=method) + b_im = make_lsq_spline(x, yc.imag, t, k, method=method) + + xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15) + + def test_complex_2(self): + # test complex-valued y with y.ndim > 1 + + x, t, k = self.x, self.t, self.k + yc = self.y * (1. + 2.j) + yc = np.stack((yc, yc), axis=1) + + b = make_lsq_spline(x, yc, t, k) + b_re = make_lsq_spline(x, yc.real, t, k) + b_im = make_lsq_spline(x, yc.imag, t, k) + + xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15) + + # repeat with num_trailing_dims > 1 : yc.shape[1:] = (2, 2) + yc = np.stack((yc, yc), axis=1) + + b = make_lsq_spline(x, yc, t, k) + b_re = make_lsq_spline(x, yc.real, t, k) + b_im = make_lsq_spline(x, yc.imag, t, k) + + xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15) + + @parametrize_lsq_methods + def test_int_xy(self, method): + x = np.arange(10).astype(int) + y = np.arange(10).astype(int) + t = _augknt(x, k=1) + # Cython chokes on "buffer type mismatch" + make_lsq_spline(x, y, t, k=1, method=method) + + @parametrize_lsq_methods + def test_f32_xy(self, method): + x = np.arange(10, dtype=np.float32) + y = np.arange(10, dtype=np.float32) + t = _augknt(x, k=1) + spl_f32 = make_lsq_spline(x, y, t, k=1, method=method) + spl_f64 = make_lsq_spline( + x.astype(float), y.astype(float), t.astype(float), k=1, method=method + ) + + x2 = (x[1:] + x[:-1]) / 2.0 + xp_assert_close(spl_f32(x2), spl_f64(x2), atol=1e-15) + + @parametrize_lsq_methods + def test_sliced_input(self, method): + # Cython code chokes on non C contiguous arrays + xx = np.linspace(-1, 1, 100) + + x = xx[::3] + y = xx[::3] + t = _augknt(x, 1) + make_lsq_spline(x, y, t, k=1, method=method) + + @parametrize_lsq_methods + def test_checkfinite(self, method): + # check_finite defaults to True; nans and such trigger a ValueError + x = np.arange(12).astype(float) + y = x**2 + t = _augknt(x, 3) + + for z in [np.nan, np.inf, -np.inf]: + y[-1] = z + assert_raises(ValueError, make_lsq_spline, x, y, t, method=method) + + @parametrize_lsq_methods + def test_read_only(self, method): + # Check that make_lsq_spline works with read only arrays + x, y, t = self.x, self.y, self.t + x.setflags(write=False) + y.setflags(write=False) + t.setflags(write=False) + make_lsq_spline(x=x, y=y, t=t, method=method) + + @pytest.mark.parametrize('k', list(range(1, 7))) + def test_qr_vs_norm_eq(self, k): + # check that QR and normal eq solutions match + x, y = self.x, self.y + t = _augknt(np.linspace(x[0], x[-1], 7), k) + spl_norm_eq = make_lsq_spline(x, y, t, k=k, method='norm-eq') + spl_qr = make_lsq_spline(x, y, t, k=k, method='qr') + + xx = (x[1:] + x[:-1]) / 2.0 + xp_assert_close(spl_norm_eq(xx), spl_qr(xx), atol=1e-15) + + def test_duplicates(self): + # method="qr" can handle duplicated data points + x = np.repeat(self.x, 2) + y = np.repeat(self.y, 2) + spl_1 = make_lsq_spline(self.x, self.y, self.t, k=3, method='qr') + spl_2 = make_lsq_spline(x, y, self.t, k=3, method='qr') + + xx = (x[1:] + x[:-1]) / 2.0 + xp_assert_close(spl_1(xx), spl_2(xx), atol=1e-15) + + +class PackedMatrix: + """A simplified CSR format for when non-zeros in each row are consecutive. + + Assuming that each row of an `(m, nc)` matrix 1) only has `nz` non-zeros, and + 2) these non-zeros are consecutive, we only store an `(m, nz)` matrix of + non-zeros and a 1D array of row offsets. This way, a row `i` of the original + matrix A is ``A[i, offset[i]: offset[i] + nz]``. + + """ + def __init__(self, a, offset, nc): + self.a = a + self.offset = offset + self.nc = nc + + assert a.ndim == 2 + assert offset.ndim == 1 + assert a.shape[0] == offset.shape[0] + + @property + def shape(self): + return self.a.shape[0], self.nc + + def todense(self): + out = np.zeros(self.shape) + nelem = self.a.shape[1] + for i in range(out.shape[0]): + nel = min(self.nc - self.offset[i], nelem) + out[i, self.offset[i]:self.offset[i] + nel] = self.a[i, :nel] + return out + + +def _qr_reduce_py(a_p, y, startrow=1): + """This is a python counterpart of the `_qr_reduce` routine, + declared in interpolate/src/__fitpack.h + """ + from scipy.linalg.lapack import dlartg + + # unpack the packed format + a = a_p.a + offset = a_p.offset + nc = a_p.nc + + m, nz = a.shape + + assert y.shape[0] == m + R = a.copy() + y1 = y.copy() + + for i in range(startrow, m): + oi = offset[i] + for j in range(oi, nc): + # rotate only the lower diagonal + if j >= min(i, nc): + break + + # In dense format: diag a1[j, j] vs a1[i, j] + c, s, r = dlartg(R[j, 0], R[i, 0]) + + # rotate l.h.s. + R[j, 0] = r + for l in range(1, nz): + R[j, l], R[i, l-1] = fprota(c, s, R[j, l], R[i, l]) + R[i, -1] = 0.0 + + # rotate r.h.s. + for l in range(y1.shape[1]): + y1[j, l], y1[i, l] = fprota(c, s, y1[j, l], y1[i, l]) + + # convert to packed + offs = list(range(R.shape[0])) + R_p = PackedMatrix(R, np.array(offs, dtype=np.int64), nc) + + return R_p, y1 + + +def fprota(c, s, a, b): + """Givens rotate [a, b]. + + [aa] = [ c s] @ [a] + [bb] [-s c] [b] + + """ + aa = c*a + s*b + bb = -s*a + c*b + return aa, bb + + +def fpback(R_p, y): + """Backsubsitution solve upper triangular banded `R @ c = y.` + + `R` is in the "packed" format: `R[i, :]` is `a[i, i:i+k+1]` + """ + R = R_p.a + _, nz = R.shape + nc = R_p.nc + assert y.shape[0] == R.shape[0] + + c = np.zeros_like(y[:nc]) + c[nc-1, ...] = y[nc-1] / R[nc-1, 0] + for i in range(nc-2, -1, -1): + nel = min(nz, nc-i) + # NB: broadcast R across trailing dimensions of `c`. + summ = (R[i, 1:nel, None] * c[i+1:i+nel, ...]).sum(axis=0) + c[i, ...] = ( y[i] - summ ) / R[i, 0] + return c + + +class TestGivensQR: + # Test row-by-row QR factorization, used for the LSQ spline construction. + # This is implementation detail; still test it separately. + def _get_xyt(self, n): + k = 3 + x = np.arange(n, dtype=float) + y = x**3 + 1/(1+x) + t = _not_a_knot(x, k) + return x, y, t, k + + def test_vs_full(self): + n = 10 + x, y, t, k = self._get_xyt(n) + + # design matrix + a_csr = BSpline.design_matrix(x, t, k) + + # dense QR + q, r = sl.qr(a_csr.todense()) + qTy = q.T @ y + + # prepare the PackedMatrix to factorize + # convert to "packed" format + m, nc = a_csr.shape + assert nc == t.shape[0] - k - 1 + + offset = a_csr.indices[::(k+1)] + offset = np.ascontiguousarray(offset, dtype=np.int64) + A = a_csr.data.reshape(m, k+1) + + R = PackedMatrix(A, offset, nc) + y_ = y[:, None] # _qr_reduce requires `y` a 2D array + _dierckx.qr_reduce(A, offset, nc, y_) # modifies arguments in-place + + # signs may differ + xp_assert_close(np.minimum(R.todense() + r, + R.todense() - r), np.zeros_like(r), atol=1e-15) + xp_assert_close(np.minimum(abs(qTy - y_[:, 0]), + abs(qTy + y_[:, 0])), np.zeros_like(qTy), atol=2e-13) + + # sign changes are consistent between Q and R: + c_full = sl.solve(r, qTy) + c_banded = _dierckx.fpback(R.a, R.nc, y_) + xp_assert_close(c_full, c_banded[:, 0], atol=5e-13) + + def test_py_vs_compiled(self): + # test _qr_reduce vs a python implementation + n = 10 + x, y, t, k = self._get_xyt(n) + + # design matrix + a_csr = BSpline.design_matrix(x, t, k) + m, nc = a_csr.shape + assert nc == t.shape[0] - k - 1 + + offset = a_csr.indices[::(k+1)] + offset = np.ascontiguousarray(offset, dtype=np.int64) + A = a_csr.data.reshape(m, k+1) + + R = PackedMatrix(A, offset, nc) + y_ = y[:, None] + + RR, yy = _qr_reduce_py(R, y_) + _dierckx.qr_reduce(A, offset, nc , y_) # in-place + + xp_assert_close(RR.a, R.a, atol=1e-15) + xp_assert_equal(RR.offset, R.offset, check_dtype=False) + assert RR.nc == R.nc + xp_assert_close(yy, y_, atol=1e-15) + + # Test C-level construction of the design matrix + + def test_data_matrix(self): + n = 10 + x, y, t, k = self._get_xyt(n) + w = np.arange(1, n+1, dtype=float) + + A, offset, nc = _dierckx.data_matrix(x, t, k, w) + + m = x.shape[0] + a_csr = BSpline.design_matrix(x, t, k) + a_w = (a_csr * w[:, None]).tocsr() + A_ = a_w.data.reshape((m, k+1)) + offset_ = a_w.indices[::(k+1)].astype(np.int64) + + xp_assert_close(A, A_, atol=1e-15) + xp_assert_equal(offset, offset_) + assert nc == t.shape[0] - k - 1 + + def test_fpback(self): + n = 10 + x, y, t, k = self._get_xyt(n) + y = np.c_[y, y**2] + A, offset, nc = _dierckx.data_matrix(x, t, k, np.ones_like(x)) + R = PackedMatrix(A, offset, nc) + _dierckx.qr_reduce(A, offset, nc, y) + + c = fpback(R, y) + cc = _dierckx.fpback(A, nc, y) + + xp_assert_close(cc, c, atol=1e-14) + + +def data_file(basename): + return os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', basename) + + +class TestSmoothingSpline: + # + # test make_smoothing_spline + # + def test_invalid_input(self): + rng = np.random.RandomState(1234) + n = 100 + x = np.sort(rng.random_sample(n) * 4 - 2) + y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n) + + # ``x`` and ``y`` should have same shapes (1-D array) + with assert_raises(ValueError): + make_smoothing_spline(x, y[1:]) + with assert_raises(ValueError): + make_smoothing_spline(x[1:], y) + with assert_raises(ValueError): + make_smoothing_spline(x.reshape(1, n), y) + + # ``x`` should be an ascending array + with assert_raises(ValueError): + make_smoothing_spline(x[::-1], y) + + x_dupl = np.copy(x) + x_dupl[0] = x_dupl[1] + + with assert_raises(ValueError): + make_smoothing_spline(x_dupl, y) + + # x and y length must be >= 5 + x = np.arange(4) + y = np.ones(4) + exception_message = "``x`` and ``y`` length must be at least 5" + with pytest.raises(ValueError, match=exception_message): + make_smoothing_spline(x, y) + + def test_compare_with_GCVSPL(self): + """ + Data is generated in the following way: + >>> np.random.seed(1234) + >>> n = 100 + >>> x = np.sort(np.random.random_sample(n) * 4 - 2) + >>> y = np.sin(x) + np.random.normal(scale=.5, size=n) + >>> np.savetxt('x.csv', x) + >>> np.savetxt('y.csv', y) + + We obtain the result of performing the GCV smoothing splines + package (by Woltring, gcvspl) on the sample data points + using its version for Octave (https://github.com/srkuberski/gcvspl). + In order to use this implementation, one should clone the repository + and open the folder in Octave. + In Octave, we load up ``x`` and ``y`` (generated from Python code + above): + + >>> x = csvread('x.csv'); + >>> y = csvread('y.csv'); + + Then, in order to access the implementation, we compile gcvspl files in + Octave: + + >>> mex gcvsplmex.c gcvspl.c + >>> mex spldermex.c gcvspl.c + + The first function computes the vector of unknowns from the dataset + (x, y) while the second one evaluates the spline in certain points + with known vector of coefficients. + + >>> c = gcvsplmex( x, y, 2 ); + >>> y0 = spldermex( x, c, 2, x, 0 ); + + If we want to compare the results of the gcvspl code, we can save + ``y0`` in csv file: + + >>> csvwrite('y0.csv', y0); + + """ + # load the data sample + with np.load(data_file('gcvspl.npz')) as data: + # data points + x = data['x'] + y = data['y'] + + y_GCVSPL = data['y_GCVSPL'] + y_compr = make_smoothing_spline(x, y)(x) + + # such tolerance is explained by the fact that the spline is built + # using an iterative algorithm for minimizing the GCV criteria. These + # algorithms may vary, so the tolerance should be rather low. + # Not checking dtypes as gcvspl.npz stores little endian arrays, which + # result in conflicting dtypes on big endian systems. + xp_assert_close(y_compr, y_GCVSPL, atol=1e-4, rtol=1e-4, check_dtype=False) + + def test_non_regularized_case(self): + """ + In case the regularization parameter is 0, the resulting spline + is an interpolation spline with natural boundary conditions. + """ + # create data sample + rng = np.random.RandomState(1234) + n = 100 + x = np.sort(rng.random_sample(n) * 4 - 2) + y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n) + + spline_GCV = make_smoothing_spline(x, y, lam=0.) + spline_interp = make_interp_spline(x, y, 3, bc_type='natural') + + grid = np.linspace(x[0], x[-1], 2 * n) + xp_assert_close(spline_GCV(grid), + spline_interp(grid), + atol=1e-15) + + @pytest.mark.fail_slow(2) + def test_weighted_smoothing_spline(self): + # create data sample + rng = np.random.RandomState(1234) + n = 100 + x = np.sort(rng.random_sample(n) * 4 - 2) + y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n) + + spl = make_smoothing_spline(x, y) + + # in order not to iterate over all of the indices, we select 10 of + # them randomly + for ind in rng.choice(range(100), size=10): + w = np.ones(n) + w[ind] = 30. + spl_w = make_smoothing_spline(x, y, w) + # check that spline with weight in a certain point is closer to the + # original point than the one without weights + orig = abs(spl(x[ind]) - y[ind]) + weighted = abs(spl_w(x[ind]) - y[ind]) + + if orig < weighted: + raise ValueError(f'Spline with weights should be closer to the' + f' points than the original one: {orig:.4} < ' + f'{weighted:.4}') + + +################################ +# NdBSpline tests +def bspline2(xy, t, c, k): + """A naive 2D tensort product spline evaluation.""" + x, y = xy + tx, ty = t + nx = len(tx) - k - 1 + assert (nx >= k+1) + ny = len(ty) - k - 1 + assert (ny >= k+1) + res = sum(c[ix, iy] * B(x, k, ix, tx) * B(y, k, iy, ty) + for ix in range(nx) for iy in range(ny)) + return np.asarray(res) + + +def B(x, k, i, t): + if k == 0: + return 1.0 if t[i] <= x < t[i+1] else 0.0 + if t[i+k] == t[i]: + c1 = 0.0 + else: + c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t) + if t[i+k+1] == t[i+1]: + c2 = 0.0 + else: + c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t) + return c1 + c2 + + +def bspline(x, t, c, k): + n = len(t) - k - 1 + assert (n >= k+1) and (len(c) >= n) + return sum(c[i] * B(x, k, i, t) for i in range(n)) + + +class NdBSpline0: + def __init__(self, t, c, k=3): + """Tensor product spline object. + + c[i1, i2, ..., id] * B(x1, i1) * B(x2, i2) * ... * B(xd, id) + + Parameters + ---------- + c : ndarray, shape (n1, n2, ..., nd, ...) + b-spline coefficients + t : tuple of 1D ndarrays + knot vectors in directions 1, 2, ... d + ``len(t[i]) == n[i] + k + 1`` + k : int or length-d tuple of integers + spline degrees. + """ + ndim = len(t) + assert ndim <= len(c.shape) + + try: + len(k) + except TypeError: + # make k a tuple + k = (k,)*ndim + + self.k = tuple(operator.index(ki) for ki in k) + self.t = tuple(np.asarray(ti, dtype=float) for ti in t) + self.c = c + + def __call__(self, x): + ndim = len(self.t) + # a single evaluation point: `x` is a 1D array_like, shape (ndim,) + assert len(x) == ndim + + # get the indices in an ndim-dimensional vector + i = ['none', ]*ndim + for d in range(ndim): + td, xd = self.t[d], x[d] + k = self.k[d] + + # find the index for x[d] + if xd == td[k]: + i[d] = k + else: + i[d] = np.searchsorted(td, xd) - 1 + assert td[i[d]] <= xd <= td[i[d]+1] + assert i[d] >= k and i[d] < len(td) - k + i = tuple(i) + + # iterate over the dimensions, form linear combinations of + # products B(x_1) * B(x_2) * ... B(x_N) of (k+1)**N b-splines + # which are non-zero at `i = (i_1, i_2, ..., i_N)`. + result = 0 + iters = [range(i[d] - self.k[d], i[d] + 1) for d in range(ndim)] + for idx in itertools.product(*iters): + term = self.c[idx] * np.prod([B(x[d], self.k[d], idx[d], self.t[d]) + for d in range(ndim)]) + result += term + return np.asarray(result) + + +class TestNdBSpline: + + def test_1D(self): + # test ndim=1 agrees with BSpline + rng = np.random.default_rng(12345) + n, k = 11, 3 + n_tr = 7 + t = np.sort(rng.uniform(size=n + k + 1)) + c = rng.uniform(size=(n, n_tr)) + + b = BSpline(t, c, k) + nb = NdBSpline((t,), c, k) + + xi = rng.uniform(size=21) + # NdBSpline expects xi.shape=(npts, ndim) + xp_assert_close(nb(xi[:, None]), + b(xi), atol=1e-14) + assert nb(xi[:, None]).shape == (xi.shape[0], c.shape[1]) + + def make_2d_case(self): + # make a 2D separable spline + x = np.arange(6) + y = x**3 + spl = make_interp_spline(x, y, k=3) + + y_1 = x**3 + 2*x + spl_1 = make_interp_spline(x, y_1, k=3) + + t2 = (spl.t, spl_1.t) + c2 = spl.c[:, None] * spl_1.c[None, :] + + return t2, c2, 3 + + def make_2d_mixed(self): + # make a 2D separable spline w/ kx=3, ky=2 + x = np.arange(6) + y = x**3 + spl = make_interp_spline(x, y, k=3) + + x = np.arange(5) + 1.5 + y_1 = x**2 + 2*x + spl_1 = make_interp_spline(x, y_1, k=2) + + t2 = (spl.t, spl_1.t) + c2 = spl.c[:, None] * spl_1.c[None, :] + + return t2, c2, spl.k, spl_1.k + + def test_2D_separable(self): + xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)] + t2, c2, k = self.make_2d_case() + target = [x**3 * (y**3 + 2*y) for (x, y) in xi] + + # sanity check: bspline2 gives the product as constructed + xp_assert_close(np.asarray([bspline2(xy, t2, c2, k) for xy in xi]), + np.asarray(target), + check_shape=False, + atol=1e-14) + + # check evaluation on a 2D array: the 1D array of 2D points + bspl2 = NdBSpline(t2, c2, k=3) + assert bspl2(xi).shape == (len(xi), ) + xp_assert_close(bspl2(xi), + target, atol=1e-14) + + # now check on a multidim xi + rng = np.random.default_rng(12345) + xi = rng.uniform(size=(4, 3, 2)) * 5 + result = bspl2(xi) + assert result.shape == (4, 3) + + # also check the values + x, y = xi.reshape((-1, 2)).T + xp_assert_close(result.ravel(), + x**3 * (y**3 + 2*y), atol=1e-14) + + def test_2D_separable_2(self): + # test `c` with trailing dimensions, i.e. c.ndim > ndim + ndim = 2 + xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)] + target = [x**3 * (y**3 + 2*y) for (x, y) in xi] + + t2, c2, k = self.make_2d_case() + c2_4 = np.dstack((c2, c2, c2, c2)) # c22.shape = (6, 6, 4) + + xy = (1.5, 2.5) + bspl2_4 = NdBSpline(t2, c2_4, k=3) + result = bspl2_4(xy) + val_single = NdBSpline(t2, c2, k)(xy) + assert result.shape == (4,) + xp_assert_close(result, + [val_single, ]*4, atol=1e-14) + + # now try the array xi : the output.shape is (3, 4) where 3 + # is the number of points in xi and 4 is the trailing dimension of c + assert bspl2_4(xi).shape == np.shape(xi)[:-1] + bspl2_4.c.shape[ndim:] + xp_assert_close(bspl2_4(xi), np.asarray(target)[:, None], + check_shape=False, + atol=5e-14) + + # two trailing dimensions + c2_22 = c2_4.reshape((6, 6, 2, 2)) + bspl2_22 = NdBSpline(t2, c2_22, k=3) + + result = bspl2_22(xy) + assert result.shape == (2, 2) + xp_assert_close(result, + [[val_single, val_single], + [val_single, val_single]], atol=1e-14) + + # now try the array xi : the output shape is (3, 2, 2) + # for 3 points in xi and c trailing dimensions being (2, 2) + assert (bspl2_22(xi).shape == + np.shape(xi)[:-1] + bspl2_22.c.shape[ndim:]) + xp_assert_close(bspl2_22(xi), np.asarray(target)[:, None, None], + check_shape=False, + atol=5e-14) + + + def test_2D_separable_2_complex(self): + # test `c` with c.dtype == complex, with and w/o trailing dims + xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)] + target = [x**3 * (y**3 + 2*y) for (x, y) in xi] + + target = [t + 2j*t for t in target] + + t2, c2, k = self.make_2d_case() + c2 = c2 * (1 + 2j) + c2_4 = np.dstack((c2, c2, c2, c2)) # c2_4.shape = (6, 6, 4) + + xy = (1.5, 2.5) + bspl2_4 = NdBSpline(t2, c2_4, k=3) + result = bspl2_4(xy) + val_single = NdBSpline(t2, c2, k)(xy) + assert result.shape == (4,) + xp_assert_close(result, + [val_single, ]*4, atol=1e-14) + + def test_2D_random(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size-k-1, ty.size-k-1)) + + spl = NdBSpline((tx, ty), c, k=k) + + xi = (1., 1.) + xp_assert_close(spl(xi), + bspline2(xi, (tx, ty), c, k), atol=1e-14) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1]] + xp_assert_close(spl(xi), + [bspline2(xy, (tx, ty), c, k) for xy in xi], + atol=1e-14) + + def test_2D_mixed(self): + t2, c2, kx, ky = self.make_2d_mixed() + xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)] + target = [x**3 * (y**2 + 2*y) for (x, y) in xi] + bspl2 = NdBSpline(t2, c2, k=(kx, ky)) + assert bspl2(xi).shape == (len(xi), ) + xp_assert_close(bspl2(xi), + target, atol=1e-14) + + def test_2D_derivative(self): + t2, c2, kx, ky = self.make_2d_mixed() + xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)] + bspl2 = NdBSpline(t2, c2, k=(kx, ky)) + + der = bspl2(xi, nu=(1, 0)) + xp_assert_close(der, + [3*x**2 * (y**2 + 2*y) for x, y in xi], atol=1e-14) + + der = bspl2(xi, nu=(1, 1)) + xp_assert_close(der, + [3*x**2 * (2*y + 2) for x, y in xi], atol=1e-14) + + der = bspl2(xi, nu=(0, 0)) + xp_assert_close(der, + [x**3 * (y**2 + 2*y) for x, y in xi], atol=1e-14) + + with assert_raises(ValueError): + # all(nu >= 0) + der = bspl2(xi, nu=(-1, 0)) + + with assert_raises(ValueError): + # len(nu) == ndim + der = bspl2(xi, nu=(-1, 0, 1)) + + def test_2D_mixed_random(self): + rng = np.random.default_rng(12345) + kx, ky = 2, 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size - kx - 1, ty.size - ky - 1)) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1]] + + bspl2 = NdBSpline((tx, ty), c, k=(kx, ky)) + bspl2_0 = NdBSpline0((tx, ty), c, k=(kx, ky)) + + xp_assert_close(bspl2(xi), + [bspl2_0(xp) for xp in xi], atol=1e-14) + + def test_tx_neq_ty(self): + # 2D separable spline w/ len(tx) != len(ty) + x = np.arange(6) + y = np.arange(7) + 1.5 + + spl_x = make_interp_spline(x, x**3, k=3) + spl_y = make_interp_spline(y, y**2 + 2*y, k=3) + cc = spl_x.c[:, None] * spl_y.c[None, :] + bspl = NdBSpline((spl_x.t, spl_y.t), cc, (spl_x.k, spl_y.k)) + + values = (x**3)[:, None] * (y**2 + 2*y)[None, :] + rgi = RegularGridInterpolator((x, y), values) + + xi = [(a, b) for a, b in itertools.product(x, y)] + bxi = bspl(xi) + + assert not np.isnan(bxi).any() + xp_assert_close(bxi, rgi(xi), atol=1e-14) + xp_assert_close(bxi.reshape(values.shape), values, atol=1e-14) + + def make_3d_case(self): + # make a 3D separable spline + x = np.arange(6) + y = x**3 + spl = make_interp_spline(x, y, k=3) + + y_1 = x**3 + 2*x + spl_1 = make_interp_spline(x, y_1, k=3) + + y_2 = x**3 + 3*x + 1 + spl_2 = make_interp_spline(x, y_2, k=3) + + t2 = (spl.t, spl_1.t, spl_2.t) + c2 = (spl.c[:, None, None] * + spl_1.c[None, :, None] * + spl_2.c[None, None, :]) + + return t2, c2, 3 + + def test_3D_separable(self): + rng = np.random.default_rng(12345) + x, y, z = rng.uniform(size=(3, 11)) * 5 + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + xi = [_ for _ in zip(x, y, z)] + result = bspl3(xi) + assert result.shape == (11,) + xp_assert_close(result, target, atol=1e-14) + + def test_3D_derivative(self): + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + rng = np.random.default_rng(12345) + x, y, z = rng.uniform(size=(3, 11)) * 5 + xi = [_ for _ in zip(x, y, z)] + + xp_assert_close(bspl3(xi, nu=(1, 0, 0)), + 3*x**2 * (y**3 + 2*y) * (z**3 + 3*z + 1), atol=1e-14) + + xp_assert_close(bspl3(xi, nu=(2, 0, 0)), + 6*x * (y**3 + 2*y) * (z**3 + 3*z + 1), atol=1e-14) + + xp_assert_close(bspl3(xi, nu=(2, 1, 0)), + 6*x * (3*y**2 + 2) * (z**3 + 3*z + 1), atol=1e-14) + + xp_assert_close(bspl3(xi, nu=(2, 1, 3)), + 6*x * (3*y**2 + 2) * (6), atol=1e-14) + + xp_assert_close(bspl3(xi, nu=(2, 1, 4)), + np.zeros(len(xi)), atol=1e-14) + + def test_3D_random(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) + + spl = NdBSpline((tx, ty, tz), c, k=k) + spl_0 = NdBSpline0((tx, ty, tz), c, k=k) + + xi = (1., 1., 1) + xp_assert_close(spl(xi), spl_0(xi), atol=1e-14) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1], + [0.9, 1.4, 1.9]] + xp_assert_close(spl(xi), [spl_0(xp) for xp in xi], atol=1e-14) + + def test_3D_random_complex(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = (rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) + + rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))*1j) + + spl = NdBSpline((tx, ty, tz), c, k=k) + spl_re = NdBSpline((tx, ty, tz), c.real, k=k) + spl_im = NdBSpline((tx, ty, tz), c.imag, k=k) + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1], + [0.9, 1.4, 1.9]] + xp_assert_close(spl(xi), + spl_re(xi) + 1j*spl_im(xi), atol=1e-14) + + @pytest.mark.parametrize('cls_extrap', [None, True]) + @pytest.mark.parametrize('call_extrap', [None, True]) + def test_extrapolate_3D_separable(self, cls_extrap, call_extrap): + # test that extrapolate=True does extrapolate + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap) + + # evaluate out of bounds + x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5] + x, y, z = map(np.asarray, (x, y, z)) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + result = bspl3(xi, extrapolate=call_extrap) + xp_assert_close(result, target, atol=1e-14) + + @pytest.mark.parametrize('extrap', [(False, True), (True, None)]) + def test_extrapolate_3D_separable_2(self, extrap): + # test that call(..., extrapolate=None) defers to self.extrapolate, + # otherwise supersedes self.extrapolate + t3, c3, k = self.make_3d_case() + cls_extrap, call_extrap = extrap + bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap) + + # evaluate out of bounds + x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5] + x, y, z = map(np.asarray, (x, y, z)) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + result = bspl3(xi, extrapolate=call_extrap) + xp_assert_close(result, target, atol=1e-14) + + def test_extrapolate_false_3D_separable(self): + # test that extrapolate=False produces nans for out-of-bounds values + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + # evaluate out of bounds and inside + x, y, z = [-2, 1, 7], [-3, 0.5, 6.5], [-1, 1.5, 7.5] + x, y, z = map(np.asarray, (x, y, z)) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + + result = bspl3(xi, extrapolate=False) + assert np.isnan(result[0]) + assert np.isnan(result[-1]) + xp_assert_close(result[1:-1], target[1:-1], atol=1e-14) + + def test_x_nan_3D(self): + # test that spline(nan) is nan + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + # evaluate out of bounds and inside + x = np.asarray([-2, 3, np.nan, 1, 2, 7, np.nan]) + y = np.asarray([-3, 3.5, 1, np.nan, 3, 6.5, 6.5]) + z = np.asarray([-1, 3.5, 2, 3, np.nan, 7.5, 7.5]) + xi = [_ for _ in zip(x, y, z)] + target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1) + mask = np.isnan(x) | np.isnan(y) | np.isnan(z) + target[mask] = np.nan + + result = bspl3(xi) + assert np.isnan(result[mask]).all() + xp_assert_close(result, target, atol=1e-14) + + def test_non_c_contiguous(self): + # check that non C-contiguous inputs are OK + rng = np.random.default_rng(12345) + kx, ky = 3, 3 + tx = np.sort(rng.uniform(low=0, high=4, size=16)) + tx = np.r_[(tx[0],)*kx, tx, (tx[-1],)*kx] + ty = np.sort(rng.uniform(low=0, high=4, size=16)) + ty = np.r_[(ty[0],)*ky, ty, (ty[-1],)*ky] + + assert not tx[::2].flags.c_contiguous + assert not ty[::2].flags.c_contiguous + + c = rng.uniform(size=(tx.size//2 - kx - 1, ty.size//2 - ky - 1)) + c = c.T + assert not c.flags.c_contiguous + + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1]] + + bspl2 = NdBSpline((tx[::2], ty[::2]), c, k=(kx, ky)) + bspl2_0 = NdBSpline0((tx[::2], ty[::2]), c, k=(kx, ky)) + + xp_assert_close(bspl2(xi), + [bspl2_0(xp) for xp in xi], atol=1e-14) + + def test_readonly(self): + t3, c3, k = self.make_3d_case() + bspl3 = NdBSpline(t3, c3, k=3) + + for i in range(3): + t3[i].flags.writeable = False + c3.flags.writeable = False + + bspl3_ = NdBSpline(t3, c3, k=3) + + assert bspl3((1, 2, 3)) == bspl3_((1, 2, 3)) + + def test_design_matrix(self): + t3, c3, k = self.make_3d_case() + + xi = np.asarray([[1, 2, 3], [4, 5, 6]]) + dm = NdBSpline(t3, c3, k).design_matrix(xi, t3, k) + dm1 = NdBSpline.design_matrix(xi, t3, [k, k, k]) + assert dm.shape[0] == xi.shape[0] + xp_assert_close(dm.todense(), dm1.todense(), atol=1e-16) + + with assert_raises(ValueError): + NdBSpline.design_matrix([1, 2, 3], t3, [k]*3) + + with assert_raises(ValueError, match="Data and knots*"): + NdBSpline.design_matrix([[1, 2]], t3, [k]*3) + + @pytest.mark.thread_unsafe + def test_concurrency(self): + rng = np.random.default_rng(12345) + k = 3 + tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3] + ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4] + c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) + + spl = NdBSpline((tx, ty, tz), c, k=k) + + def worker_fn(_, spl): + xi = np.c_[[1, 1.5, 2], + [1.1, 1.6, 2.1], + [0.9, 1.4, 1.9]] + spl(xi) + + _run_concurrent_barrier(10, worker_fn, spl) + + +class TestMakeND: + def test_2D_separable_simple(self): + x = np.arange(6) + y = np.arange(6) + 0.5 + values = x[:, None]**3 * (y**3 + 2*y)[None, :] + xi = [(a, b) for a, b in itertools.product(x, y)] + + bspl = make_ndbspl((x, y), values, k=1) + xp_assert_close(bspl(xi), values.ravel(), atol=1e-15) + + # test the coefficients vs outer product of 1D coefficients + spl_x = make_interp_spline(x, x**3, k=1) + spl_y = make_interp_spline(y, y**3 + 2*y, k=1) + cc = spl_x.c[:, None] * spl_y.c[None, :] + xp_assert_close(cc, bspl.c, atol=1e-11, rtol=0) + + # test against RGI + from scipy.interpolate import RegularGridInterpolator as RGI + rgi = RGI((x, y), values, method='linear') + xp_assert_close(rgi(xi), bspl(xi), atol=1e-14) + + def test_2D_separable_trailing_dims(self): + # test `c` with trailing dimensions, i.e. c.ndim > ndim + x = np.arange(6) + y = np.arange(6) + xi = [(a, b) for a, b in itertools.product(x, y)] + + # make values4.shape = (6, 6, 4) + values = x[:, None]**3 * (y**3 + 2*y)[None, :] + values4 = np.dstack((values, values, values, values)) + bspl = make_ndbspl((x, y), values4, k=3, solver=ssl.spsolve) + + result = bspl(xi) + target = np.dstack((values, values, values, values)).astype(float) + assert result.shape == (36, 4) + xp_assert_close(result.reshape(6, 6, 4), + target, atol=1e-14) + + # now two trailing dimensions + values22 = values4.reshape((6, 6, 2, 2)) + bspl = make_ndbspl((x, y), values22, k=3, solver=ssl.spsolve) + + result = bspl(xi) + assert result.shape == (36, 2, 2) + xp_assert_close(result.reshape(6, 6, 2, 2), + target.reshape((6, 6, 2, 2)), atol=1e-14) + + @pytest.mark.parametrize('k', [(3, 3), (1, 1), (3, 1), (1, 3), (3, 5)]) + def test_2D_mixed(self, k): + # make a 2D separable spline w/ len(tx) != len(ty) + x = np.arange(6) + y = np.arange(7) + 1.5 + xi = [(a, b) for a, b in itertools.product(x, y)] + + values = (x**3)[:, None] * (y**2 + 2*y)[None, :] + bspl = make_ndbspl((x, y), values, k=k, solver=ssl.spsolve) + xp_assert_close(bspl(xi), values.ravel(), atol=1e-15) + + def _get_sample_2d_data(self): + # from test_rgi.py::TestIntepN + x = np.array([.5, 2., 3., 4., 5.5, 6.]) + y = np.array([.5, 2., 3., 4., 5.5, 6.]) + z = np.array( + [ + [1, 2, 1, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 3, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + ] + ) + return x, y, z + + def test_2D_vs_RGI_linear(self): + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=1) + rgi = RegularGridInterpolator((x, y), z, method='linear') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + def test_2D_vs_RGI_cubic(self): + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=3, solver=ssl.spsolve) + rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + @pytest.mark.parametrize('solver', [ssl.gmres, ssl.gcrotmk]) + def test_2D_vs_RGI_cubic_iterative(self, solver): + # same as `test_2D_vs_RGI_cubic`, only with an iterative solver. + # Note the need to add an explicit `rtol` solver_arg to achieve the + # target accuracy of 1e-14. (the relation between solver atol/rtol + # and the accuracy of the final result is not direct and needs experimenting) + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=3, solver=solver, rtol=1e-6) + rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14, rtol=1e-7) + + def test_2D_vs_RGI_quintic(self): + x, y, z = self._get_sample_2d_data() + bspl = make_ndbspl((x, y), z, k=5, solver=ssl.spsolve) + rgi = RegularGridInterpolator((x, y), z, method='quintic_legacy') + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + @pytest.mark.parametrize( + 'k, meth', [(1, 'linear'), (3, 'cubic_legacy'), (5, 'quintic_legacy')] + ) + def test_3D_random_vs_RGI(self, k, meth): + rndm = np.random.default_rng(123456) + x = np.cumsum(rndm.uniform(size=6)) + y = np.cumsum(rndm.uniform(size=7)) + z = np.cumsum(rndm.uniform(size=8)) + values = rndm.uniform(size=(6, 7, 8)) + + bspl = make_ndbspl((x, y, z), values, k=k, solver=ssl.spsolve) + rgi = RegularGridInterpolator((x, y, z), values, method=meth) + + xi = np.random.uniform(low=0.7, high=2.1, size=(11, 3)) + xp_assert_close(bspl(xi), rgi(xi), atol=1e-14) + + def test_solver_err_not_converged(self): + x, y, z = self._get_sample_2d_data() + solver_args = {'maxiter': 1} + with assert_raises(ValueError, match='solver'): + make_ndbspl((x, y), z, k=3, **solver_args) + + with assert_raises(ValueError, match='solver'): + make_ndbspl((x, y), np.dstack((z, z)), k=3, **solver_args) + + +class TestFpchec: + # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f + + def test_1D_x_t(self): + k = 1 + t = np.arange(12).reshape(2, 6) + x = np.arange(12) + + with pytest.raises(ValueError, match="1D sequence"): + _b.fpcheck(x, t, k) + + with pytest.raises(ValueError, match="1D sequence"): + _b.fpcheck(t, x, k) + + def test_condition_1(self): + # c 1) k+1 <= n-k-1 <= m + k = 3 + n = 2*(k + 1) - 1 # not OK + m = n + 11 # OK + t = np.arange(n) + x = np.arange(m) + + assert dfitpack.fpchec(x, t, k) == 10 + with pytest.raises(ValueError, match="Need k+1*"): + _b.fpcheck(x, t, k) + + n = 2*(k+1) + 1 # OK + m = n - k - 2 # not OK + t = np.arange(n) + x = np.arange(m) + + assert dfitpack.fpchec(x, t, k) == 10 + with pytest.raises(ValueError, match="Need k+1*"): + _b.fpcheck(x, t, k) + + def test_condition_2(self): + # c 2) t(1) <= t(2) <= ... <= t(k+1) + # c t(n-k) <= t(n-k+1) <= ... <= t(n) + k = 3 + t = [0]*(k+1) + [2] + [5]*(k+1) # this is OK + x = [1, 2, 3, 4, 4.5] + + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None # does not raise + + tt = t.copy() + tt[-1] = tt[0] # not OK + assert dfitpack.fpchec(x, tt, k) == 20 + with pytest.raises(ValueError, match="Last k knots*"): + _b.fpcheck(x, tt, k) + + tt = t.copy() + tt[0] = tt[-1] # not OK + assert dfitpack.fpchec(x, tt, k) == 20 + with pytest.raises(ValueError, match="First k knots*"): + _b.fpcheck(x, tt, k) + + def test_condition_3(self): + # c 3) t(k+1) < t(k+2) < ... < t(n-k) + k = 3 + t = [0]*(k+1) + [2, 3] + [5]*(k+1) # this is OK + x = [1, 2, 3, 3.5, 4, 4.5] + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + t = [0]*(k+1) + [2, 2] + [5]*(k+1) # this is not OK + assert dfitpack.fpchec(x, t, k) == 30 + with pytest.raises(ValueError, match="Internal knots*"): + _b.fpcheck(x, t, k) + + def test_condition_4(self): + # c 4) t(k+1) <= x(i) <= t(n-k) + # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow. + k = 3 + t = [0]*(k+1) + [5]*(k+1) + x = [1, 2, 3, 3.5, 4, 4.5] # this is OK + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + xx = x.copy() + xx[0] = t[0] # still OK + assert dfitpack.fpchec(xx, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + xx = x.copy() + xx[0] = t[0] - 1 # not OK + assert dfitpack.fpchec(xx, t, k) == 40 + with pytest.raises(ValueError, match="Out of bounds*"): + _b.fpcheck(xx, t, k) + + xx = x.copy() + xx[-1] = t[-1] + 1 # not OK + assert dfitpack.fpchec(xx, t, k) == 40 + with pytest.raises(ValueError, match="Out of bounds*"): + _b.fpcheck(xx, t, k) + + # ### Test the S-W condition (no 5) + # c 5) the conditions specified by schoenberg and whitney must hold + # c for at least one subset of data points, i.e. there must be a + # c subset of data points y(j) such that + # c t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 + def test_condition_5_x1xm(self): + # x(1).ge.t(k2) .or. x(m).le.t(nk1) + k = 1 + t = [0, 0, 1, 2, 2] + x = [1.1, 1.1, 1.1] + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + x = [0.5, 0.5, 0.5] + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + def test_condition_5_k1(self): + # special case nk3 (== n - k - 2) < 2 + k = 1 + t = [0, 0, 1, 1] + x = [0.5, 0.6] + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + def test_condition_5_1(self): + # basically, there can't be an interval of t[j]..t[j+k+1] with no x + k = 3 + t = [0]*(k+1) + [2] + [5]*(k+1) + x = [3]*5 + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + t = [0]*(k+1) + [2] + [5]*(k+1) + x = [1]*5 + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + def test_condition_5_2(self): + # same as _5_1, only the empty interval is in the middle + k = 3 + t = [0]*(k+1) + [2, 3] + [5]*(k+1) + x = [1.1]*5 + [4] + + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + # and this one is OK + x = [1.1]*4 + [4, 4] + assert dfitpack.fpchec(x, t, k) == 0 + assert _b.fpcheck(x, t, k) is None + + def test_condition_5_3(self): + # similar to _5_2, covers a different failure branch + k = 1 + t = [0, 0, 2, 3, 4, 5, 6, 7, 7] + x = [1, 1, 1, 5.2, 5.2, 5.2, 6.5] + + assert dfitpack.fpchec(x, t, k) == 50 + with pytest.raises(ValueError, match="Schoenberg-Whitney*"): + _b.fpcheck(x, t, k) + + +# ### python replicas of generate_knots(...) implementation details, for testing. +# ### see TestGenerateKnots::test_split_and_add_knot +def _split(x, t, k, residuals): + """Split the knot interval into "runs". + """ + ix = np.searchsorted(x, t[k:-k]) + # sum half-open intervals + fparts = [residuals[ix[i]:ix[i+1]].sum() for i in range(len(ix)-1)] + carries = residuals[ix[1:-1]] + + for i in range(len(carries)): # split residuals at internal knots + carry = carries[i] / 2 + fparts[i] += carry + fparts[i+1] -= carry + + fparts[-1] += residuals[-1] # add the contribution of the last knot + + xp_assert_close(sum(fparts), sum(residuals), atol=1e-15) + + return fparts, ix + + +def _add_knot(x, t, k, residuals): + """Insert a new knot given reduals.""" + fparts, ix = _split(x, t, k, residuals) + + # find the interval with max fparts and non-zero number of x values inside + idx_max = -101 + fpart_max = -1e100 + for i in range(len(fparts)): + if ix[i+1] - ix[i] > 1 and fparts[i] > fpart_max: + idx_max = i + fpart_max = fparts[i] + + if idx_max == -101: + raise ValueError("Internal error, please report it to SciPy developers.") + + # round up, like Dierckx does? This is really arbitrary though. + idx_newknot = (ix[idx_max] + ix[idx_max+1] + 1) // 2 + new_knot = x[idx_newknot] + idx_t = np.searchsorted(t, new_knot) + t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]] + return t_new + + +class TestGenerateKnots: + def test_split_add_knot(self): + # smoke test implementation details: insert a new knot given residuals + x = np.arange(8, dtype=float) + y = x**3 + 1./(1 + x) + k = 3 + t = np.array([0.]*(k+1) + [7.]*(k+1)) + spl = make_lsq_spline(x, y, k=k, t=t) + residuals = (spl(x) - y)**2 + + from scipy.interpolate import _fitpack_repro as _fr + new_t = _fr.add_knot(x, t, k, residuals) + new_t_py = _add_knot(x, t, k, residuals) + + xp_assert_close(new_t, new_t_py, atol=1e-15) + + # redo with new knots + spl2 = make_lsq_spline(x, y, k=k, t=new_t) + residuals2 = (spl2(x) - y)**2 + + new_t2 = _fr.add_knot(x, new_t, k, residuals2) + new_t2_py = _add_knot(x, new_t, k, residuals2) + + xp_assert_close(new_t2, new_t2_py, atol=1e-15) + + @pytest.mark.parametrize('k', [1, 2, 3, 4, 5]) + def test_s0(self, k): + x = np.arange(8, dtype=np.float64) + y = np.sin(x*np.pi/8) + t = list(generate_knots(x, y, k=k, s=0))[-1] + + tt = splrep(x, y, k=k, s=0)[0] + xp_assert_close(t, tt, atol=1e-15) + + def test_s0_1(self): + # with these data, naive algorithm tries to insert >= nmax knots + n = 10 + x = np.arange(n) + y = x**3 + knots = list(generate_knots(x, y, k=3, s=0)) # does not error out + xp_assert_close(knots[-1], _not_a_knot(x, 3), atol=1e-15) + + def test_s0_n20(self): + n = 20 + x = np.arange(n) + y = x**3 + knots = list(generate_knots(x, y, k=3, s=0)) + xp_assert_close(knots[-1], _not_a_knot(x, 3), atol=1e-15) + + def test_s0_nest(self): + # s=0 and non-default nest: not implemented, errors out + x = np.arange(10) + y = x**3 + with assert_raises(ValueError): + list(generate_knots(x, y, k=3, s=0, nest=10)) + + def test_s_switch(self): + # test the process switching to interpolating knots when len(t) == m + k + 1 + """ + To generate the `wanted` list below apply the following diff and rerun + the test. The stdout will contain successive iterations of the `t` + array. + +$ git diff scipy/interpolate/fitpack/fpcurf.f +diff --git a/scipy/interpolate/fitpack/fpcurf.f b/scipy/interpolate/fitpack/fpcurf.f +index 1afb1900f1..d817e51ad8 100644 +--- a/scipy/interpolate/fitpack/fpcurf.f ++++ b/scipy/interpolate/fitpack/fpcurf.f +@@ -216,6 +216,9 @@ c t(j+k) <= x(i) <= t(j+k+1) and store it in fpint(j),j=1,2,...nrint. + do 190 l=1,nplus + c add a new knot. + call fpknot(x,m,t,n,fpint,nrdata,nrint,nest,1) ++ print*, l, nest, ': ', t ++ print*, "n, nmax = ", n, nmax ++ + c if n=nmax we locate the knots as for interpolation. + if(n.eq.nmax) go to 10 + c test whether we cannot further increase the number of knots. + """ # NOQA: E501 + x = np.arange(8) + y = np.sin(x*np.pi/8) + k = 3 + + knots = list(generate_knots(x, y, k=k, s=1e-7)) + wanted = [[0., 0., 0., 0., 7., 7., 7., 7.], + [0., 0., 0., 0., 4., 7., 7., 7., 7.], + [0., 0., 0., 0., 2., 4., 7., 7., 7., 7.], + [0., 0., 0., 0., 2., 4., 6., 7., 7., 7., 7.], + [0., 0., 0., 0., 2., 3., 4., 5., 7, 7., 7., 7.] + ] + + assert len(knots) == len(wanted) + for t, tt in zip(knots, wanted): + xp_assert_close(t, tt, atol=1e-15) + + # also check that the last knot vector matches FITPACK + t, _, _ = splrep(x, y, k=k, s=1e-7) + xp_assert_close(knots[-1], t, atol=1e-15) + + def test_list_input(self): + # test that list inputs are accepted + x = list(range(8)) + gen = generate_knots(x, x, s=0.1, k=1) + next(gen) + + def test_nest(self): + # test that nest < nmax stops the process early (and we get 10 knots not 12) + x = np.arange(8) + y = np.sin(x*np.pi/8) + s = 1e-7 + + knots = list(generate_knots(x, y, k=3, s=s, nest=10)) + xp_assert_close(knots[-1], + [0., 0., 0., 0., 2., 4., 7., 7., 7., 7.], atol=1e-15) + + with assert_raises(ValueError): + # nest < 2*(k+1) + list(generate_knots(x, y, k=3, nest=4)) + + def test_weights(self): + x = np.arange(8) + y = np.sin(x*np.pi/8) + + with assert_raises(ValueError): + list(generate_knots(x, y, w=np.arange(11))) # len(w) != len(x) + + with assert_raises(ValueError): + list(generate_knots(x, y, w=-np.ones(8))) # w < 0 + + @pytest.mark.parametrize("npts", [30, 50, 100]) + @pytest.mark.parametrize("s", [0.1, 1e-2, 0]) + def test_vs_splrep(self, s, npts): + # XXX this test is brittle: differences start apearing for k=3 and s=1e-6, + # also for k != 3. Might be worth investigating at some point. + # I think we do not really guarantee exact agreement with splrep. Instead, + # we guarantee it is the same *in most cases*; otherwise slight differences + # are allowed. There is no theorem, it is al heuristics by P. Dierckx. + # The best we can do it to best-effort reproduce it. + rndm = np.random.RandomState(12345) + x = 10*np.sort(rndm.uniform(size=npts)) + y = np.sin(x*np.pi/10) + np.exp(-(x-6)**2) + + k = 3 + t = splrep(x, y, k=k, s=s)[0] + tt = list(generate_knots(x, y, k=k, s=s))[-1] + + xp_assert_close(tt, t, atol=1e-15) + + @pytest.mark.thread_unsafe + def test_s_too_small(self): + n = 14 + x = np.arange(n) + y = x**3 + + # XXX splrep warns that "s too small": ier=2 + knots = list(generate_knots(x, y, k=3, s=1e-50)) + + with suppress_warnings() as sup: + r = sup.record(RuntimeWarning) + tck = splrep(x, y, k=3, s=1e-50) + assert len(r) == 1 + xp_assert_equal(knots[-1], tck[0]) + + +def disc_naive(t, k): + """Straitforward way to compute the discontinuity matrix. For testing ONLY. + + This routine returns a dense matrix, while `_fitpack_repro.disc` returns + a packed one. + """ + n = t.shape[0] + + delta = t[n - k - 1] - t[k] + nrint = n - 2*k - 1 + + ti = t[k+1:n-k-1] # internal knots + tii = np.repeat(ti, 2) + tii[::2] += 1e-10 + tii[1::2] -= 1e-10 + m = BSpline(t, np.eye(n - k - 1), k)(tii, nu=k) + + matr = np.empty((nrint-1, m.shape[1]), dtype=float) + for i in range(0, m.shape[0], 2): + matr[i//2, :] = m[i, :] - m[i+1, :] + + matr *= (delta/nrint)**k / math.factorial(k) + return matr + + +class F_dense: + """ The r.h.s. of ``f(p) = s``, an analog of _fitpack_repro.F + Uses full matrices, so is for tests only. + """ + def __init__(self, x, y, t, k, s, w=None): + self.x = x + self.y = y + self.t = t + self.k = k + self.w = np.ones_like(x, dtype=float) if w is None else w + assert self.w.ndim == 1 + + # lhs + a_dense = BSpline(t, np.eye(t.shape[0] - k - 1), k)(x) + self.a_dense = a_dense * self.w[:, None] + + from scipy.interpolate import _fitpack_repro as _fr + self.b_dense = PackedMatrix(*_fr.disc(t, k)).todense() + + # rhs + assert y.ndim == 1 + yy = y * self.w + self.yy = np.r_[yy, np.zeros(self.b_dense.shape[0])] + + self.s = s + + def __call__(self, p): + ab = np.vstack((self.a_dense, self.b_dense / p)) + + # LSQ solution of ab @ c = yy + from scipy.linalg import qr, solve + q, r = qr(ab, mode='economic') + + qy = q.T @ self.yy + + nc = r.shape[1] + c = solve(r[:nc, :nc], qy[:nc]) + + spl = BSpline(self.t, c, self.k) + fp = np.sum(self.w**2 * (spl(self.x) - self.y)**2) + + self.spl = spl # store it + + return fp - self.s + + +class TestMakeSplrep: + def test_input_errors(self): + x = np.linspace(0, 10, 11) + y = np.linspace(0, 10, 12) + with assert_raises(ValueError): + # len(x) != len(y) + make_splrep(x, y) + + with assert_raises(ValueError): + # 0D inputs + make_splrep(1, 2, s=0.1) + + with assert_raises(ValueError): + # y.ndim > 2 + y = np.ones((x.size, 2, 2, 2)) + make_splrep(x, y, s=0.1) + + w = np.ones(12) + with assert_raises(ValueError): + # len(weights) != len(x) + make_splrep(x, x**3, w=w, s=0.1) + + w = -np.ones(12) + with assert_raises(ValueError): + # w < 0 + make_splrep(x, x**3, w=w, s=0.1) + + w = np.ones((x.shape[0], 2)) + with assert_raises(ValueError): + # w.ndim != 1 + make_splrep(x, x**3, w=w, s=0.1) + + with assert_raises(ValueError): + # x not ordered + make_splrep(x[::-1], x**3, s=0.1) + + with assert_raises(TypeError): + # k != int(k) + make_splrep(x, x**3, k=2.5, s=0.1) + + with assert_raises(ValueError): + # s < 0 + make_splrep(x, x**3, s=-1) + + with assert_raises(ValueError): + # nest < 2*k + 2 + make_splrep(x, x**3, k=3, nest=2, s=0.1) + + with assert_raises(ValueError): + # nest not None and s==0 + make_splrep(x, x**3, s=0, nest=11) + + with assert_raises(ValueError): + # len(x) != len(y) + make_splrep(np.arange(8), np.arange(9), s=0.1) + + def _get_xykt(self): + x = np.linspace(0, 5, 11) + y = np.sin(x*3.14 / 5)**2 + k = 3 + s = 1.7e-4 + tt = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1)) + + return x, y, k, s, tt + + def test_fitpack_F(self): + # test an implementation detail: banded/packed linalg vs full matrices + from scipy.interpolate._fitpack_repro import F + + x, y, k, s, t = self._get_xykt() + f = F(x, y[:, None], t, k, s) # F expects y to be 2D + f_d = F_dense(x, y, t, k, s) + for p in [1, 10, 100]: + xp_assert_close(f(p), f_d(p), atol=1e-15) + + def test_fitpack_F_with_weights(self): + # repeat test_fitpack_F, with weights + from scipy.interpolate._fitpack_repro import F + + x, y, k, s, t = self._get_xykt() + w = np.arange(x.shape[0], dtype=float) + fw = F(x, y[:, None], t, k, s, w=w) # F expects y to be 2D + fw_d = F_dense(x, y, t, k, s, w=w) + + f_d = F_dense(x, y, t, k, s) # no weights + + for p in [1, 10, 100]: + xp_assert_close(fw(p), fw_d(p), atol=1e-15) + assert not np.allclose(f_d(p), fw_d(p), atol=1e-15) + + def test_disc_matrix(self): + # test an implementation detail: discontinuity matrix + # (jumps of k-th derivative at knots) + import scipy.interpolate._fitpack_repro as _fr + + rng = np.random.default_rng(12345) + t = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7))*5, 5, 5, 5, 5] + + n, k = len(t), 3 + D = PackedMatrix(*_fr.disc(t, k)).todense() + D_dense = disc_naive(t, k) + assert D.shape[0] == n - 2*k - 2 # number of internal knots + xp_assert_close(D, D_dense, atol=1e-15) + + def test_simple_vs_splrep(self): + x, y, k, s, tt = self._get_xykt() + tt = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1)) + + t,c,k = splrep(x, y, k=k, s=s) + assert all(t == tt) + + spl = make_splrep(x, y, k=k, s=s) + xp_assert_close(c[:spl.c.size], spl.c, atol=1e-15) + + def test_with_knots(self): + x, y, k, s, _ = self._get_xykt() + + t = list(generate_knots(x, y, k=k, s=s))[-1] + + spl_auto = make_splrep(x, y, k=k, s=s) + spl_t = make_splrep(x, y, t=t, k=k, s=s) + + xp_assert_close(spl_auto.t, spl_t.t, atol=1e-15) + xp_assert_close(spl_auto.c, spl_t.c, atol=1e-15) + assert spl_auto.k == spl_t.k + + def test_no_internal_knots(self): + # should not fail if there are no internal knots + n = 10 + x = np.arange(n) + y = x**3 + k = 3 + spl = make_splrep(x, y, k=k, s=1) + assert spl.t.shape[0] == 2*(k+1) + + def test_default_s(self): + n = 10 + x = np.arange(n) + y = x**3 + spl = make_splrep(x, y, k=3) + spl_i = make_interp_spline(x, y, k=3) + + xp_assert_close(spl.c, spl_i.c, atol=1e-15) + + @pytest.mark.thread_unsafe + def test_s_too_small(self): + # both splrep and make_splrep warn that "s too small": ier=2 + n = 14 + x = np.arange(n) + y = x**3 + + with suppress_warnings() as sup: + r = sup.record(RuntimeWarning) + tck = splrep(x, y, k=3, s=1e-50) + spl = make_splrep(x, y, k=3, s=1e-50) + assert len(r) == 2 + xp_assert_equal(spl.t, tck[0]) + xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)], + tck[1], atol=5e-13) + + def test_shape(self): + # make sure coefficients have the right shape (not extra dims) + n, k = 10, 3 + x = np.arange(n) + y = x**3 + + spl = make_splrep(x, y, k=k) + spl_1 = make_splrep(x, y, k=k, s=1e-5) + + assert spl.c.ndim == 1 + assert spl_1.c.ndim == 1 + + # force the general code path, not shortcuts + spl_2 = make_splrep(x, y + 1/(1+y), k=k, s=1e-5) + assert spl_2.c.ndim == 1 + + def test_s0_vs_not(self): + # check that the shapes are consistent + n, k = 10, 3 + x = np.arange(n) + y = x**3 + + spl_0 = make_splrep(x, y, k=3, s=0) + spl_1 = make_splrep(x, y, k=3, s=1) + + assert spl_0.c.ndim == 1 + assert spl_1.c.ndim == 1 + + assert spl_0.t.shape[0] == n + k + 1 + assert spl_1.t.shape[0] == 2 * (k + 1) + + +class TestMakeSplprep: + def _get_xyk(self, m=10, k=3): + x = np.arange(m) * np.pi / m + y = [np.sin(x), np.cos(x)] + return x, y, k + + @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5]) + def test_simple_vs_splprep(self, s): + # Check/document the interface vs splPrep + # The four values of `s` are to probe all code paths and shortcuts + m, k = 10, 3 + x = np.arange(m) * np.pi / m + y = [np.sin(x), np.cos(x)] + + # the number of knots depends on `s` (this is by construction) + num_knots = {0: 14, 0.1: 8, 1e-3: 8 + 1, 1e-5: 8 + 2} + + # construct the splines + (t, c, k), u_ = splprep(y, s=s) + spl, u = make_splprep(y, s=s) + + # parameters + xp_assert_close(u, u_, atol=1e-15) + + # knots + xp_assert_close(spl.t, t, atol=1e-15) + assert len(t) == num_knots[s] + + # coefficients: note the transpose + cc = np.asarray(c).T + xp_assert_close(spl.c, cc, atol=1e-15) + + # values: note axis=1 + xp_assert_close(spl(u), + BSpline(t, c, k, axis=1)(u), atol=1e-15) + + @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5]) + def test_array_not_list(self, s): + # the argument of splPrep is either a list of arrays or a 2D array (sigh) + _, y, _ = self._get_xyk() + assert isinstance(y, list) + assert np.shape(y)[0] == 2 + + # assert the behavior of FITPACK's splrep + tck, u = splprep(y, s=s) + tck_a, u_a = splprep(np.asarray(y), s=s) + xp_assert_close(u, u_a, atol=s) + xp_assert_close(tck[0], tck_a[0], atol=1e-15) + assert len(tck[1]) == len(tck_a[1]) + for c1, c2 in zip(tck[1], tck_a[1]): + xp_assert_close(c1, c2, atol=1e-15) + assert tck[2] == tck_a[2] + assert np.shape(splev(u, tck)) == np.shape(y) + + spl, u = make_splprep(y, s=s) + xp_assert_close(u, u_a, atol=1e-15) + xp_assert_close(spl.t, tck_a[0], atol=1e-15) + xp_assert_close(spl.c.T, tck_a[1], atol=1e-15) + assert spl.k == tck_a[2] + assert spl(u).shape == np.shape(y) + + spl, u = make_splprep(np.asarray(y), s=s) + xp_assert_close(u, u_a, atol=1e-15) + xp_assert_close(spl.t, tck_a[0], atol=1e-15) + xp_assert_close(spl.c.T, tck_a[1], atol=1e-15) + assert spl.k == tck_a[2] + assert spl(u).shape == np.shape(y) + + with assert_raises(ValueError): + make_splprep(np.asarray(y).T, s=s) + + def test_default_s_is_zero(self): + x, y, k = self._get_xyk(m=10) + + spl, u = make_splprep(y) + xp_assert_close(spl(u), y, atol=1e-15) + + def test_s_zero_vs_near_zero(self): + # s=0 and s \approx 0 are consistent + x, y, k = self._get_xyk(m=10) + + spl_i, u_i = make_splprep(y, s=0) + spl_n, u_n = make_splprep(y, s=1e-15) + + xp_assert_close(u_i, u_n, atol=1e-15) + xp_assert_close(spl_i(u_i), y, atol=1e-15) + xp_assert_close(spl_n(u_n), y, atol=1e-7) + assert spl_i.axis == spl_n.axis + assert spl_i.c.shape == spl_n.c.shape + + def test_1D(self): + x = np.arange(8, dtype=float) + with assert_raises(ValueError): + splprep(x) + + with assert_raises(ValueError): + make_splprep(x, s=0) + + with assert_raises(ValueError): + make_splprep(x, s=0.1) + + tck, u_ = splprep([x], s=1e-5) + spl, u = make_splprep([x], s=1e-5) + + assert spl(u).shape == (1, 8) + xp_assert_close(spl(u), [x], atol=1e-15) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py new file mode 100644 index 0000000000000000000000000000000000000000..d798f0eda4eb0c099bdf46cb4b3468628013c9d3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py @@ -0,0 +1,519 @@ +import itertools +import os + +import numpy as np +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal +) +from pytest import raises as assert_raises +import pytest +from scipy._lib._testutils import check_free_memory + +from scipy.interpolate import RectBivariateSpline +from scipy.interpolate import make_splrep + +from scipy.interpolate._fitpack_py import (splrep, splev, bisplrep, bisplev, + sproot, splprep, splint, spalde, splder, splantider, insert, dblint) +from scipy.interpolate._dfitpack import regrid_smth +from scipy.interpolate._fitpack2 import dfitpack_int + + +def data_file(basename): + return os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', basename) + + +def norm2(x): + return np.sqrt(np.dot(x.T, x)) + + +def f1(x, d=0): + """Derivatives of sin->cos->-sin->-cos.""" + if d % 4 == 0: + return np.sin(x) + if d % 4 == 1: + return np.cos(x) + if d % 4 == 2: + return -np.sin(x) + if d % 4 == 3: + return -np.cos(x) + + +def makepairs(x, y): + """Helper function to create an array of pairs of x and y.""" + xy = np.array(list(itertools.product(np.asarray(x), np.asarray(y)))) + return xy.T + + +class TestSmokeTests: + """ + Smoke tests (with a few asserts) for fitpack routines -- mostly + check that they are runnable + """ + def check_1(self, per=0, s=0, a=0, b=2*np.pi, at_nodes=False, + xb=None, xe=None): + if xb is None: + xb = a + if xe is None: + xe = b + + N = 20 + # nodes and middle points of the nodes + x = np.linspace(a, b, N + 1) + x1 = a + (b - a) * np.arange(1, N, dtype=float) / float(N - 1) + v = f1(x) + + def err_est(k, d): + # Assume f has all derivatives < 1 + h = 1.0 / N + tol = 5 * h**(.75*(k-d)) + if s > 0: + tol += 1e5*s + return tol + + for k in range(1, 6): + tck = splrep(x, v, s=s, per=per, k=k, xe=xe) + tt = tck[0][k:-k] if at_nodes else x1 + + for d in range(k+1): + tol = err_est(k, d) + err = norm2(f1(tt, d) - splev(tt, tck, d)) / norm2(f1(tt, d)) + assert err < tol + + # smoke test make_splrep + if not per: + spl = make_splrep(x, v, k=k, s=s, xb=xb, xe=xe) + if len(spl.t) == len(tck[0]): + xp_assert_close(spl.t, tck[0], atol=1e-15) + xp_assert_close(spl.c, tck[1][:spl.c.size], atol=1e-13) + else: + assert k == 5 # knot length differ in some k=5 cases + + def check_2(self, per=0, N=20, ia=0, ib=2*np.pi): + a, b, dx = 0, 2*np.pi, 0.2*np.pi + x = np.linspace(a, b, N+1) # nodes + v = np.sin(x) + + def err_est(k, d): + # Assume f has all derivatives < 1 + h = 1.0 / N + tol = 5 * h**(.75*(k-d)) + return tol + + nk = [] + for k in range(1, 6): + tck = splrep(x, v, s=0, per=per, k=k, xe=b) + nk.append([splint(ia, ib, tck), spalde(dx, tck)]) + + k = 1 + for r in nk: + d = 0 + for dr in r[1]: + tol = err_est(k, d) + xp_assert_close(dr, f1(dx, d), atol=0, rtol=tol) + d = d+1 + k = k+1 + + def test_smoke_splrep_splev(self): + self.check_1(s=1e-6) + self.check_1(b=1.5*np.pi) + self.check_1(b=1.5*np.pi, xe=2*np.pi, per=1, s=1e-1) + + @pytest.mark.parametrize('per', [0, 1]) + @pytest.mark.parametrize('at_nodes', [True, False]) + def test_smoke_splrep_splev_2(self, per, at_nodes): + self.check_1(per=per, at_nodes=at_nodes) + + @pytest.mark.parametrize('N', [20, 50]) + @pytest.mark.parametrize('per', [0, 1]) + def test_smoke_splint_spalde(self, N, per): + self.check_2(per=per, N=N) + + @pytest.mark.parametrize('N', [20, 50]) + @pytest.mark.parametrize('per', [0, 1]) + def test_smoke_splint_spalde_iaib(self, N, per): + self.check_2(ia=0.2*np.pi, ib=np.pi, N=N, per=per) + + def test_smoke_sproot(self): + # sproot is only implemented for k=3 + a, b = 0.1, 15 + x = np.linspace(a, b, 20) + v = np.sin(x) + + for k in [1, 2, 4, 5]: + tck = splrep(x, v, s=0, per=0, k=k, xe=b) + with assert_raises(ValueError): + sproot(tck) + + k = 3 + tck = splrep(x, v, s=0, k=3) + roots = sproot(tck) + xp_assert_close(splev(roots, tck), np.zeros(len(roots)), atol=1e-10, rtol=1e-10) + xp_assert_close(roots, np.pi * np.array([1, 2, 3, 4]), rtol=1e-3) + + @pytest.mark.parametrize('N', [20, 50]) + @pytest.mark.parametrize('k', [1, 2, 3, 4, 5]) + def test_smoke_splprep_splrep_splev(self, N, k): + a, b, dx = 0, 2.*np.pi, 0.2*np.pi + x = np.linspace(a, b, N+1) # nodes + v = np.sin(x) + + tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1) + uv = splev(dx, tckp) + err1 = abs(uv[1] - np.sin(uv[0])) + assert err1 < 1e-2 + + tck = splrep(x, v, s=0, per=0, k=k) + err2 = abs(splev(uv[0], tck) - np.sin(uv[0])) + assert err2 < 1e-2 + + # Derivatives of parametric cubic spline at u (first function) + if k == 3: + tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1) + for d in range(1, k+1): + uv = splev(dx, tckp, d) + + def test_smoke_bisplrep_bisplev(self): + xb, xe = 0, 2.*np.pi + yb, ye = 0, 2.*np.pi + kx, ky = 3, 3 + Nx, Ny = 20, 20 + + def f2(x, y): + return np.sin(x+y) + + x = np.linspace(xb, xe, Nx + 1) + y = np.linspace(yb, ye, Ny + 1) + xy = makepairs(x, y) + tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky) + + tt = [tck[0][kx:-kx], tck[1][ky:-ky]] + t2 = makepairs(tt[0], tt[1]) + v1 = bisplev(tt[0], tt[1], tck) + v2 = f2(t2[0], t2[1]) + v2.shape = len(tt[0]), len(tt[1]) + + assert norm2(np.ravel(v1 - v2)) < 1e-2 + + +class TestSplev: + def test_1d_shape(self): + x = [1,2,3,4,5] + y = [4,5,6,7,8] + tck = splrep(x, y) + z = splev([1], tck) + assert z.shape == (1,) + z = splev(1, tck) + assert z.shape == () + + def test_2d_shape(self): + x = [1, 2, 3, 4, 5] + y = [4, 5, 6, 7, 8] + tck = splrep(x, y) + t = np.array([[1.0, 1.5, 2.0, 2.5], + [3.0, 3.5, 4.0, 4.5]]) + z = splev(t, tck) + z0 = splev(t[0], tck) + z1 = splev(t[1], tck) + xp_assert_equal(z, np.vstack((z0, z1))) + + def test_extrapolation_modes(self): + # test extrapolation modes + # * if ext=0, return the extrapolated value. + # * if ext=1, return 0 + # * if ext=2, raise a ValueError + # * if ext=3, return the boundary value. + x = [1,2,3] + y = [0,2,4] + tck = splrep(x, y, k=1) + + rstl = [[-2, 6], [0, 0], None, [0, 4]] + for ext in (0, 1, 3): + assert_array_almost_equal(splev([0, 4], tck, ext=ext), rstl[ext]) + + assert_raises(ValueError, splev, [0, 4], tck, ext=2) + + +class TestSplder: + def setup_method(self): + # non-uniform grid, just to make it sure + x = np.linspace(0, 1, 100)**3 + y = np.sin(20 * x) + self.spl = splrep(x, y) + + # double check that knots are non-uniform + assert np.ptp(np.diff(self.spl[0])) > 0 + + def test_inverse(self): + # Check that antiderivative + derivative is identity. + for n in range(5): + spl2 = splantider(self.spl, n) + spl3 = splder(spl2, n) + xp_assert_close(self.spl[0], spl3[0]) + xp_assert_close(self.spl[1], spl3[1]) + assert self.spl[2] == spl3[2] + + def test_splder_vs_splev(self): + # Check derivative vs. FITPACK + + for n in range(3+1): + # Also extrapolation! + xx = np.linspace(-1, 2, 2000) + if n == 3: + # ... except that FITPACK extrapolates strangely for + # order 0, so let's not check that. + xx = xx[(xx >= 0) & (xx <= 1)] + + dy = splev(xx, self.spl, n) + spl2 = splder(self.spl, n) + dy2 = splev(xx, spl2) + if n == 1: + xp_assert_close(dy, dy2, rtol=2e-6) + else: + xp_assert_close(dy, dy2) + + def test_splantider_vs_splint(self): + # Check antiderivative vs. FITPACK + spl2 = splantider(self.spl) + + # no extrapolation, splint assumes function is zero outside + # range + xx = np.linspace(0, 1, 20) + + for x1 in xx: + for x2 in xx: + y1 = splint(x1, x2, self.spl) + y2 = splev(x2, spl2) - splev(x1, spl2) + xp_assert_close(np.asarray(y1), np.asarray(y2)) + + def test_order0_diff(self): + assert_raises(ValueError, splder, self.spl, 4) + + def test_kink(self): + # Should refuse to differentiate splines with kinks + + spl2 = insert(0.5, self.spl, m=2) + splder(spl2, 2) # Should work + assert_raises(ValueError, splder, spl2, 3) + + spl2 = insert(0.5, self.spl, m=3) + splder(spl2, 1) # Should work + assert_raises(ValueError, splder, spl2, 2) + + spl2 = insert(0.5, self.spl, m=4) + assert_raises(ValueError, splder, spl2, 1) + + def test_multidim(self): + # c can have trailing dims + for n in range(3): + t, c, k = self.spl + c2 = np.c_[c, c, c] + c2 = np.dstack((c2, c2)) + + spl2 = splantider((t, c2, k), n) + spl3 = splder(spl2, n) + + xp_assert_close(t, spl3[0]) + xp_assert_close(c2, spl3[1]) + assert k == spl3[2] + + +class TestSplint: + def test_len_c(self): + n, k = 7, 3 + x = np.arange(n) + y = x**3 + t, c, k = splrep(x, y, s=0) + + # note that len(c) == len(t) == 11 (== len(x) + 2*(k-1)) + assert len(t) == len(c) == n + 2*(k-1) + + # integrate directly: $\int_0^6 x^3 dx = 6^4 / 4$ + res = splint(0, 6, (t, c, k)) + expected = 6**4 / 4 + assert abs(res - expected) < 1e-13 + + # check that the coefficients past len(t) - k - 1 are ignored + c0 = c.copy() + c0[len(t) - k - 1:] = np.nan + res0 = splint(0, 6, (t, c0, k)) + assert abs(res0 - expected) < 1e-13 + + # however, all other coefficients *are* used + c0[6] = np.nan + assert np.isnan(splint(0, 6, (t, c0, k))) + + # check that the coefficient array can have length `len(t) - k - 1` + c1 = c[:len(t) - k - 1] + res1 = splint(0, 6, (t, c1, k)) + assert (res1 - expected) < 1e-13 + + + # however shorter c arrays raise. The error from f2py is a + # `dftipack.error`, which is an Exception but not ValueError etc. + with assert_raises(Exception, match=r">=n-k-1"): + splint(0, 1, (np.ones(10), np.ones(5), 3)) + + +class TestBisplrep: + def test_overflow(self): + from numpy.lib.stride_tricks import as_strided + if dfitpack_int.itemsize == 8: + size = 1500000**2 + else: + size = 400**2 + # Don't allocate a real array, as it's very big, but rely + # on that it's not referenced + x = as_strided(np.zeros(()), shape=(size,)) + assert_raises(OverflowError, bisplrep, x, x, x, w=x, + xb=0, xe=1, yb=0, ye=1, s=0) + + def test_regression_1310(self): + # Regression test for gh-1310 + with np.load(data_file('bug-1310.npz')) as loaded_data: + data = loaded_data['data'] + + # Shouldn't crash -- the input data triggers work array sizes + # that caused previously some data to not be aligned on + # sizeof(double) boundaries in memory, which made the Fortran + # code to crash when compiled with -O3 + bisplrep(data[:,0], data[:,1], data[:,2], kx=3, ky=3, s=0, + full_output=True) + + @pytest.mark.skipif(dfitpack_int != np.int64, reason="needs ilp64 fitpack") + def test_ilp64_bisplrep(self): + check_free_memory(28000) # VM size, doesn't actually use the pages + x = np.linspace(0, 1, 400) + y = np.linspace(0, 1, 400) + x, y = np.meshgrid(x, y) + z = np.zeros_like(x) + tck = bisplrep(x, y, z, kx=3, ky=3, s=0) + xp_assert_close(bisplev(0.5, 0.5, tck), 0.0) + + +def test_dblint(): + # Basic test to see it runs and gives the correct result on a trivial + # problem. Note that `dblint` is not exposed in the interpolate namespace. + x = np.linspace(0, 1) + y = np.linspace(0, 1) + xx, yy = np.meshgrid(x, y) + rect = RectBivariateSpline(x, y, 4 * xx * yy) + tck = list(rect.tck) + tck.extend(rect.degrees) + + assert abs(dblint(0, 1, 0, 1, tck) - 1) < 1e-10 + assert abs(dblint(0, 0.5, 0, 1, tck) - 0.25) < 1e-10 + assert abs(dblint(0.5, 1, 0, 1, tck) - 0.75) < 1e-10 + assert abs(dblint(-100, 100, -100, 100, tck) - 1) < 1e-10 + + +def test_splev_der_k(): + # regression test for gh-2188: splev(x, tck, der=k) gives garbage or crashes + # for x outside of knot range + + # test case from gh-2188 + tck = (np.array([0., 0., 2.5, 2.5]), + np.array([-1.56679978, 2.43995873, 0., 0.]), + 1) + t, c, k = tck + x = np.array([-3, 0, 2.5, 3]) + + # an explicit form of the linear spline + xp_assert_close(splev(x, tck), c[0] + (c[1] - c[0]) * x/t[2]) + xp_assert_close(splev(x, tck, 1), + np.ones_like(x) * (c[1] - c[0]) / t[2] + ) + + # now check a random spline vs splder + np.random.seed(1234) + x = np.sort(np.random.random(30)) + y = np.random.random(30) + t, c, k = splrep(x, y) + + x = [t[0] - 1., t[-1] + 1.] + tck2 = splder((t, c, k), k) + xp_assert_close(splev(x, (t, c, k), k), splev(x, tck2)) + + +def test_splprep_segfault(): + # regression test for gh-3847: splprep segfaults if knots are specified + # for task=-1 + t = np.arange(0, 1.1, 0.1) + x = np.sin(2*np.pi*t) + y = np.cos(2*np.pi*t) + tck, u = splprep([x, y], s=0) + np.arange(0, 1.01, 0.01) + + uknots = tck[0] # using the knots from the previous fitting + tck, u = splprep([x, y], task=-1, t=uknots) # here is the crash + + +def test_bisplev_integer_overflow(): + np.random.seed(1) + + x = np.linspace(0, 1, 11) + y = x + z = np.random.randn(11, 11).ravel() + kx = 1 + ky = 1 + + nx, tx, ny, ty, c, fp, ier = regrid_smth( + x, y, z, None, None, None, None, kx=kx, ky=ky, s=0.0) + tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], kx, ky) + + xp = np.zeros([2621440]) + yp = np.zeros([2621440]) + + assert_raises((RuntimeError, MemoryError), bisplev, xp, yp, tck) + + +@pytest.mark.xslow +def test_gh_1766(): + # this should fail gracefully instead of segfaulting (int overflow) + size = 22 + kx, ky = 3, 3 + def f2(x, y): + return np.sin(x+y) + + x = np.linspace(0, 10, size) + y = np.linspace(50, 700, size) + xy = makepairs(x, y) + tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky) + # the size value here can either segfault + # or produce a MemoryError on main + tx_ty_size = 500000 + tck[0] = np.arange(tx_ty_size) + tck[1] = np.arange(tx_ty_size) * 4 + tt_0 = np.arange(50) + tt_1 = np.arange(50) * 3 + with pytest.raises(MemoryError): + bisplev(tt_0, tt_1, tck, 1, 1) + + +def test_spalde_scalar_input(): + # Ticket #629 + x = np.linspace(0, 10) + y = x**3 + tck = splrep(x, y, k=3, t=[5]) + res = spalde(np.float64(1), tck) + des = np.array([1., 3., 6., 6.]) + assert_almost_equal(res, des) + + +def test_spalde_nc(): + # regression test for https://github.com/scipy/scipy/issues/19002 + # here len(t) = 29 and len(c) = 25 (== len(t) - k - 1) + x = np.asarray([-10., -9., -8., -7., -6., -5., -4., -3., -2.5, -2., -1.5, + -1., -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 4., 5., 6.], + dtype="float") + t = [-10.0, -10.0, -10.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, + -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, + 5.0, 6.0, 6.0, 6.0, 6.0] + c = np.asarray([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.]) + k = 3 + + res = spalde(x, (t, c, k)) + res = np.vstack(res) + res_splev = np.asarray([splev(x, (t, c, k), nu) for nu in range(4)]) + xp_assert_close(res, res_splev.T, atol=1e-15) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack2.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..044ace830bc6af26ee12edbcc6488e46bdfbcce6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack2.py @@ -0,0 +1,1393 @@ +# Created by Pearu Peterson, June 2003 +import itertools +from threading import Lock +import numpy as np +from numpy.testing import suppress_warnings +import pytest +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal +) + +from numpy import array, diff, linspace, meshgrid, ones, pi, shape +from scipy.interpolate._fitpack_py import bisplrep, bisplev, splrep, spalde +from scipy.interpolate._fitpack2 import (UnivariateSpline, + LSQUnivariateSpline, InterpolatedUnivariateSpline, + LSQBivariateSpline, SmoothBivariateSpline, RectBivariateSpline, + LSQSphereBivariateSpline, SmoothSphereBivariateSpline, + RectSphereBivariateSpline) + +from scipy._lib._testutils import _run_concurrent_barrier + +from scipy.interpolate import make_splrep + +class TestUnivariateSpline: + def test_linear_constant(self): + x = [1,2,3] + y = [3,3,3] + lut = UnivariateSpline(x,y,k=1) + assert_array_almost_equal(lut.get_knots(), [1, 3]) + assert_array_almost_equal(lut.get_coeffs(), [3, 3]) + assert abs(lut.get_residual()) < 1e-10 + assert_array_almost_equal(lut([1, 1.5, 2]), [3, 3, 3]) + + spl = make_splrep(x, y, k=1, s=len(x)) + xp_assert_close(spl.t[1:-1], lut.get_knots(), atol=1e-15) + xp_assert_close(spl.c, lut.get_coeffs(), atol=1e-15) + + def test_preserve_shape(self): + x = [1, 2, 3] + y = [0, 2, 4] + lut = UnivariateSpline(x, y, k=1) + arg = 2 + assert shape(arg) == shape(lut(arg)) + assert shape(arg) == shape(lut(arg, nu=1)) + arg = [1.5, 2, 2.5] + assert shape(arg) == shape(lut(arg)) + assert shape(arg) == shape(lut(arg, nu=1)) + + def test_linear_1d(self): + x = [1,2,3] + y = [0,2,4] + lut = UnivariateSpline(x,y,k=1) + assert_array_almost_equal(lut.get_knots(),[1,3]) + assert_array_almost_equal(lut.get_coeffs(),[0,4]) + assert abs(lut.get_residual()) < 1e-15 + assert_array_almost_equal(lut([1,1.5,2]),[0,1,2]) + + def test_subclassing(self): + # See #731 + + class ZeroSpline(UnivariateSpline): + def __call__(self, x): + return 0*array(x) + + sp = ZeroSpline([1,2,3,4,5], [3,2,3,2,3], k=2) + xp_assert_equal(sp([1.5, 2.5]), [0., 0.]) + + def test_empty_input(self): + # Test whether empty input returns an empty output. Ticket 1014 + x = [1,3,5,7,9] + y = [0,4,9,12,21] + spl = UnivariateSpline(x, y, k=3) + xp_assert_equal(spl([]), array([])) + + def test_roots(self): + x = [1, 3, 5, 7, 9] + y = [0, 4, 9, 12, 21] + spl = UnivariateSpline(x, y, k=3) + assert_almost_equal(spl.roots()[0], 1.050290639101332) + + def test_roots_length(self): # for gh18335 + x = np.linspace(0, 50 * np.pi, 1000) + y = np.cos(x) + spl = UnivariateSpline(x, y, s=0) + assert len(spl.roots()) == 50 + + def test_derivatives(self): + x = [1, 3, 5, 7, 9] + y = [0, 4, 9, 12, 21] + spl = UnivariateSpline(x, y, k=3) + assert_almost_equal(spl.derivatives(3.5), + [5.5152902, 1.7146577, -0.1830357, 0.3125]) + + def test_derivatives_2(self): + x = np.arange(8) + y = x**3 + 2.*x**2 + + tck = splrep(x, y, s=0) + ders = spalde(3, tck) + xp_assert_close(ders, [45., # 3**3 + 2*(3)**2 + 39., # 3*(3)**2 + 4*(3) + 22., # 6*(3) + 4 + 6.], # 6*3**0 + atol=1e-15) + spl = UnivariateSpline(x, y, s=0, k=3) + xp_assert_close(spl.derivatives(3), + ders, + atol=1e-15) + + def test_resize_regression(self): + """Regression test for #1375.""" + x = [-1., -0.65016502, -0.58856235, -0.26903553, -0.17370892, + -0.10011001, 0., 0.10011001, 0.17370892, 0.26903553, 0.58856235, + 0.65016502, 1.] + y = [1.,0.62928599, 0.5797223, 0.39965815, 0.36322694, 0.3508061, + 0.35214793, 0.3508061, 0.36322694, 0.39965815, 0.5797223, + 0.62928599, 1.] + w = [1.00000000e+12, 6.88875973e+02, 4.89314737e+02, 4.26864807e+02, + 6.07746770e+02, 4.51341444e+02, 3.17480210e+02, 4.51341444e+02, + 6.07746770e+02, 4.26864807e+02, 4.89314737e+02, 6.88875973e+02, + 1.00000000e+12] + spl = UnivariateSpline(x=x, y=y, w=w, s=None) + desired = array([0.35100374, 0.51715855, 0.87789547, 0.98719344]) + xp_assert_close(spl([0.1, 0.5, 0.9, 0.99]), desired, atol=5e-4) + + def test_out_of_range_regression(self): + # Test different extrapolation modes. See ticket 3557 + x = np.arange(5, dtype=float) + y = x**3 + + xp = linspace(-8, 13, 100) + xp_zeros = xp.copy() + xp_zeros[np.logical_or(xp_zeros < 0., xp_zeros > 4.)] = 0 + xp_clip = xp.copy() + xp_clip[xp_clip < x[0]] = x[0] + xp_clip[xp_clip > x[-1]] = x[-1] + + for cls in [UnivariateSpline, InterpolatedUnivariateSpline]: + spl = cls(x=x, y=y) + for ext in [0, 'extrapolate']: + xp_assert_close(spl(xp, ext=ext), xp**3, atol=1e-16) + xp_assert_close(cls(x, y, ext=ext)(xp), xp**3, atol=1e-16) + for ext in [1, 'zeros']: + xp_assert_close(spl(xp, ext=ext), xp_zeros**3, atol=1e-16) + xp_assert_close(cls(x, y, ext=ext)(xp), xp_zeros**3, atol=1e-16) + for ext in [2, 'raise']: + assert_raises(ValueError, spl, xp, **dict(ext=ext)) + for ext in [3, 'const']: + xp_assert_close(spl(xp, ext=ext), xp_clip**3, atol=2e-16) + xp_assert_close(cls(x, y, ext=ext)(xp), xp_clip**3, atol=2e-16) + + # also test LSQUnivariateSpline [which needs explicit knots] + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + spl = LSQUnivariateSpline(x, y, t) + xp_assert_close(spl(xp, ext=0), xp**3, atol=1e-16) + xp_assert_close(spl(xp, ext=1), xp_zeros**3, atol=1e-16) + assert_raises(ValueError, spl, xp, **dict(ext=2)) + xp_assert_close(spl(xp, ext=3), xp_clip**3, atol=1e-16) + + # also make sure that unknown values for `ext` are caught early + for ext in [-1, 'unknown']: + spl = UnivariateSpline(x, y) + assert_raises(ValueError, spl, xp, **dict(ext=ext)) + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, ext=ext)) + + def test_lsq_fpchec(self): + xs = np.arange(100) * 1. + ys = np.arange(100) * 1. + knots = np.linspace(0, 99, 10) + bbox = (-1, 101) + assert_raises(ValueError, LSQUnivariateSpline, xs, ys, knots, + bbox=bbox) + + def test_derivative_and_antiderivative(self): + # Thin wrappers to splder/splantider, so light smoke test only. + x = np.linspace(0, 1, 70)**3 + y = np.cos(x) + + spl = UnivariateSpline(x, y, s=0) + spl2 = spl.antiderivative(2).derivative(2) + xp_assert_close(spl(0.3), spl2(0.3)) + + spl2 = spl.antiderivative(1) + xp_assert_close(spl2(0.6) - spl2(0.2), + spl.integral(0.2, 0.6)) + + def test_derivative_extrapolation(self): + # Regression test for gh-10195: for a const-extrapolation spline + # its derivative evaluates to zero for extrapolation + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 5] + f = UnivariateSpline(x_values, y_values, ext='const', k=3) + + x = [-1, 0, -0.5, 9, 9.5, 10] + xp_assert_close(f.derivative()(x), np.zeros_like(x), atol=1e-15) + + def test_integral_out_of_bounds(self): + # Regression test for gh-7906: .integral(a, b) is wrong if both + # a and b are out-of-bounds + x = np.linspace(0., 1., 7) + for ext in range(4): + f = UnivariateSpline(x, x, s=0, ext=ext) + for (a, b) in [(1, 1), (1, 5), (2, 5), + (0, 0), (-2, 0), (-2, -1)]: + assert abs(f.integral(a, b)) < 1e-15 + + def test_nan(self): + # bail out early if the input data contains nans + x = np.arange(10, dtype=float) + y = x**3 + w = np.ones_like(x) + # also test LSQUnivariateSpline [which needs explicit knots] + spl = UnivariateSpline(x, y, check_finite=True) + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + y_end = y[-1] + for z in [np.nan, np.inf, -np.inf]: + y[-1] = z + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, LSQUnivariateSpline, + **dict(x=x, y=y, t=t, check_finite=True)) + y[-1] = y_end # check valid y but invalid w + w[-1] = z + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, w=w, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, w=w, check_finite=True)) + assert_raises(ValueError, LSQUnivariateSpline, + **dict(x=x, y=y, t=t, w=w, check_finite=True)) + + def test_strictly_increasing_x(self): + # Test the x is required to be strictly increasing for + # UnivariateSpline if s=0 and for InterpolatedUnivariateSpline, + # but merely increasing for UnivariateSpline if s>0 + # and for LSQUnivariateSpline; see gh-8535 + xx = np.arange(10, dtype=float) + yy = xx**3 + x = np.arange(10, dtype=float) + x[1] = x[0] + y = x**3 + w = np.ones_like(x) + # also test LSQUnivariateSpline [which needs explicit knots] + spl = UnivariateSpline(xx, yy, check_finite=True) + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + UnivariateSpline(x=x, y=y, w=w, s=1, check_finite=True) + LSQUnivariateSpline(x=x, y=y, t=t, w=w, check_finite=True) + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, s=0, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + + def test_increasing_x(self): + # Test that x is required to be increasing, see gh-8535 + xx = np.arange(10, dtype=float) + yy = xx**3 + x = np.arange(10, dtype=float) + x[1] = x[0] - 1.0 + y = x**3 + w = np.ones_like(x) + # also test LSQUnivariateSpline [which needs explicit knots] + spl = UnivariateSpline(xx, yy, check_finite=True) + t = spl.get_knots()[3:4] # interior knots w/ default k=3 + assert_raises(ValueError, UnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, InterpolatedUnivariateSpline, + **dict(x=x, y=y, check_finite=True)) + assert_raises(ValueError, LSQUnivariateSpline, + **dict(x=x, y=y, t=t, w=w, check_finite=True)) + + def test_invalid_input_for_univariate_spline(self): + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5] + UnivariateSpline(x_values, y_values) + assert "x and y should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + w_values = [-1.0, 1.0, 1.0, 1.0] + UnivariateSpline(x_values, y_values, w=w_values) + assert "x, y, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-1) + UnivariateSpline(x_values, y_values, bbox=bbox) + assert "bbox shape should be (2,)" in str(info.value) + + with assert_raises(ValueError) as info: + UnivariateSpline(x_values, y_values, k=6) + assert "k should be 1 <= k <= 5" in str(info.value) + + with assert_raises(ValueError) as info: + UnivariateSpline(x_values, y_values, s=-1.0) + assert "s should be s >= 0.0" in str(info.value) + + def test_invalid_input_for_interpolated_univariate_spline(self): + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5] + InterpolatedUnivariateSpline(x_values, y_values) + assert "x and y should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + w_values = [-1.0, 1.0, 1.0, 1.0] + InterpolatedUnivariateSpline(x_values, y_values, w=w_values) + assert "x, y, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-1) + InterpolatedUnivariateSpline(x_values, y_values, bbox=bbox) + assert "bbox shape should be (2,)" in str(info.value) + + with assert_raises(ValueError) as info: + InterpolatedUnivariateSpline(x_values, y_values, k=6) + assert "k should be 1 <= k <= 5" in str(info.value) + + def test_invalid_input_for_lsq_univariate_spline(self): + + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + spl = UnivariateSpline(x_values, y_values, check_finite=True) + t_values = spl.get_knots()[3:4] # interior knots w/ default k=3 + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5] + LSQUnivariateSpline(x_values, y_values, t_values) + assert "x and y should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x_values = [1, 2, 4, 6, 8.5] + y_values = [0.5, 0.8, 1.3, 2.5, 2.8] + w_values = [1.0, 1.0, 1.0, 1.0] + LSQUnivariateSpline(x_values, y_values, t_values, w=w_values) + assert "x, y, and w should have a same length" in str(info.value) + + message = "Interior knots t must satisfy Schoenberg-Whitney conditions" + with assert_raises(ValueError, match=message) as info: + bbox = (100, -100) + LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox) + + with assert_raises(ValueError) as info: + bbox = (-1) + LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox) + assert "bbox shape should be (2,)" in str(info.value) + + with assert_raises(ValueError) as info: + LSQUnivariateSpline(x_values, y_values, t_values, k=6) + assert "k should be 1 <= k <= 5" in str(info.value) + + def test_array_like_input(self): + x_values = np.array([1, 2, 4, 6, 8.5]) + y_values = np.array([0.5, 0.8, 1.3, 2.5, 2.8]) + w_values = np.array([1.0, 1.0, 1.0, 1.0, 1.0]) + bbox = np.array([-100, 100]) + # np.array input + spl1 = UnivariateSpline(x=x_values, y=y_values, w=w_values, + bbox=bbox) + # list input + spl2 = UnivariateSpline(x=x_values.tolist(), y=y_values.tolist(), + w=w_values.tolist(), bbox=bbox.tolist()) + + xp_assert_close(spl1([0.1, 0.5, 0.9, 0.99]), + spl2([0.1, 0.5, 0.9, 0.99])) + + @pytest.mark.thread_unsafe + def test_fpknot_oob_crash(self): + # https://github.com/scipy/scipy/issues/3691 + x = range(109) + y = [0., 0., 0., 0., 0., 10.9, 0., 11., 0., + 0., 0., 10.9, 0., 0., 0., 0., 0., 0., + 10.9, 0., 0., 0., 11., 0., 0., 0., 10.9, + 0., 0., 0., 10.5, 0., 0., 0., 10.7, 0., + 0., 0., 11., 0., 0., 0., 0., 0., 0., + 10.9, 0., 0., 10.7, 0., 0., 0., 10.6, 0., + 0., 0., 10.5, 0., 0., 10.7, 0., 0., 10.5, + 0., 0., 11.5, 0., 0., 0., 10.7, 0., 0., + 10.7, 0., 0., 10.9, 0., 0., 10.8, 0., 0., + 0., 10.7, 0., 0., 10.6, 0., 0., 0., 10.4, + 0., 0., 10.6, 0., 0., 10.5, 0., 0., 0., + 10.7, 0., 0., 0., 10.4, 0., 0., 0., 10.8, 0.] + with suppress_warnings() as sup: + r = sup.record( + UserWarning, + r""" +The maximal number of iterations maxit \(set to 20 by the program\) +allowed for finding a smoothing spline with fp=s has been reached: s +too small. +There is an approximation returned but the corresponding weighted sum +of squared residuals does not satisfy the condition abs\(fp-s\)/s < tol.""") + UnivariateSpline(x, y, k=1) + assert len(r) == 1 + + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to + # UnivariateSpline + xx = np.arange(100, dtype=float) + yy = xx**3 + x = np.arange(100, dtype=float) + x[1] = x[0] + spl = UnivariateSpline(xx, yy, check_finite=True) + + def worker_fn(_, interp, x): + interp(x) + + _run_concurrent_barrier(10, worker_fn, spl, x) + + +class TestLSQBivariateSpline: + # NOTE: The systems in this test class are rank-deficient + @pytest.mark.thread_unsafe + def test_linear_constant(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [3,3,3,3,3,3,3,3,3] + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with suppress_warnings() as sup: + r = sup.record(UserWarning, "\nThe coefficients of the spline") + lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1) + assert len(r) == 1 + + assert_almost_equal(lut(2, 2), np.asarray(3.)) + + def test_bilinearity(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [0,7,8,3,4,7,1,3,4] + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with suppress_warnings() as sup: + # This seems to fail (ier=1, see ticket 1642). + sup.filter(UserWarning, "\nThe coefficients of the spline") + lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1) + + tx, ty = lut.get_knots() + for xa, xb in zip(tx[:-1], tx[1:]): + for ya, yb in zip(ty[:-1], ty[1:]): + for t in [0.1, 0.5, 0.9]: + for s in [0.3, 0.4, 0.7]: + xp = xa*(1-t) + xb*t + yp = ya*(1-s) + yb*s + zp = (+ lut(xa, ya)*(1-t)*(1-s) + + lut(xb, ya)*t*(1-s) + + lut(xa, yb)*(1-t)*s + + lut(xb, yb)*t*s) + assert_almost_equal(lut(xp,yp), zp) + + @pytest.mark.thread_unsafe + def test_integral(self): + x = [1,1,1,2,2,2,8,8,8] + y = [1,2,3,1,2,3,1,2,3] + z = array([0,7,8,3,4,7,1,3,4]) + + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with suppress_warnings() as sup: + r = sup.record(UserWarning, "\nThe coefficients of the spline") + lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1) + assert len(r) == 1 + tx, ty = lut.get_knots() + tz = lut(tx, ty) + trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:] + * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum() + + assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-1], ty[0], ty[-1])), + np.asarray(trpz)) + + @pytest.mark.thread_unsafe + def test_empty_input(self): + # Test whether empty inputs returns an empty output. Ticket 1014 + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [3,3,3,3,3,3,3,3,3] + s = 0.1 + tx = [1+s,3-s] + ty = [1+s,3-s] + with suppress_warnings() as sup: + r = sup.record(UserWarning, "\nThe coefficients of the spline") + lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1) + assert len(r) == 1 + + xp_assert_equal(lut([], []), np.zeros((0,0))) + xp_assert_equal(lut([], [], grid=False), np.zeros((0,))) + + def test_invalid_input(self): + s = 0.1 + tx = [1 + s, 3 - s] + ty = [1 + s, 3 - s] + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0, num=10) + LSQBivariateSpline(x, y, z, tx, ty) + assert "x, y, and z should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0) + w = np.linspace(1.0, 10.0, num=20) + LSQBivariateSpline(x, y, z, tx, ty, w=w) + assert "x, y, z, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + w = np.linspace(-1.0, 10.0) + LSQBivariateSpline(x, y, z, tx, ty, w=w) + assert "w should be positive" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-100, 100, -100) + LSQBivariateSpline(x, y, z, tx, ty, bbox=bbox) + assert "bbox shape should be (4,)" in str(info.value) + + with assert_raises(ValueError) as info: + LSQBivariateSpline(x, y, z, tx, ty, kx=10, ky=10) + assert "The length of x, y and z should be at least (kx+1) * (ky+1)" in \ + str(info.value) + + with assert_raises(ValueError) as exc_info: + LSQBivariateSpline(x, y, z, tx, ty, eps=0.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + LSQBivariateSpline(x, y, z, tx, ty, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + @pytest.mark.thread_unsafe + def test_array_like_input(self): + s = 0.1 + tx = np.array([1 + s, 3 - s]) + ty = np.array([1 + s, 3 - s]) + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0) + w = np.linspace(1.0, 10.0) + bbox = np.array([1.0, 10.0, 1.0, 10.0]) + + with suppress_warnings() as sup: + r = sup.record(UserWarning, "\nThe coefficients of the spline") + # np.array input + spl1 = LSQBivariateSpline(x, y, z, tx, ty, w=w, bbox=bbox) + # list input + spl2 = LSQBivariateSpline(x.tolist(), y.tolist(), z.tolist(), + tx.tolist(), ty.tolist(), w=w.tolist(), + bbox=bbox) + xp_assert_close(spl1(2.0, 2.0), spl2(2.0, 2.0)) + assert len(r) == 2 + + @pytest.mark.thread_unsafe + def test_unequal_length_of_knots(self): + """Test for the case when the input knot-location arrays in x and y are + of different lengths. + """ + x, y = np.mgrid[0:100, 0:100] + x = x.ravel() + y = y.ravel() + z = 3.0 * np.ones_like(x) + tx = np.linspace(0.1, 98.0, 29) + ty = np.linspace(0.1, 98.0, 33) + with suppress_warnings() as sup: + r = sup.record(UserWarning, "\nThe coefficients of the spline") + lut = LSQBivariateSpline(x,y,z,tx,ty) + assert len(r) == 1 + + assert_almost_equal(lut(x, y, grid=False), z) + + +class TestSmoothBivariateSpline: + def test_linear_constant(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [3,3,3,3,3,3,3,3,3] + lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1) + for t in lut.get_knots(): + assert_array_almost_equal(t, [1, 1, 3, 3]) + + assert_array_almost_equal(lut.get_coeffs(), [3, 3, 3, 3]) + assert abs(lut.get_residual()) < 1e-15 + assert_array_almost_equal(lut([1, 1.5, 2], [1, 1.5]), [[3, 3], [3, 3], [3, 3]]) + + def test_linear_1d(self): + x = [1,1,1,2,2,2,3,3,3] + y = [1,2,3,1,2,3,1,2,3] + z = [0,0,0,2,2,2,4,4,4] + lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1) + for t in lut.get_knots(): + xp_assert_close(t, np.asarray([1.0, 1, 3, 3])) + assert_array_almost_equal(lut.get_coeffs(), [0, 0, 4, 4]) + assert abs(lut.get_residual()) < 1e-15 + assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[0,0],[1,1],[2,2]]) + + @pytest.mark.thread_unsafe + def test_integral(self): + x = [1,1,1,2,2,2,4,4,4] + y = [1,2,3,1,2,3,1,2,3] + z = array([0,7,8,3,4,7,1,3,4]) + + with suppress_warnings() as sup: + # This seems to fail (ier=1, see ticket 1642). + sup.filter(UserWarning, "\nThe required storage space") + lut = SmoothBivariateSpline(x, y, z, kx=1, ky=1, s=0) + + tx = [1,2,4] + ty = [1,2,3] + + tz = lut(tx, ty) + trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:] + * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum() + assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-1], ty[0], ty[-1])), + np.asarray(trpz)) + + lut2 = SmoothBivariateSpline(x, y, z, kx=2, ky=2, s=0) + assert_almost_equal(np.asarray(lut2.integral(tx[0], tx[-1], ty[0], ty[-1])), + np.asarray(trpz), + decimal=0) # the quadratures give 23.75 and 23.85 + + tz = lut(tx[:-1], ty[:-1]) + trpz = .25*(diff(tx[:-1])[:,None]*diff(ty[:-1])[None,:] + * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum() + assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-2], ty[0], ty[-2])), + np.asarray(trpz)) + + def test_rerun_lwrk2_too_small(self): + # in this setting, lwrk2 is too small in the default run. Here we + # check for equality with the bisplrep/bisplev output because there, + # an automatic re-run of the spline representation is done if ier>10. + x = np.linspace(-2, 2, 80) + y = np.linspace(-2, 2, 80) + z = x + y + xi = np.linspace(-1, 1, 100) + yi = np.linspace(-2, 2, 100) + tck = bisplrep(x, y, z) + res1 = bisplev(xi, yi, tck) + interp_ = SmoothBivariateSpline(x, y, z) + res2 = interp_(xi, yi) + assert_almost_equal(res1, res2) + + def test_invalid_input(self): + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0, num=10) + SmoothBivariateSpline(x, y, z) + assert "x, y, and z should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + x = np.linspace(1.0, 10.0) + y = np.linspace(1.0, 10.0) + z = np.linspace(1.0, 10.0) + w = np.linspace(1.0, 10.0, num=20) + SmoothBivariateSpline(x, y, z, w=w) + assert "x, y, z, and w should have a same length" in str(info.value) + + with assert_raises(ValueError) as info: + w = np.linspace(-1.0, 10.0) + SmoothBivariateSpline(x, y, z, w=w) + assert "w should be positive" in str(info.value) + + with assert_raises(ValueError) as info: + bbox = (-100, 100, -100) + SmoothBivariateSpline(x, y, z, bbox=bbox) + assert "bbox shape should be (4,)" in str(info.value) + + with assert_raises(ValueError) as info: + SmoothBivariateSpline(x, y, z, kx=10, ky=10) + assert "The length of x, y and z should be at least (kx+1) * (ky+1)" in\ + str(info.value) + + with assert_raises(ValueError) as info: + SmoothBivariateSpline(x, y, z, s=-1.0) + assert "s should be s >= 0.0" in str(info.value) + + with assert_raises(ValueError) as exc_info: + SmoothBivariateSpline(x, y, z, eps=0.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothBivariateSpline(x, y, z, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + def test_array_like_input(self): + x = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3]) + y = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3]) + z = np.array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + w = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1]) + bbox = np.array([1.0, 3.0, 1.0, 3.0]) + # np.array input + spl1 = SmoothBivariateSpline(x, y, z, w=w, bbox=bbox, kx=1, ky=1) + # list input + spl2 = SmoothBivariateSpline(x.tolist(), y.tolist(), z.tolist(), + bbox=bbox.tolist(), w=w.tolist(), + kx=1, ky=1) + xp_assert_close(spl1(0.1, 0.5), spl2(0.1, 0.5)) + + +class TestLSQSphereBivariateSpline: + def setup_method(self): + # define the input data and coordinates + ntheta, nphi = 70, 90 + theta = linspace(0.5/(ntheta - 1), 1 - 0.5/(ntheta - 1), ntheta) * pi + phi = linspace(0.5/(nphi - 1), 1 - 0.5/(nphi - 1), nphi) * 2. * pi + data = ones((theta.shape[0], phi.shape[0])) + # define knots and extract data values at the knots + knotst = theta[::5] + knotsp = phi[::5] + knotdata = data[::5, ::5] + # calculate spline coefficients + lats, lons = meshgrid(theta, phi) + lut_lsq = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp) + self.lut_lsq = lut_lsq + self.data = knotdata + self.new_lons, self.new_lats = knotsp, knotst + + def test_linear_constant(self): + assert abs(self.lut_lsq.get_residual()) < 1e-15 + assert_array_almost_equal(self.lut_lsq(self.new_lats, self.new_lons), + self.data) + + def test_empty_input(self): + assert_array_almost_equal(self.lut_lsq([], []), np.zeros((0,0))) + assert_array_almost_equal(self.lut_lsq([], [], grid=False), np.zeros((0,))) + + def test_invalid_input(self): + ntheta, nphi = 70, 90 + theta = linspace(0.5 / (ntheta - 1), 1 - 0.5 / (ntheta - 1), + ntheta) * pi + phi = linspace(0.5 / (nphi - 1), 1 - 0.5 / (nphi - 1), nphi) * 2. * pi + data = ones((theta.shape[0], phi.shape[0])) + # define knots and extract data values at the knots + knotst = theta[::5] + knotsp = phi[::5] + + with assert_raises(ValueError) as exc_info: + invalid_theta = linspace(-0.1, 1.0, num=ntheta) * pi + invalid_lats, lons = meshgrid(invalid_theta, phi) + LSQSphereBivariateSpline(invalid_lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_theta = linspace(0.1, 1.1, num=ntheta) * pi + invalid_lats, lons = meshgrid(invalid_theta, phi) + LSQSphereBivariateSpline(invalid_lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = linspace(-0.1, 1.0, num=ntheta) * 2.0 * pi + lats, invalid_lons = meshgrid(theta, invalid_phi) + LSQSphereBivariateSpline(lats.ravel(), invalid_lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = linspace(0.0, 1.1, num=ntheta) * 2.0 * pi + lats, invalid_lons = meshgrid(theta, invalid_phi) + LSQSphereBivariateSpline(lats.ravel(), invalid_lons.ravel(), + data.T.ravel(), knotst, knotsp) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + lats, lons = meshgrid(theta, phi) + + with assert_raises(ValueError) as exc_info: + invalid_knotst = np.copy(knotst) + invalid_knotst[0] = -0.1 + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), invalid_knotst, knotsp) + assert "tt should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_knotst = np.copy(knotst) + invalid_knotst[0] = pi + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), invalid_knotst, knotsp) + assert "tt should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_knotsp = np.copy(knotsp) + invalid_knotsp[0] = -0.1 + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, invalid_knotsp) + assert "tp should be between (0, 2pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_knotsp = np.copy(knotsp) + invalid_knotsp[0] = 2 * pi + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, invalid_knotsp) + assert "tp should be between (0, 2pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_w = array([-1.0, 1.0, 1.5, 0.5, 1.0, 1.5, 0.5, 1.0, 1.0]) + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(), + knotst, knotsp, w=invalid_w) + assert "w should be positive" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(), + knotst, knotsp, eps=0.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(), + knotst, knotsp, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + def test_array_like_input(self): + ntheta, nphi = 70, 90 + theta = linspace(0.5 / (ntheta - 1), 1 - 0.5 / (ntheta - 1), + ntheta) * pi + phi = linspace(0.5 / (nphi - 1), 1 - 0.5 / (nphi - 1), + nphi) * 2. * pi + lats, lons = meshgrid(theta, phi) + data = ones((theta.shape[0], phi.shape[0])) + # define knots and extract data values at the knots + knotst = theta[::5] + knotsp = phi[::5] + w = ones(lats.ravel().shape[0]) + + # np.array input + spl1 = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + data.T.ravel(), knotst, knotsp, w=w) + # list input + spl2 = LSQSphereBivariateSpline(lats.ravel().tolist(), + lons.ravel().tolist(), + data.T.ravel().tolist(), + knotst.tolist(), + knotsp.tolist(), w=w.tolist()) + assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0)) + + +class TestSmoothSphereBivariateSpline: + def setup_method(self): + theta = array([.25*pi, .25*pi, .25*pi, .5*pi, .5*pi, .5*pi, .75*pi, + .75*pi, .75*pi]) + phi = array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, pi, + 1.5 * pi]) + r = array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + self.lut = SmoothSphereBivariateSpline(theta, phi, r, s=1E10) + + def test_linear_constant(self): + assert abs(self.lut.get_residual()) < 1e-15 + assert_array_almost_equal(self.lut([1, 1.5, 2],[1, 1.5]), + [[3, 3], [3, 3], [3, 3]]) + + def test_empty_input(self): + assert_array_almost_equal(self.lut([], []), np.zeros((0,0))) + assert_array_almost_equal(self.lut([], [], grid=False), np.zeros((0,))) + + def test_invalid_input(self): + theta = array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, .5 * pi, .5 * pi, + .75 * pi, .75 * pi, .75 * pi]) + phi = array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, pi, + 1.5 * pi]) + r = array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + + with assert_raises(ValueError) as exc_info: + invalid_theta = array([-0.1 * pi, .25 * pi, .25 * pi, .5 * pi, + .5 * pi, .5 * pi, .75 * pi, .75 * pi, + .75 * pi]) + SmoothSphereBivariateSpline(invalid_theta, phi, r, s=1E10) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_theta = array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, + .5 * pi, .5 * pi, .75 * pi, .75 * pi, + 1.1 * pi]) + SmoothSphereBivariateSpline(invalid_theta, phi, r, s=1E10) + assert "theta should be between [0, pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = array([-.1 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, + .5 * pi, pi, 1.5 * pi]) + SmoothSphereBivariateSpline(theta, invalid_phi, r, s=1E10) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_phi = array([1.0 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, + .5 * pi, pi, 2.1 * pi]) + SmoothSphereBivariateSpline(theta, invalid_phi, r, s=1E10) + assert "phi should be between [0, 2pi]" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + invalid_w = array([-1.0, 1.0, 1.5, 0.5, 1.0, 1.5, 0.5, 1.0, 1.0]) + SmoothSphereBivariateSpline(theta, phi, r, w=invalid_w, s=1E10) + assert "w should be positive" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothSphereBivariateSpline(theta, phi, r, s=-1.0) + assert "s should be positive" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothSphereBivariateSpline(theta, phi, r, eps=-1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + SmoothSphereBivariateSpline(theta, phi, r, eps=1.0) + assert "eps should be between (0, 1)" in str(exc_info.value) + + def test_array_like_input(self): + theta = np.array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, .5 * pi, + .5 * pi, .75 * pi, .75 * pi, .75 * pi]) + phi = np.array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, + pi, 1.5 * pi]) + r = np.array([3, 3, 3, 3, 3, 3, 3, 3, 3]) + w = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # np.array input + spl1 = SmoothSphereBivariateSpline(theta, phi, r, w=w, s=1E10) + + # list input + spl2 = SmoothSphereBivariateSpline(theta.tolist(), phi.tolist(), + r.tolist(), w=w.tolist(), s=1E10) + assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0)) + + +class TestRectBivariateSpline: + def test_defaults(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + lut = RectBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y),z) + + def test_evaluate(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + lut = RectBivariateSpline(x,y,z) + + xi = [1, 2.3, 5.3, 0.5, 3.3, 1.2, 3] + yi = [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3] + zi = lut.ev(xi, yi) + zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)]) + + assert_almost_equal(zi, zi2) + + def test_derivatives_grid(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + dx = array([[0,0,-20,0,0],[0,0,13,0,0],[0,0,4,0,0], + [0,0,-11,0,0],[0,0,4,0,0]])/6. + dy = array([[4,-1,0,1,-4],[4,-1,0,1,-4],[0,1.5,0,-1.5,0], + [2,.25,0,-.25,-2],[4,-1,0,1,-4]]) + dxdy = array([[40,-25,0,25,-40],[-26,16.25,0,-16.25,26], + [-8,5,0,-5,8],[22,-13.75,0,13.75,-22],[-8,5,0,-5,8]])/6. + lut = RectBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y,dx=1),dx) + assert_array_almost_equal(lut(x,y,dy=1),dy) + assert_array_almost_equal(lut(x,y,dx=1,dy=1),dxdy) + + def test_derivatives(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + dx = array([0,0,2./3,0,0]) + dy = array([4,-1,0,-.25,-4]) + dxdy = array([160,65,0,55,32])/24. + lut = RectBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y,dx=1,grid=False),dx) + assert_array_almost_equal(lut(x,y,dy=1,grid=False),dy) + assert_array_almost_equal(lut(x,y,dx=1,dy=1,grid=False),dxdy) + + def test_partial_derivative_method_grid(self): + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], + [1, 2, 1, 2, 1], + [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], + [1, 2, 1, 2, 1]]) + dx = array([[0, 0, -20, 0, 0], + [0, 0, 13, 0, 0], + [0, 0, 4, 0, 0], + [0, 0, -11, 0, 0], + [0, 0, 4, 0, 0]]) / 6. + dy = array([[4, -1, 0, 1, -4], + [4, -1, 0, 1, -4], + [0, 1.5, 0, -1.5, 0], + [2, .25, 0, -.25, -2], + [4, -1, 0, 1, -4]]) + dxdy = array([[40, -25, 0, 25, -40], + [-26, 16.25, 0, -16.25, 26], + [-8, 5, 0, -5, 8], + [22, -13.75, 0, 13.75, -22], + [-8, 5, 0, -5, 8]]) / 6. + lut = RectBivariateSpline(x, y, z) + assert_array_almost_equal(lut.partial_derivative(1, 0)(x, y), dx) + assert_array_almost_equal(lut.partial_derivative(0, 1)(x, y), dy) + assert_array_almost_equal(lut.partial_derivative(1, 1)(x, y), dxdy) + + def test_partial_derivative_method(self): + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], + [1, 2, 1, 2, 1], + [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], + [1, 2, 1, 2, 1]]) + dx = array([0, 0, 2./3, 0, 0]) + dy = array([4, -1, 0, -.25, -4]) + dxdy = array([160, 65, 0, 55, 32]) / 24. + lut = RectBivariateSpline(x, y, z) + assert_array_almost_equal(lut.partial_derivative(1, 0)(x, y, + grid=False), + dx) + assert_array_almost_equal(lut.partial_derivative(0, 1)(x, y, + grid=False), + dy) + assert_array_almost_equal(lut.partial_derivative(1, 1)(x, y, + grid=False), + dxdy) + + def test_partial_derivative_order_too_large(self): + x = array([0, 1, 2, 3, 4], dtype=float) + y = x.copy() + z = ones((x.size, y.size)) + lut = RectBivariateSpline(x, y, z) + with assert_raises(ValueError): + lut.partial_derivative(4, 1) + + def test_broadcast(self): + x = array([1,2,3,4,5]) + y = array([1,2,3,4,5]) + z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) + lut = RectBivariateSpline(x,y,z) + xp_assert_close(lut(x, y), lut(x[:,None], y[None,:], grid=False)) + + def test_invalid_input(self): + + with assert_raises(ValueError) as info: + x = array([6, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + RectBivariateSpline(x, y, z) + assert "x must be strictly increasing" in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([2, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + RectBivariateSpline(x, y, z) + assert "y must be strictly increasing" in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1]]) + RectBivariateSpline(x, y, z) + assert "x dimension of z must have same number of elements as x"\ + in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 3, 2], + [1, 2, 2, 2], [1, 2, 1, 2]]) + RectBivariateSpline(x, y, z) + assert "y dimension of z must have same number of elements as y"\ + in str(info.value) + + with assert_raises(ValueError) as info: + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + bbox = (-100, 100, -100) + RectBivariateSpline(x, y, z, bbox=bbox) + assert "bbox shape should be (4,)" in str(info.value) + + with assert_raises(ValueError) as info: + RectBivariateSpline(x, y, z, s=-1.0) + assert "s should be s >= 0.0" in str(info.value) + + def test_array_like_input(self): + x = array([1, 2, 3, 4, 5]) + y = array([1, 2, 3, 4, 5]) + z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + bbox = array([1, 5, 1, 5]) + + spl1 = RectBivariateSpline(x, y, z, bbox=bbox) + spl2 = RectBivariateSpline(x.tolist(), y.tolist(), z.tolist(), + bbox=bbox.tolist()) + assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0)) + + def test_not_increasing_input(self): + # gh-8565 + NSamp = 20 + Theta = np.random.uniform(0, np.pi, NSamp) + Phi = np.random.uniform(0, 2 * np.pi, NSamp) + Data = np.ones(NSamp) + + Interpolator = SmoothSphereBivariateSpline(Theta, Phi, Data, s=3.5) + + NLon = 6 + NLat = 3 + GridPosLats = np.arange(NLat) / NLat * np.pi + GridPosLons = np.arange(NLon) / NLon * 2 * np.pi + + # No error + Interpolator(GridPosLats, GridPosLons) + + nonGridPosLats = GridPosLats.copy() + nonGridPosLats[2] = 0.001 + with assert_raises(ValueError) as exc_info: + Interpolator(nonGridPosLats, GridPosLons) + assert "x must be strictly increasing" in str(exc_info.value) + + nonGridPosLons = GridPosLons.copy() + nonGridPosLons[2] = 0.001 + with assert_raises(ValueError) as exc_info: + Interpolator(GridPosLats, nonGridPosLons) + assert "y must be strictly increasing" in str(exc_info.value) + + +class TestRectSphereBivariateSpline: + def test_defaults(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + lut = RectSphereBivariateSpline(x,y,z) + assert_array_almost_equal(lut(x,y),z) + + def test_evaluate(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + lut = RectSphereBivariateSpline(x,y,z) + yi = [0.2, 1, 2.3, 2.35, 3.0, 3.99, 5.25] + xi = [1.5, 0.4, 1.1, 0.45, 0.2345, 1., 0.0001] + zi = lut.ev(xi, yi) + zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)]) + assert_almost_equal(zi, zi2) + + def test_invalid_input(self): + data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T, + np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(-1, 170, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 181, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-181, 10, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[0] should be between [-pi, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-10, 360, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[-1] should be v[0] + 2pi or less" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(10, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data, s=-1) + assert "s should be positive" in str(exc_info.value) + + def test_derivatives_grid(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + + lut = RectSphereBivariateSpline(x,y,z) + + y = linspace(0.02, 2*pi-0.02, 7) + x = linspace(0.02, pi-0.02, 7) + + xp_assert_close(lut(x, y, dtheta=1), _numdiff_2d(lut, x, y, dx=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dphi=1), _numdiff_2d(lut, x, y, dy=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dtheta=1, dphi=1), + _numdiff_2d(lut, x, y, dx=1, dy=1, eps=1e-6), + rtol=1e-3, atol=1e-3) + + xp_assert_equal(lut(x, y, dtheta=1), + lut.partial_derivative(1, 0)(x, y)) + xp_assert_equal(lut(x, y, dphi=1), + lut.partial_derivative(0, 1)(x, y)) + xp_assert_equal(lut(x, y, dtheta=1, dphi=1), + lut.partial_derivative(1, 1)(x, y)) + + xp_assert_equal(lut(x, y, dtheta=1, grid=False), + lut.partial_derivative(1, 0)(x, y, grid=False)) + xp_assert_equal(lut(x, y, dphi=1, grid=False), + lut.partial_derivative(0, 1)(x, y, grid=False)) + xp_assert_equal(lut(x, y, dtheta=1, dphi=1, grid=False), + lut.partial_derivative(1, 1)(x, y, grid=False)) + + def test_derivatives(self): + y = linspace(0.01, 2*pi-0.01, 7) + x = linspace(0.01, pi-0.01, 7) + z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1], + [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1], + [1,2,1,2,1,2,1]]) + + lut = RectSphereBivariateSpline(x,y,z) + + y = linspace(0.02, 2*pi-0.02, 7) + x = linspace(0.02, pi-0.02, 7) + + assert lut(x, y, dtheta=1, grid=False).shape == x.shape + xp_assert_close(lut(x, y, dtheta=1, grid=False), + _numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dx=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dphi=1, grid=False), + _numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dy=1), + rtol=1e-4, atol=1e-4) + xp_assert_close(lut(x, y, dtheta=1, dphi=1, grid=False), + _numdiff_2d(lambda x,y: lut(x,y,grid=False), + x, y, dx=1, dy=1, eps=1e-6), + rtol=1e-3, atol=1e-3) + + def test_invalid_input_2(self): + data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T, + np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(0, 170, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 180, 9) * np.pi / 180. + lons = np.linspace(0, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "u should be between (0, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-181, 10, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[0] should be between [-pi, pi)" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(-10, 360, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data) + assert "v[-1] should be v[0] + 2pi or less" in str(exc_info.value) + + with assert_raises(ValueError) as exc_info: + lats = np.linspace(10, 170, 9) * np.pi / 180. + lons = np.linspace(10, 350, 18) * np.pi / 180. + RectSphereBivariateSpline(lats, lons, data, s=-1) + assert "s should be positive" in str(exc_info.value) + + def test_array_like_input(self): + y = linspace(0.01, 2 * pi - 0.01, 7) + x = linspace(0.01, pi - 0.01, 7) + z = array([[1, 2, 1, 2, 1, 2, 1], [1, 2, 1, 2, 1, 2, 1], + [1, 2, 3, 2, 1, 2, 1], + [1, 2, 2, 2, 1, 2, 1], [1, 2, 1, 2, 1, 2, 1], + [1, 2, 2, 2, 1, 2, 1], + [1, 2, 1, 2, 1, 2, 1]]) + # np.array input + spl1 = RectSphereBivariateSpline(x, y, z) + # list input + spl2 = RectSphereBivariateSpline(x.tolist(), y.tolist(), z.tolist()) + assert_array_almost_equal(spl1(x, y), spl2(x, y)) + + def test_negative_evaluation(self): + lats = np.array([25, 30, 35, 40, 45]) + lons = np.array([-90, -85, -80, -75, 70]) + mesh = np.meshgrid(lats, lons) + data = mesh[0] + mesh[1] # lon + lat value + lat_r = np.radians(lats) + lon_r = np.radians(lons) + interpolator = RectSphereBivariateSpline(lat_r, lon_r, data) + query_lat = np.radians(np.array([35, 37.5])) + query_lon = np.radians(np.array([-80, -77.5])) + data_interp = interpolator(query_lat, query_lon) + ans = np.array([[-45.0, -42.480862], + [-49.0625, -46.54315]]) + assert_array_almost_equal(data_interp, ans) + + def test_pole_continuity_gh_14591(self): + # regression test for https://github.com/scipy/scipy/issues/14591 + # with pole_continuty=(True, True), the internal work array size + # was too small, leading to a FITPACK data validation error. + + # The reproducer in gh-14591 was using a NetCDF4 file with + # 361x507 arrays, so here we trivialize array sizes to a minimum + # which still demonstrates the issue. + u = np.arange(1, 10) * np.pi / 10 + v = np.arange(1, 10) * np.pi / 10 + r = np.zeros((9, 9)) + for p in [(True, True), (True, False), (False, False)]: + RectSphereBivariateSpline(u, v, r, s=0, pole_continuity=p) + + +def _numdiff_2d(func, x, y, dx=0, dy=0, eps=1e-8): + if dx == 0 and dy == 0: + return func(x, y) + elif dx == 1 and dy == 0: + return (func(x + eps, y) - func(x - eps, y)) / (2*eps) + elif dx == 0 and dy == 1: + return (func(x, y + eps) - func(x, y - eps)) / (2*eps) + elif dx == 1 and dy == 1: + return (func(x + eps, y + eps) - func(x - eps, y + eps) + - func(x + eps, y - eps) + func(x - eps, y - eps)) / (2*eps)**2 + else: + raise ValueError("invalid derivative order") + + +class Test_DerivedBivariateSpline: + """Test the creation, usage, and attribute access of the (private) + _DerivedBivariateSpline class. + """ + def setup_method(self): + x = np.concatenate(list(zip(range(10), range(10)))) + y = np.concatenate(list(zip(range(10), range(1, 11)))) + z = np.concatenate((np.linspace(3, 1, 10), np.linspace(1, 3, 10))) + with suppress_warnings() as sup: + sup.record(UserWarning, "\nThe coefficients of the spline") + self.lut_lsq = LSQBivariateSpline(x, y, z, + linspace(0.5, 19.5, 4), + linspace(1.5, 20.5, 4), + eps=1e-2) + self.lut_smooth = SmoothBivariateSpline(x, y, z) + xx = linspace(0, 1, 20) + yy = xx + 1.0 + zz = array([np.roll(z, i) for i in range(z.size)]) + self.lut_rect = RectBivariateSpline(xx, yy, zz) + self.orders = list(itertools.product(range(3), range(3))) + + def test_creation_from_LSQ(self): + for nux, nuy in self.orders: + lut_der = self.lut_lsq.partial_derivative(nux, nuy) + a = lut_der(3.5, 3.5, grid=False) + b = self.lut_lsq(3.5, 3.5, dx=nux, dy=nuy, grid=False) + assert a == b + + def test_creation_from_Smooth(self): + for nux, nuy in self.orders: + lut_der = self.lut_smooth.partial_derivative(nux, nuy) + a = lut_der(5.5, 5.5, grid=False) + b = self.lut_smooth(5.5, 5.5, dx=nux, dy=nuy, grid=False) + assert a == b + + def test_creation_from_Rect(self): + for nux, nuy in self.orders: + lut_der = self.lut_rect.partial_derivative(nux, nuy) + a = lut_der(0.5, 1.5, grid=False) + b = self.lut_rect(0.5, 1.5, dx=nux, dy=nuy, grid=False) + assert a == b + + def test_invalid_attribute_fp(self): + der = self.lut_rect.partial_derivative(1, 1) + with assert_raises(AttributeError): + der.fp + + def test_invalid_attribute_get_residual(self): + der = self.lut_smooth.partial_derivative(1, 1) + with assert_raises(AttributeError): + der.get_residual() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py new file mode 100644 index 0000000000000000000000000000000000000000..48197062e0b83a9ef54e45089d9089d49b8ad367 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py @@ -0,0 +1,64 @@ +import itertools +import threading +import time + +import numpy as np +import pytest +import scipy.interpolate + + +class TestGIL: + """Check if the GIL is properly released by scipy.interpolate functions.""" + + def setup_method(self): + self.messages = [] + + def log(self, message): + self.messages.append(message) + + def make_worker_thread(self, target, args): + log = self.log + + class WorkerThread(threading.Thread): + def run(self): + log('interpolation started') + target(*args) + log('interpolation complete') + + return WorkerThread() + + @pytest.mark.xslow + @pytest.mark.xfail(reason='race conditions, may depend on system load') + def test_rectbivariatespline(self): + def generate_params(n_points): + x = y = np.linspace(0, 1000, n_points) + x_grid, y_grid = np.meshgrid(x, y) + z = x_grid * y_grid + return x, y, z + + def calibrate_delay(requested_time): + for n_points in itertools.count(5000, 1000): + args = generate_params(n_points) + time_started = time.time() + interpolate(*args) + if time.time() - time_started > requested_time: + return args + + def interpolate(x, y, z): + scipy.interpolate.RectBivariateSpline(x, y, z) + + args = calibrate_delay(requested_time=3) + worker_thread = self.make_worker_thread(interpolate, args) + worker_thread.start() + for i in range(3): + time.sleep(0.5) + self.log('working') + worker_thread.join() + assert self.messages == [ + 'interpolation started', + 'working', + 'working', + 'working', + 'interpolation complete', + ] + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py new file mode 100644 index 0000000000000000000000000000000000000000..981cd99d9d56e11e8d8ce0635e7b7240c19eef1f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py @@ -0,0 +1,440 @@ +import os +import sys + +import numpy as np +from numpy.testing import suppress_warnings +from pytest import raises as assert_raises +import pytest +from scipy._lib._array_api import xp_assert_close, assert_almost_equal + +from scipy._lib._testutils import check_free_memory +import scipy.interpolate._interpnd as interpnd +import scipy.spatial._qhull as qhull + +import pickle +import threading + +_IS_32BIT = (sys.maxsize < 2**32) + + +def data_file(basename): + return os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', basename) + + +class TestLinearNDInterpolation: + def test_smoketest(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + yi = interpnd.LinearNDInterpolator(x, y)(x) + assert_almost_equal(y, yi) + + def test_smoketest_alternate(self): + # Test at single points, alternate calling convention + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + yi = interpnd.LinearNDInterpolator((x[:,0], x[:,1]), y)(x[:,0], x[:,1]) + assert_almost_equal(y, yi) + + def test_complex_smoketest(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + yi = interpnd.LinearNDInterpolator(x, y)(x) + assert_almost_equal(y, yi) + + def test_tri_input(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + interpolator = interpnd.LinearNDInterpolator(tri, y) + yi = interpolator(x) + assert_almost_equal(y, yi) + assert interpolator.tri is tri + + def test_square(self): + # Test barycentric interpolation on a square against a manual + # implementation + + points = np.array([(0,0), (0,1), (1,1), (1,0)], dtype=np.float64) + values = np.array([1., 2., -3., 5.], dtype=np.float64) + + # NB: assume triangles (0, 1, 3) and (1, 2, 3) + # + # 1----2 + # | \ | + # | \ | + # 0----3 + + def ip(x, y): + t1 = (x + y <= 1) + t2 = ~t1 + + x1 = x[t1] + y1 = y[t1] + + x2 = x[t2] + y2 = y[t2] + + z = 0*x + + z[t1] = (values[0]*(1 - x1 - y1) + + values[1]*y1 + + values[3]*x1) + + z[t2] = (values[2]*(x2 + y2 - 1) + + values[1]*(1 - x2) + + values[3]*(1 - y2)) + return z + + xx, yy = np.broadcast_arrays(np.linspace(0, 1, 14)[:,None], + np.linspace(0, 1, 14)[None,:]) + xx = xx.ravel() + yy = yy.ravel() + + xi = np.array([xx, yy]).T.copy() + zi = interpnd.LinearNDInterpolator(points, values)(xi) + + assert_almost_equal(zi, ip(xx, yy)) + + def test_smoketest_rescale(self): + # Test at single points + x = np.array([(0, 0), (-5, -5), (-5, 5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + yi = interpnd.LinearNDInterpolator(x, y, rescale=True)(x) + assert_almost_equal(y, yi) + + def test_square_rescale(self): + # Test barycentric interpolation on a rectangle with rescaling + # agaings the same implementation without rescaling + + points = np.array([(0,0), (0,100), (10,100), (10,0)], dtype=np.float64) + values = np.array([1., 2., -3., 5.], dtype=np.float64) + + xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None], + np.linspace(0, 100, 14)[None,:]) + xx = xx.ravel() + yy = yy.ravel() + xi = np.array([xx, yy]).T.copy() + zi = interpnd.LinearNDInterpolator(points, values)(xi) + zi_rescaled = interpnd.LinearNDInterpolator(points, values, + rescale=True)(xi) + + assert_almost_equal(zi, zi_rescaled) + + def test_tripoints_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + yi = interpnd.LinearNDInterpolator(tri.points, y)(x) + yi_rescale = interpnd.LinearNDInterpolator(tri.points, y, + rescale=True)(x) + assert_almost_equal(yi, yi_rescale) + + def test_tri_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + match = ("Rescaling is not supported when passing a " + "Delaunay triangulation as ``points``.") + with pytest.raises(ValueError, match=match): + interpnd.LinearNDInterpolator(tri, y, rescale=True)(x) + + def test_pickle(self): + # Test at single points + np.random.seed(1234) + x = np.random.rand(30, 2) + y = np.random.rand(30) + 1j*np.random.rand(30) + + ip = interpnd.LinearNDInterpolator(x, y) + ip2 = pickle.loads(pickle.dumps(ip)) + + assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5)) + + @pytest.mark.slow + @pytest.mark.thread_unsafe + @pytest.mark.skipif(_IS_32BIT, reason='it fails on 32-bit') + def test_threading(self): + # This test was taken from issue 8856 + # https://github.com/scipy/scipy/issues/8856 + check_free_memory(10000) + + r_ticks = np.arange(0, 4200, 10) + phi_ticks = np.arange(0, 4200, 10) + r_grid, phi_grid = np.meshgrid(r_ticks, phi_ticks) + + def do_interp(interpolator, slice_rows, slice_cols): + grid_x, grid_y = np.mgrid[slice_rows, slice_cols] + res = interpolator((grid_x, grid_y)) + return res + + points = np.vstack((r_grid.ravel(), phi_grid.ravel())).T + values = (r_grid * phi_grid).ravel() + interpolator = interpnd.LinearNDInterpolator(points, values) + + worker_thread_1 = threading.Thread( + target=do_interp, + args=(interpolator, slice(0, 2100), slice(0, 2100))) + worker_thread_2 = threading.Thread( + target=do_interp, + args=(interpolator, slice(2100, 4200), slice(0, 2100))) + worker_thread_3 = threading.Thread( + target=do_interp, + args=(interpolator, slice(0, 2100), slice(2100, 4200))) + worker_thread_4 = threading.Thread( + target=do_interp, + args=(interpolator, slice(2100, 4200), slice(2100, 4200))) + + worker_thread_1.start() + worker_thread_2.start() + worker_thread_3.start() + worker_thread_4.start() + + worker_thread_1.join() + worker_thread_2.join() + worker_thread_3.join() + worker_thread_4.join() + + +class TestEstimateGradients2DGlobal: + def test_smoketest(self): + x = np.array([(0, 0), (0, 2), + (1, 0), (1, 2), (0.25, 0.75), (0.6, 0.8)], dtype=float) + tri = qhull.Delaunay(x) + + # Should be exact for linear functions, independent of triangulation + + funcs = [ + (lambda x, y: 0*x + 1, (0, 0)), + (lambda x, y: 0 + x, (1, 0)), + (lambda x, y: -2 + y, (0, 1)), + (lambda x, y: 3 + 3*x + 14.15*y, (3, 14.15)) + ] + + for j, (func, grad) in enumerate(funcs): + z = func(x[:,0], x[:,1]) + dz = interpnd.estimate_gradients_2d_global(tri, z, tol=1e-6) + + assert dz.shape == (6, 2) + xp_assert_close(dz, np.array(grad)[None,:] + 0*dz, + rtol=1e-5, atol=1e-5, err_msg="item %d" % j) + + def test_regression_2359(self): + # Check regression --- for certain point sets, gradient + # estimation could end up in an infinite loop + points = np.load(data_file('estimate_gradients_hang.npy')) + values = np.random.rand(points.shape[0]) + tri = qhull.Delaunay(points) + + # This should not hang + with suppress_warnings() as sup: + sup.filter(interpnd.GradientEstimationWarning, + "Gradient estimation did not converge") + interpnd.estimate_gradients_2d_global(tri, values, maxiter=1) + + +class TestCloughTocher2DInterpolator: + + def _check_accuracy(self, func, x=None, tol=1e-6, alternate=False, + rescale=False, **kw): + rng = np.random.RandomState(1234) + # np.random.seed(1234) + if x is None: + x = np.array([(0, 0), (0, 1), + (1, 0), (1, 1), (0.25, 0.75), (0.6, 0.8), + (0.5, 0.2)], + dtype=float) + + if not alternate: + ip = interpnd.CloughTocher2DInterpolator(x, func(x[:,0], x[:,1]), + tol=1e-6, rescale=rescale) + else: + ip = interpnd.CloughTocher2DInterpolator((x[:,0], x[:,1]), + func(x[:,0], x[:,1]), + tol=1e-6, rescale=rescale) + + p = rng.rand(50, 2) + + if not alternate: + a = ip(p) + else: + a = ip(p[:,0], p[:,1]) + b = func(p[:,0], p[:,1]) + + try: + xp_assert_close(a, b, **kw) + except AssertionError: + print("_check_accuracy: abs(a-b):", abs(a - b)) + print("ip.grad:", ip.grad) + raise + + def test_linear_smoketest(self): + # Should be exact for linear functions, independent of triangulation + funcs = [ + lambda x, y: 0*x + 1, + lambda x, y: 0 + x, + lambda x, y: -2 + y, + lambda x, y: 3 + 3*x + 14.15*y, + ] + + for j, func in enumerate(funcs): + self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7, + err_msg="Function %d" % j) + self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7, + alternate=True, + err_msg="Function (alternate) %d" % j) + # check rescaling + self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7, + err_msg="Function (rescaled) %d" % j, rescale=True) + self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7, + alternate=True, rescale=True, + err_msg="Function (alternate, rescaled) %d" % j) + + def test_quadratic_smoketest(self): + # Should be reasonably accurate for quadratic functions + funcs = [ + lambda x, y: x**2, + lambda x, y: y**2, + lambda x, y: x**2 - y**2, + lambda x, y: x*y, + ] + + for j, func in enumerate(funcs): + self._check_accuracy(func, tol=1e-9, atol=0.22, rtol=0, + err_msg="Function %d" % j) + self._check_accuracy(func, tol=1e-9, atol=0.22, rtol=0, + err_msg="Function %d" % j, rescale=True) + + def test_tri_input(self): + # Test at single points + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + yi = interpnd.CloughTocher2DInterpolator(tri, y)(x) + assert_almost_equal(y, yi) + + def test_tri_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + match = ("Rescaling is not supported when passing a " + "Delaunay triangulation as ``points``.") + with pytest.raises(ValueError, match=match): + interpnd.CloughTocher2DInterpolator(tri, y, rescale=True)(x) + + def test_tripoints_input_rescale(self): + # Test at single points + x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 3j*y + + tri = qhull.Delaunay(x) + yi = interpnd.CloughTocher2DInterpolator(tri.points, y)(x) + yi_rescale = interpnd.CloughTocher2DInterpolator(tri.points, y, rescale=True)(x) + assert_almost_equal(yi, yi_rescale) + + @pytest.mark.fail_slow(5) + def test_dense(self): + # Should be more accurate for dense meshes + funcs = [ + lambda x, y: x**2, + lambda x, y: y**2, + lambda x, y: x**2 - y**2, + lambda x, y: x*y, + lambda x, y: np.cos(2*np.pi*x)*np.sin(2*np.pi*y) + ] + + rng = np.random.RandomState(4321) # use a different seed than the check! + grid = np.r_[np.array([(0,0), (0,1), (1,0), (1,1)], dtype=float), + rng.rand(30*30, 2)] + + for j, func in enumerate(funcs): + self._check_accuracy(func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2, + err_msg="Function %d" % j) + self._check_accuracy(func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2, + err_msg="Function %d" % j, rescale=True) + + def test_wrong_ndim(self): + x = np.random.randn(30, 3) + y = np.random.randn(30) + assert_raises(ValueError, interpnd.CloughTocher2DInterpolator, x, y) + + def test_pickle(self): + # Test at single points + rng = np.random.RandomState(1234) + x = rng.rand(30, 2) + y = rng.rand(30) + 1j*rng.rand(30) + + ip = interpnd.CloughTocher2DInterpolator(x, y) + ip2 = pickle.loads(pickle.dumps(ip)) + + assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5)) + + def test_boundary_tri_symmetry(self): + # Interpolation at neighbourless triangles should retain + # symmetry with mirroring the triangle. + + # Equilateral triangle + points = np.array([(0, 0), (1, 0), (0.5, np.sqrt(3)/2)]) + values = np.array([1, 0, 0]) + + ip = interpnd.CloughTocher2DInterpolator(points, values) + + # Set gradient to zero at vertices + ip.grad[...] = 0 + + # Interpolation should be symmetric vs. bisector + alpha = 0.3 + p1 = np.array([0.5 * np.cos(alpha), 0.5 * np.sin(alpha)]) + p2 = np.array([0.5 * np.cos(np.pi/3 - alpha), 0.5 * np.sin(np.pi/3 - alpha)]) + + v1 = ip(p1) + v2 = ip(p2) + xp_assert_close(v1, v2) + + # ... and affine invariant + rng = np.random.RandomState(1) + A = rng.randn(2, 2) + b = rng.randn(2) + + points = A.dot(points.T).T + b[None,:] + p1 = A.dot(p1) + b + p2 = A.dot(p2) + b + + ip = interpnd.CloughTocher2DInterpolator(points, values) + ip.grad[...] = 0 + + w1 = ip(p1) + w2 = ip(p2) + xp_assert_close(w1, v1) + xp_assert_close(w2, v2) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..24a6907b7b050ddb0686cf8b1761bfd50eaf692a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py @@ -0,0 +1,2586 @@ +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal +) +from pytest import raises as assert_raises +import pytest + +from numpy import mgrid, pi, sin, poly1d +import numpy as np + +from scipy.interpolate import (interp1d, interp2d, lagrange, PPoly, BPoly, + splrep, splev, splantider, splint, sproot, Akima1DInterpolator, + NdPPoly, BSpline, PchipInterpolator) + +from scipy.special import poch, gamma + +from scipy.interpolate import _ppoly + +from scipy._lib._gcutils import assert_deallocated, IS_PYPY +from scipy._lib._testutils import _run_concurrent_barrier + +from scipy.integrate import nquad + +from scipy.special import binom + + +class TestInterp2D: + def test_interp2d(self): + y, x = mgrid[0:2:20j, 0:pi:21j] + z = sin(x+0.5*y) + with assert_raises(NotImplementedError): + interp2d(x, y, z) + + +class TestInterp1D: + + def setup_method(self): + self.x5 = np.arange(5.) + self.x10 = np.arange(10.) + self.y10 = np.arange(10.) + self.x25 = self.x10.reshape((2,5)) + self.x2 = np.arange(2.) + self.y2 = np.arange(2.) + self.x1 = np.array([0.]) + self.y1 = np.array([0.]) + + self.y210 = np.arange(20.).reshape((2, 10)) + self.y102 = np.arange(20.).reshape((10, 2)) + self.y225 = np.arange(20.).reshape((2, 2, 5)) + self.y25 = np.arange(10.).reshape((2, 5)) + self.y235 = np.arange(30.).reshape((2, 3, 5)) + self.y325 = np.arange(30.).reshape((3, 2, 5)) + + # Edge updated test matrix 1 + # array([[ 30, 1, 2, 3, 4, 5, 6, 7, 8, -30], + # [ 30, 11, 12, 13, 14, 15, 16, 17, 18, -30]]) + self.y210_edge_updated = np.arange(20.).reshape((2, 10)) + self.y210_edge_updated[:, 0] = 30 + self.y210_edge_updated[:, -1] = -30 + + # Edge updated test matrix 2 + # array([[ 30, 30], + # [ 2, 3], + # [ 4, 5], + # [ 6, 7], + # [ 8, 9], + # [ 10, 11], + # [ 12, 13], + # [ 14, 15], + # [ 16, 17], + # [-30, -30]]) + self.y102_edge_updated = np.arange(20.).reshape((10, 2)) + self.y102_edge_updated[0, :] = 30 + self.y102_edge_updated[-1, :] = -30 + + self.fill_value = -100.0 + + def test_validation(self): + # Make sure that appropriate exceptions are raised when invalid values + # are given to the constructor. + + # These should all work. + for kind in ('nearest', 'nearest-up', 'zero', 'linear', 'slinear', + 'quadratic', 'cubic', 'previous', 'next'): + interp1d(self.x10, self.y10, kind=kind) + interp1d(self.x10, self.y10, kind=kind, fill_value="extrapolate") + interp1d(self.x10, self.y10, kind='linear', fill_value=(-1, 1)) + interp1d(self.x10, self.y10, kind='linear', + fill_value=np.array([-1])) + interp1d(self.x10, self.y10, kind='linear', + fill_value=(-1,)) + interp1d(self.x10, self.y10, kind='linear', + fill_value=-1) + interp1d(self.x10, self.y10, kind='linear', + fill_value=(-1, -1)) + interp1d(self.x10, self.y10, kind=0) + interp1d(self.x10, self.y10, kind=1) + interp1d(self.x10, self.y10, kind=2) + interp1d(self.x10, self.y10, kind=3) + interp1d(self.x10, self.y210, kind='linear', axis=-1, + fill_value=(-1, -1)) + interp1d(self.x2, self.y210, kind='linear', axis=0, + fill_value=np.ones(10)) + interp1d(self.x2, self.y210, kind='linear', axis=0, + fill_value=(np.ones(10), np.ones(10))) + interp1d(self.x2, self.y210, kind='linear', axis=0, + fill_value=(np.ones(10), -1)) + + # x array must be 1D. + assert_raises(ValueError, interp1d, self.x25, self.y10) + + # y array cannot be a scalar. + assert_raises(ValueError, interp1d, self.x10, np.array(0)) + + # Check for x and y arrays having the same length. + assert_raises(ValueError, interp1d, self.x10, self.y2) + assert_raises(ValueError, interp1d, self.x2, self.y10) + assert_raises(ValueError, interp1d, self.x10, self.y102) + interp1d(self.x10, self.y210) + interp1d(self.x10, self.y102, axis=0) + + # Check for x and y having at least 1 element. + assert_raises(ValueError, interp1d, self.x1, self.y10) + assert_raises(ValueError, interp1d, self.x10, self.y1) + + # Bad fill values + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=(-1, -1, -1)) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=[-1, -1, -1]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=np.array((-1, -1, -1))) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=[[-1]]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=[-1, -1]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=np.array([])) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear', + fill_value=()) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear', + axis=0, fill_value=[-1, -1]) # doesn't broadcast + assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear', + axis=0, fill_value=(0., [-1, -1])) # above doesn't bc + + def test_init(self): + # Check that the attributes are initialized appropriately by the + # constructor. + assert interp1d(self.x10, self.y10).copy + assert not interp1d(self.x10, self.y10, copy=False).copy + assert interp1d(self.x10, self.y10).bounds_error + assert not interp1d(self.x10, self.y10, bounds_error=False).bounds_error + assert np.isnan(interp1d(self.x10, self.y10).fill_value) + assert interp1d(self.x10, self.y10, fill_value=3.0).fill_value == 3.0 + assert (interp1d(self.x10, self.y10, fill_value=(1.0, 2.0)).fill_value == + (1.0, 2.0) + ) + assert interp1d(self.x10, self.y10).axis == 0 + assert interp1d(self.x10, self.y210).axis == 1 + assert interp1d(self.x10, self.y102, axis=0).axis == 0 + xp_assert_equal(interp1d(self.x10, self.y10).x, self.x10) + xp_assert_equal(interp1d(self.x10, self.y10).y, self.y10) + xp_assert_equal(interp1d(self.x10, self.y210).y, self.y210) + + def test_assume_sorted(self): + # Check for unsorted arrays + interp10 = interp1d(self.x10, self.y10) + interp10_unsorted = interp1d(self.x10[::-1], self.y10[::-1]) + + assert_array_almost_equal(interp10_unsorted(self.x10), self.y10) + assert_array_almost_equal(interp10_unsorted(1.2), np.array(1.2)) + assert_array_almost_equal(interp10_unsorted([2.4, 5.6, 6.0]), + interp10([2.4, 5.6, 6.0])) + + # Check assume_sorted keyword (defaults to False) + interp10_assume_kw = interp1d(self.x10[::-1], self.y10[::-1], + assume_sorted=False) + assert_array_almost_equal(interp10_assume_kw(self.x10), self.y10) + + interp10_assume_kw2 = interp1d(self.x10[::-1], self.y10[::-1], + assume_sorted=True) + # Should raise an error for unsorted input if assume_sorted=True + assert_raises(ValueError, interp10_assume_kw2, self.x10) + + # Check that if y is a 2-D array, things are still consistent + interp10_y_2d = interp1d(self.x10, self.y210) + interp10_y_2d_unsorted = interp1d(self.x10[::-1], self.y210[:, ::-1]) + assert_array_almost_equal(interp10_y_2d(self.x10), + interp10_y_2d_unsorted(self.x10)) + + def test_linear(self): + for kind in ['linear', 'slinear']: + self._check_linear(kind) + + def _check_linear(self, kind): + # Check the actual implementation of linear interpolation. + interp10 = interp1d(self.x10, self.y10, kind=kind) + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.2)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2.4, 5.6, 6.0])) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind=kind, + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + np.asarray([-1.0, 0, 9, 11]), rtol=1e-14) + + opts = dict(kind=kind, + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + def test_linear_dtypes(self): + # regression test for gh-5898, where 1D linear interpolation has been + # delegated to numpy.interp for all float dtypes, and the latter was + # not handling e.g. np.float128. + for dtyp in [np.float16, + np.float32, + np.float64, + np.longdouble]: + x = np.arange(8, dtype=dtyp) + y = x + yp = interp1d(x, y, kind='linear')(x) + assert yp.dtype == dtyp + xp_assert_close(yp, y, atol=1e-15) + + # regression test for gh-14531, where 1D linear interpolation has been + # has been extended to delegate to numpy.interp for integer dtypes + x = [0, 1, 2] + y = [np.nan, 0, 1] + yp = interp1d(x, y)(x) + xp_assert_close(yp, y, atol=1e-15) + + def test_slinear_dtypes(self): + # regression test for gh-7273: 1D slinear interpolation fails with + # float32 inputs + dt_r = [np.float16, np.float32, np.float64] + dt_rc = dt_r + [np.complex64, np.complex128] + spline_kinds = ['slinear', 'zero', 'quadratic', 'cubic'] + for dtx in dt_r: + x = np.arange(0, 10, dtype=dtx) + for dty in dt_rc: + y = np.exp(-x/3.0).astype(dty) + for dtn in dt_r: + xnew = x.astype(dtn) + for kind in spline_kinds: + f = interp1d(x, y, kind=kind, bounds_error=False) + xp_assert_close(f(xnew), y, atol=1e-7, + check_dtype=False, + err_msg=f"{dtx}, {dty} {dtn}") + + def test_cubic(self): + # Check the actual implementation of spline interpolation. + interp10 = interp1d(self.x10, self.y10, kind='cubic') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.2)) + assert_array_almost_equal(interp10(1.5), np.array(1.5)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2.4, 5.6, 6.0]),) + + def test_nearest(self): + # Check the actual implementation of nearest-neighbour interpolation. + # Nearest asserts that half-integer case (1.5) rounds down to 1 + interp10 = interp1d(self.x10, self.y10, kind='nearest') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(1.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 6., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='nearest', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [0.0, 0, 9, 9], rtol=1e-14) + + opts = dict(kind='nearest', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + def test_nearest_up(self): + # Check the actual implementation of nearest-neighbour interpolation. + # Nearest-up asserts that half-integer case (1.5) rounds up to 2 + interp10 = interp1d(self.x10, self.y10, kind='nearest-up') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(2.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 6., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='nearest-up', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [0.0, 0, 9, 9], rtol=1e-14) + + opts = dict(kind='nearest-up', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + def test_previous(self): + # Check the actual implementation of previous interpolation. + interp10 = interp1d(self.x10, self.y10, kind='previous') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(1.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 5., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='previous', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [np.nan, 0, 9, 9], rtol=1e-14) + + # Tests for gh-9591 + interpolator1D = interp1d(self.x10, self.y10, kind="previous", + fill_value='extrapolate') + xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]), + [np.nan, np.nan, 5, 8, 9, 9]) + + interpolator2D = interp1d(self.x10, self.y210, kind="previous", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[np.nan, np.nan, 5, 8, 9, 9], + [np.nan, np.nan, 15, 18, 19, 19]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="previous", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[np.nan, np.nan], + [10, 11], + [18, 19]]) + + opts = dict(kind='previous', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + # Tests for gh-16813 + interpolator1D = interp1d([0, 1, 2], + [0, 1, -1], kind="previous", + fill_value='extrapolate', + assume_sorted=True) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [np.nan, np.nan, 0, 1, -1, -1, -1]) + + interpolator1D = interp1d([2, 0, 1], # x is not ascending + [-1, 0, 1], kind="previous", + fill_value='extrapolate', + assume_sorted=False) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [np.nan, np.nan, 0, 1, -1, -1, -1]) + + interpolator2D = interp1d(self.x10, self.y210_edge_updated, + kind="previous", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[np.nan, np.nan, 5, 8, -30, -30], + [np.nan, np.nan, 15, 18, -30, -30]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated, + kind="previous", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[np.nan, np.nan], + [10, 11], + [-30, -30]]) + + def test_next(self): + # Check the actual implementation of next interpolation. + interp10 = interp1d(self.x10, self.y10, kind='next') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(2.)) + assert_array_almost_equal(interp10(1.5), np.array(2.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([3., 6., 6.]),) + + # test fill_value="extrapolate" + extrapolator = interp1d(self.x10, self.y10, kind='next', + fill_value='extrapolate') + xp_assert_close(extrapolator([-1., 0, 9, 11]), + [0, 0, 9, np.nan], rtol=1e-14) + + # Tests for gh-9591 + interpolator1D = interp1d(self.x10, self.y10, kind="next", + fill_value='extrapolate') + xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]), + [0, 0, 5, 8, np.nan, np.nan]) + + interpolator2D = interp1d(self.x10, self.y210, kind="next", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[0, 0, 5, 8, np.nan, np.nan], + [10, 10, 15, 18, np.nan, np.nan]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="next", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[0, 1], + [10, 11], + [np.nan, np.nan]]) + + opts = dict(kind='next', + fill_value='extrapolate', + bounds_error=True) + assert_raises(ValueError, interp1d, self.x10, self.y10, **opts) + + # Tests for gh-16813 + interpolator1D = interp1d([0, 1, 2], + [0, 1, -1], kind="next", + fill_value='extrapolate', + assume_sorted=True) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [0, 0, 0, 1, -1, np.nan, np.nan]) + + interpolator1D = interp1d([2, 0, 1], # x is not ascending + [-1, 0, 1], kind="next", + fill_value='extrapolate', + assume_sorted=False) + xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]), + [0, 0, 0, 1, -1, np.nan, np.nan]) + + interpolator2D = interp1d(self.x10, self.y210_edge_updated, + kind="next", + fill_value='extrapolate') + xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]), + [[30, 30, 5, 8, np.nan, np.nan], + [30, 30, 15, 18, np.nan, np.nan]]) + + interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated, + kind="next", + axis=0, fill_value='extrapolate') + xp_assert_close(interpolator2DAxis0([-2, 5, 12]), + [[30, 30], + [10, 11], + [np.nan, np.nan]]) + + def test_zero(self): + # Check the actual implementation of zero-order spline interpolation. + interp10 = interp1d(self.x10, self.y10, kind='zero') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10(1.5), np.array(1.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 5., 6.])) + + def bounds_check_helper(self, interpolant, test_array, fail_value): + # Asserts that a ValueError is raised and that the error message + # contains the value causing this exception. + assert_raises(ValueError, interpolant, test_array) + try: + interpolant(test_array) + except ValueError as err: + assert (f"{fail_value}" in str(err)) + + def _bounds_check(self, kind='linear'): + # Test that our handling of out-of-bounds input is correct. + extrap10 = interp1d(self.x10, self.y10, fill_value=self.fill_value, + bounds_error=False, kind=kind) + + xp_assert_equal(extrap10(11.2), np.array(self.fill_value)) + xp_assert_equal(extrap10(-3.4), np.array(self.fill_value)) + xp_assert_equal(extrap10([[[11.2], [-3.4], [12.6], [19.3]]]), + np.array(self.fill_value), check_shape=False) + xp_assert_equal(extrap10._check_bounds( + np.array([-1.0, 0.0, 5.0, 9.0, 11.0])), + np.array([[True, False, False, False, False], + [False, False, False, False, True]])) + + raises_bounds_error = interp1d(self.x10, self.y10, bounds_error=True, + kind=kind) + + self.bounds_check_helper(raises_bounds_error, -1.0, -1.0) + self.bounds_check_helper(raises_bounds_error, 11.0, 11.0) + self.bounds_check_helper(raises_bounds_error, [0.0, -1.0, 0.0], -1.0) + self.bounds_check_helper(raises_bounds_error, [0.0, 1.0, 21.0], 21.0) + + raises_bounds_error([0.0, 5.0, 9.0]) + + def _bounds_check_int_nan_fill(self, kind='linear'): + x = np.arange(10).astype(int) + y = np.arange(10).astype(int) + c = interp1d(x, y, kind=kind, fill_value=np.nan, bounds_error=False) + yi = c(x - 1) + assert np.isnan(yi[0]) + assert_array_almost_equal(yi, np.r_[np.nan, y[:-1]]) + + def test_bounds(self): + for kind in ('linear', 'cubic', 'nearest', 'previous', 'next', + 'slinear', 'zero', 'quadratic'): + self._bounds_check(kind) + self._bounds_check_int_nan_fill(kind) + + def _check_fill_value(self, kind): + interp = interp1d(self.x10, self.y10, kind=kind, + fill_value=(-100, 100), bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), np.asarray(-100.)) + assert_array_almost_equal(interp([-10, 10]), [-100, 100]) + + # Proper broadcasting: + # interp along axis of length 5 + # other dim=(2, 3), (3, 2), (2, 2), or (2,) + + # one singleton fill_value (works for all) + for y in (self.y235, self.y325, self.y225, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=100, bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), np.asarray(100.)) + assert_array_almost_equal(interp([-10, 10]), np.asarray(100.)) + + # singleton lower, singleton upper + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=(-100, 100), bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), np.asarray(-100.)) + if y.ndim == 3: + result = [[[-100, 100]] * y.shape[1]] * y.shape[0] + else: + result = [[-100, 100]] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # one broadcastable (3,) fill_value + fill_value = [100, 200, 300] + for y in (self.y325, self.y225): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + interp = interp1d(self.x5, self.y235, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2) + assert_array_almost_equal(interp(-10), [[100, 200, 300]] * 2) + assert_array_almost_equal(interp([-10, 10]), [[[100, 100], + [200, 200], + [300, 300]]] * 2) + + # one broadcastable (2,) fill_value + fill_value = [100, 200] + assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for y in (self.y225, self.y325, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + result = [100, 200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(10), result) + assert_array_almost_equal(interp(-10), result) + result = [[100, 100], [200, 200]] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # broadcastable (3,) lower, singleton upper + fill_value = (np.array([-100, -200, -300]), 100) + for y in (self.y325, self.y225): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + interp = interp1d(self.x5, self.y235, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100.)) + assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2) + assert_array_almost_equal(interp([-10, 10]), [[[-100, 100], + [-200, 100], + [-300, 100]]] * 2) + + # broadcastable (2,) lower, singleton upper + fill_value = (np.array([-100, -200]), 100) + assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for y in (self.y225, self.y325, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), np.asarray(100)) + result = [-100, -200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(-10), result) + result = [[-100, 100], [-200, 100]] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # broadcastable (3,) lower, broadcastable (3,) upper + fill_value = ([-100, -200, -300], [100, 200, 300]) + for y in (self.y325, self.y225): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for ii in range(2): # check ndarray as well as list here + if ii == 1: + fill_value = tuple(np.array(f) for f in fill_value) + interp = interp1d(self.x5, self.y235, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2) + assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2) + assert_array_almost_equal(interp([-10, 10]), [[[-100, 100], + [-200, 200], + [-300, 300]]] * 2) + # broadcastable (2,) lower, broadcastable (2,) upper + fill_value = ([-100, -200], [100, 200]) + assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for y in (self.y325, self.y225, self.y25): + interp = interp1d(self.x5, y, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + result = [100, 200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(10), result) + result = [-100, -200] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp(-10), result) + result = [[-100, 100], [-200, 200]] + if y.ndim == 3: + result = [result] * y.shape[0] + assert_array_almost_equal(interp([-10, 10]), result) + + # one broadcastable (2, 2) array-like + fill_value = [[100, 200], [1000, 2000]] + for y in (self.y235, self.y325, self.y25): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for ii in range(2): + if ii == 1: + fill_value = np.array(fill_value) + interp = interp1d(self.x5, self.y225, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]]) + assert_array_almost_equal(interp(-10), [[100, 200], [1000, 2000]]) + assert_array_almost_equal(interp([-10, 10]), [[[100, 100], + [200, 200]], + [[1000, 1000], + [2000, 2000]]]) + + # broadcastable (2, 2) lower, broadcastable (2, 2) upper + fill_value = ([[-100, -200], [-1000, -2000]], + [[100, 200], [1000, 2000]]) + for y in (self.y235, self.y325, self.y25): + assert_raises(ValueError, interp1d, self.x5, y, kind=kind, + axis=-1, fill_value=fill_value, bounds_error=False) + for ii in range(2): + if ii == 1: + fill_value = (np.array(fill_value[0]), np.array(fill_value[1])) + interp = interp1d(self.x5, self.y225, kind=kind, axis=-1, + fill_value=fill_value, bounds_error=False) + assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]]) + assert_array_almost_equal(interp(-10), [[-100, -200], + [-1000, -2000]]) + assert_array_almost_equal(interp([-10, 10]), [[[-100, 100], + [-200, 200]], + [[-1000, 1000], + [-2000, 2000]]]) + + def test_fill_value(self): + # test that two-element fill value works + for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic', + 'zero', 'previous', 'next'): + self._check_fill_value(kind) + + def test_fill_value_writeable(self): + # backwards compat: fill_value is a public writeable attribute + interp = interp1d(self.x10, self.y10, fill_value=123.0) + assert interp.fill_value == 123.0 + interp.fill_value = 321.0 + assert interp.fill_value == 321.0 + + def _nd_check_interp(self, kind='linear'): + # Check the behavior when the inputs and outputs are multidimensional. + + # Multidimensional input. + interp10 = interp1d(self.x10, self.y10, kind=kind) + assert_array_almost_equal(interp10(np.array([[3., 5.], [2., 7.]])), + np.array([[3., 5.], [2., 7.]])) + + # Scalar input -> 0-dim scalar array output + assert isinstance(interp10(1.2), np.ndarray) + assert interp10(1.2).shape == () + + # Multidimensional outputs. + interp210 = interp1d(self.x10, self.y210, kind=kind) + assert_array_almost_equal(interp210(1.), np.array([1., 11.])) + assert_array_almost_equal(interp210(np.array([1., 2.])), + np.array([[1., 2.], [11., 12.]])) + + interp102 = interp1d(self.x10, self.y102, axis=0, kind=kind) + assert_array_almost_equal(interp102(1.), np.array([2.0, 3.0])) + assert_array_almost_equal(interp102(np.array([1., 3.])), + np.array([[2., 3.], [6., 7.]])) + + # Both at the same time! + x_new = np.array([[3., 5.], [2., 7.]]) + assert_array_almost_equal(interp210(x_new), + np.array([[[3., 5.], [2., 7.]], + [[13., 15.], [12., 17.]]])) + assert_array_almost_equal(interp102(x_new), + np.array([[[6., 7.], [10., 11.]], + [[4., 5.], [14., 15.]]])) + + def _nd_check_shape(self, kind='linear'): + # Check large N-D output shape + a = [4, 5, 6, 7] + y = np.arange(np.prod(a)).reshape(*a) + for n, s in enumerate(a): + x = np.arange(s) + z = interp1d(x, y, axis=n, kind=kind) + assert_array_almost_equal(z(x), y, err_msg=kind) + + x2 = np.arange(2*3*1).reshape((2,3,1)) / 12. + b = list(a) + b[n:n+1] = [2, 3, 1] + assert z(x2).shape == tuple(b), kind + + def test_nd(self): + for kind in ('linear', 'cubic', 'slinear', 'quadratic', 'nearest', + 'zero', 'previous', 'next'): + self._nd_check_interp(kind) + self._nd_check_shape(kind) + + def _check_complex(self, dtype=np.complex128, kind='linear'): + x = np.array([1, 2.5, 3, 3.1, 4, 6.4, 7.9, 8.0, 9.5, 10]) + y = x * x ** (1 + 2j) + y = y.astype(dtype) + + # simple test + c = interp1d(x, y, kind=kind) + assert_array_almost_equal(y[:-1], c(x)[:-1]) + + # check against interpolating real+imag separately + xi = np.linspace(1, 10, 31) + cr = interp1d(x, y.real, kind=kind) + ci = interp1d(x, y.imag, kind=kind) + assert_array_almost_equal(c(xi).real, cr(xi)) + assert_array_almost_equal(c(xi).imag, ci(xi)) + + def test_complex(self): + for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic', + 'zero', 'previous', 'next'): + self._check_complex(np.complex64, kind) + self._check_complex(np.complex128, kind) + + @pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy") + def test_circular_refs(self): + # Test interp1d can be automatically garbage collected + x = np.linspace(0, 1) + y = np.linspace(0, 1) + # Confirm interp can be released from memory after use + with assert_deallocated(interp1d, x, y) as interp: + interp([0.1, 0.2]) + del interp + + def test_overflow_nearest(self): + # Test that the x range doesn't overflow when given integers as input + for kind in ('nearest', 'previous', 'next'): + x = np.array([0, 50, 127], dtype=np.int8) + ii = interp1d(x, x, kind=kind) + assert_array_almost_equal(ii(x), x) + + def test_local_nans(self): + # check that for local interpolation kinds (slinear, zero) a single nan + # only affects its local neighborhood + x = np.arange(10).astype(float) + y = x.copy() + y[6] = np.nan + for kind in ('zero', 'slinear'): + ir = interp1d(x, y, kind=kind) + vals = ir([4.9, 7.0]) + assert np.isfinite(vals).all() + + def test_spline_nans(self): + # Backwards compat: a single nan makes the whole spline interpolation + # return nans in an array of the correct shape. And it doesn't raise, + # just quiet nans because of backcompat. + x = np.arange(8).astype(float) + y = x.copy() + yn = y.copy() + yn[3] = np.nan + + for kind in ['quadratic', 'cubic']: + ir = interp1d(x, y, kind=kind) + irn = interp1d(x, yn, kind=kind) + for xnew in (6, [1, 6], [[1, 6], [3, 5]]): + xnew = np.asarray(xnew) + out, outn = ir(x), irn(x) + assert np.isnan(outn).all() + assert out.shape == outn.shape + + def test_all_nans(self): + # regression test for gh-11637: interp1d core dumps with all-nan `x` + x = np.ones(10) * np.nan + y = np.arange(10) + with assert_raises(ValueError): + interp1d(x, y, kind='cubic') + + def test_read_only(self): + x = np.arange(0, 10) + y = np.exp(-x / 3.0) + xnew = np.arange(0, 9, 0.1) + # Check both read-only and not read-only: + for xnew_writeable in (True, False): + xnew.flags.writeable = xnew_writeable + x.flags.writeable = False + for kind in ('linear', 'nearest', 'zero', 'slinear', 'quadratic', + 'cubic'): + f = interp1d(x, y, kind=kind) + vals = f(xnew) + assert np.isfinite(vals).all() + + @pytest.mark.parametrize( + "kind", ("linear", "nearest", "nearest-up", "previous", "next") + ) + def test_single_value(self, kind): + # https://github.com/scipy/scipy/issues/4043 + f = interp1d([1.5], [6], kind=kind, bounds_error=False, + fill_value=(2, 10)) + xp_assert_equal(f([1, 1.5, 2]), np.asarray([2.0, 6, 10])) + # check still error if bounds_error=True + f = interp1d([1.5], [6], kind=kind, bounds_error=True) + with assert_raises(ValueError, match="x_new is above"): + f(2.0) + + +class TestLagrange: + + def test_lagrange(self): + p = poly1d([5,2,1,4,3]) + xs = np.arange(len(p.coeffs)) + ys = p(xs) + pl = lagrange(xs,ys) + assert_array_almost_equal(p.coeffs,pl.coeffs) + + +class TestAkima1DInterpolator: + def test_eval(self): + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + ak = Akima1DInterpolator(x, y) + xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.]) + yi = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375, + 4.1363636363636366866103344, 5.9803623910336236590978842, + 5.5067291516462386624652936, 5.2031367459745245795943447, + 4.1796554159017080820603951, 3.4110386597938129327189927, + 3.]) + xp_assert_close(ak(xi), yi) + + def test_eval_mod(self): + # Reference values generated with the following MATLAB code: + # format longG + # x = 0:10; y = [0. 2. 1. 3. 2. 6. 5.5 5.5 2.7 5.1 3.]; + # xi = [0. 0.5 1. 1.5 2.5 3.5 4.5 5.1 6.5 7.2 8.6 9.9 10.]; + # makima(x, y, xi) + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + ak = Akima1DInterpolator(x, y, method="makima") + xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.]) + yi = np.array([ + 0.0, 1.34471153846154, 2.0, 1.44375, 1.94375, 2.51939102564103, + 4.10366931918656, 5.98501550899192, 5.51756330960439, 5.1757231914014, + 4.12326636931311, 3.32931513157895, 3.0]) + xp_assert_close(ak(xi), yi) + + def test_eval_2d(self): + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + y = np.column_stack((y, 2. * y)) + ak = Akima1DInterpolator(x, y) + xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.]) + yi = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375, + 4.1363636363636366866103344, + 5.9803623910336236590978842, + 5.5067291516462386624652936, + 5.2031367459745245795943447, + 4.1796554159017080820603951, + 3.4110386597938129327189927, 3.]) + yi = np.column_stack((yi, 2. * yi)) + xp_assert_close(ak(xi), yi) + + def test_eval_3d(self): + x = np.arange(0., 11.) + y_ = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + y = np.empty((11, 2, 2)) + y[:, 0, 0] = y_ + y[:, 1, 0] = 2. * y_ + y[:, 0, 1] = 3. * y_ + y[:, 1, 1] = 4. * y_ + ak = Akima1DInterpolator(x, y) + xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2, + 8.6, 9.9, 10.]) + yi = np.empty((13, 2, 2)) + yi_ = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375, + 4.1363636363636366866103344, + 5.9803623910336236590978842, + 5.5067291516462386624652936, + 5.2031367459745245795943447, + 4.1796554159017080820603951, + 3.4110386597938129327189927, 3.]) + yi[:, 0, 0] = yi_ + yi[:, 1, 0] = 2. * yi_ + yi[:, 0, 1] = 3. * yi_ + yi[:, 1, 1] = 4. * yi_ + xp_assert_close(ak(xi), yi) + + def test_degenerate_case_multidimensional(self): + # This test is for issue #5683. + x = np.array([0, 1, 2]) + y = np.vstack((x, x**2)).T + ak = Akima1DInterpolator(x, y) + x_eval = np.array([0.5, 1.5]) + y_eval = ak(x_eval) + xp_assert_close(y_eval, np.vstack((x_eval, x_eval**2)).T) + + def test_extend(self): + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + ak = Akima1DInterpolator(x, y) + match = "Extending a 1-D Akima interpolator is not yet implemented" + with pytest.raises(NotImplementedError, match=match): + ak.extend(None, None) + + def test_mod_invalid_method(self): + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + match = "`method`=invalid is unsupported." + with pytest.raises(NotImplementedError, match=match): + Akima1DInterpolator(x, y, method="invalid") # type: ignore + + def test_extrapolate_attr(self): + # + x = np.linspace(-5, 5, 11) + y = x**2 + x_ext = np.linspace(-10, 10, 17) + y_ext = x_ext**2 + # Testing all extrapolate cases. + ak_true = Akima1DInterpolator(x, y, extrapolate=True) + ak_false = Akima1DInterpolator(x, y, extrapolate=False) + ak_none = Akima1DInterpolator(x, y, extrapolate=None) + # None should default to False; extrapolated points are NaN. + xp_assert_close(ak_false(x_ext), ak_none(x_ext), atol=1e-15) + xp_assert_equal(ak_false(x_ext)[0:4], np.full(4, np.nan)) + xp_assert_equal(ak_false(x_ext)[-4:-1], np.full(3, np.nan)) + # Extrapolation on call and attribute should be equal. + xp_assert_close(ak_false(x_ext, extrapolate=True), ak_true(x_ext), atol=1e-15) + # Testing extrapoation to actual function. + xp_assert_close(y_ext, ak_true(x_ext), atol=1e-15) + + +@pytest.mark.parametrize("method", [Akima1DInterpolator, PchipInterpolator]) +def test_complex(method): + # Complex-valued data deprecated + x = np.arange(0., 11.) + y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.]) + y = y - 2j*y + msg = "real values" + with pytest.raises(ValueError, match=msg): + method(x, y) + + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to Akima1D + x = np.linspace(-5, 5, 11) + y = x**2 + x_ext = np.linspace(-10, 10, 17) + ak = Akima1DInterpolator(x, y, extrapolate=True) + + def worker_fn(_, ak, x_ext): + ak(x_ext) + + _run_concurrent_barrier(10, worker_fn, ak, x_ext) + + +class TestPPolyCommon: + # test basic functionality for PPoly and BPoly + def test_sort_check(self): + c = np.array([[1, 4], [2, 5], [3, 6]]) + x = np.array([0, 1, 0.5]) + assert_raises(ValueError, PPoly, c, x) + assert_raises(ValueError, BPoly, c, x) + + def test_ctor_c(self): + # wrong shape: `c` must be at least 2D + with assert_raises(ValueError): + PPoly([1, 2], [0, 1]) + + def test_extend(self): + # Test adding new points to the piecewise polynomial + np.random.seed(1234) + + order = 3 + x = np.unique(np.r_[0, 10 * np.random.rand(30), 10]) + c = 2*np.random.rand(order+1, len(x)-1, 2, 3) - 1 + + for cls in (PPoly, BPoly): + pp = cls(c[:,:9], x[:10]) + pp.extend(c[:,9:], x[10:]) + + pp2 = cls(c[:, 10:], x[10:]) + pp2.extend(c[:, :10], x[:10]) + + pp3 = cls(c, x) + + xp_assert_equal(pp.c, pp3.c) + xp_assert_equal(pp.x, pp3.x) + xp_assert_equal(pp2.c, pp3.c) + xp_assert_equal(pp2.x, pp3.x) + + def test_extend_diff_orders(self): + # Test extending polynomial with different order one + np.random.seed(1234) + + x = np.linspace(0, 1, 6) + c = np.random.rand(2, 5) + + x2 = np.linspace(1, 2, 6) + c2 = np.random.rand(4, 5) + + for cls in (PPoly, BPoly): + pp1 = cls(c, x) + pp2 = cls(c2, x2) + + pp_comb = cls(c, x) + pp_comb.extend(c2, x2[1:]) + + # NB. doesn't match to pp1 at the endpoint, because pp1 is not + # continuous with pp2 as we took random coefs. + xi1 = np.linspace(0, 1, 300, endpoint=False) + xi2 = np.linspace(1, 2, 300) + + xp_assert_close(pp1(xi1), pp_comb(xi1)) + xp_assert_close(pp2(xi2), pp_comb(xi2)) + + def test_extend_descending(self): + np.random.seed(0) + + order = 3 + x = np.sort(np.random.uniform(0, 10, 20)) + c = np.random.rand(order + 1, x.shape[0] - 1, 2, 3) + + for cls in (PPoly, BPoly): + p = cls(c, x) + + p1 = cls(c[:, :9], x[:10]) + p1.extend(c[:, 9:], x[10:]) + + p2 = cls(c[:, 10:], x[10:]) + p2.extend(c[:, :10], x[:10]) + + xp_assert_equal(p1.c, p.c) + xp_assert_equal(p1.x, p.x) + xp_assert_equal(p2.c, p.c) + xp_assert_equal(p2.x, p.x) + + def test_shape(self): + np.random.seed(1234) + c = np.random.rand(8, 12, 5, 6, 7) + x = np.sort(np.random.rand(13)) + xp = np.random.rand(3, 4) + for cls in (PPoly, BPoly): + p = cls(c, x) + assert p(xp).shape == (3, 4, 5, 6, 7) + + # 'scalars' + for cls in (PPoly, BPoly): + p = cls(c[..., 0, 0, 0], x) + + assert np.shape(p(0.5)) == () + assert np.shape(p(np.array(0.5))) == () + + assert_raises(ValueError, p, np.array([[0.1, 0.2], [0.4]], dtype=object)) + + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to BPoly, PPoly + c = np.random.rand(8, 12, 5, 6, 7) + x = np.sort(np.random.rand(13)) + xp = np.random.rand(3, 4) + + for cls in (PPoly, BPoly): + interp = cls(c, x) + + def worker_fn(_, interp, xp): + interp(xp) + + _run_concurrent_barrier(10, worker_fn, interp, xp) + + + def test_complex_coef(self): + np.random.seed(12345) + x = np.sort(np.random.random(13)) + c = np.random.random((8, 12)) * (1. + 0.3j) + c_re, c_im = c.real, c.imag + xp = np.random.random(5) + for cls in (PPoly, BPoly): + p, p_re, p_im = cls(c, x), cls(c_re, x), cls(c_im, x) + for nu in [0, 1, 2]: + xp_assert_close(p(xp, nu).real, p_re(xp, nu)) + xp_assert_close(p(xp, nu).imag, p_im(xp, nu)) + + def test_axis(self): + np.random.seed(12345) + c = np.random.rand(3, 4, 5, 6, 7, 8) + c_s = c.shape + xp = np.random.random((1, 2)) + for axis in (0, 1, 2, 3): + m = c.shape[axis+1] + x = np.sort(np.random.rand(m+1)) + for cls in (PPoly, BPoly): + p = cls(c, x, axis=axis) + assert p.c.shape == c_s[axis:axis+2] + c_s[:axis] + c_s[axis+2:] + res = p(xp) + targ_shape = c_s[:axis] + xp.shape + c_s[2+axis:] + assert res.shape == targ_shape + + # deriv/antideriv does not drop the axis + for p1 in [cls(c, x, axis=axis).derivative(), + cls(c, x, axis=axis).derivative(2), + cls(c, x, axis=axis).antiderivative(), + cls(c, x, axis=axis).antiderivative(2)]: + assert p1.axis == p.axis + + # c array needs two axes for the coefficients and intervals, so + # 0 <= axis < c.ndim-1; raise otherwise + for axis in (-1, 4, 5, 6): + for cls in (BPoly, PPoly): + assert_raises(ValueError, cls, **dict(c=c, x=x, axis=axis)) + + +class TestPolySubclassing: + class P(PPoly): + pass + + class B(BPoly): + pass + + def _make_polynomials(self): + np.random.seed(1234) + x = np.sort(np.random.random(3)) + c = np.random.random((4, 2)) + return self.P(c, x), self.B(c, x) + + def test_derivative(self): + pp, bp = self._make_polynomials() + for p in (pp, bp): + pd = p.derivative() + assert p.__class__ == pd.__class__ + + ppa = pp.antiderivative() + assert pp.__class__ == ppa.__class__ + + def test_from_spline(self): + np.random.seed(1234) + x = np.sort(np.r_[0, np.random.rand(11), 1]) + y = np.random.rand(len(x)) + + spl = splrep(x, y, s=0) + pp = self.P.from_spline(spl) + assert pp.__class__ == self.P + + def test_conversions(self): + pp, bp = self._make_polynomials() + + pp1 = self.P.from_bernstein_basis(bp) + assert pp1.__class__ == self.P + + bp1 = self.B.from_power_basis(pp) + assert bp1.__class__ == self.B + + def test_from_derivatives(self): + x = [0, 1, 2] + y = [[1], [2], [3]] + bp = self.B.from_derivatives(x, y) + assert bp.__class__ == self.B + + +class TestPPoly: + def test_simple(self): + c = np.array([[1, 4], [2, 5], [3, 6]]) + x = np.array([0, 0.5, 1]) + p = PPoly(c, x) + xp_assert_close(p(0.3), np.asarray(1*0.3**2 + 2*0.3 + 3)) + xp_assert_close(p(0.7), np.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6)) + + def test_periodic(self): + c = np.array([[1, 4], [2, 5], [3, 6]]) + x = np.array([0, 0.5, 1]) + p = PPoly(c, x, extrapolate='periodic') + + xp_assert_close(p(1.3), + np.asarray(1 * 0.3 ** 2 + 2 * 0.3 + 3)) + xp_assert_close(p(-0.3), + np.asarray(4 * (0.7 - 0.5) ** 2 + 5 * (0.7 - 0.5) + 6)) + + xp_assert_close(p(1.3, 1), np.asarray(2 * 0.3 + 2)) + xp_assert_close(p(-0.3, 1), np.asarray(8 * (0.7 - 0.5) + 5)) + + def test_read_only(self): + c = np.array([[1, 4], [2, 5], [3, 6]]) + x = np.array([0, 0.5, 1]) + xnew = np.array([0, 0.1, 0.2]) + PPoly(c, x, extrapolate='periodic') + + for writeable in (True, False): + x.flags.writeable = writeable + c.flags.writeable = writeable + f = PPoly(c, x) + vals = f(xnew) + assert np.isfinite(vals).all() + + def test_descending(self): + def binom_matrix(power): + n = np.arange(power + 1).reshape(-1, 1) + k = np.arange(power + 1) + B = binom(n, k) + return B[::-1, ::-1] + + rng = np.random.RandomState(0) + + power = 3 + for m in [10, 20, 30]: + x = np.sort(rng.uniform(0, 10, m + 1)) + ca = rng.uniform(-2, 2, size=(power + 1, m)) + + h = np.diff(x) + h_powers = h[None, :] ** np.arange(power + 1)[::-1, None] + B = binom_matrix(power) + cap = ca * h_powers + cdp = np.dot(B.T, cap) + cd = cdp / h_powers + + pa = PPoly(ca, x, extrapolate=True) + pd = PPoly(cd[:, ::-1], x[::-1], extrapolate=True) + + x_test = rng.uniform(-10, 20, 100) + xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13) + xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13) + + pa_d = pa.derivative() + pd_d = pd.derivative() + + xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13) + + # Antiderivatives won't be equal because fixing continuity is + # done in the reverse order, but surely the differences should be + # equal. + pa_i = pa.antiderivative() + pd_i = pd.antiderivative() + for a, b in rng.uniform(-10, 20, (5, 2)): + int_a = pa.integrate(a, b) + int_d = pd.integrate(a, b) + xp_assert_close(int_a, int_d, rtol=1e-13) + xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a), + rtol=1e-13) + + roots_d = pd.roots() + roots_a = pa.roots() + xp_assert_close(roots_a, np.sort(roots_d), rtol=1e-12) + + def test_multi_shape(self): + c = np.random.rand(6, 2, 1, 2, 3) + x = np.array([0, 0.5, 1]) + p = PPoly(c, x) + assert p.x.shape == x.shape + assert p.c.shape == c.shape + assert p(0.3).shape == c.shape[2:] + + assert p(np.random.rand(5, 6)).shape == (5, 6) + c.shape[2:] + + dp = p.derivative() + assert dp.c.shape == (5, 2, 1, 2, 3) + ip = p.antiderivative() + assert ip.c.shape == (7, 2, 1, 2, 3) + + def test_construct_fast(self): + np.random.seed(1234) + c = np.array([[1, 4], [2, 5], [3, 6]], dtype=float) + x = np.array([0, 0.5, 1]) + p = PPoly.construct_fast(c, x) + xp_assert_close(p(0.3), np.asarray(1*0.3**2 + 2*0.3 + 3)) + xp_assert_close(p(0.7), np.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6)) + + def test_vs_alternative_implementations(self): + rng = np.random.RandomState(1234) + c = rng.rand(3, 12, 22) + x = np.sort(np.r_[0, rng.rand(11), 1]) + + p = PPoly(c, x) + + xp = np.r_[0.3, 0.5, 0.33, 0.6] + expected = _ppoly_eval_1(c, x, xp) + xp_assert_close(p(xp), expected) + + expected = _ppoly_eval_2(c[:,:,0], x, xp) + xp_assert_close(p(xp)[:, 0], expected) + + def test_from_spline(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0) + pp = PPoly.from_spline(spl) + + xi = np.linspace(0, 1, 200) + xp_assert_close(pp(xi), splev(xi, spl)) + + # make sure .from_spline accepts BSpline objects + b = BSpline(*spl) + ppp = PPoly.from_spline(b) + xp_assert_close(ppp(xi), b(xi)) + + # BSpline's extrapolate attribute propagates unless overridden + t, c, k = spl + for extrap in (None, True, False): + b = BSpline(t, c, k, extrapolate=extrap) + p = PPoly.from_spline(b) + assert p.extrapolate == b.extrapolate + + def test_derivative_simple(self): + np.random.seed(1234) + c = np.array([[4, 3, 2, 1]]).T + dc = np.array([[3*4, 2*3, 2]]).T + ddc = np.array([[2*3*4, 1*2*3]]).T + x = np.array([0, 1]) + + pp = PPoly(c, x) + dpp = PPoly(dc, x) + ddpp = PPoly(ddc, x) + + xp_assert_close(pp.derivative().c, dpp.c) + xp_assert_close(pp.derivative(2).c, ddpp.c) + + def test_derivative_eval(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0) + pp = PPoly.from_spline(spl) + + xi = np.linspace(0, 1, 200) + for dx in range(0, 3): + xp_assert_close(pp(xi, dx), splev(xi, spl, dx)) + + def test_derivative(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + xi = np.linspace(0, 1, 200) + for dx in range(0, 10): + xp_assert_close(pp(xi, dx), pp.derivative(dx)(xi), + err_msg="dx=%d" % (dx,)) + + def test_antiderivative_of_constant(self): + # https://github.com/scipy/scipy/issues/4216 + p = PPoly([[1.]], [0, 1]) + xp_assert_equal(p.antiderivative().c, PPoly([[1], [0]], [0, 1]).c) + xp_assert_equal(p.antiderivative().x, PPoly([[1], [0]], [0, 1]).x) + + def test_antiderivative_regression_4355(self): + # https://github.com/scipy/scipy/issues/4355 + p = PPoly([[1., 0.5]], [0, 1, 2]) + q = p.antiderivative() + xp_assert_equal(q.c, [[1, 0.5], [0, 1]]) + xp_assert_equal(q.x, [0.0, 1, 2]) + xp_assert_close(p.integrate(0, 2), np.asarray(1.5)) + xp_assert_close(np.asarray(q(2) - q(0)), + np.asarray(1.5)) + + def test_antiderivative_simple(self): + np.random.seed(1234) + # [ p1(x) = 3*x**2 + 2*x + 1, + # p2(x) = 1.6875] + c = np.array([[3, 2, 1], [0, 0, 1.6875]]).T + # [ pp1(x) = x**3 + x**2 + x, + # pp2(x) = 1.6875*(x - 0.25) + pp1(0.25)] + ic = np.array([[1, 1, 1, 0], [0, 0, 1.6875, 0.328125]]).T + # [ ppp1(x) = (1/4)*x**4 + (1/3)*x**3 + (1/2)*x**2, + # ppp2(x) = (1.6875/2)*(x - 0.25)**2 + pp1(0.25)*x + ppp1(0.25)] + iic = np.array([[1/4, 1/3, 1/2, 0, 0], + [0, 0, 1.6875/2, 0.328125, 0.037434895833333336]]).T + x = np.array([0, 0.25, 1]) + + pp = PPoly(c, x) + ipp = pp.antiderivative() + iipp = pp.antiderivative(2) + iipp2 = ipp.antiderivative() + + xp_assert_close(ipp.x, x) + xp_assert_close(ipp.c.T, ic.T) + xp_assert_close(iipp.c.T, iic.T) + xp_assert_close(iipp2.c.T, iic.T) + + def test_antiderivative_vs_derivative(self): + rng = np.random.RandomState(1234) + x = np.linspace(0, 1, 30)**2 + y = rng.rand(len(x)) + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + for dx in range(0, 10): + ipp = pp.antiderivative(dx) + + # check that derivative is inverse op + pp2 = ipp.derivative(dx) + xp_assert_close(pp.c, pp2.c) + + # check continuity + for k in range(dx): + pp2 = ipp.derivative(k) + + r = 1e-13 + endpoint = r*pp2.x[:-1] + (1 - r)*pp2.x[1:] + + xp_assert_close(pp2(pp2.x[1:]), pp2(endpoint), + rtol=1e-7, err_msg="dx=%d k=%d" % (dx, k)) + + def test_antiderivative_vs_spline(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + for dx in range(0, 10): + pp2 = pp.antiderivative(dx) + spl2 = splantider(spl, dx) + + xi = np.linspace(0, 1, 200) + xp_assert_close(pp2(xi), splev(xi, spl2), + rtol=1e-7) + + def test_antiderivative_continuity(self): + c = np.array([[2, 1, 2, 2], [2, 1, 3, 3]]).T + x = np.array([0, 0.5, 1]) + + p = PPoly(c, x) + ip = p.antiderivative() + + # check continuity + xp_assert_close(ip(0.5 - 1e-9), ip(0.5 + 1e-9), rtol=1e-8) + + # check that only lowest order coefficients were changed + p2 = ip.derivative() + xp_assert_close(p2.c, p.c) + + def test_integrate(self): + rng = np.random.RandomState(1234) + x = np.sort(np.r_[0, rng.rand(11), 1]) + y = rng.rand(len(x)) + + spl = splrep(x, y, s=0, k=5) + pp = PPoly.from_spline(spl) + + a, b = 0.3, 0.9 + ig = pp.integrate(a, b) + + ipp = pp.antiderivative() + xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False) + xp_assert_close(ig, splint(a, b, spl), check_0d=False) + + a, b = -0.3, 0.9 + ig = pp.integrate(a, b, extrapolate=True) + xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False) + + assert np.isnan(pp.integrate(a, b, extrapolate=False)).all() + + def test_integrate_readonly(self): + x = np.array([1, 2, 4]) + c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]]) + + for writeable in (True, False): + x.flags.writeable = writeable + + P = PPoly(c, x) + vals = P.integrate(1, 4) + + assert np.isfinite(vals).all() + + def test_integrate_periodic(self): + x = np.array([1, 2, 4]) + c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]]) + + P = PPoly(c, x, extrapolate='periodic') + I = P.antiderivative() + + period_int = np.asarray(I(4) - I(1)) + + xp_assert_close(P.integrate(1, 4), period_int) + xp_assert_close(P.integrate(-10, -7), period_int) + xp_assert_close(P.integrate(-10, -4), np.asarray(2 * period_int)) + + xp_assert_close(P.integrate(1.5, 2.5), + np.asarray(I(2.5) - I(1.5))) + xp_assert_close(P.integrate(3.5, 5), + np.asarray(I(2) - I(1) + I(4) - I(3.5))) + xp_assert_close(P.integrate(3.5 + 12, 5 + 12), + np.asarray(I(2) - I(1) + I(4) - I(3.5))) + xp_assert_close(P.integrate(3.5, 5 + 12), + np.asarray(I(2) - I(1) + I(4) - I(3.5) + 4 * period_int)) + xp_assert_close(P.integrate(0, -1), + np.asarray(I(2) - I(3))) + xp_assert_close(P.integrate(-9, -10), + np.asarray(I(2) - I(3))) + xp_assert_close(P.integrate(0, -10), + np.asarray(I(2) - I(3) - 3 * period_int)) + + def test_roots(self): + x = np.linspace(0, 1, 31)**2 + y = np.sin(30*x) + + spl = splrep(x, y, s=0, k=3) + pp = PPoly.from_spline(spl) + + r = pp.roots() + r = r[(r >= 0 - 1e-15) & (r <= 1 + 1e-15)] + xp_assert_close(r, sproot(spl), atol=1e-15) + + def test_roots_idzero(self): + # Roots for piecewise polynomials with identically zero + # sections. + c = np.array([[-1, 0.25], [0, 0], [-1, 0.25]]).T + x = np.array([0, 0.4, 0.6, 1.0]) + + pp = PPoly(c, x) + xp_assert_equal(pp.roots(), + [0.25, 0.4, np.nan, 0.6 + 0.25]) + + # ditto for p.solve(const) with sections identically equal const + const = 2. + c1 = c.copy() + c1[1, :] += const + pp1 = PPoly(c1, x) + + xp_assert_equal(pp1.solve(const), + [0.25, 0.4, np.nan, 0.6 + 0.25]) + + def test_roots_all_zero(self): + # test the code path for the polynomial being identically zero everywhere + c = [[0], [0]] + x = [0, 1] + p = PPoly(c, x) + xp_assert_equal(p.roots(), [0, np.nan]) + xp_assert_equal(p.solve(0), [0, np.nan]) + xp_assert_equal(p.solve(1), []) + + c = [[0, 0], [0, 0]] + x = [0, 1, 2] + p = PPoly(c, x) + xp_assert_equal(p.roots(), [0, np.nan, 1, np.nan]) + xp_assert_equal(p.solve(0), [0, np.nan, 1, np.nan]) + xp_assert_equal(p.solve(1), []) + + def test_roots_repeated(self): + # Check roots repeated in multiple sections are reported only + # once. + + # [(x + 1)**2 - 1, -x**2] ; x == 0 is a repeated root + c = np.array([[1, 0, -1], [-1, 0, 0]]).T + x = np.array([-1, 0, 1]) + + pp = PPoly(c, x) + xp_assert_equal(pp.roots(), np.asarray([-2.0, 0.0])) + xp_assert_equal(pp.roots(extrapolate=False), np.asarray([0.0])) + + def test_roots_discont(self): + # Check that a discontinuity across zero is reported as root + c = np.array([[1], [-1]]).T + x = np.array([0, 0.5, 1]) + pp = PPoly(c, x) + xp_assert_equal(pp.roots(), np.asarray([0.5])) + xp_assert_equal(pp.roots(discontinuity=False), np.asarray([])) + + # ditto for a discontinuity across y: + xp_assert_equal(pp.solve(0.5), np.asarray([0.5])) + xp_assert_equal(pp.solve(0.5, discontinuity=False), np.asarray([])) + + xp_assert_equal(pp.solve(1.5), np.asarray([])) + xp_assert_equal(pp.solve(1.5, discontinuity=False), np.asarray([])) + + def test_roots_random(self): + # Check high-order polynomials with random coefficients + rng = np.random.RandomState(1234) + + num = 0 + + for extrapolate in (True, False): + for order in range(0, 20): + x = np.unique(np.r_[0, 10 * rng.rand(30), 10]) + c = 2*rng.rand(order+1, len(x)-1, 2, 3) - 1 + + pp = PPoly(c, x) + for y in [0, rng.random()]: + r = pp.solve(y, discontinuity=False, extrapolate=extrapolate) + + for i in range(2): + for j in range(3): + rr = r[i,j] + if rr.size > 0: + # Check that the reported roots indeed are roots + num += rr.size + val = pp(rr, extrapolate=extrapolate)[:,i,j] + cmpval = pp(rr, nu=1, + extrapolate=extrapolate)[:,i,j] + msg = f"({extrapolate!r}) r = {repr(rr)}" + xp_assert_close((val-y) / cmpval, np.asarray(0.0), + atol=1e-7, + err_msg=msg, check_shape=False) + + # Check that we checked a number of roots + assert num > 100, repr(num) + + def test_roots_croots(self): + # Test the complex root finding algorithm + rng = np.random.RandomState(1234) + + for k in range(1, 15): + c = rng.rand(k, 1, 130) + + if k == 3: + # add a case with zero discriminant + c[:,0,0] = 1, 2, 1 + + for y in [0, rng.random()]: + w = np.empty(c.shape, dtype=complex) + _ppoly._croots_poly1(c, w, y) + + if k == 1: + assert np.isnan(w).all() + continue + + res = -y + cres = 0 + for i in range(k): + res += c[i,None] * w**(k-1-i) + cres += abs(c[i,None] * w**(k-1-i)) + with np.errstate(invalid='ignore'): + res /= cres + res = res.ravel() + res = res[~np.isnan(res)] + xp_assert_close(res, np.zeros_like(res), atol=1e-10) + + def test_extrapolate_attr(self): + # [ 1 - x**2 ] + c = np.array([[-1, 0, 1]]).T + x = np.array([0, 1]) + + for extrapolate in [True, False, None]: + pp = PPoly(c, x, extrapolate=extrapolate) + pp_d = pp.derivative() + pp_i = pp.antiderivative() + + if extrapolate is False: + assert np.isnan(pp([-0.1, 1.1])).all() + assert np.isnan(pp_i([-0.1, 1.1])).all() + assert np.isnan(pp_d([-0.1, 1.1])).all() + assert pp.roots() == [1] + else: + xp_assert_close(pp([-0.1, 1.1]), [1-0.1**2, 1-1.1**2]) + assert not np.isnan(pp_i([-0.1, 1.1])).any() + assert not np.isnan(pp_d([-0.1, 1.1])).any() + xp_assert_close(pp.roots(), np.asarray([1.0, -1.0])) + + +class TestBPoly: + def test_simple(self): + x = [0, 1] + c = [[3]] + bp = BPoly(c, x) + xp_assert_close(bp(0.1), np.asarray(3.)) + + def test_simple2(self): + x = [0, 1] + c = [[3], [1]] + bp = BPoly(c, x) # 3*(1-x) + 1*x + xp_assert_close(bp(0.1), np.asarray(3*0.9 + 1.*0.1)) + + def test_simple3(self): + x = [0, 1] + c = [[3], [1], [4]] + bp = BPoly(c, x) # 3 * (1-x)**2 + 2 * x (1-x) + 4 * x**2 + xp_assert_close(bp(0.2), + np.asarray(3 * 0.8*0.8 + 1 * 2*0.2*0.8 + 4 * 0.2*0.2)) + + def test_simple4(self): + x = [0, 1] + c = [[1], [1], [1], [2]] + bp = BPoly(c, x) + xp_assert_close(bp(0.3), + np.asarray( 0.7**3 + + 3 * 0.7**2 * 0.3 + + 3 * 0.7 * 0.3**2 + + 2 * 0.3**3) + ) + + def test_simple5(self): + x = [0, 1] + c = [[1], [1], [8], [2], [1]] + bp = BPoly(c, x) + xp_assert_close(bp(0.3), + np.asarray( 0.7**4 + + 4 * 0.7**3 * 0.3 + + 8 * 6 * 0.7**2 * 0.3**2 + + 2 * 4 * 0.7 * 0.3**3 + + 0.3**4) + ) + + def test_periodic(self): + x = [0, 1, 3] + c = [[3, 0], [0, 0], [0, 2]] + # [3*(1-x)**2, 2*((x-1)/2)**2] + bp = BPoly(c, x, extrapolate='periodic') + + xp_assert_close(bp(3.4), np.asarray(3 * 0.6**2)) + xp_assert_close(bp(-1.3), np.asarray(2 * (0.7/2)**2)) + + xp_assert_close(bp(3.4, 1), np.asarray(-6 * 0.6)) + xp_assert_close(bp(-1.3, 1), np.asarray(2 * (0.7/2))) + + def test_descending(self): + rng = np.random.RandomState(0) + + power = 3 + for m in [10, 20, 30]: + x = np.sort(rng.uniform(0, 10, m + 1)) + ca = rng.uniform(-0.1, 0.1, size=(power + 1, m)) + # We need only to flip coefficients to get it right! + cd = ca[::-1].copy() + + pa = BPoly(ca, x, extrapolate=True) + pd = BPoly(cd[:, ::-1], x[::-1], extrapolate=True) + + x_test = rng.uniform(-10, 20, 100) + xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13) + xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13) + + pa_d = pa.derivative() + pd_d = pd.derivative() + + xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13) + + # Antiderivatives won't be equal because fixing continuity is + # done in the reverse order, but surely the differences should be + # equal. + pa_i = pa.antiderivative() + pd_i = pd.antiderivative() + for a, b in rng.uniform(-10, 20, (5, 2)): + int_a = pa.integrate(a, b) + int_d = pd.integrate(a, b) + xp_assert_close(int_a, int_d, rtol=1e-12) + xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a), + rtol=1e-12) + + def test_multi_shape(self): + rng = np.random.RandomState(1234) + c = rng.rand(6, 2, 1, 2, 3) + x = np.array([0, 0.5, 1]) + p = BPoly(c, x) + assert p.x.shape == x.shape + assert p.c.shape == c.shape + assert p(0.3).shape == c.shape[2:] + assert p(rng.rand(5, 6)).shape == (5, 6) + c.shape[2:] + + dp = p.derivative() + assert dp.c.shape == (5, 2, 1, 2, 3) + + def test_interval_length(self): + x = [0, 2] + c = [[3], [1], [4]] + bp = BPoly(c, x) + xval = 0.1 + s = xval / 2 # s = (x - xa) / (xb - xa) + xp_assert_close(bp(xval), + np.asarray(3 * (1-s)*(1-s) + 1 * 2*s*(1-s) + 4 * s*s) + ) + + def test_two_intervals(self): + x = [0, 1, 3] + c = [[3, 0], [0, 0], [0, 2]] + bp = BPoly(c, x) # [3*(1-x)**2, 2*((x-1)/2)**2] + + xp_assert_close(bp(0.4), np.asarray(3 * 0.6*0.6)) + xp_assert_close(bp(1.7), np.asarray(2 * (0.7/2)**2)) + + def test_extrapolate_attr(self): + x = [0, 2] + c = [[3], [1], [4]] + bp = BPoly(c, x) + + for extrapolate in (True, False, None): + bp = BPoly(c, x, extrapolate=extrapolate) + bp_d = bp.derivative() + if extrapolate is False: + assert np.isnan(bp([-0.1, 2.1])).all() + assert np.isnan(bp_d([-0.1, 2.1])).all() + else: + assert not np.isnan(bp([-0.1, 2.1])).any() + assert not np.isnan(bp_d([-0.1, 2.1])).any() + + +class TestBPolyCalculus: + def test_derivative(self): + x = [0, 1, 3] + c = [[3, 0], [0, 0], [0, 2]] + bp = BPoly(c, x) # [3*(1-x)**2, 2*((x-1)/2)**2] + bp_der = bp.derivative() + xp_assert_close(bp_der(0.4), np.asarray(-6*(0.6))) + xp_assert_close(bp_der(1.7), np.asarray(0.7)) + + # derivatives in-place + xp_assert_close(np.asarray([bp(0.4, nu) for nu in [1, 2, 3]]), + np.asarray([-6*(1-0.4), 6., 0.]) + ) + xp_assert_close(np.asarray([bp(1.7, nu) for nu in [1, 2, 3]]), + np.asarray([0.7, 1., 0]) + ) + + def test_derivative_ppoly(self): + # make sure it's consistent w/ power basis + rng = np.random.RandomState(1234) + m, k = 5, 8 # number of intervals, order + x = np.sort(rng.random(m)) + c = rng.random((k, m-1)) + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + + for d in range(k): + bp = bp.derivative() + pp = pp.derivative() + xp = np.linspace(x[0], x[-1], 21) + xp_assert_close(bp(xp), pp(xp)) + + def test_deriv_inplace(self): + rng = np.random.RandomState(1234) + m, k = 5, 8 # number of intervals, order + x = np.sort(rng.random(m)) + c = rng.random((k, m-1)) + + # test both real and complex coefficients + for cc in [c.copy(), c*(1. + 2.j)]: + bp = BPoly(cc, x) + xp = np.linspace(x[0], x[-1], 21) + for i in range(k): + xp_assert_close(bp(xp, i), bp.derivative(i)(xp)) + + def test_antiderivative_simple(self): + # f(x) = x for x \in [0, 1), + # (x-1)/2 for x \in [1, 3] + # + # antiderivative is then + # F(x) = x**2 / 2 for x \in [0, 1), + # 0.5*x*(x/2 - 1) + A for x \in [1, 3] + # where A = 3/4 for continuity at x = 1. + x = [0, 1, 3] + c = [[0, 0], [1, 1]] + + bp = BPoly(c, x) + bi = bp.antiderivative() + + xx = np.linspace(0, 3, 11) + xp_assert_close(bi(xx), + np.where(xx < 1, xx**2 / 2., + 0.5 * xx * (xx/2. - 1) + 3./4), + atol=1e-12, rtol=1e-12) + + def test_der_antider(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10, 2, 3)) + bp = BPoly(c, x) + + xx = np.linspace(x[0], x[-1], 100) + xp_assert_close(bp.antiderivative().derivative()(xx), + bp(xx), atol=1e-12, rtol=1e-12) + + def test_antider_ppoly(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10, 2, 3)) + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + + xx = np.linspace(x[0], x[-1], 10) + + xp_assert_close(bp.antiderivative(2)(xx), + pp.antiderivative(2)(xx), atol=1e-12, rtol=1e-12) + + def test_antider_continuous(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10)) + bp = BPoly(c, x).antiderivative() + + xx = bp.x[1:-1] + xp_assert_close(bp(xx - 1e-14), + bp(xx + 1e-14), atol=1e-12, rtol=1e-12) + + def test_integrate(self): + rng = np.random.RandomState(1234) + x = np.sort(rng.random(11)) + c = rng.random((4, 10)) + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + xp_assert_close(bp.integrate(0, 1), + pp.integrate(0, 1), atol=1e-12, rtol=1e-12, check_0d=False) + + def test_integrate_extrap(self): + c = [[1]] + x = [0, 1] + b = BPoly(c, x) + + # default is extrapolate=True + xp_assert_close(b.integrate(0, 2), np.asarray(2.), + atol=1e-14, check_0d=False) + + # .integrate argument overrides self.extrapolate + b1 = BPoly(c, x, extrapolate=False) + assert np.isnan(b1.integrate(0, 2)) + xp_assert_close(b1.integrate(0, 2, extrapolate=True), + np.asarray(2.), atol=1e-14, check_0d=False) + + def test_integrate_periodic(self): + x = np.array([1, 2, 4]) + c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]]) + + P = BPoly.from_power_basis(PPoly(c, x), extrapolate='periodic') + I = P.antiderivative() + + period_int = I(4) - I(1) + + xp_assert_close(P.integrate(1, 4), period_int) #, check_0d=False) + xp_assert_close(P.integrate(-10, -7), period_int) + xp_assert_close(P.integrate(-10, -4), 2 * period_int) + + xp_assert_close(P.integrate(1.5, 2.5), I(2.5) - I(1.5)) + xp_assert_close(P.integrate(3.5, 5), I(2) - I(1) + I(4) - I(3.5)) + xp_assert_close(P.integrate(3.5 + 12, 5 + 12), + I(2) - I(1) + I(4) - I(3.5)) + xp_assert_close(P.integrate(3.5, 5 + 12), + I(2) - I(1) + I(4) - I(3.5) + 4 * period_int) + + xp_assert_close(P.integrate(0, -1), I(2) - I(3)) + xp_assert_close(P.integrate(-9, -10), I(2) - I(3)) + xp_assert_close(P.integrate(0, -10), I(2) - I(3) - 3 * period_int) + + def test_antider_neg(self): + # .derivative(-nu) ==> .andiderivative(nu) and vice versa + c = [[1]] + x = [0, 1] + b = BPoly(c, x) + + xx = np.linspace(0, 1, 21) + + xp_assert_close(b.derivative(-1)(xx), b.antiderivative()(xx), + atol=1e-12, rtol=1e-12) + xp_assert_close(b.derivative(1)(xx), b.antiderivative(-1)(xx), + atol=1e-12, rtol=1e-12) + + +class TestPolyConversions: + def test_bp_from_pp(self): + x = [0, 1, 3] + c = [[3, 2], [1, 8], [4, 3]] + pp = PPoly(c, x) + bp = BPoly.from_power_basis(pp) + pp1 = PPoly.from_bernstein_basis(bp) + + xp = [0.1, 1.4] + xp_assert_close(pp(xp), bp(xp)) + xp_assert_close(pp(xp), pp1(xp)) + + def test_bp_from_pp_random(self): + rng = np.random.RandomState(1234) + m, k = 5, 8 # number of intervals, order + x = np.sort(rng.random(m)) + c = rng.random((k, m-1)) + pp = PPoly(c, x) + bp = BPoly.from_power_basis(pp) + pp1 = PPoly.from_bernstein_basis(bp) + + xp = np.linspace(x[0], x[-1], 21) + xp_assert_close(pp(xp), bp(xp)) + xp_assert_close(pp(xp), pp1(xp)) + + def test_pp_from_bp(self): + x = [0, 1, 3] + c = [[3, 3], [1, 1], [4, 2]] + bp = BPoly(c, x) + pp = PPoly.from_bernstein_basis(bp) + bp1 = BPoly.from_power_basis(pp) + + xp = [0.1, 1.4] + xp_assert_close(bp(xp), pp(xp)) + xp_assert_close(bp(xp), bp1(xp)) + + def test_broken_conversions(self): + # regression test for gh-10597: from_power_basis only accepts PPoly etc. + x = [0, 1, 3] + c = [[3, 3], [1, 1], [4, 2]] + pp = PPoly(c, x) + with assert_raises(TypeError): + PPoly.from_bernstein_basis(pp) + + bp = BPoly(c, x) + with assert_raises(TypeError): + BPoly.from_power_basis(bp) + + +class TestBPolyFromDerivatives: + def test_make_poly_1(self): + c1 = BPoly._construct_from_derivatives(0, 1, [2], [3]) + xp_assert_close(c1, [2., 3.]) + + def test_make_poly_2(self): + c1 = BPoly._construct_from_derivatives(0, 1, [1, 0], [1]) + xp_assert_close(c1, [1., 1., 1.]) + + # f'(0) = 3 + c2 = BPoly._construct_from_derivatives(0, 1, [2, 3], [1]) + xp_assert_close(c2, [2., 7./2, 1.]) + + # f'(1) = 3 + c3 = BPoly._construct_from_derivatives(0, 1, [2], [1, 3]) + xp_assert_close(c3, [2., -0.5, 1.]) + + def test_make_poly_3(self): + # f'(0)=2, f''(0)=3 + c1 = BPoly._construct_from_derivatives(0, 1, [1, 2, 3], [4]) + xp_assert_close(c1, [1., 5./3, 17./6, 4.]) + + # f'(1)=2, f''(1)=3 + c2 = BPoly._construct_from_derivatives(0, 1, [1], [4, 2, 3]) + xp_assert_close(c2, [1., 19./6, 10./3, 4.]) + + # f'(0)=2, f'(1)=3 + c3 = BPoly._construct_from_derivatives(0, 1, [1, 2], [4, 3]) + xp_assert_close(c3, [1., 5./3, 3., 4.]) + + def test_make_poly_12(self): + rng = np.random.RandomState(12345) + ya = np.r_[0, rng.random(5)] + yb = np.r_[0, rng.random(5)] + + c = BPoly._construct_from_derivatives(0, 1, ya, yb) + pp = BPoly(c[:, None], [0, 1]) + for j in range(6): + xp_assert_close(pp(0.), ya[j], check_0d=False) + xp_assert_close(pp(1.), yb[j], check_0d=False) + pp = pp.derivative() + + def test_raise_degree(self): + rng = np.random.RandomState(12345) + x = [0, 1] + k, d = 8, 5 + c = rng.random((k, 1, 2, 3, 4)) + bp = BPoly(c, x) + + c1 = BPoly._raise_degree(c, d) + bp1 = BPoly(c1, x) + + xp = np.linspace(0, 1, 11) + xp_assert_close(bp(xp), bp1(xp)) + + def test_xi_yi(self): + assert_raises(ValueError, BPoly.from_derivatives, [0, 1], [0]) + + def test_coords_order(self): + xi = [0, 0, 1] + yi = [[0], [0], [0]] + assert_raises(ValueError, BPoly.from_derivatives, xi, yi) + + def test_zeros(self): + xi = [0, 1, 2, 3] + yi = [[0, 0], [0], [0, 0], [0, 0]] # NB: will have to raise the degree + pp = BPoly.from_derivatives(xi, yi) + assert pp.c.shape == (4, 3) + + ppd = pp.derivative() + for xp in [0., 0.1, 1., 1.1, 1.9, 2., 2.5]: + xp_assert_close(pp(xp), np.asarray(0.0)) + xp_assert_close(ppd(xp), np.asarray(0.0)) + + + def _make_random_mk(self, m, k): + # k derivatives at each breakpoint + rng = np.random.RandomState(1234) + xi = np.asarray([1. * j**2 for j in range(m+1)]) + yi = [rng.random(k) for j in range(m+1)] + return xi, yi + + def test_random_12(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + pp = BPoly.from_derivatives(xi, yi) + + for order in range(k//2): + xp_assert_close(pp(xi), [yy[order] for yy in yi]) + pp = pp.derivative() + + def test_order_zero(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + assert_raises(ValueError, BPoly.from_derivatives, + **dict(xi=xi, yi=yi, orders=0)) + + def test_orders_too_high(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + + BPoly.from_derivatives(xi, yi, orders=2*k-1) # this is still ok + assert_raises(ValueError, BPoly.from_derivatives, # but this is not + **dict(xi=xi, yi=yi, orders=2*k)) + + def test_orders_global(self): + m, k = 5, 12 + xi, yi = self._make_random_mk(m, k) + + # ok, this is confusing. Local polynomials will be of the order 5 + # which means that up to the 2nd derivatives will be used at each point + order = 5 + pp = BPoly.from_derivatives(xi, yi, orders=order) + + for j in range(order//2+1): + xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + pp = pp.derivative() + assert not np.allclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + + # now repeat with `order` being even: on each interval, it uses + # order//2 'derivatives' @ the right-hand endpoint and + # order//2+1 @ 'derivatives' the left-hand endpoint + order = 6 + pp = BPoly.from_derivatives(xi, yi, orders=order) + for j in range(order//2): + xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + pp = pp.derivative() + assert not np.allclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)) + + def test_orders_local(self): + m, k = 7, 12 + xi, yi = self._make_random_mk(m, k) + + orders = [o + 1 for o in range(m)] + for i, x in enumerate(xi[1:-1]): + pp = BPoly.from_derivatives(xi, yi, orders=orders) + for j in range(orders[i] // 2 + 1): + xp_assert_close(pp(x - 1e-12), pp(x + 1e-12)) + pp = pp.derivative() + assert not np.allclose(pp(x - 1e-12), pp(x + 1e-12)) + + def test_yi_trailing_dims(self): + rng = np.random.RandomState(1234) + m, k = 7, 5 + xi = np.sort(rng.random(m+1)) + yi = rng.random((m+1, k, 6, 7, 8)) + pp = BPoly.from_derivatives(xi, yi) + assert pp.c.shape == (2*k, m, 6, 7, 8) + + def test_gh_5430(self): + # At least one of these raises an error unless gh-5430 is + # fixed. In py2k an int is implemented using a C long, so + # which one fails depends on your system. In py3k there is only + # one arbitrary precision integer type, so both should fail. + orders = np.int32(1) + p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders) + assert_almost_equal(p(0), np.asarray(0)) + orders = np.int64(1) + p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders) + assert_almost_equal(p(0), np.asarray(0)) + orders = 1 + # This worked before; make sure it still works + p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders) + assert_almost_equal(p(0), np.asarray(0)) + orders = 1 + + +class TestNdPPoly: + def test_simple_1d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5) + x = np.linspace(0, 1, 5+1) + + xi = rng.rand(200) + + p = NdPPoly(c, (x,)) + v1 = p((xi,)) + + v2 = _ppoly_eval_1(c[:,:,None], x, xi).ravel() + xp_assert_close(v1, v2) + + def test_simple_2d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7) + x = np.linspace(0, 1, 6+1) + y = np.linspace(0, 1, 7+1)**2 + + xi = rng.rand(200) + yi = rng.rand(200) + + v1 = np.empty([len(xi), 1], dtype=c.dtype) + v1.fill(np.nan) + _ppoly.evaluate_nd(c.reshape(4*5, 6*7, 1), + (x, y), + np.array([4, 5], dtype=np.intc), + np.c_[xi, yi], + np.array([0, 0], dtype=np.intc), + 1, + v1) + v1 = v1.ravel() + v2 = _ppoly2d_eval(c, (x, y), xi, yi) + xp_assert_close(v1, v2) + + p = NdPPoly(c, (x, y)) + for nu in (None, (0, 0), (0, 1), (1, 0), (2, 3), (9, 2)): + v1 = p(np.c_[xi, yi], nu=nu) + v2 = _ppoly2d_eval(c, (x, y), xi, yi, nu=nu) + xp_assert_close(v1, v2, err_msg=repr(nu)) + + def test_simple_3d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7, 8, 9) + x = np.linspace(0, 1, 7+1) + y = np.linspace(0, 1, 8+1)**2 + z = np.linspace(0, 1, 9+1)**3 + + xi = rng.rand(40) + yi = rng.rand(40) + zi = rng.rand(40) + + p = NdPPoly(c, (x, y, z)) + + for nu in (None, (0, 0, 0), (0, 1, 0), (1, 0, 0), (2, 3, 0), + (6, 0, 2)): + v1 = p((xi, yi, zi), nu=nu) + v2 = _ppoly3d_eval(c, (x, y, z), xi, yi, zi, nu=nu) + xp_assert_close(v1, v2, err_msg=repr(nu)) + + def test_simple_4d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7, 8, 9, 10, 11) + x = np.linspace(0, 1, 8+1) + y = np.linspace(0, 1, 9+1)**2 + z = np.linspace(0, 1, 10+1)**3 + u = np.linspace(0, 1, 11+1)**4 + + xi = rng.rand(20) + yi = rng.rand(20) + zi = rng.rand(20) + ui = rng.rand(20) + + p = NdPPoly(c, (x, y, z, u)) + v1 = p((xi, yi, zi, ui)) + + v2 = _ppoly4d_eval(c, (x, y, z, u), xi, yi, zi, ui) + xp_assert_close(v1, v2) + + def test_deriv_1d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5) + x = np.linspace(0, 1, 5+1) + + p = NdPPoly(c, (x,)) + + # derivative + dp = p.derivative(nu=[1]) + p1 = PPoly(c, x) + dp1 = p1.derivative() + xp_assert_close(dp.c, dp1.c) + + # antiderivative + dp = p.antiderivative(nu=[2]) + p1 = PPoly(c, x) + dp1 = p1.antiderivative(2) + xp_assert_close(dp.c, dp1.c) + + def test_deriv_3d(self): + rng = np.random.RandomState(1234) + + c = rng.rand(4, 5, 6, 7, 8, 9) + x = np.linspace(0, 1, 7+1) + y = np.linspace(0, 1, 8+1)**2 + z = np.linspace(0, 1, 9+1)**3 + + p = NdPPoly(c, (x, y, z)) + + # differentiate vs x + p1 = PPoly(c.transpose(0, 3, 1, 2, 4, 5), x) + dp = p.derivative(nu=[2]) + dp1 = p1.derivative(2) + xp_assert_close(dp.c, + dp1.c.transpose(0, 2, 3, 1, 4, 5)) + + # antidifferentiate vs y + p1 = PPoly(c.transpose(1, 4, 0, 2, 3, 5), y) + dp = p.antiderivative(nu=[0, 1, 0]) + dp1 = p1.antiderivative(1) + xp_assert_close(dp.c, + dp1.c.transpose(2, 0, 3, 4, 1, 5)) + + # differentiate vs z + p1 = PPoly(c.transpose(2, 5, 0, 1, 3, 4), z) + dp = p.derivative(nu=[0, 0, 3]) + dp1 = p1.derivative(3) + xp_assert_close(dp.c, + dp1.c.transpose(2, 3, 0, 4, 5, 1)) + + def test_deriv_3d_simple(self): + # Integrate to obtain function x y**2 z**4 / (2! 4!) + rng = np.random.RandomState(1234) + + c = np.ones((1, 1, 1, 3, 4, 5)) + x = np.linspace(0, 1, 3+1)**1 + y = np.linspace(0, 1, 4+1)**2 + z = np.linspace(0, 1, 5+1)**3 + + p = NdPPoly(c, (x, y, z)) + ip = p.antiderivative((1, 0, 4)) + ip = ip.antiderivative((0, 2, 0)) + + xi = rng.rand(20) + yi = rng.rand(20) + zi = rng.rand(20) + + xp_assert_close(ip((xi, yi, zi)), + xi * yi**2 * zi**4 / (gamma(3)*gamma(5))) + + def test_integrate_2d(self): + rng = np.random.RandomState(1234) + c = rng.rand(4, 5, 16, 17) + x = np.linspace(0, 1, 16+1)**1 + y = np.linspace(0, 1, 17+1)**2 + + # make continuously differentiable so that nquad() has an + # easier time + c = c.transpose(0, 2, 1, 3) + cx = c.reshape(c.shape[0], c.shape[1], -1).copy() + _ppoly.fix_continuity(cx, x, 2) + c = cx.reshape(c.shape) + c = c.transpose(0, 2, 1, 3) + c = c.transpose(1, 3, 0, 2) + cx = c.reshape(c.shape[0], c.shape[1], -1).copy() + _ppoly.fix_continuity(cx, y, 2) + c = cx.reshape(c.shape) + c = c.transpose(2, 0, 3, 1).copy() + + # Check integration + p = NdPPoly(c, (x, y)) + + for ranges in [[(0, 1), (0, 1)], + [(0, 0.5), (0, 1)], + [(0, 1), (0, 0.5)], + [(0.3, 0.7), (0.6, 0.2)]]: + + ig = p.integrate(ranges) + ig2, err2 = nquad(lambda x, y: p((x, y)), ranges, + opts=[dict(epsrel=1e-5, epsabs=1e-5)]*2) + xp_assert_close(ig, ig2, rtol=1e-5, atol=1e-5, check_0d=False, + err_msg=repr(ranges)) + + def test_integrate_1d(self): + rng = np.random.RandomState(1234) + c = rng.rand(4, 5, 6, 16, 17, 18) + x = np.linspace(0, 1, 16+1)**1 + y = np.linspace(0, 1, 17+1)**2 + z = np.linspace(0, 1, 18+1)**3 + + # Check 1-D integration + p = NdPPoly(c, (x, y, z)) + + u = rng.rand(200) + v = rng.rand(200) + a, b = 0.2, 0.7 + + px = p.integrate_1d(a, b, axis=0) + pax = p.antiderivative((1, 0, 0)) + xp_assert_close(px((u, v)), pax((b, u, v)) - pax((a, u, v))) + + py = p.integrate_1d(a, b, axis=1) + pay = p.antiderivative((0, 1, 0)) + xp_assert_close(py((u, v)), pay((u, b, v)) - pay((u, a, v))) + + pz = p.integrate_1d(a, b, axis=2) + paz = p.antiderivative((0, 0, 1)) + xp_assert_close(pz((u, v)), paz((u, v, b)) - paz((u, v, a))) + + @pytest.mark.thread_unsafe + def test_concurrency(self): + rng = np.random.default_rng(12345) + + c = rng.uniform(size=(4, 5, 6, 7, 8, 9)) + x = np.linspace(0, 1, 7+1) + y = np.linspace(0, 1, 8+1)**2 + z = np.linspace(0, 1, 9+1)**3 + + p = NdPPoly(c, (x, y, z)) + + def worker_fn(_, spl): + xi = rng.uniform(size=40) + yi = rng.uniform(size=40) + zi = rng.uniform(size=40) + spl((xi, yi, zi)) + + _run_concurrent_barrier(10, worker_fn, p) + + +def _ppoly_eval_1(c, x, xps): + """Evaluate piecewise polynomial manually""" + out = np.zeros((len(xps), c.shape[2])) + for i, xp in enumerate(xps): + if xp < 0 or xp > 1: + out[i,:] = np.nan + continue + j = np.searchsorted(x, xp) - 1 + d = xp - x[j] + assert x[j] <= xp < x[j+1] + r = sum(c[k,j] * d**(c.shape[0]-k-1) + for k in range(c.shape[0])) + out[i,:] = r + return out + + +def _ppoly_eval_2(coeffs, breaks, xnew, fill=np.nan): + """Evaluate piecewise polynomial manually (another way)""" + a = breaks[0] + b = breaks[-1] + K = coeffs.shape[0] + + saveshape = np.shape(xnew) + xnew = np.ravel(xnew) + res = np.empty_like(xnew) + mask = (xnew >= a) & (xnew <= b) + res[~mask] = fill + xx = xnew.compress(mask) + indxs = np.searchsorted(breaks, xx)-1 + indxs = indxs.clip(0, len(breaks)) + pp = coeffs + diff = xx - breaks.take(indxs) + V = np.vander(diff, N=K) + values = np.array([np.dot(V[k, :], pp[:, indxs[k]]) for k in range(len(xx))]) + res[mask] = values + res.shape = saveshape + return res + + +def _dpow(x, y, n): + """ + d^n (x**y) / dx^n + """ + if n < 0: + raise ValueError("invalid derivative order") + elif n > y: + return 0 + else: + return poch(y - n + 1, n) * x**(y - n) + + +def _ppoly2d_eval(c, xs, xnew, ynew, nu=None): + """ + Straightforward evaluation of 2-D piecewise polynomial + """ + if nu is None: + nu = (0, 0) + + out = np.empty((len(xnew),), dtype=c.dtype) + + nx, ny = c.shape[:2] + + for jout, (x, y) in enumerate(zip(xnew, ynew)): + if not ((xs[0][0] <= x <= xs[0][-1]) and + (xs[1][0] <= y <= xs[1][-1])): + out[jout] = np.nan + continue + + j1 = np.searchsorted(xs[0], x) - 1 + j2 = np.searchsorted(xs[1], y) - 1 + + s1 = x - xs[0][j1] + s2 = y - xs[1][j2] + + val = 0 + + for k1 in range(c.shape[0]): + for k2 in range(c.shape[1]): + val += (c[nx-k1-1,ny-k2-1,j1,j2] + * _dpow(s1, k1, nu[0]) + * _dpow(s2, k2, nu[1])) + + out[jout] = val + + return out + + +def _ppoly3d_eval(c, xs, xnew, ynew, znew, nu=None): + """ + Straightforward evaluation of 3-D piecewise polynomial + """ + if nu is None: + nu = (0, 0, 0) + + out = np.empty((len(xnew),), dtype=c.dtype) + + nx, ny, nz = c.shape[:3] + + for jout, (x, y, z) in enumerate(zip(xnew, ynew, znew)): + if not ((xs[0][0] <= x <= xs[0][-1]) and + (xs[1][0] <= y <= xs[1][-1]) and + (xs[2][0] <= z <= xs[2][-1])): + out[jout] = np.nan + continue + + j1 = np.searchsorted(xs[0], x) - 1 + j2 = np.searchsorted(xs[1], y) - 1 + j3 = np.searchsorted(xs[2], z) - 1 + + s1 = x - xs[0][j1] + s2 = y - xs[1][j2] + s3 = z - xs[2][j3] + + val = 0 + for k1 in range(c.shape[0]): + for k2 in range(c.shape[1]): + for k3 in range(c.shape[2]): + val += (c[nx-k1-1,ny-k2-1,nz-k3-1,j1,j2,j3] + * _dpow(s1, k1, nu[0]) + * _dpow(s2, k2, nu[1]) + * _dpow(s3, k3, nu[2])) + + out[jout] = val + + return out + + +def _ppoly4d_eval(c, xs, xnew, ynew, znew, unew, nu=None): + """ + Straightforward evaluation of 4-D piecewise polynomial + """ + if nu is None: + nu = (0, 0, 0, 0) + + out = np.empty((len(xnew),), dtype=c.dtype) + + mx, my, mz, mu = c.shape[:4] + + for jout, (x, y, z, u) in enumerate(zip(xnew, ynew, znew, unew)): + if not ((xs[0][0] <= x <= xs[0][-1]) and + (xs[1][0] <= y <= xs[1][-1]) and + (xs[2][0] <= z <= xs[2][-1]) and + (xs[3][0] <= u <= xs[3][-1])): + out[jout] = np.nan + continue + + j1 = np.searchsorted(xs[0], x) - 1 + j2 = np.searchsorted(xs[1], y) - 1 + j3 = np.searchsorted(xs[2], z) - 1 + j4 = np.searchsorted(xs[3], u) - 1 + + s1 = x - xs[0][j1] + s2 = y - xs[1][j2] + s3 = z - xs[2][j3] + s4 = u - xs[3][j4] + + val = 0 + for k1 in range(c.shape[0]): + for k2 in range(c.shape[1]): + for k3 in range(c.shape[2]): + for k4 in range(c.shape[3]): + val += (c[mx-k1-1,my-k2-1,mz-k3-1,mu-k4-1,j1,j2,j3,j4] + * _dpow(s1, k1, nu[0]) + * _dpow(s2, k2, nu[1]) + * _dpow(s3, k3, nu[2]) + * _dpow(s4, k4, nu[3])) + + out[jout] = val + + return out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py new file mode 100644 index 0000000000000000000000000000000000000000..047a940b3efcb24ec85a94a87dd1050baa01f165 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py @@ -0,0 +1,308 @@ +import numpy as np +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close +) +import pytest +from pytest import raises as assert_raises + +from scipy.interpolate import (griddata, NearestNDInterpolator, + LinearNDInterpolator, + CloughTocher2DInterpolator) +from scipy._lib._testutils import _run_concurrent_barrier + + +parametrize_interpolators = pytest.mark.parametrize( + "interpolator", [NearestNDInterpolator, LinearNDInterpolator, + CloughTocher2DInterpolator] +) +parametrize_methods = pytest.mark.parametrize( + 'method', + ('nearest', 'linear', 'cubic'), +) +parametrize_rescale = pytest.mark.parametrize( + 'rescale', + (True, False), +) + + +class TestGriddata: + def test_fill_value(self): + x = [(0,0), (0,1), (1,0)] + y = [1, 2, 3] + + yi = griddata(x, y, [(1,1), (1,2), (0,0)], fill_value=-1) + xp_assert_equal(yi, [-1., -1, 1]) + + yi = griddata(x, y, [(1,1), (1,2), (0,0)]) + xp_assert_equal(yi, [np.nan, np.nan, 1]) + + @parametrize_methods + @parametrize_rescale + def test_alternative_call(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = (np.arange(x.shape[0], dtype=np.float64)[:,None] + + np.array([0,1])[None,:]) + + msg = repr((method, rescale)) + yi = griddata((x[:,0], x[:,1]), y, (x[:,0], x[:,1]), method=method, + rescale=rescale) + xp_assert_close(y, yi, atol=1e-14, err_msg=msg) + + @parametrize_methods + @parametrize_rescale + def test_multivalue_2d(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = (np.arange(x.shape[0], dtype=np.float64)[:,None] + + np.array([0,1])[None,:]) + + msg = repr((method, rescale)) + yi = griddata(x, y, x, method=method, rescale=rescale) + xp_assert_close(y, yi, atol=1e-14, err_msg=msg) + + @parametrize_methods + @parametrize_rescale + def test_multipoint_2d(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + + xi = x[:,None,:] + np.array([0,0,0])[None,:,None] + + msg = repr((method, rescale)) + yi = griddata(x, y, xi, method=method, rescale=rescale) + + assert yi.shape == (5, 3), msg + xp_assert_close(yi, np.tile(y[:,None], (1, 3)), + atol=1e-14, err_msg=msg) + + @parametrize_methods + @parametrize_rescale + def test_complex_2d(self, method, rescale): + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 2j*y[::-1] + + xi = x[:,None,:] + np.array([0,0,0])[None,:,None] + + msg = repr((method, rescale)) + yi = griddata(x, y, xi, method=method, rescale=rescale) + + assert yi.shape == (5, 3) + xp_assert_close(yi, np.tile(y[:,None], (1, 3)), + atol=1e-14, err_msg=msg) + + @parametrize_methods + def test_1d(self, method): + x = np.array([1, 2.5, 3, 4.5, 5, 6]) + y = np.array([1, 2, 0, 3.9, 2, 1]) + + xp_assert_close(griddata(x, y, x, method=method), y, + err_msg=method, atol=1e-14) + xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y, + err_msg=method, atol=1e-14) + xp_assert_close(griddata((x,), y, (x,), method=method), y, + err_msg=method, atol=1e-14) + + def test_1d_borders(self): + # Test for nearest neighbor case with xi outside + # the range of the values. + x = np.array([1, 2.5, 3, 4.5, 5, 6]) + y = np.array([1, 2, 0, 3.9, 2, 1]) + xi = np.array([0.9, 6.5]) + yi_should = np.array([1.0, 1.0]) + + method = 'nearest' + xp_assert_close(griddata(x, y, xi, + method=method), yi_should, + err_msg=method, + atol=1e-14) + xp_assert_close(griddata(x.reshape(6, 1), y, xi, + method=method), yi_should, + err_msg=method, + atol=1e-14) + xp_assert_close(griddata((x, ), y, (xi, ), + method=method), yi_should, + err_msg=method, + atol=1e-14) + + @parametrize_methods + def test_1d_unsorted(self, method): + x = np.array([2.5, 1, 4.5, 5, 6, 3]) + y = np.array([1, 2, 0, 3.9, 2, 1]) + + xp_assert_close(griddata(x, y, x, method=method), y, + err_msg=method, atol=1e-10) + xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y, + err_msg=method, atol=1e-10) + xp_assert_close(griddata((x,), y, (x,), method=method), y, + err_msg=method, atol=1e-10) + + @parametrize_methods + def test_square_rescale_manual(self, method): + points = np.array([(0,0), (0,100), (10,100), (10,0), (1, 5)], dtype=np.float64) + points_rescaled = np.array([(0,0), (0,1), (1,1), (1,0), (0.1, 0.05)], + dtype=np.float64) + values = np.array([1., 2., -3., 5., 9.], dtype=np.float64) + + xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None], + np.linspace(0, 100, 14)[None,:]) + xx = xx.ravel() + yy = yy.ravel() + xi = np.array([xx, yy]).T.copy() + + msg = method + zi = griddata(points_rescaled, values, xi/np.array([10, 100.]), + method=method) + zi_rescaled = griddata(points, values, xi, method=method, + rescale=True) + xp_assert_close(zi, zi_rescaled, err_msg=msg, + atol=1e-12) + + @parametrize_methods + def test_xi_1d(self, method): + # Check that 1-D xi is interpreted as a coordinate + x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)], + dtype=np.float64) + y = np.arange(x.shape[0], dtype=np.float64) + y = y - 2j*y[::-1] + + xi = np.array([0.5, 0.5]) + + p1 = griddata(x, y, xi, method=method) + p2 = griddata(x, y, xi[None,:], method=method) + xp_assert_close(p1, p2, err_msg=method) + + xi1 = np.array([0.5]) + xi3 = np.array([0.5, 0.5, 0.5]) + assert_raises(ValueError, griddata, x, y, xi1, + method=method) + assert_raises(ValueError, griddata, x, y, xi3, + method=method) + + +class TestNearestNDInterpolator: + def test_nearest_options(self): + # smoke test that NearestNDInterpolator accept cKDTree options + npts, nd = 4, 3 + x = np.arange(npts*nd).reshape((npts, nd)) + y = np.arange(npts) + nndi = NearestNDInterpolator(x, y) + + opts = {'balanced_tree': False, 'compact_nodes': False} + nndi_o = NearestNDInterpolator(x, y, tree_options=opts) + xp_assert_close(nndi(x), nndi_o(x), atol=1e-14) + + def test_nearest_list_argument(self): + nd = np.array([[0, 0, 0, 0, 1, 0, 1], + [0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 1, 2]]) + d = nd[:, 3:] + + # z is np.array + NI = NearestNDInterpolator((d[0], d[1]), d[2]) + xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0]) + + # z is list + NI = NearestNDInterpolator((d[0], d[1]), list(d[2])) + xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0]) + + def test_nearest_query_options(self): + nd = np.array([[0, 0.5, 0, 1], + [0, 0, 0.5, 1], + [0, 1, 1, 2]]) + delta = 0.1 + query_points = [0 + delta, 1 + delta], [0 + delta, 1 + delta] + + # case 1 - query max_dist is smaller than + # the query points' nearest distance to nd. + NI = NearestNDInterpolator((nd[0], nd[1]), nd[2]) + distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7 + xp_assert_equal(NI(query_points, distance_upper_bound=distance_upper_bound), + [np.nan, np.nan]) + + # case 2 - query p is inf, will return [0, 2] + distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7 + p = np.inf + xp_assert_equal( + NI(query_points, distance_upper_bound=distance_upper_bound, p=p), + [0.0, 2.0] + ) + + # case 3 - query max_dist is larger, so should return non np.nan + distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) + 1e-7 + xp_assert_equal( + NI(query_points, distance_upper_bound=distance_upper_bound), + [0.0, 2.0] + ) + + def test_nearest_query_valid_inputs(self): + nd = np.array([[0, 1, 0, 1], + [0, 0, 1, 1], + [0, 1, 1, 2]]) + NI = NearestNDInterpolator((nd[0], nd[1]), nd[2]) + with assert_raises(TypeError): + NI([0.5, 0.5], query_options="not a dictionary") + + @pytest.mark.thread_unsafe + def test_concurrency(self): + npts, nd = 50, 3 + x = np.arange(npts * nd).reshape((npts, nd)) + y = np.arange(npts) + nndi = NearestNDInterpolator(x, y) + + def worker_fn(_, spl): + spl(x) + + _run_concurrent_barrier(10, worker_fn, nndi) + + +class TestNDInterpolators: + @parametrize_interpolators + def test_broadcastable_input(self, interpolator): + # input data + rng = np.random.RandomState(0) + x = rng.random(10) + y = rng.random(10) + z = np.hypot(x, y) + + # x-y grid for interpolation + X = np.linspace(min(x), max(x)) + Y = np.linspace(min(y), max(y)) + X, Y = np.meshgrid(X, Y) + XY = np.vstack((X.ravel(), Y.ravel())).T + interp = interpolator(list(zip(x, y)), z) + # single array input + interp_points0 = interp(XY) + # tuple input + interp_points1 = interp((X, Y)) + interp_points2 = interp((X, 0.0)) + # broadcastable input + interp_points3 = interp(X, Y) + interp_points4 = interp(X, 0.0) + + assert (interp_points0.size == + interp_points1.size == + interp_points2.size == + interp_points3.size == + interp_points4.size) + + @parametrize_interpolators + def test_read_only(self, interpolator): + # input data + rng = np.random.RandomState(0) + xy = rng.random((10, 2)) + x, y = xy[:, 0], xy[:, 1] + z = np.hypot(x, y) + + # interpolation points + XY = rng.random((50, 2)) + + xy.setflags(write=False) + z.setflags(write=False) + XY.setflags(write=False) + + interp = interpolator(xy, z) + interp(XY) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py new file mode 100644 index 0000000000000000000000000000000000000000..119b7d1c5667368b284fbf6458174ea14e71957a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py @@ -0,0 +1,107 @@ +import numpy as np +from scipy.interpolate import pade +from scipy._lib._array_api import ( + xp_assert_equal, assert_array_almost_equal +) + +def test_pade_trivial(): + nump, denomp = pade([1.0], 0) + xp_assert_equal(nump.c, np.asarray([1.0])) + xp_assert_equal(denomp.c, np.asarray([1.0])) + + nump, denomp = pade([1.0], 0, 0) + xp_assert_equal(nump.c, np.asarray([1.0])) + xp_assert_equal(denomp.c, np.asarray([1.0])) + + +def test_pade_4term_exp(): + # First four Taylor coefficients of exp(x). + # Unlike poly1d, the first array element is the zero-order term. + an = [1.0, 1.0, 0.5, 1.0/6] + + nump, denomp = pade(an, 0) + assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0]) + assert_array_almost_equal(denomp.c, [1.0]) + + nump, denomp = pade(an, 1) + assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [-1.0/3, 1.0]) + + nump, denomp = pade(an, 2) + assert_array_almost_equal(nump.c, [1.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0]) + + nump, denomp = pade(an, 3) + assert_array_almost_equal(nump.c, [1.0]) + assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0]) + + # Testing inclusion of optional parameter + nump, denomp = pade(an, 0, 3) + assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0]) + assert_array_almost_equal(denomp.c, [1.0]) + + nump, denomp = pade(an, 1, 2) + assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [-1.0/3, 1.0]) + + nump, denomp = pade(an, 2, 1) + assert_array_almost_equal(nump.c, [1.0/3, 1.0]) + assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0]) + + nump, denomp = pade(an, 3, 0) + assert_array_almost_equal(nump.c, [1.0]) + assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0]) + + # Testing reducing array. + nump, denomp = pade(an, 0, 2) + assert_array_almost_equal(nump.c, [0.5, 1.0, 1.0]) + assert_array_almost_equal(denomp.c, [1.0]) + + nump, denomp = pade(an, 1, 1) + assert_array_almost_equal(nump.c, [1.0/2, 1.0]) + assert_array_almost_equal(denomp.c, [-1.0/2, 1.0]) + + nump, denomp = pade(an, 2, 0) + assert_array_almost_equal(nump.c, [1.0]) + assert_array_almost_equal(denomp.c, [1.0/2, -1.0, 1.0]) + + +def test_pade_ints(): + # Simple test sequences (one of ints, one of floats). + an_int = [1, 2, 3, 4] + an_flt = [1.0, 2.0, 3.0, 4.0] + + # Make sure integer arrays give the same result as float arrays with same values. + for i in range(0, len(an_int)): + for j in range(0, len(an_int) - i): + + # Create float and int pade approximation for given order. + nump_int, denomp_int = pade(an_int, i, j) + nump_flt, denomp_flt = pade(an_flt, i, j) + + # Check that they are the same. + xp_assert_equal(nump_int.c, nump_flt.c) + xp_assert_equal(denomp_int.c, denomp_flt.c) + + +def test_pade_complex(): + # Test sequence with known solutions - see page 6 of 10.1109/PESGM.2012.6344759. + # Variable x is parameter - these tests will work with any complex number. + x = 0.2 + 0.6j + an = [1.0, x, -x*x.conjugate(), x.conjugate()*(x**2) + x*(x.conjugate()**2), + -(x**3)*x.conjugate() - 3*(x*x.conjugate())**2 - x*(x.conjugate()**3)] + + nump, denomp = pade(an, 1, 1) + assert_array_almost_equal(nump.c, [x + x.conjugate(), 1.0]) + assert_array_almost_equal(denomp.c, [x.conjugate(), 1.0]) + + nump, denomp = pade(an, 1, 2) + assert_array_almost_equal(nump.c, [x**2, 2*x + x.conjugate(), 1.0]) + assert_array_almost_equal(denomp.c, [x + x.conjugate(), 1.0]) + + nump, denomp = pade(an, 2, 2) + assert_array_almost_equal( + nump.c, + [x**2 + x*x.conjugate() + x.conjugate()**2, 2*(x + x.conjugate()), 1.0] + ) + assert_array_almost_equal(denomp.c, [x.conjugate()**2, x + 2*x.conjugate(), 1.0]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py new file mode 100644 index 0000000000000000000000000000000000000000..e3e6cb7894ea344289c12b522b45c5e0f22748e6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py @@ -0,0 +1,972 @@ +import warnings +import io +import numpy as np + +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_array_almost_equal, assert_almost_equal +) +from pytest import raises as assert_raises +import pytest + +from scipy.interpolate import ( + KroghInterpolator, krogh_interpolate, + BarycentricInterpolator, barycentric_interpolate, + approximate_taylor_polynomial, CubicHermiteSpline, pchip, + PchipInterpolator, pchip_interpolate, Akima1DInterpolator, CubicSpline, + make_interp_spline) +from scipy._lib._testutils import _run_concurrent_barrier + + +def check_shape(interpolator_cls, x_shape, y_shape, deriv_shape=None, axis=0, + extra_args=None): + if extra_args is None: + extra_args = {} + rng = np.random.RandomState(1234) + + x = [-1, 0, 1, 2, 3, 4] + s = list(range(1, len(y_shape)+1)) + s.insert(axis % (len(y_shape)+1), 0) + y = rng.rand(*((6,) + y_shape)).transpose(s) + + xi = np.zeros(x_shape) + if interpolator_cls is CubicHermiteSpline: + dydx = rng.rand(*((6,) + y_shape)).transpose(s) + yi = interpolator_cls(x, y, dydx, axis=axis, **extra_args)(xi) + else: + yi = interpolator_cls(x, y, axis=axis, **extra_args)(xi) + + target_shape = ((deriv_shape or ()) + y.shape[:axis] + + x_shape + y.shape[axis:][1:]) + assert yi.shape == target_shape + + # check it works also with lists + if x_shape and y.size > 0: + if interpolator_cls is CubicHermiteSpline: + interpolator_cls(list(x), list(y), list(dydx), axis=axis, + **extra_args)(list(xi)) + else: + interpolator_cls(list(x), list(y), axis=axis, + **extra_args)(list(xi)) + + # check also values + if xi.size > 0 and deriv_shape is None: + bs_shape = y.shape[:axis] + (1,)*len(x_shape) + y.shape[axis:][1:] + yv = y[((slice(None,),)*(axis % y.ndim)) + (1,)] + yv = yv.reshape(bs_shape) + + yi, y = np.broadcast_arrays(yi, yv) + xp_assert_close(yi, y) + + +SHAPES = [(), (0,), (1,), (6, 2, 5)] + + +def test_shapes(): + + def spl_interp(x, y, axis): + return make_interp_spline(x, y, axis=axis) + + for ip in [KroghInterpolator, BarycentricInterpolator, CubicHermiteSpline, + pchip, Akima1DInterpolator, CubicSpline, spl_interp]: + for s1 in SHAPES: + for s2 in SHAPES: + for axis in range(-len(s2), len(s2)): + if ip != CubicSpline: + check_shape(ip, s1, s2, None, axis) + else: + for bc in ['natural', 'clamped']: + extra = {'bc_type': bc} + check_shape(ip, s1, s2, None, axis, extra) + +def test_derivs_shapes(): + for ip in [KroghInterpolator, BarycentricInterpolator]: + def interpolator_derivs(x, y, axis=0): + return ip(x, y, axis).derivatives + + for s1 in SHAPES: + for s2 in SHAPES: + for axis in range(-len(s2), len(s2)): + check_shape(interpolator_derivs, s1, s2, (6,), axis) + + +def test_deriv_shapes(): + def krogh_deriv(x, y, axis=0): + return KroghInterpolator(x, y, axis).derivative + + def bary_deriv(x, y, axis=0): + return BarycentricInterpolator(x, y, axis).derivative + + def pchip_deriv(x, y, axis=0): + return pchip(x, y, axis).derivative() + + def pchip_deriv2(x, y, axis=0): + return pchip(x, y, axis).derivative(2) + + def pchip_antideriv(x, y, axis=0): + return pchip(x, y, axis).antiderivative() + + def pchip_antideriv2(x, y, axis=0): + return pchip(x, y, axis).antiderivative(2) + + def pchip_deriv_inplace(x, y, axis=0): + class P(PchipInterpolator): + def __call__(self, x): + return PchipInterpolator.__call__(self, x, 1) + pass + return P(x, y, axis) + + def akima_deriv(x, y, axis=0): + return Akima1DInterpolator(x, y, axis).derivative() + + def akima_antideriv(x, y, axis=0): + return Akima1DInterpolator(x, y, axis).antiderivative() + + def cspline_deriv(x, y, axis=0): + return CubicSpline(x, y, axis).derivative() + + def cspline_antideriv(x, y, axis=0): + return CubicSpline(x, y, axis).antiderivative() + + def bspl_deriv(x, y, axis=0): + return make_interp_spline(x, y, axis=axis).derivative() + + def bspl_antideriv(x, y, axis=0): + return make_interp_spline(x, y, axis=axis).antiderivative() + + for ip in [krogh_deriv, bary_deriv, pchip_deriv, pchip_deriv2, pchip_deriv_inplace, + pchip_antideriv, pchip_antideriv2, akima_deriv, akima_antideriv, + cspline_deriv, cspline_antideriv, bspl_deriv, bspl_antideriv]: + for s1 in SHAPES: + for s2 in SHAPES: + for axis in range(-len(s2), len(s2)): + check_shape(ip, s1, s2, (), axis) + + +def test_complex(): + x = [1, 2, 3, 4] + y = [1, 2, 1j, 3] + + for ip in [KroghInterpolator, BarycentricInterpolator, CubicSpline]: + p = ip(x, y) + xp_assert_close(p(x), np.asarray(y)) + + dydx = [0, -1j, 2, 3j] + p = CubicHermiteSpline(x, y, dydx) + xp_assert_close(p(x), np.asarray(y)) + xp_assert_close(p(x, 1), np.asarray(dydx)) + + +class TestKrogh: + def setup_method(self): + self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2]) + self.test_xs = np.linspace(-1,1,100) + self.xs = np.linspace(-1,1,5) + self.ys = self.true_poly(self.xs) + + def test_lagrange(self): + P = KroghInterpolator(self.xs,self.ys) + assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs)) + + def test_scalar(self): + P = KroghInterpolator(self.xs,self.ys) + assert_almost_equal(self.true_poly(7), P(7), check_0d=False) + assert_almost_equal(self.true_poly(np.array(7)), P(np.array(7)), check_0d=False) + + def test_derivatives(self): + P = KroghInterpolator(self.xs,self.ys) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + assert_almost_equal(self.true_poly.deriv(i)(self.test_xs), + D[i]) + + def test_low_derivatives(self): + P = KroghInterpolator(self.xs,self.ys) + D = P.derivatives(self.test_xs,len(self.xs)+2) + for i in range(D.shape[0]): + assert_almost_equal(self.true_poly.deriv(i)(self.test_xs), + D[i]) + + def test_derivative(self): + P = KroghInterpolator(self.xs,self.ys) + m = 10 + r = P.derivatives(self.test_xs,m) + for i in range(m): + assert_almost_equal(P.derivative(self.test_xs,i),r[i]) + + def test_high_derivative(self): + P = KroghInterpolator(self.xs,self.ys) + for i in range(len(self.xs), 2*len(self.xs)): + assert_almost_equal(P.derivative(self.test_xs,i), + np.zeros(len(self.test_xs))) + + def test_ndim_derivatives(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = KroghInterpolator(self.xs, ys, axis=0) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + xp_assert_close(D[i], + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1)) + + def test_ndim_derivative(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = KroghInterpolator(self.xs, ys, axis=0) + for i in range(P.n): + xp_assert_close(P.derivative(self.test_xs, i), + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1)) + + def test_hermite(self): + P = KroghInterpolator(self.xs,self.ys) + assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs)) + + def test_vector(self): + xs = [0, 1, 2] + ys = np.array([[0,1],[1,0],[2,1]]) + P = KroghInterpolator(xs,ys) + Pi = [KroghInterpolator(xs,ys[:,i]) for i in range(ys.shape[1])] + test_xs = np.linspace(-1,3,100) + assert_almost_equal(P(test_xs), + np.asarray([p(test_xs) for p in Pi]).T) + assert_almost_equal(P.derivatives(test_xs), + np.transpose(np.asarray([p.derivatives(test_xs) for p in Pi]), + (1,2,0))) + + def test_empty(self): + P = KroghInterpolator(self.xs,self.ys) + xp_assert_equal(P([]), np.asarray([])) + + def test_shapes_scalarvalue(self): + P = KroghInterpolator(self.xs,self.ys) + assert np.shape(P(0)) == () + assert np.shape(P(np.array(0))) == () + assert np.shape(P([0])) == (1,) + assert np.shape(P([0,1])) == (2,) + + def test_shapes_scalarvalue_derivative(self): + P = KroghInterpolator(self.xs,self.ys) + n = P.n + assert np.shape(P.derivatives(0)) == (n,) + assert np.shape(P.derivatives(np.array(0))) == (n,) + assert np.shape(P.derivatives([0])) == (n, 1) + assert np.shape(P.derivatives([0, 1])) == (n, 2) + + def test_shapes_vectorvalue(self): + P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3))) + assert np.shape(P(0)) == (3,) + assert np.shape(P([0])) == (1, 3) + assert np.shape(P([0, 1])) == (2, 3) + + def test_shapes_1d_vectorvalue(self): + P = KroghInterpolator(self.xs,np.outer(self.ys,[1])) + assert np.shape(P(0)) == (1,) + assert np.shape(P([0])) == (1, 1) + assert np.shape(P([0,1])) == (2, 1) + + def test_shapes_vectorvalue_derivative(self): + P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3))) + n = P.n + assert np.shape(P.derivatives(0)) == (n, 3) + assert np.shape(P.derivatives([0])) == (n, 1, 3) + assert np.shape(P.derivatives([0,1])) == (n, 2, 3) + + def test_wrapper(self): + P = KroghInterpolator(self.xs, self.ys) + ki = krogh_interpolate + assert_almost_equal(P(self.test_xs), ki(self.xs, self.ys, self.test_xs)) + assert_almost_equal(P.derivative(self.test_xs, 2), + ki(self.xs, self.ys, self.test_xs, der=2)) + assert_almost_equal(P.derivatives(self.test_xs, 2), + ki(self.xs, self.ys, self.test_xs, der=[0, 1])) + + def test_int_inputs(self): + # Check input args are cast correctly to floats, gh-3669 + x = [0, 234, 468, 702, 936, 1170, 1404, 2340, 3744, 6084, 8424, + 13104, 60000] + offset_cdf = np.array([-0.95, -0.86114777, -0.8147762, -0.64072425, + -0.48002351, -0.34925329, -0.26503107, + -0.13148093, -0.12988833, -0.12979296, + -0.12973574, -0.08582937, 0.05]) + f = KroghInterpolator(x, offset_cdf) + + xp_assert_close(abs((f(x) - offset_cdf) / f.derivative(x, 1)), + np.zeros_like(offset_cdf), atol=1e-10) + + def test_derivatives_complex(self): + # regression test for gh-7381: krogh.derivatives(0) fails complex y + x, y = np.array([-1, -1, 0, 1, 1]), np.array([1, 1.0j, 0, -1, 1.0j]) + func = KroghInterpolator(x, y) + cmplx = func.derivatives(0) + + cmplx2 = (KroghInterpolator(x, y.real).derivatives(0) + + 1j*KroghInterpolator(x, y.imag).derivatives(0)) + xp_assert_close(cmplx, cmplx2, atol=1e-15) + + @pytest.mark.thread_unsafe + def test_high_degree_warning(self): + with pytest.warns(UserWarning, match="40 degrees provided,"): + KroghInterpolator(np.arange(40), np.ones(40)) + + @pytest.mark.thread_unsafe + def test_concurrency(self): + P = KroghInterpolator(self.xs, self.ys) + + def worker_fn(_, interp): + interp(self.xs) + + _run_concurrent_barrier(10, worker_fn, P) + + +class TestTaylor: + def test_exponential(self): + degree = 5 + p = approximate_taylor_polynomial(np.exp, 0, degree, 1, 15) + for i in range(degree+1): + assert_almost_equal(p(0),1) + p = p.deriv() + assert_almost_equal(p(0),0) + + +class TestBarycentric: + def setup_method(self): + self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2]) + self.test_xs = np.linspace(-1, 1, 100) + self.xs = np.linspace(-1, 1, 5) + self.ys = self.true_poly(self.xs) + + def test_lagrange(self): + # Ensure backwards compatible post SPEC7 + P = BarycentricInterpolator(self.xs, self.ys, random_state=1) + xp_assert_close(P(self.test_xs), self.true_poly(self.test_xs)) + + def test_scalar(self): + P = BarycentricInterpolator(self.xs, self.ys, rng=1) + xp_assert_close(P(7), self.true_poly(7), check_0d=False) + xp_assert_close(P(np.array(7)), self.true_poly(np.array(7)), check_0d=False) + + def test_derivatives(self): + P = BarycentricInterpolator(self.xs, self.ys) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + xp_assert_close(self.true_poly.deriv(i)(self.test_xs), D[i]) + + def test_low_derivatives(self): + P = BarycentricInterpolator(self.xs, self.ys) + D = P.derivatives(self.test_xs, len(self.xs)+2) + for i in range(D.shape[0]): + xp_assert_close(self.true_poly.deriv(i)(self.test_xs), + D[i], + atol=1e-12) + + def test_derivative(self): + P = BarycentricInterpolator(self.xs, self.ys) + m = 10 + r = P.derivatives(self.test_xs, m) + for i in range(m): + xp_assert_close(P.derivative(self.test_xs, i), r[i]) + + def test_high_derivative(self): + P = BarycentricInterpolator(self.xs, self.ys) + for i in range(len(self.xs), 5*len(self.xs)): + xp_assert_close(P.derivative(self.test_xs, i), + np.zeros(len(self.test_xs))) + + def test_ndim_derivatives(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = BarycentricInterpolator(self.xs, ys, axis=0) + D = P.derivatives(self.test_xs) + for i in range(D.shape[0]): + xp_assert_close(D[i], + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1), + atol=1e-12) + + def test_ndim_derivative(self): + poly1 = self.true_poly + poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) + poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) + ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) + + P = BarycentricInterpolator(self.xs, ys, axis=0) + for i in range(P.n): + xp_assert_close(P.derivative(self.test_xs, i), + np.stack((poly1.deriv(i)(self.test_xs), + poly2.deriv(i)(self.test_xs), + poly3.deriv(i)(self.test_xs)), + axis=-1), + atol=1e-12) + + def test_delayed(self): + P = BarycentricInterpolator(self.xs) + P.set_yi(self.ys) + assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs)) + + def test_append(self): + P = BarycentricInterpolator(self.xs[:3], self.ys[:3]) + P.add_xi(self.xs[3:], self.ys[3:]) + assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs)) + + def test_vector(self): + xs = [0, 1, 2] + ys = np.array([[0, 1], [1, 0], [2, 1]]) + BI = BarycentricInterpolator + P = BI(xs, ys) + Pi = [BI(xs, ys[:, i]) for i in range(ys.shape[1])] + test_xs = np.linspace(-1, 3, 100) + assert_almost_equal(P(test_xs), + np.asarray([p(test_xs) for p in Pi]).T) + + def test_shapes_scalarvalue(self): + P = BarycentricInterpolator(self.xs, self.ys) + assert np.shape(P(0)) == () + assert np.shape(P(np.array(0))) == () + assert np.shape(P([0])) == (1,) + assert np.shape(P([0, 1])) == (2,) + + def test_shapes_scalarvalue_derivative(self): + P = BarycentricInterpolator(self.xs,self.ys) + n = P.n + assert np.shape(P.derivatives(0)) == (n,) + assert np.shape(P.derivatives(np.array(0))) == (n,) + assert np.shape(P.derivatives([0])) == (n,1) + assert np.shape(P.derivatives([0,1])) == (n,2) + + def test_shapes_vectorvalue(self): + P = BarycentricInterpolator(self.xs, np.outer(self.ys, np.arange(3))) + assert np.shape(P(0)) == (3,) + assert np.shape(P([0])) == (1, 3) + assert np.shape(P([0, 1])) == (2, 3) + + def test_shapes_1d_vectorvalue(self): + P = BarycentricInterpolator(self.xs, np.outer(self.ys, [1])) + assert np.shape(P(0)) == (1,) + assert np.shape(P([0])) == (1, 1) + assert np.shape(P([0, 1])) == (2, 1) + + def test_shapes_vectorvalue_derivative(self): + P = BarycentricInterpolator(self.xs,np.outer(self.ys,np.arange(3))) + n = P.n + assert np.shape(P.derivatives(0)) == (n, 3) + assert np.shape(P.derivatives([0])) == (n, 1, 3) + assert np.shape(P.derivatives([0, 1])) == (n, 2, 3) + + def test_wrapper(self): + P = BarycentricInterpolator(self.xs, self.ys, rng=1) + bi = barycentric_interpolate + xp_assert_close(P(self.test_xs), bi(self.xs, self.ys, self.test_xs, rng=1)) + xp_assert_close(P.derivative(self.test_xs, 2), + bi(self.xs, self.ys, self.test_xs, der=2, rng=1)) + xp_assert_close(P.derivatives(self.test_xs, 2), + bi(self.xs, self.ys, self.test_xs, der=[0, 1], rng=1)) + + def test_int_input(self): + x = 1000 * np.arange(1, 11) # np.prod(x[-1] - x[:-1]) overflows + y = np.arange(1, 11) + value = barycentric_interpolate(x, y, 1000 * 9.5) + assert_almost_equal(value, np.asarray(9.5)) + + def test_large_chebyshev(self): + # The weights for Chebyshev points of the second kind have analytically + # solvable weights. Naive calculation of barycentric weights will fail + # for large N because of numerical underflow and overflow. We test + # correctness for large N against analytical Chebyshev weights. + + # Without capacity scaling or permutation, n=800 fails, + # With just capacity scaling, n=1097 fails + # With both capacity scaling and random permutation, n=30000 succeeds + n = 1100 + j = np.arange(n + 1).astype(np.float64) + x = np.cos(j * np.pi / n) + + # See page 506 of Berrut and Trefethen 2004 for this formula + w = (-1) ** j + w[0] *= 0.5 + w[-1] *= 0.5 + + P = BarycentricInterpolator(x) + + # It's okay to have a constant scaling factor in the weights because it + # cancels out in the evaluation of the polynomial. + factor = P.wi[0] + assert_almost_equal(P.wi / (2 * factor), w) + + def test_warning(self): + # Test if the divide-by-zero warning is properly ignored when computing + # interpolated values equals to interpolation points + P = BarycentricInterpolator([0, 1], [1, 2]) + with np.errstate(divide='raise'): + yi = P(P.xi) + + # Check if the interpolated values match the input values + # at the nodes + assert_almost_equal(yi, P.yi.ravel()) + + @pytest.mark.thread_unsafe + def test_repeated_node(self): + # check that a repeated node raises a ValueError + # (computing the weights requires division by xi[i] - xi[j]) + xis = np.array([0.1, 0.5, 0.9, 0.5]) + ys = np.array([1, 2, 3, 4]) + with pytest.raises(ValueError, + match="Interpolation points xi must be distinct."): + BarycentricInterpolator(xis, ys) + + @pytest.mark.thread_unsafe + def test_concurrency(self): + P = BarycentricInterpolator(self.xs, self.ys) + + def worker_fn(_, interp): + interp(self.xs) + + _run_concurrent_barrier(10, worker_fn, P) + + +class TestPCHIP: + def _make_random(self, npts=20): + rng = np.random.RandomState(1234) + xi = np.sort(rng.random(npts)) + yi = rng.random(npts) + return pchip(xi, yi), xi, yi + + def test_overshoot(self): + # PCHIP should not overshoot + p, xi, yi = self._make_random() + for i in range(len(xi)-1): + x1, x2 = xi[i], xi[i+1] + y1, y2 = yi[i], yi[i+1] + if y1 > y2: + y1, y2 = y2, y1 + xp = np.linspace(x1, x2, 10) + yp = p(xp) + assert ((y1 <= yp + 1e-15) & (yp <= y2 + 1e-15)).all() + + def test_monotone(self): + # PCHIP should preserve monotonicty + p, xi, yi = self._make_random() + for i in range(len(xi)-1): + x1, x2 = xi[i], xi[i+1] + y1, y2 = yi[i], yi[i+1] + xp = np.linspace(x1, x2, 10) + yp = p(xp) + assert ((y2-y1) * (yp[1:] - yp[:1]) > 0).all() + + def test_cast(self): + # regression test for integer input data, see gh-3453 + data = np.array([[0, 4, 12, 27, 47, 60, 79, 87, 99, 100], + [-33, -33, -19, -2, 12, 26, 38, 45, 53, 55]]) + xx = np.arange(100) + curve = pchip(data[0], data[1])(xx) + + data1 = data * 1.0 + curve1 = pchip(data1[0], data1[1])(xx) + + xp_assert_close(curve, curve1, atol=1e-14, rtol=1e-14) + + def test_nag(self): + # Example from NAG C implementation, + # http://nag.com/numeric/cl/nagdoc_cl25/html/e01/e01bec.html + # suggested in gh-5326 as a smoke test for the way the derivatives + # are computed (see also gh-3453) + dataStr = ''' + 7.99 0.00000E+0 + 8.09 0.27643E-4 + 8.19 0.43750E-1 + 8.70 0.16918E+0 + 9.20 0.46943E+0 + 10.00 0.94374E+0 + 12.00 0.99864E+0 + 15.00 0.99992E+0 + 20.00 0.99999E+0 + ''' + data = np.loadtxt(io.StringIO(dataStr)) + pch = pchip(data[:,0], data[:,1]) + + resultStr = ''' + 7.9900 0.0000 + 9.1910 0.4640 + 10.3920 0.9645 + 11.5930 0.9965 + 12.7940 0.9992 + 13.9950 0.9998 + 15.1960 0.9999 + 16.3970 1.0000 + 17.5980 1.0000 + 18.7990 1.0000 + 20.0000 1.0000 + ''' + result = np.loadtxt(io.StringIO(resultStr)) + xp_assert_close(result[:,1], pch(result[:,0]), rtol=0., atol=5e-5) + + def test_endslopes(self): + # this is a smoke test for gh-3453: PCHIP interpolator should not + # set edge slopes to zero if the data do not suggest zero edge derivatives + x = np.array([0.0, 0.1, 0.25, 0.35]) + y1 = np.array([279.35, 0.5e3, 1.0e3, 2.5e3]) + y2 = np.array([279.35, 2.5e3, 1.50e3, 1.0e3]) + for pp in (pchip(x, y1), pchip(x, y2)): + for t in (x[0], x[-1]): + assert pp(t, 1) != 0 + + @pytest.mark.thread_unsafe + def test_all_zeros(self): + x = np.arange(10) + y = np.zeros_like(x) + + # this should work and not generate any warnings + with warnings.catch_warnings(): + warnings.filterwarnings('error') + pch = pchip(x, y) + + xx = np.linspace(0, 9, 101) + assert all(pch(xx) == 0.) + + def test_two_points(self): + # regression test for gh-6222: pchip([0, 1], [0, 1]) fails because + # it tries to use a three-point scheme to estimate edge derivatives, + # while there are only two points available. + # Instead, it should construct a linear interpolator. + x = np.linspace(0, 1, 11) + p = pchip([0, 1], [0, 2]) + xp_assert_close(p(x), 2*x, atol=1e-15) + + def test_pchip_interpolate(self): + assert_array_almost_equal( + pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=1), + np.asarray([1.])) + + assert_array_almost_equal( + pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=0), + np.asarray([3.5])) + + assert_array_almost_equal( + np.asarray(pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=[0, 1])), + np.asarray([[3.5], [1]])) + + def test_roots(self): + # regression test for gh-6357: .roots method should work + p = pchip([0, 1], [-1, 1]) + r = p.roots() + xp_assert_close(r, np.asarray([0.5])) + + +class TestCubicSpline: + @staticmethod + def check_correctness(S, bc_start='not-a-knot', bc_end='not-a-knot', + tol=1e-14): + """Check that spline coefficients satisfy the continuity and boundary + conditions.""" + x = S.x + c = S.c + dx = np.diff(x) + dx = dx.reshape([dx.shape[0]] + [1] * (c.ndim - 2)) + dxi = dx[:-1] + + # Check C2 continuity. + xp_assert_close(c[3, 1:], c[0, :-1] * dxi**3 + c[1, :-1] * dxi**2 + + c[2, :-1] * dxi + c[3, :-1], rtol=tol, atol=tol) + xp_assert_close(c[2, 1:], 3 * c[0, :-1] * dxi**2 + + 2 * c[1, :-1] * dxi + c[2, :-1], rtol=tol, atol=tol) + xp_assert_close(c[1, 1:], 3 * c[0, :-1] * dxi + c[1, :-1], + rtol=tol, atol=tol) + + # Check that we found a parabola, the third derivative is 0. + if x.size == 3 and bc_start == 'not-a-knot' and bc_end == 'not-a-knot': + xp_assert_close(c[0], np.zeros_like(c[0]), rtol=tol, atol=tol) + return + + # Check periodic boundary conditions. + if bc_start == 'periodic': + xp_assert_close(S(x[0], 0), S(x[-1], 0), rtol=tol, atol=tol) + xp_assert_close(S(x[0], 1), S(x[-1], 1), rtol=tol, atol=tol) + xp_assert_close(S(x[0], 2), S(x[-1], 2), rtol=tol, atol=tol) + return + + # Check other boundary conditions. + if bc_start == 'not-a-knot': + if x.size == 2: + slope = (S(x[1]) - S(x[0])) / dx[0] + slope = np.asarray(slope) + xp_assert_close(S(x[0], 1), slope, rtol=tol, atol=tol) + else: + xp_assert_close(c[0, 0], c[0, 1], rtol=tol, atol=tol) + elif bc_start == 'clamped': + xp_assert_close( + S(x[0], 1), np.zeros_like(S(x[0], 1)), rtol=tol, atol=tol) + elif bc_start == 'natural': + xp_assert_close( + S(x[0], 2), np.zeros_like(S(x[0], 2)), rtol=tol, atol=tol) + else: + order, value = bc_start + xp_assert_close(S(x[0], order), np.asarray(value), rtol=tol, atol=tol) + + if bc_end == 'not-a-knot': + if x.size == 2: + slope = (S(x[1]) - S(x[0])) / dx[0] + slope = np.asarray(slope) + xp_assert_close(S(x[1], 1), slope, rtol=tol, atol=tol) + else: + xp_assert_close(c[0, -1], c[0, -2], rtol=tol, atol=tol) + elif bc_end == 'clamped': + xp_assert_close(S(x[-1], 1), np.zeros_like(S(x[-1], 1)), + rtol=tol, atol=tol) + elif bc_end == 'natural': + xp_assert_close(S(x[-1], 2), np.zeros_like(S(x[-1], 2)), + rtol=2*tol, atol=2*tol) + else: + order, value = bc_end + xp_assert_close(S(x[-1], order), np.asarray(value), rtol=tol, atol=tol) + + def check_all_bc(self, x, y, axis): + deriv_shape = list(y.shape) + del deriv_shape[axis] + first_deriv = np.empty(deriv_shape) + first_deriv.fill(2) + second_deriv = np.empty(deriv_shape) + second_deriv.fill(-1) + bc_all = [ + 'not-a-knot', + 'natural', + 'clamped', + (1, first_deriv), + (2, second_deriv) + ] + for bc in bc_all[:3]: + S = CubicSpline(x, y, axis=axis, bc_type=bc) + self.check_correctness(S, bc, bc) + + for bc_start in bc_all: + for bc_end in bc_all: + S = CubicSpline(x, y, axis=axis, bc_type=(bc_start, bc_end)) + self.check_correctness(S, bc_start, bc_end, tol=2e-14) + + def test_general(self): + x = np.array([-1, 0, 0.5, 2, 4, 4.5, 5.5, 9]) + y = np.array([0, -0.5, 2, 3, 2.5, 1, 1, 0.5]) + for n in [2, 3, x.size]: + self.check_all_bc(x[:n], y[:n], 0) + + Y = np.empty((2, n, 2)) + Y[0, :, 0] = y[:n] + Y[0, :, 1] = y[:n] - 1 + Y[1, :, 0] = y[:n] + 2 + Y[1, :, 1] = y[:n] + 3 + self.check_all_bc(x[:n], Y, 1) + + def test_periodic(self): + for n in [2, 3, 5]: + x = np.linspace(0, 2 * np.pi, n) + y = np.cos(x) + S = CubicSpline(x, y, bc_type='periodic') + self.check_correctness(S, 'periodic', 'periodic') + + Y = np.empty((2, n, 2)) + Y[0, :, 0] = y + Y[0, :, 1] = y + 2 + Y[1, :, 0] = y - 1 + Y[1, :, 1] = y + 5 + S = CubicSpline(x, Y, axis=1, bc_type='periodic') + self.check_correctness(S, 'periodic', 'periodic') + + def test_periodic_eval(self): + x = np.linspace(0, 2 * np.pi, 10) + y = np.cos(x) + S = CubicSpline(x, y, bc_type='periodic') + assert_almost_equal(S(1), S(1 + 2 * np.pi), decimal=15) + + def test_second_derivative_continuity_gh_11758(self): + # gh-11758: C2 continuity fail + x = np.array([0.9, 1.3, 1.9, 2.1, 2.6, 3.0, 3.9, 4.4, 4.7, 5.0, 6.0, + 7.0, 8.0, 9.2, 10.5, 11.3, 11.6, 12.0, 12.6, 13.0, 13.3]) + y = np.array([1.3, 1.5, 1.85, 2.1, 2.6, 2.7, 2.4, 2.15, 2.05, 2.1, + 2.25, 2.3, 2.25, 1.95, 1.4, 0.9, 0.7, 0.6, 0.5, 0.4, 1.3]) + S = CubicSpline(x, y, bc_type='periodic', extrapolate='periodic') + self.check_correctness(S, 'periodic', 'periodic') + + def test_three_points(self): + # gh-11758: Fails computing a_m2_m1 + # In this case, s (first derivatives) could be found manually by solving + # system of 2 linear equations. Due to solution of this system, + # s[i] = (h1m2 + h2m1) / (h1 + h2), where h1 = x[1] - x[0], h2 = x[2] - x[1], + # m1 = (y[1] - y[0]) / h1, m2 = (y[2] - y[1]) / h2 + x = np.array([1.0, 2.75, 3.0]) + y = np.array([1.0, 15.0, 1.0]) + S = CubicSpline(x, y, bc_type='periodic') + self.check_correctness(S, 'periodic', 'periodic') + xp_assert_close(S.derivative(1)(x), np.array([-48.0, -48.0, -48.0])) + + def test_periodic_three_points_multidim(self): + # make sure one multidimensional interpolator does the same as multiple + # one-dimensional interpolators + x = np.array([0.0, 1.0, 3.0]) + y = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]) + S = CubicSpline(x, y, bc_type="periodic") + self.check_correctness(S, 'periodic', 'periodic') + S0 = CubicSpline(x, y[:, 0], bc_type="periodic") + S1 = CubicSpline(x, y[:, 1], bc_type="periodic") + q = np.linspace(0, 2, 5) + xp_assert_close(S(q)[:, 0], S0(q)) + xp_assert_close(S(q)[:, 1], S1(q)) + + def test_dtypes(self): + x = np.array([0, 1, 2, 3], dtype=int) + y = np.array([-5, 2, 3, 1], dtype=int) + S = CubicSpline(x, y) + self.check_correctness(S) + + y = np.array([-1+1j, 0.0, 1-1j, 0.5-1.5j]) + S = CubicSpline(x, y) + self.check_correctness(S) + + S = CubicSpline(x, x ** 3, bc_type=("natural", (1, 2j))) + self.check_correctness(S, "natural", (1, 2j)) + + y = np.array([-5, 2, 3, 1]) + S = CubicSpline(x, y, bc_type=[(1, 2 + 0.5j), (2, 0.5 - 1j)]) + self.check_correctness(S, (1, 2 + 0.5j), (2, 0.5 - 1j)) + + def test_small_dx(self): + rng = np.random.RandomState(0) + x = np.sort(rng.uniform(size=100)) + y = 1e4 + rng.uniform(size=100) + S = CubicSpline(x, y) + self.check_correctness(S, tol=1e-13) + + def test_incorrect_inputs(self): + x = np.array([1, 2, 3, 4]) + y = np.array([1, 2, 3, 4]) + xc = np.array([1 + 1j, 2, 3, 4]) + xn = np.array([np.nan, 2, 3, 4]) + xo = np.array([2, 1, 3, 4]) + yn = np.array([np.nan, 2, 3, 4]) + y3 = [1, 2, 3] + x1 = [1] + y1 = [1] + + assert_raises(ValueError, CubicSpline, xc, y) + assert_raises(ValueError, CubicSpline, xn, y) + assert_raises(ValueError, CubicSpline, x, yn) + assert_raises(ValueError, CubicSpline, xo, y) + assert_raises(ValueError, CubicSpline, x, y3) + assert_raises(ValueError, CubicSpline, x[:, np.newaxis], y) + assert_raises(ValueError, CubicSpline, x1, y1) + + wrong_bc = [('periodic', 'clamped'), + ((2, 0), (3, 10)), + ((1, 0), ), + (0., 0.), + 'not-a-typo'] + + for bc_type in wrong_bc: + assert_raises(ValueError, CubicSpline, x, y, 0, bc_type, True) + + # Shapes mismatch when giving arbitrary derivative values: + Y = np.c_[y, y] + bc1 = ('clamped', (1, 0)) + bc2 = ('clamped', (1, [0, 0, 0])) + bc3 = ('clamped', (1, [[0, 0]])) + assert_raises(ValueError, CubicSpline, x, Y, 0, bc1, True) + assert_raises(ValueError, CubicSpline, x, Y, 0, bc2, True) + assert_raises(ValueError, CubicSpline, x, Y, 0, bc3, True) + + # periodic condition, y[-1] must be equal to y[0]: + assert_raises(ValueError, CubicSpline, x, y, 0, 'periodic', True) + + +def test_CubicHermiteSpline_correctness(): + x = [0, 2, 7] + y = [-1, 2, 3] + dydx = [0, 3, 7] + s = CubicHermiteSpline(x, y, dydx) + xp_assert_close(s(x), y, check_shape=False, check_dtype=False, rtol=1e-15) + xp_assert_close(s(x, 1), dydx, check_shape=False, check_dtype=False, rtol=1e-15) + + +def test_CubicHermiteSpline_error_handling(): + x = [1, 2, 3] + y = [0, 3, 5] + dydx = [1, -1, 2, 3] + assert_raises(ValueError, CubicHermiteSpline, x, y, dydx) + + dydx_with_nan = [1, 0, np.nan] + assert_raises(ValueError, CubicHermiteSpline, x, y, dydx_with_nan) + + +def test_roots_extrapolate_gh_11185(): + x = np.array([0.001, 0.002]) + y = np.array([1.66066935e-06, 1.10410807e-06]) + dy = np.array([-1.60061854, -1.600619]) + p = CubicHermiteSpline(x, y, dy) + + # roots(extrapolate=True) for a polynomial with a single interval + # should return all three real roots + r = p.roots(extrapolate=True) + assert p.c.shape[1] == 1 + assert r.size == 3 + + +class TestZeroSizeArrays: + # regression tests for gh-17241 : CubicSpline et al must not segfault + # when y.size == 0 + # The two methods below are _almost_ the same, but not quite: + # one is for objects which have the `bc_type` argument (CubicSpline) + # and the other one is for those which do not (Pchip, Akima1D) + + @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)), + np.zeros((10, 5, 0))]) + @pytest.mark.parametrize('bc_type', + ['not-a-knot', 'periodic', 'natural', 'clamped']) + @pytest.mark.parametrize('axis', [0, 1, 2]) + @pytest.mark.parametrize('cls', [make_interp_spline, CubicSpline]) + def test_zero_size(self, cls, y, bc_type, axis): + x = np.arange(10) + xval = np.arange(3) + + obj = cls(x, y, bc_type=bc_type) + assert obj(xval).size == 0 + assert obj(xval).shape == xval.shape + y.shape[1:] + + # Also check with an explicit non-default axis + yt = np.moveaxis(y, 0, axis) # (10, 0, 5) --> (0, 10, 5) if axis=1 etc + + obj = cls(x, yt, bc_type=bc_type, axis=axis) + sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:] + assert obj(xval).size == 0 + assert obj(xval).shape == sh + + @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)), + np.zeros((10, 5, 0))]) + @pytest.mark.parametrize('axis', [0, 1, 2]) + @pytest.mark.parametrize('cls', [PchipInterpolator, Akima1DInterpolator]) + def test_zero_size_2(self, cls, y, axis): + x = np.arange(10) + xval = np.arange(3) + + obj = cls(x, y) + assert obj(xval).size == 0 + assert obj(xval).shape == xval.shape + y.shape[1:] + + # Also check with an explicit non-default axis + yt = np.moveaxis(y, 0, axis) # (10, 0, 5) --> (0, 10, 5) if axis=1 etc + + obj = cls(x, yt, axis=axis) + sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:] + assert obj(xval).size == 0 + assert obj(xval).shape == sh diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbf.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbf.py new file mode 100644 index 0000000000000000000000000000000000000000..d824a84a80eda316b680ba4e43d0f418c774af99 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbf.py @@ -0,0 +1,246 @@ +# Created by John Travers, Robert Hetland, 2007 +""" Test functions for rbf module """ + +import numpy as np + +from scipy._lib._array_api import assert_array_almost_equal, assert_almost_equal + +from numpy import linspace, sin, cos, exp, allclose +from scipy.interpolate._rbf import Rbf +from scipy._lib._testutils import _run_concurrent_barrier + +import pytest + + +FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian', + 'cubic', 'quintic', 'thin-plate', 'linear') + + +def check_rbf1d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (1D) + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y, function=function) + yi = rbf(x) + assert_array_almost_equal(y, yi) + assert_almost_equal(rbf(float(x[0])), y[0], check_0d=False) + + +def check_rbf2d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (2D). + rng = np.random.RandomState(1234) + x = rng.rand(50,1)*4-2 + y = rng.rand(50,1)*4-2 + z = x*exp(-x**2-1j*y**2) + rbf = Rbf(x, y, z, epsilon=2, function=function) + zi = rbf(x, y) + zi.shape = x.shape + assert_array_almost_equal(z, zi) + + +def check_rbf3d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (3D). + rng = np.random.RandomState(1234) + x = rng.rand(50, 1)*4 - 2 + y = rng.rand(50, 1)*4 - 2 + z = rng.rand(50, 1)*4 - 2 + d = x*exp(-x**2 - y**2) + rbf = Rbf(x, y, z, d, epsilon=2, function=function) + di = rbf(x, y, z) + di.shape = x.shape + assert_array_almost_equal(di, d) + + +def test_rbf_interpolation(): + for function in FUNCTIONS: + check_rbf1d_interpolation(function) + check_rbf2d_interpolation(function) + check_rbf3d_interpolation(function) + + +def check_2drbf1d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (1D) + x = linspace(0, 10, 9) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, function=function, mode='N-D') + yi = rbf(x) + assert_array_almost_equal(y, yi) + assert_almost_equal(rbf(float(x[0])), y[0]) + + +def check_2drbf2d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (2D). + rng = np.random.RandomState(1234) + x = rng.rand(50, ) * 4 - 2 + y = rng.rand(50, ) * 4 - 2 + z0 = x * exp(-x ** 2 - 1j * y ** 2) + z1 = y * exp(-y ** 2 - 1j * x ** 2) + z = np.vstack([z0, z1]).T + rbf = Rbf(x, y, z, epsilon=2, function=function, mode='N-D') + zi = rbf(x, y) + zi.shape = z.shape + assert_array_almost_equal(z, zi) + + +def check_2drbf3d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (3D). + rng = np.random.RandomState(1234) + x = rng.rand(50, ) * 4 - 2 + y = rng.rand(50, ) * 4 - 2 + z = rng.rand(50, ) * 4 - 2 + d0 = x * exp(-x ** 2 - y ** 2) + d1 = y * exp(-y ** 2 - x ** 2) + d = np.vstack([d0, d1]).T + rbf = Rbf(x, y, z, d, epsilon=2, function=function, mode='N-D') + di = rbf(x, y, z) + di.shape = d.shape + assert_array_almost_equal(di, d) + + +def test_2drbf_interpolation(): + for function in FUNCTIONS: + check_2drbf1d_interpolation(function) + check_2drbf2d_interpolation(function) + check_2drbf3d_interpolation(function) + + +def check_rbf1d_regularity(function, atol): + # Check that the Rbf function approximates a smooth function well away + # from the nodes. + x = linspace(0, 10, 9) + y = sin(x) + rbf = Rbf(x, y, function=function) + xi = linspace(0, 10, 100) + yi = rbf(xi) + msg = f"abs-diff: {abs(yi - sin(xi)).max():f}" + assert allclose(yi, sin(xi), atol=atol), msg + + +def test_rbf_regularity(): + tolerances = { + 'multiquadric': 0.1, + 'inverse multiquadric': 0.15, + 'gaussian': 0.15, + 'cubic': 0.15, + 'quintic': 0.1, + 'thin-plate': 0.1, + 'linear': 0.2 + } + for function in FUNCTIONS: + check_rbf1d_regularity(function, tolerances.get(function, 1e-2)) + + +def check_2drbf1d_regularity(function, atol): + # Check that the 2-D Rbf function approximates a smooth function well away + # from the nodes. + x = linspace(0, 10, 9) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, function=function, mode='N-D') + xi = linspace(0, 10, 100) + yi = rbf(xi) + msg = f"abs-diff: {abs(yi - np.vstack([sin(xi), cos(xi)]).T).max():f}" + assert allclose(yi, np.vstack([sin(xi), cos(xi)]).T, atol=atol), msg + + +def test_2drbf_regularity(): + tolerances = { + 'multiquadric': 0.1, + 'inverse multiquadric': 0.15, + 'gaussian': 0.15, + 'cubic': 0.15, + 'quintic': 0.1, + 'thin-plate': 0.15, + 'linear': 0.2 + } + for function in FUNCTIONS: + check_2drbf1d_regularity(function, tolerances.get(function, 1e-2)) + + +def check_rbf1d_stability(function): + # Check that the Rbf function with default epsilon is not subject + # to overshoot. Regression for issue #4523. + # + # Generate some data (fixed random seed hence deterministic) + rng = np.random.RandomState(1234) + x = np.linspace(0, 10, 50) + z = x + 4.0 * rng.randn(len(x)) + + rbf = Rbf(x, z, function=function) + xi = np.linspace(0, 10, 1000) + yi = rbf(xi) + + # subtract the linear trend and make sure there no spikes + assert np.abs(yi-xi).max() / np.abs(z-x).max() < 1.1 + +def test_rbf_stability(): + for function in FUNCTIONS: + check_rbf1d_stability(function) + + +def test_default_construction(): + # Check that the Rbf class can be constructed with the default + # multiquadric basis function. Regression test for ticket #1228. + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_function_is_callable(): + # Check that the Rbf class can be constructed with function=callable. + x = linspace(0,10,9) + y = sin(x) + def linfunc(x): + return x + rbf = Rbf(x, y, function=linfunc) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_two_arg_function_is_callable(): + # Check that the Rbf class can be constructed with a two argument + # function=callable. + def _func(self, r): + return self.epsilon + r + + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y, function=_func) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_rbf_epsilon_none(): + x = linspace(0, 10, 9) + y = sin(x) + Rbf(x, y, epsilon=None) + + +def test_rbf_epsilon_none_collinear(): + # Check that collinear points in one dimension doesn't cause an error + # due to epsilon = 0 + x = [1, 2, 3] + y = [4, 4, 4] + z = [5, 6, 7] + rbf = Rbf(x, y, z, epsilon=None) + assert rbf.epsilon > 0 + + +@pytest.mark.thread_unsafe +def test_rbf_concurrency(): + x = linspace(0, 10, 100) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, mode='N-D') + + def worker_fn(_, interp, xp): + interp(xp) + + _run_concurrent_barrier(10, worker_fn, rbf, x) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py new file mode 100644 index 0000000000000000000000000000000000000000..3d2759fdee41fa64c09bb00979f10b70e49a2855 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py @@ -0,0 +1,534 @@ +import pickle +import pytest +import numpy as np +from numpy.linalg import LinAlgError +from scipy._lib._array_api import xp_assert_close +from scipy.stats.qmc import Halton +from scipy.spatial import cKDTree # type: ignore[attr-defined] +from scipy.interpolate._rbfinterp import ( + _AVAILABLE, _SCALE_INVARIANT, _NAME_TO_MIN_DEGREE, _monomial_powers, + RBFInterpolator + ) +from scipy.interpolate import _rbfinterp_pythran +from scipy._lib._testutils import _run_concurrent_barrier + + +def _vandermonde(x, degree): + # Returns a matrix of monomials that span polynomials with the specified + # degree evaluated at x. + powers = _monomial_powers(x.shape[1], degree) + return _rbfinterp_pythran._polynomial_matrix(x, powers) + + +def _1d_test_function(x): + # Test function used in Wahba's "Spline Models for Observational Data". + # domain ~= (0, 3), range ~= (-1.0, 0.2) + x = x[:, 0] + y = 4.26*(np.exp(-x) - 4*np.exp(-2*x) + 3*np.exp(-3*x)) + return y + + +def _2d_test_function(x): + # Franke's test function. + # domain ~= (0, 1) X (0, 1), range ~= (0.0, 1.2) + x1, x2 = x[:, 0], x[:, 1] + term1 = 0.75 * np.exp(-(9*x1-2)**2/4 - (9*x2-2)**2/4) + term2 = 0.75 * np.exp(-(9*x1+1)**2/49 - (9*x2+1)/10) + term3 = 0.5 * np.exp(-(9*x1-7)**2/4 - (9*x2-3)**2/4) + term4 = -0.2 * np.exp(-(9*x1-4)**2 - (9*x2-7)**2) + y = term1 + term2 + term3 + term4 + return y + + +def _is_conditionally_positive_definite(kernel, m): + # Tests whether the kernel is conditionally positive definite of order m. + # See chapter 7 of Fasshauer's "Meshfree Approximation Methods with + # MATLAB". + nx = 10 + ntests = 100 + for ndim in [1, 2, 3, 4, 5]: + # Generate sample points with a Halton sequence to avoid samples that + # are too close to each other, which can make the matrix singular. + seq = Halton(ndim, scramble=False, seed=np.random.RandomState()) + for _ in range(ntests): + x = 2*seq.random(nx) - 1 + A = _rbfinterp_pythran._kernel_matrix(x, kernel) + P = _vandermonde(x, m - 1) + Q, R = np.linalg.qr(P, mode='complete') + # Q2 forms a basis spanning the space where P.T.dot(x) = 0. Project + # A onto this space, and then see if it is positive definite using + # the Cholesky decomposition. If not, then the kernel is not c.p.d. + # of order m. + Q2 = Q[:, P.shape[1]:] + B = Q2.T.dot(A).dot(Q2) + try: + np.linalg.cholesky(B) + except np.linalg.LinAlgError: + return False + + return True + + +# Sorting the parametrize arguments is necessary to avoid a parallelization +# issue described here: https://github.com/pytest-dev/pytest-xdist/issues/432. +@pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) +def test_conditionally_positive_definite(kernel): + # Test if each kernel in _AVAILABLE is conditionally positive definite of + # order m, where m comes from _NAME_TO_MIN_DEGREE. This is a necessary + # condition for the smoothed RBF interpolant to be well-posed in general. + m = _NAME_TO_MIN_DEGREE.get(kernel, -1) + 1 + assert _is_conditionally_positive_definite(kernel, m) + + +class _TestRBFInterpolator: + @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT)) + def test_scale_invariance_1d(self, kernel): + # Verify that the functions in _SCALE_INVARIANT are insensitive to the + # shape parameter (when smoothing == 0) in 1d. + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + x = 3*seq.random(50) + y = _1d_test_function(x) + xitp = 3*seq.random(50) + yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp) + yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp) + xp_assert_close(yitp1, yitp2, atol=1e-8) + + @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT)) + def test_scale_invariance_2d(self, kernel): + # Verify that the functions in _SCALE_INVARIANT are insensitive to the + # shape parameter (when smoothing == 0) in 2d. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + x = seq.random(100) + y = _2d_test_function(x) + xitp = seq.random(100) + yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp) + yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp) + xp_assert_close(yitp1, yitp2, atol=1e-8) + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_extreme_domains(self, kernel): + # Make sure the interpolant remains numerically stable for very + # large/small domains. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + scale = 1e50 + shift = 1e55 + + x = seq.random(100) + y = _2d_test_function(x) + xitp = seq.random(100) + + if kernel in _SCALE_INVARIANT: + yitp1 = self.build(x, y, kernel=kernel)(xitp) + yitp2 = self.build( + x*scale + shift, y, + kernel=kernel + )(xitp*scale + shift) + else: + yitp1 = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp) + yitp2 = self.build( + x*scale + shift, y, + epsilon=5.0/scale, + kernel=kernel + )(xitp*scale + shift) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_polynomial_reproduction(self): + # If the observed data comes from a polynomial, then the interpolant + # should be able to reproduce the polynomial exactly, provided that + # `degree` is sufficiently high. + rng = np.random.RandomState(0) + seq = Halton(2, scramble=False, seed=rng) + degree = 3 + + x = seq.random(50) + xitp = seq.random(50) + + P = _vandermonde(x, degree) + Pitp = _vandermonde(xitp, degree) + + poly_coeffs = rng.normal(0.0, 1.0, P.shape[1]) + + y = P.dot(poly_coeffs) + yitp1 = Pitp.dot(poly_coeffs) + yitp2 = self.build(x, y, degree=degree)(xitp) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + @pytest.mark.slow + def test_chunking(self, monkeypatch): + # If the observed data comes from a polynomial, then the interpolant + # should be able to reproduce the polynomial exactly, provided that + # `degree` is sufficiently high. + rng = np.random.RandomState(0) + seq = Halton(2, scramble=False, seed=rng) + degree = 3 + + largeN = 1000 + 33 + # this is large to check that chunking of the RBFInterpolator is tested + x = seq.random(50) + xitp = seq.random(largeN) + + P = _vandermonde(x, degree) + Pitp = _vandermonde(xitp, degree) + + poly_coeffs = rng.normal(0.0, 1.0, P.shape[1]) + + y = P.dot(poly_coeffs) + yitp1 = Pitp.dot(poly_coeffs) + interp = self.build(x, y, degree=degree) + ce_real = interp._chunk_evaluator + + def _chunk_evaluator(*args, **kwargs): + kwargs.update(memory_budget=100) + return ce_real(*args, **kwargs) + + monkeypatch.setattr(interp, '_chunk_evaluator', _chunk_evaluator) + yitp2 = interp(xitp) + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_vector_data(self): + # Make sure interpolating a vector field is the same as interpolating + # each component separately. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + + y = np.array([_2d_test_function(x), + _2d_test_function(x[:, ::-1])]).T + + yitp1 = self.build(x, y)(xitp) + yitp2 = self.build(x, y[:, 0])(xitp) + yitp3 = self.build(x, y[:, 1])(xitp) + + xp_assert_close(yitp1[:, 0], yitp2) + xp_assert_close(yitp1[:, 1], yitp3) + + def test_complex_data(self): + # Interpolating complex input should be the same as interpolating the + # real and complex components. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x) + 1j*_2d_test_function(x[:, ::-1]) + + yitp1 = self.build(x, y)(xitp) + yitp2 = self.build(x, y.real)(xitp) + yitp3 = self.build(x, y.imag)(xitp) + + xp_assert_close(yitp1.real, yitp2) + xp_assert_close(yitp1.imag, yitp3) + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_interpolation_misfit_1d(self, kernel): + # Make sure that each kernel, with its default `degree` and an + # appropriate `epsilon`, does a good job at interpolation in 1d. + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + + y = _1d_test_function(x) + ytrue = _1d_test_function(xitp) + yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp) + + mse = np.mean((yitp - ytrue)**2) + assert mse < 1.0e-4 + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_interpolation_misfit_2d(self, kernel): + # Make sure that each kernel, with its default `degree` and an + # appropriate `epsilon`, does a good job at interpolation in 2d. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x) + ytrue = _2d_test_function(xitp) + yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp) + + mse = np.mean((yitp - ytrue)**2) + assert mse < 2.0e-4 + + @pytest.mark.parametrize('kernel', sorted(_AVAILABLE)) + def test_smoothing_misfit(self, kernel): + # Make sure we can find a smoothing parameter for each kernel that + # removes a sufficient amount of noise. + rng = np.random.RandomState(0) + seq = Halton(1, scramble=False, seed=rng) + + noise = 0.2 + rmse_tol = 0.1 + smoothing_range = 10**np.linspace(-4, 1, 20) + + x = 3*seq.random(100) + y = _1d_test_function(x) + rng.normal(0.0, noise, (100,)) + ytrue = _1d_test_function(x) + rmse_within_tol = False + for smoothing in smoothing_range: + ysmooth = self.build( + x, y, + epsilon=1.0, + smoothing=smoothing, + kernel=kernel)(x) + rmse = np.sqrt(np.mean((ysmooth - ytrue)**2)) + if rmse < rmse_tol: + rmse_within_tol = True + break + + assert rmse_within_tol + + def test_array_smoothing(self): + # Test using an array for `smoothing` to give less weight to a known + # outlier. + rng = np.random.RandomState(0) + seq = Halton(1, scramble=False, seed=rng) + degree = 2 + + x = seq.random(50) + P = _vandermonde(x, degree) + poly_coeffs = rng.normal(0.0, 1.0, P.shape[1]) + y = P.dot(poly_coeffs) + y_with_outlier = np.copy(y) + y_with_outlier[10] += 1.0 + smoothing = np.zeros((50,)) + smoothing[10] = 1000.0 + yitp = self.build(x, y_with_outlier, smoothing=smoothing)(x) + # Should be able to reproduce the uncorrupted data almost exactly. + xp_assert_close(yitp, y, atol=1e-4) + + def test_inconsistent_x_dimensions_error(self): + # ValueError should be raised if the observation points and evaluation + # points have a different number of dimensions. + y = Halton(2, scramble=False, seed=np.random.RandomState()).random(10) + d = _2d_test_function(y) + x = Halton(1, scramble=False, seed=np.random.RandomState()).random(10) + match = 'Expected the second axis of `x`' + with pytest.raises(ValueError, match=match): + self.build(y, d)(x) + + def test_inconsistent_d_length_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(1) + match = 'Expected the first axis of `d`' + with pytest.raises(ValueError, match=match): + self.build(y, d) + + def test_y_not_2d_error(self): + y = np.linspace(0, 1, 5) + d = np.zeros(5) + match = '`y` must be a 2-dimensional array.' + with pytest.raises(ValueError, match=match): + self.build(y, d) + + def test_inconsistent_smoothing_length_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + smoothing = np.ones(1) + match = 'Expected `smoothing` to be' + with pytest.raises(ValueError, match=match): + self.build(y, d, smoothing=smoothing) + + def test_invalid_kernel_name_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + match = '`kernel` must be one of' + with pytest.raises(ValueError, match=match): + self.build(y, d, kernel='test') + + def test_epsilon_not_specified_error(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + for kernel in _AVAILABLE: + if kernel in _SCALE_INVARIANT: + continue + + match = '`epsilon` must be specified' + with pytest.raises(ValueError, match=match): + self.build(y, d, kernel=kernel) + + def test_x_not_2d_error(self): + y = np.linspace(0, 1, 5)[:, None] + x = np.linspace(0, 1, 5) + d = np.zeros(5) + match = '`x` must be a 2-dimensional array.' + with pytest.raises(ValueError, match=match): + self.build(y, d)(x) + + def test_not_enough_observations_error(self): + y = np.linspace(0, 1, 1)[:, None] + d = np.zeros(1) + match = 'At least 2 data points are required' + with pytest.raises(ValueError, match=match): + self.build(y, d, kernel='thin_plate_spline') + + @pytest.mark.thread_unsafe + def test_degree_warning(self): + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + for kernel, deg in _NAME_TO_MIN_DEGREE.items(): + # Only test for kernels that its minimum degree is not 0. + if deg >= 1: + match = f'`degree` should not be below {deg}' + with pytest.warns(Warning, match=match): + self.build(y, d, epsilon=1.0, kernel=kernel, degree=deg-1) + + def test_minus_one_degree(self): + # Make sure a degree of -1 is accepted without any warning. + y = np.linspace(0, 1, 5)[:, None] + d = np.zeros(5) + for kernel, _ in _NAME_TO_MIN_DEGREE.items(): + self.build(y, d, epsilon=1.0, kernel=kernel, degree=-1) + + def test_rank_error(self): + # An error should be raised when `kernel` is "thin_plate_spline" and + # observations are 2-D and collinear. + y = np.array([[2.0, 0.0], [1.0, 0.0], [0.0, 0.0]]) + d = np.array([0.0, 0.0, 0.0]) + match = 'does not have full column rank' + with pytest.raises(LinAlgError, match=match): + self.build(y, d, kernel='thin_plate_spline')(y) + + def test_single_point(self): + # Make sure interpolation still works with only one point (in 1, 2, and + # 3 dimensions). + for dim in [1, 2, 3]: + y = np.zeros((1, dim)) + d = np.ones((1,)) + f = self.build(y, d, kernel='linear')(y) + xp_assert_close(d, f) + + def test_pickleable(self): + # Make sure we can pickle and unpickle the interpolant without any + # changes in the behavior. + seq = Halton(1, scramble=False, seed=np.random.RandomState(2305982309)) + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + + y = _1d_test_function(x) + + interp = self.build(x, y) + + yitp1 = interp(xitp) + yitp2 = pickle.loads(pickle.dumps(interp))(xitp) + + xp_assert_close(yitp1, yitp2, atol=1e-16) + + +class TestRBFInterpolatorNeighborsNone(_TestRBFInterpolator): + def build(self, *args, **kwargs): + return RBFInterpolator(*args, **kwargs) + + def test_smoothing_limit_1d(self): + # For large smoothing parameters, the interpolant should approach a + # least squares fit of a polynomial with the specified degree. + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + + degree = 3 + smoothing = 1e8 + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + + y = _1d_test_function(x) + + yitp1 = self.build( + x, y, + degree=degree, + smoothing=smoothing + )(xitp) + + P = _vandermonde(x, degree) + Pitp = _vandermonde(xitp, degree) + yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0]) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_smoothing_limit_2d(self): + # For large smoothing parameters, the interpolant should approach a + # least squares fit of a polynomial with the specified degree. + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + degree = 3 + smoothing = 1e8 + + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x) + + yitp1 = self.build( + x, y, + degree=degree, + smoothing=smoothing + )(xitp) + + P = _vandermonde(x, degree) + Pitp = _vandermonde(xitp, degree) + yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0]) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + +class TestRBFInterpolatorNeighbors20(_TestRBFInterpolator): + # RBFInterpolator using 20 nearest neighbors. + def build(self, *args, **kwargs): + return RBFInterpolator(*args, **kwargs, neighbors=20) + + def test_equivalent_to_rbf_interpolator(self): + seq = Halton(2, scramble=False, seed=np.random.RandomState()) + + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x) + + yitp1 = self.build(x, y)(xitp) + + yitp2 = [] + tree = cKDTree(x) + for xi in xitp: + _, nbr = tree.query(xi, 20) + yitp2.append(RBFInterpolator(x[nbr], y[nbr])(xi[None])[0]) + + xp_assert_close(yitp1, yitp2, atol=1e-8) + + def test_concurrency(self): + # Check that no segfaults appear with concurrent access to + # RbfInterpolator + seq = Halton(2, scramble=False, seed=np.random.RandomState(0)) + x = seq.random(100) + xitp = seq.random(100) + + y = _2d_test_function(x) + + interp = self.build(x, y) + + def worker_fn(_, interp, xp): + interp(xp) + + _run_concurrent_barrier(10, worker_fn, interp, xitp) + + +class TestRBFInterpolatorNeighborsInf(TestRBFInterpolatorNeighborsNone): + # RBFInterpolator using neighbors=np.inf. This should give exactly the same + # results as neighbors=None, but it will be slower. + def build(self, *args, **kwargs): + return RBFInterpolator(*args, **kwargs, neighbors=np.inf) + + def test_equivalent_to_rbf_interpolator(self): + seq = Halton(1, scramble=False, seed=np.random.RandomState()) + + x = 3*seq.random(50) + xitp = 3*seq.random(50) + + y = _1d_test_function(x) + yitp1 = self.build(x, y)(xitp) + yitp2 = RBFInterpolator(x, y)(xitp) + + xp_assert_close(yitp1, yitp2, atol=1e-8) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rgi.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rgi.py new file mode 100644 index 0000000000000000000000000000000000000000..54c4f380ad7d51f54a5947cfc7764a60c1fc235e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rgi.py @@ -0,0 +1,1150 @@ +import itertools + +import pytest +import numpy as np + +from numpy.testing import assert_warns +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, assert_array_almost_equal +) +from scipy.conftest import skip_xp_invalid_arg + +from pytest import raises as assert_raises + +from scipy.interpolate import (RegularGridInterpolator, interpn, + RectBivariateSpline, + NearestNDInterpolator, LinearNDInterpolator) + +from scipy.sparse._sputils import matrix +from scipy._lib._util import ComplexWarning +from scipy._lib._testutils import _run_concurrent_barrier + + +parametrize_rgi_interp_methods = pytest.mark.parametrize( + "method", RegularGridInterpolator._ALL_METHODS +) + +class TestRegularGridInterpolator: + def _get_sample_4d(self): + # create a 4-D grid of 3 points in each dimension + points = [(0., .5, 1.)] * 4 + values = np.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def _get_sample_4d_2(self): + # create another 4-D grid of 3 points in each dimension + points = [(0., .5, 1.)] * 2 + [(0., 5., 10.)] * 2 + values = np.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def _get_sample_4d_3(self): + # create another 4-D grid of 7 points in each dimension + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0)] * 4 + values = np.asarray([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def _get_sample_4d_4(self): + # create another 4-D grid of 2 points in each dimension + points = [(0.0, 1.0)] * 4 + values = np.asarray([0.0, 1.0]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + @parametrize_rgi_interp_methods + def test_list_input(self, method): + points, values = self._get_sample_4d_3() + + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + + interp = RegularGridInterpolator(points, + values.tolist(), + method=method) + v1 = interp(sample.tolist()) + interp = RegularGridInterpolator(points, + values, + method=method) + v2 = interp(sample) + xp_assert_close(v1, v2) + + @pytest.mark.parametrize('method', ['cubic', 'quintic', 'pchip']) + def test_spline_dim_error(self, method): + points, values = self._get_sample_4d_4() + match = "points in dimension" + + # Check error raise when creating interpolator + with pytest.raises(ValueError, match=match): + RegularGridInterpolator(points, values, method=method) + + # Check error raise when creating interpolator + interp = RegularGridInterpolator(points, values) + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + with pytest.raises(ValueError, match=match): + interp(sample, method=method) + + @pytest.mark.parametrize( + "points_values, sample", + [ + ( + _get_sample_4d, + np.asarray( + [[0.1, 0.1, 1.0, 0.9], + [0.2, 0.1, 0.45, 0.8], + [0.5, 0.5, 0.5, 0.5]] + ), + ), + (_get_sample_4d_2, np.asarray([0.1, 0.1, 10.0, 9.0])), + ], + ) + def test_linear_and_slinear_close(self, points_values, sample): + points, values = points_values(self) + interp = RegularGridInterpolator(points, values, method="linear") + v1 = interp(sample) + interp = RegularGridInterpolator(points, values, method="slinear") + v2 = interp(sample) + xp_assert_close(v1, v2) + + def test_derivatives(self): + points, values = self._get_sample_4d() + sample = np.array([[0.1 , 0.1 , 1. , 0.9 ], + [0.2 , 0.1 , 0.45, 0.8 ], + [0.5 , 0.5 , 0.5 , 0.5 ]]) + interp = RegularGridInterpolator(points, values, method="slinear") + + with assert_raises(ValueError): + # wrong number of derivatives (need 4) + interp(sample, nu=1) + + xp_assert_close(interp(sample, nu=(1, 0, 0, 0)), + np.asarray([1.0, 1, 1]), atol=1e-15) + xp_assert_close(interp(sample, nu=(0, 1, 0, 0)), + np.asarray([10.0, 10, 10]), atol=1e-15) + + # 2nd derivatives of a linear function are zero + xp_assert_close(interp(sample, nu=(0, 1, 1, 0)), + np.asarray([0.0, 0, 0]), atol=2e-12) + + @parametrize_rgi_interp_methods + def test_complex(self, method): + if method == "pchip": + pytest.skip("pchip does not make sense for complex data") + points, values = self._get_sample_4d_3() + values = values - 2j*values + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + + interp = RegularGridInterpolator(points, values, method=method) + rinterp = RegularGridInterpolator(points, values.real, method=method) + iinterp = RegularGridInterpolator(points, values.imag, method=method) + + v1 = interp(sample) + v2 = rinterp(sample) + 1j*iinterp(sample) + xp_assert_close(v1, v2) + + def test_cubic_vs_pchip(self): + x, y = [1, 2, 3, 4], [1, 2, 3, 4] + xg, yg = np.meshgrid(x, y, indexing='ij') + + values = (lambda x, y: x**4 * y**4)(xg, yg) + cubic = RegularGridInterpolator((x, y), values, method='cubic') + pchip = RegularGridInterpolator((x, y), values, method='pchip') + + vals_cubic = cubic([1.5, 2]) + vals_pchip = pchip([1.5, 2]) + assert not np.allclose(vals_cubic, vals_pchip, atol=1e-14, rtol=0) + + def test_linear_xi1d(self): + points, values = self._get_sample_4d_2() + interp = RegularGridInterpolator(points, values) + sample = np.asarray([0.1, 0.1, 10., 9.]) + wanted = np.asarray([1001.1]) + assert_array_almost_equal(interp(sample), wanted) + + def test_linear_xi3d(self): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values) + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + wanted = np.asarray([1001.1, 846.2, 555.5]) + assert_array_almost_equal(interp(sample), wanted) + + @pytest.mark.parametrize( + "sample, wanted", + [ + (np.asarray([0.1, 0.1, 0.9, 0.9]), 1100.0), + (np.asarray([0.1, 0.1, 0.1, 0.1]), 0.0), + (np.asarray([0.0, 0.0, 0.0, 0.0]), 0.0), + (np.asarray([1.0, 1.0, 1.0, 1.0]), 1111.0), + (np.asarray([0.1, 0.4, 0.6, 0.9]), 1055.0), + ], + ) + def test_nearest(self, sample, wanted): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values, method="nearest") + wanted = np.asarray([wanted]) + assert_array_almost_equal(interp(sample), wanted) + + def test_linear_edges(self): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values) + sample = np.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]]) + wanted = np.asarray([0., 1111.]) + assert_array_almost_equal(interp(sample), wanted) + + def test_valid_create(self): + # create a 2-D grid of 3 points in each dimension + points = [(0., .5, 1.), (0., 1., .5)] + values = np.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis] + values1 = values[np.newaxis, :] + values = (values0 + values1 * 10) + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [((0., .5, 1.), ), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [(0., .5, .75, 1.), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [(0., .5, 1.), (0., .5, 1.), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values) + points = [(0., .5, 1.), (0., .5, 1.)] + assert_raises(ValueError, RegularGridInterpolator, points, values, + method="undefmethod") + + def test_valid_call(self): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values) + sample = np.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]]) + assert_raises(ValueError, interp, sample, "undefmethod") + sample = np.asarray([[0., 0., 0.], [1., 1., 1.]]) + assert_raises(ValueError, interp, sample) + sample = np.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.1]]) + assert_raises(ValueError, interp, sample) + + def test_out_of_bounds_extrap(self): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values, bounds_error=False, + fill_value=None) + sample = np.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1], + [21, 2.1, -1.1, -11], [2.1, 2.1, -1.1, -1.1]]) + wanted = np.asarray([0., 1111., 11., 11.]) + assert_array_almost_equal(interp(sample, method="nearest"), wanted) + wanted = np.asarray([-111.1, 1222.1, -11068., -1186.9]) + assert_array_almost_equal(interp(sample, method="linear"), wanted) + + def test_out_of_bounds_extrap2(self): + points, values = self._get_sample_4d_2() + interp = RegularGridInterpolator(points, values, bounds_error=False, + fill_value=None) + sample = np.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1], + [21, 2.1, -1.1, -11], [2.1, 2.1, -1.1, -1.1]]) + wanted = np.asarray([0., 11., 11., 11.]) + assert_array_almost_equal(interp(sample, method="nearest"), wanted) + wanted = np.asarray([-12.1, 133.1, -1069., -97.9]) + assert_array_almost_equal(interp(sample, method="linear"), wanted) + + def test_out_of_bounds_fill(self): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values, bounds_error=False, + fill_value=np.nan) + sample = np.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1], + [2.1, 2.1, -1.1, -1.1]]) + wanted = np.asarray([np.nan, np.nan, np.nan]) + assert_array_almost_equal(interp(sample, method="nearest"), wanted) + assert_array_almost_equal(interp(sample, method="linear"), wanted) + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + wanted = np.asarray([1001.1, 846.2, 555.5]) + assert_array_almost_equal(interp(sample), wanted) + + def test_nearest_compare_qhull(self): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values, method="nearest") + points_qhull = itertools.product(*points) + points_qhull = [p for p in points_qhull] + points_qhull = np.asarray(points_qhull) + values_qhull = values.reshape(-1) + interp_qhull = NearestNDInterpolator(points_qhull, values_qhull) + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + assert_array_almost_equal(interp(sample), interp_qhull(sample)) + + def test_linear_compare_qhull(self): + points, values = self._get_sample_4d() + interp = RegularGridInterpolator(points, values) + points_qhull = itertools.product(*points) + points_qhull = [p for p in points_qhull] + points_qhull = np.asarray(points_qhull) + values_qhull = values.reshape(-1) + interp_qhull = LinearNDInterpolator(points_qhull, values_qhull) + sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8], + [0.5, 0.5, .5, .5]]) + assert_array_almost_equal(interp(sample), interp_qhull(sample)) + + @pytest.mark.parametrize("method", ["nearest", "linear"]) + def test_duck_typed_values(self, method): + x = np.linspace(0, 2, 5) + y = np.linspace(0, 1, 7) + + values = MyValue((5, 7)) + + interp = RegularGridInterpolator((x, y), values, method=method) + v1 = interp([0.4, 0.7]) + + interp = RegularGridInterpolator((x, y), values._v, method=method) + v2 = interp([0.4, 0.7]) + xp_assert_close(v1, v2, check_dtype=False) + + def test_invalid_fill_value(self): + np.random.seed(1234) + x = np.linspace(0, 2, 5) + y = np.linspace(0, 1, 7) + values = np.random.rand(5, 7) + + # integers can be cast to floats + RegularGridInterpolator((x, y), values, fill_value=1) + + # complex values cannot + assert_raises(ValueError, RegularGridInterpolator, + (x, y), values, fill_value=1+2j) + + def test_fillvalue_type(self): + # from #3703; test that interpolator object construction succeeds + values = np.ones((10, 20, 30), dtype='>f4') + points = [np.arange(n) for n in values.shape] + # xi = [(1, 1, 1)] + RegularGridInterpolator(points, values) + RegularGridInterpolator(points, values, fill_value=0.) + + def test_length_one_axis(self): + # gh-5890, gh-9524 : length-1 axis is legal for method='linear'. + # Along the axis it's linear interpolation; away from the length-1 + # axis, it's an extrapolation, so fill_value should be used. + def f(x, y): + return x + y + x = np.linspace(1, 1, 1) + y = np.linspace(1, 10, 10) + data = f(*np.meshgrid(x, y, indexing="ij", sparse=True)) + + interp = RegularGridInterpolator((x, y), data, method="linear", + bounds_error=False, fill_value=101) + + # check values at the grid + xp_assert_close(interp(np.array([[1, 1], [1, 5], [1, 10]])), + np.asarray([2.0, 6, 11]), + atol=1e-14) + + # check off-grid interpolation is indeed linear + xp_assert_close(interp(np.array([[1, 1.4], [1, 5.3], [1, 10]])), + [2.4, 6.3, 11], + atol=1e-14) + + # check exrapolation w/ fill_value + xp_assert_close(interp(np.array([1.1, 2.4])), + interp.fill_value, + check_dtype=False, check_shape=False, check_0d=False, + atol=1e-14) + + # check extrapolation: linear along the `y` axis, const along `x` + interp.fill_value = None + xp_assert_close(interp([[1, 0.3], [1, 11.5]]), + [1.3, 12.5], atol=1e-15) + + xp_assert_close(interp([[1.5, 0.3], [1.9, 11.5]]), + [1.3, 12.5], atol=1e-15) + + # extrapolation with method='nearest' + interp = RegularGridInterpolator((x, y), data, method="nearest", + bounds_error=False, fill_value=None) + xp_assert_close(interp([[1.5, 1.8], [-4, 5.1]]), + np.asarray([3.0, 6]), + atol=1e-15) + + @pytest.mark.parametrize("fill_value", [None, np.nan, np.pi]) + @pytest.mark.parametrize("method", ['linear', 'nearest']) + def test_length_one_axis2(self, fill_value, method): + options = {"fill_value": fill_value, "bounds_error": False, + "method": method} + + x = np.linspace(0, 2*np.pi, 20) + z = np.sin(x) + + fa = RegularGridInterpolator((x,), z[:], **options) + fb = RegularGridInterpolator((x, [0]), z[:, None], **options) + + x1a = np.linspace(-1, 2*np.pi+1, 100) + za = fa(x1a) + + # evaluated at provided y-value, fb should behave exactly as fa + y1b = np.zeros(100) + zb = fb(np.vstack([x1a, y1b]).T) + xp_assert_close(zb, za) + + # evaluated at a different y-value, fb should return fill value + y1b = np.ones(100) + zb = fb(np.vstack([x1a, y1b]).T) + if fill_value is None: + xp_assert_close(zb, za) + else: + xp_assert_close(zb, np.full_like(zb, fill_value)) + + @pytest.mark.parametrize("method", ['nearest', 'linear']) + def test_nan_x_1d(self, method): + # gh-6624 : if x is nan, result should be nan + f = RegularGridInterpolator(([1, 2, 3],), [10, 20, 30], fill_value=1, + bounds_error=False, method=method) + assert np.isnan(f([np.nan])) + + # test arbitrary nan pattern + rng = np.random.default_rng(8143215468) + x = rng.random(size=100)*4 + i = rng.random(size=100) > 0.5 + x[i] = np.nan + with np.errstate(invalid='ignore'): + # out-of-bounds comparisons, `out_of_bounds += x < grid[0]`, + # generate numpy warnings if `x` contains nans. + # These warnings should propagate to user (since `x` is user + # input) and we simply filter them out. + res = f(x) + + assert np.isnan(res[i]).all() + xp_assert_equal(res[~i], f(x[~i])) + + # also test the length-one axis f(nan) + x = [1, 2, 3] + y = [1, ] + data = np.ones((3, 1)) + f = RegularGridInterpolator((x, y), data, fill_value=1, + bounds_error=False, method=method) + assert np.all(np.isnan(f([np.nan, 1]))) + assert np.all(np.isnan(f([1, np.nan]))) + + @pytest.mark.parametrize("method", ['nearest', 'linear']) + def test_nan_x_2d(self, method): + x, y = np.array([0, 1, 2]), np.array([1, 3, 7]) + + def f(x, y): + return x**2 + y**2 + + xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True) + data = f(xg, yg) + interp = RegularGridInterpolator((x, y), data, + method=method, bounds_error=False) + + with np.errstate(invalid='ignore'): + res = interp([[1.5, np.nan], [1, 1]]) + xp_assert_close(res[1], 2.0, atol=1e-14) + assert np.isnan(res[0]) + + # test arbitrary nan pattern + rng = np.random.default_rng(8143215468) + x = rng.random(size=100)*4-1 + y = rng.random(size=100)*8 + i1 = rng.random(size=100) > 0.5 + i2 = rng.random(size=100) > 0.5 + i = i1 | i2 + x[i1] = np.nan + y[i2] = np.nan + z = np.array([x, y]).T + with np.errstate(invalid='ignore'): + # out-of-bounds comparisons, `out_of_bounds += x < grid[0]`, + # generate numpy warnings if `x` contains nans. + # These warnings should propagate to user (since `x` is user + # input) and we simply filter them out. + res = interp(z) + + assert np.isnan(res[i]).all() + xp_assert_equal(res[~i], interp(z[~i]), check_dtype=False) + + @pytest.mark.fail_slow(10) + @parametrize_rgi_interp_methods + @pytest.mark.parametrize(("ndims", "func"), [ + (2, lambda x, y: 2 * x ** 3 + 3 * y ** 2), + (3, lambda x, y, z: 2 * x ** 3 + 3 * y ** 2 - z), + (4, lambda x, y, z, a: 2 * x ** 3 + 3 * y ** 2 - z + a), + (5, lambda x, y, z, a, b: 2 * x ** 3 + 3 * y ** 2 - z + a * b), + ]) + def test_descending_points_nd(self, method, ndims, func): + + if ndims >= 4 and method in {"cubic", "quintic"}: + pytest.skip("too slow; OOM (quintic); or nearly so (cubic)") + + rng = np.random.default_rng(42) + sample_low = 1 + sample_high = 5 + test_points = rng.uniform(sample_low, sample_high, size=(2, ndims)) + + ascending_points = [np.linspace(sample_low, sample_high, 12) + for _ in range(ndims)] + + ascending_values = func(*np.meshgrid(*ascending_points, + indexing="ij", + sparse=True)) + + ascending_interp = RegularGridInterpolator(ascending_points, + ascending_values, + method=method) + ascending_result = ascending_interp(test_points) + + descending_points = [xi[::-1] for xi in ascending_points] + descending_values = func(*np.meshgrid(*descending_points, + indexing="ij", + sparse=True)) + descending_interp = RegularGridInterpolator(descending_points, + descending_values, + method=method) + descending_result = descending_interp(test_points) + + xp_assert_equal(ascending_result, descending_result) + + def test_invalid_points_order(self): + def val_func_2d(x, y): + return 2 * x ** 3 + 3 * y ** 2 + + x = np.array([.5, 2., 0., 4., 5.5]) # not ascending or descending + y = np.array([.5, 2., 3., 4., 5.5]) + points = (x, y) + values = val_func_2d(*np.meshgrid(*points, indexing='ij', + sparse=True)) + match = "must be strictly ascending or descending" + with pytest.raises(ValueError, match=match): + RegularGridInterpolator(points, values) + + @parametrize_rgi_interp_methods + def test_fill_value(self, method): + interp = RegularGridInterpolator([np.arange(6)], np.ones(6), + method=method, bounds_error=False) + assert np.isnan(interp([10])) + + @pytest.mark.fail_slow(5) + @parametrize_rgi_interp_methods + def test_nonscalar_values(self, method): + + if method == "quintic": + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also works + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5)] * 2 + [ + (0.0, 5.0, 10.0, 15.0, 20, 25.0) + ] * 2 + + rng = np.random.default_rng(1234) + values = rng.random((6, 6, 6, 6, 8)) + sample = rng.random((7, 3, 4)) + + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=False) + v = interp(sample) + assert v.shape == (7, 3, 8), method + + vs = [] + for j in range(8): + interp = RegularGridInterpolator(points, values[..., j], + method=method, + bounds_error=False) + vs.append(interp(sample)) + v2 = np.array(vs).transpose(1, 2, 0) + + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + @parametrize_rgi_interp_methods + @pytest.mark.parametrize("flip_points", [False, True]) + def test_nonscalar_values_2(self, method, flip_points): + + if method in {"cubic", "quintic"}: + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also work : use different + # lengths of axes to simplify tracing the internals + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5), + (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0, 47)] + + # verify, that strictly decreasing dimensions work + if flip_points: + points = [tuple(reversed(p)) for p in points] + + rng = np.random.default_rng(1234) + + trailing_points = (3, 2) + # NB: values has a `num_trailing_dims` trailing dimension + values = rng.random((6, 7, 8, 9, *trailing_points)) + sample = rng.random(4) # a single sample point ! + + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=False) + v = interp(sample) + + # v has a single sample point *per entry in the trailing dimensions* + assert v.shape == (1, *trailing_points) + + # check the values, too : manually loop over the trailing dimensions + vs = np.empty(values.shape[-2:]) + for i in range(values.shape[-2]): + for j in range(values.shape[-1]): + interp = RegularGridInterpolator(points, values[..., i, j], + method=method, + bounds_error=False) + vs[i, j] = interp(sample).item() + v2 = np.expand_dims(vs, axis=0) + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + def test_nonscalar_values_linear_2D(self): + # Verify that non-scalar values work in the 2D fast path + method = 'linear' + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5), + (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), ] + + rng = np.random.default_rng(1234) + + trailing_points = (3, 4) + # NB: values has a `num_trailing_dims` trailing dimension + values = rng.random((6, 7, *trailing_points)) + sample = rng.random(2) # a single sample point ! + + interp = RegularGridInterpolator(points, values, method=method, + bounds_error=False) + v = interp(sample) + + # v has a single sample point *per entry in the trailing dimensions* + assert v.shape == (1, *trailing_points) + + # check the values, too : manually loop over the trailing dimensions + vs = np.empty(values.shape[-2:]) + for i in range(values.shape[-2]): + for j in range(values.shape[-1]): + interp = RegularGridInterpolator(points, values[..., i, j], + method=method, + bounds_error=False) + vs[i, j] = interp(sample).item() + v2 = np.expand_dims(vs, axis=0) + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + @pytest.mark.parametrize( + "dtype", + [np.float32, np.float64, np.complex64, np.complex128] + ) + @pytest.mark.parametrize("xi_dtype", [np.float32, np.float64]) + def test_float32_values(self, dtype, xi_dtype): + # regression test for gh-17718: values.dtype=float32 fails + def f(x, y): + return 2 * x**3 + 3 * y**2 + + x = np.linspace(1, 4, 11) + y = np.linspace(4, 7, 22) + + xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True) + data = f(xg, yg) + + data = data.astype(dtype) + + interp = RegularGridInterpolator((x, y), data) + + pts = np.array([[2.1, 6.2], + [3.3, 5.2]], dtype=xi_dtype) + + # the values here are just what the call returns; the test checks that + # that the call succeeds at all, instead of failing with cython not + # having a float32 kernel + xp_assert_close(interp(pts), [134.10469388, 153.40069388], + atol=1e-7, rtol=1e-7, check_dtype=False) + + def test_bad_solver(self): + x = np.linspace(0, 3, 7) + y = np.linspace(0, 3, 7) + xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True) + data = xg + yg + + # default method 'linear' does not accept 'solver' + with assert_raises(ValueError): + RegularGridInterpolator((x, y), data, solver=lambda x: x) + + with assert_raises(TypeError): + # wrong solver interface + RegularGridInterpolator( + (x, y), data, method='slinear', solver=lambda x: x + ) + + with assert_raises(TypeError): + # unknown argument + RegularGridInterpolator( + (x, y), data, method='slinear', solver=lambda x: x, woof='woof' + ) + + with assert_raises(TypeError): + # unknown argument + RegularGridInterpolator( + (x, y), data, method='slinear', solver_args={'woof': 42} + ) + + @pytest.mark.thread_unsafe + def test_concurrency(self): + points, values = self._get_sample_4d() + sample = np.array([[0.1 , 0.1 , 1. , 0.9 ], + [0.2 , 0.1 , 0.45, 0.8 ], + [0.5 , 0.5 , 0.5 , 0.5 ], + [0.3 , 0.1 , 0.2 , 0.4 ]]) + interp = RegularGridInterpolator(points, values, method="slinear") + + # A call to RGI with a method different from the one specified on the + # constructor, should not mutate it. + methods = ['slinear', 'nearest'] + def worker_fn(tid, interp): + spline = interp._spline + method = methods[tid % 2] + interp(sample, method=method) + assert interp._spline is spline + + _run_concurrent_barrier(10, worker_fn, interp) + + +class MyValue: + """ + Minimal indexable object + """ + + def __init__(self, shape): + self.ndim = 2 + self.shape = shape + self._v = np.arange(np.prod(shape)).reshape(shape) + + def __getitem__(self, idx): + return self._v[idx] + + def __array_interface__(self): + return None + + def __array__(self, dtype=None, copy=None): + raise RuntimeError("No array representation") + + +class TestInterpN: + def _sample_2d_data(self): + x = np.array([.5, 2., 3., 4., 5.5, 6.]) + y = np.array([.5, 2., 3., 4., 5.5, 6.]) + z = np.array( + [ + [1, 2, 1, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 3, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + [1, 2, 1, 2, 1, 1], + [1, 2, 2, 2, 1, 1], + ] + ) + return x, y, z + + def test_spline_2d(self): + x, y, z = self._sample_2d_data() + lut = RectBivariateSpline(x, y, z) + + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + assert_array_almost_equal(interpn((x, y), z, xi, method="splinef2d"), + lut.ev(xi[:, 0], xi[:, 1])) + + @parametrize_rgi_interp_methods + def test_list_input(self, method): + x, y, z = self._sample_2d_data() + xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + v1 = interpn((x, y), z, xi, method=method) + v2 = interpn( + (x.tolist(), y.tolist()), z.tolist(), xi.tolist(), method=method + ) + xp_assert_close(v1, v2, err_msg=method) + + def test_spline_2d_outofbounds(self): + x = np.array([.5, 2., 3., 4., 5.5]) + y = np.array([.5, 2., 3., 4., 5.5]) + z = np.array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + lut = RectBivariateSpline(x, y, z) + + xi = np.array([[1, 2.3, 6.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, -4.0, 5.0, 1.0, 3]]).T + actual = interpn((x, y), z, xi, method="splinef2d", + bounds_error=False, fill_value=999.99) + expected = lut.ev(xi[:, 0], xi[:, 1]) + expected[2:4] = 999.99 + assert_array_almost_equal(actual, expected) + + # no extrapolation for splinef2d + assert_raises(ValueError, interpn, (x, y), z, xi, method="splinef2d", + bounds_error=False, fill_value=None) + + def _sample_4d_data(self): + points = [(0., .5, 1.)] * 2 + [(0., 5., 10.)] * 2 + values = np.asarray([0., .5, 1.]) + values0 = values[:, np.newaxis, np.newaxis, np.newaxis] + values1 = values[np.newaxis, :, np.newaxis, np.newaxis] + values2 = values[np.newaxis, np.newaxis, :, np.newaxis] + values3 = values[np.newaxis, np.newaxis, np.newaxis, :] + values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000) + return points, values + + def test_linear_4d(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + interp_rg = RegularGridInterpolator(points, values) + sample = np.asarray([[0.1, 0.1, 10., 9.]]) + wanted = interpn(points, values, sample, method="linear") + assert_array_almost_equal(interp_rg(sample), wanted) + + def test_4d_linear_outofbounds(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + sample = np.asarray([[0.1, -0.1, 10.1, 9.]]) + wanted = np.asarray([999.99]) + actual = interpn(points, values, sample, method="linear", + bounds_error=False, fill_value=999.99) + assert_array_almost_equal(actual, wanted) + + def test_nearest_4d(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + interp_rg = RegularGridInterpolator(points, values, method="nearest") + sample = np.asarray([[0.1, 0.1, 10., 9.]]) + wanted = interpn(points, values, sample, method="nearest") + assert_array_almost_equal(interp_rg(sample), wanted) + + def test_4d_nearest_outofbounds(self): + # create a 4-D grid of 3 points in each dimension + points, values = self._sample_4d_data() + sample = np.asarray([[0.1, -0.1, 10.1, 9.]]) + wanted = np.asarray([999.99]) + actual = interpn(points, values, sample, method="nearest", + bounds_error=False, fill_value=999.99) + assert_array_almost_equal(actual, wanted) + + def test_xi_1d(self): + # verify that 1-D xi works as expected + points, values = self._sample_4d_data() + sample = np.asarray([0.1, 0.1, 10., 9.]) + v1 = interpn(points, values, sample, bounds_error=False) + v2 = interpn(points, values, sample[None,:], bounds_error=False) + xp_assert_close(v1, v2) + + def test_xi_nd(self): + # verify that higher-d xi works as expected + points, values = self._sample_4d_data() + + np.random.seed(1234) + sample = np.random.rand(2, 3, 4) + + v1 = interpn(points, values, sample, method='nearest', + bounds_error=False) + assert v1.shape == (2, 3) + + v2 = interpn(points, values, sample.reshape(-1, 4), + method='nearest', bounds_error=False) + xp_assert_close(v1, v2.reshape(v1.shape)) + + @parametrize_rgi_interp_methods + def test_xi_broadcast(self, method): + # verify that the interpolators broadcast xi + x, y, values = self._sample_2d_data() + points = (x, y) + + xi = np.linspace(0, 1, 2) + yi = np.linspace(0, 3, 3) + + sample = (xi[:, None], yi[None, :]) + v1 = interpn(points, values, sample, method=method, bounds_error=False) + assert v1.shape == (2, 3) + + xx, yy = np.meshgrid(xi, yi) + sample = np.c_[xx.T.ravel(), yy.T.ravel()] + + v2 = interpn(points, values, sample, + method=method, bounds_error=False) + xp_assert_close(v1, v2.reshape(v1.shape)) + + @pytest.mark.fail_slow(5) + @parametrize_rgi_interp_methods + def test_nonscalar_values(self, method): + + if method == "quintic": + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also works + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5)] * 2 + [ + (0.0, 5.0, 10.0, 15.0, 20, 25.0) + ] * 2 + + rng = np.random.default_rng(1234) + values = rng.random((6, 6, 6, 6, 8)) + sample = rng.random((7, 3, 4)) + + v = interpn(points, values, sample, method=method, + bounds_error=False) + assert v.shape == (7, 3, 8), method + + vs = [interpn(points, values[..., j], sample, method=method, + bounds_error=False) for j in range(8)] + v2 = np.array(vs).transpose(1, 2, 0) + + xp_assert_close(v, v2, atol=1e-14, err_msg=method) + + @parametrize_rgi_interp_methods + def test_nonscalar_values_2(self, method): + + if method in {"cubic", "quintic"}: + pytest.skip("Way too slow.") + + # Verify that non-scalar valued values also work : use different + # lengths of axes to simplify tracing the internals + points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5), + (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0), + (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0, 47)] + + rng = np.random.default_rng(1234) + + trailing_points = (3, 2) + # NB: values has a `num_trailing_dims` trailing dimension + values = rng.random((6, 7, 8, 9, *trailing_points)) + sample = rng.random(4) # a single sample point ! + + v = interpn(points, values, sample, method=method, bounds_error=False) + + # v has a single sample point *per entry in the trailing dimensions* + assert v.shape == (1, *trailing_points) + + # check the values, too : manually loop over the trailing dimensions + vs = [[ + interpn(points, values[..., i, j], sample, method=method, + bounds_error=False) for i in range(values.shape[-2]) + ] for j in range(values.shape[-1])] + + xp_assert_close(v, np.asarray(vs).T, atol=1e-14, err_msg=method) + + def test_non_scalar_values_splinef2d(self): + # Vector-valued splines supported with fitpack + points, values = self._sample_4d_data() + + np.random.seed(1234) + values = np.random.rand(3, 3, 3, 3, 6) + sample = np.random.rand(7, 11, 4) + assert_raises(ValueError, interpn, points, values, sample, + method='splinef2d') + + @parametrize_rgi_interp_methods + def test_complex(self, method): + if method == "pchip": + pytest.skip("pchip does not make sense for complex data") + + x, y, values = self._sample_2d_data() + points = (x, y) + values = values - 2j*values + + sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + + v1 = interpn(points, values, sample, method=method) + v2r = interpn(points, values.real, sample, method=method) + v2i = interpn(points, values.imag, sample, method=method) + v2 = v2r + 1j*v2i + + xp_assert_close(v1, v2) + + @pytest.mark.thread_unsafe + def test_complex_pchip(self): + # Complex-valued data deprecated for pchip + x, y, values = self._sample_2d_data() + points = (x, y) + values = values - 2j*values + + sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + with pytest.raises(ValueError, match='real'): + interpn(points, values, sample, method='pchip') + + @pytest.mark.thread_unsafe + def test_complex_spline2fd(self): + # Complex-valued data not supported by spline2fd + x, y, values = self._sample_2d_data() + points = (x, y) + values = values - 2j*values + + sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T + with assert_warns(ComplexWarning): + interpn(points, values, sample, method='splinef2d') + + @pytest.mark.parametrize( + "method", + ["linear", "nearest"] + ) + def test_duck_typed_values(self, method): + x = np.linspace(0, 2, 5) + y = np.linspace(0, 1, 7) + + values = MyValue((5, 7)) + + v1 = interpn((x, y), values, [0.4, 0.7], method=method) + v2 = interpn((x, y), values._v, [0.4, 0.7], method=method) + xp_assert_close(v1, v2, check_dtype=False) + + @skip_xp_invalid_arg + @parametrize_rgi_interp_methods + def test_matrix_input(self, method): + """np.matrix inputs are allowed for backwards compatibility""" + x = np.linspace(0, 2, 6) + y = np.linspace(0, 1, 7) + + values = matrix(np.random.rand(6, 7)) + + sample = np.random.rand(3, 7, 2) + + v1 = interpn((x, y), values, sample, method=method) + v2 = interpn((x, y), np.asarray(values), sample, method=method) + if method == "quintic": + # https://github.com/scipy/scipy/issues/20472 + xp_assert_close(v1, v2, atol=5e-5, rtol=2e-6) + else: + xp_assert_close(v1, v2) + + def test_length_one_axis(self): + # gh-5890, gh-9524 : length-1 axis is legal for method='linear'. + # Along the axis it's linear interpolation; away from the length-1 + # axis, it's an extrapolation, so fill_value should be used. + + values = np.array([[0.1, 1, 10]]) + xi = np.array([[1, 2.2], [1, 3.2], [1, 3.8]]) + + res = interpn(([1], [2, 3, 4]), values, xi) + wanted = [0.9*0.2 + 0.1, # on [2, 3) it's 0.9*(x-2) + 0.1 + 9*0.2 + 1, # on [3, 4] it's 9*(x-3) + 1 + 9*0.8 + 1] + + xp_assert_close(res, wanted, atol=1e-15) + + # check extrapolation + xi = np.array([[1.1, 2.2], [1.5, 3.2], [-2.3, 3.8]]) + res = interpn(([1], [2, 3, 4]), values, xi, + bounds_error=False, fill_value=None) + + xp_assert_close(res, wanted, atol=1e-15) + + def test_descending_points(self): + def value_func_4d(x, y, z, a): + return 2 * x ** 3 + 3 * y ** 2 - z - a + + x1 = np.array([0, 1, 2, 3]) + x2 = np.array([0, 10, 20, 30]) + x3 = np.array([0, 10, 20, 30]) + x4 = np.array([0, .1, .2, .30]) + points = (x1, x2, x3, x4) + values = value_func_4d( + *np.meshgrid(*points, indexing='ij', sparse=True)) + pts = (0.1, 0.3, np.transpose(np.linspace(0, 30, 4)), + np.linspace(0, 0.3, 4)) + correct_result = interpn(points, values, pts) + + x1_descend = x1[::-1] + x2_descend = x2[::-1] + x3_descend = x3[::-1] + x4_descend = x4[::-1] + points_shuffled = (x1_descend, x2_descend, x3_descend, x4_descend) + values_shuffled = value_func_4d( + *np.meshgrid(*points_shuffled, indexing='ij', sparse=True)) + test_result = interpn(points_shuffled, values_shuffled, pts) + + xp_assert_equal(correct_result, test_result) + + def test_invalid_points_order(self): + x = np.array([.5, 2., 0., 4., 5.5]) # not ascending or descending + y = np.array([.5, 2., 3., 4., 5.5]) + z = np.array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], + [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]]) + xi = np.array([[1, 2.3, 6.3, 0.5, 3.3, 1.2, 3], + [1, 3.3, 1.2, -4.0, 5.0, 1.0, 3]]).T + + match = "must be strictly ascending or descending" + with pytest.raises(ValueError, match=match): + interpn((x, y), z, xi) + + def test_invalid_xi_dimensions(self): + # https://github.com/scipy/scipy/issues/16519 + points = [(0, 1)] + values = [0, 1] + xi = np.ones((1, 1, 3)) + msg = ("The requested sample points xi have dimension 3, but this " + "RegularGridInterpolator has dimension 1") + with assert_raises(ValueError, match=msg): + interpn(points, values, xi) + + def test_readonly_grid(self): + # https://github.com/scipy/scipy/issues/17716 + x = np.linspace(0, 4, 5) + y = np.linspace(0, 5, 6) + z = np.linspace(0, 6, 7) + points = (x, y, z) + values = np.ones((5, 6, 7)) + point = np.array([2.21, 3.12, 1.15]) + for d in points: + d.flags.writeable = False + values.flags.writeable = False + point.flags.writeable = False + interpn(points, values, point) + RegularGridInterpolator(points, values)(point) + + def test_2d_readonly_grid(self): + # https://github.com/scipy/scipy/issues/17716 + # test special 2d case + x = np.linspace(0, 4, 5) + y = np.linspace(0, 5, 6) + points = (x, y) + values = np.ones((5, 6)) + point = np.array([2.21, 3.12]) + for d in points: + d.flags.writeable = False + values.flags.writeable = False + point.flags.writeable = False + interpn(points, values, point) + RegularGridInterpolator(points, values)(point) + + def test_non_c_contiguous_grid(self): + # https://github.com/scipy/scipy/issues/17716 + x = np.linspace(0, 4, 5) + x = np.vstack((x, np.empty_like(x))).T.copy()[:, 0] + assert not x.flags.c_contiguous + y = np.linspace(0, 5, 6) + z = np.linspace(0, 6, 7) + points = (x, y, z) + values = np.ones((5, 6, 7)) + point = np.array([2.21, 3.12, 1.15]) + interpn(points, values, point) + RegularGridInterpolator(points, values)(point) + + @pytest.mark.parametrize("dtype", ['>f8', '` and \ + its inverse. + stft -- Compute the Short Time Fourier Transform (legacy). + istft -- Compute the Inverse Short Time Fourier Transform (legacy). + check_COLA -- Check the COLA constraint for iSTFT reconstruction. + check_NOLA -- Check the NOLA constraint for iSTFT reconstruction. + +Chirp Z-transform and Zoom FFT +============================================ + +.. autosummary:: + :toctree: generated/ + + czt - Chirp z-transform convenience function + zoom_fft - Zoom FFT convenience function + CZT - Chirp z-transform function generator + ZoomFFT - Zoom FFT function generator + czt_points - Output the z-plane points sampled by a chirp z-transform + +The functions are simpler to use than the classes, but are less efficient when +using the same transform on many arrays of the same length, since they +repeatedly generate the same chirp signal with every call. In these cases, +use the classes to create a reusable function instead. + +""" + +from . import _sigtools, windows +from ._waveforms import * +from ._max_len_seq import max_len_seq +from ._upfirdn import upfirdn + +from ._spline import ( + sepfir2d +) + +from ._spline_filters import * +from ._filter_design import * +from ._fir_filter_design import * +from ._ltisys import * +from ._lti_conversion import * +from ._signaltools import * +from ._savitzky_golay import savgol_coeffs, savgol_filter +from ._spectral_py import * +from ._short_time_fft import * +from ._peak_finding import * +from ._czt import * +from .windows import get_window # keep this one in signal namespace + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ( + bsplines, filter_design, fir_filter_design, lti_conversion, ltisys, + spectral, signaltools, waveforms, wavelets, spline +) + +__all__ = [ + s for s in dir() if not s.startswith("_") +] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_arraytools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_arraytools.py new file mode 100644 index 0000000000000000000000000000000000000000..87ce75d8d892a64021da7abc5d149556c22cf983 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_arraytools.py @@ -0,0 +1,264 @@ +""" +Functions for acting on a axis of an array. +""" +import numpy as np + + +def axis_slice(a, start=None, stop=None, step=None, axis=-1): + """Take a slice along axis 'axis' from 'a'. + + Parameters + ---------- + a : numpy.ndarray + The array to be sliced. + start, stop, step : int or None + The slice parameters. + axis : int, optional + The axis of `a` to be sliced. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import axis_slice + >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> axis_slice(a, start=0, stop=1, axis=1) + array([[1], + [4], + [7]]) + >>> axis_slice(a, start=1, axis=0) + array([[4, 5, 6], + [7, 8, 9]]) + + Notes + ----- + The keyword arguments start, stop and step are used by calling + slice(start, stop, step). This implies axis_slice() does not + handle its arguments the exactly the same as indexing. To select + a single index k, for example, use + axis_slice(a, start=k, stop=k+1) + In this case, the length of the axis 'axis' in the result will + be 1; the trivial dimension is not removed. (Use numpy.squeeze() + to remove trivial axes.) + """ + a_slice = [slice(None)] * a.ndim + a_slice[axis] = slice(start, stop, step) + b = a[tuple(a_slice)] + return b + + +def axis_reverse(a, axis=-1): + """Reverse the 1-D slices of `a` along axis `axis`. + + Returns axis_slice(a, step=-1, axis=axis). + """ + return axis_slice(a, step=-1, axis=axis) + + +def odd_ext(x, n, axis=-1): + """ + Odd extension at the boundaries of an array + + Generate a new ndarray by making an odd extension of `x` along an axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import odd_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> odd_ext(a, 2) + array([[-1, 0, 1, 2, 3, 4, 5, 6, 7], + [-4, -1, 0, 1, 4, 9, 16, 23, 28]]) + + Odd extension is a "180 degree rotation" at the endpoints of the original + array: + + >>> t = np.linspace(0, 1.5, 100) + >>> a = 0.9 * np.sin(2 * np.pi * t**2) + >>> b = odd_ext(a, 40) + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='odd extension') + >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original') + >>> plt.legend(loc='best') + >>> plt.show() + """ + if n < 1: + return x + if n > x.shape[axis] - 1: + raise ValueError(("The extension length n (%d) is too big. " + + "It must not exceed x.shape[axis]-1, which is %d.") + % (n, x.shape[axis] - 1)) + left_end = axis_slice(x, start=0, stop=1, axis=axis) + left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis) + right_end = axis_slice(x, start=-1, axis=axis) + right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis) + ext = np.concatenate((2 * left_end - left_ext, + x, + 2 * right_end - right_ext), + axis=axis) + return ext + + +def even_ext(x, n, axis=-1): + """ + Even extension at the boundaries of an array + + Generate a new ndarray by making an even extension of `x` along an axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import even_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> even_ext(a, 2) + array([[ 3, 2, 1, 2, 3, 4, 5, 4, 3], + [ 4, 1, 0, 1, 4, 9, 16, 9, 4]]) + + Even extension is a "mirror image" at the boundaries of the original array: + + >>> t = np.linspace(0, 1.5, 100) + >>> a = 0.9 * np.sin(2 * np.pi * t**2) + >>> b = even_ext(a, 40) + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='even extension') + >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original') + >>> plt.legend(loc='best') + >>> plt.show() + """ + if n < 1: + return x + if n > x.shape[axis] - 1: + raise ValueError(("The extension length n (%d) is too big. " + + "It must not exceed x.shape[axis]-1, which is %d.") + % (n, x.shape[axis] - 1)) + left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis) + right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis) + ext = np.concatenate((left_ext, + x, + right_ext), + axis=axis) + return ext + + +def const_ext(x, n, axis=-1): + """ + Constant extension at the boundaries of an array + + Generate a new ndarray that is a constant extension of `x` along an axis. + + The extension repeats the values at the first and last element of + the axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import const_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> const_ext(a, 2) + array([[ 1, 1, 1, 2, 3, 4, 5, 5, 5], + [ 0, 0, 0, 1, 4, 9, 16, 16, 16]]) + + Constant extension continues with the same values as the endpoints of the + array: + + >>> t = np.linspace(0, 1.5, 100) + >>> a = 0.9 * np.sin(2 * np.pi * t**2) + >>> b = const_ext(a, 40) + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='constant extension') + >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original') + >>> plt.legend(loc='best') + >>> plt.show() + """ + if n < 1: + return x + left_end = axis_slice(x, start=0, stop=1, axis=axis) + ones_shape = [1] * x.ndim + ones_shape[axis] = n + ones = np.ones(ones_shape, dtype=x.dtype) + left_ext = ones * left_end + right_end = axis_slice(x, start=-1, axis=axis) + right_ext = ones * right_end + ext = np.concatenate((left_ext, + x, + right_ext), + axis=axis) + return ext + + +def zero_ext(x, n, axis=-1): + """ + Zero padding at the boundaries of an array + + Generate a new ndarray that is a zero-padded extension of `x` along + an axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the + axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import zero_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> zero_ext(a, 2) + array([[ 0, 0, 1, 2, 3, 4, 5, 0, 0], + [ 0, 0, 0, 1, 4, 9, 16, 0, 0]]) + """ + if n < 1: + return x + zeros_shape = list(x.shape) + zeros_shape[axis] = n + zeros = np.zeros(zeros_shape, dtype=x.dtype) + ext = np.concatenate((zeros, x, zeros), axis=axis) + return ext + + +def _validate_fs(fs, allow_none=True): + """ + Check if the given sampling frequency is a scalar and raises an exception + otherwise. If allow_none is False, also raises an exception for none + sampling rates. Returns the sampling frequency as float or none if the + input is none. + """ + if fs is None: + if not allow_none: + raise ValueError("Sampling frequency can not be none.") + else: # should be float + if not np.isscalar(fs): + raise ValueError("Sampling frequency fs must be a single scalar.") + fs = float(fs) + return fs diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_czt.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_czt.py new file mode 100644 index 0000000000000000000000000000000000000000..c5e5715b460fb2719b68d4694474bc1efc0a9fa0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_czt.py @@ -0,0 +1,575 @@ +# This program is public domain +# Authors: Paul Kienzle, Nadav Horesh +""" +Chirp z-transform. + +We provide two interfaces to the chirp z-transform: an object interface +which precalculates part of the transform and can be applied efficiently +to many different data sets, and a functional interface which is applied +only to the given data set. + +Transforms +---------- + +CZT : callable (x, axis=-1) -> array + Define a chirp z-transform that can be applied to different signals. +ZoomFFT : callable (x, axis=-1) -> array + Define a Fourier transform on a range of frequencies. + +Functions +--------- + +czt : array + Compute the chirp z-transform for a signal. +zoom_fft : array + Compute the Fourier transform on a range of frequencies. +""" + +import cmath +import numbers +import numpy as np +from numpy import pi, arange +from scipy.fft import fft, ifft, next_fast_len + +__all__ = ['czt', 'zoom_fft', 'CZT', 'ZoomFFT', 'czt_points'] + + +def _validate_sizes(n, m): + if n < 1 or not isinstance(n, numbers.Integral): + raise ValueError('Invalid number of CZT data ' + f'points ({n}) specified. ' + 'n must be positive and integer type.') + + if m is None: + m = n + elif m < 1 or not isinstance(m, numbers.Integral): + raise ValueError('Invalid number of CZT output ' + f'points ({m}) specified. ' + 'm must be positive and integer type.') + + return m + + +def czt_points(m, w=None, a=1+0j): + """ + Return the points at which the chirp z-transform is computed. + + Parameters + ---------- + m : int + The number of points desired. + w : complex, optional + The ratio between points in each step. + Defaults to equally spaced points around the entire unit circle. + a : complex, optional + The starting point in the complex plane. Default is 1+0j. + + Returns + ------- + out : ndarray + The points in the Z plane at which `CZT` samples the z-transform, + when called with arguments `m`, `w`, and `a`, as complex numbers. + + See Also + -------- + CZT : Class that creates a callable chirp z-transform function. + czt : Convenience function for quickly calculating CZT. + + Examples + -------- + Plot the points of a 16-point FFT: + + >>> import numpy as np + >>> from scipy.signal import czt_points + >>> points = czt_points(16) + >>> import matplotlib.pyplot as plt + >>> plt.plot(points.real, points.imag, 'o') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal') + >>> plt.show() + + and a 91-point logarithmic spiral that crosses the unit circle: + + >>> m, w, a = 91, 0.995*np.exp(-1j*np.pi*.05), 0.8*np.exp(1j*np.pi/6) + >>> points = czt_points(m, w, a) + >>> plt.plot(points.real, points.imag, 'o') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal') + >>> plt.show() + """ + m = _validate_sizes(1, m) + + k = arange(m) + + a = 1.0 * a # at least float + + if w is None: + # Nothing specified, default to FFT + return a * np.exp(2j * pi * k / m) + else: + # w specified + w = 1.0 * w # at least float + return a * w**-k + + +class CZT: + """ + Create a callable chirp z-transform function. + + Transform to compute the frequency response around a spiral. + Objects of this class are callables which can compute the + chirp z-transform on their inputs. This object precalculates the constant + chirps used in the given transform. + + Parameters + ---------- + n : int + The size of the signal. + m : int, optional + The number of output points desired. Default is `n`. + w : complex, optional + The ratio between points in each step. This must be precise or the + accumulated error will degrade the tail of the output sequence. + Defaults to equally spaced points around the entire unit circle. + a : complex, optional + The starting point in the complex plane. Default is 1+0j. + + Returns + ------- + f : CZT + Callable object ``f(x, axis=-1)`` for computing the chirp z-transform + on `x`. + + See Also + -------- + czt : Convenience function for quickly calculating CZT. + ZoomFFT : Class that creates a callable partial FFT function. + + Notes + ----- + The defaults are chosen such that ``f(x)`` is equivalent to + ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, m)`` is equivalent to + ``fft.fft(x, m)``. + + If `w` does not lie on the unit circle, then the transform will be + around a spiral with exponentially-increasing radius. Regardless, + angle will increase linearly. + + For transforms that do lie on the unit circle, accuracy is better when + using `ZoomFFT`, since any numerical error in `w` is + accumulated for long data lengths, drifting away from the unit circle. + + The chirp z-transform can be faster than an equivalent FFT with + zero padding. Try it with your own array sizes to see. + + However, the chirp z-transform is considerably less precise than the + equivalent zero-padded FFT. + + As this CZT is implemented using the Bluestein algorithm, it can compute + large prime-length Fourier transforms in O(N log N) time, rather than the + O(N**2) time required by the direct DFT calculation. (`scipy.fft` also + uses Bluestein's algorithm'.) + + (The name "chirp z-transform" comes from the use of a chirp in the + Bluestein algorithm. It does not decompose signals into chirps, like + other transforms with "chirp" in the name.) + + References + ---------- + .. [1] Leo I. Bluestein, "A linear filtering approach to the computation + of the discrete Fourier transform," Northeast Electronics Research + and Engineering Meeting Record 10, 218-219 (1968). + .. [2] Rabiner, Schafer, and Rader, "The chirp z-transform algorithm and + its application," Bell Syst. Tech. J. 48, 1249-1292 (1969). + + Examples + -------- + Compute multiple prime-length FFTs: + + >>> from scipy.signal import CZT + >>> import numpy as np + >>> a = np.random.rand(7) + >>> b = np.random.rand(7) + >>> c = np.random.rand(7) + >>> czt_7 = CZT(n=7) + >>> A = czt_7(a) + >>> B = czt_7(b) + >>> C = czt_7(c) + + Display the points at which the FFT is calculated: + + >>> czt_7.points() + array([ 1.00000000+0.j , 0.62348980+0.78183148j, + -0.22252093+0.97492791j, -0.90096887+0.43388374j, + -0.90096887-0.43388374j, -0.22252093-0.97492791j, + 0.62348980-0.78183148j]) + >>> import matplotlib.pyplot as plt + >>> plt.plot(czt_7.points().real, czt_7.points().imag, 'o') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal') + >>> plt.show() + """ + + def __init__(self, n, m=None, w=None, a=1+0j): + m = _validate_sizes(n, m) + + k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2)) + + if w is None: + # Nothing specified, default to FFT-like + w = cmath.exp(-2j*pi/m) + wk2 = np.exp(-(1j * pi * ((k**2) % (2*m))) / m) + else: + # w specified + wk2 = w**(k**2/2.) + + a = 1.0 * a # at least float + + self.w, self.a = w, a + self.m, self.n = m, n + + nfft = next_fast_len(n + m - 1) + self._Awk2 = a**-k[:n] * wk2[:n] + self._nfft = nfft + self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft) + self._wk2 = wk2[:m] + self._yidx = slice(n-1, n+m-1) + + def __call__(self, x, *, axis=-1): + """ + Calculate the chirp z-transform of a signal. + + Parameters + ---------- + x : array + The signal to transform. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + + Returns + ------- + out : ndarray + An array of the same dimensions as `x`, but with the length of the + transformed axis set to `m`. + """ + x = np.asarray(x) + if x.shape[axis] != self.n: + raise ValueError(f"CZT defined for length {self.n}, not " + f"{x.shape[axis]}") + # Calculate transpose coordinates, to allow operation on any given axis + trnsp = np.arange(x.ndim) + trnsp[[axis, -1]] = [-1, axis] + x = x.transpose(*trnsp) + y = ifft(self._Fwk2 * fft(x*self._Awk2, self._nfft)) + y = y[..., self._yidx] * self._wk2 + return y.transpose(*trnsp) + + def points(self): + """ + Return the points at which the chirp z-transform is computed. + """ + return czt_points(self.m, self.w, self.a) + + +class ZoomFFT(CZT): + """ + Create a callable zoom FFT transform function. + + This is a specialization of the chirp z-transform (`CZT`) for a set of + equally-spaced frequencies around the unit circle, used to calculate a + section of the FFT more efficiently than calculating the entire FFT and + truncating. + + Parameters + ---------- + n : int + The size of the signal. + fn : array_like + A length-2 sequence [`f1`, `f2`] giving the frequency range, or a + scalar, for which the range [0, `fn`] is assumed. + m : int, optional + The number of points to evaluate. Default is `n`. + fs : float, optional + The sampling frequency. If ``fs=10`` represented 10 kHz, for example, + then `f1` and `f2` would also be given in kHz. + The default sampling frequency is 2, so `f1` and `f2` should be + in the range [0, 1] to keep the transform below the Nyquist + frequency. + endpoint : bool, optional + If True, `f2` is the last sample. Otherwise, it is not included. + Default is False. + + Returns + ------- + f : ZoomFFT + Callable object ``f(x, axis=-1)`` for computing the zoom FFT on `x`. + + See Also + -------- + zoom_fft : Convenience function for calculating a zoom FFT. + + Notes + ----- + The defaults are chosen such that ``f(x, 2)`` is equivalent to + ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, 2, m)`` is equivalent to + ``fft.fft(x, m)``. + + Sampling frequency is 1/dt, the time step between samples in the + signal `x`. The unit circle corresponds to frequencies from 0 up + to the sampling frequency. The default sampling frequency of 2 + means that `f1`, `f2` values up to the Nyquist frequency are in the + range [0, 1). For `f1`, `f2` values expressed in radians, a sampling + frequency of 2*pi should be used. + + Remember that a zoom FFT can only interpolate the points of the existing + FFT. It cannot help to resolve two separate nearby frequencies. + Frequency resolution can only be increased by increasing acquisition + time. + + These functions are implemented using Bluestein's algorithm (as is + `scipy.fft`). [2]_ + + References + ---------- + .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its + applications", pg 29 (1970) + https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf + .. [2] Leo I. Bluestein, "A linear filtering approach to the computation + of the discrete Fourier transform," Northeast Electronics Research + and Engineering Meeting Record 10, 218-219 (1968). + + Examples + -------- + To plot the transform results use something like the following: + + >>> import numpy as np + >>> from scipy.signal import ZoomFFT + >>> t = np.linspace(0, 1, 1021) + >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t) + >>> f1, f2 = 5, 27 + >>> transform = ZoomFFT(len(x), [f1, f2], len(x), fs=1021) + >>> X = transform(x) + >>> f = np.linspace(f1, f2, len(x)) + >>> import matplotlib.pyplot as plt + >>> plt.plot(f, 20*np.log10(np.abs(X))) + >>> plt.show() + """ + + def __init__(self, n, fn, m=None, *, fs=2, endpoint=False): + m = _validate_sizes(n, m) + + k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2)) + + if np.size(fn) == 2: + f1, f2 = fn + elif np.size(fn) == 1: + f1, f2 = 0.0, fn + else: + raise ValueError('fn must be a scalar or 2-length sequence') + + self.f1, self.f2, self.fs = f1, f2, fs + + if endpoint: + scale = ((f2 - f1) * m) / (fs * (m - 1)) + else: + scale = (f2 - f1) / fs + a = cmath.exp(2j * pi * f1/fs) + wk2 = np.exp(-(1j * pi * scale * k**2) / m) + + self.w = cmath.exp(-2j*pi/m * scale) + self.a = a + self.m, self.n = m, n + + ak = np.exp(-2j * pi * f1/fs * k[:n]) + self._Awk2 = ak * wk2[:n] + + nfft = next_fast_len(n + m - 1) + self._nfft = nfft + self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft) + self._wk2 = wk2[:m] + self._yidx = slice(n-1, n+m-1) + + +def czt(x, m=None, w=None, a=1+0j, *, axis=-1): + """ + Compute the frequency response around a spiral in the Z plane. + + Parameters + ---------- + x : array + The signal to transform. + m : int, optional + The number of output points desired. Default is the length of the + input data. + w : complex, optional + The ratio between points in each step. This must be precise or the + accumulated error will degrade the tail of the output sequence. + Defaults to equally spaced points around the entire unit circle. + a : complex, optional + The starting point in the complex plane. Default is 1+0j. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + + Returns + ------- + out : ndarray + An array of the same dimensions as `x`, but with the length of the + transformed axis set to `m`. + + See Also + -------- + CZT : Class that creates a callable chirp z-transform function. + zoom_fft : Convenience function for partial FFT calculations. + + Notes + ----- + The defaults are chosen such that ``signal.czt(x)`` is equivalent to + ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.czt(x, m)`` is + equivalent to ``fft.fft(x, m)``. + + If the transform needs to be repeated, use `CZT` to construct a + specialized transform function which can be reused without + recomputing constants. + + An example application is in system identification, repeatedly evaluating + small slices of the z-transform of a system, around where a pole is + expected to exist, to refine the estimate of the pole's true location. [1]_ + + References + ---------- + .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its + applications", pg 20 (1970) + https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf + + Examples + -------- + Generate a sinusoid: + + >>> import numpy as np + >>> f1, f2, fs = 8, 10, 200 # Hz + >>> t = np.linspace(0, 1, fs, endpoint=False) + >>> x = np.sin(2*np.pi*t*f2) + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, x) + >>> plt.axis([0, 1, -1.1, 1.1]) + >>> plt.show() + + Its discrete Fourier transform has all of its energy in a single frequency + bin: + + >>> from scipy.fft import rfft, rfftfreq + >>> from scipy.signal import czt, czt_points + >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x))) + >>> plt.margins(0, 0.1) + >>> plt.show() + + However, if the sinusoid is logarithmically-decaying: + + >>> x = np.exp(-t*f1) * np.sin(2*np.pi*t*f2) + >>> plt.plot(t, x) + >>> plt.axis([0, 1, -1.1, 1.1]) + >>> plt.show() + + the DFT will have spectral leakage: + + >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x))) + >>> plt.margins(0, 0.1) + >>> plt.show() + + While the DFT always samples the z-transform around the unit circle, the + chirp z-transform allows us to sample the Z-transform along any + logarithmic spiral, such as a circle with radius smaller than unity: + + >>> M = fs // 2 # Just positive frequencies, like rfft + >>> a = np.exp(-f1/fs) # Starting point of the circle, radius < 1 + >>> w = np.exp(-1j*np.pi/M) # "Step size" of circle + >>> points = czt_points(M + 1, w, a) # M + 1 to include Nyquist + >>> plt.plot(points.real, points.imag, '.') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal'); plt.axis([-1.05, 1.05, -0.05, 1.05]) + >>> plt.show() + + With the correct radius, this transforms the decaying sinusoid (and others + with the same decay rate) without spectral leakage: + + >>> z_vals = czt(x, M + 1, w, a) # Include Nyquist for comparison to rfft + >>> freqs = np.angle(points)*fs/(2*np.pi) # angle = omega, radius = sigma + >>> plt.plot(freqs, abs(z_vals)) + >>> plt.margins(0, 0.1) + >>> plt.show() + """ + x = np.asarray(x) + transform = CZT(x.shape[axis], m=m, w=w, a=a) + return transform(x, axis=axis) + + +def zoom_fft(x, fn, m=None, *, fs=2, endpoint=False, axis=-1): + """ + Compute the DFT of `x` only for frequencies in range `fn`. + + Parameters + ---------- + x : array + The signal to transform. + fn : array_like + A length-2 sequence [`f1`, `f2`] giving the frequency range, or a + scalar, for which the range [0, `fn`] is assumed. + m : int, optional + The number of points to evaluate. The default is the length of `x`. + fs : float, optional + The sampling frequency. If ``fs=10`` represented 10 kHz, for example, + then `f1` and `f2` would also be given in kHz. + The default sampling frequency is 2, so `f1` and `f2` should be + in the range [0, 1] to keep the transform below the Nyquist + frequency. + endpoint : bool, optional + If True, `f2` is the last sample. Otherwise, it is not included. + Default is False. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + + Returns + ------- + out : ndarray + The transformed signal. The Fourier transform will be calculated + at the points f1, f1+df, f1+2df, ..., f2, where df=(f2-f1)/m. + + See Also + -------- + ZoomFFT : Class that creates a callable partial FFT function. + + Notes + ----- + The defaults are chosen such that ``signal.zoom_fft(x, 2)`` is equivalent + to ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.zoom_fft(x, 2, m)`` + is equivalent to ``fft.fft(x, m)``. + + To graph the magnitude of the resulting transform, use:: + + plot(linspace(f1, f2, m, endpoint=False), abs(zoom_fft(x, [f1, f2], m))) + + If the transform needs to be repeated, use `ZoomFFT` to construct + a specialized transform function which can be reused without + recomputing constants. + + Examples + -------- + To plot the transform results use something like the following: + + >>> import numpy as np + >>> from scipy.signal import zoom_fft + >>> t = np.linspace(0, 1, 1021) + >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t) + >>> f1, f2 = 5, 27 + >>> X = zoom_fft(x, [f1, f2], len(x), fs=1021) + >>> f = np.linspace(f1, f2, len(x)) + >>> import matplotlib.pyplot as plt + >>> plt.plot(f, 20*np.log10(np.abs(X))) + >>> plt.show() + """ + x = np.asarray(x) + transform = ZoomFFT(x.shape[axis], fn, m=m, fs=fs, endpoint=endpoint) + return transform(x, axis=axis) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_filter_design.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..0f177247c602cd529a064cc043d8052aa6cbc811 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_filter_design.py @@ -0,0 +1,5663 @@ +"""Filter design.""" +import math +import operator +import warnings + +import numpy as np +from numpy import (atleast_1d, poly, polyval, roots, real, asarray, + resize, pi, absolute, sqrt, tan, log10, + arcsinh, sin, exp, cosh, arccosh, ceil, conjugate, + zeros, sinh, append, concatenate, prod, ones, full, array, + mintypecode) +from numpy.polynomial.polynomial import polyval as npp_polyval +from numpy.polynomial.polynomial import polyvalfromroots + +from scipy import special, optimize, fft as sp_fft +from scipy.special import comb +from scipy._lib._util import float_factorial +from scipy.signal._arraytools import _validate_fs + + +__all__ = ['findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize', + 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign', + 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', + 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord', + 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap', + 'BadCoefficients', 'freqs_zpk', 'freqz_zpk', + 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay', + 'sosfreqz', 'freqz_sos', 'iirnotch', 'iirpeak', 'bilinear_zpk', + 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk', + 'gammatone', 'iircomb'] + + +class BadCoefficients(UserWarning): + """Warning about badly conditioned filter coefficients""" + pass + + +abs = absolute + + +def _is_int_type(x): + """ + Check if input is of a scalar integer type (so ``5`` and ``array(5)`` will + pass, while ``5.0`` and ``array([5])`` will fail. + """ + if np.ndim(x) != 0: + # Older versions of NumPy did not raise for np.array([1]).__index__() + # This is safe to remove when support for those versions is dropped + return False + try: + operator.index(x) + except TypeError: + return False + else: + return True + + +def findfreqs(num, den, N, kind='ba'): + """ + Find array of frequencies for computing the response of an analog filter. + + Parameters + ---------- + num, den : array_like, 1-D + The polynomial coefficients of the numerator and denominator of the + transfer function of the filter or LTI system, where the coefficients + are ordered from highest to lowest degree. Or, the roots of the + transfer function numerator and denominator (i.e., zeroes and poles). + N : int + The length of the array to be computed. + kind : str {'ba', 'zp'}, optional + Specifies whether the numerator and denominator are specified by their + polynomial coefficients ('ba'), or their roots ('zp'). + + Returns + ------- + w : (N,) ndarray + A 1-D array of frequencies, logarithmically spaced. + + Examples + -------- + Find a set of nine frequencies that span the "interesting part" of the + frequency response for the filter with the transfer function + + H(s) = s / (s^2 + 8s + 25) + + >>> from scipy import signal + >>> signal.findfreqs([1, 0], [1, 8, 25], N=9) + array([ 1.00000000e-02, 3.16227766e-02, 1.00000000e-01, + 3.16227766e-01, 1.00000000e+00, 3.16227766e+00, + 1.00000000e+01, 3.16227766e+01, 1.00000000e+02]) + """ + if kind == 'ba': + ep = atleast_1d(roots(den)) + 0j + tz = atleast_1d(roots(num)) + 0j + elif kind == 'zp': + ep = atleast_1d(den) + 0j + tz = atleast_1d(num) + 0j + else: + raise ValueError("input must be one of {'ba', 'zp'}") + + if len(ep) == 0: + ep = atleast_1d(-1000) + 0j + + ez = np.r_[ep[ep.imag >= 0], tz[(np.abs(tz) < 1e5) & (tz.imag >= 0)]] + + integ = np.abs(ez) < 1e-10 + hfreq = np.round(np.log10(np.max(3 * np.abs(ez.real + integ) + + 1.5 * ez.imag)) + 0.5) + lfreq = np.round(np.log10(0.1 * np.min(np.abs((ez + integ).real) + + 2 * ez.imag)) - 0.5) + + w = np.logspace(lfreq, hfreq, N) + return w + + +def freqs(b, a, worN=200, plot=None): + """ + Compute frequency response of analog filter. + + Given the M-order numerator `b` and N-order denominator `a` of an analog + filter, compute its frequency response:: + + b[0]*(jw)**M + b[1]*(jw)**(M-1) + ... + b[M] + H(w) = ---------------------------------------------- + a[0]*(jw)**N + a[1]*(jw)**(N-1) + ... + a[N] + + Parameters + ---------- + b : array_like + Numerator of a linear filter. + a : array_like + Denominator of a linear filter. + worN : {None, int, array_like}, optional + If None, then compute at 200 frequencies around the interesting parts + of the response curve (determined by pole-zero locations). If a single + integer, then compute at that many frequencies. Otherwise, compute the + response at the angular frequencies (e.g., rad/s) given in `worN`. + plot : callable, optional + A callable that takes two arguments. If given, the return parameters + `w` and `h` are passed to plot. Useful for plotting the frequency + response inside `freqs`. + + Returns + ------- + w : ndarray + The angular frequencies at which `h` was computed. + h : ndarray + The frequency response. + + See Also + -------- + freqz : Compute the frequency response of a digital filter. + + Notes + ----- + Using Matplotlib's "plot" function as the callable for `plot` produces + unexpected results, this plots the real part of the complex transfer + function, not the magnitude. Try ``lambda w, h: plot(w, abs(h))``. + + Examples + -------- + >>> from scipy.signal import freqs, iirfilter + >>> import numpy as np + + >>> b, a = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1') + + >>> w, h = freqs(b, a, worN=np.logspace(-1, 2, 1000)) + + >>> import matplotlib.pyplot as plt + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude response [dB]') + >>> plt.grid(True) + >>> plt.show() + + """ + if worN is None: + # For backwards compatibility + w = findfreqs(b, a, 200) + elif _is_int_type(worN): + w = findfreqs(b, a, worN) + else: + w = atleast_1d(worN) + + s = 1j * w + h = polyval(b, s) / polyval(a, s) + if plot is not None: + plot(w, h) + + return w, h + + +def freqs_zpk(z, p, k, worN=200): + """ + Compute frequency response of analog filter. + + Given the zeros `z`, poles `p`, and gain `k` of a filter, compute its + frequency response:: + + (jw-z[0]) * (jw-z[1]) * ... * (jw-z[-1]) + H(w) = k * ---------------------------------------- + (jw-p[0]) * (jw-p[1]) * ... * (jw-p[-1]) + + Parameters + ---------- + z : array_like + Zeroes of a linear filter + p : array_like + Poles of a linear filter + k : scalar + Gain of a linear filter + worN : {None, int, array_like}, optional + If None, then compute at 200 frequencies around the interesting parts + of the response curve (determined by pole-zero locations). If a single + integer, then compute at that many frequencies. Otherwise, compute the + response at the angular frequencies (e.g., rad/s) given in `worN`. + + Returns + ------- + w : ndarray + The angular frequencies at which `h` was computed. + h : ndarray + The frequency response. + + See Also + -------- + freqs : Compute the frequency response of an analog filter in TF form + freqz : Compute the frequency response of a digital filter in TF form + freqz_zpk : Compute the frequency response of a digital filter in ZPK form + + Notes + ----- + .. versionadded:: 0.19.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import freqs_zpk, iirfilter + + >>> z, p, k = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1', + ... output='zpk') + + >>> w, h = freqs_zpk(z, p, k, worN=np.logspace(-1, 2, 1000)) + + >>> import matplotlib.pyplot as plt + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude response [dB]') + >>> plt.grid(True) + >>> plt.show() + + """ + k = np.asarray(k) + if k.size > 1: + raise ValueError('k must be a single scalar gain') + + if worN is None: + # For backwards compatibility + w = findfreqs(z, p, 200, kind='zp') + elif _is_int_type(worN): + w = findfreqs(z, p, worN, kind='zp') + else: + w = worN + + w = atleast_1d(w) + s = 1j * w + num = polyvalfromroots(s, z) + den = polyvalfromroots(s, p) + h = k * num/den + return w, h + + +def freqz(b, a=1, worN=512, whole=False, plot=None, fs=2*pi, + include_nyquist=False): + """ + Compute the frequency response of a digital filter. + + Given the M-order numerator `b` and N-order denominator `a` of a digital + filter, compute its frequency response:: + + jw -jw -jwM + jw B(e ) b[0] + b[1]e + ... + b[M]e + H(e ) = ------ = ----------------------------------- + jw -jw -jwN + A(e ) a[0] + a[1]e + ... + a[N]e + + Parameters + ---------- + b : array_like + Numerator of a linear filter. If `b` has dimension greater than 1, + it is assumed that the coefficients are stored in the first dimension, + and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies + array must be compatible for broadcasting. + a : array_like + Denominator of a linear filter. If `b` has dimension greater than 1, + it is assumed that the coefficients are stored in the first dimension, + and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies + array must be compatible for broadcasting. + worN : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). This is a convenient alternative to:: + + np.linspace(0, fs if whole else fs/2, N, endpoint=include_nyquist) + + Using a number that is fast for FFT computations can result in + faster computations (see Notes). + + If an array_like, compute the response at the frequencies given. + These are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. Ignored if worN is array_like. + plot : callable + A callable that takes two arguments. If given, the return parameters + `w` and `h` are passed to plot. Useful for plotting the frequency + response inside `freqz`. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + include_nyquist : bool, optional + If `whole` is False and `worN` is an integer, setting `include_nyquist` + to True will include the last frequency (Nyquist frequency) and is + otherwise ignored. + + .. versionadded:: 1.5.0 + + Returns + ------- + w : ndarray + The frequencies at which `h` was computed, in the same units as `fs`. + By default, `w` is normalized to the range [0, pi) (radians/sample). + h : ndarray + The frequency response, as complex numbers. + + See Also + -------- + freqz_zpk + freqz_sos + + Notes + ----- + Using Matplotlib's :func:`matplotlib.pyplot.plot` function as the callable + for `plot` produces unexpected results, as this plots the real part of the + complex transfer function, not the magnitude. + Try ``lambda w, h: plot(w, np.abs(h))``. + + A direct computation via (R)FFT is used to compute the frequency response + when the following conditions are met: + + 1. An integer value is given for `worN`. + 2. `worN` is fast to compute via FFT (i.e., + `next_fast_len(worN) ` equals `worN`). + 3. The denominator coefficients are a single value (``a.shape[0] == 1``). + 4. `worN` is at least as long as the numerator coefficients + (``worN >= b.shape[0]``). + 5. If ``b.ndim > 1``, then ``b.shape[-1] == 1``. + + For long FIR filters, the FFT approach can have lower error and be much + faster than the equivalent direct polynomial calculation. + + Examples + -------- + >>> from scipy import signal + >>> import numpy as np + >>> taps, f_c = 80, 1.0 # number of taps and cut-off frequency + >>> b = signal.firwin(taps, f_c, window=('kaiser', 8), fs=2*np.pi) + >>> w, h = signal.freqz(b) + + >>> import matplotlib.pyplot as plt + >>> fig, ax1 = plt.subplots(tight_layout=True) + >>> ax1.set_title(f"Frequency Response of {taps} tap FIR Filter" + + ... f"($f_c={f_c}$ rad/sample)") + >>> ax1.axvline(f_c, color='black', linestyle=':', linewidth=0.8) + >>> ax1.plot(w, 20 * np.log10(abs(h)), 'C0') + >>> ax1.set_ylabel("Amplitude in dB", color='C0') + >>> ax1.set(xlabel="Frequency in rad/sample", xlim=(0, np.pi)) + + >>> ax2 = ax1.twinx() + >>> phase = np.unwrap(np.angle(h)) + >>> ax2.plot(w, phase, 'C1') + >>> ax2.set_ylabel('Phase [rad]', color='C1') + >>> ax2.grid(True) + >>> ax2.axis('tight') + >>> plt.show() + + Broadcasting Examples + + Suppose we have two FIR filters whose coefficients are stored in the + rows of an array with shape (2, 25). For this demonstration, we'll + use random data: + + >>> rng = np.random.default_rng() + >>> b = rng.random((2, 25)) + + To compute the frequency response for these two filters with one call + to `freqz`, we must pass in ``b.T``, because `freqz` expects the first + axis to hold the coefficients. We must then extend the shape with a + trivial dimension of length 1 to allow broadcasting with the array + of frequencies. That is, we pass in ``b.T[..., np.newaxis]``, which has + shape (25, 2, 1): + + >>> w, h = signal.freqz(b.T[..., np.newaxis], worN=1024) + >>> w.shape + (1024,) + >>> h.shape + (2, 1024) + + Now, suppose we have two transfer functions, with the same numerator + coefficients ``b = [0.5, 0.5]``. The coefficients for the two denominators + are stored in the first dimension of the 2-D array `a`:: + + a = [ 1 1 ] + [ -0.25, -0.5 ] + + >>> b = np.array([0.5, 0.5]) + >>> a = np.array([[1, 1], [-0.25, -0.5]]) + + Only `a` is more than 1-D. To make it compatible for + broadcasting with the frequencies, we extend it with a trivial dimension + in the call to `freqz`: + + >>> w, h = signal.freqz(b, a[..., np.newaxis], worN=1024) + >>> w.shape + (1024,) + >>> h.shape + (2, 1024) + + """ + b = atleast_1d(b) + a = atleast_1d(a) + + fs = _validate_fs(fs, allow_none=False) + + if worN is None: + # For backwards compatibility + worN = 512 + + h = None + + if _is_int_type(worN): + N = operator.index(worN) + del worN + if N < 0: + raise ValueError(f'worN must be nonnegative, got {N}') + lastpoint = 2 * pi if whole else pi + # if include_nyquist is true and whole is false, w should + # include end point + w = np.linspace(0, lastpoint, N, + endpoint=include_nyquist and not whole) + n_fft = N if whole else 2 * (N - 1) if include_nyquist else 2 * N + if (a.size == 1 and (b.ndim == 1 or (b.shape[-1] == 1)) + and n_fft >= b.shape[0] + and n_fft > 0): # TODO: review threshold acc. to benchmark? + if np.isrealobj(b) and np.isrealobj(a): + fft_func = sp_fft.rfft + else: + fft_func = sp_fft.fft + h = fft_func(b, n=n_fft, axis=0)[:N] + h /= a + if fft_func is sp_fft.rfft and whole: + # exclude DC and maybe Nyquist (no need to use axis_reverse + # here because we can build reversal with the truncation) + stop = -1 if n_fft % 2 == 1 else -2 + h_flip = slice(stop, 0, -1) + h = np.concatenate((h, h[h_flip].conj())) + if b.ndim > 1: + # Last axis of h has length 1, so drop it. + h = h[..., 0] + # Move the first axis of h to the end. + h = np.moveaxis(h, 0, -1) + else: + w = atleast_1d(worN) + del worN + w = 2*pi*w/fs + + if h is None: # still need to compute using freqs w + zm1 = exp(-1j * w) + h = (npp_polyval(zm1, b, tensor=False) / + npp_polyval(zm1, a, tensor=False)) + + w = w*(fs/(2*pi)) + + if plot is not None: + plot(w, h) + + return w, h + + +def freqz_zpk(z, p, k, worN=512, whole=False, fs=2*pi): + r""" + Compute the frequency response of a digital filter in ZPK form. + + Given the Zeros, Poles and Gain of a digital filter, compute its frequency + response: + + :math:`H(z)=k \prod_i (z - Z[i]) / \prod_j (z - P[j])` + + where :math:`k` is the `gain`, :math:`Z` are the `zeros` and :math:`P` are + the `poles`. + + Parameters + ---------- + z : array_like + Zeroes of a linear filter + p : array_like + Poles of a linear filter + k : scalar + Gain of a linear filter + worN : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). + + If an array_like, compute the response at the frequencies given. + These are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. Ignored if w is array_like. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + + Returns + ------- + w : ndarray + The frequencies at which `h` was computed, in the same units as `fs`. + By default, `w` is normalized to the range [0, pi) (radians/sample). + h : ndarray + The frequency response, as complex numbers. + + See Also + -------- + freqs : Compute the frequency response of an analog filter in TF form + freqs_zpk : Compute the frequency response of an analog filter in ZPK form + freqz : Compute the frequency response of a digital filter in TF form + + Notes + ----- + .. versionadded:: 0.19.0 + + Examples + -------- + Design a 4th-order digital Butterworth filter with cut-off of 100 Hz in a + system with sample rate of 1000 Hz, and plot the frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> z, p, k = signal.butter(4, 100, output='zpk', fs=1000) + >>> w, h = signal.freqz_zpk(z, p, k, fs=1000) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 1, 1) + >>> ax1.set_title('Digital filter frequency response') + + >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b') + >>> ax1.set_ylabel('Amplitude [dB]', color='b') + >>> ax1.set_xlabel('Frequency [Hz]') + >>> ax1.grid(True) + + >>> ax2 = ax1.twinx() + >>> phase = np.unwrap(np.angle(h)) + >>> ax2.plot(w, phase, 'g') + >>> ax2.set_ylabel('Phase [rad]', color='g') + + >>> plt.axis('tight') + >>> plt.show() + + """ + z, p = map(atleast_1d, (z, p)) + + fs = _validate_fs(fs, allow_none=False) + + if whole: + lastpoint = 2 * pi + else: + lastpoint = pi + + if worN is None: + # For backwards compatibility + w = np.linspace(0, lastpoint, 512, endpoint=False) + elif _is_int_type(worN): + w = np.linspace(0, lastpoint, worN, endpoint=False) + else: + w = atleast_1d(worN) + w = 2*pi*w/fs + + zm1 = exp(1j * w) + h = k * polyvalfromroots(zm1, z) / polyvalfromroots(zm1, p) + + w = w*(fs/(2*pi)) + + return w, h + + +def group_delay(system, w=512, whole=False, fs=2*pi): + r"""Compute the group delay of a digital filter. + + The group delay measures by how many samples amplitude envelopes of + various spectral components of a signal are delayed by a filter. + It is formally defined as the derivative of continuous (unwrapped) phase:: + + d jw + D(w) = - -- arg H(e) + dw + + Parameters + ---------- + system : tuple of array_like (b, a) + Numerator and denominator coefficients of a filter transfer function. + w : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). + + If an array_like, compute the delay at the frequencies given. These + are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. Ignored if w is array_like. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + + Returns + ------- + w : ndarray + The frequencies at which group delay was computed, in the same units + as `fs`. By default, `w` is normalized to the range [0, pi) + (radians/sample). + gd : ndarray + The group delay. + + See Also + -------- + freqz : Frequency response of a digital filter + + Notes + ----- + The similar function in MATLAB is called `grpdelay`. + + If the transfer function :math:`H(z)` has zeros or poles on the unit + circle, the group delay at corresponding frequencies is undefined. + When such a case arises the warning is raised and the group delay + is set to 0 at those frequencies. + + For the details of numerical computation of the group delay refer to [1]_ or [2]_. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] Richard G. Lyons, "Understanding Digital Signal Processing, + 3rd edition", p. 830. + .. [2] Julius O. Smith III, "Numerical Computation of Group Delay", + in "Introduction to Digital Filters with Audio Applications", + online book, 2007, + https://ccrma.stanford.edu/~jos/fp/Numerical_Computation_Group_Delay.html + + Examples + -------- + >>> from scipy import signal + >>> b, a = signal.iirdesign(0.1, 0.3, 5, 50, ftype='cheby1') + >>> w, gd = signal.group_delay((b, a)) + + >>> import matplotlib.pyplot as plt + >>> plt.title('Digital filter group delay') + >>> plt.plot(w, gd) + >>> plt.ylabel('Group delay [samples]') + >>> plt.xlabel('Frequency [rad/sample]') + >>> plt.show() + + """ + if w is None: + # For backwards compatibility + w = 512 + + fs = _validate_fs(fs, allow_none=False) + + if _is_int_type(w): + if whole: + w = np.linspace(0, 2 * pi, w, endpoint=False) + else: + w = np.linspace(0, pi, w, endpoint=False) + else: + w = np.atleast_1d(w) + w = 2*pi*w/fs + + b, a = map(np.atleast_1d, system) + c = np.convolve(b, conjugate(a[::-1])) + cr = c * np.arange(c.size) + z = np.exp(-1j * w) + num = np.polyval(cr[::-1], z) + den = np.polyval(c[::-1], z) + gd = np.real(num / den) - a.size + 1 + singular = ~np.isfinite(gd) + near_singular = np.absolute(den) < 10 * EPSILON + + if np.any(singular): + gd[singular] = 0 + warnings.warn( + "The group delay is singular at frequencies " + f"[{', '.join(f'{ws:.3f}' for ws in w[singular])}], setting to 0", + stacklevel=2 + ) + + elif np.any(near_singular): + warnings.warn( + "The filter's denominator is extremely small at frequencies " + f"[{', '.join(f'{ws:.3f}' for ws in w[near_singular])}], " + "around which a singularity may be present", + stacklevel=2 + ) + + w = w*(fs/(2*pi)) + + return w, gd + + +def _validate_sos(sos): + """Helper to validate a SOS input""" + sos = np.atleast_2d(sos) + if sos.ndim != 2: + raise ValueError('sos array must be 2D') + n_sections, m = sos.shape + if m != 6: + raise ValueError('sos array must be shape (n_sections, 6)') + if not (sos[:, 3] == 1).all(): + raise ValueError('sos[:, 3] should be all ones') + return sos, n_sections + + +def freqz_sos(sos, worN=512, whole=False, fs=2*pi): + r""" + Compute the frequency response of a digital filter in SOS format. + + Given `sos`, an array with shape (n, 6) of second order sections of + a digital filter, compute the frequency response of the system function:: + + B0(z) B1(z) B{n-1}(z) + H(z) = ----- * ----- * ... * --------- + A0(z) A1(z) A{n-1}(z) + + for z = exp(omega*1j), where B{k}(z) and A{k}(z) are numerator and + denominator of the transfer function of the k-th second order section. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. Each row corresponds to a second-order + section, with the first three columns providing the numerator + coefficients and the last three providing the denominator + coefficients. + worN : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). Using a number that is fast for FFT computations can result + in faster computations (see Notes of `freqz`). + + If an array_like, compute the response at the frequencies given (must + be 1-D). These are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + + Returns + ------- + w : ndarray + The frequencies at which `h` was computed, in the same units as `fs`. + By default, `w` is normalized to the range [0, pi) (radians/sample). + h : ndarray + The frequency response, as complex numbers. + + See Also + -------- + freqz, sosfilt + + Notes + ----- + .. versionadded:: 0.19.0 + + Examples + -------- + Design a 15th-order bandpass filter in SOS format. + + >>> from scipy import signal + >>> import numpy as np + >>> sos = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass', + ... output='sos') + + Compute the frequency response at 1500 points from DC to Nyquist. + + >>> w, h = signal.freqz_sos(sos, worN=1500) + + Plot the response. + + >>> import matplotlib.pyplot as plt + >>> plt.subplot(2, 1, 1) + >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5)) + >>> plt.plot(w/np.pi, db) + >>> plt.ylim(-75, 5) + >>> plt.grid(True) + >>> plt.yticks([0, -20, -40, -60]) + >>> plt.ylabel('Gain [dB]') + >>> plt.title('Frequency Response') + >>> plt.subplot(2, 1, 2) + >>> plt.plot(w/np.pi, np.angle(h)) + >>> plt.grid(True) + >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi], + ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$']) + >>> plt.ylabel('Phase [rad]') + >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)') + >>> plt.show() + + If the same filter is implemented as a single transfer function, + numerical error corrupts the frequency response: + + >>> b, a = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass', + ... output='ba') + >>> w, h = signal.freqz(b, a, worN=1500) + >>> plt.subplot(2, 1, 1) + >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5)) + >>> plt.plot(w/np.pi, db) + >>> plt.ylim(-75, 5) + >>> plt.grid(True) + >>> plt.yticks([0, -20, -40, -60]) + >>> plt.ylabel('Gain [dB]') + >>> plt.title('Frequency Response') + >>> plt.subplot(2, 1, 2) + >>> plt.plot(w/np.pi, np.angle(h)) + >>> plt.grid(True) + >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi], + ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$']) + >>> plt.ylabel('Phase [rad]') + >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)') + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=False) + + sos, n_sections = _validate_sos(sos) + if n_sections == 0: + raise ValueError('Cannot compute frequencies with no sections') + h = 1. + for row in sos: + w, rowh = freqz(row[:3], row[3:], worN=worN, whole=whole, fs=fs) + h *= rowh + return w, h + + +def sosfreqz(*args, **kwargs): + """ + Compute the frequency response of a digital filter in SOS format. + + .. warning:: This function is an alias, provided for backward + compatibility. New code should use the function + :func:`scipy.signal.freqz_sos`. + """ + return freqz_sos(*args, **kwargs) + + +def _cplxreal(z, tol=None): + """ + Split into complex and real parts, combining conjugate pairs. + + The 1-D input vector `z` is split up into its complex (`zc`) and real (`zr`) + elements. Every complex element must be part of a complex-conjugate pair, + which are combined into a single number (with positive imaginary part) in + the output. Two complex numbers are considered a conjugate pair if their + real and imaginary parts differ in magnitude by less than ``tol * abs(z)``. + + Parameters + ---------- + z : array_like + Vector of complex numbers to be sorted and split + tol : float, optional + Relative tolerance for testing realness and conjugate equality. + Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for + float64) + + Returns + ------- + zc : ndarray + Complex elements of `z`, with each pair represented by a single value + having positive imaginary part, sorted first by real part, and then + by magnitude of imaginary part. The pairs are averaged when combined + to reduce error. + zr : ndarray + Real elements of `z` (those having imaginary part less than + `tol` times their magnitude), sorted by value. + + Raises + ------ + ValueError + If there are any complex numbers in `z` for which a conjugate + cannot be found. + + See Also + -------- + _cplxpair + + Examples + -------- + >>> from scipy.signal._filter_design import _cplxreal + >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j] + >>> zc, zr = _cplxreal(a) + >>> print(zc) + [ 1.+1.j 2.+1.j 2.+1.j 2.+2.j] + >>> print(zr) + [ 1. 3. 4.] + """ + + z = atleast_1d(z) + if z.size == 0: + return z, z + elif z.ndim != 1: + raise ValueError('_cplxreal only accepts 1-D input') + + if tol is None: + # Get tolerance from dtype of input + tol = 100 * np.finfo((1.0 * z).dtype).eps + + # Sort by real part, magnitude of imaginary part (speed up further sorting) + z = z[np.lexsort((abs(z.imag), z.real))] + + # Split reals from conjugate pairs + real_indices = abs(z.imag) <= tol * abs(z) + zr = z[real_indices].real + + if len(zr) == len(z): + # Input is entirely real + return array([]), zr + + # Split positive and negative halves of conjugates + z = z[~real_indices] + zp = z[z.imag > 0] + zn = z[z.imag < 0] + + if len(zp) != len(zn): + raise ValueError('Array contains complex value with no matching ' + 'conjugate.') + + # Find runs of (approximately) the same real part + same_real = np.diff(zp.real) <= tol * abs(zp[:-1]) + diffs = np.diff(concatenate(([0], same_real, [0]))) + run_starts = np.nonzero(diffs > 0)[0] + run_stops = np.nonzero(diffs < 0)[0] + + # Sort each run by their imaginary parts + for i in range(len(run_starts)): + start = run_starts[i] + stop = run_stops[i] + 1 + for chunk in (zp[start:stop], zn[start:stop]): + chunk[...] = chunk[np.lexsort([abs(chunk.imag)])] + + # Check that negatives match positives + if any(abs(zp - zn.conj()) > tol * abs(zn)): + raise ValueError('Array contains complex value with no matching ' + 'conjugate.') + + # Average out numerical inaccuracy in real vs imag parts of pairs + zc = (zp + zn.conj()) / 2 + + return zc, zr + + +def _cplxpair(z, tol=None): + """ + Sort into pairs of complex conjugates. + + Complex conjugates in `z` are sorted by increasing real part. In each + pair, the number with negative imaginary part appears first. + + If pairs have identical real parts, they are sorted by increasing + imaginary magnitude. + + Two complex numbers are considered a conjugate pair if their real and + imaginary parts differ in magnitude by less than ``tol * abs(z)``. The + pairs are forced to be exact complex conjugates by averaging the positive + and negative values. + + Purely real numbers are also sorted, but placed after the complex + conjugate pairs. A number is considered real if its imaginary part is + smaller than `tol` times the magnitude of the number. + + Parameters + ---------- + z : array_like + 1-D input array to be sorted. + tol : float, optional + Relative tolerance for testing realness and conjugate equality. + Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for + float64) + + Returns + ------- + y : ndarray + Complex conjugate pairs followed by real numbers. + + Raises + ------ + ValueError + If there are any complex numbers in `z` for which a conjugate + cannot be found. + + See Also + -------- + _cplxreal + + Examples + -------- + >>> from scipy.signal._filter_design import _cplxpair + >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j] + >>> z = _cplxpair(a) + >>> print(z) + [ 1.-1.j 1.+1.j 2.-1.j 2.+1.j 2.-1.j 2.+1.j 2.-2.j 2.+2.j 1.+0.j + 3.+0.j 4.+0.j] + """ + + z = atleast_1d(z) + if z.size == 0 or np.isrealobj(z): + return np.sort(z) + + if z.ndim != 1: + raise ValueError('z must be 1-D') + + zc, zr = _cplxreal(z, tol) + + # Interleave complex values and their conjugates, with negative imaginary + # parts first in each pair + zc = np.dstack((zc.conj(), zc)).flatten() + z = np.append(zc, zr) + return z + + +def tf2zpk(b, a): + r"""Return zero, pole, gain (z, p, k) representation from a numerator, + denominator representation of a linear filter. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + + Returns + ------- + z : ndarray + Zeros of the transfer function. + p : ndarray + Poles of the transfer function. + k : float + System gain. + + Notes + ----- + If some values of `b` are too close to 0, they are removed. In that case, + a BadCoefficients warning is emitted. + + The `b` and `a` arrays are interpreted as coefficients for positive, + descending powers of the transfer function variable. So the inputs + :math:`b = [b_0, b_1, ..., b_M]` and :math:`a =[a_0, a_1, ..., a_N]` + can represent an analog filter of the form: + + .. math:: + + H(s) = \frac + {b_0 s^M + b_1 s^{(M-1)} + \cdots + b_M} + {a_0 s^N + a_1 s^{(N-1)} + \cdots + a_N} + + or a discrete-time filter of the form: + + .. math:: + + H(z) = \frac + {b_0 z^M + b_1 z^{(M-1)} + \cdots + b_M} + {a_0 z^N + a_1 z^{(N-1)} + \cdots + a_N} + + This "positive powers" form is found more commonly in controls + engineering. If `M` and `N` are equal (which is true for all filters + generated by the bilinear transform), then this happens to be equivalent + to the "negative powers" discrete-time form preferred in DSP: + + .. math:: + + H(z) = \frac + {b_0 + b_1 z^{-1} + \cdots + b_M z^{-M}} + {a_0 + a_1 z^{-1} + \cdots + a_N z^{-N}} + + Although this is true for common filters, remember that this is not true + in the general case. If `M` and `N` are not equal, the discrete-time + transfer function coefficients must first be converted to the "positive + powers" form before finding the poles and zeros. + + Examples + -------- + Find the zeroes, poles and gain of + a filter with the transfer function + + .. math:: + + H(s) = \frac{3s^2}{s^2 + 5s + 13} + + >>> from scipy.signal import tf2zpk + >>> tf2zpk([3, 0, 0], [1, 5, 13]) + ( array([ 0. , 0. ]), + array([ -2.5+2.59807621j , -2.5-2.59807621j]), + 3.0) + """ + b, a = normalize(b, a) + b = (b + 0.0) / a[0] + a = (a + 0.0) / a[0] + k = b[0] + b /= b[0] + z = roots(b) + p = roots(a) + return z, p, k + + +def zpk2tf(z, p, k): + r""" + Return polynomial transfer function representation from zeros and poles + + Parameters + ---------- + z : array_like + Zeros of the transfer function. + p : array_like + Poles of the transfer function. + k : float + System gain. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + Examples + -------- + Find the polynomial representation of a transfer function H(s) + using its 'zpk' (Zero-Pole-Gain) representation. + + .. math:: + + H(z) = 5 \frac + { (s - 2)(s - 6) } + { (s - 1)(s - 8) } + + >>> from scipy.signal import zpk2tf + >>> z = [2, 6] + >>> p = [1, 8] + >>> k = 5 + >>> zpk2tf(z, p, k) + ( array([ 5., -40., 60.]), array([ 1., -9., 8.])) + """ + z = atleast_1d(z) + k = atleast_1d(k) + if len(z.shape) > 1: + temp = poly(z[0]) + b = np.empty((z.shape[0], z.shape[1] + 1), temp.dtype.char) + if len(k) == 1: + k = [k[0]] * z.shape[0] + for i in range(z.shape[0]): + b[i] = k[i] * poly(z[i]) + else: + b = k * poly(z) + a = atleast_1d(poly(p)) + + # Use real output if possible. Copied from np.poly, since + # we can't depend on a specific version of numpy. + if issubclass(b.dtype.type, np.complexfloating): + # if complex roots are all complex conjugates, the roots are real. + roots = np.asarray(z, complex) + pos_roots = np.compress(roots.imag > 0, roots) + neg_roots = np.conjugate(np.compress(roots.imag < 0, roots)) + if len(pos_roots) == len(neg_roots): + if np.all(np.sort_complex(neg_roots) == np.sort_complex(pos_roots)): + b = b.real.copy() + + if issubclass(a.dtype.type, np.complexfloating): + # if complex roots are all complex conjugates, the roots are real. + roots = np.asarray(p, complex) + pos_roots = np.compress(roots.imag > 0, roots) + neg_roots = np.conjugate(np.compress(roots.imag < 0, roots)) + if len(pos_roots) == len(neg_roots): + if np.all(np.sort_complex(neg_roots) == np.sort_complex(pos_roots)): + a = a.real.copy() + + return b, a + + +def tf2sos(b, a, pairing=None, *, analog=False): + r""" + Return second-order sections from transfer function representation + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional + The method to use to combine pairs of poles and zeros into sections. + See `zpk2sos` for information and restrictions on `pairing` and + `analog` arguments. + analog : bool, optional + If True, system is analog, otherwise discrete. + + .. versionadded:: 1.8.0 + + Returns + ------- + sos : ndarray + Array of second-order filter coefficients, with shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + See Also + -------- + zpk2sos, sosfilt + + Notes + ----- + It is generally discouraged to convert from TF to SOS format, since doing + so usually will not improve numerical precision errors. Instead, consider + designing filters in ZPK format and converting directly to SOS. TF is + converted to SOS by first converting to ZPK format, then converting + ZPK to SOS. + + .. versionadded:: 0.16.0 + + Examples + -------- + Find the 'sos' (second-order sections) of the transfer function H(s) + using its polynomial representation. + + .. math:: + + H(s) = \frac{s^2 - 3.5s - 2}{s^4 + 3s^3 - 15s^2 - 19s + 30} + + >>> from scipy.signal import tf2sos + >>> tf2sos([1, -3.5, -2], [1, 3, -15, -19, 30], analog=True) + array([[ 0. , 0. , 1. , 1. , 2. , -15. ], + [ 1. , -3.5, -2. , 1. , 1. , -2. ]]) + """ + return zpk2sos(*tf2zpk(b, a), pairing=pairing, analog=analog) + + +def sos2tf(sos): + r""" + Return a single transfer function from a series of second-order sections + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + Notes + ----- + .. versionadded:: 0.16.0 + + Examples + -------- + Find the polynomial representation of an elliptic filter + using its 'sos' (second-order sections) format. + + >>> from scipy.signal import sos2tf + >>> from scipy import signal + >>> sos = signal.ellip(1, 0.001, 50, 0.1, output='sos') + >>> sos2tf(sos) + ( array([0.91256522, 0.91256522, 0. ]), + array([1. , 0.82513043, 0. ])) + """ + sos = np.asarray(sos) + result_type = sos.dtype + if result_type.kind in 'bui': + result_type = np.float64 + + b = np.array([1], dtype=result_type) + a = np.array([1], dtype=result_type) + n_sections = sos.shape[0] + for section in range(n_sections): + b = np.polymul(b, sos[section, :3]) + a = np.polymul(a, sos[section, 3:]) + return b, a + + +def sos2zpk(sos): + """ + Return zeros, poles, and gain of a series of second-order sections + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + Returns + ------- + z : ndarray + Zeros of the transfer function. + p : ndarray + Poles of the transfer function. + k : float + System gain. + + Notes + ----- + The number of zeros and poles returned will be ``n_sections * 2`` + even if some of these are (effectively) zero. + + .. versionadded:: 0.16.0 + """ + sos = np.asarray(sos) + n_sections = sos.shape[0] + z = np.zeros(n_sections*2, np.complex128) + p = np.zeros(n_sections*2, np.complex128) + k = 1. + for section in range(n_sections): + zpk = tf2zpk(sos[section, :3], sos[section, 3:]) + z[2*section:2*section+len(zpk[0])] = zpk[0] + p[2*section:2*section+len(zpk[1])] = zpk[1] + k *= zpk[2] + return z, p, k + + +def _nearest_real_complex_idx(fro, to, which): + """Get the next closest real or complex element based on distance""" + assert which in ('real', 'complex', 'any') + order = np.argsort(np.abs(fro - to)) + if which == 'any': + return order[0] + else: + mask = np.isreal(fro[order]) + if which == 'complex': + mask = ~mask + return order[np.nonzero(mask)[0][0]] + + +def _single_zpksos(z, p, k): + """Create one second-order section from up to two zeros and poles""" + sos = np.zeros(6) + b, a = zpk2tf(z, p, k) + sos[3-len(b):3] = b + sos[6-len(a):6] = a + return sos + + +def zpk2sos(z, p, k, pairing=None, *, analog=False): + """Return second-order sections from zeros, poles, and gain of a system + + Parameters + ---------- + z : array_like + Zeros of the transfer function. + p : array_like + Poles of the transfer function. + k : float + System gain. + pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional + The method to use to combine pairs of poles and zeros into sections. + If analog is False and pairing is None, pairing is set to 'nearest'; + if analog is True, pairing must be 'minimal', and is set to that if + it is None. + analog : bool, optional + If True, system is analog, otherwise discrete. + + .. versionadded:: 1.8.0 + + Returns + ------- + sos : ndarray + Array of second-order filter coefficients, with shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + See Also + -------- + sosfilt + + Notes + ----- + The algorithm used to convert ZPK to SOS format is designed to + minimize errors due to numerical precision issues. The pairing + algorithm attempts to minimize the peak gain of each biquadratic + section. This is done by pairing poles with the nearest zeros, starting + with the poles closest to the unit circle for discrete-time systems, and + poles closest to the imaginary axis for continuous-time systems. + + ``pairing='minimal'`` outputs may not be suitable for `sosfilt`, + and ``analog=True`` outputs will never be suitable for `sosfilt`. + + *Algorithms* + + The steps in the ``pairing='nearest'``, ``pairing='keep_odd'``, + and ``pairing='minimal'`` algorithms are mostly shared. The + ``'nearest'`` algorithm attempts to minimize the peak gain, while + ``'keep_odd'`` minimizes peak gain under the constraint that + odd-order systems should retain one section as first order. + ``'minimal'`` is similar to ``'keep_odd'``, but no additional + poles or zeros are introduced + + The algorithm steps are as follows: + + As a pre-processing step for ``pairing='nearest'``, + ``pairing='keep_odd'``, add poles or zeros to the origin as + necessary to obtain the same number of poles and zeros for + pairing. If ``pairing == 'nearest'`` and there are an odd number + of poles, add an additional pole and a zero at the origin. + + The following steps are then iterated over until no more poles or + zeros remain: + + 1. Take the (next remaining) pole (complex or real) closest to the + unit circle (or imaginary axis, for ``analog=True``) to + begin a new filter section. + + 2. If the pole is real and there are no other remaining real poles [#]_, + add the closest real zero to the section and leave it as a first + order section. Note that after this step we are guaranteed to be + left with an even number of real poles, complex poles, real zeros, + and complex zeros for subsequent pairing iterations. + + 3. Else: + + 1. If the pole is complex and the zero is the only remaining real + zero*, then pair the pole with the *next* closest zero + (guaranteed to be complex). This is necessary to ensure that + there will be a real zero remaining to eventually create a + first-order section (thus keeping the odd order). + + 2. Else pair the pole with the closest remaining zero (complex or + real). + + 3. Proceed to complete the second-order section by adding another + pole and zero to the current pole and zero in the section: + + 1. If the current pole and zero are both complex, add their + conjugates. + + 2. Else if the pole is complex and the zero is real, add the + conjugate pole and the next closest real zero. + + 3. Else if the pole is real and the zero is complex, add the + conjugate zero and the real pole closest to those zeros. + + 4. Else (we must have a real pole and real zero) add the next + real pole closest to the unit circle, and then add the real + zero closest to that pole. + + .. [#] This conditional can only be met for specific odd-order inputs + with the ``pairing = 'keep_odd'`` or ``'minimal'`` methods. + + .. versionadded:: 0.16.0 + + Examples + -------- + + Design a 6th order low-pass elliptic digital filter for a system with a + sampling rate of 8000 Hz that has a pass-band corner frequency of + 1000 Hz. The ripple in the pass-band should not exceed 0.087 dB, and + the attenuation in the stop-band should be at least 90 dB. + + In the following call to `ellip`, we could use ``output='sos'``, + but for this example, we'll use ``output='zpk'``, and then convert + to SOS format with `zpk2sos`: + + >>> from scipy import signal + >>> import numpy as np + >>> z, p, k = signal.ellip(6, 0.087, 90, 1000/(0.5*8000), output='zpk') + + Now convert to SOS format. + + >>> sos = signal.zpk2sos(z, p, k) + + The coefficients of the numerators of the sections: + + >>> sos[:, :3] + array([[0.0014152 , 0.00248677, 0.0014152 ], + [1. , 0.72976874, 1. ], + [1. , 0.17607852, 1. ]]) + + The symmetry in the coefficients occurs because all the zeros are on the + unit circle. + + The coefficients of the denominators of the sections: + + >>> sos[:, 3:] + array([[ 1. , -1.32544025, 0.46989976], + [ 1. , -1.26118294, 0.62625924], + [ 1. , -1.2570723 , 0.8619958 ]]) + + The next example shows the effect of the `pairing` option. We have a + system with three poles and three zeros, so the SOS array will have + shape (2, 6). The means there is, in effect, an extra pole and an extra + zero at the origin in the SOS representation. + + >>> z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j]) + >>> p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j]) + + With ``pairing='nearest'`` (the default), we obtain + + >>> signal.zpk2sos(z1, p1, 1) + array([[ 1. , 1. , 0.5 , 1. , -0.75, 0. ], + [ 1. , 1. , 0. , 1. , -1.6 , 0.65]]) + + The first section has the zeros {-0.5-0.05j, -0.5+0.5j} and the poles + {0, 0.75}, and the second section has the zeros {-1, 0} and poles + {0.8+0.1j, 0.8-0.1j}. Note that the extra pole and zero at the origin + have been assigned to different sections. + + With ``pairing='keep_odd'``, we obtain: + + >>> signal.zpk2sos(z1, p1, 1, pairing='keep_odd') + array([[ 1. , 1. , 0. , 1. , -0.75, 0. ], + [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]]) + + The extra pole and zero at the origin are in the same section. + The first section is, in effect, a first-order section. + + With ``pairing='minimal'``, the first-order section doesn't have + the extra pole and zero at the origin: + + >>> signal.zpk2sos(z1, p1, 1, pairing='minimal') + array([[ 0. , 1. , 1. , 0. , 1. , -0.75], + [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]]) + + """ + # TODO in the near future: + # 1. Add SOS capability to `filtfilt`, `freqz`, etc. somehow (#3259). + # 2. Make `decimate` use `sosfilt` instead of `lfilter`. + # 3. Make sosfilt automatically simplify sections to first order + # when possible. Note this might make `sosfiltfilt` a bit harder (ICs). + # 4. Further optimizations of the section ordering / pole-zero pairing. + # See the wiki for other potential issues. + + if pairing is None: + pairing = 'minimal' if analog else 'nearest' + + valid_pairings = ['nearest', 'keep_odd', 'minimal'] + if pairing not in valid_pairings: + raise ValueError(f'pairing must be one of {valid_pairings}, not {pairing}') + + if analog and pairing != 'minimal': + raise ValueError('for analog zpk2sos conversion, ' + 'pairing must be "minimal"') + + if len(z) == len(p) == 0: + if not analog: + return np.array([[k, 0., 0., 1., 0., 0.]]) + else: + return np.array([[0., 0., k, 0., 0., 1.]]) + + if pairing != 'minimal': + # ensure we have the same number of poles and zeros, and make copies + p = np.concatenate((p, np.zeros(max(len(z) - len(p), 0)))) + z = np.concatenate((z, np.zeros(max(len(p) - len(z), 0)))) + n_sections = (max(len(p), len(z)) + 1) // 2 + + if len(p) % 2 == 1 and pairing == 'nearest': + p = np.concatenate((p, [0.])) + z = np.concatenate((z, [0.])) + assert len(p) == len(z) + else: + if len(p) < len(z): + raise ValueError('for analog zpk2sos conversion, ' + 'must have len(p)>=len(z)') + + n_sections = (len(p) + 1) // 2 + + # Ensure we have complex conjugate pairs + # (note that _cplxreal only gives us one element of each complex pair): + z = np.concatenate(_cplxreal(z)) + p = np.concatenate(_cplxreal(p)) + if not np.isreal(k): + raise ValueError('k must be real') + k = k.real + + if not analog: + # digital: "worst" is the closest to the unit circle + def idx_worst(p): + return np.argmin(np.abs(1 - np.abs(p))) + else: + # analog: "worst" is the closest to the imaginary axis + def idx_worst(p): + return np.argmin(np.abs(np.real(p))) + + sos = np.zeros((n_sections, 6)) + + # Construct the system, reversing order so the "worst" are last + for si in range(n_sections-1, -1, -1): + # Select the next "worst" pole + p1_idx = idx_worst(p) + p1 = p[p1_idx] + p = np.delete(p, p1_idx) + + # Pair that pole with a zero + + if np.isreal(p1) and np.isreal(p).sum() == 0: + # Special case (1): last remaining real pole + if pairing != 'minimal': + z1_idx = _nearest_real_complex_idx(z, p1, 'real') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + sos[si] = _single_zpksos([z1, 0], [p1, 0], 1) + elif len(z) > 0: + z1_idx = _nearest_real_complex_idx(z, p1, 'real') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + sos[si] = _single_zpksos([z1], [p1], 1) + else: + sos[si] = _single_zpksos([], [p1], 1) + + elif (len(p) + 1 == len(z) + and not np.isreal(p1) + and np.isreal(p).sum() == 1 + and np.isreal(z).sum() == 1): + + # Special case (2): there's one real pole and one real zero + # left, and an equal number of poles and zeros to pair up. + # We *must* pair with a complex zero + + z1_idx = _nearest_real_complex_idx(z, p1, 'complex') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + sos[si] = _single_zpksos([z1, z1.conj()], [p1, p1.conj()], 1) + + else: + if np.isreal(p1): + prealidx = np.flatnonzero(np.isreal(p)) + p2_idx = prealidx[idx_worst(p[prealidx])] + p2 = p[p2_idx] + p = np.delete(p, p2_idx) + else: + p2 = p1.conj() + + # find closest zero + if len(z) > 0: + z1_idx = _nearest_real_complex_idx(z, p1, 'any') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + + if not np.isreal(z1): + sos[si] = _single_zpksos([z1, z1.conj()], [p1, p2], 1) + else: + if len(z) > 0: + z2_idx = _nearest_real_complex_idx(z, p1, 'real') + z2 = z[z2_idx] + assert np.isreal(z2) + z = np.delete(z, z2_idx) + sos[si] = _single_zpksos([z1, z2], [p1, p2], 1) + else: + sos[si] = _single_zpksos([z1], [p1, p2], 1) + else: + # no more zeros + sos[si] = _single_zpksos([], [p1, p2], 1) + + assert len(p) == len(z) == 0 # we've consumed all poles and zeros + del p, z + + # put gain in first sos + sos[0][:3] *= k + return sos + + +def _align_nums(nums): + """Aligns the shapes of multiple numerators. + + Given an array of numerator coefficient arrays [[a_1, a_2,..., + a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator + arrays with zero's so that all numerators have the same length. Such + alignment is necessary for functions like 'tf2ss', which needs the + alignment when dealing with SIMO transfer functions. + + Parameters + ---------- + nums: array_like + Numerator or list of numerators. Not necessarily with same length. + + Returns + ------- + nums: array + The numerator. If `nums` input was a list of numerators then a 2-D + array with padded zeros for shorter numerators is returned. Otherwise + returns ``np.asarray(nums)``. + """ + try: + # The statement can throw a ValueError if one + # of the numerators is a single digit and another + # is array-like e.g. if nums = [5, [1, 2, 3]] + nums = asarray(nums) + + if not np.issubdtype(nums.dtype, np.number): + raise ValueError("dtype of numerator is non-numeric") + + return nums + + except ValueError: + nums = [np.atleast_1d(num) for num in nums] + max_width = max(num.size for num in nums) + + # pre-allocate + aligned_nums = np.zeros((len(nums), max_width)) + + # Create numerators with padded zeros + for index, num in enumerate(nums): + aligned_nums[index, -num.size:] = num + + return aligned_nums + + +def normalize(b, a): + """Normalize numerator/denominator of a continuous-time transfer function. + + If values of `b` are too close to 0, they are removed. In that case, a + BadCoefficients warning is emitted. + + Parameters + ---------- + b: array_like + Numerator of the transfer function. Can be a 2-D array to normalize + multiple transfer functions. + a: array_like + Denominator of the transfer function. At most 1-D. + + Returns + ------- + num: array + The numerator of the normalized transfer function. At least a 1-D + array. A 2-D array if the input `num` is a 2-D array. + den: 1-D array + The denominator of the normalized transfer function. + + Notes + ----- + Coefficients for both the numerator and denominator should be specified in + descending exponent order (e.g., ``s^2 + 3s + 5`` would be represented as + ``[1, 3, 5]``). + + Examples + -------- + >>> from scipy.signal import normalize + + Normalize the coefficients of the transfer function + ``(3*s^2 - 2*s + 5) / (2*s^2 + 3*s + 1)``: + + >>> b = [3, -2, 5] + >>> a = [2, 3, 1] + >>> normalize(b, a) + (array([ 1.5, -1. , 2.5]), array([1. , 1.5, 0.5])) + + A warning is generated if, for example, the first coefficient of + `b` is 0. In the following example, the result is as expected: + + >>> import warnings + >>> with warnings.catch_warnings(record=True) as w: + ... num, den = normalize([0, 3, 6], [2, -5, 4]) + + >>> num + array([1.5, 3. ]) + >>> den + array([ 1. , -2.5, 2. ]) + + >>> print(w[0].message) + Badly conditioned filter coefficients (numerator): the results may be meaningless + + """ + num, den = b, a + + den = np.atleast_1d(den) + num = np.atleast_2d(_align_nums(num)) + + if den.ndim != 1: + raise ValueError("Denominator polynomial must be rank-1 array.") + if num.ndim > 2: + raise ValueError("Numerator polynomial must be rank-1 or" + " rank-2 array.") + if np.all(den == 0): + raise ValueError("Denominator must have at least on nonzero element.") + + # Trim leading zeros in denominator, leave at least one. + den = np.trim_zeros(den, 'f') + + # Normalize transfer function + num, den = num / den[0], den / den[0] + + # Count numerator columns that are all zero + leading_zeros = 0 + for col in num.T: + if np.allclose(col, 0, atol=1e-14): + leading_zeros += 1 + else: + break + + # Trim leading zeros of numerator + if leading_zeros > 0: + warnings.warn("Badly conditioned filter coefficients (numerator): the " + "results may be meaningless", + BadCoefficients, stacklevel=2) + # Make sure at least one column remains + if leading_zeros == num.shape[1]: + leading_zeros -= 1 + num = num[:, leading_zeros:] + + # Squeeze first dimension if singular + if num.shape[0] == 1: + num = num[0, :] + + return num, den + + +def lp2lp(b, a, wo=1.0): + r""" + Transform a lowpass filter prototype to a different frequency. + + Return an analog low-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, in + transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired cutoff, as angular frequency (e.g. rad/s). + Defaults to no change. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed low-pass filter. + a : array_like + Denominator polynomial coefficients of the transformed low-pass filter. + + See Also + -------- + lp2hp, lp2bp, lp2bs, bilinear + lp2lp_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s}{\omega_0} + + Examples + -------- + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.0]) + >>> lp2 = signal.lti(*signal.lp2lp(lp.num, lp.den, 2)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_lp2, p_lp2 = lp2.bode(w) + + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_lp2, label='Transformed Lowpass') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + + """ + a, b = map(atleast_1d, (a, b)) + try: + wo = float(wo) + except TypeError: + wo = float(wo[0]) + d = len(a) + n = len(b) + M = max((d, n)) + pwo = pow(wo, np.arange(M - 1, -1, -1)) + start1 = max((n - d, 0)) + start2 = max((d - n, 0)) + b = b * pwo[start1] / pwo[start2:] + a = a * pwo[start1] / pwo[start1:] + return normalize(b, a) + + +def lp2hp(b, a, wo=1.0): + r""" + Transform a lowpass filter prototype to a highpass filter. + + Return an analog high-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, in + transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired cutoff, as angular frequency (e.g., rad/s). + Defaults to no change. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed high-pass filter. + a : array_like + Denominator polynomial coefficients of the transformed high-pass filter. + + See Also + -------- + lp2lp, lp2bp, lp2bs, bilinear + lp2hp_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{\omega_0}{s} + + This maintains symmetry of the lowpass and highpass responses on a + logarithmic scale. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.0]) + >>> hp = signal.lti(*signal.lp2hp(lp.num, lp.den)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_hp, p_hp = hp.bode(w) + + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_hp, label='Highpass') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + + """ + a, b = map(atleast_1d, (a, b)) + try: + wo = float(wo) + except TypeError: + wo = float(wo[0]) + d = len(a) + n = len(b) + if wo != 1: + pwo = pow(wo, np.arange(max((d, n)))) + else: + pwo = np.ones(max((d, n)), b.dtype.char) + if d >= n: + outa = a[::-1] * pwo + outb = resize(b, (d,)) + outb[n:] = 0.0 + outb[:n] = b[::-1] * pwo[:n] + else: + outb = b[::-1] * pwo + outa = resize(a, (n,)) + outa[d:] = 0.0 + outa[:d] = a[::-1] * pwo[:d] + + return normalize(outb, outa) + + +def lp2bp(b, a, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandpass filter. + + Return an analog band-pass filter with center frequency `wo` and + bandwidth `bw` from an analog low-pass filter prototype with unity + cutoff frequency, in transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired passband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired passband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed band-pass filter. + a : array_like + Denominator polynomial coefficients of the transformed band-pass filter. + + See Also + -------- + lp2lp, lp2hp, lp2bs, bilinear + lp2bp_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}} + + This is the "wideband" transformation, producing a passband with + geometric (log frequency) symmetry about `wo`. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.0]) + >>> bp = signal.lti(*signal.lp2bp(lp.num, lp.den)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_bp, p_bp = bp.bode(w) + + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_bp, label='Bandpass') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + """ + + a, b = map(atleast_1d, (a, b)) + D = len(a) - 1 + N = len(b) - 1 + artype = mintypecode((a, b)) + ma = max([N, D]) + Np = N + ma + Dp = D + ma + bprime = np.empty(Np + 1, artype) + aprime = np.empty(Dp + 1, artype) + wosq = wo * wo + for j in range(Np + 1): + val = 0.0 + for i in range(0, N + 1): + for k in range(0, i + 1): + if ma - i + 2 * k == j: + val += comb(i, k) * b[N - i] * (wosq) ** (i - k) / bw ** i + bprime[Np - j] = val + for j in range(Dp + 1): + val = 0.0 + for i in range(0, D + 1): + for k in range(0, i + 1): + if ma - i + 2 * k == j: + val += comb(i, k) * a[D - i] * (wosq) ** (i - k) / bw ** i + aprime[Dp - j] = val + + return normalize(bprime, aprime) + + +def lp2bs(b, a, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandstop filter. + + Return an analog band-stop filter with center frequency `wo` and + bandwidth `bw` from an analog low-pass filter prototype with unity + cutoff frequency, in transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired stopband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired stopband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed band-stop filter. + a : array_like + Denominator polynomial coefficients of the transformed band-stop filter. + + See Also + -------- + lp2lp, lp2hp, lp2bp, bilinear + lp2bs_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2} + + This is the "wideband" transformation, producing a stopband with + geometric (log frequency) symmetry about `wo`. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.5]) + >>> bs = signal.lti(*signal.lp2bs(lp.num, lp.den)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_bs, p_bs = bs.bode(w) + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_bs, label='Bandstop') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + """ + a, b = map(atleast_1d, (a, b)) + D = len(a) - 1 + N = len(b) - 1 + artype = mintypecode((a, b)) + M = max([N, D]) + Np = M + M + Dp = M + M + bprime = np.empty(Np + 1, artype) + aprime = np.empty(Dp + 1, artype) + wosq = wo * wo + for j in range(Np + 1): + val = 0.0 + for i in range(0, N + 1): + for k in range(0, M - i + 1): + if i + 2 * k == j: + val += (comb(M - i, k) * b[N - i] * + (wosq) ** (M - i - k) * bw ** i) + bprime[Np - j] = val + for j in range(Dp + 1): + val = 0.0 + for i in range(0, D + 1): + for k in range(0, M - i + 1): + if i + 2 * k == j: + val += (comb(M - i, k) * a[D - i] * + (wosq) ** (M - i - k) * bw ** i) + aprime[Dp - j] = val + + return normalize(bprime, aprime) + + +def bilinear(b, a, fs=1.0): + r""" + Return a digital IIR filter from an analog one using a bilinear transform. + + Transform a set of poles and zeros from the analog s-plane to the digital + z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for + ``s``, maintaining the shape of the frequency response. + + Parameters + ---------- + b : array_like + Numerator of the analog filter transfer function. + a : array_like + Denominator of the analog filter transfer function. + fs : float + Sample rate, as ordinary frequency (e.g., hertz). No prewarping is + done in this function. + + Returns + ------- + b : ndarray + Numerator of the transformed digital filter transfer function. + a : ndarray + Denominator of the transformed digital filter transfer function. + + See Also + -------- + lp2lp, lp2hp, lp2bp, lp2bs + bilinear_zpk + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fs = 100 + >>> bf = 2 * np.pi * np.array([7, 13]) + >>> filts = signal.lti(*signal.butter(4, bf, btype='bandpass', + ... analog=True)) + >>> filtz = signal.lti(*signal.bilinear(filts.num, filts.den, fs)) + >>> wz, hz = signal.freqz(filtz.num, filtz.den) + >>> ws, hs = signal.freqs(filts.num, filts.den, worN=fs*wz) + + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hz).clip(1e-15)), + ... label=r'$|H_z(e^{j \omega})|$') + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hs).clip(1e-15)), + ... label=r'$|H(j \omega)|$') + >>> plt.legend() + >>> plt.xlabel('Frequency [Hz]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(True) + """ + fs = _validate_fs(fs, allow_none=False) + a, b = map(atleast_1d, (a, b)) + D = len(a) - 1 + N = len(b) - 1 + artype = float + M = max([N, D]) + Np = M + Dp = M + bprime = np.empty(Np + 1, artype) + aprime = np.empty(Dp + 1, artype) + for j in range(Np + 1): + val = 0.0 + for i in range(N + 1): + for k in range(i + 1): + for l in range(M - i + 1): + if k + l == j: + val += (comb(i, k) * comb(M - i, l) * b[N - i] * + pow(2 * fs, i) * (-1) ** k) + bprime[j] = real(val) + for j in range(Dp + 1): + val = 0.0 + for i in range(D + 1): + for k in range(i + 1): + for l in range(M - i + 1): + if k + l == j: + val += (comb(i, k) * comb(M - i, l) * a[D - i] * + pow(2 * fs, i) * (-1) ** k) + aprime[j] = real(val) + + return normalize(bprime, aprime) + + +def _validate_gpass_gstop(gpass, gstop): + + if gpass <= 0.0: + raise ValueError("gpass should be larger than 0.0") + elif gstop <= 0.0: + raise ValueError("gstop should be larger than 0.0") + elif gpass > gstop: + raise ValueError("gpass should be smaller than gstop") + + +def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba', + fs=None): + """Complete IIR digital and analog filter design. + + Given passband and stopband frequencies and gains, construct an analog or + digital IIR filter of minimum order for a given basic type. Return the + output in numerator, denominator ('ba'), pole-zero ('zpk') or second order + sections ('sos') form. + + Parameters + ---------- + wp, ws : float or array like, shape (2,) + Passband and stopband edge frequencies. Possible values are scalars + (for lowpass and highpass filters) or ranges (for bandpass and bandstop + filters). + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + Note, that for bandpass and bandstop filters passband must lie strictly + inside stopband or vice versa. Also note that the cutoff at the band edges + for IIR filters is defined as half-power, so -3dB, not half-amplitude (-6dB) + like for `scipy.signal.fiwin`. + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + ftype : str, optional + The type of IIR filter to design: + + - Butterworth : 'butter' + - Chebyshev I : 'cheby1' + - Chebyshev II : 'cheby2' + - Cauer/elliptic: 'ellip' + + output : {'ba', 'zpk', 'sos'}, optional + Filter form of the output: + + - second-order sections (recommended): 'sos' + - numerator/denominator (default) : 'ba' + - pole-zero : 'zpk' + + In general the second-order sections ('sos') form is + recommended because inferring the coefficients for the + numerator/denominator form ('ba') suffers from numerical + instabilities. For reasons of backward compatibility the default + form is the numerator/denominator form ('ba'), where the 'b' + and the 'a' in 'ba' refer to the commonly used names of the + coefficients used. + + Note: Using the second-order sections form ('sos') is sometimes + associated with additional computational costs: for + data-intense use cases it is therefore recommended to also + investigate the numerator/denominator form ('ba'). + + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + butter : Filter design using order and critical points + cheby1, cheby2, ellip, bessel + buttord : Find order and critical points from passband and stopband spec + cheb1ord, cheb2ord, ellipord + iirfilter : General filter design using order and critical frequencies + + Notes + ----- + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import matplotlib.ticker + + >>> wp = 0.2 + >>> ws = 0.3 + >>> gpass = 1 + >>> gstop = 40 + + >>> system = signal.iirdesign(wp, ws, gpass, gstop) + >>> w, h = signal.freqz(*system) + + >>> fig, ax1 = plt.subplots() + >>> ax1.set_title('Digital filter frequency response') + >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b') + >>> ax1.set_ylabel('Amplitude [dB]', color='b') + >>> ax1.set_xlabel('Frequency [rad/sample]') + >>> ax1.grid(True) + >>> ax1.set_ylim([-120, 20]) + >>> ax2 = ax1.twinx() + >>> phase = np.unwrap(np.angle(h)) + >>> ax2.plot(w, phase, 'g') + >>> ax2.set_ylabel('Phase [rad]', color='g') + >>> ax2.grid(True) + >>> ax2.axis('tight') + >>> ax2.set_ylim([-6, 1]) + >>> nticks = 8 + >>> ax1.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks)) + >>> ax2.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks)) + + """ + try: + ordfunc = filter_dict[ftype][1] + except KeyError as e: + raise ValueError(f"Invalid IIR filter type: {ftype}") from e + except IndexError as e: + raise ValueError(f"{ftype} does not have order selection. " + "Use iirfilter function.") from e + + _validate_gpass_gstop(gpass, gstop) + + wp = atleast_1d(wp) + ws = atleast_1d(ws) + + fs = _validate_fs(fs, allow_none=True) + + if wp.shape[0] != ws.shape[0] or wp.shape not in [(1,), (2,)]: + raise ValueError("wp and ws must have one or two elements each, and " + f"the same shape, got {wp.shape} and {ws.shape}") + + if any(wp <= 0) or any(ws <= 0): + raise ValueError("Values for wp, ws must be greater than 0") + + if not analog: + if fs is None: + if any(wp >= 1) or any(ws >= 1): + raise ValueError("Values for wp, ws must be less than 1") + elif any(wp >= fs/2) or any(ws >= fs/2): + raise ValueError("Values for wp, ws must be less than fs/2 " + f"(fs={fs} -> fs/2={fs/2})") + + if wp.shape[0] == 2: + if not ((ws[0] < wp[0] and wp[1] < ws[1]) or + (wp[0] < ws[0] and ws[1] < wp[1])): + raise ValueError("Passband must lie strictly inside stopband " + "or vice versa") + + band_type = 2 * (len(wp) - 1) + band_type += 1 + if wp[0] >= ws[0]: + band_type += 1 + + btype = {1: 'lowpass', 2: 'highpass', + 3: 'bandstop', 4: 'bandpass'}[band_type] + + N, Wn = ordfunc(wp, ws, gpass, gstop, analog=analog, fs=fs) + return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype, + ftype=ftype, output=output, fs=fs) + + +def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=False, + ftype='butter', output='ba', fs=None): + """ + IIR digital and analog filter design given order and critical points. + + Design an Nth-order digital or analog filter and return the filter + coefficients. + + Parameters + ---------- + N : int + The order of the filter. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + + When Wn is a length-2 sequence, ``Wn[0]`` must be less than ``Wn[1]``. + rp : float, optional + For Chebyshev and elliptic filters, provides the maximum ripple + in the passband. (dB) + rs : float, optional + For Chebyshev and elliptic filters, provides the minimum attenuation + in the stop band. (dB) + btype : {'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional + The type of filter. Default is 'bandpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + ftype : str, optional + The type of IIR filter to design: + + - Butterworth : 'butter' + - Chebyshev I : 'cheby1' + - Chebyshev II : 'cheby2' + - Cauer/elliptic: 'ellip' + - Bessel/Thomson: 'bessel' + + output : {'ba', 'zpk', 'sos'}, optional + Filter form of the output: + + - second-order sections (recommended): 'sos' + - numerator/denominator (default) : 'ba' + - pole-zero : 'zpk' + + In general the second-order sections ('sos') form is + recommended because inferring the coefficients for the + numerator/denominator form ('ba') suffers from numerical + instabilities. For reasons of backward compatibility the default + form is the numerator/denominator form ('ba'), where the 'b' + and the 'a' in 'ba' refer to the commonly used names of the + coefficients used. + + Note: Using the second-order sections form ('sos') is sometimes + associated with additional computational costs: for + data-intense use cases it is therefore recommended to also + investigate the numerator/denominator form ('ba'). + + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + butter : Filter design using order and critical points + cheby1, cheby2, ellip, bessel + buttord : Find order and critical points from passband and stopband spec + cheb1ord, cheb2ord, ellipord + iirdesign : General filter design using passband and stopband spec + + Notes + ----- + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Generate a 17th-order Chebyshev II analog bandpass filter from 50 Hz to + 200 Hz and plot the frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> b, a = signal.iirfilter(17, [2*np.pi*50, 2*np.pi*200], rs=60, + ... btype='band', analog=True, ftype='cheby2') + >>> w, h = signal.freqs(b, a, 1000) + >>> fig = plt.figure() + >>> ax = fig.add_subplot(1, 1, 1) + >>> ax.semilogx(w / (2*np.pi), 20 * np.log10(np.maximum(abs(h), 1e-5))) + >>> ax.set_title('Chebyshev Type II bandpass frequency response') + >>> ax.set_xlabel('Frequency [Hz]') + >>> ax.set_ylabel('Amplitude [dB]') + >>> ax.axis((10, 1000, -100, 10)) + >>> ax.grid(which='both', axis='both') + >>> plt.show() + + Create a digital filter with the same properties, in a system with + sampling rate of 2000 Hz, and plot the frequency response. (Second-order + sections implementation is required to ensure stability of a filter of + this order): + + >>> sos = signal.iirfilter(17, [50, 200], rs=60, btype='band', + ... analog=False, ftype='cheby2', fs=2000, + ... output='sos') + >>> w, h = signal.freqz_sos(sos, 2000, fs=2000) + >>> fig = plt.figure() + >>> ax = fig.add_subplot(1, 1, 1) + >>> ax.semilogx(w, 20 * np.log10(np.maximum(abs(h), 1e-5))) + >>> ax.set_title('Chebyshev Type II bandpass frequency response') + >>> ax.set_xlabel('Frequency [Hz]') + >>> ax.set_ylabel('Amplitude [dB]') + >>> ax.axis((10, 1000, -100, 10)) + >>> ax.grid(which='both', axis='both') + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + ftype, btype, output = (x.lower() for x in (ftype, btype, output)) + Wn = asarray(Wn) + if fs is not None: + if analog: + raise ValueError("fs cannot be specified for an analog filter") + Wn = Wn / (fs/2) + + if np.any(Wn <= 0): + raise ValueError("filter critical frequencies must be greater than 0") + + if Wn.size > 1 and not Wn[0] < Wn[1]: + raise ValueError("Wn[0] must be less than Wn[1]") + + try: + btype = band_dict[btype] + except KeyError as e: + raise ValueError(f"'{btype}' is an invalid bandtype for filter.") from e + + try: + typefunc = filter_dict[ftype][0] + except KeyError as e: + raise ValueError(f"'{ftype}' is not a valid basic IIR filter.") from e + + if output not in ['ba', 'zpk', 'sos']: + raise ValueError(f"'{output}' is not a valid output form.") + + if rp is not None and rp < 0: + raise ValueError("passband ripple (rp) must be positive") + + if rs is not None and rs < 0: + raise ValueError("stopband attenuation (rs) must be positive") + + # Get analog lowpass prototype + if typefunc == buttap: + z, p, k = typefunc(N) + elif typefunc == besselap: + z, p, k = typefunc(N, norm=bessel_norms[ftype]) + elif typefunc == cheb1ap: + if rp is None: + raise ValueError("passband ripple (rp) must be provided to " + "design a Chebyshev I filter.") + z, p, k = typefunc(N, rp) + elif typefunc == cheb2ap: + if rs is None: + raise ValueError("stopband attenuation (rs) must be provided to " + "design an Chebyshev II filter.") + z, p, k = typefunc(N, rs) + elif typefunc == ellipap: + if rs is None or rp is None: + raise ValueError("Both rp and rs must be provided to design an " + "elliptic filter.") + z, p, k = typefunc(N, rp, rs) + else: + raise NotImplementedError(f"'{ftype}' not implemented in iirfilter.") + + # Pre-warp frequencies for digital filter design + if not analog: + if np.any(Wn <= 0) or np.any(Wn >= 1): + if fs is not None: + raise ValueError("Digital filter critical frequencies must " + f"be 0 < Wn < fs/2 (fs={fs} -> fs/2={fs/2})") + raise ValueError("Digital filter critical frequencies " + "must be 0 < Wn < 1") + fs = 2.0 + warped = 2 * fs * tan(pi * Wn / fs) + else: + warped = Wn + + # transform to lowpass, bandpass, highpass, or bandstop + if btype in ('lowpass', 'highpass'): + if np.size(Wn) != 1: + raise ValueError('Must specify a single critical frequency Wn ' + 'for lowpass or highpass filter') + + if btype == 'lowpass': + z, p, k = lp2lp_zpk(z, p, k, wo=warped) + elif btype == 'highpass': + z, p, k = lp2hp_zpk(z, p, k, wo=warped) + elif btype in ('bandpass', 'bandstop'): + try: + bw = warped[1] - warped[0] + wo = sqrt(warped[0] * warped[1]) + except IndexError as e: + raise ValueError('Wn must specify start and stop frequencies for ' + 'bandpass or bandstop filter') from e + + if btype == 'bandpass': + z, p, k = lp2bp_zpk(z, p, k, wo=wo, bw=bw) + elif btype == 'bandstop': + z, p, k = lp2bs_zpk(z, p, k, wo=wo, bw=bw) + else: + raise NotImplementedError(f"'{btype}' not implemented in iirfilter.") + + # Find discrete equivalent if necessary + if not analog: + z, p, k = bilinear_zpk(z, p, k, fs=fs) + + # Transform to proper out type (pole-zero, state-space, numer-denom) + if output == 'zpk': + return z, p, k + elif output == 'ba': + return zpk2tf(z, p, k) + elif output == 'sos': + return zpk2sos(z, p, k, analog=analog) + + +def _relative_degree(z, p): + """ + Return relative degree of transfer function from zeros and poles + """ + degree = len(p) - len(z) + if degree < 0: + raise ValueError("Improper transfer function. " + "Must have at least as many poles as zeros.") + else: + return degree + + +def bilinear_zpk(z, p, k, fs): + r""" + Return a digital IIR filter from an analog one using a bilinear transform. + + Transform a set of poles and zeros from the analog s-plane to the digital + z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for + ``s``, maintaining the shape of the frequency response. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + fs : float + Sample rate, as ordinary frequency (e.g., hertz). No prewarping is + done in this function. + + Returns + ------- + z : ndarray + Zeros of the transformed digital filter transfer function. + p : ndarray + Poles of the transformed digital filter transfer function. + k : float + System gain of the transformed digital filter. + + See Also + -------- + lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, lp2bs_zpk + bilinear + + Notes + ----- + .. versionadded:: 1.1.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> fs = 100 + >>> bf = 2 * np.pi * np.array([7, 13]) + >>> filts = signal.lti(*signal.butter(4, bf, btype='bandpass', analog=True, + ... output='zpk')) + >>> filtz = signal.lti(*signal.bilinear_zpk(filts.zeros, filts.poles, + ... filts.gain, fs)) + >>> wz, hz = signal.freqz_zpk(filtz.zeros, filtz.poles, filtz.gain) + >>> ws, hs = signal.freqs_zpk(filts.zeros, filts.poles, filts.gain, + ... worN=fs*wz) + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hz).clip(1e-15)), + ... label=r'$|H_z(e^{j \omega})|$') + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hs).clip(1e-15)), + ... label=r'$|H(j \omega)|$') + >>> plt.legend() + >>> plt.xlabel('Frequency [Hz]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(True) + """ + z = atleast_1d(z) + p = atleast_1d(p) + + fs = _validate_fs(fs, allow_none=False) + + degree = _relative_degree(z, p) + + fs2 = 2.0*fs + + # Bilinear transform the poles and zeros + z_z = (fs2 + z) / (fs2 - z) + p_z = (fs2 + p) / (fs2 - p) + + # Any zeros that were at infinity get moved to the Nyquist frequency + z_z = append(z_z, -ones(degree)) + + # Compensate for gain change + k_z = k * real(prod(fs2 - z) / prod(fs2 - p)) + + return z_z, p_z, k_z + + +def lp2lp_zpk(z, p, k, wo=1.0): + r""" + Transform a lowpass filter prototype to a different frequency. + + Return an analog low-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, + using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired cutoff, as angular frequency (e.g., rad/s). + Defaults to no change. + + Returns + ------- + z : ndarray + Zeros of the transformed low-pass filter transfer function. + p : ndarray + Poles of the transformed low-pass filter transfer function. + k : float + System gain of the transformed low-pass filter. + + See Also + -------- + lp2hp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear + lp2lp + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s}{\omega_0} + + .. versionadded:: 1.1.0 + + Examples + -------- + Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to + transform it to a new 'zpk' representation associated with a cutoff frequency wo. + + >>> from scipy.signal import lp2lp_zpk + >>> z = [7, 2] + >>> p = [5, 13] + >>> k = 0.8 + >>> wo = 0.4 + >>> lp2lp_zpk(z, p, k, wo) + ( array([2.8, 0.8]), array([2. , 5.2]), 0.8) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) # Avoid int wraparound + + degree = _relative_degree(z, p) + + # Scale all points radially from origin to shift cutoff frequency + z_lp = wo * z + p_lp = wo * p + + # Each shifted pole decreases gain by wo, each shifted zero increases it. + # Cancel out the net change to keep overall gain the same + k_lp = k * wo**degree + + return z_lp, p_lp, k_lp + + +def lp2hp_zpk(z, p, k, wo=1.0): + r""" + Transform a lowpass filter prototype to a highpass filter. + + Return an analog high-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, + using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired cutoff, as angular frequency (e.g., rad/s). + Defaults to no change. + + Returns + ------- + z : ndarray + Zeros of the transformed high-pass filter transfer function. + p : ndarray + Poles of the transformed high-pass filter transfer function. + k : float + System gain of the transformed high-pass filter. + + See Also + -------- + lp2lp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear + lp2hp + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{\omega_0}{s} + + This maintains symmetry of the lowpass and highpass responses on a + logarithmic scale. + + .. versionadded:: 1.1.0 + + Examples + -------- + Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to + transform it to a highpass filter with a cutoff frequency wo. + + >>> from scipy.signal import lp2hp_zpk + >>> z = [ -2 + 3j , -0.5 - 0.8j ] + >>> p = [ -1 , -4 ] + >>> k = 10 + >>> wo = 0.6 + >>> lp2hp_zpk(z, p, k, wo) + ( array([-0.09230769-0.13846154j, -0.33707865+0.53932584j]), + array([-0.6 , -0.15]), + 8.5) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) + + degree = _relative_degree(z, p) + + # Invert positions radially about unit circle to convert LPF to HPF + # Scale all points radially from origin to shift cutoff frequency + z_hp = wo / z + p_hp = wo / p + + # If lowpass had zeros at infinity, inverting moves them to origin. + z_hp = append(z_hp, zeros(degree)) + + # Cancel out gain change caused by inversion + k_hp = k * real(prod(-z) / prod(-p)) + + return z_hp, p_hp, k_hp + + +def lp2bp_zpk(z, p, k, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandpass filter. + + Return an analog band-pass filter with center frequency `wo` and + bandwidth `bw` from an analog low-pass filter prototype with unity + cutoff frequency, using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired passband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired passband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + z : ndarray + Zeros of the transformed band-pass filter transfer function. + p : ndarray + Poles of the transformed band-pass filter transfer function. + k : float + System gain of the transformed band-pass filter. + + See Also + -------- + lp2lp_zpk, lp2hp_zpk, lp2bs_zpk, bilinear + lp2bp + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}} + + This is the "wideband" transformation, producing a passband with + geometric (log frequency) symmetry about `wo`. + + .. versionadded:: 1.1.0 + + Examples + -------- + Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to + transform it to a bandpass filter with a center frequency wo and + bandwidth bw. + + >>> from scipy.signal import lp2bp_zpk + >>> z = [ 5 + 2j , 5 - 2j ] + >>> p = [ 7 , -16 ] + >>> k = 0.8 + >>> wo = 0.62 + >>> bw = 15 + >>> lp2bp_zpk(z, p, k, wo, bw) + ( array([7.49955815e+01+3.00017676e+01j, 7.49955815e+01-3.00017676e+01j, + 4.41850748e-03-1.76761126e-03j, 4.41850748e-03+1.76761126e-03j]), + array([1.04996339e+02+0.j, -1.60167736e-03+0.j, 3.66108003e-03+0.j, + -2.39998398e+02+0.j]), 0.8) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) + bw = float(bw) + + degree = _relative_degree(z, p) + + # Scale poles and zeros to desired bandwidth + z_lp = z * bw/2 + p_lp = p * bw/2 + + # Square root needs to produce complex result, not NaN + z_lp = z_lp.astype(complex) + p_lp = p_lp.astype(complex) + + # Duplicate poles and zeros and shift from baseband to +wo and -wo + z_bp = concatenate((z_lp + sqrt(z_lp**2 - wo**2), + z_lp - sqrt(z_lp**2 - wo**2))) + p_bp = concatenate((p_lp + sqrt(p_lp**2 - wo**2), + p_lp - sqrt(p_lp**2 - wo**2))) + + # Move degree zeros to origin, leaving degree zeros at infinity for BPF + z_bp = append(z_bp, zeros(degree)) + + # Cancel out gain change from frequency scaling + k_bp = k * bw**degree + + return z_bp, p_bp, k_bp + + +def lp2bs_zpk(z, p, k, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandstop filter. + + Return an analog band-stop filter with center frequency `wo` and + stopband width `bw` from an analog low-pass filter prototype with unity + cutoff frequency, using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired stopband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired stopband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + z : ndarray + Zeros of the transformed band-stop filter transfer function. + p : ndarray + Poles of the transformed band-stop filter transfer function. + k : float + System gain of the transformed band-stop filter. + + See Also + -------- + lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, bilinear + lp2bs + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2} + + This is the "wideband" transformation, producing a stopband with + geometric (log frequency) symmetry about `wo`. + + .. versionadded:: 1.1.0 + + Examples + -------- + Transform a low-pass filter represented in 'zpk' (Zero-Pole-Gain) form + into a bandstop filter represented in 'zpk' form, with a center frequency wo and + bandwidth bw. + + >>> from scipy.signal import lp2bs_zpk + >>> z = [ ] + >>> p = [ 0.7 , -1 ] + >>> k = 9 + >>> wo = 0.5 + >>> bw = 10 + >>> lp2bs_zpk(z, p, k, wo, bw) + ( array([0.+0.5j, 0.+0.5j, 0.-0.5j, 0.-0.5j]), + array([14.2681928 +0.j, -0.02506281+0.j, 0.01752149+0.j, -9.97493719+0.j]), + -12.857142857142858) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) + bw = float(bw) + + degree = _relative_degree(z, p) + + # Invert to a highpass filter with desired bandwidth + z_hp = (bw/2) / z + p_hp = (bw/2) / p + + # Square root needs to produce complex result, not NaN + z_hp = z_hp.astype(complex) + p_hp = p_hp.astype(complex) + + # Duplicate poles and zeros and shift from baseband to +wo and -wo + z_bs = concatenate((z_hp + sqrt(z_hp**2 - wo**2), + z_hp - sqrt(z_hp**2 - wo**2))) + p_bs = concatenate((p_hp + sqrt(p_hp**2 - wo**2), + p_hp - sqrt(p_hp**2 - wo**2))) + + # Move any zeros that were at infinity to the center of the stopband + z_bs = append(z_bs, full(degree, +1j*wo)) + z_bs = append(z_bs, full(degree, -1j*wo)) + + # Cancel out gain change caused by inversion + k_bs = k * real(prod(-z) / prod(-p)) + + return z_bs, p_bs, k_bs + + +def butter(N, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Butterworth digital and analog filter design. + + Design an Nth-order digital or analog Butterworth filter and return + the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. For 'bandpass' and 'bandstop' filters, + the resulting order of the final second-order sections ('sos') + matrix is ``2*N``, with `N` the number of biquad sections + of the desired system. + Wn : array_like + The critical frequency or frequencies. For lowpass and highpass + filters, Wn is a scalar; for bandpass and bandstop filters, + Wn is a length-2 sequence. + + For a Butterworth filter, this is the point at which the gain + drops to 1/sqrt(2) that of the passband (the "-3 dB point"). + + For digital filters, if `fs` is not specified, `Wn` units are + normalized from 0 to 1, where 1 is the Nyquist frequency (`Wn` is + thus in half cycles / sample and defined as 2*critical frequencies + / `fs`). If `fs` is specified, `Wn` is in the same units as `fs`. + + For analog filters, `Wn` is an angular frequency (e.g. rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + buttord, buttap + + Notes + ----- + The Butterworth filter has maximally flat frequency response in the + passband. + + The ``'sos'`` output parameter was added in 0.16.0. + + If the transfer function form ``[b, a]`` is requested, numerical + problems can occur since the conversion between roots and + the polynomial coefficients is a numerically sensitive operation, + even for N >= 4. It is recommended to work with the SOS + representation. + + .. warning:: + Designing high-order and narrowband IIR filters in TF form can + result in unstable or incorrect filtering due to floating point + numerical precision issues. Consider inspecting output filter + characteristics `freqz` or designing the filters with second-order + sections via ``output='sos'``. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.butter(4, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Butterworth filter frequency response') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.butter(10, 15, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 15 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.tight_layout() + >>> plt.show() + """ + return iirfilter(N, Wn, btype=btype, analog=analog, + output=output, ftype='butter', fs=fs) + + +def cheby1(N, rp, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Chebyshev type I digital and analog filter design. + + Design an Nth-order digital or analog Chebyshev type I filter and + return the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + rp : float + The maximum ripple allowed below unity gain in the passband. + Specified in decibels, as a positive number. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + For Type I filters, this is the point in the transition band at which + the gain first drops below -`rp`. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + cheb1ord, cheb1ap + + Notes + ----- + The Chebyshev type I filter maximizes the rate of cutoff between the + frequency response's passband and stopband, at the expense of ripple in + the passband and increased ringing in the step response. + + Type I filters roll off faster than Type II (`cheby2`), but Type II + filters do not have any ripple in the passband. + + The equiripple passband has N maxima or minima (for example, a + 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is + unity for odd-order filters, or -rp dB for even-order filters. + + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.cheby1(4, 5, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev Type I frequency response (rp=5)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-5, color='green') # rp + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.cheby1(10, 1, 15, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 15 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.tight_layout() + >>> plt.show() + """ + return iirfilter(N, Wn, rp=rp, btype=btype, analog=analog, + output=output, ftype='cheby1', fs=fs) + + +def cheby2(N, rs, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Chebyshev type II digital and analog filter design. + + Design an Nth-order digital or analog Chebyshev type II filter and + return the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + rs : float + The minimum attenuation required in the stop band. + Specified in decibels, as a positive number. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + For Type II filters, this is the point in the transition band at which + the gain first reaches -`rs`. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + cheb2ord, cheb2ap + + Notes + ----- + The Chebyshev type II filter maximizes the rate of cutoff between the + frequency response's passband and stopband, at the expense of ripple in + the stopband and increased ringing in the step response. + + Type II filters do not roll off as fast as Type I (`cheby1`). + + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.cheby2(4, 40, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev Type II frequency response (rs=40)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-40, color='green') # rs + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.cheby2(12, 20, 17, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 17 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.show() + """ + return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog, + output=output, ftype='cheby2', fs=fs) + + +def ellip(N, rp, rs, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Elliptic (Cauer) digital and analog filter design. + + Design an Nth-order digital or analog elliptic filter and return + the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + rp : float + The maximum ripple allowed below unity gain in the passband. + Specified in decibels, as a positive number. + rs : float + The minimum attenuation required in the stop band. + Specified in decibels, as a positive number. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + For elliptic filters, this is the point in the transition band at + which the gain first drops below -`rp`. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + ellipord, ellipap + + Notes + ----- + Also known as Cauer or Zolotarev filters, the elliptical filter maximizes + the rate of transition between the frequency response's passband and + stopband, at the expense of ripple in both, and increased ringing in the + step response. + + As `rp` approaches 0, the elliptical filter becomes a Chebyshev + type II filter (`cheby2`). As `rs` approaches 0, it becomes a Chebyshev + type I filter (`cheby1`). As both approach 0, it becomes a Butterworth + filter (`butter`). + + The equiripple passband has N maxima or minima (for example, a + 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is + unity for odd-order filters, or -rp dB for even-order filters. + + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Elliptic filter frequency response (rp=5, rs=40)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-40, color='green') # rs + >>> plt.axhline(-5, color='green') # rp + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.ellip(8, 1, 100, 17, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 17 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.tight_layout() + >>> plt.show() + """ + return iirfilter(N, Wn, rs=rs, rp=rp, btype=btype, analog=analog, + output=output, ftype='elliptic', fs=fs) + + +def bessel(N, Wn, btype='low', analog=False, output='ba', norm='phase', + fs=None): + """ + Bessel/Thomson digital and analog filter design. + + Design an Nth-order digital or analog Bessel filter and return the + filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies (defined + by the `norm` parameter). + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. (See Notes.) + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba'. + norm : {'phase', 'delay', 'mag'}, optional + Critical frequency normalization: + + ``phase`` + The filter is normalized such that the phase response reaches its + midpoint at angular (e.g. rad/s) frequency `Wn`. This happens for + both low-pass and high-pass filters, so this is the + "phase-matched" case. + + The magnitude response asymptotes are the same as a Butterworth + filter of the same order with a cutoff of `Wn`. + + This is the default, and matches MATLAB's implementation. + + ``delay`` + The filter is normalized such that the group delay in the passband + is 1/`Wn` (e.g., seconds). This is the "natural" type obtained by + solving Bessel polynomials. + + ``mag`` + The filter is normalized such that the gain magnitude is -3 dB at + angular frequency `Wn`. + + .. versionadded:: 0.18.0 + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + Notes + ----- + Also known as a Thomson filter, the analog Bessel filter has maximally + flat group delay and maximally linear phase response, with very little + ringing in the step response. [1]_ + + The Bessel is inherently an analog filter. This function generates digital + Bessel filters using the bilinear transform, which does not preserve the + phase response of the analog filter. As such, it is only approximately + correct at frequencies below about fs/4. To get maximally-flat group + delay at higher frequencies, the analog Bessel filter must be transformed + using phase-preserving techniques. + + See `besselap` for implementation details and references. + + The ``'sos'`` output parameter was added in 0.16.0. + + References + ---------- + .. [1] Thomson, W.E., "Delay Networks having Maximally Flat Frequency + Characteristics", Proceedings of the Institution of Electrical + Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490. + + Examples + -------- + Plot the phase-normalized frequency response, showing the relationship + to the Butterworth's cutoff frequency (green): + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.butter(4, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(np.abs(h)), color='silver', ls='dashed') + >>> b, a = signal.bessel(4, 100, 'low', analog=True, norm='phase') + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(np.abs(h))) + >>> plt.title('Bessel filter magnitude response (with Butterworth)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.show() + + and the phase midpoint: + + >>> plt.figure() + >>> plt.semilogx(w, np.unwrap(np.angle(h))) + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-np.pi, color='red') # phase midpoint + >>> plt.title('Bessel filter phase response') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Phase [rad]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.show() + + Plot the magnitude-normalized frequency response, showing the -3 dB cutoff: + + >>> b, a = signal.bessel(3, 10, 'low', analog=True, norm='mag') + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(np.abs(h))) + >>> plt.axhline(-3, color='red') # -3 dB magnitude + >>> plt.axvline(10, color='green') # cutoff frequency + >>> plt.title('Amplitude-normalized Bessel filter frequency response') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.show() + + Plot the delay-normalized filter, showing the maximally-flat group delay + at 0.1 seconds: + + >>> b, a = signal.bessel(5, 1/0.1, 'low', analog=True, norm='delay') + >>> w, h = signal.freqs(b, a) + >>> plt.figure() + >>> plt.semilogx(w[1:], -np.diff(np.unwrap(np.angle(h)))/np.diff(w)) + >>> plt.axhline(0.1, color='red') # 0.1 seconds group delay + >>> plt.title('Bessel filter group delay') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Group delay [s]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.show() + + """ + return iirfilter(N, Wn, btype=btype, analog=analog, + output=output, ftype='bessel_'+norm, fs=fs) + + +def maxflat(): + pass + + +def yulewalk(): + pass + + +def band_stop_obj(wp, ind, passb, stopb, gpass, gstop, type): + """ + Band Stop Objective Function for order minimization. + + Returns the non-integer order for an analog band stop filter. + + Parameters + ---------- + wp : scalar + Edge of passband `passb`. + ind : int, {0, 1} + Index specifying which `passb` edge to vary (0 or 1). + passb : ndarray + Two element sequence of fixed passband edges. + stopb : ndarray + Two element sequence of fixed stopband edges. + gstop : float + Amount of attenuation in stopband in dB. + gpass : float + Amount of ripple in the passband in dB. + type : {'butter', 'cheby', 'ellip'} + Type of filter. + + Returns + ------- + n : scalar + Filter order (possibly non-integer). + + Notes + ----- + Band-stop filters are used in applications where certain frequency + components need to be blocked while others are allowed; for instance, + removing noise at specific frequencies while allowing the desired signal + to pass through. The order of a filter often determines its complexity and + accuracy. Determining the right order can be a challenge. This function + aims to provide an appropriate order for an analog band stop filter. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.signal import band_stop_obj + >>> wp = 2 + >>> ind = 1 + >>> passb = np.array([1, 3]) + >>> stopb = np.array([0.5, 4]) + >>> gstop = 30 + >>> gpass = 3 + >>> filter_type = 'butter' + >>> band_stop_obj(wp, ind, passb, stopb, gpass, gstop, filter_type) + np.float64(-2.758504160760643) + + """ + + _validate_gpass_gstop(gpass, gstop) + + passbC = passb.copy() + passbC[ind] = wp + nat = (stopb * (passbC[0] - passbC[1]) / + (stopb ** 2 - passbC[0] * passbC[1])) + nat = min(abs(nat)) + + if type == 'butter': + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + n = (log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * log10(nat))) + elif type == 'cheby': + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + n = arccosh(sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / arccosh(nat) + elif type == 'ellip': + GSTOP = 10 ** (0.1 * gstop) + GPASS = 10 ** (0.1 * gpass) + arg1 = sqrt((GPASS - 1.0) / (GSTOP - 1.0)) + arg0 = 1.0 / nat + d0 = special.ellipk([arg0 ** 2, 1 - arg0 ** 2]) + d1 = special.ellipk([arg1 ** 2, 1 - arg1 ** 2]) + n = (d0[0] * d1[1] / (d0[1] * d1[0])) + else: + raise ValueError(f"Incorrect type: {type}") + return n + + +def _pre_warp(wp, ws, analog): + # Pre-warp frequencies for digital filter design + if not analog: + passb = np.tan(pi * wp / 2.0) + stopb = np.tan(pi * ws / 2.0) + else: + passb = wp * 1.0 + stopb = ws * 1.0 + return passb, stopb + + +def _validate_wp_ws(wp, ws, fs, analog): + wp = atleast_1d(wp) + ws = atleast_1d(ws) + if fs is not None: + if analog: + raise ValueError("fs cannot be specified for an analog filter") + wp = 2 * wp / fs + ws = 2 * ws / fs + + filter_type = 2 * (len(wp) - 1) + 1 + if wp[0] >= ws[0]: + filter_type += 1 + + return wp, ws, filter_type + + +def _find_nat_freq(stopb, passb, gpass, gstop, filter_type, filter_kind): + if filter_type == 1: # low + nat = stopb / passb + elif filter_type == 2: # high + nat = passb / stopb + elif filter_type == 3: # stop + + ### breakpoint() + + wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12, + args=(0, passb, stopb, gpass, gstop, + filter_kind), + disp=0) + passb[0] = wp0 + wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1], + args=(1, passb, stopb, gpass, gstop, + filter_kind), + disp=0) + passb[1] = wp1 + nat = ((stopb * (passb[0] - passb[1])) / + (stopb ** 2 - passb[0] * passb[1])) + elif filter_type == 4: # pass + nat = ((stopb ** 2 - passb[0] * passb[1]) / + (stopb * (passb[0] - passb[1]))) + else: + raise ValueError(f"should not happen: {filter_type =}.") + + nat = min(abs(nat)) + return nat, passb + + +def _postprocess_wn(WN, analog, fs): + wn = WN if analog else np.arctan(WN) * 2.0 / pi + if len(wn) == 1: + wn = wn[0] + if fs is not None: + wn = wn * fs / 2 + return wn + + +def buttord(wp, ws, gpass, gstop, analog=False, fs=None): + """Butterworth filter order selection. + + Return the order of the lowest order digital or analog Butterworth filter + that loses no more than `gpass` dB in the passband and has at least + `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for a Butterworth filter which meets specs. + wn : ndarray or float + The Butterworth natural frequency (i.e. the "3dB frequency"). Should + be used with `butter` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `butter`. + + See Also + -------- + butter : Filter design using order and critical points + cheb1ord : Find order and critical points from passband and stopband spec + cheb2ord, ellipord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design an analog bandpass filter with passband within 3 dB from 20 to + 50 rad/s, while rejecting at least -40 dB below 14 and above 60 rad/s. + Plot its frequency response, showing the passband and stopband + constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.buttord([20, 50], [14, 60], 3, 40, True) + >>> b, a = signal.butter(N, Wn, 'band', True) + >>> w, h = signal.freqs(b, a, np.logspace(1, 2, 500)) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Butterworth bandpass filter fit to constraints') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([1, 14, 14, 1], [-40, -40, 99, 99], '0.9', lw=0) # stop + >>> plt.fill([20, 20, 50, 50], [-99, -3, -3, -99], '0.9', lw=0) # pass + >>> plt.fill([60, 60, 1e9, 1e9], [99, -40, -40, 99], '0.9', lw=0) # stop + >>> plt.axis([10, 100, -60, 3]) + >>> plt.show() + + """ + _validate_gpass_gstop(gpass, gstop) + fs = _validate_fs(fs, allow_none=True) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'butter') + + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + ord = int(ceil(log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * log10(nat)))) + + # Find the Butterworth natural frequency WN (or the "3dB" frequency") + # to give exactly gpass at passb. + try: + W0 = (GPASS - 1.0) ** (-1.0 / (2.0 * ord)) + except ZeroDivisionError: + W0 = 1.0 + warnings.warn("Order is zero...check input parameters.", + RuntimeWarning, stacklevel=2) + + # now convert this frequency back from lowpass prototype + # to the original analog filter + + if filter_type == 1: # low + WN = W0 * passb + elif filter_type == 2: # high + WN = passb / W0 + elif filter_type == 3: # stop + WN = np.empty(2, float) + discr = sqrt((passb[1] - passb[0]) ** 2 + + 4 * W0 ** 2 * passb[0] * passb[1]) + WN[0] = ((passb[1] - passb[0]) + discr) / (2 * W0) + WN[1] = ((passb[1] - passb[0]) - discr) / (2 * W0) + WN = np.sort(abs(WN)) + elif filter_type == 4: # pass + W0 = np.array([-W0, W0], float) + WN = (-W0 * (passb[1] - passb[0]) / 2.0 + + sqrt(W0 ** 2 / 4.0 * (passb[1] - passb[0]) ** 2 + + passb[0] * passb[1])) + WN = np.sort(abs(WN)) + else: + raise ValueError(f"Bad type: {filter_type}") + + wn = _postprocess_wn(WN, analog, fs) + + return ord, wn + + +def cheb1ord(wp, ws, gpass, gstop, analog=False, fs=None): + """Chebyshev type I filter order selection. + + Return the order of the lowest order digital or analog Chebyshev Type I + filter that loses no more than `gpass` dB in the passband and has at + least `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for a Chebyshev type I filter that meets specs. + wn : ndarray or float + The Chebyshev natural frequency (the "3dB frequency") for use with + `cheby1` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `cheby1`. + + See Also + -------- + cheby1 : Filter design using order and critical points + buttord : Find order and critical points from passband and stopband spec + cheb2ord, ellipord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design a digital lowpass filter such that the passband is within 3 dB up + to 0.2*(fs/2), while rejecting at least -40 dB above 0.3*(fs/2). Plot its + frequency response, showing the passband and stopband constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.cheb1ord(0.2, 0.3, 3, 40) + >>> b, a = signal.cheby1(N, 3, Wn, 'low') + >>> w, h = signal.freqz(b, a) + >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev I lowpass filter fit to constraints') + >>> plt.xlabel('Normalized frequency') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([.01, 0.2, 0.2, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop + >>> plt.fill([0.3, 0.3, 2, 2], [ 9, -40, -40, 9], '0.9', lw=0) # pass + >>> plt.axis([0.08, 1, -60, 3]) + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + _validate_gpass_gstop(gpass, gstop) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby') + + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + v_pass_stop = np.arccosh(np.sqrt((GSTOP - 1.0) / (GPASS - 1.0))) + ord = int(ceil(v_pass_stop / np.arccosh(nat))) + + # Natural frequencies are just the passband edges + wn = _postprocess_wn(passb, analog, fs) + + return ord, wn + + +def cheb2ord(wp, ws, gpass, gstop, analog=False, fs=None): + """Chebyshev type II filter order selection. + + Return the order of the lowest order digital or analog Chebyshev Type II + filter that loses no more than `gpass` dB in the passband and has at least + `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for a Chebyshev type II filter that meets specs. + wn : ndarray or float + The Chebyshev natural frequency (the "3dB frequency") for use with + `cheby2` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `cheby2`. + + See Also + -------- + cheby2 : Filter design using order and critical points + buttord : Find order and critical points from passband and stopband spec + cheb1ord, ellipord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design a digital bandstop filter which rejects -60 dB from 0.2*(fs/2) to + 0.5*(fs/2), while staying within 3 dB below 0.1*(fs/2) or above + 0.6*(fs/2). Plot its frequency response, showing the passband and + stopband constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + >>> b, a = signal.cheby2(N, 60, Wn, 'stop') + >>> w, h = signal.freqz(b, a) + >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev II bandstop filter fit to constraints') + >>> plt.xlabel('Normalized frequency') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([.01, .1, .1, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop + >>> plt.fill([.2, .2, .5, .5], [ 9, -60, -60, 9], '0.9', lw=0) # pass + >>> plt.fill([.6, .6, 2, 2], [-99, -3, -3, -99], '0.9', lw=0) # stop + >>> plt.axis([0.06, 1, -80, 3]) + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + _validate_gpass_gstop(gpass, gstop) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby') + + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + v_pass_stop = np.arccosh(np.sqrt((GSTOP - 1.0) / (GPASS - 1.0))) + ord = int(ceil(v_pass_stop / arccosh(nat))) + + # Find frequency where analog response is -gpass dB. + # Then convert back from low-pass prototype to the original filter. + + new_freq = cosh(1.0 / ord * v_pass_stop) + new_freq = 1.0 / new_freq + + if filter_type == 1: + nat = passb / new_freq + elif filter_type == 2: + nat = passb * new_freq + elif filter_type == 3: + nat = np.empty(2, float) + nat[0] = (new_freq / 2.0 * (passb[0] - passb[1]) + + sqrt(new_freq ** 2 * (passb[1] - passb[0]) ** 2 / 4.0 + + passb[1] * passb[0])) + nat[1] = passb[1] * passb[0] / nat[0] + elif filter_type == 4: + nat = np.empty(2, float) + nat[0] = (1.0 / (2.0 * new_freq) * (passb[0] - passb[1]) + + sqrt((passb[1] - passb[0]) ** 2 / (4.0 * new_freq ** 2) + + passb[1] * passb[0])) + nat[1] = passb[0] * passb[1] / nat[0] + + wn = _postprocess_wn(nat, analog, fs) + + return ord, wn + + +_POW10_LOG10 = np.log(10) + + +def _pow10m1(x): + """10 ** x - 1 for x near 0""" + return np.expm1(_POW10_LOG10 * x) + + +def ellipord(wp, ws, gpass, gstop, analog=False, fs=None): + """Elliptic (Cauer) filter order selection. + + Return the order of the lowest order digital or analog elliptic filter + that loses no more than `gpass` dB in the passband and has at least + `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for an Elliptic (Cauer) filter that meets specs. + wn : ndarray or float + The Chebyshev natural frequency (the "3dB frequency") for use with + `ellip` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `ellip`. + + See Also + -------- + ellip : Filter design using order and critical points + buttord : Find order and critical points from passband and stopband spec + cheb1ord, cheb2ord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design an analog highpass filter such that the passband is within 3 dB + above 30 rad/s, while rejecting -60 dB at 10 rad/s. Plot its + frequency response, showing the passband and stopband constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.ellipord(30, 10, 3, 60, True) + >>> b, a = signal.ellip(N, 3, 60, Wn, 'high', True) + >>> w, h = signal.freqs(b, a, np.logspace(0, 3, 500)) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Elliptical highpass filter fit to constraints') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([.1, 10, 10, .1], [1e4, 1e4, -60, -60], '0.9', lw=0) # stop + >>> plt.fill([30, 30, 1e9, 1e9], [-99, -3, -3, -99], '0.9', lw=0) # pass + >>> plt.axis([1, 300, -80, 3]) + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + _validate_gpass_gstop(gpass, gstop) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'ellip') + + arg1_sq = _pow10m1(0.1 * gpass) / _pow10m1(0.1 * gstop) + arg0 = 1.0 / nat + d0 = special.ellipk(arg0 ** 2), special.ellipkm1(arg0 ** 2) + d1 = special.ellipk(arg1_sq), special.ellipkm1(arg1_sq) + ord = int(ceil(d0[0] * d1[1] / (d0[1] * d1[0]))) + + wn = _postprocess_wn(passb, analog, fs) + + return ord, wn + + +def buttap(N): + """Return (z,p,k) for analog prototype of Nth-order Butterworth filter. + + The filter will have an angular (e.g., rad/s) cutoff frequency of 1. + + See Also + -------- + butter : Filter design function using this prototype + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + z = np.array([]) + m = np.arange(-N+1, N, 2) + # Middle value is 0 to ensure an exactly real pole + p = -np.exp(1j * pi * m / (2 * N)) + k = 1 + return z, p, k + + +def cheb1ap(N, rp): + """ + Return (z,p,k) for Nth-order Chebyshev type I analog lowpass filter. + + The returned filter prototype has `rp` decibels of ripple in the passband. + + The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1, + defined as the point at which the gain first drops below ``-rp``. + + See Also + -------- + cheby1 : Filter design function using this prototype + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + elif N == 0: + # Avoid divide-by-zero error + # Even order filters have DC gain of -rp dB + return np.array([]), np.array([]), 10**(-rp/20) + z = np.array([]) + + # Ripple factor (epsilon) + eps = np.sqrt(10 ** (0.1 * rp) - 1.0) + mu = 1.0 / N * arcsinh(1 / eps) + + # Arrange poles in an ellipse on the left half of the S-plane + m = np.arange(-N+1, N, 2) + theta = pi * m / (2*N) + p = -sinh(mu + 1j*theta) + + k = np.prod(-p, axis=0).real + if N % 2 == 0: + k = k / sqrt(1 + eps * eps) + + return z, p, k + + +def cheb2ap(N, rs): + """ + Return (z,p,k) for Nth-order Chebyshev type II analog lowpass filter. + + The returned filter prototype has attenuation of at least ``rs`` decibels + in the stopband. + + The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1, + defined as the point at which the attenuation first reaches ``rs``. + + See Also + -------- + cheby2 : Filter design function using this prototype + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + elif N == 0: + # Avoid divide-by-zero warning + return np.array([]), np.array([]), 1 + + # Ripple factor (epsilon) + de = 1.0 / sqrt(10 ** (0.1 * rs) - 1) + mu = arcsinh(1.0 / de) / N + + if N % 2: + m = np.concatenate((np.arange(-N+1, 0, 2), np.arange(2, N, 2))) + else: + m = np.arange(-N+1, N, 2) + + z = -conjugate(1j / sin(m * pi / (2.0 * N))) + + # Poles around the unit circle like Butterworth + p = -exp(1j * pi * np.arange(-N+1, N, 2) / (2 * N)) + # Warp into Chebyshev II + p = sinh(mu) * p.real + 1j * cosh(mu) * p.imag + p = 1.0 / p + + k = (np.prod(-p, axis=0) / np.prod(-z, axis=0)).real + return z, p, k + + +EPSILON = 2e-16 + +# number of terms in solving degree equation +_ELLIPDEG_MMAX = 7 + + +def _ellipdeg(n, m1): + """Solve degree equation using nomes + + Given n, m1, solve + n * K(m) / K'(m) = K1(m1) / K1'(m1) + for m + + See [1], Eq. (49) + + References + ---------- + .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design", + https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf + """ + K1 = special.ellipk(m1) + K1p = special.ellipkm1(m1) + + q1 = np.exp(-np.pi * K1p / K1) + q = q1 ** (1/n) + + mnum = np.arange(_ELLIPDEG_MMAX + 1) + mden = np.arange(1, _ELLIPDEG_MMAX + 2) + + num = np.sum(q ** (mnum * (mnum+1))) + den = 1 + 2 * np.sum(q ** (mden**2)) + + return 16 * q * (num / den) ** 4 + + +# Maximum number of iterations in Landen transformation recursion +# sequence. 10 is conservative; unit tests pass with 4, Orfanidis +# (see _arc_jac_cn [1]) suggests 5. +_ARC_JAC_SN_MAXITER = 10 + + +def _arc_jac_sn(w, m): + """Inverse Jacobian elliptic sn + + Solve for z in w = sn(z, m) + + Parameters + ---------- + w : complex scalar + argument + + m : scalar + modulus; in interval [0, 1] + + + See [1], Eq. (56) + + References + ---------- + .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design", + https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf + + """ + + def _complement(kx): + # (1-k**2) ** 0.5; the expression below + # works for small kx + return ((1 - kx) * (1 + kx)) ** 0.5 + + k = m ** 0.5 + + if k > 1: + return np.nan + elif k == 1: + return np.arctanh(w) + + ks = [k] + niter = 0 + while ks[-1] != 0: + k_ = ks[-1] + k_p = _complement(k_) + ks.append((1 - k_p) / (1 + k_p)) + niter += 1 + if niter > _ARC_JAC_SN_MAXITER: + raise ValueError('Landen transformation not converging') + + K = np.prod(1 + np.array(ks[1:])) * np.pi/2 + + wns = [w] + + for kn, knext in zip(ks[:-1], ks[1:]): + wn = wns[-1] + wnext = (2 * wn / + ((1 + knext) * (1 + _complement(kn * wn)))) + wns.append(wnext) + + u = 2 / np.pi * np.arcsin(wns[-1]) + + z = K * u + return z + + +def _arc_jac_sc1(w, m): + """Real inverse Jacobian sc, with complementary modulus + + Solve for z in w = sc(z, 1-m) + + w - real scalar + + m - modulus + + From [1], sc(z, m) = -i * sn(i * z, 1 - m) + + References + ---------- + # noqa: E501 + .. [1] https://functions.wolfram.com/EllipticFunctions/JacobiSC/introductions/JacobiPQs/ShowAll.html, + "Representations through other Jacobi functions" + + """ + + zcomplex = _arc_jac_sn(1j * w, m) + if abs(zcomplex.real) > 1e-14: + raise ValueError + + return zcomplex.imag + + +def ellipap(N, rp, rs): + """Return (z,p,k) of Nth-order elliptic analog lowpass filter. + + The filter is a normalized prototype that has `rp` decibels of ripple + in the passband and a stopband `rs` decibels down. + + The filter's angular (e.g., rad/s) cutoff frequency is normalized to 1, + defined as the point at which the gain first drops below ``-rp``. + + See Also + -------- + ellip : Filter design function using this prototype + + References + ---------- + .. [1] Lutovac, Tosic, and Evans, "Filter Design for Signal Processing", + Chapters 5 and 12. + + .. [2] Orfanidis, "Lecture Notes on Elliptic Filter Design", + https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + elif N == 0: + # Avoid divide-by-zero warning + # Even order filters have DC gain of -rp dB + return np.array([]), np.array([]), 10**(-rp/20) + elif N == 1: + p = -sqrt(1.0 / _pow10m1(0.1 * rp)) + k = -p + z = [] + return asarray(z), asarray(p), k + + eps_sq = _pow10m1(0.1 * rp) + + eps = np.sqrt(eps_sq) + ck1_sq = eps_sq / _pow10m1(0.1 * rs) + if ck1_sq == 0: + raise ValueError("Cannot design a filter with given rp and rs" + " specifications.") + + val = special.ellipk(ck1_sq), special.ellipkm1(ck1_sq) + + m = _ellipdeg(N, ck1_sq) + + capk = special.ellipk(m) + + j = np.arange(1 - N % 2, N, 2) + jj = len(j) + + [s, c, d, phi] = special.ellipj(j * capk / N, m * np.ones(jj)) + snew = np.compress(abs(s) > EPSILON, s, axis=-1) + z = 1.0 / (sqrt(m) * snew) + z = 1j * z + z = np.concatenate((z, conjugate(z))) + + r = _arc_jac_sc1(1. / eps, ck1_sq) + v0 = capk * r / (N * val[0]) + + [sv, cv, dv, phi] = special.ellipj(v0, 1 - m) + p = -(c * d * sv * cv + 1j * s * dv) / (1 - (d * sv) ** 2.0) + + if N % 2: + newp = np.compress( + abs(p.imag) > EPSILON * np.sqrt(np.sum(p * np.conjugate(p), axis=0).real), + p, axis=-1 + ) + p = np.concatenate((p, conjugate(newp))) + else: + p = np.concatenate((p, conjugate(p))) + + k = (np.prod(-p, axis=0) / np.prod(-z, axis=0)).real + if N % 2 == 0: + k = k / np.sqrt(1 + eps_sq) + + return z, p, k + + +# TODO: Make this a real public function scipy.misc.ff +def _falling_factorial(x, n): + r""" + Return the factorial of `x` to the `n` falling. + + This is defined as: + + .. math:: x^\underline n = (x)_n = x (x-1) \cdots (x-n+1) + + This can more efficiently calculate ratios of factorials, since: + + n!/m! == falling_factorial(n, n-m) + + where n >= m + + skipping the factors that cancel out + + the usual factorial n! == ff(n, n) + """ + val = 1 + for k in range(x - n + 1, x + 1): + val *= k + return val + + +def _bessel_poly(n, reverse=False): + """ + Return the coefficients of Bessel polynomial of degree `n` + + If `reverse` is true, a reverse Bessel polynomial is output. + + Output is a list of coefficients: + [1] = 1 + [1, 1] = 1*s + 1 + [1, 3, 3] = 1*s^2 + 3*s + 3 + [1, 6, 15, 15] = 1*s^3 + 6*s^2 + 15*s + 15 + [1, 10, 45, 105, 105] = 1*s^4 + 10*s^3 + 45*s^2 + 105*s + 105 + etc. + + Output is a Python list of arbitrary precision long ints, so n is only + limited by your hardware's memory. + + Sequence is http://oeis.org/A001498, and output can be confirmed to + match http://oeis.org/A001498/b001498.txt : + + >>> from scipy.signal._filter_design import _bessel_poly + >>> i = 0 + >>> for n in range(51): + ... for x in _bessel_poly(n, reverse=True): + ... print(i, x) + ... i += 1 + + """ + if abs(int(n)) != n: + raise ValueError("Polynomial order must be a nonnegative integer") + else: + n = int(n) # np.int32 doesn't work, for instance + + out = [] + for k in range(n + 1): + num = _falling_factorial(2*n - k, n) + den = 2**(n - k) * math.factorial(k) + out.append(num // den) + + if reverse: + return out[::-1] + else: + return out + + +def _campos_zeros(n): + """ + Return approximate zero locations of Bessel polynomials y_n(x) for order + `n` using polynomial fit (Campos-Calderon 2011) + """ + if n == 1: + return asarray([-1+0j]) + + s = npp_polyval(n, [0, 0, 2, 0, -3, 1]) + b3 = npp_polyval(n, [16, -8]) / s + b2 = npp_polyval(n, [-24, -12, 12]) / s + b1 = npp_polyval(n, [8, 24, -12, -2]) / s + b0 = npp_polyval(n, [0, -6, 0, 5, -1]) / s + + r = npp_polyval(n, [0, 0, 2, 1]) + a1 = npp_polyval(n, [-6, -6]) / r + a2 = 6 / r + + k = np.arange(1, n+1) + x = npp_polyval(k, [0, a1, a2]) + y = npp_polyval(k, [b0, b1, b2, b3]) + + return x + 1j*y + + +def _aberth(f, fp, x0, tol=1e-15, maxiter=50): + """ + Given a function `f`, its first derivative `fp`, and a set of initial + guesses `x0`, simultaneously find the roots of the polynomial using the + Aberth-Ehrlich method. + + ``len(x0)`` should equal the number of roots of `f`. + + (This is not a complete implementation of Bini's algorithm.) + """ + + N = len(x0) + + x = array(x0, complex) + beta = np.empty_like(x0) + + for iteration in range(maxiter): + alpha = -f(x) / fp(x) # Newton's method + + # Model "repulsion" between zeros + for k in range(N): + beta[k] = np.sum(1/(x[k] - x[k+1:])) + beta[k] += np.sum(1/(x[k] - x[:k])) + + x += alpha / (1 + alpha * beta) + + if not all(np.isfinite(x)): + raise RuntimeError('Root-finding calculation failed') + + # Mekwi: The iterative process can be stopped when |hn| has become + # less than the largest error one is willing to permit in the root. + if all(abs(alpha) <= tol): + break + else: + raise Exception('Zeros failed to converge') + + return x + + +def _bessel_zeros(N): + """ + Find zeros of ordinary Bessel polynomial of order `N`, by root-finding of + modified Bessel function of the second kind + """ + if N == 0: + return asarray([]) + + # Generate starting points + x0 = _campos_zeros(N) + + # Zeros are the same for exp(1/x)*K_{N+0.5}(1/x) and Nth-order ordinary + # Bessel polynomial y_N(x) + def f(x): + return special.kve(N+0.5, 1/x) + + # First derivative of above + def fp(x): + return (special.kve(N-0.5, 1/x)/(2*x**2) - + special.kve(N+0.5, 1/x)/(x**2) + + special.kve(N+1.5, 1/x)/(2*x**2)) + + # Starting points converge to true zeros + x = _aberth(f, fp, x0) + + # Improve precision using Newton's method on each + for i in range(len(x)): + x[i] = optimize.newton(f, x[i], fp, tol=1e-15) + + # Average complex conjugates to make them exactly symmetrical + x = np.mean((x, x[::-1].conj()), 0) + + # Zeros should sum to -1 + if abs(np.sum(x) + 1) > 1e-15: + raise RuntimeError('Generated zeros are inaccurate') + + return x + + +def _norm_factor(p, k): + """ + Numerically find frequency shift to apply to delay-normalized filter such + that -3 dB point is at 1 rad/sec. + + `p` is an array_like of polynomial poles + `k` is a float gain + + First 10 values are listed in "Bessel Scale Factors" table, + "Bessel Filters Polynomials, Poles and Circuit Elements 2003, C. Bond." + """ + p = asarray(p, dtype=complex) + + def G(w): + """ + Gain of filter + """ + return abs(k / prod(1j*w - p)) + + def cutoff(w): + """ + When gain = -3 dB, return 0 + """ + return G(w) - 1/np.sqrt(2) + + return optimize.newton(cutoff, 1.5) + + +def besselap(N, norm='phase'): + """ + Return (z,p,k) for analog prototype of an Nth-order Bessel filter. + + Parameters + ---------- + N : int + The order of the filter. + norm : {'phase', 'delay', 'mag'}, optional + Frequency normalization: + + ``phase`` + The filter is normalized such that the phase response reaches its + midpoint at an angular (e.g., rad/s) cutoff frequency of 1. This + happens for both low-pass and high-pass filters, so this is the + "phase-matched" case. [6]_ + + The magnitude response asymptotes are the same as a Butterworth + filter of the same order with a cutoff of `Wn`. + + This is the default, and matches MATLAB's implementation. + + ``delay`` + The filter is normalized such that the group delay in the passband + is 1 (e.g., 1 second). This is the "natural" type obtained by + solving Bessel polynomials + + ``mag`` + The filter is normalized such that the gain magnitude is -3 dB at + angular frequency 1. This is called "frequency normalization" by + Bond. [1]_ + + .. versionadded:: 0.18.0 + + Returns + ------- + z : ndarray + Zeros of the transfer function. Is always an empty array. + p : ndarray + Poles of the transfer function. + k : scalar + Gain of the transfer function. For phase-normalized, this is always 1. + + See Also + -------- + bessel : Filter design function using this prototype + + Notes + ----- + To find the pole locations, approximate starting points are generated [2]_ + for the zeros of the ordinary Bessel polynomial [3]_, then the + Aberth-Ehrlich method [4]_ [5]_ is used on the Kv(x) Bessel function to + calculate more accurate zeros, and these locations are then inverted about + the unit circle. + + References + ---------- + .. [1] C.R. Bond, "Bessel Filter Constants", + http://www.crbond.com/papers/bsf.pdf + .. [2] Campos and Calderon, "Approximate closed-form formulas for the + zeros of the Bessel Polynomials", :arXiv:`1105.0957`. + .. [3] Thomson, W.E., "Delay Networks having Maximally Flat Frequency + Characteristics", Proceedings of the Institution of Electrical + Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490. + .. [4] Aberth, "Iteration Methods for Finding all Zeros of a Polynomial + Simultaneously", Mathematics of Computation, Vol. 27, No. 122, + April 1973 + .. [5] Ehrlich, "A modified Newton method for polynomials", Communications + of the ACM, Vol. 10, Issue 2, pp. 107-108, Feb. 1967, + :DOI:`10.1145/363067.363115` + .. [6] Miller and Bohn, "A Bessel Filter Crossover, and Its Relation to + Others", RaneNote 147, 1998, + https://www.ranecommercial.com/legacy/note147.html + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + + N = int(N) # calculation below doesn't always fit in np.int64 + if N == 0: + p = [] + k = 1 + else: + # Find roots of reverse Bessel polynomial + p = 1/_bessel_zeros(N) + + a_last = _falling_factorial(2*N, N) // 2**N + + # Shift them to a different normalization if required + if norm in ('delay', 'mag'): + # Normalized for group delay of 1 + k = a_last + if norm == 'mag': + # -3 dB magnitude point is at 1 rad/sec + norm_factor = _norm_factor(p, k) + p /= norm_factor + k = norm_factor**-N * a_last + elif norm == 'phase': + # Phase-matched (1/2 max phase shift at 1 rad/sec) + # Asymptotes are same as Butterworth filter + p *= 10**(-math.log10(a_last)/N) + k = 1 + else: + raise ValueError('normalization not understood') + + return asarray([]), asarray(p, dtype=complex), float(k) + + +def iirnotch(w0, Q, fs=2.0): + """ + Design second-order IIR notch digital filter. + + A notch filter is a band-stop filter with a narrow bandwidth + (high quality factor). It rejects a narrow frequency band and + leaves the rest of the spectrum little changed. + + Parameters + ---------- + w0 : float + Frequency to remove from a signal. If `fs` is specified, this is in + the same units as `fs`. By default, it is a normalized scalar that must + satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the + sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + notch filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + + See Also + -------- + iirpeak + + Notes + ----- + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing", + Prentice-Hall, 1996 + + Examples + -------- + Design and plot filter to remove the 60 Hz component from a + signal sampled at 200 Hz, using a quality factor Q = 30 + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fs = 200.0 # Sample frequency (Hz) + >>> f0 = 60.0 # Frequency to be removed from signal (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design notch filter + >>> b, a = signal.iirnotch(f0, Q, fs) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6)) + >>> ax[0].plot(freq, 20*np.log10(abs(h)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 100]) + >>> ax[0].set_ylim([-25, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 100]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + """ + + return _design_notch_peak_filter(w0, Q, "notch", fs) + + +def iirpeak(w0, Q, fs=2.0): + """ + Design second-order IIR peak (resonant) digital filter. + + A peak filter is a band-pass filter with a narrow bandwidth + (high quality factor). It rejects components outside a narrow + frequency band. + + Parameters + ---------- + w0 : float + Frequency to be retained in a signal. If `fs` is specified, this is in + the same units as `fs`. By default, it is a normalized scalar that must + satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the + sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + peak filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + + See Also + -------- + iirnotch + + Notes + ----- + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing", + Prentice-Hall, 1996 + + Examples + -------- + Design and plot filter to remove the frequencies other than the 300 Hz + component from a signal sampled at 1000 Hz, using a quality factor Q = 30 + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> fs = 1000.0 # Sample frequency (Hz) + >>> f0 = 300.0 # Frequency to be retained (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design peak filter + >>> b, a = signal.iirpeak(f0, Q, fs) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6)) + >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 500]) + >>> ax[0].set_ylim([-50, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 500]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + """ + + return _design_notch_peak_filter(w0, Q, "peak", fs) + + +def _design_notch_peak_filter(w0, Q, ftype, fs=2.0): + """ + Design notch or peak digital filter. + + Parameters + ---------- + w0 : float + Normalized frequency to remove from a signal. If `fs` is specified, + this is in the same units as `fs`. By default, it is a normalized + scalar that must satisfy ``0 < w0 < 1``, with ``w0 = 1`` + corresponding to half of the sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + notch filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + ftype : str + The type of IIR filter to design: + + - notch filter : ``notch`` + - peak filter : ``peak`` + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0: + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + """ + fs = _validate_fs(fs, allow_none=False) + + # Guarantee that the inputs are floats + w0 = float(w0) + Q = float(Q) + w0 = 2*w0/fs + + # Checks if w0 is within the range + if w0 > 1.0 or w0 < 0.0: + raise ValueError("w0 should be such that 0 < w0 < 1") + + # Get bandwidth + bw = w0/Q + + # Normalize inputs + bw = bw*np.pi + w0 = w0*np.pi + + if ftype not in ("notch", "peak"): + raise ValueError("Unknown ftype.") + + # Compute beta according to Eqs. 11.3.4 (p.575) and 11.3.19 (p.579) from + # reference [1]. Due to assuming a -3 dB attenuation value, i.e, assuming + # gb = 1 / np.sqrt(2), the following terms simplify to: + # (np.sqrt(1.0 - gb**2.0) / gb) = 1 + # (gb / np.sqrt(1.0 - gb**2.0)) = 1 + beta = np.tan(bw/2.0) + + # Compute gain: formula 11.3.6 (p.575) from reference [1] + gain = 1.0/(1.0+beta) + + # Compute numerator b and denominator a + # formulas 11.3.7 (p.575) and 11.3.21 (p.579) + # from reference [1] + if ftype == "notch": + b = gain*np.array([1.0, -2.0*np.cos(w0), 1.0]) + else: + b = (1.0-gain)*np.array([1.0, 0.0, -1.0]) + a = np.array([1.0, -2.0*gain*np.cos(w0), (2.0*gain-1.0)]) + + return b, a + + +def iircomb(w0, Q, ftype='notch', fs=2.0, *, pass_zero=False): + """ + Design IIR notching or peaking digital comb filter. + + A notching comb filter consists of regularly-spaced band-stop filters with + a narrow bandwidth (high quality factor). Each rejects a narrow frequency + band and leaves the rest of the spectrum little changed. + + A peaking comb filter consists of regularly-spaced band-pass filters with + a narrow bandwidth (high quality factor). Each rejects components outside + a narrow frequency band. + + Parameters + ---------- + w0 : float + The fundamental frequency of the comb filter (the spacing between its + peaks). This must evenly divide the sampling frequency. If `fs` is + specified, this is in the same units as `fs`. By default, it is + a normalized scalar that must satisfy ``0 < w0 < 1``, with + ``w0 = 1`` corresponding to half of the sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + notch filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + ftype : {'notch', 'peak'} + The type of comb filter generated by the function. If 'notch', then + the Q factor applies to the notches. If 'peak', then the Q factor + applies to the peaks. Default is 'notch'. + fs : float, optional + The sampling frequency of the signal. Default is 2.0. + pass_zero : bool, optional + If False (default), the notches (nulls) of the filter are centered on + frequencies [0, w0, 2*w0, ...], and the peaks are centered on the + midpoints [w0/2, 3*w0/2, 5*w0/2, ...]. If True, the peaks are centered + on [0, w0, 2*w0, ...] (passing zero frequency) and vice versa. + + .. versionadded:: 1.9.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + + Raises + ------ + ValueError + If `w0` is less than or equal to 0 or greater than or equal to + ``fs/2``, if `fs` is not divisible by `w0`, if `ftype` + is not 'notch' or 'peak' + + See Also + -------- + iirnotch + iirpeak + + Notes + ----- + For implementation details, see [1]_. The TF implementation of the + comb filter is numerically stable even at higher orders due to the + use of a single repeated pole, which won't suffer from precision loss. + + References + ---------- + .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing", + Prentice-Hall, 1996, ch. 11, "Digital Filter Design" + + Examples + -------- + Design and plot notching comb filter at 20 Hz for a + signal sampled at 200 Hz, using quality factor Q = 30 + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fs = 200.0 # Sample frequency (Hz) + >>> f0 = 20.0 # Frequency to be removed from signal (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design notching comb filter + >>> b, a = signal.iircomb(f0, Q, ftype='notch', fs=fs) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> response = abs(h) + >>> # To avoid divide by zero when graphing + >>> response[response == 0] = 1e-20 + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True) + >>> ax[0].plot(freq, 20*np.log10(abs(response)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 100]) + >>> ax[0].set_ylim([-30, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, (np.angle(h)*180/np.pi+180)%360 - 180, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 100]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + + Design and plot peaking comb filter at 250 Hz for a + signal sampled at 1000 Hz, using quality factor Q = 30 + + >>> fs = 1000.0 # Sample frequency (Hz) + >>> f0 = 250.0 # Frequency to be retained (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design peaking filter + >>> b, a = signal.iircomb(f0, Q, ftype='peak', fs=fs, pass_zero=True) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> response = abs(h) + >>> # To avoid divide by zero when graphing + >>> response[response == 0] = 1e-20 + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True) + >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 500]) + >>> ax[0].set_ylim([-80, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, (np.angle(h)*180/np.pi+180)%360 - 180, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 500]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + """ + + # Convert w0, Q, and fs to float + w0 = float(w0) + Q = float(Q) + fs = _validate_fs(fs, allow_none=False) + + # Check for invalid cutoff frequency or filter type + ftype = ftype.lower() + if not 0 < w0 < fs / 2: + raise ValueError(f"w0 must be between 0 and {fs / 2}" + f" (Nyquist), but given {w0}.") + if ftype not in ('notch', 'peak'): + raise ValueError('ftype must be either notch or peak.') + + # Compute the order of the filter + N = round(fs / w0) + + # Check for cutoff frequency divisibility + if abs(w0 - fs/N)/fs > 1e-14: + raise ValueError('fs must be divisible by w0.') + + # Compute frequency in radians and filter bandwidth + # Eq. 11.3.1 (p. 574) from reference [1] + w0 = (2 * np.pi * w0) / fs + w_delta = w0 / Q + + # Define base gain values depending on notch or peak filter + # Compute -3dB attenuation + # Eqs. 11.4.1 and 11.4.2 (p. 582) from reference [1] + if ftype == 'notch': + G0, G = 1, 0 + elif ftype == 'peak': + G0, G = 0, 1 + + # Compute beta according to Eq. 11.5.3 (p. 591) from reference [1]. Due to + # assuming a -3 dB attenuation value, i.e, assuming GB = 1 / np.sqrt(2), + # the following term simplifies to: + # np.sqrt((GB**2 - G0**2) / (G**2 - GB**2)) = 1 + beta = np.tan(N * w_delta / 4) + + # Compute filter coefficients + # Eq 11.5.1 (p. 590) variables a, b, c from reference [1] + ax = (1 - beta) / (1 + beta) + bx = (G0 + G * beta) / (1 + beta) + cx = (G0 - G * beta) / (1 + beta) + + # Last coefficients are negative to get peaking comb that passes zero or + # notching comb that doesn't. + negative_coef = ((ftype == 'peak' and pass_zero) or + (ftype == 'notch' and not pass_zero)) + + # Compute numerator coefficients + # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1] + # b - cz^-N or b + cz^-N + b = np.zeros(N + 1) + b[0] = bx + if negative_coef: + b[-1] = -cx + else: + b[-1] = +cx + + # Compute denominator coefficients + # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1] + # 1 - az^-N or 1 + az^-N + a = np.zeros(N + 1) + a[0] = 1 + if negative_coef: + a[-1] = -ax + else: + a[-1] = +ax + + return b, a + + +def _hz_to_erb(hz): + """ + Utility for converting from frequency (Hz) to the + Equivalent Rectangular Bandwidth (ERB) scale + ERB = frequency / EarQ + minBW + """ + EarQ = 9.26449 + minBW = 24.7 + return hz / EarQ + minBW + + +def gammatone(freq, ftype, order=None, numtaps=None, fs=None): + """ + Gammatone filter design. + + This function computes the coefficients of an FIR or IIR gammatone + digital filter [1]_. + + Parameters + ---------- + freq : float + Center frequency of the filter (expressed in the same units + as `fs`). + ftype : {'fir', 'iir'} + The type of filter the function generates. If 'fir', the function + will generate an Nth order FIR gammatone filter. If 'iir', the + function will generate an 8th order digital IIR filter, modeled as + as 4th order gammatone filter. + order : int, optional + The order of the filter. Only used when ``ftype='fir'``. + Default is 4 to model the human auditory system. Must be between + 0 and 24. + numtaps : int, optional + Length of the filter. Only used when ``ftype='fir'``. + Default is ``fs*0.015`` if `fs` is greater than 1000, + 15 if `fs` is less than or equal to 1000. + fs : float, optional + The sampling frequency of the signal. `freq` must be between + 0 and ``fs/2``. Default is 2. + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials of the filter. + + Raises + ------ + ValueError + If `freq` is less than or equal to 0 or greater than or equal to + ``fs/2``, if `ftype` is not 'fir' or 'iir', if `order` is less than + or equal to 0 or greater than 24 when ``ftype='fir'`` + + See Also + -------- + firwin + iirfilter + + References + ---------- + .. [1] Slaney, Malcolm, "An Efficient Implementation of the + Patterson-Holdsworth Auditory Filter Bank", Apple Computer + Technical Report 35, 1993, pp.3-8, 34-39. + + Examples + -------- + 16-sample 4th order FIR Gammatone filter centered at 440 Hz + + >>> from scipy import signal + >>> signal.gammatone(440, 'fir', numtaps=16, fs=16000) + (array([ 0.00000000e+00, 2.22196719e-07, 1.64942101e-06, 4.99298227e-06, + 1.01993969e-05, 1.63125770e-05, 2.14648940e-05, 2.29947263e-05, + 1.76776931e-05, 2.04980537e-06, -2.72062858e-05, -7.28455299e-05, + -1.36651076e-04, -2.19066855e-04, -3.18905076e-04, -4.33156712e-04]), + [1.0]) + + IIR Gammatone filter centered at 440 Hz + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fc, fs = 440, 16000 + >>> b, a = signal.gammatone(fc, 'iir', fs=fs) + >>> w, h = signal.freqz(b, a) + >>> plt.plot(w * fs / (2 * np.pi), 20 * np.log10(abs(h))) + >>> plt.xscale('log') + >>> plt.title('Gammatone filter frequency response') + >>> plt.xlabel('Frequency [Hz]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(fc, color='green') # cutoff frequency + >>> plt.show() + """ + # Converts freq to float + freq = float(freq) + + # Set sampling rate if not passed + if fs is None: + fs = 2 + fs = _validate_fs(fs, allow_none=False) + + # Check for invalid cutoff frequency or filter type + ftype = ftype.lower() + filter_types = ['fir', 'iir'] + if not 0 < freq < fs / 2: + raise ValueError(f"The frequency must be between 0 and {fs / 2}" + f" (Nyquist), but given {freq}.") + if ftype not in filter_types: + raise ValueError('ftype must be either fir or iir.') + + # Calculate FIR gammatone filter + if ftype == 'fir': + # Set order and numtaps if not passed + if order is None: + order = 4 + order = operator.index(order) + + if numtaps is None: + numtaps = max(int(fs * 0.015), 15) + numtaps = operator.index(numtaps) + + # Check for invalid order + if not 0 < order <= 24: + raise ValueError("Invalid order: order must be > 0 and <= 24.") + + # Gammatone impulse response settings + t = np.arange(numtaps) / fs + bw = 1.019 * _hz_to_erb(freq) + + # Calculate the FIR gammatone filter + b = (t ** (order - 1)) * np.exp(-2 * np.pi * bw * t) + b *= np.cos(2 * np.pi * freq * t) + + # Scale the FIR filter so the frequency response is 1 at cutoff + scale_factor = 2 * (2 * np.pi * bw) ** (order) + scale_factor /= float_factorial(order - 1) + scale_factor /= fs + b *= scale_factor + a = [1.0] + + # Calculate IIR gammatone filter + elif ftype == 'iir': + # Raise warning if order and/or numtaps is passed + if order is not None: + warnings.warn('order is not used for IIR gammatone filter.', stacklevel=2) + if numtaps is not None: + warnings.warn('numtaps is not used for IIR gammatone filter.', stacklevel=2) + + # Gammatone impulse response settings + T = 1./fs + bw = 2 * np.pi * 1.019 * _hz_to_erb(freq) + fr = 2 * freq * np.pi * T + bwT = bw * T + + # Calculate the gain to normalize the volume at the center frequency + g1 = -2 * np.exp(2j * fr) * T + g2 = 2 * np.exp(-(bwT) + 1j * fr) * T + g3 = np.sqrt(3 + 2 ** (3 / 2)) * np.sin(fr) + g4 = np.sqrt(3 - 2 ** (3 / 2)) * np.sin(fr) + g5 = np.exp(2j * fr) + + g = g1 + g2 * (np.cos(fr) - g4) + g *= (g1 + g2 * (np.cos(fr) + g4)) + g *= (g1 + g2 * (np.cos(fr) - g3)) + g *= (g1 + g2 * (np.cos(fr) + g3)) + g /= ((-2 / np.exp(2 * bwT) - 2 * g5 + 2 * (1 + g5) / np.exp(bwT)) ** 4) + g = np.abs(g) + + # Create empty filter coefficient lists + b = np.empty(5) + a = np.empty(9) + + # Calculate the numerator coefficients + b[0] = (T ** 4) / g + b[1] = -4 * T ** 4 * np.cos(fr) / np.exp(bw * T) / g + b[2] = 6 * T ** 4 * np.cos(2 * fr) / np.exp(2 * bw * T) / g + b[3] = -4 * T ** 4 * np.cos(3 * fr) / np.exp(3 * bw * T) / g + b[4] = T ** 4 * np.cos(4 * fr) / np.exp(4 * bw * T) / g + + # Calculate the denominator coefficients + a[0] = 1 + a[1] = -8 * np.cos(fr) / np.exp(bw * T) + a[2] = 4 * (4 + 3 * np.cos(2 * fr)) / np.exp(2 * bw * T) + a[3] = -8 * (6 * np.cos(fr) + np.cos(3 * fr)) + a[3] /= np.exp(3 * bw * T) + a[4] = 2 * (18 + 16 * np.cos(2 * fr) + np.cos(4 * fr)) + a[4] /= np.exp(4 * bw * T) + a[5] = -8 * (6 * np.cos(fr) + np.cos(3 * fr)) + a[5] /= np.exp(5 * bw * T) + a[6] = 4 * (4 + 3 * np.cos(2 * fr)) / np.exp(6 * bw * T) + a[7] = -8 * np.cos(fr) / np.exp(7 * bw * T) + a[8] = np.exp(-8 * bw * T) + + return b, a + + +filter_dict = {'butter': [buttap, buttord], + 'butterworth': [buttap, buttord], + + 'cauer': [ellipap, ellipord], + 'elliptic': [ellipap, ellipord], + 'ellip': [ellipap, ellipord], + + 'bessel': [besselap], + 'bessel_phase': [besselap], + 'bessel_delay': [besselap], + 'bessel_mag': [besselap], + + 'cheby1': [cheb1ap, cheb1ord], + 'chebyshev1': [cheb1ap, cheb1ord], + 'chebyshevi': [cheb1ap, cheb1ord], + + 'cheby2': [cheb2ap, cheb2ord], + 'chebyshev2': [cheb2ap, cheb2ord], + 'chebyshevii': [cheb2ap, cheb2ord], + } + +band_dict = {'band': 'bandpass', + 'bandpass': 'bandpass', + 'pass': 'bandpass', + 'bp': 'bandpass', + + 'bs': 'bandstop', + 'bandstop': 'bandstop', + 'bands': 'bandstop', + 'stop': 'bandstop', + + 'l': 'lowpass', + 'low': 'lowpass', + 'lowpass': 'lowpass', + 'lp': 'lowpass', + + 'high': 'highpass', + 'highpass': 'highpass', + 'h': 'highpass', + 'hp': 'highpass', + } + +bessel_norms = {'bessel': 'phase', + 'bessel_phase': 'phase', + 'bessel_delay': 'delay', + 'bessel_mag': 'mag'} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..b46d1bcc72f5fb03965b66cf131c25c2ca2f5585 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py @@ -0,0 +1,1286 @@ +"""Functions for FIR filter design.""" + +from math import ceil, log +import operator +import warnings +from typing import Literal + +import numpy as np +from numpy.fft import irfft, fft, ifft +from scipy.special import sinc +from scipy.linalg import (toeplitz, hankel, solve, LinAlgError, LinAlgWarning, + lstsq) +from scipy.signal._arraytools import _validate_fs + +from . import _sigtools + +__all__ = ['kaiser_beta', 'kaiser_atten', 'kaiserord', + 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase'] + + +# Some notes on function parameters: +# +# `cutoff` and `width` are given as numbers between 0 and 1. These are +# relative frequencies, expressed as a fraction of the Nyquist frequency. +# For example, if the Nyquist frequency is 2 KHz, then width=0.15 is a width +# of 300 Hz. +# +# The `order` of a FIR filter is one less than the number of taps. +# This is a potential source of confusion, so in the following code, +# we will always use the number of taps as the parameterization of +# the 'size' of the filter. The "number of taps" means the number +# of coefficients, which is the same as the length of the impulse +# response of the filter. + + +def kaiser_beta(a): + """Compute the Kaiser parameter `beta`, given the attenuation `a`. + + Parameters + ---------- + a : float + The desired attenuation in the stopband and maximum ripple in + the passband, in dB. This should be a *positive* number. + + Returns + ------- + beta : float + The `beta` parameter to be used in the formula for a Kaiser window. + + References + ---------- + Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476. + + Examples + -------- + Suppose we want to design a lowpass filter, with 65 dB attenuation + in the stop band. The Kaiser window parameter to be used in the + window method is computed by ``kaiser_beta(65)``: + + >>> from scipy.signal import kaiser_beta + >>> kaiser_beta(65) + 6.20426 + + """ + if a > 50: + beta = 0.1102 * (a - 8.7) + elif a > 21: + beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21) + else: + beta = 0.0 + return beta + + +def kaiser_atten(numtaps, width): + """Compute the attenuation of a Kaiser FIR filter. + + Given the number of taps `N` and the transition width `width`, compute the + attenuation `a` in dB, given by Kaiser's formula: + + a = 2.285 * (N - 1) * pi * width + 7.95 + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. + width : float + The desired width of the transition region between passband and + stopband (or, in general, at any discontinuity) for the filter, + expressed as a fraction of the Nyquist frequency. + + Returns + ------- + a : float + The attenuation of the ripple, in dB. + + See Also + -------- + kaiserord, kaiser_beta + + Examples + -------- + Suppose we want to design a FIR filter using the Kaiser window method + that will have 211 taps and a transition width of 9 Hz for a signal that + is sampled at 480 Hz. Expressed as a fraction of the Nyquist frequency, + the width is 9/(0.5*480) = 0.0375. The approximate attenuation (in dB) + is computed as follows: + + >>> from scipy.signal import kaiser_atten + >>> kaiser_atten(211, 0.0375) + 64.48099630593983 + + """ + a = 2.285 * (numtaps - 1) * np.pi * width + 7.95 + return a + + +def kaiserord(ripple, width): + """ + Determine the filter window parameters for the Kaiser window method. + + The parameters returned by this function are generally used to create + a finite impulse response filter using the window method, with either + `firwin` or `firwin2`. + + Parameters + ---------- + ripple : float + Upper bound for the deviation (in dB) of the magnitude of the + filter's frequency response from that of the desired filter (not + including frequencies in any transition intervals). That is, if w + is the frequency expressed as a fraction of the Nyquist frequency, + A(w) is the actual frequency response of the filter and D(w) is the + desired frequency response, the design requirement is that:: + + abs(A(w) - D(w))) < 10**(-ripple/20) + + for 0 <= w <= 1 and w not in a transition interval. + width : float + Width of transition region, normalized so that 1 corresponds to pi + radians / sample. That is, the frequency is expressed as a fraction + of the Nyquist frequency. + + Returns + ------- + numtaps : int + The length of the Kaiser window. + beta : float + The beta parameter for the Kaiser window. + + See Also + -------- + kaiser_beta, kaiser_atten + + Notes + ----- + There are several ways to obtain the Kaiser window: + + - ``signal.windows.kaiser(numtaps, beta, sym=True)`` + - ``signal.get_window(beta, numtaps)`` + - ``signal.get_window(('kaiser', beta), numtaps)`` + + The empirical equations discovered by Kaiser are used. + + References + ---------- + Oppenheim, Schafer, "Discrete-Time Signal Processing", pp.475-476. + + Examples + -------- + We will use the Kaiser window method to design a lowpass FIR filter + for a signal that is sampled at 1000 Hz. + + We want at least 65 dB rejection in the stop band, and in the pass + band the gain should vary no more than 0.5%. + + We want a cutoff frequency of 175 Hz, with a transition between the + pass band and the stop band of 24 Hz. That is, in the band [0, 163], + the gain varies no more than 0.5%, and in the band [187, 500], the + signal is attenuated by at least 65 dB. + + >>> import numpy as np + >>> from scipy.signal import kaiserord, firwin, freqz + >>> import matplotlib.pyplot as plt + >>> fs = 1000.0 + >>> cutoff = 175 + >>> width = 24 + + The Kaiser method accepts just a single parameter to control the pass + band ripple and the stop band rejection, so we use the more restrictive + of the two. In this case, the pass band ripple is 0.005, or 46.02 dB, + so we will use 65 dB as the design parameter. + + Use `kaiserord` to determine the length of the filter and the + parameter for the Kaiser window. + + >>> numtaps, beta = kaiserord(65, width/(0.5*fs)) + >>> numtaps + 167 + >>> beta + 6.20426 + + Use `firwin` to create the FIR filter. + + >>> taps = firwin(numtaps, cutoff, window=('kaiser', beta), + ... scale=False, fs=fs) + + Compute the frequency response of the filter. ``w`` is the array of + frequencies, and ``h`` is the corresponding complex array of frequency + responses. + + >>> w, h = freqz(taps, worN=8000) + >>> w *= 0.5*fs/np.pi # Convert w to Hz. + + Compute the deviation of the magnitude of the filter's response from + that of the ideal lowpass filter. Values in the transition region are + set to ``nan``, so they won't appear in the plot. + + >>> ideal = w < cutoff # The "ideal" frequency response. + >>> deviation = np.abs(np.abs(h) - ideal) + >>> deviation[(w > cutoff - 0.5*width) & (w < cutoff + 0.5*width)] = np.nan + + Plot the deviation. A close look at the left end of the stop band shows + that the requirement for 65 dB attenuation is violated in the first lobe + by about 0.125 dB. This is not unusual for the Kaiser window method. + + >>> plt.plot(w, 20*np.log10(np.abs(deviation))) + >>> plt.xlim(0, 0.5*fs) + >>> plt.ylim(-90, -60) + >>> plt.grid(alpha=0.25) + >>> plt.axhline(-65, color='r', ls='--', alpha=0.3) + >>> plt.xlabel('Frequency (Hz)') + >>> plt.ylabel('Deviation from ideal (dB)') + >>> plt.title('Lowpass Filter Frequency Response') + >>> plt.show() + + """ + A = abs(ripple) # in case somebody is confused as to what's meant + if A < 8: + # Formula for N is not valid in this range. + raise ValueError("Requested maximum ripple attenuation " + f"{A:f} is too small for the Kaiser formula.") + beta = kaiser_beta(A) + + # Kaiser's formula (as given in Oppenheim and Schafer) is for the filter + # order, so we have to add 1 to get the number of taps. + numtaps = (A - 7.95) / 2.285 / (np.pi * width) + 1 + + return int(ceil(numtaps)), beta + + +def firwin(numtaps, cutoff, *, width=None, window='hamming', pass_zero=True, + scale=True, fs=None): + """ + FIR filter design using the window method. + + This function computes the coefficients of a finite impulse response + filter. The filter will have linear phase; it will be Type I if + `numtaps` is odd and Type II if `numtaps` is even. + + Type II filters always have zero response at the Nyquist frequency, so a + ValueError exception is raised if firwin is called with `numtaps` even and + having a passband whose right end is at the Nyquist frequency. + + Parameters + ---------- + numtaps : int + Length of the filter (number of coefficients, i.e. the filter + order + 1). `numtaps` must be odd if a passband includes the + Nyquist frequency. + cutoff : float or 1-D array_like + Cutoff frequency of filter (expressed in the same units as `fs`) + OR an array of cutoff frequencies (that is, band edges). In the + former case, as a float, the cutoff frequency should correspond + with the half-amplitude point, where the attenuation will be -6dB. + In the latter case, the frequencies in `cutoff` should be positive + and monotonically increasing between 0 and `fs/2`. The values 0 + and `fs/2` must not be included in `cutoff`. It should be noted + that this is different than the behavior of `scipy.signal.iirdesign`, + where the cutoff is the half-power point (-3dB). + width : float or None, optional + If `width` is not None, then assume it is the approximate width + of the transition region (expressed in the same units as `fs`) + for use in Kaiser FIR filter design. In this case, the `window` + argument is ignored. + window : string or tuple of string and parameter values, optional + Desired window to use. See `scipy.signal.get_window` for a list + of windows and required parameters. + pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional + If True, the gain at the frequency 0 (i.e., the "DC gain") is 1. + If False, the DC gain is 0. Can also be a string argument for the + desired filter type (equivalent to ``btype`` in IIR design functions). + + .. versionadded:: 1.3.0 + Support for string arguments. + scale : bool, optional + Set to True to scale the coefficients so that the frequency + response is exactly unity at a certain frequency. + That frequency is either: + + - 0 (DC) if the first passband starts at 0 (i.e. pass_zero + is True) + - `fs/2` (the Nyquist frequency) if the first passband ends at + `fs/2` (i.e the filter is a single band highpass filter); + center of first passband otherwise + + fs : float, optional + The sampling frequency of the signal. Each frequency in `cutoff` + must be between 0 and ``fs/2``. Default is 2. + + Returns + ------- + h : (numtaps,) ndarray + Coefficients of length `numtaps` FIR filter. + + Raises + ------ + ValueError + If any value in `cutoff` is less than or equal to 0 or greater + than or equal to ``fs/2``, if the values in `cutoff` are not strictly + monotonically increasing, or if `numtaps` is even but a passband + includes the Nyquist frequency. + + See Also + -------- + firwin2 + firls + minimum_phase + remez + + Examples + -------- + Low-pass from 0 to f: + + >>> from scipy import signal + >>> numtaps = 3 + >>> f = 0.1 + >>> signal.firwin(numtaps, f) + array([ 0.06799017, 0.86401967, 0.06799017]) + + Use a specific window function: + + >>> signal.firwin(numtaps, f, window='nuttall') + array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04]) + + High-pass ('stop' from 0 to f): + + >>> signal.firwin(numtaps, f, pass_zero=False) + array([-0.00859313, 0.98281375, -0.00859313]) + + Band-pass: + + >>> f1, f2 = 0.1, 0.2 + >>> signal.firwin(numtaps, [f1, f2], pass_zero=False) + array([ 0.06301614, 0.88770441, 0.06301614]) + + Band-stop: + + >>> signal.firwin(numtaps, [f1, f2]) + array([-0.00801395, 1.0160279 , -0.00801395]) + + Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]): + + >>> f3, f4 = 0.3, 0.4 + >>> signal.firwin(numtaps, [f1, f2, f3, f4]) + array([-0.01376344, 1.02752689, -0.01376344]) + + Multi-band (passbands are [f1, f2] and [f3,f4]): + + >>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False) + array([ 0.04890915, 0.91284326, 0.04890915]) + + """ + # The major enhancements to this function added in November 2010 were + # developed by Tom Krauss (see ticket #902). + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + + nyq = 0.5 * fs + + cutoff = np.atleast_1d(cutoff) / float(nyq) + + # Check for invalid input. + if cutoff.ndim > 1: + raise ValueError("The cutoff argument must be at most " + "one-dimensional.") + if cutoff.size == 0: + raise ValueError("At least one cutoff frequency must be given.") + if cutoff.min() <= 0 or cutoff.max() >= 1: + raise ValueError("Invalid cutoff frequency: frequencies must be " + "greater than 0 and less than fs/2.") + if np.any(np.diff(cutoff) <= 0): + raise ValueError("Invalid cutoff frequencies: the frequencies " + "must be strictly increasing.") + + if width is not None: + # A width was given. Find the beta parameter of the Kaiser window + # and set `window`. This overrides the value of `window` passed in. + atten = kaiser_atten(numtaps, float(width) / nyq) + beta = kaiser_beta(atten) + window = ('kaiser', beta) + + if isinstance(pass_zero, str): + if pass_zero in ('bandstop', 'lowpass'): + if pass_zero == 'lowpass': + if cutoff.size != 1: + raise ValueError('cutoff must have one element if ' + f'pass_zero=="lowpass", got {cutoff.shape}') + elif cutoff.size <= 1: + raise ValueError('cutoff must have at least two elements if ' + f'pass_zero=="bandstop", got {cutoff.shape}') + pass_zero = True + elif pass_zero in ('bandpass', 'highpass'): + if pass_zero == 'highpass': + if cutoff.size != 1: + raise ValueError('cutoff must have one element if ' + f'pass_zero=="highpass", got {cutoff.shape}') + elif cutoff.size <= 1: + raise ValueError('cutoff must have at least two elements if ' + f'pass_zero=="bandpass", got {cutoff.shape}') + pass_zero = False + else: + raise ValueError('pass_zero must be True, False, "bandpass", ' + '"lowpass", "highpass", or "bandstop", got ' + f'{pass_zero}') + pass_zero = bool(operator.index(pass_zero)) # ensure bool-like + + pass_nyquist = bool(cutoff.size & 1) ^ pass_zero + if pass_nyquist and numtaps % 2 == 0: + raise ValueError("A filter with an even number of coefficients must " + "have zero response at the Nyquist frequency.") + + # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff + # is even, and each pair in cutoff corresponds to passband. + cutoff = np.hstack(([0.0] * pass_zero, cutoff, [1.0] * pass_nyquist)) + + # `bands` is a 2-D array; each row gives the left and right edges of + # a passband. + bands = cutoff.reshape(-1, 2) + + # Build up the coefficients. + alpha = 0.5 * (numtaps - 1) + m = np.arange(0, numtaps) - alpha + h = 0 + for left, right in bands: + h += right * sinc(right * m) + h -= left * sinc(left * m) + + # Get and apply the window function. + from .windows import get_window + win = get_window(window, numtaps, fftbins=False) + h *= win + + # Now handle scaling if desired. + if scale: + # Get the first passband. + left, right = bands[0] + if left == 0: + scale_frequency = 0.0 + elif right == 1: + scale_frequency = 1.0 + else: + scale_frequency = 0.5 * (left + right) + c = np.cos(np.pi * m * scale_frequency) + s = np.sum(h * c) + h /= s + + return h + + +# Original version of firwin2 from scipy ticket #457, submitted by "tash". +# +# Rewritten by Warren Weckesser, 2010. +def firwin2(numtaps, freq, gain, *, nfreqs=None, window='hamming', + antisymmetric=False, fs=None): + """ + FIR filter design using the window method. + + From the given frequencies `freq` and corresponding gains `gain`, + this function constructs an FIR filter with linear phase and + (approximately) the given frequency response. + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. `numtaps` must be less than + `nfreqs`. + freq : array_like, 1-D + The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being + Nyquist. The Nyquist frequency is half `fs`. + The values in `freq` must be nondecreasing. A value can be repeated + once to implement a discontinuity. The first value in `freq` must + be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must + not be repeated. + gain : array_like + The filter gains at the frequency sampling points. Certain + constraints to gain values, depending on the filter type, are applied, + see Notes for details. + nfreqs : int, optional + The size of the interpolation mesh used to construct the filter. + For most efficient behavior, this should be a power of 2 plus 1 + (e.g, 129, 257, etc). The default is one more than the smallest + power of 2 that is not less than `numtaps`. `nfreqs` must be greater + than `numtaps`. + window : string or (string, float) or float, or None, optional + Window function to use. Default is "hamming". See + `scipy.signal.get_window` for the complete list of possible values. + If None, no window function is applied. + antisymmetric : bool, optional + Whether resulting impulse response is symmetric/antisymmetric. + See Notes for more details. + fs : float, optional + The sampling frequency of the signal. Each frequency in `cutoff` + must be between 0 and ``fs/2``. Default is 2. + + Returns + ------- + taps : ndarray + The filter coefficients of the FIR filter, as a 1-D array of length + `numtaps`. + + See Also + -------- + firls + firwin + minimum_phase + remez + + Notes + ----- + From the given set of frequencies and gains, the desired response is + constructed in the frequency domain. The inverse FFT is applied to the + desired response to create the associated convolution kernel, and the + first `numtaps` coefficients of this kernel, scaled by `window`, are + returned. + + The FIR filter will have linear phase. The type of filter is determined by + the value of 'numtaps` and `antisymmetric` flag. + There are four possible combinations: + + - odd `numtaps`, `antisymmetric` is False, type I filter is produced + - even `numtaps`, `antisymmetric` is False, type II filter is produced + - odd `numtaps`, `antisymmetric` is True, type III filter is produced + - even `numtaps`, `antisymmetric` is True, type IV filter is produced + + Magnitude response of all but type I filters are subjects to following + constraints: + + - type II -- zero at the Nyquist frequency + - type III -- zero at zero and Nyquist frequencies + - type IV -- zero at zero frequency + + .. versionadded:: 0.9.0 + + References + ---------- + .. [1] Oppenheim, A. V. and Schafer, R. W., "Discrete-Time Signal + Processing", Prentice-Hall, Englewood Cliffs, New Jersey (1989). + (See, for example, Section 7.4.) + + .. [2] Smith, Steven W., "The Scientist and Engineer's Guide to Digital + Signal Processing", Ch. 17. http://www.dspguide.com/ch17/1.htm + + Examples + -------- + A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and + that decreases linearly on [0.5, 1.0] from 1 to 0: + + >>> from scipy import signal + >>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) + >>> print(taps[72:78]) + [-0.02286961 -0.06362756 0.57310236 0.57310236 -0.06362756 -0.02286961] + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + nyq = 0.5 * fs + + if len(freq) != len(gain): + raise ValueError('freq and gain must be of same length.') + + if nfreqs is not None and numtaps >= nfreqs: + raise ValueError(('ntaps must be less than nfreqs, but firwin2 was ' + 'called with ntaps=%d and nfreqs=%s') % + (numtaps, nfreqs)) + + if freq[0] != 0 or freq[-1] != nyq: + raise ValueError('freq must start with 0 and end with fs/2.') + d = np.diff(freq) + if (d < 0).any(): + raise ValueError('The values in freq must be nondecreasing.') + d2 = d[:-1] + d[1:] + if (d2 == 0).any(): + raise ValueError('A value in freq must not occur more than twice.') + if freq[1] == 0: + raise ValueError('Value 0 must not be repeated in freq') + if freq[-2] == nyq: + raise ValueError('Value fs/2 must not be repeated in freq') + + if antisymmetric: + if numtaps % 2 == 0: + ftype = 4 + else: + ftype = 3 + else: + if numtaps % 2 == 0: + ftype = 2 + else: + ftype = 1 + + if ftype == 2 and gain[-1] != 0.0: + raise ValueError("A Type II filter must have zero gain at the " + "Nyquist frequency.") + elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0): + raise ValueError("A Type III filter must have zero gain at zero " + "and Nyquist frequencies.") + elif ftype == 4 and gain[0] != 0.0: + raise ValueError("A Type IV filter must have zero gain at zero " + "frequency.") + + if nfreqs is None: + nfreqs = 1 + 2 ** int(ceil(log(numtaps, 2))) + + if (d == 0).any(): + # Tweak any repeated values in freq so that interp works. + freq = np.array(freq, copy=True) + eps = np.finfo(float).eps * nyq + for k in range(len(freq) - 1): + if freq[k] == freq[k + 1]: + freq[k] = freq[k] - eps + freq[k + 1] = freq[k + 1] + eps + # Check if freq is strictly increasing after tweak + d = np.diff(freq) + if (d <= 0).any(): + raise ValueError("freq cannot contain numbers that are too close " + "(within eps * (fs/2): " + f"{eps}) to a repeated value") + + # Linearly interpolate the desired response on a uniform mesh `x`. + x = np.linspace(0.0, nyq, nfreqs) + fx = np.interp(x, freq, gain) + + # Adjust the phases of the coefficients so that the first `ntaps` of the + # inverse FFT are the desired filter coefficients. + shift = np.exp(-(numtaps - 1) / 2. * 1.j * np.pi * x / nyq) + if ftype > 2: + shift *= 1j + + fx2 = fx * shift + + # Use irfft to compute the inverse FFT. + out_full = irfft(fx2) + + if window is not None: + # Create the window to apply to the filter coefficients. + from .windows import get_window + wind = get_window(window, numtaps, fftbins=False) + else: + wind = 1 + + # Keep only the first `numtaps` coefficients in `out`, and multiply by + # the window. + out = out_full[:numtaps] * wind + + if ftype == 3: + out[out.size // 2] = 0.0 + + return out + + +def remez(numtaps, bands, desired, *, weight=None, type='bandpass', + maxiter=25, grid_density=16, fs=None): + """ + Calculate the minimax optimal filter using the Remez exchange algorithm. + + Calculate the filter-coefficients for the finite impulse response + (FIR) filter whose transfer function minimizes the maximum error + between the desired gain and the realized gain in the specified + frequency bands using the Remez exchange algorithm. + + Parameters + ---------- + numtaps : int + The desired number of taps in the filter. The number of taps is + the number of terms in the filter, or the filter order plus one. + bands : array_like + A monotonic sequence containing the band edges. + All elements must be non-negative and less than half the sampling + frequency as given by `fs`. + desired : array_like + A sequence half the size of bands containing the desired gain + in each of the specified bands. + weight : array_like, optional + A relative weighting to give to each band region. The length of + `weight` has to be half the length of `bands`. + type : {'bandpass', 'differentiator', 'hilbert'}, optional + The type of filter: + + * 'bandpass' : flat response in bands. This is the default. + + * 'differentiator' : frequency proportional response in bands. + + * 'hilbert' : filter with odd symmetry, that is, type III + (for even order) or type IV (for odd order) + linear phase filters. + + maxiter : int, optional + Maximum number of iterations of the algorithm. Default is 25. + grid_density : int, optional + Grid density. The dense grid used in `remez` is of size + ``(numtaps + 1) * grid_density``. Default is 16. + fs : float, optional + The sampling frequency of the signal. Default is 1. + + Returns + ------- + out : ndarray + A rank-1 array containing the coefficients of the optimal + (in a minimax sense) filter. + + See Also + -------- + firls + firwin + firwin2 + minimum_phase + + References + ---------- + .. [1] J. H. McClellan and T. W. Parks, "A unified approach to the + design of optimum FIR linear phase digital filters", + IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973. + .. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer + Program for Designing Optimum FIR Linear Phase Digital + Filters", IEEE Trans. Audio Electroacoust., vol. AU-21, + pp. 506-525, 1973. + + Examples + -------- + In these examples, `remez` is used to design low-pass, high-pass, + band-pass and band-stop filters. The parameters that define each filter + are the filter order, the band boundaries, the transition widths of the + boundaries, the desired gains in each band, and the sampling frequency. + + We'll use a sample frequency of 22050 Hz in all the examples. In each + example, the desired gain in each band is either 0 (for a stop band) + or 1 (for a pass band). + + `freqz` is used to compute the frequency response of each filter, and + the utility function ``plot_response`` defined below is used to plot + the response. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> fs = 22050 # Sample rate, Hz + + >>> def plot_response(w, h, title): + ... "Utility function to plot response functions" + ... fig = plt.figure() + ... ax = fig.add_subplot(111) + ... ax.plot(w, 20*np.log10(np.abs(h))) + ... ax.set_ylim(-40, 5) + ... ax.grid(True) + ... ax.set_xlabel('Frequency (Hz)') + ... ax.set_ylabel('Gain (dB)') + ... ax.set_title(title) + + The first example is a low-pass filter, with cutoff frequency 8 kHz. + The filter length is 325, and the transition width from pass to stop + is 100 Hz. + + >>> cutoff = 8000.0 # Desired cutoff frequency, Hz + >>> trans_width = 100 # Width of transition from pass to stop, Hz + >>> numtaps = 325 # Size of the FIR filter. + >>> taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5*fs], + ... [1, 0], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Low-pass Filter") + >>> plt.show() + + This example shows a high-pass filter: + + >>> cutoff = 2000.0 # Desired cutoff frequency, Hz + >>> trans_width = 250 # Width of transition from pass to stop, Hz + >>> numtaps = 125 # Size of the FIR filter. + >>> taps = signal.remez(numtaps, [0, cutoff - trans_width, cutoff, 0.5*fs], + ... [0, 1], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "High-pass Filter") + >>> plt.show() + + This example shows a band-pass filter with a pass-band from 2 kHz to + 5 kHz. The transition width is 260 Hz and the length of the filter + is 63, which is smaller than in the other examples: + + >>> band = [2000, 5000] # Desired pass band, Hz + >>> trans_width = 260 # Width of transition from pass to stop, Hz + >>> numtaps = 63 # Size of the FIR filter. + >>> edges = [0, band[0] - trans_width, band[0], band[1], + ... band[1] + trans_width, 0.5*fs] + >>> taps = signal.remez(numtaps, edges, [0, 1, 0], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Band-pass Filter") + >>> plt.show() + + The low order leads to higher ripple and less steep transitions. + + The next example shows a band-stop filter. + + >>> band = [6000, 8000] # Desired stop band, Hz + >>> trans_width = 200 # Width of transition from pass to stop, Hz + >>> numtaps = 175 # Size of the FIR filter. + >>> edges = [0, band[0] - trans_width, band[0], band[1], + ... band[1] + trans_width, 0.5*fs] + >>> taps = signal.remez(numtaps, edges, [1, 0, 1], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Band-stop Filter") + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 1.0 if fs is None else fs + + # Convert type + try: + tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type] + except KeyError as e: + raise ValueError("Type must be 'bandpass', 'differentiator', " + "or 'hilbert'") from e + + # Convert weight + if weight is None: + weight = [1] * len(desired) + + bands = np.asarray(bands).copy() + return _sigtools._remez(numtaps, bands, desired, weight, tnum, fs, + maxiter, grid_density) + + +def firls(numtaps, bands, desired, *, weight=None, fs=None): + """ + FIR filter design using least-squares error minimization. + + Calculate the filter coefficients for the linear-phase finite + impulse response (FIR) filter which has the best approximation + to the desired frequency response described by `bands` and + `desired` in the least squares sense (i.e., the integral of the + weighted mean-squared error within the specified bands is + minimized). + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. `numtaps` must be odd. + bands : array_like + A monotonic nondecreasing sequence containing the band edges in + Hz. All elements must be non-negative and less than or equal to + the Nyquist frequency given by `nyq`. The bands are specified as + frequency pairs, thus, if using a 1D array, its length must be + even, e.g., `np.array([0, 1, 2, 3, 4, 5])`. Alternatively, the + bands can be specified as an nx2 sized 2D array, where n is the + number of bands, e.g, `np.array([[0, 1], [2, 3], [4, 5]])`. + desired : array_like + A sequence the same size as `bands` containing the desired gain + at the start and end point of each band. + weight : array_like, optional + A relative weighting to give to each band region when solving + the least squares problem. `weight` has to be half the size of + `bands`. + fs : float, optional + The sampling frequency of the signal. Each frequency in `bands` + must be between 0 and ``fs/2`` (inclusive). Default is 2. + + Returns + ------- + coeffs : ndarray + Coefficients of the optimal (in a least squares sense) FIR filter. + + See Also + -------- + firwin + firwin2 + minimum_phase + remez + + Notes + ----- + This implementation follows the algorithm given in [1]_. + As noted there, least squares design has multiple advantages: + + 1. Optimal in a least-squares sense. + 2. Simple, non-iterative method. + 3. The general solution can obtained by solving a linear + system of equations. + 4. Allows the use of a frequency dependent weighting function. + + This function constructs a Type I linear phase FIR filter, which + contains an odd number of `coeffs` satisfying for :math:`n < numtaps`: + + .. math:: coeffs(n) = coeffs(numtaps - 1 - n) + + The odd number of coefficients and filter symmetry avoid boundary + conditions that could otherwise occur at the Nyquist and 0 frequencies + (e.g., for Type II, III, or IV variants). + + .. versionadded:: 0.18 + + References + ---------- + .. [1] Ivan Selesnick, Linear-Phase Fir Filter Design By Least Squares. + OpenStax CNX. Aug 9, 2005. + https://eeweb.engineering.nyu.edu/iselesni/EL713/firls/firls.pdf + + Examples + -------- + We want to construct a band-pass filter. Note that the behavior in the + frequency ranges between our stop bands and pass bands is unspecified, + and thus may overshoot depending on the parameters of our filter: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> fig, axs = plt.subplots(2) + >>> fs = 10.0 # Hz + >>> desired = (0, 0, 1, 1, 0, 0) + >>> for bi, bands in enumerate(((0, 1, 2, 3, 4, 5), (0, 1, 2, 4, 4.5, 5))): + ... fir_firls = signal.firls(73, bands, desired, fs=fs) + ... fir_remez = signal.remez(73, bands, desired[::2], fs=fs) + ... fir_firwin2 = signal.firwin2(73, bands, desired, fs=fs) + ... hs = list() + ... ax = axs[bi] + ... for fir in (fir_firls, fir_remez, fir_firwin2): + ... freq, response = signal.freqz(fir) + ... hs.append(ax.semilogy(0.5*fs*freq/np.pi, np.abs(response))[0]) + ... for band, gains in zip(zip(bands[::2], bands[1::2]), + ... zip(desired[::2], desired[1::2])): + ... ax.semilogy(band, np.maximum(gains, 1e-7), 'k--', linewidth=2) + ... if bi == 0: + ... ax.legend(hs, ('firls', 'remez', 'firwin2'), + ... loc='lower center', frameon=False) + ... else: + ... ax.set_xlabel('Frequency (Hz)') + ... ax.grid(True) + ... ax.set(title='Band-pass %d-%d Hz' % bands[2:4], ylabel='Magnitude') + ... + >>> fig.tight_layout() + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + nyq = 0.5 * fs + + numtaps = int(numtaps) + if numtaps % 2 == 0 or numtaps < 1: + raise ValueError("numtaps must be odd and >= 1") + M = (numtaps-1) // 2 + + # normalize bands 0->1 and make it 2 columns + nyq = float(nyq) + if nyq <= 0: + raise ValueError(f'nyq must be positive, got {nyq} <= 0.') + bands = np.asarray(bands).flatten() / nyq + if len(bands) % 2 != 0: + raise ValueError("bands must contain frequency pairs.") + if (bands < 0).any() or (bands > 1).any(): + raise ValueError("bands must be between 0 and 1 relative to Nyquist") + bands.shape = (-1, 2) + + # check remaining params + desired = np.asarray(desired).flatten() + if bands.size != desired.size: + raise ValueError( + f"desired must have one entry per frequency, got {desired.size} " + f"gains for {bands.size} frequencies." + ) + desired.shape = (-1, 2) + if (np.diff(bands) <= 0).any() or (np.diff(bands[:, 0]) < 0).any(): + raise ValueError("bands must be monotonically nondecreasing and have " + "width > 0.") + if (bands[:-1, 1] > bands[1:, 0]).any(): + raise ValueError("bands must not overlap.") + if (desired < 0).any(): + raise ValueError("desired must be non-negative.") + if weight is None: + weight = np.ones(len(desired)) + weight = np.asarray(weight).flatten() + if len(weight) != len(desired): + raise ValueError("weight must be the same size as the number of " + f"band pairs ({len(bands)}).") + if (weight < 0).any(): + raise ValueError("weight must be non-negative.") + + # Set up the linear matrix equation to be solved, Qa = b + + # We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n) + # where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel. + + # We omit the factor of 0.5 above, instead adding it during coefficient + # calculation. + + # We also omit the 1/π from both Q and b equations, as they cancel + # during solving. + + # We have that: + # q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π) + # Using our normalization ω=πf and with a constant weight W over each + # interval f1->f2 we get: + # q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf + # integrated over each f1->f2 pair (i.e., value at f2 - value at f1). + n = np.arange(numtaps)[:, np.newaxis, np.newaxis] + q = np.dot(np.diff(np.sinc(bands * n) * bands, axis=2)[:, :, 0], weight) + + # Now we assemble our sum of Toeplitz and Hankel + Q1 = toeplitz(q[:M+1]) + Q2 = hankel(q[:M+1], q[M:]) + Q = Q1 + Q2 + + # Now for b(n) we have that: + # b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π) + # Using our normalization ω=πf and with a constant weight W over each + # interval and a linear term for D(ω) we get (over each f1->f2 interval): + # b(n) = W ∫ (mf+c)cos(πnf)df + # = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2 + # integrated over each f1->f2 pair (i.e., value at f2 - value at f1). + n = n[:M + 1] # only need this many coefficients here + # Choose m and c such that we are at the start and end weights + m = (np.diff(desired, axis=1) / np.diff(bands, axis=1)) + c = desired[:, [0]] - bands[:, [0]] * m + b = bands * (m*bands + c) * np.sinc(bands * n) + # Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0 + b[0] -= m * bands * bands / 2. + b[1:] += m * np.cos(n[1:] * np.pi * bands) / (np.pi * n[1:]) ** 2 + b = np.dot(np.diff(b, axis=2)[:, :, 0], weight) + + # Now we can solve the equation + try: # try the fast way + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + a = solve(Q, b, assume_a="pos", check_finite=False) + for ww in w: + if (ww.category == LinAlgWarning and + str(ww.message).startswith('Ill-conditioned matrix')): + raise LinAlgError(str(ww.message)) + except LinAlgError: # in case Q is rank deficient + # This is faster than pinvh, even though we don't explicitly use + # the symmetry here. gelsy was faster than gelsd and gelss in + # some non-exhaustive tests. + a = lstsq(Q, b, lapack_driver='gelsy')[0] + + # make coefficients symmetric (linear phase) + coeffs = np.hstack((a[:0:-1], 2 * a[0], a[1:])) + return coeffs + + +def _dhtm(mag): + """Compute the modified 1-D discrete Hilbert transform + + Parameters + ---------- + mag : ndarray + The magnitude spectrum. Should be 1-D with an even length, and + preferably a fast length for FFT/IFFT. + """ + # Adapted based on code by Niranjan Damera-Venkata, + # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`) + sig = np.zeros(len(mag)) + # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5 + midpt = len(mag) // 2 + sig[1:midpt] = 1 + sig[midpt+1:] = -1 + # eventually if we want to support complex filters, we will need a + # np.abs() on the mag inside the log, and should remove the .real + recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real + return recon + + +def minimum_phase(h: np.ndarray, + method: Literal['homomorphic', 'hilbert'] = 'homomorphic', + n_fft: int | None = None, *, half: bool = True) -> np.ndarray: + """Convert a linear-phase FIR filter to minimum phase + + Parameters + ---------- + h : array + Linear-phase FIR filter coefficients. + method : {'hilbert', 'homomorphic'} + The provided methods are: + + 'homomorphic' (default) + This method [4]_ [5]_ works best with filters with an + odd number of taps, and the resulting minimum phase filter + will have a magnitude response that approximates the square + root of the original filter's magnitude response using half + the number of taps when ``half=True`` (default), or the + original magnitude spectrum using the same number of taps + when ``half=False``. + + 'hilbert' + This method [1]_ is designed to be used with equiripple + filters (e.g., from `remez`) with unity or zero gain + regions. + + n_fft : int + The number of points to use for the FFT. Should be at least a + few times larger than the signal length (see Notes). + half : bool + If ``True``, create a filter that is half the length of the original, with a + magnitude spectrum that is the square root of the original. If ``False``, + create a filter that is the same length as the original, with a magnitude + spectrum that is designed to match the original (only supported when + ``method='homomorphic'``). + + .. versionadded:: 1.14.0 + + Returns + ------- + h_minimum : array + The minimum-phase version of the filter, with length + ``(len(h) + 1) // 2`` when ``half is True`` or ``len(h)`` otherwise. + + See Also + -------- + firwin + firwin2 + remez + + Notes + ----- + Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection + of an FFT length to estimate the complex cepstrum of the filter. + + In the case of the Hilbert method, the deviation from the ideal + spectrum ``epsilon`` is related to the number of stopband zeros + ``n_stop`` and FFT length ``n_fft`` as:: + + epsilon = 2. * n_stop / n_fft + + For example, with 100 stopband zeros and a FFT length of 2048, + ``epsilon = 0.0976``. If we conservatively assume that the number of + stopband zeros is one less than the filter length, we can take the FFT + length to be the next power of 2 that satisfies ``epsilon=0.01`` as:: + + n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01))) + + This gives reasonable results for both the Hilbert and homomorphic + methods, and gives the value used when ``n_fft=None``. + + Alternative implementations exist for creating minimum-phase filters, + including zero inversion [2]_ and spectral factorization [3]_ [4]_. + For more information, see `this DSPGuru page + `__. + + References + ---------- + .. [1] N. Damera-Venkata and B. L. Evans, "Optimal design of real and + complex minimum phase digital FIR filters," Acoustics, Speech, + and Signal Processing, 1999. Proceedings., 1999 IEEE International + Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3. + :doi:`10.1109/ICASSP.1999.756179` + .. [2] X. Chen and T. W. Parks, "Design of optimal minimum phase FIR + filters by direct factorization," Signal Processing, + vol. 10, no. 4, pp. 369-383, Jun. 1986. + .. [3] T. Saramaki, "Finite Impulse Response Filter Design," in + Handbook for Digital Signal Processing, chapter 4, + New York: Wiley-Interscience, 1993. + .. [4] J. S. Lim, Advanced Topics in Signal Processing. + Englewood Cliffs, N.J.: Prentice Hall, 1988. + .. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck, + "Discrete-Time Signal Processing," 3rd edition. + Upper Saddle River, N.J.: Pearson, 2009. + + Examples + -------- + Create an optimal linear-phase low-pass filter `h` with a transition band of + [0.2, 0.3] (assuming a Nyquist frequency of 1): + + >>> import numpy as np + >>> from scipy.signal import remez, minimum_phase, freqz, group_delay + >>> import matplotlib.pyplot as plt + >>> freq = [0, 0.2, 0.3, 1.0] + >>> desired = [1, 0] + >>> h_linear = remez(151, freq, desired, fs=2) + + Convert it to minimum phase: + + >>> h_hil = minimum_phase(h_linear, method='hilbert') + >>> h_hom = minimum_phase(h_linear, method='homomorphic') + >>> h_hom_full = minimum_phase(h_linear, method='homomorphic', half=False) + + Compare the impulse and frequency response of the four filters: + + >>> fig0, ax0 = plt.subplots(figsize=(6, 3), tight_layout=True) + >>> fig1, axs = plt.subplots(3, sharex='all', figsize=(6, 6), tight_layout=True) + >>> ax0.set_title("Impulse response") + >>> ax0.set(xlabel='Samples', ylabel='Amplitude', xlim=(0, len(h_linear) - 1)) + >>> axs[0].set_title("Frequency Response") + >>> axs[0].set(xlim=(0, .65), ylabel="Magnitude / dB") + >>> axs[1].set(ylabel="Phase / rad") + >>> axs[2].set(ylabel="Group Delay / samples", ylim=(-31, 81), + ... xlabel='Normalized Frequency (Nyqist frequency: 1)') + >>> for h, lb in ((h_linear, f'Linear ({len(h_linear)})'), + ... (h_hil, f'Min-Hilbert ({len(h_hil)})'), + ... (h_hom, f'Min-Homomorphic ({len(h_hom)})'), + ... (h_hom_full, f'Min-Homom. Full ({len(h_hom_full)})')): + ... w_H, H = freqz(h, fs=2) + ... w_gd, gd = group_delay((h, 1), fs=2) + ... + ... alpha = 1.0 if lb == 'linear' else 0.5 # full opacity for 'linear' line + ... ax0.plot(h, '.-', alpha=alpha, label=lb) + ... axs[0].plot(w_H, 20 * np.log10(np.abs(H)), alpha=alpha) + ... axs[1].plot(w_H, np.unwrap(np.angle(H)), alpha=alpha, label=lb) + ... axs[2].plot(w_gd, gd, alpha=alpha) + >>> ax0.grid(True) + >>> ax0.legend(title='Filter Phase (Order)') + >>> axs[1].legend(title='Filter Phase (Order)', loc='lower right') + >>> for ax_ in axs: # shade transition band: + ... ax_.axvspan(freq[1], freq[2], color='y', alpha=.25) + ... ax_.grid(True) + >>> plt.show() + + The impulse response and group delay plot depict the 75 sample delay of the linear + phase filter `h`. The phase should also be linear in the stop band--due to the small + magnitude, numeric noise dominates there. Furthermore, the plots show that the + minimum phase filters clearly show a reduced (negative) phase slope in the pass and + transition band. The plots also illustrate that the filter with parameters + ``method='homomorphic', half=False`` has same order and magnitude response as the + linear filter `h` whereas the other minimum phase filters have only half the order + and the square root of the magnitude response. + """ + h = np.asarray(h) + if np.iscomplexobj(h): + raise ValueError('Complex filters not supported') + if h.ndim != 1 or h.size <= 2: + raise ValueError('h must be 1-D and at least 2 samples long') + n_half = len(h) // 2 + if not np.allclose(h[-n_half:][::-1], h[:n_half]): + warnings.warn('h does not appear to by symmetric, conversion may fail', + RuntimeWarning, stacklevel=2) + if not isinstance(method, str) or method not in \ + ('homomorphic', 'hilbert',): + raise ValueError(f'method must be "homomorphic" or "hilbert", got {method!r}') + if method == "hilbert" and not half: + raise ValueError("`half=False` is only supported when `method='homomorphic'`") + if n_fft is None: + n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01))) + n_fft = int(n_fft) + if n_fft < len(h): + raise ValueError(f'n_fft must be at least len(h)=={len(h)}') + if method == 'hilbert': + w = np.arange(n_fft) * (2 * np.pi / n_fft * n_half) + H = np.real(fft(h, n_fft) * np.exp(1j * w)) + dp = max(H) - 1 + ds = 0 - min(H) + S = 4. / (np.sqrt(1+dp+ds) + np.sqrt(1-dp+ds)) ** 2 + H += ds + H *= S + H = np.sqrt(H, out=H) + H += 1e-10 # ensure that the log does not explode + h_minimum = _dhtm(H) + else: # method == 'homomorphic' + # zero-pad; calculate the DFT + h_temp = np.abs(fft(h, n_fft)) + # take 0.25*log(|H|**2) = 0.5*log(|H|) + h_temp += 1e-7 * h_temp[h_temp > 0].min() # don't let log blow up + np.log(h_temp, out=h_temp) + if half: # halving of magnitude spectrum optional + h_temp *= 0.5 + # IDFT + h_temp = ifft(h_temp).real + # multiply pointwise by the homomorphic filter + # lmin[n] = 2u[n] - d[n] + # i.e., double the positive frequencies and zero out the negative ones; + # Oppenheim+Shafer 3rd ed p991 eq13.42b and p1004 fig13.7 + win = np.zeros(n_fft) + win[0] = 1 + stop = n_fft // 2 + win[1:stop] = 2 + if n_fft % 2: + win[stop] = 1 + h_temp *= win + h_temp = ifft(np.exp(fft(h_temp))) + h_minimum = h_temp.real + n_out = (n_half + len(h) % 2) if half else len(h) + return h_minimum[:n_out] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..52c6efbbfa53288934d12918566016db6c742ef1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py @@ -0,0 +1,533 @@ +""" +ltisys -- a collection of functions to convert linear time invariant systems +from one representation to another. +""" + +import numpy as np +from numpy import (r_, eye, atleast_2d, poly, dot, + asarray, zeros, array, outer) +from scipy import linalg + +from ._filter_design import tf2zpk, zpk2tf, normalize + + +__all__ = ['tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk', + 'cont2discrete'] + + +def tf2ss(num, den): + r"""Transfer function to state-space representation. + + Parameters + ---------- + num, den : array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of descending degree. The + denominator needs to be at least as long as the numerator. + + Returns + ------- + A, B, C, D : ndarray + State space representation of the system, in controller canonical + form. + + Examples + -------- + Convert the transfer function: + + .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1} + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + to the state-space representation: + + .. math:: + + \dot{\textbf{x}}(t) = + \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\ + + \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t) + + >>> from scipy.signal import tf2ss + >>> A, B, C, D = tf2ss(num, den) + >>> A + array([[-2., -1.], + [ 1., 0.]]) + >>> B + array([[ 1.], + [ 0.]]) + >>> C + array([[ 1., 2.]]) + >>> D + array([[ 1.]]) + """ + # Controller canonical state-space representation. + # if M+1 = len(num) and K+1 = len(den) then we must have M <= K + # states are found by asserting that X(s) = U(s) / D(s) + # then Y(s) = N(s) * X(s) + # + # A, B, C, and D follow quite naturally. + # + num, den = normalize(num, den) # Strips zeros, checks arrays + nn = len(num.shape) + if nn == 1: + num = asarray([num], num.dtype) + M = num.shape[1] + K = len(den) + if M > K: + msg = "Improper transfer function. `num` is longer than `den`." + raise ValueError(msg) + if M == 0 or K == 0: # Null system + return (array([], float), array([], float), array([], float), + array([], float)) + + # pad numerator to have same number of columns has denominator + num = np.hstack((np.zeros((num.shape[0], K - M), dtype=num.dtype), num)) + + if num.shape[-1] > 0: + D = atleast_2d(num[:, 0]) + + else: + # We don't assign it an empty array because this system + # is not 'null'. It just doesn't have a non-zero D + # matrix. Thus, it should have a non-zero shape so that + # it can be operated on by functions like 'ss2tf' + D = array([[0]], float) + + if K == 1: + D = D.reshape(num.shape) + + return (zeros((1, 1)), zeros((1, D.shape[1])), + zeros((D.shape[0], 1)), D) + + frow = -array([den[1:]]) + A = r_[frow, eye(K - 2, K - 1)] + B = eye(K - 1, 1) + C = num[:, 1:] - outer(num[:, 0], den[1:]) + D = D.reshape((C.shape[0], B.shape[1])) + + return A, B, C, D + + +def _none_to_empty_2d(arg): + if arg is None: + return zeros((0, 0)) + else: + return arg + + +def _atleast_2d_or_none(arg): + if arg is not None: + return atleast_2d(arg) + + +def _shape_or_none(M): + if M is not None: + return M.shape + else: + return (None,) * 2 + + +def _choice_not_none(*args): + for arg in args: + if arg is not None: + return arg + + +def _restore(M, shape): + if M.shape == (0, 0): + return zeros(shape) + else: + if M.shape != shape: + raise ValueError("The input arrays have incompatible shapes.") + return M + + +def abcd_normalize(A=None, B=None, C=None, D=None): + """Check state-space matrices and ensure they are 2-D. + + If enough information on the system is provided, that is, enough + properly-shaped arrays are passed to the function, the missing ones + are built from this information, ensuring the correct number of + rows and columns. Otherwise a ValueError is raised. + + Parameters + ---------- + A, B, C, D : array_like, optional + State-space matrices. All of them are None (missing) by default. + See `ss2tf` for format. + + Returns + ------- + A, B, C, D : array + Properly shaped state-space matrices. + + Raises + ------ + ValueError + If not enough information on the system was provided. + + """ + A, B, C, D = map(_atleast_2d_or_none, (A, B, C, D)) + + MA, NA = _shape_or_none(A) + MB, NB = _shape_or_none(B) + MC, NC = _shape_or_none(C) + MD, ND = _shape_or_none(D) + + p = _choice_not_none(MA, MB, NC) + q = _choice_not_none(NB, ND) + r = _choice_not_none(MC, MD) + if p is None or q is None or r is None: + raise ValueError("Not enough information on the system.") + + A, B, C, D = map(_none_to_empty_2d, (A, B, C, D)) + A = _restore(A, (p, p)) + B = _restore(B, (p, q)) + C = _restore(C, (r, p)) + D = _restore(D, (r, q)) + + return A, B, C, D + + +def ss2tf(A, B, C, D, input=0): + r"""State-space to transfer function. + + A, B, C, D defines a linear state-space system with `p` inputs, + `q` outputs, and `n` state variables. + + Parameters + ---------- + A : array_like + State (or system) matrix of shape ``(n, n)`` + B : array_like + Input matrix of shape ``(n, p)`` + C : array_like + Output matrix of shape ``(q, n)`` + D : array_like + Feedthrough (or feedforward) matrix of shape ``(q, p)`` + input : int, optional + For multiple-input systems, the index of the input to use. + + Returns + ------- + num : 2-D ndarray + Numerator(s) of the resulting transfer function(s). `num` has one row + for each of the system's outputs. Each row is a sequence representation + of the numerator polynomial. + den : 1-D ndarray + Denominator of the resulting transfer function(s). `den` is a sequence + representation of the denominator polynomial. + + Examples + -------- + Convert the state-space representation: + + .. math:: + + \dot{\textbf{x}}(t) = + \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\ + + \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t) + + >>> A = [[-2, -1], [1, 0]] + >>> B = [[1], [0]] # 2-D column vector + >>> C = [[1, 2]] # 2-D row vector + >>> D = 1 + + to the transfer function: + + .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1} + + >>> from scipy.signal import ss2tf + >>> ss2tf(A, B, C, D) + (array([[1., 3., 3.]]), array([ 1., 2., 1.])) + """ + # transfer function is C (sI - A)**(-1) B + D + + # Check consistency and make them all rank-2 arrays + A, B, C, D = abcd_normalize(A, B, C, D) + + nout, nin = D.shape + if input >= nin: + raise ValueError("System does not have the input specified.") + + # make SIMO from possibly MIMO system. + B = B[:, input:input + 1] + D = D[:, input:input + 1] + + try: + den = poly(A) + except ValueError: + den = 1 + + if (B.size == 0) and (C.size == 0): + num = np.ravel(D) + if (D.size == 0) and (A.size == 0): + den = [] + return num, den + + num_states = A.shape[0] + type_test = A[:, 0] + B[:, 0] + C[0, :] + D + 0.0 + num = np.empty((nout, num_states + 1), type_test.dtype) + for k in range(nout): + Ck = atleast_2d(C[k, :]) + num[k] = poly(A - dot(B, Ck)) + (D[k] - 1) * den + + return num, den + + +def zpk2ss(z, p, k): + """Zero-pole-gain representation to state-space representation + + Parameters + ---------- + z, p : sequence + Zeros and poles. + k : float + System gain. + + Returns + ------- + A, B, C, D : ndarray + State space representation of the system, in controller canonical + form. + + """ + return tf2ss(*zpk2tf(z, p, k)) + + +def ss2zpk(A, B, C, D, input=0): + """State-space representation to zero-pole-gain representation. + + A, B, C, D defines a linear state-space system with `p` inputs, + `q` outputs, and `n` state variables. + + Parameters + ---------- + A : array_like + State (or system) matrix of shape ``(n, n)`` + B : array_like + Input matrix of shape ``(n, p)`` + C : array_like + Output matrix of shape ``(q, n)`` + D : array_like + Feedthrough (or feedforward) matrix of shape ``(q, p)`` + input : int, optional + For multiple-input systems, the index of the input to use. + + Returns + ------- + z, p : sequence + Zeros and poles. + k : float + System gain. + + """ + return tf2zpk(*ss2tf(A, B, C, D, input=input)) + + +def cont2discrete(system, dt, method="zoh", alpha=None): + """ + Transform a continuous to a discrete state-space system. + + Parameters + ---------- + system : a tuple describing the system or an instance of `lti` + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `lti`) + * 2: (num, den) + * 3: (zeros, poles, gain) + * 4: (A, B, C, D) + + dt : float + The discretization time step. + method : str, optional + Which method to use: + + * gbt: generalized bilinear transformation + * bilinear: Tustin's approximation ("gbt" with alpha=0.5) + * euler: Euler (or forward differencing) method ("gbt" with alpha=0) + * backward_diff: Backwards differencing ("gbt" with alpha=1.0) + * zoh: zero-order hold (default) + * foh: first-order hold (*versionadded: 1.3.0*) + * impulse: equivalent impulse response (*versionadded: 1.3.0*) + + alpha : float within [0, 1], optional + The generalized bilinear transformation weighting parameter, which + should only be specified with method="gbt", and is ignored otherwise + + Returns + ------- + sysd : tuple containing the discrete system + Based on the input type, the output will be of the form + + * (num, den, dt) for transfer function input + * (zeros, poles, gain, dt) for zeros-poles-gain input + * (A, B, C, D, dt) for state-space system input + + Notes + ----- + By default, the routine uses a Zero-Order Hold (zoh) method to perform + the transformation. Alternatively, a generalized bilinear transformation + may be used, which includes the common Tustin's bilinear approximation, + an Euler's method technique, or a backwards differencing technique. + + The Zero-Order Hold (zoh) method is based on [1]_, the generalized bilinear + approximation is based on [2]_ and [3]_, the First-Order Hold (foh) method + is based on [4]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Discretization#Discretization_of_linear_state_space_models + + .. [2] http://techteach.no/publications/discretetime_signals_systems/discrete.pdf + + .. [3] G. Zhang, X. Chen, and T. Chen, Digital redesign via the generalized + bilinear transformation, Int. J. Control, vol. 82, no. 4, pp. 741-754, + 2009. + (https://www.mypolyuweb.hk/~magzhang/Research/ZCC09_IJC.pdf) + + .. [4] G. F. Franklin, J. D. Powell, and M. L. Workman, Digital control + of dynamic systems, 3rd ed. Menlo Park, Calif: Addison-Wesley, + pp. 204-206, 1998. + + Examples + -------- + We can transform a continuous state-space system to a discrete one: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cont2discrete, lti, dlti, dstep + + Define a continuous state-space system. + + >>> A = np.array([[0, 1],[-10., -3]]) + >>> B = np.array([[0],[10.]]) + >>> C = np.array([[1., 0]]) + >>> D = np.array([[0.]]) + >>> l_system = lti(A, B, C, D) + >>> t, x = l_system.step(T=np.linspace(0, 5, 100)) + >>> fig, ax = plt.subplots() + >>> ax.plot(t, x, label='Continuous', linewidth=3) + + Transform it to a discrete state-space system using several methods. + + >>> dt = 0.1 + >>> for method in ['zoh', 'bilinear', 'euler', 'backward_diff', 'foh', 'impulse']: + ... d_system = cont2discrete((A, B, C, D), dt, method=method) + ... s, x_d = dstep(d_system) + ... ax.step(s, np.squeeze(x_d), label=method, where='post') + >>> ax.axis([t[0], t[-1], x[0], 1.4]) + >>> ax.legend(loc='best') + >>> fig.tight_layout() + >>> plt.show() + + """ + if len(system) == 1: + return system.to_discrete() + if len(system) == 2: + sysd = cont2discrete(tf2ss(system[0], system[1]), dt, method=method, + alpha=alpha) + return ss2tf(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,) + elif len(system) == 3: + sysd = cont2discrete(zpk2ss(system[0], system[1], system[2]), dt, + method=method, alpha=alpha) + return ss2zpk(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,) + elif len(system) == 4: + a, b, c, d = system + else: + raise ValueError("First argument must either be a tuple of 2 (tf), " + "3 (zpk), or 4 (ss) arrays.") + + if method == 'gbt': + if alpha is None: + raise ValueError("Alpha parameter must be specified for the " + "generalized bilinear transform (gbt) method") + elif alpha < 0 or alpha > 1: + raise ValueError("Alpha parameter must be within the interval " + "[0,1] for the gbt method") + + if method == 'gbt': + # This parameter is used repeatedly - compute once here + ima = np.eye(a.shape[0]) - alpha*dt*a + ad = linalg.solve(ima, np.eye(a.shape[0]) + (1.0-alpha)*dt*a) + bd = linalg.solve(ima, dt*b) + + # Similarly solve for the output equation matrices + cd = linalg.solve(ima.transpose(), c.transpose()) + cd = cd.transpose() + dd = d + alpha*np.dot(c, bd) + + elif method == 'bilinear' or method == 'tustin': + return cont2discrete(system, dt, method="gbt", alpha=0.5) + + elif method == 'euler' or method == 'forward_diff': + return cont2discrete(system, dt, method="gbt", alpha=0.0) + + elif method == 'backward_diff': + return cont2discrete(system, dt, method="gbt", alpha=1.0) + + elif method == 'zoh': + # Build an exponential matrix + em_upper = np.hstack((a, b)) + + # Need to stack zeros under the a and b matrices + em_lower = np.hstack((np.zeros((b.shape[1], a.shape[0])), + np.zeros((b.shape[1], b.shape[1])))) + + em = np.vstack((em_upper, em_lower)) + ms = linalg.expm(dt * em) + + # Dispose of the lower rows + ms = ms[:a.shape[0], :] + + ad = ms[:, 0:a.shape[1]] + bd = ms[:, a.shape[1]:] + + cd = c + dd = d + + elif method == 'foh': + # Size parameters for convenience + n = a.shape[0] + m = b.shape[1] + + # Build an exponential matrix similar to 'zoh' method + em_upper = linalg.block_diag(np.block([a, b]) * dt, np.eye(m)) + em_lower = zeros((m, n + 2 * m)) + em = np.block([[em_upper], [em_lower]]) + + ms = linalg.expm(em) + + # Get the three blocks from upper rows + ms11 = ms[:n, 0:n] + ms12 = ms[:n, n:n + m] + ms13 = ms[:n, n + m:] + + ad = ms11 + bd = ms12 - ms13 + ms11 @ ms13 + cd = c + dd = d + c @ ms13 + + elif method == 'impulse': + if not np.allclose(d, 0): + raise ValueError("Impulse method is only applicable " + "to strictly proper systems") + + ad = linalg.expm(a * dt) + bd = ad @ b * dt + cd = c + dd = c @ b * dt + + else: + raise ValueError(f"Unknown transformation method '{method}'") + + return ad, bd, cd, dd, dt diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_ltisys.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_ltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..3992797a09a3ceee4be1f052603fcd6593ae6274 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_ltisys.py @@ -0,0 +1,3519 @@ +""" +ltisys -- a collection of classes and functions for modeling linear +time invariant systems. +""" +# +# Author: Travis Oliphant 2001 +# +# Feb 2010: Warren Weckesser +# Rewrote lsim2 and added impulse2. +# Apr 2011: Jeffrey Armstrong +# Added dlsim, dstep, dimpulse, cont2discrete +# Aug 2013: Juan Luis Cano +# Rewrote abcd_normalize. +# Jan 2015: Irvin Probst irvin DOT probst AT ensta-bretagne DOT fr +# Added pole placement +# Mar 2015: Clancy Rowley +# Rewrote lsim +# May 2015: Felix Berkenkamp +# Split lti class into subclasses +# Merged discrete systems and added dlti + +import warnings + +# np.linalg.qr fails on some tests with LinAlgError: zgeqrf returns -7 +# use scipy's qr until this is solved + +from scipy.linalg import qr as s_qr +from scipy import linalg +from scipy.interpolate import make_interp_spline +from ._filter_design import (tf2zpk, zpk2tf, normalize, freqs, freqz, freqs_zpk, + freqz_zpk) +from ._lti_conversion import (tf2ss, abcd_normalize, ss2tf, zpk2ss, ss2zpk, + cont2discrete, _atleast_2d_or_none) + +import numpy as np +from numpy import (real, atleast_1d, squeeze, asarray, zeros, + dot, transpose, ones, linspace) +import copy + +__all__ = ['lti', 'dlti', 'TransferFunction', 'ZerosPolesGain', 'StateSpace', + 'lsim', 'impulse', 'step', 'bode', + 'freqresp', 'place_poles', 'dlsim', 'dstep', 'dimpulse', + 'dfreqresp', 'dbode'] + + +class LinearTimeInvariant: + def __new__(cls, *system, **kwargs): + """Create a new object, don't allow direct instances.""" + if cls is LinearTimeInvariant: + raise NotImplementedError('The LinearTimeInvariant class is not ' + 'meant to be used directly, use `lti` ' + 'or `dlti` instead.') + return super().__new__(cls) + + def __init__(self): + """ + Initialize the `lti` baseclass. + + The heavy lifting is done by the subclasses. + """ + super().__init__() + + self.inputs = None + self.outputs = None + self._dt = None + + @property + def dt(self): + """Return the sampling time of the system, `None` for `lti` systems.""" + return self._dt + + @property + def _dt_dict(self): + if self.dt is None: + return {} + else: + return {'dt': self.dt} + + @property + def zeros(self): + """Zeros of the system.""" + return self.to_zpk().zeros + + @property + def poles(self): + """Poles of the system.""" + return self.to_zpk().poles + + def _as_ss(self): + """Convert to `StateSpace` system, without copying. + + Returns + ------- + sys: StateSpace + The `StateSpace` system. If the class is already an instance of + `StateSpace` then this instance is returned. + """ + if isinstance(self, StateSpace): + return self + else: + return self.to_ss() + + def _as_zpk(self): + """Convert to `ZerosPolesGain` system, without copying. + + Returns + ------- + sys: ZerosPolesGain + The `ZerosPolesGain` system. If the class is already an instance of + `ZerosPolesGain` then this instance is returned. + """ + if isinstance(self, ZerosPolesGain): + return self + else: + return self.to_zpk() + + def _as_tf(self): + """Convert to `TransferFunction` system, without copying. + + Returns + ------- + sys: ZerosPolesGain + The `TransferFunction` system. If the class is already an instance of + `TransferFunction` then this instance is returned. + """ + if isinstance(self, TransferFunction): + return self + else: + return self.to_tf() + + +class lti(LinearTimeInvariant): + r""" + Continuous-time linear time invariant system base class. + + Parameters + ---------- + *system : arguments + The `lti` class can be instantiated with either 2, 3 or 4 arguments. + The following gives the number of arguments and the corresponding + continuous-time subclass that is created: + + * 2: `TransferFunction`: (numerator, denominator) + * 3: `ZerosPolesGain`: (zeros, poles, gain) + * 4: `StateSpace`: (A, B, C, D) + + Each argument can be an array or a sequence. + + See Also + -------- + ZerosPolesGain, StateSpace, TransferFunction, dlti + + Notes + ----- + `lti` instances do not exist directly. Instead, `lti` creates an instance + of one of its subclasses: `StateSpace`, `TransferFunction` or + `ZerosPolesGain`. + + If (numerator, denominator) is passed in for ``*system``, coefficients for + both the numerator and denominator should be specified in descending + exponent order (e.g., ``s^2 + 3s + 5`` would be represented as ``[1, 3, + 5]``). + + Changing the value of properties that are not directly part of the current + system representation (such as the `zeros` of a `StateSpace` system) is + very inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> from scipy import signal + + >>> signal.lti(1, 2, 3, 4) + StateSpaceContinuous( + array([[1]]), + array([[2]]), + array([[3]]), + array([[4]]), + dt: None + ) + + Construct the transfer function + :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> signal.lti([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + Construct the transfer function :math:`H(s) = \frac{3s + 4}{1s + 2}`: + + >>> signal.lti([3, 4], [1, 2]) + TransferFunctionContinuous( + array([3., 4.]), + array([1., 2.]), + dt: None + ) + + """ + def __new__(cls, *system): + """Create an instance of the appropriate subclass.""" + if cls is lti: + N = len(system) + if N == 2: + return TransferFunctionContinuous.__new__( + TransferFunctionContinuous, *system) + elif N == 3: + return ZerosPolesGainContinuous.__new__( + ZerosPolesGainContinuous, *system) + elif N == 4: + return StateSpaceContinuous.__new__(StateSpaceContinuous, + *system) + else: + raise ValueError("`system` needs to be an instance of `lti` " + "or have 2, 3 or 4 arguments.") + # __new__ was called from a subclass, let it call its own functions + return super().__new__(cls) + + def __init__(self, *system): + """ + Initialize the `lti` baseclass. + + The heavy lifting is done by the subclasses. + """ + super().__init__(*system) + + def impulse(self, X0=None, T=None, N=None): + """ + Return the impulse response of a continuous-time system. + See `impulse` for details. + """ + return impulse(self, X0=X0, T=T, N=N) + + def step(self, X0=None, T=None, N=None): + """ + Return the step response of a continuous-time system. + See `step` for details. + """ + return step(self, X0=X0, T=T, N=N) + + def output(self, U, T, X0=None): + """ + Return the response of a continuous-time system to input `U`. + See `lsim` for details. + """ + return lsim(self, U, T, X0=X0) + + def bode(self, w=None, n=100): + """ + Calculate Bode magnitude and phase data of a continuous-time system. + + Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude + [dB] and phase [deg]. See `bode` for details. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> sys = signal.TransferFunction([1], [1, 1]) + >>> w, mag, phase = sys.bode() + + >>> plt.figure() + >>> plt.semilogx(w, mag) # Bode magnitude plot + >>> plt.figure() + >>> plt.semilogx(w, phase) # Bode phase plot + >>> plt.show() + + """ + return bode(self, w=w, n=n) + + def freqresp(self, w=None, n=10000): + """ + Calculate the frequency response of a continuous-time system. + + Returns a 2-tuple containing arrays of frequencies [rad/s] and + complex magnitude. + See `freqresp` for details. + """ + return freqresp(self, w=w, n=n) + + def to_discrete(self, dt, method='zoh', alpha=None): + """Return a discretized version of the current system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` + """ + raise NotImplementedError('to_discrete is not implemented for this ' + 'system class.') + + +class dlti(LinearTimeInvariant): + r""" + Discrete-time linear time invariant system base class. + + Parameters + ---------- + *system: arguments + The `dlti` class can be instantiated with either 2, 3 or 4 arguments. + The following gives the number of arguments and the corresponding + discrete-time subclass that is created: + + * 2: `TransferFunction`: (numerator, denominator) + * 3: `ZerosPolesGain`: (zeros, poles, gain) + * 4: `StateSpace`: (A, B, C, D) + + Each argument can be an array or a sequence. + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to ``True`` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + ZerosPolesGain, StateSpace, TransferFunction, lti + + Notes + ----- + `dlti` instances do not exist directly. Instead, `dlti` creates an instance + of one of its subclasses: `StateSpace`, `TransferFunction` or + `ZerosPolesGain`. + + Changing the value of properties that are not directly part of the current + system representation (such as the `zeros` of a `StateSpace` system) is + very inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + If (numerator, denominator) is passed in for ``*system``, coefficients for + both the numerator and denominator should be specified in descending + exponent order (e.g., ``z^2 + 3z + 5`` would be represented as ``[1, 3, + 5]``). + + .. versionadded:: 0.18.0 + + Examples + -------- + >>> from scipy import signal + + >>> signal.dlti(1, 2, 3, 4) + StateSpaceDiscrete( + array([[1]]), + array([[2]]), + array([[3]]), + array([[4]]), + dt: True + ) + + >>> signal.dlti(1, 2, 3, 4, dt=0.1) + StateSpaceDiscrete( + array([[1]]), + array([[2]]), + array([[3]]), + array([[4]]), + dt: 0.1 + ) + + Construct the transfer function + :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time + of 0.1 seconds: + + >>> signal.dlti([1, 2], [3, 4], 5, dt=0.1) + ZerosPolesGainDiscrete( + array([1, 2]), + array([3, 4]), + 5, + dt: 0.1 + ) + + Construct the transfer function :math:`H(z) = \frac{3z + 4}{1z + 2}` with + a sampling time of 0.1 seconds: + + >>> signal.dlti([3, 4], [1, 2], dt=0.1) + TransferFunctionDiscrete( + array([3., 4.]), + array([1., 2.]), + dt: 0.1 + ) + + """ + def __new__(cls, *system, **kwargs): + """Create an instance of the appropriate subclass.""" + if cls is dlti: + N = len(system) + if N == 2: + return TransferFunctionDiscrete.__new__( + TransferFunctionDiscrete, *system, **kwargs) + elif N == 3: + return ZerosPolesGainDiscrete.__new__(ZerosPolesGainDiscrete, + *system, **kwargs) + elif N == 4: + return StateSpaceDiscrete.__new__(StateSpaceDiscrete, *system, + **kwargs) + else: + raise ValueError("`system` needs to be an instance of `dlti` " + "or have 2, 3 or 4 arguments.") + # __new__ was called from a subclass, let it call its own functions + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """ + Initialize the `lti` baseclass. + + The heavy lifting is done by the subclasses. + """ + dt = kwargs.pop('dt', True) + super().__init__(*system, **kwargs) + + self.dt = dt + + @property + def dt(self): + """Return the sampling time of the system.""" + return self._dt + + @dt.setter + def dt(self, dt): + self._dt = dt + + def impulse(self, x0=None, t=None, n=None): + """ + Return the impulse response of the discrete-time `dlti` system. + See `dimpulse` for details. + """ + return dimpulse(self, x0=x0, t=t, n=n) + + def step(self, x0=None, t=None, n=None): + """ + Return the step response of the discrete-time `dlti` system. + See `dstep` for details. + """ + return dstep(self, x0=x0, t=t, n=n) + + def output(self, u, t, x0=None): + """ + Return the response of the discrete-time system to input `u`. + See `dlsim` for details. + """ + return dlsim(self, u, t, x0=x0) + + def bode(self, w=None, n=100): + r""" + Calculate Bode magnitude and phase data of a discrete-time system. + + Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude + [dB] and phase [deg]. See `dbode` for details. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Construct the transfer function :math:`H(z) = \frac{1}{z^2 + 2z + 3}` + with sampling time 0.5s: + + >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.5) + + Equivalent: signal.dbode(sys) + + >>> w, mag, phase = sys.bode() + + >>> plt.figure() + >>> plt.semilogx(w, mag) # Bode magnitude plot + >>> plt.figure() + >>> plt.semilogx(w, phase) # Bode phase plot + >>> plt.show() + + """ + return dbode(self, w=w, n=n) + + def freqresp(self, w=None, n=10000, whole=False): + """ + Calculate the frequency response of a discrete-time system. + + Returns a 2-tuple containing arrays of frequencies [rad/s] and + complex magnitude. + See `dfreqresp` for details. + + """ + return dfreqresp(self, w=w, n=n, whole=whole) + + +class TransferFunction(LinearTimeInvariant): + r"""Linear Time Invariant system class in transfer function form. + + Represents the system as the continuous-time transfer function + :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j` or the + discrete-time transfer function + :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where + :math:`b` are elements of the numerator `num`, :math:`a` are elements of + the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``. + `TransferFunction` systems inherit additional + functionality from the `lti`, respectively the `dlti` classes, depending on + which system representation is used. + + Parameters + ---------- + *system: arguments + The `TransferFunction` class can be instantiated with 1 or 2 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 2: array_like: (numerator, denominator) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `None` + (continuous-time). Must be specified as a keyword argument, for + example, ``dt=0.1``. + + See Also + -------- + ZerosPolesGain, StateSpace, lti, dlti + tf2ss, tf2zpk, tf2sos + + Notes + ----- + Changing the value of properties that are not part of the + `TransferFunction` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + If (numerator, denominator) is passed in for ``*system``, coefficients + for both the numerator and denominator should be specified in descending + exponent order (e.g. ``s^2 + 3s + 5`` or ``z^2 + 3z + 5`` would be + represented as ``[1, 3, 5]``) + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`: + + >>> from scipy import signal + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + >>> signal.TransferFunction(num, den) + TransferFunctionContinuous( + array([1., 3., 3.]), + array([1., 2., 1.]), + dt: None + ) + + Construct the transfer function + :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of + 0.1 seconds: + + >>> signal.TransferFunction(num, den, dt=0.1) + TransferFunctionDiscrete( + array([1., 3., 3.]), + array([1., 2., 1.]), + dt: 0.1 + ) + + """ + def __new__(cls, *system, **kwargs): + """Handle object conversion if input is an instance of lti.""" + if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): + return system[0].to_tf() + + # Choose whether to inherit from `lti` or from `dlti` + if cls is TransferFunction: + if kwargs.get('dt') is None: + return TransferFunctionContinuous.__new__( + TransferFunctionContinuous, + *system, + **kwargs) + else: + return TransferFunctionDiscrete.__new__( + TransferFunctionDiscrete, + *system, + **kwargs) + + # No special conversion needed + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """Initialize the state space LTI system.""" + # Conversion of lti instances is handled in __new__ + if isinstance(system[0], LinearTimeInvariant): + return + + # Remove system arguments, not needed by parents anymore + super().__init__(**kwargs) + + self._num = None + self._den = None + + self.num, self.den = normalize(*system) + + def __repr__(self): + """Return representation of the system's transfer function""" + return ( + f'{self.__class__.__name__}(\n' + f'{repr(self.num)},\n' + f'{repr(self.den)},\n' + f'dt: {repr(self.dt)}\n)' + ) + + @property + def num(self): + """Numerator of the `TransferFunction` system.""" + return self._num + + @num.setter + def num(self, num): + self._num = atleast_1d(num) + + # Update dimensions + if len(self.num.shape) > 1: + self.outputs, self.inputs = self.num.shape + else: + self.outputs = 1 + self.inputs = 1 + + @property + def den(self): + """Denominator of the `TransferFunction` system.""" + return self._den + + @den.setter + def den(self, den): + self._den = atleast_1d(den) + + def _copy(self, system): + """ + Copy the parameters of another `TransferFunction` object + + Parameters + ---------- + system : `TransferFunction` + The `StateSpace` system that is to be copied + + """ + self.num = system.num + self.den = system.den + + def to_tf(self): + """ + Return a copy of the current `TransferFunction` system. + + Returns + ------- + sys : instance of `TransferFunction` + The current system (copy) + + """ + return copy.deepcopy(self) + + def to_zpk(self): + """ + Convert system representation to `ZerosPolesGain`. + + Returns + ------- + sys : instance of `ZerosPolesGain` + Zeros, poles, gain representation of the current system + + """ + return ZerosPolesGain(*tf2zpk(self.num, self.den), + **self._dt_dict) + + def to_ss(self): + """ + Convert system representation to `StateSpace`. + + Returns + ------- + sys : instance of `StateSpace` + State space model of the current system + + """ + return StateSpace(*tf2ss(self.num, self.den), + **self._dt_dict) + + @staticmethod + def _z_to_zinv(num, den): + """Change a transfer function from the variable `z` to `z**-1`. + + Parameters + ---------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of descending degree of 'z'. + That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``. + + Returns + ------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of ascending degree of 'z**-1'. + That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``. + """ + diff = len(num) - len(den) + if diff > 0: + den = np.hstack((np.zeros(diff), den)) + elif diff < 0: + num = np.hstack((np.zeros(-diff), num)) + return num, den + + @staticmethod + def _zinv_to_z(num, den): + """Change a transfer function from the variable `z` to `z**-1`. + + Parameters + ---------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of ascending degree of 'z**-1'. + That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``. + + Returns + ------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of descending degree of 'z'. + That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``. + """ + diff = len(num) - len(den) + if diff > 0: + den = np.hstack((den, np.zeros(diff))) + elif diff < 0: + num = np.hstack((num, np.zeros(-diff))) + return num, den + + +class TransferFunctionContinuous(TransferFunction, lti): + r""" + Continuous-time Linear Time Invariant system in transfer function form. + + Represents the system as the transfer function + :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j`, where + :math:`b` are elements of the numerator `num`, :math:`a` are elements of + the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``. + Continuous-time `TransferFunction` systems inherit additional + functionality from the `lti` class. + + Parameters + ---------- + *system: arguments + The `TransferFunction` class can be instantiated with 1 or 2 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 2: array_like: (numerator, denominator) + + See Also + -------- + ZerosPolesGain, StateSpace, lti + tf2ss, tf2zpk, tf2sos + + Notes + ----- + Changing the value of properties that are not part of the + `TransferFunction` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + If (numerator, denominator) is passed in for ``*system``, coefficients + for both the numerator and denominator should be specified in descending + exponent order (e.g. ``s^2 + 3s + 5`` would be represented as + ``[1, 3, 5]``) + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`: + + >>> from scipy import signal + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + >>> signal.TransferFunction(num, den) + TransferFunctionContinuous( + array([ 1., 3., 3.]), + array([ 1., 2., 1.]), + dt: None + ) + + """ + + def to_discrete(self, dt, method='zoh', alpha=None): + """ + Returns the discretized `TransferFunction` system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` and `StateSpace` + """ + return TransferFunction(*cont2discrete((self.num, self.den), + dt, + method=method, + alpha=alpha)[:-1], + dt=dt) + + +class TransferFunctionDiscrete(TransferFunction, dlti): + r""" + Discrete-time Linear Time Invariant system in transfer function form. + + Represents the system as the transfer function + :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where + :math:`b` are elements of the numerator `num`, :math:`a` are elements of + the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``. + Discrete-time `TransferFunction` systems inherit additional functionality + from the `dlti` class. + + Parameters + ---------- + *system: arguments + The `TransferFunction` class can be instantiated with 1 or 2 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 2: array_like: (numerator, denominator) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `True` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + ZerosPolesGain, StateSpace, dlti + tf2ss, tf2zpk, tf2sos + + Notes + ----- + Changing the value of properties that are not part of the + `TransferFunction` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. + + If (numerator, denominator) is passed in for ``*system``, coefficients + for both the numerator and denominator should be specified in descending + exponent order (e.g., ``z^2 + 3z + 5`` would be represented as + ``[1, 3, 5]``). + + Examples + -------- + Construct the transfer function + :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of + 0.5 seconds: + + >>> from scipy import signal + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + >>> signal.TransferFunction(num, den, dt=0.5) + TransferFunctionDiscrete( + array([ 1., 3., 3.]), + array([ 1., 2., 1.]), + dt: 0.5 + ) + + """ + pass + + +class ZerosPolesGain(LinearTimeInvariant): + r""" + Linear Time Invariant system class in zeros, poles, gain form. + + Represents the system as the continuous- or discrete-time transfer function + :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is + the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`. + `ZerosPolesGain` systems inherit additional functionality from the `lti`, + respectively the `dlti` classes, depending on which system representation + is used. + + Parameters + ---------- + *system : arguments + The `ZerosPolesGain` class can be instantiated with 1 or 3 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 3: array_like: (zeros, poles, gain) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `None` + (continuous-time). Must be specified as a keyword argument, for + example, ``dt=0.1``. + + + See Also + -------- + TransferFunction, StateSpace, lti, dlti + zpk2ss, zpk2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> from scipy import signal + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + Construct the transfer function + :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time + of 0.1 seconds: + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1) + ZerosPolesGainDiscrete( + array([1, 2]), + array([3, 4]), + 5, + dt: 0.1 + ) + + """ + def __new__(cls, *system, **kwargs): + """Handle object conversion if input is an instance of `lti`""" + if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): + return system[0].to_zpk() + + # Choose whether to inherit from `lti` or from `dlti` + if cls is ZerosPolesGain: + if kwargs.get('dt') is None: + return ZerosPolesGainContinuous.__new__( + ZerosPolesGainContinuous, + *system, + **kwargs) + else: + return ZerosPolesGainDiscrete.__new__( + ZerosPolesGainDiscrete, + *system, + **kwargs + ) + + # No special conversion needed + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """Initialize the zeros, poles, gain system.""" + # Conversion of lti instances is handled in __new__ + if isinstance(system[0], LinearTimeInvariant): + return + + super().__init__(**kwargs) + + self._zeros = None + self._poles = None + self._gain = None + + self.zeros, self.poles, self.gain = system + + def __repr__(self): + """Return representation of the `ZerosPolesGain` system.""" + return ( + f'{self.__class__.__name__}(\n' + f'{repr(self.zeros)},\n' + f'{repr(self.poles)},\n' + f'{repr(self.gain)},\n' + f'dt: {repr(self.dt)}\n)' + ) + + @property + def zeros(self): + """Zeros of the `ZerosPolesGain` system.""" + return self._zeros + + @zeros.setter + def zeros(self, zeros): + self._zeros = atleast_1d(zeros) + + # Update dimensions + if len(self.zeros.shape) > 1: + self.outputs, self.inputs = self.zeros.shape + else: + self.outputs = 1 + self.inputs = 1 + + @property + def poles(self): + """Poles of the `ZerosPolesGain` system.""" + return self._poles + + @poles.setter + def poles(self, poles): + self._poles = atleast_1d(poles) + + @property + def gain(self): + """Gain of the `ZerosPolesGain` system.""" + return self._gain + + @gain.setter + def gain(self, gain): + self._gain = gain + + def _copy(self, system): + """ + Copy the parameters of another `ZerosPolesGain` system. + + Parameters + ---------- + system : instance of `ZerosPolesGain` + The zeros, poles gain system that is to be copied + + """ + self.poles = system.poles + self.zeros = system.zeros + self.gain = system.gain + + def to_tf(self): + """ + Convert system representation to `TransferFunction`. + + Returns + ------- + sys : instance of `TransferFunction` + Transfer function of the current system + + """ + return TransferFunction(*zpk2tf(self.zeros, self.poles, self.gain), + **self._dt_dict) + + def to_zpk(self): + """ + Return a copy of the current 'ZerosPolesGain' system. + + Returns + ------- + sys : instance of `ZerosPolesGain` + The current system (copy) + + """ + return copy.deepcopy(self) + + def to_ss(self): + """ + Convert system representation to `StateSpace`. + + Returns + ------- + sys : instance of `StateSpace` + State space model of the current system + + """ + return StateSpace(*zpk2ss(self.zeros, self.poles, self.gain), + **self._dt_dict) + + +class ZerosPolesGainContinuous(ZerosPolesGain, lti): + r""" + Continuous-time Linear Time Invariant system in zeros, poles, gain form. + + Represents the system as the continuous time transfer function + :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is + the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`. + Continuous-time `ZerosPolesGain` systems inherit additional functionality + from the `lti` class. + + Parameters + ---------- + *system : arguments + The `ZerosPolesGain` class can be instantiated with 1 or 3 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 3: array_like: (zeros, poles, gain) + + See Also + -------- + TransferFunction, StateSpace, lti + zpk2ss, zpk2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + Examples + -------- + Construct the transfer function + :math:`H(s)=\frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> from scipy import signal + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + """ + + def to_discrete(self, dt, method='zoh', alpha=None): + """ + Returns the discretized `ZerosPolesGain` system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` and `ZerosPolesGain` + """ + return ZerosPolesGain( + *cont2discrete((self.zeros, self.poles, self.gain), + dt, + method=method, + alpha=alpha)[:-1], + dt=dt) + + +class ZerosPolesGainDiscrete(ZerosPolesGain, dlti): + r""" + Discrete-time Linear Time Invariant system in zeros, poles, gain form. + + Represents the system as the discrete-time transfer function + :math:`H(z)=k \prod_i (z - q[i]) / \prod_j (z - p[j])`, where :math:`k` is + the `gain`, :math:`q` are the `zeros` and :math:`p` are the `poles`. + Discrete-time `ZerosPolesGain` systems inherit additional functionality + from the `dlti` class. + + Parameters + ---------- + *system : arguments + The `ZerosPolesGain` class can be instantiated with 1 or 3 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 3: array_like: (zeros, poles, gain) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `True` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + TransferFunction, StateSpace, dlti + zpk2ss, zpk2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> from scipy import signal + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + Construct the transfer function + :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time + of 0.1 seconds: + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1) + ZerosPolesGainDiscrete( + array([1, 2]), + array([3, 4]), + 5, + dt: 0.1 + ) + + """ + pass + + +class StateSpace(LinearTimeInvariant): + r""" + Linear Time Invariant system in state-space form. + + Represents the system as the continuous-time, first order differential + equation :math:`\dot{x} = A x + B u` or the discrete-time difference + equation :math:`x[k+1] = A x[k] + B u[k]`. `StateSpace` systems + inherit additional functionality from the `lti`, respectively the `dlti` + classes, depending on which system representation is used. + + Parameters + ---------- + *system: arguments + The `StateSpace` class can be instantiated with 1 or 4 arguments. + The following gives the number of input arguments and their + interpretation: + + * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 4: array_like: (A, B, C, D) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `None` + (continuous-time). Must be specified as a keyword argument, for + example, ``dt=0.1``. + + See Also + -------- + TransferFunction, ZerosPolesGain, lti, dlti + ss2zpk, ss2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `StateSpace` system representation (such as `zeros` or `poles`) is very + inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> from scipy import signal + >>> import numpy as np + >>> a = np.array([[0, 1], [0, 0]]) + >>> b = np.array([[0], [1]]) + >>> c = np.array([[1, 0]]) + >>> d = np.array([[0]]) + + >>> sys = signal.StateSpace(a, b, c, d) + >>> print(sys) + StateSpaceContinuous( + array([[0, 1], + [0, 0]]), + array([[0], + [1]]), + array([[1, 0]]), + array([[0]]), + dt: None + ) + + >>> sys.to_discrete(0.1) + StateSpaceDiscrete( + array([[1. , 0.1], + [0. , 1. ]]), + array([[0.005], + [0.1 ]]), + array([[1, 0]]), + array([[0]]), + dt: 0.1 + ) + + >>> a = np.array([[1, 0.1], [0, 1]]) + >>> b = np.array([[0.005], [0.1]]) + + >>> signal.StateSpace(a, b, c, d, dt=0.1) + StateSpaceDiscrete( + array([[1. , 0.1], + [0. , 1. ]]), + array([[0.005], + [0.1 ]]), + array([[1, 0]]), + array([[0]]), + dt: 0.1 + ) + + """ + + # Override NumPy binary operations and ufuncs + __array_priority__ = 100.0 + __array_ufunc__ = None + + def __new__(cls, *system, **kwargs): + """Create new StateSpace object and settle inheritance.""" + # Handle object conversion if input is an instance of `lti` + if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): + return system[0].to_ss() + + # Choose whether to inherit from `lti` or from `dlti` + if cls is StateSpace: + if kwargs.get('dt') is None: + return StateSpaceContinuous.__new__(StateSpaceContinuous, + *system, **kwargs) + else: + return StateSpaceDiscrete.__new__(StateSpaceDiscrete, + *system, **kwargs) + + # No special conversion needed + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """Initialize the state space lti/dlti system.""" + # Conversion of lti instances is handled in __new__ + if isinstance(system[0], LinearTimeInvariant): + return + + # Remove system arguments, not needed by parents anymore + super().__init__(**kwargs) + + self._A = None + self._B = None + self._C = None + self._D = None + + self.A, self.B, self.C, self.D = abcd_normalize(*system) + + def __repr__(self): + """Return representation of the `StateSpace` system.""" + return ( + f'{self.__class__.__name__}(\n' + f'{repr(self.A)},\n' + f'{repr(self.B)},\n' + f'{repr(self.C)},\n' + f'{repr(self.D)},\n' + f'dt: {repr(self.dt)}\n)' + ) + + def _check_binop_other(self, other): + return isinstance(other, (StateSpace, np.ndarray, float, complex, + np.number, int)) + + def __mul__(self, other): + """ + Post-multiply another system or a scalar + + Handles multiplication of systems in the sense of a frequency domain + multiplication. That means, given two systems E1(s) and E2(s), their + multiplication, H(s) = E1(s) * E2(s), means that applying H(s) to U(s) + is equivalent to first applying E2(s), and then E1(s). + + Notes + ----- + For SISO systems the order of system application does not matter. + However, for MIMO systems, where the two systems are matrices, the + order above ensures standard Matrix multiplication rules apply. + """ + if not self._check_binop_other(other): + return NotImplemented + + if isinstance(other, StateSpace): + # Disallow mix of discrete and continuous systems. + if type(other) is not type(self): + return NotImplemented + + if self.dt != other.dt: + raise TypeError('Cannot multiply systems with different `dt`.') + + n1 = self.A.shape[0] + n2 = other.A.shape[0] + + # Interconnection of systems + # x1' = A1 x1 + B1 u1 + # y1 = C1 x1 + D1 u1 + # x2' = A2 x2 + B2 y1 + # y2 = C2 x2 + D2 y1 + # + # Plugging in with u1 = y2 yields + # [x1'] [A1 B1*C2 ] [x1] [B1*D2] + # [x2'] = [0 A2 ] [x2] + [B2 ] u2 + # [x1] + # y2 = [C1 D1*C2] [x2] + D1*D2 u2 + a = np.vstack((np.hstack((self.A, np.dot(self.B, other.C))), + np.hstack((zeros((n2, n1)), other.A)))) + b = np.vstack((np.dot(self.B, other.D), other.B)) + c = np.hstack((self.C, np.dot(self.D, other.C))) + d = np.dot(self.D, other.D) + else: + # Assume that other is a scalar / matrix + # For post multiplication the input gets scaled + a = self.A + b = np.dot(self.B, other) + c = self.C + d = np.dot(self.D, other) + + common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype) + return StateSpace(np.asarray(a, dtype=common_dtype), + np.asarray(b, dtype=common_dtype), + np.asarray(c, dtype=common_dtype), + np.asarray(d, dtype=common_dtype), + **self._dt_dict) + + def __rmul__(self, other): + """Pre-multiply a scalar or matrix (but not StateSpace)""" + if not self._check_binop_other(other) or isinstance(other, StateSpace): + return NotImplemented + + # For pre-multiplication only the output gets scaled + a = self.A + b = self.B + c = np.dot(other, self.C) + d = np.dot(other, self.D) + + common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype) + return StateSpace(np.asarray(a, dtype=common_dtype), + np.asarray(b, dtype=common_dtype), + np.asarray(c, dtype=common_dtype), + np.asarray(d, dtype=common_dtype), + **self._dt_dict) + + def __neg__(self): + """Negate the system (equivalent to pre-multiplying by -1).""" + return StateSpace(self.A, self.B, -self.C, -self.D, **self._dt_dict) + + def __add__(self, other): + """ + Adds two systems in the sense of frequency domain addition. + """ + if not self._check_binop_other(other): + return NotImplemented + + if isinstance(other, StateSpace): + # Disallow mix of discrete and continuous systems. + if type(other) is not type(self): + raise TypeError(f'Cannot add {type(self)} and {type(other)}') + + if self.dt != other.dt: + raise TypeError('Cannot add systems with different `dt`.') + # Interconnection of systems + # x1' = A1 x1 + B1 u + # y1 = C1 x1 + D1 u + # x2' = A2 x2 + B2 u + # y2 = C2 x2 + D2 u + # y = y1 + y2 + # + # Plugging in yields + # [x1'] [A1 0 ] [x1] [B1] + # [x2'] = [0 A2] [x2] + [B2] u + # [x1] + # y = [C1 C2] [x2] + [D1 + D2] u + a = linalg.block_diag(self.A, other.A) + b = np.vstack((self.B, other.B)) + c = np.hstack((self.C, other.C)) + d = self.D + other.D + else: + other = np.atleast_2d(other) + if self.D.shape == other.shape: + # A scalar/matrix is really just a static system (A=0, B=0, C=0) + a = self.A + b = self.B + c = self.C + d = self.D + other + else: + raise ValueError("Cannot add systems with incompatible " + f"dimensions ({self.D.shape} and {other.shape})") + + common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype) + return StateSpace(np.asarray(a, dtype=common_dtype), + np.asarray(b, dtype=common_dtype), + np.asarray(c, dtype=common_dtype), + np.asarray(d, dtype=common_dtype), + **self._dt_dict) + + def __sub__(self, other): + if not self._check_binop_other(other): + return NotImplemented + + return self.__add__(-other) + + def __radd__(self, other): + if not self._check_binop_other(other): + return NotImplemented + + return self.__add__(other) + + def __rsub__(self, other): + if not self._check_binop_other(other): + return NotImplemented + + return (-self).__add__(other) + + def __truediv__(self, other): + """ + Divide by a scalar + """ + # Division by non-StateSpace scalars + if not self._check_binop_other(other) or isinstance(other, StateSpace): + return NotImplemented + + if isinstance(other, np.ndarray) and other.ndim > 0: + # It's ambiguous what this means, so disallow it + raise ValueError("Cannot divide StateSpace by non-scalar numpy arrays") + + return self.__mul__(1/other) + + @property + def A(self): + """State matrix of the `StateSpace` system.""" + return self._A + + @A.setter + def A(self, A): + self._A = _atleast_2d_or_none(A) + + @property + def B(self): + """Input matrix of the `StateSpace` system.""" + return self._B + + @B.setter + def B(self, B): + self._B = _atleast_2d_or_none(B) + self.inputs = self.B.shape[-1] + + @property + def C(self): + """Output matrix of the `StateSpace` system.""" + return self._C + + @C.setter + def C(self, C): + self._C = _atleast_2d_or_none(C) + self.outputs = self.C.shape[0] + + @property + def D(self): + """Feedthrough matrix of the `StateSpace` system.""" + return self._D + + @D.setter + def D(self, D): + self._D = _atleast_2d_or_none(D) + + def _copy(self, system): + """ + Copy the parameters of another `StateSpace` system. + + Parameters + ---------- + system : instance of `StateSpace` + The state-space system that is to be copied + + """ + self.A = system.A + self.B = system.B + self.C = system.C + self.D = system.D + + def to_tf(self, **kwargs): + """ + Convert system representation to `TransferFunction`. + + Parameters + ---------- + kwargs : dict, optional + Additional keywords passed to `ss2zpk` + + Returns + ------- + sys : instance of `TransferFunction` + Transfer function of the current system + + """ + return TransferFunction(*ss2tf(self._A, self._B, self._C, self._D, + **kwargs), **self._dt_dict) + + def to_zpk(self, **kwargs): + """ + Convert system representation to `ZerosPolesGain`. + + Parameters + ---------- + kwargs : dict, optional + Additional keywords passed to `ss2zpk` + + Returns + ------- + sys : instance of `ZerosPolesGain` + Zeros, poles, gain representation of the current system + + """ + return ZerosPolesGain(*ss2zpk(self._A, self._B, self._C, self._D, + **kwargs), **self._dt_dict) + + def to_ss(self): + """ + Return a copy of the current `StateSpace` system. + + Returns + ------- + sys : instance of `StateSpace` + The current system (copy) + + """ + return copy.deepcopy(self) + + +class StateSpaceContinuous(StateSpace, lti): + r""" + Continuous-time Linear Time Invariant system in state-space form. + + Represents the system as the continuous-time, first order differential + equation :math:`\dot{x} = A x + B u`. + Continuous-time `StateSpace` systems inherit additional functionality + from the `lti` class. + + Parameters + ---------- + *system: arguments + The `StateSpace` class can be instantiated with 1 or 3 arguments. + The following gives the number of input arguments and their + interpretation: + + * 1: `lti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 4: array_like: (A, B, C, D) + + See Also + -------- + TransferFunction, ZerosPolesGain, lti + ss2zpk, ss2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `StateSpace` system representation (such as `zeros` or `poles`) is very + inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + + >>> a = np.array([[0, 1], [0, 0]]) + >>> b = np.array([[0], [1]]) + >>> c = np.array([[1, 0]]) + >>> d = np.array([[0]]) + + >>> sys = signal.StateSpace(a, b, c, d) + >>> print(sys) + StateSpaceContinuous( + array([[0, 1], + [0, 0]]), + array([[0], + [1]]), + array([[1, 0]]), + array([[0]]), + dt: None + ) + + """ + + def to_discrete(self, dt, method='zoh', alpha=None): + """ + Returns the discretized `StateSpace` system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` and `StateSpace` + """ + return StateSpace(*cont2discrete((self.A, self.B, self.C, self.D), + dt, + method=method, + alpha=alpha)[:-1], + dt=dt) + + +class StateSpaceDiscrete(StateSpace, dlti): + r""" + Discrete-time Linear Time Invariant system in state-space form. + + Represents the system as the discrete-time difference equation + :math:`x[k+1] = A x[k] + B u[k]`. + `StateSpace` systems inherit additional functionality from the `dlti` + class. + + Parameters + ---------- + *system: arguments + The `StateSpace` class can be instantiated with 1 or 3 arguments. + The following gives the number of input arguments and their + interpretation: + + * 1: `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 4: array_like: (A, B, C, D) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `True` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + TransferFunction, ZerosPolesGain, dlti + ss2zpk, ss2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `StateSpace` system representation (such as `zeros` or `poles`) is very + inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + + >>> a = np.array([[1, 0.1], [0, 1]]) + >>> b = np.array([[0.005], [0.1]]) + >>> c = np.array([[1, 0]]) + >>> d = np.array([[0]]) + + >>> signal.StateSpace(a, b, c, d, dt=0.1) + StateSpaceDiscrete( + array([[ 1. , 0.1], + [ 0. , 1. ]]), + array([[ 0.005], + [ 0.1 ]]), + array([[1, 0]]), + array([[0]]), + dt: 0.1 + ) + + """ + pass + + +def lsim(system, U, T, X0=None, interp=True): + """ + Simulate output of a continuous-time linear system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `lti`) + * 2: (num, den) + * 3: (zeros, poles, gain) + * 4: (A, B, C, D) + + U : array_like + An input array describing the input at each time `T` + (interpolation is assumed between given times). If there are + multiple inputs, then each column of the rank-2 array + represents an input. If U = 0 or None, a zero input is used. + T : array_like + The time steps at which the input is defined and at which the + output is desired. Must be nonnegative, increasing, and equally spaced. + X0 : array_like, optional + The initial conditions on the state vector (zero by default). + interp : bool, optional + Whether to use linear (True, the default) or zero-order-hold (False) + interpolation for the input array. + + Returns + ------- + T : 1D ndarray + Time values for the output. + yout : 1D ndarray + System response. + xout : ndarray + Time evolution of the state vector. + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + We'll use `lsim` to simulate an analog Bessel filter applied to + a signal. + + >>> import numpy as np + >>> from scipy.signal import bessel, lsim + >>> import matplotlib.pyplot as plt + + Create a low-pass Bessel filter with a cutoff of 12 Hz. + + >>> b, a = bessel(N=5, Wn=2*np.pi*12, btype='lowpass', analog=True) + + Generate data to which the filter is applied. + + >>> t = np.linspace(0, 1.25, 500, endpoint=False) + + The input signal is the sum of three sinusoidal curves, with + frequencies 4 Hz, 40 Hz, and 80 Hz. The filter should mostly + eliminate the 40 Hz and 80 Hz components, leaving just the 4 Hz signal. + + >>> u = (np.cos(2*np.pi*4*t) + 0.6*np.sin(2*np.pi*40*t) + + ... 0.5*np.cos(2*np.pi*80*t)) + + Simulate the filter with `lsim`. + + >>> tout, yout, xout = lsim((b, a), U=u, T=t) + + Plot the result. + + >>> plt.plot(t, u, 'r', alpha=0.5, linewidth=1, label='input') + >>> plt.plot(tout, yout, 'k', linewidth=1.5, label='output') + >>> plt.legend(loc='best', shadow=True, framealpha=1) + >>> plt.grid(alpha=0.3) + >>> plt.xlabel('t') + >>> plt.show() + + In a second example, we simulate a double integrator ``y'' = u``, with + a constant input ``u = 1``. We'll use the state space representation + of the integrator. + + >>> from scipy.signal import lti + >>> A = np.array([[0.0, 1.0], [0.0, 0.0]]) + >>> B = np.array([[0.0], [1.0]]) + >>> C = np.array([[1.0, 0.0]]) + >>> D = 0.0 + >>> system = lti(A, B, C, D) + + `t` and `u` define the time and input signal for the system to + be simulated. + + >>> t = np.linspace(0, 5, num=50) + >>> u = np.ones_like(t) + + Compute the simulation, and then plot `y`. As expected, the plot shows + the curve ``y = 0.5*t**2``. + + >>> tout, y, x = lsim(system, u, t) + >>> plt.plot(t, y) + >>> plt.grid(alpha=0.3) + >>> plt.xlabel('t') + >>> plt.show() + + """ + if isinstance(system, lti): + sys = system._as_ss() + elif isinstance(system, dlti): + raise AttributeError('lsim can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_ss() + T = atleast_1d(T) + if len(T.shape) != 1: + raise ValueError("T must be a rank-1 array.") + + A, B, C, D = map(np.asarray, (sys.A, sys.B, sys.C, sys.D)) + n_states = A.shape[0] + n_inputs = B.shape[1] + + n_steps = T.size + if X0 is None: + X0 = zeros(n_states, sys.A.dtype) + xout = np.empty((n_steps, n_states), sys.A.dtype) + + if T[0] == 0: + xout[0] = X0 + elif T[0] > 0: + # step forward to initial time, with zero input + xout[0] = dot(X0, linalg.expm(transpose(A) * T[0])) + else: + raise ValueError("Initial time must be nonnegative") + + no_input = (U is None or + (isinstance(U, (int, float)) and U == 0.) or + not np.any(U)) + + if n_steps == 1: + yout = squeeze(xout @ C.T) + if not no_input: + yout += squeeze(U @ D.T) + return T, yout, squeeze(xout) + + dt = T[1] - T[0] + if not np.allclose(np.diff(T), dt): + raise ValueError("Time steps are not equally spaced.") + + if no_input: + # Zero input: just use matrix exponential + # take transpose because state is a row vector + expAT_dt = linalg.expm(A.T * dt) + for i in range(1, n_steps): + xout[i] = xout[i-1] @ expAT_dt + yout = squeeze(xout @ C.T) + return T, yout, squeeze(xout) + + # Nonzero input + U = atleast_1d(U) + if U.ndim == 1: + U = U[:, np.newaxis] + + if U.shape[0] != n_steps: + raise ValueError("U must have the same number of rows " + "as elements in T.") + + if U.shape[1] != n_inputs: + raise ValueError("System does not define that many inputs.") + + if not interp: + # Zero-order hold + # Algorithm: to integrate from time 0 to time dt, we solve + # xdot = A x + B u, x(0) = x0 + # udot = 0, u(0) = u0. + # + # Solution is + # [ x(dt) ] [ A*dt B*dt ] [ x0 ] + # [ u(dt) ] = exp [ 0 0 ] [ u0 ] + M = np.vstack([np.hstack([A * dt, B * dt]), + np.zeros((n_inputs, n_states + n_inputs))]) + # transpose everything because the state and input are row vectors + expMT = linalg.expm(M.T) + Ad = expMT[:n_states, :n_states] + Bd = expMT[n_states:, :n_states] + for i in range(1, n_steps): + xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd + else: + # Linear interpolation between steps + # Algorithm: to integrate from time 0 to time dt, with linear + # interpolation between inputs u(0) = u0 and u(dt) = u1, we solve + # xdot = A x + B u, x(0) = x0 + # udot = (u1 - u0) / dt, u(0) = u0. + # + # Solution is + # [ x(dt) ] [ A*dt B*dt 0 ] [ x0 ] + # [ u(dt) ] = exp [ 0 0 I ] [ u0 ] + # [u1 - u0] [ 0 0 0 ] [u1 - u0] + M = np.vstack([np.hstack([A * dt, B * dt, + np.zeros((n_states, n_inputs))]), + np.hstack([np.zeros((n_inputs, n_states + n_inputs)), + np.identity(n_inputs)]), + np.zeros((n_inputs, n_states + 2 * n_inputs))]) + expMT = linalg.expm(M.T) + Ad = expMT[:n_states, :n_states] + Bd1 = expMT[n_states+n_inputs:, :n_states] + Bd0 = expMT[n_states:n_states + n_inputs, :n_states] - Bd1 + for i in range(1, n_steps): + xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd0 + U[i] @ Bd1 + + yout = squeeze(xout @ C.T) + squeeze(U @ D.T) + return T, yout, squeeze(xout) + + +def _default_response_times(A, n): + """Compute a reasonable set of time samples for the response time. + + This function is used by `impulse` and `step` to compute the response time + when the `T` argument to the function is None. + + Parameters + ---------- + A : array_like + The system matrix, which is square. + n : int + The number of time samples to generate. + + Returns + ------- + t : ndarray + The 1-D array of length `n` of time samples at which the response + is to be computed. + """ + # Create a reasonable time interval. + # TODO: This could use some more work. + # For example, what is expected when the system is unstable? + vals = linalg.eigvals(A) + r = min(abs(real(vals))) + if r == 0.0: + r = 1.0 + tc = 1.0 / r + t = linspace(0.0, 7 * tc, n) + return t + + +def impulse(system, X0=None, T=None, N=None): + """Impulse response of continuous-time system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple of array_like + describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + X0 : array_like, optional + Initial state-vector. Defaults to zero. + T : array_like, optional + Time points. Computed if not given. + N : int, optional + The number of time points to compute (if `T` is not given). + + Returns + ------- + T : ndarray + A 1-D array of time points. + yout : ndarray + A 1-D array containing the impulse response of the system (except for + singularities at zero). + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + Compute the impulse response of a second order system with a repeated + root: ``x''(t) + 2*x'(t) + x(t) = u(t)`` + + >>> from scipy import signal + >>> system = ([1.0], [1.0, 2.0, 1.0]) + >>> t, y = signal.impulse(system) + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, y) + + """ + if isinstance(system, lti): + sys = system._as_ss() + elif isinstance(system, dlti): + raise AttributeError('impulse can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_ss() + if X0 is None: + X = squeeze(sys.B) + else: + X = squeeze(sys.B + X0) + if N is None: + N = 100 + if T is None: + T = _default_response_times(sys.A, N) + else: + T = asarray(T) + + _, h, _ = lsim(sys, 0., T, X, interp=False) + return T, h + + +def step(system, X0=None, T=None, N=None): + """Step response of continuous-time system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple of array_like + describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + X0 : array_like, optional + Initial state-vector (default is zero). + T : array_like, optional + Time points (computed if not given). + N : int, optional + Number of time points to compute if `T` is not given. + + Returns + ------- + T : 1D ndarray + Output time points. + yout : 1D ndarray + Step response of system. + + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> lti = signal.lti([1.0], [1.0, 1.0]) + >>> t, y = signal.step(lti) + >>> plt.plot(t, y) + >>> plt.xlabel('Time [s]') + >>> plt.ylabel('Amplitude') + >>> plt.title('Step response for 1. Order Lowpass') + >>> plt.grid() + + """ + if isinstance(system, lti): + sys = system._as_ss() + elif isinstance(system, dlti): + raise AttributeError('step can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_ss() + if N is None: + N = 100 + if T is None: + T = _default_response_times(sys.A, N) + else: + T = asarray(T) + U = ones(T.shape, sys.A.dtype) + vals = lsim(sys, U, T, X0=X0, interp=False) + return vals[0], vals[1] + + +def bode(system, w=None, n=100): + """ + Calculate Bode magnitude and phase data of a continuous-time system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + w : array_like, optional + Array of frequencies (in rad/s). Magnitude and phase data is calculated + for every value in this array. If not given a reasonable set will be + calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + + Returns + ------- + w : 1D ndarray + Frequency array [rad/s] + mag : 1D ndarray + Magnitude array [dB] + phase : 1D ndarray + Phase array [deg] + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> sys = signal.TransferFunction([1], [1, 1]) + >>> w, mag, phase = signal.bode(sys) + + >>> plt.figure() + >>> plt.semilogx(w, mag) # Bode magnitude plot + >>> plt.figure() + >>> plt.semilogx(w, phase) # Bode phase plot + >>> plt.show() + + """ + w, y = freqresp(system, w=w, n=n) + + mag = 20.0 * np.log10(abs(y)) + phase = np.unwrap(np.arctan2(y.imag, y.real)) * 180.0 / np.pi + + return w, mag, phase + + +def freqresp(system, w=None, n=10000): + r"""Calculate the frequency response of a continuous-time system. + + Parameters + ---------- + system : an instance of the `lti` class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + w : array_like, optional + Array of frequencies (in rad/s). Magnitude and phase data is + calculated for every value in this array. If not given, a reasonable + set will be calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + + Returns + ------- + w : 1D ndarray + Frequency array [rad/s] + H : 1D ndarray + Array of complex magnitude values + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + Generating the Nyquist plot of a transfer function + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Construct the transfer function :math:`H(s) = \frac{5}{(s-1)^3}`: + + >>> s1 = signal.ZerosPolesGain([], [1, 1, 1], [5]) + + >>> w, H = signal.freqresp(s1) + + >>> plt.figure() + >>> plt.plot(H.real, H.imag, "b") + >>> plt.plot(H.real, -H.imag, "r") + >>> plt.show() + """ + if isinstance(system, lti): + if isinstance(system, (TransferFunction, ZerosPolesGain)): + sys = system + else: + sys = system._as_zpk() + elif isinstance(system, dlti): + raise AttributeError('freqresp can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_zpk() + + if sys.inputs != 1 or sys.outputs != 1: + raise ValueError("freqresp() requires a SISO (single input, single " + "output) system.") + + if w is not None: + worN = w + else: + worN = n + + if isinstance(sys, TransferFunction): + # In the call to freqs(), sys.num.ravel() is used because there are + # cases where sys.num is a 2-D array with a single row. + w, h = freqs(sys.num.ravel(), sys.den, worN=worN) + + elif isinstance(sys, ZerosPolesGain): + w, h = freqs_zpk(sys.zeros, sys.poles, sys.gain, worN=worN) + + return w, h + + +# This class will be used by place_poles to return its results +# see https://code.activestate.com/recipes/52308/ +class Bunch: + def __init__(self, **kwds): + self.__dict__.update(kwds) + + +def _valid_inputs(A, B, poles, method, rtol, maxiter): + """ + Check the poles come in complex conjugate pairs + Check shapes of A, B and poles are compatible. + Check the method chosen is compatible with provided poles + Return update method to use and ordered poles + + """ + poles = np.asarray(poles) + if poles.ndim > 1: + raise ValueError("Poles must be a 1D array like.") + # Will raise ValueError if poles do not come in complex conjugates pairs + poles = _order_complex_poles(poles) + if A.ndim > 2: + raise ValueError("A must be a 2D array/matrix.") + if B.ndim > 2: + raise ValueError("B must be a 2D array/matrix") + if A.shape[0] != A.shape[1]: + raise ValueError("A must be square") + if len(poles) > A.shape[0]: + raise ValueError("maximum number of poles is %d but you asked for %d" % + (A.shape[0], len(poles))) + if len(poles) < A.shape[0]: + raise ValueError("number of poles is %d but you should provide %d" % + (len(poles), A.shape[0])) + r = np.linalg.matrix_rank(B) + for p in poles: + if sum(p == poles) > r: + raise ValueError("at least one of the requested pole is repeated " + "more than rank(B) times") + # Choose update method + update_loop = _YT_loop + if method not in ('KNV0','YT'): + raise ValueError("The method keyword must be one of 'YT' or 'KNV0'") + + if method == "KNV0": + update_loop = _KNV0_loop + if not all(np.isreal(poles)): + raise ValueError("Complex poles are not supported by KNV0") + + if maxiter < 1: + raise ValueError("maxiter must be at least equal to 1") + + # We do not check rtol <= 0 as the user can use a negative rtol to + # force maxiter iterations + if rtol > 1: + raise ValueError("rtol can not be greater than 1") + + return update_loop, poles + + +def _order_complex_poles(poles): + """ + Check we have complex conjugates pairs and reorder P according to YT, ie + real_poles, complex_i, conjugate complex_i, .... + The lexicographic sort on the complex poles is added to help the user to + compare sets of poles. + """ + ordered_poles = np.sort(poles[np.isreal(poles)]) + im_poles = [] + for p in np.sort(poles[np.imag(poles) < 0]): + if np.conj(p) in poles: + im_poles.extend((p, np.conj(p))) + + ordered_poles = np.hstack((ordered_poles, im_poles)) + + if poles.shape[0] != len(ordered_poles): + raise ValueError("Complex poles must come with their conjugates") + return ordered_poles + + +def _KNV0(B, ker_pole, transfer_matrix, j, poles): + """ + Algorithm "KNV0" Kautsky et Al. Robust pole + assignment in linear state feedback, Int journal of Control + 1985, vol 41 p 1129->1155 + https://la.epfl.ch/files/content/sites/la/files/ + users/105941/public/KautskyNicholsDooren + + """ + # Remove xj form the base + transfer_matrix_not_j = np.delete(transfer_matrix, j, axis=1) + # If we QR this matrix in full mode Q=Q0|Q1 + # then Q1 will be a single column orthogonal to + # Q0, that's what we are looking for ! + + # After merge of gh-4249 great speed improvements could be achieved + # using QR updates instead of full QR in the line below + + # To debug with numpy qr uncomment the line below + # Q, R = np.linalg.qr(transfer_matrix_not_j, mode="complete") + Q, R = s_qr(transfer_matrix_not_j, mode="full") + + mat_ker_pj = np.dot(ker_pole[j], ker_pole[j].T) + yj = np.dot(mat_ker_pj, Q[:, -1]) + + # If Q[:, -1] is "almost" orthogonal to ker_pole[j] its + # projection into ker_pole[j] will yield a vector + # close to 0. As we are looking for a vector in ker_pole[j] + # simply stick with transfer_matrix[:, j] (unless someone provides me with + # a better choice ?) + + if not np.allclose(yj, 0): + xj = yj/np.linalg.norm(yj) + transfer_matrix[:, j] = xj + + # KNV does not support complex poles, using YT technique the two lines + # below seem to work 9 out of 10 times but it is not reliable enough: + # transfer_matrix[:, j]=real(xj) + # transfer_matrix[:, j+1]=imag(xj) + + # Add this at the beginning of this function if you wish to test + # complex support: + # if ~np.isreal(P[j]) and (j>=B.shape[0]-1 or P[j]!=np.conj(P[j+1])): + # return + # Problems arise when imag(xj)=>0 I have no idea on how to fix this + + +def _YT_real(ker_pole, Q, transfer_matrix, i, j): + """ + Applies algorithm from YT section 6.1 page 19 related to real pairs + """ + # step 1 page 19 + u = Q[:, -2, np.newaxis] + v = Q[:, -1, np.newaxis] + + # step 2 page 19 + m = np.dot(np.dot(ker_pole[i].T, np.dot(u, v.T) - + np.dot(v, u.T)), ker_pole[j]) + + # step 3 page 19 + um, sm, vm = np.linalg.svd(m) + # mu1, mu2 two first columns of U => 2 first lines of U.T + mu1, mu2 = um.T[:2, :, np.newaxis] + # VM is V.T with numpy we want the first two lines of V.T + nu1, nu2 = vm[:2, :, np.newaxis] + + # what follows is a rough python translation of the formulas + # in section 6.2 page 20 (step 4) + transfer_matrix_j_mo_transfer_matrix_j = np.vstack(( + transfer_matrix[:, i, np.newaxis], + transfer_matrix[:, j, np.newaxis])) + + if not np.allclose(sm[0], sm[1]): + ker_pole_imo_mu1 = np.dot(ker_pole[i], mu1) + ker_pole_i_nu1 = np.dot(ker_pole[j], nu1) + ker_pole_mu_nu = np.vstack((ker_pole_imo_mu1, ker_pole_i_nu1)) + else: + ker_pole_ij = np.vstack(( + np.hstack((ker_pole[i], + np.zeros(ker_pole[i].shape))), + np.hstack((np.zeros(ker_pole[j].shape), + ker_pole[j])) + )) + mu_nu_matrix = np.vstack( + (np.hstack((mu1, mu2)), np.hstack((nu1, nu2))) + ) + ker_pole_mu_nu = np.dot(ker_pole_ij, mu_nu_matrix) + transfer_matrix_ij = np.dot(np.dot(ker_pole_mu_nu, ker_pole_mu_nu.T), + transfer_matrix_j_mo_transfer_matrix_j) + if not np.allclose(transfer_matrix_ij, 0): + transfer_matrix_ij = (np.sqrt(2)*transfer_matrix_ij / + np.linalg.norm(transfer_matrix_ij)) + transfer_matrix[:, i] = transfer_matrix_ij[ + :transfer_matrix[:, i].shape[0], 0 + ] + transfer_matrix[:, j] = transfer_matrix_ij[ + transfer_matrix[:, i].shape[0]:, 0 + ] + else: + # As in knv0 if transfer_matrix_j_mo_transfer_matrix_j is orthogonal to + # Vect{ker_pole_mu_nu} assign transfer_matrixi/transfer_matrix_j to + # ker_pole_mu_nu and iterate. As we are looking for a vector in + # Vect{Matker_pole_MU_NU} (see section 6.1 page 19) this might help + # (that's a guess, not a claim !) + transfer_matrix[:, i] = ker_pole_mu_nu[ + :transfer_matrix[:, i].shape[0], 0 + ] + transfer_matrix[:, j] = ker_pole_mu_nu[ + transfer_matrix[:, i].shape[0]:, 0 + ] + + +def _YT_complex(ker_pole, Q, transfer_matrix, i, j): + """ + Applies algorithm from YT section 6.2 page 20 related to complex pairs + """ + # step 1 page 20 + ur = np.sqrt(2)*Q[:, -2, np.newaxis] + ui = np.sqrt(2)*Q[:, -1, np.newaxis] + u = ur + 1j*ui + + # step 2 page 20 + ker_pole_ij = ker_pole[i] + m = np.dot(np.dot(np.conj(ker_pole_ij.T), np.dot(u, np.conj(u).T) - + np.dot(np.conj(u), u.T)), ker_pole_ij) + + # step 3 page 20 + e_val, e_vec = np.linalg.eig(m) + # sort eigenvalues according to their module + e_val_idx = np.argsort(np.abs(e_val)) + mu1 = e_vec[:, e_val_idx[-1], np.newaxis] + mu2 = e_vec[:, e_val_idx[-2], np.newaxis] + + # what follows is a rough python translation of the formulas + # in section 6.2 page 20 (step 4) + + # remember transfer_matrix_i has been split as + # transfer_matrix[i]=real(transfer_matrix_i) and + # transfer_matrix[j]=imag(transfer_matrix_i) + transfer_matrix_j_mo_transfer_matrix_j = ( + transfer_matrix[:, i, np.newaxis] + + 1j*transfer_matrix[:, j, np.newaxis] + ) + if not np.allclose(np.abs(e_val[e_val_idx[-1]]), + np.abs(e_val[e_val_idx[-2]])): + ker_pole_mu = np.dot(ker_pole_ij, mu1) + else: + mu1_mu2_matrix = np.hstack((mu1, mu2)) + ker_pole_mu = np.dot(ker_pole_ij, mu1_mu2_matrix) + transfer_matrix_i_j = np.dot(np.dot(ker_pole_mu, np.conj(ker_pole_mu.T)), + transfer_matrix_j_mo_transfer_matrix_j) + + if not np.allclose(transfer_matrix_i_j, 0): + transfer_matrix_i_j = (transfer_matrix_i_j / + np.linalg.norm(transfer_matrix_i_j)) + transfer_matrix[:, i] = np.real(transfer_matrix_i_j[:, 0]) + transfer_matrix[:, j] = np.imag(transfer_matrix_i_j[:, 0]) + else: + # same idea as in YT_real + transfer_matrix[:, i] = np.real(ker_pole_mu[:, 0]) + transfer_matrix[:, j] = np.imag(ker_pole_mu[:, 0]) + + +def _YT_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol): + """ + Algorithm "YT" Tits, Yang. Globally Convergent + Algorithms for Robust Pole Assignment by State Feedback + https://hdl.handle.net/1903/5598 + The poles P have to be sorted accordingly to section 6.2 page 20 + + """ + # The IEEE edition of the YT paper gives useful information on the + # optimal update order for the real poles in order to minimize the number + # of times we have to loop over all poles, see page 1442 + nb_real = poles[np.isreal(poles)].shape[0] + # hnb => Half Nb Real + hnb = nb_real // 2 + + # Stick to the indices in the paper and then remove one to get numpy array + # index it is a bit easier to link the code to the paper this way even if it + # is not very clean. The paper is unclear about what should be done when + # there is only one real pole => use KNV0 on this real pole seem to work + if nb_real > 0: + #update the biggest real pole with the smallest one + update_order = [[nb_real], [1]] + else: + update_order = [[],[]] + + r_comp = np.arange(nb_real+1, len(poles)+1, 2) + # step 1.a + r_p = np.arange(1, hnb+nb_real % 2) + update_order[0].extend(2*r_p) + update_order[1].extend(2*r_p+1) + # step 1.b + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 1.c + r_p = np.arange(1, hnb+1) + update_order[0].extend(2*r_p-1) + update_order[1].extend(2*r_p) + # step 1.d + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 2.a + r_j = np.arange(2, hnb+nb_real % 2) + for j in r_j: + for i in range(1, hnb+1): + update_order[0].append(i) + update_order[1].append(i+j) + # step 2.b + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 2.c + r_j = np.arange(2, hnb+nb_real % 2) + for j in r_j: + for i in range(hnb+1, nb_real+1): + idx_1 = i+j + if idx_1 > nb_real: + idx_1 = i+j-nb_real + update_order[0].append(i) + update_order[1].append(idx_1) + # step 2.d + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 3.a + for i in range(1, hnb+1): + update_order[0].append(i) + update_order[1].append(i+hnb) + # step 3.b + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + + update_order = np.array(update_order).T-1 + stop = False + nb_try = 0 + while nb_try < maxiter and not stop: + det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix)) + for i, j in update_order: + if i == j: + assert i == 0, "i!=0 for KNV call in YT" + assert np.isreal(poles[i]), "calling KNV on a complex pole" + _KNV0(B, ker_pole, transfer_matrix, i, poles) + else: + transfer_matrix_not_i_j = np.delete(transfer_matrix, (i, j), + axis=1) + # after merge of gh-4249 great speed improvements could be + # achieved using QR updates instead of full QR in the line below + + #to debug with numpy qr uncomment the line below + #Q, _ = np.linalg.qr(transfer_matrix_not_i_j, mode="complete") + Q, _ = s_qr(transfer_matrix_not_i_j, mode="full") + + if np.isreal(poles[i]): + assert np.isreal(poles[j]), "mixing real and complex " + \ + "in YT_real" + str(poles) + _YT_real(ker_pole, Q, transfer_matrix, i, j) + else: + assert ~np.isreal(poles[i]), "mixing real and complex " + \ + "in YT_real" + str(poles) + _YT_complex(ker_pole, Q, transfer_matrix, i, j) + + det_transfer_matrix = np.max((np.sqrt(np.spacing(1)), + np.abs(np.linalg.det(transfer_matrix)))) + cur_rtol = np.abs( + (det_transfer_matrix - + det_transfer_matrixb) / + det_transfer_matrix) + if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)): + # Convergence test from YT page 21 + stop = True + nb_try += 1 + return stop, cur_rtol, nb_try + + +def _KNV0_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol): + """ + Loop over all poles one by one and apply KNV method 0 algorithm + """ + # This method is useful only because we need to be able to call + # _KNV0 from YT without looping over all poles, otherwise it would + # have been fine to mix _KNV0_loop and _KNV0 in a single function + stop = False + nb_try = 0 + while nb_try < maxiter and not stop: + det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix)) + for j in range(B.shape[0]): + _KNV0(B, ker_pole, transfer_matrix, j, poles) + + det_transfer_matrix = np.max((np.sqrt(np.spacing(1)), + np.abs(np.linalg.det(transfer_matrix)))) + cur_rtol = np.abs((det_transfer_matrix - det_transfer_matrixb) / + det_transfer_matrix) + if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)): + # Convergence test from YT page 21 + stop = True + + nb_try += 1 + return stop, cur_rtol, nb_try + + +def place_poles(A, B, poles, method="YT", rtol=1e-3, maxiter=30): + """ + Compute K such that eigenvalues (A - dot(B, K))=poles. + + K is the gain matrix such as the plant described by the linear system + ``AX+BU`` will have its closed-loop poles, i.e the eigenvalues ``A - B*K``, + as close as possible to those asked for in poles. + + SISO, MISO and MIMO systems are supported. + + Parameters + ---------- + A, B : ndarray + State-space representation of linear system ``AX + BU``. + poles : array_like + Desired real poles and/or complex conjugates poles. + Complex poles are only supported with ``method="YT"`` (default). + method: {'YT', 'KNV0'}, optional + Which method to choose to find the gain matrix K. One of: + + - 'YT': Yang Tits + - 'KNV0': Kautsky, Nichols, Van Dooren update method 0 + + See References and Notes for details on the algorithms. + rtol: float, optional + After each iteration the determinant of the eigenvectors of + ``A - B*K`` is compared to its previous value, when the relative + error between these two values becomes lower than `rtol` the algorithm + stops. Default is 1e-3. + maxiter: int, optional + Maximum number of iterations to compute the gain matrix. + Default is 30. + + Returns + ------- + full_state_feedback : Bunch object + full_state_feedback is composed of: + gain_matrix : 1-D ndarray + The closed loop matrix K such as the eigenvalues of ``A-BK`` + are as close as possible to the requested poles. + computed_poles : 1-D ndarray + The poles corresponding to ``A-BK`` sorted as first the real + poles in increasing order, then the complex conjugates in + lexicographic order. + requested_poles : 1-D ndarray + The poles the algorithm was asked to place sorted as above, + they may differ from what was achieved. + X : 2-D ndarray + The transfer matrix such as ``X * diag(poles) = (A - B*K)*X`` + (see Notes) + rtol : float + The relative tolerance achieved on ``det(X)`` (see Notes). + `rtol` will be NaN if it is possible to solve the system + ``diag(poles) = (A - B*K)``, or 0 when the optimization + algorithms can't do anything i.e when ``B.shape[1] == 1``. + nb_iter : int + The number of iterations performed before converging. + `nb_iter` will be NaN if it is possible to solve the system + ``diag(poles) = (A - B*K)``, or 0 when the optimization + algorithms can't do anything i.e when ``B.shape[1] == 1``. + + Notes + ----- + The Tits and Yang (YT), [2]_ paper is an update of the original Kautsky et + al. (KNV) paper [1]_. KNV relies on rank-1 updates to find the transfer + matrix X such that ``X * diag(poles) = (A - B*K)*X``, whereas YT uses + rank-2 updates. This yields on average more robust solutions (see [2]_ + pp 21-22), furthermore the YT algorithm supports complex poles whereas KNV + does not in its original version. Only update method 0 proposed by KNV has + been implemented here, hence the name ``'KNV0'``. + + KNV extended to complex poles is used in Matlab's ``place`` function, YT is + distributed under a non-free licence by Slicot under the name ``robpole``. + It is unclear and undocumented how KNV0 has been extended to complex poles + (Tits and Yang claim on page 14 of their paper that their method can not be + used to extend KNV to complex poles), therefore only YT supports them in + this implementation. + + As the solution to the problem of pole placement is not unique for MIMO + systems, both methods start with a tentative transfer matrix which is + altered in various way to increase its determinant. Both methods have been + proven to converge to a stable solution, however depending on the way the + initial transfer matrix is chosen they will converge to different + solutions and therefore there is absolutely no guarantee that using + ``'KNV0'`` will yield results similar to Matlab's or any other + implementation of these algorithms. + + Using the default method ``'YT'`` should be fine in most cases; ``'KNV0'`` + is only provided because it is needed by ``'YT'`` in some specific cases. + Furthermore ``'YT'`` gives on average more robust results than ``'KNV0'`` + when ``abs(det(X))`` is used as a robustness indicator. + + [2]_ is available as a technical report on the following URL: + https://hdl.handle.net/1903/5598 + + References + ---------- + .. [1] J. Kautsky, N.K. Nichols and P. van Dooren, "Robust pole assignment + in linear state feedback", International Journal of Control, Vol. 41 + pp. 1129-1155, 1985. + .. [2] A.L. Tits and Y. Yang, "Globally convergent algorithms for robust + pole assignment by state feedback", IEEE Transactions on Automatic + Control, Vol. 41, pp. 1432-1452, 1996. + + Examples + -------- + A simple example demonstrating real pole placement using both KNV and YT + algorithms. This is example number 1 from section 4 of the reference KNV + publication ([1]_): + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> A = np.array([[ 1.380, -0.2077, 6.715, -5.676 ], + ... [-0.5814, -4.290, 0, 0.6750 ], + ... [ 1.067, 4.273, -6.654, 5.893 ], + ... [ 0.0480, 4.273, 1.343, -2.104 ]]) + >>> B = np.array([[ 0, 5.679 ], + ... [ 1.136, 1.136 ], + ... [ 0, 0, ], + ... [-3.146, 0 ]]) + >>> P = np.array([-0.2, -0.5, -5.0566, -8.6659]) + + Now compute K with KNV method 0, with the default YT method and with the YT + method while forcing 100 iterations of the algorithm and print some results + after each call. + + >>> fsf1 = signal.place_poles(A, B, P, method='KNV0') + >>> fsf1.gain_matrix + array([[ 0.20071427, -0.96665799, 0.24066128, -0.10279785], + [ 0.50587268, 0.57779091, 0.51795763, -0.41991442]]) + + >>> fsf2 = signal.place_poles(A, B, P) # uses YT method + >>> fsf2.computed_poles + array([-8.6659, -5.0566, -0.5 , -0.2 ]) + + >>> fsf3 = signal.place_poles(A, B, P, rtol=-1, maxiter=100) + >>> fsf3.X + array([[ 0.52072442+0.j, -0.08409372+0.j, -0.56847937+0.j, 0.74823657+0.j], + [-0.04977751+0.j, -0.80872954+0.j, 0.13566234+0.j, -0.29322906+0.j], + [-0.82266932+0.j, -0.19168026+0.j, -0.56348322+0.j, -0.43815060+0.j], + [ 0.22267347+0.j, 0.54967577+0.j, -0.58387806+0.j, -0.40271926+0.j]]) + + The absolute value of the determinant of X is a good indicator to check the + robustness of the results, both ``'KNV0'`` and ``'YT'`` aim at maximizing + it. Below a comparison of the robustness of the results above: + + >>> abs(np.linalg.det(fsf1.X)) < abs(np.linalg.det(fsf2.X)) + True + >>> abs(np.linalg.det(fsf2.X)) < abs(np.linalg.det(fsf3.X)) + True + + Now a simple example for complex poles: + + >>> A = np.array([[ 0, 7/3., 0, 0 ], + ... [ 0, 0, 0, 7/9. ], + ... [ 0, 0, 0, 0 ], + ... [ 0, 0, 0, 0 ]]) + >>> B = np.array([[ 0, 0 ], + ... [ 0, 0 ], + ... [ 1, 0 ], + ... [ 0, 1 ]]) + >>> P = np.array([-3, -1, -2-1j, -2+1j]) / 3. + >>> fsf = signal.place_poles(A, B, P, method='YT') + + We can plot the desired and computed poles in the complex plane: + + >>> t = np.linspace(0, 2*np.pi, 401) + >>> plt.plot(np.cos(t), np.sin(t), 'k--') # unit circle + >>> plt.plot(fsf.requested_poles.real, fsf.requested_poles.imag, + ... 'wo', label='Desired') + >>> plt.plot(fsf.computed_poles.real, fsf.computed_poles.imag, 'bx', + ... label='Placed') + >>> plt.grid() + >>> plt.axis('image') + >>> plt.axis([-1.1, 1.1, -1.1, 1.1]) + >>> plt.legend(bbox_to_anchor=(1.05, 1), loc=2, numpoints=1) + + """ + # Move away all the inputs checking, it only adds noise to the code + update_loop, poles = _valid_inputs(A, B, poles, method, rtol, maxiter) + + # The current value of the relative tolerance we achieved + cur_rtol = 0 + # The number of iterations needed before converging + nb_iter = 0 + + # Step A: QR decomposition of B page 1132 KN + # to debug with numpy qr uncomment the line below + # u, z = np.linalg.qr(B, mode="complete") + u, z = s_qr(B, mode="full") + rankB = np.linalg.matrix_rank(B) + u0 = u[:, :rankB] + u1 = u[:, rankB:] + z = z[:rankB, :] + + # If we can use the identity matrix as X the solution is obvious + if B.shape[0] == rankB: + # if B is square and full rank there is only one solution + # such as (A+BK)=inv(X)*diag(P)*X with X=eye(A.shape[0]) + # i.e K=inv(B)*(diag(P)-A) + # if B has as many lines as its rank (but not square) there are many + # solutions and we can choose one using least squares + # => use lstsq in both cases. + # In both cases the transfer matrix X will be eye(A.shape[0]) and I + # can hardly think of a better one so there is nothing to optimize + # + # for complex poles we use the following trick + # + # |a -b| has for eigenvalues a+b and a-b + # |b a| + # + # |a+bi 0| has the obvious eigenvalues a+bi and a-bi + # |0 a-bi| + # + # e.g solving the first one in R gives the solution + # for the second one in C + diag_poles = np.zeros(A.shape) + idx = 0 + while idx < poles.shape[0]: + p = poles[idx] + diag_poles[idx, idx] = np.real(p) + if ~np.isreal(p): + diag_poles[idx, idx+1] = -np.imag(p) + diag_poles[idx+1, idx+1] = np.real(p) + diag_poles[idx+1, idx] = np.imag(p) + idx += 1 # skip next one + idx += 1 + gain_matrix = np.linalg.lstsq(B, diag_poles-A, rcond=-1)[0] + transfer_matrix = np.eye(A.shape[0]) + cur_rtol = np.nan + nb_iter = np.nan + else: + # step A (p1144 KNV) and beginning of step F: decompose + # dot(U1.T, A-P[i]*I).T and build our set of transfer_matrix vectors + # in the same loop + ker_pole = [] + + # flag to skip the conjugate of a complex pole + skip_conjugate = False + # select orthonormal base ker_pole for each Pole and vectors for + # transfer_matrix + for j in range(B.shape[0]): + if skip_conjugate: + skip_conjugate = False + continue + pole_space_j = np.dot(u1.T, A-poles[j]*np.eye(B.shape[0])).T + + # after QR Q=Q0|Q1 + # only Q0 is used to reconstruct the qr'ed (dot Q, R) matrix. + # Q1 is orthogonal to Q0 and will be multiplied by the zeros in + # R when using mode "complete". In default mode Q1 and the zeros + # in R are not computed + + # To debug with numpy qr uncomment the line below + # Q, _ = np.linalg.qr(pole_space_j, mode="complete") + Q, _ = s_qr(pole_space_j, mode="full") + + ker_pole_j = Q[:, pole_space_j.shape[1]:] + + # We want to select one vector in ker_pole_j to build the transfer + # matrix, however qr returns sometimes vectors with zeros on the + # same line for each pole and this yields very long convergence + # times. + # Or some other times a set of vectors, one with zero imaginary + # part and one (or several) with imaginary parts. After trying + # many ways to select the best possible one (eg ditch vectors + # with zero imaginary part for complex poles) I ended up summing + # all vectors in ker_pole_j, this solves 100% of the problems and + # is a valid choice for transfer_matrix. + # This way for complex poles we are sure to have a non zero + # imaginary part that way, and the problem of lines full of zeros + # in transfer_matrix is solved too as when a vector from + # ker_pole_j has a zero the other one(s) when + # ker_pole_j.shape[1]>1) for sure won't have a zero there. + + transfer_matrix_j = np.sum(ker_pole_j, axis=1)[:, np.newaxis] + transfer_matrix_j = (transfer_matrix_j / + np.linalg.norm(transfer_matrix_j)) + if ~np.isreal(poles[j]): # complex pole + transfer_matrix_j = np.hstack([np.real(transfer_matrix_j), + np.imag(transfer_matrix_j)]) + ker_pole.extend([ker_pole_j, ker_pole_j]) + + # Skip next pole as it is the conjugate + skip_conjugate = True + else: # real pole, nothing to do + ker_pole.append(ker_pole_j) + + if j == 0: + transfer_matrix = transfer_matrix_j + else: + transfer_matrix = np.hstack((transfer_matrix, transfer_matrix_j)) + + if rankB > 1: # otherwise there is nothing we can optimize + stop, cur_rtol, nb_iter = update_loop(ker_pole, transfer_matrix, + poles, B, maxiter, rtol) + if not stop and rtol > 0: + # if rtol<=0 the user has probably done that on purpose, + # don't annoy them + err_msg = ( + "Convergence was not reached after maxiter iterations.\n" + f"You asked for a tolerance of {rtol}, we got {cur_rtol}." + ) + warnings.warn(err_msg, stacklevel=2) + + # reconstruct transfer_matrix to match complex conjugate pairs, + # ie transfer_matrix_j/transfer_matrix_j+1 are + # Re(Complex_pole), Im(Complex_pole) now and will be Re-Im/Re+Im after + transfer_matrix = transfer_matrix.astype(complex) + idx = 0 + while idx < poles.shape[0]-1: + if ~np.isreal(poles[idx]): + rel = transfer_matrix[:, idx].copy() + img = transfer_matrix[:, idx+1] + # rel will be an array referencing a column of transfer_matrix + # if we don't copy() it will changer after the next line and + # and the line after will not yield the correct value + transfer_matrix[:, idx] = rel-1j*img + transfer_matrix[:, idx+1] = rel+1j*img + idx += 1 # skip next one + idx += 1 + + try: + m = np.linalg.solve(transfer_matrix.T, np.dot(np.diag(poles), + transfer_matrix.T)).T + gain_matrix = np.linalg.solve(z, np.dot(u0.T, m-A)) + except np.linalg.LinAlgError as e: + raise ValueError("The poles you've chosen can't be placed. " + "Check the controllability matrix and try " + "another set of poles") from e + + # Beware: Kautsky solves A+BK but the usual form is A-BK + gain_matrix = -gain_matrix + # K still contains complex with ~=0j imaginary parts, get rid of them + gain_matrix = np.real(gain_matrix) + + full_state_feedback = Bunch() + full_state_feedback.gain_matrix = gain_matrix + full_state_feedback.computed_poles = _order_complex_poles( + np.linalg.eig(A - np.dot(B, gain_matrix))[0] + ) + full_state_feedback.requested_poles = poles + full_state_feedback.X = transfer_matrix + full_state_feedback.rtol = cur_rtol + full_state_feedback.nb_iter = nb_iter + + return full_state_feedback + + +def dlsim(system, u, t=None, x0=None): + """ + Simulate output of a discrete-time linear system. + + Parameters + ---------- + system : tuple of array_like or instance of `dlti` + A tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `dlti`) + * 3: (num, den, dt) + * 4: (zeros, poles, gain, dt) + * 5: (A, B, C, D, dt) + + u : array_like + An input array describing the input at each time `t` (interpolation is + assumed between given times). If there are multiple inputs, then each + column of the rank-2 array represents an input. + t : array_like, optional + The time steps at which the input is defined. If `t` is given, it + must be the same length as `u`, and the final value in `t` determines + the number of steps returned in the output. + x0 : array_like, optional + The initial conditions on the state vector (zero by default). + + Returns + ------- + tout : ndarray + Time values for the output, as a 1-D array. + yout : ndarray + System response, as a 1-D array. + xout : ndarray, optional + Time-evolution of the state-vector. Only generated if the input is a + `StateSpace` system. + + See Also + -------- + lsim, dstep, dimpulse, cont2discrete + + Examples + -------- + A simple integrator transfer function with a discrete time step of 1.0 + could be implemented as: + + >>> import numpy as np + >>> from scipy import signal + >>> tf = ([1.0,], [1.0, -1.0], 1.0) + >>> t_in = [0.0, 1.0, 2.0, 3.0] + >>> u = np.asarray([0.0, 0.0, 1.0, 1.0]) + >>> t_out, y = signal.dlsim(tf, u, t=t_in) + >>> y.T + array([[ 0., 0., 0., 1.]]) + + """ + # Convert system to dlti-StateSpace + if isinstance(system, lti): + raise AttributeError('dlsim can only be used with discrete-time dlti ' + 'systems.') + elif not isinstance(system, dlti): + system = dlti(*system[:-1], dt=system[-1]) + + # Condition needed to ensure output remains compatible + is_ss_input = isinstance(system, StateSpace) + system = system._as_ss() + + u = np.atleast_1d(u) + + if u.ndim == 1: + u = np.atleast_2d(u).T + + if t is None: + out_samples = len(u) + stoptime = (out_samples - 1) * system.dt + else: + stoptime = t[-1] + out_samples = int(np.floor(stoptime / system.dt)) + 1 + + # Pre-build output arrays + xout = np.zeros((out_samples, system.A.shape[0])) + yout = np.zeros((out_samples, system.C.shape[0])) + tout = np.linspace(0.0, stoptime, num=out_samples) + + # Check initial condition + if x0 is None: + xout[0, :] = np.zeros((system.A.shape[1],)) + else: + xout[0, :] = np.asarray(x0) + + # Pre-interpolate inputs into the desired time steps + if t is None: + u_dt = u + else: + if len(u.shape) == 1: + u = u[:, np.newaxis] + + u_dt = make_interp_spline(t, u, k=1)(tout) + + # Simulate the system + for i in range(0, out_samples - 1): + xout[i+1, :] = (np.dot(system.A, xout[i, :]) + + np.dot(system.B, u_dt[i, :])) + yout[i, :] = (np.dot(system.C, xout[i, :]) + + np.dot(system.D, u_dt[i, :])) + + # Last point + yout[out_samples-1, :] = (np.dot(system.C, xout[out_samples-1, :]) + + np.dot(system.D, u_dt[out_samples-1, :])) + + if is_ss_input: + return tout, yout, xout + else: + return tout, yout + + +def dimpulse(system, x0=None, t=None, n=None): + """ + Impulse response of discrete-time system. + + Parameters + ---------- + system : tuple of array_like or instance of `dlti` + A tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `dlti`) + * 3: (num, den, dt) + * 4: (zeros, poles, gain, dt) + * 5: (A, B, C, D, dt) + + x0 : array_like, optional + Initial state-vector. Defaults to zero. + t : array_like, optional + Time points. Computed if not given. + n : int, optional + The number of time points to compute (if `t` is not given). + + Returns + ------- + tout : ndarray + Time values for the output, as a 1-D array. + yout : tuple of ndarray + Impulse response of system. Each element of the tuple represents + the output of the system based on an impulse in each input. + + See Also + -------- + impulse, dstep, dlsim, cont2discrete + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> butter = signal.dlti(*signal.butter(3, 0.5)) + >>> t, y = signal.dimpulse(butter, n=25) + >>> plt.step(t, np.squeeze(y)) + >>> plt.grid() + >>> plt.xlabel('n [samples]') + >>> plt.ylabel('Amplitude') + + """ + # Convert system to dlti-StateSpace + if isinstance(system, dlti): + system = system._as_ss() + elif isinstance(system, lti): + raise AttributeError('dimpulse can only be used with discrete-time ' + 'dlti systems.') + else: + system = dlti(*system[:-1], dt=system[-1])._as_ss() + + # Default to 100 samples if unspecified + if n is None: + n = 100 + + # If time is not specified, use the number of samples + # and system dt + if t is None: + t = np.linspace(0, n * system.dt, n, endpoint=False) + else: + t = np.asarray(t) + + # For each input, implement a step change + yout = None + for i in range(0, system.inputs): + u = np.zeros((t.shape[0], system.inputs)) + u[0, i] = 1.0 + + one_output = dlsim(system, u, t=t, x0=x0) + + if yout is None: + yout = (one_output[1],) + else: + yout = yout + (one_output[1],) + + tout = one_output[0] + + return tout, yout + + +def dstep(system, x0=None, t=None, n=None): + """ + Step response of discrete-time system. + + Parameters + ---------- + system : tuple of array_like + A tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `dlti`) + * 3: (num, den, dt) + * 4: (zeros, poles, gain, dt) + * 5: (A, B, C, D, dt) + + x0 : array_like, optional + Initial state-vector. Defaults to zero. + t : array_like, optional + Time points. Computed if not given. + n : int, optional + The number of time points to compute (if `t` is not given). + + Returns + ------- + tout : ndarray + Output time points, as a 1-D array. + yout : tuple of ndarray + Step response of system. Each element of the tuple represents + the output of the system based on a step response to each input. + + See Also + -------- + step, dimpulse, dlsim, cont2discrete + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> butter = signal.dlti(*signal.butter(3, 0.5)) + >>> t, y = signal.dstep(butter, n=25) + >>> plt.step(t, np.squeeze(y)) + >>> plt.grid() + >>> plt.xlabel('n [samples]') + >>> plt.ylabel('Amplitude') + """ + # Convert system to dlti-StateSpace + if isinstance(system, dlti): + system = system._as_ss() + elif isinstance(system, lti): + raise AttributeError('dstep can only be used with discrete-time dlti ' + 'systems.') + else: + system = dlti(*system[:-1], dt=system[-1])._as_ss() + + # Default to 100 samples if unspecified + if n is None: + n = 100 + + # If time is not specified, use the number of samples + # and system dt + if t is None: + t = np.linspace(0, n * system.dt, n, endpoint=False) + else: + t = np.asarray(t) + + # For each input, implement a step change + yout = None + for i in range(0, system.inputs): + u = np.zeros((t.shape[0], system.inputs)) + u[:, i] = np.ones((t.shape[0],)) + + one_output = dlsim(system, u, t=t, x0=x0) + + if yout is None: + yout = (one_output[1],) + else: + yout = yout + (one_output[1],) + + tout = one_output[0] + + return tout, yout + + +def dfreqresp(system, w=None, n=10000, whole=False): + r""" + Calculate the frequency response of a discrete-time system. + + Parameters + ---------- + system : an instance of the `dlti` class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `dlti`) + * 2 (numerator, denominator, dt) + * 3 (zeros, poles, gain, dt) + * 4 (A, B, C, D, dt) + + w : array_like, optional + Array of frequencies (in radians/sample). Magnitude and phase data is + calculated for every value in this array. If not given a reasonable + set will be calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + whole : bool, optional + Normally, if 'w' is not given, frequencies are computed from 0 to the + Nyquist frequency, pi radians/sample (upper-half of unit-circle). If + `whole` is True, compute frequencies from 0 to 2*pi radians/sample. + + Returns + ------- + w : 1D ndarray + Frequency array [radians/sample] + H : 1D ndarray + Array of complex magnitude values + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``z^2 + 3z + 5`` would be represented as ``[1, 3, 5]``). + + .. versionadded:: 0.18.0 + + Examples + -------- + Generating the Nyquist plot of a transfer function + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Construct the transfer function + :math:`H(z) = \frac{1}{z^2 + 2z + 3}` with a sampling time of 0.05 + seconds: + + >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.05) + + >>> w, H = signal.dfreqresp(sys) + + >>> plt.figure() + >>> plt.plot(H.real, H.imag, "b") + >>> plt.plot(H.real, -H.imag, "r") + >>> plt.show() + + """ + if not isinstance(system, dlti): + if isinstance(system, lti): + raise AttributeError('dfreqresp can only be used with ' + 'discrete-time systems.') + + system = dlti(*system[:-1], dt=system[-1]) + + if isinstance(system, StateSpace): + # No SS->ZPK code exists right now, just SS->TF->ZPK + system = system._as_tf() + + if not isinstance(system, (TransferFunction, ZerosPolesGain)): + raise ValueError('Unknown system type') + + if system.inputs != 1 or system.outputs != 1: + raise ValueError("dfreqresp requires a SISO (single input, single " + "output) system.") + + if w is not None: + worN = w + else: + worN = n + + if isinstance(system, TransferFunction): + # Convert numerator and denominator from polynomials in the variable + # 'z' to polynomials in the variable 'z^-1', as freqz expects. + num, den = TransferFunction._z_to_zinv(system.num.ravel(), system.den) + w, h = freqz(num, den, worN=worN, whole=whole) + + elif isinstance(system, ZerosPolesGain): + w, h = freqz_zpk(system.zeros, system.poles, system.gain, worN=worN, + whole=whole) + + return w, h + + +def dbode(system, w=None, n=100): + r""" + Calculate Bode magnitude and phase data of a discrete-time system. + + Parameters + ---------- + system : + An instance of the LTI class `dlti` or a tuple describing the system. + The number of elements in the tuple determine the interpretation, i.e.: + + 1. ``(sys_dlti)``: Instance of LTI class `dlti`. Note that derived instances, + such as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, + are allowed as well. + 2. ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`. + The coefficients of the polynomials should be specified in descending + exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``. + 3. ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described + in `ZerosPolesGain`. + 4. ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`. + + w : array_like, optional + Array of frequencies normalized to the Nyquist frequency being π, i.e., + having unit radiant / sample. Magnitude and phase data is calculated for every + value in this array. If not given, a reasonable set will be calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + + Returns + ------- + w : 1D ndarray + Array of frequencies normalized to the Nyquist frequency being ``np.pi/dt`` + with ``dt`` being the sampling interval of the `system` parameter. + The unit is rad/s assuming ``dt`` is in seconds. + mag : 1D ndarray + Magnitude array in dB + phase : 1D ndarray + Phase array in degrees + + Notes + ----- + This function is a convenience wrapper around `dfreqresp` for extracting + magnitude and phase from the calculated complex-valued amplitude of the + frequency response. + + .. versionadded:: 0.18.0 + + See Also + -------- + dfreqresp, dlti, TransferFunction, ZerosPolesGain, StateSpace + + + Examples + -------- + The following example shows how to create a Bode plot of a 5-th order + Butterworth lowpass filter with a corner frequency of 100 Hz: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy import signal + ... + >>> T = 1e-4 # sampling interval in s + >>> f_c, o = 1e2, 5 # corner frequency in Hz (i.e., -3 dB value) and filter order + >>> bb, aa = signal.butter(o, f_c, 'lowpass', fs=1/T) + ... + >>> w, mag, phase = signal.dbode((bb, aa, T)) + >>> w /= 2*np.pi # convert unit of frequency into Hertz + ... + >>> fg, (ax0, ax1) = plt.subplots(2, 1, sharex='all', figsize=(5, 4), + ... tight_layout=True) + >>> ax0.set_title("Bode Plot of Butterworth Lowpass Filter " + + ... rf"($f_c={f_c:g}\,$Hz, order={o})") + >>> ax0.set_ylabel(r"Magnitude in dB") + >>> ax1.set(ylabel=r"Phase in Degrees", + ... xlabel="Frequency $f$ in Hertz", xlim=(w[1], w[-1])) + >>> ax0.semilogx(w, mag, 'C0-', label=r"$20\,\log_{10}|G(f)|$") # Magnitude plot + >>> ax1.semilogx(w, phase, 'C1-', label=r"$\angle G(f)$") # Phase plot + ... + >>> for ax_ in (ax0, ax1): + ... ax_.axvline(f_c, color='m', alpha=0.25, label=rf"${f_c=:g}\,$Hz") + ... ax_.grid(which='both', axis='x') # plot major & minor vertical grid lines + ... ax_.grid(which='major', axis='y') + ... ax_.legend() + >>> plt.show() + """ + w, y = dfreqresp(system, w=w, n=n) + + if isinstance(system, dlti): + dt = system.dt + else: + dt = system[-1] + + mag = 20.0 * np.log10(abs(y)) + phase = np.rad2deg(np.unwrap(np.angle(y))) + + return w / dt, mag, phase diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..4d64beaca86d1da50b563668679b6fc52c954ab0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py @@ -0,0 +1,139 @@ +# Author: Eric Larson +# 2014 + +"""Tools for MLS generation""" + +import numpy as np + +from ._max_len_seq_inner import _max_len_seq_inner + +__all__ = ['max_len_seq'] + + +# These are definitions of linear shift register taps for use in max_len_seq() +_mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1], + 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8], + 14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14], + 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21], + 23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20], + 27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7], + 31: [28], 32: [31, 30, 10]} + +def max_len_seq(nbits, state=None, length=None, taps=None): + """ + Maximum length sequence (MLS) generator. + + Parameters + ---------- + nbits : int + Number of bits to use. Length of the resulting sequence will + be ``(2**nbits) - 1``. Note that generating long sequences + (e.g., greater than ``nbits == 16``) can take a long time. + state : array_like, optional + If array, must be of length ``nbits``, and will be cast to binary + (bool) representation. If None, a seed of ones will be used, + producing a repeatable representation. If ``state`` is all + zeros, an error is raised as this is invalid. Default: None. + length : int, optional + Number of samples to compute. If None, the entire length + ``(2**nbits) - 1`` is computed. + taps : array_like, optional + Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence). + If None, taps will be automatically selected (for up to + ``nbits == 32``). + + Returns + ------- + seq : array + Resulting MLS sequence of 0's and 1's. + state : array + The final state of the shift register. + + Notes + ----- + The algorithm for MLS generation is generically described in: + + https://en.wikipedia.org/wiki/Maximum_length_sequence + + The default values for taps are specifically taken from the first + option listed for each value of ``nbits`` in: + + https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm + + .. versionadded:: 0.15.0 + + Examples + -------- + MLS uses binary convention: + + >>> from scipy.signal import max_len_seq + >>> max_len_seq(4)[0] + array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8) + + MLS has a white spectrum (except for DC): + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from numpy.fft import fft, ifft, fftshift, fftfreq + >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1 + >>> spec = fft(seq) + >>> N = len(seq) + >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-') + >>> plt.margins(0.1, 0.1) + >>> plt.grid(True) + >>> plt.show() + + Circular autocorrelation of MLS is an impulse: + + >>> acorrcirc = ifft(spec * np.conj(spec)).real + >>> plt.figure() + >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-') + >>> plt.margins(0.1, 0.1) + >>> plt.grid(True) + >>> plt.show() + + Linear autocorrelation of MLS is approximately an impulse: + + >>> acorr = np.correlate(seq, seq, 'full') + >>> plt.figure() + >>> plt.plot(np.arange(-N+1, N), acorr, '.-') + >>> plt.margins(0.1, 0.1) + >>> plt.grid(True) + >>> plt.show() + + """ + taps_dtype = np.int32 if np.intp().itemsize == 4 else np.int64 + if taps is None: + if nbits not in _mls_taps: + known_taps = np.array(list(_mls_taps.keys())) + raise ValueError(f'nbits must be between {known_taps.min()} and ' + f'{known_taps.max()} if taps is None') + taps = np.array(_mls_taps[nbits], taps_dtype) + else: + taps = np.unique(np.array(taps, taps_dtype))[::-1] + if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1: + raise ValueError('taps must be non-empty with values between ' + 'zero and nbits (inclusive)') + taps = np.array(taps) # needed for Cython and Pythran + n_max = (2**nbits) - 1 + if length is None: + length = n_max + else: + length = int(length) + if length < 0: + raise ValueError('length must be greater than or equal to 0') + # We use int8 instead of bool here because NumPy arrays of bools + # don't seem to work nicely with Cython + if state is None: + state = np.ones(nbits, dtype=np.int8, order='c') + else: + # makes a copy if need be, ensuring it's 0's and 1's + state = np.array(state, dtype=bool, order='c').astype(np.int8) + if state.ndim != 1 or state.size != nbits: + raise ValueError('state must be a 1-D array of size nbits') + if np.all(state == 0): + raise ValueError('state must not be all zeros') + + seq = np.empty(length, dtype=np.int8, order='c') + state = _max_len_seq_inner(taps, state, nbits, length, seq) + return seq, state diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_max_len_seq_inner.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_max_len_seq_inner.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4eb7c7b2a3b658919f14450c20cad1e612a327d7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_max_len_seq_inner.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_peak_finding.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_peak_finding.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbeca5b7a4839bbc28e9c1cfd1ebd1d028a82cf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_peak_finding.py @@ -0,0 +1,1310 @@ +""" +Functions for identifying peaks in signals. +""" +import math +import numpy as np + +from scipy.signal._wavelets import _cwt, _ricker +from scipy.stats import scoreatpercentile + +from ._peak_finding_utils import ( + _local_maxima_1d, + _select_by_peak_distance, + _peak_prominences, + _peak_widths +) + + +__all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences', + 'peak_widths', 'find_peaks', 'find_peaks_cwt'] + + +def _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Relative extrema are calculated by finding locations where + ``comparator(data[n], data[n+1:n+order+1])`` is True. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n,n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : ndarray + Boolean array of the same shape as `data` that is True at an extrema, + False otherwise. + + See also + -------- + argrelmax, argrelmin + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _boolrelextrema + >>> testdata = np.array([1,2,3,2,1]) + >>> _boolrelextrema(testdata, np.greater, axis=0) + array([False, False, True, False, False], dtype=bool) + + """ + if (int(order) != order) or (order < 1): + raise ValueError('Order must be an int >= 1') + + datalen = data.shape[axis] + locs = np.arange(0, datalen) + + results = np.ones(data.shape, dtype=bool) + main = data.take(locs, axis=axis, mode=mode) + for shift in range(1, order + 1): + plus = data.take(locs + shift, axis=axis, mode=mode) + minus = data.take(locs - shift, axis=axis, mode=mode) + results &= comparator(main, plus) + results &= comparator(main, minus) + if ~results.any(): + return results + return results + + +def argrelmin(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative minima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative minima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the minima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmax, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.less as comparator. Therefore, it + requires a strict inequality on both sides of a value to consider it a + minimum. This means flat minima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local minima, including flat ones, by calling it with negated `data`. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmin + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmin(x) + (array([1, 5]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmin(y, axis=1) + (array([0, 2]), array([2, 1])) + + """ + return argrelextrema(data, np.less, axis, order, mode) + + +def argrelmax(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative maxima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative maxima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmin, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.greater as comparator. Therefore, + it requires a strict inequality on both sides of a value to consider it a + maximum. This means flat maxima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local maxima, including flat ones. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmax + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmax(x) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmax(y, axis=1) + (array([0]), array([1])) + """ + return argrelextrema(data, np.greater, axis, order, mode) + + +def argrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default is 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelmin, argrelmax + + Notes + ----- + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelextrema + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelextrema(x, np.greater) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelextrema(y, np.less, axis=1) + (array([0, 2]), array([2, 1])) + + """ + results = _boolrelextrema(data, comparator, + axis, order, mode) + return np.nonzero(results) + + +def _arg_x_as_expected(value): + """Ensure argument `x` is a 1-D C-contiguous array of dtype('float64'). + + Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x` + compatible with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('float64'). + """ + value = np.asarray(value, order='C', dtype=np.float64) + if value.ndim != 1: + raise ValueError('`x` must be a 1-D array') + return value + + +def _arg_peaks_as_expected(value): + """Ensure argument `peaks` is a 1-D C-contiguous array of dtype('intp'). + + Used in `peak_prominences` and `peak_widths` to make `peaks` compatible + with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('intp'). + """ + value = np.asarray(value) + if value.size == 0: + # Empty arrays default to np.float64 but are valid input + value = np.array([], dtype=np.intp) + try: + # Safely convert to C-contiguous array of type np.intp + value = value.astype(np.intp, order='C', casting='safe', + subok=False, copy=False) + except TypeError as e: + raise TypeError("cannot safely cast `peaks` to dtype('intp')") from e + if value.ndim != 1: + raise ValueError('`peaks` must be a 1-D array') + return value + + +def _arg_wlen_as_expected(value): + """Ensure argument `wlen` is of type `np.intp` and larger than 1. + + Used in `peak_prominences` and `peak_widths`. + + Returns + ------- + value : np.intp + The original `value` rounded up to an integer or -1 if `value` was + None. + """ + if value is None: + # _peak_prominences expects an intp; -1 signals that no value was + # supplied by the user + value = -1 + elif 1 < value: + # Round up to a positive integer + if isinstance(value, float): + value = math.ceil(value) + value = np.intp(value) + else: + raise ValueError(f'`wlen` must be larger than 1, was {value}') + return value + + +def peak_prominences(x, peaks, wlen=None): + """ + Calculate the prominence of each peak in a signal. + + The prominence of a peak measures how much a peak stands out from the + surrounding baseline of the signal and is defined as the vertical distance + between the peak and its lowest contour line. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + wlen : int, optional + A window length in samples that optionally limits the evaluated area for + each peak to a subset of `x`. The peak is always placed in the middle of + the window therefore the given length is rounded up to the next odd + integer. This parameter can speed up the calculation (see Notes). + + Returns + ------- + prominences : ndarray + The calculated prominences for each peak in `peaks`. + left_bases, right_bases : ndarray + The peaks' bases as indices in `x` to the left and right of each peak. + The higher base of each pair is a peak's lowest contour line. + + Raises + ------ + ValueError + If a value in `peaks` is an invalid index for `x`. + + Warns + ----- + PeakPropertyWarning + For indices in `peaks` that don't point to valid local maxima in `x`, + the returned prominence will be 0 and this warning is raised. This + also happens if `wlen` is smaller than the plateau size of a peak. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_widths + Calculate the width of peaks. + + Notes + ----- + Strategy to compute a peak's prominence: + + 1. Extend a horizontal line from the current peak to the left and right + until the line either reaches the window border (see `wlen`) or + intersects the signal again at the slope of a higher peak. An + intersection with a peak of the same height is ignored. + 2. On each side find the minimal signal value within the interval defined + above. These points are the peak's bases. + 3. The higher one of the two bases marks the peak's lowest contour line. The + prominence can then be calculated as the vertical difference between the + peaks height itself and its lowest contour line. + + Searching for the peak's bases can be slow for large `x` with periodic + behavior because large chunks or even the full signal need to be evaluated + for the first algorithmic step. This evaluation area can be limited with the + parameter `wlen` which restricts the algorithm to a window around the + current peak and can shorten the calculation time if the window length is + short in relation to `x`. + However, this may stop the algorithm from finding the true global contour + line if the peak's true bases are outside this window. Instead, a higher + contour line is found within the restricted window leading to a smaller + calculated prominence. In practice, this is only relevant for the highest set + of peaks in `x`. This behavior may even be used intentionally to calculate + "local" prominences. + + .. versionadded:: 1.1.0 + + References + ---------- + .. [1] Wikipedia Article for Topographic Prominence: + https://en.wikipedia.org/wiki/Topographic_prominence + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import find_peaks, peak_prominences + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate prominences + + >>> peaks, _ = find_peaks(x) + >>> prominences = peak_prominences(x, peaks)[0] + >>> prominences + array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 , + 0.47822491, 2.48340261, 0.47822491]) + + Calculate the height of each peak's contour line and plot the results + + >>> contour_heights = x[peaks] - prominences + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks]) + >>> plt.show() + + Let's evaluate a second example that demonstrates several edge cases for + one peak at index 5. + + >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0]) + >>> peaks = np.array([5]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases) + (array([3.]), array([2]), array([6])) + + Note how the peak at index 3 of the same height is not considered as a + border while searching for the left base. Instead, two minima at 0 and 2 + are found in which case the one closer to the evaluated peak is always + chosen. On the right side, however, the base must be placed at 6 because the + higher peak represents the right border to the evaluated area. + + >>> peak_prominences(x, peaks, wlen=3.1) + (array([2.]), array([4]), array([6])) + + Here, we restricted the algorithm to a window from 3 to 7 (the length is 5 + samples because `wlen` was rounded up to the next odd integer). Thus, the + only two candidates in the evaluated area are the two neighboring samples + and a smaller prominence is calculated. + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + wlen = _arg_wlen_as_expected(wlen) + return _peak_prominences(x, peaks, wlen) + + +def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None): + """ + Calculate the width of each peak in a signal. + + This function calculates the width of a peak in samples at a relative + distance to the peak's height and prominence. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + rel_height : float, optional + Chooses the relative height at which the peak width is measured as a + percentage of its prominence. 1.0 calculates the width of the peak at + its lowest contour line while 0.5 evaluates at half the prominence + height. Must be at least 0. See notes for further explanation. + prominence_data : tuple, optional + A tuple of three arrays matching the output of `peak_prominences` when + called with the same arguments `x` and `peaks`. This data are calculated + internally if not provided. + wlen : int, optional + A window length in samples passed to `peak_prominences` as an optional + argument for internal calculation of `prominence_data`. This argument + is ignored if `prominence_data` is given. + + Returns + ------- + widths : ndarray + The widths for each peak in samples. + width_heights : ndarray + The height of the contour lines at which the `widths` where evaluated. + left_ips, right_ips : ndarray + Interpolated positions of left and right intersection points of a + horizontal line at the respective evaluation height. + + Raises + ------ + ValueError + If `prominence_data` is supplied but doesn't satisfy the condition + ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak, + has the wrong dtype, is not C-contiguous or does not have the same + shape. + + Warns + ----- + PeakPropertyWarning + Raised if any calculated width is 0. This may stem from the supplied + `prominence_data` or if `rel_height` is set to 0. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_prominences + Calculate the prominence of peaks. + + Notes + ----- + The basic algorithm to calculate a peak's width is as follows: + + * Calculate the evaluation height :math:`h_{eval}` with the formula + :math:`h_{eval} = h_{Peak} - P \\cdot R`, where :math:`h_{Peak}` is the + height of the peak itself, :math:`P` is the peak's prominence and + :math:`R` a positive ratio specified with the argument `rel_height`. + * Draw a horizontal line at the evaluation height to both sides, starting at + the peak's current vertical position until the lines either intersect a + slope, the signal border or cross the vertical position of the peak's + base (see `peak_prominences` for an definition). For the first case, + intersection with the signal, the true intersection point is estimated + with linear interpolation. + * Calculate the width as the horizontal distance between the chosen + endpoints on both sides. As a consequence of this the maximal possible + width for each peak is the horizontal distance between its bases. + + As shown above to calculate a peak's width its prominence and bases must be + known. You can supply these yourself with the argument `prominence_data`. + Otherwise, they are internally calculated (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import chirp, find_peaks, peak_widths + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate their widths at the relative height of 0.5 + (contour line at half the prominence height) and 1 (at the lowest contour + line at full prominence height). + + >>> peaks, _ = find_peaks(x) + >>> results_half = peak_widths(x, peaks, rel_height=0.5) + >>> results_half[0] # widths + array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081, + 35.46729324, 41.30429622, 181.93835853, 45.37078546]) + >>> results_full = peak_widths(x, peaks, rel_height=1) + >>> results_full[0] # widths + array([181.9396084 , 72.99284945, 61.28657872, 373.84622694, + 61.78404617, 72.48822812, 253.09161876, 79.36860878]) + + Plot signal, peaks and contour lines at which the widths where calculated + + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.hlines(*results_half[1:], color="C2") + >>> plt.hlines(*results_full[1:], color="C3") + >>> plt.show() + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + if prominence_data is None: + # Calculate prominence if not supplied and use wlen if supplied. + wlen = _arg_wlen_as_expected(wlen) + prominence_data = _peak_prominences(x, peaks, wlen) + return _peak_widths(x, peaks, rel_height, *prominence_data) + + +def _unpack_condition_args(interval, x, peaks): + """ + Parse condition arguments for `find_peaks`. + + Parameters + ---------- + interval : number or ndarray or sequence + Either a number or ndarray or a 2-element sequence of the former. The + first value is always interpreted as `imin` and the second, if supplied, + as `imax`. + x : ndarray + The signal with `peaks`. + peaks : ndarray + An array with indices used to reduce `imin` and / or `imax` if those are + arrays. + + Returns + ------- + imin, imax : number or ndarray or None + Minimal and maximal value in `argument`. + + Raises + ------ + ValueError : + If interval border is given as array and its size does not match the size + of `x`. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + try: + imin, imax = interval + except (TypeError, ValueError): + imin, imax = (interval, None) + + # Reduce arrays if arrays + if isinstance(imin, np.ndarray): + if imin.size != x.size: + raise ValueError('array size of lower interval border must match x') + imin = imin[peaks] + if isinstance(imax, np.ndarray): + if imax.size != x.size: + raise ValueError('array size of upper interval border must match x') + imax = imax[peaks] + + return imin, imax + + +def _select_by_property(peak_properties, pmin, pmax): + """ + Evaluate where the generic property of peaks confirms to an interval. + + Parameters + ---------- + peak_properties : ndarray + An array with properties for each peak. + pmin : None or number or ndarray + Lower interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + pmax : None or number or ndarray + Upper interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peak_properties` confirms to the + interval. + + See Also + -------- + find_peaks + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + keep = np.ones(peak_properties.size, dtype=bool) + if pmin is not None: + keep &= (pmin <= peak_properties) + if pmax is not None: + keep &= (peak_properties <= pmax) + return keep + + +def _select_by_peak_threshold(x, peaks, tmin, tmax): + """ + Evaluate which peaks fulfill the threshold condition. + + Parameters + ---------- + x : ndarray + A 1-D array which is indexable by `peaks`. + peaks : ndarray + Indices of peaks in `x`. + tmin, tmax : scalar or ndarray or None + Minimal and / or maximal required thresholds. If supplied as ndarrays + their size must match `peaks`. ``None`` is interpreted as an open + border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peaks` fulfill the threshold + condition. + left_thresholds, right_thresholds : ndarray + Array matching `peak` containing the thresholds of each peak on + both sides. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + # Stack thresholds on both sides to make min / max operations easier: + # tmin is compared with the smaller, and tmax with the greater threshold to + # each peak's side + stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1], + x[peaks] - x[peaks + 1]]) + keep = np.ones(peaks.size, dtype=bool) + if tmin is not None: + min_thresholds = np.min(stacked_thresholds, axis=0) + keep &= (tmin <= min_thresholds) + if tmax is not None: + max_thresholds = np.max(stacked_thresholds, axis=0) + keep &= (max_thresholds <= tmax) + + return keep, stacked_thresholds[0], stacked_thresholds[1] + + +def find_peaks(x, height=None, threshold=None, distance=None, + prominence=None, width=None, wlen=None, rel_height=0.5, + plateau_size=None): + """ + Find peaks inside a signal based on peak properties. + + This function takes a 1-D array and finds all local maxima by + simple comparison of neighboring values. Optionally, a subset of these + peaks can be selected by specifying conditions for a peak's properties. + + Parameters + ---------- + x : sequence + A signal with peaks. + height : number or ndarray or sequence, optional + Required height of peaks. Either a number, ``None``, an array matching + `x` or a 2-element sequence of the former. The first element is + always interpreted as the minimal and the second, if supplied, as the + maximal required height. + threshold : number or ndarray or sequence, optional + Required threshold of peaks, the vertical distance to its neighboring + samples. Either a number, ``None``, an array matching `x` or a + 2-element sequence of the former. The first element is always + interpreted as the minimal and the second, if supplied, as the maximal + required threshold. + distance : number, optional + Required minimal horizontal distance (>= 1) in samples between + neighbouring peaks. Smaller peaks are removed first until the condition + is fulfilled for all remaining peaks. + prominence : number or ndarray or sequence, optional + Required prominence of peaks. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required prominence. + width : number or ndarray or sequence, optional + Required width of peaks in samples. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required width. + wlen : int, optional + Used for calculation of the peaks prominences, thus it is only used if + one of the arguments `prominence` or `width` is given. See argument + `wlen` in `peak_prominences` for a full description of its effects. + rel_height : float, optional + Used for calculation of the peaks width, thus it is only used if `width` + is given. See argument `rel_height` in `peak_widths` for a full + description of its effects. + plateau_size : number or ndarray or sequence, optional + Required size of the flat top of peaks in samples. Either a number, + ``None``, an array matching `x` or a 2-element sequence of the former. + The first element is always interpreted as the minimal and the second, + if supplied as the maximal required plateau size. + + .. versionadded:: 1.2.0 + + Returns + ------- + peaks : ndarray + Indices of peaks in `x` that satisfy all given conditions. + properties : dict + A dictionary containing properties of the returned peaks which were + calculated as intermediate results during evaluation of the specified + conditions: + + * 'peak_heights' + If `height` is given, the height of each peak in `x`. + * 'left_thresholds', 'right_thresholds' + If `threshold` is given, these keys contain a peaks vertical + distance to its neighbouring samples. + * 'prominences', 'right_bases', 'left_bases' + If `prominence` is given, these keys are accessible. See + `peak_prominences` for a description of their content. + * 'widths', 'width_heights', 'left_ips', 'right_ips' + If `width` is given, these keys are accessible. See `peak_widths` + for a description of their content. + * 'plateau_sizes', left_edges', 'right_edges' + If `plateau_size` is given, these keys are accessible and contain + the indices of a peak's edges (edges are still part of the + plateau) and the calculated plateau sizes. + + .. versionadded:: 1.2.0 + + To calculate and return properties without excluding peaks, provide the + open interval ``(None, None)`` as a value to the appropriate argument + (excluding `distance`). + + Warns + ----- + PeakPropertyWarning + Raised if a peak's properties have unexpected values (see + `peak_prominences` and `peak_widths`). + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks_cwt + Find peaks using the wavelet transformation. + peak_prominences + Directly calculate the prominence of peaks. + peak_widths + Directly calculate the width of peaks. + + Notes + ----- + In the context of this function, a peak or local maximum is defined as any + sample whose two direct neighbours have a smaller amplitude. For flat peaks + (more than one sample of equal amplitude wide) the index of the middle + sample is returned (rounded down in case the number of samples is even). + For noisy signals the peak locations can be off because the noise might + change the position of local maxima. In those cases consider smoothing the + signal before searching for peaks or use other peak finding and fitting + methods (like `find_peaks_cwt`). + + Some additional comments on specifying conditions: + + * Almost all conditions (excluding `distance`) can be given as half-open or + closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open + interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval + :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified + as well, which returns the matching properties without exclusion of peaks. + * The border is always included in the interval used to select valid peaks. + * For several conditions the interval borders can be specified with + arrays matching `x` in shape which enables dynamic constrains based on + the sample position. + * The conditions are evaluated in the following order: `plateau_size`, + `height`, `threshold`, `distance`, `prominence`, `width`. In most cases + this order is the fastest one because faster operations are applied first + to reduce the number of peaks that need to be evaluated later. + * While indices in `peaks` are guaranteed to be at least `distance` samples + apart, edges of flat peaks may be closer than the allowed `distance`. + * Use `wlen` to reduce the time it takes to evaluate the conditions for + `prominence` or `width` if `x` is large or has many local maxima + (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + To demonstrate this function's usage we use a signal `x` supplied with + SciPy (see `scipy.datasets.electrocardiogram`). Let's find all peaks (local + maxima) in `x` whose amplitude lies above 0. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.datasets import electrocardiogram + >>> from scipy.signal import find_peaks + >>> x = electrocardiogram()[2000:4000] + >>> peaks, _ = find_peaks(x, height=0) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.plot(np.zeros_like(x), "--", color="gray") + >>> plt.show() + + We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching + `x` in size to reflect a changing condition for different parts of the + signal. + + >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size)) + >>> peaks, _ = find_peaks(x, height=(-border, border)) + >>> plt.plot(x) + >>> plt.plot(-border, "--", color="gray") + >>> plt.plot(border, ":", color="gray") + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Another useful condition for periodic signals can be given with the + `distance` argument. In this case, we can easily select the positions of + QRS complexes within the electrocardiogram (ECG) by demanding a distance of + at least 150 samples. + + >>> peaks, _ = find_peaks(x, distance=150) + >>> np.diff(peaks) + array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Especially for noisy signals peaks can be easily grouped by their + prominence (see `peak_prominences`). E.g., we can select all peaks except + for the mentioned QRS complexes by limiting the allowed prominence to 0.6. + + >>> peaks, properties = find_peaks(x, prominence=(None, 0.6)) + >>> properties["prominences"].max() + 0.5049999999999999 + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + And, finally, let's examine a different section of the ECG which contains + beat forms of different shape. To select only the atypical heart beats, we + combine two conditions: a minimal prominence of 1 and width of at least 20 + samples. + + >>> x = electrocardiogram()[17000:18000] + >>> peaks, properties = find_peaks(x, prominence=1, width=20) + >>> properties["prominences"], properties["widths"] + (array([1.495, 2.3 ]), array([36.93773946, 39.32723577])) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"], + ... ymax = x[peaks], color = "C1") + >>> plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"], + ... xmax=properties["right_ips"], color = "C1") + >>> plt.show() + """ + # _argmaxima1d expects array of dtype 'float64' + x = _arg_x_as_expected(x) + if distance is not None and distance < 1: + raise ValueError('`distance` must be greater or equal to 1') + + peaks, left_edges, right_edges = _local_maxima_1d(x) + properties = {} + + if plateau_size is not None: + # Evaluate plateau size + plateau_sizes = right_edges - left_edges + 1 + pmin, pmax = _unpack_condition_args(plateau_size, x, peaks) + keep = _select_by_property(plateau_sizes, pmin, pmax) + peaks = peaks[keep] + properties["plateau_sizes"] = plateau_sizes + properties["left_edges"] = left_edges + properties["right_edges"] = right_edges + properties = {key: array[keep] for key, array in properties.items()} + + if height is not None: + # Evaluate height condition + peak_heights = x[peaks] + hmin, hmax = _unpack_condition_args(height, x, peaks) + keep = _select_by_property(peak_heights, hmin, hmax) + peaks = peaks[keep] + properties["peak_heights"] = peak_heights + properties = {key: array[keep] for key, array in properties.items()} + + if threshold is not None: + # Evaluate threshold condition + tmin, tmax = _unpack_condition_args(threshold, x, peaks) + keep, left_thresholds, right_thresholds = _select_by_peak_threshold( + x, peaks, tmin, tmax) + peaks = peaks[keep] + properties["left_thresholds"] = left_thresholds + properties["right_thresholds"] = right_thresholds + properties = {key: array[keep] for key, array in properties.items()} + + if distance is not None: + # Evaluate distance condition + keep = _select_by_peak_distance(peaks, x[peaks], distance) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if prominence is not None or width is not None: + # Calculate prominence (required for both conditions) + wlen = _arg_wlen_as_expected(wlen) + properties.update(zip( + ['prominences', 'left_bases', 'right_bases'], + _peak_prominences(x, peaks, wlen=wlen) + )) + + if prominence is not None: + # Evaluate prominence condition + pmin, pmax = _unpack_condition_args(prominence, x, peaks) + keep = _select_by_property(properties['prominences'], pmin, pmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if width is not None: + # Calculate widths + properties.update(zip( + ['widths', 'width_heights', 'left_ips', 'right_ips'], + _peak_widths(x, peaks, rel_height, properties['prominences'], + properties['left_bases'], properties['right_bases']) + )) + # Evaluate width condition + wmin, wmax = _unpack_condition_args(width, x, peaks) + keep = _select_by_property(properties['widths'], wmin, wmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + return peaks, properties + + +def _identify_ridge_lines(matr, max_distances, gap_thresh): + """ + Identify ridges in the 2-D matrix. + + Expect that the width of the wavelet feature increases with increasing row + number. + + Parameters + ---------- + matr : 2-D ndarray + Matrix in which to identify ridge lines. + max_distances : 1-D sequence + At each row, a ridge line is only connected + if the relative max at row[n] is within + `max_distances`[n] from the relative max at row[n+1]. + gap_thresh : int + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if + there are more than `gap_thresh` points without connecting + a new relative maximum. + + Returns + ------- + ridge_lines : tuple + Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the + ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none + found. Each ridge-line will be sorted by row (increasing), but the + order of the ridge lines is not specified. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _identify_ridge_lines + >>> rng = np.random.default_rng() + >>> data = rng.random((5,5)) + >>> max_dist = 3 + >>> max_distances = np.full(20, max_dist) + >>> ridge_lines = _identify_ridge_lines(data, max_distances, 1) + + Notes + ----- + This function is intended to be used in conjunction with `cwt` + as part of `find_peaks_cwt`. + + """ + if len(max_distances) < matr.shape[0]: + raise ValueError('Max_distances must have at least as many rows ' + 'as matr') + + all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1) + # Highest row for which there are any relative maxima + has_relmax = np.nonzero(all_max_cols.any(axis=1))[0] + if len(has_relmax) == 0: + return [] + start_row = has_relmax[-1] + # Each ridge line is a 3-tuple: + # rows, cols,Gap number + ridge_lines = [[[start_row], + [col], + 0] for col in np.nonzero(all_max_cols[start_row])[0]] + final_lines = [] + rows = np.arange(start_row - 1, -1, -1) + cols = np.arange(0, matr.shape[1]) + for row in rows: + this_max_cols = cols[all_max_cols[row]] + + # Increment gap number of each line, + # set it to zero later if appropriate + for line in ridge_lines: + line[2] += 1 + + # XXX These should always be all_max_cols[row] + # But the order might be different. Might be an efficiency gain + # to make sure the order is the same and avoid this iteration + prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines]) + # Look through every relative maximum found at current row + # Attempt to connect them with existing ridge lines. + for ind, col in enumerate(this_max_cols): + # If there is a previous ridge line within + # the max_distance to connect to, do so. + # Otherwise start a new one. + line = None + if len(prev_ridge_cols) > 0: + diffs = np.abs(col - prev_ridge_cols) + closest = np.argmin(diffs) + if diffs[closest] <= max_distances[row]: + line = ridge_lines[closest] + if line is not None: + # Found a point close enough, extend current ridge line + line[1].append(col) + line[0].append(row) + line[2] = 0 + else: + new_line = [[row], + [col], + 0] + ridge_lines.append(new_line) + + # Remove the ridge lines with gap_number too high + # XXX Modifying a list while iterating over it. + # Should be safe, since we iterate backwards, but + # still tacky. + for ind in range(len(ridge_lines) - 1, -1, -1): + line = ridge_lines[ind] + if line[2] > gap_thresh: + final_lines.append(line) + del ridge_lines[ind] + + out_lines = [] + for line in (final_lines + ridge_lines): + sortargs = np.array(np.argsort(line[0])) + rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs) + rows[sortargs] = line[0] + cols[sortargs] = line[1] + out_lines.append([rows, cols]) + + return out_lines + + +def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None, + min_snr=1, noise_perc=10): + """ + Filter ridge lines according to prescribed criteria. Intended + to be used for finding relative maxima. + + Parameters + ---------- + cwt : 2-D ndarray + Continuous wavelet transform from which the `ridge_lines` were defined. + ridge_lines : 1-D sequence + Each element should contain 2 sequences, the rows and columns + of the ridge line (respectively). + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the value of + the cwt matrix at the shortest length scale (``cwt[0, loc]``), the + noise is the `noise_perc`\\ th percentile of datapoints contained within a + window of `window_size` around ``cwt[0, loc]``. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + scipy.stats.scoreatpercentile. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + """ + num_points = cwt.shape[1] + if min_length is None: + min_length = np.ceil(cwt.shape[0] / 4) + if window_size is None: + window_size = np.ceil(num_points / 20) + + window_size = int(window_size) + hf_window, odd = divmod(window_size, 2) + + # Filter based on SNR + row_one = cwt[0, :] + noises = np.empty_like(row_one) + for ind, val in enumerate(row_one): + window_start = max(ind - hf_window, 0) + window_end = min(ind + hf_window + odd, num_points) + noises[ind] = scoreatpercentile(row_one[window_start:window_end], + per=noise_perc) + + def filt_func(line): + if len(line[0]) < min_length: + return False + snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]]) + if snr < min_snr: + return False + return True + + return list(filter(filt_func, ridge_lines)) + + +def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None, + gap_thresh=None, min_length=None, + min_snr=1, noise_perc=10, window_size=None): + """ + Find peaks in a 1-D array with wavelet transformation. + + The general approach is to smooth `vector` by convolving it with + `wavelet(width)` for each width in `widths`. Relative maxima which + appear at enough length scales, and with sufficiently high SNR, are + accepted. + + Parameters + ---------- + vector : ndarray + 1-D array in which to find the peaks. + widths : float or sequence + Single width or 1-D array-like of widths to use for calculating + the CWT matrix. In general, + this range should cover the expected width of peaks of interest. + wavelet : callable, optional + Should take two parameters and return a 1-D array to convolve + with `vector`. The first parameter determines the number of points + of the returned wavelet array, the second parameter is the scale + (`width`) of the wavelet. Should be normalized and symmetric. + Default is the ricker wavelet. + max_distances : ndarray, optional + At each row, a ridge line is only connected if the relative max at + row[n] is within ``max_distances[n]`` from the relative max at + ``row[n+1]``. Default value is ``widths/4``. + gap_thresh : float, optional + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if there are more + than `gap_thresh` points without connecting a new relative maximum. + Default is the first value of the widths array i.e. widths[0]. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the maximum CWT coefficient + on the largest ridge line. The noise is `noise_perc` th percentile of + datapoints contained within the same ridge line. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + `stats.scoreatpercentile`. Default is 10. + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + + Returns + ------- + peaks_indices : ndarray + Indices of the locations in the `vector` where peaks were found. + The list is sorted. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + + Notes + ----- + This approach was designed for finding sharp peaks among noisy data, + however with proper parameter selection it should function well for + different peak shapes. + + The algorithm is as follows: + 1. Perform a continuous wavelet transform on `vector`, for the supplied + `widths`. This is a convolution of `vector` with `wavelet(width)` for + each width in `widths`. See `cwt`. + 2. Identify "ridge lines" in the cwt matrix. These are relative maxima + at each row, connected across adjacent rows. See identify_ridge_lines + 3. Filter the ridge_lines using filter_ridge_lines. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> xs = np.arange(0, np.pi, 0.05) + >>> data = np.sin(xs) + >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10)) + >>> peakind, xs[peakind], data[peakind] + ([32], array([ 1.6]), array([ 0.9995736])) + + """ + widths = np.atleast_1d(np.asarray(widths)) + + if gap_thresh is None: + gap_thresh = np.ceil(widths[0]) + if max_distances is None: + max_distances = widths / 4.0 + if wavelet is None: + wavelet = _ricker + + cwt_dat = _cwt(vector, wavelet, widths) + ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh) + filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length, + window_size=window_size, min_snr=min_snr, + noise_perc=noise_perc) + max_locs = np.asarray([x[1][0] for x in filtered]) + max_locs.sort() + + return max_locs diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py new file mode 100644 index 0000000000000000000000000000000000000000..addcbe6951f8df093461c47848f8027dfdd406f2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py @@ -0,0 +1,357 @@ +import numpy as np +from scipy.linalg import lstsq +from scipy._lib._util import float_factorial +from scipy.ndimage import convolve1d # type: ignore[attr-defined] +from ._arraytools import axis_slice + + +def savgol_coeffs(window_length, polyorder, deriv=0, delta=1.0, pos=None, + use="conv"): + """Compute the coefficients for a 1-D Savitzky-Golay FIR filter. + + Parameters + ---------- + window_length : int + The length of the filter window (i.e., the number of coefficients). + polyorder : int + The order of the polynomial used to fit the samples. + `polyorder` must be less than `window_length`. + deriv : int, optional + The order of the derivative to compute. This must be a + nonnegative integer. The default is 0, which means to filter + the data without differentiating. + delta : float, optional + The spacing of the samples to which the filter will be applied. + This is only used if deriv > 0. + pos : int or None, optional + If pos is not None, it specifies evaluation position within the + window. The default is the middle of the window. + use : str, optional + Either 'conv' or 'dot'. This argument chooses the order of the + coefficients. The default is 'conv', which means that the + coefficients are ordered to be used in a convolution. With + use='dot', the order is reversed, so the filter is applied by + dotting the coefficients with the data set. + + Returns + ------- + coeffs : 1-D ndarray + The filter coefficients. + + See Also + -------- + savgol_filter + + Notes + ----- + .. versionadded:: 0.14.0 + + References + ---------- + A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by + Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), + pp 1627-1639. + Jianwen Luo, Kui Ying, and Jing Bai. 2005. Savitzky-Golay smoothing and + differentiation filter for even number data. Signal Process. + 85, 7 (July 2005), 1429-1434. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import savgol_coeffs + >>> savgol_coeffs(5, 2) + array([-0.08571429, 0.34285714, 0.48571429, 0.34285714, -0.08571429]) + >>> savgol_coeffs(5, 2, deriv=1) + array([ 2.00000000e-01, 1.00000000e-01, 2.07548111e-16, -1.00000000e-01, + -2.00000000e-01]) + + Note that use='dot' simply reverses the coefficients. + + >>> savgol_coeffs(5, 2, pos=3) + array([ 0.25714286, 0.37142857, 0.34285714, 0.17142857, -0.14285714]) + >>> savgol_coeffs(5, 2, pos=3, use='dot') + array([-0.14285714, 0.17142857, 0.34285714, 0.37142857, 0.25714286]) + >>> savgol_coeffs(4, 2, pos=3, deriv=1, use='dot') + array([0.45, -0.85, -0.65, 1.05]) + + `x` contains data from the parabola x = t**2, sampled at + t = -1, 0, 1, 2, 3. `c` holds the coefficients that will compute the + derivative at the last position. When dotted with `x` the result should + be 6. + + >>> x = np.array([1, 0, 1, 4, 9]) + >>> c = savgol_coeffs(5, 2, pos=4, deriv=1, use='dot') + >>> c.dot(x) + 6.0 + """ + + # An alternative method for finding the coefficients when deriv=0 is + # t = np.arange(window_length) + # unit = (t == pos).astype(int) + # coeffs = np.polyval(np.polyfit(t, unit, polyorder), t) + # The method implemented here is faster. + + # To recreate the table of sample coefficients shown in the chapter on + # the Savitzy-Golay filter in the Numerical Recipes book, use + # window_length = nL + nR + 1 + # pos = nL + 1 + # c = savgol_coeffs(window_length, M, pos=pos, use='dot') + + if polyorder >= window_length: + raise ValueError("polyorder must be less than window_length.") + + halflen, rem = divmod(window_length, 2) + + if pos is None: + if rem == 0: + pos = halflen - 0.5 + else: + pos = halflen + + if not (0 <= pos < window_length): + raise ValueError("pos must be nonnegative and less than " + "window_length.") + + if use not in ['conv', 'dot']: + raise ValueError("`use` must be 'conv' or 'dot'") + + if deriv > polyorder: + coeffs = np.zeros(window_length) + return coeffs + + # Form the design matrix A. The columns of A are powers of the integers + # from -pos to window_length - pos - 1. The powers (i.e., rows) range + # from 0 to polyorder. (That is, A is a vandermonde matrix, but not + # necessarily square.) + x = np.arange(-pos, window_length - pos, dtype=float) + + if use == "conv": + # Reverse so that result can be used in a convolution. + x = x[::-1] + + order = np.arange(polyorder + 1).reshape(-1, 1) + A = x ** order + + # y determines which order derivative is returned. + y = np.zeros(polyorder + 1) + # The coefficient assigned to y[deriv] scales the result to take into + # account the order of the derivative and the sample spacing. + y[deriv] = float_factorial(deriv) / (delta ** deriv) + + # Find the least-squares solution of A*c = y + coeffs, _, _, _ = lstsq(A, y) + + return coeffs + + +def _polyder(p, m): + """Differentiate polynomials represented with coefficients. + + p must be a 1-D or 2-D array. In the 2-D case, each column gives + the coefficients of a polynomial; the first row holds the coefficients + associated with the highest power. m must be a nonnegative integer. + (numpy.polyder doesn't handle the 2-D case.) + """ + + if m == 0: + result = p + else: + n = len(p) + if n <= m: + result = np.zeros_like(p[:1, ...]) + else: + dp = p[:-m].copy() + for k in range(m): + rng = np.arange(n - k - 1, m - k - 1, -1) + dp *= rng.reshape((n - m,) + (1,) * (p.ndim - 1)) + result = dp + return result + + +def _fit_edge(x, window_start, window_stop, interp_start, interp_stop, + axis, polyorder, deriv, delta, y): + """ + Given an N-d array `x` and the specification of a slice of `x` from + `window_start` to `window_stop` along `axis`, create an interpolating + polynomial of each 1-D slice, and evaluate that polynomial in the slice + from `interp_start` to `interp_stop`. Put the result into the + corresponding slice of `y`. + """ + + # Get the edge into a (window_length, -1) array. + x_edge = axis_slice(x, start=window_start, stop=window_stop, axis=axis) + if axis == 0 or axis == -x.ndim: + xx_edge = x_edge + swapped = False + else: + xx_edge = x_edge.swapaxes(axis, 0) + swapped = True + xx_edge = xx_edge.reshape(xx_edge.shape[0], -1) + + # Fit the edges. poly_coeffs has shape (polyorder + 1, -1), + # where '-1' is the same as in xx_edge. + poly_coeffs = np.polyfit(np.arange(0, window_stop - window_start), + xx_edge, polyorder) + + if deriv > 0: + poly_coeffs = _polyder(poly_coeffs, deriv) + + # Compute the interpolated values for the edge. + i = np.arange(interp_start - window_start, interp_stop - window_start) + values = np.polyval(poly_coeffs, i.reshape(-1, 1)) / (delta ** deriv) + + # Now put the values into the appropriate slice of y. + # First reshape values to match y. + shp = list(y.shape) + shp[0], shp[axis] = shp[axis], shp[0] + values = values.reshape(interp_stop - interp_start, *shp[1:]) + if swapped: + values = values.swapaxes(0, axis) + # Get a view of the data to be replaced by values. + y_edge = axis_slice(y, start=interp_start, stop=interp_stop, axis=axis) + y_edge[...] = values + + +def _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y): + """ + Use polynomial interpolation of x at the low and high ends of the axis + to fill in the halflen values in y. + + This function just calls _fit_edge twice, once for each end of the axis. + """ + halflen = window_length // 2 + _fit_edge(x, 0, window_length, 0, halflen, axis, + polyorder, deriv, delta, y) + n = x.shape[axis] + _fit_edge(x, n - window_length, n, n - halflen, n, axis, + polyorder, deriv, delta, y) + + +def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, + axis=-1, mode='interp', cval=0.0): + """ Apply a Savitzky-Golay filter to an array. + + This is a 1-D filter. If `x` has dimension greater than 1, `axis` + determines the axis along which the filter is applied. + + Parameters + ---------- + x : array_like + The data to be filtered. If `x` is not a single or double precision + floating point array, it will be converted to type ``numpy.float64`` + before filtering. + window_length : int + The length of the filter window (i.e., the number of coefficients). + If `mode` is 'interp', `window_length` must be less than or equal + to the size of `x`. + polyorder : int + The order of the polynomial used to fit the samples. + `polyorder` must be less than `window_length`. + deriv : int, optional + The order of the derivative to compute. This must be a + nonnegative integer. The default is 0, which means to filter + the data without differentiating. + delta : float, optional + The spacing of the samples to which the filter will be applied. + This is only used if deriv > 0. Default is 1.0. + axis : int, optional + The axis of the array `x` along which the filter is to be applied. + Default is -1. + mode : str, optional + Must be 'mirror', 'constant', 'nearest', 'wrap' or 'interp'. This + determines the type of extension to use for the padded signal to + which the filter is applied. When `mode` is 'constant', the padding + value is given by `cval`. See the Notes for more details on 'mirror', + 'constant', 'wrap', and 'nearest'. + When the 'interp' mode is selected (the default), no extension + is used. Instead, a degree `polyorder` polynomial is fit to the + last `window_length` values of the edges, and this polynomial is + used to evaluate the last `window_length // 2` output values. + cval : scalar, optional + Value to fill past the edges of the input if `mode` is 'constant'. + Default is 0.0. + + Returns + ------- + y : ndarray, same shape as `x` + The filtered data. + + See Also + -------- + savgol_coeffs + + Notes + ----- + Details on the `mode` options: + + 'mirror': + Repeats the values at the edges in reverse order. The value + closest to the edge is not included. + 'nearest': + The extension contains the nearest input value. + 'constant': + The extension contains the value given by the `cval` argument. + 'wrap': + The extension contains the values from the other end of the array. + + For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and + `window_length` is 7, the following shows the extended data for + the various `mode` options (assuming `cval` is 0):: + + mode | Ext | Input | Ext + -----------+---------+------------------------+--------- + 'mirror' | 4 3 2 | 1 2 3 4 5 6 7 8 | 7 6 5 + 'nearest' | 1 1 1 | 1 2 3 4 5 6 7 8 | 8 8 8 + 'constant' | 0 0 0 | 1 2 3 4 5 6 7 8 | 0 0 0 + 'wrap' | 6 7 8 | 1 2 3 4 5 6 7 8 | 1 2 3 + + .. versionadded:: 0.14.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import savgol_filter + >>> np.set_printoptions(precision=2) # For compact display. + >>> x = np.array([2, 2, 5, 2, 1, 0, 1, 4, 9]) + + Filter with a window length of 5 and a degree 2 polynomial. Use + the defaults for all other parameters. + + >>> savgol_filter(x, 5, 2) + array([1.66, 3.17, 3.54, 2.86, 0.66, 0.17, 1. , 4. , 9. ]) + + Note that the last five values in x are samples of a parabola, so + when mode='interp' (the default) is used with polyorder=2, the last + three values are unchanged. Compare that to, for example, + `mode='nearest'`: + + >>> savgol_filter(x, 5, 2, mode='nearest') + array([1.74, 3.03, 3.54, 2.86, 0.66, 0.17, 1. , 4.6 , 7.97]) + + """ + if mode not in ["mirror", "constant", "nearest", "interp", "wrap"]: + raise ValueError("mode must be 'mirror', 'constant', 'nearest' " + "'wrap' or 'interp'.") + + x = np.asarray(x) + # Ensure that x is either single or double precision floating point. + if x.dtype != np.float64 and x.dtype != np.float32: + x = x.astype(np.float64) + + coeffs = savgol_coeffs(window_length, polyorder, deriv=deriv, delta=delta) + + if mode == "interp": + if window_length > x.shape[axis]: + raise ValueError("If mode is 'interp', window_length must be less " + "than or equal to the size of x.") + + # Do not pad. Instead, for the elements within `window_length // 2` + # of the ends of the sequence, use the polynomial that is fitted to + # the last `window_length` elements. + y = convolve1d(x, coeffs, axis=axis, mode="constant") + _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y) + else: + # Any mode other than 'interp' is passed on to ndimage.convolve1d. + y = convolve1d(x, coeffs, axis=axis, mode=mode, cval=cval) + + return y diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py new file mode 100644 index 0000000000000000000000000000000000000000..6c87718dea8b777d23c77d6147b4ca6368204637 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py @@ -0,0 +1,1738 @@ +"""Implementation of an FFT-based Short-time Fourier Transform. """ + +# Implementation Notes for this file (as of 2023-07) +# -------------------------------------------------- +# * MyPy version 1.1.1 does not seem to support decorated property methods +# properly. Hence, applying ``@property`` to methods decorated with `@cache`` +# (as tried with the ``lower_border_end`` method) causes a mypy error when +# accessing it as an index (e.g., ``SFT.lower_border_end[0]``). +# * Since the method `stft` and `istft` have identical names as the legacy +# functions in the signal module, referencing them as HTML link in the +# docstrings has to be done by an explicit `~ShortTimeFFT.stft` instead of an +# ambiguous `stft` (The ``~`` hides the class / module name). +# * The HTML documentation currently renders each method/property on a separate +# page without reference to the parent class. Thus, a link to `ShortTimeFFT` +# was added to the "See Also" section of each method/property. These links +# can be removed, when SciPy updates ``pydata-sphinx-theme`` to >= 0.13.3 +# (currently 0.9). Consult Issue 18512 and PR 16660 for further details. +# + +# Provides typing union operator ``|`` in Python 3.9: +# Linter does not allow to import ``Generator`` from ``typing`` module: +from collections.abc import Generator, Callable +from functools import cache, lru_cache, partial +from typing import get_args, Literal + +import numpy as np + +import scipy.fft as fft_lib +from scipy.signal import detrend +from scipy.signal.windows import get_window + +__all__ = ['ShortTimeFFT'] + + +#: Allowed values for parameter `padding` of method `ShortTimeFFT.stft()`: +PAD_TYPE = Literal['zeros', 'edge', 'even', 'odd'] + +#: Allowed values for property `ShortTimeFFT.fft_mode`: +FFT_MODE_TYPE = Literal['twosided', 'centered', 'onesided', 'onesided2X'] + + +def _calc_dual_canonical_window(win: np.ndarray, hop: int) -> np.ndarray: + """Calculate canonical dual window for 1d window `win` and a time step + of `hop` samples. + + A ``ValueError`` is raised, if the inversion fails. + + This is a separate function not a method, since it is also used in the + class method ``ShortTimeFFT.from_dual()``. + """ + if hop > len(win): + raise ValueError(f"{hop=} is larger than window length of {len(win)}" + + " => STFT not invertible!") + if issubclass(win.dtype.type, np.integer): + raise ValueError("Parameter 'win' cannot be of integer type, but " + + f"{win.dtype=} => STFT not invertible!") + # The calculation of `relative_resolution` does not work for ints. + # Furthermore, `win / DD` casts the integers away, thus an implicit + # cast is avoided, which can always cause confusion when using 32-Bit + # floats. + + w2 = win.real**2 + win.imag**2 # win*win.conj() does not ensure w2 is real + DD = w2.copy() + for k_ in range(hop, len(win), hop): + DD[k_:] += w2[:-k_] + DD[:-k_] += w2[k_:] + + # check DD > 0: + relative_resolution = np.finfo(win.dtype).resolution * max(DD) + if not np.all(DD >= relative_resolution): + raise ValueError("Short-time Fourier Transform not invertible!") + + return win / DD + + +# noinspection PyShadowingNames +class ShortTimeFFT: + r"""Provide a parametrized discrete Short-time Fourier transform (stft) + and its inverse (istft). + + .. currentmodule:: scipy.signal.ShortTimeFFT + + The `~ShortTimeFFT.stft` calculates sequential FFTs by sliding a + window (`win`) over an input signal by `hop` increments. It can be used to + quantify the change of the spectrum over time. + + The `~ShortTimeFFT.stft` is represented by a complex-valued matrix S[q,p] + where the p-th column represents an FFT with the window centered at the + time t[p] = p * `delta_t` = p * `hop` * `T` where `T` is the sampling + interval of the input signal. The q-th row represents the values at the + frequency f[q] = q * `delta_f` with `delta_f` = 1 / (`mfft` * `T`) being + the bin width of the FFT. + + The inverse STFT `~ShortTimeFFT.istft` is calculated by reversing the steps + of the STFT: Take the IFFT of the p-th slice of S[q,p] and multiply the + result with the so-called dual window (see `dual_win`). Shift the result by + p * `delta_t` and add the result to previous shifted results to reconstruct + the signal. If only the dual window is known and the STFT is invertible, + `from_dual` can be used to instantiate this class. + + Due to the convention of time t = 0 being at the first sample of the input + signal, the STFT values typically have negative time slots. Hence, + negative indexes like `p_min` or `k_min` do not indicate counting + backwards from an array's end like in standard Python indexing but being + left of t = 0. + + More detailed information can be found in the :ref:`tutorial_stft` section + of the :ref:`user_guide`. + + Note that all parameters of the initializer, except `scale_to` (which uses + `scaling`) have identical named attributes. + + Parameters + ---------- + win : np.ndarray + The window must be a real- or complex-valued 1d array. + hop : int + The increment in samples, by which the window is shifted in each step. + fs : float + Sampling frequency of input signal and window. Its relation to the + sampling interval `T` is ``T = 1 / fs``. + fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X' + Mode of FFT to be used (default 'onesided'). + See property `fft_mode` for details. + mfft: int | None + Length of the FFT used, if a zero padded FFT is desired. + If ``None`` (default), the length of the window `win` is used. + dual_win : np.ndarray | None + The dual window of `win`. If set to ``None``, it is calculated if + needed. + scale_to : 'magnitude', 'psd' | None + If not ``None`` (default) the window function is scaled, so each STFT + column represents either a 'magnitude' or a power spectral density + ('psd') spectrum. This parameter sets the property `scaling` to the + same value. See method `scale_to` for details. + phase_shift : int | None + If set, add a linear phase `phase_shift` / `mfft` * `f` to each + frequency `f`. The default value 0 ensures that there is no phase shift + on the zeroth slice (in which t=0 is centered). See property + `phase_shift` for more details. + + Examples + -------- + The following example shows the magnitude of the STFT of a sine with + varying frequency :math:`f_i(t)` (marked by a red dashed line in the plot): + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import ShortTimeFFT + >>> from scipy.signal.windows import gaussian + ... + >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal + >>> t_x = np.arange(N) * T_x # time indexes for signal + >>> f_i = 1 * np.arctan((t_x - t_x[N // 2]) / 2) + 5 # varying frequency + >>> x = np.sin(2*np.pi*np.cumsum(f_i)*T_x) # the signal + + The utilized Gaussian window is 50 samples or 2.5 s long. The parameter + ``mfft=200`` in `ShortTimeFFT` causes the spectrum to be oversampled + by a factor of 4: + + >>> g_std = 8 # standard deviation for Gaussian window in samples + >>> w = gaussian(50, std=g_std, sym=True) # symmetric Gaussian window + >>> SFT = ShortTimeFFT(w, hop=10, fs=1/T_x, mfft=200, scale_to='magnitude') + >>> Sx = SFT.stft(x) # perform the STFT + + In the plot, the time extent of the signal `x` is marked by vertical dashed + lines. Note that the SFT produces values outside the time range of `x`. The + shaded areas on the left and the right indicate border effects caused + by the window slices in that area not fully being inside time range of + `x`: + + >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit + >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot + >>> ax1.set_title(rf"STFT ({SFT.m_num*SFT.T:g}$\,s$ Gaussian window, " + + ... rf"$\sigma_t={g_std*SFT.T}\,$s)") + >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " + + ... rf"$\Delta t = {SFT.delta_t:g}\,$s)", + ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " + + ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)", + ... xlim=(t_lo, t_hi)) + ... + >>> im1 = ax1.imshow(abs(Sx), origin='lower', aspect='auto', + ... extent=SFT.extent(N), cmap='viridis') + >>> ax1.plot(t_x, f_i, 'r--', alpha=.5, label='$f_i(t)$') + >>> fig1.colorbar(im1, label="Magnitude $|S_x(t, f)|$") + ... + >>> # Shade areas where window slices stick out to the side: + >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T), + ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]: + ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.2) + >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line: + ... ax1.axvline(t_, color='y', linestyle='--', alpha=0.5) + >>> ax1.legend() + >>> fig1.tight_layout() + >>> plt.show() + + Reconstructing the signal with the `~ShortTimeFFT.istft` is + straightforward, but note that the length of `x1` should be specified, + since the SFT length increases in `hop` steps: + + >>> SFT.invertible # check if invertible + True + >>> x1 = SFT.istft(Sx, k1=N) + >>> np.allclose(x, x1) + True + + It is possible to calculate the SFT of signal parts: + + >>> N2 = SFT.nearest_k_p(N // 2) + >>> Sx0 = SFT.stft(x[:N2]) + >>> Sx1 = SFT.stft(x[N2:]) + + When assembling sequential STFT parts together, the overlap needs to be + considered: + + >>> p0_ub = SFT.upper_border_begin(N2)[1] - SFT.p_min + >>> p1_le = SFT.lower_border_end[1] - SFT.p_min + >>> Sx01 = np.hstack((Sx0[:, :p0_ub], + ... Sx0[:, p0_ub:] + Sx1[:, :p1_le], + ... Sx1[:, p1_le:])) + >>> np.allclose(Sx01, Sx) # Compare with SFT of complete signal + True + + It is also possible to calculate the `itsft` for signal parts: + + >>> y_p = SFT.istft(Sx, N//3, N//2) + >>> np.allclose(y_p, x[N//3:N//2]) + True + + """ + # immutable attributes (only have getters but no setters): + _win: np.ndarray # window + _dual_win: np.ndarray | None = None # canonical dual window + _hop: int # Step of STFT in number of samples + + # mutable attributes: + _fs: float # sampling frequency of input signal and window + _fft_mode: FFT_MODE_TYPE = 'onesided' # Mode of FFT to use + _mfft: int # length of FFT used - defaults to len(win) + _scaling: Literal['magnitude', 'psd'] | None = None # Scaling of _win + _phase_shift: int | None # amount to shift phase of FFT in samples + + # attributes for caching calculated values: + _fac_mag: float | None = None + _fac_psd: float | None = None + _lower_border_end: tuple[int, int] | None = None + + def __init__(self, win: np.ndarray, hop: int, fs: float, *, + fft_mode: FFT_MODE_TYPE = 'onesided', + mfft: int | None = None, + dual_win: np.ndarray | None = None, + scale_to: Literal['magnitude', 'psd'] | None = None, + phase_shift: int | None = 0): + if not (win.ndim == 1 and win.size > 0): + raise ValueError(f"Parameter win must be 1d, but {win.shape=}!") + if not all(np.isfinite(win)): + raise ValueError("Parameter win must have finite entries!") + if not (hop >= 1 and isinstance(hop, int)): + raise ValueError(f"Parameter {hop=} is not an integer >= 1!") + self._win, self._hop, self.fs = win, hop, fs + + self.mfft = len(win) if mfft is None else mfft + + if dual_win is not None: + if dual_win.shape != win.shape: + raise ValueError(f"{dual_win.shape=} must equal {win.shape=}!") + if not all(np.isfinite(dual_win)): + raise ValueError("Parameter dual_win must be a finite array!") + self._dual_win = dual_win # needs to be set before scaling + + if scale_to is not None: # needs to be set before fft_mode + self.scale_to(scale_to) + + self.fft_mode, self.phase_shift = fft_mode, phase_shift + + @classmethod + def from_dual(cls, dual_win: np.ndarray, hop: int, fs: float, *, + fft_mode: FFT_MODE_TYPE = 'onesided', + mfft: int | None = None, + scale_to: Literal['magnitude', 'psd'] | None = None, + phase_shift: int | None = 0): + r"""Instantiate a `ShortTimeFFT` by only providing a dual window. + + If an STFT is invertible, it is possible to calculate the window `win` + from a given dual window `dual_win`. All other parameters have the + same meaning as in the initializer of `ShortTimeFFT`. + + As explained in the :ref:`tutorial_stft` section of the + :ref:`user_guide`, an invertible STFT can be interpreted as series + expansion of time-shifted and frequency modulated dual windows. E.g., + the series coefficient S[q,p] belongs to the term, which shifted + `dual_win` by p * `delta_t` and multiplied it by + exp( 2 * j * pi * t * q * `delta_f`). + + + Examples + -------- + The following example discusses decomposing a signal into time- and + frequency-shifted Gaussians. A Gaussian with standard deviation of + one made up of 51 samples will be used: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import ShortTimeFFT + >>> from scipy.signal.windows import gaussian + ... + >>> T, N = 0.1, 51 + >>> d_win = gaussian(N, std=1/T, sym=True) # symmetric Gaussian window + >>> t = T * (np.arange(N) - N//2) + ... + >>> fg1, ax1 = plt.subplots() + >>> ax1.set_title(r"Dual Window: Gaussian with $\sigma_t=1$") + >>> ax1.set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)", + ... xlim=(t[0], t[-1]), ylim=(0, 1.1*max(d_win))) + >>> ax1.plot(t, d_win, 'C0-') + + The following plot with the overlap of 41, 11 and 2 samples show how + the `hop` interval affects the shape of the window `win`: + + >>> fig2, axx = plt.subplots(3, 1, sharex='all') + ... + >>> axx[0].set_title(r"Windows for hop$\in\{10, 40, 49\}$") + >>> for c_, h_ in enumerate([10, 40, 49]): + ... SFT = ShortTimeFFT.from_dual(d_win, h_, 1/T) + ... axx[c_].plot(t + h_ * T, SFT.win, 'k--', alpha=.3, label=None) + ... axx[c_].plot(t - h_ * T, SFT.win, 'k:', alpha=.3, label=None) + ... axx[c_].plot(t, SFT.win, f'C{c_+1}', + ... label=r"$\Delta t=%0.1f\,$s" % SFT.delta_t) + ... axx[c_].set_ylim(0, 1.1*max(SFT.win)) + ... axx[c_].legend(loc='center') + >>> axx[-1].set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)", + ... xlim=(t[0], t[-1])) + >>> plt.show() + + Beside the window `win` centered at t = 0 the previous (t = -`delta_t`) + and following window (t = `delta_t`) are depicted. It can be seen that + for small `hop` intervals, the window is compact and smooth, having a + good time-frequency concentration in the STFT. For the large `hop` + interval of 4.9 s, the window has small values around t = 0, which are + not covered by the overlap of the adjacent windows, which could lead to + numeric inaccuracies. Furthermore, the peaky shape at the beginning and + the end of the window points to a higher bandwidth, resulting in a + poorer time-frequency resolution of the STFT. + Hence, the choice of the `hop` interval will be a compromise between + a time-frequency resolution and memory requirements demanded by small + `hop` sizes. + + See Also + -------- + from_window: Create instance by wrapping `get_window`. + ShortTimeFFT: Create instance using standard initializer. + """ + win = _calc_dual_canonical_window(dual_win, hop) + return cls(win=win, hop=hop, fs=fs, fft_mode=fft_mode, mfft=mfft, + dual_win=dual_win, scale_to=scale_to, + phase_shift=phase_shift) + + @classmethod + def from_window(cls, win_param: str | tuple | float, + fs: float, nperseg: int, noverlap: int, *, + symmetric_win: bool = False, + fft_mode: FFT_MODE_TYPE = 'onesided', + mfft: int | None = None, + scale_to: Literal['magnitude', 'psd'] | None = None, + phase_shift: int | None = 0): + """Instantiate `ShortTimeFFT` by using `get_window`. + + The method `get_window` is used to create a window of length + `nperseg`. The parameter names `noverlap`, and `nperseg` are used here, + since they more inline with other classical STFT libraries. + + Parameters + ---------- + win_param: Union[str, tuple, float], + Parameters passed to `get_window`. For windows with no parameters, + it may be a string (e.g., ``'hann'``), for parametrized windows a + tuple, (e.g., ``('gaussian', 2.)``) or a single float specifying + the shape parameter of a kaiser window (i.e. ``4.`` and + ``('kaiser', 4.)`` are equal. See `get_window` for more details. + fs : float + Sampling frequency of input signal. Its relation to the + sampling interval `T` is ``T = 1 / fs``. + nperseg: int + Window length in samples, which corresponds to the `m_num`. + noverlap: int + Window overlap in samples. It relates to the `hop` increment by + ``hop = npsereg - noverlap``. + symmetric_win: bool + If ``True`` then a symmetric window is generated, else a periodic + window is generated (default). Though symmetric windows seem for + most applications to be more sensible, the default of a periodic + windows was chosen to correspond to the default of `get_window`. + fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X' + Mode of FFT to be used (default 'onesided'). + See property `fft_mode` for details. + mfft: int | None + Length of the FFT used, if a zero padded FFT is desired. + If ``None`` (default), the length of the window `win` is used. + scale_to : 'magnitude', 'psd' | None + If not ``None`` (default) the window function is scaled, so each + STFT column represents either a 'magnitude' or a power spectral + density ('psd') spectrum. This parameter sets the property + `scaling` to the same value. See method `scale_to` for details. + phase_shift : int | None + If set, add a linear phase `phase_shift` / `mfft` * `f` to each + frequency `f`. The default value 0 ensures that there is no phase + shift on the zeroth slice (in which t=0 is centered). See property + `phase_shift` for more details. + + Examples + -------- + The following instances ``SFT0`` and ``SFT1`` are equivalent: + + >>> from scipy.signal import ShortTimeFFT, get_window + >>> nperseg = 9 # window length + >>> w = get_window(('gaussian', 2.), nperseg) + >>> fs = 128 # sampling frequency + >>> hop = 3 # increment of STFT time slice + >>> SFT0 = ShortTimeFFT(w, hop, fs=fs) + >>> SFT1 = ShortTimeFFT.from_window(('gaussian', 2.), fs, nperseg, + ... noverlap=nperseg-hop) + + See Also + -------- + scipy.signal.get_window: Return a window of a given length and type. + from_dual: Create instance using dual window. + ShortTimeFFT: Create instance using standard initializer. + """ + win = get_window(win_param, nperseg, fftbins=not symmetric_win) + return cls(win, hop=nperseg-noverlap, fs=fs, fft_mode=fft_mode, + mfft=mfft, scale_to=scale_to, phase_shift=phase_shift) + + @property + def win(self) -> np.ndarray: + """Window function as real- or complex-valued 1d array. + + This attribute is read only, since `dual_win` depends on it. + + See Also + -------- + dual_win: Canonical dual window. + m_num: Number of samples in window `win`. + m_num_mid: Center index of window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + hop: ime increment in signal samples for sliding window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return self._win + + @property + def hop(self) -> int: + """Time increment in signal samples for sliding window. + + This attribute is read only, since `dual_win` depends on it. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + m_num: Number of samples in window `win`. + m_num_mid: Center index of window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + T: Sampling interval of input signal and of the window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return self._hop + + @property + def T(self) -> float: + """Sampling interval of input signal and of the window. + + A ``ValueError`` is raised if it is set to a non-positive value. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + fs: Sampling frequency (being ``1/T``) + t: Times of STFT for an input signal with `n` samples. + ShortTimeFFT: Class this property belongs to. + """ + return 1 / self._fs + + @T.setter + def T(self, v: float): + """Sampling interval of input signal and of the window. + + A ``ValueError`` is raised if it is set to a non-positive value. + """ + if not (v > 0): + raise ValueError(f"Sampling interval T={v} must be positive!") + self._fs = 1 / v + + @property + def fs(self) -> float: + """Sampling frequency of input signal and of the window. + + The sampling frequency is the inverse of the sampling interval `T`. + A ``ValueError`` is raised if it is set to a non-positive value. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + T: Sampling interval of input signal and of the window (``1/fs``). + ShortTimeFFT: Class this property belongs to. + """ + return self._fs + + @fs.setter + def fs(self, v: float): + """Sampling frequency of input signal and of the window. + + The sampling frequency is the inverse of the sampling interval `T`. + A ``ValueError`` is raised if it is set to a non-positive value. + """ + if not (v > 0): + raise ValueError(f"Sampling frequency fs={v} must be positive!") + self._fs = v + + @property + def fft_mode(self) -> FFT_MODE_TYPE: + """Mode of utilized FFT ('twosided', 'centered', 'onesided' or + 'onesided2X'). + + It can have the following values: + + 'twosided': + Two-sided FFT, where values for the negative frequencies are in + upper half of the array. Corresponds to :func:`~scipy.fft.fft()`. + 'centered': + Two-sided FFT with the values being ordered along monotonically + increasing frequencies. Corresponds to applying + :func:`~scipy.fft.fftshift()` to :func:`~scipy.fft.fft()`. + 'onesided': + Calculates only values for non-negative frequency values. + Corresponds to :func:`~scipy.fft.rfft()`. + 'onesided2X': + Like `onesided`, but the non-zero frequencies are doubled if + `scaling` is set to 'magnitude' or multiplied by ``sqrt(2)`` if + set to 'psd'. If `scaling` is ``None``, setting `fft_mode` to + `onesided2X` is not allowed. + If the FFT length `mfft` is even, the last FFT value is not paired, + and thus it is not scaled. + + Note that `onesided` and `onesided2X` do not work for complex-valued signals or + complex-valued windows. Furthermore, the frequency values can be obtained by + reading the `f` property, and the number of samples by accessing the `f_pts` + property. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f: Frequencies values of the STFT. + f_pts: Width of the frequency bins of the STFT. + onesided_fft: True if a one-sided FFT is used. + scaling: Normalization applied to the window function + ShortTimeFFT: Class this property belongs to. + """ + return self._fft_mode + + @fft_mode.setter + def fft_mode(self, t: FFT_MODE_TYPE): + """Set mode of FFT. + + Allowed values are 'twosided', 'centered', 'onesided', 'onesided2X'. + See the property `fft_mode` for more details. + """ + if t not in (fft_mode_types := get_args(FFT_MODE_TYPE)): + raise ValueError(f"fft_mode='{t}' not in {fft_mode_types}!") + + if t in {'onesided', 'onesided2X'} and np.iscomplexobj(self.win): + raise ValueError(f"One-sided spectra, i.e., fft_mode='{t}', " + + "are not allowed for complex-valued windows!") + + if t == 'onesided2X' and self.scaling is None: + raise ValueError(f"For scaling is None, fft_mode='{t}' is invalid!" + "Do scale_to('psd') or scale_to('magnitude')!") + self._fft_mode = t + + @property + def mfft(self) -> int: + """Length of input for the FFT used - may be larger than window + length `m_num`. + + If not set, `mfft` defaults to the window length `m_num`. + + See Also + -------- + f_pts: Number of points along the frequency axis. + f: Frequencies values of the STFT. + m_num: Number of samples in window `win`. + ShortTimeFFT: Class this property belongs to. + """ + return self._mfft + + @mfft.setter + def mfft(self, n_: int): + """Setter for the length of FFT utilized. + + See the property `mfft` for further details. + """ + if not (n_ >= self.m_num): + raise ValueError(f"Attribute mfft={n_} needs to be at least the " + + f"window length m_num={self.m_num}!") + self._mfft = n_ + + @property + def scaling(self) -> Literal['magnitude', 'psd'] | None: + """Normalization applied to the window function + ('magnitude', 'psd' or ``None``). + + If not ``None``, the FFTs can be either interpreted as a magnitude or + a power spectral density spectrum. + + The window function can be scaled by calling the `scale_to` method, + or it is set by the initializer parameter ``scale_to``. + + See Also + -------- + fac_magnitude: Scaling factor for to a magnitude spectrum. + fac_psd: Scaling factor for to a power spectral density spectrum. + fft_mode: Mode of utilized FFT + scale_to: Scale window to obtain 'magnitude' or 'psd' scaling. + ShortTimeFFT: Class this property belongs to. + """ + return self._scaling + + def scale_to(self, scaling: Literal['magnitude', 'psd']): + """Scale window to obtain 'magnitude' or 'psd' scaling for the STFT. + + The window of a 'magnitude' spectrum has an integral of one, i.e., unit + area for non-negative windows. This ensures that absolute the values of + spectrum does not change if the length of the window changes (given + the input signal is stationary). + + To represent the power spectral density ('psd') for varying length + windows the area of the absolute square of the window needs to be + unity. + + The `scaling` property shows the current scaling. The properties + `fac_magnitude` and `fac_psd` show the scaling factors required to + scale the STFT values to a magnitude or a psd spectrum. + + This method is called, if the initializer parameter `scale_to` is set. + + See Also + -------- + fac_magnitude: Scaling factor for to a magnitude spectrum. + fac_psd: Scaling factor for to a power spectral density spectrum. + fft_mode: Mode of utilized FFT + scaling: Normalization applied to the window function. + ShortTimeFFT: Class this method belongs to. + """ + if scaling not in (scaling_values := {'magnitude', 'psd'}): + raise ValueError(f"{scaling=} not in {scaling_values}!") + if self._scaling == scaling: # do nothing + return + + s_fac = self.fac_psd if scaling == 'psd' else self.fac_magnitude + self._win = self._win * s_fac + if self._dual_win is not None: + self._dual_win = self._dual_win / s_fac + self._fac_mag, self._fac_psd = None, None # reset scaling factors + self._scaling = scaling + + @property + def phase_shift(self) -> int | None: + """If set, add linear phase `phase_shift` / `mfft` * `f` to each FFT + slice of frequency `f`. + + Shifting (more precisely `rolling`) an `mfft`-point FFT input by + `phase_shift` samples results in a multiplication of the output by + ``np.exp(2j*np.pi*q*phase_shift/mfft)`` at the frequency q * `delta_f`. + + The default value 0 ensures that there is no phase shift on the + zeroth slice (in which t=0 is centered). + No phase shift (``phase_shift is None``) is equivalent to + ``phase_shift = -mfft//2``. In this case slices are not shifted + before calculating the FFT. + + The absolute value of `phase_shift` is limited to be less than `mfft`. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f: Frequencies values of the STFT. + mfft: Length of input for the FFT used + ShortTimeFFT: Class this property belongs to. + """ + return self._phase_shift + + @phase_shift.setter + def phase_shift(self, v: int | None): + """The absolute value of the phase shift needs to be less than mfft + samples. + + See the `phase_shift` getter method for more details. + """ + if v is None: + self._phase_shift = v + return + if not isinstance(v, int): + raise ValueError(f"phase_shift={v} has the unit samples. Hence " + + "it needs to be an int or it may be None!") + if not (-self.mfft < v < self.mfft): + raise ValueError("-mfft < phase_shift < mfft does not hold " + + f"for mfft={self.mfft}, phase_shift={v}!") + self._phase_shift = v + + def _x_slices(self, x: np.ndarray, k_off: int, p0: int, p1: int, + padding: PAD_TYPE) -> Generator[np.ndarray, None, None]: + """Generate signal slices along last axis of `x`. + + This method is only used by `stft_detrend`. The parameters are + described in `~ShortTimeFFT.stft`. + """ + if padding not in (padding_types := get_args(PAD_TYPE)): + raise ValueError(f"Parameter {padding=} not in {padding_types}!") + pad_kws: dict[str, dict] = { # possible keywords to pass to np.pad: + 'zeros': dict(mode='constant', constant_values=(0, 0)), + 'edge': dict(mode='edge'), + 'even': dict(mode='reflect', reflect_type='even'), + 'odd': dict(mode='reflect', reflect_type='odd'), + } # typing of pad_kws is needed to make mypy happy + + n, n1 = x.shape[-1], (p1 - p0) * self.hop + k0 = p0 * self.hop - self.m_num_mid + k_off # start sample + k1 = k0 + n1 + self.m_num # end sample + + i0, i1 = max(k0, 0), min(k1, n) # indexes to shorten x + # dimensions for padding x: + pad_width = [(0, 0)] * (x.ndim-1) + [(-min(k0, 0), max(k1 - n, 0))] + + x1 = np.pad(x[..., i0:i1], pad_width, **pad_kws[padding]) + for k_ in range(0, n1, self.hop): + yield x1[..., k_:k_ + self.m_num] + + def stft(self, x: np.ndarray, p0: int | None = None, + p1: int | None = None, *, k_offset: int = 0, + padding: PAD_TYPE = 'zeros', axis: int = -1) \ + -> np.ndarray: + """Perform the short-time Fourier transform. + + A two-dimensional matrix with ``p1-p0`` columns is calculated. + The `f_pts` rows represent value at the frequencies `f`. The q-th + column of the windowed FFT with the window `win` is centered at t[q]. + The columns represent the values at the frequencies `f`. + + Parameters + ---------- + x + The input signal as real or complex valued array. For complex values, the + property `fft_mode` must be set to 'twosided' or 'centered'. + p0 + The first element of the range of slices to calculate. If ``None`` + then it is set to :attr:`p_min`, which is the smallest possible + slice. + p1 + The end of the array. If ``None`` then `p_max(n)` is used. + k_offset + Index of first sample (t = 0) in `x`. + padding + Kind of values which are added, when the sliding window sticks out + on either the lower or upper end of the input `x`. Zeros are added + if the default 'zeros' is set. For 'edge' either the first or the + last value of `x` is used. 'even' pads by reflecting the + signal on the first or last sample and 'odd' additionally + multiplies it with -1. + axis + The axis of `x` over which to compute the STFT. + If not given, the last axis is used. + + Returns + ------- + S + A complex array is returned with the dimension always being larger + by one than of `x`. The last axis always represent the time slices + of the STFT. `axis` defines the frequency axis (default second to + last). E.g., for a one-dimensional `x`, a complex 2d array is + returned, with axis 0 representing frequency and axis 1 the time + slices. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + delta_t: Time increment of STFT + f: Frequencies values of the STFT. + invertible: Check if STFT is invertible. + :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform. + p_range: Determine and validate slice index range. + stft_detrend: STFT with detrended segments. + t: Times of STFT for an input signal with `n` samples. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + return self.stft_detrend(x, None, p0, p1, k_offset=k_offset, + padding=padding, axis=axis) + + def stft_detrend(self, x: np.ndarray, + detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None, # noqa: E501 + p0: int | None = None, p1: int | None = None, *, + k_offset: int = 0, padding: PAD_TYPE = 'zeros', + axis: int = -1) \ + -> np.ndarray: + """Short-time Fourier transform with a trend being subtracted from each + segment beforehand. + + If `detr` is set to 'constant', the mean is subtracted, if set to + "linear", the linear trend is removed. This is achieved by calling + :func:`scipy.signal.detrend`. If `detr` is a function, `detr` is + applied to each segment. + All other parameters have the same meaning as in `~ShortTimeFFT.stft`. + + Note that due to the detrending, the original signal cannot be + reconstructed by the `~ShortTimeFFT.istft`. + + See Also + -------- + invertible: Check if STFT is invertible. + :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform. + :meth:`~ShortTimeFFT.stft`: Short-time Fourier transform + (without detrending). + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + if self.onesided_fft and np.iscomplexobj(x): + raise ValueError(f"Complex-valued `x` not allowed for {self.fft_mode=}'! " + "Set property `fft_mode` to 'twosided' or 'centered'.") + if isinstance(detr, str): + detr = partial(detrend, type=detr) + elif not (detr is None or callable(detr)): + raise ValueError(f"Parameter {detr=} is not a str, function or " + + "None!") + n = x.shape[axis] + if not (n >= (m2p := self.m_num-self.m_num_mid)): + e_str = f'{len(x)=}' if x.ndim == 1 else f'of {axis=} of {x.shape}' + raise ValueError(f"{e_str} must be >= ceil(m_num/2) = {m2p}!") + + if x.ndim > 1: # motivated by the NumPy broadcasting mechanisms: + x = np.moveaxis(x, axis, -1) + # determine slice index range: + p0, p1 = self.p_range(n, p0, p1) + S_shape_1d = (self.f_pts, p1 - p0) + S_shape = x.shape[:-1] + S_shape_1d if x.ndim > 1 else S_shape_1d + S = np.zeros(S_shape, dtype=complex) + for p_, x_ in enumerate(self._x_slices(x, k_offset, p0, p1, padding)): + if detr is not None: + x_ = detr(x_) + S[..., :, p_] = self._fft_func(x_ * self.win.conj()) + if x.ndim > 1: + return np.moveaxis(S, -2, axis if axis >= 0 else axis-1) + return S + + def spectrogram(self, x: np.ndarray, y: np.ndarray | None = None, + detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None = None, # noqa: E501 + *, + p0: int | None = None, p1: int | None = None, + k_offset: int = 0, padding: PAD_TYPE = 'zeros', + axis: int = -1) \ + -> np.ndarray: + r"""Calculate spectrogram or cross-spectrogram. + + The spectrogram is the absolute square of the STFT, i.e., it is + ``abs(S[q,p])**2`` for given ``S[q,p]`` and thus is always + non-negative. + For two STFTs ``Sx[q,p], Sy[q,p]``, the cross-spectrogram is defined + as ``Sx[q,p] * np.conj(Sy[q,p])`` and is complex-valued. + This is a convenience function for calling `~ShortTimeFFT.stft` / + `stft_detrend`, hence all parameters are discussed there. If `y` is not + ``None`` it needs to have the same shape as `x`. + + Examples + -------- + The following example shows the spectrogram of a square wave with + varying frequency :math:`f_i(t)` (marked by a green dashed line in the + plot) sampled with 20 Hz: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal import square, ShortTimeFFT + >>> from scipy.signal.windows import gaussian + ... + >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal + >>> t_x = np.arange(N) * T_x # time indexes for signal + >>> f_i = 5e-3*(t_x - t_x[N // 3])**2 + 1 # varying frequency + >>> x = square(2*np.pi*np.cumsum(f_i)*T_x) # the signal + + The utilized Gaussian window is 50 samples or 2.5 s long. The + parameter ``mfft=800`` (oversampling factor 16) and the `hop` interval + of 2 in `ShortTimeFFT` was chosen to produce a sufficient number of + points: + + >>> g_std = 12 # standard deviation for Gaussian window in samples + >>> win = gaussian(50, std=g_std, sym=True) # symmetric Gaussian wind. + >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T_x, mfft=800, scale_to='psd') + >>> Sx2 = SFT.spectrogram(x) # calculate absolute square of STFT + + The plot's colormap is logarithmically scaled as the power spectral + density is in dB. The time extent of the signal `x` is marked by + vertical dashed lines and the shaded areas mark the presence of border + effects: + + >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit + >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot + >>> ax1.set_title(rf"Spectrogram ({SFT.m_num*SFT.T:g}$\,s$ Gaussian " + + ... rf"window, $\sigma_t={g_std*SFT.T:g}\,$s)") + >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " + + ... rf"$\Delta t = {SFT.delta_t:g}\,$s)", + ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " + + ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)", + ... xlim=(t_lo, t_hi)) + >>> Sx_dB = 10 * np.log10(np.fmax(Sx2, 1e-4)) # limit range to -40 dB + >>> im1 = ax1.imshow(Sx_dB, origin='lower', aspect='auto', + ... extent=SFT.extent(N), cmap='magma') + >>> ax1.plot(t_x, f_i, 'g--', alpha=.5, label='$f_i(t)$') + >>> fig1.colorbar(im1, label='Power Spectral Density ' + + ... r"$20\,\log_{10}|S_x(t, f)|$ in dB") + ... + >>> # Shade areas where window slices stick out to the side: + >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T), + ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]: + ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.3) + >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line + ... ax1.axvline(t_, color='c', linestyle='--', alpha=0.5) + >>> ax1.legend() + >>> fig1.tight_layout() + >>> plt.show() + + The logarithmic scaling reveals the odd harmonics of the square wave, + which are reflected at the Nyquist frequency of 10 Hz. This aliasing + is also the main source of the noise artifacts in the plot. + + + See Also + -------- + :meth:`~ShortTimeFFT.stft`: Perform the short-time Fourier transform. + stft_detrend: STFT with a trend subtracted from each segment. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + Sx = self.stft_detrend(x, detr, p0, p1, k_offset=k_offset, + padding=padding, axis=axis) + if y is None or y is x: # do spectrogram: + return Sx.real**2 + Sx.imag**2 + # Cross-spectrogram: + Sy = self.stft_detrend(y, detr, p0, p1, k_offset=k_offset, + padding=padding, axis=axis) + return Sx * Sy.conj() + + @property + def dual_win(self) -> np.ndarray: + """Canonical dual window. + + A STFT can be interpreted as the input signal being expressed as a + weighted sum of modulated and time-shifted dual windows. Note that for + a given window there exist many dual windows. The canonical window is + the one with the minimal energy (i.e., :math:`L_2` norm). + + `dual_win` has same length as `win`, namely `m_num` samples. + + If the dual window cannot be calculated a ``ValueError`` is raised. + This attribute is read only and calculated lazily. + + See Also + -------- + dual_win: Canonical dual window. + m_num: Number of samples in window `win`. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + if self._dual_win is None: + self._dual_win = _calc_dual_canonical_window(self.win, self.hop) + return self._dual_win + + @property + def invertible(self) -> bool: + """Check if STFT is invertible. + + This is achieved by trying to calculate the canonical dual window. + + See Also + -------- + :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform. + m_num: Number of samples in window `win` and `dual_win`. + dual_win: Canonical dual window. + win: Window for STFT. + ShortTimeFFT: Class this property belongs to. + """ + try: + return len(self.dual_win) > 0 # call self.dual_win() + except ValueError: + return False + + def istft(self, S: np.ndarray, k0: int = 0, k1: int | None = None, *, + f_axis: int = -2, t_axis: int = -1) \ + -> np.ndarray: + """Inverse short-time Fourier transform. + + It returns an array of dimension ``S.ndim - 1`` which is real + if `onesided_fft` is set, else complex. If the STFT is not + `invertible`, or the parameters are out of bounds a ``ValueError`` is + raised. + + Parameters + ---------- + S + A complex valued array where `f_axis` denotes the frequency + values and the `t-axis` dimension the temporal values of the + STFT values. + k0, k1 + The start and the end index of the reconstructed signal. The + default (``k0 = 0``, ``k1 = None``) assumes that the maximum length + signal should be reconstructed. + f_axis, t_axis + The axes in `S` denoting the frequency and the time dimension. + + Notes + ----- + It is required that `S` has `f_pts` entries along the `f_axis`. For + the `t_axis` it is assumed that the first entry corresponds to + `p_min` * `delta_t` (being <= 0). The length of `t_axis` needs to be + compatible with `k1`. I.e., ``S.shape[t_axis] >= self.p_max(k1)`` must + hold, if `k1` is not ``None``. Else `k1` is set to `k_max` with:: + + q_max = S.shape[t_range] + self.p_min + k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid + + The :ref:`tutorial_stft` section of the :ref:`user_guide` discussed the + slicing behavior by means of an example. + + See Also + -------- + invertible: Check if STFT is invertible. + :meth:`~ShortTimeFFT.stft`: Perform Short-time Fourier transform. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + if f_axis == t_axis: + raise ValueError(f"{f_axis=} may not be equal to {t_axis=}!") + if S.shape[f_axis] != self.f_pts: + raise ValueError(f"{S.shape[f_axis]=} must be equal to " + + f"{self.f_pts=} ({S.shape=})!") + n_min = self.m_num-self.m_num_mid # minimum signal length + if not (S.shape[t_axis] >= (q_num := self.p_num(n_min))): + raise ValueError(f"{S.shape[t_axis]=} needs to have at least " + + f"{q_num} slices ({S.shape=})!") + if t_axis != S.ndim - 1 or f_axis != S.ndim - 2: + t_axis = S.ndim + t_axis if t_axis < 0 else t_axis + f_axis = S.ndim + f_axis if f_axis < 0 else f_axis + S = np.moveaxis(S, (f_axis, t_axis), (-2, -1)) + + q_max = S.shape[-1] + self.p_min + k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid + + k1 = k_max if k1 is None else k1 + if not (self.k_min <= k0 < k1 <= k_max): + raise ValueError(f"({self.k_min=}) <= ({k0=}) < ({k1=}) <= " + + f"({k_max=}) is false!") + if not (num_pts := k1 - k0) >= n_min: + raise ValueError(f"({k1=}) - ({k0=}) = {num_pts} has to be at " + + f"least the half the window length {n_min}!") + + q0 = (k0 // self.hop + self.p_min if k0 >= 0 else # p_min always <= 0 + k0 // self.hop) + q1 = min(self.p_max(k1), q_max) + k_q0, k_q1 = self.nearest_k_p(k0), self.nearest_k_p(k1, left=False) + n_pts = k_q1 - k_q0 + self.m_num - self.m_num_mid + x = np.zeros(S.shape[:-2] + (n_pts,), + dtype=float if self.onesided_fft else complex) + for q_ in range(q0, q1): + xs = self._ifft_func(S[..., :, q_ - self.p_min]) * self.dual_win + i0 = q_ * self.hop - self.m_num_mid + i1 = min(i0 + self.m_num, n_pts+k0) + j0, j1 = 0, i1 - i0 + if i0 < k0: # xs sticks out to the left on x: + j0 += k0 - i0 + i0 = k0 + x[..., i0-k0:i1-k0] += xs[..., j0:j1] + x = x[..., :k1-k0] + if x.ndim > 1: + x = np.moveaxis(x, -1, f_axis if f_axis < x.ndim else t_axis) + return x + + @property + def fac_magnitude(self) -> float: + """Factor to multiply the STFT values by to scale each frequency slice + to a magnitude spectrum. + + It is 1 if attribute ``scaling == 'magnitude'``. + The window can be scaled to a magnitude spectrum by using the method + `scale_to`. + + See Also + -------- + fac_psd: Scaling factor for to a power spectral density spectrum. + scale_to: Scale window to obtain 'magnitude' or 'psd' scaling. + scaling: Normalization applied to the window function. + ShortTimeFFT: Class this property belongs to. + """ + if self.scaling == 'magnitude': + return 1 + if self._fac_mag is None: + self._fac_mag = 1 / abs(sum(self.win)) + return self._fac_mag + + @property + def fac_psd(self) -> float: + """Factor to multiply the STFT values by to scale each frequency slice + to a power spectral density (PSD). + + It is 1 if attribute ``scaling == 'psd'``. + The window can be scaled to a psd spectrum by using the method + `scale_to`. + + See Also + -------- + fac_magnitude: Scaling factor for to a magnitude spectrum. + scale_to: Scale window to obtain 'magnitude' or 'psd' scaling. + scaling: Normalization applied to the window function. + ShortTimeFFT: Class this property belongs to. + """ + if self.scaling == 'psd': + return 1 + if self._fac_psd is None: + self._fac_psd = 1 / np.sqrt( + sum(self.win.real**2+self.win.imag**2) / self.T) + return self._fac_psd + + @property + def m_num(self) -> int: + """Number of samples in window `win`. + + Note that the FFT can be oversampled by zero-padding. This is achieved + by setting the `mfft` property. + + See Also + -------- + m_num_mid: Center index of window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + hop: Time increment in signal samples for sliding window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return len(self.win) + + @property + def m_num_mid(self) -> int: + """Center index of window `win`. + + For odd `m_num`, ``(m_num - 1) / 2`` is returned and + for even `m_num` (per definition) ``m_num / 2`` is returned. + + See Also + -------- + m_num: Number of samples in window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + hop: ime increment in signal samples for sliding window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return self.m_num // 2 + + @cache + def _pre_padding(self) -> tuple[int, int]: + """Smallest signal index and slice index due to padding. + + Since, per convention, for time t=0, n,q is zero, the returned values + are negative or zero. + """ + w2 = self.win.real**2 + self.win.imag**2 + # move window to the left until the overlap with t >= 0 vanishes: + n0 = -self.m_num_mid + for q_, n_ in enumerate(range(n0, n0-self.m_num-1, -self.hop)): + n_next = n_ - self.hop + if n_next + self.m_num <= 0 or all(w2[n_next:] == 0): + return n_, -q_ + raise RuntimeError("This is code line should not have been reached!") + # If this case is reached, it probably means the first slice should be + # returned, i.e.: return n0, 0 + + @property + def k_min(self) -> int: + """The smallest possible signal index of the STFT. + + `k_min` is the index of the left-most non-zero value of the lowest + slice `p_min`. Since the zeroth slice is centered over the zeroth + sample of the input signal, `k_min` is never positive. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this property belongs to. + """ + return self._pre_padding()[0] + + @property + def p_min(self) -> int: + """The smallest possible slice index. + + `p_min` is the index of the left-most slice, where the window still + sticks into the signal, i.e., has non-zero part for t >= 0. + `k_min` is the smallest index where the window function of the slice + `p_min` is non-zero. + + Since, per convention the zeroth slice is centered at t=0, + `p_min` <= 0 always holds. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this property belongs to. + """ + return self._pre_padding()[1] + + @lru_cache(maxsize=256) + def _post_padding(self, n: int) -> tuple[int, int]: + """Largest signal index and slice index due to padding. + + Parameters + ---------- + n : int + Number of samples of input signal (must be ≥ half of the window length). + """ + if not (n >= (m2p := self.m_num - self.m_num_mid)): + raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!") + w2 = self.win.real**2 + self.win.imag**2 + # move window to the right until the overlap for t < t[n] vanishes: + q1 = n // self.hop # last slice index with t[p1] <= t[n] + k1 = q1 * self.hop - self.m_num_mid + for q_, k_ in enumerate(range(k1, n+self.m_num, self.hop), start=q1): + n_next = k_ + self.hop + if n_next >= n or all(w2[:n-n_next] == 0): + return k_ + self.m_num, q_ + 1 + raise RuntimeError("This is code line should not have been reached!") + # If this case is reached, it probably means the last slice should be + # returned, i.e.: return k1 + self.m_num - self.m_num_mid, q1 + 1 + + def k_max(self, n: int) -> int: + """First sample index after signal end not touched by a time slice. + + `k_max` - 1 is the largest sample index of the slice `p_max` for a + given input signal of `n` samples. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + Parameters + ---------- + n : int + Number of samples of input signal (must be ≥ half of the window length). + + See Also + -------- + k_min: The smallest possible signal index. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this method belongs to. + """ + return self._post_padding(n)[0] + + def p_max(self, n: int) -> int: + """Index of first non-overlapping upper time slice for `n` sample + input. + + Note that center point t[p_max] = (p_max(n)-1) * `delta_t` is typically + larger than last time index t[n-1] == (`n`-1) * `T`. The upper border + of samples indexes covered by the window slices is given by `k_max`. + Furthermore, `p_max` does not denote the number of slices `p_num` since + `p_min` is typically less than zero. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + p_min: The smallest possible slice index. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this method belongs to. + """ + return self._post_padding(n)[1] + + def p_num(self, n: int) -> int: + """Number of time slices for an input signal with `n` samples. + + It is given by `p_num` = `p_max` - `p_min` with `p_min` typically + being negative. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_range: Determine and validate slice index range. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this method belongs to. + """ + return self.p_max(n) - self.p_min + + @property + def lower_border_end(self) -> tuple[int, int]: + """First signal index and first slice index unaffected by pre-padding. + + Describes the point where the window does not stick out to the left + of the signal domain. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this property belongs to. + """ + # not using @cache decorator due to MyPy limitations + if self._lower_border_end is not None: + return self._lower_border_end + + # first non-zero element in self.win: + m0 = np.flatnonzero(self.win.real**2 + self.win.imag**2)[0] + + # move window to the right until does not stick out to the left: + k0 = -self.m_num_mid + m0 + for q_, k_ in enumerate(range(k0, self.hop + 1, self.hop)): + if k_ + self.hop >= 0: # next entry does not stick out anymore + self._lower_border_end = (k_ + self.m_num, q_ + 1) + return self._lower_border_end + self._lower_border_end = (0, max(self.p_min, 0)) # ends at first slice + return self._lower_border_end + + @lru_cache(maxsize=256) + def upper_border_begin(self, n: int) -> tuple[int, int]: + """First signal index and first slice index affected by post-padding. + + Describes the point where the window does begin stick out to the right + of the signal domain. + A detailed example is given :ref:`tutorial_stft_sliding_win` section + of the :ref:`user_guide`. + + Parameters + ---------- + n : int + Number of samples of input signal (must be ≥ half of the window length). + + Returns + ------- + k_ub : int + Lowest signal index, where a touching time slice sticks out past the + signal end. + p_ub : int + Lowest index of time slice of which the end sticks out past the signal end. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this method belongs to. + """ + if not (n >= (m2p := self.m_num - self.m_num_mid)): + raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!") + w2 = self.win.real**2 + self.win.imag**2 + q2 = n // self.hop + 1 # first t[q] >= t[n] + q1 = max((n-self.m_num) // self.hop - 1, -1) + # move window left until does not stick out to the right: + for q_ in range(q2, q1, -1): + k_ = q_ * self.hop + (self.m_num - self.m_num_mid) + if k_ <= n or all(w2[n-k_:] == 0): + return (q_ + 1) * self.hop - self.m_num_mid, q_ + 1 + return 0, 0 # border starts at first slice + + @property + def delta_t(self) -> float: + """Time increment of STFT. + + The time increment `delta_t` = `T` * `hop` represents the sample + increment `hop` converted to time based on the sampling interval `T`. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + hop: Hop size in signal samples for sliding window. + t: Times of STFT for an input signal with `n` samples. + T: Sampling interval of input signal and window `win`. + ShortTimeFFT: Class this property belongs to + """ + return self.T * self.hop + + def p_range(self, n: int, p0: int | None = None, + p1: int | None = None) -> tuple[int, int]: + """Determine and validate slice index range. + + Parameters + ---------- + n : int + Number of samples of input signal, assuming t[0] = 0. + p0 : int | None + First slice index. If 0 then the first slice is centered at t = 0. + If ``None`` then `p_min` is used. Note that p0 may be < 0 if + slices are left of t = 0. + p1 : int | None + End of interval (last value is p1-1). + If ``None`` then `p_max(n)` is used. + + + Returns + ------- + p0_ : int + The fist slice index + p1_ : int + End of interval (last value is p1-1). + + Notes + ----- + A ``ValueError`` is raised if ``p_min <= p0 < p1 <= p_max(n)`` does not + hold. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this property belongs to. + """ + p_max = self.p_max(n) # shorthand + p0_ = self.p_min if p0 is None else p0 + p1_ = p_max if p1 is None else p1 + if not (self.p_min <= p0_ < p1_ <= p_max): + raise ValueError(f"Invalid Parameter {p0=}, {p1=}, i.e., " + + f"{self.p_min=} <= p0 < p1 <= {p_max=} " + + f"does not hold for signal length {n=}!") + return p0_, p1_ + + @lru_cache(maxsize=1) + def t(self, n: int, p0: int | None = None, p1: int | None = None, + k_offset: int = 0) -> np.ndarray: + """Times of STFT for an input signal with `n` samples. + + Returns a 1d array with times of the `~ShortTimeFFT.stft` values with + the same parametrization. Note that the slices are + ``delta_t = hop * T`` time units apart. + + Parameters + ---------- + n + Number of sample of the input signal. + p0 + The first element of the range of slices to calculate. If ``None`` + then it is set to :attr:`p_min`, which is the smallest possible + slice. + p1 + The end of the array. If ``None`` then `p_max(n)` is used. + k_offset + Index of first sample (t = 0) in `x`. + + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + nearest_k_p: Nearest sample index k_p for which t[k_p] == t[p] holds. + T: Sampling interval of input signal and of the window (``1/fs``). + fs: Sampling frequency (being ``1/T``) + ShortTimeFFT: Class this method belongs to. + """ + p0, p1 = self.p_range(n, p0, p1) + return np.arange(p0, p1) * self.delta_t + k_offset * self.T + + def nearest_k_p(self, k: int, left: bool = True) -> int: + """Return nearest sample index k_p for which t[k_p] == t[p] holds. + + The nearest next smaller time sample p (where t[p] is the center + position of the window of the p-th slice) is p_k = k // `hop`. + If `hop` is a divisor of `k` than `k` is returned. + If `left` is set than p_k * `hop` is returned else (p_k+1) * `hop`. + + This method can be used to slice an input signal into chunks for + calculating the STFT and iSTFT incrementally. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + T: Sampling interval of input signal and of the window (``1/fs``). + fs: Sampling frequency (being ``1/T``) + t: Times of STFT for an input signal with `n` samples. + ShortTimeFFT: Class this method belongs to. + """ + p_q, remainder = divmod(k, self.hop) + if remainder == 0: + return k + return p_q * self.hop if left else (p_q + 1) * self.hop + + @property + def delta_f(self) -> float: + """Width of the frequency bins of the STFT. + + Return the frequency interval `delta_f` = 1 / (`mfft` * `T`). + + See Also + -------- + delta_t: Time increment of STFT. + f_pts: Number of points along the frequency axis. + f: Frequencies values of the STFT. + mfft: Length of the input for FFT used. + T: Sampling interval. + t: Times of STFT for an input signal with `n` samples. + ShortTimeFFT: Class this property belongs to. + """ + return 1 / (self.mfft * self.T) + + @property + def f_pts(self) -> int: + """Number of points along the frequency axis. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f: Frequencies values of the STFT. + mfft: Length of the input for FFT used. + ShortTimeFFT: Class this property belongs to. + """ + return self.mfft // 2 + 1 if self.onesided_fft else self.mfft + + @property + def onesided_fft(self) -> bool: + """Return True if a one-sided FFT is used. + + Returns ``True`` if `fft_mode` is either 'onesided' or 'onesided2X'. + + See Also + -------- + fft_mode: Utilized FFT ('twosided', 'centered', 'onesided' or + 'onesided2X') + ShortTimeFFT: Class this property belongs to. + """ + return self.fft_mode in {'onesided', 'onesided2X'} + + @property + def f(self) -> np.ndarray: + """Frequencies values of the STFT. + + A 1d array of length `f_pts` with `delta_f` spaced entries is returned. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f_pts: Number of points along the frequency axis. + mfft: Length of the input for FFT used. + ShortTimeFFT: Class this property belongs to. + """ + if self.fft_mode in {'onesided', 'onesided2X'}: + return fft_lib.rfftfreq(self.mfft, self.T) + elif self.fft_mode == 'twosided': + return fft_lib.fftfreq(self.mfft, self.T) + elif self.fft_mode == 'centered': + return fft_lib.fftshift(fft_lib.fftfreq(self.mfft, self.T)) + # This should never happen but makes the Linters happy: + fft_modes = get_args(FFT_MODE_TYPE) + raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!") + + def _fft_func(self, x: np.ndarray) -> np.ndarray: + """FFT based on the `fft_mode`, `mfft`, `scaling` and `phase_shift` + attributes. + + For multidimensional arrays the transformation is carried out on the + last axis. + """ + if self.phase_shift is not None: + if x.shape[-1] < self.mfft: # zero pad if needed + z_shape = list(x.shape) + z_shape[-1] = self.mfft - x.shape[-1] + x = np.hstack((x, np.zeros(z_shape, dtype=x.dtype))) + p_s = (self.phase_shift + self.m_num_mid) % self.m_num + x = np.roll(x, -p_s, axis=-1) + + if self.fft_mode == 'twosided': + return fft_lib.fft(x, n=self.mfft, axis=-1) + if self.fft_mode == 'centered': + return fft_lib.fftshift(fft_lib.fft(x, self.mfft, axis=-1), axes=-1) + if self.fft_mode == 'onesided': + return fft_lib.rfft(x, n=self.mfft, axis=-1) + if self.fft_mode == 'onesided2X': + X = fft_lib.rfft(x, n=self.mfft, axis=-1) + # Either squared magnitude (psd) or magnitude is doubled: + fac = np.sqrt(2) if self.scaling == 'psd' else 2 + # For even input length, the last entry is unpaired: + X[..., 1: -1 if self.mfft % 2 == 0 else None] *= fac + return X + # This should never happen but makes the Linter happy: + fft_modes = get_args(FFT_MODE_TYPE) + raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!") + + def _ifft_func(self, X: np.ndarray) -> np.ndarray: + """Inverse to `_fft_func`. + + Returned is an array of length `m_num`. If the FFT is `onesided` + then a float array is returned else a complex array is returned. + For multidimensional arrays the transformation is carried out on the + last axis. + """ + if self.fft_mode == 'twosided': + x = fft_lib.ifft(X, n=self.mfft, axis=-1) + elif self.fft_mode == 'centered': + x = fft_lib.ifft(fft_lib.ifftshift(X, axes=-1), n=self.mfft, axis=-1) + elif self.fft_mode == 'onesided': + x = fft_lib.irfft(X, n=self.mfft, axis=-1) + elif self.fft_mode == 'onesided2X': + Xc = X.copy() # we do not want to modify function parameters + fac = np.sqrt(2) if self.scaling == 'psd' else 2 + # For even length X the last value is not paired with a negative + # value on the two-sided FFT: + q1 = -1 if self.mfft % 2 == 0 else None + Xc[..., 1:q1] /= fac + x = fft_lib.irfft(Xc, n=self.mfft, axis=-1) + else: # This should never happen but makes the Linter happy: + error_str = f"{self.fft_mode=} not in {get_args(FFT_MODE_TYPE)}!" + raise RuntimeError(error_str) + + if self.phase_shift is None: + return x[..., :self.m_num] + p_s = (self.phase_shift + self.m_num_mid) % self.m_num + return np.roll(x, p_s, axis=-1)[..., :self.m_num] + + def extent(self, n: int, axes_seq: Literal['tf', 'ft'] = 'tf', + center_bins: bool = False) -> tuple[float, float, float, float]: + """Return minimum and maximum values time-frequency values. + + A tuple with four floats ``(t0, t1, f0, f1)`` for 'tf' and + ``(f0, f1, t0, t1)`` for 'ft' is returned describing the corners + of the time-frequency domain of the `~ShortTimeFFT.stft`. + That tuple can be passed to `matplotlib.pyplot.imshow` as a parameter + with the same name. + + Parameters + ---------- + n : int + Number of samples in input signal. + axes_seq : {'tf', 'ft'} + Return time extent first and then frequency extent or vice-versa. + center_bins: bool + If set (default ``False``), the values of the time slots and + frequency bins are moved from the side the middle. This is useful, + when plotting the `~ShortTimeFFT.stft` values as step functions, + i.e., with no interpolation. + + See Also + -------- + :func:`matplotlib.pyplot.imshow`: Display data as an image. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + + Examples + -------- + The following two plots illustrate the effect of the parameter `center_bins`: + The grid lines represent the three time and the four frequency values of the + STFT. + The left plot, where ``(t0, t1, f0, f1) = (0, 3, 0, 4)`` is passed as parameter + ``extent`` to `~matplotlib.pyplot.imshow`, shows the standard behavior of the + time and frequency values being at the lower edge of the corrsponding bin. + The right plot, with ``(t0, t1, f0, f1) = (-0.5, 2.5, -0.5, 3.5)``, shows that + the bins are centered over the respective values when passing + ``center_bins=True``. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal import ShortTimeFFT + ... + >>> n, m = 12, 6 + >>> SFT = ShortTimeFFT.from_window('hann', fs=m, nperseg=m, noverlap=0) + >>> Sxx = SFT.stft(np.cos(np.arange(n))) # produces a colorful plot + ... + >>> fig, axx = plt.subplots(1, 2, tight_layout=True, figsize=(6., 4.)) + >>> for ax_, center_bins in zip(axx, (False, True)): + ... ax_.imshow(abs(Sxx), origin='lower', interpolation=None, aspect='equal', + ... cmap='viridis', extent=SFT.extent(n, 'tf', center_bins)) + ... ax_.set_title(f"{center_bins=}") + ... ax_.set_xlabel(f"Time ({SFT.p_num(n)} points, Δt={SFT.delta_t})") + ... ax_.set_ylabel(f"Frequency ({SFT.f_pts} points, Δf={SFT.delta_f})") + ... ax_.set_xticks(SFT.t(n)) # vertical grid line are timestamps + ... ax_.set_yticks(SFT.f) # horizontal grid line are frequency values + ... ax_.grid(True) + >>> plt.show() + + Note that the step-like behavior with the constant colors is caused by passing + ``interpolation=None`` to `~matplotlib.pyplot.imshow`. + """ + if axes_seq not in ('tf', 'ft'): + raise ValueError(f"Parameter {axes_seq=} not in ['tf', 'ft']!") + + if self.onesided_fft: + q0, q1 = 0, self.f_pts + elif self.fft_mode == 'centered': + q0 = -(self.mfft // 2) + q1 = self.mfft // 2 if self.mfft % 2 == 0 else self.mfft // 2 + 1 + else: + raise ValueError(f"Attribute fft_mode={self.fft_mode} must be " + + "in ['centered', 'onesided', 'onesided2X']") + + p0, p1 = self.p_min, self.p_max(n) # shorthand + if center_bins: + t0, t1 = self.delta_t * (p0 - 0.5), self.delta_t * (p1 - 0.5) + f0, f1 = self.delta_f * (q0 - 0.5), self.delta_f * (q1 - 0.5) + else: + t0, t1 = self.delta_t * p0, self.delta_t * p1 + f0, f1 = self.delta_f * q0, self.delta_f * q1 + return (t0, t1, f0, f1) if axes_seq == 'tf' else (f0, f1, t0, t1) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_signaltools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_signaltools.py new file mode 100644 index 0000000000000000000000000000000000000000..340e227760ecd0a4bbf7bf5a135b92acb123a4d3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_signaltools.py @@ -0,0 +1,4989 @@ +# Author: Travis Oliphant +# 1999 -- 2002 + +from __future__ import annotations # Provides typing union operator `|` in Python 3.9 +import operator +import math +from math import prod as _prod +import timeit +import warnings +from typing import Literal + +from numpy._typing import ArrayLike + +from scipy.spatial import cKDTree +from . import _sigtools +from ._ltisys import dlti +from ._upfirdn import upfirdn, _output_len, _upfirdn_modes +from scipy import linalg, fft as sp_fft +from scipy import ndimage +from scipy.fft._helper import _init_nd_shape_and_axes +import numpy as np +from scipy.special import lambertw +from .windows import get_window +from ._arraytools import axis_slice, axis_reverse, odd_ext, even_ext, const_ext +from ._filter_design import cheby1, _validate_sos, zpk2sos +from ._fir_filter_design import firwin +from ._sosfilt import _sosfilt + + +__all__ = ['correlate', 'correlation_lags', 'correlate2d', + 'convolve', 'convolve2d', 'fftconvolve', 'oaconvolve', + 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter', + 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2', 'envelope', + 'unique_roots', 'invres', 'invresz', 'residue', + 'residuez', 'resample', 'resample_poly', 'detrend', + 'lfilter_zi', 'sosfilt_zi', 'sosfiltfilt', 'choose_conv_method', + 'filtfilt', 'decimate', 'vectorstrength'] + + +_modedict = {'valid': 0, 'same': 1, 'full': 2} + +_boundarydict = {'fill': 0, 'pad': 0, 'wrap': 2, 'circular': 2, 'symm': 1, + 'symmetric': 1, 'reflect': 4} + + +def _valfrommode(mode): + try: + return _modedict[mode] + except KeyError as e: + raise ValueError("Acceptable mode flags are 'valid'," + " 'same', or 'full'.") from e + + +def _bvalfromboundary(boundary): + try: + return _boundarydict[boundary] << 2 + except KeyError as e: + raise ValueError("Acceptable boundary flags are 'fill', 'circular' " + "(or 'wrap'), and 'symmetric' (or 'symm').") from e + + +def _inputs_swap_needed(mode, shape1, shape2, axes=None): + """Determine if inputs arrays need to be swapped in `"valid"` mode. + + If in `"valid"` mode, returns whether or not the input arrays need to be + swapped depending on whether `shape1` is at least as large as `shape2` in + every calculated dimension. + + This is important for some of the correlation and convolution + implementations in this module, where the larger array input needs to come + before the smaller array input when operating in this mode. + + Note that if the mode provided is not 'valid', False is immediately + returned. + + """ + if mode != 'valid': + return False + + if not shape1: + return False + + if axes is None: + axes = range(len(shape1)) + + ok1 = all(shape1[i] >= shape2[i] for i in axes) + ok2 = all(shape2[i] >= shape1[i] for i in axes) + + if not (ok1 or ok2): + raise ValueError("For 'valid' mode, one must be at least " + "as large as the other in every dimension") + + return not ok1 + + +def _reject_objects(arr, name): + """Warn if arr.dtype is object or longdouble. + """ + dt = np.asarray(arr).dtype + if not (np.issubdtype(dt, np.integer) + or dt in [np.bool_, np.float16, np.float32, np.float64, + np.complex64, np.complex128] + ): + msg = ( + f"dtype={dt} is not supported by {name} and will raise an error in " + f"SciPy 1.17.0. Supported dtypes are: boolean, integer, `np.float16`," + f"`np.float32`, `np.float64`, `np.complex64`, `np.complex128`." + ) + warnings.warn(msg, category=DeprecationWarning, stacklevel=3) + + +def correlate(in1, in2, mode='full', method='auto'): + r""" + Cross-correlate two N-dimensional arrays. + + Cross-correlate `in1` and `in2`, with the output size determined by the + `mode` argument. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear cross-correlation + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + method : str {'auto', 'direct', 'fft'}, optional + A string indicating which method to use to calculate the correlation. + + ``direct`` + The correlation is determined directly from sums, the definition of + correlation. + ``fft`` + The Fast Fourier Transform is used to perform the correlation more + quickly (only available for numerical arrays.) + ``auto`` + Automatically chooses direct or Fourier method based on an estimate + of which is faster (default). See `convolve` Notes for more detail. + + .. versionadded:: 0.19.0 + + Returns + ------- + correlate : array + An N-dimensional array containing a subset of the discrete linear + cross-correlation of `in1` with `in2`. + + See Also + -------- + choose_conv_method : contains more documentation on `method`. + correlation_lags : calculates the lag / displacement indices array for 1D + cross-correlation. + + Notes + ----- + The correlation z of two d-dimensional arrays x and y is defined as:: + + z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...]) + + This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')`` + then + + .. math:: + + z[k] = (x * y)(k - N + 1) + = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*} + + for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2` + + where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`, + and :math:`y_m` is 0 when m is outside the range of y. + + ``method='fft'`` only works for numerical arrays as it relies on + `fftconvolve`. In certain cases (i.e., arrays of objects or when + rounding integers can lose precision), ``method='direct'`` is always used. + + When using "same" mode with even-length inputs, the outputs of `correlate` + and `correlate2d` differ: There is a 1-index offset between them. + + Examples + -------- + Implement a matched filter using cross-correlation, to recover a signal + that has passed through a noisy channel. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128) + >>> sig_noise = sig + rng.standard_normal(len(sig)) + >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128 + + >>> clock = np.arange(64, len(sig), 128) + >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True) + >>> ax_orig.plot(sig) + >>> ax_orig.plot(clock, sig[clock], 'ro') + >>> ax_orig.set_title('Original signal') + >>> ax_noise.plot(sig_noise) + >>> ax_noise.set_title('Signal with noise') + >>> ax_corr.plot(corr) + >>> ax_corr.plot(clock, corr[clock], 'ro') + >>> ax_corr.axhline(0.5, ls=':') + >>> ax_corr.set_title('Cross-correlated with rectangular pulse') + >>> ax_orig.margins(0, 0.1) + >>> fig.tight_layout() + >>> plt.show() + + Compute the cross-correlation of a noisy signal with the original signal. + + >>> x = np.arange(128) / 128 + >>> sig = np.sin(2 * np.pi * x) + >>> sig_noise = sig + rng.standard_normal(len(sig)) + >>> corr = signal.correlate(sig_noise, sig) + >>> lags = signal.correlation_lags(len(sig), len(sig_noise)) + >>> corr /= np.max(corr) + + >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, figsize=(4.8, 4.8)) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('Original signal') + >>> ax_orig.set_xlabel('Sample Number') + >>> ax_noise.plot(sig_noise) + >>> ax_noise.set_title('Signal with noise') + >>> ax_noise.set_xlabel('Sample Number') + >>> ax_corr.plot(lags, corr) + >>> ax_corr.set_title('Cross-correlated signal') + >>> ax_corr.set_xlabel('Lag') + >>> ax_orig.margins(0, 0.1) + >>> ax_noise.margins(0, 0.1) + >>> ax_corr.margins(0, 0.1) + >>> fig.tight_layout() + >>> plt.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + _reject_objects(in1, 'correlate') + _reject_objects(in2, 'correlate') + + if in1.ndim == in2.ndim == 0: + return in1 * in2.conj() + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + + # Don't use _valfrommode, since correlate should not accept numeric modes + try: + val = _modedict[mode] + except KeyError as e: + raise ValueError("Acceptable mode flags are 'valid'," + " 'same', or 'full'.") from e + + # this either calls fftconvolve or this function with method=='direct' + if method in ('fft', 'auto'): + return convolve(in1, _reverse_and_conj(in2), mode, method) + + elif method == 'direct': + # fastpath to faster numpy.correlate for 1d inputs when possible + if _np_conv_ok(in1, in2, mode): + return np.correlate(in1, in2, mode) + + # _correlateND is far slower when in2.size > in1.size, so swap them + # and then undo the effect afterward if mode == 'full'. Also, it fails + # with 'valid' mode if in2 is larger than in1, so swap those, too. + # Don't swap inputs for 'same' mode, since shape of in1 matters. + swapped_inputs = ((mode == 'full') and (in2.size > in1.size) or + _inputs_swap_needed(mode, in1.shape, in2.shape)) + + if swapped_inputs: + in1, in2 = in2, in1 + + if mode == 'valid': + ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)] + out = np.empty(ps, in1.dtype) + + z = _sigtools._correlateND(in1, in2, out, val) + + else: + ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)] + + # zero pad input + in1zpadded = np.zeros(ps, in1.dtype) + sc = tuple(slice(0, i) for i in in1.shape) + in1zpadded[sc] = in1.copy() + + if mode == 'full': + out = np.empty(ps, in1.dtype) + elif mode == 'same': + out = np.empty(in1.shape, in1.dtype) + + z = _sigtools._correlateND(in1zpadded, in2, out, val) + + if swapped_inputs: + # Reverse and conjugate to undo the effect of swapping inputs + z = _reverse_and_conj(z) + + return z + + else: + raise ValueError("Acceptable method flags are 'auto'," + " 'direct', or 'fft'.") + + +def correlation_lags(in1_len, in2_len, mode='full'): + r""" + Calculates the lag / displacement indices array for 1D cross-correlation. + + Parameters + ---------- + in1_len : int + First input size. + in2_len : int + Second input size. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output. + See the documentation `correlate` for more information. + + Returns + ------- + lags : array + Returns an array containing cross-correlation lag/displacement indices. + Indices can be indexed with the np.argmax of the correlation to return + the lag/displacement. + + See Also + -------- + correlate : Compute the N-dimensional cross-correlation. + + Notes + ----- + Cross-correlation for continuous functions :math:`f` and :math:`g` is + defined as: + + .. math:: + + \left ( f\star g \right )\left ( \tau \right ) + \triangleq \int_{t_0}^{t_0 +T} + \overline{f\left ( t \right )}g\left ( t+\tau \right )dt + + Where :math:`\tau` is defined as the displacement, also known as the lag. + + Cross correlation for discrete functions :math:`f` and :math:`g` is + defined as: + + .. math:: + \left ( f\star g \right )\left [ n \right ] + \triangleq \sum_{-\infty}^{\infty} + \overline{f\left [ m \right ]}g\left [ m+n \right ] + + Where :math:`n` is the lag. + + Examples + -------- + Cross-correlation of a signal with its time-delayed self. + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> x = rng.standard_normal(1000) + >>> y = np.concatenate([rng.standard_normal(100), x]) + >>> correlation = signal.correlate(x, y, mode="full") + >>> lags = signal.correlation_lags(x.size, y.size, mode="full") + >>> lag = lags[np.argmax(correlation)] + """ + + # calculate lag ranges in different modes of operation + if mode == "full": + # the output is the full discrete linear convolution + # of the inputs. (Default) + lags = np.arange(-in2_len + 1, in1_len) + elif mode == "same": + # the output is the same size as `in1`, centered + # with respect to the 'full' output. + # calculate the full output + lags = np.arange(-in2_len + 1, in1_len) + # determine the midpoint in the full output + mid = lags.size // 2 + # determine lag_bound to be used with respect + # to the midpoint + lag_bound = in1_len // 2 + # calculate lag ranges for even and odd scenarios + if in1_len % 2 == 0: + lags = lags[(mid-lag_bound):(mid+lag_bound)] + else: + lags = lags[(mid-lag_bound):(mid+lag_bound)+1] + elif mode == "valid": + # the output consists only of those elements that do not + # rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + # must be at least as large as the other in every dimension. + + # the lag_bound will be either negative or positive + # this let's us infer how to present the lag range + lag_bound = in1_len - in2_len + if lag_bound >= 0: + lags = np.arange(lag_bound + 1) + else: + lags = np.arange(lag_bound, 1) + else: + raise ValueError(f"Mode {mode} is invalid") + return lags + + +def _centered(arr, newshape): + # Return the center newshape portion of the array. + newshape = np.asarray(newshape) + currshape = np.array(arr.shape) + startind = (currshape - newshape) // 2 + endind = startind + newshape + myslice = [slice(startind[k], endind[k]) for k in range(len(endind))] + return arr[tuple(myslice)] + + +def _init_freq_conv_axes(in1, in2, mode, axes, sorted_axes=False): + """Handle the axes argument for frequency-domain convolution. + + Returns the inputs and axes in a standard form, eliminating redundant axes, + swapping the inputs if necessary, and checking for various potential + errors. + + Parameters + ---------- + in1 : array + First input. + in2 : array + Second input. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output. + See the documentation `fftconvolve` for more information. + axes : list of ints + Axes over which to compute the FFTs. + sorted_axes : bool, optional + If `True`, sort the axes. + Default is `False`, do not sort. + + Returns + ------- + in1 : array + The first input, possible swapped with the second input. + in2 : array + The second input, possible swapped with the first input. + axes : list of ints + Axes over which to compute the FFTs. + + """ + s1 = in1.shape + s2 = in2.shape + noaxes = axes is None + + _, axes = _init_nd_shape_and_axes(in1, shape=None, axes=axes) + + if not noaxes and not len(axes): + raise ValueError("when provided, axes cannot be empty") + + # Axes of length 1 can rely on broadcasting rules for multiply, + # no fft needed. + axes = [a for a in axes if s1[a] != 1 and s2[a] != 1] + + if sorted_axes: + axes.sort() + + if not all(s1[a] == s2[a] or s1[a] == 1 or s2[a] == 1 + for a in range(in1.ndim) if a not in axes): + raise ValueError("incompatible shapes for in1 and in2:" + f" {s1} and {s2}") + + # Check that input sizes are compatible with 'valid' mode. + if _inputs_swap_needed(mode, s1, s2, axes=axes): + # Convolution is commutative; order doesn't have any effect on output. + in1, in2 = in2, in1 + + return in1, in2, axes + + +def _freq_domain_conv(in1, in2, axes, shape, calc_fast_len=False): + """Convolve two arrays in the frequency domain. + + This function implements only base the FFT-related operations. + Specifically, it converts the signals to the frequency domain, multiplies + them, then converts them back to the time domain. Calculations of axes, + shapes, convolution mode, etc. are implemented in higher level-functions, + such as `fftconvolve` and `oaconvolve`. Those functions should be used + instead of this one. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + axes : array_like of ints + Axes over which to compute the FFTs. + shape : array_like of ints + The sizes of the FFTs. + calc_fast_len : bool, optional + If `True`, set each value of `shape` to the next fast FFT length. + Default is `False`, use `axes` as-is. + + Returns + ------- + out : array + An N-dimensional array containing the discrete linear convolution of + `in1` with `in2`. + + """ + if not len(axes): + return in1 * in2 + + complex_result = (in1.dtype.kind == 'c' or in2.dtype.kind == 'c') + + if calc_fast_len: + # Speed up FFT by padding to optimal size. + fshape = [ + sp_fft.next_fast_len(shape[a], not complex_result) for a in axes] + else: + fshape = shape + + if not complex_result: + fft, ifft = sp_fft.rfftn, sp_fft.irfftn + else: + fft, ifft = sp_fft.fftn, sp_fft.ifftn + + sp1 = fft(in1, fshape, axes=axes) + sp2 = fft(in2, fshape, axes=axes) + + ret = ifft(sp1 * sp2, fshape, axes=axes) + + if calc_fast_len: + fslice = tuple([slice(sz) for sz in shape]) + ret = ret[fslice] + + return ret + + +def _apply_conv_mode(ret, s1, s2, mode, axes): + """Calculate the convolution result shape based on the `mode` argument. + + Returns the result sliced to the correct size for the given mode. + + Parameters + ---------- + ret : array + The result array, with the appropriate shape for the 'full' mode. + s1 : list of int + The shape of the first input. + s2 : list of int + The shape of the second input. + mode : str {'full', 'valid', 'same'} + A string indicating the size of the output. + See the documentation `fftconvolve` for more information. + axes : list of ints + Axes over which to compute the convolution. + + Returns + ------- + ret : array + A copy of `res`, sliced to the correct size for the given `mode`. + + """ + if mode == "full": + return ret.copy() + elif mode == "same": + return _centered(ret, s1).copy() + elif mode == "valid": + shape_valid = [ret.shape[a] if a not in axes else s1[a] - s2[a] + 1 + for a in range(ret.ndim)] + return _centered(ret, shape_valid).copy() + else: + raise ValueError("acceptable mode flags are 'valid'," + " 'same', or 'full'") + + +def fftconvolve(in1, in2, mode="full", axes=None): + """Convolve two N-dimensional arrays using FFT. + + Convolve `in1` and `in2` using the fast Fourier transform method, with + the output size determined by the `mode` argument. + + This is generally much faster than `convolve` for large arrays (n > ~500), + but can be slower when only a few output values are needed, and can only + output float arrays (int or object array inputs will be cast to float). + + As of v0.19, `convolve` automatically chooses this method or the direct + method based on an estimation of which is faster. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + axes : int or array_like of ints or None, optional + Axes over which to compute the convolution. + The default is over all axes. + + Returns + ------- + out : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + See Also + -------- + convolve : Uses the direct convolution or FFT convolution algorithm + depending on which is faster. + oaconvolve : Uses the overlap-add method to do convolution, which is + generally faster when the input arrays are large and + significantly different in size. + + Examples + -------- + Autocorrelation of white noise is an impulse. + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> sig = rng.standard_normal(1000) + >>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full') + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('White noise') + >>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr) + >>> ax_mag.set_title('Autocorrelation') + >>> fig.tight_layout() + >>> fig.show() + + Gaussian blur implemented using FFT convolution. Notice the dark borders + around the image, due to the zero-padding beyond its boundaries. + The `convolve2d` function allows for other types of image boundaries, + but is far slower. + + >>> from scipy import datasets + >>> face = datasets.face(gray=True) + >>> kernel = np.outer(signal.windows.gaussian(70, 8), + ... signal.windows.gaussian(70, 8)) + >>> blurred = signal.fftconvolve(face, kernel, mode='same') + + >>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(3, 1, + ... figsize=(6, 15)) + >>> ax_orig.imshow(face, cmap='gray') + >>> ax_orig.set_title('Original') + >>> ax_orig.set_axis_off() + >>> ax_kernel.imshow(kernel, cmap='gray') + >>> ax_kernel.set_title('Gaussian kernel') + >>> ax_kernel.set_axis_off() + >>> ax_blurred.imshow(blurred, cmap='gray') + >>> ax_blurred.set_title('Blurred') + >>> ax_blurred.set_axis_off() + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if in1.ndim == in2.ndim == 0: # scalar inputs + return in1 * in2 + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + elif in1.size == 0 or in2.size == 0: # empty arrays + return np.array([]) + + in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes, + sorted_axes=False) + + s1 = in1.shape + s2 = in2.shape + + shape = [max((s1[i], s2[i])) if i not in axes else s1[i] + s2[i] - 1 + for i in range(in1.ndim)] + + ret = _freq_domain_conv(in1, in2, axes, shape, calc_fast_len=True) + + return _apply_conv_mode(ret, s1, s2, mode, axes) + + +def _calc_oa_lens(s1, s2): + """Calculate the optimal FFT lengths for overlap-add convolution. + + The calculation is done for a single dimension. + + Parameters + ---------- + s1 : int + Size of the dimension for the first array. + s2 : int + Size of the dimension for the second array. + + Returns + ------- + block_size : int + The size of the FFT blocks. + overlap : int + The amount of overlap between two blocks. + in1_step : int + The size of each step for the first array. + in2_step : int + The size of each step for the first array. + + """ + # Set up the arguments for the conventional FFT approach. + fallback = (s1+s2-1, None, s1, s2) + + # Use conventional FFT convolve if sizes are same. + if s1 == s2 or s1 == 1 or s2 == 1: + return fallback + + if s2 > s1: + s1, s2 = s2, s1 + swapped = True + else: + swapped = False + + # There cannot be a useful block size if s2 is more than half of s1. + if s2 >= s1/2: + return fallback + + # Derivation of optimal block length + # For original formula see: + # https://en.wikipedia.org/wiki/Overlap-add_method + # + # Formula: + # K = overlap = s2-1 + # N = block_size + # C = complexity + # e = exponential, exp(1) + # + # C = (N*(log2(N)+1))/(N-K) + # C = (N*log2(2N))/(N-K) + # C = N/(N-K) * log2(2N) + # C1 = N/(N-K) + # C2 = log2(2N) = ln(2N)/ln(2) + # + # dC1/dN = (1*(N-K)-N)/(N-K)^2 = -K/(N-K)^2 + # dC2/dN = 2/(2*N*ln(2)) = 1/(N*ln(2)) + # + # dC/dN = dC1/dN*C2 + dC2/dN*C1 + # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + N/(N*ln(2)*(N-K)) + # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + 1/(ln(2)*(N-K)) + # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + (N-K)/(ln(2)*(N-K)^2) + # dC/dN = (-K*ln(2N) + (N-K)/(ln(2)*(N-K)^2) + # dC/dN = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2) + # + # Solve for minimum, where dC/dN = 0 + # 0 = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2) + # 0 * ln(2)*(N-K)^2 = N - K*ln(2N) - K + # 0 = N - K*ln(2N) - K + # 0 = N - K*(ln(2N) + 1) + # 0 = N - K*ln(2Ne) + # N = K*ln(2Ne) + # N/K = ln(2Ne) + # + # e^(N/K) = e^ln(2Ne) + # e^(N/K) = 2Ne + # 1/e^(N/K) = 1/(2*N*e) + # e^(N/-K) = 1/(2*N*e) + # e^(N/-K) = K/N*1/(2*K*e) + # N/K*e^(N/-K) = 1/(2*e*K) + # N/-K*e^(N/-K) = -1/(2*e*K) + # + # Using Lambert W function + # https://en.wikipedia.org/wiki/Lambert_W_function + # x = W(y) It is the solution to y = x*e^x + # x = N/-K + # y = -1/(2*e*K) + # + # N/-K = W(-1/(2*e*K)) + # + # N = -K*W(-1/(2*e*K)) + overlap = s2-1 + opt_size = -overlap*lambertw(-1/(2*math.e*overlap), k=-1).real + block_size = sp_fft.next_fast_len(math.ceil(opt_size)) + + # Use conventional FFT convolve if there is only going to be one block. + if block_size >= s1: + return fallback + + if not swapped: + in1_step = block_size-s2+1 + in2_step = s2 + else: + in1_step = s2 + in2_step = block_size-s2+1 + + return block_size, overlap, in1_step, in2_step + + +def oaconvolve(in1, in2, mode="full", axes=None): + """Convolve two N-dimensional arrays using the overlap-add method. + + Convolve `in1` and `in2` using the overlap-add method, with + the output size determined by the `mode` argument. + + This is generally much faster than `convolve` for large arrays (n > ~500), + and generally much faster than `fftconvolve` when one array is much + larger than the other, but can be slower when only a few output values are + needed or when the arrays are very similar in shape, and can only + output float arrays (int or object array inputs will be cast to float). + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + axes : int or array_like of ints or None, optional + Axes over which to compute the convolution. + The default is over all axes. + + Returns + ------- + out : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + See Also + -------- + convolve : Uses the direct convolution or FFT convolution algorithm + depending on which is faster. + fftconvolve : An implementation of convolution using FFT. + + Notes + ----- + .. versionadded:: 1.4.0 + + References + ---------- + .. [1] Wikipedia, "Overlap-add_method". + https://en.wikipedia.org/wiki/Overlap-add_method + .. [2] Richard G. Lyons. Understanding Digital Signal Processing, + Third Edition, 2011. Chapter 13.10. + ISBN 13: 978-0137-02741-5 + + Examples + -------- + Convolve a 100,000 sample signal with a 512-sample filter. + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> sig = rng.standard_normal(100000) + >>> filt = signal.firwin(512, 0.01) + >>> fsig = signal.oaconvolve(sig, filt) + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('White noise') + >>> ax_mag.plot(fsig) + >>> ax_mag.set_title('Filtered noise') + >>> fig.tight_layout() + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if in1.ndim == in2.ndim == 0: # scalar inputs + return in1 * in2 + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + elif in1.size == 0 or in2.size == 0: # empty arrays + return np.array([]) + elif in1.shape == in2.shape: # Equivalent to fftconvolve + return fftconvolve(in1, in2, mode=mode, axes=axes) + + in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes, + sorted_axes=True) + + s1 = in1.shape + s2 = in2.shape + + if not axes: + ret = in1 * in2 + return _apply_conv_mode(ret, s1, s2, mode, axes) + + # Calculate this now since in1 is changed later + shape_final = [None if i not in axes else + s1[i] + s2[i] - 1 for i in range(in1.ndim)] + + # Calculate the block sizes for the output, steps, first and second inputs. + # It is simpler to calculate them all together than doing them in separate + # loops due to all the special cases that need to be handled. + optimal_sizes = ((-1, -1, s1[i], s2[i]) if i not in axes else + _calc_oa_lens(s1[i], s2[i]) for i in range(in1.ndim)) + block_size, overlaps, \ + in1_step, in2_step = zip(*optimal_sizes) + + # Fall back to fftconvolve if there is only one block in every dimension. + if in1_step == s1 and in2_step == s2: + return fftconvolve(in1, in2, mode=mode, axes=axes) + + # Figure out the number of steps and padding. + # This would get too complicated in a list comprehension. + nsteps1 = [] + nsteps2 = [] + pad_size1 = [] + pad_size2 = [] + for i in range(in1.ndim): + if i not in axes: + pad_size1 += [(0, 0)] + pad_size2 += [(0, 0)] + continue + + if s1[i] > in1_step[i]: + curnstep1 = math.ceil((s1[i]+1)/in1_step[i]) + if (block_size[i] - overlaps[i])*curnstep1 < shape_final[i]: + curnstep1 += 1 + + curpad1 = curnstep1*in1_step[i] - s1[i] + else: + curnstep1 = 1 + curpad1 = 0 + + if s2[i] > in2_step[i]: + curnstep2 = math.ceil((s2[i]+1)/in2_step[i]) + if (block_size[i] - overlaps[i])*curnstep2 < shape_final[i]: + curnstep2 += 1 + + curpad2 = curnstep2*in2_step[i] - s2[i] + else: + curnstep2 = 1 + curpad2 = 0 + + nsteps1 += [curnstep1] + nsteps2 += [curnstep2] + pad_size1 += [(0, curpad1)] + pad_size2 += [(0, curpad2)] + + # Pad the array to a size that can be reshaped to the desired shape + # if necessary. + if not all(curpad == (0, 0) for curpad in pad_size1): + in1 = np.pad(in1, pad_size1, mode='constant', constant_values=0) + + if not all(curpad == (0, 0) for curpad in pad_size2): + in2 = np.pad(in2, pad_size2, mode='constant', constant_values=0) + + # Reshape the overlap-add parts to input block sizes. + split_axes = [iax+i for i, iax in enumerate(axes)] + fft_axes = [iax+1 for iax in split_axes] + + # We need to put each new dimension before the corresponding dimension + # being reshaped in order to get the data in the right layout at the end. + reshape_size1 = list(in1_step) + reshape_size2 = list(in2_step) + for i, iax in enumerate(split_axes): + reshape_size1.insert(iax, nsteps1[i]) + reshape_size2.insert(iax, nsteps2[i]) + + in1 = in1.reshape(*reshape_size1) + in2 = in2.reshape(*reshape_size2) + + # Do the convolution. + fft_shape = [block_size[i] for i in axes] + ret = _freq_domain_conv(in1, in2, fft_axes, fft_shape, calc_fast_len=False) + + # Do the overlap-add. + for ax, ax_fft, ax_split in zip(axes, fft_axes, split_axes): + overlap = overlaps[ax] + if overlap is None: + continue + + ret, overpart = np.split(ret, [-overlap], ax_fft) + overpart = np.split(overpart, [-1], ax_split)[0] + + ret_overpart = np.split(ret, [overlap], ax_fft)[0] + ret_overpart = np.split(ret_overpart, [1], ax_split)[1] + ret_overpart += overpart + + # Reshape back to the correct dimensionality. + shape_ret = [ret.shape[i] if i not in fft_axes else + ret.shape[i]*ret.shape[i-1] + for i in range(ret.ndim) if i not in split_axes] + ret = ret.reshape(*shape_ret) + + # Slice to the correct size. + slice_final = tuple([slice(islice) for islice in shape_final]) + ret = ret[slice_final] + + return _apply_conv_mode(ret, s1, s2, mode, axes) + + +def _numeric_arrays(arrays, kinds='buifc'): + """ + See if a list of arrays are all numeric. + + Parameters + ---------- + arrays : array or list of arrays + arrays to check if numeric. + kinds : string-like + The dtypes of the arrays to be checked. If the dtype.kind of + the ndarrays are not in this string the function returns False and + otherwise returns True. + """ + if isinstance(arrays, np.ndarray): + return arrays.dtype.kind in kinds + for array_ in arrays: + if array_.dtype.kind not in kinds: + return False + return True + + +def _conv_ops(x_shape, h_shape, mode): + """ + Find the number of operations required for direct/fft methods of + convolution. The direct operations were recorded by making a dummy class to + record the number of operations by overriding ``__mul__`` and ``__add__``. + The FFT operations rely on the (well-known) computational complexity of the + FFT (and the implementation of ``_freq_domain_conv``). + + """ + if mode == "full": + out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)] + elif mode == "valid": + out_shape = [abs(n - k) + 1 for n, k in zip(x_shape, h_shape)] + elif mode == "same": + out_shape = x_shape + else: + raise ValueError("Acceptable mode flags are 'valid'," + f" 'same', or 'full', not mode={mode}") + + s1, s2 = x_shape, h_shape + if len(x_shape) == 1: + s1, s2 = s1[0], s2[0] + if mode == "full": + direct_ops = s1 * s2 + elif mode == "valid": + direct_ops = (s2 - s1 + 1) * s1 if s2 >= s1 else (s1 - s2 + 1) * s2 + elif mode == "same": + direct_ops = (s1 * s2 if s1 < s2 else + s1 * s2 - (s2 // 2) * ((s2 + 1) // 2)) + else: + if mode == "full": + direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape) + elif mode == "valid": + direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape) + elif mode == "same": + direct_ops = _prod(s1) * _prod(s2) + + full_out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)] + N = _prod(full_out_shape) + fft_ops = 3 * N * np.log(N) # 3 separate FFTs of size full_out_shape + return fft_ops, direct_ops + + +def _fftconv_faster(x, h, mode): + """ + See if using fftconvolve or convolve is faster. + + Parameters + ---------- + x : np.ndarray + Signal + h : np.ndarray + Kernel + mode : str + Mode passed to convolve + + Returns + ------- + fft_faster : bool + + Notes + ----- + See docstring of `choose_conv_method` for details on tuning hardware. + + See pull request 11031 for more detail: + https://github.com/scipy/scipy/pull/11031. + + """ + fft_ops, direct_ops = _conv_ops(x.shape, h.shape, mode) + offset = -1e-3 if x.ndim == 1 else -1e-4 + constants = { + "valid": (1.89095737e-9, 2.1364985e-10, offset), + "full": (1.7649070e-9, 2.1414831e-10, offset), + "same": (3.2646654e-9, 2.8478277e-10, offset) + if h.size <= x.size + else (3.21635404e-9, 1.1773253e-8, -1e-5), + } if x.ndim == 1 else { + "valid": (1.85927e-9, 2.11242e-8, offset), + "full": (1.99817e-9, 1.66174e-8, offset), + "same": (2.04735e-9, 1.55367e-8, offset), + } + O_fft, O_direct, O_offset = constants[mode] + return O_fft * fft_ops < O_direct * direct_ops + O_offset + + +def _reverse_and_conj(x): + """ + Reverse array `x` in all dimensions and perform the complex conjugate + """ + reverse = (slice(None, None, -1),) * x.ndim + return x[reverse].conj() + + +def _np_conv_ok(volume, kernel, mode): + """ + See if numpy supports convolution of `volume` and `kernel` (i.e. both are + 1D ndarrays and of the appropriate shape). NumPy's 'same' mode uses the + size of the larger input, while SciPy's uses the size of the first input. + + Invalid mode strings will return False and be caught by the calling func. + """ + if volume.ndim == kernel.ndim == 1: + if mode in ('full', 'valid'): + return True + elif mode == 'same': + return volume.size >= kernel.size + else: + return False + + +def _timeit_fast(stmt="pass", setup="pass", repeat=3): + """ + Returns the time the statement/function took, in seconds. + + Faster, less precise version of IPython's timeit. `stmt` can be a statement + written as a string or a callable. + + Will do only 1 loop (like IPython's timeit) with no repetitions + (unlike IPython) for very slow functions. For fast functions, only does + enough loops to take 5 ms, which seems to produce similar results (on + Windows at least), and avoids doing an extraneous cycle that isn't + measured. + + """ + timer = timeit.Timer(stmt, setup) + + # determine number of calls per rep so total time for 1 rep >= 5 ms + x = 0 + for p in range(0, 10): + number = 10**p + x = timer.timeit(number) # seconds + if x >= 5e-3 / 10: # 5 ms for final test, 1/10th that for this one + break + if x > 1: # second + # If it's macroscopic, don't bother with repetitions + best = x + else: + number *= 10 + r = timer.repeat(repeat, number) + best = min(r) + + sec = best / number + return sec + + +def choose_conv_method(in1, in2, mode='full', measure=False): + """ + Find the fastest convolution/correlation method. + + This primarily exists to be called during the ``method='auto'`` option in + `convolve` and `correlate`. It can also be used to determine the value of + ``method`` for many different convolutions of the same dtype/shape. + In addition, it supports timing the convolution to adapt the value of + ``method`` to a particular set of inputs and/or hardware. + + Parameters + ---------- + in1 : array_like + The first argument passed into the convolution function. + in2 : array_like + The second argument passed into the convolution function. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + measure : bool, optional + If True, run and time the convolution of `in1` and `in2` with both + methods and return the fastest. If False (default), predict the fastest + method using precomputed values. + + Returns + ------- + method : str + A string indicating which convolution method is fastest, either + 'direct' or 'fft' + times : dict, optional + A dictionary containing the times (in seconds) needed for each method. + This value is only returned if ``measure=True``. + + See Also + -------- + convolve + correlate + + Notes + ----- + Generally, this method is 99% accurate for 2D signals and 85% accurate + for 1D signals for randomly chosen input sizes. For precision, use + ``measure=True`` to find the fastest method by timing the convolution. + This can be used to avoid the minimal overhead of finding the fastest + ``method`` later, or to adapt the value of ``method`` to a particular set + of inputs. + + Experiments were run on an Amazon EC2 r5a.2xlarge machine to test this + function. These experiments measured the ratio between the time required + when using ``method='auto'`` and the time required for the fastest method + (i.e., ``ratio = time_auto / min(time_fft, time_direct)``). In these + experiments, we found: + + * There is a 95% chance of this ratio being less than 1.5 for 1D signals + and a 99% chance of being less than 2.5 for 2D signals. + * The ratio was always less than 2.5/5 for 1D/2D signals respectively. + * This function is most inaccurate for 1D convolutions that take between 1 + and 10 milliseconds with ``method='direct'``. A good proxy for this + (at least in our experiments) is ``1e6 <= in1.size * in2.size <= 1e7``. + + The 2D results almost certainly generalize to 3D/4D/etc because the + implementation is the same (the 1D implementation is different). + + All the numbers above are specific to the EC2 machine. However, we did find + that this function generalizes fairly decently across hardware. The speed + tests were of similar quality (and even slightly better) than the same + tests performed on the machine to tune this function's numbers (a mid-2014 + 15-inch MacBook Pro with 16GB RAM and a 2.5GHz Intel i7 processor). + + There are cases when `fftconvolve` supports the inputs but this function + returns `direct` (e.g., to protect against floating point integer + precision). + + .. versionadded:: 0.19 + + Examples + -------- + Estimate the fastest method for a given input: + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> img = rng.random((32, 32)) + >>> filter = rng.random((8, 8)) + >>> method = signal.choose_conv_method(img, filter, mode='same') + >>> method + 'fft' + + This can then be applied to other arrays of the same dtype and shape: + + >>> img2 = rng.random((32, 32)) + >>> filter2 = rng.random((8, 8)) + >>> corr2 = signal.correlate(img2, filter2, mode='same', method=method) + >>> conv2 = signal.convolve(img2, filter2, mode='same', method=method) + + The output of this function (``method``) works with `correlate` and + `convolve`. + + """ + volume = np.asarray(in1) + kernel = np.asarray(in2) + + _reject_objects(volume, 'choose_conv_method') + _reject_objects(kernel, 'choose_conv_method') + + if measure: + times = {} + for method in ['fft', 'direct']: + times[method] = _timeit_fast(lambda: convolve(volume, kernel, + mode=mode, method=method)) + + chosen_method = 'fft' if times['fft'] < times['direct'] else 'direct' + return chosen_method, times + + # for integer input, + # catch when more precision required than float provides (representing an + # integer as float can lose precision in fftconvolve if larger than 2**52) + if any([_numeric_arrays([x], kinds='ui') for x in [volume, kernel]]): + max_value = int(np.abs(volume).max()) * int(np.abs(kernel).max()) + max_value *= int(min(volume.size, kernel.size)) + if max_value > 2**np.finfo('float').nmant - 1: + return 'direct' + + if _numeric_arrays([volume, kernel], kinds='b'): + return 'direct' + + if _numeric_arrays([volume, kernel]): + if _fftconv_faster(volume, kernel, mode): + return 'fft' + + return 'direct' + + +def convolve(in1, in2, mode='full', method='auto'): + """ + Convolve two N-dimensional arrays. + + Convolve `in1` and `in2`, with the output size determined by the + `mode` argument. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + method : str {'auto', 'direct', 'fft'}, optional + A string indicating which method to use to calculate the convolution. + + ``direct`` + The convolution is determined directly from sums, the definition of + convolution. + ``fft`` + The Fourier Transform is used to perform the convolution by calling + `fftconvolve`. + ``auto`` + Automatically chooses direct or Fourier method based on an estimate + of which is faster (default). See Notes for more detail. + + .. versionadded:: 0.19.0 + + Returns + ------- + convolve : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + Warns + ----- + RuntimeWarning + Use of the FFT convolution on input containing NAN or INF will lead + to the entire output being NAN or INF. Use method='direct' when your + input contains NAN or INF values. + + See Also + -------- + numpy.polymul : performs polynomial multiplication (same operation, but + also accepts poly1d objects) + choose_conv_method : chooses the fastest appropriate convolution method + fftconvolve : Always uses the FFT method. + oaconvolve : Uses the overlap-add method to do convolution, which is + generally faster when the input arrays are large and + significantly different in size. + + Notes + ----- + By default, `convolve` and `correlate` use ``method='auto'``, which calls + `choose_conv_method` to choose the fastest method using pre-computed + values (`choose_conv_method` can also measure real-world timing with a + keyword argument). Because `fftconvolve` relies on floating point numbers, + there are certain constraints that may force ``method='direct'`` (more detail + in `choose_conv_method` docstring). + + Examples + -------- + Smooth a square pulse using a Hann window: + + >>> import numpy as np + >>> from scipy import signal + >>> sig = np.repeat([0., 1., 0.], 100) + >>> win = signal.windows.hann(50) + >>> filtered = signal.convolve(sig, win, mode='same') / sum(win) + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_win, ax_filt) = plt.subplots(3, 1, sharex=True) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('Original pulse') + >>> ax_orig.margins(0, 0.1) + >>> ax_win.plot(win) + >>> ax_win.set_title('Filter impulse response') + >>> ax_win.margins(0, 0.1) + >>> ax_filt.plot(filtered) + >>> ax_filt.set_title('Filtered signal') + >>> ax_filt.margins(0, 0.1) + >>> fig.tight_layout() + >>> fig.show() + + """ + volume = np.asarray(in1) + kernel = np.asarray(in2) + + _reject_objects(volume, 'correlate') + _reject_objects(kernel, 'correlate') + + if volume.ndim == kernel.ndim == 0: + return volume * kernel + elif volume.ndim != kernel.ndim: + raise ValueError("volume and kernel should have the same " + "dimensionality") + + if _inputs_swap_needed(mode, volume.shape, kernel.shape): + # Convolution is commutative; order doesn't have any effect on output + volume, kernel = kernel, volume + + if method == 'auto': + method = choose_conv_method(volume, kernel, mode=mode) + + if method == 'fft': + out = fftconvolve(volume, kernel, mode=mode) + result_type = np.result_type(volume, kernel) + if result_type.kind in {'u', 'i'}: + out = np.around(out) + + if np.isnan(out.flat[0]) or np.isinf(out.flat[0]): + warnings.warn("Use of fft convolution on input with NAN or inf" + " results in NAN or inf output. Consider using" + " method='direct' instead.", + category=RuntimeWarning, stacklevel=2) + + return out.astype(result_type) + elif method == 'direct': + # fastpath to faster numpy.convolve for 1d inputs when possible + if _np_conv_ok(volume, kernel, mode): + return np.convolve(volume, kernel, mode) + + return correlate(volume, _reverse_and_conj(kernel), mode, 'direct') + else: + raise ValueError("Acceptable method flags are 'auto'," + " 'direct', or 'fft'.") + + +def order_filter(a, domain, rank): + """ + Perform an order filter on an N-D array. + + Perform an order filter on the array in. The domain argument acts as a + mask centered over each pixel. The non-zero elements of domain are + used to select elements surrounding each input pixel which are placed + in a list. The list is sorted, and the output for that pixel is the + element corresponding to rank in the sorted list. + + Parameters + ---------- + a : ndarray + The N-dimensional input array. + domain : array_like + A mask array with the same number of dimensions as `a`. + Each dimension should have an odd number of elements. + rank : int + A non-negative integer which selects the element from the + sorted list (0 corresponds to the smallest element, 1 is the + next smallest element, etc.). + + Returns + ------- + out : ndarray + The results of the order filter in an array with the same + shape as `a`. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> x = np.arange(25).reshape(5, 5) + >>> domain = np.identity(3) + >>> x + 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, 24]]) + >>> signal.order_filter(x, domain, 0) + array([[ 0, 0, 0, 0, 0], + [ 0, 0, 1, 2, 0], + [ 0, 5, 6, 7, 0], + [ 0, 10, 11, 12, 0], + [ 0, 0, 0, 0, 0]]) + >>> signal.order_filter(x, domain, 2) + array([[ 6, 7, 8, 9, 4], + [ 11, 12, 13, 14, 9], + [ 16, 17, 18, 19, 14], + [ 21, 22, 23, 24, 19], + [ 20, 21, 22, 23, 24]]) + + """ + domain = np.asarray(domain) + for dimsize in domain.shape: + if (dimsize % 2) != 1: + raise ValueError("Each dimension of domain argument " + "should have an odd number of elements.") + + a = np.asarray(a) + if not (np.issubdtype(a.dtype, np.integer) + or a.dtype in [np.float32, np.float64]): + raise ValueError(f"dtype={a.dtype} is not supported by order_filter") + + result = ndimage.rank_filter(a, rank, footprint=domain, mode='constant') + return result + + +def medfilt(volume, kernel_size=None): + """ + Perform a median filter on an N-dimensional array. + + Apply a median filter to the input array using a local window-size + given by `kernel_size`. The array will automatically be zero-padded. + + Parameters + ---------- + volume : array_like + An N-dimensional input array. + kernel_size : array_like, optional + A scalar or an N-length list giving the size of the median filter + window in each dimension. Elements of `kernel_size` should be odd. + If `kernel_size` is a scalar, then this scalar is used as the size in + each dimension. Default size is 3 for each dimension. + + Returns + ------- + out : ndarray + An array the same size as input containing the median filtered + result. + + Warns + ----- + UserWarning + If array size is smaller than kernel size along any dimension + + See Also + -------- + scipy.ndimage.median_filter + scipy.signal.medfilt2d + + Notes + ----- + The more general function `scipy.ndimage.median_filter` has a more + efficient implementation of a median filter and therefore runs much faster. + + For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes, + the specialised function `scipy.signal.medfilt2d` may be faster. + + """ + volume = np.atleast_1d(volume) + if not (np.issubdtype(volume.dtype, np.integer) + or volume.dtype in [np.float32, np.float64]): + raise ValueError(f"dtype={volume.dtype} is not supported by medfilt") + + if kernel_size is None: + kernel_size = [3] * volume.ndim + kernel_size = np.asarray(kernel_size) + if kernel_size.shape == (): + kernel_size = np.repeat(kernel_size.item(), volume.ndim) + + for k in range(volume.ndim): + if (kernel_size[k] % 2) != 1: + raise ValueError("Each element of kernel_size should be odd.") + if any(k > s for k, s in zip(kernel_size, volume.shape)): + warnings.warn('kernel_size exceeds volume extent: the volume will be ' + 'zero-padded.', + stacklevel=2) + + size = math.prod(kernel_size) + result = ndimage.rank_filter(volume, size // 2, size=kernel_size, + mode='constant') + + return result + + +def wiener(im, mysize=None, noise=None): + """ + Perform a Wiener filter on an N-dimensional array. + + Apply a Wiener filter to the N-dimensional array `im`. + + Parameters + ---------- + im : ndarray + An N-dimensional array. + mysize : int or array_like, optional + A scalar or an N-length list giving the size of the Wiener filter + window in each dimension. Elements of mysize should be odd. + If mysize is a scalar, then this scalar is used as the size + in each dimension. + noise : float, optional + The noise-power to use. If None, then noise is estimated as the + average of the local variance of the input. + + Returns + ------- + out : ndarray + Wiener filtered result with the same shape as `im`. + + Notes + ----- + This implementation is similar to wiener2 in Matlab/Octave. + For more details see [1]_ + + References + ---------- + .. [1] Lim, Jae S., Two-Dimensional Signal and Image Processing, + Englewood Cliffs, NJ, Prentice Hall, 1990, p. 548. + + Examples + -------- + >>> from scipy.datasets import face + >>> from scipy.signal import wiener + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> img = rng.random((40, 40)) #Create a random image + >>> filtered_img = wiener(img, (5, 5)) #Filter the image + >>> f, (plot1, plot2) = plt.subplots(1, 2) + >>> plot1.imshow(img) + >>> plot2.imshow(filtered_img) + >>> plt.show() + + """ + im = np.asarray(im) + if mysize is None: + mysize = [3] * im.ndim + mysize = np.asarray(mysize) + if mysize.shape == (): + mysize = np.repeat(mysize.item(), im.ndim) + + # Estimate the local mean + size = math.prod(mysize) + lMean = correlate(im, np.ones(mysize), 'same') / size + + # Estimate the local variance + lVar = (correlate(im ** 2, np.ones(mysize), 'same') / size - lMean ** 2) + + # Estimate the noise power if needed. + if noise is None: + noise = np.mean(np.ravel(lVar), axis=0) + + res = (im - lMean) + res *= (1 - noise / lVar) + res += lMean + out = np.where(lVar < noise, lMean, res) + + return out + + +def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0): + """ + Convolve two 2-dimensional arrays. + + Convolve `in1` and `in2` with output size determined by `mode`, and + boundary conditions determined by `boundary` and `fillvalue`. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + boundary : str {'fill', 'wrap', 'symm'}, optional + A flag indicating how to handle boundaries: + + ``fill`` + pad input arrays with fillvalue. (default) + ``wrap`` + circular boundary conditions. + ``symm`` + symmetrical boundary conditions. + + fillvalue : scalar, optional + Value to fill pad input arrays with. Default is 0. + + Returns + ------- + out : ndarray + A 2-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + Examples + -------- + Compute the gradient of an image by 2D convolution with a complex Scharr + operator. (Horizontal operator is real, vertical is imaginary.) Use + symmetric boundary condition to avoid creating edges at the image + boundaries. + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy import datasets + >>> ascent = datasets.ascent() + >>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j], + ... [-10+0j, 0+ 0j, +10 +0j], + ... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy + >>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same') + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15)) + >>> ax_orig.imshow(ascent, cmap='gray') + >>> ax_orig.set_title('Original') + >>> ax_orig.set_axis_off() + >>> ax_mag.imshow(np.absolute(grad), cmap='gray') + >>> ax_mag.set_title('Gradient magnitude') + >>> ax_mag.set_axis_off() + >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles + >>> ax_ang.set_title('Gradient orientation') + >>> ax_ang.set_axis_off() + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if not in1.ndim == in2.ndim == 2: + raise ValueError('convolve2d inputs must both be 2-D arrays') + + if _inputs_swap_needed(mode, in1.shape, in2.shape): + in1, in2 = in2, in1 + + val = _valfrommode(mode) + bval = _bvalfromboundary(boundary) + out = _sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue) + return out + + +def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0): + """ + Cross-correlate two 2-dimensional arrays. + + Cross correlate `in1` and `in2` with output size determined by `mode`, and + boundary conditions determined by `boundary` and `fillvalue`. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear cross-correlation + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + boundary : str {'fill', 'wrap', 'symm'}, optional + A flag indicating how to handle boundaries: + + ``fill`` + pad input arrays with fillvalue. (default) + ``wrap`` + circular boundary conditions. + ``symm`` + symmetrical boundary conditions. + + fillvalue : scalar, optional + Value to fill pad input arrays with. Default is 0. + + Returns + ------- + correlate2d : ndarray + A 2-dimensional array containing a subset of the discrete linear + cross-correlation of `in1` with `in2`. + + Notes + ----- + When using "same" mode with even-length inputs, the outputs of `correlate` + and `correlate2d` differ: There is a 1-index offset between them. + + Examples + -------- + Use 2D cross-correlation to find the location of a template in a noisy + image: + + >>> import numpy as np + >>> from scipy import signal, datasets, ndimage + >>> rng = np.random.default_rng() + >>> face = datasets.face(gray=True) - datasets.face(gray=True).mean() + >>> face = ndimage.zoom(face[30:500, 400:950], 0.5) # extract the face + >>> template = np.copy(face[135:165, 140:175]) # right eye + >>> template -= template.mean() + >>> face = face + rng.standard_normal(face.shape) * 50 # add noise + >>> corr = signal.correlate2d(face, template, boundary='symm', mode='same') + >>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1, + ... figsize=(6, 15)) + >>> ax_orig.imshow(face, cmap='gray') + >>> ax_orig.set_title('Original') + >>> ax_orig.set_axis_off() + >>> ax_template.imshow(template, cmap='gray') + >>> ax_template.set_title('Template') + >>> ax_template.set_axis_off() + >>> ax_corr.imshow(corr, cmap='gray') + >>> ax_corr.set_title('Cross-correlation') + >>> ax_corr.set_axis_off() + >>> ax_orig.plot(x, y, 'ro') + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if not in1.ndim == in2.ndim == 2: + raise ValueError('correlate2d inputs must both be 2-D arrays') + + swapped_inputs = _inputs_swap_needed(mode, in1.shape, in2.shape) + if swapped_inputs: + in1, in2 = in2, in1 + + val = _valfrommode(mode) + bval = _bvalfromboundary(boundary) + out = _sigtools._convolve2d(in1, in2.conj(), 0, val, bval, fillvalue) + + if swapped_inputs: + out = out[::-1, ::-1] + + return out + + +def medfilt2d(input, kernel_size=3): + """ + Median filter a 2-dimensional array. + + Apply a median filter to the `input` array using a local window-size + given by `kernel_size` (must be odd). The array is zero-padded + automatically. + + Parameters + ---------- + input : array_like + A 2-dimensional input array. + kernel_size : array_like, optional + A scalar or a list of length 2, giving the size of the + median filter window in each dimension. Elements of + `kernel_size` should be odd. If `kernel_size` is a scalar, + then this scalar is used as the size in each dimension. + Default is a kernel of size (3, 3). + + Returns + ------- + out : ndarray + An array the same size as input containing the median filtered + result. + + See Also + -------- + scipy.ndimage.median_filter + + Notes + ----- + This is faster than `medfilt` when the input dtype is ``uint8``, + ``float32``, or ``float64``; for other types, this falls back to + `medfilt`. In some situations, `scipy.ndimage.median_filter` may be + faster than this function. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> x = np.arange(25).reshape(5, 5) + >>> x + 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, 24]]) + + # Replaces i,j with the median out of 5*5 window + + >>> signal.medfilt2d(x, kernel_size=5) + array([[ 0, 0, 2, 0, 0], + [ 0, 3, 7, 4, 0], + [ 2, 8, 12, 9, 4], + [ 0, 8, 12, 9, 0], + [ 0, 0, 12, 0, 0]]) + + # Replaces i,j with the median out of default 3*3 window + + >>> signal.medfilt2d(x) + array([[ 0, 1, 2, 3, 0], + [ 1, 6, 7, 8, 4], + [ 6, 11, 12, 13, 9], + [11, 16, 17, 18, 14], + [ 0, 16, 17, 18, 0]]) + + # Replaces i,j with the median out of default 5*3 window + + >>> signal.medfilt2d(x, kernel_size=[5,3]) + array([[ 0, 1, 2, 3, 0], + [ 0, 6, 7, 8, 3], + [ 5, 11, 12, 13, 8], + [ 5, 11, 12, 13, 8], + [ 0, 11, 12, 13, 0]]) + + # Replaces i,j with the median out of default 3*5 window + + >>> signal.medfilt2d(x, kernel_size=[3,5]) + array([[ 0, 0, 2, 1, 0], + [ 1, 5, 7, 6, 3], + [ 6, 10, 12, 11, 8], + [11, 15, 17, 16, 13], + [ 0, 15, 17, 16, 0]]) + + # As seen in the examples, + # kernel numbers must be odd and not exceed original array dim + + """ + image = np.asarray(input) + + # checking dtype.type, rather than just dtype, is necessary for + # excluding np.longdouble with MS Visual C. + if image.dtype.type not in (np.ubyte, np.float32, np.float64): + return medfilt(image, kernel_size) + + if kernel_size is None: + kernel_size = [3] * 2 + kernel_size = np.asarray(kernel_size) + if kernel_size.shape == (): + kernel_size = np.repeat(kernel_size.item(), 2) + + for size in kernel_size: + if (size % 2) != 1: + raise ValueError("Each element of kernel_size should be odd.") + + return _sigtools._medfilt2d(image, kernel_size) + + +def lfilter(b, a, x, axis=-1, zi=None): + """ + Filter data along one-dimension with an IIR or FIR filter. + + Filter a data sequence, `x`, using a digital filter. This works for many + fundamental data types (including Object type). The filter is a direct + form II transposed implementation of the standard difference equation + (see Notes). + + The function `sosfilt` (and filter design using ``output='sos'``) should be + preferred over `lfilter` for most filtering tasks, as second-order sections + have fewer numerical problems. + + Parameters + ---------- + b : array_like + The numerator coefficient vector in a 1-D sequence. + a : array_like + The denominator coefficient vector in a 1-D sequence. If ``a[0]`` + is not 1, then both `a` and `b` are normalized by ``a[0]``. + x : array_like + An N-dimensional input array. + axis : int, optional + The axis of the input data array along which to apply the + linear filter. The filter is applied to each subarray along + this axis. Default is -1. + zi : array_like, optional + Initial conditions for the filter delays. It is a vector + (or array of vectors for an N-dimensional input) of length + ``max(len(a), len(b)) - 1``. If `zi` is None or is not given then + initial rest is assumed. See `lfiltic` for more information. + + Returns + ------- + y : array + The output of the digital filter. + zf : array, optional + If `zi` is None, this is not returned, otherwise, `zf` holds the + final filter delay values. + + See Also + -------- + lfiltic : Construct initial conditions for `lfilter`. + lfilter_zi : Compute initial state (steady state of step response) for + `lfilter`. + filtfilt : A forward-backward filter, to obtain a filter with zero phase. + savgol_filter : A Savitzky-Golay filter. + sosfilt: Filter data using cascaded second-order sections. + sosfiltfilt: A forward-backward filter using second-order sections. + + Notes + ----- + The filter function is implemented as a direct II transposed structure. + This means that the filter implements:: + + a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M] + - a[1]*y[n-1] - ... - a[N]*y[n-N] + + where `M` is the degree of the numerator, `N` is the degree of the + denominator, and `n` is the sample number. It is implemented using + the following difference equations (assuming M = N):: + + a[0]*y[n] = b[0] * x[n] + d[0][n-1] + d[0][n] = b[1] * x[n] - a[1] * y[n] + d[1][n-1] + d[1][n] = b[2] * x[n] - a[2] * y[n] + d[2][n-1] + ... + d[N-2][n] = b[N-1]*x[n] - a[N-1]*y[n] + d[N-1][n-1] + d[N-1][n] = b[N] * x[n] - a[N] * y[n] + + where `d` are the state variables. + + The rational transfer function describing this filter in the + z-transform domain is:: + + -1 -M + b[0] + b[1]z + ... + b[M] z + Y(z) = -------------------------------- X(z) + -1 -N + a[0] + a[1]z + ... + a[N] z + + Examples + -------- + Generate a noisy signal to be filtered: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> t = np.linspace(-1, 1, 201) + >>> x = (np.sin(2*np.pi*0.75*t*(1-t) + 2.1) + + ... 0.1*np.sin(2*np.pi*1.25*t + 1) + + ... 0.18*np.cos(2*np.pi*3.85*t)) + >>> xn = x + rng.standard_normal(len(t)) * 0.08 + + Create an order 3 lowpass butterworth filter: + + >>> b, a = signal.butter(3, 0.05) + + Apply the filter to xn. Use lfilter_zi to choose the initial condition of + the filter: + + >>> zi = signal.lfilter_zi(b, a) + >>> z, _ = signal.lfilter(b, a, xn, zi=zi*xn[0]) + + Apply the filter again, to have a result filtered at an order the same as + filtfilt: + + >>> z2, _ = signal.lfilter(b, a, z, zi=zi*z[0]) + + Use filtfilt to apply the filter: + + >>> y = signal.filtfilt(b, a, xn) + + Plot the original signal and the various filtered versions: + + >>> plt.figure + >>> plt.plot(t, xn, 'b', alpha=0.75) + >>> plt.plot(t, z, 'r--', t, z2, 'r', t, y, 'k') + >>> plt.legend(('noisy signal', 'lfilter, once', 'lfilter, twice', + ... 'filtfilt'), loc='best') + >>> plt.grid(True) + >>> plt.show() + + """ + b = np.atleast_1d(b) + a = np.atleast_1d(a) + + _reject_objects(x, 'lfilter') + _reject_objects(a, 'lfilter') + _reject_objects(b, 'lfilter') + + if len(a) == 1: + # This path only supports types fdgFDGO to mirror _linear_filter below. + # Any of b, a, x, or zi can set the dtype, but there is no default + # casting of other types; instead a NotImplementedError is raised. + b = np.asarray(b) + a = np.asarray(a) + if b.ndim != 1 and a.ndim != 1: + raise ValueError('object of too small depth for desired array') + x = _validate_x(x) + inputs = [b, a, x] + if zi is not None: + # _linear_filter does not broadcast zi, but does do expansion of + # singleton dims. + zi = np.asarray(zi) + if zi.ndim != x.ndim: + raise ValueError('object of too small depth for desired array') + expected_shape = list(x.shape) + expected_shape[axis] = b.shape[0] - 1 + expected_shape = tuple(expected_shape) + # check the trivial case where zi is the right shape first + if zi.shape != expected_shape: + strides = zi.ndim * [None] + if axis < 0: + axis += zi.ndim + for k in range(zi.ndim): + if k == axis and zi.shape[k] == expected_shape[k]: + strides[k] = zi.strides[k] + elif k != axis and zi.shape[k] == expected_shape[k]: + strides[k] = zi.strides[k] + elif k != axis and zi.shape[k] == 1: + strides[k] = 0 + else: + raise ValueError('Unexpected shape for zi: expected ' + f'{expected_shape}, found {zi.shape}.') + zi = np.lib.stride_tricks.as_strided(zi, expected_shape, + strides) + inputs.append(zi) + dtype = np.result_type(*inputs) + + if dtype.char not in 'fdgFDGO': + raise NotImplementedError(f"input type '{dtype}' not supported") + + b = np.array(b, dtype=dtype) + a = np.asarray(a, dtype=dtype) + b /= a[0] + x = np.asarray(x, dtype=dtype) + + out_full = np.apply_along_axis(lambda y: np.convolve(b, y), axis, x) + ind = out_full.ndim * [slice(None)] + if zi is not None: + ind[axis] = slice(zi.shape[axis]) + out_full[tuple(ind)] += zi + + ind[axis] = slice(out_full.shape[axis] - len(b) + 1) + out = out_full[tuple(ind)] + + if zi is None: + return out + else: + ind[axis] = slice(out_full.shape[axis] - len(b) + 1, None) + zf = out_full[tuple(ind)] + return out, zf + else: + if zi is None: + return _sigtools._linear_filter(b, a, x, axis) + else: + return _sigtools._linear_filter(b, a, x, axis, zi) + + +def lfiltic(b, a, y, x=None): + """ + Construct initial conditions for lfilter given input and output vectors. + + Given a linear filter (b, a) and initial conditions on the output `y` + and the input `x`, return the initial conditions on the state vector zi + which is used by `lfilter` to generate the output given the input. + + Parameters + ---------- + b : array_like + Linear filter term. + a : array_like + Linear filter term. + y : array_like + Initial conditions. + + If ``N = len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``. + + If `y` is too short, it is padded with zeros. + x : array_like, optional + Initial conditions. + + If ``M = len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``. + + If `x` is not given, its initial conditions are assumed zero. + + If `x` is too short, it is padded with zeros. + + Returns + ------- + zi : ndarray + The state vector ``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``, + where ``K = max(M, N)``. + + See Also + -------- + lfilter, lfilter_zi + + """ + N = np.size(a) - 1 + M = np.size(b) - 1 + K = max(M, N) + y = np.asarray(y) + + if x is None: + result_type = np.result_type(np.asarray(b), np.asarray(a), y) + if result_type.kind in 'bui': + result_type = np.float64 + x = np.zeros(M, dtype=result_type) + else: + x = np.asarray(x) + + result_type = np.result_type(np.asarray(b), np.asarray(a), y, x) + if result_type.kind in 'bui': + result_type = np.float64 + x = x.astype(result_type) + + L = np.size(x) + if L < M: + x = np.r_[x, np.zeros(M - L)] + + y = y.astype(result_type) + zi = np.zeros(K, result_type) + + L = np.size(y) + if L < N: + y = np.r_[y, np.zeros(N - L)] + + for m in range(M): + zi[m] = np.sum(b[m + 1:] * x[:M - m], axis=0) + + for m in range(N): + zi[m] -= np.sum(a[m + 1:] * y[:N - m], axis=0) + + return zi + + +def deconvolve(signal, divisor): + """Deconvolves ``divisor`` out of ``signal`` using inverse filtering. + + Returns the quotient and remainder such that + ``signal = convolve(divisor, quotient) + remainder`` + + Parameters + ---------- + signal : (N,) array_like + Signal data, typically a recorded signal + divisor : (N,) array_like + Divisor data, typically an impulse response or filter that was + applied to the original signal + + Returns + ------- + quotient : ndarray + Quotient, typically the recovered original signal + remainder : ndarray + Remainder + + See Also + -------- + numpy.polydiv : performs polynomial division (same operation, but + also accepts poly1d objects) + + Examples + -------- + Deconvolve a signal that's been filtered: + + >>> from scipy import signal + >>> original = [0, 1, 0, 0, 1, 1, 0, 0] + >>> impulse_response = [2, 1] + >>> recorded = signal.convolve(impulse_response, original) + >>> recorded + array([0, 2, 1, 0, 2, 3, 1, 0, 0]) + >>> recovered, remainder = signal.deconvolve(recorded, impulse_response) + >>> recovered + array([ 0., 1., 0., 0., 1., 1., 0., 0.]) + + """ + num = np.atleast_1d(signal) + den = np.atleast_1d(divisor) + if num.ndim > 1: + raise ValueError("signal must be 1-D.") + if den.ndim > 1: + raise ValueError("divisor must be 1-D.") + N = len(num) + D = len(den) + if D > N: + quot = [] + rem = num + else: + input = np.zeros(N - D + 1, float) + input[0] = 1 + quot = lfilter(num, den, input) + rem = num - convolve(den, quot, mode='full') + return quot, rem + + +def hilbert(x, N=None, axis=-1): + r"""FFT-based computation of the analytic signal. + + The analytic signal is calculated by filtering out the negative frequencies and + doubling the amplitudes of the positive frequencies in the FFT domain. + The imaginary part of the result is the hilbert transform of the real-valued input + signal. + + The transformation is done along the last axis by default. + + Parameters + ---------- + x : array_like + Signal data. Must be real. + N : int, optional + Number of Fourier components. Default: ``x.shape[axis]`` + axis : int, optional + Axis along which to do the transformation. Default: -1. + + Returns + ------- + xa : ndarray + Analytic signal of `x`, of each 1-D array along `axis` + + Notes + ----- + The analytic signal ``x_a(t)`` of a real-valued signal ``x(t)`` + can be expressed as [1]_ + + .. math:: x_a = F^{-1}(F(x) 2U) = x + i y\ , + + where `F` is the Fourier transform, `U` the unit step function, + and `y` the Hilbert transform of `x`. [2]_ + + In other words, the negative half of the frequency spectrum is zeroed + out, turning the real-valued signal into a complex-valued signal. The Hilbert + transformed signal can be obtained from ``np.imag(hilbert(x))``, and the + original signal from ``np.real(hilbert(x))``. + + References + ---------- + .. [1] Wikipedia, "Analytic signal". + https://en.wikipedia.org/wiki/Analytic_signal + .. [2] Wikipedia, "Hilbert Transform". + https://en.wikipedia.org/wiki/Hilbert_transform + .. [3] Leon Cohen, "Time-Frequency Analysis", 1995. Chapter 2. + .. [4] Alan V. Oppenheim, Ronald W. Schafer. Discrete-Time Signal + Processing, Third Edition, 2009. Chapter 12. + ISBN 13: 978-1292-02572-8 + + See Also + -------- + envelope: Compute envelope of a real- or complex-valued signal. + + Examples + -------- + In this example we use the Hilbert transform to determine the amplitude + envelope and instantaneous frequency of an amplitude-modulated signal. + + Let's create a chirp of which the frequency increases from 20 Hz to 100 Hz and + apply an amplitude modulation: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import hilbert, chirp + ... + >>> duration, fs = 1, 400 # 1 s signal with sampling frequency of 400 Hz + >>> t = np.arange(int(fs*duration)) / fs # timestamps of samples + >>> signal = chirp(t, 20.0, t[-1], 100.0) + >>> signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) ) + + The amplitude envelope is given by the magnitude of the analytic signal. The + instantaneous frequency can be obtained by differentiating the + instantaneous phase in respect to time. The instantaneous phase corresponds + to the phase angle of the analytic signal. + + >>> analytic_signal = hilbert(signal) + >>> amplitude_envelope = np.abs(analytic_signal) + >>> instantaneous_phase = np.unwrap(np.angle(analytic_signal)) + >>> instantaneous_frequency = np.diff(instantaneous_phase) / (2.0*np.pi) * fs + ... + >>> fig, (ax0, ax1) = plt.subplots(nrows=2, sharex='all', tight_layout=True) + >>> ax0.set_title("Amplitude-modulated Chirp Signal") + >>> ax0.set_ylabel("Amplitude") + >>> ax0.plot(t, signal, label='Signal') + >>> ax0.plot(t, amplitude_envelope, label='Envelope') + >>> ax0.legend() + >>> ax1.set(xlabel="Time in seconds", ylabel="Phase in rad", ylim=(0, 120)) + >>> ax1.plot(t[1:], instantaneous_frequency, 'C2-', label='Instantaneous Phase') + >>> ax1.legend() + >>> plt.show() + + """ + x = np.asarray(x) + if np.iscomplexobj(x): + raise ValueError("x must be real.") + if N is None: + N = x.shape[axis] + if N <= 0: + raise ValueError("N must be positive.") + + Xf = sp_fft.fft(x, N, axis=axis) + h = np.zeros(N, dtype=Xf.dtype) + if N % 2 == 0: + h[0] = h[N // 2] = 1 + h[1:N // 2] = 2 + else: + h[0] = 1 + h[1:(N + 1) // 2] = 2 + + if x.ndim > 1: + ind = [np.newaxis] * x.ndim + ind[axis] = slice(None) + h = h[tuple(ind)] + x = sp_fft.ifft(Xf * h, axis=axis) + return x + + +def hilbert2(x, N=None): + """ + Compute the '2-D' analytic signal of `x` + + Parameters + ---------- + x : array_like + 2-D signal data. + N : int or tuple of two ints, optional + Number of Fourier components. Default is ``x.shape`` + + Returns + ------- + xa : ndarray + Analytic signal of `x` taken along axes (0,1). + + References + ---------- + .. [1] Wikipedia, "Analytic signal", + https://en.wikipedia.org/wiki/Analytic_signal + + """ + x = np.atleast_2d(x) + if x.ndim > 2: + raise ValueError("x must be 2-D.") + if np.iscomplexobj(x): + raise ValueError("x must be real.") + if N is None: + N = x.shape + elif isinstance(N, int): + if N <= 0: + raise ValueError("N must be positive.") + N = (N, N) + elif len(N) != 2 or np.any(np.asarray(N) <= 0): + raise ValueError("When given as a tuple, N must hold exactly " + "two positive integers") + + Xf = sp_fft.fft2(x, N, axes=(0, 1)) + h1 = np.zeros(N[0], dtype=Xf.dtype) + h2 = np.zeros(N[1], dtype=Xf.dtype) + for h in (h1, h2): + N1 = h.shape[0] + if N1 % 2 == 0: + h[0] = h[N1 // 2] = 1 + h[1:N1 // 2] = 2 + else: + h[0] = 1 + h[1:(N1 + 1) // 2] = 2 + + h = h1[:, np.newaxis] * h2[np.newaxis, :] + k = x.ndim + while k > 2: + h = h[:, np.newaxis] + k -= 1 + x = sp_fft.ifft2(Xf * h, axes=(0, 1)) + return x + + +def envelope(z: np.ndarray, bp_in: tuple[int | None, int | None] = (1, None), *, + n_out: int | None = None, squared: bool = False, + residual: Literal['lowpass', 'all', None] = 'lowpass', + axis: int = -1) -> np.ndarray: + r"""Compute the envelope of a real- or complex-valued signal. + + Parameters + ---------- + z : ndarray + Real- or complex-valued input signal, which is assumed to be made up of ``n`` + samples and having sampling interval ``T``. `z` may also be a multidimensional + array with the time axis being defined by `axis`. + bp_in : tuple[int | None, int | None], optional + 2-tuple defining the frequency band ``bp_in[0]:bp_in[1]`` of the input filter. + The corner frequencies are specified as integer multiples of ``1/(n*T)`` with + ``-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2`` being the allowed frequency range. + ``None`` entries are replaced with ``-n//2`` or ``(n+1)//2`` respectively. The + default of ``(1, None)`` removes the mean value as well as the negative + frequency components. + n_out : int | None, optional + If not ``None`` the output will be resampled to `n_out` samples. The default + of ``None`` sets the output to the same length as the input `z`. + squared : bool, optional + If set, the square of the envelope is returned. The bandwidth of the squared + envelope is often smaller than the non-squared envelope bandwidth due to the + nonlinear nature of the utilized absolute value function. I.e., the embedded + square root function typically produces addiational harmonics. + The default is ``False``. + residual : Literal['lowpass', 'all', None], optional + This option determines what kind of residual, i.e., the signal part which the + input bandpass filter removes, is returned. ``'all'`` returns everything except + the contents of the frequency band ``bp_in[0]:bp_in[1]``, ``'lowpass'`` + returns the contents of the frequency band ``< bp_in[0]``. If ``None`` then + only the envelope is returned. Default: ``'lowpass'``. + axis : int, optional + Axis of `z` over which to compute the envelope. Default is last the axis. + + Returns + ------- + ndarray + If parameter `residual` is ``None`` then an array ``z_env`` with the same shape + as the input `z` is returned, containing its envelope. Otherwise, an array with + shape ``(2, *z.shape)``, containing the arrays ``z_env`` and ``z_res``, stacked + along the first axis, is returned. + It allows unpacking, i.e., ``z_env, z_res = envelope(z, residual='all')``. + The residual ``z_res`` contains the signal part which the input bandpass filter + removed, depending on the parameter `residual`. Note that for real-valued + signals, a real-valued residual is returned. Hence, the negative frequency + components of `bp_in` are ignored. + + Notes + ----- + Any complex-valued signal :math:`z(t)` can be described by a real-valued + instantaneous amplitude :math:`a(t)` and a real-valued instantaneous phase + :math:`\phi(t)`, i.e., :math:`z(t) = a(t) \exp\!\big(j \phi(t)\big)`. The + envelope is defined as the absolute value of the amplitude :math:`|a(t)| = |z(t)|`, + which is at the same time the absolute value of the signal. Hence, :math:`|a(t)|` + "envelopes" the class of all signals with amplitude :math:`a(t)` and arbitrary + phase :math:`\phi(t)`. + For real-valued signals, :math:`x(t) = a(t) \cos\!\big(\phi(t)\big)` is the + analogous formulation. Hence, :math:`|a(t)|` can be determined by converting + :math:`x(t)` into an analytic signal :math:`z_a(t)` by means of a Hilbert + transform, i.e., + :math:`z_a(t) = a(t) \cos\!\big(\phi(t)\big) + j a(t) \sin\!\big(\phi(t) \big)`, + which produces a complex-valued signal with the same envelope :math:`|a(t)|`. + + The implementation is based on computing the FFT of the input signal and then + performing the necessary operations in Fourier space. Hence, the typical FFT + caveats need to be taken into account: + + * The signal is assumed to be periodic. Discontinuities between signal start and + end can lead to unwanted results due to Gibbs phenomenon. + * The FFT is slow if the signal length is prime or very long. Also, the memory + demands are typically higher than a comparable FIR/IIR filter based + implementation. + * The frequency spacing ``1 / (n*T)`` for corner frequencies of the bandpass filter + corresponds to the frequencies produced by ``scipy.fft.fftfreq(len(z), T)``. + + If the envelope of a complex-valued signal `z` with no bandpass filtering is + desired, i.e., ``bp_in=(None, None)``, then the envelope corresponds to the + absolute value. Hence, it is more efficient to use ``np.abs(z)`` instead of this + function. + + Although computing the envelope based on the analytic signal [1]_ is the natural + method for real-valued signals, other methods are also frequently used. The most + popular alternative is probably the so-called "square-law" envelope detector and + its relatives [2]_. They do not always compute the correct result for all kinds of + signals, but are usually correct and typically computationally more efficient for + most kinds of narrowband signals. The definition for an envelope presented here is + common where instantaneous amplitude and phase are of interest (e.g., as described + in [3]_). There exist also other concepts, which rely on the general mathematical + idea of an envelope [4]_: A pragmatic approach is to determine all upper and lower + signal peaks and use a spline interpolation to determine the curves [5]_. + + + References + ---------- + .. [1] "Analytic Signal", Wikipedia, + https://en.wikipedia.org/wiki/Analytic_signal + .. [2] Lyons, Richard, "Digital envelope detection: The good, the bad, and the + ugly", IEEE Signal Processing Magazine 34.4 (2017): 183-187. + `PDF `__ + .. [3] T.G. Kincaid, "The complex representation of signals.", + TIS R67# MH5, General Electric Co. (1966). + `PDF `__ + .. [4] "Envelope (mathematics)", Wikipedia, + https://en.wikipedia.org/wiki/Envelope_(mathematics) + .. [5] Yang, Yanli. "A signal theoretic approach for envelope analysis of + real-valued signals." IEEE Access 5 (2017): 5623-5630. + `PDF `__ + + + See Also + -------- + hilbert: Compute analytic signal by means of Hilbert transform. + + + Examples + -------- + The following plot illustrates the envelope of a signal with variable frequency and + a low-frequency drift. To separate the drift from the envelope, a 4 Hz highpass + filter is used. The low-pass residuum of the input bandpass filter is utilized to + determine an asymmetric upper and lower bound to enclose the signal. Due to the + smoothness of the resulting envelope, it is down-sampled from 500 to 40 samples. + Note that the instantaneous amplitude ``a_x`` and the computed envelope ``x_env`` + are not perfectly identical. This is due to the signal not being perfectly periodic + as well as the existence of some spectral overlapping of ``x_carrier`` and + ``x_drift``. Hence, they cannot be completely separated by a bandpass filter. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal.windows import gaussian + >>> from scipy.signal import envelope + ... + >>> n, n_out = 500, 40 # number of signal samples and envelope samples + >>> T = 2 / n # sampling interval for 2 s duration + >>> t = np.arange(n) * T # time stamps + >>> a_x = gaussian(len(t), 0.4/T) # instantaneous amplitude + >>> phi_x = 30*np.pi*t + 35*np.cos(2*np.pi*0.25*t) # instantaneous phase + >>> x_carrier = a_x * np.cos(phi_x) + >>> x_drift = 0.3 * gaussian(len(t), 0.4/T) # drift + >>> x = x_carrier + x_drift + ... + >>> bp_in = (int(4 * (n*T)), None) # 4 Hz highpass input filter + >>> x_env, x_res = envelope(x, bp_in, n_out=n_out) + >>> t_out = np.arange(n_out) * (n / n_out) * T + ... + >>> fg0, ax0 = plt.subplots(1, 1, tight_layout=True) + >>> ax0.set_title(r"$4\,$Hz Highpass Envelope of Drifting Signal") + >>> ax0.set(xlabel="Time in seconds", xlim=(0, n*T), ylabel="Amplitude") + >>> ax0.plot(t, x, 'C0-', alpha=0.5, label="Signal") + >>> ax0.plot(t, x_drift, 'C2--', alpha=0.25, label="Drift") + >>> ax0.plot(t_out, x_res+x_env, 'C1.-', alpha=0.5, label="Envelope") + >>> ax0.plot(t_out, x_res-x_env, 'C1.-', alpha=0.5, label=None) + >>> ax0.grid(True) + >>> ax0.legend() + >>> plt.show() + + The second example provides a geometric envelope interpretation of complex-valued + signals: The following two plots show the complex-valued signal as a blue + 3d-trajectory and the envelope as an orange round tube with varying diameter, i.e., + as :math:`|a(t)| \exp(j\rho(t))`, with :math:`\rho(t)\in[-\pi,\pi]`. Also, the + projection into the 2d real and imaginary coordinate planes of trajectory and tube + is depicted. Every point of the complex-valued signal touches the tube's surface. + + The left plot shows an analytic signal, i.e, the phase difference between + imaginary and real part is always 90 degrees, resulting in a spiraling trajectory. + It can be seen that in this case the real part has also the expected envelope, + i.e., representing the absolute value of the instantaneous amplitude. + + The right plot shows the real part of that analytic signal being interpreted + as a complex-vauled signal, i.e., having zero imaginary part. There the resulting + envelope is not as smooth as in the analytic case and the instantaneous amplitude + in the real plane is not recovered. If ``z_re`` had been passed as a real-valued + signal, i.e., as ``z_re = z.real`` instead of ``z_re = z.real + 0j``, the result + would have been identical to the left plot. The reason for this is that real-valued + signals are interpreted as being the real part of a complex-valued analytic signal. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal.windows import gaussian + >>> from scipy.signal import envelope + ... + >>> n, T = 1000, 1/1000 # number of samples and sampling interval + >>> t = np.arange(n) * T # time stamps for 1 s duration + >>> f_c = 3 # Carrier frequency for signal + >>> z = gaussian(len(t), 0.3/T) * np.exp(2j*np.pi*f_c*t) # analytic signal + >>> z_re = z.real + 0j # complex signal with zero imaginary part + ... + >>> e_a, e_r = (envelope(z_, (None, None), residual=None) for z_ in (z, z_re)) + ... + >>> # Generate grids to visualize envelopes as 2d and 3d surfaces: + >>> E2d_t, E2_amp = np.meshgrid(t, [-1, 1]) + >>> E2d_1 = np.ones_like(E2_amp) + >>> E3d_t, E3d_phi = np.meshgrid(t, np.linspace(-np.pi, np.pi, 300)) + >>> ma = 1.8 # maximum axis values in real and imaginary direction + ... + >>> fg0 = plt.figure(figsize=(6.2, 4.)) + >>> ax00 = fg0.add_subplot(1, 2, 1, projection='3d') + >>> ax01 = fg0.add_subplot(1, 2, 2, projection='3d', sharex=ax00, + ... sharey=ax00, sharez=ax00) + >>> ax00.set_title("Analytic Signal") + >>> ax00.set(xlim=(0, 1), ylim=(-ma, ma), zlim=(-ma, ma)) + >>> ax01.set_title("Real-valued Signal") + >>> for z_, e_, ax_ in zip((z, z.real), (e_a, e_r), (ax00, ax01)): + ... ax_.set(xlabel="Time $t$", ylabel="Real Amp. $x(t)$", + ... zlabel="Imag. Amp. $y(t)$") + ... ax_.plot(t, z_.real, 'C0-', zs=-ma, zdir='z', alpha=0.5, label="Real") + ... ax_.plot_surface(E2d_t, e_*E2_amp, -ma*E2d_1, color='C1', alpha=0.25) + ... ax_.plot(t, z_.imag, 'C0-', zs=+ma, zdir='y', alpha=0.5, label="Imag.") + ... ax_.plot_surface(E2d_t, ma*E2d_1, e_*E2_amp, color='C1', alpha=0.25) + ... ax_.plot(t, z_.real, z_.imag, 'C0-', label="Signal") + ... ax_.plot_surface(E3d_t, e_*np.cos(E3d_phi), e_*np.sin(E3d_phi), + ... color='C1', alpha=0.5, shade=True, label="Envelope") + ... ax_.view_init(elev=22.7, azim=-114.3) + >>> fg0.subplots_adjust(left=0.08, right=0.97, wspace=0.15) + >>> plt.show() + """ + if not (-z.ndim <= axis < z.ndim): + raise ValueError(f"Invalid parameter {axis=} for {z.shape=}!") + if not (z.shape[axis] > 0): + raise ValueError(f"z.shape[axis] not > 0 for {z.shape=}, {axis=}!") + if len(bp_in) != 2 or not all((isinstance(b_, int) or b_ is None) for b_ in bp_in): + raise ValueError(f"{bp_in=} isn't a 2-tuple of type (int | None, int | None)!") + if not ((isinstance(n_out, int) and 0 < n_out) or n_out is None): + raise ValueError(f"{n_out=} is not a positive integer or None!") + if residual not in ('lowpass', 'all', None): + raise ValueError(f"{residual=} not in ['lowpass', 'all', None]!") + + n = z.shape[axis] # number of time samples of input + n_out = n if n_out is None else n_out + fak = n_out / n # scaling factor for resampling + + bp = slice(bp_in[0] if bp_in[0] is not None else -(n//2), + bp_in[1] if bp_in[1] is not None else (n+1)//2) + if not (-n//2 <= bp.start < bp.stop <= (n+1)//2): + raise ValueError("`-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2` does not hold " + + f"for n={z.shape[axis]=} and {bp_in=}!") + + # moving active axis to end allows to use `...` for indexing: + z = np.moveaxis(z, axis, -1) + + if np.iscomplexobj(z): + Z = sp_fft.fft(z) + else: # avoid calculating negative frequency bins for real signals: + Z = np.zeros_like(z, dtype=sp_fft.rfft(z.flat[:1]).dtype) + Z[..., :n//2 + 1] = sp_fft.rfft(z) + if bp.start > 0: # make signal analytic within bp_in band: + Z[..., bp] *= 2 + elif bp.stop > 0: + Z[..., 1:bp.stop] *= 2 + if not (bp.start <= 0 < bp.stop): # envelope is invariant to freq. shifts. + z_bb = sp_fft.ifft(Z[..., bp], n=n_out) * fak # baseband signal + else: + bp_shift = slice(bp.start + n//2, bp.stop + n//2) + z_bb = sp_fft.ifft(sp_fft.fftshift(Z, axes=-1)[..., bp_shift], n=n_out) * fak + + z_env = np.abs(z_bb) if not squared else z_bb.real ** 2 + z_bb.imag ** 2 + z_env = np.moveaxis(z_env, -1, axis) + + # Calculate the residual from the input bandpass filter: + if residual is None: + return z_env + if not (bp.start <= 0 < bp.stop): + Z[..., bp] = 0 + else: + Z[..., :bp.stop], Z[..., bp.start:] = 0, 0 + if residual == 'lowpass': + if bp.stop > 0: + Z[..., bp.stop:(n+1) // 2] = 0 + else: + Z[..., bp.start:], Z[..., 0:(n + 1) // 2] = 0, 0 + + z_res = fak * (sp_fft.ifft(Z, n=n_out) if np.iscomplexobj(z) else + sp_fft.irfft(Z, n=n_out)) + return np.stack((z_env, np.moveaxis(z_res, -1, axis)), axis=0) + +def _cmplx_sort(p): + """Sort roots based on magnitude. + + Parameters + ---------- + p : array_like + The roots to sort, as a 1-D array. + + Returns + ------- + p_sorted : ndarray + Sorted roots. + indx : ndarray + Array of indices needed to sort the input `p`. + + Examples + -------- + >>> from scipy import signal + >>> vals = [1, 4, 1+1.j, 3] + >>> p_sorted, indx = signal.cmplx_sort(vals) + >>> p_sorted + array([1.+0.j, 1.+1.j, 3.+0.j, 4.+0.j]) + >>> indx + array([0, 2, 3, 1]) + """ + p = np.asarray(p) + indx = np.argsort(abs(p)) + return np.take(p, indx, 0), indx + + +def unique_roots(p, tol=1e-3, rtype='min'): + """Determine unique roots and their multiplicities from a list of roots. + + Parameters + ---------- + p : array_like + The list of roots. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. Refer to Notes about + the details on roots grouping. + rtype : {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}, optional + How to determine the returned root if multiple roots are within + `tol` of each other. + + - 'max', 'maximum': pick the maximum of those roots + - 'min', 'minimum': pick the minimum of those roots + - 'avg', 'mean': take the average of those roots + + When finding minimum or maximum among complex roots they are compared + first by the real part and then by the imaginary part. + + Returns + ------- + unique : ndarray + The list of unique roots. + multiplicity : ndarray + The multiplicity of each root. + + Notes + ----- + If we have 3 roots ``a``, ``b`` and ``c``, such that ``a`` is close to + ``b`` and ``b`` is close to ``c`` (distance is less than `tol`), then it + doesn't necessarily mean that ``a`` is close to ``c``. It means that roots + grouping is not unique. In this function we use "greedy" grouping going + through the roots in the order they are given in the input `p`. + + This utility function is not specific to roots but can be used for any + sequence of values for which uniqueness and multiplicity has to be + determined. For a more general routine, see `numpy.unique`. + + Examples + -------- + >>> from scipy import signal + >>> vals = [0, 1.3, 1.31, 2.8, 1.25, 2.2, 10.3] + >>> uniq, mult = signal.unique_roots(vals, tol=2e-2, rtype='avg') + + Check which roots have multiplicity larger than 1: + + >>> uniq[mult > 1] + array([ 1.305]) + """ + if rtype in ['max', 'maximum']: + reduce = np.max + elif rtype in ['min', 'minimum']: + reduce = np.min + elif rtype in ['avg', 'mean']: + reduce = np.mean + else: + raise ValueError("`rtype` must be one of " + "{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}") + + p = np.asarray(p) + + points = np.empty((len(p), 2)) + points[:, 0] = np.real(p) + points[:, 1] = np.imag(p) + tree = cKDTree(points) + + p_unique = [] + p_multiplicity = [] + used = np.zeros(len(p), dtype=bool) + for i in range(len(p)): + if used[i]: + continue + + group = tree.query_ball_point(points[i], tol) + group = [x for x in group if not used[x]] + + p_unique.append(reduce(p[group])) + p_multiplicity.append(len(group)) + + used[group] = True + + return np.asarray(p_unique), np.asarray(p_multiplicity) + + +def invres(r, p, k, tol=1e-3, rtype='avg'): + """Compute b(s) and a(s) from partial fraction expansion. + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M] + H(s) = ------ = ------------------------------------------ + a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N] + + then the partial-fraction expansion H(s) is defined as:: + + r[0] r[1] r[-1] + = -------- + -------- + ... + --------- + k(s) + (s-p[0]) (s-p[1]) (s-p[-1]) + + If there are any repeated roots (closer together than `tol`), then H(s) + has terms like:: + + r[i] r[i+1] r[i+n-1] + -------- + ----------- + ... + ----------- + (s-p[i]) (s-p[i])**2 (s-p[i])**n + + This function is used for polynomials in positive powers of s or z, + such as analog filters or digital filters in controls engineering. For + negative powers of z (typical for digital filters in DSP), use `invresz`. + + Parameters + ---------- + r : array_like + Residues corresponding to the poles. For repeated poles, the residues + must be ordered to correspond to ascending by power fractions. + p : array_like + Poles. Equal poles must be adjacent. + k : array_like + Coefficients of the direct polynomial term. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + See Also + -------- + residue, invresz, unique_roots + + """ + r = np.atleast_1d(r) + p = np.atleast_1d(p) + k = np.trim_zeros(np.atleast_1d(k), 'f') + + unique_poles, multiplicity = _group_poles(p, tol, rtype) + factors, denominator = _compute_factors(unique_poles, multiplicity, + include_powers=True) + + if len(k) == 0: + numerator = 0 + else: + numerator = np.polymul(k, denominator) + + for residue, factor in zip(r, factors): + numerator = np.polyadd(numerator, residue * factor) + + return numerator, denominator + + +def _compute_factors(roots, multiplicity, include_powers=False): + """Compute the total polynomial divided by factors for each root.""" + current = np.array([1]) + suffixes = [current] + for pole, mult in zip(roots[-1:0:-1], multiplicity[-1:0:-1]): + monomial = np.array([1, -pole]) + for _ in range(mult): + current = np.polymul(current, monomial) + suffixes.append(current) + suffixes = suffixes[::-1] + + factors = [] + current = np.array([1]) + for pole, mult, suffix in zip(roots, multiplicity, suffixes): + monomial = np.array([1, -pole]) + block = [] + for i in range(mult): + if i == 0 or include_powers: + block.append(np.polymul(current, suffix)) + current = np.polymul(current, monomial) + factors.extend(reversed(block)) + + return factors, current + + +def _compute_residues(poles, multiplicity, numerator): + denominator_factors, _ = _compute_factors(poles, multiplicity) + numerator = numerator.astype(poles.dtype) + + residues = [] + for pole, mult, factor in zip(poles, multiplicity, + denominator_factors): + if mult == 1: + residues.append(np.polyval(numerator, pole) / + np.polyval(factor, pole)) + else: + numer = numerator.copy() + monomial = np.array([1, -pole]) + factor, d = np.polydiv(factor, monomial) + + block = [] + for _ in range(mult): + numer, n = np.polydiv(numer, monomial) + r = n[0] / d[0] + numer = np.polysub(numer, r * factor) + block.append(r) + + residues.extend(reversed(block)) + + return np.asarray(residues) + + +def residue(b, a, tol=1e-3, rtype='avg'): + """Compute partial-fraction expansion of b(s) / a(s). + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M] + H(s) = ------ = ------------------------------------------ + a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N] + + then the partial-fraction expansion H(s) is defined as:: + + r[0] r[1] r[-1] + = -------- + -------- + ... + --------- + k(s) + (s-p[0]) (s-p[1]) (s-p[-1]) + + If there are any repeated roots (closer together than `tol`), then H(s) + has terms like:: + + r[i] r[i+1] r[i+n-1] + -------- + ----------- + ... + ----------- + (s-p[i]) (s-p[i])**2 (s-p[i])**n + + This function is used for polynomials in positive powers of s or z, + such as analog filters or digital filters in controls engineering. For + negative powers of z (typical for digital filters in DSP), use `residuez`. + + See Notes for details about the algorithm. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + r : ndarray + Residues corresponding to the poles. For repeated poles, the residues + are ordered to correspond to ascending by power fractions. + p : ndarray + Poles ordered by magnitude in ascending order. + k : ndarray + Coefficients of the direct polynomial term. + + See Also + -------- + invres, residuez, numpy.poly, unique_roots + + Notes + ----- + The "deflation through subtraction" algorithm is used for + computations --- method 6 in [1]_. + + The form of partial fraction expansion depends on poles multiplicity in + the exact mathematical sense. However there is no way to exactly + determine multiplicity of roots of a polynomial in numerical computing. + Thus you should think of the result of `residue` with given `tol` as + partial fraction expansion computed for the denominator composed of the + computed poles with empirically determined multiplicity. The choice of + `tol` can drastically change the result if there are close poles. + + References + ---------- + .. [1] J. F. Mahoney, B. D. Sivazlian, "Partial fractions expansion: a + review of computational methodology and efficiency", Journal of + Computational and Applied Mathematics, Vol. 9, 1983. + """ + b = np.asarray(b) + a = np.asarray(a) + if (np.issubdtype(b.dtype, np.complexfloating) + or np.issubdtype(a.dtype, np.complexfloating)): + b = b.astype(complex) + a = a.astype(complex) + else: + b = b.astype(float) + a = a.astype(float) + + b = np.trim_zeros(np.atleast_1d(b), 'f') + a = np.trim_zeros(np.atleast_1d(a), 'f') + + if a.size == 0: + raise ValueError("Denominator `a` is zero.") + + poles = np.roots(a) + if b.size == 0: + return np.zeros(poles.shape), _cmplx_sort(poles)[0], np.array([]) + + if len(b) < len(a): + k = np.empty(0) + else: + k, b = np.polydiv(b, a) + + unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype) + unique_poles, order = _cmplx_sort(unique_poles) + multiplicity = multiplicity[order] + + residues = _compute_residues(unique_poles, multiplicity, b) + + index = 0 + for pole, mult in zip(unique_poles, multiplicity): + poles[index:index + mult] = pole + index += mult + + return residues / a[0], poles, k + + +def residuez(b, a, tol=1e-3, rtype='avg'): + """Compute partial-fraction expansion of b(z) / a(z). + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M) + H(z) = ------ = ------------------------------------------ + a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N) + + then the partial-fraction expansion H(z) is defined as:: + + r[0] r[-1] + = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... + (1-p[0]z**(-1)) (1-p[-1]z**(-1)) + + If there are any repeated roots (closer than `tol`), then the partial + fraction expansion has terms like:: + + r[i] r[i+1] r[i+n-1] + -------------- + ------------------ + ... + ------------------ + (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n + + This function is used for polynomials in negative powers of z, + such as digital filters in DSP. For positive powers, use `residue`. + + See Notes of `residue` for details about the algorithm. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + r : ndarray + Residues corresponding to the poles. For repeated poles, the residues + are ordered to correspond to ascending by power fractions. + p : ndarray + Poles ordered by magnitude in ascending order. + k : ndarray + Coefficients of the direct polynomial term. + + See Also + -------- + invresz, residue, unique_roots + """ + b = np.asarray(b) + a = np.asarray(a) + if (np.issubdtype(b.dtype, np.complexfloating) + or np.issubdtype(a.dtype, np.complexfloating)): + b = b.astype(complex) + a = a.astype(complex) + else: + b = b.astype(float) + a = a.astype(float) + + b = np.trim_zeros(np.atleast_1d(b), 'b') + a = np.trim_zeros(np.atleast_1d(a), 'b') + + if a.size == 0: + raise ValueError("Denominator `a` is zero.") + elif a[0] == 0: + raise ValueError("First coefficient of determinant `a` must be " + "non-zero.") + + poles = np.roots(a) + if b.size == 0: + return np.zeros(poles.shape), _cmplx_sort(poles)[0], np.array([]) + + b_rev = b[::-1] + a_rev = a[::-1] + + if len(b_rev) < len(a_rev): + k_rev = np.empty(0) + else: + k_rev, b_rev = np.polydiv(b_rev, a_rev) + + unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype) + unique_poles, order = _cmplx_sort(unique_poles) + multiplicity = multiplicity[order] + + residues = _compute_residues(1 / unique_poles, multiplicity, b_rev) + + index = 0 + powers = np.empty(len(residues), dtype=int) + for pole, mult in zip(unique_poles, multiplicity): + poles[index:index + mult] = pole + powers[index:index + mult] = 1 + np.arange(mult) + index += mult + + residues *= (-poles) ** powers / a_rev[0] + + return residues, poles, k_rev[::-1] + + +def _group_poles(poles, tol, rtype): + if rtype in ['max', 'maximum']: + reduce = np.max + elif rtype in ['min', 'minimum']: + reduce = np.min + elif rtype in ['avg', 'mean']: + reduce = np.mean + else: + raise ValueError("`rtype` must be one of " + "{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}") + + unique = [] + multiplicity = [] + + pole = poles[0] + block = [pole] + for i in range(1, len(poles)): + if abs(poles[i] - pole) <= tol: + block.append(pole) + else: + unique.append(reduce(block)) + multiplicity.append(len(block)) + pole = poles[i] + block = [pole] + + unique.append(reduce(block)) + multiplicity.append(len(block)) + + return np.asarray(unique), np.asarray(multiplicity) + + +def invresz(r, p, k, tol=1e-3, rtype='avg'): + """Compute b(z) and a(z) from partial fraction expansion. + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M) + H(z) = ------ = ------------------------------------------ + a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N) + + then the partial-fraction expansion H(z) is defined as:: + + r[0] r[-1] + = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... + (1-p[0]z**(-1)) (1-p[-1]z**(-1)) + + If there are any repeated roots (closer than `tol`), then the partial + fraction expansion has terms like:: + + r[i] r[i+1] r[i+n-1] + -------------- + ------------------ + ... + ------------------ + (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n + + This function is used for polynomials in negative powers of z, + such as digital filters in DSP. For positive powers, use `invres`. + + Parameters + ---------- + r : array_like + Residues corresponding to the poles. For repeated poles, the residues + must be ordered to correspond to ascending by power fractions. + p : array_like + Poles. Equal poles must be adjacent. + k : array_like + Coefficients of the direct polynomial term. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + See Also + -------- + residuez, unique_roots, invres + + """ + r = np.atleast_1d(r) + p = np.atleast_1d(p) + k = np.trim_zeros(np.atleast_1d(k), 'b') + + unique_poles, multiplicity = _group_poles(p, tol, rtype) + factors, denominator = _compute_factors(unique_poles, multiplicity, + include_powers=True) + + if len(k) == 0: + numerator = 0 + else: + numerator = np.polymul(k[::-1], denominator[::-1]) + + for residue, factor in zip(r, factors): + numerator = np.polyadd(numerator, residue * factor[::-1]) + + return numerator[::-1], denominator + + +def resample(x, num, t=None, axis=0, window=None, domain='time'): + """ + Resample `x` to `num` samples using Fourier method along the given axis. + + The resampled signal starts at the same value as `x` but is sampled + with a spacing of ``len(x) / num * (spacing of x)``. Because a + Fourier method is used, the signal is assumed to be periodic. + + Parameters + ---------- + x : array_like + The data to be resampled. + num : int + The number of samples in the resampled signal. + t : array_like, optional + If `t` is given, it is assumed to be the equally spaced sample + positions associated with the signal data in `x`. + axis : int, optional + The axis of `x` that is resampled. Default is 0. + window : array_like, callable, string, float, or tuple, optional + Specifies the window applied to the signal in the Fourier + domain. See below for details. + domain : string, optional + A string indicating the domain of the input `x`: + ``time`` Consider the input `x` as time-domain (Default), + ``freq`` Consider the input `x` as frequency-domain. + + Returns + ------- + resampled_x or (resampled_x, resampled_t) + Either the resampled array, or, if `t` was given, a tuple + containing the resampled array and the corresponding resampled + positions. + + See Also + -------- + decimate : Downsample the signal after applying an FIR or IIR filter. + resample_poly : Resample using polyphase filtering and an FIR filter. + + Notes + ----- + The argument `window` controls a Fourier-domain window that tapers + the Fourier spectrum before zero-padding to alleviate ringing in + the resampled values for sampled signals you didn't intend to be + interpreted as band-limited. + + If `window` is a function, then it is called with a vector of inputs + indicating the frequency bins (i.e. fftfreq(x.shape[axis]) ). + + If `window` is an array of the same length as `x.shape[axis]` it is + assumed to be the window to be applied directly in the Fourier + domain (with dc and low-frequency first). + + For any other type of `window`, the function `scipy.signal.get_window` + is called to generate the window. + + The first sample of the returned vector is the same as the first + sample of the input vector. The spacing between samples is changed + from ``dx`` to ``dx * len(x) / num``. + + If `t` is not None, then it is used solely to calculate the resampled + positions `resampled_t` + + As noted, `resample` uses FFT transformations, which can be very + slow if the number of input or output samples is large and prime; + see :func:`~scipy.fft.fft`. In such cases, it can be faster to first downsample + a signal of length ``n`` with :func:`~scipy.signal.resample_poly` by a factor of + ``n//num`` before using `resample`. Note that this approach changes the + characteristics of the antialiasing filter. + + Examples + -------- + Note that the end of the resampled data rises to meet the first + sample of the next cycle: + + >>> import numpy as np + >>> from scipy import signal + + >>> x = np.linspace(0, 10, 20, endpoint=False) + >>> y = np.cos(-x**2/6.0) + >>> f = signal.resample(y, 100) + >>> xnew = np.linspace(0, 10, 100, endpoint=False) + + >>> import matplotlib.pyplot as plt + >>> plt.plot(x, y, 'go-', xnew, f, '.-', 10, y[0], 'ro') + >>> plt.legend(['data', 'resampled'], loc='best') + >>> plt.show() + + Consider the following signal ``y`` where ``len(y)`` is a large prime number: + + >>> N = 55949 + >>> freq = 100 + >>> x = np.linspace(0, 1, N) + >>> y = np.cos(2 * np.pi * freq * x) + + Due to ``N`` being prime, + + >>> num = 5000 + >>> f = signal.resample(signal.resample_poly(y, 1, N // num), num) + + runs significantly faster than + + >>> f = signal.resample(y, num) + """ + + if domain not in ('time', 'freq'): + raise ValueError("Acceptable domain flags are 'time' or" + f" 'freq', not domain={domain}") + + x = np.asarray(x) + Nx = x.shape[axis] + + # Check if we can use faster real FFT + real_input = np.isrealobj(x) + + if domain == 'time': + # Forward transform + if real_input: + X = sp_fft.rfft(x, axis=axis) + else: # Full complex FFT + X = sp_fft.fft(x, axis=axis) + else: # domain == 'freq' + X = x + + # Apply window to spectrum + if window is not None: + if callable(window): + W = window(sp_fft.fftfreq(Nx)) + elif isinstance(window, np.ndarray): + if window.shape != (Nx,): + raise ValueError('window must have the same length as data') + W = window + else: + W = sp_fft.ifftshift(get_window(window, Nx)) + + newshape_W = [1] * x.ndim + newshape_W[axis] = X.shape[axis] + if real_input: + # Fold the window back on itself to mimic complex behavior + W_real = W.copy() + W_real[1:] += W_real[-1:0:-1] + W_real[1:] *= 0.5 + X *= W_real[:newshape_W[axis]].reshape(newshape_W) + else: + X *= W.reshape(newshape_W) + + # Copy each half of the original spectrum to the output spectrum, either + # truncating high frequencies (downsampling) or zero-padding them + # (upsampling) + + # Placeholder array for output spectrum + newshape = list(x.shape) + if real_input: + newshape[axis] = num // 2 + 1 + else: + newshape[axis] = num + Y = np.zeros(newshape, X.dtype) + + # Copy positive frequency components (and Nyquist, if present) + N = min(num, Nx) + nyq = N // 2 + 1 # Slice index that includes Nyquist if present + sl = [slice(None)] * x.ndim + sl[axis] = slice(0, nyq) + Y[tuple(sl)] = X[tuple(sl)] + if not real_input: + # Copy negative frequency components + if N > 2: # (slice expression doesn't collapse to empty array) + sl[axis] = slice(nyq - N, None) + Y[tuple(sl)] = X[tuple(sl)] + + # Split/join Nyquist component(s) if present + # So far we have set Y[+N/2]=X[+N/2] + if N % 2 == 0: + if num < Nx: # downsampling + if real_input: + sl[axis] = slice(N//2, N//2 + 1) + Y[tuple(sl)] *= 2. + else: + # select the component of Y at frequency +N/2, + # add the component of X at -N/2 + sl[axis] = slice(-N//2, -N//2 + 1) + Y[tuple(sl)] += X[tuple(sl)] + elif Nx < num: # upsampling + # select the component at frequency +N/2 and halve it + sl[axis] = slice(N//2, N//2 + 1) + Y[tuple(sl)] *= 0.5 + if not real_input: + temp = Y[tuple(sl)] + # set the component at -N/2 equal to the component at +N/2 + sl[axis] = slice(num-N//2, num-N//2 + 1) + Y[tuple(sl)] = temp + + # Inverse transform + if real_input: + y = sp_fft.irfft(Y, num, axis=axis) + else: + y = sp_fft.ifft(Y, axis=axis, overwrite_x=True) + + y *= (float(num) / float(Nx)) + + if t is None: + return y + else: + new_t = np.arange(0, num) * (t[1] - t[0]) * Nx / float(num) + t[0] + return y, new_t + + +def resample_poly(x, up, down, axis=0, window=('kaiser', 5.0), + padtype='constant', cval=None): + """ + Resample `x` along the given axis using polyphase filtering. + + The signal `x` is upsampled by the factor `up`, a zero-phase low-pass + FIR filter is applied, and then it is downsampled by the factor `down`. + The resulting sample rate is ``up / down`` times the original sample + rate. By default, values beyond the boundary of the signal are assumed + to be zero during the filtering step. + + Parameters + ---------- + x : array_like + The data to be resampled. + up : int + The upsampling factor. + down : int + The downsampling factor. + axis : int, optional + The axis of `x` that is resampled. Default is 0. + window : string, tuple, or array_like, optional + Desired window to use to design the low-pass filter, or the FIR filter + coefficients to employ. See below for details. + padtype : string, optional + `constant`, `line`, `mean`, `median`, `maximum`, `minimum` or any of + the other signal extension modes supported by `scipy.signal.upfirdn`. + Changes assumptions on values beyond the boundary. If `constant`, + assumed to be `cval` (default zero). If `line` assumed to continue a + linear trend defined by the first and last points. `mean`, `median`, + `maximum` and `minimum` work as in `np.pad` and assume that the values + beyond the boundary are the mean, median, maximum or minimum + respectively of the array along the axis. + + .. versionadded:: 1.4.0 + cval : float, optional + Value to use if `padtype='constant'`. Default is zero. + + .. versionadded:: 1.4.0 + + Returns + ------- + resampled_x : array + The resampled array. + + See Also + -------- + decimate : Downsample the signal after applying an FIR or IIR filter. + resample : Resample up or down using the FFT method. + + Notes + ----- + This polyphase method will likely be faster than the Fourier method + in `scipy.signal.resample` when the number of samples is large and + prime, or when the number of samples is large and `up` and `down` + share a large greatest common denominator. The length of the FIR + filter used will depend on ``max(up, down) // gcd(up, down)``, and + the number of operations during polyphase filtering will depend on + the filter length and `down` (see `scipy.signal.upfirdn` for details). + + The argument `window` specifies the FIR low-pass filter design. + + If `window` is an array_like it is assumed to be the FIR filter + coefficients. Note that the FIR filter is applied after the upsampling + step, so it should be designed to operate on a signal at a sampling + frequency higher than the original by a factor of `up//gcd(up, down)`. + This function's output will be centered with respect to this array, so it + is best to pass a symmetric filter with an odd number of samples if, as + is usually the case, a zero-phase filter is desired. + + For any other type of `window`, the functions `scipy.signal.get_window` + and `scipy.signal.firwin` are called to generate the appropriate filter + coefficients. + + The first sample of the returned vector is the same as the first + sample of the input vector. The spacing between samples is changed + from ``dx`` to ``dx * down / float(up)``. + + Examples + -------- + By default, the end of the resampled data rises to meet the first + sample of the next cycle for the FFT method, and gets closer to zero + for the polyphase method: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> x = np.linspace(0, 10, 20, endpoint=False) + >>> y = np.cos(-x**2/6.0) + >>> f_fft = signal.resample(y, 100) + >>> f_poly = signal.resample_poly(y, 100, 20) + >>> xnew = np.linspace(0, 10, 100, endpoint=False) + + >>> plt.plot(xnew, f_fft, 'b.-', xnew, f_poly, 'r.-') + >>> plt.plot(x, y, 'ko-') + >>> plt.plot(10, y[0], 'bo', 10, 0., 'ro') # boundaries + >>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best') + >>> plt.show() + + This default behaviour can be changed by using the padtype option: + + >>> N = 5 + >>> x = np.linspace(0, 1, N, endpoint=False) + >>> y = 2 + x**2 - 1.7*np.sin(x) + .2*np.cos(11*x) + >>> y2 = 1 + x**3 + 0.1*np.sin(x) + .1*np.cos(11*x) + >>> Y = np.stack([y, y2], axis=-1) + >>> up = 4 + >>> xr = np.linspace(0, 1, N*up, endpoint=False) + + >>> y2 = signal.resample_poly(Y, up, 1, padtype='constant') + >>> y3 = signal.resample_poly(Y, up, 1, padtype='mean') + >>> y4 = signal.resample_poly(Y, up, 1, padtype='line') + + >>> for i in [0,1]: + ... plt.figure() + ... plt.plot(xr, y4[:,i], 'g.', label='line') + ... plt.plot(xr, y3[:,i], 'y.', label='mean') + ... plt.plot(xr, y2[:,i], 'r.', label='constant') + ... plt.plot(x, Y[:,i], 'k-') + ... plt.legend() + >>> plt.show() + + """ + x = np.asarray(x) + if up != int(up): + raise ValueError("up must be an integer") + if down != int(down): + raise ValueError("down must be an integer") + up = int(up) + down = int(down) + if up < 1 or down < 1: + raise ValueError('up and down must be >= 1') + if cval is not None and padtype != 'constant': + raise ValueError('cval has no effect when padtype is ', padtype) + + # Determine our up and down factors + # Use a rational approximation to save computation time on really long + # signals + g_ = math.gcd(up, down) + up //= g_ + down //= g_ + if up == down == 1: + return x.copy() + n_in = x.shape[axis] + n_out = n_in * up + n_out = n_out // down + bool(n_out % down) + + if isinstance(window, (list | np.ndarray)): + window = np.array(window) # use array to force a copy (we modify it) + if window.ndim > 1: + raise ValueError('window must be 1-D') + half_len = (window.size - 1) // 2 + h = window + else: + # Design a linear-phase low-pass FIR filter + max_rate = max(up, down) + f_c = 1. / max_rate # cutoff of FIR filter (rel. to Nyquist) + half_len = 10 * max_rate # reasonable cutoff for sinc-like function + if np.issubdtype(x.dtype, np.complexfloating): + h = firwin(2 * half_len + 1, f_c, + window=window).astype(x.dtype) # match dtype of x + elif np.issubdtype(x.dtype, np.floating): + h = firwin(2 * half_len + 1, f_c, + window=window).astype(x.dtype) # match dtype of x + else: + h = firwin(2 * half_len + 1, f_c, + window=window) + h *= up + + # Zero-pad our filter to put the output samples at the center + n_pre_pad = (down - half_len % down) + n_post_pad = 0 + n_pre_remove = (half_len + n_pre_pad) // down + # We should rarely need to do this given our filter lengths... + while _output_len(len(h) + n_pre_pad + n_post_pad, n_in, + up, down) < n_out + n_pre_remove: + n_post_pad += 1 + h = np.concatenate((np.zeros(n_pre_pad, dtype=h.dtype), h, + np.zeros(n_post_pad, dtype=h.dtype))) + n_pre_remove_end = n_pre_remove + n_out + + # Remove background depending on the padtype option + funcs = {'mean': np.mean, 'median': np.median, + 'minimum': np.amin, 'maximum': np.amax} + upfirdn_kwargs = {'mode': 'constant', 'cval': 0} + if padtype in funcs: + background_values = funcs[padtype](x, axis=axis, keepdims=True) + elif padtype in _upfirdn_modes: + upfirdn_kwargs = {'mode': padtype} + if padtype == 'constant': + if cval is None: + cval = 0 + upfirdn_kwargs['cval'] = cval + else: + raise ValueError( + 'padtype must be one of: maximum, mean, median, minimum, ' + + ', '.join(_upfirdn_modes)) + + if padtype in funcs: + x = x - background_values + + # filter then remove excess + y = upfirdn(h, x, up, down, axis=axis, **upfirdn_kwargs) + keep = [slice(None), ]*x.ndim + keep[axis] = slice(n_pre_remove, n_pre_remove_end) + y_keep = y[tuple(keep)] + + # Add background back + if padtype in funcs: + y_keep += background_values + + return y_keep + + +def vectorstrength(events, period): + ''' + Determine the vector strength of the events corresponding to the given + period. + + The vector strength is a measure of phase synchrony, how well the + timing of the events is synchronized to a single period of a periodic + signal. + + If multiple periods are used, calculate the vector strength of each. + This is called the "resonating vector strength". + + Parameters + ---------- + events : 1D array_like + An array of time points containing the timing of the events. + period : float or array_like + The period of the signal that the events should synchronize to. + The period is in the same units as `events`. It can also be an array + of periods, in which case the outputs are arrays of the same length. + + Returns + ------- + strength : float or 1D array + The strength of the synchronization. 1.0 is perfect synchronization + and 0.0 is no synchronization. If `period` is an array, this is also + an array with each element containing the vector strength at the + corresponding period. + phase : float or array + The phase that the events are most strongly synchronized to in radians. + If `period` is an array, this is also an array with each element + containing the phase for the corresponding period. + + References + ---------- + van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector + strength: Auditory system, electric fish, and noise. + Chaos 21, 047508 (2011); + :doi:`10.1063/1.3670512`. + van Hemmen, JL. Vector strength after Goldberg, Brown, and von Mises: + biological and mathematical perspectives. Biol Cybern. + 2013 Aug;107(4):385-96. :doi:`10.1007/s00422-013-0561-7`. + van Hemmen, JL and Vollmayr, AN. Resonating vector strength: what happens + when we vary the "probing" frequency while keeping the spike times + fixed. Biol Cybern. 2013 Aug;107(4):491-94. + :doi:`10.1007/s00422-013-0560-8`. + ''' + events = np.asarray(events) + period = np.asarray(period) + if events.ndim > 1: + raise ValueError('events cannot have dimensions more than 1') + if period.ndim > 1: + raise ValueError('period cannot have dimensions more than 1') + + # we need to know later if period was originally a scalar + scalarperiod = not period.ndim + + events = np.atleast_2d(events) + period = np.atleast_2d(period) + if (period <= 0).any(): + raise ValueError('periods must be positive') + + # this converts the times to vectors + vectors = np.exp(np.dot(2j*np.pi/period.T, events)) + + # the vector strength is just the magnitude of the mean of the vectors + # the vector phase is the angle of the mean of the vectors + vectormean = np.mean(vectors, axis=1) + strength = abs(vectormean) + phase = np.angle(vectormean) + + # if the original period was a scalar, return scalars + if scalarperiod: + strength = strength[0] + phase = phase[0] + return strength, phase + + +def detrend(data: np.ndarray, axis: int = -1, + type: Literal['linear', 'constant'] = 'linear', + bp: ArrayLike | int = 0, overwrite_data: bool = False) -> np.ndarray: + r"""Remove linear or constant trend along axis from data. + + Parameters + ---------- + data : array_like + The input data. + axis : int, optional + The axis along which to detrend the data. By default this is the + last axis (-1). + type : {'linear', 'constant'}, optional + The type of detrending. If ``type == 'linear'`` (default), + the result of a linear least-squares fit to `data` is subtracted + from `data`. + If ``type == 'constant'``, only the mean of `data` is subtracted. + bp : array_like of ints, optional + A sequence of break points. If given, an individual linear fit is + performed for each part of `data` between two break points. + Break points are specified as indices into `data`. This parameter + only has an effect when ``type == 'linear'``. + overwrite_data : bool, optional + If True, perform in place detrending and avoid a copy. Default is False + + Returns + ------- + ret : ndarray + The detrended input data. + + Notes + ----- + Detrending can be interpreted as subtracting a least squares fit polynomial: + Setting the parameter `type` to 'constant' corresponds to fitting a zeroth degree + polynomial, 'linear' to a first degree polynomial. Consult the example below. + + See Also + -------- + numpy.polynomial.polynomial.Polynomial.fit: Create least squares fit polynomial. + + + Examples + -------- + The following example detrends the function :math:`x(t) = \sin(\pi t) + 1/4`: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal import detrend + ... + >>> t = np.linspace(-0.5, 0.5, 21) + >>> x = np.sin(np.pi*t) + 1/4 + ... + >>> x_d_const = detrend(x, type='constant') + >>> x_d_linear = detrend(x, type='linear') + ... + >>> fig1, ax1 = plt.subplots() + >>> ax1.set_title(r"Detrending $x(t)=\sin(\pi t) + 1/4$") + >>> ax1.set(xlabel="t", ylabel="$x(t)$", xlim=(t[0], t[-1])) + >>> ax1.axhline(y=0, color='black', linewidth=.5) + >>> ax1.axvline(x=0, color='black', linewidth=.5) + >>> ax1.plot(t, x, 'C0.-', label="No detrending") + >>> ax1.plot(t, x_d_const, 'C1x-', label="type='constant'") + >>> ax1.plot(t, x_d_linear, 'C2+-', label="type='linear'") + >>> ax1.legend() + >>> plt.show() + + Alternatively, NumPy's `~numpy.polynomial.polynomial.Polynomial` can be used for + detrending as well: + + >>> pp0 = np.polynomial.Polynomial.fit(t, x, deg=0) # fit degree 0 polynomial + >>> np.allclose(x_d_const, x - pp0(t)) # compare with constant detrend + True + >>> pp1 = np.polynomial.Polynomial.fit(t, x, deg=1) # fit degree 1 polynomial + >>> np.allclose(x_d_linear, x - pp1(t)) # compare with linear detrend + True + + Note that `~numpy.polynomial.polynomial.Polynomial` also allows fitting higher + degree polynomials. Consult its documentation on how to extract the polynomial + coefficients. + """ + if type not in ['linear', 'l', 'constant', 'c']: + raise ValueError("Trend type must be 'linear' or 'constant'.") + data = np.asarray(data) + dtype = data.dtype.char + if dtype not in 'dfDF': + dtype = 'd' + if type in ['constant', 'c']: + ret = data - np.mean(data, axis, keepdims=True) + return ret + else: + dshape = data.shape + N = dshape[axis] + bp = np.sort(np.unique(np.concatenate(np.atleast_1d(0, bp, N)))) + if np.any(bp > N): + raise ValueError("Breakpoints must be less than length " + "of data along given axis.") + + # Restructure data so that axis is along first dimension and + # all other dimensions are collapsed into second dimension + rnk = len(dshape) + if axis < 0: + axis = axis + rnk + newdata = np.moveaxis(data, axis, 0) + newdata_shape = newdata.shape + newdata = newdata.reshape(N, -1) + + if not overwrite_data: + newdata = newdata.copy() # make sure we have a copy + if newdata.dtype.char not in 'dfDF': + newdata = newdata.astype(dtype) + +# Nreg = len(bp) - 1 + # Find leastsq fit and remove it for each piece + for m in range(len(bp) - 1): + Npts = bp[m + 1] - bp[m] + A = np.ones((Npts, 2), dtype) + A[:, 0] = np.arange(1, Npts + 1, dtype=dtype) / Npts + sl = slice(bp[m], bp[m + 1]) + coef, resids, rank, s = linalg.lstsq(A, newdata[sl]) + newdata[sl] = newdata[sl] - A @ coef + + # Put data back in original shape. + newdata = newdata.reshape(newdata_shape) + ret = np.moveaxis(newdata, 0, axis) + return ret + + +def lfilter_zi(b, a): + """ + Construct initial conditions for lfilter for step response steady-state. + + Compute an initial state `zi` for the `lfilter` function that corresponds + to the steady state of the step response. + + A typical use of this function is to set the initial state so that the + output of the filter starts at the same value as the first element of + the signal to be filtered. + + Parameters + ---------- + b, a : array_like (1-D) + The IIR filter coefficients. See `lfilter` for more + information. + + Returns + ------- + zi : 1-D ndarray + The initial state for the filter. + + See Also + -------- + lfilter, lfiltic, filtfilt + + Notes + ----- + A linear filter with order m has a state space representation (A, B, C, D), + for which the output y of the filter can be expressed as:: + + z(n+1) = A*z(n) + B*x(n) + y(n) = C*z(n) + D*x(n) + + where z(n) is a vector of length m, A has shape (m, m), B has shape + (m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is + a scalar). lfilter_zi solves:: + + zi = A*zi + B + + In other words, it finds the initial condition for which the response + to an input of all ones is a constant. + + Given the filter coefficients `a` and `b`, the state space matrices + for the transposed direct form II implementation of the linear filter, + which is the implementation used by scipy.signal.lfilter, are:: + + A = scipy.linalg.companion(a).T + B = b[1:] - a[1:]*b[0] + + assuming ``a[0]`` is 1.0; if ``a[0]`` is not 1, `a` and `b` are first + divided by a[0]. + + Examples + -------- + The following code creates a lowpass Butterworth filter. Then it + applies that filter to an array whose values are all 1.0; the + output is also all 1.0, as expected for a lowpass filter. If the + `zi` argument of `lfilter` had not been given, the output would have + shown the transient signal. + + >>> from numpy import array, ones + >>> from scipy.signal import lfilter, lfilter_zi, butter + >>> b, a = butter(5, 0.25) + >>> zi = lfilter_zi(b, a) + >>> y, zo = lfilter(b, a, ones(10), zi=zi) + >>> y + array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) + + Another example: + + >>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]) + >>> y, zf = lfilter(b, a, x, zi=zi*x[0]) + >>> y + array([ 0.5 , 0.5 , 0.5 , 0.49836039, 0.48610528, + 0.44399389, 0.35505241]) + + Note that the `zi` argument to `lfilter` was computed using + `lfilter_zi` and scaled by ``x[0]``. Then the output `y` has no + transient until the input drops from 0.5 to 0.0. + + """ + + # FIXME: Can this function be replaced with an appropriate + # use of lfiltic? For example, when b,a = butter(N,Wn), + # lfiltic(b, a, y=numpy.ones_like(a), x=numpy.ones_like(b)). + # + + # We could use scipy.signal.normalize, but it uses warnings in + # cases where a ValueError is more appropriate, and it allows + # b to be 2D. + b = np.atleast_1d(b) + if b.ndim != 1: + raise ValueError("Numerator b must be 1-D.") + a = np.atleast_1d(a) + if a.ndim != 1: + raise ValueError("Denominator a must be 1-D.") + + while len(a) > 1 and a[0] == 0.0: + a = a[1:] + if a.size < 1: + raise ValueError("There must be at least one nonzero `a` coefficient.") + + if a[0] != 1.0: + # Normalize the coefficients so a[0] == 1. + b = b / a[0] + a = a / a[0] + + n = max(len(a), len(b)) + + # Pad a or b with zeros so they are the same length. + if len(a) < n: + a = np.r_[a, np.zeros(n - len(a), dtype=a.dtype)] + elif len(b) < n: + b = np.r_[b, np.zeros(n - len(b), dtype=b.dtype)] + + IminusA = np.eye(n - 1, dtype=np.result_type(a, b)) - linalg.companion(a).T + B = b[1:] - a[1:] * b[0] + # Solve zi = A*zi + B + zi = np.linalg.solve(IminusA, B) + + # For future reference: we could also use the following + # explicit formulas to solve the linear system: + # + # zi = np.zeros(n - 1) + # zi[0] = B.sum() / IminusA[:,0].sum() + # asum = 1.0 + # csum = 0.0 + # for k in range(1,n-1): + # asum += a[k] + # csum += b[k] - a[k]*b[0] + # zi[k] = asum*zi[0] - csum + + return zi + + +def sosfilt_zi(sos): + """ + Construct initial conditions for sosfilt for step response steady-state. + + Compute an initial state `zi` for the `sosfilt` function that corresponds + to the steady state of the step response. + + A typical use of this function is to set the initial state so that the + output of the filter starts at the same value as the first element of + the signal to be filtered. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + Returns + ------- + zi : ndarray + Initial conditions suitable for use with ``sosfilt``, shape + ``(n_sections, 2)``. + + See Also + -------- + sosfilt, zpk2sos + + Notes + ----- + .. versionadded:: 0.16.0 + + Examples + -------- + Filter a rectangular pulse that begins at time 0, with and without + the use of the `zi` argument of `scipy.signal.sosfilt`. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> sos = signal.butter(9, 0.125, output='sos') + >>> zi = signal.sosfilt_zi(sos) + >>> x = (np.arange(250) < 100).astype(int) + >>> f1 = signal.sosfilt(sos, x) + >>> f2, zo = signal.sosfilt(sos, x, zi=zi) + + >>> plt.plot(x, 'k--', label='x') + >>> plt.plot(f1, 'b', alpha=0.5, linewidth=2, label='filtered') + >>> plt.plot(f2, 'g', alpha=0.25, linewidth=4, label='filtered with zi') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + sos = np.asarray(sos) + if sos.ndim != 2 or sos.shape[1] != 6: + raise ValueError('sos must be shape (n_sections, 6)') + + if sos.dtype.kind in 'bui': + sos = sos.astype(np.float64) + + n_sections = sos.shape[0] + zi = np.empty((n_sections, 2), dtype=sos.dtype) + scale = 1.0 + for section in range(n_sections): + b = sos[section, :3] + a = sos[section, 3:] + zi[section] = scale * lfilter_zi(b, a) + # If H(z) = B(z)/A(z) is this section's transfer function, then + # b.sum()/a.sum() is H(1), the gain at omega=0. That's the steady + # state value of this section's step response. + scale *= b.sum() / a.sum() + + return zi + + +def _filtfilt_gust(b, a, x, axis=-1, irlen=None): + """Forward-backward IIR filter that uses Gustafsson's method. + + Apply the IIR filter defined by ``(b,a)`` to `x` twice, first forward + then backward, using Gustafsson's initial conditions [1]_. + + Let ``y_fb`` be the result of filtering first forward and then backward, + and let ``y_bf`` be the result of filtering first backward then forward. + Gustafsson's method is to compute initial conditions for the forward + pass and the backward pass such that ``y_fb == y_bf``. + + Parameters + ---------- + b : scalar or 1-D ndarray + Numerator coefficients of the filter. + a : scalar or 1-D ndarray + Denominator coefficients of the filter. + x : ndarray + Data to be filtered. + axis : int, optional + Axis of `x` to be filtered. Default is -1. + irlen : int or None, optional + The length of the nonnegligible part of the impulse response. + If `irlen` is None, or if the length of the signal is less than + ``2 * irlen``, then no part of the impulse response is ignored. + + Returns + ------- + y : ndarray + The filtered data. + x0 : ndarray + Initial condition for the forward filter. + x1 : ndarray + Initial condition for the backward filter. + + Notes + ----- + Typically the return values `x0` and `x1` are not needed by the + caller. The intended use of these return values is in unit tests. + + References + ---------- + .. [1] F. Gustaffson. Determining the initial states in forward-backward + filtering. Transactions on Signal Processing, 46(4):988-992, 1996. + + """ + # In the comments, "Gustafsson's paper" and [1] refer to the + # paper referenced in the docstring. + + b = np.atleast_1d(b) + a = np.atleast_1d(a) + + order = max(len(b), len(a)) - 1 + if order == 0: + # The filter is just scalar multiplication, with no state. + scale = (b[0] / a[0])**2 + y = scale * x + return y, np.array([]), np.array([]) + + if axis != -1 or axis != x.ndim - 1: + # Move the axis containing the data to the end. + x = np.swapaxes(x, axis, x.ndim - 1) + + # n is the number of samples in the data to be filtered. + n = x.shape[-1] + + if irlen is None or n <= 2*irlen: + m = n + else: + m = irlen + + # Create Obs, the observability matrix (called O in the paper). + # This matrix can be interpreted as the operator that propagates + # an arbitrary initial state to the output, assuming the input is + # zero. + # In Gustafsson's paper, the forward and backward filters are not + # necessarily the same, so he has both O_f and O_b. We use the same + # filter in both directions, so we only need O. The same comment + # applies to S below. + Obs = np.zeros((m, order)) + zi = np.zeros(order) + zi[0] = 1 + Obs[:, 0] = lfilter(b, a, np.zeros(m), zi=zi)[0] + for k in range(1, order): + Obs[k:, k] = Obs[:-k, 0] + + # Obsr is O^R (Gustafsson's notation for row-reversed O) + Obsr = Obs[::-1] + + # Create S. S is the matrix that applies the filter to the reversed + # propagated initial conditions. That is, + # out = S.dot(zi) + # is the same as + # tmp, _ = lfilter(b, a, zeros(), zi=zi) # Propagate ICs. + # out = lfilter(b, a, tmp[::-1]) # Reverse and filter. + + # Equations (5) & (6) of [1] + S = lfilter(b, a, Obs[::-1], axis=0) + + # Sr is S^R (row-reversed S) + Sr = S[::-1] + + # M is [(S^R - O), (O^R - S)] + if m == n: + M = np.hstack((Sr - Obs, Obsr - S)) + else: + # Matrix described in section IV of [1]. + M = np.zeros((2*m, 2*order)) + M[:m, :order] = Sr - Obs + M[m:, order:] = Obsr - S + + # Naive forward-backward and backward-forward filters. + # These have large transients because the filters use zero initial + # conditions. + y_f = lfilter(b, a, x) + y_fb = lfilter(b, a, y_f[..., ::-1])[..., ::-1] + + y_b = lfilter(b, a, x[..., ::-1])[..., ::-1] + y_bf = lfilter(b, a, y_b) + + delta_y_bf_fb = y_bf - y_fb + if m == n: + delta = delta_y_bf_fb + else: + start_m = delta_y_bf_fb[..., :m] + end_m = delta_y_bf_fb[..., -m:] + delta = np.concatenate((start_m, end_m), axis=-1) + + # ic_opt holds the "optimal" initial conditions. + # The following code computes the result shown in the formula + # of the paper between equations (6) and (7). + if delta.ndim == 1: + ic_opt = linalg.lstsq(M, delta)[0] + else: + # Reshape delta so it can be used as an array of multiple + # right-hand-sides in linalg.lstsq. + delta2d = delta.reshape(-1, delta.shape[-1]).T + ic_opt0 = linalg.lstsq(M, delta2d)[0].T + ic_opt = ic_opt0.reshape(delta.shape[:-1] + (M.shape[-1],)) + + # Now compute the filtered signal using equation (7) of [1]. + # First, form [S^R, O^R] and call it W. + if m == n: + W = np.hstack((Sr, Obsr)) + else: + W = np.zeros((2*m, 2*order)) + W[:m, :order] = Sr + W[m:, order:] = Obsr + + # Equation (7) of [1] says + # Y_fb^opt = Y_fb^0 + W * [x_0^opt; x_{N-1}^opt] + # `wic` is (almost) the product on the right. + # W has shape (m, 2*order), and ic_opt has shape (..., 2*order), + # so we can't use W.dot(ic_opt). Instead, we dot ic_opt with W.T, + # so wic has shape (..., m). + wic = ic_opt.dot(W.T) + + # `wic` is "almost" the product of W and the optimal ICs in equation + # (7)--if we're using a truncated impulse response (m < n), `wic` + # contains only the adjustments required for the ends of the signal. + # Here we form y_opt, taking this into account if necessary. + y_opt = y_fb + if m == n: + y_opt += wic + else: + y_opt[..., :m] += wic[..., :m] + y_opt[..., -m:] += wic[..., -m:] + + x0 = ic_opt[..., :order] + x1 = ic_opt[..., -order:] + if axis != -1 or axis != x.ndim - 1: + # Restore the data axis to its original position. + x0 = np.swapaxes(x0, axis, x.ndim - 1) + x1 = np.swapaxes(x1, axis, x.ndim - 1) + y_opt = np.swapaxes(y_opt, axis, x.ndim - 1) + + return y_opt, x0, x1 + + +def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad', + irlen=None): + """ + Apply a digital filter forward and backward to a signal. + + This function applies a linear digital filter twice, once forward and + once backwards. The combined filter has zero phase and a filter order + twice that of the original. + + The function provides options for handling the edges of the signal. + + The function `sosfiltfilt` (and filter design using ``output='sos'``) + should be preferred over `filtfilt` for most filtering tasks, as + second-order sections have fewer numerical problems. + + Parameters + ---------- + b : (N,) array_like + The numerator coefficient vector of the filter. + a : (N,) array_like + The denominator coefficient vector of the filter. If ``a[0]`` + is not 1, then both `a` and `b` are normalized by ``a[0]``. + x : array_like + The array of data to be filtered. + axis : int, optional + The axis of `x` to which the filter is applied. + Default is -1. + padtype : str or None, optional + Must be 'odd', 'even', 'constant', or None. This determines the + type of extension to use for the padded signal to which the filter + is applied. If `padtype` is None, no padding is used. The default + is 'odd'. + padlen : int or None, optional + The number of elements by which to extend `x` at both ends of + `axis` before applying the filter. This value must be less than + ``x.shape[axis] - 1``. ``padlen=0`` implies no padding. + The default value is ``3 * max(len(a), len(b))``. + method : str, optional + Determines the method for handling the edges of the signal, either + "pad" or "gust". When `method` is "pad", the signal is padded; the + type of padding is determined by `padtype` and `padlen`, and `irlen` + is ignored. When `method` is "gust", Gustafsson's method is used, + and `padtype` and `padlen` are ignored. + irlen : int or None, optional + When `method` is "gust", `irlen` specifies the length of the + impulse response of the filter. If `irlen` is None, no part + of the impulse response is ignored. For a long signal, specifying + `irlen` can significantly improve the performance of the filter. + + Returns + ------- + y : ndarray + The filtered output with the same shape as `x`. + + See Also + -------- + sosfiltfilt, lfilter_zi, lfilter, lfiltic, savgol_filter, sosfilt + + Notes + ----- + When `method` is "pad", the function pads the data along the given axis + in one of three ways: odd, even or constant. The odd and even extensions + have the corresponding symmetry about the end point of the data. The + constant extension extends the data with the values at the end points. On + both the forward and backward passes, the initial condition of the + filter is found by using `lfilter_zi` and scaling it by the end point of + the extended data. + + When `method` is "gust", Gustafsson's method [1]_ is used. Initial + conditions are chosen for the forward and backward passes so that the + forward-backward filter gives the same result as the backward-forward + filter. + + The option to use Gustaffson's method was added in scipy version 0.16.0. + + References + ---------- + .. [1] F. Gustaffson, "Determining the initial states in forward-backward + filtering", Transactions on Signal Processing, Vol. 46, pp. 988-992, + 1996. + + Examples + -------- + The examples will use several functions from `scipy.signal`. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + First we create a one second signal that is the sum of two pure sine + waves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz. + + >>> t = np.linspace(0, 1.0, 2001) + >>> xlow = np.sin(2 * np.pi * 5 * t) + >>> xhigh = np.sin(2 * np.pi * 250 * t) + >>> x = xlow + xhigh + + Now create a lowpass Butterworth filter with a cutoff of 0.125 times + the Nyquist frequency, or 125 Hz, and apply it to ``x`` with `filtfilt`. + The result should be approximately ``xlow``, with no phase shift. + + >>> b, a = signal.butter(8, 0.125) + >>> y = signal.filtfilt(b, a, x, padlen=150) + >>> np.abs(y - xlow).max() + 9.1086182074789912e-06 + + We get a fairly clean result for this artificial example because + the odd extension is exact, and with the moderately long padding, + the filter's transients have dissipated by the time the actual data + is reached. In general, transient effects at the edges are + unavoidable. + + The following example demonstrates the option ``method="gust"``. + + First, create a filter. + + >>> b, a = signal.ellip(4, 0.01, 120, 0.125) # Filter to be applied. + + `sig` is a random input signal to be filtered. + + >>> rng = np.random.default_rng() + >>> n = 60 + >>> sig = rng.standard_normal(n)**3 + 3*rng.standard_normal(n).cumsum() + + Apply `filtfilt` to `sig`, once using the Gustafsson method, and + once using padding, and plot the results for comparison. + + >>> fgust = signal.filtfilt(b, a, sig, method="gust") + >>> fpad = signal.filtfilt(b, a, sig, padlen=50) + >>> plt.plot(sig, 'k-', label='input') + >>> plt.plot(fgust, 'b-', linewidth=4, label='gust') + >>> plt.plot(fpad, 'c-', linewidth=1.5, label='pad') + >>> plt.legend(loc='best') + >>> plt.show() + + The `irlen` argument can be used to improve the performance + of Gustafsson's method. + + Estimate the impulse response length of the filter. + + >>> z, p, k = signal.tf2zpk(b, a) + >>> eps = 1e-9 + >>> r = np.max(np.abs(p)) + >>> approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r))) + >>> approx_impulse_len + 137 + + Apply the filter to a longer signal, with and without the `irlen` + argument. The difference between `y1` and `y2` is small. For long + signals, using `irlen` gives a significant performance improvement. + + >>> x = rng.standard_normal(4000) + >>> y1 = signal.filtfilt(b, a, x, method='gust') + >>> y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len) + >>> print(np.max(np.abs(y1 - y2))) + 2.875334415008979e-10 + + """ + b = np.atleast_1d(b) + a = np.atleast_1d(a) + x = np.asarray(x) + + if method not in ["pad", "gust"]: + raise ValueError("method must be 'pad' or 'gust'.") + + if method == "gust": + y, z1, z2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen) + return y + + # method == "pad" + edge, ext = _validate_pad(padtype, padlen, x, axis, + ntaps=max(len(a), len(b))) + + # Get the steady state of the filter's step response. + zi = lfilter_zi(b, a) + + # Reshape zi and create x0 so that zi*x0 broadcasts + # to the correct value for the 'zi' keyword argument + # to lfilter. + zi_shape = [1] * x.ndim + zi_shape[axis] = zi.size + zi = np.reshape(zi, zi_shape) + x0 = axis_slice(ext, stop=1, axis=axis) + + # Forward filter. + (y, zf) = lfilter(b, a, ext, axis=axis, zi=zi * x0) + + # Backward filter. + # Create y0 so zi*y0 broadcasts appropriately. + y0 = axis_slice(y, start=-1, axis=axis) + (y, zf) = lfilter(b, a, axis_reverse(y, axis=axis), axis=axis, zi=zi * y0) + + # Reverse y. + y = axis_reverse(y, axis=axis) + + if edge > 0: + # Slice the actual signal from the extended signal. + y = axis_slice(y, start=edge, stop=-edge, axis=axis) + + return y + + +def _validate_pad(padtype, padlen, x, axis, ntaps): + """Helper to validate padding for filtfilt""" + if padtype not in ['even', 'odd', 'constant', None]: + raise ValueError(f"Unknown value '{padtype}' given to padtype. " + "padtype must be 'even', 'odd', 'constant', or None.") + + if padtype is None: + padlen = 0 + + if padlen is None: + # Original padding; preserved for backwards compatibility. + edge = ntaps * 3 + else: + edge = padlen + + # x's 'axis' dimension must be bigger than edge. + if x.shape[axis] <= edge: + raise ValueError("The length of the input vector x must be greater " + "than padlen, which is %d." % edge) + + if padtype is not None and edge > 0: + # Make an extension of length `edge` at each + # end of the input array. + if padtype == 'even': + ext = even_ext(x, edge, axis=axis) + elif padtype == 'odd': + ext = odd_ext(x, edge, axis=axis) + else: + ext = const_ext(x, edge, axis=axis) + else: + ext = x + return edge, ext + + +def _validate_x(x): + x = np.asarray(x) + if x.ndim == 0: + raise ValueError('x must be at least 1-D') + return x + + +def sosfilt(sos, x, axis=-1, zi=None): + """ + Filter data along one dimension using cascaded second-order sections. + + Filter a data sequence, `x`, using a digital IIR filter defined by + `sos`. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. Each row corresponds to a second-order + section, with the first three columns providing the numerator + coefficients and the last three providing the denominator + coefficients. + x : array_like + An N-dimensional input array. + axis : int, optional + The axis of the input data array along which to apply the + linear filter. The filter is applied to each subarray along + this axis. Default is -1. + zi : array_like, optional + Initial conditions for the cascaded filter delays. It is a (at + least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where + ``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]`` + replaced by 2. If `zi` is None or is not given then initial rest + (i.e. all zeros) is assumed. + Note that these initial conditions are *not* the same as the initial + conditions given by `lfiltic` or `lfilter_zi`. + + Returns + ------- + y : ndarray + The output of the digital filter. + zf : ndarray, optional + If `zi` is None, this is not returned, otherwise, `zf` holds the + final filter delay values. + + See Also + -------- + zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, freqz_sos + + Notes + ----- + The filter function is implemented as a series of second-order filters + with direct-form II transposed structure. It is designed to minimize + numerical precision errors for high-order filters. + + .. versionadded:: 0.16.0 + + Examples + -------- + Plot a 13th-order filter's impulse response using both `lfilter` and + `sosfilt`, showing the instability that results from trying to do a + 13th-order filter in a single stage (the numerical error pushes some poles + outside of the unit circle): + + >>> import matplotlib.pyplot as plt + >>> from scipy import signal + >>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba') + >>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos') + >>> x = signal.unit_impulse(700) + >>> y_tf = signal.lfilter(b, a, x) + >>> y_sos = signal.sosfilt(sos, x) + >>> plt.plot(y_tf, 'r', label='TF') + >>> plt.plot(y_sos, 'k', label='SOS') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + _reject_objects(sos, 'sosfilt') + _reject_objects(x, 'sosfilt') + if zi is not None: + _reject_objects(zi, 'sosfilt') + + x = _validate_x(x) + sos, n_sections = _validate_sos(sos) + x_zi_shape = list(x.shape) + x_zi_shape[axis] = 2 + x_zi_shape = tuple([n_sections] + x_zi_shape) + inputs = [sos, x] + if zi is not None: + inputs.append(np.asarray(zi)) + dtype = np.result_type(*inputs) + if dtype.char not in 'fdgFDGO': + raise NotImplementedError(f"input type '{dtype}' not supported") + if zi is not None: + zi = np.array(zi, dtype) # make a copy so that we can operate in place + if zi.shape != x_zi_shape: + raise ValueError('Invalid zi shape. With axis=%r, an input with ' + 'shape %r, and an sos array with %d sections, zi ' + 'must have shape %r, got %r.' % + (axis, x.shape, n_sections, x_zi_shape, zi.shape)) + return_zi = True + else: + zi = np.zeros(x_zi_shape, dtype=dtype) + return_zi = False + axis = axis % x.ndim # make positive + x = np.moveaxis(x, axis, -1) + zi = np.moveaxis(zi, [0, axis + 1], [-2, -1]) + x_shape, zi_shape = x.shape, zi.shape + x = np.reshape(x, (-1, x.shape[-1])) + x = np.array(x, dtype, order='C') # make a copy, can modify in place + zi = np.ascontiguousarray(np.reshape(zi, (-1, n_sections, 2))) + sos = sos.astype(dtype, copy=False) + _sosfilt(sos, x, zi) + x.shape = x_shape + x = np.moveaxis(x, -1, axis) + if return_zi: + zi.shape = zi_shape + zi = np.moveaxis(zi, [-2, -1], [0, axis + 1]) + out = (x, zi) + else: + out = x + return out + + +def sosfiltfilt(sos, x, axis=-1, padtype='odd', padlen=None): + """ + A forward-backward digital filter using cascaded second-order sections. + + See `filtfilt` for more complete information about this method. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. Each row corresponds to a second-order + section, with the first three columns providing the numerator + coefficients and the last three providing the denominator + coefficients. + x : array_like + The array of data to be filtered. + axis : int, optional + The axis of `x` to which the filter is applied. + Default is -1. + padtype : str or None, optional + Must be 'odd', 'even', 'constant', or None. This determines the + type of extension to use for the padded signal to which the filter + is applied. If `padtype` is None, no padding is used. The default + is 'odd'. + padlen : int or None, optional + The number of elements by which to extend `x` at both ends of + `axis` before applying the filter. This value must be less than + ``x.shape[axis] - 1``. ``padlen=0`` implies no padding. + The default value is:: + + 3 * (2 * len(sos) + 1 - min((sos[:, 2] == 0).sum(), + (sos[:, 5] == 0).sum())) + + The extra subtraction at the end attempts to compensate for poles + and zeros at the origin (e.g. for odd-order filters) to yield + equivalent estimates of `padlen` to those of `filtfilt` for + second-order section filters built with `scipy.signal` functions. + + Returns + ------- + y : ndarray + The filtered output with the same shape as `x`. + + See Also + -------- + filtfilt, sosfilt, sosfilt_zi, freqz_sos + + Notes + ----- + .. versionadded:: 0.18.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import sosfiltfilt, butter + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Create an interesting signal to filter. + + >>> n = 201 + >>> t = np.linspace(0, 1, n) + >>> x = 1 + (t < 0.5) - 0.25*t**2 + 0.05*rng.standard_normal(n) + + Create a lowpass Butterworth filter, and use it to filter `x`. + + >>> sos = butter(4, 0.125, output='sos') + >>> y = sosfiltfilt(sos, x) + + For comparison, apply an 8th order filter using `sosfilt`. The filter + is initialized using the mean of the first four values of `x`. + + >>> from scipy.signal import sosfilt, sosfilt_zi + >>> sos8 = butter(8, 0.125, output='sos') + >>> zi = x[:4].mean() * sosfilt_zi(sos8) + >>> y2, zo = sosfilt(sos8, x, zi=zi) + + Plot the results. Note that the phase of `y` matches the input, while + `y2` has a significant phase delay. + + >>> plt.plot(t, x, alpha=0.5, label='x(t)') + >>> plt.plot(t, y, label='y(t)') + >>> plt.plot(t, y2, label='y2(t)') + >>> plt.legend(framealpha=1, shadow=True) + >>> plt.grid(alpha=0.25) + >>> plt.xlabel('t') + >>> plt.show() + + """ + sos, n_sections = _validate_sos(sos) + x = _validate_x(x) + + # `method` is "pad"... + ntaps = 2 * n_sections + 1 + ntaps -= min((sos[:, 2] == 0).sum(), (sos[:, 5] == 0).sum()) + edge, ext = _validate_pad(padtype, padlen, x, axis, + ntaps=ntaps) + + # These steps follow the same form as filtfilt with modifications + zi = sosfilt_zi(sos) # shape (n_sections, 2) --> (n_sections, ..., 2, ...) + zi_shape = [1] * x.ndim + zi_shape[axis] = 2 + zi.shape = [n_sections] + zi_shape + x_0 = axis_slice(ext, stop=1, axis=axis) + (y, zf) = sosfilt(sos, ext, axis=axis, zi=zi * x_0) + y_0 = axis_slice(y, start=-1, axis=axis) + (y, zf) = sosfilt(sos, axis_reverse(y, axis=axis), axis=axis, zi=zi * y_0) + y = axis_reverse(y, axis=axis) + if edge > 0: + y = axis_slice(y, start=edge, stop=-edge, axis=axis) + return y + + +def decimate(x, q, n=None, ftype='iir', axis=-1, zero_phase=True): + """ + Downsample the signal after applying an anti-aliasing filter. + + By default, an order 8 Chebyshev type I filter is used. A 30 point FIR + filter with Hamming window is used if `ftype` is 'fir'. + + Parameters + ---------- + x : array_like + The signal to be downsampled, as an N-dimensional array. + q : int + The downsampling factor. When using IIR downsampling, it is recommended + to call `decimate` multiple times for downsampling factors higher than + 13. + n : int, optional + The order of the filter (1 less than the length for 'fir'). Defaults to + 8 for 'iir' and 20 times the downsampling factor for 'fir'. + ftype : str {'iir', 'fir'} or ``dlti`` instance, optional + If 'iir' or 'fir', specifies the type of lowpass filter. If an instance + of an `dlti` object, uses that object to filter before downsampling. + axis : int, optional + The axis along which to decimate. + zero_phase : bool, optional + Prevent phase shift by filtering with `filtfilt` instead of `lfilter` + when using an IIR filter, and shifting the outputs back by the filter's + group delay when using an FIR filter. The default value of ``True`` is + recommended, since a phase shift is generally not desired. + + .. versionadded:: 0.18.0 + + Returns + ------- + y : ndarray + The down-sampled signal. + + See Also + -------- + resample : Resample up or down using the FFT method. + resample_poly : Resample using polyphase filtering and an FIR filter. + + Notes + ----- + The ``zero_phase`` keyword was added in 0.18.0. + The possibility to use instances of ``dlti`` as ``ftype`` was added in + 0.18.0. + + Examples + -------- + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Define wave parameters. + + >>> wave_duration = 3 + >>> sample_rate = 100 + >>> freq = 2 + >>> q = 5 + + Calculate number of samples. + + >>> samples = wave_duration*sample_rate + >>> samples_decimated = int(samples/q) + + Create cosine wave. + + >>> x = np.linspace(0, wave_duration, samples, endpoint=False) + >>> y = np.cos(x*np.pi*freq*2) + + Decimate cosine wave. + + >>> ydem = signal.decimate(y, q) + >>> xnew = np.linspace(0, wave_duration, samples_decimated, endpoint=False) + + Plot original and decimated waves. + + >>> plt.plot(x, y, '.-', xnew, ydem, 'o-') + >>> plt.xlabel('Time, Seconds') + >>> plt.legend(['data', 'decimated'], loc='best') + >>> plt.show() + + """ + + x = np.asarray(x) + q = operator.index(q) + + if n is not None: + n = operator.index(n) + + result_type = x.dtype + if not np.issubdtype(result_type, np.inexact) \ + or result_type.type == np.float16: + # upcast integers and float16 to float64 + result_type = np.float64 + + if ftype == 'fir': + if n is None: + half_len = 10 * q # reasonable cutoff for our sinc-like function + n = 2 * half_len + b, a = firwin(n+1, 1. / q, window='hamming'), 1. + b = np.asarray(b, dtype=result_type) + a = np.asarray(a, dtype=result_type) + elif ftype == 'iir': + iir_use_sos = True + if n is None: + n = 8 + sos = cheby1(n, 0.05, 0.8 / q, output='sos') + sos = np.asarray(sos, dtype=result_type) + elif isinstance(ftype, dlti): + system = ftype._as_zpk() + if system.poles.shape[0] == 0: + # FIR + system = ftype._as_tf() + b, a = system.num, system.den + ftype = 'fir' + elif (any(np.iscomplex(system.poles)) + or any(np.iscomplex(system.poles)) + or np.iscomplex(system.gain)): + # sosfilt & sosfiltfilt don't handle complex coeffs + iir_use_sos = False + system = ftype._as_tf() + b, a = system.num, system.den + else: + iir_use_sos = True + sos = zpk2sos(system.zeros, system.poles, system.gain) + sos = np.asarray(sos, dtype=result_type) + else: + raise ValueError('invalid ftype') + + sl = [slice(None)] * x.ndim + + if ftype == 'fir': + b = b / a + if zero_phase: + y = resample_poly(x, 1, q, axis=axis, window=b) + else: + # upfirdn is generally faster than lfilter by a factor equal to the + # downsampling factor, since it only calculates the needed outputs + n_out = x.shape[axis] // q + bool(x.shape[axis] % q) + y = upfirdn(b, x, up=1, down=q, axis=axis) + sl[axis] = slice(None, n_out, None) + + else: # IIR case + if zero_phase: + if iir_use_sos: + y = sosfiltfilt(sos, x, axis=axis) + else: + y = filtfilt(b, a, x, axis=axis) + else: + if iir_use_sos: + y = sosfilt(sos, x, axis=axis) + else: + y = lfilter(b, a, x, axis=axis) + + sl[axis] = slice(None, None, q) + + return y[tuple(sl)] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9697a8a7dda74e71dadf9522d0ba943d2946a581 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spectral_py.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spectral_py.py new file mode 100644 index 0000000000000000000000000000000000000000..5151b2b335172a485b5d13408d35290812cadc43 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spectral_py.py @@ -0,0 +1,2291 @@ +"""Tools for spectral analysis. +""" +import numpy as np +import numpy.typing as npt +from scipy import fft as sp_fft +from . import _signaltools +from .windows import get_window +from ._arraytools import const_ext, even_ext, odd_ext, zero_ext +import warnings +from typing import Literal + + +__all__ = ['periodogram', 'welch', 'lombscargle', 'csd', 'coherence', + 'spectrogram', 'stft', 'istft', 'check_COLA', 'check_NOLA'] + + +def lombscargle( + x: npt.ArrayLike, + y: npt.ArrayLike, + freqs: npt.ArrayLike, + precenter: bool = False, + normalize: bool | Literal["power", "normalize", "amplitude"] = False, + *, + weights: npt.NDArray | None = None, + floating_mean: bool = False, +) -> npt.NDArray: + """ + Compute the generalized Lomb-Scargle periodogram. + + The Lomb-Scargle periodogram was developed by Lomb [1]_ and further + extended by Scargle [2]_ to find, and test the significance of weak + periodic signals with uneven temporal sampling. The algorithm used + here is based on a weighted least-squares fit of the form + ``y(ω) = a*cos(ω*x) + b*sin(ω*x) + c``, where the fit is calculated for + each frequency independently. This algorithm was developed by Zechmeister + and Kürster which improves the Lomb-Scargle periodogram by enabling + the weighting of individual samples and calculating an unknown y offset + (also called a "floating-mean" model) [3]_. For more details, and practical + considerations, see the excellent reference on the Lomb-Scargle periodogram [4]_. + + When *normalize* is False (or "power") (default) the computed periodogram + is unnormalized, it takes the value ``(A**2) * N/4`` for a harmonic + signal with amplitude A for sufficiently large N. Where N is the length of x or y. + + When *normalize* is True (or "normalize") the computed periodogram is normalized + by the residuals of the data around a constant reference model (at zero). + + When *normalize* is "amplitude" the computed periodogram is the complex + representation of the amplitude and phase. + + Input arrays should be 1-D of a real floating data type, which are converted into + float64 arrays before processing. + + Parameters + ---------- + x : array_like + Sample times. + y : array_like + Measurement values. Values are assumed to have a baseline of ``y = 0``. If + there is a possibility of a y offset, it is recommended to set `floating_mean` + to True. + freqs : array_like + Angular frequencies (e.g., having unit rad/s=2π/s for `x` having unit s) for + output periodogram. Frequencies are normally >= 0, as any peak at ``-freq`` will + also exist at ``+freq``. + precenter : bool, optional + Pre-center measurement values by subtracting the mean, if True. This is + a legacy parameter and unnecessary if `floating_mean` is True. + normalize : bool | str, optional + Compute normalized or complex (amplitude + phase) periodogram. + Valid options are: ``False``/``"power"``, ``True``/``"normalize"``, or + ``"amplitude"``. + weights : array_like, optional + Weights for each sample. Weights must be nonnegative. + floating_mean : bool, optional + Determines a y offset for each frequency independently, if True. + Else the y offset is assumed to be `0`. + + Returns + ------- + pgram : array_like + Lomb-Scargle periodogram. + + Raises + ------ + ValueError + If any of the input arrays x, y, freqs, or weights are not 1D, or if any are + zero length. Or, if the input arrays x, y, and weights do not have the same + shape as each other. + ValueError + If any weight is < 0, or the sum of the weights is <= 0. + ValueError + If the normalize parameter is not one of the allowed options. + + See Also + -------- + periodogram: Power spectral density using a periodogram + welch: Power spectral density by Welch's method + csd: Cross spectral density by Welch's method + + Notes + ----- + The algorithm used will not automatically account for any unknown y offset, unless + floating_mean is True. Therefore, for most use cases, if there is a possibility of + a y offset, it is recommended to set floating_mean to True. If precenter is True, + it performs the operation ``y -= y.mean()``. However, precenter is a legacy + parameter, and unnecessary when floating_mean is True. Furthermore, the mean + removed by precenter does not account for sample weights, nor will it correct for + any bias due to consistently missing observations at peaks and/or troughs. When the + normalize parameter is "amplitude", for any frequency in freqs that is below + ``(2*pi)/(x.max() - x.min())``, the predicted amplitude will tend towards infinity. + The concept of a "Nyquist frequency" limit (see Nyquist-Shannon sampling theorem) + is not generally applicable to unevenly sampled data. Therefore, with unevenly + sampled data, valid frequencies in freqs can often be much higher than expected. + + References + ---------- + .. [1] N.R. Lomb "Least-squares frequency analysis of unequally spaced + data", Astrophysics and Space Science, vol 39, pp. 447-462, 1976 + :doi:`10.1007/bf00648343` + + .. [2] J.D. Scargle "Studies in astronomical time series analysis. II - + Statistical aspects of spectral analysis of unevenly spaced data", + The Astrophysical Journal, vol 263, pp. 835-853, 1982 + :doi:`10.1086/160554` + + .. [3] M. Zechmeister and M. Kürster, "The generalised Lomb-Scargle periodogram. + A new formalism for the floating-mean and Keplerian periodograms," + Astronomy and Astrophysics, vol. 496, pp. 577-584, 2009 + :doi:`10.1051/0004-6361:200811296` + + .. [4] J.T. VanderPlas, "Understanding the Lomb-Scargle Periodogram," + The Astrophysical Journal Supplement Series, vol. 236, no. 1, p. 16, + May 2018 + :doi:`10.3847/1538-4365/aab766` + + + Examples + -------- + >>> import numpy as np + >>> rng = np.random.default_rng() + + First define some input parameters for the signal: + + >>> A = 2. # amplitude + >>> c = 2. # offset + >>> w0 = 1. # rad/sec + >>> nin = 150 + >>> nout = 1002 + + Randomly generate sample times: + + >>> x = rng.uniform(0, 10*np.pi, nin) + + Plot a sine wave for the selected times: + + >>> y = A * np.cos(w0*x) + c + + Define the array of frequencies for which to compute the periodogram: + + >>> w = np.linspace(0.25, 10, nout) + + Calculate Lomb-Scargle periodogram for each of the normalize options: + + >>> from scipy.signal import lombscargle + >>> pgram_power = lombscargle(x, y, w, normalize=False) + >>> pgram_norm = lombscargle(x, y, w, normalize=True) + >>> pgram_amp = lombscargle(x, y, w, normalize='amplitude') + ... + >>> pgram_power_f = lombscargle(x, y, w, normalize=False, floating_mean=True) + >>> pgram_norm_f = lombscargle(x, y, w, normalize=True, floating_mean=True) + >>> pgram_amp_f = lombscargle(x, y, w, normalize='amplitude', floating_mean=True) + + Now make a plot of the input data: + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_t, ax_p, ax_n, ax_a) = plt.subplots(4, 1, figsize=(5, 6)) + >>> ax_t.plot(x, y, 'b+') + >>> ax_t.set_xlabel('Time [s]') + >>> ax_t.set_ylabel('Amplitude') + + Then plot the periodogram for each of the normalize options, as well as with and + without floating_mean=True: + + >>> ax_p.plot(w, pgram_power, label='default') + >>> ax_p.plot(w, pgram_power_f, label='floating_mean=True') + >>> ax_p.set_xlabel('Angular frequency [rad/s]') + >>> ax_p.set_ylabel('Power') + >>> ax_p.legend(prop={'size': 7}) + ... + >>> ax_n.plot(w, pgram_norm, label='default') + >>> ax_n.plot(w, pgram_norm_f, label='floating_mean=True') + >>> ax_n.set_xlabel('Angular frequency [rad/s]') + >>> ax_n.set_ylabel('Normalized') + >>> ax_n.legend(prop={'size': 7}) + ... + >>> ax_a.plot(w, np.abs(pgram_amp), label='default') + >>> ax_a.plot(w, np.abs(pgram_amp_f), label='floating_mean=True') + >>> ax_a.set_xlabel('Angular frequency [rad/s]') + >>> ax_a.set_ylabel('Amplitude') + >>> ax_a.legend(prop={'size': 7}) + ... + >>> plt.tight_layout() + >>> plt.show() + + """ + + # if no weights are provided, assume all data points are equally important + if weights is None: + weights = np.ones_like(y, dtype=np.float64) + else: + # if provided, make sure weights is an array and cast to float64 + weights = np.asarray(weights, dtype=np.float64) + + # make sure other inputs are arrays and cast to float64 + # done before validation, in case they were not arrays + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + freqs = np.asarray(freqs, dtype=np.float64) + + # validate input shapes + if not (x.ndim == 1 and x.size > 0 and x.shape == y.shape == weights.shape): + raise ValueError("Parameters x, y, weights must be 1-D arrays of " + "equal non-zero length!") + if not (freqs.ndim == 1 and freqs.size > 0): + raise ValueError("Parameter freqs must be a 1-D array of non-zero length!") + + # validate weights + if not (np.all(weights >= 0) and np.sum(weights) > 0): + raise ValueError("Parameter weights must have only non-negative entries " + "which sum to a positive value!") + + # validate normalize parameter + if isinstance(normalize, bool): + # if bool, convert to str literal + normalize = "normalize" if normalize else "power" + + if normalize not in ["power", "normalize", "amplitude"]: + raise ValueError( + "Normalize must be: False (or 'power'), True (or 'normalize'), " + "or 'amplitude'." + ) + + # weight vector must sum to 1 + weights *= 1.0 / weights.sum() + + # if requested, perform precenter + if precenter: + y -= y.mean() + + # transform arrays + # row vector + freqs = freqs.reshape(1, -1) + # column vectors + x = x.reshape(-1, 1) + y = y.reshape(-1, 1) + weights = weights.reshape(-1, 1) + + # store frequent intermediates + weights_y = weights * y + freqst = freqs * x + coswt = np.cos(freqst) + sinwt = np.sin(freqst) + + Y = np.dot(weights.T, y) # Eq. 7 + CC = np.dot(weights.T, coswt * coswt) # Eq. 13 + SS = 1.0 - CC # trig identity: S^2 = 1 - C^2 Eq.14 + CS = np.dot(weights.T, coswt * sinwt) # Eq. 15 + + if floating_mean: + C = np.dot(weights.T, coswt) # Eq. 8 + S = np.dot(weights.T, sinwt) # Eq. 9 + CC -= C * C # Eq. 13 + SS -= S * S # Eq. 14 + CS -= C * S # Eq. 15 + + # calculate tau (phase offset to eliminate CS variable) + tau = 0.5 * np.arctan2(2.0 * CS, CC - SS) # Eq. 19 + freqst_tau = freqst - tau + + # coswt and sinwt are now offset by tau, which eliminates CS + coswt_tau = np.cos(freqst_tau) + sinwt_tau = np.sin(freqst_tau) + + YC = np.dot(weights_y.T, coswt_tau) # Eq. 11 + YS = np.dot(weights_y.T, sinwt_tau) # Eq. 12 + CC = np.dot(weights.T, coswt_tau * coswt_tau) # Eq. 13, CC range is [0.5, 1.0] + SS = 1.0 - CC # trig identity: S^2 = 1 - C^2 Eq. 14, SS range is [0.0, 0.5] + + if floating_mean: + C = np.dot(weights.T, coswt_tau) # Eq. 8 + S = np.dot(weights.T, sinwt_tau) # Eq. 9 + YC -= Y * C # Eq. 11 + YS -= Y * S # Eq. 12 + CC -= C * C # Eq. 13, CC range is now [0.0, 1.0] + SS -= S * S # Eq. 14, SS range is now [0.0, 0.5] + + # to prevent division by zero errors with a and b, as well as correcting for + # numerical precision errors that lead to CC or SS being approximately -0.0, + # make sure CC and SS are both > 0 + epsneg = np.finfo(dtype=y.dtype).epsneg + CC[CC < epsneg] = epsneg + SS[SS < epsneg] = epsneg + + # calculate a and b + # where: y(w) = a*cos(w) + b*sin(w) + c + a = YC / CC # Eq. A.4 and 6, eliminating CS + b = YS / SS # Eq. A.4 and 6, eliminating CS + # c = Y - a * C - b * S + + # store final value as power in A^2 (i.e., (y units)^2) + pgram = 2.0 * (a * YC + b * YS) + + # squeeze back to a vector + pgram = np.squeeze(pgram) + + if normalize == "power": # (default) + # return the legacy power units ((A**2) * N/4) + + pgram *= float(x.shape[0]) / 4.0 + + elif normalize == "normalize": + # return the normalized power (power at current frequency wrt the entire signal) + # range will be [0, 1] + + YY = np.dot(weights_y.T, y) # Eq. 10 + if floating_mean: + YY -= Y * Y # Eq. 10 + + pgram *= 0.5 / np.squeeze(YY) # Eq. 20 + + else: # normalize == "amplitude": + # return the complex representation of the best-fit amplitude and phase + + # squeeze back to vectors + a = np.squeeze(a) + b = np.squeeze(b) + tau = np.squeeze(tau) + + # calculate the complex representation, and correct for tau rotation + pgram = (a + 1j * b) * np.exp(1j * tau) + + return pgram + + +def periodogram(x, fs=1.0, window='boxcar', nfft=None, detrend='constant', + return_onesided=True, scaling='density', axis=-1): + """ + Estimate power spectral density using a periodogram. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be equal to the length + of the axis over which the periodogram is computed. Defaults + to 'boxcar'. + nfft : int, optional + Length of the FFT used. If `None` the length of `x` will be + used. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the power spectral density ('density') + where `Pxx` has units of V**2/Hz and computing the squared magnitude + spectrum ('spectrum') where `Pxx` has units of V**2, if `x` + is measured in V and `fs` is measured in Hz. Defaults to + 'density' + axis : int, optional + Axis along which the periodogram is computed; the default is + over the last axis (i.e. ``axis=-1``). + + Returns + ------- + f : ndarray + Array of sample frequencies. + Pxx : ndarray + Power spectral density or power spectrum of `x`. + + See Also + -------- + welch: Estimate power spectral density using Welch's method + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + + Notes + ----- + Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide` + for a discussion of the scalings of the power spectral density and + the magnitude (squared) spectrum. + + .. versionadded:: 0.12.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by + 0.001 V**2/Hz of white noise sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2*np.sqrt(2) + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> x = amp*np.sin(2*np.pi*freq*time) + >>> x += rng.normal(scale=np.sqrt(noise_power), size=time.shape) + + Compute and plot the power spectral density. + + >>> f, Pxx_den = signal.periodogram(x, fs) + >>> plt.semilogy(f, Pxx_den) + >>> plt.ylim([1e-7, 1e2]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('PSD [V**2/Hz]') + >>> plt.show() + + If we average the last half of the spectral density, to exclude the + peak, we can recover the noise power on the signal. + + >>> np.mean(Pxx_den[25000:]) + 0.000985320699252543 + + Now compute and plot the power spectrum. + + >>> f, Pxx_spec = signal.periodogram(x, fs, 'flattop', scaling='spectrum') + >>> plt.figure() + >>> plt.semilogy(f, np.sqrt(Pxx_spec)) + >>> plt.ylim([1e-4, 1e1]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('Linear spectrum [V RMS]') + >>> plt.show() + + The peak height in the power spectrum is an estimate of the RMS + amplitude. + + >>> np.sqrt(Pxx_spec.max()) + 2.0077340678640727 + + """ + x = np.asarray(x) + + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape) + + if window is None: + window = 'boxcar' + + if nfft is None: + nperseg = x.shape[axis] + elif nfft == x.shape[axis]: + nperseg = nfft + elif nfft > x.shape[axis]: + nperseg = x.shape[axis] + elif nfft < x.shape[axis]: + s = [np.s_[:]]*len(x.shape) + s[axis] = np.s_[:nfft] + x = x[tuple(s)] + nperseg = nfft + nfft = None + + if hasattr(window, 'size'): + if window.size != nperseg: + raise ValueError('the size of the window must be the same size ' + 'of the input on the specified axis') + + return welch(x, fs=fs, window=window, nperseg=nperseg, noverlap=0, + nfft=nfft, detrend=detrend, return_onesided=return_onesided, + scaling=scaling, axis=axis) + + +def welch(x, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, + detrend='constant', return_onesided=True, scaling='density', + axis=-1, average='mean'): + r""" + Estimate power spectral density using Welch's method. + + Welch's method [1]_ computes an estimate of the power spectral + density by dividing the data into overlapping segments, computing a + modified periodogram for each segment and averaging the + periodograms. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the power spectral density ('density') + where `Pxx` has units of V**2/Hz and computing the squared magnitude + spectrum ('spectrum') where `Pxx` has units of V**2, if `x` + is measured in V and `fs` is measured in Hz. Defaults to + 'density' + axis : int, optional + Axis along which the periodogram is computed; the default is + over the last axis (i.e. ``axis=-1``). + average : { 'mean', 'median' }, optional + Method to use when averaging periodograms. Defaults to 'mean'. + + .. versionadded:: 1.2.0 + + Returns + ------- + f : ndarray + Array of sample frequencies. + Pxx : ndarray + Power spectral density or power spectrum of x. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + + Notes + ----- + An appropriate amount of overlap will depend on the choice of window + and on your requirements. For the default Hann window an overlap of + 50% is a reasonable trade off between accurately estimating the + signal power, while not over counting any of the data. Narrower + windows may require a larger overlap. + + If `noverlap` is 0, this method is equivalent to Bartlett's method + [2]_. + + Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide` + for a discussion of the scalings of the power spectral density and + the (squared) magnitude spectrum. + + .. versionadded:: 0.12.0 + + References + ---------- + .. [1] P. Welch, "The use of the fast Fourier transform for the + estimation of power spectra: A method based on time averaging + over short, modified periodograms", IEEE Trans. Audio + Electroacoust. vol. 15, pp. 70-73, 1967. + .. [2] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", + Biometrika, vol. 37, pp. 1-16, 1950. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by + 0.001 V**2/Hz of white noise sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2*np.sqrt(2) + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> x = amp*np.sin(2*np.pi*freq*time) + >>> x += rng.normal(scale=np.sqrt(noise_power), size=time.shape) + + Compute and plot the power spectral density. + + >>> f, Pxx_den = signal.welch(x, fs, nperseg=1024) + >>> plt.semilogy(f, Pxx_den) + >>> plt.ylim([0.5e-3, 1]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('PSD [V**2/Hz]') + >>> plt.show() + + If we average the last half of the spectral density, to exclude the + peak, we can recover the noise power on the signal. + + >>> np.mean(Pxx_den[256:]) + 0.0009924865443739191 + + Now compute and plot the power spectrum. + + >>> f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum') + >>> plt.figure() + >>> plt.semilogy(f, np.sqrt(Pxx_spec)) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('Linear spectrum [V RMS]') + >>> plt.show() + + The peak height in the power spectrum is an estimate of the RMS + amplitude. + + >>> np.sqrt(Pxx_spec.max()) + 2.0077340678640727 + + If we now introduce a discontinuity in the signal, by increasing the + amplitude of a small portion of the signal by 50, we can see the + corruption of the mean average power spectral density, but using a + median average better estimates the normal behaviour. + + >>> x[int(N//2):int(N//2)+10] *= 50. + >>> f, Pxx_den = signal.welch(x, fs, nperseg=1024) + >>> f_med, Pxx_den_med = signal.welch(x, fs, nperseg=1024, average='median') + >>> plt.semilogy(f, Pxx_den, label='mean') + >>> plt.semilogy(f_med, Pxx_den_med, label='median') + >>> plt.ylim([0.5e-3, 1]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('PSD [V**2/Hz]') + >>> plt.legend() + >>> plt.show() + + """ + freqs, Pxx = csd(x, x, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, + return_onesided=return_onesided, scaling=scaling, + axis=axis, average=average) + + return freqs, Pxx.real + + +def csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, + detrend='constant', return_onesided=True, scaling='density', + axis=-1, average='mean'): + r""" + Estimate the cross power spectral density, Pxy, using Welch's method. + + Parameters + ---------- + x : array_like + Time series of measurement values + y : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` and `y` time series. Defaults + to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap: int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the cross spectral density ('density') + where `Pxy` has units of V**2/Hz and computing the cross spectrum + ('spectrum') where `Pxy` has units of V**2, if `x` and `y` are + measured in V and `fs` is measured in Hz. Defaults to 'density' + axis : int, optional + Axis along which the CSD is computed for both inputs; the + default is over the last axis (i.e. ``axis=-1``). + average : { 'mean', 'median' }, optional + Method to use when averaging periodograms. If the spectrum is + complex, the average is computed separately for the real and + imaginary parts. Defaults to 'mean'. + + .. versionadded:: 1.2.0 + + Returns + ------- + f : ndarray + Array of sample frequencies. + Pxy : ndarray + Cross spectral density or cross power spectrum of x,y. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + welch: Power spectral density by Welch's method. [Equivalent to + csd(x,x)] + coherence: Magnitude squared coherence by Welch's method. + + Notes + ----- + By convention, Pxy is computed with the conjugate FFT of X + multiplied by the FFT of Y. + + If the input series differ in length, the shorter series will be + zero-padded to match. + + An appropriate amount of overlap will depend on the choice of window + and on your requirements. For the default Hann window an overlap of + 50% is a reasonable trade off between accurately estimating the + signal power, while not over counting any of the data. Narrower + windows may require a larger overlap. + + Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide` + for a discussion of the scalings of a spectral density and an (amplitude) spectrum. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] P. Welch, "The use of the fast Fourier transform for the + estimation of power spectra: A method based on time averaging + over short, modified periodograms", IEEE Trans. Audio + Electroacoust. vol. 15, pp. 70-73, 1967. + .. [2] Rabiner, Lawrence R., and B. Gold. "Theory and Application of + Digital Signal Processing" Prentice-Hall, pp. 414-419, 1975 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate two test signals with some common features. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 20 + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> b, a = signal.butter(2, 0.25, 'low') + >>> x = rng.normal(scale=np.sqrt(noise_power), size=time.shape) + >>> y = signal.lfilter(b, a, x) + >>> x += amp*np.sin(2*np.pi*freq*time) + >>> y += rng.normal(scale=0.1*np.sqrt(noise_power), size=time.shape) + + Compute and plot the magnitude of the cross spectral density. + + >>> f, Pxy = signal.csd(x, y, fs, nperseg=1024) + >>> plt.semilogy(f, np.abs(Pxy)) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('CSD [V**2/Hz]') + >>> plt.show() + + """ + freqs, _, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, + nfft, detrend, return_onesided, scaling, + axis, mode='psd') + + # Average over windows. + if len(Pxy.shape) >= 2 and Pxy.size > 0: + if Pxy.shape[-1] > 1: + if average == 'median': + # np.median must be passed real arrays for the desired result + bias = _median_bias(Pxy.shape[-1]) + if np.iscomplexobj(Pxy): + Pxy = (np.median(np.real(Pxy), axis=-1) + + 1j * np.median(np.imag(Pxy), axis=-1)) + else: + Pxy = np.median(Pxy, axis=-1) + Pxy /= bias + elif average == 'mean': + Pxy = Pxy.mean(axis=-1) + else: + raise ValueError(f'average must be "median" or "mean", got {average}') + else: + Pxy = np.reshape(Pxy, Pxy.shape[:-1]) + + return freqs, Pxy + + +def spectrogram(x, fs=1.0, window=('tukey', .25), nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, mode='psd'): + """Compute a spectrogram with consecutive Fourier transforms (legacy function). + + Spectrograms can be used as a way of visualizing the change of a + nonstationary signal's frequency content over time. + + .. legacy:: function + + :class:`ShortTimeFFT` is a newer STFT / ISTFT implementation with more + features also including a :meth:`~ShortTimeFFT.spectrogram` method. + A :ref:`comparison ` between the + implementations can be found in the :ref:`tutorial_stft` section of + the :ref:`user_guide`. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. + Defaults to a Tukey window with shape parameter of 0.25. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 8``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the power spectral density ('density') + where `Sxx` has units of V**2/Hz and computing the power + spectrum ('spectrum') where `Sxx` has units of V**2, if `x` + is measured in V and `fs` is measured in Hz. Defaults to + 'density'. + axis : int, optional + Axis along which the spectrogram is computed; the default is over + the last axis (i.e. ``axis=-1``). + mode : str, optional + Defines what kind of return values are expected. Options are + ['psd', 'complex', 'magnitude', 'angle', 'phase']. 'complex' is + equivalent to the output of `stft` with no padding or boundary + extension. 'magnitude' returns the absolute magnitude of the + STFT. 'angle' and 'phase' return the complex angle of the STFT, + with and without unwrapping, respectively. + + Returns + ------- + f : ndarray + Array of sample frequencies. + t : ndarray + Array of segment times. + Sxx : ndarray + Spectrogram of x. By default, the last axis of Sxx corresponds + to the segment times. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + welch: Power spectral density by Welch's method. + csd: Cross spectral density by Welch's method. + ShortTimeFFT: Newer STFT/ISTFT implementation providing more features, + which also includes a :meth:`~ShortTimeFFT.spectrogram` + method. + + Notes + ----- + An appropriate amount of overlap will depend on the choice of window + and on your requirements. In contrast to welch's method, where the + entire data stream is averaged over, one may wish to use a smaller + overlap (or perhaps none at all) when computing a spectrogram, to + maintain some statistical independence between individual segments. + It is for this reason that the default window is a Tukey window with + 1/8th of a window's length overlap at each end. + + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck + "Discrete-Time Signal Processing", Prentice Hall, 1999. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fftshift + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave whose frequency is slowly + modulated around 3kHz, corrupted by white noise of exponentially + decreasing magnitude sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2 * np.sqrt(2) + >>> noise_power = 0.01 * fs / 2 + >>> time = np.arange(N) / float(fs) + >>> mod = 500*np.cos(2*np.pi*0.25*time) + >>> carrier = amp * np.sin(2*np.pi*3e3*time + mod) + >>> noise = rng.normal(scale=np.sqrt(noise_power), size=time.shape) + >>> noise *= np.exp(-time/5) + >>> x = carrier + noise + + Compute and plot the spectrogram. + + >>> f, t, Sxx = signal.spectrogram(x, fs) + >>> plt.pcolormesh(t, f, Sxx, shading='gouraud') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.show() + + Note, if using output that is not one sided, then use the following: + + >>> f, t, Sxx = signal.spectrogram(x, fs, return_onesided=False) + >>> plt.pcolormesh(t, fftshift(f), fftshift(Sxx, axes=0), shading='gouraud') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.show() + + """ + modelist = ['psd', 'complex', 'magnitude', 'angle', 'phase'] + if mode not in modelist: + raise ValueError(f'unknown value for mode {mode}, must be one of {modelist}') + + # need to set default for nperseg before setting default for noverlap below + window, nperseg = _triage_segments(window, nperseg, + input_length=x.shape[axis]) + + # Less overlap than welch, so samples are more statistically independent + if noverlap is None: + noverlap = nperseg // 8 + + if mode == 'psd': + freqs, time, Sxx = _spectral_helper(x, x, fs, window, nperseg, + noverlap, nfft, detrend, + return_onesided, scaling, axis, + mode='psd') + + else: + freqs, time, Sxx = _spectral_helper(x, x, fs, window, nperseg, + noverlap, nfft, detrend, + return_onesided, scaling, axis, + mode='stft') + + if mode == 'magnitude': + Sxx = np.abs(Sxx) + elif mode in ['angle', 'phase']: + Sxx = np.angle(Sxx) + if mode == 'phase': + # Sxx has one additional dimension for time strides + if axis < 0: + axis -= 1 + Sxx = np.unwrap(Sxx, axis=axis) + + # mode =='complex' is same as `stft`, doesn't need modification + + return freqs, time, Sxx + + +def check_COLA(window, nperseg, noverlap, tol=1e-10): + r"""Check whether the Constant OverLap Add (COLA) constraint is met. + + Parameters + ---------- + window : str or tuple or array_like + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. + nperseg : int + Length of each segment. + noverlap : int + Number of points to overlap between segments. + tol : float, optional + The allowed variance of a bin's weighted sum from the median bin + sum. + + Returns + ------- + verdict : bool + `True` if chosen combination satisfies COLA within `tol`, + `False` otherwise + + See Also + -------- + check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met + stft: Short Time Fourier Transform + istft: Inverse Short Time Fourier Transform + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT in + `istft`, it is sufficient that the signal windowing obeys the constraint of + "Constant OverLap Add" (COLA). This ensures that every point in the input + data is equally weighted, thereby avoiding aliasing and allowing full + reconstruction. + + Some examples of windows that satisfy COLA: + - Rectangular window at overlap of 0, 1/2, 2/3, 3/4, ... + - Bartlett window at overlap of 1/2, 3/4, 5/6, ... + - Hann window at 1/2, 2/3, 3/4, ... + - Any Blackman family window at 2/3 overlap + - Any window with ``noverlap = nperseg-1`` + + A very comprehensive list of other windows may be found in [2]_, + wherein the COLA condition is satisfied when the "Amplitude + Flatness" is unity. + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Julius O. Smith III, "Spectral Audio Signal Processing", W3K + Publishing, 2011,ISBN 978-0-9745607-3-1. + .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and + spectral density estimation by the Discrete Fourier transform + (DFT), including a comprehensive list of window functions and + some new at-top windows", 2002, + http://hdl.handle.net/11858/00-001M-0000-0013-557A-5 + + Examples + -------- + >>> from scipy import signal + + Confirm COLA condition for rectangular window of 75% (3/4) overlap: + + >>> signal.check_COLA(signal.windows.boxcar(100), 100, 75) + True + + COLA is not true for 25% (1/4) overlap, though: + + >>> signal.check_COLA(signal.windows.boxcar(100), 100, 25) + False + + "Symmetrical" Hann window (for filter design) is not COLA: + + >>> signal.check_COLA(signal.windows.hann(120, sym=True), 120, 60) + False + + "Periodic" or "DFT-even" Hann window (for FFT analysis) is COLA for + overlap of 1/2, 2/3, 3/4, etc.: + + >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 60) + True + + >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 80) + True + + >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 90) + True + + """ + nperseg = int(nperseg) + + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + noverlap = int(noverlap) + + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError('window must have length of nperseg') + + step = nperseg - noverlap + binsums = sum(win[ii*step:(ii+1)*step] for ii in range(nperseg//step)) + + if nperseg % step != 0: + binsums[:nperseg % step] += win[-(nperseg % step):] + + deviation = binsums - np.median(binsums) + return np.max(np.abs(deviation)) < tol + + +def check_NOLA(window, nperseg, noverlap, tol=1e-10): + r"""Check whether the Nonzero Overlap Add (NOLA) constraint is met. + + Parameters + ---------- + window : str or tuple or array_like + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. + nperseg : int + Length of each segment. + noverlap : int + Number of points to overlap between segments. + tol : float, optional + The allowed variance of a bin's weighted sum from the median bin + sum. + + Returns + ------- + verdict : bool + `True` if chosen combination satisfies the NOLA constraint within + `tol`, `False` otherwise + + See Also + -------- + check_COLA: Check whether the Constant OverLap Add (COLA) constraint is met + stft: Short Time Fourier Transform + istft: Inverse Short Time Fourier Transform + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT in + `istft`, the signal windowing must obey the constraint of "nonzero + overlap add" (NOLA): + + .. math:: \sum_{t}w^{2}[n-tH] \ne 0 + + for all :math:`n`, where :math:`w` is the window function, :math:`t` is the + frame index, and :math:`H` is the hop size (:math:`H` = `nperseg` - + `noverlap`). + + This ensures that the normalization factors in the denominator of the + overlap-add inversion equation are not zero. Only very pathological windows + will fail the NOLA constraint. + + .. versionadded:: 1.2.0 + + References + ---------- + .. [1] Julius O. Smith III, "Spectral Audio Signal Processing", W3K + Publishing, 2011,ISBN 978-0-9745607-3-1. + .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and + spectral density estimation by the Discrete Fourier transform + (DFT), including a comprehensive list of window functions and + some new at-top windows", 2002, + http://hdl.handle.net/11858/00-001M-0000-0013-557A-5 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + + Confirm NOLA condition for rectangular window of 75% (3/4) overlap: + + >>> signal.check_NOLA(signal.windows.boxcar(100), 100, 75) + True + + NOLA is also true for 25% (1/4) overlap: + + >>> signal.check_NOLA(signal.windows.boxcar(100), 100, 25) + True + + "Symmetrical" Hann window (for filter design) is also NOLA: + + >>> signal.check_NOLA(signal.windows.hann(120, sym=True), 120, 60) + True + + As long as there is overlap, it takes quite a pathological window to fail + NOLA: + + >>> w = np.ones(64, dtype="float") + >>> w[::2] = 0 + >>> signal.check_NOLA(w, 64, 32) + False + + If there is not enough overlap, a window with zeros at the ends will not + work: + + >>> signal.check_NOLA(signal.windows.hann(64), 64, 0) + False + >>> signal.check_NOLA(signal.windows.hann(64), 64, 1) + False + >>> signal.check_NOLA(signal.windows.hann(64), 64, 2) + True + + """ + nperseg = int(nperseg) + + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg') + if noverlap < 0: + raise ValueError('noverlap must be a nonnegative integer') + noverlap = int(noverlap) + + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError('window must have length of nperseg') + + step = nperseg - noverlap + binsums = sum(win[ii*step:(ii+1)*step]**2 for ii in range(nperseg//step)) + + if nperseg % step != 0: + binsums[:nperseg % step] += win[-(nperseg % step):]**2 + + return np.min(binsums) > tol + + +def stft(x, fs=1.0, window='hann', nperseg=256, noverlap=None, nfft=None, + detrend=False, return_onesided=True, boundary='zeros', padded=True, + axis=-1, scaling='spectrum'): + r"""Compute the Short Time Fourier Transform (legacy function). + + STFTs can be used as a way of quantifying the change of a + nonstationary signal's frequency and phase content over time. + + .. legacy:: function + + `ShortTimeFFT` is a newer STFT / ISTFT implementation with more + features. A :ref:`comparison ` between the + implementations can be found in the :ref:`tutorial_stft` section of the + :ref:`user_guide`. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to 256. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. When + specified, the COLA constraint must be met (see Notes below). + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to `False`. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + boundary : str or None, optional + Specifies whether the input signal is extended at both ends, and + how to generate the new values, in order to center the first + windowed segment on the first input point. This has the benefit + of enabling reconstruction of the first input point when the + employed window function starts at zero. Valid options are + ``['even', 'odd', 'constant', 'zeros', None]``. Defaults to + 'zeros', for zero padding extension. I.e. ``[1, 2, 3, 4]`` is + extended to ``[0, 1, 2, 3, 4, 0]`` for ``nperseg=3``. + padded : bool, optional + Specifies whether the input signal is zero-padded at the end to + make the signal fit exactly into an integer number of window + segments, so that all of the signal is included in the output. + Defaults to `True`. Padding occurs after boundary extension, if + `boundary` is not `None`, and `padded` is `True`, as is the + default. + axis : int, optional + Axis along which the STFT is computed; the default is over the + last axis (i.e. ``axis=-1``). + scaling: {'spectrum', 'psd'} + The default 'spectrum' scaling allows each frequency line of `Zxx` to + be interpreted as a magnitude spectrum. The 'psd' option scales each + line to a power spectral density - it allows to calculate the signal's + energy by numerically integrating over ``abs(Zxx)**2``. + + .. versionadded:: 1.9.0 + + Returns + ------- + f : ndarray + Array of sample frequencies. + t : ndarray + Array of segment times. + Zxx : ndarray + STFT of `x`. By default, the last axis of `Zxx` corresponds + to the segment times. + + See Also + -------- + istft: Inverse Short Time Fourier Transform + ShortTimeFFT: Newer STFT/ISTFT implementation providing more features. + check_COLA: Check whether the Constant OverLap Add (COLA) constraint + is met + check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met + welch: Power spectral density by Welch's method. + spectrogram: Spectrogram by Welch's method. + csd: Cross spectral density by Welch's method. + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT in + `istft`, the signal windowing must obey the constraint of "Nonzero + OverLap Add" (NOLA), and the input signal must have complete + windowing coverage (i.e. ``(x.shape[axis] - nperseg) % + (nperseg-noverlap) == 0``). The `padded` argument may be used to + accomplish this. + + Given a time-domain signal :math:`x[n]`, a window :math:`w[n]`, and a hop + size :math:`H` = `nperseg - noverlap`, the windowed frame at time index + :math:`t` is given by + + .. math:: x_{t}[n]=x[n]w[n-tH] + + The overlap-add (OLA) reconstruction equation is given by + + .. math:: x[n]=\frac{\sum_{t}x_{t}[n]w[n-tH]}{\sum_{t}w^{2}[n-tH]} + + The NOLA constraint ensures that every normalization term that appears + in the denominator of the OLA reconstruction equation is nonzero. Whether a + choice of `window`, `nperseg`, and `noverlap` satisfy this constraint can + be tested with `check_NOLA`. + + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck + "Discrete-Time Signal Processing", Prentice Hall, 1999. + .. [2] Daniel W. Griffin, Jae S. Lim "Signal Estimation from + Modified Short-Time Fourier Transform", IEEE 1984, + 10.1109/TASSP.1984.1164317 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave whose frequency is slowly + modulated around 3kHz, corrupted by white noise of exponentially + decreasing magnitude sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2 * np.sqrt(2) + >>> noise_power = 0.01 * fs / 2 + >>> time = np.arange(N) / float(fs) + >>> mod = 500*np.cos(2*np.pi*0.25*time) + >>> carrier = amp * np.sin(2*np.pi*3e3*time + mod) + >>> noise = rng.normal(scale=np.sqrt(noise_power), + ... size=time.shape) + >>> noise *= np.exp(-time/5) + >>> x = carrier + noise + + Compute and plot the STFT's magnitude. + + >>> f, t, Zxx = signal.stft(x, fs, nperseg=1000) + >>> plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud') + >>> plt.title('STFT Magnitude') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.show() + + Compare the energy of the signal `x` with the energy of its STFT: + + >>> E_x = sum(x**2) / fs # Energy of x + >>> # Calculate a two-sided STFT with PSD scaling: + >>> f, t, Zxx = signal.stft(x, fs, nperseg=1000, return_onesided=False, + ... scaling='psd') + >>> # Integrate numerically over abs(Zxx)**2: + >>> df, dt = f[1] - f[0], t[1] - t[0] + >>> E_Zxx = sum(np.sum(Zxx.real**2 + Zxx.imag**2, axis=0) * df) * dt + >>> # The energy is the same, but the numerical errors are quite large: + >>> np.isclose(E_x, E_Zxx, rtol=1e-2) + True + + """ + if scaling == 'psd': + scaling = 'density' + elif scaling != 'spectrum': + raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!") + + freqs, time, Zxx = _spectral_helper(x, x, fs, window, nperseg, noverlap, + nfft, detrend, return_onesided, + scaling=scaling, axis=axis, + mode='stft', boundary=boundary, + padded=padded) + + return freqs, time, Zxx + + +def istft(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, + input_onesided=True, boundary=True, time_axis=-1, freq_axis=-2, + scaling='spectrum'): + r"""Perform the inverse Short Time Fourier transform (legacy function). + + .. legacy:: function + + `ShortTimeFFT` is a newer STFT / ISTFT implementation with more + features. A :ref:`comparison ` between the + implementations can be found in the :ref:`tutorial_stft` section of the + :ref:`user_guide`. + + Parameters + ---------- + Zxx : array_like + STFT of the signal to be reconstructed. If a purely real array + is passed, it will be cast to a complex data type. + fs : float, optional + Sampling frequency of the time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. Must match the window used to generate the + STFT for faithful inversion. + nperseg : int, optional + Number of data points corresponding to each STFT segment. This + parameter must be specified if the number of data points per + segment is odd, or if the STFT was padded via ``nfft > + nperseg``. If `None`, the value depends on the shape of + `Zxx` and `input_onesided`. If `input_onesided` is `True`, + ``nperseg=2*(Zxx.shape[freq_axis] - 1)``. Otherwise, + ``nperseg=Zxx.shape[freq_axis]``. Defaults to `None`. + noverlap : int, optional + Number of points to overlap between segments. If `None`, half + of the segment length. Defaults to `None`. When specified, the + COLA constraint must be met (see Notes below), and should match + the parameter used to generate the STFT. Defaults to `None`. + nfft : int, optional + Number of FFT points corresponding to each STFT segment. This + parameter must be specified if the STFT was padded via ``nfft > + nperseg``. If `None`, the default values are the same as for + `nperseg`, detailed above, with one exception: if + `input_onesided` is True and + ``nperseg==2*Zxx.shape[freq_axis] - 1``, `nfft` also takes on + that value. This case allows the proper inversion of an + odd-length unpadded STFT using ``nfft=None``. Defaults to + `None`. + input_onesided : bool, optional + If `True`, interpret the input array as one-sided FFTs, such + as is returned by `stft` with ``return_onesided=True`` and + `numpy.fft.rfft`. If `False`, interpret the input as a a + two-sided FFT. Defaults to `True`. + boundary : bool, optional + Specifies whether the input signal was extended at its + boundaries by supplying a non-`None` ``boundary`` argument to + `stft`. Defaults to `True`. + time_axis : int, optional + Where the time segments of the STFT is located; the default is + the last axis (i.e. ``axis=-1``). + freq_axis : int, optional + Where the frequency axis of the STFT is located; the default is + the penultimate axis (i.e. ``axis=-2``). + scaling: {'spectrum', 'psd'} + The default 'spectrum' scaling allows each frequency line of `Zxx` to + be interpreted as a magnitude spectrum. The 'psd' option scales each + line to a power spectral density - it allows to calculate the signal's + energy by numerically integrating over ``abs(Zxx)**2``. + + Returns + ------- + t : ndarray + Array of output data times. + x : ndarray + iSTFT of `Zxx`. + + See Also + -------- + stft: Short Time Fourier Transform + ShortTimeFFT: Newer STFT/ISTFT implementation providing more features. + check_COLA: Check whether the Constant OverLap Add (COLA) constraint + is met + check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT with + `istft`, the signal windowing must obey the constraint of "nonzero + overlap add" (NOLA): + + .. math:: \sum_{t}w^{2}[n-tH] \ne 0 + + This ensures that the normalization factors that appear in the denominator + of the overlap-add reconstruction equation + + .. math:: x[n]=\frac{\sum_{t}x_{t}[n]w[n-tH]}{\sum_{t}w^{2}[n-tH]} + + are not zero. The NOLA constraint can be checked with the `check_NOLA` + function. + + An STFT which has been modified (via masking or otherwise) is not + guaranteed to correspond to a exactly realizible signal. This + function implements the iSTFT via the least-squares estimation + algorithm detailed in [2]_, which produces a signal that minimizes + the mean squared error between the STFT of the returned signal and + the modified STFT. + + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck + "Discrete-Time Signal Processing", Prentice Hall, 1999. + .. [2] Daniel W. Griffin, Jae S. Lim "Signal Estimation from + Modified Short-Time Fourier Transform", IEEE 1984, + 10.1109/TASSP.1984.1164317 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave at 50Hz corrupted by + 0.001 V**2/Hz of white noise sampled at 1024 Hz. + + >>> fs = 1024 + >>> N = 10*fs + >>> nperseg = 512 + >>> amp = 2 * np.sqrt(2) + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / float(fs) + >>> carrier = amp * np.sin(2*np.pi*50*time) + >>> noise = rng.normal(scale=np.sqrt(noise_power), + ... size=time.shape) + >>> x = carrier + noise + + Compute the STFT, and plot its magnitude + + >>> f, t, Zxx = signal.stft(x, fs=fs, nperseg=nperseg) + >>> plt.figure() + >>> plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud') + >>> plt.ylim([f[1], f[-1]]) + >>> plt.title('STFT Magnitude') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.yscale('log') + >>> plt.show() + + Zero the components that are 10% or less of the carrier magnitude, + then convert back to a time series via inverse STFT + + >>> Zxx = np.where(np.abs(Zxx) >= amp/10, Zxx, 0) + >>> _, xrec = signal.istft(Zxx, fs) + + Compare the cleaned signal with the original and true carrier signals. + + >>> plt.figure() + >>> plt.plot(time, x, time, xrec, time, carrier) + >>> plt.xlim([2, 2.1]) + >>> plt.xlabel('Time [sec]') + >>> plt.ylabel('Signal') + >>> plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier']) + >>> plt.show() + + Note that the cleaned signal does not start as abruptly as the original, + since some of the coefficients of the transient were also removed: + + >>> plt.figure() + >>> plt.plot(time, x, time, xrec, time, carrier) + >>> plt.xlim([0, 0.1]) + >>> plt.xlabel('Time [sec]') + >>> plt.ylabel('Signal') + >>> plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier']) + >>> plt.show() + + """ + # Make sure input is an ndarray of appropriate complex dtype + Zxx = np.asarray(Zxx) + 0j + freq_axis = int(freq_axis) + time_axis = int(time_axis) + + if Zxx.ndim < 2: + raise ValueError('Input stft must be at least 2d!') + + if freq_axis == time_axis: + raise ValueError('Must specify differing time and frequency axes!') + + nseg = Zxx.shape[time_axis] + + if input_onesided: + # Assume even segment length + n_default = 2*(Zxx.shape[freq_axis] - 1) + else: + n_default = Zxx.shape[freq_axis] + + # Check windowing parameters + if nperseg is None: + nperseg = n_default + else: + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if nfft is None: + if (input_onesided) and (nperseg == n_default + 1): + # Odd nperseg, no FFT padding + nfft = nperseg + else: + nfft = n_default + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + # Rearrange axes if necessary + if time_axis != Zxx.ndim-1 or freq_axis != Zxx.ndim-2: + # Turn negative indices to positive for the call to transpose + if freq_axis < 0: + freq_axis = Zxx.ndim + freq_axis + if time_axis < 0: + time_axis = Zxx.ndim + time_axis + zouter = list(range(Zxx.ndim)) + for ax in sorted([time_axis, freq_axis], reverse=True): + zouter.pop(ax) + Zxx = np.transpose(Zxx, zouter+[freq_axis, time_axis]) + + # Get window as array + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError(f'window must have length of {nperseg}') + + ifunc = sp_fft.irfft if input_onesided else sp_fft.ifft + xsubs = ifunc(Zxx, axis=-2, n=nfft)[..., :nperseg, :] + + # Initialize output and normalization arrays + outputlength = nperseg + (nseg-1)*nstep + x = np.zeros(list(Zxx.shape[:-2])+[outputlength], dtype=xsubs.dtype) + norm = np.zeros(outputlength, dtype=xsubs.dtype) + + if np.result_type(win, xsubs) != xsubs.dtype: + win = win.astype(xsubs.dtype) + + if scaling == 'spectrum': + xsubs *= win.sum() + elif scaling == 'psd': + xsubs *= np.sqrt(fs * sum(win**2)) + else: + raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!") + + # Construct the output from the ifft segments + # This loop could perhaps be vectorized/strided somehow... + for ii in range(nseg): + # Window the ifft + x[..., ii*nstep:ii*nstep+nperseg] += xsubs[..., ii] * win + norm[..., ii*nstep:ii*nstep+nperseg] += win**2 + + # Remove extension points + if boundary: + x = x[..., nperseg//2:-(nperseg//2)] + norm = norm[..., nperseg//2:-(nperseg//2)] + + # Divide out normalization where non-tiny + if np.sum(norm > 1e-10) != len(norm): + warnings.warn( + "NOLA condition failed, STFT may not be invertible." + + (" Possibly due to missing boundary" if not boundary else ""), + stacklevel=2 + ) + x /= np.where(norm > 1e-10, norm, 1.0) + + if input_onesided: + x = x.real + + # Put axes back + if x.ndim > 1: + if time_axis != Zxx.ndim-1: + if freq_axis < time_axis: + time_axis -= 1 + x = np.moveaxis(x, -1, time_axis) + + time = np.arange(x.shape[0])/float(fs) + return time, x + + +def coherence(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', axis=-1): + r""" + Estimate the magnitude squared coherence estimate, Cxy, of + discrete-time signals X and Y using Welch's method. + + ``Cxy = abs(Pxy)**2/(Pxx*Pyy)``, where `Pxx` and `Pyy` are power + spectral density estimates of X and Y, and `Pxy` is the cross + spectral density estimate of X and Y. + + Parameters + ---------- + x : array_like + Time series of measurement values + y : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` and `y` time series. Defaults + to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap: int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + axis : int, optional + Axis along which the coherence is computed for both inputs; the + default is over the last axis (i.e. ``axis=-1``). + + Returns + ------- + f : ndarray + Array of sample frequencies. + Cxy : ndarray + Magnitude squared coherence of x and y. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + welch: Power spectral density by Welch's method. + csd: Cross spectral density by Welch's method. + + Notes + ----- + An appropriate amount of overlap will depend on the choice of window + and on your requirements. For the default Hann window an overlap of + 50% is a reasonable trade off between accurately estimating the + signal power, while not over counting any of the data. Narrower + windows may require a larger overlap. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] P. Welch, "The use of the fast Fourier transform for the + estimation of power spectra: A method based on time averaging + over short, modified periodograms", IEEE Trans. Audio + Electroacoust. vol. 15, pp. 70-73, 1967. + .. [2] Stoica, Petre, and Randolph Moses, "Spectral Analysis of + Signals" Prentice Hall, 2005 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate two test signals with some common features. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 20 + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> b, a = signal.butter(2, 0.25, 'low') + >>> x = rng.normal(scale=np.sqrt(noise_power), size=time.shape) + >>> y = signal.lfilter(b, a, x) + >>> x += amp*np.sin(2*np.pi*freq*time) + >>> y += rng.normal(scale=0.1*np.sqrt(noise_power), size=time.shape) + + Compute and plot the coherence. + + >>> f, Cxy = signal.coherence(x, y, fs, nperseg=1024) + >>> plt.semilogy(f, Cxy) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('Coherence') + >>> plt.show() + + """ + freqs, Pxx = welch(x, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, + axis=axis) + _, Pyy = welch(y, fs=fs, window=window, nperseg=nperseg, noverlap=noverlap, + nfft=nfft, detrend=detrend, axis=axis) + _, Pxy = csd(x, y, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, axis=axis) + + Cxy = np.abs(Pxy)**2 / Pxx / Pyy + + return freqs, Cxy + + +def _spectral_helper(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, mode='psd', boundary=None, + padded=False): + """Calculate various forms of windowed FFTs for PSD, CSD, etc. + + This is a helper function that implements the commonality between + the stft, psd, csd, and spectrogram functions. It is not designed to + be called externally. The windows are not averaged over; the result + from each window is returned. + + Parameters + ---------- + x : array_like + Array or sequence containing the data to be analyzed. + y : array_like + Array or sequence containing the data to be analyzed. If this is + the same object in memory as `x` (i.e. ``_spectral_helper(x, + x, ...)``), the extra computations are spared. + fs : float, optional + Sampling frequency of the time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the cross spectral density ('density') + where `Pxy` has units of V**2/Hz and computing the cross + spectrum ('spectrum') where `Pxy` has units of V**2, if `x` + and `y` are measured in V and `fs` is measured in Hz. + Defaults to 'density' + axis : int, optional + Axis along which the FFTs are computed; the default is over the + last axis (i.e. ``axis=-1``). + mode: str {'psd', 'stft'}, optional + Defines what kind of return values are expected. Defaults to + 'psd'. + boundary : str or None, optional + Specifies whether the input signal is extended at both ends, and + how to generate the new values, in order to center the first + windowed segment on the first input point. This has the benefit + of enabling reconstruction of the first input point when the + employed window function starts at zero. Valid options are + ``['even', 'odd', 'constant', 'zeros', None]``. Defaults to + `None`. + padded : bool, optional + Specifies whether the input signal is zero-padded at the end to + make the signal fit exactly into an integer number of window + segments, so that all of the signal is included in the output. + Defaults to `False`. Padding occurs after boundary extension, if + `boundary` is not `None`, and `padded` is `True`. + + Returns + ------- + freqs : ndarray + Array of sample frequencies. + t : ndarray + Array of times corresponding to each data segment + result : ndarray + Array of output data, contents dependent on *mode* kwarg. + + Notes + ----- + Adapted from matplotlib.mlab + + .. versionadded:: 0.16.0 + """ + if mode not in ['psd', 'stft']: + raise ValueError(f"Unknown value for mode {mode}, must be one of: " + "{'psd', 'stft'}") + + boundary_funcs = {'even': even_ext, + 'odd': odd_ext, + 'constant': const_ext, + 'zeros': zero_ext, + None: None} + + if boundary not in boundary_funcs: + raise ValueError(f"Unknown boundary option '{boundary}', " + f"must be one of: {list(boundary_funcs.keys())}") + + # If x and y are the same object we can save ourselves some computation. + same_data = y is x + + if not same_data and mode != 'psd': + raise ValueError("x and y must be equal if mode is 'stft'") + + axis = int(axis) + + # Ensure we have np.arrays, get outdtype + x = np.asarray(x) + if not same_data: + y = np.asarray(y) + outdtype = np.result_type(x, y, np.complex64) + else: + outdtype = np.result_type(x, np.complex64) + + if not same_data: + # Check if we can broadcast the outer axes together + xouter = list(x.shape) + youter = list(y.shape) + xouter.pop(axis) + youter.pop(axis) + try: + outershape = np.broadcast(np.empty(xouter), np.empty(youter)).shape + except ValueError as e: + raise ValueError('x and y cannot be broadcast together.') from e + + if same_data: + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape) + else: + if x.size == 0 or y.size == 0: + outshape = outershape + (min([x.shape[axis], y.shape[axis]]),) + emptyout = np.moveaxis(np.empty(outshape), -1, axis) + return emptyout, emptyout, emptyout + + if x.ndim > 1: + if axis != -1: + x = np.moveaxis(x, axis, -1) + if not same_data and y.ndim > 1: + y = np.moveaxis(y, axis, -1) + + # Check if x and y are the same length, zero-pad if necessary + if not same_data: + if x.shape[-1] != y.shape[-1]: + if x.shape[-1] < y.shape[-1]: + pad_shape = list(x.shape) + pad_shape[-1] = y.shape[-1] - x.shape[-1] + x = np.concatenate((x, np.zeros(pad_shape)), -1) + else: + pad_shape = list(y.shape) + pad_shape[-1] = x.shape[-1] - y.shape[-1] + y = np.concatenate((y, np.zeros(pad_shape)), -1) + + if nperseg is not None: # if specified by user + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + # parse window; if array like, then set nperseg = win.shape + win, nperseg = _triage_segments(window, nperseg, input_length=x.shape[-1]) + + if nfft is None: + nfft = nperseg + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + # Padding occurs after boundary extension, so that the extended signal ends + # in zeros, instead of introducing an impulse at the end. + # I.e. if x = [..., 3, 2] + # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0] + # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3] + + if boundary is not None: + ext_func = boundary_funcs[boundary] + x = ext_func(x, nperseg//2, axis=-1) + if not same_data: + y = ext_func(y, nperseg//2, axis=-1) + + if padded: + # Pad to integer number of windowed segments + # I.e. make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg + nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg + zeros_shape = list(x.shape[:-1]) + [nadd] + x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1) + if not same_data: + zeros_shape = list(y.shape[:-1]) + [nadd] + y = np.concatenate((y, np.zeros(zeros_shape)), axis=-1) + + # Handle detrending and window functions + if not detrend: + def detrend_func(d): + return d + elif not hasattr(detrend, '__call__'): + def detrend_func(d): + return _signaltools.detrend(d, type=detrend, axis=-1) + elif axis != -1: + # Wrap this function so that it receives a shape that it could + # reasonably expect to receive. + def detrend_func(d): + d = np.moveaxis(d, -1, axis) + d = detrend(d) + return np.moveaxis(d, axis, -1) + else: + detrend_func = detrend + + if np.result_type(win, np.complex64) != outdtype: + win = win.astype(outdtype) + + if scaling == 'density': + scale = 1.0 / (fs * (win*win).sum()) + elif scaling == 'spectrum': + scale = 1.0 / win.sum()**2 + else: + raise ValueError(f'Unknown scaling: {scaling!r}') + + if mode == 'stft': + scale = np.sqrt(scale) + + if return_onesided: + if np.iscomplexobj(x): + sides = 'twosided' + warnings.warn('Input data is complex, switching to return_onesided=False', + stacklevel=3) + else: + sides = 'onesided' + if not same_data: + if np.iscomplexobj(y): + sides = 'twosided' + warnings.warn('Input data is complex, switching to ' + 'return_onesided=False', + stacklevel=3) + else: + sides = 'twosided' + + if sides == 'twosided': + freqs = sp_fft.fftfreq(nfft, 1/fs) + elif sides == 'onesided': + freqs = sp_fft.rfftfreq(nfft, 1/fs) + + # Perform the windowed FFTs + result = _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides) + + if not same_data: + # All the same operations on the y data + result_y = _fft_helper(y, win, detrend_func, nperseg, noverlap, nfft, + sides) + result = np.conjugate(result) * result_y + elif mode == 'psd': + result = np.conjugate(result) * result + + result *= scale + if sides == 'onesided' and mode == 'psd': + if nfft % 2: + result[..., 1:] *= 2 + else: + # Last point is unpaired Nyquist freq point, don't double + result[..., 1:-1] *= 2 + + time = np.arange(nperseg/2, x.shape[-1] - nperseg/2 + 1, + nperseg - noverlap)/float(fs) + if boundary is not None: + time -= (nperseg/2) / fs + + result = result.astype(outdtype) + + # All imaginary parts are zero anyways + if same_data and mode != 'stft': + result = result.real + + # Output is going to have new last axis for time/window index, so a + # negative axis index shifts down one + if axis < 0: + axis -= 1 + + # Roll frequency axis back to axis where the data came from + result = np.moveaxis(result, -1, axis) + + return freqs, time, result + + +def _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides): + """ + Calculate windowed FFT, for internal use by + `scipy.signal._spectral_helper`. + + This is a helper function that does the main FFT calculation for + `_spectral helper`. All input validation is performed there, and the + data axis is assumed to be the last axis of x. It is not designed to + be called externally. The windows are not averaged over; the result + from each window is returned. + + Returns + ------- + result : ndarray + Array of FFT data + + Notes + ----- + Adapted from matplotlib.mlab + + .. versionadded:: 0.16.0 + """ + # Created sliding window view of array + if nperseg == 1 and noverlap == 0: + result = x[..., np.newaxis] + else: + step = nperseg - noverlap + result = np.lib.stride_tricks.sliding_window_view( + x, window_shape=nperseg, axis=-1, writeable=True + ) + result = result[..., 0::step, :] + + # Detrend each data segment individually + result = detrend_func(result) + + # Apply window by multiplication + result = win * result + + # Perform the fft. Acts on last axis by default. Zero-pads automatically + if sides == 'twosided': + func = sp_fft.fft + else: + result = result.real + func = sp_fft.rfft + result = func(result, n=nfft) + + return result + + +def _triage_segments(window, nperseg, input_length): + """ + Parses window and nperseg arguments for spectrogram and _spectral_helper. + This is a helper function, not meant to be called externally. + + Parameters + ---------- + window : string, tuple, or ndarray + If window is specified by a string or tuple and nperseg is not + specified, nperseg is set to the default of 256 and returns a window of + that length. + If instead the window is array_like and nperseg is not specified, then + nperseg is set to the length of the window. A ValueError is raised if + the user supplies both an array_like window and a value for nperseg but + nperseg does not equal the length of the window. + + nperseg : int + Length of each segment + + input_length: int + Length of input signal, i.e. x.shape[-1]. Used to test for errors. + + Returns + ------- + win : ndarray + window. If function was called with string or tuple than this will hold + the actual array used as a window. + + nperseg : int + Length of each segment. If window is str or tuple, nperseg is set to + 256. If window is array_like, nperseg is set to the length of the + window. + """ + # parse window; if array like, then set nperseg = win.shape + if isinstance(window, str) or isinstance(window, tuple): + # if nperseg not specified + if nperseg is None: + nperseg = 256 # then change to default + if nperseg > input_length: + warnings.warn(f'nperseg = {nperseg:d} is greater than input length ' + f' = {input_length:d}, using nperseg = {input_length:d}', + stacklevel=3) + nperseg = input_length + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if input_length < win.shape[-1]: + raise ValueError('window is longer than input signal') + if nperseg is None: + nperseg = win.shape[0] + elif nperseg is not None: + if nperseg != win.shape[0]: + raise ValueError("value specified for nperseg is different" + " from length of window") + return win, nperseg + + +def _median_bias(n): + """ + Returns the bias of the median of a set of periodograms relative to + the mean. + + See Appendix B from [1]_ for details. + + Parameters + ---------- + n : int + Numbers of periodograms being averaged. + + Returns + ------- + bias : float + Calculated bias. + + References + ---------- + .. [1] B. Allen, W.G. Anderson, P.R. Brady, D.A. Brown, J.D.E. Creighton. + "FINDCHIRP: an algorithm for detection of gravitational waves from + inspiraling compact binaries", Physical Review D 85, 2012, + :arxiv:`gr-qc/0509116` + """ + ii_2 = 2 * np.arange(1., (n-1) // 2 + 1) + return 1 + np.sum(1. / (ii_2 + 1) - 1. / ii_2) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c776c84deedabf62573fdee3f6b0bea1089d0092 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c4225577db7ea188a2add225ecec1fbec855de06 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline.pyi @@ -0,0 +1,34 @@ + +import numpy as np +from numpy.typing import NDArray + +FloatingArray = NDArray[np.float32] | NDArray[np.float64] +ComplexArray = NDArray[np.complex64] | NDArray[np.complex128] +FloatingComplexArray = FloatingArray | ComplexArray + + +def symiirorder1_ic(signal: FloatingComplexArray, + c0: float, + z1: float, + precision: float) -> FloatingComplexArray: + ... + + +def symiirorder2_ic_fwd(signal: FloatingArray, + r: float, + omega: float, + precision: float) -> FloatingArray: + ... + + +def symiirorder2_ic_bwd(signal: FloatingArray, + r: float, + omega: float, + precision: float) -> FloatingArray: + ... + + +def sepfir2d(input: FloatingComplexArray, + hrow: FloatingComplexArray, + hcol: FloatingComplexArray) -> FloatingComplexArray: + ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline_filters.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7884c5cc5544e9fc6d37476016e7a2d0e81d57 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_spline_filters.py @@ -0,0 +1,808 @@ +from numpy import (asarray, pi, zeros_like, + array, arctan2, tan, ones, arange, floor, + r_, atleast_1d, sqrt, exp, greater, cos, add, sin, + moveaxis, abs, arctan, complex64, float32) +import numpy as np + +from scipy._lib._util import normalize_axis_index + +# From splinemodule.c +from ._spline import sepfir2d, symiirorder1_ic, symiirorder2_ic_fwd, symiirorder2_ic_bwd +from ._signaltools import lfilter, sosfilt, lfiltic +from ._arraytools import axis_slice, axis_reverse + +from scipy.interpolate import BSpline + + +__all__ = ['spline_filter', 'gauss_spline', + 'cspline1d', 'qspline1d', 'qspline2d', 'cspline2d', + 'cspline1d_eval', 'qspline1d_eval', 'symiirorder1', 'symiirorder2'] + + +def spline_filter(Iin, lmbda=5.0): + """Smoothing spline (cubic) filtering of a rank-2 array. + + Filter an input data set, `Iin`, using a (cubic) smoothing spline of + fall-off `lmbda`. + + Parameters + ---------- + Iin : array_like + input data set + lmbda : float, optional + spline smoothing fall-off value, default is `5.0`. + + Returns + ------- + res : ndarray + filtered input data + + Examples + -------- + We can filter an multi dimensional signal (ex: 2D image) using cubic + B-spline filter: + + >>> import numpy as np + >>> from scipy.signal import spline_filter + >>> import matplotlib.pyplot as plt + >>> orig_img = np.eye(20) # create an image + >>> orig_img[10, :] = 1.0 + >>> sp_filter = spline_filter(orig_img, lmbda=0.1) + >>> f, ax = plt.subplots(1, 2, sharex=True) + >>> for ind, data in enumerate([[orig_img, "original image"], + ... [sp_filter, "spline filter"]]): + ... ax[ind].imshow(data[0], cmap='gray_r') + ... ax[ind].set_title(data[1]) + >>> plt.tight_layout() + >>> plt.show() + + """ + if Iin.dtype not in [np.float32, np.float64, np.complex64, np.complex128]: + raise TypeError(f"Invalid data type for Iin: {Iin.dtype = }") + + # XXX: note that complex-valued computations are done in single precision + # this is historic, and the root reason is unclear, + # see https://github.com/scipy/scipy/issues/9209 + # Attempting to work in complex double precision leads to symiirorder1 + # failing to converge for the boundary conditions. + intype = Iin.dtype + hcol = array([1.0, 4.0, 1.0], np.float32) / 6.0 + if intype == np.complex128: + Iin = Iin.astype(np.complex64) + + ck = cspline2d(Iin, lmbda) + out = sepfir2d(ck, hcol, hcol) + out = out.astype(intype) + return out + + +_splinefunc_cache = {} + + +def gauss_spline(x, n): + r"""Gaussian approximation to B-spline basis function of order n. + + Parameters + ---------- + x : array_like + a knot vector + n : int + The order of the spline. Must be non-negative, i.e., n >= 0 + + Returns + ------- + res : ndarray + B-spline basis function values approximated by a zero-mean Gaussian + function. + + Notes + ----- + The B-spline basis function can be approximated well by a zero-mean + Gaussian function with standard-deviation equal to :math:`\sigma=(n+1)/12` + for large `n` : + + .. math:: \frac{1}{\sqrt {2\pi\sigma^2}}exp(-\frac{x^2}{2\sigma}) + + References + ---------- + .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen + F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In: + Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational + Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer + Science, vol 4485. Springer, Berlin, Heidelberg + .. [2] http://folk.uio.no/inf3330/scripting/doc/python/SciPy/tutorial/old/node24.html + + Examples + -------- + We can calculate B-Spline basis functions approximated by a gaussian + distribution: + + >>> import numpy as np + >>> from scipy.signal import gauss_spline + >>> knots = np.array([-1.0, 0.0, -1.0]) + >>> gauss_spline(knots, 3) + array([0.15418033, 0.6909883, 0.15418033]) # may vary + + """ + x = asarray(x) + signsq = (n + 1) / 12.0 + return 1 / sqrt(2 * pi * signsq) * exp(-x ** 2 / 2 / signsq) + + +def _cubic(x): + x = asarray(x, dtype=float) + b = BSpline.basis_element([-2, -1, 0, 1, 2], extrapolate=False) + out = b(x) + out[(x < -2) | (x > 2)] = 0 + return out + + +def _quadratic(x): + x = abs(asarray(x, dtype=float)) + b = BSpline.basis_element([-1.5, -0.5, 0.5, 1.5], extrapolate=False) + out = b(x) + out[(x < -1.5) | (x > 1.5)] = 0 + return out + + +def _coeff_smooth(lam): + xi = 1 - 96 * lam + 24 * lam * sqrt(3 + 144 * lam) + omeg = arctan2(sqrt(144 * lam - 1), sqrt(xi)) + rho = (24 * lam - 1 - sqrt(xi)) / (24 * lam) + rho = rho * sqrt((48 * lam + 24 * lam * sqrt(3 + 144 * lam)) / xi) + return rho, omeg + + +def _hc(k, cs, rho, omega): + return (cs / sin(omega) * (rho ** k) * sin(omega * (k + 1)) * + greater(k, -1)) + + +def _hs(k, cs, rho, omega): + c0 = (cs * cs * (1 + rho * rho) / (1 - rho * rho) / + (1 - 2 * rho * rho * cos(2 * omega) + rho ** 4)) + gamma = (1 - rho * rho) / (1 + rho * rho) / tan(omega) + ak = abs(k) + return c0 * rho ** ak * (cos(omega * ak) + gamma * sin(omega * ak)) + + +def _cubic_smooth_coeff(signal, lamb): + rho, omega = _coeff_smooth(lamb) + cs = 1 - 2 * rho * cos(omega) + rho * rho + K = len(signal) + k = arange(K) + + zi_2 = (_hc(0, cs, rho, omega) * signal[0] + + add.reduce(_hc(k + 1, cs, rho, omega) * signal)) + zi_1 = (_hc(0, cs, rho, omega) * signal[0] + + _hc(1, cs, rho, omega) * signal[1] + + add.reduce(_hc(k + 2, cs, rho, omega) * signal)) + + # Forward filter: + # for n in range(2, K): + # yp[n] = (cs * signal[n] + 2 * rho * cos(omega) * yp[n - 1] - + # rho * rho * yp[n - 2]) + zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2]) + zi = zi.reshape(1, -1) + + sos = r_[cs, 0, 0, 1, -2 * rho * cos(omega), rho * rho] + sos = sos.reshape(1, -1) + + yp, _ = sosfilt(sos, signal[2:], zi=zi) + yp = r_[zi_2, zi_1, yp] + + # Reverse filter: + # for n in range(K - 3, -1, -1): + # y[n] = (cs * yp[n] + 2 * rho * cos(omega) * y[n + 1] - + # rho * rho * y[n + 2]) + + zi_2 = add.reduce((_hs(k, cs, rho, omega) + + _hs(k + 1, cs, rho, omega)) * signal[::-1]) + zi_1 = add.reduce((_hs(k - 1, cs, rho, omega) + + _hs(k + 2, cs, rho, omega)) * signal[::-1]) + + zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2]) + zi = zi.reshape(1, -1) + y, _ = sosfilt(sos, yp[-3::-1], zi=zi) + y = r_[y[::-1], zi_1, zi_2] + return y + + +def _cubic_coeff(signal): + zi = -2 + sqrt(3) + K = len(signal) + powers = zi ** arange(K) + + if K == 1: + yplus = signal[0] + zi * add.reduce(powers * signal) + output = zi / (zi - 1) * yplus + return atleast_1d(output) + + # Forward filter: + # yplus[0] = signal[0] + zi * add.reduce(powers * signal) + # for k in range(1, K): + # yplus[k] = signal[k] + zi * yplus[k - 1] + + state = lfiltic(1, r_[1, -zi], atleast_1d(add.reduce(powers * signal))) + + b = ones(1) + a = r_[1, -zi] + yplus, _ = lfilter(b, a, signal, zi=state) + + # Reverse filter: + # output[K - 1] = zi / (zi - 1) * yplus[K - 1] + # for k in range(K - 2, -1, -1): + # output[k] = zi * (output[k + 1] - yplus[k]) + out_last = zi / (zi - 1) * yplus[K - 1] + state = lfiltic(-zi, r_[1, -zi], atleast_1d(out_last)) + + b = asarray([-zi]) + output, _ = lfilter(b, a, yplus[-2::-1], zi=state) + output = r_[output[::-1], out_last] + return output * 6.0 + + +def _quadratic_coeff(signal): + zi = -3 + 2 * sqrt(2.0) + K = len(signal) + powers = zi ** arange(K) + + if K == 1: + yplus = signal[0] + zi * add.reduce(powers * signal) + output = zi / (zi - 1) * yplus + return atleast_1d(output) + + # Forward filter: + # yplus[0] = signal[0] + zi * add.reduce(powers * signal) + # for k in range(1, K): + # yplus[k] = signal[k] + zi * yplus[k - 1] + + state = lfiltic(1, r_[1, -zi], atleast_1d(add.reduce(powers * signal))) + + b = ones(1) + a = r_[1, -zi] + yplus, _ = lfilter(b, a, signal, zi=state) + + # Reverse filter: + # output[K - 1] = zi / (zi - 1) * yplus[K - 1] + # for k in range(K - 2, -1, -1): + # output[k] = zi * (output[k + 1] - yplus[k]) + out_last = zi / (zi - 1) * yplus[K - 1] + state = lfiltic(-zi, r_[1, -zi], atleast_1d(out_last)) + + b = asarray([-zi]) + output, _ = lfilter(b, a, yplus[-2::-1], zi=state) + output = r_[output[::-1], out_last] + return output * 8.0 + + +def compute_root_from_lambda(lamb): + tmp = sqrt(3 + 144 * lamb) + xi = 1 - 96 * lamb + 24 * lamb * tmp + omega = arctan(sqrt((144 * lamb - 1.0) / xi)) + tmp2 = sqrt(xi) + r = ((24 * lamb - 1 - tmp2) / (24 * lamb) * + sqrt(48*lamb + 24 * lamb * tmp) / tmp2) + return r, omega + + +def cspline1d(signal, lamb=0.0): + """ + Compute cubic spline coefficients for rank-1 array. + + Find the cubic spline coefficients for a 1-D signal assuming + mirror-symmetric boundary conditions. To obtain the signal back from the + spline representation mirror-symmetric-convolve these coefficients with a + length 3 FIR window [1.0, 4.0, 1.0]/ 6.0 . + + Parameters + ---------- + signal : ndarray + A rank-1 array representing samples of a signal. + lamb : float, optional + Smoothing coefficient, default is 0.0. + + Returns + ------- + c : ndarray + Cubic spline coefficients. + + See Also + -------- + cspline1d_eval : Evaluate a cubic spline at the new set of points. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a cubic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cspline1d, cspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = cspline1d_eval(cspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + if lamb != 0.0: + return _cubic_smooth_coeff(signal, lamb) + else: + return _cubic_coeff(signal) + + +def qspline1d(signal, lamb=0.0): + """Compute quadratic spline coefficients for rank-1 array. + + Parameters + ---------- + signal : ndarray + A rank-1 array representing samples of a signal. + lamb : float, optional + Smoothing coefficient (must be zero for now). + + Returns + ------- + c : ndarray + Quadratic spline coefficients. + + See Also + -------- + qspline1d_eval : Evaluate a quadratic spline at the new set of points. + + Notes + ----- + Find the quadratic spline coefficients for a 1-D signal assuming + mirror-symmetric boundary conditions. To obtain the signal back from the + spline representation mirror-symmetric-convolve these coefficients with a + length 3 FIR window [1.0, 6.0, 1.0]/ 8.0 . + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a quadratic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import qspline1d, qspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = qspline1d_eval(qspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + if lamb != 0.0: + raise ValueError("Smoothing quadratic splines not supported yet.") + else: + return _quadratic_coeff(signal) + + +def collapse_2d(x, axis): + x = moveaxis(x, axis, -1) + x_shape = x.shape + x = x.reshape(-1, x.shape[-1]) + if not x.flags.c_contiguous: + x = x.copy() + return x, x_shape + + +def symiirorder_nd(func, input, *args, axis=-1, **kwargs): + axis = normalize_axis_index(axis, input.ndim) + input_shape = input.shape + input_ndim = input.ndim + if input.ndim > 1: + input, input_shape = collapse_2d(input, axis) + + out = func(input, *args, **kwargs) + + if input_ndim > 1: + out = out.reshape(input_shape) + out = moveaxis(out, -1, axis) + if not out.flags.c_contiguous: + out = out.copy() + return out + + +def qspline2d(signal, lamb=0.0, precision=-1.0): + """ + Coefficients for 2-D quadratic (2nd order) B-spline. + + Return the second-order B-spline coefficients over a regularly spaced + input grid for the two-dimensional input image. + + Parameters + ---------- + input : ndarray + The input signal. + lamb : float + Specifies the amount of smoothing in the transfer function. + precision : float + Specifies the precision for computing the infinite sum needed to apply + mirror-symmetric boundary conditions. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if precision < 0.0 or precision >= 1.0: + if signal.dtype in [float32, complex64]: + precision = 1e-3 + else: + precision = 1e-6 + + if lamb > 0: + raise ValueError('lambda must be negative or zero') + + # normal quadratic spline + r = -3 + 2 * sqrt(2.0) + c0 = -r * 8.0 + z1 = r + + out = symiirorder_nd(symiirorder1, signal, c0, z1, precision, axis=-1) + out = symiirorder_nd(symiirorder1, out, c0, z1, precision, axis=0) + return out + + +def cspline2d(signal, lamb=0.0, precision=-1.0): + """ + Coefficients for 2-D cubic (3rd order) B-spline. + + Return the third-order B-spline coefficients over a regularly spaced + input grid for the two-dimensional input image. + + Parameters + ---------- + input : ndarray + The input signal. + lamb : float + Specifies the amount of smoothing in the transfer function. + precision : float + Specifies the precision for computing the infinite sum needed to apply + mirror-symmetric boundary conditions. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if precision < 0.0 or precision >= 1.0: + if signal.dtype in [float32, complex64]: + precision = 1e-3 + else: + precision = 1e-6 + + if lamb <= 1 / 144.0: + # Normal cubic spline + r = -2 + sqrt(3.0) + out = symiirorder_nd( + symiirorder1, signal, -r * 6.0, r, precision=precision, axis=-1) + out = symiirorder_nd( + symiirorder1, out, -r * 6.0, r, precision=precision, axis=0) + return out + + r, omega = compute_root_from_lambda(lamb) + out = symiirorder_nd(symiirorder2, signal, r, omega, + precision=precision, axis=-1) + out = symiirorder_nd(symiirorder2, out, r, omega, + precision=precision, axis=0) + return out + + +def cspline1d_eval(cj, newx, dx=1.0, x0=0): + """Evaluate a cubic spline at the new set of points. + + `dx` is the old sample-spacing while `x0` was the old origin. In + other-words the old-sample points (knot-points) for which the `cj` + represent spline coefficients were at equally-spaced points of: + + oldx = x0 + j*dx j=0...N-1, with N=len(cj) + + Edges are handled using mirror-symmetric boundary conditions. + + Parameters + ---------- + cj : ndarray + cublic spline coefficients + newx : ndarray + New set of points. + dx : float, optional + Old sample-spacing, the default value is 1.0. + x0 : int, optional + Old origin, the default value is 0. + + Returns + ------- + res : ndarray + Evaluated a cubic spline points. + + See Also + -------- + cspline1d : Compute cubic spline coefficients for rank-1 array. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a cubic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cspline1d, cspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = cspline1d_eval(cspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + newx = (asarray(newx) - x0) / float(dx) + res = zeros_like(newx, dtype=cj.dtype) + if res.size == 0: + return res + N = len(cj) + cond1 = newx < 0 + cond2 = newx > (N - 1) + cond3 = ~(cond1 | cond2) + # handle general mirror-symmetry + res[cond1] = cspline1d_eval(cj, -newx[cond1]) + res[cond2] = cspline1d_eval(cj, 2 * (N - 1) - newx[cond2]) + newx = newx[cond3] + if newx.size == 0: + return res + result = zeros_like(newx, dtype=cj.dtype) + jlower = floor(newx - 2).astype(int) + 1 + for i in range(4): + thisj = jlower + i + indj = thisj.clip(0, N - 1) # handle edge cases + result += cj[indj] * _cubic(newx - thisj) + res[cond3] = result + return res + + +def qspline1d_eval(cj, newx, dx=1.0, x0=0): + """Evaluate a quadratic spline at the new set of points. + + Parameters + ---------- + cj : ndarray + Quadratic spline coefficients + newx : ndarray + New set of points. + dx : float, optional + Old sample-spacing, the default value is 1.0. + x0 : int, optional + Old origin, the default value is 0. + + Returns + ------- + res : ndarray + Evaluated a quadratic spline points. + + See Also + -------- + qspline1d : Compute quadratic spline coefficients for rank-1 array. + + Notes + ----- + `dx` is the old sample-spacing while `x0` was the old origin. In + other-words the old-sample points (knot-points) for which the `cj` + represent spline coefficients were at equally-spaced points of:: + + oldx = x0 + j*dx j=0...N-1, with N=len(cj) + + Edges are handled using mirror-symmetric boundary conditions. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a quadratic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import qspline1d, qspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = qspline1d_eval(qspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + newx = (asarray(newx) - x0) / dx + res = zeros_like(newx) + if res.size == 0: + return res + N = len(cj) + cond1 = newx < 0 + cond2 = newx > (N - 1) + cond3 = ~(cond1 | cond2) + # handle general mirror-symmetry + res[cond1] = qspline1d_eval(cj, -newx[cond1]) + res[cond2] = qspline1d_eval(cj, 2 * (N - 1) - newx[cond2]) + newx = newx[cond3] + if newx.size == 0: + return res + result = zeros_like(newx) + jlower = floor(newx - 1.5).astype(int) + 1 + for i in range(3): + thisj = jlower + i + indj = thisj.clip(0, N - 1) # handle edge cases + result += cj[indj] * _quadratic(newx - thisj) + res[cond3] = result + return res + + +def symiirorder1(signal, c0, z1, precision=-1.0): + """ + Implement a smoothing IIR filter with mirror-symmetric boundary conditions + using a cascade of first-order sections. + + The second section uses a reversed sequence. This implements a system with + the following transfer function and mirror-symmetric boundary conditions:: + + c0 + H(z) = --------------------- + (1-z1/z) (1 - z1 z) + + The resulting signal will have mirror symmetric boundary conditions + as well. + + Parameters + ---------- + signal : ndarray + The input signal. If 2D, then the filter will be applied in a batched + fashion across the last axis. + c0, z1 : scalar + Parameters in the transfer function. + precision : + Specifies the precision for calculating initial conditions + of the recursive filter based on mirror-symmetric input. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if np.abs(z1) >= 1: + raise ValueError('|z1| must be less than 1.0') + + if signal.ndim > 2: + raise ValueError('Input must be 1D or 2D') + + squeeze_dim = False + if signal.ndim == 1: + signal = signal[None, :] + squeeze_dim = True + + if np.issubdtype(signal.dtype, np.integer): + signal = signal.astype(np.promote_types(signal.dtype, np.float32)) + + y0 = symiirorder1_ic(signal, z1, precision) + + # Apply first the system 1 / (1 - z1 * z^-1) + b = np.ones(1, dtype=signal.dtype) + a = np.r_[1, -z1] + a = a.astype(signal.dtype) + + # Compute the initial state for lfilter. + zii = y0 * z1 + + y1, _ = lfilter(b, a, axis_slice(signal, 1), zi=zii) + y1 = np.c_[y0, y1] + + # Compute backward symmetric condition and apply the system + # c0 / (1 - z1 * z) + b = np.asarray([c0], dtype=signal.dtype) + out_last = -c0 / (z1 - 1.0) * axis_slice(y1, -1) + + # Compute the initial state for lfilter. + zii = out_last * z1 + + # Apply the system c0 / (1 - z1 * z) by reversing the output of the previous stage + out, _ = lfilter(b, a, axis_slice(y1, -2, step=-1), zi=zii) + out = np.c_[axis_reverse(out), out_last] + + if squeeze_dim: + out = out[0] + + return out + + +def symiirorder2(input, r, omega, precision=-1.0): + """ + Implement a smoothing IIR filter with mirror-symmetric boundary conditions + using a cascade of second-order sections. + + The second section uses a reversed sequence. This implements the following + transfer function:: + + cs^2 + H(z) = --------------------------------------- + (1 - a2/z - a3/z^2) (1 - a2 z - a3 z^2 ) + + where:: + + a2 = 2 * r * cos(omega) + a3 = - r ** 2 + cs = 1 - 2 * r * cos(omega) + r ** 2 + + Parameters + ---------- + input : ndarray + The input signal. + r, omega : float + Parameters in the transfer function. + precision : float + Specifies the precision for calculating initial conditions + of the recursive filter based on mirror-symmetric input. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if r >= 1.0: + raise ValueError('r must be less than 1.0') + + if input.ndim > 2: + raise ValueError('Input must be 1D or 2D') + + if not input.flags.c_contiguous: + input = input.copy() + + squeeze_dim = False + if input.ndim == 1: + input = input[None, :] + squeeze_dim = True + + if np.issubdtype(input.dtype, np.integer): + input = input.astype(np.promote_types(input.dtype, np.float32)) + + rsq = r * r + a2 = 2 * r * np.cos(omega) + a3 = -rsq + cs = np.atleast_1d(1 - 2 * r * np.cos(omega) + rsq) + sos = np.atleast_2d(np.r_[cs, 0, 0, 1, -a2, -a3]).astype(input.dtype) + + # Find the starting (forward) conditions. + ic_fwd = symiirorder2_ic_fwd(input, r, omega, precision) + + # Apply first the system cs / (1 - a2 * z^-1 - a3 * z^-2) + # Compute the initial conditions in the form expected by sosfilt + # coef = np.asarray([[a3, a2], [0, a3]], dtype=input.dtype) + coef = np.r_[a3, a2, 0, a3].reshape(2, 2).astype(input.dtype) + zi = np.matmul(coef, ic_fwd[:, :, None])[:, :, 0] + + y_fwd, _ = sosfilt(sos, axis_slice(input, 2), zi=zi[None]) + y_fwd = np.c_[ic_fwd, y_fwd] + + # Then compute the symmetric backward starting conditions + ic_bwd = symiirorder2_ic_bwd(input, r, omega, precision) + + # Apply the system cs / (1 - a2 * z^1 - a3 * z^2) + # Compute the initial conditions in the form expected by sosfilt + zi = np.matmul(coef, ic_bwd[:, :, None])[:, :, 0] + y, _ = sosfilt(sos, axis_slice(y_fwd, -3, step=-1), zi=zi[None]) + out = np.c_[axis_reverse(y), axis_reverse(ic_bwd)] + + if squeeze_dim: + out = out[0] + + return out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_upfirdn.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_upfirdn.py new file mode 100644 index 0000000000000000000000000000000000000000..d64cc142ff194b1404e380507289ddbaffab3359 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_upfirdn.py @@ -0,0 +1,216 @@ +# Code adapted from "upfirdn" python library with permission: +# +# Copyright (c) 2009, Motorola, Inc +# +# All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the name of Motorola nor the names of its contributors may be +# used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np + +from ._upfirdn_apply import _output_len, _apply, mode_enum + +__all__ = ['upfirdn', '_output_len'] + +_upfirdn_modes = [ + 'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect', + 'antisymmetric', 'antireflect', 'line', +] + + +def _pad_h(h, up): + """Store coefficients in a transposed, flipped arrangement. + + For example, suppose upRate is 3, and the + input number of coefficients is 10, represented as h[0], ..., h[9]. + + Then the internal buffer will look like this:: + + h[9], h[6], h[3], h[0], // flipped phase 0 coefs + 0, h[7], h[4], h[1], // flipped phase 1 coefs (zero-padded) + 0, h[8], h[5], h[2], // flipped phase 2 coefs (zero-padded) + + """ + h_padlen = len(h) + (-len(h) % up) + h_full = np.zeros(h_padlen, h.dtype) + h_full[:len(h)] = h + h_full = h_full.reshape(-1, up).T[:, ::-1].ravel() + return h_full + + +def _check_mode(mode): + mode = mode.lower() + enum = mode_enum(mode) + return enum + + +class _UpFIRDn: + """Helper for resampling.""" + + def __init__(self, h, x_dtype, up, down): + h = np.asarray(h) + if h.ndim != 1 or h.size == 0: + raise ValueError('h must be 1-D with non-zero length') + self._output_type = np.result_type(h.dtype, x_dtype, np.float32) + h = np.asarray(h, self._output_type) + self._up = int(up) + self._down = int(down) + if self._up < 1 or self._down < 1: + raise ValueError('Both up and down must be >= 1') + # This both transposes, and "flips" each phase for filtering + self._h_trans_flip = _pad_h(h, self._up) + self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip) + self._h_len_orig = len(h) + + def apply_filter(self, x, axis=-1, mode='constant', cval=0): + """Apply the prepared filter to the specified axis of N-D signal x.""" + output_len = _output_len(self._h_len_orig, x.shape[axis], + self._up, self._down) + # Explicit use of np.int64 for output_shape dtype avoids OverflowError + # when allocating large array on platforms where intp is 32 bits. + output_shape = np.asarray(x.shape, dtype=np.int64) + output_shape[axis] = output_len + out = np.zeros(output_shape, dtype=self._output_type, order='C') + axis = axis % x.ndim + mode = _check_mode(mode) + _apply(np.asarray(x, self._output_type), + self._h_trans_flip, out, + self._up, self._down, axis, mode, cval) + return out + + +def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0): + """Upsample, FIR filter, and downsample. + + Parameters + ---------- + h : array_like + 1-D FIR (finite-impulse response) filter coefficients. + x : array_like + Input signal array. + up : int, optional + Upsampling rate. Default is 1. + down : int, optional + Downsampling rate. Default is 1. + axis : int, optional + The axis of the input data array along which to apply the + linear filter. The filter is applied to each subarray along + this axis. Default is -1. + mode : str, optional + The signal extension mode to use. The set + ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to + modes provided by `numpy.pad`. ``"smooth"`` implements a smooth + extension by extending based on the slope of the last 2 points at each + end of the array. ``"antireflect"`` and ``"antisymmetric"`` are + anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode + `"line"` extends the signal based on a linear trend defined by the + first and last points along the ``axis``. + + .. versionadded:: 1.4.0 + cval : float, optional + The constant value to use when ``mode == "constant"``. + + .. versionadded:: 1.4.0 + + Returns + ------- + y : ndarray + The output signal array. Dimensions will be the same as `x` except + for along `axis`, which will change size according to the `h`, + `up`, and `down` parameters. + + Notes + ----- + The algorithm is an implementation of the block diagram shown on page 129 + of the Vaidyanathan text [1]_ (Figure 4.3-8d). + + The direct approach of upsampling by factor of P with zero insertion, + FIR filtering of length ``N``, and downsampling by factor of Q is + O(N*Q) per output sample. The polyphase implementation used here is + O(N/P). + + .. versionadded:: 0.18 + + References + ---------- + .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks, + Prentice Hall, 1993. + + Examples + -------- + Simple operations: + + >>> import numpy as np + >>> from scipy.signal import upfirdn + >>> upfirdn([1, 1, 1], [1, 1, 1]) # FIR filter + array([ 1., 2., 3., 2., 1.]) + >>> upfirdn([1], [1, 2, 3], 3) # upsampling with zeros insertion + array([ 1., 0., 0., 2., 0., 0., 3.]) + >>> upfirdn([1, 1, 1], [1, 2, 3], 3) # upsampling with sample-and-hold + array([ 1., 1., 1., 2., 2., 2., 3., 3., 3.]) + >>> upfirdn([.5, 1, .5], [1, 1, 1], 2) # linear interpolation + array([ 0.5, 1. , 1. , 1. , 1. , 1. , 0.5]) + >>> upfirdn([1], np.arange(10), 1, 3) # decimation by 3 + array([ 0., 3., 6., 9.]) + >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3) # linear interp, rate 2/3 + array([ 0. , 1. , 2.5, 4. , 5.5, 7. , 8.5]) + + Apply a single filter to multiple signals: + + >>> x = np.reshape(np.arange(8), (4, 2)) + >>> x + array([[0, 1], + [2, 3], + [4, 5], + [6, 7]]) + + Apply along the last dimension of ``x``: + + >>> h = [1, 1] + >>> upfirdn(h, x, 2) + array([[ 0., 0., 1., 1.], + [ 2., 2., 3., 3.], + [ 4., 4., 5., 5.], + [ 6., 6., 7., 7.]]) + + Apply along the 0th dimension of ``x``: + + >>> upfirdn(h, x, 2, axis=0) + array([[ 0., 1.], + [ 0., 1.], + [ 2., 3.], + [ 2., 3.], + [ 4., 5.], + [ 4., 5.], + [ 6., 7.], + [ 6., 7.]]) + """ + x = np.asarray(x) + ufd = _UpFIRDn(h, x.dtype, up, down) + # This is equivalent to (but faster than) using np.apply_along_axis + return ufd.apply_filter(x, axis, mode, cval) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_waveforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_waveforms.py new file mode 100644 index 0000000000000000000000000000000000000000..a6be46cfd38674ee8c3ae89c9762461440c1e620 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_waveforms.py @@ -0,0 +1,696 @@ +# Author: Travis Oliphant +# 2003 +# +# Feb. 2010: Updated by Warren Weckesser: +# Rewrote much of chirp() +# Added sweep_poly() +import numpy as np +from numpy import asarray, zeros, place, nan, mod, pi, extract, log, sqrt, \ + exp, cos, sin, polyval, polyint + + +__all__ = ['sawtooth', 'square', 'gausspulse', 'chirp', 'sweep_poly', + 'unit_impulse'] + + +def sawtooth(t, width=1): + """ + Return a periodic sawtooth or triangle waveform. + + The sawtooth waveform has a period ``2*pi``, rises from -1 to 1 on the + interval 0 to ``width*2*pi``, then drops from 1 to -1 on the interval + ``width*2*pi`` to ``2*pi``. `width` must be in the interval [0, 1]. + + Note that this is not band-limited. It produces an infinite number + of harmonics, which are aliased back and forth across the frequency + spectrum. + + Parameters + ---------- + t : array_like + Time. + width : array_like, optional + Width of the rising ramp as a proportion of the total cycle. + Default is 1, producing a rising ramp, while 0 produces a falling + ramp. `width` = 0.5 produces a triangle wave. + If an array, causes wave shape to change over time, and must be the + same length as t. + + Returns + ------- + y : ndarray + Output array containing the sawtooth waveform. + + Examples + -------- + A 5 Hz waveform sampled at 500 Hz for 1 second: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> t = np.linspace(0, 1, 500) + >>> plt.plot(t, signal.sawtooth(2 * np.pi * 5 * t)) + + """ + t, w = asarray(t), asarray(width) + w = asarray(w + (t - t)) + t = asarray(t + (w - w)) + if t.dtype.char in ['fFdD']: + ytype = t.dtype.char + else: + ytype = 'd' + y = zeros(t.shape, ytype) + + # width must be between 0 and 1 inclusive + mask1 = (w > 1) | (w < 0) + place(y, mask1, nan) + + # take t modulo 2*pi + tmod = mod(t, 2 * pi) + + # on the interval 0 to width*2*pi function is + # tmod / (pi*w) - 1 + mask2 = (1 - mask1) & (tmod < w * 2 * pi) + tsub = extract(mask2, tmod) + wsub = extract(mask2, w) + place(y, mask2, tsub / (pi * wsub) - 1) + + # on the interval width*2*pi to 2*pi function is + # (pi*(w+1)-tmod) / (pi*(1-w)) + + mask3 = (1 - mask1) & (1 - mask2) + tsub = extract(mask3, tmod) + wsub = extract(mask3, w) + place(y, mask3, (pi * (wsub + 1) - tsub) / (pi * (1 - wsub))) + return y + + +def square(t, duty=0.5): + """ + Return a periodic square-wave waveform. + + The square wave has a period ``2*pi``, has value +1 from 0 to + ``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in + the interval [0,1]. + + Note that this is not band-limited. It produces an infinite number + of harmonics, which are aliased back and forth across the frequency + spectrum. + + Parameters + ---------- + t : array_like + The input time array. + duty : array_like, optional + Duty cycle. Default is 0.5 (50% duty cycle). + If an array, causes wave shape to change over time, and must be the + same length as t. + + Returns + ------- + y : ndarray + Output array containing the square waveform. + + Examples + -------- + A 5 Hz waveform sampled at 500 Hz for 1 second: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> t = np.linspace(0, 1, 500, endpoint=False) + >>> plt.plot(t, signal.square(2 * np.pi * 5 * t)) + >>> plt.ylim(-2, 2) + + A pulse-width modulated sine wave: + + >>> plt.figure() + >>> sig = np.sin(2 * np.pi * t) + >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2) + >>> plt.subplot(2, 1, 1) + >>> plt.plot(t, sig) + >>> plt.subplot(2, 1, 2) + >>> plt.plot(t, pwm) + >>> plt.ylim(-1.5, 1.5) + + """ + t, w = asarray(t), asarray(duty) + w = asarray(w + (t - t)) + t = asarray(t + (w - w)) + if t.dtype.char in ['fFdD']: + ytype = t.dtype.char + else: + ytype = 'd' + + y = zeros(t.shape, ytype) + + # width must be between 0 and 1 inclusive + mask1 = (w > 1) | (w < 0) + place(y, mask1, nan) + + # on the interval 0 to duty*2*pi function is 1 + tmod = mod(t, 2 * pi) + mask2 = (1 - mask1) & (tmod < w * 2 * pi) + place(y, mask2, 1) + + # on the interval duty*2*pi to 2*pi function is + # (pi*(w+1)-tmod) / (pi*(1-w)) + mask3 = (1 - mask1) & (1 - mask2) + place(y, mask3, -1) + return y + + +def gausspulse(t, fc=1000, bw=0.5, bwr=-6, tpr=-60, retquad=False, + retenv=False): + """ + Return a Gaussian modulated sinusoid: + + ``exp(-a t^2) exp(1j*2*pi*fc*t).`` + + If `retquad` is True, then return the real and imaginary parts + (in-phase and quadrature). + If `retenv` is True, then return the envelope (unmodulated signal). + Otherwise, return the real part of the modulated sinusoid. + + Parameters + ---------- + t : ndarray or the string 'cutoff' + Input array. + fc : float, optional + Center frequency (e.g. Hz). Default is 1000. + bw : float, optional + Fractional bandwidth in frequency domain of pulse (e.g. Hz). + Default is 0.5. + bwr : float, optional + Reference level at which fractional bandwidth is calculated (dB). + Default is -6. + tpr : float, optional + If `t` is 'cutoff', then the function returns the cutoff + time for when the pulse amplitude falls below `tpr` (in dB). + Default is -60. + retquad : bool, optional + If True, return the quadrature (imaginary) as well as the real part + of the signal. Default is False. + retenv : bool, optional + If True, return the envelope of the signal. Default is False. + + Returns + ------- + yI : ndarray + Real part of signal. Always returned. + yQ : ndarray + Imaginary part of signal. Only returned if `retquad` is True. + yenv : ndarray + Envelope of signal. Only returned if `retenv` is True. + + Examples + -------- + Plot real component, imaginary component, and envelope for a 5 Hz pulse, + sampled at 100 Hz for 2 seconds: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> t = np.linspace(-1, 1, 2 * 100, endpoint=False) + >>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True) + >>> plt.plot(t, i, t, q, t, e, '--') + + """ + if fc < 0: + raise ValueError(f"Center frequency (fc={fc:.2f}) must be >=0.") + if bw <= 0: + raise ValueError(f"Fractional bandwidth (bw={bw:.2f}) must be > 0.") + if bwr >= 0: + raise ValueError(f"Reference level for bandwidth (bwr={bwr:.2f}) " + "must be < 0 dB") + + # exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f) + + ref = pow(10.0, bwr / 20.0) + # fdel = fc*bw/2: g(fdel) = ref --- solve this for a + # + # pi^2/a * fc^2 * bw^2 /4=-log(ref) + a = -(pi * fc * bw) ** 2 / (4.0 * log(ref)) + + if isinstance(t, str): + if t == 'cutoff': # compute cut_off point + # Solve exp(-a tc**2) = tref for tc + # tc = sqrt(-log(tref) / a) where tref = 10^(tpr/20) + if tpr >= 0: + raise ValueError("Reference level for time cutoff must " + "be < 0 dB") + tref = pow(10.0, tpr / 20.0) + return sqrt(-log(tref) / a) + else: + raise ValueError("If `t` is a string, it must be 'cutoff'") + + yenv = exp(-a * t * t) + yI = yenv * cos(2 * pi * fc * t) + yQ = yenv * sin(2 * pi * fc * t) + if not retquad and not retenv: + return yI + if not retquad and retenv: + return yI, yenv + if retquad and not retenv: + return yI, yQ + if retquad and retenv: + return yI, yQ, yenv + + +def chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True, *, + complex=False): + r"""Frequency-swept cosine generator. + + In the following, 'Hz' should be interpreted as 'cycles per unit'; + there is no requirement here that the unit is one second. The + important distinction is that the units of rotation are cycles, not + radians. Likewise, `t` could be a measurement of space instead of time. + + Parameters + ---------- + t : array_like + Times at which to evaluate the waveform. + f0 : float + Frequency (e.g. Hz) at time t=0. + t1 : float + Time at which `f1` is specified. + f1 : float + Frequency (e.g. Hz) of the waveform at time `t1`. + method : {'linear', 'quadratic', 'logarithmic', 'hyperbolic'}, optional + Kind of frequency sweep. If not given, `linear` is assumed. See + Notes below for more details. + phi : float, optional + Phase offset, in degrees. Default is 0. + vertex_zero : bool, optional + This parameter is only used when `method` is 'quadratic'. + It determines whether the vertex of the parabola that is the graph + of the frequency is at t=0 or t=t1. + complex : bool, optional + This parameter creates a complex-valued analytic signal instead of a + real-valued signal. It allows the use of complex baseband (in communications + domain). Default is False. + + .. versionadded:: 1.15.0 + + Returns + ------- + y : ndarray + A numpy array containing the signal evaluated at `t` with the requested + time-varying frequency. More precisely, the function returns + ``exp(1j*phase + 1j*(pi/180)*phi) if complex else cos(phase + (pi/180)*phi)`` + where `phase` is the integral (from 0 to `t`) of ``2*pi*f(t)``. + The instantaneous frequency ``f(t)`` is defined below. + + See Also + -------- + sweep_poly + + Notes + ----- + There are four possible options for the parameter `method`, which have a (long) + standard form and some allowed abbreviations. The formulas for the instantaneous + frequency :math:`f(t)` of the generated signal are as follows: + + 1. Parameter `method` in ``('linear', 'lin', 'li')``: + + .. math:: + f(t) = f_0 + \beta\, t \quad\text{with}\quad + \beta = \frac{f_1 - f_0}{t_1} + + Frequency :math:`f(t)` varies linearly over time with a constant rate + :math:`\beta`. + + 2. Parameter `method` in ``('quadratic', 'quad', 'q')``: + + .. math:: + f(t) = + \begin{cases} + f_0 + \beta\, t^2 & \text{if vertex_zero is True,}\\ + f_1 + \beta\, (t_1 - t)^2 & \text{otherwise,} + \end{cases} + \quad\text{with}\quad + \beta = \frac{f_1 - f_0}{t_1^2} + + The graph of the frequency f(t) is a parabola through :math:`(0, f_0)` and + :math:`(t_1, f_1)`. By default, the vertex of the parabola is at + :math:`(0, f_0)`. If `vertex_zero` is ``False``, then the vertex is at + :math:`(t_1, f_1)`. + To use a more general quadratic function, or an arbitrary + polynomial, use the function `scipy.signal.sweep_poly`. + + 3. Parameter `method` in ``('logarithmic', 'log', 'lo')``: + + .. math:: + f(t) = f_0 \left(\frac{f_1}{f_0}\right)^{t/t_1} + + :math:`f_0` and :math:`f_1` must be nonzero and have the same sign. + This signal is also known as a geometric or exponential chirp. + + 4. Parameter `method` in ``('hyperbolic', 'hyp')``: + + .. math:: + f(t) = \frac{\alpha}{\beta\, t + \gamma} \quad\text{with}\quad + \alpha = f_0 f_1 t_1, \ \beta = f_0 - f_1, \ \gamma = f_1 t_1 + + :math:`f_0` and :math:`f_1` must be nonzero. + + + Examples + -------- + For the first example, a linear chirp ranging from 6 Hz to 1 Hz over 10 seconds is + plotted: + + >>> import numpy as np + >>> from matplotlib.pyplot import tight_layout + >>> from scipy.signal import chirp, square, ShortTimeFFT + >>> from scipy.signal.windows import gaussian + >>> import matplotlib.pyplot as plt + ... + >>> N, T = 1000, 0.01 # number of samples and sampling interval for 10 s signal + >>> t = np.arange(N) * T # timestamps + ... + >>> x_lin = chirp(t, f0=6, f1=1, t1=10, method='linear') + ... + >>> fg0, ax0 = plt.subplots() + >>> ax0.set_title(r"Linear Chirp from $f(0)=6\,$Hz to $f(10)=1\,$Hz") + >>> ax0.set(xlabel="Time $t$ in Seconds", ylabel=r"Amplitude $x_\text{lin}(t)$") + >>> ax0.plot(t, x_lin) + >>> plt.show() + + The following four plots each show the short-time Fourier transform of a chirp + ranging from 45 Hz to 5 Hz with different values for the parameter `method` + (and `vertex_zero`): + + >>> x_qu0 = chirp(t, f0=45, f1=5, t1=N*T, method='quadratic', vertex_zero=True) + >>> x_qu1 = chirp(t, f0=45, f1=5, t1=N*T, method='quadratic', vertex_zero=False) + >>> x_log = chirp(t, f0=45, f1=5, t1=N*T, method='logarithmic') + >>> x_hyp = chirp(t, f0=45, f1=5, t1=N*T, method='hyperbolic') + ... + >>> win = gaussian(50, std=12, sym=True) + >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T, mfft=800, scale_to='magnitude') + >>> ts = ("'quadratic', vertex_zero=True", "'quadratic', vertex_zero=False", + ... "'logarithmic'", "'hyperbolic'") + >>> fg1, ax1s = plt.subplots(2, 2, sharex='all', sharey='all', + ... figsize=(6, 5), layout="constrained") + >>> for x_, ax_, t_ in zip([x_qu0, x_qu1, x_log, x_hyp], ax1s.ravel(), ts): + ... aSx = abs(SFT.stft(x_)) + ... im_ = ax_.imshow(aSx, origin='lower', aspect='auto', extent=SFT.extent(N), + ... cmap='plasma') + ... ax_.set_title(t_) + ... if t_ == "'hyperbolic'": + ... fg1.colorbar(im_, ax=ax1s, label='Magnitude $|S_z(t,f)|$') + >>> _ = fg1.supxlabel("Time $t$ in Seconds") # `_ =` is needed to pass doctests + >>> _ = fg1.supylabel("Frequency $f$ in Hertz") + >>> plt.show() + + Finally, the short-time Fourier transform of a complex-valued linear chirp + ranging from -30 Hz to 30 Hz is depicted: + + >>> z_lin = chirp(t, f0=-30, f1=30, t1=N*T, method="linear", complex=True) + >>> SFT.fft_mode = 'centered' # needed to work with complex signals + >>> aSz = abs(SFT.stft(z_lin)) + ... + >>> fg2, ax2 = plt.subplots() + >>> ax2.set_title(r"Linear Chirp from $-30\,$Hz to $30\,$Hz") + >>> ax2.set(xlabel="Time $t$ in Seconds", ylabel="Frequency $f$ in Hertz") + >>> im2 = ax2.imshow(aSz, origin='lower', aspect='auto', + ... extent=SFT.extent(N), cmap='viridis') + >>> fg2.colorbar(im2, label='Magnitude $|S_z(t,f)|$') + >>> plt.show() + + Note that using negative frequencies makes only sense with complex-valued signals. + Furthermore, the magnitude of the complex exponential function is one whereas the + magnitude of the real-valued cosine function is only 1/2. + """ + # 'phase' is computed in _chirp_phase, to make testing easier. + phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero) + np.deg2rad(phi) + return np.exp(1j*phase) if complex else np.cos(phase) + + +def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True): + """ + Calculate the phase used by `chirp` to generate its output. + + See `chirp` for a description of the arguments. + + """ + t = asarray(t) + f0 = float(f0) + t1 = float(t1) + f1 = float(f1) + if method in ['linear', 'lin', 'li']: + beta = (f1 - f0) / t1 + phase = 2 * pi * (f0 * t + 0.5 * beta * t * t) + + elif method in ['quadratic', 'quad', 'q']: + beta = (f1 - f0) / (t1 ** 2) + if vertex_zero: + phase = 2 * pi * (f0 * t + beta * t ** 3 / 3) + else: + phase = 2 * pi * (f1 * t + beta * ((t1 - t) ** 3 - t1 ** 3) / 3) + + elif method in ['logarithmic', 'log', 'lo']: + if f0 * f1 <= 0.0: + raise ValueError("For a logarithmic chirp, f0 and f1 must be " + "nonzero and have the same sign.") + if f0 == f1: + phase = 2 * pi * f0 * t + else: + beta = t1 / log(f1 / f0) + phase = 2 * pi * beta * f0 * (pow(f1 / f0, t / t1) - 1.0) + + elif method in ['hyperbolic', 'hyp']: + if f0 == 0 or f1 == 0: + raise ValueError("For a hyperbolic chirp, f0 and f1 must be " + "nonzero.") + if f0 == f1: + # Degenerate case: constant frequency. + phase = 2 * pi * f0 * t + else: + # Singular point: the instantaneous frequency blows up + # when t == sing. + sing = -f1 * t1 / (f0 - f1) + phase = 2 * pi * (-sing * f0) * log(np.abs(1 - t/sing)) + + else: + raise ValueError("method must be 'linear', 'quadratic', 'logarithmic', " + f"or 'hyperbolic', but a value of {method!r} was given.") + + return phase + + +def sweep_poly(t, poly, phi=0): + """ + Frequency-swept cosine generator, with a time-dependent frequency. + + This function generates a sinusoidal function whose instantaneous + frequency varies with time. The frequency at time `t` is given by + the polynomial `poly`. + + Parameters + ---------- + t : ndarray + Times at which to evaluate the waveform. + poly : 1-D array_like or instance of numpy.poly1d + The desired frequency expressed as a polynomial. If `poly` is + a list or ndarray of length n, then the elements of `poly` are + the coefficients of the polynomial, and the instantaneous + frequency is + + ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]`` + + If `poly` is an instance of numpy.poly1d, then the + instantaneous frequency is + + ``f(t) = poly(t)`` + + phi : float, optional + Phase offset, in degrees, Default: 0. + + Returns + ------- + sweep_poly : ndarray + A numpy array containing the signal evaluated at `t` with the + requested time-varying frequency. More precisely, the function + returns ``cos(phase + (pi/180)*phi)``, where `phase` is the integral + (from 0 to t) of ``2 * pi * f(t)``; ``f(t)`` is defined above. + + See Also + -------- + chirp + + Notes + ----- + .. versionadded:: 0.8.0 + + If `poly` is a list or ndarray of length `n`, then the elements of + `poly` are the coefficients of the polynomial, and the instantaneous + frequency is: + + ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]`` + + If `poly` is an instance of `numpy.poly1d`, then the instantaneous + frequency is: + + ``f(t) = poly(t)`` + + Finally, the output `s` is: + + ``cos(phase + (pi/180)*phi)`` + + where `phase` is the integral from 0 to `t` of ``2 * pi * f(t)``, + ``f(t)`` as defined above. + + Examples + -------- + Compute the waveform with instantaneous frequency:: + + f(t) = 0.025*t**3 - 0.36*t**2 + 1.25*t + 2 + + over the interval 0 <= t <= 10. + + >>> import numpy as np + >>> from scipy.signal import sweep_poly + >>> p = np.poly1d([0.025, -0.36, 1.25, 2.0]) + >>> t = np.linspace(0, 10, 5001) + >>> w = sweep_poly(t, p) + + Plot it: + + >>> import matplotlib.pyplot as plt + >>> plt.subplot(2, 1, 1) + >>> plt.plot(t, w) + >>> plt.title("Sweep Poly\\nwith frequency " + + ... "$f(t) = 0.025t^3 - 0.36t^2 + 1.25t + 2$") + >>> plt.subplot(2, 1, 2) + >>> plt.plot(t, p(t), 'r', label='f(t)') + >>> plt.legend() + >>> plt.xlabel('t') + >>> plt.tight_layout() + >>> plt.show() + + """ + # 'phase' is computed in _sweep_poly_phase, to make testing easier. + phase = _sweep_poly_phase(t, poly) + # Convert to radians. + phi *= pi / 180 + return cos(phase + phi) + + +def _sweep_poly_phase(t, poly): + """ + Calculate the phase used by sweep_poly to generate its output. + + See `sweep_poly` for a description of the arguments. + + """ + # polyint handles lists, ndarrays and instances of poly1d automatically. + intpoly = polyint(poly) + phase = 2 * pi * polyval(intpoly, t) + return phase + + +def unit_impulse(shape, idx=None, dtype=float): + r""" + Unit impulse signal (discrete delta function) or unit basis vector. + + Parameters + ---------- + shape : int or tuple of int + Number of samples in the output (1-D), or a tuple that represents the + shape of the output (N-D). + idx : None or int or tuple of int or 'mid', optional + Index at which the value is 1. If None, defaults to the 0th element. + If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in + all dimensions. If an int, the impulse will be at `idx` in all + dimensions. + dtype : data-type, optional + The desired data-type for the array, e.g., ``numpy.int8``. Default is + ``numpy.float64``. + + Returns + ------- + y : ndarray + Output array containing an impulse signal. + + Notes + ----- + In digital signal processing literature the unit impulse signal is often + represented by the Kronecker delta. [1]_ I.e., a signal :math:`u_k[n]`, + which is zero everywhere except being one at the :math:`k`-th sample, + can be expressed as + + .. math:: + + u_k[n] = \delta[n-k] \equiv \delta_{n,k}\ . + + Furthermore, the unit impulse is frequently interpreted as the discrete-time + version of the continuous-time Dirac distribution. [2]_ + + References + ---------- + .. [1] "Kronecker delta", *Wikipedia*, + https://en.wikipedia.org/wiki/Kronecker_delta#Digital_signal_processing + .. [2] "Dirac delta function" *Wikipedia*, + https://en.wikipedia.org/wiki/Dirac_delta_function#Relationship_to_the_Kronecker_delta + + .. versionadded:: 0.19.0 + + Examples + -------- + An impulse at the 0th element (:math:`\\delta[n]`): + + >>> from scipy import signal + >>> signal.unit_impulse(8) + array([ 1., 0., 0., 0., 0., 0., 0., 0.]) + + Impulse offset by 2 samples (:math:`\\delta[n-2]`): + + >>> signal.unit_impulse(7, 2) + array([ 0., 0., 1., 0., 0., 0., 0.]) + + 2-dimensional impulse, centered: + + >>> signal.unit_impulse((3, 3), 'mid') + array([[ 0., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 0.]]) + + Impulse at (2, 2), using broadcasting: + + >>> signal.unit_impulse((4, 4), 2) + array([[ 0., 0., 0., 0.], + [ 0., 0., 0., 0.], + [ 0., 0., 1., 0.], + [ 0., 0., 0., 0.]]) + + Plot the impulse response of a 4th-order Butterworth lowpass filter: + + >>> imp = signal.unit_impulse(100, 'mid') + >>> b, a = signal.butter(4, 0.2) + >>> response = signal.lfilter(b, a, imp) + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-50, 50), imp) + >>> plt.plot(np.arange(-50, 50), response) + >>> plt.margins(0.1, 0.1) + >>> plt.xlabel('Time [samples]') + >>> plt.ylabel('Amplitude') + >>> plt.grid(True) + >>> plt.show() + + """ + out = zeros(shape, dtype) + + shape = np.atleast_1d(shape) + + if idx is None: + idx = (0,) * len(shape) + elif idx == 'mid': + idx = tuple(shape // 2) + elif not hasattr(idx, "__iter__"): + idx = (idx,) * len(shape) + + out[idx] = 1 + return out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_wavelets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_wavelets.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9f8fa32672e3f252f0f4ec4e387e0d474dc21e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/_wavelets.py @@ -0,0 +1,29 @@ +import numpy as np +from scipy.signal import convolve + + +def _ricker(points, a): + A = 2 / (np.sqrt(3 * a) * (np.pi**0.25)) + wsq = a**2 + vec = np.arange(0, points) - (points - 1.0) / 2 + xsq = vec**2 + mod = (1 - xsq / wsq) + gauss = np.exp(-xsq / (2 * wsq)) + total = A * mod * gauss + return total + + +def _cwt(data, wavelet, widths, dtype=None, **kwargs): + # Determine output type + if dtype is None: + if np.asarray(wavelet(1, widths[0], **kwargs)).dtype.char in 'FDG': + dtype = np.complex128 + else: + dtype = np.float64 + + output = np.empty((len(widths), len(data)), dtype=dtype) + for ind, width in enumerate(widths): + N = np.min([10 * width, len(data)]) + wavelet_data = np.conj(wavelet(N, width, **kwargs)[::-1]) + output[ind] = convolve(data, wavelet_data, mode='same') + return output diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/bsplines.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..0328d45c107bda78cbdbd374148237ca09ac411d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/bsplines.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'spline_filter', 'gauss_spline', + 'cspline1d', 'qspline1d', 'cspline1d_eval', 'qspline1d_eval', + 'cspline2d', 'sepfir2d' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="bsplines", + private_modules=["_spline_filters"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/filter_design.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..41dc230a7f24a7ac3209f821d8d0f9417130afbd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/filter_design.py @@ -0,0 +1,28 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize', + 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign', + 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', + 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord', + 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap', + 'BadCoefficients', 'freqs_zpk', 'freqz_zpk', + 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay', + 'sosfreqz', 'freqz_sos', 'iirnotch', 'iirpeak', 'bilinear_zpk', + 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk', + 'gammatone', 'iircomb', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="filter_design", + private_modules=["_filter_design"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..2214b82998bdefd2c6d6171cc952adf827269736 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'kaiser_beta', 'kaiser_atten', 'kaiserord', + 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="fir_filter_design", + private_modules=["_fir_filter_design"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/lti_conversion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/lti_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..7080990afc9e23e51e8a45aaa146b64c58dda3cf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/lti_conversion.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk', + 'cont2discrete', 'tf2zpk', 'zpk2tf', 'normalize' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="lti_conversion", + private_modules=["_lti_conversion"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/ltisys.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/ltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..5123068de559f124bf444c12ef9824c3d14de64f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/ltisys.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'lti', 'dlti', 'TransferFunction', 'ZerosPolesGain', 'StateSpace', + 'lsim', 'impulse', 'step', 'bode', + 'freqresp', 'place_poles', 'dlsim', 'dstep', 'dimpulse', + 'dfreqresp', 'dbode', + 'tf2zpk', 'zpk2tf', 'normalize', 'freqs', + 'freqz', 'freqs_zpk', 'freqz_zpk', 'tf2ss', 'abcd_normalize', + 'ss2tf', 'zpk2ss', 'ss2zpk', 'cont2discrete', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="ltisys", + private_modules=["_ltisys"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/signaltools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/signaltools.py new file mode 100644 index 0000000000000000000000000000000000000000..85d426f5fb2605c639fc6dbd1b4d0284a3f11e1b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/signaltools.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'correlate', 'correlation_lags', 'correlate2d', + 'convolve', 'convolve2d', 'fftconvolve', 'oaconvolve', + 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter', + 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2', + 'unique_roots', 'invres', 'invresz', 'residue', + 'residuez', 'resample', 'resample_poly', 'detrend', + 'lfilter_zi', 'sosfilt_zi', 'sosfiltfilt', 'choose_conv_method', + 'filtfilt', 'decimate', 'vectorstrength', + 'dlti', 'upfirdn', 'get_window', 'cheby1', 'firwin' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="signaltools", + private_modules=["_signaltools"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/spectral.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..299ebed781b00a1f1f35e96c54f4c20d9bd9d0fc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/spectral.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'periodogram', 'welch', 'lombscargle', 'csd', 'coherence', + 'spectrogram', 'stft', 'istft', 'check_COLA', 'check_NOLA', + 'get_window', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="spectral", + private_modules=["_spectral_py"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/spline.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/spline.py new file mode 100644 index 0000000000000000000000000000000000000000..7afd0d0a14beecd5bc4522050eaf3b195f1a3601 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/spline.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in the future +# versions of SciPy. Use the `scipy.signal` namespace for importing the +# functions included below. + +import warnings + +from . import _spline + +__all__ = ['sepfir2d'] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + if name not in __all__: + raise AttributeError( + f"scipy.signal.spline is deprecated and has no attribute {name}. " + "Try looking in scipy.signal instead.") + + warnings.warn(f"Please use `{name}` from the `scipy.signal` namespace, " + "the `scipy.signal.spline` namespace is deprecated.", + category=DeprecationWarning, stacklevel=2) + return getattr(_spline, name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py new file mode 100644 index 0000000000000000000000000000000000000000..42d3d830d0e39797832472b9e039259111cfccc8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py @@ -0,0 +1,480 @@ +"""Helpers to utilize existing stft / istft tests for testing `ShortTimeFFT`. + +This module provides the functions stft_compare() and istft_compare(), which, +compares the output between the existing (i)stft() and the shortTimeFFT based +_(i)stft_wrapper() implementations in this module. + +For testing add the following imports to the file ``tests/test_spectral.py``:: + + from ._scipy_spectral_test_shim import stft_compare as stft + from ._scipy_spectral_test_shim import istft_compare as istft + +and remove the existing imports of stft and istft. + +The idea of these wrappers is not to provide a backward-compatible interface +but to demonstrate that the ShortTimeFFT implementation is at least as capable +as the existing one and delivers comparable results. Furthermore, the +wrappers highlight the different philosophies of the implementations, +especially in the border handling. +""" +import platform +from typing import cast, Literal + +import numpy as np +from numpy.testing import assert_allclose + +from scipy.signal import ShortTimeFFT +from scipy.signal import csd, get_window, stft, istft +from scipy.signal._arraytools import const_ext, even_ext, odd_ext, zero_ext +from scipy.signal._short_time_fft import FFT_MODE_TYPE +from scipy.signal._spectral_py import _spectral_helper, _triage_segments, \ + _median_bias + + +def _stft_wrapper(x, fs=1.0, window='hann', nperseg=256, noverlap=None, + nfft=None, detrend=False, return_onesided=True, + boundary='zeros', padded=True, axis=-1, scaling='spectrum'): + """Wrapper for the SciPy `stft()` function based on `ShortTimeFFT` for + unit testing. + + Handling the boundary and padding is where `ShortTimeFFT` and `stft()` + differ in behavior. Parts of `_spectral_helper()` were copied to mimic + the` stft()` behavior. + + This function is meant to be solely used by `stft_compare()`. + """ + if scaling not in ('psd', 'spectrum'): # same errors as in original stft: + raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!") + + # The following lines are taken from the original _spectral_helper(): + boundary_funcs = {'even': even_ext, + 'odd': odd_ext, + 'constant': const_ext, + 'zeros': zero_ext, + None: None} + + if boundary not in boundary_funcs: + raise ValueError(f"Unknown boundary option '{boundary}', must be one" + + f" of: {list(boundary_funcs.keys())}") + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape) + + if nperseg is not None: # if specified by user + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + # parse window; if array like, then set nperseg = win.shape + win, nperseg = _triage_segments(window, nperseg, + input_length=x.shape[axis]) + + if nfft is None: + nfft = nperseg + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + n = x.shape[axis] + + # Padding occurs after boundary extension, so that the extended signal ends + # in zeros, instead of introducing an impulse at the end. + # I.e. if x = [..., 3, 2] + # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0] + # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3] + + if boundary is not None: + ext_func = boundary_funcs[boundary] + # Extend by nperseg//2 in front and back: + x = ext_func(x, nperseg//2, axis=axis) + + if padded: + # Pad to integer number of windowed segments + # I.e make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg + x = np.moveaxis(x, axis, -1) + + # This is an edge case where shortTimeFFT returns one more time slice + # than the Scipy stft() shorten to remove last time slice: + if n % 2 == 1 and nperseg % 2 == 1 and noverlap % 2 == 1: + x = x[..., : -1] + + nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg + zeros_shape = list(x.shape[:-1]) + [nadd] + x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1) + x = np.moveaxis(x, -1, axis) + + # ... end original _spectral_helper() code. + scale_to = {'spectrum': 'magnitude', 'psd': 'psd'}[scaling] + + if np.iscomplexobj(x) and return_onesided: + return_onesided = False + # using cast() to make mypy happy: + fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided else 'twosided') + + ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft, + scale_to=scale_to, phase_shift=None) + + k_off = nperseg // 2 + p0 = 0 # ST.lower_border_end[1] + 1 + nn = x.shape[axis] if padded else n+k_off+1 + # number of frames akin to legacy stft computation + p1 = (x.shape[axis] - nperseg) // nstep + 1 + + detr = None if detrend is False else detrend + Sxx = ST.stft_detrend(x, detr, p0, p1, k_offset=k_off, axis=axis) + t = ST.t(nn, 0, p1 - p0, k_offset=0 if boundary is not None else k_off) + if x.dtype in (np.float32, np.complex64): + Sxx = Sxx.astype(np.complex64) + + return ST.f, t, Sxx + + +def _istft_wrapper(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, input_onesided=True, boundary=True, time_axis=-1, + freq_axis=-2, scaling='spectrum') -> \ + tuple[np.ndarray, np.ndarray, tuple[int, int]]: + """Wrapper for the SciPy `istft()` function based on `ShortTimeFFT` for + unit testing. + + Note that only option handling is implemented as far as to handle the unit + tests. E.g., the case ``nperseg=None`` is not handled. + + This function is meant to be solely used by `istft_compare()`. + """ + # *** Lines are taken from _spectral_py.istft() ***: + if Zxx.ndim < 2: + raise ValueError('Input stft must be at least 2d!') + + if freq_axis == time_axis: + raise ValueError('Must specify differing time and frequency axes!') + + nseg = Zxx.shape[time_axis] + + if input_onesided: + # Assume even segment length + n_default = 2*(Zxx.shape[freq_axis] - 1) + else: + n_default = Zxx.shape[freq_axis] + + # Check windowing parameters + if nperseg is None: + nperseg = n_default + else: + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if nfft is None: + if input_onesided and (nperseg == n_default + 1): + # Odd nperseg, no FFT padding + nfft = nperseg + else: + nfft = n_default + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + # Get window as array + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError(f'window must have length of {nperseg}') + + outputlength = nperseg + (nseg-1)*nstep + # *** End block of: Taken from _spectral_py.istft() *** + + # Using cast() to make mypy happy: + fft_mode = cast(FFT_MODE_TYPE, 'onesided' if input_onesided else 'twosided') + scale_to = cast(Literal['magnitude', 'psd'], + {'spectrum': 'magnitude', 'psd': 'psd'}[scaling]) + + ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft, + scale_to=scale_to, phase_shift=None) + + if boundary: + j = nperseg if nperseg % 2 == 0 else nperseg - 1 + k0 = ST.k_min + nperseg // 2 + k1 = outputlength - j + k0 + else: + raise NotImplementedError("boundary=False does not make sense with" + + "ShortTimeFFT.istft()!") + + x = ST.istft(Zxx, k0=k0, k1=k1, f_axis=freq_axis, t_axis=time_axis) + t = np.arange(k1 - k0) * ST.T + k_hi = ST.upper_border_begin(k1 - k0)[0] + # using cast() to make mypy happy: + return t, x, (ST.lower_border_end[0], k_hi) + + +def _csd_wrapper(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, average='mean'): + """Wrapper for the `csd()` function based on `ShortTimeFFT` for + unit testing. + """ + freqs, _, Pxy = _csd_test_shim(x, y, fs, window, nperseg, noverlap, nfft, + detrend, return_onesided, scaling, axis) + + # The following code is taken from csd(): + if len(Pxy.shape) >= 2 and Pxy.size > 0: + if Pxy.shape[-1] > 1: + if average == 'median': + # np.median must be passed real arrays for the desired result + bias = _median_bias(Pxy.shape[-1]) + if np.iscomplexobj(Pxy): + Pxy = (np.median(np.real(Pxy), axis=-1) + + 1j * np.median(np.imag(Pxy), axis=-1)) + else: + Pxy = np.median(Pxy, axis=-1) + Pxy /= bias + elif average == 'mean': + Pxy = Pxy.mean(axis=-1) + else: + raise ValueError(f'average must be "median" or "mean", got {average}') + else: + Pxy = np.reshape(Pxy, Pxy.shape[:-1]) + + return freqs, Pxy + + +def _csd_test_shim(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1): + """Compare output of _spectral_helper() and ShortTimeFFT, more + precisely _spect_helper_csd() for used in csd_wrapper(). + + The motivation of this function is to test if the ShortTimeFFT-based + wrapper `_spect_helper_csd()` returns the same values as `_spectral_helper`. + This function should only be usd by csd() in (unit) testing. + """ + freqs, t, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, nfft, + detrend, return_onesided, scaling, axis, + mode='psd') + freqs1, Pxy1 = _spect_helper_csd(x, y, fs, window, nperseg, noverlap, nfft, + detrend, return_onesided, scaling, axis) + + np.testing.assert_allclose(freqs1, freqs) + amax_Pxy = max(np.abs(Pxy).max(), 1) if Pxy.size else 1 + atol = np.finfo(Pxy.dtype).resolution * amax_Pxy # needed for large Pxy + # for c_ in range(Pxy.shape[-1]): + # np.testing.assert_allclose(Pxy1[:, c_], Pxy[:, c_], atol=atol) + np.testing.assert_allclose(Pxy1, Pxy, atol=atol) + return freqs, t, Pxy + + +def _spect_helper_csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1): + """Wrapper for replacing _spectral_helper() by using the ShortTimeFFT + for use by csd(). + + This function should be only used by _csd_test_shim() and is only useful + for testing the ShortTimeFFT implementation. + """ + + # The following lines are taken from the original _spectral_helper(): + same_data = y is x + axis = int(axis) + + # Ensure we have np.arrays, get outdtype + x = np.asarray(x) + if not same_data: + y = np.asarray(y) + # outdtype = np.result_type(x, y, np.complex64) + # else: + # outdtype = np.result_type(x, np.complex64) + + if not same_data: + # Check if we can broadcast the outer axes together + xouter = list(x.shape) + youter = list(y.shape) + xouter.pop(axis) + youter.pop(axis) + try: + outershape = np.broadcast(np.empty(xouter), np.empty(youter)).shape + except ValueError as e: + raise ValueError('x and y cannot be broadcast together.') from e + + if same_data: + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape) + else: + if x.size == 0 or y.size == 0: + outshape = outershape + (min([x.shape[axis], y.shape[axis]]),) + emptyout = np.moveaxis(np.empty(outshape), -1, axis) + return emptyout, emptyout + + if nperseg is not None: # if specified by user + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + # parse window; if array like, then set nperseg = win.shape + n = x.shape[axis] if same_data else max(x.shape[axis], y.shape[axis]) + win, nperseg = _triage_segments(window, nperseg, input_length=n) + + if nfft is None: + nfft = nperseg + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg // 2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + if np.iscomplexobj(x) and return_onesided: + return_onesided = False + + # using cast() to make mypy happy: + fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided + else 'twosided') + scale = {'spectrum': 'magnitude', 'density': 'psd'}[scaling] + SFT = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft, + scale_to=scale, phase_shift=None) + + # _spectral_helper() calculates X.conj()*Y instead of X*Y.conj(): + Pxy = SFT.spectrogram(y, x, detr=None if detrend is False else detrend, + p0=0, p1=(n-noverlap)//SFT.hop, k_offset=nperseg//2, + axis=axis).conj() + # Note: + # 'onesided2X' scaling of ShortTimeFFT conflicts with the + # scaling='spectrum' parameter, since it doubles the squared magnitude, + # which in the view of the ShortTimeFFT implementation does not make sense. + # Hence, the doubling of the square is implemented here: + if return_onesided: + f_axis = Pxy.ndim - 1 + axis if axis < 0 else axis + Pxy = np.moveaxis(Pxy, f_axis, -1) + Pxy[..., 1:-1 if SFT.mfft % 2 == 0 else None] *= 2 + Pxy = np.moveaxis(Pxy, -1, f_axis) + + return SFT.f, Pxy + + +def stft_compare(x, fs=1.0, window='hann', nperseg=256, noverlap=None, + nfft=None, detrend=False, return_onesided=True, + boundary='zeros', padded=True, axis=-1, scaling='spectrum'): + """Assert that the results from the existing `stft()` and `_stft_wrapper()` + are close to each other. + + For comparing the STFT values an absolute tolerance of the floating point + resolution was added to circumvent problems with the following tests: + * For float32 the tolerances are much higher in + TestSTFT.test_roundtrip_float32()). + * The TestSTFT.test_roundtrip_scaling() has a high relative deviation. + Interestingly this did not appear in Scipy 1.9.1 but only in the current + development version. + """ + kw = dict(x=x, fs=fs, window=window, nperseg=nperseg, noverlap=noverlap, + nfft=nfft, detrend=detrend, return_onesided=return_onesided, + boundary=boundary, padded=padded, axis=axis, scaling=scaling) + f, t, Zxx = stft(**kw) + f_wrapper, t_wrapper, Zxx_wrapper = _stft_wrapper(**kw) + + e_msg_part = " of `stft_wrapper()` differ from `stft()`." + assert_allclose(f_wrapper, f, err_msg=f"Frequencies {e_msg_part}") + assert_allclose(t_wrapper, t, err_msg=f"Time slices {e_msg_part}") + + # Adapted tolerances to account for: + atol = np.finfo(Zxx.dtype).resolution * 2 + assert_allclose(Zxx_wrapper, Zxx, atol=atol, + err_msg=f"STFT values {e_msg_part}") + return f, t, Zxx + + +def istft_compare(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, input_onesided=True, boundary=True, time_axis=-1, + freq_axis=-2, scaling='spectrum'): + """Assert that the results from the existing `istft()` and + `_istft_wrapper()` are close to each other. + + Quirks: + * If ``boundary=False`` the comparison is skipped, since it does not + make sense with ShortTimeFFT.istft(). Only used in test + TestSTFT.test_roundtrip_boundary_extension(). + * If ShortTimeFFT.istft() decides the STFT is not invertible, the + comparison is skipped, since istft() only emits a warning and does not + return a correct result. Only used in + ShortTimeFFT.test_roundtrip_not_nola(). + * For comparing the signals an absolute tolerance of the floating point + resolution was added to account for the low accuracy of float32 (Occurs + only in TestSTFT.test_roundtrip_float32()). + """ + kw = dict(Zxx=Zxx, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, input_onesided=input_onesided, + boundary=boundary, time_axis=time_axis, freq_axis=freq_axis, + scaling=scaling) + + t, x = istft(**kw) + if not boundary: # skip test_roundtrip_boundary_extension(): + return t, x # _istft_wrapper does() not implement this case + try: # if inversion fails, istft() only emits a warning: + t_wrapper, x_wrapper, (k_lo, k_hi) = _istft_wrapper(**kw) + except ValueError as v: # Do nothing if inversion fails: + if v.args[0] == "Short-time Fourier Transform not invertible!": + return t, x + raise v + + e_msg_part = " of `istft_wrapper()` differ from `istft()`" + assert_allclose(t, t_wrapper, err_msg=f"Sample times {e_msg_part}") + + # Adapted tolerances to account for resolution loss: + atol = np.finfo(x.dtype).resolution*2 # instead of default atol = 0 + rtol = 1e-7 # default for np.allclose() + + # Relax atol on 32-Bit platforms a bit to pass CI tests. + # - Not clear why there are discrepancies (in the FFT maybe?) + # - Not sure what changed on 'i686' since earlier on those test passed + if x.dtype == np.float32 and platform.machine() == 'i686': + # float32 gets only used by TestSTFT.test_roundtrip_float32() so + # we are using the tolerances from there to circumvent CI problems + atol, rtol = 1e-4, 1e-5 + elif platform.machine() in ('aarch64', 'i386', 'i686'): + atol = max(atol, 1e-12) # 2e-15 seems too tight for 32-Bit platforms + + assert_allclose(x_wrapper[k_lo:k_hi], x[k_lo:k_hi], atol=atol, rtol=rtol, + err_msg=f"Signal values {e_msg_part}") + return t, x + + +def csd_compare(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, average='mean'): + """Assert that the results from the existing `csd()` and `_csd_wrapper()` + are close to each other. """ + kw = dict(x=x, y=y, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, + return_onesided=return_onesided, scaling=scaling, axis=axis, + average=average) + freqs0, Pxy0 = csd(**kw) + freqs1, Pxy1 = _csd_wrapper(**kw) + + assert_allclose(freqs1, freqs0) + assert_allclose(Pxy1, Pxy0) + assert_allclose(freqs1, freqs0) + return freqs0, Pxy0 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/mpsig.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/mpsig.py new file mode 100644 index 0000000000000000000000000000000000000000..d129de74e5df00c22bc0b82c7d3f7b52483941f9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/mpsig.py @@ -0,0 +1,122 @@ +""" +Some signal functions implemented using mpmath. +""" + +try: + import mpmath +except ImportError: + mpmath = None + + +def _prod(seq): + """Returns the product of the elements in the sequence `seq`.""" + p = 1 + for elem in seq: + p *= elem + return p + + +def _relative_degree(z, p): + """ + Return relative degree of transfer function from zeros and poles. + + This is simply len(p) - len(z), which must be nonnegative. + A ValueError is raised if len(p) < len(z). + """ + degree = len(p) - len(z) + if degree < 0: + raise ValueError("Improper transfer function. " + "Must have at least as many poles as zeros.") + return degree + + +def _zpkbilinear(z, p, k, fs): + """Bilinear transformation to convert a filter from analog to digital.""" + + degree = _relative_degree(z, p) + + fs2 = 2*fs + + # Bilinear transform the poles and zeros + z_z = [(fs2 + z1) / (fs2 - z1) for z1 in z] + p_z = [(fs2 + p1) / (fs2 - p1) for p1 in p] + + # Any zeros that were at infinity get moved to the Nyquist frequency + z_z.extend([-1] * degree) + + # Compensate for gain change + numer = _prod(fs2 - z1 for z1 in z) + denom = _prod(fs2 - p1 for p1 in p) + k_z = k * numer / denom + + return z_z, p_z, k_z.real + + +def _zpklp2lp(z, p, k, wo=1): + """Transform a lowpass filter to a different cutoff frequency.""" + + degree = _relative_degree(z, p) + + # Scale all points radially from origin to shift cutoff frequency + z_lp = [wo * z1 for z1 in z] + p_lp = [wo * p1 for p1 in p] + + # Each shifted pole decreases gain by wo, each shifted zero increases it. + # Cancel out the net change to keep overall gain the same + k_lp = k * wo**degree + + return z_lp, p_lp, k_lp + + +def _butter_analog_poles(n): + """ + Poles of an analog Butterworth lowpass filter. + + This is the same calculation as scipy.signal.buttap(n) or + scipy.signal.butter(n, 1, analog=True, output='zpk'), but mpmath is used, + and only the poles are returned. + """ + poles = [-mpmath.exp(1j*mpmath.pi*k/(2*n)) for k in range(-n+1, n, 2)] + return poles + + +def butter_lp(n, Wn): + """ + Lowpass Butterworth digital filter design. + + This computes the same result as scipy.signal.butter(n, Wn, output='zpk'), + but it uses mpmath, and the results are returned in lists instead of NumPy + arrays. + """ + zeros = [] + poles = _butter_analog_poles(n) + k = 1 + fs = 2 + warped = 2 * fs * mpmath.tan(mpmath.pi * Wn / fs) + z, p, k = _zpklp2lp(zeros, poles, k, wo=warped) + z, p, k = _zpkbilinear(z, p, k, fs=fs) + return z, p, k + + +def zpkfreqz(z, p, k, worN=None): + """ + Frequency response of a filter in zpk format, using mpmath. + + This is the same calculation as scipy.signal.freqz, but the input is in + zpk format, the calculation is performed using mpath, and the results are + returned in lists instead of NumPy arrays. + """ + if worN is None or isinstance(worN, int): + N = worN or 512 + ws = [mpmath.pi * mpmath.mpf(j) / N for j in range(N)] + else: + ws = worN + + h = [] + for wk in ws: + zm1 = mpmath.exp(1j * wk) + numer = _prod([zm1 - t for t in z]) + denom = _prod([zm1 - t for t in p]) + hk = k * numer / denom + h.append(hk) + return ws, h diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..4bda9716e0bc4b6ad3ed0c3954147043b74c421a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py @@ -0,0 +1,111 @@ +import numpy as np + +from scipy._lib._array_api import xp_assert_equal +from pytest import raises as assert_raises + +from scipy.signal._arraytools import (axis_slice, axis_reverse, + odd_ext, even_ext, const_ext, zero_ext) + + +class TestArrayTools: + + def test_axis_slice(self): + a = np.arange(12).reshape(3, 4) + + s = axis_slice(a, start=0, stop=1, axis=0) + xp_assert_equal(s, a[0:1, :]) + + s = axis_slice(a, start=-1, axis=0) + xp_assert_equal(s, a[-1:, :]) + + s = axis_slice(a, start=0, stop=1, axis=1) + xp_assert_equal(s, a[:, 0:1]) + + s = axis_slice(a, start=-1, axis=1) + xp_assert_equal(s, a[:, -1:]) + + s = axis_slice(a, start=0, step=2, axis=0) + xp_assert_equal(s, a[::2, :]) + + s = axis_slice(a, start=0, step=2, axis=1) + xp_assert_equal(s, a[:, ::2]) + + def test_axis_reverse(self): + a = np.arange(12).reshape(3, 4) + + r = axis_reverse(a, axis=0) + xp_assert_equal(r, a[::-1, :]) + + r = axis_reverse(a, axis=1) + xp_assert_equal(r, a[:, ::-1]) + + def test_odd_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + odd = odd_ext(a, 2, axis=1) + expected = np.array([[-1, 0, 1, 2, 3, 4, 5, 6, 7], + [11, 10, 9, 8, 7, 6, 5, 4, 3]]) + xp_assert_equal(odd, expected) + + odd = odd_ext(a, 1, axis=0) + expected = np.array([[-7, -4, -1, 2, 5], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [17, 14, 11, 8, 5]]) + xp_assert_equal(odd, expected) + + assert_raises(ValueError, odd_ext, a, 2, axis=0) + assert_raises(ValueError, odd_ext, a, 5, axis=1) + + def test_even_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + even = even_ext(a, 2, axis=1) + expected = np.array([[3, 2, 1, 2, 3, 4, 5, 4, 3], + [7, 8, 9, 8, 7, 6, 5, 6, 7]]) + xp_assert_equal(even, expected) + + even = even_ext(a, 1, axis=0) + expected = np.array([[9, 8, 7, 6, 5], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [1, 2, 3, 4, 5]]) + xp_assert_equal(even, expected) + + assert_raises(ValueError, even_ext, a, 2, axis=0) + assert_raises(ValueError, even_ext, a, 5, axis=1) + + def test_const_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + const = const_ext(a, 2, axis=1) + expected = np.array([[1, 1, 1, 2, 3, 4, 5, 5, 5], + [9, 9, 9, 8, 7, 6, 5, 5, 5]]) + xp_assert_equal(const, expected) + + const = const_ext(a, 1, axis=0) + expected = np.array([[1, 2, 3, 4, 5], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [9, 8, 7, 6, 5]]) + xp_assert_equal(const, expected) + + def test_zero_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + zero = zero_ext(a, 2, axis=1) + expected = np.array([[0, 0, 1, 2, 3, 4, 5, 0, 0], + [0, 0, 9, 8, 7, 6, 5, 0, 0]]) + xp_assert_equal(zero, expected) + + zero = zero_ext(a, 1, axis=0) + expected = np.array([[0, 0, 0, 0, 0], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [0, 0, 0, 0, 0]]) + xp_assert_equal(zero, expected) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7baf2d8d9f2f9a84452965c35b5262ca20105d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py @@ -0,0 +1,330 @@ +# pylint: disable=missing-docstring +import numpy as np + +from scipy._lib._array_api import ( + assert_almost_equal, xp_assert_close, xp_assert_equal +) +import pytest +from pytest import raises + +import scipy.signal._spline_filters as bsp +from scipy import signal + + +class TestBSplines: + """Test behaviors of B-splines. Some of the values tested against were + returned as of SciPy 1.1.0 and are included for regression testing + purposes. Others (at integer points) are compared to theoretical + expressions (cf. Unser, Aldroubi, Eden, IEEE TSP 1993, Table 1).""" + + def test_spline_filter(self): + rng = np.random.RandomState(12457) + # Test the type-error branch + raises(TypeError, bsp.spline_filter, np.asarray([0]), 0) + # Test the real branch + data_array_real = rng.rand(12, 12) + # make the magnitude exceed 1, and make some negative + data_array_real = 10*(1-2*data_array_real) + result_array_real = np.asarray( + [[-.463312621, 8.33391222, .697290949, 5.28390836, + 5.92066474, 6.59452137, 9.84406950, -8.78324188, + 7.20675750, -8.17222994, -4.38633345, 9.89917069], + [2.67755154, 6.24192170, -3.15730578, 9.87658581, + -9.96930425, 3.17194115, -4.50919947, 5.75423446, + 9.65979824, -8.29066885, .971416087, -2.38331897], + [-7.08868346, 4.89887705, -1.37062289, 7.70705838, + 2.51526461, 3.65885497, 5.16786604, -8.77715342e-03, + 4.10533325, 9.04761993, -.577960351, 9.86382519], + [-4.71444301, -1.68038985, 2.84695116, 1.14315938, + -3.17127091, 1.91830461, 7.13779687, -5.35737482, + -9.66586425, -9.87717456, 9.93160672, 4.71948144], + [9.49551194, -1.92958436, 6.25427993, -9.05582911, + 3.97562282, 7.68232426, -1.04514824, -5.86021443, + -8.43007451, 5.47528997, 2.06330736, -8.65968112], + [-8.91720100, 8.87065356, 3.76879937, 2.56222894, + -.828387146, 8.72288903, 6.42474741, -6.84576083, + 9.94724115, 6.90665380, -6.61084494, -9.44907391], + [9.25196790, -.774032030, 7.05371046, -2.73505725, + 2.53953305, -1.82889155, 2.95454824, -1.66362046, + 5.72478916, -3.10287679, 1.54017123, -7.87759020], + [-3.98464539, -2.44316992, -1.12708657, 1.01725672, + -8.89294671, -5.42145629, -6.16370321, 2.91775492, + 9.64132208, .702499998, -2.02622392, 1.56308431], + [-2.22050773, 7.89951554, 5.98970713, -7.35861835, + 5.45459283, -7.76427957, 3.67280490, -4.05521315, + 4.51967507, -3.22738749, -3.65080177, 3.05630155], + [-6.21240584, -.296796126, -8.34800163, 9.21564563, + -3.61958784, -4.77120006, -3.99454057, 1.05021988e-03, + -6.95982829, 6.04380797, 8.43181250, -2.71653339], + [1.19638037, 6.99718842e-02, 6.72020394, -2.13963198, + 3.75309875, -5.70076744, 5.92143551, -7.22150575, + -3.77114594, -1.11903194, -5.39151466, 3.06620093], + [9.86326886, 1.05134482, -7.75950607, -3.64429655, + 7.81848957, -9.02270373, 3.73399754, -4.71962549, + -7.71144306, 3.78263161, 6.46034818, -4.43444731]]) + xp_assert_close(bsp.spline_filter(data_array_real, 0), + result_array_real) + + def test_spline_filter_complex(self): + rng = np.random.RandomState(12457) + data_array_complex = rng.rand(7, 7) + rng.rand(7, 7)*1j + # make the magnitude exceed 1, and make some negative + data_array_complex = 10*(1+1j-2*data_array_complex) + result_array_complex = np.asarray( + [[-4.61489230e-01-1.92994022j, 8.33332443+6.25519943j, + 6.96300745e-01-9.05576038j, 5.28294849+3.97541356j, + 5.92165565+7.68240595j, 6.59493160-1.04542804j, + 9.84503460-5.85946894j], + [-8.78262329-8.4295969j, 7.20675516+5.47528982j, + -8.17223072+2.06330729j, -4.38633347-8.65968037j, + 9.89916801-8.91720295j, 2.67755103+8.8706522j, + 6.24192142+3.76879835j], + [-3.15627527+2.56303072j, 9.87658501-0.82838702j, + -9.96930313+8.72288895j, 3.17193985+6.42474651j, + -4.50919819-6.84576082j, 5.75423431+9.94723988j, + 9.65979767+6.90665293j], + [-8.28993416-6.61064005j, 9.71416473e-01-9.44907284j, + -2.38331890+9.25196648j, -7.08868170-0.77403212j, + 4.89887714+7.05371094j, -1.37062311-2.73505688j, + 7.70705748+2.5395329j], + [2.51528406-1.82964492j, 3.65885472+2.95454836j, + 5.16786575-1.66362023j, -8.77737999e-03+5.72478867j, + 4.10533333-3.10287571j, 9.04761887+1.54017115j, + -5.77960968e-01-7.87758923j], + [9.86398506-3.98528528j, -4.71444130-2.44316983j, + -1.68038976-1.12708664j, 2.84695053+1.01725709j, + 1.14315915-8.89294529j, -3.17127085-5.42145538j, + 1.91830420-6.16370344j], + [7.13875294+2.91851187j, -5.35737514+9.64132309j, + -9.66586399+0.70250005j, -9.87717438-2.0262239j, + 9.93160629+1.5630846j, 4.71948051-2.22050714j, + 9.49550819+7.8995142j]]) + # FIXME: for complex types, the computations are done in + # single precision (reason unclear). When this is changed, + # this test needs updating. + xp_assert_close(bsp.spline_filter(data_array_complex, 0), + result_array_complex, rtol=1e-6) + + def test_gauss_spline(self): + np.random.seed(12459) + assert_almost_equal(bsp.gauss_spline(0, 0), 1.381976597885342) + xp_assert_close(bsp.gauss_spline(np.asarray([1.]), 1), + np.asarray([0.04865217]), atol=1e-9 + ) + + def test_gauss_spline_list(self): + # regression test for gh-12152 (accept array_like) + knots = [-1.0, 0.0, -1.0] + assert_almost_equal(bsp.gauss_spline(knots, 3), + np.asarray([0.15418033, 0.6909883, 0.15418033]) + ) + + def test_cspline1d(self): + np.random.seed(12462) + xp_assert_equal(bsp.cspline1d(np.asarray([0])), [0.]) + c1d = np.asarray([1.21037185, 1.86293902, 2.98834059, 4.11660378, + 4.78893826]) + # test lamda != 0 + xp_assert_close(bsp.cspline1d(np.asarray([1., 2, 3, 4, 5]), 1), c1d) + c1d0 = np.asarray([0.78683946, 2.05333735, 2.99981113, 3.94741812, + 5.21051638]) + xp_assert_close(bsp.cspline1d(np.asarray([1., 2, 3, 4, 5])), c1d0) + + def test_qspline1d(self): + np.random.seed(12463) + xp_assert_equal(bsp.qspline1d(np.asarray([0])), [0.]) + # test lamda != 0 + raises(ValueError, bsp.qspline1d, np.asarray([1., 2, 3, 4, 5]), 1.) + raises(ValueError, bsp.qspline1d, np.asarray([1., 2, 3, 4, 5]), -1.) + q1d0 = np.asarray([0.85350007, 2.02441743, 2.99999534, 3.97561055, + 5.14634135]) + xp_assert_close(bsp.qspline1d(np.asarray([1., 2, 3, 4, 5])), q1d0) + + def test_cspline1d_eval(self): + np.random.seed(12464) + xp_assert_close(bsp.cspline1d_eval(np.asarray([0., 0]), [0.]), + np.asarray([0.]) + ) + xp_assert_equal(bsp.cspline1d_eval(np.asarray([1., 0, 1]), []), + np.asarray([]) + ) + x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + dx = x[1] - x[0] + newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1., + -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6., + 6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12., + 12.5] + y = np.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879, + 1.396, 4.094]) + cj = bsp.cspline1d(y) + newy = np.asarray([6.203, 4.41570658, 3.514, 5.16924703, 6.864, 6.04643068, + 4.21600281, 6.04643068, 6.864, 5.16924703, 3.514, + 4.41570658, 6.203, 6.80717667, 6.759, 6.98971173, 7.433, + 7.79560142, 7.874, 7.41525761, 5.879, 3.18686814, 1.396, + 2.24889482, 4.094, 2.24889482, 1.396, 3.18686814, 5.879, + 7.41525761, 7.874, 7.79560142, 7.433, 6.98971173, 6.759, + 6.80717667, 6.203, 4.41570658]) + xp_assert_close(bsp.cspline1d_eval(cj, newx, dx=dx, x0=x[0]), newy) + + def test_qspline1d_eval(self): + np.random.seed(12465) + xp_assert_close(bsp.qspline1d_eval(np.asarray([0., 0]), [0.]), + np.asarray([0.]) + ) + xp_assert_equal(bsp.qspline1d_eval(np.asarray([1., 0, 1]), []), + np.asarray([]) + ) + x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + dx = x[1]-x[0] + newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1., + -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6., + 6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12., + 12.5] + y = np.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879, + 1.396, 4.094]) + cj = bsp.qspline1d(y) + newy = np.asarray([6.203, 4.49418159, 3.514, 5.18390821, 6.864, 5.91436915, + 4.21600002, 5.91436915, 6.864, 5.18390821, 3.514, + 4.49418159, 6.203, 6.71900226, 6.759, 7.03980488, 7.433, + 7.81016848, 7.874, 7.32718426, 5.879, 3.23872593, 1.396, + 2.34046013, 4.094, 2.34046013, 1.396, 3.23872593, 5.879, + 7.32718426, 7.874, 7.81016848, 7.433, 7.03980488, 6.759, + 6.71900226, 6.203, 4.49418159]) + xp_assert_close(bsp.qspline1d_eval(cj, newx, dx=dx, x0=x[0]), newy) + + +# i/o dtypes with scipy 1.9.1, likely fixed by backwards compat +sepfir_dtype_map = {np.uint8: np.float32, int: np.float64, + np.float32: np.float32, float: float, + np.complex64: np.complex64, complex: complex} + +class TestSepfir2d: + def test_sepfir2d_invalid_filter(self): + filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0]) + image = np.random.rand(7, 9) + # No error for odd lengths + signal.sepfir2d(image, filt, filt[2:]) + + # Row or column filter must be odd + with pytest.raises(ValueError, match="odd length"): + signal.sepfir2d(image, filt, filt[1:]) + with pytest.raises(ValueError, match="odd length"): + signal.sepfir2d(image, filt[1:], filt) + + # Filters must be 1-dimensional + with pytest.raises(ValueError, match="object too deep"): + signal.sepfir2d(image, filt.reshape(1, -1), filt) + with pytest.raises(ValueError, match="object too deep"): + signal.sepfir2d(image, filt, filt.reshape(1, -1)) + + def test_sepfir2d_invalid_image(self): + filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0]) + image = np.random.rand(8, 8) + + # Image must be 2 dimensional + with pytest.raises(ValueError, match="object too deep"): + signal.sepfir2d(image.reshape(4, 4, 4), filt, filt) + + with pytest.raises(ValueError, match="object of too small depth"): + signal.sepfir2d(image[0], filt, filt) + + @pytest.mark.parametrize('dtyp', + [np.uint8, int, np.float32, float, np.complex64, complex] + ) + def test_simple(self, dtyp): + # test values on a paper-and-pencil example + a = np.array([[1, 2, 3, 3, 2, 1], + [1, 2, 3, 3, 2, 1], + [1, 2, 3, 3, 2, 1], + [1, 2, 3, 3, 2, 1]], dtype=dtyp) + h1 = [0.5, 1, 0.5] + h2 = [1] + result = signal.sepfir2d(a, h1, h2) + dt = sepfir_dtype_map[dtyp] + expected = np.asarray([[2.5, 4. , 5.5, 5.5, 4. , 2.5], + [2.5, 4. , 5.5, 5.5, 4. , 2.5], + [2.5, 4. , 5.5, 5.5, 4. , 2.5], + [2.5, 4. , 5.5, 5.5, 4. , 2.5]], dtype=dt) + xp_assert_close(result, expected, atol=1e-16) + + result = signal.sepfir2d(a, h2, h1) + expected = np.asarray([[2., 4., 6., 6., 4., 2.], + [2., 4., 6., 6., 4., 2.], + [2., 4., 6., 6., 4., 2.], + [2., 4., 6., 6., 4., 2.]], dtype=dt) + xp_assert_close(result, expected, atol=1e-16) + + @pytest.mark.parametrize('dtyp', + [np.uint8, int, np.float32, float, np.complex64, complex] + ) + def test_strided(self, dtyp): + a = np.array([[1, 2, 3, 3, 2, 1, 1, 2, 3], + [1, 2, 3, 3, 2, 1, 1, 2, 3], + [1, 2, 3, 3, 2, 1, 1, 2, 3], + [1, 2, 3, 3, 2, 1, 1, 2, 3]]) + h1, h2 = [0.5, 1, 0.5], [1] + result_strided = signal.sepfir2d(a[:, ::2], h1, h2) + result_contig = signal.sepfir2d(a[:, ::2].copy(), h1, h2) + xp_assert_close(result_strided, result_contig, atol=1e-15) + assert result_strided.dtype == result_contig.dtype + + @pytest.mark.xfail(reason="XXX: filt.size > image.shape: flaky") + def test_sepfir2d_strided_2(self): + # XXX: this test is flaky: fails on some reruns, with + # result[0, 1] and result[1, 1] being ~1e+224. + np.random.seed(1234) + filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0, 3.0, 2.0]) + image = np.random.rand(4, 4) + + expected = np.asarray([[36.018162, 30.239061, 38.71187 , 43.878183], + [38.180999, 35.824583, 43.525247, 43.874945], + [43.269533, 40.834018, 46.757772, 44.276423], + [49.120928, 39.681844, 43.596067, 45.085854]]) + xp_assert_close(signal.sepfir2d(image, filt, filt[::3]), expected) + + @pytest.mark.xfail(reason="XXX: flaky. pointers OOB on some platforms") + @pytest.mark.parametrize('dtyp', + [np.uint8, int, np.float32, float, np.complex64, complex] + ) + def test_sepfir2d_strided_3(self, dtyp): + # NB: 'image' and 'filt' dtypes match here. Otherwise we can run into + # unsafe casting errors for many combinations. Historically, dtype handling + # in `sepfir2d` is a tad baroque; fixing it is an enhancement. + filt = np.array([1, 2, 4, 2, 1, 3, 2], dtype=dtyp) + image = np.asarray([[0, 3, 0, 1, 2], + [2, 2, 3, 3, 3], + [0, 1, 3, 0, 3], + [2, 3, 0, 1, 3], + [3, 3, 2, 1, 2]], dtype=dtyp) + + expected = [[123., 101., 91., 136., 127.], + [133., 125., 126., 152., 160.], + [136., 137., 150., 162., 177.], + [133., 124., 132., 148., 147.], + [173., 158., 152., 164., 141.]] + expected = np.asarray(expected) + result = signal.sepfir2d(image, filt, filt[::3]) + xp_assert_close(result, expected, atol=1e-15) + assert result.dtype == sepfir_dtype_map[dtyp] + + expected = [[22., 35., 41., 31., 47.], + [27., 39., 48., 47., 55.], + [33., 42., 49., 53., 59.], + [39., 44., 41., 36., 48.], + [67., 62., 47., 34., 46.]] + expected = np.asarray(expected) + result = signal.sepfir2d(image, filt[::3], filt[::3]) + xp_assert_close(result, expected, atol=1e-15) + assert result.dtype == sepfir_dtype_map[dtyp] + + +def test_cspline2d(): + np.random.seed(181819142) + image = np.random.rand(71, 73) + signal.cspline2d(image, 8.0) + + +def test_qspline2d(): + np.random.seed(181819143) + image = np.random.rand(71, 73) + signal.qspline2d(image) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_cont2discrete.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_cont2discrete.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4008afd4728acb5b63a6626440b214f2d90f6f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_cont2discrete.py @@ -0,0 +1,417 @@ +import numpy as np +from scipy._lib._array_api import ( + assert_array_almost_equal, assert_almost_equal, xp_assert_close +) + +import pytest +from scipy.signal import cont2discrete as c2d +from scipy.signal import dlsim, ss2tf, ss2zpk, lsim, lti +from scipy.signal import tf2ss, impulse, dimpulse, step, dstep + +# Author: Jeffrey Armstrong +# March 29, 2011 + + +class TestC2D: + @pytest.mark.thread_unsafe # due to Cython fused types, see cython#6506 + def test_zoh(self): + ac = np.eye(2, dtype=np.float64) + bc = np.full((2, 1), 0.5, dtype=np.float64) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + ad_truth = 1.648721270700128 * np.eye(2) + bd_truth = np.full((2, 1), 0.324360635350064) + # c and d in discrete should be equal to their continuous counterparts + dt_requested = 0.5 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, method='zoh') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cc, cd) + assert_array_almost_equal(dc, dd) + assert_almost_equal(dt_requested, dt) + + def test_foh(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + # True values are verified with Matlab + ad_truth = 1.648721270700128 * np.eye(2) + bd_truth = np.full((2, 1), 0.420839287058789) + cd_truth = cc + dd_truth = np.array([[0.260262223725224], + [0.297442541400256], + [-0.144098411624840]]) + dt_requested = 0.5 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, method='foh') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_impulse(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [0.0]]) + + # True values are verified with Matlab + ad_truth = 1.648721270700128 * np.eye(2) + bd_truth = np.full((2, 1), 0.412180317675032) + cd_truth = cc + dd_truth = np.array([[0.4375], [0.5], [0.3125]]) + dt_requested = 0.5 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='impulse') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_gbt(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + alpha = 1.0 / 3.0 + + ad_truth = 1.6 * np.eye(2) + bd_truth = np.full((2, 1), 0.3) + cd_truth = np.array([[0.9, 1.2], + [1.2, 1.2], + [1.2, 0.3]]) + dd_truth = np.array([[0.175], + [0.2], + [-0.205]]) + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='gbt', alpha=alpha) + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + + def test_euler(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + + ad_truth = 1.5 * np.eye(2) + bd_truth = np.full((2, 1), 0.25) + cd_truth = np.array([[0.75, 1.0], + [1.0, 1.0], + [1.0, 0.25]]) + dd_truth = dc + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='euler') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_backward_diff(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + + ad_truth = 2.0 * np.eye(2) + bd_truth = np.full((2, 1), 0.5) + cd_truth = np.array([[1.5, 2.0], + [2.0, 2.0], + [2.0, 0.5]]) + dd_truth = np.array([[0.875], + [1.0], + [0.295]]) + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='backward_diff') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + + def test_bilinear(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + + ad_truth = (5.0 / 3.0) * np.eye(2) + bd_truth = np.full((2, 1), 1.0 / 3.0) + cd_truth = np.array([[1.0, 4.0 / 3.0], + [4.0 / 3.0, 4.0 / 3.0], + [4.0 / 3.0, 1.0 / 3.0]]) + dd_truth = np.array([[0.291666666666667], + [1.0 / 3.0], + [-0.121666666666667]]) + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='bilinear') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + # Same continuous system again, but change sampling rate + + ad_truth = 1.4 * np.eye(2) + bd_truth = np.full((2, 1), 0.2) + cd_truth = np.array([[0.9, 1.2], [1.2, 1.2], [1.2, 0.3]]) + dd_truth = np.array([[0.175], [0.2], [-0.205]]) + + dt_requested = 1.0 / 3.0 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='bilinear') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_transferfunction(self): + numc = np.array([0.25, 0.25, 0.5]) + denc = np.array([0.75, 0.75, 1.0]) + + numd = np.array([[1.0 / 3.0, -0.427419169438754, 0.221654141101125]]) + dend = np.array([1.0, -1.351394049721225, 0.606530659712634]) + + dt_requested = 0.5 + + num, den, dt = c2d((numc, denc), dt_requested, method='zoh') + + assert_array_almost_equal(numd, num) + assert_array_almost_equal(dend, den) + assert_almost_equal(dt_requested, dt) + + def test_zerospolesgain(self): + zeros_c = np.array([0.5, -0.5]) + poles_c = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)]) + k_c = 1.0 + + zeros_d = [1.23371727305860, 0.735356894461267] + polls_d = [0.938148335039729 + 0.346233593780536j, + 0.938148335039729 - 0.346233593780536j] + k_d = 1.0 + + dt_requested = 0.5 + + zeros, poles, k, dt = c2d((zeros_c, poles_c, k_c), dt_requested, + method='zoh') + + assert_array_almost_equal(zeros_d, zeros) + assert_array_almost_equal(polls_d, poles) + assert_almost_equal(k_d, k) + assert_almost_equal(dt_requested, dt) + + def test_gbt_with_sio_tf_and_zpk(self): + """Test method='gbt' with alpha=0.25 for tf and zpk cases.""" + # State space coefficients for the continuous SIO system. + A = -1.0 + B = 1.0 + C = 1.0 + D = 0.5 + + # The continuous transfer function coefficients. + cnum, cden = ss2tf(A, B, C, D) + + # Continuous zpk representation + cz, cp, ck = ss2zpk(A, B, C, D) + + h = 1.0 + alpha = 0.25 + + # Explicit formulas, in the scalar case. + Ad = (1 + (1 - alpha) * h * A) / (1 - alpha * h * A) + Bd = h * B / (1 - alpha * h * A) + Cd = C / (1 - alpha * h * A) + Dd = D + alpha * C * Bd + + # Convert the explicit solution to tf + dnum, dden = ss2tf(Ad, Bd, Cd, Dd) + + # Compute the discrete tf using cont2discrete. + c2dnum, c2dden, dt = c2d((cnum, cden), h, method='gbt', alpha=alpha) + + xp_assert_close(dnum, c2dnum) + xp_assert_close(dden, c2dden) + + # Convert explicit solution to zpk. + dz, dp, dk = ss2zpk(Ad, Bd, Cd, Dd) + + # Compute the discrete zpk using cont2discrete. + c2dz, c2dp, c2dk, dt = c2d((cz, cp, ck), h, method='gbt', alpha=alpha) + + xp_assert_close(dz, c2dz) + xp_assert_close(dp, c2dp) + xp_assert_close(dk, c2dk) + + def test_discrete_approx(self): + """ + Test that the solution to the discrete approximation of a continuous + system actually approximates the solution to the continuous system. + This is an indirect test of the correctness of the implementation + of cont2discrete. + """ + + def u(t): + return np.sin(2.5 * t) + + a = np.array([[-0.01]]) + b = np.array([[1.0]]) + c = np.array([[1.0]]) + d = np.array([[0.2]]) + x0 = 1.0 + + t = np.linspace(0, 10.0, 101) + dt = t[1] - t[0] + u1 = u(t) + + # Use lsim to compute the solution to the continuous system. + t, yout, xout = lsim((a, b, c, d), T=t, U=u1, X0=x0) + + # Convert the continuous system to a discrete approximation. + dsys = c2d((a, b, c, d), dt, method='bilinear') + + # Use dlsim with the pairwise averaged input to compute the output + # of the discrete system. + u2 = 0.5 * (u1[:-1] + u1[1:]) + t2 = t[:-1] + td2, yd2, xd2 = dlsim(dsys, u=u2.reshape(-1, 1), t=t2, x0=x0) + + # ymid is the average of consecutive terms of the "exact" output + # computed by lsim2. This is what the discrete approximation + # actually approximates. + ymid = 0.5 * (yout[:-1] + yout[1:]) + + xp_assert_close(yd2.ravel(), ymid, rtol=1e-4) + + def test_simo_tf(self): + # See gh-5753 + tf = ([[1, 0], [1, 1]], [1, 1]) + num, den, dt = c2d(tf, 0.01) + + assert dt == 0.01 # sanity check + xp_assert_close(den, [1, -0.990404983], rtol=1e-3) + xp_assert_close(num, [[1, -1], [1, -0.99004983]], rtol=1e-3) + + def test_multioutput(self): + ts = 0.01 # time step + + tf = ([[1, -3], [1, 5]], [1, 1]) + num, den, dt = c2d(tf, ts) + + tf1 = (tf[0][0], tf[1]) + num1, den1, dt1 = c2d(tf1, ts) + + tf2 = (tf[0][1], tf[1]) + num2, den2, dt2 = c2d(tf2, ts) + + # Sanity checks + assert dt == dt1 + assert dt == dt2 + + # Check that we get the same results + xp_assert_close(num, np.vstack((num1, num2)), rtol=1e-13) + + # Single input, so the denominator should + # not be multidimensional like the numerator + xp_assert_close(den, den1, rtol=1e-13) + xp_assert_close(den, den2, rtol=1e-13) + +class TestC2dLti: + def test_c2d_ss(self): + # StateSpace + A = np.array([[-0.3, 0.1], [0.2, -0.7]]) + B = np.array([[0], [1]]) + C = np.array([[1, 0]]) + D = 0 + + A_res = np.array([[0.985136404135682, 0.004876671474795], + [0.009753342949590, 0.965629718236502]]) + B_res = np.array([[0.000122937599964], [0.049135527547844]]) + + sys_ssc = lti(A, B, C, D) + sys_ssd = sys_ssc.to_discrete(0.05) + + xp_assert_close(sys_ssd.A, A_res) + xp_assert_close(sys_ssd.B, B_res) + xp_assert_close(sys_ssd.C, C) + xp_assert_close(sys_ssd.D, np.zeros_like(sys_ssd.D)) + + def test_c2d_tf(self): + + sys = lti([0.5, 0.3], [1.0, 0.4]) + sys = sys.to_discrete(0.005) + + # Matlab results + num_res = np.array([0.5, -0.485149004980066]) + den_res = np.array([1.0, -0.980198673306755]) + + # Somehow a lot of numerical errors + xp_assert_close(sys.den, den_res, atol=0.02) + xp_assert_close(sys.num, num_res, atol=0.02) + + +class TestC2dInvariants: + # Some test cases for checking the invariances. + # Array of triplets: (system, sample time, number of samples) + cases = [ + (tf2ss([1, 1], [1, 1.5, 1]), 0.25, 10), + (tf2ss([1, 2], [1, 1.5, 3, 1]), 0.5, 10), + (tf2ss(0.1, [1, 1, 2, 1]), 0.5, 10), + ] + + # Check that systems discretized with the impulse-invariant + # method really hold the invariant + @pytest.mark.parametrize("sys,sample_time,samples_number", cases) + def test_impulse_invariant(self, sys, sample_time, samples_number): + time = np.arange(samples_number) * sample_time + _, yout_cont = impulse(sys, T=time) + _, yout_disc = dimpulse(c2d(sys, sample_time, method='impulse'), + n=len(time)) + xp_assert_close(sample_time * yout_cont.ravel(), yout_disc[0].ravel()) + + # Step invariant should hold for ZOH discretized systems + @pytest.mark.parametrize("sys,sample_time,samples_number", cases) + def test_step_invariant(self, sys, sample_time, samples_number): + time = np.arange(samples_number) * sample_time + _, yout_cont = step(sys, T=time) + _, yout_disc = dstep(c2d(sys, sample_time, method='zoh'), n=len(time)) + xp_assert_close(yout_cont.ravel(), yout_disc[0].ravel()) + + # Linear invariant should hold for FOH discretized systems + @pytest.mark.parametrize("sys,sample_time,samples_number", cases) + def test_linear_invariant(self, sys, sample_time, samples_number): + time = np.arange(samples_number) * sample_time + _, yout_cont, _ = lsim(sys, T=time, U=time) + _, yout_disc, _ = dlsim(c2d(sys, sample_time, method='foh'), u=time) + xp_assert_close(yout_cont.ravel(), yout_disc.ravel()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_czt.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_czt.py new file mode 100644 index 0000000000000000000000000000000000000000..35087d99fec5057131f0735d43e0faa33a74ef82 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_czt.py @@ -0,0 +1,221 @@ +# This program is public domain +# Authors: Paul Kienzle, Nadav Horesh +''' +A unit test module for czt.py +''' +import pytest +from scipy._lib._array_api import xp_assert_close +from scipy.fft import fft +from scipy.signal import (czt, zoom_fft, czt_points, CZT, ZoomFFT) +import numpy as np + + +def check_czt(x): + # Check that czt is the equivalent of normal fft + y = fft(x) + y1 = czt(x) + xp_assert_close(y1, y, rtol=1e-13) + + # Check that interpolated czt is the equivalent of normal fft + y = fft(x, 100*len(x)) + y1 = czt(x, 100*len(x)) + xp_assert_close(y1, y, rtol=1e-12) + + +def check_zoom_fft(x): + # Check that zoom_fft is the equivalent of normal fft + y = fft(x) + y1 = zoom_fft(x, [0, 2-2./len(y)], endpoint=True) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + y1 = zoom_fft(x, [0, 2]) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + + # Test fn scalar + y1 = zoom_fft(x, 2-2./len(y), endpoint=True) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + y1 = zoom_fft(x, 2) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + + # Check that zoom_fft with oversampling is equivalent to zero padding + over = 10 + yover = fft(x, over*len(x)) + y2 = zoom_fft(x, [0, 2-2./len(yover)], m=len(yover), endpoint=True) + xp_assert_close(y2, yover, rtol=1e-12, atol=1e-10) + y2 = zoom_fft(x, [0, 2], m=len(yover)) + xp_assert_close(y2, yover, rtol=1e-12, atol=1e-10) + + # Check that zoom_fft works on a subrange + w = np.linspace(0, 2-2./len(x), len(x)) + f1, f2 = w[3], w[6] + y3 = zoom_fft(x, [f1, f2], m=3*over+1, endpoint=True) + idx3 = slice(3*over, 6*over+1) + xp_assert_close(y3, yover[idx3], rtol=1e-13) + + +def test_1D(): + # Test of 1D version of the transforms + + rng = np.random.RandomState(0) # Deterministic randomness + + # Random signals + lengths = rng.randint(8, 200, 20) + np.append(lengths, 1) + for length in lengths: + x = rng.random(length) + check_zoom_fft(x) + check_czt(x) + + # Gauss + t = np.linspace(-2, 2, 128) + x = np.exp(-t**2/0.01) + check_zoom_fft(x) + + # Linear + x = [1, 2, 3, 4, 5, 6, 7] + check_zoom_fft(x) + + # Check near powers of two + check_zoom_fft(range(126-31)) + check_zoom_fft(range(127-31)) + check_zoom_fft(range(128-31)) + check_zoom_fft(range(129-31)) + check_zoom_fft(range(130-31)) + + # Check transform on n-D array input + x = np.reshape(np.arange(3*2*28), (3, 2, 28)) + y1 = zoom_fft(x, [0, 2-2./28]) + y2 = zoom_fft(x[2, 0, :], [0, 2-2./28]) + xp_assert_close(y1[2, 0], y2, rtol=1e-13, atol=1e-12) + + y1 = zoom_fft(x, [0, 2], endpoint=False) + y2 = zoom_fft(x[2, 0, :], [0, 2], endpoint=False) + xp_assert_close(y1[2, 0], y2, rtol=1e-13, atol=1e-12) + + # Random (not a test condition) + x = rng.rand(101) + check_zoom_fft(x) + + # Spikes + t = np.linspace(0, 1, 128) + x = np.sin(2*np.pi*t*5)+np.sin(2*np.pi*t*13) + check_zoom_fft(x) + + # Sines + x = np.zeros(100, dtype=complex) + x[[1, 5, 21]] = 1 + check_zoom_fft(x) + + # Sines plus complex component + x += 1j*np.linspace(0, 0.5, x.shape[0]) + check_zoom_fft(x) + + +def test_large_prime_lengths(): + rng = np.random.RandomState(0) # Deterministic randomness + for N in (101, 1009, 10007): + x = rng.rand(N) + y = fft(x) + y1 = czt(x) + xp_assert_close(y, y1, rtol=1e-12) + + +@pytest.mark.slow +def test_czt_vs_fft(): + rng = np.random.RandomState(123) # Deterministic randomness + random_lengths = rng.exponential(100000, size=10).astype('int') + for n in random_lengths: + a = rng.randn(n) + xp_assert_close(czt(a), fft(a), rtol=1e-11) + + +def test_empty_input(): + with pytest.raises(ValueError, match='Invalid number of CZT'): + czt([]) + with pytest.raises(ValueError, match='Invalid number of CZT'): + zoom_fft([], 0.5) + + +def test_0_rank_input(): + with pytest.raises(IndexError, match='tuple index out of range'): + czt(5) + with pytest.raises(IndexError, match='tuple index out of range'): + zoom_fft(5, 0.5) + + +@pytest.mark.parametrize('impulse', ([0, 0, 1], [0, 0, 1, 0, 0], + np.concatenate((np.array([0, 0, 1]), + np.zeros(100))))) +@pytest.mark.parametrize('m', (1, 3, 5, 8, 101, 1021)) +@pytest.mark.parametrize('a', (1, 2, 0.5, 1.1)) +# Step that tests away from the unit circle, but not so far it explodes from +# numerical error +@pytest.mark.parametrize('w', (None, 0.98534 + 0.17055j)) +def test_czt_math(impulse, m, w, a): + # z-transform of an impulse is 1 everywhere + xp_assert_close(czt(impulse[2:], m=m, w=w, a=a), + np.ones(m, dtype=np.complex128), rtol=1e-10) + + # z-transform of a delayed impulse is z**-1 + xp_assert_close(czt(impulse[1:], m=m, w=w, a=a), + czt_points(m=m, w=w, a=a)**-1, rtol=1e-10) + + # z-transform of a 2-delayed impulse is z**-2 + xp_assert_close(czt(impulse, m=m, w=w, a=a), + czt_points(m=m, w=w, a=a)**-2, rtol=1e-10) + + +def test_int_args(): + # Integer argument `a` was producing all 0s + xp_assert_close(abs(czt([0, 1], m=10, a=2)), 0.5*np.ones(10), rtol=1e-15) + xp_assert_close(czt_points(11, w=2), + 1/(2**np.arange(11, dtype=np.complex128)), rtol=1e-30) + + +def test_czt_points(): + for N in (1, 2, 3, 8, 11, 100, 101, 10007): + xp_assert_close(czt_points(N), np.exp(2j*np.pi*np.arange(N)/N), + rtol=1e-30) + + xp_assert_close(czt_points(7, w=1), np.ones(7, dtype=np.complex128), rtol=1e-30) + xp_assert_close(czt_points(11, w=2.), + 1/(2**np.arange(11, dtype=np.complex128)), rtol=1e-30) + + func = CZT(12, m=11, w=2., a=1) + xp_assert_close(func.points(), 1/(2**np.arange(11)), rtol=1e-30) + + +@pytest.mark.parametrize('cls, args', [(CZT, (100,)), (ZoomFFT, (100, 0.2))]) +def test_CZT_size_mismatch(cls, args): + # Data size doesn't match function's expected size + myfunc = cls(*args) + with pytest.raises(ValueError, match='CZT defined for'): + myfunc(np.arange(5)) + + +def test_invalid_range(): + with pytest.raises(ValueError, match='2-length sequence'): + ZoomFFT(100, [1, 2, 3]) + + +@pytest.mark.parametrize('m', [0, -11, 5.5, 4.0]) +def test_czt_points_errors(m): + # Invalid number of points + with pytest.raises(ValueError, match='Invalid number of CZT'): + czt_points(m) + + +@pytest.mark.parametrize('size', [0, -5, 3.5, 4.0]) +def test_nonsense_size(size): + # Numpy and Scipy fft() give ValueError for 0 output size, so we do, too + with pytest.raises(ValueError, match='Invalid number of CZT'): + CZT(size, 3) + with pytest.raises(ValueError, match='Invalid number of CZT'): + ZoomFFT(size, 0.2, 3) + with pytest.raises(ValueError, match='Invalid number of CZT'): + CZT(3, size) + with pytest.raises(ValueError, match='Invalid number of CZT'): + ZoomFFT(3, 0.2, size) + with pytest.raises(ValueError, match='Invalid number of CZT'): + czt([1, 2, 3], size) + with pytest.raises(ValueError, match='Invalid number of CZT'): + zoom_fft([1, 2, 3], 0.2, size) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..872541543ba485f3e8a17735bee471875f92fd05 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py @@ -0,0 +1,599 @@ +# Author: Jeffrey Armstrong +# April 4, 2011 + +import numpy as np +from numpy.testing import suppress_warnings +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + assert_array_almost_equal, assert_almost_equal, xp_assert_close, xp_assert_equal, +) + +from scipy.signal import (dlsim, dstep, dimpulse, tf2zpk, lti, dlti, + StateSpace, TransferFunction, ZerosPolesGain, + dfreqresp, dbode, BadCoefficients) + + +class TestDLTI: + + def test_dlsim(self): + + a = np.asarray([[0.9, 0.1], [-0.2, 0.9]]) + b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]]) + c = np.asarray([[0.1, 0.3]]) + d = np.asarray([[0.0, -0.1, 0.0]]) + dt = 0.5 + + # Create an input matrix with inputs down the columns (3 cols) and its + # respective time input vector + u = np.hstack((np.linspace(0, 4.0, num=5)[:, np.newaxis], + np.full((5, 1), 0.01), + np.full((5, 1), -0.002))) + t_in = np.linspace(0, 2.0, num=5) + + # Define the known result + yout_truth = np.array([[-0.001, + -0.00073, + 0.039446, + 0.0915387, + 0.13195948]]).T + xout_truth = np.asarray([[0, 0], + [0.0012, 0.0005], + [0.40233, 0.00071], + [1.163368, -0.079327], + [2.2402985, -0.3035679]]) + + tout, yout, xout = dlsim((a, b, c, d, dt), u, t_in) + + assert_array_almost_equal(yout_truth, yout) + assert_array_almost_equal(xout_truth, xout) + assert_array_almost_equal(t_in, tout) + + # Make sure input with single-dimension doesn't raise error + dlsim((1, 2, 3), 4) + + # Interpolated control - inputs should have different time steps + # than the discrete model uses internally + u_sparse = u[[0, 4], :] + t_sparse = np.asarray([0.0, 2.0]) + + tout, yout, xout = dlsim((a, b, c, d, dt), u_sparse, t_sparse) + + assert_array_almost_equal(yout_truth, yout) + assert_array_almost_equal(xout_truth, xout) + assert len(tout) == len(yout) + + # Transfer functions (assume dt = 0.5) + num = np.asarray([1.0, -0.1]) + den = np.asarray([0.3, 1.0, 0.2]) + yout_truth = np.array([[0.0, + 0.0, + 3.33333333333333, + -4.77777777777778, + 23.0370370370370]]).T + + # Assume use of the first column of the control input built earlier + tout, yout = dlsim((num, den, 0.5), u[:, 0], t_in) + + assert_array_almost_equal(yout, yout_truth) + assert_array_almost_equal(t_in, tout) + + # Retest the same with a 1-D input vector + uflat = np.asarray(u[:, 0]) + uflat = uflat.reshape((5,)) + tout, yout = dlsim((num, den, 0.5), uflat, t_in) + + assert_array_almost_equal(yout, yout_truth) + assert_array_almost_equal(t_in, tout) + + # zeros-poles-gain representation + zd = np.array([0.5, -0.5]) + pd = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)]) + k = 1.0 + yout_truth = np.array([[0.0, 1.0, 2.0, 2.25, 2.5]]).T + + tout, yout = dlsim((zd, pd, k, 0.5), u[:, 0], t_in) + + assert_array_almost_equal(yout, yout_truth) + assert_array_almost_equal(t_in, tout) + + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dlsim, system, u) + + def test_dstep(self): + + a = np.asarray([[0.9, 0.1], [-0.2, 0.9]]) + b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]]) + c = np.asarray([[0.1, 0.3]]) + d = np.asarray([[0.0, -0.1, 0.0]]) + dt = 0.5 + + # Because b.shape[1] == 3, dstep should result in a tuple of three + # result vectors + yout_step_truth = (np.asarray([0.0, 0.04, 0.052, 0.0404, 0.00956, + -0.036324, -0.093318, -0.15782348, + -0.226628324, -0.2969374948]), + np.asarray([-0.1, -0.075, -0.058, -0.04815, + -0.04453, -0.0461895, -0.0521812, + -0.061588875, -0.073549579, + -0.08727047595]), + np.asarray([0.0, -0.01, -0.013, -0.0101, -0.00239, + 0.009081, 0.0233295, 0.03945587, + 0.056657081, 0.0742343737])) + + tout, yout = dstep((a, b, c, d, dt), n=10) + + assert len(yout) == 3 + + for i in range(0, len(yout)): + assert yout[i].shape[0] == 10 + assert_array_almost_equal(yout[i].flatten(), yout_step_truth[i]) + + # Check that the other two inputs (tf, zpk) will work as well + tfin = ([1.0], [1.0, 1.0], 0.5) + yout_tfstep = np.asarray([0.0, 1.0, 0.0]) + tout, yout = dstep(tfin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfstep) + + zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,) + tout, yout = dstep(zpkin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfstep) + + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dstep, system) + + def test_dimpulse(self): + + a = np.asarray([[0.9, 0.1], [-0.2, 0.9]]) + b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]]) + c = np.asarray([[0.1, 0.3]]) + d = np.asarray([[0.0, -0.1, 0.0]]) + dt = 0.5 + + # Because b.shape[1] == 3, dimpulse should result in a tuple of three + # result vectors + yout_imp_truth = (np.asarray([0.0, 0.04, 0.012, -0.0116, -0.03084, + -0.045884, -0.056994, -0.06450548, + -0.068804844, -0.0703091708]), + np.asarray([-0.1, 0.025, 0.017, 0.00985, 0.00362, + -0.0016595, -0.0059917, -0.009407675, + -0.011960704, -0.01372089695]), + np.asarray([0.0, -0.01, -0.003, 0.0029, 0.00771, + 0.011471, 0.0142485, 0.01612637, + 0.017201211, 0.0175772927])) + + tout, yout = dimpulse((a, b, c, d, dt), n=10) + + assert len(yout) == 3 + + for i in range(0, len(yout)): + assert yout[i].shape[0] == 10 + assert_array_almost_equal(yout[i].flatten(), yout_imp_truth[i]) + + # Check that the other two inputs (tf, zpk) will work as well + tfin = ([1.0], [1.0, 1.0], 0.5) + yout_tfimpulse = np.asarray([0.0, 1.0, -1.0]) + tout, yout = dimpulse(tfin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse) + + zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,) + tout, yout = dimpulse(zpkin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse) + + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dimpulse, system) + + def test_dlsim_trivial(self): + a = np.array([[0.0]]) + b = np.array([[0.0]]) + c = np.array([[0.0]]) + d = np.array([[0.0]]) + n = 5 + u = np.zeros(n).reshape(-1, 1) + tout, yout, xout = dlsim((a, b, c, d, 1), u) + xp_assert_equal(tout, np.arange(float(n))) + xp_assert_equal(yout, np.zeros((n, 1))) + xp_assert_equal(xout, np.zeros((n, 1))) + + def test_dlsim_simple1d(self): + a = np.array([[0.5]]) + b = np.array([[0.0]]) + c = np.array([[1.0]]) + d = np.array([[0.0]]) + n = 5 + u = np.zeros(n).reshape(-1, 1) + tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1) + xp_assert_equal(tout, np.arange(float(n))) + expected = (0.5 ** np.arange(float(n))).reshape(-1, 1) + xp_assert_equal(yout, expected) + xp_assert_equal(xout, expected) + + def test_dlsim_simple2d(self): + lambda1 = 0.5 + lambda2 = 0.25 + a = np.array([[lambda1, 0.0], + [0.0, lambda2]]) + b = np.array([[0.0], + [0.0]]) + c = np.array([[1.0, 0.0], + [0.0, 1.0]]) + d = np.array([[0.0], + [0.0]]) + n = 5 + u = np.zeros(n).reshape(-1, 1) + tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1) + xp_assert_equal(tout, np.arange(float(n))) + # The analytical solution: + expected = (np.array([lambda1, lambda2]) ** + np.arange(float(n)).reshape(-1, 1)) + xp_assert_equal(yout, expected) + xp_assert_equal(xout, expected) + + def test_more_step_and_impulse(self): + lambda1 = 0.5 + lambda2 = 0.75 + a = np.array([[lambda1, 0.0], + [0.0, lambda2]]) + b = np.array([[1.0, 0.0], + [0.0, 1.0]]) + c = np.array([[1.0, 1.0]]) + d = np.array([[0.0, 0.0]]) + + n = 10 + + # Check a step response. + ts, ys = dstep((a, b, c, d, 1), n=n) + + # Create the exact step response. + stp0 = (1.0 / (1 - lambda1)) * (1.0 - lambda1 ** np.arange(n)) + stp1 = (1.0 / (1 - lambda2)) * (1.0 - lambda2 ** np.arange(n)) + + xp_assert_close(ys[0][:, 0], stp0) + xp_assert_close(ys[1][:, 0], stp1) + + # Check an impulse response with an initial condition. + x0 = np.array([1.0, 1.0]) + ti, yi = dimpulse((a, b, c, d, 1), n=n, x0=x0) + + # Create the exact impulse response. + imp = (np.array([lambda1, lambda2]) ** + np.arange(-1, n + 1).reshape(-1, 1)) + imp[0, :] = 0.0 + # Analytical solution to impulse response + y0 = imp[:n, 0] + np.dot(imp[1:n + 1, :], x0) + y1 = imp[:n, 1] + np.dot(imp[1:n + 1, :], x0) + + xp_assert_close(yi[0][:, 0], y0) + xp_assert_close(yi[1][:, 0], y1) + + # Check that dt=0.1, n=3 gives 3 time values. + system = ([1.0], [1.0, -0.5], 0.1) + t, (y,) = dstep(system, n=3) + xp_assert_close(t, [0, 0.1, 0.2]) + xp_assert_equal(y.T, [[0, 1.0, 1.5]]) + t, (y,) = dimpulse(system, n=3) + xp_assert_close(t, [0, 0.1, 0.2]) + xp_assert_equal(y.T, [[0, 1, 0.5]]) + + +class TestDlti: + def test_dlti_instantiation(self): + # Test that lti can be instantiated. + + dt = 0.05 + # TransferFunction + s = dlti([1], [-1], dt=dt) + assert isinstance(s, TransferFunction) + assert isinstance(s, dlti) + assert not isinstance(s, lti) + assert s.dt == dt + + # ZerosPolesGain + s = dlti(np.array([]), np.array([-1]), 1, dt=dt) + assert isinstance(s, ZerosPolesGain) + assert isinstance(s, dlti) + assert not isinstance(s, lti) + assert s.dt == dt + + # StateSpace + s = dlti([1], [-1], 1, 3, dt=dt) + assert isinstance(s, StateSpace) + assert isinstance(s, dlti) + assert not isinstance(s, lti) + assert s.dt == dt + + # Number of inputs + assert_raises(ValueError, dlti, 1) + assert_raises(ValueError, dlti, 1, 1, 1, 1, 1) + + +class TestStateSpaceDisc: + def test_initialization(self): + # Check that all initializations work + dt = 0.05 + StateSpace(1, 1, 1, 1, dt=dt) + StateSpace([1], [2], [3], [4], dt=dt) + StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]), + np.array([[1, 0]]), np.array([[0]]), dt=dt) + StateSpace(1, 1, 1, 1, dt=True) + + def test_conversion(self): + # Check the conversion functions + s = StateSpace(1, 2, 3, 4, dt=0.05) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert StateSpace(s) is not s + assert s.to_ss() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_tf() and to_zpk() + + # Getters + s = StateSpace(1, 1, 1, 1, dt=0.05) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + + +class TestTransferFunction: + def test_initialization(self): + # Check that all initializations work + dt = 0.05 + TransferFunction(1, 1, dt=dt) + TransferFunction([1], [2], dt=dt) + TransferFunction(np.array([1]), np.array([2]), dt=dt) + TransferFunction(1, 1, dt=True) + + def test_conversion(self): + # Check the conversion functions + s = TransferFunction([1, 0], [1, -1], dt=0.05) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert TransferFunction(s) is not s + assert s.to_tf() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_ss() and to_zpk() + + # Getters + s = TransferFunction([1, 0], [1, -1], dt=0.05) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + + +class TestZerosPolesGain: + def test_initialization(self): + # Check that all initializations work + dt = 0.05 + ZerosPolesGain(1, 1, 1, dt=dt) + ZerosPolesGain([1], [2], 1, dt=dt) + ZerosPolesGain(np.array([1]), np.array([2]), 1, dt=dt) + ZerosPolesGain(1, 1, 1, dt=True) + + def test_conversion(self): + # Check the conversion functions + s = ZerosPolesGain(1, 2, 3, dt=0.05) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert ZerosPolesGain(s) is not s + assert s.to_zpk() is not s + + +class Test_dfreqresp: + + def test_manual(self): + # Test dfreqresp() real part calculation (manual sanity check). + # 1st order low-pass filter: H(z) = 1 / (z - 0.2), + system = TransferFunction(1, [1, -0.2], dt=0.1) + w = [0.1, 1, 10] + w, H = dfreqresp(system, w=w) + + # test real + expected_re = [1.2383, 0.4130, -0.7553] + assert_almost_equal(H.real, expected_re, decimal=4) + + # test imag + expected_im = [-0.1555, -1.0214, 0.3955] + assert_almost_equal(H.imag, expected_im, decimal=4) + + def test_auto(self): + # Test dfreqresp() real part calculation. + # 1st order low-pass filter: H(z) = 1 / (z - 0.2), + system = TransferFunction(1, [1, -0.2], dt=0.1) + w = [0.1, 1, 10, 100] + w, H = dfreqresp(system, w=w) + jw = np.exp(w * 1j) + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + + # test real + expected_re = y.real + assert_almost_equal(H.real, expected_re) + + # test imag + expected_im = y.imag + assert_almost_equal(H.imag, expected_im) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(z) = 1 / (z - 0.2), + # Expected range is from 0.01 to 10. + system = TransferFunction(1, [1, -0.2], dt=0.1) + n = 10 + expected_w = np.linspace(0, np.pi, 10, endpoint=False) + w, H = dfreqresp(system, n=n) + assert_almost_equal(w, expected_w) + + def test_pole_one(self): + # Test that freqresp() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = TransferFunction([1], [1, -1], dt=0.1) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, message="divide by zero") + sup.filter(RuntimeWarning, message="invalid value encountered") + w, H = dfreqresp(system, n=2) + assert w[0] == 0. # a fail would give not-a-number + + def test_error(self): + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dfreqresp, system) + + def test_from_state_space(self): + # H(z) = 2 / z^3 - 0.5 * z^2 + + system_TF = dlti([2], [1, -0.5, 0, 0]) + + A = np.array([[0.5, 0, 0], + [1, 0, 0], + [0, 1, 0]]) + B = np.array([[1, 0, 0]]).T + C = np.array([[0, 0, 2]]) + D = 0 + + system_SS = dlti(A, B, C, D) + w = 10.0**np.arange(-3,0,.5) + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + w1, H1 = dfreqresp(system_TF, w=w) + w2, H2 = dfreqresp(system_SS, w=w) + + assert_almost_equal(H1, H2) + + def test_from_zpk(self): + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + system_ZPK = dlti([],[0.2],0.3) + system_TF = dlti(0.3, [1, -0.2]) + w = [0.1, 1, 10, 100] + w1, H1 = dfreqresp(system_ZPK, w=w) + w2, H2 = dfreqresp(system_TF, w=w) + assert_almost_equal(H1, H2) + + +class Test_bode: + + def test_manual(self): + # Test bode() magnitude calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + dt = 0.1 + system = TransferFunction(0.3, [1, -0.2], dt=dt) + w = [0.1, 0.5, 1, np.pi] + w2, mag, phase = dbode(system, w=w) + + # Test mag + expected_mag = [-8.5329, -8.8396, -9.6162, -12.0412] + assert_almost_equal(mag, expected_mag, decimal=4) + + # Test phase + expected_phase = [-7.1575, -35.2814, -67.9809, -180.0000] + assert_almost_equal(phase, expected_phase, decimal=4) + + # Test frequency + xp_assert_equal(np.array(w) / dt, w2) + + def test_auto(self): + # Test bode() magnitude calculation. + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + system = TransferFunction(0.3, [1, -0.2], dt=0.1) + w = np.array([0.1, 0.5, 1, np.pi]) + w2, mag, phase = dbode(system, w=w) + jw = np.exp(w * 1j) + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + + # Test mag + expected_mag = 20.0 * np.log10(abs(y)) + assert_almost_equal(mag, expected_mag) + + # Test phase + expected_phase = np.rad2deg(np.angle(y)) + assert_almost_equal(phase, expected_phase) + + def test_range(self): + # Test that bode() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + dt = 0.1 + system = TransferFunction(0.3, [1, -0.2], dt=0.1) + n = 10 + # Expected range is from 0.01 to 10. + expected_w = np.linspace(0, np.pi, n, endpoint=False) / dt + w, mag, phase = dbode(system, n=n) + assert_almost_equal(w, expected_w) + + def test_pole_one(self): + # Test that freqresp() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = TransferFunction([1], [1, -1], dt=0.1) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, message="divide by zero") + sup.filter(RuntimeWarning, message="invalid value encountered") + w, mag, phase = dbode(system, n=2) + assert w[0] == 0. # a fail would give not-a-number + + def test_imaginary(self): + # bode() should not fail on a system with pure imaginary poles. + # The test passes if bode doesn't raise an exception. + system = TransferFunction([1], [1, 0, 100], dt=0.1) + dbode(system, n=2) + + def test_error(self): + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dbode, system) + + +class TestTransferFunctionZConversion: + """Test private conversions between 'z' and 'z**-1' polynomials.""" + + def test_full(self): + # Numerator and denominator same order + num = np.asarray([2.0, 3, 4]) + den = np.asarray([5.0, 6, 7]) + num2, den2 = TransferFunction._z_to_zinv(num, den) + xp_assert_equal(num, num2) + xp_assert_equal(den, den2) + + num2, den2 = TransferFunction._zinv_to_z(num, den) + xp_assert_equal(num, num2) + xp_assert_equal(den, den2) + + def test_numerator(self): + # Numerator lower order than denominator + num = np.asarray([2.0, 3]) + den = np.asarray([50, 6, 7]) + num2, den2 = TransferFunction._z_to_zinv(num, den) + xp_assert_equal([0.0, 2, 3], num2) + xp_assert_equal(den, den2) + + num2, den2 = TransferFunction._zinv_to_z(num, den) + xp_assert_equal([2.0, 3, 0], num2) + xp_assert_equal(den, den2) + + def test_denominator(self): + # Numerator higher order than denominator + num = np.asarray([2., 3, 4]) + den = np.asarray([5.0, 6]) + num2, den2 = TransferFunction._z_to_zinv(num, den) + xp_assert_equal(num, num2) + xp_assert_equal([0.0, 5, 6], den2) + + num2, den2 = TransferFunction._zinv_to_z(num, den) + xp_assert_equal(num, num2) + xp_assert_equal([5.0, 6, 0], den2) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_filter_design.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..62613b5bb64ec2980dc8a306e7a2a997b5713d2c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_filter_design.py @@ -0,0 +1,4485 @@ +import warnings + +from scipy._lib import _pep440 +import numpy as np +from numpy.testing import ( + assert_array_almost_equal_nulp, assert_warns, suppress_warnings +) +import pytest +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + xp_assert_close, xp_assert_equal, + assert_array_almost_equal, +) + +from numpy import array, spacing, sin, pi, sort, sqrt +from scipy.signal import (argrelextrema, BadCoefficients, bessel, besselap, bilinear, + buttap, butter, buttord, cheb1ap, cheb1ord, cheb2ap, + cheb2ord, cheby1, cheby2, ellip, ellipap, ellipord, + firwin, freqs_zpk, freqs, freqz, freqz_zpk, + gammatone, group_delay, iircomb, iirdesign, iirfilter, + iirnotch, iirpeak, lp2bp, lp2bs, lp2hp, lp2lp, normalize, + medfilt, order_filter, + sos2tf, sos2zpk, sosfreqz, freqz_sos, tf2sos, tf2zpk, zpk2sos, + zpk2tf, bilinear_zpk, lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, + lp2bs_zpk) +from scipy.signal._filter_design import (_cplxreal, _cplxpair, _norm_factor, + _bessel_poly, _bessel_zeros) + +try: + import mpmath +except ImportError: + mpmath = None + + +def mpmath_check(min_ver): + return pytest.mark.skipif( + mpmath is None + or _pep440.parse(mpmath.__version__) < _pep440.Version(min_ver), + reason=f"mpmath version >= {min_ver} required", + ) + + +class TestCplxPair: + + def test_trivial_input(self): + assert _cplxpair([]).size == 0 + assert _cplxpair(1) == 1 + + def test_output_order(self): + xp_assert_close(_cplxpair([1+1j, 1-1j]), [1-1j, 1+1j]) + + a = [1+1j, 1+1j, 1, 1-1j, 1-1j, 2] + b = [1-1j, 1+1j, 1-1j, 1+1j, 1, 2] + xp_assert_close(_cplxpair(a), b) + + # points spaced around the unit circle + z = np.exp(2j*pi*array([4, 3, 5, 2, 6, 1, 0])/7) + z1 = np.copy(z) + np.random.shuffle(z) + xp_assert_close(_cplxpair(z), z1) + np.random.shuffle(z) + xp_assert_close(_cplxpair(z), z1) + np.random.shuffle(z) + xp_assert_close(_cplxpair(z), z1) + + # Should be able to pair up all the conjugates + x = np.random.rand(10000) + 1j * np.random.rand(10000) + y = x.conj() + z = np.random.rand(10000) + x = np.concatenate((x, y, z)) + np.random.shuffle(x) + c = _cplxpair(x) + + # Every other element of head should be conjugates: + xp_assert_close(c[0:20000:2], np.conj(c[1:20000:2])) + # Real parts of head should be in sorted order: + xp_assert_close(c[0:20000:2].real, np.sort(c[0:20000:2].real)) + # Tail should be sorted real numbers: + xp_assert_close(c[20000:], np.sort(c[20000:])) + + def test_real_integer_input(self): + xp_assert_equal(_cplxpair([2, 0, 1]), [0, 1, 2]) + + def test_tolerances(self): + eps = spacing(1) + xp_assert_close(_cplxpair([1j, -1j, 1+1j*eps], tol=2*eps), + [-1j, 1j, 1+1j*eps]) + + # sorting close to 0 + xp_assert_close(_cplxpair([-eps+1j, +eps-1j]), [-1j, +1j]) + xp_assert_close(_cplxpair([+eps+1j, -eps-1j]), [-1j, +1j]) + xp_assert_close(_cplxpair([+1j, -1j]), [-1j, +1j]) + + def test_unmatched_conjugates(self): + # 1+2j is unmatched + assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j]) + + # 1+2j and 1-3j are unmatched + assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j, 1-3j]) + + # 1+3j is unmatched + assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+3j]) + + # Not conjugates + assert_raises(ValueError, _cplxpair, [4+5j, 4+5j]) + assert_raises(ValueError, _cplxpair, [1-7j, 1-7j]) + + # No pairs + assert_raises(ValueError, _cplxpair, [1+3j]) + assert_raises(ValueError, _cplxpair, [1-3j]) + + +class TestCplxReal: + + def test_trivial_input(self): + assert all(x.size == 0 for x in _cplxreal([])) + + x = _cplxreal(1) + assert x[0].size == 0 + xp_assert_equal(x[1], np.asarray([1])) + + + def test_output_order(self): + zc, zr = _cplxreal(np.roots(array([1, 0, 0, 1]))) + xp_assert_close(np.append(zc, zr), [1/2 + 1j*sin(pi/3), -1]) + + eps = spacing(1) + + a = [0+1j, 0-1j, eps + 1j, eps - 1j, -eps + 1j, -eps - 1j, + 1, 4, 2, 3, 0, 0, + 2+3j, 2-3j, + 1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, # sorts out of order + 3+1j, 3+1j, 3+1j, 3-1j, 3-1j, 3-1j, + 2-3j, 2+3j] + zc, zr = _cplxreal(a) + xp_assert_close(zc, [1j, 1j, 1j, 1+1j, 1+2j, 2+3j, 2+3j, 3+1j, 3+1j, + 3+1j]) + xp_assert_close(zr, [0.0, 0, 1, 2, 3, 4]) + + z = array([1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, 1+eps+3j, 1-2*eps-3j, + 0+1j, 0-1j, 2+4j, 2-4j, 2+3j, 2-3j, 3+7j, 3-7j, 4-eps+1j, + 4+eps-2j, 4-1j, 4-eps+2j]) + + zc, zr = _cplxreal(z) + xp_assert_close(zc, [1j, 1+1j, 1+2j, 1+3j, 2+3j, 2+4j, 3+7j, 4+1j, + 4+2j]) + xp_assert_equal(zr, np.asarray([])) + + def test_unmatched_conjugates(self): + # 1+2j is unmatched + assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j]) + + # 1+2j and 1-3j are unmatched + assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j, 1-3j]) + + # 1+3j is unmatched + assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+3j]) + + # No pairs + assert_raises(ValueError, _cplxreal, [1+3j]) + assert_raises(ValueError, _cplxreal, [1-3j]) + + def test_real_integer_input(self): + zc, zr = _cplxreal([2, 0, 1, 4]) + xp_assert_equal(zc, []) + xp_assert_equal(zr, [0, 1, 2, 4]) + + +class TestTf2zpk: + + @pytest.mark.parametrize('dt', (np.float64, np.complex128)) + def test_simple(self, dt): + z_r = np.array([0.5, -0.5]) + p_r = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)]) + # Sort the zeros/poles so that we don't fail the test if the order + # changes + z_r.sort() + p_r.sort() + b = np.poly(z_r).astype(dt) + a = np.poly(p_r).astype(dt) + + z, p, k = tf2zpk(b, a) + z.sort() + # The real part of `p` is ~0.0, so sort by imaginary part + p = p[np.argsort(p.imag)] + + assert_array_almost_equal(z, z_r) + assert_array_almost_equal(p, p_r) + assert_array_almost_equal(k, 1.) + assert k.dtype == dt + + def test_bad_filter(self): + # Regression test for #651: better handling of badly conditioned + # filter coefficients. + with suppress_warnings(): + warnings.simplefilter("error", BadCoefficients) + assert_raises(BadCoefficients, tf2zpk, [1e-15], [1.0, 1.0]) + + +class TestZpk2Tf: + + def test_identity(self): + """Test the identity transfer function.""" + z = [] + p = [] + k = 1. + b, a = zpk2tf(z, p, k) + b_r = np.array([1.]) # desired result + a_r = np.array([1.]) # desired result + # The test for the *type* of the return values is a regression + # test for ticket #1095. In the case p=[], zpk2tf used to + # return the scalar 1.0 instead of array([1.0]). + xp_assert_equal(b, b_r) + assert isinstance(b, np.ndarray) + xp_assert_equal(a, a_r) + assert isinstance(a, np.ndarray) + + +class TestSos2Zpk: + + def test_basic(self): + sos = [[1, 0, 1, 1, 0, -0.81], + [1, 0, 0, 1, 0, +0.49]] + z, p, k = sos2zpk(sos) + z2 = [1j, -1j, 0, 0] + p2 = [0.9, -0.9, 0.7j, -0.7j] + k2 = 1 + assert_array_almost_equal(sort(z), sort(z2), decimal=4) + assert_array_almost_equal(sort(p), sort(p2), decimal=4) + assert_array_almost_equal(k, k2) + + sos = [[1.00000, +0.61803, 1.0000, 1.00000, +0.60515, 0.95873], + [1.00000, -1.61803, 1.0000, 1.00000, -1.58430, 0.95873], + [1.00000, +1.00000, 0.0000, 1.00000, +0.97915, 0.00000]] + z, p, k = sos2zpk(sos) + z2 = [-0.3090 + 0.9511j, -0.3090 - 0.9511j, 0.8090 + 0.5878j, + 0.8090 - 0.5878j, -1.0000 + 0.0000j, 0] + p2 = [-0.3026 + 0.9312j, -0.3026 - 0.9312j, 0.7922 + 0.5755j, + 0.7922 - 0.5755j, -0.9791 + 0.0000j, 0] + k2 = 1 + assert_array_almost_equal(sort(z), sort(z2), decimal=4) + assert_array_almost_equal(sort(p), sort(p2), decimal=4) + + sos = array([[1, 2, 3, 1, 0.2, 0.3], + [4, 5, 6, 1, 0.4, 0.5]]) + z = array([-1 - 1.41421356237310j, -1 + 1.41421356237310j, + -0.625 - 1.05326872164704j, -0.625 + 1.05326872164704j]) + p = array([-0.2 - 0.678232998312527j, -0.2 + 0.678232998312527j, + -0.1 - 0.538516480713450j, -0.1 + 0.538516480713450j]) + k = 4 + z2, p2, k2 = sos2zpk(sos) + xp_assert_close(_cplxpair(z2), z) + xp_assert_close(_cplxpair(p2), p) + assert k2 == k + + @pytest.mark.thread_unsafe + def test_fewer_zeros(self): + """Test not the expected number of p/z (effectively at origin).""" + sos = butter(3, 0.1, output='sos') + z, p, k = sos2zpk(sos) + assert len(z) == 4 + assert len(p) == 4 + + sos = butter(12, [5., 30.], 'bandpass', fs=1200., analog=False, + output='sos') + with pytest.warns(BadCoefficients, match='Badly conditioned'): + z, p, k = sos2zpk(sos) + assert len(z) == 24 + assert len(p) == 24 + + +class TestSos2Tf: + + def test_basic(self): + sos = [[1, 1, 1, 1, 0, -1], + [-2, 3, 1, 1, 10, 1]] + b, a = sos2tf(sos) + assert_array_almost_equal(b, [-2, 1, 2, 4, 1]) + assert_array_almost_equal(a, [1, 10, 0, -10, -1]) + + +class TestTf2Sos: + + def test_basic(self): + num = [2, 16, 44, 56, 32] + den = [3, 3, -15, 18, -12] + sos = tf2sos(num, den) + sos2 = [[0.6667, 4.0000, 5.3333, 1.0000, +2.0000, -4.0000], + [1.0000, 2.0000, 2.0000, 1.0000, -1.0000, +1.0000]] + assert_array_almost_equal(sos, sos2, decimal=4) + + b = [1, -3, 11, -27, 18] + a = [16, 12, 2, -4, -1] + sos = tf2sos(b, a) + sos2 = [[0.0625, -0.1875, 0.1250, 1.0000, -0.2500, -0.1250], + [1.0000, +0.0000, 9.0000, 1.0000, +1.0000, +0.5000]] + # assert_array_almost_equal(sos, sos2, decimal=4) + + @pytest.mark.parametrize('b, a, analog, sos', + [([1], [1], False, [[1., 0., 0., 1., 0., 0.]]), + ([1], [1], True, [[0., 0., 1., 0., 0., 1.]]), + ([1], [1., 0., -1.01, 0, 0.01], False, + [[1., 0., 0., 1., 0., -0.01], + [1., 0., 0., 1., 0., -1]]), + ([1], [1., 0., -1.01, 0, 0.01], True, + [[0., 0., 1., 1., 0., -1], + [0., 0., 1., 1., 0., -0.01]])]) + def test_analog(self, b, a, analog, sos): + sos2 = tf2sos(b, a, analog=analog) + assert_array_almost_equal(sos, sos2, decimal=4) + + +class TestZpk2Sos: + + @pytest.mark.parametrize('dt', 'fdgFDG') + @pytest.mark.parametrize('pairing, analog', + [('nearest', False), + ('keep_odd', False), + ('minimal', False), + ('minimal', True)]) + def test_dtypes(self, dt, pairing, analog): + z = np.array([-1, -1]).astype(dt) + ct = dt.upper() # the poles have to be complex + p = np.array([0.57149 + 0.29360j, 0.57149 - 0.29360j]).astype(ct) + k = np.array(1).astype(dt) + sos = zpk2sos(z, p, k, pairing=pairing, analog=analog) + sos2 = [[1, 2, 1, 1, -1.14298, 0.41280]] # octave & MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + def test_basic(self): + for pairing in ('nearest', 'keep_odd'): + # + # Cases that match octave + # + + z = [-1, -1] + p = [0.57149 + 0.29360j, 0.57149 - 0.29360j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1, 2, 1, 1, -1.14298, 0.41280]] # octave & MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [1j, -1j] + p = [0.9, -0.9, 0.7j, -0.7j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1, 0, 1, 1, 0, +0.49], + [1, 0, 0, 1, 0, -0.81]] # octave + # sos2 = [[0, 0, 1, 1, -0.9, 0], + # [1, 0, 1, 1, 0.9, 0]] # MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [] + p = [0.8, -0.5+0.25j, -0.5-0.25j] + k = 1. + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1., 0., 0., 1., 1., 0.3125], + [1., 0., 0., 1., -0.8, 0.]] # octave, MATLAB fails + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [1., 1., 0.9j, -0.9j] + p = [0.99+0.01j, 0.99-0.01j, 0.1+0.9j, 0.1-0.9j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1, 0, 0.81, 1, -0.2, 0.82], + [1, -2, 1, 1, -1.98, 0.9802]] # octave + # sos2 = [[1, -2, 1, 1, -0.2, 0.82], + # [1, 0, 0.81, 1, -1.98, 0.9802]] # MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [0.9+0.1j, 0.9-0.1j, -0.9] + p = [0.75+0.25j, 0.75-0.25j, 0.9] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + if pairing == 'keep_odd': + sos2 = [[1, -1.8, 0.82, 1, -1.5, 0.625], + [1, 0.9, 0, 1, -0.9, 0]] # octave; MATLAB fails + assert_array_almost_equal(sos, sos2, decimal=4) + else: # pairing == 'nearest' + sos2 = [[1, 0.9, 0, 1, -1.5, 0.625], + [1, -1.8, 0.82, 1, -0.9, 0]] # our algorithm + assert_array_almost_equal(sos, sos2, decimal=4) + + # + # Cases that differ from octave: + # + + z = [-0.3090 + 0.9511j, -0.3090 - 0.9511j, 0.8090 + 0.5878j, + +0.8090 - 0.5878j, -1.0000 + 0.0000j] + p = [-0.3026 + 0.9312j, -0.3026 - 0.9312j, 0.7922 + 0.5755j, + +0.7922 - 0.5755j, -0.9791 + 0.0000j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + # sos2 = [[1, 0.618, 1, 1, 0.6052, 0.95870], + # [1, -1.618, 1, 1, -1.5844, 0.95878], + # [1, 1, 0, 1, 0.9791, 0]] # octave, MATLAB fails + sos2 = [[1, 1, 0, 1, +0.97915, 0], + [1, 0.61803, 1, 1, +0.60515, 0.95873], + [1, -1.61803, 1, 1, -1.58430, 0.95873]] + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [-1 - 1.4142j, -1 + 1.4142j, + -0.625 - 1.0533j, -0.625 + 1.0533j] + p = [-0.2 - 0.6782j, -0.2 + 0.6782j, + -0.1 - 0.5385j, -0.1 + 0.5385j] + k = 4 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[4, 8, 12, 1, 0.2, 0.3], + [1, 1.25, 1.5, 1, 0.4, 0.5]] # MATLAB + # sos2 = [[4, 8, 12, 1, 0.4, 0.5], + # [1, 1.25, 1.5, 1, 0.2, 0.3]] # octave + xp_assert_close(sos, sos2, rtol=1e-4, atol=1e-4) + + z = [] + p = [0.2, -0.5+0.25j, -0.5-0.25j] + k = 1. + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1., 0., 0., 1., -0.2, 0.], + [1., 0., 0., 1., 1., 0.3125]] + # sos2 = [[1., 0., 0., 1., 1., 0.3125], + # [1., 0., 0., 1., -0.2, 0]] # octave, MATLAB fails + assert_array_almost_equal(sos, sos2, decimal=4) + + # The next two examples are adapted from Leland B. Jackson, + # "Digital Filters and Signal Processing (1995) p.400: + # http://books.google.com/books?id=VZ8uabI1pNMC&lpg=PA400&ots=gRD9pi8Jua&dq=Pole%2Fzero%20pairing%20for%20minimum%20roundoff%20noise%20in%20BSF.&pg=PA400#v=onepage&q=Pole%2Fzero%20pairing%20for%20minimum%20roundoff%20noise%20in%20BSF.&f=false + + deg2rad = np.pi / 180. + k = 1. + + # first example + thetas = [22.5, 45, 77.5] + mags = [0.8, 0.6, 0.9] + z = np.array([np.exp(theta * deg2rad * 1j) for theta in thetas]) + z = np.concatenate((z, np.conj(z))) + p = np.array([mag * np.exp(theta * deg2rad * 1j) + for theta, mag in zip(thetas, mags)]) + p = np.concatenate((p, np.conj(p))) + sos = zpk2sos(z, p, k) + # sos2 = [[1, -0.43288, 1, 1, -0.38959, 0.81], # octave, + # [1, -1.41421, 1, 1, -0.84853, 0.36], # MATLAB fails + # [1, -1.84776, 1, 1, -1.47821, 0.64]] + # Note that pole-zero pairing matches, but ordering is different + sos2 = [[1, -1.41421, 1, 1, -0.84853, 0.36], + [1, -1.84776, 1, 1, -1.47821, 0.64], + [1, -0.43288, 1, 1, -0.38959, 0.81]] + assert_array_almost_equal(sos, sos2, decimal=4) + + # second example + z = np.array([np.exp(theta * deg2rad * 1j) + for theta in (85., 10.)]) + z = np.concatenate((z, np.conj(z), [1, -1])) + sos = zpk2sos(z, p, k) + + # sos2 = [[1, -0.17431, 1, 1, -0.38959, 0.81], # octave "wrong", + # [1, -1.96962, 1, 1, -0.84853, 0.36], # MATLAB fails + # [1, 0, -1, 1, -1.47821, 0.64000]] + # Our pole-zero pairing matches the text, Octave does not + sos2 = [[1, 0, -1, 1, -0.84853, 0.36], + [1, -1.96962, 1, 1, -1.47821, 0.64], + [1, -0.17431, 1, 1, -0.38959, 0.81]] + assert_array_almost_equal(sos, sos2, decimal=4) + + # these examples are taken from the doc string, and show the + # effect of the 'pairing' argument + @pytest.mark.parametrize('pairing, sos', + [('nearest', + np.array([[1., 1., 0.5, 1., -0.75, 0.], + [1., 1., 0., 1., -1.6, 0.65]])), + ('keep_odd', + np.array([[1., 1., 0, 1., -0.75, 0.], + [1., 1., 0.5, 1., -1.6, 0.65]])), + ('minimal', + np.array([[0., 1., 1., 0., 1., -0.75], + [1., 1., 0.5, 1., -1.6, 0.65]]))]) + def test_pairing(self, pairing, sos): + z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j]) + p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j]) + sos2 = zpk2sos(z1, p1, 1, pairing=pairing) + assert_array_almost_equal(sos, sos2, decimal=4) + + @pytest.mark.parametrize('p, sos_dt', + [([-1, 1, -0.1, 0.1], + [[0., 0., 1., 1., 0., -0.01], + [0., 0., 1., 1., 0., -1]]), + ([-0.7071+0.7071j, -0.7071-0.7071j, -0.1j, 0.1j], + [[0., 0., 1., 1., 0., 0.01], + [0., 0., 1., 1., 1.4142, 1.]])]) + def test_analog(self, p, sos_dt): + # test `analog` argument + # for discrete time, poles closest to unit circle should appear last + # for cont. time, poles closest to imaginary axis should appear last + sos2_dt = zpk2sos([], p, 1, pairing='minimal', analog=False) + sos2_ct = zpk2sos([], p, 1, pairing='minimal', analog=True) + assert_array_almost_equal(sos_dt, sos2_dt, decimal=4) + assert_array_almost_equal(sos_dt[::-1], sos2_ct, decimal=4) + + def test_bad_args(self): + with pytest.raises(ValueError, match=r'pairing must be one of'): + zpk2sos([1], [2], 1, pairing='no_such_pairing') + + with pytest.raises(ValueError, match=r'.*pairing must be "minimal"'): + zpk2sos([1], [2], 1, pairing='keep_odd', analog=True) + + with pytest.raises(ValueError, + match=r'.*must have len\(p\)>=len\(z\)'): + zpk2sos([1, 1], [2], 1, analog=True) + + with pytest.raises(ValueError, match=r'k must be real'): + zpk2sos([1], [2], k=1j) + + +class TestFreqs: + + def test_basic(self): + _, h = freqs([1.0], [1.0], worN=8) + assert_array_almost_equal(h, np.ones(8)) + + def test_output(self): + # 1st order low-pass filter: H(s) = 1 / (s + 1) + w = [0.1, 1, 10, 100] + num = [1] + den = [1, 1] + w, H = freqs(num, den, worN=w) + s = w * 1j + expected = 1 / (s + 1) + assert_array_almost_equal(H.real, expected.real) + assert_array_almost_equal(H.imag, expected.imag) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + # Expected range is from 0.01 to 10. + num = [1] + den = [1, 1] + n = 10 + expected_w = np.logspace(-2, 1, n) + w, H = freqs(num, den, worN=n) + assert_array_almost_equal(w, expected_w) + + def test_plot(self): + + def plot(w, h): + assert_array_almost_equal(h, np.ones(8)) + + assert_raises(ZeroDivisionError, freqs, [1.0], [1.0], worN=8, + plot=lambda w, h: 1 / 0) + freqs([1.0], [1.0], worN=8, plot=plot) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqs([1.0], [1.0]) + w2, h2 = freqs([1.0], [1.0], None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + w, h = freqs([1.0], [1.0], worN=N) + assert len(w) == 8 + assert_array_almost_equal(h, np.ones(8)) + + # Measure at frequency 8 rad/sec + for w in (8.0, 8.0+0j): + w_out, h = freqs([1.0], [1.0], worN=w) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + +class TestFreqs_zpk: + + def test_basic(self): + _, h = freqs_zpk([1.0], [1.0], [1.0], worN=8) + assert_array_almost_equal(h, np.ones(8)) + + def test_output(self): + # 1st order low-pass filter: H(s) = 1 / (s + 1) + w = [0.1, 1, 10, 100] + z = [] + p = [-1] + k = 1 + w, H = freqs_zpk(z, p, k, worN=w) + s = w * 1j + expected = 1 / (s + 1) + assert_array_almost_equal(H.real, expected.real) + assert_array_almost_equal(H.imag, expected.imag) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + # Expected range is from 0.01 to 10. + z = [] + p = [-1] + k = 1 + n = 10 + expected_w = np.logspace(-2, 1, n) + w, H = freqs_zpk(z, p, k, worN=n) + assert_array_almost_equal(w, expected_w) + + def test_vs_freqs(self): + b, a = cheby1(4, 5, 100, analog=True, output='ba') + z, p, k = cheby1(4, 5, 100, analog=True, output='zpk') + + w1, h1 = freqs(b, a) + w2, h2 = freqs_zpk(z, p, k) + xp_assert_close(w1, w2) + xp_assert_close(h1, h2, rtol=1e-6) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqs_zpk([1.0], [1.0], [1.0]) + w2, h2 = freqs_zpk([1.0], [1.0], [1.0], None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + w, h = freqs_zpk([], [], 1, worN=N) + assert len(w) == 8 + assert_array_almost_equal(h, np.ones(8)) + + # Measure at frequency 8 rad/sec + for w in (8.0, 8.0+0j): + w_out, h = freqs_zpk([], [], 1, worN=w) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + +class TestFreqz: + + def test_ticket1441(self): + """Regression test for ticket 1441.""" + # Because freqz previously used arange instead of linspace, + # when N was large, it would return one more point than + # requested. + N = 100000 + w, h = freqz([1.0], worN=N) + assert w.shape == (N,) + + def test_basic(self): + w, h = freqz([1.0], worN=8) + assert_array_almost_equal(w, np.pi * np.arange(8) / 8.) + assert_array_almost_equal(h, np.ones(8)) + w, h = freqz([1.0], worN=9) + assert_array_almost_equal(w, np.pi * np.arange(9) / 9.) + assert_array_almost_equal(h, np.ones(9)) + + for a in [1, np.ones(2)]: + w, h = freqz(np.ones(2), a, worN=0) + assert w.shape == (0,) + assert h.shape == (0,) + assert h.dtype == np.dtype('complex128') + + t = np.linspace(0, 1, 4, endpoint=False) + for b, a, h_whole in zip( + ([1., 0, 0, 0], np.sin(2 * np.pi * t)), + ([1., 0, 0, 0], [0.5, 0, 0, 0]), + ([1., 1., 1., 1.], [0, -4j, 0, 4j])): + w, h = freqz(b, a, worN=4, whole=True) + expected_w = np.linspace(0, 2 * np.pi, 4, endpoint=False) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, h_whole) + # simultaneously check int-like support + w, h = freqz(b, a, worN=np.int32(4), whole=True) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, h_whole) + w, h = freqz(b, a, worN=w, whole=True) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, h_whole) + + def test_basic_whole(self): + w, h = freqz([1.0], worN=8, whole=True) + assert_array_almost_equal(w, 2 * np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + def test_plot(self): + + def plot(w, h): + assert_array_almost_equal(w, np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + assert_raises(ZeroDivisionError, freqz, [1.0], worN=8, + plot=lambda w, h: 1 / 0) + freqz([1.0], worN=8, plot=plot) + + def test_fft_wrapping(self): + # Some simple real FIR filters + bs = list() # filters + as_ = list() + hs_whole = list() + hs_half = list() + # 3 taps + t = np.linspace(0, 1, 3, endpoint=False) + bs.append(np.sin(2 * np.pi * t)) + as_.append(3.) + hs_whole.append([0, -0.5j, 0.5j]) + hs_half.append([0, np.sqrt(1./12.), -0.5j]) + # 4 taps + t = np.linspace(0, 1, 4, endpoint=False) + bs.append(np.sin(2 * np.pi * t)) + as_.append(0.5) + hs_whole.append([0, -4j, 0, 4j]) + hs_half.append([0, np.sqrt(8), -4j, -np.sqrt(8)]) + del t + for ii, b in enumerate(bs): + # whole + a = as_[ii] + expected_w = np.linspace(0, 2 * np.pi, len(b), endpoint=False) + w, h = freqz(b, a, worN=expected_w, whole=True) # polyval + err_msg = f'b = {b}, a={a}' + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_whole[ii], err_msg=err_msg) + w, h = freqz(b, a, worN=len(b), whole=True) # FFT + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_whole[ii], err_msg=err_msg) + # non-whole + expected_w = np.linspace(0, np.pi, len(b), endpoint=False) + w, h = freqz(b, a, worN=expected_w, whole=False) # polyval + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_half[ii], err_msg=err_msg) + w, h = freqz(b, a, worN=len(b), whole=False) # FFT + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_half[ii], err_msg=err_msg) + + # some random FIR filters (real + complex) + # assume polyval is accurate + rng = np.random.RandomState(0) + for ii in range(2, 10): # number of taps + b = rng.randn(ii) + for kk in range(2): + a = rng.randn(1) if kk == 0 else rng.randn(3) + for jj in range(2): + if jj == 1: + b = b + rng.randn(ii) * 1j + # whole + expected_w = np.linspace(0, 2 * np.pi, ii, endpoint=False) + w, expected_h = freqz(b, a, worN=expected_w, whole=True) + assert_array_almost_equal(w, expected_w) + w, h = freqz(b, a, worN=ii, whole=True) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, expected_h) + # half + expected_w = np.linspace(0, np.pi, ii, endpoint=False) + w, expected_h = freqz(b, a, worN=expected_w, whole=False) + assert_array_almost_equal(w, expected_w) + w, h = freqz(b, a, worN=ii, whole=False) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, expected_h) + + def test_broadcasting1(self): + # Test broadcasting with worN an integer or a 1-D array, + # b and a are n-dimensional arrays. + np.random.seed(123) + b = np.random.rand(3, 5, 1) + a = np.random.rand(2, 1) + for whole in [False, True]: + # Test with worN being integers (one fast for FFT and one not), + # a 1-D array, and an empty array. + for worN in [16, 17, np.linspace(0, 1, 10), np.array([])]: + w, h = freqz(b, a, worN=worN, whole=whole) + for k in range(b.shape[1]): + bk = b[:, k, 0] + ak = a[:, 0] + ww, hh = freqz(bk, ak, worN=worN, whole=whole) + xp_assert_close(ww, w) + xp_assert_close(hh, h[k]) + + def test_broadcasting2(self): + # Test broadcasting with worN an integer or a 1-D array, + # b is an n-dimensional array, and a is left at the default value. + np.random.seed(123) + b = np.random.rand(3, 5, 1) + for whole in [False, True]: + for worN in [16, 17, np.linspace(0, 1, 10)]: + w, h = freqz(b, worN=worN, whole=whole) + for k in range(b.shape[1]): + bk = b[:, k, 0] + ww, hh = freqz(bk, worN=worN, whole=whole) + xp_assert_close(ww, w) + xp_assert_close(hh, h[k]) + + def test_broadcasting3(self): + # Test broadcasting where b.shape[-1] is the same length + # as worN, and a is left at the default value. + np.random.seed(123) + N = 16 + b = np.random.rand(3, N) + for whole in [False, True]: + for worN in [N, np.linspace(0, 1, N)]: + w, h = freqz(b, worN=worN, whole=whole) + assert w.size == N + for k in range(N): + bk = b[:, k] + ww, hh = freqz(bk, worN=w[k], whole=whole) + xp_assert_close(ww, np.asarray(w[k])[None]) + xp_assert_close(hh, np.asarray(h[k])[None]) + + def test_broadcasting4(self): + # Test broadcasting with worN a 2-D array. + np.random.seed(123) + b = np.random.rand(4, 2, 1, 1) + a = np.random.rand(5, 2, 1, 1) + for whole in [False, True]: + for worN in [np.random.rand(6, 7), np.empty((6, 0))]: + w, h = freqz(b, a, worN=worN, whole=whole) + xp_assert_close(w, worN, rtol=1e-14) + assert h.shape == (2,) + worN.shape + for k in range(2): + ww, hh = freqz(b[:, k, 0, 0], a[:, k, 0, 0], + worN=worN.ravel(), + whole=whole) + xp_assert_close(ww, worN.ravel(), rtol=1e-14) + xp_assert_close(hh, h[k, :, :].ravel()) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqz([1.0], 1) + w2, h2 = freqz([1.0], 1, None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_fs_param(self): + fs = 900 + b = [0.039479155677484369, 0.11843746703245311, 0.11843746703245311, + 0.039479155677484369] + a = [1.0, -1.3199152021838287, 0.80341991081938424, + -0.16767146321568049] + + # N = None, whole=False + w1, h1 = freqz(b, a, fs=fs) + w2, h2 = freqz(b, a) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 512, endpoint=False)) + + # N = None, whole=True + w1, h1 = freqz(b, a, whole=True, fs=fs) + w2, h2 = freqz(b, a, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 512, endpoint=False)) + + # N = 5, whole=False + w1, h1 = freqz(b, a, 5, fs=fs) + w2, h2 = freqz(b, a, 5) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 5, endpoint=False)) + + # N = 5, whole=True + w1, h1 = freqz(b, a, 5, whole=True, fs=fs) + w2, h2 = freqz(b, a, 5, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 5, endpoint=False)) + + # w is an array_like + for w in ([123], (123,), np.array([123]), (50, 123, 230), + np.array([50, 123, 230])): + w1, h1 = freqz(b, a, w, fs=fs) + w2, h2 = freqz(b, a, 2*pi*np.array(w)/fs) + xp_assert_close(h1, h2) + xp_assert_close(w, w1, check_dtype=False) + + def test_w_or_N_types(self): + # Measure at 7 (polyval) or 8 (fft) equally-spaced points + for N in (7, np.int8(7), np.int16(7), np.int32(7), np.int64(7), + np.array(7), + 8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + + w, h = freqz([1.0], worN=N) + assert_array_almost_equal(w, np.pi * np.arange(N) / N) + assert_array_almost_equal(h, np.ones(N)) + + w, h = freqz([1.0], worN=N, fs=100) + assert_array_almost_equal(w, np.linspace(0, 50, N, endpoint=False)) + assert_array_almost_equal(h, np.ones(N)) + + # Measure at frequency 8 Hz + for w in (8.0, 8.0+0j): + # Only makes sense when fs is specified + w_out, h = freqz([1.0], worN=w, fs=100) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + def test_nyquist(self): + w, h = freqz([1.0], worN=8, include_nyquist=True) + assert_array_almost_equal(w, np.pi * np.arange(8) / 7.) + assert_array_almost_equal(h, np.ones(8)) + w, h = freqz([1.0], worN=9, include_nyquist=True) + assert_array_almost_equal(w, np.pi * np.arange(9) / 8.) + assert_array_almost_equal(h, np.ones(9)) + + for a in [1, np.ones(2)]: + w, h = freqz(np.ones(2), a, worN=0, include_nyquist=True) + assert w.shape == (0,) + assert h.shape == (0,) + assert h.dtype == np.dtype('complex128') + + w1, h1 = freqz([1.0], worN=8, whole = True, include_nyquist=True) + w2, h2 = freqz([1.0], worN=8, whole = True, include_nyquist=False) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + # https://github.com/scipy/scipy/issues/17289 + # https://github.com/scipy/scipy/issues/15273 + @pytest.mark.parametrize('whole,nyquist,worN', + [(False, False, 32), + (False, True, 32), + (True, False, 32), + (True, True, 32), + (False, False, 257), + (False, True, 257), + (True, False, 257), + (True, True, 257)]) + def test_17289(self, whole, nyquist, worN): + d = [0, 1] + w, Drfft = freqz(d, worN=32, whole=whole, include_nyquist=nyquist) + _, Dpoly = freqz(d, worN=w) + xp_assert_close(Drfft, Dpoly) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + freqz([1.0], fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none."): + freqz([1.0], fs=None) + + +class Testfreqz_sos: + + def test_freqz_sos_basic(self): + # Compare the results of freqz and freqz_sos for a low order + # Butterworth filter. + + N = 500 + + b, a = butter(4, 0.2) + sos = butter(4, 0.2, output='sos') + w, h = freqz(b, a, worN=N) + w2, h2 = freqz_sos(sos, worN=N) + xp_assert_equal(w2, w) + xp_assert_close(h2, h, rtol=1e-10, atol=1e-14) + + b, a = ellip(3, 1, 30, (0.2, 0.3), btype='bandpass') + sos = ellip(3, 1, 30, (0.2, 0.3), btype='bandpass', output='sos') + w, h = freqz(b, a, worN=N) + w2, h2 = freqz_sos(sos, worN=N) + xp_assert_equal(w2, w) + xp_assert_close(h2, h, rtol=1e-10, atol=1e-14) + # must have at least one section + assert_raises(ValueError, freqz_sos, sos[:0]) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + N = 500 + + sos = butter(4, 0.2, output='sos') + w1, h1 = freqz_sos(sos, worN=N) + w2, h2 = sosfreqz(sos, worN=N) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_freqz_sos_design(self): + # Compare freqz_sos output against expected values for different + # filter types + + # from cheb2ord + N, Wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + sos = cheby2(N, 60, Wn, 'stop', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + xp_assert_close(20 * np.log10(h[w <= 0.1]), np.asarray(0.), atol=3.01, + check_shape=False) + xp_assert_close(20 * np.log10(h[w >= 0.6]), np.asarray(0.), atol=3.01, + check_shape=False) + xp_assert_close(h[(w >= 0.2) & (w <= 0.5)], + np.asarray(0.), atol=1e-3, + check_shape=False) # <= -60 dB + + N, Wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 150) + sos = cheby2(N, 150, Wn, 'stop', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.abs(h)) + w /= np.pi + xp_assert_close(dB[w <= 0.1], np.asarray(0.0), atol=3.01, check_shape=False) + xp_assert_close(dB[w >= 0.6], np.asarray(0.0), atol=3.01, check_shape=False) + assert np.all(dB[(w >= 0.2) & (w <= 0.5)] < -149.9) + + # from cheb1ord + N, Wn = cheb1ord(0.2, 0.3, 3, 40) + sos = cheby1(N, 3, Wn, 'low', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + xp_assert_close(20 * np.log10(h[w <= 0.2]), np.asarray(0.0), atol=3.01, + check_shape=False) + xp_assert_close(h[w >= 0.3], np.asarray(0.0), atol=1e-2, + check_shape=False) # <= -40 dB + + N, Wn = cheb1ord(0.2, 0.3, 1, 150) + sos = cheby1(N, 1, Wn, 'low', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.abs(h)) + w /= np.pi + xp_assert_close(dB[w <= 0.2], np.asarray(0.0), atol=1.01, + check_shape=False) + assert np.all(dB[w >= 0.3] < -149.9) + + # adapted from ellipord + N, Wn = ellipord(0.3, 0.2, 3, 60) + sos = ellip(N, 0.3, 60, Wn, 'high', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + xp_assert_close(20 * np.log10(h[w >= 0.3]), np.asarray(0.0), atol=3.01, + check_shape=False) + xp_assert_close(h[w <= 0.1], np.asarray(0.0), atol=1.5e-3, + check_shape=False) # <= -60 dB (approx) + + # adapted from buttord + N, Wn = buttord([0.2, 0.5], [0.14, 0.6], 3, 40) + sos = butter(N, Wn, 'band', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + + h014 = h[w <= 0.14] + xp_assert_close(h014, np.zeros_like(h014), atol=1e-2) # <= -40 dB + h06 = h[w >= 0.6] + xp_assert_close(h06, np.zeros_like(h06), atol=1e-2) # <= -40 dB + h0205 = 20 * np.log10(h[(w >= 0.2) & (w <= 0.5)]) + xp_assert_close(h0205, np.zeros_like(h0205), atol=3.01) + + N, Wn = buttord([0.2, 0.5], [0.14, 0.6], 3, 100) + sos = butter(N, Wn, 'band', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.maximum(np.abs(h), 1e-10)) + w /= np.pi + + assert np.all(dB[(w > 0) & (w <= 0.14)] < -99.9) + assert np.all(dB[w >= 0.6] < -99.9) + db0205 = dB[(w >= 0.2) & (w <= 0.5)] + xp_assert_close(db0205, np.zeros_like(db0205), atol=3.01) + + def test_freqz_sos_design_ellip(self): + N, Wn = ellipord(0.3, 0.1, 3, 60) + sos = ellip(N, 0.3, 60, Wn, 'high', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + + h03 = 20 * np.log10(h[w >= 0.3]) + xp_assert_close(h03, np.zeros_like(h03), atol=3.01) + h01 = h[w <= 0.1] + xp_assert_close(h01, np.zeros_like(h01), atol=1.5e-3) # <= -60 dB (approx) + + N, Wn = ellipord(0.3, 0.2, .5, 150) + sos = ellip(N, .5, 150, Wn, 'high', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.maximum(np.abs(h), 1e-10)) + w /= np.pi + + db03 = dB[w >= 0.3] + xp_assert_close(db03, np.zeros_like(db03), atol=.55) + # Allow some numerical slop in the upper bound -150, so this is + # a check that dB[w <= 0.2] is less than or almost equal to -150. + assert dB[w <= 0.2].max() < -150*(1 - 1e-12) + + @mpmath_check("0.10") + def test_freqz_sos_against_mp(self): + # Compare the result of freqz_sos applied to a high order Butterworth + # filter against the result computed using mpmath. (signal.freqz fails + # miserably with such high order filters.) + from . import mpsig + N = 500 + order = 25 + Wn = 0.15 + with mpmath.workdps(80): + z_mp, p_mp, k_mp = mpsig.butter_lp(order, Wn) + w_mp, h_mp = mpsig.zpkfreqz(z_mp, p_mp, k_mp, N) + w_mp = np.array([float(x) for x in w_mp]) + h_mp = np.array([complex(x) for x in h_mp]) + + sos = butter(order, Wn, output='sos') + w, h = freqz_sos(sos, worN=N) + xp_assert_close(w, w_mp, rtol=1e-12, atol=1e-14) + xp_assert_close(h, h_mp, rtol=1e-12, atol=1e-14) + + def test_fs_param(self): + fs = 900 + sos = [[0.03934683014103762, 0.07869366028207524, 0.03934683014103762, + 1.0, -0.37256600288916636, 0.0], + [1.0, 1.0, 0.0, 1.0, -0.9495739996946778, 0.45125966317124144]] + + # N = None, whole=False + w1, h1 = freqz_sos(sos, fs=fs) + w2, h2 = freqz_sos(sos) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 512, endpoint=False)) + + # N = None, whole=True + w1, h1 = freqz_sos(sos, whole=True, fs=fs) + w2, h2 = freqz_sos(sos, whole=True) + xp_assert_close(h1, h2, atol=1e-27) + xp_assert_close(w1, np.linspace(0, fs, 512, endpoint=False)) + + # N = 5, whole=False + w1, h1 = freqz_sos(sos, 5, fs=fs) + w2, h2 = freqz_sos(sos, 5) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 5, endpoint=False)) + + # N = 5, whole=True + w1, h1 = freqz_sos(sos, 5, whole=True, fs=fs) + w2, h2 = freqz_sos(sos, 5, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 5, endpoint=False)) + + # w is an array_like + for w in ([123], (123,), np.array([123]), (50, 123, 230), + np.array([50, 123, 230])): + w1, h1 = freqz_sos(sos, w, fs=fs) + w2, h2 = freqz_sos(sos, 2*pi*np.array(w)/fs) + xp_assert_close(h1, h2) + xp_assert_close(w, w1, check_dtype=False) + + def test_w_or_N_types(self): + # Measure at 7 (polyval) or 8 (fft) equally-spaced points + for N in (7, np.int8(7), np.int16(7), np.int32(7), np.int64(7), + np.array(7), + 8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + + w, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=N) + assert_array_almost_equal(w, np.pi * np.arange(N) / N) + assert_array_almost_equal(h, np.ones(N)) + + w, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=N, fs=100) + assert_array_almost_equal(w, np.linspace(0, 50, N, endpoint=False)) + assert_array_almost_equal(h, np.ones(N)) + + # Measure at frequency 8 Hz + for w in (8.0, 8.0+0j): + # Only makes sense when fs is specified + w_out, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=w, fs=100) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + def test_fs_validation(self): + sos = butter(4, 0.2, output='sos') + with pytest.raises(ValueError, match="Sampling.*single scalar"): + freqz_sos(sos, fs=np.array([10, 20])) + + +class TestFreqz_zpk: + + def test_ticket1441(self): + """Regression test for ticket 1441.""" + # Because freqz previously used arange instead of linspace, + # when N was large, it would return one more point than + # requested. + N = 100000 + w, h = freqz_zpk([0.5], [0.5], 1.0, worN=N) + assert w.shape == (N,) + + def test_basic(self): + w, h = freqz_zpk([0.5], [0.5], 1.0, worN=8) + assert_array_almost_equal(w, np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + def test_basic_whole(self): + w, h = freqz_zpk([0.5], [0.5], 1.0, worN=8, whole=True) + assert_array_almost_equal(w, 2 * np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + def test_vs_freqz(self): + b, a = cheby1(4, 5, 0.5, analog=False, output='ba') + z, p, k = cheby1(4, 5, 0.5, analog=False, output='zpk') + + w1, h1 = freqz(b, a) + w2, h2 = freqz_zpk(z, p, k) + xp_assert_close(w1, w2) + xp_assert_close(h1, h2, rtol=1e-6) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqz_zpk([0.5], [0.5], 1.0) + w2, h2 = freqz_zpk([0.5], [0.5], 1.0, None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_fs_param(self): + fs = 900 + z = [-1, -1, -1] + p = [0.4747869998473389+0.4752230717749344j, 0.37256600288916636, + 0.4747869998473389-0.4752230717749344j] + k = 0.03934683014103762 + + # N = None, whole=False + w1, h1 = freqz_zpk(z, p, k, whole=False, fs=fs) + w2, h2 = freqz_zpk(z, p, k, whole=False) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 512, endpoint=False)) + + # N = None, whole=True + w1, h1 = freqz_zpk(z, p, k, whole=True, fs=fs) + w2, h2 = freqz_zpk(z, p, k, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 512, endpoint=False)) + + # N = 5, whole=False + w1, h1 = freqz_zpk(z, p, k, 5, fs=fs) + w2, h2 = freqz_zpk(z, p, k, 5) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 5, endpoint=False)) + + # N = 5, whole=True + w1, h1 = freqz_zpk(z, p, k, 5, whole=True, fs=fs) + w2, h2 = freqz_zpk(z, p, k, 5, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 5, endpoint=False)) + + # w is an array_like + for w in ([123], (123,), np.array([123]), (50, 123, 230), + np.array([50, 123, 230])): + w1, h1 = freqz_zpk(z, p, k, w, fs=fs) + w2, h2 = freqz_zpk(z, p, k, 2*pi*np.array(w)/fs) + xp_assert_close(h1, h2) + xp_assert_close(w, w1, check_dtype=False) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + + w, h = freqz_zpk([], [], 1, worN=N) + assert_array_almost_equal(w, np.pi * np.arange(8) / 8.) + assert_array_almost_equal(h, np.ones(8)) + + w, h = freqz_zpk([], [], 1, worN=N, fs=100) + assert_array_almost_equal(w, np.linspace(0, 50, 8, endpoint=False)) + assert_array_almost_equal(h, np.ones(8)) + + # Measure at frequency 8 Hz + for w in (8.0, 8.0+0j): + # Only makes sense when fs is specified + w_out, h = freqz_zpk([], [], 1, worN=w, fs=100) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + freqz_zpk([1.0], [1.0], [1.0], fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none."): + freqz_zpk([1.0], [1.0], [1.0], fs=None) + + +class TestNormalize: + + def test_allclose(self): + """Test for false positive on allclose in normalize() in + filter_design.py""" + # Test to make sure the allclose call within signal.normalize does not + # choose false positives. Then check against a known output from MATLAB + # to make sure the fix doesn't break anything. + + # These are the coefficients returned from + # `[b,a] = cheby1(8, 0.5, 0.048)' + # in MATLAB. There are at least 15 significant figures in each + # coefficient, so it makes sense to test for errors on the order of + # 1e-13 (this can always be relaxed if different platforms have + # different rounding errors) + b_matlab = np.array([2.150733144728282e-11, 1.720586515782626e-10, + 6.022052805239190e-10, 1.204410561047838e-09, + 1.505513201309798e-09, 1.204410561047838e-09, + 6.022052805239190e-10, 1.720586515782626e-10, + 2.150733144728282e-11]) + a_matlab = np.array([1.000000000000000e+00, -7.782402035027959e+00, + 2.654354569747454e+01, -5.182182531666387e+01, + 6.334127355102684e+01, -4.963358186631157e+01, + 2.434862182949389e+01, -6.836925348604676e+00, + 8.412934944449140e-01]) + + # This is the input to signal.normalize after passing through the + # equivalent steps in signal.iirfilter as was done for MATLAB + b_norm_in = np.array([1.5543135865293012e-06, 1.2434508692234413e-05, + 4.3520780422820447e-05, 8.7041560845640893e-05, + 1.0880195105705122e-04, 8.7041560845640975e-05, + 4.3520780422820447e-05, 1.2434508692234413e-05, + 1.5543135865293012e-06]) + a_norm_in = np.array([7.2269025909127173e+04, -5.6242661430467968e+05, + 1.9182761917308895e+06, -3.7451128364682454e+06, + 4.5776121393762771e+06, -3.5869706138592605e+06, + 1.7596511818472347e+06, -4.9409793515707983e+05, + 6.0799461347219651e+04]) + + b_output, a_output = normalize(b_norm_in, a_norm_in) + + # The test on b works for decimal=14 but the one for a does not. For + # the sake of consistency, both of these are decimal=13. If something + # breaks on another platform, it is probably fine to relax this lower. + assert_array_almost_equal(b_matlab, b_output, decimal=13) + assert_array_almost_equal(a_matlab, a_output, decimal=13) + + def test_errors(self): + """Test the error cases.""" + # all zero denominator + assert_raises(ValueError, normalize, [1, 2], 0) + + # denominator not 1 dimensional + assert_raises(ValueError, normalize, [1, 2], [[1]]) + + # numerator too many dimensions + assert_raises(ValueError, normalize, [[[1, 2]]], 1) + + +class TestLp2lp: + + def test_basic(self): + b = [1] + a = [1, np.sqrt(2), 1] + b_lp, a_lp = lp2lp(b, a, 0.38574256627112119) + assert_array_almost_equal(b_lp, [0.1488], decimal=4) + assert_array_almost_equal(a_lp, [1, 0.5455, 0.1488], decimal=4) + + +class TestLp2hp: + + def test_basic(self): + b = [0.25059432325190018] + a = [1, 0.59724041654134863, 0.92834805757524175, 0.25059432325190018] + b_hp, a_hp = lp2hp(b, a, 2*np.pi*5000) + xp_assert_close(b_hp, [1.0, 0, 0, 0]) + xp_assert_close(a_hp, [1, 1.1638e5, 2.3522e9, 1.2373e14], rtol=1e-4) + + +class TestLp2bp: + + def test_basic(self): + b = [1] + a = [1, 2, 2, 1] + b_bp, a_bp = lp2bp(b, a, 2*np.pi*4000, 2*np.pi*2000) + xp_assert_close(b_bp, [1.9844e12, 0, 0, 0], rtol=1e-6) + xp_assert_close(a_bp, [1, 2.5133e4, 2.2108e9, 3.3735e13, + 1.3965e18, 1.0028e22, 2.5202e26], rtol=1e-4) + + +class TestLp2bs: + + def test_basic(self): + b = [1] + a = [1, 1] + b_bs, a_bs = lp2bs(b, a, 0.41722257286366754, 0.18460575326152251) + assert_array_almost_equal(b_bs, [1, 0, 0.17407], decimal=5) + assert_array_almost_equal(a_bs, [1, 0.18461, 0.17407], decimal=5) + + +class TestBilinear: + + def test_basic(self): + b = [0.14879732743343033] + a = [1, 0.54552236880522209, 0.14879732743343033] + b_z, a_z = bilinear(b, a, 0.5) + assert_array_almost_equal(b_z, [0.087821, 0.17564, 0.087821], + decimal=5) + assert_array_almost_equal(a_z, [1, -1.0048, 0.35606], decimal=4) + + b = [1, 0, 0.17407467530697837] + a = [1, 0.18460575326152251, 0.17407467530697837] + b_z, a_z = bilinear(b, a, 0.5) + assert_array_almost_equal(b_z, [0.86413, -1.2158, 0.86413], + decimal=4) + assert_array_almost_equal(a_z, [1, -1.2158, 0.72826], + decimal=4) + + def test_fs_validation(self): + b = [0.14879732743343033] + a = [1, 0.54552236880522209, 0.14879732743343033] + with pytest.raises(ValueError, match="Sampling.*single scalar"): + bilinear(b, a, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + bilinear(b, a, fs=None) + + +class TestLp2lp_zpk: + + def test_basic(self): + z = [] + p = [(-1+1j)/np.sqrt(2), (-1-1j)/np.sqrt(2)] + k = 1 + z_lp, p_lp, k_lp = lp2lp_zpk(z, p, k, 5) + xp_assert_equal(z_lp, []) + xp_assert_close(sort(p_lp), sort(p)*5) + xp_assert_close(k_lp, 25.) + + # Pseudo-Chebyshev with both poles and zeros + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + z_lp, p_lp, k_lp = lp2lp_zpk(z, p, k, 20) + xp_assert_close(sort(z_lp), sort([-40j, +40j])) + xp_assert_close(sort(p_lp), sort([-15, -10-10j, -10+10j])) + xp_assert_close(k_lp, 60.) + + def test_fs_validation(self): + z = [-2j, +2j] + p = [-0.75, -0.5 - 0.5j, -0.5 + 0.5j] + k = 3 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + bilinear_zpk(z, p, k, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + bilinear_zpk(z, p, k, fs=None) + + +class TestLp2hp_zpk: + + def test_basic(self): + z = [] + p = [(-1+1j)/np.sqrt(2), (-1-1j)/np.sqrt(2)] + k = 1 + + z_hp, p_hp, k_hp = lp2hp_zpk(z, p, k, 5) + xp_assert_equal(z_hp, np.asarray([0.0, 0.0])) + xp_assert_close(sort(p_hp), sort(p)*5) + xp_assert_close(k_hp, 1.0) + + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + z_hp, p_hp, k_hp = lp2hp_zpk(z, p, k, 6) + xp_assert_close(sort(z_hp), sort([-3j, 0, +3j])) + xp_assert_close(sort(p_hp), sort([-8, -6-6j, -6+6j])) + xp_assert_close(k_hp, 32.0) + + +class TestLp2bp_zpk: + + def test_basic(self): + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + z_bp, p_bp, k_bp = lp2bp_zpk(z, p, k, 15, 8) + xp_assert_close(sort(z_bp), sort([-25j, -9j, 0, +9j, +25j])) + xp_assert_close(sort(p_bp), sort([-3 + 6j*sqrt(6), + -3 - 6j*sqrt(6), + +2j+sqrt(-8j-225)-2, + -2j+sqrt(+8j-225)-2, + +2j-sqrt(-8j-225)-2, + -2j-sqrt(+8j-225)-2, ])) + xp_assert_close(k_bp, 24.0) + + +class TestLp2bs_zpk: + + def test_basic(self): + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + + z_bs, p_bs, k_bs = lp2bs_zpk(z, p, k, 35, 12) + + xp_assert_close(sort(z_bs), sort([+35j, -35j, + +3j+sqrt(1234)*1j, + -3j+sqrt(1234)*1j, + +3j-sqrt(1234)*1j, + -3j-sqrt(1234)*1j])) + xp_assert_close(sort(p_bs), sort([+3j*sqrt(129) - 8, + -3j*sqrt(129) - 8, + (-6 + 6j) - sqrt(-1225 - 72j), + (-6 - 6j) - sqrt(-1225 + 72j), + (-6 + 6j) + sqrt(-1225 - 72j), + (-6 - 6j) + sqrt(-1225 + 72j), ])) + xp_assert_close(k_bs, 32.0) + + +class TestBilinear_zpk: + + def test_basic(self): + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + + z_d, p_d, k_d = bilinear_zpk(z, p, k, 10) + + xp_assert_close(sort(z_d), sort([(20-2j)/(20+2j), (20+2j)/(20-2j), + -1])) + xp_assert_close(sort(p_d), sort([77/83, + (1j/2 + 39/2) / (41/2 - 1j/2), + (39/2 - 1j/2) / (1j/2 + 41/2), ])) + xp_assert_close(k_d, 9696/69803) + + +class TestPrototypeType: + + def test_output_type(self): + # Prototypes should consistently output arrays, not lists + # https://github.com/scipy/scipy/pull/441 + for func in (buttap, + besselap, + lambda N: cheb1ap(N, 1), + lambda N: cheb2ap(N, 20), + lambda N: ellipap(N, 1, 20)): + for N in range(7): + z, p, k = func(N) + assert isinstance(z, np.ndarray) + assert isinstance(p, np.ndarray) + + +def dB(x): + # Return magnitude in decibels, avoiding divide-by-zero warnings + # (and deal with some "not less-ordered" errors when -inf shows up) + return 20 * np.log10(np.maximum(np.abs(x), np.finfo(np.float64).tiny)) + + +class TestButtord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'lowpass', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs) + + assert N == 16 + xp_assert_close(Wn, + 2.0002776782743284e-01, rtol=1e-15) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'highpass', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs) + + assert N == 18 + xp_assert_close(Wn, + 2.9996603079132672e-01, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'bandpass', False) + w, h = freqz(b, a) + w /= np.pi + + assert np.all((-rp - 0.1) < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < (-rs + 0.1)) + + assert N == 18 + xp_assert_close(Wn, [1.9998742411409134e-01, 5.0002139595676276e-01], + rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'bandstop', False) + w, h = freqz(b, a) + w /= np.pi + + assert np.all(-rp < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs) + + assert N == 20 + xp_assert_close(Wn, [1.4759432329294042e-01, 5.9997365985276407e-01], + rtol=1e-6) + + def test_analog(self): + wp = 200 + ws = 600 + rp = 3 + rs = 60 + N, Wn = buttord(wp, ws, rp, rs, True) + b, a = butter(N, Wn, 'lowpass', True) + w, h = freqs(b, a) + assert np.all(-rp < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs) + + assert N == 7 + xp_assert_close(Wn, 2.0006785355671877e+02, rtol=1e-15) + + n, Wn = buttord(1, 550/450, 1, 26, analog=True) + assert n == 19 + xp_assert_close(Wn, 1.0361980524629517, rtol=1e-15) + + xp_assert_equal(buttord(1, 1.2, 1, 80, analog=True)[0], 55) + + def test_fs_param(self): + wp = [4410, 11025] + ws = [2205, 13230] + rp = 3 + rs = 80 + fs = 44100 + N, Wn = buttord(wp, ws, rp, rs, False, fs=fs) + b, a = butter(N, Wn, 'bandpass', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 18 + xp_assert_close(Wn, [4409.722701715714, 11025.47178084662], + rtol=1e-15) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + buttord([20, 50], [14, 60], 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + buttord([20, 50], [14, 60], -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + buttord([20, 50], [14, 60], 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + @pytest.mark.thread_unsafe + def test_runtime_warnings(self): + msg = "Order is zero.*|divide by zero encountered" + with pytest.warns(RuntimeWarning, match=msg): + buttord(0.0, 1.0, 3, 60) + + def test_ellip_butter(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = buttord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 14 + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + buttord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestCheb1ord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'low', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, 0.2, rtol=1e-15) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'high', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, 0.3, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'band', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, [0.2, 0.5], rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'stop', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 10 + xp_assert_close(Wn, [0.14758232569947785, 0.6], rtol=1e-5) + + def test_analog(self): + wp = 700 + ws = 100 + rp = 3 + rs = 70 + N, Wn = cheb1ord(wp, ws, rp, rs, True) + b, a = cheby1(N, rp, Wn, 'high', True) + w, h = freqs(b, a) + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 4 + xp_assert_close(Wn, 700.0, rtol=1e-15) + + xp_assert_equal(cheb1ord(1, 1.2, 1, 80, analog=True)[0], 17) + + def test_fs_param(self): + wp = 4800 + ws = 7200 + rp = 3 + rs = 60 + fs = 48000 + N, Wn = cheb1ord(wp, ws, rp, rs, False, fs=fs) + b, a = cheby1(N, rp, Wn, 'low', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, 4800.0, rtol=1e-15) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + cheb1ord(0.2, 0.3, 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb1ord(0.2, 0.3, -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb1ord(0.2, 0.3, 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + def test_ellip_cheb1(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = cheb1ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 7 + + n2, w2 = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert not (wn == w2).all() + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + cheb1ord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestCheb2ord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'lp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, 0.28647639976553163, rtol=1e-15) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'hp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, 0.20697492182903282, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'bp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, [0.14876937565923479, 0.59748447842351482], + rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'bs', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 10 + xp_assert_close(Wn, [0.19926249974781743, 0.50125246585567362], + rtol=1e-6) + + def test_analog(self): + wp = [20, 50] + ws = [10, 60] + rp = 3 + rs = 80 + N, Wn = cheb2ord(wp, ws, rp, rs, True) + b, a = cheby2(N, rs, Wn, 'bp', True) + w, h = freqs(b, a) + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 11 + xp_assert_close(Wn, [1.673740595370124e+01, 5.974641487254268e+01], + rtol=1e-15) + + def test_fs_param(self): + wp = 150 + ws = 100 + rp = 3 + rs = 70 + fs = 1000 + N, Wn = cheb2ord(wp, ws, rp, rs, False, fs=fs) + b, a = cheby2(N, rs, Wn, 'hp', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, 103.4874609145164, rtol=1e-15) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb2ord([0.1, 0.6], [0.2, 0.5], -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb2ord([0.1, 0.6], [0.2, 0.5], 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + def test_ellip_cheb2(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 7 + + n1, w1 = cheb1ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert not (wn == w1).all() + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + cheb2ord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestEllipord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'lp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 5 + xp_assert_close(Wn, 0.2, rtol=1e-15) + + def test_lowpass_1000dB(self): + # failed when ellipkm1 wasn't used in ellipord and ellipap + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 1000 + N, Wn = ellipord(wp, ws, rp, rs, False) + sos = ellip(N, rp, rs, Wn, 'lp', False, output='sos') + w, h = freqz_sos(sos) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'hp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 6 + xp_assert_close(Wn, 0.3, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'bp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 6 + xp_assert_close(Wn, [0.2, 0.5], rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'bs', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 7 + xp_assert_close(Wn, [0.14758232794342988, 0.6], rtol=1e-5) + + def test_analog(self): + wp = [1000, 6000] + ws = [2000, 5000] + rp = 3 + rs = 90 + N, Wn = ellipord(wp, ws, rp, rs, True) + b, a = ellip(N, rp, rs, Wn, 'bs', True) + w, h = freqs(b, a) + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, [1666.6666, 6000]) + + assert ellipord(1, 1.2, 1, 80, analog=True)[0] == 9 + + def test_fs_param(self): + wp = [400, 2400] + ws = [800, 2000] + rp = 3 + rs = 90 + fs = 8000 + N, Wn = ellipord(wp, ws, rp, rs, False, fs=fs) + b, a = ellip(N, rp, rs, Wn, 'bs', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 7 + xp_assert_close(Wn, [590.3293117737195, 2400], rtol=1e-5) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + ellipord(0.2, 0.5, 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + ellipord(0.2, 0.5, -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + ellipord(0.2, 0.5, 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + def test_ellip_butter(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = ellipord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 5 + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + ellipord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestBessel: + + def test_degenerate(self): + for norm in ('delay', 'phase', 'mag'): + # 0-order filter is just a passthrough + b, a = bessel(0, 1, analog=True, norm=norm) + xp_assert_equal(b, np.asarray([1.0])) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = bessel(1, 1, analog=True, norm=norm) + xp_assert_close(b, np.asarray([1.0]), rtol=1e-15) + xp_assert_close(a, np.asarray([1.0, 1]), rtol=1e-15) + + z, p, k = bessel(1, 0.3, analog=True, output='zpk', norm=norm) + xp_assert_equal(z, np.asarray([])) + xp_assert_close(p, np.asarray([-0.3+0j]), rtol=1e-14) + xp_assert_close(k, 0.3, rtol=1e-14) + + def test_high_order(self): + # high even order, 'phase' + z, p, k = bessel(24, 100, analog=True, output='zpk') + z2 = [] + p2 = [ + -9.055312334014323e+01 + 4.844005815403969e+00j, + -8.983105162681878e+01 + 1.454056170018573e+01j, + -8.837357994162065e+01 + 2.426335240122282e+01j, + -8.615278316179575e+01 + 3.403202098404543e+01j, + -8.312326467067703e+01 + 4.386985940217900e+01j, + -7.921695461084202e+01 + 5.380628489700191e+01j, + -7.433392285433246e+01 + 6.388084216250878e+01j, + -6.832565803501586e+01 + 7.415032695116071e+01j, + -6.096221567378025e+01 + 8.470292433074425e+01j, + -5.185914574820616e+01 + 9.569048385258847e+01j, + -4.027853855197555e+01 + 1.074195196518679e+02j, + -2.433481337524861e+01 + 1.207298683731973e+02j, + ] + k2 = 9.999999999999989e+47 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + xp_assert_close(k, k2, rtol=1e-14) + + # high odd order, 'phase' + z, p, k = bessel(23, 1000, analog=True, output='zpk') + z2 = [] + p2 = [ + -2.497697202208956e+02 + 1.202813187870698e+03j, + -4.126986617510172e+02 + 1.065328794475509e+03j, + -5.304922463809596e+02 + 9.439760364018479e+02j, + -9.027564978975828e+02 + 1.010534334242318e+02j, + -8.909283244406079e+02 + 2.023024699647598e+02j, + -8.709469394347836e+02 + 3.039581994804637e+02j, + -8.423805948131370e+02 + 4.062657947488952e+02j, + -8.045561642249877e+02 + 5.095305912401127e+02j, + -7.564660146766259e+02 + 6.141594859516342e+02j, + -6.965966033906477e+02 + 7.207341374730186e+02j, + -6.225903228776276e+02 + 8.301558302815096e+02j, + -9.066732476324988e+02] + k2 = 9.999999999999983e+68 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + xp_assert_close(k, k2, rtol=1e-14) + + # high even order, 'delay' (Orchard 1965 "The Roots of the + # Maximally Flat-Delay Polynomials" Table 1) + z, p, k = bessel(31, 1, analog=True, output='zpk', norm='delay') + p2 = [-20.876706, + -20.826543 + 1.735732j, + -20.675502 + 3.473320j, + -20.421895 + 5.214702j, + -20.062802 + 6.961982j, + -19.593895 + 8.717546j, + -19.009148 + 10.484195j, + -18.300400 + 12.265351j, + -17.456663 + 14.065350j, + -16.463032 + 15.889910j, + -15.298849 + 17.746914j, + -13.934466 + 19.647827j, + -12.324914 + 21.610519j, + -10.395893 + 23.665701j, + - 8.005600 + 25.875019j, + - 4.792045 + 28.406037j, + ] + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + + # high odd order, 'delay' + z, p, k = bessel(30, 1, analog=True, output='zpk', norm='delay') + p2 = [-20.201029 + 0.867750j, + -20.097257 + 2.604235j, + -19.888485 + 4.343721j, + -19.572188 + 6.088363j, + -19.144380 + 7.840570j, + -18.599342 + 9.603147j, + -17.929195 + 11.379494j, + -17.123228 + 13.173901j, + -16.166808 + 14.992008j, + -15.039580 + 16.841580j, + -13.712245 + 18.733902j, + -12.140295 + 20.686563j, + -10.250119 + 22.729808j, + - 7.901170 + 24.924391j, + - 4.734679 + 27.435615j, + ] + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + + def test_refs(self): + # Compare to http://www.crbond.com/papers/bsf2.pdf + # "Delay Normalized Bessel Polynomial Coefficients" + bond_b = np.asarray([10395.0]) + bond_a = np.asarray([1.0, 21, 210, 1260, 4725, 10395, 10395]) + b, a = bessel(6, 1, norm='delay', analog=True) + xp_assert_close(b, bond_b) + xp_assert_close(a, bond_a) + + # "Delay Normalized Bessel Pole Locations" + bond_poles = { + 1: [-1.0000000000], + 2: [-1.5000000000 + 0.8660254038j], + 3: [-1.8389073227 + 1.7543809598j, -2.3221853546], + 4: [-2.1037893972 + 2.6574180419j, -2.8962106028 + 0.8672341289j], + 5: [-2.3246743032 + 3.5710229203j, -3.3519563992 + 1.7426614162j, + -3.6467385953], + 6: [-2.5159322478 + 4.4926729537j, -3.7357083563 + 2.6262723114j, + -4.2483593959 + 0.8675096732j], + 7: [-2.6856768789 + 5.4206941307j, -4.0701391636 + 3.5171740477j, + -4.7582905282 + 1.7392860611j, -4.9717868585], + 8: [-2.8389839489 + 6.3539112986j, -4.3682892172 + 4.4144425005j, + -5.2048407906 + 2.6161751526j, -5.5878860433 + 0.8676144454j], + 9: [-2.9792607982 + 7.2914636883j, -4.6384398872 + 5.3172716754j, + -5.6044218195 + 3.4981569179j, -6.1293679043 + 1.7378483835j, + -6.2970191817], + 10: [-3.1089162336 + 8.2326994591j, -4.8862195669 + 6.2249854825j, + -5.9675283286 + 4.3849471889j, -6.6152909655 + 2.6115679208j, + -6.9220449054 + 0.8676651955j] + } + + for N in range(1, 11): + p1 = np.sort(bond_poles[N]) + p2 = np.sort(np.concatenate(_cplxreal(besselap(N, 'delay')[1]))) + assert_array_almost_equal(p1, p2, decimal=10) + + # "Frequency Normalized Bessel Pole Locations" + bond_poles = { + 1: [-1.0000000000], + 2: [-1.1016013306 + 0.6360098248j], + 3: [-1.0474091610 + 0.9992644363j, -1.3226757999], + 4: [-0.9952087644 + 1.2571057395j, -1.3700678306 + 0.4102497175j], + 5: [-0.9576765486 + 1.4711243207j, -1.3808773259 + 0.7179095876j, + -1.5023162714], + 6: [-0.9306565229 + 1.6618632689j, -1.3818580976 + 0.9714718907j, + -1.5714904036 + 0.3208963742j], + 7: [-0.9098677806 + 1.8364513530j, -1.3789032168 + 1.1915667778j, + -1.6120387662 + 0.5892445069j, -1.6843681793], + 8: [-0.8928697188 + 1.9983258436j, -1.3738412176 + 1.3883565759j, + -1.6369394181 + 0.8227956251j, -1.7574084004 + 0.2728675751j], + 9: [-0.8783992762 + 2.1498005243j, -1.3675883098 + 1.5677337122j, + -1.6523964846 + 1.0313895670j, -1.8071705350 + 0.5123837306j, + -1.8566005012], + 10: [-0.8657569017 + 2.2926048310j, -1.3606922784 + 1.7335057427j, + -1.6618102414 + 1.2211002186j, -1.8421962445 + 0.7272575978j, + -1.9276196914 + 0.2416234710j] + } + + for N in range(1, 11): + p1 = np.sort(bond_poles[N]) + p2 = np.sort(np.concatenate(_cplxreal(besselap(N, 'mag')[1]))) + assert_array_almost_equal(p1, p2, decimal=10) + + # Compare to https://www.ranecommercial.com/legacy/note147.html + # "Table 1 - Bessel Crossovers of Second, Third, and Fourth-Order" + a = np.asarray([1, 1, 1/3]) + b2, a2 = bessel(2, 1, norm='delay', analog=True) + xp_assert_close(a[::-1], a2/b2) + + a = np.asarray([1, 1, 2/5, 1/15]) + b2, a2 = bessel(3, 1, norm='delay', analog=True) + xp_assert_close(a[::-1], a2/b2) + + a = np.asarray([1, 1, 9/21, 2/21, 1/105]) + b2, a2 = bessel(4, 1, norm='delay', analog=True) + xp_assert_close(a[::-1], a2/b2) + + a = np.asarray([1, np.sqrt(3), 1]) + b2, a2 = bessel(2, 1, norm='phase', analog=True) + xp_assert_close(a[::-1], a2/b2) + + # TODO: Why so inaccurate? Is reference flawed? + a = np.asarray([1, 2.481, 2.463, 1.018]) + b2, a2 = bessel(3, 1, norm='phase', analog=True) + assert_array_almost_equal(a[::-1], a2/b2, decimal=1) + + # TODO: Why so inaccurate? Is reference flawed? + a = np.asarray([1, 3.240, 4.5, 3.240, 1.050]) + b2, a2 = bessel(4, 1, norm='phase', analog=True) + assert_array_almost_equal(a[::-1], a2/b2, decimal=1) + + # Table of -3 dB factors: + N, scale = 2, np.asarray([1.272, 1.272], dtype=np.complex128) + scale2 = besselap(N, 'mag')[1] / besselap(N, 'phase')[1] + assert_array_almost_equal(scale2, scale, decimal=3) + + # TODO: Why so inaccurate? Is reference flawed? + N, scale = 3, np.asarray([1.413, 1.413, 1.413], dtype=np.complex128) + scale2 = besselap(N, 'mag')[1] / besselap(N, 'phase')[1] + assert_array_almost_equal(scale2, scale, decimal=2) + + # TODO: Why so inaccurate? Is reference flawed? + N, scale = 4, np.asarray([1.533]*4, dtype=np.complex128) + scale2 = besselap(N, 'mag')[1] / besselap(N, 'phase')[1] + assert_array_almost_equal(scale, scale2, decimal=1) + + def test_hardcoded(self): + # Compare to values from original hardcoded implementation + originals = { + 0: [], + 1: [-1], + 2: [-.8660254037844386467637229 + .4999999999999999999999996j], + 3: [-.9416000265332067855971980, + -.7456403858480766441810907 + .7113666249728352680992154j], + 4: [-.6572111716718829545787788 + .8301614350048733772399715j, + -.9047587967882449459642624 + .2709187330038746636700926j], + 5: [-.9264420773877602247196260, + -.8515536193688395541722677 + .4427174639443327209850002j, + -.5905759446119191779319432 + .9072067564574549539291747j], + 6: [-.9093906830472271808050953 + .1856964396793046769246397j, + -.7996541858328288520243325 + .5621717346937317988594118j, + -.5385526816693109683073792 + .9616876881954277199245657j], + 7: [-.9194871556490290014311619, + -.8800029341523374639772340 + .3216652762307739398381830j, + -.7527355434093214462291616 + .6504696305522550699212995j, + -.4966917256672316755024763 + 1.002508508454420401230220j], + 8: [-.9096831546652910216327629 + .1412437976671422927888150j, + -.8473250802359334320103023 + .4259017538272934994996429j, + -.7111381808485399250796172 + .7186517314108401705762571j, + -.4621740412532122027072175 + 1.034388681126901058116589j], + 9: [-.9154957797499037686769223, + -.8911217017079759323183848 + .2526580934582164192308115j, + -.8148021112269012975514135 + .5085815689631499483745341j, + -.6743622686854761980403401 + .7730546212691183706919682j, + -.4331415561553618854685942 + 1.060073670135929666774323j], + 10: [-.9091347320900502436826431 + .1139583137335511169927714j, + -.8688459641284764527921864 + .3430008233766309973110589j, + -.7837694413101441082655890 + .5759147538499947070009852j, + -.6417513866988316136190854 + .8175836167191017226233947j, + -.4083220732868861566219785 + 1.081274842819124562037210j], + 11: [-.9129067244518981934637318, + -.8963656705721166099815744 + .2080480375071031919692341j, + -.8453044014712962954184557 + .4178696917801248292797448j, + -.7546938934722303128102142 + .6319150050721846494520941j, + -.6126871554915194054182909 + .8547813893314764631518509j, + -.3868149510055090879155425 + 1.099117466763120928733632j], + 12: [-.9084478234140682638817772 + 95506365213450398415258360e-27j, + -.8802534342016826507901575 + .2871779503524226723615457j, + -.8217296939939077285792834 + .4810212115100676440620548j, + -.7276681615395159454547013 + .6792961178764694160048987j, + -.5866369321861477207528215 + .8863772751320727026622149j, + -.3679640085526312839425808 + 1.114373575641546257595657j], + 13: [-.9110914665984182781070663, + -.8991314665475196220910718 + .1768342956161043620980863j, + -.8625094198260548711573628 + .3547413731172988997754038j, + -.7987460692470972510394686 + .5350752120696801938272504j, + -.7026234675721275653944062 + .7199611890171304131266374j, + -.5631559842430199266325818 + .9135900338325109684927731j, + -.3512792323389821669401925 + 1.127591548317705678613239j], + 14: [-.9077932138396487614720659 + 82196399419401501888968130e-27j, + -.8869506674916445312089167 + .2470079178765333183201435j, + -.8441199160909851197897667 + .4131653825102692595237260j, + -.7766591387063623897344648 + .5819170677377608590492434j, + -.6794256425119233117869491 + .7552857305042033418417492j, + -.5418766775112297376541293 + .9373043683516919569183099j, + -.3363868224902037330610040 + 1.139172297839859991370924j], + 15: [-.9097482363849064167228581, + -.9006981694176978324932918 + .1537681197278439351298882j, + -.8731264620834984978337843 + .3082352470564267657715883j, + -.8256631452587146506294553 + .4642348752734325631275134j, + -.7556027168970728127850416 + .6229396358758267198938604j, + -.6579196593110998676999362 + .7862895503722515897065645j, + -.5224954069658330616875186 + .9581787261092526478889345j, + -.3229963059766444287113517 + 1.149416154583629539665297j], + 16: [-.9072099595087001356491337 + 72142113041117326028823950e-27j, + -.8911723070323647674780132 + .2167089659900576449410059j, + -.8584264231521330481755780 + .3621697271802065647661080j, + -.8074790293236003885306146 + .5092933751171800179676218j, + -.7356166304713115980927279 + .6591950877860393745845254j, + -.6379502514039066715773828 + .8137453537108761895522580j, + -.5047606444424766743309967 + .9767137477799090692947061j, + -.3108782755645387813283867 + 1.158552841199330479412225j], + 17: [-.9087141161336397432860029, + -.9016273850787285964692844 + .1360267995173024591237303j, + -.8801100704438627158492165 + .2725347156478803885651973j, + -.8433414495836129204455491 + .4100759282910021624185986j, + -.7897644147799708220288138 + .5493724405281088674296232j, + -.7166893842372349049842743 + .6914936286393609433305754j, + -.6193710717342144521602448 + .8382497252826992979368621j, + -.4884629337672704194973683 + .9932971956316781632345466j, + -.2998489459990082015466971 + 1.166761272925668786676672j], + 18: [-.9067004324162775554189031 + 64279241063930693839360680e-27j, + -.8939764278132455733032155 + .1930374640894758606940586j, + -.8681095503628830078317207 + .3224204925163257604931634j, + -.8281885016242836608829018 + .4529385697815916950149364j, + -.7726285030739558780127746 + .5852778162086640620016316j, + -.6987821445005273020051878 + .7204696509726630531663123j, + -.6020482668090644386627299 + .8602708961893664447167418j, + -.4734268069916151511140032 + 1.008234300314801077034158j, + -.2897592029880489845789953 + 1.174183010600059128532230j], + 19: [-.9078934217899404528985092, + -.9021937639390660668922536 + .1219568381872026517578164j, + -.8849290585034385274001112 + .2442590757549818229026280j, + -.8555768765618421591093993 + .3672925896399872304734923j, + -.8131725551578197705476160 + .4915365035562459055630005j, + -.7561260971541629355231897 + .6176483917970178919174173j, + -.6818424412912442033411634 + .7466272357947761283262338j, + -.5858613321217832644813602 + .8801817131014566284786759j, + -.4595043449730988600785456 + 1.021768776912671221830298j, + -.2804866851439370027628724 + 1.180931628453291873626003j], + 20: [-.9062570115576771146523497 + 57961780277849516990208850e-27j, + -.8959150941925768608568248 + .1740317175918705058595844j, + -.8749560316673332850673214 + .2905559296567908031706902j, + -.8427907479956670633544106 + .4078917326291934082132821j, + -.7984251191290606875799876 + .5264942388817132427317659j, + -.7402780309646768991232610 + .6469975237605228320268752j, + -.6658120544829934193890626 + .7703721701100763015154510j, + -.5707026806915714094398061 + .8982829066468255593407161j, + -.4465700698205149555701841 + 1.034097702560842962315411j, + -.2719299580251652601727704 + 1.187099379810885886139638j], + 21: [-.9072262653142957028884077, + -.9025428073192696303995083 + .1105252572789856480992275j, + -.8883808106664449854431605 + .2213069215084350419975358j, + -.8643915813643204553970169 + .3326258512522187083009453j, + -.8299435470674444100273463 + .4448177739407956609694059j, + -.7840287980408341576100581 + .5583186348022854707564856j, + -.7250839687106612822281339 + .6737426063024382240549898j, + -.6506315378609463397807996 + .7920349342629491368548074j, + -.5564766488918562465935297 + .9148198405846724121600860j, + -.4345168906815271799687308 + 1.045382255856986531461592j, + -.2640041595834031147954813 + 1.192762031948052470183960j], + 22: [-.9058702269930872551848625 + 52774908289999045189007100e-27j, + -.8972983138153530955952835 + .1584351912289865608659759j, + -.8799661455640176154025352 + .2644363039201535049656450j, + -.8534754036851687233084587 + .3710389319482319823405321j, + -.8171682088462720394344996 + .4785619492202780899653575j, + -.7700332930556816872932937 + .5874255426351153211965601j, + -.7105305456418785989070935 + .6982266265924524000098548j, + -.6362427683267827226840153 + .8118875040246347267248508j, + -.5430983056306302779658129 + .9299947824439872998916657j, + -.4232528745642628461715044 + 1.055755605227545931204656j, + -.2566376987939318038016012 + 1.197982433555213008346532j], + 23: [-.9066732476324988168207439, + -.9027564979912504609412993 + .1010534335314045013252480j, + -.8909283242471251458653994 + .2023024699381223418195228j, + -.8709469395587416239596874 + .3039581993950041588888925j, + -.8423805948021127057054288 + .4062657948237602726779246j, + -.8045561642053176205623187 + .5095305912227258268309528j, + -.7564660146829880581478138 + .6141594859476032127216463j, + -.6965966033912705387505040 + .7207341374753046970247055j, + -.6225903228771341778273152 + .8301558302812980678845563j, + -.5304922463810191698502226 + .9439760364018300083750242j, + -.4126986617510148836149955 + 1.065328794475513585531053j, + -.2497697202208956030229911 + 1.202813187870697831365338j], + 24: [-.9055312363372773709269407 + 48440066540478700874836350e-27j, + -.8983105104397872954053307 + .1454056133873610120105857j, + -.8837358034555706623131950 + .2426335234401383076544239j, + -.8615278304016353651120610 + .3403202112618624773397257j, + -.8312326466813240652679563 + .4386985933597305434577492j, + -.7921695462343492518845446 + .5380628490968016700338001j, + -.7433392285088529449175873 + .6388084216222567930378296j, + -.6832565803536521302816011 + .7415032695091650806797753j, + -.6096221567378335562589532 + .8470292433077202380020454j, + -.5185914574820317343536707 + .9569048385259054576937721j, + -.4027853855197518014786978 + 1.074195196518674765143729j, + -.2433481337524869675825448 + 1.207298683731972524975429j], + 25: [-.9062073871811708652496104, + -.9028833390228020537142561 + 93077131185102967450643820e-27j, + -.8928551459883548836774529 + .1863068969804300712287138j, + -.8759497989677857803656239 + .2798521321771408719327250j, + -.8518616886554019782346493 + .3738977875907595009446142j, + -.8201226043936880253962552 + .4686668574656966589020580j, + -.7800496278186497225905443 + .5644441210349710332887354j, + -.7306549271849967721596735 + .6616149647357748681460822j, + -.6704827128029559528610523 + .7607348858167839877987008j, + -.5972898661335557242320528 + .8626676330388028512598538j, + -.5073362861078468845461362 + .9689006305344868494672405j, + -.3934529878191079606023847 + 1.082433927173831581956863j, + -.2373280669322028974199184 + 1.211476658382565356579418j], + } + for N in originals: + p1 = sorted(np.union1d(originals[N], + np.conj(originals[N])), key=np.imag) + p2 = sorted(besselap(N)[1], key=np.imag) + xp_assert_close(p1, + p2, rtol=1e-14, check_dtype=False) + + def test_norm_phase(self): + # Test some orders and frequencies and see that they have the right + # phase at w0 + for N in (1, 2, 3, 4, 5, 51, 72): + for w0 in (1, 100): + b, a = bessel(N, w0, analog=True, norm='phase') + w = np.linspace(0, w0, 100) + w, h = freqs(b, a, w) + phase = np.unwrap(np.angle(h)) + xp_assert_close(phase[[0, -1]], (0, -N*pi/4), rtol=1e-1) + + def test_norm_mag(self): + # Test some orders and frequencies and see that they have the right + # mag at w0 + for N in (1, 2, 3, 4, 5, 51, 72): + for w0 in (1, 100): + b, a = bessel(N, w0, analog=True, norm='mag') + w = (0, w0) + w, h = freqs(b, a, w) + mag = abs(h) + xp_assert_close(mag, (1, 1/np.sqrt(2))) + + def test_norm_delay(self): + # Test some orders and frequencies and see that they have the right + # delay at DC + for N in (1, 2, 3, 4, 5, 51, 72): + for w0 in (1, 100): + b, a = bessel(N, w0, analog=True, norm='delay') + w = np.linspace(0, 10*w0, 1000) + w, h = freqs(b, a, w) + delay = -np.diff(np.unwrap(np.angle(h)))/np.diff(w) + xp_assert_close(delay[0], 1/w0, rtol=1e-4) + + def test_norm_factor(self): + mpmath_values = { + 1: 1.0, 2: 1.361654128716130520, 3: 1.755672368681210649, + 4: 2.113917674904215843, 5: 2.427410702152628137, + 6: 2.703395061202921876, 7: 2.951722147038722771, + 8: 3.179617237510651330, 9: 3.391693138911660101, + 10: 3.590980594569163482, 11: 3.779607416439620092, + 12: 3.959150821144285315, 13: 4.130825499383535980, + 14: 4.295593409533637564, 15: 4.454233021624377494, + 16: 4.607385465472647917, 17: 4.755586548961147727, + 18: 4.899289677284488007, 19: 5.038882681488207605, + 20: 5.174700441742707423, 21: 5.307034531360917274, + 22: 5.436140703250035999, 23: 5.562244783787878196, + 24: 5.685547371295963521, 25: 5.806227623775418541, + 50: 8.268963160013226298, 51: 8.352374541546012058, + } + for N in mpmath_values: + z, p, k = besselap(N, 'delay') + xp_assert_close(mpmath_values[N], _norm_factor(p, k), rtol=1e-13) + + def test_bessel_poly(self): + xp_assert_equal(_bessel_poly(5), [945, 945, 420, 105, 15, 1]) + xp_assert_equal(_bessel_poly(4, True), [1, 10, 45, 105, 105]) + + def test_bessel_zeros(self): + xp_assert_equal(_bessel_zeros(0), []) + + def test_invalid(self): + assert_raises(ValueError, besselap, 5, 'nonsense') + assert_raises(ValueError, besselap, -5) + assert_raises(ValueError, besselap, 3.2) + assert_raises(ValueError, _bessel_poly, -3) + assert_raises(ValueError, _bessel_poly, 3.3) + + @pytest.mark.fail_slow(10) + def test_fs_param(self): + for norm in ('phase', 'mag', 'delay'): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = bessel(N, fc, btype, norm=norm, fs=fs) + ba2 = bessel(N, fc/(fs/2), btype, norm=norm) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = bessel(N, fc, btype, norm=norm, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = bessel(N, fcnorm, btype, norm=norm) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + + +class TestButter: + + def test_degenerate(self): + # 0-order filter is just a passthrough + b, a = butter(0, 1, analog=True) + xp_assert_equal(b, np.asarray([1.0])) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = butter(1, 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = butter(1, 0.3, output='zpk') + xp_assert_equal(z, np.asarray([-1.0])) + xp_assert_close(p, [3.249196962329063e-01 + 0j], rtol=1e-14) + xp_assert_close(k, 3.375401518835469e-01, rtol=1e-14) + + def test_basic(self): + # analog s-plane + for N in range(25): + wn = 0.01 + z, p, k = butter(N, wn, 'low', analog=True, output='zpk') + assert_array_almost_equal([], z) + assert len(p) == N + # All poles should be at distance wn from origin + assert_array_almost_equal(abs(p), np.asarray(wn)) + assert all(np.real(p) <= 0) # No poles in right half of S-plane + assert_array_almost_equal(wn**N, k) + + # digital z-plane + for N in range(25): + wn = 0.01 + z, p, k = butter(N, wn, 'high', analog=False, output='zpk') + xp_assert_equal(np.ones(N), z) # All zeros exactly at DC + assert all(np.abs(p) <= 1) # No poles outside unit circle + + b1, a1 = butter(2, 1, analog=True) + assert_array_almost_equal(b1, [1]) + assert_array_almost_equal(a1, [1, np.sqrt(2), 1]) + + b2, a2 = butter(5, 1, analog=True) + assert_array_almost_equal(b2, [1]) + assert_array_almost_equal(a2, [1, 3.2361, 5.2361, + 5.2361, 3.2361, 1], decimal=4) + + b3, a3 = butter(10, 1, analog=True) + assert_array_almost_equal(b3, [1]) + assert_array_almost_equal(a3, [1, 6.3925, 20.4317, 42.8021, 64.8824, + 74.2334, 64.8824, 42.8021, 20.4317, + 6.3925, 1], decimal=4) + + b2, a2 = butter(19, 1.0441379169150726, analog=True) + assert_array_almost_equal(b2, [2.2720], decimal=4) + assert_array_almost_equal(a2, 1.0e+004 * np.array([ + 0.0001, 0.0013, 0.0080, 0.0335, 0.1045, 0.2570, + 0.5164, 0.8669, 1.2338, 1.5010, 1.5672, 1.4044, + 1.0759, 0.6986, 0.3791, 0.1681, 0.0588, 0.0153, + 0.0026, 0.0002]), decimal=0) + + b, a = butter(5, 0.4) + assert_array_almost_equal(b, [0.0219, 0.1097, 0.2194, + 0.2194, 0.1097, 0.0219], decimal=4) + assert_array_almost_equal(a, [1.0000, -0.9853, 0.9738, + -0.3864, 0.1112, -0.0113], decimal=4) + + def test_highpass(self): + # highpass, high even order + z, p, k = butter(28, 0.43, 'high', output='zpk') + z2 = np.ones(28) + p2 = [ + 2.068257195514592e-01 + 9.238294351481734e-01j, + 2.068257195514592e-01 - 9.238294351481734e-01j, + 1.874933103892023e-01 + 8.269455076775277e-01j, + 1.874933103892023e-01 - 8.269455076775277e-01j, + 1.717435567330153e-01 + 7.383078571194629e-01j, + 1.717435567330153e-01 - 7.383078571194629e-01j, + 1.588266870755982e-01 + 6.564623730651094e-01j, + 1.588266870755982e-01 - 6.564623730651094e-01j, + 1.481881532502603e-01 + 5.802343458081779e-01j, + 1.481881532502603e-01 - 5.802343458081779e-01j, + 1.394122576319697e-01 + 5.086609000582009e-01j, + 1.394122576319697e-01 - 5.086609000582009e-01j, + 1.321840881809715e-01 + 4.409411734716436e-01j, + 1.321840881809715e-01 - 4.409411734716436e-01j, + 1.262633413354405e-01 + 3.763990035551881e-01j, + 1.262633413354405e-01 - 3.763990035551881e-01j, + 1.214660449478046e-01 + 3.144545234797277e-01j, + 1.214660449478046e-01 - 3.144545234797277e-01j, + 1.104868766650320e-01 + 2.771505404367791e-02j, + 1.104868766650320e-01 - 2.771505404367791e-02j, + 1.111768629525075e-01 + 8.331369153155753e-02j, + 1.111768629525075e-01 - 8.331369153155753e-02j, + 1.125740630842972e-01 + 1.394219509611784e-01j, + 1.125740630842972e-01 - 1.394219509611784e-01j, + 1.147138487992747e-01 + 1.963932363793666e-01j, + 1.147138487992747e-01 - 1.963932363793666e-01j, + 1.176516491045901e-01 + 2.546021573417188e-01j, + 1.176516491045901e-01 - 2.546021573417188e-01j, + ] + k2 = 1.446671081817286e-06 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-7) + xp_assert_close(k, k2, rtol=1e-10) + + # highpass, high odd order + z, p, k = butter(27, 0.56, 'high', output='zpk') + z2 = np.ones(27) + p2 = [ + -1.772572785680147e-01 + 9.276431102995948e-01j, + -1.772572785680147e-01 - 9.276431102995948e-01j, + -1.600766565322114e-01 + 8.264026279893268e-01j, + -1.600766565322114e-01 - 8.264026279893268e-01j, + -1.461948419016121e-01 + 7.341841939120078e-01j, + -1.461948419016121e-01 - 7.341841939120078e-01j, + -1.348975284762046e-01 + 6.493235066053785e-01j, + -1.348975284762046e-01 - 6.493235066053785e-01j, + -1.256628210712206e-01 + 5.704921366889227e-01j, + -1.256628210712206e-01 - 5.704921366889227e-01j, + -1.181038235962314e-01 + 4.966120551231630e-01j, + -1.181038235962314e-01 - 4.966120551231630e-01j, + -1.119304913239356e-01 + 4.267938916403775e-01j, + -1.119304913239356e-01 - 4.267938916403775e-01j, + -1.069237739782691e-01 + 3.602914879527338e-01j, + -1.069237739782691e-01 - 3.602914879527338e-01j, + -1.029178030691416e-01 + 2.964677964142126e-01j, + -1.029178030691416e-01 - 2.964677964142126e-01j, + -9.978747500816100e-02 + 2.347687643085738e-01j, + -9.978747500816100e-02 - 2.347687643085738e-01j, + -9.743974496324025e-02 + 1.747028739092479e-01j, + -9.743974496324025e-02 - 1.747028739092479e-01j, + -9.580754551625957e-02 + 1.158246860771989e-01j, + -9.580754551625957e-02 - 1.158246860771989e-01j, + -9.484562207782568e-02 + 5.772118357151691e-02j, + -9.484562207782568e-02 - 5.772118357151691e-02j, + -9.452783117928215e-02 + ] + k2 = 9.585686688851069e-09 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-8) + xp_assert_close(k, k2) + + def test_bandpass(self): + z, p, k = butter(8, [0.25, 0.33], 'band', output='zpk') + z2 = [1, 1, 1, 1, 1, 1, 1, 1, + -1, -1, -1, -1, -1, -1, -1, -1] + p2 = [ + 4.979909925436156e-01 + 8.367609424799387e-01j, + 4.979909925436156e-01 - 8.367609424799387e-01j, + 4.913338722555539e-01 + 7.866774509868817e-01j, + 4.913338722555539e-01 - 7.866774509868817e-01j, + 5.035229361778706e-01 + 7.401147376726750e-01j, + 5.035229361778706e-01 - 7.401147376726750e-01j, + 5.307617160406101e-01 + 7.029184459442954e-01j, + 5.307617160406101e-01 - 7.029184459442954e-01j, + 5.680556159453138e-01 + 6.788228792952775e-01j, + 5.680556159453138e-01 - 6.788228792952775e-01j, + 6.100962560818854e-01 + 6.693849403338664e-01j, + 6.100962560818854e-01 - 6.693849403338664e-01j, + 6.904694312740631e-01 + 6.930501690145245e-01j, + 6.904694312740631e-01 - 6.930501690145245e-01j, + 6.521767004237027e-01 + 6.744414640183752e-01j, + 6.521767004237027e-01 - 6.744414640183752e-01j, + ] + k2 = 3.398854055800844e-08 + xp_assert_equal(z, z2, check_dtype=False) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-13) + + # bandpass analog + z, p, k = butter(4, [90.5, 110.5], 'bp', analog=True, output='zpk') + z2 = np.zeros(4, dtype=z.dtype) + p2 = [ + -4.179137760733086e+00 + 1.095935899082837e+02j, + -4.179137760733086e+00 - 1.095935899082837e+02j, + -9.593598668443835e+00 + 1.034745398029734e+02j, + -9.593598668443835e+00 - 1.034745398029734e+02j, + -8.883991981781929e+00 + 9.582087115567160e+01j, + -8.883991981781929e+00 - 9.582087115567160e+01j, + -3.474530886568715e+00 + 9.111599925805801e+01j, + -3.474530886568715e+00 - 9.111599925805801e+01j, + ] + k2 = 1.600000000000001e+05 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag)) + xp_assert_close(k, k2, rtol=1e-15) + + def test_bandstop(self): + z, p, k = butter(7, [0.45, 0.56], 'stop', output='zpk') + z2 = [-1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j] + p2 = [-1.766850742887729e-01 + 9.466951258673900e-01j, + -1.766850742887729e-01 - 9.466951258673900e-01j, + 1.467897662432886e-01 + 9.515917126462422e-01j, + 1.467897662432886e-01 - 9.515917126462422e-01j, + -1.370083529426906e-01 + 8.880376681273993e-01j, + -1.370083529426906e-01 - 8.880376681273993e-01j, + 1.086774544701390e-01 + 8.915240810704319e-01j, + 1.086774544701390e-01 - 8.915240810704319e-01j, + -7.982704457700891e-02 + 8.506056315273435e-01j, + -7.982704457700891e-02 - 8.506056315273435e-01j, + 5.238812787110331e-02 + 8.524011102699969e-01j, + 5.238812787110331e-02 - 8.524011102699969e-01j, + -1.357545000491310e-02 + 8.382287744986582e-01j, + -1.357545000491310e-02 - 8.382287744986582e-01j] + k2 = 4.577122512960063e-01 + xp_assert_close(sorted(z, key=np.imag), + sorted(z2, key=np.imag)) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag)) + xp_assert_close(k, k2, rtol=1e-14) + + def test_ba_output(self): + b, a = butter(4, [100, 300], 'bandpass', analog=True) + b2 = [1.6e+09, 0, 0, 0, 0] + a2 = [1.000000000000000e+00, 5.226251859505511e+02, + 2.565685424949238e+05, 6.794127417357160e+07, + 1.519411254969542e+10, 2.038238225207147e+12, + 2.309116882454312e+14, 1.411088002066486e+16, + 8.099999999999991e+17] + xp_assert_close(b, b2, rtol=1e-14) + xp_assert_close(a, a2, rtol=1e-14) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = butter(N, fc, btype, fs=fs) + ba2 = butter(N, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = butter(N, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = butter(N, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + + +class TestCheby1: + + def test_degenerate(self): + # 0-order filter is just a passthrough + # Even-order filters have DC gain of -rp dB + b, a = cheby1(0, 10*np.log10(2), 1, analog=True) + assert_array_almost_equal(b, [1/np.sqrt(2)]) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = cheby1(1, 10*np.log10(2), 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = cheby1(1, 0.1, 0.3, output='zpk') + xp_assert_equal(z, np.asarray([-1.0])) + xp_assert_close(p, [-5.390126972799615e-01 + 0j], rtol=1e-14) + xp_assert_close(k, 7.695063486399808e-01, rtol=1e-14) + + def test_basic(self): + for N in range(25): + wn = 0.01 + z, p, k = cheby1(N, 1, wn, 'low', analog=True, output='zpk') + assert_array_almost_equal([], z) + assert len(p) == N + assert all(np.real(p) <= 0) # No poles in right half of S-plane + + for N in range(25): + wn = 0.01 + z, p, k = cheby1(N, 1, wn, 'high', analog=False, output='zpk') + xp_assert_equal(np.ones(N), z) # All zeros exactly at DC + assert all(np.abs(p) <= 1) # No poles outside unit circle + + # Same test as TestNormalize + b, a = cheby1(8, 0.5, 0.048) + assert_array_almost_equal(b, [ + 2.150733144728282e-11, 1.720586515782626e-10, + 6.022052805239190e-10, 1.204410561047838e-09, + 1.505513201309798e-09, 1.204410561047838e-09, + 6.022052805239190e-10, 1.720586515782626e-10, + 2.150733144728282e-11], decimal=14) + assert_array_almost_equal(a, [ + 1.000000000000000e+00, -7.782402035027959e+00, + 2.654354569747454e+01, -5.182182531666387e+01, + 6.334127355102684e+01, -4.963358186631157e+01, + 2.434862182949389e+01, -6.836925348604676e+00, + 8.412934944449140e-01], decimal=14) + + b, a = cheby1(4, 1, [0.4, 0.7], btype='band') + assert_array_almost_equal(b, [0.0084, 0, -0.0335, 0, 0.0502, 0, + -0.0335, 0, 0.0084], decimal=4) + assert_array_almost_equal(a, [1.0, 1.1191, 2.862, 2.2986, 3.4137, + 1.8653, 1.8982, 0.5676, 0.4103], + decimal=4) + + b2, a2 = cheby1(5, 3, 1, analog=True) + assert_array_almost_equal(b2, [0.0626], decimal=4) + assert_array_almost_equal(a2, [1, 0.5745, 1.4150, 0.5489, 0.4080, + 0.0626], decimal=4) + + b, a = cheby1(8, 0.5, 0.1) + assert_array_almost_equal(b, 1.0e-006 * np.array([ + 0.00703924326028, 0.05631394608227, 0.19709881128793, + 0.39419762257586, 0.49274702821983, 0.39419762257586, + 0.19709881128793, 0.05631394608227, 0.00703924326028]), + decimal=13) + assert_array_almost_equal(a, [ + 1.00000000000000, -7.44912258934158, 24.46749067762108, + -46.27560200466141, 55.11160187999928, -42.31640010161038, + 20.45543300484147, -5.69110270561444, 0.69770374759022], + decimal=13) + + b, a = cheby1(8, 0.5, 0.25) + assert_array_almost_equal(b, 1.0e-003 * np.array([ + 0.00895261138923, 0.07162089111382, 0.25067311889837, + 0.50134623779673, 0.62668279724591, 0.50134623779673, + 0.25067311889837, 0.07162089111382, 0.00895261138923]), + decimal=13) + assert_array_almost_equal(a, [1.00000000000000, -5.97529229188545, + 16.58122329202101, -27.71423273542923, + 30.39509758355313, -22.34729670426879, + 10.74509800434910, -3.08924633697497, + 0.40707685889802], decimal=13) + + def test_highpass(self): + # high even order + z, p, k = cheby1(24, 0.7, 0.2, 'high', output='zpk') + z2 = np.ones(24) + p2 = [-6.136558509657073e-01 + 2.700091504942893e-01j, + -6.136558509657073e-01 - 2.700091504942893e-01j, + -3.303348340927516e-01 + 6.659400861114254e-01j, + -3.303348340927516e-01 - 6.659400861114254e-01j, + 8.779713780557169e-03 + 8.223108447483040e-01j, + 8.779713780557169e-03 - 8.223108447483040e-01j, + 2.742361123006911e-01 + 8.356666951611864e-01j, + 2.742361123006911e-01 - 8.356666951611864e-01j, + 4.562984557158206e-01 + 7.954276912303594e-01j, + 4.562984557158206e-01 - 7.954276912303594e-01j, + 5.777335494123628e-01 + 7.435821817961783e-01j, + 5.777335494123628e-01 - 7.435821817961783e-01j, + 6.593260977749194e-01 + 6.955390907990932e-01j, + 6.593260977749194e-01 - 6.955390907990932e-01j, + 7.149590948466562e-01 + 6.559437858502012e-01j, + 7.149590948466562e-01 - 6.559437858502012e-01j, + 7.532432388188739e-01 + 6.256158042292060e-01j, + 7.532432388188739e-01 - 6.256158042292060e-01j, + 7.794365244268271e-01 + 6.042099234813333e-01j, + 7.794365244268271e-01 - 6.042099234813333e-01j, + 7.967253874772997e-01 + 5.911966597313203e-01j, + 7.967253874772997e-01 - 5.911966597313203e-01j, + 8.069756417293870e-01 + 5.862214589217275e-01j, + 8.069756417293870e-01 - 5.862214589217275e-01j] + k2 = 6.190427617192018e-04 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-10) + xp_assert_close(k, k2, rtol=1e-10) + + # high odd order + z, p, k = cheby1(23, 0.8, 0.3, 'high', output='zpk') + z2 = np.ones(23) + p2 = [-7.676400532011010e-01, + -6.754621070166477e-01 + 3.970502605619561e-01j, + -6.754621070166477e-01 - 3.970502605619561e-01j, + -4.528880018446727e-01 + 6.844061483786332e-01j, + -4.528880018446727e-01 - 6.844061483786332e-01j, + -1.986009130216447e-01 + 8.382285942941594e-01j, + -1.986009130216447e-01 - 8.382285942941594e-01j, + 2.504673931532608e-02 + 8.958137635794080e-01j, + 2.504673931532608e-02 - 8.958137635794080e-01j, + 2.001089429976469e-01 + 9.010678290791480e-01j, + 2.001089429976469e-01 - 9.010678290791480e-01j, + 3.302410157191755e-01 + 8.835444665962544e-01j, + 3.302410157191755e-01 - 8.835444665962544e-01j, + 4.246662537333661e-01 + 8.594054226449009e-01j, + 4.246662537333661e-01 - 8.594054226449009e-01j, + 4.919620928120296e-01 + 8.366772762965786e-01j, + 4.919620928120296e-01 - 8.366772762965786e-01j, + 5.385746917494749e-01 + 8.191616180796720e-01j, + 5.385746917494749e-01 - 8.191616180796720e-01j, + 5.855636993537203e-01 + 8.060680937701062e-01j, + 5.855636993537203e-01 - 8.060680937701062e-01j, + 5.688812849391721e-01 + 8.086497795114683e-01j, + 5.688812849391721e-01 - 8.086497795114683e-01j] + k2 = 1.941697029206324e-05 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-10) + xp_assert_close(k, k2, rtol=1e-10) + + z, p, k = cheby1(10, 1, 1000, 'high', analog=True, output='zpk') + z2 = np.zeros(10) + p2 = [-3.144743169501551e+03 + 3.511680029092744e+03j, + -3.144743169501551e+03 - 3.511680029092744e+03j, + -5.633065604514602e+02 + 2.023615191183945e+03j, + -5.633065604514602e+02 - 2.023615191183945e+03j, + -1.946412183352025e+02 + 1.372309454274755e+03j, + -1.946412183352025e+02 - 1.372309454274755e+03j, + -7.987162953085479e+01 + 1.105207708045358e+03j, + -7.987162953085479e+01 - 1.105207708045358e+03j, + -2.250315039031946e+01 + 1.001723931471477e+03j, + -2.250315039031946e+01 - 1.001723931471477e+03j] + k2 = 8.912509381337453e-01 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-15) + + def test_bandpass(self): + z, p, k = cheby1(8, 1, [0.3, 0.4], 'bp', output='zpk') + z2 = [1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1] + p2 = [3.077784854851463e-01 + 9.453307017592942e-01j, + 3.077784854851463e-01 - 9.453307017592942e-01j, + 3.280567400654425e-01 + 9.272377218689016e-01j, + 3.280567400654425e-01 - 9.272377218689016e-01j, + 3.677912763284301e-01 + 9.038008865279966e-01j, + 3.677912763284301e-01 - 9.038008865279966e-01j, + 4.194425632520948e-01 + 8.769407159656157e-01j, + 4.194425632520948e-01 - 8.769407159656157e-01j, + 4.740921994669189e-01 + 8.496508528630974e-01j, + 4.740921994669189e-01 - 8.496508528630974e-01j, + 5.234866481897429e-01 + 8.259608422808477e-01j, + 5.234866481897429e-01 - 8.259608422808477e-01j, + 5.844717632289875e-01 + 8.052901363500210e-01j, + 5.844717632289875e-01 - 8.052901363500210e-01j, + 5.615189063336070e-01 + 8.100667803850766e-01j, + 5.615189063336070e-01 - 8.100667803850766e-01j] + k2 = 5.007028718074307e-09 + xp_assert_equal(z, z2, check_dtype=False) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-13) + + def test_bandstop(self): + z, p, k = cheby1(7, 1, [0.5, 0.6], 'stop', output='zpk') + z2 = [-1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j] + p2 = [-8.942974551472813e-02 + 3.482480481185926e-01j, + -8.942974551472813e-02 - 3.482480481185926e-01j, + 1.293775154041798e-01 + 8.753499858081858e-01j, + 1.293775154041798e-01 - 8.753499858081858e-01j, + 3.399741945062013e-02 + 9.690316022705607e-01j, + 3.399741945062013e-02 - 9.690316022705607e-01j, + 4.167225522796539e-04 + 9.927338161087488e-01j, + 4.167225522796539e-04 - 9.927338161087488e-01j, + -3.912966549550960e-01 + 8.046122859255742e-01j, + -3.912966549550960e-01 - 8.046122859255742e-01j, + -3.307805547127368e-01 + 9.133455018206508e-01j, + -3.307805547127368e-01 - 9.133455018206508e-01j, + -3.072658345097743e-01 + 9.443589759799366e-01j, + -3.072658345097743e-01 - 9.443589759799366e-01j] + k2 = 3.619438310405028e-01 + xp_assert_close(sorted(z, key=np.imag), + sorted(z2, key=np.imag), rtol=1e-13) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=0, atol=5e-16) + + def test_ba_output(self): + # with transfer function conversion, without digital conversion + b, a = cheby1(5, 0.9, [210, 310], 'stop', analog=True) + b2 = [1.000000000000006e+00, 0, + 3.255000000000020e+05, 0, + 4.238010000000026e+10, 0, + 2.758944510000017e+15, 0, + 8.980364380050052e+19, 0, + 1.169243442282517e+24 + ] + a2 = [1.000000000000000e+00, 4.630555945694342e+02, + 4.039266454794788e+05, 1.338060988610237e+08, + 5.844333551294591e+10, 1.357346371637638e+13, + 3.804661141892782e+15, 5.670715850340080e+17, + 1.114411200988328e+20, 8.316815934908471e+21, + 1.169243442282517e+24 + ] + xp_assert_close(b, b2, rtol=1e-14) + xp_assert_close(a, a2, rtol=1e-14) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = cheby1(N, 1, fc, btype, fs=fs) + ba2 = cheby1(N, 1, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = cheby1(N, 1, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = cheby1(N, 1, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + +class TestCheby2: + + def test_degenerate(self): + # 0-order filter is just a passthrough + # Stopband ripple factor doesn't matter + b, a = cheby2(0, 123.456, 1, analog=True) + xp_assert_equal(b, np.asarray([1.0])) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = cheby2(1, 10*np.log10(2), 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = cheby2(1, 50, 0.3, output='zpk') + xp_assert_equal(z, np.asarray([-1], dtype=np.complex128)) + xp_assert_close(p, [9.967826460175649e-01 + 0j], rtol=1e-14) + xp_assert_close(k, 1.608676991217512e-03, rtol=1e-14) + + def test_basic(self): + for N in range(25): + wn = 0.01 + z, p, k = cheby2(N, 40, wn, 'low', analog=True, output='zpk') + assert len(p) == N + assert all(np.real(p) <= 0) # No poles in right half of S-plane + + for N in range(25): + wn = 0.01 + z, p, k = cheby2(N, 40, wn, 'high', analog=False, output='zpk') + assert all(np.abs(p) <= 1) # No poles outside unit circle + + B, A = cheby2(18, 100, 0.5) + assert_array_almost_equal(B, [ + 0.00167583914216, 0.01249479541868, 0.05282702120282, + 0.15939804265706, 0.37690207631117, 0.73227013789108, + 1.20191856962356, 1.69522872823393, 2.07598674519837, + 2.21972389625291, 2.07598674519838, 1.69522872823395, + 1.20191856962359, 0.73227013789110, 0.37690207631118, + 0.15939804265707, 0.05282702120282, 0.01249479541868, + 0.00167583914216], decimal=13) + assert_array_almost_equal(A, [ + 1.00000000000000, -0.27631970006174, 3.19751214254060, + -0.15685969461355, 4.13926117356269, 0.60689917820044, + 2.95082770636540, 0.89016501910416, 1.32135245849798, + 0.51502467236824, 0.38906643866660, 0.15367372690642, + 0.07255803834919, 0.02422454070134, 0.00756108751837, + 0.00179848550988, 0.00033713574499, 0.00004258794833, + 0.00000281030149], decimal=13) + + def test_highpass(self): + # high even order + z, p, k = cheby2(26, 60, 0.3, 'high', output='zpk') + z2 = [9.981088955489852e-01 + 6.147058341984388e-02j, + 9.981088955489852e-01 - 6.147058341984388e-02j, + 9.832702870387426e-01 + 1.821525257215483e-01j, + 9.832702870387426e-01 - 1.821525257215483e-01j, + 9.550760158089112e-01 + 2.963609353922882e-01j, + 9.550760158089112e-01 - 2.963609353922882e-01j, + 9.162054748821922e-01 + 4.007087817803773e-01j, + 9.162054748821922e-01 - 4.007087817803773e-01j, + 8.700619897368064e-01 + 4.929423232136168e-01j, + 8.700619897368064e-01 - 4.929423232136168e-01j, + 5.889791753434985e-01 + 8.081482110427953e-01j, + 5.889791753434985e-01 - 8.081482110427953e-01j, + 5.984900456570295e-01 + 8.011302423760501e-01j, + 5.984900456570295e-01 - 8.011302423760501e-01j, + 6.172880888914629e-01 + 7.867371958365343e-01j, + 6.172880888914629e-01 - 7.867371958365343e-01j, + 6.448899971038180e-01 + 7.642754030030161e-01j, + 6.448899971038180e-01 - 7.642754030030161e-01j, + 6.804845629637927e-01 + 7.327624168637228e-01j, + 6.804845629637927e-01 - 7.327624168637228e-01j, + 8.202619107108660e-01 + 5.719881098737678e-01j, + 8.202619107108660e-01 - 5.719881098737678e-01j, + 7.228410452536148e-01 + 6.910143437705678e-01j, + 7.228410452536148e-01 - 6.910143437705678e-01j, + 7.702121399578629e-01 + 6.377877856007792e-01j, + 7.702121399578629e-01 - 6.377877856007792e-01j] + p2 = [7.365546198286450e-01 + 4.842085129329526e-02j, + 7.365546198286450e-01 - 4.842085129329526e-02j, + 7.292038510962885e-01 + 1.442201672097581e-01j, + 7.292038510962885e-01 - 1.442201672097581e-01j, + 7.151293788040354e-01 + 2.369925800458584e-01j, + 7.151293788040354e-01 - 2.369925800458584e-01j, + 6.955051820787286e-01 + 3.250341363856910e-01j, + 6.955051820787286e-01 - 3.250341363856910e-01j, + 6.719122956045220e-01 + 4.070475750638047e-01j, + 6.719122956045220e-01 - 4.070475750638047e-01j, + 6.461722130611300e-01 + 4.821965916689270e-01j, + 6.461722130611300e-01 - 4.821965916689270e-01j, + 5.528045062872224e-01 + 8.162920513838372e-01j, + 5.528045062872224e-01 - 8.162920513838372e-01j, + 5.464847782492791e-01 + 7.869899955967304e-01j, + 5.464847782492791e-01 - 7.869899955967304e-01j, + 5.488033111260949e-01 + 7.520442354055579e-01j, + 5.488033111260949e-01 - 7.520442354055579e-01j, + 6.201874719022955e-01 + 5.500894392527353e-01j, + 6.201874719022955e-01 - 5.500894392527353e-01j, + 5.586478152536709e-01 + 7.112676877332921e-01j, + 5.586478152536709e-01 - 7.112676877332921e-01j, + 5.958145844148228e-01 + 6.107074340842115e-01j, + 5.958145844148228e-01 - 6.107074340842115e-01j, + 5.747812938519067e-01 + 6.643001536914696e-01j, + 5.747812938519067e-01 - 6.643001536914696e-01j] + k2 = 9.932997786497189e-02 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-12) + xp_assert_close(k, k2, rtol=1e-11) + + # high odd order + z, p, k = cheby2(25, 80, 0.5, 'high', output='zpk') + z2 = [9.690690376586687e-01 + 2.467897896011971e-01j, + 9.690690376586687e-01 - 2.467897896011971e-01j, + 9.999999999999492e-01, + 8.835111277191199e-01 + 4.684101698261429e-01j, + 8.835111277191199e-01 - 4.684101698261429e-01j, + 7.613142857900539e-01 + 6.483830335935022e-01j, + 7.613142857900539e-01 - 6.483830335935022e-01j, + 6.232625173626231e-01 + 7.820126817709752e-01j, + 6.232625173626231e-01 - 7.820126817709752e-01j, + 4.864456563413621e-01 + 8.737108351316745e-01j, + 4.864456563413621e-01 - 8.737108351316745e-01j, + 3.618368136816749e-01 + 9.322414495530347e-01j, + 3.618368136816749e-01 - 9.322414495530347e-01j, + 2.549486883466794e-01 + 9.669545833752675e-01j, + 2.549486883466794e-01 - 9.669545833752675e-01j, + 1.676175432109457e-01 + 9.858520980390212e-01j, + 1.676175432109457e-01 - 9.858520980390212e-01j, + 1.975218468277521e-03 + 9.999980492540941e-01j, + 1.975218468277521e-03 - 9.999980492540941e-01j, + 1.786959496651858e-02 + 9.998403260399917e-01j, + 1.786959496651858e-02 - 9.998403260399917e-01j, + 9.967933660557139e-02 + 9.950196127985684e-01j, + 9.967933660557139e-02 - 9.950196127985684e-01j, + 5.013970951219547e-02 + 9.987422137518890e-01j, + 5.013970951219547e-02 - 9.987422137518890e-01j] + p2 = [4.218866331906864e-01, + 4.120110200127552e-01 + 1.361290593621978e-01j, + 4.120110200127552e-01 - 1.361290593621978e-01j, + 3.835890113632530e-01 + 2.664910809911026e-01j, + 3.835890113632530e-01 - 2.664910809911026e-01j, + 3.399195570456499e-01 + 3.863983538639875e-01j, + 3.399195570456499e-01 - 3.863983538639875e-01j, + 2.855977834508353e-01 + 4.929444399540688e-01j, + 2.855977834508353e-01 - 4.929444399540688e-01j, + 2.255765441339322e-01 + 5.851631870205766e-01j, + 2.255765441339322e-01 - 5.851631870205766e-01j, + 1.644087535815792e-01 + 6.637356937277153e-01j, + 1.644087535815792e-01 - 6.637356937277153e-01j, + -7.293633845273095e-02 + 9.739218252516307e-01j, + -7.293633845273095e-02 - 9.739218252516307e-01j, + 1.058259206358626e-01 + 7.304739464862978e-01j, + 1.058259206358626e-01 - 7.304739464862978e-01j, + -5.703971947785402e-02 + 9.291057542169088e-01j, + -5.703971947785402e-02 - 9.291057542169088e-01j, + 5.263875132656864e-02 + 7.877974334424453e-01j, + 5.263875132656864e-02 - 7.877974334424453e-01j, + -3.007943405982616e-02 + 8.846331716180016e-01j, + -3.007943405982616e-02 - 8.846331716180016e-01j, + 6.857277464483946e-03 + 8.383275456264492e-01j, + 6.857277464483946e-03 - 8.383275456264492e-01j] + k2 = 6.507068761705037e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-12) + xp_assert_close(k, k2, rtol=1e-11) + + def test_bandpass(self): + z, p, k = cheby2(9, 40, [0.07, 0.2], 'pass', output='zpk') + z2 = [-9.999999999999999e-01, + 3.676588029658514e-01 + 9.299607543341383e-01j, + 3.676588029658514e-01 - 9.299607543341383e-01j, + 7.009689684982283e-01 + 7.131917730894889e-01j, + 7.009689684982283e-01 - 7.131917730894889e-01j, + 7.815697973765858e-01 + 6.238178033919218e-01j, + 7.815697973765858e-01 - 6.238178033919218e-01j, + 8.063793628819866e-01 + 5.913986160941200e-01j, + 8.063793628819866e-01 - 5.913986160941200e-01j, + 1.000000000000001e+00, + 9.944493019920448e-01 + 1.052168511576739e-01j, + 9.944493019920448e-01 - 1.052168511576739e-01j, + 9.854674703367308e-01 + 1.698642543566085e-01j, + 9.854674703367308e-01 - 1.698642543566085e-01j, + 9.762751735919308e-01 + 2.165335665157851e-01j, + 9.762751735919308e-01 - 2.165335665157851e-01j, + 9.792277171575134e-01 + 2.027636011479496e-01j, + 9.792277171575134e-01 - 2.027636011479496e-01j] + p2 = [8.143803410489621e-01 + 5.411056063397541e-01j, + 8.143803410489621e-01 - 5.411056063397541e-01j, + 7.650769827887418e-01 + 5.195412242095543e-01j, + 7.650769827887418e-01 - 5.195412242095543e-01j, + 6.096241204063443e-01 + 3.568440484659796e-01j, + 6.096241204063443e-01 - 3.568440484659796e-01j, + 6.918192770246239e-01 + 4.770463577106911e-01j, + 6.918192770246239e-01 - 4.770463577106911e-01j, + 6.986241085779207e-01 + 1.146512226180060e-01j, + 6.986241085779207e-01 - 1.146512226180060e-01j, + 8.654645923909734e-01 + 1.604208797063147e-01j, + 8.654645923909734e-01 - 1.604208797063147e-01j, + 9.164831670444591e-01 + 1.969181049384918e-01j, + 9.164831670444591e-01 - 1.969181049384918e-01j, + 9.630425777594550e-01 + 2.317513360702271e-01j, + 9.630425777594550e-01 - 2.317513360702271e-01j, + 9.438104703725529e-01 + 2.193509900269860e-01j, + 9.438104703725529e-01 - 2.193509900269860e-01j] + k2 = 9.345352824659604e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-11) + + def test_bandstop(self): + z, p, k = cheby2(6, 55, [0.1, 0.9], 'stop', output='zpk') + z2 = [6.230544895101009e-01 + 7.821784343111114e-01j, + 6.230544895101009e-01 - 7.821784343111114e-01j, + 9.086608545660115e-01 + 4.175349702471991e-01j, + 9.086608545660115e-01 - 4.175349702471991e-01j, + 9.478129721465802e-01 + 3.188268649763867e-01j, + 9.478129721465802e-01 - 3.188268649763867e-01j, + -6.230544895100982e-01 + 7.821784343111109e-01j, + -6.230544895100982e-01 - 7.821784343111109e-01j, + -9.086608545660116e-01 + 4.175349702472088e-01j, + -9.086608545660116e-01 - 4.175349702472088e-01j, + -9.478129721465784e-01 + 3.188268649763897e-01j, + -9.478129721465784e-01 - 3.188268649763897e-01j] + p2 = [-9.464094036167638e-01 + 1.720048695084344e-01j, + -9.464094036167638e-01 - 1.720048695084344e-01j, + -8.715844103386737e-01 + 1.370665039509297e-01j, + -8.715844103386737e-01 - 1.370665039509297e-01j, + -8.078751204586425e-01 + 5.729329866682983e-02j, + -8.078751204586425e-01 - 5.729329866682983e-02j, + 9.464094036167665e-01 + 1.720048695084332e-01j, + 9.464094036167665e-01 - 1.720048695084332e-01j, + 8.078751204586447e-01 + 5.729329866683007e-02j, + 8.078751204586447e-01 - 5.729329866683007e-02j, + 8.715844103386721e-01 + 1.370665039509331e-01j, + 8.715844103386721e-01 - 1.370665039509331e-01j] + k2 = 2.917823332763358e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-11) + + def test_ba_output(self): + # with transfer function conversion, without digital conversion + b, a = cheby2(5, 20, [2010, 2100], 'stop', True) + b2 = [1.000000000000000e+00, 0, # Matlab: 6.683253076978249e-12, + 2.111512500000000e+07, 0, # Matlab: 1.134325604589552e-04, + 1.782966433781250e+14, 0, # Matlab: 7.216787944356781e+02, + 7.525901316990656e+20, 0, # Matlab: 2.039829265789886e+09, + 1.587960565565748e+27, 0, # Matlab: 2.161236218626134e+15, + 1.339913493808585e+33] + a2 = [1.000000000000000e+00, 1.849550755473371e+02, + 2.113222918998538e+07, 3.125114149732283e+09, + 1.785133457155609e+14, 1.979158697776348e+16, + 7.535048322653831e+20, 5.567966191263037e+22, + 1.589246884221346e+27, 5.871210648525566e+28, + 1.339913493808590e+33] + xp_assert_close(b, b2, rtol=1e-14) + xp_assert_close(a, a2, rtol=1e-14) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = cheby2(N, 20, fc, btype, fs=fs) + ba2 = cheby2(N, 20, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = cheby2(N, 20, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = cheby2(N, 20, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + +class TestEllip: + + def test_degenerate(self): + # 0-order filter is just a passthrough + # Even-order filters have DC gain of -rp dB + # Stopband ripple factor doesn't matter + b, a = ellip(0, 10*np.log10(2), 123.456, 1, analog=True) + assert_array_almost_equal(b, [1/np.sqrt(2)]) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = ellip(1, 10*np.log10(2), 1, 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = ellip(1, 1, 55, 0.3, output='zpk') + xp_assert_close(z, [-9.999999999999998e-01], rtol=1e-14) + xp_assert_close(p, [-6.660721153525525e-04], rtol=1e-10) + xp_assert_close(k, 5.003330360576763e-01, rtol=1e-14) + + def test_basic(self): + for N in range(25): + wn = 0.01 + z, p, k = ellip(N, 1, 40, wn, 'low', analog=True, output='zpk') + assert len(p) == N + assert all(np.real(p) <= 0) # No poles in right half of S-plane + + for N in range(25): + wn = 0.01 + z, p, k = ellip(N, 1, 40, wn, 'high', analog=False, output='zpk') + assert all(np.abs(p) <= 1) # No poles outside unit circle + + b3, a3 = ellip(5, 3, 26, 1, analog=True) + assert_array_almost_equal(b3, [0.1420, 0, 0.3764, 0, + 0.2409], decimal=4) + assert_array_almost_equal(a3, [1, 0.5686, 1.8061, 0.8017, 0.8012, + 0.2409], decimal=4) + + b, a = ellip(3, 1, 60, [0.4, 0.7], 'stop') + assert_array_almost_equal(b, [0.3310, 0.3469, 1.1042, 0.7044, 1.1042, + 0.3469, 0.3310], decimal=4) + assert_array_almost_equal(a, [1.0000, 0.6973, 1.1441, 0.5878, 0.7323, + 0.1131, -0.0060], decimal=4) + + def test_highpass(self): + # high even order + z, p, k = ellip(24, 1, 80, 0.3, 'high', output='zpk') + z2 = [9.761875332501075e-01 + 2.169283290099910e-01j, + 9.761875332501075e-01 - 2.169283290099910e-01j, + 8.413503353963494e-01 + 5.404901600661900e-01j, + 8.413503353963494e-01 - 5.404901600661900e-01j, + 7.160082576305009e-01 + 6.980918098681732e-01j, + 7.160082576305009e-01 - 6.980918098681732e-01j, + 6.456533638965329e-01 + 7.636306264739803e-01j, + 6.456533638965329e-01 - 7.636306264739803e-01j, + 6.127321820971366e-01 + 7.902906256703928e-01j, + 6.127321820971366e-01 - 7.902906256703928e-01j, + 5.983607817490196e-01 + 8.012267936512676e-01j, + 5.983607817490196e-01 - 8.012267936512676e-01j, + 5.922577552594799e-01 + 8.057485658286990e-01j, + 5.922577552594799e-01 - 8.057485658286990e-01j, + 5.896952092563588e-01 + 8.076258788449631e-01j, + 5.896952092563588e-01 - 8.076258788449631e-01j, + 5.886248765538837e-01 + 8.084063054565607e-01j, + 5.886248765538837e-01 - 8.084063054565607e-01j, + 5.881802711123132e-01 + 8.087298490066037e-01j, + 5.881802711123132e-01 - 8.087298490066037e-01j, + 5.879995719101164e-01 + 8.088612386766461e-01j, + 5.879995719101164e-01 - 8.088612386766461e-01j, + 5.879354086709576e-01 + 8.089078780868164e-01j, + 5.879354086709576e-01 - 8.089078780868164e-01j] + p2 = [-3.184805259081650e-01 + 4.206951906775851e-01j, + -3.184805259081650e-01 - 4.206951906775851e-01j, + 1.417279173459985e-01 + 7.903955262836452e-01j, + 1.417279173459985e-01 - 7.903955262836452e-01j, + 4.042881216964651e-01 + 8.309042239116594e-01j, + 4.042881216964651e-01 - 8.309042239116594e-01j, + 5.128964442789670e-01 + 8.229563236799665e-01j, + 5.128964442789670e-01 - 8.229563236799665e-01j, + 5.569614712822724e-01 + 8.155957702908510e-01j, + 5.569614712822724e-01 - 8.155957702908510e-01j, + 5.750478870161392e-01 + 8.118633973883931e-01j, + 5.750478870161392e-01 - 8.118633973883931e-01j, + 5.825314018170804e-01 + 8.101960910679270e-01j, + 5.825314018170804e-01 - 8.101960910679270e-01j, + 5.856397379751872e-01 + 8.094825218722543e-01j, + 5.856397379751872e-01 - 8.094825218722543e-01j, + 5.869326035251949e-01 + 8.091827531557583e-01j, + 5.869326035251949e-01 - 8.091827531557583e-01j, + 5.874697218855733e-01 + 8.090593298213502e-01j, + 5.874697218855733e-01 - 8.090593298213502e-01j, + 5.876904783532237e-01 + 8.090127161018823e-01j, + 5.876904783532237e-01 - 8.090127161018823e-01j, + 5.877753105317594e-01 + 8.090050577978136e-01j, + 5.877753105317594e-01 - 8.090050577978136e-01j] + k2 = 4.918081266957108e-02 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-4) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-4) + xp_assert_close(k, k2, rtol=1e-3) + + # high odd order + z, p, k = ellip(23, 1, 70, 0.5, 'high', output='zpk') + z2 = [9.999999999998661e-01, + 6.603717261750994e-01 + 7.509388678638675e-01j, + 6.603717261750994e-01 - 7.509388678638675e-01j, + 2.788635267510325e-01 + 9.603307416968041e-01j, + 2.788635267510325e-01 - 9.603307416968041e-01j, + 1.070215532544218e-01 + 9.942567008268131e-01j, + 1.070215532544218e-01 - 9.942567008268131e-01j, + 4.049427369978163e-02 + 9.991797705105507e-01j, + 4.049427369978163e-02 - 9.991797705105507e-01j, + 1.531059368627931e-02 + 9.998827859909265e-01j, + 1.531059368627931e-02 - 9.998827859909265e-01j, + 5.808061438534933e-03 + 9.999831330689181e-01j, + 5.808061438534933e-03 - 9.999831330689181e-01j, + 2.224277847754599e-03 + 9.999975262909676e-01j, + 2.224277847754599e-03 - 9.999975262909676e-01j, + 8.731857107534554e-04 + 9.999996187732845e-01j, + 8.731857107534554e-04 - 9.999996187732845e-01j, + 3.649057346914968e-04 + 9.999999334218996e-01j, + 3.649057346914968e-04 - 9.999999334218996e-01j, + 1.765538109802615e-04 + 9.999999844143768e-01j, + 1.765538109802615e-04 - 9.999999844143768e-01j, + 1.143655290967426e-04 + 9.999999934602630e-01j, + 1.143655290967426e-04 - 9.999999934602630e-01j] + p2 = [-6.322017026545028e-01, + -4.648423756662754e-01 + 5.852407464440732e-01j, + -4.648423756662754e-01 - 5.852407464440732e-01j, + -2.249233374627773e-01 + 8.577853017985717e-01j, + -2.249233374627773e-01 - 8.577853017985717e-01j, + -9.234137570557621e-02 + 9.506548198678851e-01j, + -9.234137570557621e-02 - 9.506548198678851e-01j, + -3.585663561241373e-02 + 9.821494736043981e-01j, + -3.585663561241373e-02 - 9.821494736043981e-01j, + -1.363917242312723e-02 + 9.933844128330656e-01j, + -1.363917242312723e-02 - 9.933844128330656e-01j, + -5.131505238923029e-03 + 9.975221173308673e-01j, + -5.131505238923029e-03 - 9.975221173308673e-01j, + -1.904937999259502e-03 + 9.990680819857982e-01j, + -1.904937999259502e-03 - 9.990680819857982e-01j, + -6.859439885466834e-04 + 9.996492201426826e-01j, + -6.859439885466834e-04 - 9.996492201426826e-01j, + -2.269936267937089e-04 + 9.998686250679161e-01j, + -2.269936267937089e-04 - 9.998686250679161e-01j, + -5.687071588789117e-05 + 9.999527573294513e-01j, + -5.687071588789117e-05 - 9.999527573294513e-01j, + -6.948417068525226e-07 + 9.999882737700173e-01j, + -6.948417068525226e-07 - 9.999882737700173e-01j] + k2 = 1.220910020289434e-02 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-4) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-4) + xp_assert_close(k, k2, rtol=1e-3) + + def test_bandpass(self): + z, p, k = ellip(7, 1, 40, [0.07, 0.2], 'pass', output='zpk') + z2 = [-9.999999999999991e-01, + 6.856610961780020e-01 + 7.279209168501619e-01j, + 6.856610961780020e-01 - 7.279209168501619e-01j, + 7.850346167691289e-01 + 6.194518952058737e-01j, + 7.850346167691289e-01 - 6.194518952058737e-01j, + 7.999038743173071e-01 + 6.001281461922627e-01j, + 7.999038743173071e-01 - 6.001281461922627e-01j, + 9.999999999999999e-01, + 9.862938983554124e-01 + 1.649980183725925e-01j, + 9.862938983554124e-01 - 1.649980183725925e-01j, + 9.788558330548762e-01 + 2.045513580850601e-01j, + 9.788558330548762e-01 - 2.045513580850601e-01j, + 9.771155231720003e-01 + 2.127093189691258e-01j, + 9.771155231720003e-01 - 2.127093189691258e-01j] + p2 = [8.063992755498643e-01 + 5.858071374778874e-01j, + 8.063992755498643e-01 - 5.858071374778874e-01j, + 8.050395347071724e-01 + 5.639097428109795e-01j, + 8.050395347071724e-01 - 5.639097428109795e-01j, + 8.113124936559144e-01 + 4.855241143973142e-01j, + 8.113124936559144e-01 - 4.855241143973142e-01j, + 8.665595314082394e-01 + 3.334049560919331e-01j, + 8.665595314082394e-01 - 3.334049560919331e-01j, + 9.412369011968871e-01 + 2.457616651325908e-01j, + 9.412369011968871e-01 - 2.457616651325908e-01j, + 9.679465190411238e-01 + 2.228772501848216e-01j, + 9.679465190411238e-01 - 2.228772501848216e-01j, + 9.747235066273385e-01 + 2.178937926146544e-01j, + 9.747235066273385e-01 - 2.178937926146544e-01j] + k2 = 8.354782670263239e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-4) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-4) + xp_assert_close(k, k2, rtol=1e-3) + + z, p, k = ellip(5, 1, 75, [90.5, 110.5], 'pass', True, 'zpk') + z2 = [-5.583607317695175e-14 + 1.433755965989225e+02j, + -5.583607317695175e-14 - 1.433755965989225e+02j, + 5.740106416459296e-14 + 1.261678754570291e+02j, + 5.740106416459296e-14 - 1.261678754570291e+02j, + -2.199676239638652e-14 + 6.974861996895196e+01j, + -2.199676239638652e-14 - 6.974861996895196e+01j, + -3.372595657044283e-14 + 7.926145989044531e+01j, + -3.372595657044283e-14 - 7.926145989044531e+01j, + 0] + p2 = [-8.814960004852743e-01 + 1.104124501436066e+02j, + -8.814960004852743e-01 - 1.104124501436066e+02j, + -2.477372459140184e+00 + 1.065638954516534e+02j, + -2.477372459140184e+00 - 1.065638954516534e+02j, + -3.072156842945799e+00 + 9.995404870405324e+01j, + -3.072156842945799e+00 - 9.995404870405324e+01j, + -2.180456023925693e+00 + 9.379206865455268e+01j, + -2.180456023925693e+00 - 9.379206865455268e+01j, + -7.230484977485752e-01 + 9.056598800801140e+01j, + -7.230484977485752e-01 - 9.056598800801140e+01j] + k2 = 3.774571622827070e-02 + xp_assert_close(sorted(z, key=np.imag), + sorted(z2, key=np.imag), rtol=1e-4) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-6) + xp_assert_close(k, k2, rtol=1e-3) + + def test_bandstop(self): + z, p, k = ellip(8, 1, 65, [0.2, 0.4], 'stop', output='zpk') + z2 = [3.528578094286510e-01 + 9.356769561794296e-01j, + 3.528578094286510e-01 - 9.356769561794296e-01j, + 3.769716042264783e-01 + 9.262248159096587e-01j, + 3.769716042264783e-01 - 9.262248159096587e-01j, + 4.406101783111199e-01 + 8.976985411420985e-01j, + 4.406101783111199e-01 - 8.976985411420985e-01j, + 5.539386470258847e-01 + 8.325574907062760e-01j, + 5.539386470258847e-01 - 8.325574907062760e-01j, + 6.748464963023645e-01 + 7.379581332490555e-01j, + 6.748464963023645e-01 - 7.379581332490555e-01j, + 7.489887970285254e-01 + 6.625826604475596e-01j, + 7.489887970285254e-01 - 6.625826604475596e-01j, + 7.913118471618432e-01 + 6.114127579150699e-01j, + 7.913118471618432e-01 - 6.114127579150699e-01j, + 7.806804740916381e-01 + 6.249303940216475e-01j, + 7.806804740916381e-01 - 6.249303940216475e-01j] + + p2 = [-1.025299146693730e-01 + 5.662682444754943e-01j, + -1.025299146693730e-01 - 5.662682444754943e-01j, + 1.698463595163031e-01 + 8.926678667070186e-01j, + 1.698463595163031e-01 - 8.926678667070186e-01j, + 2.750532687820631e-01 + 9.351020170094005e-01j, + 2.750532687820631e-01 - 9.351020170094005e-01j, + 3.070095178909486e-01 + 9.457373499553291e-01j, + 3.070095178909486e-01 - 9.457373499553291e-01j, + 7.695332312152288e-01 + 2.792567212705257e-01j, + 7.695332312152288e-01 - 2.792567212705257e-01j, + 8.083818999225620e-01 + 4.990723496863960e-01j, + 8.083818999225620e-01 - 4.990723496863960e-01j, + 8.066158014414928e-01 + 5.649811440393374e-01j, + 8.066158014414928e-01 - 5.649811440393374e-01j, + 8.062787978834571e-01 + 5.855780880424964e-01j, + 8.062787978834571e-01 - 5.855780880424964e-01j] + k2 = 2.068622545291259e-01 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-6) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-5) + xp_assert_close(k, k2, rtol=1e-5) + + def test_ba_output(self): + # with transfer function conversion, without digital conversion + b, a = ellip(5, 1, 40, [201, 240], 'stop', True) + b2 = [ + 1.000000000000000e+00, 0, # Matlab: 1.743506051190569e-13, + 2.426561778314366e+05, 0, # Matlab: 3.459426536825722e-08, + 2.348218683400168e+10, 0, # Matlab: 2.559179747299313e-03, + 1.132780692872241e+15, 0, # Matlab: 8.363229375535731e+01, + 2.724038554089566e+19, 0, # Matlab: 1.018700994113120e+06, + 2.612380874940186e+23 + ] + a2 = [ + 1.000000000000000e+00, 1.337266601804649e+02, + 2.486725353510667e+05, 2.628059713728125e+07, + 2.436169536928770e+10, 1.913554568577315e+12, + 1.175208184614438e+15, 6.115751452473410e+16, + 2.791577695211466e+19, 7.241811142725384e+20, + 2.612380874940182e+23 + ] + xp_assert_close(b, b2, rtol=1e-6) + xp_assert_close(a, a2, rtol=1e-4) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = ellip(N, 1, 20, fc, btype, fs=fs) + ba2 = ellip(N, 1, 20, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = ellip(N, 1, 20, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = ellip(N, 1, 20, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + iirnotch(0.06, 30, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + iirnotch(0.06, 30, fs=None) + + +def test_sos_consistency(): + # Consistency checks of output='sos' for the specialized IIR filter + # design functions. + design_funcs = [(bessel, (0.1,)), + (butter, (0.1,)), + (cheby1, (45.0, 0.1)), + (cheby2, (0.087, 0.1)), + (ellip, (0.087, 45, 0.1))] + for func, args in design_funcs: + name = func.__name__ + + b, a = func(2, *args, output='ba') + sos = func(2, *args, output='sos') + xp_assert_close(sos, [np.hstack((b, a))], err_msg=f"{name}(2,...)") + + zpk = func(3, *args, output='zpk') + sos = func(3, *args, output='sos') + xp_assert_close(sos, zpk2sos(*zpk), err_msg=f"{name}(3,...)") + + zpk = func(4, *args, output='zpk') + sos = func(4, *args, output='sos') + xp_assert_close(sos, zpk2sos(*zpk), err_msg=f"{name}(4,...)") + + +class TestIIRNotch: + + def test_ba_output(self): + # Compare coefficients with Matlab ones + # for the equivalent input: + b, a = iirnotch(0.06, 30) + b2 = [ + 9.9686824e-01, -1.9584219e+00, + 9.9686824e-01 + ] + a2 = [ + 1.0000000e+00, -1.9584219e+00, + 9.9373647e-01 + ] + + xp_assert_close(b, b2, rtol=1e-8) + xp_assert_close(a, a2, rtol=1e-8) + + def test_frequency_response(self): + # Get filter coefficients + b, a = iirnotch(0.3, 30) + + # Get frequency response + w, h = freqz(b, a, 1000) + + # Pick 5 point + p = [200, # w0 = 0.200 + 295, # w0 = 0.295 + 300, # w0 = 0.300 + 305, # w0 = 0.305 + 400] # w0 = 0.400 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 0.3 and should be close to 1 + xp_assert_close(abs(hp[0]), np.asarray(1.), rtol=1e-2, check_0d=False) + xp_assert_close(abs(hp[4]), np.asarray(1.), rtol=1e-2, check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to -3dB + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be removed + # the frequency response should be very close to 0 + xp_assert_close(abs(hp[2]), np.asarray(0.0), atol=1e-10, check_0d=False) + + def test_errors(self): + # Exception should be raised if w0 > 1 or w0 <0 + assert_raises(ValueError, iirnotch, w0=2, Q=30) + assert_raises(ValueError, iirnotch, w0=-1, Q=30) + + # Exception should be raised if any of the parameters + # are not float (or cannot be converted to one) + assert_raises(ValueError, iirnotch, w0="blabla", Q=30) + assert_raises(TypeError, iirnotch, w0=-1, Q=[1, 2, 3]) + + def test_fs_param(self): + # Get filter coefficients + b, a = iirnotch(1500, 30, fs=10000) + + # Get frequency response + w, h = freqz(b, a, 1000, fs=10000) + + # Pick 5 point + p = [200, # w0 = 1000 + 295, # w0 = 1475 + 300, # w0 = 1500 + 305, # w0 = 1525 + 400] # w0 = 2000 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 1500 and should be close to 1 + xp_assert_close(abs(hp[0]), np.ones_like(abs(hp[0])), rtol=1e-2, + check_0d=False) + xp_assert_close(abs(hp[4]), np.ones_like(abs(hp[4])), rtol=1e-2, + check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to -3dB + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be removed + # the frequency response should be very close to 0 + xp_assert_close(abs(hp[2]), np.asarray(0.0), atol=1e-10, check_0d=False) + + +class TestIIRPeak: + + def test_ba_output(self): + # Compare coefficients with Matlab ones + # for the equivalent input: + b, a = iirpeak(0.06, 30) + b2 = [ + 3.131764229e-03, 0, + -3.131764229e-03 + ] + a2 = [ + 1.0000000e+00, -1.958421917e+00, + 9.9373647e-01 + ] + xp_assert_close(b, b2, rtol=1e-8) + xp_assert_close(a, a2, rtol=1e-8) + + def test_frequency_response(self): + # Get filter coefficients + b, a = iirpeak(0.3, 30) + + # Get frequency response + w, h = freqz(b, a, 1000) + + # Pick 5 point + p = [30, # w0 = 0.030 + 295, # w0 = 0.295 + 300, # w0 = 0.300 + 305, # w0 = 0.305 + 800] # w0 = 0.800 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 0.3 and should be close to 0 + xp_assert_close(abs(hp[0]), + np.zeros_like(abs(hp[0])), atol=1e-2, check_0d=False) + xp_assert_close(abs(hp[4]), + np.zeros_like(abs(hp[4])), atol=1e-2, check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to 10**(-3/20) + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be retained and + # the frequency response should be very close to 1 + xp_assert_close(abs(hp[2]), np.asarray(1.0), rtol=1e-10, check_0d=False) + + def test_errors(self): + # Exception should be raised if w0 > 1 or w0 <0 + assert_raises(ValueError, iirpeak, w0=2, Q=30) + assert_raises(ValueError, iirpeak, w0=-1, Q=30) + + # Exception should be raised if any of the parameters + # are not float (or cannot be converted to one) + assert_raises(ValueError, iirpeak, w0="blabla", Q=30) + assert_raises(TypeError, iirpeak, w0=-1, Q=[1, 2, 3]) + + def test_fs_param(self): + # Get filter coefficients + b, a = iirpeak(1200, 30, fs=8000) + + # Get frequency response + w, h = freqz(b, a, 1000, fs=8000) + + # Pick 5 point + p = [30, # w0 = 120 + 295, # w0 = 1180 + 300, # w0 = 1200 + 305, # w0 = 1220 + 800] # w0 = 3200 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 1200 and should be close to 0 + xp_assert_close(abs(hp[0]), + np.zeros_like(abs(hp[0])), atol=1e-2, check_0d=False) + xp_assert_close(abs(hp[4]), + np.zeros_like(abs(hp[4])), atol=1e-2, check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to 10**(-3/20) + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be retained and + # the frequency response should be very close to 1 + xp_assert_close(abs(hp[2]), + np.ones_like(abs(hp[2])), rtol=1e-10, check_0d=False) + + +class TestIIRComb: + # Test erroneous input cases + def test_invalid_input(self): + # w0 is <= 0 or >= fs / 2 + fs = 1000 + for args in [(-fs, 30), (0, 35), (fs / 2, 40), (fs, 35)]: + with pytest.raises(ValueError, match='w0 must be between '): + iircomb(*args, fs=fs) + + # fs is not divisible by w0 + for args in [(120, 30), (157, 35)]: + with pytest.raises(ValueError, match='fs must be divisible '): + iircomb(*args, fs=fs) + + # https://github.com/scipy/scipy/issues/14043#issuecomment-1107349140 + # Previously, fs=44100, w0=49.999 was rejected, but fs=2, + # w0=49.999/int(44100/2) was accepted. Now it is rejected, too. + with pytest.raises(ValueError, match='fs must be divisible '): + iircomb(w0=49.999/int(44100/2), Q=30) + + with pytest.raises(ValueError, match='fs must be divisible '): + iircomb(w0=49.999, Q=30, fs=44100) + + # Filter type is not notch or peak + for args in [(0.2, 30, 'natch'), (0.5, 35, 'comb')]: + with pytest.raises(ValueError, match='ftype must be '): + iircomb(*args) + + # Verify that the filter's frequency response contains a + # notch at the cutoff frequency + @pytest.mark.parametrize('ftype', ('notch', 'peak')) + def test_frequency_response(self, ftype): + # Create a notching or peaking comb filter at 1000 Hz + b, a = iircomb(1000, 30, ftype=ftype, fs=10000) + + # Compute the frequency response + freqs, response = freqz(b, a, 1000, fs=10000) + + # Find the notch using argrelextrema + comb_points = argrelextrema(abs(response), np.less)[0] + + # Verify that the first notch sits at 1000 Hz + comb1 = comb_points[0] + xp_assert_close(freqs[comb1], np.asarray(1000.), check_0d=False) + + # Verify pass_zero parameter + @pytest.mark.parametrize('ftype,pass_zero,peak,notch', + [('peak', True, 123.45, 61.725), + ('peak', False, 61.725, 123.45), + ('peak', None, 61.725, 123.45), + ('notch', None, 61.725, 123.45), + ('notch', True, 123.45, 61.725), + ('notch', False, 61.725, 123.45)]) + def test_pass_zero(self, ftype, pass_zero, peak, notch): + # Create a notching or peaking comb filter + b, a = iircomb(123.45, 30, ftype=ftype, fs=1234.5, pass_zero=pass_zero) + + # Compute the frequency response + freqs, response = freqz(b, a, [peak, notch], fs=1234.5) + + # Verify that expected notches are notches and peaks are peaks + assert abs(response[0]) > 0.99 + assert abs(response[1]) < 1e-10 + + # All built-in IIR filters are real, so should have perfectly + # symmetrical poles and zeros. Then ba representation (using + # numpy.poly) will be purely real instead of having negligible + # imaginary parts. + def test_iir_symmetry(self): + b, a = iircomb(400, 30, fs=24000) + z, p, k = tf2zpk(b, a) + xp_assert_equal(sorted(z), sorted(z.conj())) + xp_assert_equal(sorted(p), sorted(p.conj())) + xp_assert_equal(k, np.real(k)) + + assert issubclass(b.dtype.type, np.floating) + assert issubclass(a.dtype.type, np.floating) + + # Verify filter coefficients with MATLAB's iircomb function + def test_ba_output(self): + b_notch, a_notch = iircomb(60, 35, ftype='notch', fs=600) + b_notch2 = [0.957020174408697, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, -0.957020174408697] + a_notch2 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, -0.914040348817395] + xp_assert_close(b_notch, b_notch2) + xp_assert_close(a_notch, a_notch2) + + b_peak, a_peak = iircomb(60, 35, ftype='peak', fs=600) + b_peak2 = [0.0429798255913026, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, -0.0429798255913026] + a_peak2 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.914040348817395] + xp_assert_close(b_peak, b_peak2) + xp_assert_close(a_peak, a_peak2) + + # Verify that https://github.com/scipy/scipy/issues/14043 is fixed + def test_nearest_divisor(self): + # Create a notching comb filter + b, a = iircomb(50/int(44100/2), 50.0, ftype='notch') + + # Compute the frequency response at an upper harmonic of 50 + freqs, response = freqz(b, a, [22000], fs=44100) + + # Before bug fix, this would produce N = 881, so that 22 kHz was ~0 dB. + # Now N = 882 correctly and 22 kHz should be a notch <-220 dB + assert abs(response[0]) < 1e-10 + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + iircomb(1000, 30, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + iircomb(1000, 30, fs=None) + + +class TestIIRDesign: + + def test_exceptions(self): + with pytest.raises(ValueError, match="the same shape"): + iirdesign(0.2, [0.1, 0.3], 1, 40) + with pytest.raises(ValueError, match="the same shape"): + iirdesign(np.array([[0.3, 0.6], [0.3, 0.6]]), + np.array([[0.4, 0.5], [0.4, 0.5]]), 1, 40) + + # discrete filter with non-positive frequency + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(-0.1, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0.1, 0, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0.1, -0.5, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([-0.1, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, -0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [-0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0.1, 0], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0.1, -0.5], 1, 40) + + # analog filter with negative frequency + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(-0.1, 0.5, 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0.1, -0.5, 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([-0.1, 0.3], [0.1, 0.5], 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, -0.3], [0.1, 0.5], 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [-0.1, 0.5], 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0.1, -0.5], 1, 40, analog=True) + + # discrete filter with fs=None, freq > 1 + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(1, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(1.1, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(0.1, 1, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(0.1, 1.5, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([1, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([1.1, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 1], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 1.1], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [1.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [0.1, 1], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [0.1, 1.5], 1, 40) + + # discrete filter with fs>2, wp, ws < fs/2 must pass + iirdesign(100, 500, 1, 40, fs=2000) + iirdesign(500, 100, 1, 40, fs=2000) + iirdesign([200, 400], [100, 500], 1, 40, fs=2000) + iirdesign([100, 500], [200, 400], 1, 40, fs=2000) + + # discrete filter with fs>2, freq > fs/2: this must raise + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(1000, 400, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(1100, 500, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(100, 1000, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(100, 1100, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([1000, 400], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([1100, 400], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 1000], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 1100], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [1000, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [1100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [100, 1000], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [100, 1100], 1, 40, fs=2000) + + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.1, 0.4], [0.5, 0.6], 1, 40) + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.5, 0.6], [0.1, 0.4], 1, 40) + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.3, 0.6], [0.4, 0.7], 1, 40) + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.4, 0.7], [0.3, 0.6], 1, 40) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + iirfilter(1, 1, btype="low", fs=np.array([10, 20])) + + +class TestIIRFilter: + + def test_symmetry(self): + # All built-in IIR filters are real, so should have perfectly + # symmetrical poles and zeros. Then ba representation (using + # numpy.poly) will be purely real instead of having negligible + # imaginary parts. + for N in np.arange(1, 26): + for ftype in ('butter', 'bessel', 'cheby1', 'cheby2', 'ellip'): + z, p, k = iirfilter(N, 1.1, 1, 20, 'low', analog=True, + ftype=ftype, output='zpk') + xp_assert_equal(sorted(z), + sorted(z.conj())) + xp_assert_equal(sorted(p), + sorted(p.conj())) + xp_assert_equal(k, np.real(k)) + + b, a = iirfilter(N, 1.1, 1, 20, 'low', analog=True, + ftype=ftype, output='ba') + assert issubclass(b.dtype.type, np.floating) + assert issubclass(a.dtype.type, np.floating) + + def test_int_inputs(self): + # Using integer frequency arguments and large N should not produce + # numpy integers that wraparound to negative numbers + k = iirfilter(24, 100, btype='low', analog=True, ftype='bessel', + output='zpk')[2] + k2 = 9.999999999999989e+47 + xp_assert_close(np.asarray(k), np.asarray(k2)) + # if fs is specified then the normalization of Wn to have + # 0 <= Wn <= 1 should not cause an integer overflow + # the following line should not raise an exception + iirfilter(20, [1000000000, 1100000000], btype='bp', + analog=False, fs=6250000000) + + def test_invalid_wn_size(self): + # low and high have 1 Wn, band and stop have 2 Wn + assert_raises(ValueError, iirfilter, 1, [0.1, 0.9], btype='low') + assert_raises(ValueError, iirfilter, 1, [0.2, 0.5], btype='high') + assert_raises(ValueError, iirfilter, 1, 0.2, btype='bp') + assert_raises(ValueError, iirfilter, 1, 400, btype='bs', analog=True) + + def test_invalid_wn_range(self): + # For digital filters, 0 <= Wn <= 1 + assert_raises(ValueError, iirfilter, 1, 2, btype='low') + assert_raises(ValueError, iirfilter, 1, [0.5, 1], btype='band') + assert_raises(ValueError, iirfilter, 1, [0., 0.5], btype='band') + assert_raises(ValueError, iirfilter, 1, -1, btype='high') + assert_raises(ValueError, iirfilter, 1, [1, 2], btype='band') + assert_raises(ValueError, iirfilter, 1, [10, 20], btype='stop') + + # analog=True with non-positive critical frequencies + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, 0, btype='low', analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, -1, btype='low', analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [0, 100], analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [-1, 100], analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [10, 0], analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [10, -1], analog=True) + + def test_analog_sos(self): + # first order Butterworth filter with Wn = 1 has tf 1/(s+1) + sos = [[0., 0., 1., 0., 1., 1.]] + sos2 = iirfilter(N=1, Wn=1, btype='low', analog=True, output='sos') + assert_array_almost_equal(sos, sos2) + + def test_wn1_ge_wn0(self): + # gh-15773: should raise error if Wn[0] >= Wn[1] + with pytest.raises(ValueError, + match=r"Wn\[0\] must be less than Wn\[1\]"): + iirfilter(2, [0.5, 0.5]) + with pytest.raises(ValueError, + match=r"Wn\[0\] must be less than Wn\[1\]"): + iirfilter(2, [0.6, 0.5]) + + +class TestGroupDelay: + def test_identity_filter(self): + w, gd = group_delay((1, 1)) + assert_array_almost_equal(w, pi * np.arange(512) / 512) + assert_array_almost_equal(gd, np.zeros(512)) + w, gd = group_delay((1, 1), whole=True) + assert_array_almost_equal(w, 2 * pi * np.arange(512) / 512) + assert_array_almost_equal(gd, np.zeros(512)) + + def test_fir(self): + # Let's design linear phase FIR and check that the group delay + # is constant. + N = 100 + b = firwin(N + 1, 0.1) + w, gd = group_delay((b, 1)) + xp_assert_close(gd, np.ones_like(gd)*(0.5 * N)) + + def test_iir(self): + # Let's design Butterworth filter and test the group delay at + # some points against MATLAB answer. + b, a = butter(4, 0.1) + w = np.linspace(0, pi, num=10, endpoint=False) + w, gd = group_delay((b, a), w=w) + matlab_gd = np.array([8.249313898506037, 11.958947880907104, + 2.452325615326005, 1.048918665702008, + 0.611382575635897, 0.418293269460578, + 0.317932917836572, 0.261371844762525, + 0.229038045801298, 0.212185774208521]) + assert_array_almost_equal(gd, matlab_gd) + + @pytest.mark.thread_unsafe + def test_singular(self): + # Let's create a filter with zeros and poles on the unit circle and + # check if warnings are raised at those frequencies. + z1 = np.exp(1j * 0.1 * pi) + z2 = np.exp(1j * 0.25 * pi) + p1 = np.exp(1j * 0.5 * pi) + p2 = np.exp(1j * 0.8 * pi) + b = np.convolve([1, -z1], [1, -z2]) + a = np.convolve([1, -p1], [1, -p2]) + w = np.array([0.1 * pi, 0.25 * pi, -0.5 * pi, -0.8 * pi]) + + w, gd = assert_warns(UserWarning, group_delay, (b, a), w=w) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, gd1 = group_delay((1, 1)) + w2, gd2 = group_delay((1, 1), None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(gd1, gd2) + + def test_fs_param(self): + # Let's design Butterworth filter and test the group delay at + # some points against the normalized frequency answer. + b, a = butter(4, 4800, fs=96000) + w = np.linspace(0, 96000/2, num=10, endpoint=False) + w, gd = group_delay((b, a), w=w, fs=96000) + norm_gd = np.array([8.249313898506037, 11.958947880907104, + 2.452325615326005, 1.048918665702008, + 0.611382575635897, 0.418293269460578, + 0.317932917836572, 0.261371844762525, + 0.229038045801298, 0.212185774208521]) + assert_array_almost_equal(gd, norm_gd) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + w, gd = group_delay((1, 1), N) + assert_array_almost_equal(w, pi * np.arange(8) / 8) + assert_array_almost_equal(gd, np.zeros(8)) + + # Measure at frequency 8 rad/sec + for w in (8.0, 8.0+0j): + w_out, gd = group_delay((1, 1), w) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(gd, [0]) + + def test_complex_coef(self): + # gh-19586: handle complex coef TFs + # + # for g(z) = (alpha*z+1)/(1+conjugate(alpha)), group delay is + # given by function below. + # + # def gd_expr(w, alpha): + # num = 1j*(abs(alpha)**2-1)*np.exp(1j*w) + # den = (alpha*np.exp(1j*w)+1)*(np.exp(1j*w)+np.conj(alpha)) + # return -np.imag(num/den) + + # arbitrary non-real alpha + alpha = -0.6143077933232609+0.3355978770229421j + # 8 points from from -pi to pi + wref = np.array([-3.141592653589793 , + -2.356194490192345 , + -1.5707963267948966, + -0.7853981633974483, + 0. , + 0.7853981633974483, + 1.5707963267948966, + 2.356194490192345 ]) + gdref = array([0.18759548150354619, + 0.17999770352712252, + 0.23598047471879877, + 0.46539443069907194, + 1.9511492420564165 , + 3.478129975138865 , + 0.6228594960517333 , + 0.27067831839471224]) + b = [alpha,1] + a = [1, np.conjugate(alpha)] + gdtest = group_delay((b,a), wref)[1] + # need nulp=14 for macOS arm64 wheel builds; added 2 for some + # robustness on other platforms. + assert_array_almost_equal_nulp(gdtest, gdref, nulp=16) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + group_delay((1, 1), fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + group_delay((1, 1), fs=None) + + +class TestGammatone: + # Test erroneous input cases. + def test_invalid_input(self): + # Cutoff frequency is <= 0 or >= fs / 2. + fs = 16000 + for args in [(-fs, 'iir'), (0, 'fir'), (fs / 2, 'iir'), (fs, 'fir')]: + with pytest.raises(ValueError, match='The frequency must be ' + 'between '): + gammatone(*args, fs=fs) + + # Filter type is not fir or iir + for args in [(440, 'fie'), (220, 'it')]: + with pytest.raises(ValueError, match='ftype must be '): + gammatone(*args, fs=fs) + + # Order is <= 0 or > 24 for FIR filter. + for args in [(440, 'fir', -50), (220, 'fir', 0), (110, 'fir', 25), + (55, 'fir', 50)]: + with pytest.raises(ValueError, match='Invalid order: '): + gammatone(*args, numtaps=None, fs=fs) + + # Verify that the filter's frequency response is approximately + # 1 at the cutoff frequency. + def test_frequency_response(self): + fs = 16000 + ftypes = ['fir', 'iir'] + for ftype in ftypes: + # Create a gammatone filter centered at 1000 Hz. + b, a = gammatone(1000, ftype, fs=fs) + + # Calculate the frequency response. + freqs, response = freqz(b, a) + + # Determine peak magnitude of the response + # and corresponding frequency. + response_max = np.max(np.abs(response)) + freq_hz = freqs[np.argmax(np.abs(response))] / ((2 * np.pi) / fs) + + # Check that the peak magnitude is 1 and the frequency is 1000 Hz. + xp_assert_close(response_max, + np.ones_like(response_max), rtol=1e-2, check_0d=False) + xp_assert_close(freq_hz, + 1000*np.ones_like(freq_hz), rtol=1e-2, check_0d=False) + + # All built-in IIR filters are real, so should have perfectly + # symmetrical poles and zeros. Then ba representation (using + # numpy.poly) will be purely real instead of having negligible + # imaginary parts. + def test_iir_symmetry(self): + b, a = gammatone(440, 'iir', fs=24000) + z, p, k = tf2zpk(b, a) + xp_assert_equal(sorted(z), sorted(z.conj())) + xp_assert_equal(sorted(p), sorted(p.conj())) + xp_assert_equal(k, np.real(k)) + + assert issubclass(b.dtype.type, np.floating) + assert issubclass(a.dtype.type, np.floating) + + # Verify FIR filter coefficients with the paper's + # Mathematica implementation + def test_fir_ba_output(self): + b, _ = gammatone(15, 'fir', fs=1000) + b2 = [0.0, 2.2608075649884e-04, + 1.5077903981357e-03, 4.2033687753998e-03, + 8.1508962726503e-03, 1.2890059089154e-02, + 1.7833890391666e-02, 2.2392613558564e-02, + 2.6055195863104e-02, 2.8435872863284e-02, + 2.9293319149544e-02, 2.852976858014e-02, + 2.6176557156294e-02, 2.2371510270395e-02, + 1.7332485267759e-02] + xp_assert_close(b, b2) + + # Verify IIR filter coefficients with the paper's MATLAB implementation + def test_iir_ba_output(self): + b, a = gammatone(440, 'iir', fs=16000) + b2 = [1.31494461367464e-06, -5.03391196645395e-06, + 7.00649426000897e-06, -4.18951968419854e-06, + 9.02614910412011e-07] + a2 = [1.0, -7.65646235454218, + 25.7584699322366, -49.7319214483238, + 60.2667361289181, -46.9399590980486, + 22.9474798808461, -6.43799381299034, + 0.793651554625368] + xp_assert_close(b, b2) + xp_assert_close(a, a2) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + gammatone(440, 'iir', fs=np.array([10, 20])) + + +class TestOrderFilter: + def test_doc_example(self): + x = np.arange(25).reshape(5, 5) + domain = np.identity(3) + + # minimum of elements 1,3,9 (zero-padded) on phone pad + # 7,5,3 on numpad + expected = np.array( + [[0., 0., 0., 0., 0.], + [0., 0., 1., 2., 0.], + [0., 5., 6., 7., 0.], + [0., 10., 11., 12., 0.], + [0., 0., 0., 0., 0.]], + ) + xp_assert_close(order_filter(x, domain, 0), expected, check_dtype=False) + + # maximum of elements 1,3,9 (zero-padded) on phone pad + # 7,5,3 on numpad + expected = np.array( + [[6., 7., 8., 9., 4.], + [11., 12., 13., 14., 9.], + [16., 17., 18., 19., 14.], + [21., 22., 23., 24., 19.], + [20., 21., 22., 23., 24.]], + ) + xp_assert_close(order_filter(x, domain, 2), expected, check_dtype=False) + + # and, just to complete the set, median of zero-padded elements + expected = np.array( + [[0, 1, 2, 3, 0], + [5, 6, 7, 8, 3], + [10, 11, 12, 13, 8], + [15, 16, 17, 18, 13], + [0, 15, 16, 17, 18]], + ) + xp_assert_close(order_filter(x, domain, 1), expected) + + def test_medfilt_order_filter(self): + x = np.arange(25).reshape(5, 5) + + # median of zero-padded elements 1,5,9 on phone pad + # 7,5,3 on numpad + expected = np.array( + [[0, 1, 2, 3, 0], + [1, 6, 7, 8, 4], + [6, 11, 12, 13, 9], + [11, 16, 17, 18, 14], + [0, 16, 17, 18, 0]], + ) + xp_assert_close(medfilt(x, 3), expected) + + xp_assert_close( + order_filter(x, np.ones((3, 3)), 4), + expected + ) + + def test_order_filter_asymmetric(self): + x = np.arange(25).reshape(5, 5) + domain = np.array( + [[1, 1, 0], + [0, 1, 0], + [0, 0, 0]], + ) + + expected = np.array( + [[0, 0, 0, 0, 0], + [0, 0, 1, 2, 3], + [0, 5, 6, 7, 8], + [0, 10, 11, 12, 13], + [0, 15, 16, 17, 18]] + ) + xp_assert_close(order_filter(x, domain, 0), expected) + + expected = np.array( + [[0, 0, 0, 0, 0], + [0, 1, 2, 3, 4], + [5, 6, 7, 8, 9], + [10, 11, 12, 13, 14], + [15, 16, 17, 18, 19]] + ) + xp_assert_close(order_filter(x, domain, 1), expected) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_fir_filter_design.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_fir_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..cd2b60e63cdcb36e39c6775fa99394d123c2956b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_fir_filter_design.py @@ -0,0 +1,654 @@ +import numpy as np +from numpy.testing import assert_warns +from scipy._lib._array_api import ( + xp_assert_close, xp_assert_equal, + assert_almost_equal, assert_array_almost_equal, +) +from pytest import raises as assert_raises +import pytest + +from scipy.fft import fft +from scipy.special import sinc +from scipy.signal import (kaiser_beta, kaiser_atten, kaiserord, + firwin, firwin2, freqz, remez, firls, minimum_phase +) + + +def test_kaiser_beta(): + b = kaiser_beta(58.7) + assert_almost_equal(b, 0.1102 * 50.0) + b = kaiser_beta(22.0) + assert_almost_equal(b, 0.5842 + 0.07886) + b = kaiser_beta(21.0) + assert b == 0.0 + b = kaiser_beta(10.0) + assert b == 0.0 + + +def test_kaiser_atten(): + a = kaiser_atten(1, 1.0) + assert a == 7.95 + a = kaiser_atten(2, 1/np.pi) + assert a == 2.285 + 7.95 + + +def test_kaiserord(): + assert_raises(ValueError, kaiserord, 1.0, 1.0) + numtaps, beta = kaiserord(2.285 + 7.95 - 0.001, 1/np.pi) + assert (numtaps, beta) == (2, 0.0) + + +class TestFirwin: + + def check_response(self, h, expected_response, tol=.05): + N = len(h) + alpha = 0.5 * (N-1) + m = np.arange(0,N) - alpha # time indices of taps + for freq, expected in expected_response: + actual = abs(np.sum(h*np.exp(-1.j*np.pi*m*freq))) + mse = abs(actual-expected)**2 + assert mse < tol, f'response not as expected, mse={mse:g} > {tol:g}' + + def test_response(self): + N = 51 + f = .5 + # increase length just to try even/odd + h = firwin(N, f) # low-pass from 0 to f + self.check_response(h, [(.25,1), (.75,0)]) + + h = firwin(N+1, f, window='nuttall') # specific window + self.check_response(h, [(.25,1), (.75,0)]) + + h = firwin(N+2, f, pass_zero=False) # stop from 0 to f --> high-pass + self.check_response(h, [(.25,0), (.75,1)]) + + f1, f2, f3, f4 = .2, .4, .6, .8 + h = firwin(N+3, [f1, f2], pass_zero=False) # band-pass filter + self.check_response(h, [(.1,0), (.3,1), (.5,0)]) + + h = firwin(N+4, [f1, f2]) # band-stop filter + self.check_response(h, [(.1,1), (.3,0), (.5,1)]) + + h = firwin(N+5, [f1, f2, f3, f4], pass_zero=False, scale=False) + self.check_response(h, [(.1,0), (.3,1), (.5,0), (.7,1), (.9,0)]) + + h = firwin(N+6, [f1, f2, f3, f4]) # multiband filter + self.check_response(h, [(.1,1), (.3,0), (.5,1), (.7,0), (.9,1)]) + + h = firwin(N+7, 0.1, width=.03) # low-pass + self.check_response(h, [(.05,1), (.75,0)]) + + h = firwin(N+8, 0.1, pass_zero=False) # high-pass + self.check_response(h, [(.05,0), (.75,1)]) + + def mse(self, h, bands): + """Compute mean squared error versus ideal response across frequency + band. + h -- coefficients + bands -- list of (left, right) tuples relative to 1==Nyquist of + passbands + """ + w, H = freqz(h, worN=1024) + f = w/np.pi + passIndicator = np.zeros(len(w), bool) + for left, right in bands: + passIndicator |= (f >= left) & (f < right) + Hideal = np.where(passIndicator, 1, 0) + mse = np.mean(abs(abs(H)-Hideal)**2) + return mse + + def test_scaling(self): + """ + For one lowpass, bandpass, and highpass example filter, this test + checks two things: + - the mean squared error over the frequency domain of the unscaled + filter is smaller than the scaled filter (true for rectangular + window) + - the response of the scaled filter is exactly unity at the center + of the first passband + """ + N = 11 + cases = [ + ([.5], True, (0, 1)), + ([0.2, .6], False, (.4, 1)), + ([.5], False, (1, 1)), + ] + for cutoff, pass_zero, expected_response in cases: + h = firwin(N, cutoff, scale=False, pass_zero=pass_zero, window='ones') + hs = firwin(N, cutoff, scale=True, pass_zero=pass_zero, window='ones') + if len(cutoff) == 1: + if pass_zero: + cutoff = [0] + cutoff + else: + cutoff = cutoff + [1] + msg = 'least squares violation' + assert self.mse(h, [cutoff]) < self.mse(hs, [cutoff]), msg + self.check_response(hs, [expected_response], 1e-12) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + firwin(51, .5, fs=np.array([10, 20])) + + +class TestFirWinMore: + """Different author, different style, different tests...""" + + def test_lowpass(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + kwargs = dict(cutoff=0.5, window=('kaiser', beta), scale=False) + taps = firwin(ntaps, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) + + taps_str = firwin(ntaps, pass_zero='lowpass', **kwargs) + xp_assert_close(taps, taps_str) + + def test_highpass(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + + # Ensure that ntaps is odd. + ntaps |= 1 + + kwargs = dict(cutoff=0.5, window=('kaiser', beta), scale=False) + taps = firwin(ntaps, pass_zero=False, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) + + taps_str = firwin(ntaps, pass_zero='highpass', **kwargs) + xp_assert_close(taps, taps_str) + + def test_bandpass(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + kwargs = dict(cutoff=[0.3, 0.7], window=('kaiser', beta), scale=False) + taps = firwin(ntaps, pass_zero=False, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.2, 0.3-width/2, 0.3+width/2, 0.5, + 0.7-width/2, 0.7+width/2, 0.8, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) + + taps_str = firwin(ntaps, pass_zero='bandpass', **kwargs) + xp_assert_close(taps, taps_str) + + def test_bandstop_multi(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + kwargs = dict(cutoff=[0.2, 0.5, 0.8], window=('kaiser', beta), + scale=False) + taps = firwin(ntaps, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.1, 0.2-width/2, 0.2+width/2, 0.35, + 0.5-width/2, 0.5+width/2, 0.65, + 0.8-width/2, 0.8+width/2, 0.9, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], + decimal=5) + + taps_str = firwin(ntaps, pass_zero='bandstop', **kwargs) + xp_assert_close(taps, taps_str) + + def test_fs_nyq(self): + """Test the fs and nyq keywords.""" + nyquist = 1000 + width = 40.0 + relative_width = width/nyquist + ntaps, beta = kaiserord(120, relative_width) + taps = firwin(ntaps, cutoff=[300, 700], window=('kaiser', beta), + pass_zero=False, scale=False, fs=2*nyquist) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 200, 300-width/2, 300+width/2, 500, + 700-width/2, 700+width/2, 800, 1000]) + freqs, response = freqz(taps, worN=np.pi*freq_samples/nyquist) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) + + def test_bad_cutoff(self): + """Test that invalid cutoff argument raises ValueError.""" + # cutoff values must be greater than 0 and less than 1. + assert_raises(ValueError, firwin, 99, -0.5) + assert_raises(ValueError, firwin, 99, 1.5) + # Don't allow 0 or 1 in cutoff. + assert_raises(ValueError, firwin, 99, [0, 0.5]) + assert_raises(ValueError, firwin, 99, [0.5, 1]) + # cutoff values must be strictly increasing. + assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.2]) + assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.5]) + # Must have at least one cutoff value. + assert_raises(ValueError, firwin, 99, []) + # 2D array not allowed. + assert_raises(ValueError, firwin, 99, [[0.1, 0.2],[0.3, 0.4]]) + # cutoff values must be less than nyq. + assert_raises(ValueError, firwin, 99, 50.0, fs=80) + assert_raises(ValueError, firwin, 99, [10, 20, 30], fs=50) + + def test_even_highpass_raises_value_error(self): + """Test that attempt to create a highpass filter with an even number + of taps raises a ValueError exception.""" + assert_raises(ValueError, firwin, 40, 0.5, pass_zero=False) + assert_raises(ValueError, firwin, 40, [.25, 0.5]) + + def test_bad_pass_zero(self): + """Test degenerate pass_zero cases.""" + with assert_raises(ValueError, match='pass_zero must be'): + firwin(41, 0.5, pass_zero='foo') + with assert_raises(TypeError, match='cannot be interpreted'): + firwin(41, 0.5, pass_zero=1.) + for pass_zero in ('lowpass', 'highpass'): + with assert_raises(ValueError, match='cutoff must have one'): + firwin(41, [0.5, 0.6], pass_zero=pass_zero) + for pass_zero in ('bandpass', 'bandstop'): + with assert_raises(ValueError, match='must have at least two'): + firwin(41, [0.5], pass_zero=pass_zero) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + firwin2(51, .5, 1, fs=np.array([10, 20])) + + +class TestFirwin2: + + def test_invalid_args(self): + # `freq` and `gain` have different lengths. + with assert_raises(ValueError, match='must be of same length'): + firwin2(50, [0, 0.5, 1], [0.0, 1.0]) + # `nfreqs` is less than `ntaps`. + with assert_raises(ValueError, match='ntaps must be less than nfreqs'): + firwin2(50, [0, 0.5, 1], [0.0, 1.0, 1.0], nfreqs=33) + # Decreasing value in `freq` + with assert_raises(ValueError, match='must be nondecreasing'): + firwin2(50, [0, 0.5, 0.4, 1.0], [0, .25, .5, 1.0]) + # Value in `freq` repeated more than once. + with assert_raises(ValueError, match='must not occur more than twice'): + firwin2(50, [0, .1, .1, .1, 1.0], [0.0, 0.5, 0.75, 1.0, 1.0]) + # `freq` does not start at 0.0. + with assert_raises(ValueError, match='start with 0'): + firwin2(50, [0.5, 1.0], [0.0, 1.0]) + # `freq` does not end at fs/2. + with assert_raises(ValueError, match='end with fs/2'): + firwin2(50, [0.0, 0.5], [0.0, 1.0]) + # Value 0 is repeated in `freq` + with assert_raises(ValueError, match='0 must not be repeated'): + firwin2(50, [0.0, 0.0, 0.5, 1.0], [1.0, 1.0, 0.0, 0.0]) + # Value fs/2 is repeated in `freq` + with assert_raises(ValueError, match='fs/2 must not be repeated'): + firwin2(50, [0.0, 0.5, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0]) + # Value in `freq` that is too close to a repeated number + with assert_raises(ValueError, match='cannot contain numbers ' + 'that are too close'): + firwin2(50, [0.0, 0.5 - np.finfo(float).eps * 0.5, 0.5, 0.5, 1.0], + [1.0, 1.0, 1.0, 0.0, 0.0]) + + # Type II filter, but the gain at nyquist frequency is not zero. + with assert_raises(ValueError, match='Type II filter'): + firwin2(16, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0]) + + # Type III filter, but the gains at nyquist and zero rate are not zero. + with assert_raises(ValueError, match='Type III filter'): + firwin2(17, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0], antisymmetric=True) + with assert_raises(ValueError, match='Type III filter'): + firwin2(17, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True) + with assert_raises(ValueError, match='Type III filter'): + firwin2(17, [0.0, 0.5, 1.0], [1.0, 1.0, 1.0], antisymmetric=True) + + # Type IV filter, but the gain at zero rate is not zero. + with assert_raises(ValueError, match='Type IV filter'): + firwin2(16, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True) + + def test01(self): + width = 0.04 + beta = 12.0 + ntaps = 400 + # Filter is 1 from w=0 to w=0.5, then decreases linearly from 1 to 0 as w + # increases from w=0.5 to w=1 (w=1 is the Nyquist frequency). + freq = [0.0, 0.5, 1.0] + gain = [1.0, 1.0, 0.0] + taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) + freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, + 0.75, 1.0-width/2]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 1.0, 1.0-width, 0.5, width], decimal=5) + + def test02(self): + width = 0.04 + beta = 12.0 + # ntaps must be odd for positive gain at Nyquist. + ntaps = 401 + # An ideal highpass filter. + freq = [0.0, 0.5, 0.5, 1.0] + gain = [0.0, 0.0, 1.0, 1.0] + taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) + freq_samples = np.array([0.0, 0.25, 0.5-width, 0.5+width, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) + + def test03(self): + width = 0.02 + ntaps, beta = kaiserord(120, width) + # ntaps must be odd for positive gain at Nyquist. + ntaps = int(ntaps) | 1 + freq = [0.0, 0.4, 0.4, 0.5, 0.5, 1.0] + gain = [1.0, 1.0, 0.0, 0.0, 1.0, 1.0] + taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) + freq_samples = np.array([0.0, 0.4-width, 0.4+width, 0.45, + 0.5-width, 0.5+width, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) + + def test04(self): + """Test firwin2 when window=None.""" + ntaps = 5 + # Ideal lowpass: gain is 1 on [0,0.5], and 0 on [0.5, 1.0] + freq = [0.0, 0.5, 0.5, 1.0] + gain = [1.0, 1.0, 0.0, 0.0] + taps = firwin2(ntaps, freq, gain, window=None, nfreqs=8193) + alpha = 0.5 * (ntaps - 1) + m = np.arange(0, ntaps) - alpha + h = 0.5 * sinc(0.5 * m) + assert_array_almost_equal(h, taps) + + def test05(self): + """Test firwin2 for calculating Type IV filters""" + ntaps = 1500 + + freq = [0.0, 1.0] + gain = [0.0, 1.0] + taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True) + assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2:][::-1]) + + freqs, response = freqz(taps, worN=2048) + assert_array_almost_equal(abs(response), freqs / np.pi, decimal=4) + + def test06(self): + """Test firwin2 for calculating Type III filters""" + ntaps = 1501 + + freq = [0.0, 0.5, 0.55, 1.0] + gain = [0.0, 0.5, 0.0, 0.0] + taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True) + assert taps[ntaps // 2] == 0.0 + assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2 + 1:][::-1]) + + freqs, response1 = freqz(taps, worN=2048) + response2 = np.interp(freqs / np.pi, freq, gain) + assert_array_almost_equal(abs(response1), response2, decimal=3) + + def test_fs_nyq(self): + taps1 = firwin2(80, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) + taps2 = firwin2(80, [0.0, 30.0, 60.0], [1.0, 1.0, 0.0], fs=120.0) + assert_array_almost_equal(taps1, taps2) + + def test_tuple(self): + taps1 = firwin2(150, (0.0, 0.5, 0.5, 1.0), (1.0, 1.0, 0.0, 0.0)) + taps2 = firwin2(150, [0.0, 0.5, 0.5, 1.0], [1.0, 1.0, 0.0, 0.0]) + assert_array_almost_equal(taps1, taps2) + + def test_input_modyfication(self): + freq1 = np.array([0.0, 0.5, 0.5, 1.0]) + freq2 = np.array(freq1) + firwin2(80, freq1, [1.0, 1.0, 0.0, 0.0]) + xp_assert_equal(freq1, freq2) + + +class TestRemez: + + def test_bad_args(self): + assert_raises(ValueError, remez, 11, [0.1, 0.4], [1], type='pooka') + + def test_hilbert(self): + N = 11 # number of taps in the filter + a = 0.1 # width of the transition band + + # design an unity gain hilbert bandpass filter from w to 0.5-w + h = remez(11, [a, 0.5-a], [1], type='hilbert') + + # make sure the filter has correct # of taps + assert len(h) == N, "Number of Taps" + + # make sure it is type III (anti-symmetric tap coefficients) + assert_array_almost_equal(h[:(N-1)//2], -h[:-(N-1)//2-1:-1]) + + # Since the requested response is symmetric, all even coefficients + # should be zero (or in this case really small) + assert (abs(h[1::2]) < 1e-15).all(), "Even Coefficients Equal Zero" + + # now check the frequency response + w, H = freqz(h, 1) + f = w/2/np.pi + Hmag = abs(H) + + # should have a zero at 0 and pi (in this case close to zero) + assert (Hmag[[0, -1]] < 0.02).all(), "Zero at zero and pi" + + # check that the pass band is close to unity + idx = np.logical_and(f > a, f < 0.5-a) + assert (abs(Hmag[idx] - 1) < 0.015).all(), "Pass Band Close To Unity" + + def test_compare(self): + # test comparison to MATLAB + k = [0.024590270518440, -0.041314581814658, -0.075943803756711, + -0.003530911231040, 0.193140296954975, 0.373400753484939, + 0.373400753484939, 0.193140296954975, -0.003530911231040, + -0.075943803756711, -0.041314581814658, 0.024590270518440] + h = remez(12, [0, 0.3, 0.5, 1], [1, 0], fs=2.) + xp_assert_close(h, k) + + h = [-0.038976016082299, 0.018704846485491, -0.014644062687875, + 0.002879152556419, 0.016849978528150, -0.043276706138248, + 0.073641298245579, -0.103908158578635, 0.129770906801075, + -0.147163447297124, 0.153302248456347, -0.147163447297124, + 0.129770906801075, -0.103908158578635, 0.073641298245579, + -0.043276706138248, 0.016849978528150, 0.002879152556419, + -0.014644062687875, 0.018704846485491, -0.038976016082299] + xp_assert_close(remez(21, [0, 0.8, 0.9, 1], [0, 1], fs=2.), h) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + remez(11, .1, 1, fs=np.array([10, 20])) + +class TestFirls: + + def test_bad_args(self): + # even numtaps + assert_raises(ValueError, firls, 10, [0.1, 0.2], [0, 0]) + # odd bands + assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.4], [0, 0, 0]) + # len(bands) != len(desired) + assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.4], [0, 0, 0]) + # non-monotonic bands + assert_raises(ValueError, firls, 11, [0.2, 0.1], [0, 0]) + assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.3], [0] * 4) + assert_raises(ValueError, firls, 11, [0.3, 0.4, 0.1, 0.2], [0] * 4) + assert_raises(ValueError, firls, 11, [0.1, 0.3, 0.2, 0.4], [0] * 4) + # negative desired + assert_raises(ValueError, firls, 11, [0.1, 0.2], [-1, 1]) + # len(weight) != len(pairs) + assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], weight=[1, 2]) + # negative weight + assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], weight=[-1]) + + def test_firls(self): + N = 11 # number of taps in the filter + a = 0.1 # width of the transition band + + # design a halfband symmetric low-pass filter + h = firls(11, [0, a, 0.5-a, 0.5], [1, 1, 0, 0], fs=1.0) + + # make sure the filter has correct # of taps + assert h.shape[0] == N + + # make sure it is symmetric + midx = (N-1) // 2 + assert_array_almost_equal(h[:midx], h[:-midx-1:-1]) + + # make sure the center tap is 0.5 + assert_almost_equal(h[midx], 0.5) + + # For halfband symmetric, odd coefficients (except the center) + # should be zero (really small) + hodd = np.hstack((h[1:midx:2], h[-midx+1::2])) + assert_array_almost_equal(hodd, np.zeros_like(hodd)) + + # now check the frequency response + w, H = freqz(h, 1) + f = w/2/np.pi + Hmag = np.abs(H) + + # check that the pass band is close to unity + idx = np.logical_and(f > 0, f < a) + assert_array_almost_equal(Hmag[idx], np.ones_like(Hmag[idx]), decimal=3) + + # check that the stop band is close to zero + idx = np.logical_and(f > 0.5-a, f < 0.5) + assert_array_almost_equal(Hmag[idx], np.zeros_like(Hmag[idx]), decimal=3) + + def test_compare(self): + # compare to OCTAVE output + taps = firls(9, [0, 0.5, 0.55, 1], [1, 1, 0, 0], weight=[1, 2]) + # >> taps = firls(8, [0 0.5 0.55 1], [1 1 0 0], [1, 2]); + known_taps = [-6.26930101730182e-04, -1.03354450635036e-01, + -9.81576747564301e-03, 3.17271686090449e-01, + 5.11409425599933e-01, 3.17271686090449e-01, + -9.81576747564301e-03, -1.03354450635036e-01, + -6.26930101730182e-04] + xp_assert_close(taps, known_taps) + + # compare to MATLAB output + taps = firls(11, [0, 0.5, 0.5, 1], [1, 1, 0, 0], weight=[1, 2]) + # >> taps = firls(10, [0 0.5 0.5 1], [1 1 0 0], [1, 2]); + known_taps = [ + 0.058545300496815, -0.014233383714318, -0.104688258464392, + 0.012403323025279, 0.317930861136062, 0.488047220029700, + 0.317930861136062, 0.012403323025279, -0.104688258464392, + -0.014233383714318, 0.058545300496815] + xp_assert_close(taps, known_taps) + + # With linear changes: + taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], fs=20) + # >> taps = firls(6, [0, 0.1, 0.2, 0.3, 0.4, 0.5], [1, 0, 0, 1, 1, 0]) + known_taps = [ + 1.156090832768218, -4.1385894727395849, 7.5288619164321826, + -8.5530572592947856, 7.5288619164321826, -4.1385894727395849, + 1.156090832768218] + xp_assert_close(taps, known_taps) + + def test_rank_deficient(self): + # solve() runs but warns (only sometimes, so here we don't use match) + x = firls(21, [0, 0.1, 0.9, 1], [1, 1, 0, 0]) + w, h = freqz(x, fs=2.) + absh2 = np.abs(h[:2]) + xp_assert_close(absh2, np.ones_like(absh2), atol=1e-5) + absh2 = np.abs(h[-2:]) + xp_assert_close(absh2, np.zeros_like(absh2), atol=1e-6, rtol=1e-7) + # switch to pinvh (tolerances could be higher with longer + # filters, but using shorter ones is faster computationally and + # the idea is the same) + x = firls(101, [0, 0.01, 0.99, 1], [1, 1, 0, 0]) + w, h = freqz(x, fs=2.) + mask = w < 0.01 + assert mask.sum() > 3 + habs = np.abs(h[mask]) + xp_assert_close(habs, np.ones_like(habs), atol=1e-4) + mask = w > 0.99 + assert mask.sum() > 3 + habs = np.abs(h[mask]) + xp_assert_close(habs, np.zeros_like(habs), atol=1e-4) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + firls(11, .1, 1, fs=np.array([10, 20])) + +class TestMinimumPhase: + @pytest.mark.thread_unsafe + def test_bad_args(self): + # not enough taps + assert_raises(ValueError, minimum_phase, [1.]) + assert_raises(ValueError, minimum_phase, [1., 1.]) + assert_raises(ValueError, minimum_phase, np.full(10, 1j)) + assert_raises(ValueError, minimum_phase, 'foo') + assert_raises(ValueError, minimum_phase, np.ones(10), n_fft=8) + assert_raises(ValueError, minimum_phase, np.ones(10), method='foo') + assert_warns(RuntimeWarning, minimum_phase, np.arange(3)) + with pytest.raises(ValueError, match="is only supported when"): + minimum_phase(np.ones(3), method='hilbert', half=False) + + def test_homomorphic(self): + # check that it can recover frequency responses of arbitrary + # linear-phase filters + + # for some cases we can get the actual filter back + h = [1, -1] + h_new = minimum_phase(np.convolve(h, h[::-1])) + xp_assert_close(h_new, np.asarray(h, dtype=np.float64), rtol=0.05) + + # but in general we only guarantee we get the magnitude back + rng = np.random.RandomState(0) + for n in (2, 3, 10, 11, 15, 16, 17, 20, 21, 100, 101): + h = rng.randn(n) + h_linear = np.convolve(h, h[::-1]) + h_new = minimum_phase(h_linear) + xp_assert_close(np.abs(fft(h_new)), np.abs(fft(h)), rtol=1e-4) + h_new = minimum_phase(h_linear, half=False) + assert len(h_linear) == len(h_new) + xp_assert_close(np.abs(fft(h_new)), np.abs(fft(h_linear)), rtol=1e-4) + + def test_hilbert(self): + # compare to MATLAB output of reference implementation + + # f=[0 0.3 0.5 1]; + # a=[1 1 0 0]; + # h=remez(11,f,a); + h = remez(12, [0, 0.3, 0.5, 1], [1, 0], fs=2.) + k = [0.349585548646686, 0.373552164395447, 0.326082685363438, + 0.077152207480935, -0.129943946349364, -0.059355880509749] + m = minimum_phase(h, 'hilbert') + xp_assert_close(m, k, rtol=5e-3) + + # f=[0 0.8 0.9 1]; + # a=[0 0 1 1]; + # h=remez(20,f,a); + h = remez(21, [0, 0.8, 0.9, 1], [0, 1], fs=2.) + k = [0.232486803906329, -0.133551833687071, 0.151871456867244, + -0.157957283165866, 0.151739294892963, -0.129293146705090, + 0.100787844523204, -0.065832656741252, 0.035361328741024, + -0.014977068692269, -0.158416139047557] + m = minimum_phase(h, 'hilbert', n_fft=2**19) + xp_assert_close(m, k, rtol=2e-3) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_ltisys.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_ltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..826b39cb0e066b3a6198bbcf1a293f6e0497076b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_ltisys.py @@ -0,0 +1,1225 @@ +import warnings + +import numpy as np +from numpy.testing import suppress_warnings +import pytest +from pytest import raises as assert_raises +from scipy._lib._array_api import( + assert_almost_equal, xp_assert_equal, xp_assert_close +) + +from scipy.signal import (ss2tf, tf2ss, lti, + dlti, bode, freqresp, lsim, impulse, step, + abcd_normalize, place_poles, + TransferFunction, StateSpace, ZerosPolesGain) +from scipy.signal._filter_design import BadCoefficients +import scipy.linalg as linalg + + +def _assert_poles_close(P1,P2, rtol=1e-8, atol=1e-8): + """ + Check each pole in P1 is close to a pole in P2 with a 1e-8 + relative tolerance or 1e-8 absolute tolerance (useful for zero poles). + These tolerances are very strict but the systems tested are known to + accept these poles so we should not be far from what is requested. + """ + P2 = P2.copy() + for p1 in P1: + found = False + for p2_idx in range(P2.shape[0]): + if np.allclose([np.real(p1), np.imag(p1)], + [np.real(P2[p2_idx]), np.imag(P2[p2_idx])], + rtol, atol): + found = True + np.delete(P2, p2_idx) + break + if not found: + raise ValueError("Can't find pole " + str(p1) + " in " + str(P2)) + + +class TestPlacePoles: + + def _check(self, A, B, P, **kwargs): + """ + Perform the most common tests on the poles computed by place_poles + and return the Bunch object for further specific tests + """ + fsf = place_poles(A, B, P, **kwargs) + expected, _ = np.linalg.eig(A - np.dot(B, fsf.gain_matrix)) + _assert_poles_close(expected, fsf.requested_poles) + _assert_poles_close(expected, fsf.computed_poles) + _assert_poles_close(P,fsf.requested_poles) + return fsf + + def test_real(self): + # Test real pole placement using KNV and YT0 algorithm and example 1 in + # section 4 of the reference publication (see place_poles docstring) + A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0, + 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273, + 1.343, -2.104]).reshape(4, 4) + B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146,0]).reshape(4, 2) + P = np.array([-0.2, -0.5, -5.0566, -8.6659]) + + # Check that both KNV and YT compute correct K matrix + self._check(A, B, P, method='KNV0') + self._check(A, B, P, method='YT') + + # Try to reach the specific case in _YT_real where two singular + # values are almost equal. This is to improve code coverage but I + # have no way to be sure this code is really reached + + # on some architectures this can lead to a RuntimeWarning invalid + # value in divide (see gh-7590), so suppress it for now + with np.errstate(invalid='ignore'): + self._check(A, B, (2,2,3,3)) + + def test_complex(self): + # Test complex pole placement on a linearized car model, taken from L. + # Jaulin, Automatique pour la robotique, Cours et Exercices, iSTE + # editions p 184/185 + A = np.array([[0, 7, 0, 0], + [0, 0, 0, 7/3.], + [0, 0, 0, 0], + [0, 0, 0, 0]]) + B = np.array([[0, 0], + [0, 0], + [1, 0], + [0, 1]]) + # Test complex poles on YT + P = np.array([-3, -1, -2-1j, -2+1j]) + # on macOS arm64 this can lead to a RuntimeWarning invalid + # value in divide, so suppress it for now + with np.errstate(divide='ignore', invalid='ignore'): + self._check(A, B, P) + + # Try to reach the specific case in _YT_complex where two singular + # values are almost equal. This is to improve code coverage but I + # have no way to be sure this code is really reached + + P = [0-1e-6j,0+1e-6j,-10,10] + with np.errstate(divide='ignore', invalid='ignore'): + self._check(A, B, P, maxiter=1000) + + # Try to reach the specific case in _YT_complex where the rank two + # update yields two null vectors. This test was found via Monte Carlo. + + A = np.array( + [-2148,-2902, -2267, -598, -1722, -1829, -165, -283, -2546, + -167, -754, -2285, -543, -1700, -584, -2978, -925, -1300, + -1583, -984, -386, -2650, -764, -897, -517, -1598, 2, -1709, + -291, -338, -153, -1804, -1106, -1168, -867, -2297] + ).reshape(6,6) + + B = np.array( + [-108, -374, -524, -1285, -1232, -161, -1204, -672, -637, + -15, -483, -23, -931, -780, -1245, -1129, -1290, -1502, + -952, -1374, -62, -964, -930, -939, -792, -756, -1437, + -491, -1543, -686] + ).reshape(6,5) + P = [-25.-29.j, -25.+29.j, 31.-42.j, 31.+42.j, 33.-41.j, 33.+41.j] + self._check(A, B, P) + + # Use a lot of poles to go through all cases for update_order + # in _YT_loop + + big_A = np.ones((11,11))-np.eye(11) + big_B = np.ones((11,10))-np.diag([1]*10,1)[:,1:] + big_A[:6,:6] = A + big_B[:6,:5] = B + + P = [-10,-20,-30,40,50,60,70,-20-5j,-20+5j,5+3j,5-3j] + with np.errstate(divide='ignore', invalid='ignore'): + self._check(big_A, big_B, P) + + #check with only complex poles and only real poles + P = [-10,-20,-30,-40,-50,-60,-70,-80,-90,-100] + self._check(big_A[:-1,:-1], big_B[:-1,:-1], P) + P = [-10+10j,-20+20j,-30+30j,-40+40j,-50+50j, + -10-10j,-20-20j,-30-30j,-40-40j,-50-50j] + self._check(big_A[:-1,:-1], big_B[:-1,:-1], P) + + # need a 5x5 array to ensure YT handles properly when there + # is only one real pole and several complex + A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0, + 0,0,0,5,0,0,0,0,9]).reshape(5,5) + B = np.array([0,0,0,0,1,0,0,1,2,3]).reshape(5,2) + P = np.array([-2, -3+1j, -3-1j, -1+1j, -1-1j]) + with np.errstate(divide='ignore', invalid='ignore'): + place_poles(A, B, P) + + # same test with an odd number of real poles > 1 + # this is another specific case of YT + P = np.array([-2, -3, -4, -1+1j, -1-1j]) + with np.errstate(divide='ignore', invalid='ignore'): + self._check(A, B, P) + + def test_tricky_B(self): + # check we handle as we should the 1 column B matrices and + # n column B matrices (with n such as shape(A)=(n, n)) + A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0, + 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273, + 1.343, -2.104]).reshape(4, 4) + B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146, 0, 1, 2, 3, 4, + 5, 6, 7, 8]).reshape(4, 4) + + # KNV or YT are not called here, it's a specific case with only + # one unique solution + P = np.array([-0.2, -0.5, -5.0566, -8.6659]) + fsf = self._check(A, B, P) + # rtol and nb_iter should be set to np.nan as the identity can be + # used as transfer matrix + assert np.isnan(fsf.rtol) + assert np.isnan(fsf.nb_iter) + + # check with complex poles too as they trigger a specific case in + # the specific case :-) + P = np.array((-2+1j,-2-1j,-3,-2)) + fsf = self._check(A, B, P) + assert np.isnan(fsf.rtol) + assert np.isnan(fsf.nb_iter) + + #now test with a B matrix with only one column (no optimisation) + B = B[:,0].reshape(4,1) + P = np.array((-2+1j,-2-1j,-3,-2)) + fsf = self._check(A, B, P) + + # we can't optimize anything, check they are set to 0 as expected + assert fsf.rtol == 0 + assert fsf.nb_iter == 0 + + @pytest.mark.thread_unsafe + def test_errors(self): + # Test input mistakes from user + A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0]).reshape(4,4) + B = np.array([0,0,0,0,1,0,0,1]).reshape(4,2) + + #should fail as the method keyword is invalid + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4), + method="foo") + + #should fail as poles are not 1D array + assert_raises(ValueError, place_poles, A, B, + np.array((-2.1,-2.2,-2.3,-2.4)).reshape(4,1)) + + #should fail as A is not a 2D array + assert_raises(ValueError, place_poles, A[:,:,np.newaxis], B, + (-2.1,-2.2,-2.3,-2.4)) + + #should fail as B is not a 2D array + assert_raises(ValueError, place_poles, A, B[:,:,np.newaxis], + (-2.1,-2.2,-2.3,-2.4)) + + #should fail as there are too many poles + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4,-3)) + + #should fail as there are not enough poles + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3)) + + #should fail as the rtol is greater than 1 + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4), + rtol=42) + + #should fail as maxiter is smaller than 1 + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4), + maxiter=-42) + + # should fail as ndim(B) is two + assert_raises(ValueError, place_poles, A, B, (-2,-2,-2,-2)) + + # uncontrollable system + assert_raises(ValueError, place_poles, np.ones((4,4)), + np.ones((4,2)), (1,2,3,4)) + + # Should not raise ValueError as the poles can be placed but should + # raise a warning as the convergence is not reached + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + fsf = place_poles(A, B, (-1,-2,-3,-4), rtol=1e-16, maxiter=42) + assert len(w) == 1 + assert issubclass(w[-1].category, UserWarning) + assert ("Convergence was not reached after maxiter iterations" + in str(w[-1].message)) + assert fsf.nb_iter == 42 + + # should fail as a complex misses its conjugate + assert_raises(ValueError, place_poles, A, B, (-2+1j,-2-1j,-2+3j,-2)) + + # should fail as A is not square + assert_raises(ValueError, place_poles, A[:,:3], B, (-2,-3,-4,-5)) + + # should fail as B has not the same number of lines as A + assert_raises(ValueError, place_poles, A, B[:3,:], (-2,-3,-4,-5)) + + # should fail as KNV0 does not support complex poles + assert_raises(ValueError, place_poles, A, B, + (-2+1j,-2-1j,-2+3j,-2-3j), method="KNV0") + + +class TestSS2TF: + + def check_matrix_shapes(self, p, q, r): + ss2tf(np.zeros((p, p)), + np.zeros((p, q)), + np.zeros((r, p)), + np.zeros((r, q)), 0) + + def test_shapes(self): + # Each tuple holds: + # number of states, number of inputs, number of outputs + for p, q, r in [(3, 3, 3), (1, 3, 3), (1, 1, 1)]: + self.check_matrix_shapes(p, q, r) + + def test_basic(self): + # Test a round trip through tf2ss and ss2tf. + b = np.array([1.0, 3.0, 5.0]) + a = np.array([1.0, 2.0, 3.0]) + + A, B, C, D = tf2ss(b, a) + xp_assert_close(A, [[-2., -3], [1, 0]], rtol=1e-13) + xp_assert_close(B, [[1.], [0]], rtol=1e-13) + xp_assert_close(C, [[1., 2]], rtol=1e-13) + xp_assert_close(D, [[1.]], rtol=1e-14) + + bb, aa = ss2tf(A, B, C, D) + xp_assert_close(bb[0], b, rtol=1e-13) + xp_assert_close(aa, a, rtol=1e-13) + + def test_zero_order_round_trip(self): + # See gh-5760 + tf = (2, 1) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[0.]], rtol=1e-13) + xp_assert_close(B, [[0.]], rtol=1e-13) + xp_assert_close(C, [[0.]], rtol=1e-13) + xp_assert_close(D, [[2.]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[2., 0]], rtol=1e-13) + xp_assert_close(den, [1., 0], rtol=1e-13) + + tf = ([[5], [2]], 1) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[0.]], rtol=1e-13) + xp_assert_close(B, [[0.]], rtol=1e-13) + xp_assert_close(C, [[0.], [0]], rtol=1e-13) + xp_assert_close(D, [[5.], [2]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[5., 0], [2, 0]], rtol=1e-13) + xp_assert_close(den, [1., 0], rtol=1e-13) + + def test_simo_round_trip(self): + # See gh-5753 + tf = ([[1, 2], [1, 1]], [1, 2]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-2.]], rtol=1e-13) + xp_assert_close(B, [[1.]], rtol=1e-13) + xp_assert_close(C, [[0.], [-1.]], rtol=1e-13) + xp_assert_close(D, [[1.], [1.]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[1., 2.], [1., 1.]], rtol=1e-13) + xp_assert_close(den, [1., 2.], rtol=1e-13) + + tf = ([[1, 0, 1], [1, 1, 1]], [1, 1, 1]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-1., -1.], [1., 0.]], rtol=1e-13) + xp_assert_close(B, [[1.], [0.]], rtol=1e-13) + xp_assert_close(C, [[-1., 0.], [0., 0.]], rtol=1e-13) + xp_assert_close(D, [[1.], [1.]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[1., 0., 1.], [1., 1., 1.]], rtol=1e-13) + xp_assert_close(den, [1., 1., 1.], rtol=1e-13) + + tf = ([[1, 2, 3], [1, 2, 3]], [1, 2, 3, 4]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-2., -3, -4], [1, 0, 0], [0, 1, 0]], rtol=1e-13) + xp_assert_close(B, [[1.], [0], [0]], rtol=1e-13) + xp_assert_close(C, [[1., 2, 3], [1, 2, 3]], rtol=1e-13) + xp_assert_close(D, [[0.], [0]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0., 1, 2, 3], [0, 1, 2, 3]], rtol=1e-13) + xp_assert_close(den, [1., 2, 3, 4], rtol=1e-13) + + tf = (np.array([1, [2, 3]], dtype=object), [1, 6]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-6.]], rtol=1e-31) + xp_assert_close(B, [[1.]], rtol=1e-31) + xp_assert_close(C, [[1.], [-9]], rtol=1e-31) + xp_assert_close(D, [[0.], [2]], rtol=1e-31) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0., 1], [2, 3]], rtol=1e-13) + xp_assert_close(den, [1., 6], rtol=1e-13) + + tf = (np.array([[1, -3], [1, 2, 3]], dtype=object), [1, 6, 5]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-6., -5], [1, 0]], rtol=1e-13) + xp_assert_close(B, [[1.], [0]], rtol=1e-13) + xp_assert_close(C, [[1., -3], [-4, -2]], rtol=1e-13) + xp_assert_close(D, [[0.], [1]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0., 1, -3], [1, 2, 3]], rtol=1e-13) + xp_assert_close(den, [1., 6, 5], rtol=1e-13) + + def test_all_int_arrays(self): + A = [[0, 1, 0], [0, 0, 1], [-3, -4, -2]] + B = [[0], [0], [1]] + C = [[5, 1, 0]] + D = [[0]] + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0.0, 0.0, 1.0, 5.0]], rtol=1e-13, atol=1e-14) + xp_assert_close(den, [1.0, 2.0, 4.0, 3.0], rtol=1e-13) + + def test_multioutput(self): + # Regression test for gh-2669. + + # 4 states + A = np.array([[-1.0, 0.0, 1.0, 0.0], + [-1.0, 0.0, 2.0, 0.0], + [-4.0, 0.0, 3.0, 0.0], + [-8.0, 8.0, 0.0, 4.0]]) + + # 1 input + B = np.array([[0.3], + [0.0], + [7.0], + [0.0]]) + + # 3 outputs + C = np.array([[0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + [8.0, 8.0, 0.0, 0.0]]) + + D = np.array([[0.0], + [0.0], + [1.0]]) + + # Get the transfer functions for all the outputs in one call. + b_all, a = ss2tf(A, B, C, D) + + # Get the transfer functions for each output separately. + b0, a0 = ss2tf(A, B, C[0], D[0]) + b1, a1 = ss2tf(A, B, C[1], D[1]) + b2, a2 = ss2tf(A, B, C[2], D[2]) + + # Check that we got the same results. + xp_assert_close(a0, a, rtol=1e-13) + xp_assert_close(a1, a, rtol=1e-13) + xp_assert_close(a2, a, rtol=1e-13) + xp_assert_close(b_all, np.vstack((b0, b1, b2)), rtol=1e-13, atol=1e-14) + + +class TestLsim: + digits_accuracy = 7 + + def lti_nowarn(self, *args): + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + system = lti(*args) + return system + + def test_first_order(self): + # y' = -y + # exact solution is y(t) = exp(-t) + system = self.lti_nowarn(-1.,1.,1.,0.) + t = np.linspace(0,5) + u = np.zeros_like(t) + tout, y, x = lsim(system, u, t, X0=[1.0]) + expected_x = np.exp(-tout) + assert_almost_equal(x, expected_x) + assert_almost_equal(y, expected_x) + + def test_second_order(self): + t = np.linspace(0, 10, 1001) + u = np.zeros_like(t) + # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0. + # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution + # is (1-t)*exp(-t). + system = self.lti_nowarn([1.0], [1.0, 2.0, 1.0]) + tout, y, x = lsim(system, u, t, X0=[1.0, 0.0]) + expected_x = (1.0 - tout) * np.exp(-tout) + assert_almost_equal(x[:, 0], expected_x) + + def test_integrator(self): + # integrator: y' = u + system = self.lti_nowarn(0., 1., 1., 0.) + t = np.linspace(0,5) + u = t + tout, y, x = lsim(system, u, t) + expected_x = 0.5 * tout**2 + assert_almost_equal(x, expected_x, decimal=self.digits_accuracy) + assert_almost_equal(y, expected_x, decimal=self.digits_accuracy) + + def test_two_states(self): + # A system with two state variables, two inputs, and one output. + A = np.array([[-1.0, 0.0], [0.0, -2.0]]) + B = np.array([[1.0, 0.0], [0.0, 1.0]]) + C = np.array([1.0, 0.0]) + D = np.zeros((1, 2)) + + system = self.lti_nowarn(A, B, C, D) + + t = np.linspace(0, 10.0, 21) + u = np.zeros((len(t), 2)) + tout, y, x = lsim(system, U=u, T=t, X0=[1.0, 1.0]) + expected_y = np.exp(-tout) + expected_x0 = np.exp(-tout) + expected_x1 = np.exp(-2.0 * tout) + assert_almost_equal(y, expected_y) + assert_almost_equal(x[:, 0], expected_x0) + assert_almost_equal(x[:, 1], expected_x1) + + def test_double_integrator(self): + # double integrator: y'' = 2u + A = np.array([[0., 1.], [0., 0.]]) + B = np.array([[0.], [1.]]) + C = np.array([[2., 0.]]) + system = self.lti_nowarn(A, B, C, 0.) + t = np.linspace(0,5) + u = np.ones_like(t) + tout, y, x = lsim(system, u, t) + expected_x = np.transpose(np.array([0.5 * tout**2, tout])) + expected_y = tout**2 + assert_almost_equal(x, expected_x, decimal=self.digits_accuracy) + assert_almost_equal(y, expected_y, decimal=self.digits_accuracy) + + def test_jordan_block(self): + # Non-diagonalizable A matrix + # x1' + x1 = x2 + # x2' + x2 = u + # y = x1 + # Exact solution with u = 0 is y(t) = t exp(-t) + A = np.array([[-1., 1.], [0., -1.]]) + B = np.array([[0.], [1.]]) + C = np.array([[1., 0.]]) + system = self.lti_nowarn(A, B, C, 0.) + t = np.linspace(0,5) + u = np.zeros_like(t) + tout, y, x = lsim(system, u, t, X0=[0.0, 1.0]) + expected_y = tout * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_miso(self): + # A system with two state variables, two inputs, and one output. + A = np.array([[-1.0, 0.0], [0.0, -2.0]]) + B = np.array([[1.0, 0.0], [0.0, 1.0]]) + C = np.array([1.0, 0.0]) + D = np.zeros((1,2)) + system = self.lti_nowarn(A, B, C, D) + + t = np.linspace(0, 5.0, 101) + u = np.zeros((len(t), 2)) + tout, y, x = lsim(system, u, t, X0=[1.0, 1.0]) + expected_y = np.exp(-tout) + expected_x0 = np.exp(-tout) + expected_x1 = np.exp(-2.0*tout) + assert_almost_equal(y, expected_y) + assert_almost_equal(x[:,0], expected_x0) + assert_almost_equal(x[:,1], expected_x1) + + def test_nonzero_initial_time(self): + system = self.lti_nowarn(-1.,1.,1.,0.) + t = np.linspace(1,2) + u = np.zeros_like(t) + tout, y, x = lsim(system, u, t, X0=[1.0]) + expected_y = np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_nonequal_timesteps(self): + t = np.array([0.0, 1.0, 1.0, 3.0]) + u = np.array([0.0, 0.0, 1.0, 1.0]) + # Simple integrator: x'(t) = u(t) + system = ([1.0], [1.0, 0.0]) + with assert_raises(ValueError, + match="Time steps are not equally spaced."): + tout, y, x = lsim(system, u, t, X0=[1.0]) + + +class TestImpulse: + def test_first_order(self): + # First order system: x'(t) + x(t) = u(t) + # Exact impulse response is x(t) = exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = impulse(system) + expected_y = np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_fixed_time(self): + # Specify the desired time values for the output. + + # First order system: x'(t) + x(t) = u(t) + # Exact impulse response is x(t) = exp(-t). + system = ([1.0], [1.0,1.0]) + n = 21 + t = np.linspace(0, 2.0, n) + tout, y = impulse(system, T=t) + assert tout.shape == (n,) + assert_almost_equal(tout, t) + expected_y = np.exp(-t) + assert_almost_equal(y, expected_y) + + def test_first_order_initial(self): + # Specify an initial condition as a scalar. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact impulse response is x(t) = 4*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = impulse(system, X0=3.0) + expected_y = 4.0 * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_initial_list(self): + # Specify an initial condition as a list. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact impulse response is x(t) = 4*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = impulse(system, X0=[3.0]) + expected_y = 4.0 * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_integrator(self): + # Simple integrator: x'(t) = u(t) + system = ([1.0], [1.0,0.0]) + tout, y = impulse(system) + expected_y = np.ones_like(tout) + assert_almost_equal(y, expected_y) + + def test_second_order(self): + # Second order system with a repeated root: + # x''(t) + 2*x(t) + x(t) = u(t) + # The exact impulse response is t*exp(-t). + system = ([1.0], [1.0, 2.0, 1.0]) + tout, y = impulse(system) + expected_y = tout * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_array_like(self): + # Test that function can accept sequences, scalars. + system = ([1.0], [1.0, 2.0, 1.0]) + # TODO: add meaningful test where X0 is a list + tout, y = impulse(system, X0=[3], T=[5, 6]) + tout, y = impulse(system, X0=[3], T=[5]) + + def test_array_like2(self): + system = ([1.0], [1.0, 2.0, 1.0]) + tout, y = impulse(system, X0=3, T=5) + + +class TestStep: + def test_first_order(self): + # First order system: x'(t) + x(t) = u(t) + # Exact step response is x(t) = 1 - exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = step(system) + expected_y = 1.0 - np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_fixed_time(self): + # Specify the desired time values for the output. + + # First order system: x'(t) + x(t) = u(t) + # Exact step response is x(t) = 1 - exp(-t). + system = ([1.0], [1.0,1.0]) + n = 21 + t = np.linspace(0, 2.0, n) + tout, y = step(system, T=t) + assert tout.shape == (n,) + assert_almost_equal(tout, t) + expected_y = 1 - np.exp(-t) + assert_almost_equal(y, expected_y) + + def test_first_order_initial(self): + # Specify an initial condition as a scalar. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact step response is x(t) = 1 + 2*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = step(system, X0=3.0) + expected_y = 1 + 2.0*np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_initial_list(self): + # Specify an initial condition as a list. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact step response is x(t) = 1 + 2*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = step(system, X0=[3.0]) + expected_y = 1 + 2.0*np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_integrator(self): + # Simple integrator: x'(t) = u(t) + # Exact step response is x(t) = t. + system = ([1.0],[1.0,0.0]) + tout, y = step(system) + expected_y = tout + assert_almost_equal(y, expected_y) + + def test_second_order(self): + # Second order system with a repeated root: + # x''(t) + 2*x(t) + x(t) = u(t) + # The exact step response is 1 - (1 + t)*exp(-t). + system = ([1.0], [1.0, 2.0, 1.0]) + tout, y = step(system) + expected_y = 1 - (1 + tout) * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_array_like(self): + # Test that function can accept sequences, scalars. + system = ([1.0], [1.0, 2.0, 1.0]) + # TODO: add meaningful test where X0 is a list + tout, y = step(system, T=[5, 6]) + + def test_complex_input(self): + # Test that complex input doesn't raise an error. + # `step` doesn't seem to have been designed for complex input, but this + # works and may be used, so add regression test. See gh-2654. + step(([], [-1], 1+0j)) + + +class TestLti: + def test_lti_instantiation(self): + # Test that lti can be instantiated with sequences, scalars. + # See PR-225. + + # TransferFunction + s = lti([1], [-1]) + assert isinstance(s, TransferFunction) + assert isinstance(s, lti) + assert not isinstance(s, dlti) + assert s.dt is None + + # ZerosPolesGain + s = lti(np.array([]), np.array([-1]), 1) + assert isinstance(s, ZerosPolesGain) + assert isinstance(s, lti) + assert not isinstance(s, dlti) + assert s.dt is None + + # StateSpace + s = lti([], [-1], 1) + s = lti([1], [-1], 1, 3) + assert isinstance(s, StateSpace) + assert isinstance(s, lti) + assert not isinstance(s, dlti) + assert s.dt is None + + +class TestStateSpace: + def test_initialization(self): + # Check that all initializations work + StateSpace(1, 1, 1, 1) + StateSpace([1], [2], [3], [4]) + StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]), + np.array([[1, 0]]), np.array([[0]])) + + def test_conversion(self): + # Check the conversion functions + s = StateSpace(1, 2, 3, 4) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert StateSpace(s) is not s + assert s.to_ss() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_tf() and to_zpk() + + # Getters + s = StateSpace(1, 1, 1, 1) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + assert s.dt is None + + def test_operators(self): + # Test +/-/* operators on systems + + class BadType: + pass + + s1 = StateSpace(np.array([[-0.5, 0.7], [0.3, -0.8]]), + np.array([[1], [0]]), + np.array([[1, 0]]), + np.array([[0]]), + ) + + s2 = StateSpace(np.array([[-0.2, -0.1], [0.4, -0.1]]), + np.array([[1], [0]]), + np.array([[1, 0]]), + np.array([[0]]) + ) + + s_discrete = s1.to_discrete(0.1) + s2_discrete = s2.to_discrete(0.2) + s3_discrete = s2.to_discrete(0.1) + + # Impulse response + t = np.linspace(0, 1, 100) + u = np.zeros_like(t) + u[0] = 1 + + # Test multiplication + for typ in (int, float, complex, np.float32, np.complex128, np.array): + xp_assert_close(lsim(typ(2) * s1, U=u, T=t)[1], + typ(2) * lsim(s1, U=u, T=t)[1]) + + xp_assert_close(lsim(s1 * typ(2), U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] * typ(2)) + + xp_assert_close(lsim(s1 / typ(2), U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] / typ(2)) + + with assert_raises(TypeError): + typ(2) / s1 + + xp_assert_close(lsim(s1 * 2, U=u, T=t)[1], + lsim(s1, U=2 * u, T=t)[1]) + + xp_assert_close(lsim(s1 * s2, U=u, T=t)[1], + lsim(s1, U=lsim(s2, U=u, T=t)[1], T=t)[1], + atol=1e-5) + + with assert_raises(TypeError): + s1 / s1 + + with assert_raises(TypeError): + s1 * s_discrete + + with assert_raises(TypeError): + # Check different discretization constants + s_discrete * s2_discrete + + with assert_raises(TypeError): + s1 * BadType() + + with assert_raises(TypeError): + BadType() * s1 + + with assert_raises(TypeError): + s1 / BadType() + + with assert_raises(TypeError): + BadType() / s1 + + # Test addition + xp_assert_close(lsim(s1 + 2, U=u, T=t)[1], + 2 * u + lsim(s1, U=u, T=t)[1]) + + # Check for dimension mismatch + with assert_raises(ValueError): + s1 + np.array([1, 2]) + + with assert_raises(ValueError): + np.array([1, 2]) + s1 + + with assert_raises(TypeError): + s1 + s_discrete + + with assert_raises(ValueError): + s1 / np.array([[1, 2], [3, 4]]) + + with assert_raises(TypeError): + # Check different discretization constants + s_discrete + s2_discrete + + with assert_raises(TypeError): + s1 + BadType() + + with assert_raises(TypeError): + BadType() + s1 + + xp_assert_close(lsim(s1 + s2, U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] + lsim(s2, U=u, T=t)[1]) + + # Test subtraction + xp_assert_close(lsim(s1 - 2, U=u, T=t)[1], + -2 * u + lsim(s1, U=u, T=t)[1]) + + xp_assert_close(lsim(2 - s1, U=u, T=t)[1], + 2 * u + lsim(-s1, U=u, T=t)[1]) + + xp_assert_close(lsim(s1 - s2, U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] - lsim(s2, U=u, T=t)[1]) + + with assert_raises(TypeError): + s1 - BadType() + + with assert_raises(TypeError): + BadType() - s1 + + s = s_discrete + s3_discrete + assert s.dt == 0.1 + + s = s_discrete * s3_discrete + assert s.dt == 0.1 + + s = 3 * s_discrete + assert s.dt == 0.1 + + s = -s_discrete + assert s.dt == 0.1 + +class TestTransferFunction: + def test_initialization(self): + # Check that all initializations work + TransferFunction(1, 1) + TransferFunction([1], [2]) + TransferFunction(np.array([1]), np.array([2])) + + def test_conversion(self): + # Check the conversion functions + s = TransferFunction([1, 0], [1, -1]) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert TransferFunction(s) is not s + assert s.to_tf() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_ss() and to_zpk() + + # Getters + s = TransferFunction([1, 0], [1, -1]) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + + +class TestZerosPolesGain: + def test_initialization(self): + # Check that all initializations work + ZerosPolesGain(1, 1, 1) + ZerosPolesGain([1], [2], 1) + ZerosPolesGain(np.array([1]), np.array([2]), 1) + + def test_conversion(self): + #Check the conversion functions + s = ZerosPolesGain(1, 2, 3) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert ZerosPolesGain(s) is not s + assert s.to_zpk() is not s + + +class Test_abcd_normalize: + def setup_method(self): + self.A = np.array([[1.0, 2.0], [3.0, 4.0]]) + self.B = np.array([[-1.0], [5.0]]) + self.C = np.array([[4.0, 5.0]]) + self.D = np.array([[2.5]]) + + def test_no_matrix_fails(self): + assert_raises(ValueError, abcd_normalize) + + def test_A_nosquare_fails(self): + assert_raises(ValueError, abcd_normalize, [1, -1], + self.B, self.C, self.D) + + def test_AB_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, [-1, 5], + self.C, self.D) + + def test_AC_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, self.B, + [[4.0], [5.0]], self.D) + + def test_CD_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, self.B, + self.C, [2.5, 0]) + + def test_BD_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, [-1, 5], + self.C, self.D) + + def test_normalized_matrices_unchanged(self): + A, B, C, D = abcd_normalize(self.A, self.B, self.C, self.D) + xp_assert_equal(A, self.A) + xp_assert_equal(B, self.B) + xp_assert_equal(C, self.C) + xp_assert_equal(D, self.D) + + def test_shapes(self): + A, B, C, D = abcd_normalize(self.A, self.B, [1, 0], 0) + xp_assert_equal(A.shape[0], A.shape[1]) + xp_assert_equal(A.shape[0], B.shape[0]) + xp_assert_equal(A.shape[0], C.shape[1]) + xp_assert_equal(C.shape[0], D.shape[0]) + xp_assert_equal(B.shape[1], D.shape[1]) + + def test_zero_dimension_is_not_none1(self): + B_ = np.zeros((2, 0)) + D_ = np.zeros((0, 0)) + A, B, C, D = abcd_normalize(A=self.A, B=B_, D=D_) + xp_assert_equal(A, self.A) + xp_assert_equal(B, B_) + xp_assert_equal(D, D_) + assert C.shape[0] == D_.shape[0] + assert C.shape[1] == self.A.shape[0] + + def test_zero_dimension_is_not_none2(self): + B_ = np.zeros((2, 0)) + C_ = np.zeros((0, 2)) + A, B, C, D = abcd_normalize(A=self.A, B=B_, C=C_) + xp_assert_equal(A, self.A) + xp_assert_equal(B, B_) + xp_assert_equal(C, C_) + assert D.shape[0] == C_.shape[0] + assert D.shape[1] == B_.shape[1] + + def test_missing_A(self): + A, B, C, D = abcd_normalize(B=self.B, C=self.C, D=self.D) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert A.shape == (self.B.shape[0], self.B.shape[0]) + + def test_missing_B(self): + A, B, C, D = abcd_normalize(A=self.A, C=self.C, D=self.D) + assert B.shape[0] == A.shape[0] + assert B.shape[1] == D.shape[1] + assert B.shape == (self.A.shape[0], self.D.shape[1]) + + def test_missing_C(self): + A, B, C, D = abcd_normalize(A=self.A, B=self.B, D=self.D) + assert C.shape[0] == D.shape[0] + assert C.shape[1] == A.shape[0] + assert C.shape == (self.D.shape[0], self.A.shape[0]) + + def test_missing_D(self): + A, B, C, D = abcd_normalize(A=self.A, B=self.B, C=self.C) + assert D.shape[0] == C.shape[0] + assert D.shape[1] == B.shape[1] + assert D.shape == (self.C.shape[0], self.B.shape[1]) + + def test_missing_AB(self): + A, B, C, D = abcd_normalize(C=self.C, D=self.D) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert B.shape[1] == D.shape[1] + assert A.shape == (self.C.shape[1], self.C.shape[1]) + assert B.shape == (self.C.shape[1], self.D.shape[1]) + + def test_missing_AC(self): + A, B, C, D = abcd_normalize(B=self.B, D=self.D) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert C.shape[0] == D.shape[0] + assert C.shape[1] == A.shape[0] + assert A.shape == (self.B.shape[0], self.B.shape[0]) + assert C.shape == (self.D.shape[0], self.B.shape[0]) + + def test_missing_AD(self): + A, B, C, D = abcd_normalize(B=self.B, C=self.C) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert D.shape[0] == C.shape[0] + assert D.shape[1] == B.shape[1] + assert A.shape == (self.B.shape[0], self.B.shape[0]) + assert D.shape == (self.C.shape[0], self.B.shape[1]) + + def test_missing_BC(self): + A, B, C, D = abcd_normalize(A=self.A, D=self.D) + assert B.shape[0] == A.shape[0] + assert B.shape[1] == D.shape[1] + assert C.shape[0] == D.shape[0] + assert C.shape[1], A.shape[0] + assert B.shape == (self.A.shape[0], self.D.shape[1]) + assert C.shape == (self.D.shape[0], self.A.shape[0]) + + def test_missing_ABC_fails(self): + assert_raises(ValueError, abcd_normalize, D=self.D) + + def test_missing_BD_fails(self): + assert_raises(ValueError, abcd_normalize, A=self.A, C=self.C) + + def test_missing_CD_fails(self): + assert_raises(ValueError, abcd_normalize, A=self.A, B=self.B) + + +class Test_bode: + + def test_01(self): + # Test bode() magnitude calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 1 / (s + 1), + # cutoff: 1 rad/s, slope: -20 dB/decade + # H(s=0.1) ~= 0 dB + # H(s=1) ~= -3 dB + # H(s=10) ~= -20 dB + # H(s=100) ~= -40 dB + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, mag, phase = bode(system, w=w) + expected_mag = [0, -3, -20, -40] + assert_almost_equal(mag, expected_mag, decimal=1) + + def test_02(self): + # Test bode() phase calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 1 / (s + 1), + # angle(H(s=0.1)) ~= -5.7 deg + # angle(H(s=1)) ~= -45 deg + # angle(H(s=10)) ~= -84.3 deg + system = lti([1], [1, 1]) + w = [0.1, 1, 10] + w, mag, phase = bode(system, w=w) + expected_phase = [-5.7, -45, -84.3] + assert_almost_equal(phase, expected_phase, decimal=1) + + def test_03(self): + # Test bode() magnitude calculation. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, mag, phase = bode(system, w=w) + jw = w * 1j + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + expected_mag = 20.0 * np.log10(abs(y)) + assert_almost_equal(mag, expected_mag) + + def test_04(self): + # Test bode() phase calculation. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, mag, phase = bode(system, w=w) + jw = w * 1j + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + expected_phase = np.arctan2(y.imag, y.real) * 180.0 / np.pi + assert_almost_equal(phase, expected_phase) + + def test_05(self): + # Test that bode() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + n = 10 + # Expected range is from 0.01 to 10. + expected_w = np.logspace(-2, 1, n) + w, mag, phase = bode(system, n=n) + assert_almost_equal(w, expected_w) + + def test_06(self): + # Test that bode() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = lti([1], [1, 0]) + w, mag, phase = bode(system, n=2) + assert w[0] == 0.01 # a fail would give not-a-number + + def test_07(self): + # bode() should not fail on a system with pure imaginary poles. + # The test passes if bode doesn't raise an exception. + system = lti([1], [1, 0, 100]) + w, mag, phase = bode(system, n=2) + + def test_08(self): + # Test that bode() return continuous phase, issues/2331. + system = lti([], [-10, -30, -40, -60, -70], 1) + w, mag, phase = system.bode(w=np.logspace(-3, 40, 100)) + assert_almost_equal(min(phase), -450, decimal=15) + + def test_from_state_space(self): + # Ensure that bode works with a system that was created from the + # state space representation matrices A, B, C, D. In this case, + # system.num will be a 2-D array with shape (1, n+1), where (n,n) + # is the shape of A. + # A Butterworth lowpass filter is used, so we know the exact + # frequency response. + a = np.array([1.0, 2.0, 2.0, 1.0]) + A = linalg.companion(a).T + B = np.array([[0.0], [0.0], [1.0]]) + C = np.array([[1.0, 0.0, 0.0]]) + D = np.array([[0.0]]) + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + system = lti(A, B, C, D) + w, mag, phase = bode(system, n=100) + + expected_magnitude = 20 * np.log10(np.sqrt(1.0 / (1.0 + w**6))) + assert_almost_equal(mag, expected_magnitude) + + +class Test_freqresp: + + def test_output_manual(self): + # Test freqresp() output calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 1 / (s + 1), + # re(H(s=0.1)) ~= 0.99 + # re(H(s=1)) ~= 0.5 + # re(H(s=10)) ~= 0.0099 + system = lti([1], [1, 1]) + w = [0.1, 1, 10] + w, H = freqresp(system, w=w) + expected_re = [0.99, 0.5, 0.0099] + expected_im = [-0.099, -0.5, -0.099] + assert_almost_equal(H.real, expected_re, decimal=1) + assert_almost_equal(H.imag, expected_im, decimal=1) + + def test_output(self): + # Test freqresp() output calculation. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, H = freqresp(system, w=w) + s = w * 1j + expected = np.polyval(system.num, s) / np.polyval(system.den, s) + assert_almost_equal(H.real, expected.real) + assert_almost_equal(H.imag, expected.imag) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + # Expected range is from 0.01 to 10. + system = lti([1], [1, 1]) + n = 10 + expected_w = np.logspace(-2, 1, n) + w, H = freqresp(system, n=n) + assert_almost_equal(w, expected_w) + + def test_pole_zero(self): + # Test that freqresp() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = lti([1], [1, 0]) + w, H = freqresp(system, n=2) + assert w[0] == 0.01 # a fail would give not-a-number + + def test_from_state_space(self): + # Ensure that freqresp works with a system that was created from the + # state space representation matrices A, B, C, D. In this case, + # system.num will be a 2-D array with shape (1, n+1), where (n,n) is + # the shape of A. + # A Butterworth lowpass filter is used, so we know the exact + # frequency response. + a = np.array([1.0, 2.0, 2.0, 1.0]) + A = linalg.companion(a).T + B = np.array([[0.0],[0.0],[1.0]]) + C = np.array([[1.0, 0.0, 0.0]]) + D = np.array([[0.0]]) + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + system = lti(A, B, C, D) + w, H = freqresp(system, n=100) + s = w * 1j + expected = (1.0 / (1.0 + 2*s + 2*s**2 + s**3)) + assert_almost_equal(H.real, expected.real) + assert_almost_equal(H.imag, expected.imag) + + def test_from_zpk(self): + # 4th order low-pass filter: H(s) = 1 / (s + 1) + system = lti([],[-1]*4,[1]) + w = [0.1, 1, 10, 100] + w, H = freqresp(system, w=w) + s = w * 1j + expected = 1 / (s + 1)**4 + assert_almost_equal(H.real, expected.real) + assert_almost_equal(H.imag, expected.imag) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_max_len_seq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_max_len_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..7610b3f898571d10d75a64f00d900168c7142fbe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_max_len_seq.py @@ -0,0 +1,71 @@ +import numpy as np +from pytest import raises as assert_raises +from scipy._lib._array_api import xp_assert_close, xp_assert_equal + +from numpy.fft import fft, ifft + +from scipy.signal import max_len_seq + + +class TestMLS: + + def test_mls_inputs(self): + # can't all be zero state + assert_raises(ValueError, max_len_seq, + 10, state=np.zeros(10)) + # wrong size state + assert_raises(ValueError, max_len_seq, 10, + state=np.ones(3)) + # wrong length + assert_raises(ValueError, max_len_seq, 10, length=-1) + xp_assert_equal(max_len_seq(10, length=0)[0], + np.asarray([], dtype=np.int8) + ) + # unknown taps + assert_raises(ValueError, max_len_seq, 64) + # bad taps + assert_raises(ValueError, max_len_seq, 10, taps=[-1, 1]) + + def test_mls_output(self): + # define some alternate working taps + alt_taps = {2: [1], 3: [2], 4: [3], 5: [4, 3, 2], 6: [5, 4, 1], 7: [4], + 8: [7, 5, 3]} + # assume the other bit levels work, too slow to test higher orders... + for nbits in range(2, 8): + for state in [None, np.round(np.random.rand(nbits))]: + for taps in [None, alt_taps[nbits]]: + if state is not None and np.all(state == 0): + state[0] = 1 # they can't all be zero + orig_m = max_len_seq(nbits, state=state, + taps=taps)[0] + m = 2. * orig_m - 1. # convert to +/- 1 representation + # First, make sure we got all 1's or -1 + err_msg = "mls had non binary terms" + xp_assert_equal(np.abs(m), np.ones_like(m), + err_msg=err_msg) + # Test via circular cross-correlation, which is just mult. + # in the frequency domain with one signal conjugated + tester = np.real(ifft(fft(m) * np.conj(fft(m)))) + out_len = 2**nbits - 1 + # impulse amplitude == test_len + err_msg = "mls impulse has incorrect value" + xp_assert_close(tester[0], + float(out_len), + err_msg=err_msg + ) + # steady-state is -1 + err_msg = "mls steady-state has incorrect value" + xp_assert_close(tester[1:], + np.full(out_len - 1, -1, dtype=tester.dtype), + err_msg=err_msg) + # let's do the split thing using a couple options + for n in (1, 2**(nbits - 1)): + m1, s1 = max_len_seq(nbits, state=state, taps=taps, + length=n) + m2, s2 = max_len_seq(nbits, state=s1, taps=taps, + length=1) + m3, s3 = max_len_seq(nbits, state=s2, taps=taps, + length=out_len - n - 1) + new_m = np.concatenate((m1, m2, m3)) + xp_assert_equal(orig_m, new_m) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_peak_finding.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_peak_finding.py new file mode 100644 index 0000000000000000000000000000000000000000..8de5a2379c2d43c0a10b5b3facd0b33be0778a36 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_peak_finding.py @@ -0,0 +1,915 @@ +import copy + +import numpy as np +import pytest +from pytest import raises, warns +from scipy._lib._array_api import xp_assert_close, xp_assert_equal + +from scipy.signal._peak_finding import ( + argrelmax, + argrelmin, + peak_prominences, + peak_widths, + _unpack_condition_args, + find_peaks, + find_peaks_cwt, + _identify_ridge_lines +) +from scipy.signal.windows import gaussian +from scipy.signal._peak_finding_utils import _local_maxima_1d, PeakPropertyWarning + + +def _gen_gaussians(center_locs, sigmas, total_length): + xdata = np.arange(0, total_length).astype(float) + out_data = np.zeros(total_length, dtype=float) + for ind, sigma in enumerate(sigmas): + tmp = (xdata - center_locs[ind]) / sigma + out_data += np.exp(-(tmp**2)) + return out_data + + +def _gen_gaussians_even(sigmas, total_length): + num_peaks = len(sigmas) + delta = total_length / (num_peaks + 1) + center_locs = np.linspace(delta, total_length - delta, num=num_peaks).astype(int) + out_data = _gen_gaussians(center_locs, sigmas, total_length) + return out_data, center_locs + + +def _gen_ridge_line(start_locs, max_locs, length, distances, gaps): + """ + Generate coordinates for a ridge line. + + Will be a series of coordinates, starting a start_loc (length 2). + The maximum distance between any adjacent columns will be + `max_distance`, the max distance between adjacent rows + will be `map_gap'. + + `max_locs` should be the size of the intended matrix. The + ending coordinates are guaranteed to be less than `max_locs`, + although they may not approach `max_locs` at all. + """ + + def keep_bounds(num, max_val): + out = max(num, 0) + out = min(out, max_val) + return out + + gaps = copy.deepcopy(gaps) + distances = copy.deepcopy(distances) + + locs = np.zeros([length, 2], dtype=int) + locs[0, :] = start_locs + total_length = max_locs[0] - start_locs[0] - sum(gaps) + if total_length < length: + raise ValueError('Cannot generate ridge line according to constraints') + dist_int = length / len(distances) - 1 + gap_int = length / len(gaps) - 1 + for ind in range(1, length): + nextcol = locs[ind - 1, 1] + nextrow = locs[ind - 1, 0] + 1 + if (ind % dist_int == 0) and (len(distances) > 0): + nextcol += ((-1)**ind)*distances.pop() + if (ind % gap_int == 0) and (len(gaps) > 0): + nextrow += gaps.pop() + nextrow = keep_bounds(nextrow, max_locs[0]) + nextcol = keep_bounds(nextcol, max_locs[1]) + locs[ind, :] = [nextrow, nextcol] + + return [locs[:, 0], locs[:, 1]] + + +class TestLocalMaxima1d: + + def test_empty(self): + """Test with empty signal.""" + x = np.array([], dtype=np.float64) + for array in _local_maxima_1d(x): + xp_assert_equal(array, np.array([]), check_dtype=False) + assert array.base is None + + def test_linear(self): + """Test with linear signal.""" + x = np.linspace(0, 100) + for array in _local_maxima_1d(x): + xp_assert_equal(array, np.array([], dtype=np.intp)) + assert array.base is None + + def test_simple(self): + """Test with simple signal.""" + x = np.linspace(-10, 10, 50) + x[2::3] += 1 + expected = np.arange(2, 50, 3, dtype=np.intp) + for array in _local_maxima_1d(x): + # For plateaus of size 1, the edges are identical with the + # midpoints + xp_assert_equal(array, expected, check_dtype=False) + assert array.base is None + + def test_flat_maxima(self): + """Test if flat maxima are detected correctly.""" + x = np.array([-1.3, 0, 1, 0, 2, 2, 0, 3, 3, 3, 2.99, 4, 4, 4, 4, -10, + -5, -5, -5, -5, -5, -10]) + midpoints, left_edges, right_edges = _local_maxima_1d(x) + xp_assert_equal(midpoints, np.array([2, 4, 8, 12, 18]), check_dtype=False) + xp_assert_equal(left_edges, np.array([2, 4, 7, 11, 16]), check_dtype=False) + xp_assert_equal(right_edges, np.array([2, 5, 9, 14, 20]), check_dtype=False) + + @pytest.mark.parametrize('x', [ + np.array([1., 0, 2]), + np.array([3., 3, 0, 4, 4]), + np.array([5., 5, 5, 0, 6, 6, 6]), + ]) + def test_signal_edges(self, x): + """Test if behavior on signal edges is correct.""" + for array in _local_maxima_1d(x): + xp_assert_equal(array, np.array([], dtype=np.intp)) + assert array.base is None + + def test_exceptions(self): + """Test input validation and raised exceptions.""" + with raises(ValueError, match="wrong number of dimensions"): + _local_maxima_1d(np.ones((1, 1))) + with raises(ValueError, match="expected 'const float64_t'"): + _local_maxima_1d(np.ones(1, dtype=int)) + with raises(TypeError, match="list"): + _local_maxima_1d([1., 2.]) + with raises(TypeError, match="'x' must not be None"): + _local_maxima_1d(None) + + +class TestRidgeLines: + + def test_empty(self): + test_matr = np.zeros([20, 100]) + lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1) + assert len(lines) == 0 + + def test_minimal(self): + test_matr = np.zeros([20, 100]) + test_matr[0, 10] = 1 + lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1) + assert len(lines) == 1 + + test_matr = np.zeros([20, 100]) + test_matr[0:2, 10] = 1 + lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1) + assert len(lines) == 1 + + def test_single_pass(self): + distances = [0, 1, 2, 5] + gaps = [0, 1, 2, 0, 1] + test_matr = np.zeros([20, 50]) + 1e-12 + length = 12 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_distances = np.full(20, max(distances)) + identified_lines = _identify_ridge_lines(test_matr, + max_distances, + max(gaps) + 1) + assert len(identified_lines) == 1 + for iline_, line_ in zip(identified_lines[0], line): + xp_assert_equal(iline_, line_, check_dtype=False) + + def test_single_bigdist(self): + distances = [0, 1, 2, 5] + gaps = [0, 1, 2, 4] + test_matr = np.zeros([20, 50]) + length = 12 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_dist = 3 + max_distances = np.full(20, max_dist) + #This should get 2 lines, since the distance is too large + identified_lines = _identify_ridge_lines(test_matr, + max_distances, + max(gaps) + 1) + assert len(identified_lines) == 2 + + for iline in identified_lines: + adists = np.diff(iline[1]) + np.testing.assert_array_less(np.abs(adists), max_dist) + + agaps = np.diff(iline[0]) + np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1) + + def test_single_biggap(self): + distances = [0, 1, 2, 5] + max_gap = 3 + gaps = [0, 4, 2, 1] + test_matr = np.zeros([20, 50]) + length = 12 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_dist = 6 + max_distances = np.full(20, max_dist) + #This should get 2 lines, since the gap is too large + identified_lines = _identify_ridge_lines(test_matr, max_distances, max_gap) + assert len(identified_lines) == 2 + + for iline in identified_lines: + adists = np.diff(iline[1]) + np.testing.assert_array_less(np.abs(adists), max_dist) + + agaps = np.diff(iline[0]) + np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1) + + def test_single_biggaps(self): + distances = [0] + max_gap = 1 + gaps = [3, 6] + test_matr = np.zeros([50, 50]) + length = 30 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_dist = 1 + max_distances = np.full(50, max_dist) + #This should get 3 lines, since the gaps are too large + identified_lines = _identify_ridge_lines(test_matr, max_distances, max_gap) + assert len(identified_lines) == 3 + + for iline in identified_lines: + adists = np.diff(iline[1]) + np.testing.assert_array_less(np.abs(adists), max_dist) + + agaps = np.diff(iline[0]) + np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1) + + +class TestArgrel: + + def test_empty(self): + # Regression test for gh-2832. + # When there are no relative extrema, make sure that + # the number of empty arrays returned matches the + # dimension of the input. + + empty_array = np.array([], dtype=int) + + z1 = np.zeros(5) + + i = argrelmin(z1) + xp_assert_equal(len(i), 1) + xp_assert_equal(i[0], empty_array, check_dtype=False) + + z2 = np.zeros((3, 5)) + + row, col = argrelmin(z2, axis=0) + xp_assert_equal(row, empty_array, check_dtype=False) + xp_assert_equal(col, empty_array, check_dtype=False) + + row, col = argrelmin(z2, axis=1) + xp_assert_equal(row, empty_array, check_dtype=False) + xp_assert_equal(col, empty_array, check_dtype=False) + + def test_basic(self): + # Note: the docstrings for the argrel{min,max,extrema} functions + # do not give a guarantee of the order of the indices, so we'll + # sort them before testing. + + x = np.array([[1, 2, 2, 3, 2], + [2, 1, 2, 2, 3], + [3, 2, 1, 2, 2], + [2, 3, 2, 1, 2], + [1, 2, 3, 2, 1]]) + + row, col = argrelmax(x, axis=0) + order = np.argsort(row) + xp_assert_equal(row[order], [1, 2, 3], check_dtype=False) + xp_assert_equal(col[order], [4, 0, 1], check_dtype=False) + + row, col = argrelmax(x, axis=1) + order = np.argsort(row) + xp_assert_equal(row[order], [0, 3, 4], check_dtype=False) + xp_assert_equal(col[order], [3, 1, 2], check_dtype=False) + + row, col = argrelmin(x, axis=0) + order = np.argsort(row) + xp_assert_equal(row[order], [1, 2, 3], check_dtype=False) + xp_assert_equal(col[order], [1, 2, 3], check_dtype=False) + + row, col = argrelmin(x, axis=1) + order = np.argsort(row) + xp_assert_equal(row[order], [1, 2, 3], check_dtype=False) + xp_assert_equal(col[order], [1, 2, 3], check_dtype=False) + + def test_highorder(self): + order = 2 + sigmas = [1.0, 2.0, 10.0, 5.0, 15.0] + test_data, act_locs = _gen_gaussians_even(sigmas, 500) + test_data[act_locs + order] = test_data[act_locs]*0.99999 + test_data[act_locs - order] = test_data[act_locs]*0.99999 + rel_max_locs = argrelmax(test_data, order=order, mode='clip')[0] + + assert len(rel_max_locs) == len(act_locs) + assert (rel_max_locs == act_locs).all() + + def test_2d_gaussians(self): + sigmas = [1.0, 2.0, 10.0] + test_data, act_locs = _gen_gaussians_even(sigmas, 100) + rot_factor = 20 + rot_range = np.arange(0, len(test_data)) - rot_factor + test_data_2 = np.vstack([test_data, test_data[rot_range]]) + rel_max_rows, rel_max_cols = argrelmax(test_data_2, axis=1, order=1) + + for rw in range(0, test_data_2.shape[0]): + inds = (rel_max_rows == rw) + + assert len(rel_max_cols[inds]) == len(act_locs) + assert (act_locs == (rel_max_cols[inds] - rot_factor*rw)).all() + + +class TestPeakProminences: + + def test_empty(self): + """ + Test if an empty array is returned if no peaks are provided. + """ + out = peak_prominences([1, 2, 3], []) + for arr, dtype in zip(out, [np.float64, np.intp, np.intp]): + assert arr.size == 0 + assert arr.dtype == dtype + + out = peak_prominences([], []) + for arr, dtype in zip(out, [np.float64, np.intp, np.intp]): + assert arr.size == 0 + assert arr.dtype == dtype + + def test_basic(self): + """ + Test if height of prominences is correctly calculated in signal with + rising baseline (peak widths are 1 sample). + """ + # Prepare basic signal + x = np.array([-1, 1.2, 1.2, 1, 3.2, 1.3, 2.88, 2.1]) + peaks = np.array([1, 2, 4, 6]) + lbases = np.array([0, 0, 0, 5]) + rbases = np.array([3, 3, 5, 7]) + proms = x[peaks] - np.max([x[lbases], x[rbases]], axis=0) + # Test if calculation matches handcrafted result + out = peak_prominences(x, peaks) + xp_assert_equal(out[0], proms, check_dtype=False) + xp_assert_equal(out[1], lbases, check_dtype=False) + xp_assert_equal(out[2], rbases, check_dtype=False) + + def test_edge_cases(self): + """ + Test edge cases. + """ + # Peaks have same height, prominence and bases + x = [0, 2, 1, 2, 1, 2, 0] + peaks = [1, 3, 5] + proms, lbases, rbases = peak_prominences(x, peaks) + xp_assert_equal(proms, np.asarray([2.0, 2, 2]), check_dtype=False) + xp_assert_equal(lbases, [0, 0, 0], check_dtype=False) + xp_assert_equal(rbases, [6, 6, 6], check_dtype=False) + + # Peaks have same height & prominence but different bases + x = [0, 1, 0, 1, 0, 1, 0] + peaks = np.array([1, 3, 5]) + proms, lbases, rbases = peak_prominences(x, peaks) + xp_assert_equal(proms, np.asarray([1.0, 1, 1])) + xp_assert_equal(lbases, peaks - 1, check_dtype=False) + xp_assert_equal(rbases, peaks + 1, check_dtype=False) + + def test_non_contiguous(self): + """ + Test with non-C-contiguous input arrays. + """ + x = np.repeat([-9, 9, 9, 0, 3, 1], 2) + peaks = np.repeat([1, 2, 4], 2) + proms, lbases, rbases = peak_prominences(x[::2], peaks[::2]) + xp_assert_equal(proms, np.asarray([9.0, 9, 2])) + xp_assert_equal(lbases, [0, 0, 3], check_dtype=False) + xp_assert_equal(rbases, [3, 3, 5], check_dtype=False) + + def test_wlen(self): + """ + Test if wlen actually shrinks the evaluation range correctly. + """ + x = [0, 1, 2, 3, 1, 0, -1] + peak = [3] + # Test rounding behavior of wlen + proms = peak_prominences(x, peak) + for prom, val in zip(proms, [3.0, 0, 6]): + assert prom == val + + for wlen, i in [(8, 0), (7, 0), (6, 0), (5, 1), (3.2, 1), (3, 2), (1.1, 2)]: + proms = peak_prominences(x, peak, wlen) + for prom, val in zip(proms, [3. - i, 0 + i, 6 - i]): + assert prom == val + + def test_exceptions(self): + """ + Verify that exceptions and warnings are raised. + """ + # x with dimension > 1 + with raises(ValueError, match='1-D array'): + peak_prominences([[0, 1, 1, 0]], [1, 2]) + # peaks with dimension > 1 + with raises(ValueError, match='1-D array'): + peak_prominences([0, 1, 1, 0], [[1, 2]]) + # x with dimension < 1 + with raises(ValueError, match='1-D array'): + peak_prominences(3, [0,]) + + # empty x with supplied + with raises(ValueError, match='not a valid index'): + peak_prominences([], [0]) + # invalid indices with non-empty x + for p in [-100, -1, 3, 1000]: + with raises(ValueError, match='not a valid index'): + peak_prominences([1, 0, 2], [p]) + + # peaks is not cast-able to np.intp + with raises(TypeError, match='cannot safely cast'): + peak_prominences([0, 1, 1, 0], [1.1, 2.3]) + + # wlen < 3 + with raises(ValueError, match='wlen'): + peak_prominences(np.arange(10), [3, 5], wlen=1) + + @pytest.mark.thread_unsafe + def test_warnings(self): + """ + Verify that appropriate warnings are raised. + """ + msg = "some peaks have a prominence of 0" + for p in [0, 1, 2]: + with warns(PeakPropertyWarning, match=msg): + peak_prominences([1, 0, 2], [p,]) + with warns(PeakPropertyWarning, match=msg): + peak_prominences([0, 1, 1, 1, 0], [2], wlen=2) + + +class TestPeakWidths: + + def test_empty(self): + """ + Test if an empty array is returned if no peaks are provided. + """ + widths = peak_widths([], [])[0] + assert isinstance(widths, np.ndarray) + assert widths.size == 0 + widths = peak_widths([1, 2, 3], [])[0] + assert isinstance(widths, np.ndarray) + assert widths.size == 0 + out = peak_widths([], []) + for arr in out: + assert isinstance(arr, np.ndarray) + assert arr.size == 0 + + @pytest.mark.filterwarnings("ignore:some peaks have a width of 0") + def test_basic(self): + """ + Test a simple use case with easy to verify results at different relative + heights. + """ + x = np.array([1, 0, 1, 2, 1, 0, -1]) + prominence = 2 + for rel_height, width_true, lip_true, rip_true in [ + (0., 0., 3., 3.), # raises warning + (0.25, 1., 2.5, 3.5), + (0.5, 2., 2., 4.), + (0.75, 3., 1.5, 4.5), + (1., 4., 1., 5.), + (2., 5., 1., 6.), + (3., 5., 1., 6.) + ]: + width_calc, height, lip_calc, rip_calc = peak_widths( + x, [3], rel_height) + xp_assert_close(width_calc, np.asarray([width_true])) + xp_assert_close(height, np.asarray([2 - rel_height * prominence])) + xp_assert_close(lip_calc, np.asarray([lip_true])) + xp_assert_close(rip_calc, np.asarray([rip_true])) + + def test_non_contiguous(self): + """ + Test with non-C-contiguous input arrays. + """ + x = np.repeat([0, 100, 50], 4) + peaks = np.repeat([1], 3) + result = peak_widths(x[::4], peaks[::3]) + xp_assert_equal(result, + np.asarray([[0.75], [75], [0.75], [1.5]]) + ) + + def test_exceptions(self): + """ + Verify that argument validation works as intended. + """ + with raises(ValueError, match='1-D array'): + # x with dimension > 1 + peak_widths(np.zeros((3, 4)), np.ones(3)) + with raises(ValueError, match='1-D array'): + # x with dimension < 1 + peak_widths(3, [0]) + with raises(ValueError, match='1-D array'): + # peaks with dimension > 1 + peak_widths(np.arange(10), np.ones((3, 2), dtype=np.intp)) + with raises(ValueError, match='1-D array'): + # peaks with dimension < 1 + peak_widths(np.arange(10), 3) + with raises(ValueError, match='not a valid index'): + # peak pos exceeds x.size + peak_widths(np.arange(10), [8, 11]) + with raises(ValueError, match='not a valid index'): + # empty x with peaks supplied + peak_widths([], [1, 2]) + with raises(TypeError, match='cannot safely cast'): + # peak cannot be safely cast to intp + peak_widths(np.arange(10), [1.1, 2.3]) + with raises(ValueError, match='rel_height'): + # rel_height is < 0 + peak_widths([0, 1, 0, 1, 0], [1, 3], rel_height=-1) + with raises(TypeError, match='None'): + # prominence data contains None + peak_widths([1, 2, 1], [1], prominence_data=(None, None, None)) + + @pytest.mark.thread_unsafe + def test_warnings(self): + """ + Verify that appropriate warnings are raised. + """ + msg = "some peaks have a width of 0" + with warns(PeakPropertyWarning, match=msg): + # Case: rel_height is 0 + peak_widths([0, 1, 0], [1], rel_height=0) + with warns(PeakPropertyWarning, match=msg): + # Case: prominence is 0 and bases are identical + peak_widths( + [0, 1, 1, 1, 0], [2], + prominence_data=(np.array([0.], np.float64), + np.array([2], np.intp), + np.array([2], np.intp)) + ) + + def test_mismatching_prominence_data(self): + """Test with mismatching peak and / or prominence data.""" + x = [0, 1, 0] + peak = [1] + for i, (prominences, left_bases, right_bases) in enumerate([ + ((1.,), (-1,), (2,)), # left base not in x + ((1.,), (0,), (3,)), # right base not in x + ((1.,), (2,), (0,)), # swapped bases same as peak + ((1., 1.), (0, 0), (2, 2)), # array shapes don't match peaks + ((1., 1.), (0,), (2,)), # arrays with different shapes + ((1.,), (0, 0), (2,)), # arrays with different shapes + ((1.,), (0,), (2, 2)) # arrays with different shapes + ]): + # Make sure input is matches output of signal.peak_prominences + prominence_data = (np.array(prominences, dtype=np.float64), + np.array(left_bases, dtype=np.intp), + np.array(right_bases, dtype=np.intp)) + # Test for correct exception + if i < 3: + match = "prominence data is invalid for peak" + else: + match = "arrays in `prominence_data` must have the same shape" + with raises(ValueError, match=match): + peak_widths(x, peak, prominence_data=prominence_data) + + @pytest.mark.filterwarnings("ignore:some peaks have a width of 0") + def test_intersection_rules(self): + """Test if x == eval_height counts as an intersection.""" + # Flatt peak with two possible intersection points if evaluated at 1 + x = [0, 1, 2, 1, 3, 3, 3, 1, 2, 1, 0] + # relative height is 0 -> width is 0 as well, raises warning + xp_assert_close(peak_widths(x, peaks=[5], rel_height=0), + [(0.,), (3.,), (5.,), (5.,)]) + # width_height == x counts as intersection -> nearest 1 is chosen + xp_assert_close(peak_widths(x, peaks=[5], rel_height=2/3), + [(4.,), (1.,), (3.,), (7.,)]) + + +def test_unpack_condition_args(): + """ + Verify parsing of condition arguments for `scipy.signal.find_peaks` function. + """ + x = np.arange(10) + amin_true = x + amax_true = amin_true + 10 + peaks = amin_true[1::2] + + # Test unpacking with None or interval + assert (None, None) == _unpack_condition_args((None, None), x, peaks) + assert (1, None) == _unpack_condition_args(1, x, peaks) + assert (1, None) == _unpack_condition_args((1, None), x, peaks) + assert (None, 2) == _unpack_condition_args((None, 2), x, peaks) + assert (3., 4.5) == _unpack_condition_args((3., 4.5), x, peaks) + + # Test if borders are correctly reduced with `peaks` + amin_calc, amax_calc = _unpack_condition_args((amin_true, amax_true), x, peaks) + xp_assert_equal(amin_calc, amin_true[peaks]) + xp_assert_equal(amax_calc, amax_true[peaks]) + + # Test raises if array borders don't match x + with raises(ValueError, match="array size of lower"): + _unpack_condition_args(amin_true, np.arange(11), peaks) + with raises(ValueError, match="array size of upper"): + _unpack_condition_args((None, amin_true), np.arange(11), peaks) + + +class TestFindPeaks: + + # Keys of optionally returned properties + property_keys = {'peak_heights', 'left_thresholds', 'right_thresholds', + 'prominences', 'left_bases', 'right_bases', 'widths', + 'width_heights', 'left_ips', 'right_ips'} + + def test_constant(self): + """ + Test behavior for signal without local maxima. + """ + open_interval = (None, None) + peaks, props = find_peaks(np.ones(10), + height=open_interval, threshold=open_interval, + prominence=open_interval, width=open_interval) + assert peaks.size == 0 + for key in self.property_keys: + assert props[key].size == 0 + + def test_plateau_size(self): + """ + Test plateau size condition for peaks. + """ + # Prepare signal with peaks with peak_height == plateau_size + plateau_sizes = np.array([1, 2, 3, 4, 8, 20, 111]) + x = np.zeros(plateau_sizes.size * 2 + 1) + x[1::2] = plateau_sizes + repeats = np.ones(x.size, dtype=int) + repeats[1::2] = x[1::2] + x = np.repeat(x, repeats) + + # Test full output + peaks, props = find_peaks(x, plateau_size=(None, None)) + xp_assert_equal(peaks, [1, 3, 7, 11, 18, 33, 100], check_dtype=False) + xp_assert_equal(props["plateau_sizes"], plateau_sizes, check_dtype=False) + xp_assert_equal(props["left_edges"], peaks - (plateau_sizes - 1) // 2, + check_dtype=False) + xp_assert_equal(props["right_edges"], peaks + plateau_sizes // 2, + check_dtype=False) + + # Test conditions + xp_assert_equal(find_peaks(x, plateau_size=4)[0], [11, 18, 33, 100], + check_dtype=False) + xp_assert_equal(find_peaks(x, plateau_size=(None, 3.5))[0], [1, 3, 7], + check_dtype=False) + xp_assert_equal(find_peaks(x, plateau_size=(5, 50))[0], [18, 33], + check_dtype=False) + + def test_height_condition(self): + """ + Test height condition for peaks. + """ + x = (0., 1/3, 0., 2.5, 0, 4., 0) + peaks, props = find_peaks(x, height=(None, None)) + xp_assert_equal(peaks, np.array([1, 3, 5]), check_dtype=False) + xp_assert_equal(props['peak_heights'], np.array([1/3, 2.5, 4.]), + check_dtype=False) + xp_assert_equal(find_peaks(x, height=0.5)[0], np.array([3, 5]), + check_dtype=False) + xp_assert_equal(find_peaks(x, height=(None, 3))[0], np.array([1, 3]), + check_dtype=False) + xp_assert_equal(find_peaks(x, height=(2, 3))[0], np.array([3]), + check_dtype=False) + + def test_threshold_condition(self): + """ + Test threshold condition for peaks. + """ + x = (0, 2, 1, 4, -1) + peaks, props = find_peaks(x, threshold=(None, None)) + xp_assert_equal(peaks, np.array([1, 3]), check_dtype=False) + xp_assert_equal(props['left_thresholds'], np.array([2.0, 3.0])) + xp_assert_equal(props['right_thresholds'], np.array([1.0, 5.0])) + xp_assert_equal(find_peaks(x, threshold=2)[0], np.array([3]), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=3.5)[0], np.array([], dtype=int), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=(None, 5))[0], np.array([1, 3]), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=(None, 4))[0], np.array([1]), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=(2, 4))[0], np.array([], dtype=int), + check_dtype=False) + + def test_distance_condition(self): + """ + Test distance condition for peaks. + """ + # Peaks of different height with constant distance 3 + peaks_all = np.arange(1, 21, 3) + x = np.zeros(21) + x[peaks_all] += np.linspace(1, 2, peaks_all.size) + + # Test if peaks with "minimal" distance are still selected (distance = 3) + xp_assert_equal(find_peaks(x, distance=3)[0], peaks_all, check_dtype=False) + + # Select every second peak (distance > 3) + peaks_subset = find_peaks(x, distance=3.0001)[0] + # Test if peaks_subset is subset of peaks_all + assert np.setdiff1d(peaks_subset, peaks_all, assume_unique=True).size == 0 + + # Test if every second peak was removed + dfs = np.diff(peaks_subset) + xp_assert_equal(dfs, 6*np.ones_like(dfs)) + + # Test priority of peak removal + x = [-2, 1, -1, 0, -3] + peaks_subset = find_peaks(x, distance=10)[0] # use distance > x size + assert peaks_subset.size == 1 and peaks_subset[0] == 1 + + def test_prominence_condition(self): + """ + Test prominence condition for peaks. + """ + x = np.linspace(0, 10, 100) + peaks_true = np.arange(1, 99, 2) + offset = np.linspace(1, 10, peaks_true.size) + x[peaks_true] += offset + prominences = x[peaks_true] - x[peaks_true + 1] + interval = (3, 9) + keep = np.nonzero( + (interval[0] <= prominences) & (prominences <= interval[1])) + + peaks_calc, properties = find_peaks(x, prominence=interval) + xp_assert_equal(peaks_calc, peaks_true[keep], check_dtype=False) + xp_assert_equal(properties['prominences'], prominences[keep], check_dtype=False) + xp_assert_equal(properties['left_bases'], + np.zeros_like(properties['left_bases'])) + xp_assert_equal(properties['right_bases'], peaks_true[keep] + 1, + check_dtype=False) + + def test_width_condition(self): + """ + Test width condition for peaks. + """ + x = np.array([1, 0, 1, 2, 1, 0, -1, 4, 0]) + peaks, props = find_peaks(x, width=(None, 2), rel_height=0.75) + assert peaks.size == 1 + xp_assert_equal(peaks, 7*np.ones_like(peaks)) + xp_assert_close(props['widths'], np.asarray([1.35])) + xp_assert_close(props['width_heights'], np.asarray([1.])) + xp_assert_close(props['left_ips'], np.asarray([6.4])) + xp_assert_close(props['right_ips'], np.asarray([7.75])) + + def test_properties(self): + """ + Test returned properties. + """ + open_interval = (None, None) + x = [0, 1, 0, 2, 1.5, 0, 3, 0, 5, 9] + peaks, props = find_peaks(x, + height=open_interval, threshold=open_interval, + prominence=open_interval, width=open_interval) + assert len(props) == len(self.property_keys) + for key in self.property_keys: + assert peaks.size == props[key].size + + def test_raises(self): + """ + Test exceptions raised by function. + """ + with raises(ValueError, match="1-D array"): + find_peaks(np.array(1)) + with raises(ValueError, match="1-D array"): + find_peaks(np.ones((2, 2))) + with raises(ValueError, match="distance"): + find_peaks(np.arange(10), distance=-1) + + @pytest.mark.filterwarnings("ignore:some peaks have a prominence of 0", + "ignore:some peaks have a width of 0") + def test_wlen_smaller_plateau(self): + """ + Test behavior of prominence and width calculation if the given window + length is smaller than a peak's plateau size. + + Regression test for gh-9110. + """ + peaks, props = find_peaks([0, 1, 1, 1, 0], prominence=(None, None), + width=(None, None), wlen=2) + xp_assert_equal(peaks, 2 * np.ones_like(peaks)) + xp_assert_equal(props["prominences"], np.zeros_like(props["prominences"])) + xp_assert_equal(props["widths"], np.zeros_like(props["widths"])) + xp_assert_equal(props["width_heights"], np.ones_like(props["width_heights"])) + for key in ("left_bases", "right_bases", "left_ips", "right_ips"): + xp_assert_equal(props[key], peaks, check_dtype=False) + + @pytest.mark.parametrize("kwargs", [ + {}, + {"distance": 3.0}, + {"prominence": (None, None)}, + {"width": (None, 2)}, + + ]) + def test_readonly_array(self, kwargs): + """ + Test readonly arrays are accepted. + """ + x = np.linspace(0, 10, 15) + x_readonly = x.copy() + x_readonly.flags.writeable = False + + peaks, _ = find_peaks(x) + peaks_readonly, _ = find_peaks(x_readonly, **kwargs) + + xp_assert_close(peaks, peaks_readonly) + + +class TestFindPeaksCwt: + + def test_find_peaks_exact(self): + """ + Generate a series of gaussians and attempt to find the peak locations. + """ + sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0] + num_points = 500 + test_data, act_locs = _gen_gaussians_even(sigmas, num_points) + widths = np.arange(0.1, max(sigmas)) + found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=0, + min_length=None) + xp_assert_equal(found_locs, act_locs, + check_dtype=False, + err_msg="Found maximum locations did not equal those expected" + ) + + def test_find_peaks_withnoise(self): + """ + Verify that peak locations are (approximately) found + for a series of gaussians with added noise. + """ + sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0] + num_points = 500 + test_data, act_locs = _gen_gaussians_even(sigmas, num_points) + widths = np.arange(0.1, max(sigmas)) + noise_amp = 0.07 + np.random.seed(18181911) + test_data += (np.random.rand(num_points) - 0.5)*(2*noise_amp) + found_locs = find_peaks_cwt(test_data, widths, min_length=15, + gap_thresh=1, min_snr=noise_amp / 5) + + err_msg ='Different number of peaks found than expected' + assert len(found_locs) == len(act_locs), err_msg + diffs = np.abs(found_locs - act_locs) + max_diffs = np.array(sigmas) / 5 + np.testing.assert_array_less(diffs, max_diffs, 'Maximum location differed' + + f'by more than {max_diffs}') + + def test_find_peaks_nopeak(self): + """ + Verify that no peak is found in + data that's just noise. + """ + noise_amp = 1.0 + num_points = 100 + rng = np.random.RandomState(181819141) + test_data = (rng.rand(num_points) - 0.5)*(2*noise_amp) + widths = np.arange(10, 50) + found_locs = find_peaks_cwt(test_data, widths, min_snr=5, noise_perc=30) + assert len(found_locs) == 0 + + def test_find_peaks_with_non_default_wavelets(self): + x = gaussian(200, 2) + widths = np.array([1, 2, 3, 4]) + a = find_peaks_cwt(x, widths, wavelet=gaussian) + + xp_assert_equal(a, np.asarray([100]), check_dtype=False) + + def test_find_peaks_window_size(self): + """ + Verify that window_size is passed correctly to private function and + affects the result. + """ + sigmas = [2.0, 2.0] + num_points = 1000 + test_data, act_locs = _gen_gaussians_even(sigmas, num_points) + widths = np.arange(0.1, max(sigmas), 0.2) + noise_amp = 0.05 + rng = np.random.RandomState(18181911) + test_data += (rng.rand(num_points) - 0.5)*(2*noise_amp) + + # Possibly contrived negative region to throw off peak finding + # when window_size is too large + test_data[250:320] -= 1 + + found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3, + min_length=None, window_size=None) + with pytest.raises(AssertionError): + assert found_locs.size == act_locs.size + + found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3, + min_length=None, window_size=20) + assert found_locs.size == act_locs.size + + def test_find_peaks_with_one_width(self): + """ + Verify that the `width` argument + in `find_peaks_cwt` can be a float + """ + xs = np.arange(0, np.pi, 0.05) + test_data = np.sin(xs) + widths = 1 + found_locs = find_peaks_cwt(test_data, widths) + + np.testing.assert_equal(found_locs, 32) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_result_type.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_result_type.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cadd325a7e36c877df8532ba957712831c2dad --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_result_type.py @@ -0,0 +1,51 @@ +# Regressions tests on result types of some signal functions + +import numpy as np + +from scipy.signal import (decimate, + lfilter_zi, + lfiltic, + sos2tf, + sosfilt_zi) + + +def test_decimate(): + ones_f32 = np.ones(32, dtype=np.float32) + assert decimate(ones_f32, 2).dtype == np.float32 + + ones_i64 = np.ones(32, dtype=np.int64) + assert decimate(ones_i64, 2).dtype == np.float64 + + +def test_lfilter_zi(): + b_f32 = np.array([1, 2, 3], dtype=np.float32) + a_f32 = np.array([4, 5, 6], dtype=np.float32) + assert lfilter_zi(b_f32, a_f32).dtype == np.float32 + + +def test_lfiltic(): + # this would return f32 when given a mix of f32 / f64 args + b_f32 = np.array([1, 2, 3], dtype=np.float32) + a_f32 = np.array([4, 5, 6], dtype=np.float32) + x_f32 = np.ones(32, dtype=np.float32) + + b_f64 = b_f32.astype(np.float64) + a_f64 = a_f32.astype(np.float64) + x_f64 = x_f32.astype(np.float64) + + assert lfiltic(b_f64, a_f32, x_f32).dtype == np.float64 + assert lfiltic(b_f32, a_f64, x_f32).dtype == np.float64 + assert lfiltic(b_f32, a_f32, x_f64).dtype == np.float64 + assert lfiltic(b_f32, a_f32, x_f32, x_f64).dtype == np.float64 + + +def test_sos2tf(): + sos_f32 = np.array([[4, 5, 6, 1, 2, 3]], dtype=np.float32) + b, a = sos2tf(sos_f32) + assert b.dtype == np.float32 + assert a.dtype == np.float32 + + +def test_sosfilt_zi(): + sos_f32 = np.array([[4, 5, 6, 1, 2, 3]], dtype=np.float32) + assert sosfilt_zi(sos_f32).dtype == np.float32 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_savitzky_golay.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_savitzky_golay.py new file mode 100644 index 0000000000000000000000000000000000000000..61d958e35d91b7d537e0bd3551b6cec3f45a4983 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_savitzky_golay.py @@ -0,0 +1,362 @@ +import pytest +import numpy as np +from numpy.testing import (assert_equal, + assert_array_equal, +) + +from scipy._lib._array_api import ( + assert_almost_equal, assert_array_almost_equal, xp_assert_close +) + +from scipy.ndimage import convolve1d # type: ignore[attr-defined] + +from scipy.signal import savgol_coeffs, savgol_filter +from scipy.signal._savitzky_golay import _polyder + + +def check_polyder(p, m, expected): + dp = _polyder(p, m) + assert_array_equal(dp, expected) + + +def test_polyder(): + cases = [ + ([5], 0, [5]), + ([5], 1, [0]), + ([3, 2, 1], 0, [3, 2, 1]), + ([3, 2, 1], 1, [6, 2]), + ([3, 2, 1], 2, [6]), + ([3, 2, 1], 3, [0]), + ([[3, 2, 1], [5, 6, 7]], 0, [[3, 2, 1], [5, 6, 7]]), + ([[3, 2, 1], [5, 6, 7]], 1, [[6, 2], [10, 6]]), + ([[3, 2, 1], [5, 6, 7]], 2, [[6], [10]]), + ([[3, 2, 1], [5, 6, 7]], 3, [[0], [0]]), + ] + for p, m, expected in cases: + check_polyder(np.array(p).T, m, np.array(expected).T) + + +#-------------------------------------------------------------------- +# savgol_coeffs tests +#-------------------------------------------------------------------- + +def alt_sg_coeffs(window_length, polyorder, pos): + """This is an alternative implementation of the SG coefficients. + + It uses numpy.polyfit and numpy.polyval. The results should be + equivalent to those of savgol_coeffs(), but this implementation + is slower. + + window_length should be odd. + + """ + if pos is None: + pos = window_length // 2 + t = np.arange(window_length) + unit = (t == pos).astype(int) + h = np.polyval(np.polyfit(t, unit, polyorder), t) + return h + + +def test_sg_coeffs_trivial(): + # Test a trivial case of savgol_coeffs: polyorder = window_length - 1 + h = savgol_coeffs(1, 0) + xp_assert_close(h, [1.0]) + + h = savgol_coeffs(3, 2) + xp_assert_close(h, [0.0, 1, 0], atol=1e-10) + + h = savgol_coeffs(5, 4) + xp_assert_close(h, [0.0, 0, 1, 0, 0], atol=1e-10) + + h = savgol_coeffs(5, 4, pos=1) + xp_assert_close(h, [0.0, 0, 0, 1, 0], atol=1e-10) + + h = savgol_coeffs(5, 4, pos=1, use='dot') + xp_assert_close(h, [0.0, 1, 0, 0, 0], atol=1e-10) + + +def compare_coeffs_to_alt(window_length, order): + # For the given window_length and order, compare the results + # of savgol_coeffs and alt_sg_coeffs for pos from 0 to window_length - 1. + # Also include pos=None. + for pos in [None] + list(range(window_length)): + h1 = savgol_coeffs(window_length, order, pos=pos, use='dot') + h2 = alt_sg_coeffs(window_length, order, pos=pos) + xp_assert_close(h1, h2, atol=1e-10, + err_msg=("window_length = %d, order = %d, pos = %s" % + (window_length, order, pos))) + + +def test_sg_coeffs_compare(): + # Compare savgol_coeffs() to alt_sg_coeffs(). + for window_length in range(1, 8, 2): + for order in range(window_length): + compare_coeffs_to_alt(window_length, order) + + +def test_sg_coeffs_exact(): + polyorder = 4 + window_length = 9 + halflen = window_length // 2 + + x = np.linspace(0, 21, 43) + delta = x[1] - x[0] + + # The data is a cubic polynomial. We'll use an order 4 + # SG filter, so the filtered values should equal the input data + # (except within half window_length of the edges). + y = 0.5 * x ** 3 - x + h = savgol_coeffs(window_length, polyorder) + y0 = convolve1d(y, h) + xp_assert_close(y0[halflen:-halflen], y[halflen:-halflen]) + + # Check the same input, but use deriv=1. dy is the exact result. + dy = 1.5 * x ** 2 - 1 + h = savgol_coeffs(window_length, polyorder, deriv=1, delta=delta) + y1 = convolve1d(y, h) + xp_assert_close(y1[halflen:-halflen], dy[halflen:-halflen]) + + # Check the same input, but use deriv=2. d2y is the exact result. + d2y = 3.0 * x + h = savgol_coeffs(window_length, polyorder, deriv=2, delta=delta) + y2 = convolve1d(y, h) + xp_assert_close(y2[halflen:-halflen], d2y[halflen:-halflen]) + + +def test_sg_coeffs_deriv(): + # The data in `x` is a sampled parabola, so using savgol_coeffs with an + # order 2 or higher polynomial should give exact results. + i = np.array([-2.0, 0.0, 2.0, 4.0, 6.0]) + x = i ** 2 / 4 + dx = i / 2 + d2x = np.full_like(i, 0.5) + for pos in range(x.size): + coeffs0 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot') + xp_assert_close(coeffs0.dot(x), x[pos], atol=1e-10) + coeffs1 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=1) + xp_assert_close(coeffs1.dot(x), dx[pos], atol=1e-10) + coeffs2 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=2) + xp_assert_close(coeffs2.dot(x), d2x[pos], atol=1e-10) + + +def test_sg_coeffs_deriv_gt_polyorder(): + """ + If deriv > polyorder, the coefficients should be all 0. + This is a regression test for a bug where, e.g., + savgol_coeffs(5, polyorder=1, deriv=2) + raised an error. + """ + coeffs = savgol_coeffs(5, polyorder=1, deriv=2) + assert_array_equal(coeffs, np.zeros(5)) + coeffs = savgol_coeffs(7, polyorder=4, deriv=6) + assert_array_equal(coeffs, np.zeros(7)) + + +def test_sg_coeffs_large(): + # Test that for large values of window_length and polyorder the array of + # coefficients returned is symmetric. The aim is to ensure that + # no potential numeric overflow occurs. + coeffs0 = savgol_coeffs(31, 9) + assert_array_almost_equal(coeffs0, coeffs0[::-1]) + coeffs1 = savgol_coeffs(31, 9, deriv=1) + assert_array_almost_equal(coeffs1, -coeffs1[::-1]) + +# -------------------------------------------------------------------- +# savgol_coeffs tests for even window length +# -------------------------------------------------------------------- + + +def test_sg_coeffs_even_window_length(): + # Simple case - deriv=0, polyorder=0, 1 + window_lengths = [4, 6, 8, 10, 12, 14, 16] + for length in window_lengths: + h_p_d = savgol_coeffs(length, 0, 0) + xp_assert_close(h_p_d, np.ones_like(h_p_d) / length) + + # Verify with closed forms + # deriv=1, polyorder=1, 2 + def h_p_d_closed_form_1(k, m): + return 6*(k - 0.5)/((2*m + 1)*m*(2*m - 1)) + + # deriv=2, polyorder=2 + def h_p_d_closed_form_2(k, m): + numer = 15*(-4*m**2 + 1 + 12*(k - 0.5)**2) + denom = 4*(2*m + 1)*(m + 1)*m*(m - 1)*(2*m - 1) + return numer/denom + + for length in window_lengths: + m = length//2 + expected_output = [h_p_d_closed_form_1(k, m) + for k in range(-m + 1, m + 1)][::-1] + actual_output = savgol_coeffs(length, 1, 1) + xp_assert_close(expected_output, actual_output) + actual_output = savgol_coeffs(length, 2, 1) + xp_assert_close(expected_output, actual_output) + + expected_output = [h_p_d_closed_form_2(k, m) + for k in range(-m + 1, m + 1)][::-1] + actual_output = savgol_coeffs(length, 2, 2) + xp_assert_close(expected_output, actual_output) + actual_output = savgol_coeffs(length, 3, 2) + xp_assert_close(expected_output, actual_output) + +#-------------------------------------------------------------------- +# savgol_filter tests +#-------------------------------------------------------------------- + + +def test_sg_filter_trivial(): + """ Test some trivial edge cases for savgol_filter().""" + x = np.array([1.0]) + y = savgol_filter(x, 1, 0) + assert_equal(y, [1.0]) + + # Input is a single value. With a window length of 3 and polyorder 1, + # the value in y is from the straight-line fit of (-1,0), (0,3) and + # (1, 0) at 0. This is just the average of the three values, hence 1.0. + x = np.array([3.0]) + y = savgol_filter(x, 3, 1, mode='constant') + assert_almost_equal(y, [1.0], decimal=15) + + x = np.array([3.0]) + y = savgol_filter(x, 3, 1, mode='nearest') + assert_almost_equal(y, [3.0], decimal=15) + + x = np.array([1.0] * 3) + y = savgol_filter(x, 3, 1, mode='wrap') + assert_almost_equal(y, [1.0, 1.0, 1.0], decimal=15) + + +def test_sg_filter_basic(): + # Some basic test cases for savgol_filter(). + x = np.array([1.0, 2.0, 1.0]) + y = savgol_filter(x, 3, 1, mode='constant') + xp_assert_close(y, [1.0, 4.0 / 3, 1.0]) + + y = savgol_filter(x, 3, 1, mode='mirror') + xp_assert_close(y, [5.0 / 3, 4.0 / 3, 5.0 / 3]) + + y = savgol_filter(x, 3, 1, mode='wrap') + xp_assert_close(y, [4.0 / 3, 4.0 / 3, 4.0 / 3]) + + +def test_sg_filter_2d(): + x = np.array([[1.0, 2.0, 1.0], + [2.0, 4.0, 2.0]]) + expected = np.array([[1.0, 4.0 / 3, 1.0], + [2.0, 8.0 / 3, 2.0]]) + y = savgol_filter(x, 3, 1, mode='constant') + xp_assert_close(y, expected) + + y = savgol_filter(x.T, 3, 1, mode='constant', axis=0) + xp_assert_close(y, expected.T) + + +def test_sg_filter_interp_edges(): + # Another test with low degree polynomial data, for which we can easily + # give the exact results. In this test, we use mode='interp', so + # savgol_filter should match the exact solution for the entire data set, + # including the edges. + t = np.linspace(-5, 5, 21) + delta = t[1] - t[0] + # Polynomial test data. + x = np.array([t, + 3 * t ** 2, + t ** 3 - t]) + dx = np.array([np.ones_like(t), + 6 * t, + 3 * t ** 2 - 1.0]) + d2x = np.array([np.zeros_like(t), + np.full_like(t, 6), + 6 * t]) + + window_length = 7 + + y = savgol_filter(x, window_length, 3, axis=-1, mode='interp') + xp_assert_close(y, x, atol=1e-12) + + y1 = savgol_filter(x, window_length, 3, axis=-1, mode='interp', + deriv=1, delta=delta) + xp_assert_close(y1, dx, atol=1e-12) + + y2 = savgol_filter(x, window_length, 3, axis=-1, mode='interp', + deriv=2, delta=delta) + xp_assert_close(y2, d2x, atol=1e-12) + + # Transpose everything, and test again with axis=0. + + x = x.T + dx = dx.T + d2x = d2x.T + + y = savgol_filter(x, window_length, 3, axis=0, mode='interp') + xp_assert_close(y, x, atol=1e-12) + + y1 = savgol_filter(x, window_length, 3, axis=0, mode='interp', + deriv=1, delta=delta) + xp_assert_close(y1, dx, atol=1e-12) + + y2 = savgol_filter(x, window_length, 3, axis=0, mode='interp', + deriv=2, delta=delta) + xp_assert_close(y2, d2x, atol=1e-12) + + +def test_sg_filter_interp_edges_3d(): + # Test mode='interp' with a 3-D array. + t = np.linspace(-5, 5, 21) + delta = t[1] - t[0] + x1 = np.array([t, -t]) + x2 = np.array([t ** 2, 3 * t ** 2 + 5]) + x3 = np.array([t ** 3, 2 * t ** 3 + t ** 2 - 0.5 * t]) + dx1 = np.array([np.ones_like(t), -np.ones_like(t)]) + dx2 = np.array([2 * t, 6 * t]) + dx3 = np.array([3 * t ** 2, 6 * t ** 2 + 2 * t - 0.5]) + + # z has shape (3, 2, 21) + z = np.array([x1, x2, x3]) + dz = np.array([dx1, dx2, dx3]) + + y = savgol_filter(z, 7, 3, axis=-1, mode='interp', delta=delta) + xp_assert_close(y, z, atol=1e-10) + + dy = savgol_filter(z, 7, 3, axis=-1, mode='interp', deriv=1, delta=delta) + xp_assert_close(dy, dz, atol=1e-10) + + # z has shape (3, 21, 2) + z = np.array([x1.T, x2.T, x3.T]) + dz = np.array([dx1.T, dx2.T, dx3.T]) + + y = savgol_filter(z, 7, 3, axis=1, mode='interp', delta=delta) + xp_assert_close(y, z, atol=1e-10) + + dy = savgol_filter(z, 7, 3, axis=1, mode='interp', deriv=1, delta=delta) + xp_assert_close(dy, dz, atol=1e-10) + + # z has shape (21, 3, 2) + z = z.swapaxes(0, 1).copy() + dz = dz.swapaxes(0, 1).copy() + + y = savgol_filter(z, 7, 3, axis=0, mode='interp', delta=delta) + xp_assert_close(y, z, atol=1e-10) + + dy = savgol_filter(z, 7, 3, axis=0, mode='interp', deriv=1, delta=delta) + xp_assert_close(dy, dz, atol=1e-10) + + +def test_sg_filter_valid_window_length_3d(): + """Tests that the window_length check is using the correct axis.""" + + x = np.ones((10, 20, 30)) + + savgol_filter(x, window_length=29, polyorder=3, mode='interp') + + with pytest.raises(ValueError, match='window_length must be less than'): + # window_length is more than x.shape[-1]. + savgol_filter(x, window_length=31, polyorder=3, mode='interp') + + savgol_filter(x, window_length=9, polyorder=3, axis=0, mode='interp') + + with pytest.raises(ValueError, match='window_length must be less than'): + # window_length is more than x.shape[0]. + savgol_filter(x, window_length=11, polyorder=3, axis=0, mode='interp') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py new file mode 100644 index 0000000000000000000000000000000000000000..df1ccc639f2041cfc8a6aec50190b34f72d25c84 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py @@ -0,0 +1,880 @@ +"""Unit tests for module `_short_time_fft`. + +This file's structure loosely groups the tests into the following sequential +categories: + +1. Test function `_calc_dual_canonical_window`. +2. Test for invalid parameters and exceptions in `ShortTimeFFT` (until the + `test_from_window` function). +3. Test algorithmic properties of STFT/ISTFT. Some tests were ported from + ``test_spectral.py``. + +Notes +----- +* Mypy 0.990 does interpret the line:: + + from scipy.stats import norm as normal_distribution + + incorrectly (but the code works), hence a ``type: ignore`` was appended. +""" +import math +from itertools import product +from typing import cast, get_args, Literal + +import numpy as np +import pytest +from scipy._lib._array_api import xp_assert_close, xp_assert_equal +from scipy.fft import fftshift +from scipy.stats import norm as normal_distribution # type: ignore +from scipy.signal import get_window, welch, stft, istft, spectrogram + +from scipy.signal._short_time_fft import FFT_MODE_TYPE, \ + _calc_dual_canonical_window, ShortTimeFFT, PAD_TYPE +from scipy.signal.windows import gaussian + + +def test__calc_dual_canonical_window_roundtrip(): + """Test dual window calculation with a round trip to verify duality. + + Note that this works only for canonical window pairs (having minimal + energy) like a Gaussian. + + The window is the same as in the example of `from ShortTimeFFT.from_dual`. + """ + win = gaussian(51, std=10, sym=True) + d_win = _calc_dual_canonical_window(win, 10) + win2 = _calc_dual_canonical_window(d_win, 10) + xp_assert_close(win2, win) + + +def test__calc_dual_canonical_window_exceptions(): + """Raise all exceptions in `_calc_dual_canonical_window`.""" + # Verify that calculation can fail: + with pytest.raises(ValueError, match="hop=5 is larger than window len.*"): + _calc_dual_canonical_window(np.ones(4), 5) + with pytest.raises(ValueError, match=".* Transform not invertible!"): + _calc_dual_canonical_window(np.array([.1, .2, .3, 0]), 4) + + # Verify that parameter `win` may not be integers: + with pytest.raises(ValueError, match="Parameter 'win' cannot be of int.*"): + _calc_dual_canonical_window(np.ones(4, dtype=int), 1) + + +def test_invalid_initializer_parameters(): + """Verify that exceptions get raised on invalid parameters when + instantiating ShortTimeFFT. """ + with pytest.raises(ValueError, match=r"Parameter win must be 1d, " + + r"but win.shape=\(2, 2\)!"): + ShortTimeFFT(np.ones((2, 2)), hop=4, fs=1) + with pytest.raises(ValueError, match="Parameter win must have " + + "finite entries"): + ShortTimeFFT(np.array([1, np.inf, 2, 3]), hop=4, fs=1) + with pytest.raises(ValueError, match="Parameter hop=0 is not " + + "an integer >= 1!"): + ShortTimeFFT(np.ones(4), hop=0, fs=1) + with pytest.raises(ValueError, match="Parameter hop=2.0 is not " + + "an integer >= 1!"): + # noinspection PyTypeChecker + ShortTimeFFT(np.ones(4), hop=2.0, fs=1) + with pytest.raises(ValueError, match=r"dual_win.shape=\(5,\) must equal " + + r"win.shape=\(4,\)!"): + ShortTimeFFT(np.ones(4), hop=2, fs=1, dual_win=np.ones(5)) + with pytest.raises(ValueError, match="Parameter dual_win must be " + + "a finite array!"): + ShortTimeFFT(np.ones(3), hop=2, fs=1, + dual_win=np.array([np.nan, 2, 3])) + + +def test_exceptions_properties_methods(): + """Verify that exceptions get raised when setting properties or calling + method of ShortTimeFFT to/with invalid values.""" + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + with pytest.raises(ValueError, match="Sampling interval T=-1 must be " + + "positive!"): + SFT.T = -1 + with pytest.raises(ValueError, match="Sampling frequency fs=-1 must be " + + "positive!"): + SFT.fs = -1 + with pytest.raises(ValueError, match="fft_mode='invalid_typ' not in " + + r"\('twosided', 'centered', " + + r"'onesided', 'onesided2X'\)!"): + SFT.fft_mode = 'invalid_typ' + with pytest.raises(ValueError, match="For scaling is None, " + + "fft_mode='onesided2X' is invalid.*"): + SFT.fft_mode = 'onesided2X' + with pytest.raises(ValueError, match="Attribute mfft=7 needs to be " + + "at least the window length.*"): + SFT.mfft = 7 + with pytest.raises(ValueError, match="scaling='invalid' not in.*"): + # noinspection PyTypeChecker + SFT.scale_to('invalid') + with pytest.raises(ValueError, match="phase_shift=3.0 has the unit .*"): + SFT.phase_shift = 3.0 + with pytest.raises(ValueError, match="-mfft < phase_shift < mfft " + + "does not hold.*"): + SFT.phase_shift = 2*SFT.mfft + with pytest.raises(ValueError, match="Parameter padding='invalid' not.*"): + # noinspection PyTypeChecker + g = SFT._x_slices(np.zeros(16), k_off=0, p0=0, p1=1, padding='invalid') + next(g) # execute generator + with pytest.raises(ValueError, match="Trend type must be 'linear' " + + "or 'constant'"): + # noinspection PyTypeChecker + SFT.stft_detrend(np.zeros(16), detr='invalid') + with pytest.raises(ValueError, match="Parameter detr=nan is not a str, " + + "function or None!"): + # noinspection PyTypeChecker + SFT.stft_detrend(np.zeros(16), detr=np.nan) + with pytest.raises(ValueError, match="Invalid Parameter p0=0, p1=200.*"): + SFT.p_range(100, 0, 200) + + with pytest.raises(ValueError, match="f_axis=0 may not be equal to " + + "t_axis=0!"): + SFT.istft(np.zeros((SFT.f_pts, 2)), t_axis=0, f_axis=0) + with pytest.raises(ValueError, match=r"S.shape\[f_axis\]=2 must be equal" + + " to self.f_pts=5.*"): + SFT.istft(np.zeros((2, 2))) + with pytest.raises(ValueError, match=r"S.shape\[t_axis\]=1 needs to have" + + " at least 2 slices.*"): + SFT.istft(np.zeros((SFT.f_pts, 1))) + with pytest.raises(ValueError, match=r".*\(k1=100\) <= \(k_max=12\) " + + "is false!$"): + SFT.istft(np.zeros((SFT.f_pts, 3)), k1=100) + with pytest.raises(ValueError, match=r"\(k1=1\) - \(k0=0\) = 1 has to " + + "be at least.* length 4!"): + SFT.istft(np.zeros((SFT.f_pts, 3)), k0=0, k1=1) + + with pytest.raises(ValueError, match=r"Parameter axes_seq='invalid' " + + r"not in \['tf', 'ft'\]!"): + # noinspection PyTypeChecker + SFT.extent(n=100, axes_seq='invalid') + with pytest.raises(ValueError, match="Attribute fft_mode=twosided must.*"): + SFT.fft_mode = 'twosided' + SFT.extent(n=100) + + +@pytest.mark.parametrize('m', ('onesided', 'onesided2X')) +def test_exceptions_fft_mode_complex_win(m: FFT_MODE_TYPE): + """Verify that one-sided spectra are not allowed with complex-valued + windows or with complex-valued signals. + + The reason being, the `rfft` function only accepts real-valued input. + """ + with pytest.raises(ValueError, + match=f"One-sided spectra, i.e., fft_mode='{m}'.*"): + ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode=m) + + SFT = ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode='twosided') + with pytest.raises(ValueError, + match=f"One-sided spectra, i.e., fft_mode='{m}'.*"): + SFT.fft_mode = m + + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1, scale_to='psd', fft_mode='onesided') + with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"): + SFT.stft(np.ones(8)*1j) + SFT.fft_mode = 'onesided2X' + with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"): + SFT.stft(np.ones(8)*1j) + + +def test_invalid_fft_mode_RuntimeError(): + """Ensure exception gets raised when property `fft_mode` is invalid. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + SFT._fft_mode = 'invalid_typ' + + with pytest.raises(RuntimeError): + _ = SFT.f + with pytest.raises(RuntimeError): + SFT._fft_func(np.ones(8)) + with pytest.raises(RuntimeError): + SFT._ifft_func(np.ones(8)) + + +@pytest.mark.parametrize('win_params, Nx', [(('gaussian', 2.), 9), # in docstr + ('triang', 7), + (('kaiser', 4.0), 9), + (('exponential', None, 1.), 9), + (4.0, 9)]) +def test_from_window(win_params, Nx: int): + """Verify that `from_window()` handles parameters correctly. + + The window parameterizations are documented in the `get_window` docstring. + """ + w_sym, fs = get_window(win_params, Nx, fftbins=False), 16. + w_per = get_window(win_params, Nx, fftbins=True) + SFT0 = ShortTimeFFT(w_sym, hop=3, fs=fs, fft_mode='twosided', + scale_to='psd', phase_shift=1) + nperseg = len(w_sym) + noverlap = nperseg - SFT0.hop + SFT1 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap, + symmetric_win=True, fft_mode='twosided', + scale_to='psd', phase_shift=1) + # periodic window: + SFT2 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap, + symmetric_win=False, fft_mode='twosided', + scale_to='psd', phase_shift=1) + # Be informative when comparing instances: + xp_assert_equal(SFT1.win, SFT0.win) + xp_assert_close(SFT2.win, w_per / np.sqrt(sum(w_per**2) * fs)) + for n_ in ('hop', 'T', 'fft_mode', 'mfft', 'scaling', 'phase_shift'): + v0, v1, v2 = (getattr(SFT_, n_) for SFT_ in (SFT0, SFT1, SFT2)) + assert v1 == v0, f"SFT1.{n_}={v1} does not equal SFT0.{n_}={v0}" + assert v2 == v0, f"SFT2.{n_}={v2} does not equal SFT0.{n_}={v0}" + + +def test_dual_win_roundtrip(): + """Verify the duality of `win` and `dual_win`. + + Note that this test does not work for arbitrary windows, since dual windows + are not unique. It always works for invertible STFTs if the windows do not + overlap. + """ + # Non-standard values for keyword arguments (except for `scale_to`): + kw = dict(hop=4, fs=1, fft_mode='twosided', mfft=8, scale_to=None, + phase_shift=2) + SFT0 = ShortTimeFFT(np.ones(4), **kw) + SFT1 = ShortTimeFFT.from_dual(SFT0.dual_win, **kw) + xp_assert_close(SFT1.dual_win, SFT0.win) + + +@pytest.mark.parametrize('scale_to, fac_psd, fac_mag', + [(None, 0.25, 0.125), + ('magnitude', 2.0, 1), + ('psd', 1, 0.5)]) +def test_scaling(scale_to: Literal['magnitude', 'psd'], fac_psd, fac_mag): + """Verify scaling calculations. + + * Verify passing `scale_to`parameter to ``__init__(). + * Roundtrip while changing scaling factor. + """ + SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=scale_to) + assert SFT.fac_psd == fac_psd + assert SFT.fac_magnitude == fac_mag + # increase coverage by accessing properties twice: + assert SFT.fac_psd == fac_psd + assert SFT.fac_magnitude == fac_mag + + x = np.fft.irfft([0, 0, 7, 0, 0, 0, 0]) # periodic signal + Sx = SFT.stft(x) + Sx_mag, Sx_psd = Sx * SFT.fac_magnitude, Sx * SFT.fac_psd + + SFT.scale_to('magnitude') + x_mag = SFT.istft(Sx_mag, k1=len(x)) + xp_assert_close(x_mag, x) + + SFT.scale_to('psd') + x_psd = SFT.istft(Sx_psd, k1=len(x)) + xp_assert_close(x_psd, x) + + +def test_scale_to(): + """Verify `scale_to()` method.""" + SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None) + + SFT.scale_to('magnitude') + assert SFT.scaling == 'magnitude' + assert SFT.fac_psd == 2.0 + assert SFT.fac_magnitude == 1 + + SFT.scale_to('psd') + assert SFT.scaling == 'psd' + assert SFT.fac_psd == 1 + assert SFT.fac_magnitude == 0.5 + + SFT.scale_to('psd') # needed for coverage + + for scale, s_fac in zip(('magnitude', 'psd'), (8, 4)): + SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None) + dual_win = SFT.dual_win.copy() + + SFT.scale_to(cast(Literal['magnitude', 'psd'], scale)) + xp_assert_close(SFT.dual_win, dual_win * s_fac) + + +def test_x_slices_padding(): + """Verify padding. + + The reference arrays were taken from the docstrings of `zero_ext`, + `const_ext`, `odd_ext()`, and `even_ext()` from the _array_tools module. + """ + SFT = ShortTimeFFT(np.ones(5), hop=4, fs=1) + x = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]], dtype=float) + d = {'zeros': [[[0, 0, 1, 2, 3], [0, 0, 0, 1, 4]], + [[3, 4, 5, 0, 0], [4, 9, 16, 0, 0]]], + 'edge': [[[1, 1, 1, 2, 3], [0, 0, 0, 1, 4]], + [[3, 4, 5, 5, 5], [4, 9, 16, 16, 16]]], + 'even': [[[3, 2, 1, 2, 3], [4, 1, 0, 1, 4]], + [[3, 4, 5, 4, 3], [4, 9, 16, 9, 4]]], + 'odd': [[[-1, 0, 1, 2, 3], [-4, -1, 0, 1, 4]], + [[3, 4, 5, 6, 7], [4, 9, 16, 23, 28]]]} + for p_, xx in d.items(): + gen = SFT._x_slices(np.array(x), 0, 0, 2, padding=cast(PAD_TYPE, p_)) + yy = np.array([y_.copy() for y_ in gen]) # due to inplace copying + xx = np.asarray(xx, dtype=np.float64) + xp_assert_equal(yy, xx, err_msg=f"Failed '{p_}' padding.") + + +def test_invertible(): + """Verify `invertible` property. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + assert SFT.invertible + SFT = ShortTimeFFT(np.ones(8), hop=9, fs=1) + assert not SFT.invertible + + +def test_border_values(): + """Ensure that minimum and maximum values of slices are correct.""" + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + assert SFT.p_min == 0 + assert SFT.k_min == -4 + assert SFT.lower_border_end == (4, 1) + assert SFT.lower_border_end == (4, 1) # needed to test caching + assert SFT.p_max(10) == 4 + assert SFT.k_max(10) == 16 + assert SFT.upper_border_begin(10) == (4, 2) + # Raise exceptions: + with pytest.raises(ValueError, match="^Parameter n must be"): + SFT.upper_border_begin(3) + with pytest.raises(ValueError, match="^Parameter n must be"): + SFT._post_padding(3) + +def test_border_values_exotic(): + """Ensure that the border calculations are correct for windows with + zeros. """ + w = np.array([0, 0, 0, 0, 0, 0, 0, 1.]) + SFT = ShortTimeFFT(w, hop=1, fs=1) + assert SFT.lower_border_end == (0, 0) + + SFT = ShortTimeFFT(np.flip(w), hop=20, fs=1) + assert SFT.upper_border_begin(4) == (16, 1) + assert SFT.upper_border_begin(5) == (16, 1) + assert SFT.upper_border_begin(23) == (36, 2) + assert SFT.upper_border_begin(24) == (36, 2) + assert SFT.upper_border_begin(25) == (36, 2) + + SFT._hop = -1 # provoke unreachable line + with pytest.raises(RuntimeError): + _ = SFT.k_max(4) + with pytest.raises(RuntimeError): + _ = SFT.k_min + + +def test_t(): + """Verify that the times of the slices are correct. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=2) + assert SFT.T == 1/2 + assert SFT.fs == 2. + assert SFT.delta_t == 4 * 1/2 + t_stft = np.arange(0, SFT.p_max(10)) * SFT.delta_t + xp_assert_equal(SFT.t(10), t_stft) + xp_assert_equal(SFT.t(10, 1, 3), t_stft[1:3]) + SFT.T = 1/4 + assert SFT.T == 1/4 + assert SFT.fs == 4 + SFT.fs = 1/8 + assert SFT.fs == 1/8 + assert SFT.T == 8 + + +@pytest.mark.parametrize('fft_mode, f', + [('onesided', [0., 1., 2.]), + ('onesided2X', [0., 1., 2.]), + ('twosided', [0., 1., 2., -2., -1.]), + ('centered', [-2., -1., 0., 1., 2.])]) +def test_f(fft_mode: FFT_MODE_TYPE, f): + """Verify the frequency values property `f`.""" + SFT = ShortTimeFFT(np.ones(5), hop=4, fs=5, fft_mode=fft_mode, + scale_to='psd') + xp_assert_equal(SFT.f, f) + + +@pytest.mark.parametrize('n', [20, 21]) +@pytest.mark.parametrize('m', [5, 6]) +@pytest.mark.parametrize('fft_mode', ['onesided', 'centered']) +def test_extent(n, m, fft_mode: FFT_MODE_TYPE): + """Ensure that the `extent()` method is correct. """ + SFT = ShortTimeFFT(np.ones(m), hop=m, fs=m, fft_mode=fft_mode) + + t0 = SFT.t(n)[0] # first timestamp + t1 = SFT.t(n)[-1] + SFT.delta_t # last timestamp + 1 + t0c, t1c = t0 - SFT.delta_t / 2, t1 - SFT.delta_t / 2 # centered timestamps + + f0 = SFT.f[0] # first frequency + f1 = SFT.f[-1] + SFT.delta_f # last frequency + 1 + f0c, f1c = f0 - SFT.delta_f / 2, f1 - SFT.delta_f / 2 # centered frequencies + + assert SFT.extent(n, 'tf', False) == (t0, t1, f0, f1) + assert SFT.extent(n, 'ft', False) == (f0, f1, t0, t1) + assert SFT.extent(n, 'tf', True) == (t0c, t1c, f0c, f1c) + assert SFT.extent(n, 'ft', True) == (f0c, f1c, t0c, t1c) + + +def test_spectrogram(): + """Verify spectrogram and cross-spectrogram methods. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + x, y = np.ones(10), np.arange(10) + X, Y = SFT.stft(x), SFT.stft(y) + xp_assert_close(SFT.spectrogram(x), X.real**2+X.imag**2) + xp_assert_close(SFT.spectrogram(x, y), X * Y.conj()) + + +@pytest.mark.parametrize('n', [8, 9]) +def test_fft_func_roundtrip(n: int): + """Test roundtrip `ifft_func(fft_func(x)) == x` for all permutations of + relevant parameters. """ + np.random.seed(2394795) + x0 = np.random.rand(n) + w, h_n = np.ones(n), 4 + + pp = dict( + fft_mode=get_args(FFT_MODE_TYPE), + mfft=[None, n, n+1, n+2], + scaling=[None, 'magnitude', 'psd'], + phase_shift=[None, -n+1, 0, n // 2, n-1]) + for f_typ, mfft, scaling, phase_shift in product(*pp.values()): + if f_typ == 'onesided2X' and scaling is None: + continue # this combination is forbidden + SFT = ShortTimeFFT(w, h_n, fs=n, fft_mode=f_typ, mfft=mfft, + scale_to=scaling, phase_shift=phase_shift) + X0 = SFT._fft_func(x0) + x1 = SFT._ifft_func(X0) + xp_assert_close(x0.astype(x1.dtype), x1, + err_msg="_fft_func() roundtrip failed for " + + f"{f_typ=}, {mfft=}, {scaling=}, {phase_shift=}") + + SFT = ShortTimeFFT(w, h_n, fs=1) + SFT._fft_mode = 'invalid_fft' # type: ignore + with pytest.raises(RuntimeError): + SFT._fft_func(x0) + with pytest.raises(RuntimeError): + SFT._ifft_func(x0) + + +@pytest.mark.parametrize('i', range(19)) +def test_impulse_roundtrip(i): + """Roundtrip for an impulse being at different positions `i`.""" + n = 19 + w, h_n = np.ones(8), 3 + x = np.zeros(n) + x[i] = 1 + + SFT = ShortTimeFFT(w, hop=h_n, fs=1, scale_to=None, phase_shift=None) + Sx = SFT.stft(x) + # test slicing the input signal into two parts: + n_q = SFT.nearest_k_p(n // 2) + Sx0 = SFT.stft(x[:n_q], padding='zeros') + Sx1 = SFT.stft(x[n_q:], padding='zeros') + q0_ub = SFT.upper_border_begin(n_q)[1] - SFT.p_min + q1_le = SFT.lower_border_end[1] - SFT.p_min + xp_assert_close(Sx0[:, :q0_ub], Sx[:, :q0_ub], err_msg=f"{i=}") + xp_assert_close(Sx1[:, q1_le:], Sx[:, q1_le-Sx1.shape[1]:], + err_msg=f"{i=}") + + Sx01 = np.hstack((Sx0[:, :q0_ub], + Sx0[:, q0_ub:] + Sx1[:, :q1_le], + Sx1[:, q1_le:])) + xp_assert_close(Sx, Sx01, atol=1e-8, err_msg=f"{i=}") + + y = SFT.istft(Sx, 0, n) + xp_assert_close(y, x, atol=1e-8, err_msg=f"{i=}") + y0 = SFT.istft(Sx, 0, n//2) + xp_assert_close(x[:n//2], y0, atol=1e-8, err_msg=f"{i=}") + y1 = SFT.istft(Sx, n // 2, n) + xp_assert_close(x[n // 2:], y1, atol=1e-8, err_msg=f"{i=}") + + +@pytest.mark.parametrize('hop', [1, 7, 8]) +def test_asymmetric_window_roundtrip(hop: int): + """An asymmetric window could uncover indexing problems. """ + np.random.seed(23371) + + w = np.arange(16) / 8 # must be of type float + w[len(w)//2:] = 1 + SFT = ShortTimeFFT(w, hop, fs=1) + + x = 10 * np.random.randn(64) + Sx = SFT.stft(x) + x1 = SFT.istft(Sx, k1=len(x)) + xp_assert_close(x1, x1, err_msg="Roundtrip for asymmetric window with " + + f" {hop=} failed!") + + +@pytest.mark.parametrize('m_num', [6, 7]) +def test_minimal_length_signal(m_num): + """Verify that the shortest allowed signal works. """ + SFT = ShortTimeFFT(np.ones(m_num), m_num//2, fs=1) + n = math.ceil(m_num/2) + x = np.ones(n) + Sx = SFT.stft(x) + x1 = SFT.istft(Sx, k1=n) + xp_assert_close(x1, x, err_msg=f"Roundtrip minimal length signal ({n=})" + + f" for {m_num} sample window failed!") + with pytest.raises(ValueError, match=rf"len\(x\)={n-1} must be >= ceil.*"): + SFT.stft(x[:-1]) + with pytest.raises(ValueError, match=rf"S.shape\[t_axis\]={Sx.shape[1]-1}" + f" needs to have at least {Sx.shape[1]} slices"): + SFT.istft(Sx[:, :-1], k1=n) + + +def test_tutorial_stft_sliding_win(): + """Verify example in "Sliding Windows" subsection from the "User Guide". + + In :ref:`tutorial_stft_sliding_win` (file ``signal.rst``) of the + :ref:`user_guide` the behavior the border behavior of + ``ShortTimeFFT(np.ones(6), 2, fs=1)`` with a 50 sample signal is discussed. + This test verifies the presented indexes. + """ + SFT = ShortTimeFFT(np.ones(6), 2, fs=1) + + # Lower border: + assert SFT.m_num_mid == 3, f"Slice middle is not 3 but {SFT.m_num_mid=}" + assert SFT.p_min == -1, f"Lowest slice {SFT.p_min=} is not -1" + assert SFT.k_min == -5, f"Lowest slice sample {SFT.p_min=} is not -5" + k_lb, p_lb = SFT.lower_border_end + assert p_lb == 2, f"First unaffected slice {p_lb=} is not 2" + assert k_lb == 5, f"First unaffected sample {k_lb=} is not 5" + + n = 50 # upper signal border + assert (p_max := SFT.p_max(n)) == 27, f"Last slice {p_max=} must be 27" + assert (k_max := SFT.k_max(n)) == 55, f"Last sample {k_max=} must be 55" + k_ub, p_ub = SFT.upper_border_begin(n) + assert p_ub == 24, f"First upper border slice {p_ub=} must be 24" + assert k_ub == 45, f"First upper border slice {k_ub=} must be 45" + + +def test_tutorial_stft_legacy_stft(): + """Verify STFT example in "Comparison with Legacy Implementation" from the + "User Guide". + + In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the + :ref:`user_guide` the legacy and the new implementation are compared. + """ + fs, N = 200, 1001 # # 200 Hz sampling rate for 5 s signal + t_z = np.arange(N) / fs # time indexes for signal + z = np.exp(2j*np.pi * 70 * (t_z - 0.2 * t_z ** 2)) # complex-valued chirp + + nperseg, noverlap = 50, 40 + win = ('gaussian', 1e-2 * fs) # Gaussian with 0.01 s standard deviation + + # Legacy STFT: + f0_u, t0, Sz0_u = stft(z, fs, win, nperseg, noverlap, + return_onesided=False, scaling='spectrum') + Sz0 = fftshift(Sz0_u, axes=0) + + # New STFT: + SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap, + fft_mode='centered', + scale_to='magnitude', phase_shift=None) + Sz1 = SFT.stft(z) + + xp_assert_close(Sz0, Sz1[:, 2:-1]) + + xp_assert_close((abs(Sz1[:, 1]).min(), abs(Sz1[:, 1]).max()), + (6.925060911593139e-07, 8.00271269218721e-07)) + + t0_r, z0_r = istft(Sz0_u, fs, win, nperseg, noverlap, input_onesided=False, + scaling='spectrum') + z1_r = SFT.istft(Sz1, k1=N) + assert len(z0_r) == N + 9 + xp_assert_close(z0_r[:N], z) + xp_assert_close(z1_r, z) + + # Spectrogram is just the absolute square of th STFT: + xp_assert_close(SFT.spectrogram(z), abs(Sz1) ** 2) + + +def test_tutorial_stft_legacy_spectrogram(): + """Verify spectrogram example in "Comparison with Legacy Implementation" + from the "User Guide". + + In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the + :ref:`user_guide` the legacy and the new implementation are compared. + """ + fs, N = 200, 1001 # 200 Hz sampling rate for almost 5 s signal + t_z = np.arange(N) / fs # time indexes for signal + z = np.exp(2j*np.pi*70 * (t_z - 0.2*t_z**2)) # complex-valued sweep + + nperseg, noverlap = 50, 40 + win = ('gaussian', 1e-2 * fs) # Gaussian with 0.01 s standard dev. + + # Legacy spectrogram: + f2_u, t2, Sz2_u = spectrogram(z, fs, win, nperseg, noverlap, detrend=None, + return_onesided=False, scaling='spectrum', + mode='complex') + + f2, Sz2 = fftshift(f2_u), fftshift(Sz2_u, axes=0) + + # New STFT: + SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap, + fft_mode='centered', scale_to='magnitude', + phase_shift=None) + Sz3 = SFT.stft(z, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2) + t3 = SFT.t(N, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2) + + xp_assert_close(t2, t3) + xp_assert_close(f2, SFT.f) + xp_assert_close(Sz2, Sz3) + + +def test_permute_axes(): + """Verify correctness of four-dimensional signal by permuting its + shape. """ + n = 25 + SFT = ShortTimeFFT(np.ones(8)/8, hop=3, fs=n) + x0 = np.arange(n, dtype=np.float64) + Sx0 = SFT.stft(x0) + Sx0 = Sx0.reshape((Sx0.shape[0], 1, 1, 1, Sx0.shape[-1])) + SxT = np.moveaxis(Sx0, (0, -1), (-1, 0)) + + atol = 2 * np.finfo(SFT.win.dtype).resolution + for i in range(4): + y = np.reshape(x0, np.roll((n, 1, 1, 1), i)) + Sy = SFT.stft(y, axis=i) + xp_assert_close(Sy, np.moveaxis(Sx0, 0, i)) + + yb0 = SFT.istft(Sy, k1=n, f_axis=i) + xp_assert_close(yb0, y, atol=atol) + # explicit t-axis parameter (for coverage): + yb1 = SFT.istft(Sy, k1=n, f_axis=i, t_axis=Sy.ndim-1) + xp_assert_close(yb1, y, atol=atol) + + SyT = np.moveaxis(Sy, (i, -1), (-1, i)) + xp_assert_close(SyT, np.moveaxis(SxT, 0, i)) + + ybT = SFT.istft(SyT, k1=n, t_axis=i, f_axis=-1) + xp_assert_close(ybT, y, atol=atol) + + +@pytest.mark.parametrize("fft_mode", + ('twosided', 'centered', 'onesided', 'onesided2X')) +def test_roundtrip_multidimensional(fft_mode: FFT_MODE_TYPE): + """Test roundtrip of a multidimensional input signal versus its components. + + This test can uncover potential problems with `fftshift()`. + """ + n = 9 + x = np.arange(4*n*2, dtype=np.float64).reshape(4, n, 2) + SFT = ShortTimeFFT(get_window('hann', 4), hop=2, fs=1, + scale_to='magnitude', fft_mode=fft_mode) + Sx = SFT.stft(x, axis=1) + y = SFT.istft(Sx, k1=n, f_axis=1, t_axis=-1) + xp_assert_close(y, x.astype(y.dtype), err_msg='Multidim. roundtrip failed!') + + for i, j in product(range(x.shape[0]), range(x.shape[2])): + y_ = SFT.istft(Sx[i, :, j, :], k1=n) + xp_assert_close(y_, x[i, :, j].astype(y_.dtype), + err_msg="Multidim. roundtrip for component " + + f"x[{i}, :, {j}] and {fft_mode=} failed!") + +@pytest.mark.parametrize("phase_shift", (0, 4, None)) +def test_roundtrip_two_dimensional(phase_shift: int|None): + """Test roundtrip of a 2 channel input signal with `mfft` set with different + values for `phase_shift` + + Tests for Issue https://github.com/scipy/scipy/issues/21671 + """ + n = 21 + SFT = ShortTimeFFT.from_window('hann', fs=1, nperseg=13, noverlap=7, + mfft=16, phase_shift=phase_shift) + x = np.arange(2*n, dtype=float).reshape(2, n) + Sx = SFT.stft(x) + y = SFT.istft(Sx, k1=n) + xp_assert_close(y, x, atol=2 * np.finfo(SFT.win.dtype).resolution, + err_msg='2-dim. roundtrip failed!') + + +@pytest.mark.parametrize('window, n, nperseg, noverlap', + [('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ('bartlett', 101, 51, 26), # Test odd nperseg + ('hann', 1024, 256, 128), # Test defaults + (('tukey', 0.5), 1152, 256, 64), # Test Tukey + ('hann', 1024, 256, 255), # Test overlapped hann + ('boxcar', 100, 10, 3), # NOLA True, COLA False + ('bartlett', 101, 51, 37), # NOLA True, COLA False + ('hann', 1024, 256, 127), # NOLA True, COLA False + # NOLA True, COLA False: + (('tukey', 0.5), 1152, 256, 14), + ('hann', 1024, 256, 5)]) # NOLA True, COLA False +def test_roundtrip_windows(window, n: int, nperseg: int, noverlap: int): + """Roundtrip test adapted from `test_spectral.TestSTFT`. + + The parameters are taken from the methods test_roundtrip_real(), + test_roundtrip_nola_not_cola(), test_roundtrip_float32(), + test_roundtrip_complex(). + """ + np.random.seed(2394655) + + w = get_window(window, nperseg) + SFT = ShortTimeFFT(w, nperseg - noverlap, fs=1, fft_mode='twosided', + phase_shift=None) + + z = 10 * np.random.randn(n) + 10j * np.random.randn(n) + Sz = SFT.stft(z) + z1 = SFT.istft(Sz, k1=len(z)) + xp_assert_close(z, z1, err_msg="Roundtrip for complex values failed") + + x = 10 * np.random.randn(n) + Sx = SFT.stft(x) + x1 = SFT.istft(Sx, k1=len(z)) + xp_assert_close(x.astype(np.complex128), x1, + err_msg="Roundtrip for float values failed") + + x32 = x.astype(np.float32) + Sx32 = SFT.stft(x32) + x32_1 = SFT.istft(Sx32, k1=len(x32)) + x32_1_r = x32_1.real + xp_assert_close(x32, x32_1_r.astype(np.float32), + err_msg="Roundtrip for 32 Bit float values failed") + xp_assert_close(x32.imag, np.zeros_like(x32.imag), + err_msg="Roundtrip for 32 Bit float values failed") + + +@pytest.mark.parametrize('signal_type', ('real', 'complex')) +def test_roundtrip_complex_window(signal_type): + """Test roundtrip for complex-valued window function + + The purpose of this test is to check if the dual window is calculated + correctly for complex-valued windows. + """ + np.random.seed(1354654) + win = np.exp(2j*np.linspace(0, np.pi, 8)) + SFT = ShortTimeFFT(win, 3, fs=1, fft_mode='twosided') + + z = 10 * np.random.randn(11) + if signal_type == 'complex': + z = z + 2j * z + Sz = SFT.stft(z) + z1 = SFT.istft(Sz, k1=len(z)) + xp_assert_close(z.astype(np.complex128), z1, + err_msg="Roundtrip for complex-valued window failed") + + +def test_average_all_segments(): + """Compare `welch` function with stft mean. + + Ported from `TestSpectrogram.test_average_all_segments` from file + ``test__spectral.py``. + """ + x = np.random.randn(1024) + + fs = 1.0 + window = ('tukey', 0.25) + nperseg, noverlap = 16, 2 + fw, Pw = welch(x, fs, window, nperseg, noverlap) + SFT = ShortTimeFFT.from_window(window, fs, nperseg, noverlap, + fft_mode='onesided2X', scale_to='psd', + phase_shift=None) + # `welch` positions the window differently than the STFT: + P = SFT.spectrogram(x, detr='constant', p0=0, + p1=(len(x)-noverlap)//SFT.hop, k_offset=nperseg//2) + + xp_assert_close(SFT.f, fw) + xp_assert_close(np.mean(P, axis=-1), Pw) + + +@pytest.mark.parametrize('window, N, nperseg, noverlap, mfft', + # from test_roundtrip_padded_FFT: + [('hann', 1024, 256, 128, 512), + ('hann', 1024, 256, 128, 501), + ('boxcar', 100, 10, 0, 33), + (('tukey', 0.5), 1152, 256, 64, 1024), + # from test_roundtrip_padded_signal: + ('boxcar', 101, 10, 0, None), + ('hann', 1000, 256, 128, None), + # from test_roundtrip_boundary_extension: + ('boxcar', 100, 10, 0, None), + ('boxcar', 100, 10, 9, None)]) +@pytest.mark.parametrize('padding', get_args(PAD_TYPE)) +def test_stft_padding_roundtrip(window, N: int, nperseg: int, noverlap: int, + mfft: int, padding): + """Test the parameter 'padding' of `stft` with roundtrips. + + The STFT parametrizations were taken from the methods + `test_roundtrip_padded_FFT`, `test_roundtrip_padded_signal` and + `test_roundtrip_boundary_extension` from class `TestSTFT` in file + ``test_spectral.py``. Note that the ShortTimeFFT does not need the + concept of "boundary extension". + """ + x = normal_distribution.rvs(size=N, random_state=2909) # real signal + z = x * np.exp(1j * np.pi / 4) # complex signal + + SFT = ShortTimeFFT.from_window(window, 1, nperseg, noverlap, + fft_mode='twosided', mfft=mfft) + Sx = SFT.stft(x, padding=padding) + x1 = SFT.istft(Sx, k1=N) + xp_assert_close(x1, x.astype(np.complex128), + err_msg=f"Failed real roundtrip with '{padding}' padding") + + Sz = SFT.stft(z, padding=padding) + z1 = SFT.istft(Sz, k1=N) + xp_assert_close(z1, z, err_msg="Failed complex roundtrip with " + + f" '{padding}' padding") + + +@pytest.mark.parametrize('N_x', (128, 129, 255, 256, 1337)) # signal length +@pytest.mark.parametrize('w_size', (128, 256)) # window length +@pytest.mark.parametrize('t_step', (4, 64)) # SFT time hop +@pytest.mark.parametrize('f_c', (7., 23.)) # frequency of input sine +def test_energy_conservation(N_x: int, w_size: int, t_step: int, f_c: float): + """Test if a `psd`-scaled STFT conserves the L2 norm. + + This test is adapted from MNE-Python [1]_. Besides being battle-tested, + this test has the benefit of using non-standard window including + non-positive values and a 2d input signal. + + Since `ShortTimeFFT` requires the signal length `N_x` to be at least the + window length `w_size`, the parameter `N_x` was changed from + ``(127, 128, 255, 256, 1337)`` to ``(128, 129, 255, 256, 1337)`` to be + more useful. + + .. [1] File ``test_stft.py`` of MNE-Python + https://github.com/mne-tools/mne-python/blob/main/mne/time_frequency/tests/test_stft.py + """ + window = np.sin(np.arange(.5, w_size + .5) / w_size * np.pi) + SFT = ShortTimeFFT(window, t_step, fs=1000, fft_mode='onesided2X', + scale_to='psd') + atol = 2*np.finfo(window.dtype).resolution + N_x = max(N_x, w_size) # minimal sing + # Test with low frequency signal + t = np.arange(N_x).astype(np.float64) + x = np.sin(2 * np.pi * f_c * t * SFT.T) + x = np.array([x, x + 1.]) + X = SFT.stft(x) + xp = SFT.istft(X, k1=N_x) + + max_freq = SFT.f[np.argmax(np.sum(np.abs(X[0]) ** 2, axis=1))] + + assert X.shape[1] == SFT.f_pts + assert np.all(SFT.f >= 0.) + assert np.abs(max_freq - f_c) < 1. + xp_assert_close(x, xp, atol=atol) + + # check L2-norm squared (i.e., energy) conservation: + E_x = np.sum(x**2, axis=-1) * SFT.T # numerical integration + aX2 = X.real**2 + X.imag.real**2 + E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f + xp_assert_close(E_X, E_x, atol=atol) + + # Test with random signal + np.random.seed(2392795) + x = np.random.randn(2, N_x) + X = SFT.stft(x) + xp = SFT.istft(X, k1=N_x) + + assert X.shape[1] == SFT.f_pts + assert np.all(SFT.f >= 0.) + assert np.abs(max_freq - f_c) < 1. + xp_assert_close(x, xp, atol=atol) + + # check L2-norm squared (i.e., energy) conservation: + E_x = np.sum(x**2, axis=-1) * SFT.T # numeric integration + aX2 = X.real ** 2 + X.imag.real ** 2 + E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f + xp_assert_close(E_X, E_x, atol=atol) + + # Try with empty array + x = np.zeros((0, N_x)) + X = SFT.stft(x) + xp = SFT.istft(X, k1=N_x) + assert xp.shape == x.shape diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_signaltools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_signaltools.py new file mode 100644 index 0000000000000000000000000000000000000000..7953fcb5ff7634f1c01d96920c1dd069cacf0c0c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_signaltools.py @@ -0,0 +1,3933 @@ +import sys + +from concurrent.futures import ThreadPoolExecutor, as_completed +from decimal import Decimal +from itertools import product +from math import gcd + +import pytest +from pytest import raises as assert_raises +from numpy.testing import ( + assert_equal, + assert_almost_equal, assert_array_equal, assert_array_almost_equal, + assert_allclose, assert_, assert_array_less, + suppress_warnings) +from numpy import array, arange +import numpy as np + +from scipy import fft as sp_fft +from scipy.ndimage import correlate1d +from scipy.optimize import fmin, linear_sum_assignment +from scipy import signal +from scipy.signal import ( + correlate, correlate2d, correlation_lags, convolve, convolve2d, + fftconvolve, oaconvolve, choose_conv_method, envelope, + hilbert, hilbert2, lfilter, lfilter_zi, filtfilt, butter, zpk2tf, zpk2sos, + invres, invresz, vectorstrength, lfiltic, tf2sos, sosfilt, sosfiltfilt, + sosfilt_zi, tf2zpk, BadCoefficients, detrend, unique_roots, residue, + residuez) +from scipy.signal.windows import hann +from scipy.signal._signaltools import (_filtfilt_gust, _compute_factors, + _group_poles) +from scipy.signal._upfirdn import _upfirdn_modes +from scipy._lib import _testutils +from scipy._lib._array_api import xp_assert_close +from scipy._lib._util import ComplexWarning, np_long, np_ulong + + +class _TestConvolve: + + def test_basic(self): + a = [3, 4, 5, 6, 5, 4] + b = [1, 2, 3] + c = convolve(a, b) + assert_array_equal(c, array([3, 10, 22, 28, 32, 32, 23, 12])) + + def test_same(self): + a = [3, 4, 5] + b = [1, 2, 3, 4] + c = convolve(a, b, mode="same") + assert_array_equal(c, array([10, 22, 34])) + + def test_same_eq(self): + a = [3, 4, 5] + b = [1, 2, 3] + c = convolve(a, b, mode="same") + assert_array_equal(c, array([10, 22, 22])) + + def test_complex(self): + x = array([1 + 1j, 2 + 1j, 3 + 1j]) + y = array([1 + 1j, 2 + 1j]) + z = convolve(x, y) + assert_array_equal(z, array([2j, 2 + 6j, 5 + 8j, 5 + 5j])) + + def test_zero_rank(self): + a = 1289 + b = 4567 + c = convolve(a, b) + assert_equal(c, a * b) + + def test_broadcastable(self): + a = np.arange(27).reshape(3, 3, 3) + b = np.arange(3) + for i in range(3): + b_shape = [1]*3 + b_shape[i] = 3 + x = convolve(a, b.reshape(b_shape), method='direct') + y = convolve(a, b.reshape(b_shape), method='fft') + assert_allclose(x, y) + + def test_single_element(self): + a = array([4967]) + b = array([3920]) + c = convolve(a, b) + assert_equal(c, a * b) + + def test_2d_arrays(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + c = convolve(a, b) + d = array([[2, 7, 16, 17, 12], + [10, 30, 62, 58, 38], + [12, 31, 58, 49, 30]]) + assert_array_equal(c, d) + + def test_input_swapping(self): + small = arange(8).reshape(2, 2, 2) + big = 1j * arange(27).reshape(3, 3, 3) + big += arange(27)[::-1].reshape(3, 3, 3) + + out_array = array( + [[[0 + 0j, 26 + 0j, 25 + 1j, 24 + 2j], + [52 + 0j, 151 + 5j, 145 + 11j, 93 + 11j], + [46 + 6j, 133 + 23j, 127 + 29j, 81 + 23j], + [40 + 12j, 98 + 32j, 93 + 37j, 54 + 24j]], + + [[104 + 0j, 247 + 13j, 237 + 23j, 135 + 21j], + [282 + 30j, 632 + 96j, 604 + 124j, 330 + 86j], + [246 + 66j, 548 + 180j, 520 + 208j, 282 + 134j], + [142 + 66j, 307 + 161j, 289 + 179j, 153 + 107j]], + + [[68 + 36j, 157 + 103j, 147 + 113j, 81 + 75j], + [174 + 138j, 380 + 348j, 352 + 376j, 186 + 230j], + [138 + 174j, 296 + 432j, 268 + 460j, 138 + 278j], + [70 + 138j, 145 + 323j, 127 + 341j, 63 + 197j]], + + [[32 + 72j, 68 + 166j, 59 + 175j, 30 + 100j], + [68 + 192j, 139 + 433j, 117 + 455j, 57 + 255j], + [38 + 222j, 73 + 499j, 51 + 521j, 21 + 291j], + [12 + 144j, 20 + 318j, 7 + 331j, 0 + 182j]]]) + + assert_array_equal(convolve(small, big, 'full'), out_array) + assert_array_equal(convolve(big, small, 'full'), out_array) + assert_array_equal(convolve(small, big, 'same'), + out_array[1:3, 1:3, 1:3]) + assert_array_equal(convolve(big, small, 'same'), + out_array[0:3, 0:3, 0:3]) + assert_array_equal(convolve(small, big, 'valid'), + out_array[1:3, 1:3, 1:3]) + assert_array_equal(convolve(big, small, 'valid'), + out_array[1:3, 1:3, 1:3]) + + def test_invalid_params(self): + a = [3, 4, 5] + b = [1, 2, 3] + assert_raises(ValueError, convolve, a, b, mode='spam') + assert_raises(ValueError, convolve, a, b, mode='eggs', method='fft') + assert_raises(ValueError, convolve, a, b, mode='ham', method='direct') + assert_raises(ValueError, convolve, a, b, mode='full', method='bacon') + assert_raises(ValueError, convolve, a, b, mode='same', method='bacon') + + +class TestConvolve(_TestConvolve): + + def test_valid_mode2(self): + # See gh-5897 + a = [1, 2, 3, 6, 5, 3] + b = [2, 3, 4, 5, 3, 4, 2, 2, 1] + expected = [70, 78, 73, 65] + + out = convolve(a, b, 'valid') + assert_array_equal(out, expected) + + out = convolve(b, a, 'valid') + assert_array_equal(out, expected) + + a = [1 + 5j, 2 - 1j, 3 + 0j] + b = [2 - 3j, 1 + 0j] + expected = [2 - 3j, 8 - 10j] + + out = convolve(a, b, 'valid') + assert_array_equal(out, expected) + + out = convolve(b, a, 'valid') + assert_array_equal(out, expected) + + def test_same_mode(self): + a = [1, 2, 3, 3, 1, 2] + b = [1, 4, 3, 4, 5, 6, 7, 4, 3, 2, 1, 1, 3] + c = convolve(a, b, 'same') + d = array([57, 61, 63, 57, 45, 36]) + assert_array_equal(c, d) + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, convolve, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, convolve, *(b, a), **{'mode': 'valid'}) + + def test_convolve_method(self, n=100): + # this types data structure was manually encoded instead of + # using custom filters on the soon-to-be-removed np.sctypes + types = {'uint16', 'uint64', 'int64', 'int32', + 'complex128', 'float64', 'float16', + 'complex64', 'float32', 'int16', + 'uint8', 'uint32', 'int8', 'bool'} + args = [(t1, t2, mode) for t1 in types for t2 in types + for mode in ['valid', 'full', 'same']] + + # These are random arrays, which means test is much stronger than + # convolving testing by convolving two np.ones arrays + rng = np.random.RandomState(42) + array_types = {'i': rng.choice([0, 1], size=n), + 'f': rng.randn(n)} + array_types['b'] = array_types['u'] = array_types['i'] + array_types['c'] = array_types['f'] + 0.5j*array_types['f'] + + for t1, t2, mode in args: + x1 = array_types[np.dtype(t1).kind].astype(t1) + x2 = array_types[np.dtype(t2).kind].astype(t2) + + results = {key: convolve(x1, x2, method=key, mode=mode) + for key in ['fft', 'direct']} + + assert_equal(results['fft'].dtype, results['direct'].dtype) + + if 'bool' in t1 and 'bool' in t2: + assert_equal(choose_conv_method(x1, x2), 'direct') + continue + + # Found by experiment. Found approx smallest value for (rtol, atol) + # threshold to have tests pass. + if any([t in {'complex64', 'float32'} for t in [t1, t2]]): + kwargs = {'rtol': 1.0e-4, 'atol': 1e-6} + elif 'float16' in [t1, t2]: + # atol is default for np.allclose + kwargs = {'rtol': 1e-3, 'atol': 1e-3} + else: + # defaults for np.allclose (different from assert_allclose) + kwargs = {'rtol': 1e-5, 'atol': 1e-8} + + assert_allclose(results['fft'], results['direct'], **kwargs) + + def test_convolve_method_large_input(self): + # This is really a test that convolving two large integers goes to the + # direct method even if they're in the fft method. + for n in [10, 20, 50, 51, 52, 53, 54, 60, 62]: + z = np.array([2**n], dtype=np.int64) + fft = convolve(z, z, method='fft') + direct = convolve(z, z, method='direct') + + # this is the case when integer precision gets to us + # issue #6076 has more detail, hopefully more tests after resolved + if n < 50: + assert_equal(fft, direct) + assert_equal(fft, 2**(2*n)) + assert_equal(direct, 2**(2*n)) + + def test_mismatched_dims(self): + # Input arrays should have the same number of dimensions + assert_raises(ValueError, convolve, [1], 2, method='direct') + assert_raises(ValueError, convolve, 1, [2], method='direct') + assert_raises(ValueError, convolve, [1], 2, method='fft') + assert_raises(ValueError, convolve, 1, [2], method='fft') + assert_raises(ValueError, convolve, [1], [[2]]) + assert_raises(ValueError, convolve, [3], 2) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + convolve(a, b) + + +class _TestConvolve2d: + + def test_2d_arrays(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + d = array([[2, 7, 16, 17, 12], + [10, 30, 62, 58, 38], + [12, 31, 58, 49, 30]]) + e = convolve2d(a, b) + assert_array_equal(e, d) + + def test_valid_mode(self): + e = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + f = [[1, 2, 3], [3, 4, 5]] + h = array([[62, 80, 98, 116, 134]]) + + g = convolve2d(e, f, 'valid') + assert_array_equal(g, h) + + # See gh-5897 + g = convolve2d(f, e, 'valid') + assert_array_equal(g, h) + + def test_valid_mode_complx(self): + e = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + f = np.array([[1, 2, 3], [3, 4, 5]], dtype=complex) + 1j + h = array([[62.+24.j, 80.+30.j, 98.+36.j, 116.+42.j, 134.+48.j]]) + + g = convolve2d(e, f, 'valid') + assert_array_almost_equal(g, h) + + # See gh-5897 + g = convolve2d(f, e, 'valid') + assert_array_equal(g, h) + + def test_fillvalue(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + fillval = 1 + c = convolve2d(a, b, 'full', 'fill', fillval) + d = array([[24, 26, 31, 34, 32], + [28, 40, 62, 64, 52], + [32, 46, 67, 62, 48]]) + assert_array_equal(c, d) + + def test_fillvalue_errors(self): + msg = "could not cast `fillvalue` directly to the output " + with np.testing.suppress_warnings() as sup: + sup.filter(ComplexWarning, "Casting complex values") + with assert_raises(ValueError, match=msg): + convolve2d([[1]], [[1, 2]], fillvalue=1j) + + msg = "`fillvalue` must be scalar or an array with " + with assert_raises(ValueError, match=msg): + convolve2d([[1]], [[1, 2]], fillvalue=[1, 2]) + + def test_fillvalue_empty(self): + # Check that fillvalue being empty raises an error: + assert_raises(ValueError, convolve2d, [[1]], [[1, 2]], + fillvalue=[]) + + def test_wrap_boundary(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + c = convolve2d(a, b, 'full', 'wrap') + d = array([[80, 80, 74, 80, 80], + [68, 68, 62, 68, 68], + [80, 80, 74, 80, 80]]) + assert_array_equal(c, d) + + def test_sym_boundary(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + c = convolve2d(a, b, 'full', 'symm') + d = array([[34, 30, 44, 62, 66], + [52, 48, 62, 80, 84], + [82, 78, 92, 110, 114]]) + assert_array_equal(c, d) + + @pytest.mark.parametrize('func', [convolve2d, correlate2d]) + @pytest.mark.parametrize('boundary, expected', + [('symm', [[37.0, 42.0, 44.0, 45.0]]), + ('wrap', [[43.0, 44.0, 42.0, 39.0]])]) + def test_same_with_boundary(self, func, boundary, expected): + # Test boundary='symm' and boundary='wrap' with a "long" kernel. + # The size of the kernel requires that the values in the "image" + # be extended more than once to handle the requested boundary method. + # This is a regression test for gh-8684 and gh-8814. + image = np.array([[2.0, -1.0, 3.0, 4.0]]) + kernel = np.ones((1, 21)) + result = func(image, kernel, mode='same', boundary=boundary) + # The expected results were calculated "by hand". Because the + # kernel is all ones, the same result is expected for convolve2d + # and correlate2d. + assert_array_equal(result, expected) + + def test_boundary_extension_same(self): + # Regression test for gh-12686. + # Use ndimage.convolve with appropriate arguments to create the + # expected result. + import scipy.ndimage as ndi + a = np.arange(1, 10*3+1, dtype=float).reshape(10, 3) + b = np.arange(1, 10*10+1, dtype=float).reshape(10, 10) + c = convolve2d(a, b, mode='same', boundary='wrap') + assert_array_equal(c, ndi.convolve(a, b, mode='wrap', origin=(-1, -1))) + + def test_boundary_extension_full(self): + # Regression test for gh-12686. + # Use ndimage.convolve with appropriate arguments to create the + # expected result. + import scipy.ndimage as ndi + a = np.arange(1, 3*3+1, dtype=float).reshape(3, 3) + b = np.arange(1, 6*6+1, dtype=float).reshape(6, 6) + c = convolve2d(a, b, mode='full', boundary='wrap') + apad = np.pad(a, ((3, 3), (3, 3)), 'wrap') + assert_array_equal(c, ndi.convolve(apad, b, mode='wrap')[:-1, :-1]) + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, convolve2d, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, convolve2d, *(b, a), **{'mode': 'valid'}) + + +class TestConvolve2d(_TestConvolve2d): + + def test_same_mode(self): + e = [[1, 2, 3], [3, 4, 5]] + f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + g = convolve2d(e, f, 'same') + h = array([[22, 28, 34], + [80, 98, 116]]) + assert_array_equal(g, h) + + def test_valid_mode2(self): + # See gh-5897 + e = [[1, 2, 3], [3, 4, 5]] + f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + expected = [[62, 80, 98, 116, 134]] + + out = convolve2d(e, f, 'valid') + assert_array_equal(out, expected) + + out = convolve2d(f, e, 'valid') + assert_array_equal(out, expected) + + e = [[1 + 1j, 2 - 3j], [3 + 1j, 4 + 0j]] + f = [[2 - 1j, 3 + 2j, 4 + 0j], [4 - 0j, 5 + 1j, 6 - 3j]] + expected = [[27 - 1j, 46. + 2j]] + + out = convolve2d(e, f, 'valid') + assert_array_equal(out, expected) + + # See gh-5897 + out = convolve2d(f, e, 'valid') + assert_array_equal(out, expected) + + def test_consistency_convolve_funcs(self): + # Compare np.convolve, signal.convolve, signal.convolve2d + a = np.arange(5) + b = np.array([3.2, 1.4, 3]) + for mode in ['full', 'valid', 'same']: + assert_almost_equal(np.convolve(a, b, mode=mode), + signal.convolve(a, b, mode=mode)) + assert_almost_equal(np.squeeze( + signal.convolve2d([a], [b], mode=mode)), + signal.convolve(a, b, mode=mode)) + + def test_invalid_dims(self): + assert_raises(ValueError, convolve2d, 3, 4) + assert_raises(ValueError, convolve2d, [3], [4]) + assert_raises(ValueError, convolve2d, [[[3]]], [[[4]]]) + + @pytest.mark.slow + @pytest.mark.xfail_on_32bit("Can't create large array for test") + def test_large_array(self): + # Test indexing doesn't overflow an int (gh-10761) + n = 2**31 // (1000 * np.int64().itemsize) + _testutils.check_free_memory(2 * n * 1001 * np.int64().itemsize / 1e6) + + # Create a chequered pattern of 1s and 0s + a = np.zeros(1001 * n, dtype=np.int64) + a[::2] = 1 + a = np.lib.stride_tricks.as_strided(a, shape=(n, 1000), strides=(8008, 8)) + + count = signal.convolve2d(a, [[1, 1]]) + fails = np.where(count > 1) + assert fails[0].size == 0 + + +class TestFFTConvolve: + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_real(self, axes): + a = array([1, 2, 3]) + expected = array([1, 4, 10, 12, 9.]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_real_axes(self, axes): + a = array([1, 2, 3]) + expected = array([1, 4, 10, 12, 9.]) + + a = np.tile(a, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_complex(self, axes): + a = array([1 + 1j, 2 + 2j, 3 + 3j]) + expected = array([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_complex_axes(self, axes): + a = array([1 + 1j, 2 + 2j, 3 + 3j]) + expected = array([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j]) + + a = np.tile(a, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', + None, + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + [-2, 1], + [1, -2], + [-2, -1], + [-1, -2]]) + def test_2d_real_same(self, axes): + a = array([[1, 2, 3], + [4, 5, 6]]) + expected = array([[1, 4, 10, 12, 9], + [8, 26, 56, 54, 36], + [16, 40, 73, 60, 36]]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [[1, 2], + [2, 1], + [1, -1], + [-1, 1], + [-2, 2], + [2, -2], + [-2, -1], + [-1, -2]]) + def test_2d_real_same_axes(self, axes): + a = array([[1, 2, 3], + [4, 5, 6]]) + expected = array([[1, 4, 10, 12, 9], + [8, 26, 56, 54, 36], + [16, 40, 73, 60, 36]]) + + a = np.tile(a, [2, 1, 1]) + expected = np.tile(expected, [2, 1, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', + None, + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + [-2, 1], + [1, -2], + [-2, -1], + [-1, -2]]) + def test_2d_complex_same(self, axes): + a = array([[1 + 2j, 3 + 4j, 5 + 6j], + [2 + 1j, 4 + 3j, 6 + 5j]]) + expected = array([ + [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j], + [10j, 44j, 118j, 156j, 122j], + [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j] + ]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [[1, 2], + [2, 1], + [1, -1], + [-1, 1], + [-2, 2], + [2, -2], + [-2, -1], + [-1, -2]]) + def test_2d_complex_same_axes(self, axes): + a = array([[1 + 2j, 3 + 4j, 5 + 6j], + [2 + 1j, 4 + 3j, 6 + 5j]]) + expected = array([ + [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j], + [10j, 44j, 118j, 156j, 122j], + [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j] + ]) + + a = np.tile(a, [2, 1, 1]) + expected = np.tile(expected, [2, 1, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_real_same_mode(self, axes): + a = array([1, 2, 3]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected_1 = array([35., 41., 47.]) + expected_2 = array([9., 20., 25., 35., 41., 47., 39., 28., 2.]) + + if axes == '': + out = fftconvolve(a, b, 'same') + else: + out = fftconvolve(a, b, 'same', axes=axes) + assert_array_almost_equal(out, expected_1) + + if axes == '': + out = fftconvolve(b, a, 'same') + else: + out = fftconvolve(b, a, 'same', axes=axes) + assert_array_almost_equal(out, expected_2) + + @pytest.mark.parametrize('axes', [1, -1, [1], [-1]]) + def test_real_same_mode_axes(self, axes): + a = array([1, 2, 3]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected_1 = array([35., 41., 47.]) + expected_2 = array([9., 20., 25., 35., 41., 47., 39., 28., 2.]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected_1 = np.tile(expected_1, [2, 1]) + expected_2 = np.tile(expected_2, [2, 1]) + + out = fftconvolve(a, b, 'same', axes=axes) + assert_array_almost_equal(out, expected_1) + + out = fftconvolve(b, a, 'same', axes=axes) + assert_array_almost_equal(out, expected_2) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_valid_mode_real(self, axes): + # See gh-5897 + a = array([3, 2, 1]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected = array([24., 31., 41., 43., 49., 25., 12.]) + + if axes == '': + out = fftconvolve(a, b, 'valid') + else: + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + if axes == '': + out = fftconvolve(b, a, 'valid') + else: + out = fftconvolve(b, a, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1]]) + def test_valid_mode_real_axes(self, axes): + # See gh-5897 + a = array([3, 2, 1]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected = array([24., 31., 41., 43., 49., 25., 12.]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_valid_mode_complex(self, axes): + a = array([3 - 1j, 2 + 7j, 1 + 0j]) + b = array([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j]) + expected = array([45. + 12.j, 30. + 23.j, 48 + 32.j]) + + if axes == '': + out = fftconvolve(a, b, 'valid') + else: + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + if axes == '': + out = fftconvolve(b, a, 'valid') + else: + out = fftconvolve(b, a, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_valid_mode_complex_axes(self, axes): + a = array([3 - 1j, 2 + 7j, 1 + 0j]) + b = array([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j]) + expected = array([45. + 12.j, 30. + 23.j, 48 + 32.j]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + out = fftconvolve(b, a, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + def test_valid_mode_ignore_nonaxes(self): + # See gh-5897 + a = array([3, 2, 1]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected = array([24., 31., 41., 43., 49., 25., 12.]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [1, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'valid', axes=1) + assert_array_almost_equal(out, expected) + + def test_empty(self): + # Regression test for #1745: crashes with 0-length input. + assert_(fftconvolve([], []).size == 0) + assert_(fftconvolve([5, 6], []).size == 0) + assert_(fftconvolve([], [7]).size == 0) + + def test_zero_rank(self): + a = array(4967) + b = array(3920) + out = fftconvolve(a, b) + assert_equal(out, a * b) + + def test_single_element(self): + a = array([4967]) + b = array([3920]) + out = fftconvolve(a, b) + assert_equal(out, a * b) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_random_data(self, axes): + np.random.seed(1234) + a = np.random.rand(1233) + 1j * np.random.rand(1233) + b = np.random.rand(1321) + 1j * np.random.rand(1321) + expected = np.convolve(a, b, 'full') + + if axes == '': + out = fftconvolve(a, b, 'full') + else: + out = fftconvolve(a, b, 'full', axes=axes) + assert_(np.allclose(out, expected, rtol=1e-10)) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_random_data_axes(self, axes): + np.random.seed(1234) + a = np.random.rand(1233) + 1j * np.random.rand(1233) + b = np.random.rand(1321) + 1j * np.random.rand(1321) + expected = np.convolve(a, b, 'full') + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'full', axes=axes) + assert_(np.allclose(out, expected, rtol=1e-10)) + + @pytest.mark.parametrize('axes', [[1, 4], + [4, 1], + [1, -1], + [-1, 1], + [-4, 4], + [4, -4], + [-4, -1], + [-1, -4]]) + def test_random_data_multidim_axes(self, axes): + a_shape, b_shape = (123, 22), (132, 11) + np.random.seed(1234) + a = np.random.rand(*a_shape) + 1j * np.random.rand(*a_shape) + b = np.random.rand(*b_shape) + 1j * np.random.rand(*b_shape) + expected = convolve2d(a, b, 'full') + + a = a[:, :, None, None, None] + b = b[:, :, None, None, None] + expected = expected[:, :, None, None, None] + + a = np.moveaxis(a.swapaxes(0, 2), 1, 4) + b = np.moveaxis(b.swapaxes(0, 2), 1, 4) + expected = np.moveaxis(expected.swapaxes(0, 2), 1, 4) + + # use 1 for dimension 2 in a and 3 in b to test broadcasting + a = np.tile(a, [2, 1, 3, 1, 1]) + b = np.tile(b, [2, 1, 1, 4, 1]) + expected = np.tile(expected, [2, 1, 3, 4, 1]) + + out = fftconvolve(a, b, 'full', axes=axes) + assert_allclose(out, expected, rtol=1e-10, atol=1e-10) + + @pytest.mark.slow + @pytest.mark.parametrize( + 'n', + list(range(1, 100)) + + list(range(1000, 1500)) + + np.random.RandomState(1234).randint(1001, 10000, 5).tolist()) + def test_many_sizes(self, n): + a = np.random.rand(n) + 1j * np.random.rand(n) + b = np.random.rand(n) + 1j * np.random.rand(n) + expected = np.convolve(a, b, 'full') + + out = fftconvolve(a, b, 'full') + assert_allclose(out, expected, atol=1e-10) + + out = fftconvolve(a, b, 'full', axes=[0]) + assert_allclose(out, expected, atol=1e-10) + + @pytest.mark.thread_unsafe + def test_fft_nan(self): + n = 1000 + rng = np.random.default_rng(43876432987) + sig_nan = rng.standard_normal(n) + + for val in [np.nan, np.inf]: + sig_nan[100] = val + coeffs = signal.firwin(200, 0.2) + + msg = "Use of fft convolution.*|invalid value encountered.*" + with pytest.warns(RuntimeWarning, match=msg): + signal.convolve(sig_nan, coeffs, mode='same', method='fft') + +def fftconvolve_err(*args, **kwargs): + raise RuntimeError('Fell back to fftconvolve') + + +def gen_oa_shapes(sizes): + return [(a, b) for a, b in product(sizes, repeat=2) + if abs(a - b) > 3] + + +def gen_oa_shapes_2d(sizes): + shapes0 = gen_oa_shapes(sizes) + shapes1 = gen_oa_shapes(sizes) + shapes = [ishapes0+ishapes1 for ishapes0, ishapes1 in + zip(shapes0, shapes1)] + + modes = ['full', 'valid', 'same'] + return [ishapes+(imode,) for ishapes, imode in product(shapes, modes) + if imode != 'valid' or + (ishapes[0] > ishapes[1] and ishapes[2] > ishapes[3]) or + (ishapes[0] < ishapes[1] and ishapes[2] < ishapes[3])] + + +def gen_oa_shapes_eq(sizes): + return [(a, b) for a, b in product(sizes, repeat=2) + if a >= b] + + +class TestOAConvolve: + @pytest.mark.slow() + @pytest.mark.parametrize('shape_a_0, shape_b_0', + gen_oa_shapes_eq(list(range(100)) + + list(range(100, 1000, 23))) + ) + def test_real_manylens(self, shape_a_0, shape_b_0): + a = np.random.rand(shape_a_0) + b = np.random.rand(shape_b_0) + + expected = fftconvolve(a, b) + out = oaconvolve(a, b) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('shape_a_0, shape_b_0', + gen_oa_shapes([50, 47, 6, 4, 1])) + @pytest.mark.parametrize('is_complex', [True, False]) + @pytest.mark.parametrize('mode', ['full', 'valid', 'same']) + def test_1d_noaxes(self, shape_a_0, shape_b_0, + is_complex, mode, monkeypatch): + a = np.random.rand(shape_a_0) + b = np.random.rand(shape_b_0) + if is_complex: + a = a + 1j*np.random.rand(shape_a_0) + b = b + 1j*np.random.rand(shape_b_0) + + expected = fftconvolve(a, b, mode=mode) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [0, 1]) + @pytest.mark.parametrize('shape_a_0, shape_b_0', + gen_oa_shapes([50, 47, 6, 4])) + @pytest.mark.parametrize('shape_a_extra', [1, 3]) + @pytest.mark.parametrize('shape_b_extra', [1, 3]) + @pytest.mark.parametrize('is_complex', [True, False]) + @pytest.mark.parametrize('mode', ['full', 'valid', 'same']) + def test_1d_axes(self, axes, shape_a_0, shape_b_0, + shape_a_extra, shape_b_extra, + is_complex, mode, monkeypatch): + ax_a = [shape_a_extra]*2 + ax_b = [shape_b_extra]*2 + ax_a[axes] = shape_a_0 + ax_b[axes] = shape_b_0 + + a = np.random.rand(*ax_a) + b = np.random.rand(*ax_b) + if is_complex: + a = a + 1j*np.random.rand(*ax_a) + b = b + 1j*np.random.rand(*ax_b) + + expected = fftconvolve(a, b, mode=mode, axes=axes) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode, axes=axes) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('shape_a_0, shape_b_0, ' + 'shape_a_1, shape_b_1, mode', + gen_oa_shapes_2d([50, 47, 6, 4])) + @pytest.mark.parametrize('is_complex', [True, False]) + def test_2d_noaxes(self, shape_a_0, shape_b_0, + shape_a_1, shape_b_1, mode, + is_complex, monkeypatch): + a = np.random.rand(shape_a_0, shape_a_1) + b = np.random.rand(shape_b_0, shape_b_1) + if is_complex: + a = a + 1j*np.random.rand(shape_a_0, shape_a_1) + b = b + 1j*np.random.rand(shape_b_0, shape_b_1) + + expected = fftconvolve(a, b, mode=mode) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [[0, 1], [0, 2], [1, 2]]) + @pytest.mark.parametrize('shape_a_0, shape_b_0, ' + 'shape_a_1, shape_b_1, mode', + gen_oa_shapes_2d([50, 47, 6, 4])) + @pytest.mark.parametrize('shape_a_extra', [1, 3]) + @pytest.mark.parametrize('shape_b_extra', [1, 3]) + @pytest.mark.parametrize('is_complex', [True, False]) + def test_2d_axes(self, axes, shape_a_0, shape_b_0, + shape_a_1, shape_b_1, mode, + shape_a_extra, shape_b_extra, + is_complex, monkeypatch): + ax_a = [shape_a_extra]*3 + ax_b = [shape_b_extra]*3 + ax_a[axes[0]] = shape_a_0 + ax_b[axes[0]] = shape_b_0 + ax_a[axes[1]] = shape_a_1 + ax_b[axes[1]] = shape_b_1 + + a = np.random.rand(*ax_a) + b = np.random.rand(*ax_b) + if is_complex: + a = a + 1j*np.random.rand(*ax_a) + b = b + 1j*np.random.rand(*ax_b) + + expected = fftconvolve(a, b, mode=mode, axes=axes) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode, axes=axes) + + assert_array_almost_equal(out, expected) + + def test_empty(self): + # Regression test for #1745: crashes with 0-length input. + assert_(oaconvolve([], []).size == 0) + assert_(oaconvolve([5, 6], []).size == 0) + assert_(oaconvolve([], [7]).size == 0) + + def test_zero_rank(self): + a = array(4967) + b = array(3920) + out = oaconvolve(a, b) + assert_equal(out, a * b) + + def test_single_element(self): + a = array([4967]) + b = array([3920]) + out = oaconvolve(a, b) + assert_equal(out, a * b) + + +class TestAllFreqConvolves: + + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_invalid_shapes(self, convapproach): + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + with assert_raises(ValueError, + match="For 'valid' mode, one must be at least " + "as large as the other in every dimension"): + convapproach(a, b, mode='valid') + + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_invalid_shapes_axes(self, convapproach): + a = np.zeros([5, 6, 2, 1]) + b = np.zeros([5, 6, 3, 1]) + with assert_raises(ValueError, + match=r"incompatible shapes for in1 and in2:" + r" \(5L?, 6L?, 2L?, 1L?\) and" + r" \(5L?, 6L?, 3L?, 1L?\)"): + convapproach(a, b, axes=[0, 1]) + + @pytest.mark.parametrize('a,b', + [([1], 2), + (1, [2]), + ([3], [[2]])]) + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_mismatched_dims(self, a, b, convapproach): + with assert_raises(ValueError, + match="in1 and in2 should have the same" + " dimensionality"): + convapproach(a, b) + + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_invalid_flags(self, convapproach): + with assert_raises(ValueError, + match="acceptable mode flags are 'valid'," + " 'same', or 'full'"): + convapproach([1], [2], mode='chips') + + with assert_raises(ValueError, + match="when provided, axes cannot be empty"): + convapproach([1], [2], axes=[]) + + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + convapproach([1], [2], axes=[[1, 2], [3, 4]]) + + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + convapproach([1], [2], axes=[1., 2., 3., 4.]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + convapproach([1], [2], axes=[1]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + convapproach([1], [2], axes=[-2]) + + with assert_raises(ValueError, + match="all axes must be unique"): + convapproach([1], [2], axes=[0, 0]) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + @pytest.mark.parametrize('dtype', [np.longdouble, np.clongdouble]) + def test_longdtype_input(self, dtype): + x = np.random.random((27, 27)).astype(dtype) + y = np.random.random((4, 4)).astype(dtype) + if np.iscomplexobj(dtype()): + x += .1j + y -= .1j + + res = fftconvolve(x, y) + assert_allclose(res, convolve(x, y, method='direct')) + assert res.dtype == dtype + + +class TestMedFilt: + + IN = [[50, 50, 50, 50, 50, 92, 18, 27, 65, 46], + [50, 50, 50, 50, 50, 0, 72, 77, 68, 66], + [50, 50, 50, 50, 50, 46, 47, 19, 64, 77], + [50, 50, 50, 50, 50, 42, 15, 29, 95, 35], + [50, 50, 50, 50, 50, 46, 34, 9, 21, 66], + [70, 97, 28, 68, 78, 77, 61, 58, 71, 42], + [64, 53, 44, 29, 68, 32, 19, 68, 24, 84], + [3, 33, 53, 67, 1, 78, 74, 55, 12, 83], + [7, 11, 46, 70, 60, 47, 24, 43, 61, 26], + [32, 61, 88, 7, 39, 4, 92, 64, 45, 61]] + + OUT = [[0, 50, 50, 50, 42, 15, 15, 18, 27, 0], + [0, 50, 50, 50, 50, 42, 19, 21, 29, 0], + [50, 50, 50, 50, 50, 47, 34, 34, 46, 35], + [50, 50, 50, 50, 50, 50, 42, 47, 64, 42], + [50, 50, 50, 50, 50, 50, 46, 55, 64, 35], + [33, 50, 50, 50, 50, 47, 46, 43, 55, 26], + [32, 50, 50, 50, 50, 47, 46, 45, 55, 26], + [7, 46, 50, 50, 47, 46, 46, 43, 45, 21], + [0, 32, 33, 39, 32, 32, 43, 43, 43, 0], + [0, 7, 11, 7, 4, 4, 19, 19, 24, 0]] + + KERNEL_SIZE = [7,3] + + def test_basic(self): + d = signal.medfilt(self.IN, self.KERNEL_SIZE) + e = signal.medfilt2d(np.array(self.IN, float), self.KERNEL_SIZE) + assert_array_equal(d, self.OUT) + assert_array_equal(d, e) + + @pytest.mark.parametrize('dtype', [np.ubyte, np.byte, np.ushort, np.short, + np_ulong, np_long, np.ulonglong, np.ulonglong, + np.float32, np.float64]) + def test_types(self, dtype): + # volume input and output types match + in_typed = np.array(self.IN, dtype=dtype) + assert_equal(signal.medfilt(in_typed).dtype, dtype) + assert_equal(signal.medfilt2d(in_typed).dtype, dtype) + + @pytest.mark.parametrize('dtype', [np.bool_, np.complex64, np.complex128, + np.clongdouble, np.float16, np.object_, + "float96", "float128"]) + def test_invalid_dtypes(self, dtype): + # We can only test this on platforms that support a native type of float96 or + # float128; comparing to np.longdouble allows us to filter out non-native types + if (dtype in ["float96", "float128"] + and np.finfo(np.longdouble).dtype != dtype): + pytest.skip(f"Platform does not support {dtype}") + + in_typed = np.array(self.IN, dtype=dtype) + with pytest.raises(ValueError, match="not supported"): + signal.medfilt(in_typed) + + with pytest.raises(ValueError, match="not supported"): + signal.medfilt2d(in_typed) + + def test_none(self): + # gh-1651, trac #1124. Ensure this does not segfault. + msg = "dtype=object is not supported by medfilt" + with assert_raises(ValueError, match=msg): + signal.medfilt(None) + + def test_odd_strides(self): + # Avoid a regression with possible contiguous + # numpy arrays that have odd strides. The stride value below gets + # us into wrong memory if used (but it does not need to be used) + dummy = np.arange(10, dtype=np.float64) + a = dummy[5:6] + a.strides = 16 + assert_(signal.medfilt(a, 1) == 5.) + + @pytest.mark.parametrize("dtype", [np.ubyte, np.float32, np.float64]) + def test_medfilt2d_parallel(self, dtype): + in_typed = np.array(self.IN, dtype=dtype) + expected = np.array(self.OUT, dtype=dtype) + + # This is used to simplify the indexing calculations. + assert in_typed.shape == expected.shape + + # We'll do the calculation in four chunks. M1 and N1 are the dimensions + # of the first output chunk. We have to extend the input by half the + # kernel size to be able to calculate the full output chunk. + M1 = expected.shape[0] // 2 + N1 = expected.shape[1] // 2 + offM = self.KERNEL_SIZE[0] // 2 + 1 + offN = self.KERNEL_SIZE[1] // 2 + 1 + + def apply(chunk): + # in = slice of in_typed to use. + # sel = slice of output to crop it to the correct region. + # out = slice of output array to store in. + M, N = chunk + if M == 0: + Min = slice(0, M1 + offM) + Msel = slice(0, -offM) + Mout = slice(0, M1) + else: + Min = slice(M1 - offM, None) + Msel = slice(offM, None) + Mout = slice(M1, None) + if N == 0: + Nin = slice(0, N1 + offN) + Nsel = slice(0, -offN) + Nout = slice(0, N1) + else: + Nin = slice(N1 - offN, None) + Nsel = slice(offN, None) + Nout = slice(N1, None) + + # Do the calculation, but do not write to the output in the threads. + chunk_data = in_typed[Min, Nin] + med = signal.medfilt2d(chunk_data, self.KERNEL_SIZE) + return med[Msel, Nsel], Mout, Nout + + # Give each chunk to a different thread. + output = np.zeros_like(expected) + with ThreadPoolExecutor(max_workers=4) as pool: + chunks = {(0, 0), (0, 1), (1, 0), (1, 1)} + futures = {pool.submit(apply, chunk) for chunk in chunks} + + # Store each result in the output as it arrives. + for future in as_completed(futures): + data, Mslice, Nslice = future.result() + output[Mslice, Nslice] = data + + assert_array_equal(output, expected) + + +class TestWiener: + + def test_basic(self): + g = array([[5, 6, 4, 3], + [3, 5, 6, 2], + [2, 3, 5, 6], + [1, 6, 9, 7]], 'd') + h = array([[2.16374269, 3.2222222222, 2.8888888889, 1.6666666667], + [2.666666667, 4.33333333333, 4.44444444444, 2.8888888888], + [2.222222222, 4.4444444444, 5.4444444444, 4.801066874837], + [1.33333333333, 3.92735042735, 6.0712560386, 5.0404040404]]) + assert_array_almost_equal(signal.wiener(g), h, decimal=6) + assert_array_almost_equal(signal.wiener(g, mysize=3), h, decimal=6) + + +padtype_options = ["mean", "median", "minimum", "maximum", "line"] +padtype_options += _upfirdn_modes + + +class TestResample: + def test_basic(self): + # Some basic tests + + # Regression test for issue #3603. + # window.shape must equal to sig.shape[0] + sig = np.arange(128) + num = 256 + win = signal.get_window(('kaiser', 8.0), 160) + assert_raises(ValueError, signal.resample, sig, num, window=win) + + # Other degenerate conditions + assert_raises(ValueError, signal.resample_poly, sig, 'yo', 1) + assert_raises(ValueError, signal.resample_poly, sig, 1, 0) + assert_raises(ValueError, signal.resample_poly, sig, 2, 1, padtype='') + assert_raises(ValueError, signal.resample_poly, sig, 2, 1, + padtype='mean', cval=10) + + # test for issue #6505 - should not modify window.shape when axis ≠ 0 + sig2 = np.tile(np.arange(160), (2, 1)) + signal.resample(sig2, num, axis=-1, window=win) + assert_(win.shape == (160,)) + + @pytest.mark.parametrize('window', (None, 'hamming')) + @pytest.mark.parametrize('N', (20, 19)) + @pytest.mark.parametrize('num', (100, 101, 10, 11)) + def test_rfft(self, N, num, window): + # Make sure the speed up using rfft gives the same result as the normal + # way using fft + x = np.linspace(0, 10, N, endpoint=False) + y = np.cos(-x**2/6.0) + assert_allclose(signal.resample(y, num, window=window), + signal.resample(y + 0j, num, window=window).real) + + y = np.array([np.cos(-x**2/6.0), np.sin(-x**2/6.0)]) + y_complex = y + 0j + assert_allclose( + signal.resample(y, num, axis=1, window=window), + signal.resample(y_complex, num, axis=1, window=window).real, + atol=1e-9) + + def test_input_domain(self): + # Test if both input domain modes produce the same results. + tsig = np.arange(256) + 0j + fsig = sp_fft.fft(tsig) + num = 256 + assert_allclose( + signal.resample(fsig, num, domain='freq'), + signal.resample(tsig, num, domain='time'), + atol=1e-9) + + @pytest.mark.parametrize('nx', (1, 2, 3, 5, 8)) + @pytest.mark.parametrize('ny', (1, 2, 3, 5, 8)) + @pytest.mark.parametrize('dtype', ('float', 'complex')) + def test_dc(self, nx, ny, dtype): + x = np.array([1] * nx, dtype) + y = signal.resample(x, ny) + assert_allclose(y, [1] * ny) + + @pytest.mark.thread_unsafe # due to Cython fused types, see cython#6506 + @pytest.mark.parametrize('padtype', padtype_options) + def test_mutable_window(self, padtype): + # Test that a mutable window is not modified + impulse = np.zeros(3) + window = np.random.RandomState(0).randn(2) + window_orig = window.copy() + signal.resample_poly(impulse, 5, 1, window=window, padtype=padtype) + assert_array_equal(window, window_orig) + + @pytest.mark.parametrize('padtype', padtype_options) + def test_output_float32(self, padtype): + # Test that float32 inputs yield a float32 output + x = np.arange(10, dtype=np.float32) + h = np.array([1, 1, 1], dtype=np.float32) + y = signal.resample_poly(x, 1, 2, window=h, padtype=padtype) + assert y.dtype == np.float32 + + @pytest.mark.parametrize('padtype', padtype_options) + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_output_match_dtype(self, padtype, dtype): + # Test that the dtype of x is preserved per issue #14733 + x = np.arange(10, dtype=dtype) + y = signal.resample_poly(x, 1, 2, padtype=padtype) + assert y.dtype == x.dtype + + @pytest.mark.parametrize( + "method, ext, padtype", + [("fft", False, None)] + + list( + product( + ["polyphase"], [False, True], padtype_options, + ) + ), + ) + def test_resample_methods(self, method, ext, padtype): + # Test resampling of sinusoids and random noise (1-sec) + rate = 100 + rates_to = [49, 50, 51, 99, 100, 101, 199, 200, 201] + + # Sinusoids, windowed to avoid edge artifacts + t = np.arange(rate) / float(rate) + freqs = np.array((1., 10., 40.))[:, np.newaxis] + x = np.sin(2 * np.pi * freqs * t) * hann(rate) + + for rate_to in rates_to: + t_to = np.arange(rate_to) / float(rate_to) + y_tos = np.sin(2 * np.pi * freqs * t_to) * hann(rate_to) + if method == 'fft': + y_resamps = signal.resample(x, rate_to, axis=-1) + else: + if ext and rate_to != rate: + # Match default window design + g = gcd(rate_to, rate) + up = rate_to // g + down = rate // g + max_rate = max(up, down) + f_c = 1. / max_rate + half_len = 10 * max_rate + window = signal.firwin(2 * half_len + 1, f_c, + window=('kaiser', 5.0)) + polyargs = {'window': window, 'padtype': padtype} + else: + polyargs = {'padtype': padtype} + + y_resamps = signal.resample_poly(x, rate_to, rate, axis=-1, + **polyargs) + + for y_to, y_resamp, freq in zip(y_tos, y_resamps, freqs): + if freq >= 0.5 * rate_to: + y_to.fill(0.) # mostly low-passed away + if padtype in ['minimum', 'maximum']: + assert_allclose(y_resamp, y_to, atol=3e-1) + else: + assert_allclose(y_resamp, y_to, atol=1e-3) + else: + assert_array_equal(y_to.shape, y_resamp.shape) + corr = np.corrcoef(y_to, y_resamp)[0, 1] + assert_(corr > 0.99, msg=(corr, rate, rate_to)) + + # Random data + rng = np.random.RandomState(0) + x = hann(rate) * np.cumsum(rng.randn(rate)) # low-pass, wind + for rate_to in rates_to: + # random data + t_to = np.arange(rate_to) / float(rate_to) + y_to = np.interp(t_to, t, x) + if method == 'fft': + y_resamp = signal.resample(x, rate_to) + else: + y_resamp = signal.resample_poly(x, rate_to, rate, + padtype=padtype) + assert_array_equal(y_to.shape, y_resamp.shape) + corr = np.corrcoef(y_to, y_resamp)[0, 1] + assert_(corr > 0.99, msg=corr) + + # More tests of fft method (Master 0.18.1 fails these) + if method == 'fft': + x1 = np.array([1.+0.j, 0.+0.j]) + y1_test = signal.resample(x1, 4) + # upsampling a complex array + y1_true = np.array([1.+0.j, 0.5+0.j, 0.+0.j, 0.5+0.j]) + assert_allclose(y1_test, y1_true, atol=1e-12) + x2 = np.array([1., 0.5, 0., 0.5]) + y2_test = signal.resample(x2, 2) # downsampling a real array + y2_true = np.array([1., 0.]) + assert_allclose(y2_test, y2_true, atol=1e-12) + + def test_poly_vs_filtfilt(self): + # Check that up=1.0 gives same answer as filtfilt + slicing + random_state = np.random.RandomState(17) + try_types = (int, np.float32, np.complex64, float, complex) + size = 10000 + down_factors = [2, 11, 79] + + for dtype in try_types: + x = random_state.randn(size).astype(dtype) + if dtype in (np.complex64, np.complex128): + x += 1j * random_state.randn(size) + + # resample_poly assumes zeros outside of signl, whereas filtfilt + # can only constant-pad. Make them equivalent: + x[0] = 0 + x[-1] = 0 + + for down in down_factors: + h = signal.firwin(31, 1. / down, window='hamming') + yf = filtfilt(h, 1.0, x, padtype='constant')[::down] + + # Need to pass convolved version of filter to resample_poly, + # since filtfilt does forward and backward, but resample_poly + # only goes forward + hc = convolve(h, h[::-1]) + y = signal.resample_poly(x, 1, down, window=hc) + assert_allclose(yf, y, atol=1e-7, rtol=1e-7) + + def test_correlate1d(self): + for down in [2, 4]: + for nx in range(1, 40, down): + for nweights in (32, 33): + x = np.random.random((nx,)) + weights = np.random.random((nweights,)) + y_g = correlate1d(x, weights[::-1], mode='constant') + y_s = signal.resample_poly( + x, up=1, down=down, window=weights) + assert_allclose(y_g[::down], y_s) + + @pytest.mark.parametrize('dtype', [np.int32, np.float32]) + def test_gh_15620(self, dtype): + data = np.array([0, 1, 2, 3, 2, 1, 0], dtype=dtype) + actual = signal.resample_poly(data, + up=2, + down=1, + padtype='smooth') + assert np.count_nonzero(actual) > 0 + + +class TestCSpline1DEval: + + def test_basic(self): + y = array([1, 2, 3, 4, 3, 2, 1, 2, 3.0]) + x = arange(len(y)) + dx = x[1] - x[0] + cj = signal.cspline1d(y) + + x2 = arange(len(y) * 10.0) / 10.0 + y2 = signal.cspline1d_eval(cj, x2, dx=dx, x0=x[0]) + + # make sure interpolated values are on knot points + assert_array_almost_equal(y2[::10], y, decimal=5) + + def test_complex(self): + # create some smoothly varying complex signal to interpolate + x = np.arange(2) + y = np.zeros(x.shape, dtype=np.complex64) + T = 10.0 + f = 1.0 / T + y = np.exp(2.0J * np.pi * f * x) + + # get the cspline transform + cy = signal.cspline1d(y) + + # determine new test x value and interpolate + xnew = np.array([0.5]) + ynew = signal.cspline1d_eval(cy, xnew) + + assert_equal(ynew.dtype, y.dtype) + +class TestOrderFilt: + + def test_basic(self): + assert_array_equal(signal.order_filter([1, 2, 3], [1, 0, 1], 1), + [2, 3, 2]) + + +class _TestLinearFilter: + + def generate(self, shape): + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + return self.convert_dtype(x) + + def convert_dtype(self, arr): + if self.dtype == np.dtype('O'): + arr = np.asarray(arr) + out = np.empty(arr.shape, self.dtype) + iter = np.nditer([arr, out], ['refs_ok','zerosize_ok'], + [['readonly'],['writeonly']]) + for x, y in iter: + y[...] = self.type(x[()]) + return out + else: + return np.asarray(arr, dtype=self.dtype) + + def test_rank_1_IIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, -0.5]) + y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.]) + assert_array_almost_equal(lfilter(b, a, x), y_r) + + def test_rank_1_FIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 1]) + a = self.convert_dtype([1]) + y_r = self.convert_dtype([0, 1, 3, 5, 7, 9.]) + assert_array_almost_equal(lfilter(b, a, x), y_r) + + def test_rank_1_IIR_init_cond(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([0.5, -0.5]) + zi = self.convert_dtype([1, 2]) + y_r = self.convert_dtype([1, 5, 9, 13, 17, 21]) + zf_r = self.convert_dtype([13, -10]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_rank_1_FIR_init_cond(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 1, 1]) + a = self.convert_dtype([1]) + zi = self.convert_dtype([1, 1]) + y_r = self.convert_dtype([1, 2, 3, 6, 9, 12.]) + zf_r = self.convert_dtype([9, 5]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_rank_2_IIR_axis_0(self): + x = self.generate((4, 3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + y_r2_a0 = self.convert_dtype([[0, 2, 4], [6, 4, 2], [0, 2, 4], + [6, 4, 2]]) + y = lfilter(b, a, x, axis=0) + assert_array_almost_equal(y_r2_a0, y) + + def test_rank_2_IIR_axis_1(self): + x = self.generate((4, 3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + y_r2_a1 = self.convert_dtype([[0, 2, 0], [6, -4, 6], [12, -10, 12], + [18, -16, 18]]) + y = lfilter(b, a, x, axis=1) + assert_array_almost_equal(y_r2_a1, y) + + def test_rank_2_IIR_axis_0_init_cond(self): + x = self.generate((4, 3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + zi = self.convert_dtype(np.ones((4,1))) + + y_r2_a0_1 = self.convert_dtype([[1, 1, 1], [7, -5, 7], [13, -11, 13], + [19, -17, 19]]) + zf_r = self.convert_dtype([-5, -17, -29, -41])[:, np.newaxis] + y, zf = lfilter(b, a, x, axis=1, zi=zi) + assert_array_almost_equal(y_r2_a0_1, y) + assert_array_almost_equal(zf, zf_r) + + def test_rank_2_IIR_axis_1_init_cond(self): + x = self.generate((4,3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + zi = self.convert_dtype(np.ones((1,3))) + + y_r2_a0_0 = self.convert_dtype([[1, 3, 5], [5, 3, 1], + [1, 3, 5], [5, 3, 1]]) + zf_r = self.convert_dtype([[-23, -23, -23]]) + y, zf = lfilter(b, a, x, axis=0, zi=zi) + assert_array_almost_equal(y_r2_a0_0, y) + assert_array_almost_equal(zf, zf_r) + + def test_rank_3_IIR(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + + for axis in range(x.ndim): + y = lfilter(b, a, x, axis) + y_r = np.apply_along_axis(lambda w: lfilter(b, a, w), axis, x) + assert_array_almost_equal(y, y_r) + + def test_rank_3_IIR_init_cond(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + + for axis in range(x.ndim): + zi_shape = list(x.shape) + zi_shape[axis] = 1 + zi = self.convert_dtype(np.ones(zi_shape)) + zi1 = self.convert_dtype([1]) + y, zf = lfilter(b, a, x, axis, zi) + def lf0(w): + return lfilter(b, a, w, zi=zi1)[0] + def lf1(w): + return lfilter(b, a, w, zi=zi1)[1] + y_r = np.apply_along_axis(lf0, axis, x) + zf_r = np.apply_along_axis(lf1, axis, x) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_rank_3_FIR(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([1]) + + for axis in range(x.ndim): + y = lfilter(b, a, x, axis) + y_r = np.apply_along_axis(lambda w: lfilter(b, a, w), axis, x) + assert_array_almost_equal(y, y_r) + + def test_rank_3_FIR_init_cond(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([1]) + + for axis in range(x.ndim): + zi_shape = list(x.shape) + zi_shape[axis] = 2 + zi = self.convert_dtype(np.ones(zi_shape)) + zi1 = self.convert_dtype([1, 1]) + y, zf = lfilter(b, a, x, axis, zi) + def lf0(w): + return lfilter(b, a, w, zi=zi1)[0] + def lf1(w): + return lfilter(b, a, w, zi=zi1)[1] + y_r = np.apply_along_axis(lf0, axis, x) + zf_r = np.apply_along_axis(lf1, axis, x) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_zi_pseudobroadcast(self): + x = self.generate((4, 5, 20)) + b,a = signal.butter(8, 0.2, output='ba') + b = self.convert_dtype(b) + a = self.convert_dtype(a) + zi_size = b.shape[0] - 1 + + # lfilter requires x.ndim == zi.ndim exactly. However, zi can have + # length 1 dimensions. + zi_full = self.convert_dtype(np.ones((4, 5, zi_size))) + zi_sing = self.convert_dtype(np.ones((1, 1, zi_size))) + + y_full, zf_full = lfilter(b, a, x, zi=zi_full) + y_sing, zf_sing = lfilter(b, a, x, zi=zi_sing) + + assert_array_almost_equal(y_sing, y_full) + assert_array_almost_equal(zf_full, zf_sing) + + # lfilter does not prepend ones + assert_raises(ValueError, lfilter, b, a, x, -1, np.ones(zi_size)) + + def test_scalar_a(self): + # a can be a scalar. + x = self.generate(6) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([1]) + y_r = self.convert_dtype([0, 1, 2, 2, 2, 2]) + + y = lfilter(b, a[0], x) + assert_array_almost_equal(y, y_r) + + def test_zi_some_singleton_dims(self): + # lfilter doesn't really broadcast (no prepending of 1's). But does + # do singleton expansion if x and zi have the same ndim. This was + # broken only if a subset of the axes were singletons (gh-4681). + x = self.convert_dtype(np.zeros((3,2,5), 'l')) + b = self.convert_dtype(np.ones(5, 'l')) + a = self.convert_dtype(np.array([1,0,0])) + zi = np.ones((3,1,4), 'l') + zi[1,:,:] *= 2 + zi[2,:,:] *= 3 + zi = self.convert_dtype(zi) + + zf_expected = self.convert_dtype(np.zeros((3,2,4), 'l')) + y_expected = np.zeros((3,2,5), 'l') + y_expected[:,:,:4] = [[[1]], [[2]], [[3]]] + y_expected = self.convert_dtype(y_expected) + + # IIR + y_iir, zf_iir = lfilter(b, a, x, -1, zi) + assert_array_almost_equal(y_iir, y_expected) + assert_array_almost_equal(zf_iir, zf_expected) + + # FIR + y_fir, zf_fir = lfilter(b, a[0], x, -1, zi) + assert_array_almost_equal(y_fir, y_expected) + assert_array_almost_equal(zf_fir, zf_expected) + + def base_bad_size_zi(self, b, a, x, axis, zi): + b = self.convert_dtype(b) + a = self.convert_dtype(a) + x = self.convert_dtype(x) + zi = self.convert_dtype(zi) + assert_raises(ValueError, lfilter, b, a, x, axis, zi) + + def test_bad_size_zi(self): + # rank 1 + x1 = np.arange(6) + self.base_bad_size_zi([1], [1], x1, -1, [1]) + self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1]) + self.base_bad_size_zi([1, 1], [1], x1, -1, [[0]]) + self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [[0]]) + self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1]) + self.base_bad_size_zi([1], [1, 1], x1, -1, [[0]]) + self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [[0], [1]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2, 3]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [[0], [1]]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2, 3]) + + # rank 2 + x2 = np.arange(12).reshape((4,3)) + # for axis=0 zi.shape should == (max(len(a),len(b))-1, 3) + self.base_bad_size_zi([1], [1], x2, 0, [0]) + + # for each of these there are 5 cases tested (in this order): + # 1. not deep enough, right # elements + # 2. too deep, right # elements + # 3. right depth, right # elements, transposed + # 4. right depth, too few elements + # 5. right depth, too many elements + + self.base_bad_size_zi([1, 1], [1], x2, 0, [0,1,2]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[[0,1,2]]]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[0], [1], [2]]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[0,1]]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[0,1,2,3]]) + + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [0,1,2,3,4,5]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[[0,1,2],[3,4,5]]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1],[2,3]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1,2,3],[4,5,6,7]]) + + self.base_bad_size_zi([1], [1, 1], x2, 0, [0,1,2]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[[0,1,2]]]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[0], [1], [2]]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[0,1]]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[0,1,2,3]]) + + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [0,1,2,3,4,5]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[[0,1,2],[3,4,5]]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1],[2,3]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1,2,3],[4,5,6,7]]) + + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [0,1,2,3,4,5]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[[0,1,2],[3,4,5]]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1],[2,3]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1,2,3],[4,5,6,7]]) + + # for axis=1 zi.shape should == (4, max(len(a),len(b))-1) + self.base_bad_size_zi([1], [1], x2, 1, [0]) + + self.base_bad_size_zi([1, 1], [1], x2, 1, [0,1,2,3]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[[0],[1],[2],[3]]]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[0, 1, 2, 3]]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[0],[1],[2]]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[0],[1],[2],[3],[4]]) + + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [0,1,2,3,4,5,6,7]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1,2,3],[4,5,6,7]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) + + self.base_bad_size_zi([1], [1, 1], x2, 1, [0,1,2,3]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[[0],[1],[2],[3]]]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[0, 1, 2, 3]]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[0],[1],[2]]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[0],[1],[2],[3],[4]]) + + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [0,1,2,3,4,5,6,7]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1,2,3],[4,5,6,7]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) + + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [0,1,2,3,4,5,6,7]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1,2,3],[4,5,6,7]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) + + def test_empty_zi(self): + # Regression test for #880: empty array for zi crashes. + x = self.generate((5,)) + a = self.convert_dtype([1]) + b = self.convert_dtype([1]) + zi = self.convert_dtype([]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, x) + assert_equal(zf.dtype, self.dtype) + assert_equal(zf.size, 0) + + def test_lfiltic_bad_zi(self): + # Regression test for #3699: bad initial conditions + a = self.convert_dtype([1]) + b = self.convert_dtype([1]) + # "y" sets the datatype of zi, so it truncates if int + zi = lfiltic(b, a, [1., 0]) + zi_1 = lfiltic(b, a, [1, 0]) + zi_2 = lfiltic(b, a, [True, False]) + assert_array_equal(zi, zi_1) + assert_array_equal(zi, zi_2) + + def test_short_x_FIR(self): + # regression test for #5116 + # x shorter than b, with non None zi fails + a = self.convert_dtype([1]) + b = self.convert_dtype([1, 0, -1]) + zi = self.convert_dtype([2, 7]) + x = self.convert_dtype([72]) + ye = self.convert_dtype([74]) + zfe = self.convert_dtype([7, -72]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, ye) + assert_array_almost_equal(zf, zfe) + + def test_short_x_IIR(self): + # regression test for #5116 + # x shorter than b, with non None zi fails + a = self.convert_dtype([1, 1]) + b = self.convert_dtype([1, 0, -1]) + zi = self.convert_dtype([2, 7]) + x = self.convert_dtype([72]) + ye = self.convert_dtype([74]) + zfe = self.convert_dtype([-67, -72]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, ye) + assert_array_almost_equal(zf, zfe) + + def test_do_not_modify_a_b_IIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, -1]) + b0 = b.copy() + a = self.convert_dtype([0.5, -0.5]) + a0 = a.copy() + y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.]) + y_f = lfilter(b, a, x) + assert_array_almost_equal(y_f, y_r) + assert_equal(b, b0) + assert_equal(a, a0) + + def test_do_not_modify_a_b_FIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 0, 1]) + b0 = b.copy() + a = self.convert_dtype([2]) + a0 = a.copy() + y_r = self.convert_dtype([0, 0.5, 1, 2, 3, 4.]) + y_f = lfilter(b, a, x) + assert_array_almost_equal(y_f, y_r) + assert_equal(b, b0) + assert_equal(a, a0) + + @pytest.mark.parametrize("a", [1.0, [1.0], np.array(1.0)]) + @pytest.mark.parametrize("b", [1.0, [1.0], np.array(1.0)]) + def test_scalar_input(self, a, b): + data = np.random.randn(10) + assert_allclose( + lfilter(np.array([1.0]), np.array([1.0]), data), + lfilter(b, a, data)) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + lfilter(a, b, [1, 2, 3, 4]) + + +class TestLinearFilterFloat32(_TestLinearFilter): + dtype = np.dtype('f') + + +class TestLinearFilterFloat64(_TestLinearFilter): + dtype = np.dtype('d') + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterFloatExtended(_TestLinearFilter): + dtype = np.dtype('g') + + +class TestLinearFilterComplex64(_TestLinearFilter): + dtype = np.dtype('F') + + +class TestLinearFilterComplex128(_TestLinearFilter): + dtype = np.dtype('D') + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterComplexExtended(_TestLinearFilter): + dtype = np.dtype('G') + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterDecimal(_TestLinearFilter): + dtype = np.dtype('O') + + def type(self, x): + return Decimal(str(x)) + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterObject(_TestLinearFilter): + dtype = np.dtype('O') + type = float + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +def test_lfilter_bad_object(): + # lfilter: object arrays with non-numeric objects raise TypeError. + # Regression test for ticket #1452. + if hasattr(sys, 'abiflags') and 'd' in sys.abiflags: + pytest.skip('test is flaky when run with python3-dbg') + assert_raises(TypeError, lfilter, [1.0], [1.0], [1.0, None, 2.0]) + assert_raises(TypeError, lfilter, [1.0], [None], [1.0, 2.0, 3.0]) + assert_raises(TypeError, lfilter, [None], [1.0], [1.0, 2.0, 3.0]) + + +_pmf = pytest.mark.filterwarnings('ignore::DeprecationWarning') + +def test_lfilter_notimplemented_input(): + # Should not crash, gh-7991 + assert_raises(NotImplementedError, lfilter, [2,3], [4,5], [1,2,3,4,5]) + + +@pytest.mark.parametrize('dt', [np.ubyte, np.byte, np.ushort, np.short, + np_ulong, np_long, np.ulonglong, np.ulonglong, + np.float32, np.float64, + pytest.param(np.longdouble, marks=_pmf), + pytest.param(Decimal, marks=_pmf)] +) +class TestCorrelateReal: + def _setup_rank1(self, dt): + a = np.linspace(0, 3, 4).astype(dt) + b = np.linspace(1, 2, 2).astype(dt) + + y_r = np.array([0, 2, 5, 8, 3]).astype(dt) + return a, b, y_r + + def equal_tolerance(self, res_dt): + # default value of keyword + decimal = 6 + try: + dt_info = np.finfo(res_dt) + if hasattr(dt_info, 'resolution'): + decimal = int(-0.5*np.log10(dt_info.resolution)) + except Exception: + pass + return decimal + + def equal_tolerance_fft(self, res_dt): + # FFT implementations convert longdouble arguments down to + # double so don't expect better precision, see gh-9520 + if res_dt == np.longdouble: + return self.equal_tolerance(np.float64) + else: + return self.equal_tolerance(res_dt) + + def test_method(self, dt): + if dt == Decimal: + method = choose_conv_method([Decimal(4)], [Decimal(3)]) + assert_equal(method, 'direct') + else: + a, b, y_r = self._setup_rank3(dt) + y_fft = correlate(a, b, method='fft') + y_direct = correlate(a, b, method='direct') + + assert_array_almost_equal(y_r, + y_fft, + decimal=self.equal_tolerance_fft(y_fft.dtype),) + assert_array_almost_equal(y_r, + y_direct, + decimal=self.equal_tolerance(y_direct.dtype),) + assert_equal(y_fft.dtype, dt) + assert_equal(y_direct.dtype, dt) + + def test_rank1_valid(self, dt): + a, b, y_r = self._setup_rank1(dt) + y = correlate(a, b, 'valid') + assert_array_almost_equal(y, y_r[1:4]) + assert_equal(y.dtype, dt) + + # See gh-5897 + y = correlate(b, a, 'valid') + assert_array_almost_equal(y, y_r[1:4][::-1]) + assert_equal(y.dtype, dt) + + def test_rank1_same(self, dt): + a, b, y_r = self._setup_rank1(dt) + y = correlate(a, b, 'same') + assert_array_almost_equal(y, y_r[:-1]) + assert_equal(y.dtype, dt) + + def test_rank1_full(self, dt): + a, b, y_r = self._setup_rank1(dt) + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r) + assert_equal(y.dtype, dt) + + def _setup_rank3(self, dt): + a = np.linspace(0, 39, 40).reshape((2, 4, 5), order='F').astype( + dt) + b = np.linspace(0, 23, 24).reshape((2, 3, 4), order='F').astype( + dt) + + y_r = array([[[0., 184., 504., 912., 1360., 888., 472., 160.], + [46., 432., 1062., 1840., 2672., 1698., 864., 266.], + [134., 736., 1662., 2768., 3920., 2418., 1168., 314.], + [260., 952., 1932., 3056., 4208., 2580., 1240., 332.], + [202., 664., 1290., 1984., 2688., 1590., 712., 150.], + [114., 344., 642., 960., 1280., 726., 296., 38.]], + + [[23., 400., 1035., 1832., 2696., 1737., 904., 293.], + [134., 920., 2166., 3680., 5280., 3306., 1640., 474.], + [325., 1544., 3369., 5512., 7720., 4683., 2192., 535.], + [571., 1964., 3891., 6064., 8272., 4989., 2324., 565.], + [434., 1360., 2586., 3920., 5264., 3054., 1312., 230.], + [241., 700., 1281., 1888., 2496., 1383., 532., 39.]], + + [[22., 214., 528., 916., 1332., 846., 430., 132.], + [86., 484., 1098., 1832., 2600., 1602., 772., 206.], + [188., 802., 1698., 2732., 3788., 2256., 1018., 218.], + [308., 1006., 1950., 2996., 4052., 2400., 1078., 230.], + [230., 692., 1290., 1928., 2568., 1458., 596., 78.], + [126., 354., 636., 924., 1212., 654., 234., 0.]]], + dtype=np.float64).astype(dt) + + return a, b, y_r + + def test_rank3_valid(self, dt): + a, b, y_r = self._setup_rank3(dt) + y = correlate(a, b, "valid") + assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5]) + assert_equal(y.dtype, dt) + + # See gh-5897 + y = correlate(b, a, "valid") + assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5][::-1, ::-1, ::-1]) + assert_equal(y.dtype, dt) + + def test_rank3_same(self, dt): + a, b, y_r = self._setup_rank3(dt) + y = correlate(a, b, "same") + assert_array_almost_equal(y, y_r[0:-1, 1:-1, 1:-2]) + assert_equal(y.dtype, dt) + + def test_rank3_all(self, dt): + a, b, y_r = self._setup_rank3(dt) + y = correlate(a, b) + assert_array_almost_equal(y, y_r) + assert_equal(y.dtype, dt) + + +class TestCorrelate: + # Tests that don't depend on dtype + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, correlate, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, correlate, *(b, a), **{'mode': 'valid'}) + + def test_invalid_params(self): + a = [3, 4, 5] + b = [1, 2, 3] + assert_raises(ValueError, correlate, a, b, mode='spam') + assert_raises(ValueError, correlate, a, b, mode='eggs', method='fft') + assert_raises(ValueError, correlate, a, b, mode='ham', method='direct') + assert_raises(ValueError, correlate, a, b, mode='full', method='bacon') + assert_raises(ValueError, correlate, a, b, mode='same', method='bacon') + + def test_mismatched_dims(self): + # Input arrays should have the same number of dimensions + assert_raises(ValueError, correlate, [1], 2, method='direct') + assert_raises(ValueError, correlate, 1, [2], method='direct') + assert_raises(ValueError, correlate, [1], 2, method='fft') + assert_raises(ValueError, correlate, 1, [2], method='fft') + assert_raises(ValueError, correlate, [1], [[2]]) + assert_raises(ValueError, correlate, [3], 2) + + def test_numpy_fastpath(self): + a = [1, 2, 3] + b = [4, 5] + assert_allclose(correlate(a, b, mode='same'), [5, 14, 23]) + + a = [1, 2, 3] + b = [4, 5, 6] + assert_allclose(correlate(a, b, mode='same'), [17, 32, 23]) + assert_allclose(correlate(a, b, mode='full'), [6, 17, 32, 23, 12]) + assert_allclose(correlate(a, b, mode='valid'), [32]) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + correlate(a, b) + + +@pytest.mark.parametrize("mode", ["valid", "same", "full"]) +@pytest.mark.parametrize("behind", [True, False]) +@pytest.mark.parametrize("input_size", [100, 101, 1000, 1001, 10000, 10001]) +def test_correlation_lags(mode, behind, input_size): + # generate random data + rng = np.random.RandomState(0) + in1 = rng.standard_normal(input_size) + offset = int(input_size/10) + # generate offset version of array to correlate with + if behind: + # y is behind x + in2 = np.concatenate([rng.standard_normal(offset), in1]) + expected = -offset + else: + # y is ahead of x + in2 = in1[offset:] + expected = offset + # cross correlate, returning lag information + correlation = correlate(in1, in2, mode=mode) + lags = correlation_lags(in1.size, in2.size, mode=mode) + # identify the peak + lag_index = np.argmax(correlation) + # Check as expected + assert_equal(lags[lag_index], expected) + # Correlation and lags shape should match + assert_equal(lags.shape, correlation.shape) + + +def test_correlation_lags_invalid_mode(): + with pytest.raises(ValueError, match="Mode asdfgh is invalid"): + correlation_lags(100, 100, mode="asdfgh") + + +@pytest.mark.parametrize('dt', [np.csingle, np.cdouble, + pytest.param(np.clongdouble, marks=_pmf)]) +class TestCorrelateComplex: + # The decimal precision to be used for comparing results. + # This value will be passed as the 'decimal' keyword argument of + # assert_array_almost_equal(). + # Since correlate may chose to use FFT method which converts + # longdoubles to doubles internally don't expect better precision + # for longdouble than for double (see gh-9520). + + def decimal(self, dt): + if dt == np.clongdouble: + dt = np.cdouble + return int(2 * np.finfo(dt).precision / 3) + + def _setup_rank1(self, dt, mode): + np.random.seed(9) + a = np.random.randn(10).astype(dt) + a += 1j * np.random.randn(10).astype(dt) + b = np.random.randn(8).astype(dt) + b += 1j * np.random.randn(8).astype(dt) + + y_r = (correlate(a.real, b.real, mode=mode) + + correlate(a.imag, b.imag, mode=mode)).astype(dt) + y_r += 1j * (-correlate(a.real, b.imag, mode=mode) + + correlate(a.imag, b.real, mode=mode)) + return a, b, y_r + + def test_rank1_valid(self, dt): + a, b, y_r = self._setup_rank1(dt, 'valid') + y = correlate(a, b, 'valid') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + # See gh-5897 + y = correlate(b, a, 'valid') + assert_array_almost_equal(y, y_r[::-1].conj(), decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + def test_rank1_same(self, dt): + a, b, y_r = self._setup_rank1(dt, 'same') + y = correlate(a, b, 'same') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + def test_rank1_full(self, dt): + a, b, y_r = self._setup_rank1(dt, 'full') + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + def test_swap_full(self, dt): + d = np.array([0.+0.j, 1.+1.j, 2.+2.j], dtype=dt) + k = np.array([1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j], dtype=dt) + y = correlate(d, k) + assert_equal(y, [0.+0.j, 10.-2.j, 28.-6.j, 22.-6.j, 16.-6.j, 8.-4.j]) + + def test_swap_same(self, dt): + d = [0.+0.j, 1.+1.j, 2.+2.j] + k = [1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j] + y = correlate(d, k, mode="same") + assert_equal(y, [10.-2.j, 28.-6.j, 22.-6.j]) + + def test_rank3(self, dt): + a = np.random.randn(10, 8, 6).astype(dt) + a += 1j * np.random.randn(10, 8, 6).astype(dt) + b = np.random.randn(8, 6, 4).astype(dt) + b += 1j * np.random.randn(8, 6, 4).astype(dt) + + y_r = (correlate(a.real, b.real) + + correlate(a.imag, b.imag)).astype(dt) + y_r += 1j * (-correlate(a.real, b.imag) + correlate(a.imag, b.real)) + + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt) - 1) + assert_equal(y.dtype, dt) + + def test_rank0(self, dt): + a = np.array(np.random.randn()).astype(dt) + a += 1j * np.array(np.random.randn()).astype(dt) + b = np.array(np.random.randn()).astype(dt) + b += 1j * np.array(np.random.randn()).astype(dt) + + y_r = (correlate(a.real, b.real) + + correlate(a.imag, b.imag)).astype(dt) + y_r += 1j * np.array(-correlate(a.real, b.imag) + + correlate(a.imag, b.real)) + + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt) - 1) + assert_equal(y.dtype, dt) + + assert_equal(correlate([1], [2j]), correlate(1, 2j)) + assert_equal(correlate([2j], [3j]), correlate(2j, 3j)) + assert_equal(correlate([3j], [4]), correlate(3j, 4)) + + +class TestCorrelate2d: + + def test_consistency_correlate_funcs(self): + # Compare np.correlate, signal.correlate, signal.correlate2d + a = np.arange(5) + b = np.array([3.2, 1.4, 3]) + for mode in ['full', 'valid', 'same']: + assert_almost_equal(np.correlate(a, b, mode=mode), + signal.correlate(a, b, mode=mode)) + assert_almost_equal(np.squeeze(signal.correlate2d([a], [b], + mode=mode)), + signal.correlate(a, b, mode=mode)) + + # See gh-5897 + if mode == 'valid': + assert_almost_equal(np.correlate(b, a, mode=mode), + signal.correlate(b, a, mode=mode)) + assert_almost_equal(np.squeeze(signal.correlate2d([b], [a], + mode=mode)), + signal.correlate(b, a, mode=mode)) + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, signal.correlate2d, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, signal.correlate2d, *(b, a), **{'mode': 'valid'}) + + def test_complex_input(self): + assert_equal(signal.correlate2d([[1]], [[2j]]), -2j) + assert_equal(signal.correlate2d([[2j]], [[3j]]), 6) + assert_equal(signal.correlate2d([[3j]], [[4]]), 12j) + + +class TestLFilterZI: + + def test_basic(self): + a = np.array([1.0, -1.0, 0.5]) + b = np.array([1.0, 0.0, 2.0]) + zi_expected = np.array([5.0, -1.0]) + zi = lfilter_zi(b, a) + assert_array_almost_equal(zi, zi_expected) + + def test_scale_invariance(self): + # Regression test. There was a bug in which b was not correctly + # rescaled when a[0] was nonzero. + b = np.array([2, 8, 5]) + a = np.array([1, 1, 8]) + zi1 = lfilter_zi(b, a) + zi2 = lfilter_zi(2*b, 2*a) + assert_allclose(zi2, zi1, rtol=1e-12) + + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_types(self, dtype): + b = np.zeros((8), dtype=dtype) + a = np.array([1], dtype=dtype) + assert_equal(np.real(signal.lfilter_zi(b, a)).dtype, dtype) + + +class TestFiltFilt: + filtfilt_kind = 'tf' + + def filtfilt(self, zpk, x, axis=-1, padtype='odd', padlen=None, + method='pad', irlen=None): + if self.filtfilt_kind == 'tf': + b, a = zpk2tf(*zpk) + return filtfilt(b, a, x, axis, padtype, padlen, method, irlen) + elif self.filtfilt_kind == 'sos': + sos = zpk2sos(*zpk) + return sosfiltfilt(sos, x, axis, padtype, padlen) + + def test_basic(self): + zpk = tf2zpk([1, 2, 3], [1, 2, 3]) + out = self.filtfilt(zpk, np.arange(12)) + assert_allclose(out, arange(12), atol=5.28e-11) + + def test_sine(self): + rate = 2000 + t = np.linspace(0, 1.0, rate + 1) + # A signal with low frequency and a high frequency. + xlow = np.sin(5 * 2 * np.pi * t) + xhigh = np.sin(250 * 2 * np.pi * t) + x = xlow + xhigh + + zpk = butter(8, 0.125, output='zpk') + # r is the magnitude of the largest pole. + r = np.abs(zpk[1]).max() + eps = 1e-5 + # n estimates the number of steps for the + # transient to decay by a factor of eps. + n = int(np.ceil(np.log(eps) / np.log(r))) + + # High order lowpass filter... + y = self.filtfilt(zpk, x, padlen=n) + # Result should be just xlow. + err = np.abs(y - xlow).max() + assert_(err < 1e-4) + + # A 2D case. + x2d = np.vstack([xlow, xlow + xhigh]) + y2d = self.filtfilt(zpk, x2d, padlen=n, axis=1) + assert_equal(y2d.shape, x2d.shape) + err = np.abs(y2d - xlow).max() + assert_(err < 1e-4) + + # Use the previous result to check the use of the axis keyword. + # (Regression test for ticket #1620) + y2dt = self.filtfilt(zpk, x2d.T, padlen=n, axis=0) + assert_equal(y2d, y2dt.T) + + def test_axis(self): + # Test the 'axis' keyword on a 3D array. + x = np.arange(10.0 * 11.0 * 12.0).reshape(10, 11, 12) + zpk = butter(3, 0.125, output='zpk') + y0 = self.filtfilt(zpk, x, padlen=0, axis=0) + y1 = self.filtfilt(zpk, np.swapaxes(x, 0, 1), padlen=0, axis=1) + assert_array_equal(y0, np.swapaxes(y1, 0, 1)) + y2 = self.filtfilt(zpk, np.swapaxes(x, 0, 2), padlen=0, axis=2) + assert_array_equal(y0, np.swapaxes(y2, 0, 2)) + + def test_acoeff(self): + if self.filtfilt_kind != 'tf': + return # only necessary for TF + # test for 'a' coefficient as single number + out = signal.filtfilt([.5, .5], 1, np.arange(10)) + assert_allclose(out, np.arange(10), rtol=1e-14, atol=1e-14) + + def test_gust_simple(self): + if self.filtfilt_kind != 'tf': + pytest.skip('gust only implemented for TF systems') + # The input array has length 2. The exact solution for this case + # was computed "by hand". + x = np.array([1.0, 2.0]) + b = np.array([0.5]) + a = np.array([1.0, -0.5]) + y, z1, z2 = _filtfilt_gust(b, a, x) + assert_allclose([z1[0], z2[0]], + [0.3*x[0] + 0.2*x[1], 0.2*x[0] + 0.3*x[1]]) + assert_allclose(y, [z1[0] + 0.25*z2[0] + 0.25*x[0] + 0.125*x[1], + 0.25*z1[0] + z2[0] + 0.125*x[0] + 0.25*x[1]]) + + def test_gust_scalars(self): + if self.filtfilt_kind != 'tf': + pytest.skip('gust only implemented for TF systems') + # The filter coefficients are both scalars, so the filter simply + # multiplies its input by b/a. When it is used in filtfilt, the + # factor is (b/a)**2. + x = np.arange(12) + b = 3.0 + a = 2.0 + y = filtfilt(b, a, x, method="gust") + expected = (b/a)**2 * x + assert_allclose(y, expected) + + +class TestSOSFiltFilt(TestFiltFilt): + filtfilt_kind = 'sos' + + def test_equivalence(self): + """Test equivalence between sosfiltfilt and filtfilt""" + x = np.random.RandomState(0).randn(1000) + for order in range(1, 6): + zpk = signal.butter(order, 0.35, output='zpk') + b, a = zpk2tf(*zpk) + sos = zpk2sos(*zpk) + y = filtfilt(b, a, x) + y_sos = sosfiltfilt(sos, x) + assert_allclose(y, y_sos, atol=1e-12, err_msg=f'order={order}') + + +def filtfilt_gust_opt(b, a, x): + """ + An alternative implementation of filtfilt with Gustafsson edges. + + This function computes the same result as + `scipy.signal._signaltools._filtfilt_gust`, but only 1-d arrays + are accepted. The problem is solved using `fmin` from `scipy.optimize`. + `_filtfilt_gust` is significantly faster than this implementation. + """ + def filtfilt_gust_opt_func(ics, b, a, x): + """Objective function used in filtfilt_gust_opt.""" + m = max(len(a), len(b)) - 1 + z0f = ics[:m] + z0b = ics[m:] + y_f = lfilter(b, a, x, zi=z0f)[0] + y_fb = lfilter(b, a, y_f[::-1], zi=z0b)[0][::-1] + + y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1] + y_bf = lfilter(b, a, y_b, zi=z0f)[0] + value = np.sum((y_fb - y_bf)**2) + return value + + m = max(len(a), len(b)) - 1 + zi = lfilter_zi(b, a) + ics = np.concatenate((x[:m].mean()*zi, x[-m:].mean()*zi)) + result = fmin(filtfilt_gust_opt_func, ics, args=(b, a, x), + xtol=1e-10, ftol=1e-12, + maxfun=10000, maxiter=10000, + full_output=True, disp=False) + opt, fopt, niter, funcalls, warnflag = result + if warnflag > 0: + raise RuntimeError("minimization failed in filtfilt_gust_opt: " + "warnflag=%d" % warnflag) + z0f = opt[:m] + z0b = opt[m:] + + # Apply the forward-backward filter using the computed initial + # conditions. + y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1] + y = lfilter(b, a, y_b, zi=z0f)[0] + + return y, z0f, z0b + + +def check_filtfilt_gust(b, a, shape, axis, irlen=None): + # Generate x, the data to be filtered. + np.random.seed(123) + x = np.random.randn(*shape) + + # Apply filtfilt to x. This is the main calculation to be checked. + y = filtfilt(b, a, x, axis=axis, method="gust", irlen=irlen) + + # Also call the private function so we can test the ICs. + yg, zg1, zg2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen) + + # filtfilt_gust_opt is an independent implementation that gives the + # expected result, but it only handles 1-D arrays, so use some looping + # and reshaping shenanigans to create the expected output arrays. + xx = np.swapaxes(x, axis, -1) + out_shape = xx.shape[:-1] + yo = np.empty_like(xx) + m = max(len(a), len(b)) - 1 + zo1 = np.empty(out_shape + (m,)) + zo2 = np.empty(out_shape + (m,)) + for indx in product(*[range(d) for d in out_shape]): + yo[indx], zo1[indx], zo2[indx] = filtfilt_gust_opt(b, a, xx[indx]) + yo = np.swapaxes(yo, -1, axis) + zo1 = np.swapaxes(zo1, -1, axis) + zo2 = np.swapaxes(zo2, -1, axis) + + assert_allclose(y, yo, rtol=1e-8, atol=1e-9) + assert_allclose(yg, yo, rtol=1e-8, atol=1e-9) + assert_allclose(zg1, zo1, rtol=1e-8, atol=1e-9) + assert_allclose(zg2, zo2, rtol=1e-8, atol=1e-9) + + +@pytest.mark.fail_slow(10) +def test_choose_conv_method(): + for mode in ['valid', 'same', 'full']: + for ndim in [1, 2]: + n, k, true_method = 8, 6, 'direct' + x = np.random.randn(*((n,) * ndim)) + h = np.random.randn(*((k,) * ndim)) + + method = choose_conv_method(x, h, mode=mode) + assert_equal(method, true_method) + + method_try, times = choose_conv_method(x, h, mode=mode, measure=True) + assert_(method_try in {'fft', 'direct'}) + assert_(isinstance(times, dict)) + assert_('fft' in times.keys() and 'direct' in times.keys()) + + x = np.array([2**51], dtype=np.int64) + h = x.copy() + assert_equal(choose_conv_method(x, h, mode=mode), 'direct') + + +@pytest.mark.thread_unsafe +def test_choose_conv_dtype_deprecation(): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + choose_conv_method(a, b) + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +def test_choose_conv_method_2(): + for mode in ['valid', 'same', 'full']: + x = [Decimal(3), Decimal(2)] + h = [Decimal(1), Decimal(4)] + assert_equal(choose_conv_method(x, h, mode=mode), 'direct') + + n = 10 + for not_fft_conv_supp in ["complex256", "complex192"]: + if hasattr(np, not_fft_conv_supp): + x = np.ones(n, dtype=not_fft_conv_supp) + h = x.copy() + assert_equal(choose_conv_method(x, h, mode=mode), 'direct') + + +@pytest.mark.fail_slow(10) +def test_filtfilt_gust(): + # Design a filter. + z, p, k = signal.ellip(3, 0.01, 120, 0.0875, output='zpk') + + # Find the approximate impulse response length of the filter. + eps = 1e-10 + r = np.max(np.abs(p)) + approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r))) + + np.random.seed(123) + + b, a = zpk2tf(z, p, k) + for irlen in [None, approx_impulse_len]: + signal_len = 5 * approx_impulse_len + + # 1-d test case + check_filtfilt_gust(b, a, (signal_len,), 0, irlen) + + # 3-d test case; test each axis. + for axis in range(3): + shape = [2, 2, 2] + shape[axis] = signal_len + check_filtfilt_gust(b, a, shape, axis, irlen) + + # Test case with length less than 2*approx_impulse_len. + # In this case, `filtfilt_gust` should behave the same as if + # `irlen=None` was given. + length = 2*approx_impulse_len - 50 + check_filtfilt_gust(b, a, (length,), 0, approx_impulse_len) + + +class TestDecimate: + def test_bad_args(self): + x = np.arange(12) + assert_raises(TypeError, signal.decimate, x, q=0.5, n=1) + assert_raises(TypeError, signal.decimate, x, q=2, n=0.5) + + def test_basic_IIR(self): + x = np.arange(12) + y = signal.decimate(x, 2, n=1, ftype='iir', zero_phase=False).round() + assert_array_equal(y, x[::2]) + + def test_basic_FIR(self): + x = np.arange(12) + y = signal.decimate(x, 2, n=1, ftype='fir', zero_phase=False).round() + assert_array_equal(y, x[::2]) + + def test_shape(self): + # Regression test for ticket #1480. + z = np.zeros((30, 30)) + d0 = signal.decimate(z, 2, axis=0, zero_phase=False) + assert_equal(d0.shape, (15, 30)) + d1 = signal.decimate(z, 2, axis=1, zero_phase=False) + assert_equal(d1.shape, (30, 15)) + + def test_phaseshift_FIR(self): + with suppress_warnings() as sup: + sup.filter(BadCoefficients, "Badly conditioned filter") + self._test_phaseshift(method='fir', zero_phase=False) + + def test_zero_phase_FIR(self): + with suppress_warnings() as sup: + sup.filter(BadCoefficients, "Badly conditioned filter") + self._test_phaseshift(method='fir', zero_phase=True) + + def test_phaseshift_IIR(self): + self._test_phaseshift(method='iir', zero_phase=False) + + def test_zero_phase_IIR(self): + self._test_phaseshift(method='iir', zero_phase=True) + + def _test_phaseshift(self, method, zero_phase): + rate = 120 + rates_to = [15, 20, 30, 40] # q = 8, 6, 4, 3 + + t_tot = 100 # Need to let antialiasing filters settle + t = np.arange(rate*t_tot+1) / float(rate) + + # Sinusoids at 0.8*nyquist, windowed to avoid edge artifacts + freqs = np.array(rates_to) * 0.8 / 2 + d = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t) + * signal.windows.tukey(t.size, 0.1)) + + for rate_to in rates_to: + q = rate // rate_to + t_to = np.arange(rate_to*t_tot+1) / float(rate_to) + d_tos = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t_to) + * signal.windows.tukey(t_to.size, 0.1)) + + # Set up downsampling filters, match v0.17 defaults + if method == 'fir': + n = 30 + system = signal.dlti(signal.firwin(n + 1, 1. / q, + window='hamming'), 1.) + elif method == 'iir': + n = 8 + wc = 0.8*np.pi/q + system = signal.dlti(*signal.cheby1(n, 0.05, wc/np.pi)) + + # Calculate expected phase response, as unit complex vector + if zero_phase is False: + _, h_resps = signal.freqz(system.num, system.den, + freqs/rate*2*np.pi) + h_resps /= np.abs(h_resps) + else: + h_resps = np.ones_like(freqs) + + y_resamps = signal.decimate(d.real, q, n, ftype=system, + zero_phase=zero_phase) + + # Get phase from complex inner product, like CSD + h_resamps = np.sum(d_tos.conj() * y_resamps, axis=-1) + h_resamps /= np.abs(h_resamps) + subnyq = freqs < 0.5*rate_to + + # Complex vectors should be aligned, only compare below nyquist + assert_allclose(np.angle(h_resps.conj()*h_resamps)[subnyq], 0, + atol=1e-3, rtol=1e-3) + + def test_auto_n(self): + # Test that our value of n is a reasonable choice (depends on + # the downsampling factor) + sfreq = 100. + n = 1000 + t = np.arange(n) / sfreq + # will alias for decimations (>= 15) + x = np.sqrt(2. / n) * np.sin(2 * np.pi * (sfreq / 30.) * t) + assert_allclose(np.linalg.norm(x), 1., rtol=1e-3) + x_out = signal.decimate(x, 30, ftype='fir') + assert_array_less(np.linalg.norm(x_out), 0.01) + + def test_long_float32(self): + # regression: gh-15072. With 32-bit float and either lfilter + # or filtfilt, this is numerically unstable + x = signal.decimate(np.ones(10_000, dtype=np.float32), 10) + assert not any(np.isnan(x)) + + def test_float16_upcast(self): + # float16 must be upcast to float64 + x = signal.decimate(np.ones(100, dtype=np.float16), 10) + assert x.dtype.type == np.float64 + + def test_complex_iir_dlti(self): + # regression: gh-17845 + # centre frequency for filter [Hz] + fcentre = 50 + # filter passband width [Hz] + fwidth = 5 + # sample rate [Hz] + fs = 1e3 + + z, p, k = signal.butter(2, 2*np.pi*fwidth/2, output='zpk', fs=fs) + z = z.astype(complex) * np.exp(2j * np.pi * fcentre/fs) + p = p.astype(complex) * np.exp(2j * np.pi * fcentre/fs) + system = signal.dlti(z, p, k) + + t = np.arange(200) / fs + + # input + u = (np.exp(2j * np.pi * fcentre * t) + + 0.5 * np.exp(-2j * np.pi * fcentre * t)) + + ynzp = signal.decimate(u, 2, ftype=system, zero_phase=False) + ynzpref = signal.lfilter(*signal.zpk2tf(z, p, k), + u)[::2] + + assert_equal(ynzp, ynzpref) + + yzp = signal.decimate(u, 2, ftype=system, zero_phase=True) + yzpref = signal.filtfilt(*signal.zpk2tf(z, p, k), + u)[::2] + + assert_allclose(yzp, yzpref, rtol=1e-10, atol=1e-13) + + def test_complex_fir_dlti(self): + # centre frequency for filter [Hz] + fcentre = 50 + # filter passband width [Hz] + fwidth = 5 + # sample rate [Hz] + fs = 1e3 + numtaps = 20 + + # FIR filter about 0Hz + bbase = signal.firwin(numtaps, fwidth/2, fs=fs) + + # rotate these to desired frequency + zbase = np.roots(bbase) + zrot = zbase * np.exp(2j * np.pi * fcentre/fs) + # FIR filter about 50Hz, maintaining passband gain of 0dB + bz = bbase[0] * np.poly(zrot) + + system = signal.dlti(bz, 1) + + t = np.arange(200) / fs + + # input + u = (np.exp(2j * np.pi * fcentre * t) + + 0.5 * np.exp(-2j * np.pi * fcentre * t)) + + ynzp = signal.decimate(u, 2, ftype=system, zero_phase=False) + ynzpref = signal.upfirdn(bz, u, up=1, down=2)[:100] + + assert_equal(ynzp, ynzpref) + + yzp = signal.decimate(u, 2, ftype=system, zero_phase=True) + yzpref = signal.resample_poly(u, 1, 2, window=bz) + + assert_equal(yzp, yzpref) + + +class TestHilbert: + + def test_bad_args(self): + x = np.array([1.0 + 0.0j]) + assert_raises(ValueError, hilbert, x) + x = np.arange(8.0) + assert_raises(ValueError, hilbert, x, N=0) + + def test_hilbert_theoretical(self): + # test cases by Ariel Rokem + decimal = 14 + + pi = np.pi + t = np.arange(0, 2 * pi, pi / 256) + a0 = np.sin(t) + a1 = np.cos(t) + a2 = np.sin(2 * t) + a3 = np.cos(2 * t) + a = np.vstack([a0, a1, a2, a3]) + + h = hilbert(a) + h_abs = np.abs(h) + h_angle = np.angle(h) + h_real = np.real(h) + + # The real part should be equal to the original signals: + assert_almost_equal(h_real, a, decimal) + # The absolute value should be one everywhere, for this input: + assert_almost_equal(h_abs, np.ones(a.shape), decimal) + # For the 'slow' sine - the phase should go from -pi/2 to pi/2 in + # the first 256 bins: + assert_almost_equal(h_angle[0, :256], + np.arange(-pi / 2, pi / 2, pi / 256), + decimal) + # For the 'slow' cosine - the phase should go from 0 to pi in the + # same interval: + assert_almost_equal( + h_angle[1, :256], np.arange(0, pi, pi / 256), decimal) + # The 'fast' sine should make this phase transition in half the time: + assert_almost_equal(h_angle[2, :128], + np.arange(-pi / 2, pi / 2, pi / 128), + decimal) + # Ditto for the 'fast' cosine: + assert_almost_equal( + h_angle[3, :128], np.arange(0, pi, pi / 128), decimal) + + # The imaginary part of hilbert(cos(t)) = sin(t) Wikipedia + assert_almost_equal(h[1].imag, a0, decimal) + + def test_hilbert_axisN(self): + # tests for axis and N arguments + a = np.arange(18).reshape(3, 6) + # test axis + aa = hilbert(a, axis=-1) + assert_equal(hilbert(a.T, axis=0), aa.T) + # test 1d + assert_almost_equal(hilbert(a[0]), aa[0], 14) + + # test N + aan = hilbert(a, N=20, axis=-1) + assert_equal(aan.shape, [3, 20]) + assert_equal(hilbert(a.T, N=20, axis=0).shape, [20, 3]) + # the next test is just a regression test, + # no idea whether numbers make sense + a0hilb = np.array([0.000000000000000e+00 - 1.72015830311905j, + 1.000000000000000e+00 - 2.047794505137069j, + 1.999999999999999e+00 - 2.244055555687583j, + 3.000000000000000e+00 - 1.262750302935009j, + 4.000000000000000e+00 - 1.066489252384493j, + 5.000000000000000e+00 + 2.918022706971047j, + 8.881784197001253e-17 + 3.845658908989067j, + -9.444121133484362e-17 + 0.985044202202061j, + -1.776356839400251e-16 + 1.332257797702019j, + -3.996802888650564e-16 + 0.501905089898885j, + 1.332267629550188e-16 + 0.668696078880782j, + -1.192678053963799e-16 + 0.235487067862679j, + -1.776356839400251e-16 + 0.286439612812121j, + 3.108624468950438e-16 + 0.031676888064907j, + 1.332267629550188e-16 - 0.019275656884536j, + -2.360035624836702e-16 - 0.1652588660287j, + 0.000000000000000e+00 - 0.332049855010597j, + 3.552713678800501e-16 - 0.403810179797771j, + 8.881784197001253e-17 - 0.751023775297729j, + 9.444121133484362e-17 - 0.79252210110103j]) + assert_almost_equal(aan[0], a0hilb, 14, 'N regression') + + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_hilbert_types(self, dtype): + in_typed = np.zeros(8, dtype=dtype) + assert_equal(np.real(signal.hilbert(in_typed)).dtype, dtype) + + +class TestHilbert2: + + def test_bad_args(self): + # x must be real. + x = np.array([[1.0 + 0.0j]]) + assert_raises(ValueError, hilbert2, x) + + # x must be rank 2. + x = np.arange(24).reshape(2, 3, 4) + assert_raises(ValueError, hilbert2, x) + + # Bad value for N. + x = np.arange(16).reshape(4, 4) + assert_raises(ValueError, hilbert2, x, N=0) + assert_raises(ValueError, hilbert2, x, N=(2, 0)) + assert_raises(ValueError, hilbert2, x, N=(2,)) + + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_hilbert2_types(self, dtype): + in_typed = np.zeros((2, 32), dtype=dtype) + assert_equal(np.real(signal.hilbert2(in_typed)).dtype, dtype) + + +class TestEnvelope: + """Unit tests for function `._signaltools.envelope()`. """ + + @staticmethod + def assert_close(actual, desired, msg): + """Little helper to compare to arrays with proper tolerances""" + xp_assert_close(actual, desired, atol=1e-12, rtol=1e-12, err_msg=msg) + + def test_envelope_invalid_parameters(self): + """For `envelope()` Raise all exceptions that are used to verify function + parameters. """ + with pytest.raises(ValueError, + match=r"Invalid parameter axis=2 for z.shape=.*"): + envelope(np.ones(3), axis=2) + with pytest.raises(ValueError, + match=r"z.shape\[axis\] not > 0 for z.shape=.*"): + envelope(np.ones((3, 0)), axis=1) + for bp_in in [(0, 1, 2), (0, 2.), (None, 2.)]: + ts = ', '.join(map(str, bp_in)) + with pytest.raises(ValueError, + match=rf"bp_in=\({ts}\) isn't a 2-tuple of.*"): + # noinspection PyTypeChecker + envelope(np.ones(4), bp_in=bp_in) + with pytest.raises(ValueError, + match="n_out=10.0 is not a positive integer or.*"): + # noinspection PyTypeChecker + envelope(np.ones(4), n_out=10.) + for bp_in in [(-1, 3), (1, 1), (0, 10)]: + with pytest.raises(ValueError, + match=r"`-n//2 <= bp_in\[0\] < bp_in\[1\] <=.*"): + envelope(np.ones(4), bp_in=bp_in) + with pytest.raises(ValueError, match="residual='undefined' not in .*"): + # noinspection PyTypeChecker + envelope(np.ones(4), residual='undefined') + + def test_envelope_verify_parameters(self): + """Ensure that the various parametrizations produce compatible results. """ + Z, Zr_a = [4, 2, 2, 3, 0], [4, 0, 0, 6, 0, 0, 0, 0] + z = sp_fft.irfft(Z) + n = len(z) + + # the reference envelope: + ze2_0, zr_0 = envelope(z, (1, 3), residual='all', squared=True) + self.assert_close(sp_fft.rfft(ze2_0), np.array([4, 2, 0, 0, 0]).astype(complex), + msg="Envelope calculation error") + self.assert_close(sp_fft.rfft(zr_0), np.array([4, 0, 0, 3, 0]).astype(complex), + msg="Residual calculation error") + + ze_1, zr_1 = envelope(z, (1, 3), residual='all', squared=False) + self.assert_close(ze_1**2, ze2_0, + msg="Unsquared versus Squared envelope calculation error") + self.assert_close(zr_1, zr_0, + msg="Unsquared versus Squared residual calculation error") + + ze2_2, zr_2 = envelope(z, (1, 3), residual='all', squared=True, n_out=3*n) + self.assert_close(ze2_2[::3], ze2_0, + msg="3x up-sampled envelope calculation error") + self.assert_close(zr_2[::3], zr_0, + msg="3x up-sampled residual calculation error") + + ze2_3, zr_3 = envelope(z, (1, 3), residual='lowpass', squared=True) + self.assert_close(ze2_3, ze2_0, + msg="`residual='lowpass'` envelope calculation error") + self.assert_close(sp_fft.rfft(zr_3), np.array([4, 0, 0, 0, 0]).astype(complex), + msg="`residual='lowpass'` residual calculation error") + + ze2_4 = envelope(z, (1, 3), residual=None, squared=True) + self.assert_close(ze2_4, ze2_0, + msg="`residual=None` envelope calculation error") + + # compare complex analytic signal to real version + Z_a = np.copy(Z) + Z_a[1:] *= 2 + z_a = sp_fft.ifft(Z_a, n=n) # analytic signal of Z + self.assert_close(z_a.real, z, + msg="Reference analytic signal error") + ze2_a, zr_a = envelope(z_a, (1, 3), residual='all', squared=True) + self.assert_close(ze2_a, ze2_0.astype(complex), # dtypes must match + msg="Complex envelope calculation error") + self.assert_close(sp_fft.fft(zr_a), np.array(Zr_a).astype(complex), + msg="Complex residual calculation error") + + @pytest.mark.parametrize( + " Z, bp_in, Ze2_desired, Zr_desired", + [([1, 0, 2, 2, 0], (1, None), [4, 2, 0, 0, 0], [1, 0, 0, 0, 0]), + ([4, 0, 2, 0, 0], (0, None), [4, 0, 2, 0, 0], [0, 0, 0, 0, 0]), + ([4, 0, 0, 2, 0], (None, None), [4, 0, 0, 2, 0], [0, 0, 0, 0, 0]), + ([0, 0, 2, 2, 0], (1, 3), [2, 0, 0, 0, 0], [0, 0, 0, 2, 0]), + ([4, 0, 2, 2, 0], (-3, 3), [4, 0, 2, 0, 0], [0, 0, 0, 2, 0]), + ([4, 0, 3, 4, 0], (None, 1), [2, 0, 0, 0, 0], [0, 0, 3, 4, 0]), + ([4, 0, 3, 4, 0], (None, 0), [0, 0, 0, 0, 0], [4, 0, 3, 4, 0])]) + def test_envelope_real_signals(self, Z, bp_in, Ze2_desired, Zr_desired): + """Test envelope calculation with real-valued test signals. + + The comparisons are performed in the Fourier space, since it makes evaluating + the bandpass filter behavior straightforward. Note that also the squared + envelope can be easily calculated by hand, if one recalls that coefficients of + a complex-valued Fourier series representing the signal can be directly + determined by an FFT and that the absolute square of a Fourier series is again + a Fourier series. + """ + z = sp_fft.irfft(Z) + ze2, zr = envelope(z, bp_in, residual='all', squared=True) + ze2_lp, zr_lp = envelope(z, bp_in, residual='lowpass', squared=True) + Ze2, Zr, Ze2_lp, Zr_lp = (sp_fft.rfft(z_) for z_ in (ze2, zr, ze2_lp, zr_lp)) + + Ze2_desired = np.array(Ze2_desired).astype(complex) + Zr_desired = np.array(Zr_desired).astype(complex) + self.assert_close(Ze2, Ze2_desired, + msg="Envelope calculation error (residual='all')") + self.assert_close(Zr, Zr_desired, + msg="Residual calculation error (residual='all')") + + if bp_in[1] is not None: + Zr_desired[bp_in[1]:] = 0 + self.assert_close(Ze2_lp, Ze2_desired, + msg="Envelope calculation error (residual='lowpass')") + self.assert_close(Zr_lp, Zr_desired, + msg="Residual calculation error (residual='lowpass')") + + @pytest.mark.parametrize( + " Z, bp_in, Ze2_desired, Zr_desired", + [([0, 5, 0, 5, 0], (None, None), [5, 0, 10, 0, 5], [0, 0, 0, 0, 0]), + ([1, 5, 0, 5, 2], (-1, 2), [5, 0, 10, 0, 5], [1, 0, 0, 0, 2]), + ([1, 2, 6, 0, 6, 3], (-1, 2), [0, 6, 0, 12, 0, 6], [1, 2, 0, 0, 0, 3]) + ]) + def test_envelope_complex_signals(self, Z, bp_in, Ze2_desired, Zr_desired): + """Test envelope calculation with complex-valued test signals. + + We only need to test for the complex envelope here, since the ``Nones``s in the + bandpass filter were already tested in the previous test. + """ + z = sp_fft.ifft(sp_fft.ifftshift(Z)) + ze2, zr = envelope(z, bp_in, residual='all', squared=True) + Ze2, Zr = (sp_fft.fftshift(sp_fft.fft(z_)) for z_ in (ze2, zr)) + + self.assert_close(Ze2, np.array(Ze2_desired).astype(complex), + msg="Envelope calculation error") + self.assert_close(Zr, np.array(Zr_desired).astype(complex), + msg="Residual calculation error") + + def test_envelope_verify_axis_parameter(self): + """Test for multi-channel envelope calculations. """ + z = sp_fft.irfft([[1, 0, 2, 2, 0], [7, 0, 4, 4, 0]]) + Ze2_desired = np.array([[4, 2, 0, 0, 0], [16, 8, 0, 0, 0]], + dtype=complex) + Zr_desired = np.array([[1, 0, 0, 0, 0], [7, 0, 0, 0, 0]], dtype=complex) + + ze2, zr = envelope(z, squared=True, axis=1) + ye2T, yrT = envelope(z.T, squared=True, axis=0) + Ze2, Ye2, Zr, Yr = (sp_fft.rfft(z_) for z_ in (ze2, ye2T.T, zr, yrT.T)) + + self.assert_close(Ze2, Ze2_desired, msg="2d envelope calculation error") + self.assert_close(Zr, Zr_desired, msg="2d residual calculation error") + self.assert_close(Ye2, Ze2_desired, msg="Transposed 2d envelope calc. error") + self.assert_close(Yr, Zr_desired, msg="Transposed 2d residual calc. error") + + def test_envelope_verify_axis_parameter_complex(self): + """Test for multi-channel envelope calculations with complex values. """ + z = sp_fft.ifft(sp_fft.ifftshift([[1, 5, 0, 5, 2], [1, 10, 0, 10, 2]], axes=1)) + Ze2_des = np.array([[5, 0, 10, 0, 5], [20, 0, 40, 0, 20],], + dtype=complex) + Zr_des = np.array([[1, 0, 0, 0, 2], [1, 0, 0, 0, 2]], dtype=complex) + + kw = dict(bp_in=(-1, 2), residual='all', squared=True) + ze2, zr = envelope(z, axis=1, **kw) + ye2T, yrT = envelope(z.T, axis=0, **kw) + Ze2, Ye2, Zr, Yr = (sp_fft.fftshift(sp_fft.fft(z_), axes=1) + for z_ in (ze2, ye2T.T, zr, yrT.T)) + + self.assert_close(Ze2, Ze2_des, msg="2d envelope calculation error") + self.assert_close(Zr, Zr_des, msg="2d residual calculation error") + self.assert_close(Ye2, Ze2_des, msg="Transposed 2d envelope calc. error") + self.assert_close(Yr, Zr_des, msg="Transposed 2d residual calc. error") + + @pytest.mark.parametrize('X', [[4, 0, 0, 1, 2], [4, 0, 0, 2, 1, 2]]) + def test_compare_envelope_hilbert(self, X): + """Compare output of `envelope()` and `hilbert()`. """ + x = sp_fft.irfft(X) + e_hil = np.abs(hilbert(x)) + e_env = envelope(x, (None, None), residual=None) + self.assert_close(e_hil, e_env, msg="Hilbert-Envelope comparison error") + + +class TestPartialFractionExpansion: + @staticmethod + def assert_rp_almost_equal(r, p, r_true, p_true, decimal=7): + r_true = np.asarray(r_true) + p_true = np.asarray(p_true) + + distance = np.hypot(abs(p[:, None] - p_true), + abs(r[:, None] - r_true)) + + rows, cols = linear_sum_assignment(distance) + assert_almost_equal(p[rows], p_true[cols], decimal=decimal) + assert_almost_equal(r[rows], r_true[cols], decimal=decimal) + + def test_compute_factors(self): + factors, poly = _compute_factors([1, 2, 3], [3, 2, 1]) + assert_equal(len(factors), 3) + assert_almost_equal(factors[0], np.poly([2, 2, 3])) + assert_almost_equal(factors[1], np.poly([1, 1, 1, 3])) + assert_almost_equal(factors[2], np.poly([1, 1, 1, 2, 2])) + assert_almost_equal(poly, np.poly([1, 1, 1, 2, 2, 3])) + + factors, poly = _compute_factors([1, 2, 3], [3, 2, 1], + include_powers=True) + assert_equal(len(factors), 6) + assert_almost_equal(factors[0], np.poly([1, 1, 2, 2, 3])) + assert_almost_equal(factors[1], np.poly([1, 2, 2, 3])) + assert_almost_equal(factors[2], np.poly([2, 2, 3])) + assert_almost_equal(factors[3], np.poly([1, 1, 1, 2, 3])) + assert_almost_equal(factors[4], np.poly([1, 1, 1, 3])) + assert_almost_equal(factors[5], np.poly([1, 1, 1, 2, 2])) + assert_almost_equal(poly, np.poly([1, 1, 1, 2, 2, 3])) + + def test_group_poles(self): + unique, multiplicity = _group_poles( + [1.0, 1.001, 1.003, 2.0, 2.003, 3.0], 0.1, 'min') + assert_equal(unique, [1.0, 2.0, 3.0]) + assert_equal(multiplicity, [3, 2, 1]) + + def test_residue_general(self): + # Test are taken from issue #4464, note that poles in scipy are + # in increasing by absolute value order, opposite to MATLAB. + r, p, k = residue([5, 3, -2, 7], [-4, 0, 8, 3]) + assert_almost_equal(r, [1.3320, -0.6653, -1.4167], decimal=4) + assert_almost_equal(p, [-0.4093, -1.1644, 1.5737], decimal=4) + assert_almost_equal(k, [-1.2500], decimal=4) + + r, p, k = residue([-4, 8], [1, 6, 8]) + assert_almost_equal(r, [8, -12]) + assert_almost_equal(p, [-2, -4]) + assert_equal(k.size, 0) + + r, p, k = residue([4, 1], [1, -1, -2]) + assert_almost_equal(r, [1, 3]) + assert_almost_equal(p, [-1, 2]) + assert_equal(k.size, 0) + + r, p, k = residue([4, 3], [2, -3.4, 1.98, -0.406]) + self.assert_rp_almost_equal( + r, p, [-18.125 - 13.125j, -18.125 + 13.125j, 36.25], + [0.5 - 0.2j, 0.5 + 0.2j, 0.7]) + assert_equal(k.size, 0) + + r, p, k = residue([2, 1], [1, 5, 8, 4]) + self.assert_rp_almost_equal(r, p, [-1, 1, 3], [-1, -2, -2]) + assert_equal(k.size, 0) + + r, p, k = residue([3, -1.1, 0.88, -2.396, 1.348], + [1, -0.7, -0.14, 0.048]) + assert_almost_equal(r, [-3, 4, 1]) + assert_almost_equal(p, [0.2, -0.3, 0.8]) + assert_almost_equal(k, [3, 1]) + + r, p, k = residue([1], [1, 2, -3]) + assert_almost_equal(r, [0.25, -0.25]) + assert_almost_equal(p, [1, -3]) + assert_equal(k.size, 0) + + r, p, k = residue([1, 0, -5], [1, 0, 0, 0, -1]) + self.assert_rp_almost_equal(r, p, + [1, 1.5j, -1.5j, -1], [-1, -1j, 1j, 1]) + assert_equal(k.size, 0) + + r, p, k = residue([3, 8, 6], [1, 3, 3, 1]) + self.assert_rp_almost_equal(r, p, [1, 2, 3], [-1, -1, -1]) + assert_equal(k.size, 0) + + r, p, k = residue([3, -1], [1, -3, 2]) + assert_almost_equal(r, [-2, 5]) + assert_almost_equal(p, [1, 2]) + assert_equal(k.size, 0) + + r, p, k = residue([2, 3, -1], [1, -3, 2]) + assert_almost_equal(r, [-4, 13]) + assert_almost_equal(p, [1, 2]) + assert_almost_equal(k, [2]) + + r, p, k = residue([7, 2, 3, -1], [1, -3, 2]) + assert_almost_equal(r, [-11, 69]) + assert_almost_equal(p, [1, 2]) + assert_almost_equal(k, [7, 23]) + + r, p, k = residue([2, 3, -1], [1, -3, 4, -2]) + self.assert_rp_almost_equal(r, p, [4, -1 + 3.5j, -1 - 3.5j], + [1, 1 - 1j, 1 + 1j]) + assert_almost_equal(k.size, 0) + + def test_residue_leading_zeros(self): + # Leading zeros in numerator or denominator must not affect the answer. + r0, p0, k0 = residue([5, 3, -2, 7], [-4, 0, 8, 3]) + r1, p1, k1 = residue([0, 5, 3, -2, 7], [-4, 0, 8, 3]) + r2, p2, k2 = residue([5, 3, -2, 7], [0, -4, 0, 8, 3]) + r3, p3, k3 = residue([0, 0, 5, 3, -2, 7], [0, 0, 0, -4, 0, 8, 3]) + assert_almost_equal(r0, r1) + assert_almost_equal(r0, r2) + assert_almost_equal(r0, r3) + assert_almost_equal(p0, p1) + assert_almost_equal(p0, p2) + assert_almost_equal(p0, p3) + assert_almost_equal(k0, k1) + assert_almost_equal(k0, k2) + assert_almost_equal(k0, k3) + + def test_resiude_degenerate(self): + # Several tests for zero numerator and denominator. + r, p, k = residue([0, 0], [1, 6, 8]) + assert_almost_equal(r, [0, 0]) + assert_almost_equal(p, [-2, -4]) + assert_equal(k.size, 0) + + r, p, k = residue(0, 1) + assert_equal(r.size, 0) + assert_equal(p.size, 0) + assert_equal(k.size, 0) + + with pytest.raises(ValueError, match="Denominator `a` is zero."): + residue(1, 0) + + def test_residuez_general(self): + r, p, k = residuez([1, 6, 6, 2], [1, -(2 + 1j), (1 + 2j), -1j]) + self.assert_rp_almost_equal(r, p, [-2+2.5j, 7.5+7.5j, -4.5-12j], + [1j, 1, 1]) + assert_almost_equal(k, [2j]) + + r, p, k = residuez([1, 2, 1], [1, -1, 0.3561]) + self.assert_rp_almost_equal(r, p, + [-0.9041 - 5.9928j, -0.9041 + 5.9928j], + [0.5 + 0.3257j, 0.5 - 0.3257j], + decimal=4) + assert_almost_equal(k, [2.8082], decimal=4) + + r, p, k = residuez([1, -1], [1, -5, 6]) + assert_almost_equal(r, [-1, 2]) + assert_almost_equal(p, [2, 3]) + assert_equal(k.size, 0) + + r, p, k = residuez([2, 3, 4], [1, 3, 3, 1]) + self.assert_rp_almost_equal(r, p, [4, -5, 3], [-1, -1, -1]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, -10, -4, 4], [2, -2, -4]) + assert_almost_equal(r, [0.5, -1.5]) + assert_almost_equal(p, [-1, 2]) + assert_almost_equal(k, [1.5, -1]) + + r, p, k = residuez([18], [18, 3, -4, -1]) + self.assert_rp_almost_equal(r, p, + [0.36, 0.24, 0.4], [0.5, -1/3, -1/3]) + assert_equal(k.size, 0) + + r, p, k = residuez([2, 3], np.polymul([1, -1/2], [1, 1/4])) + assert_almost_equal(r, [-10/3, 16/3]) + assert_almost_equal(p, [-0.25, 0.5]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, -2, 1], [1, -1]) + assert_almost_equal(r, [0]) + assert_almost_equal(p, [1]) + assert_almost_equal(k, [1, -1]) + + r, p, k = residuez(1, [1, -1j]) + assert_almost_equal(r, [1]) + assert_almost_equal(p, [1j]) + assert_equal(k.size, 0) + + r, p, k = residuez(1, [1, -1, 0.25]) + assert_almost_equal(r, [0, 1]) + assert_almost_equal(p, [0.5, 0.5]) + assert_equal(k.size, 0) + + r, p, k = residuez(1, [1, -0.75, .125]) + assert_almost_equal(r, [-1, 2]) + assert_almost_equal(p, [0.25, 0.5]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, 6, 2], [1, -2, 1]) + assert_almost_equal(r, [-10, 9]) + assert_almost_equal(p, [1, 1]) + assert_almost_equal(k, [2]) + + r, p, k = residuez([6, 2], [1, -2, 1]) + assert_almost_equal(r, [-2, 8]) + assert_almost_equal(p, [1, 1]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, 6, 6, 2], [1, -2, 1]) + assert_almost_equal(r, [-24, 15]) + assert_almost_equal(p, [1, 1]) + assert_almost_equal(k, [10, 2]) + + r, p, k = residuez([1, 0, 1], [1, 0, 0, 0, 0, -1]) + self.assert_rp_almost_equal(r, p, + [0.2618 + 0.1902j, 0.2618 - 0.1902j, + 0.4, 0.0382 - 0.1176j, 0.0382 + 0.1176j], + [-0.8090 + 0.5878j, -0.8090 - 0.5878j, + 1.0, 0.3090 + 0.9511j, 0.3090 - 0.9511j], + decimal=4) + assert_equal(k.size, 0) + + def test_residuez_trailing_zeros(self): + # Trailing zeros in numerator or denominator must not affect the + # answer. + r0, p0, k0 = residuez([5, 3, -2, 7], [-4, 0, 8, 3]) + r1, p1, k1 = residuez([5, 3, -2, 7, 0], [-4, 0, 8, 3]) + r2, p2, k2 = residuez([5, 3, -2, 7], [-4, 0, 8, 3, 0]) + r3, p3, k3 = residuez([5, 3, -2, 7, 0, 0], [-4, 0, 8, 3, 0, 0, 0]) + assert_almost_equal(r0, r1) + assert_almost_equal(r0, r2) + assert_almost_equal(r0, r3) + assert_almost_equal(p0, p1) + assert_almost_equal(p0, p2) + assert_almost_equal(p0, p3) + assert_almost_equal(k0, k1) + assert_almost_equal(k0, k2) + assert_almost_equal(k0, k3) + + def test_residuez_degenerate(self): + r, p, k = residuez([0, 0], [1, 6, 8]) + assert_almost_equal(r, [0, 0]) + assert_almost_equal(p, [-2, -4]) + assert_equal(k.size, 0) + + r, p, k = residuez(0, 1) + assert_equal(r.size, 0) + assert_equal(p.size, 0) + assert_equal(k.size, 0) + + with pytest.raises(ValueError, match="Denominator `a` is zero."): + residuez(1, 0) + + with pytest.raises(ValueError, + match="First coefficient of determinant `a` must " + "be non-zero."): + residuez(1, [0, 1, 2, 3]) + + def test_inverse_unique_roots_different_rtypes(self): + # This test was inspired by GitHub issue 2496. + r = [3 / 10, -1 / 6, -2 / 15] + p = [0, -2, -5] + k = [] + b_expected = [0, 1, 3] + a_expected = [1, 7, 10, 0] + + # With the default tolerance, the rtype does not matter + # for this example. + for rtype in ('avg', 'mean', 'min', 'minimum', 'max', 'maximum'): + b, a = invres(r, p, k, rtype=rtype) + assert_allclose(b, b_expected) + assert_allclose(a, a_expected) + + b, a = invresz(r, p, k, rtype=rtype) + assert_allclose(b, b_expected) + assert_allclose(a, a_expected) + + def test_inverse_repeated_roots_different_rtypes(self): + r = [3 / 20, -7 / 36, -1 / 6, 2 / 45] + p = [0, -2, -2, -5] + k = [] + b_expected = [0, 0, 1, 3] + b_expected_z = [-1/6, -2/3, 11/6, 3] + a_expected = [1, 9, 24, 20, 0] + + for rtype in ('avg', 'mean', 'min', 'minimum', 'max', 'maximum'): + b, a = invres(r, p, k, rtype=rtype) + assert_allclose(b, b_expected, atol=1e-14) + assert_allclose(a, a_expected) + + b, a = invresz(r, p, k, rtype=rtype) + assert_allclose(b, b_expected_z, atol=1e-14) + assert_allclose(a, a_expected) + + def test_inverse_bad_rtype(self): + r = [3 / 20, -7 / 36, -1 / 6, 2 / 45] + p = [0, -2, -2, -5] + k = [] + with pytest.raises(ValueError, match="`rtype` must be one of"): + invres(r, p, k, rtype='median') + with pytest.raises(ValueError, match="`rtype` must be one of"): + invresz(r, p, k, rtype='median') + + def test_invresz_one_coefficient_bug(self): + # Regression test for issue in gh-4646. + r = [1] + p = [2] + k = [0] + b, a = invresz(r, p, k) + assert_allclose(b, [1.0]) + assert_allclose(a, [1.0, -2.0]) + + def test_invres(self): + b, a = invres([1], [1], []) + assert_almost_equal(b, [1]) + assert_almost_equal(a, [1, -1]) + + b, a = invres([1 - 1j, 2, 0.5 - 3j], [1, 0.5j, 1 + 1j], []) + assert_almost_equal(b, [3.5 - 4j, -8.5 + 0.25j, 3.5 + 3.25j]) + assert_almost_equal(a, [1, -2 - 1.5j, 0.5 + 2j, 0.5 - 0.5j]) + + b, a = invres([0.5, 1], [1 - 1j, 2 + 2j], [1, 2, 3]) + assert_almost_equal(b, [1, -1 - 1j, 1 - 2j, 0.5 - 3j, 10]) + assert_almost_equal(a, [1, -3 - 1j, 4]) + + b, a = invres([-1, 2, 1j, 3 - 1j, 4, -2], + [-1, 2 - 1j, 2 - 1j, 3, 3, 3], []) + assert_almost_equal(b, [4 - 1j, -28 + 16j, 40 - 62j, 100 + 24j, + -292 + 219j, 192 - 268j]) + assert_almost_equal(a, [1, -12 + 2j, 53 - 20j, -96 + 68j, 27 - 72j, + 108 - 54j, -81 + 108j]) + + b, a = invres([-1, 1j], [1, 1], [1, 2]) + assert_almost_equal(b, [1, 0, -4, 3 + 1j]) + assert_almost_equal(a, [1, -2, 1]) + + def test_invresz(self): + b, a = invresz([1], [1], []) + assert_almost_equal(b, [1]) + assert_almost_equal(a, [1, -1]) + + b, a = invresz([1 - 1j, 2, 0.5 - 3j], [1, 0.5j, 1 + 1j], []) + assert_almost_equal(b, [3.5 - 4j, -8.5 + 0.25j, 3.5 + 3.25j]) + assert_almost_equal(a, [1, -2 - 1.5j, 0.5 + 2j, 0.5 - 0.5j]) + + b, a = invresz([0.5, 1], [1 - 1j, 2 + 2j], [1, 2, 3]) + assert_almost_equal(b, [2.5, -3 - 1j, 1 - 2j, -1 - 3j, 12]) + assert_almost_equal(a, [1, -3 - 1j, 4]) + + b, a = invresz([-1, 2, 1j, 3 - 1j, 4, -2], + [-1, 2 - 1j, 2 - 1j, 3, 3, 3], []) + assert_almost_equal(b, [6, -50 + 11j, 100 - 72j, 80 + 58j, + -354 + 228j, 234 - 297j]) + assert_almost_equal(a, [1, -12 + 2j, 53 - 20j, -96 + 68j, 27 - 72j, + 108 - 54j, -81 + 108j]) + + b, a = invresz([-1, 1j], [1, 1], [1, 2]) + assert_almost_equal(b, [1j, 1, -3, 2]) + assert_almost_equal(a, [1, -2, 1]) + + def test_inverse_scalar_arguments(self): + b, a = invres(1, 1, 1) + assert_almost_equal(b, [1, 0]) + assert_almost_equal(a, [1, -1]) + + b, a = invresz(1, 1, 1) + assert_almost_equal(b, [2, -1]) + assert_almost_equal(a, [1, -1]) + + +class TestVectorstrength: + + def test_single_1dperiod(self): + events = np.array([.5]) + period = 5. + targ_strength = 1. + targ_phase = .1 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_single_2dperiod(self): + events = np.array([.5]) + period = [1, 2, 5.] + targ_strength = [1.] * 3 + targ_phase = np.array([.5, .25, .1]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_array_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_equal_1dperiod(self): + events = np.array([.25, .25, .25, .25, .25, .25]) + period = 2 + targ_strength = 1. + targ_phase = .125 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_equal_2dperiod(self): + events = np.array([.25, .25, .25, .25, .25, .25]) + period = [1, 2, ] + targ_strength = [1.] * 2 + targ_phase = np.array([.25, .125]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_spaced_1dperiod(self): + events = np.array([.1, 1.1, 2.1, 4.1, 10.1]) + period = 1 + targ_strength = 1. + targ_phase = .1 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_spaced_2dperiod(self): + events = np.array([.1, 1.1, 2.1, 4.1, 10.1]) + period = [1, .5] + targ_strength = [1.] * 2 + targ_phase = np.array([.1, .2]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_partial_1dperiod(self): + events = np.array([.25, .5, .75]) + period = 1 + targ_strength = 1. / 3. + targ_phase = .5 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_partial_2dperiod(self): + events = np.array([.25, .5, .75]) + period = [1., 1., 1., 1.] + targ_strength = [1. / 3.] * 4 + targ_phase = np.array([.5, .5, .5, .5]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_opposite_1dperiod(self): + events = np.array([0, .25, .5, .75]) + period = 1. + targ_strength = 0 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + + def test_opposite_2dperiod(self): + events = np.array([0, .25, .5, .75]) + period = [1.] * 10 + targ_strength = [0.] * 10 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + + def test_2d_events_ValueError(self): + events = np.array([[1, 2]]) + period = 1. + assert_raises(ValueError, vectorstrength, events, period) + + def test_2d_period_ValueError(self): + events = 1. + period = np.array([[1]]) + assert_raises(ValueError, vectorstrength, events, period) + + def test_zero_period_ValueError(self): + events = 1. + period = 0 + assert_raises(ValueError, vectorstrength, events, period) + + def test_negative_period_ValueError(self): + events = 1. + period = -1 + assert_raises(ValueError, vectorstrength, events, period) + + +def assert_allclose_cast(actual, desired, rtol=1e-7, atol=0): + """Wrap assert_allclose while casting object arrays.""" + if actual.dtype.kind == 'O': + dtype = np.array(actual.flat[0]).dtype + actual, desired = actual.astype(dtype), desired.astype(dtype) + assert_allclose(actual, desired, rtol, atol) + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +@pytest.mark.parametrize('func', (sosfilt, lfilter)) +def test_nonnumeric_dtypes(func): + x = [Decimal(1), Decimal(2), Decimal(3)] + b = [Decimal(1), Decimal(2), Decimal(3)] + a = [Decimal(1), Decimal(2), Decimal(3)] + x = np.array(x) + assert x.dtype.kind == 'O' + desired = lfilter(np.array(b, float), np.array(a, float), x.astype(float)) + if func is sosfilt: + actual = sosfilt([b + a], x) + else: + actual = lfilter(b, a, x) + assert all(isinstance(x, Decimal) for x in actual) + assert_allclose(actual.astype(float), desired.astype(float)) + # Degenerate cases + if func is lfilter: + args = [1., 1.] + else: + args = [tf2sos(1., 1.)] + + with pytest.raises(ValueError, match='must be at least 1-D'): + func(*args, x=1.) + + +@pytest.mark.parametrize('dt', 'fdFD') +class TestSOSFilt: + + # The test_rank* tests are pulled from _TestLinearFilter + def test_rank1(self, dt): + x = np.linspace(0, 5, 6).astype(dt) + b = np.array([1, -1]).astype(dt) + a = np.array([0.5, -0.5]).astype(dt) + + # Test simple IIR + y_r = np.array([0, 2, 4, 6, 8, 10.]).astype(dt) + sos = tf2sos(b, a) + assert_array_almost_equal(sosfilt(tf2sos(b, a), x), y_r) + + # Test simple FIR + b = np.array([1, 1]).astype(dt) + # NOTE: This was changed (rel. to TestLinear...) to add a pole @zero: + a = np.array([1, 0]).astype(dt) + y_r = np.array([0, 1, 3, 5, 7, 9.]).astype(dt) + assert_array_almost_equal(sosfilt(tf2sos(b, a), x), y_r) + + b = [1, 1, 0] + a = [1, 0, 0] + x = np.ones(8) + sos = np.concatenate((b, a)) + sos.shape = (1, 6) + y = sosfilt(sos, x) + assert_allclose(y, [1, 2, 2, 2, 2, 2, 2, 2]) + + def test_rank2(self, dt): + shape = (4, 3) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + x = x.astype(dt) + + b = np.array([1, -1]).astype(dt) + a = np.array([0.5, 0.5]).astype(dt) + + y_r2_a0 = np.array([[0, 2, 4], [6, 4, 2], [0, 2, 4], [6, 4, 2]], + dtype=dt) + + y_r2_a1 = np.array([[0, 2, 0], [6, -4, 6], [12, -10, 12], + [18, -16, 18]], dtype=dt) + + y = sosfilt(tf2sos(b, a), x, axis=0) + assert_array_almost_equal(y_r2_a0, y) + + y = sosfilt(tf2sos(b, a), x, axis=1) + assert_array_almost_equal(y_r2_a1, y) + + def test_rank3(self, dt): + shape = (4, 3, 2) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + + b = np.array([1, -1]).astype(dt) + a = np.array([0.5, 0.5]).astype(dt) + + # Test last axis + y = sosfilt(tf2sos(b, a), x) + for i in range(x.shape[0]): + for j in range(x.shape[1]): + assert_array_almost_equal(y[i, j], lfilter(b, a, x[i, j])) + + def test_initial_conditions(self, dt): + b1, a1 = signal.butter(2, 0.25, 'low') + b2, a2 = signal.butter(2, 0.75, 'low') + b3, a3 = signal.butter(2, 0.75, 'low') + b = np.convolve(np.convolve(b1, b2), b3) + a = np.convolve(np.convolve(a1, a2), a3) + sos = np.array((np.r_[b1, a1], np.r_[b2, a2], np.r_[b3, a3])) + + x = np.random.rand(50).astype(dt) + + # Stopping filtering and continuing + y_true, zi = lfilter(b, a, x[:20], zi=np.zeros(6)) + y_true = np.r_[y_true, lfilter(b, a, x[20:], zi=zi)[0]] + assert_allclose_cast(y_true, lfilter(b, a, x)) + + y_sos, zi = sosfilt(sos, x[:20], zi=np.zeros((3, 2))) + y_sos = np.r_[y_sos, sosfilt(sos, x[20:], zi=zi)[0]] + assert_allclose_cast(y_true, y_sos) + + # Use a step function + zi = sosfilt_zi(sos) + x = np.ones(8, dt) + y, zf = sosfilt(sos, x, zi=zi) + + assert_allclose_cast(y, np.ones(8)) + assert_allclose_cast(zf, zi) + + # Initial condition shape matching + x.shape = (1, 1) + x.shape # 3D + assert_raises(ValueError, sosfilt, sos, x, zi=zi) + zi_nd = zi.copy() + zi_nd.shape = (zi.shape[0], 1, 1, zi.shape[-1]) + assert_raises(ValueError, sosfilt, sos, x, + zi=zi_nd[:, :, :, [0, 1, 1]]) + y, zf = sosfilt(sos, x, zi=zi_nd) + assert_allclose_cast(y[0, 0], np.ones(8)) + assert_allclose_cast(zf[:, 0, 0, :], zi) + + def test_initial_conditions_3d_axis1(self, dt): + # Test the use of zi when sosfilt is applied to axis 1 of a 3-d input. + + # Input array is x. + x = np.random.RandomState(159).randint(0, 5, size=(2, 15, 3)) + x = x.astype(dt) + + # Design a filter in ZPK format and convert to SOS + zpk = signal.butter(6, 0.35, output='zpk') + sos = zpk2sos(*zpk) + nsections = sos.shape[0] + + # Filter along this axis. + axis = 1 + + # Initial conditions, all zeros. + shp = list(x.shape) + shp[axis] = 2 + shp = [nsections] + shp + z0 = np.zeros(shp) + + # Apply the filter to x. + yf, zf = sosfilt(sos, x, axis=axis, zi=z0) + + # Apply the filter to x in two stages. + y1, z1 = sosfilt(sos, x[:, :5, :], axis=axis, zi=z0) + y2, z2 = sosfilt(sos, x[:, 5:, :], axis=axis, zi=z1) + + # y should equal yf, and z2 should equal zf. + y = np.concatenate((y1, y2), axis=axis) + assert_allclose_cast(y, yf, rtol=1e-10, atol=1e-13) + assert_allclose_cast(z2, zf, rtol=1e-10, atol=1e-13) + + # let's try the "step" initial condition + zi = sosfilt_zi(sos) + zi.shape = [nsections, 1, 2, 1] + zi = zi * x[:, 0:1, :] + y = sosfilt(sos, x, axis=axis, zi=zi)[0] + # check it against the TF form + b, a = zpk2tf(*zpk) + zi = lfilter_zi(b, a) + zi.shape = [1, zi.size, 1] + zi = zi * x[:, 0:1, :] + y_tf = lfilter(b, a, x, axis=axis, zi=zi)[0] + assert_allclose_cast(y, y_tf, rtol=1e-10, atol=1e-13) + + def test_bad_zi_shape(self, dt): + # The shape of zi is checked before using any values in the + # arguments, so np.empty is fine for creating the arguments. + x = np.empty((3, 15, 3), dt) + sos = np.zeros((4, 6)) + zi = np.empty((4, 3, 3, 2)) # Correct shape is (4, 3, 2, 3) + with pytest.raises(ValueError, match='should be all ones'): + sosfilt(sos, x, zi=zi, axis=1) + sos[:, 3] = 1. + with pytest.raises(ValueError, match='Invalid zi shape'): + sosfilt(sos, x, zi=zi, axis=1) + + def test_sosfilt_zi(self, dt): + sos = signal.butter(6, 0.2, output='sos') + zi = sosfilt_zi(sos) + + y, zf = sosfilt(sos, np.ones(40, dt), zi=zi) + assert_allclose_cast(zf, zi, rtol=1e-13) + + # Expected steady state value of the step response of this filter: + ss = np.prod(sos[:, :3].sum(axis=-1) / sos[:, 3:].sum(axis=-1)) + assert_allclose_cast(y, ss, rtol=1e-13) + + # zi as array-like + _, zf = sosfilt(sos, np.ones(40, dt), zi=zi.tolist()) + assert_allclose_cast(zf, zi, rtol=1e-13) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self, dt): + # gh-21211 + sos = np.asarray([1, 2, 3, 1, 5, 3], dtype=object).reshape(1, 6) + x = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + sosfilt(sos, x) + + +class TestDeconvolve: + + def test_basic(self): + # From docstring example + original = [0, 1, 0, 0, 1, 1, 0, 0] + impulse_response = [2, 1] + recorded = [0, 2, 1, 0, 2, 3, 1, 0, 0] + recovered, remainder = signal.deconvolve(recorded, impulse_response) + assert_allclose(recovered, original) + + def test_n_dimensional_signal(self): + recorded = [[0, 0], [0, 0]] + impulse_response = [0, 0] + with pytest.raises(ValueError, match="signal must be 1-D."): + quotient, remainder = signal.deconvolve(recorded, impulse_response) + + def test_n_dimensional_divisor(self): + recorded = [0, 0] + impulse_response = [[0, 0], [0, 0]] + with pytest.raises(ValueError, match="divisor must be 1-D."): + quotient, remainder = signal.deconvolve(recorded, impulse_response) + + +class TestDetrend: + + def test_basic(self): + detrended = detrend(array([1, 2, 3])) + detrended_exact = array([0, 0, 0]) + assert_array_almost_equal(detrended, detrended_exact) + + def test_copy(self): + x = array([1, 1.2, 1.5, 1.6, 2.4]) + copy_array = detrend(x, overwrite_data=False) + inplace = detrend(x, overwrite_data=True) + assert_array_almost_equal(copy_array, inplace) + + @pytest.mark.parametrize('kind', ['linear', 'constant']) + @pytest.mark.parametrize('axis', [0, 1, 2]) + def test_axis(self, axis, kind): + data = np.arange(5*6*7).reshape(5, 6, 7) + detrended = detrend(data, type=kind, axis=axis) + assert detrended.shape == data.shape + + def test_bp(self): + data = [0, 1, 2] + [5, 0, -5, -10] + detrended = detrend(data, type='linear', bp=3) + assert_allclose(detrended, 0, atol=1e-14) + + # repeat with ndim > 1 and axis + data = np.asarray(data)[None, :, None] + + detrended = detrend(data, type="linear", bp=3, axis=1) + assert_allclose(detrended, 0, atol=1e-14) + + # breakpoint index > shape[axis]: raises + with assert_raises(ValueError): + detrend(data, type="linear", bp=3) + + @pytest.mark.parametrize('bp', [np.array([0, 2]), [0, 2]]) + def test_detrend_array_bp(self, bp): + # regression test for https://github.com/scipy/scipy/issues/18675 + rng = np.random.RandomState(12345) + x = rng.rand(10) + # bp = np.array([0, 2]) + + res = detrend(x, bp=bp) + res_scipy_191 = np.array([-4.44089210e-16, -2.22044605e-16, + -1.11128506e-01, -1.69470553e-01, 1.14710683e-01, 6.35468419e-02, + 3.53533144e-01, -3.67877935e-02, -2.00417675e-02, -1.94362049e-01]) + + assert_allclose(res, res_scipy_191, atol=1e-14) + + +class TestUniqueRoots: + def test_real_no_repeat(self): + p = [-1.0, -0.5, 0.3, 1.2, 10.0] + unique, multiplicity = unique_roots(p) + assert_almost_equal(unique, p, decimal=15) + assert_equal(multiplicity, np.ones(len(p))) + + def test_real_repeat(self): + p = [-1.0, -0.95, -0.89, -0.8, 0.5, 1.0, 1.05] + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='min') + assert_almost_equal(unique, [-1.0, -0.89, 0.5, 1.0], decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='max') + assert_almost_equal(unique, [-0.95, -0.8, 0.5, 1.05], decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='avg') + assert_almost_equal(unique, [-0.975, -0.845, 0.5, 1.025], decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + def test_complex_no_repeat(self): + p = [-1.0, 1.0j, 0.5 + 0.5j, -1.0 - 1.0j, 3.0 + 2.0j] + unique, multiplicity = unique_roots(p) + assert_almost_equal(unique, p, decimal=15) + assert_equal(multiplicity, np.ones(len(p))) + + def test_complex_repeat(self): + p = [-1.0, -1.0 + 0.05j, -0.95 + 0.15j, -0.90 + 0.15j, 0.0, + 0.5 + 0.5j, 0.45 + 0.55j] + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='min') + assert_almost_equal(unique, [-1.0, -0.95 + 0.15j, 0.0, 0.45 + 0.55j], + decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='max') + assert_almost_equal(unique, + [-1.0 + 0.05j, -0.90 + 0.15j, 0.0, 0.5 + 0.5j], + decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='avg') + assert_almost_equal( + unique, [-1.0 + 0.025j, -0.925 + 0.15j, 0.0, 0.475 + 0.525j], + decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + def test_gh_4915(self): + p = np.roots(np.convolve(np.ones(5), np.ones(5))) + true_roots = [-(-1)**(1/5), (-1)**(4/5), -(-1)**(3/5), (-1)**(2/5)] + + unique, multiplicity = unique_roots(p) + unique = np.sort(unique) + + assert_almost_equal(np.sort(unique), true_roots, decimal=7) + assert_equal(multiplicity, [2, 2, 2, 2]) + + def test_complex_roots_extra(self): + unique, multiplicity = unique_roots([1.0, 1.0j, 1.0]) + assert_almost_equal(unique, [1.0, 1.0j], decimal=15) + assert_equal(multiplicity, [2, 1]) + + unique, multiplicity = unique_roots([1, 1 + 2e-9, 1e-9 + 1j], tol=0.1) + assert_almost_equal(unique, [1.0, 1e-9 + 1.0j], decimal=15) + assert_equal(multiplicity, [2, 1]) + + def test_single_unique_root(self): + p = np.random.rand(100) + 1j * np.random.rand(100) + unique, multiplicity = unique_roots(p, 2) + assert_almost_equal(unique, [np.min(p)], decimal=15) + assert_equal(multiplicity, [100]) + + +def test_gh_22684(): + actual = signal.resample_poly(np.arange(2000, dtype=np.complex64), 6, 4) + assert actual.dtype == np.complex64 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..12dac6300b9ef4b2eac0475f0b53517ab4867416 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py @@ -0,0 +1,2059 @@ +import sys + +import numpy as np +from numpy.testing import (assert_, + assert_allclose, assert_array_equal, assert_equal, + assert_array_almost_equal_nulp, suppress_warnings) +import pytest +from pytest import raises as assert_raises + +from scipy import signal +from scipy.fft import fftfreq, rfftfreq, fft, irfft +from scipy.integrate import trapezoid +from scipy.signal import (periodogram, welch, lombscargle, coherence, + spectrogram, check_COLA, check_NOLA) +from scipy.signal.windows import hann +from scipy.signal._spectral_py import _spectral_helper + +# Compare ShortTimeFFT.stft() / ShortTimeFFT.istft() with stft() / istft(): +from scipy.signal.tests._scipy_spectral_test_shim import stft_compare as stft +from scipy.signal.tests._scipy_spectral_test_shim import istft_compare as istft +from scipy.signal.tests._scipy_spectral_test_shim import csd_compare as csd + + +class TestPeriodogram: + def test_real_onesided_even(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_real_onesided_odd(self): + x = np.zeros(15) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.arange(8.0)/15.0) + q = np.ones(8) + q[0] = 0 + q *= 2.0/15.0 + assert_allclose(p, q, atol=1e-15) + + def test_real_twosided(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 1/16.0) + q[0] = 0 + assert_allclose(p, q) + + def test_real_spectrum(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, scaling='spectrum') + g, q = periodogram(x, scaling='density') + assert_allclose(f, np.linspace(0, 0.5, 9)) + assert_allclose(p, q/16.0) + + def test_integer_even(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_integer_odd(self): + x = np.zeros(15, dtype=int) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.arange(8.0)/15.0) + q = np.ones(8) + q[0] = 0 + q *= 2.0/15.0 + assert_allclose(p, q, atol=1e-15) + + def test_integer_twosided(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 1/16.0) + q[0] = 0 + assert_allclose(p, q) + + def test_complex(self): + x = np.zeros(16, np.complex128) + x[0] = 1.0 + 2.0j + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 5.0/16.0) + q[0] = 0 + assert_allclose(p, q) + + def test_unk_scaling(self): + assert_raises(ValueError, periodogram, np.zeros(4, np.complex128), + scaling='foo') + + @pytest.mark.skipif( + sys.maxsize <= 2**32, + reason="On some 32-bit tolerance issue" + ) + def test_nd_axis_m1(self): + x = np.zeros(20, dtype=np.float64) + x = x.reshape((2,1,10)) + x[:,:,0] = 1.0 + f, p = periodogram(x) + assert_array_equal(p.shape, (2, 1, 6)) + assert_array_almost_equal_nulp(p[0,0,:], p[1,0,:], 60) + f0, p0 = periodogram(x[0,0,:]) + assert_array_almost_equal_nulp(p0[np.newaxis,:], p[1,:], 60) + + @pytest.mark.skipif( + sys.maxsize <= 2**32, + reason="On some 32-bit tolerance issue" + ) + def test_nd_axis_0(self): + x = np.zeros(20, dtype=np.float64) + x = x.reshape((10,2,1)) + x[0,:,:] = 1.0 + f, p = periodogram(x, axis=0) + assert_array_equal(p.shape, (6,2,1)) + assert_array_almost_equal_nulp(p[:,0,0], p[:,1,0], 60) + f0, p0 = periodogram(x[:,0,0]) + assert_array_almost_equal_nulp(p0, p[:,1,0]) + + def test_window_external(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, 10, 'hann') + win = signal.get_window('hann', 16) + fe, pe = periodogram(x, 10, win) + assert_array_almost_equal_nulp(p, pe) + assert_array_almost_equal_nulp(f, fe) + win_err = signal.get_window('hann', 32) + assert_raises(ValueError, periodogram, x, + 10, win_err) # win longer than signal + + def test_padded_fft(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x) + fp, pp = periodogram(x, nfft=32) + assert_allclose(f, fp[::2]) + assert_allclose(p, pp[::2]) + assert_array_equal(pp.shape, (17,)) + + def test_empty_input(self): + f, p = periodogram([]) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + for shape in [(0,), (3,0), (0,5,2)]: + f, p = periodogram(np.empty(shape)) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_empty_input_other_axis(self): + for shape in [(3,0), (0,5,2)]: + f, p = periodogram(np.empty(shape), axis=1) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_short_nfft(self): + x = np.zeros(18) + x[0] = 1 + f, p = periodogram(x, nfft=16) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_nfft_is_xshape(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, nfft=16) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_real_onesided_even_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9, 'f') + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + assert_(p.dtype == q.dtype) + + def test_real_onesided_odd_32(self): + x = np.zeros(15, 'f') + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.arange(8.0)/15.0) + q = np.ones(8, 'f') + q[0] = 0 + q *= 2.0/15.0 + assert_allclose(p, q, atol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_twosided_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 1/16.0, 'f') + q[0] = 0 + assert_allclose(p, q) + assert_(p.dtype == q.dtype) + + def test_complex_32(self): + x = np.zeros(16, 'F') + x[0] = 1.0 + 2.0j + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 5.0/16.0, 'f') + q[0] = 0 + assert_allclose(p, q) + assert_(p.dtype == q.dtype) + + def test_shorter_window_error(self): + x = np.zeros(16) + x[0] = 1 + win = signal.get_window('hann', 10) + expected_msg = ('the size of the window must be the same size ' + 'of the input on the specified axis') + with assert_raises(ValueError, match=expected_msg): + periodogram(x, window=win) + + +class TestWelch: + def test_real_onesided_even(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_onesided_odd(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_twosided(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_spectrum(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, scaling='spectrum') + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667, + 0.02083333]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_even(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_odd(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_twosided(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_complex(self): + x = np.zeros(16, np.complex128) + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556, + 0.55555556, 0.55555556, 0.55555556, 0.38194444]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_unk_scaling(self): + assert_raises(ValueError, welch, np.zeros(4, np.complex128), + scaling='foo', nperseg=4) + + def test_detrend_linear(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = welch(x, nperseg=10, detrend='linear') + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_no_detrending(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f1, p1 = welch(x, nperseg=10, detrend=False) + f2, p2 = welch(x, nperseg=10, detrend=lambda x: x) + assert_allclose(f1, f2, atol=1e-15) + assert_allclose(p1, p2, atol=1e-15) + + def test_detrend_external(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = welch(x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_m1(self): + x = np.arange(40, dtype=np.float64) + 0.04 + x = x.reshape((2,2,10)) + f, p = welch(x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + x = np.moveaxis(x, 2, 0) + f, p = welch(x, nperseg=10, axis=0, + detrend=lambda seg: signal.detrend(seg, axis=0, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_nd_axis_m1(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + f, p = welch(x, nperseg=10) + assert_array_equal(p.shape, (2, 1, 6)) + assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13) + f0, p0 = welch(x[0,0,:], nperseg=10) + assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13) + + def test_nd_axis_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((10,2,1)) + f, p = welch(x, nperseg=10, axis=0) + assert_array_equal(p.shape, (6,2,1)) + assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13) + f0, p0 = welch(x[:,0,0], nperseg=10) + assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13) + + def test_window_external(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, 10, 'hann', nperseg=8) + win = signal.get_window('hann', 8) + fe, pe = welch(x, 10, win, nperseg=None) + assert_array_almost_equal_nulp(p, pe) + assert_array_almost_equal_nulp(f, fe) + assert_array_equal(fe.shape, (5,)) # because win length used as nperseg + assert_array_equal(pe.shape, (5,)) + assert_raises(ValueError, welch, x, + 10, win, nperseg=4) # because nperseg != win.shape[-1] + win_err = signal.get_window('hann', 32) + assert_raises(ValueError, welch, x, + 10, win_err, nperseg=None) # win longer than signal + + def test_empty_input(self): + f, p = welch([]) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + for shape in [(0,), (3,0), (0,5,2)]: + f, p = welch(np.empty(shape)) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_empty_input_other_axis(self): + for shape in [(3,0), (0,5,2)]: + f, p = welch(np.empty(shape), axis=1) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_short_data(self): + x = np.zeros(8) + x[0] = 1 + #for string-like window, input signal length < nperseg value gives + #UserWarning, sets nperseg to x.shape[-1] + with suppress_warnings() as sup: + msg = "nperseg = 256 is greater than input length = 8, using nperseg = 8" + sup.filter(UserWarning, msg) + f, p = welch(x,window='hann') # default nperseg + f1, p1 = welch(x,window='hann', nperseg=256) # user-specified nperseg + f2, p2 = welch(x, nperseg=8) # valid nperseg, doesn't give warning + assert_allclose(f, f2) + assert_allclose(p, p2) + assert_allclose(f1, f2) + assert_allclose(p1, p2) + + def test_window_long_or_nd(self): + assert_raises(ValueError, welch, np.zeros(4), 1, np.array([1,1,1,1,1])) + assert_raises(ValueError, welch, np.zeros(4), 1, + np.arange(6).reshape((2,3))) + + def test_nondefault_noverlap(self): + x = np.zeros(64) + x[::8] = 1 + f, p = welch(x, nperseg=16, noverlap=4) + q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5., + 1./6.]) + assert_allclose(p, q, atol=1e-12) + + def test_bad_noverlap(self): + assert_raises(ValueError, welch, np.zeros(4), 1, 'hann', 2, 7) + + def test_nfft_too_short(self): + assert_raises(ValueError, welch, np.ones(12), nfft=3, nperseg=4) + + def test_real_onesided_even_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_onesided_odd_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116, + 0.17072113], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_twosided_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.11111111, + 0.07638889], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_complex_32(self): + x = np.zeros(16, 'F') + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552, + 0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype, + f'dtype mismatch, {p.dtype}, {q.dtype}') + + def test_padded_freqs(self): + x = np.zeros(12) + + nfft = 24 + f = fftfreq(nfft, 1.0)[:nfft//2+1] + f[-1] *= -1 + fodd, _ = welch(x, nperseg=5, nfft=nfft) + feven, _ = welch(x, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + nfft = 25 + f = fftfreq(nfft, 1.0)[:(nfft + 1)//2] + fodd, _ = welch(x, nperseg=5, nfft=nfft) + feven, _ = welch(x, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + def test_window_correction(self): + A = 20 + fs = 1e4 + nperseg = int(fs//10) + fsig = 300 + ii = int(fsig*nperseg//fs) # Freq index of fsig + + tt = np.arange(fs)/fs + x = A*np.sin(2*np.pi*fsig*tt) + + for window in ['hann', 'bartlett', ('tukey', 0.1), 'flattop']: + _, p_spec = welch(x, fs=fs, nperseg=nperseg, window=window, + scaling='spectrum') + freq, p_dens = welch(x, fs=fs, nperseg=nperseg, window=window, + scaling='density') + + # Check peak height at signal frequency for 'spectrum' + assert_allclose(p_spec[ii], A**2/2.0) + # Check integrated spectrum RMS for 'density' + assert_allclose(np.sqrt(trapezoid(p_dens, freq)), A*np.sqrt(2)/2, + rtol=1e-3) + + def test_axis_rolling(self): + np.random.seed(1234) + + x_flat = np.random.randn(1024) + _, p_flat = welch(x_flat) + + for a in range(3): + newshape = [1,]*3 + newshape[a] = -1 + x = x_flat.reshape(newshape) + + _, p_plus = welch(x, axis=a) # Positive axis index + _, p_minus = welch(x, axis=a-x.ndim) # Negative axis index + + assert_equal(p_flat, p_plus.squeeze(), err_msg=a) + assert_equal(p_flat, p_minus.squeeze(), err_msg=a-x.ndim) + + def test_average(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, average='median') + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([.1, .05, 0., 1.54074396e-33, 0.]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + assert_raises(ValueError, welch, x, nperseg=8, + average='unrecognised-average') + + +class TestCSD: + def test_pad_shorter_x(self): + x = np.zeros(8) + y = np.zeros(12) + + f = np.linspace(0, 0.5, 7) + c = np.zeros(7,dtype=np.complex128) + f1, c1 = csd(x, y, nperseg=12) + + assert_allclose(f, f1) + assert_allclose(c, c1) + + def test_pad_shorter_y(self): + x = np.zeros(12) + y = np.zeros(8) + + f = np.linspace(0, 0.5, 7) + c = np.zeros(7,dtype=np.complex128) + f1, c1 = csd(x, y, nperseg=12) + + assert_allclose(f, f1) + assert_allclose(c, c1) + + def test_real_onesided_even(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_onesided_odd(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_twosided(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_spectrum(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, scaling='spectrum') + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667, + 0.02083333]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_even(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_odd(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_twosided(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_complex(self): + x = np.zeros(16, np.complex128) + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556, + 0.55555556, 0.55555556, 0.55555556, 0.38194444]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_unk_scaling(self): + assert_raises(ValueError, csd, np.zeros(4, np.complex128), + np.ones(4, np.complex128), scaling='foo', nperseg=4) + + def test_detrend_linear(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = csd(x, x, nperseg=10, detrend='linear') + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_no_detrending(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f1, p1 = csd(x, x, nperseg=10, detrend=False) + f2, p2 = csd(x, x, nperseg=10, detrend=lambda x: x) + assert_allclose(f1, f2, atol=1e-15) + assert_allclose(p1, p2, atol=1e-15) + + def test_detrend_external(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = csd(x, x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_m1(self): + x = np.arange(40, dtype=np.float64) + 0.04 + x = x.reshape((2,2,10)) + f, p = csd(x, x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + x = np.moveaxis(x, 2, 0) + f, p = csd(x, x, nperseg=10, axis=0, + detrend=lambda seg: signal.detrend(seg, axis=0, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_nd_axis_m1(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + f, p = csd(x, x, nperseg=10) + assert_array_equal(p.shape, (2, 1, 6)) + assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13) + f0, p0 = csd(x[0,0,:], x[0,0,:], nperseg=10) + assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13) + + def test_nd_axis_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((10,2,1)) + f, p = csd(x, x, nperseg=10, axis=0) + assert_array_equal(p.shape, (6,2,1)) + assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13) + f0, p0 = csd(x[:,0,0], x[:,0,0], nperseg=10) + assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13) + + def test_window_external(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, 10, 'hann', 8) + win = signal.get_window('hann', 8) + fe, pe = csd(x, x, 10, win, nperseg=None) + assert_array_almost_equal_nulp(p, pe) + assert_array_almost_equal_nulp(f, fe) + assert_array_equal(fe.shape, (5,)) # because win length used as nperseg + assert_array_equal(pe.shape, (5,)) + assert_raises(ValueError, csd, x, x, + 10, win, nperseg=256) # because nperseg != win.shape[-1] + win_err = signal.get_window('hann', 32) + assert_raises(ValueError, csd, x, x, + 10, win_err, nperseg=None) # because win longer than signal + + def test_empty_input(self): + f, p = csd([],np.zeros(10)) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + + f, p = csd(np.zeros(10),[]) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + + for shape in [(0,), (3,0), (0,5,2)]: + f, p = csd(np.empty(shape), np.empty(shape)) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + f, p = csd(np.ones(10), np.empty((5,0))) + assert_array_equal(f.shape, (5,0)) + assert_array_equal(p.shape, (5,0)) + + f, p = csd(np.empty((5,0)), np.ones(10)) + assert_array_equal(f.shape, (5,0)) + assert_array_equal(p.shape, (5,0)) + + def test_empty_input_other_axis(self): + for shape in [(3,0), (0,5,2)]: + f, p = csd(np.empty(shape), np.empty(shape), axis=1) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + f, p = csd(np.empty((10,10,3)), np.zeros((10,0,1)), axis=1) + assert_array_equal(f.shape, (10,0,3)) + assert_array_equal(p.shape, (10,0,3)) + + f, p = csd(np.empty((10,0,1)), np.zeros((10,10,3)), axis=1) + assert_array_equal(f.shape, (10,0,3)) + assert_array_equal(p.shape, (10,0,3)) + + def test_short_data(self): + x = np.zeros(8) + x[0] = 1 + + #for string-like window, input signal length < nperseg value gives + #UserWarning, sets nperseg to x.shape[-1] + with suppress_warnings() as sup: + msg = "nperseg = 256 is greater than input length = 8, using nperseg = 8" + sup.filter(UserWarning, msg) + f, p = csd(x, x, window='hann') # default nperseg + f1, p1 = csd(x, x, window='hann', nperseg=256) # user-specified nperseg + f2, p2 = csd(x, x, nperseg=8) # valid nperseg, doesn't give warning + assert_allclose(f, f2) + assert_allclose(p, p2) + assert_allclose(f1, f2) + assert_allclose(p1, p2) + + def test_window_long_or_nd(self): + assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, + np.array([1,1,1,1,1])) + assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, + np.arange(6).reshape((2,3))) + + def test_nondefault_noverlap(self): + x = np.zeros(64) + x[::8] = 1 + f, p = csd(x, x, nperseg=16, noverlap=4) + q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5., + 1./6.]) + assert_allclose(p, q, atol=1e-12) + + def test_bad_noverlap(self): + assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, 'hann', + 2, 7) + + def test_nfft_too_short(self): + assert_raises(ValueError, csd, np.ones(12), np.zeros(12), nfft=3, + nperseg=4) + + def test_real_onesided_even_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_onesided_odd_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116, + 0.17072113], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_twosided_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.11111111, + 0.07638889], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_complex_32(self): + x = np.zeros(16, 'F') + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552, + 0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype, + f'dtype mismatch, {p.dtype}, {q.dtype}') + + def test_padded_freqs(self): + x = np.zeros(12) + y = np.ones(12) + + nfft = 24 + f = fftfreq(nfft, 1.0)[:nfft//2+1] + f[-1] *= -1 + fodd, _ = csd(x, y, nperseg=5, nfft=nfft) + feven, _ = csd(x, y, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + nfft = 25 + f = fftfreq(nfft, 1.0)[:(nfft + 1)//2] + fodd, _ = csd(x, y, nperseg=5, nfft=nfft) + feven, _ = csd(x, y, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + def test_copied_data(self): + x = np.random.randn(64) + y = x.copy() + + _, p_same = csd(x, x, nperseg=8, average='mean', + return_onesided=False) + _, p_copied = csd(x, y, nperseg=8, average='mean', + return_onesided=False) + assert_allclose(p_same, p_copied) + + _, p_same = csd(x, x, nperseg=8, average='median', + return_onesided=False) + _, p_copied = csd(x, y, nperseg=8, average='median', + return_onesided=False) + assert_allclose(p_same, p_copied) + + +class TestCoherence: + def test_identical_input(self): + x = np.random.randn(20) + y = np.copy(x) # So `y is x` -> False + + f = np.linspace(0, 0.5, 6) + C = np.ones(6) + f1, C1 = coherence(x, y, nperseg=10) + + assert_allclose(f, f1) + assert_allclose(C, C1) + + def test_phase_shifted_input(self): + x = np.random.randn(20) + y = -x + + f = np.linspace(0, 0.5, 6) + C = np.ones(6) + f1, C1 = coherence(x, y, nperseg=10) + + assert_allclose(f, f1) + assert_allclose(C, C1) + + +class TestSpectrogram: + def test_average_all_segments(self): + x = np.random.randn(1024) + + fs = 1.0 + window = ('tukey', 0.25) + nperseg = 16 + noverlap = 2 + + f, _, P = spectrogram(x, fs, window, nperseg, noverlap) + fw, Pw = welch(x, fs, window, nperseg, noverlap) + assert_allclose(f, fw) + assert_allclose(np.mean(P, axis=-1), Pw) + + def test_window_external(self): + x = np.random.randn(1024) + + fs = 1.0 + window = ('tukey', 0.25) + nperseg = 16 + noverlap = 2 + f, _, P = spectrogram(x, fs, window, nperseg, noverlap) + + win = signal.get_window(('tukey', 0.25), 16) + fe, _, Pe = spectrogram(x, fs, win, nperseg=None, noverlap=2) + assert_array_equal(fe.shape, (9,)) # because win length used as nperseg + assert_array_equal(Pe.shape, (9,73)) + assert_raises(ValueError, spectrogram, x, + fs, win, nperseg=8) # because nperseg != win.shape[-1] + win_err = signal.get_window(('tukey', 0.25), 2048) + assert_raises(ValueError, spectrogram, x, + fs, win_err, nperseg=None) # win longer than signal + + def test_short_data(self): + x = np.random.randn(1024) + fs = 1.0 + + #for string-like window, input signal length < nperseg value gives + #UserWarning, sets nperseg to x.shape[-1] + f, _, p = spectrogram(x, fs, window=('tukey',0.25)) # default nperseg + with suppress_warnings() as sup: + sup.filter(UserWarning, + "nperseg = 1025 is greater than input length = 1024, " + "using nperseg = 1024",) + f1, _, p1 = spectrogram(x, fs, window=('tukey',0.25), + nperseg=1025) # user-specified nperseg + f2, _, p2 = spectrogram(x, fs, nperseg=256) # to compare w/default + f3, _, p3 = spectrogram(x, fs, nperseg=1024) # compare w/user-spec'd + assert_allclose(f, f2) + assert_allclose(p, p2) + assert_allclose(f1, f3) + assert_allclose(p1, p3) + +class TestLombscargle: + def test_frequency(self): + """Test if frequency location of peak corresponds to frequency of + generated input signal. + """ + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + P = lombscargle(t, y, f) + + # Check if difference between found frequency maximum and input + # frequency is less than accuracy + delta = f[1] - f[0] + assert(w - f[np.argmax(P)] < (delta/2.)) + + # also, check that it works with weights + P = lombscargle(t, y, f, weights=np.ones_like(t, dtype=f.dtype)) + + # Check if difference between found frequency maximum and input + # frequency is less than accuracy + delta = f[1] - f[0] + assert(w - f[np.argmax(P)] < (delta/2.)) + + + def test_amplitude(self): + # Test if height of peak in unnormalized Lomb-Scargle periodogram + # corresponds to amplitude of the generated input signal. + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 1000 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f) + + # convert to the amplitude + pgram = np.sqrt(4.0 * pgram / t.shape[0]) + + # Check if amplitude is correct (this will not exactly match, due to + # numerical differences when data is removed) + assert_allclose(pgram[f==w], ampl, rtol=5e-2) + + def test_precenter(self): + # Test if precenter gives the same result as manually precentering + # (for a very simple offset) + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 0.15 # Offset to be subtracted in pre-centering + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + offset + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, precenter=True) + pgram2 = lombscargle(t, y - y.mean(), f, precenter=False) + + # check if centering worked + assert_allclose(pgram, pgram2) + + # do this again, but with floating_mean=True + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, precenter=True, floating_mean=True) + pgram2 = lombscargle(t, y - y.mean(), f, precenter=False, floating_mean=True) + + # check if centering worked + assert_allclose(pgram, pgram2) + + def test_normalize(self): + # Test normalize option of Lomb-Scarge. + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f) + pgram2 = lombscargle(t, y, f, normalize=True) + + # Calculate the scale to convert from unnormalized to normalized + weights = np.ones_like(t)/float(t.shape[0]) + YY_hat = (weights * y * y).sum() + YY = YY_hat # correct formula for floating_mean=False + scale_to_use = 2/(YY*t.shape[0]) + + # check if normalization works as expected + assert_allclose(pgram * scale_to_use, pgram2) + assert_allclose(np.max(pgram2), 1.0) + + def test_wrong_shape(self): + + # different length t and y + t = np.linspace(0, 1, 1) + y = np.linspace(0, 1, 2) + f = np.linspace(0, 1, 3) + 0.1 + assert_raises(ValueError, lombscargle, t, y, f) + + # t is 2D, with both axes length > 1 + t = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1) + y = np.linspace(0, 1, 2) + f = np.linspace(0, 1, 3) + 0.1 + assert_raises(ValueError, lombscargle, t, y, f) + + # y is 2D, with both axes length > 1 + t = np.linspace(0, 1, 2) + y = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1) + f = np.linspace(0, 1, 3) + 0.1 + assert_raises(ValueError, lombscargle, t, y, f) + + # f is 2D, with both axes length > 1 + t = np.linspace(0, 1, 2) + y = np.linspace(0, 1, 2) + f = np.repeat(np.expand_dims(np.linspace(0, 1, 3), 1) + 0.1, 2, axis=1) + assert_raises(ValueError, lombscargle, t, y, f) + + # weights is 2D, with both axes length > 1 + t = np.linspace(0, 1, 2) + y = np.linspace(0, 1, 2) + f = np.linspace(0, 1, 3) + 0.1 + weights = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_lombscargle_atan_vs_atan2(self): + # https://github.com/scipy/scipy/issues/3787 + # This raised a ZeroDivisionError. + t = np.linspace(0, 10, 1000, endpoint=False) + y = np.sin(4*t) + f = np.linspace(0, 50, 500, endpoint=False) + 0.1 + lombscargle(t, y, f*2*np.pi) + + def test_wrong_shape_weights(self): + # Weights must be the same shape as t + + t = np.linspace(0, 1, 1) + y = np.linspace(0, 1, 1) + f = np.linspace(0, 1, 3) + 0.1 + weights = np.linspace(1, 2, 2) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_zero_division_weights(self): + # Weights cannot sum to 0 + + t = np.zeros(1) + y = np.zeros(1) + f = np.ones(1) + weights = np.zeros(1) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_normalize_parameter(self): + # Test the validity of the normalize parameter input + + # Input parameters + ampl = 2. + w = 1. + phi = 0 + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # check each of the valid inputs + pgram_false = lombscargle(t, y, f, normalize=False) + pgram_true = lombscargle(t, y, f, normalize=True) + pgram_power = lombscargle(t, y, f, normalize='power') + pgram_norm = lombscargle(t, y, f, normalize='normalize') + pgram_amp = lombscargle(t, y, f, normalize='amplitude') + + # validate the results that should be the same + assert_allclose(pgram_false, pgram_power) + assert_allclose(pgram_true, pgram_norm) + + # validate that the power and norm outputs are proper wrt each other + weights = np.ones_like(y)/float(y.shape[0]) + YY_hat = (weights * y * y).sum() + YY = YY_hat # correct formula for floating_mean=False + assert_allclose(pgram_power * 2.0 / (float(t.shape[0]) * YY), pgram_norm) + + # validate that the amp output is correct for the given input + f_i = np.where(f==w)[0][0] + assert_allclose(np.abs(pgram_amp[f_i]), ampl) + + # check invalid inputs + # 1) a string that is not allowed + assert_raises(ValueError, lombscargle, t, y, f, normalize='lomb') + # 2) something besides a bool or str + assert_raises(ValueError, lombscargle, t, y, f, normalize=2) + + def test_offset_removal(self): + # Verify that the amplitude is the same, even with an offset + # must use floating_mean=True, otherwise it will not remove an offset + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 2.15 # Large offset + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, floating_mean=True) + pgram_offset = lombscargle(t, y + offset, f, floating_mean=True) + + # check if offset removal works as expected + assert_allclose(pgram, pgram_offset) + + def test_floating_mean_false(self): + # Verify that when disabling the floating_mean, the calculations are correct + + # Input parameters + ampl = 2. + w = 1. + phi = 0 + nin = 1000 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 2 # Large offset + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a cos wave for the selected times + y = ampl * np.cos(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, normalize=True, floating_mean=False) + pgram_offset = lombscargle(t, y + offset, f, normalize=True, + floating_mean=False) + + # check if disabling floating_mean works as expected + # nearly-zero for no offset, exact value will change based on seed + assert(pgram[0] < 0.01) + # significant value with offset, exact value will change based on seed + assert(pgram_offset[0] > 0.5) + + def test_amplitude_is_correct(self): + # Verify that the amplitude is correct (when normalize='amplitude') + + # Input parameters + ampl = 2. + w = 1. + phi = 0.12 + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 2.15 # Large offset + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.cos(w*t + phi) + offset + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Get the index of where the exact result should be + f_indx = np.where(f==w)[0][0] + + # Calculate Lomb-Scargle periodogram (amplitude + phase) + pgram = lombscargle(t, y, f, normalize='amplitude', floating_mean=True) + + # Check if amplitude is correct + assert_allclose(np.abs(pgram[f_indx]), ampl) + + # Check if phase is correct + # (phase angle is the negative of the phase offset) + assert_allclose(-np.angle(pgram[f_indx]), phi) + + def test_negative_weight(self): + # Test that a negative weight produces an error + + t = np.zeros(1) + y = np.zeros(1) + f = np.ones(1) + weights = -np.ones(1) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_list_input(self): + # Test that input can be passsed in as lists and with a numerical issue + # https://github.com/scipy/scipy/issues/8787 + + t = [1.98201652e+09, 1.98201752e+09, 1.98201852e+09, 1.98201952e+09, + 1.98202052e+09, 1.98202152e+09, 1.98202252e+09, 1.98202352e+09, + 1.98202452e+09, 1.98202552e+09, 1.98202652e+09, 1.98202752e+09, + 1.98202852e+09, 1.98202952e+09, 1.98203052e+09, 1.98203152e+09, + 1.98203252e+09, 1.98203352e+09, 1.98203452e+09, 1.98203552e+09, + 1.98205452e+09, 1.98205552e+09, 1.98205652e+09, 1.98205752e+09, + 1.98205852e+09, 1.98205952e+09, 1.98206052e+09, 1.98206152e+09, + 1.98206252e+09, 1.98206352e+09, 1.98206452e+09, 1.98206552e+09, + 1.98206652e+09, 1.98206752e+09, 1.98206852e+09, 1.98206952e+09, + 1.98207052e+09, 1.98207152e+09, 1.98207252e+09, 1.98207352e+09, + 1.98209652e+09, 1.98209752e+09, 1.98209852e+09, 1.98209952e+09, + 1.98210052e+09, 1.98210152e+09, 1.98210252e+09, 1.98210352e+09, + 1.98210452e+09, 1.98210552e+09, 1.98210652e+09, 1.98210752e+09, + 1.98210852e+09, 1.98210952e+09, 1.98211052e+09, 1.98211152e+09, + 1.98211252e+09, 1.98211352e+09, 1.98211452e+09, 1.98211552e+09, + 1.98217252e+09, 1.98217352e+09, 1.98217452e+09, 1.98217552e+09, + 1.98217652e+09, 1.98217752e+09, 1.98217852e+09, 1.98217952e+09, + 1.98218052e+09, 1.98218152e+09, 1.98218252e+09, 1.98218352e+09, + 1.98218452e+09, 1.98218552e+09, 1.98218652e+09, 1.98218752e+09, + 1.98218852e+09, 1.98218952e+09, 1.98219052e+09, 1.98219152e+09, + 1.98219352e+09, 1.98219452e+09, 1.98219552e+09, 1.98219652e+09, + 1.98219752e+09, 1.98219852e+09, 1.98219952e+09, 1.98220052e+09, + 1.98220152e+09, 1.98220252e+09, 1.98220352e+09, 1.98220452e+09, + 1.98220552e+09, 1.98220652e+09, 1.98220752e+09, 1.98220852e+09, + 1.98220952e+09, 1.98221052e+09, 1.98221152e+09, 1.98221252e+09, + 1.98222752e+09, 1.98222852e+09, 1.98222952e+09, 1.98223052e+09, + 1.98223152e+09, 1.98223252e+09, 1.98223352e+09, 1.98223452e+09, + 1.98223552e+09, 1.98223652e+09, 1.98223752e+09, 1.98223852e+09, + 1.98223952e+09, 1.98224052e+09, 1.98224152e+09, 1.98224252e+09, + 1.98224352e+09, 1.98224452e+09, 1.98224552e+09, 1.98224652e+09, + 1.98224752e+09] + y = [2.97600000e+03, 3.18200000e+03, 3.74900000e+03, 4.53500000e+03, + 5.43300000e+03, 6.38000000e+03, 7.34000000e+03, 8.29200000e+03, + 9.21900000e+03, 1.01120000e+04, 1.09620000e+04, 1.17600000e+04, + 1.25010000e+04, 1.31790000e+04, 1.37900000e+04, 1.43290000e+04, + 1.47940000e+04, 1.51800000e+04, 1.54870000e+04, 1.57110000e+04, + 5.74200000e+03, 4.82300000e+03, 3.99100000e+03, 3.33600000e+03, + 2.99600000e+03, 3.08400000e+03, 3.56700000e+03, 4.30700000e+03, + 5.18200000e+03, 6.11900000e+03, 7.07900000e+03, 8.03400000e+03, + 8.97000000e+03, 9.87300000e+03, 1.07350000e+04, 1.15480000e+04, + 1.23050000e+04, 1.30010000e+04, 1.36300000e+04, 1.41890000e+04, + 6.00000000e+03, 5.06800000e+03, 4.20500000e+03, 3.49000000e+03, + 3.04900000e+03, 3.01600000e+03, 3.40400000e+03, 4.08800000e+03, + 4.93500000e+03, 5.86000000e+03, 6.81700000e+03, 7.77500000e+03, + 8.71800000e+03, 9.63100000e+03, 1.05050000e+04, 1.13320000e+04, + 1.21050000e+04, 1.28170000e+04, 1.34660000e+04, 1.40440000e+04, + 1.32730000e+04, 1.26040000e+04, 1.18720000e+04, 1.10820000e+04, + 1.02400000e+04, 9.35300000e+03, 8.43000000e+03, 7.48100000e+03, + 6.52100000e+03, 5.57000000e+03, 4.66200000e+03, 3.85400000e+03, + 3.24600000e+03, 2.97900000e+03, 3.14700000e+03, 3.68800000e+03, + 4.45900000e+03, 5.35000000e+03, 6.29400000e+03, 7.25400000e+03, + 9.13800000e+03, 1.00340000e+04, 1.08880000e+04, 1.16910000e+04, + 1.24370000e+04, 1.31210000e+04, 1.37380000e+04, 1.42840000e+04, + 1.47550000e+04, 1.51490000e+04, 1.54630000e+04, 1.56950000e+04, + 1.58430000e+04, 1.59070000e+04, 1.58860000e+04, 1.57800000e+04, + 1.55910000e+04, 1.53190000e+04, 1.49650000e+04, 1.45330000e+04, + 3.01000000e+03, 3.05900000e+03, 3.51200000e+03, 4.23400000e+03, + 5.10000000e+03, 6.03400000e+03, 6.99300000e+03, 7.95000000e+03, + 8.88800000e+03, 9.79400000e+03, 1.06600000e+04, 1.14770000e+04, + 1.22400000e+04, 1.29410000e+04, 1.35770000e+04, 1.41430000e+04, + 1.46350000e+04, 1.50500000e+04, 1.53850000e+04, 1.56400000e+04, + 1.58110000e+04] + + periods = np.linspace(400, 120, 1000) + angular_freq = 2 * np.pi / periods + + lombscargle(t, y, angular_freq, precenter=True, normalize=True) + + def test_zero_freq(self): + # Verify that function works when freqs includes 0 + # The value at f=0 will depend on the seed + + # Input parameters + ampl = 2. + w = 1. + phi = 0.12 + nin = 100 + nout = 1001 + p = 0.7 # Fraction of points to select + offset = 0 + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.cos(w*t + phi) + offset + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, normalize=True, floating_mean=True) + + # exact value will change based on seed + # testing to make sure it is very small + assert(pgram[0] < 1e-4) + + def test_simple_div_zero(self): + # these are bare-minimum examples that would, without the eps adjustments, + # cause division-by-zero errors + + # first, test with example that will cause first SS sum to be 0.0 + t = [t + 1 for t in range(0, 32)] + y = np.ones(len(t)) + freqs = [2.0*np.pi] * 2 # must have 2+ elements + lombscargle(t, y, freqs) + + # second, test with example that will cause first CC sum to be 0.0 + t = [t*4 + 1 for t in range(0, 32)] + y = np.ones(len(t)) + freqs = [np.pi/2.0] * 2 # must have 2+ elements + + lombscargle(t, y, freqs) + + +class TestSTFT: + @pytest.mark.thread_unsafe + def test_input_validation(self): + + def chk_VE(match): + """Assert for a ValueError matching regexp `match`. + + This little wrapper allows a more concise code layout. + """ + return pytest.raises(ValueError, match=match) + + # Checks for check_COLA(): + with chk_VE('nperseg must be a positive integer'): + check_COLA('hann', -10, 0) + with chk_VE('noverlap must be less than nperseg.'): + check_COLA('hann', 10, 20) + with chk_VE('window must be 1-D'): + check_COLA(np.ones((2, 2)), 10, 0) + with chk_VE('window must have length of nperseg'): + check_COLA(np.ones(20), 10, 0) + + # Checks for check_NOLA(): + with chk_VE('nperseg must be a positive integer'): + check_NOLA('hann', -10, 0) + with chk_VE('noverlap must be less than nperseg'): + check_NOLA('hann', 10, 20) + with chk_VE('window must be 1-D'): + check_NOLA(np.ones((2, 2)), 10, 0) + with chk_VE('window must have length of nperseg'): + check_NOLA(np.ones(20), 10, 0) + with chk_VE('noverlap must be a nonnegative integer'): + check_NOLA('hann', 64, -32) + + x = np.zeros(1024) + z = stft(x)[2] + + # Checks for stft(): + with chk_VE('window must be 1-D'): + stft(x, window=np.ones((2, 2))) + with chk_VE('value specified for nperseg is different ' + + 'from length of window'): + stft(x, window=np.ones(10), nperseg=256) + with chk_VE('nperseg must be a positive integer'): + stft(x, nperseg=-256) + with chk_VE('noverlap must be less than nperseg.'): + stft(x, nperseg=256, noverlap=1024) + with chk_VE('nfft must be greater than or equal to nperseg.'): + stft(x, nperseg=256, nfft=8) + + # Checks for istft(): + with chk_VE('Input stft must be at least 2d!'): + istft(x) + with chk_VE('window must be 1-D'): + istft(z, window=np.ones((2, 2))) + with chk_VE('window must have length of 256'): + istft(z, window=np.ones(10), nperseg=256) + with chk_VE('nperseg must be a positive integer'): + istft(z, nperseg=-256) + with chk_VE('noverlap must be less than nperseg.'): + istft(z, nperseg=256, noverlap=1024) + with chk_VE('nfft must be greater than or equal to nperseg.'): + istft(z, nperseg=256, nfft=8) + with pytest.warns(UserWarning, match="NOLA condition failed, " + + "STFT may not be invertible"): + istft(z, nperseg=256, noverlap=0, window='hann') + with chk_VE('Must specify differing time and frequency axes!'): + istft(z, time_axis=0, freq_axis=0) + + # Checks for _spectral_helper(): + with chk_VE("Unknown value for mode foo, must be one of: " + + r"\{'psd', 'stft'\}"): + _spectral_helper(x, x, mode='foo') + with chk_VE("x and y must be equal if mode is 'stft'"): + _spectral_helper(x[:512], x[512:], mode='stft') + with chk_VE("Unknown boundary option 'foo', must be one of: " + + r"\['even', 'odd', 'constant', 'zeros', None\]"): + _spectral_helper(x, x, boundary='foo') + + scaling = "not_valid" + with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"): + stft(x, scaling=scaling) + with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"): + istft(z, scaling=scaling) + + def test_check_COLA(self): + settings = [ + ('boxcar', 10, 0), + ('boxcar', 10, 9), + ('bartlett', 51, 26), + ('hann', 256, 128), + ('hann', 256, 192), + ('blackman', 300, 200), + (('tukey', 0.5), 256, 64), + ('hann', 256, 255), + ] + + for setting in settings: + msg = '{}, {}, {}'.format(*setting) + assert_equal(True, check_COLA(*setting), err_msg=msg) + + def test_check_NOLA(self): + settings_pass = [ + ('boxcar', 10, 0), + ('boxcar', 10, 9), + ('boxcar', 10, 7), + ('bartlett', 51, 26), + ('bartlett', 51, 10), + ('hann', 256, 128), + ('hann', 256, 192), + ('hann', 256, 37), + ('blackman', 300, 200), + ('blackman', 300, 123), + (('tukey', 0.5), 256, 64), + (('tukey', 0.5), 256, 38), + ('hann', 256, 255), + ('hann', 256, 39), + ] + for setting in settings_pass: + msg = '{}, {}, {}'.format(*setting) + assert_equal(True, check_NOLA(*setting), err_msg=msg) + + w_fail = np.ones(16) + w_fail[::2] = 0 + settings_fail = [ + (w_fail, len(w_fail), len(w_fail) // 2), + ('hann', 64, 0), + ] + for setting in settings_fail: + msg = '{}, {}, {}'.format(*setting) + assert_equal(False, check_NOLA(*setting), err_msg=msg) + + def test_average_all_segments(self): + rng = np.random.RandomState(1234) + x = rng.randn(1024) + + fs = 1.0 + window = 'hann' + nperseg = 16 + noverlap = 8 + + # Compare twosided, because onesided welch doubles non-DC terms to + # account for power at negative frequencies. stft doesn't do this, + # because it breaks invertibility. + f, _, Z = stft(x, fs, window, nperseg, noverlap, padded=False, + return_onesided=False, boundary=None) + fw, Pw = welch(x, fs, window, nperseg, noverlap, return_onesided=False, + scaling='spectrum', detrend=False) + + assert_allclose(f, fw) + assert_allclose(np.mean(np.abs(Z)**2, axis=-1), Pw) + + def test_permute_axes(self): + rng = np.random.RandomState(1234) + x = rng.randn(1024) + + fs = 1.0 + window = 'hann' + nperseg = 16 + noverlap = 8 + + f1, t1, Z1 = stft(x, fs, window, nperseg, noverlap) + f2, t2, Z2 = stft(x.reshape((-1, 1, 1)), fs, window, nperseg, noverlap, + axis=0) + + t3, x1 = istft(Z1, fs, window, nperseg, noverlap) + t4, x2 = istft(Z2.T, fs, window, nperseg, noverlap, time_axis=0, + freq_axis=-1) + + assert_allclose(f1, f2) + assert_allclose(t1, t2) + assert_allclose(t3, t4) + assert_allclose(Z1, Z2[:, 0, 0, :]) + assert_allclose(x1, x2[:, 0, 0]) + + @pytest.mark.parametrize('scaling', ['spectrum', 'psd']) + def test_roundtrip_real(self, scaling): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ('bartlett', 101, 51, 26), # Test odd nperseg + ('hann', 1024, 256, 128), # Test defaults + (('tukey', 0.5), 1152, 256, 64), # Test Tukey + ('hann', 1024, 256, 255), # Test overlapped hann + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False, + scaling=scaling) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, scaling=scaling) + + msg = f'{window}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + + @pytest.mark.thread_unsafe + def test_roundtrip_not_nola(self): + rng = np.random.RandomState(1234) + + w_fail = np.ones(16) + w_fail[::2] = 0 + settings = [ + (w_fail, 256, len(w_fail), len(w_fail) // 2), + ('hann', 256, 64, 0), + ] + + for window, N, nperseg, noverlap in settings: + msg = f'{window}, {N}, {nperseg}, {noverlap}' + assert not check_NOLA(window, nperseg, noverlap), msg + + t = np.arange(N) + x = 10 * rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary='zeros') + with pytest.warns(UserWarning, match='NOLA'): + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, boundary=True) + + assert np.allclose(t, tr[:len(t)]), msg + assert not np.allclose(x, xr[:len(x)]), msg + + def test_roundtrip_nola_not_cola(self): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 100, 10, 3), # NOLA True, COLA False + ('bartlett', 101, 51, 37), # NOLA True, COLA False + ('hann', 1024, 256, 127), # NOLA True, COLA False + (('tukey', 0.5), 1152, 256, 14), # NOLA True, COLA False + ('hann', 1024, 256, 5), # NOLA True, COLA False + ] + + for window, N, nperseg, noverlap in settings: + msg = f'{window}, {nperseg}, {noverlap}' + assert check_NOLA(window, nperseg, noverlap), msg + assert not check_COLA(window, nperseg, noverlap), msg + + t = np.arange(N) + x = 10 * rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary='zeros') + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, boundary=True) + + msg = f'{window}, {noverlap}' + assert_allclose(t, tr[:len(t)], err_msg=msg) + assert_allclose(x, xr[:len(x)], err_msg=msg) + + def test_roundtrip_float32(self): + rng = np.random.RandomState(1234) + + settings = [('hann', 1024, 256, 128)] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + x = x.astype(np.float32) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window) + + msg = f'{window}, {noverlap}' + assert_allclose(t, t, err_msg=msg) + assert_allclose(x, xr, err_msg=msg, rtol=1e-4, atol=1e-5) + assert_(x.dtype == xr.dtype) + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('scaling', ['spectrum', 'psd']) + def test_roundtrip_complex(self, scaling): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ('bartlett', 101, 51, 26), # Test odd nperseg + ('hann', 1024, 256, 128), # Test defaults + (('tukey', 0.5), 1152, 256, 64), # Test Tukey + ('hann', 1024, 256, 255), # Test overlapped hann + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + 10j*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False, + return_onesided=False, scaling=scaling) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, input_onesided=False, + scaling=scaling) + + msg = f'{window}, {nperseg}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + + # Check that asking for onesided switches to twosided + with suppress_warnings() as sup: + sup.filter(UserWarning, + "Input data is complex, switching to return_onesided=False") + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False, + return_onesided=True, scaling=scaling) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, input_onesided=False, scaling=scaling) + + msg = f'{window}, {nperseg}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + + def test_roundtrip_boundary_extension(self): + rng = np.random.RandomState(1234) + + # Test against boxcar, since window is all ones, and thus can be fully + # recovered with no boundary extension + + settings = [ + ('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary=None) + + _, xr = istft(zz, noverlap=noverlap, window=window, boundary=False) + + for boundary in ['even', 'odd', 'constant', 'zeros']: + _, _, zz_ext = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary=boundary) + + _, xr_ext = istft(zz_ext, noverlap=noverlap, window=window, + boundary=True) + + msg = f'{window}, {noverlap}, {boundary}' + assert_allclose(x, xr, err_msg=msg) + assert_allclose(x, xr_ext, err_msg=msg) + + def test_roundtrip_padded_signal(self): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 101, 10, 0), + ('hann', 1000, 256, 128), + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True) + + tr, xr = istft(zz, noverlap=noverlap, window=window) + + msg = f'{window}, {noverlap}' + # Account for possible zero-padding at the end + assert_allclose(t, tr[:t.size], err_msg=msg) + assert_allclose(x, xr[:x.size], err_msg=msg) + + def test_roundtrip_padded_FFT(self): + rng = np.random.RandomState(1234) + + settings = [ + ('hann', 1024, 256, 128, 512), + ('hann', 1024, 256, 128, 501), + ('boxcar', 100, 10, 0, 33), + (('tukey', 0.5), 1152, 256, 64, 1024), + ] + + for window, N, nperseg, noverlap, nfft in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + xc = x*np.exp(1j*np.pi/4) + + # real signal + _, _, z = stft(x, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window, detrend=None, padded=True) + + # complex signal + _, _, zc = stft(xc, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window, detrend=None, padded=True, + return_onesided=False) + + tr, xr = istft(z, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window) + + tr, xcr = istft(zc, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window, input_onesided=False) + + msg = f'{window}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + assert_allclose(xc, xcr, err_msg=msg) + + def test_axis_rolling(self): + rng = np.random.RandomState(1234) + + x_flat = rng.randn(1024) + _, _, z_flat = stft(x_flat) + + for a in range(3): + newshape = [1,]*3 + newshape[a] = -1 + x = x_flat.reshape(newshape) + + _, _, z_plus = stft(x, axis=a) # Positive axis index + _, _, z_minus = stft(x, axis=a-x.ndim) # Negative axis index + + assert_equal(z_flat, z_plus.squeeze(), err_msg=a) + assert_equal(z_flat, z_minus.squeeze(), err_msg=a-x.ndim) + + # z_flat has shape [n_freq, n_time] + + # Test vs. transpose + _, x_transpose_m = istft(z_flat.T, time_axis=-2, freq_axis=-1) + _, x_transpose_p = istft(z_flat.T, time_axis=0, freq_axis=1) + + assert_allclose(x_flat, x_transpose_m, err_msg='istft transpose minus') + assert_allclose(x_flat, x_transpose_p, err_msg='istft transpose plus') + + def test_roundtrip_scaling(self): + """Verify behavior of scaling parameter. """ + # Create 1024 sample cosine signal with amplitude 2: + X = np.zeros(513, dtype=complex) + X[256] = 1024 + x = np.fft.irfft(X) + power_x = sum(x**2) / len(x) # power of signal x is 2 + + # Calculate magnitude-scaled STFT: + Zs = stft(x, boundary='even', scaling='spectrum')[2] + + # Test round trip: + x1 = istft(Zs, boundary=True, scaling='spectrum')[1] + assert_allclose(x1, x) + + # For a Hann-windowed 256 sample length FFT, we expect a peak at + # frequency 64 (since it is 1/4 the length of X) with a height of 1 + # (half the amplitude). A Hann window of a perfectly centered sine has + # the magnitude [..., 0, 0, 0.5, 1, 0.5, 0, 0, ...]. + # Note that in this case the 'even' padding works for the beginning + # but not for the end of the STFT. + assert_allclose(abs(Zs[63, :-1]), 0.5) + assert_allclose(abs(Zs[64, :-1]), 1) + assert_allclose(abs(Zs[65, :-1]), 0.5) + # All other values should be zero: + Zs[63:66, :-1] = 0 + # Note since 'rtol' does not have influence here, atol needs to be set: + assert_allclose(Zs[:, :-1], 0, atol=np.finfo(Zs.dtype).resolution) + + # Calculate two-sided psd-scaled STFT: + # - using 'even' padding since signal is axis symmetric - this ensures + # stationary behavior on the boundaries + # - using the two-sided transform allows determining the spectral + # power by `sum(abs(Zp[:, k])**2) / len(f)` for the k-th time slot. + Zp = stft(x, return_onesided=False, boundary='even', scaling='psd')[2] + + # Calculate spectral power of Zd by summing over the frequency axis: + psd_Zp = np.sum(Zp.real**2 + Zp.imag**2, axis=0) / Zp.shape[0] + # Spectral power of Zp should be equal to the signal's power: + assert_allclose(psd_Zp, power_x) + + # Test round trip: + x1 = istft(Zp, input_onesided=False, boundary=True, scaling='psd')[1] + assert_allclose(x1, x) + + # The power of the one-sided psd-scaled STFT can be determined + # analogously (note that the two sides are not of equal shape): + Zp0 = stft(x, return_onesided=True, boundary='even', scaling='psd')[2] + + # Since x is real, its Fourier transform is conjugate symmetric, i.e., + # the missing 'second side' can be expressed through the 'first side': + Zp1 = np.conj(Zp0[-2:0:-1, :]) # 'second side' is conjugate reversed + assert_allclose(Zp[:129, :], Zp0) + assert_allclose(Zp[129:, :], Zp1) + + # Calculate the spectral power: + s2 = (np.sum(Zp0.real ** 2 + Zp0.imag ** 2, axis=0) + + np.sum(Zp1.real ** 2 + Zp1.imag ** 2, axis=0)) + psd_Zp01 = s2 / (Zp0.shape[0] + Zp1.shape[0]) + assert_allclose(psd_Zp01, power_x) + + # Test round trip: + x1 = istft(Zp0, input_onesided=True, boundary=True, scaling='psd')[1] + assert_allclose(x1, x) + + +class TestSampledSpectralRepresentations: + """Check energy/power relations from `Spectral Analysis` section in the user guide. + + A 32 sample cosine signal is used to compare the numerical to the expected results + stated in :ref:`tutorial_SpectralAnalysis` in + file ``doc/source/tutorial/signal.rst`` + """ + n: int = 32 #: number of samples + T: float = 1/16 #: sampling interval + a_ref: float = 3 #: amplitude of reference + l_a: int = 3 #: index in fft for defining frequency of test signal + + x_ref: np.ndarray #: reference signal + X_ref: np.ndarray #: two-sided FFT of x_ref + E_ref: float #: energy of signal + P_ref: float #: power of signal + + def setup_method(self): + """Create Cosine signal with amplitude a from spectrum. """ + f = rfftfreq(self.n, self.T) + X_ref = np.zeros_like(f) + self.l_a = 3 + X_ref[self.l_a] = self.a_ref/2 * self.n # set amplitude + self.x_ref = irfft(X_ref) + self.X_ref = fft(self.x_ref) + + # Closed form expression for continuous-time signal: + self.E_ref = self.tau * self.a_ref**2 / 2 # energy of signal + self.P_ref = self.a_ref**2 / 2 # power of signal + + @property + def tau(self) -> float: + """Duration of signal. """ + return self.n * self.T + + @property + def delta_f(self) -> float: + """Bin width """ + return 1 / (self.n * self.T) + + def test_reference_signal(self): + """Test energy and power formulas. """ + # Verify that amplitude is a: + assert_allclose(2*self.a_ref, np.ptp(self.x_ref), rtol=0.1) + # Verify that energy expression for sampled signal: + assert_allclose(self.T * sum(self.x_ref ** 2), self.E_ref) + + # Verify that spectral energy and power formulas are correct: + sum_X_ref_squared = sum(self.X_ref.real**2 + self.X_ref.imag**2) + assert_allclose(self.T/self.n * sum_X_ref_squared, self.E_ref) + assert_allclose(1/self.n**2 * sum_X_ref_squared, self.P_ref) + + def test_windowed_DFT(self): + """Verify spectral representations of windowed DFT. + + Furthermore, the scalings of `periodogram` and `welch` are verified. + """ + w = hann(self.n, sym=False) + c_amp, c_rms = abs(sum(w)), np.sqrt(sum(w.real**2 + w.imag**2)) + Xw = fft(self.x_ref*w) # unnormalized windowed DFT + + # Verify that the *spectrum* peak is consistent: + assert_allclose(self.tau * Xw[self.l_a] / c_amp, self.a_ref * self.tau / 2) + # Verify that the *amplitude spectrum* peak is consistent: + assert_allclose(Xw[self.l_a] / c_amp, self.a_ref/2) + + # Verify spectral power/energy equals signal's power/energy: + X_ESD = self.tau * self.T * abs(Xw / c_rms)**2 # Energy Spectral Density + X_PSD = self.T * abs(Xw / c_rms)**2 # Power Spectral Density + assert_allclose(self.delta_f * sum(X_ESD), self.E_ref) + assert_allclose(self.delta_f * sum(X_PSD), self.P_ref) + + # Verify scalings of periodogram: + kw = dict(fs=1/self.T, window=w, detrend=False, return_onesided=False) + _, P_mag = periodogram(self.x_ref, scaling='spectrum', **kw) + _, P_psd = periodogram(self.x_ref, scaling='density', **kw) + + # Verify that periodogram calculates a squared magnitude spectrum: + float_res = np.finfo(P_mag.dtype).resolution + assert_allclose(P_mag, abs(Xw/c_amp)**2, atol=float_res*max(P_mag)) + # Verify that periodogram calculates a PSD: + assert_allclose(P_psd, X_PSD, atol=float_res*max(P_psd)) + + # Ensure that scaling of welch is the same as of periodogram: + kw = dict(nperseg=len(self.x_ref), noverlap=0, **kw) + assert_allclose(welch(self.x_ref, scaling='spectrum', **kw)[1], P_mag, + atol=float_res*max(P_mag)) + assert_allclose(welch(self.x_ref, scaling='density', **kw)[1], P_psd, + atol=float_res*max(P_psd)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py new file mode 100644 index 0000000000000000000000000000000000000000..e1be4083436f457582c7d8229198fd63ff0f9584 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py @@ -0,0 +1,362 @@ +# pylint: disable=missing-docstring +import numpy as np +import pytest +from scipy._lib._array_api import xp_assert_close + +from scipy.signal._spline import ( + symiirorder1_ic, symiirorder2_ic_fwd, symiirorder2_ic_bwd) +from scipy.signal import symiirorder1, symiirorder2 + + +def _compute_symiirorder2_bwd_hs(k, cs, rsq, omega): + cssq = cs * cs + k = np.abs(k) + rsupk = np.power(rsq, k / 2.0) + + c0 = (cssq * (1.0 + rsq) / (1.0 - rsq) / + (1 - 2 * rsq * np.cos(2 * omega) + rsq * rsq)) + gamma = (1.0 - rsq) / (1.0 + rsq) / np.tan(omega) + return c0 * rsupk * (np.cos(omega * k) + gamma * np.sin(omega * k)) + + +class TestSymIIR: + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64, np.complex64, np.complex128]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir1_ic(self, dtype, precision): + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + # Symmetrical initial conditions for a IIR filter of order 1 are: + # x[0] + z1 * \sum{k = 0}^{n - 1} x[k] * z1^k + + # Check the initial condition for a low-pass filter + # with coefficient b = 0.85 on a step signal. The initial condition is + # a geometric series: 1 + b * \sum_{k = 0}^{n - 1} u[k] b^k. + + # Finding the initial condition corresponds to + # 1. Computing the index n such that b**n < precision, which + # corresponds to ceil(log(precision) / log(b)) + # 2. Computing the geometric series until n, this can be computed + # using the partial sum formula: (1 - b**n) / (1 - b) + # This holds due to the input being a step signal. + b = 0.85 + n_exp = int(np.ceil(np.log(c_precision) / np.log(b))) + expected = np.asarray([[(1 - b ** n_exp) / (1 - b)]], dtype=dtype) + expected = 1 + b * expected + + # Create a step signal of size n + 1 + x = np.ones(n_exp + 1, dtype=dtype) + xp_assert_close(symiirorder1_ic(x, b, precision), expected, + atol=2e-6, rtol=2e-7) + + # Check the conditions for a exponential decreasing signal with base 2. + # Same conditions hold, as the product of 0.5^n * 0.85^n is + # still a geometric series + b_d = np.asarray(b, dtype=dtype) + expected = np.asarray( + [[(1 - (0.5 * b_d) ** n_exp) / (1 - (0.5 * b_d))]], dtype=dtype) + expected = 1 + b_d * expected + + # Create an exponential decreasing signal of size n + 1 + x = 2 ** -np.arange(n_exp + 1, dtype=dtype) + xp_assert_close(symiirorder1_ic(x, b, precision), expected, + atol=2e-6, rtol=2e-7) + + def test_symiir1_ic_fails(self): + # Test that symiirorder1_ic fails whenever \sum_{n = 1}^{n} b^n > eps + b = 0.85 + # Create a step signal of size 100 + x = np.ones(100, dtype=np.float64) + + # Compute the closed form for the geometrical series + precision = 1 / (1 - b) + pytest.raises(ValueError, symiirorder1_ic, x, b, precision) + + # Test that symiirorder1_ic fails when |z1| >= 1 + pytest.raises(ValueError, symiirorder1_ic, x, 1.0, -1) + pytest.raises(ValueError, symiirorder1_ic, x, 2.0, -1) + + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64, np.complex64, np.complex128]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir1(self, dtype, precision): + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + # Test for a low-pass filter with c0 = 0.15 and z1 = 0.85 + # using an unit step over 200 samples. + c0 = 0.15 + z1 = 0.85 + n = 200 + signal = np.ones(n, dtype=dtype) + + # Find the initial condition. See test_symiir1_ic for a detailed + # explanation + n_exp = int(np.ceil(np.log(c_precision) / np.log(z1))) + initial = np.asarray((1 - z1 ** n_exp) / (1 - z1), dtype=dtype) + initial = 1 + z1 * initial + + # Forward pass + # The transfer function for the system 1 / (1 - z1 * z^-1) when + # applied to an unit step with initial conditions y0 is + # 1 / (1 - z1 * z^-1) * (z^-1 / (1 - z^-1) + y0) + + # Solving the inverse Z-transform for the given expression yields: + # y[n] = y0 * z1**n * u[n] + + # -z1 / (1 - z1) * z1**(k - 1) * u[k - 1] + + # 1 / (1 - z1) * u[k - 1] + # d is the Kronecker delta function, and u is the unit step + + # y0 * z1**n * u[n] + pos = np.arange(n, dtype=dtype) + comp1 = initial * z1**pos + + # -z1 / (1 - z1) * z1**(k - 1) * u[k - 1] + comp2 = np.zeros(n, dtype=dtype) + comp2[1:] = -z1 / (1 - z1) * z1**pos[:-1] + + # 1 / (1 - z1) * u[k - 1] + comp3 = np.zeros(n, dtype=dtype) + comp3[1:] = 1 / (1 - z1) + + expected_fwd = comp1 + comp2 + comp3 + + # Reverse condition + sym_cond = -c0 / (z1 - 1.0) * expected_fwd[-1] + + # Backward pass + # The transfer function for the forward result is equivalent to + # the forward system times c0 / (1 - z1 * z). + + # Computing a closed form for the complete expression is difficult + # The result will be computed iteratively from the difference equation + exp_out = np.zeros(n, dtype=dtype) + exp_out[0] = sym_cond + + for i in range(1, n): + exp_out[i] = c0 * expected_fwd[n - 1 - i] + z1 * exp_out[i - 1] + + exp_out = exp_out[::-1] + + out = symiirorder1(signal, c0, z1, precision) + xp_assert_close(out, exp_out, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize('dtype', ['float32', 'float64']) + def test_symiir1_values(self, dtype): + rng = np.random.RandomState(1234) + dtype = getattr(np, dtype) + s = rng.uniform(size=16).astype(dtype) + res = symiirorder1(s, 0.5, 0.1) + + # values from scipy 1.9.1 + exp_res = np.array([0.14387447, 0.35166047, 0.29735238, 0.46295986, 0.45174927, + 0.19982875, 0.20355805, 0.47378628, 0.57232247, 0.51597393, + 0.25935107, 0.31438554, 0.41096728, 0.4190693 , 0.25812255, + 0.33671467], dtype=res.dtype) + assert res.dtype == dtype + atol = {np.float64: 1e-15, np.float32: 1e-7}[dtype] + xp_assert_close(res, exp_res, atol=atol) + + s = s + 1j*s + res = symiirorder1(s, 0.5, 0.1) + assert res.dtype == np.complex64 if dtype == np.float32 else np.complex128 + xp_assert_close(res, exp_res + 1j*exp_res, atol=atol) + + @pytest.mark.parametrize( + 'dtype', ['float32', 'float64']) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir2_initial_fwd(self, dtype, precision): + dtype = getattr(np, dtype) + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + # Compute the initial conditions for a order-two symmetrical low-pass + # filter with r = 0.5 and omega = pi / 3 for an unit step input. + r = np.asarray(0.5, dtype=dtype) + omega = np.asarray(np.pi / 3.0, dtype=dtype) + cs = 1 - 2 * r * np.cos(omega) + r**2 + + # The index n for the initial condition is bound from 0 to the + # first position where sin(omega * (n + 2)) = 0 => omega * (n + 2) = pi + # For omega = pi / 3, the maximum initial condition occurs when + # sqrt(3) / 2 * r**n < precision. + # => n = log(2 * sqrt(3) / 3 * precision) / log(r) + ub = np.ceil(np.log(c_precision / np.sin(omega)) / np.log(c_precision)) + lb = np.ceil(np.pi / omega) - 2 + n_exp = min(ub, lb) + + # The forward initial condition for a filter of order two is: + # \frac{cs}{\sin(\omega)} \sum_{n = 0}^{N - 1} { + # r^(n + 1) \sin{\omega(n + 2)}} + cs + # The closed expression for this sum is: + # s[n] = 2 * r * np.cos(omega) - + # r**2 - r**(n + 2) * np.sin(omega * (n + 3)) / np.sin(omega) + + # r**(n + 3) * np.sin(omega * (n + 2)) / np.sin(omega) + cs + fwd_initial_1 = ( + cs + + 2 * r * np.cos(omega) - + r**2 - + r**(n_exp + 2) * np.sin(omega * (n_exp + 3)) / np.sin(omega) + + r**(n_exp + 3) * np.sin(omega * (n_exp + 2)) / np.sin(omega)) + + # The second initial condition is given by + # s[n] = 1 / np.sin(omega) * ( + # r**2 * np.sin(3 * omega) - + # r**3 * np.sin(2 * omega) - + # r**(n + 3) * np.sin(omega * (n + 4)) + + # r**(n + 4) * np.sin(omega * (n + 3))) + ub = np.ceil(np.log(c_precision / np.sin(omega)) / np.log(c_precision)) + lb = np.ceil(np.pi / omega) - 3 + n_exp = min(ub, lb) + + fwd_initial_2 = ( + cs + cs * 2 * r * np.cos(omega) + + (r**2 * np.sin(3 * omega) - + r**3 * np.sin(2 * omega) - + r**(n_exp + 3) * np.sin(omega * (n_exp + 4)) + + r**(n_exp + 4) * np.sin(omega * (n_exp + 3))) / np.sin(omega)) + + expected = np.r_[fwd_initial_1, fwd_initial_2][None, :] + expected = expected.astype(dtype) + + n = 100 + signal = np.ones(n, dtype=dtype) + + out = symiirorder2_ic_fwd(signal, r, omega, precision) + xp_assert_close(out, expected, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir2_initial_bwd(self, dtype, precision): + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + r = np.asarray(0.5, dtype=dtype) + omega = np.asarray(np.pi / 3.0, dtype=dtype) + cs = 1 - 2 * r * np.cos(omega) + r * r + a2 = 2 * r * np.cos(omega) + a3 = -r * r + + n = 100 + signal = np.ones(n, dtype=dtype) + + # Compute initial forward conditions + ic = symiirorder2_ic_fwd(signal, r, omega, precision) + out = np.zeros(n + 2, dtype=dtype) + out[:2] = ic[0] + + # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2)) + for i in range(2, n + 2): + out[i] = cs * signal[i - 2] + a2 * out[i - 1] + a3 * out[i - 2] + + # Find the backward initial conditions + ic2 = np.zeros(2, dtype=dtype) + idx = np.arange(n) + + diff = (_compute_symiirorder2_bwd_hs(idx, cs, r * r, omega) + + _compute_symiirorder2_bwd_hs(idx + 1, cs, r * r, omega)) + ic2_0_all = np.cumsum(diff * out[:1:-1]) + pos = np.where(diff ** 2 < c_precision)[0] + ic2[0] = ic2_0_all[pos[0]] + + diff = (_compute_symiirorder2_bwd_hs(idx - 1, cs, r * r, omega) + + _compute_symiirorder2_bwd_hs(idx + 2, cs, r * r, omega)) + ic2_1_all = np.cumsum(diff * out[:1:-1]) + pos = np.where(diff ** 2 < c_precision)[0] + ic2[1] = ic2_1_all[pos[0]] + + out_ic = symiirorder2_ic_bwd(out, r, omega, precision)[0] + xp_assert_close(out_ic, ic2, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir2(self, dtype, precision): + r = np.asarray(0.5, dtype=dtype) + omega = np.asarray(np.pi / 3.0, dtype=dtype) + cs = 1 - 2 * r * np.cos(omega) + r * r + a2 = 2 * r * np.cos(omega) + a3 = -r * r + + n = 100 + signal = np.ones(n, dtype=dtype) + + # Compute initial forward conditions + ic = symiirorder2_ic_fwd(signal, r, omega, precision) + out1 = np.zeros(n + 2, dtype=dtype) + out1[:2] = ic[0] + + # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2)) + for i in range(2, n + 2): + out1[i] = cs * signal[i - 2] + a2 * out1[i - 1] + a3 * out1[i - 2] + + # Find the backward initial conditions + ic2 = symiirorder2_ic_bwd(out1, r, omega, precision)[0] + + # Apply the system cs / (1 - a2 * z - a3 * z^2)) in backwards + exp = np.empty(n, dtype=dtype) + exp[-2:] = ic2[::-1] + + for i in range(n - 3, -1, -1): + exp[i] = cs * out1[i] + a2 * exp[i + 1] + a3 * exp[i + 2] + + out = symiirorder2(signal, r, omega, precision) + xp_assert_close(out, exp, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize('dtyp', ['float32', 'float64']) + def test_symiir2_values(self, dtyp): + dtyp = getattr(np, dtyp) + rng = np.random.RandomState(1234) + s = rng.uniform(size=16).astype(dtyp) + res = symiirorder2(s, 0.1, 0.1, precision=1e-10) + + # values from scipy 1.9.1 + exp_res = np.array([0.26572609, 0.53408018, 0.51032696, 0.72115829, 0.69486885, + 0.3649055 , 0.37349478, 0.74165032, 0.89718521, 0.80582483, + 0.46758053, 0.51898709, 0.65025605, 0.65394321, 0.45273595, + 0.53539183], dtype=dtyp) + + assert res.dtype == dtyp + # The values in SciPy 1.14 agree with those in SciPy 1.9.1 to this + # accuracy only. Implementation differences are twofold: + # 1. boundary conditions are computed differently + # 2. the filter itself uses sosfilt instead of a hardcoded iteration + # The boundary conditions seem are tested separately (see + # test_symiir2_initial_{fwd,bwd} above, so the difference is likely + # due to a different way roundoff errors accumulate in the filter. + # In that respect, sosfilt is likely doing a better job. + xp_assert_close(res, exp_res, atol=2e-6) + + s = s + 1j*s + with pytest.raises(TypeError): + res = symiirorder2(s, 0.5, 0.1) + + def test_symiir1_integer_input(self): + s = np.where(np.arange(100) % 2, -1, 1) + expected = symiirorder1(s.astype(float), 0.5, 0.5) + out = symiirorder1(s, 0.5, 0.5) + xp_assert_close(out, expected) + + def test_symiir2_integer_input(self): + s = np.where(np.arange(100) % 2, -1, 1) + expected = symiirorder2(s.astype(float), 0.5, np.pi / 3.0) + out = symiirorder2(s, 0.5, np.pi / 3.0) + xp_assert_close(out, expected) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_upfirdn.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_upfirdn.py new file mode 100644 index 0000000000000000000000000000000000000000..0aaec38f06ba72a8bcd984d91b596e98eb3bbc54 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_upfirdn.py @@ -0,0 +1,288 @@ +# Code adapted from "upfirdn" python library with permission: +# +# Copyright (c) 2009, Motorola, Inc +# +# All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the name of Motorola nor the names of its contributors may be +# used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import numpy as np +from itertools import product + +from scipy._lib._array_api import xp_assert_close +from pytest import raises as assert_raises +import pytest + +from scipy.signal import upfirdn, firwin +from scipy.signal._upfirdn import _output_len, _upfirdn_modes +from scipy.signal._upfirdn_apply import _pad_test + + +def upfirdn_naive(x, h, up=1, down=1): + """Naive upfirdn processing in Python. + + Note: arg order (x, h) differs to facilitate apply_along_axis use. + """ + h = np.asarray(h) + out = np.zeros(len(x) * up, x.dtype) + out[::up] = x + out = np.convolve(h, out)[::down][:_output_len(len(h), len(x), up, down)] + return out + + +class UpFIRDnCase: + """Test _UpFIRDn object""" + def __init__(self, up, down, h, x_dtype): + self.up = up + self.down = down + self.h = np.atleast_1d(h) + self.x_dtype = x_dtype + self.rng = np.random.RandomState(17) + + def __call__(self): + # tiny signal + self.scrub(np.ones(1, self.x_dtype)) + # ones + self.scrub(np.ones(10, self.x_dtype)) # ones + # randn + x = self.rng.randn(10).astype(self.x_dtype) + if self.x_dtype in (np.complex64, np.complex128): + x += 1j * self.rng.randn(10) + self.scrub(x) + # ramp + self.scrub(np.arange(10).astype(self.x_dtype)) + # 3D, random + size = (2, 3, 5) + x = self.rng.randn(*size).astype(self.x_dtype) + if self.x_dtype in (np.complex64, np.complex128): + x += 1j * self.rng.randn(*size) + for axis in range(len(size)): + self.scrub(x, axis=axis) + x = x[:, ::2, 1::3].T + for axis in range(len(size)): + self.scrub(x, axis=axis) + + def scrub(self, x, axis=-1): + yr = np.apply_along_axis(upfirdn_naive, axis, x, + self.h, self.up, self.down) + want_len = _output_len(len(self.h), x.shape[axis], self.up, self.down) + assert yr.shape[axis] == want_len + y = upfirdn(self.h, x, self.up, self.down, axis=axis) + assert y.shape[axis] == want_len + assert y.shape == yr.shape + dtypes = (self.h.dtype, x.dtype) + if all(d == np.complex64 for d in dtypes): + assert y.dtype == np.complex64 + elif np.complex64 in dtypes and np.float32 in dtypes: + assert y.dtype == np.complex64 + elif all(d == np.float32 for d in dtypes): + assert y.dtype == np.float32 + elif np.complex128 in dtypes or np.complex64 in dtypes: + assert y.dtype == np.complex128 + else: + assert y.dtype == np.float64 + xp_assert_close(yr.astype(y.dtype), y) + + +_UPFIRDN_TYPES = (int, np.float32, np.complex64, float, complex) + + +class TestUpfirdn: + + def test_valid_input(self): + assert_raises(ValueError, upfirdn, [1], [1], 1, 0) # up or down < 1 + assert_raises(ValueError, upfirdn, [], [1], 1, 1) # h.ndim != 1 + assert_raises(ValueError, upfirdn, [[1]], [1], 1, 1) + + @pytest.mark.parametrize('len_h', [1, 2, 3, 4, 5]) + @pytest.mark.parametrize('len_x', [1, 2, 3, 4, 5]) + def test_singleton(self, len_h, len_x): + # gh-9844: lengths producing expected outputs + h = np.zeros(len_h) + h[len_h // 2] = 1. # make h a delta + x = np.ones(len_x) + y = upfirdn(h, x, 1, 1) + want = np.pad(x, (len_h // 2, (len_h - 1) // 2), 'constant') + xp_assert_close(y, want) + + def test_shift_x(self): + # gh-9844: shifted x can change values? + y = upfirdn([1, 1], [1.], 1, 1) + xp_assert_close(y, np.asarray([1.0, 1.0])) # was [0, 1] in the issue + y = upfirdn([1, 1], [0., 1.], 1, 1) + xp_assert_close(y, np.asarray([0.0, 1.0, 1.0])) + + # A bunch of lengths/factors chosen because they exposed differences + # between the "old way" and new way of computing length, and then + # got `expected` from MATLAB + @pytest.mark.parametrize('len_h, len_x, up, down, expected', [ + (2, 2, 5, 2, [1, 0, 0, 0]), + (2, 3, 6, 3, [1, 0, 1, 0, 1]), + (2, 4, 4, 3, [1, 0, 0, 0, 1]), + (3, 2, 6, 2, [1, 0, 0, 1, 0]), + (4, 11, 3, 5, [1, 0, 0, 1, 0, 0, 1]), + ]) + def test_length_factors(self, len_h, len_x, up, down, expected): + # gh-9844: weird factors + h = np.zeros(len_h) + h[0] = 1. + x = np.ones(len_x) + y = upfirdn(h, x, up, down) + expected = np.asarray(expected, dtype=np.float64) + xp_assert_close(y, expected) + + @pytest.mark.parametrize('down, want_len', [ # lengths from MATLAB + (2, 5015), + (11, 912), + (79, 127), + ]) + def test_vs_convolve(self, down, want_len): + # Check that up=1.0 gives same answer as convolve + slicing + random_state = np.random.RandomState(17) + try_types = (int, np.float32, np.complex64, float, complex) + size = 10000 + + for dtype in try_types: + x = random_state.randn(size).astype(dtype) + if dtype in (np.complex64, np.complex128): + x += 1j * random_state.randn(size) + + h = firwin(31, 1. / down, window='hamming') + yl = upfirdn_naive(x, h, 1, down) + y = upfirdn(h, x, up=1, down=down) + assert y.shape == (want_len,) + assert yl.shape[0] == y.shape[0] + xp_assert_close(yl, y, atol=1e-7, rtol=1e-7) + + @pytest.mark.parametrize('x_dtype', _UPFIRDN_TYPES) + @pytest.mark.parametrize('h', (1., 1j)) + @pytest.mark.parametrize('up, down', [(1, 1), (2, 2), (3, 2), (2, 3)]) + def test_vs_naive_delta(self, x_dtype, h, up, down): + UpFIRDnCase(up, down, h, x_dtype)() + + @pytest.mark.parametrize('x_dtype', _UPFIRDN_TYPES) + @pytest.mark.parametrize('h_dtype', _UPFIRDN_TYPES) + @pytest.mark.parametrize('p_max, q_max', + list(product((10, 100), (10, 100)))) + def test_vs_naive(self, x_dtype, h_dtype, p_max, q_max): + tests = self._random_factors(p_max, q_max, h_dtype, x_dtype) + for test in tests: + test() + + def _random_factors(self, p_max, q_max, h_dtype, x_dtype): + n_rep = 3 + longest_h = 25 + random_state = np.random.RandomState(17) + tests = [] + + for _ in range(n_rep): + # Randomize the up/down factors somewhat + p_add = q_max if p_max > q_max else 1 + q_add = p_max if q_max > p_max else 1 + p = random_state.randint(p_max) + p_add + q = random_state.randint(q_max) + q_add + + # Generate random FIR coefficients + len_h = random_state.randint(longest_h) + 1 + h = np.atleast_1d(random_state.randint(len_h)) + h = h.astype(h_dtype) + if h_dtype is complex: + h += 1j * random_state.randint(len_h) + + tests.append(UpFIRDnCase(p, q, h, x_dtype)) + + return tests + + @pytest.mark.parametrize('mode', _upfirdn_modes) + def test_extensions(self, mode): + """Test vs. manually computed results for modes not in numpy's pad.""" + x = np.array([1, 2, 3, 1], dtype=float) + npre, npost = 6, 6 + y = _pad_test(x, npre=npre, npost=npost, mode=mode) + if mode == 'antisymmetric': + y_expected = np.asarray( + [3.0, 1, -1, -3, -2, -1, 1, 2, 3, 1, -1, -3, -2, -1, 1, 2]) + elif mode == 'antireflect': + y_expected = np.asarray( + [1.0, 2, 3, 1, -1, 0, 1, 2, 3, 1, -1, 0, 1, 2, 3, 1]) + elif mode == 'smooth': + y_expected = np.asarray( + [-5.0, -4, -3, -2, -1, 0, 1, 2, 3, 1, -1, -3, -5, -7, -9, -11]) + elif mode == "line": + lin_slope = (x[-1] - x[0]) / (len(x) - 1) + left = x[0] + np.arange(-npre, 0, 1) * lin_slope + right = x[-1] + np.arange(1, npost + 1) * lin_slope + y_expected = np.concatenate((left, x, right)) + else: + y_expected = np.pad(x, (npre, npost), mode=mode) + xp_assert_close(y, y_expected) + + @pytest.mark.parametrize( + 'size, h_len, mode, dtype', + product( + [8], + [4, 5, 26], # include cases with h_len > 2*size + _upfirdn_modes, + [np.float32, np.float64, np.complex64, np.complex128], + ) + ) + def test_modes(self, size, h_len, mode, dtype): + random_state = np.random.RandomState(5) + x = random_state.randn(size).astype(dtype) + if dtype in (np.complex64, np.complex128): + x += 1j * random_state.randn(size) + h = np.arange(1, 1 + h_len, dtype=x.real.dtype) + + y = upfirdn(h, x, up=1, down=1, mode=mode) + # expected result: pad the input, filter with zero padding, then crop + npad = h_len - 1 + if mode in ['antisymmetric', 'antireflect', 'smooth', 'line']: + # use _pad_test test function for modes not supported by np.pad. + xpad = _pad_test(x, npre=npad, npost=npad, mode=mode) + else: + xpad = np.pad(x, npad, mode=mode) + ypad = upfirdn(h, xpad, up=1, down=1, mode='constant') + y_expected = ypad[npad:-npad] + + atol = rtol = np.finfo(dtype).eps * 1e2 + xp_assert_close(y, y_expected, atol=atol, rtol=rtol) + + +def test_output_len_long_input(): + # Regression test for gh-17375. On Windows, a large enough input + # that should have been well within the capabilities of 64 bit integers + # would result in a 32 bit overflow because of a bug in Cython 0.29.32. + len_h = 1001 + in_len = 10**8 + up = 320 + down = 441 + out_len = _output_len(len_h, in_len, up, down) + # The expected value was computed "by hand" from the formula + # (((in_len - 1) * up + len_h) - 1) // down + 1 + assert out_len == 72562360 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_waveforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_waveforms.py new file mode 100644 index 0000000000000000000000000000000000000000..b30f7b9ceba80822f05ecfcabaad76fb87d5f335 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_waveforms.py @@ -0,0 +1,380 @@ +import numpy as np +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + assert_almost_equal, xp_assert_equal, xp_assert_close +) + +import scipy.signal._waveforms as waveforms + + +# These chirp_* functions are the instantaneous frequencies of the signals +# returned by chirp(). + +def chirp_linear(t, f0, f1, t1): + f = f0 + (f1 - f0) * t / t1 + return f + + +def chirp_quadratic(t, f0, f1, t1, vertex_zero=True): + if vertex_zero: + f = f0 + (f1 - f0) * t**2 / t1**2 + else: + f = f1 - (f1 - f0) * (t1 - t)**2 / t1**2 + return f + + +def chirp_geometric(t, f0, f1, t1): + f = f0 * (f1/f0)**(t/t1) + return f + + +def chirp_hyperbolic(t, f0, f1, t1): + f = f0*f1*t1 / ((f0 - f1)*t + f1*t1) + return f + + +def compute_frequency(t, theta): + """ + Compute theta'(t)/(2*pi), where theta'(t) is the derivative of theta(t). + """ + # Assume theta and t are 1-D NumPy arrays. + # Assume that t is uniformly spaced. + dt = t[1] - t[0] + f = np.diff(theta)/(2*np.pi) / dt + tf = 0.5*(t[1:] + t[:-1]) + return tf, f + + +class TestChirp: + + def test_linear_at_zero(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='linear') + assert_almost_equal(w, 1.0) + + def test_linear_freq_01(self): + method = 'linear' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 100) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_linear(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_linear_freq_02(self): + method = 'linear' + f0 = 200.0 + f1 = 100.0 + t1 = 10.0 + t = np.linspace(0, t1, 100) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_linear(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_linear_complex_power(self): + method = 'linear' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 100) + w_real = waveforms.chirp(t, f0, t1, f1, method, complex=False) + w_complex = waveforms.chirp(t, f0, t1, f1, method, complex=True) + w_pwr_r = np.var(w_real) + w_pwr_c = np.var(w_complex) + + # Making sure that power of the real part is not affected with + # complex conversion operation + err = w_pwr_r - np.real(w_pwr_c) + + assert(err < 1e-6) + + def test_linear_complex_at_zero(self): + w = waveforms.chirp(t=0, f0=-10.0, f1=1.0, t1=1.0, method='linear', + complex=True) + xp_assert_close(w, 1.0+0.0j) # dtype must match + + def test_quadratic_at_zero(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='quadratic') + assert_almost_equal(w, 1.0) + + def test_quadratic_at_zero2(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='quadratic', + vertex_zero=False) + assert_almost_equal(w, 1.0) + + def test_quadratic_complex_at_zero(self): + w = waveforms.chirp(t=0, f0=-1.0, f1=2.0, t1=1.0, method='quadratic', + complex=True) + xp_assert_close(w, 1.0+0j) + + def test_quadratic_freq_01(self): + method = 'quadratic' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 2000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_quadratic(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_quadratic_freq_02(self): + method = 'quadratic' + f0 = 20.0 + f1 = 10.0 + t1 = 10.0 + t = np.linspace(0, t1, 2000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_quadratic(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_logarithmic_at_zero(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='logarithmic') + assert_almost_equal(w, 1.0) + + def test_logarithmic_freq_01(self): + method = 'logarithmic' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 10000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_logarithmic_freq_02(self): + method = 'logarithmic' + f0 = 200.0 + f1 = 100.0 + t1 = 10.0 + t = np.linspace(0, t1, 10000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_logarithmic_freq_03(self): + method = 'logarithmic' + f0 = 100.0 + f1 = 100.0 + t1 = 10.0 + t = np.linspace(0, t1, 10000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_hyperbolic_at_zero(self): + w = waveforms.chirp(t=0, f0=10.0, f1=1.0, t1=1.0, method='hyperbolic') + assert_almost_equal(w, 1.0) + + def test_hyperbolic_freq_01(self): + method = 'hyperbolic' + t1 = 1.0 + t = np.linspace(0, t1, 10000) + # f0 f1 + cases = [[10.0, 1.0], + [1.0, 10.0], + [-10.0, -1.0], + [-1.0, -10.0]] + for f0, f1 in cases: + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + expected = chirp_hyperbolic(tf, f0, f1, t1) + xp_assert_close(f, expected, atol=1e-7) + + def test_hyperbolic_zero_freq(self): + # f0=0 or f1=0 must raise a ValueError. + method = 'hyperbolic' + t1 = 1.0 + t = np.linspace(0, t1, 5) + assert_raises(ValueError, waveforms.chirp, t, 0, t1, 1, method) + assert_raises(ValueError, waveforms.chirp, t, 1, t1, 0, method) + + def test_unknown_method(self): + method = "foo" + f0 = 10.0 + f1 = 20.0 + t1 = 1.0 + t = np.linspace(0, t1, 10) + assert_raises(ValueError, waveforms.chirp, t, f0, t1, f1, method) + + def test_integer_t1(self): + f0 = 10.0 + f1 = 20.0 + t = np.linspace(-1, 1, 11) + t1 = 3.0 + float_result = waveforms.chirp(t, f0, t1, f1) + t1 = 3 + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 't1=3' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_f0(self): + f1 = 20.0 + t1 = 3.0 + t = np.linspace(-1, 1, 11) + f0 = 10.0 + float_result = waveforms.chirp(t, f0, t1, f1) + f0 = 10 + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 'f0=10' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_f1(self): + f0 = 10.0 + t1 = 3.0 + t = np.linspace(-1, 1, 11) + f1 = 20.0 + float_result = waveforms.chirp(t, f0, t1, f1) + f1 = 20 + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 'f1=20' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_all(self): + f0 = 10 + t1 = 3 + f1 = 20 + t = np.linspace(-1, 1, 11) + float_result = waveforms.chirp(t, float(f0), float(t1), float(f1)) + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 'f0=10, t1=3, f1=20' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + +class TestSweepPoly: + + def test_sweep_poly_quad1(self): + p = np.poly1d([1.0, 0.0, 1.0]) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_const(self): + p = np.poly1d(2.0) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_linear(self): + p = np.poly1d([-1.0, 10.0]) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_quad2(self): + p = np.poly1d([1.0, 0.0, -2.0]) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_cubic(self): + p = np.poly1d([2.0, 1.0, 0.0, -2.0]) + t = np.linspace(0, 2.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_cubic2(self): + """Use an array of coefficients instead of a poly1d.""" + p = np.array([2.0, 1.0, 0.0, -2.0]) + t = np.linspace(0, 2.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = np.poly1d(p)(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_cubic3(self): + """Use a list of coefficients instead of a poly1d.""" + p = [2.0, 1.0, 0.0, -2.0] + t = np.linspace(0, 2.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = np.poly1d(p)(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + +class TestGaussPulse: + + def test_integer_fc(self): + float_result = waveforms.gausspulse('cutoff', fc=1000.0) + int_result = waveforms.gausspulse('cutoff', fc=1000) + err_msg = "Integer input 'fc=1000' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_bw(self): + float_result = waveforms.gausspulse('cutoff', bw=1.0) + int_result = waveforms.gausspulse('cutoff', bw=1) + err_msg = "Integer input 'bw=1' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_bwr(self): + float_result = waveforms.gausspulse('cutoff', bwr=-6.0) + int_result = waveforms.gausspulse('cutoff', bwr=-6) + err_msg = "Integer input 'bwr=-6' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_tpr(self): + float_result = waveforms.gausspulse('cutoff', tpr=-60.0) + int_result = waveforms.gausspulse('cutoff', tpr=-60) + err_msg = "Integer input 'tpr=-60' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + +class TestUnitImpulse: + + def test_no_index(self): + xp_assert_equal(waveforms.unit_impulse(7), + np.asarray([1.0, 0, 0, 0, 0, 0, 0])) + xp_assert_equal(waveforms.unit_impulse((3, 3)), + np.asarray([[1.0, 0, 0], [0, 0, 0], [0, 0, 0]])) + + def test_index(self): + xp_assert_equal(waveforms.unit_impulse(10, 3), + np.asarray([0.0, 0, 0, 1, 0, 0, 0, 0, 0, 0])) + xp_assert_equal(waveforms.unit_impulse((3, 3), (1, 1)), + np.asarray([[0.0, 0, 0], [0, 1, 0], [0, 0, 0]])) + + # Broadcasting + imp = waveforms.unit_impulse((4, 4), 2) + xp_assert_equal(imp, np.asarray([[0.0, 0, 0, 0], + [0.0, 0, 0, 0], + [0.0, 0, 1, 0], + [0.0, 0, 0, 0]])) + + def test_mid(self): + xp_assert_equal(waveforms.unit_impulse((3, 3), 'mid'), + np.asarray([[0.0, 0, 0], [0, 1, 0], [0, 0, 0]])) + xp_assert_equal(waveforms.unit_impulse(9, 'mid'), + np.asarray([0.0, 0, 0, 0, 1, 0, 0, 0, 0])) + + def test_dtype(self): + imp = waveforms.unit_impulse(7) + assert np.issubdtype(imp.dtype, np.floating) + + imp = waveforms.unit_impulse(5, 3, dtype=int) + assert np.issubdtype(imp.dtype, np.integer) + + imp = waveforms.unit_impulse((5, 2), (3, 1), dtype=complex) + assert np.issubdtype(imp.dtype, np.complexfloating) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_wavelets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_wavelets.py new file mode 100644 index 0000000000000000000000000000000000000000..7a357d2eaf4a530930d612358b8ca69a18b5248e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_wavelets.py @@ -0,0 +1,59 @@ +import numpy as np +from numpy.testing import assert_array_equal, assert_array_almost_equal + +import scipy.signal._wavelets as wavelets + + +class TestWavelets: + def test_ricker(self): + w = wavelets._ricker(1.0, 1) + expected = 2 / (np.sqrt(3 * 1.0) * (np.pi ** 0.25)) + assert_array_equal(w, expected) + + lengths = [5, 11, 15, 51, 101] + for length in lengths: + w = wavelets._ricker(length, 1.0) + assert len(w) == length + max_loc = np.argmax(w) + assert max_loc == (length // 2) + + points = 100 + w = wavelets._ricker(points, 2.0) + half_vec = np.arange(0, points // 2) + # Wavelet should be symmetric + assert_array_almost_equal(w[half_vec], w[-(half_vec + 1)]) + + # Check zeros + aas = [5, 10, 15, 20, 30] + points = 99 + for a in aas: + w = wavelets._ricker(points, a) + vec = np.arange(0, points) - (points - 1.0) / 2 + exp_zero1 = np.argmin(np.abs(vec - a)) + exp_zero2 = np.argmin(np.abs(vec + a)) + assert_array_almost_equal(w[exp_zero1], 0) + assert_array_almost_equal(w[exp_zero2], 0) + + def test_cwt(self): + widths = [1.0] + def delta_wavelet(s, t): + return np.array([1]) + len_data = 100 + test_data = np.sin(np.pi * np.arange(0, len_data) / 10.0) + + # Test delta function input gives same data as output + cwt_dat = wavelets._cwt(test_data, delta_wavelet, widths) + assert cwt_dat.shape == (len(widths), len_data) + assert_array_almost_equal(test_data, cwt_dat.flatten()) + + # Check proper shape on output + widths = [1, 3, 4, 5, 10] + cwt_dat = wavelets._cwt(test_data, wavelets._ricker, widths) + assert cwt_dat.shape == (len(widths), len_data) + + widths = [len_data * 10] + # Note: this wavelet isn't defined quite right, but is fine for this test + def flat_wavelet(l, w): + return np.full(w, 1 / w) + cwt_dat = wavelets._cwt(test_data, flat_wavelet, widths) + assert_array_almost_equal(cwt_dat, np.mean(test_data)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_windows.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_windows.py new file mode 100644 index 0000000000000000000000000000000000000000..75c4da5327f0c1a806f72865687927bc7a380c6d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_windows.py @@ -0,0 +1,846 @@ +import numpy as np +from numpy import array +from numpy.testing import (assert_array_almost_equal, assert_array_equal, + assert_allclose, + assert_equal, assert_, assert_array_less, + suppress_warnings) +from pytest import raises as assert_raises + +from scipy.fft import fft +from scipy.signal import windows, get_window, resample + + +window_funcs = [ + ('boxcar', ()), + ('triang', ()), + ('parzen', ()), + ('bohman', ()), + ('blackman', ()), + ('nuttall', ()), + ('blackmanharris', ()), + ('flattop', ()), + ('bartlett', ()), + ('barthann', ()), + ('hamming', ()), + ('kaiser', (1,)), + ('dpss', (2,)), + ('gaussian', (0.5,)), + ('general_gaussian', (1.5, 2)), + ('chebwin', (1,)), + ('cosine', ()), + ('hann', ()), + ('exponential', ()), + ('taylor', ()), + ('tukey', (0.5,)), + ('lanczos', ()), + ] + + +class TestBartHann: + + def test_basic(self): + assert_allclose(windows.barthann(6, sym=True), + [0, 0.35857354213752, 0.8794264578624801, + 0.8794264578624801, 0.3585735421375199, 0], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.barthann(7), + [0, 0.27, 0.73, 1.0, 0.73, 0.27, 0], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.barthann(6, False), + [0, 0.27, 0.73, 1.0, 0.73, 0.27], + rtol=1e-15, atol=1e-15) + + +class TestBartlett: + + def test_basic(self): + assert_allclose(windows.bartlett(6), [0, 0.4, 0.8, 0.8, 0.4, 0]) + assert_allclose(windows.bartlett(7), [0, 1/3, 2/3, 1.0, 2/3, 1/3, 0]) + assert_allclose(windows.bartlett(6, False), + [0, 1/3, 2/3, 1.0, 2/3, 1/3]) + + +class TestBlackman: + + def test_basic(self): + assert_allclose(windows.blackman(6, sym=False), + [0, 0.13, 0.63, 1.0, 0.63, 0.13], atol=1e-14) + assert_allclose(windows.blackman(7, sym=False), + [0, 0.09045342435412804, 0.4591829575459636, + 0.9203636180999081, 0.9203636180999081, + 0.4591829575459636, 0.09045342435412804], atol=1e-8) + assert_allclose(windows.blackman(6), + [0, 0.2007701432625305, 0.8492298567374694, + 0.8492298567374694, 0.2007701432625305, 0], + atol=1e-14) + assert_allclose(windows.blackman(7, True), + [0, 0.13, 0.63, 1.0, 0.63, 0.13, 0], atol=1e-14) + + +class TestBlackmanHarris: + + def test_basic(self): + assert_allclose(windows.blackmanharris(6, False), + [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645]) + assert_allclose(windows.blackmanharris(7, sym=False), + [6.0e-05, 0.03339172347815117, 0.332833504298565, + 0.8893697722232837, 0.8893697722232838, + 0.3328335042985652, 0.03339172347815122]) + assert_allclose(windows.blackmanharris(6), + [6.0e-05, 0.1030114893456638, 0.7938335106543362, + 0.7938335106543364, 0.1030114893456638, 6.0e-05]) + assert_allclose(windows.blackmanharris(7, sym=True), + [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645, + 6.0e-05]) + + +class TestTaylor: + + def test_normalized(self): + """Tests windows of small length that are normalized to 1. See the + documentation for the Taylor window for more information on + normalization. + """ + assert_allclose(windows.taylor(1, 2, 15), 1.0) + assert_allclose( + windows.taylor(5, 2, 15), + np.array([0.75803341, 0.90757699, 1.0, 0.90757699, 0.75803341]) + ) + assert_allclose( + windows.taylor(6, 2, 15), + np.array([ + 0.7504082, 0.86624416, 0.98208011, 0.98208011, 0.86624416, + 0.7504082 + ]) + ) + + def test_non_normalized(self): + """Test windows of small length that are not normalized to 1. See + the documentation for the Taylor window for more information on + normalization. + """ + assert_allclose( + windows.taylor(5, 2, 15, norm=False), + np.array([ + 0.87508054, 1.04771499, 1.15440894, 1.04771499, 0.87508054 + ]) + ) + assert_allclose( + windows.taylor(6, 2, 15, norm=False), + np.array([ + 0.86627793, 1.0, 1.13372207, 1.13372207, 1.0, 0.86627793 + ]) + ) + + def test_correctness(self): + """This test ensures the correctness of the implemented Taylor + Windowing function. A Taylor Window of 1024 points is created, its FFT + is taken, and the Peak Sidelobe Level (PSLL) and 3dB and 18dB bandwidth + are found and checked. + + A publication from Sandia National Laboratories was used as reference + for the correctness values [1]_. + + References + ----- + .. [1] Armin Doerry, "Catalog of Window Taper Functions for + Sidelobe Control", 2017. + https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf + """ + M_win = 1024 + N_fft = 131072 + # Set norm=False for correctness as the values obtained from the + # scientific publication do not normalize the values. Normalizing + # changes the sidelobe level from the desired value. + w = windows.taylor(M_win, nbar=4, sll=35, norm=False, sym=False) + f = fft(w, N_fft) + spec = 20 * np.log10(np.abs(f / np.amax(f))) + + first_zero = np.argmax(np.diff(spec) > 0) + + PSLL = np.amax(spec[first_zero:-first_zero]) + + BW_3dB = 2*np.argmax(spec <= -3.0102999566398121) / N_fft * M_win + BW_18dB = 2*np.argmax(spec <= -18.061799739838872) / N_fft * M_win + + assert_allclose(PSLL, -35.1672, atol=1) + assert_allclose(BW_3dB, 1.1822, atol=0.1) + assert_allclose(BW_18dB, 2.6112, atol=0.1) + + +class TestBohman: + + def test_basic(self): + assert_allclose(windows.bohman(6), + [0, 0.1791238937062839, 0.8343114522576858, + 0.8343114522576858, 0.1791238937062838, 0]) + assert_allclose(windows.bohman(7, sym=True), + [0, 0.1089977810442293, 0.6089977810442293, 1.0, + 0.6089977810442295, 0.1089977810442293, 0]) + assert_allclose(windows.bohman(6, False), + [0, 0.1089977810442293, 0.6089977810442293, 1.0, + 0.6089977810442295, 0.1089977810442293]) + + +class TestBoxcar: + + def test_basic(self): + assert_allclose(windows.boxcar(6), [1, 1, 1, 1, 1, 1]) + assert_allclose(windows.boxcar(7), [1, 1, 1, 1, 1, 1, 1]) + assert_allclose(windows.boxcar(6, False), [1, 1, 1, 1, 1, 1]) + + +cheb_odd_true = array([0.200938, 0.107729, 0.134941, 0.165348, + 0.198891, 0.235450, 0.274846, 0.316836, + 0.361119, 0.407338, 0.455079, 0.503883, + 0.553248, 0.602637, 0.651489, 0.699227, + 0.745266, 0.789028, 0.829947, 0.867485, + 0.901138, 0.930448, 0.955010, 0.974482, + 0.988591, 0.997138, 1.000000, 0.997138, + 0.988591, 0.974482, 0.955010, 0.930448, + 0.901138, 0.867485, 0.829947, 0.789028, + 0.745266, 0.699227, 0.651489, 0.602637, + 0.553248, 0.503883, 0.455079, 0.407338, + 0.361119, 0.316836, 0.274846, 0.235450, + 0.198891, 0.165348, 0.134941, 0.107729, + 0.200938]) + +cheb_even_true = array([0.203894, 0.107279, 0.133904, + 0.163608, 0.196338, 0.231986, + 0.270385, 0.311313, 0.354493, + 0.399594, 0.446233, 0.493983, + 0.542378, 0.590916, 0.639071, + 0.686302, 0.732055, 0.775783, + 0.816944, 0.855021, 0.889525, + 0.920006, 0.946060, 0.967339, + 0.983557, 0.994494, 1.000000, + 1.000000, 0.994494, 0.983557, + 0.967339, 0.946060, 0.920006, + 0.889525, 0.855021, 0.816944, + 0.775783, 0.732055, 0.686302, + 0.639071, 0.590916, 0.542378, + 0.493983, 0.446233, 0.399594, + 0.354493, 0.311313, 0.270385, + 0.231986, 0.196338, 0.163608, + 0.133904, 0.107279, 0.203894]) + + +class TestChebWin: + + def test_basic(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + assert_allclose(windows.chebwin(6, 100), + [0.1046401879356917, 0.5075781475823447, 1.0, 1.0, + 0.5075781475823447, 0.1046401879356917]) + assert_allclose(windows.chebwin(7, 100), + [0.05650405062850233, 0.316608530648474, + 0.7601208123539079, 1.0, 0.7601208123539079, + 0.316608530648474, 0.05650405062850233]) + assert_allclose(windows.chebwin(6, 10), + [1.0, 0.6071201674458373, 0.6808391469897297, + 0.6808391469897297, 0.6071201674458373, 1.0]) + assert_allclose(windows.chebwin(7, 10), + [1.0, 0.5190521247588651, 0.5864059018130382, + 0.6101519801307441, 0.5864059018130382, + 0.5190521247588651, 1.0]) + assert_allclose(windows.chebwin(6, 10, False), + [1.0, 0.5190521247588651, 0.5864059018130382, + 0.6101519801307441, 0.5864059018130382, + 0.5190521247588651]) + + def test_cheb_odd_high_attenuation(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_odd = windows.chebwin(53, at=-40) + assert_array_almost_equal(cheb_odd, cheb_odd_true, decimal=4) + + def test_cheb_even_high_attenuation(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_even = windows.chebwin(54, at=40) + assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4) + + def test_cheb_odd_low_attenuation(self): + cheb_odd_low_at_true = array([1.000000, 0.519052, 0.586405, + 0.610151, 0.586405, 0.519052, + 1.000000]) + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_odd = windows.chebwin(7, at=10) + assert_array_almost_equal(cheb_odd, cheb_odd_low_at_true, decimal=4) + + def test_cheb_even_low_attenuation(self): + cheb_even_low_at_true = array([1.000000, 0.451924, 0.51027, + 0.541338, 0.541338, 0.51027, + 0.451924, 1.000000]) + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_even = windows.chebwin(8, at=-10) + assert_array_almost_equal(cheb_even, cheb_even_low_at_true, decimal=4) + + +exponential_data = { + (4, None, 0.2, False): + array([4.53999297624848542e-05, + 6.73794699908546700e-03, 1.00000000000000000e+00, + 6.73794699908546700e-03]), + (4, None, 0.2, True): array([0.00055308437014783, 0.0820849986238988, + 0.0820849986238988, 0.00055308437014783]), + (4, None, 1.0, False): array([0.1353352832366127, 0.36787944117144233, 1., + 0.36787944117144233]), + (4, None, 1.0, True): array([0.22313016014842982, 0.60653065971263342, + 0.60653065971263342, 0.22313016014842982]), + (4, 2, 0.2, False): + array([4.53999297624848542e-05, 6.73794699908546700e-03, + 1.00000000000000000e+00, 6.73794699908546700e-03]), + (4, 2, 0.2, True): None, + (4, 2, 1.0, False): array([0.1353352832366127, 0.36787944117144233, 1., + 0.36787944117144233]), + (4, 2, 1.0, True): None, + (5, None, 0.2, True): + array([4.53999297624848542e-05, + 6.73794699908546700e-03, 1.00000000000000000e+00, + 6.73794699908546700e-03, 4.53999297624848542e-05]), + (5, None, 1.0, True): array([0.1353352832366127, 0.36787944117144233, 1., + 0.36787944117144233, 0.1353352832366127]), + (5, 2, 0.2, True): None, + (5, 2, 1.0, True): None +} + + +def test_exponential(): + for k, v in exponential_data.items(): + if v is None: + assert_raises(ValueError, windows.exponential, *k) + else: + win = windows.exponential(*k) + assert_allclose(win, v, rtol=1e-14) + + +class TestFlatTop: + + def test_basic(self): + assert_allclose(windows.flattop(6, sym=False), + [-0.000421051, -0.051263156, 0.19821053, 1.0, + 0.19821053, -0.051263156]) + assert_allclose(windows.flattop(7, sym=False), + [-0.000421051, -0.03684078115492348, + 0.01070371671615342, 0.7808739149387698, + 0.7808739149387698, 0.01070371671615342, + -0.03684078115492348]) + assert_allclose(windows.flattop(6), + [-0.000421051, -0.0677142520762119, 0.6068721525762117, + 0.6068721525762117, -0.0677142520762119, + -0.000421051]) + assert_allclose(windows.flattop(7, True), + [-0.000421051, -0.051263156, 0.19821053, 1.0, + 0.19821053, -0.051263156, -0.000421051]) + + +class TestGaussian: + + def test_basic(self): + assert_allclose(windows.gaussian(6, 1.0), + [0.04393693362340742, 0.3246524673583497, + 0.8824969025845955, 0.8824969025845955, + 0.3246524673583497, 0.04393693362340742]) + assert_allclose(windows.gaussian(7, 1.2), + [0.04393693362340742, 0.2493522087772962, + 0.7066482778577162, 1.0, 0.7066482778577162, + 0.2493522087772962, 0.04393693362340742]) + assert_allclose(windows.gaussian(7, 3), + [0.6065306597126334, 0.8007374029168081, + 0.9459594689067654, 1.0, 0.9459594689067654, + 0.8007374029168081, 0.6065306597126334]) + assert_allclose(windows.gaussian(6, 3, False), + [0.6065306597126334, 0.8007374029168081, + 0.9459594689067654, 1.0, 0.9459594689067654, + 0.8007374029168081]) + + +class TestGeneralCosine: + + def test_basic(self): + assert_allclose(windows.general_cosine(5, [0.5, 0.3, 0.2]), + [0.4, 0.3, 1, 0.3, 0.4]) + assert_allclose(windows.general_cosine(4, [0.5, 0.3, 0.2], sym=False), + [0.4, 0.3, 1, 0.3]) + + +class TestGeneralHamming: + + def test_basic(self): + assert_allclose(windows.general_hamming(5, 0.7), + [0.4, 0.7, 1.0, 0.7, 0.4]) + assert_allclose(windows.general_hamming(5, 0.75, sym=False), + [0.5, 0.6727457514, 0.9522542486, + 0.9522542486, 0.6727457514]) + assert_allclose(windows.general_hamming(6, 0.75, sym=True), + [0.5, 0.6727457514, 0.9522542486, + 0.9522542486, 0.6727457514, 0.5]) + + +class TestHamming: + + def test_basic(self): + assert_allclose(windows.hamming(6, False), + [0.08, 0.31, 0.77, 1.0, 0.77, 0.31]) + assert_allclose(windows.hamming(7, sym=False), + [0.08, 0.2531946911449826, 0.6423596296199047, + 0.9544456792351128, 0.9544456792351128, + 0.6423596296199047, 0.2531946911449826]) + assert_allclose(windows.hamming(6), + [0.08, 0.3978521825875242, 0.9121478174124757, + 0.9121478174124757, 0.3978521825875242, 0.08]) + assert_allclose(windows.hamming(7, sym=True), + [0.08, 0.31, 0.77, 1.0, 0.77, 0.31, 0.08]) + + +class TestHann: + + def test_basic(self): + assert_allclose(windows.hann(6, sym=False), + [0, 0.25, 0.75, 1.0, 0.75, 0.25], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.hann(7, sym=False), + [0, 0.1882550990706332, 0.6112604669781572, + 0.9504844339512095, 0.9504844339512095, + 0.6112604669781572, 0.1882550990706332], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.hann(6, True), + [0, 0.3454915028125263, 0.9045084971874737, + 0.9045084971874737, 0.3454915028125263, 0], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.hann(7), + [0, 0.25, 0.75, 1.0, 0.75, 0.25, 0], + rtol=1e-15, atol=1e-15) + + +class TestKaiser: + + def test_basic(self): + assert_allclose(windows.kaiser(6, 0.5), + [0.9403061933191572, 0.9782962393705389, + 0.9975765035372042, 0.9975765035372042, + 0.9782962393705389, 0.9403061933191572]) + assert_allclose(windows.kaiser(7, 0.5), + [0.9403061933191572, 0.9732402256999829, + 0.9932754654413773, 1.0, 0.9932754654413773, + 0.9732402256999829, 0.9403061933191572]) + assert_allclose(windows.kaiser(6, 2.7), + [0.2603047507678832, 0.6648106293528054, + 0.9582099802511439, 0.9582099802511439, + 0.6648106293528054, 0.2603047507678832]) + assert_allclose(windows.kaiser(7, 2.7), + [0.2603047507678832, 0.5985765418119844, + 0.8868495172060835, 1.0, 0.8868495172060835, + 0.5985765418119844, 0.2603047507678832]) + assert_allclose(windows.kaiser(6, 2.7, False), + [0.2603047507678832, 0.5985765418119844, + 0.8868495172060835, 1.0, 0.8868495172060835, + 0.5985765418119844]) + + +class TestKaiserBesselDerived: + + def test_basic(self): + M = 100 + w = windows.kaiser_bessel_derived(M, beta=4.0) + w2 = windows.get_window(('kaiser bessel derived', 4.0), + M, fftbins=False) + assert_allclose(w, w2) + + # Test for Princen-Bradley condition + assert_allclose(w[:M // 2] ** 2 + w[-M // 2:] ** 2, 1.) + + # Test actual values from other implementations + # M = 2: sqrt(2) / 2 + # M = 4: 0.518562710536, 0.855039598640 + # M = 6: 0.436168993154, 0.707106781187, 0.899864772847 + # Ref:https://github.com/scipy/scipy/pull/4747#issuecomment-172849418 + assert_allclose(windows.kaiser_bessel_derived(2, beta=np.pi / 2)[:1], + np.sqrt(2) / 2) + + assert_allclose(windows.kaiser_bessel_derived(4, beta=np.pi / 2)[:2], + [0.518562710536, 0.855039598640]) + + assert_allclose(windows.kaiser_bessel_derived(6, beta=np.pi / 2)[:3], + [0.436168993154, 0.707106781187, 0.899864772847]) + + def test_exceptions(self): + M = 100 + # Assert ValueError for odd window length + msg = ("Kaiser-Bessel Derived windows are only defined for even " + "number of points") + with assert_raises(ValueError, match=msg): + windows.kaiser_bessel_derived(M + 1, beta=4.) + + # Assert ValueError for non-symmetric setting + msg = ("Kaiser-Bessel Derived windows are only defined for " + "symmetric shapes") + with assert_raises(ValueError, match=msg): + windows.kaiser_bessel_derived(M + 1, beta=4., sym=False) + + +class TestNuttall: + + def test_basic(self): + assert_allclose(windows.nuttall(6, sym=False), + [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, + 0.0613345]) + assert_allclose(windows.nuttall(7, sym=False), + [0.0003628, 0.03777576895352025, 0.3427276199688195, + 0.8918518610776603, 0.8918518610776603, + 0.3427276199688196, 0.0377757689535203]) + assert_allclose(windows.nuttall(6), + [0.0003628, 0.1105152530498718, 0.7982580969501282, + 0.7982580969501283, 0.1105152530498719, 0.0003628]) + assert_allclose(windows.nuttall(7, True), + [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, + 0.0613345, 0.0003628]) + + +class TestParzen: + + def test_basic(self): + assert_allclose(windows.parzen(6), + [0.009259259259259254, 0.25, 0.8611111111111112, + 0.8611111111111112, 0.25, 0.009259259259259254]) + assert_allclose(windows.parzen(7, sym=True), + [0.00583090379008747, 0.1574344023323616, + 0.6501457725947521, 1.0, 0.6501457725947521, + 0.1574344023323616, 0.00583090379008747]) + assert_allclose(windows.parzen(6, False), + [0.00583090379008747, 0.1574344023323616, + 0.6501457725947521, 1.0, 0.6501457725947521, + 0.1574344023323616]) + + +class TestTriang: + + def test_basic(self): + + assert_allclose(windows.triang(6, True), + [1/6, 1/2, 5/6, 5/6, 1/2, 1/6]) + assert_allclose(windows.triang(7), + [1/4, 1/2, 3/4, 1, 3/4, 1/2, 1/4]) + assert_allclose(windows.triang(6, sym=False), + [1/4, 1/2, 3/4, 1, 3/4, 1/2]) + + +tukey_data = { + (4, 0.5, True): array([0.0, 1.0, 1.0, 0.0]), + (4, 0.9, True): array([0.0, 0.84312081893436686, + 0.84312081893436686, 0.0]), + (4, 1.0, True): array([0.0, 0.75, 0.75, 0.0]), + (4, 0.5, False): array([0.0, 1.0, 1.0, 1.0]), + (4, 0.9, False): array([0.0, 0.58682408883346526, + 1.0, 0.58682408883346526]), + (4, 1.0, False): array([0.0, 0.5, 1.0, 0.5]), + (5, 0.0, True): array([1.0, 1.0, 1.0, 1.0, 1.0]), + (5, 0.8, True): array([0.0, 0.69134171618254492, + 1.0, 0.69134171618254492, 0.0]), + (5, 1.0, True): array([0.0, 0.5, 1.0, 0.5, 0.0]), + + (6, 0): [1, 1, 1, 1, 1, 1], + (7, 0): [1, 1, 1, 1, 1, 1, 1], + (6, .25): [0, 1, 1, 1, 1, 0], + (7, .25): [0, 1, 1, 1, 1, 1, 0], + (6,): [0, 0.9045084971874737, 1.0, 1.0, 0.9045084971874735, 0], + (7,): [0, 0.75, 1.0, 1.0, 1.0, 0.75, 0], + (6, .75): [0, 0.5522642316338269, 1.0, 1.0, 0.5522642316338267, 0], + (7, .75): [0, 0.4131759111665348, 0.9698463103929542, 1.0, + 0.9698463103929542, 0.4131759111665347, 0], + (6, 1): [0, 0.3454915028125263, 0.9045084971874737, 0.9045084971874737, + 0.3454915028125263, 0], + (7, 1): [0, 0.25, 0.75, 1.0, 0.75, 0.25, 0], +} + + +class TestTukey: + + def test_basic(self): + # Test against hardcoded data + for k, v in tukey_data.items(): + if v is None: + assert_raises(ValueError, windows.tukey, *k) + else: + win = windows.tukey(*k) + assert_allclose(win, v, rtol=1e-15, atol=1e-15) + + def test_extremes(self): + # Test extremes of alpha correspond to boxcar and hann + tuk0 = windows.tukey(100, 0) + box0 = windows.boxcar(100) + assert_array_almost_equal(tuk0, box0) + + tuk1 = windows.tukey(100, 1) + han1 = windows.hann(100) + assert_array_almost_equal(tuk1, han1) + + +dpss_data = { + # All values from MATLAB: + # * taper[1] of (3, 1.4, 3) sign-flipped + # * taper[3] of (5, 1.5, 5) sign-flipped + (4, 0.1, 2): ([[0.497943898, 0.502047681, 0.502047681, 0.497943898], [0.670487993, 0.224601537, -0.224601537, -0.670487993]], [0.197961815, 0.002035474]), # noqa: E501 + (3, 1.4, 3): ([[0.410233151, 0.814504464, 0.410233151], [0.707106781, 0.0, -0.707106781], [0.575941629, -0.580157287, 0.575941629]], [0.999998093, 0.998067480, 0.801934426]), # noqa: E501 + (5, 1.5, 5): ([[0.1745071052, 0.4956749177, 0.669109327, 0.495674917, 0.174507105], [0.4399493348, 0.553574369, 0.0, -0.553574369, -0.439949334], [0.631452756, 0.073280238, -0.437943884, 0.073280238, 0.631452756], [0.553574369, -0.439949334, 0.0, 0.439949334, -0.553574369], [0.266110290, -0.498935248, 0.600414741, -0.498935248, 0.266110290147157]], [0.999728571, 0.983706916, 0.768457889, 0.234159338, 0.013947282907567]), # noqa: E501 + (100, 2, 4): ([[0.0030914414, 0.0041266922, 0.005315076, 0.006665149, 0.008184854, 0.0098814158, 0.011761239, 0.013829809, 0.016091597, 0.018549973, 0.02120712, 0.02406396, 0.027120092, 0.030373728, 0.033821651, 0.037459181, 0.041280145, 0.045276872, 0.049440192, 0.053759447, 0.058222524, 0.062815894, 0.067524661, 0.072332638, 0.077222418, 0.082175473, 0.087172252, 0.092192299, 0.097214376, 0.1022166, 0.10717657, 0.11207154, 0.11687856, 0.12157463, 0.12613686, 0.13054266, 0.13476986, 0.13879691, 0.14260302, 0.14616832, 0.14947401, 0.1525025, 0.15523755, 0.15766438, 0.15976981, 0.16154233, 0.16297223, 0.16405162, 0.16477455, 0.16513702, 0.16513702, 0.16477455, 0.16405162, 0.16297223, 0.16154233, 0.15976981, 0.15766438, 0.15523755, 0.1525025, 0.14947401, 0.14616832, 0.14260302, 0.13879691, 0.13476986, 0.13054266, 0.12613686, 0.12157463, 0.11687856, 0.11207154, 0.10717657, 0.1022166, 0.097214376, 0.092192299, 0.087172252, 0.082175473, 0.077222418, 0.072332638, 0.067524661, 0.062815894, 0.058222524, 0.053759447, 0.049440192, 0.045276872, 0.041280145, 0.037459181, 0.033821651, 0.030373728, 0.027120092, 0.02406396, 0.02120712, 0.018549973, 0.016091597, 0.013829809, 0.011761239, 0.0098814158, 0.008184854, 0.006665149, 0.005315076, 0.0041266922, 0.0030914414], [0.018064449, 0.022040342, 0.026325013, 0.030905288, 0.035764398, 0.040881982, 0.046234148, 0.051793558, 0.057529559, 0.063408356, 0.069393216, 0.075444716, 0.081521022, 0.087578202, 0.093570567, 0.099451049, 0.10517159, 0.11068356, 0.11593818, 0.12088699, 0.12548227, 0.12967752, 0.1334279, 0.13669069, 0.13942569, 0.1415957, 0.14316686, 0.14410905, 0.14439626, 0.14400686, 0.14292389, 0.1411353, 0.13863416, 0.13541876, 0.13149274, 0.12686516, 0.12155045, 0.1155684, 0.10894403, 0.10170748, 0.093893752, 0.08554251, 0.076697768, 0.067407559, 0.057723559, 0.04770068, 0.037396627, 0.026871428, 0.016186944, 0.0054063557, -0.0054063557, -0.016186944, -0.026871428, -0.037396627, -0.04770068, -0.057723559, -0.067407559, -0.076697768, -0.08554251, -0.093893752, -0.10170748, -0.10894403, -0.1155684, -0.12155045, -0.12686516, -0.13149274, -0.13541876, -0.13863416, -0.1411353, -0.14292389, -0.14400686, -0.14439626, -0.14410905, -0.14316686, -0.1415957, -0.13942569, -0.13669069, -0.1334279, -0.12967752, -0.12548227, -0.12088699, -0.11593818, -0.11068356, -0.10517159, -0.099451049, -0.093570567, -0.087578202, -0.081521022, -0.075444716, -0.069393216, -0.063408356, -0.057529559, -0.051793558, -0.046234148, -0.040881982, -0.035764398, -0.030905288, -0.026325013, -0.022040342, -0.018064449], [0.064817553, 0.072567801, 0.080292992, 0.087918235, 0.095367076, 0.10256232, 0.10942687, 0.1158846, 0.12186124, 0.12728523, 0.13208858, 0.13620771, 0.13958427, 0.14216587, 0.14390678, 0.14476863, 0.1447209, 0.14374148, 0.14181704, 0.13894336, 0.13512554, 0.13037812, 0.1247251, 0.11819984, 0.11084487, 0.10271159, 0.093859853, 0.084357497, 0.074279719, 0.063708406, 0.052731374, 0.041441525, 0.029935953, 0.018314987, 0.0066811877, -0.0048616765, -0.016209689, -0.027259848, -0.037911124, -0.048065512, -0.05762905, -0.066512804, -0.0746338, -0.081915903, -0.088290621, -0.09369783, -0.098086416, -0.10141482, -0.10365146, -0.10477512, -0.10477512, -0.10365146, -0.10141482, -0.098086416, -0.09369783, -0.088290621, -0.081915903, -0.0746338, -0.066512804, -0.05762905, -0.048065512, -0.037911124, -0.027259848, -0.016209689, -0.0048616765, 0.0066811877, 0.018314987, 0.029935953, 0.041441525, 0.052731374, 0.063708406, 0.074279719, 0.084357497, 0.093859853, 0.10271159, 0.11084487, 0.11819984, 0.1247251, 0.13037812, 0.13512554, 0.13894336, 0.14181704, 0.14374148, 0.1447209, 0.14476863, 0.14390678, 0.14216587, 0.13958427, 0.13620771, 0.13208858, 0.12728523, 0.12186124, 0.1158846, 0.10942687, 0.10256232, 0.095367076, 0.087918235, 0.080292992, 0.072567801, 0.064817553], [0.14985551, 0.15512305, 0.15931467, 0.16236806, 0.16423291, 0.16487165, 0.16426009, 0.1623879, 0.1592589, 0.15489114, 0.14931693, 0.14258255, 0.13474785, 0.1258857, 0.11608124, 0.10543095, 0.094041635, 0.082029213, 0.069517411, 0.056636348, 0.043521028, 0.030309756, 0.017142511, 0.0041592774, -0.0085016282, -0.020705223, -0.032321494, -0.043226982, -0.053306291, -0.062453515, -0.070573544, -0.077583253, -0.083412547, -0.088005244, -0.091319802, -0.093329861, -0.094024602, -0.093408915, -0.091503383, -0.08834406, -0.08398207, -0.078483012, -0.071926192, -0.064403681, -0.056019215, -0.046886954, -0.037130106, -0.026879442, -0.016271713, -0.005448, 0.005448, 0.016271713, 0.026879442, 0.037130106, 0.046886954, 0.056019215, 0.064403681, 0.071926192, 0.078483012, 0.08398207, 0.08834406, 0.091503383, 0.093408915, 0.094024602, 0.093329861, 0.091319802, 0.088005244, 0.083412547, 0.077583253, 0.070573544, 0.062453515, 0.053306291, 0.043226982, 0.032321494, 0.020705223, 0.0085016282, -0.0041592774, -0.017142511, -0.030309756, -0.043521028, -0.056636348, -0.069517411, -0.082029213, -0.094041635, -0.10543095, -0.11608124, -0.1258857, -0.13474785, -0.14258255, -0.14931693, -0.15489114, -0.1592589, -0.1623879, -0.16426009, -0.16487165, -0.16423291, -0.16236806, -0.15931467, -0.15512305, -0.14985551]], [0.999943140, 0.997571533, 0.959465463, 0.721862496]), # noqa: E501 +} + + +class TestDPSS: + + def test_basic(self): + # Test against hardcoded data + for k, v in dpss_data.items(): + win, ratios = windows.dpss(*k, return_ratios=True) + assert_allclose(win, v[0], atol=1e-7, err_msg=k) + assert_allclose(ratios, v[1], rtol=1e-5, atol=1e-7, err_msg=k) + + def test_unity(self): + # Test unity value handling (gh-2221) + for M in range(1, 21): + # corrected w/approximation (default) + win = windows.dpss(M, M / 2.1) + expected = M % 2 # one for odd, none for even + assert_equal(np.isclose(win, 1.).sum(), expected, + err_msg=f'{win}') + # corrected w/subsample delay (slower) + win_sub = windows.dpss(M, M / 2.1, norm='subsample') + if M > 2: + # @M=2 the subsample doesn't do anything + assert_equal(np.isclose(win_sub, 1.).sum(), expected, + err_msg=f'{win_sub}') + assert_allclose(win, win_sub, rtol=0.03) # within 3% + # not the same, l2-norm + win_2 = windows.dpss(M, M / 2.1, norm=2) + expected = 1 if M == 1 else 0 + assert_equal(np.isclose(win_2, 1.).sum(), expected, + err_msg=f'{win_2}') + + def test_extremes(self): + # Test extremes of alpha + lam = windows.dpss(31, 6, 4, return_ratios=True)[1] + assert_array_almost_equal(lam, 1.) + lam = windows.dpss(31, 7, 4, return_ratios=True)[1] + assert_array_almost_equal(lam, 1.) + lam = windows.dpss(31, 8, 4, return_ratios=True)[1] + assert_array_almost_equal(lam, 1.) + + def test_degenerate(self): + # Test failures + assert_raises(ValueError, windows.dpss, 4, 1.5, -1) # Bad Kmax + assert_raises(ValueError, windows.dpss, 4, 1.5, -5) + assert_raises(TypeError, windows.dpss, 4, 1.5, 1.1) + assert_raises(ValueError, windows.dpss, 3, 1.5, 3) # NW must be < N/2. + assert_raises(ValueError, windows.dpss, 3, -1, 3) # NW must be pos + assert_raises(ValueError, windows.dpss, 3, 0, 3) + assert_raises(ValueError, windows.dpss, -1, 1, 3) # negative M + + +class TestLanczos: + + def test_basic(self): + # Analytical results: + # sinc(x) = sinc(-x) + # sinc(pi) = 0, sinc(0) = 1 + # Hand computation on WolframAlpha: + # sinc(2 pi / 3) = 0.413496672 + # sinc(pi / 3) = 0.826993343 + # sinc(3 pi / 5) = 0.504551152 + # sinc(pi / 5) = 0.935489284 + assert_allclose(windows.lanczos(6, sym=False), + [0., 0.413496672, + 0.826993343, 1., 0.826993343, + 0.413496672], + atol=1e-9) + assert_allclose(windows.lanczos(6), + [0., 0.504551152, + 0.935489284, 0.935489284, + 0.504551152, 0.], + atol=1e-9) + assert_allclose(windows.lanczos(7, sym=True), + [0., 0.413496672, + 0.826993343, 1., 0.826993343, + 0.413496672, 0.], + atol=1e-9) + + def test_array_size(self): + for n in [0, 10, 11]: + assert_equal(len(windows.lanczos(n, sym=False)), n) + assert_equal(len(windows.lanczos(n, sym=True)), n) + + +class TestGetWindow: + + def test_boxcar(self): + w = windows.get_window('boxcar', 12) + assert_array_equal(w, np.ones_like(w)) + + # window is a tuple of len 1 + w = windows.get_window(('boxcar',), 16) + assert_array_equal(w, np.ones_like(w)) + + def test_cheb_odd(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + w = windows.get_window(('chebwin', -40), 53, fftbins=False) + assert_array_almost_equal(w, cheb_odd_true, decimal=4) + + def test_cheb_even(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + w = windows.get_window(('chebwin', 40), 54, fftbins=False) + assert_array_almost_equal(w, cheb_even_true, decimal=4) + + def test_dpss(self): + win1 = windows.get_window(('dpss', 3), 64, fftbins=False) + win2 = windows.dpss(64, 3) + assert_array_almost_equal(win1, win2, decimal=4) + + def test_kaiser_float(self): + win1 = windows.get_window(7.2, 64) + win2 = windows.kaiser(64, 7.2, False) + assert_allclose(win1, win2) + + def test_invalid_inputs(self): + # Window is not a float, tuple, or string + assert_raises(ValueError, windows.get_window, set('hann'), 8) + + # Unknown window type error + assert_raises(ValueError, windows.get_window, 'broken', 4) + + def test_array_as_window(self): + # GitHub issue 3603 + osfactor = 128 + sig = np.arange(128) + + win = windows.get_window(('kaiser', 8.0), osfactor // 2) + with assert_raises(ValueError, match='must have the same length'): + resample(sig, len(sig) * osfactor, window=win) + + def test_general_cosine(self): + assert_allclose(get_window(('general_cosine', [0.5, 0.3, 0.2]), 4), + [0.4, 0.3, 1, 0.3]) + assert_allclose(get_window(('general_cosine', [0.5, 0.3, 0.2]), 4, + fftbins=False), + [0.4, 0.55, 0.55, 0.4]) + + def test_general_hamming(self): + assert_allclose(get_window(('general_hamming', 0.7), 5), + [0.4, 0.6072949, 0.9427051, 0.9427051, 0.6072949]) + assert_allclose(get_window(('general_hamming', 0.7), 5, fftbins=False), + [0.4, 0.7, 1.0, 0.7, 0.4]) + + def test_lanczos(self): + assert_allclose(get_window('lanczos', 6), + [0., 0.413496672, 0.826993343, 1., 0.826993343, + 0.413496672], atol=1e-9) + assert_allclose(get_window('lanczos', 6, fftbins=False), + [0., 0.504551152, 0.935489284, 0.935489284, + 0.504551152, 0.], atol=1e-9) + assert_allclose(get_window('lanczos', 6), get_window('sinc', 6)) + + +def test_windowfunc_basics(): + for window_name, params in window_funcs: + window = getattr(windows, window_name) + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + # Check symmetry for odd and even lengths + w1 = window(8, *params, sym=True) + w2 = window(7, *params, sym=False) + assert_array_almost_equal(w1[:-1], w2) + + w1 = window(9, *params, sym=True) + w2 = window(8, *params, sym=False) + assert_array_almost_equal(w1[:-1], w2) + + # Check that functions run and output lengths are correct + assert_equal(len(window(6, *params, sym=True)), 6) + assert_equal(len(window(6, *params, sym=False)), 6) + assert_equal(len(window(7, *params, sym=True)), 7) + assert_equal(len(window(7, *params, sym=False)), 7) + + # Check invalid lengths + assert_raises(ValueError, window, 5.5, *params) + assert_raises(ValueError, window, -7, *params) + + # Check degenerate cases + assert_array_equal(window(0, *params, sym=True), []) + assert_array_equal(window(0, *params, sym=False), []) + assert_array_equal(window(1, *params, sym=True), [1]) + assert_array_equal(window(1, *params, sym=False), [1]) + + # Check dtype + assert_(window(0, *params, sym=True).dtype == 'float') + assert_(window(0, *params, sym=False).dtype == 'float') + assert_(window(1, *params, sym=True).dtype == 'float') + assert_(window(1, *params, sym=False).dtype == 'float') + assert_(window(6, *params, sym=True).dtype == 'float') + assert_(window(6, *params, sym=False).dtype == 'float') + + # Check normalization + assert_array_less(window(10, *params, sym=True), 1.01) + assert_array_less(window(10, *params, sym=False), 1.01) + assert_array_less(window(9, *params, sym=True), 1.01) + assert_array_less(window(9, *params, sym=False), 1.01) + + # Check that DFT-even spectrum is purely real for odd and even + assert_allclose(fft(window(10, *params, sym=False)).imag, + 0, atol=1e-14) + assert_allclose(fft(window(11, *params, sym=False)).imag, + 0, atol=1e-14) + + +def test_needs_params(): + for winstr in ['kaiser', 'ksr', 'kaiser_bessel_derived', 'kbd', + 'gaussian', 'gauss', 'gss', + 'general gaussian', 'general_gaussian', + 'general gauss', 'general_gauss', 'ggs', + 'dss', 'dpss', 'general cosine', 'general_cosine', + 'chebwin', 'cheb', 'general hamming', 'general_hamming', + ]: + assert_raises(ValueError, get_window, winstr, 7) + + +def test_not_needs_params(): + for winstr in ['barthann', + 'bartlett', + 'blackman', + 'blackmanharris', + 'bohman', + 'boxcar', + 'cosine', + 'flattop', + 'hamming', + 'nuttall', + 'parzen', + 'taylor', + 'exponential', + 'poisson', + 'tukey', + 'tuk', + 'triangle', + 'lanczos', + 'sinc', + ]: + win = get_window(winstr, 7) + assert_equal(len(win), 7) + + +def test_symmetric(): + + for win in [windows.lanczos]: + # Even sampling points + w = win(4096) + error = np.max(np.abs(w-np.flip(w))) + assert_equal(error, 0.0) + + # Odd sampling points + w = win(4097) + error = np.max(np.abs(w-np.flip(w))) + assert_equal(error, 0.0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/waveforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/waveforms.py new file mode 100644 index 0000000000000000000000000000000000000000..30e71348d04276a66470a4053d97cefc60f7136e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/waveforms.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'sawtooth', 'square', 'gausspulse', 'chirp', 'sweep_poly', + 'unit_impulse', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="waveforms", + private_modules=["_waveforms"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/wavelets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/wavelets.py new file mode 100644 index 0000000000000000000000000000000000000000..fc897a2483536df7e995faaa29af621e25fe38c7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/wavelets.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="wavelets", + private_modules=["_wavelets"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..967a7c758f69c1c8002d886d78832904c402d2b3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py @@ -0,0 +1,52 @@ +""" +Window functions (:mod:`scipy.signal.windows`) +============================================== + +The suite of window functions for filtering and spectral estimation. + +.. currentmodule:: scipy.signal.windows + +.. autosummary:: + :toctree: generated/ + + get_window -- Return a window of a given length and type. + + barthann -- Bartlett-Hann window + bartlett -- Bartlett window + blackman -- Blackman window + blackmanharris -- Minimum 4-term Blackman-Harris window + bohman -- Bohman window + boxcar -- Boxcar window + chebwin -- Dolph-Chebyshev window + cosine -- Cosine window + dpss -- Discrete prolate spheroidal sequences + exponential -- Exponential window + flattop -- Flat top window + gaussian -- Gaussian window + general_cosine -- Generalized Cosine window + general_gaussian -- Generalized Gaussian window + general_hamming -- Generalized Hamming window + hamming -- Hamming window + hann -- Hann window + kaiser -- Kaiser window + kaiser_bessel_derived -- Kaiser-Bessel derived window + lanczos -- Lanczos window also known as a sinc window + nuttall -- Nuttall's minimum 4-term Blackman-Harris window + parzen -- Parzen window + taylor -- Taylor window + triang -- Triangular window + tukey -- Tukey window + +""" + +from ._windows import * + +# Deprecated namespaces, to be removed in v2.0.0 +from . import windows + +__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall', + 'blackmanharris', 'flattop', 'bartlett', 'barthann', + 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian', + 'general_gaussian', 'general_cosine', 'general_hamming', + 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor', + 'get_window', 'dpss', 'lanczos'] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py new file mode 100644 index 0000000000000000000000000000000000000000..e89c1aee6aba661f11a86cb2213904964d870782 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py @@ -0,0 +1,2374 @@ +"""The suite of window functions.""" + +import operator +import warnings + +import numpy as np +from scipy import linalg, special, fft as sp_fft + +__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall', + 'blackmanharris', 'flattop', 'bartlett', 'barthann', + 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian', + 'general_cosine', 'general_gaussian', 'general_hamming', + 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor', + 'dpss', 'get_window', 'lanczos'] + + +def _len_guards(M): + """Handle small or incorrect window lengths""" + if int(M) != M or M < 0: + raise ValueError('Window length M must be a non-negative integer') + return M <= 1 + + +def _extend(M, sym): + """Extend window by 1 sample if needed for DFT-even symmetry""" + if not sym: + return M + 1, True + else: + return M, False + + +def _truncate(w, needed): + """Truncate window by 1 sample if needed for DFT-even symmetry""" + if needed: + return w[:-1] + else: + return w + + +def general_cosine(M, a, sym=True): + r""" + Generic weighted sum of cosine terms window + + Parameters + ---------- + M : int + Number of points in the output window + a : array_like + Sequence of weighting coefficients. This uses the convention of being + centered on the origin, so these will typically all be positive + numbers, not alternating sign. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The array of window values. + + References + ---------- + .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE + Transactions on Acoustics, Speech, and Signal Processing, vol. 29, + no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. + .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the + Discrete Fourier transform (DFT), including a comprehensive list of + window functions and some new flat-top windows", February 15, 2002 + https://holometer.fnal.gov/GH_FFT.pdf + + Examples + -------- + Heinzel describes a flat-top window named "HFT90D" with formula: [2]_ + + .. math:: w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z) + - 0.440811 \cos(3z) + 0.043097 \cos(4z) + + where + + .. math:: z = \frac{2 \pi j}{N}, j = 0...N - 1 + + Since this uses the convention of starting at the origin, to reproduce the + window, we need to convert every other coefficient to a positive number: + + >>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097] + + The paper states that the highest sidelobe is at -90.2 dB. Reproduce + Figure 42 by plotting the window and its frequency response, and confirm + the sidelobe level in red: + + >>> import numpy as np + >>> from scipy.signal.windows import general_cosine + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = general_cosine(1000, HFT90D, sym=False) + >>> plt.plot(window) + >>> plt.title("HFT90D window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 10000) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-50/1000, 50/1000, -140, 0]) + >>> plt.title("Frequency response of the HFT90D window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + >>> plt.axhline(-90.2, color='red') + >>> plt.show() + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + fac = np.linspace(-np.pi, np.pi, M) + w = np.zeros(M) + for k in range(len(a)): + w += a[k] * np.cos(k * fac) + + return _truncate(w, needs_trunc) + + +def boxcar(M, sym=True): + """Return a boxcar or rectangular window. + + Also known as a rectangular window or Dirichlet window, this is equivalent + to no window at all. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + Whether the window is symmetric. (Has no effect for boxcar.) + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.boxcar(51) + >>> plt.plot(window) + >>> plt.title("Boxcar window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the boxcar window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + w = np.ones(M, float) + + return _truncate(w, needs_trunc) + + +def triang(M, sym=True): + """Return a triangular window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + See Also + -------- + bartlett : A triangular window that touches zero + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.triang(51) + >>> plt.plot(window) + >>> plt.title("Triangular window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the triangular window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(1, (M + 1) // 2 + 1) + if M % 2 == 0: + w = (2 * n - 1.0) / M + w = np.r_[w, w[::-1]] + else: + w = 2 * n / (M + 1.0) + w = np.r_[w, w[-2::-1]] + + return _truncate(w, needs_trunc) + + +def parzen(M, sym=True): + """Return a Parzen window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + References + ---------- + .. [1] E. Parzen, "Mathematical Considerations in the Estimation of + Spectra", Technometrics, Vol. 3, No. 2 (May, 1961), pp. 167-190 + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.parzen(51) + >>> plt.plot(window) + >>> plt.title("Parzen window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Parzen window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(-(M - 1) / 2.0, (M - 1) / 2.0 + 0.5, 1.0) + na = np.extract(n < -(M - 1) / 4.0, n) + nb = np.extract(abs(n) <= (M - 1) / 4.0, n) + wa = 2 * (1 - np.abs(na) / (M / 2.0)) ** 3.0 + wb = (1 - 6 * (np.abs(nb) / (M / 2.0)) ** 2.0 + + 6 * (np.abs(nb) / (M / 2.0)) ** 3.0) + w = np.r_[wa, wb, wa[::-1]] + + return _truncate(w, needs_trunc) + + +def bohman(M, sym=True): + """Return a Bohman window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.bohman(51) + >>> plt.plot(window) + >>> plt.title("Bohman window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2047) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Bohman window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + fac = np.abs(np.linspace(-1, 1, M)[1:-1]) + w = (1 - fac) * np.cos(np.pi * fac) + 1.0 / np.pi * np.sin(np.pi * fac) + w = np.r_[0, w, 0] + + return _truncate(w, needs_trunc) + + +def blackman(M, sym=True): + r""" + Return a Blackman window. + + The Blackman window is a taper formed by using the first three terms of + a summation of cosines. It was designed to have close to the minimal + leakage possible. It is close to optimal, only slightly worse than a + Kaiser window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Blackman window is defined as + + .. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M) + + The "exact Blackman" window was designed to null out the third and fourth + sidelobes, but has discontinuities at the boundaries, resulting in a + 6 dB/oct fall-off. This window is an approximation of the "exact" window, + which does not null the sidelobes as well, but is smooth at the edges, + improving the fall-off rate to 18 dB/oct. [3]_ + + Most references to the Blackman window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. It is known as a + "near optimal" tapering function, almost as good (by some measures) + as the Kaiser window. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. + Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. + .. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic + Analysis with the Discrete Fourier Transform". Proceedings of the + IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.blackman(51) + >>> plt.plot(window) + >>> plt.title("Blackman window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Blackman window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's blackman function + return general_cosine(M, [0.42, 0.50, 0.08], sym) + + +def nuttall(M, sym=True): + """Return a minimum 4-term Blackman-Harris window according to Nuttall. + + This variation is called "Nuttall4c" by Heinzel. [2]_ + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + References + ---------- + .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE + Transactions on Acoustics, Speech, and Signal Processing, vol. 29, + no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. + .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the + Discrete Fourier transform (DFT), including a comprehensive list of + window functions and some new flat-top windows", February 15, 2002 + https://holometer.fnal.gov/GH_FFT.pdf + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.nuttall(51) + >>> plt.plot(window) + >>> plt.title("Nuttall window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Nuttall window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + return general_cosine(M, [0.3635819, 0.4891775, 0.1365995, 0.0106411], sym) + + +def blackmanharris(M, sym=True): + """Return a minimum 4-term Blackman-Harris window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.blackmanharris(51) + >>> plt.plot(window) + >>> plt.title("Blackman-Harris window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Blackman-Harris window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + return general_cosine(M, [0.35875, 0.48829, 0.14128, 0.01168], sym) + + +def flattop(M, sym=True): + """Return a flat top window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + Flat top windows are used for taking accurate measurements of signal + amplitude in the frequency domain, with minimal scalloping error from the + center of a frequency bin to its edges, compared to others. This is a + 5th-order cosine window, with the 5 terms optimized to make the main lobe + maximally flat. [1]_ + + References + ---------- + .. [1] D'Antona, Gabriele, and A. Ferrero, "Digital Signal Processing for + Measurement Systems", Springer Media, 2006, p. 70 + :doi:`10.1007/0-387-28666-7`. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.flattop(51) + >>> plt.plot(window) + >>> plt.title("Flat top window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the flat top window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + a = [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368] + return general_cosine(M, a, sym) + + +def bartlett(M, sym=True): + r""" + Return a Bartlett window. + + The Bartlett window is very similar to a triangular window, except + that the end points are at zero. It is often used in signal + processing for tapering a signal, without generating too much + ripple in the frequency domain. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The triangular window, with the first and last samples equal to zero + and the maximum value normalized to 1 (though the value 1 does not + appear if `M` is even and `sym` is True). + + See Also + -------- + triang : A triangular window that does not touch zero at the ends + + Notes + ----- + The Bartlett window is defined as + + .. math:: w(n) = \frac{2}{M-1} \left( + \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right| + \right) + + Most references to the Bartlett window come from the signal + processing literature, where it is used as one of many windowing + functions for smoothing values. Note that convolution with this + window produces linear interpolation. It is also known as an + apodization (which means"removing the foot", i.e. smoothing + discontinuities at the beginning and end of the sampled signal) or + tapering function. The Fourier transform of the Bartlett is the product + of two sinc functions. + Note the excellent discussion in Kanasewich. [2]_ + + References + ---------- + .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", + Biometrika 37, 1-16, 1950. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", + The University of Alberta Press, 1975, pp. 109-110. + .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal + Processing", Prentice-Hall, 1999, pp. 468-471. + .. [4] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 429. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.bartlett(51) + >>> plt.plot(window) + >>> plt.title("Bartlett window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Bartlett window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's bartlett function + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + w = np.where(np.less_equal(n, (M - 1) / 2.0), + 2.0 * n / (M - 1), 2.0 - 2.0 * n / (M - 1)) + + return _truncate(w, needs_trunc) + + +def hann(M, sym=True): + r""" + Return a Hann window. + + The Hann window is a taper formed by using a raised cosine or sine-squared + with ends that touch zero. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Hann window is defined as + + .. math:: w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi{n}}{M-1}\right) + \qquad 0 \leq n \leq M-1 + + The window was named for Julius von Hann, an Austrian meteorologist. It is + also known as the Cosine Bell. It is sometimes erroneously referred to as + the "Hanning" window, from the use of "hann" as a verb in the original + paper and confusion with the very similar Hamming window. + + Most references to the Hann window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", + The University of Alberta Press, 1975, pp. 106-108. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 425. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.hann(51) + >>> plt.plot(window) + >>> plt.title("Hann window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Hann window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's hanning function + return general_hamming(M, 0.5, sym) + + +def tukey(M, alpha=0.5, sym=True): + r"""Return a Tukey window, also known as a tapered cosine window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + alpha : float, optional + Shape parameter of the Tukey window, representing the fraction of the + window inside the cosine tapered region. + If zero, the Tukey window is equivalent to a rectangular window. + If one, the Tukey window is equivalent to a Hann window. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + References + ---------- + .. [1] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic + Analysis with the Discrete Fourier Transform". Proceedings of the + IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837` + .. [2] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function#Tukey_window + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.tukey(51) + >>> plt.plot(window) + >>> plt.title("Tukey window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + >>> plt.ylim([0, 1.1]) + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Tukey window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + + if alpha <= 0: + return np.ones(M, 'd') + elif alpha >= 1.0: + return hann(M, sym=sym) + + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + width = int(np.floor(alpha*(M-1)/2.0)) + n1 = n[0:width+1] + n2 = n[width+1:M-width-1] + n3 = n[M-width-1:] + + w1 = 0.5 * (1 + np.cos(np.pi * (-1 + 2.0*n1/alpha/(M-1)))) + w2 = np.ones(n2.shape) + w3 = 0.5 * (1 + np.cos(np.pi * (-2.0/alpha + 1 + 2.0*n3/alpha/(M-1)))) + + w = np.concatenate((w1, w2, w3)) + + return _truncate(w, needs_trunc) + + +def barthann(M, sym=True): + """Return a modified Bartlett-Hann window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.barthann(51) + >>> plt.plot(window) + >>> plt.title("Bartlett-Hann window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Bartlett-Hann window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + fac = np.abs(n / (M - 1.0) - 0.5) + w = 0.62 - 0.48 * fac + 0.38 * np.cos(2 * np.pi * fac) + + return _truncate(w, needs_trunc) + + +def general_hamming(M, alpha, sym=True): + r"""Return a generalized Hamming window. + + The generalized Hamming window is constructed by multiplying a rectangular + window by one period of a cosine function [1]_. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + alpha : float + The window coefficient, :math:`\alpha` + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + See Also + -------- + hamming, hann + + Notes + ----- + The generalized Hamming window is defined as + + .. math:: w(n) = \alpha - \left(1 - \alpha\right) + \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1 + + Both the common Hamming window and Hann window are special cases of the + generalized Hamming window with :math:`\alpha` = 0.54 and :math:`\alpha` = + 0.5, respectively [2]_. + + References + ---------- + .. [1] DSPRelated, "Generalized Hamming Window Family", + https://www.dsprelated.com/freebooks/sasp/Generalized_Hamming_Window_Family.html + .. [2] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [3] Riccardo Piantanida ESA, "Sentinel-1 Level 1 Detailed Algorithm + Definition", + https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Level-1-Detailed-Algorithm-Definition + .. [4] Matthieu Bourbigot ESA, "Sentinel-1 Product Definition", + https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Product-Definition + + Examples + -------- + The Sentinel-1A/B Instrument Processing Facility uses generalized Hamming + windows in the processing of spaceborne Synthetic Aperture Radar (SAR) + data [3]_. The facility uses various values for the :math:`\alpha` + parameter based on operating mode of the SAR instrument. Some common + :math:`\alpha` values include 0.75, 0.7 and 0.52 [4]_. As an example, we + plot these different windows. + + >>> import numpy as np + >>> from scipy.signal.windows import general_hamming + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> fig1, spatial_plot = plt.subplots() + >>> spatial_plot.set_title("Generalized Hamming Windows") + >>> spatial_plot.set_ylabel("Amplitude") + >>> spatial_plot.set_xlabel("Sample") + + >>> fig2, freq_plot = plt.subplots() + >>> freq_plot.set_title("Frequency Responses") + >>> freq_plot.set_ylabel("Normalized magnitude [dB]") + >>> freq_plot.set_xlabel("Normalized frequency [cycles per sample]") + + >>> for alpha in [0.75, 0.7, 0.52]: + ... window = general_hamming(41, alpha) + ... spatial_plot.plot(window, label="{:.2f}".format(alpha)) + ... A = fft(window, 2048) / (len(window)/2.0) + ... freq = np.linspace(-0.5, 0.5, len(A)) + ... response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + ... freq_plot.plot(freq, response, label="{:.2f}".format(alpha)) + >>> freq_plot.legend(loc="upper right") + >>> spatial_plot.legend(loc="upper right") + + """ + return general_cosine(M, [alpha, 1. - alpha], sym) + + +def hamming(M, sym=True): + r"""Return a Hamming window. + + The Hamming window is a taper formed by using a raised cosine with + non-zero endpoints, optimized to minimize the nearest side lobe. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Hamming window is defined as + + .. math:: w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right) + \qquad 0 \leq n \leq M-1 + + The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and + is described in Blackman and Tukey. It was recommended for smoothing the + truncated autocovariance function in the time domain. + Most references to the Hamming window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 109-110. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 425. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.hamming(51) + >>> plt.plot(window) + >>> plt.title("Hamming window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Hamming window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's hamming function + return general_hamming(M, 0.54, sym) + + +def kaiser(M, beta, sym=True): + r"""Return a Kaiser window. + + The Kaiser window is a taper formed by using a Bessel function. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + beta : float + Shape parameter, determines trade-off between main-lobe width and + side lobe level. As beta gets large, the window narrows. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Kaiser window is defined as + + .. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}} + \right)/I_0(\beta) + + with + + .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2}, + + where :math:`I_0` is the modified zeroth-order Bessel function. + + The Kaiser was named for Jim Kaiser, who discovered a simple approximation + to the DPSS window based on Bessel functions. + The Kaiser window is a very good approximation to the discrete prolate + spheroidal sequence, or Slepian window, which is the transform which + maximizes the energy in the main lobe of the window relative to total + energy. + + The Kaiser can approximate other windows by varying the beta parameter. + (Some literature uses alpha = beta/pi.) [4]_ + + ==== ======================= + beta Window shape + ==== ======================= + 0 Rectangular + 5 Similar to a Hamming + 6 Similar to a Hann + 8.6 Similar to a Blackman + ==== ======================= + + A beta value of 14 is probably a good starting point. Note that as beta + gets large, the window narrows, and so the number of samples needs to be + large enough to sample the increasingly narrow spike, otherwise NaNs will + be returned. + + Most references to the Kaiser window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by + digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. + John Wiley and Sons, New York, (1966). + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 177-178. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] F. J. Harris, "On the use of windows for harmonic analysis with the + discrete Fourier transform," Proceedings of the IEEE, vol. 66, + no. 1, pp. 51-83, Jan. 1978. :doi:`10.1109/PROC.1978.10837`. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.kaiser(51, beta=14) + >>> plt.plot(window) + >>> plt.title(r"Kaiser window ($\beta$=14)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's kaiser function + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + alpha = (M - 1) / 2.0 + w = (special.i0(beta * np.sqrt(1 - ((n - alpha) / alpha) ** 2.0)) / + special.i0(beta)) + + return _truncate(w, needs_trunc) + + +def kaiser_bessel_derived(M, beta, *, sym=True): + """Return a Kaiser-Bessel derived window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + Note that this window is only defined for an even + number of points. + beta : float + Kaiser window shape parameter. + sym : bool, optional + This parameter only exists to comply with the interface offered by + the other window functions and to be callable by `get_window`. + When True (default), generates a symmetric window, for use in filter + design. + + Returns + ------- + w : ndarray + The window, normalized to fulfil the Princen-Bradley condition. + + See Also + -------- + kaiser + + Notes + ----- + It is designed to be suitable for use with the modified discrete cosine + transform (MDCT) and is mainly used in audio signal processing and + audio coding. + + .. versionadded:: 1.9.0 + + References + ---------- + .. [1] Bosi, Marina, and Richard E. Goldberg. Introduction to Digital + Audio Coding and Standards. Dordrecht: Kluwer, 2003. + .. [2] Wikipedia, "Kaiser window", + https://en.wikipedia.org/wiki/Kaiser_window + + Examples + -------- + Plot the Kaiser-Bessel derived window based on the wikipedia + reference [2]_: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> N = 50 + >>> for alpha in [0.64, 2.55, 7.64, 31.83]: + ... ax.plot(signal.windows.kaiser_bessel_derived(2*N, np.pi*alpha), + ... label=f"{alpha=}") + >>> ax.grid(True) + >>> ax.set_title("Kaiser-Bessel derived window") + >>> ax.set_ylabel("Amplitude") + >>> ax.set_xlabel("Sample") + >>> ax.set_xticks([0, N, 2*N-1]) + >>> ax.set_xticklabels(["0", "N", "2N+1"]) # doctest: +SKIP + >>> ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.707, 0.8, 1.0]) + >>> fig.legend(loc="center") + >>> fig.tight_layout() + >>> fig.show() + """ + if not sym: + raise ValueError( + "Kaiser-Bessel Derived windows are only defined for symmetric " + "shapes" + ) + elif M < 1: + return np.array([]) + elif M % 2: + raise ValueError( + "Kaiser-Bessel Derived windows are only defined for even number " + "of points" + ) + + kaiser_window = kaiser(M // 2 + 1, beta) + csum = np.cumsum(kaiser_window) + half_window = np.sqrt(csum[:-1] / csum[-1]) + w = np.concatenate((half_window, half_window[::-1]), axis=0) + return w + + +def gaussian(M, std, sym=True): + r"""Return a Gaussian window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + std : float + The standard deviation, sigma. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Gaussian window is defined as + + .. math:: w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 } + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.gaussian(51, std=7) + >>> plt.plot(window) + >>> plt.title(r"Gaussian window ($\sigma$=7)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) - (M - 1.0) / 2.0 + sig2 = 2 * std * std + w = np.exp(-n ** 2 / sig2) + + return _truncate(w, needs_trunc) + + +def general_gaussian(M, p, sig, sym=True): + r"""Return a window with a generalized Gaussian shape. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + p : float + Shape parameter. p = 1 is identical to `gaussian`, p = 0.5 is + the same shape as the Laplace distribution. + sig : float + The standard deviation, sigma. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The generalized Gaussian window is defined as + + .. math:: w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} } + + the half-power point is at + + .. math:: (2 \log(2))^{1/(2 p)} \sigma + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.general_gaussian(51, p=1.5, sig=7) + >>> plt.plot(window) + >>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title(r"Freq. resp. of the gen. Gaussian " + ... r"window (p=1.5, $\sigma$=7)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) - (M - 1.0) / 2.0 + w = np.exp(-0.5 * np.abs(n / sig) ** (2 * p)) + + return _truncate(w, needs_trunc) + + +# `chebwin` contributed by Kumar Appaiah. +def chebwin(M, at, sym=True): + r"""Return a Dolph-Chebyshev window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + at : float + Attenuation (in dB). + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value always normalized to 1 + + Notes + ----- + This window optimizes for the narrowest main lobe width for a given order + `M` and sidelobe equiripple attenuation `at`, using Chebyshev + polynomials. It was originally developed by Dolph to optimize the + directionality of radio antenna arrays. + + Unlike most windows, the Dolph-Chebyshev is defined in terms of its + frequency response: + + .. math:: W(k) = \frac + {\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}} + {\cosh[M \cosh^{-1}(\beta)]} + + where + + .. math:: \beta = \cosh \left [\frac{1}{M} + \cosh^{-1}(10^\frac{A}{20}) \right ] + + and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`). + + The time domain window is then generated using the IFFT, so + power-of-two `M` are the fastest to generate, and prime number `M` are + the slowest. + + The equiripple condition in the frequency domain creates impulses in the + time domain, which appear at the ends of the window. + + References + ---------- + .. [1] C. Dolph, "A current distribution for broadside arrays which + optimizes the relationship between beam width and side-lobe level", + Proceedings of the IEEE, Vol. 34, Issue 6 + .. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter", + American Meteorological Society (April 1997) + http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf + .. [3] F. J. Harris, "On the use of windows for harmonic analysis with the + discrete Fourier transforms", Proceedings of the IEEE, Vol. 66, + No. 1, January 1978 + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.chebwin(51, at=100) + >>> plt.plot(window) + >>> plt.title("Dolph-Chebyshev window (100 dB)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if np.abs(at) < 45: + warnings.warn("This window is not suitable for spectral analysis " + "for attenuation values lower than about 45dB because " + "the equivalent noise bandwidth of a Chebyshev window " + "does not grow monotonically with increasing sidelobe " + "attenuation when the attenuation is smaller than " + "about 45 dB.", + stacklevel=2) + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + # compute the parameter beta + order = M - 1.0 + beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.))) + k = np.r_[0:M] * 1.0 + x = beta * np.cos(np.pi * k / M) + # Find the window's DFT coefficients + # Use analytic definition of Chebyshev polynomial instead of expansion + # from scipy.special. Using the expansion in scipy.special leads to errors. + p = np.zeros(x.shape) + p[x > 1] = np.cosh(order * np.arccosh(x[x > 1])) + p[x < -1] = (2 * (M % 2) - 1) * np.cosh(order * np.arccosh(-x[x < -1])) + p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1])) + + # Appropriate IDFT and filling up + # depending on even/odd M + if M % 2: + w = np.real(sp_fft.fft(p)) + n = (M + 1) // 2 + w = w[:n] + w = np.concatenate((w[n - 1:0:-1], w)) + else: + p = p * np.exp(1.j * np.pi / M * np.r_[0:M]) + w = np.real(sp_fft.fft(p)) + n = M // 2 + 1 + w = np.concatenate((w[n - 1:0:-1], w[1:n])) + w = w / max(w) + + return _truncate(w, needs_trunc) + + +def cosine(M, sym=True): + """Return a window with a simple cosine shape. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + + .. versionadded:: 0.13.0 + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.cosine(51) + >>> plt.plot(window) + >>> plt.title("Cosine window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2047) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the cosine window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + >>> plt.show() + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + w = np.sin(np.pi / M * (np.arange(0, M) + .5)) + + return _truncate(w, needs_trunc) + + +def exponential(M, center=None, tau=1., sym=True): + r"""Return an exponential (or Poisson) window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + center : float, optional + Parameter defining the center location of the window function. + The default value if not given is ``center = (M-1) / 2``. This + parameter must take its default value for symmetric windows. + tau : float, optional + Parameter defining the decay. For ``center = 0`` use + ``tau = -(M-1) / ln(x)`` if ``x`` is the fraction of the window + remaining at the end. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Exponential window is defined as + + .. math:: w(n) = e^{-|n-center| / \tau} + + References + ---------- + .. [1] S. Gade and H. Herlufsen, "Windows to FFT analysis (Part I)", + Technical Review 3, Bruel & Kjaer, 1987. + + Examples + -------- + Plot the symmetric window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> M = 51 + >>> tau = 3.0 + >>> window = signal.windows.exponential(M, tau=tau) + >>> plt.plot(window) + >>> plt.title("Exponential Window (tau=3.0)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -35, 0]) + >>> plt.title("Frequency response of the Exponential window (tau=3.0)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + This function can also generate non-symmetric windows: + + >>> tau2 = -(M-1) / np.log(0.01) + >>> window2 = signal.windows.exponential(M, 0, tau2, False) + >>> plt.figure() + >>> plt.plot(window2) + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + """ + if sym and center is not None: + raise ValueError("If sym==True, center must be None.") + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + if center is None: + center = (M-1) / 2 + + n = np.arange(0, M) + w = np.exp(-np.abs(n-center) / tau) + + return _truncate(w, needs_trunc) + + +def taylor(M, nbar=4, sll=30, norm=True, sym=True): + """ + Return a Taylor window. + + The Taylor window taper function approximates the Dolph-Chebyshev window's + constant sidelobe level for a parameterized number of near-in sidelobes, + but then allows a taper beyond [2]_. + + The SAR (synthetic aperture radar) community commonly uses Taylor + weighting for image formation processing because it provides strong, + selectable sidelobe suppression with minimum broadening of the + mainlobe [1]_. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + nbar : int, optional + Number of nearly constant level sidelobes adjacent to the mainlobe. + sll : float, optional + Desired suppression of sidelobe level in decibels (dB) relative to the + DC gain of the mainlobe. This should be a positive number. + norm : bool, optional + When True (default), divides the window by the largest (middle) value + for odd-length windows or the value that would occur between the two + repeated middle values for even-length windows such that all values + are less than or equal to 1. When False the DC gain will remain at 1 + (0 dB) and the sidelobes will be `sll` dB down. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + out : array + The window. When `norm` is True (default), the maximum value is + normalized to 1 (though the value 1 does not appear if `M` is + even and `sym` is True). + + See Also + -------- + chebwin, kaiser, bartlett, blackman, hamming, hann + + References + ---------- + .. [1] W. Carrara, R. Goodman, and R. Majewski, "Spotlight Synthetic + Aperture Radar: Signal Processing Algorithms" Pages 512-513, + July 1995. + .. [2] Armin Doerry, "Catalog of Window Taper Functions for + Sidelobe Control", 2017. + https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.taylor(51, nbar=20, sll=100, norm=False) + >>> plt.plot(window) + >>> plt.title("Taylor window (100 dB)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Taylor window (100 dB)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ # noqa: E501 + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + # Original text uses a negative sidelobe level parameter and then negates + # it in the calculation of B. To keep consistent with other methods we + # assume the sidelobe level parameter to be positive. + B = 10**(sll / 20) + A = np.arccosh(B) / np.pi + s2 = nbar**2 / (A**2 + (nbar - 0.5)**2) + ma = np.arange(1, nbar) + + Fm = np.empty(nbar-1) + signs = np.empty_like(ma) + signs[::2] = 1 + signs[1::2] = -1 + m2 = ma*ma + for mi, m in enumerate(ma): + numer = signs[mi] * np.prod(1 - m2[mi]/s2/(A**2 + (ma - 0.5)**2)) + denom = 2 * np.prod(1 - m2[mi]/m2[:mi]) * np.prod(1 - m2[mi]/m2[mi+1:]) + Fm[mi] = numer / denom + + def W(n): + return 1 + 2*np.dot(Fm, np.cos( + 2*np.pi*ma[:, np.newaxis]*(n-M/2.+0.5)/M)) + + w = W(np.arange(M)) + + # normalize (Note that this is not described in the original text [1]) + if norm: + scale = 1.0 / W((M - 1) / 2) + w *= scale + + return _truncate(w, needs_trunc) + + +def dpss(M, NW, Kmax=None, sym=True, norm=None, return_ratios=False): + """ + Compute the Discrete Prolate Spheroidal Sequences (DPSS). + + DPSS (or Slepian sequences) are often used in multitaper power spectral + density estimation (see [1]_). The first window in the sequence can be + used to maximize the energy concentration in the main lobe, and is also + called the Slepian window. + + Parameters + ---------- + M : int + Window length. + NW : float + Standardized half bandwidth corresponding to ``2*NW = BW/f0 = BW*M*dt`` + where ``dt`` is taken as 1. + Kmax : int | None, optional + Number of DPSS windows to return (orders ``0`` through ``Kmax-1``). + If None (default), return only a single window of shape ``(M,)`` + instead of an array of windows of shape ``(Kmax, M)``. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + norm : {2, 'approximate', 'subsample'} | None, optional + If 'approximate' or 'subsample', then the windows are normalized by the + maximum, and a correction scale-factor for even-length windows + is applied either using ``M**2/(M**2+NW)`` ("approximate") or + a FFT-based subsample shift ("subsample"), see Notes for details. + If None, then "approximate" is used when ``Kmax=None`` and 2 otherwise + (which uses the l2 norm). + return_ratios : bool, optional + If True, also return the concentration ratios in addition to the + windows. + + Returns + ------- + v : ndarray, shape (Kmax, M) or (M,) + The DPSS windows. Will be 1D if `Kmax` is None. + r : ndarray, shape (Kmax,) or float, optional + The concentration ratios for the windows. Only returned if + `return_ratios` evaluates to True. Will be 0D if `Kmax` is None. + + Notes + ----- + This computation uses the tridiagonal eigenvector formulation given + in [2]_. + + The default normalization for ``Kmax=None``, i.e. window-generation mode, + simply using the l-infinity norm would create a window with two unity + values, which creates slight normalization differences between even and odd + orders. The approximate correction of ``M**2/float(M**2+NW)`` for even + sample numbers is used to counteract this effect (see Examples below). + + For very long signals (e.g., 1e6 elements), it can be useful to compute + windows orders of magnitude shorter and use interpolation (e.g., + `scipy.interpolate.interp1d`) to obtain tapers of length `M`, + but this in general will not preserve orthogonality between the tapers. + + .. versionadded:: 1.1 + + References + ---------- + .. [1] Percival DB, Walden WT. Spectral Analysis for Physical Applications: + Multitaper and Conventional Univariate Techniques. + Cambridge University Press; 1993. + .. [2] Slepian, D. Prolate spheroidal wave functions, Fourier analysis, and + uncertainty V: The discrete case. Bell System Technical Journal, + Volume 57 (1978), 1371430. + .. [3] Kaiser, JF, Schafer RW. On the Use of the I0-Sinh Window for + Spectrum Analysis. IEEE Transactions on Acoustics, Speech and + Signal Processing. ASSP-28 (1): 105-107; 1980. + + Examples + -------- + We can compare the window to `kaiser`, which was invented as an alternative + that was easier to calculate [3]_ (example adapted from + `here `_): + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import windows, freqz + >>> M = 51 + >>> fig, axes = plt.subplots(3, 2, figsize=(5, 7)) + >>> for ai, alpha in enumerate((1, 3, 5)): + ... win_dpss = windows.dpss(M, alpha) + ... beta = alpha*np.pi + ... win_kaiser = windows.kaiser(M, beta) + ... for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')): + ... win /= win.sum() + ... axes[ai, 0].plot(win, color=c, lw=1.) + ... axes[ai, 0].set(xlim=[0, M-1], title=r'$\\alpha$ = %s' % alpha, + ... ylabel='Amplitude') + ... w, h = freqz(win) + ... axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.) + ... axes[ai, 1].set(xlim=[0, np.pi], + ... title=r'$\\beta$ = %0.2f' % beta, + ... ylabel='Magnitude (dB)') + >>> for ax in axes.ravel(): + ... ax.grid(True) + >>> axes[2, 1].legend(['DPSS', 'Kaiser']) + >>> fig.tight_layout() + >>> plt.show() + + And here are examples of the first four windows, along with their + concentration ratios: + + >>> M = 512 + >>> NW = 2.5 + >>> win, eigvals = windows.dpss(M, NW, 4, return_ratios=True) + >>> fig, ax = plt.subplots(1) + >>> ax.plot(win.T, linewidth=1.) + >>> ax.set(xlim=[0, M-1], ylim=[-0.1, 0.1], xlabel='Samples', + ... title='DPSS, M=%d, NW=%0.1f' % (M, NW)) + >>> ax.legend(['win[%d] (%0.4f)' % (ii, ratio) + ... for ii, ratio in enumerate(eigvals)]) + >>> fig.tight_layout() + >>> plt.show() + + Using a standard :math:`l_{\\infty}` norm would produce two unity values + for even `M`, but only one unity value for odd `M`. This produces uneven + window power that can be counteracted by the approximate correction + ``M**2/float(M**2+NW)``, which can be selected by using + ``norm='approximate'`` (which is the same as ``norm=None`` when + ``Kmax=None``, as is the case here). Alternatively, the slower + ``norm='subsample'`` can be used, which uses subsample shifting in the + frequency domain (FFT) to compute the correction: + + >>> Ms = np.arange(1, 41) + >>> factors = (50, 20, 10, 5, 2.0001) + >>> energy = np.empty((3, len(Ms), len(factors))) + >>> for mi, M in enumerate(Ms): + ... for fi, factor in enumerate(factors): + ... NW = M / float(factor) + ... # Corrected using empirical approximation (default) + ... win = windows.dpss(M, NW) + ... energy[0, mi, fi] = np.sum(win ** 2) / np.sqrt(M) + ... # Corrected using subsample shifting + ... win = windows.dpss(M, NW, norm='subsample') + ... energy[1, mi, fi] = np.sum(win ** 2) / np.sqrt(M) + ... # Uncorrected (using l-infinity norm) + ... win /= win.max() + ... energy[2, mi, fi] = np.sum(win ** 2) / np.sqrt(M) + >>> fig, ax = plt.subplots(1) + >>> hs = ax.plot(Ms, energy[2], '-o', markersize=4, + ... markeredgecolor='none') + >>> leg = [hs[-1]] + >>> for hi, hh in enumerate(hs): + ... h1 = ax.plot(Ms, energy[0, :, hi], '-o', markersize=4, + ... color=hh.get_color(), markeredgecolor='none', + ... alpha=0.66) + ... h2 = ax.plot(Ms, energy[1, :, hi], '-o', markersize=4, + ... color=hh.get_color(), markeredgecolor='none', + ... alpha=0.33) + ... if hi == len(hs) - 1: + ... leg.insert(0, h1[0]) + ... leg.insert(0, h2[0]) + >>> ax.set(xlabel='M (samples)', ylabel=r'Power / $\\sqrt{M}$') + >>> ax.legend(leg, ['Uncorrected', r'Corrected: $\\frac{M^2}{M^2+NW}$', + ... 'Corrected (subsample)']) + >>> fig.tight_layout() + + """ + if _len_guards(M): + return np.ones(M) + if norm is None: + norm = 'approximate' if Kmax is None else 2 + known_norms = (2, 'approximate', 'subsample') + if norm not in known_norms: + raise ValueError(f'norm must be one of {known_norms}, got {norm}') + if Kmax is None: + singleton = True + Kmax = 1 + else: + singleton = False + Kmax = operator.index(Kmax) + if not 0 < Kmax <= M: + raise ValueError('Kmax must be greater than 0 and less than M') + if NW >= M/2.: + raise ValueError('NW must be less than M/2.') + if NW <= 0: + raise ValueError('NW must be positive') + M, needs_trunc = _extend(M, sym) + W = float(NW) / M + nidx = np.arange(M) + + # Here we want to set up an optimization problem to find a sequence + # whose energy is maximally concentrated within band [-W,W]. + # Thus, the measure lambda(T,W) is the ratio between the energy within + # that band, and the total energy. This leads to the eigen-system + # (A - (l1)I)v = 0, where the eigenvector corresponding to the largest + # eigenvalue is the sequence with maximally concentrated energy. The + # collection of eigenvectors of this system are called Slepian + # sequences, or discrete prolate spheroidal sequences (DPSS). Only the + # first K, K = 2NW/dt orders of DPSS will exhibit good spectral + # concentration + # [see https://en.wikipedia.org/wiki/Spectral_concentration_problem] + + # Here we set up an alternative symmetric tri-diagonal eigenvalue + # problem such that + # (B - (l2)I)v = 0, and v are our DPSS (but eigenvalues l2 != l1) + # the main diagonal = ([M-1-2*t]/2)**2 cos(2PIW), t=[0,1,2,...,M-1] + # and the first off-diagonal = t(M-t)/2, t=[1,2,...,M-1] + # [see Percival and Walden, 1993] + d = ((M - 1 - 2 * nidx) / 2.) ** 2 * np.cos(2 * np.pi * W) + e = nidx[1:] * (M - nidx[1:]) / 2. + + # only calculate the highest Kmax eigenvalues + w, windows = linalg.eigh_tridiagonal( + d, e, select='i', select_range=(M - Kmax, M - 1)) + w = w[::-1] + windows = windows[:, ::-1].T + + # By convention (Percival and Walden, 1993 pg 379) + # * symmetric tapers (k=0,2,4,...) should have a positive average. + fix_even = (windows[::2].sum(axis=1) < 0) + for i, f in enumerate(fix_even): + if f: + windows[2 * i] *= -1 + # * antisymmetric tapers should begin with a positive lobe + # (this depends on the definition of "lobe", here we'll take the first + # point above the numerical noise, which should be good enough for + # sufficiently smooth functions, and more robust than relying on an + # algorithm that uses max(abs(w)), which is susceptible to numerical + # noise problems) + thresh = max(1e-7, 1. / M) + for i, w in enumerate(windows[1::2]): + if w[w * w > thresh][0] < 0: + windows[2 * i + 1] *= -1 + + # Now find the eigenvalues of the original spectral concentration problem + # Use the autocorr sequence technique from Percival and Walden, 1993 pg 390 + if return_ratios: + dpss_rxx = _fftautocorr(windows) + r = 4 * W * np.sinc(2 * W * nidx) + r[0] = 2 * W + ratios = np.dot(dpss_rxx, r) + if singleton: + ratios = ratios[0] + # Deal with sym and Kmax=None + if norm != 2: + windows /= windows.max() + if M % 2 == 0: + if norm == 'approximate': + correction = M**2 / float(M**2 + NW) + else: + s = sp_fft.rfft(windows[0]) + shift = -(1 - 1./M) * np.arange(1, M//2 + 1) + s[1:] *= 2 * np.exp(-1j * np.pi * shift) + correction = M / s.real.sum() + windows *= correction + # else we're already l2 normed, so do nothing + if needs_trunc: + windows = windows[:, :-1] + if singleton: + windows = windows[0] + return (windows, ratios) if return_ratios else windows + + +def lanczos(M, *, sym=True): + r"""Return a Lanczos window also known as a sinc window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Lanczos window is defined as + + .. math:: w(n) = sinc \left( \frac{2n}{M - 1} - 1 \right) + + where + + .. math:: sinc(x) = \frac{\sin(\pi x)}{\pi x} + + The Lanczos window has reduced Gibbs oscillations and is widely used for + filtering climate timeseries with good properties in the physical and + spectral domains. + + .. versionadded:: 1.10 + + References + ---------- + .. [1] Lanczos, C., and Teichmann, T. (1957). Applied analysis. + Physics Today, 10, 44. + .. [2] Duchon C. E. (1979) Lanczos Filtering in One and Two Dimensions. + Journal of Applied Meteorology, Vol 18, pp 1016-1022. + .. [3] Thomson, R. E. and Emery, W. J. (2014) Data Analysis Methods in + Physical Oceanography (Third Edition), Elsevier, pp 593-637. + .. [4] Wikipedia, "Window function", + http://en.wikipedia.org/wiki/Window_function + + Examples + -------- + Plot the window + + >>> import numpy as np + >>> from scipy.signal.windows import lanczos + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1) + >>> window = lanczos(51) + >>> ax.plot(window) + >>> ax.set_title("Lanczos window") + >>> ax.set_ylabel("Amplitude") + >>> ax.set_xlabel("Sample") + >>> fig.tight_layout() + >>> plt.show() + + and its frequency response: + + >>> fig, ax = plt.subplots(1) + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> ax.plot(freq, response) + >>> ax.set_xlim(-0.5, 0.5) + >>> ax.set_ylim(-120, 0) + >>> ax.set_title("Frequency response of the lanczos window") + >>> ax.set_ylabel("Normalized magnitude [dB]") + >>> ax.set_xlabel("Normalized frequency [cycles per sample]") + >>> fig.tight_layout() + >>> plt.show() + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + # To make sure that the window is symmetric, we concatenate the right hand + # half of the window and the flipped one which is the left hand half of + # the window. + def _calc_right_side_lanczos(n, m): + return np.sinc(2. * np.arange(n, m) / (m - 1) - 1.0) + + if M % 2 == 0: + wh = _calc_right_side_lanczos(M/2, M) + w = np.r_[np.flip(wh), wh] + else: + wh = _calc_right_side_lanczos((M+1)/2, M) + w = np.r_[np.flip(wh), 1.0, wh] + + return _truncate(w, needs_trunc) + + +def _fftautocorr(x): + """Compute the autocorrelation of a real array and crop the result.""" + N = x.shape[-1] + use_N = sp_fft.next_fast_len(2*N-1) + x_fft = sp_fft.rfft(x, use_N, axis=-1) + cxy = sp_fft.irfft(x_fft * x_fft.conj(), n=use_N)[:, :N] + # Or equivalently (but in most cases slower): + # cxy = np.array([np.convolve(xx, yy[::-1], mode='full') + # for xx, yy in zip(x, x)])[:, N-1:2*N-1] + return cxy + + +_win_equiv_raw = { + ('barthann', 'brthan', 'bth'): (barthann, False), + ('bartlett', 'bart', 'brt'): (bartlett, False), + ('blackman', 'black', 'blk'): (blackman, False), + ('blackmanharris', 'blackharr', 'bkh'): (blackmanharris, False), + ('bohman', 'bman', 'bmn'): (bohman, False), + ('boxcar', 'box', 'ones', + 'rect', 'rectangular'): (boxcar, False), + ('chebwin', 'cheb'): (chebwin, True), + ('cosine', 'halfcosine'): (cosine, False), + ('dpss',): (dpss, True), + ('exponential', 'poisson'): (exponential, False), + ('flattop', 'flat', 'flt'): (flattop, False), + ('gaussian', 'gauss', 'gss'): (gaussian, True), + ('general cosine', 'general_cosine'): (general_cosine, True), + ('general gaussian', 'general_gaussian', + 'general gauss', 'general_gauss', 'ggs'): (general_gaussian, True), + ('general hamming', 'general_hamming'): (general_hamming, True), + ('hamming', 'hamm', 'ham'): (hamming, False), + ('hann', 'han'): (hann, False), + ('kaiser', 'ksr'): (kaiser, True), + ('kaiser bessel derived', 'kbd'): (kaiser_bessel_derived, True), + ('lanczos', 'sinc'): (lanczos, False), + ('nuttall', 'nutl', 'nut'): (nuttall, False), + ('parzen', 'parz', 'par'): (parzen, False), + ('taylor', 'taylorwin'): (taylor, False), + ('triangle', 'triang', 'tri'): (triang, False), + ('tukey', 'tuk'): (tukey, False), +} + +# Fill dict with all valid window name strings +_win_equiv = {} +for k, v in _win_equiv_raw.items(): + for key in k: + _win_equiv[key] = v[0] + +# Keep track of which windows need additional parameters +_needs_param = set() +for k, v in _win_equiv_raw.items(): + if v[1]: + _needs_param.update(k) + + +def get_window(window, Nx, fftbins=True): + """ + Return a window of a given length and type. + + Parameters + ---------- + window : string, float, or tuple + The type of window to create. See below for more details. + Nx : int + The number of samples in the window. + fftbins : bool, optional + If True (default), create a "periodic" window, ready to use with + `ifftshift` and be multiplied by the result of an FFT (see also + :func:`~scipy.fft.fftfreq`). + If False, create a "symmetric" window, for use in filter design. + + Returns + ------- + get_window : ndarray + Returns a window of length `Nx` and type `window` + + Notes + ----- + Window types: + + - `~scipy.signal.windows.boxcar` + - `~scipy.signal.windows.triang` + - `~scipy.signal.windows.blackman` + - `~scipy.signal.windows.hamming` + - `~scipy.signal.windows.hann` + - `~scipy.signal.windows.bartlett` + - `~scipy.signal.windows.flattop` + - `~scipy.signal.windows.parzen` + - `~scipy.signal.windows.bohman` + - `~scipy.signal.windows.blackmanharris` + - `~scipy.signal.windows.nuttall` + - `~scipy.signal.windows.barthann` + - `~scipy.signal.windows.cosine` + - `~scipy.signal.windows.exponential` + - `~scipy.signal.windows.tukey` + - `~scipy.signal.windows.taylor` + - `~scipy.signal.windows.lanczos` + - `~scipy.signal.windows.kaiser` (needs beta) + - `~scipy.signal.windows.kaiser_bessel_derived` (needs beta) + - `~scipy.signal.windows.gaussian` (needs standard deviation) + - `~scipy.signal.windows.general_cosine` (needs weighting coefficients) + - `~scipy.signal.windows.general_gaussian` (needs power, width) + - `~scipy.signal.windows.general_hamming` (needs window coefficient) + - `~scipy.signal.windows.dpss` (needs normalized half-bandwidth) + - `~scipy.signal.windows.chebwin` (needs attenuation) + + + If the window requires no parameters, then `window` can be a string. + + If the window requires parameters, then `window` must be a tuple + with the first argument the string name of the window, and the next + arguments the needed parameters. + + If `window` is a floating point number, it is interpreted as the beta + parameter of the `~scipy.signal.windows.kaiser` window. + + Each of the window types listed above is also the name of + a function that can be called directly to create a window of + that type. + + Examples + -------- + >>> from scipy import signal + >>> signal.get_window('triang', 7) + array([ 0.125, 0.375, 0.625, 0.875, 0.875, 0.625, 0.375]) + >>> signal.get_window(('kaiser', 4.0), 9) + array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093, + 0.97885093, 0.82160913, 0.56437221, 0.29425961]) + >>> signal.get_window(('exponential', None, 1.), 9) + array([ 0.011109 , 0.03019738, 0.082085 , 0.22313016, 0.60653066, + 0.60653066, 0.22313016, 0.082085 , 0.03019738]) + >>> signal.get_window(4.0, 9) + array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093, + 0.97885093, 0.82160913, 0.56437221, 0.29425961]) + + """ + sym = not fftbins + try: + beta = float(window) + except (TypeError, ValueError) as e: + args = () + if isinstance(window, tuple): + winstr = window[0] + if len(window) > 1: + args = window[1:] + elif isinstance(window, str): + if window in _needs_param: + raise ValueError("The '" + window + "' window needs one or " + "more parameters -- pass a tuple.") from e + else: + winstr = window + else: + raise ValueError( + f"{str(type(window))} as window type is not supported.") from e + + try: + winfunc = _win_equiv[winstr] + except KeyError as e: + raise ValueError("Unknown window type.") from e + + if winfunc is dpss: + params = (Nx,) + args + (None,) + else: + params = (Nx,) + args + else: + winfunc = kaiser + params = (Nx, beta) + + return winfunc(*params, sym=sym) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/windows.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..6858f71aceeb29ca6110864d01fb250e8c8ce403 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/windows.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal.windows` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall', + 'blackmanharris', 'flattop', 'bartlett', 'barthann', + 'hamming', 'kaiser', 'gaussian', 'general_cosine', + 'general_gaussian', 'general_hamming', 'chebwin', 'cosine', + 'hann', 'exponential', 'tukey', 'taylor', 'dpss', 'get_window', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal.windows", module="windows", + private_modules=["_windows"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3523f9fbe3f56b267f126fde4119d4ca5e3622a1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae103c09b78729845ed524b7eafa7e8235cd6b5d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59f758f21afea9069077e809a93f2ed1cf15f85a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e8b3feb0cbfb2ea0878d8134cd7c30a10e6273f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8b19532d1942e43503aa0fb73d21f8b2e718ca9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d5ea855d5b76219a2ae7570e2126f4994ba2618 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca88289ddb9a89905436de5215cfa79c1edbb487 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51b8d65c99c0d0aa9e16948c22f50976f0bf8b41 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3281c092195c61e875a13e9d3e282485fd3cb28d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e30004077c08fc4c196cafae2fb4af19d14bb171 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad0531a7455a86025ba03cff5e8dba06ee4947a4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10fae4bdee1a549ec59cc5f0b1e21a3c8623e2f8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b255035455260483beaf2d0328dea496f481ab3a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e48af73a585ba04246c36f8eedb28b87af65eef Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4ca83bb3ff35e6e7e6e0ee65a7fb5c950d53468 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a65bf4ae40ecc947a6f7804bdfa0bd6f05cf9efd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a33df5a20ea6fe4591a8acbfeea86985318d211d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10241a15c72169e1ac853491e49716fb73168b36 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08277fecb3caef39ac4db71cc0c415a2ec8c75da Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ead3ad3052142ca08b8ec30b720567e9dc2da667 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b902b296329f094c3ac064ed712bf399106d305 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78304d4ba861956663aa919f58a55010f3033a4b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b451cf4e7ca914cf83f747739590fa7958aca8c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80e4fb75d0e6199080b886ee106071a69dee2c72 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12d88395d51fb6587806d352a587a9c05be52516 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47a14c6b48ddda35fc1338d7c6e1da1af2cb9a24 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..856855358fc18f0e9ebb29d99a5bcedde2194d9b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..815b6afef356f320ec91403f4cdfb4f6ef710946 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d3c985de965e35293c0d75eb54b868ceb91a62e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcda8f4259bb80d4b9b6b97ca08a298a24785019 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ef997e273fba46aa4e7e1b81044a646e5650c4e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00ab19af4748147d748fccb51a3710d5c711f4b4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py @@ -0,0 +1,210 @@ +r""" +Compressed sparse graph routines (:mod:`scipy.sparse.csgraph`) +============================================================== + +.. currentmodule:: scipy.sparse.csgraph + +Fast graph algorithms based on sparse matrix representations. + +Contents +-------- + +.. autosummary:: + :toctree: generated/ + + connected_components -- determine connected components of a graph + laplacian -- compute the laplacian of a graph + shortest_path -- compute the shortest path between points on a positive graph + dijkstra -- use Dijkstra's algorithm for shortest path + floyd_warshall -- use the Floyd-Warshall algorithm for shortest path + bellman_ford -- use the Bellman-Ford algorithm for shortest path + johnson -- use Johnson's algorithm for shortest path + yen -- use Yen's algorithm for K-shortest paths between to nodes. + breadth_first_order -- compute a breadth-first order of nodes + depth_first_order -- compute a depth-first order of nodes + breadth_first_tree -- construct the breadth-first tree from a given node + depth_first_tree -- construct a depth-first tree from a given node + minimum_spanning_tree -- construct the minimum spanning tree of a graph + reverse_cuthill_mckee -- compute permutation for reverse Cuthill-McKee ordering + maximum_flow -- solve the maximum flow problem for a graph + maximum_bipartite_matching -- compute a maximum matching of a bipartite graph + min_weight_full_bipartite_matching - compute a minimum weight full matching of a bipartite graph + structural_rank -- compute the structural rank of a graph + NegativeCycleError + +.. autosummary:: + :toctree: generated/ + + construct_dist_matrix + csgraph_from_dense + csgraph_from_masked + csgraph_masked_from_dense + csgraph_to_dense + csgraph_to_masked + reconstruct_path + +Graph Representations +--------------------- +This module uses graphs which are stored in a matrix format. A +graph with N nodes can be represented by an (N x N) adjacency matrix G. +If there is a connection from node i to node j, then G[i, j] = w, where +w is the weight of the connection. For nodes i and j which are +not connected, the value depends on the representation: + +- for dense array representations, non-edges are represented by + G[i, j] = 0, infinity, or NaN. + +- for dense masked representations (of type np.ma.MaskedArray), non-edges + are represented by masked values. This can be useful when graphs with + zero-weight edges are desired. + +- for sparse array representations, non-edges are represented by + non-entries in the matrix. This sort of sparse representation also + allows for edges with zero weights. + +As a concrete example, imagine that you would like to represent the following +undirected graph:: + + G + + (0) + / \ + 1 2 + / \ + (2) (1) + +This graph has three nodes, where node 0 and 1 are connected by an edge of +weight 2, and nodes 0 and 2 are connected by an edge of weight 1. +We can construct the dense, masked, and sparse representations as follows, +keeping in mind that an undirected graph is represented by a symmetric matrix:: + + >>> import numpy as np + >>> G_dense = np.array([[0, 2, 1], + ... [2, 0, 0], + ... [1, 0, 0]]) + >>> G_masked = np.ma.masked_values(G_dense, 0) + >>> from scipy.sparse import csr_array + >>> G_sparse = csr_array(G_dense) + +This becomes more difficult when zero edges are significant. For example, +consider the situation when we slightly modify the above graph:: + + G2 + + (0) + / \ + 0 2 + / \ + (2) (1) + +This is identical to the previous graph, except nodes 0 and 2 are connected +by an edge of zero weight. In this case, the dense representation above +leads to ambiguities: how can non-edges be represented if zero is a meaningful +value? In this case, either a masked or sparse representation must be used +to eliminate the ambiguity:: + + >>> import numpy as np + >>> G2_data = np.array([[np.inf, 2, 0 ], + ... [2, np.inf, np.inf], + ... [0, np.inf, np.inf]]) + >>> G2_masked = np.ma.masked_invalid(G2_data) + >>> from scipy.sparse.csgraph import csgraph_from_dense + >>> # G2_sparse = csr_array(G2_data) would give the wrong result + >>> G2_sparse = csgraph_from_dense(G2_data, null_value=np.inf) + >>> G2_sparse.data + array([ 2., 0., 2., 0.]) + +Here we have used a utility routine from the csgraph submodule in order to +convert the dense representation to a sparse representation which can be +understood by the algorithms in submodule. By viewing the data array, we +can see that the zero values are explicitly encoded in the graph. + +Directed vs. undirected +^^^^^^^^^^^^^^^^^^^^^^^ +Matrices may represent either directed or undirected graphs. This is +specified throughout the csgraph module by a boolean keyword. Graphs are +assumed to be directed by default. In a directed graph, traversal from node +i to node j can be accomplished over the edge G[i, j], but not the edge +G[j, i]. Consider the following dense graph:: + + >>> import numpy as np + >>> G_dense = np.array([[0, 1, 0], + ... [2, 0, 3], + ... [0, 4, 0]]) + +When ``directed=True`` we get the graph:: + + ---1--> ---3--> + (0) (1) (2) + <--2--- <--4--- + +In a non-directed graph, traversal from node i to node j can be +accomplished over either G[i, j] or G[j, i]. If both edges are not null, +and the two have unequal weights, then the smaller of the two is used. + +So for the same graph, when ``directed=False`` we get the graph:: + + (0)--1--(1)--3--(2) + +Note that a symmetric matrix will represent an undirected graph, regardless +of whether the 'directed' keyword is set to True or False. In this case, +using ``directed=True`` generally leads to more efficient computation. + +The routines in this module accept as input either scipy.sparse representations +(csr, csc, or lil format), masked representations, or dense representations +with non-edges indicated by zeros, infinities, and NaN entries. +""" # noqa: E501 + +__docformat__ = "restructuredtext en" + +__all__ = ['connected_components', + 'laplacian', + 'shortest_path', + 'floyd_warshall', + 'dijkstra', + 'bellman_ford', + 'johnson', + 'yen', + 'breadth_first_order', + 'depth_first_order', + 'breadth_first_tree', + 'depth_first_tree', + 'minimum_spanning_tree', + 'reverse_cuthill_mckee', + 'maximum_flow', + 'maximum_bipartite_matching', + 'min_weight_full_bipartite_matching', + 'structural_rank', + 'construct_dist_matrix', + 'reconstruct_path', + 'csgraph_masked_from_dense', + 'csgraph_from_dense', + 'csgraph_from_masked', + 'csgraph_to_dense', + 'csgraph_to_masked', + 'NegativeCycleError'] + +from ._laplacian import laplacian +from ._shortest_path import ( + shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, yen, + NegativeCycleError +) +from ._traversal import ( + breadth_first_order, depth_first_order, breadth_first_tree, + depth_first_tree, connected_components +) +from ._min_spanning_tree import minimum_spanning_tree +from ._flow import maximum_flow +from ._matching import ( + maximum_bipartite_matching, min_weight_full_bipartite_matching +) +from ._reordering import reverse_cuthill_mckee, structural_rank +from ._tools import ( + construct_dist_matrix, reconstruct_path, csgraph_from_dense, + csgraph_to_dense, csgraph_masked_from_dense, csgraph_from_masked, + csgraph_to_masked +) + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8bd0a339bba1ca8a477c8f087a6e109b8966340 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bba680dadfa12d84a23212454d04d462dc636c0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3fde7fd8f53ca1524ad4a2283cad64709eb226e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py new file mode 100644 index 0000000000000000000000000000000000000000..e5529a0662a3f9db006bc5411664908f10d8fe23 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py @@ -0,0 +1,563 @@ +""" +Laplacian of a compressed-sparse graph +""" + +import numpy as np +from scipy.sparse import issparse +from scipy.sparse.linalg import LinearOperator +from scipy.sparse._sputils import convert_pydata_sparse_to_scipy, is_pydata_spmatrix + + +############################################################################### +# Graph laplacian +def laplacian( + csgraph, + normed=False, + return_diag=False, + use_out_degree=False, + *, + copy=True, + form="array", + dtype=None, + symmetrized=False, +): + """ + Return the Laplacian of a directed graph. + + Parameters + ---------- + csgraph : array_like or sparse array or matrix, 2 dimensions + compressed-sparse graph, with shape (N, N). + normed : bool, optional + If True, then compute symmetrically normalized Laplacian. + Default: False. + return_diag : bool, optional + If True, then also return an array related to vertex degrees. + Default: False. + use_out_degree : bool, optional + If True, then use out-degree instead of in-degree. + This distinction matters only if the graph is asymmetric. + Default: False. + copy: bool, optional + If False, then change `csgraph` in place if possible, + avoiding doubling the memory use. + Default: True, for backward compatibility. + form: 'array', or 'function', or 'lo' + Determines the format of the output Laplacian: + + * 'array' is a numpy array; + * 'function' is a pointer to evaluating the Laplacian-vector + or Laplacian-matrix product; + * 'lo' results in the format of the `LinearOperator`. + + Choosing 'function' or 'lo' always avoids doubling + the memory use, ignoring `copy` value. + Default: 'array', for backward compatibility. + dtype: None or one of numeric numpy dtypes, optional + The dtype of the output. If ``dtype=None``, the dtype of the + output matches the dtype of the input csgraph, except for + the case ``normed=True`` and integer-like csgraph, where + the output dtype is 'float' allowing accurate normalization, + but dramatically increasing the memory use. + Default: None, for backward compatibility. + symmetrized: bool, optional + If True, then the output Laplacian is symmetric/Hermitian. + The symmetrization is done by ``csgraph + csgraph.T.conj`` + without dividing by 2 to preserve integer dtypes if possible + prior to the construction of the Laplacian. + The symmetrization will increase the memory footprint of + sparse matrices unless the sparsity pattern is symmetric or + `form` is 'function' or 'lo'. + Default: False, for backward compatibility. + + Returns + ------- + lap : ndarray, or sparse array or matrix, or `LinearOperator` + The N x N Laplacian of csgraph. It will be a NumPy array (dense) + if the input was dense, or a sparse array otherwise, or + the format of a function or `LinearOperator` if + `form` equals 'function' or 'lo', respectively. + diag : ndarray, optional + The length-N main diagonal of the Laplacian matrix. + For the normalized Laplacian, this is the array of square roots + of vertex degrees or 1 if the degree is zero. + + Notes + ----- + The Laplacian matrix of a graph is sometimes referred to as the + "Kirchhoff matrix" or just the "Laplacian", and is useful in many + parts of spectral graph theory. + In particular, the eigen-decomposition of the Laplacian can give + insight into many properties of the graph, e.g., + is commonly used for spectral data embedding and clustering. + + The constructed Laplacian doubles the memory use if ``copy=True`` and + ``form="array"`` which is the default. + Choosing ``copy=False`` has no effect unless ``form="array"`` + or the matrix is sparse in the ``coo`` format, or dense array, except + for the integer input with ``normed=True`` that forces the float output. + + Sparse input is reformatted into ``coo`` if ``form="array"``, + which is the default. + + If the input adjacency matrix is not symmetric, the Laplacian is + also non-symmetric unless ``symmetrized=True`` is used. + + Diagonal entries of the input adjacency matrix are ignored and + replaced with zeros for the purpose of normalization where ``normed=True``. + The normalization uses the inverse square roots of row-sums of the input + adjacency matrix, and thus may fail if the row-sums contain + negative or complex with a non-zero imaginary part values. + + The normalization is symmetric, making the normalized Laplacian also + symmetric if the input csgraph was symmetric. + + References + ---------- + .. [1] Laplacian matrix. https://en.wikipedia.org/wiki/Laplacian_matrix + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csgraph + + Our first illustration is the symmetric graph + + >>> G = np.arange(4) * np.arange(4)[:, np.newaxis] + >>> G + array([[0, 0, 0, 0], + [0, 1, 2, 3], + [0, 2, 4, 6], + [0, 3, 6, 9]]) + + and its symmetric Laplacian matrix + + >>> csgraph.laplacian(G) + array([[ 0, 0, 0, 0], + [ 0, 5, -2, -3], + [ 0, -2, 8, -6], + [ 0, -3, -6, 9]]) + + The non-symmetric graph + + >>> G = np.arange(9).reshape(3, 3) + >>> G + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + + has different row- and column sums, resulting in two varieties + of the Laplacian matrix, using an in-degree, which is the default + + >>> L_in_degree = csgraph.laplacian(G) + >>> L_in_degree + array([[ 9, -1, -2], + [-3, 8, -5], + [-6, -7, 7]]) + + or alternatively an out-degree + + >>> L_out_degree = csgraph.laplacian(G, use_out_degree=True) + >>> L_out_degree + array([[ 3, -1, -2], + [-3, 8, -5], + [-6, -7, 13]]) + + Constructing a symmetric Laplacian matrix, one can add the two as + + >>> L_in_degree + L_out_degree.T + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + or use the ``symmetrized=True`` option + + >>> csgraph.laplacian(G, symmetrized=True) + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + that is equivalent to symmetrizing the original graph + + >>> csgraph.laplacian(G + G.T) + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + The goal of normalization is to make the non-zero diagonal entries + of the Laplacian matrix to be all unit, also scaling off-diagonal + entries correspondingly. The normalization can be done manually, e.g., + + >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) + >>> L, d = csgraph.laplacian(G, return_diag=True) + >>> L + array([[ 2, -1, -1], + [-1, 2, -1], + [-1, -1, 2]]) + >>> d + array([2, 2, 2]) + >>> scaling = np.sqrt(d) + >>> scaling + array([1.41421356, 1.41421356, 1.41421356]) + >>> (1/scaling)*L*(1/scaling) + array([[ 1. , -0.5, -0.5], + [-0.5, 1. , -0.5], + [-0.5, -0.5, 1. ]]) + + Or using ``normed=True`` option + + >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True) + >>> L + array([[ 1. , -0.5, -0.5], + [-0.5, 1. , -0.5], + [-0.5, -0.5, 1. ]]) + + which now instead of the diagonal returns the scaling coefficients + + >>> d + array([1.41421356, 1.41421356, 1.41421356]) + + Zero scaling coefficients are substituted with 1s, where scaling + has thus no effect, e.g., + + >>> G = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]]) + >>> G + array([[0, 0, 0], + [0, 0, 1], + [0, 1, 0]]) + >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True) + >>> L + array([[ 0., -0., -0.], + [-0., 1., -1.], + [-0., -1., 1.]]) + >>> d + array([1., 1., 1.]) + + Only the symmetric normalization is implemented, resulting + in a symmetric Laplacian matrix if and only if its graph is symmetric + and has all non-negative degrees, like in the examples above. + + The output Laplacian matrix is by default a dense array or a sparse + array or matrix inferring its class, shape, format, and dtype from + the input graph matrix: + + >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).astype(np.float32) + >>> G + array([[0., 1., 1.], + [1., 0., 1.], + [1., 1., 0.]], dtype=float32) + >>> csgraph.laplacian(G) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]], dtype=float32) + + but can alternatively be generated matrix-free as a LinearOperator: + + >>> L = csgraph.laplacian(G, form="lo") + >>> L + <3x3 _CustomLinearOperator with dtype=float32> + >>> L(np.eye(3)) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]]) + + or as a lambda-function: + + >>> L = csgraph.laplacian(G, form="function") + >>> L + . at 0x0000012AE6F5A598> + >>> L(np.eye(3)) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]]) + + The Laplacian matrix is used for + spectral data clustering and embedding + as well as for spectral graph partitioning. + Our final example illustrates the latter + for a noisy directed linear graph. + + >>> from scipy.sparse import diags_array, random_array + >>> from scipy.sparse.linalg import lobpcg + + Create a directed linear graph with ``N=35`` vertices + using a sparse adjacency matrix ``G``: + + >>> N = 35 + >>> G = diags_array(np.ones(N - 1), offsets=1, format="csr") + + Fix a random seed ``rng`` and add a random sparse noise to the graph ``G``: + + >>> rng = np.random.default_rng() + >>> G += 1e-2 * random_array((N, N), density=0.1, rng=rng) + + Set initial approximations for eigenvectors: + + >>> X = rng.random((N, 2)) + + The constant vector of ones is always a trivial eigenvector + of the non-normalized Laplacian to be filtered out: + + >>> Y = np.ones((N, 1)) + + Alternating (1) the sign of the graph weights allows determining + labels for spectral max- and min- cuts in a single loop. + Since the graph is undirected, the option ``symmetrized=True`` + must be used in the construction of the Laplacian. + The option ``normed=True`` cannot be used in (2) for the negative weights + here as the symmetric normalization evaluates square roots. + The option ``form="lo"`` in (2) is matrix-free, i.e., guarantees + a fixed memory footprint and read-only access to the graph. + Calling the eigenvalue solver ``lobpcg`` (3) computes the Fiedler vector + that determines the labels as the signs of its components in (5). + Since the sign in an eigenvector is not deterministic and can flip, + we fix the sign of the first component to be always +1 in (4). + + >>> for cut in ["max", "min"]: + ... G = -G # 1. + ... L = csgraph.laplacian(G, symmetrized=True, form="lo") # 2. + ... _, eves = lobpcg(L, X, Y=Y, largest=False, tol=1e-2) # 3. + ... eves *= np.sign(eves[0, 0]) # 4. + ... print(cut + "-cut labels:\\n", 1 * (eves[:, 0]>0)) # 5. + max-cut labels: + [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1] + min-cut labels: + [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] + + As anticipated for a (slightly noisy) linear graph, + the max-cut strips all the edges of the graph coloring all + odd vertices into one color and all even vertices into another one, + while the balanced min-cut partitions the graph + in the middle by deleting a single edge. + Both determined partitions are optimal. + """ + is_pydata_sparse = is_pydata_spmatrix(csgraph) + if is_pydata_sparse: + pydata_sparse_cls = csgraph.__class__ + csgraph = convert_pydata_sparse_to_scipy(csgraph) + if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]: + raise ValueError('csgraph must be a square matrix or array') + + if normed and ( + np.issubdtype(csgraph.dtype, np.signedinteger) + or np.issubdtype(csgraph.dtype, np.uint) + ): + csgraph = csgraph.astype(np.float64) + + if form == "array": + create_lap = ( + _laplacian_sparse if issparse(csgraph) else _laplacian_dense + ) + else: + create_lap = ( + _laplacian_sparse_flo + if issparse(csgraph) + else _laplacian_dense_flo + ) + + degree_axis = 1 if use_out_degree else 0 + + lap, d = create_lap( + csgraph, + normed=normed, + axis=degree_axis, + copy=copy, + form=form, + dtype=dtype, + symmetrized=symmetrized, + ) + if is_pydata_sparse: + lap = pydata_sparse_cls.from_scipy_sparse(lap) + if return_diag: + return lap, d + return lap + + +def _setdiag_dense(m, d): + step = len(d) + 1 + m.flat[::step] = d + + +def _laplace(m, d): + return lambda v: v * d[:, np.newaxis] - m @ v + + +def _laplace_normed(m, d, nd): + laplace = _laplace(m, d) + return lambda v: nd[:, np.newaxis] * laplace(v * nd[:, np.newaxis]) + + +def _laplace_sym(m, d): + return ( + lambda v: v * d[:, np.newaxis] + - m @ v + - np.transpose(np.conjugate(np.transpose(np.conjugate(v)) @ m)) + ) + + +def _laplace_normed_sym(m, d, nd): + laplace_sym = _laplace_sym(m, d) + return lambda v: nd[:, np.newaxis] * laplace_sym(v * nd[:, np.newaxis]) + + +def _linearoperator(mv, shape, dtype): + return LinearOperator(matvec=mv, matmat=mv, shape=shape, dtype=dtype) + + +def _laplacian_sparse_flo(graph, normed, axis, copy, form, dtype, symmetrized): + # The keyword argument `copy` is unused and has no effect here. + del copy + + if dtype is None: + dtype = graph.dtype + + graph_sum = np.asarray(graph.sum(axis=axis)).ravel() + graph_diagonal = graph.diagonal() + diag = graph_sum - graph_diagonal + if symmetrized: + graph_sum += np.asarray(graph.sum(axis=1 - axis)).ravel() + diag = graph_sum - graph_diagonal - graph_diagonal + + if normed: + isolated_node_mask = diag == 0 + w = np.where(isolated_node_mask, 1, np.sqrt(diag)) + if symmetrized: + md = _laplace_normed_sym(graph, graph_sum, 1.0 / w) + else: + md = _laplace_normed(graph, graph_sum, 1.0 / w) + if form == "function": + return md, w.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, w.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + else: + if symmetrized: + md = _laplace_sym(graph, graph_sum) + else: + md = _laplace(graph, graph_sum) + if form == "function": + return md, diag.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, diag.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + + +def _laplacian_sparse(graph, normed, axis, copy, form, dtype, symmetrized): + # The keyword argument `form` is unused and has no effect here. + del form + + if dtype is None: + dtype = graph.dtype + + needs_copy = False + if graph.format in ('lil', 'dok'): + m = graph.tocoo() + else: + m = graph + if copy: + needs_copy = True + + if symmetrized: + m += m.T.conj() + + w = np.asarray(m.sum(axis=axis)).ravel() - m.diagonal() + if normed: + m = m.tocoo(copy=needs_copy) + isolated_node_mask = (w == 0) + w = np.where(isolated_node_mask, 1, np.sqrt(w)) + m.data /= w[m.row] + m.data /= w[m.col] + m.data *= -1 + m.setdiag(1 - isolated_node_mask) + else: + if m.format == 'dia': + m = m.copy() + else: + m = m.tocoo(copy=needs_copy) + m.data *= -1 + m.setdiag(w) + + return m.astype(dtype, copy=False), w.astype(dtype) + + +def _laplacian_dense_flo(graph, normed, axis, copy, form, dtype, symmetrized): + + if copy: + m = np.array(graph) + else: + m = np.asarray(graph) + + if dtype is None: + dtype = m.dtype + + graph_sum = m.sum(axis=axis) + graph_diagonal = m.diagonal() + diag = graph_sum - graph_diagonal + if symmetrized: + graph_sum += m.sum(axis=1 - axis) + diag = graph_sum - graph_diagonal - graph_diagonal + + if normed: + isolated_node_mask = diag == 0 + w = np.where(isolated_node_mask, 1, np.sqrt(diag)) + if symmetrized: + md = _laplace_normed_sym(m, graph_sum, 1.0 / w) + else: + md = _laplace_normed(m, graph_sum, 1.0 / w) + if form == "function": + return md, w.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, w.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + else: + if symmetrized: + md = _laplace_sym(m, graph_sum) + else: + md = _laplace(m, graph_sum) + if form == "function": + return md, diag.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, diag.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + + +def _laplacian_dense(graph, normed, axis, copy, form, dtype, symmetrized): + + if form != "array": + raise ValueError(f'{form!r} must be "array"') + + if dtype is None: + dtype = graph.dtype + + if copy: + m = np.array(graph) + else: + m = np.asarray(graph) + + if dtype is None: + dtype = m.dtype + + if symmetrized: + m += m.T.conj() + np.fill_diagonal(m, 0) + w = m.sum(axis=axis) + if normed: + isolated_node_mask = (w == 0) + w = np.where(isolated_node_mask, 1, np.sqrt(w)) + m /= w + m /= w[:, np.newaxis] + m *= -1 + _setdiag_dense(m, 1 - isolated_node_mask) + else: + m *= -1 + _setdiag_dense(m, w) + + return m.astype(dtype, copy=False), w.astype(dtype, copy=False) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb9ce811b73e751ebb1cd6b226b73f7bcfe7ceb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py @@ -0,0 +1,66 @@ +import numpy as np +from scipy.sparse import issparse +from scipy.sparse._sputils import convert_pydata_sparse_to_scipy +from scipy.sparse.csgraph._tools import ( + csgraph_to_dense, csgraph_from_dense, + csgraph_masked_from_dense, csgraph_from_masked +) + +DTYPE = np.float64 + + +def validate_graph(csgraph, directed, dtype=DTYPE, + csr_output=True, dense_output=True, + copy_if_dense=False, copy_if_sparse=False, + null_value_in=0, null_value_out=np.inf, + infinity_null=True, nan_null=True): + """Routine for validation and conversion of csgraph inputs""" + if not (csr_output or dense_output): + raise ValueError("Internal: dense or csr output must be true") + + accept_fv = [null_value_in] + if infinity_null: + accept_fv.append(np.inf) + if nan_null: + accept_fv.append(np.nan) + csgraph = convert_pydata_sparse_to_scipy(csgraph, accept_fv=accept_fv) + + # if undirected and csc storage, then transposing in-place + # is quicker than later converting to csr. + if (not directed) and issparse(csgraph) and csgraph.format == "csc": + csgraph = csgraph.T + + if issparse(csgraph): + if csr_output: + csgraph = csgraph.tocsr(copy=copy_if_sparse).astype(DTYPE, copy=False) + else: + csgraph = csgraph_to_dense(csgraph, null_value=null_value_out) + elif np.ma.isMaskedArray(csgraph): + if dense_output: + mask = csgraph.mask + csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_masked(csgraph) + else: + if dense_output: + csgraph = csgraph_masked_from_dense(csgraph, + copy=copy_if_dense, + null_value=null_value_in, + nan_null=nan_null, + infinity_null=infinity_null) + mask = csgraph.mask + csgraph = np.asarray(csgraph.data, dtype=DTYPE) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_dense(csgraph, null_value=null_value_in, + infinity_null=infinity_null, + nan_null=nan_null) + + if csgraph.ndim != 2: + raise ValueError("compressed-sparse graph must be 2-D") + + if csgraph.shape[0] != csgraph.shape[1]: + raise ValueError("compressed-sparse graph must be shape (N, N)") + + return csgraph diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py new file mode 100644 index 0000000000000000000000000000000000000000..0b190a24deb9f2818893a120f8ea376fbfb8d6fe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py @@ -0,0 +1,119 @@ +import numpy as np +from numpy.testing import assert_equal, assert_array_almost_equal +from scipy.sparse import csgraph, csr_array + + +def test_weak_connections(): + Xde = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + + Xsp = csgraph.csgraph_from_dense(Xde, null_value=0) + + for X in Xsp, Xde: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + + assert_equal(n_components, 2) + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections(): + X1de = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + X2de = X1de + X1de.T + + X1sp = csgraph.csgraph_from_dense(X1de, null_value=0) + X2sp = csgraph.csgraph_from_dense(X2de, null_value=0) + + for X in X1sp, X1de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 3) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2]) + + for X in X2sp, X2de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + assert_equal(n_components, 5) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) + + +def test_weak_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) + + +def test_ticket1876(): + # Regression test: this failed in the original implementation + # There should be two strongly-connected components; previously gave one + g = np.array([[0, 1, 1, 0], + [1, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 1, 0]]) + n_components, labels = csgraph.connected_components(g, connection='strong') + + assert_equal(n_components, 2) + assert_equal(labels[0], labels[1]) + assert_equal(labels[2], labels[3]) + + +def test_fully_connected_graph(): + # Fully connected dense matrices raised an exception. + # https://github.com/scipy/scipy/issues/3818 + g = np.ones((4, 4)) + n_components, labels = csgraph.connected_components(g) + assert_equal(n_components, 1) + + +def test_int64_indices_undirected(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=False) + assert n == 1 + assert_array_almost_equal(labels, [0, 0]) + + +def test_int64_indices_directed(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=True, + connection='strong') + assert n == 2 + assert_array_almost_equal(labels, [1, 0]) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..65f141e5b371367018a6e9985f8325850d8972da --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py @@ -0,0 +1,61 @@ +import numpy as np +from numpy.testing import assert_array_almost_equal +from scipy.sparse import csr_array +from scipy.sparse.csgraph import csgraph_from_dense, csgraph_to_dense + + +def test_csgraph_from_dense(): + np.random.seed(1234) + G = np.random.random((10, 10)) + some_nulls = (G < 0.4) + all_nulls = (G < 0.8) + + for null_value in [0, np.nan, np.inf]: + G[all_nulls] = null_value + with np.errstate(invalid="ignore"): + G_csr = csgraph_from_dense(G, null_value=0) + + G[all_nulls] = 0 + assert_array_almost_equal(G, G_csr.toarray()) + + for null_value in [np.nan, np.inf]: + G[all_nulls] = 0 + G[some_nulls] = null_value + with np.errstate(invalid="ignore"): + G_csr = csgraph_from_dense(G, null_value=0) + + G[all_nulls] = 0 + assert_array_almost_equal(G, G_csr.toarray()) + + +def test_csgraph_to_dense(): + np.random.seed(1234) + G = np.random.random((10, 10)) + nulls = (G < 0.8) + G[nulls] = np.inf + + G_csr = csgraph_from_dense(G) + + for null_value in [0, 10, -np.inf, np.inf]: + G[nulls] = null_value + assert_array_almost_equal(G, csgraph_to_dense(G_csr, null_value)) + + +def test_multiple_edges(): + # create a random square matrix with an even number of elements + np.random.seed(1234) + X = np.random.random((10, 10)) + Xcsr = csr_array(X) + + # now double-up every other column + Xcsr.indices[::2] = Xcsr.indices[1::2] + + # normal sparse toarray() will sum the duplicated edges + Xdense = Xcsr.toarray() + assert_array_almost_equal(Xdense[:, 1::2], + X[:, ::2] + X[:, 1::2]) + + # csgraph_to_dense chooses the minimum of each duplicated edge + Xdense = csgraph_to_dense(Xcsr) + assert_array_almost_equal(Xdense[:, 1::2], + np.minimum(X[:, ::2], X[:, 1::2])) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..c92eb985a1145c4b7c1777f0449bb423402f6d66 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py @@ -0,0 +1,209 @@ +import numpy as np +from numpy.testing import assert_array_equal +import pytest + +from scipy.sparse import csr_array, csc_array, csr_matrix +from scipy.sparse.csgraph import maximum_flow +from scipy.sparse.csgraph._flow import ( + _add_reverse_edges, _make_edge_pointers, _make_tails +) + +methods = ['edmonds_karp', 'dinic'] + +def test_raises_on_dense_input(): + with pytest.raises(TypeError): + graph = np.array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_csc_input(): + with pytest.raises(TypeError): + graph = csc_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_floating_point_input(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1.5], [0, 0]], dtype=np.float64) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_non_square_input(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1, 2], [2, 1, 0]]) + maximum_flow(graph, 0, 1) + + +def test_raises_when_source_is_sink(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 0) + maximum_flow(graph, 0, 0, method='edmonds_karp') + + +@pytest.mark.parametrize('method', methods) +@pytest.mark.parametrize('source', [-1, 2, 3]) +def test_raises_when_source_is_out_of_bounds(source, method): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, source, 1, method=method) + + +@pytest.mark.parametrize('method', methods) +@pytest.mark.parametrize('sink', [-1, 2, 3]) +def test_raises_when_sink_is_out_of_bounds(sink, method): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, sink, method=method) + + +@pytest.mark.parametrize('method', methods) +def test_simple_graph(method): + # This graph looks as follows: + # (0) --5--> (1) + graph = csr_array([[0, 5], [0, 0]]) + res = maximum_flow(graph, 0, 1, method=method) + assert res.flow_value == 5 + expected_flow = np.array([[0, 5], [-5, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_return_type(method): + graph = csr_array([[0, 5], [0, 0]]) + assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_array) + graph = csr_matrix([[0, 5], [0, 0]]) + assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_matrix) + + +@pytest.mark.parametrize('method', methods) +def test_bottle_neck_graph(method): + # This graph cannot use the full capacity between 0 and 1: + # (0) --5--> (1) --3--> (2) + graph = csr_array([[0, 5, 0], [0, 0, 3], [0, 0, 0]]) + res = maximum_flow(graph, 0, 2, method=method) + assert res.flow_value == 3 + expected_flow = np.array([[0, 3, 0], [-3, 0, 3], [0, -3, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_backwards_flow(method): + # This example causes backwards flow between vertices 3 and 4, + # and so this test ensures that we handle that accordingly. See + # https://stackoverflow.com/q/38843963/5085211 + # for more information. + graph = csr_array([[0, 10, 0, 0, 10, 0, 0, 0], + [0, 0, 10, 0, 0, 0, 0, 0], + [0, 0, 0, 10, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 10], + [0, 0, 0, 10, 0, 10, 0, 0], + [0, 0, 0, 0, 0, 0, 10, 0], + [0, 0, 0, 0, 0, 0, 0, 10], + [0, 0, 0, 0, 0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 7, method=method) + assert res.flow_value == 20 + expected_flow = np.array([[0, 10, 0, 0, 10, 0, 0, 0], + [-10, 0, 10, 0, 0, 0, 0, 0], + [0, -10, 0, 10, 0, 0, 0, 0], + [0, 0, -10, 0, 0, 0, 0, 10], + [-10, 0, 0, 0, 0, 10, 0, 0], + [0, 0, 0, 0, -10, 0, 10, 0], + [0, 0, 0, 0, 0, -10, 0, 10], + [0, 0, 0, -10, 0, 0, -10, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_example_from_clrs_chapter_26_1(method): + # See page 659 in CLRS second edition, but note that the maximum flow + # we find is slightly different than the one in CLRS; we push a flow of + # 12 to v_1 instead of v_2. + graph = csr_array([[0, 16, 13, 0, 0, 0], + [0, 0, 10, 12, 0, 0], + [0, 4, 0, 0, 14, 0], + [0, 0, 9, 0, 0, 20], + [0, 0, 0, 7, 0, 4], + [0, 0, 0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 5, method=method) + assert res.flow_value == 23 + expected_flow = np.array([[0, 12, 11, 0, 0, 0], + [-12, 0, 0, 12, 0, 0], + [-11, 0, 0, 0, 11, 0], + [0, -12, 0, 0, -7, 19], + [0, 0, -11, 7, 0, 4], + [0, 0, 0, -19, -4, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_disconnected_graph(method): + # This tests the following disconnected graph: + # (0) --5--> (1) (2) --3--> (3) + graph = csr_array([[0, 5, 0, 0], + [0, 0, 0, 0], + [0, 0, 9, 3], + [0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 3, method=method) + assert res.flow_value == 0 + expected_flow = np.zeros((4, 4), dtype=np.int32) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_add_reverse_edges_large_graph(method): + # Regression test for https://github.com/scipy/scipy/issues/14385 + n = 100_000 + indices = np.arange(1, n) + indptr = np.array(list(range(n)) + [n - 1]) + data = np.ones(n - 1, dtype=np.int32) + graph = csr_array((data, indices, indptr), shape=(n, n)) + res = maximum_flow(graph, 0, n - 1, method=method) + assert res.flow_value == 1 + expected_flow = graph - graph.transpose() + assert_array_equal(res.flow.data, expected_flow.data) + assert_array_equal(res.flow.indices, expected_flow.indices) + assert_array_equal(res.flow.indptr, expected_flow.indptr) + + +@pytest.mark.parametrize("a,b_data_expected", [ + ([[]], []), + ([[0], [0]], []), + ([[1, 0, 2], [0, 0, 0], [0, 3, 0]], [1, 2, 0, 0, 3]), + ([[9, 8, 7], [4, 5, 6], [0, 0, 0]], [9, 8, 7, 4, 5, 6, 0, 0])]) +def test_add_reverse_edges(a, b_data_expected): + """Test that the reversal of the edges of the input graph works + as expected. + """ + a = csr_array(a, dtype=np.int32, shape=(len(a), len(a))) + b = _add_reverse_edges(a) + assert_array_equal(b.data, b_data_expected) + + +@pytest.mark.parametrize("a,expected", [ + ([[]], []), + ([[0]], []), + ([[1]], [0]), + ([[0, 1], [10, 0]], [1, 0]), + ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 3, 4, 1, 2]) +]) +def test_make_edge_pointers(a, expected): + a = csr_array(a, dtype=np.int32) + rev_edge_ptr = _make_edge_pointers(a) + assert_array_equal(rev_edge_ptr, expected) + + +@pytest.mark.parametrize("a,expected", [ + ([[]], []), + ([[0]], []), + ([[1]], [0]), + ([[0, 1], [10, 0]], [0, 1]), + ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 0, 1, 2, 2]) +]) +def test_make_tails(a, expected): + a = csr_array(a, dtype=np.int32) + tails = _make_tails(a) + assert_array_equal(tails, expected) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed5e2edf92ef0cacc819fcbd06bc6d4e195cb44 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py @@ -0,0 +1,368 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose +from pytest import raises as assert_raises +from scipy import sparse + +from scipy.sparse import csgraph +from scipy._lib._util import np_long, np_ulong + + +def check_int_type(mat): + return np.issubdtype(mat.dtype, np.signedinteger) or np.issubdtype( + mat.dtype, np_ulong + ) + + +def test_laplacian_value_error(): + for t in int, float, complex: + for m in ([1, 1], + [[[1]]], + [[1, 2, 3], [4, 5, 6]], + [[1, 2], [3, 4], [5, 5]]): + A = np.array(m, dtype=t) + assert_raises(ValueError, csgraph.laplacian, A) + + +def _explicit_laplacian(x, normed=False): + if sparse.issparse(x): + x = x.toarray() + x = np.asarray(x) + y = -1.0 * x + for j in range(y.shape[0]): + y[j,j] = x[j,j+1:].sum() + x[j,:j].sum() + if normed: + d = np.diag(y).copy() + d[d == 0] = 1.0 + y /= d[:,None]**.5 + y /= d[None,:]**.5 + return y + + +def _check_symmetric_graph_laplacian(mat, normed, copy=True): + if not hasattr(mat, 'shape'): + mat = eval(mat, dict(np=np, sparse=sparse)) + + if sparse.issparse(mat): + sp_mat = mat + mat = sp_mat.toarray() + else: + sp_mat = sparse.csr_array(mat) + + mat_copy = np.copy(mat) + sp_mat_copy = sparse.csr_array(sp_mat, copy=True) + + n_nodes = mat.shape[0] + explicit_laplacian = _explicit_laplacian(mat, normed=normed) + laplacian = csgraph.laplacian(mat, normed=normed, copy=copy) + sp_laplacian = csgraph.laplacian(sp_mat, normed=normed, + copy=copy) + + if copy: + assert_allclose(mat, mat_copy) + _assert_allclose_sparse(sp_mat, sp_mat_copy) + else: + if not (normed and check_int_type(mat)): + assert_allclose(laplacian, mat) + if sp_mat.format == 'coo': + _assert_allclose_sparse(sp_laplacian, sp_mat) + + assert_allclose(laplacian, sp_laplacian.toarray()) + + for tested in [laplacian, sp_laplacian.toarray()]: + if not normed: + assert_allclose(tested.sum(axis=0), np.zeros(n_nodes)) + assert_allclose(tested.T, tested) + assert_allclose(tested, explicit_laplacian) + + +def test_symmetric_graph_laplacian(): + symmetric_mats = ( + 'np.arange(10) * np.arange(10)[:, np.newaxis]', + 'np.ones((7, 7))', + 'np.eye(19)', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4))', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).toarray()', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).todense()', + 'np.vander(np.arange(4)) + np.vander(np.arange(4)).T' + ) + for mat in symmetric_mats: + for normed in True, False: + for copy in True, False: + _check_symmetric_graph_laplacian(mat, normed, copy) + + +def _assert_allclose_sparse(a, b, **kwargs): + # helper function that can deal with sparse matrices + if sparse.issparse(a): + a = a.toarray() + if sparse.issparse(b): + b = b.toarray() + assert_allclose(a, b, **kwargs) + + +def _check_laplacian_dtype_none( + A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type +): + mat = arr_type(A, dtype=dtype) + L, d = csgraph.laplacian( + mat, + normed=normed, + return_diag=True, + use_out_degree=use_out_degree, + copy=copy, + dtype=None, + ) + if normed and check_int_type(mat): + assert L.dtype == np.float64 + assert d.dtype == np.float64 + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + else: + assert L.dtype == dtype + assert d.dtype == dtype + desired_L = np.asarray(desired_L).astype(dtype) + desired_d = np.asarray(desired_d).astype(dtype) + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + + if not copy: + if not (normed and check_int_type(mat)): + if type(mat) is np.ndarray: + assert_allclose(L, mat) + elif mat.format == "coo": + _assert_allclose_sparse(L, mat) + + +def _check_laplacian_dtype( + A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type +): + mat = arr_type(A, dtype=dtype) + L, d = csgraph.laplacian( + mat, + normed=normed, + return_diag=True, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + ) + assert L.dtype == dtype + assert d.dtype == dtype + desired_L = np.asarray(desired_L).astype(dtype) + desired_d = np.asarray(desired_d).astype(dtype) + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + + if not copy: + if not (normed and check_int_type(mat)): + if type(mat) is np.ndarray: + assert_allclose(L, mat) + elif mat.format == 'coo': + _assert_allclose_sparse(L, mat) + + +INT_DTYPES = (np.intc, np_long, np.longlong) +REAL_DTYPES = (np.float32, np.float64, np.longdouble) +COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble) +DTYPES = INT_DTYPES + REAL_DTYPES + COMPLEX_DTYPES + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("arr_type", [np.array, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array]) +@pytest.mark.parametrize("copy", [True, False]) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("use_out_degree", [True, False]) +def test_asymmetric_laplacian(use_out_degree, normed, + copy, dtype, arr_type): + # adjacency matrix + A = [[0, 1, 0], + [4, 2, 0], + [0, 0, 0]] + A = arr_type(np.array(A), dtype=dtype) + A_copy = A.copy() + + if not normed and use_out_degree: + # Laplacian matrix using out-degree + L = [[1, -1, 0], + [-4, 4, 0], + [0, 0, 0]] + d = [1, 4, 0] + + if normed and use_out_degree: + # normalized Laplacian matrix using out-degree + L = [[1, -0.5, 0], + [-2, 1, 0], + [0, 0, 0]] + d = [1, 2, 1] + + if not normed and not use_out_degree: + # Laplacian matrix using in-degree + L = [[4, -1, 0], + [-4, 1, 0], + [0, 0, 0]] + d = [4, 1, 0] + + if normed and not use_out_degree: + # normalized Laplacian matrix using in-degree + L = [[1, -0.5, 0], + [-2, 1, 0], + [0, 0, 0]] + d = [2, 1, 1] + + _check_laplacian_dtype_none( + A, + L, + d, + normed=normed, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + arr_type=arr_type, + ) + + _check_laplacian_dtype( + A_copy, + L, + d, + normed=normed, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + arr_type=arr_type, + ) + + +@pytest.mark.parametrize("fmt", ['csr', 'csc', 'coo', 'lil', + 'dok', 'dia', 'bsr']) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("copy", [True, False]) +def test_sparse_formats(fmt, normed, copy): + mat = sparse.diags_array([1, 1], offsets=[-1, 1], shape=(4, 4), format=fmt) + _check_symmetric_graph_laplacian(mat, normed, copy) + + +@pytest.mark.parametrize( + "arr_type", [np.asarray, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array] +) +@pytest.mark.parametrize("form", ["array", "function", "lo"]) +def test_laplacian_symmetrized(arr_type, form): + # adjacency matrix + n = 3 + mat = arr_type(np.arange(n * n).reshape(n, n)) + L_in, d_in = csgraph.laplacian( + mat, + return_diag=True, + form=form, + ) + L_out, d_out = csgraph.laplacian( + mat, + return_diag=True, + use_out_degree=True, + form=form, + ) + Ls, ds = csgraph.laplacian( + mat, + return_diag=True, + symmetrized=True, + form=form, + ) + Ls_normed, ds_normed = csgraph.laplacian( + mat, + return_diag=True, + symmetrized=True, + normed=True, + form=form, + ) + mat += mat.T + Lss, dss = csgraph.laplacian(mat, return_diag=True, form=form) + Lss_normed, dss_normed = csgraph.laplacian( + mat, + return_diag=True, + normed=True, + form=form, + ) + + assert_allclose(ds, d_in + d_out) + assert_allclose(ds, dss) + assert_allclose(ds_normed, dss_normed) + + d = {} + for L in ["L_in", "L_out", "Ls", "Ls_normed", "Lss", "Lss_normed"]: + if form == "array": + d[L] = eval(L) + else: + d[L] = eval(L)(np.eye(n, dtype=mat.dtype)) + + _assert_allclose_sparse(d["Ls"], d["L_in"] + d["L_out"].T) + _assert_allclose_sparse(d["Ls"], d["Lss"]) + _assert_allclose_sparse(d["Ls_normed"], d["Lss_normed"]) + + +@pytest.mark.parametrize( + "arr_type", [np.asarray, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array] +) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("symmetrized", [True, False]) +@pytest.mark.parametrize("use_out_degree", [True, False]) +@pytest.mark.parametrize("form", ["function", "lo"]) +def test_format(dtype, arr_type, normed, symmetrized, use_out_degree, form): + n = 3 + mat = [[0, 1, 0], [4, 2, 0], [0, 0, 0]] + mat = arr_type(np.array(mat), dtype=dtype) + Lo, do = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + ) + La, da = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + form="array", + ) + assert_allclose(do, da) + _assert_allclose_sparse(Lo, La) + + L, d = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + form=form, + ) + assert_allclose(d, do) + assert d.dtype == dtype + Lm = L(np.eye(n, dtype=mat.dtype)).astype(dtype) + _assert_allclose_sparse(Lm, Lo, rtol=2e-7, atol=2e-7) + x = np.arange(6).reshape(3, 2) + if not (normed and dtype in INT_DTYPES): + assert_allclose(L(x), Lo @ x) + else: + # Normalized Lo is casted to integer, but L() is not + pass + + +def test_format_error_message(): + with pytest.raises(ValueError, match="Invalid form: 'toto'"): + _ = csgraph.laplacian(np.eye(1), form='toto') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..8477861d3e563c43379c615ec0913f47a4349abd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py @@ -0,0 +1,295 @@ +from itertools import product + +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +import pytest + +from scipy.sparse import csr_array, diags_array +from scipy.sparse.csgraph import ( + maximum_bipartite_matching, min_weight_full_bipartite_matching +) + + +def test_maximum_bipartite_matching_raises_on_dense_input(): + with pytest.raises(TypeError): + graph = np.array([[0, 1], [0, 0]]) + maximum_bipartite_matching(graph) + + +def test_maximum_bipartite_matching_empty_graph(): + graph = csr_array((0, 0)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + expected_matching = np.array([]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_empty_left_partition(): + graph = csr_array((2, 0)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([]), x) + assert_array_equal(np.array([-1, -1]), y) + + +def test_maximum_bipartite_matching_empty_right_partition(): + graph = csr_array((0, 3)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([-1, -1, -1]), x) + assert_array_equal(np.array([]), y) + + +def test_maximum_bipartite_matching_graph_with_no_edges(): + graph = csr_array((2, 2)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([-1, -1]), x) + assert_array_equal(np.array([-1, -1]), y) + + +def test_maximum_bipartite_matching_graph_that_causes_augmentation(): + # In this graph, column 1 is initially assigned to row 1, but it should be + # reassigned to make room for row 2. + graph = csr_array([[1, 1], [1, 0]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + expected_matching = np.array([1, 0]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_graph_with_more_rows_than_columns(): + graph = csr_array([[1, 1], [1, 0], [0, 1]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + assert_array_equal(np.array([0, -1, 1]), x) + assert_array_equal(np.array([0, 2]), y) + + +def test_maximum_bipartite_matching_graph_with_more_columns_than_rows(): + graph = csr_array([[1, 1, 0], [0, 0, 1]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + assert_array_equal(np.array([0, 2]), x) + assert_array_equal(np.array([0, -1, 1]), y) + + +def test_maximum_bipartite_matching_explicit_zeros_count_as_edges(): + data = [0, 0] + indices = [1, 0] + indptr = [0, 1, 2] + graph = csr_array((data, indices, indptr), shape=(2, 2)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + expected_matching = np.array([1, 0]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_feasibility_of_result(): + # This is a regression test for GitHub issue #11458 + data = np.ones(50, dtype=int) + indices = [11, 12, 19, 22, 23, 5, 22, 3, 8, 10, 5, 6, 11, 12, 13, 5, 13, + 14, 20, 22, 3, 15, 3, 13, 14, 11, 12, 19, 22, 23, 5, 22, 3, 8, + 10, 5, 6, 11, 12, 13, 5, 13, 14, 20, 22, 3, 15, 3, 13, 14] + indptr = [0, 5, 7, 10, 10, 15, 20, 22, 22, 23, 25, 30, 32, 35, 35, 40, 45, + 47, 47, 48, 50] + graph = csr_array((data, indices, indptr), shape=(20, 25)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert (x != -1).sum() == 13 + assert (y != -1).sum() == 13 + # Ensure that each element of the matching is in fact an edge in the graph. + for u, v in zip(range(graph.shape[0]), y): + if v != -1: + assert graph[u, v] + for u, v in zip(x, range(graph.shape[1])): + if u != -1: + assert graph[u, v] + + +def test_matching_large_random_graph_with_one_edge_incident_to_each_vertex(): + np.random.seed(42) + A = diags_array(np.ones(25), offsets=0, format='csr') + rand_perm = np.random.permutation(25) + rand_perm2 = np.random.permutation(25) + + Rrow = np.arange(25) + Rcol = rand_perm + Rdata = np.ones(25, dtype=int) + Rmat = csr_array((Rdata, (Rrow, Rcol))) + + Crow = rand_perm2 + Ccol = np.arange(25) + Cdata = np.ones(25, dtype=int) + Cmat = csr_array((Cdata, (Crow, Ccol))) + # Randomly permute identity matrix + B = Rmat @ A @ Cmat + + # Row permute + perm = maximum_bipartite_matching(B, perm_type='row') + Rrow = np.arange(25) + Rcol = perm + Rdata = np.ones(25, dtype=int) + Rmat = csr_array((Rdata, (Rrow, Rcol))) + C1 = Rmat @ B + + # Column permute + perm2 = maximum_bipartite_matching(B, perm_type='column') + Crow = perm2 + Ccol = np.arange(25) + Cdata = np.ones(25, dtype=int) + Cmat = csr_array((Cdata, (Crow, Ccol))) + C2 = B @ Cmat + + # Should get identity matrix back + assert_equal(any(C1.diagonal() == 0), False) + assert_equal(any(C2.diagonal() == 0), False) + + +@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)]) +def test_min_weight_full_matching_trivial_graph(num_rows, num_cols): + biadjacency = csr_array((num_cols, num_rows)) + row_ind, col_ind = min_weight_full_bipartite_matching(biadjacency) + assert len(row_ind) == 0 + assert len(col_ind) == 0 + + +@pytest.mark.parametrize('biadjacency', + [ + [[1, 1, 1], [1, 0, 0], [1, 0, 0]], + [[1, 1, 1], [0, 0, 1], [0, 0, 1]], + [[1, 0, 0, 1], [1, 1, 0, 1], [0, 0, 0, 0]], + [[1, 0, 0], [2, 0, 0]], + [[0, 1, 0], [0, 2, 0]], + [[1, 0], [2, 0], [5, 0]] + ]) +def test_min_weight_full_matching_infeasible_problems(biadjacency): + with pytest.raises(ValueError): + min_weight_full_bipartite_matching(csr_array(biadjacency)) + + +def test_min_weight_full_matching_large_infeasible(): + # Regression test for GitHub issue #17269 + a = np.asarray([ + [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.001, 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, 0.0, 0.0, 0.001, 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, 0.0, 0.0, 0.001, 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, 0.0, 0.0, 0.001, 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, 0.0, 0.0, 0.001, 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, 0.0, 0.0, 0.001, 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, 0.0, 0.0, 0.001, 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, 0.0, 0.0, 0.001, 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, 0.0, 0.0, 0.001], + [0.0, 0.11687445, 0.0, 0.0, 0.01319788, 0.07509257, 0.0, + 0.0, 0.0, 0.74228317, 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.81087935, 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, 0.0, 0.0, 0.8408466, 0.0, 0.0, 0.0, 0.0, 0.01194389, + 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.82994211, 0.0, 0.0, 0.0, 0.11468516, 0.0, 0.0, 0.0, + 0.11173505, 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.18796507, 0.0, 0.04002318, 0.0, 0.0, 0.0, 0.0, 0.0, 0.75883335, + 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.71545464, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02748488, + 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.78470564, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.14829198, + 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.10870609, 0.0, 0.0, 0.0, 0.8918677, 0.0, 0.0, 0.0, 0.06306644, + 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, 0.0, 0.0, 0.0, 0.0, + 0.63844085, 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.7442354, 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, 0.0, 0.0, 0.09850549, 0.0, 0.0, 0.18638258, + 0.2769244, 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.73182464, 0.0, 0.0, 0.46443561, + 0.38589284, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.29510278, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09666032, 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] + ]) + with pytest.raises(ValueError, match='no full matching exists'): + min_weight_full_bipartite_matching(csr_array(a)) + + +@pytest.mark.thread_unsafe +def test_explicit_zero_causes_warning(): + with pytest.warns(UserWarning): + biadjacency = csr_array(((2, 0, 3), (0, 1, 1), (0, 2, 3))) + min_weight_full_bipartite_matching(biadjacency) + + +# General test for linear sum assignment solvers to make it possible to rely +# on the same tests for scipy.optimize.linear_sum_assignment. +def linear_sum_assignment_assertions( + solver, array_type, sign, test_case +): + cost_matrix, expected_cost = test_case + maximize = sign == -1 + cost_matrix = sign * array_type(cost_matrix) + expected_cost = sign * np.array(expected_cost) + + row_ind, col_ind = solver(cost_matrix, maximize=maximize) + assert_array_equal(row_ind, np.sort(row_ind)) + assert_array_equal(expected_cost, + np.array(cost_matrix[row_ind, col_ind]).flatten()) + + cost_matrix = cost_matrix.T + row_ind, col_ind = solver(cost_matrix, maximize=maximize) + assert_array_equal(row_ind, np.sort(row_ind)) + assert_array_equal(np.sort(expected_cost), + np.sort(np.array( + cost_matrix[row_ind, col_ind])).flatten()) + + +linear_sum_assignment_test_cases = product( + [-1, 1], + [ + # Square + ([[400, 150, 400], + [400, 450, 600], + [300, 225, 300]], + [150, 400, 300]), + + # Rectangular variant + ([[400, 150, 400, 1], + [400, 450, 600, 2], + [300, 225, 300, 3]], + [150, 2, 300]), + + ([[10, 10, 8], + [9, 8, 1], + [9, 7, 4]], + [10, 1, 7]), + + # Square + ([[10, 10, 8, 11], + [9, 8, 1, 1], + [9, 7, 4, 10]], + [10, 1, 4]), + + # Rectangular variant + ([[10, float("inf"), float("inf")], + [float("inf"), float("inf"), 1], + [float("inf"), 7, float("inf")]], + [10, 1, 7]) + ]) + + +@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases) +def test_min_weight_full_matching_small_inputs(sign, test_case): + linear_sum_assignment_assertions( + min_weight_full_bipartite_matching, csr_array, sign, test_case) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..1476c29a3ba97869c6c38be4d717641a494c1183 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py @@ -0,0 +1,194 @@ +import pytest + +import numpy as np +import scipy.sparse as sp +import scipy.sparse.csgraph as spgraph +from scipy._lib import _pep440 + +from numpy.testing import assert_equal + +try: + import sparse +except Exception: + sparse = None + +pytestmark = pytest.mark.skipif(sparse is None, + reason="pydata/sparse not installed") + + +msg = "pydata/sparse (0.15.1) does not implement necessary operations" + + +sparse_params = (pytest.param("COO"), + pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)])) + + +def check_sparse_version(min_ver): + if sparse is None: + return pytest.mark.skip(reason="sparse is not installed") + return pytest.mark.skipif( + _pep440.parse(sparse.__version__) < _pep440.Version(min_ver), + reason=f"sparse version >= {min_ver} required" + ) + + +@pytest.fixture(params=sparse_params) +def sparse_cls(request): + return getattr(sparse, request.param) + + +@pytest.fixture +def graphs(sparse_cls): + graph = [ + [0, 1, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 0, 0, 0, 0], + ] + A_dense = np.array(graph) + A_sparse = sparse_cls(A_dense) + return A_dense, A_sparse + + +@pytest.mark.parametrize( + "func", + [ + spgraph.shortest_path, + spgraph.dijkstra, + spgraph.floyd_warshall, + spgraph.bellman_ford, + spgraph.johnson, + spgraph.reverse_cuthill_mckee, + spgraph.maximum_bipartite_matching, + spgraph.structural_rank, + ] +) +def test_csgraph_equiv(func, graphs): + A_dense, A_sparse = graphs + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + assert_equal(actual, desired) + + +def test_connected_components(graphs): + A_dense, A_sparse = graphs + func = spgraph.connected_components + + actual_comp, actual_labels = func(A_sparse) + desired_comp, desired_labels, = func(sp.csc_array(A_dense)) + + assert actual_comp == desired_comp + assert_equal(actual_labels, desired_labels) + + +def test_laplacian(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.laplacian + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +@pytest.mark.parametrize( + "func", [spgraph.breadth_first_order, spgraph.depth_first_order] +) +def test_order_search(graphs, func): + A_dense, A_sparse = graphs + + actual = func(A_sparse, 0) + desired = func(sp.csc_array(A_dense), 0) + + assert_equal(actual, desired) + + +@pytest.mark.parametrize( + "func", [spgraph.breadth_first_tree, spgraph.depth_first_tree] +) +def test_tree_search(graphs, func): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + + actual = func(A_sparse, 0) + desired = func(sp.csc_array(A_dense), 0) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +def test_minimum_spanning_tree(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.minimum_spanning_tree + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +def test_maximum_flow(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.maximum_flow + + actual = func(A_sparse, 0, 2) + desired = func(sp.csr_array(A_dense), 0, 2) + + assert actual.flow_value == desired.flow_value + assert isinstance(actual.flow, sparse_cls) + + assert_equal(actual.flow.todense(), desired.flow.todense()) + + +def test_min_weight_full_bipartite_matching(graphs): + A_dense, A_sparse = graphs + func = spgraph.min_weight_full_bipartite_matching + + actual = func(A_sparse[0:2, 1:3]) + desired = func(sp.csc_array(A_dense)[0:2, 1:3]) + + assert_equal(actual, desired) + + +@check_sparse_version("0.15.4") +@pytest.mark.parametrize( + "func", + [ + spgraph.shortest_path, + spgraph.dijkstra, + spgraph.floyd_warshall, + spgraph.bellman_ford, + spgraph.johnson, + spgraph.minimum_spanning_tree, + ] +) +@pytest.mark.parametrize( + "fill_value, comp_func", + [(np.inf, np.isposinf), (np.nan, np.isnan)], +) +def test_nonzero_fill_value(graphs, func, fill_value, comp_func): + A_dense, A_sparse = graphs + A_sparse = A_sparse.astype(float) + A_sparse.fill_value = fill_value + sparse_cls = type(A_sparse) + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + if func == spgraph.minimum_spanning_tree: + assert isinstance(actual, sparse_cls) + assert comp_func(actual.fill_value) + actual = actual.todense() + actual[comp_func(actual)] = 0.0 + assert_equal(actual, desired.todense()) + else: + assert_equal(actual, desired) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py new file mode 100644 index 0000000000000000000000000000000000000000..add76cdc29c39c079f386a6ca73075bb90b0a6e8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py @@ -0,0 +1,70 @@ +import numpy as np +from numpy.testing import assert_equal +from scipy.sparse.csgraph import reverse_cuthill_mckee, structural_rank +from scipy.sparse import csc_array, csr_array, coo_array + + +def test_graph_reverse_cuthill_mckee(): + A = np.array([[1, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 0, 0, 1, 0, 1], + [0, 1, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 1, 0], + [1, 0, 1, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 1], + [0, 0, 0, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0, 1]], dtype=int) + + graph = csr_array(A) + perm = reverse_cuthill_mckee(graph) + correct_perm = np.array([6, 3, 7, 5, 1, 2, 4, 0]) + assert_equal(perm, correct_perm) + + # Test int64 indices input + graph.indices = graph.indices.astype('int64') + graph.indptr = graph.indptr.astype('int64') + perm = reverse_cuthill_mckee(graph, True) + assert_equal(perm, correct_perm) + + +def test_graph_reverse_cuthill_mckee_ordering(): + data = np.ones(63,dtype=int) + rows = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, + 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, + 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, + 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, + 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, + 14, 15, 15, 15, 15, 15]) + cols = np.array([0, 2, 5, 8, 10, 1, 3, 9, 11, 0, 2, + 7, 10, 1, 3, 11, 4, 6, 12, 14, 0, 7, 13, + 15, 4, 6, 14, 2, 5, 7, 15, 0, 8, 10, 13, + 1, 9, 11, 0, 2, 8, 10, 15, 1, 3, 9, 11, + 4, 12, 14, 5, 8, 13, 15, 4, 6, 12, 14, + 5, 7, 10, 13, 15]) + graph = csr_array((data, (rows,cols))) + perm = reverse_cuthill_mckee(graph) + correct_perm = np.array([12, 14, 4, 6, 10, 8, 2, 15, + 0, 13, 7, 5, 9, 11, 1, 3]) + assert_equal(perm, correct_perm) + + +def test_graph_structural_rank(): + # Test square matrix #1 + A = csc_array([[1, 1, 0], + [1, 0, 1], + [0, 1, 0]]) + assert_equal(structural_rank(A), 3) + + # Test square matrix #2 + rows = np.array([0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,4,4,5,5,6,6,7,7]) + cols = np.array([0,1,2,3,4,2,5,2,6,0,1,3,5,6,7,4,5,5,6,2,6,2,4]) + data = np.ones_like(rows) + B = coo_array((data,(rows,cols)), shape=(8,8)) + assert_equal(structural_rank(B), 6) + + #Test non-square matrix + C = csc_array([[1, 0, 2, 0], + [2, 0, 4, 0]]) + assert_equal(structural_rank(C), 2) + + #Test tall matrix + assert_equal(structural_rank(C.T), 2) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py new file mode 100644 index 0000000000000000000000000000000000000000..ba50f760e750ce1dbdec3624c2ab985fca1af7d1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py @@ -0,0 +1,484 @@ +from io import StringIO +import warnings +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_allclose +from pytest import raises as assert_raises +from scipy.sparse.csgraph import (shortest_path, dijkstra, johnson, + bellman_ford, construct_dist_matrix, yen, + NegativeCycleError) +import scipy.sparse +from scipy.io import mmread +import pytest + +directed_G = np.array([[0, 3, 3, 0, 0], + [0, 0, 0, 2, 4], + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 0], + [2, 0, 0, 2, 0]], dtype=float) + +undirected_G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + +unweighted_G = (directed_G > 0).astype(float) + +directed_SP = [[0, 3, 3, 5, 7], + [3, 0, 6, 2, 4], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 4, 4, 0, 8], + [2, 5, 5, 2, 0]] + +directed_2SP_0_to_3 = [[-9999, 0, -9999, 1, -9999], + [-9999, 0, -9999, 4, 1]] + +directed_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 1, 2, 3, 1], + ([0, 1, 2, 3, 4], [1, 2, 0, 4, 3]), + ), + shape=(5, 5), +) + +directed_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [3, 0, 1, np.inf, np.inf], + [2, 2, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 3], + [np.inf, np.inf, np.inf, 1, 0]] + +undirected_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 0, 1, 1, 2, 2, 1, 1], + ([0, 1, 1, 2, 2, 0, 3, 4], [1, 0, 2, 1, 0, 2, 4, 3]) + ), + shape=(5, 5), +) + +undirected_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [0, 0, 1, np.inf, np.inf], + [1, 1, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 1], + [np.inf, np.inf, np.inf, 1, 0]] + +directed_pred = np.array([[-9999, 0, 0, 1, 1], + [3, -9999, 0, 1, 1], + [-9999, -9999, -9999, -9999, -9999], + [3, 0, 0, -9999, 1], + [4, 0, 0, 4, -9999]], dtype=float) + +undirected_SP = np.array([[0, 3, 3, 1, 2], + [3, 0, 6, 2, 4], + [3, 6, 0, 4, 5], + [1, 2, 4, 0, 2], + [2, 4, 5, 2, 0]], dtype=float) + +undirected_SP_limit_2 = np.array([[0, np.inf, np.inf, 1, 2], + [np.inf, 0, np.inf, 2, np.inf], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 2, np.inf, 0, 2], + [2, np.inf, np.inf, 2, 0]], dtype=float) + +undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5) +undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf + +undirected_pred = np.array([[-9999, 0, 0, 0, 0], + [1, -9999, 0, 1, 1], + [2, 0, -9999, 0, 0], + [3, 3, 0, -9999, 3], + [4, 4, 0, 4, -9999]], dtype=float) + +directed_negative_weighted_G = np.array([[0, 0, 0], + [-1, 0, 0], + [0, -1, 0]], dtype=float) + +directed_negative_weighted_SP = np.array([[0, np.inf, np.inf], + [-1, 0, np.inf], + [-2, -1, 0]], dtype=float) + +methods = ['auto', 'FW', 'D', 'BF', 'J'] + + +def test_dijkstra_limit(): + limits = [0, 2, np.inf] + results = [undirected_SP_limit_0, + undirected_SP_limit_2, + undirected_SP] + + def check(limit, result): + SP = dijkstra(undirected_G, directed=False, limit=limit) + assert_array_almost_equal(SP, result) + + for limit, result in zip(limits, results): + check(limit, result) + + +def test_directed(): + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_undirected(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_SP) + else: + SP2 = shortest_path(undirected_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +def test_directed_sparse_zero(): + # test directed sparse graph with zero-weight edge and two connected components + def check(method): + SP = shortest_path(directed_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_sparse_zero_SP) + + for method in methods: + check(method) + + +def test_undirected_sparse_zero(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_sparse_zero_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_sparse_zero_SP) + else: + SP2 = shortest_path(undirected_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_sparse_zero_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +@pytest.mark.parametrize('directed, SP_ans', + ((True, directed_SP), + (False, undirected_SP))) +@pytest.mark.parametrize('indices', ([0, 2, 4], [0, 4], [3, 4], [0, 0])) +def test_dijkstra_indices_min_only(directed, SP_ans, indices): + SP_ans = np.array(SP_ans) + indices = np.array(indices, dtype=np.int64) + min_ind_ans = indices[np.argmin(SP_ans[indices, :], axis=0)] + min_d_ans = np.zeros(SP_ans.shape[0], SP_ans.dtype) + for k in range(SP_ans.shape[0]): + min_d_ans[k] = SP_ans[min_ind_ans[k], k] + min_ind_ans[np.isinf(min_d_ans)] = -9999 + + SP, pred, sources = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=True) + assert_array_almost_equal(SP, min_d_ans) + assert_array_equal(min_ind_ans, sources) + SP = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=False) + assert_array_almost_equal(SP, min_d_ans) + + +@pytest.mark.parametrize('n', (10, 100, 1000)) +def test_dijkstra_min_only_random(n): + rng = np.random.default_rng(7345782358920239234) + data = scipy.sparse.random_array((n, n), density=0.5, format='lil', + rng=rng, dtype=np.float64) + data.setdiag(np.zeros(n, dtype=np.bool_)) + # choose some random vertices + v = np.arange(n) + rng.shuffle(v) + indices = v[:int(n*.1)] + ds, pred, sources = dijkstra(data, + directed=True, + indices=indices, + min_only=True, + return_predecessors=True) + for k in range(n): + p = pred[k] + s = sources[k] + while p != -9999: + assert sources[p] == s + p = pred[p] + + +def test_dijkstra_random(): + # reproduces the hang observed in gh-17782 + n = 10 + indices = [0, 4, 4, 5, 7, 9, 0, 6, 2, 3, 7, 9, 1, 2, 9, 2, 5, 6] + indptr = [0, 0, 2, 5, 6, 7, 8, 12, 15, 18, 18] + data = [0.33629, 0.40458, 0.47493, 0.42757, 0.11497, 0.91653, 0.69084, + 0.64979, 0.62555, 0.743, 0.01724, 0.99945, 0.31095, 0.15557, + 0.02439, 0.65814, 0.23478, 0.24072] + graph = scipy.sparse.csr_array((data, indices, indptr), shape=(n, n)) + dijkstra(graph, directed=True, return_predecessors=True) + + +def test_gh_17782_segfault(): + text = """%%MatrixMarket matrix coordinate real general + 84 84 22 + 2 1 4.699999809265137e+00 + 6 14 1.199999973177910e-01 + 9 6 1.199999973177910e-01 + 10 16 2.012000083923340e+01 + 11 10 1.422000026702881e+01 + 12 1 9.645999908447266e+01 + 13 18 2.012000083923340e+01 + 14 13 4.679999828338623e+00 + 15 11 1.199999973177910e-01 + 16 12 1.199999973177910e-01 + 18 15 1.199999973177910e-01 + 32 2 2.299999952316284e+00 + 33 20 6.000000000000000e+00 + 33 32 5.000000000000000e+00 + 36 9 3.720000028610229e+00 + 36 37 3.720000028610229e+00 + 36 38 3.720000028610229e+00 + 37 44 8.159999847412109e+00 + 38 32 7.903999328613281e+01 + 43 20 2.400000000000000e+01 + 43 33 4.000000000000000e+00 + 44 43 6.028000259399414e+01 + """ + data = mmread(StringIO(text), spmatrix=False) + dijkstra(data, directed=True, return_predecessors=True) + + +def test_shortest_path_indices(): + indices = np.arange(4) + + def check(func, indshape): + outshape = indshape + (5,) + SP = func(directed_G, directed=False, + indices=indices.reshape(indshape)) + assert_array_almost_equal(SP, undirected_SP[indices].reshape(outshape)) + + for indshape in [(4,), (4, 1), (2, 2)]: + for func in (dijkstra, bellman_ford, johnson, shortest_path): + check(func, indshape) + + assert_raises(ValueError, shortest_path, directed_G, method='FW', + indices=indices) + + +def test_predecessors(): + SP_res = {True: directed_SP, + False: undirected_SP} + pred_res = {True: directed_pred, + False: undirected_pred} + + def check(method, directed): + SP, pred = shortest_path(directed_G, method, directed=directed, + overwrite=False, + return_predecessors=True) + assert_array_almost_equal(SP, SP_res[directed]) + assert_array_almost_equal(pred, pred_res[directed]) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_construct_shortest_path(): + def check(method, directed): + SP1, pred = shortest_path(directed_G, + directed=directed, + overwrite=False, + return_predecessors=True) + SP2 = construct_dist_matrix(directed_G, pred, directed=directed) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_unweighted_path(): + def check(method, directed): + SP1 = shortest_path(directed_G, + directed=directed, + overwrite=False, + unweighted=True) + SP2 = shortest_path(unweighted_G, + directed=directed, + overwrite=False, + unweighted=False) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_negative_cycles(): + # create a small graph with a negative cycle + graph = np.ones([5, 5]) + graph.flat[::6] = 0 + graph[1, 2] = -2 + + def check(method, directed): + assert_raises(NegativeCycleError, shortest_path, graph, method, + directed) + + for directed in (True, False): + for method in ['FW', 'J', 'BF']: + check(method, directed) + + assert_raises(NegativeCycleError, yen, graph, 0, 1, 1, + directed=directed) + + +@pytest.mark.parametrize("method", ['FW', 'J', 'BF']) +def test_negative_weights(method): + SP = shortest_path(directed_negative_weighted_G, method, directed=True) + assert_allclose(SP, directed_negative_weighted_SP, atol=1e-10) + + +def test_masked_input(): + np.ma.masked_equal(directed_G, 0) + + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_overwrite(): + G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + foo = G.copy() + shortest_path(foo, overwrite=False) + assert_array_equal(foo, G) + + +@pytest.mark.parametrize('method', methods) +def test_buffer(method): + # Smoke test that sparse matrices with read-only buffers (e.g., those from + # joblib workers) do not cause:: + # + # ValueError: buffer source array is read-only + # + G = scipy.sparse.csr_array([[1.]]) + G.data.flags['WRITEABLE'] = False + shortest_path(G, method=method) + + +def test_NaN_warnings(): + with warnings.catch_warnings(record=True) as record: + shortest_path(np.array([[0, 1], [np.nan, 0]])) + for r in record: + assert r.category is not RuntimeWarning + + +def test_sparse_matrices(): + # Test that using lil,csr and csc sparse matrix do not cause error + G_dense = np.array([[0, 3, 0, 0, 0], + [0, 0, -1, 0, 0], + [0, 0, 0, 2, 0], + [0, 0, 0, 0, 4], + [0, 0, 0, 0, 0]], dtype=float) + SP = shortest_path(G_dense) + G_csr = scipy.sparse.csr_array(G_dense) + G_csc = scipy.sparse.csc_array(G_dense) + G_lil = scipy.sparse.lil_array(G_dense) + assert_array_almost_equal(SP, shortest_path(G_csr)) + assert_array_almost_equal(SP, shortest_path(G_csc)) + assert_array_almost_equal(SP, shortest_path(G_lil)) + + +def test_yen_directed(): + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=2, + return_predecessors=True + ) + assert_allclose(distances, [5., 9.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + + +def test_yen_undirected(): + distances = yen( + undirected_G, + source=0, + sink=3, + K=4, + ) + assert_allclose(distances, [1., 4., 5., 8.]) + +def test_yen_unweighted(): + # Ask for more paths than there are, verify only the available paths are returned + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=4, + unweighted=True, + return_predecessors=True, + ) + assert_allclose(distances, [2., 3.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + +def test_yen_no_paths(): + distances = yen( + directed_G, + source=2, + sink=3, + K=1, + ) + assert distances.size == 0 + +def test_yen_negative_weights(): + distances = yen( + directed_negative_weighted_G, + source=2, + sink=0, + K=1, + ) + assert_allclose(distances, [-2.]) + + +@pytest.mark.parametrize("min_only", (True, False)) +@pytest.mark.parametrize("directed", (True, False)) +@pytest.mark.parametrize("return_predecessors", (True, False)) +@pytest.mark.parametrize("index_dtype", (np.int32, np.int64)) +@pytest.mark.parametrize("indices", (None, [1])) +def test_20904(min_only, directed, return_predecessors, index_dtype, indices): + """Test two failures from gh-20904: int32 and indices-as-None.""" + adj_mat = scipy.sparse.eye_array(4, format="csr") + adj_mat = scipy.sparse.csr_array( + ( + adj_mat.data, + adj_mat.indices.astype(index_dtype), + adj_mat.indptr.astype(index_dtype), + ), + ) + dijkstra( + adj_mat, + directed, + indices=indices, + min_only=min_only, + return_predecessors=return_predecessors, + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..3237a14584d42022184a54f174b809a2b06d16ed --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py @@ -0,0 +1,66 @@ +"""Test the minimum spanning tree function""" +import numpy as np +from numpy.testing import assert_ +import numpy.testing as npt +from scipy.sparse import csr_array +from scipy.sparse.csgraph import minimum_spanning_tree + + +def test_minimum_spanning_tree(): + + # Create a graph with two connected components. + graph = [[0,1,0,0,0], + [1,0,0,0,0], + [0,0,0,8,5], + [0,0,8,0,1], + [0,0,5,1,0]] + graph = np.asarray(graph) + + # Create the expected spanning tree. + expected = [[0,1,0,0,0], + [0,0,0,0,0], + [0,0,0,0,5], + [0,0,0,0,1], + [0,0,0,0,0]] + expected = np.asarray(expected) + + # Ensure minimum spanning tree code gives this expected output. + csgraph = csr_array(graph) + mintree = minimum_spanning_tree(csgraph) + mintree_array = mintree.toarray() + npt.assert_array_equal(mintree_array, expected, + 'Incorrect spanning tree found.') + + # Ensure that the original graph was not modified. + npt.assert_array_equal(csgraph.toarray(), graph, + 'Original graph was modified.') + + # Now let the algorithm modify the csgraph in place. + mintree = minimum_spanning_tree(csgraph, overwrite=True) + npt.assert_array_equal(mintree.toarray(), expected, + 'Graph was not properly modified to contain MST.') + + np.random.seed(1234) + for N in (5, 10, 15, 20): + + # Create a random graph. + graph = 3 + np.random.random((N, N)) + csgraph = csr_array(graph) + + # The spanning tree has at most N - 1 edges. + mintree = minimum_spanning_tree(csgraph) + assert_(mintree.nnz < N) + + # Set the sub diagonal to 1 to create a known spanning tree. + idx = np.arange(N-1) + graph[idx,idx+1] = 1 + csgraph = csr_array(graph) + mintree = minimum_spanning_tree(csgraph) + + # We expect to see this pattern in the spanning tree and otherwise + # have this zero. + expected = np.zeros((N, N)) + expected[idx, idx+1] = 1 + + npt.assert_array_equal(mintree.toarray(), expected, + 'Incorrect spanning tree found.') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py new file mode 100644 index 0000000000000000000000000000000000000000..aef6def21b61ff6b8d8bfb990a3a69136349d7c5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py @@ -0,0 +1,148 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal +from scipy.sparse import csr_array, csr_matrix, coo_array, coo_matrix +from scipy.sparse.csgraph import (breadth_first_tree, depth_first_tree, + csgraph_to_dense, csgraph_from_dense, csgraph_masked_from_dense) + + +def test_graph_breadth_first(): + csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + bfirst = np.array([[0, 1, 2, 0, 0], + [0, 0, 0, 0, 3], + [0, 0, 0, 7, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]) + + for directed in [True, False]: + bfirst_test = breadth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(bfirst_test), + bfirst) + + +def test_graph_depth_first(): + csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + dfirst = np.array([[0, 1, 0, 0, 0], + [0, 0, 0, 0, 3], + [0, 0, 0, 0, 0], + [0, 0, 7, 0, 0], + [0, 0, 0, 1, 0]]) + + for directed in [True, False]: + dfirst_test = depth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(dfirst_test), dfirst) + + +def test_return_type(): + from .._laplacian import laplacian + from .._min_spanning_tree import minimum_spanning_tree + + np_csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csr_array(np_csgraph) + assert isinstance(laplacian(csgraph), coo_array) + assert isinstance(minimum_spanning_tree(csgraph), csr_array) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array) + + csgraph = csgraph_from_dense(np_csgraph, null_value=0) + assert isinstance(csgraph, csr_array) + assert isinstance(laplacian(csgraph), coo_array) + assert isinstance(minimum_spanning_tree(csgraph), csr_array) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array) + + csgraph = csgraph_masked_from_dense(np_csgraph, null_value=0) + assert isinstance(csgraph, np.ma.MaskedArray) + assert csgraph._baseclass is np.ndarray + # laplacian doesnt work with masked arrays so not here + assert isinstance(minimum_spanning_tree(csgraph), csr_array) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array) + + # start of testing with matrix/spmatrix types + with np.testing.suppress_warnings() as sup: + sup.filter(DeprecationWarning, "the matrix subclass.*") + sup.filter(PendingDeprecationWarning, "the matrix subclass.*") + + nm_csgraph = np.matrix([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + + csgraph = csr_matrix(nm_csgraph) + assert isinstance(laplacian(csgraph), coo_matrix) + assert isinstance(minimum_spanning_tree(csgraph), csr_matrix) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix) + + csgraph = csgraph_from_dense(nm_csgraph, null_value=0) + assert isinstance(csgraph, csr_matrix) + assert isinstance(laplacian(csgraph), coo_matrix) + assert isinstance(minimum_spanning_tree(csgraph), csr_matrix) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix) + + mm_csgraph = csgraph_masked_from_dense(nm_csgraph, null_value=0) + assert isinstance(mm_csgraph, np.ma.MaskedArray) + # laplacian doesnt work with masked arrays so not here + assert isinstance(minimum_spanning_tree(csgraph), csr_matrix) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix) + # end of testing with matrix/spmatrix types + + +def test_graph_breadth_first_trivial_graph(): + csgraph = np.array([[0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + bfirst = np.array([[0]]) + + for directed in [True, False]: + bfirst_test = breadth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(bfirst_test), bfirst) + + +def test_graph_depth_first_trivial_graph(): + csgraph = np.array([[0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + bfirst = np.array([[0]]) + + for directed in [True, False]: + bfirst_test = depth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(bfirst_test), + bfirst) + + +@pytest.mark.parametrize('directed', [True, False]) +@pytest.mark.parametrize('tree_func', [breadth_first_tree, depth_first_tree]) +def test_int64_indices(tree_func, directed): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + tree = tree_func(g, 0, directed=directed) + assert_array_almost_equal(csgraph_to_dense(tree), [[0, 1], [0, 0]]) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py new file mode 100644 index 0000000000000000000000000000000000000000..6523f0b344e86bdcb1e520a61cbaed0a28e77e70 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python +"""Tests for the linalg._isolve.gcrotmk module +""" + +import threading +from numpy.testing import (assert_, assert_allclose, assert_equal, + suppress_warnings) + +import numpy as np +from numpy import zeros, array, allclose +from scipy.linalg import norm +from scipy.sparse import csr_array, eye_array, random_array + +from scipy.sparse.linalg._interface import LinearOperator +from scipy.sparse.linalg import splu +from scipy.sparse.linalg._isolve import gcrotmk, gmres + + +Am = csr_array(array([[-2,1,0,0,0,9], + [1,-2,1,0,5,0], + [0,1,-2,1,0,0], + [0,0,1,-2,1,0], + [0,3,0,1,-2,1], + [1,0,0,0,1,-2]])) +b = array([1,2,3,4,5,6]) +count = threading.local() # [0] +niter = threading.local() # [0] + + +def matvec(v): + if not hasattr(count, 'c'): + count.c = [0] + count.c[0] += 1 + return Am@v + + +def cb(v): + if not hasattr(niter, 'n'): + niter.n = [0] + niter.n[0] += 1 + + +A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype) + + +def do_solve(**kw): + if not hasattr(niter, 'n'): + niter.n = [0] + + if not hasattr(count, 'c'): + count.c = [0] + + count.c[0] = 0 + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x0, flag = gcrotmk(A, b, x0=zeros(A.shape[0]), rtol=1e-14, **kw) + count_0 = count.c[0] + assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b)) + return x0, count_0 + + +class TestGCROTMK: + def test_preconditioner(self): + # Check that preconditioning works + pc = splu(Am.tocsc()) + M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype) + + x0, count_0 = do_solve() + niter.n[0] = 0 + x1, count_1 = do_solve(M=M, callback=cb) + + assert_equal(count_1, 3) + assert count_1 < count_0/2 + assert allclose(x1, x0, rtol=1e-14) + assert niter.n[0] < 3 + + def test_arnoldi(self): + rng = np.random.default_rng(1) + + A = eye_array(2000) + random_array((2000, 2000), density=5e-4, rng=rng) + b = rng.random(2000) + + # The inner arnoldi should be equivalent to gmres + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x0, flag0 = gcrotmk(A, b, x0=zeros(A.shape[0]), m=10, k=0, maxiter=1) + x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=10, maxiter=1) + + assert_equal(flag0, 1) + assert_equal(flag1, 1) + assert np.linalg.norm(A.dot(x0) - b) > 1e-4 + + assert_allclose(x0, x1) + + def test_cornercase(self): + np.random.seed(1234) + + # Rounding error may prevent convergence with tol=0 --- ensure + # that the return values in this case are correct, and no + # exceptions are raised + + for n in [3, 5, 10, 100]: + A = 2*eye_array(n) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + b = np.ones(n) + x, info = gcrotmk(A, b, maxiter=10) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + x, info = gcrotmk(A, b, rtol=0, maxiter=10) + if info == 0: + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + b = np.random.rand(n) + x, info = gcrotmk(A, b, maxiter=10) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + x, info = gcrotmk(A, b, rtol=0, maxiter=10) + if info == 0: + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + def test_nans(self): + A = eye_array(3, format='lil') + A[1,1] = np.nan + b = np.ones(3) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x, info = gcrotmk(A, b, rtol=0, maxiter=10) + assert_equal(info, 1) + + def test_truncate(self): + np.random.seed(1234) + A = np.random.rand(30, 30) + np.eye(30) + b = np.random.rand(30) + + for truncate in ['oldest', 'smallest']: + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x, info = gcrotmk(A, b, m=10, k=10, truncate=truncate, + rtol=1e-4, maxiter=200) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-3) + + def test_CU(self): + for discard_C in (True, False): + # Check that C,U behave as expected + CU = [] + x0, count_0 = do_solve(CU=CU, discard_C=discard_C) + assert_(len(CU) > 0) + assert_(len(CU) <= 6) + + if discard_C: + for c, u in CU: + assert_(c is None) + + # should converge immediately + x1, count_1 = do_solve(CU=CU, discard_C=discard_C) + if discard_C: + assert_equal(count_1, 2 + len(CU)) + else: + assert_equal(count_1, 3) + assert_(count_1 <= count_0/2) + assert_allclose(x1, x0, atol=1e-14) + + def test_denormals(self): + # Check that no warnings are emitted if the matrix contains + # numbers for which 1/x has no float representation, and that + # the solver behaves properly. + A = np.array([[1, 2], [3, 4]], dtype=float) + A *= 100 * np.nextafter(0, 1) + + b = np.array([1, 1]) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + xp, info = gcrotmk(A, b) + + if info == 0: + assert_allclose(A.dot(xp), b) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py new file mode 100644 index 0000000000000000000000000000000000000000..7daff5fc854a0a53fea80f7e5d7fde8736ceb2e7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py @@ -0,0 +1,809 @@ +""" Test functions for the sparse.linalg._isolve module +""" + +import itertools +import platform +import pytest + +import numpy as np +from numpy.testing import assert_array_equal, assert_allclose +from numpy import zeros, arange, array, ones, eye, iscomplexobj +from numpy.linalg import norm + +from scipy.sparse import dia_array, csr_array, kronsum + +from scipy.sparse.linalg import LinearOperator, aslinearoperator +from scipy.sparse.linalg._isolve import (bicg, bicgstab, cg, cgs, + gcrotmk, gmres, lgmres, + minres, qmr, tfqmr) + +# TODO check that method preserve shape and type +# TODO test both preconditioner methods + + +# list of all solvers under test +_SOLVERS = [bicg, bicgstab, cg, cgs, gcrotmk, gmres, lgmres, + minres, qmr, tfqmr] + +CB_TYPE_FILTER = ".*called without specifying `callback_type`.*" + + +# create parametrized fixture for easy reuse in tests +@pytest.fixture(params=_SOLVERS, scope="session") +def solver(request): + """ + Fixture for all solvers in scipy.sparse.linalg._isolve + """ + return request.param + + +class Case: + def __init__(self, name, A, b=None, skip=None, nonconvergence=None): + self.name = name + self.A = A + if b is None: + self.b = arange(A.shape[0], dtype=float) + else: + self.b = b + if skip is None: + self.skip = [] + else: + self.skip = skip + if nonconvergence is None: + self.nonconvergence = [] + else: + self.nonconvergence = nonconvergence + + +class SingleTest: + def __init__(self, A, b, solver, casename, convergence=True): + self.A = A + self.b = b + self.solver = solver + self.name = casename + '-' + solver.__name__ + self.convergence = convergence + + def __repr__(self): + return f"<{self.name}>" + + +class IterativeParams: + def __init__(self): + sym_solvers = [minres, cg] + posdef_solvers = [cg] + real_solvers = [minres] + + # list of Cases + self.cases = [] + + # Symmetric and Positive Definite + N = 40 + data = ones((3, N)) + data[0, :] = 2 + data[1, :] = -1 + data[2, :] = -1 + Poisson1D = dia_array((data, [0, -1, 1]), shape=(N, N)).tocsr() + self.cases.append(Case("poisson1d", Poisson1D)) + # note: minres fails for single precision + self.cases.append(Case("poisson1d-F", Poisson1D.astype('f'), + skip=[minres])) + + # Symmetric and Negative Definite + self.cases.append(Case("neg-poisson1d", -Poisson1D, + skip=posdef_solvers)) + # note: minres fails for single precision + self.cases.append(Case("neg-poisson1d-F", (-Poisson1D).astype('f'), + skip=posdef_solvers + [minres])) + + # 2-dimensional Poisson equations + Poisson2D = kronsum(Poisson1D, Poisson1D) + # note: minres fails for 2-d poisson problem, + # it will be fixed in the future PR + self.cases.append(Case("poisson2d", Poisson2D, skip=[minres])) + # note: minres fails for single precision + self.cases.append(Case("poisson2d-F", Poisson2D.astype('f'), + skip=[minres])) + + # Symmetric and Indefinite + data = array([[6, -5, 2, 7, -1, 10, 4, -3, -8, 9]], dtype='d') + RandDiag = dia_array((data, [0]), shape=(10, 10)).tocsr() + self.cases.append(Case("rand-diag", RandDiag, skip=posdef_solvers)) + self.cases.append(Case("rand-diag-F", RandDiag.astype('f'), + skip=posdef_solvers)) + + # Random real-valued + rng = np.random.RandomState(1234) + data = rng.rand(4, 4) + self.cases.append(Case("rand", data, + skip=posdef_solvers + sym_solvers)) + self.cases.append(Case("rand-F", data.astype('f'), + skip=posdef_solvers + sym_solvers)) + + # Random symmetric real-valued + rng = np.random.RandomState(1234) + data = rng.rand(4, 4) + data = data + data.T + self.cases.append(Case("rand-sym", data, skip=posdef_solvers)) + self.cases.append(Case("rand-sym-F", data.astype('f'), + skip=posdef_solvers)) + + # Random pos-def symmetric real + np.random.seed(1234) + data = np.random.rand(9, 9) + data = np.dot(data.conj(), data.T) + self.cases.append(Case("rand-sym-pd", data)) + # note: minres fails for single precision + self.cases.append(Case("rand-sym-pd-F", data.astype('f'), + skip=[minres])) + + # Random complex-valued + rng = np.random.RandomState(1234) + data = rng.rand(4, 4) + 1j * rng.rand(4, 4) + skip_cmplx = posdef_solvers + sym_solvers + real_solvers + self.cases.append(Case("rand-cmplx", data, skip=skip_cmplx)) + self.cases.append(Case("rand-cmplx-F", data.astype('F'), + skip=skip_cmplx)) + + # Random hermitian complex-valued + rng = np.random.RandomState(1234) + data = rng.rand(4, 4) + 1j * rng.rand(4, 4) + data = data + data.T.conj() + self.cases.append(Case("rand-cmplx-herm", data, + skip=posdef_solvers + real_solvers)) + self.cases.append(Case("rand-cmplx-herm-F", data.astype('F'), + skip=posdef_solvers + real_solvers)) + + # Random pos-def hermitian complex-valued + rng = np.random.RandomState(1234) + data = rng.rand(9, 9) + 1j * rng.rand(9, 9) + data = np.dot(data.conj(), data.T) + self.cases.append(Case("rand-cmplx-sym-pd", data, skip=real_solvers)) + self.cases.append(Case("rand-cmplx-sym-pd-F", data.astype('F'), + skip=real_solvers)) + + # Non-symmetric and Positive Definite + # + # cgs, qmr, bicg and tfqmr fail to converge on this one + # -- algorithmic limitation apparently + data = ones((2, 10)) + data[0, :] = 2 + data[1, :] = -1 + A = dia_array((data, [0, -1]), shape=(10, 10)).tocsr() + self.cases.append(Case("nonsymposdef", A, + skip=sym_solvers + [cgs, qmr, bicg, tfqmr])) + self.cases.append(Case("nonsymposdef-F", A.astype('F'), + skip=sym_solvers + [cgs, qmr, bicg, tfqmr])) + + # Symmetric, non-pd, hitting cgs/bicg/bicgstab/qmr/tfqmr breakdown + A = np.array([[0, 0, 0, 0, 0, 1, -1, -0, -0, -0, -0], + [0, 0, 0, 0, 0, 2, -0, -1, -0, -0, -0], + [0, 0, 0, 0, 0, 2, -0, -0, -1, -0, -0], + [0, 0, 0, 0, 0, 2, -0, -0, -0, -1, -0], + [0, 0, 0, 0, 0, 1, -0, -0, -0, -0, -1], + [1, 2, 2, 2, 1, 0, -0, -0, -0, -0, -0], + [-1, 0, 0, 0, 0, 0, -1, -0, -0, -0, -0], + [0, -1, 0, 0, 0, 0, -0, -1, -0, -0, -0], + [0, 0, -1, 0, 0, 0, -0, -0, -1, -0, -0], + [0, 0, 0, -1, 0, 0, -0, -0, -0, -1, -0], + [0, 0, 0, 0, -1, 0, -0, -0, -0, -0, -1]], dtype=float) + b = np.array([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=float) + assert (A == A.T).all() + self.cases.append(Case("sym-nonpd", A, b, + skip=posdef_solvers, + nonconvergence=[cgs, bicg, bicgstab, qmr, tfqmr] + ) + ) + + def generate_tests(self): + # generate test cases with skips applied + tests = [] + for case in self.cases: + for solver in _SOLVERS: + if (solver in case.skip): + continue + if solver in case.nonconvergence: + tests += [SingleTest(case.A, case.b, solver, case.name, + convergence=False)] + else: + tests += [SingleTest(case.A, case.b, solver, case.name)] + return tests + + +cases = IterativeParams().generate_tests() + + +@pytest.fixture(params=cases, ids=[x.name for x in cases], scope="module") +def case(request): + """ + Fixture for all cases in IterativeParams + """ + return request.param + +@pytest.mark.thread_unsafe +def test_maxiter(case): + if not case.convergence: + pytest.skip("Solver - Breakdown case, see gh-8829") + A = case.A + rtol = 1e-12 + + b = case.b + x0 = 0 * b + + residuals = [] + + def callback(x): + if x.ndim == 0: + residuals.append(norm(b - case.A * x)) + else: + residuals.append(norm(b - case.A @ x)) + + if case.solver == gmres: + with pytest.warns(DeprecationWarning, match=CB_TYPE_FILTER): + x, info = case.solver(A, b, x0=x0, rtol=rtol, maxiter=1, callback=callback) + else: + x, info = case.solver(A, b, x0=x0, rtol=rtol, maxiter=1, callback=callback) + + assert len(residuals) == 1 + assert info == 1 + + +def test_convergence(case): + A = case.A + + if A.dtype.char in "dD": + rtol = 1e-8 + else: + rtol = 1e-2 + + b = case.b + x0 = 0 * b + + x, info = case.solver(A, b, x0=x0, rtol=rtol) + + assert_array_equal(x0, 0 * b) # ensure that x0 is not overwritten + if case.convergence: + assert info == 0 + assert norm(A @ x - b) <= norm(b) * rtol + else: + assert info != 0 + assert norm(A @ x - b) <= norm(b) + + +def test_precond_dummy(case): + if not case.convergence: + pytest.skip("Solver - Breakdown case, see gh-8829") + + rtol = 1e-8 + + def identity(b, which=None): + """trivial preconditioner""" + return b + + A = case.A + + M, N = A.shape + # Ensure the diagonal elements of A are non-zero before calculating + # 1.0/A.diagonal() + diagOfA = A.diagonal() + if np.count_nonzero(diagOfA) == len(diagOfA): + dia_array(([1.0 / diagOfA], [0]), shape=(M, N)) + + b = case.b + x0 = 0 * b + + precond = LinearOperator(A.shape, identity, rmatvec=identity) + + if case.solver is qmr: + x, info = case.solver(A, b, M1=precond, M2=precond, x0=x0, rtol=rtol) + else: + x, info = case.solver(A, b, M=precond, x0=x0, rtol=rtol) + assert info == 0 + assert norm(A @ x - b) <= norm(b) * rtol + + A = aslinearoperator(A) + A.psolve = identity + A.rpsolve = identity + + x, info = case.solver(A, b, x0=x0, rtol=rtol) + assert info == 0 + assert norm(A @ x - b) <= norm(b) * rtol + + +# Specific test for poisson1d and poisson2d cases +@pytest.mark.fail_slow(10) +@pytest.mark.parametrize('case', [x for x in IterativeParams().cases + if x.name in ('poisson1d', 'poisson2d')], + ids=['poisson1d', 'poisson2d']) +def test_precond_inverse(case): + for solver in _SOLVERS: + if solver in case.skip or solver is qmr: + continue + + rtol = 1e-8 + + def inverse(b, which=None): + """inverse preconditioner""" + A = case.A + if not isinstance(A, np.ndarray): + A = A.toarray() + return np.linalg.solve(A, b) + + def rinverse(b, which=None): + """inverse preconditioner""" + A = case.A + if not isinstance(A, np.ndarray): + A = A.toarray() + return np.linalg.solve(A.T, b) + + matvec_count = [0] + + def matvec(b): + matvec_count[0] += 1 + return case.A @ b + + def rmatvec(b): + matvec_count[0] += 1 + return case.A.T @ b + + b = case.b + x0 = 0 * b + + A = LinearOperator(case.A.shape, matvec, rmatvec=rmatvec) + precond = LinearOperator(case.A.shape, inverse, rmatvec=rinverse) + + # Solve with preconditioner + matvec_count = [0] + x, info = solver(A, b, M=precond, x0=x0, rtol=rtol) + + assert info == 0 + assert norm(case.A @ x - b) <= norm(b) * rtol + + # Solution should be nearly instant + assert matvec_count[0] <= 3 + + +def test_atol(solver): + # TODO: minres / tfqmr. It didn't historically use absolute tolerances, so + # fixing it is less urgent. + if solver in (minres, tfqmr): + pytest.skip("TODO: Add atol to minres/tfqmr") + + # Historically this is tested as below, all pass but for some reason + # gcrotmk is over-sensitive to difference between random.seed/rng.random + # Hence tol lower bound is changed from -10 to -9 + # np.random.seed(1234) + # A = np.random.rand(10, 10) + # A = A @ A.T + 10 * np.eye(10) + # b = 1e3*np.random.rand(10) + + rng = np.random.default_rng(168441431005389) + A = rng.uniform(size=[10, 10]) + A = A @ A.T + 10*np.eye(10) + b = 1e3 * rng.uniform(size=10) + + b_norm = np.linalg.norm(b) + + tols = np.r_[0, np.logspace(-9, 2, 7), np.inf] + + # Check effect of badly scaled preconditioners + M0 = rng.standard_normal(size=(10, 10)) + M0 = M0 @ M0.T + Ms = [None, 1e-6 * M0, 1e6 * M0] + + for M, rtol, atol in itertools.product(Ms, tols, tols): + if rtol == 0 and atol == 0: + continue + + if solver is qmr: + if M is not None: + M = aslinearoperator(M) + M2 = aslinearoperator(np.eye(10)) + else: + M2 = None + x, info = solver(A, b, M1=M, M2=M2, rtol=rtol, atol=atol) + else: + x, info = solver(A, b, M=M, rtol=rtol, atol=atol) + + assert info == 0 + residual = A @ x - b + err = np.linalg.norm(residual) + atol2 = rtol * b_norm + # Added 1.00025 fudge factor because of `err` exceeding `atol` just + # very slightly on s390x (see gh-17839) + assert err <= 1.00025 * max(atol, atol2) + + +def test_zero_rhs(solver): + rng = np.random.default_rng(1684414984100503) + A = rng.random(size=[10, 10]) + A = A @ A.T + 10 * np.eye(10) + + b = np.zeros(10) + tols = np.r_[np.logspace(-10, 2, 7)] + + for tol in tols: + x, info = solver(A, b, rtol=tol) + assert info == 0 + assert_allclose(x, 0., atol=1e-15) + + x, info = solver(A, b, rtol=tol, x0=ones(10)) + assert info == 0 + assert_allclose(x, 0., atol=tol) + + if solver is not minres: + x, info = solver(A, b, rtol=tol, atol=0, x0=ones(10)) + if info == 0: + assert_allclose(x, 0) + + x, info = solver(A, b, rtol=tol, atol=tol) + assert info == 0 + assert_allclose(x, 0, atol=1e-300) + + x, info = solver(A, b, rtol=tol, atol=0) + assert info == 0 + assert_allclose(x, 0, atol=1e-300) + + +@pytest.mark.xfail(reason="see gh-18697") +def test_maxiter_worsening(solver): + if solver not in (gmres, lgmres, qmr): + # these were skipped from the very beginning, see gh-9201; gh-14160 + pytest.skip("Solver breakdown case") + # Check error does not grow (boundlessly) with increasing maxiter. + # This can occur due to the solvers hitting close to breakdown, + # which they should detect and halt as necessary. + # cf. gh-9100 + if (solver is lgmres and + platform.machine() not in ['x86_64' 'x86', 'aarch64', 'arm64']): + # see gh-17839 + pytest.xfail(reason="fails on at least ppc64le, ppc64 and riscv64") + + # Singular matrix, rhs numerically not in range + A = np.array([[-0.1112795288033378, 0, 0, 0.16127952880333685], + [0, -0.13627952880333782 + 6.283185307179586j, 0, 0], + [0, 0, -0.13627952880333782 - 6.283185307179586j, 0], + [0.1112795288033368, 0j, 0j, -0.16127952880333785]]) + v = np.ones(4) + best_error = np.inf + + # Unable to match the Fortran code tolerance levels with this example + # Original tolerance values + + # slack_tol = 7 if platform.machine() == 'aarch64' else 5 + slack_tol = 9 + + for maxiter in range(1, 20): + x, info = solver(A, v, maxiter=maxiter, rtol=1e-8, atol=0) + + if info == 0: + assert norm(A @ x - v) <= 1e-8 * norm(v) + + error = np.linalg.norm(A @ x - v) + best_error = min(best_error, error) + + # Check with slack + assert error <= slack_tol * best_error + + +def test_x0_working(solver): + # Easy problem + rng = np.random.default_rng(1685363802304750) + n = 10 + A = rng.random(size=[n, n]) + A = A @ A.T + b = rng.random(n) + x0 = rng.random(n) + + if solver is minres: + kw = dict(rtol=1e-6) + else: + kw = dict(atol=0, rtol=1e-6) + + x, info = solver(A, b, **kw) + assert info == 0 + assert norm(A @ x - b) <= 1e-6 * norm(b) + + x, info = solver(A, b, x0=x0, **kw) + assert info == 0 + assert norm(A @ x - b) <= 4.5e-6*norm(b) + + +def test_x0_equals_Mb(case): + if (case.solver is bicgstab) and (case.name == 'nonsymposdef-bicgstab'): + pytest.skip("Solver fails due to numerical noise " + "on some architectures (see gh-15533).") + if case.solver is tfqmr: + pytest.skip("Solver does not support x0='Mb'") + + A = case.A + b = case.b + x0 = 'Mb' + rtol = 1e-8 + x, info = case.solver(A, b, x0=x0, rtol=rtol) + + assert_array_equal(x0, 'Mb') # ensure that x0 is not overwritten + assert info == 0 + assert norm(A @ x - b) <= rtol * norm(b) + + +@pytest.mark.parametrize('solver', _SOLVERS) +def test_x0_solves_problem_exactly(solver): + # See gh-19948 + mat = np.eye(2) + rhs = np.array([-1., -1.]) + + sol, info = solver(mat, rhs, x0=rhs) + assert_allclose(sol, rhs) + assert info == 0 + + +# Specific tfqmr test +@pytest.mark.thread_unsafe +@pytest.mark.parametrize('case', IterativeParams().cases) +def test_show(case, capsys): + def cb(x): + pass + + x, info = tfqmr(case.A, case.b, callback=cb, show=True) + out, err = capsys.readouterr() + + if case.name == "sym-nonpd": + # no logs for some reason + exp = "" + elif case.name in ("nonsymposdef", "nonsymposdef-F"): + # Asymmetric and Positive Definite + exp = "TFQMR: Linear solve not converged due to reach MAXIT iterations" + else: # all other cases + exp = "TFQMR: Linear solve converged due to reach TOL iterations" + + assert out.startswith(exp) + assert err == "" + + +def test_positional_error(solver): + # from test_x0_working + rng = np.random.default_rng(1685363802304750) + n = 10 + A = rng.random(size=[n, n]) + A = A @ A.T + b = rng.random(n) + x0 = rng.random(n) + with pytest.raises(TypeError): + solver(A, b, x0, 1e-5) + + +@pytest.mark.parametrize("atol", ["legacy", None, -1]) +def test_invalid_atol(solver, atol): + if solver == minres: + pytest.skip("minres has no `atol` argument") + # from test_x0_working + rng = np.random.default_rng(1685363802304750) + n = 10 + A = rng.random(size=[n, n]) + A = A @ A.T + b = rng.random(n) + x0 = rng.random(n) + with pytest.raises(ValueError): + solver(A, b, x0, atol=atol) + + +class TestQMR: + @pytest.mark.filterwarnings('ignore::scipy.sparse.SparseEfficiencyWarning') + def test_leftright_precond(self): + """Check that QMR works with left and right preconditioners""" + + from scipy.sparse.linalg._dsolve import splu + from scipy.sparse.linalg._interface import LinearOperator + + n = 100 + + dat = ones(n) + A = dia_array(([-2 * dat, 4 * dat, -dat], [-1, 0, 1]), shape=(n, n)) + b = arange(n, dtype='d') + + L = dia_array(([-dat / 2, dat], [-1, 0]), shape=(n, n)) + U = dia_array(([4 * dat, -dat], [0, 1]), shape=(n, n)) + L_solver = splu(L) + U_solver = splu(U) + + def L_solve(b): + return L_solver.solve(b) + + def U_solve(b): + return U_solver.solve(b) + + def LT_solve(b): + return L_solver.solve(b, 'T') + + def UT_solve(b): + return U_solver.solve(b, 'T') + + M1 = LinearOperator((n, n), matvec=L_solve, rmatvec=LT_solve) + M2 = LinearOperator((n, n), matvec=U_solve, rmatvec=UT_solve) + + rtol = 1e-8 + x, info = qmr(A, b, rtol=rtol, maxiter=15, M1=M1, M2=M2) + + assert info == 0 + assert norm(A @ x - b) <= rtol * norm(b) + + +class TestGMRES: + def test_basic(self): + A = np.vander(np.arange(10) + 1)[:, ::-1] + b = np.zeros(10) + b[0] = 1 + + x_gm, err = gmres(A, b, restart=5, maxiter=1) + + assert_allclose(x_gm[0], 0.359, rtol=1e-2) + + @pytest.mark.filterwarnings(f"ignore:{CB_TYPE_FILTER}:DeprecationWarning") + def test_callback(self): + + def store_residual(r, rvec): + rvec[rvec.nonzero()[0].max() + 1] = r + + # Define, A,b + A = csr_array(array([[-2, 1, 0, 0, 0, 0], + [1, -2, 1, 0, 0, 0], + [0, 1, -2, 1, 0, 0], + [0, 0, 1, -2, 1, 0], + [0, 0, 0, 1, -2, 1], + [0, 0, 0, 0, 1, -2]])) + b = ones((A.shape[0],)) + maxiter = 1 + rvec = zeros(maxiter + 1) + rvec[0] = 1.0 + + def callback(r): + return store_residual(r, rvec) + + x, flag = gmres(A, b, x0=zeros(A.shape[0]), rtol=1e-16, + maxiter=maxiter, callback=callback) + + # Expected output from SciPy 1.0.0 + assert_allclose(rvec, array([1.0, 0.81649658092772603]), rtol=1e-10) + + # Test preconditioned callback + M = 1e-3 * np.eye(A.shape[0]) + rvec = zeros(maxiter + 1) + rvec[0] = 1.0 + x, flag = gmres(A, b, M=M, rtol=1e-16, maxiter=maxiter, + callback=callback) + + # Expected output from SciPy 1.0.0 + # (callback has preconditioned residual!) + assert_allclose(rvec, array([1.0, 1e-3 * 0.81649658092772603]), + rtol=1e-10) + + def test_abi(self): + # Check we don't segfault on gmres with complex argument + A = eye(2) + b = ones(2) + r_x, r_info = gmres(A, b) + r_x = r_x.astype(complex) + x, info = gmres(A.astype(complex), b.astype(complex)) + + assert iscomplexobj(x) + assert_allclose(r_x, x) + assert r_info == info + + @pytest.mark.fail_slow(10) + def test_atol_legacy(self): + + A = eye(2) + b = ones(2) + x, info = gmres(A, b, rtol=1e-5) + assert np.linalg.norm(A @ x - b) <= 1e-5 * np.linalg.norm(b) + assert_allclose(x, b, atol=0, rtol=1e-8) + + rndm = np.random.RandomState(12345) + A = rndm.rand(30, 30) + b = 1e-6 * ones(30) + x, info = gmres(A, b, rtol=1e-7, restart=20) + assert np.linalg.norm(A @ x - b) > 1e-7 + + A = eye(2) + b = 1e-10 * ones(2) + x, info = gmres(A, b, rtol=1e-8, atol=0) + assert np.linalg.norm(A @ x - b) <= 1e-8 * np.linalg.norm(b) + + def test_defective_precond_breakdown(self): + # Breakdown due to defective preconditioner + M = np.eye(3) + M[2, 2] = 0 + + b = np.array([0, 1, 1]) + x = np.array([1, 0, 0]) + A = np.diag([2, 3, 4]) + + x, info = gmres(A, b, x0=x, M=M, rtol=1e-15, atol=0) + + # Should not return nans, nor terminate with false success + assert not np.isnan(x).any() + if info == 0: + assert np.linalg.norm(A @ x - b) <= 1e-15 * np.linalg.norm(b) + + # The solution should be OK outside null space of M + assert_allclose(M @ (A @ x), M @ b) + + def test_defective_matrix_breakdown(self): + # Breakdown due to defective matrix + A = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 0]]) + b = np.array([1, 0, 1]) + rtol = 1e-8 + x, info = gmres(A, b, rtol=rtol, atol=0) + + # Should not return nans, nor terminate with false success + assert not np.isnan(x).any() + if info == 0: + assert np.linalg.norm(A @ x - b) <= rtol * np.linalg.norm(b) + + # The solution should be OK outside null space of A + assert_allclose(A @ (A @ x), A @ b) + + @pytest.mark.filterwarnings(f"ignore:{CB_TYPE_FILTER}:DeprecationWarning") + def test_callback_type(self): + # The legacy callback type changes meaning of 'maxiter' + np.random.seed(1) + A = np.random.rand(20, 20) + b = np.random.rand(20) + + cb_count = [0] + + def pr_norm_cb(r): + cb_count[0] += 1 + assert isinstance(r, float) + + def x_cb(x): + cb_count[0] += 1 + assert isinstance(x, np.ndarray) + + # 2 iterations is not enough to solve the problem + cb_count = [0] + x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb, + maxiter=2, restart=50) + assert info == 2 + assert cb_count[0] == 2 + + # With `callback_type` specified, no warning should be raised + cb_count = [0] + x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb, + maxiter=2, restart=50, callback_type='legacy') + assert info == 2 + assert cb_count[0] == 2 + + # 2 restart cycles is enough to solve the problem + cb_count = [0] + x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb, + maxiter=2, restart=50, callback_type='pr_norm') + assert info == 0 + assert cb_count[0] > 2 + + # 2 restart cycles is enough to solve the problem + cb_count = [0] + x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=2, + restart=50, callback_type='x') + assert info == 0 + assert cb_count[0] == 1 + + def test_callback_x_monotonic(self): + # Check that callback_type='x' gives monotonic norm decrease + rng = np.random.RandomState(1) + A = rng.rand(20, 20) + np.eye(20) + b = rng.rand(20) + + prev_r = [np.inf] + count = [0] + + def x_cb(x): + r = np.linalg.norm(A @ x - b) + assert r <= prev_r[0] + prev_r[0] = r + count[0] += 1 + + x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=20, + restart=10, callback_type='x') + assert info == 20 + assert count[0] == 20 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py new file mode 100644 index 0000000000000000000000000000000000000000..a33fc9bc13b36faef48f04388b76ed33eac775d6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py @@ -0,0 +1,225 @@ +"""Tests for the linalg._isolve.lgmres module +""" + +import threading +from numpy.testing import (assert_, assert_allclose, assert_equal, + suppress_warnings) + +import pytest +from platform import python_implementation + +import numpy as np +from numpy import zeros, array, allclose +from scipy.linalg import norm +from scipy.sparse import csr_array, eye_array, random_array + +from scipy.sparse.linalg._interface import LinearOperator +from scipy.sparse.linalg import splu +from scipy.sparse.linalg._isolve import lgmres, gmres + + +Am = csr_array(array([[-2, 1, 0, 0, 0, 9], + [1, -2, 1, 0, 5, 0], + [0, 1, -2, 1, 0, 0], + [0, 0, 1, -2, 1, 0], + [0, 3, 0, 1, -2, 1], + [1, 0, 0, 0, 1, -2]])) +b = array([1, 2, 3, 4, 5, 6]) +count = threading.local() # [0] +niter = threading.local() # [0] + + +def matvec(v): + if not hasattr(count, 'c'): + count.c = [0] + count.c[0] += 1 + return Am@v + + +def cb(v): + if not hasattr(niter, 'n'): + niter.n = [0] + niter.n[0] += 1 + + +A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype) + + +def do_solve(**kw): + if not hasattr(niter, 'n'): + niter.n = [0] + if not hasattr(count, 'c'): + count.c = [0] + count.c[0] = 0 + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x0, flag = lgmres(A, b, x0=zeros(A.shape[0]), + inner_m=6, rtol=1e-14, **kw) + count_0 = count.c[0] + assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b)) + return x0, count_0 + + +class TestLGMRES: + def test_preconditioner(self): + # Check that preconditioning works + pc = splu(Am.tocsc()) + M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype) + + x0, count_0 = do_solve() + niter.n[0] = 0 + x1, count_1 = do_solve(M=M, callback=cb) + + assert count_1 == 3 + assert count_1 < count_0/2 + assert allclose(x1, x0, rtol=1e-14) + assert niter.n[0] < 3 + + def test_outer_v(self): + # Check that the augmentation vectors behave as expected + + outer_v = [] + x0, count_0 = do_solve(outer_k=6, outer_v=outer_v) + assert_(len(outer_v) > 0) + assert_(len(outer_v) <= 6) + + x1, count_1 = do_solve(outer_k=6, outer_v=outer_v, + prepend_outer_v=True) + assert_(count_1 == 2, count_1) + assert_(count_1 < count_0/2) + assert_(allclose(x1, x0, rtol=1e-14)) + + # --- + + outer_v = [] + x0, count_0 = do_solve(outer_k=6, outer_v=outer_v, + store_outer_Av=False) + assert_(array([v[1] is None for v in outer_v]).all()) + assert_(len(outer_v) > 0) + assert_(len(outer_v) <= 6) + + x1, count_1 = do_solve(outer_k=6, outer_v=outer_v, + prepend_outer_v=True) + assert_(count_1 == 3, count_1) + assert_(count_1 < count_0/2) + assert_(allclose(x1, x0, rtol=1e-14)) + + @pytest.mark.skipif(python_implementation() == 'PyPy', + reason="Fails on PyPy CI runs. See #9507") + def test_arnoldi(self): + rng = np.random.default_rng(123) + + A = eye_array(2000) + random_array((2000, 2000), density=5e-4, rng=rng) + b = rng.random(2000) + + # The inner arnoldi should be equivalent to gmres + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x0, flag0 = lgmres(A, b, x0=zeros(A.shape[0]), inner_m=10, maxiter=1) + x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=10, maxiter=1) + + assert_equal(flag0, 1) + assert_equal(flag1, 1) + norm = np.linalg.norm(A.dot(x0) - b) + assert_(norm > 1e-4) + assert_allclose(x0, x1) + + def test_cornercase(self): + rng = np.random.RandomState(1234) + + # Rounding error may prevent convergence with tol=0 --- ensure + # that the return values in this case are correct, and no + # exceptions are raised + + for n in [3, 5, 10, 100]: + A = 2*eye_array(n) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + + b = np.ones(n) + x, info = lgmres(A, b, maxiter=10) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + x, info = lgmres(A, b, rtol=0, maxiter=10) + if info == 0: + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + b = rng.rand(n) + x, info = lgmres(A, b, maxiter=10) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + x, info = lgmres(A, b, rtol=0, maxiter=10) + if info == 0: + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + def test_nans(self): + A = eye_array(3, format='lil') + A[1, 1] = np.nan + b = np.ones(3) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x, info = lgmres(A, b, rtol=0, maxiter=10) + assert_equal(info, 1) + + def test_breakdown_with_outer_v(self): + A = np.array([[1, 2], [3, 4]], dtype=float) + b = np.array([1, 2]) + + x = np.linalg.solve(A, b) + v0 = np.array([1, 0]) + + # The inner iteration should converge to the correct solution, + # since it's in the outer vector list + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + xp, info = lgmres(A, b, outer_v=[(v0, None), (x, None)], maxiter=1) + + assert_allclose(xp, x, atol=1e-12) + + def test_breakdown_underdetermined(self): + # Should find LSQ solution in the Krylov span in one inner + # iteration, despite solver breakdown from nilpotent A. + A = np.array([[0, 1, 1, 1], + [0, 0, 1, 1], + [0, 0, 0, 1], + [0, 0, 0, 0]], dtype=float) + + bs = [ + np.array([1, 1, 1, 1]), + np.array([1, 1, 1, 0]), + np.array([1, 1, 0, 0]), + np.array([1, 0, 0, 0]), + ] + + for b in bs: + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + xp, info = lgmres(A, b, maxiter=1) + resp = np.linalg.norm(A.dot(xp) - b) + + K = np.c_[b, A.dot(b), A.dot(A.dot(b)), A.dot(A.dot(A.dot(b)))] + y, _, _, _ = np.linalg.lstsq(A.dot(K), b, rcond=-1) + x = K.dot(y) + res = np.linalg.norm(A.dot(x) - b) + + assert_allclose(resp, res, err_msg=repr(b)) + + def test_denormals(self): + # Check that no warnings are emitted if the matrix contains + # numbers for which 1/x has no float representation, and that + # the solver behaves properly. + A = np.array([[1, 2], [3, 4]], dtype=float) + A *= 100 * np.nextafter(0, 1) + + b = np.array([1, 1]) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + xp, info = lgmres(A, b) + + if info == 0: + assert_allclose(A.dot(xp), b) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1196b23e0b7a24513850116ee134193709619e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py @@ -0,0 +1,185 @@ +""" +Copyright (C) 2010 David Fong and Michael Saunders +Distributed under the same license as SciPy + +Testing Code for LSMR. + +03 Jun 2010: First version release with lsmr.py + +David Chin-lung Fong clfong@stanford.edu +Institute for Computational and Mathematical Engineering +Stanford University + +Michael Saunders saunders@stanford.edu +Systems Optimization Laboratory +Dept of MS&E, Stanford University. + +""" + +from numpy import array, arange, eye, zeros, ones, transpose, hstack +from numpy.linalg import norm +from numpy.testing import assert_allclose +import pytest +from scipy.sparse import coo_array +from scipy.sparse.linalg._interface import aslinearoperator +from scipy.sparse.linalg import lsmr +from .test_lsqr import G, b + + +class TestLSMR: + def setup_method(self): + self.n = 10 + self.m = 10 + + def assertCompatibleSystem(self, A, xtrue): + Afun = aslinearoperator(A) + b = Afun.matvec(xtrue) + x = lsmr(A, b)[0] + assert norm(x - xtrue) == pytest.approx(0, abs=1e-5) + + def testIdentityACase1(self): + A = eye(self.n) + xtrue = zeros((self.n, 1)) + self.assertCompatibleSystem(A, xtrue) + + def testIdentityACase2(self): + A = eye(self.n) + xtrue = ones((self.n,1)) + self.assertCompatibleSystem(A, xtrue) + + def testIdentityACase3(self): + A = eye(self.n) + xtrue = transpose(arange(self.n,0,-1)) + self.assertCompatibleSystem(A, xtrue) + + def testBidiagonalA(self): + A = lowerBidiagonalMatrix(20,self.n) + xtrue = transpose(arange(self.n,0,-1)) + self.assertCompatibleSystem(A,xtrue) + + def testScalarB(self): + A = array([[1.0, 2.0]]) + b = 3.0 + x = lsmr(A, b)[0] + assert norm(A.dot(x) - b) == pytest.approx(0) + + def testComplexX(self): + A = eye(self.n) + xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j)) + self.assertCompatibleSystem(A, xtrue) + + def testComplexX0(self): + A = 4 * eye(self.n) + ones((self.n, self.n)) + xtrue = transpose(arange(self.n, 0, -1)) + b = aslinearoperator(A).matvec(xtrue) + x0 = zeros(self.n, dtype=complex) + x = lsmr(A, b, x0=x0)[0] + assert norm(x - xtrue) == pytest.approx(0, abs=1e-5) + + def testComplexA(self): + A = 4 * eye(self.n) + 1j * ones((self.n, self.n)) + xtrue = transpose(arange(self.n, 0, -1).astype(complex)) + self.assertCompatibleSystem(A, xtrue) + + def testComplexB(self): + A = 4 * eye(self.n) + ones((self.n, self.n)) + xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j)) + b = aslinearoperator(A).matvec(xtrue) + x = lsmr(A, b)[0] + assert norm(x - xtrue) == pytest.approx(0, abs=1e-5) + + def testColumnB(self): + A = eye(self.n) + b = ones((self.n, 1)) + x = lsmr(A, b)[0] + assert norm(A.dot(x) - b.ravel()) == pytest.approx(0) + + def testInitialization(self): + # Test that the default setting is not modified + x_ref, _, itn_ref, normr_ref, *_ = lsmr(G, b) + assert_allclose(norm(b - G@x_ref), normr_ref, atol=1e-6) + + # Test passing zeros yields similar result + x0 = zeros(b.shape) + x = lsmr(G, b, x0=x0)[0] + assert_allclose(x, x_ref) + + # Test warm-start with single iteration + x0 = lsmr(G, b, maxiter=1)[0] + + x, _, itn, normr, *_ = lsmr(G, b, x0=x0) + assert_allclose(norm(b - G@x), normr, atol=1e-6) + + # NOTE(gh-12139): This doesn't always converge to the same value as + # ref because error estimates will be slightly different when calculated + # from zeros vs x0 as a result only compare norm and itn (not x). + + # x generally converges 1 iteration faster because it started at x0. + # itn == itn_ref means that lsmr(x0) took an extra iteration see above. + # -1 is technically possible but is rare (1 in 100000) so it's more + # likely to be an error elsewhere. + assert itn - itn_ref in (0, 1) + + # If an extra iteration is performed normr may be 0, while normr_ref + # may be much larger. + assert normr < normr_ref * (1 + 1e-6) + + +class TestLSMRReturns: + def setup_method(self): + self.n = 10 + self.A = lowerBidiagonalMatrix(20, self.n) + self.xtrue = transpose(arange(self.n, 0, -1)) + self.Afun = aslinearoperator(self.A) + self.b = self.Afun.matvec(self.xtrue) + self.x0 = ones(self.n) + self.x00 = self.x0.copy() + self.returnValues = lsmr(self.A, self.b) + self.returnValuesX0 = lsmr(self.A, self.b, x0=self.x0) + + def test_unchanged_x0(self): + x, istop, itn, normr, normar, normA, condA, normx = self.returnValuesX0 + assert_allclose(self.x00, self.x0) + + def testNormr(self): + x, istop, itn, normr, normar, normA, condA, normx = self.returnValues + assert norm(self.b - self.Afun.matvec(x)) == pytest.approx(normr) + + def testNormar(self): + x, istop, itn, normr, normar, normA, condA, normx = self.returnValues + assert (norm(self.Afun.rmatvec(self.b - self.Afun.matvec(x))) + == pytest.approx(normar)) + + def testNormx(self): + x, istop, itn, normr, normar, normA, condA, normx = self.returnValues + assert norm(x) == pytest.approx(normx) + + +def lowerBidiagonalMatrix(m, n): + # This is a simple example for testing LSMR. + # It uses the leading m*n submatrix from + # A = [ 1 + # 1 2 + # 2 3 + # 3 4 + # ... + # n ] + # suitably padded by zeros. + # + # 04 Jun 2010: First version for distribution with lsmr.py + if m <= n: + row = hstack((arange(m, dtype=int), + arange(1, m, dtype=int))) + col = hstack((arange(m, dtype=int), + arange(m-1, dtype=int))) + data = hstack((arange(1, m+1, dtype=float), + arange(1,m, dtype=float))) + return coo_array((data, (row, col)), shape=(m,n)) + else: + row = hstack((arange(n, dtype=int), + arange(1, n+1, dtype=int))) + col = hstack((arange(n, dtype=int), + arange(n, dtype=int))) + data = hstack((arange(1, n+1, dtype=float), + arange(1,n+1, dtype=float))) + return coo_array((data,(row, col)), shape=(m,n)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py new file mode 100644 index 0000000000000000000000000000000000000000..d77048af48a6b4495d23c9bc9a3b2d71466bade6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py @@ -0,0 +1,120 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal, assert_equal +import pytest +import scipy.sparse +import scipy.sparse.linalg +from scipy.sparse.linalg import lsqr + +# Set up a test problem +n = 35 +G = np.eye(n) +normal = np.random.normal +norm = np.linalg.norm + +for jj in range(5): + gg = normal(size=n) + hh = gg * gg.T + G += (hh + hh.T) * 0.5 + G += normal(size=n) * normal(size=n) + +b = normal(size=n) + +# tolerance for atol/btol keywords of lsqr() +tol = 2e-10 +# tolerances for testing the results of the lsqr() call with assert_allclose +# These tolerances are a bit fragile - see discussion in gh-15301. +atol_test = 4e-10 +rtol_test = 2e-8 +show = False +maxit = None + + +def test_lsqr_basic(): + b_copy = b.copy() + xo, *_ = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit) + assert_array_equal(b_copy, b) + + svx = np.linalg.solve(G, b) + assert_allclose(xo, svx, atol=atol_test, rtol=rtol_test) + + # Now the same but with damp > 0. + # This is equivalent to solving the extended system: + # ( G ) @ x = ( b ) + # ( damp*I ) ( 0 ) + damp = 1.5 + xo, *_ = lsqr( + G, b, damp=damp, show=show, atol=tol, btol=tol, iter_lim=maxit) + + Gext = np.r_[G, damp * np.eye(G.shape[1])] + bext = np.r_[b, np.zeros(G.shape[1])] + svx, *_ = np.linalg.lstsq(Gext, bext, rcond=None) + assert_allclose(xo, svx, atol=atol_test, rtol=rtol_test) + + +def test_gh_2466(): + row = np.array([0, 0]) + col = np.array([0, 1]) + val = np.array([1, -1]) + A = scipy.sparse.coo_array((val, (row, col)), shape=(1, 2)) + b = np.asarray([4]) + lsqr(A, b) + + +def test_well_conditioned_problems(): + # Test that sparse the lsqr solver returns the right solution + # on various problems with different random seeds. + # This is a non-regression test for a potential ZeroDivisionError + # raised when computing the `test2` & `test3` convergence conditions. + n = 10 + A_sparse = scipy.sparse.eye_array(n, n) + A_dense = A_sparse.toarray() + + with np.errstate(invalid='raise'): + for seed in range(30): + rng = np.random.RandomState(seed + 10) + beta = rng.rand(n) + beta[beta == 0] = 0.00001 # ensure that all the betas are not null + b = A_sparse @ beta[:, np.newaxis] + output = lsqr(A_sparse, b, show=show) + + # Check that the termination condition corresponds to an approximate + # solution to Ax = b + assert_equal(output[1], 1) + solution = output[0] + + # Check that we recover the ground truth solution + assert_allclose(solution, beta) + + # Sanity check: compare to the dense array solver + reference_solution = np.linalg.solve(A_dense, b).ravel() + assert_allclose(solution, reference_solution) + + +def test_b_shapes(): + # Test b being a scalar. + A = np.array([[1.0, 2.0]]) + b = 3.0 + x = lsqr(A, b)[0] + assert norm(A.dot(x) - b) == pytest.approx(0) + + # Test b being a column vector. + A = np.eye(10) + b = np.ones((10, 1)) + x = lsqr(A, b)[0] + assert norm(A.dot(x) - b.ravel()) == pytest.approx(0) + + +def test_initialization(): + # Test the default setting is the same as zeros + b_copy = b.copy() + x_ref = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit) + x0 = np.zeros(x_ref[0].shape) + x = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit, x0=x0) + assert_array_equal(b_copy, b) + assert_allclose(x_ref[0], x[0]) + + # Test warm-start with single iteration + x0 = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=1)[0] + x = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit, x0=x0) + assert_allclose(x_ref[0], x[0]) + assert_array_equal(b_copy, b) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py new file mode 100644 index 0000000000000000000000000000000000000000..cae169e14f0306b195bca73ce86547391851aab6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py @@ -0,0 +1,97 @@ +import numpy as np +from numpy.linalg import norm +from numpy.testing import assert_equal, assert_allclose, assert_ +from scipy.sparse.linalg._isolve import minres + +from pytest import raises as assert_raises + + +def get_sample_problem(): + # A random 10 x 10 symmetric matrix + rng = np.random.RandomState(1234) + matrix = rng.rand(10, 10) + matrix = matrix + matrix.T + # A random vector of length 10 + vector = rng.rand(10) + return matrix, vector + + +def test_singular(): + A, b = get_sample_problem() + A[0, ] = 0 + b[0] = 0 + xp, info = minres(A, b) + assert_equal(info, 0) + assert norm(A @ xp - b) <= 1e-5 * norm(b) + + +def test_x0_is_used_by(): + A, b = get_sample_problem() + # Random x0 to feed minres + rng = np.random.RandomState(12345) + x0 = rng.rand(10) + trace = [] + + def trace_iterates(xk): + trace.append(xk) + minres(A, b, x0=x0, callback=trace_iterates) + trace_with_x0 = trace + + trace = [] + minres(A, b, callback=trace_iterates) + assert_(not np.array_equal(trace_with_x0[0], trace[0])) + + +def test_shift(): + A, b = get_sample_problem() + shift = 0.5 + shifted_A = A - shift * np.eye(10) + x1, info1 = minres(A, b, shift=shift) + x2, info2 = minres(shifted_A, b) + assert_equal(info1, 0) + assert_allclose(x1, x2, rtol=1e-5) + + +def test_asymmetric_fail(): + """Asymmetric matrix should raise `ValueError` when check=True""" + A, b = get_sample_problem() + A[1, 2] = 1 + A[2, 1] = 2 + with assert_raises(ValueError): + xp, info = minres(A, b, check=True) + + +def test_minres_non_default_x0(): + rng = np.random.RandomState(1234) + rtol = 1e-6 + a = rng.randn(5, 5) + a = np.dot(a, a.T) + b = rng.randn(5) + c = rng.randn(5) + x = minres(a, b, x0=c, rtol=rtol)[0] + assert norm(a @ x - b) <= rtol * norm(b) + + +def test_minres_precond_non_default_x0(): + rng = np.random.RandomState(12345) + rtol = 1e-6 + a = rng.randn(5, 5) + a = np.dot(a, a.T) + b = rng.randn(5) + c = rng.randn(5) + m = rng.randn(5, 5) + m = np.dot(m, m.T) + x = minres(a, b, M=m, x0=c, rtol=rtol)[0] + assert norm(a @ x - b) <= rtol * norm(b) + + +def test_minres_precond_exact_x0(): + rng = np.random.RandomState(1234) + rtol = 1e-6 + a = np.eye(10) + b = np.ones(10) + c = np.ones(10) + m = rng.randn(10, 10) + m = np.dot(m, m.T) + x = minres(a, b, M=m, x0=c, rtol=rtol)[0] + assert norm(a @ x - b) <= rtol * norm(b) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb62e2223d515288bd5aa6c5a70028279c4f6d30 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py @@ -0,0 +1,9 @@ +import numpy as np +from pytest import raises as assert_raises + +import scipy.sparse.linalg._isolve.utils as utils + + +def test_make_system_bad_shape(): + assert_raises(ValueError, + utils.make_system, np.zeros((5,3)), None, np.zeros(4), np.zeros(4)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py new file mode 100644 index 0000000000000000000000000000000000000000..3d5d2ee2f1bc2c3fef03c71fc0206cd06f3f8618 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py @@ -0,0 +1,338 @@ +"""Test of 1D arithmetic operations""" + +import pytest + +import numpy as np +from numpy.testing import assert_equal, assert_allclose + +from scipy.sparse import coo_array, csr_array +from scipy.sparse._sputils import isscalarlike + + +spcreators = [coo_array, csr_array] +math_dtypes = [np.int64, np.float64, np.complex128] + + +def toarray(a): + if isinstance(a, np.ndarray) or isscalarlike(a): + return a + return a.toarray() + +@pytest.fixture +def dat1d(): + return np.array([3, 0, 1, 0], 'd') + + +@pytest.fixture +def datsp_math_dtypes(dat1d): + dat_dtypes = {dtype: dat1d.astype(dtype) for dtype in math_dtypes} + return { + sp: [(dtype, dat, sp(dat)) for dtype, dat in dat_dtypes.items()] + for sp in spcreators + } + + +@pytest.mark.parametrize("spcreator", spcreators) +class TestArithmetic1D: + def test_empty_arithmetic(self, spcreator): + shape = (5,) + for mytype in [ + np.dtype('int32'), + np.dtype('float32'), + np.dtype('float64'), + np.dtype('complex64'), + np.dtype('complex128'), + ]: + a = spcreator(shape, dtype=mytype) + b = a + a + c = 2 * a + assert isinstance(a @ a.tocsr(), np.ndarray) + assert isinstance(a @ a.tocoo(), np.ndarray) + for m in [a, b, c]: + assert m @ m == a.toarray() @ a.toarray() + assert m.dtype == mytype + assert toarray(m).dtype == mytype + + def test_abs(self, spcreator): + A = np.array([-1, 0, 17, 0, -5, 0, 1, -4, 0, 0, 0, 0], 'd') + assert_equal(abs(A), abs(spcreator(A)).toarray()) + + def test_round(self, spcreator): + A = np.array([-1.35, 0.56, 17.25, -5.98], 'd') + Asp = spcreator(A) + assert_equal(np.around(A, decimals=1), round(Asp, ndigits=1).toarray()) + + def test_elementwise_power(self, spcreator): + A = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4], 'd') + Asp = spcreator(A) + assert_equal(np.power(A, 2), Asp.power(2).toarray()) + + # element-wise power function needs a scalar power + with pytest.raises(NotImplementedError, match='input is not scalar'): + spcreator(A).power(A) + + def test_real(self, spcreator): + D = np.array([1 + 3j, 2 - 4j]) + A = spcreator(D) + assert_equal(A.real.toarray(), D.real) + + def test_imag(self, spcreator): + D = np.array([1 + 3j, 2 - 4j]) + A = spcreator(D) + assert_equal(A.imag.toarray(), D.imag) + + def test_mul_scalar(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + assert_equal(dat * 2, (datsp * 2).toarray()) + assert_equal(dat * 17.3, (datsp * 17.3).toarray()) + + def test_rmul_scalar(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + assert_equal(2 * dat, (2 * datsp).toarray()) + assert_equal(17.3 * dat, (17.3 * datsp).toarray()) + + def test_sub(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + if dtype == np.dtype('bool'): + # boolean array subtraction deprecated in 1.9.0 + continue + + assert_equal((datsp - datsp).toarray(), np.zeros(4)) + assert_equal((datsp - 0).toarray(), dat) + + A = spcreator([1, -4, 0, 2], dtype='d') + assert_equal((datsp - A).toarray(), dat - A.toarray()) + assert_equal((A - datsp).toarray(), A.toarray() - dat) + + # test broadcasting + assert_equal(datsp.toarray() - dat[0], dat - dat[0]) + + def test_add0(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + # Adding 0 to a sparse matrix + assert_equal((datsp + 0).toarray(), dat) + # use sum (which takes 0 as a starting value) + sumS = sum([k * datsp for k in range(1, 3)]) + sumD = sum([k * dat for k in range(1, 3)]) + assert_allclose(sumS.toarray(), sumD) + + def test_elementwise_multiply(self, spcreator): + # real/real + A = np.array([4, 0, 9]) + B = np.array([0, 7, -1]) + Asp = spcreator(A) + Bsp = spcreator(B) + assert_allclose(Asp.multiply(Bsp).toarray(), A * B) # sparse/sparse + assert_allclose(Asp.multiply(B).toarray(), A * B) # sparse/dense + + # complex/complex + C = np.array([1 - 2j, 0 + 5j, -1 + 0j]) + D = np.array([5 + 2j, 7 - 3j, -2 + 1j]) + Csp = spcreator(C) + Dsp = spcreator(D) + assert_allclose(Csp.multiply(Dsp).toarray(), C * D) # sparse/sparse + assert_allclose(Csp.multiply(D).toarray(), C * D) # sparse/dense + + # real/complex + assert_allclose(Asp.multiply(Dsp).toarray(), A * D) # sparse/sparse + assert_allclose(Asp.multiply(D).toarray(), A * D) # sparse/dense + + def test_elementwise_multiply_broadcast(self, spcreator): + A = np.array([4]) + B = np.array([[-9]]) + C = np.array([1, -1, 0]) + D = np.array([[7, 9, -9]]) + E = np.array([[3], [2], [1]]) + F = np.array([[8, 6, 3], [-4, 3, 2], [6, 6, 6]]) + G = [1, 2, 3] + H = np.ones((3, 4)) + J = H.T + K = np.array([[0]]) + L = np.array([[[1, 2], [0, 1]]]) + + # Some arrays can't be cast as spmatrices (A, C, L) so leave + # them out. + Asp = spcreator(A) + Csp = spcreator(C) + Gsp = spcreator(G) + # 2d arrays + Bsp = spcreator(B) + Dsp = spcreator(D) + Esp = spcreator(E) + Fsp = spcreator(F) + Hsp = spcreator(H) + Hspp = spcreator(H[0, None]) + Jsp = spcreator(J) + Jspp = spcreator(J[:, 0, None]) + Ksp = spcreator(K) + + matrices = [A, B, C, D, E, F, G, H, J, K, L] + spmatrices = [Asp, Bsp, Csp, Dsp, Esp, Fsp, Gsp, Hsp, Hspp, Jsp, Jspp, Ksp] + sp1dmatrices = [Asp, Csp, Gsp] + + # sparse/sparse + for i in sp1dmatrices: + for j in spmatrices: + try: + dense_mult = i.toarray() * j.toarray() + except ValueError: + with pytest.raises(ValueError, match='inconsistent shapes'): + i.multiply(j) + continue + sp_mult = i.multiply(j) + assert_allclose(sp_mult.toarray(), dense_mult) + + # sparse/dense + for i in sp1dmatrices: + for j in matrices: + try: + dense_mult = i.toarray() * j + except TypeError: + continue + except ValueError: + matchme = 'broadcast together|inconsistent shapes' + with pytest.raises(ValueError, match=matchme): + i.multiply(j) + continue + sp_mult = i.multiply(j) + assert_allclose(toarray(sp_mult), dense_mult) + + def test_elementwise_divide(self, spcreator, dat1d): + datsp = spcreator(dat1d) + expected = np.array([1, np.nan, 1, np.nan]) + actual = datsp / datsp + # need assert_array_equal to handle nan values + np.testing.assert_array_equal(actual, expected) + + denom = spcreator([1, 0, 0, 4], dtype='d') + expected = [3, np.nan, np.inf, 0] + np.testing.assert_array_equal(datsp / denom, expected) + + # complex + A = np.array([1 - 2j, 0 + 5j, -1 + 0j]) + B = np.array([5 + 2j, 7 - 3j, -2 + 1j]) + Asp = spcreator(A) + Bsp = spcreator(B) + assert_allclose(Asp / Bsp, A / B) + + # integer + A = np.array([1, 2, 3]) + B = np.array([0, 1, 2]) + Asp = spcreator(A) + Bsp = spcreator(B) + with np.errstate(divide='ignore'): + assert_equal(Asp / Bsp, A / B) + + # mismatching sparsity patterns + A = np.array([0, 1]) + B = np.array([1, 0]) + Asp = spcreator(A) + Bsp = spcreator(B) + with np.errstate(divide='ignore', invalid='ignore'): + assert_equal(Asp / Bsp, A / B) + + def test_pow(self, spcreator): + A = np.array([1, 0, 2, 0]) + B = spcreator(A) + + # unusual exponents + with pytest.raises(ValueError, match='negative integer powers'): + B**-1 + with pytest.raises(NotImplementedError, match='zero power'): + B**0 + + for exponent in [1, 2, 3, 2.2]: + ret_sp = B**exponent + ret_np = A**exponent + assert_equal(ret_sp.toarray(), ret_np) + assert_equal(ret_sp.dtype, ret_np.dtype) + + def test_dot_scalar(self, spcreator, dat1d): + A = spcreator(dat1d) + scalar = 10 + actual = A.dot(scalar) + expected = A * scalar + + assert_allclose(actual.toarray(), expected.toarray()) + + def test_matmul(self, spcreator): + Msp = spcreator([2, 0, 3.0]) + B = spcreator(np.array([[0, 1], [1, 0], [0, 2]], 'd')) + col = np.array([[1, 2, 3]]).T + + # check sparse @ dense 2d column + assert_allclose(Msp @ col, Msp.toarray() @ col) + + # check sparse1d @ sparse2d, sparse1d @ dense2d, dense1d @ sparse2d + assert_allclose((Msp @ B).toarray(), (Msp @ B).toarray()) + assert_allclose(Msp.toarray() @ B, (Msp @ B).toarray()) + assert_allclose(Msp @ B.toarray(), (Msp @ B).toarray()) + + # check sparse1d @ dense1d, sparse1d @ sparse1d + V = np.array([0, 0, 1]) + assert_allclose(Msp @ V, Msp.toarray() @ V) + + Vsp = spcreator(V) + Msp_Vsp = Msp @ Vsp + assert isinstance(Msp_Vsp, np.ndarray) + assert Msp_Vsp.shape == () + + # output is 0-dim ndarray + assert_allclose(np.array(3), Msp_Vsp) + assert_allclose(np.array(3), Msp.toarray() @ Vsp) + assert_allclose(np.array(3), Msp @ Vsp.toarray()) + assert_allclose(np.array(3), Msp.toarray() @ Vsp.toarray()) + + # check error on matrix-scalar + with pytest.raises(ValueError, match='Scalar operands are not allowed'): + Msp @ 1 + with pytest.raises(ValueError, match='Scalar operands are not allowed'): + 1 @ Msp + + def test_sub_dense(self, spcreator, datsp_math_dtypes): + # subtracting a dense matrix to/from a sparse matrix + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + if dtype == np.dtype('bool'): + # boolean array subtraction deprecated in 1.9.0 + continue + + # Manually add to avoid upcasting from scalar + # multiplication. + sum1 = (dat + dat + dat) - datsp + assert_equal(sum1, dat + dat) + sum2 = (datsp + datsp + datsp) - dat + assert_equal(sum2, dat + dat) + + def test_size_zero_matrix_arithmetic(self, spcreator): + # Test basic matrix arithmetic with shapes like 0, (1, 0), (0, 3), etc. + mat = np.array([]) + a = mat.reshape(0) + d = mat.reshape((1, 0)) + f = np.ones([5, 5]) + + asp = spcreator(a) + dsp = spcreator(d) + # bad shape for addition + with pytest.raises(ValueError, match='inconsistent shapes'): + asp.__add__(dsp) + + # matrix product. + assert_equal(asp.dot(asp), np.dot(a, a)) + + # bad matrix products + with pytest.raises(ValueError, match='dimension mismatch'): + asp.dot(f) + + # elemente-wise multiplication + assert_equal(asp.multiply(asp).toarray(), np.multiply(a, a)) + + assert_equal(asp.multiply(a).toarray(), np.multiply(a, a)) + + assert_equal(asp.multiply(6).toarray(), np.multiply(a, 6)) + + # bad element-wise multiplication + with pytest.raises(ValueError, match='inconsistent shapes'): + asp.multiply(f) + + # Addition + assert_equal(asp.__add__(asp).toarray(), a.__add__(a)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..96ca22939df371c0d11b06fb06f2920c705f4578 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py @@ -0,0 +1,561 @@ +import pytest +import numpy as np +import numpy.testing as npt +import scipy.sparse +import scipy.sparse.linalg as spla + + +sparray_types = ('bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil') + +sparray_classes = [ + getattr(scipy.sparse, f'{T}_array') for T in sparray_types +] + +A = np.array([ + [0, 1, 2, 0], + [2, 0, 0, 3], + [1, 4, 0, 0] +]) + +B = np.array([ + [0, 1], + [2, 0] +]) + +X = np.array([ + [1, 0, 0, 1], + [2, 1, 2, 0], + [0, 2, 1, 0], + [0, 0, 1, 2] +], dtype=float) + + +sparrays = [sparray(A) for sparray in sparray_classes] +square_sparrays = [sparray(B) for sparray in sparray_classes] +eig_sparrays = [sparray(X) for sparray in sparray_classes] + +parametrize_sparrays = pytest.mark.parametrize( + "A", sparrays, ids=sparray_types +) +parametrize_square_sparrays = pytest.mark.parametrize( + "B", square_sparrays, ids=sparray_types +) +parametrize_eig_sparrays = pytest.mark.parametrize( + "X", eig_sparrays, ids=sparray_types +) + + +@parametrize_sparrays +def test_sum(A): + assert not isinstance(A.sum(axis=0), np.matrix), \ + "Expected array, got matrix" + assert A.sum(axis=0).shape == (4,) + assert A.sum(axis=1).shape == (3,) + + +@parametrize_sparrays +def test_mean(A): + assert not isinstance(A.mean(axis=1), np.matrix), \ + "Expected array, got matrix" + + +@parametrize_sparrays +def test_min_max(A): + # Some formats don't support min/max operations, so we skip those here. + if hasattr(A, 'min'): + assert not isinstance(A.min(axis=1), np.matrix), \ + "Expected array, got matrix" + if hasattr(A, 'max'): + assert not isinstance(A.max(axis=1), np.matrix), \ + "Expected array, got matrix" + if hasattr(A, 'argmin'): + assert not isinstance(A.argmin(axis=1), np.matrix), \ + "Expected array, got matrix" + if hasattr(A, 'argmax'): + assert not isinstance(A.argmax(axis=1), np.matrix), \ + "Expected array, got matrix" + + +@parametrize_sparrays +def test_todense(A): + assert not isinstance(A.todense(), np.matrix), \ + "Expected array, got matrix" + + +@parametrize_sparrays +def test_indexing(A): + if A.__class__.__name__[:3] in ('dia', 'coo', 'bsr'): + return + + all_res = ( + A[1, :], + A[:, 1], + A[1, [1, 2]], + A[[1, 2], 1], + A[[0]], + A[:, [1, 2]], + A[[1, 2], :], + A[1, [[1, 2]]], + A[[[1, 2]], 1], + ) + + for res in all_res: + assert isinstance(res, scipy.sparse.sparray), \ + f"Expected sparse array, got {res._class__.__name__}" + + +@parametrize_sparrays +def test_dense_addition(A): + X = np.random.random(A.shape) + assert not isinstance(A + X, np.matrix), "Expected array, got matrix" + + +@parametrize_sparrays +def test_sparse_addition(A): + assert isinstance((A + A), scipy.sparse.sparray), "Expected array, got matrix" + + +@parametrize_sparrays +def test_elementwise_mul(A): + assert np.all((A * A).todense() == A.power(2).todense()) + + +@parametrize_sparrays +def test_elementwise_rmul(A): + with pytest.raises(TypeError): + None * A + + with pytest.raises(ValueError): + np.eye(3) * scipy.sparse.csr_array(np.arange(6).reshape(2, 3)) + + assert np.all((2 * A) == (A.todense() * 2)) + + assert np.all((A.todense() * A) == (A.todense() ** 2)) + + +@parametrize_sparrays +def test_matmul(A): + assert np.all((A @ A.T).todense() == A.dot(A.T).todense()) + + +@parametrize_sparrays +def test_power_operator(A): + assert isinstance((A**2), scipy.sparse.sparray), "Expected array, got matrix" + + # https://github.com/scipy/scipy/issues/15948 + npt.assert_equal((A**2).todense(), (A.todense())**2) + + # power of zero is all ones (dense) so helpful msg exception + with pytest.raises(NotImplementedError, match="zero power"): + A**0 + + +@parametrize_sparrays +def test_sparse_divide(A): + assert isinstance(A / A, np.ndarray) + +@parametrize_sparrays +@pytest.mark.thread_unsafe +def test_sparse_dense_divide(A): + with pytest.warns(RuntimeWarning): + assert isinstance((A / A.todense()), scipy.sparse.sparray) + +@parametrize_sparrays +def test_dense_divide(A): + assert isinstance((A / 2), scipy.sparse.sparray), "Expected array, got matrix" + + +@parametrize_sparrays +def test_no_A_attr(A): + with pytest.raises(AttributeError): + A.A + + +@parametrize_sparrays +def test_no_H_attr(A): + with pytest.raises(AttributeError): + A.H + + +@parametrize_sparrays +def test_getrow_getcol(A): + assert isinstance(A._getcol(0), scipy.sparse.sparray) + assert isinstance(A._getrow(0), scipy.sparse.sparray) + + +# -- linalg -- + +@parametrize_sparrays +def test_as_linearoperator(A): + L = spla.aslinearoperator(A) + npt.assert_allclose(L * [1, 2, 3, 4], A @ [1, 2, 3, 4]) + + +@parametrize_square_sparrays +def test_inv(B): + if B.__class__.__name__[:3] != 'csc': + return + + C = spla.inv(B) + + assert isinstance(C, scipy.sparse.sparray) + npt.assert_allclose(C.todense(), np.linalg.inv(B.todense())) + + +@parametrize_square_sparrays +def test_expm(B): + if B.__class__.__name__[:3] != 'csc': + return + + Bmat = scipy.sparse.csc_matrix(B) + + C = spla.expm(B) + + assert isinstance(C, scipy.sparse.sparray) + npt.assert_allclose( + C.todense(), + spla.expm(Bmat).todense() + ) + + +@parametrize_square_sparrays +def test_expm_multiply(B): + if B.__class__.__name__[:3] != 'csc': + return + + npt.assert_allclose( + spla.expm_multiply(B, np.array([1, 2])), + spla.expm(B) @ [1, 2] + ) + + +@parametrize_sparrays +def test_norm(A): + C = spla.norm(A) + npt.assert_allclose(C, np.linalg.norm(A.todense())) + + +@parametrize_square_sparrays +def test_onenormest(B): + C = spla.onenormest(B) + npt.assert_allclose(C, np.linalg.norm(B.todense(), 1)) + + +@parametrize_square_sparrays +def test_spsolve(B): + if B.__class__.__name__[:3] not in ('csc', 'csr'): + return + + npt.assert_allclose( + spla.spsolve(B, [1, 2]), + np.linalg.solve(B.todense(), [1, 2]) + ) + + +@pytest.mark.parametrize("fmt",["csr","csc"]) +def test_spsolve_triangular(fmt): + arr = [ + [1, 0, 0, 0], + [2, 1, 0, 0], + [3, 2, 1, 0], + [4, 3, 2, 1], + ] + if fmt == "csr": + X = scipy.sparse.csr_array(arr) + else: + X = scipy.sparse.csc_array(arr) + spla.spsolve_triangular(X, [1, 2, 3, 4]) + + +@parametrize_square_sparrays +def test_factorized(B): + if B.__class__.__name__[:3] != 'csc': + return + + LU = spla.factorized(B) + npt.assert_allclose( + LU(np.array([1, 2])), + np.linalg.solve(B.todense(), [1, 2]) + ) + + +@parametrize_square_sparrays +@pytest.mark.parametrize( + "solver", + ["bicg", "bicgstab", "cg", "cgs", "gmres", "lgmres", "minres", "qmr", + "gcrotmk", "tfqmr"] +) +def test_solvers(B, solver): + if solver == "minres": + kwargs = {} + else: + kwargs = {'atol': 1e-5} + + x, info = getattr(spla, solver)(B, np.array([1, 2]), **kwargs) + assert info >= 0 # no errors, even if perhaps did not converge fully + npt.assert_allclose(x, [1, 1], atol=1e-1) + + +@parametrize_sparrays +@pytest.mark.parametrize( + "solver", + ["lsqr", "lsmr"] +) +def test_lstsqr(A, solver): + x, *_ = getattr(spla, solver)(A, [1, 2, 3]) + npt.assert_allclose(A @ x, [1, 2, 3]) + + +@parametrize_eig_sparrays +def test_eigs(X): + e, v = spla.eigs(X, k=1) + npt.assert_allclose( + X @ v, + e[0] * v + ) + + +@parametrize_eig_sparrays +def test_eigsh(X): + X = X + X.T + e, v = spla.eigsh(X, k=1) + npt.assert_allclose( + X @ v, + e[0] * v + ) + + +@parametrize_eig_sparrays +def test_svds(X): + u, s, vh = spla.svds(X, k=3) + u2, s2, vh2 = np.linalg.svd(X.todense()) + s = np.sort(s) + s2 = np.sort(s2[:3]) + npt.assert_allclose(s, s2, atol=1e-3) + + +def test_splu(): + X = scipy.sparse.csc_array([ + [1, 0, 0, 0], + [2, 1, 0, 0], + [3, 2, 1, 0], + [4, 3, 2, 1], + ]) + LU = spla.splu(X) + npt.assert_allclose( + LU.solve(np.array([1, 2, 3, 4])), + np.asarray([1, 0, 0, 0], dtype=np.float64), + rtol=1e-14, atol=3e-16 + ) + + +def test_spilu(): + X = scipy.sparse.csc_array([ + [1, 0, 0, 0], + [2, 1, 0, 0], + [3, 2, 1, 0], + [4, 3, 2, 1], + ]) + LU = spla.spilu(X) + npt.assert_allclose( + LU.solve(np.array([1, 2, 3, 4])), + np.asarray([1, 0, 0, 0], dtype=np.float64), + rtol=1e-14, atol=3e-16 + ) + + +@pytest.mark.parametrize( + "cls,indices_attrs", + [ + ( + scipy.sparse.csr_array, + ["indices", "indptr"], + ), + ( + scipy.sparse.csc_array, + ["indices", "indptr"], + ), + ( + scipy.sparse.coo_array, + ["row", "col"], + ), + ] +) +@pytest.mark.parametrize("expected_dtype", [np.int64, np.int32]) +def test_index_dtype_compressed(cls, indices_attrs, expected_dtype): + input_array = scipy.sparse.coo_array(np.arange(9).reshape(3, 3)) + coo_tuple = ( + input_array.data, + ( + input_array.row.astype(expected_dtype), + input_array.col.astype(expected_dtype), + ) + ) + + result = cls(coo_tuple) + for attr in indices_attrs: + assert getattr(result, attr).dtype == expected_dtype + + result = cls(coo_tuple, shape=(3, 3)) + for attr in indices_attrs: + assert getattr(result, attr).dtype == expected_dtype + + if issubclass(cls, scipy.sparse._compressed._cs_matrix): + input_array_csr = input_array.tocsr() + csr_tuple = ( + input_array_csr.data, + input_array_csr.indices.astype(expected_dtype), + input_array_csr.indptr.astype(expected_dtype), + ) + + result = cls(csr_tuple) + for attr in indices_attrs: + assert getattr(result, attr).dtype == expected_dtype + + result = cls(csr_tuple, shape=(3, 3)) + for attr in indices_attrs: + assert getattr(result, attr).dtype == expected_dtype + + +def test_default_is_matrix_diags(): + m = scipy.sparse.diags([0, 1, 2]) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_eye(): + m = scipy.sparse.eye(3) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_spdiags(): + m = scipy.sparse.spdiags([1, 2, 3], 0, 3, 3) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_identity(): + m = scipy.sparse.identity(3) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_kron_dense(): + m = scipy.sparse.kron( + np.array([[1, 2], [3, 4]]), np.array([[4, 3], [2, 1]]) + ) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_kron_sparse(): + m = scipy.sparse.kron( + np.array([[1, 2], [3, 4]]), np.array([[1, 0], [0, 0]]) + ) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_kronsum(): + m = scipy.sparse.kronsum( + np.array([[1, 0], [0, 1]]), np.array([[0, 1], [1, 0]]) + ) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_random(): + m = scipy.sparse.random(3, 3) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_default_is_matrix_rand(): + m = scipy.sparse.rand(3, 3) + assert not isinstance(m, scipy.sparse.sparray) + + +@pytest.mark.parametrize("fn", (scipy.sparse.hstack, scipy.sparse.vstack)) +def test_default_is_matrix_stacks(fn): + """Same idea as `test_default_construction_fn_matrices`, but for the + stacking creation functions.""" + A = scipy.sparse.coo_matrix(np.eye(2)) + B = scipy.sparse.coo_matrix([[0, 1], [1, 0]]) + m = fn([A, B]) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_blocks_default_construction_fn_matrices(): + """Same idea as `test_default_construction_fn_matrices`, but for the block + creation function""" + A = scipy.sparse.coo_matrix(np.eye(2)) + B = scipy.sparse.coo_matrix([[2], [0]]) + C = scipy.sparse.coo_matrix([[3]]) + + # block diag + m = scipy.sparse.block_diag((A, B, C)) + assert not isinstance(m, scipy.sparse.sparray) + + # bmat + m = scipy.sparse.bmat([[A, None], [None, C]]) + assert not isinstance(m, scipy.sparse.sparray) + + +def test_format_property(): + for fmt in sparray_types: + arr_cls = getattr(scipy.sparse, f"{fmt}_array") + M = arr_cls([[1, 2]]) + assert M.format == fmt + assert M._format == fmt + with pytest.raises(AttributeError): + M.format = "qqq" + + +def test_issparse(): + m = scipy.sparse.eye(3) + a = scipy.sparse.csr_array(m) + assert not isinstance(m, scipy.sparse.sparray) + assert isinstance(a, scipy.sparse.sparray) + + # Both sparse arrays and sparse matrices should be sparse + assert scipy.sparse.issparse(a) + assert scipy.sparse.issparse(m) + + # ndarray and array_likes are not sparse + assert not scipy.sparse.issparse(a.todense()) + assert not scipy.sparse.issparse(m.todense()) + + +def test_isspmatrix(): + m = scipy.sparse.eye(3) + a = scipy.sparse.csr_array(m) + assert not isinstance(m, scipy.sparse.sparray) + assert isinstance(a, scipy.sparse.sparray) + + # Should only be true for sparse matrices, not sparse arrays + assert not scipy.sparse.isspmatrix(a) + assert scipy.sparse.isspmatrix(m) + + # ndarray and array_likes are not sparse + assert not scipy.sparse.isspmatrix(a.todense()) + assert not scipy.sparse.isspmatrix(m.todense()) + + +@pytest.mark.parametrize( + ("fmt", "fn"), + ( + ("bsr", scipy.sparse.isspmatrix_bsr), + ("coo", scipy.sparse.isspmatrix_coo), + ("csc", scipy.sparse.isspmatrix_csc), + ("csr", scipy.sparse.isspmatrix_csr), + ("dia", scipy.sparse.isspmatrix_dia), + ("dok", scipy.sparse.isspmatrix_dok), + ("lil", scipy.sparse.isspmatrix_lil), + ), +) +def test_isspmatrix_format(fmt, fn): + m = scipy.sparse.eye(3, format=fmt) + a = scipy.sparse.csr_array(m).asformat(fmt) + assert not isinstance(m, scipy.sparse.sparray) + assert isinstance(a, scipy.sparse.sparray) + + # Should only be true for sparse matrices, not sparse arrays + assert not fn(a) + assert fn(m) + + # ndarray and array_likes are not sparse + assert not fn(a.todense()) + assert not fn(m.todense()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5f7ead8b134dc2e09bb0cef8441cb2b75a5aee8b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py @@ -0,0 +1,5695 @@ +# +# Authors: Travis Oliphant, Ed Schofield, Robert Cimrman, Nathan Bell, and others + +""" Test functions for sparse matrices. Each class in the "Matrix class +based tests" section become subclasses of the classes in the "Generic +tests" section. This is done by the functions in the "Tailored base +class for generic tests" section. + +""" + + +import contextlib +import functools +import operator +import platform +import itertools +import sys + +import pytest +from pytest import raises as assert_raises + +import numpy as np +from numpy import (arange, zeros, array, dot, asarray, + vstack, ndarray, transpose, diag, kron, inf, conjugate, + int8) + +import random +from numpy.testing import (assert_equal, assert_array_equal, + assert_array_almost_equal, assert_almost_equal, assert_, + assert_allclose, suppress_warnings) + +import scipy.linalg + +import scipy.sparse as sparse +from scipy.sparse import (csc_matrix, csr_matrix, dok_matrix, + coo_matrix, lil_matrix, dia_matrix, bsr_matrix, + csc_array, csr_array, dok_array, + coo_array, lil_array, dia_array, bsr_array, + eye, issparse, SparseEfficiencyWarning, sparray) +from scipy.sparse._base import _formats +from scipy.sparse._sputils import (supported_dtypes, isscalarlike, + get_index_dtype, asmatrix, matrix) +from scipy.sparse.linalg import splu, expm, inv + +from scipy._lib.decorator import decorator +from scipy._lib._util import ComplexWarning + +IS_COLAB = ('google.colab' in sys.modules) + + +def assert_in(member, collection, msg=None): + message = msg if msg is not None else f"{member!r} not found in {collection!r}" + assert_(member in collection, msg=message) + + +def assert_array_equal_dtype(x, y, **kwargs): + assert_(x.dtype == y.dtype) + assert_array_equal(x, y, **kwargs) + + +NON_ARRAY_BACKED_FORMATS = frozenset(['dok']) + +def sparse_may_share_memory(A, B): + # Checks if A and B have any numpy array sharing memory. + + def _underlying_arrays(x): + # Given any object (e.g. a sparse array), returns all numpy arrays + # stored in any attribute. + + arrays = [] + for a in x.__dict__.values(): + if isinstance(a, np.ndarray | np.generic): + arrays.append(a) + return arrays + + for a in _underlying_arrays(A): + for b in _underlying_arrays(B): + if np.may_share_memory(a, b): + return True + return False + + +sup_complex = suppress_warnings() +sup_complex.filter(ComplexWarning) + + +def with_64bit_maxval_limit(maxval_limit=None, random=False, fixed_dtype=None, + downcast_maxval=None, assert_32bit=False): + """ + Monkeypatch the maxval threshold at which scipy.sparse switches to + 64-bit index arrays, or make it (pseudo-)random. + + """ + if maxval_limit is None: + maxval_limit = np.int64(10) + else: + # Ensure we use numpy scalars rather than Python scalars (matters for + # NEP 50 casting rule changes) + maxval_limit = np.int64(maxval_limit) + + if assert_32bit: + def new_get_index_dtype(arrays=(), maxval=None, check_contents=False): + tp = get_index_dtype(arrays, maxval, check_contents) + assert_equal(np.iinfo(tp).max, np.iinfo(np.int32).max) + assert_(tp == np.int32 or tp == np.intc) + return tp + elif fixed_dtype is not None: + def new_get_index_dtype(arrays=(), maxval=None, check_contents=False): + return fixed_dtype + elif random: + counter = np.random.RandomState(seed=1234) + + def new_get_index_dtype(arrays=(), maxval=None, check_contents=False): + return (np.int32, np.int64)[counter.randint(2)] + else: + def new_get_index_dtype(arrays=(), maxval=None, check_contents=False): + dtype = np.int32 + if maxval is not None: + if maxval > maxval_limit: + dtype = np.int64 + for arr in arrays: + arr = np.asarray(arr) + if arr.dtype > np.int32: + if check_contents: + if arr.size == 0: + # a bigger type not needed + continue + elif np.issubdtype(arr.dtype, np.integer): + maxval = arr.max() + minval = arr.min() + if minval >= -maxval_limit and maxval <= maxval_limit: + # a bigger type not needed + continue + dtype = np.int64 + return dtype + + if downcast_maxval is not None: + def new_downcast_intp_index(arr): + if arr.max() > downcast_maxval: + raise AssertionError("downcast limited") + return arr.astype(np.intp) + + @decorator + def deco(func, *a, **kw): + backup = [] + modules = [scipy.sparse._bsr, scipy.sparse._coo, scipy.sparse._csc, + scipy.sparse._csr, scipy.sparse._dia, scipy.sparse._dok, + scipy.sparse._lil, scipy.sparse._sputils, + scipy.sparse._compressed, scipy.sparse._construct] + try: + for mod in modules: + backup.append((mod, 'get_index_dtype', + getattr(mod, 'get_index_dtype', None))) + setattr(mod, 'get_index_dtype', new_get_index_dtype) + if downcast_maxval is not None: + backup.append((mod, 'downcast_intp_index', + getattr(mod, 'downcast_intp_index', None))) + setattr(mod, 'downcast_intp_index', new_downcast_intp_index) + return func(*a, **kw) + finally: + for mod, name, oldfunc in backup: + if oldfunc is not None: + setattr(mod, name, oldfunc) + + return deco + + +def toarray(a): + if isinstance(a, np.ndarray) or isscalarlike(a): + return a + return a.toarray() + + +class BinopTester: + # Custom type to test binary operations on sparse matrices. + + def __add__(self, mat): + return "matrix on the right" + + def __mul__(self, mat): + return "matrix on the right" + + def __sub__(self, mat): + return "matrix on the right" + + def __radd__(self, mat): + return "matrix on the left" + + def __rmul__(self, mat): + return "matrix on the left" + + def __rsub__(self, mat): + return "matrix on the left" + + def __matmul__(self, mat): + return "matrix on the right" + + def __rmatmul__(self, mat): + return "matrix on the left" + +class BinopTester_with_shape: + # Custom type to test binary operations on sparse matrices + # with object which has shape attribute. + def __init__(self,shape): + self._shape = shape + + def shape(self): + return self._shape + + def ndim(self): + return len(self._shape) + + def __add__(self, mat): + return "matrix on the right" + + def __mul__(self, mat): + return "matrix on the right" + + def __sub__(self, mat): + return "matrix on the right" + + def __radd__(self, mat): + return "matrix on the left" + + def __rmul__(self, mat): + return "matrix on the left" + + def __rsub__(self, mat): + return "matrix on the left" + + def __matmul__(self, mat): + return "matrix on the right" + + def __rmatmul__(self, mat): + return "matrix on the left" + +class ComparisonTester: + # Custom type to test comparison operations on sparse matrices. + def __eq__(self, other): + return "eq" + + def __ne__(self, other): + return "ne" + + def __lt__(self, other): + return "lt" + + def __le__(self, other): + return "le" + + def __gt__(self, other): + return "gt" + + def __ge__(self, other): + return "ge" + + +#------------------------------------------------------------------------------ +# Generic tests +#------------------------------------------------------------------------------ + + +class _MatrixMixin: + """mixin to easily allow tests of both sparray and spmatrix""" + bsr_container = bsr_matrix + coo_container = coo_matrix + csc_container = csc_matrix + csr_container = csr_matrix + dia_container = dia_matrix + dok_container = dok_matrix + lil_container = lil_matrix + asdense = staticmethod(asmatrix) + + def test_getrow(self): + assert_array_equal(self.datsp.getrow(1).toarray(), self.dat[[1], :]) + assert_array_equal(self.datsp.getrow(-1).toarray(), self.dat[[-1], :]) + + def test_getcol(self): + assert_array_equal(self.datsp.getcol(1).toarray(), self.dat[:, [1]]) + assert_array_equal(self.datsp.getcol(-1).toarray(), self.dat[:, [-1]]) + + def test_asfptype(self): + A = self.spcreator(arange(6,dtype='int32').reshape(2,3)) + + assert_equal(A.asfptype().dtype, np.dtype('float64')) + assert_equal(A.asfptype().format, A.format) + assert_equal(A.astype('int16').asfptype().dtype, np.dtype('float32')) + assert_equal(A.astype('complex128').asfptype().dtype, np.dtype('complex128')) + + B = A.asfptype() + C = B.asfptype() + assert_(B is C) + + +# TODO test prune +# TODO test has_sorted_indices +class _TestCommon: + """test common functionality shared by all sparse formats""" + math_dtypes = supported_dtypes + + bsr_container = bsr_array + coo_container = coo_array + csc_container = csc_array + csr_container = csr_array + dia_container = dia_array + dok_container = dok_array + lil_container = lil_array + asdense = array + + @classmethod + def init_class(cls): + # Canonical data. + cls.dat = array([[1, 0, 0, 2], [3, 0, 1, 0], [0, 2, 0, 0]], 'd') + cls.datsp = cls.spcreator(cls.dat) + + # Some sparse and dense matrices with data for every supported dtype. + # This set union is a workaround for numpy#6295, which means that + # two np.int64 dtypes don't hash to the same value. + cls.checked_dtypes = set(supported_dtypes).union(cls.math_dtypes) + cls.dat_dtypes = {} + cls.datsp_dtypes = {} + for dtype in cls.checked_dtypes: + cls.dat_dtypes[dtype] = cls.dat.astype(dtype) + cls.datsp_dtypes[dtype] = cls.spcreator(cls.dat.astype(dtype)) + + # Check that the original data is equivalent to the + # corresponding dat_dtypes & datsp_dtypes. + assert_equal(cls.dat, cls.dat_dtypes[np.float64]) + assert_equal(cls.datsp.toarray(), + cls.datsp_dtypes[np.float64].toarray()) + + cls.is_array_test = isinstance(cls.datsp, sparray) + + def test_bool(self): + def check(dtype): + datsp = self.datsp_dtypes[dtype] + + assert_raises(ValueError, bool, datsp) + assert_(self.spcreator([[1]])) + assert_(not self.spcreator([[0]])) + + if isinstance(self, TestDOK): + pytest.skip("Cannot create a rank <= 2 DOK matrix.") + for dtype in self.checked_dtypes: + check(dtype) + + def test_bool_rollover(self): + # bool's underlying dtype is 1 byte, check that it does not + # rollover True -> False at 256. + dat = array([[True, False]]) + datsp = self.spcreator(dat) + + for _ in range(10): + datsp = datsp + datsp + dat = dat + dat + assert_array_equal(dat, datsp.toarray()) + + def test_eq(self): + sup = suppress_warnings() + sup.filter(SparseEfficiencyWarning) + + @sup + @sup_complex + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + datbsr = self.bsr_container(dat) + datcsr = self.csr_container(dat) + datcsc = self.csc_container(dat) + datlil = self.lil_container(dat) + + # sparse/sparse + assert_array_equal_dtype(dat == dat2, (datsp == datsp2).toarray()) + # mix sparse types + assert_array_equal_dtype(dat == dat2, (datbsr == datsp2).toarray()) + assert_array_equal_dtype(dat == dat2, (datcsr == datsp2).toarray()) + assert_array_equal_dtype(dat == dat2, (datcsc == datsp2).toarray()) + assert_array_equal_dtype(dat == dat2, (datlil == datsp2).toarray()) + # sparse/dense + assert_array_equal_dtype(dat == datsp2, datsp2 == dat) + # sparse/scalar + assert_array_equal_dtype(dat == 0, (datsp == 0).toarray()) + assert_array_equal_dtype(dat == 1, (datsp == 1).toarray()) + assert_array_equal_dtype(dat == np.nan, + (datsp == np.nan).toarray()) + + if self.datsp.format not in ['bsr', 'csc', 'csr']: + pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.") + for dtype in self.checked_dtypes: + check(dtype) + + def test_ne(self): + sup = suppress_warnings() + sup.filter(SparseEfficiencyWarning) + + @sup + @sup_complex + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + datbsr = self.bsr_container(dat) + datcsc = self.csc_container(dat) + datcsr = self.csr_container(dat) + datlil = self.lil_container(dat) + + # sparse/sparse + assert_array_equal_dtype(dat != dat2, (datsp != datsp2).toarray()) + # mix sparse types + assert_array_equal_dtype(dat != dat2, (datbsr != datsp2).toarray()) + assert_array_equal_dtype(dat != dat2, (datcsc != datsp2).toarray()) + assert_array_equal_dtype(dat != dat2, (datcsr != datsp2).toarray()) + assert_array_equal_dtype(dat != dat2, (datlil != datsp2).toarray()) + # sparse/dense + assert_array_equal_dtype(dat != datsp2, datsp2 != dat) + # sparse/scalar + assert_array_equal_dtype(dat != 0, (datsp != 0).toarray()) + assert_array_equal_dtype(dat != 1, (datsp != 1).toarray()) + assert_array_equal_dtype(0 != dat, (0 != datsp).toarray()) + assert_array_equal_dtype(1 != dat, (1 != datsp).toarray()) + assert_array_equal_dtype(dat != np.nan, + (datsp != np.nan).toarray()) + + if self.datsp.format not in ['bsr', 'csc', 'csr']: + pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.") + for dtype in self.checked_dtypes: + check(dtype) + + def test_lt(self): + sup = suppress_warnings() + sup.filter(SparseEfficiencyWarning) + + @sup + @sup_complex + def check(dtype): + # data + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + datcomplex = dat.astype(complex) + datcomplex[:,0] = 1 + 1j + datspcomplex = self.spcreator(datcomplex) + datbsr = self.bsr_container(dat) + datcsc = self.csc_container(dat) + datcsr = self.csr_container(dat) + datlil = self.lil_container(dat) + + # sparse/sparse + assert_array_equal_dtype(dat < dat2, (datsp < datsp2).toarray()) + assert_array_equal_dtype(datcomplex < dat2, + (datspcomplex < datsp2).toarray()) + # mix sparse types + assert_array_equal_dtype(dat < dat2, (datbsr < datsp2).toarray()) + assert_array_equal_dtype(dat < dat2, (datcsc < datsp2).toarray()) + assert_array_equal_dtype(dat < dat2, (datcsr < datsp2).toarray()) + assert_array_equal_dtype(dat < dat2, (datlil < datsp2).toarray()) + + assert_array_equal_dtype(dat2 < dat, (datsp2 < datbsr).toarray()) + assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsc).toarray()) + assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsr).toarray()) + assert_array_equal_dtype(dat2 < dat, (datsp2 < datlil).toarray()) + # sparse/dense + assert_array_equal_dtype(dat < dat2, datsp < dat2) + assert_array_equal_dtype(datcomplex < dat2, datspcomplex < dat2) + # sparse/scalar + for val in [2, 1, 0, -1, -2]: + val = np.int64(val) # avoid Python scalar (due to NEP 50 changes) + assert_array_equal_dtype((datsp < val).toarray(), dat < val) + assert_array_equal_dtype((val < datsp).toarray(), val < dat) + + with np.errstate(invalid='ignore'): + assert_array_equal_dtype((datsp < np.nan).toarray(), + dat < np.nan) + + # data + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + + # dense rhs + assert_array_equal_dtype(dat < datsp2, datsp < dat2) + + if self.datsp.format not in ['bsr', 'csc', 'csr']: + pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.") + for dtype in self.checked_dtypes: + check(dtype) + + def test_gt(self): + sup = suppress_warnings() + sup.filter(SparseEfficiencyWarning) + + @sup + @sup_complex + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + datcomplex = dat.astype(complex) + datcomplex[:,0] = 1 + 1j + datspcomplex = self.spcreator(datcomplex) + datbsr = self.bsr_container(dat) + datcsc = self.csc_container(dat) + datcsr = self.csr_container(dat) + datlil = self.lil_container(dat) + + # sparse/sparse + assert_array_equal_dtype(dat > dat2, (datsp > datsp2).toarray()) + assert_array_equal_dtype(datcomplex > dat2, + (datspcomplex > datsp2).toarray()) + # mix sparse types + assert_array_equal_dtype(dat > dat2, (datbsr > datsp2).toarray()) + assert_array_equal_dtype(dat > dat2, (datcsc > datsp2).toarray()) + assert_array_equal_dtype(dat > dat2, (datcsr > datsp2).toarray()) + assert_array_equal_dtype(dat > dat2, (datlil > datsp2).toarray()) + + assert_array_equal_dtype(dat2 > dat, (datsp2 > datbsr).toarray()) + assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsc).toarray()) + assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsr).toarray()) + assert_array_equal_dtype(dat2 > dat, (datsp2 > datlil).toarray()) + # sparse/dense + assert_array_equal_dtype(dat > dat2, datsp > dat2) + assert_array_equal_dtype(datcomplex > dat2, datspcomplex > dat2) + # sparse/scalar + for val in [2, 1, 0, -1, -2]: + val = np.int64(val) # avoid Python scalar (due to NEP 50 changes) + assert_array_equal_dtype((datsp > val).toarray(), dat > val) + assert_array_equal_dtype((val > datsp).toarray(), val > dat) + + with np.errstate(invalid='ignore'): + assert_array_equal_dtype((datsp > np.nan).toarray(), + dat > np.nan) + + # data + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + + # dense rhs + assert_array_equal_dtype(dat > datsp2, datsp > dat2) + + if self.datsp.format not in ['bsr', 'csc', 'csr']: + pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.") + for dtype in self.checked_dtypes: + check(dtype) + + def test_le(self): + sup = suppress_warnings() + sup.filter(SparseEfficiencyWarning) + + @sup + @sup_complex + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + datcomplex = dat.astype(complex) + datcomplex[:,0] = 1 + 1j + datspcomplex = self.spcreator(datcomplex) + datbsr = self.bsr_container(dat) + datcsc = self.csc_container(dat) + datcsr = self.csr_container(dat) + datlil = self.lil_container(dat) + + # sparse/sparse + assert_array_equal_dtype(dat <= dat2, (datsp <= datsp2).toarray()) + assert_array_equal_dtype(datcomplex <= dat2, + (datspcomplex <= datsp2).toarray()) + # mix sparse types + assert_array_equal_dtype((datbsr <= datsp2).toarray(), dat <= dat2) + assert_array_equal_dtype((datcsc <= datsp2).toarray(), dat <= dat2) + assert_array_equal_dtype((datcsr <= datsp2).toarray(), dat <= dat2) + assert_array_equal_dtype((datlil <= datsp2).toarray(), dat <= dat2) + + assert_array_equal_dtype((datsp2 <= datbsr).toarray(), dat2 <= dat) + assert_array_equal_dtype((datsp2 <= datcsc).toarray(), dat2 <= dat) + assert_array_equal_dtype((datsp2 <= datcsr).toarray(), dat2 <= dat) + assert_array_equal_dtype((datsp2 <= datlil).toarray(), dat2 <= dat) + # sparse/dense + assert_array_equal_dtype(datsp <= dat2, dat <= dat2) + assert_array_equal_dtype(datspcomplex <= dat2, datcomplex <= dat2) + # sparse/scalar + for val in [2, 1, -1, -2]: + val = np.int64(val) # avoid Python scalar (due to NEP 50 changes) + assert_array_equal_dtype((datsp <= val).toarray(), dat <= val) + assert_array_equal_dtype((val <= datsp).toarray(), val <= dat) + + # data + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + + # dense rhs + assert_array_equal_dtype(dat <= datsp2, datsp <= dat2) + + if self.datsp.format not in ['bsr', 'csc', 'csr']: + pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.") + for dtype in self.checked_dtypes: + check(dtype) + + def test_ge(self): + sup = suppress_warnings() + sup.filter(SparseEfficiencyWarning) + + @sup + @sup_complex + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + datcomplex = dat.astype(complex) + datcomplex[:,0] = 1 + 1j + datspcomplex = self.spcreator(datcomplex) + datbsr = self.bsr_container(dat) + datcsc = self.csc_container(dat) + datcsr = self.csr_container(dat) + datlil = self.lil_container(dat) + + # sparse/sparse + assert_array_equal_dtype(dat >= dat2, (datsp >= datsp2).toarray()) + assert_array_equal_dtype(datcomplex >= dat2, + (datspcomplex >= datsp2).toarray()) + # mix sparse types + assert_array_equal_dtype((datbsr >= datsp2).toarray(), dat >= dat2) + assert_array_equal_dtype((datcsc >= datsp2).toarray(), dat >= dat2) + assert_array_equal_dtype((datcsr >= datsp2).toarray(), dat >= dat2) + assert_array_equal_dtype((datlil >= datsp2).toarray(), dat >= dat2) + + assert_array_equal_dtype((datsp2 >= datbsr).toarray(), dat2 >= dat) + assert_array_equal_dtype((datsp2 >= datcsc).toarray(), dat2 >= dat) + assert_array_equal_dtype((datsp2 >= datcsr).toarray(), dat2 >= dat) + assert_array_equal_dtype((datsp2 >= datlil).toarray(), dat2 >= dat) + # sparse/dense + assert_array_equal_dtype(datsp >= dat2, dat >= dat2) + assert_array_equal_dtype(datspcomplex >= dat2, datcomplex >= dat2) + # sparse/scalar + for val in [2, 1, -1, -2]: + val = np.int64(val) # avoid Python scalar (due to NEP 50 changes) + assert_array_equal_dtype((datsp >= val).toarray(), dat >= val) + assert_array_equal_dtype((val >= datsp).toarray(), val >= dat) + + # dense data + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + dat2 = dat.copy() + dat2[:,0] = 0 + datsp2 = self.spcreator(dat2) + + # dense rhs + assert_array_equal_dtype(dat >= datsp2, datsp >= dat2) + + if self.datsp.format not in ['bsr', 'csc', 'csr']: + pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.") + for dtype in self.checked_dtypes: + check(dtype) + + def test_empty(self): + # create empty matrices + assert_equal(self.spcreator((3, 3)).toarray(), zeros((3, 3))) + assert_equal(self.spcreator((3, 3)).nnz, 0) + assert_equal(self.spcreator((3, 3)).count_nonzero(), 0) + if self.datsp.format in ["coo", "csr", "csc", "lil"]: + assert_equal(self.spcreator((3, 3)).count_nonzero(axis=0), array([0, 0, 0])) + + def test_count_nonzero(self): + axis_support = self.datsp.format in ["coo", "csr", "csc", "lil"] + axes = [None, 0, 1, -1, -2] if axis_support else [None] + + for A in (self.datsp, self.datsp.T): + for ax in axes: + expected = np.count_nonzero(A.toarray(), axis=ax) + assert_equal(A.count_nonzero(axis=ax), expected) + + if not axis_support: + with assert_raises(NotImplementedError, match="not implemented .* format"): + self.datsp.count_nonzero(axis=0) + + def test_invalid_shapes(self): + assert_raises(ValueError, self.spcreator, (-1,3)) + assert_raises(ValueError, self.spcreator, (3,-1)) + assert_raises(ValueError, self.spcreator, (-1,-1)) + + def test_repr(self): + datsp = self.spcreator([[1, 0, 0], [0, 0, 0], [0, 0, -2]]) + extra = ( + "(1 diagonals) " if datsp.format == "dia" + else "(blocksize=1x1) " if datsp.format == "bsr" + else "" + ) + _, fmt = _formats[datsp.format] + sparse_cls = "array" if self.is_array_test else "matrix" + expected = ( + f"<{fmt} sparse {sparse_cls} of dtype '{datsp.dtype}'\n" + f"\twith {datsp.nnz} stored elements {extra}and shape {datsp.shape}>" + ) + assert repr(datsp) == expected + + def test_str_maxprint(self): + datsp = self.spcreator(np.arange(75).reshape(5, 15)) + assert datsp.maxprint == 50 + assert len(str(datsp).split('\n')) == 51 + 3 + + dat = np.arange(15).reshape(5,3) + datsp = self.spcreator(dat) + # format dia reports nnz=15, but we want 14 + nnz_small = 14 if datsp.format == 'dia' else datsp.nnz + datsp_mp6 = self.spcreator(dat, maxprint=6) + + assert len(str(datsp).split('\n')) == nnz_small + 3 + assert len(str(datsp_mp6).split('\n')) == 6 + 4 + + # Check parameter `maxprint` is keyword only + datsp = self.spcreator(dat, shape=(5, 3), dtype='i', copy=False, maxprint=4) + datsp = self.spcreator(dat, (5, 3), 'i', False, maxprint=4) + with pytest.raises(TypeError, match="positional argument|unpack non-iterable"): + self.spcreator(dat, (5, 3), 'i', False, 4) + + def test_str(self): + datsp = self.spcreator([[1, 0, 0], [0, 0, 0], [0, 0, -2]]) + if datsp.nnz != 2: + return + extra = ( + "(1 diagonals) " if datsp.format == "dia" + else "(blocksize=1x1) " if datsp.format == "bsr" + else "" + ) + _, fmt = _formats[datsp.format] + sparse_cls = "array" if self.is_array_test else "matrix" + expected = ( + f"<{fmt} sparse {sparse_cls} of dtype '{datsp.dtype}'\n" + f"\twith {datsp.nnz} stored elements {extra}and shape {datsp.shape}>" + "\n Coords\tValues" + "\n (0, 0)\t1" + "\n (2, 2)\t-2" + ) + assert str(datsp) == expected + + def test_empty_arithmetic(self): + # Test manipulating empty matrices. Fails in SciPy SVN <= r1768 + shape = (5, 5) + for mytype in [np.dtype('int32'), np.dtype('float32'), + np.dtype('float64'), np.dtype('complex64'), + np.dtype('complex128')]: + a = self.spcreator(shape, dtype=mytype) + b = a + a + c = 2 * a + d = a @ a.tocsc() + e = a @ a.tocsr() + f = a @ a.tocoo() + for m in [a,b,c,d,e,f]: + assert_equal(m.toarray(), a.toarray()@a.toarray()) + # These fail in all revisions <= r1768: + assert_equal(m.dtype,mytype) + assert_equal(m.toarray().dtype,mytype) + + def test_abs(self): + A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd') + assert_equal(abs(A), abs(self.spcreator(A)).toarray()) + + def test_round(self): + decimal = 1 + A = array([[-1.35, 0.56], [17.25, -5.98]], 'd') + assert_equal(np.around(A, decimals=decimal), + round(self.spcreator(A), ndigits=decimal).toarray()) + + def test_elementwise_power(self): + A = array([[-4, -3, -2], [-1, 0, 1], [2, 3, 4]], 'd') + assert_equal(np.power(A, 2), self.spcreator(A).power(2).toarray()) + + #it's element-wise power function, input has to be a scalar + assert_raises(NotImplementedError, self.spcreator(A).power, A) + + def test_neg(self): + A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd') + assert_equal(-A, (-self.spcreator(A)).toarray()) + + # see gh-5843 + A = array([[True, False, False], [False, False, True]]) + assert_raises(NotImplementedError, self.spcreator(A).__neg__) + + def test_real(self): + D = array([[1 + 3j, 2 - 4j]]) + A = self.spcreator(D) + assert_equal(A.real.toarray(), D.real) + + def test_imag(self): + D = array([[1 + 3j, 2 - 4j]]) + A = self.spcreator(D) + assert_equal(A.imag.toarray(), D.imag) + + def test_diagonal(self): + # Does the matrix's .diagonal() method work? + mats = [] + mats.append([[1,0,2]]) + mats.append([[1],[0],[2]]) + mats.append([[0,1],[0,2],[0,3]]) + mats.append([[0,0,1],[0,0,2],[0,3,0]]) + mats.append([[1,0],[0,0]]) + + mats.append(kron(mats[0],[[1,2]])) + mats.append(kron(mats[0],[[1],[2]])) + mats.append(kron(mats[1],[[1,2],[3,4]])) + mats.append(kron(mats[2],[[1,2],[3,4]])) + mats.append(kron(mats[3],[[1,2],[3,4]])) + mats.append(kron(mats[3],[[1,2,3,4]])) + + for m in mats: + rows, cols = array(m).shape + sparse_mat = self.spcreator(m) + for k in range(-rows-1, cols+2): + assert_equal(sparse_mat.diagonal(k=k), diag(m, k=k)) + # Test for k beyond boundaries(issue #11949) + assert_equal(sparse_mat.diagonal(k=10), diag(m, k=10)) + assert_equal(sparse_mat.diagonal(k=-99), diag(m, k=-99)) + + # Test all-zero matrix. + assert_equal(self.spcreator((40, 16130)).diagonal(), np.zeros(40)) + # Test empty matrix + # https://github.com/scipy/scipy/issues/11949 + assert_equal(self.spcreator((0, 0)).diagonal(), np.empty(0)) + assert_equal(self.spcreator((15, 0)).diagonal(), np.empty(0)) + assert_equal(self.spcreator((0, 5)).diagonal(10), np.empty(0)) + + def test_trace(self): + # For square matrix + A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + B = self.spcreator(A) + for k in range(-2, 3): + assert_equal(A.trace(offset=k), B.trace(offset=k)) + + # For rectangular matrix + A = np.array([[1, 2, 3], [4, 5, 6]]) + B = self.spcreator(A) + for k in range(-1, 3): + assert_equal(A.trace(offset=k), B.trace(offset=k)) + + def test_reshape(self): + x = self.spcreator([[1, 0, 7], [0, 0, 0], [0, 3, 0], [0, 0, 5]]) + for order in ['C', 'F']: + for s in [(12, 1), (1, 12)]: + assert_array_equal(x.reshape(s, order=order).toarray(), + x.toarray().reshape(s, order=order)) + + # This example is taken from the stackoverflow answer at + # https://stackoverflow.com/q/16511879 + x = self.spcreator([[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]]) + y = x.reshape((2, 6)) # Default order is 'C' + desired = [[0, 10, 0, 0, 0, 0], [0, 0, 0, 20, 30, 40]] + assert_array_equal(y.toarray(), desired) + + # Reshape with negative indexes + y = x.reshape((2, -1)) + assert_array_equal(y.toarray(), desired) + y = x.reshape((-1, 6)) + assert_array_equal(y.toarray(), desired) + assert_raises(ValueError, x.reshape, (-1, -1)) + + # Reshape with star args + y = x.reshape(2, 6) + assert_array_equal(y.toarray(), desired) + assert_raises(TypeError, x.reshape, 2, 6, not_an_arg=1) + + # Reshape with same size is noop unless copy=True + y = x.reshape((3, 4)) + assert_(y is x) + y = x.reshape((3, 4), copy=True) + assert_(y is not x) + + # Ensure reshape did not alter original size + assert_array_equal(x.shape, (3, 4)) + + if self.is_array_test: + with assert_raises(AttributeError, match="has no setter|n't set attribute"): + x.shape = (2, 6) + else: # spmatrix test + # Reshape in place + x.shape = (2, 6) + assert_array_equal(x.toarray(), desired) + + # Reshape to bad ndim + assert_raises(ValueError, x.reshape, (x.size,)) + assert_raises(ValueError, x.reshape, (1, x.size, 1)) + + @pytest.mark.slow + def test_setdiag_comprehensive(self): + def dense_setdiag(a, v, k): + v = np.asarray(v) + if k >= 0: + n = min(a.shape[0], a.shape[1] - k) + if v.ndim != 0: + n = min(n, len(v)) + v = v[:n] + i = np.arange(0, n) + j = np.arange(k, k + n) + a[i,j] = v + elif k < 0: + dense_setdiag(a.T, v, -k) + + def check_setdiag(a, b, k): + # Check setting diagonal using a scalar, a vector of + # correct length, and too short or too long vectors + for r in [-1, len(np.diag(a, k)), 2, 30]: + if r < 0: + v = np.random.choice(range(1, 20)) + else: + v = np.random.randint(1, 20, size=r) + + dense_setdiag(a, v, k) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structu") + b.setdiag(v, k) + + # check that dense_setdiag worked + d = np.diag(a, k) + if np.asarray(v).ndim == 0: + assert_array_equal(d, v, err_msg="{msg} {r}") + else: + n = min(len(d), len(v)) + assert_array_equal(d[:n], v[:n], err_msg="{msg} {r}") + # check that sparse setdiag worked + assert_array_equal(b.toarray(), a, err_msg="{msg} {r}") + + # comprehensive test + np.random.seed(1234) + shapes = [(0,5), (5,0), (1,5), (5,1), (5,5)] + for dtype in [np.int8, np.float64]: + for m,n in shapes: + ks = np.arange(-m+1, n-1) + for k in ks: + a = np.zeros((m, n), dtype=dtype) + b = self.spcreator((m, n), dtype=dtype) + + check_setdiag(a, b, k) + + # check overwriting etc + for k2 in np.random.choice(ks, size=min(len(ks), 5)): + check_setdiag(a, b, k2) + + def test_setdiag(self): + # simple test cases + m = self.spcreator(np.eye(3)) + m2 = self.spcreator((4, 4)) + values = [3, 2, 1] + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + assert_raises(ValueError, m.setdiag, values, k=4) + m.setdiag(values) + assert_array_equal(m.diagonal(), values) + m.setdiag(values, k=1) + assert_array_equal(m.toarray(), np.array([[3, 3, 0], + [0, 2, 2], + [0, 0, 1]])) + m.setdiag(values, k=-2) + assert_array_equal(m.toarray(), np.array([[3, 3, 0], + [0, 2, 2], + [3, 0, 1]])) + m.setdiag((9,), k=2) + assert_array_equal(m.toarray()[0,2], 9) + m.setdiag((9,), k=-2) + assert_array_equal(m.toarray()[2,0], 9) + # test short values on an empty matrix + m2.setdiag([1], k=2) + assert_array_equal(m2.toarray()[0], [0, 0, 1, 0]) + # test overwriting that same diagonal + m2.setdiag([1, 1], k=2) + assert_array_equal(m2.toarray()[:2], [[0, 0, 1, 0], + [0, 0, 0, 1]]) + + def test_nonzero(self): + A = array([[1, 0, 1],[0, 1, 1],[0, 0, 1]]) + Asp = self.spcreator(A) + + A_nz = {tuple(ij) for ij in transpose(A.nonzero())} + Asp_nz = {tuple(ij) for ij in transpose(Asp.nonzero())} + + assert_equal(A_nz, Asp_nz) + + def test_numpy_nonzero(self): + # See gh-5987 + A = array([[1, 0, 1], [0, 1, 1], [0, 0, 1]]) + Asp = self.spcreator(A) + + A_nz = {tuple(ij) for ij in transpose(np.nonzero(A))} + Asp_nz = {tuple(ij) for ij in transpose(np.nonzero(Asp))} + + assert_equal(A_nz, Asp_nz) + + def test_sum(self): + np.random.seed(1234) + dat_1 = np.array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + dat_2 = np.random.rand(5, 5) + dat_3 = np.array([[]]) + dat_4 = np.zeros((40, 40)) + dat_5 = sparse.rand(5, 5, density=1e-2).toarray() + matrices = [dat_1, dat_2, dat_3, dat_4, dat_5] + + def check(dtype, j): + dat = self.asdense(matrices[j], dtype=dtype) + datsp = self.spcreator(dat, dtype=dtype) + with np.errstate(over='ignore'): + assert_array_almost_equal(dat.sum(), datsp.sum()) + assert_equal(dat.sum().dtype, datsp.sum().dtype) + assert_(np.isscalar(datsp.sum(axis=None))) + assert_array_almost_equal(dat.sum(axis=None), + datsp.sum(axis=None)) + assert_equal(dat.sum(axis=None).dtype, + datsp.sum(axis=None).dtype) + assert_array_almost_equal(dat.sum(axis=0), datsp.sum(axis=0)) + assert_equal(dat.sum(axis=0).dtype, datsp.sum(axis=0).dtype) + assert_array_almost_equal(dat.sum(axis=1), datsp.sum(axis=1)) + assert_equal(dat.sum(axis=1).dtype, datsp.sum(axis=1).dtype) + assert_array_almost_equal(dat.sum(axis=-2), datsp.sum(axis=-2)) + assert_equal(dat.sum(axis=-2).dtype, datsp.sum(axis=-2).dtype) + assert_array_almost_equal(dat.sum(axis=-1), datsp.sum(axis=-1)) + assert_equal(dat.sum(axis=-1).dtype, datsp.sum(axis=-1).dtype) + + for dtype in self.checked_dtypes: + for j in range(len(matrices)): + check(dtype, j) + + def test_sum_invalid_params(self): + out = np.zeros((1, 3)) + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + assert_raises(ValueError, datsp.sum, axis=3) + assert_raises(TypeError, datsp.sum, axis=(0, 1)) + assert_raises(TypeError, datsp.sum, axis=1.5) + assert_raises(ValueError, datsp.sum, axis=1, out=out) + + def test_sum_dtype(self): + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + def check(dtype): + dat_sum = dat.sum(dtype=dtype) + datsp_sum = datsp.sum(dtype=dtype) + + assert_array_almost_equal(dat_sum, datsp_sum) + assert_equal(dat_sum.dtype, datsp_sum.dtype) + + for dtype in self.checked_dtypes: + check(dtype) + + def test_sum_out(self): + keep = not self.is_array_test + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + dat_out = array(0) if self.is_array_test else array([[0]]) + datsp_out = array(0) if self.is_array_test else matrix([[0]]) + + dat.sum(out=dat_out, keepdims=keep) + datsp.sum(out=datsp_out) + assert_array_almost_equal(dat_out, datsp_out) + + dat_out = np.zeros((3,)) if self.is_array_test else np.zeros((3, 1)) + datsp_out = np.zeros((3,)) if self.is_array_test else matrix(np.zeros((3, 1))) + + dat.sum(axis=1, out=dat_out, keepdims=keep) + datsp.sum(axis=1, out=datsp_out) + assert_array_almost_equal(dat_out, datsp_out) + + # check that wrong shape out parameter raises + with assert_raises(ValueError, match="output parameter.*wrong.*dimension"): + datsp.sum(out=array([0])) + with assert_raises(ValueError, match="output parameter.*wrong.*dimension"): + datsp.sum(out=array([[0]] if self.is_array_test else 0)) + + def test_numpy_sum(self): + # See gh-5987 + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + dat_sum = np.sum(dat) + datsp_sum = np.sum(datsp) + + assert_array_almost_equal(dat_sum, datsp_sum) + assert_equal(dat_sum.dtype, datsp_sum.dtype) + + def test_mean(self): + keep = not self.is_array_test + def check(dtype): + dat = array([[0, 1, 2], + [3, 4, 5], + [6, 7, 9]], dtype=dtype) + datsp = self.spcreator(dat, dtype=dtype) + + assert_array_almost_equal(dat.mean(), datsp.mean()) + assert_equal(dat.mean().dtype, datsp.mean().dtype) + assert_(np.isscalar(datsp.mean(axis=None))) + assert_array_almost_equal( + dat.mean(axis=None, keepdims=keep), datsp.mean(axis=None) + ) + assert_equal(dat.mean(axis=None).dtype, datsp.mean(axis=None).dtype) + assert_array_almost_equal( + dat.mean(axis=0, keepdims=keep), datsp.mean(axis=0) + ) + assert_equal(dat.mean(axis=0).dtype, datsp.mean(axis=0).dtype) + assert_array_almost_equal( + dat.mean(axis=1, keepdims=keep), datsp.mean(axis=1) + ) + assert_equal(dat.mean(axis=1).dtype, datsp.mean(axis=1).dtype) + assert_array_almost_equal( + dat.mean(axis=-2, keepdims=keep), datsp.mean(axis=-2) + ) + assert_equal(dat.mean(axis=-2).dtype, datsp.mean(axis=-2).dtype) + assert_array_almost_equal( + dat.mean(axis=-1, keepdims=keep), datsp.mean(axis=-1) + ) + assert_equal(dat.mean(axis=-1).dtype, datsp.mean(axis=-1).dtype) + + for dtype in self.checked_dtypes: + check(dtype) + + def test_mean_invalid_params(self): + out = self.asdense(np.zeros((1, 3))) + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + assert_raises(ValueError, datsp.mean, axis=3) + assert_raises(TypeError, datsp.mean, axis=(0, 1)) + assert_raises(TypeError, datsp.mean, axis=1.5) + assert_raises(ValueError, datsp.mean, axis=1, out=out) + + def test_mean_dtype(self): + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + def check(dtype): + dat_mean = dat.mean(dtype=dtype) + datsp_mean = datsp.mean(dtype=dtype) + + assert_array_almost_equal(dat_mean, datsp_mean) + assert_equal(dat_mean.dtype, datsp_mean.dtype) + + for dtype in self.checked_dtypes: + check(dtype) + + def test_mean_out(self): + keep = not self.is_array_test + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + dat_out = array(0) if self.is_array_test else array([[0]]) + datsp_out = array(0) if self.is_array_test else matrix([[0]]) + + dat.mean(out=dat_out, keepdims=keep) + datsp.mean(out=datsp_out) + assert_array_almost_equal(dat_out, datsp_out) + + dat_out = np.zeros((3,)) if self.is_array_test else np.zeros((3, 1)) + datsp_out = np.zeros((3,)) if self.is_array_test else matrix(np.zeros((3, 1))) + + dat.mean(axis=1, out=dat_out, keepdims=keep) + datsp.mean(axis=1, out=datsp_out) + assert_array_almost_equal(dat_out, datsp_out) + + # check that wrong shape out parameter raises + with assert_raises(ValueError, match="output parameter.*wrong.*dimension"): + datsp.mean(out=array([0])) + with assert_raises(ValueError, match="output parameter.*wrong.*dimension"): + datsp.mean(out=array([[0]] if self.is_array_test else 0)) + + def test_numpy_mean(self): + # See gh-5987 + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + dat_mean = np.mean(dat) + datsp_mean = np.mean(datsp) + + assert_array_almost_equal(dat_mean, datsp_mean) + assert_equal(dat_mean.dtype, datsp_mean.dtype) + + def test_expm(self): + M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], float) + sM = self.spcreator(M, shape=(3,3), dtype=float) + Mexp = scipy.linalg.expm(M) + + N = array([[3., 0., 1.], [0., 2., 0.], [0., 0., 0.]]) + sN = self.spcreator(N, shape=(3,3), dtype=float) + Nexp = scipy.linalg.expm(N) + + with suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "splu converted its input to CSC format", + ) + sup.filter( + SparseEfficiencyWarning, + "spsolve is more efficient when sparse b is in the CSC matrix format", + ) + sup.filter( + SparseEfficiencyWarning, + "spsolve requires A be CSC or CSR matrix format", + ) + sMexp = expm(sM).toarray() + sNexp = expm(sN).toarray() + + assert_array_almost_equal((sMexp - Mexp), zeros((3, 3))) + assert_array_almost_equal((sNexp - Nexp), zeros((3, 3))) + + def test_inv(self): + def check(dtype): + M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], dtype) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, + "spsolve requires A be CSC or CSR matrix format",) + sup.filter(SparseEfficiencyWarning, + "spsolve is more efficient when sparse b " + "is in the CSC matrix format",) + sup.filter(SparseEfficiencyWarning, + "splu converted its input to CSC format",) + sM = self.spcreator(M, shape=(3,3), dtype=dtype) + sMinv = inv(sM) + assert_array_almost_equal(sMinv.dot(sM).toarray(), np.eye(3)) + assert_raises(TypeError, inv, M) + for dtype in [float]: + check(dtype) + + @sup_complex + def test_from_array(self): + A = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]]) + assert_array_equal(self.spcreator(A).toarray(), A) + + A = array([[1.0 + 3j, 0, 0], + [0, 2.0 + 5, 0], + [0, 0, 0]]) + assert_array_equal(self.spcreator(A).toarray(), A) + assert_array_equal(self.spcreator(A, dtype='int16').toarray(),A.astype('int16')) + + @sup_complex + def test_from_matrix(self): + A = self.asdense([[1, 0, 0], [2, 3, 4], [0, 5, 0], [0, 0, 0]]) + assert_array_equal(self.spcreator(A).todense(), A) + + A = self.asdense([[1.0 + 3j, 0, 0], + [0, 2.0 + 5, 0], + [0, 0, 0]]) + assert_array_equal(self.spcreator(A).todense(), A) + assert_array_equal( + self.spcreator(A, dtype='int16').todense(), A.astype('int16') + ) + + @sup_complex + def test_from_list(self): + A = [[1,0,0],[2,3,4],[0,5,0],[0,0,0]] + assert_array_equal(self.spcreator(A).toarray(), A) + + A = [[1.0 + 3j, 0, 0], + [0, 2.0 + 5, 0], + [0, 0, 0]] + assert_array_equal(self.spcreator(A).toarray(), array(A)) + assert_array_equal( + self.spcreator(A, dtype='int16').toarray(), array(A).astype('int16') + ) + + @sup_complex + def test_from_sparse(self): + D = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]]) + S = self.csr_container(D) + assert_array_equal(self.spcreator(S).toarray(), D) + S = self.spcreator(D) + assert_array_equal(self.spcreator(S).toarray(), D) + + D = array([[1.0 + 3j, 0, 0], + [0, 2.0 + 5, 0], + [0, 0, 0]]) + S = self.csr_container(D) + assert_array_equal(self.spcreator(S).toarray(), D) + assert_array_equal(self.spcreator(S, dtype='int16').toarray(), + D.astype('int16')) + S = self.spcreator(D) + assert_array_equal(self.spcreator(S).toarray(), D) + assert_array_equal(self.spcreator(S, dtype='int16').toarray(), + D.astype('int16')) + + # def test_array(self): + # """test array(A) where A is in sparse format""" + # assert_equal( array(self.datsp), self.dat ) + + def test_todense(self): + # Check C- or F-contiguous (default). + chk = self.datsp.todense() + assert isinstance(chk, np.ndarray if self.is_array_test else np.matrix) + assert_array_equal(chk, self.dat) + assert_(chk.flags.c_contiguous != chk.flags.f_contiguous) + # Check C-contiguous (with arg). + chk = self.datsp.todense(order='C') + assert_array_equal(chk, self.dat) + assert_(chk.flags.c_contiguous) + assert_(not chk.flags.f_contiguous) + # Check F-contiguous (with arg). + chk = self.datsp.todense(order='F') + assert_array_equal(chk, self.dat) + assert_(not chk.flags.c_contiguous) + assert_(chk.flags.f_contiguous) + # Check with out argument (array). + out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype) + chk = self.datsp.todense(out=out) + assert_array_equal(self.dat, out) + assert_array_equal(self.dat, chk) + assert np.may_share_memory(chk, out) + # Check with out array (matrix). + out = self.asdense(np.zeros(self.datsp.shape, dtype=self.datsp.dtype)) + chk = self.datsp.todense(out=out) + assert_array_equal(self.dat, out) + assert_array_equal(self.dat, chk) + assert np.may_share_memory(chk, out) + a = array([[1.,2.,3.]]) + dense_dot_dense = a @ self.dat + check = a @ self.datsp.todense() + assert_array_equal(dense_dot_dense, check) + b = array([[1.,2.,3.,4.]]).T + dense_dot_dense = self.dat @ b + check2 = self.datsp.todense() @ b + assert_array_equal(dense_dot_dense, check2) + # Check bool data works. + spbool = self.spcreator(self.dat, dtype=bool) + matbool = self.dat.astype(bool) + assert_array_equal(spbool.todense(), matbool) + + def test_toarray(self): + # Check C- or F-contiguous (default). + dat = asarray(self.dat) + chk = self.datsp.toarray() + assert_array_equal(chk, dat) + assert_(chk.flags.c_contiguous != chk.flags.f_contiguous) + # Check C-contiguous (with arg). + chk = self.datsp.toarray(order='C') + assert_array_equal(chk, dat) + assert_(chk.flags.c_contiguous) + assert_(not chk.flags.f_contiguous) + # Check F-contiguous (with arg). + chk = self.datsp.toarray(order='F') + assert_array_equal(chk, dat) + assert_(not chk.flags.c_contiguous) + assert_(chk.flags.f_contiguous) + # Check with output arg. + out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype) + self.datsp.toarray(out=out) + assert_array_equal(chk, dat) + # Check that things are fine when we don't initialize with zeros. + out[...] = 1. + self.datsp.toarray(out=out) + assert_array_equal(chk, dat) + a = array([1.,2.,3.]) + dense_dot_dense = dot(a, dat) + check = dot(a, self.datsp.toarray()) + assert_array_equal(dense_dot_dense, check) + b = array([1.,2.,3.,4.]) + dense_dot_dense = dot(dat, b) + check2 = dot(self.datsp.toarray(), b) + assert_array_equal(dense_dot_dense, check2) + # Check bool data works. + spbool = self.spcreator(self.dat, dtype=bool) + arrbool = dat.astype(bool) + assert_array_equal(spbool.toarray(), arrbool) + + @sup_complex + def test_astype(self): + D = array([[2.0 + 3j, 0, 0], + [0, 4.0 + 5j, 0], + [0, 0, 0]]) + S = self.spcreator(D) + + for x in supported_dtypes: + # Check correctly casted + D_casted = D.astype(x) + for copy in (True, False): + S_casted = S.astype(x, copy=copy) + assert_equal(S_casted.dtype, D_casted.dtype) # correct type + assert_equal(S_casted.toarray(), D_casted) # correct values + assert_equal(S_casted.format, S.format) # format preserved + # Check correctly copied + assert_(S_casted.astype(x, copy=False) is S_casted) + S_copied = S_casted.astype(x, copy=True) + assert_(S_copied is not S_casted) + + def check_equal_but_not_same_array_attribute(attribute): + a = getattr(S_casted, attribute) + b = getattr(S_copied, attribute) + assert_array_equal(a, b) + assert_(a is not b) + i = (0,) * b.ndim + b_i = b[i] + b[i] = not b[i] + assert_(a[i] != b[i]) + b[i] = b_i + + if S_casted.format in ('csr', 'csc', 'bsr'): + for attribute in ('indices', 'indptr', 'data'): + check_equal_but_not_same_array_attribute(attribute) + elif S_casted.format == 'coo': + for attribute in ('row', 'col', 'data'): + check_equal_but_not_same_array_attribute(attribute) + elif S_casted.format == 'dia': + for attribute in ('offsets', 'data'): + check_equal_but_not_same_array_attribute(attribute) + + @sup_complex + def test_astype_immutable(self): + D = array([[2.0 + 3j, 0, 0], + [0, 4.0 + 5j, 0], + [0, 0, 0]]) + S = self.spcreator(D) + if hasattr(S, 'data'): + S.data.flags.writeable = False + if S.format in ('csr', 'csc', 'bsr'): + S.indptr.flags.writeable = False + S.indices.flags.writeable = False + for x in supported_dtypes: + D_casted = D.astype(x) + S_casted = S.astype(x) + assert_equal(S_casted.dtype, D_casted.dtype) + + def test_mul_scalar(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + assert_array_equal(dat*2, (datsp*2).toarray()) + assert_array_equal(dat*17.3, (datsp*17.3).toarray()) + + for dtype in self.math_dtypes: + check(dtype) + + def test_rmul_scalar(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + assert_array_equal(2*dat, (2*datsp).toarray()) + assert_array_equal(17.3*dat, (17.3*datsp).toarray()) + + for dtype in self.math_dtypes: + check(dtype) + + # GitHub issue #15210 + def test_rmul_scalar_type_error(self): + datsp = self.datsp_dtypes[np.float64] + with assert_raises(TypeError): + None * datsp + + def test_add(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + a = dat.copy() + a[0,2] = 2.0 + b = datsp + c = b + a + assert_array_equal(c, b.toarray() + a) + + c = b + b.tocsr() + assert_array_equal(c.toarray(), + b.toarray() + b.toarray()) + + # test broadcasting + c = b + a[0] + assert_array_equal(c, b.toarray() + a[0]) + + for dtype in self.math_dtypes: + check(dtype) + + def test_radd(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + a = dat.copy() + a[0,2] = 2.0 + b = datsp + c = a + b + assert_array_equal(c, a + b.toarray()) + + for dtype in self.math_dtypes: + check(dtype) + + def test_sub(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + assert_array_equal((datsp - datsp).toarray(), np.zeros((3, 4))) + assert_array_equal((datsp - 0).toarray(), dat) + + A = self.spcreator( + np.array([[1, 0, 0, 4], [-1, 0, 0, 0], [0, 8, 0, -5]], 'd') + ) + assert_array_equal((datsp - A).toarray(), dat - A.toarray()) + assert_array_equal((A - datsp).toarray(), A.toarray() - dat) + + # test broadcasting + assert_array_equal(datsp - dat[0], dat - dat[0]) + + for dtype in self.math_dtypes: + if dtype == np.dtype('bool'): + # boolean array subtraction deprecated in 1.9.0 + continue + + check(dtype) + + def test_rsub(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + assert_array_equal((dat - datsp),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) + assert_array_equal((datsp - dat),[[0,0,0,0],[0,0,0,0],[0,0,0,0]]) + assert_array_equal((0 - datsp).toarray(), -dat) + + A = self.spcreator([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],dtype='d') + assert_array_equal((dat - A), dat - A.toarray()) + assert_array_equal((A - dat), A.toarray() - dat) + assert_array_equal(A.toarray() - datsp, A.toarray() - dat) + assert_array_equal(datsp - A.toarray(), dat - A.toarray()) + + # test broadcasting + assert_array_equal(dat[0] - datsp, dat[0] - dat) + + for dtype in self.math_dtypes: + if dtype == np.dtype('bool'): + # boolean array subtraction deprecated in 1.9.0 + continue + + check(dtype) + + def test_add0(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + # Adding 0 to a sparse matrix + assert_array_equal((datsp + 0).toarray(), dat) + # use sum (which takes 0 as a starting value) + sumS = sum([k * datsp for k in range(1, 3)]) + sumD = sum([k * dat for k in range(1, 3)]) + assert_almost_equal(sumS.toarray(), sumD) + + for dtype in self.math_dtypes: + check(dtype) + + def test_elementwise_multiply(self): + # real/real + A = array([[4,0,9],[2,-3,5]]) + B = array([[0,7,0],[0,-4,0]]) + Asp = self.spcreator(A) + Bsp = self.spcreator(B) + assert_almost_equal(Asp.multiply(Bsp).toarray(), A*B) # sparse/sparse + assert_almost_equal(Asp.multiply(B).toarray(), A*B) # sparse/dense + + # complex/complex + C = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]]) + D = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]]) + Csp = self.spcreator(C) + Dsp = self.spcreator(D) + assert_almost_equal(Csp.multiply(Dsp).toarray(), C*D) # sparse/sparse + assert_almost_equal(Csp.multiply(D).toarray(), C*D) # sparse/dense + + # real/complex + assert_almost_equal(Asp.multiply(Dsp).toarray(), A*D) # sparse/sparse + assert_almost_equal(Asp.multiply(D).toarray(), A*D) # sparse/dense + + def test_elementwise_multiply_broadcast(self): + A = array([4]) + B = array([[-9]]) + C = array([1,-1,0]) + D = array([[7,9,-9]]) + E = array([[3],[2],[1]]) + F = array([[8,6,3],[-4,3,2],[6,6,6]]) + G = [1, 2, 3] + H = np.ones((3, 4)) + J = H.T + K = array([[0]]) + L = array([[[1,2],[0,1]]]) + + # Some arrays can't be cast as spmatrices (A,C,L) so leave + # them out. + Bsp = self.spcreator(B) + Dsp = self.spcreator(D) + Esp = self.spcreator(E) + Fsp = self.spcreator(F) + Hsp = self.spcreator(H) + Hspp = self.spcreator(H[0,None]) + Jsp = self.spcreator(J) + Jspp = self.spcreator(J[:,0,None]) + Ksp = self.spcreator(K) + + matrices = [A, B, C, D, E, F, G, H, J, K, L] + spmatrices = [Bsp, Dsp, Esp, Fsp, Hsp, Hspp, Jsp, Jspp, Ksp] + + # sparse/sparse + for i in spmatrices: + for j in spmatrices: + try: + dense_mult = i.toarray() * j.toarray() + except ValueError: + assert_raises(ValueError, i.multiply, j) + continue + sp_mult = i.multiply(j) + assert_almost_equal(sp_mult.toarray(), dense_mult) + + # sparse/dense + for i in spmatrices: + for j in matrices: + try: + dense_mult = i.toarray() * j + except TypeError: + continue + except ValueError: + assert_raises(ValueError, i.multiply, j) + continue + sp_mult = i.multiply(j) + if issparse(sp_mult): + assert_almost_equal(sp_mult.toarray(), dense_mult) + else: + assert_almost_equal(sp_mult, dense_mult) + + def test_elementwise_divide(self): + expected = [[1,np.nan,np.nan,1], + [1,np.nan,1,np.nan], + [np.nan,1,np.nan,np.nan]] + assert_array_equal(toarray(self.datsp / self.datsp), expected) + + denom = self.spcreator([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],dtype='d') + expected = [[1,np.nan,np.nan,0.5], + [-3,np.nan,inf,np.nan], + [np.nan,0.25,np.nan,0]] + assert_array_equal(toarray(self.datsp / denom), expected) + + # complex + A = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]]) + B = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]]) + Asp = self.spcreator(A) + Bsp = self.spcreator(B) + assert_almost_equal(toarray(Asp / Bsp), A/B) + + # integer + A = array([[1,2,3],[-3,2,1]]) + B = array([[0,1,2],[0,-2,3]]) + Asp = self.spcreator(A) + Bsp = self.spcreator(B) + with np.errstate(divide='ignore'): + assert_array_equal(toarray(Asp / Bsp), A / B) + + # mismatching sparsity patterns + A = array([[0,1],[1,0]]) + B = array([[1,0],[1,0]]) + Asp = self.spcreator(A) + Bsp = self.spcreator(B) + with np.errstate(divide='ignore', invalid='ignore'): + assert_array_equal(np.array(toarray(Asp / Bsp)), A / B) + + def test_pow(self): + A = array([[1, 0, 2, 0], [0, 3, 4, 0], [0, 5, 0, 0], [0, 6, 7, 8]]) + B = self.spcreator(A) + + if self.is_array_test: # sparrays use element-wise power + # Todo: Add 1+3j to tested exponent list when np1.24 is no longer supported + # Complex exponents of 0 (our implicit fill value) change in numpy-1.25 + # from `(nan+nanj)` to `0`. Old value makes array element-wise result + # dense and is hard to check for without any `isnan` method. + # So while untested here, element-wise complex exponents work with np>=1.25. + # for exponent in [1, 2, 2.2, 3, 1+3j]: + for exponent in [1, 2, 2.2, 3]: + ret_sp = B**exponent + ret_np = A**exponent + assert_array_equal(ret_sp.toarray(), ret_np) + assert_equal(ret_sp.dtype, ret_np.dtype) + + # invalid exponents + assert_raises(NotImplementedError, B.__pow__, 0) + assert_raises(ValueError, B.__pow__, -1) + + # nonsquare matrix + B = self.spcreator(A[:3,:]) + assert_equal((B**1).toarray(), B.toarray()) + else: # test sparse matrix. spmatrices use matrix multiplicative power + for exponent in [0,1,2,3]: + ret_sp = B**exponent + ret_np = np.linalg.matrix_power(A, exponent) + assert_array_equal(ret_sp.toarray(), ret_np) + assert_equal(ret_sp.dtype, ret_np.dtype) + + # invalid exponents + for exponent in [-1, 2.2, 1 + 3j]: + assert_raises(ValueError, B.__pow__, exponent) + + # nonsquare matrix + B = self.spcreator(A[:3,:]) + assert_raises(TypeError, B.__pow__, 1) + + def test_rmatvec(self): + M = self.spcreator([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) + assert_array_almost_equal([1,2,3,4] @ M, dot([1,2,3,4], M.toarray())) + row = array([[1,2,3,4]]) + assert_array_almost_equal(row @ M, row @ M.toarray()) + + def test_small_multiplication(self): + # test that A*x works for x with shape () (1,) (1,1) and (1,0) + A = self.spcreator([[1],[2],[3]]) + + assert_(issparse(A * array(1))) + assert_equal((A * array(1)).toarray(), [[1], [2], [3]]) + + assert_equal(A @ array([1]), array([1, 2, 3])) + assert_equal(A @ array([[1]]), array([[1], [2], [3]])) + assert_equal(A @ np.ones((1, 1)), array([[1], [2], [3]])) + assert_equal(A @ np.ones((1, 0)), np.ones((3, 0))) + + def test_star_vs_at_sign_for_sparray_and_spmatrix(self): + # test that * is matmul for spmatrix and mul for sparray + A = np.array([[1], [2], [3]]) + Asp = self.spcreator(A) + + if self.is_array_test: + assert_array_almost_equal((Asp * np.ones((3, 1))).toarray(), A) + assert_array_almost_equal((Asp * array([[1]])).toarray(), A) + else: + assert_equal(Asp * array([1]), array([1, 2, 3])) + assert_equal(Asp * array([[1]]), array([[1], [2], [3]])) + assert_equal(Asp * np.ones((1, 0)), np.ones((3, 0))) + + def test_binop_custom_type(self): + # Non-regression test: previously, binary operations would raise + # NotImplementedError instead of returning NotImplemented + # (https://docs.python.org/library/constants.html#NotImplemented) + # so overloading Custom + matrix etc. didn't work. + A = self.spcreator([[1], [2], [3]]) + B = BinopTester() + assert_equal(A + B, "matrix on the left") + assert_equal(A - B, "matrix on the left") + assert_equal(A * B, "matrix on the left") + assert_equal(B + A, "matrix on the right") + assert_equal(B - A, "matrix on the right") + assert_equal(B * A, "matrix on the right") + + assert_equal(A @ B, "matrix on the left") + assert_equal(B @ A, "matrix on the right") + + def test_binop_custom_type_with_shape(self): + A = self.spcreator([[1], [2], [3]]) + B = BinopTester_with_shape((3,1)) + assert_equal(A + B, "matrix on the left") + assert_equal(A - B, "matrix on the left") + assert_equal(A * B, "matrix on the left") + assert_equal(B + A, "matrix on the right") + assert_equal(B - A, "matrix on the right") + assert_equal(B * A, "matrix on the right") + + assert_equal(A @ B, "matrix on the left") + assert_equal(B @ A, "matrix on the right") + + def test_mul_custom_type(self): + class Custom: + def __init__(self, scalar): + self.scalar = scalar + + def __rmul__(self, other): + return other * self.scalar + + scalar = 2 + A = self.spcreator([[1],[2],[3]]) + c = Custom(scalar) + A_scalar = A * scalar + A_c = A * c + assert_array_equal_dtype(A_scalar.toarray(), A_c.toarray()) + assert_equal(A_scalar.format, A_c.format) + + def test_comparisons_custom_type(self): + A = self.spcreator([[1], [2], [3]]) + B = ComparisonTester() + assert_equal(A == B, "eq") + assert_equal(A != B, "ne") + assert_equal(A > B, "lt") + assert_equal(A >= B, "le") + assert_equal(A < B, "gt") + assert_equal(A <= B, "ge") + + def test_dot_scalar(self): + M = self.spcreator(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) + scalar = 10 + actual = M.dot(scalar) + expected = M * scalar + + assert_allclose(actual.toarray(), expected.toarray()) + + def test_matmul(self): + M = self.spcreator(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) + B = self.spcreator(array([[0,1],[1,0],[0,2]],'d')) + col = array([[1,2,3]]).T + + matmul = operator.matmul + # check matrix-vector + assert_array_almost_equal(matmul(M, col), M.toarray() @ col) + + # check matrix-matrix + assert_array_almost_equal(matmul(M, B).toarray(), (M @ B).toarray()) + assert_array_almost_equal(matmul(M.toarray(), B), (M @ B).toarray()) + assert_array_almost_equal(matmul(M, B.toarray()), (M @ B).toarray()) + + # check error on matrix-scalar + assert_raises(ValueError, matmul, M, 1) + assert_raises(ValueError, matmul, 1, M) + + def test_matvec(self): + M = self.spcreator([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) + col = array([[1,2,3]]).T + + assert_array_almost_equal(M @ col, M.toarray() @ col) + + # check result dimensions (ticket #514) + assert_equal((M @ array([1,2,3])).shape,(4,)) + assert_equal((M @ array([[1],[2],[3]])).shape,(4,1)) + assert_equal((M @ matrix([[1],[2],[3]])).shape,(4,1)) + + # check result type + assert_(isinstance(M @ array([1,2,3]), ndarray)) + matrix_or_array = ndarray if self.is_array_test else np.matrix + assert_(isinstance(M @ matrix([1,2,3]).T, matrix_or_array)) + + # ensure exception is raised for improper dimensions + bad_vecs = [array([1,2]), array([1,2,3,4]), array([[1],[2]]), + matrix([1,2,3]), matrix([[1],[2]])] + for x in bad_vecs: + assert_raises(ValueError, M.__matmul__, x) + + # The current relationship between sparse matrix products and array + # products is as follows: + assert_almost_equal(M@array([1,2,3]), dot(M.toarray(),[1,2,3])) + assert_almost_equal(M@[[1],[2],[3]], np.atleast_2d(dot(M.toarray(),[1,2,3])).T) + # Note that the result of M * x is dense if x has a singleton dimension. + + # Currently M.matvec(asarray(col)) is rank-1, whereas M.matvec(col) + # is rank-2. Is this desirable? + + def test_matmat_sparse(self): + a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) + a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) + b = matrix([[0,1],[1,0],[0,2]],'d') + asp = self.spcreator(a) + bsp = self.spcreator(b) + assert_array_almost_equal((asp @ bsp).toarray(), a @ b) + assert_array_almost_equal(asp @ b, a @ b) + assert_array_almost_equal(a @ bsp, a @ b) + assert_array_almost_equal(a2 @ bsp, a @ b) + + # Now try performing cross-type multiplication: + csp = bsp.tocsc() + c = b + want = a @ c + assert_array_almost_equal((asp @ csp).toarray(), want) + assert_array_almost_equal(asp @ c, want) + + assert_array_almost_equal(a @ csp, want) + assert_array_almost_equal(a2 @ csp, want) + csp = bsp.tocsr() + assert_array_almost_equal((asp @ csp).toarray(), want) + assert_array_almost_equal(asp @ c, want) + + assert_array_almost_equal(a @ csp, want) + assert_array_almost_equal(a2 @ csp, want) + csp = bsp.tocoo() + assert_array_almost_equal((asp @ csp).toarray(), want) + assert_array_almost_equal(asp @ c, want) + + assert_array_almost_equal(a @ csp, want) + assert_array_almost_equal(a2 @ csp, want) + + # Test provided by Andy Fraser, 2006-03-26 + L = 30 + frac = .3 + random.seed(0) # make runs repeatable + A = zeros((L,2)) + for i in range(L): + for j in range(2): + r = random.random() + if r < frac: + A[i,j] = r/frac + + A = self.spcreator(A) + B = A @ A.T + assert_array_almost_equal(B.toarray(), A.toarray() @ A.T.toarray()) + assert_array_almost_equal(B.toarray(), A.toarray() @ A.toarray().T) + + # check dimension mismatch 2x2 times 3x2 + A = self.spcreator([[1,2],[3,4]]) + B = self.spcreator([[1,2],[3,4],[5,6]]) + assert_raises(ValueError, A.__matmul__, B) + if self.is_array_test: + assert_raises(ValueError, A.__mul__, B) + + def test_matmat_dense(self): + a = [[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]] + asp = self.spcreator(a) + + # check both array and matrix types + bs = [array([[1,2],[3,4],[5,6]]), matrix([[1,2],[3,4],[5,6]])] + + for b in bs: + result = asp @ b + assert_(isinstance(result, ndarray if self.is_array_test else type(b))) + assert_equal(result.shape, (4,2)) + assert_equal(result, dot(a,b)) + + def test_sparse_format_conversions(self): + A = sparse.kron([[1,0,2],[0,3,4],[5,0,0]], [[1,2],[0,3]]) + D = A.toarray() + A = self.spcreator(A) + + for format in ['bsr','coo','csc','csr','dia','dok','lil']: + a = A.asformat(format) + assert_equal(a.format,format) + assert_array_equal(a.toarray(), D) + + b = self.spcreator(D+3j).asformat(format) + assert_equal(b.format,format) + assert_array_equal(b.toarray(), D+3j) + + c = self.spcreator(D).asformat(format) + assert_equal(c.format,format) + assert_array_equal(c.toarray(), D) + + for format in ['array', 'dense']: + a = A.asformat(format) + assert_array_equal(a, D) + + b = self.spcreator(D+3j).asformat(format) + assert_array_equal(b, D+3j) + + def test_tobsr(self): + x = array([[1,0,2,0],[0,0,0,0],[0,0,4,5]]) + y = array([[0,1,2],[3,0,5]]) + A = kron(x,y) + Asp = self.spcreator(A) + for format in ['bsr']: + fn = getattr(Asp, 'to' + format) + + for X in [1, 2, 3, 6]: + for Y in [1, 2, 3, 4, 6, 12]: + assert_equal(fn(blocksize=(X, Y)).toarray(), A) + + def test_transpose(self): + dat_1 = self.dat + dat_2 = np.array([[]]) + matrices = [dat_1, dat_2] + + def check(dtype, j): + dat = array(matrices[j], dtype=dtype) + datsp = self.spcreator(dat) + + a = datsp.transpose() + b = dat.transpose() + + assert_array_equal(a.toarray(), b) + assert_array_equal(a.transpose().toarray(), dat) + assert_array_equal(datsp.transpose(axes=(1, 0)).toarray(), b) + assert_equal(a.dtype, b.dtype) + + # See gh-5987 + empty = self.spcreator((3, 4)) + assert_array_equal(np.transpose(empty).toarray(), + np.transpose(zeros((3, 4)))) + assert_array_equal(empty.T.toarray(), zeros((4, 3))) + assert_raises(ValueError, empty.transpose, axes=0) + + for dtype in self.checked_dtypes: + for j in range(len(matrices)): + check(dtype, j) + + def test_add_dense(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + # adding a dense matrix to a sparse matrix + sum1 = dat + datsp + assert_array_equal(sum1, dat + dat) + sum2 = datsp + dat + assert_array_equal(sum2, dat + dat) + + for dtype in self.math_dtypes: + check(dtype) + + def test_sub_dense(self): + # subtracting a dense matrix to/from a sparse matrix + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + # Behavior is different for bool. + if dat.dtype == bool: + sum1 = dat - datsp + assert_array_equal(sum1, dat - dat) + sum2 = datsp - dat + assert_array_equal(sum2, dat - dat) + else: + # Manually add to avoid upcasting from scalar + # multiplication. + sum1 = (dat + dat + dat) - datsp + assert_array_equal(sum1, dat + dat) + sum2 = (datsp + datsp + datsp) - dat + assert_array_equal(sum2, dat + dat) + + for dtype in self.math_dtypes: + if dtype == np.dtype('bool'): + # boolean array subtraction deprecated in 1.9.0 + continue + + check(dtype) + + def test_maximum_minimum(self): + A_dense = np.array([[1, 0, 3], [0, 4, 5], [0, 0, 0]]) + B_dense = np.array([[1, 1, 2], [0, 3, 6], [1, -1, 0]]) + + A_dense_cpx = np.array([[1, 0, 3], [0, 4+2j, 5], [0, 1j, -1j]]) + + def check(dtype, dtype2, btype): + if np.issubdtype(dtype, np.complexfloating): + A = self.spcreator(A_dense_cpx.astype(dtype)) + else: + A = self.spcreator(A_dense.astype(dtype)) + if btype == 'scalar': + B = dtype2.type(1) + elif btype == 'scalar2': + B = dtype2.type(-1) + elif btype == 'dense': + B = B_dense.astype(dtype2) + elif btype == 'sparse': + B = self.spcreator(B_dense.astype(dtype2)) + else: + raise ValueError() + + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, + "Taking maximum .minimum. with > 0 .< 0. number " + "results to a dense matrix") + + max_s = A.maximum(B) + min_s = A.minimum(B) + + max_d = np.maximum(toarray(A), toarray(B)) + assert_array_equal(toarray(max_s), max_d) + assert_equal(max_s.dtype, max_d.dtype) + + min_d = np.minimum(toarray(A), toarray(B)) + assert_array_equal(toarray(min_s), min_d) + assert_equal(min_s.dtype, min_d.dtype) + + for dtype in self.math_dtypes: + for dtype2 in [np.int8, np.float64, np.complex128]: + for btype in ['scalar', 'scalar2', 'dense', 'sparse']: + check(np.dtype(dtype), np.dtype(dtype2), btype) + + def test_copy(self): + # Check whether the copy=True and copy=False keywords work + A = self.datsp + + # check that copy preserves format + assert_equal(A.copy().format, A.format) + assert_equal(A.__class__(A,copy=True).format, A.format) + assert_equal(A.__class__(A,copy=False).format, A.format) + + assert_equal(A.copy().toarray(), A.toarray()) + assert_equal(A.__class__(A, copy=True).toarray(), A.toarray()) + assert_equal(A.__class__(A, copy=False).toarray(), A.toarray()) + + # check that XXX_array.toXXX() works + toself = getattr(A,'to' + A.format) + assert_(toself() is A) + assert_(toself(copy=False) is A) + assert_equal(toself(copy=True).format, A.format) + assert_equal(toself(copy=True).toarray(), A.toarray()) + + # check whether the data is copied? + assert_(not sparse_may_share_memory(A.copy(), A)) + + # test that __iter__ is compatible with NumPy matrix + def test_iterator(self): + B = self.asdense(np.arange(50).reshape(5, 10)) + A = self.spcreator(B) + + for x, y in zip(A, B): + assert_equal(x.toarray(), y) + + def test_size_zero_matrix_arithmetic(self): + # Test basic matrix arithmetic with shapes like (0,0), (10,0), + # (0, 3), etc. + mat = array([]) + a = mat.reshape((0, 0)) + b = mat.reshape((0, 1)) + c = mat.reshape((0, 5)) + d = mat.reshape((1, 0)) + e = mat.reshape((5, 0)) + f = np.ones([5, 5]) + + asp = self.spcreator(a) + bsp = self.spcreator(b) + csp = self.spcreator(c) + dsp = self.spcreator(d) + esp = self.spcreator(e) + fsp = self.spcreator(f) + + # matrix product. + assert_array_equal(asp.dot(asp).toarray(), np.dot(a, a)) + assert_array_equal(bsp.dot(dsp).toarray(), np.dot(b, d)) + assert_array_equal(dsp.dot(bsp).toarray(), np.dot(d, b)) + assert_array_equal(csp.dot(esp).toarray(), np.dot(c, e)) + assert_array_equal(csp.dot(fsp).toarray(), np.dot(c, f)) + assert_array_equal(esp.dot(csp).toarray(), np.dot(e, c)) + assert_array_equal(dsp.dot(csp).toarray(), np.dot(d, c)) + assert_array_equal(fsp.dot(esp).toarray(), np.dot(f, e)) + + # bad matrix products + assert_raises(ValueError, dsp.dot, e) + assert_raises(ValueError, asp.dot, d) + + # elemente-wise multiplication + assert_array_equal(asp.multiply(asp).toarray(), np.multiply(a, a)) + assert_array_equal(bsp.multiply(bsp).toarray(), np.multiply(b, b)) + assert_array_equal(dsp.multiply(dsp).toarray(), np.multiply(d, d)) + + assert_array_equal(asp.multiply(a).toarray(), np.multiply(a, a)) + assert_array_equal(bsp.multiply(b).toarray(), np.multiply(b, b)) + assert_array_equal(dsp.multiply(d).toarray(), np.multiply(d, d)) + + assert_array_equal(asp.multiply(6).toarray(), np.multiply(a, 6)) + assert_array_equal(bsp.multiply(6).toarray(), np.multiply(b, 6)) + assert_array_equal(dsp.multiply(6).toarray(), np.multiply(d, 6)) + + # bad element-wise multiplication + assert_raises(ValueError, asp.multiply, c) + assert_raises(ValueError, esp.multiply, c) + + # Addition + assert_array_equal(asp.__add__(asp).toarray(), a.__add__(a)) + assert_array_equal(bsp.__add__(bsp).toarray(), b.__add__(b)) + assert_array_equal(dsp.__add__(dsp).toarray(), d.__add__(d)) + + # bad addition + assert_raises(ValueError, asp.__add__, dsp) + assert_raises(ValueError, bsp.__add__, asp) + + def test_size_zero_conversions(self): + mat = array([]) + a = mat.reshape((0, 0)) + b = mat.reshape((0, 5)) + c = mat.reshape((5, 0)) + + for m in [a, b, c]: + spm = self.spcreator(m) + assert_array_equal(spm.tocoo().toarray(), m) + assert_array_equal(spm.tocsr().toarray(), m) + assert_array_equal(spm.tocsc().toarray(), m) + assert_array_equal(spm.tolil().toarray(), m) + assert_array_equal(spm.todok().toarray(), m) + assert_array_equal(spm.tobsr().toarray(), m) + + def test_dtype_check(self): + a = np.array([[3.5, 0, 1.1], [0, 0, 0]], dtype=np.float16) + with assert_raises(ValueError, match="does not support dtype"): + self.spcreator(a) + + A32 = self.spcreator(a.astype(np.float32)) + with assert_raises(ValueError, match="does not support dtype"): + self.spcreator(A32, dtype=np.float16) + + def test_pickle(self): + import pickle + sup = suppress_warnings() + sup.filter(SparseEfficiencyWarning) + + @sup + def check(): + datsp = self.datsp.copy() + for protocol in range(pickle.HIGHEST_PROTOCOL): + sploaded = pickle.loads(pickle.dumps(datsp, protocol=protocol)) + assert_equal(datsp.shape, sploaded.shape) + assert_array_equal(datsp.toarray(), sploaded.toarray()) + assert_equal(datsp.format, sploaded.format) + # Hacky check for class member equality. This assumes that + # all instance variables are one of: + # 1. Plain numpy ndarrays + # 2. Tuples of ndarrays + # 3. Types that support equality comparison with == + for key, val in datsp.__dict__.items(): + if isinstance(val, np.ndarray): + assert_array_equal(val, sploaded.__dict__[key]) + elif (isinstance(val, tuple) and val + and isinstance(val[0], np.ndarray)): + assert_array_equal(val, sploaded.__dict__[key]) + else: + assert_(val == sploaded.__dict__[key]) + check() + + def test_unary_ufunc_overrides(self): + def check(name): + if name == "sign": + pytest.skip("sign conflicts with comparison op " + "support on Numpy") + if self.datsp.format in ["dok", "lil"]: + pytest.skip("Unary ops not implemented for dok/lil") + ufunc = getattr(np, name) + + X = self.spcreator(np.arange(20).reshape(4, 5) / 20.) + X0 = ufunc(X.toarray()) + + X2 = ufunc(X) + assert_array_equal(X2.toarray(), X0) + + for name in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh", + "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p", + "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt", + "abs"]: + check(name) + + def test_resize(self): + # resize(shape) resizes the matrix in-place + D = np.array([[1, 0, 3, 4], + [2, 0, 0, 0], + [3, 0, 0, 0]]) + S = self.spcreator(D) + assert_(S.resize((3, 2)) is None) + assert_array_equal(S.toarray(), [[1, 0], + [2, 0], + [3, 0]]) + S.resize((2, 2)) + assert_array_equal(S.toarray(), [[1, 0], + [2, 0]]) + S.resize((3, 2)) + assert_array_equal(S.toarray(), [[1, 0], + [2, 0], + [0, 0]]) + S.resize((3, 3)) + assert_array_equal(S.toarray(), [[1, 0, 0], + [2, 0, 0], + [0, 0, 0]]) + # test no-op + S.resize((3, 3)) + assert_array_equal(S.toarray(), [[1, 0, 0], + [2, 0, 0], + [0, 0, 0]]) + + # test *args + S.resize(3, 2) + assert_array_equal(S.toarray(), [[1, 0], + [2, 0], + [0, 0]]) + + if self.is_array_test and S.format in ["coo", "csr"]: + S.resize(1) + else: + assert_raises((ValueError, NotImplementedError, IndexError), S.resize, 1) + + for bad_shape in [(-1, 2), (2, -1), (1, 2, 3)]: + assert_raises(ValueError, S.resize, bad_shape) + + def test_constructor1_base(self): + A = self.datsp + + self_format = A.format + + C = A.__class__(A, copy=False) + assert_array_equal_dtype(A.toarray(), C.toarray()) + if self_format not in NON_ARRAY_BACKED_FORMATS: + assert_(sparse_may_share_memory(A, C)) + + C = A.__class__(A, dtype=A.dtype, copy=False) + assert_array_equal_dtype(A.toarray(), C.toarray()) + if self_format not in NON_ARRAY_BACKED_FORMATS: + assert_(sparse_may_share_memory(A, C)) + + C = A.__class__(A, dtype=np.float32, copy=False) + assert_array_equal(A.toarray(), C.toarray()) + + C = A.__class__(A, copy=True) + assert_array_equal_dtype(A.toarray(), C.toarray()) + assert_(not sparse_may_share_memory(A, C)) + + for other_format in ['csr', 'csc', 'coo', 'dia', 'dok', 'lil']: + if other_format == self_format: + continue + B = A.asformat(other_format) + C = A.__class__(B, copy=False) + assert_array_equal_dtype(A.toarray(), C.toarray()) + + C = A.__class__(B, copy=True) + assert_array_equal_dtype(A.toarray(), C.toarray()) + assert_(not sparse_may_share_memory(B, C)) + + +class _TestInplaceArithmetic: + def test_inplace_dense(self): + a = np.ones((3, 4)) + b = self.spcreator(a) + + x = a.copy() + y = a.copy() + x += a + y += b + assert_array_equal(x, y) + + x = a.copy() + y = a.copy() + x -= a + y -= b + assert_array_equal(x, y) + + if self.is_array_test: + # Elementwise multiply from sparray.__rmul__ + x = a.copy() + y = a.copy() + with assert_raises(ValueError, match="inconsistent shapes"): + x *= b.T + x = x * a + y *= b + assert_array_equal(x, y.toarray()) + else: + # Matrix multiply from spmatrix.__rmul__ + x = a.copy() + y = a.copy() + with assert_raises(ValueError, match="dimension mismatch"): + x *= b + x = x.dot(a.T) + y *= b.T + assert_array_equal(x, y) + + # Matrix multiply from __rmatmul__ + y = a.copy() + # skip this test if numpy doesn't support __imatmul__ yet. + # move out of the try/except once numpy 1.24 is no longer supported. + try: + y @= b.T + except TypeError: + pass + else: + x = a.copy() + y = a.copy() + with assert_raises(ValueError, match="dimension mismatch"): + x @= b + x = x.dot(a.T) + y @= b.T + assert_array_equal(x, y) + + # Floor division is not supported + with assert_raises(TypeError, match="unsupported operand"): + x //= b + + def test_imul_scalar(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + # Avoid implicit casting. + if np.can_cast(int, dtype, casting='same_kind'): + a = datsp.copy() + a *= 2 + b = dat.copy() + b *= 2 + assert_array_equal(b, a.toarray()) + + if np.can_cast(float, dtype, casting='same_kind'): + a = datsp.copy() + a *= 17.3 + b = dat.copy() + b *= 17.3 + assert_array_equal(b, a.toarray()) + + for dtype in self.math_dtypes: + check(dtype) + + def test_idiv_scalar(self): + def check(dtype): + dat = self.dat_dtypes[dtype] + datsp = self.datsp_dtypes[dtype] + + if np.can_cast(int, dtype, casting='same_kind'): + a = datsp.copy() + a /= 2 + b = dat.copy() + b /= 2 + assert_array_equal(b, a.toarray()) + + if np.can_cast(float, dtype, casting='same_kind'): + a = datsp.copy() + a /= 17.3 + b = dat.copy() + b /= 17.3 + assert_array_equal(b, a.toarray()) + + for dtype in self.math_dtypes: + # /= should only be used with float dtypes to avoid implicit + # casting. + if not np.can_cast(dtype, np.dtype(int)): + check(dtype) + + def test_inplace_success(self): + # Inplace ops should work even if a specialized version is not + # implemented, falling back to x = x y + a = self.spcreator(np.eye(5)) + b = self.spcreator(np.eye(5)) + bp = self.spcreator(np.eye(5)) + + b += a + bp = bp + a + assert_allclose(b.toarray(), bp.toarray()) + + if self.is_array_test: + b *= a + bp = bp * a + assert_allclose(b.toarray(), bp.toarray()) + + b @= a + bp = bp @ a + assert_allclose(b.toarray(), bp.toarray()) + + b -= a + bp = bp - a + assert_allclose(b.toarray(), bp.toarray()) + + with assert_raises(TypeError, match="unsupported operand"): + a //= b + + +class _TestGetSet: + def test_getelement(self): + def check(dtype): + D = array([[1,0,0], + [4,3,0], + [0,2,0], + [0,0,0]], dtype=dtype) + A = self.spcreator(D) + + M,N = D.shape + + for i in range(-M, M): + for j in range(-N, N): + assert_equal(A[i,j], D[i,j]) + + assert_equal(type(A[1,1]), dtype) + + for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]: + assert_raises((IndexError, TypeError), A.__getitem__, ij) + + for dtype in supported_dtypes: + check(np.dtype(dtype)) + + def test_setelement(self): + def check(dtype): + A = self.spcreator((3,4), dtype=dtype) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[0, 0] = dtype.type(0) # bug 870 + A[1, 2] = dtype.type(4.0) + A[0, 1] = dtype.type(3) + A[2, 0] = dtype.type(2.0) + A[0,-1] = dtype.type(8) + A[-1,-2] = dtype.type(7) + A[0, 1] = dtype.type(5) + + if dtype != np.bool_: + assert_array_equal( + A.toarray(), + [ + [0, 5, 0, 8], + [0, 0, 4, 0], + [2, 0, 7, 0] + ] + ) + + for ij in [(0,4),(-1,4),(3,0),(3,4),(3,-1)]: + assert_raises(IndexError, A.__setitem__, ij, 123.0) + + for v in [[1,2,3], array([1,2,3])]: + assert_raises(ValueError, A.__setitem__, (0,0), v) + + if (not np.issubdtype(dtype, np.complexfloating) and + dtype != np.bool_): + for v in [3j]: + assert_raises(TypeError, A.__setitem__, (0,0), v) + + for dtype in supported_dtypes: + check(np.dtype(dtype)) + + def test_negative_index_assignment(self): + # Regression test for GitHub issue 4428. + + def check(dtype): + A = self.spcreator((3, 10), dtype=dtype) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[0, -4] = 1 + assert_equal(A[0, -4], 1) + + for dtype in self.math_dtypes: + check(np.dtype(dtype)) + + def test_scalar_assign_2(self): + n, m = (5, 10) + + def _test_set(i, j, nitems): + msg = f"{i!r} ; {j!r} ; {nitems!r}" + A = self.spcreator((n, m)) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[i, j] = 1 + assert_almost_equal(A.sum(), nitems, err_msg=msg) + assert_almost_equal(A[i, j], 1, err_msg=msg) + + # [i,j] + for i, j in [(2, 3), (-1, 8), (-1, -2), (array(-1), -2), (-1, array(-2)), + (array(-1), array(-2))]: + _test_set(i, j, 1) + + def test_index_scalar_assign(self): + A = self.spcreator((5, 5)) + B = np.zeros((5, 5)) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + for C in [A, B]: + C[0,1] = 1 + C[3,0] = 4 + C[3,0] = 9 + assert_array_equal(A.toarray(), B) + + +@pytest.mark.thread_unsafe +class _TestSolve: + def test_solve(self): + # Test whether the lu_solve command segfaults, as reported by Nils + # Wagner for a 64-bit machine, 02 March 2005 (EJS) + n = 20 + np.random.seed(0) # make tests repeatable + A = zeros((n,n), dtype=complex) + x = np.random.rand(n) + y = np.random.rand(n-1)+1j*np.random.rand(n-1) + r = np.random.rand(n) + for i in range(len(x)): + A[i,i] = x[i] + for i in range(len(y)): + A[i,i+1] = y[i] + A[i+1,i] = conjugate(y[i]) + A = self.spcreator(A) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, + "splu converted its input to CSC format") + x = splu(A).solve(r) + assert_almost_equal(A @ x,r) + + +class _TestSlicing: + def test_dtype_preservation(self): + assert_equal(self.spcreator((1,10), dtype=np.int16)[0,1:5].dtype, np.int16) + assert_equal(self.spcreator((1,10), dtype=np.int32)[0,1:5].dtype, np.int32) + assert_equal(self.spcreator((1,10), dtype=np.float32)[0,1:5].dtype, np.float32) + assert_equal(self.spcreator((1,10), dtype=np.float64)[0,1:5].dtype, np.float64) + + def test_dtype_preservation_empty_slice(self): + # This should be parametrized with pytest, but something in the parent + # class creation used in this file breaks pytest.mark.parametrize. + for dt in [np.int16, np.int32, np.float32, np.float64]: + A = self.spcreator((3, 2), dtype=dt) + assert_equal(A[:, 0:0:2].dtype, dt) + assert_equal(A[0:0:2, :].dtype, dt) + assert_equal(A[0, 0:0:2].dtype, dt) + assert_equal(A[0:0:2, 0].dtype, dt) + + def test_get_horiz_slice(self): + B = self.asdense(arange(50.).reshape(5,10)) + A = self.spcreator(B) + r0, r1, r2 = (0, 1, 2) if self.is_array_test else ([0], [1], [2]) + assert_array_equal(B[r1, :], A[1, :].toarray()) + assert_array_equal(B[r1, 2:5], A[1, 2:5].toarray()) + + C = self.asdense([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]]) + D = self.spcreator(C) + assert_array_equal(C[r1, 1:3], D[1, 1:3].toarray()) + + # Now test slicing when a row contains only zeros + E = self.asdense([[1, 2, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]]) + F = self.spcreator(E) + assert_array_equal(E[r1, 1:3], F[1, 1:3].toarray()) + assert_array_equal(E[r2, -2:], F[2, -2:].toarray()) + + # The following should raise exceptions: + assert_raises(IndexError, A.__getitem__, (slice(None), 11)) + assert_raises(IndexError, A.__getitem__, (6, slice(3, 7))) + + def test_get_vert_slice(self): + B = arange(50.).reshape(5, 10) + A = self.spcreator(B) + c0, c1, c2 = (0, 1, 2) if self.is_array_test else ([0], [1], [2]) + assert_array_equal(B[2:5, c0], A[2:5, 0].toarray()) + assert_array_equal(B[:, c1], A[:, 1].toarray()) + + C = array([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]]) + D = self.spcreator(C) + assert_array_equal(C[1:3, c1], D[1:3, 1].toarray()) + assert_array_equal(C[:, c2], D[:, 2].toarray()) + + # Now test slicing when a column contains only zeros + E = array([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]]) + F = self.spcreator(E) + assert_array_equal(E[:, c1], F[:, 1].toarray()) + assert_array_equal(E[-2:, c2], F[-2:, 2].toarray()) + + # The following should raise exceptions: + assert_raises(IndexError, A.__getitem__, (slice(None), 11)) + assert_raises(IndexError, A.__getitem__, (6, slice(3, 7))) + + def test_get_slices(self): + B = arange(50.).reshape(5, 10) + A = self.spcreator(B) + assert_array_equal(A[2:5, 0:3].toarray(), B[2:5, 0:3]) + assert_array_equal(A[1:, :-1].toarray(), B[1:, :-1]) + assert_array_equal(A[:-1, 1:].toarray(), B[:-1, 1:]) + + # Now test slicing when a column contains only zeros + E = array([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]]) + F = self.spcreator(E) + assert_array_equal(E[1:2, 1:2], F[1:2, 1:2].toarray()) + assert_array_equal(E[:, 1:], F[:, 1:].toarray()) + + def test_non_unit_stride_2d_indexing(self): + # Regression test -- used to silently ignore the stride. + v0 = np.random.rand(50, 50) + try: + v = self.spcreator(v0)[0:25:2, 2:30:3] + except ValueError: + # if unsupported + raise pytest.skip("feature not implemented") + + assert_array_equal(v.toarray(), v0[0:25:2, 2:30:3]) + + def test_slicing_2(self): + B = self.asdense(arange(50).reshape(5,10)) + A = self.spcreator(B) + + # [i,j] + assert_equal(A[2,3], B[2,3]) + assert_equal(A[-1,8], B[-1,8]) + assert_equal(A[-1,-2],B[-1,-2]) + assert_equal(A[array(-1),-2],B[-1,-2]) + assert_equal(A[-1,array(-2)],B[-1,-2]) + assert_equal(A[array(-1),array(-2)],B[-1,-2]) + + # [i,1:2] + assert_equal(A[2, :].toarray(), B[2, :]) + assert_equal(A[2, 5:-2].toarray(), B[2, 5:-2]) + assert_equal(A[array(2), 5:-2].toarray(), B[2, 5:-2]) + + # [1:2,j] + assert_equal(A[:, 2].toarray(), B[:, 2]) + assert_equal(A[3:4, 9].toarray(), B[3:4, 9]) + assert_equal(A[1:4, -5].toarray(), B[1:4, -5]) + assert_equal(A[2:-1, 3].toarray(), B[2:-1, 3]) + assert_equal(A[2:-1, array(3)].toarray(), B[2:-1, 3]) + + # [1:2,1:2] + assert_equal(A[1:2, 1:2].toarray(), B[1:2, 1:2]) + assert_equal(A[4:, 3:].toarray(), B[4:, 3:]) + assert_equal(A[:4, :5].toarray(), B[:4, :5]) + assert_equal(A[2:-1, :5].toarray(), B[2:-1, :5]) + + # [i] + assert_equal(A[1, :].toarray(), B[1, :]) + assert_equal(A[-2, :].toarray(), B[-2, :]) + assert_equal(A[array(-2), :].toarray(), B[-2, :]) + + # [1:2] + assert_equal(A[1:4].toarray(), B[1:4]) + assert_equal(A[1:-2].toarray(), B[1:-2]) + + # Check bug reported by Robert Cimrman: + # http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link) + s = slice(int8(2),int8(4),None) + assert_equal(A[s, :].toarray(), B[2:4, :]) + assert_equal(A[:, s].toarray(), B[:, 2:4]) + + @pytest.mark.fail_slow(2) + def test_slicing_3(self): + B = self.asdense(arange(50).reshape(5,10)) + A = self.spcreator(B) + + s_ = np.s_ + slices = [s_[:2], s_[1:2], s_[3:], s_[3::2], + s_[15:20], s_[3:2], + s_[8:3:-1], s_[4::-2], s_[:5:-1], + 0, 1, s_[:], s_[1:5], -1, -2, -5, + array(-1), np.int8(-3)] + + def check_1(a): + x = A[a] + y = B[a] + if y.shape == (): + assert_equal(x, y, repr(a)) + else: + if x.size == 0 and y.size == 0: + pass + else: + assert_array_equal(x.toarray(), y, repr(a)) + + for j, a in enumerate(slices): + check_1(a) + + def check_2(a, b): + # Indexing np.matrix with 0-d arrays seems to be broken, + # as they seem not to be treated as scalars. + # https://github.com/numpy/numpy/issues/3110 + if isinstance(a, np.ndarray): + ai = int(a) + else: + ai = a + if isinstance(b, np.ndarray): + bi = int(b) + else: + bi = b + + x = A[a, b] + y = B[ai, bi] + + if y.shape == (): + assert_equal(x, y, repr((a, b))) + else: + if x.size == 0 and y.size == 0: + pass + else: + assert_array_equal(x.toarray(), y, repr((a, b))) + + for i, a in enumerate(slices): + for j, b in enumerate(slices): + check_2(a, b) + + # Check out of bounds etc. systematically + extra_slices = [] + for a, b, c in itertools.product(*([(None, 0, 1, 2, 5, 15, + -1, -2, 5, -15)]*3)): + if c == 0: + continue + extra_slices.append(slice(a, b, c)) + + for a in extra_slices: + check_2(a, a) + check_2(a, -2) + check_2(-2, a) + + def test_None_slicing(self): + B = self.asdense(arange(50).reshape(5,10)) + A = self.spcreator(B) + + assert A[1, 2].ndim == 0 + assert A[None, 1, 2:4].shape == (1, 2) + assert A[None, 1, 2, None].shape == (1, 1) + + # see gh-22458 + assert A[None, 1].shape == (1, 10) + assert A[1, None].shape == (1, 10) + assert A[None, 1, :].shape == (1, 10) + assert A[1, None, :].shape == (1, 10) + assert A[1, :, None].shape == (10, 1) + + assert A[None, 1:3, 2].shape == B[None, 1:3, 2].shape == (1, 2) + assert A[1:3, None, 2].shape == B[1:3, None, 2].shape == (2, 1) + assert A[1:3, 2, None].shape == B[1:3, 2, None].shape == (2, 1) + assert A[None, 1, 2:4].shape == B[None, 1, 2:4].shape == (1, 2) + assert A[1, None, 2:4].shape == B[1, None, 2:4].shape == (1, 2) + assert A[1, 2:4, None].shape == B[1, 2:4, None].shape == (2, 1) + + # different for spmatrix + if self.is_array_test: + assert A[1:3, 2].shape == B[1:3, 2].shape == (2,) + assert A[1, 2:4].shape == B[1, 2:4].shape == (2,) + assert A[None, 1, 2].shape == B[None, 1, 2].shape == (1,) + assert A[1, None, 2].shape == B[1, None, 2].shape == (1,) + assert A[1, 2, None].shape == B[1, 2, None].shape == (1,) + else: + assert A[1, 2:4].shape == B[1, 2:4].shape == (1, 2) + assert A[1:3, 2].shape == B[1:3, 2].shape == (2, 1) + assert A[None, 1, 2].shape == B[None, 1, 2].shape == (1, 1) + assert A[1, None, 2].shape == B[1, None, 2].shape == (1, 1) + assert A[1, 2, None].shape == B[1, 2, None].shape == (1, 1) + + def test_ellipsis_slicing(self): + b = self.asdense(arange(50).reshape(5,10)) + a = self.spcreator(b) + + assert_array_equal(a[...].toarray(), b[...]) + assert_array_equal(a[...,].toarray(), b[...,]) + + assert_array_equal(a[4, ...].toarray(), b[4, ...]) + assert_array_equal(a[..., 4].toarray(), b[..., 4]) + assert_array_equal(a[..., 5].toarray(), b[..., 5]) + with pytest.raises(IndexError, match='index .5. out of range'): + a[5, ...] + with pytest.raises(IndexError, match='index .10. out of range'): + a[..., 10] + with pytest.raises(IndexError, match='index .5. out of range'): + a.T[..., 5] + + assert_array_equal(a[1:, ...].toarray(), b[1:, ...]) + assert_array_equal(a[..., 1:].toarray(), b[..., 1:]) + assert_array_equal(a[:2, ...].toarray(), b[:2, ...]) + assert_array_equal(a[..., :2].toarray(), b[..., :2]) + + # check slice limit outside range + assert_array_equal(a[:5, ...].toarray(), b[:5, ...]) + assert_array_equal(a[..., :5].toarray(), b[..., :5]) + assert_array_equal(a[5:, ...].toarray(), b[5:, ...]) + assert_array_equal(a[..., 5:].toarray(), b[..., 5:]) + assert_array_equal(a[10:, ...].toarray(), b[10:, ...]) + assert_array_equal(a[..., 10:].toarray(), b[..., 10:]) + + # ellipsis should be ignored + assert_array_equal(a[1:, 1, ...].toarray(), b[1:, 1, ...]) + assert_array_equal(a[1, ..., 1:].toarray(), b[1, ..., 1:]) + assert_array_equal(a[..., 1, 1:].toarray(), b[1, ..., 1:]) + assert_array_equal(a[:2, 1, ...].toarray(), b[:2, 1, ...]) + assert_array_equal(a[1, ..., :2].toarray(), b[1, ..., :2]) + assert_array_equal(a[..., 1, :2].toarray(), b[1, ..., :2]) + # These return ints + assert_equal(a[1, 1, ...], b[1, 1, ...]) + assert_equal(a[1, ..., 1], b[1, ..., 1]) + + def test_ellipsis_fancy_bool(self): + numpy_a = self.asdense(arange(50).reshape(5, 10)) + a = self.spcreator(numpy_a) + + ix5 = [True, False, True, False, True] + ix10 = [False] * 5 + ix5 # same number of True values as ix5 + ix10_6True = ix5 + ix5 # not same number of True values as ix5 + full_ix = [ix10] * 5 + + assert_array_equal(toarray(a[full_ix, ...]), numpy_a[full_ix, ...]) + assert_array_equal(toarray(a[..., full_ix]), numpy_a[..., full_ix]) + + assert_array_equal(toarray(a[ix5, ...]), numpy_a[ix5, ...]) + assert_array_equal(toarray(a[..., ix10]), numpy_a[..., ix10]) + + assert_array_equal(toarray(a[ix5, ..., ix10]), numpy_a[ix5, ..., ix10]) + assert_array_equal(toarray(a[..., ix5, ix10]), numpy_a[..., ix5, ix10]) + assert_array_equal(toarray(a[ix5, ix10, ...]), numpy_a[ix5, ix10, ...]) + + with assert_raises(ValueError, match="shape mismatch"): + a[ix5, ix10_6True] + + def test_ellipsis_fancy_slicing(self): + b = self.asdense(arange(50).reshape(5, 10)) + a = self.spcreator(b) + + assert_array_equal(a[[4], ...].toarray(), b[[4], ...]) + assert_array_equal(a[[2, 4], ...].toarray(), b[[2, 4], ...]) + assert_array_equal(a[..., [4]].toarray(), b[..., [4]]) + assert_array_equal(a[..., [2, 4]].toarray(), b[..., [2, 4]]) + + assert_array_equal(a[[4], 1, ...].toarray(), b[[4], 1, ...]) + assert_array_equal(a[[2, 4], 1, ...].toarray(), b[[2, 4], 1, ...]) + assert_array_equal(a[[4], ..., 1].toarray(), b[[4], ..., 1]) + assert_array_equal(a[..., [4], 1].toarray(), b[..., [4], 1]) + # fancy index gives dense + assert_array_equal(toarray(a[[2, 4], ..., [2, 4]]), b[[2, 4], ..., [2, 4]]) + assert_array_equal(toarray(a[..., [2, 4], [2, 4]]), b[..., [2, 4], [2, 4]]) + + def test_multiple_ellipsis_slicing(self): + a = self.spcreator(arange(6).reshape(3, 2)) + + with pytest.raises(IndexError, + match='an index can only have a single ellipsis'): + a[..., ...] + with pytest.raises(IndexError, + match='an index can only have a single ellipsis'): + a[..., 1, ...] + + +class _TestSlicingAssign: + def test_slice_scalar_assign(self): + A = self.spcreator((5, 5)) + B = np.zeros((5, 5)) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + for C in [A, B]: + C[0:1,1] = 1 + C[3:0,0] = 4 + C[3:4,0] = 9 + C[0,4:] = 1 + C[3::-1,4:] = 9 + assert_array_equal(A.toarray(), B) + + def test_slice_assign_2(self): + n, m = (5, 10) + + def _test_set(i, j): + msg = f"i={i!r}; j={j!r}" + A = self.spcreator((n, m)) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[i, j] = 1 + B = np.zeros((n, m)) + B[i, j] = 1 + assert_array_almost_equal(A.toarray(), B, err_msg=msg) + # [i,1:2] + for i, j in [(2, slice(3)), (2, slice(None, 10, 4)), (2, slice(5, -2)), + (array(2), slice(5, -2))]: + _test_set(i, j) + + def test_self_self_assignment(self): + # Tests whether a row of one sparse array can be assigned to another. + B = self.spcreator((4,3)) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + B[0,0] = 2 + B[1,2] = 7 + B[2,1] = 3 + B[3,0] = 10 + + A = B / 10 + B[0,:] = A[0,:] + assert_array_equal(A[0,:].toarray(), B[0,:].toarray()) + + A = B / 10 + B[:,:] = A[:1,:1] + assert_array_equal(np.zeros((4,3)) + A[0,0], B.toarray()) + + A = B / 10 + B[:-1,0] = A[None,0,:].T + assert_array_equal(A[0,:].toarray().T, B[:-1,0].toarray()) + + def test_slice_assignment(self): + B = self.spcreator((4,3)) + expected = array([[10,0,0], + [0,0,6], + [0,14,0], + [0,0,0]]) + block = [[1,0],[0,4]] + + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + B[0,0] = 5 + B[1,2] = 3 + B[2,1] = 7 + B[:,:] = B+B + assert_array_equal(B.toarray(), expected) + + B[:2,:2] = self.csc_container(array(block)) + assert_array_equal(B.toarray()[:2, :2], block) + + def test_sparsity_modifying_assignment(self): + B = self.spcreator((4,3)) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + B[0,0] = 5 + B[1,2] = 3 + B[2,1] = 7 + B[3,0] = 10 + B[:3] = self.csr_container(np.eye(3)) + + expected = array([[1,0,0],[0,1,0],[0,0,1],[10,0,0]]) + assert_array_equal(B.toarray(), expected) + + def test_set_slice(self): + A = self.spcreator((5,10)) + B = array(zeros((5, 10), float)) + s_ = np.s_ + slices = [s_[:2], s_[1:2], s_[3:], s_[3::2], + s_[8:3:-1], s_[4::-2], s_[:5:-1], + 0, 1, s_[:], s_[1:5], -1, -2, -5, + array(-1), np.int8(-3)] + + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + for j, a in enumerate(slices): + A[a] = j + B[a] = j + assert_array_equal(A.toarray(), B, repr(a)) + + for i, a in enumerate(slices): + for j, b in enumerate(slices): + A[a,b] = 10*i + 1000*(j+1) + B[a,b] = 10*i + 1000*(j+1) + assert_array_equal(A.toarray(), B, repr((a, b))) + + A[0, 1:10:2] = range(1, 10, 2) + B[0, 1:10:2] = range(1, 10, 2) + assert_array_equal(A.toarray(), B) + A[1:5:2, 0] = np.arange(1, 5, 2)[:, None] + B[1:5:2, 0] = np.arange(1, 5, 2)[:] + assert_array_equal(A.toarray(), B) + + # The next commands should raise exceptions + assert_raises(ValueError, A.__setitem__, (0, 0), list(range(100))) + assert_raises(ValueError, A.__setitem__, (0, 0), arange(100)) + assert_raises(ValueError, A.__setitem__, (0, slice(None)), + list(range(100))) + assert_raises(ValueError, A.__setitem__, (slice(None), 1), + list(range(100))) + assert_raises(ValueError, A.__setitem__, (slice(None), 1), A.copy()) + assert_raises(ValueError, A.__setitem__, + ([[1, 2, 3], [0, 3, 4]], [1, 2, 3]), [1, 2, 3, 4]) + assert_raises(ValueError, A.__setitem__, + ([[1, 2, 3], [0, 3, 4], [4, 1, 3]], + [[1, 2, 4], [0, 1, 3]]), [2, 3, 4]) + assert_raises(ValueError, A.__setitem__, (slice(4), 0), + [[1, 2], [3, 4]]) + + def test_assign_empty(self): + A = self.spcreator(np.ones((2, 3))) + B = self.spcreator((1, 2)) + A[1, :2] = B + assert_array_equal(A.toarray(), [[1, 1, 1], [0, 0, 1]]) + + def test_assign_1d_slice(self): + A = self.spcreator(np.ones((3, 3))) + x = np.zeros(3) + A[:, 0] = x + A[1, :] = x + assert_array_equal(A.toarray(), [[0, 1, 1], [0, 0, 0], [0, 1, 1]]) + + +class _TestFancyIndexing: + """Tests fancy indexing features. The tests for any matrix formats + that implement these features should derive from this class. + """ + + def test_dtype_preservation_empty_index(self): + # This should be parametrized with pytest, but something in the parent + # class creation used in this file breaks pytest.mark.parametrize. + for dt in [np.int16, np.int32, np.float32, np.float64]: + A = self.spcreator((3, 2), dtype=dt) + assert_equal(A[:, [False, False]].dtype, dt) + assert_equal(A[[False, False, False], :].dtype, dt) + assert_equal(A[:, []].dtype, dt) + assert_equal(A[[], :].dtype, dt) + + def test_bad_index(self): + A = self.spcreator(np.zeros([5, 5])) + assert_raises((IndexError, ValueError, TypeError), A.__getitem__, "foo") + assert_raises((IndexError, ValueError, TypeError), A.__getitem__, (2, "foo")) + assert_raises((IndexError, ValueError), A.__getitem__, + ([1, 2, 3], [1, 2, 3, 4])) + + def test_fancy_indexing(self): + B = self.asdense(arange(50).reshape(5,10)) + A = self.spcreator(B) + + # [i] + assert_equal(A[[3]].toarray(), B[[3]]) + assert_equal(A[[1, 3]].toarray(), B[[1, 3]]) + + # [i,[1,2]] + assert_equal(A[3, [3]].toarray(), B[3, [3]]) + assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]]) + assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]]) + assert_equal(A[array(-1), [2, -5]].toarray(), B[-1, [2, -5]]) + assert_equal(A[-1, array([2, -5])].toarray(), B[-1, [2, -5]]) + assert_equal(A[array(-1), array([2, -5])].toarray(), B[-1, [2, -5]]) + + # [1:2,[1,2]] + assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]]) + assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]]) + assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]]) + assert_equal(A[1:4, array([-1, -5])].toarray(), B[1:4, [-1, -5]]) + + # [[1,2],j] + assert_equal(A[[3], 3].toarray(), B[[3], 3]) + assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3]) + assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4]) + assert_equal(A[array([2, -5]), -4].toarray(), B[[2, -5], -4]) + assert_equal(A[[2, -5], array(-4)].toarray(), B[[2, -5], -4]) + assert_equal(A[array([2, -5]), array(-4)].toarray(), B[[2, -5], -4]) + + # [[1,2],1:2] + assert_equal(A[[3], :].toarray(), B[[3], :]) + assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :]) + assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1]) + assert_equal(A[array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1]) + + # [[1,2],[1,2]] + assert_equal(toarray(A[[3], [4]]), B[[3], [4]]) + assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]]) + assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]]) + assert_equal( + toarray(A[array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]] + ) + assert_equal( + toarray(A[[-1, -3], array([2, -4])]), B[[-1, -3], [2, -4]] + ) + assert_equal( + toarray(A[array([-1, -3]), array([2, -4])]), B[[-1, -3], [2, -4]] + ) + + # [[[1],[2]],[1,2]] + assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]]) + assert_equal( + A[[[-1], [-3], [-2]], [2, -4]].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + assert_equal( + A[array([[-1], [-3], [-2]]), [2, -4]].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + assert_equal( + A[[[-1], [-3], [-2]], array([2, -4])].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + assert_equal( + A[array([[-1], [-3], [-2]]), array([2, -4])].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + + # [[1,2]] + assert_equal(A[[1, 3]].toarray(), B[[1, 3]]) + assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]]) + assert_equal(A[array([-1, -3])].toarray(), B[[-1, -3]]) + + # [[1,2],:][:,[1,2]] + assert_equal(A[[3], :][:, [4]].toarray(), B[[3], :][:, [4]]) + assert_equal( + A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]] + ) + assert_equal( + A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]] + ) + assert_equal( + A[array([-1, -3]), :][:, array([2, -4])].toarray(), + B[[-1, -3], :][:, [2, -4]] + ) + + # [1,[[1,2]]][[[1,2]],1] + assert_equal( + A[1, [[1, 3]]][[[0, 0]], 1].toarray(), B[1, [[1, 3]]][[[0, 0]], 1] + ) + assert_equal( + A[1, [[-1, -3]]][[[0, -1]], 1].toarray(), B[1, [[-1, -3]]][[[0, -1]], 1] + ) + # [:1,[[1,2]]][[[1,2]],:1] + with pytest.raises(IndexError, match="Only 1D or 2D arrays allowed"): + A[:1, [[1, 3]]] + with pytest.raises(IndexError, match="Only 1D or 2D arrays allowed"): + A[[[0, 0]], :1] + + # [:,[1,2]][[1,2],:] + assert_equal( + A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :] + ) + assert_equal( + A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :] + ) + assert_equal( + A[:, array([-1, -3])][array([2, -4]), :].toarray(), + B[:, [-1, -3]][[2, -4], :] + ) + + # Check bug reported by Robert Cimrman: + # http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link) + s = slice(int8(2),int8(4),None) + assert_equal(A[s, :].toarray(), B[2:4, :]) + assert_equal(A[:, s].toarray(), B[:, 2:4]) + + # Regression for gh-4917: index with tuple of 2D arrays + i = np.array([[1]], dtype=int) + assert_equal(A[i, i].toarray(), B[i, i]) + + # Regression for gh-4917: index with tuple of empty nested lists + assert_equal(A[[[]], [[]]].toarray(), B[[[]], [[]]]) + + def test_fancy_indexing_randomized(self): + np.random.seed(1234) # make runs repeatable + + NUM_SAMPLES = 50 + M = 6 + N = 4 + + D = self.asdense(np.random.rand(M,N)) + D = np.multiply(D, D > 0.5) + + I = np.random.randint(-M + 1, M, size=NUM_SAMPLES) + J = np.random.randint(-N + 1, N, size=NUM_SAMPLES) + + S = self.spcreator(D) + + SIJ = S[I,J] + if issparse(SIJ): + SIJ = SIJ.toarray() + assert_equal(SIJ, D[I,J]) + + I_bad = I + M + J_bad = J - N + + assert_raises(IndexError, S.__getitem__, (I_bad,J)) + assert_raises(IndexError, S.__getitem__, (I,J_bad)) + + def test_missized_masking(self): + M, N = 5, 10 + + B = self.asdense(arange(M * N).reshape(M, N)) + A = self.spcreator(B) + + # Content of mask shouldn't matter, only its size + row_long = np.ones(M + 1, dtype=bool) + row_short = np.ones(M - 1, dtype=bool) + col_long = np.ones(N + 2, dtype=bool) + col_short = np.ones(N - 2, dtype=bool) + + match="bool index .* has shape .* instead of .*" + for i, j in itertools.product( + (row_long, row_short, slice(None)), + (col_long, col_short, slice(None)), + ): + if isinstance(i, slice) and isinstance(j, slice): + continue + with pytest.raises(IndexError, match=match): + _ = A[i, j] + + def test_fancy_indexing_boolean(self): + np.random.seed(1234) # make runs repeatable + + B = self.asdense(arange(50).reshape(5,10)) + A = self.spcreator(B) + + I = np.array(np.random.randint(0, 2, size=5), dtype=bool) + J = np.array(np.random.randint(0, 2, size=10), dtype=bool) + X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool) + + assert_equal(toarray(A[I]), B[I]) + assert_equal(toarray(A[:, J]), B[:, J]) + assert_equal(toarray(A[X]), B[X]) + assert_equal(toarray(A[B > 9]), B[B > 9]) + + I = np.array([True, False, True, True, False]) + J = np.array([False, True, True, False, True, + False, False, False, False, False]) + + assert_equal(toarray(A[I, J]), B[I, J]) + + Z1 = np.zeros((6, 11), dtype=bool) + Z2 = np.zeros((6, 11), dtype=bool) + Z2[0,-1] = True + Z3 = np.zeros((6, 11), dtype=bool) + Z3[-1,0] = True + + assert_raises(IndexError, A.__getitem__, Z1) + assert_raises(IndexError, A.__getitem__, Z2) + assert_raises(IndexError, A.__getitem__, Z3) + assert_raises((IndexError, ValueError), A.__getitem__, (X, 1)) + + def test_fancy_indexing_sparse_boolean(self): + np.random.seed(1234) # make runs repeatable + + B = self.asdense(arange(50).reshape(5,10)) + A = self.spcreator(B) + + X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool) + + Xsp = self.csr_container(X) + + assert_equal(toarray(A[Xsp]), B[X]) + assert_equal(toarray(A[A > 9]), B[B > 9]) + + Z = np.array(np.random.randint(0, 2, size=(5, 11)), dtype=bool) + Y = np.array(np.random.randint(0, 2, size=(6, 10)), dtype=bool) + + Zsp = self.csr_container(Z) + Ysp = self.csr_container(Y) + + assert_raises(IndexError, A.__getitem__, Zsp) + assert_raises(IndexError, A.__getitem__, Ysp) + assert_raises((IndexError, ValueError), A.__getitem__, (Xsp, 1)) + + def test_fancy_indexing_regression_3087(self): + mat = self.spcreator(array([[1, 0, 0], [0,1,0], [1,0,0]])) + desired_cols = np.ravel(mat.sum(0)) > 0 + assert_equal(mat[:, desired_cols].toarray(), [[1, 0], [0, 1], [1, 0]]) + + def test_fancy_indexing_seq_assign(self): + mat = self.spcreator(array([[1, 0], [0, 1]])) + assert_raises(ValueError, mat.__setitem__, (0, 0), np.array([1,2])) + + def test_fancy_indexing_2d_assign(self): + # regression test for gh-10695 + mat = self.spcreator(array([[1, 0], [2, 3]])) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + mat[[0, 1], [1, 1]] = mat[[1, 0], [0, 0]] + assert_equal(toarray(mat), array([[1, 2], [2, 1]])) + + def test_fancy_indexing_empty(self): + B = self.asdense(arange(50).reshape(5,10)) + B[1,:] = 0 + B[:,2] = 0 + B[3,6] = 0 + A = self.spcreator(B) + + K = np.array([False, False, False, False, False]) + assert_equal(toarray(A[K]), B[K]) + K = np.array([], dtype=int) + assert_equal(toarray(A[K]), B[K]) + assert_equal(toarray(A[K, K]), B[K, K]) + J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None] + assert_equal(toarray(A[K, J]), B[K, J]) + assert_equal(toarray(A[J, K]), B[J, K]) + + +@contextlib.contextmanager +def check_remains_sorted(X): + """Checks that sorted indices property is retained through an operation + """ + if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices: + yield + return + yield + indices = X.indices.copy() + X.has_sorted_indices = False + X.sort_indices() + assert_array_equal(indices, X.indices, + 'Expected sorted indices, found unsorted') + + +class _TestFancyIndexingAssign: + def test_bad_index_assign(self): + A = self.spcreator(np.zeros([5, 5])) + assert_raises((IndexError, ValueError, TypeError), A.__setitem__, "foo", 2) + assert_raises((IndexError, ValueError, TypeError), A.__setitem__, (2, "foo"), 5) + + def test_fancy_indexing_set(self): + n, m = (5, 10) + + def _test_set_slice(i, j): + A = self.spcreator((n, m)) + B = self.asdense(np.zeros((n, m))) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + B[i, j] = 1 + with check_remains_sorted(A): + A[i, j] = 1 + assert_array_almost_equal(A.toarray(), B) + # [1:2,1:2] + for i, j in [((2, 3, 4), slice(None, 10, 4)), + (np.arange(3), slice(5, -2)), + (slice(2, 5), slice(5, -2))]: + _test_set_slice(i, j) + for i, j in [(np.arange(3), np.arange(3)), ((0, 3, 4), (1, 2, 4))]: + _test_set_slice(i, j) + + def test_fancy_assignment_dtypes(self): + def check(dtype): + A = self.spcreator((5, 5), dtype=dtype) + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[[0,1],[0,1]] = dtype.type(1) + assert_equal(A.sum(), dtype.type(1)*2) + A[0:2,0:2] = dtype.type(1.0) + assert_equal(A.sum(), dtype.type(1)*4) + A[2,2] = dtype.type(1.0) + assert_equal(A.sum(), dtype.type(1)*4 + dtype.type(1)) + + for dtype in supported_dtypes: + check(np.dtype(dtype)) + + def test_sequence_assignment(self): + A = self.spcreator((4,3)) + B = self.spcreator(eye(3,4)) + + i0 = [0,1,2] + i1 = (0,1,2) + i2 = array(i0) + + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + with check_remains_sorted(A): + A[0,i0] = B[i0,0].T + A[1,i1] = B[i1,1].T + A[2,i2] = B[i2,2].T + assert_array_equal(A.toarray(), B.T.toarray()) + + # column slice + A = self.spcreator((2,3)) + with check_remains_sorted(A): + A[1,1:3] = [10,20] + assert_array_equal(A.toarray(), [[0, 0, 0], [0, 10, 20]]) + + # row slice + A = self.spcreator((3,2)) + with check_remains_sorted(A): + A[1:3,1] = [[10],[20]] + assert_array_equal(A.toarray(), [[0, 0], [0, 10], [0, 20]]) + + # both slices + A = self.spcreator((3,3)) + B = self.asdense(np.zeros((3,3))) + with check_remains_sorted(A): + for C in [A, B]: + C[[0,1,2], [0,1,2]] = [4,5,6] + assert_array_equal(A.toarray(), B) + + # both slices (2) + A = self.spcreator((4, 3)) + with check_remains_sorted(A): + A[(1, 2, 3), (0, 1, 2)] = [1, 2, 3] + assert_almost_equal(A.sum(), 6) + B = self.asdense(np.zeros((4, 3))) + B[(1, 2, 3), (0, 1, 2)] = [1, 2, 3] + assert_array_equal(A.toarray(), B) + + def test_fancy_assign_empty(self): + B = self.asdense(arange(50).reshape(5,10)) + B[1,:] = 0 + B[:,2] = 0 + B[3,6] = 0 + A = self.spcreator(B) + + K = np.array([False, False, False, False, False]) + A[K] = 42 + assert_equal(toarray(A), B) + + K = np.array([], dtype=int) + A[K] = 42 + assert_equal(toarray(A), B) + A[K,K] = 42 + assert_equal(toarray(A), B) + + J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None] + A[K,J] = 42 + assert_equal(toarray(A), B) + A[J,K] = 42 + assert_equal(toarray(A), B) + + +class _TestFancyMultidim: + def test_fancy_indexing_ndarray(self): + sets = [ + (np.array([[1], [2], [3]]), np.array([3, 4, 2])), + (np.array([[1], [2], [3]]), np.array([[3, 4, 2]])), + (np.array([[1, 2, 3]]), np.array([[3], [4], [2]])), + (np.array([1, 2, 3]), np.array([[3], [4], [2]])), + (np.array([[1, 2, 3], [3, 4, 2]]), + np.array([[5, 6, 3], [2, 3, 1]])) + ] + # These inputs generate 3-D outputs + # (np.array([[[1], [2], [3]], [[3], [4], [2]]]), + # np.array([[[5], [6], [3]], [[2], [3], [1]]])), + + for I, J in sets: + np.random.seed(1234) + D = self.asdense(np.random.rand(5, 7)) + S = self.spcreator(D) + + SIJ = S[I,J] + if issparse(SIJ): + SIJ = SIJ.toarray() + assert_equal(SIJ, D[I,J]) + + I_bad = I + 5 + J_bad = J + 7 + + assert_raises(IndexError, S.__getitem__, (I_bad,J)) + assert_raises(IndexError, S.__getitem__, (I,J_bad)) + + # This would generate 3-D arrays -- not supported + assert_raises(IndexError, S.__getitem__, ([I, I], slice(None))) + assert_raises(IndexError, S.__getitem__, (slice(None), [J, J])) + + +class _TestFancyMultidimAssign: + def test_fancy_assign_ndarray(self): + np.random.seed(1234) + + D = self.asdense(np.random.rand(5, 7)) + S = self.spcreator(D) + X = np.random.rand(2, 3) + + I = np.array([[1, 2, 3], [3, 4, 2]]) + J = np.array([[5, 6, 3], [2, 3, 1]]) + + with check_remains_sorted(S): + S[I,J] = X + D[I,J] = X + assert_equal(S.toarray(), D) + + I_bad = I + 5 + J_bad = J + 7 + + C = [1, 2, 3] + + with check_remains_sorted(S): + S[I,J] = C + D[I,J] = C + assert_equal(S.toarray(), D) + + with check_remains_sorted(S): + S[I,J] = 3 + D[I,J] = 3 + assert_equal(S.toarray(), D) + + assert_raises(IndexError, S.__setitem__, (I_bad,J), C) + assert_raises(IndexError, S.__setitem__, (I,J_bad), C) + + def test_fancy_indexing_multidim_set(self): + n, m = (5, 10) + + def _test_set_slice(i, j): + A = self.spcreator((n, m)) + with check_remains_sorted(A), suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[i, j] = 1 + B = self.asdense(np.zeros((n, m))) + B[i, j] = 1 + assert_array_almost_equal(A.toarray(), B) + # [[[1, 2], [1, 2]], [1, 2]] + for i, j in [(np.array([[1, 2], [1, 3]]), [1, 3]), + (np.array([0, 4]), [[0, 3], [1, 2]]), + ([[1, 2, 3], [0, 2, 4]], [[0, 4, 3], [4, 1, 2]])]: + _test_set_slice(i, j) + + def test_fancy_assign_list(self): + np.random.seed(1234) + + D = self.asdense(np.random.rand(5, 7)) + S = self.spcreator(D) + X = np.random.rand(2, 3) + + I = [[1, 2, 3], [3, 4, 2]] + J = [[5, 6, 3], [2, 3, 1]] + + S[I,J] = X + D[I,J] = X + assert_equal(S.toarray(), D) + + I_bad = [[ii + 5 for ii in i] for i in I] + J_bad = [[jj + 7 for jj in j] for j in J] + C = [1, 2, 3] + + S[I,J] = C + D[I,J] = C + assert_equal(S.toarray(), D) + + S[I,J] = 3 + D[I,J] = 3 + assert_equal(S.toarray(), D) + + assert_raises(IndexError, S.__setitem__, (I_bad,J), C) + assert_raises(IndexError, S.__setitem__, (I,J_bad), C) + + def test_fancy_assign_slice(self): + np.random.seed(1234) + + D = self.asdense(np.random.rand(5, 7)) + S = self.spcreator(D) + + I = [1, 2, 3, 3, 4, 2] + J = [5, 6, 3, 2, 3, 1] + + I_bad = [ii + 5 for ii in I] + J_bad = [jj + 7 for jj in J] + + C1 = [1, 2, 3, 4, 5, 6, 7] + C2 = np.arange(5)[:, None] + assert_raises(IndexError, S.__setitem__, (I_bad, slice(None)), C1) + assert_raises(IndexError, S.__setitem__, (slice(None), J_bad), C2) + + +class _TestArithmetic: + """ + Test real/complex arithmetic + """ + def __arith_init(self): + # these can be represented exactly in FP (so arithmetic should be exact) + __A = array([[-1.5, 6.5, 0, 2.25, 0, 0], + [3.125, -7.875, 0.625, 0, 0, 0], + [0, 0, -0.125, 1.0, 0, 0], + [0, 0, 8.375, 0, 0, 0]], 'float64') + __B = array([[0.375, 0, 0, 0, -5, 2.5], + [14.25, -3.75, 0, 0, -0.125, 0], + [0, 7.25, 0, 0, 0, 0], + [18.5, -0.0625, 0, 0, 0, 0]], 'complex128') + __B.imag = array([[1.25, 0, 0, 0, 6, -3.875], + [2.25, 4.125, 0, 0, 0, 2.75], + [0, 4.125, 0, 0, 0, 0], + [-0.0625, 0, 0, 0, 0, 0]], 'float64') + + # fractions are all x/16ths + assert_array_equal((__A*16).astype('int32'),16*__A) + assert_array_equal((__B.real*16).astype('int32'),16*__B.real) + assert_array_equal((__B.imag*16).astype('int32'),16*__B.imag) + + __Asp = self.spcreator(__A) + __Bsp = self.spcreator(__B) + return __A, __B, __Asp, __Bsp + + @pytest.mark.fail_slow(20) + def test_add_sub(self): + __A, __B, __Asp, __Bsp = self.__arith_init() + + # basic tests + assert_array_equal( + (__Asp + __Bsp).toarray(), __A + __B + ) + + # check conversions + for x in supported_dtypes: + with np.errstate(invalid="ignore"): + A = __A.astype(x) + Asp = self.spcreator(A) + for y in supported_dtypes: + if not np.issubdtype(y, np.complexfloating): + with np.errstate(invalid="ignore"): + B = __B.real.astype(y) + else: + B = __B.astype(y) + Bsp = self.spcreator(B) + + # addition + D1 = A + B + S1 = Asp + Bsp + + assert_equal(S1.dtype,D1.dtype) + assert_array_equal(S1.toarray(), D1) + assert_array_equal(Asp + B,D1) # check sparse + dense + assert_array_equal(A + Bsp,D1) # check dense + sparse + + # subtraction + if np.dtype('bool') in [x, y]: + # boolean array subtraction deprecated in 1.9.0 + continue + + D1 = A - B + S1 = Asp - Bsp + + assert_equal(S1.dtype,D1.dtype) + assert_array_equal(S1.toarray(), D1) + assert_array_equal(Asp - B,D1) # check sparse - dense + assert_array_equal(A - Bsp,D1) # check dense - sparse + + def test_mu(self): + __A, __B, __Asp, __Bsp = self.__arith_init() + + # basic tests + assert_array_equal((__Asp @ __Bsp.T).toarray(), + __A @ __B.T) + + for x in supported_dtypes: + with np.errstate(invalid="ignore"): + A = __A.astype(x) + Asp = self.spcreator(A) + for y in supported_dtypes: + if np.issubdtype(y, np.complexfloating): + B = __B.astype(y) + else: + with np.errstate(invalid="ignore"): + B = __B.real.astype(y) + Bsp = self.spcreator(B) + + D1 = A @ B.T + S1 = Asp @ Bsp.T + + assert_allclose(S1.toarray(), D1, + atol=1e-14*abs(D1).max()) + assert_equal(S1.dtype,D1.dtype) + + +class _TestMinMax: + def test_minmax(self): + for dtype in [np.float32, np.float64, np.int32, np.int64, np.complex128]: + D = np.arange(20, dtype=dtype).reshape(5,4) + + X = self.spcreator(D) + assert_equal(X.min(), 0) + assert_equal(X.max(), 19) + assert_equal(X.min().dtype, dtype) + assert_equal(X.max().dtype, dtype) + + D *= -1 + X = self.spcreator(D) + assert_equal(X.min(), -19) + assert_equal(X.max(), 0) + + D += 5 + X = self.spcreator(D) + assert_equal(X.min(), -14) + assert_equal(X.max(), 5) + + # try a fully dense matrix + X = self.spcreator(np.arange(1, 10).reshape(3, 3)) + assert_equal(X.min(), 1) + assert_equal(X.min().dtype, X.dtype) + + X = -X + assert_equal(X.max(), -1) + + # and a fully sparse matrix + Z = self.spcreator(np.zeros((1, 1))) + assert_equal(Z.min(), 0) + assert_equal(Z.max(), 0) + assert_equal(Z.max().dtype, Z.dtype) + + # another test + D = np.arange(20, dtype=float).reshape(5,4) + D[0:2, :] = 0 + X = self.spcreator(D) + assert_equal(X.min(), 0) + assert_equal(X.max(), 19) + + # zero-size matrices + for D in [np.zeros((0, 0)), np.zeros((0, 10)), np.zeros((10, 0))]: + X = self.spcreator(D) + assert_raises(ValueError, X.min) + assert_raises(ValueError, X.max) + + def test_minmax_axis(self): + keep = not self.is_array_test + D = np.arange(50).reshape(5, 10) + # completely empty rows, leaving some completely full: + D[1, :] = 0 + # empty at end for reduceat: + D[:, 9] = 0 + # partial rows/cols: + D[3, 3] = 0 + # entries on either side of 0: + D[2, 2] = -1 + X = self.spcreator(D) + + axes_even = [0, -2] + axes_odd = [1, -1] + for axis in axes_odd + axes_even: + assert_array_equal( + X.max(axis=axis).toarray(), D.max(axis=axis, keepdims=keep) + ) + assert_array_equal( + X.min(axis=axis).toarray(), D.min(axis=axis, keepdims=keep) + ) + + for axis in axes_even: + assert_equal( + X.max(axis=axis, explicit=True).toarray(), + self.asdense([40, 41, 42, 43, 44, 45, 46, 47, 48, 0]) + ) + if np.any(X.data == 0): + # Noncanonical case + expected = self.asdense([20, 1, -1, 3, 4, 5, 0, 7, 8, 0]) + else: + expected = self.asdense([20, 1, -1, 3, 4, 5, 6, 7, 8, 0]) + assert_equal(X.min(axis=axis, explicit=True).toarray(), expected) + + for axis in axes_odd: + expected_max = np.array([8, 0, 28, 38, 48]) + expected_min = np.array([1, 0, -1, 30, 40]) + if not self.is_array_test: + expected_max = expected_max.reshape((5, 1)) + expected_min = expected_min.reshape((5, 1)) + assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max) + assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min) + + # full matrix + D = np.arange(1, 51).reshape(10, 5) + X = self.spcreator(D) + for axis in axes_odd + axes_even: + assert_array_equal( + X.max(axis=axis).toarray(), D.max(axis=axis, keepdims=keep) + ) + assert_array_equal( + X.min(axis=axis).toarray(), D.min(axis=axis, keepdims=keep) + ) + + for axis in axes_even: + expected_max = D[-1, :] + expected_min = D[0, :] + if not self.is_array_test: + expected_max = D[None, -1, :] + expected_min = D[None, 0, :] + assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max) + assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min) + for axis in axes_odd: + expected_max = D[:, -1] + expected_min = D[:, 0] + if not self.is_array_test: + expected_max = D[:, -1, None] + expected_min = D[:, 0, None] + assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max) + assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min) + + # empty matrix + D = self.asdense(np.zeros((10, 5))) + X = self.spcreator(D) + for axis in axes_even + axes_odd: + assert_equal(X.max(axis=axis, explicit=True).toarray(), D.max(axis=axis)) + assert_equal(X.min(axis=axis, explicit=True).toarray(), D.min(axis=axis)) + + # zero-size matrices + D = self.asdense(np.zeros((0, 10))) + X = self.spcreator(D) + explicit_values = [True, False] + even_explicit_pairs = list(itertools.product(axes_even, explicit_values)) + odd_explicit_pairs = list(itertools.product(axes_odd, explicit_values)) + for axis, ex in even_explicit_pairs: + assert_raises(ValueError, X.min, axis=axis, explicit=ex) + assert_raises(ValueError, X.max, axis=axis, explicit=ex) + for axis, ex in odd_explicit_pairs: + assert_equal(X.max(axis=axis, explicit=ex).toarray(), D.max(axis=axis)) + assert_equal(X.min(axis=axis, explicit=ex).toarray(), D.min(axis=axis)) + + D = self.asdense(np.zeros((10, 0))) + X = self.spcreator(D) + for axis, ex in odd_explicit_pairs: + assert_raises(ValueError, X.min, axis=axis, explicit=ex) + assert_raises(ValueError, X.max, axis=axis, explicit=ex) + for axis, ex in even_explicit_pairs: + assert_equal(X.max(axis=axis, explicit=ex).toarray(), D.max(axis=axis)) + assert_equal(X.min(axis=axis, explicit=ex).toarray(), D.min(axis=axis)) + + def test_nanminmax(self): + D = self.asdense(np.arange(50).reshape(5,10), dtype=float) + D[1, :] = 0 + D[:, 9] = 0 + D[3, 3] = 0 + D[2, 2] = -1 + D[4, 2] = np.nan + D[1, 4] = np.nan + X = self.spcreator(D) + + X_nan_maximum = X.nanmax() + assert np.isscalar(X_nan_maximum) + assert X_nan_maximum == np.nanmax(D) + + X_nan_minimum = X.nanmin() + assert np.isscalar(X_nan_minimum) + assert X_nan_minimum == np.nanmin(D) + + axes = [-2, -1, 0, 1] + for axis in axes: + X_nan_maxima = X.nanmax(axis=axis) + assert_allclose(X_nan_maxima.toarray(), np.nanmax(D, axis=axis)) + assert isinstance(X_nan_maxima, self.coo_container) + + X_nan_minima = X.nanmin(axis=axis) + assert_allclose(X_nan_minima.toarray(), np.nanmin(D, axis=axis)) + assert isinstance(X_nan_minima, self.coo_container) + + def test_minmax_invalid_params(self): + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + for fname in ('min', 'max'): + func = getattr(datsp, fname) + assert_raises(ValueError, func, axis=3) + assert_raises(TypeError, func, axis=(0, 1)) + assert_raises(TypeError, func, axis=1.5) + assert_raises(ValueError, func, axis=1, out=1) + + def test_numpy_minmax(self): + # See gh-5987 + # xref gh-7460 in 'numpy' + from scipy.sparse import _data + + dat = array([[0, 1, 2], + [3, -4, 5], + [-6, 7, 9]]) + datsp = self.spcreator(dat) + + # We are only testing sparse matrices who have + # implemented 'min' and 'max' because they are + # the ones with the compatibility issues with + # the 'numpy' implementation. + if isinstance(datsp, _data._minmax_mixin): + assert_array_equal(np.min(datsp), np.min(dat)) + assert_array_equal(np.max(datsp), np.max(dat)) + + def test_argmax(self): + from scipy.sparse import _data + D1 = np.array([ + [-1, 5, 2, 3], + [0, 0, -1, -2], + [-1, -2, -3, -4], + [1, 2, 3, 4], + [1, 2, 0, 0], + ]) + D2 = D1.transpose() + # Non-regression test cases for gh-16929. + D3 = np.array([[4, 3], [7, 5]]) + D4 = np.array([[4, 3], [7, 0]]) + D5 = np.array([[5, 5, 3], [4, 9, 10], [3, 4, 9]]) + + for D in [D1, D2, D3, D4, D5]: + D = self.asdense(D) + mat = self.spcreator(D) + if not isinstance(mat, _data._minmax_mixin): + continue + + assert_equal(mat.argmax(), np.argmax(D)) + assert_equal(mat.argmin(), np.argmin(D)) + + assert_equal(mat.argmax(axis=0), np.argmax(D, axis=0)) + assert_equal(mat.argmin(axis=0), np.argmin(D, axis=0)) + + assert_equal(mat.argmax(axis=1), np.argmax(D, axis=1)) + assert_equal(mat.argmin(axis=1), np.argmin(D, axis=1)) + + # zero-size matrices + D6 = self.spcreator(np.empty((0, 5))) + D7 = self.spcreator(np.empty((5, 0))) + explicits = [True, False] + + for mat, axis, ex in itertools.product([D6, D7], [None, 0, 1], explicits): + if axis is None or mat.shape[axis] == 0: + with pytest.raises(ValueError, match="Cannot apply"): + mat.argmax(axis=axis, explicit=ex) + with pytest.raises(ValueError, match="Cannot apply"): + mat.argmin(axis=axis, explicit=ex) + else: + if self.is_array_test: + expected = np.zeros(0) + else: + expected = np.zeros((0, 1) if axis == 1 else (1, 0)) + assert_equal(mat.argmin(axis=axis, explicit=ex), expected) + assert_equal(mat.argmax(axis=axis, explicit=ex), expected) + + mat = self.spcreator(D1) + assert_equal(mat.argmax(axis=0, explicit=True), self.asdense([3, 0, 3, 3])) + assert_equal(mat.argmin(axis=0, explicit=True), self.asdense([0, 2, 2, 2])) + + expected_max = np.array([1, 2, 0, 3, 1]) + expected_min = np.array([0, 3, 3, 0, 0]) + if mat.nnz != 16: + # Noncanonical case + expected_min[-1] = 2 + if not self.is_array_test: + expected_max = expected_max.reshape((5, 1)) + expected_min = expected_min.reshape((5, 1)) + + assert_equal(mat.argmax(axis=1, explicit=True), expected_max) + assert_equal(asarray(mat.argmin(axis=1, explicit=True)), expected_min) + + # all zeros + D = np.zeros((2, 2)) + mat = self.spcreator(D) + if mat.nnz != 0: + # Noncanonical case + assert_equal(mat.argmin(axis=None, explicit=True), 0) + assert_equal(mat.argmax(axis=None, explicit=True), 0) + else: + # Canonical case + with pytest.raises(ValueError, match="Cannot apply"): + mat.argmin(axis=None, explicit=True) + with pytest.raises(ValueError, match="Cannot apply"): + mat.argmax(axis=None, explicit=True) + + +class _TestGetNnzAxis: + def test_getnnz_axis(self): + dat = array([[0, 2], + [3, 5], + [-6, 9]]) + bool_dat = dat.astype(bool) + datsp = self.spcreator(dat) + + accepted_return_dtypes = (np.int32, np.int64) + + getnnz = datsp.count_nonzero if self.is_array_test else datsp.getnnz + assert_array_equal(bool_dat.sum(axis=None), getnnz(axis=None)) + assert_array_equal(bool_dat.sum(), getnnz()) + assert_array_equal(bool_dat.sum(axis=0), getnnz(axis=0)) + assert_in(getnnz(axis=0).dtype, accepted_return_dtypes) + assert_array_equal(bool_dat.sum(axis=1), getnnz(axis=1)) + assert_in(getnnz(axis=1).dtype, accepted_return_dtypes) + assert_array_equal(bool_dat.sum(axis=-2), getnnz(axis=-2)) + assert_in(getnnz(axis=-2).dtype, accepted_return_dtypes) + assert_array_equal(bool_dat.sum(axis=-1), getnnz(axis=-1)) + assert_in(getnnz(axis=-1).dtype, accepted_return_dtypes) + + assert_raises(ValueError, getnnz, axis=2) + + +#------------------------------------------------------------------------------ +# Tailored base class for generic tests +#------------------------------------------------------------------------------ + +def _possibly_unimplemented(cls, require=True): + """ + Construct a class that either runs tests as usual (require=True), + or each method skips if it encounters a common error. + """ + if require: + return cls + else: + def wrap(fc): + @functools.wraps(fc) + def wrapper(*a, **kw): + try: + return fc(*a, **kw) + except (NotImplementedError, TypeError, ValueError, + IndexError, AttributeError): + raise pytest.skip("feature not implemented") + + return wrapper + + new_dict = dict(cls.__dict__) + for name, func in cls.__dict__.items(): + if name.startswith('test_'): + new_dict[name] = wrap(func) + return type(cls.__name__ + "NotImplemented", + cls.__bases__, + new_dict) + + +def sparse_test_class(getset=True, slicing=True, slicing_assign=True, + fancy_indexing=True, fancy_assign=True, + fancy_multidim_indexing=True, fancy_multidim_assign=True, + minmax=True, nnz_axis=True): + """ + Construct a base class, optionally converting some of the tests in + the suite to check that the feature is not implemented. + """ + bases = (_TestCommon, + _possibly_unimplemented(_TestGetSet, getset), + _TestSolve, + _TestInplaceArithmetic, + _TestArithmetic, + _possibly_unimplemented(_TestSlicing, slicing), + _possibly_unimplemented(_TestSlicingAssign, slicing_assign), + _possibly_unimplemented(_TestFancyIndexing, fancy_indexing), + _possibly_unimplemented(_TestFancyIndexingAssign, + fancy_assign), + _possibly_unimplemented(_TestFancyMultidim, + fancy_indexing and fancy_multidim_indexing), + _possibly_unimplemented(_TestFancyMultidimAssign, + fancy_multidim_assign and fancy_assign), + _possibly_unimplemented(_TestMinMax, minmax), + _possibly_unimplemented(_TestGetNnzAxis, nnz_axis)) + + # check that test names do not clash + names = {} + for cls in bases: + for name in cls.__dict__: + if not name.startswith('test_'): + continue + old_cls = names.get(name) + if old_cls is not None: + raise ValueError(f"Test class {cls.__name__} overloads test " + f"{name} defined in {old_cls.__name__}") + names[name] = cls + + return type("TestBase", bases, {}) + + +#------------------------------------------------------------------------------ +# Matrix class based tests +#------------------------------------------------------------------------------ + +class TestCSR(sparse_test_class()): + @classmethod + def spcreator(cls, *args, **kwargs): + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + return csr_array(*args, **kwargs) + math_dtypes = [np.bool_, np.int_, np.float64, np.complex128] + + def test_constructor1(self): + b = array([[0, 4, 0], + [3, 0, 0], + [0, 2, 0]], 'd') + bsp = self.csr_container(b) + assert_array_almost_equal(bsp.data,[4,3,2]) + assert_array_equal(bsp.indices,[1,0,1]) + assert_array_equal(bsp.indptr,[0,1,2,3]) + assert_equal(bsp.nnz,3) + assert_equal(bsp.format,'csr') + assert_array_equal(bsp.toarray(), b) + + def test_constructor2(self): + b = zeros((6,6),'d') + b[3,4] = 5 + bsp = self.csr_container(b) + assert_array_almost_equal(bsp.data,[5]) + assert_array_equal(bsp.indices,[4]) + assert_array_equal(bsp.indptr,[0,0,0,0,1,1,1]) + assert_array_almost_equal(bsp.toarray(), b) + + def test_constructor3(self): + b = array([[1, 0], + [0, 2], + [3, 0]], 'd') + bsp = self.csr_container(b) + assert_array_almost_equal(bsp.data,[1,2,3]) + assert_array_equal(bsp.indices,[0,1,0]) + assert_array_equal(bsp.indptr,[0,1,2,3]) + assert_array_almost_equal(bsp.toarray(), b) + + def test_constructor4(self): + # using (data, ij) format + row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) + col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) + data = array([6., 10., 3., 9., 1., 4., + 11., 2., 8., 5., 7.]) + + ij = vstack((row,col)) + csr = self.csr_container((data,ij),(4,3)) + assert_array_equal(arange(12).reshape(4, 3), csr.toarray()) + + # using Python lists and a specified dtype + csr = self.csr_container(([2**63 + 1, 1], ([0, 1], [0, 1])), dtype=np.uint64) + dense = array([[2**63 + 1, 0], [0, 1]], dtype=np.uint64) + assert_array_equal(dense, csr.toarray()) + + # with duplicates (should sum the duplicates) + csr = self.csr_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0]))) + assert csr.nnz == 2 + + def test_constructor5(self): + # infer dimensions from arrays + indptr = array([0,1,3,3]) + indices = array([0,5,1,2]) + data = array([1,2,3,4]) + csr = self.csr_container((data, indices, indptr)) + assert_array_equal(csr.shape,(3,6)) + + def test_constructor6(self): + # infer dimensions and dtype from lists + indptr = [0, 1, 3, 3] + indices = [0, 5, 1, 2] + data = [1, 2, 3, 4] + csr = self.csr_container((data, indices, indptr)) + assert_array_equal(csr.shape, (3,6)) + assert_(np.issubdtype(csr.dtype, np.signedinteger)) + + def test_constructor_smallcol(self): + # int64 indices not required + data = arange(6) + 1 + col = array([1, 2, 1, 0, 0, 2], dtype=np.int64) + ptr = array([0, 2, 4, 6], dtype=np.int64) + + a = self.csr_container((data, col, ptr), shape=(3, 3)) + + b = array([[0, 1, 2], + [4, 3, 0], + [5, 0, 6]], 'd') + + # sparray is less aggressive in downcasting indices to int32 than spmatrix + expected_dtype = np.dtype(np.int64 if self.is_array_test else np.int32) + assert_equal(a.indptr.dtype, expected_dtype) + assert_equal(a.indices.dtype, expected_dtype) + assert_array_equal(a.toarray(), b) + + def test_constructor_largecol(self): + # int64 indices required + data = arange(6) + 1 + large = np.iinfo(np.int32).max + 100 + col = array([0, 1, 2, large, large+1, large+2], dtype=np.int64) + ptr = array([0, 2, 4, 6], dtype=np.int64) + + a = self.csr_container((data, col, ptr)) + + assert_equal(a.indptr.dtype, np.dtype(np.int64)) + assert_equal(a.indices.dtype, np.dtype(np.int64)) + assert_array_equal(a.shape, (3, max(col)+1)) + + def test_sort_indices(self): + data = arange(5) + indices = array([7, 2, 1, 5, 4]) + indptr = array([0, 3, 5]) + asp = self.csr_container((data, indices, indptr), shape=(2,10)) + bsp = asp.copy() + asp.sort_indices() + assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) + assert_array_equal(asp.toarray(), bsp.toarray()) + + def test_eliminate_zeros(self): + data = array([1, 0, 0, 0, 2, 0, 3, 0]) + indices = array([1, 2, 3, 4, 5, 6, 7, 8]) + indptr = array([0, 3, 8]) + asp = self.csr_container((data, indices, indptr), shape=(2,10)) + bsp = asp.copy() + asp.eliminate_zeros() + assert_array_equal(asp.nnz, 3) + assert_array_equal(asp.data,[1, 2, 3]) + assert_array_equal(asp.toarray(), bsp.toarray()) + + def test_ufuncs(self): + X = self.csr_container(np.arange(20).reshape(4, 5) / 20.) + for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh", + "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p", + "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]: + assert_equal(hasattr(self.datsp, f), True) + X2 = getattr(X, f)() + assert_equal(X.shape, X2.shape) + assert_array_equal(X.indices, X2.indices) + assert_array_equal(X.indptr, X2.indptr) + assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray())) + + def test_unsorted_arithmetic(self): + data = arange(5) + indices = array([7, 2, 1, 5, 4]) + indptr = array([0, 3, 5]) + asp = self.csr_container((data, indices, indptr), shape=(2,10)) + data = arange(6) + indices = array([8, 1, 5, 7, 2, 4]) + indptr = array([0, 2, 6]) + bsp = self.csr_container((data, indices, indptr), shape=(2,10)) + assert_equal((asp + bsp).toarray(), asp.toarray() + bsp.toarray()) + + def test_fancy_indexing_broadcast(self): + # broadcasting indexing mode is supported + I = np.array([[1], [2], [3]]) + J = np.array([3, 4, 2]) + + np.random.seed(1234) + D = self.asdense(np.random.rand(5, 7)) + S = self.spcreator(D) + + SIJ = S[I,J] + if issparse(SIJ): + SIJ = SIJ.toarray() + assert_equal(SIJ, D[I,J]) + + def test_has_sorted_indices(self): + "Ensure has_sorted_indices memoizes sorted state for sort_indices" + sorted_inds = np.array([0, 1]) + unsorted_inds = np.array([1, 0]) + data = np.array([1, 1]) + indptr = np.array([0, 2]) + M = self.csr_container((data, sorted_inds, indptr)).copy() + assert_equal(True, M.has_sorted_indices) + assert isinstance(M.has_sorted_indices, bool) + + M = self.csr_container((data, unsorted_inds, indptr)).copy() + assert_equal(False, M.has_sorted_indices) + + # set by sorting + M.sort_indices() + assert_equal(True, M.has_sorted_indices) + assert_array_equal(M.indices, sorted_inds) + + M = self.csr_container((data, unsorted_inds, indptr)).copy() + # set manually (although underlyingly unsorted) + M.has_sorted_indices = True + assert_equal(True, M.has_sorted_indices) + assert_array_equal(M.indices, unsorted_inds) + + # ensure sort bypassed when has_sorted_indices == True + M.sort_indices() + assert_array_equal(M.indices, unsorted_inds) + + def test_has_canonical_format(self): + "Ensure has_canonical_format memoizes state for sum_duplicates" + + M = self.csr_container((np.array([2]), np.array([0]), np.array([0, 1]))) + assert_equal(True, M.has_canonical_format) + + indices = np.array([0, 0]) # contains duplicate + data = np.array([1, 1]) + indptr = np.array([0, 2]) + + M = self.csr_container((data, indices, indptr)).copy() + assert_equal(False, M.has_canonical_format) + assert isinstance(M.has_canonical_format, bool) + + # set by deduplicating + M.sum_duplicates() + assert_equal(True, M.has_canonical_format) + assert_equal(1, len(M.indices)) + + M = self.csr_container((data, indices, indptr)).copy() + # set manually (although underlyingly duplicated) + M.has_canonical_format = True + assert_equal(True, M.has_canonical_format) + assert_equal(2, len(M.indices)) # unaffected content + + # ensure deduplication bypassed when has_canonical_format == True + M.sum_duplicates() + assert_equal(2, len(M.indices)) # unaffected content + + def test_scalar_idx_dtype(self): + # Check that index dtype takes into account all parameters + # passed to sparsetools, including the scalar ones + indptr = np.zeros(2, dtype=np.int32) + indices = np.zeros(0, dtype=np.int32) + vals = np.zeros(0) + a = self.csr_container((vals, indices, indptr), shape=(1, 2**31-1)) + b = self.csr_container((vals, indices, indptr), shape=(1, 2**31)) + ij = np.zeros((2, 0), dtype=np.int32) + c = self.csr_container((vals, ij), shape=(1, 2**31-1)) + d = self.csr_container((vals, ij), shape=(1, 2**31)) + e = self.csr_container((1, 2**31-1)) + f = self.csr_container((1, 2**31)) + assert_equal(a.indptr.dtype, np.int32) + assert_equal(b.indptr.dtype, np.int64) + assert_equal(c.indptr.dtype, np.int32) + assert_equal(d.indptr.dtype, np.int64) + assert_equal(e.indptr.dtype, np.int32) + assert_equal(f.indptr.dtype, np.int64) + + # These shouldn't fail + for x in [a, b, c, d, e, f]: + x + x + + def test_setdiag_csr(self): + # see gh-21791 setting mixture of existing and not when new_values < 0.001*nnz + D = self.dia_container(([np.arange(1002)], [0]), shape=(1002, 1002)) + A = self.spcreator(D) + A.setdiag(5 * np.ones(A.shape[0])) + assert A[-1, -1] == 5 + + def test_binop_explicit_zeros(self): + # Check that binary ops don't introduce spurious explicit zeros. + # See gh-9619 for context. + a = self.csr_container([[0, 1, 0]]) + b = self.csr_container([[1, 1, 0]]) + assert (a + b).nnz == 2 + assert a.multiply(b).nnz == 1 + + +TestCSR.init_class() + + +class TestCSRMatrix(_MatrixMixin, TestCSR): + @classmethod + def spcreator(cls, *args, **kwargs): + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + return csr_matrix(*args, **kwargs) + + +TestCSRMatrix.init_class() + + +class TestCSC(sparse_test_class()): + @classmethod + def spcreator(cls, *args, **kwargs): + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + return csc_array(*args, **kwargs) + math_dtypes = [np.bool_, np.int_, np.float64, np.complex128] + + def test_constructor1(self): + b = array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 2, 0, 3]], 'd') + bsp = self.csc_container(b) + assert_array_almost_equal(bsp.data,[1,2,1,3]) + assert_array_equal(bsp.indices,[0,2,1,2]) + assert_array_equal(bsp.indptr,[0,1,2,3,4]) + assert_equal(bsp.nnz,4) + assert_equal(bsp.shape,b.shape) + assert_equal(bsp.format,'csc') + + def test_constructor2(self): + b = zeros((6,6),'d') + b[2,4] = 5 + bsp = self.csc_container(b) + assert_array_almost_equal(bsp.data,[5]) + assert_array_equal(bsp.indices,[2]) + assert_array_equal(bsp.indptr,[0,0,0,0,0,1,1]) + + def test_constructor3(self): + b = array([[1, 0], [0, 0], [0, 2]], 'd') + bsp = self.csc_container(b) + assert_array_almost_equal(bsp.data,[1,2]) + assert_array_equal(bsp.indices,[0,2]) + assert_array_equal(bsp.indptr,[0,1,2]) + + def test_constructor4(self): + # using (data, ij) format + row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) + col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) + data = array([6., 10., 3., 9., 1., 4., 11., 2., 8., 5., 7.]) + + ij = vstack((row,col)) + csc = self.csc_container((data,ij),(4,3)) + assert_array_equal(arange(12).reshape(4, 3), csc.toarray()) + + # with duplicates (should sum the duplicates) + csc = self.csc_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0]))) + assert csc.nnz == 2 + + def test_constructor5(self): + # infer dimensions from arrays + indptr = array([0,1,3,3]) + indices = array([0,5,1,2]) + data = array([1,2,3,4]) + csc = self.csc_container((data, indices, indptr)) + assert_array_equal(csc.shape,(6,3)) + + def test_constructor6(self): + # infer dimensions and dtype from lists + indptr = [0, 1, 3, 3] + indices = [0, 5, 1, 2] + data = [1, 2, 3, 4] + csc = self.csc_container((data, indices, indptr)) + assert_array_equal(csc.shape,(6,3)) + assert_(np.issubdtype(csc.dtype, np.signedinteger)) + + def test_eliminate_zeros(self): + data = array([1, 0, 0, 0, 2, 0, 3, 0]) + indices = array([1, 2, 3, 4, 5, 6, 7, 8]) + indptr = array([0, 3, 8]) + asp = self.csc_container((data, indices, indptr), shape=(10,2)) + bsp = asp.copy() + asp.eliminate_zeros() + assert_array_equal(asp.nnz, 3) + assert_array_equal(asp.data,[1, 2, 3]) + assert_array_equal(asp.toarray(), bsp.toarray()) + + def test_sort_indices(self): + data = arange(5) + row = array([7, 2, 1, 5, 4]) + ptr = [0, 3, 5] + asp = self.csc_container((data, row, ptr), shape=(10,2)) + bsp = asp.copy() + asp.sort_indices() + assert_array_equal(asp.indices,[1, 2, 7, 4, 5]) + assert_array_equal(asp.toarray(), bsp.toarray()) + + def test_ufuncs(self): + X = self.csc_container(np.arange(21).reshape(7, 3) / 21.) + for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh", + "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p", + "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]: + assert_equal(hasattr(self.datsp, f), True) + X2 = getattr(X, f)() + assert_equal(X.shape, X2.shape) + assert_array_equal(X.indices, X2.indices) + assert_array_equal(X.indptr, X2.indptr) + assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray())) + + def test_unsorted_arithmetic(self): + data = arange(5) + indices = array([7, 2, 1, 5, 4]) + indptr = array([0, 3, 5]) + asp = self.csc_container((data, indices, indptr), shape=(10,2)) + data = arange(6) + indices = array([8, 1, 5, 7, 2, 4]) + indptr = array([0, 2, 6]) + bsp = self.csc_container((data, indices, indptr), shape=(10,2)) + assert_equal((asp + bsp).toarray(), asp.toarray() + bsp.toarray()) + + def test_fancy_indexing_broadcast(self): + # broadcasting indexing mode is supported + I = np.array([[1], [2], [3]]) + J = np.array([3, 4, 2]) + + np.random.seed(1234) + D = self.asdense(np.random.rand(5, 7)) + S = self.spcreator(D) + + SIJ = S[I,J] + if issparse(SIJ): + SIJ = SIJ.toarray() + assert_equal(SIJ, D[I,J]) + + def test_scalar_idx_dtype(self): + # Check that index dtype takes into account all parameters + # passed to sparsetools, including the scalar ones + indptr = np.zeros(2, dtype=np.int32) + indices = np.zeros(0, dtype=np.int32) + vals = np.zeros(0) + a = self.csc_container((vals, indices, indptr), shape=(2**31-1, 1)) + b = self.csc_container((vals, indices, indptr), shape=(2**31, 1)) + ij = np.zeros((2, 0), dtype=np.int32) + c = self.csc_container((vals, ij), shape=(2**31-1, 1)) + d = self.csc_container((vals, ij), shape=(2**31, 1)) + e = self.csr_container((1, 2**31-1)) + f = self.csr_container((1, 2**31)) + assert_equal(a.indptr.dtype, np.int32) + assert_equal(b.indptr.dtype, np.int64) + assert_equal(c.indptr.dtype, np.int32) + assert_equal(d.indptr.dtype, np.int64) + assert_equal(e.indptr.dtype, np.int32) + assert_equal(f.indptr.dtype, np.int64) + + # These shouldn't fail + for x in [a, b, c, d, e, f]: + x + x + + def test_setdiag_csc(self): + # see gh-21791 setting mixture of existing and not when new_values < 0.001*nnz + D = self.dia_container(([np.arange(1002)], [0]), shape=(1002, 1002)) + A = self.spcreator(D) + A.setdiag(5 * np.ones(A.shape[0])) + assert A[-1, -1] == 5 + + +TestCSC.init_class() + + +class TestCSCMatrix(_MatrixMixin, TestCSC): + @classmethod + def spcreator(cls, *args, **kwargs): + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + return csc_matrix(*args, **kwargs) + + +TestCSCMatrix.init_class() + + +class TestDOK(sparse_test_class(minmax=False, nnz_axis=False)): + spcreator = dok_array + math_dtypes = [np.int_, np.float64, np.complex128] + + def test_mult(self): + A = self.dok_container((10, 12)) + A[0, 3] = 10 + A[5, 6] = 20 + D = A @ A.T + E = A @ A.T.conjugate() + assert_array_equal(D.toarray(), E.toarray()) + + def test_add_nonzero(self): + A = self.spcreator((3,2)) + A[0,1] = -10 + A[2,0] = 20 + A = A + 10 + B = array([[10, 0], [10, 10], [30, 10]]) + assert_array_equal(A.toarray(), B) + + A = A + 1j + B = B + 1j + assert_array_equal(A.toarray(), B) + + def test_dok_divide_scalar(self): + A = self.spcreator((3,2)) + A[0,1] = -10 + A[2,0] = 20 + + assert_array_equal((A/1j).toarray(), A.toarray()/1j) + assert_array_equal((A/9).toarray(), A.toarray()/9) + + def test_convert(self): + # Test provided by Andrew Straw. Fails in SciPy <= r1477. + (m, n) = (6, 7) + a = self.dok_container((m, n)) + + # set a few elements, but none in the last column + a[2,1] = 1 + a[0,2] = 2 + a[3,1] = 3 + a[1,5] = 4 + a[4,3] = 5 + a[4,2] = 6 + + # assert that the last column is all zeros + assert_array_equal(a.toarray()[:,n-1], zeros(m,)) + + # make sure it still works for CSC format + csc = a.tocsc() + assert_array_equal(csc.toarray()[:,n-1], zeros(m,)) + + # now test CSR + (m, n) = (n, m) + b = a.transpose() + assert_equal(b.shape, (m, n)) + # assert that the last row is all zeros + assert_array_equal(b.toarray()[m-1,:], zeros(n,)) + + # make sure it still works for CSR format + csr = b.tocsr() + assert_array_equal(csr.toarray()[m-1,:], zeros(n,)) + + def test_ctor(self): + # Empty ctor + assert_raises(TypeError, self.dok_container) + + # Dense ctor + b = array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 2, 0, 3]], 'd') + A = self.dok_container(b) + assert_equal(b.dtype, A.dtype) + assert_equal(A.toarray(), b) + + # Sparse ctor + c = self.csr_container(b) + assert_equal(A.toarray(), c.toarray()) + + data = [[0, 1, 2], [3, 0, 0]] + d = self.dok_container(data, dtype=np.float32) + assert_equal(d.dtype, np.float32) + da = d.toarray() + assert_equal(da.dtype, np.float32) + assert_array_equal(da, data) + + def test_ticket1160(self): + # Regression test for ticket #1160. + a = self.dok_container((3,3)) + a[0,0] = 0 + # This assert would fail, because the above assignment would + # incorrectly call __set_item__ even though the value was 0. + assert_((0,0) not in a.keys(), "Unexpected entry (0,0) in keys") + + # Slice assignments were also affected. + b = self.dok_container((3,3)) + b[:,0] = 0 + assert_(len(b.keys()) == 0, "Unexpected entries in keys") + + +class TestDOKMatrix(_MatrixMixin, TestDOK): + spcreator = dok_matrix + + +TestDOK.init_class() +TestDOKMatrix.init_class() + + +class TestLIL(sparse_test_class(minmax=False)): + spcreator = lil_array + math_dtypes = [np.int_, np.float64, np.complex128] + + def test_dot(self): + A = zeros((10, 10), np.complex128) + A[0, 3] = 10 + A[5, 6] = 20j + + B = self.lil_container((10, 10), dtype=np.complex128) + B[0, 3] = 10 + B[5, 6] = 20j + + # TODO: properly handle this assertion on ppc64le + if platform.machine() != 'ppc64le': + assert_array_equal(A @ A.T, (B @ B.T).toarray()) + + assert_array_equal(A @ A.conjugate().T, (B @ B.conjugate().T).toarray()) + + def test_scalar_mul(self): + x = self.lil_container((3, 3)) + x[0, 0] = 2 + + x = x*2 + assert_equal(x[0, 0], 4) + + x = x*0 + assert_equal(x[0, 0], 0) + + def test_truediv_scalar(self): + A = self.spcreator((3, 2)) + A[0, 1] = -10 + A[2, 0] = 20 + + assert_array_equal((A / 1j).toarray(), A.toarray() / 1j) + assert_array_equal((A / 9).toarray(), A.toarray() / 9) + + def test_inplace_ops(self): + A = self.lil_container([[0, 2, 3], [4, 0, 6]]) + B = self.lil_container([[0, 1, 0], [0, 2, 3]]) + + data = {'add': (B, A + B), + 'sub': (B, A - B), + 'mul': (3, A * 3)} + + for op, (other, expected) in data.items(): + result = A.copy() + getattr(result, f'__i{op}__')(other) + + assert_array_equal(result.toarray(), expected.toarray()) + + # Ticket 1604. + A = self.lil_container((1, 3), dtype=np.dtype('float64')) + B = self.asdense([0.1, 0.1, 0.1]) + A[0, :] += B + assert_array_equal(A[0, :].toarray(), B) + + def test_lil_iteration(self): + row_data = [[1, 2, 3], [4, 5, 6]] + B = self.lil_container(array(row_data)) + for r, row in enumerate(B): + assert_array_equal(row.toarray(), array(row_data[r], ndmin=row.ndim)) + + def test_lil_from_csr(self): + # Tests whether a LIL can be constructed from a CSR. + B = self.lil_container((10, 10)) + B[0, 3] = 10 + B[5, 6] = 20 + B[8, 3] = 30 + B[3, 8] = 40 + B[8, 9] = 50 + C = B.tocsr() + D = self.lil_container(C) + assert_array_equal(C.toarray(), D.toarray()) + + def test_fancy_indexing_lil(self): + M = self.asdense(arange(25).reshape(5, 5)) + A = self.lil_container(M) + + assert_equal(A[array([1, 2, 3]), 2:3].toarray(), + M[array([1, 2, 3]), 2:3]) + + def test_point_wise_multiply(self): + l = self.lil_container((4, 3)) + l[0, 0] = 1 + l[1, 1] = 2 + l[2, 2] = 3 + l[3, 1] = 4 + + m = self.lil_container((4, 3)) + m[0, 0] = 1 + m[0, 1] = 2 + m[2, 2] = 3 + m[3, 1] = 4 + m[3, 2] = 4 + + assert_array_equal(l.multiply(m).toarray(), + m.multiply(l).toarray()) + + assert_array_equal(l.multiply(m).toarray(), + [[1, 0, 0], + [0, 0, 0], + [0, 0, 9], + [0, 16, 0]]) + + def test_lil_multiply_removal(self): + # Ticket #1427. + a = self.lil_container(np.ones((3, 3))) + a *= 2. + a[0, :] = 0 + + +class TestLILMatrix(_MatrixMixin, TestLIL): + spcreator = lil_matrix + + +TestLIL.init_class() +TestLILMatrix.init_class() + + +class TestCOO(sparse_test_class(getset=False, + slicing=False, slicing_assign=False, + fancy_indexing=False, fancy_assign=False)): + spcreator = coo_array + math_dtypes = [np.int_, np.float64, np.complex128] + + def test_constructor1(self): + # unsorted triplet format + row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2]) + col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1]) + data = array([6., 10., 3., 9., 1., 4., 11., 2., 8., 5., 7.]) + + coo = self.coo_container((data,(row,col)),(4,3)) + assert_array_equal(arange(12).reshape(4, 3), coo.toarray()) + + # using Python lists and a specified dtype + coo = self.coo_container(([2**63 + 1, 1], ([0, 1], [0, 1])), dtype=np.uint64) + dense = array([[2**63 + 1, 0], [0, 1]], dtype=np.uint64) + assert_array_equal(dense, coo.toarray()) + + def test_constructor2(self): + # unsorted triplet format with duplicates (which are summed) + row = array([0,1,2,2,2,2,0,0,2,2]) + col = array([0,2,0,2,1,1,1,0,0,2]) + data = array([2,9,-4,5,7,0,-1,2,1,-5]) + coo = self.coo_container((data,(row,col)),(3,3)) + + mat = array([[4, -1, 0], [0, 0, 9], [-3, 7, 0]]) + + assert_array_equal(mat, coo.toarray()) + + def test_constructor3(self): + # empty matrix + coo = self.coo_container((4,3)) + + assert_array_equal(coo.shape,(4,3)) + assert_array_equal(coo.row,[]) + assert_array_equal(coo.col,[]) + assert_array_equal(coo.data,[]) + assert_array_equal(coo.toarray(), zeros((4, 3))) + + def test_constructor4(self): + # from dense matrix + mat = array([[0,1,0,0], + [7,0,3,0], + [0,4,0,0]]) + coo = self.coo_container(mat) + assert_array_equal(coo.toarray(), mat) + + # upgrade rank 1 arrays to row matrix + mat = array([0,1,0,0]) + coo = self.coo_container(mat) + expected = mat if self.is_array_test else mat.reshape(1, -1) + assert_array_equal(coo.toarray(), expected) + + # error if second arg interpreted as shape (gh-9919) + with pytest.raises(TypeError, match=r'object cannot be interpreted'): + self.coo_container([0, 11, 22, 33], ([0, 1, 2, 3], [0, 0, 0, 0])) + + # error if explicit shape arg doesn't match the dense matrix + with pytest.raises(ValueError, match=r'inconsistent shapes'): + self.coo_container([0, 11, 22, 33], shape=(4, 4)) + + def test_constructor_data_ij_dtypeNone(self): + data = [1] + coo = self.coo_container((data, ([0], [0])), dtype=None) + assert coo.dtype == np.array(data).dtype + + @pytest.mark.xfail(run=False, reason='COO does not have a __getitem__') + def test_iterator(self): + pass + + def test_todia_all_zeros(self): + zeros = [[0, 0]] + dia = self.coo_container(zeros).todia() + assert_array_equal(dia.toarray(), zeros) + + def test_sum_duplicates(self): + coo = self.coo_container((4,3)) + coo.sum_duplicates() + coo = self.coo_container(([1,2], ([1,0], [1,0]))) + coo.sum_duplicates() + assert_array_equal(coo.toarray(), [[2,0],[0,1]]) + coo = self.coo_container(([1,2], ([1,1], [1,1]))) + coo.sum_duplicates() + assert_array_equal(coo.toarray(), [[0,0],[0,3]]) + assert_array_equal(coo.row, [1]) + assert_array_equal(coo.col, [1]) + assert_array_equal(coo.data, [3]) + + def test_todok_duplicates(self): + coo = self.coo_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0]))) + dok = coo.todok() + assert_array_equal(dok.toarray(), coo.toarray()) + + def test_tocompressed_duplicates(self): + coo = self.coo_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0]))) + csr = coo.tocsr() + assert_equal(csr.nnz + 2, coo.nnz) + csc = coo.tocsc() + assert_equal(csc.nnz + 2, coo.nnz) + + def test_eliminate_zeros(self): + data = array([1, 0, 0, 0, 2, 0, 3, 0]) + row = array([0, 0, 0, 1, 1, 1, 1, 1]) + col = array([1, 2, 3, 4, 5, 6, 7, 8]) + asp = self.coo_container((data, (row, col)), shape=(2,10)) + bsp = asp.copy() + asp.eliminate_zeros() + assert_((asp.data != 0).all()) + assert_array_equal(asp.toarray(), bsp.toarray()) + + def test_reshape_copy(self): + arr = [[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]] + new_shape = (2, 6) + x = self.coo_container(arr) + + y = x.reshape(new_shape) + assert_(y.data is x.data) + + y = x.reshape(new_shape, copy=False) + assert_(y.data is x.data) + + y = x.reshape(new_shape, copy=True) + assert_(not np.may_share_memory(y.data, x.data)) + + def test_large_dimensions_reshape(self): + # Test that reshape is immune to integer overflow when number of elements + # exceeds 2^31-1 + mat1 = self.coo_container(([1], ([3000000], [1000])), (3000001, 1001)) + mat2 = self.coo_container(([1], ([1000], [3000000])), (1001, 3000001)) + + # assert_array_equal is slow for big matrices because it expects dense + # Using __ne__ and nnz instead + assert_((mat1.reshape((1001, 3000001), order='C') != mat2).nnz == 0) + assert_((mat2.reshape((3000001, 1001), order='F') != mat1).nnz == 0) + + +class TestCOOMatrix(_MatrixMixin, TestCOO): + spcreator = coo_matrix + + +TestCOO.init_class() +TestCOOMatrix.init_class() + + +class TestDIA(sparse_test_class(getset=False, slicing=False, slicing_assign=False, + fancy_indexing=False, fancy_assign=False, + minmax=False, nnz_axis=False)): + spcreator = dia_array + math_dtypes = [np.int_, np.float64, np.complex128] + + def test_constructor1(self): + D = array([[1, 0, 3, 0], + [1, 2, 0, 4], + [0, 2, 3, 0], + [0, 0, 3, 4]]) + data = np.array([[1,2,3,4]]).repeat(3,axis=0) + offsets = np.array([0,-1,2]) + assert_equal(self.dia_container((data, offsets), shape=(4, 4)).toarray(), D) + + @pytest.mark.xfail(run=False, reason='DIA does not have a __getitem__') + def test_iterator(self): + pass + + @with_64bit_maxval_limit(3) + def test_setdiag_dtype(self): + m = self.dia_container(np.eye(3)) + assert_equal(m.offsets.dtype, np.int32) + m.setdiag((3,), k=2) + assert_equal(m.offsets.dtype, np.int32) + + m = self.dia_container(np.eye(4)) + assert_equal(m.offsets.dtype, np.int64) + m.setdiag((3,), k=3) + assert_equal(m.offsets.dtype, np.int64) + + @pytest.mark.skip(reason='DIA stores extra zeros') + def test_getnnz_axis(self): + pass + + def test_convert_gh14555(self): + # regression test for gh-14555 + m = self.dia_container(([[1, 1, 0]], [-1]), shape=(4, 2)) + expected = m.toarray() + assert_array_equal(m.tocsc().toarray(), expected) + assert_array_equal(m.tocsr().toarray(), expected) + + def test_tocoo_gh10050(self): + # regression test for gh-10050 + m = self.dia_container([[1, 2], [3, 4]]).tocoo() + flat_inds = np.ravel_multi_index((m.row, m.col), m.shape) + inds_are_sorted = np.all(np.diff(flat_inds) > 0) + assert m.has_canonical_format == inds_are_sorted + + def test_tocoo_tocsr_tocsc_gh19245(self): + # test index_dtype with tocoo, tocsr, tocsc + data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0) + offsets = np.array([0, -1, 2], dtype=np.int32) + dia = sparse.dia_array((data, offsets), shape=(4, 4)) + + coo = dia.tocoo() + assert coo.col.dtype == np.int32 + csr = dia.tocsr() + assert csr.indices.dtype == np.int32 + csc = dia.tocsc() + assert csc.indices.dtype == np.int32 + + def test_mul_scalar(self): + # repro for gh-20434 + m = self.dia_container([[1, 2], [0, 4]]) + res = m * 3 + assert isinstance(res, m.__class__) + assert_array_equal(res.toarray(), [[3, 6], [0, 12]]) + + res2 = m.multiply(3) + assert isinstance(res2, m.__class__) + assert_array_equal(res2.toarray(), [[3, 6], [0, 12]]) + + +class TestDIAMatrix(_MatrixMixin, TestDIA): + spcreator = dia_matrix + + +TestDIA.init_class() +TestDIAMatrix.init_class() + + +class TestBSR(sparse_test_class(getset=False, + slicing=False, slicing_assign=False, + fancy_indexing=False, fancy_assign=False, + nnz_axis=False)): + spcreator = bsr_array + math_dtypes = [np.int_, np.float64, np.complex128] + + def test_constructor1(self): + # check native BSR format constructor + indptr = array([0,2,2,4]) + indices = array([0,2,2,3]) + data = zeros((4,2,3)) + + data[0] = array([[0, 1, 2], + [3, 0, 5]]) + data[1] = array([[0, 2, 4], + [6, 0, 10]]) + data[2] = array([[0, 4, 8], + [12, 0, 20]]) + data[3] = array([[0, 5, 10], + [15, 0, 25]]) + + A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]]) + Asp = self.bsr_container((data,indices,indptr),shape=(6,12)) + assert_equal(Asp.toarray(), A) + + # infer shape from arrays + Asp = self.bsr_container((data,indices,indptr)) + assert_equal(Asp.toarray(), A) + + def test_constructor2(self): + # construct from dense + + # test zero mats + for shape in [(1,1), (5,1), (1,10), (10,4), (3,7), (2,1)]: + A = zeros(shape) + assert_equal(self.bsr_container(A).toarray(), A) + A = zeros((4,6)) + assert_equal(self.bsr_container(A, blocksize=(2, 2)).toarray(), A) + assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A) + + A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]]) + assert_equal(self.bsr_container(A).toarray(), A) + assert_equal(self.bsr_container(A, shape=(6, 12)).toarray(), A) + assert_equal(self.bsr_container(A, blocksize=(1, 1)).toarray(), A) + assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A) + assert_equal(self.bsr_container(A, blocksize=(2, 6)).toarray(), A) + assert_equal(self.bsr_container(A, blocksize=(2, 12)).toarray(), A) + assert_equal(self.bsr_container(A, blocksize=(3, 12)).toarray(), A) + assert_equal(self.bsr_container(A, blocksize=(6, 12)).toarray(), A) + + A = kron([[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]]) + assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A) + + def test_constructor3(self): + # construct from coo-like (data,(row,col)) format + arg = ([1,2,3], ([0,1,1], [0,0,1])) + A = array([[1,0],[2,3]]) + assert_equal(self.bsr_container(arg, blocksize=(2, 2)).toarray(), A) + + def test_constructor4(self): + # regression test for gh-6292: self.bsr_matrix((data, indices, indptr)) was + # trying to compare an int to a None + n = 8 + data = np.ones((n, n, 1), dtype=np.int8) + indptr = np.array([0, n], dtype=np.int32) + indices = np.arange(n, dtype=np.int32) + self.bsr_container((data, indices, indptr), blocksize=(n, 1), copy=False) + + def test_constructor5(self): + # check for validations introduced in gh-13400 + n = 8 + data_1dim = np.ones(n) + data = np.ones((n, n, n)) + indptr = np.array([0, n]) + indices = np.arange(n) + + with assert_raises(ValueError): + # data ndim check + self.bsr_container((data_1dim, indices, indptr)) + + with assert_raises(ValueError): + # invalid blocksize + self.bsr_container((data, indices, indptr), blocksize=(1, 1, 1)) + + with assert_raises(ValueError): + # mismatching blocksize + self.bsr_container((data, indices, indptr), blocksize=(1, 1)) + + def test_default_dtype(self): + # As a numpy array, `values` has shape (2, 2, 1). + values = [[[1], [1]], [[1], [1]]] + indptr = np.array([0, 2], dtype=np.int32) + indices = np.array([0, 1], dtype=np.int32) + b = self.bsr_container((values, indices, indptr), blocksize=(2, 1)) + assert b.dtype == np.array(values).dtype + + def test_bsr_tocsr(self): + # check native conversion from BSR to CSR + indptr = array([0, 2, 2, 4]) + indices = array([0, 2, 2, 3]) + data = zeros((4, 2, 3)) + + data[0] = array([[0, 1, 2], + [3, 0, 5]]) + data[1] = array([[0, 2, 4], + [6, 0, 10]]) + data[2] = array([[0, 4, 8], + [12, 0, 20]]) + data[3] = array([[0, 5, 10], + [15, 0, 25]]) + + A = kron([[1, 0, 2, 0], [0, 0, 0, 0], [0, 0, 4, 5]], + [[0, 1, 2], [3, 0, 5]]) + Absr = self.bsr_container((data, indices, indptr), shape=(6, 12)) + Acsr = Absr.tocsr() + Acsr_via_coo = Absr.tocoo().tocsr() + assert_equal(Acsr.toarray(), A) + assert_equal(Acsr.toarray(), Acsr_via_coo.toarray()) + + def test_eliminate_zeros(self): + data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T + data = data.reshape(-1,2,2) + indices = array([1, 2, 3, 4, 5, 6, 7, 8]) + indptr = array([0, 3, 8]) + asp = self.bsr_container((data, indices, indptr), shape=(4,20)) + bsp = asp.copy() + asp.eliminate_zeros() + assert_array_equal(asp.nnz, 3*4) + assert_array_equal(asp.toarray(), bsp.toarray()) + + # GitHub issue #9687 + def test_eliminate_zeros_all_zero(self): + np.random.seed(0) + m = self.bsr_container(np.random.random((12, 12)), blocksize=(2, 3)) + + # eliminate some blocks, but not all + m.data[m.data <= 0.9] = 0 + m.eliminate_zeros() + assert_equal(m.nnz, 66) + assert_array_equal(m.data.shape, (11, 2, 3)) + + # eliminate all remaining blocks + m.data[m.data <= 1.0] = 0 + m.eliminate_zeros() + assert_equal(m.nnz, 0) + assert_array_equal(m.data.shape, (0, 2, 3)) + assert_array_equal(m.toarray(), np.zeros((12, 12))) + + # test fast path + m.eliminate_zeros() + assert_equal(m.nnz, 0) + assert_array_equal(m.data.shape, (0, 2, 3)) + assert_array_equal(m.toarray(), np.zeros((12, 12))) + + def test_bsr_matvec(self): + A = self.bsr_container(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5)) + x = arange(A.shape[1]).reshape(-1,1) + assert_equal(A @ x, A.toarray() @ x) + + def test_bsr_matvecs(self): + A = self.bsr_container(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5)) + x = arange(A.shape[1]*6).reshape(-1,6) + assert_equal(A @ x, A.toarray() @ x) + + @pytest.mark.xfail(run=False, reason='BSR does not have a __getitem__') + def test_iterator(self): + pass + + @pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__') + def test_setdiag(self): + pass + + def test_resize_blocked(self): + # test resize() with non-(1,1) blocksize + D = np.array([[1, 0, 3, 4], + [2, 0, 0, 0], + [3, 0, 0, 0]]) + S = self.spcreator(D, blocksize=(1, 2)) + assert_(S.resize((3, 2)) is None) + assert_array_equal(S.toarray(), [[1, 0], + [2, 0], + [3, 0]]) + S.resize((2, 2)) + assert_array_equal(S.toarray(), [[1, 0], + [2, 0]]) + S.resize((3, 2)) + assert_array_equal(S.toarray(), [[1, 0], + [2, 0], + [0, 0]]) + S.resize((3, 4)) + assert_array_equal(S.toarray(), [[1, 0, 0, 0], + [2, 0, 0, 0], + [0, 0, 0, 0]]) + assert_raises(ValueError, S.resize, (2, 3)) + + @pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__') + def test_setdiag_comprehensive(self): + pass + + @pytest.mark.skipif(IS_COLAB, reason="exceeds memory limit") + def test_scalar_idx_dtype(self): + # Check that index dtype takes into account all parameters + # passed to sparsetools, including the scalar ones + indptr = np.zeros(2, dtype=np.int32) + indices = np.zeros(0, dtype=np.int32) + vals = np.zeros((0, 1, 1)) + a = self.bsr_container((vals, indices, indptr), shape=(1, 2**31-1)) + b = self.bsr_container((vals, indices, indptr), shape=(1, 2**31)) + c = self.bsr_container((1, 2**31-1)) + d = self.bsr_container((1, 2**31)) + assert_equal(a.indptr.dtype, np.int32) + assert_equal(b.indptr.dtype, np.int64) + assert_equal(c.indptr.dtype, np.int32) + assert_equal(d.indptr.dtype, np.int64) + + try: + vals2 = np.zeros((0, 1, 2**31-1)) + vals3 = np.zeros((0, 1, 2**31)) + e = self.bsr_container((vals2, indices, indptr), shape=(1, 2**31-1)) + f = self.bsr_container((vals3, indices, indptr), shape=(1, 2**31)) + assert_equal(e.indptr.dtype, np.int32) + assert_equal(f.indptr.dtype, np.int64) + except (MemoryError, ValueError): + # May fail on 32-bit Python + e = 0 + f = 0 + + # These shouldn't fail + for x in [a, b, c, d, e, f]: + x + x + + +class TestBSRMatrix(_MatrixMixin, TestBSR): + spcreator = bsr_matrix + + +TestBSR.init_class() +TestBSRMatrix.init_class() + + +#------------------------------------------------------------------------------ +# Tests for non-canonical representations (with duplicates, unsorted indices) +#------------------------------------------------------------------------------ + +def _same_sum_duplicate(data, *inds, **kwargs): + """Duplicates entries to produce the same matrix""" + indptr = kwargs.pop('indptr', None) + if np.issubdtype(data.dtype, np.bool_) or \ + np.issubdtype(data.dtype, np.unsignedinteger): + if indptr is None: + return (data,) + inds + else: + return (data,) + inds + (indptr,) + + zeros_pos = (data == 0).nonzero() + + # duplicate data + data = data.repeat(2, axis=0) + data[::2] -= 1 + data[1::2] = 1 + + # don't spoil all explicit zeros + if zeros_pos[0].size > 0: + pos = tuple(p[0] for p in zeros_pos) + pos1 = (2*pos[0],) + pos[1:] + pos2 = (2*pos[0]+1,) + pos[1:] + data[pos1] = 0 + data[pos2] = 0 + + inds = tuple(indices.repeat(2) for indices in inds) + + if indptr is None: + return (data,) + inds + else: + return (data,) + inds + (indptr * 2,) + + +class _NonCanonicalMixin: + def spcreator(self, D, *args, sorted_indices=False, **kwargs): + """Replace D with a non-canonical equivalent: containing + duplicate elements and explicit zeros""" + construct = super().spcreator + M = construct(D, *args, **kwargs) + + zero_pos = (M.toarray() == 0).nonzero() + has_zeros = (zero_pos[0].size > 0) + if has_zeros: + k = zero_pos[0].size//2 + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + M = self._insert_explicit_zero(M, zero_pos[0][k], zero_pos[1][k]) + + arg1 = self._arg1_for_noncanonical(M, sorted_indices) + if 'shape' not in kwargs: + kwargs['shape'] = M.shape + NC = construct(arg1, **kwargs) + + # check that result is valid + if NC.dtype in [np.float32, np.complex64]: + # For single-precision floats, the differences between M and NC + # that are introduced by the extra operations involved in the + # construction of NC necessitate a more lenient tolerance level + # than the default. + rtol = 1e-05 + else: + rtol = 1e-07 + assert_allclose(NC.toarray(), M.toarray(), rtol=rtol) + + # check that at least one explicit zero + if has_zeros: + assert_((NC.data == 0).any()) + # TODO check that NC has duplicates (which are not explicit zeros) + + return NC + + @pytest.mark.skip(reason='bool(matrix) counts explicit zeros') + def test_bool(self): + pass + + @pytest.mark.skip(reason='getnnz-axis counts explicit zeros') + def test_getnnz_axis(self): + pass + + @pytest.mark.skip(reason='nnz counts explicit zeros') + def test_empty(self): + pass + + +class _NonCanonicalCompressedMixin(_NonCanonicalMixin): + def _arg1_for_noncanonical(self, M, sorted_indices=False): + """Return non-canonical constructor arg1 equivalent to M""" + data, indices, indptr = _same_sum_duplicate(M.data, M.indices, + indptr=M.indptr) + if not sorted_indices: + for start, stop in zip(indptr, indptr[1:]): + indices[start:stop] = indices[start:stop][::-1].copy() + data[start:stop] = data[start:stop][::-1].copy() + return data, indices, indptr + + def _insert_explicit_zero(self, M, i, j): + M[i,j] = 0 + return M + + +class _NonCanonicalCSMixin(_NonCanonicalCompressedMixin): + def test_getelement(self): + def check(dtype, sorted_indices): + D = array([[1,0,0], + [4,3,0], + [0,2,0], + [0,0,0]], dtype=dtype) + A = self.spcreator(D, sorted_indices=sorted_indices) + + M,N = D.shape + + for i in range(-M, M): + for j in range(-N, N): + assert_equal(A[i,j], D[i,j]) + + for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]: + assert_raises((IndexError, TypeError), A.__getitem__, ij) + + for dtype in supported_dtypes: + for sorted_indices in [False, True]: + check(np.dtype(dtype), sorted_indices) + + def test_setitem_sparse(self): + D = np.eye(3) + A = self.spcreator(D) + B = self.spcreator([[1,2,3]]) + + D[1,:] = B.toarray() + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[1,:] = B + assert_array_equal(A.toarray(), D) + + D[:,2] = B.toarray().ravel() + with suppress_warnings() as sup: + sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure") + A[:,2] = B.T + assert_array_equal(A.toarray(), D) + + @pytest.mark.xfail(run=False, reason='inverse broken with non-canonical matrix') + def test_inv(self): + pass + + @pytest.mark.xfail(run=False, reason='solve broken with non-canonical matrix') + def test_solve(self): + pass + + +class TestCSRNonCanonical(_NonCanonicalCSMixin, TestCSR): + pass + + +class TestCSRNonCanonicalMatrix(TestCSRNonCanonical, TestCSRMatrix): + pass + + +class TestCSCNonCanonical(_NonCanonicalCSMixin, TestCSC): + pass + + +class TestCSCNonCanonicalMatrix(TestCSCNonCanonical, TestCSCMatrix): + pass + + +class TestBSRNonCanonical(_NonCanonicalCompressedMixin, TestBSR): + def _insert_explicit_zero(self, M, i, j): + x = M.tocsr() + x[i,j] = 0 + return x.tobsr(blocksize=M.blocksize) + + @pytest.mark.xfail(run=False, reason='diagonal broken with non-canonical BSR') + def test_diagonal(self): + pass + + @pytest.mark.xfail(run=False, reason='expm broken with non-canonical BSR') + def test_expm(self): + pass + + +class TestBSRNonCanonicalMatrix(TestBSRNonCanonical, TestBSRMatrix): + pass + + +class TestCOONonCanonical(_NonCanonicalMixin, TestCOO): + def _arg1_for_noncanonical(self, M, sorted_indices=None): + """Return non-canonical constructor arg1 equivalent to M""" + data, row, col = _same_sum_duplicate(M.data, M.row, M.col) + return data, (row, col) + + def _insert_explicit_zero(self, M, i, j): + M.data = np.r_[M.data.dtype.type(0), M.data] + M.row = np.r_[M.row.dtype.type(i), M.row] + M.col = np.r_[M.col.dtype.type(j), M.col] + return M + + def test_setdiag_noncanonical(self): + m = self.spcreator(np.eye(3)) + m.sum_duplicates() + m.setdiag([3, 2], k=1) + m.sum_duplicates() + assert_(np.all(np.diff(m.col) >= 0)) + + +class TestCOONonCanonicalMatrix(TestCOONonCanonical, TestCOOMatrix): + pass + + +#Todo: Revisit 64bit tests: avoid rerun of all tests for each version of get_index_dtype +def cases_64bit(sp_api): + """Yield all tests for all formats that use get_index_dtype + + This is more than testing get_index_dtype. It allows checking whether upcasting + or downcasting the index dtypes affects test results. The approach used here + does not try to figure out which tests might fail due to 32/64-bit issues. + We just run them all. + So, each test method in that uses cases_64bit reruns most of the test suite! + """ + if sp_api == "sparray": + TEST_CLASSES = [TestBSR, TestCOO, TestCSC, TestCSR, TestDIA, + # lil/dok->other conversion operations use get_index_dtype + # so we include lil & dok test suite even though they do not + # use get_index_dtype within the class. That means many of + # these tests are superfluous, but it's hard to pick which + TestDOK, TestLIL + ] + elif sp_api == "spmatrix": + TEST_CLASSES = [TestBSRMatrix, TestCOOMatrix, TestCSCMatrix, + TestCSRMatrix, TestDIAMatrix, + # lil/dok->other conversion operations use get_index_dtype + TestDOKMatrix, TestLILMatrix + ] + else: + raise ValueError(f"parameter {sp_api=} is not one of 'sparray' or 'spmatrix'") + + # The following features are missing, so skip the tests: + SKIP_TESTS = { + 'test_expm': 'expm for 64-bit indices not available', + 'test_inv': 'linsolve for 64-bit indices not available', + 'test_solve': 'linsolve for 64-bit indices not available', + 'test_scalar_idx_dtype': 'test implemented in base class', + 'test_large_dimensions_reshape': 'test actually requires 64-bit to work', + 'test_constructor_smallcol': 'test verifies int32 indexes', + 'test_constructor_largecol': 'test verifies int64 indexes', + 'test_tocoo_tocsr_tocsc_gh19245': 'test verifies int32 indexes', + } + + for cls in TEST_CLASSES: + for method_name in sorted(dir(cls)): + method = getattr(cls, method_name) + if (method_name.startswith('test_') and + not getattr(method, 'slow', False)): + marks = [] + + msg = SKIP_TESTS.get(method_name) + if bool(msg): + marks += [pytest.mark.skip(reason=msg)] + + markers = getattr(method, 'pytestmark', []) + for mark in markers: + if mark.name in ('skipif', 'skip', 'xfail', 'xslow'): + marks.append(mark) + + yield pytest.param(cls, method_name, marks=marks) + + +class Test64Bit: + # classes that use get_index_dtype + MAT_CLASSES = [ + bsr_matrix, coo_matrix, csc_matrix, csr_matrix, dia_matrix, + bsr_array, coo_array, csc_array, csr_array, dia_array, + ] + + def _compare_index_dtype(self, m, dtype): + dtype = np.dtype(dtype) + if m.format in ['csc', 'csr', 'bsr']: + return (m.indices.dtype == dtype) and (m.indptr.dtype == dtype) + elif m.format == 'coo': + return (m.row.dtype == dtype) and (m.col.dtype == dtype) + elif m.format == 'dia': + return (m.offsets.dtype == dtype) + else: + raise ValueError(f"matrix {m!r} has no integer indices") + + @pytest.mark.thread_unsafe + def test_decorator_maxval_limit(self): + # Test that the with_64bit_maxval_limit decorator works + + @with_64bit_maxval_limit(maxval_limit=10) + def check(mat_cls): + m = mat_cls(np.random.rand(10, 1)) + assert_(self._compare_index_dtype(m, np.int32)) + m = mat_cls(np.random.rand(11, 1)) + assert_(self._compare_index_dtype(m, np.int64)) + + for mat_cls in self.MAT_CLASSES: + check(mat_cls) + + @pytest.mark.thread_unsafe + def test_decorator_maxval_random(self): + # Test that the with_64bit_maxval_limit decorator works (2) + + @with_64bit_maxval_limit(random=True) + def check(mat_cls): + seen_32 = False + seen_64 = False + for k in range(100): + m = mat_cls(np.random.rand(9, 9)) + seen_32 = seen_32 or self._compare_index_dtype(m, np.int32) + seen_64 = seen_64 or self._compare_index_dtype(m, np.int64) + if seen_32 and seen_64: + break + else: + raise AssertionError("both 32 and 64 bit indices not seen") + + for mat_cls in self.MAT_CLASSES: + check(mat_cls) + + @pytest.mark.thread_unsafe + def test_downcast_intp(self): + # Check that bincount and ufunc.reduceat intp downcasts are + # dealt with. The point here is to trigger points in the code + # that can fail on 32-bit systems when using 64-bit indices, + # due to use of functions that only work with intp-size + # indices. + + @with_64bit_maxval_limit(fixed_dtype=np.int64, downcast_maxval=1) + def check_limited(csc_container, csr_container, coo_container): + # These involve indices larger than `downcast_maxval` + a = csc_container([[1, 2], [3, 4], [5, 6]]) + assert_raises(AssertionError, a.count_nonzero, axis=1) + assert_raises(AssertionError, a.sum, axis=0) + + a = csr_container([[1, 2, 3], [3, 4, 6]]) + assert_raises(AssertionError, a.count_nonzero, axis=0) + assert_raises(AssertionError, a.sum, axis=1) + + a = coo_container([[1, 2, 3], [3, 4, 5]]) + assert_raises(AssertionError, a.count_nonzero, axis=0) + a.has_canonical_format = False + assert_raises(AssertionError, a.sum_duplicates) + + @with_64bit_maxval_limit(fixed_dtype=np.int64) + def check_unlimited(csc_container, csr_container, coo_container): + # These involve indices smaller than `downcast_maxval` + a = csc_container([[1, 2], [3, 4], [5, 6]]) + a.count_nonzero(axis=1) + a.sum(axis=0) + + a = csr_container([[1, 2, 3], [3, 4, 6]]) + a.count_nonzero(axis=0) + a.sum(axis=1) + + a = coo_container([[1, 2, 3], [3, 4, 5]]) + a.count_nonzero(axis=0) + a.has_canonical_format = False + a.sum_duplicates() + + check_limited(csc_array, csr_array, coo_array) + check_unlimited(csc_array, csr_array, coo_array) + check_limited(csc_matrix, csr_matrix, coo_matrix) + check_unlimited(csc_matrix, csr_matrix, coo_matrix) + + +# Testing both spmatrices and sparrays for 64bit index dtype handling is +# expensive and double-checks the same code (e.g. _coobase) +class RunAll64Bit: + def _check_resiliency(self, cls, method_name, **kw): + # Resiliency test, to check that sparse matrices deal reasonably + # with varying index data types. + + @with_64bit_maxval_limit(**kw) + def check(cls, method_name): + instance = cls() + if hasattr(instance, 'setup_method'): + instance.setup_method() + try: + getattr(instance, method_name)() + finally: + if hasattr(instance, 'teardown_method'): + instance.teardown_method() + + check(cls, method_name) + + +@pytest.mark.thread_unsafe +@pytest.mark.slow +class Test64BitArray(RunAll64Bit): + # inheritance of pytest test classes does not separate marks for subclasses. + # So we define these functions in both Array and Matrix versions. + @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray")) + def test_resiliency_limit_10(self, cls, method_name): + self._check_resiliency(cls, method_name, maxval_limit=10) + + @pytest.mark.fail_slow(2) + @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray")) + def test_resiliency_random(self, cls, method_name): + # bsr_array.eliminate_zeros relies on csr_array constructor + # not making copies of index arrays --- this is not + # necessarily true when we pick the index data type randomly + self._check_resiliency(cls, method_name, random=True) + + @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray")) + def test_resiliency_all_32(self, cls, method_name): + self._check_resiliency(cls, method_name, fixed_dtype=np.int32) + + @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray")) + def test_resiliency_all_64(self, cls, method_name): + self._check_resiliency(cls, method_name, fixed_dtype=np.int64) + + +@pytest.mark.thread_unsafe +class Test64BitMatrix(RunAll64Bit): + # assert_32bit=True only for spmatrix cuz sparray does not check index content + @pytest.mark.fail_slow(5) + @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix")) + def test_no_64(self, cls, method_name): + self._check_resiliency(cls, method_name, assert_32bit=True) + + # inheritance of pytest test classes does not separate marks for subclasses. + # So we define these functions in both Array and Matrix versions. + @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix")) + def test_resiliency_limit_10(self, cls, method_name): + self._check_resiliency(cls, method_name, maxval_limit=10) + + @pytest.mark.fail_slow(2) + @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix")) + def test_resiliency_random(self, cls, method_name): + # bsr_array.eliminate_zeros relies on csr_array constructor + # not making copies of index arrays --- this is not + # necessarily true when we pick the index data type randomly + self._check_resiliency(cls, method_name, random=True) + + @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix")) + def test_resiliency_all_32(self, cls, method_name): + self._check_resiliency(cls, method_name, fixed_dtype=np.int32) + + @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix")) + def test_resiliency_all_64(self, cls, method_name): + self._check_resiliency(cls, method_name, fixed_dtype=np.int64) + +def test_broadcast_to(): + a = np.array([[1, 0, 2]]) + b = np.array([[1], [0], [2]]) + c = np.array([[1, 0, 2], [0, 3, 0]]) + d = np.array([[7]]) + e = np.array([[0]]) + f = np.array([[0,0,0,0]]) + for container in (csc_matrix, csc_array, csr_matrix, csr_array): + res_a = container(a)._broadcast_to((2,3)) + res_b = container(b)._broadcast_to((3,4)) + res_c = container(c)._broadcast_to((2,3)) + res_d = container(d)._broadcast_to((4,4)) + res_e = container(e)._broadcast_to((5,6)) + res_f = container(f)._broadcast_to((2,4)) + assert_array_equal(res_a.toarray(), np.broadcast_to(a, (2,3))) + assert_array_equal(res_b.toarray(), np.broadcast_to(b, (3,4))) + assert_array_equal(res_c.toarray(), c) + assert_array_equal(res_d.toarray(), np.broadcast_to(d, (4,4))) + assert_array_equal(res_e.toarray(), np.broadcast_to(e, (5,6))) + assert_array_equal(res_f.toarray(), np.broadcast_to(f, (2,4))) + + with pytest.raises(ValueError, match="cannot be broadcast"): + container([[1, 2, 0], [3, 0, 1]])._broadcast_to(shape=(2, 1)) + + with pytest.raises(ValueError, match="cannot be broadcast"): + container([[0, 1, 2]])._broadcast_to(shape=(3, 2)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py new file mode 100644 index 0000000000000000000000000000000000000000..ab091f7c8fccc42c6d9c6c249e59b1d5e9c326b8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py @@ -0,0 +1,447 @@ +"""Test of 1D aspects of sparse array classes""" + +import pytest + +import numpy as np +from numpy.testing import assert_equal, assert_allclose + +from scipy.sparse import ( + bsr_array, csc_array, dia_array, lil_array, + coo_array, csr_array, dok_array, + ) +from scipy.sparse._sputils import supported_dtypes, matrix +from scipy._lib._util import ComplexWarning + + +sup_complex = np.testing.suppress_warnings() +sup_complex.filter(ComplexWarning) + + +spcreators = [coo_array, csr_array, dok_array] +math_dtypes = [np.int64, np.float64, np.complex128] + + +@pytest.fixture +def dat1d(): + return np.array([3, 0, 1, 0], 'd') + + +@pytest.fixture +def datsp_math_dtypes(dat1d): + dat_dtypes = {dtype: dat1d.astype(dtype) for dtype in math_dtypes} + return { + spcreator: [(dtype, dat, spcreator(dat)) for dtype, dat in dat_dtypes.items()] + for spcreator in spcreators + } + + +# Test init with 1D dense input +# sparrays which do not plan to support 1D +@pytest.mark.parametrize("spcreator", [bsr_array, csc_array, dia_array, lil_array]) +def test_no_1d_support_in_init(spcreator): + with pytest.raises(ValueError, match="arrays don't support 1D input"): + spcreator([0, 1, 2, 3]) + + +# Test init with nD dense input +# sparrays which do not yet support nD +@pytest.mark.parametrize( + "spcreator", [csr_array, dok_array, bsr_array, csc_array, dia_array, lil_array] +) +def test_no_nd_support_in_init(spcreator): + with pytest.raises(ValueError, match="arrays don't.*support 3D"): + spcreator(np.ones((3, 2, 4))) + + +# Main tests class +@pytest.mark.parametrize("spcreator", spcreators) +class TestCommon1D: + """test common functionality shared by 1D sparse formats""" + + def test_create_empty(self, spcreator): + assert_equal(spcreator((3,)).toarray(), np.zeros(3)) + assert_equal(spcreator((3,)).nnz, 0) + assert_equal(spcreator((3,)).count_nonzero(), 0) + + def test_invalid_shapes(self, spcreator): + with pytest.raises(ValueError, match='elements cannot be negative'): + spcreator((-3,)) + + def test_repr(self, spcreator, dat1d): + repr(spcreator(dat1d)) + + def test_str(self, spcreator, dat1d): + str(spcreator(dat1d)) + + def test_neg(self, spcreator): + A = np.array([-1, 0, 17, 0, -5, 0, 1, -4, 0, 0, 0, 0], 'd') + assert_equal(-A, (-spcreator(A)).toarray()) + + def test_1d_supported_init(self, spcreator): + A = spcreator([0, 1, 2, 3]) + assert A.ndim == 1 + + def test_reshape_1d_tofrom_row_or_column(self, spcreator): + # add a dimension 1d->2d + x = spcreator([1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5]) + y = x.reshape(1, 12) + desired = [[1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5]] + assert_equal(y.toarray(), desired) + + # remove a size-1 dimension 2d->1d + x = spcreator(desired) + y = x.reshape(12) + assert_equal(y.toarray(), desired[0]) + y2 = x.reshape((12,)) + assert y.shape == y2.shape + + # make a 2d column into 1d. 2d->1d + y = x.T.reshape(12) + assert_equal(y.toarray(), desired[0]) + + def test_reshape(self, spcreator): + x = spcreator([1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5]) + y = x.reshape((4, 3)) + desired = [[1, 0, 7], [0, 0, 0], [0, -3, 0], [0, 0, 5]] + assert_equal(y.toarray(), desired) + + y = x.reshape((12,)) + assert y is x + + y = x.reshape(12) + assert_equal(y.toarray(), x.toarray()) + + def test_sum(self, spcreator): + np.random.seed(1234) + dat_1 = np.array([0, 1, 2, 3, -4, 5, -6, 7, 9]) + dat_2 = np.random.rand(5) + dat_3 = np.array([]) + dat_4 = np.zeros((40,)) + arrays = [dat_1, dat_2, dat_3, dat_4] + + for dat in arrays: + datsp = spcreator(dat) + with np.errstate(over='ignore'): + assert np.isscalar(datsp.sum()) + assert_allclose(dat.sum(), datsp.sum()) + assert_allclose(dat.sum(axis=None), datsp.sum(axis=None)) + assert_allclose(dat.sum(axis=0), datsp.sum(axis=0)) + assert_allclose(dat.sum(axis=-1), datsp.sum(axis=-1)) + + # test `out` parameter + datsp.sum(axis=0, out=np.zeros(())) + + def test_sum_invalid_params(self, spcreator): + out = np.zeros((3,)) # wrong size for out + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + + with pytest.raises(ValueError, match='axis must be None, -1 or 0'): + datsp.sum(axis=1) + with pytest.raises(TypeError, match='Tuples are not accepted'): + datsp.sum(axis=(0, 1)) + with pytest.raises(TypeError, match='axis must be an integer'): + datsp.sum(axis=1.5) + with pytest.raises(ValueError, match='output parameter.*wrong.*dimension'): + datsp.sum(axis=0, out=out) + + def test_numpy_sum(self, spcreator): + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + + dat_sum = np.sum(dat) + datsp_sum = np.sum(datsp) + + assert_allclose(dat_sum, datsp_sum) + + def test_mean(self, spcreator): + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + + assert_allclose(dat.mean(), datsp.mean()) + assert np.isscalar(datsp.mean(axis=None)) + assert_allclose(dat.mean(axis=None), datsp.mean(axis=None)) + assert_allclose(dat.mean(axis=0), datsp.mean(axis=0)) + assert_allclose(dat.mean(axis=-1), datsp.mean(axis=-1)) + + with pytest.raises(ValueError, match='axis'): + datsp.mean(axis=1) + with pytest.raises(ValueError, match='axis'): + datsp.mean(axis=-2) + + def test_mean_invalid_params(self, spcreator): + out = np.asarray(np.zeros((1, 3))) + dat = np.array([[0, 1, 2], [3, -4, 5], [-6, 7, 9]]) + + datsp = spcreator(dat) + with pytest.raises(ValueError, match='axis out of range'): + datsp.mean(axis=3) + with pytest.raises(TypeError, match='Tuples are not accepted'): + datsp.mean(axis=(0, 1)) + with pytest.raises(TypeError, match='axis must be an integer'): + datsp.mean(axis=1.5) + with pytest.raises(ValueError, match='output parameter.*wrong.*dimension'): + datsp.mean(axis=1, out=out) + + def test_sum_dtype(self, spcreator): + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + + for dtype in supported_dtypes: + dat_sum = dat.sum(dtype=dtype) + datsp_sum = datsp.sum(dtype=dtype) + + assert_allclose(dat_sum, datsp_sum) + assert_equal(dat_sum.dtype, datsp_sum.dtype) + + def test_mean_dtype(self, spcreator): + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + + for dtype in supported_dtypes: + dat_mean = dat.mean(dtype=dtype) + datsp_mean = datsp.mean(dtype=dtype) + + assert_allclose(dat_mean, datsp_mean) + assert_equal(dat_mean.dtype, datsp_mean.dtype) + + def test_mean_out(self, spcreator): + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + + dat_out = np.array(0) + datsp_out = np.array(0) + + dat.mean(out=dat_out) + datsp.mean(out=datsp_out) + assert_allclose(dat_out, datsp_out) + + dat.mean(axis=0, out=dat_out) + datsp.mean(axis=0, out=datsp_out) + assert_allclose(dat_out, datsp_out) + + with pytest.raises(ValueError, match="output parameter.*dimension"): + datsp.mean(out=np.array([0])) + with pytest.raises(ValueError, match="output parameter.*dimension"): + datsp.mean(out=np.array([[0]])) + + def test_numpy_mean(self, spcreator): + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + + dat_mean = np.mean(dat) + datsp_mean = np.mean(datsp) + + assert_allclose(dat_mean, datsp_mean) + assert_equal(dat_mean.dtype, datsp_mean.dtype) + + @pytest.mark.thread_unsafe + @sup_complex + def test_from_array(self, spcreator): + A = np.array([2, 3, 4]) + assert_equal(spcreator(A).toarray(), A) + + A = np.array([1.0 + 3j, 0, -1]) + assert_equal(spcreator(A).toarray(), A) + assert_equal(spcreator(A, dtype='int16').toarray(), A.astype('int16')) + + @pytest.mark.thread_unsafe + @sup_complex + def test_from_list(self, spcreator): + A = [2, 3, 4] + assert_equal(spcreator(A).toarray(), A) + + A = [1.0 + 3j, 0, -1] + assert_equal(spcreator(A).toarray(), np.array(A)) + assert_equal( + spcreator(A, dtype='int16').toarray(), np.array(A).astype('int16') + ) + + @pytest.mark.thread_unsafe + @sup_complex + def test_from_sparse(self, spcreator): + D = np.array([1, 0, 0]) + S = coo_array(D) + assert_equal(spcreator(S).toarray(), D) + S = spcreator(D) + assert_equal(spcreator(S).toarray(), D) + + D = np.array([1.0 + 3j, 0, -1]) + S = coo_array(D) + assert_equal(spcreator(S).toarray(), D) + assert_equal(spcreator(S, dtype='int16').toarray(), D.astype('int16')) + S = spcreator(D) + assert_equal(spcreator(S).toarray(), D) + assert_equal(spcreator(S, dtype='int16').toarray(), D.astype('int16')) + + def test_toarray(self, spcreator, dat1d): + datsp = spcreator(dat1d) + # Check C- or F-contiguous (default). + chk = datsp.toarray() + assert_equal(chk, dat1d) + assert chk.flags.c_contiguous == chk.flags.f_contiguous + + # Check C-contiguous (with arg). + chk = datsp.toarray(order='C') + assert_equal(chk, dat1d) + assert chk.flags.c_contiguous + assert chk.flags.f_contiguous + + # Check F-contiguous (with arg). + chk = datsp.toarray(order='F') + assert_equal(chk, dat1d) + assert chk.flags.c_contiguous + assert chk.flags.f_contiguous + + # Check with output arg. + out = np.zeros(datsp.shape, dtype=datsp.dtype) + datsp.toarray(out=out) + assert_equal(out, dat1d) + + # Check that things are fine when we don't initialize with zeros. + out[...] = 1.0 + datsp.toarray(out=out) + assert_equal(out, dat1d) + + # np.dot does not work with sparse matrices (unless scalars) + # so this is testing whether dat1d matches datsp.toarray() + a = np.array([1.0, 2.0, 3.0, 4.0]) + dense_dot_dense = np.dot(a, dat1d) + check = np.dot(a, datsp.toarray()) + assert_equal(dense_dot_dense, check) + + b = np.array([1.0, 2.0, 3.0, 4.0]) + dense_dot_dense = np.dot(dat1d, b) + check = np.dot(datsp.toarray(), b) + assert_equal(dense_dot_dense, check) + + # Check bool data works. + spbool = spcreator(dat1d, dtype=bool) + arrbool = dat1d.astype(bool) + assert_equal(spbool.toarray(), arrbool) + + def test_add(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + a = dat.copy() + a[0] = 2.0 + b = datsp + c = b + a + assert_equal(c, b.toarray() + a) + + # test broadcasting + # Note: cant add nonzero scalar to sparray. Can add len 1 array + c = b + a[0:1] + assert_equal(c, b.toarray() + a[0]) + + def test_radd(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + a = dat.copy() + a[0] = 2.0 + b = datsp + c = a + b + assert_equal(c, a + b.toarray()) + + def test_rsub(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + if dtype == np.dtype('bool'): + # boolean array subtraction deprecated in 1.9.0 + continue + + assert_equal((dat - datsp), [0, 0, 0, 0]) + assert_equal((datsp - dat), [0, 0, 0, 0]) + assert_equal((0 - datsp).toarray(), -dat) + + A = spcreator([1, -4, 0, 2], dtype='d') + assert_equal((dat - A), dat - A.toarray()) + assert_equal((A - dat), A.toarray() - dat) + assert_equal(A.toarray() - datsp, A.toarray() - dat) + assert_equal(datsp - A.toarray(), dat - A.toarray()) + + # test broadcasting + assert_equal(dat[:1] - datsp, dat[:1] - dat) + + def test_matmul_basic(self, spcreator): + A = np.array([[2, 0, 3.0], [0, 0, 0], [0, 1, 2]]) + v = np.array([1, 0, 3]) + Asp = spcreator(A) + vsp = spcreator(v) + + # sparse result when both args are sparse and result not scalar + assert_equal((Asp @ vsp).toarray(), A @ v) + assert_equal(A @ vsp, A @ v) + assert_equal(Asp @ v, A @ v) + assert_equal((vsp @ Asp).toarray(), v @ A) + assert_equal(vsp @ A, v @ A) + assert_equal(v @ Asp, v @ A) + + assert_equal(vsp @ vsp, v @ v) + assert_equal(v @ vsp, v @ v) + assert_equal(vsp @ v, v @ v) + assert_equal((Asp @ Asp).toarray(), A @ A) + assert_equal(A @ Asp, A @ A) + assert_equal(Asp @ A, A @ A) + + def test_matvec(self, spcreator): + A = np.array([2, 0, 3.0]) + Asp = spcreator(A) + col = np.array([[1, 2, 3]]).T + + assert_allclose(Asp @ col, Asp.toarray() @ col) + + assert (A @ np.array([1, 2, 3])).shape == () + assert Asp @ np.array([1, 2, 3]) == 11 + assert (Asp @ np.array([1, 2, 3])).shape == () + assert (Asp @ np.array([[1], [2], [3]])).shape == (1,) + # check result type + assert isinstance(Asp @ matrix([[1, 2, 3]]).T, np.ndarray) + + # ensure exception is raised for improper dimensions + bad_vecs = [np.array([1, 2]), np.array([1, 2, 3, 4]), np.array([[1], [2]])] + for x in bad_vecs: + with pytest.raises(ValueError, match='dimension mismatch'): + Asp @ x + + # The current relationship between sparse matrix products and array + # products is as follows: + dot_result = np.dot(Asp.toarray(), [1, 2, 3]) + assert_allclose(Asp @ np.array([1, 2, 3]), dot_result) + assert_allclose(Asp @ [[1], [2], [3]], dot_result.T) + # Note that the result of Asp @ x is dense if x has a singleton dimension. + + def test_rmatvec(self, spcreator, dat1d): + M = spcreator(dat1d) + assert_allclose([1, 2, 3, 4] @ M, np.dot([1, 2, 3, 4], M.toarray())) + row = np.array([[1, 2, 3, 4]]) + assert_allclose(row @ M, row @ M.toarray()) + + def test_transpose(self, spcreator, dat1d): + for A in [dat1d, np.array([])]: + B = spcreator(A) + assert_equal(B.toarray(), A) + assert_equal(B.transpose().toarray(), A) + assert_equal(B.dtype, A.dtype) + + def test_add_dense_to_sparse(self, spcreator, datsp_math_dtypes): + for dtype, dat, datsp in datsp_math_dtypes[spcreator]: + sum1 = dat + datsp + assert_equal(sum1, dat + dat) + sum2 = datsp + dat + assert_equal(sum2, dat + dat) + + def test_iterator(self, spcreator): + # test that __iter__ is compatible with NumPy + B = np.arange(5) + A = spcreator(B) + + if A.format not in ['coo', 'dia', 'bsr']: + for x, y in zip(A, B): + assert_equal(x, y) + + def test_resize(self, spcreator): + # resize(shape) resizes the matrix in-place + D = np.array([1, 0, 3, 4]) + S = spcreator(D) + assert S.resize((3,)) is None + assert_equal(S.toarray(), [1, 0, 3]) + S.resize((5,)) + assert_equal(S.toarray(), [1, 0, 3, 0, 0]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py new file mode 100644 index 0000000000000000000000000000000000000000..38b8288c39f4ebacd9cadc58bba7b18416377c73 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py @@ -0,0 +1,872 @@ +"""test sparse matrix construction functions""" + +import numpy as np +from numpy import array +from numpy.testing import (assert_equal, assert_, + assert_array_equal, assert_array_almost_equal_nulp) +import pytest +from pytest import raises as assert_raises +from scipy._lib._testutils import check_free_memory + +from scipy.sparse import (csr_matrix, coo_matrix, + csr_array, coo_array, + csc_array, bsr_array, + dia_array, dok_array, + lil_array, csc_matrix, + bsr_matrix, dia_matrix, + lil_matrix, sparray, spmatrix, + _construct as construct) +from scipy.sparse._construct import rand as sprand + +sparse_formats = ['csr','csc','coo','bsr','dia','lil','dok'] + +#TODO check whether format=XXX is respected + + +def _sprandn(m, n, density=0.01, format="coo", dtype=None, rng=None): + # Helper function for testing. + rng = np.random.default_rng(rng) + data_rvs = rng.standard_normal + return construct.random(m, n, density, format, dtype, rng, data_rvs) + + +def _sprandn_array(m, n, density=0.01, format="coo", dtype=None, rng=None): + # Helper function for testing. + rng = np.random.default_rng(rng) + data_sampler = rng.standard_normal + return construct.random_array((m, n), density=density, format=format, dtype=dtype, + rng=rng, data_sampler=data_sampler) + + +class TestConstructUtils: + + @pytest.mark.parametrize("cls", [ + csc_array, csr_array, coo_array, bsr_array, + dia_array, dok_array, lil_array + ]) + def test_singleton_array_constructor(self, cls): + with pytest.raises( + ValueError, + match=( + 'scipy sparse array classes do not support ' + 'instantiation from a scalar' + ) + ): + cls(0) + + @pytest.mark.parametrize("cls", [ + csc_matrix, csr_matrix, coo_matrix, + bsr_matrix, dia_matrix, lil_matrix + ]) + def test_singleton_matrix_constructor(self, cls): + """ + This test is for backwards compatibility post scipy 1.13. + The behavior observed here is what is to be expected + with the older matrix classes. This test comes with the + exception of dok_matrix, which was not working pre scipy1.12 + (unlike the rest of these). + """ + assert cls(0).shape == (1, 1) + + def test_spdiags(self): + diags1 = array([[1, 2, 3, 4, 5]]) + diags2 = array([[1, 2, 3, 4, 5], + [6, 7, 8, 9,10]]) + diags3 = array([[1, 2, 3, 4, 5], + [6, 7, 8, 9,10], + [11,12,13,14,15]]) + + cases = [] + cases.append((diags1, 0, 1, 1, [[1]])) + cases.append((diags1, [0], 1, 1, [[1]])) + cases.append((diags1, [0], 2, 1, [[1],[0]])) + cases.append((diags1, [0], 1, 2, [[1,0]])) + cases.append((diags1, [1], 1, 2, [[0,2]])) + cases.append((diags1,[-1], 1, 2, [[0,0]])) + cases.append((diags1, [0], 2, 2, [[1,0],[0,2]])) + cases.append((diags1,[-1], 2, 2, [[0,0],[1,0]])) + cases.append((diags1, [3], 2, 2, [[0,0],[0,0]])) + cases.append((diags1, [0], 3, 4, [[1,0,0,0],[0,2,0,0],[0,0,3,0]])) + cases.append((diags1, [1], 3, 4, [[0,2,0,0],[0,0,3,0],[0,0,0,4]])) + cases.append((diags1, [2], 3, 5, [[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]])) + + cases.append((diags2, [0,2], 3, 3, [[1,0,8],[0,2,0],[0,0,3]])) + cases.append((diags2, [-1,0], 3, 4, [[6,0,0,0],[1,7,0,0],[0,2,8,0]])) + cases.append((diags2, [2,-3], 6, 6, [[0,0,3,0,0,0], + [0,0,0,4,0,0], + [0,0,0,0,5,0], + [6,0,0,0,0,0], + [0,7,0,0,0,0], + [0,0,8,0,0,0]])) + + cases.append((diags3, [-1,0,1], 6, 6, [[6,12, 0, 0, 0, 0], + [1, 7,13, 0, 0, 0], + [0, 2, 8,14, 0, 0], + [0, 0, 3, 9,15, 0], + [0, 0, 0, 4,10, 0], + [0, 0, 0, 0, 5, 0]])) + cases.append((diags3, [-4,2,-1], 6, 5, [[0, 0, 8, 0, 0], + [11, 0, 0, 9, 0], + [0,12, 0, 0,10], + [0, 0,13, 0, 0], + [1, 0, 0,14, 0], + [0, 2, 0, 0,15]])) + cases.append((diags3, [-1, 1, 2], len(diags3[0]), len(diags3[0]), + [[0, 7, 13, 0, 0], + [1, 0, 8, 14, 0], + [0, 2, 0, 9, 15], + [0, 0, 3, 0, 10], + [0, 0, 0, 4, 0]])) + + for d, o, m, n, result in cases: + if len(d[0]) == m and m == n: + assert_equal(construct.spdiags(d, o).toarray(), result) + assert_equal(construct.spdiags(d, o, m, n).toarray(), result) + assert_equal(construct.spdiags(d, o, (m, n)).toarray(), result) + + def test_diags(self): + a = array([1, 2, 3, 4, 5]) + b = array([6, 7, 8, 9, 10]) + c = array([11, 12, 13, 14, 15]) + + cases = [] + cases.append((a[:1], 0, (1, 1), [[1]])) + cases.append(([a[:1]], [0], (1, 1), [[1]])) + cases.append(([a[:1]], [0], (2, 1), [[1],[0]])) + cases.append(([a[:1]], [0], (1, 2), [[1,0]])) + cases.append(([a[:1]], [1], (1, 2), [[0,1]])) + cases.append(([a[:2]], [0], (2, 2), [[1,0],[0,2]])) + cases.append(([a[:1]],[-1], (2, 2), [[0,0],[1,0]])) + cases.append(([a[:3]], [0], (3, 4), [[1,0,0,0],[0,2,0,0],[0,0,3,0]])) + cases.append(([a[:3]], [1], (3, 4), [[0,1,0,0],[0,0,2,0],[0,0,0,3]])) + cases.append(([a[:1]], [-2], (3, 5), [[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0]])) + cases.append(([a[:2]], [-1], (3, 5), [[0,0,0,0,0],[1,0,0,0,0],[0,2,0,0,0]])) + cases.append(([a[:3]], [0], (3, 5), [[1,0,0,0,0],[0,2,0,0,0],[0,0,3,0,0]])) + cases.append(([a[:3]], [1], (3, 5), [[0,1,0,0,0],[0,0,2,0,0],[0,0,0,3,0]])) + cases.append(([a[:3]], [2], (3, 5), [[0,0,1,0,0],[0,0,0,2,0],[0,0,0,0,3]])) + cases.append(([a[:2]], [3], (3, 5), [[0,0,0,1,0],[0,0,0,0,2],[0,0,0,0,0]])) + cases.append(([a[:1]], [4], (3, 5), [[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0]])) + cases.append(([a[:1]], [-4], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[1,0,0]])) + cases.append(([a[:2]], [-3], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[1,0,0],[0,2,0]])) + cases.append(([a[:3]], [-2], (5, 3), [[0,0,0],[0,0,0],[1,0,0],[0,2,0],[0,0,3]])) + cases.append(([a[:3]], [-1], (5, 3), [[0,0,0],[1,0,0],[0,2,0],[0,0,3],[0,0,0]])) + cases.append(([a[:3]], [0], (5, 3), [[1,0,0],[0,2,0],[0,0,3],[0,0,0],[0,0,0]])) + cases.append(([a[:2]], [1], (5, 3), [[0,1,0],[0,0,2],[0,0,0],[0,0,0],[0,0,0]])) + cases.append(([a[:1]], [2], (5, 3), [[0,0,1],[0,0,0],[0,0,0],[0,0,0],[0,0,0]])) + + cases.append(([a[:3],b[:1]], [0,2], (3, 3), [[1,0,6],[0,2,0],[0,0,3]])) + cases.append(([a[:2],b[:3]], [-1,0], (3, 4), [[6,0,0,0],[1,7,0,0],[0,2,8,0]])) + cases.append(([a[:4],b[:3]], [2,-3], (6, 6), [[0,0,1,0,0,0], + [0,0,0,2,0,0], + [0,0,0,0,3,0], + [6,0,0,0,0,4], + [0,7,0,0,0,0], + [0,0,8,0,0,0]])) + + cases.append(([a[:4],b,c[:4]], [-1,0,1], (5, 5), [[6,11, 0, 0, 0], + [1, 7,12, 0, 0], + [0, 2, 8,13, 0], + [0, 0, 3, 9,14], + [0, 0, 0, 4,10]])) + cases.append(([a[:2],b[:3],c], [-4,2,-1], (6, 5), [[0, 0, 6, 0, 0], + [11, 0, 0, 7, 0], + [0,12, 0, 0, 8], + [0, 0,13, 0, 0], + [1, 0, 0,14, 0], + [0, 2, 0, 0,15]])) + + # too long arrays are OK + cases.append(([a], [0], (1, 1), [[1]])) + cases.append(([a[:3],b], [0,2], (3, 3), [[1, 0, 6], [0, 2, 0], [0, 0, 3]])) + cases.append(( + np.array([[1, 2, 3], [4, 5, 6]]), + [0,-1], + (3, 3), + [[1, 0, 0], [4, 2, 0], [0, 5, 3]] + )) + + # scalar case: broadcasting + cases.append(([1,-2,1], [1,0,-1], (3, 3), [[-2, 1, 0], + [1, -2, 1], + [0, 1, -2]])) + + for d, o, shape, result in cases: + err_msg = f"{d!r} {o!r} {shape!r} {result!r}" + assert_equal(construct.diags(d, offsets=o, shape=shape).toarray(), + result, err_msg=err_msg) + + if (shape[0] == shape[1] + and hasattr(d[0], '__len__') + and len(d[0]) <= max(shape)): + # should be able to find the shape automatically + assert_equal(construct.diags(d, offsets=o).toarray(), result, + err_msg=err_msg) + + def test_diags_default(self): + a = array([1, 2, 3, 4, 5]) + assert_equal(construct.diags(a).toarray(), np.diag(a)) + + def test_diags_default_bad(self): + a = array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]) + assert_raises(ValueError, construct.diags, a) + + def test_diags_bad(self): + a = array([1, 2, 3, 4, 5]) + b = array([6, 7, 8, 9, 10]) + c = array([11, 12, 13, 14, 15]) + + cases = [] + cases.append(([a[:0]], 0, (1, 1))) + cases.append(([a[:4],b,c[:3]], [-1,0,1], (5, 5))) + cases.append(([a[:2],c,b[:3]], [-4,2,-1], (6, 5))) + cases.append(([a[:2],c,b[:3]], [-4,2,-1], None)) + cases.append(([], [-4,2,-1], None)) + cases.append(([1], [-5], (4, 4))) + cases.append(([a], 0, None)) + + for d, o, shape in cases: + assert_raises(ValueError, construct.diags, d, offsets=o, shape=shape) + + assert_raises(TypeError, construct.diags, [[None]], offsets=[0]) + + def test_diags_vs_diag(self): + # Check that + # + # diags([a, b, ...], [i, j, ...]) == diag(a, i) + diag(b, j) + ... + # + + rng = np.random.RandomState(1234) + + for n_diags in [1, 2, 3, 4, 5, 10]: + n = 1 + n_diags//2 + rng.randint(0, 10) + + offsets = np.arange(-n+1, n-1) + rng.shuffle(offsets) + offsets = offsets[:n_diags] + + diagonals = [rng.rand(n - abs(q)) for q in offsets] + + mat = construct.diags(diagonals, offsets=offsets) + dense_mat = sum([np.diag(x, j) for x, j in zip(diagonals, offsets)]) + + assert_array_almost_equal_nulp(mat.toarray(), dense_mat) + + if len(offsets) == 1: + mat = construct.diags(diagonals[0], offsets=offsets[0]) + dense_mat = np.diag(diagonals[0], offsets[0]) + assert_array_almost_equal_nulp(mat.toarray(), dense_mat) + + def test_diags_dtype(self): + x = construct.diags([2.2], offsets=[0], shape=(2, 2), dtype=int) + assert_equal(x.dtype, int) + assert_equal(x.toarray(), [[2, 0], [0, 2]]) + + def test_diags_one_diagonal(self): + d = list(range(5)) + for k in range(-5, 6): + assert_equal(construct.diags(d, offsets=k).toarray(), + construct.diags([d], offsets=[k]).toarray()) + + def test_diags_empty(self): + x = construct.diags([]) + assert_equal(x.shape, (0, 0)) + + @pytest.mark.parametrize("identity", [construct.identity, construct.eye_array]) + def test_identity(self, identity): + assert_equal(identity(1).toarray(), [[1]]) + assert_equal(identity(2).toarray(), [[1,0],[0,1]]) + + I = identity(3, dtype='int8', format='dia') + assert_equal(I.dtype, np.dtype('int8')) + assert_equal(I.format, 'dia') + + for fmt in sparse_formats: + I = identity(3, format=fmt) + assert_equal(I.format, fmt) + assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]]) + + @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array]) + def test_eye(self, eye): + assert_equal(eye(1,1).toarray(), [[1]]) + assert_equal(eye(2,3).toarray(), [[1,0,0],[0,1,0]]) + assert_equal(eye(3,2).toarray(), [[1,0],[0,1],[0,0]]) + assert_equal(eye(3,3).toarray(), [[1,0,0],[0,1,0],[0,0,1]]) + + assert_equal(eye(3,3,dtype='int16').dtype, np.dtype('int16')) + + for m in [3, 5]: + for n in [3, 5]: + for k in range(-5,6): + # scipy.sparse.eye deviates from np.eye here. np.eye will + # create arrays of all 0's when the diagonal offset is + # greater than the size of the array. For sparse arrays + # this makes less sense, especially as it results in dia + # arrays with negative diagonals. Therefore sp.sparse.eye + # validates that diagonal offsets fall within the shape of + # the array. See gh-18555. + if (k > 0 and k > n) or (k < 0 and abs(k) > m): + with pytest.raises( + ValueError, match="Offset.*out of bounds" + ): + eye(m, n, k=k) + + else: + assert_equal( + eye(m, n, k=k).toarray(), + np.eye(m, n, k=k) + ) + if m == n: + assert_equal( + eye(m, k=k).toarray(), + np.eye(m, n, k=k) + ) + + @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array]) + def test_eye_one(self, eye): + assert_equal(eye(1).toarray(), [[1]]) + assert_equal(eye(2).toarray(), [[1,0],[0,1]]) + + I = eye(3, dtype='int8', format='dia') + assert_equal(I.dtype, np.dtype('int8')) + assert_equal(I.format, 'dia') + + for fmt in sparse_formats: + I = eye(3, format=fmt) + assert_equal(I.format, fmt) + assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]]) + + def test_eye_array_vs_matrix(self): + assert isinstance(construct.eye_array(3), sparray) + assert not isinstance(construct.eye(3), sparray) + + def test_kron(self): + cases = [] + + cases.append(array([[0]])) + cases.append(array([[-1]])) + cases.append(array([[4]])) + cases.append(array([[10]])) + cases.append(array([[0],[0]])) + cases.append(array([[0,0]])) + cases.append(array([[1,2],[3,4]])) + cases.append(array([[0,2],[5,0]])) + cases.append(array([[0,2,-6],[8,0,14]])) + cases.append(array([[5,4],[0,0],[6,0]])) + cases.append(array([[5,4,4],[1,0,0],[6,0,8]])) + cases.append(array([[0,1,0,2,0,5,8]])) + cases.append(array([[0.5,0.125,0,3.25],[0,2.5,0,0]])) + + # test all cases with some formats + for a in cases: + ca = csr_array(a) + for b in cases: + cb = csr_array(b) + expected = np.kron(a, b) + for fmt in sparse_formats[1:4]: + result = construct.kron(ca, cb, format=fmt) + assert_equal(result.format, fmt) + assert_array_equal(result.toarray(), expected) + assert isinstance(result, sparray) + + # test one case with all formats + a = cases[-1] + b = cases[-3] + ca = csr_array(a) + cb = csr_array(b) + + expected = np.kron(a, b) + for fmt in sparse_formats: + result = construct.kron(ca, cb, format=fmt) + assert_equal(result.format, fmt) + assert_array_equal(result.toarray(), expected) + assert isinstance(result, sparray) + + # check that spmatrix returned when both inputs are spmatrix + result = construct.kron(csr_matrix(a), csr_matrix(b), format=fmt) + assert_equal(result.format, fmt) + assert_array_equal(result.toarray(), expected) + assert isinstance(result, spmatrix) + + def test_kron_ndim_exceptions(self): + with pytest.raises(ValueError, match='requires 2D input'): + construct.kron([[0], [1]], csr_array([0, 1])) + with pytest.raises(ValueError, match='requires 2D input'): + construct.kron(csr_array([0, 1]), [[0], [1]]) + # no exception if sparse arrays are not input (spmatrix inferred) + construct.kron([[0], [1]], [0, 1]) + + def test_kron_large(self): + n = 2**16 + a = construct.diags_array([1], shape=(1, n), offsets=n-1) + b = construct.diags_array([1], shape=(n, 1), offsets=1-n) + + construct.kron(a, a) + construct.kron(b, b) + + def test_kronsum(self): + cases = [] + + cases.append(array([[0]])) + cases.append(array([[-1]])) + cases.append(array([[4]])) + cases.append(array([[10]])) + cases.append(array([[1,2],[3,4]])) + cases.append(array([[0,2],[5,0]])) + cases.append(array([[0,2,-6],[8,0,14],[0,3,0]])) + cases.append(array([[1,0,0],[0,5,-1],[4,-2,8]])) + + # test all cases with default format + for a in cases: + for b in cases: + result = construct.kronsum(csr_array(a), csr_array(b)).toarray() + expected = (np.kron(np.eye(b.shape[0]), a) + + np.kron(b, np.eye(a.shape[0]))) + assert_array_equal(result, expected) + + # check that spmatrix returned when both inputs are spmatrix + result = construct.kronsum(csr_matrix(a), csr_matrix(b)).toarray() + assert_array_equal(result, expected) + + def test_kronsum_ndim_exceptions(self): + with pytest.raises(ValueError, match='requires 2D input'): + construct.kronsum([[0], [1]], csr_array([0, 1])) + with pytest.raises(ValueError, match='requires 2D input'): + construct.kronsum(csr_array([0, 1]), [[0], [1]]) + # no exception if sparse arrays are not input (spmatrix inferred) + construct.kronsum([[0, 1], [1, 0]], [2]) + + @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array]) + def test_vstack(self, coo_cls): + A = coo_cls([[1,2],[3,4]]) + B = coo_cls([[5,6]]) + + expected = array([[1, 2], + [3, 4], + [5, 6]]) + assert_equal(construct.vstack([A, B]).toarray(), expected) + assert_equal(construct.vstack([A, B], dtype=np.float32).dtype, + np.float32) + + assert_equal(construct.vstack([A.todok(), B.todok()]).toarray(), expected) + + assert_equal(construct.vstack([A.tocsr(), B.tocsr()]).toarray(), + expected) + result = construct.vstack([A.tocsr(), B.tocsr()], + format="csr", dtype=np.float32) + assert_equal(result.dtype, np.float32) + assert_equal(result.indices.dtype, np.int32) + assert_equal(result.indptr.dtype, np.int32) + + assert_equal(construct.vstack([A.tocsc(), B.tocsc()]).toarray(), + expected) + result = construct.vstack([A.tocsc(), B.tocsc()], + format="csc", dtype=np.float32) + assert_equal(result.dtype, np.float32) + assert_equal(result.indices.dtype, np.int32) + assert_equal(result.indptr.dtype, np.int32) + + def test_vstack_maintain64bit_idx_dtype(self): + # see gh-20389 v/hstack returns int32 idx_dtype with input int64 idx_dtype + X = csr_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.indptr = X.indptr.astype(np.int64) + X.indices = X.indices.astype(np.int64) + assert construct.vstack([X, X]).indptr.dtype == np.int64 + assert construct.hstack([X, X]).indptr.dtype == np.int64 + + X = csc_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.indptr = X.indptr.astype(np.int64) + X.indices = X.indices.astype(np.int64) + assert construct.vstack([X, X]).indptr.dtype == np.int64 + assert construct.hstack([X, X]).indptr.dtype == np.int64 + + X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.coords = tuple(co.astype(np.int64) for co in X.coords) + assert construct.vstack([X, X]).coords[0].dtype == np.int64 + assert construct.hstack([X, X]).coords[0].dtype == np.int64 + + def test_vstack_matrix_or_array(self): + A = [[1,2],[3,4]] + B = [[5,6]] + assert isinstance(construct.vstack([coo_array(A), coo_array(B)]), sparray) + assert isinstance(construct.vstack([coo_array(A), coo_matrix(B)]), sparray) + assert isinstance(construct.vstack([coo_matrix(A), coo_array(B)]), sparray) + assert isinstance(construct.vstack([coo_matrix(A), coo_matrix(B)]), spmatrix) + + def test_vstack_1d_with_2d(self): + # fixes gh-21064 + arr = csr_array([[1, 0, 0], [0, 1, 0]]) + arr1d = csr_array([1, 0, 0]) + arr1dcoo = coo_array([1, 0, 0]) + assert construct.vstack([arr, np.array([0, 0, 0])]).shape == (3, 3) + assert construct.hstack([arr1d, np.array([[0]])]).shape == (1, 4) + assert construct.hstack([arr1d, arr1d]).shape == (1, 6) + assert construct.vstack([arr1d, arr1d]).shape == (2, 3) + + # check csr specialty stacking code like _stack_along_minor_axis + assert construct.hstack([arr, arr]).shape == (2, 6) + assert construct.hstack([arr1d, arr1d]).shape == (1, 6) + + assert construct.hstack([arr1d, arr1dcoo]).shape == (1, 6) + assert construct.vstack([arr, arr1dcoo]).shape == (3, 3) + assert construct.vstack([arr1d, arr1dcoo]).shape == (2, 3) + + with pytest.raises(ValueError, match="incompatible row dimensions"): + construct.hstack([arr, np.array([0, 0])]) + with pytest.raises(ValueError, match="incompatible column dimensions"): + construct.vstack([arr, np.array([0, 0])]) + + @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array]) + def test_hstack(self, coo_cls): + A = coo_cls([[1,2],[3,4]]) + B = coo_cls([[5],[6]]) + + expected = array([[1, 2, 5], + [3, 4, 6]]) + assert_equal(construct.hstack([A, B]).toarray(), expected) + assert_equal(construct.hstack([A, B], dtype=np.float32).dtype, + np.float32) + + assert_equal(construct.hstack([A.todok(), B.todok()]).toarray(), expected) + + assert_equal(construct.hstack([A.tocsc(), B.tocsc()]).toarray(), + expected) + assert_equal(construct.hstack([A.tocsc(), B.tocsc()], + dtype=np.float32).dtype, + np.float32) + assert_equal(construct.hstack([A.tocsr(), B.tocsr()]).toarray(), + expected) + assert_equal(construct.hstack([A.tocsr(), B.tocsr()], + dtype=np.float32).dtype, + np.float32) + + def test_hstack_matrix_or_array(self): + A = [[1,2],[3,4]] + B = [[5],[6]] + assert isinstance(construct.hstack([coo_array(A), coo_array(B)]), sparray) + assert isinstance(construct.hstack([coo_array(A), coo_matrix(B)]), sparray) + assert isinstance(construct.hstack([coo_matrix(A), coo_array(B)]), sparray) + assert isinstance(construct.hstack([coo_matrix(A), coo_matrix(B)]), spmatrix) + + @pytest.mark.parametrize("block_array", (construct.bmat, construct.block_array)) + def test_block_creation(self, block_array): + + A = coo_array([[1, 2], [3, 4]]) + B = coo_array([[5],[6]]) + C = coo_array([[7]]) + D = coo_array((0, 0)) + + expected = array([[1, 2, 5], + [3, 4, 6], + [0, 0, 7]]) + assert_equal(block_array([[A, B], [None, C]]).toarray(), expected) + E = csr_array((1, 2), dtype=np.int32) + assert_equal(block_array([[A.tocsr(), B.tocsr()], + [E, C.tocsr()]]).toarray(), + expected) + assert_equal(block_array([[A.tocsc(), B.tocsc()], + [E.tocsc(), C.tocsc()]]).toarray(), + expected) + + expected = array([[1, 2, 0], + [3, 4, 0], + [0, 0, 7]]) + assert_equal(block_array([[A, None], [None, C]]).toarray(), expected) + assert_equal(block_array([[A.tocsr(), E.T.tocsr()], + [E, C.tocsr()]]).toarray(), + expected) + assert_equal(block_array([[A.tocsc(), E.T.tocsc()], + [E.tocsc(), C.tocsc()]]).toarray(), + expected) + + Z = csr_array((1, 1), dtype=np.int32) + expected = array([[0, 5], + [0, 6], + [7, 0]]) + assert_equal(block_array([[None, B], [C, None]]).toarray(), expected) + assert_equal(block_array([[E.T.tocsr(), B.tocsr()], + [C.tocsr(), Z]]).toarray(), + expected) + assert_equal(block_array([[E.T.tocsc(), B.tocsc()], + [C.tocsc(), Z.tocsc()]]).toarray(), + expected) + + expected = np.empty((0, 0)) + assert_equal(block_array([[None, None]]).toarray(), expected) + assert_equal(block_array([[None, D], [D, None]]).toarray(), + expected) + + # test bug reported in gh-5976 + expected = array([[7]]) + assert_equal(block_array([[None, D], [C, None]]).toarray(), + expected) + + # test failure cases + with assert_raises(ValueError) as excinfo: + block_array([[A], [B]]) + excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsr()], [B.tocsr()]]) + excinfo.match(r'incompatible dimensions for axis 1') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsc()], [B.tocsc()]]) + excinfo.match(r'Mismatching dimensions along axis 1: ({1, 2}|{2, 1})') + + with assert_raises(ValueError) as excinfo: + block_array([[A, C]]) + excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsr(), C.tocsr()]]) + excinfo.match(r'Mismatching dimensions along axis 0: ({1, 2}|{2, 1})') + + with assert_raises(ValueError) as excinfo: + block_array([[A.tocsc(), C.tocsc()]]) + excinfo.match(r'incompatible dimensions for axis 0') + + def test_block_return_type(self): + block = construct.block_array + + # csr format ensures we hit _compressed_sparse_stack + # shape of F,G ensure we hit _stack_along_minor_axis + # list version ensure we hit the path with neither helper function + Fl, Gl = [[1, 2],[3, 4]], [[7], [5]] + Fm, Gm = csr_matrix(Fl), csr_matrix(Gl) + assert isinstance(block([[None, Fl], [Gl, None]], format="csr"), sparray) + assert isinstance(block([[None, Fm], [Gm, None]], format="csr"), sparray) + assert isinstance(block([[Fm, Gm]], format="csr"), sparray) + + def test_bmat_return_type(self): + """This can be removed after sparse matrix is removed""" + bmat = construct.bmat + # check return type. if any input _is_array output array, else matrix + Fl, Gl = [[1, 2],[3, 4]], [[7], [5]] + Fm, Gm = csr_matrix(Fl), csr_matrix(Gl) + Fa, Ga = csr_array(Fl), csr_array(Gl) + assert isinstance(bmat([[Fa, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Fm, Gm]], format="csr"), spmatrix) + assert isinstance(bmat([[None, Fa], [Ga, None]], format="csr"), sparray) + assert isinstance(bmat([[None, Fm], [Ga, None]], format="csr"), sparray) + assert isinstance(bmat([[None, Fm], [Gm, None]], format="csr"), spmatrix) + assert isinstance(bmat([[None, Fl], [Gl, None]], format="csr"), spmatrix) + + # type returned by _compressed_sparse_stack (all csr) + assert isinstance(bmat([[Ga, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Gm, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Ga, Gm]], format="csr"), sparray) + assert isinstance(bmat([[Gm, Gm]], format="csr"), spmatrix) + # shape is 2x2 so no _stack_along_minor_axis + assert isinstance(bmat([[Fa, Fm]], format="csr"), sparray) + assert isinstance(bmat([[Fm, Fm]], format="csr"), spmatrix) + + # type returned by _compressed_sparse_stack (all csc) + assert isinstance(bmat([[Gm.tocsc(), Ga.tocsc()]], format="csc"), sparray) + assert isinstance(bmat([[Gm.tocsc(), Gm.tocsc()]], format="csc"), spmatrix) + # shape is 2x2 so no _stack_along_minor_axis + assert isinstance(bmat([[Fa.tocsc(), Fm.tocsc()]], format="csr"), sparray) + assert isinstance(bmat([[Fm.tocsc(), Fm.tocsc()]], format="csr"), spmatrix) + + # type returned when mixed input + assert isinstance(bmat([[Gl, Ga]], format="csr"), sparray) + assert isinstance(bmat([[Gm.tocsc(), Ga]], format="csr"), sparray) + assert isinstance(bmat([[Gm.tocsc(), Gm]], format="csr"), spmatrix) + assert isinstance(bmat([[Gm, Gm]], format="csc"), spmatrix) + + @pytest.mark.slow + @pytest.mark.thread_unsafe + @pytest.mark.xfail_on_32bit("Can't create large array for test") + def test_concatenate_int32_overflow(self): + """ test for indptr overflow when concatenating matrices """ + check_free_memory(30000) + + n = 33000 + A = csr_array(np.ones((n, n), dtype=bool)) + B = A.copy() + C = construct._compressed_sparse_stack((A, B), axis=0, + return_spmatrix=False) + + assert_(np.all(np.equal(np.diff(C.indptr), n))) + assert_equal(C.indices.dtype, np.int64) + assert_equal(C.indptr.dtype, np.int64) + + def test_block_diag_basic(self): + """ basic test for block_diag """ + A = coo_array([[1,2],[3,4]]) + B = coo_array([[5],[6]]) + C = coo_array([[7]]) + + expected = array([[1, 2, 0, 0], + [3, 4, 0, 0], + [0, 0, 5, 0], + [0, 0, 6, 0], + [0, 0, 0, 7]]) + + ABC = construct.block_diag((A, B, C)) + assert_equal(ABC.toarray(), expected) + assert ABC.coords[0].dtype == np.int32 + + def test_block_diag_idx_dtype(self): + X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]]) + X.coords = tuple(co.astype(np.int64) for co in X.coords) + assert construct.block_diag([X, X]).coords[0].dtype == np.int64 + + def test_block_diag_scalar_1d_args(self): + """ block_diag with scalar and 1d arguments """ + # one 1d matrix and a scalar + assert_array_equal(construct.block_diag([[2,3], 4]).toarray(), + [[2, 3, 0], [0, 0, 4]]) + # 1d sparse arrays + A = coo_array([1,0,3]) + B = coo_array([0,4]) + assert_array_equal(construct.block_diag([A, B]).toarray(), + [[1, 0, 3, 0, 0], [0, 0, 0, 0, 4]]) + + def test_block_diag_1(self): + """ block_diag with one matrix """ + assert_equal(construct.block_diag([[1, 0]]).toarray(), + array([[1, 0]])) + assert_equal(construct.block_diag([[[1, 0]]]).toarray(), + array([[1, 0]])) + assert_equal(construct.block_diag([[[1], [0]]]).toarray(), + array([[1], [0]])) + # just on scalar + assert_equal(construct.block_diag([1]).toarray(), + array([[1]])) + + def test_block_diag_sparse_arrays(self): + """ block_diag with sparse arrays """ + + A = coo_array([[1, 2, 3]], shape=(1, 3)) + B = coo_array([[4, 5]], shape=(1, 2)) + assert_equal(construct.block_diag([A, B]).toarray(), + array([[1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])) + + A = coo_array([[1], [2], [3]], shape=(3, 1)) + B = coo_array([[4], [5]], shape=(2, 1)) + assert_equal(construct.block_diag([A, B]).toarray(), + array([[1, 0], [2, 0], [3, 0], [0, 4], [0, 5]])) + + def test_block_diag_return_type(self): + A, B = coo_array([[1, 2, 3]]), coo_matrix([[2, 3, 4]]) + assert isinstance(construct.block_diag([A, A]), sparray) + assert isinstance(construct.block_diag([A, B]), sparray) + assert isinstance(construct.block_diag([B, A]), sparray) + assert isinstance(construct.block_diag([B, B]), spmatrix) + + def test_random_sampling(self): + # Simple sanity checks for sparse random sampling. + for f in sprand, _sprandn: + for t in [np.float32, np.float64, np.longdouble, + np.int32, np.int64, np.complex64, np.complex128]: + x = f(5, 10, density=0.1, dtype=t) + assert_equal(x.dtype, t) + assert_equal(x.shape, (5, 10)) + assert_equal(x.nnz, 5) + + x1 = f(5, 10, density=0.1, rng=4321) + assert_equal(x1.dtype, np.float64) + + x2 = f(5, 10, density=0.1, rng=np.random.default_rng(4321)) + + assert_array_equal(x1.data, x2.data) + assert_array_equal(x1.row, x2.row) + assert_array_equal(x1.col, x2.col) + + for density in [0.0, 0.1, 0.5, 1.0]: + x = f(5, 10, density=density) + assert_equal(x.nnz, int(density * np.prod(x.shape))) + + for fmt in ['coo', 'csc', 'csr', 'lil']: + x = f(5, 10, format=fmt) + assert_equal(x.format, fmt) + + assert_raises(ValueError, lambda: f(5, 10, 1.1)) + assert_raises(ValueError, lambda: f(5, 10, -0.1)) + + @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)]) + def test_rand(self, rng): + # Simple distributional checks for sparse.rand. + x = sprand(10, 20, density=0.5, dtype=np.float64, rng=rng) + assert_(np.all(np.less_equal(0, x.data))) + assert_(np.all(np.less_equal(x.data, 1))) + + @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)]) + def test_randn(self, rng): + # Simple distributional checks for sparse.randn. + # Statistically, some of these should be negative + # and some should be greater than 1. + x = _sprandn(10, 20, density=0.5, dtype=np.float64, rng=rng) + assert_(np.any(np.less(x.data, 0))) + assert_(np.any(np.less(1, x.data))) + x = _sprandn_array(10, 20, density=0.5, dtype=np.float64, rng=rng) + assert_(np.any(np.less(x.data, 0))) + assert_(np.any(np.less(1, x.data))) + + def test_random_accept_str_dtype(self): + # anything that np.dtype can convert to a dtype should be accepted + # for the dtype + construct.random(10, 10, dtype='d') + construct.random_array((10, 10), dtype='d') + construct.random_array((10, 10, 10), dtype='d') + construct.random_array((10, 10, 10, 10, 10), dtype='d') + + def test_random_array_maintains_array_shape(self): + # preserve use of old random_state during SPEC 7 transition + arr = construct.random_array((0, 4), density=0.3, dtype=int, random_state=0) + assert arr.shape == (0, 4) + + arr = construct.random_array((10, 10, 10), density=0.3, dtype=int, rng=0) + assert arr.shape == (10, 10, 10) + + arr = construct.random_array((10, 10, 10, 10, 10), density=0.3, dtype=int, + rng=0) + assert arr.shape == (10, 10, 10, 10, 10) + + def test_random_array_idx_dtype(self): + A = construct.random_array((10, 10)) + assert A.coords[0].dtype == np.int32 + + def test_random_sparse_matrix_returns_correct_number_of_non_zero_elements(self): + # A 10 x 10 matrix, with density of 12.65%, should have 13 nonzero elements. + # 10 x 10 x 0.1265 = 12.65, which should be rounded up to 13, not 12. + sparse_matrix = construct.random(10, 10, density=0.1265) + assert_equal(sparse_matrix.count_nonzero(),13) + # check random_array + sparse_array = construct.random_array((10, 10), density=0.1265) + assert_equal(sparse_array.count_nonzero(),13) + assert isinstance(sparse_array, sparray) + # check big size + shape = (2**33, 2**33) + sparse_array = construct.random_array(shape, density=2.7105e-17) + assert_equal(sparse_array.count_nonzero(),2000) + + # for n-D + # check random_array + sparse_array = construct.random_array((10, 10, 10, 10), density=0.12658) + assert_equal(sparse_array.count_nonzero(),1266) + assert isinstance(sparse_array, sparray) + # check big size + shape = (2**33, 2**33, 2**33) + sparse_array = construct.random_array(shape, density=2.7105e-28) + assert_equal(sparse_array.count_nonzero(),172) + + +def test_diags_array(): + """Tests of diags_array that do not rely on diags wrapper.""" + diag = np.arange(1, 5) + + assert_array_equal(construct.diags_array(diag).toarray(), np.diag(diag)) + + assert_array_equal( + construct.diags_array(diag, offsets=2).toarray(), np.diag(diag, k=2) + ) + + assert_array_equal( + construct.diags_array(diag, offsets=2, shape=(4, 4)).toarray(), + np.diag(diag, k=2)[:4, :4] + ) + + # Offset outside bounds when shape specified + with pytest.raises(ValueError, match=".*out of bounds"): + construct.diags(np.arange(1, 5), 5, shape=(4, 4)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py new file mode 100644 index 0000000000000000000000000000000000000000..e9281748e6fc9ccdcf8aa44d154ada5856bd46a9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py @@ -0,0 +1,851 @@ +import numpy as np +from numpy.testing import assert_equal +import pytest +from scipy.linalg import block_diag +from scipy.sparse import coo_array, random_array +from .._coo import _block_diag, _extract_block_diag + + +def test_shape_constructor(): + empty1d = coo_array((3,)) + assert empty1d.shape == (3,) + assert_equal(empty1d.toarray(), np.zeros((3,))) + + empty2d = coo_array((3, 2)) + assert empty2d.shape == (3, 2) + assert_equal(empty2d.toarray(), np.zeros((3, 2))) + + empty_nd = coo_array((2,3,4,6,7)) + assert empty_nd.shape == (2,3,4,6,7) + assert_equal(empty_nd.toarray(), np.zeros((2,3,4,6,7))) + + +def test_dense_constructor(): + # 1d + res1d = coo_array([1, 2, 3]) + assert res1d.shape == (3,) + assert_equal(res1d.toarray(), np.array([1, 2, 3])) + + # 2d + res2d = coo_array([[1, 2, 3], [4, 5, 6]]) + assert res2d.shape == (2, 3) + assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]])) + + # 4d + arr4d = np.array([[[[3, 7], [1, 0]], [[6, 5], [9, 2]]], + [[[4, 3], [2, 8]], [[7, 5], [1, 6]]], + [[[0, 9], [4, 3]], [[2, 1], [7, 8]]]]) + res4d = coo_array(arr4d) + assert res4d.shape == (3, 2, 2, 2) + assert_equal(res4d.toarray(), arr4d) + + # 9d + np.random.seed(12) + arr9d = np.random.randn(2,3,4,7,6,5,3,2,4) + res9d = coo_array(arr9d) + assert res9d.shape == (2,3,4,7,6,5,3,2,4) + assert_equal(res9d.toarray(), arr9d) + + # storing nan as element of sparse array + nan_3d = coo_array([[[1, np.nan]], [[3, 4]], [[5, 6]]]) + assert nan_3d.shape == (3, 1, 2) + assert_equal(nan_3d.toarray(), np.array([[[1, np.nan]], [[3, 4]], [[5, 6]]])) + + +def test_dense_constructor_with_shape(): + res1d = coo_array([1, 2, 3], shape=(3,)) + assert res1d.shape == (3,) + assert_equal(res1d.toarray(), np.array([1, 2, 3])) + + res2d = coo_array([[1, 2, 3], [4, 5, 6]], shape=(2, 3)) + assert res2d.shape == (2, 3) + assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]])) + + res3d = coo_array([[[3]], [[4]]], shape=(2, 1, 1)) + assert res3d.shape == (2, 1, 1) + assert_equal(res3d.toarray(), np.array([[[3]], [[4]]])) + + np.random.seed(12) + arr7d = np.random.randn(2,4,1,6,5,3,2) + res7d = coo_array((arr7d), shape=(2,4,1,6,5,3,2)) + assert res7d.shape == (2,4,1,6,5,3,2) + assert_equal(res7d.toarray(), arr7d) + + +def test_dense_constructor_with_inconsistent_shape(): + with pytest.raises(ValueError, match='inconsistent shapes'): + coo_array([1, 2, 3], shape=(4,)) + + with pytest.raises(ValueError, match='inconsistent shapes'): + coo_array([1, 2, 3], shape=(3, 1)) + + with pytest.raises(ValueError, match='inconsistent shapes'): + coo_array([[1, 2, 3]], shape=(3,)) + + with pytest.raises(ValueError, match='inconsistent shapes'): + coo_array([[[3]], [[4]]], shape=(1, 1, 1)) + + with pytest.raises(ValueError, + match='axis 0 index 2 exceeds matrix dimension 2'): + coo_array(([1], ([2],)), shape=(2,)) + + with pytest.raises(ValueError, + match='axis 1 index 3 exceeds matrix dimension 3'): + coo_array(([1,3], ([0, 1], [0, 3], [1, 1])), shape=(2, 3, 2)) + + with pytest.raises(ValueError, match='negative axis 0 index: -1'): + coo_array(([1], ([-1],))) + + with pytest.raises(ValueError, match='negative axis 2 index: -1'): + coo_array(([1], ([0], [2], [-1]))) + + +def test_1d_sparse_constructor(): + empty1d = coo_array((3,)) + res = coo_array(empty1d) + assert res.shape == (3,) + assert_equal(res.toarray(), np.zeros((3,))) + + +def test_1d_tuple_constructor(): + res = coo_array(([9,8], ([1,2],))) + assert res.shape == (3,) + assert_equal(res.toarray(), np.array([0, 9, 8])) + + +def test_1d_tuple_constructor_with_shape(): + res = coo_array(([9,8], ([1,2],)), shape=(4,)) + assert res.shape == (4,) + assert_equal(res.toarray(), np.array([0, 9, 8, 0])) + +def test_non_subscriptability(): + coo_2d = coo_array((2, 2)) + + with pytest.raises(TypeError, + match="'coo_array' object does not support item assignment"): + coo_2d[0, 0] = 1 + + with pytest.raises(TypeError, + match="'coo_array' object is not subscriptable"): + coo_2d[0, :] + +def test_reshape_overflow(): + # see gh-22353 : new idx_dtype can need to be int64 instead of int32 + M, N = (1045507, 523266) + coords = (np.array([M - 1], dtype='int32'), np.array([N - 1], dtype='int32')) + A = coo_array(([3.3], coords), shape=(M, N)) + + # need new idx_dtype to not overflow + B = A.reshape((M * N, 1)) + assert B.coords[0].dtype == np.dtype('int64') + assert B.coords[0][0] == (M * N) - 1 + + # need idx_dtype to stay int32 if before and after can be int32 + C = A.reshape(N, M) + assert C.coords[0].dtype == np.dtype('int32') + assert C.coords[0][0] == N - 1 + +def test_reshape(): + arr1d = coo_array([1, 0, 3]) + assert arr1d.shape == (3,) + + col_vec = arr1d.reshape((3, 1)) + assert col_vec.shape == (3, 1) + assert_equal(col_vec.toarray(), np.array([[1], [0], [3]])) + + row_vec = arr1d.reshape((1, 3)) + assert row_vec.shape == (1, 3) + assert_equal(row_vec.toarray(), np.array([[1, 0, 3]])) + + # attempting invalid reshape + with pytest.raises(ValueError, match="cannot reshape array"): + arr1d.reshape((3,3)) + + # attempting reshape with a size 0 dimension + with pytest.raises(ValueError, match="cannot reshape array"): + arr1d.reshape((3,0)) + + arr2d = coo_array([[1, 2, 0], [0, 0, 3]]) + assert arr2d.shape == (2, 3) + + flat = arr2d.reshape((6,)) + assert flat.shape == (6,) + assert_equal(flat.toarray(), np.array([1, 2, 0, 0, 0, 3])) + + # 2d to 3d + to_3d_arr = arr2d.reshape((2, 3, 1)) + assert to_3d_arr.shape == (2, 3, 1) + assert_equal(to_3d_arr.toarray(), np.array([[[1], [2], [0]], [[0], [0], [3]]])) + + # attempting invalid reshape + with pytest.raises(ValueError, match="cannot reshape array"): + arr2d.reshape((1,3)) + + +def test_nnz(): + arr1d = coo_array([1, 0, 3]) + assert arr1d.shape == (3,) + assert arr1d.nnz == 2 + + arr2d = coo_array([[1, 2, 0], [0, 0, 3]]) + assert arr2d.shape == (2, 3) + assert arr2d.nnz == 3 + + +def test_transpose(): + arr1d = coo_array([1, 0, 3]).T + assert arr1d.shape == (3,) + assert_equal(arr1d.toarray(), np.array([1, 0, 3])) + + arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).T + assert arr2d.shape == (3, 2) + assert_equal(arr2d.toarray(), np.array([[1, 0], [2, 0], [0, 3]])) + + +def test_transpose_with_axis(): + arr1d = coo_array([1, 0, 3]).transpose(axes=(0,)) + assert arr1d.shape == (3,) + assert_equal(arr1d.toarray(), np.array([1, 0, 3])) + + arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(0, 1)) + assert arr2d.shape == (2, 3) + assert_equal(arr2d.toarray(), np.array([[1, 2, 0], [0, 0, 3]])) + + with pytest.raises(ValueError, match="axes don't match matrix dimensions"): + coo_array([1, 0, 3]).transpose(axes=(0, 1)) + + with pytest.raises(ValueError, match="repeated axis in transpose"): + coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(1, 1)) + + +def test_1d_row_and_col(): + res = coo_array([1, -2, -3]) + assert_equal(res.col, np.array([0, 1, 2])) + assert_equal(res.row, np.zeros_like(res.col)) + assert res.row.dtype == res.col.dtype + assert res.row.flags.writeable is False + + res.col = [1, 2, 3] + assert len(res.coords) == 1 + assert_equal(res.col, np.array([1, 2, 3])) + assert res.row.dtype == res.col.dtype + + with pytest.raises(ValueError, match="cannot set row attribute"): + res.row = [1, 2, 3] + + +def test_1d_toformats(): + res = coo_array([1, -2, -3]) + for f in [res.tobsr, res.tocsc, res.todia, res.tolil]: + with pytest.raises(ValueError, match='Cannot convert'): + f() + for f in [res.tocoo, res.tocsr, res.todok]: + assert_equal(f().toarray(), res.toarray()) + + +@pytest.mark.parametrize('arg', [1, 2, 4, 5, 8]) +def test_1d_resize(arg: int): + den = np.array([1, -2, -3]) + res = coo_array(den) + den.resize(arg, refcheck=False) + res.resize(arg) + assert res.shape == den.shape + assert_equal(res.toarray(), den) + + +@pytest.mark.parametrize('arg', zip([1, 2, 3, 4], [1, 2, 3, 4])) +def test_1d_to_2d_resize(arg: tuple[int, int]): + den = np.array([1, 0, 3]) + res = coo_array(den) + + den.resize(arg, refcheck=False) + res.resize(arg) + assert res.shape == den.shape + assert_equal(res.toarray(), den) + + +@pytest.mark.parametrize('arg', [1, 4, 6, 8]) +def test_2d_to_1d_resize(arg: int): + den = np.array([[1, 0, 3], [4, 0, 0]]) + res = coo_array(den) + den.resize(arg, refcheck=False) + res.resize(arg) + assert res.shape == den.shape + assert_equal(res.toarray(), den) + + +def test_sum_duplicates(): + # 1d case + arr1d = coo_array(([2, 2, 2], ([1, 0, 1],))) + assert arr1d.nnz == 3 + assert_equal(arr1d.toarray(), np.array([2, 4])) + arr1d.sum_duplicates() + assert arr1d.nnz == 2 + assert_equal(arr1d.toarray(), np.array([2, 4])) + + # 4d case + arr4d = coo_array(([2, 3, 7], ([1, 0, 1], [0, 2, 0], [1, 2, 1], [1, 0, 1]))) + assert arr4d.nnz == 3 + expected = np.array( # noqa: E501 + [[[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [3, 0]]], + [[[0, 0], [0, 9], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]] + ) + assert_equal(arr4d.toarray(), expected) + arr4d.sum_duplicates() + assert arr4d.nnz == 2 + assert_equal(arr4d.toarray(), expected) + + # when there are no duplicates + arr_nodups = coo_array(([1, 2, 3, 4], ([0, 1, 2, 3],))) + assert arr_nodups.nnz == 4 + arr_nodups.sum_duplicates() + assert arr_nodups.nnz == 4 + + +def test_eliminate_zeros(): + arr1d = coo_array(([0, 0, 1], ([1, 0, 1],))) + assert arr1d.nnz == 3 + assert arr1d.count_nonzero() == 1 + assert_equal(arr1d.toarray(), np.array([0, 1])) + arr1d.eliminate_zeros() + assert arr1d.nnz == 1 + assert arr1d.count_nonzero() == 1 + assert_equal(arr1d.toarray(), np.array([0, 1])) + assert_equal(arr1d.col, np.array([1])) + assert_equal(arr1d.row, np.array([0])) + + +def test_1d_add_dense(): + den_a = np.array([0, -2, -3, 0]) + den_b = np.array([0, 1, 2, 3]) + exp = den_a + den_b + res = coo_array(den_a) + den_b + assert type(res) is type(exp) + assert_equal(res, exp) + + +def test_1d_add_sparse(): + den_a = np.array([0, -2, -3, 0]) + den_b = np.array([0, 1, 2, 3]) + dense_sum = den_a + den_b + # this routes through CSR format + sparse_sum = coo_array(den_a) + coo_array(den_b) + assert_equal(dense_sum, sparse_sum.toarray()) + + +def test_1d_matmul_vector(): + den_a = np.array([0, -2, -3, 0]) + den_b = np.array([0, 1, 2, 3]) + exp = den_a @ den_b + res = coo_array(den_a) @ den_b + assert np.ndim(res) == 0 + assert_equal(res, exp) + + +def test_1d_matmul_multivector(): + den = np.array([0, -2, -3, 0]) + other = np.array([[0, 1, 2, 3], [3, 2, 1, 0]]).T + exp = den @ other + res = coo_array(den) @ other + assert type(res) is type(exp) + assert_equal(res, exp) + + +def test_2d_matmul_multivector(): + # sparse-sparse matmul + den = np.array([[0, 1, 2, 3], [3, 2, 1, 0]]) + arr2d = coo_array(den) + exp = den @ den.T + res = arr2d @ arr2d.T + assert_equal(res.toarray(), exp) + + # sparse-dense matmul for self.ndim = 2 + den = np.array([[0, 4, 3, 0, 5], [1, 0, 7, 3, 4]]) + arr2d = coo_array(den) + exp = den @ den.T + res = arr2d @ den.T + assert_equal(res, exp) + + # sparse-dense matmul for self.ndim = 1 + den_a = np.array([[0, 4, 3, 0, 5], [1, 0, 7, 3, 4]]) + den_b = np.array([0, 1, 6, 0, 4]) + arr1d = coo_array(den_b) + exp = den_b @ den_a.T + res = arr1d @ den_a.T + assert_equal(res, exp) + + # sparse-dense matmul for self.ndim = 1 and other.ndim = 2 + den_a = np.array([1, 0, 2]) + den_b = np.array([[3], [4], [0]]) + exp = den_a @ den_b + res = coo_array(den_a) @ den_b + assert_equal(res, exp) + res = coo_array(den_a) @ list(den_b) + assert_equal(res, exp) + + +def test_1d_diagonal(): + den = np.array([0, -2, -3, 0]) + with pytest.raises(ValueError, match='diagonal requires two dimensions'): + coo_array(den).diagonal() + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_todense(shape): + np.random.seed(12) + arr = np.random.randint(low=0, high=5, size=shape) + assert_equal(coo_array(arr).todense(), arr) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_sparse_constructor(shape): + empty_arr = coo_array(shape) + res = coo_array(empty_arr) + assert res.shape == (shape) + assert_equal(res.toarray(), np.zeros(shape)) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_tuple_constructor(shape): + np.random.seed(12) + arr = np.random.randn(*shape) + res = coo_array(arr) + assert res.shape == shape + assert_equal(res.toarray(), arr) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_tuple_constructor_with_shape(shape): + np.random.seed(12) + arr = np.random.randn(*shape) + res = coo_array(arr, shape=shape) + assert res.shape == shape + assert_equal(res.toarray(), arr) + + +def test_tuple_constructor_for_dim_size_zero(): + # arrays with a dimension of size 0 + with pytest.raises(ValueError, match='exceeds matrix dimension'): + coo_array(([9, 8], ([1, 2], [1, 0], [2, 1])), shape=(3,4,0)) + + empty_arr = coo_array(([], ([], [], [], [])), shape=(4,0,2,3)) + assert_equal(empty_arr.toarray(), np.empty((4,0,2,3))) + + +@pytest.mark.parametrize(('shape', 'new_shape'), [((4,9,6,5), (3,6,15,4)), + ((4,9,6,5), (36,30)), + ((4,9,6,5), (1080,)), + ((4,9,6,5), (2,3,2,2,3,5,3)),]) +def test_nd_reshape(shape, new_shape): + # reshaping a 4d sparse array + rng = np.random.default_rng(23409823) + + arr4d = random_array(shape, density=0.6, rng=rng, dtype=int) + assert arr4d.shape == shape + den4d = arr4d.toarray() + + exp_arr = den4d.reshape(new_shape) + res_arr = arr4d.reshape(new_shape) + assert res_arr.shape == new_shape + assert_equal(res_arr.toarray(), exp_arr) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_nnz(shape): + rng = np.random.default_rng(23409823) + + arr = random_array(shape, density=0.6, rng=rng, dtype=int) + assert arr.nnz == np.count_nonzero(arr.toarray()) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_transpose(shape): + rng = np.random.default_rng(23409823) + + arr = random_array(shape, density=0.6, rng=rng, dtype=int) + exp_arr = arr.toarray().T + trans_arr = arr.transpose() + assert trans_arr.shape == shape[::-1] + assert_equal(exp_arr, trans_arr.toarray()) + + +@pytest.mark.parametrize(('shape', 'axis_perm'), [((3,), (0,)), + ((2,3), (0,1)), + ((2,4,3,6,5,3), (1,2,0,5,3,4)),]) +def test_nd_transpose_with_axis(shape, axis_perm): + rng = np.random.default_rng(23409823) + + arr = random_array(shape, density=0.6, rng=rng, dtype=int) + trans_arr = arr.transpose(axes=axis_perm) + assert_equal(trans_arr.toarray(), np.transpose(arr.toarray(), axes=axis_perm)) + + +def test_transpose_with_inconsistent_axis(): + with pytest.raises(ValueError, match="axes don't match matrix dimensions"): + coo_array([1, 0, 3]).transpose(axes=(0, 1)) + + with pytest.raises(ValueError, match="repeated axis in transpose"): + coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(1, 1)) + + +def test_nd_eliminate_zeros(): + # for 3d sparse arrays + arr3d = coo_array(([1, 0, 0, 4], ([0, 1, 1, 2], [0, 1, 0, 1], [1, 1, 2, 0]))) + assert arr3d.nnz == 4 + assert arr3d.count_nonzero() == 2 + assert_equal(arr3d.toarray(), np.array([[[0, 1, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [4, 0, 0]]])) + arr3d.eliminate_zeros() + assert arr3d.nnz == 2 + assert arr3d.count_nonzero() == 2 + assert_equal(arr3d.toarray(), np.array([[[0, 1, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [4, 0, 0]]])) + + # for a 5d sparse array when all elements of data array are 0 + coords = ([0, 1, 1, 2], [0, 1, 0, 1], [1, 1, 2, 0], [0, 0, 2, 3], [1, 0, 0, 2]) + arr5d = coo_array(([0, 0, 0, 0], coords)) + assert arr5d.nnz == 4 + assert arr5d.count_nonzero() == 0 + arr5d.eliminate_zeros() + assert arr5d.nnz == 0 + assert arr5d.count_nonzero() == 0 + assert_equal(arr5d.col, np.array([])) + assert_equal(arr5d.row, np.array([])) + assert_equal(arr5d.coords, ([], [], [], [], [])) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_add_dense(shape): + rng = np.random.default_rng(23409823) + sp_x = random_array(shape, density=0.6, rng=rng, dtype=int) + sp_y = random_array(shape, density=0.6, rng=rng, dtype=int) + den_x, den_y = sp_x.toarray(), sp_y.toarray() + exp = den_x + den_y + res = sp_x + den_y + assert type(res) is type(exp) + assert_equal(res, exp) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_add_sparse(shape): + rng = np.random.default_rng(23409823) + sp_x = random_array((shape), density=0.6, rng=rng, dtype=int) + sp_y = random_array((shape), density=0.6, rng=rng, dtype=int) + den_x, den_y = sp_x.toarray(), sp_y.toarray() + + dense_sum = den_x + den_y + sparse_sum = sp_x + sp_y + assert_equal(dense_sum, sparse_sum.toarray()) + + +def test_add_sparse_with_inf(): + # addition of sparse arrays with an inf element + den_a = np.array([[[0], [np.inf]], [[-3], [0]]]) + den_b = np.array([[[0], [1]], [[2], [3]]]) + dense_sum = den_a + den_b + sparse_sum = coo_array(den_a) + coo_array(den_b) + assert_equal(dense_sum, sparse_sum.toarray()) + + +@pytest.mark.parametrize(('a_shape', 'b_shape'), [((7,), (12,)), + ((6,4), (6,5)), + ((5,9,3,2), (9,5,2,3)),]) +def test_nd_add_sparse_with_inconsistent_shapes(a_shape, b_shape): + rng = np.random.default_rng(23409823) + + arr_a = random_array((a_shape), density=0.6, rng=rng, dtype=int) + arr_b = random_array((b_shape), density=0.6, rng=rng, dtype=int) + with pytest.raises(ValueError, + match="(Incompatible|inconsistent) shapes|cannot be broadcast"): + arr_a + arr_b + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_sub_dense(shape): + rng = np.random.default_rng(23409823) + sp_x = random_array(shape, density=0.6, rng=rng, dtype=int) + sp_y = random_array(shape, density=0.6, rng=rng, dtype=int) + den_x, den_y = sp_x.toarray(), sp_y.toarray() + exp = den_x - den_y + res = sp_x - den_y + assert type(res) is type(exp) + assert_equal(res, exp) + + +@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2), + (1,0,3), (7,9,3,2,4,5)]) +def test_nd_sub_sparse(shape): + rng = np.random.default_rng(23409823) + + sp_x = random_array(shape, density=0.6, rng=rng, dtype=int) + sp_y = random_array(shape, density=0.6, rng=rng, dtype=int) + den_x, den_y = sp_x.toarray(), sp_y.toarray() + + dense_sum = den_x - den_y + sparse_sum = sp_x - sp_y + assert_equal(dense_sum, sparse_sum.toarray()) + + +def test_nd_sub_sparse_with_nan(): + # subtraction of sparse arrays with a nan element + den_a = np.array([[[0], [np.nan]], [[-3], [0]]]) + den_b = np.array([[[0], [1]], [[2], [3]]]) + dense_sum = den_a - den_b + sparse_sum = coo_array(den_a) - coo_array(den_b) + assert_equal(dense_sum, sparse_sum.toarray()) + + +@pytest.mark.parametrize(('a_shape', 'b_shape'), [((7,), (12,)), + ((6,4), (6,5)), + ((5,9,3,2), (9,5,2,3)),]) +def test_nd_sub_sparse_with_inconsistent_shapes(a_shape, b_shape): + rng = np.random.default_rng(23409823) + + arr_a = random_array((a_shape), density=0.6, rng=rng, dtype=int) + arr_b = random_array((b_shape), density=0.6, rng=rng, dtype=int) + with pytest.raises(ValueError, match="inconsistent shapes"): + arr_a - arr_b + + +mat_vec_shapes = [ + ((2, 3, 4, 5), (5,)), + ((0, 0), (0,)), + ((2, 3, 4, 7, 8), (8,)), + ((4, 4, 2, 0), (0,)), + ((6, 5, 3, 2, 4), (4, 1)), + ((2,5), (5,)), + ((2, 5), (5, 1)), + ((3,), (3, 1)), + ((4,), (4,)) +] +@pytest.mark.parametrize(('mat_shape', 'vec_shape'), mat_vec_shapes) +def test_nd_matmul_vector(mat_shape, vec_shape): + rng = np.random.default_rng(23409823) + + sp_x = random_array(mat_shape, density=0.6, rng=rng, dtype=int) + sp_y = random_array(vec_shape, density=0.6, rng=rng, dtype=int) + den_x, den_y = sp_x.toarray(), sp_y.toarray() + exp = den_x @ den_y + res = sp_x @ den_y + assert_equal(res,exp) + res = sp_x @ list(den_y) + assert_equal(res,exp) + + +mat_mat_shapes = [ + ((2, 3, 4, 5), (2, 3, 5, 7)), + ((0, 0), (0,)), + ((4, 4, 2, 0), (0,)), + ((7, 8, 3), (3,)), + ((7, 8, 3), (3, 1)), + ((6, 5, 3, 2, 4), (4, 3)), + ((1, 3, 2, 4), (6, 5, 1, 4, 3)), + ((6, 1, 1, 2, 4), (1, 3, 4, 3)), + ((4,), (2, 4, 3)), + ((3,), (5, 6, 7, 3, 2)), + ((4,), (4, 3)), + ((2, 5), (5, 1)), +] +@pytest.mark.parametrize(('mat_shape1', 'mat_shape2'), mat_mat_shapes) +def test_nd_matmul(mat_shape1, mat_shape2): + rng = np.random.default_rng(23409823) + + sp_x = random_array(mat_shape1, density=0.6, random_state=rng, dtype=int) + sp_y = random_array(mat_shape2, density=0.6, random_state=rng, dtype=int) + den_x, den_y = sp_x.toarray(), sp_y.toarray() + exp = den_x @ den_y + # sparse-sparse + res = sp_x @ sp_y + assert_equal(res.toarray(), exp) + # sparse-dense + res = sp_x @ den_y + assert_equal(res, exp) + res = sp_x @ list(den_y) + assert_equal(res, exp) + + # dense-sparse + res = den_x @ sp_y + assert_equal(res, exp) + + +def test_nd_matmul_sparse_with_inconsistent_arrays(): + rng = np.random.default_rng(23409823) + + sp_x = random_array((4,5,7,6,3), density=0.6, random_state=rng, dtype=int) + sp_y = random_array((1,5,3,2,5), density=0.6, random_state=rng, dtype=int) + with pytest.raises(ValueError, match="matmul: dimension mismatch with signature"): + sp_x @ sp_y + with pytest.raises(ValueError, match="matmul: dimension mismatch with signature"): + sp_x @ (sp_y.toarray()) + + sp_z = random_array((1,5,3,2), density=0.6, random_state=rng, dtype=int) + with pytest.raises(ValueError, match="Batch dimensions are not broadcastable"): + sp_x @ sp_z + with pytest.raises(ValueError, match="Batch dimensions are not broadcastable"): + sp_x @ (sp_z.toarray()) + + +def test_dot_1d_1d(): # 1-D inner product + a = coo_array([1,2,3]) + b = coo_array([4,5,6]) + exp = np.dot(a.toarray(), b.toarray()) + res = a.dot(b) + assert_equal(res, exp) + res = a.dot(b.toarray()) + assert_equal(res, exp) + + +def test_dot_sparse_scalar(): + a = coo_array([[1, 2], [3, 4], [5, 6]]) + b = 3 + res = a.dot(b) + exp = np.dot(a.toarray(), b) + assert_equal(res.toarray(), exp) + + +def test_dot_with_inconsistent_shapes(): + arr_a = coo_array([[[1, 2]], [[3, 4]]]) + arr_b = coo_array([4, 5, 6]) + with pytest.raises(ValueError, match="not aligned for n-D dot"): + arr_a.dot(arr_b) + + +def test_matmul_dot_not_implemented(): + arr_a = coo_array([[1, 2], [3, 4]]) + with pytest.raises(TypeError, match="argument not supported type"): + arr_a.dot(None) + with pytest.raises(TypeError, match="arg not supported type"): + arr_a.tensordot(None) + with pytest.raises(TypeError, match="unsupported operand type"): + arr_a @ None + with pytest.raises(TypeError, match="unsupported operand type"): + None @ arr_a + + +dot_shapes = [ + ((3,3), (3,3)), ((4,6), (6,7)), ((1,4), (4,1)), # matrix multiplication 2-D + ((3,2,4,7), (7,)), ((5,), (6,3,5,2)), # dot of n-D and 1-D arrays + ((3,2,4,7), (7,1)), ((1,5,), (6,3,5,2)), + ((4,6), (3,2,6,4)), ((2,8,7), (4,5,7,7,2)), # dot of n-D and m-D arrays + ((4,5,7,6), (3,2,6,4)), +] +@pytest.mark.parametrize(('a_shape', 'b_shape'), dot_shapes) +def test_dot_nd(a_shape, b_shape): + rng = np.random.default_rng(23409823) + + arr_a = random_array(a_shape, density=0.6, random_state=rng, dtype=int) + arr_b = random_array(b_shape, density=0.6, random_state=rng, dtype=int) + + exp = np.dot(arr_a.toarray(), arr_b.toarray()) + # sparse-dense + res = arr_a.dot(arr_b.toarray()) + assert_equal(res, exp) + res = arr_a.dot(list(arr_b.toarray())) + assert_equal(res, exp) + # sparse-sparse + res = arr_a.dot(arr_b) + assert_equal(res.toarray(), exp) + + +tensordot_shapes_and_axes = [ + ((4,6), (6,7), ([1], [0])), + ((3,2,4,7), (7,), ([3], [0])), + ((5,), (6,3,5,2), ([0], [2])), + ((4,5,7,6), (3,2,6,4), ([0, 3], [3, 2])), + ((2,8,7), (4,5,7,8,2), ([0, 1, 2], [4, 3, 2])), + ((4,5,3,2,6), (3,2,6,7,8), 3), + ((4,5,7), (7,3,7), 1), + ((2,3,4), (2,3,4), ([0, 1, 2], [0, 1, 2])), +] +@pytest.mark.parametrize(('a_shape', 'b_shape', 'axes'), tensordot_shapes_and_axes) +def test_tensordot(a_shape, b_shape, axes): + rng = np.random.default_rng(23409823) + + arr_a = random_array(a_shape, density=0.6, random_state=rng, dtype=int) + arr_b = random_array(b_shape, density=0.6, random_state=rng, dtype=int) + + exp = np.tensordot(arr_a.toarray(), arr_b.toarray(), axes=axes) + + # sparse-dense + res = arr_a.tensordot(arr_b.toarray(), axes=axes) + assert_equal(res, exp) + res = arr_a.tensordot(list(arr_b.toarray()), axes=axes) + assert_equal(res, exp) + + # sparse-sparse + res = arr_a.tensordot(arr_b, axes=axes) + if type(res) is coo_array: + assert_equal(res.toarray(), exp) + else: + assert_equal(res, exp) + + +def test_tensordot_with_invalid_args(): + rng = np.random.default_rng(23409823) + + arr_a = random_array((3,4,5), density=0.6, random_state=rng, dtype=int) + arr_b = random_array((3,4,6), density=0.6, random_state=rng, dtype=int) + + axes = ([2], [2]) # sizes of 2nd axes of both shapes do not match + with pytest.raises(ValueError, match="sizes of the corresponding axes must match"): + arr_a.tensordot(arr_b, axes=axes) + + arr_a = random_array((5,4,2,3,7), density=0.6, random_state=rng, dtype=int) + arr_b = random_array((4,6,3,2), density=0.6, random_state=rng, dtype=int) + + axes = ([2,0,1], [1,3]) # lists have different lengths + with pytest.raises(ValueError, match="axes lists/tuples must be of the" + " same length"): + arr_a.tensordot(arr_b, axes=axes) + + +@pytest.mark.parametrize(('actual_shape', 'broadcast_shape'), + [((1,3,5,4), (2,3,5,4)), ((2,1,5,4), (6,2,3,5,4)), + ((1,1,7,8,9), (4,5,6,7,8,9)), ((1,3), (4,5,3)), + ((7,8,1), (7,8,5)), ((3,1), (3,4)), ((1,), (5,)), + ((1,1,1), (4,5,6)), ((1,3,1,5,4), (8,2,3,9,5,4)),]) +def test_broadcast_to(actual_shape, broadcast_shape): + rng = np.random.default_rng(23409823) + + arr = random_array(actual_shape, density=0.6, random_state=rng, dtype=int) + res = arr._broadcast_to(broadcast_shape) + exp = np.broadcast_to(arr.toarray(), broadcast_shape) + assert_equal(res.toarray(), exp) + + +@pytest.mark.parametrize(('shape'), [(4,5,6,7,8), (6,4), + (5,9,3,2), (9,5,2,3,4),]) +def test_block_diag(shape): + rng = np.random.default_rng(23409823) + sp_x = random_array(shape, density=0.6, random_state=rng, dtype=int) + den_x = sp_x.toarray() + + # converting n-d numpy array to an array of slices of 2-D matrices, + # to pass as argument into scipy.linalg.block_diag + num_slices = int(np.prod(den_x.shape[:-2])) + reshaped_array = den_x.reshape((num_slices,) + den_x.shape[-2:]) + matrices = [reshaped_array[i, :, :] for i in range(num_slices)] + exp = block_diag(*matrices) + + res = _block_diag(sp_x) + + assert_equal(res.toarray(), exp) + + +@pytest.mark.parametrize(('shape'), [(4,5,6,7,8), (6,4), + (5,9,3,2), (9,5,2,3,4),]) +def test_extract_block_diag(shape): + rng = np.random.default_rng(23409823) + sp_x = random_array(shape, density=0.6, random_state=rng, dtype=int) + res = _extract_block_diag(_block_diag(sp_x), shape) + + assert_equal(res.toarray(), sp_x.toarray()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py new file mode 100644 index 0000000000000000000000000000000000000000..6313751e41899ae7c5daf01fbdbbacdc1f303fa1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py @@ -0,0 +1,98 @@ +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_ +from scipy.sparse import csr_matrix, csc_matrix, lil_matrix + +import pytest + + +def test_csc_getrow(): + N = 10 + np.random.seed(0) + X = np.random.random((N, N)) + X[X > 0.7] = 0 + Xcsc = csc_matrix(X) + + for i in range(N): + arr_row = X[i:i + 1, :] + csc_row = Xcsc.getrow(i) + + assert_array_almost_equal(arr_row, csc_row.toarray()) + assert_(type(csc_row) is csr_matrix) + + +def test_csc_getcol(): + N = 10 + np.random.seed(0) + X = np.random.random((N, N)) + X[X > 0.7] = 0 + Xcsc = csc_matrix(X) + + for i in range(N): + arr_col = X[:, i:i + 1] + csc_col = Xcsc.getcol(i) + + assert_array_almost_equal(arr_col, csc_col.toarray()) + assert_(type(csc_col) is csc_matrix) + +@pytest.mark.parametrize("matrix_input, axis, expected_shape", + [(csc_matrix([[1, 0], + [0, 0], + [0, 2]]), + 0, (0, 2)), + (csc_matrix([[1, 0], + [0, 0], + [0, 2]]), + 1, (3, 0)), + (csc_matrix([[1, 0], + [0, 0], + [0, 2]]), + 'both', (0, 0)), + (csc_matrix([[0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 2, 3, 0, 1]]), + 0, (0, 6))]) +def test_csc_empty_slices(matrix_input, axis, expected_shape): + # see gh-11127 for related discussion + slice_1 = matrix_input.toarray().shape[0] - 1 + slice_2 = slice_1 + slice_3 = slice_2 - 1 + + if axis == 0: + actual_shape_1 = matrix_input[slice_1:slice_2, :].toarray().shape + actual_shape_2 = matrix_input[slice_1:slice_3, :].toarray().shape + elif axis == 1: + actual_shape_1 = matrix_input[:, slice_1:slice_2].toarray().shape + actual_shape_2 = matrix_input[:, slice_1:slice_3].toarray().shape + elif axis == 'both': + actual_shape_1 = matrix_input[slice_1:slice_2, slice_1:slice_2].toarray().shape + actual_shape_2 = matrix_input[slice_1:slice_3, slice_1:slice_3].toarray().shape + + assert actual_shape_1 == expected_shape + assert actual_shape_1 == actual_shape_2 + + +@pytest.mark.parametrize('ax', (-2, -1, 0, 1, None)) +def test_argmax_overflow(ax): + # See gh-13646: Windows integer overflow for large sparse matrices. + dim = (100000, 100000) + A = lil_matrix(dim) + A[-2, -2] = 42 + A[-3, -3] = 0.1234 + A = csc_matrix(A) + idx = A.argmax(axis=ax) + + if ax is None: + # idx is a single flattened index + # that we need to convert to a 2d index pair; + # can't do this with np.unravel_index because + # the dimensions are too large + ii = idx % dim[0] + jj = idx // dim[0] + else: + # idx is an array of size of A.shape[ax]; + # check the max index to make sure no overflows + # we encountered + assert np.count_nonzero(idx) == A.nnz + ii, jj = np.max(idx), np.argmax(idx) + + assert A[ii, jj] == A[-2, -2] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py new file mode 100644 index 0000000000000000000000000000000000000000..6b011ad4fdce93c0fac36e58381da0bb554ba3be --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py @@ -0,0 +1,214 @@ +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_, assert_array_equal +from scipy.sparse import csr_matrix, csc_matrix, csr_array, csc_array, hstack +from scipy import sparse +import pytest + + +def _check_csr_rowslice(i, sl, X, Xcsr): + np_slice = X[i, sl] + csr_slice = Xcsr[i, sl] + assert_array_almost_equal(np_slice, csr_slice.toarray()[0]) + assert_(type(csr_slice) is csr_matrix) + + +def test_csr_rowslice(): + N = 10 + np.random.seed(0) + X = np.random.random((N, N)) + X[X > 0.7] = 0 + Xcsr = csr_matrix(X) + + slices = [slice(None, None, None), + slice(None, None, -1), + slice(1, -2, 2), + slice(-2, 1, -2)] + + for i in range(N): + for sl in slices: + _check_csr_rowslice(i, sl, X, Xcsr) + + +def test_csr_getrow(): + N = 10 + np.random.seed(0) + X = np.random.random((N, N)) + X[X > 0.7] = 0 + Xcsr = csr_matrix(X) + + for i in range(N): + arr_row = X[i:i + 1, :] + csr_row = Xcsr.getrow(i) + + assert_array_almost_equal(arr_row, csr_row.toarray()) + assert_(type(csr_row) is csr_matrix) + + +def test_csr_getcol(): + N = 10 + np.random.seed(0) + X = np.random.random((N, N)) + X[X > 0.7] = 0 + Xcsr = csr_matrix(X) + + for i in range(N): + arr_col = X[:, i:i + 1] + csr_col = Xcsr.getcol(i) + + assert_array_almost_equal(arr_col, csr_col.toarray()) + assert_(type(csr_col) is csr_matrix) + +@pytest.mark.parametrize("matrix_input, axis, expected_shape", + [(csr_matrix([[1, 0, 0, 0], + [0, 0, 0, 0], + [0, 2, 3, 0]]), + 0, (0, 4)), + (csr_matrix([[1, 0, 0, 0], + [0, 0, 0, 0], + [0, 2, 3, 0]]), + 1, (3, 0)), + (csr_matrix([[1, 0, 0, 0], + [0, 0, 0, 0], + [0, 2, 3, 0]]), + 'both', (0, 0)), + (csr_matrix([[0, 1, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 2, 3, 0]]), + 0, (0, 5))]) +def test_csr_empty_slices(matrix_input, axis, expected_shape): + # see gh-11127 for related discussion + slice_1 = matrix_input.toarray().shape[0] - 1 + slice_2 = slice_1 + slice_3 = slice_2 - 1 + + if axis == 0: + actual_shape_1 = matrix_input[slice_1:slice_2, :].toarray().shape + actual_shape_2 = matrix_input[slice_1:slice_3, :].toarray().shape + elif axis == 1: + actual_shape_1 = matrix_input[:, slice_1:slice_2].toarray().shape + actual_shape_2 = matrix_input[:, slice_1:slice_3].toarray().shape + elif axis == 'both': + actual_shape_1 = matrix_input[slice_1:slice_2, slice_1:slice_2].toarray().shape + actual_shape_2 = matrix_input[slice_1:slice_3, slice_1:slice_3].toarray().shape + + assert actual_shape_1 == expected_shape + assert actual_shape_1 == actual_shape_2 + + +def test_csr_bool_indexing(): + data = csr_matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) + list_indices1 = [False, True, False] + array_indices1 = np.array(list_indices1) + list_indices2 = [[False, True, False], [False, True, False], [False, True, False]] + array_indices2 = np.array(list_indices2) + list_indices3 = ([False, True, False], [False, True, False]) + array_indices3 = (np.array(list_indices3[0]), np.array(list_indices3[1])) + slice_list1 = data[list_indices1].toarray() + slice_array1 = data[array_indices1].toarray() + slice_list2 = data[list_indices2] + slice_array2 = data[array_indices2] + slice_list3 = data[list_indices3] + slice_array3 = data[array_indices3] + assert (slice_list1 == slice_array1).all() + assert (slice_list2 == slice_array2).all() + assert (slice_list3 == slice_array3).all() + + +def test_csr_hstack_int64(): + """ + Tests if hstack properly promotes to indices and indptr arrays to np.int64 + when using np.int32 during concatenation would result in either array + overflowing. + """ + max_int32 = np.iinfo(np.int32).max + + # First case: indices would overflow with int32 + data = [1.0] + row = [0] + + max_indices_1 = max_int32 - 1 + max_indices_2 = 3 + + # Individual indices arrays are representable with int32 + col_1 = [max_indices_1 - 1] + col_2 = [max_indices_2 - 1] + + X_1 = csr_matrix((data, (row, col_1))) + X_2 = csr_matrix((data, (row, col_2))) + + assert max(max_indices_1 - 1, max_indices_2 - 1) < max_int32 + assert X_1.indices.dtype == X_1.indptr.dtype == np.int32 + assert X_2.indices.dtype == X_2.indptr.dtype == np.int32 + + # ... but when concatenating their CSR matrices, the resulting indices + # array can't be represented with int32 and must be promoted to int64. + X_hs = hstack([X_1, X_2], format="csr") + + assert X_hs.indices.max() == max_indices_1 + max_indices_2 - 1 + assert max_indices_1 + max_indices_2 - 1 > max_int32 + assert X_hs.indices.dtype == X_hs.indptr.dtype == np.int64 + + # Even if the matrices are empty, we must account for their size + # contribution so that we may safely set the final elements. + X_1_empty = csr_matrix(X_1.shape) + X_2_empty = csr_matrix(X_2.shape) + X_hs_empty = hstack([X_1_empty, X_2_empty], format="csr") + + assert X_hs_empty.shape == X_hs.shape + assert X_hs_empty.indices.dtype == np.int64 + + # Should be just small enough to stay in int32 after stack. Note that + # we theoretically could support indices.max() == max_int32, but due to an + # edge-case in the underlying sparsetools code + # (namely the `coo_tocsr` routine), + # we require that max(X_hs_32.shape) < max_int32 as well. + # Hence we can only support max_int32 - 1. + col_3 = [max_int32 - max_indices_1 - 1] + X_3 = csr_matrix((data, (row, col_3))) + X_hs_32 = hstack([X_1, X_3], format="csr") + assert X_hs_32.indices.dtype == np.int32 + assert X_hs_32.indices.max() == max_int32 - 1 + +@pytest.mark.parametrize("cls", [csr_matrix, csr_array, csc_matrix, csc_array]) +def test_mixed_index_dtype_int_indexing(cls): + # https://github.com/scipy/scipy/issues/20182 + rng = np.random.default_rng(0) + base_mtx = cls(sparse.random(50, 50, random_state=rng, density=0.1)) + indptr_64bit = base_mtx.copy() + indices_64bit = base_mtx.copy() + indptr_64bit.indptr = base_mtx.indptr.astype(np.int64) + indices_64bit.indices = base_mtx.indices.astype(np.int64) + + for mtx in [base_mtx, indptr_64bit, indices_64bit]: + np.testing.assert_array_equal( + mtx[[1,2], :].toarray(), + base_mtx[[1, 2], :].toarray() + ) + np.testing.assert_array_equal( + mtx[:, [1, 2]].toarray(), + base_mtx[:, [1, 2]].toarray() + ) + +def test_broadcast_to(): + a = np.array([1, 0, 2]) + b = np.array([3]) + e = np.zeros((0,)) + res_a = csr_array(a)._broadcast_to((2,3)) + res_b = csr_array(b)._broadcast_to((4,)) + res_c = csr_array(b)._broadcast_to((2,4)) + res_d = csr_array(b)._broadcast_to((1,)) + res_e = csr_array(e)._broadcast_to((4,0)) + assert_array_equal(res_a.toarray(), np.broadcast_to(a, (2,3))) + assert_array_equal(res_b.toarray(), np.broadcast_to(b, (4,))) + assert_array_equal(res_c.toarray(), np.broadcast_to(b, (2,4))) + assert_array_equal(res_d.toarray(), np.broadcast_to(b, (1,))) + assert_array_equal(res_e.toarray(), np.broadcast_to(e, (4,0))) + + with pytest.raises(ValueError, match="cannot be broadcast"): + csr_matrix([[1, 2, 0], [3, 0, 1]])._broadcast_to(shape=(2, 1)) + + with pytest.raises(ValueError, match="cannot be broadcast"): + csr_matrix([[0, 1, 2]])._broadcast_to(shape=(3, 2)) + + with pytest.raises(ValueError, match="cannot be broadcast"): + csr_array([0, 1, 2])._broadcast_to(shape=(3, 2)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py new file mode 100644 index 0000000000000000000000000000000000000000..f3deda1668c3f526cfb205131a1348c620f25d20 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py @@ -0,0 +1,209 @@ +import pytest +import numpy as np +from numpy.testing import assert_equal +import scipy as sp +from scipy.sparse import dok_array, dok_matrix + + +pytestmark = pytest.mark.thread_unsafe + + +@pytest.fixture +def d(): + return {(0, 1): 1, (0, 2): 2} + +@pytest.fixture +def A(): + return np.array([[0, 1, 2], [0, 0, 0], [0, 0, 0]]) + +@pytest.fixture(params=[dok_array, dok_matrix]) +def Asp(request): + A = request.param((3, 3)) + A[(0, 1)] = 1 + A[(0, 2)] = 2 + yield A + +# Note: __iter__ and comparison dunders act like ndarrays for DOK, not dict. +# Dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array +# All other dict methods on DOK format act like dict methods (with extra checks). + +# Start of tests +################ +def test_dict_methods_covered(d, Asp): + d_methods = set(dir(d)) - {"__class_getitem__"} + asp_methods = set(dir(Asp)) + assert d_methods < asp_methods + +def test_clear(d, Asp): + assert d.items() == Asp.items() + d.clear() + Asp.clear() + assert d.items() == Asp.items() + +def test_copy(d, Asp): + assert d.items() == Asp.items() + dd = d.copy() + asp = Asp.copy() + assert dd.items() == asp.items() + assert asp.items() == Asp.items() + asp[(0, 1)] = 3 + assert Asp[(0, 1)] == 1 + +def test_fromkeys_default(): + # test with default value + edges = [(0, 2), (1, 0), (2, 1)] + Xdok = dok_array.fromkeys(edges) + X = [[0, 0, 1], [1, 0, 0], [0, 1, 0]] + assert_equal(Xdok.toarray(), X) + +def test_fromkeys_positional(): + # test with positional value + edges = [(0, 2), (1, 0), (2, 1)] + Xdok = dok_array.fromkeys(edges, -1) + X = [[0, 0, -1], [-1, 0, 0], [0, -1, 0]] + assert_equal(Xdok.toarray(), X) + +def test_fromkeys_iterator(): + it = ((a, a % 2) for a in range(4)) + Xdok = dok_array.fromkeys(it) + X = [[1, 0], [0, 1], [1, 0], [0, 1]] + assert_equal(Xdok.toarray(), X) + +def test_get(d, Asp): + assert Asp.get((0, 1)) == d.get((0, 1)) + assert Asp.get((0, 0), 99) == d.get((0, 0), 99) + with pytest.raises(IndexError, match="out of bounds"): + Asp.get((0, 4), 99) + +def test_items(d, Asp): + assert Asp.items() == d.items() + +def test_keys(d, Asp): + assert Asp.keys() == d.keys() + +def test_pop(d, Asp): + assert d.pop((0, 1)) == 1 + assert Asp.pop((0, 1)) == 1 + assert d.items() == Asp.items() + + assert Asp.pop((22, 21), None) is None + assert Asp.pop((22, 21), "other") == "other" + with pytest.raises(KeyError, match="(22, 21)"): + Asp.pop((22, 21)) + with pytest.raises(TypeError, match="got an unexpected keyword argument"): + Asp.pop((22, 21), default=5) + +def test_popitem(d, Asp): + assert d.popitem() == Asp.popitem() + assert d.items() == Asp.items() + +def test_setdefault(d, Asp): + assert Asp.setdefault((0, 1), 4) == 1 + assert Asp.setdefault((2, 2), 4) == 4 + d.setdefault((0, 1), 4) + d.setdefault((2, 2), 4) + assert d.items() == Asp.items() + +def test_update(d, Asp): + with pytest.raises(NotImplementedError): + Asp.update(Asp) + +def test_values(d, Asp): + # Note: dict.values are strange: d={1: 1}; d.values() == d.values() is False + # Using list(d.values()) makes them comparable. + assert list(Asp.values()) == list(d.values()) + +def test_dunder_getitem(d, Asp): + assert Asp[(0, 1)] == d[(0, 1)] + +def test_dunder_setitem(d, Asp): + Asp[(1, 1)] = 5 + d[(1, 1)] = 5 + assert d.items() == Asp.items() + +def test_dunder_delitem(d, Asp): + del Asp[(0, 1)] + del d[(0, 1)] + assert d.items() == Asp.items() + +def test_dunder_contains(d, Asp): + assert ((0, 1) in d) == ((0, 1) in Asp) + assert ((0, 0) in d) == ((0, 0) in Asp) + +def test_dunder_len(d, Asp): + assert len(d) == len(Asp) + +# Note: dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array +def test_dunder_reversed(d, Asp): + if isinstance(Asp, dok_array): + with pytest.raises(TypeError): + list(reversed(Asp)) + else: + assert list(reversed(Asp)) == list(reversed(d)) + +def test_dunder_ior(d, Asp): + if isinstance(Asp, dok_array): + with pytest.raises(TypeError): + Asp |= Asp + else: + dd = {(0, 0): 5} + Asp |= dd + assert Asp[(0, 0)] == 5 + d |= dd + assert d.items() == Asp.items() + dd |= Asp + assert dd.items() == Asp.items() + +def test_dunder_or(d, Asp): + if isinstance(Asp, dok_array): + with pytest.raises(TypeError): + Asp | Asp + else: + assert d | d == Asp | d + assert d | d == Asp | Asp + +def test_dunder_ror(d, Asp): + if isinstance(Asp, dok_array): + with pytest.raises(TypeError): + Asp | Asp + with pytest.raises(TypeError): + d | Asp + else: + assert Asp.__ror__(d) == Asp.__ror__(Asp) + assert d.__ror__(d) == Asp.__ror__(d) + assert d | Asp + +# Note: comparison dunders, e.g. ==, >=, etc follow np.array not dict +def test_dunder_eq(A, Asp): + with np.testing.suppress_warnings() as sup: + sup.filter(sp.sparse.SparseEfficiencyWarning) + assert (Asp == Asp).toarray().all() + assert (A == Asp).all() + +def test_dunder_ne(A, Asp): + assert not (Asp != Asp).toarray().any() + assert not (A != Asp).any() + +def test_dunder_lt(A, Asp): + assert not (Asp < Asp).toarray().any() + assert not (A < Asp).any() + +def test_dunder_gt(A, Asp): + assert not (Asp > Asp).toarray().any() + assert not (A > Asp).any() + +def test_dunder_le(A, Asp): + with np.testing.suppress_warnings() as sup: + sup.filter(sp.sparse.SparseEfficiencyWarning) + assert (Asp <= Asp).toarray().all() + assert (A <= Asp).all() + +def test_dunder_ge(A, Asp): + with np.testing.suppress_warnings() as sup: + sup.filter(sp.sparse.SparseEfficiencyWarning) + assert (Asp >= Asp).toarray().all() + assert (A >= Asp).all() + +# Note: iter dunder follows np.array not dict +def test_dunder_iter(A, Asp): + assert all((a == asp).all() for a, asp in zip(A, Asp)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c9f68bb2bde76d74ca767abba3c99b89d6e771 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py @@ -0,0 +1,51 @@ +"""test sparse matrix construction functions""" + +from numpy.testing import assert_equal +from scipy.sparse import csr_matrix, csr_array, sparray + +import numpy as np +from scipy.sparse import _extract + + +class TestExtract: + def setup_method(self): + self.cases = [ + csr_array([[1,2]]), + csr_array([[1,0]]), + csr_array([[0,0]]), + csr_array([[1],[2]]), + csr_array([[1],[0]]), + csr_array([[0],[0]]), + csr_array([[1,2],[3,4]]), + csr_array([[0,1],[0,0]]), + csr_array([[0,0],[1,0]]), + csr_array([[0,0],[0,0]]), + csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]), + csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]).T, + ] + + def test_find(self): + for A in self.cases: + I,J,V = _extract.find(A) + B = csr_array((V,(I,J)), shape=A.shape) + assert_equal(A.toarray(), B.toarray()) + + def test_tril(self): + for A in self.cases: + B = A.toarray() + for k in [-3,-2,-1,0,1,2,3]: + assert_equal(_extract.tril(A,k=k).toarray(), np.tril(B,k=k)) + + def test_triu(self): + for A in self.cases: + B = A.toarray() + for k in [-3,-2,-1,0,1,2,3]: + assert_equal(_extract.triu(A,k=k).toarray(), np.triu(B,k=k)) + + def test_array_vs_matrix(self): + for A in self.cases: + assert isinstance(_extract.tril(A), sparray) + assert isinstance(_extract.triu(A), sparray) + M = csr_matrix(A) + assert not isinstance(_extract.tril(M), sparray) + assert not isinstance(_extract.triu(M), sparray) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py new file mode 100644 index 0000000000000000000000000000000000000000..99934c455b796511b9f48243da044a9cee8a4d53 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py @@ -0,0 +1,603 @@ +import contextlib +import pytest +import numpy as np +from numpy.testing import assert_allclose, assert_equal + +from scipy.sparse import csr_array, dok_array, SparseEfficiencyWarning +from .test_arithmetic1d import toarray + + +formats_for_index1d = [csr_array, dok_array] + + +@contextlib.contextmanager +def check_remains_sorted(X): + """Checks that sorted indices property is retained through an operation""" + yield + if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices: + return + indices = X.indices.copy() + X.has_sorted_indices = False + X.sort_indices() + assert_equal(indices, X.indices, 'Expected sorted indices, found unsorted') + + +@pytest.mark.parametrize("spcreator", formats_for_index1d) +class TestGetSet1D: + def test_None_index(self, spcreator): + D = np.array([4, 3, 0]) + A = spcreator(D) + + N = D.shape[0] + for j in range(-N, N): + assert_equal(A[j, None].toarray(), D[j, None]) + assert_equal(A[None, j].toarray(), D[None, j]) + assert_equal(A[None, None, j].toarray(), D[None, None, j]) + + def test_getitem_shape(self, spcreator): + A = spcreator(np.arange(3 * 4).reshape(3, 4)) + assert A[1, 2].ndim == 0 + assert A[1, 2:3].shape == (1,) + assert A[None, 1, 2:3].shape == (1, 1) + assert A[None, 1, 2].shape == (1,) + assert A[None, 1, 2, None].shape == (1, 1) + + # see gh-22458 + assert A[None, 1].shape == (1, 4) + assert A[1, None].shape == (1, 4) + assert A[None, 1, :].shape == (1, 4) + assert A[1, None, :].shape == (1, 4) + assert A[1, :, None].shape == (4, 1) + + with pytest.raises(IndexError, match='Only 1D or 2D arrays'): + A[None, 2, 1, None, None] + with pytest.raises(IndexError, match='Only 1D or 2D arrays'): + A[None, 0:2, None, 1] + with pytest.raises(IndexError, match='Only 1D or 2D arrays'): + A[0:1, 1:, None] + with pytest.raises(IndexError, match='Only 1D or 2D arrays'): + A[1:, 1, None, None] + + def test_getelement(self, spcreator): + D = np.array([4, 3, 0]) + A = spcreator(D) + + N = D.shape[0] + for j in range(-N, N): + assert_equal(A[j], D[j]) + + for ij in [3, -4]: + with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'): + A.__getitem__(ij) + + # single element tuples unwrapped + assert A[(0,)] == 4 + + with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'): + A.__getitem__((4,)) + + def test_setelement(self, spcreator): + dtype = np.float64 + A = spcreator((12,), dtype=dtype) + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + A[0] = dtype(0) + A[1] = dtype(3) + A[8] = dtype(9.0) + A[-2] = dtype(7) + A[5] = 9 + + A[-9,] = dtype(8) + A[1,] = dtype(5) # overwrite using 1-tuple index + + for ij in [13, -14, (13,), (14,)]: + with pytest.raises(IndexError, match='out of (range|bounds)'): + A.__setitem__(ij, 123.0) + + +@pytest.mark.parametrize("spcreator", formats_for_index1d) +class TestSlicingAndFancy1D: + ####################### + # Int-like Array Index + ####################### + def test_get_array_index(self, spcreator): + D = np.array([4, 3, 0]) + A = spcreator(D) + + assert_equal(A[()].toarray(), D[()]) + for ij in [(0, 3), (3,)]: + with pytest.raises(IndexError, match='out of (range|bounds)|many indices'): + A.__getitem__(ij) + + def test_set_array_index(self, spcreator): + dtype = np.float64 + A = spcreator((12,), dtype=dtype) + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + A[np.array(6)] = dtype(4.0) # scalar index + A[np.array(6)] = dtype(2.0) # overwrite with scalar index + assert_equal(A.toarray(), [0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0]) + + for ij in [(13,), (-14,)]: + with pytest.raises(IndexError, match='index .* out of (range|bounds)'): + A.__setitem__(ij, 123.0) + + for v in [(), (0, 3), [1, 2, 3], np.array([1, 2, 3])]: + msg = 'Trying to assign a sequence to an item' + with pytest.raises(ValueError, match=msg): + A.__setitem__(0, v) + + #################### + # 1d Slice as index + #################### + def test_dtype_preservation(self, spcreator): + assert_equal(spcreator((10,), dtype=np.int16)[1:5].dtype, np.int16) + assert_equal(spcreator((6,), dtype=np.int32)[0:0:2].dtype, np.int32) + assert_equal(spcreator((6,), dtype=np.int64)[:].dtype, np.int64) + + def test_get_1d_slice(self, spcreator): + B = np.arange(50.) + A = spcreator(B) + assert_equal(B[:], A[:].toarray()) + assert_equal(B[2:5], A[2:5].toarray()) + + C = np.array([4, 0, 6, 0, 0, 0, 0, 0, 1]) + D = spcreator(C) + assert_equal(C[1:3], D[1:3].toarray()) + + # Now test slicing when a row contains only zeros + E = np.array([0, 0, 0, 0, 0]) + F = spcreator(E) + assert_equal(E[1:3], F[1:3].toarray()) + assert_equal(E[-2:], F[-2:].toarray()) + assert_equal(E[:], F[:].toarray()) + assert_equal(E[slice(None)], F[slice(None)].toarray()) + + def test_slicing_idx_slice(self, spcreator): + B = np.arange(50) + A = spcreator(B) + + # [i] + assert_equal(A[2], B[2]) + assert_equal(A[-1], B[-1]) + assert_equal(A[np.array(-2)], B[-2]) + + # [1:2] + assert_equal(A[:].toarray(), B[:]) + assert_equal(A[5:-2].toarray(), B[5:-2]) + assert_equal(A[5:12:3].toarray(), B[5:12:3]) + + # int8 slice + s = slice(np.int8(2), np.int8(4), None) + assert_equal(A[s].toarray(), B[2:4]) + + # np.s_ + s_ = np.s_ + slices = [s_[:2], s_[1:2], s_[3:], s_[3::2], + s_[15:20], s_[3:2], + s_[8:3:-1], s_[4::-2], s_[:5:-1], + 0, 1, s_[:], s_[1:5], -1, -2, -5, + np.array(-1), np.int8(-3)] + + for j, a in enumerate(slices): + x = A[a] + y = B[a] + if y.shape == (): + assert_equal(x, y, repr(a)) + else: + if x.size == 0 and y.size == 0: + pass + else: + assert_equal(x.toarray(), y, repr(a)) + + def test_ellipsis_1d_slicing(self, spcreator): + B = np.arange(50) + A = spcreator(B) + assert_equal(A[...].toarray(), B[...]) + assert_equal(A[...,].toarray(), B[...,]) + + ########################## + # Assignment with Slicing + ########################## + def test_slice_scalar_assign(self, spcreator): + A = spcreator((5,)) + B = np.zeros((5,)) + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + for C in [A, B]: + C[0:1] = 1 + C[2:0] = 4 + C[2:3] = 9 + C[3:] = 1 + C[3::-1] = 9 + assert_equal(A.toarray(), B) + + def test_slice_assign_2(self, spcreator): + shape = (10,) + + for idx in [slice(3), slice(None, 10, 4), slice(5, -2)]: + A = spcreator(shape) + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + A[idx] = 1 + B = np.zeros(shape) + B[idx] = 1 + msg = f"idx={idx!r}" + assert_allclose(A.toarray(), B, err_msg=msg) + + def test_self_self_assignment(self, spcreator): + # Tests whether a row of one lil_matrix can be assigned to another. + B = spcreator((5,)) + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + B[0] = 2 + B[1] = 0 + B[2] = 3 + B[3] = 10 + + A = B / 10 + B[:] = A[:] + assert_equal(A[:].toarray(), B[:].toarray()) + + A = B / 10 + B[:] = A[:1] + assert_equal(np.zeros((5,)) + A[0], B.toarray()) + + A = B / 10 + B[:-1] = A[1:] + assert_equal(A[1:].toarray(), B[:-1].toarray()) + + def test_slice_assignment(self, spcreator): + B = spcreator((4,)) + expected = np.array([10, 0, 14, 0]) + block = [2, 1] + + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + B[0] = 5 + B[2] = 7 + B[:] = B + B + assert_equal(B.toarray(), expected) + + B[:2] = csr_array(block) + assert_equal(B.toarray()[:2], block) + + def test_set_slice(self, spcreator): + A = spcreator((5,)) + B = np.zeros(5, float) + s_ = np.s_ + slices = [s_[:2], s_[1:2], s_[3:], s_[3::2], + s_[8:3:-1], s_[4::-2], s_[:5:-1], + 0, 1, s_[:], s_[1:5], -1, -2, -5, + np.array(-1), np.int8(-3)] + + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + for j, a in enumerate(slices): + A[a] = j + B[a] = j + assert_equal(A.toarray(), B, repr(a)) + + A[1:10:2] = range(1, 5, 2) + B[1:10:2] = range(1, 5, 2) + assert_equal(A.toarray(), B) + + # The next commands should raise exceptions + toobig = list(range(100)) + with pytest.raises(ValueError, match='Trying to assign a sequence to an item'): + A.__setitem__(0, toobig) + with pytest.raises(ValueError, match='could not be broadcast together'): + A.__setitem__(slice(None), toobig) + + def test_assign_empty(self, spcreator): + A = spcreator(np.ones(3)) + B = spcreator((2,)) + A[:2] = B + assert_equal(A.toarray(), [0, 0, 1]) + + #################### + # 1d Fancy Indexing + #################### + def test_dtype_preservation_empty_index(self, spcreator): + A = spcreator((2,), dtype=np.int16) + assert_equal(A[[False, False]].dtype, np.int16) + assert_equal(A[[]].dtype, np.int16) + + def test_bad_index(self, spcreator): + A = spcreator(np.zeros(5)) + with pytest.raises( + (IndexError, ValueError, TypeError), + match='Index dimension must be 1 or 2|only integers', + ): + A.__getitem__("foo") + with pytest.raises( + (IndexError, ValueError, TypeError), + match='tuple index out of range|only integers', + ): + A.__getitem__((2, "foo")) + + def test_fancy_indexing_2darray(self, spcreator): + B = np.arange(50).reshape((5, 10)) + A = spcreator(B) + + # [i] + assert_equal(A[[1, 3]].toarray(), B[[1, 3]]) + + # [i,[1,2]] + assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]]) + assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]]) + assert_equal(A[np.array(-1), [2, -5]].toarray(), B[-1, [2, -5]]) + assert_equal(A[-1, np.array([2, -5])].toarray(), B[-1, [2, -5]]) + assert_equal(A[np.array(-1), np.array([2, -5])].toarray(), B[-1, [2, -5]]) + + # [1:2,[1,2]] + assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]]) + assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]]) + assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]]) + assert_equal(A[1:4, np.array([-1, -5])].toarray(), B[1:4, [-1, -5]]) + + # [[1,2],j] + assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3]) + assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4]) + assert_equal(A[np.array([2, -5]), -4].toarray(), B[[2, -5], -4]) + assert_equal(A[[2, -5], np.array(-4)].toarray(), B[[2, -5], -4]) + assert_equal(A[np.array([2, -5]), np.array(-4)].toarray(), B[[2, -5], -4]) + + # [[1,2],1:2] + assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :]) + assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1]) + assert_equal(A[np.array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1]) + + # [[1,2],[1,2]] + assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]]) + assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]]) + assert_equal( + toarray(A[np.array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]] + ) + assert_equal( + toarray(A[[-1, -3], np.array([2, -4])]), B[[-1, -3], [2, -4]] + ) + assert_equal( + toarray(A[np.array([-1, -3]), np.array([2, -4])]), B[[-1, -3], [2, -4]] + ) + + # [[[1],[2]],[1,2]] + assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]]) + assert_equal( + A[[[-1], [-3], [-2]], [2, -4]].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + assert_equal( + A[np.array([[-1], [-3], [-2]]), [2, -4]].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + assert_equal( + A[[[-1], [-3], [-2]], np.array([2, -4])].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + assert_equal( + A[np.array([[-1], [-3], [-2]]), np.array([2, -4])].toarray(), + B[[[-1], [-3], [-2]], [2, -4]] + ) + + # [[1,2]] + assert_equal(A[[1, 3]].toarray(), B[[1, 3]]) + assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]]) + assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]]) + + # [[1,2],:][:,[1,2]] + assert_equal( + A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]] + ) + assert_equal( + A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]] + ) + assert_equal( + A[np.array([-1, -3]), :][:, np.array([2, -4])].toarray(), + B[[-1, -3], :][:, [2, -4]] + ) + + # [:,[1,2]][[1,2],:] + assert_equal( + A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :] + ) + assert_equal( + A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :] + ) + assert_equal( + A[:, np.array([-1, -3])][np.array([2, -4]), :].toarray(), + B[:, [-1, -3]][[2, -4], :] + ) + + def test_fancy_indexing(self, spcreator): + B = np.arange(50) + A = spcreator(B) + + # [i] + assert_equal(A[[3]].toarray(), B[[3]]) + + # [np.array] + assert_equal(A[[1, 3]].toarray(), B[[1, 3]]) + assert_equal(A[[2, -5]].toarray(), B[[2, -5]]) + assert_equal(A[np.array(-1)], B[-1]) + assert_equal(A[np.array([-1, 2])].toarray(), B[[-1, 2]]) + assert_equal(A[np.array(5)], B[np.array(5)]) + + # [[[1],[2]]] + ind = np.array([[1], [3]]) + assert_equal(A[ind].toarray(), B[ind]) + ind = np.array([[-1], [-3], [-2]]) + assert_equal(A[ind].toarray(), B[ind]) + + # [[1, 2]] + assert_equal(A[[1, 3]].toarray(), B[[1, 3]]) + assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]]) + assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]]) + + # [[1, 2]][[1, 2]] + assert_equal(A[[1, 5, 2, 8]][[1, 3]].toarray(), + B[[1, 5, 2, 8]][[1, 3]]) + assert_equal(A[[-1, -5, 2, 8]][[1, -4]].toarray(), + B[[-1, -5, 2, 8]][[1, -4]]) + + def test_fancy_indexing_boolean(self, spcreator): + np.random.seed(1234) # make runs repeatable + + B = np.arange(50) + A = spcreator(B) + + I = np.array(np.random.randint(0, 2, size=50), dtype=bool) + + assert_equal(toarray(A[I]), B[I]) + assert_equal(toarray(A[B > 9]), B[B > 9]) + + Z1 = np.zeros(51, dtype=bool) + Z2 = np.zeros(51, dtype=bool) + Z2[-1] = True + Z3 = np.zeros(51, dtype=bool) + Z3[0] = True + + msg = 'bool index .* has shape|boolean index did not match' + with pytest.raises(IndexError, match=msg): + A.__getitem__(Z1) + with pytest.raises(IndexError, match=msg): + A.__getitem__(Z2) + with pytest.raises(IndexError, match=msg): + A.__getitem__(Z3) + + def test_fancy_indexing_sparse_boolean(self, spcreator): + np.random.seed(1234) # make runs repeatable + + B = np.arange(20) + A = spcreator(B) + + X = np.array(np.random.randint(0, 2, size=20), dtype=bool) + Xsp = csr_array(X) + + assert_equal(toarray(A[Xsp]), B[X]) + assert_equal(toarray(A[A > 9]), B[B > 9]) + + Y = np.array(np.random.randint(0, 2, size=60), dtype=bool) + + Ysp = csr_array(Y) + + with pytest.raises(IndexError, match='bool index .* has shape|only integers'): + A.__getitem__(Ysp) + with pytest.raises(IndexError, match='tuple index out of range|only integers'): + A.__getitem__((Xsp, 1)) + + def test_fancy_indexing_seq_assign(self, spcreator): + mat = spcreator(np.array([1, 0])) + with pytest.raises(ValueError, match='Trying to assign a sequence to an item'): + mat.__setitem__(0, np.array([1, 2])) + + def test_fancy_indexing_empty(self, spcreator): + B = np.arange(50) + B[3:9] = 0 + B[30] = 0 + A = spcreator(B) + + K = np.array([False] * 50) + assert_equal(toarray(A[K]), B[K]) + K = np.array([], dtype=int) + assert_equal(toarray(A[K]), B[K]) + J = np.array([0, 1, 2, 3, 4], dtype=int) + assert_equal(toarray(A[J]), B[J]) + + ############################ + # 1d Fancy Index Assignment + ############################ + def test_bad_index_assign(self, spcreator): + A = spcreator(np.zeros(5)) + msg = 'Index dimension must be 1 or 2|only integers' + with pytest.raises((IndexError, ValueError, TypeError), match=msg): + A.__setitem__("foo", 2) + + def test_fancy_indexing_set(self, spcreator): + M = (5,) + + # [1:2] + for j in [[2, 3, 4], slice(None, 10, 4), np.arange(3), + slice(5, -2), slice(2, 5)]: + A = spcreator(M) + B = np.zeros(M) + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + B[j] = 1 + with check_remains_sorted(A): + A[j] = 1 + assert_allclose(A.toarray(), B) + + def test_sequence_assignment(self, spcreator): + A = spcreator((4,)) + B = spcreator((3,)) + + i0 = [0, 1, 2] + i1 = (0, 1, 2) + i2 = np.array(i0) + + with np.testing.suppress_warnings() as sup: + sup.filter( + SparseEfficiencyWarning, + "Changing the sparsity structure of .* is expensive", + ) + with check_remains_sorted(A): + A[i0] = B[i0] + msg = "too many indices for array|tuple index out of range" + with pytest.raises(IndexError, match=msg): + B.__getitem__(i1) + A[i2] = B[i2] + assert_equal(A[:3].toarray(), B.toarray()) + assert A.shape == (4,) + + # slice + A = spcreator((4,)) + with check_remains_sorted(A): + A[1:3] = [10, 20] + assert_equal(A.toarray(), [0, 10, 20, 0]) + + # array + A = spcreator((4,)) + B = np.zeros(4) + with check_remains_sorted(A): + for C in [A, B]: + C[[0, 1, 2]] = [4, 5, 6] + assert_equal(A.toarray(), B) + + def test_fancy_assign_empty(self, spcreator): + B = np.arange(50) + B[2] = 0 + B[[3, 6]] = 0 + A = spcreator(B) + + K = np.array([False] * 50) + A[K] = 42 + assert_equal(A.toarray(), B) + + K = np.array([], dtype=int) + A[K] = 42 + assert_equal(A.toarray(), B) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py new file mode 100644 index 0000000000000000000000000000000000000000..90b4ea64a8928073eb5dd3f1b2752379f57327d9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py @@ -0,0 +1,109 @@ +import os +import numpy as np +import tempfile + +from pytest import raises as assert_raises +from numpy.testing import assert_equal, assert_ + +from scipy.sparse import (sparray, csc_matrix, csr_matrix, bsr_matrix, dia_matrix, + coo_matrix, dok_matrix, csr_array, save_npz, load_npz) + + +DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') + + +def _save_and_load(matrix): + fd, tmpfile = tempfile.mkstemp(suffix='.npz') + os.close(fd) + try: + save_npz(tmpfile, matrix) + loaded_matrix = load_npz(tmpfile) + finally: + os.remove(tmpfile) + return loaded_matrix + +def _check_save_and_load(dense_matrix): + for matrix_class in [csc_matrix, csr_matrix, bsr_matrix, dia_matrix, coo_matrix]: + matrix = matrix_class(dense_matrix) + loaded_matrix = _save_and_load(matrix) + assert_(type(loaded_matrix) is matrix_class) + assert_(loaded_matrix.shape == dense_matrix.shape) + assert_(loaded_matrix.dtype == dense_matrix.dtype) + assert_equal(loaded_matrix.toarray(), dense_matrix) + +def test_save_and_load_random(): + N = 10 + np.random.seed(0) + dense_matrix = np.random.random((N, N)) + dense_matrix[dense_matrix > 0.7] = 0 + _check_save_and_load(dense_matrix) + +def test_save_and_load_empty(): + dense_matrix = np.zeros((4,6)) + _check_save_and_load(dense_matrix) + +def test_save_and_load_one_entry(): + dense_matrix = np.zeros((4,6)) + dense_matrix[1,2] = 1 + _check_save_and_load(dense_matrix) + +def test_sparray_vs_spmatrix(): + #save/load matrix + fd, tmpfile = tempfile.mkstemp(suffix='.npz') + os.close(fd) + try: + save_npz(tmpfile, csr_matrix([[1.2, 0, 0.9], [0, 0.3, 0]])) + loaded_matrix = load_npz(tmpfile) + finally: + os.remove(tmpfile) + + #save/load array + fd, tmpfile = tempfile.mkstemp(suffix='.npz') + os.close(fd) + try: + save_npz(tmpfile, csr_array([[1.2, 0, 0.9], [0, 0.3, 0]])) + loaded_array = load_npz(tmpfile) + finally: + os.remove(tmpfile) + + assert not isinstance(loaded_matrix, sparray) + assert isinstance(loaded_array, sparray) + assert_(loaded_matrix.dtype == loaded_array.dtype) + assert_equal(loaded_matrix.toarray(), loaded_array.toarray()) + +def test_malicious_load(): + class Executor: + def __reduce__(self): + return (assert_, (False, 'unexpected code execution')) + + fd, tmpfile = tempfile.mkstemp(suffix='.npz') + os.close(fd) + try: + np.savez(tmpfile, format=Executor()) + + # Should raise a ValueError, not execute code + assert_raises(ValueError, load_npz, tmpfile) + finally: + os.remove(tmpfile) + + +def test_py23_compatibility(): + # Try loading files saved on Python 2 and Python 3. They are not + # the same, since files saved with SciPy versions < 1.0.0 may + # contain unicode. + + a = load_npz(os.path.join(DATA_DIR, 'csc_py2.npz')) + b = load_npz(os.path.join(DATA_DIR, 'csc_py3.npz')) + c = csc_matrix([[0]]) + + assert_equal(a.toarray(), c.toarray()) + assert_equal(b.toarray(), c.toarray()) + +def test_implemented_error(): + # Attempts to save an unsupported type and checks that an + # NotImplementedError is raised. + + x = dok_matrix((2,3)) + x[0,1] = 1 + + assert_raises(NotImplementedError, save_npz, 'x.npz', x) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py new file mode 100644 index 0000000000000000000000000000000000000000..dca3f44fa485070805995c2f76c0c511123ce355 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py @@ -0,0 +1,128 @@ +"""Test of min-max 1D features of sparse array classes""" + +import pytest + +import numpy as np + +from numpy.testing import assert_equal, assert_array_equal + +from scipy.sparse import coo_array, csr_array, csc_array, bsr_array +from scipy.sparse import coo_matrix, csr_matrix, csc_matrix, bsr_matrix +from scipy.sparse._sputils import isscalarlike + + +def toarray(a): + if isinstance(a, np.ndarray) or isscalarlike(a): + return a + return a.toarray() + + +formats_for_minmax = [bsr_array, coo_array, csc_array, csr_array] +formats_for_minmax_supporting_1d = [coo_array, csr_array] + + +@pytest.mark.parametrize("spcreator", formats_for_minmax_supporting_1d) +class Test_MinMaxMixin1D: + def test_minmax(self, spcreator): + D = np.arange(5) + X = spcreator(D) + + assert_equal(X.min(), 0) + assert_equal(X.max(), 4) + assert_equal((-X).min(), -4) + assert_equal((-X).max(), 0) + + def test_minmax_axis(self, spcreator): + D = np.arange(50) + X = spcreator(D) + + for axis in [0, -1]: + assert_array_equal( + toarray(X.max(axis=axis)), D.max(axis=axis, keepdims=True) + ) + assert_array_equal( + toarray(X.min(axis=axis)), D.min(axis=axis, keepdims=True) + ) + for axis in [-2, 1]: + with pytest.raises(ValueError, match="axis out of range"): + X.min(axis=axis) + with pytest.raises(ValueError, match="axis out of range"): + X.max(axis=axis) + + def test_numpy_minmax(self, spcreator): + dat = np.array([0, 1, 2]) + datsp = spcreator(dat) + assert_array_equal(np.min(datsp), np.min(dat)) + assert_array_equal(np.max(datsp), np.max(dat)) + + + def test_argmax(self, spcreator): + D1 = np.array([-1, 5, 2, 3]) + D2 = np.array([0, 0, -1, -2]) + D3 = np.array([-1, -2, -3, -4]) + D4 = np.array([1, 2, 3, 4]) + D5 = np.array([1, 2, 0, 0]) + + for D in [D1, D2, D3, D4, D5]: + mat = spcreator(D) + + assert_equal(mat.argmax(), np.argmax(D)) + assert_equal(mat.argmin(), np.argmin(D)) + + assert_equal(mat.argmax(axis=0), np.argmax(D, axis=0)) + assert_equal(mat.argmin(axis=0), np.argmin(D, axis=0)) + + D6 = np.empty((0,)) + + for axis in [None, 0]: + mat = spcreator(D6) + with pytest.raises(ValueError, match="to an empty matrix"): + mat.argmin(axis=axis) + with pytest.raises(ValueError, match="to an empty matrix"): + mat.argmax(axis=axis) + + +@pytest.mark.parametrize("spcreator", formats_for_minmax) +class Test_ShapeMinMax2DWithAxis: + def test_minmax(self, spcreator): + dat = np.array([[-1, 5, 0, 3], [0, 0, -1, -2], [0, 0, 1, 2]]) + datsp = spcreator(dat) + + for (spminmax, npminmax) in [ + (datsp.min, np.min), + (datsp.max, np.max), + (datsp.nanmin, np.nanmin), + (datsp.nanmax, np.nanmax), + ]: + for ax, result_shape in [(0, (4,)), (1, (3,))]: + assert_equal(toarray(spminmax(axis=ax)), npminmax(dat, axis=ax)) + assert_equal(spminmax(axis=ax).shape, result_shape) + assert spminmax(axis=ax).format == "coo" + + for spminmax in [datsp.argmin, datsp.argmax]: + for ax in [0, 1]: + assert isinstance(spminmax(axis=ax), np.ndarray) + + # verify spmatrix behavior + spmat_form = { + 'coo': coo_matrix, + 'csr': csr_matrix, + 'csc': csc_matrix, + 'bsr': bsr_matrix, + } + datspm = spmat_form[datsp.format](dat) + + for spm, npm in [ + (datspm.min, np.min), + (datspm.max, np.max), + (datspm.nanmin, np.nanmin), + (datspm.nanmax, np.nanmax), + ]: + for ax, result_shape in [(0, (1, 4)), (1, (3, 1))]: + assert_equal(toarray(spm(axis=ax)), npm(dat, axis=ax, keepdims=True)) + assert_equal(spm(axis=ax).shape, result_shape) + assert spm(axis=ax).format == "coo" + + for spminmax in [datspm.argmin, datspm.argmax]: + for ax in [0, 1]: + assert isinstance(spminmax(axis=ax), np.ndarray) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8b94796116a22c210104fc446c5a17045ed21c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py @@ -0,0 +1,339 @@ +import sys +import os +import gc +import threading + +import numpy as np +from numpy.testing import assert_equal, assert_, assert_allclose +from scipy.sparse import (_sparsetools, coo_matrix, csr_matrix, csc_matrix, + bsr_matrix, dia_matrix) +from scipy.sparse._sputils import supported_dtypes +from scipy._lib._testutils import check_free_memory + +import pytest +from pytest import raises as assert_raises + + +def int_to_int8(n): + """ + Wrap an integer to the interval [-128, 127]. + """ + return (n + 128) % 256 - 128 + + +def test_exception(): + assert_raises(MemoryError, _sparsetools.test_throw_error) + + +def test_threads(): + # Smoke test for parallel threaded execution; doesn't actually + # check that code runs in parallel, but just that it produces + # expected results. + nthreads = 10 + niter = 100 + + n = 20 + a = csr_matrix(np.ones([n, n])) + bres = [] + + class Worker(threading.Thread): + def run(self): + b = a.copy() + for j in range(niter): + _sparsetools.csr_plus_csr(n, n, + a.indptr, a.indices, a.data, + a.indptr, a.indices, a.data, + b.indptr, b.indices, b.data) + bres.append(b) + + threads = [Worker() for _ in range(nthreads)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + for b in bres: + assert_(np.all(b.toarray() == 2)) + + +def test_regression_std_vector_dtypes(): + # Regression test for gh-3780, checking the std::vector typemaps + # in sparsetools.cxx are complete. + for dtype in supported_dtypes: + ad = np.array([[1, 2], [3, 4]]).astype(dtype) + a = csr_matrix(ad, dtype=dtype) + + # getcol is one function using std::vector typemaps, and should not fail + assert_equal(a.getcol(0).toarray(), ad[:, :1]) + + +@pytest.mark.slow +@pytest.mark.xfail_on_32bit("Can't create large array for test") +def test_nnz_overflow(): + # Regression test for gh-7230 / gh-7871, checking that coo_toarray + # with nnz > int32max doesn't overflow. + nnz = np.iinfo(np.int32).max + 1 + # Ensure ~20 GB of RAM is free to run this test. + check_free_memory((4 + 4 + 1) * nnz / 1e6 + 0.5) + + # Use nnz duplicate entries to keep the dense version small. + row = np.zeros(nnz, dtype=np.int32) + col = np.zeros(nnz, dtype=np.int32) + data = np.zeros(nnz, dtype=np.int8) + data[-1] = 4 + s = coo_matrix((data, (row, col)), shape=(1, 1), copy=False) + # Sums nnz duplicates to produce a 1x1 array containing 4. + d = s.toarray() + + assert_allclose(d, [[4]]) + + +@pytest.mark.skipif( + not (sys.platform.startswith('linux') and np.dtype(np.intp).itemsize >= 8), + reason="test requires 64-bit Linux" +) +class TestInt32Overflow: + """ + Some of the sparsetools routines use dense 2D matrices whose + total size is not bounded by the nnz of the sparse matrix. These + routines used to suffer from int32 wraparounds; here, we try to + check that the wraparounds don't occur any more. + """ + # choose n large enough + n = 50000 + + def setup_method(self): + assert self.n**2 > np.iinfo(np.int32).max + + # check there's enough memory even if everything is run at the + # same time + try: + parallel_count = int(os.environ.get('PYTEST_XDIST_WORKER_COUNT', '1')) + except ValueError: + parallel_count = np.inf + + check_free_memory(3000 * parallel_count) + + def teardown_method(self): + gc.collect() + + def test_coo_todense(self): + # Check *_todense routines (cf. gh-2179) + # + # All of them in the end call coo_matrix.todense + + n = self.n + + i = np.array([0, n-1]) + j = np.array([0, n-1]) + data = np.array([1, 2], dtype=np.int8) + m = coo_matrix((data, (i, j))) + + r = m.todense() + assert_equal(r[0,0], 1) + assert_equal(r[-1,-1], 2) + del r + gc.collect() + + @pytest.mark.slow + def test_matvecs(self): + # Check *_matvecs routines + n = self.n + + i = np.array([0, n-1]) + j = np.array([0, n-1]) + data = np.array([1, 2], dtype=np.int8) + m = coo_matrix((data, (i, j))) + + b = np.ones((n, n), dtype=np.int8) + for sptype in (csr_matrix, csc_matrix, bsr_matrix): + m2 = sptype(m) + r = m2.dot(b) + assert_equal(r[0,0], 1) + assert_equal(r[-1,-1], 2) + del r + gc.collect() + + del b + gc.collect() + + @pytest.mark.slow + def test_dia_matvec(self): + # Check: huge dia_matrix _matvec + n = self.n + data = np.ones((n, n), dtype=np.int8) + offsets = np.arange(n) + m = dia_matrix((data, offsets), shape=(n, n)) + v = np.ones(m.shape[1], dtype=np.int8) + r = m.dot(v) + assert_equal(r[0], int_to_int8(n)) + del data, offsets, m, v, r + gc.collect() + + _bsr_ops = [pytest.param("matmat", marks=pytest.mark.xslow), + pytest.param("matvecs", marks=pytest.mark.xslow), + "matvec", + "diagonal", + "sort_indices", + pytest.param("transpose", marks=pytest.mark.xslow)] + + @pytest.mark.slow + @pytest.mark.parametrize("op", _bsr_ops) + def test_bsr_1_block(self, op): + # Check: huge bsr_matrix (1-block) + # + # The point here is that indices inside a block may overflow. + + def get_matrix(): + n = self.n + data = np.ones((1, n, n), dtype=np.int8) + indptr = np.array([0, 1], dtype=np.int32) + indices = np.array([0], dtype=np.int32) + m = bsr_matrix((data, indices, indptr), blocksize=(n, n), copy=False) + del data, indptr, indices + return m + + gc.collect() + try: + getattr(self, "_check_bsr_" + op)(get_matrix) + finally: + gc.collect() + + @pytest.mark.slow + @pytest.mark.parametrize("op", _bsr_ops) + def test_bsr_n_block(self, op): + # Check: huge bsr_matrix (n-block) + # + # The point here is that while indices within a block don't + # overflow, accumulators across many block may. + + def get_matrix(): + n = self.n + data = np.ones((n, n, 1), dtype=np.int8) + indptr = np.array([0, n], dtype=np.int32) + indices = np.arange(n, dtype=np.int32) + m = bsr_matrix((data, indices, indptr), blocksize=(n, 1), copy=False) + del data, indptr, indices + return m + + gc.collect() + try: + getattr(self, "_check_bsr_" + op)(get_matrix) + finally: + gc.collect() + + def _check_bsr_matvecs(self, m): # skip name check + m = m() + n = self.n + + # _matvecs + r = m.dot(np.ones((n, 2), dtype=np.int8)) + assert_equal(r[0, 0], int_to_int8(n)) + + def _check_bsr_matvec(self, m): # skip name check + m = m() + n = self.n + + # _matvec + r = m.dot(np.ones((n,), dtype=np.int8)) + assert_equal(r[0], int_to_int8(n)) + + def _check_bsr_diagonal(self, m): # skip name check + m = m() + n = self.n + + # _diagonal + r = m.diagonal() + assert_equal(r, np.ones(n)) + + def _check_bsr_sort_indices(self, m): # skip name check + # _sort_indices + m = m() + m.sort_indices() + + def _check_bsr_transpose(self, m): # skip name check + # _transpose + m = m() + m.transpose() + + def _check_bsr_matmat(self, m): # skip name check + m = m() + n = self.n + + # _bsr_matmat + m2 = bsr_matrix(np.ones((n, 2), dtype=np.int8), blocksize=(m.blocksize[1], 2)) + m.dot(m2) # shouldn't SIGSEGV + del m2 + + # _bsr_matmat + m2 = bsr_matrix(np.ones((2, n), dtype=np.int8), blocksize=(2, m.blocksize[0])) + m2.dot(m) # shouldn't SIGSEGV + + +@pytest.mark.skip(reason="64-bit indices in sparse matrices not available") +def test_csr_matmat_int64_overflow(): + n = 3037000500 + assert n**2 > np.iinfo(np.int64).max + + # the test would take crazy amounts of memory + check_free_memory(n * (8*2 + 1) * 3 / 1e6) + + # int64 overflow + data = np.ones((n,), dtype=np.int8) + indptr = np.arange(n+1, dtype=np.int64) + indices = np.zeros(n, dtype=np.int64) + a = csr_matrix((data, indices, indptr)) + b = a.T + + assert_raises(RuntimeError, a.dot, b) + + +def test_upcast(): + a0 = csr_matrix([[np.pi, np.pi*1j], [3, 4]], dtype=complex) + b0 = np.array([256+1j, 2**32], dtype=complex) + + for a_dtype in supported_dtypes: + for b_dtype in supported_dtypes: + msg = f"({a_dtype!r}, {b_dtype!r})" + + if np.issubdtype(a_dtype, np.complexfloating): + a = a0.copy().astype(a_dtype) + else: + a = a0.real.copy().astype(a_dtype) + + if np.issubdtype(b_dtype, np.complexfloating): + b = b0.copy().astype(b_dtype) + else: + with np.errstate(invalid="ignore"): + # Casting a large value (2**32) to int8 causes a warning in + # numpy >1.23 + b = b0.real.copy().astype(b_dtype) + + if not (a_dtype == np.bool_ and b_dtype == np.bool_): + c = np.zeros((2,), dtype=np.bool_) + assert_raises(ValueError, _sparsetools.csr_matvec, + 2, 2, a.indptr, a.indices, a.data, b, c) + + if ((np.issubdtype(a_dtype, np.complexfloating) and + not np.issubdtype(b_dtype, np.complexfloating)) or + (not np.issubdtype(a_dtype, np.complexfloating) and + np.issubdtype(b_dtype, np.complexfloating))): + c = np.zeros((2,), dtype=np.float64) + assert_raises(ValueError, _sparsetools.csr_matvec, + 2, 2, a.indptr, a.indices, a.data, b, c) + + c = np.zeros((2,), dtype=np.result_type(a_dtype, b_dtype)) + _sparsetools.csr_matvec(2, 2, a.indptr, a.indices, a.data, b, c) + assert_allclose(c, np.dot(a.toarray(), b), err_msg=msg) + + +def test_endianness(): + d = np.ones((3,4)) + offsets = [-1,0,1] + + a = dia_matrix((d.astype('f8'), offsets), (4, 4)) + v = np.arange(4) + + assert_allclose(a.dot(v), [1, 3, 6, 5]) + assert_allclose(b.dot(v), [1, 3, 6, 5]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..75bc2d92c369be5799a904bc0938617f30321f12 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py @@ -0,0 +1,97 @@ +from numpy import array, kron, diag +from numpy.testing import assert_, assert_equal + +from scipy.sparse import _spfuncs as spfuncs +from scipy.sparse import csr_matrix, csc_matrix, bsr_matrix +from scipy.sparse._sparsetools import (csr_scale_rows, csr_scale_columns, + bsr_scale_rows, bsr_scale_columns) + + +class TestSparseFunctions: + def test_scale_rows_and_cols(self): + D = array([[1, 0, 0, 2, 3], + [0, 4, 0, 5, 0], + [0, 0, 6, 7, 0]]) + + #TODO expose through function + S = csr_matrix(D) + v = array([1,2,3]) + csr_scale_rows(3,5,S.indptr,S.indices,S.data,v) + assert_equal(S.toarray(), diag(v)@D) + + S = csr_matrix(D) + v = array([1,2,3,4,5]) + csr_scale_columns(3,5,S.indptr,S.indices,S.data,v) + assert_equal(S.toarray(), D@diag(v)) + + # blocks + E = kron(D,[[1,2],[3,4]]) + S = bsr_matrix(E,blocksize=(2,2)) + v = array([1,2,3,4,5,6]) + bsr_scale_rows(3,5,2,2,S.indptr,S.indices,S.data,v) + assert_equal(S.toarray(), diag(v)@E) + + S = bsr_matrix(E,blocksize=(2,2)) + v = array([1,2,3,4,5,6,7,8,9,10]) + bsr_scale_columns(3,5,2,2,S.indptr,S.indices,S.data,v) + assert_equal(S.toarray(), E@diag(v)) + + E = kron(D,[[1,2,3],[4,5,6]]) + S = bsr_matrix(E,blocksize=(2,3)) + v = array([1,2,3,4,5,6]) + bsr_scale_rows(3,5,2,3,S.indptr,S.indices,S.data,v) + assert_equal(S.toarray(), diag(v)@E) + + S = bsr_matrix(E,blocksize=(2,3)) + v = array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) + bsr_scale_columns(3,5,2,3,S.indptr,S.indices,S.data,v) + assert_equal(S.toarray(), E@diag(v)) + + def test_estimate_blocksize(self): + mats = [] + mats.append([[0,1],[1,0]]) + mats.append([[1,1,0],[0,0,1],[1,0,1]]) + mats.append([[0],[0],[1]]) + mats = [array(x) for x in mats] + + blks = [] + blks.append([[1]]) + blks.append([[1,1],[1,1]]) + blks.append([[1,1],[0,1]]) + blks.append([[1,1,0],[1,0,1],[1,1,1]]) + blks = [array(x) for x in blks] + + for A in mats: + for B in blks: + X = kron(A,B) + r,c = spfuncs.estimate_blocksize(X) + assert_(r >= B.shape[0]) + assert_(c >= B.shape[1]) + + def test_count_blocks(self): + def gold(A,bs): + R,C = bs + I,J = A.nonzero() + return len(set(zip(I//R,J//C))) + + mats = [] + mats.append([[0]]) + mats.append([[1]]) + mats.append([[1,0]]) + mats.append([[1,1]]) + mats.append([[0,1],[1,0]]) + mats.append([[1,1,0],[0,0,1],[1,0,1]]) + mats.append([[0],[0],[1]]) + + for A in mats: + for B in mats: + X = kron(A,B) + Y = csr_matrix(X) + for R in range(1,6): + for C in range(1,6): + assert_equal(spfuncs.count_blocks(Y, (R, C)), gold(X, (R, C))) + + X = kron([[1,1,0],[0,0,1],[1,0,1]],[[1,1]]) + Y = csc_matrix(X) + assert_equal(spfuncs.count_blocks(X, (1, 2)), gold(X, (1, 2))) + assert_equal(spfuncs.count_blocks(Y, (1, 2)), gold(X, (1, 2))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py new file mode 100644 index 0000000000000000000000000000000000000000..fb328e3f6512081f76604c4b92fe3d407819e448 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py @@ -0,0 +1,395 @@ +"""unit tests for sparse utility functions""" + +import numpy as np +from numpy.testing import assert_equal +import pytest +from pytest import raises as assert_raises +from scipy.sparse import _sputils as sputils, csr_array, bsr_array, dia_array, coo_array +from scipy.sparse._sputils import matrix + + +class TestSparseUtils: + + def test_upcast(self): + assert_equal(sputils.upcast('intc'), np.intc) + assert_equal(sputils.upcast('int32', 'float32'), np.float64) + assert_equal(sputils.upcast('bool', complex, float), np.complex128) + assert_equal(sputils.upcast('i', 'd'), np.float64) + + def test_getdtype(self): + A = np.array([1], dtype='int8') + + assert_equal(sputils.getdtype(None, default=float), float) + assert_equal(sputils.getdtype(None, a=A), np.int8) + + with assert_raises( + ValueError, + match="scipy.sparse does not support dtype object. .*", + ): + sputils.getdtype("O") + + with assert_raises( + ValueError, + match="scipy.sparse does not support dtype float16. .*", + ): + sputils.getdtype(None, default=np.float16) + + def test_isscalarlike(self): + assert_equal(sputils.isscalarlike(3.0), True) + assert_equal(sputils.isscalarlike(-4), True) + assert_equal(sputils.isscalarlike(2.5), True) + assert_equal(sputils.isscalarlike(1 + 3j), True) + assert_equal(sputils.isscalarlike(np.array(3)), True) + assert_equal(sputils.isscalarlike("16"), True) + + assert_equal(sputils.isscalarlike(np.array([3])), False) + assert_equal(sputils.isscalarlike([[3]]), False) + assert_equal(sputils.isscalarlike((1,)), False) + assert_equal(sputils.isscalarlike((1, 2)), False) + + def test_isintlike(self): + assert_equal(sputils.isintlike(-4), True) + assert_equal(sputils.isintlike(np.array(3)), True) + assert_equal(sputils.isintlike(np.array([3])), False) + with assert_raises( + ValueError, + match="Inexact indices into sparse matrices are not allowed" + ): + sputils.isintlike(3.0) + + assert_equal(sputils.isintlike(2.5), False) + assert_equal(sputils.isintlike(1 + 3j), False) + assert_equal(sputils.isintlike((1,)), False) + assert_equal(sputils.isintlike((1, 2)), False) + + def test_isshape(self): + assert_equal(sputils.isshape((1, 2)), True) + assert_equal(sputils.isshape((5, 2)), True) + + assert_equal(sputils.isshape((1.5, 2)), False) + assert_equal(sputils.isshape((2, 2, 2)), False) + assert_equal(sputils.isshape(([2], 2)), False) + assert_equal(sputils.isshape((-1, 2), nonneg=False),True) + assert_equal(sputils.isshape((2, -1), nonneg=False),True) + assert_equal(sputils.isshape((-1, 2), nonneg=True),False) + assert_equal(sputils.isshape((2, -1), nonneg=True),False) + + assert_equal(sputils.isshape((1.5, 2), allow_nd=(1, 2)), False) + assert_equal(sputils.isshape(([2], 2), allow_nd=(1, 2)), False) + assert_equal(sputils.isshape((2, 2, -2), nonneg=True, allow_nd=(1, 2)), + False) + assert_equal(sputils.isshape((2,), allow_nd=(1, 2)), True) + assert_equal(sputils.isshape((2, 2,), allow_nd=(1, 2)), True) + assert_equal(sputils.isshape((2, 2, 2), allow_nd=(1, 2)), False) + + def test_issequence(self): + assert_equal(sputils.issequence((1,)), True) + assert_equal(sputils.issequence((1, 2, 3)), True) + assert_equal(sputils.issequence([1]), True) + assert_equal(sputils.issequence([1, 2, 3]), True) + assert_equal(sputils.issequence(np.array([1, 2, 3])), True) + + assert_equal(sputils.issequence(np.array([[1], [2], [3]])), False) + assert_equal(sputils.issequence(3), False) + + def test_ismatrix(self): + assert_equal(sputils.ismatrix(((),)), True) + assert_equal(sputils.ismatrix([[1], [2]]), True) + assert_equal(sputils.ismatrix(np.arange(3)[None]), True) + + assert_equal(sputils.ismatrix([1, 2]), False) + assert_equal(sputils.ismatrix(np.arange(3)), False) + assert_equal(sputils.ismatrix([[[1]]]), False) + assert_equal(sputils.ismatrix(3), False) + + def test_isdense(self): + assert_equal(sputils.isdense(np.array([1])), True) + assert_equal(sputils.isdense(matrix([1])), True) + + def test_validateaxis(self): + assert_raises(TypeError, sputils.validateaxis, (0, 1)) + assert_raises(TypeError, sputils.validateaxis, 1.5) + assert_raises(ValueError, sputils.validateaxis, 3) + + # These function calls should not raise errors + for axis in (-2, -1, 0, 1, None): + sputils.validateaxis(axis) + + @pytest.mark.parametrize("container", [csr_array, bsr_array]) + def test_safely_cast_index_compressed(self, container): + # This is slow to test completely as nnz > imax is big + # and indptr is big for some shapes + # So we don't test large nnz, nor csc_array (same code as csr_array) + imax = np.int64(np.iinfo(np.int32).max) + + # Shape 32bit + A32 = container((1, imax)) + # indices big type, small values + B32 = A32.copy() + B32.indices = B32.indices.astype(np.int64) + B32.indptr = B32.indptr.astype(np.int64) + + # Shape 64bit + # indices big type, small values + A64 = csr_array((1, imax + 1)) + # indices small type, small values + B64 = A64.copy() + B64.indices = B64.indices.astype(np.int32) + B64.indptr = B64.indptr.astype(np.int32) + # indices big type, big values + C64 = A64.copy() + C64.indices = np.array([imax + 1], dtype=np.int64) + C64.indptr = np.array([0, 1], dtype=np.int64) + C64.data = np.array([2.2]) + + assert (A32.indices.dtype, A32.indptr.dtype) == (np.int32, np.int32) + assert (B32.indices.dtype, B32.indptr.dtype) == (np.int64, np.int64) + assert (A64.indices.dtype, A64.indptr.dtype) == (np.int64, np.int64) + assert (B64.indices.dtype, B64.indptr.dtype) == (np.int32, np.int32) + assert (C64.indices.dtype, C64.indptr.dtype) == (np.int64, np.int64) + + for A in [A32, B32, A64, B64]: + indices, indptr = sputils.safely_cast_index_arrays(A, np.int32) + assert (indices.dtype, indptr.dtype) == (np.int32, np.int32) + indices, indptr = sputils.safely_cast_index_arrays(A, np.int64) + assert (indices.dtype, indptr.dtype) == (np.int64, np.int64) + + indices, indptr = sputils.safely_cast_index_arrays(A, A.indices.dtype) + assert indices is A.indices + assert indptr is A.indptr + + with assert_raises(ValueError): + sputils.safely_cast_index_arrays(C64, np.int32) + indices, indptr = sputils.safely_cast_index_arrays(C64, np.int64) + assert indices is C64.indices + assert indptr is C64.indptr + + def test_safely_cast_index_coo(self): + # This is slow to test completely as nnz > imax is big + # So we don't test large nnz + imax = np.int64(np.iinfo(np.int32).max) + + # Shape 32bit + A32 = coo_array((1, imax)) + # coords big type, small values + B32 = A32.copy() + B32.coords = tuple(co.astype(np.int64) for co in B32.coords) + + # Shape 64bit + # coords big type, small values + A64 = coo_array((1, imax + 1)) + # coords small type, small values + B64 = A64.copy() + B64.coords = tuple(co.astype(np.int32) for co in B64.coords) + # coords big type, big values + C64 = A64.copy() + C64.coords = (np.array([imax + 1]), np.array([0])) + C64.data = np.array([2.2]) + + assert A32.coords[0].dtype == np.int32 + assert B32.coords[0].dtype == np.int64 + assert A64.coords[0].dtype == np.int64 + assert B64.coords[0].dtype == np.int32 + assert C64.coords[0].dtype == np.int64 + + for A in [A32, B32, A64, B64]: + coords = sputils.safely_cast_index_arrays(A, np.int32) + assert coords[0].dtype == np.int32 + coords = sputils.safely_cast_index_arrays(A, np.int64) + assert coords[0].dtype == np.int64 + + coords = sputils.safely_cast_index_arrays(A, A.coords[0].dtype) + assert coords[0] is A.coords[0] + + with assert_raises(ValueError): + sputils.safely_cast_index_arrays(C64, np.int32) + coords = sputils.safely_cast_index_arrays(C64, np.int64) + assert coords[0] is C64.coords[0] + + def test_safely_cast_index_dia(self): + # This is slow to test completely as nnz > imax is big + # So we don't test large nnz + imax = np.int64(np.iinfo(np.int32).max) + + # Shape 32bit + A32 = dia_array((1, imax)) + # offsets big type, small values + B32 = A32.copy() + B32.offsets = B32.offsets.astype(np.int64) + + # Shape 64bit + # offsets big type, small values + A64 = dia_array((1, imax + 2)) + # offsets small type, small values + B64 = A64.copy() + B64.offsets = B64.offsets.astype(np.int32) + # offsets big type, big values + C64 = A64.copy() + C64.offsets = np.array([imax + 1]) + C64.data = np.array([2.2]) + + assert A32.offsets.dtype == np.int32 + assert B32.offsets.dtype == np.int64 + assert A64.offsets.dtype == np.int64 + assert B64.offsets.dtype == np.int32 + assert C64.offsets.dtype == np.int64 + + for A in [A32, B32, A64, B64]: + offsets = sputils.safely_cast_index_arrays(A, np.int32) + assert offsets.dtype == np.int32 + offsets = sputils.safely_cast_index_arrays(A, np.int64) + assert offsets.dtype == np.int64 + + offsets = sputils.safely_cast_index_arrays(A, A.offsets.dtype) + assert offsets is A.offsets + + with assert_raises(ValueError): + sputils.safely_cast_index_arrays(C64, np.int32) + offsets = sputils.safely_cast_index_arrays(C64, np.int64) + assert offsets is C64.offsets + + def test_get_index_dtype(self): + imax = np.int64(np.iinfo(np.int32).max) + too_big = imax + 1 + + # Check that uint32's with no values too large doesn't return + # int64 + a1 = np.ones(90, dtype='uint32') + a2 = np.ones(90, dtype='uint32') + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), + np.dtype('int32') + ) + + # Check that if we can not convert but all values are less than or + # equal to max that we can just convert to int32 + a1[-1] = imax + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), + np.dtype('int32') + ) + + # Check that if it can not convert directly and the contents are + # too large that we return int64 + a1[-1] = too_big + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), + np.dtype('int64') + ) + + # test that if can not convert and didn't specify to check_contents + # we return int64 + a1 = np.ones(89, dtype='uint32') + a2 = np.ones(89, dtype='uint32') + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2))), + np.dtype('int64') + ) + + # Check that even if we have arrays that can be converted directly + # that if we specify a maxval directly it takes precedence + a1 = np.ones(12, dtype='uint32') + a2 = np.ones(12, dtype='uint32') + assert_equal( + np.dtype(sputils.get_index_dtype( + (a1, a2), maxval=too_big, check_contents=True + )), + np.dtype('int64') + ) + + # Check that an array with a too max size and maxval set + # still returns int64 + a1[-1] = too_big + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), maxval=too_big)), + np.dtype('int64') + ) + + # tests public broadcast_shapes largely from + # numpy/numpy/lib/tests/test_stride_tricks.py + # first 3 cause np.broadcast to raise index too large, but not sputils + @pytest.mark.parametrize("input_shapes,target_shape", [ + [((6, 5, 1, 4, 1, 1), (1, 2**32), (2**32, 1)), (6, 5, 1, 4, 2**32, 2**32)], + [((6, 5, 1, 4, 1, 1), (1, 2**32)), (6, 5, 1, 4, 1, 2**32)], + [((1, 2**32), (2**32, 1)), (2**32, 2**32)], + [[2, 2, 2], (2,)], + [[], ()], + [[()], ()], + [[(7,)], (7,)], + [[(1, 2), (2,)], (1, 2)], + [[(2,), (1, 2)], (1, 2)], + [[(1, 1)], (1, 1)], + [[(1, 1), (3, 4)], (3, 4)], + [[(6, 7), (5, 6, 1), (7,), (5, 1, 7)], (5, 6, 7)], + [[(5, 6, 1)], (5, 6, 1)], + [[(1, 3), (3, 1)], (3, 3)], + [[(1, 0), (0, 0)], (0, 0)], + [[(0, 1), (0, 0)], (0, 0)], + [[(1, 0), (0, 1)], (0, 0)], + [[(1, 1), (0, 0)], (0, 0)], + [[(1, 1), (1, 0)], (1, 0)], + [[(1, 1), (0, 1)], (0, 1)], + [[(), (0,)], (0,)], + [[(0,), (0, 0)], (0, 0)], + [[(0,), (0, 1)], (0, 0)], + [[(1,), (0, 0)], (0, 0)], + [[(), (0, 0)], (0, 0)], + [[(1, 1), (0,)], (1, 0)], + [[(1,), (0, 1)], (0, 1)], + [[(1,), (1, 0)], (1, 0)], + [[(), (1, 0)], (1, 0)], + [[(), (0, 1)], (0, 1)], + [[(1,), (3,)], (3,)], + [[2, (3, 2)], (3, 2)], + [[(1, 2)] * 32, (1, 2)], + [[(1, 2)] * 100, (1, 2)], + [[(2,)] * 32, (2,)], + ]) + def test_broadcast_shapes_successes(self, input_shapes, target_shape): + assert_equal(sputils.broadcast_shapes(*input_shapes), target_shape) + + # tests public broadcast_shapes failures + @pytest.mark.parametrize("input_shapes", [ + [(3,), (4,)], + [(2, 3), (2,)], + [2, (2, 3)], + [(3,), (3,), (4,)], + [(2, 5), (3, 5)], + [(2, 4), (2, 5)], + [(1, 3, 4), (2, 3, 3)], + [(1, 2), (3, 1), (3, 2), (10, 5)], + [(2,)] * 32 + [(3,)] * 32, + ]) + def test_broadcast_shapes_failures(self, input_shapes): + with assert_raises(ValueError, match="cannot be broadcast"): + sputils.broadcast_shapes(*input_shapes) + + def test_check_shape_overflow(self): + new_shape = sputils.check_shape([(10, -1)], (65535, 131070)) + assert_equal(new_shape, (10, 858967245)) + + def test_matrix(self): + a = [[1, 2, 3]] + b = np.array(a) + + assert isinstance(sputils.matrix(a), np.matrix) + assert isinstance(sputils.matrix(b), np.matrix) + + c = sputils.matrix(b) + c[:, :] = 123 + assert_equal(b, a) + + c = sputils.matrix(b, copy=False) + c[:, :] = 123 + assert_equal(b, [[123, 123, 123]]) + + def test_asmatrix(self): + a = [[1, 2, 3]] + b = np.array(a) + + assert isinstance(sputils.asmatrix(a), np.matrix) + assert isinstance(sputils.asmatrix(b), np.matrix) + + c = sputils.asmatrix(b) + c[:, :] = 123 + assert_equal(b, [[123, 123, 123]]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1daa9fb379572aac4bc9b6d74330a18c5c52bf79 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd @@ -0,0 +1 @@ +from scipy.special cimport cython_special diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8993f522a0fac00e243d361835a42b89a82d11ef --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.py @@ -0,0 +1,887 @@ +""" +======================================== +Special functions (:mod:`scipy.special`) +======================================== + +.. currentmodule:: scipy.special + +Almost all of the functions below accept NumPy arrays as input +arguments as well as single numbers. This means they follow +broadcasting and automatic array-looping rules. Technically, +they are `NumPy universal functions +`_. +Functions which do not accept NumPy arrays are marked by a warning +in the section description. + +.. seealso:: + + `scipy.special.cython_special` -- Typed Cython versions of special functions + + +Error handling +============== + +Errors are handled by returning NaNs or other appropriate values. +Some of the special function routines can emit warnings or raise +exceptions when an error occurs. By default this is disabled, except +for memory allocation errors, which result in an exception being raised. +To query and control the current error handling state the following +functions are provided. + +.. autosummary:: + :toctree: generated/ + + geterr -- Get the current way of handling special-function errors. + seterr -- Set how special-function errors are handled. + errstate -- Context manager for special-function error handling. + SpecialFunctionWarning -- Warning that can be emitted by special functions. + SpecialFunctionError -- Exception that can be raised by special functions. + +Available functions +=================== + +Airy functions +-------------- + +.. autosummary:: + :toctree: generated/ + + airy -- Airy functions and their derivatives. + airye -- Exponentially scaled Airy functions and their derivatives. + ai_zeros -- Compute `nt` zeros and values of the Airy function Ai and its derivative. + bi_zeros -- Compute `nt` zeros and values of the Airy function Bi and its derivative. + itairy -- Integrals of Airy functions + + +Elliptic functions and integrals +-------------------------------- + +.. autosummary:: + :toctree: generated/ + + ellipj -- Jacobian elliptic functions. + ellipk -- Complete elliptic integral of the first kind. + ellipkm1 -- Complete elliptic integral of the first kind around `m` = 1. + ellipkinc -- Incomplete elliptic integral of the first kind. + ellipe -- Complete elliptic integral of the second kind. + ellipeinc -- Incomplete elliptic integral of the second kind. + elliprc -- Degenerate symmetric integral RC. + elliprd -- Symmetric elliptic integral of the second kind. + elliprf -- Completely-symmetric elliptic integral of the first kind. + elliprg -- Completely-symmetric elliptic integral of the second kind. + elliprj -- Symmetric elliptic integral of the third kind. + +Bessel functions +---------------- + +.. autosummary:: + :toctree: generated/ + + jv -- Bessel function of the first kind of real order and \ + complex argument. + jve -- Exponentially scaled Bessel function of order `v`. + yn -- Bessel function of the second kind of integer order and \ + real argument. + yv -- Bessel function of the second kind of real order and \ + complex argument. + yve -- Exponentially scaled Bessel function of the second kind \ + of real order. + kn -- Modified Bessel function of the second kind of integer \ + order `n` + kv -- Modified Bessel function of the second kind of real order \ + `v` + kve -- Exponentially scaled modified Bessel function of the \ + second kind. + iv -- Modified Bessel function of the first kind of real order. + ive -- Exponentially scaled modified Bessel function of the \ + first kind. + hankel1 -- Hankel function of the first kind. + hankel1e -- Exponentially scaled Hankel function of the first kind. + hankel2 -- Hankel function of the second kind. + hankel2e -- Exponentially scaled Hankel function of the second kind. + wright_bessel -- Wright's generalized Bessel function. + log_wright_bessel -- Logarithm of Wright's generalized Bessel function. + +The following function does not accept NumPy arrays (it is not a +universal function): + +.. autosummary:: + :toctree: generated/ + + lmbda -- Jahnke-Emden Lambda function, Lambdav(x). + +Zeros of Bessel functions +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following functions do not accept NumPy arrays (they are not +universal functions): + +.. autosummary:: + :toctree: generated/ + + jnjnp_zeros -- Compute zeros of integer-order Bessel functions Jn and Jn'. + jnyn_zeros -- Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x). + jn_zeros -- Compute zeros of integer-order Bessel function Jn(x). + jnp_zeros -- Compute zeros of integer-order Bessel function derivative Jn'(x). + yn_zeros -- Compute zeros of integer-order Bessel function Yn(x). + ynp_zeros -- Compute zeros of integer-order Bessel function derivative Yn'(x). + y0_zeros -- Compute nt zeros of Bessel function Y0(z), and derivative at each zero. + y1_zeros -- Compute nt zeros of Bessel function Y1(z), and derivative at each zero. + y1p_zeros -- Compute nt zeros of Bessel derivative Y1'(z), and value at each zero. + +Faster versions of common Bessel functions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + j0 -- Bessel function of the first kind of order 0. + j1 -- Bessel function of the first kind of order 1. + y0 -- Bessel function of the second kind of order 0. + y1 -- Bessel function of the second kind of order 1. + i0 -- Modified Bessel function of order 0. + i0e -- Exponentially scaled modified Bessel function of order 0. + i1 -- Modified Bessel function of order 1. + i1e -- Exponentially scaled modified Bessel function of order 1. + k0 -- Modified Bessel function of the second kind of order 0, :math:`K_0`. + k0e -- Exponentially scaled modified Bessel function K of order 0 + k1 -- Modified Bessel function of the second kind of order 1, :math:`K_1(x)`. + k1e -- Exponentially scaled modified Bessel function K of order 1. + +Integrals of Bessel functions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + itj0y0 -- Integrals of Bessel functions of order 0. + it2j0y0 -- Integrals related to Bessel functions of order 0. + iti0k0 -- Integrals of modified Bessel functions of order 0. + it2i0k0 -- Integrals related to modified Bessel functions of order 0. + besselpoly -- Weighted integral of a Bessel function. + +Derivatives of Bessel functions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + jvp -- Compute nth derivative of Bessel function Jv(z) with respect to `z`. + yvp -- Compute nth derivative of Bessel function Yv(z) with respect to `z`. + kvp -- Compute nth derivative of real-order modified Bessel function Kv(z) + ivp -- Compute nth derivative of modified Bessel function Iv(z) with respect to `z`. + h1vp -- Compute nth derivative of Hankel function H1v(z) with respect to `z`. + h2vp -- Compute nth derivative of Hankel function H2v(z) with respect to `z`. + +Spherical Bessel functions +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + spherical_jn -- Spherical Bessel function of the first kind or its derivative. + spherical_yn -- Spherical Bessel function of the second kind or its derivative. + spherical_in -- Modified spherical Bessel function of the first kind or its derivative. + spherical_kn -- Modified spherical Bessel function of the second kind or its derivative. + +Riccati-Bessel functions +^^^^^^^^^^^^^^^^^^^^^^^^ + +The following functions do not accept NumPy arrays (they are not +universal functions): + +.. autosummary:: + :toctree: generated/ + + riccati_jn -- Compute Ricatti-Bessel function of the first kind and its derivative. + riccati_yn -- Compute Ricatti-Bessel function of the second kind and its derivative. + +Struve functions +---------------- + +.. autosummary:: + :toctree: generated/ + + struve -- Struve function. + modstruve -- Modified Struve function. + itstruve0 -- Integral of the Struve function of order 0. + it2struve0 -- Integral related to the Struve function of order 0. + itmodstruve0 -- Integral of the modified Struve function of order 0. + + +Raw statistical functions +------------------------- + +.. seealso:: :mod:`scipy.stats`: Friendly versions of these functions. + +Binomial distribution +^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + bdtr -- Binomial distribution cumulative distribution function. + bdtrc -- Binomial distribution survival function. + bdtri -- Inverse function to `bdtr` with respect to `p`. + bdtrik -- Inverse function to `bdtr` with respect to `k`. + bdtrin -- Inverse function to `bdtr` with respect to `n`. + +Beta distribution +^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + btdtria -- Inverse of `betainc` with respect to `a`. + btdtrib -- Inverse of `betainc` with respect to `b`. + +F distribution +^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + fdtr -- F cumulative distribution function. + fdtrc -- F survival function. + fdtri -- The `p`-th quantile of the F-distribution. + fdtridfd -- Inverse to `fdtr` vs dfd. + +Gamma distribution +^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + gdtr -- Gamma distribution cumulative distribution function. + gdtrc -- Gamma distribution survival function. + gdtria -- Inverse of `gdtr` vs a. + gdtrib -- Inverse of `gdtr` vs b. + gdtrix -- Inverse of `gdtr` vs x. + +Negative binomial distribution +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + nbdtr -- Negative binomial cumulative distribution function. + nbdtrc -- Negative binomial survival function. + nbdtri -- Inverse of `nbdtr` vs `p`. + nbdtrik -- Inverse of `nbdtr` vs `k`. + nbdtrin -- Inverse of `nbdtr` vs `n`. + +Noncentral F distribution +^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + ncfdtr -- Cumulative distribution function of the non-central F distribution. + ncfdtridfd -- Calculate degrees of freedom (denominator) for the noncentral F-distribution. + ncfdtridfn -- Calculate degrees of freedom (numerator) for the noncentral F-distribution. + ncfdtri -- Inverse cumulative distribution function of the non-central F distribution. + ncfdtrinc -- Calculate non-centrality parameter for non-central F distribution. + +Noncentral t distribution +^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + nctdtr -- Cumulative distribution function of the non-central `t` distribution. + nctdtridf -- Calculate degrees of freedom for non-central t distribution. + nctdtrit -- Inverse cumulative distribution function of the non-central t distribution. + nctdtrinc -- Calculate non-centrality parameter for non-central t distribution. + +Normal distribution +^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + nrdtrimn -- Calculate mean of normal distribution given other params. + nrdtrisd -- Calculate standard deviation of normal distribution given other params. + ndtr -- Normal cumulative distribution function. + log_ndtr -- Logarithm of normal cumulative distribution function. + ndtri -- Inverse of `ndtr` vs x. + ndtri_exp -- Inverse of `log_ndtr` vs x. + +Poisson distribution +^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + pdtr -- Poisson cumulative distribution function. + pdtrc -- Poisson survival function. + pdtri -- Inverse to `pdtr` vs m. + pdtrik -- Inverse to `pdtr` vs k. + +Student t distribution +^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + stdtr -- Student t distribution cumulative distribution function. + stdtridf -- Inverse of `stdtr` vs df. + stdtrit -- Inverse of `stdtr` vs `t`. + +Chi square distribution +^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + chdtr -- Chi square cumulative distribution function. + chdtrc -- Chi square survival function. + chdtri -- Inverse to `chdtrc`. + chdtriv -- Inverse to `chdtr` vs `v`. + +Non-central chi square distribution +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + chndtr -- Non-central chi square cumulative distribution function. + chndtridf -- Inverse to `chndtr` vs `df`. + chndtrinc -- Inverse to `chndtr` vs `nc`. + chndtrix -- Inverse to `chndtr` vs `x`. + +Kolmogorov distribution +^^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + smirnov -- Kolmogorov-Smirnov complementary cumulative distribution function. + smirnovi -- Inverse to `smirnov`. + kolmogorov -- Complementary cumulative distribution function of Kolmogorov distribution. + kolmogi -- Inverse function to `kolmogorov`. + +Box-Cox transformation +^^^^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + boxcox -- Compute the Box-Cox transformation. + boxcox1p -- Compute the Box-Cox transformation of 1 + `x`. + inv_boxcox -- Compute the inverse of the Box-Cox transformation. + inv_boxcox1p -- Compute the inverse of the Box-Cox transformation. + + +Sigmoidal functions +^^^^^^^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + logit -- Logit ufunc for ndarrays. + expit -- Logistic sigmoid function. + log_expit -- Logarithm of the logistic sigmoid function. + +Miscellaneous +^^^^^^^^^^^^^ + +.. autosummary:: + :toctree: generated/ + + tklmbda -- Tukey-Lambda cumulative distribution function. + owens_t -- Owen's T Function. + + +Information Theory functions +---------------------------- + +.. autosummary:: + :toctree: generated/ + + entr -- Elementwise function for computing entropy. + rel_entr -- Elementwise function for computing relative entropy. + kl_div -- Elementwise function for computing Kullback-Leibler divergence. + huber -- Huber loss function. + pseudo_huber -- Pseudo-Huber loss function. + + +Gamma and related functions +--------------------------- + +.. autosummary:: + :toctree: generated/ + + gamma -- Gamma function. + gammaln -- Logarithm of the absolute value of the Gamma function for real inputs. + loggamma -- Principal branch of the logarithm of the Gamma function. + gammasgn -- Sign of the gamma function. + gammainc -- Regularized lower incomplete gamma function. + gammaincinv -- Inverse to `gammainc`. + gammaincc -- Regularized upper incomplete gamma function. + gammainccinv -- Inverse to `gammaincc`. + beta -- Beta function. + betaln -- Natural logarithm of absolute value of beta function. + betainc -- Incomplete beta integral. + betaincc -- Complemented incomplete beta integral. + betaincinv -- Inverse function to beta integral. + betainccinv -- Inverse of the complemented incomplete beta integral. + psi -- The digamma function. + rgamma -- Gamma function inverted. + polygamma -- Polygamma function n. + multigammaln -- Returns the log of multivariate gamma, also sometimes called the generalized gamma. + digamma -- psi(x[, out]). + poch -- Rising factorial (z)_m. + +Error function and Fresnel integrals +------------------------------------ + +.. autosummary:: + :toctree: generated/ + + erf -- Returns the error function of complex argument. + erfc -- Complementary error function, ``1 - erf(x)``. + erfcx -- Scaled complementary error function, ``exp(x**2) * erfc(x)``. + erfi -- Imaginary error function, ``-i erf(i z)``. + erfinv -- Inverse function for erf. + erfcinv -- Inverse function for erfc. + wofz -- Faddeeva function. + dawsn -- Dawson's integral. + fresnel -- Fresnel sin and cos integrals. + fresnel_zeros -- Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z). + modfresnelp -- Modified Fresnel positive integrals. + modfresnelm -- Modified Fresnel negative integrals. + voigt_profile -- Voigt profile. + +The following functions do not accept NumPy arrays (they are not +universal functions): + +.. autosummary:: + :toctree: generated/ + + erf_zeros -- Compute nt complex zeros of error function erf(z). + fresnelc_zeros -- Compute nt complex zeros of cosine Fresnel integral C(z). + fresnels_zeros -- Compute nt complex zeros of sine Fresnel integral S(z). + +Legendre functions +------------------ + +.. autosummary:: + :toctree: generated/ + + legendre_p -- Legendre polynomials of the first kind. + legendre_p_all -- All Legendre polynomials of the first kind up to a specified order. + assoc_legendre_p -- Associated Legendre polynomials of the first kind. + assoc_legendre_p_all -- All associated Legendre polynomials of the first kind up to a specified order and degree. + sph_legendre_p -- Spherical Legendre polynomials of the first kind. + sph_legendre_p_all -- All spherical Legendre polynomials of the first kind up to a specified order and degree. + sph_harm_y -- Spherical harmonics. + sph_harm_y_all -- All spherical harmonics up to a specified order and degree. + +The following functions are in the process of being deprecated in favor of the above, +which provide a more flexible and consistent interface. + +.. autosummary:: + :toctree: generated/ + + lpmv -- Associated Legendre function of integer order and real degree. + sph_harm -- Compute spherical harmonics. + clpmn -- Associated Legendre function of the first kind for complex arguments. + lpn -- Legendre function of the first kind. + lqn -- Legendre function of the second kind. + lpmn -- Sequence of associated Legendre functions of the first kind. + lqmn -- Sequence of associated Legendre functions of the second kind. + +Ellipsoidal harmonics +--------------------- + +.. autosummary:: + :toctree: generated/ + + ellip_harm -- Ellipsoidal harmonic functions E^p_n(l). + ellip_harm_2 -- Ellipsoidal harmonic functions F^p_n(l). + ellip_normal -- Ellipsoidal harmonic normalization constants gamma^p_n. + +Orthogonal polynomials +---------------------- + +The following functions evaluate values of orthogonal polynomials: + +.. autosummary:: + :toctree: generated/ + + assoc_laguerre -- Compute the generalized (associated) Laguerre polynomial of degree n and order k. + eval_legendre -- Evaluate Legendre polynomial at a point. + eval_chebyt -- Evaluate Chebyshev polynomial of the first kind at a point. + eval_chebyu -- Evaluate Chebyshev polynomial of the second kind at a point. + eval_chebyc -- Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a point. + eval_chebys -- Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a point. + eval_jacobi -- Evaluate Jacobi polynomial at a point. + eval_laguerre -- Evaluate Laguerre polynomial at a point. + eval_genlaguerre -- Evaluate generalized Laguerre polynomial at a point. + eval_hermite -- Evaluate physicist's Hermite polynomial at a point. + eval_hermitenorm -- Evaluate probabilist's (normalized) Hermite polynomial at a point. + eval_gegenbauer -- Evaluate Gegenbauer polynomial at a point. + eval_sh_legendre -- Evaluate shifted Legendre polynomial at a point. + eval_sh_chebyt -- Evaluate shifted Chebyshev polynomial of the first kind at a point. + eval_sh_chebyu -- Evaluate shifted Chebyshev polynomial of the second kind at a point. + eval_sh_jacobi -- Evaluate shifted Jacobi polynomial at a point. + +The following functions compute roots and quadrature weights for +orthogonal polynomials: + +.. autosummary:: + :toctree: generated/ + + roots_legendre -- Gauss-Legendre quadrature. + roots_chebyt -- Gauss-Chebyshev (first kind) quadrature. + roots_chebyu -- Gauss-Chebyshev (second kind) quadrature. + roots_chebyc -- Gauss-Chebyshev (first kind) quadrature. + roots_chebys -- Gauss-Chebyshev (second kind) quadrature. + roots_jacobi -- Gauss-Jacobi quadrature. + roots_laguerre -- Gauss-Laguerre quadrature. + roots_genlaguerre -- Gauss-generalized Laguerre quadrature. + roots_hermite -- Gauss-Hermite (physicist's) quadrature. + roots_hermitenorm -- Gauss-Hermite (statistician's) quadrature. + roots_gegenbauer -- Gauss-Gegenbauer quadrature. + roots_sh_legendre -- Gauss-Legendre (shifted) quadrature. + roots_sh_chebyt -- Gauss-Chebyshev (first kind, shifted) quadrature. + roots_sh_chebyu -- Gauss-Chebyshev (second kind, shifted) quadrature. + roots_sh_jacobi -- Gauss-Jacobi (shifted) quadrature. + +The functions below, in turn, return the polynomial coefficients in +``orthopoly1d`` objects, which function similarly as `numpy.poly1d`. +The ``orthopoly1d`` class also has an attribute ``weights``, which returns +the roots, weights, and total weights for the appropriate form of Gaussian +quadrature. These are returned in an ``n x 3`` array with roots in the first +column, weights in the second column, and total weights in the final column. +Note that ``orthopoly1d`` objects are converted to `~numpy.poly1d` when doing +arithmetic, and lose information of the original orthogonal polynomial. + +.. autosummary:: + :toctree: generated/ + + legendre -- Legendre polynomial. + chebyt -- Chebyshev polynomial of the first kind. + chebyu -- Chebyshev polynomial of the second kind. + chebyc -- Chebyshev polynomial of the first kind on :math:`[-2, 2]`. + chebys -- Chebyshev polynomial of the second kind on :math:`[-2, 2]`. + jacobi -- Jacobi polynomial. + laguerre -- Laguerre polynomial. + genlaguerre -- Generalized (associated) Laguerre polynomial. + hermite -- Physicist's Hermite polynomial. + hermitenorm -- Normalized (probabilist's) Hermite polynomial. + gegenbauer -- Gegenbauer (ultraspherical) polynomial. + sh_legendre -- Shifted Legendre polynomial. + sh_chebyt -- Shifted Chebyshev polynomial of the first kind. + sh_chebyu -- Shifted Chebyshev polynomial of the second kind. + sh_jacobi -- Shifted Jacobi polynomial. + +.. warning:: + + Computing values of high-order polynomials (around ``order > 20``) using + polynomial coefficients is numerically unstable. To evaluate polynomial + values, the ``eval_*`` functions should be used instead. + + +Hypergeometric functions +------------------------ + +.. autosummary:: + :toctree: generated/ + + hyp2f1 -- Gauss hypergeometric function 2F1(a, b; c; z). + hyp1f1 -- Confluent hypergeometric function 1F1(a, b; x). + hyperu -- Confluent hypergeometric function U(a, b, x) of the second kind. + hyp0f1 -- Confluent hypergeometric limit function 0F1. + + +Parabolic cylinder functions +---------------------------- + +.. autosummary:: + :toctree: generated/ + + pbdv -- Parabolic cylinder function D. + pbvv -- Parabolic cylinder function V. + pbwa -- Parabolic cylinder function W. + +The following functions do not accept NumPy arrays (they are not +universal functions): + +.. autosummary:: + :toctree: generated/ + + pbdv_seq -- Parabolic cylinder functions Dv(x) and derivatives. + pbvv_seq -- Parabolic cylinder functions Vv(x) and derivatives. + pbdn_seq -- Parabolic cylinder functions Dn(z) and derivatives. + +Mathieu and related functions +----------------------------- + +.. autosummary:: + :toctree: generated/ + + mathieu_a -- Characteristic value of even Mathieu functions. + mathieu_b -- Characteristic value of odd Mathieu functions. + +The following functions do not accept NumPy arrays (they are not +universal functions): + +.. autosummary:: + :toctree: generated/ + + mathieu_even_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions. + mathieu_odd_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions. + +The following return both function and first derivative: + +.. autosummary:: + :toctree: generated/ + + mathieu_cem -- Even Mathieu function and its derivative. + mathieu_sem -- Odd Mathieu function and its derivative. + mathieu_modcem1 -- Even modified Mathieu function of the first kind and its derivative. + mathieu_modcem2 -- Even modified Mathieu function of the second kind and its derivative. + mathieu_modsem1 -- Odd modified Mathieu function of the first kind and its derivative. + mathieu_modsem2 -- Odd modified Mathieu function of the second kind and its derivative. + +Spheroidal wave functions +------------------------- + +.. autosummary:: + :toctree: generated/ + + pro_ang1 -- Prolate spheroidal angular function of the first kind and its derivative. + pro_rad1 -- Prolate spheroidal radial function of the first kind and its derivative. + pro_rad2 -- Prolate spheroidal radial function of the second kind and its derivative. + obl_ang1 -- Oblate spheroidal angular function of the first kind and its derivative. + obl_rad1 -- Oblate spheroidal radial function of the first kind and its derivative. + obl_rad2 -- Oblate spheroidal radial function of the second kind and its derivative. + pro_cv -- Characteristic value of prolate spheroidal function. + obl_cv -- Characteristic value of oblate spheroidal function. + pro_cv_seq -- Characteristic values for prolate spheroidal wave functions. + obl_cv_seq -- Characteristic values for oblate spheroidal wave functions. + +The following functions require pre-computed characteristic value: + +.. autosummary:: + :toctree: generated/ + + pro_ang1_cv -- Prolate spheroidal angular function pro_ang1 for precomputed characteristic value. + pro_rad1_cv -- Prolate spheroidal radial function pro_rad1 for precomputed characteristic value. + pro_rad2_cv -- Prolate spheroidal radial function pro_rad2 for precomputed characteristic value. + obl_ang1_cv -- Oblate spheroidal angular function obl_ang1 for precomputed characteristic value. + obl_rad1_cv -- Oblate spheroidal radial function obl_rad1 for precomputed characteristic value. + obl_rad2_cv -- Oblate spheroidal radial function obl_rad2 for precomputed characteristic value. + +Kelvin functions +---------------- + +.. autosummary:: + :toctree: generated/ + + kelvin -- Kelvin functions as complex numbers. + kelvin_zeros -- Compute nt zeros of all Kelvin functions. + ber -- Kelvin function ber. + bei -- Kelvin function bei + berp -- Derivative of the Kelvin function `ber`. + beip -- Derivative of the Kelvin function `bei`. + ker -- Kelvin function ker. + kei -- Kelvin function ker. + kerp -- Derivative of the Kelvin function ker. + keip -- Derivative of the Kelvin function kei. + +The following functions do not accept NumPy arrays (they are not +universal functions): + +.. autosummary:: + :toctree: generated/ + + ber_zeros -- Compute nt zeros of the Kelvin function ber(x). + bei_zeros -- Compute nt zeros of the Kelvin function bei(x). + berp_zeros -- Compute nt zeros of the Kelvin function ber'(x). + beip_zeros -- Compute nt zeros of the Kelvin function bei'(x). + ker_zeros -- Compute nt zeros of the Kelvin function ker(x). + kei_zeros -- Compute nt zeros of the Kelvin function kei(x). + kerp_zeros -- Compute nt zeros of the Kelvin function ker'(x). + keip_zeros -- Compute nt zeros of the Kelvin function kei'(x). + +Combinatorics +------------- + +.. autosummary:: + :toctree: generated/ + + comb -- The number of combinations of N things taken k at a time. + perm -- Permutations of N things taken k at a time, i.e., k-permutations of N. + stirling2 -- Stirling numbers of the second kind. + +Lambert W and related functions +------------------------------- + +.. autosummary:: + :toctree: generated/ + + lambertw -- Lambert W function. + wrightomega -- Wright Omega function. + +Other special functions +----------------------- + +.. autosummary:: + :toctree: generated/ + + agm -- Arithmetic, Geometric Mean. + bernoulli -- Bernoulli numbers B0..Bn (inclusive). + binom -- Binomial coefficient + diric -- Periodic sinc function, also called the Dirichlet function. + euler -- Euler numbers E0..En (inclusive). + expn -- Exponential integral E_n. + exp1 -- Exponential integral E_1 of complex argument z. + expi -- Exponential integral Ei. + factorial -- The factorial of a number or array of numbers. + factorial2 -- Double factorial. + factorialk -- Multifactorial of n of order k, n(!!...!). + shichi -- Hyperbolic sine and cosine integrals. + sici -- Sine and cosine integrals. + softmax -- Softmax function. + log_softmax -- Logarithm of softmax function. + spence -- Spence's function, also known as the dilogarithm. + zeta -- Riemann zeta function. + zetac -- Riemann zeta function minus 1. + softplus -- Softplus function. + +Convenience functions +--------------------- + +.. autosummary:: + :toctree: generated/ + + cbrt -- Cube root of `x`. + exp10 -- 10**x. + exp2 -- 2**x. + radian -- Convert from degrees to radians. + cosdg -- Cosine of the angle `x` given in degrees. + sindg -- Sine of angle given in degrees. + tandg -- Tangent of angle x given in degrees. + cotdg -- Cotangent of the angle `x` given in degrees. + log1p -- Calculates log(1+x) for use when `x` is near zero. + expm1 -- ``exp(x) - 1`` for use when `x` is near zero. + cosm1 -- ``cos(x) - 1`` for use when `x` is near zero. + powm1 -- ``x**y - 1`` for use when `y` is near zero or `x` is near 1. + round -- Round to nearest integer. + xlogy -- Compute ``x*log(y)`` so that the result is 0 if ``x = 0``. + xlog1py -- Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``. + logsumexp -- Compute the log of the sum of exponentials of input elements. + exprel -- Relative error exponential, (exp(x)-1)/x, for use when `x` is near zero. + sinc -- Return the sinc function. + +""" # noqa: E501 + +import os +import warnings + + +def _load_libsf_error_state(): + """Load libsf_error_state.dll shared library on Windows + + libsf_error_state manages shared state used by + ``scipy.special.seterr`` and ``scipy.special.geterr`` so that these + can work consistently between special functions provided by different + extension modules. This shared library is installed in scipy/special + alongside this __init__.py file. Due to lack of rpath support, Windows + cannot find shared libraries installed within wheels. To circumvent this, + we pre-load ``lib_sf_error_state.dll`` when on Windows. + + The logic for this function was borrowed from the function ``make_init`` + in `scipy/tools/openblas_support.py`: + https://github.com/scipy/scipy/blob/bb92c8014e21052e7dde67a76b28214dd1dcb94a/tools/openblas_support.py#L239-L274 + """ # noqa: E501 + if os.name == "nt": + try: + from ctypes import WinDLL + basedir = os.path.dirname(__file__) + except: # noqa: E722 + pass + else: + dll_path = os.path.join(basedir, "libsf_error_state.dll") + if os.path.exists(dll_path): + WinDLL(dll_path) + + +_load_libsf_error_state() + + +from ._sf_error import SpecialFunctionWarning, SpecialFunctionError + +from . import _ufuncs +from ._ufuncs import * + +# Replace some function definitions from _ufuncs to add Array API support +from ._support_alternative_backends import ( + log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln, + gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy, + chdtr, chdtrc, betainc, betaincc, stdtr) + +from . import _basic +from ._basic import * + +from ._logsumexp import logsumexp, softmax, log_softmax + +from . import _multiufuncs +from ._multiufuncs import * + +from . import _orthogonal +from ._orthogonal import * + +from ._spfun_stats import multigammaln +from ._ellip_harm import ( + ellip_harm, + ellip_harm_2, + ellip_normal +) +from ._lambertw import lambertw +from ._spherical_bessel import ( + spherical_jn, + spherical_yn, + spherical_in, + spherical_kn +) + +# Deprecated namespaces, to be removed in v2.0.0 +from . import add_newdocs, basic, orthogonal, specfun, sf_error, spfun_stats + +# We replace some function definitions from _ufuncs with those from +# _support_alternative_backends above, but those are all listed in _ufuncs.__all__, +# so there is no need to consider _support_alternative_backends.__all__ here. +__all__ = _ufuncs.__all__ + _basic.__all__ + _orthogonal.__all__ + _multiufuncs.__all__ +__all__ += [ + 'SpecialFunctionWarning', + 'SpecialFunctionError', + 'logsumexp', + 'softmax', + 'log_softmax', + 'multigammaln', + 'ellip_harm', + 'ellip_harm_2', + 'ellip_normal', + 'lambertw', + 'spherical_jn', + 'spherical_yn', + 'spherical_in', + 'spherical_kn', +] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester + + +def _get_include(): + """This function is for development purposes only. + + This function could disappear or its behavior could change at any time. + """ + import os + return os.path.dirname(__file__) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0a43ea0d4af22ee31ab0e4382ee3a081e62666d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2430d1c83784008dc1cb1af3f84f39eb32b1f1e3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea9bfa31074dba3212fae752b85f54cf49d80994 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf9f4c08a1b471605c6a985127c0f5d73c54dec2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1e3fb72a94bd4c3874c1142850cf49bfdf3367c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a14a23f5b39e5d450777b786f5670b2bf1d54645 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c45e85c8c52fb3588d8c20ea53695b9c2156eb96 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7d2a1ee9cf22fbff6149b137bf49daec4bdab13 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83f2dc9a19da7411f33a6acf456251b92fe73fe5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f9b500cc086030cacdfad56b8e54250d8b89ee8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..556bb5adb7437c0dd91e5353dea0e414b0653d64 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..811ff8b9d93b76293b64e42b2177252f8c626faf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d896cabb6a796ee27a9274a93cfa7dc4ffaa32 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09ed5bebe44d4990afcac1587ddbe757280b607d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..726f68b0180d70b51cd67fbbc62d653d13d46cb5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9acafdb9209fd034cbe5f025e980c11160deed45 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c359ca20e81c2a58d725d33ca0bbbcd6c822c53 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py new file mode 100644 index 0000000000000000000000000000000000000000..134604c90128a59d48dee66318fa6fd02308f80c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py @@ -0,0 +1,10699 @@ +# Docstrings for generated ufuncs +# +# The syntax is designed to look like the function add_newdoc is being +# called from numpy.lib, but in this file add_newdoc puts the +# docstrings in a dictionary. This dictionary is used in +# _generate_pyx.py to generate the docstrings for the ufuncs in +# scipy.special at the C level when the ufuncs are created at compile +# time. + +docdict: dict[str, str] = {} + + +def get(name): + return docdict.get(name) + + +def add_newdoc(name, doc): + docdict[name] = doc + + +add_newdoc("_sf_error_test_function", + """ + Private function; do not use. + """) + + +add_newdoc("_cosine_cdf", + """ + _cosine_cdf(x) + + Cumulative distribution function (CDF) of the cosine distribution:: + + { 0, x < -pi + cdf(x) = { (pi + x + sin(x))/(2*pi), -pi <= x <= pi + { 1, x > pi + + Parameters + ---------- + x : array_like + `x` must contain real numbers. + + Returns + ------- + scalar or ndarray + The cosine distribution CDF evaluated at `x`. + + """) + +add_newdoc("_cosine_invcdf", + """ + _cosine_invcdf(p) + + Inverse of the cumulative distribution function (CDF) of the cosine + distribution. + + The CDF of the cosine distribution is:: + + cdf(x) = (pi + x + sin(x))/(2*pi) + + This function computes the inverse of cdf(x). + + Parameters + ---------- + p : array_like + `p` must contain real numbers in the interval ``0 <= p <= 1``. + `nan` is returned for values of `p` outside the interval [0, 1]. + + Returns + ------- + scalar or ndarray + The inverse of the cosine distribution CDF evaluated at `p`. + + """) + +add_newdoc("_ellip_harm", + """ + Internal function, use `ellip_harm` instead. + """) + +add_newdoc("_ellip_norm", + """ + Internal function, use `ellip_norm` instead. + """) + +add_newdoc("voigt_profile", + r""" + voigt_profile(x, sigma, gamma, out=None) + + Voigt profile. + + The Voigt profile is a convolution of a 1-D Normal distribution with + standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at + half-maximum ``gamma``. + + If ``sigma = 0``, PDF of Cauchy distribution is returned. + Conversely, if ``gamma = 0``, PDF of Normal distribution is returned. + If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``, + and ``0`` for all other ``x``. + + Parameters + ---------- + x : array_like + Real argument + sigma : array_like + The standard deviation of the Normal distribution part + gamma : array_like + The half-width at half-maximum of the Cauchy distribution part + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + The Voigt profile at the given arguments + + See Also + -------- + wofz : Faddeeva function + + Notes + ----- + It can be expressed in terms of Faddeeva function + + .. math:: V(x; \sigma, \gamma) = \frac{Re[w(z)]}{\sigma\sqrt{2\pi}}, + .. math:: z = \frac{x + i\gamma}{\sqrt{2}\sigma} + + where :math:`w(z)` is the Faddeeva function. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Voigt_profile + + Examples + -------- + Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``. + + >>> from scipy.special import voigt_profile + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> voigt_profile(2, 1., 1.) + 0.09071519942627544 + + Calculate the function at several points by providing a NumPy array + for `x`. + + >>> values = np.array([-2., 0., 5]) + >>> voigt_profile(values, 1., 1.) + array([0.0907152 , 0.20870928, 0.01388492]) + + Plot the function for different parameter sets. + + >>> fig, ax = plt.subplots(figsize=(8, 8)) + >>> x = np.linspace(-10, 10, 500) + >>> parameters_list = [(1.5, 0., "solid"), (1.3, 0.5, "dashed"), + ... (0., 1.8, "dotted"), (1., 1., "dashdot")] + >>> for params in parameters_list: + ... sigma, gamma, linestyle = params + ... voigt = voigt_profile(x, sigma, gamma) + ... ax.plot(x, voigt, label=rf"$\sigma={sigma},\, \gamma={gamma}$", + ... ls=linestyle) + >>> ax.legend() + >>> plt.show() + + Verify visually that the Voigt profile indeed arises as the convolution + of a normal and a Cauchy distribution. + + >>> from scipy.signal import convolve + >>> x, dx = np.linspace(-10, 10, 500, retstep=True) + >>> def gaussian(x, sigma): + ... return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi)) + >>> def cauchy(x, gamma): + ... return gamma/(np.pi * (np.square(x)+gamma**2)) + >>> sigma = 2 + >>> gamma = 1 + >>> gauss_profile = gaussian(x, sigma) + >>> cauchy_profile = cauchy(x, gamma) + >>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode="same") + >>> voigt = voigt_profile(x, sigma, gamma) + >>> fig, ax = plt.subplots(figsize=(8, 8)) + >>> ax.plot(x, gauss_profile, label="Gauss: $G$", c='b') + >>> ax.plot(x, cauchy_profile, label="Cauchy: $C$", c='y', ls="dashed") + >>> xx = 0.5*(x[1:] + x[:-1]) # midpoints + >>> ax.plot(xx, convolved[1:], label="Convolution: $G * C$", ls='dashdot', + ... c='k') + >>> ax.plot(x, voigt, label="Voigt", ls='dotted', c='r') + >>> ax.legend() + >>> plt.show() + """) + +add_newdoc("wrightomega", + r""" + wrightomega(z, out=None) + + Wright Omega function. + + Defined as the solution to + + .. math:: + + \omega + \log(\omega) = z + + where :math:`\log` is the principal branch of the complex logarithm. + + Parameters + ---------- + z : array_like + Points at which to evaluate the Wright Omega function + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + omega : scalar or ndarray + Values of the Wright Omega function + + See Also + -------- + lambertw : The Lambert W function + + Notes + ----- + .. versionadded:: 0.19.0 + + The function can also be defined as + + .. math:: + + \omega(z) = W_{K(z)}(e^z) + + where :math:`K(z) = \lceil (\Im(z) - \pi)/(2\pi) \rceil` is the + unwinding number and :math:`W` is the Lambert W function. + + The implementation here is taken from [1]_. + + References + ---------- + .. [1] Lawrence, Corless, and Jeffrey, "Algorithm 917: Complex + Double-Precision Evaluation of the Wright :math:`\omega` + Function." ACM Transactions on Mathematical Software, + 2012. :doi:`10.1145/2168773.2168779`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import wrightomega, lambertw + + >>> wrightomega([-2, -1, 0, 1, 2]) + array([0.12002824, 0.27846454, 0.56714329, 1. , 1.5571456 ]) + + Complex input: + + >>> wrightomega(3 + 5j) + (1.5804428632097158+3.8213626783287937j) + + Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``: + + >>> w = -5 + 4j + >>> wrightomega(w + np.log(w)) + (-5+4j) + + Verify the connection to ``lambertw``: + + >>> z = 0.5 + 3j + >>> wrightomega(z) + (0.0966015889280649+1.4937828458191993j) + >>> lambertw(np.exp(z)) + (0.09660158892806493+1.4937828458191993j) + + >>> z = 0.5 + 4j + >>> wrightomega(z) + (-0.3362123489037213+2.282986001579032j) + >>> lambertw(np.exp(z), k=1) + (-0.33621234890372115+2.282986001579032j) + """) + + +add_newdoc("agm", + """ + agm(a, b, out=None) + + Compute the arithmetic-geometric mean of `a` and `b`. + + Start with a_0 = a and b_0 = b and iteratively compute:: + + a_{n+1} = (a_n + b_n)/2 + b_{n+1} = sqrt(a_n*b_n) + + a_n and b_n converge to the same limit as n increases; their common + limit is agm(a, b). + + Parameters + ---------- + a, b : array_like + Real values only. If the values are both negative, the result + is negative. If one value is negative and the other is positive, + `nan` is returned. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + The arithmetic-geometric mean of `a` and `b`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import agm + >>> a, b = 24.0, 6.0 + >>> agm(a, b) + 13.458171481725614 + + Compare that result to the iteration: + + >>> while a != b: + ... a, b = (a + b)/2, np.sqrt(a*b) + ... print("a = %19.16f b=%19.16f" % (a, b)) + ... + a = 15.0000000000000000 b=12.0000000000000000 + a = 13.5000000000000000 b=13.4164078649987388 + a = 13.4582039324993694 b=13.4581390309909850 + a = 13.4581714817451772 b=13.4581714817060547 + a = 13.4581714817256159 b=13.4581714817256159 + + When array-like arguments are given, broadcasting applies: + + >>> a = np.array([[1.5], [3], [6]]) # a has shape (3, 1). + >>> b = np.array([6, 12, 24, 48]) # b has shape (4,). + >>> agm(a, b) + array([[ 3.36454287, 5.42363427, 9.05798751, 15.53650756], + [ 4.37037309, 6.72908574, 10.84726853, 18.11597502], + [ 6. , 8.74074619, 13.45817148, 21.69453707]]) + """) + +add_newdoc("airy", + r""" + airy(z, out=None) + + Airy functions and their derivatives. + + Parameters + ---------- + z : array_like + Real or complex argument. + out : tuple of ndarray, optional + Optional output arrays for the function values + + Returns + ------- + Ai, Aip, Bi, Bip : 4-tuple of scalar or ndarray + Airy functions Ai and Bi, and their derivatives Aip and Bip. + + See Also + -------- + airye : exponentially scaled Airy functions. + + Notes + ----- + The Airy functions Ai and Bi are two independent solutions of + + .. math:: y''(x) = x y(x). + + For real `z` in [-10, 10], the computation is carried out by calling + the Cephes [1]_ `airy` routine, which uses power series summation + for small `z` and rational minimax approximations for large `z`. + + Outside this range, the AMOS [2]_ `zairy` and `zbiry` routines are + employed. They are computed using power series for :math:`|z| < 1` and + the following relations to modified Bessel functions for larger `z` + (where :math:`t \equiv 2 z^{3/2}/3`): + + .. math:: + + Ai(z) = \frac{1}{\pi \sqrt{3}} K_{1/3}(t) + + Ai'(z) = -\frac{z}{\pi \sqrt{3}} K_{2/3}(t) + + Bi(z) = \sqrt{\frac{z}{3}} \left(I_{-1/3}(t) + I_{1/3}(t) \right) + + Bi'(z) = \frac{z}{\sqrt{3}} \left(I_{-2/3}(t) + I_{2/3}(t)\right) + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + Compute the Airy functions on the interval [-15, 5]. + + >>> import numpy as np + >>> from scipy import special + >>> x = np.linspace(-15, 5, 201) + >>> ai, aip, bi, bip = special.airy(x) + + Plot Ai(x) and Bi(x). + + >>> import matplotlib.pyplot as plt + >>> plt.plot(x, ai, 'r', label='Ai(x)') + >>> plt.plot(x, bi, 'b--', label='Bi(x)') + >>> plt.ylim(-0.5, 1.0) + >>> plt.grid() + >>> plt.legend(loc='upper left') + >>> plt.show() + + """) + +add_newdoc("airye", + """ + airye(z, out=None) + + Exponentially scaled Airy functions and their derivatives. + + Scaling:: + + eAi = Ai * exp(2.0/3.0*z*sqrt(z)) + eAip = Aip * exp(2.0/3.0*z*sqrt(z)) + eBi = Bi * exp(-abs(2.0/3.0*(z*sqrt(z)).real)) + eBip = Bip * exp(-abs(2.0/3.0*(z*sqrt(z)).real)) + + Parameters + ---------- + z : array_like + Real or complex argument. + out : tuple of ndarray, optional + Optional output arrays for the function values + + Returns + ------- + eAi, eAip, eBi, eBip : 4-tuple of scalar or ndarray + Exponentially scaled Airy functions eAi and eBi, and their derivatives + eAip and eBip + + See Also + -------- + airy + + Notes + ----- + Wrapper for the AMOS [1]_ routines `zairy` and `zbiry`. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + We can compute exponentially scaled Airy functions and their derivatives: + + >>> import numpy as np + >>> from scipy.special import airye + >>> import matplotlib.pyplot as plt + >>> z = np.linspace(0, 50, 500) + >>> eAi, eAip, eBi, eBip = airye(z) + >>> f, ax = plt.subplots(2, 1, sharex=True) + >>> for ind, data in enumerate([[eAi, eAip, ["eAi", "eAip"]], + ... [eBi, eBip, ["eBi", "eBip"]]]): + ... ax[ind].plot(z, data[0], "-r", z, data[1], "-b") + ... ax[ind].legend(data[2]) + ... ax[ind].grid(True) + >>> plt.show() + + We can compute these using usual non-scaled Airy functions by: + + >>> from scipy.special import airy + >>> Ai, Aip, Bi, Bip = airy(z) + >>> np.allclose(eAi, Ai * np.exp(2.0 / 3.0 * z * np.sqrt(z))) + True + >>> np.allclose(eAip, Aip * np.exp(2.0 / 3.0 * z * np.sqrt(z))) + True + >>> np.allclose(eBi, Bi * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z))))) + True + >>> np.allclose(eBip, Bip * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z))))) + True + + Comparing non-scaled and exponentially scaled ones, the usual non-scaled + function quickly underflows for large values, whereas the exponentially + scaled function does not. + + >>> airy(200) + (0.0, 0.0, nan, nan) + >>> airye(200) + (0.07501041684381093, -1.0609012305109042, 0.15003188417418148, 2.1215836725571093) + + """) + +add_newdoc("bdtr", + r""" + bdtr(k, n, p, out=None) + + Binomial distribution cumulative distribution function. + + Sum of the terms 0 through `floor(k)` of the Binomial probability density. + + .. math:: + \mathrm{bdtr}(k, n, p) = + \sum_{j=0}^{\lfloor k \rfloor} {{n}\choose{j}} p^j (1-p)^{n-j} + + Parameters + ---------- + k : array_like + Number of successes (double), rounded down to the nearest integer. + n : array_like + Number of events (int). + p : array_like + Probability of success in a single event (float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + y : scalar or ndarray + Probability of `floor(k)` or fewer successes in `n` independent events with + success probabilities of `p`. + + Notes + ----- + The terms are not summed directly; instead the regularized incomplete beta + function is employed, according to the formula, + + .. math:: + \mathrm{bdtr}(k, n, p) = + I_{1 - p}(n - \lfloor k \rfloor, \lfloor k \rfloor + 1). + + Wrapper for the Cephes [1]_ routine `bdtr`. + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + """) + +add_newdoc("bdtrc", + r""" + bdtrc(k, n, p, out=None) + + Binomial distribution survival function. + + Sum of the terms `floor(k) + 1` through `n` of the binomial probability + density, + + .. math:: + \mathrm{bdtrc}(k, n, p) = + \sum_{j=\lfloor k \rfloor +1}^n {{n}\choose{j}} p^j (1-p)^{n-j} + + Parameters + ---------- + k : array_like + Number of successes (double), rounded down to nearest integer. + n : array_like + Number of events (int) + p : array_like + Probability of success in a single event. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + y : scalar or ndarray + Probability of `floor(k) + 1` or more successes in `n` independent + events with success probabilities of `p`. + + See Also + -------- + bdtr + betainc + + Notes + ----- + The terms are not summed directly; instead the regularized incomplete beta + function is employed, according to the formula, + + .. math:: + \mathrm{bdtrc}(k, n, p) = I_{p}(\lfloor k \rfloor + 1, n - \lfloor k \rfloor). + + Wrapper for the Cephes [1]_ routine `bdtrc`. + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + """) + +add_newdoc("bdtri", + r""" + bdtri(k, n, y, out=None) + + Inverse function to `bdtr` with respect to `p`. + + Finds the event probability `p` such that the sum of the terms 0 through + `k` of the binomial probability density is equal to the given cumulative + probability `y`. + + Parameters + ---------- + k : array_like + Number of successes (float), rounded down to the nearest integer. + n : array_like + Number of events (float) + y : array_like + Cumulative probability (probability of `k` or fewer successes in `n` + events). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + p : scalar or ndarray + The event probability such that `bdtr(\lfloor k \rfloor, n, p) = y`. + + See Also + -------- + bdtr + betaincinv + + Notes + ----- + The computation is carried out using the inverse beta integral function + and the relation,:: + + 1 - p = betaincinv(n - k, k + 1, y). + + Wrapper for the Cephes [1]_ routine `bdtri`. + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + """) + +add_newdoc("bdtrik", + """ + bdtrik(y, n, p, out=None) + + Inverse function to `bdtr` with respect to `k`. + + Finds the number of successes `k` such that the sum of the terms 0 through + `k` of the Binomial probability density for `n` events with probability + `p` is equal to the given cumulative probability `y`. + + Parameters + ---------- + y : array_like + Cumulative probability (probability of `k` or fewer successes in `n` + events). + n : array_like + Number of events (float). + p : array_like + Success probability (float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + k : scalar or ndarray + The number of successes `k` such that `bdtr(k, n, p) = y`. + + See Also + -------- + bdtr + + Notes + ----- + Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the + cumulative incomplete beta distribution. + + Computation of `k` involves a search for a value that produces the desired + value of `y`. The search relies on the monotonicity of `y` with `k`. + + Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`. + + References + ---------- + .. [1] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + .. [2] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + + """) + +add_newdoc("bdtrin", + """ + bdtrin(k, y, p, out=None) + + Inverse function to `bdtr` with respect to `n`. + + Finds the number of events `n` such that the sum of the terms 0 through + `k` of the Binomial probability density for events with probability `p` is + equal to the given cumulative probability `y`. + + Parameters + ---------- + k : array_like + Number of successes (float). + y : array_like + Cumulative probability (probability of `k` or fewer successes in `n` + events). + p : array_like + Success probability (float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + n : scalar or ndarray + The number of events `n` such that `bdtr(k, n, p) = y`. + + See Also + -------- + bdtr + + Notes + ----- + Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the + cumulative incomplete beta distribution. + + Computation of `n` involves a search for a value that produces the desired + value of `y`. The search relies on the monotonicity of `y` with `n`. + + Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`. + + References + ---------- + .. [1] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + .. [2] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + """) + +add_newdoc("btdtria", + r""" + btdtria(p, b, x, out=None) + + Inverse of `betainc` with respect to `a`. + + This is the inverse of the beta cumulative distribution function, `betainc`, + considered as a function of `a`, returning the value of `a` for which + `betainc(a, b, x) = p`, or + + .. math:: + p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt + + Parameters + ---------- + p : array_like + Cumulative probability, in [0, 1]. + b : array_like + Shape parameter (`b` > 0). + x : array_like + The quantile, in [0, 1]. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + a : scalar or ndarray + The value of the shape parameter `a` such that `betainc(a, b, x) = p`. + + See Also + -------- + btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`. + + Notes + ----- + Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`. + + The cumulative distribution function `p` is computed using a routine by + DiDinato and Morris [2]_. Computation of `a` involves a search for a value + that produces the desired value of `p`. The search relies on the + monotonicity of `p` with `a`. + + References + ---------- + .. [1] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + .. [2] DiDinato, A. R. and Morris, A. H., + Algorithm 708: Significant Digit Computation of the Incomplete Beta + Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373. + + """) + +add_newdoc("btdtrib", + r""" + btdtria(a, p, x, out=None) + + Inverse of `betainc` with respect to `b`. + + This is the inverse of the beta cumulative distribution function, `betainc`, + considered as a function of `b`, returning the value of `b` for which + `betainc(a, b, x) = p`, or + + .. math:: + p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt + + Parameters + ---------- + a : array_like + Shape parameter (`a` > 0). + p : array_like + Cumulative probability, in [0, 1]. + x : array_like + The quantile, in [0, 1]. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + b : scalar or ndarray + The value of the shape parameter `b` such that `betainc(a, b, x) = p`. + + See Also + -------- + btdtria : Inverse of the beta cumulative distribution function, with respect to `a`. + + Notes + ----- + Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`. + + The cumulative distribution function `p` is computed using a routine by + DiDinato and Morris [2]_. Computation of `b` involves a search for a value + that produces the desired value of `p`. The search relies on the + monotonicity of `p` with `b`. + + References + ---------- + .. [1] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + .. [2] DiDinato, A. R. and Morris, A. H., + Algorithm 708: Significant Digit Computation of the Incomplete Beta + Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373. + + + """) + +add_newdoc( + "betainc", + r""" + betainc(a, b, x, out=None) + + Regularized incomplete beta function. + + Computes the regularized incomplete beta function, defined as [1]_: + + .. math:: + + I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x + t^{a-1}(1-t)^{b-1}dt, + + for :math:`0 \leq x \leq 1`. + + This function is the cumulative distribution function for the beta + distribution; its range is [0, 1]. + + Parameters + ---------- + a, b : array_like + Positive, real-valued parameters + x : array_like + Real-valued such that :math:`0 \leq x \leq 1`, + the upper limit of integration + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Value of the regularized incomplete beta function + + See Also + -------- + beta : beta function + betaincinv : inverse of the regularized incomplete beta function + betaincc : complement of the regularized incomplete beta function + scipy.stats.beta : beta distribution + + Notes + ----- + The term *regularized* in the name of this function refers to the + scaling of the function by the gamma function terms shown in the + formula. When not qualified as *regularized*, the name *incomplete + beta function* often refers to just the integral expression, + without the gamma terms. One can use the function `beta` from + `scipy.special` to get this "nonregularized" incomplete beta + function by multiplying the result of ``betainc(a, b, x)`` by + ``beta(a, b)``. + + This function wraps the ``ibeta`` routine from the + Boost Math C++ library [2]_. + + References + ---------- + .. [1] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/8.17 + .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + + Let :math:`B(a, b)` be the `beta` function. + + >>> import scipy.special as sc + + The coefficient in terms of `gamma` is equal to + :math:`1/B(a, b)`. Also, when :math:`x=1` + the integral is equal to :math:`B(a, b)`. + Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`. + + >>> sc.betainc(0.2, 3.5, 1.0) + 1.0 + + It satisfies + :math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`, + where :math:`F` is the hypergeometric function `hyp2f1`: + + >>> a, b, x = 1.4, 3.1, 0.5 + >>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b)) + 0.8148904036225295 + >>> sc.betainc(a, b, x) + 0.8148904036225296 + + This functions satisfies the relationship + :math:`I_x(a, b) = 1 - I_{1-x}(b, a)`: + + >>> sc.betainc(2.2, 3.1, 0.4) + 0.49339638807619446 + >>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4) + 0.49339638807619446 + + """) + + +add_newdoc( + "betaincc", + r""" + betaincc(a, b, x, out=None) + + Complement of the regularized incomplete beta function. + + Computes the complement of the regularized incomplete beta function, + defined as [1]_: + + .. math:: + + \bar{I}_x(a, b) = 1 - I_x(a, b) + = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x + t^{a-1}(1-t)^{b-1}dt, + + for :math:`0 \leq x \leq 1`. + + Parameters + ---------- + a, b : array_like + Positive, real-valued parameters + x : array_like + Real-valued such that :math:`0 \leq x \leq 1`, + the upper limit of integration + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Value of the regularized incomplete beta function + + See Also + -------- + betainc : regularized incomplete beta function + betaincinv : inverse of the regularized incomplete beta function + betainccinv : + inverse of the complement of the regularized incomplete beta function + beta : beta function + scipy.stats.beta : beta distribution + + Notes + ----- + .. versionadded:: 1.11.0 + + This function wraps the ``ibetac`` routine from the + Boost Math C++ library [2]_. + + References + ---------- + .. [1] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/8.17 + .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> from scipy.special import betaincc, betainc + + The naive calculation ``1 - betainc(a, b, x)`` loses precision when + the values of ``betainc(a, b, x)`` are close to 1: + + >>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999]) + array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00]) + + By using ``betaincc``, we get the correct values: + + >>> betaincc(0.5, 8, [0.9, 0.99, 0.999]) + array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25]) + + """) + +add_newdoc( + "betaincinv", + r""" + betaincinv(a, b, y, out=None) + + Inverse of the regularized incomplete beta function. + + Computes :math:`x` such that: + + .. math:: + + y = I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} + \int_0^x t^{a-1}(1-t)^{b-1}dt, + + where :math:`I_x` is the normalized incomplete beta function `betainc` + and :math:`\Gamma` is the `gamma` function [1]_. + + Parameters + ---------- + a, b : array_like + Positive, real-valued parameters + y : array_like + Real-valued input + out : ndarray, optional + Optional output array for function values + + Returns + ------- + scalar or ndarray + Value of the inverse of the regularized incomplete beta function + + See Also + -------- + betainc : regularized incomplete beta function + gamma : gamma function + + Notes + ----- + This function wraps the ``ibeta_inv`` routine from the + Boost Math C++ library [2]_. + + References + ---------- + .. [1] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/8.17 + .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> import scipy.special as sc + + This function is the inverse of `betainc` for fixed + values of :math:`a` and :math:`b`. + + >>> a, b = 1.2, 3.1 + >>> y = sc.betainc(a, b, 0.2) + >>> sc.betaincinv(a, b, y) + 0.2 + >>> + >>> a, b = 7.5, 0.4 + >>> x = sc.betaincinv(a, b, 0.5) + >>> sc.betainc(a, b, x) + 0.5 + + """) + + +add_newdoc( + "betainccinv", + r""" + betainccinv(a, b, y, out=None) + + Inverse of the complemented regularized incomplete beta function. + + Computes :math:`x` such that: + + .. math:: + + y = 1 - I_x(a, b) = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} + \int_0^x t^{a-1}(1-t)^{b-1}dt, + + where :math:`I_x` is the normalized incomplete beta function `betainc` + and :math:`\Gamma` is the `gamma` function [1]_. + + Parameters + ---------- + a, b : array_like + Positive, real-valued parameters + y : array_like + Real-valued input + out : ndarray, optional + Optional output array for function values + + Returns + ------- + scalar or ndarray + Value of the inverse of the regularized incomplete beta function + + See Also + -------- + betainc : regularized incomplete beta function + betaincc : complement of the regularized incomplete beta function + + Notes + ----- + .. versionadded:: 1.11.0 + + This function wraps the ``ibetac_inv`` routine from the + Boost Math C++ library [2]_. + + References + ---------- + .. [1] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/8.17 + .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> from scipy.special import betainccinv, betaincc + + This function is the inverse of `betaincc` for fixed + values of :math:`a` and :math:`b`. + + >>> a, b = 1.2, 3.1 + >>> y = betaincc(a, b, 0.2) + >>> betainccinv(a, b, y) + 0.2 + + >>> a, b = 7, 2.5 + >>> x = betainccinv(a, b, 0.875) + >>> betaincc(a, b, x) + 0.875 + + """) + +add_newdoc("boxcox", + """ + boxcox(x, lmbda, out=None) + + Compute the Box-Cox transformation. + + The Box-Cox transformation is:: + + y = (x**lmbda - 1) / lmbda if lmbda != 0 + log(x) if lmbda == 0 + + Returns `nan` if ``x < 0``. + Returns `-inf` if ``x == 0`` and ``lmbda < 0``. + + Parameters + ---------- + x : array_like + Data to be transformed. + lmbda : array_like + Power parameter of the Box-Cox transform. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + y : scalar or ndarray + Transformed data. + + Notes + ----- + + .. versionadded:: 0.14.0 + + Examples + -------- + >>> from scipy.special import boxcox + >>> boxcox([1, 4, 10], 2.5) + array([ 0. , 12.4 , 126.09110641]) + >>> boxcox(2, [0, 1, 2]) + array([ 0.69314718, 1. , 1.5 ]) + """) + +add_newdoc("boxcox1p", + """ + boxcox1p(x, lmbda, out=None) + + Compute the Box-Cox transformation of 1 + `x`. + + The Box-Cox transformation computed by `boxcox1p` is:: + + y = ((1+x)**lmbda - 1) / lmbda if lmbda != 0 + log(1+x) if lmbda == 0 + + Returns `nan` if ``x < -1``. + Returns `-inf` if ``x == -1`` and ``lmbda < 0``. + + Parameters + ---------- + x : array_like + Data to be transformed. + lmbda : array_like + Power parameter of the Box-Cox transform. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + y : scalar or ndarray + Transformed data. + + Notes + ----- + + .. versionadded:: 0.14.0 + + Examples + -------- + >>> from scipy.special import boxcox1p + >>> boxcox1p(1e-4, [0, 0.5, 1]) + array([ 9.99950003e-05, 9.99975001e-05, 1.00000000e-04]) + >>> boxcox1p([0.01, 0.1], 0.25) + array([ 0.00996272, 0.09645476]) + """) + +add_newdoc("inv_boxcox", + """ + inv_boxcox(y, lmbda, out=None) + + Compute the inverse of the Box-Cox transformation. + + Find ``x`` such that:: + + y = (x**lmbda - 1) / lmbda if lmbda != 0 + log(x) if lmbda == 0 + + Parameters + ---------- + y : array_like + Data to be transformed. + lmbda : array_like + Power parameter of the Box-Cox transform. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + x : scalar or ndarray + Transformed data. + + Notes + ----- + + .. versionadded:: 0.16.0 + + Examples + -------- + >>> from scipy.special import boxcox, inv_boxcox + >>> y = boxcox([1, 4, 10], 2.5) + >>> inv_boxcox(y, 2.5) + array([1., 4., 10.]) + """) + +add_newdoc("inv_boxcox1p", + """ + inv_boxcox1p(y, lmbda, out=None) + + Compute the inverse of the Box-Cox transformation. + + Find ``x`` such that:: + + y = ((1+x)**lmbda - 1) / lmbda if lmbda != 0 + log(1+x) if lmbda == 0 + + Parameters + ---------- + y : array_like + Data to be transformed. + lmbda : array_like + Power parameter of the Box-Cox transform. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + x : scalar or ndarray + Transformed data. + + Notes + ----- + + .. versionadded:: 0.16.0 + + Examples + -------- + >>> from scipy.special import boxcox1p, inv_boxcox1p + >>> y = boxcox1p([1, 4, 10], 2.5) + >>> inv_boxcox1p(y, 2.5) + array([1., 4., 10.]) + """) + +add_newdoc("chdtr", + r""" + chdtr(v, x, out=None) + + Chi square cumulative distribution function. + + Returns the area under the left tail (from 0 to `x`) of the Chi + square probability density function with `v` degrees of freedom: + + .. math:: + + \frac{1}{2^{v/2} \Gamma(v/2)} \int_0^x t^{v/2 - 1} e^{-t/2} dt + + Here :math:`\Gamma` is the Gamma function; see `gamma`. This + integral can be expressed in terms of the regularized lower + incomplete gamma function `gammainc` as + ``gammainc(v / 2, x / 2)``. [1]_ + + Parameters + ---------- + v : array_like + Degrees of freedom. + x : array_like + Upper bound of the integral. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + Values of the cumulative distribution function. + + See Also + -------- + chdtrc, chdtri, chdtriv, gammainc + + References + ---------- + .. [1] Chi-Square distribution, + https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It can be expressed in terms of the regularized lower incomplete + gamma function. + + >>> v = 1 + >>> x = np.arange(4) + >>> sc.chdtr(v, x) + array([0. , 0.68268949, 0.84270079, 0.91673548]) + >>> sc.gammainc(v / 2, x / 2) + array([0. , 0.68268949, 0.84270079, 0.91673548]) + + """) + +add_newdoc("chdtrc", + r""" + chdtrc(v, x, out=None) + + Chi square survival function. + + Returns the area under the right hand tail (from `x` to infinity) + of the Chi square probability density function with `v` degrees of + freedom: + + .. math:: + + \frac{1}{2^{v/2} \Gamma(v/2)} \int_x^\infty t^{v/2 - 1} e^{-t/2} dt + + Here :math:`\Gamma` is the Gamma function; see `gamma`. This + integral can be expressed in terms of the regularized upper + incomplete gamma function `gammaincc` as + ``gammaincc(v / 2, x / 2)``. [1]_ + + Parameters + ---------- + v : array_like + Degrees of freedom. + x : array_like + Lower bound of the integral. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + Values of the survival function. + + See Also + -------- + chdtr, chdtri, chdtriv, gammaincc + + References + ---------- + .. [1] Chi-Square distribution, + https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It can be expressed in terms of the regularized upper incomplete + gamma function. + + >>> v = 1 + >>> x = np.arange(4) + >>> sc.chdtrc(v, x) + array([1. , 0.31731051, 0.15729921, 0.08326452]) + >>> sc.gammaincc(v / 2, x / 2) + array([1. , 0.31731051, 0.15729921, 0.08326452]) + + """) + +add_newdoc("chdtri", + """ + chdtri(v, p, out=None) + + Inverse to `chdtrc` with respect to `x`. + + Returns `x` such that ``chdtrc(v, x) == p``. + + Parameters + ---------- + v : array_like + Degrees of freedom. + p : array_like + Probability. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + x : scalar or ndarray + Value so that the probability a Chi square random variable + with `v` degrees of freedom is greater than `x` equals `p`. + + See Also + -------- + chdtrc, chdtr, chdtriv + + References + ---------- + .. [1] Chi-Square distribution, + https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm + + Examples + -------- + >>> import scipy.special as sc + + It inverts `chdtrc`. + + >>> v, p = 1, 0.3 + >>> sc.chdtrc(v, sc.chdtri(v, p)) + 0.3 + >>> x = 1 + >>> sc.chdtri(v, sc.chdtrc(v, x)) + 1.0 + + """) + +add_newdoc("chdtriv", + """ + chdtriv(p, x, out=None) + + Inverse to `chdtr` with respect to `v`. + + Returns `v` such that ``chdtr(v, x) == p``. + + Parameters + ---------- + p : array_like + Probability that the Chi square random variable is less than + or equal to `x`. + x : array_like + Nonnegative input. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + Degrees of freedom. + + See Also + -------- + chdtr, chdtrc, chdtri + + References + ---------- + .. [1] Chi-Square distribution, + https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm + + Examples + -------- + >>> import scipy.special as sc + + It inverts `chdtr`. + + >>> p, x = 0.5, 1 + >>> sc.chdtr(sc.chdtriv(p, x), x) + 0.5000000000202172 + >>> v = 1 + >>> sc.chdtriv(sc.chdtr(v, x), v) + 1.0000000000000013 + + """) + +add_newdoc("chndtr", + r""" + chndtr(x, df, nc, out=None) + + Non-central chi square cumulative distribution function + + The cumulative distribution function is given by: + + .. math:: + + P(\chi^{\prime 2} \vert \nu, \lambda) =\sum_{j=0}^{\infty} + e^{-\lambda /2} + \frac{(\lambda /2)^j}{j!} P(\chi^{\prime 2} \vert \nu + 2j), + + where :math:`\nu > 0` is the degrees of freedom (``df``) and + :math:`\lambda \geq 0` is the non-centrality parameter (``nc``). + + Parameters + ---------- + x : array_like + Upper bound of the integral; must satisfy ``x >= 0`` + df : array_like + Degrees of freedom; must satisfy ``df > 0`` + nc : array_like + Non-centrality parameter; must satisfy ``nc >= 0`` + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + x : scalar or ndarray + Value of the non-central chi square cumulative distribution function. + + See Also + -------- + chndtrix, chndtridf, chndtrinc + + """) + +add_newdoc("chndtrix", + """ + chndtrix(p, df, nc, out=None) + + Inverse to `chndtr` vs `x` + + Calculated using a search to find a value for `x` that produces the + desired value of `p`. + + Parameters + ---------- + p : array_like + Probability; must satisfy ``0 <= p < 1`` + df : array_like + Degrees of freedom; must satisfy ``df > 0`` + nc : array_like + Non-centrality parameter; must satisfy ``nc >= 0`` + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + x : scalar or ndarray + Value so that the probability a non-central Chi square random variable + with `df` degrees of freedom and non-centrality, `nc`, is greater than + `x` equals `p`. + + See Also + -------- + chndtr, chndtridf, chndtrinc + + """) + +add_newdoc("chndtridf", + """ + chndtridf(x, p, nc, out=None) + + Inverse to `chndtr` vs `df` + + Calculated using a search to find a value for `df` that produces the + desired value of `p`. + + Parameters + ---------- + x : array_like + Upper bound of the integral; must satisfy ``x >= 0`` + p : array_like + Probability; must satisfy ``0 <= p < 1`` + nc : array_like + Non-centrality parameter; must satisfy ``nc >= 0`` + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + df : scalar or ndarray + Degrees of freedom + + See Also + -------- + chndtr, chndtrix, chndtrinc + + """) + +add_newdoc("chndtrinc", + """ + chndtrinc(x, df, p, out=None) + + Inverse to `chndtr` vs `nc` + + Calculated using a search to find a value for `df` that produces the + desired value of `p`. + + Parameters + ---------- + x : array_like + Upper bound of the integral; must satisfy ``x >= 0`` + df : array_like + Degrees of freedom; must satisfy ``df > 0`` + p : array_like + Probability; must satisfy ``0 <= p < 1`` + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + nc : scalar or ndarray + Non-centrality + + See Also + -------- + chndtr, chndtrix, chndtrinc + + """) + +add_newdoc("dawsn", + """ + dawsn(x, out=None) + + Dawson's integral. + + Computes:: + + exp(-x**2) * integral(exp(t**2), t=0..x). + + Parameters + ---------- + x : array_like + Function parameter. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + y : scalar or ndarray + Value of the integral. + + See Also + -------- + wofz, erf, erfc, erfcx, erfi + + References + ---------- + .. [1] Steven G. Johnson, Faddeeva W function implementation. + http://ab-initio.mit.edu/Faddeeva + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-15, 15, num=1000) + >>> plt.plot(x, special.dawsn(x)) + >>> plt.xlabel('$x$') + >>> plt.ylabel('$dawsn(x)$') + >>> plt.show() + + """) + +add_newdoc( + "elliprc", + r""" + elliprc(x, y, out=None) + + Degenerate symmetric elliptic integral. + + The function RC is defined as [1]_ + + .. math:: + + R_{\mathrm{C}}(x, y) = + \frac{1}{2} \int_0^{+\infty} (t + x)^{-1/2} (t + y)^{-1} dt + = R_{\mathrm{F}}(x, y, y) + + Parameters + ---------- + x, y : array_like + Real or complex input parameters. `x` can be any number in the + complex plane cut along the negative real axis. `y` must be non-zero. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + R : scalar or ndarray + Value of the integral. If `y` is real and negative, the Cauchy + principal value is returned. If both of `x` and `y` are real, the + return value is real. Otherwise, the return value is complex. + + See Also + -------- + elliprf : Completely-symmetric elliptic integral of the first kind. + elliprd : Symmetric elliptic integral of the second kind. + elliprg : Completely-symmetric elliptic integral of the second kind. + elliprj : Symmetric elliptic integral of the third kind. + + Notes + ----- + RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) == + elliprf(x, y, y)``. It is an elementary function rather than an elliptic + integral. + + The code implements Carlson's algorithm based on the duplication theorems + and series expansion up to the 7th order. [2]_ + + .. versionadded:: 1.8.0 + + References + ---------- + .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical + Functions," NIST, US Dept. of Commerce. + https://dlmf.nist.gov/19.16.E6 + .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic + integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995. + https://arxiv.org/abs/math/9409227 + https://doi.org/10.1007/BF02198293 + + Examples + -------- + Basic homogeneity property: + + >>> import numpy as np + >>> from scipy.special import elliprc + + >>> x = 1.2 + 3.4j + >>> y = 5. + >>> scale = 0.3 + 0.4j + >>> elliprc(scale*x, scale*y) + (0.5484493976710874-0.4169557678995833j) + + >>> elliprc(x, y)/np.sqrt(scale) + (0.5484493976710874-0.41695576789958333j) + + When the two arguments coincide, the integral is particularly + simple: + + >>> x = 1.2 + 3.4j + >>> elliprc(x, x) + (0.4299173120614631-0.3041729818745595j) + + >>> 1/np.sqrt(x) + (0.4299173120614631-0.30417298187455954j) + + Another simple case: the first argument vanishes: + + >>> y = 1.2 + 3.4j + >>> elliprc(0, y) + (0.6753125346116815-0.47779380263880866j) + + >>> np.pi/2/np.sqrt(y) + (0.6753125346116815-0.4777938026388088j) + + When `x` and `y` are both positive, we can express + :math:`R_C(x,y)` in terms of more elementary functions. For the + case :math:`0 \le x < y`, + + >>> x = 3.2 + >>> y = 6. + >>> elliprc(x, y) + 0.44942991498453444 + + >>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x) + 0.44942991498453433 + + And for the case :math:`0 \le y < x`, + + >>> x = 6. + >>> y = 3.2 + >>> elliprc(x,y) + 0.4989837501576147 + + >>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y) + 0.49898375015761476 + + """) + +add_newdoc( + "elliprd", + r""" + elliprd(x, y, z, out=None) + + Symmetric elliptic integral of the second kind. + + The function RD is defined as [1]_ + + .. math:: + + R_{\mathrm{D}}(x, y, z) = + \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2} + dt + + Parameters + ---------- + x, y, z : array_like + Real or complex input parameters. `x` or `y` can be any number in the + complex plane cut along the negative real axis, but at most one of them + can be zero, while `z` must be non-zero. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + R : scalar or ndarray + Value of the integral. If all of `x`, `y`, and `z` are real, the + return value is real. Otherwise, the return value is complex. + + See Also + -------- + elliprc : Degenerate symmetric elliptic integral. + elliprf : Completely-symmetric elliptic integral of the first kind. + elliprg : Completely-symmetric elliptic integral of the second kind. + elliprj : Symmetric elliptic integral of the third kind. + + Notes + ----- + RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) == + elliprj(x, y, z, z)``. + + The code implements Carlson's algorithm based on the duplication theorems + and series expansion up to the 7th order. [2]_ + + .. versionadded:: 1.8.0 + + References + ---------- + .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical + Functions," NIST, US Dept. of Commerce. + https://dlmf.nist.gov/19.16.E5 + .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic + integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995. + https://arxiv.org/abs/math/9409227 + https://doi.org/10.1007/BF02198293 + + Examples + -------- + Basic homogeneity property: + + >>> import numpy as np + >>> from scipy.special import elliprd + + >>> x = 1.2 + 3.4j + >>> y = 5. + >>> z = 6. + >>> scale = 0.3 + 0.4j + >>> elliprd(scale*x, scale*y, scale*z) + (-0.03703043835680379-0.24500934665683802j) + + >>> elliprd(x, y, z)*np.power(scale, -1.5) + (-0.0370304383568038-0.24500934665683805j) + + All three arguments coincide: + + >>> x = 1.2 + 3.4j + >>> elliprd(x, x, x) + (-0.03986825876151896-0.14051741840449586j) + + >>> np.power(x, -1.5) + (-0.03986825876151894-0.14051741840449583j) + + The so-called "second lemniscate constant": + + >>> elliprd(0, 2, 1)/3 + 0.5990701173677961 + + >>> from scipy.special import gamma + >>> gamma(0.75)**2/np.sqrt(2*np.pi) + 0.5990701173677959 + + """) + +add_newdoc( + "elliprf", + r""" + elliprf(x, y, z, out=None) + + Completely-symmetric elliptic integral of the first kind. + + The function RF is defined as [1]_ + + .. math:: + + R_{\mathrm{F}}(x, y, z) = + \frac{1}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt + + Parameters + ---------- + x, y, z : array_like + Real or complex input parameters. `x`, `y`, or `z` can be any number in + the complex plane cut along the negative real axis, but at most one of + them can be zero. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + R : scalar or ndarray + Value of the integral. If all of `x`, `y`, and `z` are real, the return + value is real. Otherwise, the return value is complex. + + See Also + -------- + elliprc : Degenerate symmetric integral. + elliprd : Symmetric elliptic integral of the second kind. + elliprg : Completely-symmetric elliptic integral of the second kind. + elliprj : Symmetric elliptic integral of the third kind. + + Notes + ----- + The code implements Carlson's algorithm based on the duplication theorems + and series expansion up to the 7th order (cf.: + https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete + integral. [2]_ + + .. versionadded:: 1.8.0 + + References + ---------- + .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical + Functions," NIST, US Dept. of Commerce. + https://dlmf.nist.gov/19.16.E1 + .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic + integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995. + https://arxiv.org/abs/math/9409227 + https://doi.org/10.1007/BF02198293 + + Examples + -------- + Basic homogeneity property: + + >>> import numpy as np + >>> from scipy.special import elliprf + + >>> x = 1.2 + 3.4j + >>> y = 5. + >>> z = 6. + >>> scale = 0.3 + 0.4j + >>> elliprf(scale*x, scale*y, scale*z) + (0.5328051227278146-0.4008623567957094j) + + >>> elliprf(x, y, z)/np.sqrt(scale) + (0.5328051227278147-0.4008623567957095j) + + All three arguments coincide: + + >>> x = 1.2 + 3.4j + >>> elliprf(x, x, x) + (0.42991731206146316-0.30417298187455954j) + + >>> 1/np.sqrt(x) + (0.4299173120614631-0.30417298187455954j) + + The so-called "first lemniscate constant": + + >>> elliprf(0, 1, 2) + 1.3110287771460598 + + >>> from scipy.special import gamma + >>> gamma(0.25)**2/(4*np.sqrt(2*np.pi)) + 1.3110287771460598 + + """) + +add_newdoc( + "elliprg", + r""" + elliprg(x, y, z, out=None) + + Completely-symmetric elliptic integral of the second kind. + + The function RG is defined as [1]_ + + .. math:: + + R_{\mathrm{G}}(x, y, z) = + \frac{1}{4} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2} + \left(\frac{x}{t + x} + \frac{y}{t + y} + \frac{z}{t + z}\right) t + dt + + Parameters + ---------- + x, y, z : array_like + Real or complex input parameters. `x`, `y`, or `z` can be any number in + the complex plane cut along the negative real axis. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + R : scalar or ndarray + Value of the integral. If all of `x`, `y`, and `z` are real, the return + value is real. Otherwise, the return value is complex. + + See Also + -------- + elliprc : Degenerate symmetric integral. + elliprd : Symmetric elliptic integral of the second kind. + elliprf : Completely-symmetric elliptic integral of the first kind. + elliprj : Symmetric elliptic integral of the third kind. + + Notes + ----- + The implementation uses the relation [1]_ + + .. math:: + + 2 R_{\mathrm{G}}(x, y, z) = + z R_{\mathrm{F}}(x, y, z) - + \frac{1}{3} (x - z) (y - z) R_{\mathrm{D}}(x, y, z) + + \sqrt{\frac{x y}{z}} + + and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can + be chosen as the pivot. When one of the arguments is close to zero, the AGM + method is applied instead. Other special cases are computed following Ref. + [2]_ + + .. versionadded:: 1.8.0 + + References + ---------- + .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic + integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995. + https://arxiv.org/abs/math/9409227 + https://doi.org/10.1007/BF02198293 + .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical + Functions," NIST, US Dept. of Commerce. + https://dlmf.nist.gov/19.16.E1 + https://dlmf.nist.gov/19.20.ii + + Examples + -------- + Basic homogeneity property: + + >>> import numpy as np + >>> from scipy.special import elliprg + + >>> x = 1.2 + 3.4j + >>> y = 5. + >>> z = 6. + >>> scale = 0.3 + 0.4j + >>> elliprg(scale*x, scale*y, scale*z) + (1.195936862005246+0.8470988320464167j) + + >>> elliprg(x, y, z)*np.sqrt(scale) + (1.195936862005246+0.8470988320464165j) + + Simplifications: + + >>> elliprg(0, y, y) + 1.756203682760182 + + >>> 0.25*np.pi*np.sqrt(y) + 1.7562036827601817 + + >>> elliprg(0, 0, z) + 1.224744871391589 + + >>> 0.5*np.sqrt(z) + 1.224744871391589 + + The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and + ``c`` is given by + + .. math:: + + S = 4 \pi a b c R_{\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2). + + >>> def ellipsoid_area(a, b, c): + ... r = 4.0 * np.pi * a * b * c + ... return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c)) + >>> print(ellipsoid_area(1, 3, 5)) + 108.62688289491807 + """) + +add_newdoc( + "elliprj", + r""" + elliprj(x, y, z, p, out=None) + + Symmetric elliptic integral of the third kind. + + The function RJ is defined as [1]_ + + .. math:: + + R_{\mathrm{J}}(x, y, z, p) = + \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2} + (t + p)^{-1} dt + + .. warning:: + This function should be considered experimental when the inputs are + unbalanced. Check correctness with another independent implementation. + + Parameters + ---------- + x, y, z, p : array_like + Real or complex input parameters. `x`, `y`, or `z` are numbers in + the complex plane cut along the negative real axis (subject to further + constraints, see Notes), and at most one of them can be zero. `p` must + be non-zero. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + R : scalar or ndarray + Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the + return value is real. Otherwise, the return value is complex. + + If `p` is real and negative, while `x`, `y`, and `z` are real, + non-negative, and at most one of them is zero, the Cauchy principal + value is returned. [1]_ [2]_ + + See Also + -------- + elliprc : Degenerate symmetric integral. + elliprd : Symmetric elliptic integral of the second kind. + elliprf : Completely-symmetric elliptic integral of the first kind. + elliprg : Completely-symmetric elliptic integral of the second kind. + + Notes + ----- + The code implements Carlson's algorithm based on the duplication theorems + and series expansion up to the 7th order. [3]_ The algorithm is slightly + different from its earlier incarnation as it appears in [1]_, in that the + call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in + the inner loop. Asymptotic approximations are used where arguments differ + widely in the order of magnitude. [5]_ + + The input values are subject to certain sufficient but not necessary + constraints when input arguments are complex. Notably, ``x``, ``y``, and + ``z`` must have non-negative real parts, unless two of them are + non-negative and complex-conjugates to each other while the other is a real + non-negative number. [1]_ If the inputs do not satisfy the sufficient + condition described in Ref. [1]_ they are rejected outright with the output + set to NaN. + + In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the + function ``elliprd`` should be preferred because of its less restrictive + domain. + + .. versionadded:: 1.8.0 + + References + ---------- + .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic + integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995. + https://arxiv.org/abs/math/9409227 + https://doi.org/10.1007/BF02198293 + .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical + Functions," NIST, US Dept. of Commerce. + https://dlmf.nist.gov/19.20.iii + .. [3] B. C. Carlson, J. FitzSimmons, "Reduction Theorems for Elliptic + Integrands with the Square Root of Two Quadratic Factors," J. + Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000. + https://doi.org/10.1016/S0377-0427(00)00282-X + .. [4] F. Johansson, "Numerical Evaluation of Elliptic Functions, Elliptic + Integrals and Modular Forms," in J. Blumlein, C. Schneider, P. + Paule, eds., "Elliptic Integrals, Elliptic Functions and Modular + Forms in Quantum Field Theory," pp. 269-293, 2019 (Cham, + Switzerland: Springer Nature Switzerland) + https://arxiv.org/abs/1806.06725 + https://doi.org/10.1007/978-3-030-04480-0 + .. [5] B. C. Carlson, J. L. Gustafson, "Asymptotic Approximations for + Symmetric Elliptic Integrals," SIAM J. Math. Anls., vol. 25, no. 2, + pp. 288-303, 1994. + https://arxiv.org/abs/math/9310223 + https://doi.org/10.1137/S0036141092228477 + + Examples + -------- + Basic homogeneity property: + + >>> import numpy as np + >>> from scipy.special import elliprj + + >>> x = 1.2 + 3.4j + >>> y = 5. + >>> z = 6. + >>> p = 7. + >>> scale = 0.3 - 0.4j + >>> elliprj(scale*x, scale*y, scale*z, scale*p) + (0.10834905565679157+0.19694950747103812j) + + >>> elliprj(x, y, z, p)*np.power(scale, -1.5) + (0.10834905565679556+0.19694950747103854j) + + Reduction to simpler elliptic integral: + + >>> elliprj(x, y, z, z) + (0.08288462362195129-0.028376809745123258j) + + >>> from scipy.special import elliprd + >>> elliprd(x, y, z) + (0.08288462362195136-0.028376809745123296j) + + All arguments coincide: + + >>> elliprj(x, x, x, x) + (-0.03986825876151896-0.14051741840449586j) + + >>> np.power(x, -1.5) + (-0.03986825876151894-0.14051741840449583j) + + """) + +add_newdoc("entr", + r""" + entr(x, out=None) + + Elementwise function for computing entropy. + + .. math:: \text{entr}(x) = \begin{cases} - x \log(x) & x > 0 \\ 0 & x = 0 + \\ -\infty & \text{otherwise} \end{cases} + + Parameters + ---------- + x : ndarray + Input array. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + res : scalar or ndarray + The value of the elementwise entropy function at the given points `x`. + + See Also + -------- + kl_div, rel_entr, scipy.stats.entropy + + Notes + ----- + .. versionadded:: 0.15.0 + + This function is concave. + + The origin of this function is in convex programming; see [1]_. + Given a probability distribution :math:`p_1, \ldots, p_n`, + the definition of entropy in the context of *information theory* is + + .. math:: + + \sum_{i = 1}^n \mathrm{entr}(p_i). + + To compute the latter quantity, use `scipy.stats.entropy`. + + References + ---------- + .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*. + Cambridge University Press, 2004. + :doi:`https://doi.org/10.1017/CBO9780511804441` + + """) + +add_newdoc("erf", + """ + erf(z, out=None) + + Returns the error function of complex argument. + + It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``. + + Parameters + ---------- + x : ndarray + Input array. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + res : scalar or ndarray + The values of the error function at the given points `x`. + + See Also + -------- + erfc, erfinv, erfcinv, wofz, erfcx, erfi + + Notes + ----- + The cumulative of the unit normal distribution is given by + ``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Error_function + .. [2] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, + 1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm + .. [3] Steven G. Johnson, Faddeeva W function implementation. + http://ab-initio.mit.edu/Faddeeva + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-3, 3) + >>> plt.plot(x, special.erf(x)) + >>> plt.xlabel('$x$') + >>> plt.ylabel('$erf(x)$') + >>> plt.show() + + """) + +add_newdoc("erfc", + """ + erfc(x, out=None) + + Complementary error function, ``1 - erf(x)``. + + Parameters + ---------- + x : array_like + Real or complex valued argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the complementary error function + + See Also + -------- + erf, erfi, erfcx, dawsn, wofz + + References + ---------- + .. [1] Steven G. Johnson, Faddeeva W function implementation. + http://ab-initio.mit.edu/Faddeeva + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-3, 3) + >>> plt.plot(x, special.erfc(x)) + >>> plt.xlabel('$x$') + >>> plt.ylabel('$erfc(x)$') + >>> plt.show() + + """) + +add_newdoc("erfi", + """ + erfi(z, out=None) + + Imaginary error function, ``-i erf(i z)``. + + Parameters + ---------- + z : array_like + Real or complex valued argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the imaginary error function + + See Also + -------- + erf, erfc, erfcx, dawsn, wofz + + Notes + ----- + + .. versionadded:: 0.12.0 + + References + ---------- + .. [1] Steven G. Johnson, Faddeeva W function implementation. + http://ab-initio.mit.edu/Faddeeva + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-3, 3) + >>> plt.plot(x, special.erfi(x)) + >>> plt.xlabel('$x$') + >>> plt.ylabel('$erfi(x)$') + >>> plt.show() + + """) + +add_newdoc("erfcx", + """ + erfcx(x, out=None) + + Scaled complementary error function, ``exp(x**2) * erfc(x)``. + + Parameters + ---------- + x : array_like + Real or complex valued argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the scaled complementary error function + + + See Also + -------- + erf, erfc, erfi, dawsn, wofz + + Notes + ----- + + .. versionadded:: 0.12.0 + + References + ---------- + .. [1] Steven G. Johnson, Faddeeva W function implementation. + http://ab-initio.mit.edu/Faddeeva + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-3, 3) + >>> plt.plot(x, special.erfcx(x)) + >>> plt.xlabel('$x$') + >>> plt.ylabel('$erfcx(x)$') + >>> plt.show() + + """) + +add_newdoc( + "erfinv", + """ + erfinv(y, out=None) + + Inverse of the error function. + + Computes the inverse of the error function. + + In the complex domain, there is no unique complex number w satisfying + erf(w)=z. This indicates a true inverse function would be multivalued. + When the domain restricts to the real, -1 < x < 1, there is a unique real + number satisfying erf(erfinv(x)) = x. + + Parameters + ---------- + y : ndarray + Argument at which to evaluate. Domain: [-1, 1] + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + erfinv : scalar or ndarray + The inverse of erf of y, element-wise + + See Also + -------- + erf : Error function of a complex argument + erfc : Complementary error function, ``1 - erf(x)`` + erfcinv : Inverse of the complementary error function + + Notes + ----- + This function wraps the ``erf_inv`` routine from the + Boost Math C++ library [1]_. + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import erfinv, erf + + >>> erfinv(0.5) + 0.4769362762044699 + + >>> y = np.linspace(-1.0, 1.0, num=9) + >>> x = erfinv(y) + >>> x + array([ -inf, -0.81341985, -0.47693628, -0.22531206, 0. , + 0.22531206, 0.47693628, 0.81341985, inf]) + + Verify that ``erf(erfinv(y))`` is ``y``. + + >>> erf(x) + array([-1. , -0.75, -0.5 , -0.25, 0. , 0.25, 0.5 , 0.75, 1. ]) + + Plot the function: + + >>> y = np.linspace(-1, 1, 200) + >>> fig, ax = plt.subplots() + >>> ax.plot(y, erfinv(y)) + >>> ax.grid(True) + >>> ax.set_xlabel('y') + >>> ax.set_title('erfinv(y)') + >>> plt.show() + + """) + +add_newdoc( + "erfcinv", + """ + erfcinv(y, out=None) + + Inverse of the complementary error function. + + Computes the inverse of the complementary error function. + + In the complex domain, there is no unique complex number w satisfying + erfc(w)=z. This indicates a true inverse function would be multivalued. + When the domain restricts to the real, 0 < x < 2, there is a unique real + number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)). + + It is related to inverse of the error function by erfcinv(1-x) = erfinv(x) + + Parameters + ---------- + y : ndarray + Argument at which to evaluate. Domain: [0, 2] + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + erfcinv : scalar or ndarray + The inverse of erfc of y, element-wise + + See Also + -------- + erf : Error function of a complex argument + erfc : Complementary error function, ``1 - erf(x)`` + erfinv : Inverse of the error function + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import erfcinv + + >>> erfcinv(0.5) + 0.4769362762044699 + + >>> y = np.linspace(0.0, 2.0, num=11) + >>> erfcinv(y) + array([ inf, 0.9061938 , 0.59511608, 0.37080716, 0.17914345, + -0. , -0.17914345, -0.37080716, -0.59511608, -0.9061938 , + -inf]) + + Plot the function: + + >>> y = np.linspace(0, 2, 200) + >>> fig, ax = plt.subplots() + >>> ax.plot(y, erfcinv(y)) + >>> ax.grid(True) + >>> ax.set_xlabel('y') + >>> ax.set_title('erfcinv(y)') + >>> plt.show() + + """) + +add_newdoc("eval_jacobi", + r""" + eval_jacobi(n, alpha, beta, x, out=None) + + Evaluate Jacobi polynomial at a point. + + The Jacobi polynomials can be defined via the Gauss hypergeometric + function :math:`{}_2F_1` as + + .. math:: + + P_n^{(\alpha, \beta)}(x) = \frac{(\alpha + 1)_n}{\Gamma(n + 1)} + {}_2F_1(-n, 1 + \alpha + \beta + n; \alpha + 1; (1 - z)/2) + + where :math:`(\cdot)_n` is the Pochhammer symbol; see `poch`. When + :math:`n` is an integer the result is a polynomial of degree + :math:`n`. See 22.5.42 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer the result is + determined via the relation to the Gauss hypergeometric + function. + alpha : array_like + Parameter + beta : array_like + Parameter + x : array_like + Points at which to evaluate the polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + P : scalar or ndarray + Values of the Jacobi polynomial + + See Also + -------- + roots_jacobi : roots and quadrature weights of Jacobi polynomials + jacobi : Jacobi polynomial object + hyp2f1 : Gauss hypergeometric function + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_sh_jacobi", + r""" + eval_sh_jacobi(n, p, q, x, out=None) + + Evaluate shifted Jacobi polynomial at a point. + + Defined by + + .. math:: + + G_n^{(p, q)}(x) + = \binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1), + + where :math:`P_n^{(\cdot, \cdot)}` is the n-th Jacobi + polynomial. See 22.5.2 in [AS]_ for details. + + Parameters + ---------- + n : int + Degree of the polynomial. If not an integer, the result is + determined via the relation to `binom` and `eval_jacobi`. + p : float + Parameter + q : float + Parameter + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + G : scalar or ndarray + Values of the shifted Jacobi polynomial. + + See Also + -------- + roots_sh_jacobi : roots and quadrature weights of shifted Jacobi + polynomials + sh_jacobi : shifted Jacobi polynomial object + eval_jacobi : evaluate Jacobi polynomials + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_gegenbauer", + r""" + eval_gegenbauer(n, alpha, x, out=None) + + Evaluate Gegenbauer polynomial at a point. + + The Gegenbauer polynomials can be defined via the Gauss + hypergeometric function :math:`{}_2F_1` as + + .. math:: + + C_n^{(\alpha)} = \frac{(2\alpha)_n}{\Gamma(n + 1)} + {}_2F_1(-n, 2\alpha + n; \alpha + 1/2; (1 - z)/2). + + When :math:`n` is an integer the result is a polynomial of degree + :math:`n`. See 22.5.46 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to the Gauss hypergeometric + function. + alpha : array_like + Parameter + x : array_like + Points at which to evaluate the Gegenbauer polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + C : scalar or ndarray + Values of the Gegenbauer polynomial + + See Also + -------- + roots_gegenbauer : roots and quadrature weights of Gegenbauer + polynomials + gegenbauer : Gegenbauer polynomial object + hyp2f1 : Gauss hypergeometric function + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_chebyt", + r""" + eval_chebyt(n, x, out=None) + + Evaluate Chebyshev polynomial of the first kind at a point. + + The Chebyshev polynomials of the first kind can be defined via the + Gauss hypergeometric function :math:`{}_2F_1` as + + .. math:: + + T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2). + + When :math:`n` is an integer the result is a polynomial of degree + :math:`n`. See 22.5.47 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to the Gauss hypergeometric + function. + x : array_like + Points at which to evaluate the Chebyshev polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + T : scalar or ndarray + Values of the Chebyshev polynomial + + See Also + -------- + roots_chebyt : roots and quadrature weights of Chebyshev + polynomials of the first kind + chebyu : Chebychev polynomial object + eval_chebyu : evaluate Chebyshev polynomials of the second kind + hyp2f1 : Gauss hypergeometric function + numpy.polynomial.chebyshev.Chebyshev : Chebyshev series + + Notes + ----- + This routine is numerically stable for `x` in ``[-1, 1]`` at least + up to order ``10000``. + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_chebyu", + r""" + eval_chebyu(n, x, out=None) + + Evaluate Chebyshev polynomial of the second kind at a point. + + The Chebyshev polynomials of the second kind can be defined via + the Gauss hypergeometric function :math:`{}_2F_1` as + + .. math:: + + U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2). + + When :math:`n` is an integer the result is a polynomial of degree + :math:`n`. See 22.5.48 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to the Gauss hypergeometric + function. + x : array_like + Points at which to evaluate the Chebyshev polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + U : scalar or ndarray + Values of the Chebyshev polynomial + + See Also + -------- + roots_chebyu : roots and quadrature weights of Chebyshev + polynomials of the second kind + chebyu : Chebyshev polynomial object + eval_chebyt : evaluate Chebyshev polynomials of the first kind + hyp2f1 : Gauss hypergeometric function + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_chebys", + r""" + eval_chebys(n, x, out=None) + + Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a + point. + + These polynomials are defined as + + .. math:: + + S_n(x) = U_n(x/2) + + where :math:`U_n` is a Chebyshev polynomial of the second + kind. See 22.5.13 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to `eval_chebyu`. + x : array_like + Points at which to evaluate the Chebyshev polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + S : scalar or ndarray + Values of the Chebyshev polynomial + + See Also + -------- + roots_chebys : roots and quadrature weights of Chebyshev + polynomials of the second kind on [-2, 2] + chebys : Chebyshev polynomial object + eval_chebyu : evaluate Chebyshev polynomials of the second kind + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + They are a scaled version of the Chebyshev polynomials of the + second kind. + + >>> x = np.linspace(-2, 2, 6) + >>> sc.eval_chebys(3, x) + array([-4. , 0.672, 0.736, -0.736, -0.672, 4. ]) + >>> sc.eval_chebyu(3, x / 2) + array([-4. , 0.672, 0.736, -0.736, -0.672, 4. ]) + + """) + +add_newdoc("eval_chebyc", + r""" + eval_chebyc(n, x, out=None) + + Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a + point. + + These polynomials are defined as + + .. math:: + + C_n(x) = 2 T_n(x/2) + + where :math:`T_n` is a Chebyshev polynomial of the first kind. See + 22.5.11 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to `eval_chebyt`. + x : array_like + Points at which to evaluate the Chebyshev polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + C : scalar or ndarray + Values of the Chebyshev polynomial + + See Also + -------- + roots_chebyc : roots and quadrature weights of Chebyshev + polynomials of the first kind on [-2, 2] + chebyc : Chebyshev polynomial object + numpy.polynomial.chebyshev.Chebyshev : Chebyshev series + eval_chebyt : evaluate Chebycshev polynomials of the first kind + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + They are a scaled version of the Chebyshev polynomials of the + first kind. + + >>> x = np.linspace(-2, 2, 6) + >>> sc.eval_chebyc(3, x) + array([-2. , 1.872, 1.136, -1.136, -1.872, 2. ]) + >>> 2 * sc.eval_chebyt(3, x / 2) + array([-2. , 1.872, 1.136, -1.136, -1.872, 2. ]) + + """) + +add_newdoc("eval_sh_chebyt", + r""" + eval_sh_chebyt(n, x, out=None) + + Evaluate shifted Chebyshev polynomial of the first kind at a + point. + + These polynomials are defined as + + .. math:: + + T_n^*(x) = T_n(2x - 1) + + where :math:`T_n` is a Chebyshev polynomial of the first kind. See + 22.5.14 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to `eval_chebyt`. + x : array_like + Points at which to evaluate the shifted Chebyshev polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + T : scalar or ndarray + Values of the shifted Chebyshev polynomial + + See Also + -------- + roots_sh_chebyt : roots and quadrature weights of shifted + Chebyshev polynomials of the first kind + sh_chebyt : shifted Chebyshev polynomial object + eval_chebyt : evaluate Chebyshev polynomials of the first kind + numpy.polynomial.chebyshev.Chebyshev : Chebyshev series + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_sh_chebyu", + r""" + eval_sh_chebyu(n, x, out=None) + + Evaluate shifted Chebyshev polynomial of the second kind at a + point. + + These polynomials are defined as + + .. math:: + + U_n^*(x) = U_n(2x - 1) + + where :math:`U_n` is a Chebyshev polynomial of the first kind. See + 22.5.15 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to `eval_chebyu`. + x : array_like + Points at which to evaluate the shifted Chebyshev polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + U : scalar or ndarray + Values of the shifted Chebyshev polynomial + + See Also + -------- + roots_sh_chebyu : roots and quadrature weights of shifted + Chebychev polynomials of the second kind + sh_chebyu : shifted Chebyshev polynomial object + eval_chebyu : evaluate Chebyshev polynomials of the second kind + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_legendre", + r""" + eval_legendre(n, x, out=None) + + Evaluate Legendre polynomial at a point. + + The Legendre polynomials can be defined via the Gauss + hypergeometric function :math:`{}_2F_1` as + + .. math:: + + P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2). + + When :math:`n` is an integer the result is a polynomial of degree + :math:`n`. See 22.5.49 in [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to the Gauss hypergeometric + function. + x : array_like + Points at which to evaluate the Legendre polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + P : scalar or ndarray + Values of the Legendre polynomial + + See Also + -------- + roots_legendre : roots and quadrature weights of Legendre + polynomials + legendre : Legendre polynomial object + hyp2f1 : Gauss hypergeometric function + numpy.polynomial.legendre.Legendre : Legendre series + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import eval_legendre + + Evaluate the zero-order Legendre polynomial at x = 0 + + >>> eval_legendre(0, 0) + 1.0 + + Evaluate the first-order Legendre polynomial between -1 and 1 + + >>> X = np.linspace(-1, 1, 5) # Domain of Legendre polynomials + >>> eval_legendre(1, X) + array([-1. , -0.5, 0. , 0.5, 1. ]) + + Evaluate Legendre polynomials of order 0 through 4 at x = 0 + + >>> N = range(0, 5) + >>> eval_legendre(N, 0) + array([ 1. , 0. , -0.5 , 0. , 0.375]) + + Plot Legendre polynomials of order 0 through 4 + + >>> X = np.linspace(-1, 1) + + >>> import matplotlib.pyplot as plt + >>> for n in range(0, 5): + ... y = eval_legendre(n, X) + ... plt.plot(X, y, label=r'$P_{}(x)$'.format(n)) + + >>> plt.title("Legendre Polynomials") + >>> plt.xlabel("x") + >>> plt.ylabel(r'$P_n(x)$') + >>> plt.legend(loc='lower right') + >>> plt.show() + + """) + +add_newdoc("eval_sh_legendre", + r""" + eval_sh_legendre(n, x, out=None) + + Evaluate shifted Legendre polynomial at a point. + + These polynomials are defined as + + .. math:: + + P_n^*(x) = P_n(2x - 1) + + where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_ + for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the value is + determined via the relation to `eval_legendre`. + x : array_like + Points at which to evaluate the shifted Legendre polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + P : scalar or ndarray + Values of the shifted Legendre polynomial + + See Also + -------- + roots_sh_legendre : roots and quadrature weights of shifted + Legendre polynomials + sh_legendre : shifted Legendre polynomial object + eval_legendre : evaluate Legendre polynomials + numpy.polynomial.legendre.Legendre : Legendre series + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_genlaguerre", + r""" + eval_genlaguerre(n, alpha, x, out=None) + + Evaluate generalized Laguerre polynomial at a point. + + The generalized Laguerre polynomials can be defined via the + confluent hypergeometric function :math:`{}_1F_1` as + + .. math:: + + L_n^{(\alpha)}(x) = \binom{n + \alpha}{n} + {}_1F_1(-n, \alpha + 1, x). + + When :math:`n` is an integer the result is a polynomial of degree + :math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre + polynomials are the special case where :math:`\alpha = 0`. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer, the result is + determined via the relation to the confluent hypergeometric + function. + alpha : array_like + Parameter; must have ``alpha > -1`` + x : array_like + Points at which to evaluate the generalized Laguerre + polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + L : scalar or ndarray + Values of the generalized Laguerre polynomial + + See Also + -------- + roots_genlaguerre : roots and quadrature weights of generalized + Laguerre polynomials + genlaguerre : generalized Laguerre polynomial object + hyp1f1 : confluent hypergeometric function + eval_laguerre : evaluate Laguerre polynomials + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_laguerre", + r""" + eval_laguerre(n, x, out=None) + + Evaluate Laguerre polynomial at a point. + + The Laguerre polynomials can be defined via the confluent + hypergeometric function :math:`{}_1F_1` as + + .. math:: + + L_n(x) = {}_1F_1(-n, 1, x). + + See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an + integer the result is a polynomial of degree :math:`n`. + + Parameters + ---------- + n : array_like + Degree of the polynomial. If not an integer the result is + determined via the relation to the confluent hypergeometric + function. + x : array_like + Points at which to evaluate the Laguerre polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + L : scalar or ndarray + Values of the Laguerre polynomial + + See Also + -------- + roots_laguerre : roots and quadrature weights of Laguerre + polynomials + laguerre : Laguerre polynomial object + numpy.polynomial.laguerre.Laguerre : Laguerre series + eval_genlaguerre : evaluate generalized Laguerre polynomials + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_hermite", + r""" + eval_hermite(n, x, out=None) + + Evaluate physicist's Hermite polynomial at a point. + + Defined by + + .. math:: + + H_n(x) = (-1)^n e^{x^2} \frac{d^n}{dx^n} e^{-x^2}; + + :math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in + [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial + x : array_like + Points at which to evaluate the Hermite polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + H : scalar or ndarray + Values of the Hermite polynomial + + See Also + -------- + roots_hermite : roots and quadrature weights of physicist's + Hermite polynomials + hermite : physicist's Hermite polynomial object + numpy.polynomial.hermite.Hermite : Physicist's Hermite series + eval_hermitenorm : evaluate Probabilist's Hermite polynomials + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + +add_newdoc("eval_hermitenorm", + r""" + eval_hermitenorm(n, x, out=None) + + Evaluate probabilist's (normalized) Hermite polynomial at a + point. + + Defined by + + .. math:: + + He_n(x) = (-1)^n e^{x^2/2} \frac{d^n}{dx^n} e^{-x^2/2}; + + :math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in + [AS]_ for details. + + Parameters + ---------- + n : array_like + Degree of the polynomial + x : array_like + Points at which to evaluate the Hermite polynomial + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + He : scalar or ndarray + Values of the Hermite polynomial + + See Also + -------- + roots_hermitenorm : roots and quadrature weights of probabilist's + Hermite polynomials + hermitenorm : probabilist's Hermite polynomial object + numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series + eval_hermite : evaluate physicist's Hermite polynomials + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """) + + +add_newdoc("exp10", + """ + exp10(x, out=None) + + Compute ``10**x`` element-wise. + + Parameters + ---------- + x : array_like + `x` must contain real numbers. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + ``10**x``, computed element-wise. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import exp10 + + >>> exp10(3) + 1000.0 + >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]]) + >>> exp10(x) + array([[ 0.1 , 0.31622777, 1. ], + [ 3.16227766, 10. , 31.6227766 ]]) + + """) + +add_newdoc("exp2", + """ + exp2(x, out=None) + + Compute ``2**x`` element-wise. + + Parameters + ---------- + x : array_like + `x` must contain real numbers. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + ``2**x``, computed element-wise. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import exp2 + + >>> exp2(3) + 8.0 + >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]]) + >>> exp2(x) + array([[ 0.5 , 0.70710678, 1. ], + [ 1.41421356, 2. , 2.82842712]]) + """) + +add_newdoc("expm1", + """ + expm1(x, out=None) + + Compute ``exp(x) - 1``. + + When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation + of ``exp(x) - 1`` can suffer from catastrophic loss of precision. + ``expm1(x)`` is implemented to avoid the loss of precision that occurs when + `x` is near zero. + + Parameters + ---------- + x : array_like + `x` must contain real numbers. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + ``exp(x) - 1`` computed element-wise. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import expm1 + + >>> expm1(1.0) + 1.7182818284590451 + >>> expm1([-0.2, -0.1, 0, 0.1, 0.2]) + array([-0.18126925, -0.09516258, 0. , 0.10517092, 0.22140276]) + + The exact value of ``exp(7.5e-13) - 1`` is:: + + 7.5000000000028125000000007031250000001318...*10**-13. + + Here is what ``expm1(7.5e-13)`` gives: + + >>> expm1(7.5e-13) + 7.5000000000028135e-13 + + Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in + a "catastrophic" loss of precision: + + >>> np.exp(7.5e-13) - 1 + 7.5006667543675576e-13 + + """) + +add_newdoc("expn", + r""" + expn(n, x, out=None) + + Generalized exponential integral En. + + For integer :math:`n \geq 0` and real :math:`x \geq 0` the + generalized exponential integral is defined as [dlmf]_ + + .. math:: + + E_n(x) = x^{n - 1} \int_x^\infty \frac{e^{-t}}{t^n} dt. + + Parameters + ---------- + n : array_like + Non-negative integers + x : array_like + Real argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the generalized exponential integral + + See Also + -------- + exp1 : special case of :math:`E_n` for :math:`n = 1` + expi : related to :math:`E_n` when :math:`n = 1` + + References + ---------- + .. [dlmf] Digital Library of Mathematical Functions, 8.19.2 + https://dlmf.nist.gov/8.19#E2 + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + Its domain is nonnegative n and x. + + >>> sc.expn(-1, 1.0), sc.expn(1, -1.0) + (nan, nan) + + It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it + is equal to ``1 / (n - 1)``. + + >>> sc.expn([0, 1, 2, 3, 4], 0) + array([ inf, inf, 1. , 0.5 , 0.33333333]) + + For n equal to 0 it reduces to ``exp(-x) / x``. + + >>> x = np.array([1, 2, 3, 4]) + >>> sc.expn(0, x) + array([0.36787944, 0.06766764, 0.01659569, 0.00457891]) + >>> np.exp(-x) / x + array([0.36787944, 0.06766764, 0.01659569, 0.00457891]) + + For n equal to 1 it reduces to `exp1`. + + >>> sc.expn(1, x) + array([0.21938393, 0.04890051, 0.01304838, 0.00377935]) + >>> sc.exp1(x) + array([0.21938393, 0.04890051, 0.01304838, 0.00377935]) + + """) + +add_newdoc("fdtr", + r""" + fdtr(dfn, dfd, x, out=None) + + F cumulative distribution function. + + Returns the value of the cumulative distribution function of the + F-distribution, also known as Snedecor's F-distribution or the + Fisher-Snedecor distribution. + + The F-distribution with parameters :math:`d_n` and :math:`d_d` is the + distribution of the random variable, + + .. math:: + X = \frac{U_n/d_n}{U_d/d_d}, + + where :math:`U_n` and :math:`U_d` are random variables distributed + :math:`\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom, + respectively. + + Parameters + ---------- + dfn : array_like + First parameter (positive float). + dfd : array_like + Second parameter (positive float). + x : array_like + Argument (nonnegative float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + y : scalar or ndarray + The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`. + + See Also + -------- + fdtrc : F distribution survival function + fdtri : F distribution inverse cumulative distribution + scipy.stats.f : F distribution + + Notes + ----- + The regularized incomplete beta function is used, according to the + formula, + + .. math:: + F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2). + + Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also + available as `scipy.stats.f`. Calling `fdtr` directly can improve + performance compared to the ``cdf`` method of `scipy.stats.f` (see last + example below). + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``. + + >>> import numpy as np + >>> from scipy.special import fdtr + >>> fdtr(1, 2, 1) + 0.5773502691896258 + + Calculate the function at several points by providing a NumPy array for + `x`. + + >>> x = np.array([0.5, 2., 3.]) + >>> fdtr(1, 2, x) + array([0.4472136 , 0.70710678, 0.77459667]) + + Plot the function for several parameter sets. + + >>> import matplotlib.pyplot as plt + >>> dfn_parameters = [1, 5, 10, 50] + >>> dfd_parameters = [1, 1, 2, 3] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(dfn_parameters, dfd_parameters, + ... linestyles)) + >>> x = np.linspace(0, 30, 1000) + >>> fig, ax = plt.subplots() + >>> for parameter_set in parameters_list: + ... dfn, dfd, style = parameter_set + ... fdtr_vals = fdtr(dfn, dfd, x) + ... ax.plot(x, fdtr_vals, label=rf"$d_n={dfn},\, d_d={dfd}$", + ... ls=style) + >>> ax.legend() + >>> ax.set_xlabel("$x$") + >>> ax.set_title("F distribution cumulative distribution function") + >>> plt.show() + + The F distribution is also available as `scipy.stats.f`. Using `fdtr` + directly can be much faster than calling the ``cdf`` method of + `scipy.stats.f`, especially for small arrays or individual values. + To get the same results one must use the following parametrization: + ``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``. + + >>> from scipy.stats import f + >>> dfn, dfd = 1, 2 + >>> x = 1 + >>> fdtr_res = fdtr(dfn, dfd, x) # this will often be faster than below + >>> f_dist_res = f(dfn, dfd).cdf(x) + >>> fdtr_res == f_dist_res # test that results are equal + True + """) + +add_newdoc("fdtrc", + r""" + fdtrc(dfn, dfd, x, out=None) + + F survival function. + + Returns the complemented F-distribution function (the integral of the + density from `x` to infinity). + + Parameters + ---------- + dfn : array_like + First parameter (positive float). + dfd : array_like + Second parameter (positive float). + x : array_like + Argument (nonnegative float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + y : scalar or ndarray + The complemented F-distribution function with parameters `dfn` and + `dfd` at `x`. + + See Also + -------- + fdtr : F distribution cumulative distribution function + fdtri : F distribution inverse cumulative distribution function + scipy.stats.f : F distribution + + Notes + ----- + The regularized incomplete beta function is used, according to the + formula, + + .. math:: + F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2). + + Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also + available as `scipy.stats.f`. Calling `fdtrc` directly can improve + performance compared to the ``sf`` method of `scipy.stats.f` (see last + example below). + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``. + + >>> import numpy as np + >>> from scipy.special import fdtrc + >>> fdtrc(1, 2, 1) + 0.42264973081037427 + + Calculate the function at several points by providing a NumPy array for + `x`. + + >>> x = np.array([0.5, 2., 3.]) + >>> fdtrc(1, 2, x) + array([0.5527864 , 0.29289322, 0.22540333]) + + Plot the function for several parameter sets. + + >>> import matplotlib.pyplot as plt + >>> dfn_parameters = [1, 5, 10, 50] + >>> dfd_parameters = [1, 1, 2, 3] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(dfn_parameters, dfd_parameters, + ... linestyles)) + >>> x = np.linspace(0, 30, 1000) + >>> fig, ax = plt.subplots() + >>> for parameter_set in parameters_list: + ... dfn, dfd, style = parameter_set + ... fdtrc_vals = fdtrc(dfn, dfd, x) + ... ax.plot(x, fdtrc_vals, label=rf"$d_n={dfn},\, d_d={dfd}$", + ... ls=style) + >>> ax.legend() + >>> ax.set_xlabel("$x$") + >>> ax.set_title("F distribution survival function") + >>> plt.show() + + The F distribution is also available as `scipy.stats.f`. Using `fdtrc` + directly can be much faster than calling the ``sf`` method of + `scipy.stats.f`, especially for small arrays or individual values. + To get the same results one must use the following parametrization: + ``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``. + + >>> from scipy.stats import f + >>> dfn, dfd = 1, 2 + >>> x = 1 + >>> fdtrc_res = fdtrc(dfn, dfd, x) # this will often be faster than below + >>> f_dist_res = f(dfn, dfd).sf(x) + >>> f_dist_res == fdtrc_res # test that results are equal + True + """) + +add_newdoc("fdtri", + r""" + fdtri(dfn, dfd, p, out=None) + + The `p`-th quantile of the F-distribution. + + This function is the inverse of the F-distribution CDF, `fdtr`, returning + the `x` such that `fdtr(dfn, dfd, x) = p`. + + Parameters + ---------- + dfn : array_like + First parameter (positive float). + dfd : array_like + Second parameter (positive float). + p : array_like + Cumulative probability, in [0, 1]. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + x : scalar or ndarray + The quantile corresponding to `p`. + + See Also + -------- + fdtr : F distribution cumulative distribution function + fdtrc : F distribution survival function + scipy.stats.f : F distribution + + Notes + ----- + The computation is carried out using the relation to the inverse + regularized beta function, :math:`I^{-1}_x(a, b)`. Let + :math:`z = I^{-1}_p(d_d/2, d_n/2).` Then, + + .. math:: + x = \frac{d_d (1 - z)}{d_n z}. + + If `p` is such that :math:`x < 0.5`, the following relation is used + instead for improved stability: let + :math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then, + + .. math:: + x = \frac{d_d z'}{d_n (1 - z')}. + + Wrapper for the Cephes [1]_ routine `fdtri`. + + The F distribution is also available as `scipy.stats.f`. Calling + `fdtri` directly can improve performance compared to the ``ppf`` + method of `scipy.stats.f` (see last example below). + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + `fdtri` represents the inverse of the F distribution CDF which is + available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2`` + at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`, + `df2` and the computed CDF value. + + >>> import numpy as np + >>> from scipy.special import fdtri, fdtr + >>> df1, df2 = 1, 2 + >>> x = 3 + >>> cdf_value = fdtr(df1, df2, x) + >>> fdtri(df1, df2, cdf_value) + 3.000000000000006 + + Calculate the function at several points by providing a NumPy array for + `x`. + + >>> x = np.array([0.1, 0.4, 0.7]) + >>> fdtri(1, 2, x) + array([0.02020202, 0.38095238, 1.92156863]) + + Plot the function for several parameter sets. + + >>> import matplotlib.pyplot as plt + >>> dfn_parameters = [50, 10, 1, 50] + >>> dfd_parameters = [0.5, 1, 1, 5] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(dfn_parameters, dfd_parameters, + ... linestyles)) + >>> x = np.linspace(0, 1, 1000) + >>> fig, ax = plt.subplots() + >>> for parameter_set in parameters_list: + ... dfn, dfd, style = parameter_set + ... fdtri_vals = fdtri(dfn, dfd, x) + ... ax.plot(x, fdtri_vals, label=rf"$d_n={dfn},\, d_d={dfd}$", + ... ls=style) + >>> ax.legend() + >>> ax.set_xlabel("$x$") + >>> title = "F distribution inverse cumulative distribution function" + >>> ax.set_title(title) + >>> ax.set_ylim(0, 30) + >>> plt.show() + + The F distribution is also available as `scipy.stats.f`. Using `fdtri` + directly can be much faster than calling the ``ppf`` method of + `scipy.stats.f`, especially for small arrays or individual values. + To get the same results one must use the following parametrization: + ``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``. + + >>> from scipy.stats import f + >>> dfn, dfd = 1, 2 + >>> x = 0.7 + >>> fdtri_res = fdtri(dfn, dfd, x) # this will often be faster than below + >>> f_dist_res = f(dfn, dfd).ppf(x) + >>> f_dist_res == fdtri_res # test that results are equal + True + """) + +add_newdoc("fdtridfd", + """ + fdtridfd(dfn, p, x, out=None) + + Inverse to `fdtr` vs dfd + + Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``. + + Parameters + ---------- + dfn : array_like + First parameter (positive float). + p : array_like + Cumulative probability, in [0, 1]. + x : array_like + Argument (nonnegative float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + dfd : scalar or ndarray + `dfd` such that ``fdtr(dfn, dfd, x) == p``. + + See Also + -------- + fdtr : F distribution cumulative distribution function + fdtrc : F distribution survival function + fdtri : F distribution quantile function + scipy.stats.f : F distribution + + Examples + -------- + Compute the F distribution cumulative distribution function for one + parameter set. + + >>> from scipy.special import fdtridfd, fdtr + >>> dfn, dfd, x = 10, 5, 2 + >>> cdf_value = fdtr(dfn, dfd, x) + >>> cdf_value + 0.7700248806501017 + + Verify that `fdtridfd` recovers the original value for `dfd`: + + >>> fdtridfd(dfn, cdf_value, x) + 5.0 + """) + +''' +commented out as fdtridfn seems to have bugs and is not in functions.json +see: https://github.com/scipy/scipy/pull/15622#discussion_r811440983 + +add_newdoc( + "fdtridfn", + """ + fdtridfn(p, dfd, x, out=None) + + Inverse to `fdtr` vs dfn + + finds the F density argument dfn such that ``fdtr(dfn, dfd, x) == p``. + + + Parameters + ---------- + p : array_like + Cumulative probability, in [0, 1]. + dfd : array_like + Second parameter (positive float). + x : array_like + Argument (nonnegative float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + dfn : scalar or ndarray + `dfn` such that ``fdtr(dfn, dfd, x) == p``. + + See Also + -------- + fdtr, fdtrc, fdtri, fdtridfd + + + """) +''' + +add_newdoc("gdtr", + r""" + gdtr(a, b, x, out=None) + + Gamma distribution cumulative distribution function. + + Returns the integral from zero to `x` of the gamma probability density + function, + + .. math:: + + F = \int_0^x \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt, + + where :math:`\Gamma` is the gamma function. + + Parameters + ---------- + a : array_like + The rate parameter of the gamma distribution, sometimes denoted + :math:`\beta` (float). It is also the reciprocal of the scale + parameter :math:`\theta`. + b : array_like + The shape parameter of the gamma distribution, sometimes denoted + :math:`\alpha` (float). + x : array_like + The quantile (upper limit of integration; float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + F : scalar or ndarray + The CDF of the gamma distribution with parameters `a` and `b` + evaluated at `x`. + + See Also + -------- + gdtrc : 1 - CDF of the gamma distribution. + scipy.stats.gamma: Gamma distribution + + Notes + ----- + The evaluation is carried out using the relation to the incomplete gamma + integral (regularized gamma function). + + Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can + improve performance compared to the ``cdf`` method of `scipy.stats.gamma` + (see last example below). + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + Compute the function for ``a=1``, ``b=2`` at ``x=5``. + + >>> import numpy as np + >>> from scipy.special import gdtr + >>> import matplotlib.pyplot as plt + >>> gdtr(1., 2., 5.) + 0.9595723180054873 + + Compute the function for ``a=1`` and ``b=2`` at several points by + providing a NumPy array for `x`. + + >>> xvalues = np.array([1., 2., 3., 4]) + >>> gdtr(1., 1., xvalues) + array([0.63212056, 0.86466472, 0.95021293, 0.98168436]) + + `gdtr` can evaluate different parameter sets by providing arrays with + broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the + function for three different `a` at four positions `x` and ``b=3``, + resulting in a 3x4 array. + + >>> a = np.array([[0.5], [1.5], [2.5]]) + >>> x = np.array([1., 2., 3., 4]) + >>> a.shape, x.shape + ((3, 1), (4,)) + + >>> gdtr(a, 3., x) + array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358], + [0.19115317, 0.57680992, 0.82642193, 0.9380312 ], + [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]]) + + Plot the function for four different parameter sets. + + >>> a_parameters = [0.3, 1, 2, 6] + >>> b_parameters = [2, 10, 15, 20] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles)) + >>> x = np.linspace(0, 30, 1000) + >>> fig, ax = plt.subplots() + >>> for parameter_set in parameters_list: + ... a, b, style = parameter_set + ... gdtr_vals = gdtr(a, b, x) + ... ax.plot(x, gdtr_vals, label=fr"$a= {a},\, b={b}$", ls=style) + >>> ax.legend() + >>> ax.set_xlabel("$x$") + >>> ax.set_title("Gamma distribution cumulative distribution function") + >>> plt.show() + + The gamma distribution is also available as `scipy.stats.gamma`. Using + `gdtr` directly can be much faster than calling the ``cdf`` method of + `scipy.stats.gamma`, especially for small arrays or individual values. + To get the same results one must use the following parametrization: + ``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``. + + >>> from scipy.stats import gamma + >>> a = 2. + >>> b = 3 + >>> x = 1. + >>> gdtr_result = gdtr(a, b, x) # this will often be faster than below + >>> gamma_dist_result = gamma(b, scale=1/a).cdf(x) + >>> gdtr_result == gamma_dist_result # test that results are equal + True + """) + +add_newdoc("gdtrc", + r""" + gdtrc(a, b, x, out=None) + + Gamma distribution survival function. + + Integral from `x` to infinity of the gamma probability density function, + + .. math:: + + F = \int_x^\infty \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt, + + where :math:`\Gamma` is the gamma function. + + Parameters + ---------- + a : array_like + The rate parameter of the gamma distribution, sometimes denoted + :math:`\beta` (float). It is also the reciprocal of the scale + parameter :math:`\theta`. + b : array_like + The shape parameter of the gamma distribution, sometimes denoted + :math:`\alpha` (float). + x : array_like + The quantile (lower limit of integration; float). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + F : scalar or ndarray + The survival function of the gamma distribution with parameters `a` + and `b` evaluated at `x`. + + See Also + -------- + gdtr: Gamma distribution cumulative distribution function + scipy.stats.gamma: Gamma distribution + gdtrix + + Notes + ----- + The evaluation is carried out using the relation to the incomplete gamma + integral (regularized gamma function). + + Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can + improve performance compared to the ``sf`` method of `scipy.stats.gamma` + (see last example below). + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + Compute the function for ``a=1`` and ``b=2`` at ``x=5``. + + >>> import numpy as np + >>> from scipy.special import gdtrc + >>> import matplotlib.pyplot as plt + >>> gdtrc(1., 2., 5.) + 0.04042768199451279 + + Compute the function for ``a=1``, ``b=2`` at several points by providing + a NumPy array for `x`. + + >>> xvalues = np.array([1., 2., 3., 4]) + >>> gdtrc(1., 1., xvalues) + array([0.36787944, 0.13533528, 0.04978707, 0.01831564]) + + `gdtrc` can evaluate different parameter sets by providing arrays with + broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the + function for three different `a` at four positions `x` and ``b=3``, + resulting in a 3x4 array. + + >>> a = np.array([[0.5], [1.5], [2.5]]) + >>> x = np.array([1., 2., 3., 4]) + >>> a.shape, x.shape + ((3, 1), (4,)) + + >>> gdtrc(a, 3., x) + array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642], + [0.80884683, 0.42319008, 0.17357807, 0.0619688 ], + [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]]) + + Plot the function for four different parameter sets. + + >>> a_parameters = [0.3, 1, 2, 6] + >>> b_parameters = [2, 10, 15, 20] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles)) + >>> x = np.linspace(0, 30, 1000) + >>> fig, ax = plt.subplots() + >>> for parameter_set in parameters_list: + ... a, b, style = parameter_set + ... gdtrc_vals = gdtrc(a, b, x) + ... ax.plot(x, gdtrc_vals, label=fr"$a= {a},\, b={b}$", ls=style) + >>> ax.legend() + >>> ax.set_xlabel("$x$") + >>> ax.set_title("Gamma distribution survival function") + >>> plt.show() + + The gamma distribution is also available as `scipy.stats.gamma`. + Using `gdtrc` directly can be much faster than calling the ``sf`` method + of `scipy.stats.gamma`, especially for small arrays or individual + values. To get the same results one must use the following parametrization: + ``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``. + + >>> from scipy.stats import gamma + >>> a = 2 + >>> b = 3 + >>> x = 1. + >>> gdtrc_result = gdtrc(a, b, x) # this will often be faster than below + >>> gamma_dist_result = gamma(b, scale=1/a).sf(x) + >>> gdtrc_result == gamma_dist_result # test that results are equal + True + """) + +add_newdoc("gdtria", + """ + gdtria(p, b, x, out=None) + + Inverse of `gdtr` vs a. + + Returns the inverse with respect to the parameter `a` of ``p = + gdtr(a, b, x)``, the cumulative distribution function of the gamma + distribution. + + Parameters + ---------- + p : array_like + Probability values. + b : array_like + `b` parameter values of `gdtr(a, b, x)`. `b` is the "shape" parameter + of the gamma distribution. + x : array_like + Nonnegative real values, from the domain of the gamma distribution. + out : ndarray, optional + If a fourth argument is given, it must be a numpy.ndarray whose size + matches the broadcast result of `a`, `b` and `x`. `out` is then the + array returned by the function. + + Returns + ------- + a : scalar or ndarray + Values of the `a` parameter such that ``p = gdtr(a, b, x)`. ``1/a`` + is the "scale" parameter of the gamma distribution. + + See Also + -------- + gdtr : CDF of the gamma distribution. + gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`. + gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`. + + Notes + ----- + Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`. + + The cumulative distribution function `p` is computed using a routine by + DiDinato and Morris [2]_. Computation of `a` involves a search for a value + that produces the desired value of `p`. The search relies on the + monotonicity of `p` with `a`. + + References + ---------- + .. [1] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + .. [2] DiDinato, A. R. and Morris, A. H., + Computation of the incomplete gamma function ratios and their + inverse. ACM Trans. Math. Softw. 12 (1986), 377-393. + + Examples + -------- + First evaluate `gdtr`. + + >>> from scipy.special import gdtr, gdtria + >>> p = gdtr(1.2, 3.4, 5.6) + >>> print(p) + 0.94378087442 + + Verify the inverse. + + >>> gdtria(p, 3.4, 5.6) + 1.2 + """) + +add_newdoc("gdtrib", + """ + gdtrib(a, p, x, out=None) + + Inverse of `gdtr` vs b. + + Returns the inverse with respect to the parameter `b` of ``p = + gdtr(a, b, x)``, the cumulative distribution function of the gamma + distribution. + + Parameters + ---------- + a : array_like + `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the "scale" + parameter of the gamma distribution. + p : array_like + Probability values. + x : array_like + Nonnegative real values, from the domain of the gamma distribution. + out : ndarray, optional + If a fourth argument is given, it must be a numpy.ndarray whose size + matches the broadcast result of `a`, `b` and `x`. `out` is then the + array returned by the function. + + Returns + ------- + b : scalar or ndarray + Values of the `b` parameter such that `p = gdtr(a, b, x)`. `b` is + the "shape" parameter of the gamma distribution. + + See Also + -------- + gdtr : CDF of the gamma distribution. + gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`. + gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`. + + Notes + ----- + + The cumulative distribution function `p` is computed using the Cephes [1]_ + routines `igam` and `igamc`. Computation of `b` involves a search for a value + that produces the desired value of `p` using Chandrupatla's bracketing + root finding algorithm [2]_. + + Note that there are some edge cases where `gdtrib` is extended by taking + limits where they are uniquely defined. In particular + ``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``. + For these edge cases, a numerical result will be returned for + ``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is + undefined. + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + .. [2] Chandrupatla, Tirupathi R. + "A new hybrid quadratic/bisection algorithm for finding the zero of a + nonlinear function without using derivatives". + Advances in Engineering Software, 28(3), 145-149. + https://doi.org/10.1016/s0965-9978(96)00051-8 + + Examples + -------- + First evaluate `gdtr`. + + >>> from scipy.special import gdtr, gdtrib + >>> p = gdtr(1.2, 3.4, 5.6) + >>> print(p) + 0.94378087442 + + Verify the inverse. + + >>> gdtrib(1.2, p, 5.6) + 3.3999999999999995 + """) + +add_newdoc("gdtrix", + """ + gdtrix(a, b, p, out=None) + + Inverse of `gdtr` vs x. + + Returns the inverse with respect to the parameter `x` of ``p = + gdtr(a, b, x)``, the cumulative distribution function of the gamma + distribution. This is also known as the pth quantile of the + distribution. + + Parameters + ---------- + a : array_like + `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the "scale" + parameter of the gamma distribution. + b : array_like + `b` parameter values of ``gdtr(a, b, x)``. `b` is the "shape" parameter + of the gamma distribution. + p : array_like + Probability values. + out : ndarray, optional + If a fourth argument is given, it must be a numpy.ndarray whose size + matches the broadcast result of `a`, `b` and `x`. `out` is then the + array returned by the function. + + Returns + ------- + x : scalar or ndarray + Values of the `x` parameter such that `p = gdtr(a, b, x)`. + + See Also + -------- + gdtr : CDF of the gamma distribution. + gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``. + gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``. + + Notes + ----- + Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`. + + The cumulative distribution function `p` is computed using a routine by + DiDinato and Morris [2]_. Computation of `x` involves a search for a value + that produces the desired value of `p`. The search relies on the + monotonicity of `p` with `x`. + + References + ---------- + .. [1] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + .. [2] DiDinato, A. R. and Morris, A. H., + Computation of the incomplete gamma function ratios and their + inverse. ACM Trans. Math. Softw. 12 (1986), 377-393. + + Examples + -------- + First evaluate `gdtr`. + + >>> from scipy.special import gdtr, gdtrix + >>> p = gdtr(1.2, 3.4, 5.6) + >>> print(p) + 0.94378087442 + + Verify the inverse. + + >>> gdtrix(1.2, 3.4, p) + 5.5999999999999996 + """) + +add_newdoc("hankel1", + r""" + hankel1(v, z, out=None) + + Hankel function of the first kind + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Values of the Hankel function of the first kind. + + See Also + -------- + hankel1e : ndarray + This function with leading exponential behavior stripped off. + + Notes + ----- + A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the + computation using the relation, + + .. math:: H^{(1)}_v(z) = + \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2)) + + where :math:`K_v` is the modified Bessel function of the second kind. + For negative orders, the relation + + .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v) + + is used. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + """) + +add_newdoc("hankel1e", + r""" + hankel1e(v, z, out=None) + + Exponentially scaled Hankel function of the first kind + + Defined as:: + + hankel1e(v, z) = hankel1(v, z) * exp(-1j * z) + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Values of the exponentially scaled Hankel function. + + Notes + ----- + A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the + computation using the relation, + + .. math:: H^{(1)}_v(z) = + \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2)) + + where :math:`K_v` is the modified Bessel function of the second kind. + For negative orders, the relation + + .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v) + + is used. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + """) + +add_newdoc("hankel2", + r""" + hankel2(v, z, out=None) + + Hankel function of the second kind + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Values of the Hankel function of the second kind. + + See Also + -------- + hankel2e : this function with leading exponential behavior stripped off. + + Notes + ----- + A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the + computation using the relation, + + .. math:: H^{(2)}_v(z) = + -\frac{2}{\imath\pi} \exp(\imath \pi v/2) K_v(z \exp(\imath\pi/2)) + + where :math:`K_v` is the modified Bessel function of the second kind. + For negative orders, the relation + + .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v) + + is used. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + """) + +add_newdoc("hankel2e", + r""" + hankel2e(v, z, out=None) + + Exponentially scaled Hankel function of the second kind + + Defined as:: + + hankel2e(v, z) = hankel2(v, z) * exp(1j * z) + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Values of the exponentially scaled Hankel function of the second kind. + + Notes + ----- + A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the + computation using the relation, + + .. math:: H^{(2)}_v(z) = -\frac{2}{\imath\pi} + \exp(\frac{\imath \pi v}{2}) K_v(z exp(\frac{\imath\pi}{2})) + + where :math:`K_v` is the modified Bessel function of the second kind. + For negative orders, the relation + + .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v) + + is used. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + """) + +add_newdoc("huber", + r""" + huber(delta, r, out=None) + + Huber loss function. + + .. math:: \text{huber}(\delta, r) = \begin{cases} \infty & \delta < 0 \\ + \frac{1}{2}r^2 & 0 \le \delta, | r | \le \delta \\ + \delta ( |r| - \frac{1}{2}\delta ) & \text{otherwise} \end{cases} + + Parameters + ---------- + delta : ndarray + Input array, indicating the quadratic vs. linear loss changepoint. + r : ndarray + Input array, possibly representing residuals. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + The computed Huber loss function values. + + See Also + -------- + pseudo_huber : smooth approximation of this function + + Notes + ----- + `huber` is useful as a loss function in robust statistics or machine + learning to reduce the influence of outliers as compared to the common + squared error loss, residuals with a magnitude higher than `delta` are + not squared [1]_. + + Typically, `r` represents residuals, the difference + between a model prediction and data. Then, for :math:`|r|\leq\delta`, + `huber` resembles the squared error and for :math:`|r|>\delta` the + absolute error. This way, the Huber loss often achieves + a fast convergence in model fitting for small residuals like the squared + error loss function and still reduces the influence of outliers + (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is + the cutoff between squared and absolute error regimes, it has + to be tuned carefully for each problem. `huber` is also + convex, making it suitable for gradient based optimization. + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Peter Huber. "Robust Estimation of a Location Parameter", + 1964. Annals of Statistics. 53 (1): 73 - 101. + + Examples + -------- + Import all necessary modules. + + >>> import numpy as np + >>> from scipy.special import huber + >>> import matplotlib.pyplot as plt + + Compute the function for ``delta=1`` at ``r=2`` + + >>> huber(1., 2.) + 1.5 + + Compute the function for different `delta` by providing a NumPy array or + list for `delta`. + + >>> huber([1., 3., 5.], 4.) + array([3.5, 7.5, 8. ]) + + Compute the function at different points by providing a NumPy array or + list for `r`. + + >>> huber(2., np.array([1., 1.5, 3.])) + array([0.5 , 1.125, 4. ]) + + The function can be calculated for different `delta` and `r` by + providing arrays for both with compatible shapes for broadcasting. + + >>> r = np.array([1., 2.5, 8., 10.]) + >>> deltas = np.array([[1.], [5.], [9.]]) + >>> print(r.shape, deltas.shape) + (4,) (3, 1) + + >>> huber(deltas, r) + array([[ 0.5 , 2. , 7.5 , 9.5 ], + [ 0.5 , 3.125, 27.5 , 37.5 ], + [ 0.5 , 3.125, 32. , 49.5 ]]) + + Plot the function for different `delta`. + + >>> x = np.linspace(-4, 4, 500) + >>> deltas = [1, 2, 3] + >>> linestyles = ["dashed", "dotted", "dashdot"] + >>> fig, ax = plt.subplots() + >>> combined_plot_parameters = list(zip(deltas, linestyles)) + >>> for delta, style in combined_plot_parameters: + ... ax.plot(x, huber(delta, x), label=fr"$\delta={delta}$", ls=style) + >>> ax.legend(loc="upper center") + >>> ax.set_xlabel("$x$") + >>> ax.set_title(r"Huber loss function $h_{\delta}(x)$") + >>> ax.set_xlim(-4, 4) + >>> ax.set_ylim(0, 8) + >>> plt.show() + """) + +add_newdoc("hyp0f1", + r""" + hyp0f1(v, z, out=None) + + Confluent hypergeometric limit function 0F1. + + Parameters + ---------- + v : array_like + Real-valued parameter + z : array_like + Real- or complex-valued argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The confluent hypergeometric limit function + + Notes + ----- + This function is defined as: + + .. math:: _0F_1(v, z) = \sum_{k=0}^{\infty}\frac{z^k}{(v)_k k!}. + + It's also the limit as :math:`q \to \infty` of :math:`_1F_1(q; v; z/q)`, + and satisfies the differential equation :math:`f''(z) + vf'(z) = + f(z)`. See [1]_ for more information. + + References + ---------- + .. [1] Wolfram MathWorld, "Confluent Hypergeometric Limit Function", + http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It is one when `z` is zero. + + >>> sc.hyp0f1(1, 0) + 1.0 + + It is the limit of the confluent hypergeometric function as `q` + goes to infinity. + + >>> q = np.array([1, 10, 100, 1000]) + >>> v = 1 + >>> z = 1 + >>> sc.hyp1f1(q, v, z / q) + array([2.71828183, 2.31481985, 2.28303778, 2.27992985]) + >>> sc.hyp0f1(v, z) + 2.2795853023360673 + + It is related to Bessel functions. + + >>> n = 1 + >>> x = np.linspace(0, 1, 5) + >>> sc.jv(n, x) + array([0. , 0.12402598, 0.24226846, 0.3492436 , 0.44005059]) + >>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2) + array([0. , 0.12402598, 0.24226846, 0.3492436 , 0.44005059]) + + """) + +add_newdoc("hyp1f1", + r""" + hyp1f1(a, b, x, out=None) + + Confluent hypergeometric function 1F1. + + The confluent hypergeometric function is defined by the series + + .. math:: + + {}_1F_1(a; b; x) = \sum_{k = 0}^\infty \frac{(a)_k}{(b)_k k!} x^k. + + See [dlmf]_ for more details. Here :math:`(\cdot)_k` is the + Pochhammer symbol; see `poch`. + + Parameters + ---------- + a, b : array_like + Real parameters + x : array_like + Real or complex argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the confluent hypergeometric function + + See Also + -------- + hyperu : another confluent hypergeometric function + hyp0f1 : confluent hypergeometric limit function + hyp2f1 : Gaussian hypergeometric function + + Notes + ----- + For real values, this function uses the ``hyp1f1`` routine from the C++ Boost + library [2]_, for complex values a C translation of the specfun + Fortran library [3]_. + + References + ---------- + .. [dlmf] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/13.2#E2 + .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + .. [3] Zhang, Jin, "Computation of Special Functions", John Wiley + and Sons, Inc, 1996. + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It is one when `x` is zero: + + >>> sc.hyp1f1(0.5, 0.5, 0) + 1.0 + + It is singular when `b` is a nonpositive integer. + + >>> sc.hyp1f1(0.5, -1, 0) + inf + + It is a polynomial when `a` is a nonpositive integer. + + >>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0]) + >>> sc.hyp1f1(a, b, x) + array([-1., -3., -5., -7.]) + >>> 1 + (a / b) * x + array([-1., -3., -5., -7.]) + + It reduces to the exponential function when ``a = b``. + + >>> sc.hyp1f1(2, 2, [1, 2, 3, 4]) + array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003]) + >>> np.exp([1, 2, 3, 4]) + array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003]) + + """) + +add_newdoc("hyperu", + r""" + hyperu(a, b, x, out=None) + + Confluent hypergeometric function U + + It is defined as the solution to the equation + + .. math:: + + x \frac{d^2w}{dx^2} + (b - x) \frac{dw}{dx} - aw = 0 + + which satisfies the property + + .. math:: + + U(a, b, x) \sim x^{-a} + + as :math:`x \to \infty`. See [dlmf]_ for more details. + + Parameters + ---------- + a, b : array_like + Real-valued parameters + x : array_like + Real-valued argument + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Values of `U` + + References + ---------- + .. [dlmf] NIST Digital Library of Mathematics Functions + https://dlmf.nist.gov/13.2#E6 + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It has a branch cut along the negative `x` axis. + + >>> x = np.linspace(-0.1, -10, 5) + >>> sc.hyperu(1, 1, x) + array([nan, nan, nan, nan, nan]) + + It approaches zero as `x` goes to infinity. + + >>> x = np.array([1, 10, 100]) + >>> sc.hyperu(1, 1, x) + array([0.59634736, 0.09156333, 0.00990194]) + + It satisfies Kummer's transformation. + + >>> a, b, x = 2, 1, 1 + >>> sc.hyperu(a, b, x) + 0.1926947246463881 + >>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x) + 0.1926947246463881 + + """) + +add_newdoc("_igam_fac", + """ + Internal function, do not use. + """) + +add_newdoc("iv", + r""" + iv(v, z, out=None) + + Modified Bessel function of the first kind of real order. + + Parameters + ---------- + v : array_like + Order. If `z` is of real type and negative, `v` must be integer + valued. + z : array_like of float or complex + Argument. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Values of the modified Bessel function. + + See Also + -------- + ive : This function with leading exponential behavior stripped off. + i0 : Faster version of this function for order 0. + i1 : Faster version of this function for order 1. + + Notes + ----- + For real `z` and :math:`v \in [-50, 50]`, the evaluation is carried out + using Temme's method [1]_. For larger orders, uniform asymptotic + expansions are applied. + + For complex `z` and positive `v`, the AMOS [2]_ `zbesi` routine is + called. It uses a power series for small `z`, the asymptotic expansion + for large `abs(z)`, the Miller algorithm normalized by the Wronskian + and a Neumann series for intermediate magnitudes, and the uniform + asymptotic expansions for :math:`I_v(z)` and :math:`J_v(z)` for large + orders. Backward recurrence is used to generate sequences or reduce + orders when necessary. + + The calculations above are done in the right half plane and continued + into the left half plane by the formula, + + .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z) + + (valid when the real part of `z` is positive). For negative `v`, the + formula + + .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z) + + is used, where :math:`K_v(z)` is the modified Bessel function of the + second kind, evaluated using the AMOS routine `zbesk`. + + References + ---------- + .. [1] Temme, Journal of Computational Physics, vol 21, 343 (1976) + .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + Evaluate the function of order 0 at one point. + + >>> from scipy.special import iv + >>> iv(0, 1.) + 1.2660658777520084 + + Evaluate the function at one point for different orders. + + >>> iv(0, 1.), iv(1, 1.), iv(1.5, 1.) + (1.2660658777520084, 0.565159103992485, 0.2935253263474798) + + The evaluation for different orders can be carried out in one call by + providing a list or NumPy array as argument for the `v` parameter: + + >>> iv([0, 1, 1.5], 1.) + array([1.26606588, 0.5651591 , 0.29352533]) + + Evaluate the function at several points for order 0 by providing an + array for `z`. + + >>> import numpy as np + >>> points = np.array([-2., 0., 3.]) + >>> iv(0, points) + array([2.2795853 , 1. , 4.88079259]) + + If `z` is an array, the order parameter `v` must be broadcastable to + the correct shape if different orders shall be computed in one call. + To calculate the orders 0 and 1 for an 1D array: + + >>> orders = np.array([[0], [1]]) + >>> orders.shape + (2, 1) + + >>> iv(orders, points) + array([[ 2.2795853 , 1. , 4.88079259], + [-1.59063685, 0. , 3.95337022]]) + + Plot the functions of order 0 to 3 from -5 to 5. + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> x = np.linspace(-5., 5., 1000) + >>> for i in range(4): + ... ax.plot(x, iv(i, x), label=f'$I_{i!r}$') + >>> ax.legend() + >>> plt.show() + + """) + +add_newdoc("ive", + r""" + ive(v, z, out=None) + + Exponentially scaled modified Bessel function of the first kind. + + Defined as:: + + ive(v, z) = iv(v, z) * exp(-abs(z.real)) + + For imaginary numbers without a real part, returns the unscaled + Bessel function of the first kind `iv`. + + Parameters + ---------- + v : array_like of float + Order. + z : array_like of float or complex + Argument. + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + Values of the exponentially scaled modified Bessel function. + + See Also + -------- + iv: Modified Bessel function of the first kind + i0e: Faster implementation of this function for order 0 + i1e: Faster implementation of this function for order 1 + + Notes + ----- + For positive `v`, the AMOS [1]_ `zbesi` routine is called. It uses a + power series for small `z`, the asymptotic expansion for large + `abs(z)`, the Miller algorithm normalized by the Wronskian and a + Neumann series for intermediate magnitudes, and the uniform asymptotic + expansions for :math:`I_v(z)` and :math:`J_v(z)` for large orders. + Backward recurrence is used to generate sequences or reduce orders when + necessary. + + The calculations above are done in the right half plane and continued + into the left half plane by the formula, + + .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z) + + (valid when the real part of `z` is positive). For negative `v`, the + formula + + .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z) + + is used, where :math:`K_v(z)` is the modified Bessel function of the + second kind, evaluated using the AMOS routine `zbesk`. + + `ive` is useful for large arguments `z`: for these, `iv` easily overflows, + while `ive` does not due to the exponential scaling. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + In the following example `iv` returns infinity whereas `ive` still returns + a finite number. + + >>> from scipy.special import iv, ive + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> iv(3, 1000.), ive(3, 1000.) + (inf, 0.01256056218254712) + + Evaluate the function at one point for different orders by + providing a list or NumPy array as argument for the `v` parameter: + + >>> ive([0, 1, 1.5], 1.) + array([0.46575961, 0.20791042, 0.10798193]) + + Evaluate the function at several points for order 0 by providing an + array for `z`. + + >>> points = np.array([-2., 0., 3.]) + >>> ive(0, points) + array([0.30850832, 1. , 0.24300035]) + + Evaluate the function at several points for different orders by + providing arrays for both `v` for `z`. Both arrays have to be + broadcastable to the correct shape. To calculate the orders 0, 1 + and 2 for a 1D array of points: + + >>> ive([[0], [1], [2]], points) + array([[ 0.30850832, 1. , 0.24300035], + [-0.21526929, 0. , 0.19682671], + [ 0.09323903, 0. , 0.11178255]]) + + Plot the functions of order 0 to 3 from -5 to 5. + + >>> fig, ax = plt.subplots() + >>> x = np.linspace(-5., 5., 1000) + >>> for i in range(4): + ... ax.plot(x, ive(i, x), label=fr'$I_{i!r}(z)\cdot e^{{-|z|}}$') + >>> ax.legend() + >>> ax.set_xlabel(r"$z$") + >>> plt.show() + """) + +add_newdoc("jn", + """ + jn(n, x, out=None) + + Bessel function of the first kind of integer order and real argument. + + Parameters + ---------- + n : array_like + order of the Bessel function + x : array_like + argument of the Bessel function + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + scalar or ndarray + The value of the bessel function + + See Also + -------- + jv + spherical_jn : spherical Bessel functions. + + Notes + ----- + `jn` is an alias of `jv`. + Not to be confused with the spherical Bessel functions (see + `spherical_jn`). + + """) + +add_newdoc("jv", + r""" + jv(v, z, out=None) + + Bessel function of the first kind of real order and complex argument. + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + J : scalar or ndarray + Value of the Bessel function, :math:`J_v(z)`. + + See Also + -------- + jve : :math:`J_v` with leading exponential behavior stripped off. + spherical_jn : spherical Bessel functions. + j0 : faster version of this function for order 0. + j1 : faster version of this function for order 1. + + Notes + ----- + For positive `v` values, the computation is carried out using the AMOS + [1]_ `zbesj` routine, which exploits the connection to the modified + Bessel function :math:`I_v`, + + .. math:: + J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0) + + J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0) + + For negative `v` values the formula, + + .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v) + + is used, where :math:`Y_v(z)` is the Bessel function of the second + kind, computed using the AMOS routine `zbesy`. Note that the second + term is exactly zero for integer `v`; to improve accuracy the second + term is explicitly omitted for `v` values such that `v = floor(v)`. + + Not to be confused with the spherical Bessel functions (see `spherical_jn`). + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + Evaluate the function of order 0 at one point. + + >>> from scipy.special import jv + >>> jv(0, 1.) + 0.7651976865579666 + + Evaluate the function at one point for different orders. + + >>> jv(0, 1.), jv(1, 1.), jv(1.5, 1.) + (0.7651976865579666, 0.44005058574493355, 0.24029783912342725) + + The evaluation for different orders can be carried out in one call by + providing a list or NumPy array as argument for the `v` parameter: + + >>> jv([0, 1, 1.5], 1.) + array([0.76519769, 0.44005059, 0.24029784]) + + Evaluate the function at several points for order 0 by providing an + array for `z`. + + >>> import numpy as np + >>> points = np.array([-2., 0., 3.]) + >>> jv(0, points) + array([ 0.22389078, 1. , -0.26005195]) + + If `z` is an array, the order parameter `v` must be broadcastable to + the correct shape if different orders shall be computed in one call. + To calculate the orders 0 and 1 for an 1D array: + + >>> orders = np.array([[0], [1]]) + >>> orders.shape + (2, 1) + + >>> jv(orders, points) + array([[ 0.22389078, 1. , -0.26005195], + [-0.57672481, 0. , 0.33905896]]) + + Plot the functions of order 0 to 3 from -10 to 10. + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> x = np.linspace(-10., 10., 1000) + >>> for i in range(4): + ... ax.plot(x, jv(i, x), label=f'$J_{i!r}$') + >>> ax.legend() + >>> plt.show() + + """) + +add_newdoc("jve", + r""" + jve(v, z, out=None) + + Exponentially scaled Bessel function of the first kind of order `v`. + + Defined as:: + + jve(v, z) = jv(v, z) * exp(-abs(z.imag)) + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function values + + Returns + ------- + J : scalar or ndarray + Value of the exponentially scaled Bessel function. + + See Also + -------- + jv: Unscaled Bessel function of the first kind + + Notes + ----- + For positive `v` values, the computation is carried out using the AMOS + [1]_ `zbesj` routine, which exploits the connection to the modified + Bessel function :math:`I_v`, + + .. math:: + J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0) + + J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0) + + For negative `v` values the formula, + + .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v) + + is used, where :math:`Y_v(z)` is the Bessel function of the second + kind, computed using the AMOS routine `zbesy`. Note that the second + term is exactly zero for integer `v`; to improve accuracy the second + term is explicitly omitted for `v` values such that `v = floor(v)`. + + Exponentially scaled Bessel functions are useful for large arguments `z`: + for these, the unscaled Bessel functions can easily under-or overflow. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + Compare the output of `jv` and `jve` for large complex arguments for `z` + by computing their values for order ``v=1`` at ``z=1000j``. We see that + `jv` overflows but `jve` returns a finite number: + + >>> import numpy as np + >>> from scipy.special import jv, jve + >>> v = 1 + >>> z = 1000j + >>> jv(v, z), jve(v, z) + ((inf+infj), (7.721967686709077e-19+0.012610930256928629j)) + + For real arguments for `z`, `jve` returns the same as `jv`. + + >>> v, z = 1, 1000 + >>> jv(v, z), jve(v, z) + (0.004728311907089523, 0.004728311907089523) + + The function can be evaluated for several orders at the same time by + providing a list or NumPy array for `v`: + + >>> jve([1, 3, 5], 1j) + array([1.27304208e-17+2.07910415e-01j, -4.99352086e-19-8.15530777e-03j, + 6.11480940e-21+9.98657141e-05j]) + + In the same way, the function can be evaluated at several points in one + call by providing a list or NumPy array for `z`: + + >>> jve(1, np.array([1j, 2j, 3j])) + array([1.27308412e-17+0.20791042j, 1.31814423e-17+0.21526929j, + 1.20521602e-17+0.19682671j]) + + It is also possible to evaluate several orders at several points + at the same time by providing arrays for `v` and `z` with + compatible shapes for broadcasting. Compute `jve` for two different orders + `v` and three points `z` resulting in a 2x3 array. + + >>> v = np.array([[1], [3]]) + >>> z = np.array([1j, 2j, 3j]) + >>> v.shape, z.shape + ((2, 1), (3,)) + + >>> jve(v, z) + array([[1.27304208e-17+0.20791042j, 1.31810070e-17+0.21526929j, + 1.20517622e-17+0.19682671j], + [-4.99352086e-19-0.00815531j, -1.76289571e-18-0.02879122j, + -2.92578784e-18-0.04778332j]]) + """) + +add_newdoc("kelvin", + """ + kelvin(x, out=None) + + Kelvin functions as complex numbers + + Parameters + ---------- + x : array_like + Argument + out : tuple of ndarray, optional + Optional output arrays for the function values + + Returns + ------- + Be, Ke, Bep, Kep : 4-tuple of scalar or ndarray + The tuple (Be, Ke, Bep, Kep) contains complex numbers + representing the real and imaginary Kelvin functions and their + derivatives evaluated at `x`. For example, kelvin(x)[0].real = + ber x and kelvin(x)[0].imag = bei x with similar relationships + for ker and kei. + """) + +add_newdoc("ker", + r""" + ker(x, out=None) + + Kelvin function ker. + + Defined as + + .. math:: + + \mathrm{ker}(x) = \Re[K_0(x e^{\pi i / 4})] + + Where :math:`K_0` is the modified Bessel function of the second + kind (see `kv`). See [dlmf]_ for more details. + + Parameters + ---------- + x : array_like + Real argument. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + Values of the Kelvin function. + + See Also + -------- + kei : the corresponding imaginary part + kerp : the derivative of ker + kv : modified Bessel function of the second kind + + References + ---------- + .. [dlmf] NIST, Digital Library of Mathematical Functions, + https://dlmf.nist.gov/10.61 + + Examples + -------- + It can be expressed using the modified Bessel function of the + second kind. + + >>> import numpy as np + >>> import scipy.special as sc + >>> x = np.array([1.0, 2.0, 3.0, 4.0]) + >>> sc.kv(0, x * np.exp(np.pi * 1j / 4)).real + array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885]) + >>> sc.ker(x) + array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885]) + + """) + +add_newdoc("kerp", + r""" + kerp(x, out=None) + + Derivative of the Kelvin function ker. + + Parameters + ---------- + x : array_like + Real argument. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + Values of the derivative of ker. + + See Also + -------- + ker + + References + ---------- + .. [dlmf] NIST, Digital Library of Mathematical Functions, + https://dlmf.nist.gov/10#PT5 + + """) + +add_newdoc("kl_div", + r""" + kl_div(x, y, out=None) + + Elementwise function for computing Kullback-Leibler divergence. + + .. math:: + + \mathrm{kl\_div}(x, y) = + \begin{cases} + x \log(x / y) - x + y & x > 0, y > 0 \\ + y & x = 0, y \ge 0 \\ + \infty & \text{otherwise} + \end{cases} + + Parameters + ---------- + x, y : array_like + Real arguments + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the Kullback-Liebler divergence. + + See Also + -------- + entr, rel_entr, scipy.stats.entropy + + Notes + ----- + .. versionadded:: 0.15.0 + + This function is non-negative and is jointly convex in `x` and `y`. + + The origin of this function is in convex programming; see [1]_ for + details. This is why the function contains the extra :math:`-x + + y` terms over what might be expected from the Kullback-Leibler + divergence. For a version of the function without the extra terms, + see `rel_entr`. + + References + ---------- + .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*. + Cambridge University Press, 2004. + :doi:`https://doi.org/10.1017/CBO9780511804441` + + """) + +add_newdoc("kn", + r""" + kn(n, x, out=None) + + Modified Bessel function of the second kind of integer order `n` + + Returns the modified Bessel function of the second kind for integer order + `n` at real `z`. + + These are also sometimes called functions of the third kind, Basset + functions, or Macdonald functions. + + Parameters + ---------- + n : array_like of int + Order of Bessel functions (floats will truncate with a warning) + x : array_like of float + Argument at which to evaluate the Bessel functions + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + Value of the Modified Bessel function of the second kind, + :math:`K_n(x)`. + + See Also + -------- + kv : Same function, but accepts real order and complex argument + kvp : Derivative of this function + + Notes + ----- + Wrapper for AMOS [1]_ routine `zbesk`. For a discussion of the + algorithm used, see [2]_ and the references therein. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel + functions of a complex argument and nonnegative order", ACM + TOMS Vol. 12 Issue 3, Sept. 1986, p. 265 + + Examples + -------- + Plot the function of several orders for real input: + + >>> import numpy as np + >>> from scipy.special import kn + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0, 5, 1000) + >>> for N in range(6): + ... plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N)) + >>> plt.ylim(0, 10) + >>> plt.legend() + >>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$') + >>> plt.show() + + Calculate for a single value at multiple orders: + + >>> kn([4, 5, 6], 1) + array([ 44.23241585, 360.9605896 , 3653.83831186]) + """) + +add_newdoc("kolmogi", + """ + kolmogi(p, out=None) + + Inverse Survival Function of Kolmogorov distribution + + It is the inverse function to `kolmogorov`. + Returns y such that ``kolmogorov(y) == p``. + + Parameters + ---------- + p : float array_like + Probability + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The value(s) of kolmogi(p) + + See Also + -------- + kolmogorov : The Survival Function for the distribution + scipy.stats.kstwobign : Provides the functionality as a continuous distribution + smirnov, smirnovi : Functions for the one-sided distribution + + Notes + ----- + `kolmogorov` is used by `stats.kstest` in the application of the + Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this + function is exposed in `scpy.special`, but the recommended way to achieve + the most accurate CDF/SF/PDF/PPF/ISF computations is to use the + `stats.kstwobign` distribution. + + Examples + -------- + >>> from scipy.special import kolmogi + >>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0]) + array([ inf, 1.22384787, 1.01918472, 0.82757356, 0.67644769, + 0.57117327, 0. ]) + + """) + +add_newdoc("kolmogorov", + r""" + kolmogorov(y, out=None) + + Complementary cumulative distribution (Survival Function) function of + Kolmogorov distribution. + + Returns the complementary cumulative distribution function of + Kolmogorov's limiting distribution (``D_n*\sqrt(n)`` as n goes to infinity) + of a two-sided test for equality between an empirical and a theoretical + distribution. It is equal to the (limit as n->infinity of the) + probability that ``sqrt(n) * max absolute deviation > y``. + + Parameters + ---------- + y : float array_like + Absolute deviation between the Empirical CDF (ECDF) and the target CDF, + multiplied by sqrt(n). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The value(s) of kolmogorov(y) + + See Also + -------- + kolmogi : The Inverse Survival Function for the distribution + scipy.stats.kstwobign : Provides the functionality as a continuous distribution + smirnov, smirnovi : Functions for the one-sided distribution + + Notes + ----- + `kolmogorov` is used by `stats.kstest` in the application of the + Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this + function is exposed in `scpy.special`, but the recommended way to achieve + the most accurate CDF/SF/PDF/PPF/ISF computations is to use the + `stats.kstwobign` distribution. + + Examples + -------- + Show the probability of a gap at least as big as 0, 0.5 and 1.0. + + >>> import numpy as np + >>> from scipy.special import kolmogorov + >>> from scipy.stats import kstwobign + >>> kolmogorov([0, 0.5, 1.0]) + array([ 1. , 0.96394524, 0.26999967]) + + Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against + the target distribution, a Normal(0, 1) distribution. + + >>> from scipy.stats import norm, laplace + >>> rng = np.random.default_rng() + >>> n = 1000 + >>> lap01 = laplace(0, 1) + >>> x = np.sort(lap01.rvs(n, random_state=rng)) + >>> np.mean(x), np.std(x) + (-0.05841730131499543, 1.3968109101997568) + + Construct the Empirical CDF and the K-S statistic Dn. + + >>> target = norm(0,1) # Normal mean 0, stddev 1 + >>> cdfs = target.cdf(x) + >>> ecdfs = np.arange(n+1, dtype=float)/n + >>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs]) + >>> Dn = np.max(gaps) + >>> Kn = np.sqrt(n) * Dn + >>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn)) + Dn=0.043363, sqrt(n)*Dn=1.371265 + >>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:', + ... ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' % + ... (Kn, kolmogorov(Kn)), + ... ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' % + ... (Kn, kstwobign.cdf(Kn))])) + For a sample of size n drawn from a N(0, 1) distribution: + the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533 + the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467 + + Plot the Empirical CDF against the target N(0, 1) CDF. + + >>> import matplotlib.pyplot as plt + >>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF') + >>> x3 = np.linspace(-3, 3, 100) + >>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)') + >>> plt.ylim([0, 1]); plt.grid(True); plt.legend(); + >>> # Add vertical lines marking Dn+ and Dn- + >>> iminus, iplus = np.argmax(gaps, axis=0) + >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], + ... color='r', linestyle='dashed', lw=4) + >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], + ... color='r', linestyle='dashed', lw=4) + >>> plt.show() + """) + +add_newdoc("_kolmogc", + r""" + Internal function, do not use. + """) + +add_newdoc("_kolmogci", + r""" + Internal function, do not use. + """) + +add_newdoc("_kolmogp", + r""" + Internal function, do not use. + """) + +add_newdoc("kv", + r""" + kv(v, z, out=None) + + Modified Bessel function of the second kind of real order `v` + + Returns the modified Bessel function of the second kind for real order + `v` at complex `z`. + + These are also sometimes called functions of the third kind, Basset + functions, or Macdonald functions. They are defined as those solutions + of the modified Bessel equation for which, + + .. math:: + K_v(x) \sim \sqrt{\pi/(2x)} \exp(-x) + + as :math:`x \to \infty` [3]_. + + Parameters + ---------- + v : array_like of float + Order of Bessel functions + z : array_like of complex + Argument at which to evaluate the Bessel functions + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The results. Note that input must be of complex type to get complex + output, e.g. ``kv(3, -2+0j)`` instead of ``kv(3, -2)``. + + See Also + -------- + kve : This function with leading exponential behavior stripped off. + kvp : Derivative of this function + + Notes + ----- + Wrapper for AMOS [1]_ routine `zbesk`. For a discussion of the + algorithm used, see [2]_ and the references therein. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel + functions of a complex argument and nonnegative order", ACM + TOMS Vol. 12 Issue 3, Sept. 1986, p. 265 + .. [3] NIST Digital Library of Mathematical Functions, + Eq. 10.25.E3. https://dlmf.nist.gov/10.25.E3 + + Examples + -------- + Plot the function of several orders for real input: + + >>> import numpy as np + >>> from scipy.special import kv + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0, 5, 1000) + >>> for N in np.linspace(0, 6, 5): + ... plt.plot(x, kv(N, x), label='$K_{{{}}}(x)$'.format(N)) + >>> plt.ylim(0, 10) + >>> plt.legend() + >>> plt.title(r'Modified Bessel function of the second kind $K_\nu(x)$') + >>> plt.show() + + Calculate for a single value at multiple orders: + + >>> kv([4, 4.5, 5], 1+2j) + array([ 0.1992+2.3892j, 2.3493+3.6j , 7.2827+3.8104j]) + + """) + +add_newdoc("kve", + r""" + kve(v, z, out=None) + + Exponentially scaled modified Bessel function of the second kind. + + Returns the exponentially scaled, modified Bessel function of the + second kind (sometimes called the third kind) for real order `v` at + complex `z`:: + + kve(v, z) = kv(v, z) * exp(z) + + Parameters + ---------- + v : array_like of float + Order of Bessel functions + z : array_like of complex + Argument at which to evaluate the Bessel functions + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The exponentially scaled modified Bessel function of the second kind. + + See Also + -------- + kv : This function without exponential scaling. + k0e : Faster version of this function for order 0. + k1e : Faster version of this function for order 1. + + Notes + ----- + Wrapper for AMOS [1]_ routine `zbesk`. For a discussion of the + algorithm used, see [2]_ and the references therein. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel + functions of a complex argument and nonnegative order", ACM + TOMS Vol. 12 Issue 3, Sept. 1986, p. 265 + + Examples + -------- + In the following example `kv` returns 0 whereas `kve` still returns + a useful finite number. + + >>> import numpy as np + >>> from scipy.special import kv, kve + >>> import matplotlib.pyplot as plt + >>> kv(3, 1000.), kve(3, 1000.) + (0.0, 0.03980696128440973) + + Evaluate the function at one point for different orders by + providing a list or NumPy array as argument for the `v` parameter: + + >>> kve([0, 1, 1.5], 1.) + array([1.14446308, 1.63615349, 2.50662827]) + + Evaluate the function at several points for order 0 by providing an + array for `z`. + + >>> points = np.array([1., 3., 10.]) + >>> kve(0, points) + array([1.14446308, 0.6977616 , 0.39163193]) + + Evaluate the function at several points for different orders by + providing arrays for both `v` for `z`. Both arrays have to be + broadcastable to the correct shape. To calculate the orders 0, 1 + and 2 for a 1D array of points: + + >>> kve([[0], [1], [2]], points) + array([[1.14446308, 0.6977616 , 0.39163193], + [1.63615349, 0.80656348, 0.41076657], + [4.41677005, 1.23547058, 0.47378525]]) + + Plot the functions of order 0 to 3 from 0 to 5. + + >>> fig, ax = plt.subplots() + >>> x = np.linspace(0., 5., 1000) + >>> for i in range(4): + ... ax.plot(x, kve(i, x), label=fr'$K_{i!r}(z)\cdot e^z$') + >>> ax.legend() + >>> ax.set_xlabel(r"$z$") + >>> ax.set_ylim(0, 4) + >>> ax.set_xlim(0, 5) + >>> plt.show() + """) + +add_newdoc("_lanczos_sum_expg_scaled", + """ + Internal function, do not use. + """) + +add_newdoc( + "_landau_pdf", + """ + _landau_pdf(x, loc, scale) + + Probability density function of the Landau distribution. + + Parameters + ---------- + x : array_like + Real-valued argument + loc : array_like + Real-valued distribution location + scale : array_like + Positive, real-valued distribution scale + + Returns + ------- + scalar or ndarray + """) + +add_newdoc( + "_landau_cdf", + """ + _landau_cdf(x, loc, scale) + + Cumulative distribution function of the Landau distribution. + + Parameters + ---------- + x : array_like + Real-valued argument + loc : array_like + Real-valued distribution location + scale : array_like + Positive, real-valued distribution scale + + Returns + ------- + scalar or ndarray + """) + +add_newdoc( + "_landau_sf", + """ + _landau_sf(x, loc, scale) + + Survival function of the Landau distribution. + + Parameters + ---------- + x : array_like + Real-valued argument + loc : array_like + Real-valued distribution location + scale : array_like + Positive, real-valued distribution scale + + Returns + ------- + scalar or ndarray + """) + +add_newdoc( + "_landau_ppf", + """ + _landau_ppf(p, loc, scale) + + Percent point function of the Landau distribution. + + Parameters + ---------- + p : array_like + Real-valued argument between 0 and 1 + loc : array_like + Real-valued distribution location + scale : array_like + Positive, real-valued distribution scale + + Returns + ------- + scalar or ndarray + """) + +add_newdoc( + "_landau_isf", + """ + _landau_isf(p, loc, scale) + + Inverse survival function of the Landau distribution. + + Parameters + ---------- + p : array_like + Real-valued argument between 0 and 1 + loc : array_like + Real-valued distribution location + scale : array_like + Positive, real-valued distribution scale + + Returns + ------- + scalar or ndarray + """) + +add_newdoc("_lgam1p", + """ + Internal function, do not use. + """) + +add_newdoc("log1p", + """ + log1p(x, out=None) + + Calculates log(1 + x) for use when `x` is near zero. + + Parameters + ---------- + x : array_like + Real or complex valued input. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + Values of ``log(1 + x)``. + + See Also + -------- + expm1, cosm1 + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It is more accurate than using ``log(1 + x)`` directly for ``x`` + near 0. Note that in the below example ``1 + 1e-17 == 1`` to + double precision. + + >>> sc.log1p(1e-17) + 1e-17 + >>> np.log(1 + 1e-17) + 0.0 + + """) + +add_newdoc("_log1pmx", + """ + Internal function, do not use. + """) + +add_newdoc("lpmv", + r""" + lpmv(m, v, x, out=None) + + Associated Legendre function of integer order and real degree. + + Defined as + + .. math:: + + P_v^m = (-1)^m (1 - x^2)^{m/2} \frac{d^m}{dx^m} P_v(x) + + where + + .. math:: + + P_v = \sum_{k = 0}^\infty \frac{(-v)_k (v + 1)_k}{(k!)^2} + \left(\frac{1 - x}{2}\right)^k + + is the Legendre function of the first kind. Here :math:`(\cdot)_k` + is the Pochhammer symbol; see `poch`. + + Parameters + ---------- + m : array_like + Order (int or float). If passed a float not equal to an + integer the function returns NaN. + v : array_like + Degree (float). + x : array_like + Argument (float). Must have ``|x| <= 1``. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + pmv : scalar or ndarray + Value of the associated Legendre function. + + See Also + -------- + lpmn : Compute the associated Legendre function for all orders + ``0, ..., m`` and degrees ``0, ..., n``. + clpmn : Compute the associated Legendre function at complex + arguments. + + Notes + ----- + Note that this implementation includes the Condon-Shortley phase. + + References + ---------- + .. [1] Zhang, Jin, "Computation of Special Functions", John Wiley + and Sons, Inc, 1996. + + """) + +add_newdoc("nbdtr", + r""" + nbdtr(k, n, p, out=None) + + Negative binomial cumulative distribution function. + + Returns the sum of the terms 0 through `k` of the negative binomial + distribution probability mass function, + + .. math:: + + F = \sum_{j=0}^k {{n + j - 1}\choose{j}} p^n (1 - p)^j. + + In a sequence of Bernoulli trials with individual success probabilities + `p`, this is the probability that `k` or fewer failures precede the nth + success. + + Parameters + ---------- + k : array_like + The maximum number of allowed failures (nonnegative int). + n : array_like + The target number of successes (positive int). + p : array_like + Probability of success in a single event (float). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + F : scalar or ndarray + The probability of `k` or fewer failures before `n` successes in a + sequence of events with individual success probability `p`. + + See Also + -------- + nbdtrc : Negative binomial survival function + nbdtrik : Negative binomial quantile function + scipy.stats.nbinom : Negative binomial distribution + + Notes + ----- + If floating point values are passed for `k` or `n`, they will be truncated + to integers. + + The terms are not summed directly; instead the regularized incomplete beta + function is employed, according to the formula, + + .. math:: + \mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1). + + Wrapper for the Cephes [1]_ routine `nbdtr`. + + The negative binomial distribution is also available as + `scipy.stats.nbinom`. Using `nbdtr` directly can improve performance + compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example). + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``. + + >>> import numpy as np + >>> from scipy.special import nbdtr + >>> nbdtr(10, 5, 0.5) + 0.940765380859375 + + Compute the function for ``n=10`` and ``p=0.5`` at several points by + providing a NumPy array or list for `k`. + + >>> nbdtr([5, 10, 15], 10, 0.5) + array([0.15087891, 0.58809853, 0.88523853]) + + Plot the function for four different parameter sets. + + >>> import matplotlib.pyplot as plt + >>> k = np.arange(130) + >>> n_parameters = [20, 20, 20, 80] + >>> p_parameters = [0.2, 0.5, 0.8, 0.5] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(p_parameters, n_parameters, + ... linestyles)) + >>> fig, ax = plt.subplots(figsize=(8, 8)) + >>> for parameter_set in parameters_list: + ... p, n, style = parameter_set + ... nbdtr_vals = nbdtr(k, n, p) + ... ax.plot(k, nbdtr_vals, label=rf"$n={n},\, p={p}$", + ... ls=style) + >>> ax.legend() + >>> ax.set_xlabel("$k$") + >>> ax.set_title("Negative binomial cumulative distribution function") + >>> plt.show() + + The negative binomial distribution is also available as + `scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than + calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small + arrays or individual values. To get the same results one must use the + following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``. + + >>> from scipy.stats import nbinom + >>> k, n, p = 5, 3, 0.5 + >>> nbdtr_res = nbdtr(k, n, p) # this will often be faster than below + >>> stats_res = nbinom(n, p).cdf(k) + >>> stats_res, nbdtr_res # test that results are equal + (0.85546875, 0.85546875) + + `nbdtr` can evaluate different parameter sets by providing arrays with + shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute + the function for three different `k` at four locations `p`, resulting in + a 3x4 array. + + >>> k = np.array([[5], [10], [15]]) + >>> p = np.array([0.3, 0.5, 0.7, 0.9]) + >>> k.shape, p.shape + ((3, 1), (4,)) + + >>> nbdtr(k, 5, p) + array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ], + [0.48450894, 0.94076538, 0.99932777, 0.99999999], + [0.76249222, 0.99409103, 0.99999445, 1. ]]) + """) + +add_newdoc("nbdtrc", + r""" + nbdtrc(k, n, p, out=None) + + Negative binomial survival function. + + Returns the sum of the terms `k + 1` to infinity of the negative binomial + distribution probability mass function, + + .. math:: + + F = \sum_{j=k + 1}^\infty {{n + j - 1}\choose{j}} p^n (1 - p)^j. + + In a sequence of Bernoulli trials with individual success probabilities + `p`, this is the probability that more than `k` failures precede the nth + success. + + Parameters + ---------- + k : array_like + The maximum number of allowed failures (nonnegative int). + n : array_like + The target number of successes (positive int). + p : array_like + Probability of success in a single event (float). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + F : scalar or ndarray + The probability of `k + 1` or more failures before `n` successes in a + sequence of events with individual success probability `p`. + + See Also + -------- + nbdtr : Negative binomial cumulative distribution function + nbdtrik : Negative binomial percentile function + scipy.stats.nbinom : Negative binomial distribution + + Notes + ----- + If floating point values are passed for `k` or `n`, they will be truncated + to integers. + + The terms are not summed directly; instead the regularized incomplete beta + function is employed, according to the formula, + + .. math:: + \mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n). + + Wrapper for the Cephes [1]_ routine `nbdtrc`. + + The negative binomial distribution is also available as + `scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance + compared to the ``sf`` method of `scipy.stats.nbinom` (see last example). + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``. + + >>> import numpy as np + >>> from scipy.special import nbdtrc + >>> nbdtrc(10, 5, 0.5) + 0.059234619140624986 + + Compute the function for ``n=10`` and ``p=0.5`` at several points by + providing a NumPy array or list for `k`. + + >>> nbdtrc([5, 10, 15], 10, 0.5) + array([0.84912109, 0.41190147, 0.11476147]) + + Plot the function for four different parameter sets. + + >>> import matplotlib.pyplot as plt + >>> k = np.arange(130) + >>> n_parameters = [20, 20, 20, 80] + >>> p_parameters = [0.2, 0.5, 0.8, 0.5] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(p_parameters, n_parameters, + ... linestyles)) + >>> fig, ax = plt.subplots(figsize=(8, 8)) + >>> for parameter_set in parameters_list: + ... p, n, style = parameter_set + ... nbdtrc_vals = nbdtrc(k, n, p) + ... ax.plot(k, nbdtrc_vals, label=rf"$n={n},\, p={p}$", + ... ls=style) + >>> ax.legend() + >>> ax.set_xlabel("$k$") + >>> ax.set_title("Negative binomial distribution survival function") + >>> plt.show() + + The negative binomial distribution is also available as + `scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than + calling the ``sf`` method of `scipy.stats.nbinom`, especially for small + arrays or individual values. To get the same results one must use the + following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``. + + >>> from scipy.stats import nbinom + >>> k, n, p = 3, 5, 0.5 + >>> nbdtr_res = nbdtrc(k, n, p) # this will often be faster than below + >>> stats_res = nbinom(n, p).sf(k) + >>> stats_res, nbdtr_res # test that results are equal + (0.6367187499999999, 0.6367187499999999) + + `nbdtrc` can evaluate different parameter sets by providing arrays with + shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute + the function for three different `k` at four locations `p`, resulting in + a 3x4 array. + + >>> k = np.array([[5], [10], [15]]) + >>> p = np.array([0.3, 0.5, 0.7, 0.9]) + >>> k.shape, p.shape + ((3, 1), (4,)) + + >>> nbdtrc(k, 5, p) + array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04], + [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09], + [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]]) + """) + +add_newdoc( + "nbdtri", + r""" + nbdtri(k, n, y, out=None) + + Returns the inverse with respect to the parameter `p` of + ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution + function. + + Parameters + ---------- + k : array_like + The maximum number of allowed failures (nonnegative int). + n : array_like + The target number of successes (positive int). + y : array_like + The probability of `k` or fewer failures before `n` successes (float). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + p : scalar or ndarray + Probability of success in a single event (float) such that + `nbdtr(k, n, p) = y`. + + See Also + -------- + nbdtr : Cumulative distribution function of the negative binomial. + nbdtrc : Negative binomial survival function. + scipy.stats.nbinom : negative binomial distribution. + nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`. + nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`. + scipy.stats.nbinom : Negative binomial distribution + + Notes + ----- + Wrapper for the Cephes [1]_ routine `nbdtri`. + + The negative binomial distribution is also available as + `scipy.stats.nbinom`. Using `nbdtri` directly can improve performance + compared to the ``ppf`` method of `scipy.stats.nbinom`. + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + `nbdtri` is the inverse of `nbdtr` with respect to `p`. + Up to floating point errors the following holds: + ``nbdtri(k, n, nbdtr(k, n, p))=p``. + + >>> import numpy as np + >>> from scipy.special import nbdtri, nbdtr + >>> k, n, y = 5, 10, 0.2 + >>> cdf_val = nbdtr(k, n, y) + >>> nbdtri(k, n, cdf_val) + 0.20000000000000004 + + Compute the function for ``k=10`` and ``n=5`` at several points by + providing a NumPy array or list for `y`. + + >>> y = np.array([0.1, 0.4, 0.8]) + >>> nbdtri(3, 5, y) + array([0.34462319, 0.51653095, 0.69677416]) + + Plot the function for three different parameter sets. + + >>> import matplotlib.pyplot as plt + >>> n_parameters = [5, 20, 30, 30] + >>> k_parameters = [20, 20, 60, 80] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(n_parameters, k_parameters, linestyles)) + >>> cdf_vals = np.linspace(0, 1, 1000) + >>> fig, ax = plt.subplots(figsize=(8, 8)) + >>> for parameter_set in parameters_list: + ... n, k, style = parameter_set + ... nbdtri_vals = nbdtri(k, n, cdf_vals) + ... ax.plot(cdf_vals, nbdtri_vals, label=rf"$k={k},\ n={n}$", + ... ls=style) + >>> ax.legend() + >>> ax.set_ylabel("$p$") + >>> ax.set_xlabel("$CDF$") + >>> title = "nbdtri: inverse of negative binomial CDF with respect to $p$" + >>> ax.set_title(title) + >>> plt.show() + + `nbdtri` can evaluate different parameter sets by providing arrays with + shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute + the function for three different `k` at four locations `p`, resulting in + a 3x4 array. + + >>> k = np.array([[5], [10], [15]]) + >>> y = np.array([0.3, 0.5, 0.7, 0.9]) + >>> k.shape, y.shape + ((3, 1), (4,)) + + >>> nbdtri(k, 5, y) + array([[0.37258157, 0.45169416, 0.53249956, 0.64578407], + [0.24588501, 0.30451981, 0.36778453, 0.46397088], + [0.18362101, 0.22966758, 0.28054743, 0.36066188]]) + """) + +add_newdoc("nbdtrik", + r""" + nbdtrik(y, n, p, out=None) + + Negative binomial percentile function. + + Returns the inverse with respect to the parameter `k` of + ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution + function. + + Parameters + ---------- + y : array_like + The probability of `k` or fewer failures before `n` successes (float). + n : array_like + The target number of successes (positive int). + p : array_like + Probability of success in a single event (float). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + k : scalar or ndarray + The maximum number of allowed failures such that `nbdtr(k, n, p) = y`. + + See Also + -------- + nbdtr : Cumulative distribution function of the negative binomial. + nbdtrc : Survival function of the negative binomial. + nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`. + nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`. + scipy.stats.nbinom : Negative binomial distribution + + Notes + ----- + Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`. + + Formula 26.5.26 of [2]_, + + .. math:: + \sum_{j=k + 1}^\infty {{n + j - 1} + \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n), + + is used to reduce calculation of the cumulative distribution function to + that of a regularized incomplete beta :math:`I`. + + Computation of `k` involves a search for a value that produces the desired + value of `y`. The search relies on the monotonicity of `y` with `k`. + + References + ---------- + .. [1] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + .. [2] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + Compute the negative binomial cumulative distribution function for an + exemplary parameter set. + + >>> import numpy as np + >>> from scipy.special import nbdtr, nbdtrik + >>> k, n, p = 5, 2, 0.5 + >>> cdf_value = nbdtr(k, n, p) + >>> cdf_value + 0.9375 + + Verify that `nbdtrik` recovers the original value for `k`. + + >>> nbdtrik(cdf_value, n, p) + 5.0 + + Plot the function for different parameter sets. + + >>> import matplotlib.pyplot as plt + >>> p_parameters = [0.2, 0.5, 0.7, 0.5] + >>> n_parameters = [30, 30, 30, 80] + >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot'] + >>> parameters_list = list(zip(p_parameters, n_parameters, linestyles)) + >>> cdf_vals = np.linspace(0, 1, 1000) + >>> fig, ax = plt.subplots(figsize=(8, 8)) + >>> for parameter_set in parameters_list: + ... p, n, style = parameter_set + ... nbdtrik_vals = nbdtrik(cdf_vals, n, p) + ... ax.plot(cdf_vals, nbdtrik_vals, label=rf"$n={n},\ p={p}$", + ... ls=style) + >>> ax.legend() + >>> ax.set_ylabel("$k$") + >>> ax.set_xlabel("$CDF$") + >>> ax.set_title("Negative binomial percentile function") + >>> plt.show() + + The negative binomial distribution is also available as + `scipy.stats.nbinom`. The percentile function method ``ppf`` + returns the result of `nbdtrik` rounded up to integers: + + >>> from scipy.stats import nbinom + >>> q, n, p = 0.6, 5, 0.5 + >>> nbinom.ppf(q, n, p), nbdtrik(q, n, p) + (5.0, 4.800428460273882) + + """) + +add_newdoc("nbdtrin", + r""" + nbdtrin(k, y, p, out=None) + + Inverse of `nbdtr` vs `n`. + + Returns the inverse with respect to the parameter `n` of + ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution + function. + + Parameters + ---------- + k : array_like + The maximum number of allowed failures (nonnegative int). + y : array_like + The probability of `k` or fewer failures before `n` successes (float). + p : array_like + Probability of success in a single event (float). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + n : scalar or ndarray + The number of successes `n` such that `nbdtr(k, n, p) = y`. + + See Also + -------- + nbdtr : Cumulative distribution function of the negative binomial. + nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`. + nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`. + + Notes + ----- + Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`. + + Formula 26.5.26 of [2]_, + + .. math:: + \sum_{j=k + 1}^\infty {{n + j - 1} + \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n), + + is used to reduce calculation of the cumulative distribution function to + that of a regularized incomplete beta :math:`I`. + + Computation of `n` involves a search for a value that produces the desired + value of `y`. The search relies on the monotonicity of `y` with `n`. + + References + ---------- + .. [1] Barry Brown, James Lovato, and Kathy Russell, + CDFLIB: Library of Fortran Routines for Cumulative Distribution + Functions, Inverses, and Other Parameters. + .. [2] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + Compute the negative binomial cumulative distribution function for an + exemplary parameter set. + + >>> from scipy.special import nbdtr, nbdtrin + >>> k, n, p = 5, 2, 0.5 + >>> cdf_value = nbdtr(k, n, p) + >>> cdf_value + 0.9375 + + Verify that `nbdtrin` recovers the original value for `n` up to floating + point accuracy. + + >>> nbdtrin(k, cdf_value, p) + 1.999999999998137 + """) + +add_newdoc("ncfdtr", + r""" + ncfdtr(dfn, dfd, nc, f, out=None) + + Cumulative distribution function of the non-central F distribution. + + The non-central F describes the distribution of, + + .. math:: + Z = \frac{X/d_n}{Y/d_d} + + where :math:`X` and :math:`Y` are independently distributed, with + :math:`X` distributed non-central :math:`\chi^2` with noncentrality + parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y` + distributed :math:`\chi^2` with :math:`d_d` degrees of freedom. + + Parameters + ---------- + dfn : array_like + Degrees of freedom of the numerator sum of squares. Range (0, inf). + dfd : array_like + Degrees of freedom of the denominator sum of squares. Range (0, inf). + nc : array_like + Noncentrality parameter. Range [0, inf). + f : array_like + Quantiles, i.e. the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + cdf : scalar or ndarray + The calculated CDF. If all inputs are scalar, the return will be a + float. Otherwise it will be an array. + + See Also + -------- + ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`. + ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`. + ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`. + ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`. + scipy.stats.ncf : Non-central F distribution. + + Notes + ----- + This function calculates the CDF of the non-central f distribution using + the Boost Math C++ library [1]_. + + The cumulative distribution function is computed using Formula 26.6.20 of + [2]_: + + .. math:: + F(d_n, d_d, n_c, f) = \sum_{j=0}^\infty e^{-n_c/2} + \frac{(n_c/2)^j}{j!} I_{x}(\frac{d_n}{2} + j, \frac{d_d}{2}), + + where :math:`I` is the regularized incomplete beta function, and + :math:`x = f d_n/(f d_n + d_d)`. + + Note that argument order of `ncfdtr` is different from that of the + similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last + parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``. + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + .. [2] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Plot the CDF of the non-central F distribution, for nc=0. Compare with the + F-distribution from scipy.stats: + + >>> x = np.linspace(-1, 8, num=500) + >>> dfn = 3 + >>> dfd = 2 + >>> ncf_stats = stats.f.cdf(x, dfn, dfd) + >>> ncf_special = special.ncfdtr(dfn, dfd, 0, x) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(x, ncf_stats, 'b-', lw=3) + >>> ax.plot(x, ncf_special, 'r-') + >>> plt.show() + + """) + +add_newdoc("ncfdtri", + """ + ncfdtri(dfn, dfd, nc, p, out=None) + + Inverse with respect to `f` of the CDF of the non-central F distribution. + + See `ncfdtr` for more details. + + Parameters + ---------- + dfn : array_like + Degrees of freedom of the numerator sum of squares. Range (0, inf). + dfd : array_like + Degrees of freedom of the denominator sum of squares. Range (0, inf). + nc : array_like + Noncentrality parameter. Range [0, inf). + p : array_like + Value of the cumulative distribution function. Must be in the + range [0, 1]. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + f : scalar or ndarray + Quantiles, i.e., the upper limit of integration. + + See Also + -------- + ncfdtr : CDF of the non-central F distribution. + ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`. + ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`. + ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`. + scipy.stats.ncf : Non-central F distribution. + + Notes + ----- + This function calculates the Quantile of the non-central f distribution + using the Boost Math C++ library [1]_. + + Note that argument order of `ncfdtri` is different from that of the + similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter + of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``. + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> from scipy.special import ncfdtr, ncfdtri + + Compute the CDF for several values of `f`: + + >>> f = [0.5, 1, 1.5] + >>> p = ncfdtr(2, 3, 1.5, f) + >>> p + array([ 0.20782291, 0.36107392, 0.47345752]) + + Compute the inverse. We recover the values of `f`, as expected: + + >>> ncfdtri(2, 3, 1.5, p) + array([ 0.5, 1. , 1.5]) + + """) + +add_newdoc("ncfdtridfd", + """ + ncfdtridfd(dfn, p, nc, f, out=None) + + Calculate degrees of freedom (denominator) for the noncentral F-distribution. + + This is the inverse with respect to `dfd` of `ncfdtr`. + See `ncfdtr` for more details. + + Parameters + ---------- + dfn : array_like + Degrees of freedom of the numerator sum of squares. Range (0, inf). + p : array_like + Value of the cumulative distribution function. Must be in the + range [0, 1]. + nc : array_like + Noncentrality parameter. Should be in range (0, 1e4). + f : array_like + Quantiles, i.e., the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + dfd : scalar or ndarray + Degrees of freedom of the denominator sum of squares. + + See Also + -------- + ncfdtr : CDF of the non-central F distribution. + ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`. + ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`. + ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`. + + Notes + ----- + The value of the cumulative noncentral F distribution is not necessarily + monotone in either degrees of freedom. There thus may be two values that + provide a given CDF value. This routine assumes monotonicity and will + find an arbitrary one of the two values. + + Examples + -------- + >>> from scipy.special import ncfdtr, ncfdtridfd + + Compute the CDF for several values of `dfd`: + + >>> dfd = [1, 2, 3] + >>> p = ncfdtr(2, dfd, 0.25, 15) + >>> p + array([ 0.8097138 , 0.93020416, 0.96787852]) + + Compute the inverse. We recover the values of `dfd`, as expected: + + >>> ncfdtridfd(2, p, 0.25, 15) + array([ 1., 2., 3.]) + + """) + +add_newdoc("ncfdtridfn", + """ + ncfdtridfn(p, dfd, nc, f, out=None) + + Calculate degrees of freedom (numerator) for the noncentral F-distribution. + + This is the inverse with respect to `dfn` of `ncfdtr`. + See `ncfdtr` for more details. + + Parameters + ---------- + p : array_like + Value of the cumulative distribution function. Must be in the + range [0, 1]. + dfd : array_like + Degrees of freedom of the denominator sum of squares. Range (0, inf). + nc : array_like + Noncentrality parameter. Should be in range (0, 1e4). + f : float + Quantiles, i.e., the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + dfn : scalar or ndarray + Degrees of freedom of the numerator sum of squares. + + See Also + -------- + ncfdtr : CDF of the non-central F distribution. + ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`. + ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`. + ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`. + + Notes + ----- + The value of the cumulative noncentral F distribution is not necessarily + monotone in either degrees of freedom. There thus may be two values that + provide a given CDF value. This routine assumes monotonicity and will + find an arbitrary one of the two values. + + Examples + -------- + >>> from scipy.special import ncfdtr, ncfdtridfn + + Compute the CDF for several values of `dfn`: + + >>> dfn = [1, 2, 3] + >>> p = ncfdtr(dfn, 2, 0.25, 15) + >>> p + array([ 0.92562363, 0.93020416, 0.93188394]) + + Compute the inverse. We recover the values of `dfn`, as expected: + + >>> ncfdtridfn(p, 2, 0.25, 15) + array([ 1., 2., 3.]) + + """) + +add_newdoc("ncfdtrinc", + """ + ncfdtrinc(dfn, dfd, p, f, out=None) + + Calculate non-centrality parameter for non-central F distribution. + + This is the inverse with respect to `nc` of `ncfdtr`. + See `ncfdtr` for more details. + + Parameters + ---------- + dfn : array_like + Degrees of freedom of the numerator sum of squares. Range (0, inf). + dfd : array_like + Degrees of freedom of the denominator sum of squares. Range (0, inf). + p : array_like + Value of the cumulative distribution function. Must be in the + range [0, 1]. + f : array_like + Quantiles, i.e., the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + nc : scalar or ndarray + Noncentrality parameter. + + See Also + -------- + ncfdtr : CDF of the non-central F distribution. + ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`. + ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`. + ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`. + + Examples + -------- + >>> from scipy.special import ncfdtr, ncfdtrinc + + Compute the CDF for several values of `nc`: + + >>> nc = [0.5, 1.5, 2.0] + >>> p = ncfdtr(2, 3, nc, 15) + >>> p + array([ 0.96309246, 0.94327955, 0.93304098]) + + Compute the inverse. We recover the values of `nc`, as expected: + + >>> ncfdtrinc(2, 3, p, 15) + array([ 0.5, 1.5, 2. ]) + + """) + +add_newdoc("nctdtr", + """ + nctdtr(df, nc, t, out=None) + + Cumulative distribution function of the non-central `t` distribution. + + Parameters + ---------- + df : array_like + Degrees of freedom of the distribution. Should be in range (0, inf). + nc : array_like + Noncentrality parameter. + t : array_like + Quantiles, i.e., the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + cdf : scalar or ndarray + The calculated CDF. If all inputs are scalar, the return will be a + float. Otherwise, it will be an array. + + See Also + -------- + nctdtrit : Inverse CDF (iCDF) of the non-central t distribution. + nctdtridf : Calculate degrees of freedom, given CDF and iCDF values. + nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values. + + Notes + ----- + This function calculates the CDF of the non-central t distribution using + the Boost Math C++ library [1]_. + + Note that the argument order of `nctdtr` is different from that of the + similar ``cdf`` method of `scipy.stats.nct`: `t` is the last + parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``. + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Plot the CDF of the non-central t distribution, for nc=0. Compare with the + t-distribution from scipy.stats: + + >>> x = np.linspace(-5, 5, num=500) + >>> df = 3 + >>> nct_stats = stats.t.cdf(x, df) + >>> nct_special = special.nctdtr(df, 0, x) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(x, nct_stats, 'b-', lw=3) + >>> ax.plot(x, nct_special, 'r-') + >>> plt.show() + + """) + +add_newdoc("nctdtridf", + """ + nctdtridf(p, nc, t, out=None) + + Calculate degrees of freedom for non-central t distribution. + + See `nctdtr` for more details. + + Parameters + ---------- + p : array_like + CDF values, in range (0, 1]. + nc : array_like + Noncentrality parameter. Should be in range (-1e6, 1e6). + t : array_like + Quantiles, i.e., the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + df : scalar or ndarray + The degrees of freedom. If all inputs are scalar, the return will be a + float. Otherwise, it will be an array. + + See Also + -------- + nctdtr : CDF of the non-central `t` distribution. + nctdtrit : Inverse CDF (iCDF) of the non-central t distribution. + nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values. + + Examples + -------- + >>> from scipy.special import nctdtr, nctdtridf + + Compute the CDF for several values of `df`: + + >>> df = [1, 2, 3] + >>> p = nctdtr(df, 0.25, 1) + >>> p + array([0.67491974, 0.716464 , 0.73349456]) + + Compute the inverse. We recover the values of `df`, as expected: + + >>> nctdtridf(p, 0.25, 1) + array([1., 2., 3.]) + + """) + +add_newdoc("nctdtrinc", + """ + nctdtrinc(df, p, t, out=None) + + Calculate non-centrality parameter for non-central t distribution. + + See `nctdtr` for more details. + + Parameters + ---------- + df : array_like + Degrees of freedom of the distribution. Should be in range (0, inf). + p : array_like + CDF values, in range (0, 1]. + t : array_like + Quantiles, i.e., the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + nc : scalar or ndarray + Noncentrality parameter + + See Also + -------- + nctdtr : CDF of the non-central `t` distribution. + nctdtrit : Inverse CDF (iCDF) of the non-central t distribution. + nctdtridf : Calculate degrees of freedom, given CDF and iCDF values. + + Examples + -------- + >>> from scipy.special import nctdtr, nctdtrinc + + Compute the CDF for several values of `nc`: + + >>> nc = [0.5, 1.5, 2.5] + >>> p = nctdtr(3, nc, 1.5) + >>> p + array([0.77569497, 0.45524533, 0.1668691 ]) + + Compute the inverse. We recover the values of `nc`, as expected: + + >>> nctdtrinc(3, p, 1.5) + array([0.5, 1.5, 2.5]) + + """) + +add_newdoc("nctdtrit", + """ + nctdtrit(df, nc, p, out=None) + + Inverse cumulative distribution function of the non-central t distribution. + + See `nctdtr` for more details. + + Parameters + ---------- + df : array_like + Degrees of freedom of the distribution. Should be in range (0, inf). + nc : array_like + Noncentrality parameter. Should be in range (-1e6, 1e6). + p : array_like + CDF values, in range (0, 1]. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + t : scalar or ndarray + Quantiles + + See Also + -------- + nctdtr : CDF of the non-central `t` distribution. + nctdtridf : Calculate degrees of freedom, given CDF and iCDF values. + nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values. + + Examples + -------- + >>> from scipy.special import nctdtr, nctdtrit + + Compute the CDF for several values of `t`: + + >>> t = [0.5, 1, 1.5] + >>> p = nctdtr(3, 1, t) + >>> p + array([0.29811049, 0.46922687, 0.6257559 ]) + + Compute the inverse. We recover the values of `t`, as expected: + + >>> nctdtrit(3, 1, p) + array([0.5, 1. , 1.5]) + + """) + +add_newdoc("ndtr", + r""" + ndtr(x, out=None) + + Cumulative distribution of the standard normal distribution. + + Returns the area under the standard Gaussian probability + density function, integrated from minus infinity to `x` + + .. math:: + + \frac{1}{\sqrt{2\pi}} \int_{-\infty}^x \exp(-t^2/2) dt + + Parameters + ---------- + x : array_like, real or complex + Argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The value of the normal CDF evaluated at `x` + + See Also + -------- + log_ndtr : Logarithm of ndtr + ndtri : Inverse of ndtr, standard normal percentile function + erf : Error function + erfc : 1 - erf + scipy.stats.norm : Normal distribution + + Examples + -------- + Evaluate `ndtr` at one point. + + >>> import numpy as np + >>> from scipy.special import ndtr + >>> ndtr(0.5) + 0.6914624612740131 + + Evaluate the function at several points by providing a NumPy array + or list for `x`. + + >>> ndtr([0, 0.5, 2]) + array([0.5 , 0.69146246, 0.97724987]) + + Plot the function. + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-5, 5, 100) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, ndtr(x)) + >>> ax.set_title(r"Standard normal cumulative distribution function $\Phi$") + >>> plt.show() + """) + + +add_newdoc("nrdtrimn", + """ + nrdtrimn(p, std, x, out=None) + + Calculate mean of normal distribution given other params. + + Parameters + ---------- + p : array_like + CDF values, in range (0, 1]. + std : array_like + Standard deviation. + x : array_like + Quantiles, i.e. the upper limit of integration. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + mn : scalar or ndarray + The mean of the normal distribution. + + See Also + -------- + scipy.stats.norm : Normal distribution + ndtr : Standard normal cumulative probability distribution + ndtri : Inverse of standard normal CDF with respect to quantile + nrdtrisd : Inverse of normal distribution CDF with respect to + standard deviation + + Examples + -------- + `nrdtrimn` can be used to recover the mean of a normal distribution + if we know the CDF value `p` for a given quantile `x` and the + standard deviation `std`. First, we calculate + the normal distribution CDF for an exemplary parameter set. + + >>> from scipy.stats import norm + >>> mean = 3. + >>> std = 2. + >>> x = 6. + >>> p = norm.cdf(x, loc=mean, scale=std) + >>> p + 0.9331927987311419 + + Verify that `nrdtrimn` returns the original value for `mean`. + + >>> from scipy.special import nrdtrimn + >>> nrdtrimn(p, std, x) + 3.0000000000000004 + + """) + +add_newdoc("nrdtrisd", + """ + nrdtrisd(mn, p, x, out=None) + + Calculate standard deviation of normal distribution given other params. + + Parameters + ---------- + mn : scalar or ndarray + The mean of the normal distribution. + p : array_like + CDF values, in range (0, 1]. + x : array_like + Quantiles, i.e. the upper limit of integration. + + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + std : scalar or ndarray + Standard deviation. + + See Also + -------- + scipy.stats.norm : Normal distribution + ndtr : Standard normal cumulative probability distribution + ndtri : Inverse of standard normal CDF with respect to quantile + nrdtrimn : Inverse of normal distribution CDF with respect to + mean + + Examples + -------- + `nrdtrisd` can be used to recover the standard deviation of a normal + distribution if we know the CDF value `p` for a given quantile `x` and + the mean `mn`. First, we calculate the normal distribution CDF for an + exemplary parameter set. + + >>> from scipy.stats import norm + >>> mean = 3. + >>> std = 2. + >>> x = 6. + >>> p = norm.cdf(x, loc=mean, scale=std) + >>> p + 0.9331927987311419 + + Verify that `nrdtrisd` returns the original value for `std`. + + >>> from scipy.special import nrdtrisd + >>> nrdtrisd(mean, p, x) + 2.0000000000000004 + + """) + +add_newdoc("log_ndtr", + """ + log_ndtr(x, out=None) + + Logarithm of Gaussian cumulative distribution function. + + Returns the log of the area under the standard Gaussian probability + density function, integrated from minus infinity to `x`:: + + log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x)) + + Parameters + ---------- + x : array_like, real or complex + Argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The value of the log of the normal CDF evaluated at `x` + + See Also + -------- + erf + erfc + scipy.stats.norm + ndtr + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import log_ndtr, ndtr + + The benefit of ``log_ndtr(x)`` over the naive implementation + ``np.log(ndtr(x))`` is most evident with moderate to large positive + values of ``x``: + + >>> x = np.array([6, 7, 9, 12, 15, 25]) + >>> log_ndtr(x) + array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019, + -1.77648211e-033, -3.67096620e-051, -3.05669671e-138]) + + The results of the naive calculation for the moderate ``x`` values + have only 5 or 6 correct significant digits. For values of ``x`` + greater than approximately 8.3, the naive expression returns 0: + + >>> np.log(ndtr(x)) + array([-9.86587701e-10, -1.27986510e-12, 0.00000000e+00, + 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]) + """) + +add_newdoc("ndtri", + """ + ndtri(y, out=None) + + Inverse of `ndtr` vs x + + Returns the argument x for which the area under the standard normal + probability density function (integrated from minus infinity to `x`) + is equal to y. + + Parameters + ---------- + p : array_like + Probability + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + x : scalar or ndarray + Value of x such that ``ndtr(x) == p``. + + See Also + -------- + ndtr : Standard normal cumulative probability distribution + ndtri_exp : Inverse of log_ndtr + + Examples + -------- + `ndtri` is the percentile function of the standard normal distribution. + This means it returns the inverse of the cumulative density `ndtr`. First, + let us compute a cumulative density value. + + >>> import numpy as np + >>> from scipy.special import ndtri, ndtr + >>> cdf_val = ndtr(2) + >>> cdf_val + 0.9772498680518208 + + Verify that `ndtri` yields the original value for `x` up to floating point + errors. + + >>> ndtri(cdf_val) + 2.0000000000000004 + + Plot the function. For that purpose, we provide a NumPy array as argument. + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0.01, 1, 200) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, ndtri(x)) + >>> ax.set_title("Standard normal percentile function") + >>> plt.show() + """) + +add_newdoc("pdtr", + r""" + pdtr(k, m, out=None) + + Poisson cumulative distribution function. + + Defined as the probability that a Poisson-distributed random + variable with event rate :math:`m` is less than or equal to + :math:`k`. More concretely, this works out to be [1]_ + + .. math:: + + \exp(-m) \sum_{j = 0}^{\lfloor{k}\rfloor} \frac{m^j}{j!}. + + Parameters + ---------- + k : array_like + Number of occurrences (nonnegative, real) + m : array_like + Shape parameter (nonnegative, real) + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the Poisson cumulative distribution function + + See Also + -------- + pdtrc : Poisson survival function + pdtrik : inverse of `pdtr` with respect to `k` + pdtri : inverse of `pdtr` with respect to `m` + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Poisson_distribution + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It is a cumulative distribution function, so it converges to 1 + monotonically as `k` goes to infinity. + + >>> sc.pdtr([1, 10, 100, np.inf], 1) + array([0.73575888, 0.99999999, 1. , 1. ]) + + It is discontinuous at integers and constant between integers. + + >>> sc.pdtr([1, 1.5, 1.9, 2], 1) + array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ]) + + """) + +add_newdoc("pdtrc", + """ + pdtrc(k, m, out=None) + + Poisson survival function + + Returns the sum of the terms from k+1 to infinity of the Poisson + distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc( + k+1, m). Arguments must both be non-negative doubles. + + Parameters + ---------- + k : array_like + Number of occurrences (nonnegative, real) + m : array_like + Shape parameter (nonnegative, real) + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the Poisson survival function + + See Also + -------- + pdtr : Poisson cumulative distribution function + pdtrik : inverse of `pdtr` with respect to `k` + pdtri : inverse of `pdtr` with respect to `m` + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + It is a survival function, so it decreases to 0 + monotonically as `k` goes to infinity. + + >>> k = np.array([1, 10, 100, np.inf]) + >>> sc.pdtrc(k, 1) + array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000]) + + It can be expressed in terms of the lower incomplete gamma + function `gammainc`. + + >>> sc.gammainc(k + 1, 1) + array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000]) + + """) + +add_newdoc("pdtri", + """ + pdtri(k, y, out=None) + + Inverse to `pdtr` vs m + + Returns the Poisson variable `m` such that the sum from 0 to `k` of + the Poisson density is equal to the given probability `y`: + calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative + integer and `y` between 0 and 1. + + Parameters + ---------- + k : array_like + Number of occurrences (nonnegative, real) + y : array_like + Probability + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Values of the shape parameter `m` such that ``pdtr(k, m) = p`` + + See Also + -------- + pdtr : Poisson cumulative distribution function + pdtrc : Poisson survival function + pdtrik : inverse of `pdtr` with respect to `k` + + Examples + -------- + >>> import scipy.special as sc + + Compute the CDF for several values of `m`: + + >>> m = [0.5, 1, 1.5] + >>> p = sc.pdtr(1, m) + >>> p + array([0.90979599, 0.73575888, 0.5578254 ]) + + Compute the inverse. We recover the values of `m`, as expected: + + >>> sc.pdtri(1, p) + array([0.5, 1. , 1.5]) + + """) + +add_newdoc("pdtrik", + """ + pdtrik(p, m, out=None) + + Inverse to `pdtr` vs `k`. + + Parameters + ---------- + p : array_like + Probability + m : array_like + Shape parameter (nonnegative, real) + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The number of occurrences `k` such that ``pdtr(k, m) = p`` + + See Also + -------- + pdtr : Poisson cumulative distribution function + pdtrc : Poisson survival function + pdtri : inverse of `pdtr` with respect to `m` + + Examples + -------- + >>> import scipy.special as sc + + Compute the CDF for several values of `k`: + + >>> k = [1, 2, 3] + >>> p = sc.pdtr(k, 2) + >>> p + array([0.40600585, 0.67667642, 0.85712346]) + + Compute the inverse. We recover the values of `k`, as expected: + + >>> sc.pdtrik(p, 2) + array([1., 2., 3.]) + + """) + +add_newdoc("poch", + r""" + poch(z, m, out=None) + + Pochhammer symbol. + + The Pochhammer symbol (rising factorial) is defined as + + .. math:: + + (z)_m = \frac{\Gamma(z + m)}{\Gamma(z)} + + For positive integer `m` it reads + + .. math:: + + (z)_m = z (z + 1) ... (z + m - 1) + + See [dlmf]_ for more details. + + Parameters + ---------- + z, m : array_like + Real-valued arguments. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The value of the function. + + References + ---------- + .. [dlmf] Nist, Digital Library of Mathematical Functions + https://dlmf.nist.gov/5.2#iii + + Examples + -------- + >>> import scipy.special as sc + + It is 1 when m is 0. + + >>> sc.poch([1, 2, 3, 4], 0) + array([1., 1., 1., 1.]) + + For z equal to 1 it reduces to the factorial function. + + >>> sc.poch(1, 5) + 120.0 + >>> 1 * 2 * 3 * 4 * 5 + 120 + + It can be expressed in terms of the gamma function. + + >>> z, m = 3.7, 2.1 + >>> sc.poch(z, m) + 20.529581933776953 + >>> sc.gamma(z + m) / sc.gamma(z) + 20.52958193377696 + + """) + +add_newdoc("powm1", """ + powm1(x, y, out=None) + + Computes ``x**y - 1``. + + This function is useful when `y` is near 0, or when `x` is near 1. + + The function is implemented for real types only (unlike ``numpy.power``, + which accepts complex inputs). + + Parameters + ---------- + x : array_like + The base. Must be a real type (i.e. integer or float, not complex). + y : array_like + The exponent. Must be a real type (i.e. integer or float, not complex). + + Returns + ------- + array_like + Result of the calculation + + Notes + ----- + .. versionadded:: 1.10.0 + + The underlying code is implemented for single precision and double + precision floats only. Unlike `numpy.power`, integer inputs to + `powm1` are converted to floating point, and complex inputs are + not accepted. + + Note the following edge cases: + + * ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf`` + and ``nan``. + * ``powm1(1, y)`` returns 0 for any ``y``, including ``nan`` + and ``inf``. + + This function wraps the ``powm1`` routine from the + Boost Math C++ library [1]_. + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import powm1 + + >>> x = np.array([1.2, 10.0, 0.9999999975]) + >>> y = np.array([1e-9, 1e-11, 0.1875]) + >>> powm1(x, y) + array([ 1.82321557e-10, 2.30258509e-11, -4.68749998e-10]) + + It can be verified that the relative errors in those results + are less than 2.5e-16. + + Compare that to the result of ``x**y - 1``, where the + relative errors are all larger than 8e-8: + + >>> x**y - 1 + array([ 1.82321491e-10, 2.30258035e-11, -4.68750039e-10]) + + """) + + +add_newdoc("pseudo_huber", + r""" + pseudo_huber(delta, r, out=None) + + Pseudo-Huber loss function. + + .. math:: \mathrm{pseudo\_huber}(\delta, r) = + \delta^2 \left( \sqrt{ 1 + \left( \frac{r}{\delta} \right)^2 } - 1 \right) + + Parameters + ---------- + delta : array_like + Input array, indicating the soft quadratic vs. linear loss changepoint. + r : array_like + Input array, possibly representing residuals. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + res : scalar or ndarray + The computed Pseudo-Huber loss function values. + + See Also + -------- + huber: Similar function which this function approximates + + Notes + ----- + Like `huber`, `pseudo_huber` often serves as a robust loss function + in statistics or machine learning to reduce the influence of outliers. + Unlike `huber`, `pseudo_huber` is smooth. + + Typically, `r` represents residuals, the difference + between a model prediction and data. Then, for :math:`|r|\leq\delta`, + `pseudo_huber` resembles the squared error and for :math:`|r|>\delta` the + absolute error. This way, the Pseudo-Huber loss often achieves + a fast convergence in model fitting for small residuals like the squared + error loss function and still reduces the influence of outliers + (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is + the cutoff between squared and absolute error regimes, it has + to be tuned carefully for each problem. `pseudo_huber` is also + convex, making it suitable for gradient based optimization. [1]_ [2]_ + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Hartley, Zisserman, "Multiple View Geometry in Computer Vision". + 2003. Cambridge University Press. p. 619 + .. [2] Charbonnier et al. "Deterministic edge-preserving regularization + in computed imaging". 1997. IEEE Trans. Image Processing. + 6 (2): 298 - 311. + + Examples + -------- + Import all necessary modules. + + >>> import numpy as np + >>> from scipy.special import pseudo_huber, huber + >>> import matplotlib.pyplot as plt + + Calculate the function for ``delta=1`` at ``r=2``. + + >>> pseudo_huber(1., 2.) + 1.2360679774997898 + + Calculate the function at ``r=2`` for different `delta` by providing + a list or NumPy array for `delta`. + + >>> pseudo_huber([1., 2., 4.], 3.) + array([2.16227766, 3.21110255, 4. ]) + + Calculate the function for ``delta=1`` at several points by providing + a list or NumPy array for `r`. + + >>> pseudo_huber(2., np.array([1., 1.5, 3., 4.])) + array([0.47213595, 1. , 3.21110255, 4.94427191]) + + The function can be calculated for different `delta` and `r` by + providing arrays for both with compatible shapes for broadcasting. + + >>> r = np.array([1., 2.5, 8., 10.]) + >>> deltas = np.array([[1.], [5.], [9.]]) + >>> print(r.shape, deltas.shape) + (4,) (3, 1) + + >>> pseudo_huber(deltas, r) + array([[ 0.41421356, 1.6925824 , 7.06225775, 9.04987562], + [ 0.49509757, 2.95084972, 22.16990566, 30.90169944], + [ 0.49846624, 3.06693762, 27.37435121, 40.08261642]]) + + Plot the function for different `delta`. + + >>> x = np.linspace(-4, 4, 500) + >>> deltas = [1, 2, 3] + >>> linestyles = ["dashed", "dotted", "dashdot"] + >>> fig, ax = plt.subplots() + >>> combined_plot_parameters = list(zip(deltas, linestyles)) + >>> for delta, style in combined_plot_parameters: + ... ax.plot(x, pseudo_huber(delta, x), label=rf"$\delta={delta}$", + ... ls=style) + >>> ax.legend(loc="upper center") + >>> ax.set_xlabel("$x$") + >>> ax.set_title(r"Pseudo-Huber loss function $h_{\delta}(x)$") + >>> ax.set_xlim(-4, 4) + >>> ax.set_ylim(0, 8) + >>> plt.show() + + Finally, illustrate the difference between `huber` and `pseudo_huber` by + plotting them and their gradients with respect to `r`. The plot shows + that `pseudo_huber` is continuously differentiable while `huber` is not + at the points :math:`\pm\delta`. + + >>> def huber_grad(delta, x): + ... grad = np.copy(x) + ... linear_area = np.argwhere(np.abs(x) > delta) + ... grad[linear_area]=delta*np.sign(x[linear_area]) + ... return grad + >>> def pseudo_huber_grad(delta, x): + ... return x* (1+(x/delta)**2)**(-0.5) + >>> x=np.linspace(-3, 3, 500) + >>> delta = 1. + >>> fig, ax = plt.subplots(figsize=(7, 7)) + >>> ax.plot(x, huber(delta, x), label="Huber", ls="dashed") + >>> ax.plot(x, huber_grad(delta, x), label="Huber Gradient", ls="dashdot") + >>> ax.plot(x, pseudo_huber(delta, x), label="Pseudo-Huber", ls="dotted") + >>> ax.plot(x, pseudo_huber_grad(delta, x), label="Pseudo-Huber Gradient", + ... ls="solid") + >>> ax.legend(loc="upper center") + >>> plt.show() + """) + +add_newdoc("rel_entr", + r""" + rel_entr(x, y, out=None) + + Elementwise function for computing relative entropy. + + .. math:: + + \mathrm{rel\_entr}(x, y) = + \begin{cases} + x \log(x / y) & x > 0, y > 0 \\ + 0 & x = 0, y \ge 0 \\ + \infty & \text{otherwise} + \end{cases} + + Parameters + ---------- + x, y : array_like + Input arrays + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Relative entropy of the inputs + + See Also + -------- + entr, kl_div, scipy.stats.entropy + + Notes + ----- + .. versionadded:: 0.15.0 + + This function is jointly convex in x and y. + + The origin of this function is in convex programming; see + [1]_. Given two discrete probability distributions :math:`p_1, + \ldots, p_n` and :math:`q_1, \ldots, q_n`, the definition of relative + entropy in the context of *information theory* is + + .. math:: + + \sum_{i = 1}^n \mathrm{rel\_entr}(p_i, q_i). + + To compute the latter quantity, use `scipy.stats.entropy`. + + See [2]_ for details. + + References + ---------- + .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*. + Cambridge University Press, 2004. + :doi:`https://doi.org/10.1017/CBO9780511804441` + .. [2] Kullback-Leibler divergence, + https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence + + """) + +add_newdoc("round", + """ + round(x, out=None) + + Round to the nearest integer. + + Returns the nearest integer to `x`. If `x` ends in 0.5 exactly, + the nearest even integer is chosen. + + Parameters + ---------- + x : array_like + Real valued input. + out : ndarray, optional + Optional output array for the function results. + + Returns + ------- + scalar or ndarray + The nearest integers to the elements of `x`. The result is of + floating type, not integer type. + + Examples + -------- + >>> import scipy.special as sc + + It rounds to even. + + >>> sc.round([0.5, 1.5]) + array([0., 2.]) + + """) + +add_newdoc("shichi", + r""" + shichi(x, out=None) + + Hyperbolic sine and cosine integrals. + + The hyperbolic sine integral is + + .. math:: + + \int_0^x \frac{\sinh{t}}{t}dt + + and the hyperbolic cosine integral is + + .. math:: + + \gamma + \log(x) + \int_0^x \frac{\cosh{t} - 1}{t} dt + + where :math:`\gamma` is Euler's constant and :math:`\log` is the + principal branch of the logarithm [1]_. + + Parameters + ---------- + x : array_like + Real or complex points at which to compute the hyperbolic sine + and cosine integrals. + out : tuple of ndarray, optional + Optional output arrays for the function results + + Returns + ------- + si : scalar or ndarray + Hyperbolic sine integral at ``x`` + ci : scalar or ndarray + Hyperbolic cosine integral at ``x`` + + See Also + -------- + sici : Sine and cosine integrals. + exp1 : Exponential integral E1. + expi : Exponential integral Ei. + + Notes + ----- + For real arguments with ``x < 0``, ``chi`` is the real part of the + hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x + + 0j)`` differ by a factor of ``1j*pi``. + + For real arguments the function is computed by calling Cephes' + [2]_ *shichi* routine. For complex arguments the algorithm is based + on Mpmath's [3]_ *shi* and *chi* routines. + + References + ---------- + .. [1] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + (See Section 5.2.) + .. [2] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + .. [3] Fredrik Johansson and others. + "mpmath: a Python library for arbitrary-precision floating-point + arithmetic" (Version 0.19) http://mpmath.org/ + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import shichi, sici + + `shichi` accepts real or complex input: + + >>> shichi(0.5) + (0.5069967498196671, -0.05277684495649357) + >>> shichi(0.5 + 2.5j) + ((0.11772029666668238+1.831091777729851j), + (0.29912435887648825+1.7395351121166562j)) + + The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are + related to the sine and cosine integrals Si(z) and Ci(z) by + + * Shi(z) = -i*Si(i*z) + * Chi(z) = Ci(-i*z) + i*pi/2 + + >>> z = 0.25 + 5j + >>> shi, chi = shichi(z) + >>> shi, -1j*sici(1j*z)[0] # Should be the same. + ((-0.04834719325101729+1.5469354086921228j), + (-0.04834719325101729+1.5469354086921228j)) + >>> chi, sici(-1j*z)[1] + 1j*np.pi/2 # Should be the same. + ((-0.19568708973868087+1.556276312103824j), + (-0.19568708973868087+1.556276312103824j)) + + Plot the functions evaluated on the real axis: + + >>> xp = np.geomspace(1e-8, 4.0, 250) + >>> x = np.concatenate((-xp[::-1], xp)) + >>> shi, chi = shichi(x) + + >>> fig, ax = plt.subplots() + >>> ax.plot(x, shi, label='Shi(x)') + >>> ax.plot(x, chi, '--', label='Chi(x)') + >>> ax.set_xlabel('x') + >>> ax.set_title('Hyperbolic Sine and Cosine Integrals') + >>> ax.legend(shadow=True, framealpha=1, loc='lower right') + >>> ax.grid(True) + >>> plt.show() + + """) + +add_newdoc("sici", + r""" + sici(x, out=None) + + Sine and cosine integrals. + + The sine integral is + + .. math:: + + \int_0^x \frac{\sin{t}}{t}dt + + and the cosine integral is + + .. math:: + + \gamma + \log(x) + \int_0^x \frac{\cos{t} - 1}{t}dt + + where :math:`\gamma` is Euler's constant and :math:`\log` is the + principal branch of the logarithm [1]_. + + Parameters + ---------- + x : array_like + Real or complex points at which to compute the sine and cosine + integrals. + out : tuple of ndarray, optional + Optional output arrays for the function results + + Returns + ------- + si : scalar or ndarray + Sine integral at ``x`` + ci : scalar or ndarray + Cosine integral at ``x`` + + See Also + -------- + shichi : Hyperbolic sine and cosine integrals. + exp1 : Exponential integral E1. + expi : Exponential integral Ei. + + Notes + ----- + For real arguments with ``x < 0``, ``ci`` is the real part of the + cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)`` + differ by a factor of ``1j*pi``. + + For real arguments the function is computed by calling Cephes' + [2]_ *sici* routine. For complex arguments the algorithm is based + on Mpmath's [3]_ *si* and *ci* routines. + + References + ---------- + .. [1] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + (See Section 5.2.) + .. [2] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + .. [3] Fredrik Johansson and others. + "mpmath: a Python library for arbitrary-precision floating-point + arithmetic" (Version 0.19) http://mpmath.org/ + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import sici, exp1 + + `sici` accepts real or complex input: + + >>> sici(2.5) + (1.7785201734438267, 0.2858711963653835) + >>> sici(2.5 + 3j) + ((4.505735874563953+0.06863305018999577j), + (0.0793644206906966-2.935510262937543j)) + + For z in the right half plane, the sine and cosine integrals are + related to the exponential integral E1 (implemented in SciPy as + `scipy.special.exp1`) by + + * Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2 + * Ci(z) = -(E1(i*z) + E1(-i*z))/2 + + See [1]_ (equations 5.2.21 and 5.2.23). + + We can verify these relations: + + >>> z = 2 - 3j + >>> sici(z) + ((4.54751388956229-1.3991965806460565j), + (1.408292501520851+2.9836177420296055j)) + + >>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2 # Same as sine integral + (4.54751388956229-1.3991965806460565j) + + >>> -(exp1(1j*z) + exp1(-1j*z))/2 # Same as cosine integral + (1.408292501520851+2.9836177420296055j) + + Plot the functions evaluated on the real axis; the dotted horizontal + lines are at pi/2 and -pi/2: + + >>> x = np.linspace(-16, 16, 150) + >>> si, ci = sici(x) + + >>> fig, ax = plt.subplots() + >>> ax.plot(x, si, label='Si(x)') + >>> ax.plot(x, ci, '--', label='Ci(x)') + >>> ax.legend(shadow=True, framealpha=1, loc='upper left') + >>> ax.set_xlabel('x') + >>> ax.set_title('Sine and Cosine Integrals') + >>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k') + >>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k') + >>> ax.grid(True) + >>> plt.show() + + """) + +add_newdoc("smirnov", + r""" + smirnov(n, d, out=None) + + Kolmogorov-Smirnov complementary cumulative distribution function + + Returns the exact Kolmogorov-Smirnov complementary cumulative + distribution function,(aka the Survival Function) of Dn+ (or Dn-) + for a one-sided test of equality between an empirical and a + theoretical distribution. It is equal to the probability that the + maximum difference between a theoretical distribution and an empirical + one based on `n` samples is greater than d. + + Parameters + ---------- + n : int + Number of samples + d : float array_like + Deviation between the Empirical CDF (ECDF) and the target CDF. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d)) + + See Also + -------- + smirnovi : The Inverse Survival Function for the distribution + scipy.stats.ksone : Provides the functionality as a continuous distribution + kolmogorov, kolmogi : Functions for the two-sided distribution + + Notes + ----- + `smirnov` is used by `stats.kstest` in the application of the + Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this + function is exposed in `scpy.special`, but the recommended way to achieve + the most accurate CDF/SF/PDF/PPF/ISF computations is to use the + `stats.ksone` distribution. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import smirnov + >>> from scipy.stats import norm + + Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a + sample of size 5. + + >>> smirnov(5, [0, 0.5, 1.0]) + array([ 1. , 0.056, 0. ]) + + Compare a sample of size 5 against N(0, 1), the standard normal + distribution with mean 0 and standard deviation 1. + + `x` is the sample. + + >>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82]) + + >>> target = norm(0, 1) + >>> cdfs = target.cdf(x) + >>> cdfs + array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ]) + + Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn). + + >>> n = len(x) + >>> ecdfs = np.arange(n+1, dtype=float)/n + >>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n], + ... ecdfs[1:] - cdfs]) + >>> with np.printoptions(precision=3): + ... print(cols) + [[-1.392 0.2 0.082 0.082 0.118] + [-0.135 0.4 0.446 0.246 -0.046] + [ 0.114 0.6 0.545 0.145 0.055] + [ 0.19 0.8 0.575 -0.025 0.225] + [ 1.82 1. 0.966 0.166 0.034]] + >>> gaps = cols[:, -2:] + >>> Dnpm = np.max(gaps, axis=0) + >>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}') + Dn-=0.246306, Dn+=0.224655 + >>> probs = smirnov(n, Dnpm) + >>> print(f'For a sample of size {n} drawn from N(0, 1):', + ... f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}', + ... f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}', + ... sep='\n') + For a sample of size 5 drawn from N(0, 1): + Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711 + Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245 + + Plot the empirical CDF and the standard normal CDF. + + >>> import matplotlib.pyplot as plt + >>> plt.step(np.concatenate(([-2.5], x, [2.5])), + ... np.concatenate((ecdfs, [1])), + ... where='post', label='Empirical CDF') + >>> xx = np.linspace(-2.5, 2.5, 100) + >>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)') + + Add vertical lines marking Dn+ and Dn-. + + >>> iminus, iplus = np.argmax(gaps, axis=0) + >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r', + ... alpha=0.5, lw=4) + >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m', + ... alpha=0.5, lw=4) + + >>> plt.grid(True) + >>> plt.legend(framealpha=1, shadow=True) + >>> plt.show() + """) + +add_newdoc("smirnovi", + """ + smirnovi(n, p, out=None) + + Inverse to `smirnov` + + Returns `d` such that ``smirnov(n, d) == p``, the critical value + corresponding to `p`. + + Parameters + ---------- + n : int + Number of samples + p : float array_like + Probability + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + The value(s) of smirnovi(n, p), the critical values. + + See Also + -------- + smirnov : The Survival Function (SF) for the distribution + scipy.stats.ksone : Provides the functionality as a continuous distribution + kolmogorov, kolmogi : Functions for the two-sided distribution + scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n + + Notes + ----- + `smirnov` is used by `stats.kstest` in the application of the + Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this + function is exposed in `scpy.special`, but the recommended way to achieve + the most accurate CDF/SF/PDF/PPF/ISF computations is to use the + `stats.ksone` distribution. + + Examples + -------- + >>> from scipy.special import smirnovi, smirnov + + >>> n = 24 + >>> deviations = [0.1, 0.2, 0.3] + + Use `smirnov` to compute the complementary CDF of the Smirnov + distribution for the given number of samples and deviations. + + >>> p = smirnov(n, deviations) + >>> p + array([0.58105083, 0.12826832, 0.01032231]) + + The inverse function ``smirnovi(n, p)`` returns ``deviations``. + + >>> smirnovi(n, p) + array([0.1, 0.2, 0.3]) + + """) + +add_newdoc("_smirnovc", + """ + _smirnovc(n, d) + Internal function, do not use. + """) + +add_newdoc("_smirnovci", + """ + Internal function, do not use. + """) + +add_newdoc("_smirnovp", + """ + _smirnovp(n, p) + Internal function, do not use. + """) + +add_newdoc("spence", + r""" + spence(z, out=None) + + Spence's function, also known as the dilogarithm. + + It is defined to be + + .. math:: + \int_1^z \frac{\log(t)}{1 - t}dt + + for complex :math:`z`, where the contour of integration is taken + to avoid the branch cut of the logarithm. Spence's function is + analytic everywhere except the negative real axis where it has a + branch cut. + + Parameters + ---------- + z : array_like + Points at which to evaluate Spence's function + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + s : scalar or ndarray + Computed values of Spence's function + + Notes + ----- + There is a different convention which defines Spence's function by + the integral + + .. math:: + -\int_0^z \frac{\log(1 - t)}{t}dt; + + this is our ``spence(1 - z)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import spence + >>> import matplotlib.pyplot as plt + + The function is defined for complex inputs: + + >>> spence([1-1j, 1.5+2j, 3j, -10-5j]) + array([-0.20561676+0.91596559j, -0.86766909-1.39560134j, + -0.59422064-2.49129918j, -1.14044398+6.80075924j]) + + For complex inputs on the branch cut, which is the negative real axis, + the function returns the limit for ``z`` with positive imaginary part. + For example, in the following, note the sign change of the imaginary + part of the output for ``z = -2`` and ``z = -2 - 1e-8j``: + + >>> spence([-2 + 1e-8j, -2, -2 - 1e-8j]) + array([2.32018041-3.45139229j, 2.32018042-3.4513923j , + 2.32018041+3.45139229j]) + + The function returns ``nan`` for real inputs on the branch cut: + + >>> spence(-1.5) + nan + + Verify some particular values: ``spence(0) = pi**2/6``, + ``spence(1) = 0`` and ``spence(2) = -pi**2/12``. + + >>> spence([0, 1, 2]) + array([ 1.64493407, 0. , -0.82246703]) + >>> np.pi**2/6, -np.pi**2/12 + (1.6449340668482264, -0.8224670334241132) + + Verify the identity:: + + spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z) + + >>> z = 3 + 4j + >>> spence(z) + spence(1 - z) + (-2.6523186143876067+1.8853470951513935j) + >>> np.pi**2/6 - np.log(z)*np.log(1 - z) + (-2.652318614387606+1.885347095151394j) + + Plot the function for positive real input. + + >>> fig, ax = plt.subplots() + >>> x = np.linspace(0, 6, 400) + >>> ax.plot(x, spence(x)) + >>> ax.grid() + >>> ax.set_xlabel('x') + >>> ax.set_title('spence(x)') + >>> plt.show() + """) + +add_newdoc( + "stdtr", + r""" + stdtr(df, t, out=None) + + Student t distribution cumulative distribution function + + Returns the integral: + + .. math:: + \frac{\Gamma((df+1)/2)}{\sqrt{\pi df} \Gamma(df/2)} + \int_{-\infty}^t (1+x^2/df)^{-(df+1)/2}\, dx + + Parameters + ---------- + df : array_like + Degrees of freedom + t : array_like + Upper bound of the integral + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Value of the Student t CDF at t + + See Also + -------- + stdtridf : inverse of stdtr with respect to `df` + stdtrit : inverse of stdtr with respect to `t` + scipy.stats.t : student t distribution + + Notes + ----- + The student t distribution is also available as `scipy.stats.t`. + Calling `stdtr` directly can improve performance compared to the + ``cdf`` method of `scipy.stats.t` (see last example below). + + Examples + -------- + Calculate the function for ``df=3`` at ``t=1``. + + >>> import numpy as np + >>> from scipy.special import stdtr + >>> import matplotlib.pyplot as plt + >>> stdtr(3, 1) + 0.8044988905221148 + + Plot the function for three different degrees of freedom. + + >>> x = np.linspace(-10, 10, 1000) + >>> fig, ax = plt.subplots() + >>> parameters = [(1, "solid"), (3, "dashed"), (10, "dotted")] + >>> for (df, linestyle) in parameters: + ... ax.plot(x, stdtr(df, x), ls=linestyle, label=f"$df={df}$") + >>> ax.legend() + >>> ax.set_title("Student t distribution cumulative distribution function") + >>> plt.show() + + The function can be computed for several degrees of freedom at the same + time by providing a NumPy array or list for `df`: + + >>> stdtr([1, 2, 3], 1) + array([0.75 , 0.78867513, 0.80449889]) + + It is possible to calculate the function at several points for several + different degrees of freedom simultaneously by providing arrays for `df` + and `t` with shapes compatible for broadcasting. Compute `stdtr` at + 4 points for 3 degrees of freedom resulting in an array of shape 3x4. + + >>> dfs = np.array([[1], [2], [3]]) + >>> t = np.array([2, 4, 6, 8]) + >>> dfs.shape, t.shape + ((3, 1), (4,)) + + >>> stdtr(dfs, t) + array([[0.85241638, 0.92202087, 0.94743154, 0.96041658], + [0.90824829, 0.97140452, 0.98666426, 0.99236596], + [0.93033702, 0.98599577, 0.99536364, 0.99796171]]) + + The t distribution is also available as `scipy.stats.t`. Calling `stdtr` + directly can be much faster than calling the ``cdf`` method of + `scipy.stats.t`. To get the same results, one must use the following + parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``. + + >>> from scipy.stats import t + >>> df, x = 3, 1 + >>> stdtr_result = stdtr(df, x) # this can be faster than below + >>> stats_result = t(df).cdf(x) + >>> stats_result == stdtr_result # test that results are equal + True + """) + +add_newdoc("stdtridf", + """ + stdtridf(p, t, out=None) + + Inverse of `stdtr` vs df + + Returns the argument df such that stdtr(df, t) is equal to `p`. + + Parameters + ---------- + p : array_like + Probability + t : array_like + Upper bound of the integral + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + df : scalar or ndarray + Value of `df` such that ``stdtr(df, t) == p`` + + See Also + -------- + stdtr : Student t CDF + stdtrit : inverse of stdtr with respect to `t` + scipy.stats.t : Student t distribution + + Examples + -------- + Compute the student t cumulative distribution function for one + parameter set. + + >>> from scipy.special import stdtr, stdtridf + >>> df, x = 5, 2 + >>> cdf_value = stdtr(df, x) + >>> cdf_value + 0.9490302605850709 + + Verify that `stdtridf` recovers the original value for `df` given + the CDF value and `x`. + + >>> stdtridf(cdf_value, x) + 5.0 + """) + +add_newdoc("stdtrit", + """ + stdtrit(df, p, out=None) + + The `p`-th quantile of the student t distribution. + + This function is the inverse of the student t distribution cumulative + distribution function (CDF), returning `t` such that `stdtr(df, t) = p`. + + Returns the argument `t` such that stdtr(df, t) is equal to `p`. + + Parameters + ---------- + df : array_like + Degrees of freedom + p : array_like + Probability + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + t : scalar or ndarray + Value of `t` such that ``stdtr(df, t) == p`` + + See Also + -------- + stdtr : Student t CDF + stdtridf : inverse of stdtr with respect to `df` + scipy.stats.t : Student t distribution + + Notes + ----- + The student t distribution is also available as `scipy.stats.t`. Calling + `stdtrit` directly can improve performance compared to the ``ppf`` + method of `scipy.stats.t` (see last example below). + + Examples + -------- + `stdtrit` represents the inverse of the student t distribution CDF which + is available as `stdtr`. Here, we calculate the CDF for ``df`` at + ``x=1``. `stdtrit` then returns ``1`` up to floating point errors + given the same value for `df` and the computed CDF value. + + >>> import numpy as np + >>> from scipy.special import stdtr, stdtrit + >>> import matplotlib.pyplot as plt + >>> df = 3 + >>> x = 1 + >>> cdf_value = stdtr(df, x) + >>> stdtrit(df, cdf_value) + 0.9999999994418539 + + Plot the function for three different degrees of freedom. + + >>> x = np.linspace(0, 1, 1000) + >>> parameters = [(1, "solid"), (2, "dashed"), (5, "dotted")] + >>> fig, ax = plt.subplots() + >>> for (df, linestyle) in parameters: + ... ax.plot(x, stdtrit(df, x), ls=linestyle, label=f"$df={df}$") + >>> ax.legend() + >>> ax.set_ylim(-10, 10) + >>> ax.set_title("Student t distribution quantile function") + >>> plt.show() + + The function can be computed for several degrees of freedom at the same + time by providing a NumPy array or list for `df`: + + >>> stdtrit([1, 2, 3], 0.7) + array([0.72654253, 0.6172134 , 0.58438973]) + + It is possible to calculate the function at several points for several + different degrees of freedom simultaneously by providing arrays for `df` + and `p` with shapes compatible for broadcasting. Compute `stdtrit` at + 4 points for 3 degrees of freedom resulting in an array of shape 3x4. + + >>> dfs = np.array([[1], [2], [3]]) + >>> p = np.array([0.2, 0.4, 0.7, 0.8]) + >>> dfs.shape, p.shape + ((3, 1), (4,)) + + >>> stdtrit(dfs, p) + array([[-1.37638192, -0.3249197 , 0.72654253, 1.37638192], + [-1.06066017, -0.28867513, 0.6172134 , 1.06066017], + [-0.97847231, -0.27667066, 0.58438973, 0.97847231]]) + + The t distribution is also available as `scipy.stats.t`. Calling `stdtrit` + directly can be much faster than calling the ``ppf`` method of + `scipy.stats.t`. To get the same results, one must use the following + parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``. + + >>> from scipy.stats import t + >>> df, x = 3, 0.5 + >>> stdtrit_result = stdtrit(df, x) # this can be faster than below + >>> stats_result = t(df).ppf(x) + >>> stats_result == stdtrit_result # test that results are equal + True + """) + +add_newdoc( + "tklmbda", + r""" + tklmbda(x, lmbda, out=None) + + Cumulative distribution function of the Tukey lambda distribution. + + Parameters + ---------- + x, lmbda : array_like + Parameters + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + cdf : scalar or ndarray + Value of the Tukey lambda CDF + + See Also + -------- + scipy.stats.tukeylambda : Tukey lambda distribution + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import tklmbda, expit + + Compute the cumulative distribution function (CDF) of the Tukey lambda + distribution at several ``x`` values for `lmbda` = -1.5. + + >>> x = np.linspace(-2, 2, 9) + >>> x + array([-2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5, 2. ]) + >>> tklmbda(x, -1.5) + array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5 , + 0.54370263, 0.58471195, 0.6213446 , 0.65311266]) + + When `lmbda` is 0, the function is the logistic sigmoid function, + which is implemented in `scipy.special` as `expit`. + + >>> tklmbda(x, 0) + array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5 , + 0.62245933, 0.73105858, 0.81757448, 0.88079708]) + >>> expit(x) + array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5 , + 0.62245933, 0.73105858, 0.81757448, 0.88079708]) + + When `lmbda` is 1, the Tukey lambda distribution is uniform on the + interval [-1, 1], so the CDF increases linearly. + + >>> t = np.linspace(-1, 1, 9) + >>> tklmbda(t, 1) + array([0. , 0.125, 0.25 , 0.375, 0.5 , 0.625, 0.75 , 0.875, 1. ]) + + In the following, we generate plots for several values of `lmbda`. + + The first figure shows graphs for `lmbda` <= 0. + + >>> styles = ['-', '-.', '--', ':'] + >>> fig, ax = plt.subplots() + >>> x = np.linspace(-12, 12, 500) + >>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]): + ... y = tklmbda(x, lmbda) + ... ax.plot(x, y, styles[k], label=rf'$\lambda$ = {lmbda:-4.1f}') + + >>> ax.set_title(r'tklmbda(x, $\lambda$)') + >>> ax.set_label('x') + >>> ax.legend(framealpha=1, shadow=True) + >>> ax.grid(True) + + The second figure shows graphs for `lmbda` > 0. The dots in the + graphs show the bounds of the support of the distribution. + + >>> fig, ax = plt.subplots() + >>> x = np.linspace(-4.2, 4.2, 500) + >>> lmbdas = [0.25, 0.5, 1.0, 1.5] + >>> for k, lmbda in enumerate(lmbdas): + ... y = tklmbda(x, lmbda) + ... ax.plot(x, y, styles[k], label=fr'$\lambda$ = {lmbda}') + + >>> ax.set_prop_cycle(None) + >>> for lmbda in lmbdas: + ... ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8) + + >>> ax.set_title(r'tklmbda(x, $\lambda$)') + >>> ax.set_xlabel('x') + >>> ax.legend(framealpha=1, shadow=True) + >>> ax.grid(True) + + >>> plt.tight_layout() + >>> plt.show() + + The CDF of the Tukey lambda distribution is also implemented as the + ``cdf`` method of `scipy.stats.tukeylambda`. In the following, + ``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the + same values: + + >>> from scipy.stats import tukeylambda + >>> x = np.linspace(-2, 2, 9) + + >>> tukeylambda.cdf(x, -0.5) + array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5 , + 0.58671839, 0.66458323, 0.72906142, 0.78004843]) + + >>> tklmbda(x, -0.5) + array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5 , + 0.58671839, 0.66458323, 0.72906142, 0.78004843]) + + The implementation in ``tukeylambda`` also provides location and scale + parameters, and other methods such as ``pdf()`` (the probability + density function) and ``ppf()`` (the inverse of the CDF), so for + working with the Tukey lambda distribution, ``tukeylambda`` is more + generally useful. The primary advantage of ``tklmbda`` is that it is + significantly faster than ``tukeylambda.cdf``. + """) + +add_newdoc("wofz", + """ + wofz(z, out=None) + + Faddeeva function + + Returns the value of the Faddeeva function for complex argument:: + + exp(-z**2) * erfc(-i*z) + + Parameters + ---------- + z : array_like + complex argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Value of the Faddeeva function + + See Also + -------- + dawsn, erf, erfc, erfcx, erfi + + References + ---------- + .. [1] Steven G. Johnson, Faddeeva W function implementation. + http://ab-initio.mit.edu/Faddeeva + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + + >>> x = np.linspace(-3, 3) + >>> z = special.wofz(x) + + >>> plt.plot(x, z.real, label='wofz(x).real') + >>> plt.plot(x, z.imag, label='wofz(x).imag') + >>> plt.xlabel('$x$') + >>> plt.legend(framealpha=1, shadow=True) + >>> plt.grid(alpha=0.25) + >>> plt.show() + + """) + +add_newdoc("xlogy", + """ + xlogy(x, y, out=None) + + Compute ``x*log(y)`` so that the result is 0 if ``x = 0``. + + Parameters + ---------- + x : array_like + Multiplier + y : array_like + Argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + z : scalar or ndarray + Computed x*log(y) + + Notes + ----- + The log function used in the computation is the natural log. + + .. versionadded:: 0.13.0 + + Examples + -------- + We can use this function to calculate the binary logistic loss also + known as the binary cross entropy. This loss function is used for + binary classification problems and is defined as: + + .. math:: + L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i)) + + We can define the parameters `x` and `y` as y and y_pred respectively. + y is the array of the actual labels which over here can be either 0 or 1. + y_pred is the array of the predicted probabilities with respect to + the positive class (1). + + >>> import numpy as np + >>> from scipy.special import xlogy + >>> y = np.array([0, 1, 0, 1, 1, 0]) + >>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2]) + >>> n = len(y) + >>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum() + >>> loss /= n + >>> loss + 0.29597052165495025 + + A lower loss is usually better as it indicates that the predictions are + similar to the actual labels. In this example since our predicted + probabilities are close to the actual labels, we get an overall loss + that is reasonably low and appropriate. + + """) + +add_newdoc("xlog1py", + """ + xlog1py(x, y, out=None) + + Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``. + + Parameters + ---------- + x : array_like + Multiplier + y : array_like + Argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + z : scalar or ndarray + Computed x*log1p(y) + + Notes + ----- + + .. versionadded:: 0.13.0 + + Examples + -------- + This example shows how the function can be used to calculate the log of + the probability mass function for a geometric discrete random variable. + The probability mass function of the geometric distribution is defined + as follows: + + .. math:: f(k) = (1-p)^{k-1} p + + where :math:`p` is the probability of a single success + and :math:`1-p` is the probability of a single failure + and :math:`k` is the number of trials to get the first success. + + >>> import numpy as np + >>> from scipy.special import xlog1py + >>> p = 0.5 + >>> k = 100 + >>> _pmf = np.power(1 - p, k - 1) * p + >>> _pmf + 7.888609052210118e-31 + + If we take k as a relatively large number the value of the probability + mass function can become very low. In such cases taking the log of the + pmf would be more suitable as the log function can change the values + to a scale that is more appropriate to work with. + + >>> _log_pmf = xlog1py(k - 1, -p) + np.log(p) + >>> _log_pmf + -69.31471805599453 + + We can confirm that we get a value close to the original pmf value by + taking the exponential of the log pmf. + + >>> _orig_pmf = np.exp(_log_pmf) + >>> np.isclose(_pmf, _orig_pmf) + True + + """) + +add_newdoc("yn", + r""" + yn(n, x, out=None) + + Bessel function of the second kind of integer order and real argument. + + Parameters + ---------- + n : array_like + Order (integer). + x : array_like + Argument (float). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + Y : scalar or ndarray + Value of the Bessel function, :math:`Y_n(x)`. + + See Also + -------- + yv : For real order and real or complex argument. + y0: faster implementation of this function for order 0 + y1: faster implementation of this function for order 1 + + Notes + ----- + Wrapper for the Cephes [1]_ routine `yn`. + + The function is evaluated by forward recurrence on `n`, starting with + values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1, + the routine for `y0` or `y1` is called directly. + + References + ---------- + .. [1] Cephes Mathematical Functions Library, + http://www.netlib.org/cephes/ + + Examples + -------- + Evaluate the function of order 0 at one point. + + >>> from scipy.special import yn + >>> yn(0, 1.) + 0.08825696421567697 + + Evaluate the function at one point for different orders. + + >>> yn(0, 1.), yn(1, 1.), yn(2, 1.) + (0.08825696421567697, -0.7812128213002888, -1.6506826068162546) + + The evaluation for different orders can be carried out in one call by + providing a list or NumPy array as argument for the `v` parameter: + + >>> yn([0, 1, 2], 1.) + array([ 0.08825696, -0.78121282, -1.65068261]) + + Evaluate the function at several points for order 0 by providing an + array for `z`. + + >>> import numpy as np + >>> points = np.array([0.5, 3., 8.]) + >>> yn(0, points) + array([-0.44451873, 0.37685001, 0.22352149]) + + If `z` is an array, the order parameter `v` must be broadcastable to + the correct shape if different orders shall be computed in one call. + To calculate the orders 0 and 1 for an 1D array: + + >>> orders = np.array([[0], [1]]) + >>> orders.shape + (2, 1) + + >>> yn(orders, points) + array([[-0.44451873, 0.37685001, 0.22352149], + [-1.47147239, 0.32467442, -0.15806046]]) + + Plot the functions of order 0 to 3 from 0 to 10. + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> x = np.linspace(0., 10., 1000) + >>> for i in range(4): + ... ax.plot(x, yn(i, x), label=f'$Y_{i!r}$') + >>> ax.set_ylim(-3, 1) + >>> ax.legend() + >>> plt.show() + """) + +add_newdoc("yv", + r""" + yv(v, z, out=None) + + Bessel function of the second kind of real order and complex argument. + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + Y : scalar or ndarray + Value of the Bessel function of the second kind, :math:`Y_v(x)`. + + See Also + -------- + yve : :math:`Y_v` with leading exponential behavior stripped off. + y0: faster implementation of this function for order 0 + y1: faster implementation of this function for order 1 + + Notes + ----- + For positive `v` values, the computation is carried out using the + AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel + Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`, + + .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}). + + For negative `v` values the formula, + + .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v) + + is used, where :math:`J_v(z)` is the Bessel function of the first kind, + computed using the AMOS routine `zbesj`. Note that the second term is + exactly zero for integer `v`; to improve accuracy the second term is + explicitly omitted for `v` values such that `v = floor(v)`. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + Evaluate the function of order 0 at one point. + + >>> from scipy.special import yv + >>> yv(0, 1.) + 0.088256964215677 + + Evaluate the function at one point for different orders. + + >>> yv(0, 1.), yv(1, 1.), yv(1.5, 1.) + (0.088256964215677, -0.7812128213002889, -1.102495575160179) + + The evaluation for different orders can be carried out in one call by + providing a list or NumPy array as argument for the `v` parameter: + + >>> yv([0, 1, 1.5], 1.) + array([ 0.08825696, -0.78121282, -1.10249558]) + + Evaluate the function at several points for order 0 by providing an + array for `z`. + + >>> import numpy as np + >>> points = np.array([0.5, 3., 8.]) + >>> yv(0, points) + array([-0.44451873, 0.37685001, 0.22352149]) + + If `z` is an array, the order parameter `v` must be broadcastable to + the correct shape if different orders shall be computed in one call. + To calculate the orders 0 and 1 for an 1D array: + + >>> orders = np.array([[0], [1]]) + >>> orders.shape + (2, 1) + + >>> yv(orders, points) + array([[-0.44451873, 0.37685001, 0.22352149], + [-1.47147239, 0.32467442, -0.15806046]]) + + Plot the functions of order 0 to 3 from 0 to 10. + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> x = np.linspace(0., 10., 1000) + >>> for i in range(4): + ... ax.plot(x, yv(i, x), label=f'$Y_{i!r}$') + >>> ax.set_ylim(-3, 1) + >>> ax.legend() + >>> plt.show() + + """) + +add_newdoc("yve", + r""" + yve(v, z, out=None) + + Exponentially scaled Bessel function of the second kind of real order. + + Returns the exponentially scaled Bessel function of the second + kind of real order `v` at complex `z`:: + + yve(v, z) = yv(v, z) * exp(-abs(z.imag)) + + Parameters + ---------- + v : array_like + Order (float). + z : array_like + Argument (float or complex). + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + Y : scalar or ndarray + Value of the exponentially scaled Bessel function. + + See Also + -------- + yv: Unscaled Bessel function of the second kind of real order. + + Notes + ----- + For positive `v` values, the computation is carried out using the + AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel + Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`, + + .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}). + + For negative `v` values the formula, + + .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v) + + is used, where :math:`J_v(z)` is the Bessel function of the first kind, + computed using the AMOS routine `zbesj`. Note that the second term is + exactly zero for integer `v`; to improve accuracy the second term is + explicitly omitted for `v` values such that `v = floor(v)`. + + Exponentially scaled Bessel functions are useful for large `z`: + for these, the unscaled Bessel functions can easily under-or overflow. + + References + ---------- + .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions + of a Complex Argument and Nonnegative Order", + http://netlib.org/amos/ + + Examples + -------- + Compare the output of `yv` and `yve` for large complex arguments for `z` + by computing their values for order ``v=1`` at ``z=1000j``. We see that + `yv` returns nan but `yve` returns a finite number: + + >>> import numpy as np + >>> from scipy.special import yv, yve + >>> v = 1 + >>> z = 1000j + >>> yv(v, z), yve(v, z) + ((nan+nanj), (-0.012610930256928629+7.721967686709076e-19j)) + + For real arguments for `z`, `yve` returns the same as `yv` up to + floating point errors. + + >>> v, z = 1, 1000 + >>> yv(v, z), yve(v, z) + (-0.02478433129235178, -0.02478433129235179) + + The function can be evaluated for several orders at the same time by + providing a list or NumPy array for `v`: + + >>> yve([1, 2, 3], 1j) + array([-0.20791042+0.14096627j, 0.38053618-0.04993878j, + 0.00815531-1.66311097j]) + + In the same way, the function can be evaluated at several points in one + call by providing a list or NumPy array for `z`: + + >>> yve(1, np.array([1j, 2j, 3j])) + array([-0.20791042+0.14096627j, -0.21526929+0.01205044j, + -0.19682671+0.00127278j]) + + It is also possible to evaluate several orders at several points + at the same time by providing arrays for `v` and `z` with + broadcasting compatible shapes. Compute `yve` for two different orders + `v` and three points `z` resulting in a 2x3 array. + + >>> v = np.array([[1], [2]]) + >>> z = np.array([3j, 4j, 5j]) + >>> v.shape, z.shape + ((2, 1), (3,)) + + >>> yve(v, z) + array([[-1.96826713e-01+1.27277544e-03j, -1.78750840e-01+1.45558819e-04j, + -1.63972267e-01+1.73494110e-05j], + [1.94960056e-03-1.11782545e-01j, 2.02902325e-04-1.17626501e-01j, + 2.27727687e-05-1.17951906e-01j]]) + """) + +add_newdoc("_struve_asymp_large_z", + """ + _struve_asymp_large_z(v, z, is_h) + + Internal function for testing `struve` & `modstruve` + + Evaluates using asymptotic expansion + + Returns + ------- + v, err + """) + +add_newdoc("_struve_power_series", + """ + _struve_power_series(v, z, is_h) + + Internal function for testing `struve` & `modstruve` + + Evaluates using power series + + Returns + ------- + v, err + """) + +add_newdoc("_struve_bessel_series", + """ + _struve_bessel_series(v, z, is_h) + + Internal function for testing `struve` & `modstruve` + + Evaluates using Bessel function series + + Returns + ------- + v, err + """) + +add_newdoc("_spherical_jn", + """ + Internal function, use `spherical_jn` instead. + """) + +add_newdoc("_spherical_jn_d", + """ + Internal function, use `spherical_jn` instead. + """) + +add_newdoc("_spherical_yn", + """ + Internal function, use `spherical_yn` instead. + """) + +add_newdoc("_spherical_yn_d", + """ + Internal function, use `spherical_yn` instead. + """) + +add_newdoc("_spherical_in", + """ + Internal function, use `spherical_in` instead. + """) + +add_newdoc("_spherical_in_d", + """ + Internal function, use `spherical_in` instead. + """) + +add_newdoc("_spherical_kn", + """ + Internal function, use `spherical_kn` instead. + """) + +add_newdoc("_spherical_kn_d", + """ + Internal function, use `spherical_kn` instead. + """) + +add_newdoc("owens_t", + """ + owens_t(h, a, out=None) + + Owen's T Function. + + The function T(h, a) gives the probability of the event + (X > h and 0 < Y < a * X) where X and Y are independent + standard normal random variables. + + Parameters + ---------- + h: array_like + Input value. + a: array_like + Input value. + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + t: scalar or ndarray + Probability of the event (X > h and 0 < Y < a * X), + where X and Y are independent standard normal random variables. + + References + ---------- + .. [1] M. Patefield and D. Tandy, "Fast and accurate calculation of + Owen's T Function", Statistical Software vol. 5, pp. 1-25, 2000. + + Examples + -------- + >>> from scipy import special + >>> a = 3.5 + >>> h = 0.78 + >>> special.owens_t(h, a) + 0.10877216734852274 + """) + +add_newdoc("_factorial", + """ + Internal function, do not use. + """) + +add_newdoc("ndtri_exp", + r""" + ndtri_exp(y, out=None) + + Inverse of `log_ndtr` vs x. Allows for greater precision than + `ndtri` composed with `numpy.exp` for very small values of y and for + y close to 0. + + Parameters + ---------- + y : array_like of float + Function argument + out : ndarray, optional + Optional output array for the function results + + Returns + ------- + scalar or ndarray + Inverse of the log CDF of the standard normal distribution, evaluated + at y. + + See Also + -------- + log_ndtr : log of the standard normal cumulative distribution function + ndtr : standard normal cumulative distribution function + ndtri : standard normal percentile function + + Examples + -------- + >>> import numpy as np + >>> import scipy.special as sc + + `ndtri_exp` agrees with the naive implementation when the latter does + not suffer from underflow. + + >>> sc.ndtri_exp(-1) + -0.33747496376420244 + >>> sc.ndtri(np.exp(-1)) + -0.33747496376420244 + + For extreme values of y, the naive approach fails + + >>> sc.ndtri(np.exp(-800)) + -inf + >>> sc.ndtri(np.exp(-1e-20)) + inf + + whereas `ndtri_exp` is still able to compute the result to high precision. + + >>> sc.ndtri_exp(-800) + -39.88469483825668 + >>> sc.ndtri_exp(-1e-20) + 9.262340089798409 + """) + + +add_newdoc("_stirling2_inexact", + r""" + Internal function, do not use. + """) + +add_newdoc( + "_beta_pdf", + r""" + _beta_pdf(x, a, b) + + Probability density function of beta distribution. + + Parameters + ---------- + x : array_like + Real-valued such that :math:`0 \leq x \leq 1`, + the upper limit of integration + a, b : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_beta_ppf", + r""" + _beta_ppf(x, a, b) + + Percent point function of beta distribution. + + Parameters + ---------- + x : array_like + Real-valued such that :math:`0 \leq x \leq 1`, + the upper limit of integration + a, b : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_invgauss_ppf", + """ + _invgauss_ppf(x, mu) + + Percent point function of inverse gaussian distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + mu : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_invgauss_isf", + """ + _invgauss_isf(x, mu, s) + + Inverse survival function of inverse gaussian distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + mu : array_like + Positive, real-valued parameters + s : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_cauchy_ppf", + """ + _cauchy_ppf(p, loc, scale) + + Percent point function (i.e. quantile) of the Cauchy distribution. + + Parameters + ---------- + p : array_like + Probabilities + loc : array_like + Location parameter of the distribution. + scale : array_like + Scale parameter of the distribution. + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_cauchy_isf", + """ + _cauchy_isf(p, loc, scale) + + Inverse survival function of the Cauchy distribution. + + Parameters + ---------- + p : array_like + Probabilities + loc : array_like + Location parameter of the distribution. + scale : array_like + Scale parameter of the distribution. + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncx2_pdf", + """ + _ncx2_pdf(x, k, l) + + Probability density function of Non-central chi-squared distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + k, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncx2_cdf", + """ + _ncx2_cdf(x, k, l) + + Cumulative density function of Non-central chi-squared distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + k, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncx2_ppf", + """ + _ncx2_ppf(x, k, l) + + Percent point function of Non-central chi-squared distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + k, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncx2_sf", + """ + _ncx2_sf(x, k, l) + + Survival function of Non-central chi-squared distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + k, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncx2_isf", + """ + _ncx2_isf(x, k, l) + + Inverse survival function of Non-central chi-squared distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + k, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_pdf", + """ + _ncf_pdf(x, v1, v2, l) + + Probability density function of noncentral F-distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_cdf", + """ + _ncf_cdf(x, v1, v2, l) + + Cumulative density function of noncentral F-distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_ppf", + """ + _ncf_ppf(x, v1, v2, l) + + Percent point function of noncentral F-distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_sf", + """ + _ncf_sf(x, v1, v2, l) + + Survival function of noncentral F-distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_isf", + """ + _ncf_isf(x, v1, v2, l) + + Inverse survival function of noncentral F-distribution. + + Parameters + ---------- + x : array_like + Positive real-valued + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_mean", + """ + _ncf_mean(v1, v2, l) + + Mean of noncentral F-distribution. + + Parameters + ---------- + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_variance", + """ + _ncf_variance(v1, v2, l) + + Variance of noncentral F-distribution. + + Parameters + ---------- + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_skewness", + """ + _ncf_skewness(v1, v2, l) + + Skewness of noncentral F-distribution. + + Parameters + ---------- + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_ncf_kurtosis_excess", + """ + _ncf_kurtosis_excess(v1, v2, l) + + Kurtosis excess of noncentral F-distribution. + + Parameters + ---------- + v1, v2, l : array_like + Positive, real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_cdf", + """ + _nct_cdf(x, v, l) + + Cumulative density function of noncentral t-distribution. + + Parameters + ---------- + x : array_like + Real-valued + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_pdf", + """ + _nct_pdf(x, v, l) + + Probability density function of noncentral t-distribution. + + Parameters + ---------- + x : array_like + Real-valued + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + + +add_newdoc( + "_nct_ppf", + """ + _nct_ppf(x, v, l) + + Percent point function of noncentral t-distribution. + + Parameters + ---------- + x : array_like + Real-valued + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_sf", + """ + _nct_sf(x, v, l) + + Survival function of noncentral t-distribution. + + Parameters + ---------- + x : array_like + Real-valued + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_isf", + """ + _nct_isf(x, v, l) + + Inverse survival function of noncentral t-distribution. + + Parameters + ---------- + x : array_like + Real-valued + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_mean", + """ + _nct_mean(v, l) + + Mean of noncentral t-distribution. + + Parameters + ---------- + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_variance", + """ + _nct_variance(v, l) + + Variance of noncentral t-distribution. + + Parameters + ---------- + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_skewness", + """ + _nct_skewness(v, l) + + Skewness of noncentral t-distribution. + + Parameters + ---------- + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nct_kurtosis_excess", + """ + _nct_kurtosis_excess(v, l) + + Kurtosis excess of noncentral t-distribution. + + Parameters + ---------- + v : array_like + Positive, real-valued parameters + l : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_skewnorm_cdf", + """ + _skewnorm_cdf(x, l, sc, sh) + + Cumulative density function of skewnorm distribution. + + Parameters + ---------- + x : array_like + Real-valued + l : array_like + Real-valued parameters + sc : array_like + Positive, Real-valued parameters + sh : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_skewnorm_ppf", + """ + _skewnorm_ppf(x, l, sc, sh) + + Percent point function of skewnorm distribution. + + Parameters + ---------- + x : array_like + Real-valued + l : array_like + Real-valued parameters + sc : array_like + Positive, Real-valued parameters + sh : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_skewnorm_isf", + """ + _skewnorm_isf(x, l, sc, sh) + + Inverse survival function of skewnorm distribution. + + Parameters + ---------- + x : array_like + Real-valued + l : array_like + Real-valued parameters + sc : array_like + Positive, Real-valued parameters + sh : array_like + Real-valued parameters + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_binom_pmf", + """ + _binom_pmf(x, n, p) + + Probability mass function of binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + n : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_binom_cdf", + """ + _binom_cdf(x, n, p) + + Cumulative density function of binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + n : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_binom_ppf", + """ + _binom_ppf(x, n, p) + + Percent point function of binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + n : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_binom_sf", + """ + _binom_sf(x, n, p) + + Survival function of binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + n : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_binom_isf", + """ + _binom_isf(x, n, p) + + Inverse survival function of binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + n : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_pmf", + """ + _nbinom_pmf(x, r, p) + + Probability mass function of negative binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_cdf", + """ + _nbinom_cdf(x, r, p) + + Cumulative density function of negative binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_ppf", + """ + _nbinom_ppf(x, r, p) + + Percent point function of negative binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_sf", + """ + _nbinom_sf(x, r, p) + + Survival function of negative binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_isf", + """ + _nbinom_isf(x, r, p) + + Inverse survival function of negative binomial distribution. + + Parameters + ---------- + x : array_like + Real-valued + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_mean", + """ + _nbinom_mean(r, p) + + Mean of negative binomial distribution. + + Parameters + ---------- + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_variance", + """ + _nbinom_variance(r, p) + + Variance of negative binomial distribution. + + Parameters + ---------- + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_skewness", + """ + _nbinom_skewness(r, p) + + Skewness of negative binomial distribution. + + Parameters + ---------- + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_nbinom_kurtosis_excess", + """ + _nbinom_kurtosis_excess(r, p) + + Kurtosis excess of negative binomial distribution. + + Parameters + ---------- + r : array_like + Positive, integer-valued parameter + p : array_like + Positive, real-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_hypergeom_pmf", + """ + _hypergeom_pmf(x, r, N, M) + + Probability mass function of hypergeometric distribution. + + Parameters + ---------- + x : array_like + Real-valued + r, N, M : array_like + Positive, integer-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_hypergeom_cdf", + """ + _hypergeom_cdf(x, r, N, M) + + Cumulative density function of hypergeometric distribution. + + Parameters + ---------- + x : array_like + Real-valued + r, N, M : array_like + Positive, integer-valued parameter + + Returns + ------- + scalar or ndarray + """) + +add_newdoc( + "_hypergeom_sf", + """ + _hypergeom_sf(x, r, N, M) + + Survival function of hypergeometric distribution. + + Parameters + ---------- + x : array_like + Real-valued + r, N, M : array_like + Positive, integer-valued parameter + + Returns + ------- + scalar or ndarray + """) + +add_newdoc( + "_hypergeom_mean", + """ + _hypergeom_mean(r, N, M) + + Mean of hypergeometric distribution. + + Parameters + ---------- + r, N, M : array_like + Positive, integer-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_hypergeom_variance", + """ + _hypergeom_variance(r, N, M) + + Mean of hypergeometric distribution. + + Parameters + ---------- + r, N, M : array_like + Positive, integer-valued parameter + + Returns + ------- + scalar or ndarray + + """) + +add_newdoc( + "_hypergeom_skewness", + """ + _hypergeom_skewness(r, N, M) + + Skewness of hypergeometric distribution. + + Parameters + ---------- + r, N, M : array_like + Positive, integer-valued parameter + + Returns + ------- + scalar or ndarray + + """) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..76b13b309eed0c036dd226ff96f0e020f296e032 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_basic.py @@ -0,0 +1,3579 @@ +# +# Author: Travis Oliphant, 2002 +# + +import numpy as np +import math +import warnings +from collections import defaultdict +from heapq import heapify, heappop +from numpy import (pi, asarray, floor, isscalar, sqrt, where, + sin, place, issubdtype, extract, inexact, nan, zeros, sinc) + +from . import _ufuncs +from ._ufuncs import (mathieu_a, mathieu_b, iv, jv, gamma, rgamma, + psi, hankel1, hankel2, yv, kv, poch, binom, + _stirling2_inexact) + +from ._gufuncs import _lqn, _lqmn, _rctj, _rcty +from ._input_validation import _nonneg_int_or_fail +from . import _specfun +from ._comb import _comb_int +from ._multiufuncs import (assoc_legendre_p_all, + legendre_p_all) +from scipy._lib.deprecation import _deprecated + + +__all__ = [ + 'ai_zeros', + 'assoc_laguerre', + 'bei_zeros', + 'beip_zeros', + 'ber_zeros', + 'bernoulli', + 'berp_zeros', + 'bi_zeros', + 'clpmn', + 'comb', + 'digamma', + 'diric', + 'erf_zeros', + 'euler', + 'factorial', + 'factorial2', + 'factorialk', + 'fresnel_zeros', + 'fresnelc_zeros', + 'fresnels_zeros', + 'h1vp', + 'h2vp', + 'ivp', + 'jn_zeros', + 'jnjnp_zeros', + 'jnp_zeros', + 'jnyn_zeros', + 'jvp', + 'kei_zeros', + 'keip_zeros', + 'kelvin_zeros', + 'ker_zeros', + 'kerp_zeros', + 'kvp', + 'lmbda', + 'lpmn', + 'lpn', + 'lqmn', + 'lqn', + 'mathieu_even_coef', + 'mathieu_odd_coef', + 'obl_cv_seq', + 'pbdn_seq', + 'pbdv_seq', + 'pbvv_seq', + 'perm', + 'polygamma', + 'pro_cv_seq', + 'riccati_jn', + 'riccati_yn', + 'sinc', + 'softplus', + 'stirling2', + 'y0_zeros', + 'y1_zeros', + 'y1p_zeros', + 'yn_zeros', + 'ynp_zeros', + 'yvp', + 'zeta' +] + + +__DEPRECATION_MSG_1_15 = ( + "`scipy.special.{}` is deprecated as of SciPy 1.15.0 and will be " + "removed in SciPy 1.17.0. Please use `scipy.special.{}` instead." +) + +# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int64).max +_FACTORIALK_LIMITS_64BITS = {1: 20, 2: 33, 3: 44, 4: 54, 5: 65, + 6: 74, 7: 84, 8: 93, 9: 101} +# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int32).max +_FACTORIALK_LIMITS_32BITS = {1: 12, 2: 19, 3: 25, 4: 31, 5: 37, + 6: 43, 7: 47, 8: 51, 9: 56} + + +def diric(x, n): + """Periodic sinc function, also called the Dirichlet function. + + The Dirichlet function is defined as:: + + diric(x, n) = sin(x * n/2) / (n * sin(x / 2)), + + where `n` is a positive integer. + + Parameters + ---------- + x : array_like + Input data + n : int + Integer defining the periodicity. + + Returns + ------- + diric : ndarray + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + + >>> x = np.linspace(-8*np.pi, 8*np.pi, num=201) + >>> plt.figure(figsize=(8, 8)); + >>> for idx, n in enumerate([2, 3, 4, 9]): + ... plt.subplot(2, 2, idx+1) + ... plt.plot(x, special.diric(x, n)) + ... plt.title('diric, n={}'.format(n)) + >>> plt.show() + + The following example demonstrates that `diric` gives the magnitudes + (modulo the sign and scaling) of the Fourier coefficients of a + rectangular pulse. + + Suppress output of values that are effectively 0: + + >>> np.set_printoptions(suppress=True) + + Create a signal `x` of length `m` with `k` ones: + + >>> m = 8 + >>> k = 3 + >>> x = np.zeros(m) + >>> x[:k] = 1 + + Use the FFT to compute the Fourier transform of `x`, and + inspect the magnitudes of the coefficients: + + >>> np.abs(np.fft.fft(x)) + array([ 3. , 2.41421356, 1. , 0.41421356, 1. , + 0.41421356, 1. , 2.41421356]) + + Now find the same values (up to sign) using `diric`. We multiply + by `k` to account for the different scaling conventions of + `numpy.fft.fft` and `diric`: + + >>> theta = np.linspace(0, 2*np.pi, m, endpoint=False) + >>> k * special.diric(theta, k) + array([ 3. , 2.41421356, 1. , -0.41421356, -1. , + -0.41421356, 1. , 2.41421356]) + """ + x, n = asarray(x), asarray(n) + n = asarray(n + (x-x)) + x = asarray(x + (n-n)) + if issubdtype(x.dtype, inexact): + ytype = x.dtype + else: + ytype = float + y = zeros(x.shape, ytype) + + # empirical minval for 32, 64 or 128 bit float computations + # where sin(x/2) < minval, result is fixed at +1 or -1 + if np.finfo(ytype).eps < 1e-18: + minval = 1e-11 + elif np.finfo(ytype).eps < 1e-15: + minval = 1e-7 + else: + minval = 1e-3 + + mask1 = (n <= 0) | (n != floor(n)) + place(y, mask1, nan) + + x = x / 2 + denom = sin(x) + mask2 = (1-mask1) & (abs(denom) < minval) + xsub = extract(mask2, x) + nsub = extract(mask2, n) + zsub = xsub / pi + place(y, mask2, pow(-1, np.round(zsub)*(nsub-1))) + + mask = (1-mask1) & (1-mask2) + xsub = extract(mask, x) + nsub = extract(mask, n) + dsub = extract(mask, denom) + place(y, mask, sin(nsub*xsub)/(nsub*dsub)) + return y + + +def jnjnp_zeros(nt): + """Compute zeros of integer-order Bessel functions Jn and Jn'. + + Results are arranged in order of the magnitudes of the zeros. + + Parameters + ---------- + nt : int + Number (<=1200) of zeros to compute + + Returns + ------- + zo[l-1] : ndarray + Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`. + n[l-1] : ndarray + Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`. + m[l-1] : ndarray + Serial number of the zeros of Jn(x) or Jn'(x) associated + with lth zero. Of length `nt`. + t[l-1] : ndarray + 0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of + length `nt`. + + See Also + -------- + jn_zeros, jnp_zeros : to get separated arrays of zeros. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200): + raise ValueError("Number must be integer <= 1200.") + nt = int(nt) + n, m, t, zo = _specfun.jdzo(nt) + return zo[1:nt+1], n[:nt], m[:nt], t[:nt] + + +def jnyn_zeros(n, nt): + """Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x). + + Returns 4 arrays of length `nt`, corresponding to the first `nt` + zeros of Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively. The zeros + are returned in ascending order. + + Parameters + ---------- + n : int + Order of the Bessel functions + nt : int + Number (<=1200) of zeros to compute + + Returns + ------- + Jn : ndarray + First `nt` zeros of Jn + Jnp : ndarray + First `nt` zeros of Jn' + Yn : ndarray + First `nt` zeros of Yn + Ynp : ndarray + First `nt` zeros of Yn' + + See Also + -------- + jn_zeros, jnp_zeros, yn_zeros, ynp_zeros + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first three roots of :math:`J_1`, :math:`J_1'`, + :math:`Y_1` and :math:`Y_1'`. + + >>> from scipy.special import jnyn_zeros + >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3) + >>> jn_roots, yn_roots + (array([ 3.83170597, 7.01558667, 10.17346814]), + array([2.19714133, 5.42968104, 8.59600587])) + + Plot :math:`J_1`, :math:`J_1'`, :math:`Y_1`, :math:`Y_1'` and their roots. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import jnyn_zeros, jvp, jn, yvp, yn + >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3) + >>> fig, ax = plt.subplots() + >>> xmax= 11 + >>> x = np.linspace(0, xmax) + >>> x[0] += 1e-15 + >>> ax.plot(x, jn(1, x), label=r"$J_1$", c='r') + >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$", c='b') + >>> ax.plot(x, yn(1, x), label=r"$Y_1$", c='y') + >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$", c='c') + >>> zeros = np.zeros((3, )) + >>> ax.scatter(jn_roots, zeros, s=30, c='r', zorder=5, + ... label=r"$J_1$ roots") + >>> ax.scatter(jnp_roots, zeros, s=30, c='b', zorder=5, + ... label=r"$J_1'$ roots") + >>> ax.scatter(yn_roots, zeros, s=30, c='y', zorder=5, + ... label=r"$Y_1$ roots") + >>> ax.scatter(ynp_roots, zeros, s=30, c='c', zorder=5, + ... label=r"$Y_1'$ roots") + >>> ax.hlines(0, 0, xmax, color='k') + >>> ax.set_ylim(-0.6, 0.6) + >>> ax.set_xlim(0, xmax) + >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75)) + >>> plt.tight_layout() + >>> plt.show() + """ + if not (isscalar(nt) and isscalar(n)): + raise ValueError("Arguments must be scalars.") + if (floor(n) != n) or (floor(nt) != nt): + raise ValueError("Arguments must be integers.") + if (nt <= 0): + raise ValueError("nt > 0") + return _specfun.jyzo(abs(n), nt) + + +def jn_zeros(n, nt): + r"""Compute zeros of integer-order Bessel functions Jn. + + Compute `nt` zeros of the Bessel functions :math:`J_n(x)` on the + interval :math:`(0, \infty)`. The zeros are returned in ascending + order. Note that this interval excludes the zero at :math:`x = 0` + that exists for :math:`n > 0`. + + Parameters + ---------- + n : int + Order of Bessel function + nt : int + Number of zeros to return + + Returns + ------- + ndarray + First `nt` zeros of the Bessel function. + + See Also + -------- + jv: Real-order Bessel functions of the first kind + jnp_zeros: Zeros of :math:`Jn'` + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first four positive roots of :math:`J_3`. + + >>> from scipy.special import jn_zeros + >>> jn_zeros(3, 4) + array([ 6.3801619 , 9.76102313, 13.01520072, 16.22346616]) + + Plot :math:`J_3` and its first four positive roots. Note + that the root located at 0 is not returned by `jn_zeros`. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import jn, jn_zeros + >>> j3_roots = jn_zeros(3, 4) + >>> xmax = 18 + >>> xmin = -1 + >>> x = np.linspace(xmin, xmax, 500) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, jn(3, x), label=r'$J_3$') + >>> ax.scatter(j3_roots, np.zeros((4, )), s=30, c='r', + ... label=r"$J_3$_Zeros", zorder=5) + >>> ax.scatter(0, 0, s=30, c='k', + ... label=r"Root at 0", zorder=5) + >>> ax.hlines(0, 0, xmax, color='k') + >>> ax.set_xlim(xmin, xmax) + >>> plt.legend() + >>> plt.show() + """ + return jnyn_zeros(n, nt)[0] + + +def jnp_zeros(n, nt): + r"""Compute zeros of integer-order Bessel function derivatives Jn'. + + Compute `nt` zeros of the functions :math:`J_n'(x)` on the + interval :math:`(0, \infty)`. The zeros are returned in ascending + order. Note that this interval excludes the zero at :math:`x = 0` + that exists for :math:`n > 1`. + + Parameters + ---------- + n : int + Order of Bessel function + nt : int + Number of zeros to return + + Returns + ------- + ndarray + First `nt` zeros of the Bessel function. + + See Also + -------- + jvp: Derivatives of integer-order Bessel functions of the first kind + jv: Float-order Bessel functions of the first kind + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first four roots of :math:`J_2'`. + + >>> from scipy.special import jnp_zeros + >>> jnp_zeros(2, 4) + array([ 3.05423693, 6.70613319, 9.96946782, 13.17037086]) + + As `jnp_zeros` yields the roots of :math:`J_n'`, it can be used to + compute the locations of the peaks of :math:`J_n`. Plot + :math:`J_2`, :math:`J_2'` and the locations of the roots of :math:`J_2'`. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import jn, jnp_zeros, jvp + >>> j2_roots = jnp_zeros(2, 4) + >>> xmax = 15 + >>> x = np.linspace(0, xmax, 500) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, jn(2, x), label=r'$J_2$') + >>> ax.plot(x, jvp(2, x, 1), label=r"$J_2'$") + >>> ax.hlines(0, 0, xmax, color='k') + >>> ax.scatter(j2_roots, np.zeros((4, )), s=30, c='r', + ... label=r"Roots of $J_2'$", zorder=5) + >>> ax.set_ylim(-0.4, 0.8) + >>> ax.set_xlim(0, xmax) + >>> plt.legend() + >>> plt.show() + """ + return jnyn_zeros(n, nt)[1] + + +def yn_zeros(n, nt): + r"""Compute zeros of integer-order Bessel function Yn(x). + + Compute `nt` zeros of the functions :math:`Y_n(x)` on the interval + :math:`(0, \infty)`. The zeros are returned in ascending order. + + Parameters + ---------- + n : int + Order of Bessel function + nt : int + Number of zeros to return + + Returns + ------- + ndarray + First `nt` zeros of the Bessel function. + + See Also + -------- + yn: Bessel function of the second kind for integer order + yv: Bessel function of the second kind for real order + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first four roots of :math:`Y_2`. + + >>> from scipy.special import yn_zeros + >>> yn_zeros(2, 4) + array([ 3.38424177, 6.79380751, 10.02347798, 13.20998671]) + + Plot :math:`Y_2` and its first four roots. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import yn, yn_zeros + >>> xmin = 2 + >>> xmax = 15 + >>> x = np.linspace(xmin, xmax, 500) + >>> fig, ax = plt.subplots() + >>> ax.hlines(0, xmin, xmax, color='k') + >>> ax.plot(x, yn(2, x), label=r'$Y_2$') + >>> ax.scatter(yn_zeros(2, 4), np.zeros((4, )), s=30, c='r', + ... label='Roots', zorder=5) + >>> ax.set_ylim(-0.4, 0.4) + >>> ax.set_xlim(xmin, xmax) + >>> plt.legend() + >>> plt.show() + """ + return jnyn_zeros(n, nt)[2] + + +def ynp_zeros(n, nt): + r"""Compute zeros of integer-order Bessel function derivatives Yn'(x). + + Compute `nt` zeros of the functions :math:`Y_n'(x)` on the + interval :math:`(0, \infty)`. The zeros are returned in ascending + order. + + Parameters + ---------- + n : int + Order of Bessel function + nt : int + Number of zeros to return + + Returns + ------- + ndarray + First `nt` zeros of the Bessel derivative function. + + + See Also + -------- + yvp + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first four roots of the first derivative of the + Bessel function of second kind for order 0 :math:`Y_0'`. + + >>> from scipy.special import ynp_zeros + >>> ynp_zeros(0, 4) + array([ 2.19714133, 5.42968104, 8.59600587, 11.74915483]) + + Plot :math:`Y_0`, :math:`Y_0'` and confirm visually that the roots of + :math:`Y_0'` are located at local extrema of :math:`Y_0`. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.special import yn, ynp_zeros, yvp + >>> zeros = ynp_zeros(0, 4) + >>> xmax = 13 + >>> x = np.linspace(0, xmax, 500) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, yn(0, x), label=r'$Y_0$') + >>> ax.plot(x, yvp(0, x, 1), label=r"$Y_0'$") + >>> ax.scatter(zeros, np.zeros((4, )), s=30, c='r', + ... label=r"Roots of $Y_0'$", zorder=5) + >>> for root in zeros: + ... y0_extremum = yn(0, root) + ... lower = min(0, y0_extremum) + ... upper = max(0, y0_extremum) + ... ax.vlines(root, lower, upper, color='r') + >>> ax.hlines(0, 0, xmax, color='k') + >>> ax.set_ylim(-0.6, 0.6) + >>> ax.set_xlim(0, xmax) + >>> plt.legend() + >>> plt.show() + """ + return jnyn_zeros(n, nt)[3] + + +def y0_zeros(nt, complex=False): + """Compute nt zeros of Bessel function Y0(z), and derivative at each zero. + + The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0. + + Parameters + ---------- + nt : int + Number of zeros to return + complex : bool, default False + Set to False to return only the real zeros; set to True to return only + the complex zeros with negative real part and positive imaginary part. + Note that the complex conjugates of the latter are also zeros of the + function, but are not returned by this routine. + + Returns + ------- + z0n : ndarray + Location of nth zero of Y0(z) + y0pz0n : ndarray + Value of derivative Y0'(z0) for nth zero + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first 4 real roots and the derivatives at the roots of + :math:`Y_0`: + + >>> import numpy as np + >>> from scipy.special import y0_zeros + >>> zeros, grads = y0_zeros(4) + >>> with np.printoptions(precision=5): + ... print(f"Roots: {zeros}") + ... print(f"Gradients: {grads}") + Roots: [ 0.89358+0.j 3.95768+0.j 7.08605+0.j 10.22235+0.j] + Gradients: [-0.87942+0.j 0.40254+0.j -0.3001 +0.j 0.2497 +0.j] + + Plot the real part of :math:`Y_0` and the first four computed roots. + + >>> import matplotlib.pyplot as plt + >>> from scipy.special import y0 + >>> xmin = 0 + >>> xmax = 11 + >>> x = np.linspace(xmin, xmax, 500) + >>> fig, ax = plt.subplots() + >>> ax.hlines(0, xmin, xmax, color='k') + >>> ax.plot(x, y0(x), label=r'$Y_0$') + >>> zeros, grads = y0_zeros(4) + >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r', + ... label=r'$Y_0$_zeros', zorder=5) + >>> ax.set_ylim(-0.5, 0.6) + >>> ax.set_xlim(xmin, xmax) + >>> plt.legend(ncol=2) + >>> plt.show() + + Compute the first 4 complex roots and the derivatives at the roots of + :math:`Y_0` by setting ``complex=True``: + + >>> y0_zeros(4, True) + (array([ -2.40301663+0.53988231j, -5.5198767 +0.54718001j, + -8.6536724 +0.54841207j, -11.79151203+0.54881912j]), + array([ 0.10074769-0.88196771j, -0.02924642+0.5871695j , + 0.01490806-0.46945875j, -0.00937368+0.40230454j])) + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("Arguments must be scalar positive integer.") + kf = 0 + kc = not complex + return _specfun.cyzo(nt, kf, kc) + + +def y1_zeros(nt, complex=False): + """Compute nt zeros of Bessel function Y1(z), and derivative at each zero. + + The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1. + + Parameters + ---------- + nt : int + Number of zeros to return + complex : bool, default False + Set to False to return only the real zeros; set to True to return only + the complex zeros with negative real part and positive imaginary part. + Note that the complex conjugates of the latter are also zeros of the + function, but are not returned by this routine. + + Returns + ------- + z1n : ndarray + Location of nth zero of Y1(z) + y1pz1n : ndarray + Value of derivative Y1'(z1) for nth zero + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first 4 real roots and the derivatives at the roots of + :math:`Y_1`: + + >>> import numpy as np + >>> from scipy.special import y1_zeros + >>> zeros, grads = y1_zeros(4) + >>> with np.printoptions(precision=5): + ... print(f"Roots: {zeros}") + ... print(f"Gradients: {grads}") + Roots: [ 2.19714+0.j 5.42968+0.j 8.59601+0.j 11.74915+0.j] + Gradients: [ 0.52079+0.j -0.34032+0.j 0.27146+0.j -0.23246+0.j] + + Extract the real parts: + + >>> realzeros = zeros.real + >>> realzeros + array([ 2.19714133, 5.42968104, 8.59600587, 11.74915483]) + + Plot :math:`Y_1` and the first four computed roots. + + >>> import matplotlib.pyplot as plt + >>> from scipy.special import y1 + >>> xmin = 0 + >>> xmax = 13 + >>> x = np.linspace(xmin, xmax, 500) + >>> zeros, grads = y1_zeros(4) + >>> fig, ax = plt.subplots() + >>> ax.hlines(0, xmin, xmax, color='k') + >>> ax.plot(x, y1(x), label=r'$Y_1$') + >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r', + ... label=r'$Y_1$_zeros', zorder=5) + >>> ax.set_ylim(-0.5, 0.5) + >>> ax.set_xlim(xmin, xmax) + >>> plt.legend() + >>> plt.show() + + Compute the first 4 complex roots and the derivatives at the roots of + :math:`Y_1` by setting ``complex=True``: + + >>> y1_zeros(4, True) + (array([ -0.50274327+0.78624371j, -3.83353519+0.56235654j, + -7.01590368+0.55339305j, -10.17357383+0.55127339j]), + array([-0.45952768+1.31710194j, 0.04830191-0.69251288j, + -0.02012695+0.51864253j, 0.011614 -0.43203296j])) + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("Arguments must be scalar positive integer.") + kf = 1 + kc = not complex + return _specfun.cyzo(nt, kf, kc) + + +def y1p_zeros(nt, complex=False): + """Compute nt zeros of Bessel derivative Y1'(z), and value at each zero. + + The values are given by Y1(z1) at each z1 where Y1'(z1)=0. + + Parameters + ---------- + nt : int + Number of zeros to return + complex : bool, default False + Set to False to return only the real zeros; set to True to return only + the complex zeros with negative real part and positive imaginary part. + Note that the complex conjugates of the latter are also zeros of the + function, but are not returned by this routine. + + Returns + ------- + z1pn : ndarray + Location of nth zero of Y1'(z) + y1z1pn : ndarray + Value of derivative Y1(z1) for nth zero + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + Compute the first four roots of :math:`Y_1'` and the values of + :math:`Y_1` at these roots. + + >>> import numpy as np + >>> from scipy.special import y1p_zeros + >>> y1grad_roots, y1_values = y1p_zeros(4) + >>> with np.printoptions(precision=5): + ... print(f"Y1' Roots: {y1grad_roots.real}") + ... print(f"Y1 values: {y1_values.real}") + Y1' Roots: [ 3.68302 6.9415 10.1234 13.28576] + Y1 values: [ 0.41673 -0.30317 0.25091 -0.21897] + + `y1p_zeros` can be used to calculate the extremal points of :math:`Y_1` + directly. Here we plot :math:`Y_1` and the first four extrema. + + >>> import matplotlib.pyplot as plt + >>> from scipy.special import y1, yvp + >>> y1_roots, y1_values_at_roots = y1p_zeros(4) + >>> real_roots = y1_roots.real + >>> xmax = 15 + >>> x = np.linspace(0, xmax, 500) + >>> x[0] += 1e-15 + >>> fig, ax = plt.subplots() + >>> ax.plot(x, y1(x), label=r'$Y_1$') + >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$") + >>> ax.scatter(real_roots, np.zeros((4, )), s=30, c='r', + ... label=r"Roots of $Y_1'$", zorder=5) + >>> ax.scatter(real_roots, y1_values_at_roots.real, s=30, c='k', + ... label=r"Extrema of $Y_1$", zorder=5) + >>> ax.hlines(0, 0, xmax, color='k') + >>> ax.set_ylim(-0.5, 0.5) + >>> ax.set_xlim(0, xmax) + >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75)) + >>> plt.tight_layout() + >>> plt.show() + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("Arguments must be scalar positive integer.") + kf = 2 + kc = not complex + return _specfun.cyzo(nt, kf, kc) + + +def _bessel_diff_formula(v, z, n, L, phase): + # from AMS55. + # L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1 + # L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1 + # For K, you can pull out the exp((v-k)*pi*i) into the caller + v = asarray(v) + p = 1.0 + s = L(v-n, z) + for i in range(1, n+1): + p = phase * (p * (n-i+1)) / i # = choose(k, i) + s += p*L(v-n + i*2, z) + return s / (2.**n) + + +def jvp(v, z, n=1): + """Compute derivatives of Bessel functions of the first kind. + + Compute the nth derivative of the Bessel function `Jv` with + respect to `z`. + + Parameters + ---------- + v : array_like or float + Order of Bessel function + z : complex + Argument at which to evaluate the derivative; can be real or + complex. + n : int, default 1 + Order of derivative. For 0 returns the Bessel function `jv` itself. + + Returns + ------- + scalar or ndarray + Values of the derivative of the Bessel function. + + Notes + ----- + The derivative is computed using the relation DLFM 10.6.7 [2]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.6.E7 + + Examples + -------- + + Compute the Bessel function of the first kind of order 0 and + its first two derivatives at 1. + + >>> from scipy.special import jvp + >>> jvp(0, 1, 0), jvp(0, 1, 1), jvp(0, 1, 2) + (0.7651976865579666, -0.44005058574493355, -0.3251471008130331) + + Compute the first derivative of the Bessel function of the first + kind for several orders at 1 by providing an array for `v`. + + >>> jvp([0, 1, 2], 1, 1) + array([-0.44005059, 0.3251471 , 0.21024362]) + + Compute the first derivative of the Bessel function of the first + kind of order 0 at several points by providing an array for `z`. + + >>> import numpy as np + >>> points = np.array([0., 1.5, 3.]) + >>> jvp(0, points, 1) + array([-0. , -0.55793651, -0.33905896]) + + Plot the Bessel function of the first kind of order 1 and its + first three derivatives. + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-10, 10, 1000) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, jvp(1, x, 0), label=r"$J_1$") + >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$") + >>> ax.plot(x, jvp(1, x, 2), label=r"$J_1''$") + >>> ax.plot(x, jvp(1, x, 3), label=r"$J_1'''$") + >>> plt.legend() + >>> plt.show() + """ + n = _nonneg_int_or_fail(n, 'n') + if n == 0: + return jv(v, z) + else: + return _bessel_diff_formula(v, z, n, jv, -1) + + +def yvp(v, z, n=1): + """Compute derivatives of Bessel functions of the second kind. + + Compute the nth derivative of the Bessel function `Yv` with + respect to `z`. + + Parameters + ---------- + v : array_like of float + Order of Bessel function + z : complex + Argument at which to evaluate the derivative + n : int, default 1 + Order of derivative. For 0 returns the BEssel function `yv` + + Returns + ------- + scalar or ndarray + nth derivative of the Bessel function. + + See Also + -------- + yv : Bessel functions of the second kind + + Notes + ----- + The derivative is computed using the relation DLFM 10.6.7 [2]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.6.E7 + + Examples + -------- + Compute the Bessel function of the second kind of order 0 and + its first two derivatives at 1. + + >>> from scipy.special import yvp + >>> yvp(0, 1, 0), yvp(0, 1, 1), yvp(0, 1, 2) + (0.088256964215677, 0.7812128213002889, -0.8694697855159659) + + Compute the first derivative of the Bessel function of the second + kind for several orders at 1 by providing an array for `v`. + + >>> yvp([0, 1, 2], 1, 1) + array([0.78121282, 0.86946979, 2.52015239]) + + Compute the first derivative of the Bessel function of the + second kind of order 0 at several points by providing an array for `z`. + + >>> import numpy as np + >>> points = np.array([0.5, 1.5, 3.]) + >>> yvp(0, points, 1) + array([ 1.47147239, 0.41230863, -0.32467442]) + + Plot the Bessel function of the second kind of order 1 and its + first three derivatives. + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0, 5, 1000) + >>> x[0] += 1e-15 + >>> fig, ax = plt.subplots() + >>> ax.plot(x, yvp(1, x, 0), label=r"$Y_1$") + >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$") + >>> ax.plot(x, yvp(1, x, 2), label=r"$Y_1''$") + >>> ax.plot(x, yvp(1, x, 3), label=r"$Y_1'''$") + >>> ax.set_ylim(-10, 10) + >>> plt.legend() + >>> plt.show() + """ + n = _nonneg_int_or_fail(n, 'n') + if n == 0: + return yv(v, z) + else: + return _bessel_diff_formula(v, z, n, yv, -1) + + +def kvp(v, z, n=1): + """Compute derivatives of real-order modified Bessel function Kv(z) + + Kv(z) is the modified Bessel function of the second kind. + Derivative is calculated with respect to `z`. + + Parameters + ---------- + v : array_like of float + Order of Bessel function + z : array_like of complex + Argument at which to evaluate the derivative + n : int, default 1 + Order of derivative. For 0 returns the Bessel function `kv` itself. + + Returns + ------- + out : ndarray + The results + + See Also + -------- + kv + + Notes + ----- + The derivative is computed using the relation DLFM 10.29.5 [2]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 6. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.29.E5 + + Examples + -------- + Compute the modified bessel function of the second kind of order 0 and + its first two derivatives at 1. + + >>> from scipy.special import kvp + >>> kvp(0, 1, 0), kvp(0, 1, 1), kvp(0, 1, 2) + (0.42102443824070834, -0.6019072301972346, 1.0229316684379428) + + Compute the first derivative of the modified Bessel function of the second + kind for several orders at 1 by providing an array for `v`. + + >>> kvp([0, 1, 2], 1, 1) + array([-0.60190723, -1.02293167, -3.85158503]) + + Compute the first derivative of the modified Bessel function of the + second kind of order 0 at several points by providing an array for `z`. + + >>> import numpy as np + >>> points = np.array([0.5, 1.5, 3.]) + >>> kvp(0, points, 1) + array([-1.65644112, -0.2773878 , -0.04015643]) + + Plot the modified bessel function of the second kind and its + first three derivatives. + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0, 5, 1000) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, kvp(1, x, 0), label=r"$K_1$") + >>> ax.plot(x, kvp(1, x, 1), label=r"$K_1'$") + >>> ax.plot(x, kvp(1, x, 2), label=r"$K_1''$") + >>> ax.plot(x, kvp(1, x, 3), label=r"$K_1'''$") + >>> ax.set_ylim(-2.5, 2.5) + >>> plt.legend() + >>> plt.show() + """ + n = _nonneg_int_or_fail(n, 'n') + if n == 0: + return kv(v, z) + else: + return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1) + + +def ivp(v, z, n=1): + """Compute derivatives of modified Bessel functions of the first kind. + + Compute the nth derivative of the modified Bessel function `Iv` + with respect to `z`. + + Parameters + ---------- + v : array_like or float + Order of Bessel function + z : array_like + Argument at which to evaluate the derivative; can be real or + complex. + n : int, default 1 + Order of derivative. For 0, returns the Bessel function `iv` itself. + + Returns + ------- + scalar or ndarray + nth derivative of the modified Bessel function. + + See Also + -------- + iv + + Notes + ----- + The derivative is computed using the relation DLFM 10.29.5 [2]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 6. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.29.E5 + + Examples + -------- + Compute the modified Bessel function of the first kind of order 0 and + its first two derivatives at 1. + + >>> from scipy.special import ivp + >>> ivp(0, 1, 0), ivp(0, 1, 1), ivp(0, 1, 2) + (1.2660658777520084, 0.565159103992485, 0.7009067737595233) + + Compute the first derivative of the modified Bessel function of the first + kind for several orders at 1 by providing an array for `v`. + + >>> ivp([0, 1, 2], 1, 1) + array([0.5651591 , 0.70090677, 0.29366376]) + + Compute the first derivative of the modified Bessel function of the + first kind of order 0 at several points by providing an array for `z`. + + >>> import numpy as np + >>> points = np.array([0., 1.5, 3.]) + >>> ivp(0, points, 1) + array([0. , 0.98166643, 3.95337022]) + + Plot the modified Bessel function of the first kind of order 1 and its + first three derivatives. + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-5, 5, 1000) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, ivp(1, x, 0), label=r"$I_1$") + >>> ax.plot(x, ivp(1, x, 1), label=r"$I_1'$") + >>> ax.plot(x, ivp(1, x, 2), label=r"$I_1''$") + >>> ax.plot(x, ivp(1, x, 3), label=r"$I_1'''$") + >>> plt.legend() + >>> plt.show() + """ + n = _nonneg_int_or_fail(n, 'n') + if n == 0: + return iv(v, z) + else: + return _bessel_diff_formula(v, z, n, iv, 1) + + +def h1vp(v, z, n=1): + """Compute derivatives of Hankel function H1v(z) with respect to `z`. + + Parameters + ---------- + v : array_like + Order of Hankel function + z : array_like + Argument at which to evaluate the derivative. Can be real or + complex. + n : int, default 1 + Order of derivative. For 0 returns the Hankel function `h1v` itself. + + Returns + ------- + scalar or ndarray + Values of the derivative of the Hankel function. + + See Also + -------- + hankel1 + + Notes + ----- + The derivative is computed using the relation DLFM 10.6.7 [2]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.6.E7 + + Examples + -------- + Compute the Hankel function of the first kind of order 0 and + its first two derivatives at 1. + + >>> from scipy.special import h1vp + >>> h1vp(0, 1, 0), h1vp(0, 1, 1), h1vp(0, 1, 2) + ((0.7651976865579664+0.088256964215677j), + (-0.44005058574493355+0.7812128213002889j), + (-0.3251471008130329-0.8694697855159659j)) + + Compute the first derivative of the Hankel function of the first kind + for several orders at 1 by providing an array for `v`. + + >>> h1vp([0, 1, 2], 1, 1) + array([-0.44005059+0.78121282j, 0.3251471 +0.86946979j, + 0.21024362+2.52015239j]) + + Compute the first derivative of the Hankel function of the first kind + of order 0 at several points by providing an array for `z`. + + >>> import numpy as np + >>> points = np.array([0.5, 1.5, 3.]) + >>> h1vp(0, points, 1) + array([-0.24226846+1.47147239j, -0.55793651+0.41230863j, + -0.33905896-0.32467442j]) + """ + n = _nonneg_int_or_fail(n, 'n') + if n == 0: + return hankel1(v, z) + else: + return _bessel_diff_formula(v, z, n, hankel1, -1) + + +def h2vp(v, z, n=1): + """Compute derivatives of Hankel function H2v(z) with respect to `z`. + + Parameters + ---------- + v : array_like + Order of Hankel function + z : array_like + Argument at which to evaluate the derivative. Can be real or + complex. + n : int, default 1 + Order of derivative. For 0 returns the Hankel function `h2v` itself. + + Returns + ------- + scalar or ndarray + Values of the derivative of the Hankel function. + + See Also + -------- + hankel2 + + Notes + ----- + The derivative is computed using the relation DLFM 10.6.7 [2]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 5. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.6.E7 + + Examples + -------- + Compute the Hankel function of the second kind of order 0 and + its first two derivatives at 1. + + >>> from scipy.special import h2vp + >>> h2vp(0, 1, 0), h2vp(0, 1, 1), h2vp(0, 1, 2) + ((0.7651976865579664-0.088256964215677j), + (-0.44005058574493355-0.7812128213002889j), + (-0.3251471008130329+0.8694697855159659j)) + + Compute the first derivative of the Hankel function of the second kind + for several orders at 1 by providing an array for `v`. + + >>> h2vp([0, 1, 2], 1, 1) + array([-0.44005059-0.78121282j, 0.3251471 -0.86946979j, + 0.21024362-2.52015239j]) + + Compute the first derivative of the Hankel function of the second kind + of order 0 at several points by providing an array for `z`. + + >>> import numpy as np + >>> points = np.array([0.5, 1.5, 3.]) + >>> h2vp(0, points, 1) + array([-0.24226846-1.47147239j, -0.55793651-0.41230863j, + -0.33905896+0.32467442j]) + """ + n = _nonneg_int_or_fail(n, 'n') + if n == 0: + return hankel2(v, z) + else: + return _bessel_diff_formula(v, z, n, hankel2, -1) + + +def riccati_jn(n, x): + r"""Compute Ricatti-Bessel function of the first kind and its derivative. + + The Ricatti-Bessel function of the first kind is defined as :math:`x + j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first + kind of order :math:`n`. + + This function computes the value and first derivative of the + Ricatti-Bessel function for all orders up to and including `n`. + + Parameters + ---------- + n : int + Maximum order of function to compute + x : float + Argument at which to evaluate + + Returns + ------- + jn : ndarray + Value of j0(x), ..., jn(x) + jnp : ndarray + First derivative j0'(x), ..., jn'(x) + + Notes + ----- + The computation is carried out via backward recurrence, using the + relation DLMF 10.51.1 [2]_. + + Wrapper for a Fortran routine created by Shanjie Zhang and Jianming + Jin [1]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.51.E1 + + """ + if not (isscalar(n) and isscalar(x)): + raise ValueError("arguments must be scalars.") + n = _nonneg_int_or_fail(n, 'n', strict=False) + if (n == 0): + n1 = 1 + else: + n1 = n + + jn = np.empty((n1 + 1,), dtype=np.float64) + jnp = np.empty_like(jn) + + _rctj(x, out=(jn, jnp)) + return jn[:(n+1)], jnp[:(n+1)] + + +def riccati_yn(n, x): + """Compute Ricatti-Bessel function of the second kind and its derivative. + + The Ricatti-Bessel function of the second kind is defined here as :math:`+x + y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second + kind of order :math:`n`. *Note that this is in contrast to a common convention + that includes a minus sign in the definition.* + + This function computes the value and first derivative of the function for + all orders up to and including `n`. + + Parameters + ---------- + n : int + Maximum order of function to compute + x : float + Argument at which to evaluate + + Returns + ------- + yn : ndarray + Value of y0(x), ..., yn(x) + ynp : ndarray + First derivative y0'(x), ..., yn'(x) + + Notes + ----- + The computation is carried out via ascending recurrence, using the + relation DLMF 10.51.1 [2]_. + + Wrapper for a Fortran routine created by Shanjie Zhang and Jianming + Jin [1]_. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + .. [2] NIST Digital Library of Mathematical Functions. + https://dlmf.nist.gov/10.51.E1 + + """ + if not (isscalar(n) and isscalar(x)): + raise ValueError("arguments must be scalars.") + n = _nonneg_int_or_fail(n, 'n', strict=False) + if (n == 0): + n1 = 1 + else: + n1 = n + + yn = np.empty((n1 + 1,), dtype=np.float64) + ynp = np.empty_like(yn) + _rcty(x, out=(yn, ynp)) + + return yn[:(n+1)], ynp[:(n+1)] + + +def erf_zeros(nt): + """Compute the first nt zero in the first quadrant, ordered by absolute value. + + Zeros in the other quadrants can be obtained by using the symmetries + erf(-z) = erf(z) and erf(conj(z)) = conj(erf(z)). + + + Parameters + ---------- + nt : int + The number of zeros to compute + + Returns + ------- + The locations of the zeros of erf : ndarray (complex) + Complex values at which zeros of erf(z) + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + >>> from scipy import special + >>> special.erf_zeros(1) + array([1.45061616+1.880943j]) + + Check that erf is (close to) zero for the value returned by erf_zeros + + >>> special.erf(special.erf_zeros(1)) + array([4.95159469e-14-1.16407394e-16j]) + + """ + if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt): + raise ValueError("Argument must be positive scalar integer.") + return _specfun.cerzo(nt) + + +def fresnelc_zeros(nt): + """Compute nt complex zeros of cosine Fresnel integral C(z). + + Parameters + ---------- + nt : int + Number of zeros to compute + + Returns + ------- + fresnelc_zeros: ndarray + Zeros of the cosine Fresnel integral + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt): + raise ValueError("Argument must be positive scalar integer.") + return _specfun.fcszo(1, nt) + + +def fresnels_zeros(nt): + """Compute nt complex zeros of sine Fresnel integral S(z). + + Parameters + ---------- + nt : int + Number of zeros to compute + + Returns + ------- + fresnels_zeros: ndarray + Zeros of the sine Fresnel integral + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt): + raise ValueError("Argument must be positive scalar integer.") + return _specfun.fcszo(2, nt) + + +def fresnel_zeros(nt): + """Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z). + + Parameters + ---------- + nt : int + Number of zeros to compute + + Returns + ------- + zeros_sine: ndarray + Zeros of the sine Fresnel integral + zeros_cosine : ndarray + Zeros of the cosine Fresnel integral + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt): + raise ValueError("Argument must be positive scalar integer.") + return _specfun.fcszo(2, nt), _specfun.fcszo(1, nt) + + +def assoc_laguerre(x, n, k=0.0): + """Compute the generalized (associated) Laguerre polynomial of degree n and order k. + + The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``, + with weighting function ``exp(-x) * x**k`` with ``k > -1``. + + Parameters + ---------- + x : float or ndarray + Points where to evaluate the Laguerre polynomial + n : int + Degree of the Laguerre polynomial + k : int + Order of the Laguerre polynomial + + Returns + ------- + assoc_laguerre: float or ndarray + Associated laguerre polynomial values + + Notes + ----- + `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with + reversed argument order ``(x, n, k=0.0) --> (n, k, x)``. + + """ + return _ufuncs.eval_genlaguerre(n, k, x) + + +digamma = psi + + +def polygamma(n, x): + r"""Polygamma functions. + + Defined as :math:`\psi^{(n)}(x)` where :math:`\psi` is the + `digamma` function. See [dlmf]_ for details. + + Parameters + ---------- + n : array_like + The order of the derivative of the digamma function; must be + integral + x : array_like + Real valued input + + Returns + ------- + ndarray + Function results + + See Also + -------- + digamma + + References + ---------- + .. [dlmf] NIST, Digital Library of Mathematical Functions, + https://dlmf.nist.gov/5.15 + + Examples + -------- + >>> from scipy import special + >>> x = [2, 3, 25.5] + >>> special.polygamma(1, x) + array([ 0.64493407, 0.39493407, 0.03999467]) + >>> special.polygamma(0, x) == special.psi(x) + array([ True, True, True], dtype=bool) + + """ + n, x = asarray(n), asarray(x) + fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x) + return where(n == 0, psi(x), fac2) + + +def mathieu_even_coef(m, q): + r"""Fourier coefficients for even Mathieu and modified Mathieu functions. + + The Fourier series of the even solutions of the Mathieu differential + equation are of the form + + .. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz + + .. math:: \mathrm{ce}_{2n+1}(z, q) = + \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z + + This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even + input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input + m=2n+1. + + Parameters + ---------- + m : int + Order of Mathieu functions. Must be non-negative. + q : float (>=0) + Parameter of Mathieu functions. Must be non-negative. + + Returns + ------- + Ak : ndarray + Even or odd Fourier coefficients, corresponding to even or odd m. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + .. [2] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/28.4#i + + """ + if not (isscalar(m) and isscalar(q)): + raise ValueError("m and q must be scalars.") + if (q < 0): + raise ValueError("q >=0") + if (m != floor(m)) or (m < 0): + raise ValueError("m must be an integer >=0.") + + if (q <= 1): + qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q + else: + qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q + km = int(qm + 0.5*m) + if km > 251: + warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2) + kd = 1 + m = int(floor(m)) + if m % 2: + kd = 2 + + a = mathieu_a(m, q) + fc = _specfun.fcoef(kd, m, q, a) + return fc[:km] + + +def mathieu_odd_coef(m, q): + r"""Fourier coefficients for even Mathieu and modified Mathieu functions. + + The Fourier series of the odd solutions of the Mathieu differential + equation are of the form + + .. math:: \mathrm{se}_{2n+1}(z, q) = + \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z + + .. math:: \mathrm{se}_{2n+2}(z, q) = + \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z + + This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even + input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd + input m=2n+1. + + Parameters + ---------- + m : int + Order of Mathieu functions. Must be non-negative. + q : float (>=0) + Parameter of Mathieu functions. Must be non-negative. + + Returns + ------- + Bk : ndarray + Even or odd Fourier coefficients, corresponding to even or odd m. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not (isscalar(m) and isscalar(q)): + raise ValueError("m and q must be scalars.") + if (q < 0): + raise ValueError("q >=0") + if (m != floor(m)) or (m <= 0): + raise ValueError("m must be an integer > 0") + + if (q <= 1): + qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q + else: + qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q + km = int(qm + 0.5*m) + if km > 251: + warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2) + kd = 4 + m = int(floor(m)) + if m % 2: + kd = 3 + + b = mathieu_b(m, q) + fc = _specfun.fcoef(kd, m, q, b) + return fc[:km] + + +@_deprecated(__DEPRECATION_MSG_1_15.format("lpmn", "assoc_legendre_p_all")) +def lpmn(m, n, z): + """Sequence of associated Legendre functions of the first kind. + + Computes the associated Legendre function of the first kind of order m and + degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``. + Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and + ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``. + + This function takes a real argument ``z``. For complex arguments ``z`` + use clpmn instead. + + .. deprecated:: 1.15.0 + This function is deprecated and will be removed in SciPy 1.17.0. + Please `scipy.special.assoc_legendre_p_all` instead. + + Parameters + ---------- + m : int + ``|m| <= n``; the order of the Legendre function. + n : int + where ``n >= 0``; the degree of the Legendre function. Often + called ``l`` (lower case L) in descriptions of the associated + Legendre function + z : array_like + Input value. + + Returns + ------- + Pmn_z : (m+1, n+1) array + Values for all orders 0..m and degrees 0..n + Pmn_d_z : (m+1, n+1) array + Derivatives for all orders 0..m and degrees 0..n + + See Also + -------- + clpmn: associated Legendre functions of the first kind for complex z + + Notes + ----- + In the interval (-1, 1), Ferrer's function of the first kind is + returned. The phase convention used for the intervals (1, inf) + and (-inf, -1) is such that the result is always real. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + .. [2] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/14.3 + + """ + + n = _nonneg_int_or_fail(n, 'n', strict=False) + + if (abs(m) > n): + raise ValueError("m must be <= n.") + + if np.iscomplexobj(z): + raise ValueError("Argument must be real. Use clpmn instead.") + + m, n = int(m), int(n) # Convert to int to maintain backwards compatibility. + + branch_cut = np.where(np.abs(z) <= 1, 2, 3) + + p, pd = assoc_legendre_p_all(n, abs(m), z, branch_cut=branch_cut, diff_n=1) + p = np.swapaxes(p, 0, 1) + pd = np.swapaxes(pd, 0, 1) + + if (m >= 0): + p = p[:(m + 1)] + pd = pd[:(m + 1)] + else: + p = np.insert(p[:(m - 1):-1], 0, p[0], axis=0) + pd = np.insert(pd[:(m - 1):-1], 0, pd[0], axis=0) + + return p, pd + + +@_deprecated(__DEPRECATION_MSG_1_15.format("clpmn", "assoc_legendre_p_all")) +def clpmn(m, n, z, type=3): + """Associated Legendre function of the first kind for complex arguments. + + Computes the associated Legendre function of the first kind of order m and + degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``. + Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and + ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``. + + .. deprecated:: 1.15.0 + This function is deprecated and will be removed in SciPy 1.17.0. + Please use `scipy.special.assoc_legendre_p_all` instead. + + Parameters + ---------- + m : int + ``|m| <= n``; the order of the Legendre function. + n : int + where ``n >= 0``; the degree of the Legendre function. Often + called ``l`` (lower case L) in descriptions of the associated + Legendre function + z : array_like, float or complex + Input value. + type : int, optional + takes values 2 or 3 + 2: cut on the real axis ``|x| > 1`` + 3: cut on the real axis ``-1 < x < 1`` (default) + + Returns + ------- + Pmn_z : (m+1, n+1) array + Values for all orders ``0..m`` and degrees ``0..n`` + Pmn_d_z : (m+1, n+1) array + Derivatives for all orders ``0..m`` and degrees ``0..n`` + + See Also + -------- + lpmn: associated Legendre functions of the first kind for real z + + Notes + ----- + By default, i.e. for ``type=3``, phase conventions are chosen according + to [1]_ such that the function is analytic. The cut lies on the interval + (-1, 1). Approaching the cut from above or below in general yields a phase + factor with respect to Ferrer's function of the first kind + (cf. `lpmn`). + + For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values + on the interval (-1, 1) in the complex plane yields Ferrer's function + of the first kind. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + .. [2] NIST Digital Library of Mathematical Functions + https://dlmf.nist.gov/14.21 + + """ + + if (abs(m) > n): + raise ValueError("m must be <= n.") + + if not (type == 2 or type == 3): + raise ValueError("type must be either 2 or 3.") + + m, n = int(m), int(n) # Convert to int to maintain backwards compatibility. + + if not np.iscomplexobj(z): + z = np.asarray(z, dtype=complex) + + out, out_jac = assoc_legendre_p_all(n, abs(m), z, branch_cut=type, diff_n=1) + out = np.swapaxes(out, 0, 1) + out_jac = np.swapaxes(out_jac, 0, 1) + + if (m >= 0): + out = out[:(m + 1)] + out_jac = out_jac[:(m + 1)] + else: + out = np.insert(out[:(m - 1):-1], 0, out[0], axis=0) + out_jac = np.insert(out_jac[:(m - 1):-1], 0, out_jac[0], axis=0) + + return out, out_jac + + +def lqmn(m, n, z): + """Sequence of associated Legendre functions of the second kind. + + Computes the associated Legendre function of the second kind of order m and + degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``. + Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and + ``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``. + + Parameters + ---------- + m : int + ``|m| <= n``; the order of the Legendre function. + n : int + where ``n >= 0``; the degree of the Legendre function. Often + called ``l`` (lower case L) in descriptions of the associated + Legendre function + z : array_like, complex + Input value. + + Returns + ------- + Qmn_z : (m+1, n+1) array + Values for all orders 0..m and degrees 0..n + Qmn_d_z : (m+1, n+1) array + Derivatives for all orders 0..m and degrees 0..n + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(m) or (m < 0): + raise ValueError("m must be a non-negative integer.") + if not isscalar(n) or (n < 0): + raise ValueError("n must be a non-negative integer.") + + m, n = int(m), int(n) # Convert to int to maintain backwards compatibility. + # Ensure neither m nor n == 0 + mm = max(1, m) + nn = max(1, n) + + z = np.asarray(z) + if (not np.issubdtype(z.dtype, np.inexact)): + z = z.astype(np.float64) + + if np.iscomplexobj(z): + q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.complex128) + else: + q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.float64) + qd = np.empty_like(q) + if (z.ndim == 0): + _lqmn(z, out=(q, qd)) + else: + # new axes must be last for the ufunc + _lqmn(z, + out=(np.moveaxis(q, (0, 1), (-2, -1)), + np.moveaxis(qd, (0, 1), (-2, -1)))) + + return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)] + + +def bernoulli(n): + """Bernoulli numbers B0..Bn (inclusive). + + Parameters + ---------- + n : int + Indicated the number of terms in the Bernoulli series to generate. + + Returns + ------- + ndarray + The Bernoulli numbers ``[B(0), B(1), ..., B(n)]``. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + .. [2] "Bernoulli number", Wikipedia, https://en.wikipedia.org/wiki/Bernoulli_number + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import bernoulli, zeta + >>> bernoulli(4) + array([ 1. , -0.5 , 0.16666667, 0. , -0.03333333]) + + The Wikipedia article ([2]_) points out the relationship between the + Bernoulli numbers and the zeta function, ``B_n^+ = -n * zeta(1 - n)`` + for ``n > 0``: + + >>> n = np.arange(1, 5) + >>> -n * zeta(1 - n) + array([ 0.5 , 0.16666667, -0. , -0.03333333]) + + Note that, in the notation used in the wikipedia article, + `bernoulli` computes ``B_n^-`` (i.e. it used the convention that + ``B_1`` is -1/2). The relation given above is for ``B_n^+``, so the + sign of 0.5 does not match the output of ``bernoulli(4)``. + + """ + if not isscalar(n) or (n < 0): + raise ValueError("n must be a non-negative integer.") + n = int(n) + if (n < 2): + n1 = 2 + else: + n1 = n + return _specfun.bernob(int(n1))[:(n+1)] + + +def euler(n): + """Euler numbers E(0), E(1), ..., E(n). + + The Euler numbers [1]_ are also known as the secant numbers. + + Because ``euler(n)`` returns floating point values, it does not give + exact values for large `n`. The first inexact value is E(22). + + Parameters + ---------- + n : int + The highest index of the Euler number to be returned. + + Returns + ------- + ndarray + The Euler numbers [E(0), E(1), ..., E(n)]. + The odd Euler numbers, which are all zero, are included. + + References + ---------- + .. [1] Sequence A122045, The On-Line Encyclopedia of Integer Sequences, + https://oeis.org/A122045 + .. [2] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import euler + >>> euler(6) + array([ 1., 0., -1., 0., 5., 0., -61.]) + + >>> euler(13).astype(np.int64) + array([ 1, 0, -1, 0, 5, 0, -61, + 0, 1385, 0, -50521, 0, 2702765, 0]) + + >>> euler(22)[-1] # Exact value of E(22) is -69348874393137901. + -69348874393137976.0 + + """ + if not isscalar(n) or (n < 0): + raise ValueError("n must be a non-negative integer.") + n = int(n) + if (n < 2): + n1 = 2 + else: + n1 = n + return _specfun.eulerb(n1)[:(n+1)] + + +@_deprecated(__DEPRECATION_MSG_1_15.format("lpn", "legendre_p_all")) +def lpn(n, z): + """Legendre function of the first kind. + + Compute sequence of Legendre functions of the first kind (polynomials), + Pn(z) and derivatives for all degrees from 0 to n (inclusive). + + See also special.legendre for polynomial class. + + .. deprecated:: 1.15.0 + This function is deprecated and will be removed in SciPy 1.17.0. + Please use `scipy.special.legendre_p_all` instead. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + """ + + return legendre_p_all(n, z, diff_n=1) + + +def lqn(n, z): + """Legendre function of the second kind. + + Compute sequence of Legendre functions of the second kind, Qn(z) and + derivatives for all degrees from 0 to n (inclusive). + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + n = _nonneg_int_or_fail(n, 'n', strict=False) + if (n < 1): + n1 = 1 + else: + n1 = n + + z = np.asarray(z) + if (not np.issubdtype(z.dtype, np.inexact)): + z = z.astype(float) + + if np.iscomplexobj(z): + qn = np.empty((n1 + 1,) + z.shape, dtype=np.complex128) + else: + qn = np.empty((n1 + 1,) + z.shape, dtype=np.float64) + qd = np.empty_like(qn) + if (z.ndim == 0): + _lqn(z, out=(qn, qd)) + else: + # new axes must be last for the ufunc + _lqn(z, + out=(np.moveaxis(qn, 0, -1), + np.moveaxis(qd, 0, -1))) + + return qn[:(n+1)], qd[:(n+1)] + + +def ai_zeros(nt): + """ + Compute `nt` zeros and values of the Airy function Ai and its derivative. + + Computes the first `nt` zeros, `a`, of the Airy function Ai(x); + first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x); + the corresponding values Ai(a'); + and the corresponding values Ai'(a). + + Parameters + ---------- + nt : int + Number of zeros to compute + + Returns + ------- + a : ndarray + First `nt` zeros of Ai(x) + ap : ndarray + First `nt` zeros of Ai'(x) + ai : ndarray + Values of Ai(x) evaluated at first `nt` zeros of Ai'(x) + aip : ndarray + Values of Ai'(x) evaluated at first `nt` zeros of Ai(x) + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + >>> from scipy import special + >>> a, ap, ai, aip = special.ai_zeros(3) + >>> a + array([-2.33810741, -4.08794944, -5.52055983]) + >>> ap + array([-1.01879297, -3.24819758, -4.82009921]) + >>> ai + array([ 0.53565666, -0.41901548, 0.38040647]) + >>> aip + array([ 0.70121082, -0.80311137, 0.86520403]) + + """ + kf = 1 + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be a positive integer scalar.") + return _specfun.airyzo(nt, kf) + + +def bi_zeros(nt): + """ + Compute `nt` zeros and values of the Airy function Bi and its derivative. + + Computes the first `nt` zeros, b, of the Airy function Bi(x); + first `nt` zeros, b', of the derivative of the Airy function Bi'(x); + the corresponding values Bi(b'); + and the corresponding values Bi'(b). + + Parameters + ---------- + nt : int + Number of zeros to compute + + Returns + ------- + b : ndarray + First `nt` zeros of Bi(x) + bp : ndarray + First `nt` zeros of Bi'(x) + bi : ndarray + Values of Bi(x) evaluated at first `nt` zeros of Bi'(x) + bip : ndarray + Values of Bi'(x) evaluated at first `nt` zeros of Bi(x) + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + Examples + -------- + >>> from scipy import special + >>> b, bp, bi, bip = special.bi_zeros(3) + >>> b + array([-1.17371322, -3.2710933 , -4.83073784]) + >>> bp + array([-2.29443968, -4.07315509, -5.51239573]) + >>> bi + array([-0.45494438, 0.39652284, -0.36796916]) + >>> bip + array([ 0.60195789, -0.76031014, 0.83699101]) + + """ + kf = 2 + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be a positive integer scalar.") + return _specfun.airyzo(nt, kf) + + +def lmbda(v, x): + r"""Jahnke-Emden Lambda function, Lambdav(x). + + This function is defined as [2]_, + + .. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v}, + + where :math:`\Gamma` is the gamma function and :math:`J_v` is the + Bessel function of the first kind. + + Parameters + ---------- + v : float + Order of the Lambda function + x : float + Value at which to evaluate the function and derivatives + + Returns + ------- + vl : ndarray + Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v. + dl : ndarray + Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + .. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and + Curves" (4th ed.), Dover, 1945 + """ + if not (isscalar(v) and isscalar(x)): + raise ValueError("arguments must be scalars.") + if (v < 0): + raise ValueError("argument must be > 0.") + n = int(v) + v0 = v - n + if (n < 1): + n1 = 1 + else: + n1 = n + v1 = n1 + v0 + if (v != floor(v)): + vm, vl, dl = _specfun.lamv(v1, x) + else: + vm, vl, dl = _specfun.lamn(v1, x) + return vl[:(n+1)], dl[:(n+1)] + + +def pbdv_seq(v, x): + """Parabolic cylinder functions Dv(x) and derivatives. + + Parameters + ---------- + v : float + Order of the parabolic cylinder function + x : float + Value at which to evaluate the function and derivatives + + Returns + ------- + dv : ndarray + Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v. + dp : ndarray + Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 13. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not (isscalar(v) and isscalar(x)): + raise ValueError("arguments must be scalars.") + n = int(v) + v0 = v-n + if (n < 1): + n1 = 1 + else: + n1 = n + v1 = n1 + v0 + dv, dp, pdf, pdd = _specfun.pbdv(v1, x) + return dv[:n1+1], dp[:n1+1] + + +def pbvv_seq(v, x): + """Parabolic cylinder functions Vv(x) and derivatives. + + Parameters + ---------- + v : float + Order of the parabolic cylinder function + x : float + Value at which to evaluate the function and derivatives + + Returns + ------- + dv : ndarray + Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v. + dp : ndarray + Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 13. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not (isscalar(v) and isscalar(x)): + raise ValueError("arguments must be scalars.") + n = int(v) + v0 = v-n + if (n <= 1): + n1 = 1 + else: + n1 = n + v1 = n1 + v0 + dv, dp, pdf, pdd = _specfun.pbvv(v1, x) + return dv[:n1+1], dp[:n1+1] + + +def pbdn_seq(n, z): + """Parabolic cylinder functions Dn(z) and derivatives. + + Parameters + ---------- + n : int + Order of the parabolic cylinder function + z : complex + Value at which to evaluate the function and derivatives + + Returns + ------- + dv : ndarray + Values of D_i(z), for i=0, ..., i=n. + dp : ndarray + Derivatives D_i'(z), for i=0, ..., i=n. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996, chapter 13. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not (isscalar(n) and isscalar(z)): + raise ValueError("arguments must be scalars.") + if (floor(n) != n): + raise ValueError("n must be an integer.") + if (abs(n) <= 1): + n1 = 1 + else: + n1 = n + cpb, cpd = _specfun.cpbdn(n1, z) + return cpb[:n1+1], cpd[:n1+1] + + +def ber_zeros(nt): + """Compute nt zeros of the Kelvin function ber. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the Kelvin function. + + See Also + -------- + ber + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 1) + + +def bei_zeros(nt): + """Compute nt zeros of the Kelvin function bei. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the Kelvin function. + + See Also + -------- + bei + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 2) + + +def ker_zeros(nt): + """Compute nt zeros of the Kelvin function ker. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the Kelvin function. + + See Also + -------- + ker + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 3) + + +def kei_zeros(nt): + """Compute nt zeros of the Kelvin function kei. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the Kelvin function. + + See Also + -------- + kei + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 4) + + +def berp_zeros(nt): + """Compute nt zeros of the derivative of the Kelvin function ber. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the derivative of the Kelvin function. + + See Also + -------- + ber, berp + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + + Examples + -------- + Compute the first 5 zeros of the derivative of the Kelvin function. + + >>> from scipy.special import berp_zeros + >>> berp_zeros(5) + array([ 6.03871081, 10.51364251, 14.96844542, 19.41757493, 23.86430432]) + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 5) + + +def beip_zeros(nt): + """Compute nt zeros of the derivative of the Kelvin function bei. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the derivative of the Kelvin function. + + See Also + -------- + bei, beip + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 6) + + +def kerp_zeros(nt): + """Compute nt zeros of the derivative of the Kelvin function ker. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the derivative of the Kelvin function. + + See Also + -------- + ker, kerp + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 7) + + +def keip_zeros(nt): + """Compute nt zeros of the derivative of the Kelvin function kei. + + Parameters + ---------- + nt : int + Number of zeros to compute. Must be positive. + + Returns + ------- + ndarray + First `nt` zeros of the derivative of the Kelvin function. + + See Also + -------- + kei, keip + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return _specfun.klvnzo(nt, 8) + + +def kelvin_zeros(nt): + """Compute nt zeros of all Kelvin functions. + + Returned in a length-8 tuple of arrays of length nt. The tuple contains + the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei'). + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): + raise ValueError("nt must be positive integer scalar.") + return (_specfun.klvnzo(nt, 1), + _specfun.klvnzo(nt, 2), + _specfun.klvnzo(nt, 3), + _specfun.klvnzo(nt, 4), + _specfun.klvnzo(nt, 5), + _specfun.klvnzo(nt, 6), + _specfun.klvnzo(nt, 7), + _specfun.klvnzo(nt, 8)) + + +def pro_cv_seq(m, n, c): + """Characteristic values for prolate spheroidal wave functions. + + Compute a sequence of characteristic values for the prolate + spheroidal wave functions for mode m and n'=m..n and spheroidal + parameter c. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not (isscalar(m) and isscalar(n) and isscalar(c)): + raise ValueError("Arguments must be scalars.") + if (n != floor(n)) or (m != floor(m)): + raise ValueError("Modes must be integers.") + if (n-m > 199): + raise ValueError("Difference between n and m is too large.") + maxL = n-m+1 + return _specfun.segv(m, n, c, 1)[1][:maxL] + + +def obl_cv_seq(m, n, c): + """Characteristic values for oblate spheroidal wave functions. + + Compute a sequence of characteristic values for the oblate + spheroidal wave functions for mode m and n'=m..n and spheroidal + parameter c. + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + + """ + if not (isscalar(m) and isscalar(n) and isscalar(c)): + raise ValueError("Arguments must be scalars.") + if (n != floor(n)) or (m != floor(m)): + raise ValueError("Modes must be integers.") + if (n-m > 199): + raise ValueError("Difference between n and m is too large.") + maxL = n-m+1 + return _specfun.segv(m, n, c, -1)[1][:maxL] + + +def comb(N, k, *, exact=False, repetition=False): + """The number of combinations of N things taken k at a time. + + This is often expressed as "N choose k". + + Parameters + ---------- + N : int, ndarray + Number of things. + k : int, ndarray + Number of elements taken. + exact : bool, optional + For integers, if `exact` is False, then floating point precision is + used, otherwise the result is computed exactly. + + .. deprecated:: 1.14.0 + ``exact=True`` is deprecated for non-integer `N` and `k` and will raise an + error in SciPy 1.16.0 + repetition : bool, optional + If `repetition` is True, then the number of combinations with + repetition is computed. + + Returns + ------- + val : int, float, ndarray + The total number of combinations. + + See Also + -------- + binom : Binomial coefficient considered as a function of two real + variables. + + Notes + ----- + - Array arguments accepted only for exact=False case. + - If N < 0, or k < 0, then 0 is returned. + - If k > N and repetition=False, then 0 is returned. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import comb + >>> k = np.array([3, 4]) + >>> n = np.array([10, 10]) + >>> comb(n, k, exact=False) + array([ 120., 210.]) + >>> comb(10, 3, exact=True) + 120 + >>> comb(10, 3, exact=True, repetition=True) + 220 + + """ + if repetition: + return comb(N + k - 1, k, exact=exact) + if exact: + if int(N) == N and int(k) == k: + # _comb_int casts inputs to integers, which is safe & intended here + return _comb_int(N, k) + # otherwise, we disregard `exact=True`; it makes no sense for + # non-integral arguments + msg = ("`exact=True` is deprecated for non-integer `N` and `k` and will raise " + "an error in SciPy 1.16.0") + warnings.warn(msg, DeprecationWarning, stacklevel=2) + return comb(N, k) + else: + k, N = asarray(k), asarray(N) + cond = (k <= N) & (N >= 0) & (k >= 0) + vals = binom(N, k) + if isinstance(vals, np.ndarray): + vals[~cond] = 0 + elif not cond: + vals = np.float64(0) + return vals + + +def perm(N, k, exact=False): + """Permutations of N things taken k at a time, i.e., k-permutations of N. + + It's also known as "partial permutations". + + Parameters + ---------- + N : int, ndarray + Number of things. + k : int, ndarray + Number of elements taken. + exact : bool, optional + If ``True``, calculate the answer exactly using long integer arithmetic (`N` + and `k` must be scalar integers). If ``False``, a floating point approximation + is calculated (more rapidly) using `poch`. Default is ``False``. + + Returns + ------- + val : int, ndarray + The number of k-permutations of N. + + Notes + ----- + - Array arguments accepted only for exact=False case. + - If k > N, N < 0, or k < 0, then a 0 is returned. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import perm + >>> k = np.array([3, 4]) + >>> n = np.array([10, 10]) + >>> perm(n, k) + array([ 720., 5040.]) + >>> perm(10, 3, exact=True) + 720 + + """ + if exact: + N = np.squeeze(N)[()] # for backward compatibility (accepted size 1 arrays) + k = np.squeeze(k)[()] + if not (isscalar(N) and isscalar(k)): + raise ValueError("`N` and `k` must scalar integers be with `exact=True`.") + + floor_N, floor_k = int(N), int(k) + non_integral = not (floor_N == N and floor_k == k) + if (k > N) or (N < 0) or (k < 0): + if non_integral: + msg = ("Non-integer `N` and `k` with `exact=True` is deprecated and " + "will raise an error in SciPy 1.16.0.") + warnings.warn(msg, DeprecationWarning, stacklevel=2) + return 0 + if non_integral: + raise ValueError("Non-integer `N` and `k` with `exact=True` is not " + "supported.") + val = 1 + for i in range(floor_N - floor_k + 1, floor_N + 1): + val *= i + return val + else: + k, N = asarray(k), asarray(N) + cond = (k <= N) & (N >= 0) & (k >= 0) + vals = poch(N - k + 1, k) + if isinstance(vals, np.ndarray): + vals[~cond] = 0 + elif not cond: + vals = np.float64(0) + return vals + + +# https://stackoverflow.com/a/16327037 +def _range_prod(lo, hi, k=1): + """ + Product of a range of numbers spaced k apart (from hi). + + For k=1, this returns the product of + lo * (lo+1) * (lo+2) * ... * (hi-2) * (hi-1) * hi + = hi! / (lo-1)! + + For k>1, it correspond to taking only every k'th number when + counting down from hi - e.g. 18!!!! = _range_prod(1, 18, 4). + + Breaks into smaller products first for speed: + _range_prod(2, 9) = ((2*3)*(4*5))*((6*7)*(8*9)) + """ + if lo == 1 and k == 1: + return math.factorial(hi) + + if lo + k < hi: + mid = (hi + lo) // 2 + if k > 1: + # make sure mid is a multiple of k away from hi + mid = mid - ((mid - hi) % k) + return _range_prod(lo, mid, k) * _range_prod(mid + k, hi, k) + elif lo + k == hi: + return lo * hi + else: + return hi + + +def _factorialx_array_exact(n, k=1): + """ + Exact computation of factorial for an array. + + The factorials are computed in incremental fashion, by taking + the sorted unique values of n and multiplying the intervening + numbers between the different unique values. + + In other words, the factorial for the largest input is only + computed once, with each other result computed in the process. + + k > 1 corresponds to the multifactorial. + """ + un = np.unique(n) + # numpy changed nan-sorting behaviour with 1.21, see numpy/numpy#18070; + # to unify the behaviour, we remove the nan's here; the respective + # values will be set separately at the end + un = un[~np.isnan(un)] + + # Convert to object array if np.int64 can't handle size + if np.isnan(n).any(): + dt = float + elif k in _FACTORIALK_LIMITS_64BITS.keys(): + if un[-1] > _FACTORIALK_LIMITS_64BITS[k]: + # e.g. k=1: 21! > np.iinfo(np.int64).max + dt = object + elif un[-1] > _FACTORIALK_LIMITS_32BITS[k]: + # e.g. k=3: 26!!! > np.iinfo(np.int32).max + dt = np.int64 + else: + dt = np.dtype("long") + else: + # for k >= 10, we always use object + dt = object + + out = np.empty_like(n, dtype=dt) + + # Handle invalid/trivial values + un = un[un > 1] + out[n < 2] = 1 + out[n < 0] = 0 + + # Calculate products of each range of numbers + # we can only multiply incrementally if the values are k apart; + # therefore we partition `un` into "lanes", i.e. its residues modulo k + for lane in range(0, k): + ul = un[(un % k) == lane] if k > 1 else un + if ul.size: + # after np.unique, un resp. ul are sorted, ul[0] is the smallest; + # cast to python ints to avoid overflow with np.int-types + val = _range_prod(1, int(ul[0]), k=k) + out[n == ul[0]] = val + for i in range(len(ul) - 1): + # by the filtering above, we have ensured that prev & current + # are a multiple of k apart + prev = ul[i] + current = ul[i + 1] + # we already multiplied all factors until prev; continue + # building the full factorial from the following (`prev + 1`); + # use int() for the same reason as above + val *= _range_prod(int(prev + 1), int(current), k=k) + out[n == current] = val + + if np.isnan(n).any(): + out = out.astype(np.float64) + out[np.isnan(n)] = np.nan + return out + + +def _factorialx_array_approx(n, k, extend): + """ + Calculate approximation to multifactorial for array n and integer k. + + Ensure that values aren't calculated unnecessarily. + """ + if extend == "complex": + return _factorialx_approx_core(n, k=k, extend=extend) + + # at this point we are guaranteed that extend='zero' and that k>0 is an integer + result = zeros(n.shape) + # keep nans as nans + place(result, np.isnan(n), np.nan) + # only compute where n >= 0 (excludes nans), everything else is 0 + cond = (n >= 0) + n_to_compute = extract(cond, n) + place(result, cond, _factorialx_approx_core(n_to_compute, k=k, extend=extend)) + return result + + +def _gamma1p(vals): + """ + returns gamma(n+1), though with NaN at -1 instead of inf, c.f. #21827 + """ + res = gamma(vals + 1) + # replace infinities at -1 (from gamma function at 0) with nan + # gamma only returns inf for real inputs; can ignore complex case + if isinstance(res, np.ndarray): + if not _is_subdtype(vals.dtype, "c"): + res[vals == -1] = np.nan + elif np.isinf(res) and vals == -1: + res = np.float64("nan") + return res + + +def _factorialx_approx_core(n, k, extend): + """ + Core approximation to multifactorial for array n and integer k. + """ + if k == 1: + # shortcut for k=1; same for both extensions, because we assume the + # handling of extend == 'zero' happens in _factorialx_array_approx + result = _gamma1p(n) + if isinstance(n, np.ndarray): + # gamma does not maintain 0-dim arrays; fix it + result = np.array(result) + return result + + if extend == "complex": + # see https://numpy.org/doc/stable/reference/generated/numpy.power.html + p_dtype = complex if (_is_subdtype(type(k), "c") or k < 0) else None + with warnings.catch_warnings(): + # do not warn about 0 * inf, nan / nan etc.; the results are correct + warnings.simplefilter("ignore", RuntimeWarning) + # don't use `(n-1)/k` in np.power; underflows if 0 is of a uintX type + result = np.power(k, n / k, dtype=p_dtype) * _gamma1p(n / k) + result *= rgamma(1 / k + 1) / np.power(k, 1 / k, dtype=p_dtype) + if isinstance(n, np.ndarray): + # ensure we keep array-ness for 0-dim inputs; already n/k above loses it + result = np.array(result) + return result + + # at this point we are guaranteed that extend='zero' and that k>0 is an integer + n_mod_k = n % k + # scalar case separately, unified handling would be inefficient for arrays; + # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below + if not isinstance(n, np.ndarray): + return ( + np.power(k, (n - n_mod_k) / k) + * gamma(n / k + 1) / gamma(n_mod_k / k + 1) + * max(n_mod_k, 1) + ) + + # factor that's independent of the residue class (see factorialk docstring) + result = np.power(k, n / k) * gamma(n / k + 1) + # factor dependent on residue r (for `r=0` it's 1, so we skip `r=0` + # below and thus also avoid evaluating `max(r, 1)`) + def corr(k, r): return np.power(k, -r / k) / gamma(r / k + 1) * r + for r in np.unique(n_mod_k): + if r == 0: + continue + # cast to int because uint types break on `-r` + result[n_mod_k == r] *= corr(k, int(r)) + return result + + +def _is_subdtype(dtype, dtypes): + """ + Shorthand for calculating whether dtype is subtype of some dtypes. + + Also allows specifying a list instead of just a single dtype. + + Additionaly, the most important supertypes from + https://numpy.org/doc/stable/reference/arrays.scalars.html + can optionally be specified using abbreviations as follows: + "i": np.integer + "f": np.floating + "c": np.complexfloating + "n": np.number (contains the other three) + """ + dtypes = dtypes if isinstance(dtypes, list) else [dtypes] + # map single character abbreviations, if they are in dtypes + mapping = { + "i": np.integer, + "f": np.floating, + "c": np.complexfloating, + "n": np.number + } + dtypes = [mapping.get(x, x) for x in dtypes] + return any(np.issubdtype(dtype, dt) for dt in dtypes) + + +def _factorialx_wrapper(fname, n, k, exact, extend): + """ + Shared implementation for factorial, factorial2 & factorialk. + """ + if extend not in ("zero", "complex"): + raise ValueError( + f"argument `extend` must be either 'zero' or 'complex', received: {extend}" + ) + if exact and extend == "complex": + raise ValueError("Incompatible options: `exact=True` and `extend='complex'`") + + msg_unsup = ( + "Unsupported data type for {vname} in {fname}: {dtype}\n" + ) + if fname == "factorial": + msg_unsup += ( + "Permitted data types are integers and floating point numbers, " + "as well as complex numbers if `extend='complex' is passed." + ) + else: + msg_unsup += ( + "Permitted data types are integers, as well as floating point " + "numbers and complex numbers if `extend='complex' is passed." + ) + msg_exact_not_possible = ( + "`exact=True` only supports integers, cannot use data type {dtype}" + ) + msg_needs_complex = ( + "In order to use non-integer arguments, you must opt into this by passing " + "`extend='complex'`. Note that this changes the result for all negative " + "arguments (which by default return 0)." + ) + + if fname == "factorial2": + msg_needs_complex += (" Additionally, it will rescale the values of the double" + " factorial at even integers by a factor of sqrt(2/pi).") + elif fname == "factorialk": + msg_needs_complex += (" Additionally, it will perturb the values of the" + " multifactorial at most positive integers `n`.") + # check type of k + if not _is_subdtype(type(k), ["i", "f", "c"]): + raise ValueError(msg_unsup.format(vname="`k`", fname=fname, dtype=type(k))) + elif _is_subdtype(type(k), ["f", "c"]) and extend != "complex": + raise ValueError(msg_needs_complex) + # check value of k + if extend == "zero" and k < 1: + msg = f"For `extend='zero'`, k must be a positive integer, received: {k}" + raise ValueError(msg) + elif k == 0: + raise ValueError("Parameter k cannot be zero!") + + # factorial allows floats also for extend="zero" + types_requiring_complex = "c" if fname == "factorial" else ["f", "c"] + + # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below + if np.ndim(n) == 0 and not isinstance(n, np.ndarray): + # scalar cases + if not _is_subdtype(type(n), ["i", "f", "c", type(None)]): + raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=type(n))) + elif _is_subdtype(type(n), types_requiring_complex) and extend != "complex": + raise ValueError(msg_needs_complex) + elif n is None or np.isnan(n): + complexify = (extend == "complex") and _is_subdtype(type(n), "c") + return np.complex128("nan+nanj") if complexify else np.float64("nan") + elif extend == "zero" and n < 0: + return 0 if exact else np.float64(0) + elif n in {0, 1}: + return 1 if exact else np.float64(1) + elif exact and _is_subdtype(type(n), "i"): + # calculate with integers + return _range_prod(1, n, k=k) + elif exact: + # only relevant for factorial + raise ValueError(msg_exact_not_possible.format(dtype=type(n))) + # approximation + return _factorialx_approx_core(n, k=k, extend=extend) + + # arrays & array-likes + n = asarray(n) + + if not _is_subdtype(n.dtype, ["i", "f", "c"]): + raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=n.dtype)) + elif _is_subdtype(n.dtype, types_requiring_complex) and extend != "complex": + raise ValueError(msg_needs_complex) + elif exact and _is_subdtype(n.dtype, ["f"]): + # only relevant for factorial + raise ValueError(msg_exact_not_possible.format(dtype=n.dtype)) + + if n.size == 0: + # return empty arrays unchanged + return n + elif exact: + # calculate with integers + return _factorialx_array_exact(n, k=k) + # approximation + return _factorialx_array_approx(n, k=k, extend=extend) + + +def factorial(n, exact=False, extend="zero"): + """ + The factorial of a number or array of numbers. + + The factorial of non-negative integer `n` is the product of all + positive integers less than or equal to `n`:: + + n! = n * (n - 1) * (n - 2) * ... * 1 + + Parameters + ---------- + n : int or float or complex (or array_like thereof) + Input values for ``n!``. Complex values require ``extend='complex'``. + By default, the return value for ``n < 0`` is 0. + exact : bool, optional + If ``exact`` is set to True, calculate the answer exactly using + integer arithmetic, otherwise approximate using the gamma function + (faster, but yields floats instead of integers). + Default is False. + extend : string, optional + One of ``'zero'`` or ``'complex'``; this determines how values ``n<0`` + are handled - by default they are 0, but it is possible to opt into the + complex extension of the factorial (see below). + + Returns + ------- + nf : int or float or complex or ndarray + Factorial of ``n``, as integer, float or complex (depending on ``exact`` + and ``extend``). Array inputs are returned as arrays. + + Notes + ----- + For arrays with ``exact=True``, the factorial is computed only once, for + the largest input, with each other result computed in the process. + The output dtype is increased to ``int64`` or ``object`` if necessary. + + With ``exact=False`` the factorial is approximated using the gamma + function (which is also the definition of the complex extension): + + .. math:: n! = \\Gamma(n+1) + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import factorial + >>> arr = np.array([3, 4, 5]) + >>> factorial(arr, exact=False) + array([ 6., 24., 120.]) + >>> factorial(arr, exact=True) + array([ 6, 24, 120]) + >>> factorial(5, exact=True) + 120 + + """ + return _factorialx_wrapper("factorial", n, k=1, exact=exact, extend=extend) + + +def factorial2(n, exact=False, extend="zero"): + """Double factorial. + + This is the factorial with every second value skipped. E.g., ``7!! = 7 * 5 + * 3 * 1``. It can be approximated numerically as:: + + n!! = 2 ** (n / 2) * gamma(n / 2 + 1) * sqrt(2 / pi) n odd + = 2 ** (n / 2) * gamma(n / 2 + 1) n even + = 2 ** (n / 2) * (n / 2)! n even + + The formula for odd ``n`` is the basis for the complex extension. + + Parameters + ---------- + n : int or float or complex (or array_like thereof) + Input values for ``n!!``. Non-integer values require ``extend='complex'``. + By default, the return value for ``n < 0`` is 0. + exact : bool, optional + If ``exact`` is set to True, calculate the answer exactly using + integer arithmetic, otherwise use above approximation (faster, + but yields floats instead of integers). + Default is False. + extend : string, optional + One of ``'zero'`` or ``'complex'``; this determines how values ``n<0`` + are handled - by default they are 0, but it is possible to opt into the + complex extension of the double factorial. This also enables passing + complex values to ``n``. + + .. warning:: + + Using the ``'complex'`` extension also changes the values of the + double factorial for even integers, reducing them by a factor of + ``sqrt(2/pi) ~= 0.79``, see [1]. + + Returns + ------- + nf : int or float or complex or ndarray + Double factorial of ``n``, as integer, float or complex (depending on + ``exact`` and ``extend``). Array inputs are returned as arrays. + + Examples + -------- + >>> from scipy.special import factorial2 + >>> factorial2(7, exact=False) + array(105.00000000000001) + >>> factorial2(7, exact=True) + 105 + + References + ---------- + .. [1] Complex extension to double factorial + https://en.wikipedia.org/wiki/Double_factorial#Complex_arguments + """ + return _factorialx_wrapper("factorial2", n, k=2, exact=exact, extend=extend) + + +def factorialk(n, k, exact=False, extend="zero"): + """Multifactorial of n of order k, n(!!...!). + + This is the multifactorial of n skipping k values. For example, + + factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1 + + In particular, for any integer ``n``, we have + + factorialk(n, 1) = factorial(n) + + factorialk(n, 2) = factorial2(n) + + Parameters + ---------- + n : int or float or complex (or array_like thereof) + Input values for multifactorial. Non-integer values require + ``extend='complex'``. By default, the return value for ``n < 0`` is 0. + n : int or float or complex (or array_like thereof) + Order of multifactorial. Non-integer values require ``extend='complex'``. + exact : bool, optional + If ``exact`` is set to True, calculate the answer exactly using + integer arithmetic, otherwise use an approximation (faster, + but yields floats instead of integers) + Default is False. + extend : string, optional + One of ``'zero'`` or ``'complex'``; this determines how values ``n<0`` are + handled - by default they are 0, but it is possible to opt into the complex + extension of the multifactorial. This enables passing complex values, + not only to ``n`` but also to ``k``. + + .. warning:: + + Using the ``'complex'`` extension also changes the values of the + multifactorial at integers ``n != 1 (mod k)`` by a factor depending + on both ``k`` and ``n % k``, see below or [1]. + + Returns + ------- + nf : int or float or complex or ndarray + Multifactorial (order ``k``) of ``n``, as integer, float or complex (depending + on ``exact`` and ``extend``). Array inputs are returned as arrays. + + Examples + -------- + >>> from scipy.special import factorialk + >>> factorialk(5, k=1, exact=True) + 120 + >>> factorialk(5, k=3, exact=True) + 10 + >>> factorialk([5, 7, 9], k=3, exact=True) + array([ 10, 28, 162]) + >>> factorialk([5, 7, 9], k=3, exact=False) + array([ 10., 28., 162.]) + + Notes + ----- + While less straight-forward than for the double-factorial, it's possible to + calculate a general approximation formula of n!(k) by studying ``n`` for a given + remainder ``r < k`` (thus ``n = m * k + r``, resp. ``r = n % k``), which can be + put together into something valid for all integer values ``n >= 0`` & ``k > 0``:: + + n!(k) = k ** ((n - r)/k) * gamma(n/k + 1) / gamma(r/k + 1) * max(r, 1) + + This is the basis of the approximation when ``exact=False``. + + In principle, any fixed choice of ``r`` (ignoring its relation ``r = n%k`` + to ``n``) would provide a suitable analytic continuation from integer ``n`` + to complex ``z`` (not only satisfying the functional equation but also + being logarithmically convex, c.f. Bohr-Mollerup theorem) -- in fact, the + choice of ``r`` above only changes the function by a constant factor. The + final constraint that determines the canonical continuation is ``f(1) = 1``, + which forces ``r = 1`` (see also [1]).:: + + z!(k) = k ** ((z - 1)/k) * gamma(z/k + 1) / gamma(1/k + 1) + + References + ---------- + .. [1] Complex extension to multifactorial + https://en.wikipedia.org/wiki/Double_factorial#Alternative_extension_of_the_multifactorial + """ + return _factorialx_wrapper("factorialk", n, k=k, exact=exact, extend=extend) + + +def stirling2(N, K, *, exact=False): + r"""Generate Stirling number(s) of the second kind. + + Stirling numbers of the second kind count the number of ways to + partition a set with N elements into K non-empty subsets. + + The values this function returns are calculated using a dynamic + program which avoids redundant computation across the subproblems + in the solution. For array-like input, this implementation also + avoids redundant computation across the different Stirling number + calculations. + + The numbers are sometimes denoted + + .. math:: + + {N \brace{K}} + + see [1]_ for details. This is often expressed-verbally-as + "N subset K". + + Parameters + ---------- + N : int, ndarray + Number of things. + K : int, ndarray + Number of non-empty subsets taken. + exact : bool, optional + Uses dynamic programming (DP) with floating point + numbers for smaller arrays and uses a second order approximation due to + Temme for larger entries of `N` and `K` that allows trading speed for + accuracy. See [2]_ for a description. Temme approximation is used for + values ``n>50``. The max error from the DP has max relative error + ``4.5*10^-16`` for ``n<=50`` and the max error from the Temme approximation + has max relative error ``5*10^-5`` for ``51 <= n < 70`` and + ``9*10^-6`` for ``70 <= n < 101``. Note that these max relative errors will + decrease further as `n` increases. + + Returns + ------- + val : int, float, ndarray + The number of partitions. + + See Also + -------- + comb : The number of combinations of N things taken k at a time. + + Notes + ----- + - If N < 0, or K < 0, then 0 is returned. + - If K > N, then 0 is returned. + + The output type will always be `int` or ndarray of `object`. + The input must contain either numpy or python integers otherwise a + TypeError is raised. + + References + ---------- + .. [1] R. L. Graham, D. E. Knuth and O. Patashnik, "Concrete + Mathematics: A Foundation for Computer Science," Addison-Wesley + Publishing Company, Boston, 1989. Chapter 6, page 258. + + .. [2] Temme, Nico M. "Asymptotic estimates of Stirling numbers." + Studies in Applied Mathematics 89.3 (1993): 233-243. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import stirling2 + >>> k = np.array([3, -1, 3]) + >>> n = np.array([10, 10, 9]) + >>> stirling2(n, k) + array([9330.0, 0.0, 3025.0]) + + """ + output_is_scalar = np.isscalar(N) and np.isscalar(K) + # make a min-heap of unique (n,k) pairs + N, K = asarray(N), asarray(K) + if not np.issubdtype(N.dtype, np.integer): + raise TypeError("Argument `N` must contain only integers") + if not np.issubdtype(K.dtype, np.integer): + raise TypeError("Argument `K` must contain only integers") + if not exact: + # NOTE: here we allow np.uint via casting to double types prior to + # passing to private ufunc dispatcher. All dispatched functions + # take double type for (n,k) arguments and return double. + return _stirling2_inexact(N.astype(float), K.astype(float)) + nk_pairs = list( + set([(n.take(0), k.take(0)) + for n, k in np.nditer([N, K], ['refs_ok'])]) + ) + heapify(nk_pairs) + # base mapping for small values + snsk_vals = defaultdict(int) + for pair in [(0, 0), (1, 1), (2, 1), (2, 2)]: + snsk_vals[pair] = 1 + # for each pair in the min-heap, calculate the value, store for later + n_old, n_row = 2, [0, 1, 1] + while nk_pairs: + n, k = heappop(nk_pairs) + if n < 2 or k > n or k <= 0: + continue + elif k == n or k == 1: + snsk_vals[(n, k)] = 1 + continue + elif n != n_old: + num_iters = n - n_old + while num_iters > 0: + n_row.append(1) + # traverse from back to remove second row + for j in range(len(n_row)-2, 1, -1): + n_row[j] = n_row[j]*j + n_row[j-1] + num_iters -= 1 + snsk_vals[(n, k)] = n_row[k] + else: + snsk_vals[(n, k)] = n_row[k] + n_old, n_row = n, n_row + out_types = [object, object, object] if exact else [float, float, float] + # for each pair in the map, fetch the value, and populate the array + it = np.nditer( + [N, K, None], + ['buffered', 'refs_ok'], + [['readonly'], ['readonly'], ['writeonly', 'allocate']], + op_dtypes=out_types, + ) + with it: + while not it.finished: + it[2] = snsk_vals[(int(it[0]), int(it[1]))] + it.iternext() + output = it.operands[2] + # If N and K were both scalars, convert output to scalar. + if output_is_scalar: + output = output.take(0) + return output + + +def zeta(x, q=None, out=None): + r""" + Riemann or Hurwitz zeta function. + + Parameters + ---------- + x : array_like of float or complex. + Input data + q : array_like of float, optional + Input data, must be real. Defaults to Riemann zeta. When `q` is + ``None``, complex inputs `x` are supported. If `q` is not ``None``, + then currently only real inputs `x` with ``x >= 1`` are supported, + even when ``q = 1.0`` (corresponding to the Riemann zeta function). + + out : ndarray, optional + Output array for the computed values. + + Returns + ------- + out : array_like + Values of zeta(x). + + See Also + -------- + zetac + + Notes + ----- + The two-argument version is the Hurwitz zeta function + + .. math:: + + \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x}; + + see [dlmf]_ for details. The Riemann zeta function corresponds to + the case when ``q = 1``. + + For complex inputs with ``q = None``, points with + ``abs(z.imag) > 1e9`` and ``0 <= abs(z.real) < 2.5`` are currently not + supported due to slow convergence causing excessive runtime. + + References + ---------- + .. [dlmf] NIST, Digital Library of Mathematical Functions, + https://dlmf.nist.gov/25.11#i + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import zeta, polygamma, factorial + + Some specific values: + + >>> zeta(2), np.pi**2/6 + (1.6449340668482266, 1.6449340668482264) + + >>> zeta(4), np.pi**4/90 + (1.0823232337111381, 1.082323233711138) + + First nontrivial zero: + + >>> zeta(0.5 + 14.134725141734695j) + 0 + 0j + + Relation to the `polygamma` function: + + >>> m = 3 + >>> x = 1.25 + >>> polygamma(m, x) + array(2.782144009188397) + >>> (-1)**(m+1) * factorial(m) * zeta(m+1, x) + 2.7821440091883969 + + """ + if q is None: + return _ufuncs._riemann_zeta(x, out) + else: + return _ufuncs._zeta(x, q, out) + + +def softplus(x, **kwargs): + r""" + Compute the softplus function element-wise. + + The softplus function is defined as: ``softplus(x) = log(1 + exp(x))``. + It is a smooth approximation of the rectifier function (ReLU). + + Parameters + ---------- + x : array_like + Input value. + **kwargs + For other keyword-only arguments, see the + `ufunc docs `_. + + Returns + ------- + softplus : ndarray + Logarithm of ``exp(0) + exp(x)``. + + Examples + -------- + >>> from scipy import special + + >>> special.softplus(0) + 0.6931471805599453 + + >>> special.softplus([-1, 0, 1]) + array([0.31326169, 0.69314718, 1.31326169]) + """ + return np.logaddexp(0, x, **kwargs) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e0598ff2d395e08055065c94341de42ce84c5651 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py new file mode 100644 index 0000000000000000000000000000000000000000..1b1ce34aa58054be13edfd5d87f2059e8a0d9224 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py @@ -0,0 +1,214 @@ +import numpy as np + +from ._ufuncs import _ellip_harm +from ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm + + +def ellip_harm(h2, k2, n, p, s, signm=1, signn=1): + r""" + Ellipsoidal harmonic functions E^p_n(l) + + These are also known as Lame functions of the first kind, and are + solutions to the Lame equation: + + .. math:: (s^2 - h^2)(s^2 - k^2)E''(s) + + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0 + + where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not + returned) corresponding to the solutions. + + Parameters + ---------- + h2 : float + ``h**2`` + k2 : float + ``k**2``; should be larger than ``h**2`` + n : int + Degree + s : float + Coordinate + p : int + Order, can range between [1,2n+1] + signm : {1, -1}, optional + Sign of prefactor of functions. Can be +/-1. See Notes. + signn : {1, -1}, optional + Sign of prefactor of functions. Can be +/-1. See Notes. + + Returns + ------- + E : float + the harmonic :math:`E^p_n(s)` + + See Also + -------- + ellip_harm_2, ellip_normal + + Notes + ----- + The geometric interpretation of the ellipsoidal functions is + explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the + sign of prefactors for functions according to their type:: + + K : +1 + L : signm + M : signn + N : signm*signn + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Digital Library of Mathematical Functions 29.12 + https://dlmf.nist.gov/29.12 + .. [2] Bardhan and Knepley, "Computational science and + re-discovery: open-source implementations of + ellipsoidal harmonics for problems in potential theory", + Comput. Sci. Disc. 5, 014006 (2012) + :doi:`10.1088/1749-4699/5/1/014006`. + .. [3] David J.and Dechambre P, "Computation of Ellipsoidal + Gravity Field Harmonics for small solar system bodies" + pp. 30-36, 2000 + .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications" + pp. 418, 2012 + + Examples + -------- + >>> from scipy.special import ellip_harm + >>> w = ellip_harm(5,8,1,1,2.5) + >>> w + 2.5 + + Check that the functions indeed are solutions to the Lame equation: + + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> def eigenvalue(f, df, ddf): + ... r = (((s**2 - h**2) * (s**2 - k**2) * ddf + ... + s * (2*s**2 - h**2 - k**2) * df + ... - n * (n + 1)*s**2*f) / f) + ... return -r.mean(), r.std() + >>> s = np.linspace(0.1, 10, 200) + >>> k, h, n, p = 8.0, 2.2, 3, 2 + >>> E = ellip_harm(h**2, k**2, n, p, s) + >>> E_spl = UnivariateSpline(s, E) + >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2)) + >>> a, a_err + (583.44366156701483, 6.4580890640310646e-11) + + """ # noqa: E501 + return _ellip_harm(h2, k2, n, p, s, signm, signn) + + +_ellip_harm_2_vec = np.vectorize(_ellipsoid, otypes='d') + + +def ellip_harm_2(h2, k2, n, p, s): + r""" + Ellipsoidal harmonic functions F^p_n(l) + + These are also known as Lame functions of the second kind, and are + solutions to the Lame equation: + + .. math:: (s^2 - h^2)(s^2 - k^2)F''(s) + + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0 + + where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not + returned) corresponding to the solutions. + + Parameters + ---------- + h2 : float + ``h**2`` + k2 : float + ``k**2``; should be larger than ``h**2`` + n : int + Degree. + p : int + Order, can range between [1,2n+1]. + s : float + Coordinate + + Returns + ------- + F : float + The harmonic :math:`F^p_n(s)` + + See Also + -------- + ellip_harm, ellip_normal + + Notes + ----- + Lame functions of the second kind are related to the functions of the first kind: + + .. math:: + + F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s} + \frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}} + + .. versionadded:: 0.15.0 + + Examples + -------- + >>> from scipy.special import ellip_harm_2 + >>> w = ellip_harm_2(5,8,2,1,10) + >>> w + 0.00108056853382 + + """ + with np.errstate(all='ignore'): + return _ellip_harm_2_vec(h2, k2, n, p, s) + + +def _ellip_normal_vec(h2, k2, n, p): + return _ellipsoid_norm(h2, k2, n, p) + + +_ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d') + + +def ellip_normal(h2, k2, n, p): + r""" + Ellipsoidal harmonic normalization constants gamma^p_n + + The normalization constant is defined as + + .. math:: + + \gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy + \frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)} + + Parameters + ---------- + h2 : float + ``h**2`` + k2 : float + ``k**2``; should be larger than ``h**2`` + n : int + Degree. + p : int + Order, can range between [1,2n+1]. + + Returns + ------- + gamma : float + The normalization constant :math:`\gamma^p_n` + + See Also + -------- + ellip_harm, ellip_harm_2 + + Notes + ----- + .. versionadded:: 0.15.0 + + Examples + -------- + >>> from scipy.special import ellip_normal + >>> w = ellip_normal(5,8,3,7) + >>> w + 1723.38796997 + + """ + with np.errstate(all='ignore'): + return _ellip_normal_vec(h2, k2, n, p) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b7fe36df87617bf91655623ee0076c37a4d08a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py @@ -0,0 +1,17 @@ +import math +import operator + +def _nonneg_int_or_fail(n, var_name, strict=True): + try: + if strict: + # Raises an exception if float + n = operator.index(n) + elif n == math.floor(n): + n = int(n) + else: + raise ValueError() + if n < 0: + raise ValueError() + except (ValueError, TypeError) as err: + raise err.__class__(f"{var_name} must be a non-negative integer") from err + return n diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py new file mode 100644 index 0000000000000000000000000000000000000000..f758c7c21fdddc0ec1b84727d90c6de7f34a094e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py @@ -0,0 +1,149 @@ +from ._ufuncs import _lambertw + +import numpy as np + + +def lambertw(z, k=0, tol=1e-8): + r""" + lambertw(z, k=0, tol=1e-8) + + Lambert W function. + + The Lambert W function `W(z)` is defined as the inverse function + of ``w * exp(w)``. In other words, the value of ``W(z)`` is + such that ``z = W(z) * exp(W(z))`` for any complex number + ``z``. + + The Lambert W function is a multivalued function with infinitely + many branches. Each branch gives a separate solution of the + equation ``z = w exp(w)``. Here, the branches are indexed by the + integer `k`. + + Parameters + ---------- + z : array_like + Input argument. + k : int, optional + Branch index. + tol : float, optional + Evaluation tolerance. + + Returns + ------- + w : array + `w` will have the same shape as `z`. + + See Also + -------- + wrightomega : the Wright Omega function + + Notes + ----- + All branches are supported by `lambertw`: + + * ``lambertw(z)`` gives the principal solution (branch 0) + * ``lambertw(z, k)`` gives the solution on branch `k` + + The Lambert W function has two partially real branches: the + principal branch (`k = 0`) is real for real ``z > -1/e``, and the + ``k = -1`` branch is real for ``-1/e < z < 0``. All branches except + ``k = 0`` have a logarithmic singularity at ``z = 0``. + + **Possible issues** + + The evaluation can become inaccurate very close to the branch point + at ``-1/e``. In some corner cases, `lambertw` might currently + fail to converge, or can end up on the wrong branch. + + **Algorithm** + + Halley's iteration is used to invert ``w * exp(w)``, using a first-order + asymptotic approximation (O(log(w)) or `O(w)`) as the initial estimate. + + The definition, implementation and choice of branches is based on [2]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Lambert_W_function + .. [2] Corless et al, "On the Lambert W function", Adv. Comp. Math. 5 + (1996) 329-359. + https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf + + Examples + -------- + The Lambert W function is the inverse of ``w exp(w)``: + + >>> import numpy as np + >>> from scipy.special import lambertw + >>> w = lambertw(1) + >>> w + (0.56714329040978384+0j) + >>> w * np.exp(w) + (1.0+0j) + + Any branch gives a valid inverse: + + >>> w = lambertw(1, k=3) + >>> w + (-2.8535817554090377+17.113535539412148j) + >>> w*np.exp(w) + (1.0000000000000002+1.609823385706477e-15j) + + **Applications to equation-solving** + + The Lambert W function may be used to solve various kinds of + equations. We give two examples here. + + First, the function can be used to solve implicit equations of the + form + + :math:`x = a + b e^{c x}` + + for :math:`x`. We assume :math:`c` is not zero. After a little + algebra, the equation may be written + + :math:`z e^z = -b c e^{a c}` + + where :math:`z = c (a - x)`. :math:`z` may then be expressed using + the Lambert W function + + :math:`z = W(-b c e^{a c})` + + giving + + :math:`x = a - W(-b c e^{a c})/c` + + For example, + + >>> a = 3 + >>> b = 2 + >>> c = -0.5 + + The solution to :math:`x = a + b e^{c x}` is: + + >>> x = a - lambertw(-b*c*np.exp(a*c))/c + >>> x + (3.3707498368978794+0j) + + Verify that it solves the equation: + + >>> a + b*np.exp(c*x) + (3.37074983689788+0j) + + The Lambert W function may also be used find the value of the infinite + power tower :math:`z^{z^{z^{\ldots}}}`: + + >>> def tower(z, n): + ... if n == 0: + ... return z + ... return z ** tower(z, n-1) + ... + >>> tower(0.5, 100) + 0.641185744504986 + >>> -lambertw(-np.log(0.5)) / np.log(0.5) + (0.64118574450498589+0j) + """ + # TODO: special expert should inspect this + # interception; better place to do it? + k = np.asarray(k, dtype=np.dtype("long")) + return _lambertw(z, k, tol) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0da953464e8d92925ebdaba79ce062c38fc7e5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py @@ -0,0 +1,417 @@ +import math +import numpy as np +from scipy._lib._util import _asarray_validated +from scipy._lib._array_api import ( + array_namespace, + xp_size, + xp_broadcast_promote, + xp_copy, + xp_float_to_complex, + is_complex, +) +from scipy._lib import array_api_extra as xpx + +__all__ = ["logsumexp", "softmax", "log_softmax"] + + +def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False): + """Compute the log of the sum of exponentials of input elements. + + Parameters + ---------- + a : array_like + Input array. + axis : None or int or tuple of ints, optional + Axis or axes over which the sum is taken. By default `axis` is None, + and all elements are summed. + + .. versionadded:: 0.11.0 + b : array-like, optional + Scaling factor for exp(`a`) must be of the same shape as `a` or + broadcastable to `a`. These values may be negative in order to + implement subtraction. + + .. versionadded:: 0.12.0 + 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. + + .. versionadded:: 0.15.0 + return_sign : bool, optional + If this is set to True, the result will be a pair containing sign + information; if False, results that are negative will be returned + as NaN. Default is False (no sign information). + + .. versionadded:: 0.16.0 + + Returns + ------- + res : ndarray + The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically + more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))`` + is returned. If ``return_sign`` is True, ``res`` contains the log of + the absolute value of the argument. + sgn : ndarray + If ``return_sign`` is True, this will be an array of floating-point + numbers matching res containing +1, 0, -1 (for real-valued inputs) + or a complex phase (for complex inputs). This gives the sign of the + argument of the logarithm in ``res``. + If ``return_sign`` is False, only one result is returned. + + See Also + -------- + numpy.logaddexp, numpy.logaddexp2 + + Notes + ----- + NumPy has a logaddexp function which is very similar to `logsumexp`, but + only handles two arguments. `logaddexp.reduce` is similar to this + function, but may be less stable. + + The logarithm is a multivalued function: for each :math:`x` there is an + infinite number of :math:`z` such that :math:`exp(z) = x`. The convention + is to return the :math:`z` whose imaginary part lies in :math:`(-pi, pi]`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import logsumexp + >>> a = np.arange(10) + >>> logsumexp(a) + 9.4586297444267107 + >>> np.log(np.sum(np.exp(a))) + 9.4586297444267107 + + With weights + + >>> a = np.arange(10) + >>> b = np.arange(10, 0, -1) + >>> logsumexp(a, b=b) + 9.9170178533034665 + >>> np.log(np.sum(b*np.exp(a))) + 9.9170178533034647 + + Returning a sign flag + + >>> logsumexp([1,2],b=[1,-1],return_sign=True) + (1.5413248546129181, -1.0) + + Notice that `logsumexp` does not directly support masked arrays. To use it + on a masked array, convert the mask into zero weights: + + >>> a = np.ma.array([np.log(2), 2, np.log(3)], + ... mask=[False, True, False]) + >>> b = (~a.mask).astype(int) + >>> logsumexp(a.data, b=b), np.log(5) + 1.6094379124341005, 1.6094379124341005 + + """ + xp = array_namespace(a, b) + a, b = xp_broadcast_promote(a, b, ensure_writeable=True, force_floating=True, xp=xp) + a = xpx.atleast_nd(a, ndim=1, xp=xp) + b = xpx.atleast_nd(b, ndim=1, xp=xp) if b is not None else b + axis = tuple(range(a.ndim)) if axis is None else axis + + if xp_size(a) != 0: + with np.errstate(divide='ignore', invalid='ignore'): # log of zero is OK + out, sgn = _logsumexp(a, b, axis=axis, return_sign=return_sign, xp=xp) + else: + shape = np.asarray(a.shape) # NumPy is convenient for shape manipulation + shape[axis] = 1 + out = xp.full(tuple(shape), -xp.inf, dtype=a.dtype) + sgn = xp.sign(out) + + if xp.isdtype(out.dtype, 'complex floating'): + if return_sign: + real = xp.real(sgn) + imag = xp_float_to_complex(_wrap_radians(xp.imag(sgn), xp)) + sgn = real + imag*1j + else: + real = xp.real(out) + imag = xp_float_to_complex(_wrap_radians(xp.imag(out), xp)) + out = real + imag*1j + + # Deal with shape details - reducing dimensions and convert 0-D to scalar for NumPy + out = xp.squeeze(out, axis=axis) if not keepdims else out + sgn = xp.squeeze(sgn, axis=axis) if (sgn is not None and not keepdims) else sgn + out = out[()] if out.ndim == 0 else out + sgn = sgn[()] if (sgn is not None and sgn.ndim == 0) else sgn + + return (out, sgn) if return_sign else out + + +def _wrap_radians(x, xp=None): + xp = array_namespace(x) if xp is None else xp + # Wrap radians to (-pi, pi] interval + out = -((-x + math.pi) % (2 * math.pi) - math.pi) + # preserve relative precision + no_wrap = xp.abs(x) < xp.pi + out[no_wrap] = x[no_wrap] + return out + + +def _elements_and_indices_with_max_real(a, axis=-1, xp=None): + # This is an array-API compatible `max` function that works something + # like `np.max` for complex input. The important part is that it finds + # the element with maximum real part. When there are multiple complex values + # with this real part, it doesn't matter which we choose. + # We could use `argmax` on real component, but array API doesn't yet have + # `take_along_axis`, and even if it did, we would have problems with axis tuples. + # Feel free to rewrite! It's ugly, but it's not the purpose of the PR, and + # it gets the job done. + xp = array_namespace(a) if xp is None else xp + + if xp.isdtype(a.dtype, "complex floating"): + # select all elements with max real part. + real_a = xp.real(a) + max = xp.max(real_a, axis=axis, keepdims=True) + mask = real_a == max + + # Of those, choose one arbitrarily. This is a reasonably + # simple, array-API compatible way of doing so that doesn't + # have a problem with `axis` being a tuple or None. + i = xp.reshape(xp.arange(xp_size(a)), a.shape) + i[~mask] = -1 + max_i = xp.max(i, axis=axis, keepdims=True) + mask = i == max_i + a = xp_copy(a) + a[~mask] = 0 + max = xp.sum(a, axis=axis, dtype=a.dtype, keepdims=True) + else: + max = xp.max(a, axis=axis, keepdims=True) + mask = a == max + + return xp.asarray(max), xp.asarray(mask) + + +def _sign(x, xp): + return x / xp.where(x == 0, xp.asarray(1, dtype=x.dtype), xp.abs(x)) + + +def _logsumexp(a, b, axis, return_sign, xp): + + # This has been around for about a decade, so let's consider it a feature: + # Even if element of `a` is infinite or NaN, it adds nothing to the sum if + # the corresponding weight is zero. + if b is not None: + a[b == 0] = -xp.inf + + # Find element with maximum real part, since this is what affects the magnitude + # of the exponential. Possible enhancement: include log of `b` magnitude in `a`. + a_max, i_max = _elements_and_indices_with_max_real(a, axis=axis, xp=xp) + + # for precision, these terms are separated out of the main sum. + a[i_max] = -xp.inf + i_max_dt = xp.astype(i_max, a.dtype) + # This is an inefficient way of getting `m` because it is the sum of a sparse + # array; however, this is the simplest way I can think of to get the right shape. + m = (xp.sum(i_max_dt, axis=axis, keepdims=True, dtype=a.dtype) if b is None + else xp.sum(b * i_max_dt, axis=axis, keepdims=True, dtype=a.dtype)) + + # Arithmetic between infinities will introduce NaNs. + # `+ a_max` at the end naturally corrects for removing them here. + shift = xp.where(xp.isfinite(a_max), a_max, xp.asarray(0, dtype=a_max.dtype)) + + # Shift, exponentiate, scale, and sum + exp = b * xp.exp(a - shift) if b is not None else xp.exp(a - shift) + s = xp.sum(exp, axis=axis, keepdims=True, dtype=exp.dtype) + s = xp.where(s == 0, s, s/m) + + # Separate sign/magnitude information + # Originally, this was only performed if `return_sign=True`. + # However, this is also needed if any elements of `m < 0` or `s < -1`. + # An improvement would be to perform the calculations only on these entries. + + # Use the numpy>=2.0 convention for sign. + # When all array libraries agree, this can become sng = xp.sign(s). + sgn = _sign(s + 1, xp=xp) * _sign(m, xp=xp) + + if xp.isdtype(s.dtype, "real floating"): + # The log functions need positive arguments + s = xp.where(s < -1, -s - 2, s) + m = xp.abs(m) + else: + # `a_max` can have a sign component for complex input + sgn = sgn * xp.exp(xp.imag(a_max) * xp.asarray(1.0j, dtype=a_max.dtype)) + + # Take log and undo shift + out = xp.log1p(s) + xp.log(m) + a_max + + if return_sign: + if is_complex(out, xp): + out = xp.real(out) + elif xp.isdtype(out.dtype, 'real floating'): + out[sgn < 0] = xp.nan + + return out, sgn + + +def softmax(x, axis=None): + r"""Compute the softmax function. + + The softmax function transforms each element of a collection by + computing the exponential of each element divided by the sum of the + exponentials of all the elements. That is, if `x` is a one-dimensional + numpy array:: + + softmax(x) = np.exp(x)/sum(np.exp(x)) + + Parameters + ---------- + x : array_like + Input array. + axis : int or tuple of ints, optional + Axis to compute values along. Default is None and softmax will be + computed over the entire array `x`. + + Returns + ------- + s : ndarray + An array the same shape as `x`. The result will sum to 1 along the + specified axis. + + Notes + ----- + The formula for the softmax function :math:`\sigma(x)` for a vector + :math:`x = \{x_0, x_1, ..., x_{n-1}\}` is + + .. math:: \sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}} + + The `softmax` function is the gradient of `logsumexp`. + + The implementation uses shifting to avoid overflow. See [1]_ for more + details. + + .. versionadded:: 1.2.0 + + References + ---------- + .. [1] P. Blanchard, D.J. Higham, N.J. Higham, "Accurately computing the + log-sum-exp and softmax functions", IMA Journal of Numerical Analysis, + Vol.41(4), :doi:`10.1093/imanum/draa038`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import softmax + >>> np.set_printoptions(precision=5) + + >>> x = np.array([[1, 0.5, 0.2, 3], + ... [1, -1, 7, 3], + ... [2, 12, 13, 3]]) + ... + + Compute the softmax transformation over the entire array. + + >>> m = softmax(x) + >>> m + array([[ 4.48309e-06, 2.71913e-06, 2.01438e-06, 3.31258e-05], + [ 4.48309e-06, 6.06720e-07, 1.80861e-03, 3.31258e-05], + [ 1.21863e-05, 2.68421e-01, 7.29644e-01, 3.31258e-05]]) + + >>> m.sum() + 1.0 + + Compute the softmax transformation along the first axis (i.e., the + columns). + + >>> m = softmax(x, axis=0) + + >>> m + array([[ 2.11942e-01, 1.01300e-05, 2.75394e-06, 3.33333e-01], + [ 2.11942e-01, 2.26030e-06, 2.47262e-03, 3.33333e-01], + [ 5.76117e-01, 9.99988e-01, 9.97525e-01, 3.33333e-01]]) + + >>> m.sum(axis=0) + array([ 1., 1., 1., 1.]) + + Compute the softmax transformation along the second axis (i.e., the rows). + + >>> m = softmax(x, axis=1) + >>> m + array([[ 1.05877e-01, 6.42177e-02, 4.75736e-02, 7.82332e-01], + [ 2.42746e-03, 3.28521e-04, 9.79307e-01, 1.79366e-02], + [ 1.22094e-05, 2.68929e-01, 7.31025e-01, 3.31885e-05]]) + + >>> m.sum(axis=1) + array([ 1., 1., 1.]) + + """ + x = _asarray_validated(x, check_finite=False) + x_max = np.amax(x, axis=axis, keepdims=True) + exp_x_shifted = np.exp(x - x_max) + return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True) + + +def log_softmax(x, axis=None): + r"""Compute the logarithm of the softmax function. + + In principle:: + + log_softmax(x) = log(softmax(x)) + + but using a more accurate implementation. + + Parameters + ---------- + x : array_like + Input array. + axis : int or tuple of ints, optional + Axis to compute values along. Default is None and softmax will be + computed over the entire array `x`. + + Returns + ------- + s : ndarray or scalar + An array with the same shape as `x`. Exponential of the result will + sum to 1 along the specified axis. If `x` is a scalar, a scalar is + returned. + + Notes + ----- + `log_softmax` is more accurate than ``np.log(softmax(x))`` with inputs that + make `softmax` saturate (see examples below). + + .. versionadded:: 1.5.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import log_softmax + >>> from scipy.special import softmax + >>> np.set_printoptions(precision=5) + + >>> x = np.array([1000.0, 1.0]) + + >>> y = log_softmax(x) + >>> y + array([ 0., -999.]) + + >>> with np.errstate(divide='ignore'): + ... y = np.log(softmax(x)) + ... + >>> y + array([ 0., -inf]) + + """ + + x = _asarray_validated(x, check_finite=False) + + x_max = np.amax(x, axis=axis, keepdims=True) + + if x_max.ndim > 0: + x_max[~np.isfinite(x_max)] = 0 + elif not np.isfinite(x_max): + x_max = 0 + + tmp = x - x_max + exp_tmp = np.exp(tmp) + + # suppress warnings about log of zero + with np.errstate(divide='ignore'): + s = np.sum(exp_tmp, axis=axis, keepdims=True) + out = np.log(s) + + out = tmp - out + return out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py new file mode 100644 index 0000000000000000000000000000000000000000..9e519093dface79e21f16d7063541ad107f5ca96 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py @@ -0,0 +1,453 @@ +import os +import sys +import time +from itertools import zip_longest + +import numpy as np +from numpy.testing import assert_ +import pytest + +from scipy.special._testutils import assert_func_equal + +try: + import mpmath +except ImportError: + pass + + +# ------------------------------------------------------------------------------ +# Machinery for systematic tests with mpmath +# ------------------------------------------------------------------------------ + +class Arg: + """Generate a set of numbers on the real axis, concentrating on + 'interesting' regions and covering all orders of magnitude. + + """ + + def __init__(self, a=-np.inf, b=np.inf, inclusive_a=True, inclusive_b=True): + if a > b: + raise ValueError("a should be less than or equal to b") + if a == -np.inf: + a = -0.5*np.finfo(float).max + if b == np.inf: + b = 0.5*np.finfo(float).max + self.a, self.b = a, b + + self.inclusive_a, self.inclusive_b = inclusive_a, inclusive_b + + def _positive_values(self, a, b, n): + if a < 0: + raise ValueError("a should be positive") + + # Try to put half of the points into a linspace between a and + # 10 the other half in a logspace. + if n % 2 == 0: + nlogpts = n//2 + nlinpts = nlogpts + else: + nlogpts = n//2 + nlinpts = nlogpts + 1 + + if a >= 10: + # Outside of linspace range; just return a logspace. + pts = np.logspace(np.log10(a), np.log10(b), n) + elif a > 0 and b < 10: + # Outside of logspace range; just return a linspace + pts = np.linspace(a, b, n) + elif a > 0: + # Linspace between a and 10 and a logspace between 10 and + # b. + linpts = np.linspace(a, 10, nlinpts, endpoint=False) + logpts = np.logspace(1, np.log10(b), nlogpts) + pts = np.hstack((linpts, logpts)) + elif a == 0 and b <= 10: + # Linspace between 0 and b and a logspace between 0 and + # the smallest positive point of the linspace + linpts = np.linspace(0, b, nlinpts) + if linpts.size > 1: + right = np.log10(linpts[1]) + else: + right = -30 + logpts = np.logspace(-30, right, nlogpts, endpoint=False) + pts = np.hstack((logpts, linpts)) + else: + # Linspace between 0 and 10, logspace between 0 and the + # smallest positive point of the linspace, and a logspace + # between 10 and b. + if nlogpts % 2 == 0: + nlogpts1 = nlogpts//2 + nlogpts2 = nlogpts1 + else: + nlogpts1 = nlogpts//2 + nlogpts2 = nlogpts1 + 1 + linpts = np.linspace(0, 10, nlinpts, endpoint=False) + if linpts.size > 1: + right = np.log10(linpts[1]) + else: + right = -30 + logpts1 = np.logspace(-30, right, nlogpts1, endpoint=False) + logpts2 = np.logspace(1, np.log10(b), nlogpts2) + pts = np.hstack((logpts1, linpts, logpts2)) + + return np.sort(pts) + + def values(self, n): + """Return an array containing n numbers.""" + a, b = self.a, self.b + if a == b: + return np.zeros(n) + + if not self.inclusive_a: + n += 1 + if not self.inclusive_b: + n += 1 + + if n % 2 == 0: + n1 = n//2 + n2 = n1 + else: + n1 = n//2 + n2 = n1 + 1 + + if a >= 0: + pospts = self._positive_values(a, b, n) + negpts = [] + elif b <= 0: + pospts = [] + negpts = -self._positive_values(-b, -a, n) + else: + pospts = self._positive_values(0, b, n1) + negpts = -self._positive_values(0, -a, n2 + 1) + # Don't want to get zero twice + negpts = negpts[1:] + pts = np.hstack((negpts[::-1], pospts)) + + if not self.inclusive_a: + pts = pts[1:] + if not self.inclusive_b: + pts = pts[:-1] + return pts + + +class FixedArg: + def __init__(self, values): + self._values = np.asarray(values) + + def values(self, n): + return self._values + + +class ComplexArg: + def __init__(self, a=complex(-np.inf, -np.inf), b=complex(np.inf, np.inf)): + self.real = Arg(a.real, b.real) + self.imag = Arg(a.imag, b.imag) + + def values(self, n): + m = int(np.floor(np.sqrt(n))) + x = self.real.values(m) + y = self.imag.values(m + 1) + return (x[:,None] + 1j*y[None,:]).ravel() + + +class IntArg: + def __init__(self, a=-1000, b=1000): + self.a = a + self.b = b + + def values(self, n): + v1 = Arg(self.a, self.b).values(max(1 + n//2, n-5)).astype(int) + v2 = np.arange(-5, 5) + v = np.unique(np.r_[v1, v2]) + v = v[(v >= self.a) & (v < self.b)] + return v + + +def get_args(argspec, n): + if isinstance(argspec, np.ndarray): + args = argspec.copy() + else: + nargs = len(argspec) + ms = np.asarray( + [1.5 if isinstance(spec, ComplexArg) else 1.0 for spec in argspec] + ) + ms = (n**(ms/sum(ms))).astype(int) + 1 + + args = [spec.values(m) for spec, m in zip(argspec, ms)] + args = np.array(np.broadcast_arrays(*np.ix_(*args))).reshape(nargs, -1).T + + return args + + +class MpmathData: + def __init__(self, scipy_func, mpmath_func, arg_spec, name=None, + dps=None, prec=None, n=None, rtol=1e-7, atol=1e-300, + ignore_inf_sign=False, distinguish_nan_and_inf=True, + nan_ok=True, param_filter=None): + + # mpmath tests are really slow (see gh-6989). Use a small number of + # points by default, increase back to 5000 (old default) if XSLOW is + # set + if n is None: + try: + is_xslow = int(os.environ.get('SCIPY_XSLOW', '0')) + except ValueError: + is_xslow = False + + n = 5000 if is_xslow else 500 + + self.scipy_func = scipy_func + self.mpmath_func = mpmath_func + self.arg_spec = arg_spec + self.dps = dps + self.prec = prec + self.n = n + self.rtol = rtol + self.atol = atol + self.ignore_inf_sign = ignore_inf_sign + self.nan_ok = nan_ok + if isinstance(self.arg_spec, np.ndarray): + self.is_complex = np.issubdtype(self.arg_spec.dtype, np.complexfloating) + else: + self.is_complex = any( + [isinstance(arg, ComplexArg) for arg in self.arg_spec] + ) + self.ignore_inf_sign = ignore_inf_sign + self.distinguish_nan_and_inf = distinguish_nan_and_inf + if not name or name == '': + name = getattr(scipy_func, '__name__', None) + if not name or name == '': + name = getattr(mpmath_func, '__name__', None) + self.name = name + self.param_filter = param_filter + + def check(self): + np.random.seed(1234) + + # Generate values for the arguments + argarr = get_args(self.arg_spec, self.n) + + # Check + old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec + try: + if self.dps is not None: + dps_list = [self.dps] + else: + dps_list = [20] + if self.prec is not None: + mpmath.mp.prec = self.prec + + # Proper casting of mpmath input and output types. Using + # native mpmath types as inputs gives improved precision + # in some cases. + if np.issubdtype(argarr.dtype, np.complexfloating): + pytype = mpc2complex + + def mptype(x): + return mpmath.mpc(complex(x)) + else: + def mptype(x): + return mpmath.mpf(float(x)) + + def pytype(x): + if abs(x.imag) > 1e-16*(1 + abs(x.real)): + return np.nan + else: + return mpf2float(x.real) + + # Try out different dps until one (or none) works + for j, dps in enumerate(dps_list): + mpmath.mp.dps = dps + + try: + assert_func_equal( + self.scipy_func, + lambda *a: pytype(self.mpmath_func(*map(mptype, a))), + argarr, + vectorized=False, + rtol=self.rtol, + atol=self.atol, + ignore_inf_sign=self.ignore_inf_sign, + distinguish_nan_and_inf=self.distinguish_nan_and_inf, + nan_ok=self.nan_ok, + param_filter=self.param_filter + ) + break + except AssertionError: + if j >= len(dps_list)-1: + # reraise the Exception + tp, value, tb = sys.exc_info() + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec + + def __repr__(self): + if self.is_complex: + return f"" + else: + return f"" + + +def assert_mpmath_equal(*a, **kw): + d = MpmathData(*a, **kw) + d.check() + + +def nonfunctional_tooslow(func): + return pytest.mark.skip( + reason=" Test not yet functional (too slow), needs more work." + )(func) + + +# ------------------------------------------------------------------------------ +# Tools for dealing with mpmath quirks +# ------------------------------------------------------------------------------ + +def mpf2float(x): + """ + Convert an mpf to the nearest floating point number. Just using + float directly doesn't work because of results like this: + + with mp.workdps(50): + float(mpf("0.99999999999999999")) = 0.9999999999999999 + + """ + return float(mpmath.nstr(x, 17, min_fixed=0, max_fixed=0)) + + +def mpc2complex(x): + return complex(mpf2float(x.real), mpf2float(x.imag)) + + +def trace_args(func): + def tofloat(x): + if isinstance(x, mpmath.mpc): + return complex(x) + else: + return float(x) + + def wrap(*a, **kw): + sys.stderr.write(f"{tuple(map(tofloat, a))!r}: ") + sys.stderr.flush() + try: + r = func(*a, **kw) + sys.stderr.write(f"-> {r!r}") + finally: + sys.stderr.write("\n") + sys.stderr.flush() + return r + return wrap + + +try: + import signal + POSIX = ('setitimer' in dir(signal)) +except ImportError: + POSIX = False + + +class TimeoutError(Exception): + pass + + +def time_limited(timeout=0.5, return_val=np.nan, use_sigalrm=True): + """ + Decorator for setting a timeout for pure-Python functions. + + If the function does not return within `timeout` seconds, the + value `return_val` is returned instead. + + On POSIX this uses SIGALRM by default. On non-POSIX, settrace is + used. Do not use this with threads: the SIGALRM implementation + does probably not work well. The settrace implementation only + traces the current thread. + + The settrace implementation slows down execution speed. Slowdown + by a factor around 10 is probably typical. + """ + if POSIX and use_sigalrm: + def sigalrm_handler(signum, frame): + raise TimeoutError() + + def deco(func): + def wrap(*a, **kw): + old_handler = signal.signal(signal.SIGALRM, sigalrm_handler) + signal.setitimer(signal.ITIMER_REAL, timeout) + try: + return func(*a, **kw) + except TimeoutError: + return return_val + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, old_handler) + return wrap + else: + def deco(func): + def wrap(*a, **kw): + start_time = time.time() + + def trace(frame, event, arg): + if time.time() - start_time > timeout: + raise TimeoutError() + return trace + sys.settrace(trace) + try: + return func(*a, **kw) + except TimeoutError: + sys.settrace(None) + return return_val + finally: + sys.settrace(None) + return wrap + return deco + + +def exception_to_nan(func): + """Decorate function to return nan if it raises an exception""" + def wrap(*a, **kw): + try: + return func(*a, **kw) + except Exception: + return np.nan + return wrap + + +def inf_to_nan(func): + """Decorate function to return nan if it returns inf""" + def wrap(*a, **kw): + v = func(*a, **kw) + if not np.isfinite(v): + return np.nan + return v + return wrap + + +def mp_assert_allclose(res, std, atol=0, rtol=1e-17): + """ + Compare lists of mpmath.mpf's or mpmath.mpc's directly so that it + can be done to higher precision than double. + """ + failures = [] + for k, (resval, stdval) in enumerate(zip_longest(res, std)): + if resval is None or stdval is None: + raise ValueError('Lengths of inputs res and std are not equal.') + if mpmath.fabs(resval - stdval) > atol + rtol*mpmath.fabs(stdval): + failures.append((k, resval, stdval)) + + nfail = len(failures) + if nfail > 0: + ndigits = int(abs(np.log10(rtol))) + msg = [""] + msg.append(f"Bad results ({nfail} out of {k + 1}) for the following points:") + for k, resval, stdval in failures: + resrep = mpmath.nstr(resval, ndigits, min_fixed=0, max_fixed=0) + stdrep = mpmath.nstr(stdval, ndigits, min_fixed=0, max_fixed=0) + if stdval == 0: + rdiff = "inf" + else: + rdiff = mpmath.fabs((resval - stdval)/stdval) + rdiff = mpmath.nstr(rdiff, 3) + msg.append(f"{k}: {resrep} != {stdrep} (rdiff {rdiff})") + assert_(False, "\n".join(msg)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb1be9461c629a48841f1d01268e8d11eee230f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py @@ -0,0 +1,610 @@ +import collections +import numbers +import numpy as np + +from ._input_validation import _nonneg_int_or_fail + +from ._special_ufuncs import (legendre_p, assoc_legendre_p, + sph_legendre_p, sph_harm_y) +from ._gufuncs import (legendre_p_all, assoc_legendre_p_all, + sph_legendre_p_all, sph_harm_y_all) + +__all__ = [ + "assoc_legendre_p", + "assoc_legendre_p_all", + "legendre_p", + "legendre_p_all", + "sph_harm_y", + "sph_harm_y_all", + "sph_legendre_p", + "sph_legendre_p_all", +] + + +class MultiUFunc: + def __init__(self, ufunc_or_ufuncs, doc=None, *, + force_complex_output=False, **default_kwargs): + if not isinstance(ufunc_or_ufuncs, np.ufunc): + if isinstance(ufunc_or_ufuncs, collections.abc.Mapping): + ufuncs_iter = ufunc_or_ufuncs.values() + elif isinstance(ufunc_or_ufuncs, collections.abc.Iterable): + ufuncs_iter = ufunc_or_ufuncs + else: + raise ValueError("ufunc_or_ufuncs should be a ufunc or a" + " ufunc collection") + + # Perform input validation to ensure all ufuncs in ufuncs are + # actually ufuncs and all take the same input types. + seen_input_types = set() + for ufunc in ufuncs_iter: + if not isinstance(ufunc, np.ufunc): + raise ValueError("All ufuncs must have type `numpy.ufunc`." + f" Received {ufunc_or_ufuncs}") + seen_input_types.add(frozenset(x.split("->")[0] for x in ufunc.types)) + if len(seen_input_types) > 1: + raise ValueError("All ufuncs must take the same input types.") + + self._ufunc_or_ufuncs = ufunc_or_ufuncs + self.__doc = doc + self.__force_complex_output = force_complex_output + self._default_kwargs = default_kwargs + self._resolve_out_shapes = None + self._finalize_out = None + self._key = None + self._ufunc_default_args = lambda *args, **kwargs: () + self._ufunc_default_kwargs = lambda *args, **kwargs: {} + + @property + def __doc__(self): + return self.__doc + + def _override_key(self, func): + """Set `key` method by decorating a function. + """ + self._key = func + + def _override_ufunc_default_args(self, func): + self._ufunc_default_args = func + + def _override_ufunc_default_kwargs(self, func): + self._ufunc_default_kwargs = func + + def _override_resolve_out_shapes(self, func): + """Set `resolve_out_shapes` method by decorating a function.""" + if func.__doc__ is None: + func.__doc__ = \ + """Resolve to output shapes based on relevant inputs.""" + func.__name__ = "resolve_out_shapes" + self._resolve_out_shapes = func + + def _override_finalize_out(self, func): + self._finalize_out = func + + def _resolve_ufunc(self, **kwargs): + """Resolve to a ufunc based on keyword arguments.""" + + if isinstance(self._ufunc_or_ufuncs, np.ufunc): + return self._ufunc_or_ufuncs + + ufunc_key = self._key(**kwargs) + return self._ufunc_or_ufuncs[ufunc_key] + + def __call__(self, *args, **kwargs): + kwargs = self._default_kwargs | kwargs + + args += self._ufunc_default_args(**kwargs) + + ufunc = self._resolve_ufunc(**kwargs) + + # array arguments to be passed to the ufunc + ufunc_args = [np.asarray(arg) for arg in args[-ufunc.nin:]] + + ufunc_kwargs = self._ufunc_default_kwargs(**kwargs) + + if (self._resolve_out_shapes is not None): + ufunc_arg_shapes = tuple(np.shape(ufunc_arg) for ufunc_arg in ufunc_args) + ufunc_out_shapes = self._resolve_out_shapes(*args[:-ufunc.nin], + *ufunc_arg_shapes, ufunc.nout, + **kwargs) + + ufunc_arg_dtypes = tuple(ufunc_arg.dtype if hasattr(ufunc_arg, 'dtype') + else np.dtype(type(ufunc_arg)) + for ufunc_arg in ufunc_args) + + if hasattr(ufunc, 'resolve_dtypes'): + ufunc_dtypes = ufunc_arg_dtypes + ufunc.nout * (None,) + ufunc_dtypes = ufunc.resolve_dtypes(ufunc_dtypes) + ufunc_out_dtypes = ufunc_dtypes[-ufunc.nout:] + else: + ufunc_out_dtype = np.result_type(*ufunc_arg_dtypes) + if (not np.issubdtype(ufunc_out_dtype, np.inexact)): + ufunc_out_dtype = np.float64 + + ufunc_out_dtypes = ufunc.nout * (ufunc_out_dtype,) + + if self.__force_complex_output: + ufunc_out_dtypes = tuple(np.result_type(1j, ufunc_out_dtype) + for ufunc_out_dtype in ufunc_out_dtypes) + + out = tuple(np.empty(ufunc_out_shape, dtype=ufunc_out_dtype) + for ufunc_out_shape, ufunc_out_dtype + in zip(ufunc_out_shapes, ufunc_out_dtypes)) + + ufunc_kwargs['out'] = out + + out = ufunc(*ufunc_args, **ufunc_kwargs) + if (self._finalize_out is not None): + out = self._finalize_out(out) + + return out + + +sph_legendre_p = MultiUFunc( + sph_legendre_p, + r"""sph_legendre_p(n, m, theta, *, diff_n=0) + + Spherical Legendre polynomial of the first kind. + + Parameters + ---------- + n : ArrayLike[int] + Degree of the spherical Legendre polynomial. Must have ``n >= 0``. + m : ArrayLike[int] + Order of the spherical Legendre polynomial. + theta : ArrayLike[float] + Input value. + diff_n : Optional[int] + A non-negative integer. Compute and return all derivatives up + to order ``diff_n``. Default is 0. + + Returns + ------- + p : ndarray or tuple[ndarray] + Spherical Legendre polynomial with ``diff_n`` derivatives. + + Notes + ----- + The spherical counterpart of an (unnormalized) associated Legendre polynomial has + the additional factor + + .. math:: + + \sqrt{\frac{(2 n + 1) (n - m)!}{4 \pi (n + m)!}} + + It is the same as the spherical harmonic :math:`Y_{n}^{m}(\theta, \phi)` + with :math:`\phi = 0`. + """, diff_n=0 +) + + +@sph_legendre_p._override_key +def _(diff_n): + diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False) + if not 0 <= diff_n <= 2: + raise ValueError( + "diff_n is currently only implemented for orders 0, 1, and 2," + f" received: {diff_n}." + ) + return diff_n + + +@sph_legendre_p._override_finalize_out +def _(out): + return np.moveaxis(out, -1, 0) + + +sph_legendre_p_all = MultiUFunc( + sph_legendre_p_all, + """sph_legendre_p_all(n, m, theta, *, diff_n=0) + + All spherical Legendre polynomials of the first kind up to the + specified degree ``n`` and order ``m``. + + Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)`` + corresponds to degree ``j`` and order ``i`` for all ``0 <= j <= n`` + and ``-m <= i <= m``. + + See Also + -------- + sph_legendre_p + """, diff_n=0 +) + + +@sph_legendre_p_all._override_key +def _(diff_n): + diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False) + if not 0 <= diff_n <= 2: + raise ValueError( + "diff_n is currently only implemented for orders 0, 1, and 2," + f" received: {diff_n}." + ) + return diff_n + + +@sph_legendre_p_all._override_ufunc_default_kwargs +def _(diff_n): + return {'axes': [()] + [(0, 1, -1)]} + + +@sph_legendre_p_all._override_resolve_out_shapes +def _(n, m, theta_shape, nout, diff_n): + if not isinstance(n, numbers.Integral) or (n < 0): + raise ValueError("n must be a non-negative integer.") + + return ((n + 1, 2 * abs(m) + 1) + theta_shape + (diff_n + 1,),) + + +@sph_legendre_p_all._override_finalize_out +def _(out): + return np.moveaxis(out, -1, 0) + + +assoc_legendre_p = MultiUFunc( + assoc_legendre_p, + r"""assoc_legendre_p(n, m, z, *, branch_cut=2, norm=False, diff_n=0) + + Associated Legendre polynomial of the first kind. + + Parameters + ---------- + n : ArrayLike[int] + Degree of the associated Legendre polynomial. Must have ``n >= 0``. + m : ArrayLike[int] + order of the associated Legendre polynomial. + z : ArrayLike[float | complex] + Input value. + branch_cut : Optional[ArrayLike[int]] + Selects branch cut. Must be 2 (default) or 3. + 2: cut on the real axis ``|z| > 1`` + 3: cut on the real axis ``-1 < z < 1`` + norm : Optional[bool] + If ``True``, compute the normalized associated Legendre polynomial. + Default is ``False``. + diff_n : Optional[int] + A non-negative integer. Compute and return all derivatives up + to order ``diff_n``. Default is 0. + + Returns + ------- + p : ndarray or tuple[ndarray] + Associated Legendre polynomial with ``diff_n`` derivatives. + + Notes + ----- + The normalized counterpart of an (unnormalized) associated Legendre + polynomial has the additional factor + + .. math:: + + \sqrt{\frac{(2 n + 1) (n - m)!}{2 (n + m)!}} + """, branch_cut=2, norm=False, diff_n=0 +) + + +@assoc_legendre_p._override_key +def _(branch_cut, norm, diff_n): + diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False) + if not 0 <= diff_n <= 2: + raise ValueError( + "diff_n is currently only implemented for orders 0, 1, and 2," + f" received: {diff_n}." + ) + return norm, diff_n + + +@assoc_legendre_p._override_ufunc_default_args +def _(branch_cut, norm, diff_n): + return branch_cut, + + +@assoc_legendre_p._override_finalize_out +def _(out): + return np.moveaxis(out, -1, 0) + + +assoc_legendre_p_all = MultiUFunc( + assoc_legendre_p_all, + """assoc_legendre_p_all(n, m, z, *, branch_cut=2, norm=False, diff_n=0) + + All associated Legendre polynomials of the first kind up to the + specified degree ``n`` and order ``m``. + + Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)`` + corresponds to degree ``j`` and order ``i`` for all ``0 <= j <= n`` + and ``-m <= i <= m``. + + See Also + -------- + assoc_legendre_p + """, branch_cut=2, norm=False, diff_n=0 +) + + +@assoc_legendre_p_all._override_key +def _(branch_cut, norm, diff_n): + if not ((isinstance(diff_n, numbers.Integral)) + and diff_n >= 0): + raise ValueError( + f"diff_n must be a non-negative integer, received: {diff_n}." + ) + if not 0 <= diff_n <= 2: + raise ValueError( + "diff_n is currently only implemented for orders 0, 1, and 2," + f" received: {diff_n}." + ) + return norm, diff_n + + +@assoc_legendre_p_all._override_ufunc_default_args +def _(branch_cut, norm, diff_n): + return branch_cut, + + +@assoc_legendre_p_all._override_ufunc_default_kwargs +def _(branch_cut, norm, diff_n): + return {'axes': [(), ()] + [(0, 1, -1)]} + + +@assoc_legendre_p_all._override_resolve_out_shapes +def _(n, m, z_shape, branch_cut_shape, nout, **kwargs): + diff_n = kwargs['diff_n'] + + if not isinstance(n, numbers.Integral) or (n < 0): + raise ValueError("n must be a non-negative integer.") + if not isinstance(m, numbers.Integral) or (m < 0): + raise ValueError("m must be a non-negative integer.") + + return ((n + 1, 2 * abs(m) + 1) + + np.broadcast_shapes(z_shape, branch_cut_shape) + (diff_n + 1,),) + + +@assoc_legendre_p_all._override_finalize_out +def _(out): + return np.moveaxis(out, -1, 0) + + +legendre_p = MultiUFunc( + legendre_p, + """legendre_p(n, z, *, diff_n=0) + + Legendre polynomial of the first kind. + + Parameters + ---------- + n : ArrayLike[int] + Degree of the Legendre polynomial. Must have ``n >= 0``. + z : ArrayLike[float] + Input value. + diff_n : Optional[int] + A non-negative integer. Compute and return all derivatives up + to order ``diff_n``. Default is 0. + + Returns + ------- + p : ndarray or tuple[ndarray] + Legendre polynomial with ``diff_n`` derivatives. + + See Also + -------- + legendre + + References + ---------- + .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special + Functions", John Wiley and Sons, 1996. + https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html + """, diff_n=0 +) + + +@legendre_p._override_key +def _(diff_n): + if (not isinstance(diff_n, numbers.Integral)) or (diff_n < 0): + raise ValueError( + f"diff_n must be a non-negative integer, received: {diff_n}." + ) + if not 0 <= diff_n <= 2: + raise NotImplementedError( + "diff_n is currently only implemented for orders 0, 1, and 2," + f" received: {diff_n}." + ) + return diff_n + + +@legendre_p._override_finalize_out +def _(out): + return np.moveaxis(out, -1, 0) + + +legendre_p_all = MultiUFunc( + legendre_p_all, + """legendre_p_all(n, z, *, diff_n=0) + + All Legendre polynomials of the first kind up to the + specified degree ``n``. + + Output shape is ``(n + 1, ...)``. The entry at ``j`` + corresponds to degree ``j`` for all ``0 <= j <= n``. + + See Also + -------- + legendre_p + """, diff_n=0 +) + + +@legendre_p_all._override_key +def _(diff_n): + diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False) + if not 0 <= diff_n <= 2: + raise ValueError( + "diff_n is currently only implemented for orders 0, 1, and 2," + f" received: {diff_n}." + ) + return diff_n + + +@legendre_p_all._override_ufunc_default_kwargs +def _(diff_n): + return {'axes': [(), (0, -1)]} + + +@legendre_p_all._override_resolve_out_shapes +def _(n, z_shape, nout, diff_n): + n = _nonneg_int_or_fail(n, 'n', strict=False) + + return nout * ((n + 1,) + z_shape + (diff_n + 1,),) + + +@legendre_p_all._override_finalize_out +def _(out): + return np.moveaxis(out, -1, 0) + + +sph_harm_y = MultiUFunc( + sph_harm_y, + r"""sph_harm_y(n, m, theta, phi, *, diff_n=0) + + Spherical harmonics. They are defined as + + .. math:: + + Y_n^m(\theta,\phi) = \sqrt{\frac{2 n + 1}{4 \pi} \frac{(n - m)!}{(n + m)!}} + P_n^m(\cos(\theta)) e^{i m \phi} + + where :math:`P_n^m` are the (unnormalized) associated Legendre polynomials. + + Parameters + ---------- + n : ArrayLike[int] + Degree of the harmonic. Must have ``n >= 0``. This is + often denoted by ``l`` (lower case L) in descriptions of + spherical harmonics. + m : ArrayLike[int] + Order of the harmonic. + theta : ArrayLike[float] + Polar (colatitudinal) coordinate; must be in ``[0, pi]``. + phi : ArrayLike[float] + Azimuthal (longitudinal) coordinate; must be in ``[0, 2*pi]``. + diff_n : Optional[int] + A non-negative integer. Compute and return all derivatives up + to order ``diff_n``. Default is 0. + + Returns + ------- + y : ndarray[complex] or tuple[ndarray[complex]] + Spherical harmonics with ``diff_n`` derivatives. + + Notes + ----- + There are different conventions for the meanings of the input + arguments ``theta`` and ``phi``. In SciPy ``theta`` is the + polar angle and ``phi`` is the azimuthal angle. It is common to + see the opposite convention, that is, ``theta`` as the azimuthal angle + and ``phi`` as the polar angle. + + Note that SciPy's spherical harmonics include the Condon-Shortley + phase [2]_ because it is part of `sph_legendre_p`. + + With SciPy's conventions, the first several spherical harmonics + are + + .. math:: + + Y_0^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{1}{\pi}} \\ + Y_1^{-1}(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{2\pi}} + e^{-i\phi} \sin(\theta) \\ + Y_1^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{\pi}} + \cos(\theta) \\ + Y_1^1(\theta, \phi) &= -\frac{1}{2} \sqrt{\frac{3}{2\pi}} + e^{i\phi} \sin(\theta). + + References + ---------- + .. [1] Digital Library of Mathematical Functions, 14.30. + https://dlmf.nist.gov/14.30 + .. [2] https://en.wikipedia.org/wiki/Spherical_harmonics#Condon.E2.80.93Shortley_phase + """, force_complex_output=True, diff_n=0 +) + + +@sph_harm_y._override_key +def _(diff_n): + diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False) + if not 0 <= diff_n <= 2: + raise ValueError( + "diff_n is currently only implemented for orders 0, 1, and 2," + f" received: {diff_n}." + ) + return diff_n + + +@sph_harm_y._override_finalize_out +def _(out): + if (out.shape[-1] == 1): + return out[..., 0, 0] + + if (out.shape[-1] == 2): + return out[..., 0, 0], out[..., [1, 0], [0, 1]] + + if (out.shape[-1] == 3): + return (out[..., 0, 0], out[..., [1, 0], [0, 1]], + out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]]) + + +sph_harm_y_all = MultiUFunc( + sph_harm_y_all, + """sph_harm_y_all(n, m, theta, phi, *, diff_n=0) + + All spherical harmonics up to the specified degree ``n`` and order ``m``. + + Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)`` + corresponds to degree ``j`` and order ``i`` for all ``0 <= j <= n`` + and ``-m <= i <= m``. + + See Also + -------- + sph_harm_y + """, force_complex_output=True, diff_n=0 +) + + +@sph_harm_y_all._override_key +def _(diff_n): + diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False) + if not 0 <= diff_n <= 2: + raise ValueError( + "diff_n is currently only implemented for orders 2," + f" received: {diff_n}." + ) + return diff_n + + +@sph_harm_y_all._override_ufunc_default_kwargs +def _(diff_n): + return {'axes': [(), ()] + [(0, 1, -2, -1)]} + + +@sph_harm_y_all._override_resolve_out_shapes +def _(n, m, theta_shape, phi_shape, nout, **kwargs): + diff_n = kwargs['diff_n'] + + if not isinstance(n, numbers.Integral) or (n < 0): + raise ValueError("n must be a non-negative integer.") + + return ((n + 1, 2 * abs(m) + 1) + np.broadcast_shapes(theta_shape, phi_shape) + + (diff_n + 1, diff_n + 1),) + + +@sph_harm_y_all._override_finalize_out +def _(out): + if (out.shape[-1] == 1): + return out[..., 0, 0] + + if (out.shape[-1] == 2): + return out[..., 0, 0], out[..., [1, 0], [0, 1]] + + if (out.shape[-1] == 3): + return (out[..., 0, 0], out[..., [1, 0], [0, 1]], + out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py new file mode 100644 index 0000000000000000000000000000000000000000..e021f5a899b2b9218d59527fd91fb6cf7a545042 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py @@ -0,0 +1,2592 @@ +""" +A collection of functions to find the weights and abscissas for +Gaussian Quadrature. + +These calculations are done by finding the eigenvalues of a +tridiagonal matrix whose entries are dependent on the coefficients +in the recursion formula for the orthogonal polynomials with the +corresponding weighting function over the interval. + +Many recursion relations for orthogonal polynomials are given: + +.. math:: + + a1n f_{n+1} (x) = (a2n + a3n x ) f_n (x) - a4n f_{n-1} (x) + +The recursion relation of interest is + +.. math:: + + P_{n+1} (x) = (x - A_n) P_n (x) - B_n P_{n-1} (x) + +where :math:`P` has a different normalization than :math:`f`. + +The coefficients can be found as: + +.. math:: + + A_n = -a2n / a3n + \\qquad + B_n = ( a4n / a3n \\sqrt{h_n-1 / h_n})^2 + +where + +.. math:: + + h_n = \\int_a^b w(x) f_n(x)^2 + +assume: + +.. math:: + + P_0 (x) = 1 + \\qquad + P_{-1} (x) == 0 + +For the mathematical background, see [golub.welsch-1969-mathcomp]_ and +[abramowitz.stegun-1965]_. + +References +---------- +.. [golub.welsch-1969-mathcomp] + Golub, Gene H, and John H Welsch. 1969. Calculation of Gauss + Quadrature Rules. *Mathematics of Computation* 23, 221-230+s1--s10. + +.. [abramowitz.stegun-1965] + Abramowitz, Milton, and Irene A Stegun. (1965) *Handbook of + Mathematical Functions: with Formulas, Graphs, and Mathematical + Tables*. Gaithersburg, MD: National Bureau of Standards. + http://www.math.sfu.ca/~cbm/aands/ + +.. [townsend.trogdon.olver-2014] + Townsend, A. and Trogdon, T. and Olver, S. (2014) + *Fast computation of Gauss quadrature nodes and + weights on the whole real line*. :arXiv:`1410.5286`. + +.. [townsend.trogdon.olver-2015] + Townsend, A. and Trogdon, T. and Olver, S. (2015) + *Fast computation of Gauss quadrature nodes and + weights on the whole real line*. + IMA Journal of Numerical Analysis + :doi:`10.1093/imanum/drv002`. +""" +# +# Author: Travis Oliphant 2000 +# Updated Sep. 2003 (fixed bugs --- tested to be accurate) + +# SciPy imports. +import numpy as np +from numpy import (exp, inf, pi, sqrt, floor, sin, cos, around, + hstack, arccos, arange) +from scipy import linalg +from scipy.special import airy + +# Local imports. +# There is no .pyi file for _specfun +from . import _specfun # type: ignore +from . import _ufuncs +_gam = _ufuncs.gamma + +_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys', + 'jacobi', 'laguerre', 'genlaguerre', 'hermite', + 'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt', + 'sh_chebyu', 'sh_jacobi'] + +# Correspondence between new and old names of root functions +_rootfuns_map = {'roots_legendre': 'p_roots', + 'roots_chebyt': 't_roots', + 'roots_chebyu': 'u_roots', + 'roots_chebyc': 'c_roots', + 'roots_chebys': 's_roots', + 'roots_jacobi': 'j_roots', + 'roots_laguerre': 'l_roots', + 'roots_genlaguerre': 'la_roots', + 'roots_hermite': 'h_roots', + 'roots_hermitenorm': 'he_roots', + 'roots_gegenbauer': 'cg_roots', + 'roots_sh_legendre': 'ps_roots', + 'roots_sh_chebyt': 'ts_roots', + 'roots_sh_chebyu': 'us_roots', + 'roots_sh_jacobi': 'js_roots'} + +__all__ = _polyfuns + list(_rootfuns_map.keys()) + + +class orthopoly1d(np.poly1d): + + def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None, + limits=None, monic=False, eval_func=None): + equiv_weights = [weights[k] / wfunc(roots[k]) for + k in range(len(roots))] + mu = sqrt(hn) + if monic: + evf = eval_func + if evf: + knn = kn + def eval_func(x): + return evf(x) / knn + mu = mu / abs(kn) + kn = 1.0 + + # compute coefficients from roots, then scale + poly = np.poly1d(roots, r=True) + np.poly1d.__init__(self, poly.coeffs * float(kn)) + + self.weights = np.array(list(zip(roots, weights, equiv_weights))) + self.weight_func = wfunc + self.limits = limits + self.normcoef = mu + + # Note: eval_func will be discarded on arithmetic + self._eval_func = eval_func + + def __call__(self, v): + if self._eval_func and not isinstance(v, np.poly1d): + return self._eval_func(v) + else: + return np.poly1d.__call__(self, v) + + def _scale(self, p): + if p == 1.0: + return + self._coeffs *= p + + evf = self._eval_func + if evf: + self._eval_func = lambda x: evf(x) * p + self.normcoef *= p + + +def _gen_roots_and_weights(n, mu0, an_func, bn_func, f, df, symmetrize, mu): + """[x,w] = gen_roots_and_weights(n,an_func,sqrt_bn_func,mu) + + Returns the roots (x) of an nth order orthogonal polynomial, + and weights (w) to use in appropriate Gaussian quadrature with that + orthogonal polynomial. + + The polynomials have the recurrence relation + P_n+1(x) = (x - A_n) P_n(x) - B_n P_n-1(x) + + an_func(n) should return A_n + sqrt_bn_func(n) should return sqrt(B_n) + mu ( = h_0 ) is the integral of the weight over the orthogonal + interval + """ + k = np.arange(n, dtype='d') + c = np.zeros((2, n)) + c[0,1:] = bn_func(k[1:]) + c[1,:] = an_func(k) + x = linalg.eigvals_banded(c, overwrite_a_band=True) + + # improve roots by one application of Newton's method + y = f(n, x) + dy = df(n, x) + x -= y/dy + + # fm and dy may contain very large/small values, so we + # log-normalize them to maintain precision in the product fm*dy + fm = f(n-1, x) + log_fm = np.log(np.abs(fm)) + log_dy = np.log(np.abs(dy)) + fm /= np.exp((log_fm.max() + log_fm.min()) / 2.) + dy /= np.exp((log_dy.max() + log_dy.min()) / 2.) + w = 1.0 / (fm * dy) + + if symmetrize: + w = (w + w[::-1]) / 2 + x = (x - x[::-1]) / 2 + + w *= mu0 / w.sum() + + if mu: + return x, w, mu0 + else: + return x, w + +# Jacobi Polynomials 1 P^(alpha,beta)_n(x) + + +def roots_jacobi(n, alpha, beta, mu=False): + r"""Gauss-Jacobi quadrature. + + Compute the sample points and weights for Gauss-Jacobi + quadrature. The sample points are the roots of the nth degree + Jacobi polynomial, :math:`P^{\alpha, \beta}_n(x)`. These sample + points and weights correctly integrate polynomials of degree + :math:`2n - 1` or less over the interval :math:`[-1, 1]` with + weight function :math:`w(x) = (1 - x)^{\alpha} (1 + + x)^{\beta}`. See 22.2.1 in [AS]_ for details. + + Parameters + ---------- + n : int + quadrature order + alpha : float + alpha must be > -1 + beta : float + beta must be > -1 + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError("n must be a positive integer.") + if alpha <= -1 or beta <= -1: + raise ValueError("alpha and beta must be greater than -1.") + + if alpha == 0.0 and beta == 0.0: + return roots_legendre(m, mu) + if alpha == beta: + return roots_gegenbauer(m, alpha+0.5, mu) + + if (alpha + beta) <= 1000: + mu0 = 2.0**(alpha+beta+1) * _ufuncs.beta(alpha+1, beta+1) + else: + # Avoid overflows in pow and beta for very large parameters + mu0 = np.exp((alpha + beta + 1) * np.log(2.0) + + _ufuncs.betaln(alpha+1, beta+1)) + a = alpha + b = beta + if a + b == 0.0: + def an_func(k): + return np.where(k == 0, (b - a) / (2 + a + b), 0.0) + else: + def an_func(k): + return np.where( + k == 0, + (b - a) / (2 + a + b), + (b * b - a * a) / ((2.0 * k + a + b) * (2.0 * k + a + b + 2)) + ) + + def bn_func(k): + return ( + 2.0 / (2.0 * k + a + b) + * np.sqrt((k + a) * (k + b) / (2 * k + a + b + 1)) + * np.where(k == 1, 1.0, np.sqrt(k * (k + a + b) / (2.0 * k + a + b - 1))) + ) + + def f(n, x): + return _ufuncs.eval_jacobi(n, a, b, x) + def df(n, x): + return 0.5 * (n + a + b + 1) * _ufuncs.eval_jacobi(n - 1, a + 1, b + 1, x) + return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu) + + +def jacobi(n, alpha, beta, monic=False): + r"""Jacobi polynomial. + + Defined to be the solution of + + .. math:: + (1 - x^2)\frac{d^2}{dx^2}P_n^{(\alpha, \beta)} + + (\beta - \alpha - (\alpha + \beta + 2)x) + \frac{d}{dx}P_n^{(\alpha, \beta)} + + n(n + \alpha + \beta + 1)P_n^{(\alpha, \beta)} = 0 + + for :math:`\alpha, \beta > -1`; :math:`P_n^{(\alpha, \beta)}` is a + polynomial of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + alpha : float + Parameter, must be greater than -1. + beta : float + Parameter, must be greater than -1. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + P : orthopoly1d + Jacobi polynomial. + + Notes + ----- + For fixed :math:`\alpha, \beta`, the polynomials + :math:`P_n^{(\alpha, \beta)}` are orthogonal over :math:`[-1, 1]` + with weight function :math:`(1 - x)^\alpha(1 + x)^\beta`. + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + The Jacobi polynomials satisfy the recurrence relation: + + .. math:: + P_n^{(\alpha, \beta-1)}(x) - P_n^{(\alpha-1, \beta)}(x) + = P_{n-1}^{(\alpha, \beta)}(x) + + This can be verified, for example, for :math:`\alpha = \beta = 2` + and :math:`n = 1` over the interval :math:`[-1, 1]`: + + >>> import numpy as np + >>> from scipy.special import jacobi + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> np.allclose(jacobi(0, 2, 2)(x), + ... jacobi(1, 2, 1)(x) - jacobi(1, 1, 2)(x)) + True + + Plot of the Jacobi polynomial :math:`P_5^{(\alpha, -0.5)}` for + different values of :math:`\alpha`: + + >>> import matplotlib.pyplot as plt + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-2.0, 2.0) + >>> ax.set_title(r'Jacobi polynomials $P_5^{(\alpha, -0.5)}$') + >>> for alpha in np.arange(0, 4, 1): + ... ax.plot(x, jacobi(5, alpha, -0.5)(x), label=rf'$\alpha={alpha}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + def wfunc(x): + return (1 - x) ** alpha * (1 + x) ** beta + if n == 0: + return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic, + eval_func=np.ones_like) + x, w, mu = roots_jacobi(n, alpha, beta, mu=True) + ab1 = alpha + beta + 1.0 + hn = 2**ab1 / (2 * n + ab1) * _gam(n + alpha + 1) + hn *= _gam(n + beta + 1.0) / _gam(n + 1) / _gam(n + ab1) + kn = _gam(2 * n + ab1) / 2.0**n / _gam(n + 1) / _gam(n + ab1) + # here kn = coefficient on x^n term + p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic, + lambda x: _ufuncs.eval_jacobi(n, alpha, beta, x)) + return p + +# Jacobi Polynomials shifted G_n(p,q,x) + + +def roots_sh_jacobi(n, p1, q1, mu=False): + """Gauss-Jacobi (shifted) quadrature. + + Compute the sample points and weights for Gauss-Jacobi (shifted) + quadrature. The sample points are the roots of the nth degree + shifted Jacobi polynomial, :math:`G^{p,q}_n(x)`. These sample + points and weights correctly integrate polynomials of degree + :math:`2n - 1` or less over the interval :math:`[0, 1]` with + weight function :math:`w(x) = (1 - x)^{p-q} x^{q-1}`. See 22.2.2 + in [AS]_ for details. + + Parameters + ---------- + n : int + quadrature order + p1 : float + (p1 - q1) must be > -1 + q1 : float + q1 must be > 0 + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + if (p1-q1) <= -1 or q1 <= 0: + message = "(p - q) must be greater than -1, and q must be greater than 0." + raise ValueError(message) + x, w, m = roots_jacobi(n, p1-q1, q1-1, True) + x = (x + 1) / 2 + scale = 2.0**p1 + w /= scale + m /= scale + if mu: + return x, w, m + else: + return x, w + + +def sh_jacobi(n, p, q, monic=False): + r"""Shifted Jacobi polynomial. + + Defined by + + .. math:: + + G_n^{(p, q)}(x) + = \binom{2n + p - 1}{n}^{-1}P_n^{(p - q, q - 1)}(2x - 1), + + where :math:`P_n^{(\cdot, \cdot)}` is the nth Jacobi polynomial. + + Parameters + ---------- + n : int + Degree of the polynomial. + p : float + Parameter, must have :math:`p > q - 1`. + q : float + Parameter, must be greater than 0. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + G : orthopoly1d + Shifted Jacobi polynomial. + + Notes + ----- + For fixed :math:`p, q`, the polynomials :math:`G_n^{(p, q)}` are + orthogonal over :math:`[0, 1]` with weight function :math:`(1 - + x)^{p - q}x^{q - 1}`. + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + def wfunc(x): + return (1.0 - x) ** (p - q) * x ** (q - 1.0) + if n == 0: + return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic, + eval_func=np.ones_like) + n1 = n + x, w = roots_sh_jacobi(n1, p, q) + hn = _gam(n + 1) * _gam(n + q) * _gam(n + p) * _gam(n + p - q + 1) + hn /= (2 * n + p) * (_gam(2 * n + p)**2) + # kn = 1.0 in standard form so monic is redundant. Kept for compatibility. + kn = 1.0 + pp = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(0, 1), monic=monic, + eval_func=lambda x: _ufuncs.eval_sh_jacobi(n, p, q, x)) + return pp + +# Generalized Laguerre L^(alpha)_n(x) + + +def roots_genlaguerre(n, alpha, mu=False): + r"""Gauss-generalized Laguerre quadrature. + + Compute the sample points and weights for Gauss-generalized + Laguerre quadrature. The sample points are the roots of the nth + degree generalized Laguerre polynomial, :math:`L^{\alpha}_n(x)`. + These sample points and weights correctly integrate polynomials of + degree :math:`2n - 1` or less over the interval :math:`[0, + \infty]` with weight function :math:`w(x) = x^{\alpha} + e^{-x}`. See 22.3.9 in [AS]_ for details. + + Parameters + ---------- + n : int + quadrature order + alpha : float + alpha must be > -1 + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError("n must be a positive integer.") + if alpha < -1: + raise ValueError("alpha must be greater than -1.") + + mu0 = _ufuncs.gamma(alpha + 1) + + if m == 1: + x = np.array([alpha+1.0], 'd') + w = np.array([mu0], 'd') + if mu: + return x, w, mu0 + else: + return x, w + + def an_func(k): + return 2 * k + alpha + 1 + def bn_func(k): + return -np.sqrt(k * (k + alpha)) + def f(n, x): + return _ufuncs.eval_genlaguerre(n, alpha, x) + def df(n, x): + return (n * _ufuncs.eval_genlaguerre(n, alpha, x) + - (n + alpha) * _ufuncs.eval_genlaguerre(n - 1, alpha, x)) / x + return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu) + + +def genlaguerre(n, alpha, monic=False): + r"""Generalized (associated) Laguerre polynomial. + + Defined to be the solution of + + .. math:: + x\frac{d^2}{dx^2}L_n^{(\alpha)} + + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)} + + nL_n^{(\alpha)} = 0, + + where :math:`\alpha > -1`; :math:`L_n^{(\alpha)}` is a polynomial + of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + alpha : float + Parameter, must be greater than -1. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + L : orthopoly1d + Generalized Laguerre polynomial. + + See Also + -------- + laguerre : Laguerre polynomial. + hyp1f1 : confluent hypergeometric function + + Notes + ----- + For fixed :math:`\alpha`, the polynomials :math:`L_n^{(\alpha)}` + are orthogonal over :math:`[0, \infty)` with weight function + :math:`e^{-x}x^\alpha`. + + The Laguerre polynomials are the special case where :math:`\alpha + = 0`. + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + The generalized Laguerre polynomials are closely related to the confluent + hypergeometric function :math:`{}_1F_1`: + + .. math:: + L_n^{(\alpha)} = \binom{n + \alpha}{n} {}_1F_1(-n, \alpha +1, x) + + This can be verified, for example, for :math:`n = \alpha = 3` over the + interval :math:`[-1, 1]`: + + >>> import numpy as np + >>> from scipy.special import binom + >>> from scipy.special import genlaguerre + >>> from scipy.special import hyp1f1 + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> np.allclose(genlaguerre(3, 3)(x), binom(6, 3) * hyp1f1(-3, 4, x)) + True + + This is the plot of the generalized Laguerre polynomials + :math:`L_3^{(\alpha)}` for some values of :math:`\alpha`: + + >>> import matplotlib.pyplot as plt + >>> x = np.arange(-4.0, 12.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-5.0, 10.0) + >>> ax.set_title(r'Generalized Laguerre polynomials $L_3^{\alpha}$') + >>> for alpha in np.arange(0, 5): + ... ax.plot(x, genlaguerre(3, alpha)(x), label=rf'$L_3^{(alpha)}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + if alpha <= -1: + raise ValueError("alpha must be > -1") + if n < 0: + raise ValueError("n must be nonnegative.") + + if n == 0: + n1 = n + 1 + else: + n1 = n + x, w = roots_genlaguerre(n1, alpha) + def wfunc(x): + return exp(-x) * x ** alpha + if n == 0: + x, w = [], [] + hn = _gam(n + alpha + 1) / _gam(n + 1) + kn = (-1)**n / _gam(n + 1) + p = orthopoly1d(x, w, hn, kn, wfunc, (0, inf), monic, + lambda x: _ufuncs.eval_genlaguerre(n, alpha, x)) + return p + +# Laguerre L_n(x) + + +def roots_laguerre(n, mu=False): + r"""Gauss-Laguerre quadrature. + + Compute the sample points and weights for Gauss-Laguerre + quadrature. The sample points are the roots of the nth degree + Laguerre polynomial, :math:`L_n(x)`. These sample points and + weights correctly integrate polynomials of degree :math:`2n - 1` + or less over the interval :math:`[0, \infty]` with weight function + :math:`w(x) = e^{-x}`. See 22.2.13 in [AS]_ for details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + numpy.polynomial.laguerre.laggauss + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + return roots_genlaguerre(n, 0.0, mu=mu) + + +def laguerre(n, monic=False): + r"""Laguerre polynomial. + + Defined to be the solution of + + .. math:: + x\frac{d^2}{dx^2}L_n + (1 - x)\frac{d}{dx}L_n + nL_n = 0; + + :math:`L_n` is a polynomial of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + L : orthopoly1d + Laguerre Polynomial. + + See Also + -------- + genlaguerre : Generalized (associated) Laguerre polynomial. + + Notes + ----- + The polynomials :math:`L_n` are orthogonal over :math:`[0, + \infty)` with weight function :math:`e^{-x}`. + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + The Laguerre polynomials :math:`L_n` are the special case + :math:`\alpha = 0` of the generalized Laguerre polynomials + :math:`L_n^{(\alpha)}`. + Let's verify it on the interval :math:`[-1, 1]`: + + >>> import numpy as np + >>> from scipy.special import genlaguerre + >>> from scipy.special import laguerre + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> np.allclose(genlaguerre(3, 0)(x), laguerre(3)(x)) + True + + The polynomials :math:`L_n` also satisfy the recurrence relation: + + .. math:: + (n + 1)L_{n+1}(x) = (2n +1 -x)L_n(x) - nL_{n-1}(x) + + This can be easily checked on :math:`[0, 1]` for :math:`n = 3`: + + >>> x = np.arange(0.0, 1.0, 0.01) + >>> np.allclose(4 * laguerre(4)(x), + ... (7 - x) * laguerre(3)(x) - 3 * laguerre(2)(x)) + True + + This is the plot of the first few Laguerre polynomials :math:`L_n`: + + >>> import matplotlib.pyplot as plt + >>> x = np.arange(-1.0, 5.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-5.0, 5.0) + >>> ax.set_title(r'Laguerre polynomials $L_n$') + >>> for n in np.arange(0, 5): + ... ax.plot(x, laguerre(n)(x), label=rf'$L_{n}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + if n == 0: + n1 = n + 1 + else: + n1 = n + x, w = roots_laguerre(n1) + if n == 0: + x, w = [], [] + hn = 1.0 + kn = (-1)**n / _gam(n + 1) + p = orthopoly1d(x, w, hn, kn, lambda x: exp(-x), (0, inf), monic, + lambda x: _ufuncs.eval_laguerre(n, x)) + return p + +# Hermite 1 H_n(x) + + +def roots_hermite(n, mu=False): + r"""Gauss-Hermite (physicist's) quadrature. + + Compute the sample points and weights for Gauss-Hermite + quadrature. The sample points are the roots of the nth degree + Hermite polynomial, :math:`H_n(x)`. These sample points and + weights correctly integrate polynomials of degree :math:`2n - 1` + or less over the interval :math:`[-\infty, \infty]` with weight + function :math:`w(x) = e^{-x^2}`. See 22.2.14 in [AS]_ for + details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + numpy.polynomial.hermite.hermgauss + roots_hermitenorm + + Notes + ----- + For small n up to 150 a modified version of the Golub-Welsch + algorithm is used. Nodes are computed from the eigenvalue + problem and improved by one step of a Newton iteration. + The weights are computed from the well-known analytical formula. + + For n larger than 150 an optimal asymptotic algorithm is applied + which computes nodes and weights in a numerically stable manner. + The algorithm has linear runtime making computation for very + large n (several thousand or more) feasible. + + References + ---------- + .. [townsend.trogdon.olver-2014] + Townsend, A. and Trogdon, T. and Olver, S. (2014) + *Fast computation of Gauss quadrature nodes and + weights on the whole real line*. :arXiv:`1410.5286`. + .. [townsend.trogdon.olver-2015] + Townsend, A. and Trogdon, T. and Olver, S. (2015) + *Fast computation of Gauss quadrature nodes and + weights on the whole real line*. + IMA Journal of Numerical Analysis + :doi:`10.1093/imanum/drv002`. + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError("n must be a positive integer.") + + mu0 = np.sqrt(np.pi) + if n <= 150: + def an_func(k): + return 0.0 * k + def bn_func(k): + return np.sqrt(k / 2.0) + f = _ufuncs.eval_hermite + def df(n, x): + return 2.0 * n * _ufuncs.eval_hermite(n - 1, x) + return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu) + else: + nodes, weights = _roots_hermite_asy(m) + if mu: + return nodes, weights, mu0 + else: + return nodes, weights + + +def _compute_tauk(n, k, maxit=5): + """Helper function for Tricomi initial guesses + + For details, see formula 3.1 in lemma 3.1 in the + original paper. + + Parameters + ---------- + n : int + Quadrature order + k : ndarray of type int + Index of roots :math:`\tau_k` to compute + maxit : int + Number of Newton maxit performed, the default + value of 5 is sufficient. + + Returns + ------- + tauk : ndarray + Roots of equation 3.1 + + See Also + -------- + initial_nodes_a + roots_hermite_asy + """ + a = n % 2 - 0.5 + c = (4.0*floor(n/2.0) - 4.0*k + 3.0)*pi / (4.0*floor(n/2.0) + 2.0*a + 2.0) + def f(x): + return x - sin(x) - c + def df(x): + return 1.0 - cos(x) + xi = 0.5*pi + for i in range(maxit): + xi = xi - f(xi)/df(xi) + return xi + + +def _initial_nodes_a(n, k): + r"""Tricomi initial guesses + + Computes an initial approximation to the square of the `k`-th + (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n` + of order :math:`n`. The formula is the one from lemma 3.1 in the + original paper. The guesses are accurate except in the region + near :math:`\sqrt{2n + 1}`. + + Parameters + ---------- + n : int + Quadrature order + k : ndarray of type int + Index of roots to compute + + Returns + ------- + xksq : ndarray + Square of the approximate roots + + See Also + -------- + initial_nodes + roots_hermite_asy + """ + tauk = _compute_tauk(n, k) + sigk = cos(0.5*tauk)**2 + a = n % 2 - 0.5 + nu = 4.0*floor(n/2.0) + 2.0*a + 2.0 + # Initial approximation of Hermite roots (square) + xksq = nu*sigk - 1.0/(3.0*nu) * (5.0/(4.0*(1.0-sigk)**2) - 1.0/(1.0-sigk) - 0.25) + return xksq + + +def _initial_nodes_b(n, k): + r"""Gatteschi initial guesses + + Computes an initial approximation to the square of the kth + (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n` + of order :math:`n`. The formula is the one from lemma 3.2 in the + original paper. The guesses are accurate in the region just + below :math:`\sqrt{2n + 1}`. + + Parameters + ---------- + n : int + Quadrature order + k : ndarray of type int + Index of roots to compute + + Returns + ------- + xksq : ndarray + Square of the approximate root + + See Also + -------- + initial_nodes + roots_hermite_asy + """ + a = n % 2 - 0.5 + nu = 4.0*floor(n/2.0) + 2.0*a + 2.0 + # Airy roots by approximation + ak = _specfun.airyzo(k.max(), 1)[0][::-1] + # Initial approximation of Hermite roots (square) + xksq = (nu + + 2.0**(2.0/3.0) * ak * nu**(1.0/3.0) + + 1.0/5.0 * 2.0**(4.0/3.0) * ak**2 * nu**(-1.0/3.0) + + (9.0/140.0 - 12.0/175.0 * ak**3) * nu**(-1.0) + + (16.0/1575.0 * ak + 92.0/7875.0 * ak**4) * 2.0**(2.0/3.0) * nu**(-5.0/3.0) + - (15152.0/3031875.0 * ak**5 + 1088.0/121275.0 * ak**2) + * 2.0**(1.0/3.0) * nu**(-7.0/3.0)) + return xksq + + +def _initial_nodes(n): + """Initial guesses for the Hermite roots + + Computes an initial approximation to the non-negative + roots :math:`x_k` of the Hermite polynomial :math:`H_n` + of order :math:`n`. The Tricomi and Gatteschi initial + guesses are used in the region where they are accurate. + + Parameters + ---------- + n : int + Quadrature order + + Returns + ------- + xk : ndarray + Approximate roots + + See Also + -------- + roots_hermite_asy + """ + # Turnover point + # linear polynomial fit to error of 10, 25, 40, ..., 1000 point rules + fit = 0.49082003*n - 4.37859653 + turnover = around(fit).astype(int) + # Compute all approximations + ia = arange(1, int(floor(n*0.5)+1)) + ib = ia[::-1] + xasq = _initial_nodes_a(n, ia[:turnover+1]) + xbsq = _initial_nodes_b(n, ib[turnover+1:]) + # Combine + iv = sqrt(hstack([xasq, xbsq])) + # Central node is always zero + if n % 2 == 1: + iv = hstack([0.0, iv]) + return iv + + +def _pbcf(n, theta): + r"""Asymptotic series expansion of parabolic cylinder function + + The implementation is based on sections 3.2 and 3.3 from the + original paper. Compared to the published version this code + adds one more term to the asymptotic series. The detailed + formulas can be found at [parabolic-asymptotics]_. The evaluation + is done in a transformed variable :math:`\theta := \arccos(t)` + where :math:`t := x / \mu` and :math:`\mu := \sqrt{2n + 1}`. + + Parameters + ---------- + n : int + Quadrature order + theta : ndarray + Transformed position variable + + Returns + ------- + U : ndarray + Value of the parabolic cylinder function :math:`U(a, \theta)`. + Ud : ndarray + Value of the derivative :math:`U^{\prime}(a, \theta)` of + the parabolic cylinder function. + + See Also + -------- + roots_hermite_asy + + References + ---------- + .. [parabolic-asymptotics] + https://dlmf.nist.gov/12.10#vii + """ + st = sin(theta) + ct = cos(theta) + # https://dlmf.nist.gov/12.10#vii + mu = 2.0*n + 1.0 + # https://dlmf.nist.gov/12.10#E23 + eta = 0.5*theta - 0.5*st*ct + # https://dlmf.nist.gov/12.10#E39 + zeta = -(3.0*eta/2.0) ** (2.0/3.0) + # https://dlmf.nist.gov/12.10#E40 + phi = (-zeta / st**2) ** (0.25) + # Coefficients + # https://dlmf.nist.gov/12.10#E43 + a0 = 1.0 + a1 = 0.10416666666666666667 + a2 = 0.08355034722222222222 + a3 = 0.12822657455632716049 + a4 = 0.29184902646414046425 + a5 = 0.88162726744375765242 + b0 = 1.0 + b1 = -0.14583333333333333333 + b2 = -0.09874131944444444444 + b3 = -0.14331205391589506173 + b4 = -0.31722720267841354810 + b5 = -0.94242914795712024914 + # Polynomials + # https://dlmf.nist.gov/12.10#E9 + # https://dlmf.nist.gov/12.10#E10 + ctp = ct ** arange(16).reshape((-1,1)) + u0 = 1.0 + u1 = (1.0*ctp[3,:] - 6.0*ct) / 24.0 + u2 = (-9.0*ctp[4,:] + 249.0*ctp[2,:] + 145.0) / 1152.0 + u3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 28287.0*ctp[5,:] + - 151995.0*ctp[3,:] - 259290.0*ct) / 414720.0 + u4 = (72756.0*ctp[10,:] - 321339.0*ctp[8,:] - 154982.0*ctp[6,:] + + 50938215.0*ctp[4,:] + 122602962.0*ctp[2,:] + 12773113.0) / 39813120.0 + u5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 1994971575.0*ctp[11,:] + - 3630137104.0*ctp[9,:] + 4433574213.0*ctp[7,:] - 37370295816.0*ctp[5,:] + - 119582875013.0*ctp[3,:] - 34009066266.0*ct) / 6688604160.0 + v0 = 1.0 + v1 = (1.0*ctp[3,:] + 6.0*ct) / 24.0 + v2 = (15.0*ctp[4,:] - 327.0*ctp[2,:] - 143.0) / 1152.0 + v3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 36387.0*ctp[5,:] + + 238425.0*ctp[3,:] + 259290.0*ct) / 414720.0 + v4 = (-121260.0*ctp[10,:] + 551733.0*ctp[8,:] - 151958.0*ctp[6,:] + - 57484425.0*ctp[4,:] - 132752238.0*ctp[2,:] - 12118727) / 39813120.0 + v5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 2025529095.0*ctp[11,:] + - 3750839308.0*ctp[9,:] + 3832454253.0*ctp[7,:] + 35213253348.0*ctp[5,:] + + 130919230435.0*ctp[3,:] + 34009066266*ct) / 6688604160.0 + # Airy Evaluation (Bi and Bip unused) + Ai, Aip, Bi, Bip = airy(mu**(4.0/6.0) * zeta) + # Prefactor for U + P = 2.0*sqrt(pi) * mu**(1.0/6.0) * phi + # Terms for U + # https://dlmf.nist.gov/12.10#E42 + phip = phi ** arange(6, 31, 6).reshape((-1,1)) + A0 = b0*u0 + A1 = (b2*u0 + phip[0,:]*b1*u1 + phip[1,:]*b0*u2) / zeta**3 + A2 = (b4*u0 + phip[0,:]*b3*u1 + phip[1,:]*b2*u2 + phip[2,:]*b1*u3 + + phip[3,:]*b0*u4) / zeta**6 + B0 = -(a1*u0 + phip[0,:]*a0*u1) / zeta**2 + B1 = -(a3*u0 + phip[0,:]*a2*u1 + phip[1,:]*a1*u2 + phip[2,:]*a0*u3) / zeta**5 + B2 = -(a5*u0 + phip[0,:]*a4*u1 + phip[1,:]*a3*u2 + phip[2,:]*a2*u3 + + phip[3,:]*a1*u4 + phip[4,:]*a0*u5) / zeta**8 + # U + # https://dlmf.nist.gov/12.10#E35 + U = P * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) + + Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0)) + # Prefactor for derivative of U + Pd = sqrt(2.0*pi) * mu**(2.0/6.0) / phi + # Terms for derivative of U + # https://dlmf.nist.gov/12.10#E46 + C0 = -(b1*v0 + phip[0,:]*b0*v1) / zeta + C1 = -(b3*v0 + phip[0,:]*b2*v1 + phip[1,:]*b1*v2 + phip[2,:]*b0*v3) / zeta**4 + C2 = -(b5*v0 + phip[0,:]*b4*v1 + phip[1,:]*b3*v2 + phip[2,:]*b2*v3 + + phip[3,:]*b1*v4 + phip[4,:]*b0*v5) / zeta**7 + D0 = a0*v0 + D1 = (a2*v0 + phip[0,:]*a1*v1 + phip[1,:]*a0*v2) / zeta**3 + D2 = (a4*v0 + phip[0,:]*a3*v1 + phip[1,:]*a2*v2 + phip[2,:]*a1*v3 + + phip[3,:]*a0*v4) / zeta**6 + # Derivative of U + # https://dlmf.nist.gov/12.10#E36 + Ud = Pd * (Ai * (C0 + C1/mu**2.0 + C2/mu**4.0) / mu**(4.0/6.0) + + Aip * (D0 + D1/mu**2.0 + D2/mu**4.0)) + return U, Ud + + +def _newton(n, x_initial, maxit=5): + """Newton iteration for polishing the asymptotic approximation + to the zeros of the Hermite polynomials. + + Parameters + ---------- + n : int + Quadrature order + x_initial : ndarray + Initial guesses for the roots + maxit : int + Maximal number of Newton iterations. + The default 5 is sufficient, usually + only one or two steps are needed. + + Returns + ------- + nodes : ndarray + Quadrature nodes + weights : ndarray + Quadrature weights + + See Also + -------- + roots_hermite_asy + """ + # Variable transformation + mu = sqrt(2.0*n + 1.0) + t = x_initial / mu + theta = arccos(t) + # Newton iteration + for i in range(maxit): + u, ud = _pbcf(n, theta) + dtheta = u / (sqrt(2.0) * mu * sin(theta) * ud) + theta = theta + dtheta + if max(abs(dtheta)) < 1e-14: + break + # Undo variable transformation + x = mu * cos(theta) + # Central node is always zero + if n % 2 == 1: + x[0] = 0.0 + # Compute weights + w = exp(-x**2) / (2.0*ud**2) + return x, w + + +def _roots_hermite_asy(n): + r"""Gauss-Hermite (physicist's) quadrature for large n. + + Computes the sample points and weights for Gauss-Hermite quadrature. + The sample points are the roots of the nth degree Hermite polynomial, + :math:`H_n(x)`. These sample points and weights correctly integrate + polynomials of degree :math:`2n - 1` or less over the interval + :math:`[-\infty, \infty]` with weight function :math:`f(x) = e^{-x^2}`. + + This method relies on asymptotic expansions which work best for n > 150. + The algorithm has linear runtime making computation for very large n + feasible. + + Parameters + ---------- + n : int + quadrature order + + Returns + ------- + nodes : ndarray + Quadrature nodes + weights : ndarray + Quadrature weights + + See Also + -------- + roots_hermite + + References + ---------- + .. [townsend.trogdon.olver-2014] + Townsend, A. and Trogdon, T. and Olver, S. (2014) + *Fast computation of Gauss quadrature nodes and + weights on the whole real line*. :arXiv:`1410.5286`. + + .. [townsend.trogdon.olver-2015] + Townsend, A. and Trogdon, T. and Olver, S. (2015) + *Fast computation of Gauss quadrature nodes and + weights on the whole real line*. + IMA Journal of Numerical Analysis + :doi:`10.1093/imanum/drv002`. + """ + iv = _initial_nodes(n) + nodes, weights = _newton(n, iv) + # Combine with negative parts + if n % 2 == 0: + nodes = hstack([-nodes[::-1], nodes]) + weights = hstack([weights[::-1], weights]) + else: + nodes = hstack([-nodes[-1:0:-1], nodes]) + weights = hstack([weights[-1:0:-1], weights]) + # Scale weights + weights *= sqrt(pi) / sum(weights) + return nodes, weights + + +def hermite(n, monic=False): + r"""Physicist's Hermite polynomial. + + Defined by + + .. math:: + + H_n(x) = (-1)^ne^{x^2}\frac{d^n}{dx^n}e^{-x^2}; + + :math:`H_n` is a polynomial of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + H : orthopoly1d + Hermite polynomial. + + Notes + ----- + The polynomials :math:`H_n` are orthogonal over :math:`(-\infty, + \infty)` with weight function :math:`e^{-x^2}`. + + Examples + -------- + >>> from scipy import special + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> p_monic = special.hermite(3, monic=True) + >>> p_monic + poly1d([ 1. , 0. , -1.5, 0. ]) + >>> p_monic(1) + -0.49999999999999983 + >>> x = np.linspace(-3, 3, 400) + >>> y = p_monic(x) + >>> plt.plot(x, y) + >>> plt.title("Monic Hermite polynomial of degree 3") + >>> plt.xlabel("x") + >>> plt.ylabel("H_3(x)") + >>> plt.show() + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + if n == 0: + n1 = n + 1 + else: + n1 = n + x, w = roots_hermite(n1) + def wfunc(x): + return exp(-x * x) + if n == 0: + x, w = [], [] + hn = 2**n * _gam(n + 1) * sqrt(pi) + kn = 2**n + p = orthopoly1d(x, w, hn, kn, wfunc, (-inf, inf), monic, + lambda x: _ufuncs.eval_hermite(n, x)) + return p + +# Hermite 2 He_n(x) + + +def roots_hermitenorm(n, mu=False): + r"""Gauss-Hermite (statistician's) quadrature. + + Compute the sample points and weights for Gauss-Hermite + quadrature. The sample points are the roots of the nth degree + Hermite polynomial, :math:`He_n(x)`. These sample points and + weights correctly integrate polynomials of degree :math:`2n - 1` + or less over the interval :math:`[-\infty, \infty]` with weight + function :math:`w(x) = e^{-x^2/2}`. See 22.2.15 in [AS]_ for more + details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + numpy.polynomial.hermite_e.hermegauss + + Notes + ----- + For small n up to 150 a modified version of the Golub-Welsch + algorithm is used. Nodes are computed from the eigenvalue + problem and improved by one step of a Newton iteration. + The weights are computed from the well-known analytical formula. + + For n larger than 150 an optimal asymptotic algorithm is used + which computes nodes and weights in a numerical stable manner. + The algorithm has linear runtime making computation for very + large n (several thousand or more) feasible. + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError("n must be a positive integer.") + + mu0 = np.sqrt(2.0*np.pi) + if n <= 150: + def an_func(k): + return 0.0 * k + def bn_func(k): + return np.sqrt(k) + f = _ufuncs.eval_hermitenorm + def df(n, x): + return n * _ufuncs.eval_hermitenorm(n - 1, x) + return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu) + else: + nodes, weights = _roots_hermite_asy(m) + # Transform + nodes *= sqrt(2) + weights *= sqrt(2) + if mu: + return nodes, weights, mu0 + else: + return nodes, weights + + +def hermitenorm(n, monic=False): + r"""Normalized (probabilist's) Hermite polynomial. + + Defined by + + .. math:: + + He_n(x) = (-1)^ne^{x^2/2}\frac{d^n}{dx^n}e^{-x^2/2}; + + :math:`He_n` is a polynomial of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + He : orthopoly1d + Hermite polynomial. + + Notes + ----- + + The polynomials :math:`He_n` are orthogonal over :math:`(-\infty, + \infty)` with weight function :math:`e^{-x^2/2}`. + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + if n == 0: + n1 = n + 1 + else: + n1 = n + x, w = roots_hermitenorm(n1) + def wfunc(x): + return exp(-x * x / 2.0) + if n == 0: + x, w = [], [] + hn = sqrt(2 * pi) * _gam(n + 1) + kn = 1.0 + p = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(-inf, inf), monic=monic, + eval_func=lambda x: _ufuncs.eval_hermitenorm(n, x)) + return p + +# The remainder of the polynomials can be derived from the ones above. + +# Ultraspherical (Gegenbauer) C^(alpha)_n(x) + + +def roots_gegenbauer(n, alpha, mu=False): + r"""Gauss-Gegenbauer quadrature. + + Compute the sample points and weights for Gauss-Gegenbauer + quadrature. The sample points are the roots of the nth degree + Gegenbauer polynomial, :math:`C^{\alpha}_n(x)`. These sample + points and weights correctly integrate polynomials of degree + :math:`2n - 1` or less over the interval :math:`[-1, 1]` with + weight function :math:`w(x) = (1 - x^2)^{\alpha - 1/2}`. See + 22.2.3 in [AS]_ for more details. + + Parameters + ---------- + n : int + quadrature order + alpha : float + alpha must be > -0.5 + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError("n must be a positive integer.") + if alpha < -0.5: + raise ValueError("alpha must be greater than -0.5.") + elif alpha == 0.0: + # C(n,0,x) == 0 uniformly, however, as alpha->0, C(n,alpha,x)->T(n,x) + # strictly, we should just error out here, since the roots are not + # really defined, but we used to return something useful, so let's + # keep doing so. + return roots_chebyt(n, mu) + + if alpha <= 170: + mu0 = (np.sqrt(np.pi) * _ufuncs.gamma(alpha + 0.5)) \ + / _ufuncs.gamma(alpha + 1) + else: + # For large alpha we use a Taylor series expansion around inf, + # expressed as a 6th order polynomial of a^-1 and using Horner's + # method to minimize computation and maximize precision + inv_alpha = 1. / alpha + coeffs = np.array([0.000207186, -0.00152206, -0.000640869, + 0.00488281, 0.0078125, -0.125, 1.]) + mu0 = coeffs[0] + for term in range(1, len(coeffs)): + mu0 = mu0 * inv_alpha + coeffs[term] + mu0 = mu0 * np.sqrt(np.pi / alpha) + def an_func(k): + return 0.0 * k + def bn_func(k): + return np.sqrt(k * (k + 2 * alpha - 1) / (4 * (k + alpha) * (k + alpha - 1))) + def f(n, x): + return _ufuncs.eval_gegenbauer(n, alpha, x) + def df(n, x): + return ( + -n * x * _ufuncs.eval_gegenbauer(n, alpha, x) + + (n + 2 * alpha - 1) * _ufuncs.eval_gegenbauer(n - 1, alpha, x) + ) / (1 - x ** 2) + return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu) + + +def gegenbauer(n, alpha, monic=False): + r"""Gegenbauer (ultraspherical) polynomial. + + Defined to be the solution of + + .. math:: + (1 - x^2)\frac{d^2}{dx^2}C_n^{(\alpha)} + - (2\alpha + 1)x\frac{d}{dx}C_n^{(\alpha)} + + n(n + 2\alpha)C_n^{(\alpha)} = 0 + + for :math:`\alpha > -1/2`; :math:`C_n^{(\alpha)}` is a polynomial + of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + alpha : float + Parameter, must be greater than -0.5. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + C : orthopoly1d + Gegenbauer polynomial. + + Notes + ----- + The polynomials :math:`C_n^{(\alpha)}` are orthogonal over + :math:`[-1,1]` with weight function :math:`(1 - x^2)^{(\alpha - + 1/2)}`. + + Examples + -------- + >>> import numpy as np + >>> from scipy import special + >>> import matplotlib.pyplot as plt + + We can initialize a variable ``p`` as a Gegenbauer polynomial using the + `gegenbauer` function and evaluate at a point ``x = 1``. + + >>> p = special.gegenbauer(3, 0.5, monic=False) + >>> p + poly1d([ 2.5, 0. , -1.5, 0. ]) + >>> p(1) + 1.0 + + To evaluate ``p`` at various points ``x`` in the interval ``(-3, 3)``, + simply pass an array ``x`` to ``p`` as follows: + + >>> x = np.linspace(-3, 3, 400) + >>> y = p(x) + + We can then visualize ``x, y`` using `matplotlib.pyplot`. + + >>> fig, ax = plt.subplots() + >>> ax.plot(x, y) + >>> ax.set_title("Gegenbauer (ultraspherical) polynomial of degree 3") + >>> ax.set_xlabel("x") + >>> ax.set_ylabel("G_3(x)") + >>> plt.show() + + """ + if not np.isfinite(alpha) or alpha <= -0.5 : + raise ValueError("`alpha` must be a finite number greater than -1/2") + base = jacobi(n, alpha - 0.5, alpha - 0.5, monic=monic) + if monic or n == 0: + return base + # Abrahmowitz and Stegan 22.5.20 + factor = (_gam(2*alpha + n) * _gam(alpha + 0.5) / + _gam(2*alpha) / _gam(alpha + 0.5 + n)) + base._scale(factor) + base.__dict__['_eval_func'] = lambda x: _ufuncs.eval_gegenbauer(float(n), + alpha, x) + return base + +# Chebyshev of the first kind: T_n(x) = +# n! sqrt(pi) / _gam(n+1./2)* P^(-1/2,-1/2)_n(x) +# Computed anew. + + +def roots_chebyt(n, mu=False): + r"""Gauss-Chebyshev (first kind) quadrature. + + Computes the sample points and weights for Gauss-Chebyshev + quadrature. The sample points are the roots of the nth degree + Chebyshev polynomial of the first kind, :math:`T_n(x)`. These + sample points and weights correctly integrate polynomials of + degree :math:`2n - 1` or less over the interval :math:`[-1, 1]` + with weight function :math:`w(x) = 1/\sqrt{1 - x^2}`. See 22.2.4 + in [AS]_ for more details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + numpy.polynomial.chebyshev.chebgauss + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError('n must be a positive integer.') + x = _ufuncs._sinpi(np.arange(-m + 1, m, 2) / (2*m)) + w = np.full_like(x, pi/m) + if mu: + return x, w, pi + else: + return x, w + + +def chebyt(n, monic=False): + r"""Chebyshev polynomial of the first kind. + + Defined to be the solution of + + .. math:: + (1 - x^2)\frac{d^2}{dx^2}T_n - x\frac{d}{dx}T_n + n^2T_n = 0; + + :math:`T_n` is a polynomial of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + T : orthopoly1d + Chebyshev polynomial of the first kind. + + See Also + -------- + chebyu : Chebyshev polynomial of the second kind. + + Notes + ----- + The polynomials :math:`T_n` are orthogonal over :math:`[-1, 1]` + with weight function :math:`(1 - x^2)^{-1/2}`. + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + Chebyshev polynomials of the first kind of order :math:`n` can + be obtained as the determinant of specific :math:`n \times n` + matrices. As an example we can check how the points obtained from + the determinant of the following :math:`3 \times 3` matrix + lay exactly on :math:`T_3`: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.linalg import det + >>> from scipy.special import chebyt + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-2.0, 2.0) + >>> ax.set_title(r'Chebyshev polynomial $T_3$') + >>> ax.plot(x, chebyt(3)(x), label=rf'$T_3$') + >>> for p in np.arange(-1.0, 1.0, 0.1): + ... ax.plot(p, + ... det(np.array([[p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])), + ... 'rx') + >>> plt.legend(loc='best') + >>> plt.show() + + They are also related to the Jacobi Polynomials + :math:`P_n^{(-0.5, -0.5)}` through the relation: + + .. math:: + P_n^{(-0.5, -0.5)}(x) = \frac{1}{4^n} \binom{2n}{n} T_n(x) + + Let's verify it for :math:`n = 3`: + + >>> from scipy.special import binom + >>> from scipy.special import jacobi + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> np.allclose(jacobi(3, -0.5, -0.5)(x), + ... 1/64 * binom(6, 3) * chebyt(3)(x)) + True + + We can plot the Chebyshev polynomials :math:`T_n` for some values + of :math:`n`: + + >>> x = np.arange(-1.5, 1.5, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-4.0, 4.0) + >>> ax.set_title(r'Chebyshev polynomials $T_n$') + >>> for n in np.arange(2,5): + ... ax.plot(x, chebyt(n)(x), label=rf'$T_n={n}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + def wfunc(x): + return 1.0 / sqrt(1 - x * x) + if n == 0: + return orthopoly1d([], [], pi, 1.0, wfunc, (-1, 1), monic, + lambda x: _ufuncs.eval_chebyt(n, x)) + n1 = n + x, w, mu = roots_chebyt(n1, mu=True) + hn = pi / 2 + kn = 2**(n - 1) + p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic, + lambda x: _ufuncs.eval_chebyt(n, x)) + return p + +# Chebyshev of the second kind +# U_n(x) = (n+1)! sqrt(pi) / (2*_gam(n+3./2)) * P^(1/2,1/2)_n(x) + + +def roots_chebyu(n, mu=False): + r"""Gauss-Chebyshev (second kind) quadrature. + + Computes the sample points and weights for Gauss-Chebyshev + quadrature. The sample points are the roots of the nth degree + Chebyshev polynomial of the second kind, :math:`U_n(x)`. These + sample points and weights correctly integrate polynomials of + degree :math:`2n - 1` or less over the interval :math:`[-1, 1]` + with weight function :math:`w(x) = \sqrt{1 - x^2}`. See 22.2.5 in + [AS]_ for details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError('n must be a positive integer.') + t = np.arange(m, 0, -1) * pi / (m + 1) + x = np.cos(t) + w = pi * np.sin(t)**2 / (m + 1) + if mu: + return x, w, pi / 2 + else: + return x, w + + +def chebyu(n, monic=False): + r"""Chebyshev polynomial of the second kind. + + Defined to be the solution of + + .. math:: + (1 - x^2)\frac{d^2}{dx^2}U_n - 3x\frac{d}{dx}U_n + + n(n + 2)U_n = 0; + + :math:`U_n` is a polynomial of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + U : orthopoly1d + Chebyshev polynomial of the second kind. + + See Also + -------- + chebyt : Chebyshev polynomial of the first kind. + + Notes + ----- + The polynomials :math:`U_n` are orthogonal over :math:`[-1, 1]` + with weight function :math:`(1 - x^2)^{1/2}`. + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + Chebyshev polynomials of the second kind of order :math:`n` can + be obtained as the determinant of specific :math:`n \times n` + matrices. As an example we can check how the points obtained from + the determinant of the following :math:`3 \times 3` matrix + lay exactly on :math:`U_3`: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.linalg import det + >>> from scipy.special import chebyu + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-2.0, 2.0) + >>> ax.set_title(r'Chebyshev polynomial $U_3$') + >>> ax.plot(x, chebyu(3)(x), label=rf'$U_3$') + >>> for p in np.arange(-1.0, 1.0, 0.1): + ... ax.plot(p, + ... det(np.array([[2*p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])), + ... 'rx') + >>> plt.legend(loc='best') + >>> plt.show() + + They satisfy the recurrence relation: + + .. math:: + U_{2n-1}(x) = 2 T_n(x)U_{n-1}(x) + + where the :math:`T_n` are the Chebyshev polynomial of the first kind. + Let's verify it for :math:`n = 2`: + + >>> from scipy.special import chebyt + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> np.allclose(chebyu(3)(x), 2 * chebyt(2)(x) * chebyu(1)(x)) + True + + We can plot the Chebyshev polynomials :math:`U_n` for some values + of :math:`n`: + + >>> x = np.arange(-1.0, 1.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-1.5, 1.5) + >>> ax.set_title(r'Chebyshev polynomials $U_n$') + >>> for n in np.arange(1,5): + ... ax.plot(x, chebyu(n)(x), label=rf'$U_n={n}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + base = jacobi(n, 0.5, 0.5, monic=monic) + if monic: + return base + factor = sqrt(pi) / 2.0 * _gam(n + 2) / _gam(n + 1.5) + base._scale(factor) + return base + +# Chebyshev of the first kind C_n(x) + + +def roots_chebyc(n, mu=False): + r"""Gauss-Chebyshev (first kind) quadrature. + + Compute the sample points and weights for Gauss-Chebyshev + quadrature. The sample points are the roots of the nth degree + Chebyshev polynomial of the first kind, :math:`C_n(x)`. These + sample points and weights correctly integrate polynomials of + degree :math:`2n - 1` or less over the interval :math:`[-2, 2]` + with weight function :math:`w(x) = 1 / \sqrt{1 - (x/2)^2}`. See + 22.2.6 in [AS]_ for more details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + x, w, m = roots_chebyt(n, True) + x *= 2 + w *= 2 + m *= 2 + if mu: + return x, w, m + else: + return x, w + + +def chebyc(n, monic=False): + r"""Chebyshev polynomial of the first kind on :math:`[-2, 2]`. + + Defined as :math:`C_n(x) = 2T_n(x/2)`, where :math:`T_n` is the + nth Chebychev polynomial of the first kind. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + C : orthopoly1d + Chebyshev polynomial of the first kind on :math:`[-2, 2]`. + + See Also + -------- + chebyt : Chebyshev polynomial of the first kind. + + Notes + ----- + The polynomials :math:`C_n(x)` are orthogonal over :math:`[-2, 2]` + with weight function :math:`1/\sqrt{1 - (x/2)^2}`. + + References + ---------- + .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions" + Section 22. National Bureau of Standards, 1972. + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + if n == 0: + n1 = n + 1 + else: + n1 = n + x, w = roots_chebyc(n1) + if n == 0: + x, w = [], [] + hn = 4 * pi * ((n == 0) + 1) + kn = 1.0 + p = orthopoly1d(x, w, hn, kn, + wfunc=lambda x: 1.0 / sqrt(1 - x * x / 4.0), + limits=(-2, 2), monic=monic) + if not monic: + p._scale(2.0 / p(2)) + p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebyc(n, x) + return p + +# Chebyshev of the second kind S_n(x) + + +def roots_chebys(n, mu=False): + r"""Gauss-Chebyshev (second kind) quadrature. + + Compute the sample points and weights for Gauss-Chebyshev + quadrature. The sample points are the roots of the nth degree + Chebyshev polynomial of the second kind, :math:`S_n(x)`. These + sample points and weights correctly integrate polynomials of + degree :math:`2n - 1` or less over the interval :math:`[-2, 2]` + with weight function :math:`w(x) = \sqrt{1 - (x/2)^2}`. See 22.2.7 + in [AS]_ for more details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + x, w, m = roots_chebyu(n, True) + x *= 2 + w *= 2 + m *= 2 + if mu: + return x, w, m + else: + return x, w + + +def chebys(n, monic=False): + r"""Chebyshev polynomial of the second kind on :math:`[-2, 2]`. + + Defined as :math:`S_n(x) = U_n(x/2)` where :math:`U_n` is the + nth Chebychev polynomial of the second kind. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + S : orthopoly1d + Chebyshev polynomial of the second kind on :math:`[-2, 2]`. + + See Also + -------- + chebyu : Chebyshev polynomial of the second kind + + Notes + ----- + The polynomials :math:`S_n(x)` are orthogonal over :math:`[-2, 2]` + with weight function :math:`\sqrt{1 - (x/2)}^2`. + + References + ---------- + .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions" + Section 22. National Bureau of Standards, 1972. + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + if n == 0: + n1 = n + 1 + else: + n1 = n + x, w = roots_chebys(n1) + if n == 0: + x, w = [], [] + hn = pi + kn = 1.0 + p = orthopoly1d(x, w, hn, kn, + wfunc=lambda x: sqrt(1 - x * x / 4.0), + limits=(-2, 2), monic=monic) + if not monic: + factor = (n + 1.0) / p(2) + p._scale(factor) + p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebys(n, x) + return p + +# Shifted Chebyshev of the first kind T^*_n(x) + + +def roots_sh_chebyt(n, mu=False): + r"""Gauss-Chebyshev (first kind, shifted) quadrature. + + Compute the sample points and weights for Gauss-Chebyshev + quadrature. The sample points are the roots of the nth degree + shifted Chebyshev polynomial of the first kind, :math:`T_n(x)`. + These sample points and weights correctly integrate polynomials of + degree :math:`2n - 1` or less over the interval :math:`[0, 1]` + with weight function :math:`w(x) = 1/\sqrt{x - x^2}`. See 22.2.8 + in [AS]_ for more details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + xw = roots_chebyt(n, mu) + return ((xw[0] + 1) / 2,) + xw[1:] + + +def sh_chebyt(n, monic=False): + r"""Shifted Chebyshev polynomial of the first kind. + + Defined as :math:`T^*_n(x) = T_n(2x - 1)` for :math:`T_n` the nth + Chebyshev polynomial of the first kind. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + T : orthopoly1d + Shifted Chebyshev polynomial of the first kind. + + Notes + ----- + The polynomials :math:`T^*_n` are orthogonal over :math:`[0, 1]` + with weight function :math:`(x - x^2)^{-1/2}`. + + """ + base = sh_jacobi(n, 0.0, 0.5, monic=monic) + if monic: + return base + if n > 0: + factor = 4**n / 2.0 + else: + factor = 1.0 + base._scale(factor) + return base + + +# Shifted Chebyshev of the second kind U^*_n(x) +def roots_sh_chebyu(n, mu=False): + r"""Gauss-Chebyshev (second kind, shifted) quadrature. + + Computes the sample points and weights for Gauss-Chebyshev + quadrature. The sample points are the roots of the nth degree + shifted Chebyshev polynomial of the second kind, :math:`U_n(x)`. + These sample points and weights correctly integrate polynomials of + degree :math:`2n - 1` or less over the interval :math:`[0, 1]` + with weight function :math:`w(x) = \sqrt{x - x^2}`. See 22.2.9 in + [AS]_ for more details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + x, w, m = roots_chebyu(n, True) + x = (x + 1) / 2 + m_us = _ufuncs.beta(1.5, 1.5) + w *= m_us / m + if mu: + return x, w, m_us + else: + return x, w + + +def sh_chebyu(n, monic=False): + r"""Shifted Chebyshev polynomial of the second kind. + + Defined as :math:`U^*_n(x) = U_n(2x - 1)` for :math:`U_n` the nth + Chebyshev polynomial of the second kind. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + U : orthopoly1d + Shifted Chebyshev polynomial of the second kind. + + Notes + ----- + The polynomials :math:`U^*_n` are orthogonal over :math:`[0, 1]` + with weight function :math:`(x - x^2)^{1/2}`. + + """ + base = sh_jacobi(n, 2.0, 1.5, monic=monic) + if monic: + return base + factor = 4**n + base._scale(factor) + return base + +# Legendre + + +def roots_legendre(n, mu=False): + r"""Gauss-Legendre quadrature. + + Compute the sample points and weights for Gauss-Legendre + quadrature [GL]_. The sample points are the roots of the nth degree + Legendre polynomial :math:`P_n(x)`. These sample points and + weights correctly integrate polynomials of degree :math:`2n - 1` + or less over the interval :math:`[-1, 1]` with weight function + :math:`w(x) = 1`. See 2.2.10 in [AS]_ for more details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + numpy.polynomial.legendre.leggauss + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + .. [GL] Gauss-Legendre quadrature, Wikipedia, + https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import roots_legendre, eval_legendre + >>> roots, weights = roots_legendre(9) + + ``roots`` holds the roots, and ``weights`` holds the weights for + Gauss-Legendre quadrature. + + >>> roots + array([-0.96816024, -0.83603111, -0.61337143, -0.32425342, 0. , + 0.32425342, 0.61337143, 0.83603111, 0.96816024]) + >>> weights + array([0.08127439, 0.18064816, 0.2606107 , 0.31234708, 0.33023936, + 0.31234708, 0.2606107 , 0.18064816, 0.08127439]) + + Verify that we have the roots by evaluating the degree 9 Legendre + polynomial at ``roots``. All the values are approximately zero: + + >>> eval_legendre(9, roots) + array([-8.88178420e-16, -2.22044605e-16, 1.11022302e-16, 1.11022302e-16, + 0.00000000e+00, -5.55111512e-17, -1.94289029e-16, 1.38777878e-16, + -8.32667268e-17]) + + Here we'll show how the above values can be used to estimate the + integral from 1 to 2 of f(t) = t + 1/t with Gauss-Legendre + quadrature [GL]_. First define the function and the integration + limits. + + >>> def f(t): + ... return t + 1/t + ... + >>> a = 1 + >>> b = 2 + + We'll use ``integral(f(t), t=a, t=b)`` to denote the definite integral + of f from t=a to t=b. The sample points in ``roots`` are from the + interval [-1, 1], so we'll rewrite the integral with the simple change + of variable:: + + x = 2/(b - a) * t - (a + b)/(b - a) + + with inverse:: + + t = (b - a)/2 * x + (a + b)/2 + + Then:: + + integral(f(t), a, b) = + (b - a)/2 * integral(f((b-a)/2*x + (a+b)/2), x=-1, x=1) + + We can approximate the latter integral with the values returned + by `roots_legendre`. + + Map the roots computed above from [-1, 1] to [a, b]. + + >>> t = (b - a)/2 * roots + (a + b)/2 + + Approximate the integral as the weighted sum of the function values. + + >>> (b - a)/2 * f(t).dot(weights) + 2.1931471805599276 + + Compare that to the exact result, which is 3/2 + log(2): + + >>> 1.5 + np.log(2) + 2.1931471805599454 + + """ + m = int(n) + if n < 1 or n != m: + raise ValueError("n must be a positive integer.") + + mu0 = 2.0 + def an_func(k): + return 0.0 * k + def bn_func(k): + return k * np.sqrt(1.0 / (4 * k * k - 1)) + f = _ufuncs.eval_legendre + def df(n, x): + return (-n * x * _ufuncs.eval_legendre(n, x) + + n * _ufuncs.eval_legendre(n - 1, x)) / (1 - x ** 2) + return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu) + + +def legendre(n, monic=False): + r"""Legendre polynomial. + + Defined to be the solution of + + .. math:: + \frac{d}{dx}\left[(1 - x^2)\frac{d}{dx}P_n(x)\right] + + n(n + 1)P_n(x) = 0; + + :math:`P_n(x)` is a polynomial of degree :math:`n`. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + P : orthopoly1d + Legendre polynomial. + + Notes + ----- + The polynomials :math:`P_n` are orthogonal over :math:`[-1, 1]` + with weight function 1. + + Examples + -------- + Generate the 3rd-order Legendre polynomial 1/2*(5x^3 + 0x^2 - 3x + 0): + + >>> from scipy.special import legendre + >>> legendre(3) + poly1d([ 2.5, 0. , -1.5, 0. ]) + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + if n == 0: + n1 = n + 1 + else: + n1 = n + x, w = roots_legendre(n1) + if n == 0: + x, w = [], [] + hn = 2.0 / (2 * n + 1) + kn = _gam(2 * n + 1) / _gam(n + 1)**2 / 2.0**n + p = orthopoly1d(x, w, hn, kn, wfunc=lambda x: 1.0, limits=(-1, 1), + monic=monic, + eval_func=lambda x: _ufuncs.eval_legendre(n, x)) + return p + +# Shifted Legendre P^*_n(x) + + +def roots_sh_legendre(n, mu=False): + r"""Gauss-Legendre (shifted) quadrature. + + Compute the sample points and weights for Gauss-Legendre + quadrature. The sample points are the roots of the nth degree + shifted Legendre polynomial :math:`P^*_n(x)`. These sample points + and weights correctly integrate polynomials of degree :math:`2n - + 1` or less over the interval :math:`[0, 1]` with weight function + :math:`w(x) = 1.0`. See 2.2.11 in [AS]_ for details. + + Parameters + ---------- + n : int + quadrature order + mu : bool, optional + If True, return the sum of the weights, optional. + + Returns + ------- + x : ndarray + Sample points + w : ndarray + Weights + mu : float + Sum of the weights + + See Also + -------- + scipy.integrate.fixed_quad + + References + ---------- + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + """ + x, w = roots_legendre(n) + x = (x + 1) / 2 + w /= 2 + if mu: + return x, w, 1.0 + else: + return x, w + + +def sh_legendre(n, monic=False): + r"""Shifted Legendre polynomial. + + Defined as :math:`P^*_n(x) = P_n(2x - 1)` for :math:`P_n` the nth + Legendre polynomial. + + Parameters + ---------- + n : int + Degree of the polynomial. + monic : bool, optional + If `True`, scale the leading coefficient to be 1. Default is + `False`. + + Returns + ------- + P : orthopoly1d + Shifted Legendre polynomial. + + Notes + ----- + The polynomials :math:`P^*_n` are orthogonal over :math:`[0, 1]` + with weight function 1. + + """ + if n < 0: + raise ValueError("n must be nonnegative.") + + def wfunc(x): + return 0.0 * x + 1.0 + if n == 0: + return orthopoly1d([], [], 1.0, 1.0, wfunc, (0, 1), monic, + lambda x: _ufuncs.eval_sh_legendre(n, x)) + x, w = roots_sh_legendre(n) + hn = 1.0 / (2 * n + 1.0) + kn = _gam(2 * n + 1) / _gam(n + 1)**2 + p = orthopoly1d(x, w, hn, kn, wfunc, limits=(0, 1), monic=monic, + eval_func=lambda x: _ufuncs.eval_sh_legendre(n, x)) + return p + + +# Make the old root function names an alias for the new ones +_modattrs = globals() +for newfun, oldfun in _rootfuns_map.items(): + _modattrs[oldfun] = _modattrs[newfun] + __all__.append(oldfun) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e0ae3ce3be90187cd957fe16cc6d145a7093da5a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi @@ -0,0 +1,330 @@ +from typing import ( + Any, + Callable, + Literal, + Optional, + overload, +) + +import numpy as np + +_IntegerType = int | np.integer +_FloatingType = float | np.floating +_PointsAndWeights = tuple[np.ndarray, np.ndarray] +_PointsAndWeightsAndMu = tuple[np.ndarray, np.ndarray, float] + +_ArrayLike0D = bool | int | float | complex | str | bytes | np.generic + +__all__ = [ + 'legendre', + 'chebyt', + 'chebyu', + 'chebyc', + 'chebys', + 'jacobi', + 'laguerre', + 'genlaguerre', + 'hermite', + 'hermitenorm', + 'gegenbauer', + 'sh_legendre', + 'sh_chebyt', + 'sh_chebyu', + 'sh_jacobi', + 'roots_legendre', + 'roots_chebyt', + 'roots_chebyu', + 'roots_chebyc', + 'roots_chebys', + 'roots_jacobi', + 'roots_laguerre', + 'roots_genlaguerre', + 'roots_hermite', + 'roots_hermitenorm', + 'roots_gegenbauer', + 'roots_sh_legendre', + 'roots_sh_chebyt', + 'roots_sh_chebyu', + 'roots_sh_jacobi', +] + +@overload +def roots_jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_jacobi( + n: _IntegerType, + p1: _FloatingType, + q1: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_sh_jacobi( + n: _IntegerType, + p1: _FloatingType, + q1: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_jacobi( + n: _IntegerType, + p1: _FloatingType, + q1: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_genlaguerre( + n: _IntegerType, + alpha: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_genlaguerre( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_genlaguerre( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_laguerre(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_laguerre( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_laguerre( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_hermite(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_hermite( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_hermite( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_hermitenorm(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_hermitenorm( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_hermitenorm( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_gegenbauer( + n: _IntegerType, + alpha: _FloatingType, +) -> _PointsAndWeights: ... +@overload +def roots_gegenbauer( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_gegenbauer( + n: _IntegerType, + alpha: _FloatingType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebyt(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebyt( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebyt( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebyu(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebyu( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebyu( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebyc(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebyc( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebyc( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_chebys(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_chebys( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_chebys( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_chebyt(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyt( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyt( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_chebyu(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyu( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_chebyu( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_legendre(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_legendre( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_legendre( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +@overload +def roots_sh_legendre(n: _IntegerType) -> _PointsAndWeights: ... +@overload +def roots_sh_legendre( + n: _IntegerType, + mu: Literal[False], +) -> _PointsAndWeights: ... +@overload +def roots_sh_legendre( + n: _IntegerType, + mu: Literal[True], +) -> _PointsAndWeightsAndMu: ... + +class orthopoly1d(np.poly1d): + def __init__( + self, + roots: np.typing.ArrayLike, + weights: np.typing.ArrayLike | None, + hn: float = ..., + kn: float = ..., + wfunc = Optional[Callable[[float], float]], # noqa: UP007 + limits = tuple[float, float] | None, + monic: bool = ..., + eval_func: np.ufunc = ..., + ) -> None: ... + @property + def limits(self) -> tuple[float, float]: ... + def weight_func(self, x: float) -> float: ... + @overload + def __call__(self, x: _ArrayLike0D) -> Any: ... + @overload + def __call__(self, x: np.poly1d) -> np.poly1d: ... # type: ignore[overload-overlap] + @overload + def __call__(self, x: np.typing.ArrayLike) -> np.ndarray: ... + +def legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebyc(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def chebys(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def jacobi( + n: _IntegerType, + alpha: _FloatingType, + beta: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... +def laguerre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def genlaguerre( + n: _IntegerType, + alpha: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... +def hermite(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def hermitenorm(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def gegenbauer( + n: _IntegerType, + alpha: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... +def sh_legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def sh_chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def sh_chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ... +def sh_jacobi( + n: _IntegerType, + p: _FloatingType, + q: _FloatingType, + monic: bool = ..., +) -> orthopoly1d: ... + +# These functions are not public, but still need stubs because they +# get checked in the tests. +def _roots_hermite_asy(n: _IntegerType) -> _PointsAndWeights: ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py new file mode 100644 index 0000000000000000000000000000000000000000..662c12bc74b31478c87471fbd1cce8bea285e765 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py @@ -0,0 +1,17 @@ +import mpmath + + +def f(x): + return (mpmath.pi + x + mpmath.sin(x)) / (2*mpmath.pi) + + +# Note: 40 digits might be overkill; a few more digits than the default +# might be sufficient. +mpmath.mp.dps = 40 +ts = mpmath.taylor(f, -mpmath.pi, 20) +p, q = mpmath.pade(ts, 9, 10) + +p = [float(c) for c in p] +q = [float(c) for c in q] +print('p =', p) +print('q =', q) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py new file mode 100644 index 0000000000000000000000000000000000000000..3491b8acd588a2cacfc48f0a3a60c6ae88c3e8c5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py @@ -0,0 +1,54 @@ +"""Precompute the polynomials for the asymptotic expansion of the +generalized exponential integral. + +Sources +------- +[1] NIST, Digital Library of Mathematical Functions, + https://dlmf.nist.gov/8.20#ii + +""" +import os + +try: + import sympy + from sympy import Poly + x = sympy.symbols('x') +except ImportError: + pass + + +def generate_A(K): + A = [Poly(1, x)] + for k in range(K): + A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff()) + return A + + +WARNING = """\ +/* This file was automatically generated by _precompute/expn_asy.py. + * Do not edit it manually! + */ +""" + + +def main(): + print(__doc__) + fn = os.path.join('..', 'cephes', 'expn.h') + + K = 12 + A = generate_A(K) + with open(fn + '.new', 'w') as f: + f.write(WARNING) + f.write(f"#define nA {len(A)}\n") + for k, Ak in enumerate(A): + ', '.join([str(x.evalf(18)) for x in Ak.coeffs()]) + f.write(f"static const double A{k}[] = {{tmp}};\n") + ", ".join([f"A{k}" for k in range(K + 1)]) + f.write("static const double *A[] = {{tmp}};\n") + ", ".join([str(Ak.degree()) for Ak in A]) + f.write("static const int Adegs[] = {{tmp}};\n") + os.rename(fn + '.new', fn) + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py new file mode 100644 index 0000000000000000000000000000000000000000..98035457c78706ae01c02273ae1ab458b4ca140d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py @@ -0,0 +1,116 @@ +""" +Precompute coefficients of Temme's asymptotic expansion for gammainc. + +This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram. + +Sources: +[1] NIST, "Digital Library of Mathematical Functions", + https://dlmf.nist.gov/ + +""" +import os +from scipy.special._precompute.utils import lagrange_inversion + +try: + import mpmath as mp +except ImportError: + pass + + +def compute_a(n): + """a_k from DLMF 5.11.6""" + a = [mp.sqrt(2)/2] + for k in range(1, n): + ak = a[-1]/k + for j in range(1, len(a)): + ak -= a[j]*a[-j]/(j + 1) + ak /= a[0]*(1 + mp.mpf(1)/(k + 1)) + a.append(ak) + return a + + +def compute_g(n): + """g_k from DLMF 5.11.3/5.11.5""" + a = compute_a(2*n) + g = [mp.sqrt(2)*mp.rf(0.5, k)*a[2*k] for k in range(n)] + return g + + +def eta(lam): + """Function from DLMF 8.12.1 shifted to be centered at 0.""" + if lam > 0: + return mp.sqrt(2*(lam - mp.log(lam + 1))) + elif lam < 0: + return -mp.sqrt(2*(lam - mp.log(lam + 1))) + else: + return 0 + + +def compute_alpha(n): + """alpha_n from DLMF 8.12.13""" + coeffs = mp.taylor(eta, 0, n - 1) + return lagrange_inversion(coeffs) + + +def compute_d(K, N): + """d_{k, n} from DLMF 8.12.12""" + M = N + 2*K + d0 = [-mp.mpf(1)/3] + alpha = compute_alpha(M + 2) + for n in range(1, M): + d0.append((n + 2)*alpha[n+2]) + d = [d0] + g = compute_g(K) + for k in range(1, K): + dk = [] + for n in range(M - 2*k): + dk.append((-1)**k*g[k]*d[0][n] + (n + 2)*d[k-1][n+2]) + d.append(dk) + for k in range(K): + d[k] = d[k][:N] + return d + + +header = \ +r"""/* This file was automatically generated by _precomp/gammainc.py. + * Do not edit it manually! + */ + +#ifndef IGAM_H +#define IGAM_H + +#define K {} +#define N {} + +static const double d[K][N] = +{{""" + +footer = \ +r""" +#endif +""" + + +def main(): + print(__doc__) + K = 25 + N = 25 + with mp.workdps(50): + d = compute_d(K, N) + fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h') + with open(fn + '.new', 'w') as f: + f.write(header.format(K, N)) + for k, row in enumerate(d): + row = [mp.nstr(x, 17, min_fixed=0, max_fixed=0) for x in row] + f.write('{') + f.write(", ".join(row)) + if k < K - 1: + f.write('},\n') + else: + f.write('}};\n') + f.write(footer) + os.rename(fn + '.new', fn) + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbe39f6159fb80c424dbb38eedeba46bd8cccf2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py @@ -0,0 +1,124 @@ +"""Compute gammainc and gammaincc for large arguments and parameters +and save the values to data files for use in tests. We can't just +compare to mpmath's gammainc in test_mpmath.TestSystematic because it +would take too long. + +Note that mpmath's gammainc is computed using hypercomb, but since it +doesn't allow the user to increase the maximum number of terms used in +the series it doesn't converge for many arguments. To get around this +we copy the mpmath implementation but use more terms. + +This takes about 17 minutes to run on a 2.3 GHz Macbook Pro with 4GB +ram. + +Sources: +[1] Fredrik Johansson and others. mpmath: a Python library for + arbitrary-precision floating-point arithmetic (version 0.19), + December 2013. http://mpmath.org/. + +""" +import os +from time import time +import numpy as np +from numpy import pi + +from scipy.special._mptestutils import mpf2float + +try: + import mpmath as mp +except ImportError: + pass + + +def gammainc(a, x, dps=50, maxterms=10**8): + """Compute gammainc exactly like mpmath does but allow for more + summands in hypercomb. See + + mpmath/functions/expintegrals.py#L134 + + in the mpmath GitHub repository. + + """ + with mp.workdps(dps): + z, a, b = mp.mpf(a), mp.mpf(x), mp.mpf(x) + G = [z] + negb = mp.fneg(b, exact=True) + + def h(z): + T1 = [mp.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b + return (T1,) + + res = mp.hypercomb(h, [z], maxterms=maxterms) + return mpf2float(res) + + +def gammaincc(a, x, dps=50, maxterms=10**8): + """Compute gammaincc exactly like mpmath does but allow for more + terms in hypercomb. See + + mpmath/functions/expintegrals.py#L187 + + in the mpmath GitHub repository. + + """ + with mp.workdps(dps): + z, a = a, x + + if mp.isint(z): + try: + # mpmath has a fast integer path + return mpf2float(mp.gammainc(z, a=a, regularized=True)) + except mp.libmp.NoConvergence: + pass + nega = mp.fneg(a, exact=True) + G = [z] + # Use 2F0 series when possible; fall back to lower gamma representation + try: + def h(z): + r = z-1 + return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] + return mpf2float(mp.hypercomb(h, [z], force_series=True)) + except mp.libmp.NoConvergence: + def h(z): + T1 = [], [1, z-1], [z], G, [], [], 0 + T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a + return T1, T2 + return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms)) + + +def main(): + t0 = time() + # It would be nice to have data for larger values, but either this + # requires prohibitively large precision (dps > 800) or mpmath has + # a bug. For example, gammainc(1e20, 1e20, dps=800) returns a + # value around 0.03, while the true value should be close to 0.5 + # (DLMF 8.12.15). + print(__doc__) + pwd = os.path.dirname(__file__) + r = np.logspace(4, 14, 30) + ltheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(0.6)), 30) + utheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(1.4)), 30) + + regimes = [(gammainc, ltheta), (gammaincc, utheta)] + for func, theta in regimes: + rg, thetag = np.meshgrid(r, theta) + a, x = rg*np.cos(thetag), rg*np.sin(thetag) + a, x = a.flatten(), x.flatten() + dataset = [] + for i, (a0, x0) in enumerate(zip(a, x)): + if func == gammaincc: + # Exploit the fast integer path in gammaincc whenever + # possible so that the computation doesn't take too + # long + a0, x0 = np.floor(a0), np.floor(x0) + dataset.append((a0, x0, func(a0, x0))) + dataset = np.array(dataset) + filename = os.path.join(pwd, '..', 'tests', 'data', 'local', + f'{func.__name__}.txt') + np.savetxt(filename, dataset) + + print(f"{(time() - t0)/60} minutes elapsed") + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c4adf14f49184bf75048a28a823909d24e778e04 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py @@ -0,0 +1,484 @@ +"""This script evaluates scipy's implementation of hyp2f1 against mpmath's. + +Author: Albert Steppi + +This script is long running and generates a large output file. With default +arguments, the generated file is roughly 700MB in size and it takes around +40 minutes using an Intel(R) Core(TM) i5-8250U CPU with n_jobs set to 8 +(full utilization). There are optional arguments which can be used to restrict +(or enlarge) the computations performed. These are described below. +The output of this script can be analyzed to identify suitable test cases and +to find parameter and argument regions where hyp2f1 needs to be improved. + +The script has one mandatory positional argument for specifying the path to +the location where the output file is to be placed, and 4 optional arguments +--n_jobs, --grid_size, --regions, and --parameter_groups. --n_jobs specifies +the number of processes to use if running in parallel. The default value is 1. +The other optional arguments are explained below. + +Produces a tab separated values file with 11 columns. The first four columns +contain the parameters a, b, c and the argument z. The next two contain |z| and +a region code for which region of the complex plane belongs to. The regions are + + 0) z == 1 + 1) |z| < 0.9 and real(z) >= 0 + 2) |z| <= 1 and real(z) < 0 + 3) 0.9 <= |z| <= 1 and |1 - z| < 0.9: + 4) 0.9 <= |z| <= 1 and |1 - z| >= 0.9 and real(z) >= 0: + 5) 1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0 + 6) |z| > 1 and not in 5) + +The --regions optional argument allows the user to specify a list of regions +to which computation will be restricted. + +Parameters a, b, c are taken from a 10 * 10 * 10 grid with values at + + -16, -8, -4, -2, -1, 1, 2, 4, 8, 16 + +with random perturbations applied. + +There are 9 parameter groups handling the following cases. + + 1) A, B, C, B - A, C - A, C - B, C - A - B all non-integral. + 2) B - A integral + 3) C - A integral + 4) C - B integral + 5) C - A - B integral + 6) A integral + 7) B integral + 8) C integral + 9) Wider range with c - a - b > 0. + +The seventh column of the output file is an integer between 1 and 8 specifying +the parameter group as above. + +The --parameter_groups optional argument allows the user to specify a list of +parameter groups to which computation will be restricted. + +The argument z is taken from a grid in the box + -box_size <= real(z) <= box_size, -box_size <= imag(z) <= box_size. +with grid size specified using the optional command line argument --grid_size, +and box_size specified with the command line argument --box_size. +The default value of grid_size is 20 and the default value of box_size is 2.0, +yielding a 20 * 20 grid in the box with corners -2-2j, -2+2j, 2-2j, 2+2j. + +The final four columns have the expected value of hyp2f1 for the given +parameters and argument as calculated with mpmath, the observed value +calculated with scipy's hyp2f1, the relative error, and the absolute error. + +As special cases of hyp2f1 are moved from the original Fortran implementation +into Cython, this script can be used to ensure that no regressions occur and +to point out where improvements are needed. +""" + + +import os +import csv +import argparse +import numpy as np +from itertools import product +from multiprocessing import Pool + + +from scipy.special import hyp2f1 +from scipy.special.tests.test_hyp2f1 import mp_hyp2f1 + + +def get_region(z): + """Assign numbers for regions where hyp2f1 must be handled differently.""" + if z == 1 + 0j: + return 0 + elif abs(z) < 0.9 and z.real >= 0: + return 1 + elif abs(z) <= 1 and z.real < 0: + return 2 + elif 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9: + return 3 + elif 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9: + return 4 + elif 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0: + return 5 + else: + return 6 + + +def get_result(a, b, c, z, group): + """Get results for given parameter and value combination.""" + expected, observed = mp_hyp2f1(a, b, c, z), hyp2f1(a, b, c, z) + if ( + np.isnan(observed) and np.isnan(expected) or + expected == observed + ): + relative_error = 0.0 + absolute_error = 0.0 + elif np.isnan(observed): + # Set error to infinity if result is nan when not expected to be. + # Makes results easier to interpret. + relative_error = float("inf") + absolute_error = float("inf") + else: + absolute_error = abs(expected - observed) + relative_error = absolute_error / abs(expected) + + return ( + a, + b, + c, + z, + abs(z), + get_region(z), + group, + expected, + observed, + relative_error, + absolute_error, + ) + + +def get_result_no_mp(a, b, c, z, group): + """Get results for given parameter and value combination.""" + expected, observed = complex('nan'), hyp2f1(a, b, c, z) + relative_error, absolute_error = float('nan'), float('nan') + return ( + a, + b, + c, + z, + abs(z), + get_region(z), + group, + expected, + observed, + relative_error, + absolute_error, + ) + + +def get_results(params, Z, n_jobs=1, compute_mp=True): + """Batch compute results for multiple parameter and argument values. + + Parameters + ---------- + params : iterable + iterable of tuples of floats (a, b, c) specifying parameter values + a, b, c for hyp2f1 + Z : iterable of complex + Arguments at which to evaluate hyp2f1 + n_jobs : Optional[int] + Number of jobs for parallel execution. + + Returns + ------- + list + List of tuples of results values. See return value in source code + of `get_result`. + """ + input_ = ( + (a, b, c, z, group) for (a, b, c, group), z in product(params, Z) + ) + + with Pool(n_jobs) as pool: + rows = pool.starmap( + get_result if compute_mp else get_result_no_mp, + input_ + ) + return rows + + +def _make_hyp2f1_test_case(a, b, c, z, rtol): + """Generate string for single test case as used in test_hyp2f1.py.""" + expected = mp_hyp2f1(a, b, c, z) + return ( + " pytest.param(\n" + " Hyp2f1TestCase(\n" + f" a={a},\n" + f" b={b},\n" + f" c={c},\n" + f" z={z},\n" + f" expected={expected},\n" + f" rtol={rtol},\n" + " ),\n" + " )," + ) + + +def make_hyp2f1_test_cases(rows): + """Generate string for a list of test cases for test_hyp2f1.py. + + Parameters + ---------- + rows : list + List of lists of the form [a, b, c, z, rtol] where a, b, c, z are + parameters and the argument for hyp2f1 and rtol is an expected + relative error for the associated test case. + + Returns + ------- + str + String for a list of test cases. The output string can be printed + or saved to a file and then copied into an argument for + `pytest.mark.parameterize` within `scipy.special.tests.test_hyp2f1.py`. + """ + result = "[\n" + result += '\n'.join( + _make_hyp2f1_test_case(a, b, c, z, rtol) + for a, b, c, z, rtol in rows + ) + result += "\n]" + return result + + +def main( + outpath, + n_jobs=1, + box_size=2.0, + grid_size=20, + regions=None, + parameter_groups=None, + compute_mp=True, +): + outpath = os.path.realpath(os.path.expanduser(outpath)) + + random_state = np.random.RandomState(1234) + # Parameters a, b, c selected near these values. + root_params = np.array( + [-16, -8, -4, -2, -1, 1, 2, 4, 8, 16] + ) + # Perturbations to apply to root values. + perturbations = 0.1 * random_state.random_sample( + size=(3, len(root_params)) + ) + + params = [] + # Parameter group 1 + # ----------------- + # No integer differences. This has been confirmed for the above seed. + A = root_params + perturbations[0, :] + B = root_params + perturbations[1, :] + C = root_params + perturbations[2, :] + params.extend( + sorted( + ((a, b, c, 1) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 2 + # ----------------- + # B - A an integer + A = root_params + 0.5 + B = root_params + 0.5 + C = root_params + perturbations[1, :] + params.extend( + sorted( + ((a, b, c, 2) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 3 + # ----------------- + # C - A an integer + A = root_params + 0.5 + B = root_params + perturbations[1, :] + C = root_params + 0.5 + params.extend( + sorted( + ((a, b, c, 3) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 4 + # ----------------- + # C - B an integer + A = root_params + perturbations[0, :] + B = root_params + 0.5 + C = root_params + 0.5 + params.extend( + sorted( + ((a, b, c, 4) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 5 + # ----------------- + # C - A - B an integer + A = root_params + 0.25 + B = root_params + 0.25 + C = root_params + 0.5 + params.extend( + sorted( + ((a, b, c, 5) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 6 + # ----------------- + # A an integer + A = root_params + B = root_params + perturbations[0, :] + C = root_params + perturbations[1, :] + params.extend( + sorted( + ((a, b, c, 6) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 7 + # ----------------- + # B an integer + A = root_params + perturbations[0, :] + B = root_params + C = root_params + perturbations[1, :] + params.extend( + sorted( + ((a, b, c, 7) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 8 + # ----------------- + # C an integer + A = root_params + perturbations[0, :] + B = root_params + perturbations[1, :] + C = root_params + params.extend( + sorted( + ((a, b, c, 8) for a, b, c in product(A, B, C)), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + ) + + # Parameter group 9 + # ----------------- + # Wide range of magnitudes, c - a - b > 0. + phi = (1 + np.sqrt(5))/2 + P = phi**np.arange(16) + P = np.hstack([-P, P]) + group_9_params = sorted( + ( + (a, b, c, 9) for a, b, c in product(P, P, P) if c - a - b > 0 + ), + key=lambda x: max(abs(x[0]), abs(x[1])), + ) + + if parameter_groups is not None: + # Group 9 params only used if specified in arguments. + params.extend(group_9_params) + params = [ + (a, b, c, group) for a, b, c, group in params + if group in parameter_groups + ] + + # grid_size * grid_size grid in box with corners + # -2 - 2j, -2 + 2j, 2 - 2j, 2 + 2j + X, Y = np.meshgrid( + np.linspace(-box_size, box_size, grid_size), + np.linspace(-box_size, box_size, grid_size) + ) + Z = X + Y * 1j + Z = Z.flatten().tolist() + # Add z = 1 + 0j (region 0). + Z.append(1 + 0j) + if regions is not None: + Z = [z for z in Z if get_region(z) in regions] + + # Evaluate scipy and mpmath's hyp2f1 for all parameter combinations + # above against all arguments in the grid Z + rows = get_results(params, Z, n_jobs=n_jobs, compute_mp=compute_mp) + + with open(outpath, "w", newline="") as f: + writer = csv.writer(f, delimiter="\t") + writer.writerow( + [ + "a", + "b", + "c", + "z", + "|z|", + "region", + "parameter_group", + "expected", # mpmath's hyp2f1 + "observed", # scipy's hyp2f1 + "relative_error", + "absolute_error", + ] + ) + for row in rows: + writer.writerow(row) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Test scipy's hyp2f1 against mpmath's on a grid in the" + " complex plane over a grid of parameter values. Saves output to file" + " specified in positional argument \"outpath\"." + " Caution: With default arguments, the generated output file is" + " roughly 700MB in size. Script may take several hours to finish if" + " \"--n_jobs\" is set to 1." + ) + parser.add_argument( + "outpath", type=str, help="Path to output tsv file." + ) + parser.add_argument( + "--n_jobs", + type=int, + default=1, + help="Number of jobs for multiprocessing.", + ) + parser.add_argument( + "--box_size", + type=float, + default=2.0, + help="hyp2f1 is evaluated in box of side_length 2*box_size centered" + " at the origin." + ) + parser.add_argument( + "--grid_size", + type=int, + default=20, + help="hyp2f1 is evaluated on grid_size * grid_size grid in box of side" + " length 2*box_size centered at the origin." + ) + parser.add_argument( + "--parameter_groups", + type=int, + nargs='+', + default=None, + help="Restrict to supplied parameter groups. See the Docstring for" + " this module for more info on parameter groups. Calculate for all" + " parameter groups by default." + ) + parser.add_argument( + "--regions", + type=int, + nargs='+', + default=None, + help="Restrict to argument z only within the supplied regions. See" + " the Docstring for this module for more info on regions. Calculate" + " for all regions by default." + ) + parser.add_argument( + "--no_mp", + action='store_true', + help="If this flag is set, do not compute results with mpmath. Saves" + " time if results have already been computed elsewhere. Fills in" + " \"expected\" column with None values." + ) + args = parser.parse_args() + compute_mp = not args.no_mp + print(args.parameter_groups) + main( + args.outpath, + n_jobs=args.n_jobs, + box_size=args.box_size, + grid_size=args.grid_size, + parameter_groups=args.parameter_groups, + regions=args.regions, + compute_mp=compute_mp, + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py new file mode 100644 index 0000000000000000000000000000000000000000..1fdbf35b2cf85f1f7a6e73579546ed5cfe508fa6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py @@ -0,0 +1,68 @@ +"""Compute a Pade approximation for the principal branch of the +Lambert W function around 0 and compare it to various other +approximations. + +""" +import numpy as np + +try: + import mpmath + import matplotlib.pyplot as plt +except ImportError: + pass + + +def lambertw_pade(): + derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)] + p, q = mpmath.pade(derivs, 3, 2) + return p, q + + +def main(): + print(__doc__) + with mpmath.workdps(50): + p, q = lambertw_pade() + p, q = p[::-1], q[::-1] + print(f"p = {p}") + print(f"q = {q}") + + x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75) + x, y = np.meshgrid(x, y) + z = x + 1j*y + lambertw_std = [] + for z0 in z.flatten(): + lambertw_std.append(complex(mpmath.lambertw(z0))) + lambertw_std = np.array(lambertw_std).reshape(x.shape) + + fig, axes = plt.subplots(nrows=3, ncols=1) + # Compare Pade approximation to true result + p = np.array([float(p0) for p0 in p]) + q = np.array([float(q0) for q0 in q]) + pade_approx = np.polyval(p, z)/np.polyval(q, z) + pade_err = abs(pade_approx - lambertw_std) + axes[0].pcolormesh(x, y, pade_err) + # Compare two terms of asymptotic series to true result + asy_approx = np.log(z) - np.log(np.log(z)) + asy_err = abs(asy_approx - lambertw_std) + axes[1].pcolormesh(x, y, asy_err) + # Compare two terms of the series around the branch point to the + # true result + p = np.sqrt(2*(np.exp(1)*z + 1)) + series_approx = -1 + p - p**2/3 + series_err = abs(series_approx - lambertw_std) + im = axes[2].pcolormesh(x, y, series_err) + + fig.colorbar(im, ax=axes.ravel().tolist()) + plt.show() + + fig, ax = plt.subplots(nrows=1, ncols=1) + pade_better = pade_err < asy_err + im = ax.pcolormesh(x, y, pade_better) + t = np.linspace(-0.3, 0.3) + ax.plot(-2.5*abs(t) - 0.2, t, 'r') + fig.colorbar(im, ax=ax) + plt.show() + + +if __name__ == '__main__': + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py new file mode 100644 index 0000000000000000000000000000000000000000..74051ac7b46c70dc01919a362d05a8bbbe11333a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py @@ -0,0 +1,43 @@ +"""Precompute series coefficients for log-Gamma.""" + +try: + import mpmath +except ImportError: + pass + + +def stirling_series(N): + with mpmath.workdps(100): + coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1)) + for n in range(1, N + 1)] + return coeffs + + +def taylor_series_at_1(N): + coeffs = [] + with mpmath.workdps(100): + coeffs.append(-mpmath.euler) + for n in range(2, N + 1): + coeffs.append((-1)**n*mpmath.zeta(n)/n) + return coeffs + + +def main(): + print(__doc__) + print() + stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in stirling_series(8)[::-1]] + taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in taylor_series_at_1(23)[::-1]] + print("Stirling series coefficients") + print("----------------------------") + print("\n".join(stirling_coeffs)) + print() + print("Taylor series coefficients") + print("--------------------------") + print("\n".join(taylor_coeffs)) + print() + + +if __name__ == '__main__': + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf6009368540dbf603b61f5b72510f0acd1a65b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py @@ -0,0 +1,131 @@ +""" +Convergence regions of the expansions used in ``struve.c`` + +Note that for v >> z both functions tend rapidly to 0, +and for v << -z, they tend to infinity. + +The floating-point functions over/underflow in the lower left and right +corners of the figure. + + +Figure legend +============= + +Red region + Power series is close (1e-12) to the mpmath result + +Blue region + Asymptotic series is close to the mpmath result + +Green region + Bessel series is close to the mpmath result + +Dotted colored lines + Boundaries of the regions + +Solid colored lines + Boundaries estimated by the routine itself. These will be used + for determining which of the results to use. + +Black dashed line + The line z = 0.7*|v| + 12 + +""" +import numpy as np +import matplotlib.pyplot as plt + +import mpmath + + +def err_metric(a, b, atol=1e-290): + m = abs(a - b) / (atol + abs(b)) + m[np.isinf(b) & (a == b)] = 0 + return m + + +def do_plot(is_h=True): + from scipy.special._ufuncs import (_struve_power_series, + _struve_asymp_large_z, + _struve_bessel_series) + + vs = np.linspace(-1000, 1000, 91) + zs = np.sort(np.r_[1e-5, 1.0, np.linspace(0, 700, 91)[1:]]) + + rp = _struve_power_series(vs[:,None], zs[None,:], is_h) + ra = _struve_asymp_large_z(vs[:,None], zs[None,:], is_h) + rb = _struve_bessel_series(vs[:,None], zs[None,:], is_h) + + mpmath.mp.dps = 50 + if is_h: + def sh(v, z): + return float(mpmath.struveh(mpmath.mpf(v), mpmath.mpf(z))) + else: + def sh(v, z): + return float(mpmath.struvel(mpmath.mpf(v), mpmath.mpf(z))) + ex = np.vectorize(sh, otypes='d')(vs[:,None], zs[None,:]) + + err_a = err_metric(ra[0], ex) + 1e-300 + err_p = err_metric(rp[0], ex) + 1e-300 + err_b = err_metric(rb[0], ex) + 1e-300 + + err_est_a = abs(ra[1]/ra[0]) + err_est_p = abs(rp[1]/rp[0]) + err_est_b = abs(rb[1]/rb[0]) + + z_cutoff = 0.7*abs(vs) + 12 + + levels = [-1000, -12] + + plt.cla() + + plt.hold(1) + plt.contourf(vs, zs, np.log10(err_p).T, + levels=levels, colors=['r', 'r'], alpha=0.1) + plt.contourf(vs, zs, np.log10(err_a).T, + levels=levels, colors=['b', 'b'], alpha=0.1) + plt.contourf(vs, zs, np.log10(err_b).T, + levels=levels, colors=['g', 'g'], alpha=0.1) + + plt.contour(vs, zs, np.log10(err_p).T, + levels=levels, colors=['r', 'r'], linestyles=[':', ':']) + plt.contour(vs, zs, np.log10(err_a).T, + levels=levels, colors=['b', 'b'], linestyles=[':', ':']) + plt.contour(vs, zs, np.log10(err_b).T, + levels=levels, colors=['g', 'g'], linestyles=[':', ':']) + + lp = plt.contour(vs, zs, np.log10(err_est_p).T, + levels=levels, colors=['r', 'r'], linestyles=['-', '-']) + la = plt.contour(vs, zs, np.log10(err_est_a).T, + levels=levels, colors=['b', 'b'], linestyles=['-', '-']) + lb = plt.contour(vs, zs, np.log10(err_est_b).T, + levels=levels, colors=['g', 'g'], linestyles=['-', '-']) + + plt.clabel(lp, fmt={-1000: 'P', -12: 'P'}) + plt.clabel(la, fmt={-1000: 'A', -12: 'A'}) + plt.clabel(lb, fmt={-1000: 'B', -12: 'B'}) + + plt.plot(vs, z_cutoff, 'k--') + + plt.xlim(vs.min(), vs.max()) + plt.ylim(zs.min(), zs.max()) + + plt.xlabel('v') + plt.ylabel('z') + + +def main(): + plt.clf() + plt.subplot(121) + do_plot(True) + plt.title('Struve H') + + plt.subplot(122) + do_plot(False) + plt.title('Struve L') + + plt.savefig('struve_convergence.png') + plt.show() + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..55cf4083ed5e5a6628fd3316c02ce1a5ce21a92c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py @@ -0,0 +1,38 @@ +try: + import mpmath as mp +except ImportError: + pass + +try: + from sympy.abc import x +except ImportError: + pass + + +def lagrange_inversion(a): + """Given a series + + f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1), + + use the Lagrange inversion formula to compute a series + + g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1) + + so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so + necessarily b[0] = 0 too. + + The algorithm is naive and could be improved, but speed isn't an + issue here and it's easy to read. + + """ + n = len(a) + f = sum(a[i]*x**i for i in range(n)) + h = (x/f).series(x, 0, n).removeO() + hpower = [h**0] + for k in range(n): + hpower.append((hpower[-1]*h).expand()) + b = [mp.mpf(0)] + for k in range(1, n): + b.append(hpower[k].coeff(x, k - 1)/k) + b = [mp.mpf(x) for x in b] + return b diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..51d56b1cd5c47c7ef005d21aad9827a1e85ec0d9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py @@ -0,0 +1,342 @@ +"""Precompute coefficients of several series expansions +of Wright's generalized Bessel function Phi(a, b, x). + +See https://dlmf.nist.gov/10.46.E1 with rho=a, beta=b, z=x. +""" +from argparse import ArgumentParser, RawTextHelpFormatter +import numpy as np +from scipy.integrate import quad +from scipy.optimize import minimize_scalar, curve_fit +from time import time + +try: + import sympy + from sympy import EulerGamma, Rational, S, Sum, \ + factorial, gamma, gammasimp, pi, polygamma, symbols, zeta + from sympy.polys.polyfuncs import horner +except ImportError: + pass + + +def series_small_a(): + """Tylor series expansion of Phi(a, b, x) in a=0 up to order 5. + """ + order = 5 + a, b, x, k = symbols("a b x k") + A = [] # terms with a + X = [] # terms with x + B = [] # terms with b (polygammas) + # Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i]) + expression = Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity)) + expression = gamma(b)/sympy.exp(x) * expression + + # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0) + for n in range(0, order+1): + term = expression.diff(a, n).subs(a, 0).simplify().doit() + # set the whole bracket involving polygammas to 1 + x_part = (term.subs(polygamma(0, b), 1) + .replace(polygamma, lambda *args: 0)) + # sign convention: x part always positive + x_part *= (-1)**n + + A.append(a**n/factorial(n)) + X.append(horner(x_part)) + B.append(horner((term/x_part).simplify())) + + s = "Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.\n" + s += "Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)\n" + for name, c in zip(['A', 'X', 'B'], [A, X, B]): + for i in range(len(c)): + s += f"\n{name}[{i}] = " + str(c[i]) + return s + + +# expansion of digamma +def dg_series(z, n): + """Symbolic expansion of digamma(z) in z=0 to order n. + + See https://dlmf.nist.gov/5.7.E4 and with https://dlmf.nist.gov/5.5.E2 + """ + k = symbols("k") + return -1/z - EulerGamma + \ + sympy.summation((-1)**k * zeta(k) * z**(k-1), (k, 2, n+1)) + + +def pg_series(k, z, n): + """Symbolic expansion of polygamma(k, z) in z=0 to order n.""" + return sympy.diff(dg_series(z, n+k), z, k) + + +def series_small_a_small_b(): + """Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5. + + Be aware of cancellation of poles in b=0 of digamma(b)/Gamma(b) and + polygamma functions. + + digamma(b)/Gamma(b) = -1 - 2*M_EG*b + O(b^2) + digamma(b)^2/Gamma(b) = 1/b + 3*M_EG + b*(-5/12*PI^2+7/2*M_EG^2) + O(b^2) + polygamma(1, b)/Gamma(b) = 1/b + M_EG + b*(1/12*PI^2 + 1/2*M_EG^2) + O(b^2) + and so on. + """ + order = 5 + a, b, x, k = symbols("a b x k") + M_PI, M_EG, M_Z3 = symbols("M_PI M_EG M_Z3") + c_subs = {pi: M_PI, EulerGamma: M_EG, zeta(3): M_Z3} + A = [] # terms with a + X = [] # terms with x + B = [] # terms with b (polygammas expanded) + C = [] # terms that generate B + # Phi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i]) + # B[0] = 1 + # B[k] = sum(C[k] * b**k/k!, k=0..) + # Note: C[k] can be obtained from a series expansion of 1/gamma(b). + expression = gamma(b)/sympy.exp(x) * \ + Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity)) + + # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0) + for n in range(0, order+1): + term = expression.diff(a, n).subs(a, 0).simplify().doit() + # set the whole bracket involving polygammas to 1 + x_part = (term.subs(polygamma(0, b), 1) + .replace(polygamma, lambda *args: 0)) + # sign convention: x part always positive + x_part *= (-1)**n + # expansion of polygamma part with 1/gamma(b) + pg_part = term/x_part/gamma(b) + if n >= 1: + # Note: highest term is digamma^n + pg_part = pg_part.replace(polygamma, + lambda k, x: pg_series(k, x, order+1+n)) + pg_part = (pg_part.series(b, 0, n=order+1-n) + .removeO() + .subs(polygamma(2, 1), -2*zeta(3)) + .simplify() + ) + + A.append(a**n/factorial(n)) + X.append(horner(x_part)) + B.append(pg_part) + + # Calculate C and put in the k! + C = sympy.Poly(B[1].subs(c_subs), b).coeffs() + C.reverse() + for i in range(len(C)): + C[i] = (C[i] * factorial(i)).simplify() + + s = "Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5." + s += "\nPhi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i], i=0..5)\n" + s += "B[0] = 1\n" + s += "B[i] = sum(C[k+i-1] * b**k/k!, k=0..)\n" + s += "\nM_PI = pi" + s += "\nM_EG = EulerGamma" + s += "\nM_Z3 = zeta(3)" + for name, c in zip(['A', 'X'], [A, X]): + for i in range(len(c)): + s += f"\n{name}[{i}] = " + s += str(c[i]) + # For C, do also compute the values numerically + for i in range(len(C)): + s += f"\n# C[{i}] = " + s += str(C[i]) + s += f"\nC[{i}] = " + s += str(C[i].subs({M_EG: EulerGamma, M_PI: pi, M_Z3: zeta(3)}) + .evalf(17)) + + # Does B have the assumed structure? + s += "\n\nTest if B[i] does have the assumed structure." + s += "\nC[i] are derived from B[1] alone." + s += "\nTest B[2] == C[1] + b*C[2] + b^2/2*C[3] + b^3/6*C[4] + .." + test = sum([b**k/factorial(k) * C[k+1] for k in range(order-1)]) + test = (test - B[2].subs(c_subs)).simplify() + s += f"\ntest successful = {test==S(0)}" + s += "\nTest B[3] == C[2] + b*C[3] + b^2/2*C[4] + .." + test = sum([b**k/factorial(k) * C[k+2] for k in range(order-2)]) + test = (test - B[3].subs(c_subs)).simplify() + s += f"\ntest successful = {test==S(0)}" + return s + + +def asymptotic_series(): + """Asymptotic expansion for large x. + + Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k + Z = (a*x)^(1/(1+a)) + + Wright (1935) lists the coefficients C_0 and C_1 (he calls them a_0 and + a_1). With slightly different notation, Paris (2017) lists coefficients + c_k up to order k=3. + Paris (2017) uses ZP = (1+a)/a * Z (ZP = Z of Paris) and + C_k = C_0 * (-a/(1+a))^k * c_k + """ + order = 8 + + class g(sympy.Function): + """Helper function g according to Wright (1935) + + g(n, rho, v) = (1 + (rho+2)/3 * v + (rho+2)*(rho+3)/(2*3) * v^2 + ...) + + Note: Wright (1935) uses square root of above definition. + """ + nargs = 3 + + @classmethod + def eval(cls, n, rho, v): + if not n >= 0: + raise ValueError("must have n >= 0") + elif n == 0: + return 1 + else: + return g(n-1, rho, v) \ + + gammasimp(gamma(rho+2+n)/gamma(rho+2)) \ + / gammasimp(gamma(3+n)/gamma(3))*v**n + + class coef_C(sympy.Function): + """Calculate coefficients C_m for integer m. + + C_m is the coefficient of v^(2*m) in the Taylor expansion in v=0 of + Gamma(m+1/2)/(2*pi) * (2/(rho+1))^(m+1/2) * (1-v)^(-b) + * g(rho, v)^(-m-1/2) + """ + nargs = 3 + + @classmethod + def eval(cls, m, rho, beta): + if not m >= 0: + raise ValueError("must have m >= 0") + + v = symbols("v") + expression = (1-v)**(-beta) * g(2*m, rho, v)**(-m-Rational(1, 2)) + res = expression.diff(v, 2*m).subs(v, 0) / factorial(2*m) + res = res * (gamma(m + Rational(1, 2)) / (2*pi) + * (2/(rho+1))**(m + Rational(1, 2))) + return res + + # in order to have nice ordering/sorting of expressions, we set a = xa. + xa, b, xap1 = symbols("xa b xap1") + C0 = coef_C(0, xa, b) + # a1 = a(1, rho, beta) + s = "Asymptotic expansion for large x\n" + s += "Phi(a, b, x) = Z**(1/2-b) * exp((1+a)/a * Z) \n" + s += " * sum((-1)**k * C[k]/Z**k, k=0..6)\n\n" + s += "Z = pow(a * x, 1/(1+a))\n" + s += "A[k] = pow(a, k)\n" + s += "B[k] = pow(b, k)\n" + s += "Ap1[k] = pow(1+a, k)\n\n" + s += "C[0] = 1./sqrt(2. * M_PI * Ap1[1])\n" + for i in range(1, order+1): + expr = (coef_C(i, xa, b) / (C0/(1+xa)**i)).simplify() + factor = [x.denominator() for x in sympy.Poly(expr).coeffs()] + factor = sympy.lcm(factor) + expr = (expr * factor).simplify().collect(b, sympy.factor) + expr = expr.xreplace({xa+1: xap1}) + s += f"C[{i}] = C[0] / ({factor} * Ap1[{i}])\n" + s += f"C[{i}] *= {str(expr)}\n\n" + import re + re_a = re.compile(r'xa\*\*(\d+)') + s = re_a.sub(r'A[\1]', s) + re_b = re.compile(r'b\*\*(\d+)') + s = re_b.sub(r'B[\1]', s) + s = s.replace('xap1', 'Ap1[1]') + s = s.replace('xa', 'a') + # max integer = 2^31-1 = 2,147,483,647. Solution: Put a point after 10 + # or more digits. + re_digits = re.compile(r'(\d{10,})') + s = re_digits.sub(r'\1.', s) + return s + + +def optimal_epsilon_integral(): + """Fit optimal choice of epsilon for integral representation. + + The integrand of + int_0^pi P(eps, a, b, x, phi) * dphi + can exhibit oscillatory behaviour. It stems from the cosine of P and can be + minimized by minimizing the arc length of the argument + f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a * phi) + (1 - b) * phi + of cos(f(phi)). + We minimize the arc length in eps for a grid of values (a, b, x) and fit a + parametric function to it. + """ + def fp(eps, a, b, x, phi): + """Derivative of f w.r.t. phi.""" + eps_a = np.power(1. * eps, -a) + return eps * np.cos(phi) - a * x * eps_a * np.cos(a * phi) + 1 - b + + def arclength(eps, a, b, x, epsrel=1e-2, limit=100): + """Compute Arc length of f. + + Note that the arc length of a function f from t0 to t1 is given by + int_t0^t1 sqrt(1 + f'(t)^2) dt + """ + return quad(lambda phi: np.sqrt(1 + fp(eps, a, b, x, phi)**2), + 0, np.pi, + epsrel=epsrel, limit=100)[0] + + # grid of minimal arc length values + data_a = [1e-3, 0.1, 0.5, 0.9, 1, 2, 4, 5, 6, 8] + data_b = [0, 1, 4, 7, 10] + data_x = [1, 1.5, 2, 4, 10, 20, 50, 100, 200, 500, 1e3, 5e3, 1e4] + data_a, data_b, data_x = np.meshgrid(data_a, data_b, data_x) + data_a, data_b, data_x = (data_a.flatten(), data_b.flatten(), + data_x.flatten()) + best_eps = [] + for i in range(data_x.size): + best_eps.append( + minimize_scalar(lambda eps: arclength(eps, data_a[i], data_b[i], + data_x[i]), + bounds=(1e-3, 1000), + method='Bounded', options={'xatol': 1e-3}).x + ) + best_eps = np.array(best_eps) + # pandas would be nice, but here a dictionary is enough + df = {'a': data_a, + 'b': data_b, + 'x': data_x, + 'eps': best_eps, + } + + def func(data, A0, A1, A2, A3, A4, A5): + """Compute parametric function to fit.""" + a = data['a'] + b = data['b'] + x = data['x'] + return (A0 * b * np.exp(-0.5 * a) + + np.exp(A1 + 1 / (1 + a) * np.log(x) - A2 * np.exp(-A3 * a) + + A4 / (1 + np.exp(A5 * a)))) + + func_params = list(curve_fit(func, df, df['eps'], method='trf')[0]) + + s = "Fit optimal eps for integrand P via minimal arc length\n" + s += "with parametric function:\n" + s += "optimal_eps = (A0 * b * exp(-a/2) + exp(A1 + 1 / (1 + a) * log(x)\n" + s += " - A2 * exp(-A3 * a) + A4 / (1 + exp(A5 * a)))\n\n" + s += "Fitted parameters A0 to A5 are:\n" + s += ', '.join([f'{x:.5g}' for x in func_params]) + return s + + +def main(): + t0 = time() + parser = ArgumentParser(description=__doc__, + formatter_class=RawTextHelpFormatter) + parser.add_argument('action', type=int, choices=[1, 2, 3, 4], + help='chose what expansion to precompute\n' + '1 : Series for small a\n' + '2 : Series for small a and small b\n' + '3 : Asymptotic series for large x\n' + ' This may take some time (>4h).\n' + '4 : Fit optimal eps for integral representation.' + ) + args = parser.parse_args() + + switch = {1: lambda: print(series_small_a()), + 2: lambda: print(series_small_a_small_b()), + 3: lambda: print(asymptotic_series()), + 4: lambda: print(optimal_epsilon_integral()) + } + switch.get(args.action, lambda: print("Invalid input."))() + print(f"\n{(time() - t0)/60:.1f} minutes elapsed.\n") + + +if __name__ == '__main__': + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py new file mode 100644 index 0000000000000000000000000000000000000000..1de9b4fe552ca9178c452194ab84af6ca5daac71 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py @@ -0,0 +1,152 @@ +"""Compute a grid of values for Wright's generalized Bessel function +and save the values to data files for use in tests. Using mpmath directly in +tests would take too long. + +This takes about 10 minutes to run on a 2.7 GHz i7 Macbook Pro. +""" +from functools import lru_cache +import os +from time import time + +import numpy as np +from scipy.special._mptestutils import mpf2float + +try: + import mpmath as mp +except ImportError: + pass + +# exp_inf: smallest value x for which exp(x) == inf +exp_inf = 709.78271289338403 + + +# 64 Byte per value +@lru_cache(maxsize=100_000) +def rgamma_cached(x, dps): + with mp.workdps(dps): + return mp.rgamma(x) + + +def mp_wright_bessel(a, b, x, dps=50, maxterms=2000): + """Compute Wright's generalized Bessel function as Series with mpmath. + """ + with mp.workdps(dps): + a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x) + res = mp.nsum(lambda k: x**k / mp.fac(k) + * rgamma_cached(a * k + b, dps=dps), + [0, mp.inf], + tol=dps, method='s', steps=[maxterms] + ) + return mpf2float(res) + + +def main(): + t0 = time() + print(__doc__) + pwd = os.path.dirname(__file__) + eps = np.finfo(float).eps * 100 + + a_range = np.array([eps, + 1e-4 * (1 - eps), 1e-4, 1e-4 * (1 + eps), + 1e-3 * (1 - eps), 1e-3, 1e-3 * (1 + eps), + 0.1, 0.5, + 1 * (1 - eps), 1, 1 * (1 + eps), + 1.5, 2, 4.999, 5, 10]) + b_range = np.array([0, eps, 1e-10, 1e-5, 0.1, 1, 2, 10, 20, 100]) + x_range = np.array([0, eps, 1 - eps, 1, 1 + eps, + 1.5, + 2 - eps, 2, 2 + eps, + 9 - eps, 9, 9 + eps, + 10 * (1 - eps), 10, 10 * (1 + eps), + 100 * (1 - eps), 100, 100 * (1 + eps), + 500, exp_inf, 1e3, 1e5, 1e10, 1e20]) + + a_range, b_range, x_range = np.meshgrid(a_range, b_range, x_range, + indexing='ij') + a_range = a_range.flatten() + b_range = b_range.flatten() + x_range = x_range.flatten() + + # filter out some values, especially too large x + bool_filter = ~((a_range < 5e-3) & (x_range >= exp_inf)) + bool_filter = bool_filter & ~((a_range < 0.2) & (x_range > exp_inf)) + bool_filter = bool_filter & ~((a_range < 0.5) & (x_range > 1e3)) + bool_filter = bool_filter & ~((a_range < 0.56) & (x_range > 5e3)) + bool_filter = bool_filter & ~((a_range < 1) & (x_range > 1e4)) + bool_filter = bool_filter & ~((a_range < 1.4) & (x_range > 1e5)) + bool_filter = bool_filter & ~((a_range < 1.8) & (x_range > 1e6)) + bool_filter = bool_filter & ~((a_range < 2.2) & (x_range > 1e7)) + bool_filter = bool_filter & ~((a_range < 2.5) & (x_range > 1e8)) + bool_filter = bool_filter & ~((a_range < 2.9) & (x_range > 1e9)) + bool_filter = bool_filter & ~((a_range < 3.3) & (x_range > 1e10)) + bool_filter = bool_filter & ~((a_range < 3.7) & (x_range > 1e11)) + bool_filter = bool_filter & ~((a_range < 4) & (x_range > 1e12)) + bool_filter = bool_filter & ~((a_range < 4.4) & (x_range > 1e13)) + bool_filter = bool_filter & ~((a_range < 4.7) & (x_range > 1e14)) + bool_filter = bool_filter & ~((a_range < 5.1) & (x_range > 1e15)) + bool_filter = bool_filter & ~((a_range < 5.4) & (x_range > 1e16)) + bool_filter = bool_filter & ~((a_range < 5.8) & (x_range > 1e17)) + bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18)) + bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18)) + bool_filter = bool_filter & ~((a_range < 6.5) & (x_range > 1e19)) + bool_filter = bool_filter & ~((a_range < 6.9) & (x_range > 1e20)) + + # filter out known values that do not meet the required numerical accuracy + # see test test_wright_data_grid_failures + failing = np.array([ + [0.1, 100, 709.7827128933841], + [0.5, 10, 709.7827128933841], + [0.5, 10, 1000], + [0.5, 100, 1000], + [1, 20, 100000], + [1, 100, 100000], + [1.0000000000000222, 20, 100000], + [1.0000000000000222, 100, 100000], + [1.5, 0, 500], + [1.5, 2.220446049250313e-14, 500], + [1.5, 1.e-10, 500], + [1.5, 1.e-05, 500], + [1.5, 0.1, 500], + [1.5, 20, 100000], + [1.5, 100, 100000], + ]).tolist() + + does_fail = np.full_like(a_range, False, dtype=bool) + for i in range(x_range.size): + if [a_range[i], b_range[i], x_range[i]] in failing: + does_fail[i] = True + + # filter and flatten + a_range = a_range[bool_filter] + b_range = b_range[bool_filter] + x_range = x_range[bool_filter] + does_fail = does_fail[bool_filter] + + dataset = [] + print(f"Computing {x_range.size} single points.") + print("Tests will fail for the following data points:") + for i in range(x_range.size): + a = a_range[i] + b = b_range[i] + x = x_range[i] + # take care of difficult corner cases + maxterms = 1000 + if a < 1e-6 and x >= exp_inf/10: + maxterms = 2000 + f = mp_wright_bessel(a, b, x, maxterms=maxterms) + if does_fail[i]: + print("failing data point a, b, x, value = " + f"[{a}, {b}, {x}, {f}]") + else: + dataset.append((a, b, x, f)) + dataset = np.array(dataset) + + filename = os.path.join(pwd, '..', 'tests', 'data', 'local', + 'wright_bessel.txt') + np.savetxt(filename, dataset) + + print(f"{(time() - t0)/60:.1f} minutes elapsed") + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcd0345a9c1b90c45b0e9e3340ab4da4ec5c6d7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py @@ -0,0 +1,41 @@ +import numpy as np + +try: + import mpmath +except ImportError: + pass + + +def mpmath_wrightomega(x): + return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5')) + + +def wrightomega_series_error(x): + series = x + desired = mpmath_wrightomega(x) + return abs(series - desired) / desired + + +def wrightomega_exp_error(x): + exponential_approx = mpmath.exp(x) + desired = mpmath_wrightomega(x) + return abs(exponential_approx - desired) / desired + + +def main(): + desired_error = 2 * np.finfo(float).eps + print('Series Error') + for x in [1e5, 1e10, 1e15, 1e20]: + with mpmath.workdps(100): + error = wrightomega_series_error(x) + print(x, error, error < desired_error) + + print('Exp error') + for x in [-10, -25, -50, -100, -200, -400, -700, -740]: + with mpmath.workdps(100): + error = wrightomega_exp_error(x) + print(x, error, error < desired_error) + + +if __name__ == '__main__': + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py new file mode 100644 index 0000000000000000000000000000000000000000..d408b1a2fffb6872287452923fcc9394adc13a7c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py @@ -0,0 +1,27 @@ +"""Compute the Taylor series for zeta(x) - 1 around x = 0.""" +try: + import mpmath +except ImportError: + pass + + +def zetac_series(N): + coeffs = [] + with mpmath.workdps(100): + coeffs.append(-1.5) + for n in range(1, N): + coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n) + coeffs.append(coeff) + return coeffs + + +def main(): + print(__doc__) + coeffs = zetac_series(10) + coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in coeffs] + print("\n".join(coeffs[::-1])) + + +if __name__ == '__main__': + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py new file mode 100644 index 0000000000000000000000000000000000000000..e1edc9800759dfda9e49bde1becc775a64bce958 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py @@ -0,0 +1,15 @@ +"""Warnings and Exceptions that can be raised by special functions.""" +import warnings + + +class SpecialFunctionWarning(Warning): + """Warning that can be emitted by special functions.""" + pass + + +warnings.simplefilter("always", category=SpecialFunctionWarning) + + +class SpecialFunctionError(Exception): + """Exception that can be raised by special functions.""" + pass diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..2525eceb47ec2b20b45ca693e19e741f4a666597 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py @@ -0,0 +1,106 @@ +# Last Change: Sat Mar 21 02:00 PM 2009 J + +# Copyright (c) 2001, 2002 Enthought, Inc. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# a. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# b. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# c. Neither the name of the Enthought nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. + +"""Some more special functions which may be useful for multivariate statistical +analysis.""" + +import numpy as np +from scipy.special import gammaln as loggam + + +__all__ = ['multigammaln'] + + +def multigammaln(a, d): + r"""Returns the log of multivariate gamma, also sometimes called the + generalized gamma. + + Parameters + ---------- + a : ndarray + The multivariate gamma is computed for each item of `a`. + d : int + The dimension of the space of integration. + + Returns + ------- + res : ndarray + The values of the log multivariate gamma at the given points `a`. + + Notes + ----- + The formal definition of the multivariate gamma of dimension d for a real + `a` is + + .. math:: + + \Gamma_d(a) = \int_{A>0} e^{-tr(A)} |A|^{a - (d+1)/2} dA + + with the condition :math:`a > (d-1)/2`, and :math:`A > 0` being the set of + all the positive definite matrices of dimension `d`. Note that `a` is a + scalar: the integrand only is multivariate, the argument is not (the + function is defined over a subset of the real set). + + This can be proven to be equal to the much friendlier equation + + .. math:: + + \Gamma_d(a) = \pi^{d(d-1)/4} \prod_{i=1}^{d} \Gamma(a - (i-1)/2). + + References + ---------- + R. J. Muirhead, Aspects of multivariate statistical theory (Wiley Series in + probability and mathematical statistics). + + Examples + -------- + >>> import numpy as np + >>> from scipy.special import multigammaln, gammaln + >>> a = 23.5 + >>> d = 10 + >>> multigammaln(a, d) + 454.1488605074416 + + Verify that the result agrees with the logarithm of the equation + shown above: + + >>> d*(d-1)/4*np.log(np.pi) + gammaln(a - 0.5*np.arange(0, d)).sum() + 454.1488605074416 + """ + a = np.asarray(a) + if not np.isscalar(d) or (np.floor(d) != d): + raise ValueError("d should be a positive integer (dimension)") + if np.any(a <= 0.5 * (d - 1)): + raise ValueError(f"condition a ({a:f}) > 0.5 * (d-1) ({0.5 * (d-1):f}) not met") + + res = (d * (d-1) * 0.25) * np.log(np.pi) + res += np.sum(loggam([(a - (j - 1.)/2) for j in range(1, d+1)]), axis=0) + return res diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..f3d871fcd07ef092962a4594cf780445daae4458 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py @@ -0,0 +1,397 @@ +from functools import wraps +from scipy._lib._util import _lazywhere +import numpy as np +from ._ufuncs import (_spherical_jn, _spherical_yn, _spherical_in, + _spherical_kn, _spherical_jn_d, _spherical_yn_d, + _spherical_in_d, _spherical_kn_d) + + +def use_reflection(sign_n_even=None, reflection_fun=None): + # - If reflection_fun is not specified, reflects negative `z` and multiplies + # output by appropriate sign (indicated by `sign_n_even`). + # - If reflection_fun is specified, calls `reflection_fun` instead of `fun`. + # See DLMF 10.47(v) https://dlmf.nist.gov/10.47 + def decorator(fun): + def standard_reflection(n, z, derivative): + # sign_n_even indicates the sign when the order `n` is even + sign = np.where(n % 2 == 0, sign_n_even, -sign_n_even) + # By the chain rule, differentiation at `-z` adds a minus sign + sign = -sign if derivative else sign + # Evaluate at positive z (minus negative z) and adjust the sign + return fun(n, -z, derivative) * sign + + @wraps(fun) + def wrapper(n, z, derivative=False): + z = np.asarray(z) + + if np.issubdtype(z.dtype, np.complexfloating): + return fun(n, z, derivative) # complex dtype just works + + f2 = standard_reflection if reflection_fun is None else reflection_fun + return _lazywhere(z.real >= 0, (n, z), + f=lambda n, z: fun(n, z, derivative), + f2=lambda n, z: f2(n, z, derivative))[()] + return wrapper + return decorator + + +@use_reflection(+1) # See DLMF 10.47(v) https://dlmf.nist.gov/10.47 +def spherical_jn(n, z, derivative=False): + r"""Spherical Bessel function of the first kind or its derivative. + + Defined as [1]_, + + .. math:: j_n(z) = \sqrt{\frac{\pi}{2z}} J_{n + 1/2}(z), + + where :math:`J_n` is the Bessel function of the first kind. + + Parameters + ---------- + n : int, array_like + Order of the Bessel function (n >= 0). + z : complex or float, array_like + Argument of the Bessel function. + derivative : bool, optional + If True, the value of the derivative (rather than the function + itself) is returned. + + Returns + ------- + jn : ndarray + + Notes + ----- + For real arguments greater than the order, the function is computed + using the ascending recurrence [2]_. For small real or complex + arguments, the definitional relation to the cylindrical Bessel function + of the first kind is used. + + The derivative is computed using the relations [3]_, + + .. math:: + j_n'(z) = j_{n-1}(z) - \frac{n + 1}{z} j_n(z). + + j_0'(z) = -j_1(z) + + + .. versionadded:: 0.18.0 + + References + ---------- + .. [1] https://dlmf.nist.gov/10.47.E3 + .. [2] https://dlmf.nist.gov/10.51.E1 + .. [3] https://dlmf.nist.gov/10.51.E2 + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + The spherical Bessel functions of the first kind :math:`j_n` accept + both real and complex second argument. They can return a complex type: + + >>> from scipy.special import spherical_jn + >>> spherical_jn(0, 3+5j) + (-9.878987731663194-8.021894345786002j) + >>> type(spherical_jn(0, 3+5j)) + + + We can verify the relation for the derivative from the Notes + for :math:`n=3` in the interval :math:`[1, 2]`: + + >>> import numpy as np + >>> x = np.arange(1.0, 2.0, 0.01) + >>> np.allclose(spherical_jn(3, x, True), + ... spherical_jn(2, x) - 4/x * spherical_jn(3, x)) + True + + The first few :math:`j_n` with real argument: + + >>> import matplotlib.pyplot as plt + >>> x = np.arange(0.0, 10.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-0.5, 1.5) + >>> ax.set_title(r'Spherical Bessel functions $j_n$') + >>> for n in np.arange(0, 4): + ... ax.plot(x, spherical_jn(n, x), label=rf'$j_{n}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + n = np.asarray(n, dtype=np.dtype("long")) + if derivative: + return _spherical_jn_d(n, z) + else: + return _spherical_jn(n, z) + + +@use_reflection(-1) # See DLMF 10.47(v) https://dlmf.nist.gov/10.47 +def spherical_yn(n, z, derivative=False): + r"""Spherical Bessel function of the second kind or its derivative. + + Defined as [1]_, + + .. math:: y_n(z) = \sqrt{\frac{\pi}{2z}} Y_{n + 1/2}(z), + + where :math:`Y_n` is the Bessel function of the second kind. + + Parameters + ---------- + n : int, array_like + Order of the Bessel function (n >= 0). + z : complex or float, array_like + Argument of the Bessel function. + derivative : bool, optional + If True, the value of the derivative (rather than the function + itself) is returned. + + Returns + ------- + yn : ndarray + + Notes + ----- + For real arguments, the function is computed using the ascending + recurrence [2]_. For complex arguments, the definitional relation to + the cylindrical Bessel function of the second kind is used. + + The derivative is computed using the relations [3]_, + + .. math:: + y_n' = y_{n-1} - \frac{n + 1}{z} y_n. + + y_0' = -y_1 + + + .. versionadded:: 0.18.0 + + References + ---------- + .. [1] https://dlmf.nist.gov/10.47.E4 + .. [2] https://dlmf.nist.gov/10.51.E1 + .. [3] https://dlmf.nist.gov/10.51.E2 + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + The spherical Bessel functions of the second kind :math:`y_n` accept + both real and complex second argument. They can return a complex type: + + >>> from scipy.special import spherical_yn + >>> spherical_yn(0, 3+5j) + (8.022343088587197-9.880052589376795j) + >>> type(spherical_yn(0, 3+5j)) + + + We can verify the relation for the derivative from the Notes + for :math:`n=3` in the interval :math:`[1, 2]`: + + >>> import numpy as np + >>> x = np.arange(1.0, 2.0, 0.01) + >>> np.allclose(spherical_yn(3, x, True), + ... spherical_yn(2, x) - 4/x * spherical_yn(3, x)) + True + + The first few :math:`y_n` with real argument: + + >>> import matplotlib.pyplot as plt + >>> x = np.arange(0.0, 10.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-2.0, 1.0) + >>> ax.set_title(r'Spherical Bessel functions $y_n$') + >>> for n in np.arange(0, 4): + ... ax.plot(x, spherical_yn(n, x), label=rf'$y_{n}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + n = np.asarray(n, dtype=np.dtype("long")) + if derivative: + return _spherical_yn_d(n, z) + else: + return _spherical_yn(n, z) + + +@use_reflection(+1) # See DLMF 10.47(v) https://dlmf.nist.gov/10.47 +def spherical_in(n, z, derivative=False): + r"""Modified spherical Bessel function of the first kind or its derivative. + + Defined as [1]_, + + .. math:: i_n(z) = \sqrt{\frac{\pi}{2z}} I_{n + 1/2}(z), + + where :math:`I_n` is the modified Bessel function of the first kind. + + Parameters + ---------- + n : int, array_like + Order of the Bessel function (n >= 0). + z : complex or float, array_like + Argument of the Bessel function. + derivative : bool, optional + If True, the value of the derivative (rather than the function + itself) is returned. + + Returns + ------- + in : ndarray + + Notes + ----- + The function is computed using its definitional relation to the + modified cylindrical Bessel function of the first kind. + + The derivative is computed using the relations [2]_, + + .. math:: + i_n' = i_{n-1} - \frac{n + 1}{z} i_n. + + i_1' = i_0 + + + .. versionadded:: 0.18.0 + + References + ---------- + .. [1] https://dlmf.nist.gov/10.47.E7 + .. [2] https://dlmf.nist.gov/10.51.E5 + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + The modified spherical Bessel functions of the first kind :math:`i_n` + accept both real and complex second argument. + They can return a complex type: + + >>> from scipy.special import spherical_in + >>> spherical_in(0, 3+5j) + (-1.1689867793369182-1.2697305267234222j) + >>> type(spherical_in(0, 3+5j)) + + + We can verify the relation for the derivative from the Notes + for :math:`n=3` in the interval :math:`[1, 2]`: + + >>> import numpy as np + >>> x = np.arange(1.0, 2.0, 0.01) + >>> np.allclose(spherical_in(3, x, True), + ... spherical_in(2, x) - 4/x * spherical_in(3, x)) + True + + The first few :math:`i_n` with real argument: + + >>> import matplotlib.pyplot as plt + >>> x = np.arange(0.0, 6.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(-0.5, 5.0) + >>> ax.set_title(r'Modified spherical Bessel functions $i_n$') + >>> for n in np.arange(0, 4): + ... ax.plot(x, spherical_in(n, x), label=rf'$i_{n}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + n = np.asarray(n, dtype=np.dtype("long")) + if derivative: + return _spherical_in_d(n, z) + else: + return _spherical_in(n, z) + + +def spherical_kn_reflection(n, z, derivative=False): + # More complex than the other cases, and this will likely be re-implemented + # in C++ anyway. Would require multiple function evaluations. Probably about + # as fast to just resort to complex math, and much simpler. + return spherical_kn(n, z + 0j, derivative=derivative).real + + +@use_reflection(reflection_fun=spherical_kn_reflection) +def spherical_kn(n, z, derivative=False): + r"""Modified spherical Bessel function of the second kind or its derivative. + + Defined as [1]_, + + .. math:: k_n(z) = \sqrt{\frac{\pi}{2z}} K_{n + 1/2}(z), + + where :math:`K_n` is the modified Bessel function of the second kind. + + Parameters + ---------- + n : int, array_like + Order of the Bessel function (n >= 0). + z : complex or float, array_like + Argument of the Bessel function. + derivative : bool, optional + If True, the value of the derivative (rather than the function + itself) is returned. + + Returns + ------- + kn : ndarray + + Notes + ----- + The function is computed using its definitional relation to the + modified cylindrical Bessel function of the second kind. + + The derivative is computed using the relations [2]_, + + .. math:: + k_n' = -k_{n-1} - \frac{n + 1}{z} k_n. + + k_0' = -k_1 + + + .. versionadded:: 0.18.0 + + References + ---------- + .. [1] https://dlmf.nist.gov/10.47.E9 + .. [2] https://dlmf.nist.gov/10.51.E5 + .. [AS] Milton Abramowitz and Irene A. Stegun, eds. + Handbook of Mathematical Functions with Formulas, + Graphs, and Mathematical Tables. New York: Dover, 1972. + + Examples + -------- + The modified spherical Bessel functions of the second kind :math:`k_n` + accept both real and complex second argument. + They can return a complex type: + + >>> from scipy.special import spherical_kn + >>> spherical_kn(0, 3+5j) + (0.012985785614001561+0.003354691603137546j) + >>> type(spherical_kn(0, 3+5j)) + + + We can verify the relation for the derivative from the Notes + for :math:`n=3` in the interval :math:`[1, 2]`: + + >>> import numpy as np + >>> x = np.arange(1.0, 2.0, 0.01) + >>> np.allclose(spherical_kn(3, x, True), + ... - 4/x * spherical_kn(3, x) - spherical_kn(2, x)) + True + + The first few :math:`k_n` with real argument: + + >>> import matplotlib.pyplot as plt + >>> x = np.arange(0.0, 4.0, 0.01) + >>> fig, ax = plt.subplots() + >>> ax.set_ylim(0.0, 5.0) + >>> ax.set_title(r'Modified spherical Bessel functions $k_n$') + >>> for n in np.arange(0, 4): + ... ax.plot(x, spherical_kn(n, x), label=rf'$k_{n}$') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + n = np.asarray(n, dtype=np.dtype("long")) + if derivative: + return _spherical_kn_d(n, z) + else: + return _spherical_kn(n, z) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..3f5101198cebcbb5138e88a2050a5c4d7a115d60 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py @@ -0,0 +1,202 @@ +import os +import sys +import functools + +import numpy as np +from scipy._lib._array_api import ( + array_namespace, scipy_namespace_for, is_numpy +) +from . import _ufuncs +# These don't really need to be imported, but otherwise IDEs might not realize +# that these are defined in this file / report an error in __init__.py +from ._ufuncs import ( + log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln, # noqa: F401 + gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy, # noqa: F401 + chdtr, chdtrc, betainc, betaincc, stdtr # noqa: F401 +) + +_SCIPY_ARRAY_API = os.environ.get("SCIPY_ARRAY_API", False) +array_api_compat_prefix = "scipy._lib.array_api_compat" + + +def get_array_special_func(f_name, xp, n_array_args): + spx = scipy_namespace_for(xp) + f = None + if is_numpy(xp): + f = getattr(_ufuncs, f_name, None) + elif spx is not None: + f = getattr(spx.special, f_name, None) + + if f is not None: + return f + + # if generic array-API implementation is available, use that; + # otherwise, fall back to NumPy/SciPy + if f_name in _generic_implementations: + _f = _generic_implementations[f_name](xp=xp, spx=spx) + if _f is not None: + return _f + + _f = getattr(_ufuncs, f_name, None) + def __f(*args, _f=_f, _xp=xp, **kwargs): + array_args = args[:n_array_args] + other_args = args[n_array_args:] + array_args = [np.asarray(arg) for arg in array_args] + out = _f(*array_args, *other_args, **kwargs) + return _xp.asarray(out) + + return __f + + +def _get_shape_dtype(*args, xp): + args = xp.broadcast_arrays(*args) + shape = args[0].shape + dtype = xp.result_type(*args) + if xp.isdtype(dtype, 'integral'): + dtype = xp.float64 + args = [xp.asarray(arg, dtype=dtype) for arg in args] + return args, shape, dtype + + +def _rel_entr(xp, spx): + def __rel_entr(x, y, *, xp=xp): + args, shape, dtype = _get_shape_dtype(x, y, xp=xp) + x, y = args + res = xp.full(x.shape, xp.inf, dtype=dtype) + res[(x == 0) & (y >= 0)] = xp.asarray(0, dtype=dtype) + i = (x > 0) & (y > 0) + res[i] = x[i] * (xp.log(x[i]) - xp.log(y[i])) + return res + return __rel_entr + + +def _xlogy(xp, spx): + def __xlogy(x, y, *, xp=xp): + with np.errstate(divide='ignore', invalid='ignore'): + temp = x * xp.log(y) + return xp.where(x == 0., xp.asarray(0., dtype=temp.dtype), temp) + return __xlogy + + +def _chdtr(xp, spx): + # The difference between this and just using `gammainc` + # defined by `get_array_special_func` is that if `gammainc` + # isn't found, we don't want to use the SciPy version; we'll + # return None here and use the SciPy version of `chdtr`. + gammainc = getattr(spx.special, 'gammainc', None) if spx else None # noqa: F811 + if gammainc is None and hasattr(xp, 'special'): + gammainc = getattr(xp.special, 'gammainc', None) + if gammainc is None: + return None + + def __chdtr(v, x): + res = gammainc(v / 2, x / 2) # this is almost all we need + # The rest can be removed when google/jax#20507 is resolved + mask = (v == 0) & (x > 0) # JAX returns NaN + res = xp.where(mask, 1., res) + mask = xp.isinf(v) & xp.isinf(x) # JAX returns 1.0 + return xp.where(mask, xp.nan, res) + return __chdtr + + +def _chdtrc(xp, spx): + # The difference between this and just using `gammaincc` + # defined by `get_array_special_func` is that if `gammaincc` + # isn't found, we don't want to use the SciPy version; we'll + # return None here and use the SciPy version of `chdtrc`. + gammaincc = getattr(spx.special, 'gammaincc', None) if spx else None # noqa: F811 + if gammaincc is None and hasattr(xp, 'special'): + gammaincc = getattr(xp.special, 'gammaincc', None) + if gammaincc is None: + return None + + def __chdtrc(v, x): + res = xp.where(x >= 0, gammaincc(v/2, x/2), 1) + i_nan = ((x == 0) & (v == 0)) | xp.isnan(x) | xp.isnan(v) | (v <= 0) + res = xp.where(i_nan, xp.nan, res) + return res + return __chdtrc + + +def _betaincc(xp, spx): + betainc = getattr(spx.special, 'betainc', None) if spx else None # noqa: F811 + if betainc is None and hasattr(xp, 'special'): + betainc = getattr(xp.special, 'betainc', None) + if betainc is None: + return None + + def __betaincc(a, b, x): + # not perfect; might want to just rely on SciPy + return betainc(b, a, 1-x) + return __betaincc + + +def _stdtr(xp, spx): + betainc = getattr(spx.special, 'betainc', None) if spx else None # noqa: F811 + if betainc is None and hasattr(xp, 'special'): + betainc = getattr(xp.special, 'betainc', None) + if betainc is None: + return None + + def __stdtr(df, t): + x = df / (t ** 2 + df) + tail = betainc(df / 2, 0.5, x) / 2 + return xp.where(t < 0, tail, 1 - tail) + + return __stdtr + + +_generic_implementations = {'rel_entr': _rel_entr, + 'xlogy': _xlogy, + 'chdtr': _chdtr, + 'chdtrc': _chdtrc, + 'betaincc': _betaincc, + 'stdtr': _stdtr, + } + + +# functools.wraps doesn't work because: +# 'numpy.ufunc' object has no attribute '__module__' +def support_alternative_backends(f_name, n_array_args): + func = getattr(_ufuncs, f_name) + + @functools.wraps(func) + def wrapped(*args, **kwargs): + xp = array_namespace(*args[:n_array_args]) + f = get_array_special_func(f_name, xp, n_array_args) + return f(*args, **kwargs) + + return wrapped + + +array_special_func_map = { + 'log_ndtr': 1, + 'ndtr': 1, + 'ndtri': 1, + 'erf': 1, + 'erfc': 1, + 'i0': 1, + 'i0e': 1, + 'i1': 1, + 'i1e': 1, + 'gammaln': 1, + 'gammainc': 2, + 'gammaincc': 2, + 'logit': 1, + 'expit': 1, + 'entr': 1, + 'rel_entr': 2, + 'xlogy': 2, + 'chdtr': 2, + 'chdtrc': 2, + 'betainc': 3, + 'betaincc': 3, + 'stdtr': 2, +} + +for f_name, n_array_args in array_special_func_map.items(): + f = (support_alternative_backends(f_name, n_array_args) if _SCIPY_ARRAY_API + else getattr(_ufuncs, f_name)) + sys.modules[__name__].__dict__[f_name] = f + +__all__ = list(array_special_func_map) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1e6c272f16fa2bd3ae75af412bc6ae3270158ce4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi @@ -0,0 +1,9 @@ +import numpy as np + +def have_fenv() -> bool: ... +def random_double(size: int, rng: np.random.RandomState) -> np.float64: ... +def test_add_round(size: int, mode: str, rng: np.random.RandomState): ... + +def _dd_exp(xhi: float, xlo: float) -> tuple[float, float]: ... +def _dd_log(xhi: float, xlo: float) -> tuple[float, float]: ... +def _dd_expm1(xhi: float, xlo: float) -> tuple[float, float]: ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py new file mode 100644 index 0000000000000000000000000000000000000000..b0c2bd3053d076aacfa8be1d53cd851443fd8821 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py @@ -0,0 +1,321 @@ +import os +import functools +import operator +from scipy._lib import _pep440 + +import numpy as np +from numpy.testing import assert_ +import pytest + +import scipy.special as sc + +__all__ = ['with_special_errors', 'assert_func_equal', 'FuncData'] + + +#------------------------------------------------------------------------------ +# Check if a module is present to be used in tests +#------------------------------------------------------------------------------ + +class MissingModule: + def __init__(self, name): + self.name = name + + +def check_version(module, min_ver): + if type(module) is MissingModule: + return pytest.mark.skip(reason=f"{module.name} is not installed") + return pytest.mark.skipif( + _pep440.parse(module.__version__) < _pep440.Version(min_ver), + reason=f"{module.__name__} version >= {min_ver} required" + ) + + +#------------------------------------------------------------------------------ +# Enable convergence and loss of precision warnings -- turn off one by one +#------------------------------------------------------------------------------ + +def with_special_errors(func): + """ + Enable special function errors (such as underflow, overflow, + loss of precision, etc.) + """ + @functools.wraps(func) + def wrapper(*a, **kw): + with sc.errstate(all='raise'): + res = func(*a, **kw) + return res + return wrapper + + +#------------------------------------------------------------------------------ +# Comparing function values at many data points at once, with helpful +# error reports +#------------------------------------------------------------------------------ + +def assert_func_equal(func, results, points, rtol=None, atol=None, + param_filter=None, knownfailure=None, + vectorized=True, dtype=None, nan_ok=False, + ignore_inf_sign=False, distinguish_nan_and_inf=True): + if hasattr(points, 'next'): + # it's a generator + points = list(points) + + points = np.asarray(points) + if points.ndim == 1: + points = points[:,None] + nparams = points.shape[1] + + if hasattr(results, '__name__'): + # function + data = points + result_columns = None + result_func = results + else: + # dataset + data = np.c_[points, results] + result_columns = list(range(nparams, data.shape[1])) + result_func = None + + fdata = FuncData(func, data, list(range(nparams)), + result_columns=result_columns, result_func=result_func, + rtol=rtol, atol=atol, param_filter=param_filter, + knownfailure=knownfailure, nan_ok=nan_ok, vectorized=vectorized, + ignore_inf_sign=ignore_inf_sign, + distinguish_nan_and_inf=distinguish_nan_and_inf) + fdata.check() + + +class FuncData: + """ + Data set for checking a special function. + + Parameters + ---------- + func : function + Function to test + data : numpy array + columnar data to use for testing + param_columns : int or tuple of ints + Columns indices in which the parameters to `func` lie. + Can be imaginary integers to indicate that the parameter + should be cast to complex. + result_columns : int or tuple of ints, optional + Column indices for expected results from `func`. + result_func : callable, optional + Function to call to obtain results. + rtol : float, optional + Required relative tolerance. Default is 5*eps. + atol : float, optional + Required absolute tolerance. Default is 5*tiny. + param_filter : function, or tuple of functions/Nones, optional + Filter functions to exclude some parameter ranges. + If omitted, no filtering is done. + knownfailure : str, optional + Known failure error message to raise when the test is run. + If omitted, no exception is raised. + nan_ok : bool, optional + If nan is always an accepted result. + vectorized : bool, optional + Whether all functions passed in are vectorized. + ignore_inf_sign : bool, optional + Whether to ignore signs of infinities. + (Doesn't matter for complex-valued functions.) + distinguish_nan_and_inf : bool, optional + If True, treat numbers which contain nans or infs as + equal. Sets ignore_inf_sign to be True. + + """ + + def __init__(self, func, data, param_columns, result_columns=None, + result_func=None, rtol=None, atol=None, param_filter=None, + knownfailure=None, dataname=None, nan_ok=False, vectorized=True, + ignore_inf_sign=False, distinguish_nan_and_inf=True): + self.func = func + self.data = data + self.dataname = dataname + if not hasattr(param_columns, '__len__'): + param_columns = (param_columns,) + self.param_columns = tuple(param_columns) + if result_columns is not None: + if not hasattr(result_columns, '__len__'): + result_columns = (result_columns,) + self.result_columns = tuple(result_columns) + if result_func is not None: + message = "Only result_func or result_columns should be provided" + raise ValueError(message) + elif result_func is not None: + self.result_columns = None + else: + raise ValueError("Either result_func or result_columns should be provided") + self.result_func = result_func + self.rtol = rtol + self.atol = atol + if not hasattr(param_filter, '__len__'): + param_filter = (param_filter,) + self.param_filter = param_filter + self.knownfailure = knownfailure + self.nan_ok = nan_ok + self.vectorized = vectorized + self.ignore_inf_sign = ignore_inf_sign + self.distinguish_nan_and_inf = distinguish_nan_and_inf + if not self.distinguish_nan_and_inf: + self.ignore_inf_sign = True + + def get_tolerances(self, dtype): + if not np.issubdtype(dtype, np.inexact): + dtype = np.dtype(float) + info = np.finfo(dtype) + rtol, atol = self.rtol, self.atol + if rtol is None: + rtol = 5*info.eps + if atol is None: + atol = 5*info.tiny + return rtol, atol + + def check(self, data=None, dtype=None, dtypes=None): + """Check the special function against the data.""" + __tracebackhide__ = operator.methodcaller( + 'errisinstance', AssertionError + ) + + if self.knownfailure: + pytest.xfail(reason=self.knownfailure) + + if data is None: + data = self.data + + if dtype is None: + dtype = data.dtype + else: + data = data.astype(dtype) + + rtol, atol = self.get_tolerances(dtype) + + # Apply given filter functions + if self.param_filter: + param_mask = np.ones((data.shape[0],), np.bool_) + for j, filter in zip(self.param_columns, self.param_filter): + if filter: + param_mask &= list(filter(data[:,j])) + data = data[param_mask] + + # Pick parameters from the correct columns + params = [] + for idx, j in enumerate(self.param_columns): + if np.iscomplexobj(j): + j = int(j.imag) + params.append(data[:,j].astype(complex)) + elif dtypes and idx < len(dtypes): + params.append(data[:, j].astype(dtypes[idx])) + else: + params.append(data[:,j]) + + # Helper for evaluating results + def eval_func_at_params(func, skip_mask=None): + if self.vectorized: + got = func(*params) + else: + got = [] + for j in range(len(params[0])): + if skip_mask is not None and skip_mask[j]: + got.append(np.nan) + continue + got.append(func(*tuple([params[i][j] for i in range(len(params))]))) + got = np.asarray(got) + if not isinstance(got, tuple): + got = (got,) + return got + + # Evaluate function to be tested + got = eval_func_at_params(self.func) + + # Grab the correct results + if self.result_columns is not None: + # Correct results passed in with the data + wanted = tuple([data[:,icol] for icol in self.result_columns]) + else: + # Function producing correct results passed in + skip_mask = None + if self.nan_ok and len(got) == 1: + # Don't spend time evaluating what doesn't need to be evaluated + skip_mask = np.isnan(got[0]) + wanted = eval_func_at_params(self.result_func, skip_mask=skip_mask) + + # Check the validity of each output returned + assert_(len(got) == len(wanted)) + + for output_num, (x, y) in enumerate(zip(got, wanted)): + if np.issubdtype(x.dtype, np.complexfloating) or self.ignore_inf_sign: + pinf_x = np.isinf(x) + pinf_y = np.isinf(y) + minf_x = np.isinf(x) + minf_y = np.isinf(y) + else: + pinf_x = np.isposinf(x) + pinf_y = np.isposinf(y) + minf_x = np.isneginf(x) + minf_y = np.isneginf(y) + nan_x = np.isnan(x) + nan_y = np.isnan(y) + + with np.errstate(all='ignore'): + abs_y = np.absolute(y) + abs_y[~np.isfinite(abs_y)] = 0 + diff = np.absolute(x - y) + diff[~np.isfinite(diff)] = 0 + + rdiff = diff / np.absolute(y) + rdiff[~np.isfinite(rdiff)] = 0 + + tol_mask = (diff <= atol + rtol*abs_y) + pinf_mask = (pinf_x == pinf_y) + minf_mask = (minf_x == minf_y) + + nan_mask = (nan_x == nan_y) + + bad_j = ~(tol_mask & pinf_mask & minf_mask & nan_mask) + + point_count = bad_j.size + if self.nan_ok: + bad_j &= ~nan_x + bad_j &= ~nan_y + point_count -= (nan_x | nan_y).sum() + + if not self.distinguish_nan_and_inf and not self.nan_ok: + # If nan's are okay we've already covered all these cases + inf_x = np.isinf(x) + inf_y = np.isinf(y) + both_nonfinite = (inf_x & nan_y) | (nan_x & inf_y) + bad_j &= ~both_nonfinite + point_count -= both_nonfinite.sum() + + if np.any(bad_j): + # Some bad results: inform what, where, and how bad + msg = [""] + msg.append(f"Max |adiff|: {diff[bad_j].max():g}") + msg.append(f"Max |rdiff|: {rdiff[bad_j].max():g}") + msg.append("Bad results (%d out of %d) for the following points " + "(in output %d):" + % (np.sum(bad_j), point_count, output_num,)) + for j in np.nonzero(bad_j)[0]: + j = int(j) + def fmt(x): + return '%30s' % np.array2string(x[j], precision=18) + a = " ".join(map(fmt, params)) + b = " ".join(map(fmt, got)) + c = " ".join(map(fmt, wanted)) + d = fmt(rdiff) + msg.append(f"{a} => {b} != {c} (rdiff {d})") + assert_(False, "\n".join(msg)) + + def __repr__(self): + """Pretty-printing""" + if np.any(list(map(np.iscomplexobj, self.param_columns))): + is_complex = " (complex)" + else: + is_complex = "" + if self.dataname: + return (f"") + else: + return f"" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0ccf14137096c862a0644cdb229cb98b4556e5d7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi @@ -0,0 +1,521 @@ +from typing import Any + +import numpy as np + +__all__ = [ + 'geterr', + 'seterr', + 'errstate', + 'agm', + 'airy', + 'airye', + 'bdtr', + 'bdtrc', + 'bdtri', + 'bdtrik', + 'bdtrin', + 'bei', + 'beip', + 'ber', + 'berp', + 'besselpoly', + 'beta', + 'betainc', + 'betaincc', + 'betainccinv', + 'betaincinv', + 'betaln', + 'binom', + 'boxcox', + 'boxcox1p', + 'btdtria', + 'btdtrib', + 'cbrt', + 'chdtr', + 'chdtrc', + 'chdtri', + 'chdtriv', + 'chndtr', + 'chndtridf', + 'chndtrinc', + 'chndtrix', + 'cosdg', + 'cosm1', + 'cotdg', + 'dawsn', + 'ellipe', + 'ellipeinc', + 'ellipj', + 'ellipk', + 'ellipkinc', + 'ellipkm1', + 'elliprc', + 'elliprd', + 'elliprf', + 'elliprg', + 'elliprj', + 'entr', + 'erf', + 'erfc', + 'erfcinv', + 'erfcx', + 'erfi', + 'erfinv', + 'eval_chebyc', + 'eval_chebys', + 'eval_chebyt', + 'eval_chebyu', + 'eval_gegenbauer', + 'eval_genlaguerre', + 'eval_hermite', + 'eval_hermitenorm', + 'eval_jacobi', + 'eval_laguerre', + 'eval_legendre', + 'eval_sh_chebyt', + 'eval_sh_chebyu', + 'eval_sh_jacobi', + 'eval_sh_legendre', + 'exp1', + 'exp10', + 'exp2', + 'expi', + 'expit', + 'expm1', + 'expn', + 'exprel', + 'fdtr', + 'fdtrc', + 'fdtri', + 'fdtridfd', + 'fresnel', + 'gamma', + 'gammainc', + 'gammaincc', + 'gammainccinv', + 'gammaincinv', + 'gammaln', + 'gammasgn', + 'gdtr', + 'gdtrc', + 'gdtria', + 'gdtrib', + 'gdtrix', + 'hankel1', + 'hankel1e', + 'hankel2', + 'hankel2e', + 'huber', + 'hyp0f1', + 'hyp1f1', + 'hyp2f1', + 'hyperu', + 'i0', + 'i0e', + 'i1', + 'i1e', + 'inv_boxcox', + 'inv_boxcox1p', + 'it2i0k0', + 'it2j0y0', + 'it2struve0', + 'itairy', + 'iti0k0', + 'itj0y0', + 'itmodstruve0', + 'itstruve0', + 'iv', + 'ive', + 'j0', + 'j1', + 'jn', + 'jv', + 'jve', + 'k0', + 'k0e', + 'k1', + 'k1e', + 'kei', + 'keip', + 'kelvin', + 'ker', + 'kerp', + 'kl_div', + 'kn', + 'kolmogi', + 'kolmogorov', + 'kv', + 'kve', + 'log1p', + 'log_expit', + 'log_ndtr', + 'log_wright_bessel', + 'loggamma', + 'logit', + 'lpmv', + 'mathieu_a', + 'mathieu_b', + 'mathieu_cem', + 'mathieu_modcem1', + 'mathieu_modcem2', + 'mathieu_modsem1', + 'mathieu_modsem2', + 'mathieu_sem', + 'modfresnelm', + 'modfresnelp', + 'modstruve', + 'nbdtr', + 'nbdtrc', + 'nbdtri', + 'nbdtrik', + 'nbdtrin', + 'ncfdtr', + 'ncfdtri', + 'ncfdtridfd', + 'ncfdtridfn', + 'ncfdtrinc', + 'nctdtr', + 'nctdtridf', + 'nctdtrinc', + 'nctdtrit', + 'ndtr', + 'ndtri', + 'ndtri_exp', + 'nrdtrimn', + 'nrdtrisd', + 'obl_ang1', + 'obl_ang1_cv', + 'obl_cv', + 'obl_rad1', + 'obl_rad1_cv', + 'obl_rad2', + 'obl_rad2_cv', + 'owens_t', + 'pbdv', + 'pbvv', + 'pbwa', + 'pdtr', + 'pdtrc', + 'pdtri', + 'pdtrik', + 'poch', + 'powm1', + 'pro_ang1', + 'pro_ang1_cv', + 'pro_cv', + 'pro_rad1', + 'pro_rad1_cv', + 'pro_rad2', + 'pro_rad2_cv', + 'pseudo_huber', + 'psi', + 'radian', + 'rel_entr', + 'rgamma', + 'round', + 'shichi', + 'sici', + 'sindg', + 'smirnov', + 'smirnovi', + 'spence', + 'sph_harm', + 'stdtr', + 'stdtridf', + 'stdtrit', + 'struve', + 'tandg', + 'tklmbda', + 'voigt_profile', + 'wofz', + 'wright_bessel', + 'wrightomega', + 'xlog1py', + 'xlogy', + 'y0', + 'y1', + 'yn', + 'yv', + 'yve', + 'zetac' +] + +def geterr() -> dict[str, str]: ... +def seterr(**kwargs: str) -> dict[str, str]: ... + +class errstate: + def __init__(self, **kargs: str) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, + exc_type: Any, # Unused + exc_value: Any, # Unused + traceback: Any, # Unused + ) -> None: ... + +_cosine_cdf: np.ufunc +_cosine_invcdf: np.ufunc +_cospi: np.ufunc +_ellip_harm: np.ufunc +_factorial: np.ufunc +_igam_fac: np.ufunc +_kolmogc: np.ufunc +_kolmogci: np.ufunc +_kolmogp: np.ufunc +_lambertw: np.ufunc +_lanczos_sum_expg_scaled: np.ufunc +_lgam1p: np.ufunc +_log1pmx: np.ufunc +_riemann_zeta: np.ufunc +_scaled_exp1: np.ufunc +_sf_error_test_function: np.ufunc +_sinpi: np.ufunc +_smirnovc: np.ufunc +_smirnovci: np.ufunc +_smirnovp: np.ufunc +_spherical_in: np.ufunc +_spherical_in_d: np.ufunc +_spherical_jn: np.ufunc +_spherical_jn_d: np.ufunc +_spherical_kn: np.ufunc +_spherical_kn_d: np.ufunc +_spherical_yn: np.ufunc +_spherical_yn_d: np.ufunc +_stirling2_inexact: np.ufunc +_struve_asymp_large_z: np.ufunc +_struve_bessel_series: np.ufunc +_struve_power_series: np.ufunc +_zeta: np.ufunc +agm: np.ufunc +airy: np.ufunc +airye: np.ufunc +bdtr: np.ufunc +bdtrc: np.ufunc +bdtri: np.ufunc +bdtrik: np.ufunc +bdtrin: np.ufunc +bei: np.ufunc +beip: np.ufunc +ber: np.ufunc +berp: np.ufunc +besselpoly: np.ufunc +beta: np.ufunc +betainc: np.ufunc +betaincc: np.ufunc +betainccinv: np.ufunc +betaincinv: np.ufunc +betaln: np.ufunc +binom: np.ufunc +boxcox1p: np.ufunc +boxcox: np.ufunc +btdtria: np.ufunc +btdtrib: np.ufunc +cbrt: np.ufunc +chdtr: np.ufunc +chdtrc: np.ufunc +chdtri: np.ufunc +chdtriv: np.ufunc +chndtr: np.ufunc +chndtridf: np.ufunc +chndtrinc: np.ufunc +chndtrix: np.ufunc +cosdg: np.ufunc +cosm1: np.ufunc +cotdg: np.ufunc +dawsn: np.ufunc +ellipe: np.ufunc +ellipeinc: np.ufunc +ellipj: np.ufunc +ellipk: np.ufunc +ellipkinc: np.ufunc +ellipkm1: np.ufunc +elliprc: np.ufunc +elliprd: np.ufunc +elliprf: np.ufunc +elliprg: np.ufunc +elliprj: np.ufunc +entr: np.ufunc +erf: np.ufunc +erfc: np.ufunc +erfcinv: np.ufunc +erfcx: np.ufunc +erfi: np.ufunc +erfinv: np.ufunc +eval_chebyc: np.ufunc +eval_chebys: np.ufunc +eval_chebyt: np.ufunc +eval_chebyu: np.ufunc +eval_gegenbauer: np.ufunc +eval_genlaguerre: np.ufunc +eval_hermite: np.ufunc +eval_hermitenorm: np.ufunc +eval_jacobi: np.ufunc +eval_laguerre: np.ufunc +eval_legendre: np.ufunc +eval_sh_chebyt: np.ufunc +eval_sh_chebyu: np.ufunc +eval_sh_jacobi: np.ufunc +eval_sh_legendre: np.ufunc +exp10: np.ufunc +exp1: np.ufunc +exp2: np.ufunc +expi: np.ufunc +expit: np.ufunc +expm1: np.ufunc +expn: np.ufunc +exprel: np.ufunc +fdtr: np.ufunc +fdtrc: np.ufunc +fdtri: np.ufunc +fdtridfd: np.ufunc +fresnel: np.ufunc +gamma: np.ufunc +gammainc: np.ufunc +gammaincc: np.ufunc +gammainccinv: np.ufunc +gammaincinv: np.ufunc +gammaln: np.ufunc +gammasgn: np.ufunc +gdtr: np.ufunc +gdtrc: np.ufunc +gdtria: np.ufunc +gdtrib: np.ufunc +gdtrix: np.ufunc +hankel1: np.ufunc +hankel1e: np.ufunc +hankel2: np.ufunc +hankel2e: np.ufunc +huber: np.ufunc +hyp0f1: np.ufunc +hyp1f1: np.ufunc +hyp2f1: np.ufunc +hyperu: np.ufunc +i0: np.ufunc +i0e: np.ufunc +i1: np.ufunc +i1e: np.ufunc +inv_boxcox1p: np.ufunc +inv_boxcox: np.ufunc +it2i0k0: np.ufunc +it2j0y0: np.ufunc +it2struve0: np.ufunc +itairy: np.ufunc +iti0k0: np.ufunc +itj0y0: np.ufunc +itmodstruve0: np.ufunc +itstruve0: np.ufunc +iv: np.ufunc +ive: np.ufunc +j0: np.ufunc +j1: np.ufunc +jn: np.ufunc +jv: np.ufunc +jve: np.ufunc +k0: np.ufunc +k0e: np.ufunc +k1: np.ufunc +k1e: np.ufunc +kei: np.ufunc +keip: np.ufunc +kelvin: np.ufunc +ker: np.ufunc +kerp: np.ufunc +kl_div: np.ufunc +kn: np.ufunc +kolmogi: np.ufunc +kolmogorov: np.ufunc +kv: np.ufunc +kve: np.ufunc +log1p: np.ufunc +log_expit: np.ufunc +log_ndtr: np.ufunc +log_wright_bessel: np.ufunc +loggamma: np.ufunc +logit: np.ufunc +lpmv: np.ufunc +mathieu_a: np.ufunc +mathieu_b: np.ufunc +mathieu_cem: np.ufunc +mathieu_modcem1: np.ufunc +mathieu_modcem2: np.ufunc +mathieu_modsem1: np.ufunc +mathieu_modsem2: np.ufunc +mathieu_sem: np.ufunc +modfresnelm: np.ufunc +modfresnelp: np.ufunc +modstruve: np.ufunc +nbdtr: np.ufunc +nbdtrc: np.ufunc +nbdtri: np.ufunc +nbdtrik: np.ufunc +nbdtrin: np.ufunc +ncfdtr: np.ufunc +ncfdtri: np.ufunc +ncfdtridfd: np.ufunc +ncfdtridfn: np.ufunc +ncfdtrinc: np.ufunc +nctdtr: np.ufunc +nctdtridf: np.ufunc +nctdtrinc: np.ufunc +nctdtrit: np.ufunc +ndtr: np.ufunc +ndtri: np.ufunc +ndtri_exp: np.ufunc +nrdtrimn: np.ufunc +nrdtrisd: np.ufunc +obl_ang1: np.ufunc +obl_ang1_cv: np.ufunc +obl_cv: np.ufunc +obl_rad1: np.ufunc +obl_rad1_cv: np.ufunc +obl_rad2: np.ufunc +obl_rad2_cv: np.ufunc +owens_t: np.ufunc +pbdv: np.ufunc +pbvv: np.ufunc +pbwa: np.ufunc +pdtr: np.ufunc +pdtrc: np.ufunc +pdtri: np.ufunc +pdtrik: np.ufunc +poch: np.ufunc +powm1: np.ufunc +pro_ang1: np.ufunc +pro_ang1_cv: np.ufunc +pro_cv: np.ufunc +pro_rad1: np.ufunc +pro_rad1_cv: np.ufunc +pro_rad2: np.ufunc +pro_rad2_cv: np.ufunc +pseudo_huber: np.ufunc +psi: np.ufunc +radian: np.ufunc +rel_entr: np.ufunc +rgamma: np.ufunc +round: np.ufunc +shichi: np.ufunc +sici: np.ufunc +sindg: np.ufunc +smirnov: np.ufunc +smirnovi: np.ufunc +spence: np.ufunc +sph_harm: np.ufunc +stdtr: np.ufunc +stdtridf: np.ufunc +stdtrit: np.ufunc +struve: np.ufunc +tandg: np.ufunc +tklmbda: np.ufunc +voigt_profile: np.ufunc +wofz: np.ufunc +wright_bessel: np.ufunc +wrightomega: np.ufunc +xlog1py: np.ufunc +xlogy: np.ufunc +y0: np.ufunc +y1: np.ufunc +yn: np.ufunc +yv: np.ufunc +yve: np.ufunc +zetac: np.ufunc + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx new file mode 100644 index 0000000000000000000000000000000000000000..5f9afc828a16d598b3ba76582111cd964cfe764a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx @@ -0,0 +1,14358 @@ +# This file is automatically generated by _generate_pyx.py. +# Do not edit manually! + +from libc.math cimport NAN + +include "_ufuncs_extra_code_common.pxi" +include "_ufuncs_extra_code.pxi" +__all__ = ['agm', 'bdtr', 'bdtrc', 'bdtri', 'bdtrik', 'bdtrin', 'betainc', 'betaincc', 'betainccinv', 'betaincinv', 'boxcox', 'boxcox1p', 'btdtria', 'btdtrib', 'chdtr', 'chdtrc', 'chdtri', 'chdtriv', 'chndtr', 'chndtridf', 'chndtrinc', 'chndtrix', 'dawsn', 'elliprc', 'elliprd', 'elliprf', 'elliprg', 'elliprj', 'entr', 'erf', 'erfc', 'erfcinv', 'erfcx', 'erfi', 'erfinv', 'eval_chebyc', 'eval_chebys', 'eval_chebyt', 'eval_chebyu', 'eval_gegenbauer', 'eval_genlaguerre', 'eval_hermite', 'eval_hermitenorm', 'eval_jacobi', 'eval_laguerre', 'eval_legendre', 'eval_sh_chebyt', 'eval_sh_chebyu', 'eval_sh_jacobi', 'eval_sh_legendre', 'exp10', 'exp2', 'expm1', 'expn', 'fdtr', 'fdtrc', 'fdtri', 'fdtridfd', 'gdtr', 'gdtrc', 'gdtria', 'gdtrib', 'gdtrix', 'huber', 'hyp0f1', 'hyp1f1', 'hyperu', 'inv_boxcox', 'inv_boxcox1p', 'kl_div', 'kn', 'kolmogi', 'kolmogorov', 'log1p', 'log_ndtr', 'lpmv', 'nbdtr', 'nbdtrc', 'nbdtri', 'nbdtrik', 'nbdtrin', 'ncfdtr', 'ncfdtri', 'ncfdtridfd', 'ncfdtridfn', 'ncfdtrinc', 'nctdtr', 'nctdtridf', 'nctdtrinc', 'nctdtrit', 'ndtr', 'ndtri', 'ndtri_exp', 'nrdtrimn', 'nrdtrisd', 'owens_t', 'pdtr', 'pdtrc', 'pdtri', 'pdtrik', 'poch', 'powm1', 'pseudo_huber', 'rel_entr', 'round', 'shichi', 'sici', 'smirnov', 'smirnovi', 'spence', 'stdtr', 'stdtridf', 'stdtrit', 'tklmbda', 'voigt_profile', 'wofz', 'wrightomega', 'xlog1py', 'xlogy', 'yn', 'geterr', 'seterr', 'errstate', 'jn', 'airy', 'airye', 'bei', 'beip', 'ber', 'berp', 'binom', 'exp1', 'expi', 'expit', 'exprel', 'gamma', 'gammaln', 'hankel1', 'hankel1e', 'hankel2', 'hankel2e', 'hyp2f1', 'it2i0k0', 'it2j0y0', 'it2struve0', 'itairy', 'iti0k0', 'itj0y0', 'itmodstruve0', 'itstruve0', 'iv', 'ive', 'jv', 'jve', 'kei', 'keip', 'kelvin', 'ker', 'kerp', 'kv', 'kve', 'log_expit', 'log_wright_bessel', 'loggamma', 'logit', 'mathieu_a', 'mathieu_b', 'mathieu_cem', 'mathieu_modcem1', 'mathieu_modcem2', 'mathieu_modsem1', 'mathieu_modsem2', 'mathieu_sem', 'modfresnelm', 'modfresnelp', 'obl_ang1', 'obl_ang1_cv', 'obl_cv', 'obl_rad1', 'obl_rad1_cv', 'obl_rad2', 'obl_rad2_cv', 'pbdv', 'pbvv', 'pbwa', 'pro_ang1', 'pro_ang1_cv', 'pro_cv', 'pro_rad1', 'pro_rad1_cv', 'pro_rad2', 'pro_rad2_cv', 'psi', 'rgamma', 'sph_harm', 'wright_bessel', 'yv', 'yve', 'zetac', 'sindg', 'cosdg', 'tandg', 'cotdg', 'i0', 'i0e', 'i1', 'i1e', 'k0', 'k0e', 'k1', 'k1e', 'y0', 'y1', 'j0', 'j1', 'struve', 'modstruve', 'beta', 'betaln', 'besselpoly', 'gammaln', 'gammasgn', 'cbrt', 'radian', 'cosm1', 'gammainc', 'gammaincinv', 'gammaincc', 'gammainccinv', 'fresnel', 'ellipe', 'ellipeinc', 'ellipk', 'ellipkinc', 'ellipkm1', 'ellipj'] +cdef void loop_D_DDDD__As_DDDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_D_DDDD__As_FFFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_D_DDD__As_DDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_D_DDD__As_FFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_D_DD__As_DD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_D_DD__As_FF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_D_D__As_D_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + op0 += steps[1] + sf_error.check_fpe(func_name) + +cdef void loop_D_D__As_F_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + op0 += steps[1] + sf_error.check_fpe(func_name) + +cdef void loop_D_dD__As_dD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_D_dD__As_fF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_D_ddD__As_ddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_D_ddD__As_ffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_D_dddD__As_dddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_D_dddD__As_fffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef double complex ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_d_d__As_d_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + op0 += steps[1] + sf_error.check_fpe(func_name) + +cdef void loop_d_d__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + op0 += steps[1] + sf_error.check_fpe(func_name) + +cdef void loop_d_dd__As_dd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_d_dd__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_d_ddd__As_ddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_d_ddd__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_d_dddd__As_dddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_d_dddd__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_d_ddddddd__As_ddddddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *ip4 = args[4] + cdef char *ip5 = args[5] + cdef char *ip6 = args[6] + cdef char *op0 = args[7] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + ip4 += steps[4] + ip5 += steps[5] + ip6 += steps[6] + op0 += steps[7] + sf_error.check_fpe(func_name) + +cdef void loop_d_ddddddd__As_fffffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *ip4 = args[4] + cdef char *ip5 = args[5] + cdef char *ip6 = args[6] + cdef char *op0 = args[7] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + ip4 += steps[4] + ip5 += steps[5] + ip6 += steps[6] + op0 += steps[7] + sf_error.check_fpe(func_name) + +cdef void loop_d_ddiiddd__As_ddllddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *ip4 = args[4] + cdef char *ip5 = args[5] + cdef char *ip6 = args[6] + cdef char *op0 = args[7] + cdef double ov0 + for i in range(n): + if (ip2)[0] == (ip2)[0] and (ip3)[0] == (ip3)[0]: + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0]) + else: + sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument") + ov0 = NAN + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + ip4 += steps[4] + ip5 += steps[5] + ip6 += steps[6] + op0 += steps[7] + sf_error.check_fpe(func_name) + +cdef void loop_d_ddp_d_As_ddp_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef char *op1 = args[4] + cdef double ov0 + cdef double ov1 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], &ov1) + (op0)[0] = ov0 + (op1)[0] = ov1 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + op1 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_d_dpd__As_dpd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_d_pd__As_pd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_d_pdd__As_pdd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_d_pddd__As_pddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_d_ppd__As_ppd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef double ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_f_f__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef float ov0 + for i in range(n): + ov0 = (func)((ip0)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + op0 += steps[1] + sf_error.check_fpe(func_name) + +cdef void loop_f_ff__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *op0 = args[2] + cdef float ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + op0 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_f_fff__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *op0 = args[3] + cdef float ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + op0 += steps[3] + sf_error.check_fpe(func_name) + +cdef void loop_f_ffff__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *ip1 = args[1] + cdef char *ip2 = args[2] + cdef char *ip3 = args[3] + cdef char *op0 = args[4] + cdef float ov0 + for i in range(n): + ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0]) + (op0)[0] = ov0 + ip0 += steps[0] + ip1 += steps[1] + ip2 += steps[2] + ip3 += steps[3] + op0 += steps[4] + sf_error.check_fpe(func_name) + +cdef void loop_i_D_DD_As_D_DD(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef char *op1 = args[2] + cdef double complex ov0 + cdef double complex ov1 + for i in range(n): + (func)((ip0)[0], &ov0, &ov1) + (op0)[0] = ov0 + (op1)[0] = ov1 + ip0 += steps[0] + op0 += steps[1] + op1 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_i_D_DD_As_F_FF(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef char *op1 = args[2] + cdef double complex ov0 + cdef double complex ov1 + for i in range(n): + (func)((ip0)[0], &ov0, &ov1) + (op0)[0] = ov0 + (op1)[0] = ov1 + ip0 += steps[0] + op0 += steps[1] + op1 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_i_d_dd_As_d_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef char *op1 = args[2] + cdef double ov0 + cdef double ov1 + for i in range(n): + (func)((ip0)[0], &ov0, &ov1) + (op0)[0] = ov0 + (op1)[0] = ov1 + ip0 += steps[0] + op0 += steps[1] + op1 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_i_d_dd_As_f_ff(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef char *op1 = args[2] + cdef double ov0 + cdef double ov1 + for i in range(n): + (func)((ip0)[0], &ov0, &ov1) + (op0)[0] = ov0 + (op1)[0] = ov1 + ip0 += steps[0] + op0 += steps[1] + op1 += steps[2] + sf_error.check_fpe(func_name) + +cdef void loop_i_i__As_l_l(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil: + cdef np.npy_intp i, n = dims[0] + cdef void *func = (data)[0] + cdef char *func_name = (data)[1] + cdef char *ip0 = args[0] + cdef char *op0 = args[1] + cdef int ov0 + for i in range(n): + if (ip0)[0] == (ip0)[0]: + ov0 = (func)((ip0)[0]) + else: + sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument") + ov0 = 0xbad0bad0 + (op0)[0] = ov0 + ip0 += steps[0] + op0 += steps[1] + sf_error.check_fpe(func_name) + +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cosine_cdf "cosine_cdf"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cosine_invcdf "cosine_invcdf"(double) noexcept nogil +from ._ellip_harm cimport ellip_harmonic as _func_ellip_harmonic +ctypedef double _proto_ellip_harmonic_t(double, double, int, int, double, double, double) noexcept nogil +cdef _proto_ellip_harmonic_t *_proto_ellip_harmonic_t_var = &_func_ellip_harmonic +from ._legacy cimport ellip_harmonic_unsafe as _func_ellip_harmonic_unsafe +ctypedef double _proto_ellip_harmonic_unsafe_t(double, double, double, double, double, double, double) noexcept nogil +cdef _proto_ellip_harmonic_unsafe_t *_proto_ellip_harmonic_unsafe_t_var = &_func_ellip_harmonic_unsafe +from ._factorial cimport _factorial as _func__factorial +ctypedef double _proto__factorial_t(double) noexcept nogil +cdef _proto__factorial_t *_proto__factorial_t_var = &_func__factorial +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_igam_fac "cephes_igam_fac"(double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_kolmogc "xsf_kolmogc"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_kolmogci "xsf_kolmogci"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_kolmogp "xsf_kolmogp"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_lanczos_sum_expg_scaled "cephes_lanczos_sum_expg_scaled"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_lgam1p "cephes_lgam1p"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_log1pmx "cephes_log1pmx"(double) noexcept nogil +from .sf_error cimport _sf_error_test_function as _func__sf_error_test_function +ctypedef int _proto__sf_error_test_function_t(int) noexcept nogil +cdef _proto__sf_error_test_function_t *_proto__sf_error_test_function_t_var = &_func__sf_error_test_function +from ._legacy cimport smirnovc_unsafe as _func_smirnovc_unsafe +ctypedef double _proto_smirnovc_unsafe_t(double, double) noexcept nogil +cdef _proto_smirnovc_unsafe_t *_proto_smirnovc_unsafe_t_var = &_func_smirnovc_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_smirnovc_wrap "cephes_smirnovc_wrap"(Py_ssize_t, double) noexcept nogil +from ._legacy cimport smirnovci_unsafe as _func_smirnovci_unsafe +ctypedef double _proto_smirnovci_unsafe_t(double, double) noexcept nogil +cdef _proto_smirnovci_unsafe_t *_proto_smirnovci_unsafe_t_var = &_func_smirnovci_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_smirnovci_wrap "cephes_smirnovci_wrap"(Py_ssize_t, double) noexcept nogil +from ._legacy cimport smirnovp_unsafe as _func_smirnovp_unsafe +ctypedef double _proto_smirnovp_unsafe_t(double, double) noexcept nogil +cdef _proto_smirnovp_unsafe_t *_proto_smirnovp_unsafe_t_var = &_func_smirnovp_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_smirnovp_wrap "cephes_smirnovp_wrap"(Py_ssize_t, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes__struve_asymp_large_z "cephes__struve_asymp_large_z"(double, double, Py_ssize_t, double *) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes__struve_bessel_series "cephes__struve_bessel_series"(double, double, Py_ssize_t, double *) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes__struve_power_series "cephes__struve_power_series"(double, double, Py_ssize_t, double *) noexcept nogil +from ._agm cimport agm as _func_agm +ctypedef double _proto_agm_t(double, double) noexcept nogil +cdef _proto_agm_t *_proto_agm_t_var = &_func_agm +from ._legacy cimport bdtr_unsafe as _func_bdtr_unsafe +ctypedef double _proto_bdtr_unsafe_t(double, double, double) noexcept nogil +cdef _proto_bdtr_unsafe_t *_proto_bdtr_unsafe_t_var = &_func_bdtr_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_bdtr_wrap "cephes_bdtr_wrap"(double, Py_ssize_t, double) noexcept nogil +from ._legacy cimport bdtrc_unsafe as _func_bdtrc_unsafe +ctypedef double _proto_bdtrc_unsafe_t(double, double, double) noexcept nogil +cdef _proto_bdtrc_unsafe_t *_proto_bdtrc_unsafe_t_var = &_func_bdtrc_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_bdtrc_wrap "cephes_bdtrc_wrap"(double, Py_ssize_t, double) noexcept nogil +from ._legacy cimport bdtri_unsafe as _func_bdtri_unsafe +ctypedef double _proto_bdtri_unsafe_t(double, double, double) noexcept nogil +cdef _proto_bdtri_unsafe_t *_proto_bdtri_unsafe_t_var = &_func_bdtri_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_bdtri_wrap "cephes_bdtri_wrap"(double, Py_ssize_t, double) noexcept nogil +from ._cdflib_wrappers cimport bdtrik as _func_bdtrik +ctypedef double _proto_bdtrik_t(double, double, double) noexcept nogil +cdef _proto_bdtrik_t *_proto_bdtrik_t_var = &_func_bdtrik +from ._cdflib_wrappers cimport bdtrin as _func_bdtrin +ctypedef double _proto_bdtrin_t(double, double, double) noexcept nogil +cdef _proto_bdtrin_t *_proto_bdtrin_t_var = &_func_bdtrin +from ._boxcox cimport boxcox as _func_boxcox +ctypedef double _proto_boxcox_t(double, double) noexcept nogil +cdef _proto_boxcox_t *_proto_boxcox_t_var = &_func_boxcox +from ._boxcox cimport boxcox1p as _func_boxcox1p +ctypedef double _proto_boxcox1p_t(double, double) noexcept nogil +cdef _proto_boxcox1p_t *_proto_boxcox1p_t_var = &_func_boxcox1p +from ._cdflib_wrappers cimport btdtria as _func_btdtria +ctypedef double _proto_btdtria_t(double, double, double) noexcept nogil +cdef _proto_btdtria_t *_proto_btdtria_t_var = &_func_btdtria +from ._cdflib_wrappers cimport btdtrib as _func_btdtrib +ctypedef double _proto_btdtrib_t(double, double, double) noexcept nogil +cdef _proto_btdtrib_t *_proto_btdtrib_t_var = &_func_btdtrib +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_chdtr "xsf_chdtr"(double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_chdtrc "xsf_chdtrc"(double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_chdtri "xsf_chdtri"(double, double) noexcept nogil +from ._cdflib_wrappers cimport chdtriv as _func_chdtriv +ctypedef double _proto_chdtriv_t(double, double) noexcept nogil +cdef _proto_chdtriv_t *_proto_chdtriv_t_var = &_func_chdtriv +from ._cdflib_wrappers cimport chndtr as _func_chndtr +ctypedef double _proto_chndtr_t(double, double, double) noexcept nogil +cdef _proto_chndtr_t *_proto_chndtr_t_var = &_func_chndtr +from ._cdflib_wrappers cimport chndtridf as _func_chndtridf +ctypedef double _proto_chndtridf_t(double, double, double) noexcept nogil +cdef _proto_chndtridf_t *_proto_chndtridf_t_var = &_func_chndtridf +from ._cdflib_wrappers cimport chndtrinc as _func_chndtrinc +ctypedef double _proto_chndtrinc_t(double, double, double) noexcept nogil +cdef _proto_chndtrinc_t *_proto_chndtrinc_t_var = &_func_chndtrinc +from ._cdflib_wrappers cimport chndtrix as _func_chndtrix +ctypedef double _proto_chndtrix_t(double, double, double) noexcept nogil +cdef _proto_chndtrix_t *_proto_chndtrix_t_var = &_func_chndtrix +from ._convex_analysis cimport entr as _func_entr +ctypedef double _proto_entr_t(double) noexcept nogil +cdef _proto_entr_t *_proto_entr_t_var = &_func_entr +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_erf "cephes_erf"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_erfc "cephes_erfc"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_erfcinv "cephes_erfcinv"(double) noexcept nogil +from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc +ctypedef double complex _proto_eval_chebyc_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_chebyc_double_complex__t *_proto_eval_chebyc_double_complex__t_var = &_func_eval_chebyc[double_complex] +from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc +ctypedef double _proto_eval_chebyc_double__t(double, double) noexcept nogil +cdef _proto_eval_chebyc_double__t *_proto_eval_chebyc_double__t_var = &_func_eval_chebyc[double] +from .orthogonal_eval cimport eval_chebyc_l as _func_eval_chebyc_l +ctypedef double _proto_eval_chebyc_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_chebyc_l_t *_proto_eval_chebyc_l_t_var = &_func_eval_chebyc_l +from .orthogonal_eval cimport eval_chebys as _func_eval_chebys +ctypedef double complex _proto_eval_chebys_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_chebys_double_complex__t *_proto_eval_chebys_double_complex__t_var = &_func_eval_chebys[double_complex] +from .orthogonal_eval cimport eval_chebys as _func_eval_chebys +ctypedef double _proto_eval_chebys_double__t(double, double) noexcept nogil +cdef _proto_eval_chebys_double__t *_proto_eval_chebys_double__t_var = &_func_eval_chebys[double] +from .orthogonal_eval cimport eval_chebys_l as _func_eval_chebys_l +ctypedef double _proto_eval_chebys_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_chebys_l_t *_proto_eval_chebys_l_t_var = &_func_eval_chebys_l +from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt +ctypedef double complex _proto_eval_chebyt_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_chebyt_double_complex__t *_proto_eval_chebyt_double_complex__t_var = &_func_eval_chebyt[double_complex] +from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt +ctypedef double _proto_eval_chebyt_double__t(double, double) noexcept nogil +cdef _proto_eval_chebyt_double__t *_proto_eval_chebyt_double__t_var = &_func_eval_chebyt[double] +from .orthogonal_eval cimport eval_chebyt_l as _func_eval_chebyt_l +ctypedef double _proto_eval_chebyt_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_chebyt_l_t *_proto_eval_chebyt_l_t_var = &_func_eval_chebyt_l +from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu +ctypedef double complex _proto_eval_chebyu_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_chebyu_double_complex__t *_proto_eval_chebyu_double_complex__t_var = &_func_eval_chebyu[double_complex] +from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu +ctypedef double _proto_eval_chebyu_double__t(double, double) noexcept nogil +cdef _proto_eval_chebyu_double__t *_proto_eval_chebyu_double__t_var = &_func_eval_chebyu[double] +from .orthogonal_eval cimport eval_chebyu_l as _func_eval_chebyu_l +ctypedef double _proto_eval_chebyu_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_chebyu_l_t *_proto_eval_chebyu_l_t_var = &_func_eval_chebyu_l +from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer +ctypedef double complex _proto_eval_gegenbauer_double_complex__t(double, double, double complex) noexcept nogil +cdef _proto_eval_gegenbauer_double_complex__t *_proto_eval_gegenbauer_double_complex__t_var = &_func_eval_gegenbauer[double_complex] +from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer +ctypedef double _proto_eval_gegenbauer_double__t(double, double, double) noexcept nogil +cdef _proto_eval_gegenbauer_double__t *_proto_eval_gegenbauer_double__t_var = &_func_eval_gegenbauer[double] +from .orthogonal_eval cimport eval_gegenbauer_l as _func_eval_gegenbauer_l +ctypedef double _proto_eval_gegenbauer_l_t(Py_ssize_t, double, double) noexcept nogil +cdef _proto_eval_gegenbauer_l_t *_proto_eval_gegenbauer_l_t_var = &_func_eval_gegenbauer_l +from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre +ctypedef double complex _proto_eval_genlaguerre_double_complex__t(double, double, double complex) noexcept nogil +cdef _proto_eval_genlaguerre_double_complex__t *_proto_eval_genlaguerre_double_complex__t_var = &_func_eval_genlaguerre[double_complex] +from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre +ctypedef double _proto_eval_genlaguerre_double__t(double, double, double) noexcept nogil +cdef _proto_eval_genlaguerre_double__t *_proto_eval_genlaguerre_double__t_var = &_func_eval_genlaguerre[double] +from .orthogonal_eval cimport eval_genlaguerre_l as _func_eval_genlaguerre_l +ctypedef double _proto_eval_genlaguerre_l_t(Py_ssize_t, double, double) noexcept nogil +cdef _proto_eval_genlaguerre_l_t *_proto_eval_genlaguerre_l_t_var = &_func_eval_genlaguerre_l +from .orthogonal_eval cimport eval_hermite as _func_eval_hermite +ctypedef double _proto_eval_hermite_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_hermite_t *_proto_eval_hermite_t_var = &_func_eval_hermite +from .orthogonal_eval cimport eval_hermitenorm as _func_eval_hermitenorm +ctypedef double _proto_eval_hermitenorm_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_hermitenorm_t *_proto_eval_hermitenorm_t_var = &_func_eval_hermitenorm +from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi +ctypedef double complex _proto_eval_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil +cdef _proto_eval_jacobi_double_complex__t *_proto_eval_jacobi_double_complex__t_var = &_func_eval_jacobi[double_complex] +from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi +ctypedef double _proto_eval_jacobi_double__t(double, double, double, double) noexcept nogil +cdef _proto_eval_jacobi_double__t *_proto_eval_jacobi_double__t_var = &_func_eval_jacobi[double] +from .orthogonal_eval cimport eval_jacobi_l as _func_eval_jacobi_l +ctypedef double _proto_eval_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil +cdef _proto_eval_jacobi_l_t *_proto_eval_jacobi_l_t_var = &_func_eval_jacobi_l +from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre +ctypedef double complex _proto_eval_laguerre_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_laguerre_double_complex__t *_proto_eval_laguerre_double_complex__t_var = &_func_eval_laguerre[double_complex] +from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre +ctypedef double _proto_eval_laguerre_double__t(double, double) noexcept nogil +cdef _proto_eval_laguerre_double__t *_proto_eval_laguerre_double__t_var = &_func_eval_laguerre[double] +from .orthogonal_eval cimport eval_laguerre_l as _func_eval_laguerre_l +ctypedef double _proto_eval_laguerre_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_laguerre_l_t *_proto_eval_laguerre_l_t_var = &_func_eval_laguerre_l +from .orthogonal_eval cimport eval_legendre as _func_eval_legendre +ctypedef double complex _proto_eval_legendre_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_legendre_double_complex__t *_proto_eval_legendre_double_complex__t_var = &_func_eval_legendre[double_complex] +from .orthogonal_eval cimport eval_legendre as _func_eval_legendre +ctypedef double _proto_eval_legendre_double__t(double, double) noexcept nogil +cdef _proto_eval_legendre_double__t *_proto_eval_legendre_double__t_var = &_func_eval_legendre[double] +from .orthogonal_eval cimport eval_legendre_l as _func_eval_legendre_l +ctypedef double _proto_eval_legendre_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_legendre_l_t *_proto_eval_legendre_l_t_var = &_func_eval_legendre_l +from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt +ctypedef double complex _proto_eval_sh_chebyt_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_sh_chebyt_double_complex__t *_proto_eval_sh_chebyt_double_complex__t_var = &_func_eval_sh_chebyt[double_complex] +from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt +ctypedef double _proto_eval_sh_chebyt_double__t(double, double) noexcept nogil +cdef _proto_eval_sh_chebyt_double__t *_proto_eval_sh_chebyt_double__t_var = &_func_eval_sh_chebyt[double] +from .orthogonal_eval cimport eval_sh_chebyt_l as _func_eval_sh_chebyt_l +ctypedef double _proto_eval_sh_chebyt_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_sh_chebyt_l_t *_proto_eval_sh_chebyt_l_t_var = &_func_eval_sh_chebyt_l +from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu +ctypedef double complex _proto_eval_sh_chebyu_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_sh_chebyu_double_complex__t *_proto_eval_sh_chebyu_double_complex__t_var = &_func_eval_sh_chebyu[double_complex] +from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu +ctypedef double _proto_eval_sh_chebyu_double__t(double, double) noexcept nogil +cdef _proto_eval_sh_chebyu_double__t *_proto_eval_sh_chebyu_double__t_var = &_func_eval_sh_chebyu[double] +from .orthogonal_eval cimport eval_sh_chebyu_l as _func_eval_sh_chebyu_l +ctypedef double _proto_eval_sh_chebyu_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_sh_chebyu_l_t *_proto_eval_sh_chebyu_l_t_var = &_func_eval_sh_chebyu_l +from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi +ctypedef double complex _proto_eval_sh_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil +cdef _proto_eval_sh_jacobi_double_complex__t *_proto_eval_sh_jacobi_double_complex__t_var = &_func_eval_sh_jacobi[double_complex] +from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi +ctypedef double _proto_eval_sh_jacobi_double__t(double, double, double, double) noexcept nogil +cdef _proto_eval_sh_jacobi_double__t *_proto_eval_sh_jacobi_double__t_var = &_func_eval_sh_jacobi[double] +from .orthogonal_eval cimport eval_sh_jacobi_l as _func_eval_sh_jacobi_l +ctypedef double _proto_eval_sh_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil +cdef _proto_eval_sh_jacobi_l_t *_proto_eval_sh_jacobi_l_t_var = &_func_eval_sh_jacobi_l +from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre +ctypedef double complex _proto_eval_sh_legendre_double_complex__t(double, double complex) noexcept nogil +cdef _proto_eval_sh_legendre_double_complex__t *_proto_eval_sh_legendre_double_complex__t_var = &_func_eval_sh_legendre[double_complex] +from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre +ctypedef double _proto_eval_sh_legendre_double__t(double, double) noexcept nogil +cdef _proto_eval_sh_legendre_double__t *_proto_eval_sh_legendre_double__t_var = &_func_eval_sh_legendre[double] +from .orthogonal_eval cimport eval_sh_legendre_l as _func_eval_sh_legendre_l +ctypedef double _proto_eval_sh_legendre_l_t(Py_ssize_t, double) noexcept nogil +cdef _proto_eval_sh_legendre_l_t *_proto_eval_sh_legendre_l_t_var = &_func_eval_sh_legendre_l +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_exp10 "cephes_exp10"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_exp2 "cephes_exp2"(double) noexcept nogil +from ._cunity cimport cexpm1 as _func_cexpm1 +ctypedef double complex _proto_cexpm1_t(double complex) noexcept nogil +cdef _proto_cexpm1_t *_proto_cexpm1_t_var = &_func_cexpm1 +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_expm1 "cephes_expm1"(double) noexcept nogil +from ._legacy cimport expn_unsafe as _func_expn_unsafe +ctypedef double _proto_expn_unsafe_t(double, double) noexcept nogil +cdef _proto_expn_unsafe_t *_proto_expn_unsafe_t_var = &_func_expn_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_expn_wrap "cephes_expn_wrap"(Py_ssize_t, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_fdtr "xsf_fdtr"(double, double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_fdtrc "xsf_fdtrc"(double, double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_fdtri "xsf_fdtri"(double, double, double) noexcept nogil +from ._cdflib_wrappers cimport fdtridfd as _func_fdtridfd +ctypedef double _proto_fdtridfd_t(double, double, double) noexcept nogil +cdef _proto_fdtridfd_t *_proto_fdtridfd_t_var = &_func_fdtridfd +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_gdtr "xsf_gdtr"(double, double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_gdtrc "xsf_gdtrc"(double, double, double) noexcept nogil +from ._cdflib_wrappers cimport gdtria as _func_gdtria +ctypedef double _proto_gdtria_t(double, double, double) noexcept nogil +cdef _proto_gdtria_t *_proto_gdtria_t_var = &_func_gdtria +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_gdtrib "xsf_gdtrib"(double, double, double) noexcept nogil +from ._cdflib_wrappers cimport gdtrix as _func_gdtrix +ctypedef double _proto_gdtrix_t(double, double, double) noexcept nogil +cdef _proto_gdtrix_t *_proto_gdtrix_t_var = &_func_gdtrix +from ._convex_analysis cimport huber as _func_huber +ctypedef double _proto_huber_t(double, double) noexcept nogil +cdef _proto_huber_t *_proto_huber_t_var = &_func_huber +from ._hyp0f1 cimport _hyp0f1_cmplx as _func__hyp0f1_cmplx +ctypedef double complex _proto__hyp0f1_cmplx_t(double, double complex) noexcept nogil +cdef _proto__hyp0f1_cmplx_t *_proto__hyp0f1_cmplx_t_var = &_func__hyp0f1_cmplx +from ._hyp0f1 cimport _hyp0f1_real as _func__hyp0f1_real +ctypedef double _proto__hyp0f1_real_t(double, double) noexcept nogil +cdef _proto__hyp0f1_real_t *_proto__hyp0f1_real_t_var = &_func__hyp0f1_real +cdef extern from r"_ufuncs_defs.h": + cdef double complex _func_chyp1f1_wrap "chyp1f1_wrap"(double, double, double complex) noexcept nogil +from ._hypergeometric cimport hyperu as _func_hyperu +ctypedef double _proto_hyperu_t(double, double, double) noexcept nogil +cdef _proto_hyperu_t *_proto_hyperu_t_var = &_func_hyperu +from ._boxcox cimport inv_boxcox as _func_inv_boxcox +ctypedef double _proto_inv_boxcox_t(double, double) noexcept nogil +cdef _proto_inv_boxcox_t *_proto_inv_boxcox_t_var = &_func_inv_boxcox +from ._boxcox cimport inv_boxcox1p as _func_inv_boxcox1p +ctypedef double _proto_inv_boxcox1p_t(double, double) noexcept nogil +cdef _proto_inv_boxcox1p_t *_proto_inv_boxcox1p_t_var = &_func_inv_boxcox1p +from ._convex_analysis cimport kl_div as _func_kl_div +ctypedef double _proto_kl_div_t(double, double) noexcept nogil +cdef _proto_kl_div_t *_proto_kl_div_t_var = &_func_kl_div +from ._legacy cimport kn_unsafe as _func_kn_unsafe +ctypedef double _proto_kn_unsafe_t(double, double) noexcept nogil +cdef _proto_kn_unsafe_t *_proto_kn_unsafe_t_var = &_func_kn_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_special_cyl_bessel_k_int "special_cyl_bessel_k_int"(Py_ssize_t, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_kolmogi "xsf_kolmogi"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_kolmogorov "xsf_kolmogorov"(double) noexcept nogil +from ._cunity cimport clog1p as _func_clog1p +ctypedef double complex _proto_clog1p_t(double complex) noexcept nogil +cdef _proto_clog1p_t *_proto_clog1p_t_var = &_func_clog1p +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_log1p "cephes_log1p"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_pmv_wrap "pmv_wrap"(double, double, double) noexcept nogil +from ._legacy cimport nbdtr_unsafe as _func_nbdtr_unsafe +ctypedef double _proto_nbdtr_unsafe_t(double, double, double) noexcept nogil +cdef _proto_nbdtr_unsafe_t *_proto_nbdtr_unsafe_t_var = &_func_nbdtr_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_nbdtr_wrap "cephes_nbdtr_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil +from ._legacy cimport nbdtrc_unsafe as _func_nbdtrc_unsafe +ctypedef double _proto_nbdtrc_unsafe_t(double, double, double) noexcept nogil +cdef _proto_nbdtrc_unsafe_t *_proto_nbdtrc_unsafe_t_var = &_func_nbdtrc_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_nbdtrc_wrap "cephes_nbdtrc_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil +from ._legacy cimport nbdtri_unsafe as _func_nbdtri_unsafe +ctypedef double _proto_nbdtri_unsafe_t(double, double, double) noexcept nogil +cdef _proto_nbdtri_unsafe_t *_proto_nbdtri_unsafe_t_var = &_func_nbdtri_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_nbdtri_wrap "cephes_nbdtri_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil +from ._cdflib_wrappers cimport nbdtrik as _func_nbdtrik +ctypedef double _proto_nbdtrik_t(double, double, double) noexcept nogil +cdef _proto_nbdtrik_t *_proto_nbdtrik_t_var = &_func_nbdtrik +from ._cdflib_wrappers cimport nbdtrin as _func_nbdtrin +ctypedef double _proto_nbdtrin_t(double, double, double) noexcept nogil +cdef _proto_nbdtrin_t *_proto_nbdtrin_t_var = &_func_nbdtrin +from ._cdflib_wrappers cimport ncfdtridfd as _func_ncfdtridfd +ctypedef double _proto_ncfdtridfd_t(double, double, double, double) noexcept nogil +cdef _proto_ncfdtridfd_t *_proto_ncfdtridfd_t_var = &_func_ncfdtridfd +from ._cdflib_wrappers cimport ncfdtridfn as _func_ncfdtridfn +ctypedef double _proto_ncfdtridfn_t(double, double, double, double) noexcept nogil +cdef _proto_ncfdtridfn_t *_proto_ncfdtridfn_t_var = &_func_ncfdtridfn +from ._cdflib_wrappers cimport ncfdtrinc as _func_ncfdtrinc +ctypedef double _proto_ncfdtrinc_t(double, double, double, double) noexcept nogil +cdef _proto_ncfdtrinc_t *_proto_ncfdtrinc_t_var = &_func_ncfdtrinc +from ._cdflib_wrappers cimport nctdtridf as _func_nctdtridf +ctypedef double _proto_nctdtridf_t(double, double, double) noexcept nogil +cdef _proto_nctdtridf_t *_proto_nctdtridf_t_var = &_func_nctdtridf +from ._cdflib_wrappers cimport nctdtrinc as _func_nctdtrinc +ctypedef double _proto_nctdtrinc_t(double, double, double) noexcept nogil +cdef _proto_nctdtrinc_t *_proto_nctdtrinc_t_var = &_func_nctdtrinc +from ._cdflib_wrappers cimport nctdtrit as _func_nctdtrit +ctypedef double _proto_nctdtrit_t(double, double, double) noexcept nogil +cdef _proto_nctdtrit_t *_proto_nctdtrit_t_var = &_func_nctdtrit +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_ndtr "xsf_ndtr"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_ndtri "xsf_ndtri"(double) noexcept nogil +from ._ndtri_exp cimport ndtri_exp as _func_ndtri_exp +ctypedef double _proto_ndtri_exp_t(double) noexcept nogil +cdef _proto_ndtri_exp_t *_proto_ndtri_exp_t_var = &_func_ndtri_exp +from ._cdflib_wrappers cimport nrdtrimn as _func_nrdtrimn +ctypedef double _proto_nrdtrimn_t(double, double, double) noexcept nogil +cdef _proto_nrdtrimn_t *_proto_nrdtrimn_t_var = &_func_nrdtrimn +from ._cdflib_wrappers cimport nrdtrisd as _func_nrdtrisd +ctypedef double _proto_nrdtrisd_t(double, double, double) noexcept nogil +cdef _proto_nrdtrisd_t *_proto_nrdtrisd_t_var = &_func_nrdtrisd +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_owens_t "xsf_owens_t"(double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_pdtr "xsf_pdtr"(double, double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_pdtrc "xsf_pdtrc"(double, double) noexcept nogil +from ._legacy cimport pdtri_unsafe as _func_pdtri_unsafe +ctypedef double _proto_pdtri_unsafe_t(double, double) noexcept nogil +cdef _proto_pdtri_unsafe_t *_proto_pdtri_unsafe_t_var = &_func_pdtri_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_pdtri_wrap "cephes_pdtri_wrap"(Py_ssize_t, double) noexcept nogil +from ._cdflib_wrappers cimport pdtrik as _func_pdtrik +ctypedef double _proto_pdtrik_t(double, double) noexcept nogil +cdef _proto_pdtrik_t *_proto_pdtrik_t_var = &_func_pdtrik +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_poch "cephes_poch"(double, double) noexcept nogil +from ._convex_analysis cimport pseudo_huber as _func_pseudo_huber +ctypedef double _proto_pseudo_huber_t(double, double) noexcept nogil +cdef _proto_pseudo_huber_t *_proto_pseudo_huber_t_var = &_func_pseudo_huber +from ._convex_analysis cimport rel_entr as _func_rel_entr +ctypedef double _proto_rel_entr_t(double, double) noexcept nogil +cdef _proto_rel_entr_t *_proto_rel_entr_t_var = &_func_rel_entr +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_round "cephes_round"(double) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef int _func_xsf_cshichi "xsf_cshichi"(double complex, double complex *, double complex *) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef int _func_xsf_shichi "xsf_shichi"(double, double *, double *) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef int _func_xsf_csici "xsf_csici"(double complex, double complex *, double complex *) noexcept nogil +cdef extern from r"_ufuncs_defs.h": + cdef int _func_xsf_sici "xsf_sici"(double, double *, double *) noexcept nogil +from ._legacy cimport smirnov_unsafe as _func_smirnov_unsafe +ctypedef double _proto_smirnov_unsafe_t(double, double) noexcept nogil +cdef _proto_smirnov_unsafe_t *_proto_smirnov_unsafe_t_var = &_func_smirnov_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_smirnov_wrap "cephes_smirnov_wrap"(Py_ssize_t, double) noexcept nogil +from ._legacy cimport smirnovi_unsafe as _func_smirnovi_unsafe +ctypedef double _proto_smirnovi_unsafe_t(double, double) noexcept nogil +cdef _proto_smirnovi_unsafe_t *_proto_smirnovi_unsafe_t_var = &_func_smirnovi_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_smirnovi_wrap "cephes_smirnovi_wrap"(Py_ssize_t, double) noexcept nogil +from ._spence cimport cspence as _func_cspence +ctypedef double complex _proto_cspence_t(double complex) noexcept nogil +cdef _proto_cspence_t *_proto_cspence_t_var = &_func_cspence +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_spence "cephes_spence"(double) noexcept nogil +from ._cdflib_wrappers cimport stdtr as _func_stdtr +ctypedef double _proto_stdtr_t(double, double) noexcept nogil +cdef _proto_stdtr_t *_proto_stdtr_t_var = &_func_stdtr +from ._cdflib_wrappers cimport stdtridf as _func_stdtridf +ctypedef double _proto_stdtridf_t(double, double) noexcept nogil +cdef _proto_stdtridf_t *_proto_stdtridf_t_var = &_func_stdtridf +from ._cdflib_wrappers cimport stdtrit as _func_stdtrit +ctypedef double _proto_stdtrit_t(double, double) noexcept nogil +cdef _proto_stdtrit_t *_proto_stdtrit_t_var = &_func_stdtrit +cdef extern from r"_ufuncs_defs.h": + cdef double _func_xsf_tukeylambdacdf "xsf_tukeylambdacdf"(double, double) noexcept nogil +from ._xlogy cimport xlog1py as _func_xlog1py +ctypedef double _proto_xlog1py_double__t(double, double) noexcept nogil +cdef _proto_xlog1py_double__t *_proto_xlog1py_double__t_var = &_func_xlog1py[double] +from ._xlogy cimport xlog1py as _func_xlog1py +ctypedef double complex _proto_xlog1py_double_complex__t(double complex, double complex) noexcept nogil +cdef _proto_xlog1py_double_complex__t *_proto_xlog1py_double_complex__t_var = &_func_xlog1py[double_complex] +from ._xlogy cimport xlogy as _func_xlogy +ctypedef double _proto_xlogy_double__t(double, double) noexcept nogil +cdef _proto_xlogy_double__t *_proto_xlogy_double__t_var = &_func_xlogy[double] +from ._xlogy cimport xlogy as _func_xlogy +ctypedef double complex _proto_xlogy_double_complex__t(double complex, double complex) noexcept nogil +cdef _proto_xlogy_double_complex__t *_proto_xlogy_double_complex__t_var = &_func_xlogy[double_complex] +from ._legacy cimport yn_unsafe as _func_yn_unsafe +ctypedef double _proto_yn_unsafe_t(double, double) noexcept nogil +cdef _proto_yn_unsafe_t *_proto_yn_unsafe_t_var = &_func_yn_unsafe +cdef extern from r"_ufuncs_defs.h": + cdef double _func_cephes_yn_wrap "cephes_yn_wrap"(Py_ssize_t, double) noexcept nogil +cdef np.PyUFuncGenericFunction ufunc__beta_pdf_loops[2] +cdef void *ufunc__beta_pdf_ptr[4] +cdef void *ufunc__beta_pdf_data[2] +cdef char ufunc__beta_pdf_types[8] +cdef char *ufunc__beta_pdf_doc = ( + "_beta_pdf(x, a, b)\n" + "\n" + "Probability density function of beta distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued such that :math:`0 \\leq x \\leq 1`,\n" + " the upper limit of integration\n" + "a, b : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__beta_pdf_loops[0] = loop_f_fff__As_fff_f +ufunc__beta_pdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__beta_pdf_types[0] = NPY_FLOAT +ufunc__beta_pdf_types[1] = NPY_FLOAT +ufunc__beta_pdf_types[2] = NPY_FLOAT +ufunc__beta_pdf_types[3] = NPY_FLOAT +ufunc__beta_pdf_types[4] = NPY_DOUBLE +ufunc__beta_pdf_types[5] = NPY_DOUBLE +ufunc__beta_pdf_types[6] = NPY_DOUBLE +ufunc__beta_pdf_types[7] = NPY_DOUBLE +ufunc__beta_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_pdf_float +ufunc__beta_pdf_ptr[2*0+1] = ("_beta_pdf") +ufunc__beta_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_pdf_double +ufunc__beta_pdf_ptr[2*1+1] = ("_beta_pdf") +ufunc__beta_pdf_data[0] = &ufunc__beta_pdf_ptr[2*0] +ufunc__beta_pdf_data[1] = &ufunc__beta_pdf_ptr[2*1] +_beta_pdf = np.PyUFunc_FromFuncAndData(ufunc__beta_pdf_loops, ufunc__beta_pdf_data, ufunc__beta_pdf_types, 2, 3, 1, 0, "_beta_pdf", ufunc__beta_pdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__beta_ppf_loops[2] +cdef void *ufunc__beta_ppf_ptr[4] +cdef void *ufunc__beta_ppf_data[2] +cdef char ufunc__beta_ppf_types[8] +cdef char *ufunc__beta_ppf_doc = ( + "_beta_ppf(x, a, b)\n" + "\n" + "Percent point function of beta distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued such that :math:`0 \\leq x \\leq 1`,\n" + " the upper limit of integration\n" + "a, b : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__beta_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__beta_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__beta_ppf_types[0] = NPY_FLOAT +ufunc__beta_ppf_types[1] = NPY_FLOAT +ufunc__beta_ppf_types[2] = NPY_FLOAT +ufunc__beta_ppf_types[3] = NPY_FLOAT +ufunc__beta_ppf_types[4] = NPY_DOUBLE +ufunc__beta_ppf_types[5] = NPY_DOUBLE +ufunc__beta_ppf_types[6] = NPY_DOUBLE +ufunc__beta_ppf_types[7] = NPY_DOUBLE +ufunc__beta_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_ppf_float +ufunc__beta_ppf_ptr[2*0+1] = ("_beta_ppf") +ufunc__beta_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_ppf_double +ufunc__beta_ppf_ptr[2*1+1] = ("_beta_ppf") +ufunc__beta_ppf_data[0] = &ufunc__beta_ppf_ptr[2*0] +ufunc__beta_ppf_data[1] = &ufunc__beta_ppf_ptr[2*1] +_beta_ppf = np.PyUFunc_FromFuncAndData(ufunc__beta_ppf_loops, ufunc__beta_ppf_data, ufunc__beta_ppf_types, 2, 3, 1, 0, "_beta_ppf", ufunc__beta_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__binom_cdf_loops[2] +cdef void *ufunc__binom_cdf_ptr[4] +cdef void *ufunc__binom_cdf_data[2] +cdef char ufunc__binom_cdf_types[8] +cdef char *ufunc__binom_cdf_doc = ( + "_binom_cdf(x, n, p)\n" + "\n" + "Cumulative density function of binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "n : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__binom_cdf_loops[0] = loop_f_fff__As_fff_f +ufunc__binom_cdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__binom_cdf_types[0] = NPY_FLOAT +ufunc__binom_cdf_types[1] = NPY_FLOAT +ufunc__binom_cdf_types[2] = NPY_FLOAT +ufunc__binom_cdf_types[3] = NPY_FLOAT +ufunc__binom_cdf_types[4] = NPY_DOUBLE +ufunc__binom_cdf_types[5] = NPY_DOUBLE +ufunc__binom_cdf_types[6] = NPY_DOUBLE +ufunc__binom_cdf_types[7] = NPY_DOUBLE +ufunc__binom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_cdf_float +ufunc__binom_cdf_ptr[2*0+1] = ("_binom_cdf") +ufunc__binom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_cdf_double +ufunc__binom_cdf_ptr[2*1+1] = ("_binom_cdf") +ufunc__binom_cdf_data[0] = &ufunc__binom_cdf_ptr[2*0] +ufunc__binom_cdf_data[1] = &ufunc__binom_cdf_ptr[2*1] +_binom_cdf = np.PyUFunc_FromFuncAndData(ufunc__binom_cdf_loops, ufunc__binom_cdf_data, ufunc__binom_cdf_types, 2, 3, 1, 0, "_binom_cdf", ufunc__binom_cdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__binom_isf_loops[2] +cdef void *ufunc__binom_isf_ptr[4] +cdef void *ufunc__binom_isf_data[2] +cdef char ufunc__binom_isf_types[8] +cdef char *ufunc__binom_isf_doc = ( + "_binom_isf(x, n, p)\n" + "\n" + "Inverse survival function of binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "n : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__binom_isf_loops[0] = loop_f_fff__As_fff_f +ufunc__binom_isf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__binom_isf_types[0] = NPY_FLOAT +ufunc__binom_isf_types[1] = NPY_FLOAT +ufunc__binom_isf_types[2] = NPY_FLOAT +ufunc__binom_isf_types[3] = NPY_FLOAT +ufunc__binom_isf_types[4] = NPY_DOUBLE +ufunc__binom_isf_types[5] = NPY_DOUBLE +ufunc__binom_isf_types[6] = NPY_DOUBLE +ufunc__binom_isf_types[7] = NPY_DOUBLE +ufunc__binom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_isf_float +ufunc__binom_isf_ptr[2*0+1] = ("_binom_isf") +ufunc__binom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_isf_double +ufunc__binom_isf_ptr[2*1+1] = ("_binom_isf") +ufunc__binom_isf_data[0] = &ufunc__binom_isf_ptr[2*0] +ufunc__binom_isf_data[1] = &ufunc__binom_isf_ptr[2*1] +_binom_isf = np.PyUFunc_FromFuncAndData(ufunc__binom_isf_loops, ufunc__binom_isf_data, ufunc__binom_isf_types, 2, 3, 1, 0, "_binom_isf", ufunc__binom_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__binom_pmf_loops[2] +cdef void *ufunc__binom_pmf_ptr[4] +cdef void *ufunc__binom_pmf_data[2] +cdef char ufunc__binom_pmf_types[8] +cdef char *ufunc__binom_pmf_doc = ( + "_binom_pmf(x, n, p)\n" + "\n" + "Probability mass function of binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "n : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__binom_pmf_loops[0] = loop_f_fff__As_fff_f +ufunc__binom_pmf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__binom_pmf_types[0] = NPY_FLOAT +ufunc__binom_pmf_types[1] = NPY_FLOAT +ufunc__binom_pmf_types[2] = NPY_FLOAT +ufunc__binom_pmf_types[3] = NPY_FLOAT +ufunc__binom_pmf_types[4] = NPY_DOUBLE +ufunc__binom_pmf_types[5] = NPY_DOUBLE +ufunc__binom_pmf_types[6] = NPY_DOUBLE +ufunc__binom_pmf_types[7] = NPY_DOUBLE +ufunc__binom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_pmf_float +ufunc__binom_pmf_ptr[2*0+1] = ("_binom_pmf") +ufunc__binom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_pmf_double +ufunc__binom_pmf_ptr[2*1+1] = ("_binom_pmf") +ufunc__binom_pmf_data[0] = &ufunc__binom_pmf_ptr[2*0] +ufunc__binom_pmf_data[1] = &ufunc__binom_pmf_ptr[2*1] +_binom_pmf = np.PyUFunc_FromFuncAndData(ufunc__binom_pmf_loops, ufunc__binom_pmf_data, ufunc__binom_pmf_types, 2, 3, 1, 0, "_binom_pmf", ufunc__binom_pmf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__binom_ppf_loops[2] +cdef void *ufunc__binom_ppf_ptr[4] +cdef void *ufunc__binom_ppf_data[2] +cdef char ufunc__binom_ppf_types[8] +cdef char *ufunc__binom_ppf_doc = ( + "_binom_ppf(x, n, p)\n" + "\n" + "Percent point function of binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "n : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__binom_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__binom_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__binom_ppf_types[0] = NPY_FLOAT +ufunc__binom_ppf_types[1] = NPY_FLOAT +ufunc__binom_ppf_types[2] = NPY_FLOAT +ufunc__binom_ppf_types[3] = NPY_FLOAT +ufunc__binom_ppf_types[4] = NPY_DOUBLE +ufunc__binom_ppf_types[5] = NPY_DOUBLE +ufunc__binom_ppf_types[6] = NPY_DOUBLE +ufunc__binom_ppf_types[7] = NPY_DOUBLE +ufunc__binom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_ppf_float +ufunc__binom_ppf_ptr[2*0+1] = ("_binom_ppf") +ufunc__binom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_ppf_double +ufunc__binom_ppf_ptr[2*1+1] = ("_binom_ppf") +ufunc__binom_ppf_data[0] = &ufunc__binom_ppf_ptr[2*0] +ufunc__binom_ppf_data[1] = &ufunc__binom_ppf_ptr[2*1] +_binom_ppf = np.PyUFunc_FromFuncAndData(ufunc__binom_ppf_loops, ufunc__binom_ppf_data, ufunc__binom_ppf_types, 2, 3, 1, 0, "_binom_ppf", ufunc__binom_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__binom_sf_loops[2] +cdef void *ufunc__binom_sf_ptr[4] +cdef void *ufunc__binom_sf_data[2] +cdef char ufunc__binom_sf_types[8] +cdef char *ufunc__binom_sf_doc = ( + "_binom_sf(x, n, p)\n" + "\n" + "Survival function of binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "n : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__binom_sf_loops[0] = loop_f_fff__As_fff_f +ufunc__binom_sf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__binom_sf_types[0] = NPY_FLOAT +ufunc__binom_sf_types[1] = NPY_FLOAT +ufunc__binom_sf_types[2] = NPY_FLOAT +ufunc__binom_sf_types[3] = NPY_FLOAT +ufunc__binom_sf_types[4] = NPY_DOUBLE +ufunc__binom_sf_types[5] = NPY_DOUBLE +ufunc__binom_sf_types[6] = NPY_DOUBLE +ufunc__binom_sf_types[7] = NPY_DOUBLE +ufunc__binom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_sf_float +ufunc__binom_sf_ptr[2*0+1] = ("_binom_sf") +ufunc__binom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_sf_double +ufunc__binom_sf_ptr[2*1+1] = ("_binom_sf") +ufunc__binom_sf_data[0] = &ufunc__binom_sf_ptr[2*0] +ufunc__binom_sf_data[1] = &ufunc__binom_sf_ptr[2*1] +_binom_sf = np.PyUFunc_FromFuncAndData(ufunc__binom_sf_loops, ufunc__binom_sf_data, ufunc__binom_sf_types, 2, 3, 1, 0, "_binom_sf", ufunc__binom_sf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__cauchy_isf_loops[2] +cdef void *ufunc__cauchy_isf_ptr[4] +cdef void *ufunc__cauchy_isf_data[2] +cdef char ufunc__cauchy_isf_types[8] +cdef char *ufunc__cauchy_isf_doc = ( + "_cauchy_isf(p, loc, scale)\n" + "\n" + "Inverse survival function of the Cauchy distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probabilities\n" + "loc : array_like\n" + " Location parameter of the distribution.\n" + "scale : array_like\n" + " Scale parameter of the distribution.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__cauchy_isf_loops[0] = loop_f_fff__As_fff_f +ufunc__cauchy_isf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__cauchy_isf_types[0] = NPY_FLOAT +ufunc__cauchy_isf_types[1] = NPY_FLOAT +ufunc__cauchy_isf_types[2] = NPY_FLOAT +ufunc__cauchy_isf_types[3] = NPY_FLOAT +ufunc__cauchy_isf_types[4] = NPY_DOUBLE +ufunc__cauchy_isf_types[5] = NPY_DOUBLE +ufunc__cauchy_isf_types[6] = NPY_DOUBLE +ufunc__cauchy_isf_types[7] = NPY_DOUBLE +ufunc__cauchy_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_isf_float +ufunc__cauchy_isf_ptr[2*0+1] = ("_cauchy_isf") +ufunc__cauchy_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_isf_double +ufunc__cauchy_isf_ptr[2*1+1] = ("_cauchy_isf") +ufunc__cauchy_isf_data[0] = &ufunc__cauchy_isf_ptr[2*0] +ufunc__cauchy_isf_data[1] = &ufunc__cauchy_isf_ptr[2*1] +_cauchy_isf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_isf_loops, ufunc__cauchy_isf_data, ufunc__cauchy_isf_types, 2, 3, 1, 0, "_cauchy_isf", ufunc__cauchy_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__cauchy_ppf_loops[2] +cdef void *ufunc__cauchy_ppf_ptr[4] +cdef void *ufunc__cauchy_ppf_data[2] +cdef char ufunc__cauchy_ppf_types[8] +cdef char *ufunc__cauchy_ppf_doc = ( + "_cauchy_ppf(p, loc, scale)\n" + "\n" + "Percent point function (i.e. quantile) of the Cauchy distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probabilities\n" + "loc : array_like\n" + " Location parameter of the distribution.\n" + "scale : array_like\n" + " Scale parameter of the distribution.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__cauchy_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__cauchy_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__cauchy_ppf_types[0] = NPY_FLOAT +ufunc__cauchy_ppf_types[1] = NPY_FLOAT +ufunc__cauchy_ppf_types[2] = NPY_FLOAT +ufunc__cauchy_ppf_types[3] = NPY_FLOAT +ufunc__cauchy_ppf_types[4] = NPY_DOUBLE +ufunc__cauchy_ppf_types[5] = NPY_DOUBLE +ufunc__cauchy_ppf_types[6] = NPY_DOUBLE +ufunc__cauchy_ppf_types[7] = NPY_DOUBLE +ufunc__cauchy_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_ppf_float +ufunc__cauchy_ppf_ptr[2*0+1] = ("_cauchy_ppf") +ufunc__cauchy_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_ppf_double +ufunc__cauchy_ppf_ptr[2*1+1] = ("_cauchy_ppf") +ufunc__cauchy_ppf_data[0] = &ufunc__cauchy_ppf_ptr[2*0] +ufunc__cauchy_ppf_data[1] = &ufunc__cauchy_ppf_ptr[2*1] +_cauchy_ppf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_ppf_loops, ufunc__cauchy_ppf_data, ufunc__cauchy_ppf_types, 2, 3, 1, 0, "_cauchy_ppf", ufunc__cauchy_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__cosine_cdf_loops[2] +cdef void *ufunc__cosine_cdf_ptr[4] +cdef void *ufunc__cosine_cdf_data[2] +cdef char ufunc__cosine_cdf_types[4] +cdef char *ufunc__cosine_cdf_doc = ( + "_cosine_cdf(x)\n" + "\n" + "Cumulative distribution function (CDF) of the cosine distribution::\n" + "\n" + " { 0, x < -pi\n" + " cdf(x) = { (pi + x + sin(x))/(2*pi), -pi <= x <= pi\n" + " { 1, x > pi\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " `x` must contain real numbers.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The cosine distribution CDF evaluated at `x`.") +ufunc__cosine_cdf_loops[0] = loop_d_d__As_f_f +ufunc__cosine_cdf_loops[1] = loop_d_d__As_d_d +ufunc__cosine_cdf_types[0] = NPY_FLOAT +ufunc__cosine_cdf_types[1] = NPY_FLOAT +ufunc__cosine_cdf_types[2] = NPY_DOUBLE +ufunc__cosine_cdf_types[3] = NPY_DOUBLE +ufunc__cosine_cdf_ptr[2*0] = _func_cosine_cdf +ufunc__cosine_cdf_ptr[2*0+1] = ("_cosine_cdf") +ufunc__cosine_cdf_ptr[2*1] = _func_cosine_cdf +ufunc__cosine_cdf_ptr[2*1+1] = ("_cosine_cdf") +ufunc__cosine_cdf_data[0] = &ufunc__cosine_cdf_ptr[2*0] +ufunc__cosine_cdf_data[1] = &ufunc__cosine_cdf_ptr[2*1] +_cosine_cdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_cdf_loops, ufunc__cosine_cdf_data, ufunc__cosine_cdf_types, 2, 1, 1, 0, "_cosine_cdf", ufunc__cosine_cdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__cosine_invcdf_loops[2] +cdef void *ufunc__cosine_invcdf_ptr[4] +cdef void *ufunc__cosine_invcdf_data[2] +cdef char ufunc__cosine_invcdf_types[4] +cdef char *ufunc__cosine_invcdf_doc = ( + "_cosine_invcdf(p)\n" + "\n" + "Inverse of the cumulative distribution function (CDF) of the cosine\n" + "distribution.\n" + "\n" + "The CDF of the cosine distribution is::\n" + "\n" + " cdf(x) = (pi + x + sin(x))/(2*pi)\n" + "\n" + "This function computes the inverse of cdf(x).\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " `p` must contain real numbers in the interval ``0 <= p <= 1``.\n" + " `nan` is returned for values of `p` outside the interval [0, 1].\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The inverse of the cosine distribution CDF evaluated at `p`.") +ufunc__cosine_invcdf_loops[0] = loop_d_d__As_f_f +ufunc__cosine_invcdf_loops[1] = loop_d_d__As_d_d +ufunc__cosine_invcdf_types[0] = NPY_FLOAT +ufunc__cosine_invcdf_types[1] = NPY_FLOAT +ufunc__cosine_invcdf_types[2] = NPY_DOUBLE +ufunc__cosine_invcdf_types[3] = NPY_DOUBLE +ufunc__cosine_invcdf_ptr[2*0] = _func_cosine_invcdf +ufunc__cosine_invcdf_ptr[2*0+1] = ("_cosine_invcdf") +ufunc__cosine_invcdf_ptr[2*1] = _func_cosine_invcdf +ufunc__cosine_invcdf_ptr[2*1+1] = ("_cosine_invcdf") +ufunc__cosine_invcdf_data[0] = &ufunc__cosine_invcdf_ptr[2*0] +ufunc__cosine_invcdf_data[1] = &ufunc__cosine_invcdf_ptr[2*1] +_cosine_invcdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_invcdf_loops, ufunc__cosine_invcdf_data, ufunc__cosine_invcdf_types, 2, 1, 1, 0, "_cosine_invcdf", ufunc__cosine_invcdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ellip_harm_loops[3] +cdef void *ufunc__ellip_harm_ptr[6] +cdef void *ufunc__ellip_harm_data[3] +cdef char ufunc__ellip_harm_types[24] +cdef char *ufunc__ellip_harm_doc = ( + "Internal function, use `ellip_harm` instead.") +ufunc__ellip_harm_loops[0] = loop_d_ddddddd__As_fffffff_f +ufunc__ellip_harm_loops[1] = loop_d_ddiiddd__As_ddllddd_d +ufunc__ellip_harm_loops[2] = loop_d_ddddddd__As_ddddddd_d +ufunc__ellip_harm_types[0] = NPY_FLOAT +ufunc__ellip_harm_types[1] = NPY_FLOAT +ufunc__ellip_harm_types[2] = NPY_FLOAT +ufunc__ellip_harm_types[3] = NPY_FLOAT +ufunc__ellip_harm_types[4] = NPY_FLOAT +ufunc__ellip_harm_types[5] = NPY_FLOAT +ufunc__ellip_harm_types[6] = NPY_FLOAT +ufunc__ellip_harm_types[7] = NPY_FLOAT +ufunc__ellip_harm_types[8] = NPY_DOUBLE +ufunc__ellip_harm_types[9] = NPY_DOUBLE +ufunc__ellip_harm_types[10] = NPY_LONG +ufunc__ellip_harm_types[11] = NPY_LONG +ufunc__ellip_harm_types[12] = NPY_DOUBLE +ufunc__ellip_harm_types[13] = NPY_DOUBLE +ufunc__ellip_harm_types[14] = NPY_DOUBLE +ufunc__ellip_harm_types[15] = NPY_DOUBLE +ufunc__ellip_harm_types[16] = NPY_DOUBLE +ufunc__ellip_harm_types[17] = NPY_DOUBLE +ufunc__ellip_harm_types[18] = NPY_DOUBLE +ufunc__ellip_harm_types[19] = NPY_DOUBLE +ufunc__ellip_harm_types[20] = NPY_DOUBLE +ufunc__ellip_harm_types[21] = NPY_DOUBLE +ufunc__ellip_harm_types[22] = NPY_DOUBLE +ufunc__ellip_harm_types[23] = NPY_DOUBLE +ufunc__ellip_harm_ptr[2*0] = _func_ellip_harmonic_unsafe +ufunc__ellip_harm_ptr[2*0+1] = ("_ellip_harm") +ufunc__ellip_harm_ptr[2*1] = _func_ellip_harmonic +ufunc__ellip_harm_ptr[2*1+1] = ("_ellip_harm") +ufunc__ellip_harm_ptr[2*2] = _func_ellip_harmonic_unsafe +ufunc__ellip_harm_ptr[2*2+1] = ("_ellip_harm") +ufunc__ellip_harm_data[0] = &ufunc__ellip_harm_ptr[2*0] +ufunc__ellip_harm_data[1] = &ufunc__ellip_harm_ptr[2*1] +ufunc__ellip_harm_data[2] = &ufunc__ellip_harm_ptr[2*2] +_ellip_harm = np.PyUFunc_FromFuncAndData(ufunc__ellip_harm_loops, ufunc__ellip_harm_data, ufunc__ellip_harm_types, 3, 7, 1, 0, "_ellip_harm", ufunc__ellip_harm_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__factorial_loops[2] +cdef void *ufunc__factorial_ptr[4] +cdef void *ufunc__factorial_data[2] +cdef char ufunc__factorial_types[4] +cdef char *ufunc__factorial_doc = ( + "Internal function, do not use.") +ufunc__factorial_loops[0] = loop_d_d__As_f_f +ufunc__factorial_loops[1] = loop_d_d__As_d_d +ufunc__factorial_types[0] = NPY_FLOAT +ufunc__factorial_types[1] = NPY_FLOAT +ufunc__factorial_types[2] = NPY_DOUBLE +ufunc__factorial_types[3] = NPY_DOUBLE +ufunc__factorial_ptr[2*0] = _func__factorial +ufunc__factorial_ptr[2*0+1] = ("_factorial") +ufunc__factorial_ptr[2*1] = _func__factorial +ufunc__factorial_ptr[2*1+1] = ("_factorial") +ufunc__factorial_data[0] = &ufunc__factorial_ptr[2*0] +ufunc__factorial_data[1] = &ufunc__factorial_ptr[2*1] +_factorial = np.PyUFunc_FromFuncAndData(ufunc__factorial_loops, ufunc__factorial_data, ufunc__factorial_types, 2, 1, 1, 0, "_factorial", ufunc__factorial_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__hypergeom_cdf_loops[2] +cdef void *ufunc__hypergeom_cdf_ptr[4] +cdef void *ufunc__hypergeom_cdf_data[2] +cdef char ufunc__hypergeom_cdf_types[10] +cdef char *ufunc__hypergeom_cdf_doc = ( + "_hypergeom_cdf(x, r, N, M)\n" + "\n" + "Cumulative density function of hypergeometric distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r, N, M : array_like\n" + " Positive, integer-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__hypergeom_cdf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__hypergeom_cdf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__hypergeom_cdf_types[0] = NPY_FLOAT +ufunc__hypergeom_cdf_types[1] = NPY_FLOAT +ufunc__hypergeom_cdf_types[2] = NPY_FLOAT +ufunc__hypergeom_cdf_types[3] = NPY_FLOAT +ufunc__hypergeom_cdf_types[4] = NPY_FLOAT +ufunc__hypergeom_cdf_types[5] = NPY_DOUBLE +ufunc__hypergeom_cdf_types[6] = NPY_DOUBLE +ufunc__hypergeom_cdf_types[7] = NPY_DOUBLE +ufunc__hypergeom_cdf_types[8] = NPY_DOUBLE +ufunc__hypergeom_cdf_types[9] = NPY_DOUBLE +ufunc__hypergeom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_float +ufunc__hypergeom_cdf_ptr[2*0+1] = ("_hypergeom_cdf") +ufunc__hypergeom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_double +ufunc__hypergeom_cdf_ptr[2*1+1] = ("_hypergeom_cdf") +ufunc__hypergeom_cdf_data[0] = &ufunc__hypergeom_cdf_ptr[2*0] +ufunc__hypergeom_cdf_data[1] = &ufunc__hypergeom_cdf_ptr[2*1] +_hypergeom_cdf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_cdf_loops, ufunc__hypergeom_cdf_data, ufunc__hypergeom_cdf_types, 2, 4, 1, 0, "_hypergeom_cdf", ufunc__hypergeom_cdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__hypergeom_mean_loops[2] +cdef void *ufunc__hypergeom_mean_ptr[4] +cdef void *ufunc__hypergeom_mean_data[2] +cdef char ufunc__hypergeom_mean_types[8] +cdef char *ufunc__hypergeom_mean_doc = ( + "_hypergeom_mean(r, N, M)\n" + "\n" + "Mean of hypergeometric distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "r, N, M : array_like\n" + " Positive, integer-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__hypergeom_mean_loops[0] = loop_f_fff__As_fff_f +ufunc__hypergeom_mean_loops[1] = loop_d_ddd__As_ddd_d +ufunc__hypergeom_mean_types[0] = NPY_FLOAT +ufunc__hypergeom_mean_types[1] = NPY_FLOAT +ufunc__hypergeom_mean_types[2] = NPY_FLOAT +ufunc__hypergeom_mean_types[3] = NPY_FLOAT +ufunc__hypergeom_mean_types[4] = NPY_DOUBLE +ufunc__hypergeom_mean_types[5] = NPY_DOUBLE +ufunc__hypergeom_mean_types[6] = NPY_DOUBLE +ufunc__hypergeom_mean_types[7] = NPY_DOUBLE +ufunc__hypergeom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_mean_float +ufunc__hypergeom_mean_ptr[2*0+1] = ("_hypergeom_mean") +ufunc__hypergeom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_mean_double +ufunc__hypergeom_mean_ptr[2*1+1] = ("_hypergeom_mean") +ufunc__hypergeom_mean_data[0] = &ufunc__hypergeom_mean_ptr[2*0] +ufunc__hypergeom_mean_data[1] = &ufunc__hypergeom_mean_ptr[2*1] +_hypergeom_mean = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_mean_loops, ufunc__hypergeom_mean_data, ufunc__hypergeom_mean_types, 2, 3, 1, 0, "_hypergeom_mean", ufunc__hypergeom_mean_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__hypergeom_pmf_loops[2] +cdef void *ufunc__hypergeom_pmf_ptr[4] +cdef void *ufunc__hypergeom_pmf_data[2] +cdef char ufunc__hypergeom_pmf_types[10] +cdef char *ufunc__hypergeom_pmf_doc = ( + "_hypergeom_pmf(x, r, N, M)\n" + "\n" + "Probability mass function of hypergeometric distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r, N, M : array_like\n" + " Positive, integer-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__hypergeom_pmf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__hypergeom_pmf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__hypergeom_pmf_types[0] = NPY_FLOAT +ufunc__hypergeom_pmf_types[1] = NPY_FLOAT +ufunc__hypergeom_pmf_types[2] = NPY_FLOAT +ufunc__hypergeom_pmf_types[3] = NPY_FLOAT +ufunc__hypergeom_pmf_types[4] = NPY_FLOAT +ufunc__hypergeom_pmf_types[5] = NPY_DOUBLE +ufunc__hypergeom_pmf_types[6] = NPY_DOUBLE +ufunc__hypergeom_pmf_types[7] = NPY_DOUBLE +ufunc__hypergeom_pmf_types[8] = NPY_DOUBLE +ufunc__hypergeom_pmf_types[9] = NPY_DOUBLE +ufunc__hypergeom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_float +ufunc__hypergeom_pmf_ptr[2*0+1] = ("_hypergeom_pmf") +ufunc__hypergeom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_double +ufunc__hypergeom_pmf_ptr[2*1+1] = ("_hypergeom_pmf") +ufunc__hypergeom_pmf_data[0] = &ufunc__hypergeom_pmf_ptr[2*0] +ufunc__hypergeom_pmf_data[1] = &ufunc__hypergeom_pmf_ptr[2*1] +_hypergeom_pmf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_pmf_loops, ufunc__hypergeom_pmf_data, ufunc__hypergeom_pmf_types, 2, 4, 1, 0, "_hypergeom_pmf", ufunc__hypergeom_pmf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__hypergeom_sf_loops[2] +cdef void *ufunc__hypergeom_sf_ptr[4] +cdef void *ufunc__hypergeom_sf_data[2] +cdef char ufunc__hypergeom_sf_types[10] +cdef char *ufunc__hypergeom_sf_doc = ( + "_hypergeom_sf(x, r, N, M)\n" + "\n" + "Survival function of hypergeometric distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r, N, M : array_like\n" + " Positive, integer-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__hypergeom_sf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__hypergeom_sf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__hypergeom_sf_types[0] = NPY_FLOAT +ufunc__hypergeom_sf_types[1] = NPY_FLOAT +ufunc__hypergeom_sf_types[2] = NPY_FLOAT +ufunc__hypergeom_sf_types[3] = NPY_FLOAT +ufunc__hypergeom_sf_types[4] = NPY_FLOAT +ufunc__hypergeom_sf_types[5] = NPY_DOUBLE +ufunc__hypergeom_sf_types[6] = NPY_DOUBLE +ufunc__hypergeom_sf_types[7] = NPY_DOUBLE +ufunc__hypergeom_sf_types[8] = NPY_DOUBLE +ufunc__hypergeom_sf_types[9] = NPY_DOUBLE +ufunc__hypergeom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_sf_float +ufunc__hypergeom_sf_ptr[2*0+1] = ("_hypergeom_sf") +ufunc__hypergeom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_sf_double +ufunc__hypergeom_sf_ptr[2*1+1] = ("_hypergeom_sf") +ufunc__hypergeom_sf_data[0] = &ufunc__hypergeom_sf_ptr[2*0] +ufunc__hypergeom_sf_data[1] = &ufunc__hypergeom_sf_ptr[2*1] +_hypergeom_sf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_sf_loops, ufunc__hypergeom_sf_data, ufunc__hypergeom_sf_types, 2, 4, 1, 0, "_hypergeom_sf", ufunc__hypergeom_sf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__hypergeom_skewness_loops[2] +cdef void *ufunc__hypergeom_skewness_ptr[4] +cdef void *ufunc__hypergeom_skewness_data[2] +cdef char ufunc__hypergeom_skewness_types[8] +cdef char *ufunc__hypergeom_skewness_doc = ( + "_hypergeom_skewness(r, N, M)\n" + "\n" + "Skewness of hypergeometric distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "r, N, M : array_like\n" + " Positive, integer-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__hypergeom_skewness_loops[0] = loop_f_fff__As_fff_f +ufunc__hypergeom_skewness_loops[1] = loop_d_ddd__As_ddd_d +ufunc__hypergeom_skewness_types[0] = NPY_FLOAT +ufunc__hypergeom_skewness_types[1] = NPY_FLOAT +ufunc__hypergeom_skewness_types[2] = NPY_FLOAT +ufunc__hypergeom_skewness_types[3] = NPY_FLOAT +ufunc__hypergeom_skewness_types[4] = NPY_DOUBLE +ufunc__hypergeom_skewness_types[5] = NPY_DOUBLE +ufunc__hypergeom_skewness_types[6] = NPY_DOUBLE +ufunc__hypergeom_skewness_types[7] = NPY_DOUBLE +ufunc__hypergeom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_float +ufunc__hypergeom_skewness_ptr[2*0+1] = ("_hypergeom_skewness") +ufunc__hypergeom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_double +ufunc__hypergeom_skewness_ptr[2*1+1] = ("_hypergeom_skewness") +ufunc__hypergeom_skewness_data[0] = &ufunc__hypergeom_skewness_ptr[2*0] +ufunc__hypergeom_skewness_data[1] = &ufunc__hypergeom_skewness_ptr[2*1] +_hypergeom_skewness = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_skewness_loops, ufunc__hypergeom_skewness_data, ufunc__hypergeom_skewness_types, 2, 3, 1, 0, "_hypergeom_skewness", ufunc__hypergeom_skewness_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__hypergeom_variance_loops[2] +cdef void *ufunc__hypergeom_variance_ptr[4] +cdef void *ufunc__hypergeom_variance_data[2] +cdef char ufunc__hypergeom_variance_types[8] +cdef char *ufunc__hypergeom_variance_doc = ( + "_hypergeom_variance(r, N, M)\n" + "\n" + "Mean of hypergeometric distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "r, N, M : array_like\n" + " Positive, integer-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__hypergeom_variance_loops[0] = loop_f_fff__As_fff_f +ufunc__hypergeom_variance_loops[1] = loop_d_ddd__As_ddd_d +ufunc__hypergeom_variance_types[0] = NPY_FLOAT +ufunc__hypergeom_variance_types[1] = NPY_FLOAT +ufunc__hypergeom_variance_types[2] = NPY_FLOAT +ufunc__hypergeom_variance_types[3] = NPY_FLOAT +ufunc__hypergeom_variance_types[4] = NPY_DOUBLE +ufunc__hypergeom_variance_types[5] = NPY_DOUBLE +ufunc__hypergeom_variance_types[6] = NPY_DOUBLE +ufunc__hypergeom_variance_types[7] = NPY_DOUBLE +ufunc__hypergeom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_variance_float +ufunc__hypergeom_variance_ptr[2*0+1] = ("_hypergeom_variance") +ufunc__hypergeom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_variance_double +ufunc__hypergeom_variance_ptr[2*1+1] = ("_hypergeom_variance") +ufunc__hypergeom_variance_data[0] = &ufunc__hypergeom_variance_ptr[2*0] +ufunc__hypergeom_variance_data[1] = &ufunc__hypergeom_variance_ptr[2*1] +_hypergeom_variance = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_variance_loops, ufunc__hypergeom_variance_data, ufunc__hypergeom_variance_types, 2, 3, 1, 0, "_hypergeom_variance", ufunc__hypergeom_variance_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__igam_fac_loops[2] +cdef void *ufunc__igam_fac_ptr[4] +cdef void *ufunc__igam_fac_data[2] +cdef char ufunc__igam_fac_types[6] +cdef char *ufunc__igam_fac_doc = ( + "Internal function, do not use.") +ufunc__igam_fac_loops[0] = loop_d_dd__As_ff_f +ufunc__igam_fac_loops[1] = loop_d_dd__As_dd_d +ufunc__igam_fac_types[0] = NPY_FLOAT +ufunc__igam_fac_types[1] = NPY_FLOAT +ufunc__igam_fac_types[2] = NPY_FLOAT +ufunc__igam_fac_types[3] = NPY_DOUBLE +ufunc__igam_fac_types[4] = NPY_DOUBLE +ufunc__igam_fac_types[5] = NPY_DOUBLE +ufunc__igam_fac_ptr[2*0] = _func_cephes_igam_fac +ufunc__igam_fac_ptr[2*0+1] = ("_igam_fac") +ufunc__igam_fac_ptr[2*1] = _func_cephes_igam_fac +ufunc__igam_fac_ptr[2*1+1] = ("_igam_fac") +ufunc__igam_fac_data[0] = &ufunc__igam_fac_ptr[2*0] +ufunc__igam_fac_data[1] = &ufunc__igam_fac_ptr[2*1] +_igam_fac = np.PyUFunc_FromFuncAndData(ufunc__igam_fac_loops, ufunc__igam_fac_data, ufunc__igam_fac_types, 2, 2, 1, 0, "_igam_fac", ufunc__igam_fac_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__invgauss_isf_loops[2] +cdef void *ufunc__invgauss_isf_ptr[4] +cdef void *ufunc__invgauss_isf_data[2] +cdef char ufunc__invgauss_isf_types[8] +cdef char *ufunc__invgauss_isf_doc = ( + "_invgauss_isf(x, mu, s)\n" + "\n" + "Inverse survival function of inverse gaussian distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "mu : array_like\n" + " Positive, real-valued parameters\n" + "s : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__invgauss_isf_loops[0] = loop_f_fff__As_fff_f +ufunc__invgauss_isf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__invgauss_isf_types[0] = NPY_FLOAT +ufunc__invgauss_isf_types[1] = NPY_FLOAT +ufunc__invgauss_isf_types[2] = NPY_FLOAT +ufunc__invgauss_isf_types[3] = NPY_FLOAT +ufunc__invgauss_isf_types[4] = NPY_DOUBLE +ufunc__invgauss_isf_types[5] = NPY_DOUBLE +ufunc__invgauss_isf_types[6] = NPY_DOUBLE +ufunc__invgauss_isf_types[7] = NPY_DOUBLE +ufunc__invgauss_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_isf_float +ufunc__invgauss_isf_ptr[2*0+1] = ("_invgauss_isf") +ufunc__invgauss_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_isf_double +ufunc__invgauss_isf_ptr[2*1+1] = ("_invgauss_isf") +ufunc__invgauss_isf_data[0] = &ufunc__invgauss_isf_ptr[2*0] +ufunc__invgauss_isf_data[1] = &ufunc__invgauss_isf_ptr[2*1] +_invgauss_isf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_isf_loops, ufunc__invgauss_isf_data, ufunc__invgauss_isf_types, 2, 3, 1, 0, "_invgauss_isf", ufunc__invgauss_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__invgauss_ppf_loops[2] +cdef void *ufunc__invgauss_ppf_ptr[4] +cdef void *ufunc__invgauss_ppf_data[2] +cdef char ufunc__invgauss_ppf_types[8] +cdef char *ufunc__invgauss_ppf_doc = ( + "_invgauss_ppf(x, mu)\n" + "\n" + "Percent point function of inverse gaussian distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "mu : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__invgauss_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__invgauss_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__invgauss_ppf_types[0] = NPY_FLOAT +ufunc__invgauss_ppf_types[1] = NPY_FLOAT +ufunc__invgauss_ppf_types[2] = NPY_FLOAT +ufunc__invgauss_ppf_types[3] = NPY_FLOAT +ufunc__invgauss_ppf_types[4] = NPY_DOUBLE +ufunc__invgauss_ppf_types[5] = NPY_DOUBLE +ufunc__invgauss_ppf_types[6] = NPY_DOUBLE +ufunc__invgauss_ppf_types[7] = NPY_DOUBLE +ufunc__invgauss_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_ppf_float +ufunc__invgauss_ppf_ptr[2*0+1] = ("_invgauss_ppf") +ufunc__invgauss_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_ppf_double +ufunc__invgauss_ppf_ptr[2*1+1] = ("_invgauss_ppf") +ufunc__invgauss_ppf_data[0] = &ufunc__invgauss_ppf_ptr[2*0] +ufunc__invgauss_ppf_data[1] = &ufunc__invgauss_ppf_ptr[2*1] +_invgauss_ppf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_ppf_loops, ufunc__invgauss_ppf_data, ufunc__invgauss_ppf_types, 2, 3, 1, 0, "_invgauss_ppf", ufunc__invgauss_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__kolmogc_loops[2] +cdef void *ufunc__kolmogc_ptr[4] +cdef void *ufunc__kolmogc_data[2] +cdef char ufunc__kolmogc_types[4] +cdef char *ufunc__kolmogc_doc = ( + "Internal function, do not use.") +ufunc__kolmogc_loops[0] = loop_d_d__As_f_f +ufunc__kolmogc_loops[1] = loop_d_d__As_d_d +ufunc__kolmogc_types[0] = NPY_FLOAT +ufunc__kolmogc_types[1] = NPY_FLOAT +ufunc__kolmogc_types[2] = NPY_DOUBLE +ufunc__kolmogc_types[3] = NPY_DOUBLE +ufunc__kolmogc_ptr[2*0] = _func_xsf_kolmogc +ufunc__kolmogc_ptr[2*0+1] = ("_kolmogc") +ufunc__kolmogc_ptr[2*1] = _func_xsf_kolmogc +ufunc__kolmogc_ptr[2*1+1] = ("_kolmogc") +ufunc__kolmogc_data[0] = &ufunc__kolmogc_ptr[2*0] +ufunc__kolmogc_data[1] = &ufunc__kolmogc_ptr[2*1] +_kolmogc = np.PyUFunc_FromFuncAndData(ufunc__kolmogc_loops, ufunc__kolmogc_data, ufunc__kolmogc_types, 2, 1, 1, 0, "_kolmogc", ufunc__kolmogc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__kolmogci_loops[2] +cdef void *ufunc__kolmogci_ptr[4] +cdef void *ufunc__kolmogci_data[2] +cdef char ufunc__kolmogci_types[4] +cdef char *ufunc__kolmogci_doc = ( + "Internal function, do not use.") +ufunc__kolmogci_loops[0] = loop_d_d__As_f_f +ufunc__kolmogci_loops[1] = loop_d_d__As_d_d +ufunc__kolmogci_types[0] = NPY_FLOAT +ufunc__kolmogci_types[1] = NPY_FLOAT +ufunc__kolmogci_types[2] = NPY_DOUBLE +ufunc__kolmogci_types[3] = NPY_DOUBLE +ufunc__kolmogci_ptr[2*0] = _func_xsf_kolmogci +ufunc__kolmogci_ptr[2*0+1] = ("_kolmogci") +ufunc__kolmogci_ptr[2*1] = _func_xsf_kolmogci +ufunc__kolmogci_ptr[2*1+1] = ("_kolmogci") +ufunc__kolmogci_data[0] = &ufunc__kolmogci_ptr[2*0] +ufunc__kolmogci_data[1] = &ufunc__kolmogci_ptr[2*1] +_kolmogci = np.PyUFunc_FromFuncAndData(ufunc__kolmogci_loops, ufunc__kolmogci_data, ufunc__kolmogci_types, 2, 1, 1, 0, "_kolmogci", ufunc__kolmogci_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__kolmogp_loops[2] +cdef void *ufunc__kolmogp_ptr[4] +cdef void *ufunc__kolmogp_data[2] +cdef char ufunc__kolmogp_types[4] +cdef char *ufunc__kolmogp_doc = ( + "Internal function, do not use.") +ufunc__kolmogp_loops[0] = loop_d_d__As_f_f +ufunc__kolmogp_loops[1] = loop_d_d__As_d_d +ufunc__kolmogp_types[0] = NPY_FLOAT +ufunc__kolmogp_types[1] = NPY_FLOAT +ufunc__kolmogp_types[2] = NPY_DOUBLE +ufunc__kolmogp_types[3] = NPY_DOUBLE +ufunc__kolmogp_ptr[2*0] = _func_xsf_kolmogp +ufunc__kolmogp_ptr[2*0+1] = ("_kolmogp") +ufunc__kolmogp_ptr[2*1] = _func_xsf_kolmogp +ufunc__kolmogp_ptr[2*1+1] = ("_kolmogp") +ufunc__kolmogp_data[0] = &ufunc__kolmogp_ptr[2*0] +ufunc__kolmogp_data[1] = &ufunc__kolmogp_ptr[2*1] +_kolmogp = np.PyUFunc_FromFuncAndData(ufunc__kolmogp_loops, ufunc__kolmogp_data, ufunc__kolmogp_types, 2, 1, 1, 0, "_kolmogp", ufunc__kolmogp_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__lanczos_sum_expg_scaled_loops[2] +cdef void *ufunc__lanczos_sum_expg_scaled_ptr[4] +cdef void *ufunc__lanczos_sum_expg_scaled_data[2] +cdef char ufunc__lanczos_sum_expg_scaled_types[4] +cdef char *ufunc__lanczos_sum_expg_scaled_doc = ( + "Internal function, do not use.") +ufunc__lanczos_sum_expg_scaled_loops[0] = loop_d_d__As_f_f +ufunc__lanczos_sum_expg_scaled_loops[1] = loop_d_d__As_d_d +ufunc__lanczos_sum_expg_scaled_types[0] = NPY_FLOAT +ufunc__lanczos_sum_expg_scaled_types[1] = NPY_FLOAT +ufunc__lanczos_sum_expg_scaled_types[2] = NPY_DOUBLE +ufunc__lanczos_sum_expg_scaled_types[3] = NPY_DOUBLE +ufunc__lanczos_sum_expg_scaled_ptr[2*0] = _func_cephes_lanczos_sum_expg_scaled +ufunc__lanczos_sum_expg_scaled_ptr[2*0+1] = ("_lanczos_sum_expg_scaled") +ufunc__lanczos_sum_expg_scaled_ptr[2*1] = _func_cephes_lanczos_sum_expg_scaled +ufunc__lanczos_sum_expg_scaled_ptr[2*1+1] = ("_lanczos_sum_expg_scaled") +ufunc__lanczos_sum_expg_scaled_data[0] = &ufunc__lanczos_sum_expg_scaled_ptr[2*0] +ufunc__lanczos_sum_expg_scaled_data[1] = &ufunc__lanczos_sum_expg_scaled_ptr[2*1] +_lanczos_sum_expg_scaled = np.PyUFunc_FromFuncAndData(ufunc__lanczos_sum_expg_scaled_loops, ufunc__lanczos_sum_expg_scaled_data, ufunc__lanczos_sum_expg_scaled_types, 2, 1, 1, 0, "_lanczos_sum_expg_scaled", ufunc__lanczos_sum_expg_scaled_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__landau_cdf_loops[2] +cdef void *ufunc__landau_cdf_ptr[4] +cdef void *ufunc__landau_cdf_data[2] +cdef char ufunc__landau_cdf_types[8] +cdef char *ufunc__landau_cdf_doc = ( + "_landau_cdf(x, loc, scale)\n" + "\n" + "Cumulative distribution function of the Landau distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued argument\n" + "loc : array_like\n" + " Real-valued distribution location\n" + "scale : array_like\n" + " Positive, real-valued distribution scale\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__landau_cdf_loops[0] = loop_f_fff__As_fff_f +ufunc__landau_cdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__landau_cdf_types[0] = NPY_FLOAT +ufunc__landau_cdf_types[1] = NPY_FLOAT +ufunc__landau_cdf_types[2] = NPY_FLOAT +ufunc__landau_cdf_types[3] = NPY_FLOAT +ufunc__landau_cdf_types[4] = NPY_DOUBLE +ufunc__landau_cdf_types[5] = NPY_DOUBLE +ufunc__landau_cdf_types[6] = NPY_DOUBLE +ufunc__landau_cdf_types[7] = NPY_DOUBLE +ufunc__landau_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_cdf_float +ufunc__landau_cdf_ptr[2*0+1] = ("_landau_cdf") +ufunc__landau_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_cdf_double +ufunc__landau_cdf_ptr[2*1+1] = ("_landau_cdf") +ufunc__landau_cdf_data[0] = &ufunc__landau_cdf_ptr[2*0] +ufunc__landau_cdf_data[1] = &ufunc__landau_cdf_ptr[2*1] +_landau_cdf = np.PyUFunc_FromFuncAndData(ufunc__landau_cdf_loops, ufunc__landau_cdf_data, ufunc__landau_cdf_types, 2, 3, 1, 0, "_landau_cdf", ufunc__landau_cdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__landau_isf_loops[2] +cdef void *ufunc__landau_isf_ptr[4] +cdef void *ufunc__landau_isf_data[2] +cdef char ufunc__landau_isf_types[8] +cdef char *ufunc__landau_isf_doc = ( + "_landau_isf(p, loc, scale)\n" + "\n" + "Inverse survival function of the Landau distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Real-valued argument between 0 and 1\n" + "loc : array_like\n" + " Real-valued distribution location\n" + "scale : array_like\n" + " Positive, real-valued distribution scale\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__landau_isf_loops[0] = loop_f_fff__As_fff_f +ufunc__landau_isf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__landau_isf_types[0] = NPY_FLOAT +ufunc__landau_isf_types[1] = NPY_FLOAT +ufunc__landau_isf_types[2] = NPY_FLOAT +ufunc__landau_isf_types[3] = NPY_FLOAT +ufunc__landau_isf_types[4] = NPY_DOUBLE +ufunc__landau_isf_types[5] = NPY_DOUBLE +ufunc__landau_isf_types[6] = NPY_DOUBLE +ufunc__landau_isf_types[7] = NPY_DOUBLE +ufunc__landau_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_isf_float +ufunc__landau_isf_ptr[2*0+1] = ("_landau_isf") +ufunc__landau_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_isf_double +ufunc__landau_isf_ptr[2*1+1] = ("_landau_isf") +ufunc__landau_isf_data[0] = &ufunc__landau_isf_ptr[2*0] +ufunc__landau_isf_data[1] = &ufunc__landau_isf_ptr[2*1] +_landau_isf = np.PyUFunc_FromFuncAndData(ufunc__landau_isf_loops, ufunc__landau_isf_data, ufunc__landau_isf_types, 2, 3, 1, 0, "_landau_isf", ufunc__landau_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__landau_pdf_loops[2] +cdef void *ufunc__landau_pdf_ptr[4] +cdef void *ufunc__landau_pdf_data[2] +cdef char ufunc__landau_pdf_types[8] +cdef char *ufunc__landau_pdf_doc = ( + "_landau_pdf(x, loc, scale)\n" + "\n" + "Probability density function of the Landau distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued argument\n" + "loc : array_like\n" + " Real-valued distribution location\n" + "scale : array_like\n" + " Positive, real-valued distribution scale\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__landau_pdf_loops[0] = loop_f_fff__As_fff_f +ufunc__landau_pdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__landau_pdf_types[0] = NPY_FLOAT +ufunc__landau_pdf_types[1] = NPY_FLOAT +ufunc__landau_pdf_types[2] = NPY_FLOAT +ufunc__landau_pdf_types[3] = NPY_FLOAT +ufunc__landau_pdf_types[4] = NPY_DOUBLE +ufunc__landau_pdf_types[5] = NPY_DOUBLE +ufunc__landau_pdf_types[6] = NPY_DOUBLE +ufunc__landau_pdf_types[7] = NPY_DOUBLE +ufunc__landau_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_pdf_float +ufunc__landau_pdf_ptr[2*0+1] = ("_landau_pdf") +ufunc__landau_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_pdf_double +ufunc__landau_pdf_ptr[2*1+1] = ("_landau_pdf") +ufunc__landau_pdf_data[0] = &ufunc__landau_pdf_ptr[2*0] +ufunc__landau_pdf_data[1] = &ufunc__landau_pdf_ptr[2*1] +_landau_pdf = np.PyUFunc_FromFuncAndData(ufunc__landau_pdf_loops, ufunc__landau_pdf_data, ufunc__landau_pdf_types, 2, 3, 1, 0, "_landau_pdf", ufunc__landau_pdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__landau_ppf_loops[2] +cdef void *ufunc__landau_ppf_ptr[4] +cdef void *ufunc__landau_ppf_data[2] +cdef char ufunc__landau_ppf_types[8] +cdef char *ufunc__landau_ppf_doc = ( + "_landau_ppf(p, loc, scale)\n" + "\n" + "Percent point function of the Landau distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Real-valued argument between 0 and 1\n" + "loc : array_like\n" + " Real-valued distribution location\n" + "scale : array_like\n" + " Positive, real-valued distribution scale\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__landau_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__landau_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__landau_ppf_types[0] = NPY_FLOAT +ufunc__landau_ppf_types[1] = NPY_FLOAT +ufunc__landau_ppf_types[2] = NPY_FLOAT +ufunc__landau_ppf_types[3] = NPY_FLOAT +ufunc__landau_ppf_types[4] = NPY_DOUBLE +ufunc__landau_ppf_types[5] = NPY_DOUBLE +ufunc__landau_ppf_types[6] = NPY_DOUBLE +ufunc__landau_ppf_types[7] = NPY_DOUBLE +ufunc__landau_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_ppf_float +ufunc__landau_ppf_ptr[2*0+1] = ("_landau_ppf") +ufunc__landau_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_ppf_double +ufunc__landau_ppf_ptr[2*1+1] = ("_landau_ppf") +ufunc__landau_ppf_data[0] = &ufunc__landau_ppf_ptr[2*0] +ufunc__landau_ppf_data[1] = &ufunc__landau_ppf_ptr[2*1] +_landau_ppf = np.PyUFunc_FromFuncAndData(ufunc__landau_ppf_loops, ufunc__landau_ppf_data, ufunc__landau_ppf_types, 2, 3, 1, 0, "_landau_ppf", ufunc__landau_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__landau_sf_loops[2] +cdef void *ufunc__landau_sf_ptr[4] +cdef void *ufunc__landau_sf_data[2] +cdef char ufunc__landau_sf_types[8] +cdef char *ufunc__landau_sf_doc = ( + "_landau_sf(x, loc, scale)\n" + "\n" + "Survival function of the Landau distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued argument\n" + "loc : array_like\n" + " Real-valued distribution location\n" + "scale : array_like\n" + " Positive, real-valued distribution scale\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__landau_sf_loops[0] = loop_f_fff__As_fff_f +ufunc__landau_sf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__landau_sf_types[0] = NPY_FLOAT +ufunc__landau_sf_types[1] = NPY_FLOAT +ufunc__landau_sf_types[2] = NPY_FLOAT +ufunc__landau_sf_types[3] = NPY_FLOAT +ufunc__landau_sf_types[4] = NPY_DOUBLE +ufunc__landau_sf_types[5] = NPY_DOUBLE +ufunc__landau_sf_types[6] = NPY_DOUBLE +ufunc__landau_sf_types[7] = NPY_DOUBLE +ufunc__landau_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_sf_float +ufunc__landau_sf_ptr[2*0+1] = ("_landau_sf") +ufunc__landau_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_sf_double +ufunc__landau_sf_ptr[2*1+1] = ("_landau_sf") +ufunc__landau_sf_data[0] = &ufunc__landau_sf_ptr[2*0] +ufunc__landau_sf_data[1] = &ufunc__landau_sf_ptr[2*1] +_landau_sf = np.PyUFunc_FromFuncAndData(ufunc__landau_sf_loops, ufunc__landau_sf_data, ufunc__landau_sf_types, 2, 3, 1, 0, "_landau_sf", ufunc__landau_sf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__lgam1p_loops[2] +cdef void *ufunc__lgam1p_ptr[4] +cdef void *ufunc__lgam1p_data[2] +cdef char ufunc__lgam1p_types[4] +cdef char *ufunc__lgam1p_doc = ( + "Internal function, do not use.") +ufunc__lgam1p_loops[0] = loop_d_d__As_f_f +ufunc__lgam1p_loops[1] = loop_d_d__As_d_d +ufunc__lgam1p_types[0] = NPY_FLOAT +ufunc__lgam1p_types[1] = NPY_FLOAT +ufunc__lgam1p_types[2] = NPY_DOUBLE +ufunc__lgam1p_types[3] = NPY_DOUBLE +ufunc__lgam1p_ptr[2*0] = _func_cephes_lgam1p +ufunc__lgam1p_ptr[2*0+1] = ("_lgam1p") +ufunc__lgam1p_ptr[2*1] = _func_cephes_lgam1p +ufunc__lgam1p_ptr[2*1+1] = ("_lgam1p") +ufunc__lgam1p_data[0] = &ufunc__lgam1p_ptr[2*0] +ufunc__lgam1p_data[1] = &ufunc__lgam1p_ptr[2*1] +_lgam1p = np.PyUFunc_FromFuncAndData(ufunc__lgam1p_loops, ufunc__lgam1p_data, ufunc__lgam1p_types, 2, 1, 1, 0, "_lgam1p", ufunc__lgam1p_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__log1pmx_loops[2] +cdef void *ufunc__log1pmx_ptr[4] +cdef void *ufunc__log1pmx_data[2] +cdef char ufunc__log1pmx_types[4] +cdef char *ufunc__log1pmx_doc = ( + "Internal function, do not use.") +ufunc__log1pmx_loops[0] = loop_d_d__As_f_f +ufunc__log1pmx_loops[1] = loop_d_d__As_d_d +ufunc__log1pmx_types[0] = NPY_FLOAT +ufunc__log1pmx_types[1] = NPY_FLOAT +ufunc__log1pmx_types[2] = NPY_DOUBLE +ufunc__log1pmx_types[3] = NPY_DOUBLE +ufunc__log1pmx_ptr[2*0] = _func_cephes_log1pmx +ufunc__log1pmx_ptr[2*0+1] = ("_log1pmx") +ufunc__log1pmx_ptr[2*1] = _func_cephes_log1pmx +ufunc__log1pmx_ptr[2*1+1] = ("_log1pmx") +ufunc__log1pmx_data[0] = &ufunc__log1pmx_ptr[2*0] +ufunc__log1pmx_data[1] = &ufunc__log1pmx_ptr[2*1] +_log1pmx = np.PyUFunc_FromFuncAndData(ufunc__log1pmx_loops, ufunc__log1pmx_data, ufunc__log1pmx_types, 2, 1, 1, 0, "_log1pmx", ufunc__log1pmx_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_cdf_loops[2] +cdef void *ufunc__nbinom_cdf_ptr[4] +cdef void *ufunc__nbinom_cdf_data[2] +cdef char ufunc__nbinom_cdf_types[8] +cdef char *ufunc__nbinom_cdf_doc = ( + "_nbinom_cdf(x, r, p)\n" + "\n" + "Cumulative density function of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_cdf_loops[0] = loop_f_fff__As_fff_f +ufunc__nbinom_cdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nbinom_cdf_types[0] = NPY_FLOAT +ufunc__nbinom_cdf_types[1] = NPY_FLOAT +ufunc__nbinom_cdf_types[2] = NPY_FLOAT +ufunc__nbinom_cdf_types[3] = NPY_FLOAT +ufunc__nbinom_cdf_types[4] = NPY_DOUBLE +ufunc__nbinom_cdf_types[5] = NPY_DOUBLE +ufunc__nbinom_cdf_types[6] = NPY_DOUBLE +ufunc__nbinom_cdf_types[7] = NPY_DOUBLE +ufunc__nbinom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_cdf_float +ufunc__nbinom_cdf_ptr[2*0+1] = ("_nbinom_cdf") +ufunc__nbinom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_cdf_double +ufunc__nbinom_cdf_ptr[2*1+1] = ("_nbinom_cdf") +ufunc__nbinom_cdf_data[0] = &ufunc__nbinom_cdf_ptr[2*0] +ufunc__nbinom_cdf_data[1] = &ufunc__nbinom_cdf_ptr[2*1] +_nbinom_cdf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_cdf_loops, ufunc__nbinom_cdf_data, ufunc__nbinom_cdf_types, 2, 3, 1, 0, "_nbinom_cdf", ufunc__nbinom_cdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_isf_loops[2] +cdef void *ufunc__nbinom_isf_ptr[4] +cdef void *ufunc__nbinom_isf_data[2] +cdef char ufunc__nbinom_isf_types[8] +cdef char *ufunc__nbinom_isf_doc = ( + "_nbinom_isf(x, r, p)\n" + "\n" + "Inverse survival function of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_isf_loops[0] = loop_f_fff__As_fff_f +ufunc__nbinom_isf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nbinom_isf_types[0] = NPY_FLOAT +ufunc__nbinom_isf_types[1] = NPY_FLOAT +ufunc__nbinom_isf_types[2] = NPY_FLOAT +ufunc__nbinom_isf_types[3] = NPY_FLOAT +ufunc__nbinom_isf_types[4] = NPY_DOUBLE +ufunc__nbinom_isf_types[5] = NPY_DOUBLE +ufunc__nbinom_isf_types[6] = NPY_DOUBLE +ufunc__nbinom_isf_types[7] = NPY_DOUBLE +ufunc__nbinom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_isf_float +ufunc__nbinom_isf_ptr[2*0+1] = ("_nbinom_isf") +ufunc__nbinom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_isf_double +ufunc__nbinom_isf_ptr[2*1+1] = ("_nbinom_isf") +ufunc__nbinom_isf_data[0] = &ufunc__nbinom_isf_ptr[2*0] +ufunc__nbinom_isf_data[1] = &ufunc__nbinom_isf_ptr[2*1] +_nbinom_isf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_isf_loops, ufunc__nbinom_isf_data, ufunc__nbinom_isf_types, 2, 3, 1, 0, "_nbinom_isf", ufunc__nbinom_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_kurtosis_excess_loops[2] +cdef void *ufunc__nbinom_kurtosis_excess_ptr[4] +cdef void *ufunc__nbinom_kurtosis_excess_data[2] +cdef char ufunc__nbinom_kurtosis_excess_types[6] +cdef char *ufunc__nbinom_kurtosis_excess_doc = ( + "_nbinom_kurtosis_excess(r, p)\n" + "\n" + "Kurtosis excess of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f +ufunc__nbinom_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d +ufunc__nbinom_kurtosis_excess_types[0] = NPY_FLOAT +ufunc__nbinom_kurtosis_excess_types[1] = NPY_FLOAT +ufunc__nbinom_kurtosis_excess_types[2] = NPY_FLOAT +ufunc__nbinom_kurtosis_excess_types[3] = NPY_DOUBLE +ufunc__nbinom_kurtosis_excess_types[4] = NPY_DOUBLE +ufunc__nbinom_kurtosis_excess_types[5] = NPY_DOUBLE +ufunc__nbinom_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_float +ufunc__nbinom_kurtosis_excess_ptr[2*0+1] = ("_nbinom_kurtosis_excess") +ufunc__nbinom_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_double +ufunc__nbinom_kurtosis_excess_ptr[2*1+1] = ("_nbinom_kurtosis_excess") +ufunc__nbinom_kurtosis_excess_data[0] = &ufunc__nbinom_kurtosis_excess_ptr[2*0] +ufunc__nbinom_kurtosis_excess_data[1] = &ufunc__nbinom_kurtosis_excess_ptr[2*1] +_nbinom_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nbinom_kurtosis_excess_loops, ufunc__nbinom_kurtosis_excess_data, ufunc__nbinom_kurtosis_excess_types, 2, 2, 1, 0, "_nbinom_kurtosis_excess", ufunc__nbinom_kurtosis_excess_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_mean_loops[2] +cdef void *ufunc__nbinom_mean_ptr[4] +cdef void *ufunc__nbinom_mean_data[2] +cdef char ufunc__nbinom_mean_types[6] +cdef char *ufunc__nbinom_mean_doc = ( + "_nbinom_mean(r, p)\n" + "\n" + "Mean of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_mean_loops[0] = loop_f_ff__As_ff_f +ufunc__nbinom_mean_loops[1] = loop_d_dd__As_dd_d +ufunc__nbinom_mean_types[0] = NPY_FLOAT +ufunc__nbinom_mean_types[1] = NPY_FLOAT +ufunc__nbinom_mean_types[2] = NPY_FLOAT +ufunc__nbinom_mean_types[3] = NPY_DOUBLE +ufunc__nbinom_mean_types[4] = NPY_DOUBLE +ufunc__nbinom_mean_types[5] = NPY_DOUBLE +ufunc__nbinom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_mean_float +ufunc__nbinom_mean_ptr[2*0+1] = ("_nbinom_mean") +ufunc__nbinom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_mean_double +ufunc__nbinom_mean_ptr[2*1+1] = ("_nbinom_mean") +ufunc__nbinom_mean_data[0] = &ufunc__nbinom_mean_ptr[2*0] +ufunc__nbinom_mean_data[1] = &ufunc__nbinom_mean_ptr[2*1] +_nbinom_mean = np.PyUFunc_FromFuncAndData(ufunc__nbinom_mean_loops, ufunc__nbinom_mean_data, ufunc__nbinom_mean_types, 2, 2, 1, 0, "_nbinom_mean", ufunc__nbinom_mean_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_pmf_loops[2] +cdef void *ufunc__nbinom_pmf_ptr[4] +cdef void *ufunc__nbinom_pmf_data[2] +cdef char ufunc__nbinom_pmf_types[8] +cdef char *ufunc__nbinom_pmf_doc = ( + "_nbinom_pmf(x, r, p)\n" + "\n" + "Probability mass function of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_pmf_loops[0] = loop_f_fff__As_fff_f +ufunc__nbinom_pmf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nbinom_pmf_types[0] = NPY_FLOAT +ufunc__nbinom_pmf_types[1] = NPY_FLOAT +ufunc__nbinom_pmf_types[2] = NPY_FLOAT +ufunc__nbinom_pmf_types[3] = NPY_FLOAT +ufunc__nbinom_pmf_types[4] = NPY_DOUBLE +ufunc__nbinom_pmf_types[5] = NPY_DOUBLE +ufunc__nbinom_pmf_types[6] = NPY_DOUBLE +ufunc__nbinom_pmf_types[7] = NPY_DOUBLE +ufunc__nbinom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_pmf_float +ufunc__nbinom_pmf_ptr[2*0+1] = ("_nbinom_pmf") +ufunc__nbinom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_pmf_double +ufunc__nbinom_pmf_ptr[2*1+1] = ("_nbinom_pmf") +ufunc__nbinom_pmf_data[0] = &ufunc__nbinom_pmf_ptr[2*0] +ufunc__nbinom_pmf_data[1] = &ufunc__nbinom_pmf_ptr[2*1] +_nbinom_pmf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_pmf_loops, ufunc__nbinom_pmf_data, ufunc__nbinom_pmf_types, 2, 3, 1, 0, "_nbinom_pmf", ufunc__nbinom_pmf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_ppf_loops[2] +cdef void *ufunc__nbinom_ppf_ptr[4] +cdef void *ufunc__nbinom_ppf_data[2] +cdef char ufunc__nbinom_ppf_types[8] +cdef char *ufunc__nbinom_ppf_doc = ( + "_nbinom_ppf(x, r, p)\n" + "\n" + "Percent point function of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__nbinom_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nbinom_ppf_types[0] = NPY_FLOAT +ufunc__nbinom_ppf_types[1] = NPY_FLOAT +ufunc__nbinom_ppf_types[2] = NPY_FLOAT +ufunc__nbinom_ppf_types[3] = NPY_FLOAT +ufunc__nbinom_ppf_types[4] = NPY_DOUBLE +ufunc__nbinom_ppf_types[5] = NPY_DOUBLE +ufunc__nbinom_ppf_types[6] = NPY_DOUBLE +ufunc__nbinom_ppf_types[7] = NPY_DOUBLE +ufunc__nbinom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_ppf_float +ufunc__nbinom_ppf_ptr[2*0+1] = ("_nbinom_ppf") +ufunc__nbinom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_ppf_double +ufunc__nbinom_ppf_ptr[2*1+1] = ("_nbinom_ppf") +ufunc__nbinom_ppf_data[0] = &ufunc__nbinom_ppf_ptr[2*0] +ufunc__nbinom_ppf_data[1] = &ufunc__nbinom_ppf_ptr[2*1] +_nbinom_ppf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_ppf_loops, ufunc__nbinom_ppf_data, ufunc__nbinom_ppf_types, 2, 3, 1, 0, "_nbinom_ppf", ufunc__nbinom_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_sf_loops[2] +cdef void *ufunc__nbinom_sf_ptr[4] +cdef void *ufunc__nbinom_sf_data[2] +cdef char ufunc__nbinom_sf_types[8] +cdef char *ufunc__nbinom_sf_doc = ( + "_nbinom_sf(x, r, p)\n" + "\n" + "Survival function of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_sf_loops[0] = loop_f_fff__As_fff_f +ufunc__nbinom_sf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nbinom_sf_types[0] = NPY_FLOAT +ufunc__nbinom_sf_types[1] = NPY_FLOAT +ufunc__nbinom_sf_types[2] = NPY_FLOAT +ufunc__nbinom_sf_types[3] = NPY_FLOAT +ufunc__nbinom_sf_types[4] = NPY_DOUBLE +ufunc__nbinom_sf_types[5] = NPY_DOUBLE +ufunc__nbinom_sf_types[6] = NPY_DOUBLE +ufunc__nbinom_sf_types[7] = NPY_DOUBLE +ufunc__nbinom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_sf_float +ufunc__nbinom_sf_ptr[2*0+1] = ("_nbinom_sf") +ufunc__nbinom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_sf_double +ufunc__nbinom_sf_ptr[2*1+1] = ("_nbinom_sf") +ufunc__nbinom_sf_data[0] = &ufunc__nbinom_sf_ptr[2*0] +ufunc__nbinom_sf_data[1] = &ufunc__nbinom_sf_ptr[2*1] +_nbinom_sf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_sf_loops, ufunc__nbinom_sf_data, ufunc__nbinom_sf_types, 2, 3, 1, 0, "_nbinom_sf", ufunc__nbinom_sf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_skewness_loops[2] +cdef void *ufunc__nbinom_skewness_ptr[4] +cdef void *ufunc__nbinom_skewness_data[2] +cdef char ufunc__nbinom_skewness_types[6] +cdef char *ufunc__nbinom_skewness_doc = ( + "_nbinom_skewness(r, p)\n" + "\n" + "Skewness of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_skewness_loops[0] = loop_f_ff__As_ff_f +ufunc__nbinom_skewness_loops[1] = loop_d_dd__As_dd_d +ufunc__nbinom_skewness_types[0] = NPY_FLOAT +ufunc__nbinom_skewness_types[1] = NPY_FLOAT +ufunc__nbinom_skewness_types[2] = NPY_FLOAT +ufunc__nbinom_skewness_types[3] = NPY_DOUBLE +ufunc__nbinom_skewness_types[4] = NPY_DOUBLE +ufunc__nbinom_skewness_types[5] = NPY_DOUBLE +ufunc__nbinom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_skewness_float +ufunc__nbinom_skewness_ptr[2*0+1] = ("_nbinom_skewness") +ufunc__nbinom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_skewness_double +ufunc__nbinom_skewness_ptr[2*1+1] = ("_nbinom_skewness") +ufunc__nbinom_skewness_data[0] = &ufunc__nbinom_skewness_ptr[2*0] +ufunc__nbinom_skewness_data[1] = &ufunc__nbinom_skewness_ptr[2*1] +_nbinom_skewness = np.PyUFunc_FromFuncAndData(ufunc__nbinom_skewness_loops, ufunc__nbinom_skewness_data, ufunc__nbinom_skewness_types, 2, 2, 1, 0, "_nbinom_skewness", ufunc__nbinom_skewness_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nbinom_variance_loops[2] +cdef void *ufunc__nbinom_variance_ptr[4] +cdef void *ufunc__nbinom_variance_data[2] +cdef char ufunc__nbinom_variance_types[6] +cdef char *ufunc__nbinom_variance_doc = ( + "_nbinom_variance(r, p)\n" + "\n" + "Variance of negative binomial distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "r : array_like\n" + " Positive, integer-valued parameter\n" + "p : array_like\n" + " Positive, real-valued parameter\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nbinom_variance_loops[0] = loop_f_ff__As_ff_f +ufunc__nbinom_variance_loops[1] = loop_d_dd__As_dd_d +ufunc__nbinom_variance_types[0] = NPY_FLOAT +ufunc__nbinom_variance_types[1] = NPY_FLOAT +ufunc__nbinom_variance_types[2] = NPY_FLOAT +ufunc__nbinom_variance_types[3] = NPY_DOUBLE +ufunc__nbinom_variance_types[4] = NPY_DOUBLE +ufunc__nbinom_variance_types[5] = NPY_DOUBLE +ufunc__nbinom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_variance_float +ufunc__nbinom_variance_ptr[2*0+1] = ("_nbinom_variance") +ufunc__nbinom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_variance_double +ufunc__nbinom_variance_ptr[2*1+1] = ("_nbinom_variance") +ufunc__nbinom_variance_data[0] = &ufunc__nbinom_variance_ptr[2*0] +ufunc__nbinom_variance_data[1] = &ufunc__nbinom_variance_ptr[2*1] +_nbinom_variance = np.PyUFunc_FromFuncAndData(ufunc__nbinom_variance_loops, ufunc__nbinom_variance_data, ufunc__nbinom_variance_types, 2, 2, 1, 0, "_nbinom_variance", ufunc__nbinom_variance_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncf_isf_loops[2] +cdef void *ufunc__ncf_isf_ptr[4] +cdef void *ufunc__ncf_isf_data[2] +cdef char ufunc__ncf_isf_types[10] +cdef char *ufunc__ncf_isf_doc = ( + "_ncf_isf(x, v1, v2, l)\n" + "\n" + "Inverse survival function of noncentral F-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "v1, v2, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncf_isf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__ncf_isf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__ncf_isf_types[0] = NPY_FLOAT +ufunc__ncf_isf_types[1] = NPY_FLOAT +ufunc__ncf_isf_types[2] = NPY_FLOAT +ufunc__ncf_isf_types[3] = NPY_FLOAT +ufunc__ncf_isf_types[4] = NPY_FLOAT +ufunc__ncf_isf_types[5] = NPY_DOUBLE +ufunc__ncf_isf_types[6] = NPY_DOUBLE +ufunc__ncf_isf_types[7] = NPY_DOUBLE +ufunc__ncf_isf_types[8] = NPY_DOUBLE +ufunc__ncf_isf_types[9] = NPY_DOUBLE +ufunc__ncf_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_isf_float +ufunc__ncf_isf_ptr[2*0+1] = ("_ncf_isf") +ufunc__ncf_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_isf_double +ufunc__ncf_isf_ptr[2*1+1] = ("_ncf_isf") +ufunc__ncf_isf_data[0] = &ufunc__ncf_isf_ptr[2*0] +ufunc__ncf_isf_data[1] = &ufunc__ncf_isf_ptr[2*1] +_ncf_isf = np.PyUFunc_FromFuncAndData(ufunc__ncf_isf_loops, ufunc__ncf_isf_data, ufunc__ncf_isf_types, 2, 4, 1, 0, "_ncf_isf", ufunc__ncf_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncf_kurtosis_excess_loops[2] +cdef void *ufunc__ncf_kurtosis_excess_ptr[4] +cdef void *ufunc__ncf_kurtosis_excess_data[2] +cdef char ufunc__ncf_kurtosis_excess_types[8] +cdef char *ufunc__ncf_kurtosis_excess_doc = ( + "_ncf_kurtosis_excess(v1, v2, l)\n" + "\n" + "Kurtosis excess of noncentral F-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v1, v2, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncf_kurtosis_excess_loops[0] = loop_f_fff__As_fff_f +ufunc__ncf_kurtosis_excess_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncf_kurtosis_excess_types[0] = NPY_FLOAT +ufunc__ncf_kurtosis_excess_types[1] = NPY_FLOAT +ufunc__ncf_kurtosis_excess_types[2] = NPY_FLOAT +ufunc__ncf_kurtosis_excess_types[3] = NPY_FLOAT +ufunc__ncf_kurtosis_excess_types[4] = NPY_DOUBLE +ufunc__ncf_kurtosis_excess_types[5] = NPY_DOUBLE +ufunc__ncf_kurtosis_excess_types[6] = NPY_DOUBLE +ufunc__ncf_kurtosis_excess_types[7] = NPY_DOUBLE +ufunc__ncf_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_float +ufunc__ncf_kurtosis_excess_ptr[2*0+1] = ("_ncf_kurtosis_excess") +ufunc__ncf_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_double +ufunc__ncf_kurtosis_excess_ptr[2*1+1] = ("_ncf_kurtosis_excess") +ufunc__ncf_kurtosis_excess_data[0] = &ufunc__ncf_kurtosis_excess_ptr[2*0] +ufunc__ncf_kurtosis_excess_data[1] = &ufunc__ncf_kurtosis_excess_ptr[2*1] +_ncf_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__ncf_kurtosis_excess_loops, ufunc__ncf_kurtosis_excess_data, ufunc__ncf_kurtosis_excess_types, 2, 3, 1, 0, "_ncf_kurtosis_excess", ufunc__ncf_kurtosis_excess_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncf_mean_loops[2] +cdef void *ufunc__ncf_mean_ptr[4] +cdef void *ufunc__ncf_mean_data[2] +cdef char ufunc__ncf_mean_types[8] +cdef char *ufunc__ncf_mean_doc = ( + "_ncf_mean(v1, v2, l)\n" + "\n" + "Mean of noncentral F-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v1, v2, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncf_mean_loops[0] = loop_f_fff__As_fff_f +ufunc__ncf_mean_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncf_mean_types[0] = NPY_FLOAT +ufunc__ncf_mean_types[1] = NPY_FLOAT +ufunc__ncf_mean_types[2] = NPY_FLOAT +ufunc__ncf_mean_types[3] = NPY_FLOAT +ufunc__ncf_mean_types[4] = NPY_DOUBLE +ufunc__ncf_mean_types[5] = NPY_DOUBLE +ufunc__ncf_mean_types[6] = NPY_DOUBLE +ufunc__ncf_mean_types[7] = NPY_DOUBLE +ufunc__ncf_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_mean_float +ufunc__ncf_mean_ptr[2*0+1] = ("_ncf_mean") +ufunc__ncf_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_mean_double +ufunc__ncf_mean_ptr[2*1+1] = ("_ncf_mean") +ufunc__ncf_mean_data[0] = &ufunc__ncf_mean_ptr[2*0] +ufunc__ncf_mean_data[1] = &ufunc__ncf_mean_ptr[2*1] +_ncf_mean = np.PyUFunc_FromFuncAndData(ufunc__ncf_mean_loops, ufunc__ncf_mean_data, ufunc__ncf_mean_types, 2, 3, 1, 0, "_ncf_mean", ufunc__ncf_mean_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncf_pdf_loops[2] +cdef void *ufunc__ncf_pdf_ptr[4] +cdef void *ufunc__ncf_pdf_data[2] +cdef char ufunc__ncf_pdf_types[10] +cdef char *ufunc__ncf_pdf_doc = ( + "_ncf_pdf(x, v1, v2, l)\n" + "\n" + "Probability density function of noncentral F-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "v1, v2, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncf_pdf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__ncf_pdf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__ncf_pdf_types[0] = NPY_FLOAT +ufunc__ncf_pdf_types[1] = NPY_FLOAT +ufunc__ncf_pdf_types[2] = NPY_FLOAT +ufunc__ncf_pdf_types[3] = NPY_FLOAT +ufunc__ncf_pdf_types[4] = NPY_FLOAT +ufunc__ncf_pdf_types[5] = NPY_DOUBLE +ufunc__ncf_pdf_types[6] = NPY_DOUBLE +ufunc__ncf_pdf_types[7] = NPY_DOUBLE +ufunc__ncf_pdf_types[8] = NPY_DOUBLE +ufunc__ncf_pdf_types[9] = NPY_DOUBLE +ufunc__ncf_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_pdf_float +ufunc__ncf_pdf_ptr[2*0+1] = ("_ncf_pdf") +ufunc__ncf_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_pdf_double +ufunc__ncf_pdf_ptr[2*1+1] = ("_ncf_pdf") +ufunc__ncf_pdf_data[0] = &ufunc__ncf_pdf_ptr[2*0] +ufunc__ncf_pdf_data[1] = &ufunc__ncf_pdf_ptr[2*1] +_ncf_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncf_pdf_loops, ufunc__ncf_pdf_data, ufunc__ncf_pdf_types, 2, 4, 1, 0, "_ncf_pdf", ufunc__ncf_pdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncf_sf_loops[2] +cdef void *ufunc__ncf_sf_ptr[4] +cdef void *ufunc__ncf_sf_data[2] +cdef char ufunc__ncf_sf_types[10] +cdef char *ufunc__ncf_sf_doc = ( + "_ncf_sf(x, v1, v2, l)\n" + "\n" + "Survival function of noncentral F-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "v1, v2, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncf_sf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__ncf_sf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__ncf_sf_types[0] = NPY_FLOAT +ufunc__ncf_sf_types[1] = NPY_FLOAT +ufunc__ncf_sf_types[2] = NPY_FLOAT +ufunc__ncf_sf_types[3] = NPY_FLOAT +ufunc__ncf_sf_types[4] = NPY_FLOAT +ufunc__ncf_sf_types[5] = NPY_DOUBLE +ufunc__ncf_sf_types[6] = NPY_DOUBLE +ufunc__ncf_sf_types[7] = NPY_DOUBLE +ufunc__ncf_sf_types[8] = NPY_DOUBLE +ufunc__ncf_sf_types[9] = NPY_DOUBLE +ufunc__ncf_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_sf_float +ufunc__ncf_sf_ptr[2*0+1] = ("_ncf_sf") +ufunc__ncf_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_sf_double +ufunc__ncf_sf_ptr[2*1+1] = ("_ncf_sf") +ufunc__ncf_sf_data[0] = &ufunc__ncf_sf_ptr[2*0] +ufunc__ncf_sf_data[1] = &ufunc__ncf_sf_ptr[2*1] +_ncf_sf = np.PyUFunc_FromFuncAndData(ufunc__ncf_sf_loops, ufunc__ncf_sf_data, ufunc__ncf_sf_types, 2, 4, 1, 0, "_ncf_sf", ufunc__ncf_sf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncf_skewness_loops[2] +cdef void *ufunc__ncf_skewness_ptr[4] +cdef void *ufunc__ncf_skewness_data[2] +cdef char ufunc__ncf_skewness_types[8] +cdef char *ufunc__ncf_skewness_doc = ( + "_ncf_skewness(v1, v2, l)\n" + "\n" + "Skewness of noncentral F-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v1, v2, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncf_skewness_loops[0] = loop_f_fff__As_fff_f +ufunc__ncf_skewness_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncf_skewness_types[0] = NPY_FLOAT +ufunc__ncf_skewness_types[1] = NPY_FLOAT +ufunc__ncf_skewness_types[2] = NPY_FLOAT +ufunc__ncf_skewness_types[3] = NPY_FLOAT +ufunc__ncf_skewness_types[4] = NPY_DOUBLE +ufunc__ncf_skewness_types[5] = NPY_DOUBLE +ufunc__ncf_skewness_types[6] = NPY_DOUBLE +ufunc__ncf_skewness_types[7] = NPY_DOUBLE +ufunc__ncf_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_skewness_float +ufunc__ncf_skewness_ptr[2*0+1] = ("_ncf_skewness") +ufunc__ncf_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_skewness_double +ufunc__ncf_skewness_ptr[2*1+1] = ("_ncf_skewness") +ufunc__ncf_skewness_data[0] = &ufunc__ncf_skewness_ptr[2*0] +ufunc__ncf_skewness_data[1] = &ufunc__ncf_skewness_ptr[2*1] +_ncf_skewness = np.PyUFunc_FromFuncAndData(ufunc__ncf_skewness_loops, ufunc__ncf_skewness_data, ufunc__ncf_skewness_types, 2, 3, 1, 0, "_ncf_skewness", ufunc__ncf_skewness_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncf_variance_loops[2] +cdef void *ufunc__ncf_variance_ptr[4] +cdef void *ufunc__ncf_variance_data[2] +cdef char ufunc__ncf_variance_types[8] +cdef char *ufunc__ncf_variance_doc = ( + "_ncf_variance(v1, v2, l)\n" + "\n" + "Variance of noncentral F-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v1, v2, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncf_variance_loops[0] = loop_f_fff__As_fff_f +ufunc__ncf_variance_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncf_variance_types[0] = NPY_FLOAT +ufunc__ncf_variance_types[1] = NPY_FLOAT +ufunc__ncf_variance_types[2] = NPY_FLOAT +ufunc__ncf_variance_types[3] = NPY_FLOAT +ufunc__ncf_variance_types[4] = NPY_DOUBLE +ufunc__ncf_variance_types[5] = NPY_DOUBLE +ufunc__ncf_variance_types[6] = NPY_DOUBLE +ufunc__ncf_variance_types[7] = NPY_DOUBLE +ufunc__ncf_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_variance_float +ufunc__ncf_variance_ptr[2*0+1] = ("_ncf_variance") +ufunc__ncf_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_variance_double +ufunc__ncf_variance_ptr[2*1+1] = ("_ncf_variance") +ufunc__ncf_variance_data[0] = &ufunc__ncf_variance_ptr[2*0] +ufunc__ncf_variance_data[1] = &ufunc__ncf_variance_ptr[2*1] +_ncf_variance = np.PyUFunc_FromFuncAndData(ufunc__ncf_variance_loops, ufunc__ncf_variance_data, ufunc__ncf_variance_types, 2, 3, 1, 0, "_ncf_variance", ufunc__ncf_variance_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_isf_loops[2] +cdef void *ufunc__nct_isf_ptr[4] +cdef void *ufunc__nct_isf_data[2] +cdef char ufunc__nct_isf_types[8] +cdef char *ufunc__nct_isf_doc = ( + "_nct_isf(x, v, l)\n" + "\n" + "Inverse survival function of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_isf_loops[0] = loop_f_fff__As_fff_f +ufunc__nct_isf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nct_isf_types[0] = NPY_FLOAT +ufunc__nct_isf_types[1] = NPY_FLOAT +ufunc__nct_isf_types[2] = NPY_FLOAT +ufunc__nct_isf_types[3] = NPY_FLOAT +ufunc__nct_isf_types[4] = NPY_DOUBLE +ufunc__nct_isf_types[5] = NPY_DOUBLE +ufunc__nct_isf_types[6] = NPY_DOUBLE +ufunc__nct_isf_types[7] = NPY_DOUBLE +ufunc__nct_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_isf_float +ufunc__nct_isf_ptr[2*0+1] = ("_nct_isf") +ufunc__nct_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_isf_double +ufunc__nct_isf_ptr[2*1+1] = ("_nct_isf") +ufunc__nct_isf_data[0] = &ufunc__nct_isf_ptr[2*0] +ufunc__nct_isf_data[1] = &ufunc__nct_isf_ptr[2*1] +_nct_isf = np.PyUFunc_FromFuncAndData(ufunc__nct_isf_loops, ufunc__nct_isf_data, ufunc__nct_isf_types, 2, 3, 1, 0, "_nct_isf", ufunc__nct_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_kurtosis_excess_loops[2] +cdef void *ufunc__nct_kurtosis_excess_ptr[4] +cdef void *ufunc__nct_kurtosis_excess_data[2] +cdef char ufunc__nct_kurtosis_excess_types[6] +cdef char *ufunc__nct_kurtosis_excess_doc = ( + "_nct_kurtosis_excess(v, l)\n" + "\n" + "Kurtosis excess of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f +ufunc__nct_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d +ufunc__nct_kurtosis_excess_types[0] = NPY_FLOAT +ufunc__nct_kurtosis_excess_types[1] = NPY_FLOAT +ufunc__nct_kurtosis_excess_types[2] = NPY_FLOAT +ufunc__nct_kurtosis_excess_types[3] = NPY_DOUBLE +ufunc__nct_kurtosis_excess_types[4] = NPY_DOUBLE +ufunc__nct_kurtosis_excess_types[5] = NPY_DOUBLE +ufunc__nct_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_float +ufunc__nct_kurtosis_excess_ptr[2*0+1] = ("_nct_kurtosis_excess") +ufunc__nct_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_double +ufunc__nct_kurtosis_excess_ptr[2*1+1] = ("_nct_kurtosis_excess") +ufunc__nct_kurtosis_excess_data[0] = &ufunc__nct_kurtosis_excess_ptr[2*0] +ufunc__nct_kurtosis_excess_data[1] = &ufunc__nct_kurtosis_excess_ptr[2*1] +_nct_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nct_kurtosis_excess_loops, ufunc__nct_kurtosis_excess_data, ufunc__nct_kurtosis_excess_types, 2, 2, 1, 0, "_nct_kurtosis_excess", ufunc__nct_kurtosis_excess_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_mean_loops[2] +cdef void *ufunc__nct_mean_ptr[4] +cdef void *ufunc__nct_mean_data[2] +cdef char ufunc__nct_mean_types[6] +cdef char *ufunc__nct_mean_doc = ( + "_nct_mean(v, l)\n" + "\n" + "Mean of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_mean_loops[0] = loop_f_ff__As_ff_f +ufunc__nct_mean_loops[1] = loop_d_dd__As_dd_d +ufunc__nct_mean_types[0] = NPY_FLOAT +ufunc__nct_mean_types[1] = NPY_FLOAT +ufunc__nct_mean_types[2] = NPY_FLOAT +ufunc__nct_mean_types[3] = NPY_DOUBLE +ufunc__nct_mean_types[4] = NPY_DOUBLE +ufunc__nct_mean_types[5] = NPY_DOUBLE +ufunc__nct_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_mean_float +ufunc__nct_mean_ptr[2*0+1] = ("_nct_mean") +ufunc__nct_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_mean_double +ufunc__nct_mean_ptr[2*1+1] = ("_nct_mean") +ufunc__nct_mean_data[0] = &ufunc__nct_mean_ptr[2*0] +ufunc__nct_mean_data[1] = &ufunc__nct_mean_ptr[2*1] +_nct_mean = np.PyUFunc_FromFuncAndData(ufunc__nct_mean_loops, ufunc__nct_mean_data, ufunc__nct_mean_types, 2, 2, 1, 0, "_nct_mean", ufunc__nct_mean_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_pdf_loops[2] +cdef void *ufunc__nct_pdf_ptr[4] +cdef void *ufunc__nct_pdf_data[2] +cdef char ufunc__nct_pdf_types[8] +cdef char *ufunc__nct_pdf_doc = ( + "_nct_pdf(x, v, l)\n" + "\n" + "Probability density function of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_pdf_loops[0] = loop_f_fff__As_fff_f +ufunc__nct_pdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nct_pdf_types[0] = NPY_FLOAT +ufunc__nct_pdf_types[1] = NPY_FLOAT +ufunc__nct_pdf_types[2] = NPY_FLOAT +ufunc__nct_pdf_types[3] = NPY_FLOAT +ufunc__nct_pdf_types[4] = NPY_DOUBLE +ufunc__nct_pdf_types[5] = NPY_DOUBLE +ufunc__nct_pdf_types[6] = NPY_DOUBLE +ufunc__nct_pdf_types[7] = NPY_DOUBLE +ufunc__nct_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_pdf_float +ufunc__nct_pdf_ptr[2*0+1] = ("_nct_pdf") +ufunc__nct_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_pdf_double +ufunc__nct_pdf_ptr[2*1+1] = ("_nct_pdf") +ufunc__nct_pdf_data[0] = &ufunc__nct_pdf_ptr[2*0] +ufunc__nct_pdf_data[1] = &ufunc__nct_pdf_ptr[2*1] +_nct_pdf = np.PyUFunc_FromFuncAndData(ufunc__nct_pdf_loops, ufunc__nct_pdf_data, ufunc__nct_pdf_types, 2, 3, 1, 0, "_nct_pdf", ufunc__nct_pdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_ppf_loops[2] +cdef void *ufunc__nct_ppf_ptr[4] +cdef void *ufunc__nct_ppf_data[2] +cdef char ufunc__nct_ppf_types[8] +cdef char *ufunc__nct_ppf_doc = ( + "_nct_ppf(x, v, l)\n" + "\n" + "Percent point function of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__nct_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nct_ppf_types[0] = NPY_FLOAT +ufunc__nct_ppf_types[1] = NPY_FLOAT +ufunc__nct_ppf_types[2] = NPY_FLOAT +ufunc__nct_ppf_types[3] = NPY_FLOAT +ufunc__nct_ppf_types[4] = NPY_DOUBLE +ufunc__nct_ppf_types[5] = NPY_DOUBLE +ufunc__nct_ppf_types[6] = NPY_DOUBLE +ufunc__nct_ppf_types[7] = NPY_DOUBLE +ufunc__nct_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_ppf_float +ufunc__nct_ppf_ptr[2*0+1] = ("_nct_ppf") +ufunc__nct_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_ppf_double +ufunc__nct_ppf_ptr[2*1+1] = ("_nct_ppf") +ufunc__nct_ppf_data[0] = &ufunc__nct_ppf_ptr[2*0] +ufunc__nct_ppf_data[1] = &ufunc__nct_ppf_ptr[2*1] +_nct_ppf = np.PyUFunc_FromFuncAndData(ufunc__nct_ppf_loops, ufunc__nct_ppf_data, ufunc__nct_ppf_types, 2, 3, 1, 0, "_nct_ppf", ufunc__nct_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_sf_loops[2] +cdef void *ufunc__nct_sf_ptr[4] +cdef void *ufunc__nct_sf_data[2] +cdef char ufunc__nct_sf_types[8] +cdef char *ufunc__nct_sf_doc = ( + "_nct_sf(x, v, l)\n" + "\n" + "Survival function of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_sf_loops[0] = loop_f_fff__As_fff_f +ufunc__nct_sf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__nct_sf_types[0] = NPY_FLOAT +ufunc__nct_sf_types[1] = NPY_FLOAT +ufunc__nct_sf_types[2] = NPY_FLOAT +ufunc__nct_sf_types[3] = NPY_FLOAT +ufunc__nct_sf_types[4] = NPY_DOUBLE +ufunc__nct_sf_types[5] = NPY_DOUBLE +ufunc__nct_sf_types[6] = NPY_DOUBLE +ufunc__nct_sf_types[7] = NPY_DOUBLE +ufunc__nct_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_sf_float +ufunc__nct_sf_ptr[2*0+1] = ("_nct_sf") +ufunc__nct_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_sf_double +ufunc__nct_sf_ptr[2*1+1] = ("_nct_sf") +ufunc__nct_sf_data[0] = &ufunc__nct_sf_ptr[2*0] +ufunc__nct_sf_data[1] = &ufunc__nct_sf_ptr[2*1] +_nct_sf = np.PyUFunc_FromFuncAndData(ufunc__nct_sf_loops, ufunc__nct_sf_data, ufunc__nct_sf_types, 2, 3, 1, 0, "_nct_sf", ufunc__nct_sf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_skewness_loops[2] +cdef void *ufunc__nct_skewness_ptr[4] +cdef void *ufunc__nct_skewness_data[2] +cdef char ufunc__nct_skewness_types[6] +cdef char *ufunc__nct_skewness_doc = ( + "_nct_skewness(v, l)\n" + "\n" + "Skewness of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_skewness_loops[0] = loop_f_ff__As_ff_f +ufunc__nct_skewness_loops[1] = loop_d_dd__As_dd_d +ufunc__nct_skewness_types[0] = NPY_FLOAT +ufunc__nct_skewness_types[1] = NPY_FLOAT +ufunc__nct_skewness_types[2] = NPY_FLOAT +ufunc__nct_skewness_types[3] = NPY_DOUBLE +ufunc__nct_skewness_types[4] = NPY_DOUBLE +ufunc__nct_skewness_types[5] = NPY_DOUBLE +ufunc__nct_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_skewness_float +ufunc__nct_skewness_ptr[2*0+1] = ("_nct_skewness") +ufunc__nct_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_skewness_double +ufunc__nct_skewness_ptr[2*1+1] = ("_nct_skewness") +ufunc__nct_skewness_data[0] = &ufunc__nct_skewness_ptr[2*0] +ufunc__nct_skewness_data[1] = &ufunc__nct_skewness_ptr[2*1] +_nct_skewness = np.PyUFunc_FromFuncAndData(ufunc__nct_skewness_loops, ufunc__nct_skewness_data, ufunc__nct_skewness_types, 2, 2, 1, 0, "_nct_skewness", ufunc__nct_skewness_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__nct_variance_loops[2] +cdef void *ufunc__nct_variance_ptr[4] +cdef void *ufunc__nct_variance_data[2] +cdef char ufunc__nct_variance_types[6] +cdef char *ufunc__nct_variance_doc = ( + "_nct_variance(v, l)\n" + "\n" + "Variance of noncentral t-distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Positive, real-valued parameters\n" + "l : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__nct_variance_loops[0] = loop_f_ff__As_ff_f +ufunc__nct_variance_loops[1] = loop_d_dd__As_dd_d +ufunc__nct_variance_types[0] = NPY_FLOAT +ufunc__nct_variance_types[1] = NPY_FLOAT +ufunc__nct_variance_types[2] = NPY_FLOAT +ufunc__nct_variance_types[3] = NPY_DOUBLE +ufunc__nct_variance_types[4] = NPY_DOUBLE +ufunc__nct_variance_types[5] = NPY_DOUBLE +ufunc__nct_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_variance_float +ufunc__nct_variance_ptr[2*0+1] = ("_nct_variance") +ufunc__nct_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_variance_double +ufunc__nct_variance_ptr[2*1+1] = ("_nct_variance") +ufunc__nct_variance_data[0] = &ufunc__nct_variance_ptr[2*0] +ufunc__nct_variance_data[1] = &ufunc__nct_variance_ptr[2*1] +_nct_variance = np.PyUFunc_FromFuncAndData(ufunc__nct_variance_loops, ufunc__nct_variance_data, ufunc__nct_variance_types, 2, 2, 1, 0, "_nct_variance", ufunc__nct_variance_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncx2_cdf_loops[2] +cdef void *ufunc__ncx2_cdf_ptr[4] +cdef void *ufunc__ncx2_cdf_data[2] +cdef char ufunc__ncx2_cdf_types[8] +cdef char *ufunc__ncx2_cdf_doc = ( + "_ncx2_cdf(x, k, l)\n" + "\n" + "Cumulative density function of Non-central chi-squared distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "k, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncx2_cdf_loops[0] = loop_f_fff__As_fff_f +ufunc__ncx2_cdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncx2_cdf_types[0] = NPY_FLOAT +ufunc__ncx2_cdf_types[1] = NPY_FLOAT +ufunc__ncx2_cdf_types[2] = NPY_FLOAT +ufunc__ncx2_cdf_types[3] = NPY_FLOAT +ufunc__ncx2_cdf_types[4] = NPY_DOUBLE +ufunc__ncx2_cdf_types[5] = NPY_DOUBLE +ufunc__ncx2_cdf_types[6] = NPY_DOUBLE +ufunc__ncx2_cdf_types[7] = NPY_DOUBLE +ufunc__ncx2_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_cdf_float +ufunc__ncx2_cdf_ptr[2*0+1] = ("_ncx2_cdf") +ufunc__ncx2_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_cdf_double +ufunc__ncx2_cdf_ptr[2*1+1] = ("_ncx2_cdf") +ufunc__ncx2_cdf_data[0] = &ufunc__ncx2_cdf_ptr[2*0] +ufunc__ncx2_cdf_data[1] = &ufunc__ncx2_cdf_ptr[2*1] +_ncx2_cdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_cdf_loops, ufunc__ncx2_cdf_data, ufunc__ncx2_cdf_types, 2, 3, 1, 0, "_ncx2_cdf", ufunc__ncx2_cdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncx2_isf_loops[2] +cdef void *ufunc__ncx2_isf_ptr[4] +cdef void *ufunc__ncx2_isf_data[2] +cdef char ufunc__ncx2_isf_types[8] +cdef char *ufunc__ncx2_isf_doc = ( + "_ncx2_isf(x, k, l)\n" + "\n" + "Inverse survival function of Non-central chi-squared distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "k, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncx2_isf_loops[0] = loop_f_fff__As_fff_f +ufunc__ncx2_isf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncx2_isf_types[0] = NPY_FLOAT +ufunc__ncx2_isf_types[1] = NPY_FLOAT +ufunc__ncx2_isf_types[2] = NPY_FLOAT +ufunc__ncx2_isf_types[3] = NPY_FLOAT +ufunc__ncx2_isf_types[4] = NPY_DOUBLE +ufunc__ncx2_isf_types[5] = NPY_DOUBLE +ufunc__ncx2_isf_types[6] = NPY_DOUBLE +ufunc__ncx2_isf_types[7] = NPY_DOUBLE +ufunc__ncx2_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_isf_float +ufunc__ncx2_isf_ptr[2*0+1] = ("_ncx2_isf") +ufunc__ncx2_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_isf_double +ufunc__ncx2_isf_ptr[2*1+1] = ("_ncx2_isf") +ufunc__ncx2_isf_data[0] = &ufunc__ncx2_isf_ptr[2*0] +ufunc__ncx2_isf_data[1] = &ufunc__ncx2_isf_ptr[2*1] +_ncx2_isf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_isf_loops, ufunc__ncx2_isf_data, ufunc__ncx2_isf_types, 2, 3, 1, 0, "_ncx2_isf", ufunc__ncx2_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncx2_pdf_loops[2] +cdef void *ufunc__ncx2_pdf_ptr[4] +cdef void *ufunc__ncx2_pdf_data[2] +cdef char ufunc__ncx2_pdf_types[8] +cdef char *ufunc__ncx2_pdf_doc = ( + "_ncx2_pdf(x, k, l)\n" + "\n" + "Probability density function of Non-central chi-squared distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "k, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncx2_pdf_loops[0] = loop_f_fff__As_fff_f +ufunc__ncx2_pdf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncx2_pdf_types[0] = NPY_FLOAT +ufunc__ncx2_pdf_types[1] = NPY_FLOAT +ufunc__ncx2_pdf_types[2] = NPY_FLOAT +ufunc__ncx2_pdf_types[3] = NPY_FLOAT +ufunc__ncx2_pdf_types[4] = NPY_DOUBLE +ufunc__ncx2_pdf_types[5] = NPY_DOUBLE +ufunc__ncx2_pdf_types[6] = NPY_DOUBLE +ufunc__ncx2_pdf_types[7] = NPY_DOUBLE +ufunc__ncx2_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_pdf_float +ufunc__ncx2_pdf_ptr[2*0+1] = ("_ncx2_pdf") +ufunc__ncx2_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_pdf_double +ufunc__ncx2_pdf_ptr[2*1+1] = ("_ncx2_pdf") +ufunc__ncx2_pdf_data[0] = &ufunc__ncx2_pdf_ptr[2*0] +ufunc__ncx2_pdf_data[1] = &ufunc__ncx2_pdf_ptr[2*1] +_ncx2_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_pdf_loops, ufunc__ncx2_pdf_data, ufunc__ncx2_pdf_types, 2, 3, 1, 0, "_ncx2_pdf", ufunc__ncx2_pdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncx2_ppf_loops[2] +cdef void *ufunc__ncx2_ppf_ptr[4] +cdef void *ufunc__ncx2_ppf_data[2] +cdef char ufunc__ncx2_ppf_types[8] +cdef char *ufunc__ncx2_ppf_doc = ( + "_ncx2_ppf(x, k, l)\n" + "\n" + "Percent point function of Non-central chi-squared distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "k, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncx2_ppf_loops[0] = loop_f_fff__As_fff_f +ufunc__ncx2_ppf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncx2_ppf_types[0] = NPY_FLOAT +ufunc__ncx2_ppf_types[1] = NPY_FLOAT +ufunc__ncx2_ppf_types[2] = NPY_FLOAT +ufunc__ncx2_ppf_types[3] = NPY_FLOAT +ufunc__ncx2_ppf_types[4] = NPY_DOUBLE +ufunc__ncx2_ppf_types[5] = NPY_DOUBLE +ufunc__ncx2_ppf_types[6] = NPY_DOUBLE +ufunc__ncx2_ppf_types[7] = NPY_DOUBLE +ufunc__ncx2_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_ppf_float +ufunc__ncx2_ppf_ptr[2*0+1] = ("_ncx2_ppf") +ufunc__ncx2_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_ppf_double +ufunc__ncx2_ppf_ptr[2*1+1] = ("_ncx2_ppf") +ufunc__ncx2_ppf_data[0] = &ufunc__ncx2_ppf_ptr[2*0] +ufunc__ncx2_ppf_data[1] = &ufunc__ncx2_ppf_ptr[2*1] +_ncx2_ppf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_ppf_loops, ufunc__ncx2_ppf_data, ufunc__ncx2_ppf_types, 2, 3, 1, 0, "_ncx2_ppf", ufunc__ncx2_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__ncx2_sf_loops[2] +cdef void *ufunc__ncx2_sf_ptr[4] +cdef void *ufunc__ncx2_sf_data[2] +cdef char ufunc__ncx2_sf_types[8] +cdef char *ufunc__ncx2_sf_doc = ( + "_ncx2_sf(x, k, l)\n" + "\n" + "Survival function of Non-central chi-squared distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Positive real-valued\n" + "k, l : array_like\n" + " Positive, real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__ncx2_sf_loops[0] = loop_f_fff__As_fff_f +ufunc__ncx2_sf_loops[1] = loop_d_ddd__As_ddd_d +ufunc__ncx2_sf_types[0] = NPY_FLOAT +ufunc__ncx2_sf_types[1] = NPY_FLOAT +ufunc__ncx2_sf_types[2] = NPY_FLOAT +ufunc__ncx2_sf_types[3] = NPY_FLOAT +ufunc__ncx2_sf_types[4] = NPY_DOUBLE +ufunc__ncx2_sf_types[5] = NPY_DOUBLE +ufunc__ncx2_sf_types[6] = NPY_DOUBLE +ufunc__ncx2_sf_types[7] = NPY_DOUBLE +ufunc__ncx2_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_sf_float +ufunc__ncx2_sf_ptr[2*0+1] = ("_ncx2_sf") +ufunc__ncx2_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_sf_double +ufunc__ncx2_sf_ptr[2*1+1] = ("_ncx2_sf") +ufunc__ncx2_sf_data[0] = &ufunc__ncx2_sf_ptr[2*0] +ufunc__ncx2_sf_data[1] = &ufunc__ncx2_sf_ptr[2*1] +_ncx2_sf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_sf_loops, ufunc__ncx2_sf_data, ufunc__ncx2_sf_types, 2, 3, 1, 0, "_ncx2_sf", ufunc__ncx2_sf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__sf_error_test_function_loops[1] +cdef void *ufunc__sf_error_test_function_ptr[2] +cdef void *ufunc__sf_error_test_function_data[1] +cdef char ufunc__sf_error_test_function_types[2] +cdef char *ufunc__sf_error_test_function_doc = ( + "Private function; do not use.") +ufunc__sf_error_test_function_loops[0] = loop_i_i__As_l_l +ufunc__sf_error_test_function_types[0] = NPY_LONG +ufunc__sf_error_test_function_types[1] = NPY_LONG +ufunc__sf_error_test_function_ptr[2*0] = _func__sf_error_test_function +ufunc__sf_error_test_function_ptr[2*0+1] = ("_sf_error_test_function") +ufunc__sf_error_test_function_data[0] = &ufunc__sf_error_test_function_ptr[2*0] +_sf_error_test_function = np.PyUFunc_FromFuncAndData(ufunc__sf_error_test_function_loops, ufunc__sf_error_test_function_data, ufunc__sf_error_test_function_types, 1, 1, 1, 0, "_sf_error_test_function", ufunc__sf_error_test_function_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__skewnorm_cdf_loops[2] +cdef void *ufunc__skewnorm_cdf_ptr[4] +cdef void *ufunc__skewnorm_cdf_data[2] +cdef char ufunc__skewnorm_cdf_types[10] +cdef char *ufunc__skewnorm_cdf_doc = ( + "_skewnorm_cdf(x, l, sc, sh)\n" + "\n" + "Cumulative density function of skewnorm distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "l : array_like\n" + " Real-valued parameters\n" + "sc : array_like\n" + " Positive, Real-valued parameters\n" + "sh : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__skewnorm_cdf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__skewnorm_cdf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__skewnorm_cdf_types[0] = NPY_FLOAT +ufunc__skewnorm_cdf_types[1] = NPY_FLOAT +ufunc__skewnorm_cdf_types[2] = NPY_FLOAT +ufunc__skewnorm_cdf_types[3] = NPY_FLOAT +ufunc__skewnorm_cdf_types[4] = NPY_FLOAT +ufunc__skewnorm_cdf_types[5] = NPY_DOUBLE +ufunc__skewnorm_cdf_types[6] = NPY_DOUBLE +ufunc__skewnorm_cdf_types[7] = NPY_DOUBLE +ufunc__skewnorm_cdf_types[8] = NPY_DOUBLE +ufunc__skewnorm_cdf_types[9] = NPY_DOUBLE +ufunc__skewnorm_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_float +ufunc__skewnorm_cdf_ptr[2*0+1] = ("_skewnorm_cdf") +ufunc__skewnorm_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_double +ufunc__skewnorm_cdf_ptr[2*1+1] = ("_skewnorm_cdf") +ufunc__skewnorm_cdf_data[0] = &ufunc__skewnorm_cdf_ptr[2*0] +ufunc__skewnorm_cdf_data[1] = &ufunc__skewnorm_cdf_ptr[2*1] +_skewnorm_cdf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_cdf_loops, ufunc__skewnorm_cdf_data, ufunc__skewnorm_cdf_types, 2, 4, 1, 0, "_skewnorm_cdf", ufunc__skewnorm_cdf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__skewnorm_isf_loops[2] +cdef void *ufunc__skewnorm_isf_ptr[4] +cdef void *ufunc__skewnorm_isf_data[2] +cdef char ufunc__skewnorm_isf_types[10] +cdef char *ufunc__skewnorm_isf_doc = ( + "_skewnorm_isf(x, l, sc, sh)\n" + "\n" + "Inverse survival function of skewnorm distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "l : array_like\n" + " Real-valued parameters\n" + "sc : array_like\n" + " Positive, Real-valued parameters\n" + "sh : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__skewnorm_isf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__skewnorm_isf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__skewnorm_isf_types[0] = NPY_FLOAT +ufunc__skewnorm_isf_types[1] = NPY_FLOAT +ufunc__skewnorm_isf_types[2] = NPY_FLOAT +ufunc__skewnorm_isf_types[3] = NPY_FLOAT +ufunc__skewnorm_isf_types[4] = NPY_FLOAT +ufunc__skewnorm_isf_types[5] = NPY_DOUBLE +ufunc__skewnorm_isf_types[6] = NPY_DOUBLE +ufunc__skewnorm_isf_types[7] = NPY_DOUBLE +ufunc__skewnorm_isf_types[8] = NPY_DOUBLE +ufunc__skewnorm_isf_types[9] = NPY_DOUBLE +ufunc__skewnorm_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_isf_float +ufunc__skewnorm_isf_ptr[2*0+1] = ("_skewnorm_isf") +ufunc__skewnorm_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_isf_double +ufunc__skewnorm_isf_ptr[2*1+1] = ("_skewnorm_isf") +ufunc__skewnorm_isf_data[0] = &ufunc__skewnorm_isf_ptr[2*0] +ufunc__skewnorm_isf_data[1] = &ufunc__skewnorm_isf_ptr[2*1] +_skewnorm_isf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_isf_loops, ufunc__skewnorm_isf_data, ufunc__skewnorm_isf_types, 2, 4, 1, 0, "_skewnorm_isf", ufunc__skewnorm_isf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__skewnorm_ppf_loops[2] +cdef void *ufunc__skewnorm_ppf_ptr[4] +cdef void *ufunc__skewnorm_ppf_data[2] +cdef char ufunc__skewnorm_ppf_types[10] +cdef char *ufunc__skewnorm_ppf_doc = ( + "_skewnorm_ppf(x, l, sc, sh)\n" + "\n" + "Percent point function of skewnorm distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real-valued\n" + "l : array_like\n" + " Real-valued parameters\n" + "sc : array_like\n" + " Positive, Real-valued parameters\n" + "sh : array_like\n" + " Real-valued parameters\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray") +ufunc__skewnorm_ppf_loops[0] = loop_f_ffff__As_ffff_f +ufunc__skewnorm_ppf_loops[1] = loop_d_dddd__As_dddd_d +ufunc__skewnorm_ppf_types[0] = NPY_FLOAT +ufunc__skewnorm_ppf_types[1] = NPY_FLOAT +ufunc__skewnorm_ppf_types[2] = NPY_FLOAT +ufunc__skewnorm_ppf_types[3] = NPY_FLOAT +ufunc__skewnorm_ppf_types[4] = NPY_FLOAT +ufunc__skewnorm_ppf_types[5] = NPY_DOUBLE +ufunc__skewnorm_ppf_types[6] = NPY_DOUBLE +ufunc__skewnorm_ppf_types[7] = NPY_DOUBLE +ufunc__skewnorm_ppf_types[8] = NPY_DOUBLE +ufunc__skewnorm_ppf_types[9] = NPY_DOUBLE +ufunc__skewnorm_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_float +ufunc__skewnorm_ppf_ptr[2*0+1] = ("_skewnorm_ppf") +ufunc__skewnorm_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_double +ufunc__skewnorm_ppf_ptr[2*1+1] = ("_skewnorm_ppf") +ufunc__skewnorm_ppf_data[0] = &ufunc__skewnorm_ppf_ptr[2*0] +ufunc__skewnorm_ppf_data[1] = &ufunc__skewnorm_ppf_ptr[2*1] +_skewnorm_ppf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_ppf_loops, ufunc__skewnorm_ppf_data, ufunc__skewnorm_ppf_types, 2, 4, 1, 0, "_skewnorm_ppf", ufunc__skewnorm_ppf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__smirnovc_loops[3] +cdef void *ufunc__smirnovc_ptr[6] +cdef void *ufunc__smirnovc_data[3] +cdef char ufunc__smirnovc_types[9] +cdef char *ufunc__smirnovc_doc = ( + "_smirnovc(n, d)\n" + " Internal function, do not use.") +ufunc__smirnovc_loops[0] = loop_d_pd__As_pd_d +ufunc__smirnovc_loops[1] = loop_d_dd__As_ff_f +ufunc__smirnovc_loops[2] = loop_d_dd__As_dd_d +ufunc__smirnovc_types[0] = NPY_INTP +ufunc__smirnovc_types[1] = NPY_DOUBLE +ufunc__smirnovc_types[2] = NPY_DOUBLE +ufunc__smirnovc_types[3] = NPY_FLOAT +ufunc__smirnovc_types[4] = NPY_FLOAT +ufunc__smirnovc_types[5] = NPY_FLOAT +ufunc__smirnovc_types[6] = NPY_DOUBLE +ufunc__smirnovc_types[7] = NPY_DOUBLE +ufunc__smirnovc_types[8] = NPY_DOUBLE +ufunc__smirnovc_ptr[2*0] = _func_cephes_smirnovc_wrap +ufunc__smirnovc_ptr[2*0+1] = ("_smirnovc") +ufunc__smirnovc_ptr[2*1] = _func_smirnovc_unsafe +ufunc__smirnovc_ptr[2*1+1] = ("_smirnovc") +ufunc__smirnovc_ptr[2*2] = _func_smirnovc_unsafe +ufunc__smirnovc_ptr[2*2+1] = ("_smirnovc") +ufunc__smirnovc_data[0] = &ufunc__smirnovc_ptr[2*0] +ufunc__smirnovc_data[1] = &ufunc__smirnovc_ptr[2*1] +ufunc__smirnovc_data[2] = &ufunc__smirnovc_ptr[2*2] +_smirnovc = np.PyUFunc_FromFuncAndData(ufunc__smirnovc_loops, ufunc__smirnovc_data, ufunc__smirnovc_types, 3, 2, 1, 0, "_smirnovc", ufunc__smirnovc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__smirnovci_loops[3] +cdef void *ufunc__smirnovci_ptr[6] +cdef void *ufunc__smirnovci_data[3] +cdef char ufunc__smirnovci_types[9] +cdef char *ufunc__smirnovci_doc = ( + "Internal function, do not use.") +ufunc__smirnovci_loops[0] = loop_d_pd__As_pd_d +ufunc__smirnovci_loops[1] = loop_d_dd__As_ff_f +ufunc__smirnovci_loops[2] = loop_d_dd__As_dd_d +ufunc__smirnovci_types[0] = NPY_INTP +ufunc__smirnovci_types[1] = NPY_DOUBLE +ufunc__smirnovci_types[2] = NPY_DOUBLE +ufunc__smirnovci_types[3] = NPY_FLOAT +ufunc__smirnovci_types[4] = NPY_FLOAT +ufunc__smirnovci_types[5] = NPY_FLOAT +ufunc__smirnovci_types[6] = NPY_DOUBLE +ufunc__smirnovci_types[7] = NPY_DOUBLE +ufunc__smirnovci_types[8] = NPY_DOUBLE +ufunc__smirnovci_ptr[2*0] = _func_cephes_smirnovci_wrap +ufunc__smirnovci_ptr[2*0+1] = ("_smirnovci") +ufunc__smirnovci_ptr[2*1] = _func_smirnovci_unsafe +ufunc__smirnovci_ptr[2*1+1] = ("_smirnovci") +ufunc__smirnovci_ptr[2*2] = _func_smirnovci_unsafe +ufunc__smirnovci_ptr[2*2+1] = ("_smirnovci") +ufunc__smirnovci_data[0] = &ufunc__smirnovci_ptr[2*0] +ufunc__smirnovci_data[1] = &ufunc__smirnovci_ptr[2*1] +ufunc__smirnovci_data[2] = &ufunc__smirnovci_ptr[2*2] +_smirnovci = np.PyUFunc_FromFuncAndData(ufunc__smirnovci_loops, ufunc__smirnovci_data, ufunc__smirnovci_types, 3, 2, 1, 0, "_smirnovci", ufunc__smirnovci_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__smirnovp_loops[3] +cdef void *ufunc__smirnovp_ptr[6] +cdef void *ufunc__smirnovp_data[3] +cdef char ufunc__smirnovp_types[9] +cdef char *ufunc__smirnovp_doc = ( + "_smirnovp(n, p)\n" + " Internal function, do not use.") +ufunc__smirnovp_loops[0] = loop_d_pd__As_pd_d +ufunc__smirnovp_loops[1] = loop_d_dd__As_ff_f +ufunc__smirnovp_loops[2] = loop_d_dd__As_dd_d +ufunc__smirnovp_types[0] = NPY_INTP +ufunc__smirnovp_types[1] = NPY_DOUBLE +ufunc__smirnovp_types[2] = NPY_DOUBLE +ufunc__smirnovp_types[3] = NPY_FLOAT +ufunc__smirnovp_types[4] = NPY_FLOAT +ufunc__smirnovp_types[5] = NPY_FLOAT +ufunc__smirnovp_types[6] = NPY_DOUBLE +ufunc__smirnovp_types[7] = NPY_DOUBLE +ufunc__smirnovp_types[8] = NPY_DOUBLE +ufunc__smirnovp_ptr[2*0] = _func_cephes_smirnovp_wrap +ufunc__smirnovp_ptr[2*0+1] = ("_smirnovp") +ufunc__smirnovp_ptr[2*1] = _func_smirnovp_unsafe +ufunc__smirnovp_ptr[2*1+1] = ("_smirnovp") +ufunc__smirnovp_ptr[2*2] = _func_smirnovp_unsafe +ufunc__smirnovp_ptr[2*2+1] = ("_smirnovp") +ufunc__smirnovp_data[0] = &ufunc__smirnovp_ptr[2*0] +ufunc__smirnovp_data[1] = &ufunc__smirnovp_ptr[2*1] +ufunc__smirnovp_data[2] = &ufunc__smirnovp_ptr[2*2] +_smirnovp = np.PyUFunc_FromFuncAndData(ufunc__smirnovp_loops, ufunc__smirnovp_data, ufunc__smirnovp_types, 3, 2, 1, 0, "_smirnovp", ufunc__smirnovp_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__stirling2_inexact_loops[2] +cdef void *ufunc__stirling2_inexact_ptr[4] +cdef void *ufunc__stirling2_inexact_data[2] +cdef char ufunc__stirling2_inexact_types[6] +cdef char *ufunc__stirling2_inexact_doc = ( + "Internal function, do not use.") +ufunc__stirling2_inexact_loops[0] = loop_d_dd__As_ff_f +ufunc__stirling2_inexact_loops[1] = loop_d_dd__As_dd_d +ufunc__stirling2_inexact_types[0] = NPY_FLOAT +ufunc__stirling2_inexact_types[1] = NPY_FLOAT +ufunc__stirling2_inexact_types[2] = NPY_FLOAT +ufunc__stirling2_inexact_types[3] = NPY_DOUBLE +ufunc__stirling2_inexact_types[4] = NPY_DOUBLE +ufunc__stirling2_inexact_types[5] = NPY_DOUBLE +ufunc__stirling2_inexact_ptr[2*0] = scipy.special._ufuncs_cxx._export__stirling2_inexact +ufunc__stirling2_inexact_ptr[2*0+1] = ("_stirling2_inexact") +ufunc__stirling2_inexact_ptr[2*1] = scipy.special._ufuncs_cxx._export__stirling2_inexact +ufunc__stirling2_inexact_ptr[2*1+1] = ("_stirling2_inexact") +ufunc__stirling2_inexact_data[0] = &ufunc__stirling2_inexact_ptr[2*0] +ufunc__stirling2_inexact_data[1] = &ufunc__stirling2_inexact_ptr[2*1] +_stirling2_inexact = np.PyUFunc_FromFuncAndData(ufunc__stirling2_inexact_loops, ufunc__stirling2_inexact_data, ufunc__stirling2_inexact_types, 2, 2, 1, 0, "_stirling2_inexact", ufunc__stirling2_inexact_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__struve_asymp_large_z_loops[1] +cdef void *ufunc__struve_asymp_large_z_ptr[2] +cdef void *ufunc__struve_asymp_large_z_data[1] +cdef char ufunc__struve_asymp_large_z_types[5] +cdef char *ufunc__struve_asymp_large_z_doc = ( + "_struve_asymp_large_z(v, z, is_h)\n" + "\n" + "Internal function for testing `struve` & `modstruve`\n" + "\n" + "Evaluates using asymptotic expansion\n" + "\n" + "Returns\n" + "-------\n" + "v, err") +ufunc__struve_asymp_large_z_loops[0] = loop_d_ddp_d_As_ddp_dd +ufunc__struve_asymp_large_z_types[0] = NPY_DOUBLE +ufunc__struve_asymp_large_z_types[1] = NPY_DOUBLE +ufunc__struve_asymp_large_z_types[2] = NPY_INTP +ufunc__struve_asymp_large_z_types[3] = NPY_DOUBLE +ufunc__struve_asymp_large_z_types[4] = NPY_DOUBLE +ufunc__struve_asymp_large_z_ptr[2*0] = _func_cephes__struve_asymp_large_z +ufunc__struve_asymp_large_z_ptr[2*0+1] = ("_struve_asymp_large_z") +ufunc__struve_asymp_large_z_data[0] = &ufunc__struve_asymp_large_z_ptr[2*0] +_struve_asymp_large_z = np.PyUFunc_FromFuncAndData(ufunc__struve_asymp_large_z_loops, ufunc__struve_asymp_large_z_data, ufunc__struve_asymp_large_z_types, 1, 3, 2, 0, "_struve_asymp_large_z", ufunc__struve_asymp_large_z_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__struve_bessel_series_loops[1] +cdef void *ufunc__struve_bessel_series_ptr[2] +cdef void *ufunc__struve_bessel_series_data[1] +cdef char ufunc__struve_bessel_series_types[5] +cdef char *ufunc__struve_bessel_series_doc = ( + "_struve_bessel_series(v, z, is_h)\n" + "\n" + "Internal function for testing `struve` & `modstruve`\n" + "\n" + "Evaluates using Bessel function series\n" + "\n" + "Returns\n" + "-------\n" + "v, err") +ufunc__struve_bessel_series_loops[0] = loop_d_ddp_d_As_ddp_dd +ufunc__struve_bessel_series_types[0] = NPY_DOUBLE +ufunc__struve_bessel_series_types[1] = NPY_DOUBLE +ufunc__struve_bessel_series_types[2] = NPY_INTP +ufunc__struve_bessel_series_types[3] = NPY_DOUBLE +ufunc__struve_bessel_series_types[4] = NPY_DOUBLE +ufunc__struve_bessel_series_ptr[2*0] = _func_cephes__struve_bessel_series +ufunc__struve_bessel_series_ptr[2*0+1] = ("_struve_bessel_series") +ufunc__struve_bessel_series_data[0] = &ufunc__struve_bessel_series_ptr[2*0] +_struve_bessel_series = np.PyUFunc_FromFuncAndData(ufunc__struve_bessel_series_loops, ufunc__struve_bessel_series_data, ufunc__struve_bessel_series_types, 1, 3, 2, 0, "_struve_bessel_series", ufunc__struve_bessel_series_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc__struve_power_series_loops[1] +cdef void *ufunc__struve_power_series_ptr[2] +cdef void *ufunc__struve_power_series_data[1] +cdef char ufunc__struve_power_series_types[5] +cdef char *ufunc__struve_power_series_doc = ( + "_struve_power_series(v, z, is_h)\n" + "\n" + "Internal function for testing `struve` & `modstruve`\n" + "\n" + "Evaluates using power series\n" + "\n" + "Returns\n" + "-------\n" + "v, err") +ufunc__struve_power_series_loops[0] = loop_d_ddp_d_As_ddp_dd +ufunc__struve_power_series_types[0] = NPY_DOUBLE +ufunc__struve_power_series_types[1] = NPY_DOUBLE +ufunc__struve_power_series_types[2] = NPY_INTP +ufunc__struve_power_series_types[3] = NPY_DOUBLE +ufunc__struve_power_series_types[4] = NPY_DOUBLE +ufunc__struve_power_series_ptr[2*0] = _func_cephes__struve_power_series +ufunc__struve_power_series_ptr[2*0+1] = ("_struve_power_series") +ufunc__struve_power_series_data[0] = &ufunc__struve_power_series_ptr[2*0] +_struve_power_series = np.PyUFunc_FromFuncAndData(ufunc__struve_power_series_loops, ufunc__struve_power_series_data, ufunc__struve_power_series_types, 1, 3, 2, 0, "_struve_power_series", ufunc__struve_power_series_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_agm_loops[2] +cdef void *ufunc_agm_ptr[4] +cdef void *ufunc_agm_data[2] +cdef char ufunc_agm_types[6] +cdef char *ufunc_agm_doc = ( + "agm(a, b, out=None)\n" + "\n" + "Compute the arithmetic-geometric mean of `a` and `b`.\n" + "\n" + "Start with a_0 = a and b_0 = b and iteratively compute::\n" + "\n" + " a_{n+1} = (a_n + b_n)/2\n" + " b_{n+1} = sqrt(a_n*b_n)\n" + "\n" + "a_n and b_n converge to the same limit as n increases; their common\n" + "limit is agm(a, b).\n" + "\n" + "Parameters\n" + "----------\n" + "a, b : array_like\n" + " Real values only. If the values are both negative, the result\n" + " is negative. If one value is negative and the other is positive,\n" + " `nan` is returned.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The arithmetic-geometric mean of `a` and `b`.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import agm\n" + ">>> a, b = 24.0, 6.0\n" + ">>> agm(a, b)\n" + "13.458171481725614\n" + "\n" + "Compare that result to the iteration:\n" + "\n" + ">>> while a != b:\n" + "... a, b = (a + b)/2, np.sqrt(a*b)\n" + "... print(\"a = %19.16f b=%19.16f\" % (a, b))\n" + "...\n" + "a = 15.0000000000000000 b=12.0000000000000000\n" + "a = 13.5000000000000000 b=13.4164078649987388\n" + "a = 13.4582039324993694 b=13.4581390309909850\n" + "a = 13.4581714817451772 b=13.4581714817060547\n" + "a = 13.4581714817256159 b=13.4581714817256159\n" + "\n" + "When array-like arguments are given, broadcasting applies:\n" + "\n" + ">>> a = np.array([[1.5], [3], [6]]) # a has shape (3, 1).\n" + ">>> b = np.array([6, 12, 24, 48]) # b has shape (4,).\n" + ">>> agm(a, b)\n" + "array([[ 3.36454287, 5.42363427, 9.05798751, 15.53650756],\n" + " [ 4.37037309, 6.72908574, 10.84726853, 18.11597502],\n" + " [ 6. , 8.74074619, 13.45817148, 21.69453707]])") +ufunc_agm_loops[0] = loop_d_dd__As_ff_f +ufunc_agm_loops[1] = loop_d_dd__As_dd_d +ufunc_agm_types[0] = NPY_FLOAT +ufunc_agm_types[1] = NPY_FLOAT +ufunc_agm_types[2] = NPY_FLOAT +ufunc_agm_types[3] = NPY_DOUBLE +ufunc_agm_types[4] = NPY_DOUBLE +ufunc_agm_types[5] = NPY_DOUBLE +ufunc_agm_ptr[2*0] = _func_agm +ufunc_agm_ptr[2*0+1] = ("agm") +ufunc_agm_ptr[2*1] = _func_agm +ufunc_agm_ptr[2*1+1] = ("agm") +ufunc_agm_data[0] = &ufunc_agm_ptr[2*0] +ufunc_agm_data[1] = &ufunc_agm_ptr[2*1] +agm = np.PyUFunc_FromFuncAndData(ufunc_agm_loops, ufunc_agm_data, ufunc_agm_types, 2, 2, 1, 0, "agm", ufunc_agm_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_bdtr_loops[3] +cdef void *ufunc_bdtr_ptr[6] +cdef void *ufunc_bdtr_data[3] +cdef char ufunc_bdtr_types[12] +cdef char *ufunc_bdtr_doc = ( + "bdtr(k, n, p, out=None)\n" + "\n" + "Binomial distribution cumulative distribution function.\n" + "\n" + "Sum of the terms 0 through `floor(k)` of the Binomial probability density.\n" + "\n" + ".. math::\n" + " \\mathrm{bdtr}(k, n, p) =\n" + " \\sum_{j=0}^{\\lfloor k \\rfloor} {{n}\\choose{j}} p^j (1-p)^{n-j}\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " Number of successes (double), rounded down to the nearest integer.\n" + "n : array_like\n" + " Number of events (int).\n" + "p : array_like\n" + " Probability of success in a single event (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "y : scalar or ndarray\n" + " Probability of `floor(k)` or fewer successes in `n` independent events with\n" + " success probabilities of `p`.\n" + "\n" + "Notes\n" + "-----\n" + "The terms are not summed directly; instead the regularized incomplete beta\n" + "function is employed, according to the formula,\n" + "\n" + ".. math::\n" + " \\mathrm{bdtr}(k, n, p) =\n" + " I_{1 - p}(n - \\lfloor k \\rfloor, \\lfloor k \\rfloor + 1).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `bdtr`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/") +ufunc_bdtr_loops[0] = loop_d_ddd__As_fff_f +ufunc_bdtr_loops[1] = loop_d_dpd__As_dpd_d +ufunc_bdtr_loops[2] = loop_d_ddd__As_ddd_d +ufunc_bdtr_types[0] = NPY_FLOAT +ufunc_bdtr_types[1] = NPY_FLOAT +ufunc_bdtr_types[2] = NPY_FLOAT +ufunc_bdtr_types[3] = NPY_FLOAT +ufunc_bdtr_types[4] = NPY_DOUBLE +ufunc_bdtr_types[5] = NPY_INTP +ufunc_bdtr_types[6] = NPY_DOUBLE +ufunc_bdtr_types[7] = NPY_DOUBLE +ufunc_bdtr_types[8] = NPY_DOUBLE +ufunc_bdtr_types[9] = NPY_DOUBLE +ufunc_bdtr_types[10] = NPY_DOUBLE +ufunc_bdtr_types[11] = NPY_DOUBLE +ufunc_bdtr_ptr[2*0] = _func_bdtr_unsafe +ufunc_bdtr_ptr[2*0+1] = ("bdtr") +ufunc_bdtr_ptr[2*1] = _func_cephes_bdtr_wrap +ufunc_bdtr_ptr[2*1+1] = ("bdtr") +ufunc_bdtr_ptr[2*2] = _func_bdtr_unsafe +ufunc_bdtr_ptr[2*2+1] = ("bdtr") +ufunc_bdtr_data[0] = &ufunc_bdtr_ptr[2*0] +ufunc_bdtr_data[1] = &ufunc_bdtr_ptr[2*1] +ufunc_bdtr_data[2] = &ufunc_bdtr_ptr[2*2] +bdtr = np.PyUFunc_FromFuncAndData(ufunc_bdtr_loops, ufunc_bdtr_data, ufunc_bdtr_types, 3, 3, 1, 0, "bdtr", ufunc_bdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_bdtrc_loops[3] +cdef void *ufunc_bdtrc_ptr[6] +cdef void *ufunc_bdtrc_data[3] +cdef char ufunc_bdtrc_types[12] +cdef char *ufunc_bdtrc_doc = ( + "bdtrc(k, n, p, out=None)\n" + "\n" + "Binomial distribution survival function.\n" + "\n" + "Sum of the terms `floor(k) + 1` through `n` of the binomial probability\n" + "density,\n" + "\n" + ".. math::\n" + " \\mathrm{bdtrc}(k, n, p) =\n" + " \\sum_{j=\\lfloor k \\rfloor +1}^n {{n}\\choose{j}} p^j (1-p)^{n-j}\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " Number of successes (double), rounded down to nearest integer.\n" + "n : array_like\n" + " Number of events (int)\n" + "p : array_like\n" + " Probability of success in a single event.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "y : scalar or ndarray\n" + " Probability of `floor(k) + 1` or more successes in `n` independent\n" + " events with success probabilities of `p`.\n" + "\n" + "See Also\n" + "--------\n" + "bdtr\n" + "betainc\n" + "\n" + "Notes\n" + "-----\n" + "The terms are not summed directly; instead the regularized incomplete beta\n" + "function is employed, according to the formula,\n" + "\n" + ".. math::\n" + " \\mathrm{bdtrc}(k, n, p) = I_{p}(\\lfloor k \\rfloor + 1, n - \\lfloor k \\rfloor).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `bdtrc`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/") +ufunc_bdtrc_loops[0] = loop_d_ddd__As_fff_f +ufunc_bdtrc_loops[1] = loop_d_dpd__As_dpd_d +ufunc_bdtrc_loops[2] = loop_d_ddd__As_ddd_d +ufunc_bdtrc_types[0] = NPY_FLOAT +ufunc_bdtrc_types[1] = NPY_FLOAT +ufunc_bdtrc_types[2] = NPY_FLOAT +ufunc_bdtrc_types[3] = NPY_FLOAT +ufunc_bdtrc_types[4] = NPY_DOUBLE +ufunc_bdtrc_types[5] = NPY_INTP +ufunc_bdtrc_types[6] = NPY_DOUBLE +ufunc_bdtrc_types[7] = NPY_DOUBLE +ufunc_bdtrc_types[8] = NPY_DOUBLE +ufunc_bdtrc_types[9] = NPY_DOUBLE +ufunc_bdtrc_types[10] = NPY_DOUBLE +ufunc_bdtrc_types[11] = NPY_DOUBLE +ufunc_bdtrc_ptr[2*0] = _func_bdtrc_unsafe +ufunc_bdtrc_ptr[2*0+1] = ("bdtrc") +ufunc_bdtrc_ptr[2*1] = _func_cephes_bdtrc_wrap +ufunc_bdtrc_ptr[2*1+1] = ("bdtrc") +ufunc_bdtrc_ptr[2*2] = _func_bdtrc_unsafe +ufunc_bdtrc_ptr[2*2+1] = ("bdtrc") +ufunc_bdtrc_data[0] = &ufunc_bdtrc_ptr[2*0] +ufunc_bdtrc_data[1] = &ufunc_bdtrc_ptr[2*1] +ufunc_bdtrc_data[2] = &ufunc_bdtrc_ptr[2*2] +bdtrc = np.PyUFunc_FromFuncAndData(ufunc_bdtrc_loops, ufunc_bdtrc_data, ufunc_bdtrc_types, 3, 3, 1, 0, "bdtrc", ufunc_bdtrc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_bdtri_loops[3] +cdef void *ufunc_bdtri_ptr[6] +cdef void *ufunc_bdtri_data[3] +cdef char ufunc_bdtri_types[12] +cdef char *ufunc_bdtri_doc = ( + "bdtri(k, n, y, out=None)\n" + "\n" + "Inverse function to `bdtr` with respect to `p`.\n" + "\n" + "Finds the event probability `p` such that the sum of the terms 0 through\n" + "`k` of the binomial probability density is equal to the given cumulative\n" + "probability `y`.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " Number of successes (float), rounded down to the nearest integer.\n" + "n : array_like\n" + " Number of events (float)\n" + "y : array_like\n" + " Cumulative probability (probability of `k` or fewer successes in `n`\n" + " events).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "p : scalar or ndarray\n" + " The event probability such that `bdtr(\\lfloor k \\rfloor, n, p) = y`.\n" + "\n" + "See Also\n" + "--------\n" + "bdtr\n" + "betaincinv\n" + "\n" + "Notes\n" + "-----\n" + "The computation is carried out using the inverse beta integral function\n" + "and the relation,::\n" + "\n" + " 1 - p = betaincinv(n - k, k + 1, y).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `bdtri`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/") +ufunc_bdtri_loops[0] = loop_d_ddd__As_fff_f +ufunc_bdtri_loops[1] = loop_d_dpd__As_dpd_d +ufunc_bdtri_loops[2] = loop_d_ddd__As_ddd_d +ufunc_bdtri_types[0] = NPY_FLOAT +ufunc_bdtri_types[1] = NPY_FLOAT +ufunc_bdtri_types[2] = NPY_FLOAT +ufunc_bdtri_types[3] = NPY_FLOAT +ufunc_bdtri_types[4] = NPY_DOUBLE +ufunc_bdtri_types[5] = NPY_INTP +ufunc_bdtri_types[6] = NPY_DOUBLE +ufunc_bdtri_types[7] = NPY_DOUBLE +ufunc_bdtri_types[8] = NPY_DOUBLE +ufunc_bdtri_types[9] = NPY_DOUBLE +ufunc_bdtri_types[10] = NPY_DOUBLE +ufunc_bdtri_types[11] = NPY_DOUBLE +ufunc_bdtri_ptr[2*0] = _func_bdtri_unsafe +ufunc_bdtri_ptr[2*0+1] = ("bdtri") +ufunc_bdtri_ptr[2*1] = _func_cephes_bdtri_wrap +ufunc_bdtri_ptr[2*1+1] = ("bdtri") +ufunc_bdtri_ptr[2*2] = _func_bdtri_unsafe +ufunc_bdtri_ptr[2*2+1] = ("bdtri") +ufunc_bdtri_data[0] = &ufunc_bdtri_ptr[2*0] +ufunc_bdtri_data[1] = &ufunc_bdtri_ptr[2*1] +ufunc_bdtri_data[2] = &ufunc_bdtri_ptr[2*2] +bdtri = np.PyUFunc_FromFuncAndData(ufunc_bdtri_loops, ufunc_bdtri_data, ufunc_bdtri_types, 3, 3, 1, 0, "bdtri", ufunc_bdtri_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_bdtrik_loops[2] +cdef void *ufunc_bdtrik_ptr[4] +cdef void *ufunc_bdtrik_data[2] +cdef char ufunc_bdtrik_types[8] +cdef char *ufunc_bdtrik_doc = ( + "bdtrik(y, n, p, out=None)\n" + "\n" + "Inverse function to `bdtr` with respect to `k`.\n" + "\n" + "Finds the number of successes `k` such that the sum of the terms 0 through\n" + "`k` of the Binomial probability density for `n` events with probability\n" + "`p` is equal to the given cumulative probability `y`.\n" + "\n" + "Parameters\n" + "----------\n" + "y : array_like\n" + " Cumulative probability (probability of `k` or fewer successes in `n`\n" + " events).\n" + "n : array_like\n" + " Number of events (float).\n" + "p : array_like\n" + " Success probability (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "k : scalar or ndarray\n" + " The number of successes `k` such that `bdtr(k, n, p) = y`.\n" + "\n" + "See Also\n" + "--------\n" + "bdtr\n" + "\n" + "Notes\n" + "-----\n" + "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n" + "cumulative incomplete beta distribution.\n" + "\n" + "Computation of `k` involves a search for a value that produces the desired\n" + "value of `y`. The search relies on the monotonicity of `y` with `k`.\n" + "\n" + "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.") +ufunc_bdtrik_loops[0] = loop_d_ddd__As_fff_f +ufunc_bdtrik_loops[1] = loop_d_ddd__As_ddd_d +ufunc_bdtrik_types[0] = NPY_FLOAT +ufunc_bdtrik_types[1] = NPY_FLOAT +ufunc_bdtrik_types[2] = NPY_FLOAT +ufunc_bdtrik_types[3] = NPY_FLOAT +ufunc_bdtrik_types[4] = NPY_DOUBLE +ufunc_bdtrik_types[5] = NPY_DOUBLE +ufunc_bdtrik_types[6] = NPY_DOUBLE +ufunc_bdtrik_types[7] = NPY_DOUBLE +ufunc_bdtrik_ptr[2*0] = _func_bdtrik +ufunc_bdtrik_ptr[2*0+1] = ("bdtrik") +ufunc_bdtrik_ptr[2*1] = _func_bdtrik +ufunc_bdtrik_ptr[2*1+1] = ("bdtrik") +ufunc_bdtrik_data[0] = &ufunc_bdtrik_ptr[2*0] +ufunc_bdtrik_data[1] = &ufunc_bdtrik_ptr[2*1] +bdtrik = np.PyUFunc_FromFuncAndData(ufunc_bdtrik_loops, ufunc_bdtrik_data, ufunc_bdtrik_types, 2, 3, 1, 0, "bdtrik", ufunc_bdtrik_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_bdtrin_loops[2] +cdef void *ufunc_bdtrin_ptr[4] +cdef void *ufunc_bdtrin_data[2] +cdef char ufunc_bdtrin_types[8] +cdef char *ufunc_bdtrin_doc = ( + "bdtrin(k, y, p, out=None)\n" + "\n" + "Inverse function to `bdtr` with respect to `n`.\n" + "\n" + "Finds the number of events `n` such that the sum of the terms 0 through\n" + "`k` of the Binomial probability density for events with probability `p` is\n" + "equal to the given cumulative probability `y`.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " Number of successes (float).\n" + "y : array_like\n" + " Cumulative probability (probability of `k` or fewer successes in `n`\n" + " events).\n" + "p : array_like\n" + " Success probability (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "n : scalar or ndarray\n" + " The number of events `n` such that `bdtr(k, n, p) = y`.\n" + "\n" + "See Also\n" + "--------\n" + "bdtr\n" + "\n" + "Notes\n" + "-----\n" + "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n" + "cumulative incomplete beta distribution.\n" + "\n" + "Computation of `n` involves a search for a value that produces the desired\n" + "value of `y`. The search relies on the monotonicity of `y` with `n`.\n" + "\n" + "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.") +ufunc_bdtrin_loops[0] = loop_d_ddd__As_fff_f +ufunc_bdtrin_loops[1] = loop_d_ddd__As_ddd_d +ufunc_bdtrin_types[0] = NPY_FLOAT +ufunc_bdtrin_types[1] = NPY_FLOAT +ufunc_bdtrin_types[2] = NPY_FLOAT +ufunc_bdtrin_types[3] = NPY_FLOAT +ufunc_bdtrin_types[4] = NPY_DOUBLE +ufunc_bdtrin_types[5] = NPY_DOUBLE +ufunc_bdtrin_types[6] = NPY_DOUBLE +ufunc_bdtrin_types[7] = NPY_DOUBLE +ufunc_bdtrin_ptr[2*0] = _func_bdtrin +ufunc_bdtrin_ptr[2*0+1] = ("bdtrin") +ufunc_bdtrin_ptr[2*1] = _func_bdtrin +ufunc_bdtrin_ptr[2*1+1] = ("bdtrin") +ufunc_bdtrin_data[0] = &ufunc_bdtrin_ptr[2*0] +ufunc_bdtrin_data[1] = &ufunc_bdtrin_ptr[2*1] +bdtrin = np.PyUFunc_FromFuncAndData(ufunc_bdtrin_loops, ufunc_bdtrin_data, ufunc_bdtrin_types, 2, 3, 1, 0, "bdtrin", ufunc_bdtrin_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_betainc_loops[2] +cdef void *ufunc_betainc_ptr[4] +cdef void *ufunc_betainc_data[2] +cdef char ufunc_betainc_types[8] +cdef char *ufunc_betainc_doc = ( + "betainc(a, b, x, out=None)\n" + "\n" + "Regularized incomplete beta function.\n" + "\n" + "Computes the regularized incomplete beta function, defined as [1]_:\n" + "\n" + ".. math::\n" + "\n" + " I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n" + " t^{a-1}(1-t)^{b-1}dt,\n" + "\n" + "for :math:`0 \\leq x \\leq 1`.\n" + "\n" + "This function is the cumulative distribution function for the beta\n" + "distribution; its range is [0, 1].\n" + "\n" + "Parameters\n" + "----------\n" + "a, b : array_like\n" + " Positive, real-valued parameters\n" + "x : array_like\n" + " Real-valued such that :math:`0 \\leq x \\leq 1`,\n" + " the upper limit of integration\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Value of the regularized incomplete beta function\n" + "\n" + "See Also\n" + "--------\n" + "beta : beta function\n" + "betaincinv : inverse of the regularized incomplete beta function\n" + "betaincc : complement of the regularized incomplete beta function\n" + "scipy.stats.beta : beta distribution\n" + "\n" + "Notes\n" + "-----\n" + "The term *regularized* in the name of this function refers to the\n" + "scaling of the function by the gamma function terms shown in the\n" + "formula. When not qualified as *regularized*, the name *incomplete\n" + "beta function* often refers to just the integral expression,\n" + "without the gamma terms. One can use the function `beta` from\n" + "`scipy.special` to get this \"nonregularized\" incomplete beta\n" + "function by multiplying the result of ``betainc(a, b, x)`` by\n" + "``beta(a, b)``.\n" + "\n" + "This function wraps the ``ibeta`` routine from the\n" + "Boost Math C++ library [2]_.\n" + "\n" + "References\n" + "----------\n" + ".. [1] NIST Digital Library of Mathematical Functions\n" + " https://dlmf.nist.gov/8.17\n" + ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + "\n" + "Let :math:`B(a, b)` be the `beta` function.\n" + "\n" + ">>> import scipy.special as sc\n" + "\n" + "The coefficient in terms of `gamma` is equal to\n" + ":math:`1/B(a, b)`. Also, when :math:`x=1`\n" + "the integral is equal to :math:`B(a, b)`.\n" + "Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`.\n" + "\n" + ">>> sc.betainc(0.2, 3.5, 1.0)\n" + "1.0\n" + "\n" + "It satisfies\n" + ":math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`,\n" + "where :math:`F` is the hypergeometric function `hyp2f1`:\n" + "\n" + ">>> a, b, x = 1.4, 3.1, 0.5\n" + ">>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b))\n" + "0.8148904036225295\n" + ">>> sc.betainc(a, b, x)\n" + "0.8148904036225296\n" + "\n" + "This functions satisfies the relationship\n" + ":math:`I_x(a, b) = 1 - I_{1-x}(b, a)`:\n" + "\n" + ">>> sc.betainc(2.2, 3.1, 0.4)\n" + "0.49339638807619446\n" + ">>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4)\n" + "0.49339638807619446") +ufunc_betainc_loops[0] = loop_f_fff__As_fff_f +ufunc_betainc_loops[1] = loop_d_ddd__As_ddd_d +ufunc_betainc_types[0] = NPY_FLOAT +ufunc_betainc_types[1] = NPY_FLOAT +ufunc_betainc_types[2] = NPY_FLOAT +ufunc_betainc_types[3] = NPY_FLOAT +ufunc_betainc_types[4] = NPY_DOUBLE +ufunc_betainc_types[5] = NPY_DOUBLE +ufunc_betainc_types[6] = NPY_DOUBLE +ufunc_betainc_types[7] = NPY_DOUBLE +ufunc_betainc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_float +ufunc_betainc_ptr[2*0+1] = ("betainc") +ufunc_betainc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_double +ufunc_betainc_ptr[2*1+1] = ("betainc") +ufunc_betainc_data[0] = &ufunc_betainc_ptr[2*0] +ufunc_betainc_data[1] = &ufunc_betainc_ptr[2*1] +betainc = np.PyUFunc_FromFuncAndData(ufunc_betainc_loops, ufunc_betainc_data, ufunc_betainc_types, 2, 3, 1, 0, "betainc", ufunc_betainc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_betaincc_loops[2] +cdef void *ufunc_betaincc_ptr[4] +cdef void *ufunc_betaincc_data[2] +cdef char ufunc_betaincc_types[8] +cdef char *ufunc_betaincc_doc = ( + "betaincc(a, b, x, out=None)\n" + "\n" + "Complement of the regularized incomplete beta function.\n" + "\n" + "Computes the complement of the regularized incomplete beta function,\n" + "defined as [1]_:\n" + "\n" + ".. math::\n" + "\n" + " \\bar{I}_x(a, b) = 1 - I_x(a, b)\n" + " = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n" + " t^{a-1}(1-t)^{b-1}dt,\n" + "\n" + "for :math:`0 \\leq x \\leq 1`.\n" + "\n" + "Parameters\n" + "----------\n" + "a, b : array_like\n" + " Positive, real-valued parameters\n" + "x : array_like\n" + " Real-valued such that :math:`0 \\leq x \\leq 1`,\n" + " the upper limit of integration\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Value of the regularized incomplete beta function\n" + "\n" + "See Also\n" + "--------\n" + "betainc : regularized incomplete beta function\n" + "betaincinv : inverse of the regularized incomplete beta function\n" + "betainccinv :\n" + " inverse of the complement of the regularized incomplete beta function\n" + "beta : beta function\n" + "scipy.stats.beta : beta distribution\n" + "\n" + "Notes\n" + "-----\n" + ".. versionadded:: 1.11.0\n" + "\n" + "This function wraps the ``ibetac`` routine from the\n" + "Boost Math C++ library [2]_.\n" + "\n" + "References\n" + "----------\n" + ".. [1] NIST Digital Library of Mathematical Functions\n" + " https://dlmf.nist.gov/8.17\n" + ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import betaincc, betainc\n" + "\n" + "The naive calculation ``1 - betainc(a, b, x)`` loses precision when\n" + "the values of ``betainc(a, b, x)`` are close to 1:\n" + "\n" + ">>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999])\n" + "array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00])\n" + "\n" + "By using ``betaincc``, we get the correct values:\n" + "\n" + ">>> betaincc(0.5, 8, [0.9, 0.99, 0.999])\n" + "array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25])") +ufunc_betaincc_loops[0] = loop_f_fff__As_fff_f +ufunc_betaincc_loops[1] = loop_d_ddd__As_ddd_d +ufunc_betaincc_types[0] = NPY_FLOAT +ufunc_betaincc_types[1] = NPY_FLOAT +ufunc_betaincc_types[2] = NPY_FLOAT +ufunc_betaincc_types[3] = NPY_FLOAT +ufunc_betaincc_types[4] = NPY_DOUBLE +ufunc_betaincc_types[5] = NPY_DOUBLE +ufunc_betaincc_types[6] = NPY_DOUBLE +ufunc_betaincc_types[7] = NPY_DOUBLE +ufunc_betaincc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_float +ufunc_betaincc_ptr[2*0+1] = ("betaincc") +ufunc_betaincc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_double +ufunc_betaincc_ptr[2*1+1] = ("betaincc") +ufunc_betaincc_data[0] = &ufunc_betaincc_ptr[2*0] +ufunc_betaincc_data[1] = &ufunc_betaincc_ptr[2*1] +betaincc = np.PyUFunc_FromFuncAndData(ufunc_betaincc_loops, ufunc_betaincc_data, ufunc_betaincc_types, 2, 3, 1, 0, "betaincc", ufunc_betaincc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_betainccinv_loops[2] +cdef void *ufunc_betainccinv_ptr[4] +cdef void *ufunc_betainccinv_data[2] +cdef char ufunc_betainccinv_types[8] +cdef char *ufunc_betainccinv_doc = ( + "betainccinv(a, b, y, out=None)\n" + "\n" + "Inverse of the complemented regularized incomplete beta function.\n" + "\n" + "Computes :math:`x` such that:\n" + "\n" + ".. math::\n" + "\n" + " y = 1 - I_x(a, b) = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n" + " \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n" + "\n" + "where :math:`I_x` is the normalized incomplete beta function `betainc`\n" + "and :math:`\\Gamma` is the `gamma` function [1]_.\n" + "\n" + "Parameters\n" + "----------\n" + "a, b : array_like\n" + " Positive, real-valued parameters\n" + "y : array_like\n" + " Real-valued input\n" + "out : ndarray, optional\n" + " Optional output array for function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Value of the inverse of the regularized incomplete beta function\n" + "\n" + "See Also\n" + "--------\n" + "betainc : regularized incomplete beta function\n" + "betaincc : complement of the regularized incomplete beta function\n" + "\n" + "Notes\n" + "-----\n" + ".. versionadded:: 1.11.0\n" + "\n" + "This function wraps the ``ibetac_inv`` routine from the\n" + "Boost Math C++ library [2]_.\n" + "\n" + "References\n" + "----------\n" + ".. [1] NIST Digital Library of Mathematical Functions\n" + " https://dlmf.nist.gov/8.17\n" + ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import betainccinv, betaincc\n" + "\n" + "This function is the inverse of `betaincc` for fixed\n" + "values of :math:`a` and :math:`b`.\n" + "\n" + ">>> a, b = 1.2, 3.1\n" + ">>> y = betaincc(a, b, 0.2)\n" + ">>> betainccinv(a, b, y)\n" + "0.2\n" + "\n" + ">>> a, b = 7, 2.5\n" + ">>> x = betainccinv(a, b, 0.875)\n" + ">>> betaincc(a, b, x)\n" + "0.875") +ufunc_betainccinv_loops[0] = loop_f_fff__As_fff_f +ufunc_betainccinv_loops[1] = loop_d_ddd__As_ddd_d +ufunc_betainccinv_types[0] = NPY_FLOAT +ufunc_betainccinv_types[1] = NPY_FLOAT +ufunc_betainccinv_types[2] = NPY_FLOAT +ufunc_betainccinv_types[3] = NPY_FLOAT +ufunc_betainccinv_types[4] = NPY_DOUBLE +ufunc_betainccinv_types[5] = NPY_DOUBLE +ufunc_betainccinv_types[6] = NPY_DOUBLE +ufunc_betainccinv_types[7] = NPY_DOUBLE +ufunc_betainccinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_inv_float +ufunc_betainccinv_ptr[2*0+1] = ("betainccinv") +ufunc_betainccinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_inv_double +ufunc_betainccinv_ptr[2*1+1] = ("betainccinv") +ufunc_betainccinv_data[0] = &ufunc_betainccinv_ptr[2*0] +ufunc_betainccinv_data[1] = &ufunc_betainccinv_ptr[2*1] +betainccinv = np.PyUFunc_FromFuncAndData(ufunc_betainccinv_loops, ufunc_betainccinv_data, ufunc_betainccinv_types, 2, 3, 1, 0, "betainccinv", ufunc_betainccinv_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_betaincinv_loops[2] +cdef void *ufunc_betaincinv_ptr[4] +cdef void *ufunc_betaincinv_data[2] +cdef char ufunc_betaincinv_types[8] +cdef char *ufunc_betaincinv_doc = ( + "betaincinv(a, b, y, out=None)\n" + "\n" + "Inverse of the regularized incomplete beta function.\n" + "\n" + "Computes :math:`x` such that:\n" + "\n" + ".. math::\n" + "\n" + " y = I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n" + " \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n" + "\n" + "where :math:`I_x` is the normalized incomplete beta function `betainc`\n" + "and :math:`\\Gamma` is the `gamma` function [1]_.\n" + "\n" + "Parameters\n" + "----------\n" + "a, b : array_like\n" + " Positive, real-valued parameters\n" + "y : array_like\n" + " Real-valued input\n" + "out : ndarray, optional\n" + " Optional output array for function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Value of the inverse of the regularized incomplete beta function\n" + "\n" + "See Also\n" + "--------\n" + "betainc : regularized incomplete beta function\n" + "gamma : gamma function\n" + "\n" + "Notes\n" + "-----\n" + "This function wraps the ``ibeta_inv`` routine from the\n" + "Boost Math C++ library [2]_.\n" + "\n" + "References\n" + "----------\n" + ".. [1] NIST Digital Library of Mathematical Functions\n" + " https://dlmf.nist.gov/8.17\n" + ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import scipy.special as sc\n" + "\n" + "This function is the inverse of `betainc` for fixed\n" + "values of :math:`a` and :math:`b`.\n" + "\n" + ">>> a, b = 1.2, 3.1\n" + ">>> y = sc.betainc(a, b, 0.2)\n" + ">>> sc.betaincinv(a, b, y)\n" + "0.2\n" + ">>>\n" + ">>> a, b = 7.5, 0.4\n" + ">>> x = sc.betaincinv(a, b, 0.5)\n" + ">>> sc.betainc(a, b, x)\n" + "0.5") +ufunc_betaincinv_loops[0] = loop_f_fff__As_fff_f +ufunc_betaincinv_loops[1] = loop_d_ddd__As_ddd_d +ufunc_betaincinv_types[0] = NPY_FLOAT +ufunc_betaincinv_types[1] = NPY_FLOAT +ufunc_betaincinv_types[2] = NPY_FLOAT +ufunc_betaincinv_types[3] = NPY_FLOAT +ufunc_betaincinv_types[4] = NPY_DOUBLE +ufunc_betaincinv_types[5] = NPY_DOUBLE +ufunc_betaincinv_types[6] = NPY_DOUBLE +ufunc_betaincinv_types[7] = NPY_DOUBLE +ufunc_betaincinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_inv_float +ufunc_betaincinv_ptr[2*0+1] = ("betaincinv") +ufunc_betaincinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_inv_double +ufunc_betaincinv_ptr[2*1+1] = ("betaincinv") +ufunc_betaincinv_data[0] = &ufunc_betaincinv_ptr[2*0] +ufunc_betaincinv_data[1] = &ufunc_betaincinv_ptr[2*1] +betaincinv = np.PyUFunc_FromFuncAndData(ufunc_betaincinv_loops, ufunc_betaincinv_data, ufunc_betaincinv_types, 2, 3, 1, 0, "betaincinv", ufunc_betaincinv_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_boxcox_loops[2] +cdef void *ufunc_boxcox_ptr[4] +cdef void *ufunc_boxcox_data[2] +cdef char ufunc_boxcox_types[6] +cdef char *ufunc_boxcox_doc = ( + "boxcox(x, lmbda, out=None)\n" + "\n" + "Compute the Box-Cox transformation.\n" + "\n" + "The Box-Cox transformation is::\n" + "\n" + " y = (x**lmbda - 1) / lmbda if lmbda != 0\n" + " log(x) if lmbda == 0\n" + "\n" + "Returns `nan` if ``x < 0``.\n" + "Returns `-inf` if ``x == 0`` and ``lmbda < 0``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Data to be transformed.\n" + "lmbda : array_like\n" + " Power parameter of the Box-Cox transform.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "y : scalar or ndarray\n" + " Transformed data.\n" + "\n" + "Notes\n" + "-----\n" + "\n" + ".. versionadded:: 0.14.0\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import boxcox\n" + ">>> boxcox([1, 4, 10], 2.5)\n" + "array([ 0. , 12.4 , 126.09110641])\n" + ">>> boxcox(2, [0, 1, 2])\n" + "array([ 0.69314718, 1. , 1.5 ])") +ufunc_boxcox_loops[0] = loop_d_dd__As_ff_f +ufunc_boxcox_loops[1] = loop_d_dd__As_dd_d +ufunc_boxcox_types[0] = NPY_FLOAT +ufunc_boxcox_types[1] = NPY_FLOAT +ufunc_boxcox_types[2] = NPY_FLOAT +ufunc_boxcox_types[3] = NPY_DOUBLE +ufunc_boxcox_types[4] = NPY_DOUBLE +ufunc_boxcox_types[5] = NPY_DOUBLE +ufunc_boxcox_ptr[2*0] = _func_boxcox +ufunc_boxcox_ptr[2*0+1] = ("boxcox") +ufunc_boxcox_ptr[2*1] = _func_boxcox +ufunc_boxcox_ptr[2*1+1] = ("boxcox") +ufunc_boxcox_data[0] = &ufunc_boxcox_ptr[2*0] +ufunc_boxcox_data[1] = &ufunc_boxcox_ptr[2*1] +boxcox = np.PyUFunc_FromFuncAndData(ufunc_boxcox_loops, ufunc_boxcox_data, ufunc_boxcox_types, 2, 2, 1, 0, "boxcox", ufunc_boxcox_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_boxcox1p_loops[2] +cdef void *ufunc_boxcox1p_ptr[4] +cdef void *ufunc_boxcox1p_data[2] +cdef char ufunc_boxcox1p_types[6] +cdef char *ufunc_boxcox1p_doc = ( + "boxcox1p(x, lmbda, out=None)\n" + "\n" + "Compute the Box-Cox transformation of 1 + `x`.\n" + "\n" + "The Box-Cox transformation computed by `boxcox1p` is::\n" + "\n" + " y = ((1+x)**lmbda - 1) / lmbda if lmbda != 0\n" + " log(1+x) if lmbda == 0\n" + "\n" + "Returns `nan` if ``x < -1``.\n" + "Returns `-inf` if ``x == -1`` and ``lmbda < 0``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Data to be transformed.\n" + "lmbda : array_like\n" + " Power parameter of the Box-Cox transform.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "y : scalar or ndarray\n" + " Transformed data.\n" + "\n" + "Notes\n" + "-----\n" + "\n" + ".. versionadded:: 0.14.0\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import boxcox1p\n" + ">>> boxcox1p(1e-4, [0, 0.5, 1])\n" + "array([ 9.99950003e-05, 9.99975001e-05, 1.00000000e-04])\n" + ">>> boxcox1p([0.01, 0.1], 0.25)\n" + "array([ 0.00996272, 0.09645476])") +ufunc_boxcox1p_loops[0] = loop_d_dd__As_ff_f +ufunc_boxcox1p_loops[1] = loop_d_dd__As_dd_d +ufunc_boxcox1p_types[0] = NPY_FLOAT +ufunc_boxcox1p_types[1] = NPY_FLOAT +ufunc_boxcox1p_types[2] = NPY_FLOAT +ufunc_boxcox1p_types[3] = NPY_DOUBLE +ufunc_boxcox1p_types[4] = NPY_DOUBLE +ufunc_boxcox1p_types[5] = NPY_DOUBLE +ufunc_boxcox1p_ptr[2*0] = _func_boxcox1p +ufunc_boxcox1p_ptr[2*0+1] = ("boxcox1p") +ufunc_boxcox1p_ptr[2*1] = _func_boxcox1p +ufunc_boxcox1p_ptr[2*1+1] = ("boxcox1p") +ufunc_boxcox1p_data[0] = &ufunc_boxcox1p_ptr[2*0] +ufunc_boxcox1p_data[1] = &ufunc_boxcox1p_ptr[2*1] +boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_boxcox1p_loops, ufunc_boxcox1p_data, ufunc_boxcox1p_types, 2, 2, 1, 0, "boxcox1p", ufunc_boxcox1p_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_btdtria_loops[2] +cdef void *ufunc_btdtria_ptr[4] +cdef void *ufunc_btdtria_data[2] +cdef char ufunc_btdtria_types[8] +cdef char *ufunc_btdtria_doc = ( + "btdtria(p, b, x, out=None)\n" + "\n" + "Inverse of `betainc` with respect to `a`.\n" + "\n" + "This is the inverse of the beta cumulative distribution function, `betainc`,\n" + "considered as a function of `a`, returning the value of `a` for which\n" + "`betainc(a, b, x) = p`, or\n" + "\n" + ".. math::\n" + " p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Cumulative probability, in [0, 1].\n" + "b : array_like\n" + " Shape parameter (`b` > 0).\n" + "x : array_like\n" + " The quantile, in [0, 1].\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "a : scalar or ndarray\n" + " The value of the shape parameter `a` such that `betainc(a, b, x) = p`.\n" + "\n" + "See Also\n" + "--------\n" + "btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`.\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n" + "\n" + "The cumulative distribution function `p` is computed using a routine by\n" + "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n" + "that produces the desired value of `p`. The search relies on the\n" + "monotonicity of `p` with `a`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.\n" + ".. [2] DiDinato, A. R. and Morris, A. H.,\n" + " Algorithm 708: Significant Digit Computation of the Incomplete Beta\n" + " Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.") +ufunc_btdtria_loops[0] = loop_d_ddd__As_fff_f +ufunc_btdtria_loops[1] = loop_d_ddd__As_ddd_d +ufunc_btdtria_types[0] = NPY_FLOAT +ufunc_btdtria_types[1] = NPY_FLOAT +ufunc_btdtria_types[2] = NPY_FLOAT +ufunc_btdtria_types[3] = NPY_FLOAT +ufunc_btdtria_types[4] = NPY_DOUBLE +ufunc_btdtria_types[5] = NPY_DOUBLE +ufunc_btdtria_types[6] = NPY_DOUBLE +ufunc_btdtria_types[7] = NPY_DOUBLE +ufunc_btdtria_ptr[2*0] = _func_btdtria +ufunc_btdtria_ptr[2*0+1] = ("btdtria") +ufunc_btdtria_ptr[2*1] = _func_btdtria +ufunc_btdtria_ptr[2*1+1] = ("btdtria") +ufunc_btdtria_data[0] = &ufunc_btdtria_ptr[2*0] +ufunc_btdtria_data[1] = &ufunc_btdtria_ptr[2*1] +btdtria = np.PyUFunc_FromFuncAndData(ufunc_btdtria_loops, ufunc_btdtria_data, ufunc_btdtria_types, 2, 3, 1, 0, "btdtria", ufunc_btdtria_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_btdtrib_loops[2] +cdef void *ufunc_btdtrib_ptr[4] +cdef void *ufunc_btdtrib_data[2] +cdef char ufunc_btdtrib_types[8] +cdef char *ufunc_btdtrib_doc = ( + "btdtria(a, p, x, out=None)\n" + "\n" + "Inverse of `betainc` with respect to `b`.\n" + "\n" + "This is the inverse of the beta cumulative distribution function, `betainc`,\n" + "considered as a function of `b`, returning the value of `b` for which\n" + "`betainc(a, b, x) = p`, or\n" + "\n" + ".. math::\n" + " p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n" + "\n" + "Parameters\n" + "----------\n" + "a : array_like\n" + " Shape parameter (`a` > 0).\n" + "p : array_like\n" + " Cumulative probability, in [0, 1].\n" + "x : array_like\n" + " The quantile, in [0, 1].\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "b : scalar or ndarray\n" + " The value of the shape parameter `b` such that `betainc(a, b, x) = p`.\n" + "\n" + "See Also\n" + "--------\n" + "btdtria : Inverse of the beta cumulative distribution function, with respect to `a`.\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n" + "\n" + "The cumulative distribution function `p` is computed using a routine by\n" + "DiDinato and Morris [2]_. Computation of `b` involves a search for a value\n" + "that produces the desired value of `p`. The search relies on the\n" + "monotonicity of `p` with `b`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.\n" + ".. [2] DiDinato, A. R. and Morris, A. H.,\n" + " Algorithm 708: Significant Digit Computation of the Incomplete Beta\n" + " Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.") +ufunc_btdtrib_loops[0] = loop_d_ddd__As_fff_f +ufunc_btdtrib_loops[1] = loop_d_ddd__As_ddd_d +ufunc_btdtrib_types[0] = NPY_FLOAT +ufunc_btdtrib_types[1] = NPY_FLOAT +ufunc_btdtrib_types[2] = NPY_FLOAT +ufunc_btdtrib_types[3] = NPY_FLOAT +ufunc_btdtrib_types[4] = NPY_DOUBLE +ufunc_btdtrib_types[5] = NPY_DOUBLE +ufunc_btdtrib_types[6] = NPY_DOUBLE +ufunc_btdtrib_types[7] = NPY_DOUBLE +ufunc_btdtrib_ptr[2*0] = _func_btdtrib +ufunc_btdtrib_ptr[2*0+1] = ("btdtrib") +ufunc_btdtrib_ptr[2*1] = _func_btdtrib +ufunc_btdtrib_ptr[2*1+1] = ("btdtrib") +ufunc_btdtrib_data[0] = &ufunc_btdtrib_ptr[2*0] +ufunc_btdtrib_data[1] = &ufunc_btdtrib_ptr[2*1] +btdtrib = np.PyUFunc_FromFuncAndData(ufunc_btdtrib_loops, ufunc_btdtrib_data, ufunc_btdtrib_types, 2, 3, 1, 0, "btdtrib", ufunc_btdtrib_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chdtr_loops[2] +cdef void *ufunc_chdtr_ptr[4] +cdef void *ufunc_chdtr_data[2] +cdef char ufunc_chdtr_types[6] +cdef char *ufunc_chdtr_doc = ( + "chdtr(v, x, out=None)\n" + "\n" + "Chi square cumulative distribution function.\n" + "\n" + "Returns the area under the left tail (from 0 to `x`) of the Chi\n" + "square probability density function with `v` degrees of freedom:\n" + "\n" + ".. math::\n" + "\n" + " \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_0^x t^{v/2 - 1} e^{-t/2} dt\n" + "\n" + "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n" + "integral can be expressed in terms of the regularized lower\n" + "incomplete gamma function `gammainc` as\n" + "``gammainc(v / 2, x / 2)``. [1]_\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Degrees of freedom.\n" + "x : array_like\n" + " Upper bound of the integral.\n" + "out : ndarray, optional\n" + " Optional output array for the function results.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the cumulative distribution function.\n" + "\n" + "See Also\n" + "--------\n" + "chdtrc, chdtri, chdtriv, gammainc\n" + "\n" + "References\n" + "----------\n" + ".. [1] Chi-Square distribution,\n" + " https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It can be expressed in terms of the regularized lower incomplete\n" + "gamma function.\n" + "\n" + ">>> v = 1\n" + ">>> x = np.arange(4)\n" + ">>> sc.chdtr(v, x)\n" + "array([0. , 0.68268949, 0.84270079, 0.91673548])\n" + ">>> sc.gammainc(v / 2, x / 2)\n" + "array([0. , 0.68268949, 0.84270079, 0.91673548])") +ufunc_chdtr_loops[0] = loop_d_dd__As_ff_f +ufunc_chdtr_loops[1] = loop_d_dd__As_dd_d +ufunc_chdtr_types[0] = NPY_FLOAT +ufunc_chdtr_types[1] = NPY_FLOAT +ufunc_chdtr_types[2] = NPY_FLOAT +ufunc_chdtr_types[3] = NPY_DOUBLE +ufunc_chdtr_types[4] = NPY_DOUBLE +ufunc_chdtr_types[5] = NPY_DOUBLE +ufunc_chdtr_ptr[2*0] = _func_xsf_chdtr +ufunc_chdtr_ptr[2*0+1] = ("chdtr") +ufunc_chdtr_ptr[2*1] = _func_xsf_chdtr +ufunc_chdtr_ptr[2*1+1] = ("chdtr") +ufunc_chdtr_data[0] = &ufunc_chdtr_ptr[2*0] +ufunc_chdtr_data[1] = &ufunc_chdtr_ptr[2*1] +chdtr = np.PyUFunc_FromFuncAndData(ufunc_chdtr_loops, ufunc_chdtr_data, ufunc_chdtr_types, 2, 2, 1, 0, "chdtr", ufunc_chdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chdtrc_loops[2] +cdef void *ufunc_chdtrc_ptr[4] +cdef void *ufunc_chdtrc_data[2] +cdef char ufunc_chdtrc_types[6] +cdef char *ufunc_chdtrc_doc = ( + "chdtrc(v, x, out=None)\n" + "\n" + "Chi square survival function.\n" + "\n" + "Returns the area under the right hand tail (from `x` to infinity)\n" + "of the Chi square probability density function with `v` degrees of\n" + "freedom:\n" + "\n" + ".. math::\n" + "\n" + " \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_x^\\infty t^{v/2 - 1} e^{-t/2} dt\n" + "\n" + "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n" + "integral can be expressed in terms of the regularized upper\n" + "incomplete gamma function `gammaincc` as\n" + "``gammaincc(v / 2, x / 2)``. [1]_\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Degrees of freedom.\n" + "x : array_like\n" + " Lower bound of the integral.\n" + "out : ndarray, optional\n" + " Optional output array for the function results.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the survival function.\n" + "\n" + "See Also\n" + "--------\n" + "chdtr, chdtri, chdtriv, gammaincc\n" + "\n" + "References\n" + "----------\n" + ".. [1] Chi-Square distribution,\n" + " https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It can be expressed in terms of the regularized upper incomplete\n" + "gamma function.\n" + "\n" + ">>> v = 1\n" + ">>> x = np.arange(4)\n" + ">>> sc.chdtrc(v, x)\n" + "array([1. , 0.31731051, 0.15729921, 0.08326452])\n" + ">>> sc.gammaincc(v / 2, x / 2)\n" + "array([1. , 0.31731051, 0.15729921, 0.08326452])") +ufunc_chdtrc_loops[0] = loop_d_dd__As_ff_f +ufunc_chdtrc_loops[1] = loop_d_dd__As_dd_d +ufunc_chdtrc_types[0] = NPY_FLOAT +ufunc_chdtrc_types[1] = NPY_FLOAT +ufunc_chdtrc_types[2] = NPY_FLOAT +ufunc_chdtrc_types[3] = NPY_DOUBLE +ufunc_chdtrc_types[4] = NPY_DOUBLE +ufunc_chdtrc_types[5] = NPY_DOUBLE +ufunc_chdtrc_ptr[2*0] = _func_xsf_chdtrc +ufunc_chdtrc_ptr[2*0+1] = ("chdtrc") +ufunc_chdtrc_ptr[2*1] = _func_xsf_chdtrc +ufunc_chdtrc_ptr[2*1+1] = ("chdtrc") +ufunc_chdtrc_data[0] = &ufunc_chdtrc_ptr[2*0] +ufunc_chdtrc_data[1] = &ufunc_chdtrc_ptr[2*1] +chdtrc = np.PyUFunc_FromFuncAndData(ufunc_chdtrc_loops, ufunc_chdtrc_data, ufunc_chdtrc_types, 2, 2, 1, 0, "chdtrc", ufunc_chdtrc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chdtri_loops[2] +cdef void *ufunc_chdtri_ptr[4] +cdef void *ufunc_chdtri_data[2] +cdef char ufunc_chdtri_types[6] +cdef char *ufunc_chdtri_doc = ( + "chdtri(v, p, out=None)\n" + "\n" + "Inverse to `chdtrc` with respect to `x`.\n" + "\n" + "Returns `x` such that ``chdtrc(v, x) == p``.\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Degrees of freedom.\n" + "p : array_like\n" + " Probability.\n" + "out : ndarray, optional\n" + " Optional output array for the function results.\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " Value so that the probability a Chi square random variable\n" + " with `v` degrees of freedom is greater than `x` equals `p`.\n" + "\n" + "See Also\n" + "--------\n" + "chdtrc, chdtr, chdtriv\n" + "\n" + "References\n" + "----------\n" + ".. [1] Chi-Square distribution,\n" + " https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n" + "\n" + "Examples\n" + "--------\n" + ">>> import scipy.special as sc\n" + "\n" + "It inverts `chdtrc`.\n" + "\n" + ">>> v, p = 1, 0.3\n" + ">>> sc.chdtrc(v, sc.chdtri(v, p))\n" + "0.3\n" + ">>> x = 1\n" + ">>> sc.chdtri(v, sc.chdtrc(v, x))\n" + "1.0") +ufunc_chdtri_loops[0] = loop_d_dd__As_ff_f +ufunc_chdtri_loops[1] = loop_d_dd__As_dd_d +ufunc_chdtri_types[0] = NPY_FLOAT +ufunc_chdtri_types[1] = NPY_FLOAT +ufunc_chdtri_types[2] = NPY_FLOAT +ufunc_chdtri_types[3] = NPY_DOUBLE +ufunc_chdtri_types[4] = NPY_DOUBLE +ufunc_chdtri_types[5] = NPY_DOUBLE +ufunc_chdtri_ptr[2*0] = _func_xsf_chdtri +ufunc_chdtri_ptr[2*0+1] = ("chdtri") +ufunc_chdtri_ptr[2*1] = _func_xsf_chdtri +ufunc_chdtri_ptr[2*1+1] = ("chdtri") +ufunc_chdtri_data[0] = &ufunc_chdtri_ptr[2*0] +ufunc_chdtri_data[1] = &ufunc_chdtri_ptr[2*1] +chdtri = np.PyUFunc_FromFuncAndData(ufunc_chdtri_loops, ufunc_chdtri_data, ufunc_chdtri_types, 2, 2, 1, 0, "chdtri", ufunc_chdtri_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chdtriv_loops[2] +cdef void *ufunc_chdtriv_ptr[4] +cdef void *ufunc_chdtriv_data[2] +cdef char ufunc_chdtriv_types[6] +cdef char *ufunc_chdtriv_doc = ( + "chdtriv(p, x, out=None)\n" + "\n" + "Inverse to `chdtr` with respect to `v`.\n" + "\n" + "Returns `v` such that ``chdtr(v, x) == p``.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probability that the Chi square random variable is less than\n" + " or equal to `x`.\n" + "x : array_like\n" + " Nonnegative input.\n" + "out : ndarray, optional\n" + " Optional output array for the function results.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Degrees of freedom.\n" + "\n" + "See Also\n" + "--------\n" + "chdtr, chdtrc, chdtri\n" + "\n" + "References\n" + "----------\n" + ".. [1] Chi-Square distribution,\n" + " https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n" + "\n" + "Examples\n" + "--------\n" + ">>> import scipy.special as sc\n" + "\n" + "It inverts `chdtr`.\n" + "\n" + ">>> p, x = 0.5, 1\n" + ">>> sc.chdtr(sc.chdtriv(p, x), x)\n" + "0.5000000000202172\n" + ">>> v = 1\n" + ">>> sc.chdtriv(sc.chdtr(v, x), v)\n" + "1.0000000000000013") +ufunc_chdtriv_loops[0] = loop_d_dd__As_ff_f +ufunc_chdtriv_loops[1] = loop_d_dd__As_dd_d +ufunc_chdtriv_types[0] = NPY_FLOAT +ufunc_chdtriv_types[1] = NPY_FLOAT +ufunc_chdtriv_types[2] = NPY_FLOAT +ufunc_chdtriv_types[3] = NPY_DOUBLE +ufunc_chdtriv_types[4] = NPY_DOUBLE +ufunc_chdtriv_types[5] = NPY_DOUBLE +ufunc_chdtriv_ptr[2*0] = _func_chdtriv +ufunc_chdtriv_ptr[2*0+1] = ("chdtriv") +ufunc_chdtriv_ptr[2*1] = _func_chdtriv +ufunc_chdtriv_ptr[2*1+1] = ("chdtriv") +ufunc_chdtriv_data[0] = &ufunc_chdtriv_ptr[2*0] +ufunc_chdtriv_data[1] = &ufunc_chdtriv_ptr[2*1] +chdtriv = np.PyUFunc_FromFuncAndData(ufunc_chdtriv_loops, ufunc_chdtriv_data, ufunc_chdtriv_types, 2, 2, 1, 0, "chdtriv", ufunc_chdtriv_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chndtr_loops[2] +cdef void *ufunc_chndtr_ptr[4] +cdef void *ufunc_chndtr_data[2] +cdef char ufunc_chndtr_types[8] +cdef char *ufunc_chndtr_doc = ( + "chndtr(x, df, nc, out=None)\n" + "\n" + "Non-central chi square cumulative distribution function\n" + "\n" + "The cumulative distribution function is given by:\n" + "\n" + ".. math::\n" + "\n" + " P(\\chi^{\\prime 2} \\vert \\nu, \\lambda) =\\sum_{j=0}^{\\infty}\n" + " e^{-\\lambda /2}\n" + " \\frac{(\\lambda /2)^j}{j!} P(\\chi^{\\prime 2} \\vert \\nu + 2j),\n" + "\n" + "where :math:`\\nu > 0` is the degrees of freedom (``df``) and\n" + ":math:`\\lambda \\geq 0` is the non-centrality parameter (``nc``).\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Upper bound of the integral; must satisfy ``x >= 0``\n" + "df : array_like\n" + " Degrees of freedom; must satisfy ``df > 0``\n" + "nc : array_like\n" + " Non-centrality parameter; must satisfy ``nc >= 0``\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " Value of the non-central chi square cumulative distribution function.\n" + "\n" + "See Also\n" + "--------\n" + "chndtrix, chndtridf, chndtrinc") +ufunc_chndtr_loops[0] = loop_d_ddd__As_fff_f +ufunc_chndtr_loops[1] = loop_d_ddd__As_ddd_d +ufunc_chndtr_types[0] = NPY_FLOAT +ufunc_chndtr_types[1] = NPY_FLOAT +ufunc_chndtr_types[2] = NPY_FLOAT +ufunc_chndtr_types[3] = NPY_FLOAT +ufunc_chndtr_types[4] = NPY_DOUBLE +ufunc_chndtr_types[5] = NPY_DOUBLE +ufunc_chndtr_types[6] = NPY_DOUBLE +ufunc_chndtr_types[7] = NPY_DOUBLE +ufunc_chndtr_ptr[2*0] = _func_chndtr +ufunc_chndtr_ptr[2*0+1] = ("chndtr") +ufunc_chndtr_ptr[2*1] = _func_chndtr +ufunc_chndtr_ptr[2*1+1] = ("chndtr") +ufunc_chndtr_data[0] = &ufunc_chndtr_ptr[2*0] +ufunc_chndtr_data[1] = &ufunc_chndtr_ptr[2*1] +chndtr = np.PyUFunc_FromFuncAndData(ufunc_chndtr_loops, ufunc_chndtr_data, ufunc_chndtr_types, 2, 3, 1, 0, "chndtr", ufunc_chndtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chndtridf_loops[2] +cdef void *ufunc_chndtridf_ptr[4] +cdef void *ufunc_chndtridf_data[2] +cdef char ufunc_chndtridf_types[8] +cdef char *ufunc_chndtridf_doc = ( + "chndtridf(x, p, nc, out=None)\n" + "\n" + "Inverse to `chndtr` vs `df`\n" + "\n" + "Calculated using a search to find a value for `df` that produces the\n" + "desired value of `p`.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Upper bound of the integral; must satisfy ``x >= 0``\n" + "p : array_like\n" + " Probability; must satisfy ``0 <= p < 1``\n" + "nc : array_like\n" + " Non-centrality parameter; must satisfy ``nc >= 0``\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "df : scalar or ndarray\n" + " Degrees of freedom\n" + "\n" + "See Also\n" + "--------\n" + "chndtr, chndtrix, chndtrinc") +ufunc_chndtridf_loops[0] = loop_d_ddd__As_fff_f +ufunc_chndtridf_loops[1] = loop_d_ddd__As_ddd_d +ufunc_chndtridf_types[0] = NPY_FLOAT +ufunc_chndtridf_types[1] = NPY_FLOAT +ufunc_chndtridf_types[2] = NPY_FLOAT +ufunc_chndtridf_types[3] = NPY_FLOAT +ufunc_chndtridf_types[4] = NPY_DOUBLE +ufunc_chndtridf_types[5] = NPY_DOUBLE +ufunc_chndtridf_types[6] = NPY_DOUBLE +ufunc_chndtridf_types[7] = NPY_DOUBLE +ufunc_chndtridf_ptr[2*0] = _func_chndtridf +ufunc_chndtridf_ptr[2*0+1] = ("chndtridf") +ufunc_chndtridf_ptr[2*1] = _func_chndtridf +ufunc_chndtridf_ptr[2*1+1] = ("chndtridf") +ufunc_chndtridf_data[0] = &ufunc_chndtridf_ptr[2*0] +ufunc_chndtridf_data[1] = &ufunc_chndtridf_ptr[2*1] +chndtridf = np.PyUFunc_FromFuncAndData(ufunc_chndtridf_loops, ufunc_chndtridf_data, ufunc_chndtridf_types, 2, 3, 1, 0, "chndtridf", ufunc_chndtridf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chndtrinc_loops[2] +cdef void *ufunc_chndtrinc_ptr[4] +cdef void *ufunc_chndtrinc_data[2] +cdef char ufunc_chndtrinc_types[8] +cdef char *ufunc_chndtrinc_doc = ( + "chndtrinc(x, df, p, out=None)\n" + "\n" + "Inverse to `chndtr` vs `nc`\n" + "\n" + "Calculated using a search to find a value for `df` that produces the\n" + "desired value of `p`.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Upper bound of the integral; must satisfy ``x >= 0``\n" + "df : array_like\n" + " Degrees of freedom; must satisfy ``df > 0``\n" + "p : array_like\n" + " Probability; must satisfy ``0 <= p < 1``\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "nc : scalar or ndarray\n" + " Non-centrality\n" + "\n" + "See Also\n" + "--------\n" + "chndtr, chndtrix, chndtrinc") +ufunc_chndtrinc_loops[0] = loop_d_ddd__As_fff_f +ufunc_chndtrinc_loops[1] = loop_d_ddd__As_ddd_d +ufunc_chndtrinc_types[0] = NPY_FLOAT +ufunc_chndtrinc_types[1] = NPY_FLOAT +ufunc_chndtrinc_types[2] = NPY_FLOAT +ufunc_chndtrinc_types[3] = NPY_FLOAT +ufunc_chndtrinc_types[4] = NPY_DOUBLE +ufunc_chndtrinc_types[5] = NPY_DOUBLE +ufunc_chndtrinc_types[6] = NPY_DOUBLE +ufunc_chndtrinc_types[7] = NPY_DOUBLE +ufunc_chndtrinc_ptr[2*0] = _func_chndtrinc +ufunc_chndtrinc_ptr[2*0+1] = ("chndtrinc") +ufunc_chndtrinc_ptr[2*1] = _func_chndtrinc +ufunc_chndtrinc_ptr[2*1+1] = ("chndtrinc") +ufunc_chndtrinc_data[0] = &ufunc_chndtrinc_ptr[2*0] +ufunc_chndtrinc_data[1] = &ufunc_chndtrinc_ptr[2*1] +chndtrinc = np.PyUFunc_FromFuncAndData(ufunc_chndtrinc_loops, ufunc_chndtrinc_data, ufunc_chndtrinc_types, 2, 3, 1, 0, "chndtrinc", ufunc_chndtrinc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_chndtrix_loops[2] +cdef void *ufunc_chndtrix_ptr[4] +cdef void *ufunc_chndtrix_data[2] +cdef char ufunc_chndtrix_types[8] +cdef char *ufunc_chndtrix_doc = ( + "chndtrix(p, df, nc, out=None)\n" + "\n" + "Inverse to `chndtr` vs `x`\n" + "\n" + "Calculated using a search to find a value for `x` that produces the\n" + "desired value of `p`.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probability; must satisfy ``0 <= p < 1``\n" + "df : array_like\n" + " Degrees of freedom; must satisfy ``df > 0``\n" + "nc : array_like\n" + " Non-centrality parameter; must satisfy ``nc >= 0``\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " Value so that the probability a non-central Chi square random variable\n" + " with `df` degrees of freedom and non-centrality, `nc`, is greater than\n" + " `x` equals `p`.\n" + "\n" + "See Also\n" + "--------\n" + "chndtr, chndtridf, chndtrinc") +ufunc_chndtrix_loops[0] = loop_d_ddd__As_fff_f +ufunc_chndtrix_loops[1] = loop_d_ddd__As_ddd_d +ufunc_chndtrix_types[0] = NPY_FLOAT +ufunc_chndtrix_types[1] = NPY_FLOAT +ufunc_chndtrix_types[2] = NPY_FLOAT +ufunc_chndtrix_types[3] = NPY_FLOAT +ufunc_chndtrix_types[4] = NPY_DOUBLE +ufunc_chndtrix_types[5] = NPY_DOUBLE +ufunc_chndtrix_types[6] = NPY_DOUBLE +ufunc_chndtrix_types[7] = NPY_DOUBLE +ufunc_chndtrix_ptr[2*0] = _func_chndtrix +ufunc_chndtrix_ptr[2*0+1] = ("chndtrix") +ufunc_chndtrix_ptr[2*1] = _func_chndtrix +ufunc_chndtrix_ptr[2*1+1] = ("chndtrix") +ufunc_chndtrix_data[0] = &ufunc_chndtrix_ptr[2*0] +ufunc_chndtrix_data[1] = &ufunc_chndtrix_ptr[2*1] +chndtrix = np.PyUFunc_FromFuncAndData(ufunc_chndtrix_loops, ufunc_chndtrix_data, ufunc_chndtrix_types, 2, 3, 1, 0, "chndtrix", ufunc_chndtrix_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_dawsn_loops[4] +cdef void *ufunc_dawsn_ptr[8] +cdef void *ufunc_dawsn_data[4] +cdef char ufunc_dawsn_types[8] +cdef char *ufunc_dawsn_doc = ( + "dawsn(x, out=None)\n" + "\n" + "Dawson's integral.\n" + "\n" + "Computes::\n" + "\n" + " exp(-x**2) * integral(exp(t**2), t=0..x).\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Function parameter.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "y : scalar or ndarray\n" + " Value of the integral.\n" + "\n" + "See Also\n" + "--------\n" + "wofz, erf, erfc, erfcx, erfi\n" + "\n" + "References\n" + "----------\n" + ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n" + " http://ab-initio.mit.edu/Faddeeva\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(-15, 15, num=1000)\n" + ">>> plt.plot(x, special.dawsn(x))\n" + ">>> plt.xlabel('$x$')\n" + ">>> plt.ylabel('$dawsn(x)$')\n" + ">>> plt.show()") +ufunc_dawsn_loops[0] = loop_d_d__As_f_f +ufunc_dawsn_loops[1] = loop_d_d__As_d_d +ufunc_dawsn_loops[2] = loop_D_D__As_F_F +ufunc_dawsn_loops[3] = loop_D_D__As_D_D +ufunc_dawsn_types[0] = NPY_FLOAT +ufunc_dawsn_types[1] = NPY_FLOAT +ufunc_dawsn_types[2] = NPY_DOUBLE +ufunc_dawsn_types[3] = NPY_DOUBLE +ufunc_dawsn_types[4] = NPY_CFLOAT +ufunc_dawsn_types[5] = NPY_CFLOAT +ufunc_dawsn_types[6] = NPY_CDOUBLE +ufunc_dawsn_types[7] = NPY_CDOUBLE +ufunc_dawsn_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn +ufunc_dawsn_ptr[2*0+1] = ("dawsn") +ufunc_dawsn_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn +ufunc_dawsn_ptr[2*1+1] = ("dawsn") +ufunc_dawsn_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex +ufunc_dawsn_ptr[2*2+1] = ("dawsn") +ufunc_dawsn_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex +ufunc_dawsn_ptr[2*3+1] = ("dawsn") +ufunc_dawsn_data[0] = &ufunc_dawsn_ptr[2*0] +ufunc_dawsn_data[1] = &ufunc_dawsn_ptr[2*1] +ufunc_dawsn_data[2] = &ufunc_dawsn_ptr[2*2] +ufunc_dawsn_data[3] = &ufunc_dawsn_ptr[2*3] +dawsn = np.PyUFunc_FromFuncAndData(ufunc_dawsn_loops, ufunc_dawsn_data, ufunc_dawsn_types, 4, 1, 1, 0, "dawsn", ufunc_dawsn_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_elliprc_loops[4] +cdef void *ufunc_elliprc_ptr[8] +cdef void *ufunc_elliprc_data[4] +cdef char ufunc_elliprc_types[12] +cdef char *ufunc_elliprc_doc = ( + "elliprc(x, y, out=None)\n" + "\n" + "Degenerate symmetric elliptic integral.\n" + "\n" + "The function RC is defined as [1]_\n" + "\n" + ".. math::\n" + "\n" + " R_{\\mathrm{C}}(x, y) =\n" + " \\frac{1}{2} \\int_0^{+\\infty} (t + x)^{-1/2} (t + y)^{-1} dt\n" + " = R_{\\mathrm{F}}(x, y, y)\n" + "\n" + "Parameters\n" + "----------\n" + "x, y : array_like\n" + " Real or complex input parameters. `x` can be any number in the\n" + " complex plane cut along the negative real axis. `y` must be non-zero.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "R : scalar or ndarray\n" + " Value of the integral. If `y` is real and negative, the Cauchy\n" + " principal value is returned. If both of `x` and `y` are real, the\n" + " return value is real. Otherwise, the return value is complex.\n" + "\n" + "See Also\n" + "--------\n" + "elliprf : Completely-symmetric elliptic integral of the first kind.\n" + "elliprd : Symmetric elliptic integral of the second kind.\n" + "elliprg : Completely-symmetric elliptic integral of the second kind.\n" + "elliprj : Symmetric elliptic integral of the third kind.\n" + "\n" + "Notes\n" + "-----\n" + "RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) ==\n" + "elliprf(x, y, y)``. It is an elementary function rather than an elliptic\n" + "integral.\n" + "\n" + "The code implements Carlson's algorithm based on the duplication theorems\n" + "and series expansion up to the 7th order. [2]_\n" + "\n" + ".. versionadded:: 1.8.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n" + " Functions,\" NIST, US Dept. of Commerce.\n" + " https://dlmf.nist.gov/19.16.E6\n" + ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n" + " integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n" + " https://arxiv.org/abs/math/9409227\n" + " https://doi.org/10.1007/BF02198293\n" + "\n" + "Examples\n" + "--------\n" + "Basic homogeneity property:\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import elliprc\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> y = 5.\n" + ">>> scale = 0.3 + 0.4j\n" + ">>> elliprc(scale*x, scale*y)\n" + "(0.5484493976710874-0.4169557678995833j)\n" + "\n" + ">>> elliprc(x, y)/np.sqrt(scale)\n" + "(0.5484493976710874-0.41695576789958333j)\n" + "\n" + "When the two arguments coincide, the integral is particularly\n" + "simple:\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> elliprc(x, x)\n" + "(0.4299173120614631-0.3041729818745595j)\n" + "\n" + ">>> 1/np.sqrt(x)\n" + "(0.4299173120614631-0.30417298187455954j)\n" + "\n" + "Another simple case: the first argument vanishes:\n" + "\n" + ">>> y = 1.2 + 3.4j\n" + ">>> elliprc(0, y)\n" + "(0.6753125346116815-0.47779380263880866j)\n" + "\n" + ">>> np.pi/2/np.sqrt(y)\n" + "(0.6753125346116815-0.4777938026388088j)\n" + "\n" + "When `x` and `y` are both positive, we can express\n" + ":math:`R_C(x,y)` in terms of more elementary functions. For the\n" + "case :math:`0 \\le x < y`,\n" + "\n" + ">>> x = 3.2\n" + ">>> y = 6.\n" + ">>> elliprc(x, y)\n" + "0.44942991498453444\n" + "\n" + ">>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x)\n" + "0.44942991498453433\n" + "\n" + "And for the case :math:`0 \\le y < x`,\n" + "\n" + ">>> x = 6.\n" + ">>> y = 3.2\n" + ">>> elliprc(x,y)\n" + "0.4989837501576147\n" + "\n" + ">>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y)\n" + "0.49898375015761476") +ufunc_elliprc_loops[0] = loop_d_dd__As_ff_f +ufunc_elliprc_loops[1] = loop_d_dd__As_dd_d +ufunc_elliprc_loops[2] = loop_D_DD__As_FF_F +ufunc_elliprc_loops[3] = loop_D_DD__As_DD_D +ufunc_elliprc_types[0] = NPY_FLOAT +ufunc_elliprc_types[1] = NPY_FLOAT +ufunc_elliprc_types[2] = NPY_FLOAT +ufunc_elliprc_types[3] = NPY_DOUBLE +ufunc_elliprc_types[4] = NPY_DOUBLE +ufunc_elliprc_types[5] = NPY_DOUBLE +ufunc_elliprc_types[6] = NPY_CFLOAT +ufunc_elliprc_types[7] = NPY_CFLOAT +ufunc_elliprc_types[8] = NPY_CFLOAT +ufunc_elliprc_types[9] = NPY_CDOUBLE +ufunc_elliprc_types[10] = NPY_CDOUBLE +ufunc_elliprc_types[11] = NPY_CDOUBLE +ufunc_elliprc_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RC +ufunc_elliprc_ptr[2*0+1] = ("elliprc") +ufunc_elliprc_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RC +ufunc_elliprc_ptr[2*1+1] = ("elliprc") +ufunc_elliprc_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RC +ufunc_elliprc_ptr[2*2+1] = ("elliprc") +ufunc_elliprc_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RC +ufunc_elliprc_ptr[2*3+1] = ("elliprc") +ufunc_elliprc_data[0] = &ufunc_elliprc_ptr[2*0] +ufunc_elliprc_data[1] = &ufunc_elliprc_ptr[2*1] +ufunc_elliprc_data[2] = &ufunc_elliprc_ptr[2*2] +ufunc_elliprc_data[3] = &ufunc_elliprc_ptr[2*3] +elliprc = np.PyUFunc_FromFuncAndData(ufunc_elliprc_loops, ufunc_elliprc_data, ufunc_elliprc_types, 4, 2, 1, 0, "elliprc", ufunc_elliprc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_elliprd_loops[4] +cdef void *ufunc_elliprd_ptr[8] +cdef void *ufunc_elliprd_data[4] +cdef char ufunc_elliprd_types[16] +cdef char *ufunc_elliprd_doc = ( + "elliprd(x, y, z, out=None)\n" + "\n" + "Symmetric elliptic integral of the second kind.\n" + "\n" + "The function RD is defined as [1]_\n" + "\n" + ".. math::\n" + "\n" + " R_{\\mathrm{D}}(x, y, z) =\n" + " \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2}\n" + " dt\n" + "\n" + "Parameters\n" + "----------\n" + "x, y, z : array_like\n" + " Real or complex input parameters. `x` or `y` can be any number in the\n" + " complex plane cut along the negative real axis, but at most one of them\n" + " can be zero, while `z` must be non-zero.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "R : scalar or ndarray\n" + " Value of the integral. If all of `x`, `y`, and `z` are real, the\n" + " return value is real. Otherwise, the return value is complex.\n" + "\n" + "See Also\n" + "--------\n" + "elliprc : Degenerate symmetric elliptic integral.\n" + "elliprf : Completely-symmetric elliptic integral of the first kind.\n" + "elliprg : Completely-symmetric elliptic integral of the second kind.\n" + "elliprj : Symmetric elliptic integral of the third kind.\n" + "\n" + "Notes\n" + "-----\n" + "RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) ==\n" + "elliprj(x, y, z, z)``.\n" + "\n" + "The code implements Carlson's algorithm based on the duplication theorems\n" + "and series expansion up to the 7th order. [2]_\n" + "\n" + ".. versionadded:: 1.8.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n" + " Functions,\" NIST, US Dept. of Commerce.\n" + " https://dlmf.nist.gov/19.16.E5\n" + ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n" + " integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n" + " https://arxiv.org/abs/math/9409227\n" + " https://doi.org/10.1007/BF02198293\n" + "\n" + "Examples\n" + "--------\n" + "Basic homogeneity property:\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import elliprd\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> y = 5.\n" + ">>> z = 6.\n" + ">>> scale = 0.3 + 0.4j\n" + ">>> elliprd(scale*x, scale*y, scale*z)\n" + "(-0.03703043835680379-0.24500934665683802j)\n" + "\n" + ">>> elliprd(x, y, z)*np.power(scale, -1.5)\n" + "(-0.0370304383568038-0.24500934665683805j)\n" + "\n" + "All three arguments coincide:\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> elliprd(x, x, x)\n" + "(-0.03986825876151896-0.14051741840449586j)\n" + "\n" + ">>> np.power(x, -1.5)\n" + "(-0.03986825876151894-0.14051741840449583j)\n" + "\n" + "The so-called \"second lemniscate constant\":\n" + "\n" + ">>> elliprd(0, 2, 1)/3\n" + "0.5990701173677961\n" + "\n" + ">>> from scipy.special import gamma\n" + ">>> gamma(0.75)**2/np.sqrt(2*np.pi)\n" + "0.5990701173677959") +ufunc_elliprd_loops[0] = loop_d_ddd__As_fff_f +ufunc_elliprd_loops[1] = loop_d_ddd__As_ddd_d +ufunc_elliprd_loops[2] = loop_D_DDD__As_FFF_F +ufunc_elliprd_loops[3] = loop_D_DDD__As_DDD_D +ufunc_elliprd_types[0] = NPY_FLOAT +ufunc_elliprd_types[1] = NPY_FLOAT +ufunc_elliprd_types[2] = NPY_FLOAT +ufunc_elliprd_types[3] = NPY_FLOAT +ufunc_elliprd_types[4] = NPY_DOUBLE +ufunc_elliprd_types[5] = NPY_DOUBLE +ufunc_elliprd_types[6] = NPY_DOUBLE +ufunc_elliprd_types[7] = NPY_DOUBLE +ufunc_elliprd_types[8] = NPY_CFLOAT +ufunc_elliprd_types[9] = NPY_CFLOAT +ufunc_elliprd_types[10] = NPY_CFLOAT +ufunc_elliprd_types[11] = NPY_CFLOAT +ufunc_elliprd_types[12] = NPY_CDOUBLE +ufunc_elliprd_types[13] = NPY_CDOUBLE +ufunc_elliprd_types[14] = NPY_CDOUBLE +ufunc_elliprd_types[15] = NPY_CDOUBLE +ufunc_elliprd_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RD +ufunc_elliprd_ptr[2*0+1] = ("elliprd") +ufunc_elliprd_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RD +ufunc_elliprd_ptr[2*1+1] = ("elliprd") +ufunc_elliprd_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RD +ufunc_elliprd_ptr[2*2+1] = ("elliprd") +ufunc_elliprd_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RD +ufunc_elliprd_ptr[2*3+1] = ("elliprd") +ufunc_elliprd_data[0] = &ufunc_elliprd_ptr[2*0] +ufunc_elliprd_data[1] = &ufunc_elliprd_ptr[2*1] +ufunc_elliprd_data[2] = &ufunc_elliprd_ptr[2*2] +ufunc_elliprd_data[3] = &ufunc_elliprd_ptr[2*3] +elliprd = np.PyUFunc_FromFuncAndData(ufunc_elliprd_loops, ufunc_elliprd_data, ufunc_elliprd_types, 4, 3, 1, 0, "elliprd", ufunc_elliprd_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_elliprf_loops[4] +cdef void *ufunc_elliprf_ptr[8] +cdef void *ufunc_elliprf_data[4] +cdef char ufunc_elliprf_types[16] +cdef char *ufunc_elliprf_doc = ( + "elliprf(x, y, z, out=None)\n" + "\n" + "Completely-symmetric elliptic integral of the first kind.\n" + "\n" + "The function RF is defined as [1]_\n" + "\n" + ".. math::\n" + "\n" + " R_{\\mathrm{F}}(x, y, z) =\n" + " \\frac{1}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt\n" + "\n" + "Parameters\n" + "----------\n" + "x, y, z : array_like\n" + " Real or complex input parameters. `x`, `y`, or `z` can be any number in\n" + " the complex plane cut along the negative real axis, but at most one of\n" + " them can be zero.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "R : scalar or ndarray\n" + " Value of the integral. If all of `x`, `y`, and `z` are real, the return\n" + " value is real. Otherwise, the return value is complex.\n" + "\n" + "See Also\n" + "--------\n" + "elliprc : Degenerate symmetric integral.\n" + "elliprd : Symmetric elliptic integral of the second kind.\n" + "elliprg : Completely-symmetric elliptic integral of the second kind.\n" + "elliprj : Symmetric elliptic integral of the third kind.\n" + "\n" + "Notes\n" + "-----\n" + "The code implements Carlson's algorithm based on the duplication theorems\n" + "and series expansion up to the 7th order (cf.:\n" + "https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete\n" + "integral. [2]_\n" + "\n" + ".. versionadded:: 1.8.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n" + " Functions,\" NIST, US Dept. of Commerce.\n" + " https://dlmf.nist.gov/19.16.E1\n" + ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n" + " integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n" + " https://arxiv.org/abs/math/9409227\n" + " https://doi.org/10.1007/BF02198293\n" + "\n" + "Examples\n" + "--------\n" + "Basic homogeneity property:\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import elliprf\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> y = 5.\n" + ">>> z = 6.\n" + ">>> scale = 0.3 + 0.4j\n" + ">>> elliprf(scale*x, scale*y, scale*z)\n" + "(0.5328051227278146-0.4008623567957094j)\n" + "\n" + ">>> elliprf(x, y, z)/np.sqrt(scale)\n" + "(0.5328051227278147-0.4008623567957095j)\n" + "\n" + "All three arguments coincide:\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> elliprf(x, x, x)\n" + "(0.42991731206146316-0.30417298187455954j)\n" + "\n" + ">>> 1/np.sqrt(x)\n" + "(0.4299173120614631-0.30417298187455954j)\n" + "\n" + "The so-called \"first lemniscate constant\":\n" + "\n" + ">>> elliprf(0, 1, 2)\n" + "1.3110287771460598\n" + "\n" + ">>> from scipy.special import gamma\n" + ">>> gamma(0.25)**2/(4*np.sqrt(2*np.pi))\n" + "1.3110287771460598") +ufunc_elliprf_loops[0] = loop_d_ddd__As_fff_f +ufunc_elliprf_loops[1] = loop_d_ddd__As_ddd_d +ufunc_elliprf_loops[2] = loop_D_DDD__As_FFF_F +ufunc_elliprf_loops[3] = loop_D_DDD__As_DDD_D +ufunc_elliprf_types[0] = NPY_FLOAT +ufunc_elliprf_types[1] = NPY_FLOAT +ufunc_elliprf_types[2] = NPY_FLOAT +ufunc_elliprf_types[3] = NPY_FLOAT +ufunc_elliprf_types[4] = NPY_DOUBLE +ufunc_elliprf_types[5] = NPY_DOUBLE +ufunc_elliprf_types[6] = NPY_DOUBLE +ufunc_elliprf_types[7] = NPY_DOUBLE +ufunc_elliprf_types[8] = NPY_CFLOAT +ufunc_elliprf_types[9] = NPY_CFLOAT +ufunc_elliprf_types[10] = NPY_CFLOAT +ufunc_elliprf_types[11] = NPY_CFLOAT +ufunc_elliprf_types[12] = NPY_CDOUBLE +ufunc_elliprf_types[13] = NPY_CDOUBLE +ufunc_elliprf_types[14] = NPY_CDOUBLE +ufunc_elliprf_types[15] = NPY_CDOUBLE +ufunc_elliprf_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RF +ufunc_elliprf_ptr[2*0+1] = ("elliprf") +ufunc_elliprf_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RF +ufunc_elliprf_ptr[2*1+1] = ("elliprf") +ufunc_elliprf_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RF +ufunc_elliprf_ptr[2*2+1] = ("elliprf") +ufunc_elliprf_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RF +ufunc_elliprf_ptr[2*3+1] = ("elliprf") +ufunc_elliprf_data[0] = &ufunc_elliprf_ptr[2*0] +ufunc_elliprf_data[1] = &ufunc_elliprf_ptr[2*1] +ufunc_elliprf_data[2] = &ufunc_elliprf_ptr[2*2] +ufunc_elliprf_data[3] = &ufunc_elliprf_ptr[2*3] +elliprf = np.PyUFunc_FromFuncAndData(ufunc_elliprf_loops, ufunc_elliprf_data, ufunc_elliprf_types, 4, 3, 1, 0, "elliprf", ufunc_elliprf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_elliprg_loops[4] +cdef void *ufunc_elliprg_ptr[8] +cdef void *ufunc_elliprg_data[4] +cdef char ufunc_elliprg_types[16] +cdef char *ufunc_elliprg_doc = ( + "elliprg(x, y, z, out=None)\n" + "\n" + "Completely-symmetric elliptic integral of the second kind.\n" + "\n" + "The function RG is defined as [1]_\n" + "\n" + ".. math::\n" + "\n" + " R_{\\mathrm{G}}(x, y, z) =\n" + " \\frac{1}{4} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n" + " \\left(\\frac{x}{t + x} + \\frac{y}{t + y} + \\frac{z}{t + z}\\right) t\n" + " dt\n" + "\n" + "Parameters\n" + "----------\n" + "x, y, z : array_like\n" + " Real or complex input parameters. `x`, `y`, or `z` can be any number in\n" + " the complex plane cut along the negative real axis.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "R : scalar or ndarray\n" + " Value of the integral. If all of `x`, `y`, and `z` are real, the return\n" + " value is real. Otherwise, the return value is complex.\n" + "\n" + "See Also\n" + "--------\n" + "elliprc : Degenerate symmetric integral.\n" + "elliprd : Symmetric elliptic integral of the second kind.\n" + "elliprf : Completely-symmetric elliptic integral of the first kind.\n" + "elliprj : Symmetric elliptic integral of the third kind.\n" + "\n" + "Notes\n" + "-----\n" + "The implementation uses the relation [1]_\n" + "\n" + ".. math::\n" + "\n" + " 2 R_{\\mathrm{G}}(x, y, z) =\n" + " z R_{\\mathrm{F}}(x, y, z) -\n" + " \\frac{1}{3} (x - z) (y - z) R_{\\mathrm{D}}(x, y, z) +\n" + " \\sqrt{\\frac{x y}{z}}\n" + "\n" + "and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can\n" + "be chosen as the pivot. When one of the arguments is close to zero, the AGM\n" + "method is applied instead. Other special cases are computed following Ref.\n" + "[2]_\n" + "\n" + ".. versionadded:: 1.8.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n" + " integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n" + " https://arxiv.org/abs/math/9409227\n" + " https://doi.org/10.1007/BF02198293\n" + ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n" + " Functions,\" NIST, US Dept. of Commerce.\n" + " https://dlmf.nist.gov/19.16.E1\n" + " https://dlmf.nist.gov/19.20.ii\n" + "\n" + "Examples\n" + "--------\n" + "Basic homogeneity property:\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import elliprg\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> y = 5.\n" + ">>> z = 6.\n" + ">>> scale = 0.3 + 0.4j\n" + ">>> elliprg(scale*x, scale*y, scale*z)\n" + "(1.195936862005246+0.8470988320464167j)\n" + "\n" + ">>> elliprg(x, y, z)*np.sqrt(scale)\n" + "(1.195936862005246+0.8470988320464165j)\n" + "\n" + "Simplifications:\n" + "\n" + ">>> elliprg(0, y, y)\n" + "1.756203682760182\n" + "\n" + ">>> 0.25*np.pi*np.sqrt(y)\n" + "1.7562036827601817\n" + "\n" + ">>> elliprg(0, 0, z)\n" + "1.224744871391589\n" + "\n" + ">>> 0.5*np.sqrt(z)\n" + "1.224744871391589\n" + "\n" + "The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and\n" + "``c`` is given by\n" + "\n" + ".. math::\n" + "\n" + " S = 4 \\pi a b c R_{\\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2).\n" + "\n" + ">>> def ellipsoid_area(a, b, c):\n" + "... r = 4.0 * np.pi * a * b * c\n" + "... return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c))\n" + ">>> print(ellipsoid_area(1, 3, 5))\n" + "108.62688289491807") +ufunc_elliprg_loops[0] = loop_d_ddd__As_fff_f +ufunc_elliprg_loops[1] = loop_d_ddd__As_ddd_d +ufunc_elliprg_loops[2] = loop_D_DDD__As_FFF_F +ufunc_elliprg_loops[3] = loop_D_DDD__As_DDD_D +ufunc_elliprg_types[0] = NPY_FLOAT +ufunc_elliprg_types[1] = NPY_FLOAT +ufunc_elliprg_types[2] = NPY_FLOAT +ufunc_elliprg_types[3] = NPY_FLOAT +ufunc_elliprg_types[4] = NPY_DOUBLE +ufunc_elliprg_types[5] = NPY_DOUBLE +ufunc_elliprg_types[6] = NPY_DOUBLE +ufunc_elliprg_types[7] = NPY_DOUBLE +ufunc_elliprg_types[8] = NPY_CFLOAT +ufunc_elliprg_types[9] = NPY_CFLOAT +ufunc_elliprg_types[10] = NPY_CFLOAT +ufunc_elliprg_types[11] = NPY_CFLOAT +ufunc_elliprg_types[12] = NPY_CDOUBLE +ufunc_elliprg_types[13] = NPY_CDOUBLE +ufunc_elliprg_types[14] = NPY_CDOUBLE +ufunc_elliprg_types[15] = NPY_CDOUBLE +ufunc_elliprg_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RG +ufunc_elliprg_ptr[2*0+1] = ("elliprg") +ufunc_elliprg_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RG +ufunc_elliprg_ptr[2*1+1] = ("elliprg") +ufunc_elliprg_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RG +ufunc_elliprg_ptr[2*2+1] = ("elliprg") +ufunc_elliprg_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RG +ufunc_elliprg_ptr[2*3+1] = ("elliprg") +ufunc_elliprg_data[0] = &ufunc_elliprg_ptr[2*0] +ufunc_elliprg_data[1] = &ufunc_elliprg_ptr[2*1] +ufunc_elliprg_data[2] = &ufunc_elliprg_ptr[2*2] +ufunc_elliprg_data[3] = &ufunc_elliprg_ptr[2*3] +elliprg = np.PyUFunc_FromFuncAndData(ufunc_elliprg_loops, ufunc_elliprg_data, ufunc_elliprg_types, 4, 3, 1, 0, "elliprg", ufunc_elliprg_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_elliprj_loops[4] +cdef void *ufunc_elliprj_ptr[8] +cdef void *ufunc_elliprj_data[4] +cdef char ufunc_elliprj_types[20] +cdef char *ufunc_elliprj_doc = ( + "elliprj(x, y, z, p, out=None)\n" + "\n" + "Symmetric elliptic integral of the third kind.\n" + "\n" + "The function RJ is defined as [1]_\n" + "\n" + ".. math::\n" + "\n" + " R_{\\mathrm{J}}(x, y, z, p) =\n" + " \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n" + " (t + p)^{-1} dt\n" + "\n" + ".. warning::\n" + " This function should be considered experimental when the inputs are\n" + " unbalanced. Check correctness with another independent implementation.\n" + "\n" + "Parameters\n" + "----------\n" + "x, y, z, p : array_like\n" + " Real or complex input parameters. `x`, `y`, or `z` are numbers in\n" + " the complex plane cut along the negative real axis (subject to further\n" + " constraints, see Notes), and at most one of them can be zero. `p` must\n" + " be non-zero.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "R : scalar or ndarray\n" + " Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the\n" + " return value is real. Otherwise, the return value is complex.\n" + "\n" + " If `p` is real and negative, while `x`, `y`, and `z` are real,\n" + " non-negative, and at most one of them is zero, the Cauchy principal\n" + " value is returned. [1]_ [2]_\n" + "\n" + "See Also\n" + "--------\n" + "elliprc : Degenerate symmetric integral.\n" + "elliprd : Symmetric elliptic integral of the second kind.\n" + "elliprf : Completely-symmetric elliptic integral of the first kind.\n" + "elliprg : Completely-symmetric elliptic integral of the second kind.\n" + "\n" + "Notes\n" + "-----\n" + "The code implements Carlson's algorithm based on the duplication theorems\n" + "and series expansion up to the 7th order. [3]_ The algorithm is slightly\n" + "different from its earlier incarnation as it appears in [1]_, in that the\n" + "call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in\n" + "the inner loop. Asymptotic approximations are used where arguments differ\n" + "widely in the order of magnitude. [5]_\n" + "\n" + "The input values are subject to certain sufficient but not necessary\n" + "constraints when input arguments are complex. Notably, ``x``, ``y``, and\n" + "``z`` must have non-negative real parts, unless two of them are\n" + "non-negative and complex-conjugates to each other while the other is a real\n" + "non-negative number. [1]_ If the inputs do not satisfy the sufficient\n" + "condition described in Ref. [1]_ they are rejected outright with the output\n" + "set to NaN.\n" + "\n" + "In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the\n" + "function ``elliprd`` should be preferred because of its less restrictive\n" + "domain.\n" + "\n" + ".. versionadded:: 1.8.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n" + " integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n" + " https://arxiv.org/abs/math/9409227\n" + " https://doi.org/10.1007/BF02198293\n" + ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n" + " Functions,\" NIST, US Dept. of Commerce.\n" + " https://dlmf.nist.gov/19.20.iii\n" + ".. [3] B. C. Carlson, J. FitzSimmons, \"Reduction Theorems for Elliptic\n" + " Integrands with the Square Root of Two Quadratic Factors,\" J.\n" + " Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000.\n" + " https://doi.org/10.1016/S0377-0427(00)00282-X\n" + ".. [4] F. Johansson, \"Numerical Evaluation of Elliptic Functions, Elliptic\n" + " Integrals and Modular Forms,\" in J. Blumlein, C. Schneider, P.\n" + " Paule, eds., \"Elliptic Integrals, Elliptic Functions and Modular\n" + " Forms in Quantum Field Theory,\" pp. 269-293, 2019 (Cham,\n" + " Switzerland: Springer Nature Switzerland)\n" + " https://arxiv.org/abs/1806.06725\n" + " https://doi.org/10.1007/978-3-030-04480-0\n" + ".. [5] B. C. Carlson, J. L. Gustafson, \"Asymptotic Approximations for\n" + " Symmetric Elliptic Integrals,\" SIAM J. Math. Anls., vol. 25, no. 2,\n" + " pp. 288-303, 1994.\n" + " https://arxiv.org/abs/math/9310223\n" + " https://doi.org/10.1137/S0036141092228477\n" + "\n" + "Examples\n" + "--------\n" + "Basic homogeneity property:\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import elliprj\n" + "\n" + ">>> x = 1.2 + 3.4j\n" + ">>> y = 5.\n" + ">>> z = 6.\n" + ">>> p = 7.\n" + ">>> scale = 0.3 - 0.4j\n" + ">>> elliprj(scale*x, scale*y, scale*z, scale*p)\n" + "(0.10834905565679157+0.19694950747103812j)\n" + "\n" + ">>> elliprj(x, y, z, p)*np.power(scale, -1.5)\n" + "(0.10834905565679556+0.19694950747103854j)\n" + "\n" + "Reduction to simpler elliptic integral:\n" + "\n" + ">>> elliprj(x, y, z, z)\n" + "(0.08288462362195129-0.028376809745123258j)\n" + "\n" + ">>> from scipy.special import elliprd\n" + ">>> elliprd(x, y, z)\n" + "(0.08288462362195136-0.028376809745123296j)\n" + "\n" + "All arguments coincide:\n" + "\n" + ">>> elliprj(x, x, x, x)\n" + "(-0.03986825876151896-0.14051741840449586j)\n" + "\n" + ">>> np.power(x, -1.5)\n" + "(-0.03986825876151894-0.14051741840449583j)") +ufunc_elliprj_loops[0] = loop_d_dddd__As_ffff_f +ufunc_elliprj_loops[1] = loop_d_dddd__As_dddd_d +ufunc_elliprj_loops[2] = loop_D_DDDD__As_FFFF_F +ufunc_elliprj_loops[3] = loop_D_DDDD__As_DDDD_D +ufunc_elliprj_types[0] = NPY_FLOAT +ufunc_elliprj_types[1] = NPY_FLOAT +ufunc_elliprj_types[2] = NPY_FLOAT +ufunc_elliprj_types[3] = NPY_FLOAT +ufunc_elliprj_types[4] = NPY_FLOAT +ufunc_elliprj_types[5] = NPY_DOUBLE +ufunc_elliprj_types[6] = NPY_DOUBLE +ufunc_elliprj_types[7] = NPY_DOUBLE +ufunc_elliprj_types[8] = NPY_DOUBLE +ufunc_elliprj_types[9] = NPY_DOUBLE +ufunc_elliprj_types[10] = NPY_CFLOAT +ufunc_elliprj_types[11] = NPY_CFLOAT +ufunc_elliprj_types[12] = NPY_CFLOAT +ufunc_elliprj_types[13] = NPY_CFLOAT +ufunc_elliprj_types[14] = NPY_CFLOAT +ufunc_elliprj_types[15] = NPY_CDOUBLE +ufunc_elliprj_types[16] = NPY_CDOUBLE +ufunc_elliprj_types[17] = NPY_CDOUBLE +ufunc_elliprj_types[18] = NPY_CDOUBLE +ufunc_elliprj_types[19] = NPY_CDOUBLE +ufunc_elliprj_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RJ +ufunc_elliprj_ptr[2*0+1] = ("elliprj") +ufunc_elliprj_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RJ +ufunc_elliprj_ptr[2*1+1] = ("elliprj") +ufunc_elliprj_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RJ +ufunc_elliprj_ptr[2*2+1] = ("elliprj") +ufunc_elliprj_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RJ +ufunc_elliprj_ptr[2*3+1] = ("elliprj") +ufunc_elliprj_data[0] = &ufunc_elliprj_ptr[2*0] +ufunc_elliprj_data[1] = &ufunc_elliprj_ptr[2*1] +ufunc_elliprj_data[2] = &ufunc_elliprj_ptr[2*2] +ufunc_elliprj_data[3] = &ufunc_elliprj_ptr[2*3] +elliprj = np.PyUFunc_FromFuncAndData(ufunc_elliprj_loops, ufunc_elliprj_data, ufunc_elliprj_types, 4, 4, 1, 0, "elliprj", ufunc_elliprj_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_entr_loops[2] +cdef void *ufunc_entr_ptr[4] +cdef void *ufunc_entr_data[2] +cdef char ufunc_entr_types[4] +cdef char *ufunc_entr_doc = ( + "entr(x, out=None)\n" + "\n" + "Elementwise function for computing entropy.\n" + "\n" + ".. math:: \\text{entr}(x) = \\begin{cases} - x \\log(x) & x > 0 \\\\ 0 & x = 0\n" + " \\\\ -\\infty & \\text{otherwise} \\end{cases}\n" + "\n" + "Parameters\n" + "----------\n" + "x : ndarray\n" + " Input array.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "res : scalar or ndarray\n" + " The value of the elementwise entropy function at the given points `x`.\n" + "\n" + "See Also\n" + "--------\n" + "kl_div, rel_entr, scipy.stats.entropy\n" + "\n" + "Notes\n" + "-----\n" + ".. versionadded:: 0.15.0\n" + "\n" + "This function is concave.\n" + "\n" + "The origin of this function is in convex programming; see [1]_.\n" + "Given a probability distribution :math:`p_1, \\ldots, p_n`,\n" + "the definition of entropy in the context of *information theory* is\n" + "\n" + ".. math::\n" + "\n" + " \\sum_{i = 1}^n \\mathrm{entr}(p_i).\n" + "\n" + "To compute the latter quantity, use `scipy.stats.entropy`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n" + " Cambridge University Press, 2004.\n" + " :doi:`https://doi.org/10.1017/CBO9780511804441`") +ufunc_entr_loops[0] = loop_d_d__As_f_f +ufunc_entr_loops[1] = loop_d_d__As_d_d +ufunc_entr_types[0] = NPY_FLOAT +ufunc_entr_types[1] = NPY_FLOAT +ufunc_entr_types[2] = NPY_DOUBLE +ufunc_entr_types[3] = NPY_DOUBLE +ufunc_entr_ptr[2*0] = _func_entr +ufunc_entr_ptr[2*0+1] = ("entr") +ufunc_entr_ptr[2*1] = _func_entr +ufunc_entr_ptr[2*1+1] = ("entr") +ufunc_entr_data[0] = &ufunc_entr_ptr[2*0] +ufunc_entr_data[1] = &ufunc_entr_ptr[2*1] +entr = np.PyUFunc_FromFuncAndData(ufunc_entr_loops, ufunc_entr_data, ufunc_entr_types, 2, 1, 1, 0, "entr", ufunc_entr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_erf_loops[4] +cdef void *ufunc_erf_ptr[8] +cdef void *ufunc_erf_data[4] +cdef char ufunc_erf_types[8] +cdef char *ufunc_erf_doc = ( + "erf(z, out=None)\n" + "\n" + "Returns the error function of complex argument.\n" + "\n" + "It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : ndarray\n" + " Input array.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "res : scalar or ndarray\n" + " The values of the error function at the given points `x`.\n" + "\n" + "See Also\n" + "--------\n" + "erfc, erfinv, erfcinv, wofz, erfcx, erfi\n" + "\n" + "Notes\n" + "-----\n" + "The cumulative of the unit normal distribution is given by\n" + "``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``.\n" + "\n" + "References\n" + "----------\n" + ".. [1] https://en.wikipedia.org/wiki/Error_function\n" + ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover,\n" + " 1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm\n" + ".. [3] Steven G. Johnson, Faddeeva W function implementation.\n" + " http://ab-initio.mit.edu/Faddeeva\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(-3, 3)\n" + ">>> plt.plot(x, special.erf(x))\n" + ">>> plt.xlabel('$x$')\n" + ">>> plt.ylabel('$erf(x)$')\n" + ">>> plt.show()") +ufunc_erf_loops[0] = loop_d_d__As_f_f +ufunc_erf_loops[1] = loop_d_d__As_d_d +ufunc_erf_loops[2] = loop_D_D__As_F_F +ufunc_erf_loops[3] = loop_D_D__As_D_D +ufunc_erf_types[0] = NPY_FLOAT +ufunc_erf_types[1] = NPY_FLOAT +ufunc_erf_types[2] = NPY_DOUBLE +ufunc_erf_types[3] = NPY_DOUBLE +ufunc_erf_types[4] = NPY_CFLOAT +ufunc_erf_types[5] = NPY_CFLOAT +ufunc_erf_types[6] = NPY_CDOUBLE +ufunc_erf_types[7] = NPY_CDOUBLE +ufunc_erf_ptr[2*0] = _func_cephes_erf +ufunc_erf_ptr[2*0+1] = ("erf") +ufunc_erf_ptr[2*1] = _func_cephes_erf +ufunc_erf_ptr[2*1+1] = ("erf") +ufunc_erf_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erf +ufunc_erf_ptr[2*2+1] = ("erf") +ufunc_erf_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erf +ufunc_erf_ptr[2*3+1] = ("erf") +ufunc_erf_data[0] = &ufunc_erf_ptr[2*0] +ufunc_erf_data[1] = &ufunc_erf_ptr[2*1] +ufunc_erf_data[2] = &ufunc_erf_ptr[2*2] +ufunc_erf_data[3] = &ufunc_erf_ptr[2*3] +erf = np.PyUFunc_FromFuncAndData(ufunc_erf_loops, ufunc_erf_data, ufunc_erf_types, 4, 1, 1, 0, "erf", ufunc_erf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_erfc_loops[4] +cdef void *ufunc_erfc_ptr[8] +cdef void *ufunc_erfc_data[4] +cdef char ufunc_erfc_types[8] +cdef char *ufunc_erfc_doc = ( + "erfc(x, out=None)\n" + "\n" + "Complementary error function, ``1 - erf(x)``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real or complex valued argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the complementary error function\n" + "\n" + "See Also\n" + "--------\n" + "erf, erfi, erfcx, dawsn, wofz\n" + "\n" + "References\n" + "----------\n" + ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n" + " http://ab-initio.mit.edu/Faddeeva\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(-3, 3)\n" + ">>> plt.plot(x, special.erfc(x))\n" + ">>> plt.xlabel('$x$')\n" + ">>> plt.ylabel('$erfc(x)$')\n" + ">>> plt.show()") +ufunc_erfc_loops[0] = loop_d_d__As_f_f +ufunc_erfc_loops[1] = loop_d_d__As_d_d +ufunc_erfc_loops[2] = loop_D_D__As_F_F +ufunc_erfc_loops[3] = loop_D_D__As_D_D +ufunc_erfc_types[0] = NPY_FLOAT +ufunc_erfc_types[1] = NPY_FLOAT +ufunc_erfc_types[2] = NPY_DOUBLE +ufunc_erfc_types[3] = NPY_DOUBLE +ufunc_erfc_types[4] = NPY_CFLOAT +ufunc_erfc_types[5] = NPY_CFLOAT +ufunc_erfc_types[6] = NPY_CDOUBLE +ufunc_erfc_types[7] = NPY_CDOUBLE +ufunc_erfc_ptr[2*0] = _func_cephes_erfc +ufunc_erfc_ptr[2*0+1] = ("erfc") +ufunc_erfc_ptr[2*1] = _func_cephes_erfc +ufunc_erfc_ptr[2*1+1] = ("erfc") +ufunc_erfc_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex +ufunc_erfc_ptr[2*2+1] = ("erfc") +ufunc_erfc_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex +ufunc_erfc_ptr[2*3+1] = ("erfc") +ufunc_erfc_data[0] = &ufunc_erfc_ptr[2*0] +ufunc_erfc_data[1] = &ufunc_erfc_ptr[2*1] +ufunc_erfc_data[2] = &ufunc_erfc_ptr[2*2] +ufunc_erfc_data[3] = &ufunc_erfc_ptr[2*3] +erfc = np.PyUFunc_FromFuncAndData(ufunc_erfc_loops, ufunc_erfc_data, ufunc_erfc_types, 4, 1, 1, 0, "erfc", ufunc_erfc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_erfcinv_loops[2] +cdef void *ufunc_erfcinv_ptr[4] +cdef void *ufunc_erfcinv_data[2] +cdef char ufunc_erfcinv_types[4] +cdef char *ufunc_erfcinv_doc = ( + "erfcinv(y, out=None)\n" + "\n" + "Inverse of the complementary error function.\n" + "\n" + "Computes the inverse of the complementary error function.\n" + "\n" + "In the complex domain, there is no unique complex number w satisfying\n" + "erfc(w)=z. This indicates a true inverse function would be multivalued.\n" + "When the domain restricts to the real, 0 < x < 2, there is a unique real\n" + "number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).\n" + "\n" + "It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)\n" + "\n" + "Parameters\n" + "----------\n" + "y : ndarray\n" + " Argument at which to evaluate. Domain: [0, 2]\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "erfcinv : scalar or ndarray\n" + " The inverse of erfc of y, element-wise\n" + "\n" + "See Also\n" + "--------\n" + "erf : Error function of a complex argument\n" + "erfc : Complementary error function, ``1 - erf(x)``\n" + "erfinv : Inverse of the error function\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> from scipy.special import erfcinv\n" + "\n" + ">>> erfcinv(0.5)\n" + "0.4769362762044699\n" + "\n" + ">>> y = np.linspace(0.0, 2.0, num=11)\n" + ">>> erfcinv(y)\n" + "array([ inf, 0.9061938 , 0.59511608, 0.37080716, 0.17914345,\n" + " -0. , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,\n" + " -inf])\n" + "\n" + "Plot the function:\n" + "\n" + ">>> y = np.linspace(0, 2, 200)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> ax.plot(y, erfcinv(y))\n" + ">>> ax.grid(True)\n" + ">>> ax.set_xlabel('y')\n" + ">>> ax.set_title('erfcinv(y)')\n" + ">>> plt.show()") +ufunc_erfcinv_loops[0] = loop_d_d__As_f_f +ufunc_erfcinv_loops[1] = loop_d_d__As_d_d +ufunc_erfcinv_types[0] = NPY_FLOAT +ufunc_erfcinv_types[1] = NPY_FLOAT +ufunc_erfcinv_types[2] = NPY_DOUBLE +ufunc_erfcinv_types[3] = NPY_DOUBLE +ufunc_erfcinv_ptr[2*0] = _func_cephes_erfcinv +ufunc_erfcinv_ptr[2*0+1] = ("erfcinv") +ufunc_erfcinv_ptr[2*1] = _func_cephes_erfcinv +ufunc_erfcinv_ptr[2*1+1] = ("erfcinv") +ufunc_erfcinv_data[0] = &ufunc_erfcinv_ptr[2*0] +ufunc_erfcinv_data[1] = &ufunc_erfcinv_ptr[2*1] +erfcinv = np.PyUFunc_FromFuncAndData(ufunc_erfcinv_loops, ufunc_erfcinv_data, ufunc_erfcinv_types, 2, 1, 1, 0, "erfcinv", ufunc_erfcinv_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_erfcx_loops[4] +cdef void *ufunc_erfcx_ptr[8] +cdef void *ufunc_erfcx_data[4] +cdef char ufunc_erfcx_types[8] +cdef char *ufunc_erfcx_doc = ( + "erfcx(x, out=None)\n" + "\n" + "Scaled complementary error function, ``exp(x**2) * erfc(x)``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real or complex valued argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the scaled complementary error function\n" + "\n" + "\n" + "See Also\n" + "--------\n" + "erf, erfc, erfi, dawsn, wofz\n" + "\n" + "Notes\n" + "-----\n" + "\n" + ".. versionadded:: 0.12.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n" + " http://ab-initio.mit.edu/Faddeeva\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(-3, 3)\n" + ">>> plt.plot(x, special.erfcx(x))\n" + ">>> plt.xlabel('$x$')\n" + ">>> plt.ylabel('$erfcx(x)$')\n" + ">>> plt.show()") +ufunc_erfcx_loops[0] = loop_d_d__As_f_f +ufunc_erfcx_loops[1] = loop_d_d__As_d_d +ufunc_erfcx_loops[2] = loop_D_D__As_F_F +ufunc_erfcx_loops[3] = loop_D_D__As_D_D +ufunc_erfcx_types[0] = NPY_FLOAT +ufunc_erfcx_types[1] = NPY_FLOAT +ufunc_erfcx_types[2] = NPY_DOUBLE +ufunc_erfcx_types[3] = NPY_DOUBLE +ufunc_erfcx_types[4] = NPY_CFLOAT +ufunc_erfcx_types[5] = NPY_CFLOAT +ufunc_erfcx_types[6] = NPY_CDOUBLE +ufunc_erfcx_types[7] = NPY_CDOUBLE +ufunc_erfcx_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx +ufunc_erfcx_ptr[2*0+1] = ("erfcx") +ufunc_erfcx_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx +ufunc_erfcx_ptr[2*1+1] = ("erfcx") +ufunc_erfcx_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex +ufunc_erfcx_ptr[2*2+1] = ("erfcx") +ufunc_erfcx_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex +ufunc_erfcx_ptr[2*3+1] = ("erfcx") +ufunc_erfcx_data[0] = &ufunc_erfcx_ptr[2*0] +ufunc_erfcx_data[1] = &ufunc_erfcx_ptr[2*1] +ufunc_erfcx_data[2] = &ufunc_erfcx_ptr[2*2] +ufunc_erfcx_data[3] = &ufunc_erfcx_ptr[2*3] +erfcx = np.PyUFunc_FromFuncAndData(ufunc_erfcx_loops, ufunc_erfcx_data, ufunc_erfcx_types, 4, 1, 1, 0, "erfcx", ufunc_erfcx_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_erfi_loops[4] +cdef void *ufunc_erfi_ptr[8] +cdef void *ufunc_erfi_data[4] +cdef char ufunc_erfi_types[8] +cdef char *ufunc_erfi_doc = ( + "erfi(z, out=None)\n" + "\n" + "Imaginary error function, ``-i erf(i z)``.\n" + "\n" + "Parameters\n" + "----------\n" + "z : array_like\n" + " Real or complex valued argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the imaginary error function\n" + "\n" + "See Also\n" + "--------\n" + "erf, erfc, erfcx, dawsn, wofz\n" + "\n" + "Notes\n" + "-----\n" + "\n" + ".. versionadded:: 0.12.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n" + " http://ab-initio.mit.edu/Faddeeva\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(-3, 3)\n" + ">>> plt.plot(x, special.erfi(x))\n" + ">>> plt.xlabel('$x$')\n" + ">>> plt.ylabel('$erfi(x)$')\n" + ">>> plt.show()") +ufunc_erfi_loops[0] = loop_d_d__As_f_f +ufunc_erfi_loops[1] = loop_d_d__As_d_d +ufunc_erfi_loops[2] = loop_D_D__As_F_F +ufunc_erfi_loops[3] = loop_D_D__As_D_D +ufunc_erfi_types[0] = NPY_FLOAT +ufunc_erfi_types[1] = NPY_FLOAT +ufunc_erfi_types[2] = NPY_DOUBLE +ufunc_erfi_types[3] = NPY_DOUBLE +ufunc_erfi_types[4] = NPY_CFLOAT +ufunc_erfi_types[5] = NPY_CFLOAT +ufunc_erfi_types[6] = NPY_CDOUBLE +ufunc_erfi_types[7] = NPY_CDOUBLE +ufunc_erfi_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfi +ufunc_erfi_ptr[2*0+1] = ("erfi") +ufunc_erfi_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfi +ufunc_erfi_ptr[2*1+1] = ("erfi") +ufunc_erfi_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex +ufunc_erfi_ptr[2*2+1] = ("erfi") +ufunc_erfi_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex +ufunc_erfi_ptr[2*3+1] = ("erfi") +ufunc_erfi_data[0] = &ufunc_erfi_ptr[2*0] +ufunc_erfi_data[1] = &ufunc_erfi_ptr[2*1] +ufunc_erfi_data[2] = &ufunc_erfi_ptr[2*2] +ufunc_erfi_data[3] = &ufunc_erfi_ptr[2*3] +erfi = np.PyUFunc_FromFuncAndData(ufunc_erfi_loops, ufunc_erfi_data, ufunc_erfi_types, 4, 1, 1, 0, "erfi", ufunc_erfi_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_erfinv_loops[2] +cdef void *ufunc_erfinv_ptr[4] +cdef void *ufunc_erfinv_data[2] +cdef char ufunc_erfinv_types[4] +cdef char *ufunc_erfinv_doc = ( + "erfinv(y, out=None)\n" + "\n" + "Inverse of the error function.\n" + "\n" + "Computes the inverse of the error function.\n" + "\n" + "In the complex domain, there is no unique complex number w satisfying\n" + "erf(w)=z. This indicates a true inverse function would be multivalued.\n" + "When the domain restricts to the real, -1 < x < 1, there is a unique real\n" + "number satisfying erf(erfinv(x)) = x.\n" + "\n" + "Parameters\n" + "----------\n" + "y : ndarray\n" + " Argument at which to evaluate. Domain: [-1, 1]\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "erfinv : scalar or ndarray\n" + " The inverse of erf of y, element-wise\n" + "\n" + "See Also\n" + "--------\n" + "erf : Error function of a complex argument\n" + "erfc : Complementary error function, ``1 - erf(x)``\n" + "erfcinv : Inverse of the complementary error function\n" + "\n" + "Notes\n" + "-----\n" + "This function wraps the ``erf_inv`` routine from the\n" + "Boost Math C++ library [1]_.\n" + "\n" + "References\n" + "----------\n" + ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> from scipy.special import erfinv, erf\n" + "\n" + ">>> erfinv(0.5)\n" + "0.4769362762044699\n" + "\n" + ">>> y = np.linspace(-1.0, 1.0, num=9)\n" + ">>> x = erfinv(y)\n" + ">>> x\n" + "array([ -inf, -0.81341985, -0.47693628, -0.22531206, 0. ,\n" + " 0.22531206, 0.47693628, 0.81341985, inf])\n" + "\n" + "Verify that ``erf(erfinv(y))`` is ``y``.\n" + "\n" + ">>> erf(x)\n" + "array([-1. , -0.75, -0.5 , -0.25, 0. , 0.25, 0.5 , 0.75, 1. ])\n" + "\n" + "Plot the function:\n" + "\n" + ">>> y = np.linspace(-1, 1, 200)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> ax.plot(y, erfinv(y))\n" + ">>> ax.grid(True)\n" + ">>> ax.set_xlabel('y')\n" + ">>> ax.set_title('erfinv(y)')\n" + ">>> plt.show()") +ufunc_erfinv_loops[0] = loop_f_f__As_f_f +ufunc_erfinv_loops[1] = loop_d_d__As_d_d +ufunc_erfinv_types[0] = NPY_FLOAT +ufunc_erfinv_types[1] = NPY_FLOAT +ufunc_erfinv_types[2] = NPY_DOUBLE +ufunc_erfinv_types[3] = NPY_DOUBLE +ufunc_erfinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_erfinv_float +ufunc_erfinv_ptr[2*0+1] = ("erfinv") +ufunc_erfinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_erfinv_double +ufunc_erfinv_ptr[2*1+1] = ("erfinv") +ufunc_erfinv_data[0] = &ufunc_erfinv_ptr[2*0] +ufunc_erfinv_data[1] = &ufunc_erfinv_ptr[2*1] +erfinv = np.PyUFunc_FromFuncAndData(ufunc_erfinv_loops, ufunc_erfinv_data, ufunc_erfinv_types, 2, 1, 1, 0, "erfinv", ufunc_erfinv_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_chebyc_loops[5] +cdef void *ufunc_eval_chebyc_ptr[10] +cdef void *ufunc_eval_chebyc_data[5] +cdef char ufunc_eval_chebyc_types[15] +cdef char *ufunc_eval_chebyc_doc = ( + "eval_chebyc(n, x, out=None)\n" + "\n" + "Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a\n" + "point.\n" + "\n" + "These polynomials are defined as\n" + "\n" + ".. math::\n" + "\n" + " C_n(x) = 2 T_n(x/2)\n" + "\n" + "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n" + "22.5.11 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to `eval_chebyt`.\n" + "x : array_like\n" + " Points at which to evaluate the Chebyshev polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "C : scalar or ndarray\n" + " Values of the Chebyshev polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_chebyc : roots and quadrature weights of Chebyshev\n" + " polynomials of the first kind on [-2, 2]\n" + "chebyc : Chebyshev polynomial object\n" + "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n" + "eval_chebyt : evaluate Chebycshev polynomials of the first kind\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "They are a scaled version of the Chebyshev polynomials of the\n" + "first kind.\n" + "\n" + ">>> x = np.linspace(-2, 2, 6)\n" + ">>> sc.eval_chebyc(3, x)\n" + "array([-2. , 1.872, 1.136, -1.136, -1.872, 2. ])\n" + ">>> 2 * sc.eval_chebyt(3, x / 2)\n" + "array([-2. , 1.872, 1.136, -1.136, -1.872, 2. ])") +ufunc_eval_chebyc_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_chebyc_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_chebyc_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_chebyc_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_chebyc_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_chebyc_types[0] = NPY_INTP +ufunc_eval_chebyc_types[1] = NPY_DOUBLE +ufunc_eval_chebyc_types[2] = NPY_DOUBLE +ufunc_eval_chebyc_types[3] = NPY_FLOAT +ufunc_eval_chebyc_types[4] = NPY_FLOAT +ufunc_eval_chebyc_types[5] = NPY_FLOAT +ufunc_eval_chebyc_types[6] = NPY_FLOAT +ufunc_eval_chebyc_types[7] = NPY_CFLOAT +ufunc_eval_chebyc_types[8] = NPY_CFLOAT +ufunc_eval_chebyc_types[9] = NPY_DOUBLE +ufunc_eval_chebyc_types[10] = NPY_DOUBLE +ufunc_eval_chebyc_types[11] = NPY_DOUBLE +ufunc_eval_chebyc_types[12] = NPY_DOUBLE +ufunc_eval_chebyc_types[13] = NPY_CDOUBLE +ufunc_eval_chebyc_types[14] = NPY_CDOUBLE +ufunc_eval_chebyc_ptr[2*0] = _func_eval_chebyc_l +ufunc_eval_chebyc_ptr[2*0+1] = ("eval_chebyc") +ufunc_eval_chebyc_ptr[2*1] = _func_eval_chebyc[double] +ufunc_eval_chebyc_ptr[2*1+1] = ("eval_chebyc") +ufunc_eval_chebyc_ptr[2*2] = _func_eval_chebyc[double_complex] +ufunc_eval_chebyc_ptr[2*2+1] = ("eval_chebyc") +ufunc_eval_chebyc_ptr[2*3] = _func_eval_chebyc[double] +ufunc_eval_chebyc_ptr[2*3+1] = ("eval_chebyc") +ufunc_eval_chebyc_ptr[2*4] = _func_eval_chebyc[double_complex] +ufunc_eval_chebyc_ptr[2*4+1] = ("eval_chebyc") +ufunc_eval_chebyc_data[0] = &ufunc_eval_chebyc_ptr[2*0] +ufunc_eval_chebyc_data[1] = &ufunc_eval_chebyc_ptr[2*1] +ufunc_eval_chebyc_data[2] = &ufunc_eval_chebyc_ptr[2*2] +ufunc_eval_chebyc_data[3] = &ufunc_eval_chebyc_ptr[2*3] +ufunc_eval_chebyc_data[4] = &ufunc_eval_chebyc_ptr[2*4] +eval_chebyc = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyc_loops, ufunc_eval_chebyc_data, ufunc_eval_chebyc_types, 5, 2, 1, 0, "eval_chebyc", ufunc_eval_chebyc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_chebys_loops[5] +cdef void *ufunc_eval_chebys_ptr[10] +cdef void *ufunc_eval_chebys_data[5] +cdef char ufunc_eval_chebys_types[15] +cdef char *ufunc_eval_chebys_doc = ( + "eval_chebys(n, x, out=None)\n" + "\n" + "Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a\n" + "point.\n" + "\n" + "These polynomials are defined as\n" + "\n" + ".. math::\n" + "\n" + " S_n(x) = U_n(x/2)\n" + "\n" + "where :math:`U_n` is a Chebyshev polynomial of the second\n" + "kind. See 22.5.13 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to `eval_chebyu`.\n" + "x : array_like\n" + " Points at which to evaluate the Chebyshev polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "S : scalar or ndarray\n" + " Values of the Chebyshev polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_chebys : roots and quadrature weights of Chebyshev\n" + " polynomials of the second kind on [-2, 2]\n" + "chebys : Chebyshev polynomial object\n" + "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "They are a scaled version of the Chebyshev polynomials of the\n" + "second kind.\n" + "\n" + ">>> x = np.linspace(-2, 2, 6)\n" + ">>> sc.eval_chebys(3, x)\n" + "array([-4. , 0.672, 0.736, -0.736, -0.672, 4. ])\n" + ">>> sc.eval_chebyu(3, x / 2)\n" + "array([-4. , 0.672, 0.736, -0.736, -0.672, 4. ])") +ufunc_eval_chebys_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_chebys_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_chebys_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_chebys_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_chebys_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_chebys_types[0] = NPY_INTP +ufunc_eval_chebys_types[1] = NPY_DOUBLE +ufunc_eval_chebys_types[2] = NPY_DOUBLE +ufunc_eval_chebys_types[3] = NPY_FLOAT +ufunc_eval_chebys_types[4] = NPY_FLOAT +ufunc_eval_chebys_types[5] = NPY_FLOAT +ufunc_eval_chebys_types[6] = NPY_FLOAT +ufunc_eval_chebys_types[7] = NPY_CFLOAT +ufunc_eval_chebys_types[8] = NPY_CFLOAT +ufunc_eval_chebys_types[9] = NPY_DOUBLE +ufunc_eval_chebys_types[10] = NPY_DOUBLE +ufunc_eval_chebys_types[11] = NPY_DOUBLE +ufunc_eval_chebys_types[12] = NPY_DOUBLE +ufunc_eval_chebys_types[13] = NPY_CDOUBLE +ufunc_eval_chebys_types[14] = NPY_CDOUBLE +ufunc_eval_chebys_ptr[2*0] = _func_eval_chebys_l +ufunc_eval_chebys_ptr[2*0+1] = ("eval_chebys") +ufunc_eval_chebys_ptr[2*1] = _func_eval_chebys[double] +ufunc_eval_chebys_ptr[2*1+1] = ("eval_chebys") +ufunc_eval_chebys_ptr[2*2] = _func_eval_chebys[double_complex] +ufunc_eval_chebys_ptr[2*2+1] = ("eval_chebys") +ufunc_eval_chebys_ptr[2*3] = _func_eval_chebys[double] +ufunc_eval_chebys_ptr[2*3+1] = ("eval_chebys") +ufunc_eval_chebys_ptr[2*4] = _func_eval_chebys[double_complex] +ufunc_eval_chebys_ptr[2*4+1] = ("eval_chebys") +ufunc_eval_chebys_data[0] = &ufunc_eval_chebys_ptr[2*0] +ufunc_eval_chebys_data[1] = &ufunc_eval_chebys_ptr[2*1] +ufunc_eval_chebys_data[2] = &ufunc_eval_chebys_ptr[2*2] +ufunc_eval_chebys_data[3] = &ufunc_eval_chebys_ptr[2*3] +ufunc_eval_chebys_data[4] = &ufunc_eval_chebys_ptr[2*4] +eval_chebys = np.PyUFunc_FromFuncAndData(ufunc_eval_chebys_loops, ufunc_eval_chebys_data, ufunc_eval_chebys_types, 5, 2, 1, 0, "eval_chebys", ufunc_eval_chebys_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_chebyt_loops[5] +cdef void *ufunc_eval_chebyt_ptr[10] +cdef void *ufunc_eval_chebyt_data[5] +cdef char ufunc_eval_chebyt_types[15] +cdef char *ufunc_eval_chebyt_doc = ( + "eval_chebyt(n, x, out=None)\n" + "\n" + "Evaluate Chebyshev polynomial of the first kind at a point.\n" + "\n" + "The Chebyshev polynomials of the first kind can be defined via the\n" + "Gauss hypergeometric function :math:`{}_2F_1` as\n" + "\n" + ".. math::\n" + "\n" + " T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2).\n" + "\n" + "When :math:`n` is an integer the result is a polynomial of degree\n" + ":math:`n`. See 22.5.47 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to the Gauss hypergeometric\n" + " function.\n" + "x : array_like\n" + " Points at which to evaluate the Chebyshev polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "T : scalar or ndarray\n" + " Values of the Chebyshev polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_chebyt : roots and quadrature weights of Chebyshev\n" + " polynomials of the first kind\n" + "chebyu : Chebychev polynomial object\n" + "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n" + "hyp2f1 : Gauss hypergeometric function\n" + "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n" + "\n" + "Notes\n" + "-----\n" + "This routine is numerically stable for `x` in ``[-1, 1]`` at least\n" + "up to order ``10000``.\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_chebyt_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_chebyt_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_chebyt_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_chebyt_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_chebyt_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_chebyt_types[0] = NPY_INTP +ufunc_eval_chebyt_types[1] = NPY_DOUBLE +ufunc_eval_chebyt_types[2] = NPY_DOUBLE +ufunc_eval_chebyt_types[3] = NPY_FLOAT +ufunc_eval_chebyt_types[4] = NPY_FLOAT +ufunc_eval_chebyt_types[5] = NPY_FLOAT +ufunc_eval_chebyt_types[6] = NPY_FLOAT +ufunc_eval_chebyt_types[7] = NPY_CFLOAT +ufunc_eval_chebyt_types[8] = NPY_CFLOAT +ufunc_eval_chebyt_types[9] = NPY_DOUBLE +ufunc_eval_chebyt_types[10] = NPY_DOUBLE +ufunc_eval_chebyt_types[11] = NPY_DOUBLE +ufunc_eval_chebyt_types[12] = NPY_DOUBLE +ufunc_eval_chebyt_types[13] = NPY_CDOUBLE +ufunc_eval_chebyt_types[14] = NPY_CDOUBLE +ufunc_eval_chebyt_ptr[2*0] = _func_eval_chebyt_l +ufunc_eval_chebyt_ptr[2*0+1] = ("eval_chebyt") +ufunc_eval_chebyt_ptr[2*1] = _func_eval_chebyt[double] +ufunc_eval_chebyt_ptr[2*1+1] = ("eval_chebyt") +ufunc_eval_chebyt_ptr[2*2] = _func_eval_chebyt[double_complex] +ufunc_eval_chebyt_ptr[2*2+1] = ("eval_chebyt") +ufunc_eval_chebyt_ptr[2*3] = _func_eval_chebyt[double] +ufunc_eval_chebyt_ptr[2*3+1] = ("eval_chebyt") +ufunc_eval_chebyt_ptr[2*4] = _func_eval_chebyt[double_complex] +ufunc_eval_chebyt_ptr[2*4+1] = ("eval_chebyt") +ufunc_eval_chebyt_data[0] = &ufunc_eval_chebyt_ptr[2*0] +ufunc_eval_chebyt_data[1] = &ufunc_eval_chebyt_ptr[2*1] +ufunc_eval_chebyt_data[2] = &ufunc_eval_chebyt_ptr[2*2] +ufunc_eval_chebyt_data[3] = &ufunc_eval_chebyt_ptr[2*3] +ufunc_eval_chebyt_data[4] = &ufunc_eval_chebyt_ptr[2*4] +eval_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyt_loops, ufunc_eval_chebyt_data, ufunc_eval_chebyt_types, 5, 2, 1, 0, "eval_chebyt", ufunc_eval_chebyt_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_chebyu_loops[5] +cdef void *ufunc_eval_chebyu_ptr[10] +cdef void *ufunc_eval_chebyu_data[5] +cdef char ufunc_eval_chebyu_types[15] +cdef char *ufunc_eval_chebyu_doc = ( + "eval_chebyu(n, x, out=None)\n" + "\n" + "Evaluate Chebyshev polynomial of the second kind at a point.\n" + "\n" + "The Chebyshev polynomials of the second kind can be defined via\n" + "the Gauss hypergeometric function :math:`{}_2F_1` as\n" + "\n" + ".. math::\n" + "\n" + " U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2).\n" + "\n" + "When :math:`n` is an integer the result is a polynomial of degree\n" + ":math:`n`. See 22.5.48 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to the Gauss hypergeometric\n" + " function.\n" + "x : array_like\n" + " Points at which to evaluate the Chebyshev polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "U : scalar or ndarray\n" + " Values of the Chebyshev polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_chebyu : roots and quadrature weights of Chebyshev\n" + " polynomials of the second kind\n" + "chebyu : Chebyshev polynomial object\n" + "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n" + "hyp2f1 : Gauss hypergeometric function\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_chebyu_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_chebyu_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_chebyu_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_chebyu_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_chebyu_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_chebyu_types[0] = NPY_INTP +ufunc_eval_chebyu_types[1] = NPY_DOUBLE +ufunc_eval_chebyu_types[2] = NPY_DOUBLE +ufunc_eval_chebyu_types[3] = NPY_FLOAT +ufunc_eval_chebyu_types[4] = NPY_FLOAT +ufunc_eval_chebyu_types[5] = NPY_FLOAT +ufunc_eval_chebyu_types[6] = NPY_FLOAT +ufunc_eval_chebyu_types[7] = NPY_CFLOAT +ufunc_eval_chebyu_types[8] = NPY_CFLOAT +ufunc_eval_chebyu_types[9] = NPY_DOUBLE +ufunc_eval_chebyu_types[10] = NPY_DOUBLE +ufunc_eval_chebyu_types[11] = NPY_DOUBLE +ufunc_eval_chebyu_types[12] = NPY_DOUBLE +ufunc_eval_chebyu_types[13] = NPY_CDOUBLE +ufunc_eval_chebyu_types[14] = NPY_CDOUBLE +ufunc_eval_chebyu_ptr[2*0] = _func_eval_chebyu_l +ufunc_eval_chebyu_ptr[2*0+1] = ("eval_chebyu") +ufunc_eval_chebyu_ptr[2*1] = _func_eval_chebyu[double] +ufunc_eval_chebyu_ptr[2*1+1] = ("eval_chebyu") +ufunc_eval_chebyu_ptr[2*2] = _func_eval_chebyu[double_complex] +ufunc_eval_chebyu_ptr[2*2+1] = ("eval_chebyu") +ufunc_eval_chebyu_ptr[2*3] = _func_eval_chebyu[double] +ufunc_eval_chebyu_ptr[2*3+1] = ("eval_chebyu") +ufunc_eval_chebyu_ptr[2*4] = _func_eval_chebyu[double_complex] +ufunc_eval_chebyu_ptr[2*4+1] = ("eval_chebyu") +ufunc_eval_chebyu_data[0] = &ufunc_eval_chebyu_ptr[2*0] +ufunc_eval_chebyu_data[1] = &ufunc_eval_chebyu_ptr[2*1] +ufunc_eval_chebyu_data[2] = &ufunc_eval_chebyu_ptr[2*2] +ufunc_eval_chebyu_data[3] = &ufunc_eval_chebyu_ptr[2*3] +ufunc_eval_chebyu_data[4] = &ufunc_eval_chebyu_ptr[2*4] +eval_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyu_loops, ufunc_eval_chebyu_data, ufunc_eval_chebyu_types, 5, 2, 1, 0, "eval_chebyu", ufunc_eval_chebyu_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_gegenbauer_loops[5] +cdef void *ufunc_eval_gegenbauer_ptr[10] +cdef void *ufunc_eval_gegenbauer_data[5] +cdef char ufunc_eval_gegenbauer_types[20] +cdef char *ufunc_eval_gegenbauer_doc = ( + "eval_gegenbauer(n, alpha, x, out=None)\n" + "\n" + "Evaluate Gegenbauer polynomial at a point.\n" + "\n" + "The Gegenbauer polynomials can be defined via the Gauss\n" + "hypergeometric function :math:`{}_2F_1` as\n" + "\n" + ".. math::\n" + "\n" + " C_n^{(\\alpha)} = \\frac{(2\\alpha)_n}{\\Gamma(n + 1)}\n" + " {}_2F_1(-n, 2\\alpha + n; \\alpha + 1/2; (1 - z)/2).\n" + "\n" + "When :math:`n` is an integer the result is a polynomial of degree\n" + ":math:`n`. See 22.5.46 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to the Gauss hypergeometric\n" + " function.\n" + "alpha : array_like\n" + " Parameter\n" + "x : array_like\n" + " Points at which to evaluate the Gegenbauer polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "C : scalar or ndarray\n" + " Values of the Gegenbauer polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_gegenbauer : roots and quadrature weights of Gegenbauer\n" + " polynomials\n" + "gegenbauer : Gegenbauer polynomial object\n" + "hyp2f1 : Gauss hypergeometric function\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_gegenbauer_loops[0] = loop_d_pdd__As_pdd_d +ufunc_eval_gegenbauer_loops[1] = loop_d_ddd__As_fff_f +ufunc_eval_gegenbauer_loops[2] = loop_D_ddD__As_ffF_F +ufunc_eval_gegenbauer_loops[3] = loop_d_ddd__As_ddd_d +ufunc_eval_gegenbauer_loops[4] = loop_D_ddD__As_ddD_D +ufunc_eval_gegenbauer_types[0] = NPY_INTP +ufunc_eval_gegenbauer_types[1] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[2] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[3] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[4] = NPY_FLOAT +ufunc_eval_gegenbauer_types[5] = NPY_FLOAT +ufunc_eval_gegenbauer_types[6] = NPY_FLOAT +ufunc_eval_gegenbauer_types[7] = NPY_FLOAT +ufunc_eval_gegenbauer_types[8] = NPY_FLOAT +ufunc_eval_gegenbauer_types[9] = NPY_FLOAT +ufunc_eval_gegenbauer_types[10] = NPY_CFLOAT +ufunc_eval_gegenbauer_types[11] = NPY_CFLOAT +ufunc_eval_gegenbauer_types[12] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[13] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[14] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[15] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[16] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[17] = NPY_DOUBLE +ufunc_eval_gegenbauer_types[18] = NPY_CDOUBLE +ufunc_eval_gegenbauer_types[19] = NPY_CDOUBLE +ufunc_eval_gegenbauer_ptr[2*0] = _func_eval_gegenbauer_l +ufunc_eval_gegenbauer_ptr[2*0+1] = ("eval_gegenbauer") +ufunc_eval_gegenbauer_ptr[2*1] = _func_eval_gegenbauer[double] +ufunc_eval_gegenbauer_ptr[2*1+1] = ("eval_gegenbauer") +ufunc_eval_gegenbauer_ptr[2*2] = _func_eval_gegenbauer[double_complex] +ufunc_eval_gegenbauer_ptr[2*2+1] = ("eval_gegenbauer") +ufunc_eval_gegenbauer_ptr[2*3] = _func_eval_gegenbauer[double] +ufunc_eval_gegenbauer_ptr[2*3+1] = ("eval_gegenbauer") +ufunc_eval_gegenbauer_ptr[2*4] = _func_eval_gegenbauer[double_complex] +ufunc_eval_gegenbauer_ptr[2*4+1] = ("eval_gegenbauer") +ufunc_eval_gegenbauer_data[0] = &ufunc_eval_gegenbauer_ptr[2*0] +ufunc_eval_gegenbauer_data[1] = &ufunc_eval_gegenbauer_ptr[2*1] +ufunc_eval_gegenbauer_data[2] = &ufunc_eval_gegenbauer_ptr[2*2] +ufunc_eval_gegenbauer_data[3] = &ufunc_eval_gegenbauer_ptr[2*3] +ufunc_eval_gegenbauer_data[4] = &ufunc_eval_gegenbauer_ptr[2*4] +eval_gegenbauer = np.PyUFunc_FromFuncAndData(ufunc_eval_gegenbauer_loops, ufunc_eval_gegenbauer_data, ufunc_eval_gegenbauer_types, 5, 3, 1, 0, "eval_gegenbauer", ufunc_eval_gegenbauer_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_genlaguerre_loops[5] +cdef void *ufunc_eval_genlaguerre_ptr[10] +cdef void *ufunc_eval_genlaguerre_data[5] +cdef char ufunc_eval_genlaguerre_types[20] +cdef char *ufunc_eval_genlaguerre_doc = ( + "eval_genlaguerre(n, alpha, x, out=None)\n" + "\n" + "Evaluate generalized Laguerre polynomial at a point.\n" + "\n" + "The generalized Laguerre polynomials can be defined via the\n" + "confluent hypergeometric function :math:`{}_1F_1` as\n" + "\n" + ".. math::\n" + "\n" + " L_n^{(\\alpha)}(x) = \\binom{n + \\alpha}{n}\n" + " {}_1F_1(-n, \\alpha + 1, x).\n" + "\n" + "When :math:`n` is an integer the result is a polynomial of degree\n" + ":math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre\n" + "polynomials are the special case where :math:`\\alpha = 0`.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to the confluent hypergeometric\n" + " function.\n" + "alpha : array_like\n" + " Parameter; must have ``alpha > -1``\n" + "x : array_like\n" + " Points at which to evaluate the generalized Laguerre\n" + " polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "L : scalar or ndarray\n" + " Values of the generalized Laguerre polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_genlaguerre : roots and quadrature weights of generalized\n" + " Laguerre polynomials\n" + "genlaguerre : generalized Laguerre polynomial object\n" + "hyp1f1 : confluent hypergeometric function\n" + "eval_laguerre : evaluate Laguerre polynomials\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_genlaguerre_loops[0] = loop_d_pdd__As_pdd_d +ufunc_eval_genlaguerre_loops[1] = loop_d_ddd__As_fff_f +ufunc_eval_genlaguerre_loops[2] = loop_D_ddD__As_ffF_F +ufunc_eval_genlaguerre_loops[3] = loop_d_ddd__As_ddd_d +ufunc_eval_genlaguerre_loops[4] = loop_D_ddD__As_ddD_D +ufunc_eval_genlaguerre_types[0] = NPY_INTP +ufunc_eval_genlaguerre_types[1] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[2] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[3] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[4] = NPY_FLOAT +ufunc_eval_genlaguerre_types[5] = NPY_FLOAT +ufunc_eval_genlaguerre_types[6] = NPY_FLOAT +ufunc_eval_genlaguerre_types[7] = NPY_FLOAT +ufunc_eval_genlaguerre_types[8] = NPY_FLOAT +ufunc_eval_genlaguerre_types[9] = NPY_FLOAT +ufunc_eval_genlaguerre_types[10] = NPY_CFLOAT +ufunc_eval_genlaguerre_types[11] = NPY_CFLOAT +ufunc_eval_genlaguerre_types[12] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[13] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[14] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[15] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[16] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[17] = NPY_DOUBLE +ufunc_eval_genlaguerre_types[18] = NPY_CDOUBLE +ufunc_eval_genlaguerre_types[19] = NPY_CDOUBLE +ufunc_eval_genlaguerre_ptr[2*0] = _func_eval_genlaguerre_l +ufunc_eval_genlaguerre_ptr[2*0+1] = ("eval_genlaguerre") +ufunc_eval_genlaguerre_ptr[2*1] = _func_eval_genlaguerre[double] +ufunc_eval_genlaguerre_ptr[2*1+1] = ("eval_genlaguerre") +ufunc_eval_genlaguerre_ptr[2*2] = _func_eval_genlaguerre[double_complex] +ufunc_eval_genlaguerre_ptr[2*2+1] = ("eval_genlaguerre") +ufunc_eval_genlaguerre_ptr[2*3] = _func_eval_genlaguerre[double] +ufunc_eval_genlaguerre_ptr[2*3+1] = ("eval_genlaguerre") +ufunc_eval_genlaguerre_ptr[2*4] = _func_eval_genlaguerre[double_complex] +ufunc_eval_genlaguerre_ptr[2*4+1] = ("eval_genlaguerre") +ufunc_eval_genlaguerre_data[0] = &ufunc_eval_genlaguerre_ptr[2*0] +ufunc_eval_genlaguerre_data[1] = &ufunc_eval_genlaguerre_ptr[2*1] +ufunc_eval_genlaguerre_data[2] = &ufunc_eval_genlaguerre_ptr[2*2] +ufunc_eval_genlaguerre_data[3] = &ufunc_eval_genlaguerre_ptr[2*3] +ufunc_eval_genlaguerre_data[4] = &ufunc_eval_genlaguerre_ptr[2*4] +eval_genlaguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_genlaguerre_loops, ufunc_eval_genlaguerre_data, ufunc_eval_genlaguerre_types, 5, 3, 1, 0, "eval_genlaguerre", ufunc_eval_genlaguerre_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_hermite_loops[1] +cdef void *ufunc_eval_hermite_ptr[2] +cdef void *ufunc_eval_hermite_data[1] +cdef char ufunc_eval_hermite_types[3] +cdef char *ufunc_eval_hermite_doc = ( + "eval_hermite(n, x, out=None)\n" + "\n" + "Evaluate physicist's Hermite polynomial at a point.\n" + "\n" + "Defined by\n" + "\n" + ".. math::\n" + "\n" + " H_n(x) = (-1)^n e^{x^2} \\frac{d^n}{dx^n} e^{-x^2};\n" + "\n" + ":math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in\n" + "[AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial\n" + "x : array_like\n" + " Points at which to evaluate the Hermite polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "H : scalar or ndarray\n" + " Values of the Hermite polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_hermite : roots and quadrature weights of physicist's\n" + " Hermite polynomials\n" + "hermite : physicist's Hermite polynomial object\n" + "numpy.polynomial.hermite.Hermite : Physicist's Hermite series\n" + "eval_hermitenorm : evaluate Probabilist's Hermite polynomials\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_hermite_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_hermite_types[0] = NPY_INTP +ufunc_eval_hermite_types[1] = NPY_DOUBLE +ufunc_eval_hermite_types[2] = NPY_DOUBLE +ufunc_eval_hermite_ptr[2*0] = _func_eval_hermite +ufunc_eval_hermite_ptr[2*0+1] = ("eval_hermite") +ufunc_eval_hermite_data[0] = &ufunc_eval_hermite_ptr[2*0] +eval_hermite = np.PyUFunc_FromFuncAndData(ufunc_eval_hermite_loops, ufunc_eval_hermite_data, ufunc_eval_hermite_types, 1, 2, 1, 0, "eval_hermite", ufunc_eval_hermite_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_hermitenorm_loops[1] +cdef void *ufunc_eval_hermitenorm_ptr[2] +cdef void *ufunc_eval_hermitenorm_data[1] +cdef char ufunc_eval_hermitenorm_types[3] +cdef char *ufunc_eval_hermitenorm_doc = ( + "eval_hermitenorm(n, x, out=None)\n" + "\n" + "Evaluate probabilist's (normalized) Hermite polynomial at a\n" + "point.\n" + "\n" + "Defined by\n" + "\n" + ".. math::\n" + "\n" + " He_n(x) = (-1)^n e^{x^2/2} \\frac{d^n}{dx^n} e^{-x^2/2};\n" + "\n" + ":math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in\n" + "[AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial\n" + "x : array_like\n" + " Points at which to evaluate the Hermite polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "He : scalar or ndarray\n" + " Values of the Hermite polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_hermitenorm : roots and quadrature weights of probabilist's\n" + " Hermite polynomials\n" + "hermitenorm : probabilist's Hermite polynomial object\n" + "numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series\n" + "eval_hermite : evaluate physicist's Hermite polynomials\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_hermitenorm_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_hermitenorm_types[0] = NPY_INTP +ufunc_eval_hermitenorm_types[1] = NPY_DOUBLE +ufunc_eval_hermitenorm_types[2] = NPY_DOUBLE +ufunc_eval_hermitenorm_ptr[2*0] = _func_eval_hermitenorm +ufunc_eval_hermitenorm_ptr[2*0+1] = ("eval_hermitenorm") +ufunc_eval_hermitenorm_data[0] = &ufunc_eval_hermitenorm_ptr[2*0] +eval_hermitenorm = np.PyUFunc_FromFuncAndData(ufunc_eval_hermitenorm_loops, ufunc_eval_hermitenorm_data, ufunc_eval_hermitenorm_types, 1, 2, 1, 0, "eval_hermitenorm", ufunc_eval_hermitenorm_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_jacobi_loops[5] +cdef void *ufunc_eval_jacobi_ptr[10] +cdef void *ufunc_eval_jacobi_data[5] +cdef char ufunc_eval_jacobi_types[25] +cdef char *ufunc_eval_jacobi_doc = ( + "eval_jacobi(n, alpha, beta, x, out=None)\n" + "\n" + "Evaluate Jacobi polynomial at a point.\n" + "\n" + "The Jacobi polynomials can be defined via the Gauss hypergeometric\n" + "function :math:`{}_2F_1` as\n" + "\n" + ".. math::\n" + "\n" + " P_n^{(\\alpha, \\beta)}(x) = \\frac{(\\alpha + 1)_n}{\\Gamma(n + 1)}\n" + " {}_2F_1(-n, 1 + \\alpha + \\beta + n; \\alpha + 1; (1 - z)/2)\n" + "\n" + "where :math:`(\\cdot)_n` is the Pochhammer symbol; see `poch`. When\n" + ":math:`n` is an integer the result is a polynomial of degree\n" + ":math:`n`. See 22.5.42 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer the result is\n" + " determined via the relation to the Gauss hypergeometric\n" + " function.\n" + "alpha : array_like\n" + " Parameter\n" + "beta : array_like\n" + " Parameter\n" + "x : array_like\n" + " Points at which to evaluate the polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "P : scalar or ndarray\n" + " Values of the Jacobi polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_jacobi : roots and quadrature weights of Jacobi polynomials\n" + "jacobi : Jacobi polynomial object\n" + "hyp2f1 : Gauss hypergeometric function\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_jacobi_loops[0] = loop_d_pddd__As_pddd_d +ufunc_eval_jacobi_loops[1] = loop_d_dddd__As_ffff_f +ufunc_eval_jacobi_loops[2] = loop_D_dddD__As_fffF_F +ufunc_eval_jacobi_loops[3] = loop_d_dddd__As_dddd_d +ufunc_eval_jacobi_loops[4] = loop_D_dddD__As_dddD_D +ufunc_eval_jacobi_types[0] = NPY_INTP +ufunc_eval_jacobi_types[1] = NPY_DOUBLE +ufunc_eval_jacobi_types[2] = NPY_DOUBLE +ufunc_eval_jacobi_types[3] = NPY_DOUBLE +ufunc_eval_jacobi_types[4] = NPY_DOUBLE +ufunc_eval_jacobi_types[5] = NPY_FLOAT +ufunc_eval_jacobi_types[6] = NPY_FLOAT +ufunc_eval_jacobi_types[7] = NPY_FLOAT +ufunc_eval_jacobi_types[8] = NPY_FLOAT +ufunc_eval_jacobi_types[9] = NPY_FLOAT +ufunc_eval_jacobi_types[10] = NPY_FLOAT +ufunc_eval_jacobi_types[11] = NPY_FLOAT +ufunc_eval_jacobi_types[12] = NPY_FLOAT +ufunc_eval_jacobi_types[13] = NPY_CFLOAT +ufunc_eval_jacobi_types[14] = NPY_CFLOAT +ufunc_eval_jacobi_types[15] = NPY_DOUBLE +ufunc_eval_jacobi_types[16] = NPY_DOUBLE +ufunc_eval_jacobi_types[17] = NPY_DOUBLE +ufunc_eval_jacobi_types[18] = NPY_DOUBLE +ufunc_eval_jacobi_types[19] = NPY_DOUBLE +ufunc_eval_jacobi_types[20] = NPY_DOUBLE +ufunc_eval_jacobi_types[21] = NPY_DOUBLE +ufunc_eval_jacobi_types[22] = NPY_DOUBLE +ufunc_eval_jacobi_types[23] = NPY_CDOUBLE +ufunc_eval_jacobi_types[24] = NPY_CDOUBLE +ufunc_eval_jacobi_ptr[2*0] = _func_eval_jacobi_l +ufunc_eval_jacobi_ptr[2*0+1] = ("eval_jacobi") +ufunc_eval_jacobi_ptr[2*1] = _func_eval_jacobi[double] +ufunc_eval_jacobi_ptr[2*1+1] = ("eval_jacobi") +ufunc_eval_jacobi_ptr[2*2] = _func_eval_jacobi[double_complex] +ufunc_eval_jacobi_ptr[2*2+1] = ("eval_jacobi") +ufunc_eval_jacobi_ptr[2*3] = _func_eval_jacobi[double] +ufunc_eval_jacobi_ptr[2*3+1] = ("eval_jacobi") +ufunc_eval_jacobi_ptr[2*4] = _func_eval_jacobi[double_complex] +ufunc_eval_jacobi_ptr[2*4+1] = ("eval_jacobi") +ufunc_eval_jacobi_data[0] = &ufunc_eval_jacobi_ptr[2*0] +ufunc_eval_jacobi_data[1] = &ufunc_eval_jacobi_ptr[2*1] +ufunc_eval_jacobi_data[2] = &ufunc_eval_jacobi_ptr[2*2] +ufunc_eval_jacobi_data[3] = &ufunc_eval_jacobi_ptr[2*3] +ufunc_eval_jacobi_data[4] = &ufunc_eval_jacobi_ptr[2*4] +eval_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_jacobi_loops, ufunc_eval_jacobi_data, ufunc_eval_jacobi_types, 5, 4, 1, 0, "eval_jacobi", ufunc_eval_jacobi_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_laguerre_loops[5] +cdef void *ufunc_eval_laguerre_ptr[10] +cdef void *ufunc_eval_laguerre_data[5] +cdef char ufunc_eval_laguerre_types[15] +cdef char *ufunc_eval_laguerre_doc = ( + "eval_laguerre(n, x, out=None)\n" + "\n" + "Evaluate Laguerre polynomial at a point.\n" + "\n" + "The Laguerre polynomials can be defined via the confluent\n" + "hypergeometric function :math:`{}_1F_1` as\n" + "\n" + ".. math::\n" + "\n" + " L_n(x) = {}_1F_1(-n, 1, x).\n" + "\n" + "See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an\n" + "integer the result is a polynomial of degree :math:`n`.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer the result is\n" + " determined via the relation to the confluent hypergeometric\n" + " function.\n" + "x : array_like\n" + " Points at which to evaluate the Laguerre polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "L : scalar or ndarray\n" + " Values of the Laguerre polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_laguerre : roots and quadrature weights of Laguerre\n" + " polynomials\n" + "laguerre : Laguerre polynomial object\n" + "numpy.polynomial.laguerre.Laguerre : Laguerre series\n" + "eval_genlaguerre : evaluate generalized Laguerre polynomials\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_laguerre_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_laguerre_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_laguerre_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_laguerre_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_laguerre_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_laguerre_types[0] = NPY_INTP +ufunc_eval_laguerre_types[1] = NPY_DOUBLE +ufunc_eval_laguerre_types[2] = NPY_DOUBLE +ufunc_eval_laguerre_types[3] = NPY_FLOAT +ufunc_eval_laguerre_types[4] = NPY_FLOAT +ufunc_eval_laguerre_types[5] = NPY_FLOAT +ufunc_eval_laguerre_types[6] = NPY_FLOAT +ufunc_eval_laguerre_types[7] = NPY_CFLOAT +ufunc_eval_laguerre_types[8] = NPY_CFLOAT +ufunc_eval_laguerre_types[9] = NPY_DOUBLE +ufunc_eval_laguerre_types[10] = NPY_DOUBLE +ufunc_eval_laguerre_types[11] = NPY_DOUBLE +ufunc_eval_laguerre_types[12] = NPY_DOUBLE +ufunc_eval_laguerre_types[13] = NPY_CDOUBLE +ufunc_eval_laguerre_types[14] = NPY_CDOUBLE +ufunc_eval_laguerre_ptr[2*0] = _func_eval_laguerre_l +ufunc_eval_laguerre_ptr[2*0+1] = ("eval_laguerre") +ufunc_eval_laguerre_ptr[2*1] = _func_eval_laguerre[double] +ufunc_eval_laguerre_ptr[2*1+1] = ("eval_laguerre") +ufunc_eval_laguerre_ptr[2*2] = _func_eval_laguerre[double_complex] +ufunc_eval_laguerre_ptr[2*2+1] = ("eval_laguerre") +ufunc_eval_laguerre_ptr[2*3] = _func_eval_laguerre[double] +ufunc_eval_laguerre_ptr[2*3+1] = ("eval_laguerre") +ufunc_eval_laguerre_ptr[2*4] = _func_eval_laguerre[double_complex] +ufunc_eval_laguerre_ptr[2*4+1] = ("eval_laguerre") +ufunc_eval_laguerre_data[0] = &ufunc_eval_laguerre_ptr[2*0] +ufunc_eval_laguerre_data[1] = &ufunc_eval_laguerre_ptr[2*1] +ufunc_eval_laguerre_data[2] = &ufunc_eval_laguerre_ptr[2*2] +ufunc_eval_laguerre_data[3] = &ufunc_eval_laguerre_ptr[2*3] +ufunc_eval_laguerre_data[4] = &ufunc_eval_laguerre_ptr[2*4] +eval_laguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_laguerre_loops, ufunc_eval_laguerre_data, ufunc_eval_laguerre_types, 5, 2, 1, 0, "eval_laguerre", ufunc_eval_laguerre_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_legendre_loops[5] +cdef void *ufunc_eval_legendre_ptr[10] +cdef void *ufunc_eval_legendre_data[5] +cdef char ufunc_eval_legendre_types[15] +cdef char *ufunc_eval_legendre_doc = ( + "eval_legendre(n, x, out=None)\n" + "\n" + "Evaluate Legendre polynomial at a point.\n" + "\n" + "The Legendre polynomials can be defined via the Gauss\n" + "hypergeometric function :math:`{}_2F_1` as\n" + "\n" + ".. math::\n" + "\n" + " P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2).\n" + "\n" + "When :math:`n` is an integer the result is a polynomial of degree\n" + ":math:`n`. See 22.5.49 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to the Gauss hypergeometric\n" + " function.\n" + "x : array_like\n" + " Points at which to evaluate the Legendre polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "P : scalar or ndarray\n" + " Values of the Legendre polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_legendre : roots and quadrature weights of Legendre\n" + " polynomials\n" + "legendre : Legendre polynomial object\n" + "hyp2f1 : Gauss hypergeometric function\n" + "numpy.polynomial.legendre.Legendre : Legendre series\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import eval_legendre\n" + "\n" + "Evaluate the zero-order Legendre polynomial at x = 0\n" + "\n" + ">>> eval_legendre(0, 0)\n" + "1.0\n" + "\n" + "Evaluate the first-order Legendre polynomial between -1 and 1\n" + "\n" + ">>> X = np.linspace(-1, 1, 5) # Domain of Legendre polynomials\n" + ">>> eval_legendre(1, X)\n" + "array([-1. , -0.5, 0. , 0.5, 1. ])\n" + "\n" + "Evaluate Legendre polynomials of order 0 through 4 at x = 0\n" + "\n" + ">>> N = range(0, 5)\n" + ">>> eval_legendre(N, 0)\n" + "array([ 1. , 0. , -0.5 , 0. , 0.375])\n" + "\n" + "Plot Legendre polynomials of order 0 through 4\n" + "\n" + ">>> X = np.linspace(-1, 1)\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> for n in range(0, 5):\n" + "... y = eval_legendre(n, X)\n" + "... plt.plot(X, y, label=r'$P_{}(x)$'.format(n))\n" + "\n" + ">>> plt.title(\"Legendre Polynomials\")\n" + ">>> plt.xlabel(\"x\")\n" + ">>> plt.ylabel(r'$P_n(x)$')\n" + ">>> plt.legend(loc='lower right')\n" + ">>> plt.show()") +ufunc_eval_legendre_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_legendre_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_legendre_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_legendre_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_legendre_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_legendre_types[0] = NPY_INTP +ufunc_eval_legendre_types[1] = NPY_DOUBLE +ufunc_eval_legendre_types[2] = NPY_DOUBLE +ufunc_eval_legendre_types[3] = NPY_FLOAT +ufunc_eval_legendre_types[4] = NPY_FLOAT +ufunc_eval_legendre_types[5] = NPY_FLOAT +ufunc_eval_legendre_types[6] = NPY_FLOAT +ufunc_eval_legendre_types[7] = NPY_CFLOAT +ufunc_eval_legendre_types[8] = NPY_CFLOAT +ufunc_eval_legendre_types[9] = NPY_DOUBLE +ufunc_eval_legendre_types[10] = NPY_DOUBLE +ufunc_eval_legendre_types[11] = NPY_DOUBLE +ufunc_eval_legendre_types[12] = NPY_DOUBLE +ufunc_eval_legendre_types[13] = NPY_CDOUBLE +ufunc_eval_legendre_types[14] = NPY_CDOUBLE +ufunc_eval_legendre_ptr[2*0] = _func_eval_legendre_l +ufunc_eval_legendre_ptr[2*0+1] = ("eval_legendre") +ufunc_eval_legendre_ptr[2*1] = _func_eval_legendre[double] +ufunc_eval_legendre_ptr[2*1+1] = ("eval_legendre") +ufunc_eval_legendre_ptr[2*2] = _func_eval_legendre[double_complex] +ufunc_eval_legendre_ptr[2*2+1] = ("eval_legendre") +ufunc_eval_legendre_ptr[2*3] = _func_eval_legendre[double] +ufunc_eval_legendre_ptr[2*3+1] = ("eval_legendre") +ufunc_eval_legendre_ptr[2*4] = _func_eval_legendre[double_complex] +ufunc_eval_legendre_ptr[2*4+1] = ("eval_legendre") +ufunc_eval_legendre_data[0] = &ufunc_eval_legendre_ptr[2*0] +ufunc_eval_legendre_data[1] = &ufunc_eval_legendre_ptr[2*1] +ufunc_eval_legendre_data[2] = &ufunc_eval_legendre_ptr[2*2] +ufunc_eval_legendre_data[3] = &ufunc_eval_legendre_ptr[2*3] +ufunc_eval_legendre_data[4] = &ufunc_eval_legendre_ptr[2*4] +eval_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_legendre_loops, ufunc_eval_legendre_data, ufunc_eval_legendre_types, 5, 2, 1, 0, "eval_legendre", ufunc_eval_legendre_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyt_loops[5] +cdef void *ufunc_eval_sh_chebyt_ptr[10] +cdef void *ufunc_eval_sh_chebyt_data[5] +cdef char ufunc_eval_sh_chebyt_types[15] +cdef char *ufunc_eval_sh_chebyt_doc = ( + "eval_sh_chebyt(n, x, out=None)\n" + "\n" + "Evaluate shifted Chebyshev polynomial of the first kind at a\n" + "point.\n" + "\n" + "These polynomials are defined as\n" + "\n" + ".. math::\n" + "\n" + " T_n^*(x) = T_n(2x - 1)\n" + "\n" + "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n" + "22.5.14 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to `eval_chebyt`.\n" + "x : array_like\n" + " Points at which to evaluate the shifted Chebyshev polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "T : scalar or ndarray\n" + " Values of the shifted Chebyshev polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_sh_chebyt : roots and quadrature weights of shifted\n" + " Chebyshev polynomials of the first kind\n" + "sh_chebyt : shifted Chebyshev polynomial object\n" + "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n" + "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_sh_chebyt_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_sh_chebyt_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_sh_chebyt_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_sh_chebyt_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_sh_chebyt_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_sh_chebyt_types[0] = NPY_INTP +ufunc_eval_sh_chebyt_types[1] = NPY_DOUBLE +ufunc_eval_sh_chebyt_types[2] = NPY_DOUBLE +ufunc_eval_sh_chebyt_types[3] = NPY_FLOAT +ufunc_eval_sh_chebyt_types[4] = NPY_FLOAT +ufunc_eval_sh_chebyt_types[5] = NPY_FLOAT +ufunc_eval_sh_chebyt_types[6] = NPY_FLOAT +ufunc_eval_sh_chebyt_types[7] = NPY_CFLOAT +ufunc_eval_sh_chebyt_types[8] = NPY_CFLOAT +ufunc_eval_sh_chebyt_types[9] = NPY_DOUBLE +ufunc_eval_sh_chebyt_types[10] = NPY_DOUBLE +ufunc_eval_sh_chebyt_types[11] = NPY_DOUBLE +ufunc_eval_sh_chebyt_types[12] = NPY_DOUBLE +ufunc_eval_sh_chebyt_types[13] = NPY_CDOUBLE +ufunc_eval_sh_chebyt_types[14] = NPY_CDOUBLE +ufunc_eval_sh_chebyt_ptr[2*0] = _func_eval_sh_chebyt_l +ufunc_eval_sh_chebyt_ptr[2*0+1] = ("eval_sh_chebyt") +ufunc_eval_sh_chebyt_ptr[2*1] = _func_eval_sh_chebyt[double] +ufunc_eval_sh_chebyt_ptr[2*1+1] = ("eval_sh_chebyt") +ufunc_eval_sh_chebyt_ptr[2*2] = _func_eval_sh_chebyt[double_complex] +ufunc_eval_sh_chebyt_ptr[2*2+1] = ("eval_sh_chebyt") +ufunc_eval_sh_chebyt_ptr[2*3] = _func_eval_sh_chebyt[double] +ufunc_eval_sh_chebyt_ptr[2*3+1] = ("eval_sh_chebyt") +ufunc_eval_sh_chebyt_ptr[2*4] = _func_eval_sh_chebyt[double_complex] +ufunc_eval_sh_chebyt_ptr[2*4+1] = ("eval_sh_chebyt") +ufunc_eval_sh_chebyt_data[0] = &ufunc_eval_sh_chebyt_ptr[2*0] +ufunc_eval_sh_chebyt_data[1] = &ufunc_eval_sh_chebyt_ptr[2*1] +ufunc_eval_sh_chebyt_data[2] = &ufunc_eval_sh_chebyt_ptr[2*2] +ufunc_eval_sh_chebyt_data[3] = &ufunc_eval_sh_chebyt_ptr[2*3] +ufunc_eval_sh_chebyt_data[4] = &ufunc_eval_sh_chebyt_ptr[2*4] +eval_sh_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyt_loops, ufunc_eval_sh_chebyt_data, ufunc_eval_sh_chebyt_types, 5, 2, 1, 0, "eval_sh_chebyt", ufunc_eval_sh_chebyt_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyu_loops[5] +cdef void *ufunc_eval_sh_chebyu_ptr[10] +cdef void *ufunc_eval_sh_chebyu_data[5] +cdef char ufunc_eval_sh_chebyu_types[15] +cdef char *ufunc_eval_sh_chebyu_doc = ( + "eval_sh_chebyu(n, x, out=None)\n" + "\n" + "Evaluate shifted Chebyshev polynomial of the second kind at a\n" + "point.\n" + "\n" + "These polynomials are defined as\n" + "\n" + ".. math::\n" + "\n" + " U_n^*(x) = U_n(2x - 1)\n" + "\n" + "where :math:`U_n` is a Chebyshev polynomial of the first kind. See\n" + "22.5.15 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to `eval_chebyu`.\n" + "x : array_like\n" + " Points at which to evaluate the shifted Chebyshev polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "U : scalar or ndarray\n" + " Values of the shifted Chebyshev polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_sh_chebyu : roots and quadrature weights of shifted\n" + " Chebychev polynomials of the second kind\n" + "sh_chebyu : shifted Chebyshev polynomial object\n" + "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_sh_chebyu_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_sh_chebyu_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_sh_chebyu_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_sh_chebyu_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_sh_chebyu_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_sh_chebyu_types[0] = NPY_INTP +ufunc_eval_sh_chebyu_types[1] = NPY_DOUBLE +ufunc_eval_sh_chebyu_types[2] = NPY_DOUBLE +ufunc_eval_sh_chebyu_types[3] = NPY_FLOAT +ufunc_eval_sh_chebyu_types[4] = NPY_FLOAT +ufunc_eval_sh_chebyu_types[5] = NPY_FLOAT +ufunc_eval_sh_chebyu_types[6] = NPY_FLOAT +ufunc_eval_sh_chebyu_types[7] = NPY_CFLOAT +ufunc_eval_sh_chebyu_types[8] = NPY_CFLOAT +ufunc_eval_sh_chebyu_types[9] = NPY_DOUBLE +ufunc_eval_sh_chebyu_types[10] = NPY_DOUBLE +ufunc_eval_sh_chebyu_types[11] = NPY_DOUBLE +ufunc_eval_sh_chebyu_types[12] = NPY_DOUBLE +ufunc_eval_sh_chebyu_types[13] = NPY_CDOUBLE +ufunc_eval_sh_chebyu_types[14] = NPY_CDOUBLE +ufunc_eval_sh_chebyu_ptr[2*0] = _func_eval_sh_chebyu_l +ufunc_eval_sh_chebyu_ptr[2*0+1] = ("eval_sh_chebyu") +ufunc_eval_sh_chebyu_ptr[2*1] = _func_eval_sh_chebyu[double] +ufunc_eval_sh_chebyu_ptr[2*1+1] = ("eval_sh_chebyu") +ufunc_eval_sh_chebyu_ptr[2*2] = _func_eval_sh_chebyu[double_complex] +ufunc_eval_sh_chebyu_ptr[2*2+1] = ("eval_sh_chebyu") +ufunc_eval_sh_chebyu_ptr[2*3] = _func_eval_sh_chebyu[double] +ufunc_eval_sh_chebyu_ptr[2*3+1] = ("eval_sh_chebyu") +ufunc_eval_sh_chebyu_ptr[2*4] = _func_eval_sh_chebyu[double_complex] +ufunc_eval_sh_chebyu_ptr[2*4+1] = ("eval_sh_chebyu") +ufunc_eval_sh_chebyu_data[0] = &ufunc_eval_sh_chebyu_ptr[2*0] +ufunc_eval_sh_chebyu_data[1] = &ufunc_eval_sh_chebyu_ptr[2*1] +ufunc_eval_sh_chebyu_data[2] = &ufunc_eval_sh_chebyu_ptr[2*2] +ufunc_eval_sh_chebyu_data[3] = &ufunc_eval_sh_chebyu_ptr[2*3] +ufunc_eval_sh_chebyu_data[4] = &ufunc_eval_sh_chebyu_ptr[2*4] +eval_sh_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyu_loops, ufunc_eval_sh_chebyu_data, ufunc_eval_sh_chebyu_types, 5, 2, 1, 0, "eval_sh_chebyu", ufunc_eval_sh_chebyu_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_sh_jacobi_loops[5] +cdef void *ufunc_eval_sh_jacobi_ptr[10] +cdef void *ufunc_eval_sh_jacobi_data[5] +cdef char ufunc_eval_sh_jacobi_types[25] +cdef char *ufunc_eval_sh_jacobi_doc = ( + "eval_sh_jacobi(n, p, q, x, out=None)\n" + "\n" + "Evaluate shifted Jacobi polynomial at a point.\n" + "\n" + "Defined by\n" + "\n" + ".. math::\n" + "\n" + " G_n^{(p, q)}(x)\n" + " = \\binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1),\n" + "\n" + "where :math:`P_n^{(\\cdot, \\cdot)}` is the n-th Jacobi\n" + "polynomial. See 22.5.2 in [AS]_ for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : int\n" + " Degree of the polynomial. If not an integer, the result is\n" + " determined via the relation to `binom` and `eval_jacobi`.\n" + "p : float\n" + " Parameter\n" + "q : float\n" + " Parameter\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "G : scalar or ndarray\n" + " Values of the shifted Jacobi polynomial.\n" + "\n" + "See Also\n" + "--------\n" + "roots_sh_jacobi : roots and quadrature weights of shifted Jacobi\n" + " polynomials\n" + "sh_jacobi : shifted Jacobi polynomial object\n" + "eval_jacobi : evaluate Jacobi polynomials\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_sh_jacobi_loops[0] = loop_d_pddd__As_pddd_d +ufunc_eval_sh_jacobi_loops[1] = loop_d_dddd__As_ffff_f +ufunc_eval_sh_jacobi_loops[2] = loop_D_dddD__As_fffF_F +ufunc_eval_sh_jacobi_loops[3] = loop_d_dddd__As_dddd_d +ufunc_eval_sh_jacobi_loops[4] = loop_D_dddD__As_dddD_D +ufunc_eval_sh_jacobi_types[0] = NPY_INTP +ufunc_eval_sh_jacobi_types[1] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[2] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[3] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[4] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[5] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[6] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[7] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[8] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[9] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[10] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[11] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[12] = NPY_FLOAT +ufunc_eval_sh_jacobi_types[13] = NPY_CFLOAT +ufunc_eval_sh_jacobi_types[14] = NPY_CFLOAT +ufunc_eval_sh_jacobi_types[15] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[16] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[17] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[18] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[19] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[20] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[21] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[22] = NPY_DOUBLE +ufunc_eval_sh_jacobi_types[23] = NPY_CDOUBLE +ufunc_eval_sh_jacobi_types[24] = NPY_CDOUBLE +ufunc_eval_sh_jacobi_ptr[2*0] = _func_eval_sh_jacobi_l +ufunc_eval_sh_jacobi_ptr[2*0+1] = ("eval_sh_jacobi") +ufunc_eval_sh_jacobi_ptr[2*1] = _func_eval_sh_jacobi[double] +ufunc_eval_sh_jacobi_ptr[2*1+1] = ("eval_sh_jacobi") +ufunc_eval_sh_jacobi_ptr[2*2] = _func_eval_sh_jacobi[double_complex] +ufunc_eval_sh_jacobi_ptr[2*2+1] = ("eval_sh_jacobi") +ufunc_eval_sh_jacobi_ptr[2*3] = _func_eval_sh_jacobi[double] +ufunc_eval_sh_jacobi_ptr[2*3+1] = ("eval_sh_jacobi") +ufunc_eval_sh_jacobi_ptr[2*4] = _func_eval_sh_jacobi[double_complex] +ufunc_eval_sh_jacobi_ptr[2*4+1] = ("eval_sh_jacobi") +ufunc_eval_sh_jacobi_data[0] = &ufunc_eval_sh_jacobi_ptr[2*0] +ufunc_eval_sh_jacobi_data[1] = &ufunc_eval_sh_jacobi_ptr[2*1] +ufunc_eval_sh_jacobi_data[2] = &ufunc_eval_sh_jacobi_ptr[2*2] +ufunc_eval_sh_jacobi_data[3] = &ufunc_eval_sh_jacobi_ptr[2*3] +ufunc_eval_sh_jacobi_data[4] = &ufunc_eval_sh_jacobi_ptr[2*4] +eval_sh_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_jacobi_loops, ufunc_eval_sh_jacobi_data, ufunc_eval_sh_jacobi_types, 5, 4, 1, 0, "eval_sh_jacobi", ufunc_eval_sh_jacobi_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_eval_sh_legendre_loops[5] +cdef void *ufunc_eval_sh_legendre_ptr[10] +cdef void *ufunc_eval_sh_legendre_data[5] +cdef char ufunc_eval_sh_legendre_types[15] +cdef char *ufunc_eval_sh_legendre_doc = ( + "eval_sh_legendre(n, x, out=None)\n" + "\n" + "Evaluate shifted Legendre polynomial at a point.\n" + "\n" + "These polynomials are defined as\n" + "\n" + ".. math::\n" + "\n" + " P_n^*(x) = P_n(2x - 1)\n" + "\n" + "where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_\n" + "for details.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Degree of the polynomial. If not an integer, the value is\n" + " determined via the relation to `eval_legendre`.\n" + "x : array_like\n" + " Points at which to evaluate the shifted Legendre polynomial\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "P : scalar or ndarray\n" + " Values of the shifted Legendre polynomial\n" + "\n" + "See Also\n" + "--------\n" + "roots_sh_legendre : roots and quadrature weights of shifted\n" + " Legendre polynomials\n" + "sh_legendre : shifted Legendre polynomial object\n" + "eval_legendre : evaluate Legendre polynomials\n" + "numpy.polynomial.legendre.Legendre : Legendre series\n" + "\n" + "References\n" + "----------\n" + ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.") +ufunc_eval_sh_legendre_loops[0] = loop_d_pd__As_pd_d +ufunc_eval_sh_legendre_loops[1] = loop_d_dd__As_ff_f +ufunc_eval_sh_legendre_loops[2] = loop_D_dD__As_fF_F +ufunc_eval_sh_legendre_loops[3] = loop_d_dd__As_dd_d +ufunc_eval_sh_legendre_loops[4] = loop_D_dD__As_dD_D +ufunc_eval_sh_legendre_types[0] = NPY_INTP +ufunc_eval_sh_legendre_types[1] = NPY_DOUBLE +ufunc_eval_sh_legendre_types[2] = NPY_DOUBLE +ufunc_eval_sh_legendre_types[3] = NPY_FLOAT +ufunc_eval_sh_legendre_types[4] = NPY_FLOAT +ufunc_eval_sh_legendre_types[5] = NPY_FLOAT +ufunc_eval_sh_legendre_types[6] = NPY_FLOAT +ufunc_eval_sh_legendre_types[7] = NPY_CFLOAT +ufunc_eval_sh_legendre_types[8] = NPY_CFLOAT +ufunc_eval_sh_legendre_types[9] = NPY_DOUBLE +ufunc_eval_sh_legendre_types[10] = NPY_DOUBLE +ufunc_eval_sh_legendre_types[11] = NPY_DOUBLE +ufunc_eval_sh_legendre_types[12] = NPY_DOUBLE +ufunc_eval_sh_legendre_types[13] = NPY_CDOUBLE +ufunc_eval_sh_legendre_types[14] = NPY_CDOUBLE +ufunc_eval_sh_legendre_ptr[2*0] = _func_eval_sh_legendre_l +ufunc_eval_sh_legendre_ptr[2*0+1] = ("eval_sh_legendre") +ufunc_eval_sh_legendre_ptr[2*1] = _func_eval_sh_legendre[double] +ufunc_eval_sh_legendre_ptr[2*1+1] = ("eval_sh_legendre") +ufunc_eval_sh_legendre_ptr[2*2] = _func_eval_sh_legendre[double_complex] +ufunc_eval_sh_legendre_ptr[2*2+1] = ("eval_sh_legendre") +ufunc_eval_sh_legendre_ptr[2*3] = _func_eval_sh_legendre[double] +ufunc_eval_sh_legendre_ptr[2*3+1] = ("eval_sh_legendre") +ufunc_eval_sh_legendre_ptr[2*4] = _func_eval_sh_legendre[double_complex] +ufunc_eval_sh_legendre_ptr[2*4+1] = ("eval_sh_legendre") +ufunc_eval_sh_legendre_data[0] = &ufunc_eval_sh_legendre_ptr[2*0] +ufunc_eval_sh_legendre_data[1] = &ufunc_eval_sh_legendre_ptr[2*1] +ufunc_eval_sh_legendre_data[2] = &ufunc_eval_sh_legendre_ptr[2*2] +ufunc_eval_sh_legendre_data[3] = &ufunc_eval_sh_legendre_ptr[2*3] +ufunc_eval_sh_legendre_data[4] = &ufunc_eval_sh_legendre_ptr[2*4] +eval_sh_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_legendre_loops, ufunc_eval_sh_legendre_data, ufunc_eval_sh_legendre_types, 5, 2, 1, 0, "eval_sh_legendre", ufunc_eval_sh_legendre_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_exp10_loops[2] +cdef void *ufunc_exp10_ptr[4] +cdef void *ufunc_exp10_data[2] +cdef char ufunc_exp10_types[4] +cdef char *ufunc_exp10_doc = ( + "exp10(x, out=None)\n" + "\n" + "Compute ``10**x`` element-wise.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " `x` must contain real numbers.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " ``10**x``, computed element-wise.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import exp10\n" + "\n" + ">>> exp10(3)\n" + "1000.0\n" + ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n" + ">>> exp10(x)\n" + "array([[ 0.1 , 0.31622777, 1. ],\n" + " [ 3.16227766, 10. , 31.6227766 ]])") +ufunc_exp10_loops[0] = loop_d_d__As_f_f +ufunc_exp10_loops[1] = loop_d_d__As_d_d +ufunc_exp10_types[0] = NPY_FLOAT +ufunc_exp10_types[1] = NPY_FLOAT +ufunc_exp10_types[2] = NPY_DOUBLE +ufunc_exp10_types[3] = NPY_DOUBLE +ufunc_exp10_ptr[2*0] = _func_cephes_exp10 +ufunc_exp10_ptr[2*0+1] = ("exp10") +ufunc_exp10_ptr[2*1] = _func_cephes_exp10 +ufunc_exp10_ptr[2*1+1] = ("exp10") +ufunc_exp10_data[0] = &ufunc_exp10_ptr[2*0] +ufunc_exp10_data[1] = &ufunc_exp10_ptr[2*1] +exp10 = np.PyUFunc_FromFuncAndData(ufunc_exp10_loops, ufunc_exp10_data, ufunc_exp10_types, 2, 1, 1, 0, "exp10", ufunc_exp10_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_exp2_loops[2] +cdef void *ufunc_exp2_ptr[4] +cdef void *ufunc_exp2_data[2] +cdef char ufunc_exp2_types[4] +cdef char *ufunc_exp2_doc = ( + "exp2(x, out=None)\n" + "\n" + "Compute ``2**x`` element-wise.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " `x` must contain real numbers.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " ``2**x``, computed element-wise.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import exp2\n" + "\n" + ">>> exp2(3)\n" + "8.0\n" + ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n" + ">>> exp2(x)\n" + "array([[ 0.5 , 0.70710678, 1. ],\n" + " [ 1.41421356, 2. , 2.82842712]])") +ufunc_exp2_loops[0] = loop_d_d__As_f_f +ufunc_exp2_loops[1] = loop_d_d__As_d_d +ufunc_exp2_types[0] = NPY_FLOAT +ufunc_exp2_types[1] = NPY_FLOAT +ufunc_exp2_types[2] = NPY_DOUBLE +ufunc_exp2_types[3] = NPY_DOUBLE +ufunc_exp2_ptr[2*0] = _func_cephes_exp2 +ufunc_exp2_ptr[2*0+1] = ("exp2") +ufunc_exp2_ptr[2*1] = _func_cephes_exp2 +ufunc_exp2_ptr[2*1+1] = ("exp2") +ufunc_exp2_data[0] = &ufunc_exp2_ptr[2*0] +ufunc_exp2_data[1] = &ufunc_exp2_ptr[2*1] +exp2 = np.PyUFunc_FromFuncAndData(ufunc_exp2_loops, ufunc_exp2_data, ufunc_exp2_types, 2, 1, 1, 0, "exp2", ufunc_exp2_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_expm1_loops[4] +cdef void *ufunc_expm1_ptr[8] +cdef void *ufunc_expm1_data[4] +cdef char ufunc_expm1_types[8] +cdef char *ufunc_expm1_doc = ( + "expm1(x, out=None)\n" + "\n" + "Compute ``exp(x) - 1``.\n" + "\n" + "When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation\n" + "of ``exp(x) - 1`` can suffer from catastrophic loss of precision.\n" + "``expm1(x)`` is implemented to avoid the loss of precision that occurs when\n" + "`x` is near zero.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " `x` must contain real numbers.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " ``exp(x) - 1`` computed element-wise.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import expm1\n" + "\n" + ">>> expm1(1.0)\n" + "1.7182818284590451\n" + ">>> expm1([-0.2, -0.1, 0, 0.1, 0.2])\n" + "array([-0.18126925, -0.09516258, 0. , 0.10517092, 0.22140276])\n" + "\n" + "The exact value of ``exp(7.5e-13) - 1`` is::\n" + "\n" + " 7.5000000000028125000000007031250000001318...*10**-13.\n" + "\n" + "Here is what ``expm1(7.5e-13)`` gives:\n" + "\n" + ">>> expm1(7.5e-13)\n" + "7.5000000000028135e-13\n" + "\n" + "Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in\n" + "a \"catastrophic\" loss of precision:\n" + "\n" + ">>> np.exp(7.5e-13) - 1\n" + "7.5006667543675576e-13") +ufunc_expm1_loops[0] = loop_d_d__As_f_f +ufunc_expm1_loops[1] = loop_d_d__As_d_d +ufunc_expm1_loops[2] = loop_D_D__As_F_F +ufunc_expm1_loops[3] = loop_D_D__As_D_D +ufunc_expm1_types[0] = NPY_FLOAT +ufunc_expm1_types[1] = NPY_FLOAT +ufunc_expm1_types[2] = NPY_DOUBLE +ufunc_expm1_types[3] = NPY_DOUBLE +ufunc_expm1_types[4] = NPY_CFLOAT +ufunc_expm1_types[5] = NPY_CFLOAT +ufunc_expm1_types[6] = NPY_CDOUBLE +ufunc_expm1_types[7] = NPY_CDOUBLE +ufunc_expm1_ptr[2*0] = _func_cephes_expm1 +ufunc_expm1_ptr[2*0+1] = ("expm1") +ufunc_expm1_ptr[2*1] = _func_cephes_expm1 +ufunc_expm1_ptr[2*1+1] = ("expm1") +ufunc_expm1_ptr[2*2] = _func_cexpm1 +ufunc_expm1_ptr[2*2+1] = ("expm1") +ufunc_expm1_ptr[2*3] = _func_cexpm1 +ufunc_expm1_ptr[2*3+1] = ("expm1") +ufunc_expm1_data[0] = &ufunc_expm1_ptr[2*0] +ufunc_expm1_data[1] = &ufunc_expm1_ptr[2*1] +ufunc_expm1_data[2] = &ufunc_expm1_ptr[2*2] +ufunc_expm1_data[3] = &ufunc_expm1_ptr[2*3] +expm1 = np.PyUFunc_FromFuncAndData(ufunc_expm1_loops, ufunc_expm1_data, ufunc_expm1_types, 4, 1, 1, 0, "expm1", ufunc_expm1_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_expn_loops[3] +cdef void *ufunc_expn_ptr[6] +cdef void *ufunc_expn_data[3] +cdef char ufunc_expn_types[9] +cdef char *ufunc_expn_doc = ( + "expn(n, x, out=None)\n" + "\n" + "Generalized exponential integral En.\n" + "\n" + "For integer :math:`n \\geq 0` and real :math:`x \\geq 0` the\n" + "generalized exponential integral is defined as [dlmf]_\n" + "\n" + ".. math::\n" + "\n" + " E_n(x) = x^{n - 1} \\int_x^\\infty \\frac{e^{-t}}{t^n} dt.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Non-negative integers\n" + "x : array_like\n" + " Real argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the generalized exponential integral\n" + "\n" + "See Also\n" + "--------\n" + "exp1 : special case of :math:`E_n` for :math:`n = 1`\n" + "expi : related to :math:`E_n` when :math:`n = 1`\n" + "\n" + "References\n" + "----------\n" + ".. [dlmf] Digital Library of Mathematical Functions, 8.19.2\n" + " https://dlmf.nist.gov/8.19#E2\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "Its domain is nonnegative n and x.\n" + "\n" + ">>> sc.expn(-1, 1.0), sc.expn(1, -1.0)\n" + "(nan, nan)\n" + "\n" + "It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it\n" + "is equal to ``1 / (n - 1)``.\n" + "\n" + ">>> sc.expn([0, 1, 2, 3, 4], 0)\n" + "array([ inf, inf, 1. , 0.5 , 0.33333333])\n" + "\n" + "For n equal to 0 it reduces to ``exp(-x) / x``.\n" + "\n" + ">>> x = np.array([1, 2, 3, 4])\n" + ">>> sc.expn(0, x)\n" + "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n" + ">>> np.exp(-x) / x\n" + "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n" + "\n" + "For n equal to 1 it reduces to `exp1`.\n" + "\n" + ">>> sc.expn(1, x)\n" + "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])\n" + ">>> sc.exp1(x)\n" + "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])") +ufunc_expn_loops[0] = loop_d_pd__As_pd_d +ufunc_expn_loops[1] = loop_d_dd__As_ff_f +ufunc_expn_loops[2] = loop_d_dd__As_dd_d +ufunc_expn_types[0] = NPY_INTP +ufunc_expn_types[1] = NPY_DOUBLE +ufunc_expn_types[2] = NPY_DOUBLE +ufunc_expn_types[3] = NPY_FLOAT +ufunc_expn_types[4] = NPY_FLOAT +ufunc_expn_types[5] = NPY_FLOAT +ufunc_expn_types[6] = NPY_DOUBLE +ufunc_expn_types[7] = NPY_DOUBLE +ufunc_expn_types[8] = NPY_DOUBLE +ufunc_expn_ptr[2*0] = _func_cephes_expn_wrap +ufunc_expn_ptr[2*0+1] = ("expn") +ufunc_expn_ptr[2*1] = _func_expn_unsafe +ufunc_expn_ptr[2*1+1] = ("expn") +ufunc_expn_ptr[2*2] = _func_expn_unsafe +ufunc_expn_ptr[2*2+1] = ("expn") +ufunc_expn_data[0] = &ufunc_expn_ptr[2*0] +ufunc_expn_data[1] = &ufunc_expn_ptr[2*1] +ufunc_expn_data[2] = &ufunc_expn_ptr[2*2] +expn = np.PyUFunc_FromFuncAndData(ufunc_expn_loops, ufunc_expn_data, ufunc_expn_types, 3, 2, 1, 0, "expn", ufunc_expn_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_fdtr_loops[2] +cdef void *ufunc_fdtr_ptr[4] +cdef void *ufunc_fdtr_data[2] +cdef char ufunc_fdtr_types[8] +cdef char *ufunc_fdtr_doc = ( + "fdtr(dfn, dfd, x, out=None)\n" + "\n" + "F cumulative distribution function.\n" + "\n" + "Returns the value of the cumulative distribution function of the\n" + "F-distribution, also known as Snedecor's F-distribution or the\n" + "Fisher-Snedecor distribution.\n" + "\n" + "The F-distribution with parameters :math:`d_n` and :math:`d_d` is the\n" + "distribution of the random variable,\n" + "\n" + ".. math::\n" + " X = \\frac{U_n/d_n}{U_d/d_d},\n" + "\n" + "where :math:`U_n` and :math:`U_d` are random variables distributed\n" + ":math:`\\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom,\n" + "respectively.\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " First parameter (positive float).\n" + "dfd : array_like\n" + " Second parameter (positive float).\n" + "x : array_like\n" + " Argument (nonnegative float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "y : scalar or ndarray\n" + " The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`.\n" + "\n" + "See Also\n" + "--------\n" + "fdtrc : F distribution survival function\n" + "fdtri : F distribution inverse cumulative distribution\n" + "scipy.stats.f : F distribution\n" + "\n" + "Notes\n" + "-----\n" + "The regularized incomplete beta function is used, according to the\n" + "formula,\n" + "\n" + ".. math::\n" + " F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also\n" + "available as `scipy.stats.f`. Calling `fdtr` directly can improve\n" + "performance compared to the ``cdf`` method of `scipy.stats.f` (see last\n" + "example below).\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import fdtr\n" + ">>> fdtr(1, 2, 1)\n" + "0.5773502691896258\n" + "\n" + "Calculate the function at several points by providing a NumPy array for\n" + "`x`.\n" + "\n" + ">>> x = np.array([0.5, 2., 3.])\n" + ">>> fdtr(1, 2, x)\n" + "array([0.4472136 , 0.70710678, 0.77459667])\n" + "\n" + "Plot the function for several parameter sets.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> dfn_parameters = [1, 5, 10, 50]\n" + ">>> dfd_parameters = [1, 1, 2, 3]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n" + "... linestyles))\n" + ">>> x = np.linspace(0, 30, 1000)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> for parameter_set in parameters_list:\n" + "... dfn, dfd, style = parameter_set\n" + "... fdtr_vals = fdtr(dfn, dfd, x)\n" + "... ax.plot(x, fdtr_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n" + "... ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_xlabel(\"$x$\")\n" + ">>> ax.set_title(\"F distribution cumulative distribution function\")\n" + ">>> plt.show()\n" + "\n" + "The F distribution is also available as `scipy.stats.f`. Using `fdtr`\n" + "directly can be much faster than calling the ``cdf`` method of\n" + "`scipy.stats.f`, especially for small arrays or individual values.\n" + "To get the same results one must use the following parametrization:\n" + "``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``.\n" + "\n" + ">>> from scipy.stats import f\n" + ">>> dfn, dfd = 1, 2\n" + ">>> x = 1\n" + ">>> fdtr_res = fdtr(dfn, dfd, x) # this will often be faster than below\n" + ">>> f_dist_res = f(dfn, dfd).cdf(x)\n" + ">>> fdtr_res == f_dist_res # test that results are equal\n" + "True") +ufunc_fdtr_loops[0] = loop_d_ddd__As_fff_f +ufunc_fdtr_loops[1] = loop_d_ddd__As_ddd_d +ufunc_fdtr_types[0] = NPY_FLOAT +ufunc_fdtr_types[1] = NPY_FLOAT +ufunc_fdtr_types[2] = NPY_FLOAT +ufunc_fdtr_types[3] = NPY_FLOAT +ufunc_fdtr_types[4] = NPY_DOUBLE +ufunc_fdtr_types[5] = NPY_DOUBLE +ufunc_fdtr_types[6] = NPY_DOUBLE +ufunc_fdtr_types[7] = NPY_DOUBLE +ufunc_fdtr_ptr[2*0] = _func_xsf_fdtr +ufunc_fdtr_ptr[2*0+1] = ("fdtr") +ufunc_fdtr_ptr[2*1] = _func_xsf_fdtr +ufunc_fdtr_ptr[2*1+1] = ("fdtr") +ufunc_fdtr_data[0] = &ufunc_fdtr_ptr[2*0] +ufunc_fdtr_data[1] = &ufunc_fdtr_ptr[2*1] +fdtr = np.PyUFunc_FromFuncAndData(ufunc_fdtr_loops, ufunc_fdtr_data, ufunc_fdtr_types, 2, 3, 1, 0, "fdtr", ufunc_fdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_fdtrc_loops[2] +cdef void *ufunc_fdtrc_ptr[4] +cdef void *ufunc_fdtrc_data[2] +cdef char ufunc_fdtrc_types[8] +cdef char *ufunc_fdtrc_doc = ( + "fdtrc(dfn, dfd, x, out=None)\n" + "\n" + "F survival function.\n" + "\n" + "Returns the complemented F-distribution function (the integral of the\n" + "density from `x` to infinity).\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " First parameter (positive float).\n" + "dfd : array_like\n" + " Second parameter (positive float).\n" + "x : array_like\n" + " Argument (nonnegative float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "y : scalar or ndarray\n" + " The complemented F-distribution function with parameters `dfn` and\n" + " `dfd` at `x`.\n" + "\n" + "See Also\n" + "--------\n" + "fdtr : F distribution cumulative distribution function\n" + "fdtri : F distribution inverse cumulative distribution function\n" + "scipy.stats.f : F distribution\n" + "\n" + "Notes\n" + "-----\n" + "The regularized incomplete beta function is used, according to the\n" + "formula,\n" + "\n" + ".. math::\n" + " F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also\n" + "available as `scipy.stats.f`. Calling `fdtrc` directly can improve\n" + "performance compared to the ``sf`` method of `scipy.stats.f` (see last\n" + "example below).\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import fdtrc\n" + ">>> fdtrc(1, 2, 1)\n" + "0.42264973081037427\n" + "\n" + "Calculate the function at several points by providing a NumPy array for\n" + "`x`.\n" + "\n" + ">>> x = np.array([0.5, 2., 3.])\n" + ">>> fdtrc(1, 2, x)\n" + "array([0.5527864 , 0.29289322, 0.22540333])\n" + "\n" + "Plot the function for several parameter sets.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> dfn_parameters = [1, 5, 10, 50]\n" + ">>> dfd_parameters = [1, 1, 2, 3]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n" + "... linestyles))\n" + ">>> x = np.linspace(0, 30, 1000)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> for parameter_set in parameters_list:\n" + "... dfn, dfd, style = parameter_set\n" + "... fdtrc_vals = fdtrc(dfn, dfd, x)\n" + "... ax.plot(x, fdtrc_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n" + "... ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_xlabel(\"$x$\")\n" + ">>> ax.set_title(\"F distribution survival function\")\n" + ">>> plt.show()\n" + "\n" + "The F distribution is also available as `scipy.stats.f`. Using `fdtrc`\n" + "directly can be much faster than calling the ``sf`` method of\n" + "`scipy.stats.f`, especially for small arrays or individual values.\n" + "To get the same results one must use the following parametrization:\n" + "``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``.\n" + "\n" + ">>> from scipy.stats import f\n" + ">>> dfn, dfd = 1, 2\n" + ">>> x = 1\n" + ">>> fdtrc_res = fdtrc(dfn, dfd, x) # this will often be faster than below\n" + ">>> f_dist_res = f(dfn, dfd).sf(x)\n" + ">>> f_dist_res == fdtrc_res # test that results are equal\n" + "True") +ufunc_fdtrc_loops[0] = loop_d_ddd__As_fff_f +ufunc_fdtrc_loops[1] = loop_d_ddd__As_ddd_d +ufunc_fdtrc_types[0] = NPY_FLOAT +ufunc_fdtrc_types[1] = NPY_FLOAT +ufunc_fdtrc_types[2] = NPY_FLOAT +ufunc_fdtrc_types[3] = NPY_FLOAT +ufunc_fdtrc_types[4] = NPY_DOUBLE +ufunc_fdtrc_types[5] = NPY_DOUBLE +ufunc_fdtrc_types[6] = NPY_DOUBLE +ufunc_fdtrc_types[7] = NPY_DOUBLE +ufunc_fdtrc_ptr[2*0] = _func_xsf_fdtrc +ufunc_fdtrc_ptr[2*0+1] = ("fdtrc") +ufunc_fdtrc_ptr[2*1] = _func_xsf_fdtrc +ufunc_fdtrc_ptr[2*1+1] = ("fdtrc") +ufunc_fdtrc_data[0] = &ufunc_fdtrc_ptr[2*0] +ufunc_fdtrc_data[1] = &ufunc_fdtrc_ptr[2*1] +fdtrc = np.PyUFunc_FromFuncAndData(ufunc_fdtrc_loops, ufunc_fdtrc_data, ufunc_fdtrc_types, 2, 3, 1, 0, "fdtrc", ufunc_fdtrc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_fdtri_loops[2] +cdef void *ufunc_fdtri_ptr[4] +cdef void *ufunc_fdtri_data[2] +cdef char ufunc_fdtri_types[8] +cdef char *ufunc_fdtri_doc = ( + "fdtri(dfn, dfd, p, out=None)\n" + "\n" + "The `p`-th quantile of the F-distribution.\n" + "\n" + "This function is the inverse of the F-distribution CDF, `fdtr`, returning\n" + "the `x` such that `fdtr(dfn, dfd, x) = p`.\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " First parameter (positive float).\n" + "dfd : array_like\n" + " Second parameter (positive float).\n" + "p : array_like\n" + " Cumulative probability, in [0, 1].\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " The quantile corresponding to `p`.\n" + "\n" + "See Also\n" + "--------\n" + "fdtr : F distribution cumulative distribution function\n" + "fdtrc : F distribution survival function\n" + "scipy.stats.f : F distribution\n" + "\n" + "Notes\n" + "-----\n" + "The computation is carried out using the relation to the inverse\n" + "regularized beta function, :math:`I^{-1}_x(a, b)`. Let\n" + ":math:`z = I^{-1}_p(d_d/2, d_n/2).` Then,\n" + "\n" + ".. math::\n" + " x = \\frac{d_d (1 - z)}{d_n z}.\n" + "\n" + "If `p` is such that :math:`x < 0.5`, the following relation is used\n" + "instead for improved stability: let\n" + ":math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then,\n" + "\n" + ".. math::\n" + " x = \\frac{d_d z'}{d_n (1 - z')}.\n" + "\n" + "Wrapper for the Cephes [1]_ routine `fdtri`.\n" + "\n" + "The F distribution is also available as `scipy.stats.f`. Calling\n" + "`fdtri` directly can improve performance compared to the ``ppf``\n" + "method of `scipy.stats.f` (see last example below).\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "`fdtri` represents the inverse of the F distribution CDF which is\n" + "available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2``\n" + "at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`,\n" + "`df2` and the computed CDF value.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import fdtri, fdtr\n" + ">>> df1, df2 = 1, 2\n" + ">>> x = 3\n" + ">>> cdf_value = fdtr(df1, df2, x)\n" + ">>> fdtri(df1, df2, cdf_value)\n" + "3.000000000000006\n" + "\n" + "Calculate the function at several points by providing a NumPy array for\n" + "`x`.\n" + "\n" + ">>> x = np.array([0.1, 0.4, 0.7])\n" + ">>> fdtri(1, 2, x)\n" + "array([0.02020202, 0.38095238, 1.92156863])\n" + "\n" + "Plot the function for several parameter sets.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> dfn_parameters = [50, 10, 1, 50]\n" + ">>> dfd_parameters = [0.5, 1, 1, 5]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n" + "... linestyles))\n" + ">>> x = np.linspace(0, 1, 1000)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> for parameter_set in parameters_list:\n" + "... dfn, dfd, style = parameter_set\n" + "... fdtri_vals = fdtri(dfn, dfd, x)\n" + "... ax.plot(x, fdtri_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n" + "... ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_xlabel(\"$x$\")\n" + ">>> title = \"F distribution inverse cumulative distribution function\"\n" + ">>> ax.set_title(title)\n" + ">>> ax.set_ylim(0, 30)\n" + ">>> plt.show()\n" + "\n" + "The F distribution is also available as `scipy.stats.f`. Using `fdtri`\n" + "directly can be much faster than calling the ``ppf`` method of\n" + "`scipy.stats.f`, especially for small arrays or individual values.\n" + "To get the same results one must use the following parametrization:\n" + "``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``.\n" + "\n" + ">>> from scipy.stats import f\n" + ">>> dfn, dfd = 1, 2\n" + ">>> x = 0.7\n" + ">>> fdtri_res = fdtri(dfn, dfd, x) # this will often be faster than below\n" + ">>> f_dist_res = f(dfn, dfd).ppf(x)\n" + ">>> f_dist_res == fdtri_res # test that results are equal\n" + "True") +ufunc_fdtri_loops[0] = loop_d_ddd__As_fff_f +ufunc_fdtri_loops[1] = loop_d_ddd__As_ddd_d +ufunc_fdtri_types[0] = NPY_FLOAT +ufunc_fdtri_types[1] = NPY_FLOAT +ufunc_fdtri_types[2] = NPY_FLOAT +ufunc_fdtri_types[3] = NPY_FLOAT +ufunc_fdtri_types[4] = NPY_DOUBLE +ufunc_fdtri_types[5] = NPY_DOUBLE +ufunc_fdtri_types[6] = NPY_DOUBLE +ufunc_fdtri_types[7] = NPY_DOUBLE +ufunc_fdtri_ptr[2*0] = _func_xsf_fdtri +ufunc_fdtri_ptr[2*0+1] = ("fdtri") +ufunc_fdtri_ptr[2*1] = _func_xsf_fdtri +ufunc_fdtri_ptr[2*1+1] = ("fdtri") +ufunc_fdtri_data[0] = &ufunc_fdtri_ptr[2*0] +ufunc_fdtri_data[1] = &ufunc_fdtri_ptr[2*1] +fdtri = np.PyUFunc_FromFuncAndData(ufunc_fdtri_loops, ufunc_fdtri_data, ufunc_fdtri_types, 2, 3, 1, 0, "fdtri", ufunc_fdtri_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_fdtridfd_loops[2] +cdef void *ufunc_fdtridfd_ptr[4] +cdef void *ufunc_fdtridfd_data[2] +cdef char ufunc_fdtridfd_types[8] +cdef char *ufunc_fdtridfd_doc = ( + "fdtridfd(dfn, p, x, out=None)\n" + "\n" + "Inverse to `fdtr` vs dfd\n" + "\n" + "Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``.\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " First parameter (positive float).\n" + "p : array_like\n" + " Cumulative probability, in [0, 1].\n" + "x : array_like\n" + " Argument (nonnegative float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "dfd : scalar or ndarray\n" + " `dfd` such that ``fdtr(dfn, dfd, x) == p``.\n" + "\n" + "See Also\n" + "--------\n" + "fdtr : F distribution cumulative distribution function\n" + "fdtrc : F distribution survival function\n" + "fdtri : F distribution quantile function\n" + "scipy.stats.f : F distribution\n" + "\n" + "Examples\n" + "--------\n" + "Compute the F distribution cumulative distribution function for one\n" + "parameter set.\n" + "\n" + ">>> from scipy.special import fdtridfd, fdtr\n" + ">>> dfn, dfd, x = 10, 5, 2\n" + ">>> cdf_value = fdtr(dfn, dfd, x)\n" + ">>> cdf_value\n" + "0.7700248806501017\n" + "\n" + "Verify that `fdtridfd` recovers the original value for `dfd`:\n" + "\n" + ">>> fdtridfd(dfn, cdf_value, x)\n" + "5.0") +ufunc_fdtridfd_loops[0] = loop_d_ddd__As_fff_f +ufunc_fdtridfd_loops[1] = loop_d_ddd__As_ddd_d +ufunc_fdtridfd_types[0] = NPY_FLOAT +ufunc_fdtridfd_types[1] = NPY_FLOAT +ufunc_fdtridfd_types[2] = NPY_FLOAT +ufunc_fdtridfd_types[3] = NPY_FLOAT +ufunc_fdtridfd_types[4] = NPY_DOUBLE +ufunc_fdtridfd_types[5] = NPY_DOUBLE +ufunc_fdtridfd_types[6] = NPY_DOUBLE +ufunc_fdtridfd_types[7] = NPY_DOUBLE +ufunc_fdtridfd_ptr[2*0] = _func_fdtridfd +ufunc_fdtridfd_ptr[2*0+1] = ("fdtridfd") +ufunc_fdtridfd_ptr[2*1] = _func_fdtridfd +ufunc_fdtridfd_ptr[2*1+1] = ("fdtridfd") +ufunc_fdtridfd_data[0] = &ufunc_fdtridfd_ptr[2*0] +ufunc_fdtridfd_data[1] = &ufunc_fdtridfd_ptr[2*1] +fdtridfd = np.PyUFunc_FromFuncAndData(ufunc_fdtridfd_loops, ufunc_fdtridfd_data, ufunc_fdtridfd_types, 2, 3, 1, 0, "fdtridfd", ufunc_fdtridfd_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_gdtr_loops[2] +cdef void *ufunc_gdtr_ptr[4] +cdef void *ufunc_gdtr_data[2] +cdef char ufunc_gdtr_types[8] +cdef char *ufunc_gdtr_doc = ( + "gdtr(a, b, x, out=None)\n" + "\n" + "Gamma distribution cumulative distribution function.\n" + "\n" + "Returns the integral from zero to `x` of the gamma probability density\n" + "function,\n" + "\n" + ".. math::\n" + "\n" + " F = \\int_0^x \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n" + "\n" + "where :math:`\\Gamma` is the gamma function.\n" + "\n" + "Parameters\n" + "----------\n" + "a : array_like\n" + " The rate parameter of the gamma distribution, sometimes denoted\n" + " :math:`\\beta` (float). It is also the reciprocal of the scale\n" + " parameter :math:`\\theta`.\n" + "b : array_like\n" + " The shape parameter of the gamma distribution, sometimes denoted\n" + " :math:`\\alpha` (float).\n" + "x : array_like\n" + " The quantile (upper limit of integration; float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "F : scalar or ndarray\n" + " The CDF of the gamma distribution with parameters `a` and `b`\n" + " evaluated at `x`.\n" + "\n" + "See Also\n" + "--------\n" + "gdtrc : 1 - CDF of the gamma distribution.\n" + "scipy.stats.gamma: Gamma distribution\n" + "\n" + "Notes\n" + "-----\n" + "The evaluation is carried out using the relation to the incomplete gamma\n" + "integral (regularized gamma function).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can\n" + "improve performance compared to the ``cdf`` method of `scipy.stats.gamma`\n" + "(see last example below).\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "Compute the function for ``a=1``, ``b=2`` at ``x=5``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import gdtr\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> gdtr(1., 2., 5.)\n" + "0.9595723180054873\n" + "\n" + "Compute the function for ``a=1`` and ``b=2`` at several points by\n" + "providing a NumPy array for `x`.\n" + "\n" + ">>> xvalues = np.array([1., 2., 3., 4])\n" + ">>> gdtr(1., 1., xvalues)\n" + "array([0.63212056, 0.86466472, 0.95021293, 0.98168436])\n" + "\n" + "`gdtr` can evaluate different parameter sets by providing arrays with\n" + "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n" + "function for three different `a` at four positions `x` and ``b=3``,\n" + "resulting in a 3x4 array.\n" + "\n" + ">>> a = np.array([[0.5], [1.5], [2.5]])\n" + ">>> x = np.array([1., 2., 3., 4])\n" + ">>> a.shape, x.shape\n" + "((3, 1), (4,))\n" + "\n" + ">>> gdtr(a, 3., x)\n" + "array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358],\n" + " [0.19115317, 0.57680992, 0.82642193, 0.9380312 ],\n" + " [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]])\n" + "\n" + "Plot the function for four different parameter sets.\n" + "\n" + ">>> a_parameters = [0.3, 1, 2, 6]\n" + ">>> b_parameters = [2, 10, 15, 20]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n" + ">>> x = np.linspace(0, 30, 1000)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> for parameter_set in parameters_list:\n" + "... a, b, style = parameter_set\n" + "... gdtr_vals = gdtr(a, b, x)\n" + "... ax.plot(x, gdtr_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_xlabel(\"$x$\")\n" + ">>> ax.set_title(\"Gamma distribution cumulative distribution function\")\n" + ">>> plt.show()\n" + "\n" + "The gamma distribution is also available as `scipy.stats.gamma`. Using\n" + "`gdtr` directly can be much faster than calling the ``cdf`` method of\n" + "`scipy.stats.gamma`, especially for small arrays or individual values.\n" + "To get the same results one must use the following parametrization:\n" + "``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``.\n" + "\n" + ">>> from scipy.stats import gamma\n" + ">>> a = 2.\n" + ">>> b = 3\n" + ">>> x = 1.\n" + ">>> gdtr_result = gdtr(a, b, x) # this will often be faster than below\n" + ">>> gamma_dist_result = gamma(b, scale=1/a).cdf(x)\n" + ">>> gdtr_result == gamma_dist_result # test that results are equal\n" + "True") +ufunc_gdtr_loops[0] = loop_d_ddd__As_fff_f +ufunc_gdtr_loops[1] = loop_d_ddd__As_ddd_d +ufunc_gdtr_types[0] = NPY_FLOAT +ufunc_gdtr_types[1] = NPY_FLOAT +ufunc_gdtr_types[2] = NPY_FLOAT +ufunc_gdtr_types[3] = NPY_FLOAT +ufunc_gdtr_types[4] = NPY_DOUBLE +ufunc_gdtr_types[5] = NPY_DOUBLE +ufunc_gdtr_types[6] = NPY_DOUBLE +ufunc_gdtr_types[7] = NPY_DOUBLE +ufunc_gdtr_ptr[2*0] = _func_xsf_gdtr +ufunc_gdtr_ptr[2*0+1] = ("gdtr") +ufunc_gdtr_ptr[2*1] = _func_xsf_gdtr +ufunc_gdtr_ptr[2*1+1] = ("gdtr") +ufunc_gdtr_data[0] = &ufunc_gdtr_ptr[2*0] +ufunc_gdtr_data[1] = &ufunc_gdtr_ptr[2*1] +gdtr = np.PyUFunc_FromFuncAndData(ufunc_gdtr_loops, ufunc_gdtr_data, ufunc_gdtr_types, 2, 3, 1, 0, "gdtr", ufunc_gdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_gdtrc_loops[2] +cdef void *ufunc_gdtrc_ptr[4] +cdef void *ufunc_gdtrc_data[2] +cdef char ufunc_gdtrc_types[8] +cdef char *ufunc_gdtrc_doc = ( + "gdtrc(a, b, x, out=None)\n" + "\n" + "Gamma distribution survival function.\n" + "\n" + "Integral from `x` to infinity of the gamma probability density function,\n" + "\n" + ".. math::\n" + "\n" + " F = \\int_x^\\infty \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n" + "\n" + "where :math:`\\Gamma` is the gamma function.\n" + "\n" + "Parameters\n" + "----------\n" + "a : array_like\n" + " The rate parameter of the gamma distribution, sometimes denoted\n" + " :math:`\\beta` (float). It is also the reciprocal of the scale\n" + " parameter :math:`\\theta`.\n" + "b : array_like\n" + " The shape parameter of the gamma distribution, sometimes denoted\n" + " :math:`\\alpha` (float).\n" + "x : array_like\n" + " The quantile (lower limit of integration; float).\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "F : scalar or ndarray\n" + " The survival function of the gamma distribution with parameters `a`\n" + " and `b` evaluated at `x`.\n" + "\n" + "See Also\n" + "--------\n" + "gdtr: Gamma distribution cumulative distribution function\n" + "scipy.stats.gamma: Gamma distribution\n" + "gdtrix\n" + "\n" + "Notes\n" + "-----\n" + "The evaluation is carried out using the relation to the incomplete gamma\n" + "integral (regularized gamma function).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can\n" + "improve performance compared to the ``sf`` method of `scipy.stats.gamma`\n" + "(see last example below).\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "Compute the function for ``a=1`` and ``b=2`` at ``x=5``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import gdtrc\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> gdtrc(1., 2., 5.)\n" + "0.04042768199451279\n" + "\n" + "Compute the function for ``a=1``, ``b=2`` at several points by providing\n" + "a NumPy array for `x`.\n" + "\n" + ">>> xvalues = np.array([1., 2., 3., 4])\n" + ">>> gdtrc(1., 1., xvalues)\n" + "array([0.36787944, 0.13533528, 0.04978707, 0.01831564])\n" + "\n" + "`gdtrc` can evaluate different parameter sets by providing arrays with\n" + "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n" + "function for three different `a` at four positions `x` and ``b=3``,\n" + "resulting in a 3x4 array.\n" + "\n" + ">>> a = np.array([[0.5], [1.5], [2.5]])\n" + ">>> x = np.array([1., 2., 3., 4])\n" + ">>> a.shape, x.shape\n" + "((3, 1), (4,))\n" + "\n" + ">>> gdtrc(a, 3., x)\n" + "array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642],\n" + " [0.80884683, 0.42319008, 0.17357807, 0.0619688 ],\n" + " [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]])\n" + "\n" + "Plot the function for four different parameter sets.\n" + "\n" + ">>> a_parameters = [0.3, 1, 2, 6]\n" + ">>> b_parameters = [2, 10, 15, 20]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n" + ">>> x = np.linspace(0, 30, 1000)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> for parameter_set in parameters_list:\n" + "... a, b, style = parameter_set\n" + "... gdtrc_vals = gdtrc(a, b, x)\n" + "... ax.plot(x, gdtrc_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_xlabel(\"$x$\")\n" + ">>> ax.set_title(\"Gamma distribution survival function\")\n" + ">>> plt.show()\n" + "\n" + "The gamma distribution is also available as `scipy.stats.gamma`.\n" + "Using `gdtrc` directly can be much faster than calling the ``sf`` method\n" + "of `scipy.stats.gamma`, especially for small arrays or individual\n" + "values. To get the same results one must use the following parametrization:\n" + "``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``.\n" + "\n" + ">>> from scipy.stats import gamma\n" + ">>> a = 2\n" + ">>> b = 3\n" + ">>> x = 1.\n" + ">>> gdtrc_result = gdtrc(a, b, x) # this will often be faster than below\n" + ">>> gamma_dist_result = gamma(b, scale=1/a).sf(x)\n" + ">>> gdtrc_result == gamma_dist_result # test that results are equal\n" + "True") +ufunc_gdtrc_loops[0] = loop_d_ddd__As_fff_f +ufunc_gdtrc_loops[1] = loop_d_ddd__As_ddd_d +ufunc_gdtrc_types[0] = NPY_FLOAT +ufunc_gdtrc_types[1] = NPY_FLOAT +ufunc_gdtrc_types[2] = NPY_FLOAT +ufunc_gdtrc_types[3] = NPY_FLOAT +ufunc_gdtrc_types[4] = NPY_DOUBLE +ufunc_gdtrc_types[5] = NPY_DOUBLE +ufunc_gdtrc_types[6] = NPY_DOUBLE +ufunc_gdtrc_types[7] = NPY_DOUBLE +ufunc_gdtrc_ptr[2*0] = _func_xsf_gdtrc +ufunc_gdtrc_ptr[2*0+1] = ("gdtrc") +ufunc_gdtrc_ptr[2*1] = _func_xsf_gdtrc +ufunc_gdtrc_ptr[2*1+1] = ("gdtrc") +ufunc_gdtrc_data[0] = &ufunc_gdtrc_ptr[2*0] +ufunc_gdtrc_data[1] = &ufunc_gdtrc_ptr[2*1] +gdtrc = np.PyUFunc_FromFuncAndData(ufunc_gdtrc_loops, ufunc_gdtrc_data, ufunc_gdtrc_types, 2, 3, 1, 0, "gdtrc", ufunc_gdtrc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_gdtria_loops[2] +cdef void *ufunc_gdtria_ptr[4] +cdef void *ufunc_gdtria_data[2] +cdef char ufunc_gdtria_types[8] +cdef char *ufunc_gdtria_doc = ( + "gdtria(p, b, x, out=None)\n" + "\n" + "Inverse of `gdtr` vs a.\n" + "\n" + "Returns the inverse with respect to the parameter `a` of ``p =\n" + "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n" + "distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probability values.\n" + "b : array_like\n" + " `b` parameter values of `gdtr(a, b, x)`. `b` is the \"shape\" parameter\n" + " of the gamma distribution.\n" + "x : array_like\n" + " Nonnegative real values, from the domain of the gamma distribution.\n" + "out : ndarray, optional\n" + " If a fourth argument is given, it must be a numpy.ndarray whose size\n" + " matches the broadcast result of `a`, `b` and `x`. `out` is then the\n" + " array returned by the function.\n" + "\n" + "Returns\n" + "-------\n" + "a : scalar or ndarray\n" + " Values of the `a` parameter such that ``p = gdtr(a, b, x)`. ``1/a``\n" + " is the \"scale\" parameter of the gamma distribution.\n" + "\n" + "See Also\n" + "--------\n" + "gdtr : CDF of the gamma distribution.\n" + "gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`.\n" + "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n" + "\n" + "The cumulative distribution function `p` is computed using a routine by\n" + "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n" + "that produces the desired value of `p`. The search relies on the\n" + "monotonicity of `p` with `a`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.\n" + ".. [2] DiDinato, A. R. and Morris, A. H.,\n" + " Computation of the incomplete gamma function ratios and their\n" + " inverse. ACM Trans. Math. Softw. 12 (1986), 377-393.\n" + "\n" + "Examples\n" + "--------\n" + "First evaluate `gdtr`.\n" + "\n" + ">>> from scipy.special import gdtr, gdtria\n" + ">>> p = gdtr(1.2, 3.4, 5.6)\n" + ">>> print(p)\n" + "0.94378087442\n" + "\n" + "Verify the inverse.\n" + "\n" + ">>> gdtria(p, 3.4, 5.6)\n" + "1.2") +ufunc_gdtria_loops[0] = loop_d_ddd__As_fff_f +ufunc_gdtria_loops[1] = loop_d_ddd__As_ddd_d +ufunc_gdtria_types[0] = NPY_FLOAT +ufunc_gdtria_types[1] = NPY_FLOAT +ufunc_gdtria_types[2] = NPY_FLOAT +ufunc_gdtria_types[3] = NPY_FLOAT +ufunc_gdtria_types[4] = NPY_DOUBLE +ufunc_gdtria_types[5] = NPY_DOUBLE +ufunc_gdtria_types[6] = NPY_DOUBLE +ufunc_gdtria_types[7] = NPY_DOUBLE +ufunc_gdtria_ptr[2*0] = _func_gdtria +ufunc_gdtria_ptr[2*0+1] = ("gdtria") +ufunc_gdtria_ptr[2*1] = _func_gdtria +ufunc_gdtria_ptr[2*1+1] = ("gdtria") +ufunc_gdtria_data[0] = &ufunc_gdtria_ptr[2*0] +ufunc_gdtria_data[1] = &ufunc_gdtria_ptr[2*1] +gdtria = np.PyUFunc_FromFuncAndData(ufunc_gdtria_loops, ufunc_gdtria_data, ufunc_gdtria_types, 2, 3, 1, 0, "gdtria", ufunc_gdtria_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_gdtrib_loops[2] +cdef void *ufunc_gdtrib_ptr[4] +cdef void *ufunc_gdtrib_data[2] +cdef char ufunc_gdtrib_types[8] +cdef char *ufunc_gdtrib_doc = ( + "gdtrib(a, p, x, out=None)\n" + "\n" + "Inverse of `gdtr` vs b.\n" + "\n" + "Returns the inverse with respect to the parameter `b` of ``p =\n" + "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n" + "distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "a : array_like\n" + " `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the \"scale\"\n" + " parameter of the gamma distribution.\n" + "p : array_like\n" + " Probability values.\n" + "x : array_like\n" + " Nonnegative real values, from the domain of the gamma distribution.\n" + "out : ndarray, optional\n" + " If a fourth argument is given, it must be a numpy.ndarray whose size\n" + " matches the broadcast result of `a`, `b` and `x`. `out` is then the\n" + " array returned by the function.\n" + "\n" + "Returns\n" + "-------\n" + "b : scalar or ndarray\n" + " Values of the `b` parameter such that `p = gdtr(a, b, x)`. `b` is\n" + " the \"shape\" parameter of the gamma distribution.\n" + "\n" + "See Also\n" + "--------\n" + "gdtr : CDF of the gamma distribution.\n" + "gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`.\n" + "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n" + "\n" + "Notes\n" + "-----\n" + "\n" + "The cumulative distribution function `p` is computed using the Cephes [1]_\n" + "routines `igam` and `igamc`. Computation of `b` involves a search for a value\n" + "that produces the desired value of `p` using Chandrupatla's bracketing\n" + "root finding algorithm [2]_.\n" + "\n" + "Note that there are some edge cases where `gdtrib` is extended by taking\n" + "limits where they are uniquely defined. In particular\n" + "``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``.\n" + "For these edge cases, a numerical result will be returned for\n" + "``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is\n" + "undefined.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + ".. [2] Chandrupatla, Tirupathi R.\n" + " \"A new hybrid quadratic/bisection algorithm for finding the zero of a\n" + " nonlinear function without using derivatives\".\n" + " Advances in Engineering Software, 28(3), 145-149.\n" + " https://doi.org/10.1016/s0965-9978(96)00051-8\n" + "\n" + "Examples\n" + "--------\n" + "First evaluate `gdtr`.\n" + "\n" + ">>> from scipy.special import gdtr, gdtrib\n" + ">>> p = gdtr(1.2, 3.4, 5.6)\n" + ">>> print(p)\n" + "0.94378087442\n" + "\n" + "Verify the inverse.\n" + "\n" + ">>> gdtrib(1.2, p, 5.6)\n" + "3.3999999999999995") +ufunc_gdtrib_loops[0] = loop_d_ddd__As_fff_f +ufunc_gdtrib_loops[1] = loop_d_ddd__As_ddd_d +ufunc_gdtrib_types[0] = NPY_FLOAT +ufunc_gdtrib_types[1] = NPY_FLOAT +ufunc_gdtrib_types[2] = NPY_FLOAT +ufunc_gdtrib_types[3] = NPY_FLOAT +ufunc_gdtrib_types[4] = NPY_DOUBLE +ufunc_gdtrib_types[5] = NPY_DOUBLE +ufunc_gdtrib_types[6] = NPY_DOUBLE +ufunc_gdtrib_types[7] = NPY_DOUBLE +ufunc_gdtrib_ptr[2*0] = _func_xsf_gdtrib +ufunc_gdtrib_ptr[2*0+1] = ("gdtrib") +ufunc_gdtrib_ptr[2*1] = _func_xsf_gdtrib +ufunc_gdtrib_ptr[2*1+1] = ("gdtrib") +ufunc_gdtrib_data[0] = &ufunc_gdtrib_ptr[2*0] +ufunc_gdtrib_data[1] = &ufunc_gdtrib_ptr[2*1] +gdtrib = np.PyUFunc_FromFuncAndData(ufunc_gdtrib_loops, ufunc_gdtrib_data, ufunc_gdtrib_types, 2, 3, 1, 0, "gdtrib", ufunc_gdtrib_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_gdtrix_loops[2] +cdef void *ufunc_gdtrix_ptr[4] +cdef void *ufunc_gdtrix_data[2] +cdef char ufunc_gdtrix_types[8] +cdef char *ufunc_gdtrix_doc = ( + "gdtrix(a, b, p, out=None)\n" + "\n" + "Inverse of `gdtr` vs x.\n" + "\n" + "Returns the inverse with respect to the parameter `x` of ``p =\n" + "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n" + "distribution. This is also known as the pth quantile of the\n" + "distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "a : array_like\n" + " `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the \"scale\"\n" + " parameter of the gamma distribution.\n" + "b : array_like\n" + " `b` parameter values of ``gdtr(a, b, x)``. `b` is the \"shape\" parameter\n" + " of the gamma distribution.\n" + "p : array_like\n" + " Probability values.\n" + "out : ndarray, optional\n" + " If a fourth argument is given, it must be a numpy.ndarray whose size\n" + " matches the broadcast result of `a`, `b` and `x`. `out` is then the\n" + " array returned by the function.\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " Values of the `x` parameter such that `p = gdtr(a, b, x)`.\n" + "\n" + "See Also\n" + "--------\n" + "gdtr : CDF of the gamma distribution.\n" + "gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.\n" + "gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n" + "\n" + "The cumulative distribution function `p` is computed using a routine by\n" + "DiDinato and Morris [2]_. Computation of `x` involves a search for a value\n" + "that produces the desired value of `p`. The search relies on the\n" + "monotonicity of `p` with `x`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.\n" + ".. [2] DiDinato, A. R. and Morris, A. H.,\n" + " Computation of the incomplete gamma function ratios and their\n" + " inverse. ACM Trans. Math. Softw. 12 (1986), 377-393.\n" + "\n" + "Examples\n" + "--------\n" + "First evaluate `gdtr`.\n" + "\n" + ">>> from scipy.special import gdtr, gdtrix\n" + ">>> p = gdtr(1.2, 3.4, 5.6)\n" + ">>> print(p)\n" + "0.94378087442\n" + "\n" + "Verify the inverse.\n" + "\n" + ">>> gdtrix(1.2, 3.4, p)\n" + "5.5999999999999996") +ufunc_gdtrix_loops[0] = loop_d_ddd__As_fff_f +ufunc_gdtrix_loops[1] = loop_d_ddd__As_ddd_d +ufunc_gdtrix_types[0] = NPY_FLOAT +ufunc_gdtrix_types[1] = NPY_FLOAT +ufunc_gdtrix_types[2] = NPY_FLOAT +ufunc_gdtrix_types[3] = NPY_FLOAT +ufunc_gdtrix_types[4] = NPY_DOUBLE +ufunc_gdtrix_types[5] = NPY_DOUBLE +ufunc_gdtrix_types[6] = NPY_DOUBLE +ufunc_gdtrix_types[7] = NPY_DOUBLE +ufunc_gdtrix_ptr[2*0] = _func_gdtrix +ufunc_gdtrix_ptr[2*0+1] = ("gdtrix") +ufunc_gdtrix_ptr[2*1] = _func_gdtrix +ufunc_gdtrix_ptr[2*1+1] = ("gdtrix") +ufunc_gdtrix_data[0] = &ufunc_gdtrix_ptr[2*0] +ufunc_gdtrix_data[1] = &ufunc_gdtrix_ptr[2*1] +gdtrix = np.PyUFunc_FromFuncAndData(ufunc_gdtrix_loops, ufunc_gdtrix_data, ufunc_gdtrix_types, 2, 3, 1, 0, "gdtrix", ufunc_gdtrix_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_huber_loops[2] +cdef void *ufunc_huber_ptr[4] +cdef void *ufunc_huber_data[2] +cdef char ufunc_huber_types[6] +cdef char *ufunc_huber_doc = ( + "huber(delta, r, out=None)\n" + "\n" + "Huber loss function.\n" + "\n" + ".. math:: \\text{huber}(\\delta, r) = \\begin{cases} \\infty & \\delta < 0 \\\\\n" + " \\frac{1}{2}r^2 & 0 \\le \\delta, | r | \\le \\delta \\\\\n" + " \\delta ( |r| - \\frac{1}{2}\\delta ) & \\text{otherwise} \\end{cases}\n" + "\n" + "Parameters\n" + "----------\n" + "delta : ndarray\n" + " Input array, indicating the quadratic vs. linear loss changepoint.\n" + "r : ndarray\n" + " Input array, possibly representing residuals.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The computed Huber loss function values.\n" + "\n" + "See Also\n" + "--------\n" + "pseudo_huber : smooth approximation of this function\n" + "\n" + "Notes\n" + "-----\n" + "`huber` is useful as a loss function in robust statistics or machine\n" + "learning to reduce the influence of outliers as compared to the common\n" + "squared error loss, residuals with a magnitude higher than `delta` are\n" + "not squared [1]_.\n" + "\n" + "Typically, `r` represents residuals, the difference\n" + "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n" + "`huber` resembles the squared error and for :math:`|r|>\\delta` the\n" + "absolute error. This way, the Huber loss often achieves\n" + "a fast convergence in model fitting for small residuals like the squared\n" + "error loss function and still reduces the influence of outliers\n" + "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n" + "the cutoff between squared and absolute error regimes, it has\n" + "to be tuned carefully for each problem. `huber` is also\n" + "convex, making it suitable for gradient based optimization.\n" + "\n" + ".. versionadded:: 0.15.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] Peter Huber. \"Robust Estimation of a Location Parameter\",\n" + " 1964. Annals of Statistics. 53 (1): 73 - 101.\n" + "\n" + "Examples\n" + "--------\n" + "Import all necessary modules.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import huber\n" + ">>> import matplotlib.pyplot as plt\n" + "\n" + "Compute the function for ``delta=1`` at ``r=2``\n" + "\n" + ">>> huber(1., 2.)\n" + "1.5\n" + "\n" + "Compute the function for different `delta` by providing a NumPy array or\n" + "list for `delta`.\n" + "\n" + ">>> huber([1., 3., 5.], 4.)\n" + "array([3.5, 7.5, 8. ])\n" + "\n" + "Compute the function at different points by providing a NumPy array or\n" + "list for `r`.\n" + "\n" + ">>> huber(2., np.array([1., 1.5, 3.]))\n" + "array([0.5 , 1.125, 4. ])\n" + "\n" + "The function can be calculated for different `delta` and `r` by\n" + "providing arrays for both with compatible shapes for broadcasting.\n" + "\n" + ">>> r = np.array([1., 2.5, 8., 10.])\n" + ">>> deltas = np.array([[1.], [5.], [9.]])\n" + ">>> print(r.shape, deltas.shape)\n" + "(4,) (3, 1)\n" + "\n" + ">>> huber(deltas, r)\n" + "array([[ 0.5 , 2. , 7.5 , 9.5 ],\n" + " [ 0.5 , 3.125, 27.5 , 37.5 ],\n" + " [ 0.5 , 3.125, 32. , 49.5 ]])\n" + "\n" + "Plot the function for different `delta`.\n" + "\n" + ">>> x = np.linspace(-4, 4, 500)\n" + ">>> deltas = [1, 2, 3]\n" + ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n" + ">>> fig, ax = plt.subplots()\n" + ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n" + ">>> for delta, style in combined_plot_parameters:\n" + "... ax.plot(x, huber(delta, x), label=fr\"$\\delta={delta}$\", ls=style)\n" + ">>> ax.legend(loc=\"upper center\")\n" + ">>> ax.set_xlabel(\"$x$\")\n" + ">>> ax.set_title(r\"Huber loss function $h_{\\delta}(x)$\")\n" + ">>> ax.set_xlim(-4, 4)\n" + ">>> ax.set_ylim(0, 8)\n" + ">>> plt.show()") +ufunc_huber_loops[0] = loop_d_dd__As_ff_f +ufunc_huber_loops[1] = loop_d_dd__As_dd_d +ufunc_huber_types[0] = NPY_FLOAT +ufunc_huber_types[1] = NPY_FLOAT +ufunc_huber_types[2] = NPY_FLOAT +ufunc_huber_types[3] = NPY_DOUBLE +ufunc_huber_types[4] = NPY_DOUBLE +ufunc_huber_types[5] = NPY_DOUBLE +ufunc_huber_ptr[2*0] = _func_huber +ufunc_huber_ptr[2*0+1] = ("huber") +ufunc_huber_ptr[2*1] = _func_huber +ufunc_huber_ptr[2*1+1] = ("huber") +ufunc_huber_data[0] = &ufunc_huber_ptr[2*0] +ufunc_huber_data[1] = &ufunc_huber_ptr[2*1] +huber = np.PyUFunc_FromFuncAndData(ufunc_huber_loops, ufunc_huber_data, ufunc_huber_types, 2, 2, 1, 0, "huber", ufunc_huber_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_hyp0f1_loops[4] +cdef void *ufunc_hyp0f1_ptr[8] +cdef void *ufunc_hyp0f1_data[4] +cdef char ufunc_hyp0f1_types[12] +cdef char *ufunc_hyp0f1_doc = ( + "hyp0f1(v, z, out=None)\n" + "\n" + "Confluent hypergeometric limit function 0F1.\n" + "\n" + "Parameters\n" + "----------\n" + "v : array_like\n" + " Real-valued parameter\n" + "z : array_like\n" + " Real- or complex-valued argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The confluent hypergeometric limit function\n" + "\n" + "Notes\n" + "-----\n" + "This function is defined as:\n" + "\n" + ".. math:: _0F_1(v, z) = \\sum_{k=0}^{\\infty}\\frac{z^k}{(v)_k k!}.\n" + "\n" + "It's also the limit as :math:`q \\to \\infty` of :math:`_1F_1(q; v; z/q)`,\n" + "and satisfies the differential equation :math:`f''(z) + vf'(z) =\n" + "f(z)`. See [1]_ for more information.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Wolfram MathWorld, \"Confluent Hypergeometric Limit Function\",\n" + " http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It is one when `z` is zero.\n" + "\n" + ">>> sc.hyp0f1(1, 0)\n" + "1.0\n" + "\n" + "It is the limit of the confluent hypergeometric function as `q`\n" + "goes to infinity.\n" + "\n" + ">>> q = np.array([1, 10, 100, 1000])\n" + ">>> v = 1\n" + ">>> z = 1\n" + ">>> sc.hyp1f1(q, v, z / q)\n" + "array([2.71828183, 2.31481985, 2.28303778, 2.27992985])\n" + ">>> sc.hyp0f1(v, z)\n" + "2.2795853023360673\n" + "\n" + "It is related to Bessel functions.\n" + "\n" + ">>> n = 1\n" + ">>> x = np.linspace(0, 1, 5)\n" + ">>> sc.jv(n, x)\n" + "array([0. , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])\n" + ">>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2)\n" + "array([0. , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])") +ufunc_hyp0f1_loops[0] = loop_d_dd__As_ff_f +ufunc_hyp0f1_loops[1] = loop_D_dD__As_fF_F +ufunc_hyp0f1_loops[2] = loop_d_dd__As_dd_d +ufunc_hyp0f1_loops[3] = loop_D_dD__As_dD_D +ufunc_hyp0f1_types[0] = NPY_FLOAT +ufunc_hyp0f1_types[1] = NPY_FLOAT +ufunc_hyp0f1_types[2] = NPY_FLOAT +ufunc_hyp0f1_types[3] = NPY_FLOAT +ufunc_hyp0f1_types[4] = NPY_CFLOAT +ufunc_hyp0f1_types[5] = NPY_CFLOAT +ufunc_hyp0f1_types[6] = NPY_DOUBLE +ufunc_hyp0f1_types[7] = NPY_DOUBLE +ufunc_hyp0f1_types[8] = NPY_DOUBLE +ufunc_hyp0f1_types[9] = NPY_DOUBLE +ufunc_hyp0f1_types[10] = NPY_CDOUBLE +ufunc_hyp0f1_types[11] = NPY_CDOUBLE +ufunc_hyp0f1_ptr[2*0] = _func__hyp0f1_real +ufunc_hyp0f1_ptr[2*0+1] = ("hyp0f1") +ufunc_hyp0f1_ptr[2*1] = _func__hyp0f1_cmplx +ufunc_hyp0f1_ptr[2*1+1] = ("hyp0f1") +ufunc_hyp0f1_ptr[2*2] = _func__hyp0f1_real +ufunc_hyp0f1_ptr[2*2+1] = ("hyp0f1") +ufunc_hyp0f1_ptr[2*3] = _func__hyp0f1_cmplx +ufunc_hyp0f1_ptr[2*3+1] = ("hyp0f1") +ufunc_hyp0f1_data[0] = &ufunc_hyp0f1_ptr[2*0] +ufunc_hyp0f1_data[1] = &ufunc_hyp0f1_ptr[2*1] +ufunc_hyp0f1_data[2] = &ufunc_hyp0f1_ptr[2*2] +ufunc_hyp0f1_data[3] = &ufunc_hyp0f1_ptr[2*3] +hyp0f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp0f1_loops, ufunc_hyp0f1_data, ufunc_hyp0f1_types, 4, 2, 1, 0, "hyp0f1", ufunc_hyp0f1_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_hyp1f1_loops[4] +cdef void *ufunc_hyp1f1_ptr[8] +cdef void *ufunc_hyp1f1_data[4] +cdef char ufunc_hyp1f1_types[16] +cdef char *ufunc_hyp1f1_doc = ( + "hyp1f1(a, b, x, out=None)\n" + "\n" + "Confluent hypergeometric function 1F1.\n" + "\n" + "The confluent hypergeometric function is defined by the series\n" + "\n" + ".. math::\n" + "\n" + " {}_1F_1(a; b; x) = \\sum_{k = 0}^\\infty \\frac{(a)_k}{(b)_k k!} x^k.\n" + "\n" + "See [dlmf]_ for more details. Here :math:`(\\cdot)_k` is the\n" + "Pochhammer symbol; see `poch`.\n" + "\n" + "Parameters\n" + "----------\n" + "a, b : array_like\n" + " Real parameters\n" + "x : array_like\n" + " Real or complex argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the confluent hypergeometric function\n" + "\n" + "See Also\n" + "--------\n" + "hyperu : another confluent hypergeometric function\n" + "hyp0f1 : confluent hypergeometric limit function\n" + "hyp2f1 : Gaussian hypergeometric function\n" + "\n" + "Notes\n" + "-----\n" + "For real values, this function uses the ``hyp1f1`` routine from the C++ Boost\n" + "library [2]_, for complex values a C translation of the specfun\n" + "Fortran library [3]_.\n" + "\n" + "References\n" + "----------\n" + ".. [dlmf] NIST Digital Library of Mathematical Functions\n" + " https://dlmf.nist.gov/13.2#E2\n" + ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + ".. [3] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n" + " and Sons, Inc, 1996.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It is one when `x` is zero:\n" + "\n" + ">>> sc.hyp1f1(0.5, 0.5, 0)\n" + "1.0\n" + "\n" + "It is singular when `b` is a nonpositive integer.\n" + "\n" + ">>> sc.hyp1f1(0.5, -1, 0)\n" + "inf\n" + "\n" + "It is a polynomial when `a` is a nonpositive integer.\n" + "\n" + ">>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0])\n" + ">>> sc.hyp1f1(a, b, x)\n" + "array([-1., -3., -5., -7.])\n" + ">>> 1 + (a / b) * x\n" + "array([-1., -3., -5., -7.])\n" + "\n" + "It reduces to the exponential function when ``a = b``.\n" + "\n" + ">>> sc.hyp1f1(2, 2, [1, 2, 3, 4])\n" + "array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003])\n" + ">>> np.exp([1, 2, 3, 4])\n" + "array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003])") +ufunc_hyp1f1_loops[0] = loop_d_ddd__As_fff_f +ufunc_hyp1f1_loops[1] = loop_D_ddD__As_ffF_F +ufunc_hyp1f1_loops[2] = loop_d_ddd__As_ddd_d +ufunc_hyp1f1_loops[3] = loop_D_ddD__As_ddD_D +ufunc_hyp1f1_types[0] = NPY_FLOAT +ufunc_hyp1f1_types[1] = NPY_FLOAT +ufunc_hyp1f1_types[2] = NPY_FLOAT +ufunc_hyp1f1_types[3] = NPY_FLOAT +ufunc_hyp1f1_types[4] = NPY_FLOAT +ufunc_hyp1f1_types[5] = NPY_FLOAT +ufunc_hyp1f1_types[6] = NPY_CFLOAT +ufunc_hyp1f1_types[7] = NPY_CFLOAT +ufunc_hyp1f1_types[8] = NPY_DOUBLE +ufunc_hyp1f1_types[9] = NPY_DOUBLE +ufunc_hyp1f1_types[10] = NPY_DOUBLE +ufunc_hyp1f1_types[11] = NPY_DOUBLE +ufunc_hyp1f1_types[12] = NPY_DOUBLE +ufunc_hyp1f1_types[13] = NPY_DOUBLE +ufunc_hyp1f1_types[14] = NPY_CDOUBLE +ufunc_hyp1f1_types[15] = NPY_CDOUBLE +ufunc_hyp1f1_ptr[2*0] = scipy.special._ufuncs_cxx._export_hyp1f1_double +ufunc_hyp1f1_ptr[2*0+1] = ("hyp1f1") +ufunc_hyp1f1_ptr[2*1] = _func_chyp1f1_wrap +ufunc_hyp1f1_ptr[2*1+1] = ("hyp1f1") +ufunc_hyp1f1_ptr[2*2] = scipy.special._ufuncs_cxx._export_hyp1f1_double +ufunc_hyp1f1_ptr[2*2+1] = ("hyp1f1") +ufunc_hyp1f1_ptr[2*3] = _func_chyp1f1_wrap +ufunc_hyp1f1_ptr[2*3+1] = ("hyp1f1") +ufunc_hyp1f1_data[0] = &ufunc_hyp1f1_ptr[2*0] +ufunc_hyp1f1_data[1] = &ufunc_hyp1f1_ptr[2*1] +ufunc_hyp1f1_data[2] = &ufunc_hyp1f1_ptr[2*2] +ufunc_hyp1f1_data[3] = &ufunc_hyp1f1_ptr[2*3] +hyp1f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp1f1_loops, ufunc_hyp1f1_data, ufunc_hyp1f1_types, 4, 3, 1, 0, "hyp1f1", ufunc_hyp1f1_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_hyperu_loops[2] +cdef void *ufunc_hyperu_ptr[4] +cdef void *ufunc_hyperu_data[2] +cdef char ufunc_hyperu_types[8] +cdef char *ufunc_hyperu_doc = ( + "hyperu(a, b, x, out=None)\n" + "\n" + "Confluent hypergeometric function U\n" + "\n" + "It is defined as the solution to the equation\n" + "\n" + ".. math::\n" + "\n" + " x \\frac{d^2w}{dx^2} + (b - x) \\frac{dw}{dx} - aw = 0\n" + "\n" + "which satisfies the property\n" + "\n" + ".. math::\n" + "\n" + " U(a, b, x) \\sim x^{-a}\n" + "\n" + "as :math:`x \\to \\infty`. See [dlmf]_ for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "a, b : array_like\n" + " Real-valued parameters\n" + "x : array_like\n" + " Real-valued argument\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of `U`\n" + "\n" + "References\n" + "----------\n" + ".. [dlmf] NIST Digital Library of Mathematics Functions\n" + " https://dlmf.nist.gov/13.2#E6\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It has a branch cut along the negative `x` axis.\n" + "\n" + ">>> x = np.linspace(-0.1, -10, 5)\n" + ">>> sc.hyperu(1, 1, x)\n" + "array([nan, nan, nan, nan, nan])\n" + "\n" + "It approaches zero as `x` goes to infinity.\n" + "\n" + ">>> x = np.array([1, 10, 100])\n" + ">>> sc.hyperu(1, 1, x)\n" + "array([0.59634736, 0.09156333, 0.00990194])\n" + "\n" + "It satisfies Kummer's transformation.\n" + "\n" + ">>> a, b, x = 2, 1, 1\n" + ">>> sc.hyperu(a, b, x)\n" + "0.1926947246463881\n" + ">>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x)\n" + "0.1926947246463881") +ufunc_hyperu_loops[0] = loop_d_ddd__As_fff_f +ufunc_hyperu_loops[1] = loop_d_ddd__As_ddd_d +ufunc_hyperu_types[0] = NPY_FLOAT +ufunc_hyperu_types[1] = NPY_FLOAT +ufunc_hyperu_types[2] = NPY_FLOAT +ufunc_hyperu_types[3] = NPY_FLOAT +ufunc_hyperu_types[4] = NPY_DOUBLE +ufunc_hyperu_types[5] = NPY_DOUBLE +ufunc_hyperu_types[6] = NPY_DOUBLE +ufunc_hyperu_types[7] = NPY_DOUBLE +ufunc_hyperu_ptr[2*0] = _func_hyperu +ufunc_hyperu_ptr[2*0+1] = ("hyperu") +ufunc_hyperu_ptr[2*1] = _func_hyperu +ufunc_hyperu_ptr[2*1+1] = ("hyperu") +ufunc_hyperu_data[0] = &ufunc_hyperu_ptr[2*0] +ufunc_hyperu_data[1] = &ufunc_hyperu_ptr[2*1] +hyperu = np.PyUFunc_FromFuncAndData(ufunc_hyperu_loops, ufunc_hyperu_data, ufunc_hyperu_types, 2, 3, 1, 0, "hyperu", ufunc_hyperu_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_inv_boxcox_loops[2] +cdef void *ufunc_inv_boxcox_ptr[4] +cdef void *ufunc_inv_boxcox_data[2] +cdef char ufunc_inv_boxcox_types[6] +cdef char *ufunc_inv_boxcox_doc = ( + "inv_boxcox(y, lmbda, out=None)\n" + "\n" + "Compute the inverse of the Box-Cox transformation.\n" + "\n" + "Find ``x`` such that::\n" + "\n" + " y = (x**lmbda - 1) / lmbda if lmbda != 0\n" + " log(x) if lmbda == 0\n" + "\n" + "Parameters\n" + "----------\n" + "y : array_like\n" + " Data to be transformed.\n" + "lmbda : array_like\n" + " Power parameter of the Box-Cox transform.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " Transformed data.\n" + "\n" + "Notes\n" + "-----\n" + "\n" + ".. versionadded:: 0.16.0\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import boxcox, inv_boxcox\n" + ">>> y = boxcox([1, 4, 10], 2.5)\n" + ">>> inv_boxcox(y, 2.5)\n" + "array([1., 4., 10.])") +ufunc_inv_boxcox_loops[0] = loop_d_dd__As_ff_f +ufunc_inv_boxcox_loops[1] = loop_d_dd__As_dd_d +ufunc_inv_boxcox_types[0] = NPY_FLOAT +ufunc_inv_boxcox_types[1] = NPY_FLOAT +ufunc_inv_boxcox_types[2] = NPY_FLOAT +ufunc_inv_boxcox_types[3] = NPY_DOUBLE +ufunc_inv_boxcox_types[4] = NPY_DOUBLE +ufunc_inv_boxcox_types[5] = NPY_DOUBLE +ufunc_inv_boxcox_ptr[2*0] = _func_inv_boxcox +ufunc_inv_boxcox_ptr[2*0+1] = ("inv_boxcox") +ufunc_inv_boxcox_ptr[2*1] = _func_inv_boxcox +ufunc_inv_boxcox_ptr[2*1+1] = ("inv_boxcox") +ufunc_inv_boxcox_data[0] = &ufunc_inv_boxcox_ptr[2*0] +ufunc_inv_boxcox_data[1] = &ufunc_inv_boxcox_ptr[2*1] +inv_boxcox = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox_loops, ufunc_inv_boxcox_data, ufunc_inv_boxcox_types, 2, 2, 1, 0, "inv_boxcox", ufunc_inv_boxcox_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_inv_boxcox1p_loops[2] +cdef void *ufunc_inv_boxcox1p_ptr[4] +cdef void *ufunc_inv_boxcox1p_data[2] +cdef char ufunc_inv_boxcox1p_types[6] +cdef char *ufunc_inv_boxcox1p_doc = ( + "inv_boxcox1p(y, lmbda, out=None)\n" + "\n" + "Compute the inverse of the Box-Cox transformation.\n" + "\n" + "Find ``x`` such that::\n" + "\n" + " y = ((1+x)**lmbda - 1) / lmbda if lmbda != 0\n" + " log(1+x) if lmbda == 0\n" + "\n" + "Parameters\n" + "----------\n" + "y : array_like\n" + " Data to be transformed.\n" + "lmbda : array_like\n" + " Power parameter of the Box-Cox transform.\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " Transformed data.\n" + "\n" + "Notes\n" + "-----\n" + "\n" + ".. versionadded:: 0.16.0\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import boxcox1p, inv_boxcox1p\n" + ">>> y = boxcox1p([1, 4, 10], 2.5)\n" + ">>> inv_boxcox1p(y, 2.5)\n" + "array([1., 4., 10.])") +ufunc_inv_boxcox1p_loops[0] = loop_d_dd__As_ff_f +ufunc_inv_boxcox1p_loops[1] = loop_d_dd__As_dd_d +ufunc_inv_boxcox1p_types[0] = NPY_FLOAT +ufunc_inv_boxcox1p_types[1] = NPY_FLOAT +ufunc_inv_boxcox1p_types[2] = NPY_FLOAT +ufunc_inv_boxcox1p_types[3] = NPY_DOUBLE +ufunc_inv_boxcox1p_types[4] = NPY_DOUBLE +ufunc_inv_boxcox1p_types[5] = NPY_DOUBLE +ufunc_inv_boxcox1p_ptr[2*0] = _func_inv_boxcox1p +ufunc_inv_boxcox1p_ptr[2*0+1] = ("inv_boxcox1p") +ufunc_inv_boxcox1p_ptr[2*1] = _func_inv_boxcox1p +ufunc_inv_boxcox1p_ptr[2*1+1] = ("inv_boxcox1p") +ufunc_inv_boxcox1p_data[0] = &ufunc_inv_boxcox1p_ptr[2*0] +ufunc_inv_boxcox1p_data[1] = &ufunc_inv_boxcox1p_ptr[2*1] +inv_boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox1p_loops, ufunc_inv_boxcox1p_data, ufunc_inv_boxcox1p_types, 2, 2, 1, 0, "inv_boxcox1p", ufunc_inv_boxcox1p_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_kl_div_loops[2] +cdef void *ufunc_kl_div_ptr[4] +cdef void *ufunc_kl_div_data[2] +cdef char ufunc_kl_div_types[6] +cdef char *ufunc_kl_div_doc = ( + "kl_div(x, y, out=None)\n" + "\n" + "Elementwise function for computing Kullback-Leibler divergence.\n" + "\n" + ".. math::\n" + "\n" + " \\mathrm{kl\\_div}(x, y) =\n" + " \\begin{cases}\n" + " x \\log(x / y) - x + y & x > 0, y > 0 \\\\\n" + " y & x = 0, y \\ge 0 \\\\\n" + " \\infty & \\text{otherwise}\n" + " \\end{cases}\n" + "\n" + "Parameters\n" + "----------\n" + "x, y : array_like\n" + " Real arguments\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the Kullback-Liebler divergence.\n" + "\n" + "See Also\n" + "--------\n" + "entr, rel_entr, scipy.stats.entropy\n" + "\n" + "Notes\n" + "-----\n" + ".. versionadded:: 0.15.0\n" + "\n" + "This function is non-negative and is jointly convex in `x` and `y`.\n" + "\n" + "The origin of this function is in convex programming; see [1]_ for\n" + "details. This is why the function contains the extra :math:`-x\n" + "+ y` terms over what might be expected from the Kullback-Leibler\n" + "divergence. For a version of the function without the extra terms,\n" + "see `rel_entr`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n" + " Cambridge University Press, 2004.\n" + " :doi:`https://doi.org/10.1017/CBO9780511804441`") +ufunc_kl_div_loops[0] = loop_d_dd__As_ff_f +ufunc_kl_div_loops[1] = loop_d_dd__As_dd_d +ufunc_kl_div_types[0] = NPY_FLOAT +ufunc_kl_div_types[1] = NPY_FLOAT +ufunc_kl_div_types[2] = NPY_FLOAT +ufunc_kl_div_types[3] = NPY_DOUBLE +ufunc_kl_div_types[4] = NPY_DOUBLE +ufunc_kl_div_types[5] = NPY_DOUBLE +ufunc_kl_div_ptr[2*0] = _func_kl_div +ufunc_kl_div_ptr[2*0+1] = ("kl_div") +ufunc_kl_div_ptr[2*1] = _func_kl_div +ufunc_kl_div_ptr[2*1+1] = ("kl_div") +ufunc_kl_div_data[0] = &ufunc_kl_div_ptr[2*0] +ufunc_kl_div_data[1] = &ufunc_kl_div_ptr[2*1] +kl_div = np.PyUFunc_FromFuncAndData(ufunc_kl_div_loops, ufunc_kl_div_data, ufunc_kl_div_types, 2, 2, 1, 0, "kl_div", ufunc_kl_div_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_kn_loops[3] +cdef void *ufunc_kn_ptr[6] +cdef void *ufunc_kn_data[3] +cdef char ufunc_kn_types[9] +cdef char *ufunc_kn_doc = ( + "kn(n, x, out=None)\n" + "\n" + "Modified Bessel function of the second kind of integer order `n`\n" + "\n" + "Returns the modified Bessel function of the second kind for integer order\n" + "`n` at real `z`.\n" + "\n" + "These are also sometimes called functions of the third kind, Basset\n" + "functions, or Macdonald functions.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like of int\n" + " Order of Bessel functions (floats will truncate with a warning)\n" + "x : array_like of float\n" + " Argument at which to evaluate the Bessel functions\n" + "out : ndarray, optional\n" + " Optional output array for the function results.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Value of the Modified Bessel function of the second kind,\n" + " :math:`K_n(x)`.\n" + "\n" + "See Also\n" + "--------\n" + "kv : Same function, but accepts real order and complex argument\n" + "kvp : Derivative of this function\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for AMOS [1]_ routine `zbesk`. For a discussion of the\n" + "algorithm used, see [2]_ and the references therein.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Donald E. Amos, \"AMOS, A Portable Package for Bessel Functions\n" + " of a Complex Argument and Nonnegative Order\",\n" + " http://netlib.org/amos/\n" + ".. [2] Donald E. Amos, \"Algorithm 644: A portable package for Bessel\n" + " functions of a complex argument and nonnegative order\", ACM\n" + " TOMS Vol. 12 Issue 3, Sept. 1986, p. 265\n" + "\n" + "Examples\n" + "--------\n" + "Plot the function of several orders for real input:\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import kn\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(0, 5, 1000)\n" + ">>> for N in range(6):\n" + "... plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N))\n" + ">>> plt.ylim(0, 10)\n" + ">>> plt.legend()\n" + ">>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$')\n" + ">>> plt.show()\n" + "\n" + "Calculate for a single value at multiple orders:\n" + "\n" + ">>> kn([4, 5, 6], 1)\n" + "array([ 44.23241585, 360.9605896 , 3653.83831186])") +ufunc_kn_loops[0] = loop_d_pd__As_pd_d +ufunc_kn_loops[1] = loop_d_dd__As_ff_f +ufunc_kn_loops[2] = loop_d_dd__As_dd_d +ufunc_kn_types[0] = NPY_INTP +ufunc_kn_types[1] = NPY_DOUBLE +ufunc_kn_types[2] = NPY_DOUBLE +ufunc_kn_types[3] = NPY_FLOAT +ufunc_kn_types[4] = NPY_FLOAT +ufunc_kn_types[5] = NPY_FLOAT +ufunc_kn_types[6] = NPY_DOUBLE +ufunc_kn_types[7] = NPY_DOUBLE +ufunc_kn_types[8] = NPY_DOUBLE +ufunc_kn_ptr[2*0] = _func_special_cyl_bessel_k_int +ufunc_kn_ptr[2*0+1] = ("kn") +ufunc_kn_ptr[2*1] = _func_kn_unsafe +ufunc_kn_ptr[2*1+1] = ("kn") +ufunc_kn_ptr[2*2] = _func_kn_unsafe +ufunc_kn_ptr[2*2+1] = ("kn") +ufunc_kn_data[0] = &ufunc_kn_ptr[2*0] +ufunc_kn_data[1] = &ufunc_kn_ptr[2*1] +ufunc_kn_data[2] = &ufunc_kn_ptr[2*2] +kn = np.PyUFunc_FromFuncAndData(ufunc_kn_loops, ufunc_kn_data, ufunc_kn_types, 3, 2, 1, 0, "kn", ufunc_kn_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_kolmogi_loops[2] +cdef void *ufunc_kolmogi_ptr[4] +cdef void *ufunc_kolmogi_data[2] +cdef char ufunc_kolmogi_types[4] +cdef char *ufunc_kolmogi_doc = ( + "kolmogi(p, out=None)\n" + "\n" + "Inverse Survival Function of Kolmogorov distribution\n" + "\n" + "It is the inverse function to `kolmogorov`.\n" + "Returns y such that ``kolmogorov(y) == p``.\n" + "\n" + "Parameters\n" + "----------\n" + "p : float array_like\n" + " Probability\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The value(s) of kolmogi(p)\n" + "\n" + "See Also\n" + "--------\n" + "kolmogorov : The Survival Function for the distribution\n" + "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n" + "smirnov, smirnovi : Functions for the one-sided distribution\n" + "\n" + "Notes\n" + "-----\n" + "`kolmogorov` is used by `stats.kstest` in the application of the\n" + "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n" + "function is exposed in `scpy.special`, but the recommended way to achieve\n" + "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n" + "`stats.kstwobign` distribution.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import kolmogi\n" + ">>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])\n" + "array([ inf, 1.22384787, 1.01918472, 0.82757356, 0.67644769,\n" + " 0.57117327, 0. ])") +ufunc_kolmogi_loops[0] = loop_d_d__As_f_f +ufunc_kolmogi_loops[1] = loop_d_d__As_d_d +ufunc_kolmogi_types[0] = NPY_FLOAT +ufunc_kolmogi_types[1] = NPY_FLOAT +ufunc_kolmogi_types[2] = NPY_DOUBLE +ufunc_kolmogi_types[3] = NPY_DOUBLE +ufunc_kolmogi_ptr[2*0] = _func_xsf_kolmogi +ufunc_kolmogi_ptr[2*0+1] = ("kolmogi") +ufunc_kolmogi_ptr[2*1] = _func_xsf_kolmogi +ufunc_kolmogi_ptr[2*1+1] = ("kolmogi") +ufunc_kolmogi_data[0] = &ufunc_kolmogi_ptr[2*0] +ufunc_kolmogi_data[1] = &ufunc_kolmogi_ptr[2*1] +kolmogi = np.PyUFunc_FromFuncAndData(ufunc_kolmogi_loops, ufunc_kolmogi_data, ufunc_kolmogi_types, 2, 1, 1, 0, "kolmogi", ufunc_kolmogi_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_kolmogorov_loops[2] +cdef void *ufunc_kolmogorov_ptr[4] +cdef void *ufunc_kolmogorov_data[2] +cdef char ufunc_kolmogorov_types[4] +cdef char *ufunc_kolmogorov_doc = ( + "kolmogorov(y, out=None)\n" + "\n" + "Complementary cumulative distribution (Survival Function) function of\n" + "Kolmogorov distribution.\n" + "\n" + "Returns the complementary cumulative distribution function of\n" + "Kolmogorov's limiting distribution (``D_n*\\sqrt(n)`` as n goes to infinity)\n" + "of a two-sided test for equality between an empirical and a theoretical\n" + "distribution. It is equal to the (limit as n->infinity of the)\n" + "probability that ``sqrt(n) * max absolute deviation > y``.\n" + "\n" + "Parameters\n" + "----------\n" + "y : float array_like\n" + " Absolute deviation between the Empirical CDF (ECDF) and the target CDF,\n" + " multiplied by sqrt(n).\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The value(s) of kolmogorov(y)\n" + "\n" + "See Also\n" + "--------\n" + "kolmogi : The Inverse Survival Function for the distribution\n" + "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n" + "smirnov, smirnovi : Functions for the one-sided distribution\n" + "\n" + "Notes\n" + "-----\n" + "`kolmogorov` is used by `stats.kstest` in the application of the\n" + "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n" + "function is exposed in `scpy.special`, but the recommended way to achieve\n" + "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n" + "`stats.kstwobign` distribution.\n" + "\n" + "Examples\n" + "--------\n" + "Show the probability of a gap at least as big as 0, 0.5 and 1.0.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import kolmogorov\n" + ">>> from scipy.stats import kstwobign\n" + ">>> kolmogorov([0, 0.5, 1.0])\n" + "array([ 1. , 0.96394524, 0.26999967])\n" + "\n" + "Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against\n" + "the target distribution, a Normal(0, 1) distribution.\n" + "\n" + ">>> from scipy.stats import norm, laplace\n" + ">>> rng = np.random.default_rng()\n" + ">>> n = 1000\n" + ">>> lap01 = laplace(0, 1)\n" + ">>> x = np.sort(lap01.rvs(n, random_state=rng))\n" + ">>> np.mean(x), np.std(x)\n" + "(-0.05841730131499543, 1.3968109101997568)\n" + "\n" + "Construct the Empirical CDF and the K-S statistic Dn.\n" + "\n" + ">>> target = norm(0,1) # Normal mean 0, stddev 1\n" + ">>> cdfs = target.cdf(x)\n" + ">>> ecdfs = np.arange(n+1, dtype=float)/n\n" + ">>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs])\n" + ">>> Dn = np.max(gaps)\n" + ">>> Kn = np.sqrt(n) * Dn\n" + ">>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn))\n" + "Dn=0.043363, sqrt(n)*Dn=1.371265\n" + ">>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:',\n" + "... ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' %\n" + "... (Kn, kolmogorov(Kn)),\n" + "... ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' %\n" + "... (Kn, kstwobign.cdf(Kn))]))\n" + "For a sample of size n drawn from a N(0, 1) distribution:\n" + " the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533\n" + " the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467\n" + "\n" + "Plot the Empirical CDF against the target N(0, 1) CDF.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF')\n" + ">>> x3 = np.linspace(-3, 3, 100)\n" + ">>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)')\n" + ">>> plt.ylim([0, 1]); plt.grid(True); plt.legend();\n" + ">>> # Add vertical lines marking Dn+ and Dn-\n" + ">>> iminus, iplus = np.argmax(gaps, axis=0)\n" + ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus],\n" + "... color='r', linestyle='dashed', lw=4)\n" + ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1],\n" + "... color='r', linestyle='dashed', lw=4)\n" + ">>> plt.show()") +ufunc_kolmogorov_loops[0] = loop_d_d__As_f_f +ufunc_kolmogorov_loops[1] = loop_d_d__As_d_d +ufunc_kolmogorov_types[0] = NPY_FLOAT +ufunc_kolmogorov_types[1] = NPY_FLOAT +ufunc_kolmogorov_types[2] = NPY_DOUBLE +ufunc_kolmogorov_types[3] = NPY_DOUBLE +ufunc_kolmogorov_ptr[2*0] = _func_xsf_kolmogorov +ufunc_kolmogorov_ptr[2*0+1] = ("kolmogorov") +ufunc_kolmogorov_ptr[2*1] = _func_xsf_kolmogorov +ufunc_kolmogorov_ptr[2*1+1] = ("kolmogorov") +ufunc_kolmogorov_data[0] = &ufunc_kolmogorov_ptr[2*0] +ufunc_kolmogorov_data[1] = &ufunc_kolmogorov_ptr[2*1] +kolmogorov = np.PyUFunc_FromFuncAndData(ufunc_kolmogorov_loops, ufunc_kolmogorov_data, ufunc_kolmogorov_types, 2, 1, 1, 0, "kolmogorov", ufunc_kolmogorov_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_log1p_loops[4] +cdef void *ufunc_log1p_ptr[8] +cdef void *ufunc_log1p_data[4] +cdef char ufunc_log1p_types[8] +cdef char *ufunc_log1p_doc = ( + "log1p(x, out=None)\n" + "\n" + "Calculates log(1 + x) for use when `x` is near zero.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real or complex valued input.\n" + "out : ndarray, optional\n" + " Optional output array for the function results.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of ``log(1 + x)``.\n" + "\n" + "See Also\n" + "--------\n" + "expm1, cosm1\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It is more accurate than using ``log(1 + x)`` directly for ``x``\n" + "near 0. Note that in the below example ``1 + 1e-17 == 1`` to\n" + "double precision.\n" + "\n" + ">>> sc.log1p(1e-17)\n" + "1e-17\n" + ">>> np.log(1 + 1e-17)\n" + "0.0") +ufunc_log1p_loops[0] = loop_d_d__As_f_f +ufunc_log1p_loops[1] = loop_d_d__As_d_d +ufunc_log1p_loops[2] = loop_D_D__As_F_F +ufunc_log1p_loops[3] = loop_D_D__As_D_D +ufunc_log1p_types[0] = NPY_FLOAT +ufunc_log1p_types[1] = NPY_FLOAT +ufunc_log1p_types[2] = NPY_DOUBLE +ufunc_log1p_types[3] = NPY_DOUBLE +ufunc_log1p_types[4] = NPY_CFLOAT +ufunc_log1p_types[5] = NPY_CFLOAT +ufunc_log1p_types[6] = NPY_CDOUBLE +ufunc_log1p_types[7] = NPY_CDOUBLE +ufunc_log1p_ptr[2*0] = _func_cephes_log1p +ufunc_log1p_ptr[2*0+1] = ("log1p") +ufunc_log1p_ptr[2*1] = _func_cephes_log1p +ufunc_log1p_ptr[2*1+1] = ("log1p") +ufunc_log1p_ptr[2*2] = _func_clog1p +ufunc_log1p_ptr[2*2+1] = ("log1p") +ufunc_log1p_ptr[2*3] = _func_clog1p +ufunc_log1p_ptr[2*3+1] = ("log1p") +ufunc_log1p_data[0] = &ufunc_log1p_ptr[2*0] +ufunc_log1p_data[1] = &ufunc_log1p_ptr[2*1] +ufunc_log1p_data[2] = &ufunc_log1p_ptr[2*2] +ufunc_log1p_data[3] = &ufunc_log1p_ptr[2*3] +log1p = np.PyUFunc_FromFuncAndData(ufunc_log1p_loops, ufunc_log1p_data, ufunc_log1p_types, 4, 1, 1, 0, "log1p", ufunc_log1p_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_log_ndtr_loops[4] +cdef void *ufunc_log_ndtr_ptr[8] +cdef void *ufunc_log_ndtr_data[4] +cdef char ufunc_log_ndtr_types[8] +cdef char *ufunc_log_ndtr_doc = ( + "log_ndtr(x, out=None)\n" + "\n" + "Logarithm of Gaussian cumulative distribution function.\n" + "\n" + "Returns the log of the area under the standard Gaussian probability\n" + "density function, integrated from minus infinity to `x`::\n" + "\n" + " log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x))\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like, real or complex\n" + " Argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The value of the log of the normal CDF evaluated at `x`\n" + "\n" + "See Also\n" + "--------\n" + "erf\n" + "erfc\n" + "scipy.stats.norm\n" + "ndtr\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import log_ndtr, ndtr\n" + "\n" + "The benefit of ``log_ndtr(x)`` over the naive implementation\n" + "``np.log(ndtr(x))`` is most evident with moderate to large positive\n" + "values of ``x``:\n" + "\n" + ">>> x = np.array([6, 7, 9, 12, 15, 25])\n" + ">>> log_ndtr(x)\n" + "array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019,\n" + " -1.77648211e-033, -3.67096620e-051, -3.05669671e-138])\n" + "\n" + "The results of the naive calculation for the moderate ``x`` values\n" + "have only 5 or 6 correct significant digits. For values of ``x``\n" + "greater than approximately 8.3, the naive expression returns 0:\n" + "\n" + ">>> np.log(ndtr(x))\n" + "array([-9.86587701e-10, -1.27986510e-12, 0.00000000e+00,\n" + " 0.00000000e+00, 0.00000000e+00, 0.00000000e+00])") +ufunc_log_ndtr_loops[0] = loop_d_d__As_f_f +ufunc_log_ndtr_loops[1] = loop_d_d__As_d_d +ufunc_log_ndtr_loops[2] = loop_D_D__As_F_F +ufunc_log_ndtr_loops[3] = loop_D_D__As_D_D +ufunc_log_ndtr_types[0] = NPY_FLOAT +ufunc_log_ndtr_types[1] = NPY_FLOAT +ufunc_log_ndtr_types[2] = NPY_DOUBLE +ufunc_log_ndtr_types[3] = NPY_DOUBLE +ufunc_log_ndtr_types[4] = NPY_CFLOAT +ufunc_log_ndtr_types[5] = NPY_CFLOAT +ufunc_log_ndtr_types[6] = NPY_CDOUBLE +ufunc_log_ndtr_types[7] = NPY_CDOUBLE +ufunc_log_ndtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr +ufunc_log_ndtr_ptr[2*0+1] = ("log_ndtr") +ufunc_log_ndtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr +ufunc_log_ndtr_ptr[2*1+1] = ("log_ndtr") +ufunc_log_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex +ufunc_log_ndtr_ptr[2*2+1] = ("log_ndtr") +ufunc_log_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex +ufunc_log_ndtr_ptr[2*3+1] = ("log_ndtr") +ufunc_log_ndtr_data[0] = &ufunc_log_ndtr_ptr[2*0] +ufunc_log_ndtr_data[1] = &ufunc_log_ndtr_ptr[2*1] +ufunc_log_ndtr_data[2] = &ufunc_log_ndtr_ptr[2*2] +ufunc_log_ndtr_data[3] = &ufunc_log_ndtr_ptr[2*3] +log_ndtr = np.PyUFunc_FromFuncAndData(ufunc_log_ndtr_loops, ufunc_log_ndtr_data, ufunc_log_ndtr_types, 4, 1, 1, 0, "log_ndtr", ufunc_log_ndtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_lpmv_loops[2] +cdef void *ufunc_lpmv_ptr[4] +cdef void *ufunc_lpmv_data[2] +cdef char ufunc_lpmv_types[8] +cdef char *ufunc_lpmv_doc = ( + "lpmv(m, v, x, out=None)\n" + "\n" + "Associated Legendre function of integer order and real degree.\n" + "\n" + "Defined as\n" + "\n" + ".. math::\n" + "\n" + " P_v^m = (-1)^m (1 - x^2)^{m/2} \\frac{d^m}{dx^m} P_v(x)\n" + "\n" + "where\n" + "\n" + ".. math::\n" + "\n" + " P_v = \\sum_{k = 0}^\\infty \\frac{(-v)_k (v + 1)_k}{(k!)^2}\n" + " \\left(\\frac{1 - x}{2}\\right)^k\n" + "\n" + "is the Legendre function of the first kind. Here :math:`(\\cdot)_k`\n" + "is the Pochhammer symbol; see `poch`.\n" + "\n" + "Parameters\n" + "----------\n" + "m : array_like\n" + " Order (int or float). If passed a float not equal to an\n" + " integer the function returns NaN.\n" + "v : array_like\n" + " Degree (float).\n" + "x : array_like\n" + " Argument (float). Must have ``|x| <= 1``.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "pmv : scalar or ndarray\n" + " Value of the associated Legendre function.\n" + "\n" + "See Also\n" + "--------\n" + "lpmn : Compute the associated Legendre function for all orders\n" + " ``0, ..., m`` and degrees ``0, ..., n``.\n" + "clpmn : Compute the associated Legendre function at complex\n" + " arguments.\n" + "\n" + "Notes\n" + "-----\n" + "Note that this implementation includes the Condon-Shortley phase.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n" + " and Sons, Inc, 1996.") +ufunc_lpmv_loops[0] = loop_d_ddd__As_fff_f +ufunc_lpmv_loops[1] = loop_d_ddd__As_ddd_d +ufunc_lpmv_types[0] = NPY_FLOAT +ufunc_lpmv_types[1] = NPY_FLOAT +ufunc_lpmv_types[2] = NPY_FLOAT +ufunc_lpmv_types[3] = NPY_FLOAT +ufunc_lpmv_types[4] = NPY_DOUBLE +ufunc_lpmv_types[5] = NPY_DOUBLE +ufunc_lpmv_types[6] = NPY_DOUBLE +ufunc_lpmv_types[7] = NPY_DOUBLE +ufunc_lpmv_ptr[2*0] = _func_pmv_wrap +ufunc_lpmv_ptr[2*0+1] = ("lpmv") +ufunc_lpmv_ptr[2*1] = _func_pmv_wrap +ufunc_lpmv_ptr[2*1+1] = ("lpmv") +ufunc_lpmv_data[0] = &ufunc_lpmv_ptr[2*0] +ufunc_lpmv_data[1] = &ufunc_lpmv_ptr[2*1] +lpmv = np.PyUFunc_FromFuncAndData(ufunc_lpmv_loops, ufunc_lpmv_data, ufunc_lpmv_types, 2, 3, 1, 0, "lpmv", ufunc_lpmv_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nbdtr_loops[3] +cdef void *ufunc_nbdtr_ptr[6] +cdef void *ufunc_nbdtr_data[3] +cdef char ufunc_nbdtr_types[12] +cdef char *ufunc_nbdtr_doc = ( + "nbdtr(k, n, p, out=None)\n" + "\n" + "Negative binomial cumulative distribution function.\n" + "\n" + "Returns the sum of the terms 0 through `k` of the negative binomial\n" + "distribution probability mass function,\n" + "\n" + ".. math::\n" + "\n" + " F = \\sum_{j=0}^k {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n" + "\n" + "In a sequence of Bernoulli trials with individual success probabilities\n" + "`p`, this is the probability that `k` or fewer failures precede the nth\n" + "success.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " The maximum number of allowed failures (nonnegative int).\n" + "n : array_like\n" + " The target number of successes (positive int).\n" + "p : array_like\n" + " Probability of success in a single event (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "F : scalar or ndarray\n" + " The probability of `k` or fewer failures before `n` successes in a\n" + " sequence of events with individual success probability `p`.\n" + "\n" + "See Also\n" + "--------\n" + "nbdtrc : Negative binomial survival function\n" + "nbdtrik : Negative binomial quantile function\n" + "scipy.stats.nbinom : Negative binomial distribution\n" + "\n" + "Notes\n" + "-----\n" + "If floating point values are passed for `k` or `n`, they will be truncated\n" + "to integers.\n" + "\n" + "The terms are not summed directly; instead the regularized incomplete beta\n" + "function is employed, according to the formula,\n" + "\n" + ".. math::\n" + " \\mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `nbdtr`.\n" + "\n" + "The negative binomial distribution is also available as\n" + "`scipy.stats.nbinom`. Using `nbdtr` directly can improve performance\n" + "compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example).\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import nbdtr\n" + ">>> nbdtr(10, 5, 0.5)\n" + "0.940765380859375\n" + "\n" + "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n" + "providing a NumPy array or list for `k`.\n" + "\n" + ">>> nbdtr([5, 10, 15], 10, 0.5)\n" + "array([0.15087891, 0.58809853, 0.88523853])\n" + "\n" + "Plot the function for four different parameter sets.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> k = np.arange(130)\n" + ">>> n_parameters = [20, 20, 20, 80]\n" + ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(p_parameters, n_parameters,\n" + "... linestyles))\n" + ">>> fig, ax = plt.subplots(figsize=(8, 8))\n" + ">>> for parameter_set in parameters_list:\n" + "... p, n, style = parameter_set\n" + "... nbdtr_vals = nbdtr(k, n, p)\n" + "... ax.plot(k, nbdtr_vals, label=rf\"$n={n},\\, p={p}$\",\n" + "... ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_xlabel(\"$k$\")\n" + ">>> ax.set_title(\"Negative binomial cumulative distribution function\")\n" + ">>> plt.show()\n" + "\n" + "The negative binomial distribution is also available as\n" + "`scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than\n" + "calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small\n" + "arrays or individual values. To get the same results one must use the\n" + "following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``.\n" + "\n" + ">>> from scipy.stats import nbinom\n" + ">>> k, n, p = 5, 3, 0.5\n" + ">>> nbdtr_res = nbdtr(k, n, p) # this will often be faster than below\n" + ">>> stats_res = nbinom(n, p).cdf(k)\n" + ">>> stats_res, nbdtr_res # test that results are equal\n" + "(0.85546875, 0.85546875)\n" + "\n" + "`nbdtr` can evaluate different parameter sets by providing arrays with\n" + "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n" + "the function for three different `k` at four locations `p`, resulting in\n" + "a 3x4 array.\n" + "\n" + ">>> k = np.array([[5], [10], [15]])\n" + ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n" + ">>> k.shape, p.shape\n" + "((3, 1), (4,))\n" + "\n" + ">>> nbdtr(k, 5, p)\n" + "array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ],\n" + " [0.48450894, 0.94076538, 0.99932777, 0.99999999],\n" + " [0.76249222, 0.99409103, 0.99999445, 1. ]])") +ufunc_nbdtr_loops[0] = loop_d_ppd__As_ppd_d +ufunc_nbdtr_loops[1] = loop_d_ddd__As_fff_f +ufunc_nbdtr_loops[2] = loop_d_ddd__As_ddd_d +ufunc_nbdtr_types[0] = NPY_INTP +ufunc_nbdtr_types[1] = NPY_INTP +ufunc_nbdtr_types[2] = NPY_DOUBLE +ufunc_nbdtr_types[3] = NPY_DOUBLE +ufunc_nbdtr_types[4] = NPY_FLOAT +ufunc_nbdtr_types[5] = NPY_FLOAT +ufunc_nbdtr_types[6] = NPY_FLOAT +ufunc_nbdtr_types[7] = NPY_FLOAT +ufunc_nbdtr_types[8] = NPY_DOUBLE +ufunc_nbdtr_types[9] = NPY_DOUBLE +ufunc_nbdtr_types[10] = NPY_DOUBLE +ufunc_nbdtr_types[11] = NPY_DOUBLE +ufunc_nbdtr_ptr[2*0] = _func_cephes_nbdtr_wrap +ufunc_nbdtr_ptr[2*0+1] = ("nbdtr") +ufunc_nbdtr_ptr[2*1] = _func_nbdtr_unsafe +ufunc_nbdtr_ptr[2*1+1] = ("nbdtr") +ufunc_nbdtr_ptr[2*2] = _func_nbdtr_unsafe +ufunc_nbdtr_ptr[2*2+1] = ("nbdtr") +ufunc_nbdtr_data[0] = &ufunc_nbdtr_ptr[2*0] +ufunc_nbdtr_data[1] = &ufunc_nbdtr_ptr[2*1] +ufunc_nbdtr_data[2] = &ufunc_nbdtr_ptr[2*2] +nbdtr = np.PyUFunc_FromFuncAndData(ufunc_nbdtr_loops, ufunc_nbdtr_data, ufunc_nbdtr_types, 3, 3, 1, 0, "nbdtr", ufunc_nbdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nbdtrc_loops[3] +cdef void *ufunc_nbdtrc_ptr[6] +cdef void *ufunc_nbdtrc_data[3] +cdef char ufunc_nbdtrc_types[12] +cdef char *ufunc_nbdtrc_doc = ( + "nbdtrc(k, n, p, out=None)\n" + "\n" + "Negative binomial survival function.\n" + "\n" + "Returns the sum of the terms `k + 1` to infinity of the negative binomial\n" + "distribution probability mass function,\n" + "\n" + ".. math::\n" + "\n" + " F = \\sum_{j=k + 1}^\\infty {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n" + "\n" + "In a sequence of Bernoulli trials with individual success probabilities\n" + "`p`, this is the probability that more than `k` failures precede the nth\n" + "success.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " The maximum number of allowed failures (nonnegative int).\n" + "n : array_like\n" + " The target number of successes (positive int).\n" + "p : array_like\n" + " Probability of success in a single event (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "F : scalar or ndarray\n" + " The probability of `k + 1` or more failures before `n` successes in a\n" + " sequence of events with individual success probability `p`.\n" + "\n" + "See Also\n" + "--------\n" + "nbdtr : Negative binomial cumulative distribution function\n" + "nbdtrik : Negative binomial percentile function\n" + "scipy.stats.nbinom : Negative binomial distribution\n" + "\n" + "Notes\n" + "-----\n" + "If floating point values are passed for `k` or `n`, they will be truncated\n" + "to integers.\n" + "\n" + "The terms are not summed directly; instead the regularized incomplete beta\n" + "function is employed, according to the formula,\n" + "\n" + ".. math::\n" + " \\mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n).\n" + "\n" + "Wrapper for the Cephes [1]_ routine `nbdtrc`.\n" + "\n" + "The negative binomial distribution is also available as\n" + "`scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance\n" + "compared to the ``sf`` method of `scipy.stats.nbinom` (see last example).\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import nbdtrc\n" + ">>> nbdtrc(10, 5, 0.5)\n" + "0.059234619140624986\n" + "\n" + "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n" + "providing a NumPy array or list for `k`.\n" + "\n" + ">>> nbdtrc([5, 10, 15], 10, 0.5)\n" + "array([0.84912109, 0.41190147, 0.11476147])\n" + "\n" + "Plot the function for four different parameter sets.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> k = np.arange(130)\n" + ">>> n_parameters = [20, 20, 20, 80]\n" + ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(p_parameters, n_parameters,\n" + "... linestyles))\n" + ">>> fig, ax = plt.subplots(figsize=(8, 8))\n" + ">>> for parameter_set in parameters_list:\n" + "... p, n, style = parameter_set\n" + "... nbdtrc_vals = nbdtrc(k, n, p)\n" + "... ax.plot(k, nbdtrc_vals, label=rf\"$n={n},\\, p={p}$\",\n" + "... ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_xlabel(\"$k$\")\n" + ">>> ax.set_title(\"Negative binomial distribution survival function\")\n" + ">>> plt.show()\n" + "\n" + "The negative binomial distribution is also available as\n" + "`scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than\n" + "calling the ``sf`` method of `scipy.stats.nbinom`, especially for small\n" + "arrays or individual values. To get the same results one must use the\n" + "following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``.\n" + "\n" + ">>> from scipy.stats import nbinom\n" + ">>> k, n, p = 3, 5, 0.5\n" + ">>> nbdtr_res = nbdtrc(k, n, p) # this will often be faster than below\n" + ">>> stats_res = nbinom(n, p).sf(k)\n" + ">>> stats_res, nbdtr_res # test that results are equal\n" + "(0.6367187499999999, 0.6367187499999999)\n" + "\n" + "`nbdtrc` can evaluate different parameter sets by providing arrays with\n" + "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n" + "the function for three different `k` at four locations `p`, resulting in\n" + "a 3x4 array.\n" + "\n" + ">>> k = np.array([[5], [10], [15]])\n" + ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n" + ">>> k.shape, p.shape\n" + "((3, 1), (4,))\n" + "\n" + ">>> nbdtrc(k, 5, p)\n" + "array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04],\n" + " [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09],\n" + " [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]])") +ufunc_nbdtrc_loops[0] = loop_d_ppd__As_ppd_d +ufunc_nbdtrc_loops[1] = loop_d_ddd__As_fff_f +ufunc_nbdtrc_loops[2] = loop_d_ddd__As_ddd_d +ufunc_nbdtrc_types[0] = NPY_INTP +ufunc_nbdtrc_types[1] = NPY_INTP +ufunc_nbdtrc_types[2] = NPY_DOUBLE +ufunc_nbdtrc_types[3] = NPY_DOUBLE +ufunc_nbdtrc_types[4] = NPY_FLOAT +ufunc_nbdtrc_types[5] = NPY_FLOAT +ufunc_nbdtrc_types[6] = NPY_FLOAT +ufunc_nbdtrc_types[7] = NPY_FLOAT +ufunc_nbdtrc_types[8] = NPY_DOUBLE +ufunc_nbdtrc_types[9] = NPY_DOUBLE +ufunc_nbdtrc_types[10] = NPY_DOUBLE +ufunc_nbdtrc_types[11] = NPY_DOUBLE +ufunc_nbdtrc_ptr[2*0] = _func_cephes_nbdtrc_wrap +ufunc_nbdtrc_ptr[2*0+1] = ("nbdtrc") +ufunc_nbdtrc_ptr[2*1] = _func_nbdtrc_unsafe +ufunc_nbdtrc_ptr[2*1+1] = ("nbdtrc") +ufunc_nbdtrc_ptr[2*2] = _func_nbdtrc_unsafe +ufunc_nbdtrc_ptr[2*2+1] = ("nbdtrc") +ufunc_nbdtrc_data[0] = &ufunc_nbdtrc_ptr[2*0] +ufunc_nbdtrc_data[1] = &ufunc_nbdtrc_ptr[2*1] +ufunc_nbdtrc_data[2] = &ufunc_nbdtrc_ptr[2*2] +nbdtrc = np.PyUFunc_FromFuncAndData(ufunc_nbdtrc_loops, ufunc_nbdtrc_data, ufunc_nbdtrc_types, 3, 3, 1, 0, "nbdtrc", ufunc_nbdtrc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nbdtri_loops[3] +cdef void *ufunc_nbdtri_ptr[6] +cdef void *ufunc_nbdtri_data[3] +cdef char ufunc_nbdtri_types[12] +cdef char *ufunc_nbdtri_doc = ( + "nbdtri(k, n, y, out=None)\n" + "\n" + "Returns the inverse with respect to the parameter `p` of\n" + "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n" + "function.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " The maximum number of allowed failures (nonnegative int).\n" + "n : array_like\n" + " The target number of successes (positive int).\n" + "y : array_like\n" + " The probability of `k` or fewer failures before `n` successes (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "p : scalar or ndarray\n" + " Probability of success in a single event (float) such that\n" + " `nbdtr(k, n, p) = y`.\n" + "\n" + "See Also\n" + "--------\n" + "nbdtr : Cumulative distribution function of the negative binomial.\n" + "nbdtrc : Negative binomial survival function.\n" + "scipy.stats.nbinom : negative binomial distribution.\n" + "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n" + "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n" + "scipy.stats.nbinom : Negative binomial distribution\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the Cephes [1]_ routine `nbdtri`.\n" + "\n" + "The negative binomial distribution is also available as\n" + "`scipy.stats.nbinom`. Using `nbdtri` directly can improve performance\n" + "compared to the ``ppf`` method of `scipy.stats.nbinom`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "`nbdtri` is the inverse of `nbdtr` with respect to `p`.\n" + "Up to floating point errors the following holds:\n" + "``nbdtri(k, n, nbdtr(k, n, p))=p``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import nbdtri, nbdtr\n" + ">>> k, n, y = 5, 10, 0.2\n" + ">>> cdf_val = nbdtr(k, n, y)\n" + ">>> nbdtri(k, n, cdf_val)\n" + "0.20000000000000004\n" + "\n" + "Compute the function for ``k=10`` and ``n=5`` at several points by\n" + "providing a NumPy array or list for `y`.\n" + "\n" + ">>> y = np.array([0.1, 0.4, 0.8])\n" + ">>> nbdtri(3, 5, y)\n" + "array([0.34462319, 0.51653095, 0.69677416])\n" + "\n" + "Plot the function for three different parameter sets.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> n_parameters = [5, 20, 30, 30]\n" + ">>> k_parameters = [20, 20, 60, 80]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(n_parameters, k_parameters, linestyles))\n" + ">>> cdf_vals = np.linspace(0, 1, 1000)\n" + ">>> fig, ax = plt.subplots(figsize=(8, 8))\n" + ">>> for parameter_set in parameters_list:\n" + "... n, k, style = parameter_set\n" + "... nbdtri_vals = nbdtri(k, n, cdf_vals)\n" + "... ax.plot(cdf_vals, nbdtri_vals, label=rf\"$k={k},\\ n={n}$\",\n" + "... ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_ylabel(\"$p$\")\n" + ">>> ax.set_xlabel(\"$CDF$\")\n" + ">>> title = \"nbdtri: inverse of negative binomial CDF with respect to $p$\"\n" + ">>> ax.set_title(title)\n" + ">>> plt.show()\n" + "\n" + "`nbdtri` can evaluate different parameter sets by providing arrays with\n" + "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n" + "the function for three different `k` at four locations `p`, resulting in\n" + "a 3x4 array.\n" + "\n" + ">>> k = np.array([[5], [10], [15]])\n" + ">>> y = np.array([0.3, 0.5, 0.7, 0.9])\n" + ">>> k.shape, y.shape\n" + "((3, 1), (4,))\n" + "\n" + ">>> nbdtri(k, 5, y)\n" + "array([[0.37258157, 0.45169416, 0.53249956, 0.64578407],\n" + " [0.24588501, 0.30451981, 0.36778453, 0.46397088],\n" + " [0.18362101, 0.22966758, 0.28054743, 0.36066188]])") +ufunc_nbdtri_loops[0] = loop_d_ppd__As_ppd_d +ufunc_nbdtri_loops[1] = loop_d_ddd__As_fff_f +ufunc_nbdtri_loops[2] = loop_d_ddd__As_ddd_d +ufunc_nbdtri_types[0] = NPY_INTP +ufunc_nbdtri_types[1] = NPY_INTP +ufunc_nbdtri_types[2] = NPY_DOUBLE +ufunc_nbdtri_types[3] = NPY_DOUBLE +ufunc_nbdtri_types[4] = NPY_FLOAT +ufunc_nbdtri_types[5] = NPY_FLOAT +ufunc_nbdtri_types[6] = NPY_FLOAT +ufunc_nbdtri_types[7] = NPY_FLOAT +ufunc_nbdtri_types[8] = NPY_DOUBLE +ufunc_nbdtri_types[9] = NPY_DOUBLE +ufunc_nbdtri_types[10] = NPY_DOUBLE +ufunc_nbdtri_types[11] = NPY_DOUBLE +ufunc_nbdtri_ptr[2*0] = _func_cephes_nbdtri_wrap +ufunc_nbdtri_ptr[2*0+1] = ("nbdtri") +ufunc_nbdtri_ptr[2*1] = _func_nbdtri_unsafe +ufunc_nbdtri_ptr[2*1+1] = ("nbdtri") +ufunc_nbdtri_ptr[2*2] = _func_nbdtri_unsafe +ufunc_nbdtri_ptr[2*2+1] = ("nbdtri") +ufunc_nbdtri_data[0] = &ufunc_nbdtri_ptr[2*0] +ufunc_nbdtri_data[1] = &ufunc_nbdtri_ptr[2*1] +ufunc_nbdtri_data[2] = &ufunc_nbdtri_ptr[2*2] +nbdtri = np.PyUFunc_FromFuncAndData(ufunc_nbdtri_loops, ufunc_nbdtri_data, ufunc_nbdtri_types, 3, 3, 1, 0, "nbdtri", ufunc_nbdtri_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nbdtrik_loops[2] +cdef void *ufunc_nbdtrik_ptr[4] +cdef void *ufunc_nbdtrik_data[2] +cdef char ufunc_nbdtrik_types[8] +cdef char *ufunc_nbdtrik_doc = ( + "nbdtrik(y, n, p, out=None)\n" + "\n" + "Negative binomial percentile function.\n" + "\n" + "Returns the inverse with respect to the parameter `k` of\n" + "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n" + "function.\n" + "\n" + "Parameters\n" + "----------\n" + "y : array_like\n" + " The probability of `k` or fewer failures before `n` successes (float).\n" + "n : array_like\n" + " The target number of successes (positive int).\n" + "p : array_like\n" + " Probability of success in a single event (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "k : scalar or ndarray\n" + " The maximum number of allowed failures such that `nbdtr(k, n, p) = y`.\n" + "\n" + "See Also\n" + "--------\n" + "nbdtr : Cumulative distribution function of the negative binomial.\n" + "nbdtrc : Survival function of the negative binomial.\n" + "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n" + "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n" + "scipy.stats.nbinom : Negative binomial distribution\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n" + "\n" + "Formula 26.5.26 of [2]_,\n" + "\n" + ".. math::\n" + " \\sum_{j=k + 1}^\\infty {{n + j - 1}\n" + " \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n" + "\n" + "is used to reduce calculation of the cumulative distribution function to\n" + "that of a regularized incomplete beta :math:`I`.\n" + "\n" + "Computation of `k` involves a search for a value that produces the desired\n" + "value of `y`. The search relies on the monotonicity of `y` with `k`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.\n" + ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + "\n" + "Examples\n" + "--------\n" + "Compute the negative binomial cumulative distribution function for an\n" + "exemplary parameter set.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import nbdtr, nbdtrik\n" + ">>> k, n, p = 5, 2, 0.5\n" + ">>> cdf_value = nbdtr(k, n, p)\n" + ">>> cdf_value\n" + "0.9375\n" + "\n" + "Verify that `nbdtrik` recovers the original value for `k`.\n" + "\n" + ">>> nbdtrik(cdf_value, n, p)\n" + "5.0\n" + "\n" + "Plot the function for different parameter sets.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> p_parameters = [0.2, 0.5, 0.7, 0.5]\n" + ">>> n_parameters = [30, 30, 30, 80]\n" + ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n" + ">>> parameters_list = list(zip(p_parameters, n_parameters, linestyles))\n" + ">>> cdf_vals = np.linspace(0, 1, 1000)\n" + ">>> fig, ax = plt.subplots(figsize=(8, 8))\n" + ">>> for parameter_set in parameters_list:\n" + "... p, n, style = parameter_set\n" + "... nbdtrik_vals = nbdtrik(cdf_vals, n, p)\n" + "... ax.plot(cdf_vals, nbdtrik_vals, label=rf\"$n={n},\\ p={p}$\",\n" + "... ls=style)\n" + ">>> ax.legend()\n" + ">>> ax.set_ylabel(\"$k$\")\n" + ">>> ax.set_xlabel(\"$CDF$\")\n" + ">>> ax.set_title(\"Negative binomial percentile function\")\n" + ">>> plt.show()\n" + "\n" + "The negative binomial distribution is also available as\n" + "`scipy.stats.nbinom`. The percentile function method ``ppf``\n" + "returns the result of `nbdtrik` rounded up to integers:\n" + "\n" + ">>> from scipy.stats import nbinom\n" + ">>> q, n, p = 0.6, 5, 0.5\n" + ">>> nbinom.ppf(q, n, p), nbdtrik(q, n, p)\n" + "(5.0, 4.800428460273882)") +ufunc_nbdtrik_loops[0] = loop_d_ddd__As_fff_f +ufunc_nbdtrik_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nbdtrik_types[0] = NPY_FLOAT +ufunc_nbdtrik_types[1] = NPY_FLOAT +ufunc_nbdtrik_types[2] = NPY_FLOAT +ufunc_nbdtrik_types[3] = NPY_FLOAT +ufunc_nbdtrik_types[4] = NPY_DOUBLE +ufunc_nbdtrik_types[5] = NPY_DOUBLE +ufunc_nbdtrik_types[6] = NPY_DOUBLE +ufunc_nbdtrik_types[7] = NPY_DOUBLE +ufunc_nbdtrik_ptr[2*0] = _func_nbdtrik +ufunc_nbdtrik_ptr[2*0+1] = ("nbdtrik") +ufunc_nbdtrik_ptr[2*1] = _func_nbdtrik +ufunc_nbdtrik_ptr[2*1+1] = ("nbdtrik") +ufunc_nbdtrik_data[0] = &ufunc_nbdtrik_ptr[2*0] +ufunc_nbdtrik_data[1] = &ufunc_nbdtrik_ptr[2*1] +nbdtrik = np.PyUFunc_FromFuncAndData(ufunc_nbdtrik_loops, ufunc_nbdtrik_data, ufunc_nbdtrik_types, 2, 3, 1, 0, "nbdtrik", ufunc_nbdtrik_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nbdtrin_loops[2] +cdef void *ufunc_nbdtrin_ptr[4] +cdef void *ufunc_nbdtrin_data[2] +cdef char ufunc_nbdtrin_types[8] +cdef char *ufunc_nbdtrin_doc = ( + "nbdtrin(k, y, p, out=None)\n" + "\n" + "Inverse of `nbdtr` vs `n`.\n" + "\n" + "Returns the inverse with respect to the parameter `n` of\n" + "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n" + "function.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " The maximum number of allowed failures (nonnegative int).\n" + "y : array_like\n" + " The probability of `k` or fewer failures before `n` successes (float).\n" + "p : array_like\n" + " Probability of success in a single event (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "n : scalar or ndarray\n" + " The number of successes `n` such that `nbdtr(k, n, p) = y`.\n" + "\n" + "See Also\n" + "--------\n" + "nbdtr : Cumulative distribution function of the negative binomial.\n" + "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n" + "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n" + "\n" + "Formula 26.5.26 of [2]_,\n" + "\n" + ".. math::\n" + " \\sum_{j=k + 1}^\\infty {{n + j - 1}\n" + " \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n" + "\n" + "is used to reduce calculation of the cumulative distribution function to\n" + "that of a regularized incomplete beta :math:`I`.\n" + "\n" + "Computation of `n` involves a search for a value that produces the desired\n" + "value of `y`. The search relies on the monotonicity of `y` with `n`.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n" + " CDFLIB: Library of Fortran Routines for Cumulative Distribution\n" + " Functions, Inverses, and Other Parameters.\n" + ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + "\n" + "Examples\n" + "--------\n" + "Compute the negative binomial cumulative distribution function for an\n" + "exemplary parameter set.\n" + "\n" + ">>> from scipy.special import nbdtr, nbdtrin\n" + ">>> k, n, p = 5, 2, 0.5\n" + ">>> cdf_value = nbdtr(k, n, p)\n" + ">>> cdf_value\n" + "0.9375\n" + "\n" + "Verify that `nbdtrin` recovers the original value for `n` up to floating\n" + "point accuracy.\n" + "\n" + ">>> nbdtrin(k, cdf_value, p)\n" + "1.999999999998137") +ufunc_nbdtrin_loops[0] = loop_d_ddd__As_fff_f +ufunc_nbdtrin_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nbdtrin_types[0] = NPY_FLOAT +ufunc_nbdtrin_types[1] = NPY_FLOAT +ufunc_nbdtrin_types[2] = NPY_FLOAT +ufunc_nbdtrin_types[3] = NPY_FLOAT +ufunc_nbdtrin_types[4] = NPY_DOUBLE +ufunc_nbdtrin_types[5] = NPY_DOUBLE +ufunc_nbdtrin_types[6] = NPY_DOUBLE +ufunc_nbdtrin_types[7] = NPY_DOUBLE +ufunc_nbdtrin_ptr[2*0] = _func_nbdtrin +ufunc_nbdtrin_ptr[2*0+1] = ("nbdtrin") +ufunc_nbdtrin_ptr[2*1] = _func_nbdtrin +ufunc_nbdtrin_ptr[2*1+1] = ("nbdtrin") +ufunc_nbdtrin_data[0] = &ufunc_nbdtrin_ptr[2*0] +ufunc_nbdtrin_data[1] = &ufunc_nbdtrin_ptr[2*1] +nbdtrin = np.PyUFunc_FromFuncAndData(ufunc_nbdtrin_loops, ufunc_nbdtrin_data, ufunc_nbdtrin_types, 2, 3, 1, 0, "nbdtrin", ufunc_nbdtrin_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ncfdtr_loops[2] +cdef void *ufunc_ncfdtr_ptr[4] +cdef void *ufunc_ncfdtr_data[2] +cdef char ufunc_ncfdtr_types[10] +cdef char *ufunc_ncfdtr_doc = ( + "ncfdtr(dfn, dfd, nc, f, out=None)\n" + "\n" + "Cumulative distribution function of the non-central F distribution.\n" + "\n" + "The non-central F describes the distribution of,\n" + "\n" + ".. math::\n" + " Z = \\frac{X/d_n}{Y/d_d}\n" + "\n" + "where :math:`X` and :math:`Y` are independently distributed, with\n" + ":math:`X` distributed non-central :math:`\\chi^2` with noncentrality\n" + "parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y`\n" + "distributed :math:`\\chi^2` with :math:`d_d` degrees of freedom.\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " Degrees of freedom of the numerator sum of squares. Range (0, inf).\n" + "dfd : array_like\n" + " Degrees of freedom of the denominator sum of squares. Range (0, inf).\n" + "nc : array_like\n" + " Noncentrality parameter. Range [0, inf).\n" + "f : array_like\n" + " Quantiles, i.e. the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "cdf : scalar or ndarray\n" + " The calculated CDF. If all inputs are scalar, the return will be a\n" + " float. Otherwise it will be an array.\n" + "\n" + "See Also\n" + "--------\n" + "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n" + "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n" + "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n" + "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n" + "scipy.stats.ncf : Non-central F distribution.\n" + "\n" + "Notes\n" + "-----\n" + "This function calculates the CDF of the non-central f distribution using\n" + "the Boost Math C++ library [1]_.\n" + "\n" + "The cumulative distribution function is computed using Formula 26.6.20 of\n" + "[2]_:\n" + "\n" + ".. math::\n" + " F(d_n, d_d, n_c, f) = \\sum_{j=0}^\\infty e^{-n_c/2}\n" + " \\frac{(n_c/2)^j}{j!} I_{x}(\\frac{d_n}{2} + j, \\frac{d_d}{2}),\n" + "\n" + "where :math:`I` is the regularized incomplete beta function, and\n" + ":math:`x = f d_n/(f d_n + d_d)`.\n" + "\n" + "Note that argument order of `ncfdtr` is different from that of the\n" + "similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last\n" + "parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``.\n" + "\n" + "References\n" + "----------\n" + ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> from scipy import stats\n" + ">>> import matplotlib.pyplot as plt\n" + "\n" + "Plot the CDF of the non-central F distribution, for nc=0. Compare with the\n" + "F-distribution from scipy.stats:\n" + "\n" + ">>> x = np.linspace(-1, 8, num=500)\n" + ">>> dfn = 3\n" + ">>> dfd = 2\n" + ">>> ncf_stats = stats.f.cdf(x, dfn, dfd)\n" + ">>> ncf_special = special.ncfdtr(dfn, dfd, 0, x)\n" + "\n" + ">>> fig = plt.figure()\n" + ">>> ax = fig.add_subplot(111)\n" + ">>> ax.plot(x, ncf_stats, 'b-', lw=3)\n" + ">>> ax.plot(x, ncf_special, 'r-')\n" + ">>> plt.show()") +ufunc_ncfdtr_loops[0] = loop_f_ffff__As_ffff_f +ufunc_ncfdtr_loops[1] = loop_d_dddd__As_dddd_d +ufunc_ncfdtr_types[0] = NPY_FLOAT +ufunc_ncfdtr_types[1] = NPY_FLOAT +ufunc_ncfdtr_types[2] = NPY_FLOAT +ufunc_ncfdtr_types[3] = NPY_FLOAT +ufunc_ncfdtr_types[4] = NPY_FLOAT +ufunc_ncfdtr_types[5] = NPY_DOUBLE +ufunc_ncfdtr_types[6] = NPY_DOUBLE +ufunc_ncfdtr_types[7] = NPY_DOUBLE +ufunc_ncfdtr_types[8] = NPY_DOUBLE +ufunc_ncfdtr_types[9] = NPY_DOUBLE +ufunc_ncfdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_cdf_float +ufunc_ncfdtr_ptr[2*0+1] = ("ncfdtr") +ufunc_ncfdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_cdf_double +ufunc_ncfdtr_ptr[2*1+1] = ("ncfdtr") +ufunc_ncfdtr_data[0] = &ufunc_ncfdtr_ptr[2*0] +ufunc_ncfdtr_data[1] = &ufunc_ncfdtr_ptr[2*1] +ncfdtr = np.PyUFunc_FromFuncAndData(ufunc_ncfdtr_loops, ufunc_ncfdtr_data, ufunc_ncfdtr_types, 2, 4, 1, 0, "ncfdtr", ufunc_ncfdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ncfdtri_loops[2] +cdef void *ufunc_ncfdtri_ptr[4] +cdef void *ufunc_ncfdtri_data[2] +cdef char ufunc_ncfdtri_types[10] +cdef char *ufunc_ncfdtri_doc = ( + "ncfdtri(dfn, dfd, nc, p, out=None)\n" + "\n" + "Inverse with respect to `f` of the CDF of the non-central F distribution.\n" + "\n" + "See `ncfdtr` for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " Degrees of freedom of the numerator sum of squares. Range (0, inf).\n" + "dfd : array_like\n" + " Degrees of freedom of the denominator sum of squares. Range (0, inf).\n" + "nc : array_like\n" + " Noncentrality parameter. Range [0, inf).\n" + "p : array_like\n" + " Value of the cumulative distribution function. Must be in the\n" + " range [0, 1].\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "f : scalar or ndarray\n" + " Quantiles, i.e., the upper limit of integration.\n" + "\n" + "See Also\n" + "--------\n" + "ncfdtr : CDF of the non-central F distribution.\n" + "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n" + "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n" + "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n" + "scipy.stats.ncf : Non-central F distribution.\n" + "\n" + "Notes\n" + "-----\n" + "This function calculates the Quantile of the non-central f distribution\n" + "using the Boost Math C++ library [1]_.\n" + "\n" + "Note that argument order of `ncfdtri` is different from that of the\n" + "similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter\n" + "of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``.\n" + "\n" + "References\n" + "----------\n" + ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import ncfdtr, ncfdtri\n" + "\n" + "Compute the CDF for several values of `f`:\n" + "\n" + ">>> f = [0.5, 1, 1.5]\n" + ">>> p = ncfdtr(2, 3, 1.5, f)\n" + ">>> p\n" + "array([ 0.20782291, 0.36107392, 0.47345752])\n" + "\n" + "Compute the inverse. We recover the values of `f`, as expected:\n" + "\n" + ">>> ncfdtri(2, 3, 1.5, p)\n" + "array([ 0.5, 1. , 1.5])") +ufunc_ncfdtri_loops[0] = loop_f_ffff__As_ffff_f +ufunc_ncfdtri_loops[1] = loop_d_dddd__As_dddd_d +ufunc_ncfdtri_types[0] = NPY_FLOAT +ufunc_ncfdtri_types[1] = NPY_FLOAT +ufunc_ncfdtri_types[2] = NPY_FLOAT +ufunc_ncfdtri_types[3] = NPY_FLOAT +ufunc_ncfdtri_types[4] = NPY_FLOAT +ufunc_ncfdtri_types[5] = NPY_DOUBLE +ufunc_ncfdtri_types[6] = NPY_DOUBLE +ufunc_ncfdtri_types[7] = NPY_DOUBLE +ufunc_ncfdtri_types[8] = NPY_DOUBLE +ufunc_ncfdtri_types[9] = NPY_DOUBLE +ufunc_ncfdtri_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_ppf_float +ufunc_ncfdtri_ptr[2*0+1] = ("ncfdtri") +ufunc_ncfdtri_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_ppf_double +ufunc_ncfdtri_ptr[2*1+1] = ("ncfdtri") +ufunc_ncfdtri_data[0] = &ufunc_ncfdtri_ptr[2*0] +ufunc_ncfdtri_data[1] = &ufunc_ncfdtri_ptr[2*1] +ncfdtri = np.PyUFunc_FromFuncAndData(ufunc_ncfdtri_loops, ufunc_ncfdtri_data, ufunc_ncfdtri_types, 2, 4, 1, 0, "ncfdtri", ufunc_ncfdtri_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ncfdtridfd_loops[2] +cdef void *ufunc_ncfdtridfd_ptr[4] +cdef void *ufunc_ncfdtridfd_data[2] +cdef char ufunc_ncfdtridfd_types[10] +cdef char *ufunc_ncfdtridfd_doc = ( + "ncfdtridfd(dfn, p, nc, f, out=None)\n" + "\n" + "Calculate degrees of freedom (denominator) for the noncentral F-distribution.\n" + "\n" + "This is the inverse with respect to `dfd` of `ncfdtr`.\n" + "See `ncfdtr` for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " Degrees of freedom of the numerator sum of squares. Range (0, inf).\n" + "p : array_like\n" + " Value of the cumulative distribution function. Must be in the\n" + " range [0, 1].\n" + "nc : array_like\n" + " Noncentrality parameter. Should be in range (0, 1e4).\n" + "f : array_like\n" + " Quantiles, i.e., the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "dfd : scalar or ndarray\n" + " Degrees of freedom of the denominator sum of squares.\n" + "\n" + "See Also\n" + "--------\n" + "ncfdtr : CDF of the non-central F distribution.\n" + "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n" + "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n" + "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n" + "\n" + "Notes\n" + "-----\n" + "The value of the cumulative noncentral F distribution is not necessarily\n" + "monotone in either degrees of freedom. There thus may be two values that\n" + "provide a given CDF value. This routine assumes monotonicity and will\n" + "find an arbitrary one of the two values.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import ncfdtr, ncfdtridfd\n" + "\n" + "Compute the CDF for several values of `dfd`:\n" + "\n" + ">>> dfd = [1, 2, 3]\n" + ">>> p = ncfdtr(2, dfd, 0.25, 15)\n" + ">>> p\n" + "array([ 0.8097138 , 0.93020416, 0.96787852])\n" + "\n" + "Compute the inverse. We recover the values of `dfd`, as expected:\n" + "\n" + ">>> ncfdtridfd(2, p, 0.25, 15)\n" + "array([ 1., 2., 3.])") +ufunc_ncfdtridfd_loops[0] = loop_d_dddd__As_ffff_f +ufunc_ncfdtridfd_loops[1] = loop_d_dddd__As_dddd_d +ufunc_ncfdtridfd_types[0] = NPY_FLOAT +ufunc_ncfdtridfd_types[1] = NPY_FLOAT +ufunc_ncfdtridfd_types[2] = NPY_FLOAT +ufunc_ncfdtridfd_types[3] = NPY_FLOAT +ufunc_ncfdtridfd_types[4] = NPY_FLOAT +ufunc_ncfdtridfd_types[5] = NPY_DOUBLE +ufunc_ncfdtridfd_types[6] = NPY_DOUBLE +ufunc_ncfdtridfd_types[7] = NPY_DOUBLE +ufunc_ncfdtridfd_types[8] = NPY_DOUBLE +ufunc_ncfdtridfd_types[9] = NPY_DOUBLE +ufunc_ncfdtridfd_ptr[2*0] = _func_ncfdtridfd +ufunc_ncfdtridfd_ptr[2*0+1] = ("ncfdtridfd") +ufunc_ncfdtridfd_ptr[2*1] = _func_ncfdtridfd +ufunc_ncfdtridfd_ptr[2*1+1] = ("ncfdtridfd") +ufunc_ncfdtridfd_data[0] = &ufunc_ncfdtridfd_ptr[2*0] +ufunc_ncfdtridfd_data[1] = &ufunc_ncfdtridfd_ptr[2*1] +ncfdtridfd = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfd_loops, ufunc_ncfdtridfd_data, ufunc_ncfdtridfd_types, 2, 4, 1, 0, "ncfdtridfd", ufunc_ncfdtridfd_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ncfdtridfn_loops[2] +cdef void *ufunc_ncfdtridfn_ptr[4] +cdef void *ufunc_ncfdtridfn_data[2] +cdef char ufunc_ncfdtridfn_types[10] +cdef char *ufunc_ncfdtridfn_doc = ( + "ncfdtridfn(p, dfd, nc, f, out=None)\n" + "\n" + "Calculate degrees of freedom (numerator) for the noncentral F-distribution.\n" + "\n" + "This is the inverse with respect to `dfn` of `ncfdtr`.\n" + "See `ncfdtr` for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Value of the cumulative distribution function. Must be in the\n" + " range [0, 1].\n" + "dfd : array_like\n" + " Degrees of freedom of the denominator sum of squares. Range (0, inf).\n" + "nc : array_like\n" + " Noncentrality parameter. Should be in range (0, 1e4).\n" + "f : float\n" + " Quantiles, i.e., the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "dfn : scalar or ndarray\n" + " Degrees of freedom of the numerator sum of squares.\n" + "\n" + "See Also\n" + "--------\n" + "ncfdtr : CDF of the non-central F distribution.\n" + "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n" + "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n" + "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n" + "\n" + "Notes\n" + "-----\n" + "The value of the cumulative noncentral F distribution is not necessarily\n" + "monotone in either degrees of freedom. There thus may be two values that\n" + "provide a given CDF value. This routine assumes monotonicity and will\n" + "find an arbitrary one of the two values.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import ncfdtr, ncfdtridfn\n" + "\n" + "Compute the CDF for several values of `dfn`:\n" + "\n" + ">>> dfn = [1, 2, 3]\n" + ">>> p = ncfdtr(dfn, 2, 0.25, 15)\n" + ">>> p\n" + "array([ 0.92562363, 0.93020416, 0.93188394])\n" + "\n" + "Compute the inverse. We recover the values of `dfn`, as expected:\n" + "\n" + ">>> ncfdtridfn(p, 2, 0.25, 15)\n" + "array([ 1., 2., 3.])") +ufunc_ncfdtridfn_loops[0] = loop_d_dddd__As_ffff_f +ufunc_ncfdtridfn_loops[1] = loop_d_dddd__As_dddd_d +ufunc_ncfdtridfn_types[0] = NPY_FLOAT +ufunc_ncfdtridfn_types[1] = NPY_FLOAT +ufunc_ncfdtridfn_types[2] = NPY_FLOAT +ufunc_ncfdtridfn_types[3] = NPY_FLOAT +ufunc_ncfdtridfn_types[4] = NPY_FLOAT +ufunc_ncfdtridfn_types[5] = NPY_DOUBLE +ufunc_ncfdtridfn_types[6] = NPY_DOUBLE +ufunc_ncfdtridfn_types[7] = NPY_DOUBLE +ufunc_ncfdtridfn_types[8] = NPY_DOUBLE +ufunc_ncfdtridfn_types[9] = NPY_DOUBLE +ufunc_ncfdtridfn_ptr[2*0] = _func_ncfdtridfn +ufunc_ncfdtridfn_ptr[2*0+1] = ("ncfdtridfn") +ufunc_ncfdtridfn_ptr[2*1] = _func_ncfdtridfn +ufunc_ncfdtridfn_ptr[2*1+1] = ("ncfdtridfn") +ufunc_ncfdtridfn_data[0] = &ufunc_ncfdtridfn_ptr[2*0] +ufunc_ncfdtridfn_data[1] = &ufunc_ncfdtridfn_ptr[2*1] +ncfdtridfn = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfn_loops, ufunc_ncfdtridfn_data, ufunc_ncfdtridfn_types, 2, 4, 1, 0, "ncfdtridfn", ufunc_ncfdtridfn_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ncfdtrinc_loops[2] +cdef void *ufunc_ncfdtrinc_ptr[4] +cdef void *ufunc_ncfdtrinc_data[2] +cdef char ufunc_ncfdtrinc_types[10] +cdef char *ufunc_ncfdtrinc_doc = ( + "ncfdtrinc(dfn, dfd, p, f, out=None)\n" + "\n" + "Calculate non-centrality parameter for non-central F distribution.\n" + "\n" + "This is the inverse with respect to `nc` of `ncfdtr`.\n" + "See `ncfdtr` for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "dfn : array_like\n" + " Degrees of freedom of the numerator sum of squares. Range (0, inf).\n" + "dfd : array_like\n" + " Degrees of freedom of the denominator sum of squares. Range (0, inf).\n" + "p : array_like\n" + " Value of the cumulative distribution function. Must be in the\n" + " range [0, 1].\n" + "f : array_like\n" + " Quantiles, i.e., the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "nc : scalar or ndarray\n" + " Noncentrality parameter.\n" + "\n" + "See Also\n" + "--------\n" + "ncfdtr : CDF of the non-central F distribution.\n" + "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n" + "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n" + "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import ncfdtr, ncfdtrinc\n" + "\n" + "Compute the CDF for several values of `nc`:\n" + "\n" + ">>> nc = [0.5, 1.5, 2.0]\n" + ">>> p = ncfdtr(2, 3, nc, 15)\n" + ">>> p\n" + "array([ 0.96309246, 0.94327955, 0.93304098])\n" + "\n" + "Compute the inverse. We recover the values of `nc`, as expected:\n" + "\n" + ">>> ncfdtrinc(2, 3, p, 15)\n" + "array([ 0.5, 1.5, 2. ])") +ufunc_ncfdtrinc_loops[0] = loop_d_dddd__As_ffff_f +ufunc_ncfdtrinc_loops[1] = loop_d_dddd__As_dddd_d +ufunc_ncfdtrinc_types[0] = NPY_FLOAT +ufunc_ncfdtrinc_types[1] = NPY_FLOAT +ufunc_ncfdtrinc_types[2] = NPY_FLOAT +ufunc_ncfdtrinc_types[3] = NPY_FLOAT +ufunc_ncfdtrinc_types[4] = NPY_FLOAT +ufunc_ncfdtrinc_types[5] = NPY_DOUBLE +ufunc_ncfdtrinc_types[6] = NPY_DOUBLE +ufunc_ncfdtrinc_types[7] = NPY_DOUBLE +ufunc_ncfdtrinc_types[8] = NPY_DOUBLE +ufunc_ncfdtrinc_types[9] = NPY_DOUBLE +ufunc_ncfdtrinc_ptr[2*0] = _func_ncfdtrinc +ufunc_ncfdtrinc_ptr[2*0+1] = ("ncfdtrinc") +ufunc_ncfdtrinc_ptr[2*1] = _func_ncfdtrinc +ufunc_ncfdtrinc_ptr[2*1+1] = ("ncfdtrinc") +ufunc_ncfdtrinc_data[0] = &ufunc_ncfdtrinc_ptr[2*0] +ufunc_ncfdtrinc_data[1] = &ufunc_ncfdtrinc_ptr[2*1] +ncfdtrinc = np.PyUFunc_FromFuncAndData(ufunc_ncfdtrinc_loops, ufunc_ncfdtrinc_data, ufunc_ncfdtrinc_types, 2, 4, 1, 0, "ncfdtrinc", ufunc_ncfdtrinc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nctdtr_loops[2] +cdef void *ufunc_nctdtr_ptr[4] +cdef void *ufunc_nctdtr_data[2] +cdef char ufunc_nctdtr_types[8] +cdef char *ufunc_nctdtr_doc = ( + "nctdtr(df, nc, t, out=None)\n" + "\n" + "Cumulative distribution function of the non-central `t` distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "df : array_like\n" + " Degrees of freedom of the distribution. Should be in range (0, inf).\n" + "nc : array_like\n" + " Noncentrality parameter.\n" + "t : array_like\n" + " Quantiles, i.e., the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "cdf : scalar or ndarray\n" + " The calculated CDF. If all inputs are scalar, the return will be a\n" + " float. Otherwise, it will be an array.\n" + "\n" + "See Also\n" + "--------\n" + "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n" + "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n" + "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n" + "\n" + "Notes\n" + "-----\n" + "This function calculates the CDF of the non-central t distribution using\n" + "the Boost Math C++ library [1]_.\n" + "\n" + "Note that the argument order of `nctdtr` is different from that of the\n" + "similar ``cdf`` method of `scipy.stats.nct`: `t` is the last\n" + "parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``.\n" + "\n" + "References\n" + "----------\n" + ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> from scipy import stats\n" + ">>> import matplotlib.pyplot as plt\n" + "\n" + "Plot the CDF of the non-central t distribution, for nc=0. Compare with the\n" + "t-distribution from scipy.stats:\n" + "\n" + ">>> x = np.linspace(-5, 5, num=500)\n" + ">>> df = 3\n" + ">>> nct_stats = stats.t.cdf(x, df)\n" + ">>> nct_special = special.nctdtr(df, 0, x)\n" + "\n" + ">>> fig = plt.figure()\n" + ">>> ax = fig.add_subplot(111)\n" + ">>> ax.plot(x, nct_stats, 'b-', lw=3)\n" + ">>> ax.plot(x, nct_special, 'r-')\n" + ">>> plt.show()") +ufunc_nctdtr_loops[0] = loop_f_fff__As_fff_f +ufunc_nctdtr_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nctdtr_types[0] = NPY_FLOAT +ufunc_nctdtr_types[1] = NPY_FLOAT +ufunc_nctdtr_types[2] = NPY_FLOAT +ufunc_nctdtr_types[3] = NPY_FLOAT +ufunc_nctdtr_types[4] = NPY_DOUBLE +ufunc_nctdtr_types[5] = NPY_DOUBLE +ufunc_nctdtr_types[6] = NPY_DOUBLE +ufunc_nctdtr_types[7] = NPY_DOUBLE +ufunc_nctdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_cdf_float +ufunc_nctdtr_ptr[2*0+1] = ("nctdtr") +ufunc_nctdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_cdf_double +ufunc_nctdtr_ptr[2*1+1] = ("nctdtr") +ufunc_nctdtr_data[0] = &ufunc_nctdtr_ptr[2*0] +ufunc_nctdtr_data[1] = &ufunc_nctdtr_ptr[2*1] +nctdtr = np.PyUFunc_FromFuncAndData(ufunc_nctdtr_loops, ufunc_nctdtr_data, ufunc_nctdtr_types, 2, 3, 1, 0, "nctdtr", ufunc_nctdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nctdtridf_loops[2] +cdef void *ufunc_nctdtridf_ptr[4] +cdef void *ufunc_nctdtridf_data[2] +cdef char ufunc_nctdtridf_types[8] +cdef char *ufunc_nctdtridf_doc = ( + "nctdtridf(p, nc, t, out=None)\n" + "\n" + "Calculate degrees of freedom for non-central t distribution.\n" + "\n" + "See `nctdtr` for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " CDF values, in range (0, 1].\n" + "nc : array_like\n" + " Noncentrality parameter. Should be in range (-1e6, 1e6).\n" + "t : array_like\n" + " Quantiles, i.e., the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "df : scalar or ndarray\n" + " The degrees of freedom. If all inputs are scalar, the return will be a\n" + " float. Otherwise, it will be an array.\n" + "\n" + "See Also\n" + "--------\n" + "nctdtr : CDF of the non-central `t` distribution.\n" + "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n" + "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import nctdtr, nctdtridf\n" + "\n" + "Compute the CDF for several values of `df`:\n" + "\n" + ">>> df = [1, 2, 3]\n" + ">>> p = nctdtr(df, 0.25, 1)\n" + ">>> p\n" + "array([0.67491974, 0.716464 , 0.73349456])\n" + "\n" + "Compute the inverse. We recover the values of `df`, as expected:\n" + "\n" + ">>> nctdtridf(p, 0.25, 1)\n" + "array([1., 2., 3.])") +ufunc_nctdtridf_loops[0] = loop_d_ddd__As_fff_f +ufunc_nctdtridf_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nctdtridf_types[0] = NPY_FLOAT +ufunc_nctdtridf_types[1] = NPY_FLOAT +ufunc_nctdtridf_types[2] = NPY_FLOAT +ufunc_nctdtridf_types[3] = NPY_FLOAT +ufunc_nctdtridf_types[4] = NPY_DOUBLE +ufunc_nctdtridf_types[5] = NPY_DOUBLE +ufunc_nctdtridf_types[6] = NPY_DOUBLE +ufunc_nctdtridf_types[7] = NPY_DOUBLE +ufunc_nctdtridf_ptr[2*0] = _func_nctdtridf +ufunc_nctdtridf_ptr[2*0+1] = ("nctdtridf") +ufunc_nctdtridf_ptr[2*1] = _func_nctdtridf +ufunc_nctdtridf_ptr[2*1+1] = ("nctdtridf") +ufunc_nctdtridf_data[0] = &ufunc_nctdtridf_ptr[2*0] +ufunc_nctdtridf_data[1] = &ufunc_nctdtridf_ptr[2*1] +nctdtridf = np.PyUFunc_FromFuncAndData(ufunc_nctdtridf_loops, ufunc_nctdtridf_data, ufunc_nctdtridf_types, 2, 3, 1, 0, "nctdtridf", ufunc_nctdtridf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nctdtrinc_loops[2] +cdef void *ufunc_nctdtrinc_ptr[4] +cdef void *ufunc_nctdtrinc_data[2] +cdef char ufunc_nctdtrinc_types[8] +cdef char *ufunc_nctdtrinc_doc = ( + "nctdtrinc(df, p, t, out=None)\n" + "\n" + "Calculate non-centrality parameter for non-central t distribution.\n" + "\n" + "See `nctdtr` for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "df : array_like\n" + " Degrees of freedom of the distribution. Should be in range (0, inf).\n" + "p : array_like\n" + " CDF values, in range (0, 1].\n" + "t : array_like\n" + " Quantiles, i.e., the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "nc : scalar or ndarray\n" + " Noncentrality parameter\n" + "\n" + "See Also\n" + "--------\n" + "nctdtr : CDF of the non-central `t` distribution.\n" + "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n" + "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import nctdtr, nctdtrinc\n" + "\n" + "Compute the CDF for several values of `nc`:\n" + "\n" + ">>> nc = [0.5, 1.5, 2.5]\n" + ">>> p = nctdtr(3, nc, 1.5)\n" + ">>> p\n" + "array([0.77569497, 0.45524533, 0.1668691 ])\n" + "\n" + "Compute the inverse. We recover the values of `nc`, as expected:\n" + "\n" + ">>> nctdtrinc(3, p, 1.5)\n" + "array([0.5, 1.5, 2.5])") +ufunc_nctdtrinc_loops[0] = loop_d_ddd__As_fff_f +ufunc_nctdtrinc_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nctdtrinc_types[0] = NPY_FLOAT +ufunc_nctdtrinc_types[1] = NPY_FLOAT +ufunc_nctdtrinc_types[2] = NPY_FLOAT +ufunc_nctdtrinc_types[3] = NPY_FLOAT +ufunc_nctdtrinc_types[4] = NPY_DOUBLE +ufunc_nctdtrinc_types[5] = NPY_DOUBLE +ufunc_nctdtrinc_types[6] = NPY_DOUBLE +ufunc_nctdtrinc_types[7] = NPY_DOUBLE +ufunc_nctdtrinc_ptr[2*0] = _func_nctdtrinc +ufunc_nctdtrinc_ptr[2*0+1] = ("nctdtrinc") +ufunc_nctdtrinc_ptr[2*1] = _func_nctdtrinc +ufunc_nctdtrinc_ptr[2*1+1] = ("nctdtrinc") +ufunc_nctdtrinc_data[0] = &ufunc_nctdtrinc_ptr[2*0] +ufunc_nctdtrinc_data[1] = &ufunc_nctdtrinc_ptr[2*1] +nctdtrinc = np.PyUFunc_FromFuncAndData(ufunc_nctdtrinc_loops, ufunc_nctdtrinc_data, ufunc_nctdtrinc_types, 2, 3, 1, 0, "nctdtrinc", ufunc_nctdtrinc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nctdtrit_loops[2] +cdef void *ufunc_nctdtrit_ptr[4] +cdef void *ufunc_nctdtrit_data[2] +cdef char ufunc_nctdtrit_types[8] +cdef char *ufunc_nctdtrit_doc = ( + "nctdtrit(df, nc, p, out=None)\n" + "\n" + "Inverse cumulative distribution function of the non-central t distribution.\n" + "\n" + "See `nctdtr` for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "df : array_like\n" + " Degrees of freedom of the distribution. Should be in range (0, inf).\n" + "nc : array_like\n" + " Noncentrality parameter. Should be in range (-1e6, 1e6).\n" + "p : array_like\n" + " CDF values, in range (0, 1].\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "t : scalar or ndarray\n" + " Quantiles\n" + "\n" + "See Also\n" + "--------\n" + "nctdtr : CDF of the non-central `t` distribution.\n" + "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n" + "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import nctdtr, nctdtrit\n" + "\n" + "Compute the CDF for several values of `t`:\n" + "\n" + ">>> t = [0.5, 1, 1.5]\n" + ">>> p = nctdtr(3, 1, t)\n" + ">>> p\n" + "array([0.29811049, 0.46922687, 0.6257559 ])\n" + "\n" + "Compute the inverse. We recover the values of `t`, as expected:\n" + "\n" + ">>> nctdtrit(3, 1, p)\n" + "array([0.5, 1. , 1.5])") +ufunc_nctdtrit_loops[0] = loop_d_ddd__As_fff_f +ufunc_nctdtrit_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nctdtrit_types[0] = NPY_FLOAT +ufunc_nctdtrit_types[1] = NPY_FLOAT +ufunc_nctdtrit_types[2] = NPY_FLOAT +ufunc_nctdtrit_types[3] = NPY_FLOAT +ufunc_nctdtrit_types[4] = NPY_DOUBLE +ufunc_nctdtrit_types[5] = NPY_DOUBLE +ufunc_nctdtrit_types[6] = NPY_DOUBLE +ufunc_nctdtrit_types[7] = NPY_DOUBLE +ufunc_nctdtrit_ptr[2*0] = _func_nctdtrit +ufunc_nctdtrit_ptr[2*0+1] = ("nctdtrit") +ufunc_nctdtrit_ptr[2*1] = _func_nctdtrit +ufunc_nctdtrit_ptr[2*1+1] = ("nctdtrit") +ufunc_nctdtrit_data[0] = &ufunc_nctdtrit_ptr[2*0] +ufunc_nctdtrit_data[1] = &ufunc_nctdtrit_ptr[2*1] +nctdtrit = np.PyUFunc_FromFuncAndData(ufunc_nctdtrit_loops, ufunc_nctdtrit_data, ufunc_nctdtrit_types, 2, 3, 1, 0, "nctdtrit", ufunc_nctdtrit_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ndtr_loops[4] +cdef void *ufunc_ndtr_ptr[8] +cdef void *ufunc_ndtr_data[4] +cdef char ufunc_ndtr_types[8] +cdef char *ufunc_ndtr_doc = ( + "ndtr(x, out=None)\n" + "\n" + "Cumulative distribution of the standard normal distribution.\n" + "\n" + "Returns the area under the standard Gaussian probability\n" + "density function, integrated from minus infinity to `x`\n" + "\n" + ".. math::\n" + "\n" + " \\frac{1}{\\sqrt{2\\pi}} \\int_{-\\infty}^x \\exp(-t^2/2) dt\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like, real or complex\n" + " Argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The value of the normal CDF evaluated at `x`\n" + "\n" + "See Also\n" + "--------\n" + "log_ndtr : Logarithm of ndtr\n" + "ndtri : Inverse of ndtr, standard normal percentile function\n" + "erf : Error function\n" + "erfc : 1 - erf\n" + "scipy.stats.norm : Normal distribution\n" + "\n" + "Examples\n" + "--------\n" + "Evaluate `ndtr` at one point.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import ndtr\n" + ">>> ndtr(0.5)\n" + "0.6914624612740131\n" + "\n" + "Evaluate the function at several points by providing a NumPy array\n" + "or list for `x`.\n" + "\n" + ">>> ndtr([0, 0.5, 2])\n" + "array([0.5 , 0.69146246, 0.97724987])\n" + "\n" + "Plot the function.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(-5, 5, 100)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> ax.plot(x, ndtr(x))\n" + ">>> ax.set_title(r\"Standard normal cumulative distribution function $\\Phi$\")\n" + ">>> plt.show()") +ufunc_ndtr_loops[0] = loop_d_d__As_f_f +ufunc_ndtr_loops[1] = loop_d_d__As_d_d +ufunc_ndtr_loops[2] = loop_D_D__As_F_F +ufunc_ndtr_loops[3] = loop_D_D__As_D_D +ufunc_ndtr_types[0] = NPY_FLOAT +ufunc_ndtr_types[1] = NPY_FLOAT +ufunc_ndtr_types[2] = NPY_DOUBLE +ufunc_ndtr_types[3] = NPY_DOUBLE +ufunc_ndtr_types[4] = NPY_CFLOAT +ufunc_ndtr_types[5] = NPY_CFLOAT +ufunc_ndtr_types[6] = NPY_CDOUBLE +ufunc_ndtr_types[7] = NPY_CDOUBLE +ufunc_ndtr_ptr[2*0] = _func_xsf_ndtr +ufunc_ndtr_ptr[2*0+1] = ("ndtr") +ufunc_ndtr_ptr[2*1] = _func_xsf_ndtr +ufunc_ndtr_ptr[2*1+1] = ("ndtr") +ufunc_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr +ufunc_ndtr_ptr[2*2+1] = ("ndtr") +ufunc_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr +ufunc_ndtr_ptr[2*3+1] = ("ndtr") +ufunc_ndtr_data[0] = &ufunc_ndtr_ptr[2*0] +ufunc_ndtr_data[1] = &ufunc_ndtr_ptr[2*1] +ufunc_ndtr_data[2] = &ufunc_ndtr_ptr[2*2] +ufunc_ndtr_data[3] = &ufunc_ndtr_ptr[2*3] +ndtr = np.PyUFunc_FromFuncAndData(ufunc_ndtr_loops, ufunc_ndtr_data, ufunc_ndtr_types, 4, 1, 1, 0, "ndtr", ufunc_ndtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ndtri_loops[2] +cdef void *ufunc_ndtri_ptr[4] +cdef void *ufunc_ndtri_data[2] +cdef char ufunc_ndtri_types[4] +cdef char *ufunc_ndtri_doc = ( + "ndtri(y, out=None)\n" + "\n" + "Inverse of `ndtr` vs x\n" + "\n" + "Returns the argument x for which the area under the standard normal\n" + "probability density function (integrated from minus infinity to `x`)\n" + "is equal to y.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probability\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "x : scalar or ndarray\n" + " Value of x such that ``ndtr(x) == p``.\n" + "\n" + "See Also\n" + "--------\n" + "ndtr : Standard normal cumulative probability distribution\n" + "ndtri_exp : Inverse of log_ndtr\n" + "\n" + "Examples\n" + "--------\n" + "`ndtri` is the percentile function of the standard normal distribution.\n" + "This means it returns the inverse of the cumulative density `ndtr`. First,\n" + "let us compute a cumulative density value.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import ndtri, ndtr\n" + ">>> cdf_val = ndtr(2)\n" + ">>> cdf_val\n" + "0.9772498680518208\n" + "\n" + "Verify that `ndtri` yields the original value for `x` up to floating point\n" + "errors.\n" + "\n" + ">>> ndtri(cdf_val)\n" + "2.0000000000000004\n" + "\n" + "Plot the function. For that purpose, we provide a NumPy array as argument.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> x = np.linspace(0.01, 1, 200)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> ax.plot(x, ndtri(x))\n" + ">>> ax.set_title(\"Standard normal percentile function\")\n" + ">>> plt.show()") +ufunc_ndtri_loops[0] = loop_d_d__As_f_f +ufunc_ndtri_loops[1] = loop_d_d__As_d_d +ufunc_ndtri_types[0] = NPY_FLOAT +ufunc_ndtri_types[1] = NPY_FLOAT +ufunc_ndtri_types[2] = NPY_DOUBLE +ufunc_ndtri_types[3] = NPY_DOUBLE +ufunc_ndtri_ptr[2*0] = _func_xsf_ndtri +ufunc_ndtri_ptr[2*0+1] = ("ndtri") +ufunc_ndtri_ptr[2*1] = _func_xsf_ndtri +ufunc_ndtri_ptr[2*1+1] = ("ndtri") +ufunc_ndtri_data[0] = &ufunc_ndtri_ptr[2*0] +ufunc_ndtri_data[1] = &ufunc_ndtri_ptr[2*1] +ndtri = np.PyUFunc_FromFuncAndData(ufunc_ndtri_loops, ufunc_ndtri_data, ufunc_ndtri_types, 2, 1, 1, 0, "ndtri", ufunc_ndtri_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_ndtri_exp_loops[2] +cdef void *ufunc_ndtri_exp_ptr[4] +cdef void *ufunc_ndtri_exp_data[2] +cdef char ufunc_ndtri_exp_types[4] +cdef char *ufunc_ndtri_exp_doc = ( + "ndtri_exp(y, out=None)\n" + "\n" + "Inverse of `log_ndtr` vs x. Allows for greater precision than\n" + "`ndtri` composed with `numpy.exp` for very small values of y and for\n" + "y close to 0.\n" + "\n" + "Parameters\n" + "----------\n" + "y : array_like of float\n" + " Function argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Inverse of the log CDF of the standard normal distribution, evaluated\n" + " at y.\n" + "\n" + "See Also\n" + "--------\n" + "log_ndtr : log of the standard normal cumulative distribution function\n" + "ndtr : standard normal cumulative distribution function\n" + "ndtri : standard normal percentile function\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "`ndtri_exp` agrees with the naive implementation when the latter does\n" + "not suffer from underflow.\n" + "\n" + ">>> sc.ndtri_exp(-1)\n" + "-0.33747496376420244\n" + ">>> sc.ndtri(np.exp(-1))\n" + "-0.33747496376420244\n" + "\n" + "For extreme values of y, the naive approach fails\n" + "\n" + ">>> sc.ndtri(np.exp(-800))\n" + "-inf\n" + ">>> sc.ndtri(np.exp(-1e-20))\n" + "inf\n" + "\n" + "whereas `ndtri_exp` is still able to compute the result to high precision.\n" + "\n" + ">>> sc.ndtri_exp(-800)\n" + "-39.88469483825668\n" + ">>> sc.ndtri_exp(-1e-20)\n" + "9.262340089798409") +ufunc_ndtri_exp_loops[0] = loop_d_d__As_f_f +ufunc_ndtri_exp_loops[1] = loop_d_d__As_d_d +ufunc_ndtri_exp_types[0] = NPY_FLOAT +ufunc_ndtri_exp_types[1] = NPY_FLOAT +ufunc_ndtri_exp_types[2] = NPY_DOUBLE +ufunc_ndtri_exp_types[3] = NPY_DOUBLE +ufunc_ndtri_exp_ptr[2*0] = _func_ndtri_exp +ufunc_ndtri_exp_ptr[2*0+1] = ("ndtri_exp") +ufunc_ndtri_exp_ptr[2*1] = _func_ndtri_exp +ufunc_ndtri_exp_ptr[2*1+1] = ("ndtri_exp") +ufunc_ndtri_exp_data[0] = &ufunc_ndtri_exp_ptr[2*0] +ufunc_ndtri_exp_data[1] = &ufunc_ndtri_exp_ptr[2*1] +ndtri_exp = np.PyUFunc_FromFuncAndData(ufunc_ndtri_exp_loops, ufunc_ndtri_exp_data, ufunc_ndtri_exp_types, 2, 1, 1, 0, "ndtri_exp", ufunc_ndtri_exp_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nrdtrimn_loops[2] +cdef void *ufunc_nrdtrimn_ptr[4] +cdef void *ufunc_nrdtrimn_data[2] +cdef char ufunc_nrdtrimn_types[8] +cdef char *ufunc_nrdtrimn_doc = ( + "nrdtrimn(p, std, x, out=None)\n" + "\n" + "Calculate mean of normal distribution given other params.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " CDF values, in range (0, 1].\n" + "std : array_like\n" + " Standard deviation.\n" + "x : array_like\n" + " Quantiles, i.e. the upper limit of integration.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "mn : scalar or ndarray\n" + " The mean of the normal distribution.\n" + "\n" + "See Also\n" + "--------\n" + "scipy.stats.norm : Normal distribution\n" + "ndtr : Standard normal cumulative probability distribution\n" + "ndtri : Inverse of standard normal CDF with respect to quantile\n" + "nrdtrisd : Inverse of normal distribution CDF with respect to\n" + " standard deviation\n" + "\n" + "Examples\n" + "--------\n" + "`nrdtrimn` can be used to recover the mean of a normal distribution\n" + "if we know the CDF value `p` for a given quantile `x` and the\n" + "standard deviation `std`. First, we calculate\n" + "the normal distribution CDF for an exemplary parameter set.\n" + "\n" + ">>> from scipy.stats import norm\n" + ">>> mean = 3.\n" + ">>> std = 2.\n" + ">>> x = 6.\n" + ">>> p = norm.cdf(x, loc=mean, scale=std)\n" + ">>> p\n" + "0.9331927987311419\n" + "\n" + "Verify that `nrdtrimn` returns the original value for `mean`.\n" + "\n" + ">>> from scipy.special import nrdtrimn\n" + ">>> nrdtrimn(p, std, x)\n" + "3.0000000000000004") +ufunc_nrdtrimn_loops[0] = loop_d_ddd__As_fff_f +ufunc_nrdtrimn_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nrdtrimn_types[0] = NPY_FLOAT +ufunc_nrdtrimn_types[1] = NPY_FLOAT +ufunc_nrdtrimn_types[2] = NPY_FLOAT +ufunc_nrdtrimn_types[3] = NPY_FLOAT +ufunc_nrdtrimn_types[4] = NPY_DOUBLE +ufunc_nrdtrimn_types[5] = NPY_DOUBLE +ufunc_nrdtrimn_types[6] = NPY_DOUBLE +ufunc_nrdtrimn_types[7] = NPY_DOUBLE +ufunc_nrdtrimn_ptr[2*0] = _func_nrdtrimn +ufunc_nrdtrimn_ptr[2*0+1] = ("nrdtrimn") +ufunc_nrdtrimn_ptr[2*1] = _func_nrdtrimn +ufunc_nrdtrimn_ptr[2*1+1] = ("nrdtrimn") +ufunc_nrdtrimn_data[0] = &ufunc_nrdtrimn_ptr[2*0] +ufunc_nrdtrimn_data[1] = &ufunc_nrdtrimn_ptr[2*1] +nrdtrimn = np.PyUFunc_FromFuncAndData(ufunc_nrdtrimn_loops, ufunc_nrdtrimn_data, ufunc_nrdtrimn_types, 2, 3, 1, 0, "nrdtrimn", ufunc_nrdtrimn_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_nrdtrisd_loops[2] +cdef void *ufunc_nrdtrisd_ptr[4] +cdef void *ufunc_nrdtrisd_data[2] +cdef char ufunc_nrdtrisd_types[8] +cdef char *ufunc_nrdtrisd_doc = ( + "nrdtrisd(mn, p, x, out=None)\n" + "\n" + "Calculate standard deviation of normal distribution given other params.\n" + "\n" + "Parameters\n" + "----------\n" + "mn : scalar or ndarray\n" + " The mean of the normal distribution.\n" + "p : array_like\n" + " CDF values, in range (0, 1].\n" + "x : array_like\n" + " Quantiles, i.e. the upper limit of integration.\n" + "\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "std : scalar or ndarray\n" + " Standard deviation.\n" + "\n" + "See Also\n" + "--------\n" + "scipy.stats.norm : Normal distribution\n" + "ndtr : Standard normal cumulative probability distribution\n" + "ndtri : Inverse of standard normal CDF with respect to quantile\n" + "nrdtrimn : Inverse of normal distribution CDF with respect to\n" + " mean\n" + "\n" + "Examples\n" + "--------\n" + "`nrdtrisd` can be used to recover the standard deviation of a normal\n" + "distribution if we know the CDF value `p` for a given quantile `x` and\n" + "the mean `mn`. First, we calculate the normal distribution CDF for an\n" + "exemplary parameter set.\n" + "\n" + ">>> from scipy.stats import norm\n" + ">>> mean = 3.\n" + ">>> std = 2.\n" + ">>> x = 6.\n" + ">>> p = norm.cdf(x, loc=mean, scale=std)\n" + ">>> p\n" + "0.9331927987311419\n" + "\n" + "Verify that `nrdtrisd` returns the original value for `std`.\n" + "\n" + ">>> from scipy.special import nrdtrisd\n" + ">>> nrdtrisd(mean, p, x)\n" + "2.0000000000000004") +ufunc_nrdtrisd_loops[0] = loop_d_ddd__As_fff_f +ufunc_nrdtrisd_loops[1] = loop_d_ddd__As_ddd_d +ufunc_nrdtrisd_types[0] = NPY_FLOAT +ufunc_nrdtrisd_types[1] = NPY_FLOAT +ufunc_nrdtrisd_types[2] = NPY_FLOAT +ufunc_nrdtrisd_types[3] = NPY_FLOAT +ufunc_nrdtrisd_types[4] = NPY_DOUBLE +ufunc_nrdtrisd_types[5] = NPY_DOUBLE +ufunc_nrdtrisd_types[6] = NPY_DOUBLE +ufunc_nrdtrisd_types[7] = NPY_DOUBLE +ufunc_nrdtrisd_ptr[2*0] = _func_nrdtrisd +ufunc_nrdtrisd_ptr[2*0+1] = ("nrdtrisd") +ufunc_nrdtrisd_ptr[2*1] = _func_nrdtrisd +ufunc_nrdtrisd_ptr[2*1+1] = ("nrdtrisd") +ufunc_nrdtrisd_data[0] = &ufunc_nrdtrisd_ptr[2*0] +ufunc_nrdtrisd_data[1] = &ufunc_nrdtrisd_ptr[2*1] +nrdtrisd = np.PyUFunc_FromFuncAndData(ufunc_nrdtrisd_loops, ufunc_nrdtrisd_data, ufunc_nrdtrisd_types, 2, 3, 1, 0, "nrdtrisd", ufunc_nrdtrisd_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_owens_t_loops[2] +cdef void *ufunc_owens_t_ptr[4] +cdef void *ufunc_owens_t_data[2] +cdef char ufunc_owens_t_types[6] +cdef char *ufunc_owens_t_doc = ( + "owens_t(h, a, out=None)\n" + "\n" + "Owen's T Function.\n" + "\n" + "The function T(h, a) gives the probability of the event\n" + "(X > h and 0 < Y < a * X) where X and Y are independent\n" + "standard normal random variables.\n" + "\n" + "Parameters\n" + "----------\n" + "h: array_like\n" + " Input value.\n" + "a: array_like\n" + " Input value.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "t: scalar or ndarray\n" + " Probability of the event (X > h and 0 < Y < a * X),\n" + " where X and Y are independent standard normal random variables.\n" + "\n" + "References\n" + "----------\n" + ".. [1] M. Patefield and D. Tandy, \"Fast and accurate calculation of\n" + " Owen's T Function\", Statistical Software vol. 5, pp. 1-25, 2000.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy import special\n" + ">>> a = 3.5\n" + ">>> h = 0.78\n" + ">>> special.owens_t(h, a)\n" + "0.10877216734852274") +ufunc_owens_t_loops[0] = loop_d_dd__As_ff_f +ufunc_owens_t_loops[1] = loop_d_dd__As_dd_d +ufunc_owens_t_types[0] = NPY_FLOAT +ufunc_owens_t_types[1] = NPY_FLOAT +ufunc_owens_t_types[2] = NPY_FLOAT +ufunc_owens_t_types[3] = NPY_DOUBLE +ufunc_owens_t_types[4] = NPY_DOUBLE +ufunc_owens_t_types[5] = NPY_DOUBLE +ufunc_owens_t_ptr[2*0] = _func_xsf_owens_t +ufunc_owens_t_ptr[2*0+1] = ("owens_t") +ufunc_owens_t_ptr[2*1] = _func_xsf_owens_t +ufunc_owens_t_ptr[2*1+1] = ("owens_t") +ufunc_owens_t_data[0] = &ufunc_owens_t_ptr[2*0] +ufunc_owens_t_data[1] = &ufunc_owens_t_ptr[2*1] +owens_t = np.PyUFunc_FromFuncAndData(ufunc_owens_t_loops, ufunc_owens_t_data, ufunc_owens_t_types, 2, 2, 1, 0, "owens_t", ufunc_owens_t_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_pdtr_loops[2] +cdef void *ufunc_pdtr_ptr[4] +cdef void *ufunc_pdtr_data[2] +cdef char ufunc_pdtr_types[6] +cdef char *ufunc_pdtr_doc = ( + "pdtr(k, m, out=None)\n" + "\n" + "Poisson cumulative distribution function.\n" + "\n" + "Defined as the probability that a Poisson-distributed random\n" + "variable with event rate :math:`m` is less than or equal to\n" + ":math:`k`. More concretely, this works out to be [1]_\n" + "\n" + ".. math::\n" + "\n" + " \\exp(-m) \\sum_{j = 0}^{\\lfloor{k}\\rfloor} \\frac{m^j}{j!}.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " Number of occurrences (nonnegative, real)\n" + "m : array_like\n" + " Shape parameter (nonnegative, real)\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the Poisson cumulative distribution function\n" + "\n" + "See Also\n" + "--------\n" + "pdtrc : Poisson survival function\n" + "pdtrik : inverse of `pdtr` with respect to `k`\n" + "pdtri : inverse of `pdtr` with respect to `m`\n" + "\n" + "References\n" + "----------\n" + ".. [1] https://en.wikipedia.org/wiki/Poisson_distribution\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It is a cumulative distribution function, so it converges to 1\n" + "monotonically as `k` goes to infinity.\n" + "\n" + ">>> sc.pdtr([1, 10, 100, np.inf], 1)\n" + "array([0.73575888, 0.99999999, 1. , 1. ])\n" + "\n" + "It is discontinuous at integers and constant between integers.\n" + "\n" + ">>> sc.pdtr([1, 1.5, 1.9, 2], 1)\n" + "array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ])") +ufunc_pdtr_loops[0] = loop_d_dd__As_ff_f +ufunc_pdtr_loops[1] = loop_d_dd__As_dd_d +ufunc_pdtr_types[0] = NPY_FLOAT +ufunc_pdtr_types[1] = NPY_FLOAT +ufunc_pdtr_types[2] = NPY_FLOAT +ufunc_pdtr_types[3] = NPY_DOUBLE +ufunc_pdtr_types[4] = NPY_DOUBLE +ufunc_pdtr_types[5] = NPY_DOUBLE +ufunc_pdtr_ptr[2*0] = _func_xsf_pdtr +ufunc_pdtr_ptr[2*0+1] = ("pdtr") +ufunc_pdtr_ptr[2*1] = _func_xsf_pdtr +ufunc_pdtr_ptr[2*1+1] = ("pdtr") +ufunc_pdtr_data[0] = &ufunc_pdtr_ptr[2*0] +ufunc_pdtr_data[1] = &ufunc_pdtr_ptr[2*1] +pdtr = np.PyUFunc_FromFuncAndData(ufunc_pdtr_loops, ufunc_pdtr_data, ufunc_pdtr_types, 2, 2, 1, 0, "pdtr", ufunc_pdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_pdtrc_loops[2] +cdef void *ufunc_pdtrc_ptr[4] +cdef void *ufunc_pdtrc_data[2] +cdef char ufunc_pdtrc_types[6] +cdef char *ufunc_pdtrc_doc = ( + "pdtrc(k, m, out=None)\n" + "\n" + "Poisson survival function\n" + "\n" + "Returns the sum of the terms from k+1 to infinity of the Poisson\n" + "distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc(\n" + "k+1, m). Arguments must both be non-negative doubles.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " Number of occurrences (nonnegative, real)\n" + "m : array_like\n" + " Shape parameter (nonnegative, real)\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the Poisson survival function\n" + "\n" + "See Also\n" + "--------\n" + "pdtr : Poisson cumulative distribution function\n" + "pdtrik : inverse of `pdtr` with respect to `k`\n" + "pdtri : inverse of `pdtr` with respect to `m`\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import scipy.special as sc\n" + "\n" + "It is a survival function, so it decreases to 0\n" + "monotonically as `k` goes to infinity.\n" + "\n" + ">>> k = np.array([1, 10, 100, np.inf])\n" + ">>> sc.pdtrc(k, 1)\n" + "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])\n" + "\n" + "It can be expressed in terms of the lower incomplete gamma\n" + "function `gammainc`.\n" + "\n" + ">>> sc.gammainc(k + 1, 1)\n" + "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])") +ufunc_pdtrc_loops[0] = loop_d_dd__As_ff_f +ufunc_pdtrc_loops[1] = loop_d_dd__As_dd_d +ufunc_pdtrc_types[0] = NPY_FLOAT +ufunc_pdtrc_types[1] = NPY_FLOAT +ufunc_pdtrc_types[2] = NPY_FLOAT +ufunc_pdtrc_types[3] = NPY_DOUBLE +ufunc_pdtrc_types[4] = NPY_DOUBLE +ufunc_pdtrc_types[5] = NPY_DOUBLE +ufunc_pdtrc_ptr[2*0] = _func_xsf_pdtrc +ufunc_pdtrc_ptr[2*0+1] = ("pdtrc") +ufunc_pdtrc_ptr[2*1] = _func_xsf_pdtrc +ufunc_pdtrc_ptr[2*1+1] = ("pdtrc") +ufunc_pdtrc_data[0] = &ufunc_pdtrc_ptr[2*0] +ufunc_pdtrc_data[1] = &ufunc_pdtrc_ptr[2*1] +pdtrc = np.PyUFunc_FromFuncAndData(ufunc_pdtrc_loops, ufunc_pdtrc_data, ufunc_pdtrc_types, 2, 2, 1, 0, "pdtrc", ufunc_pdtrc_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_pdtri_loops[3] +cdef void *ufunc_pdtri_ptr[6] +cdef void *ufunc_pdtri_data[3] +cdef char ufunc_pdtri_types[9] +cdef char *ufunc_pdtri_doc = ( + "pdtri(k, y, out=None)\n" + "\n" + "Inverse to `pdtr` vs m\n" + "\n" + "Returns the Poisson variable `m` such that the sum from 0 to `k` of\n" + "the Poisson density is equal to the given probability `y`:\n" + "calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative\n" + "integer and `y` between 0 and 1.\n" + "\n" + "Parameters\n" + "----------\n" + "k : array_like\n" + " Number of occurrences (nonnegative, real)\n" + "y : array_like\n" + " Probability\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Values of the shape parameter `m` such that ``pdtr(k, m) = p``\n" + "\n" + "See Also\n" + "--------\n" + "pdtr : Poisson cumulative distribution function\n" + "pdtrc : Poisson survival function\n" + "pdtrik : inverse of `pdtr` with respect to `k`\n" + "\n" + "Examples\n" + "--------\n" + ">>> import scipy.special as sc\n" + "\n" + "Compute the CDF for several values of `m`:\n" + "\n" + ">>> m = [0.5, 1, 1.5]\n" + ">>> p = sc.pdtr(1, m)\n" + ">>> p\n" + "array([0.90979599, 0.73575888, 0.5578254 ])\n" + "\n" + "Compute the inverse. We recover the values of `m`, as expected:\n" + "\n" + ">>> sc.pdtri(1, p)\n" + "array([0.5, 1. , 1.5])") +ufunc_pdtri_loops[0] = loop_d_pd__As_pd_d +ufunc_pdtri_loops[1] = loop_d_dd__As_ff_f +ufunc_pdtri_loops[2] = loop_d_dd__As_dd_d +ufunc_pdtri_types[0] = NPY_INTP +ufunc_pdtri_types[1] = NPY_DOUBLE +ufunc_pdtri_types[2] = NPY_DOUBLE +ufunc_pdtri_types[3] = NPY_FLOAT +ufunc_pdtri_types[4] = NPY_FLOAT +ufunc_pdtri_types[5] = NPY_FLOAT +ufunc_pdtri_types[6] = NPY_DOUBLE +ufunc_pdtri_types[7] = NPY_DOUBLE +ufunc_pdtri_types[8] = NPY_DOUBLE +ufunc_pdtri_ptr[2*0] = _func_cephes_pdtri_wrap +ufunc_pdtri_ptr[2*0+1] = ("pdtri") +ufunc_pdtri_ptr[2*1] = _func_pdtri_unsafe +ufunc_pdtri_ptr[2*1+1] = ("pdtri") +ufunc_pdtri_ptr[2*2] = _func_pdtri_unsafe +ufunc_pdtri_ptr[2*2+1] = ("pdtri") +ufunc_pdtri_data[0] = &ufunc_pdtri_ptr[2*0] +ufunc_pdtri_data[1] = &ufunc_pdtri_ptr[2*1] +ufunc_pdtri_data[2] = &ufunc_pdtri_ptr[2*2] +pdtri = np.PyUFunc_FromFuncAndData(ufunc_pdtri_loops, ufunc_pdtri_data, ufunc_pdtri_types, 3, 2, 1, 0, "pdtri", ufunc_pdtri_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_pdtrik_loops[2] +cdef void *ufunc_pdtrik_ptr[4] +cdef void *ufunc_pdtrik_data[2] +cdef char ufunc_pdtrik_types[6] +cdef char *ufunc_pdtrik_doc = ( + "pdtrik(p, m, out=None)\n" + "\n" + "Inverse to `pdtr` vs `k`.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probability\n" + "m : array_like\n" + " Shape parameter (nonnegative, real)\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The number of occurrences `k` such that ``pdtr(k, m) = p``\n" + "\n" + "See Also\n" + "--------\n" + "pdtr : Poisson cumulative distribution function\n" + "pdtrc : Poisson survival function\n" + "pdtri : inverse of `pdtr` with respect to `m`\n" + "\n" + "Examples\n" + "--------\n" + ">>> import scipy.special as sc\n" + "\n" + "Compute the CDF for several values of `k`:\n" + "\n" + ">>> k = [1, 2, 3]\n" + ">>> p = sc.pdtr(k, 2)\n" + ">>> p\n" + "array([0.40600585, 0.67667642, 0.85712346])\n" + "\n" + "Compute the inverse. We recover the values of `k`, as expected:\n" + "\n" + ">>> sc.pdtrik(p, 2)\n" + "array([1., 2., 3.])") +ufunc_pdtrik_loops[0] = loop_d_dd__As_ff_f +ufunc_pdtrik_loops[1] = loop_d_dd__As_dd_d +ufunc_pdtrik_types[0] = NPY_FLOAT +ufunc_pdtrik_types[1] = NPY_FLOAT +ufunc_pdtrik_types[2] = NPY_FLOAT +ufunc_pdtrik_types[3] = NPY_DOUBLE +ufunc_pdtrik_types[4] = NPY_DOUBLE +ufunc_pdtrik_types[5] = NPY_DOUBLE +ufunc_pdtrik_ptr[2*0] = _func_pdtrik +ufunc_pdtrik_ptr[2*0+1] = ("pdtrik") +ufunc_pdtrik_ptr[2*1] = _func_pdtrik +ufunc_pdtrik_ptr[2*1+1] = ("pdtrik") +ufunc_pdtrik_data[0] = &ufunc_pdtrik_ptr[2*0] +ufunc_pdtrik_data[1] = &ufunc_pdtrik_ptr[2*1] +pdtrik = np.PyUFunc_FromFuncAndData(ufunc_pdtrik_loops, ufunc_pdtrik_data, ufunc_pdtrik_types, 2, 2, 1, 0, "pdtrik", ufunc_pdtrik_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_poch_loops[2] +cdef void *ufunc_poch_ptr[4] +cdef void *ufunc_poch_data[2] +cdef char ufunc_poch_types[6] +cdef char *ufunc_poch_doc = ( + "poch(z, m, out=None)\n" + "\n" + "Pochhammer symbol.\n" + "\n" + "The Pochhammer symbol (rising factorial) is defined as\n" + "\n" + ".. math::\n" + "\n" + " (z)_m = \\frac{\\Gamma(z + m)}{\\Gamma(z)}\n" + "\n" + "For positive integer `m` it reads\n" + "\n" + ".. math::\n" + "\n" + " (z)_m = z (z + 1) ... (z + m - 1)\n" + "\n" + "See [dlmf]_ for more details.\n" + "\n" + "Parameters\n" + "----------\n" + "z, m : array_like\n" + " Real-valued arguments.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The value of the function.\n" + "\n" + "References\n" + "----------\n" + ".. [dlmf] Nist, Digital Library of Mathematical Functions\n" + " https://dlmf.nist.gov/5.2#iii\n" + "\n" + "Examples\n" + "--------\n" + ">>> import scipy.special as sc\n" + "\n" + "It is 1 when m is 0.\n" + "\n" + ">>> sc.poch([1, 2, 3, 4], 0)\n" + "array([1., 1., 1., 1.])\n" + "\n" + "For z equal to 1 it reduces to the factorial function.\n" + "\n" + ">>> sc.poch(1, 5)\n" + "120.0\n" + ">>> 1 * 2 * 3 * 4 * 5\n" + "120\n" + "\n" + "It can be expressed in terms of the gamma function.\n" + "\n" + ">>> z, m = 3.7, 2.1\n" + ">>> sc.poch(z, m)\n" + "20.529581933776953\n" + ">>> sc.gamma(z + m) / sc.gamma(z)\n" + "20.52958193377696") +ufunc_poch_loops[0] = loop_d_dd__As_ff_f +ufunc_poch_loops[1] = loop_d_dd__As_dd_d +ufunc_poch_types[0] = NPY_FLOAT +ufunc_poch_types[1] = NPY_FLOAT +ufunc_poch_types[2] = NPY_FLOAT +ufunc_poch_types[3] = NPY_DOUBLE +ufunc_poch_types[4] = NPY_DOUBLE +ufunc_poch_types[5] = NPY_DOUBLE +ufunc_poch_ptr[2*0] = _func_cephes_poch +ufunc_poch_ptr[2*0+1] = ("poch") +ufunc_poch_ptr[2*1] = _func_cephes_poch +ufunc_poch_ptr[2*1+1] = ("poch") +ufunc_poch_data[0] = &ufunc_poch_ptr[2*0] +ufunc_poch_data[1] = &ufunc_poch_ptr[2*1] +poch = np.PyUFunc_FromFuncAndData(ufunc_poch_loops, ufunc_poch_data, ufunc_poch_types, 2, 2, 1, 0, "poch", ufunc_poch_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_powm1_loops[2] +cdef void *ufunc_powm1_ptr[4] +cdef void *ufunc_powm1_data[2] +cdef char ufunc_powm1_types[6] +cdef char *ufunc_powm1_doc = ( + "powm1(x, y, out=None)\n" + "\n" + "Computes ``x**y - 1``.\n" + "\n" + "This function is useful when `y` is near 0, or when `x` is near 1.\n" + "\n" + "The function is implemented for real types only (unlike ``numpy.power``,\n" + "which accepts complex inputs).\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " The base. Must be a real type (i.e. integer or float, not complex).\n" + "y : array_like\n" + " The exponent. Must be a real type (i.e. integer or float, not complex).\n" + "\n" + "Returns\n" + "-------\n" + "array_like\n" + " Result of the calculation\n" + "\n" + "Notes\n" + "-----\n" + ".. versionadded:: 1.10.0\n" + "\n" + "The underlying code is implemented for single precision and double\n" + "precision floats only. Unlike `numpy.power`, integer inputs to\n" + "`powm1` are converted to floating point, and complex inputs are\n" + "not accepted.\n" + "\n" + "Note the following edge cases:\n" + "\n" + "* ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf``\n" + " and ``nan``.\n" + "* ``powm1(1, y)`` returns 0 for any ``y``, including ``nan``\n" + " and ``inf``.\n" + "\n" + "This function wraps the ``powm1`` routine from the\n" + "Boost Math C++ library [1]_.\n" + "\n" + "References\n" + "----------\n" + ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import powm1\n" + "\n" + ">>> x = np.array([1.2, 10.0, 0.9999999975])\n" + ">>> y = np.array([1e-9, 1e-11, 0.1875])\n" + ">>> powm1(x, y)\n" + "array([ 1.82321557e-10, 2.30258509e-11, -4.68749998e-10])\n" + "\n" + "It can be verified that the relative errors in those results\n" + "are less than 2.5e-16.\n" + "\n" + "Compare that to the result of ``x**y - 1``, where the\n" + "relative errors are all larger than 8e-8:\n" + "\n" + ">>> x**y - 1\n" + "array([ 1.82321491e-10, 2.30258035e-11, -4.68750039e-10])") +ufunc_powm1_loops[0] = loop_f_ff__As_ff_f +ufunc_powm1_loops[1] = loop_d_dd__As_dd_d +ufunc_powm1_types[0] = NPY_FLOAT +ufunc_powm1_types[1] = NPY_FLOAT +ufunc_powm1_types[2] = NPY_FLOAT +ufunc_powm1_types[3] = NPY_DOUBLE +ufunc_powm1_types[4] = NPY_DOUBLE +ufunc_powm1_types[5] = NPY_DOUBLE +ufunc_powm1_ptr[2*0] = scipy.special._ufuncs_cxx._export_powm1_float +ufunc_powm1_ptr[2*0+1] = ("powm1") +ufunc_powm1_ptr[2*1] = scipy.special._ufuncs_cxx._export_powm1_double +ufunc_powm1_ptr[2*1+1] = ("powm1") +ufunc_powm1_data[0] = &ufunc_powm1_ptr[2*0] +ufunc_powm1_data[1] = &ufunc_powm1_ptr[2*1] +powm1 = np.PyUFunc_FromFuncAndData(ufunc_powm1_loops, ufunc_powm1_data, ufunc_powm1_types, 2, 2, 1, 0, "powm1", ufunc_powm1_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_pseudo_huber_loops[2] +cdef void *ufunc_pseudo_huber_ptr[4] +cdef void *ufunc_pseudo_huber_data[2] +cdef char ufunc_pseudo_huber_types[6] +cdef char *ufunc_pseudo_huber_doc = ( + "pseudo_huber(delta, r, out=None)\n" + "\n" + "Pseudo-Huber loss function.\n" + "\n" + ".. math:: \\mathrm{pseudo\\_huber}(\\delta, r) =\n" + " \\delta^2 \\left( \\sqrt{ 1 + \\left( \\frac{r}{\\delta} \\right)^2 } - 1 \\right)\n" + "\n" + "Parameters\n" + "----------\n" + "delta : array_like\n" + " Input array, indicating the soft quadratic vs. linear loss changepoint.\n" + "r : array_like\n" + " Input array, possibly representing residuals.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "res : scalar or ndarray\n" + " The computed Pseudo-Huber loss function values.\n" + "\n" + "See Also\n" + "--------\n" + "huber: Similar function which this function approximates\n" + "\n" + "Notes\n" + "-----\n" + "Like `huber`, `pseudo_huber` often serves as a robust loss function\n" + "in statistics or machine learning to reduce the influence of outliers.\n" + "Unlike `huber`, `pseudo_huber` is smooth.\n" + "\n" + "Typically, `r` represents residuals, the difference\n" + "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n" + "`pseudo_huber` resembles the squared error and for :math:`|r|>\\delta` the\n" + "absolute error. This way, the Pseudo-Huber loss often achieves\n" + "a fast convergence in model fitting for small residuals like the squared\n" + "error loss function and still reduces the influence of outliers\n" + "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n" + "the cutoff between squared and absolute error regimes, it has\n" + "to be tuned carefully for each problem. `pseudo_huber` is also\n" + "convex, making it suitable for gradient based optimization. [1]_ [2]_\n" + "\n" + ".. versionadded:: 0.15.0\n" + "\n" + "References\n" + "----------\n" + ".. [1] Hartley, Zisserman, \"Multiple View Geometry in Computer Vision\".\n" + " 2003. Cambridge University Press. p. 619\n" + ".. [2] Charbonnier et al. \"Deterministic edge-preserving regularization\n" + " in computed imaging\". 1997. IEEE Trans. Image Processing.\n" + " 6 (2): 298 - 311.\n" + "\n" + "Examples\n" + "--------\n" + "Import all necessary modules.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import pseudo_huber, huber\n" + ">>> import matplotlib.pyplot as plt\n" + "\n" + "Calculate the function for ``delta=1`` at ``r=2``.\n" + "\n" + ">>> pseudo_huber(1., 2.)\n" + "1.2360679774997898\n" + "\n" + "Calculate the function at ``r=2`` for different `delta` by providing\n" + "a list or NumPy array for `delta`.\n" + "\n" + ">>> pseudo_huber([1., 2., 4.], 3.)\n" + "array([2.16227766, 3.21110255, 4. ])\n" + "\n" + "Calculate the function for ``delta=1`` at several points by providing\n" + "a list or NumPy array for `r`.\n" + "\n" + ">>> pseudo_huber(2., np.array([1., 1.5, 3., 4.]))\n" + "array([0.47213595, 1. , 3.21110255, 4.94427191])\n" + "\n" + "The function can be calculated for different `delta` and `r` by\n" + "providing arrays for both with compatible shapes for broadcasting.\n" + "\n" + ">>> r = np.array([1., 2.5, 8., 10.])\n" + ">>> deltas = np.array([[1.], [5.], [9.]])\n" + ">>> print(r.shape, deltas.shape)\n" + "(4,) (3, 1)\n" + "\n" + ">>> pseudo_huber(deltas, r)\n" + "array([[ 0.41421356, 1.6925824 , 7.06225775, 9.04987562],\n" + " [ 0.49509757, 2.95084972, 22.16990566, 30.90169944],\n" + " [ 0.49846624, 3.06693762, 27.37435121, 40.08261642]])\n" + "\n" + "Plot the function for different `delta`.\n" + "\n" + ">>> x = np.linspace(-4, 4, 500)\n" + ">>> deltas = [1, 2, 3]\n" + ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n" + ">>> fig, ax = plt.subplots()\n" + ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n" + ">>> for delta, style in combined_plot_parameters:\n" + "... ax.plot(x, pseudo_huber(delta, x), label=rf\"$\\delta={delta}$\",\n" + "... ls=style)\n" + ">>> ax.legend(loc=\"upper center\")\n" + ">>> ax.set_xlabel(\"$x$\")\n" + ">>> ax.set_title(r\"Pseudo-Huber loss function $h_{\\delta}(x)$\")\n" + ">>> ax.set_xlim(-4, 4)\n" + ">>> ax.set_ylim(0, 8)\n" + ">>> plt.show()\n" + "\n" + "Finally, illustrate the difference between `huber` and `pseudo_huber` by\n" + "plotting them and their gradients with respect to `r`. The plot shows\n" + "that `pseudo_huber` is continuously differentiable while `huber` is not\n" + "at the points :math:`\\pm\\delta`.\n" + "\n" + ">>> def huber_grad(delta, x):\n" + "... grad = np.copy(x)\n" + "... linear_area = np.argwhere(np.abs(x) > delta)\n" + "... grad[linear_area]=delta*np.sign(x[linear_area])\n" + "... return grad\n" + ">>> def pseudo_huber_grad(delta, x):\n" + "... return x* (1+(x/delta)**2)**(-0.5)\n" + ">>> x=np.linspace(-3, 3, 500)\n" + ">>> delta = 1.\n" + ">>> fig, ax = plt.subplots(figsize=(7, 7))\n" + ">>> ax.plot(x, huber(delta, x), label=\"Huber\", ls=\"dashed\")\n" + ">>> ax.plot(x, huber_grad(delta, x), label=\"Huber Gradient\", ls=\"dashdot\")\n" + ">>> ax.plot(x, pseudo_huber(delta, x), label=\"Pseudo-Huber\", ls=\"dotted\")\n" + ">>> ax.plot(x, pseudo_huber_grad(delta, x), label=\"Pseudo-Huber Gradient\",\n" + "... ls=\"solid\")\n" + ">>> ax.legend(loc=\"upper center\")\n" + ">>> plt.show()") +ufunc_pseudo_huber_loops[0] = loop_d_dd__As_ff_f +ufunc_pseudo_huber_loops[1] = loop_d_dd__As_dd_d +ufunc_pseudo_huber_types[0] = NPY_FLOAT +ufunc_pseudo_huber_types[1] = NPY_FLOAT +ufunc_pseudo_huber_types[2] = NPY_FLOAT +ufunc_pseudo_huber_types[3] = NPY_DOUBLE +ufunc_pseudo_huber_types[4] = NPY_DOUBLE +ufunc_pseudo_huber_types[5] = NPY_DOUBLE +ufunc_pseudo_huber_ptr[2*0] = _func_pseudo_huber +ufunc_pseudo_huber_ptr[2*0+1] = ("pseudo_huber") +ufunc_pseudo_huber_ptr[2*1] = _func_pseudo_huber +ufunc_pseudo_huber_ptr[2*1+1] = ("pseudo_huber") +ufunc_pseudo_huber_data[0] = &ufunc_pseudo_huber_ptr[2*0] +ufunc_pseudo_huber_data[1] = &ufunc_pseudo_huber_ptr[2*1] +pseudo_huber = np.PyUFunc_FromFuncAndData(ufunc_pseudo_huber_loops, ufunc_pseudo_huber_data, ufunc_pseudo_huber_types, 2, 2, 1, 0, "pseudo_huber", ufunc_pseudo_huber_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_rel_entr_loops[2] +cdef void *ufunc_rel_entr_ptr[4] +cdef void *ufunc_rel_entr_data[2] +cdef char ufunc_rel_entr_types[6] +cdef char *ufunc_rel_entr_doc = ( + "rel_entr(x, y, out=None)\n" + "\n" + "Elementwise function for computing relative entropy.\n" + "\n" + ".. math::\n" + "\n" + " \\mathrm{rel\\_entr}(x, y) =\n" + " \\begin{cases}\n" + " x \\log(x / y) & x > 0, y > 0 \\\\\n" + " 0 & x = 0, y \\ge 0 \\\\\n" + " \\infty & \\text{otherwise}\n" + " \\end{cases}\n" + "\n" + "Parameters\n" + "----------\n" + "x, y : array_like\n" + " Input arrays\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Relative entropy of the inputs\n" + "\n" + "See Also\n" + "--------\n" + "entr, kl_div, scipy.stats.entropy\n" + "\n" + "Notes\n" + "-----\n" + ".. versionadded:: 0.15.0\n" + "\n" + "This function is jointly convex in x and y.\n" + "\n" + "The origin of this function is in convex programming; see\n" + "[1]_. Given two discrete probability distributions :math:`p_1,\n" + "\\ldots, p_n` and :math:`q_1, \\ldots, q_n`, the definition of relative\n" + "entropy in the context of *information theory* is\n" + "\n" + ".. math::\n" + "\n" + " \\sum_{i = 1}^n \\mathrm{rel\\_entr}(p_i, q_i).\n" + "\n" + "To compute the latter quantity, use `scipy.stats.entropy`.\n" + "\n" + "See [2]_ for details.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n" + " Cambridge University Press, 2004.\n" + " :doi:`https://doi.org/10.1017/CBO9780511804441`\n" + ".. [2] Kullback-Leibler divergence,\n" + " https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence") +ufunc_rel_entr_loops[0] = loop_d_dd__As_ff_f +ufunc_rel_entr_loops[1] = loop_d_dd__As_dd_d +ufunc_rel_entr_types[0] = NPY_FLOAT +ufunc_rel_entr_types[1] = NPY_FLOAT +ufunc_rel_entr_types[2] = NPY_FLOAT +ufunc_rel_entr_types[3] = NPY_DOUBLE +ufunc_rel_entr_types[4] = NPY_DOUBLE +ufunc_rel_entr_types[5] = NPY_DOUBLE +ufunc_rel_entr_ptr[2*0] = _func_rel_entr +ufunc_rel_entr_ptr[2*0+1] = ("rel_entr") +ufunc_rel_entr_ptr[2*1] = _func_rel_entr +ufunc_rel_entr_ptr[2*1+1] = ("rel_entr") +ufunc_rel_entr_data[0] = &ufunc_rel_entr_ptr[2*0] +ufunc_rel_entr_data[1] = &ufunc_rel_entr_ptr[2*1] +rel_entr = np.PyUFunc_FromFuncAndData(ufunc_rel_entr_loops, ufunc_rel_entr_data, ufunc_rel_entr_types, 2, 2, 1, 0, "rel_entr", ufunc_rel_entr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_round_loops[2] +cdef void *ufunc_round_ptr[4] +cdef void *ufunc_round_data[2] +cdef char ufunc_round_types[4] +cdef char *ufunc_round_doc = ( + "round(x, out=None)\n" + "\n" + "Round to the nearest integer.\n" + "\n" + "Returns the nearest integer to `x`. If `x` ends in 0.5 exactly,\n" + "the nearest even integer is chosen.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real valued input.\n" + "out : ndarray, optional\n" + " Optional output array for the function results.\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The nearest integers to the elements of `x`. The result is of\n" + " floating type, not integer type.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import scipy.special as sc\n" + "\n" + "It rounds to even.\n" + "\n" + ">>> sc.round([0.5, 1.5])\n" + "array([0., 2.])") +ufunc_round_loops[0] = loop_d_d__As_f_f +ufunc_round_loops[1] = loop_d_d__As_d_d +ufunc_round_types[0] = NPY_FLOAT +ufunc_round_types[1] = NPY_FLOAT +ufunc_round_types[2] = NPY_DOUBLE +ufunc_round_types[3] = NPY_DOUBLE +ufunc_round_ptr[2*0] = _func_cephes_round +ufunc_round_ptr[2*0+1] = ("round") +ufunc_round_ptr[2*1] = _func_cephes_round +ufunc_round_ptr[2*1+1] = ("round") +ufunc_round_data[0] = &ufunc_round_ptr[2*0] +ufunc_round_data[1] = &ufunc_round_ptr[2*1] +round = np.PyUFunc_FromFuncAndData(ufunc_round_loops, ufunc_round_data, ufunc_round_types, 2, 1, 1, 0, "round", ufunc_round_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_shichi_loops[4] +cdef void *ufunc_shichi_ptr[8] +cdef void *ufunc_shichi_data[4] +cdef char ufunc_shichi_types[12] +cdef char *ufunc_shichi_doc = ( + "shichi(x, out=None)\n" + "\n" + "Hyperbolic sine and cosine integrals.\n" + "\n" + "The hyperbolic sine integral is\n" + "\n" + ".. math::\n" + "\n" + " \\int_0^x \\frac{\\sinh{t}}{t}dt\n" + "\n" + "and the hyperbolic cosine integral is\n" + "\n" + ".. math::\n" + "\n" + " \\gamma + \\log(x) + \\int_0^x \\frac{\\cosh{t} - 1}{t} dt\n" + "\n" + "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n" + "principal branch of the logarithm [1]_.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real or complex points at which to compute the hyperbolic sine\n" + " and cosine integrals.\n" + "out : tuple of ndarray, optional\n" + " Optional output arrays for the function results\n" + "\n" + "Returns\n" + "-------\n" + "si : scalar or ndarray\n" + " Hyperbolic sine integral at ``x``\n" + "ci : scalar or ndarray\n" + " Hyperbolic cosine integral at ``x``\n" + "\n" + "See Also\n" + "--------\n" + "sici : Sine and cosine integrals.\n" + "exp1 : Exponential integral E1.\n" + "expi : Exponential integral Ei.\n" + "\n" + "Notes\n" + "-----\n" + "For real arguments with ``x < 0``, ``chi`` is the real part of the\n" + "hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x\n" + "+ 0j)`` differ by a factor of ``1j*pi``.\n" + "\n" + "For real arguments the function is computed by calling Cephes'\n" + "[2]_ *shichi* routine. For complex arguments the algorithm is based\n" + "on Mpmath's [3]_ *shi* and *chi* routines.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + " (See Section 5.2.)\n" + ".. [2] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + ".. [3] Fredrik Johansson and others.\n" + " \"mpmath: a Python library for arbitrary-precision floating-point\n" + " arithmetic\" (Version 0.19) http://mpmath.org/\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> from scipy.special import shichi, sici\n" + "\n" + "`shichi` accepts real or complex input:\n" + "\n" + ">>> shichi(0.5)\n" + "(0.5069967498196671, -0.05277684495649357)\n" + ">>> shichi(0.5 + 2.5j)\n" + "((0.11772029666668238+1.831091777729851j),\n" + " (0.29912435887648825+1.7395351121166562j))\n" + "\n" + "The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are\n" + "related to the sine and cosine integrals Si(z) and Ci(z) by\n" + "\n" + "* Shi(z) = -i*Si(i*z)\n" + "* Chi(z) = Ci(-i*z) + i*pi/2\n" + "\n" + ">>> z = 0.25 + 5j\n" + ">>> shi, chi = shichi(z)\n" + ">>> shi, -1j*sici(1j*z)[0] # Should be the same.\n" + "((-0.04834719325101729+1.5469354086921228j),\n" + " (-0.04834719325101729+1.5469354086921228j))\n" + ">>> chi, sici(-1j*z)[1] + 1j*np.pi/2 # Should be the same.\n" + "((-0.19568708973868087+1.556276312103824j),\n" + " (-0.19568708973868087+1.556276312103824j))\n" + "\n" + "Plot the functions evaluated on the real axis:\n" + "\n" + ">>> xp = np.geomspace(1e-8, 4.0, 250)\n" + ">>> x = np.concatenate((-xp[::-1], xp))\n" + ">>> shi, chi = shichi(x)\n" + "\n" + ">>> fig, ax = plt.subplots()\n" + ">>> ax.plot(x, shi, label='Shi(x)')\n" + ">>> ax.plot(x, chi, '--', label='Chi(x)')\n" + ">>> ax.set_xlabel('x')\n" + ">>> ax.set_title('Hyperbolic Sine and Cosine Integrals')\n" + ">>> ax.legend(shadow=True, framealpha=1, loc='lower right')\n" + ">>> ax.grid(True)\n" + ">>> plt.show()") +ufunc_shichi_loops[0] = loop_i_d_dd_As_f_ff +ufunc_shichi_loops[1] = loop_i_d_dd_As_d_dd +ufunc_shichi_loops[2] = loop_i_D_DD_As_F_FF +ufunc_shichi_loops[3] = loop_i_D_DD_As_D_DD +ufunc_shichi_types[0] = NPY_FLOAT +ufunc_shichi_types[1] = NPY_FLOAT +ufunc_shichi_types[2] = NPY_FLOAT +ufunc_shichi_types[3] = NPY_DOUBLE +ufunc_shichi_types[4] = NPY_DOUBLE +ufunc_shichi_types[5] = NPY_DOUBLE +ufunc_shichi_types[6] = NPY_CFLOAT +ufunc_shichi_types[7] = NPY_CFLOAT +ufunc_shichi_types[8] = NPY_CFLOAT +ufunc_shichi_types[9] = NPY_CDOUBLE +ufunc_shichi_types[10] = NPY_CDOUBLE +ufunc_shichi_types[11] = NPY_CDOUBLE +ufunc_shichi_ptr[2*0] = _func_xsf_shichi +ufunc_shichi_ptr[2*0+1] = ("shichi") +ufunc_shichi_ptr[2*1] = _func_xsf_shichi +ufunc_shichi_ptr[2*1+1] = ("shichi") +ufunc_shichi_ptr[2*2] = _func_xsf_cshichi +ufunc_shichi_ptr[2*2+1] = ("shichi") +ufunc_shichi_ptr[2*3] = _func_xsf_cshichi +ufunc_shichi_ptr[2*3+1] = ("shichi") +ufunc_shichi_data[0] = &ufunc_shichi_ptr[2*0] +ufunc_shichi_data[1] = &ufunc_shichi_ptr[2*1] +ufunc_shichi_data[2] = &ufunc_shichi_ptr[2*2] +ufunc_shichi_data[3] = &ufunc_shichi_ptr[2*3] +shichi = np.PyUFunc_FromFuncAndData(ufunc_shichi_loops, ufunc_shichi_data, ufunc_shichi_types, 4, 1, 2, 0, "shichi", ufunc_shichi_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_sici_loops[4] +cdef void *ufunc_sici_ptr[8] +cdef void *ufunc_sici_data[4] +cdef char ufunc_sici_types[12] +cdef char *ufunc_sici_doc = ( + "sici(x, out=None)\n" + "\n" + "Sine and cosine integrals.\n" + "\n" + "The sine integral is\n" + "\n" + ".. math::\n" + "\n" + " \\int_0^x \\frac{\\sin{t}}{t}dt\n" + "\n" + "and the cosine integral is\n" + "\n" + ".. math::\n" + "\n" + " \\gamma + \\log(x) + \\int_0^x \\frac{\\cos{t} - 1}{t}dt\n" + "\n" + "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n" + "principal branch of the logarithm [1]_.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real or complex points at which to compute the sine and cosine\n" + " integrals.\n" + "out : tuple of ndarray, optional\n" + " Optional output arrays for the function results\n" + "\n" + "Returns\n" + "-------\n" + "si : scalar or ndarray\n" + " Sine integral at ``x``\n" + "ci : scalar or ndarray\n" + " Cosine integral at ``x``\n" + "\n" + "See Also\n" + "--------\n" + "shichi : Hyperbolic sine and cosine integrals.\n" + "exp1 : Exponential integral E1.\n" + "expi : Exponential integral Ei.\n" + "\n" + "Notes\n" + "-----\n" + "For real arguments with ``x < 0``, ``ci`` is the real part of the\n" + "cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)``\n" + "differ by a factor of ``1j*pi``.\n" + "\n" + "For real arguments the function is computed by calling Cephes'\n" + "[2]_ *sici* routine. For complex arguments the algorithm is based\n" + "on Mpmath's [3]_ *si* and *ci* routines.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n" + " Handbook of Mathematical Functions with Formulas,\n" + " Graphs, and Mathematical Tables. New York: Dover, 1972.\n" + " (See Section 5.2.)\n" + ".. [2] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + ".. [3] Fredrik Johansson and others.\n" + " \"mpmath: a Python library for arbitrary-precision floating-point\n" + " arithmetic\" (Version 0.19) http://mpmath.org/\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> from scipy.special import sici, exp1\n" + "\n" + "`sici` accepts real or complex input:\n" + "\n" + ">>> sici(2.5)\n" + "(1.7785201734438267, 0.2858711963653835)\n" + ">>> sici(2.5 + 3j)\n" + "((4.505735874563953+0.06863305018999577j),\n" + "(0.0793644206906966-2.935510262937543j))\n" + "\n" + "For z in the right half plane, the sine and cosine integrals are\n" + "related to the exponential integral E1 (implemented in SciPy as\n" + "`scipy.special.exp1`) by\n" + "\n" + "* Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2\n" + "* Ci(z) = -(E1(i*z) + E1(-i*z))/2\n" + "\n" + "See [1]_ (equations 5.2.21 and 5.2.23).\n" + "\n" + "We can verify these relations:\n" + "\n" + ">>> z = 2 - 3j\n" + ">>> sici(z)\n" + "((4.54751388956229-1.3991965806460565j),\n" + "(1.408292501520851+2.9836177420296055j))\n" + "\n" + ">>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2 # Same as sine integral\n" + "(4.54751388956229-1.3991965806460565j)\n" + "\n" + ">>> -(exp1(1j*z) + exp1(-1j*z))/2 # Same as cosine integral\n" + "(1.408292501520851+2.9836177420296055j)\n" + "\n" + "Plot the functions evaluated on the real axis; the dotted horizontal\n" + "lines are at pi/2 and -pi/2:\n" + "\n" + ">>> x = np.linspace(-16, 16, 150)\n" + ">>> si, ci = sici(x)\n" + "\n" + ">>> fig, ax = plt.subplots()\n" + ">>> ax.plot(x, si, label='Si(x)')\n" + ">>> ax.plot(x, ci, '--', label='Ci(x)')\n" + ">>> ax.legend(shadow=True, framealpha=1, loc='upper left')\n" + ">>> ax.set_xlabel('x')\n" + ">>> ax.set_title('Sine and Cosine Integrals')\n" + ">>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k')\n" + ">>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k')\n" + ">>> ax.grid(True)\n" + ">>> plt.show()") +ufunc_sici_loops[0] = loop_i_d_dd_As_f_ff +ufunc_sici_loops[1] = loop_i_d_dd_As_d_dd +ufunc_sici_loops[2] = loop_i_D_DD_As_F_FF +ufunc_sici_loops[3] = loop_i_D_DD_As_D_DD +ufunc_sici_types[0] = NPY_FLOAT +ufunc_sici_types[1] = NPY_FLOAT +ufunc_sici_types[2] = NPY_FLOAT +ufunc_sici_types[3] = NPY_DOUBLE +ufunc_sici_types[4] = NPY_DOUBLE +ufunc_sici_types[5] = NPY_DOUBLE +ufunc_sici_types[6] = NPY_CFLOAT +ufunc_sici_types[7] = NPY_CFLOAT +ufunc_sici_types[8] = NPY_CFLOAT +ufunc_sici_types[9] = NPY_CDOUBLE +ufunc_sici_types[10] = NPY_CDOUBLE +ufunc_sici_types[11] = NPY_CDOUBLE +ufunc_sici_ptr[2*0] = _func_xsf_sici +ufunc_sici_ptr[2*0+1] = ("sici") +ufunc_sici_ptr[2*1] = _func_xsf_sici +ufunc_sici_ptr[2*1+1] = ("sici") +ufunc_sici_ptr[2*2] = _func_xsf_csici +ufunc_sici_ptr[2*2+1] = ("sici") +ufunc_sici_ptr[2*3] = _func_xsf_csici +ufunc_sici_ptr[2*3+1] = ("sici") +ufunc_sici_data[0] = &ufunc_sici_ptr[2*0] +ufunc_sici_data[1] = &ufunc_sici_ptr[2*1] +ufunc_sici_data[2] = &ufunc_sici_ptr[2*2] +ufunc_sici_data[3] = &ufunc_sici_ptr[2*3] +sici = np.PyUFunc_FromFuncAndData(ufunc_sici_loops, ufunc_sici_data, ufunc_sici_types, 4, 1, 2, 0, "sici", ufunc_sici_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_smirnov_loops[3] +cdef void *ufunc_smirnov_ptr[6] +cdef void *ufunc_smirnov_data[3] +cdef char ufunc_smirnov_types[9] +cdef char *ufunc_smirnov_doc = ( + "smirnov(n, d, out=None)\n" + "\n" + "Kolmogorov-Smirnov complementary cumulative distribution function\n" + "\n" + "Returns the exact Kolmogorov-Smirnov complementary cumulative\n" + "distribution function,(aka the Survival Function) of Dn+ (or Dn-)\n" + "for a one-sided test of equality between an empirical and a\n" + "theoretical distribution. It is equal to the probability that the\n" + "maximum difference between a theoretical distribution and an empirical\n" + "one based on `n` samples is greater than d.\n" + "\n" + "Parameters\n" + "----------\n" + "n : int\n" + " Number of samples\n" + "d : float array_like\n" + " Deviation between the Empirical CDF (ECDF) and the target CDF.\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d))\n" + "\n" + "See Also\n" + "--------\n" + "smirnovi : The Inverse Survival Function for the distribution\n" + "scipy.stats.ksone : Provides the functionality as a continuous distribution\n" + "kolmogorov, kolmogi : Functions for the two-sided distribution\n" + "\n" + "Notes\n" + "-----\n" + "`smirnov` is used by `stats.kstest` in the application of the\n" + "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n" + "function is exposed in `scpy.special`, but the recommended way to achieve\n" + "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n" + "`stats.ksone` distribution.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import smirnov\n" + ">>> from scipy.stats import norm\n" + "\n" + "Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a\n" + "sample of size 5.\n" + "\n" + ">>> smirnov(5, [0, 0.5, 1.0])\n" + "array([ 1. , 0.056, 0. ])\n" + "\n" + "Compare a sample of size 5 against N(0, 1), the standard normal\n" + "distribution with mean 0 and standard deviation 1.\n" + "\n" + "`x` is the sample.\n" + "\n" + ">>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])\n" + "\n" + ">>> target = norm(0, 1)\n" + ">>> cdfs = target.cdf(x)\n" + ">>> cdfs\n" + "array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])\n" + "\n" + "Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).\n" + "\n" + ">>> n = len(x)\n" + ">>> ecdfs = np.arange(n+1, dtype=float)/n\n" + ">>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],\n" + "... ecdfs[1:] - cdfs])\n" + ">>> with np.printoptions(precision=3):\n" + "... print(cols)\n" + "[[-1.392 0.2 0.082 0.082 0.118]\n" + " [-0.135 0.4 0.446 0.246 -0.046]\n" + " [ 0.114 0.6 0.545 0.145 0.055]\n" + " [ 0.19 0.8 0.575 -0.025 0.225]\n" + " [ 1.82 1. 0.966 0.166 0.034]]\n" + ">>> gaps = cols[:, -2:]\n" + ">>> Dnpm = np.max(gaps, axis=0)\n" + ">>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')\n" + "Dn-=0.246306, Dn+=0.224655\n" + ">>> probs = smirnov(n, Dnpm)\n" + ">>> print(f'For a sample of size {n} drawn from N(0, 1):',\n" + "... f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',\n" + "... f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',\n" + "... sep='\\n')\n" + "For a sample of size 5 drawn from N(0, 1):\n" + " Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711\n" + " Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245\n" + "\n" + "Plot the empirical CDF and the standard normal CDF.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> plt.step(np.concatenate(([-2.5], x, [2.5])),\n" + "... np.concatenate((ecdfs, [1])),\n" + "... where='post', label='Empirical CDF')\n" + ">>> xx = np.linspace(-2.5, 2.5, 100)\n" + ">>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')\n" + "\n" + "Add vertical lines marking Dn+ and Dn-.\n" + "\n" + ">>> iminus, iplus = np.argmax(gaps, axis=0)\n" + ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',\n" + "... alpha=0.5, lw=4)\n" + ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',\n" + "... alpha=0.5, lw=4)\n" + "\n" + ">>> plt.grid(True)\n" + ">>> plt.legend(framealpha=1, shadow=True)\n" + ">>> plt.show()") +ufunc_smirnov_loops[0] = loop_d_pd__As_pd_d +ufunc_smirnov_loops[1] = loop_d_dd__As_ff_f +ufunc_smirnov_loops[2] = loop_d_dd__As_dd_d +ufunc_smirnov_types[0] = NPY_INTP +ufunc_smirnov_types[1] = NPY_DOUBLE +ufunc_smirnov_types[2] = NPY_DOUBLE +ufunc_smirnov_types[3] = NPY_FLOAT +ufunc_smirnov_types[4] = NPY_FLOAT +ufunc_smirnov_types[5] = NPY_FLOAT +ufunc_smirnov_types[6] = NPY_DOUBLE +ufunc_smirnov_types[7] = NPY_DOUBLE +ufunc_smirnov_types[8] = NPY_DOUBLE +ufunc_smirnov_ptr[2*0] = _func_cephes_smirnov_wrap +ufunc_smirnov_ptr[2*0+1] = ("smirnov") +ufunc_smirnov_ptr[2*1] = _func_smirnov_unsafe +ufunc_smirnov_ptr[2*1+1] = ("smirnov") +ufunc_smirnov_ptr[2*2] = _func_smirnov_unsafe +ufunc_smirnov_ptr[2*2+1] = ("smirnov") +ufunc_smirnov_data[0] = &ufunc_smirnov_ptr[2*0] +ufunc_smirnov_data[1] = &ufunc_smirnov_ptr[2*1] +ufunc_smirnov_data[2] = &ufunc_smirnov_ptr[2*2] +smirnov = np.PyUFunc_FromFuncAndData(ufunc_smirnov_loops, ufunc_smirnov_data, ufunc_smirnov_types, 3, 2, 1, 0, "smirnov", ufunc_smirnov_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_smirnovi_loops[3] +cdef void *ufunc_smirnovi_ptr[6] +cdef void *ufunc_smirnovi_data[3] +cdef char ufunc_smirnovi_types[9] +cdef char *ufunc_smirnovi_doc = ( + "smirnovi(n, p, out=None)\n" + "\n" + "Inverse to `smirnov`\n" + "\n" + "Returns `d` such that ``smirnov(n, d) == p``, the critical value\n" + "corresponding to `p`.\n" + "\n" + "Parameters\n" + "----------\n" + "n : int\n" + " Number of samples\n" + "p : float array_like\n" + " Probability\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The value(s) of smirnovi(n, p), the critical values.\n" + "\n" + "See Also\n" + "--------\n" + "smirnov : The Survival Function (SF) for the distribution\n" + "scipy.stats.ksone : Provides the functionality as a continuous distribution\n" + "kolmogorov, kolmogi : Functions for the two-sided distribution\n" + "scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n\n" + "\n" + "Notes\n" + "-----\n" + "`smirnov` is used by `stats.kstest` in the application of the\n" + "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n" + "function is exposed in `scpy.special`, but the recommended way to achieve\n" + "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n" + "`stats.ksone` distribution.\n" + "\n" + "Examples\n" + "--------\n" + ">>> from scipy.special import smirnovi, smirnov\n" + "\n" + ">>> n = 24\n" + ">>> deviations = [0.1, 0.2, 0.3]\n" + "\n" + "Use `smirnov` to compute the complementary CDF of the Smirnov\n" + "distribution for the given number of samples and deviations.\n" + "\n" + ">>> p = smirnov(n, deviations)\n" + ">>> p\n" + "array([0.58105083, 0.12826832, 0.01032231])\n" + "\n" + "The inverse function ``smirnovi(n, p)`` returns ``deviations``.\n" + "\n" + ">>> smirnovi(n, p)\n" + "array([0.1, 0.2, 0.3])") +ufunc_smirnovi_loops[0] = loop_d_pd__As_pd_d +ufunc_smirnovi_loops[1] = loop_d_dd__As_ff_f +ufunc_smirnovi_loops[2] = loop_d_dd__As_dd_d +ufunc_smirnovi_types[0] = NPY_INTP +ufunc_smirnovi_types[1] = NPY_DOUBLE +ufunc_smirnovi_types[2] = NPY_DOUBLE +ufunc_smirnovi_types[3] = NPY_FLOAT +ufunc_smirnovi_types[4] = NPY_FLOAT +ufunc_smirnovi_types[5] = NPY_FLOAT +ufunc_smirnovi_types[6] = NPY_DOUBLE +ufunc_smirnovi_types[7] = NPY_DOUBLE +ufunc_smirnovi_types[8] = NPY_DOUBLE +ufunc_smirnovi_ptr[2*0] = _func_cephes_smirnovi_wrap +ufunc_smirnovi_ptr[2*0+1] = ("smirnovi") +ufunc_smirnovi_ptr[2*1] = _func_smirnovi_unsafe +ufunc_smirnovi_ptr[2*1+1] = ("smirnovi") +ufunc_smirnovi_ptr[2*2] = _func_smirnovi_unsafe +ufunc_smirnovi_ptr[2*2+1] = ("smirnovi") +ufunc_smirnovi_data[0] = &ufunc_smirnovi_ptr[2*0] +ufunc_smirnovi_data[1] = &ufunc_smirnovi_ptr[2*1] +ufunc_smirnovi_data[2] = &ufunc_smirnovi_ptr[2*2] +smirnovi = np.PyUFunc_FromFuncAndData(ufunc_smirnovi_loops, ufunc_smirnovi_data, ufunc_smirnovi_types, 3, 2, 1, 0, "smirnovi", ufunc_smirnovi_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_spence_loops[4] +cdef void *ufunc_spence_ptr[8] +cdef void *ufunc_spence_data[4] +cdef char ufunc_spence_types[8] +cdef char *ufunc_spence_doc = ( + "spence(z, out=None)\n" + "\n" + "Spence's function, also known as the dilogarithm.\n" + "\n" + "It is defined to be\n" + "\n" + ".. math::\n" + " \\int_1^z \\frac{\\log(t)}{1 - t}dt\n" + "\n" + "for complex :math:`z`, where the contour of integration is taken\n" + "to avoid the branch cut of the logarithm. Spence's function is\n" + "analytic everywhere except the negative real axis where it has a\n" + "branch cut.\n" + "\n" + "Parameters\n" + "----------\n" + "z : array_like\n" + " Points at which to evaluate Spence's function\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "s : scalar or ndarray\n" + " Computed values of Spence's function\n" + "\n" + "Notes\n" + "-----\n" + "There is a different convention which defines Spence's function by\n" + "the integral\n" + "\n" + ".. math::\n" + " -\\int_0^z \\frac{\\log(1 - t)}{t}dt;\n" + "\n" + "this is our ``spence(1 - z)``.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import spence\n" + ">>> import matplotlib.pyplot as plt\n" + "\n" + "The function is defined for complex inputs:\n" + "\n" + ">>> spence([1-1j, 1.5+2j, 3j, -10-5j])\n" + "array([-0.20561676+0.91596559j, -0.86766909-1.39560134j,\n" + " -0.59422064-2.49129918j, -1.14044398+6.80075924j])\n" + "\n" + "For complex inputs on the branch cut, which is the negative real axis,\n" + "the function returns the limit for ``z`` with positive imaginary part.\n" + "For example, in the following, note the sign change of the imaginary\n" + "part of the output for ``z = -2`` and ``z = -2 - 1e-8j``:\n" + "\n" + ">>> spence([-2 + 1e-8j, -2, -2 - 1e-8j])\n" + "array([2.32018041-3.45139229j, 2.32018042-3.4513923j ,\n" + " 2.32018041+3.45139229j])\n" + "\n" + "The function returns ``nan`` for real inputs on the branch cut:\n" + "\n" + ">>> spence(-1.5)\n" + "nan\n" + "\n" + "Verify some particular values: ``spence(0) = pi**2/6``,\n" + "``spence(1) = 0`` and ``spence(2) = -pi**2/12``.\n" + "\n" + ">>> spence([0, 1, 2])\n" + "array([ 1.64493407, 0. , -0.82246703])\n" + ">>> np.pi**2/6, -np.pi**2/12\n" + "(1.6449340668482264, -0.8224670334241132)\n" + "\n" + "Verify the identity::\n" + "\n" + " spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z)\n" + "\n" + ">>> z = 3 + 4j\n" + ">>> spence(z) + spence(1 - z)\n" + "(-2.6523186143876067+1.8853470951513935j)\n" + ">>> np.pi**2/6 - np.log(z)*np.log(1 - z)\n" + "(-2.652318614387606+1.885347095151394j)\n" + "\n" + "Plot the function for positive real input.\n" + "\n" + ">>> fig, ax = plt.subplots()\n" + ">>> x = np.linspace(0, 6, 400)\n" + ">>> ax.plot(x, spence(x))\n" + ">>> ax.grid()\n" + ">>> ax.set_xlabel('x')\n" + ">>> ax.set_title('spence(x)')\n" + ">>> plt.show()") +ufunc_spence_loops[0] = loop_d_d__As_f_f +ufunc_spence_loops[1] = loop_d_d__As_d_d +ufunc_spence_loops[2] = loop_D_D__As_F_F +ufunc_spence_loops[3] = loop_D_D__As_D_D +ufunc_spence_types[0] = NPY_FLOAT +ufunc_spence_types[1] = NPY_FLOAT +ufunc_spence_types[2] = NPY_DOUBLE +ufunc_spence_types[3] = NPY_DOUBLE +ufunc_spence_types[4] = NPY_CFLOAT +ufunc_spence_types[5] = NPY_CFLOAT +ufunc_spence_types[6] = NPY_CDOUBLE +ufunc_spence_types[7] = NPY_CDOUBLE +ufunc_spence_ptr[2*0] = _func_cephes_spence +ufunc_spence_ptr[2*0+1] = ("spence") +ufunc_spence_ptr[2*1] = _func_cephes_spence +ufunc_spence_ptr[2*1+1] = ("spence") +ufunc_spence_ptr[2*2] = _func_cspence +ufunc_spence_ptr[2*2+1] = ("spence") +ufunc_spence_ptr[2*3] = _func_cspence +ufunc_spence_ptr[2*3+1] = ("spence") +ufunc_spence_data[0] = &ufunc_spence_ptr[2*0] +ufunc_spence_data[1] = &ufunc_spence_ptr[2*1] +ufunc_spence_data[2] = &ufunc_spence_ptr[2*2] +ufunc_spence_data[3] = &ufunc_spence_ptr[2*3] +spence = np.PyUFunc_FromFuncAndData(ufunc_spence_loops, ufunc_spence_data, ufunc_spence_types, 4, 1, 1, 0, "spence", ufunc_spence_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_stdtr_loops[2] +cdef void *ufunc_stdtr_ptr[4] +cdef void *ufunc_stdtr_data[2] +cdef char ufunc_stdtr_types[6] +cdef char *ufunc_stdtr_doc = ( + "stdtr(df, t, out=None)\n" + "\n" + "Student t distribution cumulative distribution function\n" + "\n" + "Returns the integral:\n" + "\n" + ".. math::\n" + " \\frac{\\Gamma((df+1)/2)}{\\sqrt{\\pi df} \\Gamma(df/2)}\n" + " \\int_{-\\infty}^t (1+x^2/df)^{-(df+1)/2}\\, dx\n" + "\n" + "Parameters\n" + "----------\n" + "df : array_like\n" + " Degrees of freedom\n" + "t : array_like\n" + " Upper bound of the integral\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Value of the Student t CDF at t\n" + "\n" + "See Also\n" + "--------\n" + "stdtridf : inverse of stdtr with respect to `df`\n" + "stdtrit : inverse of stdtr with respect to `t`\n" + "scipy.stats.t : student t distribution\n" + "\n" + "Notes\n" + "-----\n" + "The student t distribution is also available as `scipy.stats.t`.\n" + "Calling `stdtr` directly can improve performance compared to the\n" + "``cdf`` method of `scipy.stats.t` (see last example below).\n" + "\n" + "Examples\n" + "--------\n" + "Calculate the function for ``df=3`` at ``t=1``.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import stdtr\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> stdtr(3, 1)\n" + "0.8044988905221148\n" + "\n" + "Plot the function for three different degrees of freedom.\n" + "\n" + ">>> x = np.linspace(-10, 10, 1000)\n" + ">>> fig, ax = plt.subplots()\n" + ">>> parameters = [(1, \"solid\"), (3, \"dashed\"), (10, \"dotted\")]\n" + ">>> for (df, linestyle) in parameters:\n" + "... ax.plot(x, stdtr(df, x), ls=linestyle, label=f\"$df={df}$\")\n" + ">>> ax.legend()\n" + ">>> ax.set_title(\"Student t distribution cumulative distribution function\")\n" + ">>> plt.show()\n" + "\n" + "The function can be computed for several degrees of freedom at the same\n" + "time by providing a NumPy array or list for `df`:\n" + "\n" + ">>> stdtr([1, 2, 3], 1)\n" + "array([0.75 , 0.78867513, 0.80449889])\n" + "\n" + "It is possible to calculate the function at several points for several\n" + "different degrees of freedom simultaneously by providing arrays for `df`\n" + "and `t` with shapes compatible for broadcasting. Compute `stdtr` at\n" + "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n" + "\n" + ">>> dfs = np.array([[1], [2], [3]])\n" + ">>> t = np.array([2, 4, 6, 8])\n" + ">>> dfs.shape, t.shape\n" + "((3, 1), (4,))\n" + "\n" + ">>> stdtr(dfs, t)\n" + "array([[0.85241638, 0.92202087, 0.94743154, 0.96041658],\n" + " [0.90824829, 0.97140452, 0.98666426, 0.99236596],\n" + " [0.93033702, 0.98599577, 0.99536364, 0.99796171]])\n" + "\n" + "The t distribution is also available as `scipy.stats.t`. Calling `stdtr`\n" + "directly can be much faster than calling the ``cdf`` method of\n" + "`scipy.stats.t`. To get the same results, one must use the following\n" + "parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``.\n" + "\n" + ">>> from scipy.stats import t\n" + ">>> df, x = 3, 1\n" + ">>> stdtr_result = stdtr(df, x) # this can be faster than below\n" + ">>> stats_result = t(df).cdf(x)\n" + ">>> stats_result == stdtr_result # test that results are equal\n" + "True") +ufunc_stdtr_loops[0] = loop_d_dd__As_ff_f +ufunc_stdtr_loops[1] = loop_d_dd__As_dd_d +ufunc_stdtr_types[0] = NPY_FLOAT +ufunc_stdtr_types[1] = NPY_FLOAT +ufunc_stdtr_types[2] = NPY_FLOAT +ufunc_stdtr_types[3] = NPY_DOUBLE +ufunc_stdtr_types[4] = NPY_DOUBLE +ufunc_stdtr_types[5] = NPY_DOUBLE +ufunc_stdtr_ptr[2*0] = _func_stdtr +ufunc_stdtr_ptr[2*0+1] = ("stdtr") +ufunc_stdtr_ptr[2*1] = _func_stdtr +ufunc_stdtr_ptr[2*1+1] = ("stdtr") +ufunc_stdtr_data[0] = &ufunc_stdtr_ptr[2*0] +ufunc_stdtr_data[1] = &ufunc_stdtr_ptr[2*1] +stdtr = np.PyUFunc_FromFuncAndData(ufunc_stdtr_loops, ufunc_stdtr_data, ufunc_stdtr_types, 2, 2, 1, 0, "stdtr", ufunc_stdtr_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_stdtridf_loops[2] +cdef void *ufunc_stdtridf_ptr[4] +cdef void *ufunc_stdtridf_data[2] +cdef char ufunc_stdtridf_types[6] +cdef char *ufunc_stdtridf_doc = ( + "stdtridf(p, t, out=None)\n" + "\n" + "Inverse of `stdtr` vs df\n" + "\n" + "Returns the argument df such that stdtr(df, t) is equal to `p`.\n" + "\n" + "Parameters\n" + "----------\n" + "p : array_like\n" + " Probability\n" + "t : array_like\n" + " Upper bound of the integral\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "df : scalar or ndarray\n" + " Value of `df` such that ``stdtr(df, t) == p``\n" + "\n" + "See Also\n" + "--------\n" + "stdtr : Student t CDF\n" + "stdtrit : inverse of stdtr with respect to `t`\n" + "scipy.stats.t : Student t distribution\n" + "\n" + "Examples\n" + "--------\n" + "Compute the student t cumulative distribution function for one\n" + "parameter set.\n" + "\n" + ">>> from scipy.special import stdtr, stdtridf\n" + ">>> df, x = 5, 2\n" + ">>> cdf_value = stdtr(df, x)\n" + ">>> cdf_value\n" + "0.9490302605850709\n" + "\n" + "Verify that `stdtridf` recovers the original value for `df` given\n" + "the CDF value and `x`.\n" + "\n" + ">>> stdtridf(cdf_value, x)\n" + "5.0") +ufunc_stdtridf_loops[0] = loop_d_dd__As_ff_f +ufunc_stdtridf_loops[1] = loop_d_dd__As_dd_d +ufunc_stdtridf_types[0] = NPY_FLOAT +ufunc_stdtridf_types[1] = NPY_FLOAT +ufunc_stdtridf_types[2] = NPY_FLOAT +ufunc_stdtridf_types[3] = NPY_DOUBLE +ufunc_stdtridf_types[4] = NPY_DOUBLE +ufunc_stdtridf_types[5] = NPY_DOUBLE +ufunc_stdtridf_ptr[2*0] = _func_stdtridf +ufunc_stdtridf_ptr[2*0+1] = ("stdtridf") +ufunc_stdtridf_ptr[2*1] = _func_stdtridf +ufunc_stdtridf_ptr[2*1+1] = ("stdtridf") +ufunc_stdtridf_data[0] = &ufunc_stdtridf_ptr[2*0] +ufunc_stdtridf_data[1] = &ufunc_stdtridf_ptr[2*1] +stdtridf = np.PyUFunc_FromFuncAndData(ufunc_stdtridf_loops, ufunc_stdtridf_data, ufunc_stdtridf_types, 2, 2, 1, 0, "stdtridf", ufunc_stdtridf_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_stdtrit_loops[2] +cdef void *ufunc_stdtrit_ptr[4] +cdef void *ufunc_stdtrit_data[2] +cdef char ufunc_stdtrit_types[6] +cdef char *ufunc_stdtrit_doc = ( + "stdtrit(df, p, out=None)\n" + "\n" + "The `p`-th quantile of the student t distribution.\n" + "\n" + "This function is the inverse of the student t distribution cumulative\n" + "distribution function (CDF), returning `t` such that `stdtr(df, t) = p`.\n" + "\n" + "Returns the argument `t` such that stdtr(df, t) is equal to `p`.\n" + "\n" + "Parameters\n" + "----------\n" + "df : array_like\n" + " Degrees of freedom\n" + "p : array_like\n" + " Probability\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "t : scalar or ndarray\n" + " Value of `t` such that ``stdtr(df, t) == p``\n" + "\n" + "See Also\n" + "--------\n" + "stdtr : Student t CDF\n" + "stdtridf : inverse of stdtr with respect to `df`\n" + "scipy.stats.t : Student t distribution\n" + "\n" + "Notes\n" + "-----\n" + "The student t distribution is also available as `scipy.stats.t`. Calling\n" + "`stdtrit` directly can improve performance compared to the ``ppf``\n" + "method of `scipy.stats.t` (see last example below).\n" + "\n" + "Examples\n" + "--------\n" + "`stdtrit` represents the inverse of the student t distribution CDF which\n" + "is available as `stdtr`. Here, we calculate the CDF for ``df`` at\n" + "``x=1``. `stdtrit` then returns ``1`` up to floating point errors\n" + "given the same value for `df` and the computed CDF value.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import stdtr, stdtrit\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> df = 3\n" + ">>> x = 1\n" + ">>> cdf_value = stdtr(df, x)\n" + ">>> stdtrit(df, cdf_value)\n" + "0.9999999994418539\n" + "\n" + "Plot the function for three different degrees of freedom.\n" + "\n" + ">>> x = np.linspace(0, 1, 1000)\n" + ">>> parameters = [(1, \"solid\"), (2, \"dashed\"), (5, \"dotted\")]\n" + ">>> fig, ax = plt.subplots()\n" + ">>> for (df, linestyle) in parameters:\n" + "... ax.plot(x, stdtrit(df, x), ls=linestyle, label=f\"$df={df}$\")\n" + ">>> ax.legend()\n" + ">>> ax.set_ylim(-10, 10)\n" + ">>> ax.set_title(\"Student t distribution quantile function\")\n" + ">>> plt.show()\n" + "\n" + "The function can be computed for several degrees of freedom at the same\n" + "time by providing a NumPy array or list for `df`:\n" + "\n" + ">>> stdtrit([1, 2, 3], 0.7)\n" + "array([0.72654253, 0.6172134 , 0.58438973])\n" + "\n" + "It is possible to calculate the function at several points for several\n" + "different degrees of freedom simultaneously by providing arrays for `df`\n" + "and `p` with shapes compatible for broadcasting. Compute `stdtrit` at\n" + "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n" + "\n" + ">>> dfs = np.array([[1], [2], [3]])\n" + ">>> p = np.array([0.2, 0.4, 0.7, 0.8])\n" + ">>> dfs.shape, p.shape\n" + "((3, 1), (4,))\n" + "\n" + ">>> stdtrit(dfs, p)\n" + "array([[-1.37638192, -0.3249197 , 0.72654253, 1.37638192],\n" + " [-1.06066017, -0.28867513, 0.6172134 , 1.06066017],\n" + " [-0.97847231, -0.27667066, 0.58438973, 0.97847231]])\n" + "\n" + "The t distribution is also available as `scipy.stats.t`. Calling `stdtrit`\n" + "directly can be much faster than calling the ``ppf`` method of\n" + "`scipy.stats.t`. To get the same results, one must use the following\n" + "parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``.\n" + "\n" + ">>> from scipy.stats import t\n" + ">>> df, x = 3, 0.5\n" + ">>> stdtrit_result = stdtrit(df, x) # this can be faster than below\n" + ">>> stats_result = t(df).ppf(x)\n" + ">>> stats_result == stdtrit_result # test that results are equal\n" + "True") +ufunc_stdtrit_loops[0] = loop_d_dd__As_ff_f +ufunc_stdtrit_loops[1] = loop_d_dd__As_dd_d +ufunc_stdtrit_types[0] = NPY_FLOAT +ufunc_stdtrit_types[1] = NPY_FLOAT +ufunc_stdtrit_types[2] = NPY_FLOAT +ufunc_stdtrit_types[3] = NPY_DOUBLE +ufunc_stdtrit_types[4] = NPY_DOUBLE +ufunc_stdtrit_types[5] = NPY_DOUBLE +ufunc_stdtrit_ptr[2*0] = _func_stdtrit +ufunc_stdtrit_ptr[2*0+1] = ("stdtrit") +ufunc_stdtrit_ptr[2*1] = _func_stdtrit +ufunc_stdtrit_ptr[2*1+1] = ("stdtrit") +ufunc_stdtrit_data[0] = &ufunc_stdtrit_ptr[2*0] +ufunc_stdtrit_data[1] = &ufunc_stdtrit_ptr[2*1] +stdtrit = np.PyUFunc_FromFuncAndData(ufunc_stdtrit_loops, ufunc_stdtrit_data, ufunc_stdtrit_types, 2, 2, 1, 0, "stdtrit", ufunc_stdtrit_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_tklmbda_loops[2] +cdef void *ufunc_tklmbda_ptr[4] +cdef void *ufunc_tklmbda_data[2] +cdef char ufunc_tklmbda_types[6] +cdef char *ufunc_tklmbda_doc = ( + "tklmbda(x, lmbda, out=None)\n" + "\n" + "Cumulative distribution function of the Tukey lambda distribution.\n" + "\n" + "Parameters\n" + "----------\n" + "x, lmbda : array_like\n" + " Parameters\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "cdf : scalar or ndarray\n" + " Value of the Tukey lambda CDF\n" + "\n" + "See Also\n" + "--------\n" + "scipy.stats.tukeylambda : Tukey lambda distribution\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> from scipy.special import tklmbda, expit\n" + "\n" + "Compute the cumulative distribution function (CDF) of the Tukey lambda\n" + "distribution at several ``x`` values for `lmbda` = -1.5.\n" + "\n" + ">>> x = np.linspace(-2, 2, 9)\n" + ">>> x\n" + "array([-2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5, 2. ])\n" + ">>> tklmbda(x, -1.5)\n" + "array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5 ,\n" + " 0.54370263, 0.58471195, 0.6213446 , 0.65311266])\n" + "\n" + "When `lmbda` is 0, the function is the logistic sigmoid function,\n" + "which is implemented in `scipy.special` as `expit`.\n" + "\n" + ">>> tklmbda(x, 0)\n" + "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5 ,\n" + " 0.62245933, 0.73105858, 0.81757448, 0.88079708])\n" + ">>> expit(x)\n" + "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5 ,\n" + " 0.62245933, 0.73105858, 0.81757448, 0.88079708])\n" + "\n" + "When `lmbda` is 1, the Tukey lambda distribution is uniform on the\n" + "interval [-1, 1], so the CDF increases linearly.\n" + "\n" + ">>> t = np.linspace(-1, 1, 9)\n" + ">>> tklmbda(t, 1)\n" + "array([0. , 0.125, 0.25 , 0.375, 0.5 , 0.625, 0.75 , 0.875, 1. ])\n" + "\n" + "In the following, we generate plots for several values of `lmbda`.\n" + "\n" + "The first figure shows graphs for `lmbda` <= 0.\n" + "\n" + ">>> styles = ['-', '-.', '--', ':']\n" + ">>> fig, ax = plt.subplots()\n" + ">>> x = np.linspace(-12, 12, 500)\n" + ">>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]):\n" + "... y = tklmbda(x, lmbda)\n" + "... ax.plot(x, y, styles[k], label=rf'$\\lambda$ = {lmbda:-4.1f}')\n" + "\n" + ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n" + ">>> ax.set_label('x')\n" + ">>> ax.legend(framealpha=1, shadow=True)\n" + ">>> ax.grid(True)\n" + "\n" + "The second figure shows graphs for `lmbda` > 0. The dots in the\n" + "graphs show the bounds of the support of the distribution.\n" + "\n" + ">>> fig, ax = plt.subplots()\n" + ">>> x = np.linspace(-4.2, 4.2, 500)\n" + ">>> lmbdas = [0.25, 0.5, 1.0, 1.5]\n" + ">>> for k, lmbda in enumerate(lmbdas):\n" + "... y = tklmbda(x, lmbda)\n" + "... ax.plot(x, y, styles[k], label=fr'$\\lambda$ = {lmbda}')\n" + "\n" + ">>> ax.set_prop_cycle(None)\n" + ">>> for lmbda in lmbdas:\n" + "... ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8)\n" + "\n" + ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n" + ">>> ax.set_xlabel('x')\n" + ">>> ax.legend(framealpha=1, shadow=True)\n" + ">>> ax.grid(True)\n" + "\n" + ">>> plt.tight_layout()\n" + ">>> plt.show()\n" + "\n" + "The CDF of the Tukey lambda distribution is also implemented as the\n" + "``cdf`` method of `scipy.stats.tukeylambda`. In the following,\n" + "``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the\n" + "same values:\n" + "\n" + ">>> from scipy.stats import tukeylambda\n" + ">>> x = np.linspace(-2, 2, 9)\n" + "\n" + ">>> tukeylambda.cdf(x, -0.5)\n" + "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5 ,\n" + " 0.58671839, 0.66458323, 0.72906142, 0.78004843])\n" + "\n" + ">>> tklmbda(x, -0.5)\n" + "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5 ,\n" + " 0.58671839, 0.66458323, 0.72906142, 0.78004843])\n" + "\n" + "The implementation in ``tukeylambda`` also provides location and scale\n" + "parameters, and other methods such as ``pdf()`` (the probability\n" + "density function) and ``ppf()`` (the inverse of the CDF), so for\n" + "working with the Tukey lambda distribution, ``tukeylambda`` is more\n" + "generally useful. The primary advantage of ``tklmbda`` is that it is\n" + "significantly faster than ``tukeylambda.cdf``.") +ufunc_tklmbda_loops[0] = loop_d_dd__As_ff_f +ufunc_tklmbda_loops[1] = loop_d_dd__As_dd_d +ufunc_tklmbda_types[0] = NPY_FLOAT +ufunc_tklmbda_types[1] = NPY_FLOAT +ufunc_tklmbda_types[2] = NPY_FLOAT +ufunc_tklmbda_types[3] = NPY_DOUBLE +ufunc_tklmbda_types[4] = NPY_DOUBLE +ufunc_tklmbda_types[5] = NPY_DOUBLE +ufunc_tklmbda_ptr[2*0] = _func_xsf_tukeylambdacdf +ufunc_tklmbda_ptr[2*0+1] = ("tklmbda") +ufunc_tklmbda_ptr[2*1] = _func_xsf_tukeylambdacdf +ufunc_tklmbda_ptr[2*1+1] = ("tklmbda") +ufunc_tklmbda_data[0] = &ufunc_tklmbda_ptr[2*0] +ufunc_tklmbda_data[1] = &ufunc_tklmbda_ptr[2*1] +tklmbda = np.PyUFunc_FromFuncAndData(ufunc_tklmbda_loops, ufunc_tklmbda_data, ufunc_tklmbda_types, 2, 2, 1, 0, "tklmbda", ufunc_tklmbda_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_voigt_profile_loops[2] +cdef void *ufunc_voigt_profile_ptr[4] +cdef void *ufunc_voigt_profile_data[2] +cdef char ufunc_voigt_profile_types[8] +cdef char *ufunc_voigt_profile_doc = ( + "voigt_profile(x, sigma, gamma, out=None)\n" + "\n" + "Voigt profile.\n" + "\n" + "The Voigt profile is a convolution of a 1-D Normal distribution with\n" + "standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at\n" + "half-maximum ``gamma``.\n" + "\n" + "If ``sigma = 0``, PDF of Cauchy distribution is returned.\n" + "Conversely, if ``gamma = 0``, PDF of Normal distribution is returned.\n" + "If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``,\n" + "and ``0`` for all other ``x``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Real argument\n" + "sigma : array_like\n" + " The standard deviation of the Normal distribution part\n" + "gamma : array_like\n" + " The half-width at half-maximum of the Cauchy distribution part\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " The Voigt profile at the given arguments\n" + "\n" + "See Also\n" + "--------\n" + "wofz : Faddeeva function\n" + "\n" + "Notes\n" + "-----\n" + "It can be expressed in terms of Faddeeva function\n" + "\n" + ".. math:: V(x; \\sigma, \\gamma) = \\frac{Re[w(z)]}{\\sigma\\sqrt{2\\pi}},\n" + ".. math:: z = \\frac{x + i\\gamma}{\\sqrt{2}\\sigma}\n" + "\n" + "where :math:`w(z)` is the Faddeeva function.\n" + "\n" + "References\n" + "----------\n" + ".. [1] https://en.wikipedia.org/wiki/Voigt_profile\n" + "\n" + "Examples\n" + "--------\n" + "Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``.\n" + "\n" + ">>> from scipy.special import voigt_profile\n" + ">>> import numpy as np\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> voigt_profile(2, 1., 1.)\n" + "0.09071519942627544\n" + "\n" + "Calculate the function at several points by providing a NumPy array\n" + "for `x`.\n" + "\n" + ">>> values = np.array([-2., 0., 5])\n" + ">>> voigt_profile(values, 1., 1.)\n" + "array([0.0907152 , 0.20870928, 0.01388492])\n" + "\n" + "Plot the function for different parameter sets.\n" + "\n" + ">>> fig, ax = plt.subplots(figsize=(8, 8))\n" + ">>> x = np.linspace(-10, 10, 500)\n" + ">>> parameters_list = [(1.5, 0., \"solid\"), (1.3, 0.5, \"dashed\"),\n" + "... (0., 1.8, \"dotted\"), (1., 1., \"dashdot\")]\n" + ">>> for params in parameters_list:\n" + "... sigma, gamma, linestyle = params\n" + "... voigt = voigt_profile(x, sigma, gamma)\n" + "... ax.plot(x, voigt, label=rf\"$\\sigma={sigma},\\, \\gamma={gamma}$\",\n" + "... ls=linestyle)\n" + ">>> ax.legend()\n" + ">>> plt.show()\n" + "\n" + "Verify visually that the Voigt profile indeed arises as the convolution\n" + "of a normal and a Cauchy distribution.\n" + "\n" + ">>> from scipy.signal import convolve\n" + ">>> x, dx = np.linspace(-10, 10, 500, retstep=True)\n" + ">>> def gaussian(x, sigma):\n" + "... return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi))\n" + ">>> def cauchy(x, gamma):\n" + "... return gamma/(np.pi * (np.square(x)+gamma**2))\n" + ">>> sigma = 2\n" + ">>> gamma = 1\n" + ">>> gauss_profile = gaussian(x, sigma)\n" + ">>> cauchy_profile = cauchy(x, gamma)\n" + ">>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode=\"same\")\n" + ">>> voigt = voigt_profile(x, sigma, gamma)\n" + ">>> fig, ax = plt.subplots(figsize=(8, 8))\n" + ">>> ax.plot(x, gauss_profile, label=\"Gauss: $G$\", c='b')\n" + ">>> ax.plot(x, cauchy_profile, label=\"Cauchy: $C$\", c='y', ls=\"dashed\")\n" + ">>> xx = 0.5*(x[1:] + x[:-1]) # midpoints\n" + ">>> ax.plot(xx, convolved[1:], label=\"Convolution: $G * C$\", ls='dashdot',\n" + "... c='k')\n" + ">>> ax.plot(x, voigt, label=\"Voigt\", ls='dotted', c='r')\n" + ">>> ax.legend()\n" + ">>> plt.show()") +ufunc_voigt_profile_loops[0] = loop_d_ddd__As_fff_f +ufunc_voigt_profile_loops[1] = loop_d_ddd__As_ddd_d +ufunc_voigt_profile_types[0] = NPY_FLOAT +ufunc_voigt_profile_types[1] = NPY_FLOAT +ufunc_voigt_profile_types[2] = NPY_FLOAT +ufunc_voigt_profile_types[3] = NPY_FLOAT +ufunc_voigt_profile_types[4] = NPY_DOUBLE +ufunc_voigt_profile_types[5] = NPY_DOUBLE +ufunc_voigt_profile_types[6] = NPY_DOUBLE +ufunc_voigt_profile_types[7] = NPY_DOUBLE +ufunc_voigt_profile_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile +ufunc_voigt_profile_ptr[2*0+1] = ("voigt_profile") +ufunc_voigt_profile_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile +ufunc_voigt_profile_ptr[2*1+1] = ("voigt_profile") +ufunc_voigt_profile_data[0] = &ufunc_voigt_profile_ptr[2*0] +ufunc_voigt_profile_data[1] = &ufunc_voigt_profile_ptr[2*1] +voigt_profile = np.PyUFunc_FromFuncAndData(ufunc_voigt_profile_loops, ufunc_voigt_profile_data, ufunc_voigt_profile_types, 2, 3, 1, 0, "voigt_profile", ufunc_voigt_profile_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_wofz_loops[2] +cdef void *ufunc_wofz_ptr[4] +cdef void *ufunc_wofz_data[2] +cdef char ufunc_wofz_types[4] +cdef char *ufunc_wofz_doc = ( + "wofz(z, out=None)\n" + "\n" + "Faddeeva function\n" + "\n" + "Returns the value of the Faddeeva function for complex argument::\n" + "\n" + " exp(-z**2) * erfc(-i*z)\n" + "\n" + "Parameters\n" + "----------\n" + "z : array_like\n" + " complex argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "scalar or ndarray\n" + " Value of the Faddeeva function\n" + "\n" + "See Also\n" + "--------\n" + "dawsn, erf, erfc, erfcx, erfi\n" + "\n" + "References\n" + "----------\n" + ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n" + " http://ab-initio.mit.edu/Faddeeva\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy import special\n" + ">>> import matplotlib.pyplot as plt\n" + "\n" + ">>> x = np.linspace(-3, 3)\n" + ">>> z = special.wofz(x)\n" + "\n" + ">>> plt.plot(x, z.real, label='wofz(x).real')\n" + ">>> plt.plot(x, z.imag, label='wofz(x).imag')\n" + ">>> plt.xlabel('$x$')\n" + ">>> plt.legend(framealpha=1, shadow=True)\n" + ">>> plt.grid(alpha=0.25)\n" + ">>> plt.show()") +ufunc_wofz_loops[0] = loop_D_D__As_F_F +ufunc_wofz_loops[1] = loop_D_D__As_D_D +ufunc_wofz_types[0] = NPY_CFLOAT +ufunc_wofz_types[1] = NPY_CFLOAT +ufunc_wofz_types[2] = NPY_CDOUBLE +ufunc_wofz_types[3] = NPY_CDOUBLE +ufunc_wofz_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_w +ufunc_wofz_ptr[2*0+1] = ("wofz") +ufunc_wofz_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_w +ufunc_wofz_ptr[2*1+1] = ("wofz") +ufunc_wofz_data[0] = &ufunc_wofz_ptr[2*0] +ufunc_wofz_data[1] = &ufunc_wofz_ptr[2*1] +wofz = np.PyUFunc_FromFuncAndData(ufunc_wofz_loops, ufunc_wofz_data, ufunc_wofz_types, 2, 1, 1, 0, "wofz", ufunc_wofz_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_wrightomega_loops[4] +cdef void *ufunc_wrightomega_ptr[8] +cdef void *ufunc_wrightomega_data[4] +cdef char ufunc_wrightomega_types[8] +cdef char *ufunc_wrightomega_doc = ( + "wrightomega(z, out=None)\n" + "\n" + "Wright Omega function.\n" + "\n" + "Defined as the solution to\n" + "\n" + ".. math::\n" + "\n" + " \\omega + \\log(\\omega) = z\n" + "\n" + "where :math:`\\log` is the principal branch of the complex logarithm.\n" + "\n" + "Parameters\n" + "----------\n" + "z : array_like\n" + " Points at which to evaluate the Wright Omega function\n" + "out : ndarray, optional\n" + " Optional output array for the function values\n" + "\n" + "Returns\n" + "-------\n" + "omega : scalar or ndarray\n" + " Values of the Wright Omega function\n" + "\n" + "See Also\n" + "--------\n" + "lambertw : The Lambert W function\n" + "\n" + "Notes\n" + "-----\n" + ".. versionadded:: 0.19.0\n" + "\n" + "The function can also be defined as\n" + "\n" + ".. math::\n" + "\n" + " \\omega(z) = W_{K(z)}(e^z)\n" + "\n" + "where :math:`K(z) = \\lceil (\\Im(z) - \\pi)/(2\\pi) \\rceil` is the\n" + "unwinding number and :math:`W` is the Lambert W function.\n" + "\n" + "The implementation here is taken from [1]_.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Lawrence, Corless, and Jeffrey, \"Algorithm 917: Complex\n" + " Double-Precision Evaluation of the Wright :math:`\\omega`\n" + " Function.\" ACM Transactions on Mathematical Software,\n" + " 2012. :doi:`10.1145/2168773.2168779`.\n" + "\n" + "Examples\n" + "--------\n" + ">>> import numpy as np\n" + ">>> from scipy.special import wrightomega, lambertw\n" + "\n" + ">>> wrightomega([-2, -1, 0, 1, 2])\n" + "array([0.12002824, 0.27846454, 0.56714329, 1. , 1.5571456 ])\n" + "\n" + "Complex input:\n" + "\n" + ">>> wrightomega(3 + 5j)\n" + "(1.5804428632097158+3.8213626783287937j)\n" + "\n" + "Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``:\n" + "\n" + ">>> w = -5 + 4j\n" + ">>> wrightomega(w + np.log(w))\n" + "(-5+4j)\n" + "\n" + "Verify the connection to ``lambertw``:\n" + "\n" + ">>> z = 0.5 + 3j\n" + ">>> wrightomega(z)\n" + "(0.0966015889280649+1.4937828458191993j)\n" + ">>> lambertw(np.exp(z))\n" + "(0.09660158892806493+1.4937828458191993j)\n" + "\n" + ">>> z = 0.5 + 4j\n" + ">>> wrightomega(z)\n" + "(-0.3362123489037213+2.282986001579032j)\n" + ">>> lambertw(np.exp(z), k=1)\n" + "(-0.33621234890372115+2.282986001579032j)") +ufunc_wrightomega_loops[0] = loop_d_d__As_f_f +ufunc_wrightomega_loops[1] = loop_d_d__As_d_d +ufunc_wrightomega_loops[2] = loop_D_D__As_F_F +ufunc_wrightomega_loops[3] = loop_D_D__As_D_D +ufunc_wrightomega_types[0] = NPY_FLOAT +ufunc_wrightomega_types[1] = NPY_FLOAT +ufunc_wrightomega_types[2] = NPY_DOUBLE +ufunc_wrightomega_types[3] = NPY_DOUBLE +ufunc_wrightomega_types[4] = NPY_CFLOAT +ufunc_wrightomega_types[5] = NPY_CFLOAT +ufunc_wrightomega_types[6] = NPY_CDOUBLE +ufunc_wrightomega_types[7] = NPY_CDOUBLE +ufunc_wrightomega_ptr[2*0] = scipy.special._ufuncs_cxx._export_wrightomega_real +ufunc_wrightomega_ptr[2*0+1] = ("wrightomega") +ufunc_wrightomega_ptr[2*1] = scipy.special._ufuncs_cxx._export_wrightomega_real +ufunc_wrightomega_ptr[2*1+1] = ("wrightomega") +ufunc_wrightomega_ptr[2*2] = scipy.special._ufuncs_cxx._export_wrightomega +ufunc_wrightomega_ptr[2*2+1] = ("wrightomega") +ufunc_wrightomega_ptr[2*3] = scipy.special._ufuncs_cxx._export_wrightomega +ufunc_wrightomega_ptr[2*3+1] = ("wrightomega") +ufunc_wrightomega_data[0] = &ufunc_wrightomega_ptr[2*0] +ufunc_wrightomega_data[1] = &ufunc_wrightomega_ptr[2*1] +ufunc_wrightomega_data[2] = &ufunc_wrightomega_ptr[2*2] +ufunc_wrightomega_data[3] = &ufunc_wrightomega_ptr[2*3] +wrightomega = np.PyUFunc_FromFuncAndData(ufunc_wrightomega_loops, ufunc_wrightomega_data, ufunc_wrightomega_types, 4, 1, 1, 0, "wrightomega", ufunc_wrightomega_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_xlog1py_loops[4] +cdef void *ufunc_xlog1py_ptr[8] +cdef void *ufunc_xlog1py_data[4] +cdef char ufunc_xlog1py_types[12] +cdef char *ufunc_xlog1py_doc = ( + "xlog1py(x, y, out=None)\n" + "\n" + "Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Multiplier\n" + "y : array_like\n" + " Argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "z : scalar or ndarray\n" + " Computed x*log1p(y)\n" + "\n" + "Notes\n" + "-----\n" + "\n" + ".. versionadded:: 0.13.0\n" + "\n" + "Examples\n" + "--------\n" + "This example shows how the function can be used to calculate the log of\n" + "the probability mass function for a geometric discrete random variable.\n" + "The probability mass function of the geometric distribution is defined\n" + "as follows:\n" + "\n" + ".. math:: f(k) = (1-p)^{k-1} p\n" + "\n" + "where :math:`p` is the probability of a single success\n" + "and :math:`1-p` is the probability of a single failure\n" + "and :math:`k` is the number of trials to get the first success.\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import xlog1py\n" + ">>> p = 0.5\n" + ">>> k = 100\n" + ">>> _pmf = np.power(1 - p, k - 1) * p\n" + ">>> _pmf\n" + "7.888609052210118e-31\n" + "\n" + "If we take k as a relatively large number the value of the probability\n" + "mass function can become very low. In such cases taking the log of the\n" + "pmf would be more suitable as the log function can change the values\n" + "to a scale that is more appropriate to work with.\n" + "\n" + ">>> _log_pmf = xlog1py(k - 1, -p) + np.log(p)\n" + ">>> _log_pmf\n" + "-69.31471805599453\n" + "\n" + "We can confirm that we get a value close to the original pmf value by\n" + "taking the exponential of the log pmf.\n" + "\n" + ">>> _orig_pmf = np.exp(_log_pmf)\n" + ">>> np.isclose(_pmf, _orig_pmf)\n" + "True") +ufunc_xlog1py_loops[0] = loop_d_dd__As_ff_f +ufunc_xlog1py_loops[1] = loop_d_dd__As_dd_d +ufunc_xlog1py_loops[2] = loop_D_DD__As_FF_F +ufunc_xlog1py_loops[3] = loop_D_DD__As_DD_D +ufunc_xlog1py_types[0] = NPY_FLOAT +ufunc_xlog1py_types[1] = NPY_FLOAT +ufunc_xlog1py_types[2] = NPY_FLOAT +ufunc_xlog1py_types[3] = NPY_DOUBLE +ufunc_xlog1py_types[4] = NPY_DOUBLE +ufunc_xlog1py_types[5] = NPY_DOUBLE +ufunc_xlog1py_types[6] = NPY_CFLOAT +ufunc_xlog1py_types[7] = NPY_CFLOAT +ufunc_xlog1py_types[8] = NPY_CFLOAT +ufunc_xlog1py_types[9] = NPY_CDOUBLE +ufunc_xlog1py_types[10] = NPY_CDOUBLE +ufunc_xlog1py_types[11] = NPY_CDOUBLE +ufunc_xlog1py_ptr[2*0] = _func_xlog1py[double] +ufunc_xlog1py_ptr[2*0+1] = ("xlog1py") +ufunc_xlog1py_ptr[2*1] = _func_xlog1py[double] +ufunc_xlog1py_ptr[2*1+1] = ("xlog1py") +ufunc_xlog1py_ptr[2*2] = _func_xlog1py[double_complex] +ufunc_xlog1py_ptr[2*2+1] = ("xlog1py") +ufunc_xlog1py_ptr[2*3] = _func_xlog1py[double_complex] +ufunc_xlog1py_ptr[2*3+1] = ("xlog1py") +ufunc_xlog1py_data[0] = &ufunc_xlog1py_ptr[2*0] +ufunc_xlog1py_data[1] = &ufunc_xlog1py_ptr[2*1] +ufunc_xlog1py_data[2] = &ufunc_xlog1py_ptr[2*2] +ufunc_xlog1py_data[3] = &ufunc_xlog1py_ptr[2*3] +xlog1py = np.PyUFunc_FromFuncAndData(ufunc_xlog1py_loops, ufunc_xlog1py_data, ufunc_xlog1py_types, 4, 2, 1, 0, "xlog1py", ufunc_xlog1py_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_xlogy_loops[4] +cdef void *ufunc_xlogy_ptr[8] +cdef void *ufunc_xlogy_data[4] +cdef char ufunc_xlogy_types[12] +cdef char *ufunc_xlogy_doc = ( + "xlogy(x, y, out=None)\n" + "\n" + "Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.\n" + "\n" + "Parameters\n" + "----------\n" + "x : array_like\n" + " Multiplier\n" + "y : array_like\n" + " Argument\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "z : scalar or ndarray\n" + " Computed x*log(y)\n" + "\n" + "Notes\n" + "-----\n" + "The log function used in the computation is the natural log.\n" + "\n" + ".. versionadded:: 0.13.0\n" + "\n" + "Examples\n" + "--------\n" + "We can use this function to calculate the binary logistic loss also\n" + "known as the binary cross entropy. This loss function is used for\n" + "binary classification problems and is defined as:\n" + "\n" + ".. math::\n" + " L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i))\n" + "\n" + "We can define the parameters `x` and `y` as y and y_pred respectively.\n" + "y is the array of the actual labels which over here can be either 0 or 1.\n" + "y_pred is the array of the predicted probabilities with respect to\n" + "the positive class (1).\n" + "\n" + ">>> import numpy as np\n" + ">>> from scipy.special import xlogy\n" + ">>> y = np.array([0, 1, 0, 1, 1, 0])\n" + ">>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2])\n" + ">>> n = len(y)\n" + ">>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum()\n" + ">>> loss /= n\n" + ">>> loss\n" + "0.29597052165495025\n" + "\n" + "A lower loss is usually better as it indicates that the predictions are\n" + "similar to the actual labels. In this example since our predicted\n" + "probabilities are close to the actual labels, we get an overall loss\n" + "that is reasonably low and appropriate.") +ufunc_xlogy_loops[0] = loop_d_dd__As_ff_f +ufunc_xlogy_loops[1] = loop_d_dd__As_dd_d +ufunc_xlogy_loops[2] = loop_D_DD__As_FF_F +ufunc_xlogy_loops[3] = loop_D_DD__As_DD_D +ufunc_xlogy_types[0] = NPY_FLOAT +ufunc_xlogy_types[1] = NPY_FLOAT +ufunc_xlogy_types[2] = NPY_FLOAT +ufunc_xlogy_types[3] = NPY_DOUBLE +ufunc_xlogy_types[4] = NPY_DOUBLE +ufunc_xlogy_types[5] = NPY_DOUBLE +ufunc_xlogy_types[6] = NPY_CFLOAT +ufunc_xlogy_types[7] = NPY_CFLOAT +ufunc_xlogy_types[8] = NPY_CFLOAT +ufunc_xlogy_types[9] = NPY_CDOUBLE +ufunc_xlogy_types[10] = NPY_CDOUBLE +ufunc_xlogy_types[11] = NPY_CDOUBLE +ufunc_xlogy_ptr[2*0] = _func_xlogy[double] +ufunc_xlogy_ptr[2*0+1] = ("xlogy") +ufunc_xlogy_ptr[2*1] = _func_xlogy[double] +ufunc_xlogy_ptr[2*1+1] = ("xlogy") +ufunc_xlogy_ptr[2*2] = _func_xlogy[double_complex] +ufunc_xlogy_ptr[2*2+1] = ("xlogy") +ufunc_xlogy_ptr[2*3] = _func_xlogy[double_complex] +ufunc_xlogy_ptr[2*3+1] = ("xlogy") +ufunc_xlogy_data[0] = &ufunc_xlogy_ptr[2*0] +ufunc_xlogy_data[1] = &ufunc_xlogy_ptr[2*1] +ufunc_xlogy_data[2] = &ufunc_xlogy_ptr[2*2] +ufunc_xlogy_data[3] = &ufunc_xlogy_ptr[2*3] +xlogy = np.PyUFunc_FromFuncAndData(ufunc_xlogy_loops, ufunc_xlogy_data, ufunc_xlogy_types, 4, 2, 1, 0, "xlogy", ufunc_xlogy_doc, 0) + +cdef np.PyUFuncGenericFunction ufunc_yn_loops[3] +cdef void *ufunc_yn_ptr[6] +cdef void *ufunc_yn_data[3] +cdef char ufunc_yn_types[9] +cdef char *ufunc_yn_doc = ( + "yn(n, x, out=None)\n" + "\n" + "Bessel function of the second kind of integer order and real argument.\n" + "\n" + "Parameters\n" + "----------\n" + "n : array_like\n" + " Order (integer).\n" + "x : array_like\n" + " Argument (float).\n" + "out : ndarray, optional\n" + " Optional output array for the function results\n" + "\n" + "Returns\n" + "-------\n" + "Y : scalar or ndarray\n" + " Value of the Bessel function, :math:`Y_n(x)`.\n" + "\n" + "See Also\n" + "--------\n" + "yv : For real order and real or complex argument.\n" + "y0: faster implementation of this function for order 0\n" + "y1: faster implementation of this function for order 1\n" + "\n" + "Notes\n" + "-----\n" + "Wrapper for the Cephes [1]_ routine `yn`.\n" + "\n" + "The function is evaluated by forward recurrence on `n`, starting with\n" + "values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1,\n" + "the routine for `y0` or `y1` is called directly.\n" + "\n" + "References\n" + "----------\n" + ".. [1] Cephes Mathematical Functions Library,\n" + " http://www.netlib.org/cephes/\n" + "\n" + "Examples\n" + "--------\n" + "Evaluate the function of order 0 at one point.\n" + "\n" + ">>> from scipy.special import yn\n" + ">>> yn(0, 1.)\n" + "0.08825696421567697\n" + "\n" + "Evaluate the function at one point for different orders.\n" + "\n" + ">>> yn(0, 1.), yn(1, 1.), yn(2, 1.)\n" + "(0.08825696421567697, -0.7812128213002888, -1.6506826068162546)\n" + "\n" + "The evaluation for different orders can be carried out in one call by\n" + "providing a list or NumPy array as argument for the `v` parameter:\n" + "\n" + ">>> yn([0, 1, 2], 1.)\n" + "array([ 0.08825696, -0.78121282, -1.65068261])\n" + "\n" + "Evaluate the function at several points for order 0 by providing an\n" + "array for `z`.\n" + "\n" + ">>> import numpy as np\n" + ">>> points = np.array([0.5, 3., 8.])\n" + ">>> yn(0, points)\n" + "array([-0.44451873, 0.37685001, 0.22352149])\n" + "\n" + "If `z` is an array, the order parameter `v` must be broadcastable to\n" + "the correct shape if different orders shall be computed in one call.\n" + "To calculate the orders 0 and 1 for an 1D array:\n" + "\n" + ">>> orders = np.array([[0], [1]])\n" + ">>> orders.shape\n" + "(2, 1)\n" + "\n" + ">>> yn(orders, points)\n" + "array([[-0.44451873, 0.37685001, 0.22352149],\n" + " [-1.47147239, 0.32467442, -0.15806046]])\n" + "\n" + "Plot the functions of order 0 to 3 from 0 to 10.\n" + "\n" + ">>> import matplotlib.pyplot as plt\n" + ">>> fig, ax = plt.subplots()\n" + ">>> x = np.linspace(0., 10., 1000)\n" + ">>> for i in range(4):\n" + "... ax.plot(x, yn(i, x), label=f'$Y_{i!r}$')\n" + ">>> ax.set_ylim(-3, 1)\n" + ">>> ax.legend()\n" + ">>> plt.show()") +ufunc_yn_loops[0] = loop_d_pd__As_pd_d +ufunc_yn_loops[1] = loop_d_dd__As_ff_f +ufunc_yn_loops[2] = loop_d_dd__As_dd_d +ufunc_yn_types[0] = NPY_INTP +ufunc_yn_types[1] = NPY_DOUBLE +ufunc_yn_types[2] = NPY_DOUBLE +ufunc_yn_types[3] = NPY_FLOAT +ufunc_yn_types[4] = NPY_FLOAT +ufunc_yn_types[5] = NPY_FLOAT +ufunc_yn_types[6] = NPY_DOUBLE +ufunc_yn_types[7] = NPY_DOUBLE +ufunc_yn_types[8] = NPY_DOUBLE +ufunc_yn_ptr[2*0] = _func_cephes_yn_wrap +ufunc_yn_ptr[2*0+1] = ("yn") +ufunc_yn_ptr[2*1] = _func_yn_unsafe +ufunc_yn_ptr[2*1+1] = ("yn") +ufunc_yn_ptr[2*2] = _func_yn_unsafe +ufunc_yn_ptr[2*2+1] = ("yn") +ufunc_yn_data[0] = &ufunc_yn_ptr[2*0] +ufunc_yn_data[1] = &ufunc_yn_ptr[2*1] +ufunc_yn_data[2] = &ufunc_yn_ptr[2*2] +yn = np.PyUFunc_FromFuncAndData(ufunc_yn_loops, ufunc_yn_data, ufunc_yn_types, 3, 2, 1, 0, "yn", ufunc_yn_doc, 0) + +from ._special_ufuncs import (_cospi, _lambertw, _scaled_exp1, _sinpi, _spherical_jn, _spherical_jn_d, _spherical_yn, _spherical_yn_d, _spherical_in, _spherical_in_d, _spherical_kn, _spherical_kn_d, airy, airye, bei, beip, ber, berp, binom, exp1, expi, expit, exprel, gamma, gammaln, hankel1, hankel1e, hankel2, hankel2e, hyp2f1, it2i0k0, it2j0y0, it2struve0, itairy, iti0k0, itj0y0, itmodstruve0, itstruve0, iv, _iv_ratio, _iv_ratio_c, ive, jv, jve, kei, keip, kelvin, ker, kerp, kv, kve, log_expit, log_wright_bessel, loggamma, logit, mathieu_a, mathieu_b, mathieu_cem, mathieu_modcem1, mathieu_modcem2, mathieu_modsem1, mathieu_modsem2, mathieu_sem, modfresnelm, modfresnelp, obl_ang1, obl_ang1_cv, obl_cv, obl_rad1, obl_rad1_cv, obl_rad2, obl_rad2_cv, pbdv, pbvv, pbwa, pro_ang1, pro_ang1_cv, pro_cv, pro_rad1, pro_rad1_cv, pro_rad2, pro_rad2_cv, psi, rgamma, sph_harm, wright_bessel, yv, yve, zetac, _zeta, sindg, cosdg, tandg, cotdg, i0, i0e, i1, i1e, k0, k0e, k1, k1e, y0, y1, j0, j1, struve, modstruve, beta, betaln, besselpoly, gammaln, gammasgn, cbrt, radian, cosm1, gammainc, gammaincinv, gammaincc, gammainccinv, fresnel, ellipe, ellipeinc, ellipk, ellipkinc, ellipkm1, ellipj, _riemann_zeta) + +# +# Aliases +# +jn = jv diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a2fffff86812d1a7ca547a71a19078b6d5f59716 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd @@ -0,0 +1,155 @@ +from . cimport sf_error +cdef void _set_action(sf_error.sf_error_t, sf_error.sf_action_t) noexcept nogil +cdef void *_export_beta_pdf_float +cdef void *_export_beta_pdf_double +cdef void *_export_beta_ppf_float +cdef void *_export_beta_ppf_double +cdef void *_export_binom_cdf_float +cdef void *_export_binom_cdf_double +cdef void *_export_binom_isf_float +cdef void *_export_binom_isf_double +cdef void *_export_binom_pmf_float +cdef void *_export_binom_pmf_double +cdef void *_export_binom_ppf_float +cdef void *_export_binom_ppf_double +cdef void *_export_binom_sf_float +cdef void *_export_binom_sf_double +cdef void *_export_cauchy_isf_float +cdef void *_export_cauchy_isf_double +cdef void *_export_cauchy_ppf_float +cdef void *_export_cauchy_ppf_double +cdef void *_export_hypergeom_cdf_float +cdef void *_export_hypergeom_cdf_double +cdef void *_export_hypergeom_mean_float +cdef void *_export_hypergeom_mean_double +cdef void *_export_hypergeom_pmf_float +cdef void *_export_hypergeom_pmf_double +cdef void *_export_hypergeom_sf_float +cdef void *_export_hypergeom_sf_double +cdef void *_export_hypergeom_skewness_float +cdef void *_export_hypergeom_skewness_double +cdef void *_export_hypergeom_variance_float +cdef void *_export_hypergeom_variance_double +cdef void *_export_invgauss_isf_float +cdef void *_export_invgauss_isf_double +cdef void *_export_invgauss_ppf_float +cdef void *_export_invgauss_ppf_double +cdef void *_export_landau_cdf_float +cdef void *_export_landau_cdf_double +cdef void *_export_landau_isf_float +cdef void *_export_landau_isf_double +cdef void *_export_landau_pdf_float +cdef void *_export_landau_pdf_double +cdef void *_export_landau_ppf_float +cdef void *_export_landau_ppf_double +cdef void *_export_landau_sf_float +cdef void *_export_landau_sf_double +cdef void *_export_nbinom_cdf_float +cdef void *_export_nbinom_cdf_double +cdef void *_export_nbinom_isf_float +cdef void *_export_nbinom_isf_double +cdef void *_export_nbinom_kurtosis_excess_float +cdef void *_export_nbinom_kurtosis_excess_double +cdef void *_export_nbinom_mean_float +cdef void *_export_nbinom_mean_double +cdef void *_export_nbinom_pmf_float +cdef void *_export_nbinom_pmf_double +cdef void *_export_nbinom_ppf_float +cdef void *_export_nbinom_ppf_double +cdef void *_export_nbinom_sf_float +cdef void *_export_nbinom_sf_double +cdef void *_export_nbinom_skewness_float +cdef void *_export_nbinom_skewness_double +cdef void *_export_nbinom_variance_float +cdef void *_export_nbinom_variance_double +cdef void *_export_ncf_isf_float +cdef void *_export_ncf_isf_double +cdef void *_export_ncf_kurtosis_excess_float +cdef void *_export_ncf_kurtosis_excess_double +cdef void *_export_ncf_mean_float +cdef void *_export_ncf_mean_double +cdef void *_export_ncf_pdf_float +cdef void *_export_ncf_pdf_double +cdef void *_export_ncf_sf_float +cdef void *_export_ncf_sf_double +cdef void *_export_ncf_skewness_float +cdef void *_export_ncf_skewness_double +cdef void *_export_ncf_variance_float +cdef void *_export_ncf_variance_double +cdef void *_export_nct_isf_float +cdef void *_export_nct_isf_double +cdef void *_export_nct_kurtosis_excess_float +cdef void *_export_nct_kurtosis_excess_double +cdef void *_export_nct_mean_float +cdef void *_export_nct_mean_double +cdef void *_export_nct_pdf_float +cdef void *_export_nct_pdf_double +cdef void *_export_nct_ppf_float +cdef void *_export_nct_ppf_double +cdef void *_export_nct_sf_float +cdef void *_export_nct_sf_double +cdef void *_export_nct_skewness_float +cdef void *_export_nct_skewness_double +cdef void *_export_nct_variance_float +cdef void *_export_nct_variance_double +cdef void *_export_ncx2_cdf_float +cdef void *_export_ncx2_cdf_double +cdef void *_export_ncx2_isf_float +cdef void *_export_ncx2_isf_double +cdef void *_export_ncx2_pdf_float +cdef void *_export_ncx2_pdf_double +cdef void *_export_ncx2_ppf_float +cdef void *_export_ncx2_ppf_double +cdef void *_export_ncx2_sf_float +cdef void *_export_ncx2_sf_double +cdef void *_export_skewnorm_cdf_float +cdef void *_export_skewnorm_cdf_double +cdef void *_export_skewnorm_isf_float +cdef void *_export_skewnorm_isf_double +cdef void *_export_skewnorm_ppf_float +cdef void *_export_skewnorm_ppf_double +cdef void *_export__stirling2_inexact +cdef void *_export_ibeta_float +cdef void *_export_ibeta_double +cdef void *_export_ibetac_float +cdef void *_export_ibetac_double +cdef void *_export_ibetac_inv_float +cdef void *_export_ibetac_inv_double +cdef void *_export_ibeta_inv_float +cdef void *_export_ibeta_inv_double +cdef void *_export_faddeeva_dawsn +cdef void *_export_faddeeva_dawsn_complex +cdef void *_export_fellint_RC +cdef void *_export_cellint_RC +cdef void *_export_fellint_RD +cdef void *_export_cellint_RD +cdef void *_export_fellint_RF +cdef void *_export_cellint_RF +cdef void *_export_fellint_RG +cdef void *_export_cellint_RG +cdef void *_export_fellint_RJ +cdef void *_export_cellint_RJ +cdef void *_export_faddeeva_erf +cdef void *_export_faddeeva_erfc_complex +cdef void *_export_faddeeva_erfcx +cdef void *_export_faddeeva_erfcx_complex +cdef void *_export_faddeeva_erfi +cdef void *_export_faddeeva_erfi_complex +cdef void *_export_erfinv_float +cdef void *_export_erfinv_double +cdef void *_export_hyp1f1_double +cdef void *_export_faddeeva_log_ndtr +cdef void *_export_faddeeva_log_ndtr_complex +cdef void *_export_ncf_cdf_float +cdef void *_export_ncf_cdf_double +cdef void *_export_ncf_ppf_float +cdef void *_export_ncf_ppf_double +cdef void *_export_nct_cdf_float +cdef void *_export_nct_cdf_double +cdef void *_export_faddeeva_ndtr +cdef void *_export_powm1_float +cdef void *_export_powm1_double +cdef void *_export_faddeeva_voigt_profile +cdef void *_export_faddeeva_w +cdef void *_export_wrightomega +cdef void *_export_wrightomega_real \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx new file mode 100644 index 0000000000000000000000000000000000000000..19cbd36c4707bb593e7e5638b9a158df504d3001 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx @@ -0,0 +1,466 @@ +# This file is automatically generated by _generate_pyx.py. +# Do not edit manually! + +from libc.math cimport NAN + +include "_ufuncs_extra_code_common.pxi" + +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_beta_pdf_float "beta_pdf_float"(float, float, float) noexcept nogil +cdef void *_export_beta_pdf_float = _func_beta_pdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_beta_pdf_double "beta_pdf_double"(double, double, double) noexcept nogil +cdef void *_export_beta_pdf_double = _func_beta_pdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_beta_ppf_float "beta_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_beta_ppf_float = _func_beta_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_beta_ppf_double "beta_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_beta_ppf_double = _func_beta_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_binom_cdf_float "binom_cdf_float"(float, float, float) noexcept nogil +cdef void *_export_binom_cdf_float = _func_binom_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_binom_cdf_double "binom_cdf_double"(double, double, double) noexcept nogil +cdef void *_export_binom_cdf_double = _func_binom_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_binom_isf_float "binom_isf_float"(float, float, float) noexcept nogil +cdef void *_export_binom_isf_float = _func_binom_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_binom_isf_double "binom_isf_double"(double, double, double) noexcept nogil +cdef void *_export_binom_isf_double = _func_binom_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_binom_pmf_float "binom_pmf_float"(float, float, float) noexcept nogil +cdef void *_export_binom_pmf_float = _func_binom_pmf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_binom_pmf_double "binom_pmf_double"(double, double, double) noexcept nogil +cdef void *_export_binom_pmf_double = _func_binom_pmf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_binom_ppf_float "binom_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_binom_ppf_float = _func_binom_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_binom_ppf_double "binom_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_binom_ppf_double = _func_binom_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_binom_sf_float "binom_sf_float"(float, float, float) noexcept nogil +cdef void *_export_binom_sf_float = _func_binom_sf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_binom_sf_double "binom_sf_double"(double, double, double) noexcept nogil +cdef void *_export_binom_sf_double = _func_binom_sf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_cauchy_isf_float "cauchy_isf_float"(float, float, float) noexcept nogil +cdef void *_export_cauchy_isf_float = _func_cauchy_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_cauchy_isf_double "cauchy_isf_double"(double, double, double) noexcept nogil +cdef void *_export_cauchy_isf_double = _func_cauchy_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_cauchy_ppf_float "cauchy_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_cauchy_ppf_float = _func_cauchy_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_cauchy_ppf_double "cauchy_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_cauchy_ppf_double = _func_cauchy_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_hypergeom_cdf_float "hypergeom_cdf_float"(float, float, float, float) noexcept nogil +cdef void *_export_hypergeom_cdf_float = _func_hypergeom_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_hypergeom_cdf_double "hypergeom_cdf_double"(double, double, double, double) noexcept nogil +cdef void *_export_hypergeom_cdf_double = _func_hypergeom_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_hypergeom_mean_float "hypergeom_mean_float"(float, float, float) noexcept nogil +cdef void *_export_hypergeom_mean_float = _func_hypergeom_mean_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_hypergeom_mean_double "hypergeom_mean_double"(double, double, double) noexcept nogil +cdef void *_export_hypergeom_mean_double = _func_hypergeom_mean_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_hypergeom_pmf_float "hypergeom_pmf_float"(float, float, float, float) noexcept nogil +cdef void *_export_hypergeom_pmf_float = _func_hypergeom_pmf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_hypergeom_pmf_double "hypergeom_pmf_double"(double, double, double, double) noexcept nogil +cdef void *_export_hypergeom_pmf_double = _func_hypergeom_pmf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_hypergeom_sf_float "hypergeom_sf_float"(float, float, float, float) noexcept nogil +cdef void *_export_hypergeom_sf_float = _func_hypergeom_sf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_hypergeom_sf_double "hypergeom_sf_double"(double, double, double, double) noexcept nogil +cdef void *_export_hypergeom_sf_double = _func_hypergeom_sf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_hypergeom_skewness_float "hypergeom_skewness_float"(float, float, float) noexcept nogil +cdef void *_export_hypergeom_skewness_float = _func_hypergeom_skewness_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_hypergeom_skewness_double "hypergeom_skewness_double"(double, double, double) noexcept nogil +cdef void *_export_hypergeom_skewness_double = _func_hypergeom_skewness_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_hypergeom_variance_float "hypergeom_variance_float"(float, float, float) noexcept nogil +cdef void *_export_hypergeom_variance_float = _func_hypergeom_variance_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_hypergeom_variance_double "hypergeom_variance_double"(double, double, double) noexcept nogil +cdef void *_export_hypergeom_variance_double = _func_hypergeom_variance_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_invgauss_isf_float "invgauss_isf_float"(float, float, float) noexcept nogil +cdef void *_export_invgauss_isf_float = _func_invgauss_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_invgauss_isf_double "invgauss_isf_double"(double, double, double) noexcept nogil +cdef void *_export_invgauss_isf_double = _func_invgauss_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_invgauss_ppf_float "invgauss_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_invgauss_ppf_float = _func_invgauss_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_invgauss_ppf_double "invgauss_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_invgauss_ppf_double = _func_invgauss_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_landau_cdf_float "landau_cdf_float"(float, float, float) noexcept nogil +cdef void *_export_landau_cdf_float = _func_landau_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_landau_cdf_double "landau_cdf_double"(double, double, double) noexcept nogil +cdef void *_export_landau_cdf_double = _func_landau_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_landau_isf_float "landau_isf_float"(float, float, float) noexcept nogil +cdef void *_export_landau_isf_float = _func_landau_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_landau_isf_double "landau_isf_double"(double, double, double) noexcept nogil +cdef void *_export_landau_isf_double = _func_landau_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_landau_pdf_float "landau_pdf_float"(float, float, float) noexcept nogil +cdef void *_export_landau_pdf_float = _func_landau_pdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_landau_pdf_double "landau_pdf_double"(double, double, double) noexcept nogil +cdef void *_export_landau_pdf_double = _func_landau_pdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_landau_ppf_float "landau_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_landau_ppf_float = _func_landau_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_landau_ppf_double "landau_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_landau_ppf_double = _func_landau_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_landau_sf_float "landau_sf_float"(float, float, float) noexcept nogil +cdef void *_export_landau_sf_float = _func_landau_sf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_landau_sf_double "landau_sf_double"(double, double, double) noexcept nogil +cdef void *_export_landau_sf_double = _func_landau_sf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_cdf_float "nbinom_cdf_float"(float, float, float) noexcept nogil +cdef void *_export_nbinom_cdf_float = _func_nbinom_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_cdf_double "nbinom_cdf_double"(double, double, double) noexcept nogil +cdef void *_export_nbinom_cdf_double = _func_nbinom_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_isf_float "nbinom_isf_float"(float, float, float) noexcept nogil +cdef void *_export_nbinom_isf_float = _func_nbinom_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_isf_double "nbinom_isf_double"(double, double, double) noexcept nogil +cdef void *_export_nbinom_isf_double = _func_nbinom_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_kurtosis_excess_float "nbinom_kurtosis_excess_float"(float, float) noexcept nogil +cdef void *_export_nbinom_kurtosis_excess_float = _func_nbinom_kurtosis_excess_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_kurtosis_excess_double "nbinom_kurtosis_excess_double"(double, double) noexcept nogil +cdef void *_export_nbinom_kurtosis_excess_double = _func_nbinom_kurtosis_excess_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_mean_float "nbinom_mean_float"(float, float) noexcept nogil +cdef void *_export_nbinom_mean_float = _func_nbinom_mean_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_mean_double "nbinom_mean_double"(double, double) noexcept nogil +cdef void *_export_nbinom_mean_double = _func_nbinom_mean_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_pmf_float "nbinom_pmf_float"(float, float, float) noexcept nogil +cdef void *_export_nbinom_pmf_float = _func_nbinom_pmf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_pmf_double "nbinom_pmf_double"(double, double, double) noexcept nogil +cdef void *_export_nbinom_pmf_double = _func_nbinom_pmf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_ppf_float "nbinom_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_nbinom_ppf_float = _func_nbinom_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_ppf_double "nbinom_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_nbinom_ppf_double = _func_nbinom_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_sf_float "nbinom_sf_float"(float, float, float) noexcept nogil +cdef void *_export_nbinom_sf_float = _func_nbinom_sf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_sf_double "nbinom_sf_double"(double, double, double) noexcept nogil +cdef void *_export_nbinom_sf_double = _func_nbinom_sf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_skewness_float "nbinom_skewness_float"(float, float) noexcept nogil +cdef void *_export_nbinom_skewness_float = _func_nbinom_skewness_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_skewness_double "nbinom_skewness_double"(double, double) noexcept nogil +cdef void *_export_nbinom_skewness_double = _func_nbinom_skewness_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nbinom_variance_float "nbinom_variance_float"(float, float) noexcept nogil +cdef void *_export_nbinom_variance_float = _func_nbinom_variance_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nbinom_variance_double "nbinom_variance_double"(double, double) noexcept nogil +cdef void *_export_nbinom_variance_double = _func_nbinom_variance_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_isf_float "ncf_isf_float"(float, float, float, float) noexcept nogil +cdef void *_export_ncf_isf_float = _func_ncf_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_isf_double "ncf_isf_double"(double, double, double, double) noexcept nogil +cdef void *_export_ncf_isf_double = _func_ncf_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_kurtosis_excess_float "ncf_kurtosis_excess_float"(float, float, float) noexcept nogil +cdef void *_export_ncf_kurtosis_excess_float = _func_ncf_kurtosis_excess_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_kurtosis_excess_double "ncf_kurtosis_excess_double"(double, double, double) noexcept nogil +cdef void *_export_ncf_kurtosis_excess_double = _func_ncf_kurtosis_excess_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_mean_float "ncf_mean_float"(float, float, float) noexcept nogil +cdef void *_export_ncf_mean_float = _func_ncf_mean_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_mean_double "ncf_mean_double"(double, double, double) noexcept nogil +cdef void *_export_ncf_mean_double = _func_ncf_mean_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_pdf_float "ncf_pdf_float"(float, float, float, float) noexcept nogil +cdef void *_export_ncf_pdf_float = _func_ncf_pdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_pdf_double "ncf_pdf_double"(double, double, double, double) noexcept nogil +cdef void *_export_ncf_pdf_double = _func_ncf_pdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_sf_float "ncf_sf_float"(float, float, float, float) noexcept nogil +cdef void *_export_ncf_sf_float = _func_ncf_sf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_sf_double "ncf_sf_double"(double, double, double, double) noexcept nogil +cdef void *_export_ncf_sf_double = _func_ncf_sf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_skewness_float "ncf_skewness_float"(float, float, float) noexcept nogil +cdef void *_export_ncf_skewness_float = _func_ncf_skewness_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_skewness_double "ncf_skewness_double"(double, double, double) noexcept nogil +cdef void *_export_ncf_skewness_double = _func_ncf_skewness_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_variance_float "ncf_variance_float"(float, float, float) noexcept nogil +cdef void *_export_ncf_variance_float = _func_ncf_variance_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_variance_double "ncf_variance_double"(double, double, double) noexcept nogil +cdef void *_export_ncf_variance_double = _func_ncf_variance_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_isf_float "nct_isf_float"(float, float, float) noexcept nogil +cdef void *_export_nct_isf_float = _func_nct_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_isf_double "nct_isf_double"(double, double, double) noexcept nogil +cdef void *_export_nct_isf_double = _func_nct_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_kurtosis_excess_float "nct_kurtosis_excess_float"(float, float) noexcept nogil +cdef void *_export_nct_kurtosis_excess_float = _func_nct_kurtosis_excess_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_kurtosis_excess_double "nct_kurtosis_excess_double"(double, double) noexcept nogil +cdef void *_export_nct_kurtosis_excess_double = _func_nct_kurtosis_excess_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_mean_float "nct_mean_float"(float, float) noexcept nogil +cdef void *_export_nct_mean_float = _func_nct_mean_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_mean_double "nct_mean_double"(double, double) noexcept nogil +cdef void *_export_nct_mean_double = _func_nct_mean_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_pdf_float "nct_pdf_float"(float, float, float) noexcept nogil +cdef void *_export_nct_pdf_float = _func_nct_pdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_pdf_double "nct_pdf_double"(double, double, double) noexcept nogil +cdef void *_export_nct_pdf_double = _func_nct_pdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_ppf_float "nct_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_nct_ppf_float = _func_nct_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_ppf_double "nct_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_nct_ppf_double = _func_nct_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_sf_float "nct_sf_float"(float, float, float) noexcept nogil +cdef void *_export_nct_sf_float = _func_nct_sf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_sf_double "nct_sf_double"(double, double, double) noexcept nogil +cdef void *_export_nct_sf_double = _func_nct_sf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_skewness_float "nct_skewness_float"(float, float) noexcept nogil +cdef void *_export_nct_skewness_float = _func_nct_skewness_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_skewness_double "nct_skewness_double"(double, double) noexcept nogil +cdef void *_export_nct_skewness_double = _func_nct_skewness_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_variance_float "nct_variance_float"(float, float) noexcept nogil +cdef void *_export_nct_variance_float = _func_nct_variance_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_variance_double "nct_variance_double"(double, double) noexcept nogil +cdef void *_export_nct_variance_double = _func_nct_variance_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncx2_cdf_float "ncx2_cdf_float"(float, float, float) noexcept nogil +cdef void *_export_ncx2_cdf_float = _func_ncx2_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncx2_cdf_double "ncx2_cdf_double"(double, double, double) noexcept nogil +cdef void *_export_ncx2_cdf_double = _func_ncx2_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncx2_isf_float "ncx2_isf_float"(float, float, float) noexcept nogil +cdef void *_export_ncx2_isf_float = _func_ncx2_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncx2_isf_double "ncx2_isf_double"(double, double, double) noexcept nogil +cdef void *_export_ncx2_isf_double = _func_ncx2_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncx2_pdf_float "ncx2_pdf_float"(float, float, float) noexcept nogil +cdef void *_export_ncx2_pdf_float = _func_ncx2_pdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncx2_pdf_double "ncx2_pdf_double"(double, double, double) noexcept nogil +cdef void *_export_ncx2_pdf_double = _func_ncx2_pdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncx2_ppf_float "ncx2_ppf_float"(float, float, float) noexcept nogil +cdef void *_export_ncx2_ppf_float = _func_ncx2_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncx2_ppf_double "ncx2_ppf_double"(double, double, double) noexcept nogil +cdef void *_export_ncx2_ppf_double = _func_ncx2_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncx2_sf_float "ncx2_sf_float"(float, float, float) noexcept nogil +cdef void *_export_ncx2_sf_float = _func_ncx2_sf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncx2_sf_double "ncx2_sf_double"(double, double, double) noexcept nogil +cdef void *_export_ncx2_sf_double = _func_ncx2_sf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_skewnorm_cdf_float "skewnorm_cdf_float"(float, float, float, float) noexcept nogil +cdef void *_export_skewnorm_cdf_float = _func_skewnorm_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_skewnorm_cdf_double "skewnorm_cdf_double"(double, double, double, double) noexcept nogil +cdef void *_export_skewnorm_cdf_double = _func_skewnorm_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_skewnorm_isf_float "skewnorm_isf_float"(float, float, float, float) noexcept nogil +cdef void *_export_skewnorm_isf_float = _func_skewnorm_isf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_skewnorm_isf_double "skewnorm_isf_double"(double, double, double, double) noexcept nogil +cdef void *_export_skewnorm_isf_double = _func_skewnorm_isf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_skewnorm_ppf_float "skewnorm_ppf_float"(float, float, float, float) noexcept nogil +cdef void *_export_skewnorm_ppf_float = _func_skewnorm_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_skewnorm_ppf_double "skewnorm_ppf_double"(double, double, double, double) noexcept nogil +cdef void *_export_skewnorm_ppf_double = _func_skewnorm_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func__stirling2_inexact "_stirling2_inexact"(double, double) noexcept nogil +cdef void *_export__stirling2_inexact = _func__stirling2_inexact +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ibeta_float "ibeta_float"(float, float, float) noexcept nogil +cdef void *_export_ibeta_float = _func_ibeta_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ibeta_double "ibeta_double"(double, double, double) noexcept nogil +cdef void *_export_ibeta_double = _func_ibeta_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ibetac_float "ibetac_float"(float, float, float) noexcept nogil +cdef void *_export_ibetac_float = _func_ibetac_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ibetac_double "ibetac_double"(double, double, double) noexcept nogil +cdef void *_export_ibetac_double = _func_ibetac_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ibetac_inv_float "ibetac_inv_float"(float, float, float) noexcept nogil +cdef void *_export_ibetac_inv_float = _func_ibetac_inv_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ibetac_inv_double "ibetac_inv_double"(double, double, double) noexcept nogil +cdef void *_export_ibetac_inv_double = _func_ibetac_inv_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ibeta_inv_float "ibeta_inv_float"(float, float, float) noexcept nogil +cdef void *_export_ibeta_inv_float = _func_ibeta_inv_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ibeta_inv_double "ibeta_inv_double"(double, double, double) noexcept nogil +cdef void *_export_ibeta_inv_double = _func_ibeta_inv_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_faddeeva_dawsn "faddeeva_dawsn"(double) noexcept nogil +cdef void *_export_faddeeva_dawsn = _func_faddeeva_dawsn +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_dawsn_complex "faddeeva_dawsn_complex"(double complex) noexcept nogil +cdef void *_export_faddeeva_dawsn_complex = _func_faddeeva_dawsn_complex +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_fellint_RC "fellint_RC"(double, double) noexcept nogil +cdef void *_export_fellint_RC = _func_fellint_RC +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_cellint_RC "cellint_RC"(double complex, double complex) noexcept nogil +cdef void *_export_cellint_RC = _func_cellint_RC +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_fellint_RD "fellint_RD"(double, double, double) noexcept nogil +cdef void *_export_fellint_RD = _func_fellint_RD +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_cellint_RD "cellint_RD"(double complex, double complex, double complex) noexcept nogil +cdef void *_export_cellint_RD = _func_cellint_RD +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_fellint_RF "fellint_RF"(double, double, double) noexcept nogil +cdef void *_export_fellint_RF = _func_fellint_RF +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_cellint_RF "cellint_RF"(double complex, double complex, double complex) noexcept nogil +cdef void *_export_cellint_RF = _func_cellint_RF +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_fellint_RG "fellint_RG"(double, double, double) noexcept nogil +cdef void *_export_fellint_RG = _func_fellint_RG +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_cellint_RG "cellint_RG"(double complex, double complex, double complex) noexcept nogil +cdef void *_export_cellint_RG = _func_cellint_RG +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_fellint_RJ "fellint_RJ"(double, double, double, double) noexcept nogil +cdef void *_export_fellint_RJ = _func_fellint_RJ +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_cellint_RJ "cellint_RJ"(double complex, double complex, double complex, double complex) noexcept nogil +cdef void *_export_cellint_RJ = _func_cellint_RJ +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_erf "faddeeva_erf"(double complex) noexcept nogil +cdef void *_export_faddeeva_erf = _func_faddeeva_erf +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_erfc_complex "faddeeva_erfc_complex"(double complex) noexcept nogil +cdef void *_export_faddeeva_erfc_complex = _func_faddeeva_erfc_complex +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_faddeeva_erfcx "faddeeva_erfcx"(double) noexcept nogil +cdef void *_export_faddeeva_erfcx = _func_faddeeva_erfcx +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_erfcx_complex "faddeeva_erfcx_complex"(double complex) noexcept nogil +cdef void *_export_faddeeva_erfcx_complex = _func_faddeeva_erfcx_complex +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_faddeeva_erfi "faddeeva_erfi"(double) noexcept nogil +cdef void *_export_faddeeva_erfi = _func_faddeeva_erfi +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_erfi_complex "faddeeva_erfi_complex"(double complex) noexcept nogil +cdef void *_export_faddeeva_erfi_complex = _func_faddeeva_erfi_complex +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_erfinv_float "erfinv_float"(float) noexcept nogil +cdef void *_export_erfinv_float = _func_erfinv_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_erfinv_double "erfinv_double"(double) noexcept nogil +cdef void *_export_erfinv_double = _func_erfinv_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_hyp1f1_double "hyp1f1_double"(double, double, double) noexcept nogil +cdef void *_export_hyp1f1_double = _func_hyp1f1_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_faddeeva_log_ndtr "faddeeva_log_ndtr"(double) noexcept nogil +cdef void *_export_faddeeva_log_ndtr = _func_faddeeva_log_ndtr +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_log_ndtr_complex "faddeeva_log_ndtr_complex"(double complex) noexcept nogil +cdef void *_export_faddeeva_log_ndtr_complex = _func_faddeeva_log_ndtr_complex +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_cdf_float "ncf_cdf_float"(float, float, float, float) noexcept nogil +cdef void *_export_ncf_cdf_float = _func_ncf_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_cdf_double "ncf_cdf_double"(double, double, double, double) noexcept nogil +cdef void *_export_ncf_cdf_double = _func_ncf_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_ncf_ppf_float "ncf_ppf_float"(float, float, float, float) noexcept nogil +cdef void *_export_ncf_ppf_float = _func_ncf_ppf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_ncf_ppf_double "ncf_ppf_double"(double, double, double, double) noexcept nogil +cdef void *_export_ncf_ppf_double = _func_ncf_ppf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_nct_cdf_float "nct_cdf_float"(float, float, float) noexcept nogil +cdef void *_export_nct_cdf_float = _func_nct_cdf_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_nct_cdf_double "nct_cdf_double"(double, double, double) noexcept nogil +cdef void *_export_nct_cdf_double = _func_nct_cdf_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_ndtr "faddeeva_ndtr"(double complex) noexcept nogil +cdef void *_export_faddeeva_ndtr = _func_faddeeva_ndtr +cdef extern from r"_ufuncs_cxx_defs.h": + cdef float _func_powm1_float "powm1_float"(float, float) noexcept nogil +cdef void *_export_powm1_float = _func_powm1_float +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_powm1_double "powm1_double"(double, double) noexcept nogil +cdef void *_export_powm1_double = _func_powm1_double +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_faddeeva_voigt_profile "faddeeva_voigt_profile"(double, double, double) noexcept nogil +cdef void *_export_faddeeva_voigt_profile = _func_faddeeva_voigt_profile +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_faddeeva_w "faddeeva_w"(double complex) noexcept nogil +cdef void *_export_faddeeva_w = _func_faddeeva_w +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double complex _func_wrightomega "wrightomega"(double complex) noexcept nogil +cdef void *_export_wrightomega = _func_wrightomega +cdef extern from r"_ufuncs_cxx_defs.h": + cdef double _func_wrightomega_real "wrightomega_real"(double) noexcept nogil +cdef void *_export_wrightomega_real = _func_wrightomega_real \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h new file mode 100644 index 0000000000000000000000000000000000000000..4e916ce565742ecd949c2c6f9c1a1891e734a96d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h @@ -0,0 +1,161 @@ +#ifndef UFUNCS_PROTO_H +#define UFUNCS_PROTO_H 1 +#include "boost_special_functions.h" +npy_float beta_pdf_float(npy_float, npy_float, npy_float); +npy_double beta_pdf_double(npy_double, npy_double, npy_double); +npy_float beta_ppf_float(npy_float, npy_float, npy_float); +npy_double beta_ppf_double(npy_double, npy_double, npy_double); +npy_float binom_cdf_float(npy_float, npy_float, npy_float); +npy_double binom_cdf_double(npy_double, npy_double, npy_double); +npy_float binom_isf_float(npy_float, npy_float, npy_float); +npy_double binom_isf_double(npy_double, npy_double, npy_double); +npy_float binom_pmf_float(npy_float, npy_float, npy_float); +npy_double binom_pmf_double(npy_double, npy_double, npy_double); +npy_float binom_ppf_float(npy_float, npy_float, npy_float); +npy_double binom_ppf_double(npy_double, npy_double, npy_double); +npy_float binom_sf_float(npy_float, npy_float, npy_float); +npy_double binom_sf_double(npy_double, npy_double, npy_double); +npy_float cauchy_isf_float(npy_float, npy_float, npy_float); +npy_double cauchy_isf_double(npy_double, npy_double, npy_double); +npy_float cauchy_ppf_float(npy_float, npy_float, npy_float); +npy_double cauchy_ppf_double(npy_double, npy_double, npy_double); +npy_float hypergeom_cdf_float(npy_float, npy_float, npy_float, npy_float); +npy_double hypergeom_cdf_double(npy_double, npy_double, npy_double, npy_double); +npy_float hypergeom_mean_float(npy_float, npy_float, npy_float); +npy_double hypergeom_mean_double(npy_double, npy_double, npy_double); +npy_float hypergeom_pmf_float(npy_float, npy_float, npy_float, npy_float); +npy_double hypergeom_pmf_double(npy_double, npy_double, npy_double, npy_double); +npy_float hypergeom_sf_float(npy_float, npy_float, npy_float, npy_float); +npy_double hypergeom_sf_double(npy_double, npy_double, npy_double, npy_double); +npy_float hypergeom_skewness_float(npy_float, npy_float, npy_float); +npy_double hypergeom_skewness_double(npy_double, npy_double, npy_double); +npy_float hypergeom_variance_float(npy_float, npy_float, npy_float); +npy_double hypergeom_variance_double(npy_double, npy_double, npy_double); +npy_float invgauss_isf_float(npy_float, npy_float, npy_float); +npy_double invgauss_isf_double(npy_double, npy_double, npy_double); +npy_float invgauss_ppf_float(npy_float, npy_float, npy_float); +npy_double invgauss_ppf_double(npy_double, npy_double, npy_double); +npy_float landau_cdf_float(npy_float, npy_float, npy_float); +npy_double landau_cdf_double(npy_double, npy_double, npy_double); +npy_float landau_isf_float(npy_float, npy_float, npy_float); +npy_double landau_isf_double(npy_double, npy_double, npy_double); +npy_float landau_pdf_float(npy_float, npy_float, npy_float); +npy_double landau_pdf_double(npy_double, npy_double, npy_double); +npy_float landau_ppf_float(npy_float, npy_float, npy_float); +npy_double landau_ppf_double(npy_double, npy_double, npy_double); +npy_float landau_sf_float(npy_float, npy_float, npy_float); +npy_double landau_sf_double(npy_double, npy_double, npy_double); +npy_float nbinom_cdf_float(npy_float, npy_float, npy_float); +npy_double nbinom_cdf_double(npy_double, npy_double, npy_double); +npy_float nbinom_isf_float(npy_float, npy_float, npy_float); +npy_double nbinom_isf_double(npy_double, npy_double, npy_double); +npy_float nbinom_kurtosis_excess_float(npy_float, npy_float); +npy_double nbinom_kurtosis_excess_double(npy_double, npy_double); +npy_float nbinom_mean_float(npy_float, npy_float); +npy_double nbinom_mean_double(npy_double, npy_double); +npy_float nbinom_pmf_float(npy_float, npy_float, npy_float); +npy_double nbinom_pmf_double(npy_double, npy_double, npy_double); +npy_float nbinom_ppf_float(npy_float, npy_float, npy_float); +npy_double nbinom_ppf_double(npy_double, npy_double, npy_double); +npy_float nbinom_sf_float(npy_float, npy_float, npy_float); +npy_double nbinom_sf_double(npy_double, npy_double, npy_double); +npy_float nbinom_skewness_float(npy_float, npy_float); +npy_double nbinom_skewness_double(npy_double, npy_double); +npy_float nbinom_variance_float(npy_float, npy_float); +npy_double nbinom_variance_double(npy_double, npy_double); +npy_float ncf_isf_float(npy_float, npy_float, npy_float, npy_float); +npy_double ncf_isf_double(npy_double, npy_double, npy_double, npy_double); +npy_float ncf_kurtosis_excess_float(npy_float, npy_float, npy_float); +npy_double ncf_kurtosis_excess_double(npy_double, npy_double, npy_double); +npy_float ncf_mean_float(npy_float, npy_float, npy_float); +npy_double ncf_mean_double(npy_double, npy_double, npy_double); +npy_float ncf_pdf_float(npy_float, npy_float, npy_float, npy_float); +npy_double ncf_pdf_double(npy_double, npy_double, npy_double, npy_double); +npy_float ncf_sf_float(npy_float, npy_float, npy_float, npy_float); +npy_double ncf_sf_double(npy_double, npy_double, npy_double, npy_double); +npy_float ncf_skewness_float(npy_float, npy_float, npy_float); +npy_double ncf_skewness_double(npy_double, npy_double, npy_double); +npy_float ncf_variance_float(npy_float, npy_float, npy_float); +npy_double ncf_variance_double(npy_double, npy_double, npy_double); +npy_float nct_isf_float(npy_float, npy_float, npy_float); +npy_double nct_isf_double(npy_double, npy_double, npy_double); +npy_float nct_kurtosis_excess_float(npy_float, npy_float); +npy_double nct_kurtosis_excess_double(npy_double, npy_double); +npy_float nct_mean_float(npy_float, npy_float); +npy_double nct_mean_double(npy_double, npy_double); +npy_float nct_pdf_float(npy_float, npy_float, npy_float); +npy_double nct_pdf_double(npy_double, npy_double, npy_double); +npy_float nct_ppf_float(npy_float, npy_float, npy_float); +npy_double nct_ppf_double(npy_double, npy_double, npy_double); +npy_float nct_sf_float(npy_float, npy_float, npy_float); +npy_double nct_sf_double(npy_double, npy_double, npy_double); +npy_float nct_skewness_float(npy_float, npy_float); +npy_double nct_skewness_double(npy_double, npy_double); +npy_float nct_variance_float(npy_float, npy_float); +npy_double nct_variance_double(npy_double, npy_double); +npy_float ncx2_cdf_float(npy_float, npy_float, npy_float); +npy_double ncx2_cdf_double(npy_double, npy_double, npy_double); +npy_float ncx2_isf_float(npy_float, npy_float, npy_float); +npy_double ncx2_isf_double(npy_double, npy_double, npy_double); +npy_float ncx2_pdf_float(npy_float, npy_float, npy_float); +npy_double ncx2_pdf_double(npy_double, npy_double, npy_double); +npy_float ncx2_ppf_float(npy_float, npy_float, npy_float); +npy_double ncx2_ppf_double(npy_double, npy_double, npy_double); +npy_float ncx2_sf_float(npy_float, npy_float, npy_float); +npy_double ncx2_sf_double(npy_double, npy_double, npy_double); +npy_float skewnorm_cdf_float(npy_float, npy_float, npy_float, npy_float); +npy_double skewnorm_cdf_double(npy_double, npy_double, npy_double, npy_double); +npy_float skewnorm_isf_float(npy_float, npy_float, npy_float, npy_float); +npy_double skewnorm_isf_double(npy_double, npy_double, npy_double, npy_double); +npy_float skewnorm_ppf_float(npy_float, npy_float, npy_float, npy_float); +npy_double skewnorm_ppf_double(npy_double, npy_double, npy_double, npy_double); +#include "stirling2.h" +npy_double _stirling2_inexact(npy_double, npy_double); +npy_float ibeta_float(npy_float, npy_float, npy_float); +npy_double ibeta_double(npy_double, npy_double, npy_double); +npy_float ibetac_float(npy_float, npy_float, npy_float); +npy_double ibetac_double(npy_double, npy_double, npy_double); +npy_float ibetac_inv_float(npy_float, npy_float, npy_float); +npy_double ibetac_inv_double(npy_double, npy_double, npy_double); +npy_float ibeta_inv_float(npy_float, npy_float, npy_float); +npy_double ibeta_inv_double(npy_double, npy_double, npy_double); +#include "_faddeeva.h" +npy_double faddeeva_dawsn(npy_double); +npy_cdouble faddeeva_dawsn_complex(npy_cdouble); +#include "ellint_carlson_wrap.hh" +npy_double fellint_RC(npy_double, npy_double); +npy_cdouble cellint_RC(npy_cdouble, npy_cdouble); +npy_double fellint_RD(npy_double, npy_double, npy_double); +npy_cdouble cellint_RD(npy_cdouble, npy_cdouble, npy_cdouble); +npy_double fellint_RF(npy_double, npy_double, npy_double); +npy_cdouble cellint_RF(npy_cdouble, npy_cdouble, npy_cdouble); +npy_double fellint_RG(npy_double, npy_double, npy_double); +npy_cdouble cellint_RG(npy_cdouble, npy_cdouble, npy_cdouble); +npy_double fellint_RJ(npy_double, npy_double, npy_double, npy_double); +npy_cdouble cellint_RJ(npy_cdouble, npy_cdouble, npy_cdouble, npy_cdouble); +npy_cdouble faddeeva_erf(npy_cdouble); +npy_cdouble faddeeva_erfc_complex(npy_cdouble); +npy_double faddeeva_erfcx(npy_double); +npy_cdouble faddeeva_erfcx_complex(npy_cdouble); +npy_double faddeeva_erfi(npy_double); +npy_cdouble faddeeva_erfi_complex(npy_cdouble); +npy_float erfinv_float(npy_float); +npy_double erfinv_double(npy_double); +npy_double hyp1f1_double(npy_double, npy_double, npy_double); +npy_double faddeeva_log_ndtr(npy_double); +npy_cdouble faddeeva_log_ndtr_complex(npy_cdouble); +npy_float ncf_cdf_float(npy_float, npy_float, npy_float, npy_float); +npy_double ncf_cdf_double(npy_double, npy_double, npy_double, npy_double); +npy_float ncf_ppf_float(npy_float, npy_float, npy_float, npy_float); +npy_double ncf_ppf_double(npy_double, npy_double, npy_double, npy_double); +npy_float nct_cdf_float(npy_float, npy_float, npy_float); +npy_double nct_cdf_double(npy_double, npy_double, npy_double); +npy_cdouble faddeeva_ndtr(npy_cdouble); +npy_float powm1_float(npy_float, npy_float); +npy_double powm1_double(npy_double, npy_double); +npy_double faddeeva_voigt_profile(npy_double, npy_double, npy_double); +npy_cdouble faddeeva_w(npy_cdouble); +#include "_wright.h" +npy_cdouble wrightomega(npy_cdouble); +npy_double wrightomega_real(npy_double); +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h new file mode 100644 index 0000000000000000000000000000000000000000..86d2349d2b7881b71bfdec2a60a78e2bfc18f9fe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h @@ -0,0 +1,65 @@ +#ifndef UFUNCS_PROTO_H +#define UFUNCS_PROTO_H 1 +#include "_cosine.h" +npy_double cosine_cdf(npy_double); +npy_double cosine_invcdf(npy_double); +#include "xsf_wrappers.h" +npy_double cephes_igam_fac(npy_double, npy_double); +npy_double xsf_kolmogc(npy_double); +npy_double xsf_kolmogci(npy_double); +npy_double xsf_kolmogp(npy_double); +npy_double cephes_lanczos_sum_expg_scaled(npy_double); +npy_double cephes_lgam1p(npy_double); +npy_double cephes_log1pmx(npy_double); +npy_double cephes_smirnovc_wrap(npy_intp, npy_double); +npy_double cephes_smirnovci_wrap(npy_intp, npy_double); +npy_double cephes_smirnovp_wrap(npy_intp, npy_double); +npy_double cephes__struve_asymp_large_z(npy_double, npy_double, npy_intp, npy_double *); +npy_double cephes__struve_bessel_series(npy_double, npy_double, npy_intp, npy_double *); +npy_double cephes__struve_power_series(npy_double, npy_double, npy_intp, npy_double *); +npy_double cephes_bdtr_wrap(npy_double, npy_intp, npy_double); +npy_double cephes_bdtrc_wrap(npy_double, npy_intp, npy_double); +npy_double cephes_bdtri_wrap(npy_double, npy_intp, npy_double); +npy_double xsf_chdtr(npy_double, npy_double); +npy_double xsf_chdtrc(npy_double, npy_double); +npy_double xsf_chdtri(npy_double, npy_double); +npy_double cephes_erf(npy_double); +npy_double cephes_erfc(npy_double); +npy_double cephes_erfcinv(npy_double); +npy_double cephes_exp10(npy_double); +npy_double cephes_exp2(npy_double); +npy_double cephes_expm1(npy_double); +npy_double cephes_expn_wrap(npy_intp, npy_double); +npy_double xsf_fdtr(npy_double, npy_double, npy_double); +npy_double xsf_fdtrc(npy_double, npy_double, npy_double); +npy_double xsf_fdtri(npy_double, npy_double, npy_double); +npy_double xsf_gdtr(npy_double, npy_double, npy_double); +npy_double xsf_gdtrc(npy_double, npy_double, npy_double); +npy_double xsf_gdtrib(npy_double, npy_double, npy_double); +npy_cdouble chyp1f1_wrap(npy_double, npy_double, npy_cdouble); +npy_double special_cyl_bessel_k_int(npy_intp, npy_double); +npy_double xsf_kolmogi(npy_double); +npy_double xsf_kolmogorov(npy_double); +npy_double cephes_log1p(npy_double); +npy_double pmv_wrap(npy_double, npy_double, npy_double); +npy_double cephes_nbdtr_wrap(npy_intp, npy_intp, npy_double); +npy_double cephes_nbdtrc_wrap(npy_intp, npy_intp, npy_double); +npy_double cephes_nbdtri_wrap(npy_intp, npy_intp, npy_double); +npy_double xsf_ndtr(npy_double); +npy_double xsf_ndtri(npy_double); +npy_double xsf_owens_t(npy_double, npy_double); +npy_double xsf_pdtr(npy_double, npy_double); +npy_double xsf_pdtrc(npy_double, npy_double); +npy_double cephes_pdtri_wrap(npy_intp, npy_double); +npy_double cephes_poch(npy_double, npy_double); +npy_double cephes_round(npy_double); +npy_int xsf_cshichi(npy_cdouble, npy_cdouble *, npy_cdouble *); +npy_int xsf_shichi(npy_double, npy_double *, npy_double *); +npy_int xsf_csici(npy_cdouble, npy_cdouble *, npy_cdouble *); +npy_int xsf_sici(npy_double, npy_double *, npy_double *); +npy_double cephes_smirnov_wrap(npy_intp, npy_double); +npy_double cephes_smirnovi_wrap(npy_intp, npy_double); +npy_double cephes_spence(npy_double); +npy_double xsf_tukeylambdacdf(npy_double, npy_double); +npy_double cephes_yn_wrap(npy_intp, npy_double); +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py new file mode 100644 index 0000000000000000000000000000000000000000..5549717d35710d71655e42c836625cde9346bcc3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py @@ -0,0 +1,15 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="special", module="add_newdocs", + private_modules=["_add_newdocs"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..e55695f44d05187d6c83f1ebefd70270af2c2d76 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/basic.py @@ -0,0 +1,87 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.special` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'ai_zeros', + 'assoc_laguerre', + 'bei_zeros', + 'beip_zeros', + 'ber_zeros', + 'bernoulli', + 'berp_zeros', + 'bi_zeros', + 'clpmn', + 'comb', + 'digamma', + 'diric', + 'erf_zeros', + 'euler', + 'factorial', + 'factorial2', + 'factorialk', + 'fresnel_zeros', + 'fresnelc_zeros', + 'fresnels_zeros', + 'gamma', + 'h1vp', + 'h2vp', + 'hankel1', + 'hankel2', + 'iv', + 'ivp', + 'jn_zeros', + 'jnjnp_zeros', + 'jnp_zeros', + 'jnyn_zeros', + 'jv', + 'jvp', + 'kei_zeros', + 'keip_zeros', + 'kelvin_zeros', + 'ker_zeros', + 'kerp_zeros', + 'kv', + 'kvp', + 'lmbda', + 'lpmn', + 'lpn', + 'lqmn', + 'lqn', + 'mathieu_a', + 'mathieu_b', + 'mathieu_even_coef', + 'mathieu_odd_coef', + 'obl_cv_seq', + 'pbdn_seq', + 'pbdv_seq', + 'pbvv_seq', + 'perm', + 'polygamma', + 'pro_cv_seq', + 'psi', + 'riccati_jn', + 'riccati_yn', + 'sinc', + 'y0_zeros', + 'y1_zeros', + 'y1p_zeros', + 'yn_zeros', + 'ynp_zeros', + 'yv', + 'yvp', + 'zeta' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="special", module="basic", + private_modules=["_basic", "_ufuncs"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd new file mode 100644 index 0000000000000000000000000000000000000000..c5d323fbd5f04ec56749505bc24feb080a851506 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd @@ -0,0 +1,259 @@ + +ctypedef fused number_t: + double complex + double + +cpdef number_t spherical_jn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil +cpdef number_t spherical_yn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil +cpdef number_t spherical_in(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil +cpdef number_t spherical_kn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil + +ctypedef fused Dd_number_t: + double complex + double + +ctypedef fused df_number_t: + double + float + +ctypedef fused dfg_number_t: + double + float + long double + +ctypedef fused dlp_number_t: + double + long + Py_ssize_t + +cpdef double voigt_profile(double x0, double x1, double x2) noexcept nogil +cpdef double agm(double x0, double x1) noexcept nogil +cdef void airy(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil +cdef void airye(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil +cpdef double bdtr(double x0, dlp_number_t x1, double x2) noexcept nogil +cpdef double bdtrc(double x0, dlp_number_t x1, double x2) noexcept nogil +cpdef double bdtri(double x0, dlp_number_t x1, double x2) noexcept nogil +cpdef double bdtrik(double x0, double x1, double x2) noexcept nogil +cpdef double bdtrin(double x0, double x1, double x2) noexcept nogil +cpdef double bei(double x0) noexcept nogil +cpdef double beip(double x0) noexcept nogil +cpdef double ber(double x0) noexcept nogil +cpdef double berp(double x0) noexcept nogil +cpdef double besselpoly(double x0, double x1, double x2) noexcept nogil +cpdef double beta(double x0, double x1) noexcept nogil +cpdef df_number_t betainc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil +cpdef df_number_t betaincc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil +cpdef df_number_t betaincinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil +cpdef df_number_t betainccinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil +cpdef double betaln(double x0, double x1) noexcept nogil +cpdef double binom(double x0, double x1) noexcept nogil +cpdef double boxcox(double x0, double x1) noexcept nogil +cpdef double boxcox1p(double x0, double x1) noexcept nogil +cpdef double btdtria(double x0, double x1, double x2) noexcept nogil +cpdef double btdtrib(double x0, double x1, double x2) noexcept nogil +cpdef double cbrt(double x0) noexcept nogil +cpdef double chdtr(double x0, double x1) noexcept nogil +cpdef double chdtrc(double x0, double x1) noexcept nogil +cpdef double chdtri(double x0, double x1) noexcept nogil +cpdef double chdtriv(double x0, double x1) noexcept nogil +cpdef double chndtr(double x0, double x1, double x2) noexcept nogil +cpdef double chndtridf(double x0, double x1, double x2) noexcept nogil +cpdef double chndtrinc(double x0, double x1, double x2) noexcept nogil +cpdef double chndtrix(double x0, double x1, double x2) noexcept nogil +cpdef double cosdg(double x0) noexcept nogil +cpdef double cosm1(double x0) noexcept nogil +cpdef double cotdg(double x0) noexcept nogil +cpdef Dd_number_t dawsn(Dd_number_t x0) noexcept nogil +cpdef double ellipe(double x0) noexcept nogil +cpdef double ellipeinc(double x0, double x1) noexcept nogil +cdef void ellipj(double x0, double x1, double *y0, double *y1, double *y2, double *y3) noexcept nogil +cpdef double ellipkinc(double x0, double x1) noexcept nogil +cpdef double ellipkm1(double x0) noexcept nogil +cpdef double ellipk(double x0) noexcept nogil +cpdef Dd_number_t elliprc(Dd_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t elliprd(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil +cpdef Dd_number_t elliprf(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil +cpdef Dd_number_t elliprg(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil +cpdef Dd_number_t elliprj(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2, Dd_number_t x3) noexcept nogil +cpdef double entr(double x0) noexcept nogil +cpdef Dd_number_t erf(Dd_number_t x0) noexcept nogil +cpdef Dd_number_t erfc(Dd_number_t x0) noexcept nogil +cpdef Dd_number_t erfcx(Dd_number_t x0) noexcept nogil +cpdef Dd_number_t erfi(Dd_number_t x0) noexcept nogil +cpdef df_number_t erfinv(df_number_t x0) noexcept nogil +cpdef double erfcinv(double x0) noexcept nogil +cpdef Dd_number_t eval_chebyc(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_chebys(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_gegenbauer(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil +cpdef Dd_number_t eval_genlaguerre(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil +cpdef double eval_hermite(Py_ssize_t x0, double x1) noexcept nogil +cpdef double eval_hermitenorm(Py_ssize_t x0, double x1) noexcept nogil +cpdef Dd_number_t eval_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil +cpdef Dd_number_t eval_laguerre(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_sh_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_sh_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t eval_sh_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil +cpdef Dd_number_t eval_sh_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t exp1(Dd_number_t x0) noexcept nogil +cpdef double exp10(double x0) noexcept nogil +cpdef double exp2(double x0) noexcept nogil +cpdef Dd_number_t expi(Dd_number_t x0) noexcept nogil +cpdef dfg_number_t expit(dfg_number_t x0) noexcept nogil +cpdef Dd_number_t expm1(Dd_number_t x0) noexcept nogil +cpdef double expn(dlp_number_t x0, double x1) noexcept nogil +cpdef double exprel(double x0) noexcept nogil +cpdef double fdtr(double x0, double x1, double x2) noexcept nogil +cpdef double fdtrc(double x0, double x1, double x2) noexcept nogil +cpdef double fdtri(double x0, double x1, double x2) noexcept nogil +cpdef double fdtridfd(double x0, double x1, double x2) noexcept nogil +cdef void fresnel(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil +cpdef Dd_number_t gamma(Dd_number_t x0) noexcept nogil +cpdef double gammainc(double x0, double x1) noexcept nogil +cpdef double gammaincc(double x0, double x1) noexcept nogil +cpdef double gammainccinv(double x0, double x1) noexcept nogil +cpdef double gammaincinv(double x0, double x1) noexcept nogil +cpdef double gammaln(double x0) noexcept nogil +cpdef double gammasgn(double x0) noexcept nogil +cpdef double gdtr(double x0, double x1, double x2) noexcept nogil +cpdef double gdtrc(double x0, double x1, double x2) noexcept nogil +cpdef double gdtria(double x0, double x1, double x2) noexcept nogil +cpdef double gdtrib(double x0, double x1, double x2) noexcept nogil +cpdef double gdtrix(double x0, double x1, double x2) noexcept nogil +cpdef double complex hankel1(double x0, double complex x1) noexcept nogil +cpdef double complex hankel1e(double x0, double complex x1) noexcept nogil +cpdef double complex hankel2(double x0, double complex x1) noexcept nogil +cpdef double complex hankel2e(double x0, double complex x1) noexcept nogil +cpdef double huber(double x0, double x1) noexcept nogil +cpdef Dd_number_t hyp0f1(double x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t hyp1f1(double x0, double x1, Dd_number_t x2) noexcept nogil +cpdef Dd_number_t hyp2f1(double x0, double x1, double x2, Dd_number_t x3) noexcept nogil +cpdef double hyperu(double x0, double x1, double x2) noexcept nogil +cpdef double i0(double x0) noexcept nogil +cpdef double i0e(double x0) noexcept nogil +cpdef double i1(double x0) noexcept nogil +cpdef double i1e(double x0) noexcept nogil +cpdef double inv_boxcox(double x0, double x1) noexcept nogil +cpdef double inv_boxcox1p(double x0, double x1) noexcept nogil +cdef void it2i0k0(double x0, double *y0, double *y1) noexcept nogil +cdef void it2j0y0(double x0, double *y0, double *y1) noexcept nogil +cpdef double it2struve0(double x0) noexcept nogil +cdef void itairy(double x0, double *y0, double *y1, double *y2, double *y3) noexcept nogil +cdef void iti0k0(double x0, double *y0, double *y1) noexcept nogil +cdef void itj0y0(double x0, double *y0, double *y1) noexcept nogil +cpdef double itmodstruve0(double x0) noexcept nogil +cpdef double itstruve0(double x0) noexcept nogil +cpdef Dd_number_t iv(double x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t ive(double x0, Dd_number_t x1) noexcept nogil +cpdef double j0(double x0) noexcept nogil +cpdef double j1(double x0) noexcept nogil +cpdef Dd_number_t jv(double x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t jve(double x0, Dd_number_t x1) noexcept nogil +cpdef double k0(double x0) noexcept nogil +cpdef double k0e(double x0) noexcept nogil +cpdef double k1(double x0) noexcept nogil +cpdef double k1e(double x0) noexcept nogil +cpdef double kei(double x0) noexcept nogil +cpdef double keip(double x0) noexcept nogil +cdef void kelvin(double x0, double complex *y0, double complex *y1, double complex *y2, double complex *y3) noexcept nogil +cpdef double ker(double x0) noexcept nogil +cpdef double kerp(double x0) noexcept nogil +cpdef double kl_div(double x0, double x1) noexcept nogil +cpdef double kn(dlp_number_t x0, double x1) noexcept nogil +cpdef double kolmogi(double x0) noexcept nogil +cpdef double kolmogorov(double x0) noexcept nogil +cpdef Dd_number_t kv(double x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t kve(double x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t log1p(Dd_number_t x0) noexcept nogil +cpdef dfg_number_t log_expit(dfg_number_t x0) noexcept nogil +cpdef Dd_number_t log_ndtr(Dd_number_t x0) noexcept nogil +cpdef Dd_number_t loggamma(Dd_number_t x0) noexcept nogil +cpdef dfg_number_t logit(dfg_number_t x0) noexcept nogil +cpdef double lpmv(double x0, double x1, double x2) noexcept nogil +cpdef double mathieu_a(double x0, double x1) noexcept nogil +cpdef double mathieu_b(double x0, double x1) noexcept nogil +cdef void mathieu_cem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil +cdef void mathieu_modcem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil +cdef void mathieu_modcem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil +cdef void mathieu_modsem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil +cdef void mathieu_modsem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil +cdef void mathieu_sem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil +cdef void modfresnelm(double x0, double complex *y0, double complex *y1) noexcept nogil +cdef void modfresnelp(double x0, double complex *y0, double complex *y1) noexcept nogil +cpdef double modstruve(double x0, double x1) noexcept nogil +cpdef double nbdtr(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil +cpdef double nbdtrc(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil +cpdef double nbdtri(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil +cpdef double nbdtrik(double x0, double x1, double x2) noexcept nogil +cpdef double nbdtrin(double x0, double x1, double x2) noexcept nogil +cpdef df_number_t ncfdtr(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil +cpdef df_number_t ncfdtri(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil +cpdef double ncfdtridfd(double x0, double x1, double x2, double x3) noexcept nogil +cpdef double ncfdtridfn(double x0, double x1, double x2, double x3) noexcept nogil +cpdef double ncfdtrinc(double x0, double x1, double x2, double x3) noexcept nogil +cpdef df_number_t nctdtr(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil +cpdef double nctdtridf(double x0, double x1, double x2) noexcept nogil +cpdef double nctdtrinc(double x0, double x1, double x2) noexcept nogil +cpdef double nctdtrit(double x0, double x1, double x2) noexcept nogil +cpdef Dd_number_t ndtr(Dd_number_t x0) noexcept nogil +cpdef double ndtri(double x0) noexcept nogil +cpdef double nrdtrimn(double x0, double x1, double x2) noexcept nogil +cpdef double nrdtrisd(double x0, double x1, double x2) noexcept nogil +cdef void obl_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil +cdef void obl_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil +cpdef double obl_cv(double x0, double x1, double x2) noexcept nogil +cdef void obl_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil +cdef void obl_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil +cdef void obl_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil +cdef void obl_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil +cpdef double owens_t(double x0, double x1) noexcept nogil +cdef void pbdv(double x0, double x1, double *y0, double *y1) noexcept nogil +cdef void pbvv(double x0, double x1, double *y0, double *y1) noexcept nogil +cdef void pbwa(double x0, double x1, double *y0, double *y1) noexcept nogil +cpdef double pdtr(double x0, double x1) noexcept nogil +cpdef double pdtrc(double x0, double x1) noexcept nogil +cpdef double pdtri(dlp_number_t x0, double x1) noexcept nogil +cpdef double pdtrik(double x0, double x1) noexcept nogil +cpdef double poch(double x0, double x1) noexcept nogil +cpdef df_number_t powm1(df_number_t x0, df_number_t x1) noexcept nogil +cdef void pro_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil +cdef void pro_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil +cpdef double pro_cv(double x0, double x1, double x2) noexcept nogil +cdef void pro_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil +cdef void pro_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil +cdef void pro_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil +cdef void pro_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil +cpdef double pseudo_huber(double x0, double x1) noexcept nogil +cpdef Dd_number_t psi(Dd_number_t x0) noexcept nogil +cpdef double radian(double x0, double x1, double x2) noexcept nogil +cpdef double rel_entr(double x0, double x1) noexcept nogil +cpdef Dd_number_t rgamma(Dd_number_t x0) noexcept nogil +cpdef double round(double x0) noexcept nogil +cdef void shichi(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil +cdef void sici(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil +cpdef double sindg(double x0) noexcept nogil +cpdef double smirnov(dlp_number_t x0, double x1) noexcept nogil +cpdef double smirnovi(dlp_number_t x0, double x1) noexcept nogil +cpdef Dd_number_t spence(Dd_number_t x0) noexcept nogil +cpdef double complex sph_harm(dlp_number_t x0, dlp_number_t x1, double x2, double x3) noexcept nogil +cpdef double stdtr(double x0, double x1) noexcept nogil +cpdef double stdtridf(double x0, double x1) noexcept nogil +cpdef double stdtrit(double x0, double x1) noexcept nogil +cpdef double struve(double x0, double x1) noexcept nogil +cpdef double tandg(double x0) noexcept nogil +cpdef double tklmbda(double x0, double x1) noexcept nogil +cpdef double complex wofz(double complex x0) noexcept nogil +cpdef Dd_number_t wrightomega(Dd_number_t x0) noexcept nogil +cpdef Dd_number_t xlog1py(Dd_number_t x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t xlogy(Dd_number_t x0, Dd_number_t x1) noexcept nogil +cpdef double y0(double x0) noexcept nogil +cpdef double y1(double x0) noexcept nogil +cpdef double yn(dlp_number_t x0, double x1) noexcept nogil +cpdef Dd_number_t yv(double x0, Dd_number_t x1) noexcept nogil +cpdef Dd_number_t yve(double x0, Dd_number_t x1) noexcept nogil +cpdef double zetac(double x0) noexcept nogil +cpdef double wright_bessel(double x0, double x1, double x2) noexcept nogil +cpdef double log_wright_bessel(double x0, double x1, double x2) noexcept nogil +cpdef double ndtri_exp(double x0) noexcept nogil diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi new file mode 100644 index 0000000000000000000000000000000000000000..024e962b10df8892631eaad20223f7fc8378ea83 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name) -> Any: ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so new file mode 100644 index 0000000000000000000000000000000000000000..84e37bedbdfcc83bb65efc5d7f1961f2b749ebeb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py new file mode 100644 index 0000000000000000000000000000000000000000..0b13a08a96cb683d72a4a00d6962446e1779c88a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py @@ -0,0 +1,45 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.special` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys', + 'jacobi', 'laguerre', 'genlaguerre', 'hermite', + 'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt', + 'sh_chebyu', 'sh_jacobi'] + +# Correspondence between new and old names of root functions +_rootfuns_map = {'roots_legendre': 'p_roots', + 'roots_chebyt': 't_roots', + 'roots_chebyu': 'u_roots', + 'roots_chebyc': 'c_roots', + 'roots_chebys': 's_roots', + 'roots_jacobi': 'j_roots', + 'roots_laguerre': 'l_roots', + 'roots_genlaguerre': 'la_roots', + 'roots_hermite': 'h_roots', + 'roots_hermitenorm': 'he_roots', + 'roots_gegenbauer': 'cg_roots', + 'roots_sh_legendre': 'ps_roots', + 'roots_sh_chebyt': 'ts_roots', + 'roots_sh_chebyu': 'us_roots', + 'roots_sh_jacobi': 'js_roots'} + + +__all__ = _polyfuns + list(_rootfuns_map.keys()) + [ # noqa: F822 + 'airy', 'p_roots', 't_roots', 'u_roots', 'c_roots', 's_roots', + 'j_roots', 'l_roots', 'la_roots', 'h_roots', 'he_roots', 'cg_roots', + 'ps_roots', 'ts_roots', 'us_roots', 'js_roots' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="special", module="orthogonal", + private_modules=["_orthogonal"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py new file mode 100644 index 0000000000000000000000000000000000000000..00ff73756acd4219a4ba94eb089bce7d4c32266d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.special` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'SpecialFunctionWarning', + 'SpecialFunctionError' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="special", module="sf_error", + private_modules=["_sf_error"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/specfun.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/specfun.py new file mode 100644 index 0000000000000000000000000000000000000000..9fca00415a6406b8cdf41a42b6fbf991cea1f53f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/specfun.py @@ -0,0 +1,24 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.special` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +# ruff: noqa: F822 +__all__ = [ + 'clpmn', + 'lpmn', + 'lpn', + 'lqmn', + 'pbdv' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="special", module="specfun", + private_modules=["_basic", "_specfun"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e58487aaa547483c9f2531ac4efc2ad5e4795c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.special` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = ['multigammaln'] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="special", module="spfun_stats", + private_modules=["_spfun_stats"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx new file mode 100644 index 0000000000000000000000000000000000000000..ca3bf2167f0f7726f8b0acb60ed8b8798a518d79 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +#cython: language_level=3 +#cython: boundscheck=False +#cython: wraparound=False + +from scipy.special.cython_special cimport beta, gamma + +cpdef double cy_beta(double a, double b): + return beta(a, b) + +cpdef double complex cy_gamma(double complex z): + return gamma(z) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..2a5e1535a16f840f31ca0207513e7c060767ea12 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build @@ -0,0 +1,25 @@ +project('random-build-examples', 'c', 'cpp', 'cython') + +fs = import('fs') + +py3 = import('python').find_installation(pure: false) + +cy = meson.get_compiler('cython') + +if not cy.version().version_compare('>=3.0.8') + error('tests requires Cython >= 3.0.8') +endif + +py3.extension_module( + 'extending', + 'extending.pyx', + install: false, +) + +extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx') +py3.extension_module( + 'extending_cpp', + extending_cpp, + install: false, + override_options : ['cython_language=cpp'] +) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..67bb83f1f1682e5eb83cc66f052ea51e3caf8757 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py @@ -0,0 +1,4682 @@ +# this program corresponds to special.py + +### Means test is not done yet +# E Means test is giving error (E) +# F Means test is failing (F) +# EF Means test is giving error and Failing +#! Means test is segfaulting +# 8 Means test runs forever + +### test_besselpoly +### test_mathieu_a +### test_mathieu_even_coef +### test_mathieu_odd_coef +### test_modfresnelp +### test_modfresnelm +# test_pbdv_seq +### test_pbvv_seq +### test_sph_harm + +import functools +import itertools +import operator +import platform +import sys + +import numpy as np +from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, + log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, double, + array_equal) + +import pytest +from pytest import raises as assert_raises +from numpy.testing import (assert_equal, assert_almost_equal, + assert_array_equal, assert_array_almost_equal, assert_approx_equal, + assert_, assert_allclose, assert_array_almost_equal_nulp, + suppress_warnings) + +from scipy import special +import scipy.special._ufuncs as cephes +from scipy.special import ellipe, ellipk, ellipkm1 +from scipy.special import elliprc, elliprd, elliprf, elliprg, elliprj +from scipy.special import softplus +from scipy.special import mathieu_odd_coef, mathieu_even_coef, stirling2 +from scipy.special import lpn, lpmn, clpmn +from scipy._lib._util import np_long, np_ulong +from scipy._lib._array_api import xp_assert_close, xp_assert_equal, SCIPY_ARRAY_API + +from scipy.special._basic import ( + _FACTORIALK_LIMITS_64BITS, _FACTORIALK_LIMITS_32BITS, _is_subdtype +) +from scipy.special._testutils import with_special_errors, \ + assert_func_equal, FuncData + +import math + + +native_int = np.int32 if ( + sys.platform == 'win32' + or platform.architecture()[0] == "32bit" +) else np.int64 + + +class TestCephes: + def test_airy(self): + cephes.airy(0) + + def test_airye(self): + cephes.airye(0) + + def test_binom(self): + n = np.array([0.264, 4, 5.2, 17]) + k = np.array([2, 0.4, 7, 3.3]) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, + -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], + [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], + [136, 3.5252179590758828, 19448, 1024.5526916174495]]) + assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) + + # Test branches in implementation + rng = np.random.RandomState(1234) + n = np.r_[np.arange(-7, 30), 1000*rng.rand(30) - 500] + k = np.arange(0, 102) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + + assert_func_equal(cephes.binom, + cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), + nk, + atol=1e-10, rtol=1e-10) + + def test_binom_2(self): + # Test branches in implementation + np.random.seed(1234) + n = np.r_[np.logspace(1, 300, 20)] + k = np.arange(0, 102) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + + assert_func_equal(cephes.binom, + cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), + nk, + atol=1e-10, rtol=1e-10) + + def test_binom_exact(self): + @np.vectorize + def binom_int(n, k): + n = int(n) + k = int(k) + num = 1 + den = 1 + for i in range(1, k+1): + num *= i + n - k + den *= i + return float(num/den) + + np.random.seed(1234) + n = np.arange(1, 15) + k = np.arange(0, 15) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + nk = nk[nk[:,0] >= nk[:,1]] + assert_func_equal(cephes.binom, + binom_int(nk[:,0], nk[:,1]), + nk, + atol=0, rtol=0) + + def test_binom_nooverflow_8346(self): + # Test (binom(n, k) doesn't overflow prematurely */ + dataset = [ + (1000, 500, 2.70288240945436551e+299), + (1002, 501, 1.08007396880791225e+300), + (1004, 502, 4.31599279169058121e+300), + (1006, 503, 1.72468101616263781e+301), + (1008, 504, 6.89188009236419153e+301), + (1010, 505, 2.75402257948335448e+302), + (1012, 506, 1.10052048531923757e+303), + (1014, 507, 4.39774063758732849e+303), + (1016, 508, 1.75736486108312519e+304), + (1018, 509, 7.02255427788423734e+304), + (1020, 510, 2.80626776829962255e+305), + (1022, 511, 1.12140876377061240e+306), + (1024, 512, 4.48125455209897109e+306), + (1026, 513, 1.79075474304149900e+307), + (1028, 514, 7.15605105487789676e+307) + ] + dataset = np.asarray(dataset) + FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() + + def test_bdtr(self): + assert_equal(cephes.bdtr(1,1,0.5),1.0) + + def test_bdtri(self): + assert_equal(cephes.bdtri(1,3,0.5),0.5) + + def test_bdtrc(self): + assert_equal(cephes.bdtrc(1,3,0.5),0.5) + + def test_bdtrin(self): + assert_equal(cephes.bdtrin(1,0,1),5.0) + + def test_bdtrik(self): + cephes.bdtrik(1,3,0.5) + + def test_bei(self): + assert_equal(cephes.bei(0),0.0) + + def test_beip(self): + assert_equal(cephes.beip(0),0.0) + + def test_ber(self): + assert_equal(cephes.ber(0),1.0) + + def test_berp(self): + assert_equal(cephes.berp(0),0.0) + + def test_besselpoly(self): + assert_equal(cephes.besselpoly(0,0,0),1.0) + + def test_btdtria(self): + assert_equal(cephes.btdtria(1,1,1),5.0) + + def test_btdtrib(self): + assert_equal(cephes.btdtrib(1,1,1),5.0) + + def test_cbrt(self): + assert_approx_equal(cephes.cbrt(1),1.0) + + def test_chdtr(self): + assert_equal(cephes.chdtr(1,0),0.0) + + def test_chdtrc(self): + assert_equal(cephes.chdtrc(1,0),1.0) + + def test_chdtri(self): + assert_equal(cephes.chdtri(1,1),0.0) + + def test_chdtriv(self): + assert_equal(cephes.chdtriv(0,0),5.0) + + def test_chndtr(self): + assert_equal(cephes.chndtr(0,1,0),0.0) + + # Each row holds (x, nu, lam, expected_value) + # These values were computed using Wolfram Alpha with + # CDF[NoncentralChiSquareDistribution[nu, lam], x] + values = np.array([ + [25.00, 20.0, 400, 4.1210655112396197139e-57], + [25.00, 8.00, 250, 2.3988026526832425878e-29], + [0.001, 8.00, 40., 5.3761806201366039084e-24], + [0.010, 8.00, 40., 5.45396231055999457039e-20], + [20.00, 2.00, 107, 1.39390743555819597802e-9], + [22.50, 2.00, 107, 7.11803307138105870671e-9], + [25.00, 2.00, 107, 3.11041244829864897313e-8], + [3.000, 2.00, 1.0, 0.62064365321954362734], + [350.0, 300., 10., 0.93880128006276407710], + [100.0, 13.5, 10., 0.99999999650104210949], + [700.0, 20.0, 400, 0.99999999925680650105], + [150.0, 13.5, 10., 0.99999999999999983046], + [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 + ]) + cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) + assert_allclose(cdf, values[:, 3], rtol=1e-12) + + assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) + assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) + assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) + assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) + assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) + + def test_chndtridf(self): + assert_equal(cephes.chndtridf(0,0,1),5.0) + + def test_chndtrinc(self): + assert_equal(cephes.chndtrinc(0,1,0),5.0) + + def test_chndtrix(self): + assert_equal(cephes.chndtrix(0,1,0),0.0) + + def test_cosdg(self): + assert_equal(cephes.cosdg(0),1.0) + + def test_cosm1(self): + assert_equal(cephes.cosm1(0),0.0) + + def test_cotdg(self): + assert_almost_equal(cephes.cotdg(45),1.0) + + def test_dawsn(self): + assert_equal(cephes.dawsn(0),0.0) + assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) + + def test_diric(self): + # Test behavior near multiples of 2pi. Regression test for issue + # described in gh-4001. + n_odd = [1, 5, 25] + x = np.array(2*np.pi + 5e-5).astype(np.float32) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) + x = np.array(2*np.pi + 1e-9).astype(np.float64) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) + x = np.array(2*np.pi + 1e-15).astype(np.float64) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) + if hasattr(np, 'float128'): + # No float128 available in 32-bit numpy + x = np.array(2*np.pi + 1e-12).astype(np.float128) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) + + n_even = [2, 4, 24] + x = np.array(2*np.pi + 1e-9).astype(np.float64) + assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) + + # Test at some values not near a multiple of pi + x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) + octave_result = [0.872677996249965, 0.539344662916632, + 0.127322003750035, -0.206011329583298] + assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) + + def test_diric_broadcasting(self): + x = np.arange(5) + n = np.array([1, 3, 7]) + assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) + + def test_ellipe(self): + assert_equal(cephes.ellipe(1),1.0) + + def test_ellipeinc(self): + assert_equal(cephes.ellipeinc(0,1),0.0) + + def test_ellipj(self): + cephes.ellipj(0,1) + + def test_ellipk(self): + assert_allclose(ellipk(0), pi/2) + + def test_ellipkinc(self): + assert_equal(cephes.ellipkinc(0,0),0.0) + + def test_erf(self): + assert_equal(cephes.erf(0), 0.0) + + def test_erf_symmetry(self): + x = 5.905732037710919 + assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) + + def test_erfc(self): + assert_equal(cephes.erfc(0), 1.0) + + def test_exp10(self): + assert_approx_equal(cephes.exp10(2),100.0) + + def test_exp2(self): + assert_equal(cephes.exp2(2),4.0) + + def test_expm1(self): + assert_equal(cephes.expm1(0),0.0) + assert_equal(cephes.expm1(np.inf), np.inf) + assert_equal(cephes.expm1(-np.inf), -1) + assert_equal(cephes.expm1(np.nan), np.nan) + + def test_expm1_complex(self): + expm1 = cephes.expm1 + assert_equal(expm1(0 + 0j), 0 + 0j) + assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) + assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) + assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) + assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) + assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) + assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) + assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) + assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) + assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) + assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) + + @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') + def test_expm1_complex_hard(self): + # The real part of this function is difficult to evaluate when + # z.real = -log(cos(z.imag)). + y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) + x = -np.log(np.cos(y)) + z = x + 1j*y + + # evaluate using mpmath.expm1 with dps=1000 + expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, + 2.4289354732893695e-18+0.20271003550867248j, + 4.5235500262585768e-17+0.30933624960962319j, + 7.8234305217489006e-17-3.3805150062465863j, + -1.3685191953697676e-16-225.95084645419513j, + 8.7175620481291045e-17+2.2371609442247422j]) + found = cephes.expm1(z) + # this passes. + assert_array_almost_equal_nulp(found.imag, expected.imag, 3) + # this fails. + assert_array_almost_equal_nulp(found.real, expected.real, 20) + + def test_fdtr(self): + assert_equal(cephes.fdtr(1, 1, 0), 0.0) + # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] + assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, + rtol=1e-12) + + def test_fdtrc(self): + assert_equal(cephes.fdtrc(1, 1, 0), 1.0) + # Computed using Wolfram Alpha: + # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] + assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, + rtol=1e-12) + + def test_fdtri(self): + assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), + array([0.9937365, 1.00630298]), rtol=1e-6) + # From Wolfram Alpha: + # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... + p = 0.8756751669632105666874 + assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) + + @pytest.mark.xfail(reason='Returns nan on i686.') + def test_fdtri_mysterious_failure(self): + assert_allclose(cephes.fdtri(1, 1, 0.5), 1) + + def test_fdtridfd(self): + assert_equal(cephes.fdtridfd(1,0,0),5.0) + + def test_fresnel(self): + assert_equal(cephes.fresnel(0),(0.0,0.0)) + + def test_gamma(self): + assert_equal(cephes.gamma(5),24.0) + + def test_gammainccinv(self): + assert_equal(cephes.gammainccinv(5,1),0.0) + + def test_gammaln(self): + cephes.gammaln(10) + + def test_gammasgn(self): + vals = np.array( + [-np.inf, -4, -3.5, -2.3, -0.0, 0.0, 1, 4.2, np.inf], np.float64 + ) + reference = np.array( + [np.nan, np.nan, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0], np.float64 + ) + assert_array_equal(cephes.gammasgn(vals), reference) + + def test_gdtr(self): + assert_equal(cephes.gdtr(1,1,0),0.0) + + def test_gdtr_inf(self): + assert_equal(cephes.gdtr(1,1,np.inf),1.0) + + def test_gdtrc(self): + assert_equal(cephes.gdtrc(1,1,0),1.0) + + def test_gdtria(self): + assert_equal(cephes.gdtria(0,1,1),0.0) + + def test_gdtrib(self): + cephes.gdtrib(1,0,1) + # assert_equal(cephes.gdtrib(1,0,1),5.0) + + def test_gdtrix(self): + cephes.gdtrix(1,1,.1) + + def test_hankel1(self): + cephes.hankel1(1,1) + + def test_hankel1e(self): + cephes.hankel1e(1,1) + + def test_hankel2(self): + cephes.hankel2(1,1) + + def test_hankel2e(self): + cephes.hankel2e(1,1) + + def test_hyp1f1(self): + assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) + assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) + cephes.hyp1f1(1,1,1) + + def test_hyp2f1(self): + assert_equal(cephes.hyp2f1(1,1,1,0),1.0) + + def test_i0(self): + assert_equal(cephes.i0(0),1.0) + + def test_i0e(self): + assert_equal(cephes.i0e(0),1.0) + + def test_i1(self): + assert_equal(cephes.i1(0),0.0) + + def test_i1e(self): + assert_equal(cephes.i1e(0),0.0) + + def test_it2i0k0(self): + cephes.it2i0k0(1) + + def test_it2j0y0(self): + cephes.it2j0y0(1) + + def test_it2struve0(self): + cephes.it2struve0(1) + + def test_itairy(self): + cephes.itairy(1) + + def test_iti0k0(self): + assert_equal(cephes.iti0k0(0),(0.0,0.0)) + + def test_itj0y0(self): + assert_equal(cephes.itj0y0(0),(0.0,0.0)) + + def test_itmodstruve0(self): + assert_equal(cephes.itmodstruve0(0),0.0) + + def test_itstruve0(self): + assert_equal(cephes.itstruve0(0),0.0) + + def test_iv(self): + assert_equal(cephes.iv(1,0),0.0) + + def test_ive(self): + assert_equal(cephes.ive(1,0),0.0) + + def test_j0(self): + assert_equal(cephes.j0(0),1.0) + + def test_j1(self): + assert_equal(cephes.j1(0),0.0) + + def test_jn(self): + assert_equal(cephes.jn(0,0),1.0) + + def test_jv(self): + assert_equal(cephes.jv(0,0),1.0) + + def test_jve(self): + assert_equal(cephes.jve(0,0),1.0) + + def test_k0(self): + cephes.k0(2) + + def test_k0e(self): + cephes.k0e(2) + + def test_k1(self): + cephes.k1(2) + + def test_k1e(self): + cephes.k1e(2) + + def test_kei(self): + cephes.kei(2) + + def test_keip(self): + assert_equal(cephes.keip(0),0.0) + + def test_ker(self): + cephes.ker(2) + + def test_kerp(self): + cephes.kerp(2) + + def test_kelvin(self): + cephes.kelvin(2) + + def test_kn(self): + cephes.kn(1,1) + + def test_kolmogi(self): + assert_equal(cephes.kolmogi(1),0.0) + assert_(np.isnan(cephes.kolmogi(np.nan))) + + def test_kolmogorov(self): + assert_equal(cephes.kolmogorov(0), 1.0) + + def test_kolmogp(self): + assert_equal(cephes._kolmogp(0), -0.0) + + def test_kolmogc(self): + assert_equal(cephes._kolmogc(0), 0.0) + + def test_kolmogci(self): + assert_equal(cephes._kolmogci(0), 0.0) + assert_(np.isnan(cephes._kolmogci(np.nan))) + + def test_kv(self): + cephes.kv(1,1) + + def test_kve(self): + cephes.kve(1,1) + + def test_log1p(self): + log1p = cephes.log1p + assert_equal(log1p(0), 0.0) + assert_equal(log1p(-1), -np.inf) + assert_equal(log1p(-2), np.nan) + assert_equal(log1p(np.inf), np.inf) + + def test_log1p_complex(self): + log1p = cephes.log1p + c = complex + assert_equal(log1p(0 + 0j), 0 + 0j) + assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) + assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) + assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) + assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) + assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) + assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) + assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) + assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) + assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) + assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) + assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) + + def test_lpmv(self): + assert_equal(cephes.lpmv(0,0,1),1.0) + + def test_mathieu_a(self): + assert_equal(cephes.mathieu_a(1,0),1.0) + + def test_mathieu_b(self): + assert_equal(cephes.mathieu_b(1,0),1.0) + + def test_mathieu_cem(self): + assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) + + # Test AMS 20.2.27 + @np.vectorize + def ce_smallq(m, q, z): + z *= np.pi/180 + if m == 0: + # + O(q^2) + return 2**(-0.5) * (1 - .5*q*cos(2*z)) + elif m == 1: + # + O(q^2) + return cos(z) - q/8 * cos(3*z) + elif m == 2: + # + O(q^2) + return cos(2*z) - q*(cos(4*z)/12 - 1/4) + else: + # + O(q^2) + return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) + m = np.arange(0, 100) + q = np.r_[0, np.logspace(-30, -9, 10)] + assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], + ce_smallq(m[:,None], q[None,:], 0.123), + rtol=1e-14, atol=0) + + def test_mathieu_sem(self): + assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) + + # Test AMS 20.2.27 + @np.vectorize + def se_smallq(m, q, z): + z *= np.pi/180 + if m == 1: + # + O(q^2) + return sin(z) - q/8 * sin(3*z) + elif m == 2: + # + O(q^2) + return sin(2*z) - q*sin(4*z)/12 + else: + # + O(q^2) + return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) + m = np.arange(1, 100) + q = np.r_[0, np.logspace(-30, -9, 10)] + assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], + se_smallq(m[:,None], q[None,:], 0.123), + rtol=1e-14, atol=0) + + def test_mathieu_modcem1(self): + assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) + + def test_mathieu_modcem2(self): + cephes.mathieu_modcem2(1,1,1) + + # Test reflection relation AMS 20.6.19 + m = np.arange(0, 4)[:,None,None] + q = np.r_[np.logspace(-2, 2, 10)][None,:,None] + z = np.linspace(0, 1, 7)[None,None,:] + + y1 = cephes.mathieu_modcem2(m, q, -z)[0] + + fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] + y2 = (-cephes.mathieu_modcem2(m, q, z)[0] + - 2*fr*cephes.mathieu_modcem1(m, q, z)[0]) + + assert_allclose(y1, y2, rtol=1e-10) + + def test_mathieu_modsem1(self): + assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) + + def test_mathieu_modsem2(self): + cephes.mathieu_modsem2(1,1,1) + + # Test reflection relation AMS 20.6.20 + m = np.arange(1, 4)[:,None,None] + q = np.r_[np.logspace(-2, 2, 10)][None,:,None] + z = np.linspace(0, 1, 7)[None,None,:] + + y1 = cephes.mathieu_modsem2(m, q, -z)[0] + fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] + y2 = (cephes.mathieu_modsem2(m, q, z)[0] + - 2*fr*cephes.mathieu_modsem1(m, q, z)[0]) + assert_allclose(y1, y2, rtol=1e-10) + + def test_mathieu_overflow(self): + # Check that these return NaNs instead of causing a SEGV + assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) + + def test_mathieu_ticket_1847(self): + # Regression test --- this call had some out-of-bounds access + # and could return nan occasionally + for k in range(60): + v = cephes.mathieu_modsem2(2, 100, -1) + # Values from ACM TOMS 804 (derivate by numerical differentiation) + assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) + assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) + + def test_modfresnelm(self): + cephes.modfresnelm(0) + + def test_modfresnelp(self): + cephes.modfresnelp(0) + + def test_modstruve(self): + assert_equal(cephes.modstruve(1,0),0.0) + + def test_nbdtr(self): + assert_equal(cephes.nbdtr(1,1,1),1.0) + + def test_nbdtrc(self): + assert_equal(cephes.nbdtrc(1,1,1),0.0) + + def test_nbdtri(self): + assert_equal(cephes.nbdtri(1,1,1),1.0) + + def test_nbdtrik(self): + cephes.nbdtrik(1,.4,.5) + + def test_nbdtrin(self): + assert_equal(cephes.nbdtrin(1,0,0),5.0) + + def test_ncfdtr(self): + assert_equal(cephes.ncfdtr(1,1,1,0),0.0) + + def test_ncfdtri(self): + assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) + f = [0.5, 1, 1.5] + p = cephes.ncfdtr(2, 3, 1.5, f) + assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) + + @pytest.mark.xfail( + reason=( + "ncfdtr uses a Boost math implementation but ncfdtridfd" + "inverts the less accurate cdflib implementation of ncfdtr." + ) + ) + def test_ncfdtridfd(self): + dfd = [1, 2, 3] + p = cephes.ncfdtr(2, dfd, 0.25, 15) + assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) + + @pytest.mark.xfail( + reason=( + "ncfdtr uses a Boost math implementation but ncfdtridfn" + "inverts the less accurate cdflib implementation of ncfdtr." + ) + ) + def test_ncfdtridfn(self): + dfn = [0.1, 1, 2, 3, 1e4] + p = cephes.ncfdtr(dfn, 2, 0.25, 15) + assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) + + @pytest.mark.xfail( + reason=( + "ncfdtr uses a Boost math implementation but ncfdtrinc" + "inverts the less accurate cdflib implementation of ncfdtr." + ) + ) + def test_ncfdtrinc(self): + nc = [0.5, 1.5, 2.0] + p = cephes.ncfdtr(2, 3, nc, 15) + assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) + + def test_nctdtr(self): + assert_equal(cephes.nctdtr(1,0,0),0.5) + assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) + + assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) + assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) + assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) + + assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) + assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) + assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) + + def test_nctdtridf(self): + cephes.nctdtridf(1,0.5,0) + + def test_nctdtrinc(self): + cephes.nctdtrinc(1,0,0) + + def test_nctdtrit(self): + cephes.nctdtrit(.1,0.2,.5) + + def test_nrdtrimn(self): + assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) + + def test_nrdtrisd(self): + assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, + atol=0, rtol=0) + + def test_obl_ang1(self): + cephes.obl_ang1(1,1,1,0) + + def test_obl_ang1_cv(self): + result = cephes.obl_ang1_cv(1,1,1,1,0) + assert_almost_equal(result[0],1.0) + assert_almost_equal(result[1],0.0) + + def test_obl_cv(self): + assert_equal(cephes.obl_cv(1,1,0),2.0) + + def test_obl_rad1(self): + cephes.obl_rad1(1,1,1,0) + + def test_obl_rad1_cv(self): + cephes.obl_rad1_cv(1,1,1,1,0) + + def test_obl_rad2(self): + cephes.obl_rad2(1,1,1,0) + + def test_obl_rad2_cv(self): + cephes.obl_rad2_cv(1,1,1,1,0) + + def test_pbdv(self): + assert_equal(cephes.pbdv(1,0),(0.0,1.0)) + + def test_pbvv(self): + cephes.pbvv(1,0) + + def test_pbwa(self): + cephes.pbwa(1,0) + + def test_pdtr(self): + val = cephes.pdtr(0, 1) + assert_almost_equal(val, np.exp(-1)) + # Edge case: m = 0. + val = cephes.pdtr([0, 1, 2], 0) + assert_array_equal(val, [1, 1, 1]) + + def test_pdtrc(self): + val = cephes.pdtrc(0, 1) + assert_almost_equal(val, 1 - np.exp(-1)) + # Edge case: m = 0. + val = cephes.pdtrc([0, 1, 2], 0.0) + assert_array_equal(val, [0, 0, 0]) + + def test_pdtri(self): + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "floating point number truncated to an integer") + cephes.pdtri(0.5,0.5) + + def test_pdtrik(self): + k = cephes.pdtrik(0.5, 1) + assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) + # Edge case: m = 0 or very small. + k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) + assert_array_equal(k, np.zeros((3, 3))) + + def test_pro_ang1(self): + cephes.pro_ang1(1,1,1,0) + + def test_pro_ang1_cv(self): + assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), + array((1.0,0.0))) + + def test_pro_cv(self): + assert_equal(cephes.pro_cv(1,1,0),2.0) + + def test_pro_rad1(self): + cephes.pro_rad1(1,1,1,0.1) + + def test_pro_rad1_cv(self): + cephes.pro_rad1_cv(1,1,1,1,0) + + def test_pro_rad2(self): + cephes.pro_rad2(1,1,1,0) + + def test_pro_rad2_cv(self): + cephes.pro_rad2_cv(1,1,1,1,0) + + def test_psi(self): + cephes.psi(1) + + def test_radian(self): + assert_equal(cephes.radian(0,0,0),0) + + def test_rgamma(self): + assert_equal(cephes.rgamma(1),1.0) + + def test_round(self): + assert_equal(cephes.round(3.4),3.0) + assert_equal(cephes.round(-3.4),-3.0) + assert_equal(cephes.round(3.6),4.0) + assert_equal(cephes.round(-3.6),-4.0) + assert_equal(cephes.round(3.5),4.0) + assert_equal(cephes.round(-3.5),-4.0) + + def test_shichi(self): + cephes.shichi(1) + + def test_sici(self): + cephes.sici(1) + + s, c = cephes.sici(np.inf) + assert_almost_equal(s, np.pi * 0.5) + assert_almost_equal(c, 0) + + s, c = cephes.sici(-np.inf) + assert_almost_equal(s, -np.pi * 0.5) + assert_(np.isnan(c), "cosine integral(-inf) is not nan") + + def test_sindg(self): + assert_equal(cephes.sindg(90),1.0) + + def test_smirnov(self): + assert_equal(cephes.smirnov(1,.1),0.9) + assert_(np.isnan(cephes.smirnov(1,np.nan))) + + def test_smirnovp(self): + assert_equal(cephes._smirnovp(1, .1), -1) + assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) + assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) + assert_(np.isnan(cephes._smirnovp(1, np.nan))) + + def test_smirnovc(self): + assert_equal(cephes._smirnovc(1,.1),0.1) + assert_(np.isnan(cephes._smirnovc(1,np.nan))) + x10 = np.linspace(0, 1, 11, endpoint=True) + assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) + x4 = np.linspace(0, 1, 5, endpoint=True) + assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) + + def test_smirnovi(self): + assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) + assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) + assert_(np.isnan(cephes.smirnovi(1,np.nan))) + + def test_smirnovci(self): + assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) + assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) + assert_(np.isnan(cephes._smirnovci(1,np.nan))) + + def test_spence(self): + assert_equal(cephes.spence(1),0.0) + + def test_stdtr(self): + assert_equal(cephes.stdtr(1,0),0.5) + assert_almost_equal(cephes.stdtr(1,1), 0.75) + assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) + + def test_stdtridf(self): + cephes.stdtridf(0.7,1) + + def test_stdtrit(self): + cephes.stdtrit(1,0.7) + + def test_struve(self): + assert_equal(cephes.struve(0,0),0.0) + + def test_tandg(self): + assert_equal(cephes.tandg(45),1.0) + + def test_tklmbda(self): + assert_almost_equal(cephes.tklmbda(1,1),1.0) + + def test_y0(self): + cephes.y0(1) + + def test_y1(self): + cephes.y1(1) + + def test_yn(self): + cephes.yn(1,1) + + def test_yv(self): + cephes.yv(1,1) + + def test_yve(self): + cephes.yve(1,1) + + def test_wofz(self): + z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), + complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), + complex(-0.0000000234545,1.1234), complex(-3.,5.1), + complex(-53,30.1), complex(0.0,0.12345), + complex(11,1), complex(-22,-2), complex(9,-28), + complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) + ] + w = [ + complex(-3.78270245518980507452677445620103199303131110e-7, + 0.000903861276433172057331093754199933411710053155), + complex(0.1764906227004816847297495349730234591778719532788, + -0.02146550539468457616788719893991501311573031095617), + complex(0.2410250715772692146133539023007113781272362309451, + 0.06087579663428089745895459735240964093522265589350), + complex(0.30474420525691259245713884106959496013413834051768, + -0.20821893820283162728743734725471561394145872072738), + complex(7.317131068972378096865595229600561710140617977e34, + 8.321873499714402777186848353320412813066170427e34), + complex(0.0615698507236323685519612934241429530190806818395, + -0.00676005783716575013073036218018565206070072304635), + complex(0.3960793007699874918961319170187598400134746631, + -5.593152259116644920546186222529802777409274656e-9), + complex(0.08217199226739447943295069917990417630675021771804, + -0.04701291087643609891018366143118110965272615832184), + complex(0.00457246000350281640952328010227885008541748668738, + -0.00804900791411691821818731763401840373998654987934), + complex(0.8746342859608052666092782112565360755791467973338452, + 0.), + complex(0.00468190164965444174367477874864366058339647648741, + 0.0510735563901306197993676329845149741675029197050), + complex(-0.0023193175200187620902125853834909543869428763219, + -0.025460054739731556004902057663500272721780776336), + complex(9.11463368405637174660562096516414499772662584e304, + 3.97101807145263333769664875189354358563218932e305), + complex(-4.4927207857715598976165541011143706155432296e281, + -2.8019591213423077494444700357168707775769028e281), + complex(2.820947917809305132678577516325951485807107151e-6, + 2.820947917668257736791638444590253942253354058e-6), + complex(2.82094791773878143474039725787438662716372268e-15, + 2.82094791773878143474039725773333923127678361e-15) + ] + assert_func_equal(cephes.wofz, w, z, rtol=1e-13) + + +class TestAiry: + def test_airy(self): + # This tests the airy function to ensure 8 place accuracy in computation + + x = special.airy(.99) + assert_array_almost_equal( + x, + array([0.13689066,-0.16050153,1.19815925,0.92046818]), + 8, + ) + x = special.airy(.41) + assert_array_almost_equal( + x, + array([0.25238916,-.23480512,0.80686202,0.51053919]), + 8, + ) + x = special.airy(-.36) + assert_array_almost_equal( + x, + array([0.44508477,-0.23186773,0.44939534,0.48105354]), + 8, + ) + + def test_airye(self): + a = special.airye(0.01) + b = special.airy(0.01) + b1 = [None]*4 + for n in range(2): + b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) + for n in range(2,4): + b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) + assert_array_almost_equal(a,b1,6) + + def test_bi_zeros(self): + bi = special.bi_zeros(2) + bia = (array([-1.17371322, -3.2710930]), + array([-2.29443968, -4.07315509]), + array([-0.45494438, 0.39652284]), + array([0.60195789, -0.76031014])) + assert_array_almost_equal(bi,bia,4) + + bi = special.bi_zeros(5) + assert_array_almost_equal(bi[0],array([-1.173713222709127, + -3.271093302836352, + -4.830737841662016, + -6.169852128310251, + -7.376762079367764]),11) + + assert_array_almost_equal(bi[1],array([-2.294439682614122, + -4.073155089071828, + -5.512395729663599, + -6.781294445990305, + -7.940178689168587]),10) + + assert_array_almost_equal(bi[2],array([-0.454944383639657, + 0.396522836094465, + -0.367969161486959, + 0.349499116831805, + -0.336026240133662]),11) + + assert_array_almost_equal(bi[3],array([0.601957887976239, + -0.760310141492801, + 0.836991012619261, + -0.88947990142654, + 0.929983638568022]),10) + + def test_ai_zeros(self): + ai = special.ai_zeros(1) + assert_array_almost_equal(ai,(array([-2.33810741]), + array([-1.01879297]), + array([0.5357]), + array([0.7012])),4) + + @pytest.mark.fail_slow(5) + def test_ai_zeros_big(self): + z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) + ai_z, aip_z, _, _ = special.airy(z) + ai_zp, aip_zp, _, _ = special.airy(zp) + + ai_envelope = 1/abs(z)**(1./4) + aip_envelope = abs(zp)**(1./4) + + # Check values + assert_allclose(ai_zpx, ai_zp, rtol=1e-10) + assert_allclose(aip_zx, aip_z, rtol=1e-10) + + # Check they are zeros + assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) + assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) + + # Check first zeros, DLMF 9.9.1 + assert_allclose(z[:6], + [-2.3381074105, -4.0879494441, -5.5205598281, + -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) + assert_allclose(zp[:6], + [-1.0187929716, -3.2481975822, -4.8200992112, + -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) + + @pytest.mark.fail_slow(5) + def test_bi_zeros_big(self): + z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) + _, _, bi_z, bip_z = special.airy(z) + _, _, bi_zp, bip_zp = special.airy(zp) + + bi_envelope = 1/abs(z)**(1./4) + bip_envelope = abs(zp)**(1./4) + + # Check values + assert_allclose(bi_zpx, bi_zp, rtol=1e-10) + assert_allclose(bip_zx, bip_z, rtol=1e-10) + + # Check they are zeros + assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) + assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) + + # Check first zeros, DLMF 9.9.2 + assert_allclose(z[:6], + [-1.1737132227, -3.2710933028, -4.8307378417, + -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) + assert_allclose(zp[:6], + [-2.2944396826, -4.0731550891, -5.5123957297, + -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) + + +class TestAssocLaguerre: + def test_assoc_laguerre(self): + a1 = special.genlaguerre(11,1) + a2 = special.assoc_laguerre(.2,11,1) + assert_array_almost_equal(a2,a1(.2),8) + a2 = special.assoc_laguerre(1,11,1) + assert_array_almost_equal(a2,a1(1),8) + + +class TestBesselpoly: + def test_besselpoly(self): + pass + + +class TestKelvin: + def test_bei(self): + mbei = special.bei(2) + assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact + + def test_beip(self): + mbeip = special.beip(2) + assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact + + def test_ber(self): + mber = special.ber(2) + assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact + + def test_berp(self): + mberp = special.berp(2) + assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact + + def test_bei_zeros(self): + # Abramowitz & Stegun, Table 9.12 + bi = special.bei_zeros(5) + assert_array_almost_equal(bi,array([5.02622, + 9.45541, + 13.89349, + 18.33398, + 22.77544]),4) + + def test_beip_zeros(self): + bip = special.beip_zeros(5) + assert_array_almost_equal(bip,array([3.772673304934953, + 8.280987849760042, + 12.742147523633703, + 17.193431752512542, + 21.641143941167325]),8) + + def test_ber_zeros(self): + ber = special.ber_zeros(5) + assert_array_almost_equal(ber,array([2.84892, + 7.23883, + 11.67396, + 16.11356, + 20.55463]),4) + + def test_berp_zeros(self): + brp = special.berp_zeros(5) + assert_array_almost_equal(brp,array([6.03871, + 10.51364, + 14.96844, + 19.41758, + 23.86430]),4) + + def test_kelvin(self): + mkelv = special.kelvin(2) + assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, + special.ker(2) + special.kei(2)*1j, + special.berp(2) + special.beip(2)*1j, + special.kerp(2) + special.keip(2)*1j),8) + + def test_kei(self): + mkei = special.kei(2) + assert_almost_equal(mkei,-0.20240006776470432,5) + + def test_keip(self): + mkeip = special.keip(2) + assert_almost_equal(mkeip,0.21980790991960536,5) + + def test_ker(self): + mker = special.ker(2) + assert_almost_equal(mker,-0.041664513991509472,5) + + def test_kerp(self): + mkerp = special.kerp(2) + assert_almost_equal(mkerp,-0.10660096588105264,5) + + def test_kei_zeros(self): + kei = special.kei_zeros(5) + assert_array_almost_equal(kei,array([3.91467, + 8.34422, + 12.78256, + 17.22314, + 21.66464]),4) + + def test_keip_zeros(self): + keip = special.keip_zeros(5) + assert_array_almost_equal(keip,array([4.93181, + 9.40405, + 13.85827, + 18.30717, + 22.75379]),4) + + # numbers come from 9.9 of A&S pg. 381 + def test_kelvin_zeros(self): + tmp = special.kelvin_zeros(5) + berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp + assert_array_almost_equal(berz,array([2.84892, + 7.23883, + 11.67396, + 16.11356, + 20.55463]),4) + assert_array_almost_equal(beiz,array([5.02622, + 9.45541, + 13.89349, + 18.33398, + 22.77544]),4) + assert_array_almost_equal(kerz,array([1.71854, + 6.12728, + 10.56294, + 15.00269, + 19.44382]),4) + assert_array_almost_equal(keiz,array([3.91467, + 8.34422, + 12.78256, + 17.22314, + 21.66464]),4) + assert_array_almost_equal(berpz,array([6.03871, + 10.51364, + 14.96844, + 19.41758, + 23.86430]),4) + assert_array_almost_equal(beipz,array([3.77267, + # table from 1927 had 3.77320 + # but this is more accurate + 8.28099, + 12.74215, + 17.19343, + 21.64114]),4) + assert_array_almost_equal(kerpz,array([2.66584, + 7.17212, + 11.63218, + 16.08312, + 20.53068]),4) + assert_array_almost_equal(keipz,array([4.93181, + 9.40405, + 13.85827, + 18.30717, + 22.75379]),4) + + def test_ker_zeros(self): + ker = special.ker_zeros(5) + assert_array_almost_equal(ker,array([1.71854, + 6.12728, + 10.56294, + 15.00269, + 19.44381]),4) + + def test_kerp_zeros(self): + kerp = special.kerp_zeros(5) + assert_array_almost_equal(kerp,array([2.66584, + 7.17212, + 11.63218, + 16.08312, + 20.53068]),4) + + +class TestBernoulli: + def test_bernoulli(self): + brn = special.bernoulli(5) + assert_array_almost_equal(brn,array([1.0000, + -0.5000, + 0.1667, + 0.0000, + -0.0333, + 0.0000]),4) + + +class TestBeta: + """ + Test beta and betaln. + """ + + def test_beta(self): + assert_equal(special.beta(1, 1), 1.0) + assert_allclose(special.beta(-100.3, 1e-200), special.gamma(1e-200)) + assert_allclose(special.beta(0.0342, 171), 24.070498359873497, + rtol=1e-13, atol=0) + + bet = special.beta(2, 4) + betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) + assert_allclose(bet, betg, rtol=1e-13) + + def test_beta_inf(self): + assert_(np.isinf(special.beta(-1, 2))) + + def test_betaln(self): + assert_equal(special.betaln(1, 1), 0.0) + assert_allclose(special.betaln(-100.3, 1e-200), + special.gammaln(1e-200)) + assert_allclose(special.betaln(0.0342, 170), 3.1811881124242447, + rtol=1e-14, atol=0) + + betln = special.betaln(2, 4) + bet = log(abs(special.beta(2, 4))) + assert_allclose(betln, bet, rtol=1e-13) + + +class TestBetaInc: + """ + Tests for betainc, betaincinv, betaincc, betainccinv. + """ + + def test_a1_b1(self): + # betainc(1, 1, x) is x. + x = np.array([0, 0.25, 1]) + assert_equal(special.betainc(1, 1, x), x) + assert_equal(special.betaincinv(1, 1, x), x) + assert_equal(special.betaincc(1, 1, x), 1 - x) + assert_equal(special.betainccinv(1, 1, x), 1 - x) + + # Nontrivial expected values computed with mpmath: + # from mpmath import mp + # mp.dps = 100 + # p = mp.betainc(a, b, 0, x, regularized=True) + # + # or, e.g., + # + # p = 0.25 + # a, b = 0.0342, 171 + # x = mp.findroot( + # lambda t: mp.betainc(a, b, 0, t, regularized=True) - p, + # (8e-21, 9e-21), + # solver='anderson', + # ) + # + @pytest.mark.parametrize( + 'a, b, x, p', + [(2, 4, 0.3138101704556974, 0.5), + (0.0342, 171.0, 1e-10, 0.552699169018070910641), + # gh-3761: + (0.0342, 171, 8.42313169354797e-21, 0.25), + # gh-4244: + (0.0002742794749792665, 289206.03125, 1.639984034231756e-56, + 0.9688708782196045), + # gh-12796: + (4, 99997, 0.0001947841578892121, 0.999995)]) + def test_betainc_betaincinv(self, a, b, x, p): + p1 = special.betainc(a, b, x) + assert_allclose(p1, p, rtol=1e-15) + x1 = special.betaincinv(a, b, p) + assert_allclose(x1, x, rtol=5e-13) + + # Expected values computed with mpmath: + # from mpmath import mp + # mp.dps = 100 + # p = mp.betainc(a, b, x, 1, regularized=True) + @pytest.mark.parametrize('a, b, x, p', + [(2.5, 3.0, 0.25, 0.833251953125), + (7.5, 13.25, 0.375, 0.43298734645560368593), + (0.125, 7.5, 0.425, 0.0006688257851314237), + (0.125, 18.0, 1e-6, 0.72982359145096327654), + (0.125, 18.0, 0.996, 7.2745875538380150586e-46), + (0.125, 24.0, 0.75, 3.70853404816862016966e-17), + (16.0, 0.75, 0.99999999975, + 5.4408759277418629909e-07), + # gh-4677 (numbers from stackoverflow question): + (0.4211959643503401, 16939.046996018118, + 0.000815296167195521, 1e-7)]) + def test_betaincc_betainccinv(self, a, b, x, p): + p1 = special.betaincc(a, b, x) + assert_allclose(p1, p, rtol=5e-15) + x1 = special.betainccinv(a, b, p) + assert_allclose(x1, x, rtol=8e-15) + + @pytest.mark.parametrize( + 'a, b, y, ref', + [(14.208308325339239, 14.208308325339239, 7.703145458496392e-307, + 8.566004561846704e-23), + (14.0, 14.5, 1e-280, 2.9343915006642424e-21), + (3.5, 15.0, 4e-95, 1.3290751429289227e-28), + (10.0, 1.25, 2e-234, 3.982659092143654e-24), + (4.0, 99997.0, 5e-88, 3.309800566862242e-27)] + ) + def test_betaincinv_tiny_y(self, a, b, y, ref): + # Test with extremely small y values. This test includes + # a regression test for an issue in the boost code; + # see https://github.com/boostorg/math/issues/961 + # + # The reference values were computed with mpmath. For example, + # + # from mpmath import mp + # mp.dps = 1000 + # a = 14.208308325339239 + # p = 7.703145458496392e-307 + # x = mp.findroot(lambda t: mp.betainc(a, a, 0, t, + # regularized=True) - p, + # x0=8.566e-23) + # print(float(x)) + # + x = special.betaincinv(a, b, y) + assert_allclose(x, ref, rtol=1e-14) + + @pytest.mark.parametrize('func', [special.betainc, special.betaincinv, + special.betaincc, special.betainccinv]) + @pytest.mark.parametrize('args', [(-1.0, 2, 0.5), (0, 2, 0.5), + (1.5, -2.0, 0.5), (1.5, 0, 0.5), + (1.5, 2.0, -0.3), (1.5, 2.0, 1.1)]) + def test_betainc_domain_errors(self, func, args): + with special.errstate(domain='raise'): + with pytest.raises(special.SpecialFunctionError, match='domain'): + special.betainc(*args) + + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_gh21426(self, dtype): + # Test for gh-21426: betaincinv must not return NaN + a = np.array([5.], dtype=dtype) + x = np.array([0.5], dtype=dtype) + result = special.betaincinv(a, a, x) + assert_allclose(result, x, rtol=10 * np.finfo(dtype).eps) + + +class TestCombinatorics: + def test_comb(self): + assert_allclose(special.comb([10, 10], [3, 4]), [120., 210.]) + assert_allclose(special.comb(10, 3), 120.) + assert_equal(special.comb(10, 3, exact=True), 120) + assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) + + assert_allclose([special.comb(20, k, exact=True) for k in range(21)], + special.comb(20, list(range(21))), atol=1e-15) + + ii = np.iinfo(int).max + 1 + assert_equal(special.comb(ii, ii-1, exact=True), ii) + + expected = 100891344545564193334812497256 + assert special.comb(100, 50, exact=True) == expected + + def test_comb_with_np_int64(self): + n = 70 + k = 30 + np_n = np.int64(n) + np_k = np.int64(k) + res_np = special.comb(np_n, np_k, exact=True) + res_py = special.comb(n, k, exact=True) + assert res_np == res_py + + def test_comb_zeros(self): + assert_equal(special.comb(2, 3, exact=True), 0) + assert_equal(special.comb(-1, 3, exact=True), 0) + assert_equal(special.comb(2, -1, exact=True), 0) + assert_equal(special.comb(2, -1, exact=False), 0) + assert_allclose(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.]) + + @pytest.mark.thread_unsafe + def test_comb_exact_non_int_dep(self): + msg = "`exact=True`" + with pytest.deprecated_call(match=msg): + special.comb(3.4, 4, exact=True) + + def test_perm(self): + assert_allclose(special.perm([10, 10], [3, 4]), [720., 5040.]) + assert_almost_equal(special.perm(10, 3), 720.) + assert_equal(special.perm(10, 3, exact=True), 720) + + def test_perm_zeros(self): + assert_equal(special.perm(2, 3, exact=True), 0) + assert_equal(special.perm(-1, 3, exact=True), 0) + assert_equal(special.perm(2, -1, exact=True), 0) + assert_equal(special.perm(2, -1, exact=False), 0) + assert_allclose(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.]) + + @pytest.mark.thread_unsafe + def test_perm_iv(self): + # currently `exact=True` only support scalars + with pytest.raises(ValueError, match="scalar integers"): + special.perm([1, 2], [4, 5], exact=True) + + # Non-integral scalars with N < k, or N,k < 0 used to return 0, this is now + # deprecated and will raise an error in SciPy 1.16.0 + with pytest.deprecated_call(match="Non-integer"): + special.perm(4.6, 6, exact=True) + with pytest.deprecated_call(match="Non-integer"): + special.perm(-4.6, 3, exact=True) + with pytest.deprecated_call(match="Non-integer"): + special.perm(4, -3.9, exact=True) + + # Non-integral scalars which aren't included in the cases above an raise an + # error directly without deprecation as this code never worked + with pytest.raises(ValueError, match="Non-integer"): + special.perm(6.0, 4.6, exact=True) + + +class TestTrigonometric: + def test_cbrt(self): + cb = special.cbrt(27) + cbrl = 27**(1.0/3.0) + assert_approx_equal(cb,cbrl) + + def test_cbrtmore(self): + cb1 = special.cbrt(27.9) + cbrl1 = 27.9**(1.0/3.0) + assert_almost_equal(cb1,cbrl1,8) + + def test_cosdg(self): + cdg = special.cosdg(90) + cdgrl = cos(pi/2.0) + assert_almost_equal(cdg,cdgrl,8) + + def test_cosdgmore(self): + cdgm = special.cosdg(30) + cdgmrl = cos(pi/6.0) + assert_almost_equal(cdgm,cdgmrl,8) + + def test_cosm1(self): + cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) + csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) + assert_array_almost_equal(cs,csrl,8) + + def test_cotdg(self): + ct = special.cotdg(30) + ctrl = tan(pi/6.0)**(-1) + assert_almost_equal(ct,ctrl,8) + + def test_cotdgmore(self): + ct1 = special.cotdg(45) + ctrl1 = tan(pi/4.0)**(-1) + assert_almost_equal(ct1,ctrl1,8) + + def test_specialpoints(self): + assert_almost_equal(special.cotdg(45), 1.0, 14) + assert_almost_equal(special.cotdg(-45), -1.0, 14) + assert_almost_equal(special.cotdg(90), 0.0, 14) + assert_almost_equal(special.cotdg(-90), 0.0, 14) + assert_almost_equal(special.cotdg(135), -1.0, 14) + assert_almost_equal(special.cotdg(-135), 1.0, 14) + assert_almost_equal(special.cotdg(225), 1.0, 14) + assert_almost_equal(special.cotdg(-225), -1.0, 14) + assert_almost_equal(special.cotdg(270), 0.0, 14) + assert_almost_equal(special.cotdg(-270), 0.0, 14) + assert_almost_equal(special.cotdg(315), -1.0, 14) + assert_almost_equal(special.cotdg(-315), 1.0, 14) + assert_almost_equal(special.cotdg(765), 1.0, 14) + + def test_sinc(self): + # the sinc implementation and more extensive sinc tests are in numpy + assert_array_equal(special.sinc([0]), 1) + assert_equal(special.sinc(0.0), 1.0) + + def test_sindg(self): + sn = special.sindg(90) + assert_equal(sn,1.0) + + def test_sindgmore(self): + snm = special.sindg(30) + snmrl = sin(pi/6.0) + assert_almost_equal(snm,snmrl,8) + snm1 = special.sindg(45) + snmrl1 = sin(pi/4.0) + assert_almost_equal(snm1,snmrl1,8) + + +class TestTandg: + + def test_tandg(self): + tn = special.tandg(30) + tnrl = tan(pi/6.0) + assert_almost_equal(tn,tnrl,8) + + def test_tandgmore(self): + tnm = special.tandg(45) + tnmrl = tan(pi/4.0) + assert_almost_equal(tnm,tnmrl,8) + tnm1 = special.tandg(60) + tnmrl1 = tan(pi/3.0) + assert_almost_equal(tnm1,tnmrl1,8) + + def test_specialpoints(self): + assert_almost_equal(special.tandg(0), 0.0, 14) + assert_almost_equal(special.tandg(45), 1.0, 14) + assert_almost_equal(special.tandg(-45), -1.0, 14) + assert_almost_equal(special.tandg(135), -1.0, 14) + assert_almost_equal(special.tandg(-135), 1.0, 14) + assert_almost_equal(special.tandg(180), 0.0, 14) + assert_almost_equal(special.tandg(-180), 0.0, 14) + assert_almost_equal(special.tandg(225), 1.0, 14) + assert_almost_equal(special.tandg(-225), -1.0, 14) + assert_almost_equal(special.tandg(315), -1.0, 14) + assert_almost_equal(special.tandg(-315), 1.0, 14) + + +class TestEllip: + def test_ellipj_nan(self): + """Regression test for #912.""" + special.ellipj(0.5, np.nan) + + def test_ellipj(self): + el = special.ellipj(0.2,0) + rel = [sin(0.2),cos(0.2),1.0,0.20] + assert_array_almost_equal(el,rel,13) + + def test_ellipk(self): + elk = special.ellipk(.2) + assert_almost_equal(elk,1.659623598610528,11) + + assert_equal(special.ellipkm1(0.0), np.inf) + assert_equal(special.ellipkm1(1.0), pi/2) + assert_equal(special.ellipkm1(np.inf), 0.0) + assert_equal(special.ellipkm1(np.nan), np.nan) + assert_equal(special.ellipkm1(-1), np.nan) + assert_allclose(special.ellipk(-10), 0.7908718902387385) + + def test_ellipkinc(self): + elkinc = special.ellipkinc(pi/2,.2) + elk = special.ellipk(0.2) + assert_almost_equal(elkinc,elk,15) + alpha = 20*pi/180 + phi = 45*pi/180 + m = sin(alpha)**2 + elkinc = special.ellipkinc(phi,m) + assert_almost_equal(elkinc,0.79398143,8) + # From pg. 614 of A & S + + assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) + assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) + assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) + assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) + assert_equal(special.ellipkinc(pi/2, 2), np.nan) + assert_equal(special.ellipkinc(0, 0.5), 0.0) + assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) + assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) + assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) + assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) + assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) + assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) + assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) + assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) + + assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) + assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) + + def test_ellipkinc_2(self): + # Regression test for gh-3550 + # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value + mbad = 0.68359375000000011 + phi = 0.9272952180016123 + m = np.nextafter(mbad, 0) + mvals = [] + for j in range(10): + mvals.append(m) + m = np.nextafter(m, 1) + f = special.ellipkinc(phi, mvals) + assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) + # this bug also appears at phi + n * pi for at least small n + f1 = special.ellipkinc(phi + pi, mvals) + assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) + + def test_ellipkinc_singular(self): + # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) + xlog = np.logspace(-300, -17, 25) + xlin = np.linspace(1e-17, 0.1, 25) + xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) + + assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), + rtol=1e14) + assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), + rtol=1e14) + assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), + rtol=1e14) + assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) + assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), + rtol=1e14) + assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), + rtol=1e14) + assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), + rtol=1e14) + assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) + + def test_ellipe(self): + ele = special.ellipe(.2) + assert_almost_equal(ele,1.4890350580958529,8) + + assert_equal(special.ellipe(0.0), pi/2) + assert_equal(special.ellipe(1.0), 1.0) + assert_equal(special.ellipe(-np.inf), np.inf) + assert_equal(special.ellipe(np.nan), np.nan) + assert_equal(special.ellipe(2), np.nan) + assert_allclose(special.ellipe(-10), 3.6391380384177689) + + def test_ellipeinc(self): + eleinc = special.ellipeinc(pi/2,.2) + ele = special.ellipe(0.2) + assert_almost_equal(eleinc,ele,14) + # pg 617 of A & S + alpha, phi = 52*pi/180,35*pi/180 + m = sin(alpha)**2 + eleinc = special.ellipeinc(phi,m) + assert_almost_equal(eleinc, 0.58823065, 8) + + assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) + assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) + assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) + assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) + assert_equal(special.ellipeinc(pi/2, 2), np.nan) + assert_equal(special.ellipeinc(0, 0.5), 0.0) + assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) + assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) + assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) + assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) + assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) + assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) + assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) + assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) + assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) + + def test_ellipeinc_2(self): + # Regression test for gh-3550 + # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value + mbad = 0.68359375000000011 + phi = 0.9272952180016123 + m = np.nextafter(mbad, 0) + mvals = [] + for j in range(10): + mvals.append(m) + m = np.nextafter(m, 1) + f = special.ellipeinc(phi, mvals) + assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) + # this bug also appears at phi + n * pi for at least small n + f1 = special.ellipeinc(phi + pi, mvals) + assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) + + +class TestEllipCarlson: + """Test for Carlson elliptic integrals ellipr[cdfgj]. + The special values used in these tests can be found in Sec. 3 of Carlson + (1994), https://arxiv.org/abs/math/9409227 + """ + def test_elliprc(self): + assert_allclose(elliprc(1, 1), 1) + assert elliprc(1, inf) == 0.0 + assert isnan(elliprc(1, 0)) + assert elliprc(1, complex(1, inf)) == 0.0 + args = array([[0.0, 0.25], + [2.25, 2.0], + [0.0, 1.0j], + [-1.0j, 1.0j], + [0.25, -2.0], + [1.0j, -1.0]]) + expected_results = array([np.pi, + np.log(2.0), + 1.1107207345396 * (1.0-1.0j), + 1.2260849569072-0.34471136988768j, + np.log(2.0) / 3.0, + 0.77778596920447+0.19832484993429j]) + for i, arr in enumerate(args): + assert_allclose(elliprc(*arr), expected_results[i]) + + def test_elliprd(self): + assert_allclose(elliprd(1, 1, 1), 1) + assert_allclose(elliprd(0, 2, 1) / 3.0, 0.59907011736779610371) + assert elliprd(1, 1, inf) == 0.0 + assert np.isinf(elliprd(1, 1, 0)) + assert np.isinf(elliprd(1, 1, complex(0, 0))) + assert np.isinf(elliprd(0, 1, complex(0, 0))) + assert isnan(elliprd(1, 1, -np.finfo(np.float64).tiny / 2.0)) + assert isnan(elliprd(1, 1, complex(-1, 0))) + args = array([[0.0, 2.0, 1.0], + [2.0, 3.0, 4.0], + [1.0j, -1.0j, 2.0], + [0.0, 1.0j, -1.0j], + [0.0, -1.0+1.0j, 1.0j], + [-2.0-1.0j, -1.0j, -1.0+1.0j]]) + expected_results = array([1.7972103521034, + 0.16510527294261, + 0.65933854154220, + 1.2708196271910+2.7811120159521j, + -1.8577235439239-0.96193450888839j, + 1.8249027393704-1.2218475784827j]) + for i, arr in enumerate(args): + assert_allclose(elliprd(*arr), expected_results[i]) + + def test_elliprf(self): + assert_allclose(elliprf(1, 1, 1), 1) + assert_allclose(elliprf(0, 1, 2), 1.31102877714605990523) + assert elliprf(1, inf, 1) == 0.0 + assert np.isinf(elliprf(0, 1, 0)) + assert isnan(elliprf(1, 1, -1)) + assert elliprf(complex(inf), 0, 1) == 0.0 + assert isnan(elliprf(1, 1, complex(-inf, 1))) + args = array([[1.0, 2.0, 0.0], + [1.0j, -1.0j, 0.0], + [0.5, 1.0, 0.0], + [-1.0+1.0j, 1.0j, 0.0], + [2.0, 3.0, 4.0], + [1.0j, -1.0j, 2.0], + [-1.0+1.0j, 1.0j, 1.0-1.0j]]) + expected_results = array([1.3110287771461, + 1.8540746773014, + 1.8540746773014, + 0.79612586584234-1.2138566698365j, + 0.58408284167715, + 1.0441445654064, + 0.93912050218619-0.53296252018635j]) + for i, arr in enumerate(args): + assert_allclose(elliprf(*arr), expected_results[i]) + + def test_elliprg(self): + assert_allclose(elliprg(1, 1, 1), 1) + assert_allclose(elliprg(0, 0, 1), 0.5) + assert_allclose(elliprg(0, 0, 0), 0) + assert np.isinf(elliprg(1, inf, 1)) + assert np.isinf(elliprg(complex(inf), 1, 1)) + args = array([[0.0, 16.0, 16.0], + [2.0, 3.0, 4.0], + [0.0, 1.0j, -1.0j], + [-1.0+1.0j, 1.0j, 0.0], + [-1.0j, -1.0+1.0j, 1.0j], + [0.0, 0.0796, 4.0]]) + expected_results = array([np.pi, + 1.7255030280692, + 0.42360654239699, + 0.44660591677018+0.70768352357515j, + 0.36023392184473+0.40348623401722j, + 1.0284758090288]) + for i, arr in enumerate(args): + assert_allclose(elliprg(*arr), expected_results[i]) + + def test_elliprj(self): + assert_allclose(elliprj(1, 1, 1, 1), 1) + assert elliprj(1, 1, inf, 1) == 0.0 + assert isnan(elliprj(1, 0, 0, 0)) + assert isnan(elliprj(-1, 1, 1, 1)) + assert elliprj(1, 1, 1, inf) == 0.0 + args = array([[0.0, 1.0, 2.0, 3.0], + [2.0, 3.0, 4.0, 5.0], + [2.0, 3.0, 4.0, -1.0+1.0j], + [1.0j, -1.0j, 0.0, 2.0], + [-1.0+1.0j, -1.0-1.0j, 1.0, 2.0], + [1.0j, -1.0j, 0.0, 1.0-1.0j], + [-1.0+1.0j, -1.0-1.0j, 1.0, -3.0+1.0j], + [2.0, 3.0, 4.0, -0.5], # Cauchy principal value + [2.0, 3.0, 4.0, -5.0]]) # Cauchy principal value + expected_results = array([0.77688623778582, + 0.14297579667157, + 0.13613945827771-0.38207561624427j, + 1.6490011662711, + 0.94148358841220, + 1.8260115229009+1.2290661908643j, + -0.61127970812028-1.0684038390007j, + 0.24723819703052, # Cauchy principal value + -0.12711230042964]) # Caucny principal value + for i, arr in enumerate(args): + assert_allclose(elliprj(*arr), expected_results[i]) + + @pytest.mark.xfail(reason="Insufficient accuracy on 32-bit") + def test_elliprj_hard(self): + assert_allclose(elliprj(6.483625725195452e-08, + 1.1649136528196886e-27, + 3.6767340167168e+13, + 0.493704617023468), + 8.63426920644241857617477551054e-6, + rtol=5e-15, atol=1e-20) + assert_allclose(elliprj(14.375105857849121, + 9.993988969725365e-11, + 1.72844262269944e-26, + 5.898871222598245e-06), + 829774.1424801627252574054378691828, + rtol=5e-15, atol=1e-20) + + +class TestEllipLegendreCarlsonIdentities: + """Test identities expressing the Legendre elliptic integrals in terms + of Carlson's symmetric integrals. These identities can be found + in the DLMF https://dlmf.nist.gov/19.25#i . + """ + + def setup_class(self): + self.m_n1_1 = np.arange(-1., 1., 0.01) + # For double, this is -(2**1024) + self.max_neg = finfo(double).min + # Lots of very negative numbers + self.very_neg_m = -1. * 2.**arange(-1 + + np.log2(-self.max_neg), 0., + -1.) + self.ms_up_to_1 = np.concatenate(([self.max_neg], + self.very_neg_m, + self.m_n1_1)) + + def test_k(self): + """Test identity: + K(m) = R_F(0, 1-m, 1) + """ + m = self.ms_up_to_1 + assert_allclose(ellipk(m), elliprf(0., 1.-m, 1.)) + + def test_km1(self): + """Test identity: + K(m) = R_F(0, 1-m, 1) + But with the ellipkm1 function + """ + # For double, this is 2**-1022 + tiny = finfo(double).tiny + # All these small powers of 2, up to 2**-1 + m1 = tiny * 2.**arange(0., -np.log2(tiny)) + assert_allclose(ellipkm1(m1), elliprf(0., m1, 1.)) + + def test_e(self): + """Test identity: + E(m) = 2*R_G(0, 1-k^2, 1) + """ + m = self.ms_up_to_1 + assert_allclose(ellipe(m), 2.*elliprg(0., 1.-m, 1.)) + + +class TestErf: + + def test_erf(self): + er = special.erf(.25) + assert_almost_equal(er,0.2763263902,8) + + def test_erf_zeros(self): + erz = special.erf_zeros(5) + erzr = array([1.45061616+1.88094300j, + 2.24465928+2.61657514j, + 2.83974105+3.17562810j, + 3.33546074+3.64617438j, + 3.76900557+4.06069723j]) + assert_array_almost_equal(erz,erzr,4) + + def _check_variant_func(self, func, other_func, rtol, atol=0): + rng = np.random.RandomState(1234) + n = 10000 + x = rng.pareto(0.02, n) * (2*rng.randint(0, 2, n) - 1) + y = rng.pareto(0.02, n) * (2*rng.randint(0, 2, n) - 1) + z = x + 1j*y + + with np.errstate(all='ignore'): + w = other_func(z) + w_real = other_func(x).real + + mask = np.isfinite(w) + w = w[mask] + z = z[mask] + + mask = np.isfinite(w_real) + w_real = w_real[mask] + x = x[mask] + + # test both real and complex variants + assert_func_equal(func, w, z, rtol=rtol, atol=atol) + assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) + + def test_erfc_consistent(self): + self._check_variant_func( + cephes.erfc, + lambda z: 1 - cephes.erf(z), + rtol=1e-12, + atol=1e-14 # <- the test function loses precision + ) + + def test_erfcx_consistent(self): + self._check_variant_func( + cephes.erfcx, + lambda z: np.exp(z*z) * cephes.erfc(z), + rtol=1e-12 + ) + + def test_erfi_consistent(self): + self._check_variant_func( + cephes.erfi, + lambda z: -1j * cephes.erf(1j*z), + rtol=1e-12 + ) + + def test_dawsn_consistent(self): + self._check_variant_func( + cephes.dawsn, + lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), + rtol=1e-12 + ) + + def test_erf_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, -1, 1] + assert_allclose(special.erf(vals), expected, rtol=1e-15) + + def test_erfc_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, 2, 0] + assert_allclose(special.erfc(vals), expected, rtol=1e-15) + + def test_erfcx_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, np.inf, 0] + assert_allclose(special.erfcx(vals), expected, rtol=1e-15) + + def test_erfi_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, -np.inf, np.inf] + assert_allclose(special.erfi(vals), expected, rtol=1e-15) + + def test_dawsn_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, -0.0, 0.0] + assert_allclose(special.dawsn(vals), expected, rtol=1e-15) + + def test_wofz_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] + assert_allclose(special.wofz(vals), expected, rtol=1e-15) + + +class TestEuler: + def test_euler(self): + eu0 = special.euler(0) + eu1 = special.euler(1) + eu2 = special.euler(2) # just checking segfaults + assert_allclose(eu0, [1], rtol=1e-15) + assert_allclose(eu1, [1, 0], rtol=1e-15) + assert_allclose(eu2, [1, 0, -1], rtol=1e-15) + eu24 = special.euler(24) + mathworld = [1,1,5,61,1385,50521,2702765,199360981, + 19391512145,2404879675441, + 370371188237525,69348874393137901, + 15514534163557086905] + correct = zeros((25,),'d') + for k in range(0,13): + if (k % 2): + correct[2*k] = -float(mathworld[k]) + else: + correct[2*k] = float(mathworld[k]) + with np.errstate(all='ignore'): + err = nan_to_num((eu24-correct)/correct) + errmax = max(err) + assert_almost_equal(errmax, 0.0, 14) + + +class TestExp: + def test_exp2(self): + ex = special.exp2(2) + exrl = 2**2 + assert_equal(ex,exrl) + + def test_exp2more(self): + exm = special.exp2(2.5) + exmrl = 2**(2.5) + assert_almost_equal(exm,exmrl,8) + + def test_exp10(self): + ex = special.exp10(2) + exrl = 10**2 + assert_approx_equal(ex,exrl) + + def test_exp10more(self): + exm = special.exp10(2.5) + exmrl = 10**(2.5) + assert_almost_equal(exm,exmrl,8) + + def test_expm1(self): + ex = (special.expm1(2),special.expm1(3),special.expm1(4)) + exrl = (exp(2)-1,exp(3)-1,exp(4)-1) + assert_array_almost_equal(ex,exrl,8) + + def test_expm1more(self): + ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) + exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) + assert_array_almost_equal(ex1,exrl1,8) + + +def assert_really_equal(x, y, rtol=None): + """ + Sharper assertion function that is stricter about matching types, not just values + + This is useful/necessary in some cases: + * dtypes for arrays that have the same _values_ (e.g. element 1.0 vs 1) + * distinguishing complex from real NaN + * result types for scalars + + We still want to be able to allow a relative tolerance for the values though. + The main logic comparison logic is handled by the xp_assert_* functions. + """ + def assert_func(x, y): + xp_assert_equal(x, y) if rtol is None else xp_assert_close(x, y, rtol=rtol) + + def assert_complex_nan(x): + assert np.isnan(x.real) and np.isnan(x.imag) + + assert type(x) is type(y), f"types not equal: {type(x)}, {type(y)}" + + # ensure we also compare the values _within_ an array appropriately, + # e.g. assert_equal does not distinguish different complex nans in arrays + if isinstance(x, np.ndarray): + # assert_equal does not compare (all) types, only values + assert x.dtype == y.dtype + # for empty arrays resp. to ensure shapes match + assert_func(x, y) + for elem_x, elem_y in zip(x.ravel(), y.ravel()): + assert_really_equal(elem_x, elem_y, rtol=rtol) + elif np.isnan(x) and np.isnan(y) and _is_subdtype(type(x), "c"): + assert_complex_nan(x) and assert_complex_nan(y) + # no need to consider complex infinities due to numpy/numpy#25493 + else: + assert_func(x, y) + + +class TestFactorialFunctions: + def factorialk_ref(self, n, k, exact, extend): + if exact: + return special.factorialk(n, k=k, exact=True) + # for details / explanation see factorialk-docstring + r = np.mod(n, k) if extend == "zero" else 1 + vals = np.power(k, (n - r)/k) * special.gamma(n/k + 1) * special.rgamma(r/k + 1) + # np.maximum is element-wise, which is what we want + return vals * np.maximum(r, 1) + + @pytest.mark.parametrize("exact,extend", + [(True, "zero"), (False, "zero"), (False, "complex")]) + def test_factorialx_scalar_return_type(self, exact, extend): + kw = {"exact": exact, "extend": extend} + assert np.isscalar(special.factorial(1, **kw)) + assert np.isscalar(special.factorial2(1, **kw)) + assert np.isscalar(special.factorialk(1, k=3, **kw)) + + @pytest.mark.parametrize("n", [-1, -2, -3]) + @pytest.mark.parametrize("exact", [True, False]) + def test_factorialx_negative_extend_zero(self, exact, n): + kw = {"exact": exact} + assert_equal(special.factorial(n, **kw), 0) + assert_equal(special.factorial2(n, **kw), 0) + assert_equal(special.factorialk(n, k=3, **kw), 0) + + @pytest.mark.parametrize("exact", [True, False]) + def test_factorialx_negative_extend_zero_array(self, exact): + kw = {"exact": exact} + rtol = 1e-15 + n = [-5, -4, 0, 1] + # Consistent output for n < 0 + expected = np.array([0, 0, 1, 1], dtype=native_int if exact else np.float64) + assert_really_equal(special.factorial(n, **kw), expected, rtol=rtol) + assert_really_equal(special.factorial2(n, **kw), expected, rtol=rtol) + assert_really_equal(special.factorialk(n, k=3, **kw), expected, rtol=rtol) + + @pytest.mark.parametrize("n", [-1.1, -2.2, -3.3]) + def test_factorialx_negative_extend_complex(self, n): + kw = {"extend": "complex"} + exp_1 = {-1.1: -10.686287021193184771, + -2.2: 4.8509571405220931958, + -3.3: -1.4471073942559181166} + exp_2 = {-1.1: 1.0725776858167496309, + -2.2: -3.9777171783768419874, + -3.3: -0.99588841846200555977} + exp_k = {-1.1: 0.73565345382163025659, + -2.2: 1.1749163167190809498, + -3.3: -2.4780584257450583713} + rtol = 3e-15 + assert_allclose(special.factorial(n, **kw), exp_1[n], rtol=rtol) + assert_allclose(special.factorial2(n, **kw), exp_2[n], rtol=rtol) + assert_allclose(special.factorialk(n, k=3, **kw), exp_k[n], rtol=rtol) + assert_allclose(special.factorial([n], **kw)[0], exp_1[n], rtol=rtol) + assert_allclose(special.factorial2([n], **kw)[0], exp_2[n], rtol=rtol) + assert_allclose(special.factorialk([n], k=3, **kw)[0], exp_k[n], rtol=rtol) + + @pytest.mark.parametrize("imag", [0, 0j]) + @pytest.mark.parametrize("n_outer", [-1, -2, -3]) + def test_factorialx_negative_extend_complex_poles(self, n_outer, imag): + kw = {"extend": "complex"} + def _check(n): + complexify = _is_subdtype(type(n), "c") + # like for gamma, we expect complex nans for complex inputs + complex_nan = np.complex128("nan+nanj") + exp = np.complex128("nan+nanj") if complexify else np.float64("nan") + # poles are at negative integers that are multiples of k + assert_really_equal(special.factorial(n, **kw), exp) + assert_really_equal(special.factorial2(n * 2, **kw), exp) + assert_really_equal(special.factorialk(n * 3, k=3, **kw), exp) + # also test complex k for factorialk + c = 1.5 - 2j + assert_really_equal(special.factorialk(n * c, k=c, **kw), complex_nan) + # same for array case + assert_really_equal(special.factorial([n], **kw)[0], exp) + assert_really_equal(special.factorial2([n * 2], **kw)[0], exp) + assert_really_equal(special.factorialk([n * 3], k=3, **kw)[0], exp) + assert_really_equal(special.factorialk([n * c], k=c, **kw)[0], complex_nan) + # more specific tests in test_factorial{,2,k}_complex_reference + + # imag ensures we test both real and complex representations of the poles + _check(n_outer + imag) + # check for large multiple of period + _check(100_000 * n_outer + imag) + + @pytest.mark.parametrize("boxed", [True, False]) + @pytest.mark.parametrize("extend", ["zero", "complex"]) + @pytest.mark.parametrize( + "n", + [ + np.nan, np.float64("nan"), np.nan + np.nan*1j, np.complex128("nan+nanj"), + np.inf, np.inf + 0j, -np.inf, -np.inf + 0j, None, np.datetime64("nat") + ], + ids=[ + "NaN", "np.float64('nan')", "NaN+i*NaN", "np.complex128('nan+nanj')", + "inf", "inf+0i", "-inf", "-inf+0i", "None", "NaT" + ] + ) + @pytest.mark.parametrize( + "factorialx", + [special.factorial, special.factorial2, special.factorialk] + ) + def test_factorialx_inf_nan(self, factorialx, n, extend, boxed): + # NaNs not allowed (by dtype) for exact=True + kw = {"exact": False, "extend": extend} + if factorialx == special.factorialk: + kw["k"] = 3 + + # None is allowed for scalars, but would cause object type in array case + permissible_types = ["i", "f", "c"] if boxed else ["i", "f", "c", type(None)] + # factorial allows floats also for extend="zero" + types_need_complex_ext = "c" if factorialx == special.factorial else ["f", "c"] + + if not _is_subdtype(type(n), permissible_types): + with pytest.raises(ValueError, match="Unsupported data type.*"): + factorialx([n] if boxed else n, **kw) + elif _is_subdtype(type(n), types_need_complex_ext) and extend != "complex": + with pytest.raises(ValueError, match="In order to use non-integer.*"): + factorialx([n] if boxed else n, **kw) + else: + # account for type and whether extend="complex" + complexify = (extend == "complex") and _is_subdtype(type(n), "c") + # note that the type of the naïve `np.nan + np.nan * 1j` is `complex` + # instead of `numpy.complex128`, which trips up assert_really_equal + expected = np.complex128("nan+nanj") if complexify else np.float64("nan") + # the only exception are real infinities + if _is_subdtype(type(n), "f") and np.isinf(n): + # unchanged for positive infinity; negative one depends on extension + neg_inf_result = np.float64(0 if (extend == "zero") else "nan") + expected = np.float64("inf") if (n > 0) else neg_inf_result + + result = factorialx([n], **kw)[0] if boxed else factorialx(n, **kw) + assert_really_equal(result, expected) + # also tested in test_factorial{,2,k}_{array,scalar}_corner_cases + + @pytest.mark.parametrize("extend", [0, 1.1, np.nan, "string"]) + def test_factorialx_raises_extend(self, extend): + with pytest.raises(ValueError, match="argument `extend` must be.*"): + special.factorial(1, extend=extend) + with pytest.raises(ValueError, match="argument `extend` must be.*"): + special.factorial2(1, extend=extend) + with pytest.raises(ValueError, match="argument `extend` must be.*"): + special.factorialk(1, k=3, exact=True, extend=extend) + + @pytest.mark.parametrize("levels", range(1, 5)) + @pytest.mark.parametrize("exact", [True, False]) + def test_factorialx_array_shape(self, levels, exact): + def _nest_me(x, k=1): + """ + Double x and nest it k times + + For example: + >>> _nest_me([3, 4], 2) + [[[3, 4], [3, 4]], [[3, 4], [3, 4]]] + """ + if k == 0: + return x + else: + return _nest_me([x, x], k-1) + + def _check(res, nucleus): + exp = np.array(_nest_me(nucleus, k=levels), dtype=object) + # test that ndarray shape is maintained + # need to cast to float due to numpy/numpy#21220 + assert_allclose(res.astype(np.float64), exp.astype(np.float64)) + + n = np.array(_nest_me([5, 25], k=levels)) + exp_nucleus = {1: [120, math.factorial(25)], + # correctness of factorial{2,k}() is tested elsewhere + 2: [15, special.factorial2(25, exact=True)], + 3: [10, special.factorialk(25, 3, exact=True)]} + + _check(special.factorial(n, exact=exact), exp_nucleus[1]) + _check(special.factorial2(n, exact=exact), exp_nucleus[2]) + _check(special.factorialk(n, 3, exact=exact), exp_nucleus[3]) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dtype", [ + None, int, np.int8, np.int16, np.int32, np.int64, + np.uint8, np.uint16, np.uint32, np.uint64 + ]) + @pytest.mark.parametrize("dim", range(0, 5)) + def test_factorialx_array_dimension(self, dim, dtype, exact): + n = np.array(5, dtype=dtype, ndmin=dim) + exp = {1: 120, 2: 15, 3: 10} + assert_allclose(special.factorial(n, exact=exact), + np.array(exp[1], ndmin=dim)) + assert_allclose(special.factorial2(n, exact=exact), + np.array(exp[2], ndmin=dim)) + assert_allclose(special.factorialk(n, 3, exact=exact), + np.array(exp[3], ndmin=dim)) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("level", range(1, 5)) + def test_factorialx_array_like(self, level, exact): + def _nest_me(x, k=1): + if k == 0: + return x + else: + return _nest_me([x], k-1) + + n = _nest_me([5], k=level-1) # nested list + exp_nucleus = {1: 120, 2: 15, 3: 10} + assert_func = assert_array_equal if exact else assert_allclose + assert_func(special.factorial(n, exact=exact), + np.array(exp_nucleus[1], ndmin=level)) + assert_func(special.factorial2(n, exact=exact), + np.array(exp_nucleus[2], ndmin=level)) + assert_func(special.factorialk(n, 3, exact=exact), + np.array(exp_nucleus[3], ndmin=level)) + + @pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64]) + @pytest.mark.parametrize("exact,extend", + [(True, "zero"), (False, "zero"), (False, "complex")]) + def test_factorialx_uint(self, exact, extend, dtype): + # ensure that uint types work correctly as inputs + kw = {"exact": exact, "extend": extend} + assert_func = assert_array_equal if exact else assert_allclose + def _check(n): + n_ref = n.astype(np.int64) if isinstance(n, np.ndarray) else np.int64(n) + assert_func(special.factorial(n, **kw), special.factorial(n_ref, **kw)) + assert_func(special.factorial2(n, **kw), special.factorial2(n_ref, **kw)) + assert_func(special.factorialk(n, k=3, **kw), + special.factorialk(n_ref, k=3, **kw)) + _check(dtype(0)) + _check(dtype(1)) + _check(np.array(0, dtype=dtype)) + _check(np.array([0, 1], dtype=dtype)) + + # note that n=170 is the last integer such that factorial(n) fits float64 + @pytest.mark.parametrize('n', range(30, 180, 10)) + def test_factorial_accuracy(self, n): + # Compare exact=True vs False, i.e. that the accuracy of the + # approximation is better than the specified tolerance. + + rtol = 6e-14 if sys.platform == 'win32' else 1e-15 + # need to cast exact result to float due to numpy/numpy#21220 + assert_allclose(float(special.factorial(n, exact=True)), + special.factorial(n, exact=False), rtol=rtol) + assert_allclose(special.factorial([n], exact=True).astype(float), + special.factorial([n], exact=False), rtol=rtol) + + @pytest.mark.parametrize('n', + list(range(0, 22)) + list(range(30, 180, 10))) + def test_factorial_int_reference(self, n): + # Compare all with math.factorial + correct = math.factorial(n) + assert_array_equal(correct, special.factorial(n, exact=True)) + assert_array_equal(correct, special.factorial([n], exact=True)[0]) + + rtol = 8e-14 if sys.platform == 'win32' else 1e-15 + # need to cast exact result to float due to numpy/numpy#21220 + correct = float(correct) + assert_allclose(correct, special.factorial(n, exact=False), rtol=rtol) + assert_allclose(correct, special.factorial([n], exact=False)[0], rtol=rtol) + + # extend="complex" only works for exact=False + kw = {"exact": False, "extend": "complex"} + assert_allclose(correct, special.factorial(n, **kw), rtol=rtol) + assert_allclose(correct, special.factorial([n], **kw)[0], rtol=rtol) + + def test_factorial_float_reference(self): + def _check(n, expected): + rtol = 8e-14 if sys.platform == 'win32' else 1e-15 + assert_allclose(special.factorial(n), expected, rtol=rtol) + assert_allclose(special.factorial([n])[0], expected, rtol=rtol) + # using floats with `exact=True` raises an error for scalars and arrays + with pytest.raises(ValueError, match="`exact=True` only supports.*"): + special.factorial(n, exact=True) + with pytest.raises(ValueError, match="`exact=True` only supports.*"): + special.factorial([n], exact=True) + + # Reference values from mpmath for gamma(n+1) + _check(0.01, 0.994325851191506032181932988) + _check(1.11, 1.051609009483625091514147465) + _check(5.55, 314.9503192327208241614959052) + _check(11.1, 50983227.84411615655137170553) + _check(33.3, 2.493363339642036352229215273e+37) + _check(55.5, 9.479934358436729043289162027e+73) + _check(77.7, 3.060540559059579022358692625e+114) + _check(99.9, 5.885840419492871504575693337e+157) + # close to maximum for float64 + _check(170.6243, 1.79698185749571048960082e+308) + + def test_factorial_complex_reference(self): + def _check(n, expected): + rtol = 3e-15 if sys.platform == 'win32' else 2e-15 + kw = {"exact": False, "extend": "complex"} + assert_allclose(special.factorial(n, **kw), expected, rtol=rtol) + assert_allclose(special.factorial([n], **kw)[0], expected, rtol=rtol) + + # Reference values from mpmath.gamma(n+1) + # negative & complex values + _check(-0.5, expected=1.7724538509055160276) + _check(-0.5 + 0j, expected=1.7724538509055160276 + 0j) + _check(2 + 2j, expected=-0.42263728631120216694 + 0.87181425569650686062j) + # close to poles + _check(-0.9999, expected=9999.422883232725532) + _check(-1 + 0.0001j, expected=-0.57721565582674219 - 9999.9999010944009697j) + + @pytest.mark.parametrize("dtype", [np.int64, np.float64, + np.complex128, object]) + @pytest.mark.parametrize("extend", ["zero", "complex"]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dim", range(0, 5)) + # test empty & non-empty arrays, with nans and mixed + @pytest.mark.parametrize( + "content", + [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]], + ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"], + ) + def test_factorial_array_corner_cases(self, content, dim, exact, extend, dtype): + if dtype is object and SCIPY_ARRAY_API: + pytest.skip("object arrays unsupported in array API mode") + # get dtype without calling array constructor (that might fail or mutate) + if dtype is np.int64 and any(np.isnan(x) or (x != int(x)) for x in content): + pytest.skip("impossible combination") + if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content): + pytest.skip("impossible combination") + + kw = {"exact": exact, "extend": extend} + # np.array(x, ndim=0) will not be 0-dim. unless x is too + content = content if (dim > 0 or len(content) != 1) else content[0] + n = np.array(content, ndmin=dim, dtype=dtype) + + result = None + if extend == "complex" and exact: + with pytest.raises(ValueError, match="Incompatible options:.*"): + special.factorial(n, **kw) + elif not _is_subdtype(n.dtype, ["i", "f", "c"]): + with pytest.raises(ValueError, match="Unsupported data type.*"): + special.factorial(n, **kw) + elif _is_subdtype(n.dtype, "c") and extend != "complex": + with pytest.raises(ValueError, match="In order to use non-integer.*"): + special.factorial(n, **kw) + elif exact and not _is_subdtype(n.dtype, "i"): + with pytest.raises(ValueError, match="`exact=True` only supports.*"): + special.factorial(n, **kw) + else: + result = special.factorial(n, **kw) + + if result is not None: + # use scalar case as reference; tested separately in *_scalar_corner_cases + ref = [special.factorial(x, **kw) for x in n.ravel()] + # unpack length-1 lists so that np.array(x, ndim=0) works correctly + ref = ref[0] if len(ref) == 1 else ref + # result is empty if and only if n is empty, and has the same dimension + # as n; dtype stays the same, except when not empty and not exact: + if n.size: + cx = (extend == "complex") and _is_subdtype(n.dtype, "c") + dtype = np.complex128 if cx else (native_int if exact else np.float64) + expected = np.array(ref, ndmin=dim, dtype=dtype) + assert_really_equal(result, expected, rtol=1e-15) + + @pytest.mark.parametrize("extend", ["zero", "complex"]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None], + ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"]) + def test_factorial_scalar_corner_cases(self, n, exact, extend): + kw = {"exact": exact, "extend": extend} + if extend == "complex" and exact: + with pytest.raises(ValueError, match="Incompatible options:.*"): + special.factorial(n, **kw) + elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]): + with pytest.raises(ValueError, match="Unsupported data type.*"): + special.factorial(n, **kw) + elif _is_subdtype(type(n), "c") and extend != "complex": + with pytest.raises(ValueError, match="In order to use non-integer.*"): + special.factorial(n, **kw) + elif n is None or np.isnan(n): + # account for dtype and whether extend="complex" + complexify = (extend == "complex") and _is_subdtype(type(n), "c") + expected = np.complex128("nan+nanj") if complexify else np.float64("nan") + assert_really_equal(special.factorial(n, **kw), expected) + elif exact and _is_subdtype(type(n), "f"): + with pytest.raises(ValueError, match="`exact=True` only supports.*"): + special.factorial(n, **kw) + else: + assert_equal(special.factorial(n, **kw), special.gamma(n + 1)) + + # use odd increment to make sure both odd & even numbers are tested! + @pytest.mark.parametrize('n', range(30, 180, 11)) + def test_factorial2_accuracy(self, n): + # Compare exact=True vs False, i.e. that the accuracy of the + # approximation is better than the specified tolerance. + + rtol = 2e-14 if sys.platform == 'win32' else 1e-15 + # need to cast exact result to float due to numpy/numpy#21220 + assert_allclose(float(special.factorial2(n, exact=True)), + special.factorial2(n, exact=False), rtol=rtol) + assert_allclose(special.factorial2([n], exact=True).astype(float), + special.factorial2([n], exact=False), rtol=rtol) + + @pytest.mark.parametrize('n', + list(range(0, 22)) + list(range(30, 180, 11))) + def test_factorial2_int_reference(self, n): + # Compare all with correct value + + # Cannot use np.product due to overflow + correct = functools.reduce(operator.mul, list(range(n, 0, -2)), 1) + + assert_array_equal(correct, special.factorial2(n, exact=True)) + assert_array_equal(correct, special.factorial2([n], exact=True)[0]) + + rtol = 2e-14 if sys.platform == 'win32' else 1e-15 + # need to cast exact result to float due to numpy/numpy#21220 + correct = float(correct) + assert_allclose(correct, special.factorial2(n, exact=False), rtol=rtol) + assert_allclose(correct, special.factorial2([n], exact=False)[0], rtol=rtol) + + # extend="complex" only works for exact=False + kw = {"exact": False, "extend": "complex"} + # approximation only matches exactly for `n == 1 (mod k)`, see docstring + if n % 2 == 1: + assert_allclose(correct, special.factorial2(n, **kw), rtol=rtol) + assert_allclose(correct, special.factorial2([n], **kw)[0], rtol=rtol) + + def test_factorial2_complex_reference(self): + # this tests for both floats and complex + def _check(n, expected): + rtol = 5e-15 + kw = {"exact": False, "extend": "complex"} + assert_allclose(special.factorial2(n, **kw), expected, rtol=rtol) + assert_allclose(special.factorial2([n], **kw)[0], expected, rtol=rtol) + + # Reference values from mpmath for: + # mpmath.power(2, n/2) * mpmath.gamma(n/2 + 1) * mpmath.sqrt(2 / mpmath.pi) + _check(3, expected=3) + _check(4, expected=special.factorial2(4) * math.sqrt(2 / math.pi)) + _check(20, expected=special.factorial2(20) * math.sqrt(2 / math.pi)) + # negative & complex values + _check(-0.5, expected=0.82217895866245855122) + _check(-0.5 + 0j, expected=0.82217895866245855122 + 0j) + _check(3 + 3j, expected=-1.0742236630142471526 + 1.4421398439387262897j) + # close to poles + _check(-1.9999, expected=7978.8918745523440682) + _check(-2 + 0.0001j, expected=0.0462499835314308444 - 7978.84559148876374493j) + + @pytest.mark.parametrize("dtype", [np.int64, np.float64, + np.complex128, object]) + @pytest.mark.parametrize("extend", ["zero", "complex"]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dim", range(0, 5)) + # test empty & non-empty arrays, with nans and mixed + @pytest.mark.parametrize( + "content", + [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]], + ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"], + ) + def test_factorial2_array_corner_cases(self, content, dim, exact, extend, dtype): + # get dtype without calling array constructor (that might fail or mutate) + if dtype == np.int64 and any(np.isnan(x) or (x != int(x)) for x in content): + pytest.skip("impossible combination") + if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content): + pytest.skip("impossible combination") + + kw = {"exact": exact, "extend": extend} + # np.array(x, ndim=0) will not be 0-dim. unless x is too + content = content if (dim > 0 or len(content) != 1) else content[0] + n = np.array(content, ndmin=dim, dtype=dtype) + + result = None + if extend == "complex" and exact: + with pytest.raises(ValueError, match="Incompatible options:.*"): + special.factorial2(n, **kw) + elif not _is_subdtype(n.dtype, ["i", "f", "c"]): + with pytest.raises(ValueError, match="Unsupported data type.*"): + special.factorial2(n, **kw) + elif _is_subdtype(n.dtype, ["f", "c"]) and extend != "complex": + with pytest.raises(ValueError, match="In order to use non-integer.*"): + special.factorial2(n, **kw) + else: + result = special.factorial2(n, **kw) + + if result is not None: + # use scalar case as reference; tested separately in *_scalar_corner_cases + ref = [special.factorial2(x, **kw) for x in n.ravel()] + # unpack length-1 lists so that np.array(x, ndim=0) works correctly + ref = ref[0] if len(ref) == 1 else ref + # result is empty if and only if n is empty, and has the same dimension + # as n; dtype stays the same, except when not empty and not exact: + if n.size: + cx = (extend == "complex") and _is_subdtype(n.dtype, "c") + dtype = np.complex128 if cx else (native_int if exact else np.float64) + expected = np.array(ref, ndmin=dim, dtype=dtype) + assert_really_equal(result, expected, rtol=2e-15) + + @pytest.mark.parametrize("extend", ["zero", "complex"]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None], + ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"]) + def test_factorial2_scalar_corner_cases(self, n, exact, extend): + kw = {"exact": exact, "extend": extend} + if extend == "complex" and exact: + with pytest.raises(ValueError, match="Incompatible options:.*"): + special.factorial2(n, **kw) + elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]): + with pytest.raises(ValueError, match="Unsupported data type.*"): + special.factorial2(n, **kw) + elif _is_subdtype(type(n), ["f", "c"]) and extend != "complex": + with pytest.raises(ValueError, match="In order to use non-integer.*"): + special.factorial2(n, **kw) + elif n is None or np.isnan(n): + # account for dtype and whether extend="complex" + complexify = (extend == "complex") and _is_subdtype(type(n), "c") + expected = np.complex128("nan+nanj") if complexify else np.float64("nan") + assert_really_equal(special.factorial2(n, **kw), expected) + else: + expected = self.factorialk_ref(n, k=2, **kw) + assert_really_equal(special.factorial2(n, **kw), expected, rtol=1e-15) + + @pytest.mark.parametrize("k", range(1, 5)) + # note that n=170 is the last integer such that factorial(n) fits float64; + # use odd increment to make sure both odd & even numbers are tested + @pytest.mark.parametrize('n', range(170, 20, -29)) + def test_factorialk_accuracy(self, n, k): + # Compare exact=True vs False, i.e. that the accuracy of the + # approximation is better than the specified tolerance. + + rtol = 6e-14 if sys.platform == 'win32' else 2e-14 + # need to cast exact result to float due to numpy/numpy#21220 + assert_allclose(float(special.factorialk(n, k=k, exact=True)), + special.factorialk(n, k=k, exact=False), rtol=rtol) + assert_allclose(special.factorialk([n], k=k, exact=True).astype(float), + special.factorialk([n], k=k, exact=False), rtol=rtol) + + @pytest.mark.parametrize('k', list(range(1, 5)) + [10, 20]) + @pytest.mark.parametrize('n', + list(range(0, 22)) + list(range(22, 100, 11))) + def test_factorialk_int_reference(self, n, k): + # Compare all with correct value + + # Would be nice to use np.product here, but that's + # broken on windows, see numpy/numpy#21219 + correct = functools.reduce(operator.mul, list(range(n, 0, -k)), 1) + + assert_array_equal(correct, special.factorialk(n, k, exact=True)) + assert_array_equal(correct, special.factorialk([n], k, exact=True)[0]) + + rtol = 3e-14 if sys.platform == 'win32' else 1e-14 + # need to cast exact result to float due to numpy/numpy#21220 + correct = float(correct) + assert_allclose(correct, special.factorialk(n, k, exact=False), rtol=rtol) + assert_allclose(correct, special.factorialk([n], k, exact=False)[0], rtol=rtol) + + # extend="complex" only works for exact=False + kw = {"k": k, "exact": False, "extend": "complex"} + # approximation only matches exactly for `n == 1 (mod k)`, see docstring + if n % k == 1: + rtol = 2e-14 + assert_allclose(correct, special.factorialk(n, **kw), rtol=rtol) + assert_allclose(correct, special.factorialk([n], **kw)[0], rtol=rtol) + + def test_factorialk_complex_reference(self): + # this tests for both floats and complex + def _check(n, k, exp): + rtol = 1e-14 + kw = {"k": k, "exact": False, "extend": "complex"} + assert_allclose(special.factorialk(n, **kw), exp, rtol=rtol) + assert_allclose(special.factorialk([n], **kw)[0], exp, rtol=rtol) + + # Reference values from mpmath for: + # mpmath.power(k, (n-1)/k) * mpmath.gamma(n/k + 1) / mpmath.gamma(1/k + 1) + _check(n=4, k=3, exp=special.factorialk(4, k=3, exact=True)) + _check(n=5, k=3, exp=7.29011132947227083) + _check(n=6.5, k=3, exp=19.6805080113566010) + # non-integer k + _check(n=3, k=2.5, exp=2.58465740293218541) + _check(n=11, k=2.5, exp=1963.5) # ==11*8.5*6*3.5; c.f. n == 1 (mod k) + _check(n=-3 + 3j + 1, k=-3 + 3j, exp=-2 + 3j) + # complex values + _check(n=4 + 4j, k=4, exp=-0.67855904082768043854 + 2.1993925819930311497j) + _check(n=4, k=4 - 4j, exp=1.9775338957222718742 + 0.92607172675423901371j) + _check(n=4 + 4j, k=4 - 4j, exp=0.1868492880824934475 + 0.87660580316894290247j) + # negative values + _check(n=-0.5, k=3, exp=0.72981013240713739354) + _check(n=-0.5 + 0j, k=3, exp=0.72981013240713739354 + 0j) + _check(n=2.9, k=-0.7, exp=0.45396591474966867296 + 0.56925525174685228866j) + _check(n=-0.6, k=-0.7, exp=-0.07190820089634757334 - 0.090170031876701730081j) + # close to poles + _check(n=-2.9999, k=3, exp=7764.7170695908828364) + _check(n=-3 + 0.0001j, k=3, exp=0.1349475632879599864 - 7764.5821055158365027j) + + @pytest.mark.parametrize("dtype", [np.int64, np.float64, + np.complex128, object]) + @pytest.mark.parametrize("extend", ["zero", "complex"]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dim", range(0, 5)) + # test empty & non-empty arrays, with nans and mixed + @pytest.mark.parametrize( + "content", + [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]], + ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"], + ) + def test_factorialk_array_corner_cases(self, content, dim, exact, extend, dtype): + # get dtype without calling array constructor (that might fail or mutate) + if dtype == np.int64 and any(np.isnan(x) or (x != int(x)) for x in content): + pytest.skip("impossible combination") + if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content): + pytest.skip("impossible combination") + + kw = {"k": 3, "exact": exact, "extend": extend} + # np.array(x, ndim=0) will not be 0-dim. unless x is too + content = content if (dim > 0 or len(content) != 1) else content[0] + n = np.array(content, ndmin=dim, dtype=dtype) + + result = None + if extend == "complex" and exact: + with pytest.raises(ValueError, match="Incompatible options:.*"): + special.factorialk(n, **kw) + elif not _is_subdtype(n.dtype, ["i", "f", "c"]): + with pytest.raises(ValueError, match="Unsupported data type.*"): + special.factorialk(n, **kw) + elif _is_subdtype(n.dtype, ["f", "c"]) and extend != "complex": + with pytest.raises(ValueError, match="In order to use non-integer.*"): + special.factorialk(n, **kw) + else: + result = special.factorialk(n, **kw) + + if result is not None: + # use scalar case as reference; tested separately in *_scalar_corner_cases + ref = [special.factorialk(x, **kw) for x in n.ravel()] + # unpack length-1 lists so that np.array(x, ndim=0) works correctly + ref = ref[0] if len(ref) == 1 else ref + # result is empty if and only if n is empty, and has the same dimension + # as n; dtype stays the same, except when not empty and not exact: + if n.size: + cx = (extend == "complex") and _is_subdtype(n.dtype, "c") + dtype = np.complex128 if cx else (native_int if exact else np.float64) + expected = np.array(ref, ndmin=dim, dtype=dtype) + assert_really_equal(result, expected, rtol=2e-15) + + @pytest.mark.parametrize("extend", ["zero", "complex"]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("k", range(1, 5)) + @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None], + ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"]) + def test_factorialk_scalar_corner_cases(self, n, k, exact, extend): + kw = {"k": k, "exact": exact, "extend": extend} + if extend == "complex" and exact: + with pytest.raises(ValueError, match="Incompatible options:.*"): + special.factorialk(n, **kw) + elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]): + with pytest.raises(ValueError, match="Unsupported data type.*"): + special.factorialk(n, **kw) + elif _is_subdtype(type(n), ["f", "c"]) and extend != "complex": + with pytest.raises(ValueError, match="In order to use non-integer.*"): + special.factorialk(n, **kw) + elif n is None or np.isnan(n): + # account for dtype and whether extend="complex" + complexify = (extend == "complex") and _is_subdtype(type(n), "c") + expected = np.complex128("nan+nanj") if complexify else np.float64("nan") + assert_really_equal(special.factorialk(n, **kw), expected) + else: + expected = self.factorialk_ref(n, **kw) + assert_really_equal(special.factorialk(n, **kw), expected, rtol=1e-15) + + @pytest.mark.parametrize("boxed", [True, False]) + @pytest.mark.parametrize("exact,extend", + [(True, "zero"), (False, "zero"), (False, "complex")]) + @pytest.mark.parametrize("k", [-1, -1.0, 0, 0.0, 0 + 1j, 1.1, np.nan]) + def test_factorialk_raises_k_complex(self, k, exact, extend, boxed): + n = [1] if boxed else 1 + kw = {"k": k, "exact": exact, "extend": extend} + if extend == "zero": + msg = "In order to use non-integer.*" + if _is_subdtype(type(k), "i") and (k < 1): + msg = "For `extend='zero'`.*" + with pytest.raises(ValueError, match=msg): + special.factorialk(n, **kw) + elif k == 0: + with pytest.raises(ValueError, match="Parameter k cannot be zero!"): + special.factorialk(n, **kw) + else: + # no error + special.factorialk(n, **kw) + + @pytest.mark.parametrize("boxed", [True, False]) + @pytest.mark.parametrize("exact,extend", + [(True, "zero"), (False, "zero"), (False, "complex")]) + # neither integer, float nor complex + @pytest.mark.parametrize("k", ["string", np.datetime64("nat")], + ids=["string", "NaT"]) + def test_factorialk_raises_k_other(self, k, exact, extend, boxed): + n = [1] if boxed else 1 + kw = {"k": k, "exact": exact, "extend": extend} + with pytest.raises(ValueError, match="Unsupported data type.*"): + special.factorialk(n, **kw) + + @pytest.mark.parametrize("exact,extend", + [(True, "zero"), (False, "zero"), (False, "complex")]) + @pytest.mark.parametrize("k", range(1, 12)) + def test_factorialk_dtype(self, k, exact, extend): + kw = {"k": k, "exact": exact, "extend": extend} + if exact and k in _FACTORIALK_LIMITS_64BITS.keys(): + n = np.array([_FACTORIALK_LIMITS_32BITS[k]]) + assert_equal(special.factorialk(n, **kw).dtype, np_long) + assert_equal(special.factorialk(n + 1, **kw).dtype, np.int64) + # assert maximality of limits for given dtype + assert special.factorialk(n + 1, **kw) > np.iinfo(np.int32).max + + n = np.array([_FACTORIALK_LIMITS_64BITS[k]]) + assert_equal(special.factorialk(n, **kw).dtype, np.int64) + assert_equal(special.factorialk(n + 1, **kw).dtype, object) + assert special.factorialk(n + 1, **kw) > np.iinfo(np.int64).max + else: + n = np.array([_FACTORIALK_LIMITS_64BITS.get(k, 1)]) + # for exact=True and k >= 10, we always return object; + # for exact=False it's always float (unless input is complex) + dtype = object if exact else np.float64 + assert_equal(special.factorialk(n, **kw).dtype, dtype) + + def test_factorial_mixed_nan_inputs(self): + x = np.array([np.nan, 1, 2, 3, np.nan]) + expected = np.array([np.nan, 1, 2, 6, np.nan]) + assert_equal(special.factorial(x, exact=False), expected) + with pytest.raises(ValueError, match="`exact=True` only supports.*"): + special.factorial(x, exact=True) + + +class TestFresnel: + @pytest.mark.parametrize("z, s, c", [ + # some positive value + (.5, 0.064732432859999287, 0.49234422587144644), + (.5 + .0j, 0.064732432859999287, 0.49234422587144644), + # negative half annulus + # https://github.com/scipy/scipy/issues/12309 + # Reference values can be reproduced with + # https://www.wolframalpha.com/input/?i=FresnelS%5B-2.0+%2B+0.1i%5D + # https://www.wolframalpha.com/input/?i=FresnelC%5B-2.0+%2B+0.1i%5D + ( + -2.0 + 0.1j, + -0.3109538687728942-0.0005870728836383176j, + -0.4879956866358554+0.10670801832903172j + ), + ( + -0.1 - 1.5j, + -0.03918309471866977+0.7197508454568574j, + 0.09605692502968956-0.43625191013617465j + ), + # a different algorithm kicks in for "large" values, i.e., |z| >= 4.5, + # make sure to test both float and complex values; a different + # algorithm is used + (6.0, 0.44696076, 0.49953147), + (6.0 + 0.0j, 0.44696076, 0.49953147), + (6.0j, -0.44696076j, 0.49953147j), + (-6.0 + 0.0j, -0.44696076, -0.49953147), + (-6.0j, 0.44696076j, -0.49953147j), + # inf + (np.inf, 0.5, 0.5), + (-np.inf, -0.5, -0.5), + ]) + def test_fresnel_values(self, z, s, c): + frs = array(special.fresnel(z)) + assert_array_almost_equal(frs, array([s, c]), 8) + + # values from pg 329 Table 7.11 of A & S + # slightly corrected in 4th decimal place + def test_fresnel_zeros(self): + szo, czo = special.fresnel_zeros(5) + assert_array_almost_equal(szo, + array([2.0093+0.2885j, + 2.8335+0.2443j, + 3.4675+0.2185j, + 4.0026+0.2009j, + 4.4742+0.1877j]),3) + assert_array_almost_equal(czo, + array([1.7437+0.3057j, + 2.6515+0.2529j, + 3.3204+0.2240j, + 3.8757+0.2047j, + 4.3611+0.1907j]),3) + vals1 = special.fresnel(szo)[0] + vals2 = special.fresnel(czo)[1] + assert_array_almost_equal(vals1,0,14) + assert_array_almost_equal(vals2,0,14) + + def test_fresnelc_zeros(self): + szo, czo = special.fresnel_zeros(6) + frc = special.fresnelc_zeros(6) + assert_array_almost_equal(frc,czo,12) + + def test_fresnels_zeros(self): + szo, czo = special.fresnel_zeros(5) + frs = special.fresnels_zeros(5) + assert_array_almost_equal(frs,szo,12) + + +class TestGamma: + def test_gamma(self): + gam = special.gamma(5) + assert_equal(gam,24.0) + + def test_gammaln(self): + gamln = special.gammaln(3) + lngam = log(special.gamma(3)) + assert_almost_equal(gamln,lngam,8) + + def test_gammainccinv(self): + gccinv = special.gammainccinv(.5,.5) + gcinv = special.gammaincinv(.5,.5) + assert_almost_equal(gccinv,gcinv,8) + + @with_special_errors + def test_gammaincinv(self): + y = special.gammaincinv(.4,.4) + x = special.gammainc(.4,y) + assert_almost_equal(x,0.4,1) + y = special.gammainc(10, 0.05) + x = special.gammaincinv(10, 2.5715803516000736e-20) + assert_almost_equal(0.05, x, decimal=10) + assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) + x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) + assert_almost_equal(11.0, x, decimal=10) + + @with_special_errors + def test_975(self): + # Regression test for ticket #975 -- switch point in algorithm + # check that things work OK at the point, immediately next floats + # around it, and a bit further away + pts = [0.25, + np.nextafter(0.25, 0), 0.25 - 1e-12, + np.nextafter(0.25, 1), 0.25 + 1e-12] + for xp in pts: + y = special.gammaincinv(.4, xp) + x = special.gammainc(0.4, y) + assert_allclose(x, xp, rtol=1e-12) + + def test_rgamma(self): + rgam = special.rgamma(8) + rlgam = 1/special.gamma(8) + assert_almost_equal(rgam,rlgam,8) + + def test_infinity(self): + assert_equal(special.rgamma(-1), 0) + + @pytest.mark.parametrize( + "x,expected", + [ + # infinities + ([-np.inf, np.inf], [np.nan, np.inf]), + # negative and positive zero + ([-0.0, 0.0], [-np.inf, np.inf]), + # small poles + (range(-32, 0), np.full(32, np.nan)), + # medium sized poles + (range(-1024, -32, 99), np.full(11, np.nan)), + # large pole + ([-4.141512231792294e+16], [np.nan]), + ] + ) + def test_poles(self, x, expected): + assert_array_equal(special.gamma(x), expected) + + +class TestHankel: + + def test_negv1(self): + assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) + + def test_hankel1(self): + hank1 = special.hankel1(1,.1) + hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) + assert_almost_equal(hank1,hankrl,8) + + def test_negv1e(self): + assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) + + def test_hankel1e(self): + hank1e = special.hankel1e(1,.1) + hankrle = special.hankel1(1,.1)*exp(-.1j) + assert_almost_equal(hank1e,hankrle,8) + + def test_negv2(self): + assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) + + def test_hankel2(self): + hank2 = special.hankel2(1,.1) + hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) + assert_almost_equal(hank2,hankrl2,8) + + def test_neg2e(self): + assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) + + def test_hankl2e(self): + hank2e = special.hankel2e(1,.1) + hankrl2e = special.hankel2e(1,.1) + assert_almost_equal(hank2e,hankrl2e,8) + + def test_hankel2_gh4517(self): + # Test edge case reported in https://github.com/scipy/scipy/issues/4517 + res = special.hankel2(0, 0) + assert np.isnan(res.real) + assert np.isposinf(res.imag) + + +class TestHyper: + def test_h1vp(self): + h1 = special.h1vp(1,.1) + h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) + assert_almost_equal(h1,h1real,8) + + def test_h2vp(self): + h2 = special.h2vp(1,.1) + h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) + assert_almost_equal(h2,h2real,8) + + def test_hyp0f1(self): + # scalar input + assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) + assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) + + # float input, expected values match mpmath + x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) + expected = np.array([0.58493659229143, 0.70566805723127, 1.0, + 1.37789689539747, 1.60373685288480]) + assert_allclose(x, expected, rtol=1e-12) + + # complex input + x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) + assert_allclose(x, expected.astype(complex), rtol=1e-12) + + # test broadcasting + x1 = [0.5, 1.5, 2.5] + x2 = [0, 1, 0.5] + x = special.hyp0f1(x1, x2) + expected = [1.0, 1.8134302039235093, 1.21482702689997] + assert_allclose(x, expected, rtol=1e-12) + x = special.hyp0f1(np.vstack([x1] * 2), x2) + assert_allclose(x, np.vstack([expected] * 2), rtol=1e-12) + assert_raises(ValueError, special.hyp0f1, + np.vstack([x1] * 3), [0, 1]) + + def test_hyp0f1_gh5764(self): + # Just checks the point that failed; there's a more systematic + # test in test_mpmath + res = special.hyp0f1(0.8, 0.5 + 0.5*1J) + # The expected value was generated using mpmath + assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) + + def test_hyp1f1(self): + hyp1 = special.hyp1f1(.1,.1,.3) + assert_almost_equal(hyp1, 1.3498588075760032,7) + + # test contributed by Moritz Deger (2008-05-29) + # https://github.com/scipy/scipy/issues/1186 (Trac #659) + + # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: + # produced with test_hyp1f1.nb + ref_data = array([ + [-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], + [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], + [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], + [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], + [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], + [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], + [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], + [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], + [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], + [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], + [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], + [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], + [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], + [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], + [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], + [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], + [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], + [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], + [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], + [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], + [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], + [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], + [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], + [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], + [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], + [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], + [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], + [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], + [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], + [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], + [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], + [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], + [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], + [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], + [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], + [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], + [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], + [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], + [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], + [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], + [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], + [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], + [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], + [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], + [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], + [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], + [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], + [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], + [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], + [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], + [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], + [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], + [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], + [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], + [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], + [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], + [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], + [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], + [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], + [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], + [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], + [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], + [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], + [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], + [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], + [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], + [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], + [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], + [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], + [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], + [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], + [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], + [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], + [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], + [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], + [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], + [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], + [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], + [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], + [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], + [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], + [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], + [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], + [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], + [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], + [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], + [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], + [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], + [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], + [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], + [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], + [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], + [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], + [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], + [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], + [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], + [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], + [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], + [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], + [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00] + ]) + + for a,b,c,expected in ref_data: + result = special.hyp1f1(a,b,c) + assert_(abs(expected - result)/expected < 1e-4) + + def test_hyp1f1_gh2957(self): + hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) + hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) + assert_almost_equal(hyp1, hyp2, 12) + + def test_hyp1f1_gh2282(self): + hyp = special.hyp1f1(0.5, 1.5, -1000) + assert_almost_equal(hyp, 0.028024956081989643, 12) + + def test_hyp2f1(self): + # a collection of special cases taken from AMS 55 + values = [ + [0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], + [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], + [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], + [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], + [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], + [3, 4, 8, 1, + special.gamma(8) * special.gamma(8-4-3) + / special.gamma(8-3) / special.gamma(8-4)], + [3, 2, 3-2+1, -1, + 1./2**3*sqrt(pi) * special.gamma(1+3-2) + / special.gamma(1+0.5*3-2) / special.gamma(0.5+0.5*3)], + [5, 2, 5-2+1, -1, + 1./2**5*sqrt(pi) * special.gamma(1+5-2) + / special.gamma(1+0.5*5-2) / special.gamma(0.5+0.5*5)], + [4, 0.5+4, 1.5-2*4, -1./3, + (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4) + / special.gamma(3./2) / special.gamma(4./3-2*4)], + # and some others + # ticket #424 + [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], + # negative integer a or b, with c-a-b integer and x > 0.9 + [-2,3,1,0.95,0.715], + [2,-3,1,0.95,-0.007], + [-6,3,1,0.95,0.0000810625], + [2,-5,1,0.95,-0.000029375], + # huge negative integers + (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), + (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), + ] + for i, (a, b, c, x, v) in enumerate(values): + cv = special.hyp2f1(a, b, c, x) + assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) + + def test_hyperu(self): + val1 = special.hyperu(1,0.1,100) + assert_almost_equal(val1,0.0098153,7) + a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] + a,b = asarray(a), asarray(b) + z = 0.5 + hypu = special.hyperu(a,b,z) + hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / + (special.gamma(1+a-b)*special.gamma(b)) - + z**(1-b)*special.hyp1f1(1+a-b,2-b,z) + / (special.gamma(a)*special.gamma(2-b))) + assert_array_almost_equal(hypu,hprl,12) + + def test_hyperu_gh2287(self): + assert_almost_equal(special.hyperu(1, 1.5, 20.2), + 0.048360918656699191, 12) + + +class TestBessel: + def test_itj0y0(self): + it0 = array(special.itj0y0(.2)) + assert_array_almost_equal( + it0, + array([0.19933433254006822, -0.34570883800412566]), + 8, + ) + + def test_it2j0y0(self): + it2 = array(special.it2j0y0(.2)) + assert_array_almost_equal( + it2, + array([0.0049937546274601858, -0.43423067011231614]), + 8, + ) + + def test_negv_iv(self): + assert_equal(special.iv(3,2), special.iv(-3,2)) + + def test_j0(self): + oz = special.j0(.1) + ozr = special.jn(0,.1) + assert_almost_equal(oz,ozr,8) + + def test_j1(self): + o1 = special.j1(.1) + o1r = special.jn(1,.1) + assert_almost_equal(o1,o1r,8) + + def test_jn(self): + jnnr = special.jn(1,.2) + assert_almost_equal(jnnr,0.099500832639235995,8) + + def test_negv_jv(self): + assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) + + def test_jv(self): + values = [[0, 0.1, 0.99750156206604002], + [2./3, 1e-8, 0.3239028506761532e-5], + [2./3, 1e-10, 0.1503423854873779e-6], + [3.1, 1e-10, 0.1711956265409013e-32], + [2./3, 4.0, -0.2325440850267039], + ] + for i, (v, x, y) in enumerate(values): + yc = special.jv(v, x) + assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) + + def test_negv_jve(self): + assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) + + def test_jve(self): + jvexp = special.jve(1,.2) + assert_almost_equal(jvexp,0.099500832639235995,8) + jvexp1 = special.jve(1,.2+1j) + z = .2+1j + jvexpr = special.jv(1,z)*exp(-abs(z.imag)) + assert_almost_equal(jvexp1,jvexpr,8) + + def test_jn_zeros(self): + jn0 = special.jn_zeros(0,5) + jn1 = special.jn_zeros(1,5) + assert_array_almost_equal(jn0,array([2.4048255577, + 5.5200781103, + 8.6537279129, + 11.7915344391, + 14.9309177086]),4) + assert_array_almost_equal(jn1,array([3.83171, + 7.01559, + 10.17347, + 13.32369, + 16.47063]),4) + + jn102 = special.jn_zeros(102,5) + assert_allclose(jn102, array([110.89174935992040343, + 117.83464175788308398, + 123.70194191713507279, + 129.02417238949092824, + 134.00114761868422559]), rtol=1e-13) + + jn301 = special.jn_zeros(301,5) + assert_allclose(jn301, array([313.59097866698830153, + 323.21549776096288280, + 331.22338738656748796, + 338.39676338872084500, + 345.03284233056064157]), rtol=1e-13) + + def test_jn_zeros_slow(self): + jn0 = special.jn_zeros(0, 300) + assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) + assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) + assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) + + jn10 = special.jn_zeros(10, 300) + assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) + assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) + assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) + + jn3010 = special.jn_zeros(3010,5) + assert_allclose(jn3010, array([3036.86590780927, + 3057.06598526482, + 3073.66360690272, + 3088.37736494778, + 3101.86438139042]), rtol=1e-8) + + def test_jnjnp_zeros(self): + jn = special.jn + + def jnp(n, x): + return (jn(n-1,x) - jn(n+1,x))/2 + for nt in range(1, 30): + z, n, m, t = special.jnjnp_zeros(nt) + for zz, nn, tt in zip(z, n, t): + if tt == 0: + assert_allclose(jn(nn, zz), 0, atol=1e-6) + elif tt == 1: + assert_allclose(jnp(nn, zz), 0, atol=1e-6) + else: + raise AssertionError("Invalid t return for nt=%d" % nt) + + def test_jnp_zeros(self): + jnp = special.jnp_zeros(1,5) + assert_array_almost_equal(jnp, array([1.84118, + 5.33144, + 8.53632, + 11.70600, + 14.86359]),4) + jnp = special.jnp_zeros(443,5) + assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) + + def test_jnyn_zeros(self): + jnz = special.jnyn_zeros(1,5) + assert_array_almost_equal(jnz,(array([3.83171, + 7.01559, + 10.17347, + 13.32369, + 16.47063]), + array([1.84118, + 5.33144, + 8.53632, + 11.70600, + 14.86359]), + array([2.19714, + 5.42968, + 8.59601, + 11.74915, + 14.89744]), + array([3.68302, + 6.94150, + 10.12340, + 13.28576, + 16.44006])),5) + + def test_jvp(self): + jvprim = special.jvp(2,2) + jv0 = (special.jv(1,2)-special.jv(3,2))/2 + assert_almost_equal(jvprim,jv0,10) + + def test_k0(self): + ozk = special.k0(.1) + ozkr = special.kv(0,.1) + assert_almost_equal(ozk,ozkr,8) + + def test_k0e(self): + ozke = special.k0e(.1) + ozker = special.kve(0,.1) + assert_almost_equal(ozke,ozker,8) + + def test_k1(self): + o1k = special.k1(.1) + o1kr = special.kv(1,.1) + assert_almost_equal(o1k,o1kr,8) + + def test_k1e(self): + o1ke = special.k1e(.1) + o1ker = special.kve(1,.1) + assert_almost_equal(o1ke,o1ker,8) + + def test_jacobi(self): + a = 5*np.random.random() - 1 + b = 5*np.random.random() - 1 + P0 = special.jacobi(0,a,b) + P1 = special.jacobi(1,a,b) + P2 = special.jacobi(2,a,b) + P3 = special.jacobi(3,a,b) + + assert_array_almost_equal(P0.c,[1],13) + assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) + cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] + p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] + assert_array_almost_equal(P2.c,array(p2c)/8.0,13) + cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), + 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] + p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] + assert_array_almost_equal(P3.c,array(p3c)/48.0,13) + + def test_kn(self): + kn1 = special.kn(0,.2) + assert_almost_equal(kn1,1.7527038555281462,8) + + def test_negv_kv(self): + assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) + + def test_kv0(self): + kv0 = special.kv(0,.2) + assert_almost_equal(kv0, 1.7527038555281462, 10) + + def test_kv1(self): + kv1 = special.kv(1,0.2) + assert_almost_equal(kv1, 4.775972543220472, 10) + + def test_kv2(self): + kv2 = special.kv(2,0.2) + assert_almost_equal(kv2, 49.51242928773287, 10) + + def test_kn_largeorder(self): + assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) + + def test_kv_largearg(self): + assert_equal(special.kv(0, 1e19), 0) + + def test_negv_kve(self): + assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) + + def test_kve(self): + kve1 = special.kve(0,.2) + kv1 = special.kv(0,.2)*exp(.2) + assert_almost_equal(kve1,kv1,8) + z = .2+1j + kve2 = special.kve(0,z) + kv2 = special.kv(0,z)*exp(z) + assert_almost_equal(kve2,kv2,8) + + def test_kvp_v0n1(self): + z = 2.2 + assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) + + def test_kvp_n1(self): + v = 3. + z = 2.2 + xc = -special.kv(v+1,z) + v/z*special.kv(v,z) + x = special.kvp(v,z, n=1) + assert_almost_equal(xc, x, 10) # this function (kvp) is broken + + def test_kvp_n2(self): + v = 3. + z = 2.2 + xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z + x = special.kvp(v, z, n=2) + assert_almost_equal(xc, x, 10) + + def test_y0(self): + oz = special.y0(.1) + ozr = special.yn(0,.1) + assert_almost_equal(oz,ozr,8) + + def test_y1(self): + o1 = special.y1(.1) + o1r = special.yn(1,.1) + assert_almost_equal(o1,o1r,8) + + def test_y0_zeros(self): + yo,ypo = special.y0_zeros(2) + zo,zpo = special.y0_zeros(2,complex=1) + all = r_[yo,zo] + allval = r_[ypo,zpo] + assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) + assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) + + def test_y1_zeros(self): + y1 = special.y1_zeros(1) + assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) + + def test_y1p_zeros(self): + y1p = special.y1p_zeros(1,complex=1) + assert_array_almost_equal( + y1p, + (array([0.5768+0.904j]), array([-0.7635+0.5892j])), + 3, + ) + + def test_yn_zeros(self): + an = special.yn_zeros(4,2) + assert_array_almost_equal(an,array([5.64515, 9.36162]),5) + an = special.yn_zeros(443,5) + assert_allclose(an, [450.13573091578090314, + 463.05692376675001542, + 472.80651546418663566, + 481.27353184725625838, + 488.98055964441374646], + rtol=1e-15,) + + def test_ynp_zeros(self): + ao = special.ynp_zeros(0,2) + assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) + ao = special.ynp_zeros(43,5) + assert_allclose(special.yvp(43, ao), 0, atol=1e-15) + ao = special.ynp_zeros(443,5) + assert_allclose(special.yvp(443, ao), 0, atol=1e-9) + + def test_ynp_zeros_large_order(self): + ao = special.ynp_zeros(443,5) + assert_allclose(special.yvp(443, ao), 0, atol=1e-14) + + def test_yn(self): + yn2n = special.yn(1,.2) + assert_almost_equal(yn2n,-3.3238249881118471,8) + + def test_yn_gh_20405(self): + # Enforce correct asymptotic behavior for large n. + observed = cephes.yn(500, 1) + assert observed == -np.inf + + def test_negv_yv(self): + assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) + + def test_yv(self): + yv2 = special.yv(1,.2) + assert_almost_equal(yv2,-3.3238249881118471,8) + + def test_negv_yve(self): + assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) + + def test_yve(self): + yve2 = special.yve(1,.2) + assert_almost_equal(yve2,-3.3238249881118471,8) + yve2r = special.yv(1,.2+1j)*exp(-1) + yve22 = special.yve(1,.2+1j) + assert_almost_equal(yve22,yve2r,8) + + def test_yvp(self): + yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 + yvp1 = special.yvp(2,.2) + assert_array_almost_equal(yvp1,yvpr,10) + + def _cephes_vs_amos_points(self): + """Yield points at which to compare Cephes implementation to AMOS""" + # check several points, including large-amplitude ones + v = [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301] + z = [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, + 10003] + yield from itertools.product(v, z) + + # check half-integers; these are problematic points at least + # for cephes/iv + yield from itertools.product(0.5 + arange(-60, 60), [3.5]) + + def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): + for v, z in self._cephes_vs_amos_points(): + if skip is not None and skip(v, z): + continue + c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) + if np.isinf(c1): + assert_(np.abs(c2) >= 1e300, (v, z)) + elif np.isnan(c1): + assert_(c2.imag != 0, (v, z)) + else: + assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) + if v == int(v): + assert_allclose(c3, c2, err_msg=(v, z), + rtol=rtol, atol=atol) + + @pytest.mark.xfail(platform.machine() == 'ppc64le', + reason="fails on ppc64le") + def test_jv_cephes_vs_amos(self): + self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) + + @pytest.mark.xfail(platform.machine() == 'ppc64le', + reason="fails on ppc64le") + def test_yv_cephes_vs_amos(self): + self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) + + def test_yv_cephes_vs_amos_only_small_orders(self): + def skipper(v, z): + return abs(v) > 50 + self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, + skip=skipper) + + def test_iv_cephes_vs_amos(self): + with np.errstate(all='ignore'): + self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) + + @pytest.mark.slow + def test_iv_cephes_vs_amos_mass_test(self): + N = 1000000 + np.random.seed(1) + v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) + x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) + + imsk = (np.random.randint(8, size=N) == 0) + v[imsk] = v[imsk].astype(np.int64) + + with np.errstate(all='ignore'): + c1 = special.iv(v, x) + c2 = special.iv(v, x+0j) + + # deal with differences in the inf and zero cutoffs + c1[abs(c1) > 1e300] = np.inf + c2[abs(c2) > 1e300] = np.inf + c1[abs(c1) < 1e-300] = 0 + c2[abs(c2) < 1e-300] = 0 + + dc = abs(c1/c2 - 1) + dc[np.isnan(dc)] = 0 + + k = np.argmax(dc) + + # Most error apparently comes from AMOS and not our implementation; + # there are some problems near integer orders there + assert_( + dc[k] < 2e-7, + (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j)) + ) + + def test_kv_cephes_vs_amos(self): + self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) + self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) + + def test_ticket_623(self): + assert_allclose(special.jv(3, 4), 0.43017147387562193) + assert_allclose(special.jv(301, 1300), 0.0183487151115275) + assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) + + def test_ticket_853(self): + """Negative-order Bessels""" + # cephes + assert_allclose(special.jv(-1, 1), -0.4400505857449335) + assert_allclose(special.jv(-2, 1), 0.1149034849319005) + assert_allclose(special.yv(-1, 1), 0.7812128213002887) + assert_allclose(special.yv(-2, 1), -1.650682606816255) + assert_allclose(special.iv(-1, 1), 0.5651591039924851) + assert_allclose(special.iv(-2, 1), 0.1357476697670383) + assert_allclose(special.kv(-1, 1), 0.6019072301972347) + assert_allclose(special.kv(-2, 1), 1.624838898635178) + assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) + assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) + assert_allclose(special.iv(-0.5, 1), 1.231200214592967) + assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) + # amos + assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) + assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) + assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) + assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) + + assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) + assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) + assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) + assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) + + assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) + assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) + assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) + assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) + + assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) + assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) + assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) + assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) + + assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) + assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) + assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) + assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) + + assert_allclose( + special.hankel1(-0.5, 1+1j), + special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j) + ) + assert_allclose( + special.hankel2(-0.5, 1+1j), + special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j) + ) + + def test_ticket_854(self): + """Real-valued Bessel domains""" + assert_(isnan(special.jv(0.5, -1))) + assert_(isnan(special.iv(0.5, -1))) + assert_(isnan(special.yv(0.5, -1))) + assert_(isnan(special.yv(1, -1))) + assert_(isnan(special.kv(0.5, -1))) + assert_(isnan(special.kv(1, -1))) + assert_(isnan(special.jve(0.5, -1))) + assert_(isnan(special.ive(0.5, -1))) + assert_(isnan(special.yve(0.5, -1))) + assert_(isnan(special.yve(1, -1))) + assert_(isnan(special.kve(0.5, -1))) + assert_(isnan(special.kve(1, -1))) + assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) + assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) + + def test_gh_7909(self): + assert_(special.kv(1.5, 0) == np.inf) + assert_(special.kve(1.5, 0) == np.inf) + + def test_ticket_503(self): + """Real-valued Bessel I overflow""" + assert_allclose(special.iv(1, 700), 1.528500390233901e302) + assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) + + def test_iv_hyperg_poles(self): + assert_allclose(special.iv(-0.5, 1), 1.231200214592967) + + def iv_series(self, v, z, n=200): + k = arange(0, n).astype(double) + r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) + r[isnan(r)] = inf + r = exp(r) + err = abs(r).max() * finfo(double).eps * n + abs(r[-1])*10 + return r.sum(), err + + def test_i0_series(self): + for z in [1., 10., 200.5]: + value, err = self.iv_series(0, z) + assert_allclose(special.i0(z), value, atol=err, err_msg=z) + + def test_i1_series(self): + for z in [1., 10., 200.5]: + value, err = self.iv_series(1, z) + assert_allclose(special.i1(z), value, atol=err, err_msg=z) + + def test_iv_series(self): + for v in [-20., -10., -1., 0., 1., 12.49, 120.]: + for z in [1., 10., 200.5, -1+2j]: + value, err = self.iv_series(v, z) + assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) + + def test_i0(self): + values = [[0.0, 1.0], + [1e-10, 1.0], + [0.1, 0.9071009258], + [0.5, 0.6450352706], + [1.0, 0.4657596077], + [2.5, 0.2700464416], + [5.0, 0.1835408126], + [20.0, 0.0897803119], + ] + for i, (x, v) in enumerate(values): + cv = special.i0(x) * exp(-x) + assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) + + def test_i0e(self): + oize = special.i0e(.1) + oizer = special.ive(0,.1) + assert_almost_equal(oize,oizer,8) + + def test_i1(self): + values = [[0.0, 0.0], + [1e-10, 0.4999999999500000e-10], + [0.1, 0.0452984468], + [0.5, 0.1564208032], + [1.0, 0.2079104154], + [5.0, 0.1639722669], + [20.0, 0.0875062222], + ] + for i, (x, v) in enumerate(values): + cv = special.i1(x) * exp(-x) + assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) + + def test_i1e(self): + oi1e = special.i1e(.1) + oi1er = special.ive(1,.1) + assert_almost_equal(oi1e,oi1er,8) + + def test_iti0k0(self): + iti0 = array(special.iti0k0(5)) + assert_array_almost_equal( + iti0, + array([31.848667776169801, 1.5673873907283657]), + 5, + ) + + def test_it2i0k0(self): + it2k = special.it2i0k0(.1) + assert_array_almost_equal( + it2k, + array([0.0012503906973464409, 3.3309450354686687]), + 6, + ) + + def test_iv(self): + iv1 = special.iv(0,.1)*exp(-.1) + assert_almost_equal(iv1,0.90710092578230106,10) + + def test_negv_ive(self): + assert_equal(special.ive(3,2), special.ive(-3,2)) + + def test_ive(self): + ive1 = special.ive(0,.1) + iv1 = special.iv(0,.1)*exp(-.1) + assert_almost_equal(ive1,iv1,10) + + def test_ivp0(self): + assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) + + def test_ivp(self): + y = (special.iv(0,2) + special.iv(2,2))/2 + x = special.ivp(1,2) + assert_almost_equal(x,y,10) + + +class TestLaguerre: + def test_laguerre(self): + lag0 = special.laguerre(0) + lag1 = special.laguerre(1) + lag2 = special.laguerre(2) + lag3 = special.laguerre(3) + lag4 = special.laguerre(4) + lag5 = special.laguerre(5) + assert_array_almost_equal(lag0.c,[1],13) + assert_array_almost_equal(lag1.c,[-1,1],13) + assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) + assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) + assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) + assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) + + def test_genlaguerre(self): + k = 5*np.random.random() - 0.9 + lag0 = special.genlaguerre(0,k) + lag1 = special.genlaguerre(1,k) + lag2 = special.genlaguerre(2,k) + lag3 = special.genlaguerre(3,k) + assert_equal(lag0.c, [1]) + assert_equal(lag1.c, [-1, k + 1]) + assert_almost_equal( + lag2.c, + array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0 + ) + assert_almost_equal( + lag3.c, + array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0 + ) + + +class TestLambda: + def test_lmbda(self): + lam = special.lmbda(1,.1) + lamr = ( + array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), + array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1]) + ) + assert_array_almost_equal(lam,lamr,8) + + +class TestLog1p: + def test_log1p(self): + l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) + l1prl = (log(11), log(12), log(13)) + assert_array_almost_equal(l1p,l1prl,8) + + def test_log1pmore(self): + l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) + l1pmrl = (log(2),log(2.1),log(2.2)) + assert_array_almost_equal(l1pm,l1pmrl,8) + + +class TestMathieu: + + def test_mathieu_a(self): + pass + + def test_mathieu_even_coef(self): + special.mathieu_even_coef(2,5) + # Q not defined broken and cannot figure out proper reporting order + + def test_mathieu_odd_coef(self): + # same problem as above + pass + + +class TestFresnelIntegral: + + def test_modfresnelp(self): + pass + + def test_modfresnelm(self): + pass + + +class TestOblCvSeq: + def test_obl_cv_seq(self): + obl = special.obl_cv_seq(0,3,1) + assert_array_almost_equal(obl,array([-0.348602, + 1.393206, + 5.486800, + 11.492120]),5) + + +class TestParabolicCylinder: + def test_pbdn_seq(self): + pb = special.pbdn_seq(1,.1) + assert_array_almost_equal(pb,(array([0.9975, + 0.0998]), + array([-0.0499, + 0.9925])),4) + + def test_pbdv(self): + special.pbdv(1,.2) + 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] + + def test_pbdv_seq(self): + pbn = special.pbdn_seq(1,.1) + pbv = special.pbdv_seq(1,.1) + assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) + + def test_pbdv_points(self): + # simple case + eta = np.linspace(-10, 10, 5) + z = 2**(eta/2)*np.sqrt(np.pi)*special.rgamma(.5-.5*eta) + assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) + + # some points + assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) + assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) + + def test_pbdv_gradient(self): + x = np.linspace(-4, 4, 8)[:,None] + eta = np.linspace(-10, 10, 5)[None,:] + + p = special.pbdv(eta, x) + eps = 1e-7 + 1e-7*abs(x) + dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. + assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) + + def test_pbvv_gradient(self): + x = np.linspace(-4, 4, 8)[:,None] + eta = np.linspace(-10, 10, 5)[None,:] + + p = special.pbvv(eta, x) + eps = 1e-7 + 1e-7*abs(x) + dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. + assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) + + def test_pbvv_seq(self): + res1, res2 = special.pbvv_seq(2, 3) + assert_allclose(res1, np.array([2.976319645712036, + 1.358840996329579, + 0.5501016716383508])) + assert_allclose(res2, np.array([3.105638472238475, + 0.9380581512176672, + 0.533688488872053])) + + +class TestPolygamma: + # from Table 6.2 (pg. 271) of A&S + def test_polygamma(self): + poly2 = special.polygamma(2,1) + poly3 = special.polygamma(3,1) + assert_almost_equal(poly2,-2.4041138063,10) + assert_almost_equal(poly3,6.4939394023,10) + + # Test polygamma(0, x) == psi(x) + x = [2, 3, 1.1e14] + assert_almost_equal(special.polygamma(0, x), special.psi(x)) + + # Test broadcasting + n = [0, 1, 2] + x = [0.5, 1.5, 2.5] + expected = [-1.9635100260214238, 0.93480220054467933, + -0.23620405164172739] + assert_almost_equal(special.polygamma(n, x), expected) + expected = np.vstack([expected]*2) + assert_almost_equal(special.polygamma(n, np.vstack([x]*2)), + expected) + assert_almost_equal(special.polygamma(np.vstack([n]*2), x), + expected) + + +class TestProCvSeq: + def test_pro_cv_seq(self): + prol = special.pro_cv_seq(0,3,1) + assert_array_almost_equal(prol,array([0.319000, + 2.593084, + 6.533471, + 12.514462]),5) + + +class TestPsi: + def test_psi(self): + ps = special.psi(1) + assert_almost_equal(ps,-0.57721566490153287,8) + + +class TestRadian: + def test_radian(self): + rad = special.radian(90,0,0) + assert_almost_equal(rad,pi/2.0,5) + + def test_radianmore(self): + rad1 = special.radian(90,1,60) + assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) + + +class TestRiccati: + def test_riccati_jn(self): + N, x = 2, 0.2 + S = np.empty((N, N)) + for n in range(N): + j = special.spherical_jn(n, x) + jp = special.spherical_jn(n, x, derivative=True) + S[0,n] = x*j + S[1,n] = x*jp + j + assert_array_almost_equal(S, special.riccati_jn(n, x), 8) + + def test_riccati_yn(self): + N, x = 2, 0.2 + C = np.empty((N, N)) + for n in range(N): + y = special.spherical_yn(n, x) + yp = special.spherical_yn(n, x, derivative=True) + C[0,n] = x*y + C[1,n] = x*yp + y + assert_array_almost_equal(C, special.riccati_yn(n, x), 8) + + +class TestSoftplus: + def test_softplus(self): + # Test cases for the softplus function. Selected based on Eq.(10) of: + # Mächler, M. (2012). log1mexp-note.pdf. Rmpfr: R MPFR - Multiple Precision + # Floating-Point Reliable. Retrieved from: + # https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf + # Reference values computed with `mpmath` + import numpy as np + rng = np.random.default_rng(3298432985245) + n = 3 + a1 = rng.uniform(-100, -37, size=n) + a2 = rng.uniform(-37, 18, size=n) + a3 = rng.uniform(18, 33.3, size=n) + a4 = rng.uniform(33.33, 100, size=n) + a = np.stack([a1, a2, a3, a4]) + + # from mpmath import mp + # mp.dps = 100 + # @np.vectorize + # def softplus(x): + # return float(mp.log(mp.one + mp.exp(x))) + # softplus(a).tolist() + ref = [[1.692721323272333e-42, 7.42673911145206e-41, 8.504608846033205e-35], + [1.8425343736349797, 9.488245799395577e-15, 7.225195764021444e-08], + [31.253760266045106, 27.758244090327832, 29.995959179643634], + [73.26040086468937, 76.24944728617226, 37.83955519155184]] + + res = softplus(a) + assert_allclose(res, ref, rtol=2e-15) + + def test_softplus_with_kwargs(self): + x = np.arange(5) - 2 + out = np.ones(5) + ref = out.copy() + where = x > 0 + + softplus(x, out=out, where=where) + ref[where] = softplus(x[where]) + assert_allclose(out, ref) + + +class TestRound: + def test_round(self): + rnd = list(map(int, (special.round(10.1), + special.round(10.4), + special.round(10.5), + special.round(10.6)))) + + # Note: According to the documentation, scipy.special.round is + # supposed to round to the nearest even number if the fractional + # part is exactly 0.5. On some platforms, this does not appear + # to work and thus this test may fail. However, this unit test is + # correctly written. + rndrl = (10,10,10,11) + assert_array_equal(rnd,rndrl) + +# sph_harm is deprecated and is implemented as a shim around sph_harm_y. +# The following two tests are maintained to verify the correctness of the shim. + +def test_sph_harm(): + # Tests derived from tables in + # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics + sh = special.sph_harm + pi = np.pi + exp = np.exp + sqrt = np.sqrt + sin = np.sin + cos = np.cos + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + assert_array_almost_equal(sh(0,0,0,0), + 0.5/sqrt(pi)) + assert_array_almost_equal(sh(-2,2,0.,pi/4), + 0.25*sqrt(15./(2.*pi)) * + (sin(pi/4))**2.) + assert_array_almost_equal(sh(-2,2,0.,pi/2), + 0.25*sqrt(15./(2.*pi))) + assert_array_almost_equal(sh(2,2,pi,pi/2), + 0.25*sqrt(15/(2.*pi)) * + exp(0+2.*pi*1j)*sin(pi/2.)**2.) + assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), + (3./8.)*sqrt(5./(2.*pi)) * + exp(0+2.*pi/4.*1j) * + sin(pi/3.)**2. * + (7.*cos(pi/3.)**2.-1)) + assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), + (3./16.)*sqrt(35./(2.*pi)) * + exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) + + +def test_sph_harm_ufunc_loop_selection(): + # see https://github.com/scipy/scipy/issues/4895 + dt = np.dtype(np.complex128) + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) + assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) + assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) + assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) + assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) + assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) + + +class TestStruve: + def _series(self, v, z, n=100): + """Compute Struve function & error estimate from its power series.""" + k = arange(0, n) + r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) + err = abs(r).max() * finfo(double).eps * n + return r.sum(), err + + def test_vs_series(self): + """Check Struve function versus its power series""" + for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: + for z in [1, 10, 19, 21, 30]: + value, err = self._series(v, z) + assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) + + def test_some_values(self): + assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) + assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) + assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) + assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) + assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) + assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) + assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) + assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) + + assert_(isnan(special.struve(-7.1, -1))) + assert_(isnan(special.struve(-10.1, -1))) + + def test_regression_679(self): + """Regression test for #679""" + assert_allclose(special.struve(-1.0, 20 - 1e-8), + special.struve(-1.0, 20 + 1e-8)) + assert_allclose(special.struve(-2.0, 20 - 1e-8), + special.struve(-2.0, 20 + 1e-8)) + assert_allclose(special.struve(-4.3, 20 - 1e-8), + special.struve(-4.3, 20 + 1e-8)) + + +def test_chi2_smalldf(): + assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) + + +def test_ch2_inf(): + assert_equal(special.chdtr(0.7,np.inf), 1.0) + + +def test_chi2c_smalldf(): + assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) + + +def test_chi2_inv_smalldf(): + assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) + + +def test_agm_simple(): + rtol = 1e-13 + + # Gauss's constant + assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, + rtol=rtol) + + # These values were computed using Wolfram Alpha, with the + # function ArithmeticGeometricMean[a, b]. + agm13 = 1.863616783244897 + agm15 = 2.604008190530940 + agm35 = 3.936235503649555 + assert_allclose(special.agm([[1], [3]], [1, 3, 5]), + [[1, agm13, agm15], + [agm13, 3, agm35]], rtol=rtol) + + # Computed by the iteration formula using mpmath, + # with mpmath.mp.prec = 1000: + agm12 = 1.4567910310469068 + assert_allclose(special.agm(1, 2), agm12, rtol=rtol) + assert_allclose(special.agm(2, 1), agm12, rtol=rtol) + assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) + assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) + assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, + rtol=rtol) + assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) + assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) + assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, + rtol=rtol) + assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, + rtol=rtol) + assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, + rtol=rtol) + fi = np.finfo(1.0) + assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, + rtol=rtol) + assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, + rtol=rtol) + assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, + rtol=rtol) + + # zero, nan and inf cases. + assert_equal(special.agm(0, 0), 0) + assert_equal(special.agm(99, 0), 0) + + assert_equal(special.agm(-1, 10), np.nan) + assert_equal(special.agm(0, np.inf), np.nan) + assert_equal(special.agm(np.inf, 0), np.nan) + assert_equal(special.agm(0, -np.inf), np.nan) + assert_equal(special.agm(-np.inf, 0), np.nan) + assert_equal(special.agm(np.inf, -np.inf), np.nan) + assert_equal(special.agm(-np.inf, np.inf), np.nan) + assert_equal(special.agm(1, np.nan), np.nan) + assert_equal(special.agm(np.nan, -1), np.nan) + + assert_equal(special.agm(1, np.inf), np.inf) + assert_equal(special.agm(np.inf, 1), np.inf) + assert_equal(special.agm(-1, -np.inf), -np.inf) + assert_equal(special.agm(-np.inf, -1), -np.inf) + + +def test_legacy(): + # Legacy behavior: truncating arguments to integers + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "floating point number truncated to an integer") + assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) + assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) + assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) + assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) + assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) + assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) + assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) + assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) + assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) + + +# This lock can be removed once errstate is made thread-safe (see gh-21956) +@pytest.fixture +def errstate_lock(): + import threading + return threading.Lock() + + +@with_special_errors +def test_error_raising(errstate_lock): + with errstate_lock: + with special.errstate(all='raise'): + assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) + + +def test_xlogy(): + def xfunc(x, y): + with np.errstate(invalid='ignore'): + if x == 0 and not np.isnan(y): + return x + else: + return x*np.log(y) + + z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) + z2 = np.r_[z1, [(0, 1j), (1, 1j)]] + + w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) + assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) + w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) + assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) + + +def test_xlog1py(): + def xfunc(x, y): + with np.errstate(invalid='ignore'): + if x == 0 and not np.isnan(y): + return x + else: + return x * np.log1p(y) + + z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), + (1, 1e-30)], dtype=float) + w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) + assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) + + +def test_entr(): + def xfunc(x): + if x < 0: + return -np.inf + else: + return -special.xlogy(x, x) + values = (0, 0.5, 1.0, np.inf) + signs = [-1, 1] + arr = [] + for sgn, v in itertools.product(signs, values): + arr.append(sgn * v) + z = np.array(arr, dtype=float) + w = np.vectorize(xfunc, otypes=[np.float64])(z) + assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) + + +def test_kl_div(): + def xfunc(x, y): + if x < 0 or y < 0 or (y == 0 and x != 0): + # extension of natural domain to preserve convexity + return np.inf + elif np.isposinf(x) or np.isposinf(y): + # limits within the natural domain + return np.inf + elif x == 0: + return y + else: + return special.xlogy(x, x/y) - x + y + values = (0, 0.5, 1.0) + signs = [-1, 1] + arr = [] + for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): + arr.append((sgna*va, sgnb*vb)) + z = np.array(arr, dtype=float) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) + + +def test_rel_entr(): + def xfunc(x, y): + if x > 0 and y > 0: + return special.xlogy(x, x/y) + elif x == 0 and y >= 0: + return 0 + else: + return np.inf + values = (0, 0.5, 1.0) + signs = [-1, 1] + arr = [] + for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): + arr.append((sgna*va, sgnb*vb)) + z = np.array(arr, dtype=float) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) + + +def test_rel_entr_gh_20710_near_zero(): + # Check accuracy of inputs which are very close + inputs = np.array([ + # x, y + (0.9456657713430001, 0.9456657713430094), + (0.48066098564791515, 0.48066098564794774), + (0.786048657854401, 0.7860486578542367), + ]) + # Known values produced using `x * mpmath.log(x / y)` with dps=30 + expected = [ + -9.325873406851269e-15, + -3.258504577274724e-14, + 1.6431300764454033e-13, + ] + x = inputs[:, 0] + y = inputs[:, 1] + assert_allclose(special.rel_entr(x, y), expected, rtol=1e-13, atol=0) + + +def test_rel_entr_gh_20710_overflow(): + special.seterr(all='ignore') + inputs = np.array([ + # x, y + # Overflow + (4, 2.22e-308), + # Underflow + (1e-200, 1e+200), + # Subnormal + (2.22e-308, 1e15), + ]) + # Known values produced using `x * mpmath.log(x / y)` with dps=30 + expected = [ + 2839.139983229607, + -9.210340371976183e-198, + -1.6493212008074475e-305, + ] + x = inputs[:, 0] + y = inputs[:, 1] + assert_allclose(special.rel_entr(x, y), expected, rtol=1e-13, atol=0) + + +def test_huber(): + assert_equal(special.huber(-1, 1.5), np.inf) + assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) + assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) + + def xfunc(delta, r): + if delta < 0: + return np.inf + elif np.abs(r) < delta: + return 0.5 * np.square(r) + else: + return delta * (np.abs(r) - 0.5 * delta) + + z = np.random.randn(10, 2) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) + + +def test_pseudo_huber(): + def xfunc(delta, r): + if delta < 0: + return np.inf + elif (not delta) or (not r): + return 0 + else: + return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) + + z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13) + + +def test_pseudo_huber_small_r(): + delta = 1.0 + r = 1e-18 + y = special.pseudo_huber(delta, r) + # expected computed with mpmath: + # import mpmath + # mpmath.mp.dps = 200 + # r = mpmath.mpf(1e-18) + # expected = float(mpmath.sqrt(1 + r**2) - 1) + expected = 5.0000000000000005e-37 + assert_allclose(y, expected, rtol=1e-13) + + +@pytest.mark.thread_unsafe +def test_runtime_warning(): + with pytest.warns(RuntimeWarning, + match=r'Too many predicted coefficients'): + mathieu_odd_coef(1000, 1000) + with pytest.warns(RuntimeWarning, + match=r'Too many predicted coefficients'): + mathieu_even_coef(1000, 1000) + + +class TestStirling2: + table = [ + [1], + [0, 1], + [0, 1, 1], + [0, 1, 3, 1], + [0, 1, 7, 6, 1], + [0, 1, 15, 25, 10, 1], + [0, 1, 31, 90, 65, 15, 1], + [0, 1, 63, 301, 350, 140, 21, 1], + [0, 1, 127, 966, 1701, 1050, 266, 28, 1], + [0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1], + [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1], + ] + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_table_cases(self, is_exact, comp, kwargs): + for n in range(1, len(self.table)): + k_values = list(range(n+1)) + row = self.table[n] + comp(row, stirling2([n], k_values, exact=is_exact), **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_valid_single_integer(self, is_exact, comp, kwargs): + comp(stirling2(0, 0, exact=is_exact), self.table[0][0], **kwargs) + comp(stirling2(4, 2, exact=is_exact), self.table[4][2], **kwargs) + # a single 2-tuple of integers as arguments must return an int and not + # an array whereas arrays of single values should return array + comp(stirling2(5, 3, exact=is_exact), 25, **kwargs) + comp(stirling2([5], [3], exact=is_exact), [25], **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_negative_integer(self, is_exact, comp, kwargs): + # negative integers for n or k arguments return 0 + comp(stirling2(-1, -1, exact=is_exact), 0, **kwargs) + comp(stirling2(-1, 2, exact=is_exact), 0, **kwargs) + comp(stirling2(2, -1, exact=is_exact), 0, **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_array_inputs(self, is_exact, comp, kwargs): + ans = [self.table[10][3], self.table[10][4]] + comp(stirling2(asarray([10, 10]), + asarray([3, 4]), + exact=is_exact), + ans) + comp(stirling2([10, 10], + asarray([3, 4]), + exact=is_exact), + ans) + comp(stirling2(asarray([10, 10]), + [3, 4], + exact=is_exact), + ans) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-13}) + ]) + def test_mixed_values(self, is_exact, comp, kwargs): + # negative values-of either n or k-should return 0 for the entry + ans = [0, 1, 3, 25, 1050, 5880, 9330] + n = [-1, 0, 3, 5, 8, 10, 10] + k = [-2, 0, 2, 3, 5, 7, 3] + comp(stirling2(n, k, exact=is_exact), ans, **kwargs) + + def test_correct_parity(self): + """Test parity follows well known identity. + + en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind#Parity + """ + n, K = 100, np.arange(101) + assert_equal( + stirling2(n, K, exact=True) % 2, + [math.comb(n - (k // 2) - 1, n - k) % 2 for k in K], + ) + + def test_big_numbers(self): + # via mpmath (bigger than 32bit) + ans = asarray([48063331393110, 48004081105038305]) + n = [25, 30] + k = [17, 4] + assert array_equal(stirling2(n, k, exact=True), ans) + # bigger than 64 bit + ans = asarray([2801934359500572414253157841233849412, + 14245032222277144547280648984426251]) + n = [42, 43] + k = [17, 23] + assert array_equal(stirling2(n, k, exact=True), ans) + + @pytest.mark.parametrize("N", [4.5, 3., 4+1j, "12", np.nan]) + @pytest.mark.parametrize("K", [3.5, 3, "2", None]) + @pytest.mark.parametrize("is_exact", [True, False]) + def test_unsupported_input_types(self, N, K, is_exact): + # object, float, string, complex are not supported and raise TypeError + with pytest.raises(TypeError): + stirling2(N, K, exact=is_exact) + + @pytest.mark.parametrize("is_exact", [True, False]) + def test_numpy_array_int_object_dtype(self, is_exact): + # python integers with arbitrary precision are *not* allowed as + # object type in numpy arrays are inconsistent from api perspective + ans = asarray(self.table[4][1:]) + n = asarray([4, 4, 4, 4], dtype=object) + k = asarray([1, 2, 3, 4], dtype=object) + with pytest.raises(TypeError): + array_equal(stirling2(n, k, exact=is_exact), ans) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-13}) + ]) + def test_numpy_array_unsigned_int_dtype(self, is_exact, comp, kwargs): + # numpy unsigned integers are allowed as dtype in numpy arrays + ans = asarray(self.table[4][1:]) + n = asarray([4, 4, 4, 4], dtype=np_ulong) + k = asarray([1, 2, 3, 4], dtype=np_ulong) + comp(stirling2(n, k, exact=False), ans, **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-13}) + ]) + def test_broadcasting_arrays_correctly(self, is_exact, comp, kwargs): + # broadcasting is handled by stirling2 + # test leading 1s are replicated + ans = asarray([[1, 15, 25, 10], [1, 7, 6, 1]]) # shape (2,4) + n = asarray([[5, 5, 5, 5], [4, 4, 4, 4]]) # shape (2,4) + k = asarray([1, 2, 3, 4]) # shape (4,) + comp(stirling2(n, k, exact=is_exact), ans, **kwargs) + # test that dims both mismatch broadcast correctly (5,1) & (6,) + n = asarray([[4], [4], [4], [4], [4]]) + k = asarray([0, 1, 2, 3, 4, 5]) + ans = asarray([[0, 1, 7, 6, 1, 0] for _ in range(5)]) + comp(stirling2(n, k, exact=False), ans, **kwargs) + + def test_temme_rel_max_error(self): + # python integers with arbitrary precision are *not* allowed as + # object type in numpy arrays are inconsistent from api perspective + x = list(range(51, 101, 5)) + for n in x: + k_entries = list(range(1, n+1)) + denom = stirling2([n], k_entries, exact=True) + num = denom - stirling2([n], k_entries, exact=False) + assert np.max(np.abs(num / denom)) < 2e-5 + + +class TestLegendreDeprecation: + + def test_warn_lpn(self): + msg = "`scipy.special.lpn` is deprecated..." + with pytest.deprecated_call(match=msg): + _ = lpn(1, 0) + + @pytest.mark.parametrize("xlpmn", [lpmn, clpmn]) + def test_warn_xlpmn(self, xlpmn): + message = f"`scipy.special.{xlpmn.__name__}` is deprecated..." + with pytest.deprecated_call(match=message): + _ = xlpmn(1, 1, 0) + + def test_warn_sph_harm(self): + msg = "`scipy.special.sph_harm` is deprecated..." + with pytest.deprecated_call(match=msg): + _ = special.sph_harm(1, 1, 0, 0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py new file mode 100644 index 0000000000000000000000000000000000000000..57694becc49b2028f17eac819b80a225ac010795 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py @@ -0,0 +1,112 @@ +import numpy as np +import scipy.special as sc +import pytest +from numpy.testing import assert_allclose, assert_array_equal, suppress_warnings + + +class TestBdtr: + def test(self): + val = sc.bdtr(0, 1, 0.5) + assert_allclose(val, 0.5) + + def test_sum_is_one(self): + val = sc.bdtr([0, 1, 2], 2, 0.5) + assert_array_equal(val, [0.25, 0.75, 1.0]) + + def test_rounding(self): + double_val = sc.bdtr([0.1, 1.1, 2.1], 2, 0.5) + int_val = sc.bdtr([0, 1, 2], 2, 0.5) + assert_array_equal(double_val, int_val) + + @pytest.mark.parametrize('k, n, p', [ + (np.inf, 2, 0.5), + (1.0, np.inf, 0.5), + (1.0, 2, np.inf) + ]) + def test_inf(self, k, n, p): + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + val = sc.bdtr(k, n, p) + assert np.isnan(val) + + def test_domain(self): + val = sc.bdtr(-1.1, 1, 0.5) + assert np.isnan(val) + + +class TestBdtrc: + def test_value(self): + val = sc.bdtrc(0, 1, 0.5) + assert_allclose(val, 0.5) + + def test_sum_is_one(self): + val = sc.bdtrc([0, 1, 2], 2, 0.5) + assert_array_equal(val, [0.75, 0.25, 0.0]) + + def test_rounding(self): + double_val = sc.bdtrc([0.1, 1.1, 2.1], 2, 0.5) + int_val = sc.bdtrc([0, 1, 2], 2, 0.5) + assert_array_equal(double_val, int_val) + + @pytest.mark.parametrize('k, n, p', [ + (np.inf, 2, 0.5), + (1.0, np.inf, 0.5), + (1.0, 2, np.inf) + ]) + def test_inf(self, k, n, p): + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + val = sc.bdtrc(k, n, p) + assert np.isnan(val) + + def test_domain(self): + val = sc.bdtrc(-1.1, 1, 0.5) + val2 = sc.bdtrc(2.1, 1, 0.5) + assert np.isnan(val2) + assert_allclose(val, 1.0) + + def test_bdtr_bdtrc_sum_to_one(self): + bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5) + bdtrc_vals = sc.bdtrc([0, 1, 2], 2, 0.5) + vals = bdtr_vals + bdtrc_vals + assert_allclose(vals, [1.0, 1.0, 1.0]) + + +class TestBdtri: + def test_value(self): + val = sc.bdtri(0, 1, 0.5) + assert_allclose(val, 0.5) + + def test_sum_is_one(self): + val = sc.bdtri([0, 1], 2, 0.5) + actual = np.asarray([1 - 1/np.sqrt(2), 1/np.sqrt(2)]) + assert_allclose(val, actual) + + def test_rounding(self): + double_val = sc.bdtri([0.1, 1.1], 2, 0.5) + int_val = sc.bdtri([0, 1], 2, 0.5) + assert_allclose(double_val, int_val) + + @pytest.mark.parametrize('k, n, p', [ + (np.inf, 2, 0.5), + (1.0, np.inf, 0.5), + (1.0, 2, np.inf) + ]) + def test_inf(self, k, n, p): + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + val = sc.bdtri(k, n, p) + assert np.isnan(val) + + @pytest.mark.parametrize('k, n, p', [ + (-1.1, 1, 0.5), + (2.1, 1, 0.5) + ]) + def test_domain(self, k, n, p): + val = sc.bdtri(k, n, p) + assert np.isnan(val) + + def test_bdtr_bdtri_roundtrip(self): + bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5) + roundtrip_vals = sc.bdtri([0, 1, 2], 2, bdtr_vals) + assert_allclose(roundtrip_vals, [0.5, 0.5, np.nan]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..132fb9ab11ec19d8efa00c5bb96f851795017d31 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py @@ -0,0 +1,61 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose +import scipy.special._ufuncs as scu +from scipy.integrate import tanhsinh + + +type_char_to_type_tol = {'f': (np.float32, 32*np.finfo(np.float32).eps), + 'd': (np.float64, 32*np.finfo(np.float64).eps)} + + +# Each item in this list is +# (func, args, expected_value) +# All the values can be represented exactly, even with np.float32. +# +# This is not an exhaustive test data set of all the functions! +# It is a spot check of several functions, primarily for +# checking that the different data types are handled correctly. +test_data = [ + (scu._beta_pdf, (0.5, 2, 3), 1.5), + (scu._beta_pdf, (0, 1, 5), 5.0), + (scu._beta_pdf, (1, 5, 1), 5.0), + (scu._beta_ppf, (0.5, 5., 5.), 0.5), # gh-21303 + (scu._binom_cdf, (1, 3, 0.5), 0.5), + (scu._binom_pmf, (1, 4, 0.5), 0.25), + (scu._hypergeom_cdf, (2, 3, 5, 6), 0.5), + (scu._nbinom_cdf, (1, 4, 0.25), 0.015625), + (scu._ncf_mean, (10, 12, 2.5), 1.5), +] + + +@pytest.mark.parametrize('func, args, expected', test_data) +def test_stats_boost_ufunc(func, args, expected): + type_sigs = func.types + type_chars = [sig.split('->')[-1] for sig in type_sigs] + for type_char in type_chars: + typ, rtol = type_char_to_type_tol[type_char] + args = [typ(arg) for arg in args] + # Harmless overflow warnings are a "feature" of some wrappers on some + # platforms. This test is about dtype and accuracy, so let's avoid false + # test failures cause by these warnings. See gh-17432. + with np.errstate(over='ignore'): + value = func(*args) + assert isinstance(value, typ) + assert_allclose(value, expected, rtol=rtol) + + +def test_landau(): + # Test that Landau distribution ufuncs are wrapped as expected; + # accuracy is tested by Boost. + x = np.linspace(-3, 10, 10) + args = (0, 1) + res = tanhsinh(lambda x: scu._landau_pdf(x, *args), -np.inf, x) + cdf = scu._landau_cdf(x, *args) + assert_allclose(res.integral, cdf) + sf = scu._landau_sf(x, *args) + assert_allclose(sf, 1-cdf) + ppf = scu._landau_ppf(cdf, *args) + assert_allclose(ppf, x) + isf = scu._landau_isf(sf, *args) + assert_allclose(isf, x, rtol=1e-6) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py new file mode 100644 index 0000000000000000000000000000000000000000..25d76d0560a6a9fe416f750213662b5f7fb22f25 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py @@ -0,0 +1,125 @@ +import numpy as np +from numpy.testing import assert_equal, assert_almost_equal, assert_allclose +from scipy.special import boxcox, boxcox1p, inv_boxcox, inv_boxcox1p +import pytest + + +# There are more tests of boxcox and boxcox1p in test_mpmath.py. + +def test_boxcox_basic(): + x = np.array([0.5, 1, 2, 4]) + + # lambda = 0 => y = log(x) + y = boxcox(x, 0) + assert_almost_equal(y, np.log(x)) + + # lambda = 1 => y = x - 1 + y = boxcox(x, 1) + assert_almost_equal(y, x - 1) + + # lambda = 2 => y = 0.5*(x**2 - 1) + y = boxcox(x, 2) + assert_almost_equal(y, 0.5*(x**2 - 1)) + + # x = 0 and lambda > 0 => y = -1 / lambda + lam = np.array([0.5, 1, 2]) + y = boxcox(0, lam) + assert_almost_equal(y, -1.0 / lam) + +def test_boxcox_underflow(): + x = 1 + 1e-15 + lmbda = 1e-306 + y = boxcox(x, lmbda) + assert_allclose(y, np.log(x), rtol=1e-14) + + +def test_boxcox_nonfinite(): + # x < 0 => y = nan + x = np.array([-1, -1, -0.5]) + y = boxcox(x, [0.5, 2.0, -1.5]) + assert_equal(y, np.array([np.nan, np.nan, np.nan])) + + # x = 0 and lambda <= 0 => y = -inf + x = 0 + y = boxcox(x, [-2.5, 0]) + assert_equal(y, np.array([-np.inf, -np.inf])) + + +def test_boxcox1p_basic(): + x = np.array([-0.25, -1e-20, 0, 1e-20, 0.25, 1, 3]) + + # lambda = 0 => y = log(1+x) + y = boxcox1p(x, 0) + assert_almost_equal(y, np.log1p(x)) + + # lambda = 1 => y = x + y = boxcox1p(x, 1) + assert_almost_equal(y, x) + + # lambda = 2 => y = 0.5*((1+x)**2 - 1) = 0.5*x*(2 + x) + y = boxcox1p(x, 2) + assert_almost_equal(y, 0.5*x*(2 + x)) + + # x = -1 and lambda > 0 => y = -1 / lambda + lam = np.array([0.5, 1, 2]) + y = boxcox1p(-1, lam) + assert_almost_equal(y, -1.0 / lam) + + +def test_boxcox1p_underflow(): + x = np.array([1e-15, 1e-306]) + lmbda = np.array([1e-306, 1e-18]) + y = boxcox1p(x, lmbda) + assert_allclose(y, np.log1p(x), rtol=1e-14) + + +def test_boxcox1p_nonfinite(): + # x < -1 => y = nan + x = np.array([-2, -2, -1.5]) + y = boxcox1p(x, [0.5, 2.0, -1.5]) + assert_equal(y, np.array([np.nan, np.nan, np.nan])) + + # x = -1 and lambda <= 0 => y = -inf + x = -1 + y = boxcox1p(x, [-2.5, 0]) + assert_equal(y, np.array([-np.inf, -np.inf])) + + +def test_inv_boxcox(): + x = np.array([0., 1., 2.]) + lam = np.array([0., 1., 2.]) + y = boxcox(x, lam) + x2 = inv_boxcox(y, lam) + assert_almost_equal(x, x2) + + x = np.array([0., 1., 2.]) + lam = np.array([0., 1., 2.]) + y = boxcox1p(x, lam) + x2 = inv_boxcox1p(y, lam) + assert_almost_equal(x, x2) + + +def test_inv_boxcox1p_underflow(): + x = 1e-15 + lam = 1e-306 + y = inv_boxcox1p(x, lam) + assert_allclose(y, x, rtol=1e-14) + + +@pytest.mark.parametrize( + "x, lmb", + [[100, 155], + [0.01, -155]] +) +def test_boxcox_premature_overflow(x, lmb): + # test boxcox & inv_boxcox + y = boxcox(x, lmb) + assert np.isfinite(y) + x_inv = inv_boxcox(y, lmb) + assert_allclose(x, x_inv) + + # test boxcox1p & inv_boxcox1p + y1p = boxcox1p(x-1, lmb) + assert np.isfinite(y1p) + x1p_inv = inv_boxcox1p(y1p, lmb) + assert_allclose(x-1, x1p_inv) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py new file mode 100644 index 0000000000000000000000000000000000000000..a8352182bdf657029ab9857411e1b41141fdc0a5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py @@ -0,0 +1,688 @@ +""" +Test cdflib functions versus mpmath, if available. + +The following functions still need tests: + +- ncfdtri +- ncfdtridfn +- ncfdtridfd +- ncfdtrinc +- nbdtrik +- nbdtrin +- pdtrik +- nctdtrit +- nctdtridf +- nctdtrinc + +""" +import itertools + +import numpy as np +from numpy.testing import assert_equal, assert_allclose +import pytest + +import scipy.special as sp +from scipy.special._testutils import ( + MissingModule, check_version, FuncData) +from scipy.special._mptestutils import ( + Arg, IntArg, get_args, mpf2float, assert_mpmath_equal) + +try: + import mpmath +except ImportError: + mpmath = MissingModule('mpmath') + + +class ProbArg: + """Generate a set of probabilities on [0, 1].""" + + def __init__(self): + # Include the endpoints for compatibility with Arg et. al. + self.a = 0 + self.b = 1 + + def values(self, n): + """Return an array containing approximately n numbers.""" + m = max(1, n//3) + v1 = np.logspace(-30, np.log10(0.3), m) + v2 = np.linspace(0.3, 0.7, m + 1, endpoint=False)[1:] + v3 = 1 - np.logspace(np.log10(0.3), -15, m) + v = np.r_[v1, v2, v3] + return np.unique(v) + + +class EndpointFilter: + def __init__(self, a, b, rtol, atol): + self.a = a + self.b = b + self.rtol = rtol + self.atol = atol + + def __call__(self, x): + mask1 = np.abs(x - self.a) < self.rtol*np.abs(self.a) + self.atol + mask2 = np.abs(x - self.b) < self.rtol*np.abs(self.b) + self.atol + return np.where(mask1 | mask2, False, True) + + +class _CDFData: + def __init__(self, spfunc, mpfunc, index, argspec, spfunc_first=True, + dps=20, n=5000, rtol=None, atol=None, + endpt_rtol=None, endpt_atol=None): + self.spfunc = spfunc + self.mpfunc = mpfunc + self.index = index + self.argspec = argspec + self.spfunc_first = spfunc_first + self.dps = dps + self.n = n + self.rtol = rtol + self.atol = atol + + if not isinstance(argspec, list): + self.endpt_rtol = None + self.endpt_atol = None + elif endpt_rtol is not None or endpt_atol is not None: + if isinstance(endpt_rtol, list): + self.endpt_rtol = endpt_rtol + else: + self.endpt_rtol = [endpt_rtol]*len(self.argspec) + if isinstance(endpt_atol, list): + self.endpt_atol = endpt_atol + else: + self.endpt_atol = [endpt_atol]*len(self.argspec) + else: + self.endpt_rtol = None + self.endpt_atol = None + + def idmap(self, *args): + if self.spfunc_first: + res = self.spfunc(*args) + if np.isnan(res): + return np.nan + args = list(args) + args[self.index] = res + with mpmath.workdps(self.dps): + res = self.mpfunc(*tuple(args)) + # Imaginary parts are spurious + res = mpf2float(res.real) + else: + with mpmath.workdps(self.dps): + res = self.mpfunc(*args) + res = mpf2float(res.real) + args = list(args) + args[self.index] = res + res = self.spfunc(*tuple(args)) + return res + + def get_param_filter(self): + if self.endpt_rtol is None and self.endpt_atol is None: + return None + + filters = [] + for rtol, atol, spec in zip(self.endpt_rtol, self.endpt_atol, self.argspec): + if rtol is None and atol is None: + filters.append(None) + continue + elif rtol is None: + rtol = 0.0 + elif atol is None: + atol = 0.0 + + filters.append(EndpointFilter(spec.a, spec.b, rtol, atol)) + return filters + + def check(self): + # Generate values for the arguments + args = get_args(self.argspec, self.n) + param_filter = self.get_param_filter() + param_columns = tuple(range(args.shape[1])) + result_columns = args.shape[1] + args = np.hstack((args, args[:, self.index].reshape(args.shape[0], 1))) + FuncData(self.idmap, args, + param_columns=param_columns, result_columns=result_columns, + rtol=self.rtol, atol=self.atol, vectorized=False, + param_filter=param_filter).check() + + +def _assert_inverts(*a, **kw): + d = _CDFData(*a, **kw) + d.check() + + +def _binomial_cdf(k, n, p): + k, n, p = mpmath.mpf(k), mpmath.mpf(n), mpmath.mpf(p) + if k <= 0: + return mpmath.mpf(0) + elif k >= n: + return mpmath.mpf(1) + + onemp = mpmath.fsub(1, p, exact=True) + return mpmath.betainc(n - k, k + 1, x2=onemp, regularized=True) + + +def _f_cdf(dfn, dfd, x): + if x < 0: + return mpmath.mpf(0) + dfn, dfd, x = mpmath.mpf(dfn), mpmath.mpf(dfd), mpmath.mpf(x) + ub = dfn*x/(dfn*x + dfd) + res = mpmath.betainc(dfn/2, dfd/2, x2=ub, regularized=True) + return res + + +def _student_t_cdf(df, t, dps=None): + if dps is None: + dps = mpmath.mp.dps + with mpmath.workdps(dps): + df, t = mpmath.mpf(df), mpmath.mpf(t) + fac = mpmath.hyp2f1(0.5, 0.5*(df + 1), 1.5, -t**2/df) + fac *= t*mpmath.gamma(0.5*(df + 1)) + fac /= mpmath.sqrt(mpmath.pi*df)*mpmath.gamma(0.5*df) + return 0.5 + fac + + +def _noncentral_chi_pdf(t, df, nc): + res = mpmath.besseli(df/2 - 1, mpmath.sqrt(nc*t)) + res *= mpmath.exp(-(t + nc)/2)*(t/nc)**(df/4 - 1/2)/2 + return res + + +def _noncentral_chi_cdf(x, df, nc, dps=None): + if dps is None: + dps = mpmath.mp.dps + x, df, nc = mpmath.mpf(x), mpmath.mpf(df), mpmath.mpf(nc) + with mpmath.workdps(dps): + res = mpmath.quad(lambda t: _noncentral_chi_pdf(t, df, nc), [0, x]) + return res + + +def _tukey_lmbda_quantile(p, lmbda): + # For lmbda != 0 + return (p**lmbda - (1 - p)**lmbda)/lmbda + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +class TestCDFlib: + + @pytest.mark.xfail(run=False) + def test_bdtrik(self): + _assert_inverts( + sp.bdtrik, + _binomial_cdf, + 0, [ProbArg(), IntArg(1, 1000), ProbArg()], + rtol=1e-4) + + def test_bdtrin(self): + _assert_inverts( + sp.bdtrin, + _binomial_cdf, + 1, [IntArg(1, 1000), ProbArg(), ProbArg()], + rtol=1e-4, endpt_atol=[None, None, 1e-6]) + + def test_btdtria(self): + _assert_inverts( + sp.btdtria, + lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True), + 0, [ProbArg(), Arg(0, 1e2, inclusive_a=False), + Arg(0, 1, inclusive_a=False, inclusive_b=False)], + rtol=1e-6) + + def test_btdtrib(self): + # Use small values of a or mpmath doesn't converge + _assert_inverts( + sp.btdtrib, + lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True), + 1, + [Arg(0, 1e2, inclusive_a=False), ProbArg(), + Arg(0, 1, inclusive_a=False, inclusive_b=False)], + rtol=1e-7, + endpt_atol=[None, 1e-18, 1e-15]) + + @pytest.mark.xfail(run=False) + def test_fdtridfd(self): + _assert_inverts( + sp.fdtridfd, + _f_cdf, + 1, + [IntArg(1, 100), ProbArg(), Arg(0, 100, inclusive_a=False)], + rtol=1e-7) + + def test_gdtria(self): + _assert_inverts( + sp.gdtria, + lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), + 0, + [ProbArg(), Arg(0, 1e3, inclusive_a=False), + Arg(0, 1e4, inclusive_a=False)], + rtol=1e-7, + endpt_atol=[None, 1e-7, 1e-10]) + + def test_gdtrib(self): + # Use small values of a and x or mpmath doesn't converge + _assert_inverts( + sp.gdtrib, + lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), + 1, + [Arg(0, 1e2, inclusive_a=False), ProbArg(), + Arg(0, 1e3, inclusive_a=False)], + rtol=1e-5) + + def test_gdtrix(self): + _assert_inverts( + sp.gdtrix, + lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), + 2, + [Arg(0, 1e3, inclusive_a=False), Arg(0, 1e3, inclusive_a=False), + ProbArg()], + rtol=1e-7, + endpt_atol=[None, 1e-7, 1e-10]) + + # Overall nrdtrimn and nrdtrisd are not performing well with infeasible/edge + # combinations of sigma and x, hence restricted the domains to still use the + # testing machinery, also see gh-20069 + + # nrdtrimn signature: p, sd, x + # nrdtrisd signature: mn, p, x + def test_nrdtrimn(self): + _assert_inverts( + sp.nrdtrimn, + lambda x, y, z: mpmath.ncdf(z, x, y), + 0, + [ProbArg(), # CDF value p + Arg(0.1, np.inf, inclusive_a=False, inclusive_b=False), # sigma + Arg(-1e10, 1e10)], # x + rtol=1e-5) + + def test_nrdtrisd(self): + _assert_inverts( + sp.nrdtrisd, + lambda x, y, z: mpmath.ncdf(z, x, y), + 1, + [Arg(-np.inf, 10, inclusive_a=False, inclusive_b=False), # mn + ProbArg(), # CDF value p + Arg(10, 1e100)], # x + rtol=1e-5) + + def test_stdtr(self): + # Ideally the left endpoint for Arg() should be 0. + assert_mpmath_equal( + sp.stdtr, + _student_t_cdf, + [IntArg(1, 100), Arg(1e-10, np.inf)], rtol=1e-7) + + @pytest.mark.xfail(run=False) + def test_stdtridf(self): + _assert_inverts( + sp.stdtridf, + _student_t_cdf, + 0, [ProbArg(), Arg()], rtol=1e-7) + + def test_stdtrit(self): + _assert_inverts( + sp.stdtrit, + _student_t_cdf, + 1, [IntArg(1, 100), ProbArg()], rtol=1e-7, + endpt_atol=[None, 1e-10]) + + def test_chdtriv(self): + _assert_inverts( + sp.chdtriv, + lambda v, x: mpmath.gammainc(v/2, b=x/2, regularized=True), + 0, [ProbArg(), IntArg(1, 100)], rtol=1e-4) + + @pytest.mark.xfail(run=False) + def test_chndtridf(self): + # Use a larger atol since mpmath is doing numerical integration + _assert_inverts( + sp.chndtridf, + _noncentral_chi_cdf, + 1, [Arg(0, 100, inclusive_a=False), ProbArg(), + Arg(0, 100, inclusive_a=False)], + n=1000, rtol=1e-4, atol=1e-15) + + @pytest.mark.xfail(run=False) + def test_chndtrinc(self): + # Use a larger atol since mpmath is doing numerical integration + _assert_inverts( + sp.chndtrinc, + _noncentral_chi_cdf, + 2, [Arg(0, 100, inclusive_a=False), IntArg(1, 100), ProbArg()], + n=1000, rtol=1e-4, atol=1e-15) + + def test_chndtrix(self): + # Use a larger atol since mpmath is doing numerical integration + _assert_inverts( + sp.chndtrix, + _noncentral_chi_cdf, + 0, [ProbArg(), IntArg(1, 100), Arg(0, 100, inclusive_a=False)], + n=1000, rtol=1e-4, atol=1e-15, + endpt_atol=[1e-6, None, None]) + + def test_tklmbda_zero_shape(self): + # When lmbda = 0 the CDF has a simple closed form + one = mpmath.mpf(1) + assert_mpmath_equal( + lambda x: sp.tklmbda(x, 0), + lambda x: one/(mpmath.exp(-x) + one), + [Arg()], rtol=1e-7) + + def test_tklmbda_neg_shape(self): + _assert_inverts( + sp.tklmbda, + _tukey_lmbda_quantile, + 0, [ProbArg(), Arg(-25, 0, inclusive_b=False)], + spfunc_first=False, rtol=1e-5, + endpt_atol=[1e-9, 1e-5]) + + @pytest.mark.xfail(run=False) + def test_tklmbda_pos_shape(self): + _assert_inverts( + sp.tklmbda, + _tukey_lmbda_quantile, + 0, [ProbArg(), Arg(0, 100, inclusive_a=False)], + spfunc_first=False, rtol=1e-5) + + # The values of lmdba are chosen so that 1/lmbda is exact. + @pytest.mark.parametrize('lmbda', [0.5, 1.0, 8.0]) + def test_tklmbda_lmbda1(self, lmbda): + bound = 1/lmbda + assert_equal(sp.tklmbda([-bound, bound], lmbda), [0.0, 1.0]) + + +funcs = [ + ("btdtria", 3), + ("btdtrib", 3), + ("bdtrik", 3), + ("bdtrin", 3), + ("chdtriv", 2), + ("chndtr", 3), + ("chndtrix", 3), + ("chndtridf", 3), + ("chndtrinc", 3), + ("fdtridfd", 3), + ("ncfdtr", 4), + ("ncfdtri", 4), + ("ncfdtridfn", 4), + ("ncfdtridfd", 4), + ("ncfdtrinc", 4), + ("gdtrix", 3), + ("gdtrib", 3), + ("gdtria", 3), + ("nbdtrik", 3), + ("nbdtrin", 3), + ("nrdtrimn", 3), + ("nrdtrisd", 3), + ("pdtrik", 2), + ("stdtr", 2), + ("stdtrit", 2), + ("stdtridf", 2), + ("nctdtr", 3), + ("nctdtrit", 3), + ("nctdtridf", 3), + ("nctdtrinc", 3), + ("tklmbda", 2), +] + + +@pytest.mark.parametrize('func,numargs', funcs, ids=[x[0] for x in funcs]) +def test_nonfinite(func, numargs): + + rng = np.random.default_rng(1701299355559735) + func = getattr(sp, func) + args_choices = [(float(x), np.nan, np.inf, -np.inf) for x in rng.random(numargs)] + + for args in itertools.product(*args_choices): + res = func(*args) + + if any(np.isnan(x) for x in args): + # Nan inputs should result to nan output + assert_equal(res, np.nan) + else: + # All other inputs should return something (but not + # raise exceptions or cause hangs) + pass + + +def test_chndtrix_gh2158(): + # test that gh-2158 is resolved; previously this blew up + res = sp.chndtrix(0.999999, 2, np.arange(20.)+1e-6) + + # Generated in R + # options(digits=16) + # ncp <- seq(0, 19) + 1e-6 + # print(qchisq(0.999999, df = 2, ncp = ncp)) + res_exp = [27.63103493142305, 35.25728589950540, 39.97396073236288, + 43.88033702110538, 47.35206403482798, 50.54112500166103, + 53.52720257322766, 56.35830042867810, 59.06600769498512, + 61.67243118946381, 64.19376191277179, 66.64228141346548, + 69.02756927200180, 71.35726934749408, 73.63759723904816, + 75.87368842650227, 78.06984431185720, 80.22971052389806, + 82.35640899964173, 84.45263768373256] + assert_allclose(res, res_exp) + + +def test_nctdtrinc_gh19896(): + # test that gh-19896 is resolved. + # Compared to SciPy 1.11 results from Fortran code. + dfarr = [0.001, 0.98, 9.8, 98, 980, 10000, 98, 9.8, 0.98, 0.001] + parr = [0.001, 0.1, 0.3, 0.8, 0.999, 0.001, 0.1, 0.3, 0.8, 0.999] + tarr = [0.0015, 0.15, 1.5, 15, 300, 0.0015, 0.15, 1.5, 15, 300] + desired = [3.090232306168629, 1.406141304556198, 2.014225177124157, + 13.727067118283456, 278.9765683871208, 3.090232306168629, + 1.4312427877936222, 2.014225177124157, 3.712743137978295, + -3.086951096691082] + actual = sp.nctdtrinc(dfarr, parr, tarr) + assert_allclose(actual, desired, rtol=5e-12, atol=0.0) + + +def test_stdtr_stdtrit_neg_inf(): + # -inf was treated as +inf and values from the normal were returned + assert np.all(np.isnan(sp.stdtr(-np.inf, [-np.inf, -1.0, 0.0, 1.0, np.inf]))) + assert np.all(np.isnan(sp.stdtrit(-np.inf, [0.0, 0.25, 0.5, 0.75, 1.0]))) + + +def test_bdtrik_nbdtrik_inf(): + y = np.array( + [np.nan,-np.inf,-10.0, -1.0, 0.0, .00001, .5, 0.9999, 1.0, 10.0, np.inf]) + y = y[:,None] + p = np.atleast_2d( + [np.nan, -np.inf, -10.0, -1.0, 0.0, .00001, .5, 1.0, np.inf]) + assert np.all(np.isnan(sp.bdtrik(y, np.inf, p))) + assert np.all(np.isnan(sp.nbdtrik(y, np.inf, p))) + + +@pytest.mark.parametrize( + "dfn,dfd,nc,f,expected", + [[100.0, 0.1, 0.1, 100.0, 0.29787396410092676], + [100.0, 100.0, 0.01, 0.1, 4.4344737598690424e-26], + [100.0, 0.01, 0.1, 0.01, 0.002848616633080384], + [10.0, 0.01, 1.0, 0.1, 0.012339557729057956], + [100.0, 100.0, 0.01, 0.01, 1.8926477420964936e-72], + [1.0, 100.0, 100.0, 0.1, 1.7925940526821304e-22], + [1.0, 0.01, 100.0, 10.0, 0.012334711965024968], + [1.0, 0.01, 10.0, 0.01, 0.00021944525290299], + [10.0, 1.0, 0.1, 100.0, 0.9219345555070705], + [0.1, 0.1, 1.0, 1.0, 0.3136335813423239], + [100.0, 100.0, 0.1, 10.0, 1.0], + [1.0, 0.1, 100.0, 10.0, 0.02926064279680897]] +) +def test_ncfdtr(dfn, dfd, nc, f, expected): + # Reference values computed with mpmath with the following script + # + # import numpy as np + # + # from mpmath import mp + # from scipy.special import ncfdtr + # + # mp.dps = 100 + # + # def mp_ncfdtr(dfn, dfd, nc, f): + # # Uses formula 26.2.20 from Abramowitz and Stegun. + # dfn, dfd, nc, f = map(mp.mpf, (dfn, dfd, nc, f)) + # def term(j): + # result = mp.exp(-nc/2)*(nc/2)**j / mp.factorial(j) + # result *= mp.betainc( + # dfn/2 + j, dfd/2, 0, f*dfn/(f*dfn + dfd), regularized=True + # ) + # return result + # result = mp.nsum(term, [0, mp.inf]) + # return float(result) + # + # dfn = np.logspace(-2, 2, 5) + # dfd = np.logspace(-2, 2, 5) + # nc = np.logspace(-2, 2, 5) + # f = np.logspace(-2, 2, 5) + # + # dfn, dfd, nc, f = np.meshgrid(dfn, dfd, nc, f) + # dfn, dfd, nc, f = map(np.ravel, (dfn, dfd, nc, f)) + # + # cases = [] + # re = [] + # for x0, x1, x2, x3 in zip(*(dfn, dfd, nc, f)): + # observed = ncfdtr(x0, x1, x2, x3) + # expected = mp_ncfdtr(x0, x1, x2, x3) + # cases.append((x0, x1, x2, x3, expected)) + # re.append((abs(expected - observed)/abs(expected))) + # + # assert np.max(re) < 1e-13 + # + # rng = np.random.default_rng(1234) + # sample_idx = rng.choice(len(re), replace=False, size=12) + # cases = np.array(cases)[sample_idx].tolist() + assert_allclose(sp.ncfdtr(dfn, dfd, nc, f), expected, rtol=1e-13, atol=0) + + +class TestNctdtr: + + # Reference values computed with mpmath with the following script + # Formula from: + # Lenth, Russell V (1989). "Algorithm AS 243: Cumulative Distribution Function + # of the Non-central t Distribution". Journal of the Royal Statistical Society, + # Series C. 38 (1): 185-189 + # + # Warning: may take a long time to run + # + # from mpmath import mp + # mp.dps = 400 + + # def nct_cdf(df, nc, x): + # df, nc, x = map(mp.mpf, (df, nc, x)) + + # def f(df, nc, x): + # phi = mp.ncdf(-nc) + # y = x * x / (x * x + df) + # constant = mp.exp(-nc * nc / 2.) + # def term(j): + # intermediate = constant * (nc *nc / 2.)**j + # p = intermediate/mp.factorial(j) + # q = nc / (mp.sqrt(2.) * mp.gamma(j + 1.5)) * intermediate + # first_beta_term = mp.betainc(j + 0.5, df/2., x2=y, + # regularized=True) + # second_beta_term = mp.betainc(j + mp.one, df/2., x2=y, + # regularized=True) + # return p * first_beta_term + q * second_beta_term + + # sum_term = mp.nsum(term, [0, mp.inf]) + # f = phi + 0.5 * sum_term + # return f + + # if x >= 0: + # result = f(df, nc, x) + # else: + # result = mp.one - f(df, -nc, x) + # return float(result) + + @pytest.mark.parametrize("df, nc, x, expected", [ + (0.98, -3.8, 0.0015, 0.9999279987514815), + (0.98, -3.8, 0.15, 0.9999528361700505), + (0.98, -3.8, 1.5, 0.9999908823016942), + (0.98, -3.8, 15, 0.9999990264591945), + (0.98, 0.38, 0.0015, 0.35241533122693), + (0.98, 0.38, 0.15, 0.39749697267146983), + (0.98, 0.38, 1.5, 0.716862963488558), + (0.98, 0.38, 15, 0.9656246449257494), + (0.98, 3.8, 0.0015, 7.26973354942293e-05), + (0.98, 3.8, 0.15, 0.00012416481147589105), + (0.98, 3.8, 1.5, 0.035388035775454095), + (0.98, 3.8, 15, 0.7954826975430583), + (0.98, 38, 0.0015, 3.02106943e-316), + (0.98, 38, 0.15, 6.069970616996603e-309), + (0.98, 38, 1.5, 2.591995360483094e-97), + (0.98, 38, 15, 0.011927265886910935), + (9.8, -3.8, 0.0015, 0.9999280776192786), + (9.8, -3.8, 0.15, 0.9999599410685442), + (9.8, -3.8, 1.5, 0.9999997432394788), + (9.8, -3.8, 15, 0.9999999999999984), + (9.8, 0.38, 0.0015, 0.3525155979107491), + (9.8, 0.38, 0.15, 0.40763120140379194), + (9.8, 0.38, 1.5, 0.8476794017024651), + (9.8, 0.38, 15, 0.9999999297116268), + (9.8, 3.8, 0.0015, 7.277620328149153e-05), + (9.8, 3.8, 0.15, 0.00013024802220900652), + (9.8, 3.8, 1.5, 0.013477432800072933), + (9.8, 3.8, 15, 0.999850151230648), + (9.8, 38, 0.0015, 3.05066095e-316), + (9.8, 38, 0.15, 1.79065514676e-313), + (9.8, 38, 1.5, 2.0935940165900746e-249), + (9.8, 38, 15, 2.252076291604796e-09), + (98, -3.8, 0.0015, 0.9999280875149109), + (98, -3.8, 0.15, 0.9999608250170452), + (98, -3.8, 1.5, 0.9999999304757682), + (98, -3.8, 15, 1.0), + (98, 0.38, 0.0015, 0.35252817848596313), + (98, 0.38, 0.15, 0.40890253001794846), + (98, 0.38, 1.5, 0.8664672830006552), + (98, 0.38, 15, 1.0), + (98, 3.8, 0.0015, 7.278609891281275e-05), + (98, 3.8, 0.15, 0.0001310318674827004), + (98, 3.8, 1.5, 0.010990879189991727), + (98, 3.8, 15, 0.9999999999999989), + (98, 38, 0.0015, 3.05437385e-316), + (98, 38, 0.15, 9.1668336166e-314), + (98, 38, 1.5, 1.8085884236563926e-288), + (98, 38, 15, 2.7740532792035907e-50), + (980, -3.8, 0.0015, 0.9999280885188965), + (980, -3.8, 0.15, 0.9999609144559273), + (980, -3.8, 1.5, 0.9999999410050979), + (980, -3.8, 15, 1.0), + (980, 0.38, 0.0015, 0.3525294548792812), + (980, 0.38, 0.15, 0.4090315324657382), + (980, 0.38, 1.5, 0.8684247068517293), + (980, 0.38, 15, 1.0), + (980, 3.8, 0.0015, 7.278710289828983e-05), + (980, 3.8, 0.15, 0.00013111131667906573), + (980, 3.8, 1.5, 0.010750678886113882), + (980, 3.8, 15, 1.0), + (980, 38, 0.0015, 3.0547506e-316), + (980, 38, 0.15, 8.6191646313e-314), + pytest.param(980, 38, 1.5, 1.1824454111413493e-291, + marks=pytest.mark.xfail( + reason="Bug in underlying Boost math implementation")), + (980, 38, 15, 5.407535300713606e-105) + ]) + def test_gh19896(self, df, nc, x, expected): + # test that gh-19896 is resolved. + # Originally this was a regression test that used the old Fortran results + # as a reference. The Fortran results were not accurate, so the reference + # values were recomputed with mpmath. + result = sp.nctdtr(df, nc, x) + assert_allclose(result, expected, rtol=1e-13, atol=1e-303) + + def test_nctdtr_gh8344(self): + # test that gh-8344 is resolved. + df, nc, x = 3000, 3, 0.1 + expected = 0.0018657780826323328 + assert_allclose(sp.nctdtr(df, nc, x), expected, rtol=1e-14) + + @pytest.mark.parametrize( + "df, nc, x, expected, rtol", + [[3., 5., -2., 1.5645373999149622e-09, 5e-9], + [1000., 10., 1., 1.1493552133826623e-19, 1e-13], + [1e-5, -6., 2., 0.9999999990135003, 1e-13], + [10., 20., 0.15, 6.426530505957303e-88, 1e-13], + [1., 1., np.inf, 1.0, 0.0], + [1., 1., -np.inf, 0.0, 0.0] + ] + ) + def test_accuracy(self, df, nc, x, expected, rtol): + assert_allclose(sp.nctdtr(df, nc, x), expected, rtol=rtol) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1ad41243f0865c205963d938ab61a346ee8e88 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py @@ -0,0 +1,49 @@ +# gh-14777 regression tests +# Test stdtr and stdtrit with infinite df and large values of df + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +from scipy.special import stdtr, stdtrit, ndtr, ndtri + + +def test_stdtr_vs_R_large_df(): + df = [1e10, 1e12, 1e120, np.inf] + t = 1. + res = stdtr(df, t) + # R Code: + # options(digits=20) + # pt(1., c(1e10, 1e12, 1e120, Inf)) + res_R = [0.84134474605644460343, + 0.84134474606842180044, + 0.84134474606854281475, + 0.84134474606854292578] + assert_allclose(res, res_R, rtol=2e-15) + # last value should also agree with ndtr + assert_equal(res[3], ndtr(1.)) + + +def test_stdtrit_vs_R_large_df(): + df = [1e10, 1e12, 1e120, np.inf] + p = 0.1 + res = stdtrit(df, p) + # R Code: + # options(digits=20) + # qt(0.1, c(1e10, 1e12, 1e120, Inf)) + res_R = [-1.2815515656292593150, + -1.2815515655454472466, + -1.2815515655446008125, + -1.2815515655446008125] + assert_allclose(res, res_R, rtol=1e-14, atol=1e-15) + # last value should also agree with ndtri + assert_equal(res[3], ndtri(0.1)) + + +def test_stdtr_stdtri_invalid(): + # a mix of large and inf df with t/p equal to nan + df = [1e10, 1e12, 1e120, np.inf] + x = np.nan + res1 = stdtr(df, x) + res2 = stdtrit(df, x) + res_ex = 4*[np.nan] + assert_equal(res1, res_ex) + assert_equal(res2, res_ex) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py new file mode 100644 index 0000000000000000000000000000000000000000..05f3d1ae5c101ff50c75d1065e5e234063d192e4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py @@ -0,0 +1,29 @@ +import pytest +import numpy as np +from scipy.special._ufuncs import ( + _smirnovc, _smirnovci, _smirnovp, + _struve_asymp_large_z, _struve_bessel_series, _struve_power_series, + bdtr, bdtrc, bdtri, expn, kn, nbdtr, nbdtrc, nbdtri, pdtri, + smirnov, smirnovi, yn +) + + +# +# For each ufunc here, verify that the default integer type, np.intp, +# can be safely cast to the integer type found in the input type signatures. +# For this particular set of functions, the code expects to find just one +# integer type among the input signatures. +# +@pytest.mark.parametrize( + 'ufunc', + [_smirnovc, _smirnovci, _smirnovp, + _struve_asymp_large_z, _struve_bessel_series, _struve_power_series, + bdtr, bdtrc, bdtri, expn, kn, nbdtr, nbdtrc, nbdtri, pdtri, + smirnov, smirnovi, yn], +) +def test_intp_safe_cast(ufunc): + int_chars = {'i', 'l', 'q'} + int_input = [set(sig.split('->')[0]) & int_chars for sig in ufunc.types] + int_char = ''.join(s.pop() if s else '' for s in int_input) + assert len(int_char) == 1, "More integer types in the signatures than expected" + assert np.can_cast(np.intp, np.dtype(int_char)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py new file mode 100644 index 0000000000000000000000000000000000000000..27e3ca2699d0d1d0b58665f125d99c166095696d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py @@ -0,0 +1,83 @@ +import numpy as np +from numpy.testing import assert_allclose +import pytest +from scipy.special._ufuncs import _cosine_cdf, _cosine_invcdf + + +# These values are (x, p) where p is the expected exact value of +# _cosine_cdf(x). These values will be tested for exact agreement. +_coscdf_exact = [ + (-4.0, 0.0), + (0, 0.5), + (np.pi, 1.0), + (4.0, 1.0), +] + +@pytest.mark.parametrize("x, expected", _coscdf_exact) +def test_cosine_cdf_exact(x, expected): + assert _cosine_cdf(x) == expected + + +# These values are (x, p), where p is the expected value of +# _cosine_cdf(x). The expected values were computed with mpmath using +# 50 digits of precision. These values will be tested for agreement +# with the computed values using a very small relative tolerance. +# The value at -np.pi is not 0, because -np.pi does not equal -π. +_coscdf_close = [ + (3.1409, 0.999999999991185), + (2.25, 0.9819328173287907), + # -1.6 is the threshold below which the Pade approximant is used. + (-1.599, 0.08641959838382553), + (-1.601, 0.086110582992713), + (-2.0, 0.0369709335961611), + (-3.0, 7.522387241801384e-05), + (-3.1415, 2.109869685443648e-14), + (-3.14159, 4.956444476505336e-19), + (-np.pi, 4.871934450264861e-50), +] + +@pytest.mark.parametrize("x, expected", _coscdf_close) +def test_cosine_cdf(x, expected): + assert_allclose(_cosine_cdf(x), expected, rtol=5e-15) + + +# These values are (p, x) where x is the expected exact value of +# _cosine_invcdf(p). These values will be tested for exact agreement. +_cosinvcdf_exact = [ + (0.0, -np.pi), + (0.5, 0.0), + (1.0, np.pi), +] + +@pytest.mark.parametrize("p, expected", _cosinvcdf_exact) +def test_cosine_invcdf_exact(p, expected): + assert _cosine_invcdf(p) == expected + + +def test_cosine_invcdf_invalid_p(): + # Check that p values outside of [0, 1] return nan. + assert np.isnan(_cosine_invcdf([-0.1, 1.1])).all() + + +# These values are (p, x), where x is the expected value of _cosine_invcdf(p). +# The expected values were computed with mpmath using 50 digits of precision. +_cosinvcdf_close = [ + (1e-50, -np.pi), + (1e-14, -3.1415204137058454), + (1e-08, -3.1343686589124524), + (0.0018001, -2.732563923138336), + (0.010, -2.41276589008678), + (0.060, -1.7881244975330157), + (0.125, -1.3752523669869274), + (0.250, -0.831711193579736), + (0.400, -0.3167954512395289), + (0.419, -0.25586025626919906), + (0.421, -0.24947570750445663), + (0.750, 0.831711193579736), + (0.940, 1.7881244975330153), + (0.9999999996, 3.1391220839917167), +] + +@pytest.mark.parametrize("p, expected", _cosinvcdf_close) +def test_cosine_invcdf(p, expected): + assert_allclose(_cosine_invcdf(p), expected, rtol=1e-14) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc9ed50cec9503edb77064cfa209c9d81573214 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py @@ -0,0 +1,363 @@ +from collections.abc import Callable + +import pytest +from itertools import product +from numpy.testing import assert_allclose, suppress_warnings +from scipy import special +from scipy.special import cython_special + + +bint_points = [True, False] +int_points = [-10, -1, 1, 10] +real_points = [-10.0, -1.0, 1.0, 10.0] +complex_points = [complex(*tup) for tup in product(real_points, repeat=2)] + + +CYTHON_SIGNATURE_MAP = { + 'b': 'bint', + 'f': 'float', + 'd': 'double', + 'g': 'long double', + 'F': 'float complex', + 'D': 'double complex', + 'G': 'long double complex', + 'i': 'int', + 'l': 'long' +} + + +TEST_POINTS = { + 'b': bint_points, + 'f': real_points, + 'd': real_points, + 'g': real_points, + 'F': complex_points, + 'D': complex_points, + 'G': complex_points, + 'i': int_points, + 'l': int_points, +} + + +PARAMS: list[tuple[Callable, Callable, tuple[str, ...], str | None]] = [ + (special.agm, cython_special.agm, ('dd',), None), + (special.airy, cython_special._airy_pywrap, ('d', 'D'), None), + (special.airye, cython_special._airye_pywrap, ('d', 'D'), None), + (special.bdtr, cython_special.bdtr, ('dld', 'ddd'), None), + (special.bdtrc, cython_special.bdtrc, ('dld', 'ddd'), None), + (special.bdtri, cython_special.bdtri, ('dld', 'ddd'), None), + (special.bdtrik, cython_special.bdtrik, ('ddd',), None), + (special.bdtrin, cython_special.bdtrin, ('ddd',), None), + (special.bei, cython_special.bei, ('d',), None), + (special.beip, cython_special.beip, ('d',), None), + (special.ber, cython_special.ber, ('d',), None), + (special.berp, cython_special.berp, ('d',), None), + (special.besselpoly, cython_special.besselpoly, ('ddd',), None), + (special.beta, cython_special.beta, ('dd',), None), + (special.betainc, cython_special.betainc, ('ddd',), None), + (special.betaincc, cython_special.betaincc, ('ddd',), None), + (special.betaincinv, cython_special.betaincinv, ('ddd',), None), + (special.betainccinv, cython_special.betainccinv, ('ddd',), None), + (special.betaln, cython_special.betaln, ('dd',), None), + (special.binom, cython_special.binom, ('dd',), None), + (special.boxcox, cython_special.boxcox, ('dd',), None), + (special.boxcox1p, cython_special.boxcox1p, ('dd',), None), + (special.btdtria, cython_special.btdtria, ('ddd',), None), + (special.btdtrib, cython_special.btdtrib, ('ddd',), None), + (special.cbrt, cython_special.cbrt, ('d',), None), + (special.chdtr, cython_special.chdtr, ('dd',), None), + (special.chdtrc, cython_special.chdtrc, ('dd',), None), + (special.chdtri, cython_special.chdtri, ('dd',), None), + (special.chdtriv, cython_special.chdtriv, ('dd',), None), + (special.chndtr, cython_special.chndtr, ('ddd',), None), + (special.chndtridf, cython_special.chndtridf, ('ddd',), None), + (special.chndtrinc, cython_special.chndtrinc, ('ddd',), None), + (special.chndtrix, cython_special.chndtrix, ('ddd',), None), + (special.cosdg, cython_special.cosdg, ('d',), None), + (special.cosm1, cython_special.cosm1, ('d',), None), + (special.cotdg, cython_special.cotdg, ('d',), None), + (special.dawsn, cython_special.dawsn, ('d', 'D'), None), + (special.ellipe, cython_special.ellipe, ('d',), None), + (special.ellipeinc, cython_special.ellipeinc, ('dd',), None), + (special.ellipj, cython_special._ellipj_pywrap, ('dd',), None), + (special.ellipkinc, cython_special.ellipkinc, ('dd',), None), + (special.ellipkm1, cython_special.ellipkm1, ('d',), None), + (special.ellipk, cython_special.ellipk, ('d',), None), + (special.elliprc, cython_special.elliprc, ('dd', 'DD'), None), + (special.elliprd, cython_special.elliprd, ('ddd', 'DDD'), None), + (special.elliprf, cython_special.elliprf, ('ddd', 'DDD'), None), + (special.elliprg, cython_special.elliprg, ('ddd', 'DDD'), None), + (special.elliprj, cython_special.elliprj, ('dddd', 'DDDD'), None), + (special.entr, cython_special.entr, ('d',), None), + (special.erf, cython_special.erf, ('d', 'D'), None), + (special.erfc, cython_special.erfc, ('d', 'D'), None), + (special.erfcx, cython_special.erfcx, ('d', 'D'), None), + (special.erfi, cython_special.erfi, ('d', 'D'), None), + (special.erfinv, cython_special.erfinv, ('d',), None), + (special.erfcinv, cython_special.erfcinv, ('d',), None), + (special.eval_chebyc, cython_special.eval_chebyc, ('dd', 'dD', 'ld'), None), + (special.eval_chebys, cython_special.eval_chebys, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_chebyt, cython_special.eval_chebyt, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_chebyu, cython_special.eval_chebyu, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_gegenbauer, cython_special.eval_gegenbauer, ('ddd', 'ddD', 'ldd'), + 'd and l differ for negative int'), + (special.eval_genlaguerre, cython_special.eval_genlaguerre, ('ddd', 'ddD', 'ldd'), + 'd and l differ for negative int'), + (special.eval_hermite, cython_special.eval_hermite, ('ld',), None), + (special.eval_hermitenorm, cython_special.eval_hermitenorm, ('ld',), None), + (special.eval_jacobi, cython_special.eval_jacobi, ('dddd', 'dddD', 'lddd'), + 'd and l differ for negative int'), + (special.eval_laguerre, cython_special.eval_laguerre, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_legendre, cython_special.eval_legendre, ('dd', 'dD', 'ld'), None), + (special.eval_sh_chebyt, cython_special.eval_sh_chebyt, ('dd', 'dD', 'ld'), None), + (special.eval_sh_chebyu, cython_special.eval_sh_chebyu, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_sh_jacobi, cython_special.eval_sh_jacobi, ('dddd', 'dddD', 'lddd'), + 'd and l differ for negative int'), + (special.eval_sh_legendre, cython_special.eval_sh_legendre, ('dd', 'dD', 'ld'), + None), + (special.exp1, cython_special.exp1, ('d', 'D'), None), + (special.exp10, cython_special.exp10, ('d',), None), + (special.exp2, cython_special.exp2, ('d',), None), + (special.expi, cython_special.expi, ('d', 'D'), None), + (special.expit, cython_special.expit, ('f', 'd', 'g'), None), + (special.expm1, cython_special.expm1, ('d', 'D'), None), + (special.expn, cython_special.expn, ('ld', 'dd'), None), + (special.exprel, cython_special.exprel, ('d',), None), + (special.fdtr, cython_special.fdtr, ('ddd',), None), + (special.fdtrc, cython_special.fdtrc, ('ddd',), None), + (special.fdtri, cython_special.fdtri, ('ddd',), None), + (special.fdtridfd, cython_special.fdtridfd, ('ddd',), None), + (special.fresnel, cython_special._fresnel_pywrap, ('d', 'D'), None), + (special.gamma, cython_special.gamma, ('d', 'D'), None), + (special.gammainc, cython_special.gammainc, ('dd',), None), + (special.gammaincc, cython_special.gammaincc, ('dd',), None), + (special.gammainccinv, cython_special.gammainccinv, ('dd',), None), + (special.gammaincinv, cython_special.gammaincinv, ('dd',), None), + (special.gammaln, cython_special.gammaln, ('d',), None), + (special.gammasgn, cython_special.gammasgn, ('d',), None), + (special.gdtr, cython_special.gdtr, ('ddd',), None), + (special.gdtrc, cython_special.gdtrc, ('ddd',), None), + (special.gdtria, cython_special.gdtria, ('ddd',), None), + (special.gdtrib, cython_special.gdtrib, ('ddd',), None), + (special.gdtrix, cython_special.gdtrix, ('ddd',), None), + (special.hankel1, cython_special.hankel1, ('dD',), None), + (special.hankel1e, cython_special.hankel1e, ('dD',), None), + (special.hankel2, cython_special.hankel2, ('dD',), None), + (special.hankel2e, cython_special.hankel2e, ('dD',), None), + (special.huber, cython_special.huber, ('dd',), None), + (special.hyp0f1, cython_special.hyp0f1, ('dd', 'dD'), None), + (special.hyp1f1, cython_special.hyp1f1, ('ddd', 'ddD'), None), + (special.hyp2f1, cython_special.hyp2f1, ('dddd', 'dddD'), None), + (special.hyperu, cython_special.hyperu, ('ddd',), None), + (special.i0, cython_special.i0, ('d',), None), + (special.i0e, cython_special.i0e, ('d',), None), + (special.i1, cython_special.i1, ('d',), None), + (special.i1e, cython_special.i1e, ('d',), None), + (special.inv_boxcox, cython_special.inv_boxcox, ('dd',), None), + (special.inv_boxcox1p, cython_special.inv_boxcox1p, ('dd',), None), + (special.it2i0k0, cython_special._it2i0k0_pywrap, ('d',), None), + (special.it2j0y0, cython_special._it2j0y0_pywrap, ('d',), None), + (special.it2struve0, cython_special.it2struve0, ('d',), None), + (special.itairy, cython_special._itairy_pywrap, ('d',), None), + (special.iti0k0, cython_special._iti0k0_pywrap, ('d',), None), + (special.itj0y0, cython_special._itj0y0_pywrap, ('d',), None), + (special.itmodstruve0, cython_special.itmodstruve0, ('d',), None), + (special.itstruve0, cython_special.itstruve0, ('d',), None), + (special.iv, cython_special.iv, ('dd', 'dD'), None), + (special.ive, cython_special.ive, ('dd', 'dD'), None), + (special.j0, cython_special.j0, ('d',), None), + (special.j1, cython_special.j1, ('d',), None), + (special.jv, cython_special.jv, ('dd', 'dD'), None), + (special.jve, cython_special.jve, ('dd', 'dD'), None), + (special.k0, cython_special.k0, ('d',), None), + (special.k0e, cython_special.k0e, ('d',), None), + (special.k1, cython_special.k1, ('d',), None), + (special.k1e, cython_special.k1e, ('d',), None), + (special.kei, cython_special.kei, ('d',), None), + (special.keip, cython_special.keip, ('d',), None), + (special.kelvin, cython_special._kelvin_pywrap, ('d',), None), + (special.ker, cython_special.ker, ('d',), None), + (special.kerp, cython_special.kerp, ('d',), None), + (special.kl_div, cython_special.kl_div, ('dd',), None), + (special.kn, cython_special.kn, ('ld', 'dd'), None), + (special.kolmogi, cython_special.kolmogi, ('d',), None), + (special.kolmogorov, cython_special.kolmogorov, ('d',), None), + (special.kv, cython_special.kv, ('dd', 'dD'), None), + (special.kve, cython_special.kve, ('dd', 'dD'), None), + (special.log1p, cython_special.log1p, ('d', 'D'), None), + (special.log_expit, cython_special.log_expit, ('f', 'd', 'g'), None), + (special.log_ndtr, cython_special.log_ndtr, ('d', 'D'), None), + (special.log_wright_bessel, cython_special.log_wright_bessel, ('ddd',), None), + (special.ndtri_exp, cython_special.ndtri_exp, ('d',), None), + (special.loggamma, cython_special.loggamma, ('D',), None), + (special.logit, cython_special.logit, ('f', 'd', 'g'), None), + (special.lpmv, cython_special.lpmv, ('ddd',), None), + (special.mathieu_a, cython_special.mathieu_a, ('dd',), None), + (special.mathieu_b, cython_special.mathieu_b, ('dd',), None), + (special.mathieu_cem, cython_special._mathieu_cem_pywrap, ('ddd',), None), + (special.mathieu_modcem1, cython_special._mathieu_modcem1_pywrap, ('ddd',), None), + (special.mathieu_modcem2, cython_special._mathieu_modcem2_pywrap, ('ddd',), None), + (special.mathieu_modsem1, cython_special._mathieu_modsem1_pywrap, ('ddd',), None), + (special.mathieu_modsem2, cython_special._mathieu_modsem2_pywrap, ('ddd',), None), + (special.mathieu_sem, cython_special._mathieu_sem_pywrap, ('ddd',), None), + (special.modfresnelm, cython_special._modfresnelm_pywrap, ('d',), None), + (special.modfresnelp, cython_special._modfresnelp_pywrap, ('d',), None), + (special.modstruve, cython_special.modstruve, ('dd',), None), + (special.nbdtr, cython_special.nbdtr, ('lld', 'ddd'), None), + (special.nbdtrc, cython_special.nbdtrc, ('lld', 'ddd'), None), + (special.nbdtri, cython_special.nbdtri, ('lld', 'ddd'), None), + (special.nbdtrik, cython_special.nbdtrik, ('ddd',), None), + (special.nbdtrin, cython_special.nbdtrin, ('ddd',), None), + (special.ncfdtr, cython_special.ncfdtr, ('dddd',), None), + (special.ncfdtri, cython_special.ncfdtri, ('dddd',), None), + (special.ncfdtridfd, cython_special.ncfdtridfd, ('dddd',), None), + (special.ncfdtridfn, cython_special.ncfdtridfn, ('dddd',), None), + (special.ncfdtrinc, cython_special.ncfdtrinc, ('dddd',), None), + (special.nctdtr, cython_special.nctdtr, ('ddd',), None), + (special.nctdtridf, cython_special.nctdtridf, ('ddd',), None), + (special.nctdtrinc, cython_special.nctdtrinc, ('ddd',), None), + (special.nctdtrit, cython_special.nctdtrit, ('ddd',), None), + (special.ndtr, cython_special.ndtr, ('d', 'D'), None), + (special.ndtri, cython_special.ndtri, ('d',), None), + (special.nrdtrimn, cython_special.nrdtrimn, ('ddd',), None), + (special.nrdtrisd, cython_special.nrdtrisd, ('ddd',), None), + (special.obl_ang1, cython_special._obl_ang1_pywrap, ('dddd',), None), + (special.obl_ang1_cv, cython_special._obl_ang1_cv_pywrap, ('ddddd',), None), + (special.obl_cv, cython_special.obl_cv, ('ddd',), None), + (special.obl_rad1, cython_special._obl_rad1_pywrap, ('dddd',), "see gh-6211"), + (special.obl_rad1_cv, cython_special._obl_rad1_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.obl_rad2, cython_special._obl_rad2_pywrap, ('dddd',), "see gh-6211"), + (special.obl_rad2_cv, cython_special._obl_rad2_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.pbdv, cython_special._pbdv_pywrap, ('dd',), None), + (special.pbvv, cython_special._pbvv_pywrap, ('dd',), None), + (special.pbwa, cython_special._pbwa_pywrap, ('dd',), None), + (special.pdtr, cython_special.pdtr, ('dd', 'dd'), None), + (special.pdtrc, cython_special.pdtrc, ('dd', 'dd'), None), + (special.pdtri, cython_special.pdtri, ('ld', 'dd'), None), + (special.pdtrik, cython_special.pdtrik, ('dd',), None), + (special.poch, cython_special.poch, ('dd',), None), + (special.powm1, cython_special.powm1, ('dd',), None), + (special.pro_ang1, cython_special._pro_ang1_pywrap, ('dddd',), None), + (special.pro_ang1_cv, cython_special._pro_ang1_cv_pywrap, ('ddddd',), None), + (special.pro_cv, cython_special.pro_cv, ('ddd',), None), + (special.pro_rad1, cython_special._pro_rad1_pywrap, ('dddd',), "see gh-6211"), + (special.pro_rad1_cv, cython_special._pro_rad1_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.pro_rad2, cython_special._pro_rad2_pywrap, ('dddd',), "see gh-6211"), + (special.pro_rad2_cv, cython_special._pro_rad2_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.pseudo_huber, cython_special.pseudo_huber, ('dd',), None), + (special.psi, cython_special.psi, ('d', 'D'), None), + (special.radian, cython_special.radian, ('ddd',), None), + (special.rel_entr, cython_special.rel_entr, ('dd',), None), + (special.rgamma, cython_special.rgamma, ('d', 'D'), None), + (special.round, cython_special.round, ('d',), None), + (special.spherical_jn, cython_special.spherical_jn, ('ld', 'ldb', 'lD', 'lDb'), + "Python version supports negative reals; Cython version doesn't - see gh-21629"), + (special.spherical_yn, cython_special.spherical_yn, ('ld', 'ldb', 'lD', 'lDb'), + "Python version supports negative reals; Cython version doesn't - see gh-21629"), + (special.spherical_in, cython_special.spherical_in, ('ld', 'ldb', 'lD', 'lDb'), + "Python version supports negative reals; Cython version doesn't - see gh-21629"), + (special.spherical_kn, cython_special.spherical_kn, ('ld', 'ldb', 'lD', 'lDb'), + "Python version supports negative reals; Cython version doesn't - see gh-21629"), + (special.shichi, cython_special._shichi_pywrap, ('d', 'D'), None), + (special.sici, cython_special._sici_pywrap, ('d', 'D'), None), + (special.sindg, cython_special.sindg, ('d',), None), + (special.smirnov, cython_special.smirnov, ('ld', 'dd'), None), + (special.smirnovi, cython_special.smirnovi, ('ld', 'dd'), None), + (special.spence, cython_special.spence, ('d', 'D'), None), + (special.sph_harm, cython_special.sph_harm, ('lldd', 'dddd'), None), + (special.stdtr, cython_special.stdtr, ('dd',), None), + (special.stdtridf, cython_special.stdtridf, ('dd',), None), + (special.stdtrit, cython_special.stdtrit, ('dd',), None), + (special.struve, cython_special.struve, ('dd',), None), + (special.tandg, cython_special.tandg, ('d',), None), + (special.tklmbda, cython_special.tklmbda, ('dd',), None), + (special.voigt_profile, cython_special.voigt_profile, ('ddd',), None), + (special.wofz, cython_special.wofz, ('D',), None), + (special.wright_bessel, cython_special.wright_bessel, ('ddd',), None), + (special.wrightomega, cython_special.wrightomega, ('D',), None), + (special.xlog1py, cython_special.xlog1py, ('dd', 'DD'), None), + (special.xlogy, cython_special.xlogy, ('dd', 'DD'), None), + (special.y0, cython_special.y0, ('d',), None), + (special.y1, cython_special.y1, ('d',), None), + (special.yn, cython_special.yn, ('ld', 'dd'), None), + (special.yv, cython_special.yv, ('dd', 'dD'), None), + (special.yve, cython_special.yve, ('dd', 'dD'), None), + (special.zetac, cython_special.zetac, ('d',), None), + (special.owens_t, cython_special.owens_t, ('dd',), None) +] + + +IDS = [x[0].__name__ for x in PARAMS] + + +def _generate_test_points(typecodes): + axes = tuple(TEST_POINTS[x] for x in typecodes) + pts = list(product(*axes)) + return pts + + +def test_cython_api_completeness(): + # Check that everything is tested + for name in dir(cython_special): + func = getattr(cython_special, name) + if callable(func) and not name.startswith('_'): + for _, cyfun, _, _ in PARAMS: + if cyfun is func: + break + else: + raise RuntimeError(f"{name} missing from tests!") + + +@pytest.mark.thread_unsafe +@pytest.mark.fail_slow(20) +@pytest.mark.parametrize("param", PARAMS, ids=IDS) +def test_cython_api(param): + pyfunc, cyfunc, specializations, knownfailure = param + if knownfailure: + pytest.xfail(reason=knownfailure) + + # Check which parameters are expected to be fused types + max_params = max(len(spec) for spec in specializations) + values = [set() for _ in range(max_params)] + for typecodes in specializations: + for j, v in enumerate(typecodes): + values[j].add(v) + seen = set() + is_fused_code = [False] * len(values) + for j, v in enumerate(values): + vv = tuple(sorted(v)) + if vv in seen: + continue + is_fused_code[j] = (len(v) > 1) + seen.add(vv) + + # Check results + for typecodes in specializations: + # Pick the correct specialized function + signature = [CYTHON_SIGNATURE_MAP[code] + for j, code in enumerate(typecodes) + if is_fused_code[j]] + + if signature: + cy_spec_func = cyfunc[tuple(signature)] + else: + signature = None + cy_spec_func = cyfunc + + # Test it + pts = _generate_test_points(typecodes) + for pt in pts: + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + pyval = pyfunc(*pt) + cyval = cy_spec_func(*pt) + assert_allclose(cyval, pyval, err_msg=f"{pt} {typecodes} {signature}") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc89a328cf20da0fd243ab7603cf316ecf2acb4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py @@ -0,0 +1,719 @@ +import importlib.resources + +import numpy as np +from numpy.testing import suppress_warnings +import pytest + +from scipy.special import ( + lpn, lpmn, lpmv, lqn, lqmn, sph_harm, eval_legendre, eval_hermite, + eval_laguerre, eval_genlaguerre, binom, cbrt, expm1, log1p, zeta, + jn, jv, jvp, yn, yv, yvp, iv, ivp, kn, kv, kvp, + gamma, gammaln, gammainc, gammaincc, gammaincinv, gammainccinv, digamma, + beta, betainc, betaincinv, poch, + ellipe, ellipeinc, ellipk, ellipkm1, ellipkinc, + elliprc, elliprd, elliprf, elliprg, elliprj, + erf, erfc, erfinv, erfcinv, exp1, expi, expn, + bdtrik, btdtria, btdtrib, chndtr, gdtr, gdtrc, gdtrix, gdtrib, + nbdtrik, pdtrik, owens_t, + mathieu_a, mathieu_b, mathieu_cem, mathieu_sem, mathieu_modcem1, + mathieu_modsem1, mathieu_modcem2, mathieu_modsem2, + ellip_harm, ellip_harm_2, spherical_jn, spherical_yn, wright_bessel +) +from scipy.integrate import IntegrationWarning + +from scipy.special._testutils import FuncData + + +# The npz files are generated, and hence may live in the build dir. We can only +# access them through `importlib.resources`, not an explicit path from `__file__` +_datadir = importlib.resources.files('scipy.special.tests.data') + +_boost_npz = _datadir.joinpath('boost.npz') +with importlib.resources.as_file(_boost_npz) as f: + DATASETS_BOOST = np.load(f) + +_gsl_npz = _datadir.joinpath('gsl.npz') +with importlib.resources.as_file(_gsl_npz) as f: + DATASETS_GSL = np.load(f) + +_local_npz = _datadir.joinpath('local.npz') +with importlib.resources.as_file(_local_npz) as f: + DATASETS_LOCAL = np.load(f) + + +def data(func, dataname, *a, **kw): + kw.setdefault('dataname', dataname) + return FuncData(func, DATASETS_BOOST[dataname], *a, **kw) + + +def data_gsl(func, dataname, *a, **kw): + kw.setdefault('dataname', dataname) + return FuncData(func, DATASETS_GSL[dataname], *a, **kw) + + +def data_local(func, dataname, *a, **kw): + kw.setdefault('dataname', dataname) + return FuncData(func, DATASETS_LOCAL[dataname], *a, **kw) + + +# The functions lpn, lpmn, clpmn, and sph_harm appearing below are +# deprecated in favor of legendre_p_all, assoc_legendre_p_all, +# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn), +# and sph_harm_y respectively. The deprecated functions listed above are +# implemented as shims around their respective replacements. The replacements +# are tested separately, but tests for the deprecated functions remain to +# verify the correctness of the shims. + + +def ellipk_(k): + return ellipk(k*k) + + +def ellipkinc_(f, k): + return ellipkinc(f, k*k) + + +def ellipe_(k): + return ellipe(k*k) + + +def ellipeinc_(f, k): + return ellipeinc(f, k*k) + + +def zeta_(x): + return zeta(x, 1.) + + +def assoc_legendre_p_boost_(nu, mu, x): + # the boost test data is for integer orders only + return lpmv(mu, nu.astype(int), x) + +def legendre_p_via_assoc_(nu, x): + return lpmv(0, nu, x) + +def lpn_(n, x): + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + return lpn(n.astype('l'), x)[0][-1] + +def lqn_(n, x): + return lqn(n.astype('l'), x)[0][-1] + +def legendre_p_via_lpmn(n, x): + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + return lpmn(0, n, x)[0][0,-1] + +def legendre_q_via_lqmn(n, x): + return lqmn(0, n, x)[0][0,-1] + +def mathieu_ce_rad(m, q, x): + return mathieu_cem(m, q, x*180/np.pi)[0] + + +def mathieu_se_rad(m, q, x): + return mathieu_sem(m, q, x*180/np.pi)[0] + + +def mathieu_mc1_scaled(m, q, x): + # GSL follows a different normalization. + # We follow Abramowitz & Stegun, they apparently something else. + return mathieu_modcem1(m, q, x)[0] * np.sqrt(np.pi/2) + + +def mathieu_ms1_scaled(m, q, x): + return mathieu_modsem1(m, q, x)[0] * np.sqrt(np.pi/2) + + +def mathieu_mc2_scaled(m, q, x): + return mathieu_modcem2(m, q, x)[0] * np.sqrt(np.pi/2) + + +def mathieu_ms2_scaled(m, q, x): + return mathieu_modsem2(m, q, x)[0] * np.sqrt(np.pi/2) + +def eval_legendre_ld(n, x): + return eval_legendre(n.astype('l'), x) + +def eval_legendre_dd(n, x): + return eval_legendre(n.astype('d'), x) + +def eval_hermite_ld(n, x): + return eval_hermite(n.astype('l'), x) + +def eval_laguerre_ld(n, x): + return eval_laguerre(n.astype('l'), x) + +def eval_laguerre_dd(n, x): + return eval_laguerre(n.astype('d'), x) + +def eval_genlaguerre_ldd(n, a, x): + return eval_genlaguerre(n.astype('l'), a, x) + +def eval_genlaguerre_ddd(n, a, x): + return eval_genlaguerre(n.astype('d'), a, x) + +def bdtrik_comp(y, n, p): + return bdtrik(1-y, n, p) + +def btdtria_comp(p, b, x): + return btdtria(1-p, b, x) + +def btdtrib_comp(a, p, x): + return btdtrib(a, 1-p, x) + +def gdtr_(p, x): + return gdtr(1.0, p, x) + +def gdtrc_(p, x): + return gdtrc(1.0, p, x) + +def gdtrix_(b, p): + return gdtrix(1.0, b, p) + +def gdtrix_comp(b, p): + return gdtrix(1.0, b, 1-p) + +def gdtrib_(p, x): + return gdtrib(1.0, p, x) + +def gdtrib_comp(p, x): + return gdtrib(1.0, 1-p, x) + +def nbdtrik_comp(y, n, p): + return nbdtrik(1-y, n, p) + +def pdtrik_comp(p, m): + return pdtrik(1-p, m) + +def poch_(z, m): + return 1.0 / poch(z, m) + +def poch_minus(z, m): + return 1.0 / poch(z, -m) + +def spherical_jn_(n, x): + return spherical_jn(n.astype('l'), x) + +def spherical_yn_(n, x): + return spherical_yn(n.astype('l'), x) + +def sph_harm_(m, n, theta, phi): + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + y = sph_harm(m, n, theta, phi) + return (y.real, y.imag) + +def cexpm1(x, y): + z = expm1(x + 1j*y) + return z.real, z.imag + +def clog1p(x, y): + z = log1p(x + 1j*y) + return z.real, z.imag + + +BOOST_TESTS = [ + data(assoc_legendre_p_boost_, 'assoc_legendre_p_ipp-assoc_legendre_p', + (0,1,2), 3, rtol=1e-11), + + data(legendre_p_via_assoc_, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=1e-11), + data(legendre_p_via_assoc_, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=9.6e-14), + data(legendre_p_via_lpmn, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=5e-14, vectorized=False), + data(legendre_p_via_lpmn, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=3e-13, vectorized=False), + data(lpn_, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=5e-14, vectorized=False), + data(lpn_, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=3e-13, vectorized=False), + data(eval_legendre_ld, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=6e-14), + data(eval_legendre_ld, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=2e-13), + data(eval_legendre_dd, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=2e-14), + data(eval_legendre_dd, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=2e-13), + + data(lqn_, 'legendre_p_ipp-legendre_p', + (0,1), 3, rtol=2e-14, vectorized=False), + data(lqn_, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 3, rtol=2e-12, vectorized=False), + data(legendre_q_via_lqmn, 'legendre_p_ipp-legendre_p', + (0,1), 3, rtol=2e-14, vectorized=False), + data(legendre_q_via_lqmn, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 3, rtol=2e-12, vectorized=False), + + data(beta, 'beta_exp_data_ipp-beta_exp_data', + (0,1), 2, rtol=1e-13), + data(beta, 'beta_exp_data_ipp-beta_exp_data', + (0,1), 2, rtol=1e-13), + data(beta, 'beta_med_data_ipp-beta_med_data', + (0,1), 2, rtol=5e-13), + + data(betainc, 'ibeta_small_data_ipp-ibeta_small_data', + (0,1,2), 5, rtol=6e-15), + data(betainc, 'ibeta_data_ipp-ibeta_data', + (0,1,2), 5, rtol=5e-13), + data(betainc, 'ibeta_int_data_ipp-ibeta_int_data', + (0,1,2), 5, rtol=2e-14), + data(betainc, 'ibeta_large_data_ipp-ibeta_large_data', + (0,1,2), 5, rtol=4e-10), + + data(betaincinv, 'ibeta_inv_data_ipp-ibeta_inv_data', + (0,1,2), 3, rtol=1e-5), + + data(btdtria, 'ibeta_inva_data_ipp-ibeta_inva_data', + (2,0,1), 3, rtol=5e-9), + data(btdtria_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', + (2,0,1), 4, rtol=5e-9), + + data(btdtrib, 'ibeta_inva_data_ipp-ibeta_inva_data', + (0,2,1), 5, rtol=5e-9), + data(btdtrib_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', + (0,2,1), 6, rtol=5e-9), + + data(binom, 'binomial_data_ipp-binomial_data', + (0,1), 2, rtol=1e-13), + data(binom, 'binomial_large_data_ipp-binomial_large_data', + (0,1), 2, rtol=5e-13), + + data(bdtrik, 'binomial_quantile_ipp-binomial_quantile_data', + (2,0,1), 3, rtol=5e-9), + data(bdtrik_comp, 'binomial_quantile_ipp-binomial_quantile_data', + (2,0,1), 4, rtol=5e-9), + + data(nbdtrik, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', + (2,0,1), 3, rtol=4e-9), + data(nbdtrik_comp, + 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', + (2,0,1), 4, rtol=4e-9), + + data(pdtrik, 'poisson_quantile_ipp-poisson_quantile_data', + (1,0), 2, rtol=3e-9), + data(pdtrik_comp, 'poisson_quantile_ipp-poisson_quantile_data', + (1,0), 3, rtol=4e-9), + + data(cbrt, 'cbrt_data_ipp-cbrt_data', 1, 0), + + data(digamma, 'digamma_data_ipp-digamma_data', 0, 1), + data(digamma, 'digamma_data_ipp-digamma_data', 0j, 1), + data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0, 1, rtol=2e-13), + data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0j, 1, rtol=1e-13), + data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0, 1, rtol=1e-15), + data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0j, 1, rtol=1e-15), + data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0, 1, rtol=1e-15), + data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0j, 1, rtol=1e-14), + + data(ellipk_, 'ellint_k_data_ipp-ellint_k_data', 0, 1), + data(ellipkinc_, 'ellint_f_data_ipp-ellint_f_data', (0,1), 2, rtol=1e-14), + data(ellipe_, 'ellint_e_data_ipp-ellint_e_data', 0, 1), + data(ellipeinc_, 'ellint_e2_data_ipp-ellint_e2_data', (0,1), 2, rtol=1e-14), + + data(erf, 'erf_data_ipp-erf_data', 0, 1), + data(erf, 'erf_data_ipp-erf_data', 0j, 1, rtol=1e-13), + data(erfc, 'erf_data_ipp-erf_data', 0, 2, rtol=6e-15), + data(erf, 'erf_large_data_ipp-erf_large_data', 0, 1), + data(erf, 'erf_large_data_ipp-erf_large_data', 0j, 1), + data(erfc, 'erf_large_data_ipp-erf_large_data', 0, 2, rtol=4e-14), + data(erf, 'erf_small_data_ipp-erf_small_data', 0, 1), + data(erf, 'erf_small_data_ipp-erf_small_data', 0j, 1, rtol=1e-13), + data(erfc, 'erf_small_data_ipp-erf_small_data', 0, 2), + + data(erfinv, 'erf_inv_data_ipp-erf_inv_data', 0, 1), + data(erfcinv, 'erfc_inv_data_ipp-erfc_inv_data', 0, 1), + data(erfcinv, 'erfc_inv_big_data_ipp-erfc_inv_big_data', 0, 1, + param_filter=(lambda s: s > 0)), + + data(exp1, 'expint_1_data_ipp-expint_1_data', 1, 2, rtol=1e-13), + data(exp1, 'expint_1_data_ipp-expint_1_data', 1j, 2, rtol=5e-9), + data(expi, 'expinti_data_ipp-expinti_data', 0, 1, rtol=1e-13), + data(expi, 'expinti_data_double_ipp-expinti_data_double', 0, 1, rtol=1e-13), + data(expi, 'expinti_data_long_ipp-expinti_data_long', 0, 1), + + data(expn, 'expint_small_data_ipp-expint_small_data', (0,1), 2), + data(expn, 'expint_data_ipp-expint_data', (0,1), 2, rtol=1e-14), + + data(gamma, 'test_gamma_data_ipp-near_0', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_1', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_2', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_m10', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_m55', 0, 1, rtol=7e-12), + data(gamma, 'test_gamma_data_ipp-factorials', 0, 1, rtol=4e-14), + data(gamma, 'test_gamma_data_ipp-near_0', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_1', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_2', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_m10', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_m55', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-factorials', 0j, 1, rtol=2e-13), + data(gammaln, 'test_gamma_data_ipp-near_0', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-near_1', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-near_2', 0, 2, rtol=2e-10), + data(gammaln, 'test_gamma_data_ipp-near_m10', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-near_m55', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-factorials', 0, 2), + + data(gammainc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=5e-15), + data(gammainc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13), + data(gammainc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13), + data(gammainc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=1e-12), + + data(gdtr_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=1e-13), + data(gdtr_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13), + data(gdtr_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13), + data(gdtr_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=2e-9), + + data(gammaincc, 'igamma_small_data_ipp-igamma_small_data', + (0,1), 3, rtol=1e-13), + data(gammaincc, 'igamma_med_data_ipp-igamma_med_data', + (0,1), 3, rtol=2e-13), + data(gammaincc, 'igamma_int_data_ipp-igamma_int_data', + (0,1), 3, rtol=4e-14), + data(gammaincc, 'igamma_big_data_ipp-igamma_big_data', + (0,1), 3, rtol=1e-11), + + data(gdtrc_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13), + data(gdtrc_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13), + data(gdtrc_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14), + data(gdtrc_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11), + + data(gdtrib_, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 2, rtol=5e-9), + data(gdtrib_comp, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 3, rtol=5e-9), + + data(poch_, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', + (0,1), 2, rtol=2e-13), + data(poch_, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', + (0,1), 2,), + data(poch_, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', + (0,1), 2,), + data(poch_minus, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', + (0,1), 3, rtol=2e-13), + data(poch_minus, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', + (0,1), 3), + data(poch_minus, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', + (0,1), 3), + + data(eval_hermite_ld, 'hermite_ipp-hermite', + (0,1), 2, rtol=2e-14), + + data(eval_laguerre_ld, 'laguerre2_ipp-laguerre2', + (0,1), 2, rtol=7e-12), + data(eval_laguerre_dd, 'laguerre2_ipp-laguerre2', + (0,1), 2, knownfailure='hyp2f1 insufficiently accurate.'), + data(eval_genlaguerre_ldd, 'laguerre3_ipp-laguerre3', + (0,1,2), 3, rtol=2e-13), + data(eval_genlaguerre_ddd, 'laguerre3_ipp-laguerre3', + (0,1,2), 3, knownfailure='hyp2f1 insufficiently accurate.'), + + data(log1p, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 1), + data(expm1, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 2), + + data(iv, 'bessel_i_data_ipp-bessel_i_data', + (0,1), 2, rtol=1e-12), + data(iv, 'bessel_i_data_ipp-bessel_i_data', + (0,1j), 2, rtol=2e-10, atol=1e-306), + data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', + (0,1), 2, rtol=1e-9), + data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', + (0,1j), 2, rtol=2e-10), + + data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', + (0,1), 2, rtol=1.2e-13), + data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', + (0,1j), 2, rtol=1.2e-13, atol=1e-300), + + data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12), + data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12), + data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1), 2, rtol=6e-11), + data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1j), 2, rtol=6e-11), + + data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12), + data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12), + data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1), 2, rtol=1e-12), + data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1j), 2, rtol=1e-12), + + data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', + (0,1), 2, rtol=1e-13), + data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', + (0,1j), 2, rtol=1e-13), + data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', + (0,1), 2, rtol=1e-11), + data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', + (0,1j), 2, rtol=2e-11), + + data(kn, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12), + + data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12), + data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1j), 2, rtol=1e-12), + data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1), 2, rtol=1e-12), + data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1j), 2, rtol=1e-12), + + data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', + (0,1), 2, rtol=3e-14), + data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', + (0,1j), 2, rtol=3e-14), + data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1), 2, rtol=7e-14), + data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1j), 2, rtol=7e-14), + + data(yn, 'bessel_y01_data_ipp-bessel_y01_data', (0,1), 2, rtol=1e-12), + data(yn, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12), + + data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12), + data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1j), 2, rtol=1e-12), + data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1), 2, rtol=1e-10), + data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1j), 2, rtol=1e-10), + + data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', + (0, 1), 2, rtol=4e-9), + data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', + (0, 1j), 2, rtol=4e-9), + + data(zeta_, 'zeta_data_ipp-zeta_data', 0, 1, + param_filter=(lambda s: s > 1)), + data(zeta_, 'zeta_neg_data_ipp-zeta_neg_data', 0, 1, + param_filter=(lambda s: s > 1)), + data(zeta_, 'zeta_1_up_data_ipp-zeta_1_up_data', 0, 1, + param_filter=(lambda s: s > 1)), + data(zeta_, 'zeta_1_below_data_ipp-zeta_1_below_data', 0, 1, + param_filter=(lambda s: s > 1)), + + data(gammaincinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 2, rtol=1e-11), + data(gammaincinv, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 2, rtol=1e-14), + data(gammaincinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 2, rtol=1e-11), + + data(gammainccinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 3, rtol=1e-12), + data(gammainccinv, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 3, rtol=1e-14), + data(gammainccinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 3, rtol=1e-14), + + data(gdtrix_, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 2, rtol=3e-13, knownfailure='gdtrix unflow some points'), + data(gdtrix_, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 2, rtol=3e-15), + data(gdtrix_, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 2), + data(gdtrix_comp, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 2, knownfailure='gdtrix bad some points'), + data(gdtrix_comp, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 3, rtol=6e-15), + data(gdtrix_comp, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 3), + + data(chndtr, 'nccs_ipp-nccs', + (2,0,1), 3, rtol=3e-5), + data(chndtr, 'nccs_big_ipp-nccs_big', + (2,0,1), 3, rtol=5e-4, knownfailure='chndtr inaccurate some points'), + + data(sph_harm_, 'spherical_harmonic_ipp-spherical_harmonic', + (1,0,3,2), (4,5), rtol=5e-11, + param_filter=(lambda p: np.ones(p.shape, '?'), + lambda p: np.ones(p.shape, '?'), + lambda p: np.logical_and(p < 2*np.pi, p >= 0), + lambda p: np.logical_and(p < np.pi, p >= 0))), + + data(spherical_jn_, 'sph_bessel_data_ipp-sph_bessel_data', + (0,1), 2, rtol=1e-13), + data(spherical_yn_, 'sph_neumann_data_ipp-sph_neumann_data', + (0,1), 2, rtol=8e-15), + + data(owens_t, 'owens_t_ipp-owens_t', + (0, 1), 2, rtol=5e-14), + data(owens_t, 'owens_t_large_data_ipp-owens_t_large_data', + (0, 1), 2, rtol=8e-12), + + # -- test data exists in boost but is not used in scipy -- + + # ibeta_derivative_data_ipp/ibeta_derivative_data.txt + # ibeta_derivative_int_data_ipp/ibeta_derivative_int_data.txt + # ibeta_derivative_large_data_ipp/ibeta_derivative_large_data.txt + # ibeta_derivative_small_data_ipp/ibeta_derivative_small_data.txt + + # bessel_y01_prime_data_ipp/bessel_y01_prime_data.txt + # bessel_yn_prime_data_ipp/bessel_yn_prime_data.txt + # sph_bessel_prime_data_ipp/sph_bessel_prime_data.txt + # sph_neumann_prime_data_ipp/sph_neumann_prime_data.txt + + # ellint_d2_data_ipp/ellint_d2_data.txt + # ellint_d_data_ipp/ellint_d_data.txt + # ellint_pi2_data_ipp/ellint_pi2_data.txt + # ellint_pi3_data_ipp/ellint_pi3_data.txt + # ellint_pi3_large_data_ipp/ellint_pi3_large_data.txt + data(elliprc, 'ellint_rc_data_ipp-ellint_rc_data', (0, 1), 2, + rtol=5e-16), + data(elliprd, 'ellint_rd_data_ipp-ellint_rd_data', (0, 1, 2), 3, + rtol=5e-16), + data(elliprd, 'ellint_rd_0xy_ipp-ellint_rd_0xy', (0, 1, 2), 3, + rtol=5e-16), + data(elliprd, 'ellint_rd_0yy_ipp-ellint_rd_0yy', (0, 1, 2), 3, + rtol=5e-16), + data(elliprd, 'ellint_rd_xxx_ipp-ellint_rd_xxx', (0, 1, 2), 3, + rtol=5e-16), + # Some of the following rtol for elliprd may be larger than 5e-16 to + # work around some hard cases in the Boost test where we get slightly + # larger error than the ideal bound when the x (==y) input is close to + # zero. + # Also the accuracy on 32-bit builds with g++ may suffer from excess + # loss of precision; see GCC bugzilla 323 + # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323 + data(elliprd, 'ellint_rd_xxz_ipp-ellint_rd_xxz', (0, 1, 2), 3, + rtol=6.5e-16), + data(elliprd, 'ellint_rd_xyy_ipp-ellint_rd_xyy', (0, 1, 2), 3, + rtol=6e-16), + data(elliprf, 'ellint_rf_data_ipp-ellint_rf_data', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_xxx_ipp-ellint_rf_xxx', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_xyy_ipp-ellint_rf_xyy', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_xy0_ipp-ellint_rf_xy0', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_0yy_ipp-ellint_rf_0yy', (0, 1, 2), 3, + rtol=5e-16), + # The accuracy of R_G is primarily limited by R_D that is used + # internally. It is generally worse than R_D. Notice that we increased + # the rtol for R_G here. The cases with duplicate arguments are + # slightly less likely to be unbalanced (at least two arguments are + # already balanced) so the error bound is slightly better. Again, + # precision with g++ 32-bit is even worse. + data(elliprg, 'ellint_rg_ipp-ellint_rg', (0, 1, 2), 3, + rtol=8.0e-16), + data(elliprg, 'ellint_rg_xxx_ipp-ellint_rg_xxx', (0, 1, 2), 3, + rtol=6e-16), + data(elliprg, 'ellint_rg_xyy_ipp-ellint_rg_xyy', (0, 1, 2), 3, + rtol=7.5e-16), + data(elliprg, 'ellint_rg_xy0_ipp-ellint_rg_xy0', (0, 1, 2), 3, + rtol=5e-16), + data(elliprg, 'ellint_rg_00x_ipp-ellint_rg_00x', (0, 1, 2), 3, + rtol=5e-16), + data(elliprj, 'ellint_rj_data_ipp-ellint_rj_data', (0, 1, 2, 3), 4, + rtol=5e-16, atol=1e-25, + param_filter=(lambda s: s <= 5e-26,)), + # ellint_rc_data_ipp/ellint_rc_data.txt + # ellint_rd_0xy_ipp/ellint_rd_0xy.txt + # ellint_rd_0yy_ipp/ellint_rd_0yy.txt + # ellint_rd_data_ipp/ellint_rd_data.txt + # ellint_rd_xxx_ipp/ellint_rd_xxx.txt + # ellint_rd_xxz_ipp/ellint_rd_xxz.txt + # ellint_rd_xyy_ipp/ellint_rd_xyy.txt + # ellint_rf_0yy_ipp/ellint_rf_0yy.txt + # ellint_rf_data_ipp/ellint_rf_data.txt + # ellint_rf_xxx_ipp/ellint_rf_xxx.txt + # ellint_rf_xy0_ipp/ellint_rf_xy0.txt + # ellint_rf_xyy_ipp/ellint_rf_xyy.txt + # ellint_rg_00x_ipp/ellint_rg_00x.txt + # ellint_rg_ipp/ellint_rg.txt + # ellint_rg_xxx_ipp/ellint_rg_xxx.txt + # ellint_rg_xy0_ipp/ellint_rg_xy0.txt + # ellint_rg_xyy_ipp/ellint_rg_xyy.txt + # ellint_rj_data_ipp/ellint_rj_data.txt + # ellint_rj_e2_ipp/ellint_rj_e2.txt + # ellint_rj_e3_ipp/ellint_rj_e3.txt + # ellint_rj_e4_ipp/ellint_rj_e4.txt + # ellint_rj_zp_ipp/ellint_rj_zp.txt + + # jacobi_elliptic_ipp/jacobi_elliptic.txt + # jacobi_elliptic_small_ipp/jacobi_elliptic_small.txt + # jacobi_large_phi_ipp/jacobi_large_phi.txt + # jacobi_near_1_ipp/jacobi_near_1.txt + # jacobi_zeta_big_phi_ipp/jacobi_zeta_big_phi.txt + # jacobi_zeta_data_ipp/jacobi_zeta_data.txt + + # heuman_lambda_data_ipp/heuman_lambda_data.txt + + # hypergeometric_0F2_ipp/hypergeometric_0F2.txt + # hypergeometric_1F1_big_ipp/hypergeometric_1F1_big.txt + # hypergeometric_1F1_ipp/hypergeometric_1F1.txt + # hypergeometric_1F1_small_random_ipp/hypergeometric_1F1_small_random.txt + # hypergeometric_1F2_ipp/hypergeometric_1F2.txt + # hypergeometric_1f1_large_regularized_ipp/hypergeometric_1f1_large_regularized.txt # noqa: E501 + # hypergeometric_1f1_log_large_unsolved_ipp/hypergeometric_1f1_log_large_unsolved.txt # noqa: E501 + # hypergeometric_2F0_half_ipp/hypergeometric_2F0_half.txt + # hypergeometric_2F0_integer_a2_ipp/hypergeometric_2F0_integer_a2.txt + # hypergeometric_2F0_ipp/hypergeometric_2F0.txt + # hypergeometric_2F0_large_z_ipp/hypergeometric_2F0_large_z.txt + # hypergeometric_2F1_ipp/hypergeometric_2F1.txt + # hypergeometric_2F2_ipp/hypergeometric_2F2.txt + + # ncbeta_big_ipp/ncbeta_big.txt + # nct_small_delta_ipp/nct_small_delta.txt + # nct_asym_ipp/nct_asym.txt + # ncbeta_ipp/ncbeta.txt + + # powm1_data_ipp/powm1_big_data.txt + # powm1_sqrtp1m1_test_hpp/sqrtp1m1_data.txt + + # sinc_data_ipp/sinc_data.txt + + # test_gamma_data_ipp/gammap1m1_data.txt + # tgamma_ratio_data_ipp/tgamma_ratio_data.txt + + # trig_data_ipp/trig_data.txt + # trig_data2_ipp/trig_data2.txt +] + + +@pytest.mark.thread_unsafe +@pytest.mark.parametrize('test', BOOST_TESTS, ids=repr) +def test_boost(test): + _test_factory(test) + + +GSL_TESTS = [ + data_gsl(mathieu_a, 'mathieu_ab', (0, 1), 2, rtol=1e-13, atol=1e-13), + data_gsl(mathieu_b, 'mathieu_ab', (0, 1), 3, rtol=1e-13, atol=1e-13), + + # Also the GSL output has limited accuracy... + data_gsl(mathieu_ce_rad, 'mathieu_ce_se', (0, 1, 2), 3, rtol=1e-7, atol=1e-13), + data_gsl(mathieu_se_rad, 'mathieu_ce_se', (0, 1, 2), 4, rtol=1e-7, atol=1e-13), + + data_gsl(mathieu_mc1_scaled, 'mathieu_mc_ms', + (0, 1, 2), 3, rtol=1e-7, atol=1e-13), + data_gsl(mathieu_ms1_scaled, 'mathieu_mc_ms', + (0, 1, 2), 4, rtol=1e-7, atol=1e-13), + + data_gsl(mathieu_mc2_scaled, 'mathieu_mc_ms', + (0, 1, 2), 5, rtol=1e-7, atol=1e-13), + data_gsl(mathieu_ms2_scaled, 'mathieu_mc_ms', + (0, 1, 2), 6, rtol=1e-7, atol=1e-13), +] + + +@pytest.mark.parametrize('test', GSL_TESTS, ids=repr) +def test_gsl(test): + _test_factory(test) + + +LOCAL_TESTS = [ + data_local(ellipkinc, 'ellipkinc_neg_m', (0, 1), 2), + data_local(ellipkm1, 'ellipkm1', 0, 1), + data_local(ellipeinc, 'ellipeinc_neg_m', (0, 1), 2), + data_local(clog1p, 'log1p_expm1_complex', (0,1), (2,3), rtol=1e-14), + data_local(cexpm1, 'log1p_expm1_complex', (0,1), (4,5), rtol=1e-14), + data_local(gammainc, 'gammainc', (0, 1), 2, rtol=1e-12), + data_local(gammaincc, 'gammaincc', (0, 1), 2, rtol=1e-11), + data_local(ellip_harm_2, 'ellip',(0, 1, 2, 3, 4), 6, rtol=1e-10, atol=1e-13), + data_local(ellip_harm, 'ellip',(0, 1, 2, 3, 4), 5, rtol=1e-10, atol=1e-13), + data_local(wright_bessel, 'wright_bessel', (0, 1, 2), 3, rtol=1e-11), +] + + +@pytest.mark.parametrize('test', LOCAL_TESTS, ids=repr) +def test_local(test): + _test_factory(test) + + +def _test_factory(test, dtype=np.float64): + """Boost test""" + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error is detected") + with np.errstate(all='ignore'): + test.check(dtype=dtype) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py new file mode 100644 index 0000000000000000000000000000000000000000..6da2c8ddddd7341cbb777216e9f2f3cce536a51e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py @@ -0,0 +1,42 @@ +# Tests for a few of the "double-double" C++ functions defined in +# special/cephes/dd_real.h. Prior to gh-20390 which translated these +# functions from C to C++, there were test cases for _dd_expm1. It +# was determined that this function is not used anywhere internally +# in SciPy, so this function was not translated. + + +import pytest +from numpy.testing import assert_allclose +from scipy.special._test_internal import _dd_exp, _dd_log + + +# Each tuple in test_data contains: +# (dd_func, xhi, xlo, expected_yhi, expected_ylo) +# The expected values were computed with mpmath, e.g. +# +# import mpmath +# mpmath.mp.dps = 100 +# xhi = 10.0 +# xlo = 0.0 +# x = mpmath.mpf(xhi) + mpmath.mpf(xlo) +# y = mpmath.log(x) +# expected_yhi = float(y) +# expected_ylo = float(y - expected_yhi) +# +test_data = [ + (_dd_exp, -0.3333333333333333, -1.850371707708594e-17, + 0.7165313105737893, -2.0286948382455594e-17), + (_dd_exp, 0.0, 0.0, 1.0, 0.0), + (_dd_exp, 10.0, 0.0, 22026.465794806718, -1.3780134700517372e-12), + (_dd_log, 0.03125, 0.0, -3.4657359027997265, -4.930038229799327e-18), + (_dd_log, 10.0, 0.0, 2.302585092994046, -2.1707562233822494e-16), +] + + +@pytest.mark.parametrize('dd_func, xhi, xlo, expected_yhi, expected_ylo', + test_data) +def test_dd(dd_func, xhi, xlo, expected_yhi, expected_ylo): + yhi, ylo = dd_func(xhi, xlo) + assert yhi == expected_yhi, (f"high double ({yhi}) does not equal the " + f"expected value {expected_yhi}") + assert_allclose(ylo, expected_ylo, rtol=5e-15) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f27dc7b71c1ae928b4bdd8bd987df9ca420bab --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py @@ -0,0 +1,45 @@ +import numpy as np +from numpy import pi, log, sqrt +from numpy.testing import assert_, assert_equal + +from scipy.special._testutils import FuncData +import scipy.special as sc + +# Euler-Mascheroni constant +euler = 0.57721566490153286 + + +def test_consistency(): + # Make sure the implementation of digamma for real arguments + # agrees with the implementation of digamma for complex arguments. + + # It's all poles after -1e16 + x = np.r_[-np.logspace(15, -30, 200), np.logspace(-30, 300, 200)] + dataset = np.vstack((x + 0j, sc.digamma(x))).T + FuncData(sc.digamma, dataset, 0, 1, rtol=5e-14, nan_ok=True).check() + + +def test_special_values(): + # Test special values from Gauss's digamma theorem. See + # + # https://en.wikipedia.org/wiki/Digamma_function + + dataset = [ + (1, -euler), + (0.5, -2*log(2) - euler), + (1/3, -pi/(2*sqrt(3)) - 3*log(3)/2 - euler), + (1/4, -pi/2 - 3*log(2) - euler), + (1/6, -pi*sqrt(3)/2 - 2*log(2) - 3*log(3)/2 - euler), + (1/8, + -pi/2 - 4*log(2) - (pi + log(2 + sqrt(2)) - log(2 - sqrt(2)))/sqrt(2) - euler) + ] + + dataset = np.asarray(dataset) + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check() + + +def test_nonfinite(): + pts = [0.0, -0.0, np.inf] + std = [-np.inf, np.inf, np.inf] + assert_equal(sc.digamma(pts), std) + assert_(all(np.isnan(sc.digamma([-np.inf, -1])))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py new file mode 100644 index 0000000000000000000000000000000000000000..1cfb6530e2fd80d2c261af960f42c974e1e1b26e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py @@ -0,0 +1,278 @@ +# +# Tests for the Ellipsoidal Harmonic Function, +# Distributed under the same license as SciPy itself. +# + +import numpy as np +from numpy.testing import (assert_equal, assert_almost_equal, assert_allclose, + assert_, suppress_warnings) +from scipy.special._testutils import assert_func_equal +from scipy.special import ellip_harm, ellip_harm_2, ellip_normal +from scipy.integrate import IntegrationWarning +from numpy import sqrt, pi + + +def test_ellip_potential(): + def change_coefficient(lambda1, mu, nu, h2, k2): + x = sqrt(lambda1**2*mu**2*nu**2/(h2*k2)) + y = sqrt((lambda1**2 - h2)*(mu**2 - h2)*(h2 - nu**2)/(h2*(k2 - h2))) + z = sqrt((lambda1**2 - k2)*(k2 - mu**2)*(k2 - nu**2)/(k2*(k2 - h2))) + return x, y, z + + def solid_int_ellip(lambda1, mu, nu, n, p, h2, k2): + return (ellip_harm(h2, k2, n, p, lambda1)*ellip_harm(h2, k2, n, p, mu) + * ellip_harm(h2, k2, n, p, nu)) + + def solid_int_ellip2(lambda1, mu, nu, n, p, h2, k2): + return (ellip_harm_2(h2, k2, n, p, lambda1) + * ellip_harm(h2, k2, n, p, mu)*ellip_harm(h2, k2, n, p, nu)) + + def summation(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2): + tol = 1e-8 + sum1 = 0 + for n in range(20): + xsum = 0 + for p in range(1, 2*n+2): + xsum += (4*pi*(solid_int_ellip(lambda2, mu2, nu2, n, p, h2, k2) + * solid_int_ellip2(lambda1, mu1, nu1, n, p, h2, k2)) / + (ellip_normal(h2, k2, n, p)*(2*n + 1))) + if abs(xsum) < 0.1*tol*abs(sum1): + break + sum1 += xsum + return sum1, xsum + + def potential(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2): + x1, y1, z1 = change_coefficient(lambda1, mu1, nu1, h2, k2) + x2, y2, z2 = change_coefficient(lambda2, mu2, nu2, h2, k2) + res = sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2) + return 1/res + + pts = [ + (120, sqrt(19), 2, 41, sqrt(17), 2, 15, 25), + (120, sqrt(16), 3.2, 21, sqrt(11), 2.9, 11, 20), + ] + + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error") + sup.filter(IntegrationWarning, "The maximum number of subdivisions") + + for p in pts: + err_msg = repr(p) + exact = potential(*p) + result, last_term = summation(*p) + assert_allclose(exact, result, atol=0, rtol=1e-8, err_msg=err_msg) + assert_(abs(result - exact) < 10*abs(last_term), err_msg) + + +def test_ellip_norm(): + + def G01(h2, k2): + return 4*pi + + def G11(h2, k2): + return 4*pi*h2*k2/3 + + def G12(h2, k2): + return 4*pi*h2*(k2 - h2)/3 + + def G13(h2, k2): + return 4*pi*k2*(k2 - h2)/3 + + def G22(h2, k2): + res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2 + + sqrt(h2**2 + k2**2 - h2*k2)*(-2*(h2**3 + k2**3) + 3*h2*k2*(h2 + k2))) + return 16*pi/405*res + + def G21(h2, k2): + res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2 + + sqrt(h2**2 + k2**2 - h2*k2)*(2*(h2**3 + k2**3) - 3*h2*k2*(h2 + k2))) + return 16*pi/405*res + + def G23(h2, k2): + return 4*pi*h2**2*k2*(k2 - h2)/15 + + def G24(h2, k2): + return 4*pi*h2*k2**2*(k2 - h2)/15 + + def G25(h2, k2): + return 4*pi*h2*k2*(k2 - h2)**2/15 + + def G32(h2, k2): + res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2 + + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(-8*(h2**3 + k2**3) + + 11*h2*k2*(h2 + k2))) + return 16*pi/13125*k2*h2*res + + def G31(h2, k2): + res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2 + + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(8*(h2**3 + k2**3) - + 11*h2*k2*(h2 + k2))) + return 16*pi/13125*h2*k2*res + + def G34(h2, k2): + res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(h2**2 + 4*k2**2 - h2*k2)*(-6*h2**3 - 8*k2**3 + 9*h2**2*k2 + + 13*h2*k2**2)) + return 16*pi/13125*h2*(k2 - h2)*res + + def G33(h2, k2): + res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(h2**2 + 4*k2**2 - h2*k2)*(6*h2**3 + 8*k2**3 - 9*h2**2*k2 - + 13*h2*k2**2)) + return 16*pi/13125*h2*(k2 - h2)*res + + def G36(h2, k2): + res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(4*h2**2 + k2**2 - h2*k2)*(-8*h2**3 - 6*k2**3 + 13*h2**2*k2 + + 9*h2*k2**2)) + return 16*pi/13125*k2*(k2 - h2)*res + + def G35(h2, k2): + res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(4*h2**2 + k2**2 - h2*k2)*(8*h2**3 + 6*k2**3 - 13*h2**2*k2 - + 9*h2*k2**2)) + return 16*pi/13125*k2*(k2 - h2)*res + + def G37(h2, k2): + return 4*pi*h2**2*k2**2*(k2 - h2)**2/105 + + known_funcs = {(0, 1): G01, (1, 1): G11, (1, 2): G12, (1, 3): G13, + (2, 1): G21, (2, 2): G22, (2, 3): G23, (2, 4): G24, + (2, 5): G25, (3, 1): G31, (3, 2): G32, (3, 3): G33, + (3, 4): G34, (3, 5): G35, (3, 6): G36, (3, 7): G37} + + def _ellip_norm(n, p, h2, k2): + func = known_funcs[n, p] + return func(h2, k2) + _ellip_norm = np.vectorize(_ellip_norm) + + def ellip_normal_known(h2, k2, n, p): + return _ellip_norm(n, p, h2, k2) + + # generate both large and small h2 < k2 pairs + np.random.seed(1234) + h2 = np.random.pareto(0.5, size=1) + k2 = h2 * (1 + np.random.pareto(0.5, size=h2.size)) + + points = [] + for n in range(4): + for p in range(1, 2*n+2): + points.append((h2, k2, np.full(h2.size, n), np.full(h2.size, p))) + points = np.array(points) + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error") + assert_func_equal(ellip_normal, ellip_normal_known, points, rtol=1e-12) + + +def test_ellip_harm_2(): + + def I1(h2, k2, s): + res = (ellip_harm_2(h2, k2, 1, 1, s)/(3 * ellip_harm(h2, k2, 1, 1, s)) + + ellip_harm_2(h2, k2, 1, 2, s)/(3 * ellip_harm(h2, k2, 1, 2, s)) + + ellip_harm_2(h2, k2, 1, 3, s)/(3 * ellip_harm(h2, k2, 1, 3, s))) + return res + + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error") + assert_almost_equal(I1(5, 8, 10), 1/(10*sqrt((100-5)*(100-8)))) + + # Values produced by code from arXiv:1204.0267 + assert_almost_equal(ellip_harm_2(5, 8, 2, 1, 10), 0.00108056853382) + assert_almost_equal(ellip_harm_2(5, 8, 2, 2, 10), 0.00105820513809) + assert_almost_equal(ellip_harm_2(5, 8, 2, 3, 10), 0.00106058384743) + assert_almost_equal(ellip_harm_2(5, 8, 2, 4, 10), 0.00106774492306) + assert_almost_equal(ellip_harm_2(5, 8, 2, 5, 10), 0.00107976356454) + + +def test_ellip_harm(): + + def E01(h2, k2, s): + return 1 + + def E11(h2, k2, s): + return s + + def E12(h2, k2, s): + return sqrt(abs(s*s - h2)) + + def E13(h2, k2, s): + return sqrt(abs(s*s - k2)) + + def E21(h2, k2, s): + return s*s - 1/3*((h2 + k2) + sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2))) + + def E22(h2, k2, s): + return s*s - 1/3*((h2 + k2) - sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2))) + + def E23(h2, k2, s): + return s * sqrt(abs(s*s - h2)) + + def E24(h2, k2, s): + return s * sqrt(abs(s*s - k2)) + + def E25(h2, k2, s): + return sqrt(abs((s*s - h2)*(s*s - k2))) + + def E31(h2, k2, s): + return s*s*s - (s/5)*(2*(h2 + k2) + sqrt(4*(h2 + k2)*(h2 + k2) - + 15*h2*k2)) + + def E32(h2, k2, s): + return s*s*s - (s/5)*(2*(h2 + k2) - sqrt(4*(h2 + k2)*(h2 + k2) - + 15*h2*k2)) + + def E33(h2, k2, s): + return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) + sqrt(abs((h2 + + 2*k2)*(h2 + 2*k2) - 5*h2*k2)))) + + def E34(h2, k2, s): + return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) - sqrt(abs((h2 + + 2*k2)*(h2 + 2*k2) - 5*h2*k2)))) + + def E35(h2, k2, s): + return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) + sqrt(abs((2*h2 + + k2)*(2*h2 + k2) - 5*h2*k2)))) + + def E36(h2, k2, s): + return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) - sqrt(abs((2*h2 + + k2)*(2*h2 + k2) - 5*h2*k2)))) + + def E37(h2, k2, s): + return s * sqrt(abs((s*s - h2)*(s*s - k2))) + + assert_equal(ellip_harm(5, 8, 1, 2, 2.5, 1, 1), + ellip_harm(5, 8, 1, 2, 2.5)) + + known_funcs = {(0, 1): E01, (1, 1): E11, (1, 2): E12, (1, 3): E13, + (2, 1): E21, (2, 2): E22, (2, 3): E23, (2, 4): E24, + (2, 5): E25, (3, 1): E31, (3, 2): E32, (3, 3): E33, + (3, 4): E34, (3, 5): E35, (3, 6): E36, (3, 7): E37} + + point_ref = [] + + def ellip_harm_known(h2, k2, n, p, s): + for i in range(h2.size): + func = known_funcs[(int(n[i]), int(p[i]))] + point_ref.append(func(h2[i], k2[i], s[i])) + return point_ref + + rng = np.random.RandomState(1234) + h2 = rng.pareto(0.5, size=30) + k2 = h2*(1 + rng.pareto(0.5, size=h2.size)) + s = rng.pareto(0.5, size=h2.size) + points = [] + for i in range(h2.size): + for n in range(4): + for p in range(1, 2*n+2): + points.append((h2[i], k2[i], n, p, s[i])) + points = np.array(points) + assert_func_equal(ellip_harm, ellip_harm_known, points, rtol=1e-12) + + +def test_ellip_harm_invalid_p(): + # Regression test. This should return nan. + n = 4 + # Make p > 2*n + 1. + p = 2*n + 2 + result = ellip_harm(0.5, 2.0, n, p, 0.2) + assert np.isnan(result) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py new file mode 100644 index 0000000000000000000000000000000000000000..98739b93fc6ad75a41a7b80107ee696453b12a09 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py @@ -0,0 +1,89 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pytest + +import scipy.special as sc + + +class TestInverseErrorFunction: + def test_compliment(self): + # Test erfcinv(1 - x) == erfinv(x) + x = np.linspace(-1, 1, 101) + assert_allclose(sc.erfcinv(1 - x), sc.erfinv(x), rtol=0, atol=1e-15) + + def test_literal_values(self): + # The expected values were calculated with mpmath: + # + # import mpmath + # mpmath.mp.dps = 200 + # for y in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]: + # x = mpmath.erfinv(y) + # print(x) + # + y = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) + actual = sc.erfinv(y) + expected = [ + 0.0, + 0.08885599049425769, + 0.1791434546212917, + 0.2724627147267543, + 0.37080715859355795, + 0.4769362762044699, + 0.5951160814499948, + 0.7328690779592167, + 0.9061938024368233, + 1.1630871536766743, + ] + assert_allclose(actual, expected, rtol=0, atol=1e-15) + + @pytest.mark.parametrize( + 'f, x, y', + [ + (sc.erfinv, -1, -np.inf), + (sc.erfinv, 0, 0), + (sc.erfinv, 1, np.inf), + (sc.erfinv, -100, np.nan), + (sc.erfinv, 100, np.nan), + (sc.erfcinv, 0, np.inf), + (sc.erfcinv, 1, -0.0), + (sc.erfcinv, 2, -np.inf), + (sc.erfcinv, -100, np.nan), + (sc.erfcinv, 100, np.nan), + ], + ids=[ + 'erfinv at lower bound', + 'erfinv at midpoint', + 'erfinv at upper bound', + 'erfinv below lower bound', + 'erfinv above upper bound', + 'erfcinv at lower bound', + 'erfcinv at midpoint', + 'erfcinv at upper bound', + 'erfcinv below lower bound', + 'erfcinv above upper bound', + ] + ) + def test_domain_bounds(self, f, x, y): + assert_equal(f(x), y) + + def test_erfinv_asympt(self): + # regression test for gh-12758: erfinv(x) loses precision at small x + # expected values precomputed with mpmath: + # >>> mpmath.mp.dps = 100 + # >>> expected = [float(mpmath.erfinv(t)) for t in x] + x = np.array([1e-20, 1e-15, 1e-14, 1e-10, 1e-8, 0.9e-7, 1.1e-7, 1e-6]) + expected = np.array([8.86226925452758e-21, + 8.862269254527581e-16, + 8.86226925452758e-15, + 8.862269254527581e-11, + 8.86226925452758e-09, + 7.97604232907484e-08, + 9.74849617998037e-08, + 8.8622692545299e-07]) + assert_allclose(sc.erfinv(x), expected, + rtol=1e-15) + + # also test the roundtrip consistency + assert_allclose(sc.erf(sc.erfinv(x)), + x, + rtol=5e-15) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py new file mode 100644 index 0000000000000000000000000000000000000000..8332a83267e2f75dded04e80443c150c832676c8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py @@ -0,0 +1,118 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose +import scipy.special as sc + + +class TestExp1: + + def test_branch_cut(self): + assert np.isnan(sc.exp1(-1)) + assert sc.exp1(complex(-1, 0)).imag == ( + -sc.exp1(complex(-1, -0.0)).imag + ) + + assert_allclose( + sc.exp1(complex(-1, 0)), + sc.exp1(-1 + 1e-20j), + atol=0, + rtol=1e-15 + ) + assert_allclose( + sc.exp1(complex(-1, -0.0)), + sc.exp1(-1 - 1e-20j), + atol=0, + rtol=1e-15 + ) + + def test_834(self): + # Regression test for #834 + a = sc.exp1(-complex(19.9999990)) + b = sc.exp1(-complex(19.9999991)) + assert_allclose(a.imag, b.imag, atol=0, rtol=1e-15) + + +class TestScaledExp1: + + @pytest.mark.parametrize('x, expected', [(0, 0), (np.inf, 1)]) + def test_limits(self, x, expected): + y = sc._ufuncs._scaled_exp1(x) + assert y == expected + + # The expected values were computed with mpmath, e.g.: + # + # from mpmath import mp + # mp.dps = 80 + # x = 1e-25 + # print(float(x*mp.exp(x)*np.expint(1, x))) + # + # prints 5.698741165994961e-24 + # + # The method used to compute _scaled_exp1 changes at x=1 + # and x=1250, so values at those inputs, and values just + # above and below them, are included in the test data. + @pytest.mark.parametrize('x, expected', + [(1e-25, 5.698741165994961e-24), + (0.1, 0.20146425447084518), + (0.9995, 0.5962509885831002), + (1.0, 0.5963473623231941), + (1.0005, 0.5964436833238044), + (2.5, 0.7588145912149602), + (10.0, 0.9156333393978808), + (100.0, 0.9901942286733019), + (500.0, 0.9980079523802055), + (1000.0, 0.9990019940238807), + (1249.5, 0.9992009578306811), + (1250.0, 0.9992012769377913), + (1250.25, 0.9992014363957858), + (2000.0, 0.9995004992514963), + (1e4, 0.9999000199940024), + (1e10, 0.9999999999), + (1e15, 0.999999999999999), + ]) + def test_scaled_exp1(self, x, expected): + y = sc._ufuncs._scaled_exp1(x) + assert_allclose(y, expected, rtol=2e-15) + + +class TestExpi: + + @pytest.mark.parametrize('result', [ + sc.expi(complex(-1, 0)), + sc.expi(complex(-1, -0.0)), + sc.expi(-1) + ]) + def test_branch_cut(self, result): + desired = -0.21938393439552027368 # Computed using Mpmath + assert_allclose(result, desired, atol=0, rtol=1e-14) + + def test_near_branch_cut(self): + lim_from_above = sc.expi(-1 + 1e-20j) + lim_from_below = sc.expi(-1 - 1e-20j) + assert_allclose( + lim_from_above.real, + lim_from_below.real, + atol=0, + rtol=1e-15 + ) + assert_allclose( + lim_from_above.imag, + -lim_from_below.imag, + atol=0, + rtol=1e-15 + ) + + def test_continuity_on_positive_real_axis(self): + assert_allclose( + sc.expi(complex(1, 0)), + sc.expi(complex(1, -0.0)), + atol=0, + rtol=1e-15 + ) + + +class TestExpn: + + def test_out_of_domain(self): + assert all(np.isnan([sc.expn(-1, 1.0), sc.expn(1, -1.0)])) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecaf51545e006e37a451a08f356ce0392a3159c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py @@ -0,0 +1,28 @@ +import os +import platform +import sysconfig + +import pytest + +from scipy._lib._testutils import IS_EDITABLE,_test_cython_extension, cython +from scipy.special import beta, gamma + + +@pytest.mark.fail_slow(40) +# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247 +@pytest.mark.skipif(IS_EDITABLE, + reason='Editable install cannot find .pxd headers.') +@pytest.mark.skipif((platform.system() == 'Windows' and + sysconfig.get_config_var('Py_GIL_DISABLED')), + reason='gh-22039') +@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"], + reason="Can't start subprocess") +@pytest.mark.skipif(cython is None, reason="requires cython") +def test_cython(tmp_path): + srcdir = os.path.dirname(os.path.dirname(__file__)) + extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir) + # actually test the cython c-extensions + assert extensions.cy_beta(0.5, 0.1) == beta(0.5, 0.1) + assert extensions.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j) + assert extensions_cpp.cy_beta(0.5, 0.1) == beta(0.5, 0.1) + assert extensions_cpp.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py new file mode 100644 index 0000000000000000000000000000000000000000..8868f66c47ce0d4bbb21c78435a6c89d44065252 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py @@ -0,0 +1,85 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose +import scipy.special as sc +from scipy.special._testutils import FuncData + + +class TestVoigtProfile: + + @pytest.mark.parametrize('x, sigma, gamma', [ + (np.nan, 1, 1), + (0, np.nan, 1), + (0, 1, np.nan), + (1, np.nan, 0), + (np.nan, 1, 0), + (1, 0, np.nan), + (np.nan, 0, 1), + (np.nan, 0, 0) + ]) + def test_nan(self, x, sigma, gamma): + assert np.isnan(sc.voigt_profile(x, sigma, gamma)) + + @pytest.mark.parametrize('x, desired', [ + (-np.inf, 0), + (np.inf, 0) + ]) + def test_inf(self, x, desired): + assert sc.voigt_profile(x, 1, 1) == desired + + def test_against_mathematica(self): + # Results obtained from Mathematica by computing + # + # PDF[VoigtDistribution[gamma, sigma], x] + # + points = np.array([ + [-7.89, 45.06, 6.66, 0.0077921073660388806401], + [-0.05, 7.98, 24.13, 0.012068223646769913478], + [-13.98, 16.83, 42.37, 0.0062442236362132357833], + [-12.66, 0.21, 6.32, 0.010052516161087379402], + [11.34, 4.25, 21.96, 0.0113698923627278917805], + [-11.56, 20.40, 30.53, 0.0076332760432097464987], + [-9.17, 25.61, 8.32, 0.011646345779083005429], + [16.59, 18.05, 2.50, 0.013637768837526809181], + [9.11, 2.12, 39.33, 0.0076644040807277677585], + [-43.33, 0.30, 45.68, 0.0036680463875330150996] + ]) + FuncData( + sc.voigt_profile, + points, + (0, 1, 2), + 3, + atol=0, + rtol=1e-15 + ).check() + + def test_symmetry(self): + x = np.linspace(0, 10, 20) + assert_allclose( + sc.voigt_profile(x, 1, 1), + sc.voigt_profile(-x, 1, 1), + rtol=1e-15, + atol=0 + ) + + @pytest.mark.parametrize('x, sigma, gamma, desired', [ + (0, 0, 0, np.inf), + (1, 0, 0, 0) + ]) + def test_corner_cases(self, x, sigma, gamma, desired): + assert sc.voigt_profile(x, sigma, gamma) == desired + + @pytest.mark.parametrize('sigma1, gamma1, sigma2, gamma2', [ + (0, 1, 1e-16, 1), + (1, 0, 1, 1e-16), + (0, 0, 1e-16, 1e-16) + ]) + def test_continuity(self, sigma1, gamma1, sigma2, gamma2): + x = np.linspace(1, 10, 20) + assert_allclose( + sc.voigt_profile(x, sigma1, gamma1), + sc.voigt_profile(x, sigma2, gamma2), + rtol=1e-16, + atol=1e-16 + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3fbd17dddeed73d311566a930f52899e3b9db6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py @@ -0,0 +1,12 @@ +import numpy as np +import scipy.special as sc + + +class TestRgamma: + + def test_gh_11315(self): + assert sc.rgamma(-35) == 0 + + def test_rgamma_zeros(self): + x = np.array([0, -10, -100, -1000, -10000]) + assert np.all(sc.rgamma(x) == 0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py new file mode 100644 index 0000000000000000000000000000000000000000..aae34e5c23f2d293f362abd825f1dad454371ae0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py @@ -0,0 +1,136 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal + +import scipy.special as sc +from scipy.special._testutils import FuncData + + +INVALID_POINTS = [ + (1, -1), + (0, 0), + (-1, 1), + (np.nan, 1), + (1, np.nan) +] + + +class TestGammainc: + + @pytest.mark.parametrize('a, x', INVALID_POINTS) + def test_domain(self, a, x): + assert np.isnan(sc.gammainc(a, x)) + + def test_a_eq_0_x_gt_0(self): + assert sc.gammainc(0, 1) == 1 + + @pytest.mark.parametrize('a, x, desired', [ + (np.inf, 1, 0), + (np.inf, 0, 0), + (np.inf, np.inf, np.nan), + (1, np.inf, 1) + ]) + def test_infinite_arguments(self, a, x, desired): + result = sc.gammainc(a, x) + if np.isnan(desired): + assert np.isnan(result) + else: + assert result == desired + + def test_infinite_limits(self): + # Test that large arguments converge to the hard-coded limits + # at infinity. + assert_allclose( + sc.gammainc(1000, 100), + sc.gammainc(np.inf, 100), + atol=1e-200, # Use `atol` since the function converges to 0. + rtol=0 + ) + assert sc.gammainc(100, 1000) == sc.gammainc(100, np.inf) + + def test_x_zero(self): + a = np.arange(1, 10) + assert_array_equal(sc.gammainc(a, 0), 0) + + def test_limit_check(self): + result = sc.gammainc(1e-10, 1) + limit = sc.gammainc(0, 1) + assert np.isclose(result, limit) + + def gammainc_line(self, x): + # The line a = x where a simpler asymptotic expansion (analog + # of DLMF 8.12.15) is available. + c = np.array([-1/3, -1/540, 25/6048, 101/155520, + -3184811/3695155200, -2745493/8151736420]) + res = 0 + xfac = 1 + for ck in c: + res -= ck*xfac + xfac /= x + res /= np.sqrt(2*np.pi*x) + res += 0.5 + return res + + def test_line(self): + x = np.logspace(np.log10(25), 300, 500) + a = x + dataset = np.vstack((a, x, self.gammainc_line(x))).T + FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-11).check() + + def test_roundtrip(self): + a = np.logspace(-5, 10, 100) + x = np.logspace(-5, 10, 100) + + y = sc.gammaincinv(a, sc.gammainc(a, x)) + assert_allclose(x, y, rtol=1e-10) + + +class TestGammaincc: + + @pytest.mark.parametrize('a, x', INVALID_POINTS) + def test_domain(self, a, x): + assert np.isnan(sc.gammaincc(a, x)) + + def test_a_eq_0_x_gt_0(self): + assert sc.gammaincc(0, 1) == 0 + + @pytest.mark.parametrize('a, x, desired', [ + (np.inf, 1, 1), + (np.inf, 0, 1), + (np.inf, np.inf, np.nan), + (1, np.inf, 0) + ]) + def test_infinite_arguments(self, a, x, desired): + result = sc.gammaincc(a, x) + if np.isnan(desired): + assert np.isnan(result) + else: + assert result == desired + + def test_infinite_limits(self): + # Test that large arguments converge to the hard-coded limits + # at infinity. + assert sc.gammaincc(1000, 100) == sc.gammaincc(np.inf, 100) + assert_allclose( + sc.gammaincc(100, 1000), + sc.gammaincc(100, np.inf), + atol=1e-200, # Use `atol` since the function converges to 0. + rtol=0 + ) + + def test_limit_check(self): + result = sc.gammaincc(1e-10,1) + limit = sc.gammaincc(0,1) + assert np.isclose(result, limit) + + def test_x_zero(self): + a = np.arange(1, 10) + assert_array_equal(sc.gammaincc(a, 0), 1) + + def test_roundtrip(self): + a = np.logspace(-5, 10, 100) + x = np.logspace(-5, 10, 100) + + y = sc.gammainccinv(a, sc.gammaincc(a, x)) + assert_allclose(x, y, rtol=1e-14) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py new file mode 100644 index 0000000000000000000000000000000000000000..2102152213997886d0127080a2767e8fcc9af63a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py @@ -0,0 +1,2566 @@ +"""Tests for hyp2f1 for complex values. + +Author: Albert Steppi, with credit to Adam Kullberg (FormerPhycisist) for +the implementation of mp_hyp2f1 below, which modifies mpmath's hyp2f1 to +return the same branch as scipy's on the standard branch cut. +""" + +import sys +import pytest +import numpy as np +from typing import NamedTuple +from numpy.testing import assert_allclose + +from scipy.special import hyp2f1 +from scipy.special._testutils import check_version, MissingModule + + +try: + import mpmath +except ImportError: + mpmath = MissingModule("mpmath") + + +def mp_hyp2f1(a, b, c, z): + """Return mpmath hyp2f1 calculated on same branch as scipy hyp2f1. + + For most values of a,b,c mpmath returns the x - 0j branch of hyp2f1 on the + branch cut x=(1,inf) whereas scipy's hyp2f1 calculates the x + 0j branch. + Thus, to generate the right comparison values on the branch cut, we + evaluate mpmath.hyp2f1 at x + 1e-15*j. + + The exception to this occurs when c-a=-m in which case both mpmath and + scipy calculate the x + 0j branch on the branch cut. When this happens + mpmath.hyp2f1 will be evaluated at the original z point. + """ + on_branch_cut = z.real > 1.0 and abs(z.imag) < 1.0e-15 + cond1 = abs(c - a - round(c - a)) < 1.0e-15 and round(c - a) <= 0 + cond2 = abs(c - b - round(c - b)) < 1.0e-15 and round(c - b) <= 0 + # Make sure imaginary part is *exactly* zero + if on_branch_cut: + z = z.real + 0.0j + if on_branch_cut and not (cond1 or cond2): + z_mpmath = z.real + 1.0e-15j + else: + z_mpmath = z + return complex(mpmath.hyp2f1(a, b, c, z_mpmath)) + + +class Hyp2f1TestCase(NamedTuple): + a: float + b: float + c: float + z: complex + expected: complex + rtol: float + + +class TestHyp2f1: + """Tests for hyp2f1 for complex values. + + Expected values for test cases were computed using mpmath. See + `scipy.special._precompute.hyp2f1_data`. The verbose style of specifying + test cases is used for readability and to make it easier to mark individual + cases as expected to fail. Expected failures are used to highlight cases + where improvements are needed. See + `scipy.special._precompute.hyp2f1_data.make_hyp2f1_test_cases` for a + function to generate the boilerplate for the test cases. + + Assertions have been added to each test to ensure that the test cases match + the situations that are intended. A final test `test_test_hyp2f1` checks + that the expected values in the test cases actually match what is computed + by mpmath. This test is marked slow even though it isn't particularly slow + so that it won't run by default on continuous integration builds. + """ + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=-10, + z=0.2 + 0.2j, + expected=np.inf + 0j, + rtol=0 + ) + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=-10, + z=0 + 0j, + expected=1 + 0j, + rtol=0 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0, + c=-10, + z=0.2 + 0.2j, + expected=1 + 0j, + rtol=0 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0, + c=0, + z=0.2 + 0.2j, + expected=1 + 0j, + rtol=0, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=0, + z=0.2 + 0.2j, + expected=np.inf + 0j, + rtol=0, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=0, + z=0 + 0j, + expected=np.nan + 0j, + rtol=0, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=-5, + c=-10, + z=0.2 + 0.2j, + expected=(1.0495404166666666+0.05708208333333334j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=-10, + c=-10, + z=0.2 + 0.2j, + expected=(1.092966013125+0.13455014673750001j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-10, + b=-20, + c=-10, + z=0.2 + 0.2j, + expected=(-0.07712512000000005+0.12752814080000005j), + rtol=1e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1, + b=3.2, + c=-1, + z=0.2 + 0.2j, + expected=(1.6400000000000001+0.6400000000000001j), + rtol=1e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-2, + b=1.2, + c=-4, + z=1 + 0j, + expected=1.8200000000000001 + 0j, + rtol=1e-15, + ), + ), + ] + ) + def test_c_non_positive_int(self, hyp2f1_test_case): + a, b, c, z, expected, rtol = hyp2f1_test_case + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=1.5, + z=1 + 0j, + expected=1.1496439092239847 + 0j, + rtol=1e-15 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=12.3, + b=8.0, + c=20.31, + z=1 + 0j, + expected=69280986.75273195 + 0j, + rtol=1e-15 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=290.2, + b=321.5, + c=700.1, + z=1 + 0j, + expected=1.3396562400934e117 + 0j, + rtol=1e-12, + ), + ), + # Note that here even mpmath produces different results for + # results that should be equivalent. + pytest.param( + Hyp2f1TestCase( + a=9.2, + b=621.5, + c=700.1, + z=(1+0j), + expected=(952726652.4158565+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=621.5, + b=9.2, + c=700.1, + z=(1+0j), + expected=(952726652.4160284+0j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-101.2, + b=-400.4, + c=-172.1, + z=(1+0j), + expected=(2.2253618341394838e+37+0j), + rtol=1e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-400.4, + b=-101.2, + c=-172.1, + z=(1+0j), + expected=(2.2253618341394838e+37+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=172.5, + b=-201.3, + c=151.2, + z=(1+0j), + expected=(7.072266653650905e-135+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-201.3, + b=172.5, + c=151.2, + z=(1+0j), + expected=(7.072266653650905e-135+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-102.1, + b=-20.3, + c=1.3, + z=1 + 0j, + expected=2.7899070752746906e22 + 0j, + rtol=3e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-202.6, + b=60.3, + c=1.5, + z=1 + 0j, + expected=-1.3113641413099326e-56 + 0j, + rtol=1e-12, + ), + ), + ], + ) + def test_unital_argument(self, hyp2f1_test_case): + """Tests for case z = 1, c - a - b > 0. + + Expected answers computed using mpmath. + """ + a, b, c, z, expected, rtol = hyp2f1_test_case + assert z == 1 and c - a - b > 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=1.3, + z=-1 + 0j, + expected=0.9428846409614143 + 0j, + rtol=1e-15), + ), + pytest.param( + Hyp2f1TestCase( + a=12.3, + b=8.0, + c=5.300000000000001, + z=-1 + 0j, + expected=-4.845809986595704e-06 + 0j, + rtol=1e-15 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=221.5, + b=90.2, + c=132.3, + z=-1 + 0j, + expected=2.0490488728377282e-42 + 0j, + rtol=1e-7, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-102.1, + b=-20.3, + c=-80.8, + z=-1 + 0j, + expected=45143784.46783885 + 0j, + rtol=1e-7, + ), + marks=pytest.mark.xfail( + condition=sys.maxsize < 2**32, + reason="Fails on 32 bit.", + ) + ), + ], + ) + def test_special_case_z_near_minus_1(self, hyp2f1_test_case): + """Tests for case z ~ -1, c ~ 1 + a - b + + Expected answers computed using mpmath. + """ + a, b, c, z, expected, rtol = hyp2f1_test_case + assert abs(1 + a - b - c) < 1e-15 and abs(z + 1) < 1e-15 + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=-4, + b=2.02764642551431, + c=1.0561196186065624, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.0031961077109535375-0.0011313924606557173j), + rtol=1e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-8, + b=-7.937789122896016, + c=-15.964218273004214, + z=(2-0.10526315789473695j), + expected=(0.005543763196412503-0.0025948879065698306j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-8, + b=8.095813935368371, + c=4.0013768449590685, + z=(0.9473684210526314-0.10526315789473695j), + expected=(-0.0003054674127221263-9.261359291755414e-05j), + rtol=1e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-4, + b=-3.956227226099288, + c=-3.9316537064827854, + z=(1.1578947368421053-0.3157894736842106j), + expected=(-0.0020809502580892937-0.0041877333232365095j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=-4, + c=2.050308316530781, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.0011282435590058734+0.0002027062303465851j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-8, + c=-15.964218273004214, + z=(1.3684210526315788+0.10526315789473673j), + expected=(-9.134907719238265e-05-0.00040219233987390723j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-4, + c=4.0013768449590685, + z=(0.9473684210526314-0.10526315789473695j), + expected=(-0.000519013062087489-0.0005855883076830948j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-10000, + b=2.2, + c=93459345.3, + z=(2+2j), + expected=(0.9995292071559088-0.00047047067522659253j), + rtol=1e-12, + ), + ), + ] + ) + def test_a_b_negative_int(self, hyp2f1_test_case): + a, b, c, z, expected, rtol = hyp2f1_test_case + assert a == int(a) and a < 0 or b == int(b) and b < 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-0.9629749245209605, + c=-15.5, + z=(1.1578947368421053-1.1578947368421053j), + expected=(0.9778506962676361+0.044083801141231616j), + rtol=3e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-3.9316537064827854, + c=1.5, + z=(0.9473684210526314-0.10526315789473695j), + expected=(4.0793167523167675-10.11694246310966j), + rtol=6e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-0.9629749245209605, + c=2.5, + z=(1.1578947368421053-0.10526315789473695j), + expected=(-2.9692999501916915+0.6394599899845594j), + rtol=1e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-0.9629749245209605, + c=-15.5, + z=(1.5789473684210522-1.1578947368421053j), + expected=(0.9493076367106102-0.04316852977183447j), + rtol=1e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.5, + c=-15.5, + z=(0.5263157894736841+0.10526315789473673j), + expected=(0.9844377175631795-0.003120587561483841j), + rtol=1e-10, + ), + ), + ], + ) + def test_a_b_neg_int_after_euler_hypergeometric_transformation( + self, hyp2f1_test_case + ): + a, b, c, z, expected, rtol = hyp2f1_test_case + assert ( # Tests the test + (abs(c - a - int(c - a)) < 1e-15 and c - a < 0) or + (abs(c - b - int(c - b)) < 1e-15 and c - b < 0) + ) + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.9629749245209605, + c=-15.963511401609862, + z=(0.10526315789473673-0.3157894736842106j), + expected=(0.9941449585778349+0.01756335047931358j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-0.9629749245209605, + c=-15.963511401609862, + z=(0.5263157894736841+0.5263157894736841j), + expected=(1.0388722293372104-0.09549450380041416j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=1.0561196186065624, + c=-7.93846038215665, + z=(0.10526315789473673+0.7368421052631575j), + expected=(2.1948378809826434+24.934157235172222j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=16.088264119063613, + c=8.031683612216888, + z=(0.3157894736842106-0.736842105263158j), + expected=(-0.4075277891264672-0.06819344579666956j), + rtol=2e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=2.050308316530781, + c=8.031683612216888, + z=(0.7368421052631575-0.10526315789473695j), + expected=(2.833535530740603-0.6925373701408158j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=2.050308316530781, + c=4.078873014294075, + z=(0.10526315789473673-0.3157894736842106j), + expected=(1.005347176329683-0.3580736009337313j), + rtol=5e-16, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.9629749245209605, + c=-15.963511401609862, + z=(0.3157894736842106-0.5263157894736843j), + expected=(0.9824353641135369+0.029271018868990268j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.9629749245209605, + c=-159.63511401609862, + z=(0.3157894736842106-0.5263157894736843j), + expected=(0.9982436200365834+0.002927268199671111j), + rtol=1e-7, + ), + marks=pytest.mark.xfail(reason="Poor convergence.") + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=16.088264119063613, + c=8.031683612216888, + z=(0.5263157894736841-0.5263157894736843j), + expected=(-0.6906825165778091+0.8176575137504892j), + rtol=5e-13, + ), + ), + ] + ) + def test_region1(self, hyp2f1_test_case): + """|z| < 0.9 and real(z) >= 0.""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert abs(z) < 0.9 and z.real >= 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=1.0561196186065624, + c=4.078873014294075, + z=(-0.3157894736842106+0.7368421052631575j), + expected=(0.7751915029081136+0.24068493258607315j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=16.088264119063613, + c=2.0397202577726152, + z=(-0.9473684210526316-0.3157894736842106j), + expected=(6.564549348474962e-07+1.6761570598334562e-06j), + rtol=5e-09, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=2.050308316530781, + c=16.056809865262608, + z=(-0.10526315789473695-0.10526315789473695j), + expected=(0.9862043298997204-0.013293151372712681j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=8.077282662161238, + c=16.056809865262608, + z=(-0.3157894736842106-0.736842105263158j), + expected=(0.16163826638754716-0.41378530376373734j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=2.050308316530781, + c=-0.906685989801748, + z=(-0.5263157894736843+0.3157894736842106j), + expected=(-6.256871535165936+0.13824973858225484j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=8.077282662161238, + c=-3.9924618758357022, + z=(-0.9473684210526316-0.3157894736842106j), + expected=(75.54672526086316+50.56157041797548j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=8.077282662161238, + c=-1.9631175993998025, + z=(-0.5263157894736843+0.5263157894736841j), + expected=(282.0602536306534-82.31597306936214j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-3.9316537064827854, + c=8.031683612216888, + z=(-0.5263157894736843-0.10526315789473695j), + expected=(5.179603735575851+1.4445374002099813j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-7.949900487447654, + c=1.0651378143226575, + z=(-0.3157894736842106-0.9473684210526316j), + expected=(2317.623517606141-269.51476321010324j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=-1.92872979730171, + c=2.0397202577726152, + z=(-0.736842105263158-0.3157894736842106j), + expected=(29.179154096175836+22.126690357535043j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-3.9316537064827854, + c=-15.963511401609862, + z=(-0.736842105263158-0.10526315789473695j), + expected=(0.20820247892032057-0.04763956711248794j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-15.964218273004214, + c=-1.9631175993998025, + z=(-0.3157894736842106-0.5263157894736843j), + expected=(-157471.63920142158+991294.0587828817j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-7.949900487447654, + c=-7.93846038215665, + z=(-0.10526315789473695-0.10526315789473695j), + expected=(0.30765349653210194-0.2979706363594157j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=1.0561196186065624, + c=8.031683612216888, + z=(-0.9473684210526316-0.10526315789473695j), + expected=(1.6787607400597109+0.10056620134616838j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=16.088264119063613, + c=4.078873014294075, + z=(-0.5263157894736843-0.736842105263158j), + expected=(7062.07842506049-12768.77955655703j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=16.088264119063613, + c=2.0397202577726152, + z=(-0.3157894736842106+0.7368421052631575j), + expected=(54749.216391029935-23078.144720887536j), + rtol=2e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=1.0561196186065624, + c=-0.906685989801748, + z=(-0.10526315789473695-0.10526315789473695j), + expected=(1.21521766411428-4.449385173946672j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=4.0013768449590685, + c=-1.9631175993998025, + z=(-0.736842105263158+0.5263157894736841j), + expected=(19234693144.196907+1617913967.7294445j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=1.0561196186065624, + c=-15.963511401609862, + z=(-0.5263157894736843+0.3157894736842106j), + expected=(0.9345201094534371+0.03745712558992195j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(-0.10526315789473695+0.10526315789473673j), + expected=(0.605732446296829+0.398171533680972j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=-15.964218273004214, + c=2.0397202577726152, + z=(-0.10526315789473695-0.5263157894736843j), + expected=(-9.753761888305416-4.590126012666959j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-1.92872979730171, + c=2.0397202577726152, + z=(-0.10526315789473695+0.3157894736842106j), + expected=(0.45587226291120714+1.0694545265819797j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-7.949900487447654, + c=-0.906685989801748, + z=(-0.736842105263158+0.3157894736842106j), + expected=(12.334808243233418-76.26089051819054j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-7.949900487447654, + c=-15.963511401609862, + z=(-0.5263157894736843+0.10526315789473673j), + expected=(1.2396019687632678-0.047507973161146286j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=-0.9629749245209605, + c=-0.906685989801748, + z=(-0.3157894736842106-0.5263157894736843j), + expected=(97.7889554372208-18.999754543400016j), + rtol=5e-13, + ), + ), + ] + ) + def test_region2(self, hyp2f1_test_case): + """|z| < 1 and real(z) < 0.""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert abs(z) < 1 and z.real < 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=-3.75, + c=-3.5, + z=(0.5263157894736841+0.7368421052631575j), + expected=(-1279.4894322256655-2302.914821389276j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=8.25, + c=-1.5, + z=(0.9473684210526314+0.3157894736842106j), + expected=(-8889.452798586273-11961.162305065242j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.25, + b=2.25, + c=-1.5, + z=(0.5263157894736841-0.736842105263158j), + expected=(-236.58971357952055-238.5228224781136j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.75, + b=-7.75, + c=-15.5, + z=(0.5263157894736841+0.7368421052631575j), + expected=(0.8116076584352279-0.29360565398246036j), + rtol=5e-16, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.25, + b=4.25, + c=-0.5, + z=(0.5263157894736841-0.736842105263158j), + expected=(-28.119407485189985+98.89858821348005j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.75, + b=2.25, + c=1.5, + z=(0.5263157894736841+0.7368421052631575j), + expected=(0.5311049067450484-0.9434347326448517j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=-15.75, + c=-7.5, + z=(0.9473684210526314+0.10526315789473673j), + expected=(1262084.378141873+1775569.6338380123j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=-7.75, + c=-15.5, + z=(0.5263157894736841-0.736842105263158j), + expected=(-0.009810480794804165+0.3648997569257999j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=2.25, + c=-3.5, + z=(0.5263157894736841-0.736842105263158j), + expected=(585660.8815535795-33646.68398590896j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-3.9316537064827854, + c=-15.963511401609862, + z=(0.9473684210526314-0.10526315789473695j), + expected=(181899621848365.2-173207123998705.7j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=8.25, + c=-0.5, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.04271686244952705-0.14087902824639406j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-1.92872979730171, + c=-0.906685989801748, + z=(0.9473684210526314-0.3157894736842106j), + expected=(-449.5119088817207+320.1423128036188j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=1.0561196186065624, + c=8.031683612216888, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.6361479738012501+0.028575620091205088j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.25, + b=16.25, + c=16.5, + z=(0.5263157894736841+0.7368421052631575j), + expected=(-0.9038811840552261-1.5356250756164884j), + rtol=1e-8, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=-1.75, + c=-1.5, + z=(0.9473684210526314+0.3157894736842106j), + expected=(653.0109150415394-4554.162605155542j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=-3.75, + c=4.5, + z=(0.9473684210526314-0.10526315789473695j), + expected=(118.7009859241035-34.18713648654642j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.25, + b=-15.75, + c=-3.5, + z=(0.5263157894736841+0.7368421052631575j), + expected=(-540204.4774526551+4970059.109251281j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=-15.75, + c=-0.5, + z=(0.5263157894736841-0.736842105263158j), + expected=(2253490.972258385+3318620.683390017j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=-7.75, + c=-7.5, + z=(0.9473684210526314+0.3157894736842106j), + expected=(-46159826.46716958-17880663.82218242j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-7.949900487447654, + c=-7.93846038215665, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.07116833581404514+0.11823358038036977j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=4.0013768449590685, + c=-7.93846038215665, + z=(0.7368421052631575+0.5263157894736841j), + expected=(4.7724909620664006e+17-6.039064078946702e+16j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.25, + b=-7.75, + c=1.5, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.0188022179759303+0.002921737281641378j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=1.0561196186065624, + c=-7.93846038215665, + z=(0.7368421052631575-0.5263157894736843j), + expected=(-9203.462928334846+12390.110518017136j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.75, + b=-15.75, + c=8.5, + z=(0.7368421052631575+0.5263157894736841j), + expected=(6.468457061368628+24.190040684917374j), + rtol=5e-16, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=16.088264119063613, + c=2.0397202577726152, + z=(0.7368421052631575+0.5263157894736841j), + expected=(2408.3451340186543-4275.257316636014j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.75, + b=-7.75, + c=8.5, + z=(0.7368421052631575-0.5263157894736843j), + expected=(4.1379984626381345-5.183654781039423j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=-7.75, + c=-0.5, + z=(0.5263157894736841+0.7368421052631575j), + expected=(-81177.775295738+56079.73286548954j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=2.050308316530781, + c=-0.906685989801748, + z=(0.9473684210526314+0.3157894736842106j), + expected=(1192868.5068926765+3624210.8182139914j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-1.92872979730171, + c=8.031683612216888, + z=(0.5263157894736841+0.7368421052631575j), + expected=(1.8286341846195202+1.9295255682312178j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=1.0561196186065624, + c=16.056809865262608, + z=(0.7368421052631575-0.5263157894736843j), + expected=(1.0514645669696452-0.0430834059440128j), + rtol=5e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=-15.964218273004214, + c=2.0397202577726152, + z=(0.5263157894736841+0.7368421052631575j), + expected=(541983.236432269+288200.2043029435j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.25, + b=8.25, + c=1.5, + z=(0.5263157894736841-0.736842105263158j), + expected=(-10.931988086039945+1.9136272843579096j), + rtol=1e-15, + ), + ), + ] + ) + def test_region3(self, hyp2f1_test_case): + """0.9 <= |z| <= 1 and |1 - z| < 0.9.""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=4.25, + c=2.5, + z=(0.4931034482758623-0.7965517241379311j), + expected=(38.41207903409937-30.510151276075792j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.0, + b=16.087593263474208, + c=16.088264119063613, + z=(0.5689655172413794-0.7965517241379311j), + expected=(-0.6667857912761286-1.0206224321443573j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.0, + b=1.0272592605282642, + c=-7.949900487447654, + z=(0.4931034482758623-0.7965517241379311j), + expected=(1679024.1647997478-2748129.775857212j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=16.0, + c=-7.949900487447654, + z=(0.4931034482758623-0.7965517241379311j), + expected=(424747226301.16986-1245539049327.2856j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=-15.964218273004214, + c=4.0, + z=(0.4931034482758623-0.7965517241379311j), + expected=(-0.0057826199201757595+0.026359861999025885j), + rtol=5e-06, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(0.5689655172413794-0.7965517241379311j), + expected=(0.4671901063492606+0.7769632229834897j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.0, + b=-3.956227226099288, + c=-7.949900487447654, + z=(0.4931034482758623+0.7965517241379312j), + expected=(0.9422283708145973+1.3476905754773343j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0, + b=-15.980848054962111, + c=-15.964218273004214, + z=(0.4931034482758623-0.7965517241379311j), + expected=(0.4168719497319604-0.9770953555235625j), + rtol=5e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=16.088264119063613, + c=2.5, + z=(0.5689655172413794+0.7965517241379312j), + expected=(1.279096377550619-2.173827694297929j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=4.0013768449590685, + c=2.0397202577726152, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-2.071520656161738-0.7846098268395909j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=8.0, + c=-0.9629749245209605, + z=(0.5689655172413794-0.7965517241379311j), + expected=(-7.740015495862889+3.386766435696699j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=16.088264119063613, + c=-7.93846038215665, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-6318.553685853241-7133.416085202879j), + rtol=5e-9, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=-3.9316537064827854, + c=16.056809865262608, + z=(0.5689655172413794+0.7965517241379312j), + expected=(-0.8854577905547399+8.135089099967278j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=-0.9629749245209605, + c=4.078873014294075, + z=(0.4931034482758623+0.7965517241379312j), + expected=(1.224291301521487+0.36014711766402485j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=-0.75, + c=-1.5, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-1.5765685855028473-3.9399766961046323j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=-1.92872979730171, + c=-7.93846038215665, + z=(0.5689655172413794-0.7965517241379311j), + expected=(56.794588688231194+4.556286783533971j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=4.5, + c=2.050308316530781, + z=(0.5689655172413794+0.7965517241379312j), + expected=(-4.251456563455306+6.737837111569671j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=8.5, + c=-1.92872979730171, + z=(0.4931034482758623-0.7965517241379311j), + expected=(2177143.9156599627-3313617.2748088865j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=-1.5, + c=4.0013768449590685, + z=(0.4931034482758623-0.7965517241379311j), + expected=(0.45563554481603946+0.6212000158060831j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-7.5, + c=-15.964218273004214, + z=(0.4931034482758623+0.7965517241379312j), + expected=(61.03201617828073-37.185626416756214j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=16.5, + c=4.0013768449590685, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-33143.425963520735+20790.608514722644j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=4.5, + c=-0.9629749245209605, + z=(0.5689655172413794+0.7965517241379312j), + expected=(30.778600270824423-26.65160354466787j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-3.5, + c=16.088264119063613, + z=(0.5689655172413794-0.7965517241379311j), + expected=(1.0629792615560487-0.08308454486044772j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=-7.5, + c=-0.9629749245209605, + z=(0.4931034482758623-0.7965517241379311j), + expected=(17431.571802591767+3553.7129767034507j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.25, + b=8.25, + c=16.5, + z=(0.11379310344827598+0.9482758620689657j), + expected=(0.4468600750211926+0.7313214934036885j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=16.25, + c=4.5, + z=(0.3413793103448277+0.8724137931034486j), + expected=(-3.905704438293991+3.693347860329299j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.25, + b=4.25, + c=-0.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-40.31777941834244-89.89852492432011j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=8.0, + c=-15.964218273004214, + z=(0.11379310344827598-0.9482758620689655j), + expected=(52584.347773055284-109197.86244309516j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-15.964218273004214, + c=16.056809865262608, + z=(0.03793103448275881+0.9482758620689657j), + expected=(-1.187733570412592-1.5147865053584582j), + rtol=5e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-3.9316537064827854, + c=1.0651378143226575, + z=(0.26551724137931054+0.9482758620689657j), + expected=(13.077494677898947+35.071599628224966j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-3.5, + c=-3.5, + z=(0.26551724137931054+0.8724137931034486j), + expected=(-0.5359656237994614-0.2344483936591811j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.25, + b=-3.75, + c=-1.5, + z=(0.26551724137931054+0.9482758620689657j), + expected=(1204.8114871663133+64.41022826840198j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=16.0, + c=4.0013768449590685, + z=(0.03793103448275881-0.9482758620689655j), + expected=(-9.85268872413994+7.011107558429154j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=16.0, + c=4.0013768449590685, + z=(0.3413793103448277-0.8724137931034484j), + expected=(528.5522951158454-1412.21630264791j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=1.0561196186065624, + c=-7.5, + z=(0.4172413793103451+0.8724137931034486j), + expected=(133306.45260685298+256510.7045225382j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=8.077282662161238, + c=-15.963511401609862, + z=(0.3413793103448277-0.8724137931034484j), + expected=(-0.998555715276967+2.774198742229889j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.75, + b=-0.75, + c=1.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(2.072445019723025-2.9793504811373515j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-1.92872979730171, + c=1.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-41.87581944176649-32.52980303527139j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.75, + b=-15.75, + c=-0.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-3729.6214864209774-30627.510509112635j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-15.964218273004214, + c=-0.906685989801748, + z=(0.03793103448275881+0.9482758620689657j), + expected=(-131615.07820609974+145596.13384245415j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=16.5, + c=16.088264119063613, + z=(0.26551724137931054+0.8724137931034486j), + expected=(0.18981844071070744+0.7855036242583742j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.5, + b=8.5, + c=-3.9316537064827854, + z=(0.11379310344827598-0.9482758620689655j), + expected=(110224529.2376068+128287212.04290268j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=-7.5, + c=4.0013768449590685, + z=(0.3413793103448277-0.8724137931034484j), + expected=(0.2722302180888523-0.21790187837266162j), + rtol=1e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-7.5, + c=-15.964218273004214, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-2.8252338010989035+2.430661949756161j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=16.5, + c=4.0013768449590685, + z=(0.03793103448275881+0.9482758620689657j), + expected=(-20.604894257647945+74.5109432558078j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=8.5, + c=-0.9629749245209605, + z=(0.3413793103448277+0.8724137931034486j), + expected=(-2764422.521269463-3965966.9965808876j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.5, + b=-0.5, + c=1.0561196186065624, + z=(0.26551724137931054+0.9482758620689657j), + expected=(1.2262338560994905+0.6545051266925549j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-15.5, + c=-7.949900487447654, + z=(0.4172413793103451-0.8724137931034484j), + expected=(-2258.1590330318213+8860.193389158803j), + rtol=1.4e-10, + ), + ), + ] + ) + def test_region4(self, hyp2f1_test_case): + """0.9 <= |z| <= 1 and |1 - z| >= 1. + + This region is unhandled by of the standard transformations and + needs special care. + """ + a, b, c, z, expected, rtol = hyp2f1_test_case + assert 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=16.088264119063613, + c=8.5, + z=(0.6448275862068968+0.8724137931034486j), + expected=(0.018601324701770394-0.07618420586062377j), + rtol=5e-08, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=4.25, + c=4.5, + z=(0.6448275862068968-0.8724137931034484j), + expected=(-1.391549471425551-0.118036604903893j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=2.050308316530781, + c=-1.9631175993998025, + z=(0.6448275862068968+0.8724137931034486j), + expected=(-2309.178768155151-1932.7247727595172j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=1.0, + c=-15.964218273004214, + z=(0.6448275862068968+0.8724137931034486j), + expected=(85592537010.05054-8061416766688.324j), + rtol=2e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-0.5, + c=1.5, + z=(0.6448275862068968+0.8724137931034486j), + expected=(1.2334498208515172-2.1639498536219732j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=-15.964218273004214, + c=4.0, + z=(0.6448275862068968+0.8724137931034486j), + expected=(102266.35398605966-44976.97828737755j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=4.0, + b=-3.956227226099288, + c=-15.964218273004214, + z=(0.6448275862068968-0.8724137931034484j), + expected=(-2.9590030930007236-4.190770764773225j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-15.5, + c=-7.5, + z=(0.5689655172413794-0.8724137931034484j), + expected=(-112554838.92074208+174941462.9202412j), + rtol=5e-05, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=2.050308316530781, + c=1.0, + z=(0.6448275862068968-0.8724137931034484j), + expected=(3.7519882374080145+7.360753798667486j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=2.050308316530781, + c=4.0, + z=(0.6448275862068968-0.8724137931034484j), + expected=(0.000181132943964693+0.07742903103815582j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=4.0013768449590685, + c=-1.9631175993998025, + z=(0.5689655172413794+0.8724137931034486j), + expected=(386338.760913596-386166.51762171905j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=8.0, + c=-1.92872979730171, + z=(0.6448275862068968+0.8724137931034486j), + expected=(1348667126.3444858-2375132427.158893j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=-0.9629749245209605, + c=4.5, + z=(0.5689655172413794+0.8724137931034486j), + expected=(1.428353429538678+0.6472718120804372j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(0.5689655172413794-0.8724137931034484j), + expected=(3.1439267526119643-3.145305240375117j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=-15.964218273004214, + c=-7.93846038215665, + z=(0.6448275862068968-0.8724137931034484j), + expected=(75.27467675681773+144.0946946292215j), + rtol=1e-07, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.75, + b=-7.75, + c=-7.5, + z=(0.5689655172413794+0.8724137931034486j), + expected=(-0.3699450626264222+0.8732812475910993j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=16.5, + c=1.0561196186065624, + z=(0.5689655172413794-0.8724137931034484j), + expected=(5.5361025821300665-2.4709693474656285j), + rtol=5e-09, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=8.5, + c=-3.9316537064827854, + z=(0.6448275862068968-0.8724137931034484j), + expected=(-782805.6699207705-537192.581278909j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=-15.5, + c=1.0561196186065624, + z=(0.6448275862068968+0.8724137931034486j), + expected=(12.345113400639693-14.993248992902007j), + rtol=0.0005, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=-0.5, + c=-15.964218273004214, + z=(0.6448275862068968+0.8724137931034486j), + expected=(23.698109392667842+97.15002033534108j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=16.5, + c=4.0013768449590685, + z=(0.6448275862068968-0.8724137931034484j), + expected=(1115.2978631811834+915.9212658718577j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=16.5, + c=-0.9629749245209605, + z=(0.6448275862068968+0.8724137931034486j), + expected=(642077722221.6489+535274495398.21027j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=-3.5, + c=4.0013768449590685, + z=(0.5689655172413794+0.8724137931034486j), + expected=(-5.689219222945697+16.877463062787143j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-1.5, + c=-0.9629749245209605, + z=(0.5689655172413794-0.8724137931034484j), + expected=(-44.32070290703576+1026.9127058617403j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=2.25, + c=4.5, + z=(0.11379310344827598-1.024137931034483j), + expected=(-0.021965227124574663+0.009908300237809064j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=1.5, + c=16.5, + z=(0.26551724137931054+1.024137931034483j), + expected=(1.0046072901244183+0.19945500134119992j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=1.0, + c=-3.9316537064827854, + z=(0.3413793103448277+0.9482758620689657j), + expected=(21022.30133421465+49175.98317370489j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=16.088264119063613, + c=-1.9631175993998025, + z=(0.4172413793103451-0.9482758620689655j), + expected=(-7024239.358547302+2481375.02681063j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=-15.75, + c=1.5, + z=(0.18965517241379315+1.024137931034483j), + expected=(92371704.94848-403546832.548352j), + rtol=5e-06, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-7.949900487447654, + c=8.5, + z=(0.26551724137931054-1.024137931034483j), + expected=(1.9335109845308265+5.986542524829654j), + rtol=5e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-1.92872979730171, + c=-7.93846038215665, + z=(0.4931034482758623+0.8724137931034486j), + expected=(-122.52639696039328-59.72428067512221j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=-1.75, + c=-1.5, + z=(0.4931034482758623+0.9482758620689657j), + expected=(-90.40642053579428+50.50649180047921j), + rtol=5e-08, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=8.077282662161238, + c=16.5, + z=(0.4931034482758623+0.9482758620689657j), + expected=(-0.2155745818150323-0.564628986876639j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=1.0561196186065624, + c=8.031683612216888, + z=(0.4172413793103451-0.9482758620689655j), + expected=(0.9503140488280465+0.11574960074292677j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.75, + b=2.25, + c=-15.5, + z=(0.4172413793103451+0.9482758620689657j), + expected=(0.9285862488442175+0.8203699266719692j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.75, + b=4.25, + c=-15.5, + z=(0.3413793103448277-0.9482758620689655j), + expected=(-1.0509834850116921-1.1145522325486075j), + rtol=1.1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(0.4931034482758623-0.9482758620689655j), + expected=(2.88119116536769-3.4249933450696806j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-15.964218273004214, + c=16.5, + z=(0.18965517241379315+1.024137931034483j), + expected=(199.65868451496038+347.79384207302877j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=-15.75, + c=-3.5, + z=(0.4931034482758623-0.8724137931034484j), + expected=(-208138312553.07013+58631611809.026955j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-15.5, + c=-7.5, + z=(0.3413793103448277+0.9482758620689657j), + expected=(-23032.90519856288-18256.94050457296j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=1.5, + c=1.0561196186065624, + z=(0.4931034482758623-0.8724137931034484j), + expected=(1.507342459587056+1.2332023580148403j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=4.5, + c=-3.9316537064827854, + z=(0.4172413793103451+0.9482758620689657j), + expected=(7044.766127108853-40210.365567285575j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=-1.5, + c=1.0561196186065624, + z=(0.03793103448275881+1.024137931034483j), + expected=(0.2725347741628333-2.247314875514784j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=-1.5, + c=-7.949900487447654, + z=(0.26551724137931054+1.024137931034483j), + expected=(-11.250200011017546+12.597393659160472j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=8.5, + c=16.088264119063613, + z=(0.26551724137931054+1.024137931034483j), + expected=(-0.18515160890991517+0.7959014164484782j), + rtol=2e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=16.5, + c=-3.9316537064827854, + z=(0.3413793103448277-1.024137931034483j), + expected=(998246378.8556538+1112032928.103645j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.5, + b=-3.5, + c=2.050308316530781, + z=(0.03793103448275881+1.024137931034483j), + expected=(0.5527670397711952+2.697662715303637j), + rtol=1.2e-15, # rtol bumped from 1e-15 in gh18414 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-1.5, + c=-0.9629749245209605, + z=(0.4931034482758623-0.8724137931034484j), + expected=(55.396931662136886+968.467463806326j), + rtol=5e-14, + ), + ), + ] + ) + def test_region5(self, hyp2f1_test_case): + """1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0 + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=4.0013768449590685, + c=4.078873014294075, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(-0.0018093573941378783+0.003481887377423739j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=2.050308316530781, + c=1.0651378143226575, + z=(-0.736842105263158-0.736842105263158j), + expected=(-0.00023401243818780545-1.7983496305603562e-05j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=8.077282662161238, + c=4.078873014294075, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(0.22359773002226846-0.24092487123993353j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=2.050308316530781, + c=-15.963511401609862, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(1.191573745740011+0.14347394589721466j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=4.0013768449590685, + c=-15.963511401609862, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(31.822620756901784-66.09094396747611j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=8.077282662161238, + c=-7.93846038215665, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(207.16750179245952+34.80478274924269j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-7.949900487447654, + c=8.031683612216888, + z=(-0.736842105263158+0.7368421052631575j), + expected=(-159.62429364277145+9.154224290644898j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-1.92872979730171, + c=16.056809865262608, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(1.121122351247184-0.07170260470126685j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=-0.9629749245209605, + c=16.056809865262608, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(1.9040596681316053-0.4951799449960107j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-1.92872979730171, + c=-0.906685989801748, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(-14.496623497780739-21.897524523299875j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-3.9316537064827854, + c=-3.9924618758357022, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(36.33473466026878+253.88728442029577j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-15.964218273004214, + c=-0.906685989801748, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(1505052.5653144997-50820766.81043443j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=4.0013768449590685, + c=1.0651378143226575, + z=(-0.5263157894736843+0.9473684210526314j), + expected=(-127.79407519260877-28.69899444941112j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=8.077282662161238, + c=16.056809865262608, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(2.0623331933754976+0.741234463565458j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=8.077282662161238, + c=2.0397202577726152, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(30.729193458862525-292.5700835046965j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=1.0561196186065624, + c=-1.9631175993998025, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(1.1285917906203495-0.735264575450189j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=1.0561196186065624, + c=-3.9924618758357022, + z=(-0.736842105263158+0.7368421052631575j), + expected=(0.6356474446678052-0.02429663008952248j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=16.088264119063613, + c=-7.93846038215665, + z=(-0.736842105263158+0.7368421052631575j), + expected=(0.4718880510273174+0.655083067736377j), + rtol=1e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-3.9316537064827854, + c=16.056809865262608, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(-0.14681550942352714+0.16092206364265146j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-15.964218273004214, + c=1.0651378143226575, + z=(-0.5263157894736843+0.9473684210526314j), + expected=(-6.436835190526225+22.883156700606182j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-7.949900487447654, + c=4.078873014294075, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(-0.7505682955068583-1.1026583264249945j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-3.9316537064827854, + c=-7.93846038215665, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(3.6247814989198166+2.596041360148318j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-15.964218273004214, + c=-1.9631175993998025, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(-59537.65287927933-669074.4342539902j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-15.964218273004214, + c=-1.9631175993998025, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(-433084.9970266166+431088.393918521j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1, + b=1, + c=4, + z=(3 + 4j), + expected=(0.49234384000963544+0.6051340616612397j), + rtol=5e-14, + ), + ), + ] + ) + def test_region6(self, hyp2f1_test_case): + """|z| > 1 but not in region 5.""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert ( + abs(z) > 1 and + not (1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0) + ) + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + # Broke when fixing gamma pole behavior in gh-21827 + pytest.param( + Hyp2f1TestCase( + a=1.3, + b=-0.2, + c=0.3, + z=-2.1, + expected=1.8202169687521206, + rtol=5e-15, + ), + ), + ] + ) + def test_miscellaneous(self, hyp2f1_test_case ): + a, b, c, z, expected, rtol = hyp2f1_test_case + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.slow + @check_version(mpmath, "1.0.0") + def test_test_hyp2f1(self): + """Test that expected values match what is computed by mpmath. + + This gathers the parameters for the test cases out of the pytest marks. + The parameters are a, b, c, z, expected, rtol, where expected should + be the value of hyp2f1(a, b, c, z) computed with mpmath. The test + recomputes hyp2f1(a, b, c, z) using mpmath and verifies that expected + actually is the correct value. This allows the data for the tests to + live within the test code instead of an external datafile, while + avoiding having to compute the results with mpmath during the test, + except for when slow tests are being run. + """ + test_methods = [ + test_method for test_method in dir(self) + if test_method.startswith('test') and + # Filter properties and attributes (futureproofing). + callable(getattr(self, test_method)) and + # Filter out this test + test_method != 'test_test_hyp2f1' + ] + for test_method in test_methods: + params = self._get_test_parameters(getattr(self, test_method)) + for a, b, c, z, expected, _ in params: + assert_allclose(mp_hyp2f1(a, b, c, z), expected, rtol=2.25e-16) + + def _get_test_parameters(self, test_method): + """Get pytest.mark parameters for a test in this class.""" + return [ + case.values[0] for mark in test_method.pytestmark + if mark.name == 'parametrize' + for case in mark.args[1] + ] + +class TestHyp2f1ExtremeInputs: + + @pytest.mark.parametrize("a", [1.0, 2.0, 3.0, -np.inf, np.inf]) + @pytest.mark.parametrize("b", [3.0, 4.0, 5.0, -np.inf, np.inf]) + @pytest.mark.parametrize("c", [3.0, 5.0, 6.0, 7.0]) + @pytest.mark.parametrize("z", [4.0 + 1.0j]) + def test_inf_a_b(self, a, b, c, z): + if np.any(np.isinf(np.asarray([a, b]))): + assert(np.isnan(hyp2f1(a, b, c, z))) + + def test_large_a_b(self): + assert(np.isnan(hyp2f1(10**7, 1.0, 3.0, 4.0 + 1.0j))) + assert(np.isnan(hyp2f1(-10**7, 1.0, 3.0, 4.0 + 1.0j))) + + assert(np.isnan(hyp2f1(1.0, 10**7, 3.0, 4.0 + 1.0j))) + assert(np.isnan(hyp2f1(1.0, -10**7, 3.0, 4.0 + 1.0j))) + + # Already correct in main but testing for surety + assert(np.isnan(hyp2f1(np.inf, 1.0, 3.0, 4.0))) + assert(np.isnan(hyp2f1(1.0, np.inf, 3.0, 4.0))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad092491905ae66c39cd881836054aef3dc6f6e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py @@ -0,0 +1,234 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import scipy.special as sc + + +class TestHyperu: + + def test_negative_x(self): + a, b, x = np.meshgrid( + [-1, -0.5, 0, 0.5, 1], + [-1, -0.5, 0, 0.5, 1], + np.linspace(-100, -1, 10), + ) + assert np.all(np.isnan(sc.hyperu(a, b, x))) + + def test_special_cases(self): + assert sc.hyperu(0, 1, 1) == 1.0 + + @pytest.mark.parametrize('a', [0.5, 1, np.nan]) + @pytest.mark.parametrize('b', [1, 2, np.nan]) + @pytest.mark.parametrize('x', [0.25, 3, np.nan]) + def test_nan_inputs(self, a, b, x): + assert np.isnan(sc.hyperu(a, b, x)) == np.any(np.isnan([a, b, x])) + + @pytest.mark.parametrize( + 'a,b,x,expected', + [(0.21581740448533887, 1.0, 1e-05, 3.6030558839391325), + (0.21581740448533887, 1.0, 0.00021544346900318823, 2.8783254988948976), + (0.21581740448533887, 1.0, 0.004641588833612777, 2.154928216691109), + (0.21581740448533887, 1.0, 0.1, 1.446546638718792), + (0.0030949064301273865, 1.0, 1e-05, 1.0356696454116199), + (0.0030949064301273865, 1.0, 0.00021544346900318823, 1.0261510362481985), + (0.0030949064301273865, 1.0, 0.004641588833612777, 1.0166326903402296), + (0.0030949064301273865, 1.0, 0.1, 1.0071174207698674), + (0.1509924314279033, 1.0, 1e-05, 2.806173846998948), + (0.1509924314279033, 1.0, 0.00021544346900318823, 2.3092158526816124), + (0.1509924314279033, 1.0, 0.004641588833612777, 1.812905980588048), + (0.1509924314279033, 1.0, 0.1, 1.3239738117634872), + (-0.010678995342969011, 1.0, 1e-05, 0.8775194903781114), + (-0.010678995342969011, 1.0, 0.00021544346900318823, 0.9101008998540128), + (-0.010678995342969011, 1.0, 0.004641588833612777, 0.9426854294058609), + (-0.010678995342969011, 1.0, 0.1, 0.9753065150174902), + (-0.06556622211831487, 1.0, 1e-05, 0.26435429752668904), + (-0.06556622211831487, 1.0, 0.00021544346900318823, 0.4574756033875781), + (-0.06556622211831487, 1.0, 0.004641588833612777, 0.6507121093358457), + (-0.06556622211831487, 1.0, 0.1, 0.8453129788602187), + (-0.21628242470175185, 1.0, 1e-05, -1.2318314201114489), + (-0.21628242470175185, 1.0, 0.00021544346900318823, -0.6704694233529538), + (-0.21628242470175185, 1.0, 0.004641588833612777, -0.10795098653682857), + (-0.21628242470175185, 1.0, 0.1, 0.4687227684115524)] + ) + def test_gh_15650_mp(self, a, b, x, expected): + # See https://github.com/scipy/scipy/issues/15650 + # b == 1, |a| < 0.25, 0 < x < 1 + # + # This purpose of this test is to check the accuracy of results + # in the region that was impacted by gh-15650. + # + # Reference values computed with mpmath using the script: + # + # import itertools as it + # import numpy as np + # + # from mpmath import mp + # + # rng = np.random.default_rng(1234) + # + # cases = [] + # for a, x in it.product( + # np.random.uniform(-0.25, 0.25, size=6), + # np.logspace(-5, -1, 4), + # ): + # with mp.workdps(100): + # cases.append((float(a), 1.0, float(x), float(mp.hyperu(a, 1.0, x)))) + assert_allclose(sc.hyperu(a, b, x), expected, rtol=1e-13) + + def test_gh_15650_sanity(self): + # The purpose of this test is to sanity check hyperu in the region that + # was impacted by gh-15650 by making sure there are no excessively large + # results, as were reported there. + a = np.linspace(-0.5, 0.5, 500) + x = np.linspace(1e-6, 1e-1, 500) + a, x = np.meshgrid(a, x) + results = sc.hyperu(a, 1.0, x) + assert np.all(np.abs(results) < 1e3) + + +class TestHyp1f1: + + @pytest.mark.parametrize('a, b, x', [ + (np.nan, 1, 1), + (1, np.nan, 1), + (1, 1, np.nan) + ]) + def test_nan_inputs(self, a, b, x): + assert np.isnan(sc.hyp1f1(a, b, x)) + + def test_poles(self): + assert_equal(sc.hyp1f1(1, [0, -1, -2, -3, -4], 0.5), np.inf) + + @pytest.mark.parametrize('a, b, x, result', [ + (-1, 1, 0.5, 0.5), + (1, 1, 0.5, 1.6487212707001281468), + (2, 1, 0.5, 2.4730819060501922203), + (1, 2, 0.5, 1.2974425414002562937), + (-10, 1, 0.5, -0.38937441413785204475) + ]) + def test_special_cases(self, a, b, x, result): + # Hit all the special case branches at the beginning of the + # function. Desired answers computed using Mpmath. + assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15) + + @pytest.mark.parametrize('a, b, x, result', [ + (1, 1, 0.44, 1.5527072185113360455), + (-1, 1, 0.44, 0.55999999999999999778), + (100, 100, 0.89, 2.4351296512898745592), + (-100, 100, 0.89, 0.40739062490768104667), + (1.5, 100, 59.99, 3.8073513625965598107), + (-1.5, 100, 59.99, 0.25099240047125826943) + ]) + def test_geometric_convergence(self, a, b, x, result): + # Test the region where we are relying on the ratio of + # + # (|a| + 1) * |x| / |b| + # + # being small. Desired answers computed using Mpmath + assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15) + + @pytest.mark.parametrize('a, b, x, result', [ + (-1, 1, 1.5, -0.5), + (-10, 1, 1.5, 0.41801777430943080357), + (-25, 1, 1.5, 0.25114491646037839809), + (-50, 1, 1.5, -0.25683643975194756115), + (-80, 1, 1.5, -0.24554329325751503601), + (-150, 1, 1.5, -0.173364795515420454496), + ]) + def test_a_negative_integer(self, a, b, x, result): + # Desired answers computed using Mpmath. + assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=2e-14) + + @pytest.mark.parametrize('a, b, x, expected', [ + (0.01, 150, -4, 0.99973683897677527773), # gh-3492 + (1, 5, 0.01, 1.0020033381011970966), # gh-3593 + (50, 100, 0.01, 1.0050126452421463411), # gh-3593 + (1, 0.3, -1e3, -7.011932249442947651455e-04), # gh-14149 + (1, 0.3, -1e4, -7.001190321418937164734e-05), # gh-14149 + (9, 8.5, -350, -5.224090831922378361082e-20), # gh-17120 + (9, 8.5, -355, -4.595407159813368193322e-20), # gh-17120 + (75, -123.5, 15, 3.425753920814889017493e+06), + ]) + def test_assorted_cases(self, a, b, x, expected): + # Expected values were computed with mpmath.hyp1f1(a, b, x). + assert_allclose(sc.hyp1f1(a, b, x), expected, atol=0, rtol=1e-14) + + def test_a_neg_int_and_b_equal_x(self): + # This is a case where the Boost wrapper will call hypergeometric_pFq + # instead of hypergeometric_1F1. When we use a version of Boost in + # which https://github.com/boostorg/math/issues/833 is fixed, this + # test case can probably be moved into test_assorted_cases. + # The expected value was computed with mpmath.hyp1f1(a, b, x). + a = -10.0 + b = 2.5 + x = 2.5 + expected = 0.0365323664364104338721 + computed = sc.hyp1f1(a, b, x) + assert_allclose(computed, expected, atol=0, rtol=1e-13) + + @pytest.mark.parametrize('a, b, x, desired', [ + (-1, -2, 2, 2), + (-1, -4, 10, 3.5), + (-2, -2, 1, 2.5) + ]) + def test_gh_11099(self, a, b, x, desired): + # All desired results computed using Mpmath + assert sc.hyp1f1(a, b, x) == desired + + @pytest.mark.parametrize('a', [-3, -2]) + def test_x_zero_a_and_b_neg_ints_and_a_ge_b(self, a): + assert sc.hyp1f1(a, -3, 0) == 1 + + # In the following tests with complex z, the reference values + # were computed with mpmath.hyp1f1(a, b, z), and verified with + # Wolfram Alpha Hypergeometric1F1(a, b, z), except for the + # case a=0.1, b=1, z=7-24j, where Wolfram Alpha reported + # "Standard computation time exceeded". That reference value + # was confirmed in an online Matlab session, with the commands + # + # > format long + # > hypergeom(0.1, 1, 7-24i) + # ans = + # -3.712349651834209 + 4.554636556672912i + # + @pytest.mark.parametrize( + 'a, b, z, ref', + [(-0.25, 0.5, 1+2j, 1.1814553180903435-1.2792130661292984j), + (0.25, 0.5, 1+2j, 0.24636797405707597+1.293434354945675j), + (25, 1.5, -2j, -516.1771262822523+407.04142751922024j), + (12, -1.5, -10+20j, -5098507.422706547-1341962.8043508842j), + pytest.param( + 10, 250, 10-15j, 1.1985998416598884-0.8613474402403436j, + marks=pytest.mark.xfail, + ), + pytest.param( + 0.1, 1, 7-24j, -3.712349651834209+4.554636556672913j, + marks=pytest.mark.xfail, + ) + ], + ) + def test_complex_z(self, a, b, z, ref): + h = sc.hyp1f1(a, b, z) + assert_allclose(h, ref, rtol=4e-15) + + # The "legacy edge cases" mentioned in the comments in the following + # tests refers to the behavior of hyp1f1(a, b, x) when b is a nonpositive + # integer. In some subcases, the behavior of SciPy does not match that + # of Boost (1.81+), mpmath and Mathematica (via Wolfram Alpha online). + # If the handling of these edges cases is changed to agree with those + # libraries, these test will have to be updated. + + @pytest.mark.parametrize('b', [0, -1, -5]) + def test_legacy_case1(self, b): + # Test results of hyp1f1(0, n, x) for n <= 0. + # This is a legacy edge case. + # Boost (versions greater than 1.80), Mathematica (via Wolfram Alpha + # online) and mpmath all return 1 in this case, but SciPy's hyp1f1 + # returns inf. + assert_equal(sc.hyp1f1(0, b, [-1.5, 0, 1.5]), [np.inf, np.inf, np.inf]) + + def test_legacy_case2(self): + # This is a legacy edge case. + # In software such as boost (1.81+), mpmath and Mathematica, + # the value is 1. + assert sc.hyp1f1(-4, -3, 0) == np.inf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py new file mode 100644 index 0000000000000000000000000000000000000000..dafc35982c4d4869ead2136e74466f1c44c64556 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py @@ -0,0 +1,249 @@ +# This file contains unit tests for iv_ratio() and related functions. + +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose +from scipy.special._ufuncs import ( # type: ignore[attr-defined] + _iv_ratio as iv_ratio, + _iv_ratio_c as iv_ratio_c, +) + + +class TestIvRatio: + + @pytest.mark.parametrize('v,x,r', [ + (0.5, 0.16666666666666666, 0.16514041292462933), + (0.5, 0.3333333333333333, 0.32151273753163434), + (0.5, 0.5, 0.46211715726000974), + (0.5, 0.6666666666666666, 0.5827829453479101), + (0.5, 0.8333333333333335, 0.6822617902381698), + (1, 0.3380952380952381, 0.1666773049170313), + (1, 0.7083333333333333, 0.33366443586989925), + (1, 1.1666666666666667, 0.5023355231537423), + (1, 1.8666666666666665, 0.674616572252164), + (1, 3.560606060606061, 0.844207659503163), + (2.34, 0.7975238095238094, 0.16704903081553285), + (2.34, 1.7133333333333334, 0.3360215931268845), + (2.34, 2.953333333333333, 0.50681909317803), + (2.34, 5.0826666666666656, 0.6755252698800679), + (2.34, 10.869696969696973, 0.8379351104498762), + (56.789, 19.46575238095238, 0.1667020505391409), + (56.789, 42.55008333333333, 0.33353809996933026), + (56.789, 75.552, 0.5003932381177826), + (56.789, 135.76026666666667, 0.6670528221946127), + (56.789, 307.8642424242425, 0.8334999441460798), + ]) + def test_against_reference_values(self, v, x, r): + """The reference values are computed using mpmath as follows. + + from mpmath import mp + mp.dps = 100 + + def iv_ratio_mp(v, x): + return mp.besseli(v, x) / mp.besseli(v - 1, x) + + def _sample(n, *, v): + '''Return n positive real numbers x such that iv_ratio(v, x) are + roughly evenly spaced over (0, 1). The formula is taken from [1]. + + [1] Banerjee A., Dhillon, I. S., Ghosh, J., Sra, S. (2005). + "Clustering on the Unit Hypersphere using von Mises-Fisher + Distributions." Journal of Machine Learning Research, + 6(46):1345-1382. + ''' + r = np.arange(1, n+1) / (n+1) + return r * (2*v-r*r) / (1-r*r) + + for v in (0.5, 1, 2.34, 56.789): + xs = _sample(5, v=v) + for x in xs: + print(f"({v}, {x}, {float(iv_ratio_mp(v,x))}),") + """ + assert_allclose(iv_ratio(v, x), r, rtol=4e-16, atol=0) + + @pytest.mark.parametrize('v,x,r', [ + (1, np.inf, 1), + (np.inf, 1, 0), + ]) + def test_inf(self, v, x, r): + """If exactly one of v or x is inf and the other is within domain, + should return 0 or 1 accordingly.""" + assert_equal(iv_ratio(v, x), r) + + @pytest.mark.parametrize('v', [0.49, -np.inf, np.nan, np.inf]) + @pytest.mark.parametrize('x', [-np.finfo(float).smallest_normal, + -np.finfo(float).smallest_subnormal, + -np.inf, np.nan, np.inf]) + def test_nan(self, v, x): + """If at least one argument is out of domain, or if v = x = inf, + the function should return nan.""" + assert_equal(iv_ratio(v, x), np.nan) + + @pytest.mark.parametrize('v', [0.5, 1, np.finfo(float).max, np.inf]) + def test_zero_x(self, v): + """If x is +/-0.0, return x to ensure iv_ratio is an odd function.""" + assert_equal(iv_ratio(v, 0.0), 0.0) + assert_equal(iv_ratio(v, -0.0), -0.0) + + @pytest.mark.parametrize('v,x', [ + (1, np.finfo(float).smallest_normal), + (1, np.finfo(float).smallest_subnormal), + (1, np.finfo(float).smallest_subnormal*2), + (1e20, 123), + (np.finfo(float).max, 1), + (np.finfo(float).max, np.sqrt(np.finfo(float).max)), + ]) + def test_tiny_x(self, v, x): + """If x is much less than v, the bounds + + x x + --------------------------- <= R <= ----------------------- + v-0.5+sqrt(x**2+(v+0.5)**2) v-1+sqrt(x**2+(v+1)**2) + + collapses to R ~= x/2v. Test against this asymptotic expression. + """ + assert_equal(iv_ratio(v, x), (0.5*x)/v) + + @pytest.mark.parametrize('v,x', [ + (1, 1e16), + (1e20, 1e40), + (np.sqrt(np.finfo(float).max), np.finfo(float).max), + ]) + def test_huge_x(self, v, x): + """If x is much greater than v, the bounds + + x x + --------------------------- <= R <= --------------------------- + v-0.5+sqrt(x**2+(v+0.5)**2) v-0.5+sqrt(x**2+(v-0.5)**2) + + collapses to R ~= 1. Test against this asymptotic expression. + """ + assert_equal(iv_ratio(v, x), 1.0) + + @pytest.mark.parametrize('v,x', [ + (np.finfo(float).max, np.finfo(float).max), + (np.finfo(float).max / 3, np.finfo(float).max), + (np.finfo(float).max, np.finfo(float).max / 3), + ]) + def test_huge_v_x(self, v, x): + """If both x and v are very large, the bounds + + x x + --------------------------- <= R <= ----------------------- + v-0.5+sqrt(x**2+(v+0.5)**2) v-1+sqrt(x**2+(v+1)**2) + + collapses to R ~= x/(v+sqrt(x**2+v**2). Test against this asymptotic + expression, and in particular that no numerical overflow occurs during + intermediate calculations. + """ + t = x / v + expected = t / (1 + np.hypot(1, t)) + assert_allclose(iv_ratio(v, x), expected, rtol=4e-16, atol=0) + + +class TestIvRatioC: + + @pytest.mark.parametrize('v,x,r', [ + (0.5, 0.16666666666666666, 0.8348595870753707), + (0.5, 0.3333333333333333, 0.6784872624683657), + (0.5, 0.5, 0.5378828427399902), + (0.5, 0.6666666666666666, 0.4172170546520899), + (0.5, 0.8333333333333335, 0.3177382097618302), + (1, 0.3380952380952381, 0.8333226950829686), + (1, 0.7083333333333333, 0.6663355641301008), + (1, 1.1666666666666667, 0.4976644768462577), + (1, 1.8666666666666665, 0.325383427747836), + (1, 3.560606060606061, 0.155792340496837), + (2.34, 0.7975238095238094, 0.8329509691844672), + (2.34, 1.7133333333333334, 0.6639784068731155), + (2.34, 2.953333333333333, 0.49318090682197), + (2.34, 5.0826666666666656, 0.3244747301199321), + (2.34, 10.869696969696973, 0.16206488955012377), + (56.789, 19.46575238095238, 0.8332979494608591), + (56.789, 42.55008333333333, 0.6664619000306697), + (56.789, 75.552, 0.4996067618822174), + (56.789, 135.76026666666667, 0.3329471778053873), + (56.789, 307.8642424242425, 0.16650005585392025), + ]) + def test_against_reference_values(self, v, x, r): + """The reference values are one minus those of TestIvRatio.""" + assert_allclose(iv_ratio_c(v, x), r, rtol=1e-15, atol=0) + + @pytest.mark.parametrize('v,x,r', [ + (1, np.inf, 0), + (np.inf, 1, 1), + ]) + def test_inf(self, v, x, r): + """If exactly one of v or x is inf and the other is within domain, + should return 0 or 1 accordingly.""" + assert_equal(iv_ratio_c(v, x), r) + + @pytest.mark.parametrize('v', [0.49, -np.inf, np.nan, np.inf]) + @pytest.mark.parametrize('x', [-np.finfo(float).smallest_normal, + -np.finfo(float).smallest_subnormal, + -np.inf, np.nan, np.inf]) + def test_nan(self, v, x): + """If at least one argument is out of domain, or if v = x = inf, + the function should return nan.""" + assert_equal(iv_ratio_c(v, x), np.nan) + + @pytest.mark.parametrize('v', [0.5, 1, np.finfo(float).max, np.inf]) + def test_zero_x(self, v): + """If x is +/-0.0, return 1.""" + assert_equal(iv_ratio_c(v, 0.0), 1.0) + assert_equal(iv_ratio_c(v, -0.0), 1.0) + + @pytest.mark.parametrize('v,x', [ + (1, np.finfo(float).smallest_normal), + (1, np.finfo(float).smallest_subnormal), + (1, np.finfo(float).smallest_subnormal*2), + (1e20, 123), + (np.finfo(float).max, 1), + (np.finfo(float).max, np.sqrt(np.finfo(float).max)), + ]) + def test_tiny_x(self, v, x): + """If x is much less than v, the bounds + + x x + --------------------------- <= R <= ----------------------- + v-0.5+sqrt(x**2+(v+0.5)**2) v-1+sqrt(x**2+(v+1)**2) + + collapses to 1-R ~= 1-x/2v. Test against this asymptotic expression. + """ + assert_equal(iv_ratio_c(v, x), 1.0-(0.5*x)/v) + + @pytest.mark.parametrize('v,x', [ + (1, 1e16), + (1e20, 1e40), + (np.sqrt(np.finfo(float).max), np.finfo(float).max), + ]) + def test_huge_x(self, v, x): + """If x is much greater than v, the bounds + + x x + --------------------------- <= R <= --------------------------- + v-0.5+sqrt(x**2+(v+0.5)**2) v-0.5+sqrt(x**2+(v-0.5)**2) + + collapses to 1-R ~= (v-0.5)/x. Test against this asymptotic expression. + """ + assert_allclose(iv_ratio_c(v, x), (v-0.5)/x, rtol=1e-15, atol=0) + + @pytest.mark.parametrize('v,x', [ + (np.finfo(float).max, np.finfo(float).max), + (np.finfo(float).max / 3, np.finfo(float).max), + (np.finfo(float).max, np.finfo(float).max / 3), + ]) + def test_huge_v_x(self, v, x): + """If both x and v are very large, the bounds + + x x + --------------------------- <= R <= ----------------------- + v-0.5+sqrt(x**2+(v+0.5)**2) v-1+sqrt(x**2+(v+1)**2) + + collapses to 1 - R ~= 1 - x/(v+sqrt(x**2+v**2). Test against this + asymptotic expression, and in particular that no numerical overflow + occurs during intermediate calculations. + """ + t = x / v + expected = 1 - t / (1 + np.hypot(1, t)) + assert_allclose(iv_ratio_c(v, x), expected, rtol=4e-16, atol=0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py new file mode 100644 index 0000000000000000000000000000000000000000..ade38115706808809890e1eba3b938562b0af6e6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py @@ -0,0 +1,491 @@ +import itertools + +import numpy as np +from numpy.testing import assert_ +from scipy.special._testutils import FuncData + +from scipy.special import kolmogorov, kolmogi, smirnov, smirnovi +from scipy.special._ufuncs import (_kolmogc, _kolmogci, _kolmogp, + _smirnovc, _smirnovci, _smirnovp) + +_rtol = 1e-10 + +class TestSmirnov: + def test_nan(self): + assert_(np.isnan(smirnov(1, np.nan))) + + def test_basic(self): + dataset = [(1, 0.1, 0.9), + (1, 0.875, 0.125), + (2, 0.875, 0.125 * 0.125), + (3, 0.875, 0.125 * 0.125 * 0.125)] + + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0(self): + dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_1(self): + dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0point5(self): + dataset = [(1, 0.5, 0.5), + (2, 0.5, 0.25), + (3, 0.5, 0.166666666667), + (4, 0.5, 0.09375), + (5, 0.5, 0.056), + (6, 0.5, 0.0327932098765), + (7, 0.5, 0.0191958707681), + (8, 0.5, 0.0112953186035), + (9, 0.5, 0.00661933257355), + (10, 0.5, 0.003888705)] + + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_1(self): + x = np.linspace(0, 1, 101, endpoint=True) + dataset = np.column_stack([[1]*len(x), x, 1-x]) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_2(self): + x = np.linspace(0.5, 1, 101, endpoint=True) + p = np.power(1-x, 2) + n = np.array([2] * len(x)) + dataset = np.column_stack([n, x, p]) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_3(self): + x = np.linspace(0.7, 1, 31, endpoint=True) + p = np.power(1-x, 3) + n = np.array([3] * len(x)) + dataset = np.column_stack([n, x, p]) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_large(self): + # test for large values of n + # Probabilities should go down as n goes up + x = 0.4 + pvals = np.array([smirnov(n, x) for n in range(400, 1100, 20)]) + dfs = np.diff(pvals) + assert_(np.all(dfs <= 0), msg=f'Not all diffs negative {dfs}') + + +class TestSmirnovi: + def test_nan(self): + assert_(np.isnan(smirnovi(1, np.nan))) + + def test_basic(self): + dataset = [(1, 0.4, 0.6), + (1, 0.6, 0.4), + (1, 0.99, 0.01), + (1, 0.01, 0.99), + (2, 0.125 * 0.125, 0.875), + (3, 0.125 * 0.125 * 0.125, 0.875), + (10, 1.0 / 16 ** 10, 1 - 1.0 / 16)] + + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0(self): + dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_1(self): + dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_1(self): + pp = np.linspace(0, 1, 101, endpoint=True) + # dataset = np.array([(1, p, 1-p) for p in pp]) + dataset = np.column_stack([[1]*len(pp), pp, 1-pp]) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_2(self): + x = np.linspace(0.5, 1, 101, endpoint=True) + p = np.power(1-x, 2) + n = np.array([2] * len(x)) + dataset = np.column_stack([n, p, x]) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_3(self): + x = np.linspace(0.7, 1, 31, endpoint=True) + p = np.power(1-x, 3) + n = np.array([3] * len(x)) + dataset = np.column_stack([n, p, x]) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_round_trip(self): + def _sm_smi(n, p): + return smirnov(n, smirnovi(n, p)) + + def _smc_smci(n, p): + return _smirnovc(n, _smirnovci(n, p)) + + dataset = [(1, 0.4, 0.4), + (1, 0.6, 0.6), + (2, 0.875, 0.875), + (3, 0.875, 0.875), + (3, 0.125, 0.125), + (10, 0.999, 0.999), + (10, 0.0001, 0.0001)] + + dataset = np.asarray(dataset) + FuncData( + _sm_smi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + FuncData( + _smc_smci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0point5(self): + dataset = [(1, 0.5, 0.5), + (2, 0.5, 0.366025403784), + (2, 0.25, 0.5), + (3, 0.5, 0.297156508177), + (4, 0.5, 0.255520481121), + (5, 0.5, 0.234559536069), + (6, 0.5, 0.21715965898), + (7, 0.5, 0.202722580034), + (8, 0.5, 0.190621765256), + (9, 0.5, 0.180363501362), + (10, 0.5, 0.17157867006)] + + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + +class TestSmirnovp: + def test_nan(self): + assert_(np.isnan(_smirnovp(1, np.nan))) + + def test_basic(self): + # Check derivative at endpoints + n1_10 = np.arange(1, 10) + dataset0 = np.column_stack([n1_10, + np.full_like(n1_10, 0), + np.full_like(n1_10, -1)]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + n2_10 = np.arange(2, 10) + dataset1 = np.column_stack([n2_10, + np.full_like(n2_10, 1.0), + np.full_like(n2_10, 0)]) + FuncData( + _smirnovp, dataset1, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_oneminusoneovern(self): + # Check derivative at x=1-1/n + n = np.arange(1, 20) + x = 1.0/n + xm1 = 1-1.0/n + pp1 = -n * x**(n-1) + pp1 -= (1-np.sign(n-2)**2) * 0.5 # n=2, x=0.5, 1-1/n = 0.5, need to adjust + dataset1 = np.column_stack([n, xm1, pp1]) + FuncData( + _smirnovp, dataset1, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_oneovertwon(self): + # Check derivative at x=1/2n (Discontinuous at x=1/n, so check at x=1/2n) + n = np.arange(1, 20) + x = 1.0/2/n + pp = -(n*x+1) * (1+x)**(n-2) + dataset0 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_oneovern(self): + # Check derivative at x=1/n + # (Discontinuous at x=1/n, hard to tell if x==1/n, only use n=power of 2) + n = 2**np.arange(1, 10) + x = 1.0/n + pp = -(n*x+1) * (1+x)**(n-2) + 0.5 + dataset0 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_oneovernclose(self): + # Check derivative at x=1/n + # (Discontinuous at x=1/n, test on either side: x=1/n +/- 2epsilon) + n = np.arange(3, 20) + + x = 1.0/n - 2*np.finfo(float).eps + pp = -(n*x+1) * (1+x)**(n-2) + dataset0 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + x = 1.0/n + 2*np.finfo(float).eps + pp = -(n*x+1) * (1+x)**(n-2) + 1 + dataset1 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset1, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + +class TestKolmogorov: + def test_nan(self): + assert_(np.isnan(kolmogorov(np.nan))) + + def test_basic(self): + dataset = [(0, 1.0), + (0.5, 0.96394524366487511), + (0.8275735551899077, 0.5000000000000000), + (1, 0.26999967167735456), + (2, 0.00067092525577969533)] + + dataset = np.asarray(dataset) + FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check() + + def test_linspace(self): + x = np.linspace(0, 2.0, 21) + dataset = [1.0000000000000000, 1.0000000000000000, 0.9999999999994950, + 0.9999906941986655, 0.9971923267772983, 0.9639452436648751, + 0.8642827790506042, 0.7112351950296890, 0.5441424115741981, + 0.3927307079406543, 0.2699996716773546, 0.1777181926064012, + 0.1122496666707249, 0.0680922218447664, 0.0396818795381144, + 0.0222179626165251, 0.0119520432391966, 0.0061774306344441, + 0.0030676213475797, 0.0014636048371873, 0.0006709252557797] + + dataset_c = [0.0000000000000000, 6.609305242245699e-53, 5.050407338670114e-13, + 9.305801334566668e-06, 0.0028076732227017, 0.0360547563351249, + 0.1357172209493958, 0.2887648049703110, 0.4558575884258019, + 0.6072692920593457, 0.7300003283226455, 0.8222818073935988, + 0.8877503333292751, 0.9319077781552336, 0.9603181204618857, + 0.9777820373834749, 0.9880479567608034, 0.9938225693655559, + 0.9969323786524203, 0.9985363951628127, 0.9993290747442203] + + dataset = np.column_stack([x, dataset]) + FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check() + dataset_c = np.column_stack([x, dataset_c]) + FuncData(_kolmogc, dataset_c, (0,), 1, rtol=_rtol).check() + + def test_linspacei(self): + p = np.linspace(0, 1.0, 21, endpoint=True) + dataset = [np.inf, 1.3580986393225507, 1.2238478702170823, + 1.1379465424937751, 1.0727491749396481, 1.0191847202536859, + 0.9730633753323726, 0.9320695842357622, 0.8947644549851197, + 0.8601710725555463, 0.8275735551899077, 0.7964065373291559, + 0.7661855555617682, 0.7364542888171910, 0.7067326523068980, + 0.6764476915028201, 0.6448126061663567, 0.6105590999244391, + 0.5711732651063401, 0.5196103791686224, 0.0000000000000000] + + dataset_c = [0.0000000000000000, 0.5196103791686225, 0.5711732651063401, + 0.6105590999244391, 0.6448126061663567, 0.6764476915028201, + 0.7067326523068980, 0.7364542888171910, 0.7661855555617682, + 0.7964065373291559, 0.8275735551899077, 0.8601710725555463, + 0.8947644549851196, 0.9320695842357622, 0.9730633753323727, + 1.0191847202536859, 1.0727491749396481, 1.1379465424937754, + 1.2238478702170825, 1.3580986393225509, np.inf] + + dataset = np.column_stack([p[1:], dataset[1:]]) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + dataset_c = np.column_stack([p[:-1], dataset_c[:-1]]) + FuncData(_kolmogci, dataset_c, (0,), 1, rtol=_rtol).check() + + def test_smallx(self): + epsilon = 0.1 ** np.arange(1, 14) + x = np.array([0.571173265106, 0.441027698518, 0.374219690278, 0.331392659217, + 0.300820537459, 0.277539353999, 0.259023494805, 0.243829561254, + 0.231063086389, 0.220135543236, 0.210641372041, 0.202290283658, + 0.19487060742]) + + dataset = np.column_stack([x, 1-epsilon]) + FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check() + + def test_round_trip(self): + def _ki_k(_x): + return kolmogi(kolmogorov(_x)) + + def _kci_kc(_x): + return _kolmogci(_kolmogc(_x)) + + x = np.linspace(0.0, 2.0, 21, endpoint=True) + # Exclude 0.1, 0.2. 0.2 almost makes succeeds, but 0.1 has no chance. + x02 = x[(x == 0) | (x > 0.21)] + dataset02 = np.column_stack([x02, x02]) + FuncData(_ki_k, dataset02, (0,), 1, rtol=_rtol).check() + + dataset = np.column_stack([x, x]) + FuncData(_kci_kc, dataset, (0,), 1, rtol=_rtol).check() + + +class TestKolmogi: + def test_nan(self): + assert_(np.isnan(kolmogi(np.nan))) + + def test_basic(self): + dataset = [(1.0, 0), + (0.96394524366487511, 0.5), + (0.9, 0.571173265106), + (0.5000000000000000, 0.8275735551899077), + (0.26999967167735456, 1), + (0.00067092525577969533, 2)] + + dataset = np.asarray(dataset) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + + def test_smallpcdf(self): + epsilon = 0.5 ** np.arange(1, 55, 3) + # kolmogi(1-p) == _kolmogci(p) if 1-(1-p) == p, but not necessarily otherwise + # Use epsilon s.t. 1-(1-epsilon)) == epsilon, + # so can use same x-array for both results + + x = np.array([0.8275735551899077, 0.5345255069097583, 0.4320114038786941, + 0.3736868442620478, 0.3345161714909591, 0.3057833329315859, + 0.2835052890528936, 0.2655578150208676, 0.2506869966107999, + 0.2380971058736669, 0.2272549289962079, 0.2177876361600040, + 0.2094254686862041, 0.2019676748836232, 0.1952612948137504, + 0.1891874239646641, 0.1836520225050326, 0.1785795904846466]) + + dataset = np.column_stack([1-epsilon, x]) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + + dataset = np.column_stack([epsilon, x]) + FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check() + + def test_smallpsf(self): + epsilon = 0.5 ** np.arange(1, 55, 3) + # kolmogi(p) == _kolmogci(1-p) if 1-(1-p) == p, but not necessarily otherwise + # Use epsilon s.t. 1-(1-epsilon)) == epsilon, + # so can use same x-array for both results + + x = np.array([0.8275735551899077, 1.3163786275161036, 1.6651092133663343, + 1.9525136345289607, 2.2027324540033235, 2.4272929437460848, + 2.6327688477341593, 2.8233300509220260, 3.0018183401530627, + 3.1702735084088891, 3.3302184446307912, 3.4828258153113318, + 3.6290214150152051, 3.7695513262825959, 3.9050272690877326, + 4.0359582187082550, 4.1627730557884890, 4.2858371743264527]) + + dataset = np.column_stack([epsilon, x]) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + + dataset = np.column_stack([1-epsilon, x]) + FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check() + + def test_round_trip(self): + def _k_ki(_p): + return kolmogorov(kolmogi(_p)) + + p = np.linspace(0.1, 1.0, 10, endpoint=True) + dataset = np.column_stack([p, p]) + FuncData(_k_ki, dataset, (0,), 1, rtol=_rtol).check() + + +class TestKolmogp: + def test_nan(self): + assert_(np.isnan(_kolmogp(np.nan))) + + def test_basic(self): + dataset = [(0.000000, -0.0), + (0.200000, -1.532420541338916e-10), + (0.400000, -0.1012254419260496), + (0.600000, -1.324123244249925), + (0.800000, -1.627024345636592), + (1.000000, -1.071948558356941), + (1.200000, -0.538512430720529), + (1.400000, -0.2222133182429472), + (1.600000, -0.07649302775520538), + (1.800000, -0.02208687346347873), + (2.000000, -0.005367402045629683)] + + dataset = np.asarray(dataset) + FuncData(_kolmogp, dataset, (0,), 1, rtol=_rtol).check() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py new file mode 100644 index 0000000000000000000000000000000000000000..c7fde685406661b821bb1dc490ca0da173eb4bd0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py @@ -0,0 +1,109 @@ +# +# Tests for the lambertw function, +# Adapted from the MPMath tests [1] by Yosef Meller, mellerf@netvision.net.il +# Distributed under the same license as SciPy itself. +# +# [1] mpmath source code, Subversion revision 992 +# http://code.google.com/p/mpmath/source/browse/trunk/mpmath/tests/test_functions2.py?spec=svn994&r=992 + +import pytest +import numpy as np +from numpy.testing import assert_, assert_equal, assert_array_almost_equal +from scipy.special import lambertw +from numpy import nan, inf, pi, e, isnan, log, r_, array, complex128 + +from scipy.special._testutils import FuncData + + +def test_values(): + assert_(isnan(lambertw(nan))) + assert_equal(lambertw(inf,1).real, inf) + assert_equal(lambertw(inf,1).imag, 2*pi) + assert_equal(lambertw(-inf,1).real, inf) + assert_equal(lambertw(-inf,1).imag, 3*pi) + + assert_equal(lambertw(1.), lambertw(1., 0)) + + data = [ + (0,0, 0), + (0+0j,0, 0), + (inf,0, inf), + (0,-1, -inf), + (0,1, -inf), + (0,3, -inf), + (e,0, 1), + (1,0, 0.567143290409783873), + (-pi/2,0, 1j*pi/2), + (-log(2)/2,0, -log(2)), + (0.25,0, 0.203888354702240164), + (-0.25,0, -0.357402956181388903), + (-1./10000,0, -0.000100010001500266719), + (-0.25,-1, -2.15329236411034965), + (0.25,-1, -3.00899800997004620-4.07652978899159763j), + (-0.25,-1, -2.15329236411034965), + (0.25,1, -3.00899800997004620+4.07652978899159763j), + (-0.25,1, -3.48973228422959210+7.41405453009603664j), + (-4,0, 0.67881197132094523+1.91195078174339937j), + (-4,1, -0.66743107129800988+7.76827456802783084j), + (-4,-1, 0.67881197132094523-1.91195078174339937j), + (1000,0, 5.24960285240159623), + (1000,1, 4.91492239981054535+5.44652615979447070j), + (1000,-1, 4.91492239981054535-5.44652615979447070j), + (1000,5, 3.5010625305312892+29.9614548941181328j), + (3+4j,0, 1.281561806123775878+0.533095222020971071j), + (-0.4+0.4j,0, -0.10396515323290657+0.61899273315171632j), + (3+4j,1, -0.11691092896595324+5.61888039871282334j), + (3+4j,-1, 0.25856740686699742-3.85211668616143559j), + (-0.5,-1, -0.794023632344689368-0.770111750510379110j), + (-1./10000,1, -11.82350837248724344+6.80546081842002101j), + (-1./10000,-1, -11.6671145325663544), + (-1./10000,-2, -11.82350837248724344-6.80546081842002101j), + (-1./100000,4, -14.9186890769540539+26.1856750178782046j), + (-1./100000,5, -15.0931437726379218666+32.5525721210262290086j), + ((2+1j)/10,0, 0.173704503762911669+0.071781336752835511j), + ((2+1j)/10,1, -3.21746028349820063+4.56175438896292539j), + ((2+1j)/10,-1, -3.03781405002993088-3.53946629633505737j), + ((2+1j)/10,4, -4.6878509692773249+23.8313630697683291j), + (-(2+1j)/10,0, -0.226933772515757933-0.164986470020154580j), + (-(2+1j)/10,1, -2.43569517046110001+0.76974067544756289j), + (-(2+1j)/10,-1, -3.54858738151989450-6.91627921869943589j), + (-(2+1j)/10,4, -4.5500846928118151+20.6672982215434637j), + (pi,0, 1.073658194796149172092178407024821347547745350410314531), + + # Former bug in generated branch, + (-0.5+0.002j,0, -0.78917138132659918344 + 0.76743539379990327749j), + (-0.5-0.002j,0, -0.78917138132659918344 - 0.76743539379990327749j), + (-0.448+0.4j,0, -0.11855133765652382241 + 0.66570534313583423116j), + (-0.448-0.4j,0, -0.11855133765652382241 - 0.66570534313583423116j), + ] + data = array(data, dtype=complex128) + + def w(x, y): + return lambertw(x, y.real.astype(int)) + with np.errstate(all='ignore'): + FuncData(w, data, (0,1), 2, rtol=1e-10, atol=1e-13).check() + + +def test_ufunc(): + assert_array_almost_equal( + lambertw(r_[0., e, 1.]), r_[0., 1., 0.567143290409783873]) + + +def test_lambertw_ufunc_loop_selection(): + # see https://github.com/scipy/scipy/issues/4895 + dt = np.dtype(np.complex128) + assert_equal(lambertw(0, 0, 0).dtype, dt) + assert_equal(lambertw([0], 0, 0).dtype, dt) + assert_equal(lambertw(0, [0], 0).dtype, dt) + assert_equal(lambertw(0, 0, [0]).dtype, dt) + assert_equal(lambertw([0], [0], [0]).dtype, dt) + + +@pytest.mark.parametrize('z', [1e-316, -2e-320j, -5e-318+1e-320j]) +def test_lambertw_subnormal_k0(z): + # Verify that subnormal inputs are handled correctly on + # the branch k=0 (regression test for gh-16291). + w = lambertw(z) + # For values this small, we can be sure that numerically, + # lambertw(z) is z. + assert w == z diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py new file mode 100644 index 0000000000000000000000000000000000000000..430a4175426e30bde02be7972b3144eed4923b27 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py @@ -0,0 +1,1518 @@ +import math + +import numpy as np + +import pytest +from numpy.testing import (assert_equal, assert_almost_equal, assert_array_almost_equal, + assert_allclose, suppress_warnings) + +from scipy import special +from scipy.special import (legendre_p, legendre_p_all, assoc_legendre_p, + assoc_legendre_p_all, sph_legendre_p, sph_legendre_p_all) + +# The functions lpn, lpmn, clpmn, appearing below are +# deprecated in favor of legendre_p_all, assoc_legendre_p_all, and +# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn) +# respectively. The deprecated functions listed above are implemented as +# shims around their respective replacements. The replacements are tested +# separately, but tests for the deprecated functions remain to verify the +# correctness of the shims. + +# Base polynomials come from Abrahmowitz and Stegan +class TestLegendre: + def test_legendre(self): + leg0 = special.legendre(0) + leg1 = special.legendre(1) + leg2 = special.legendre(2) + leg3 = special.legendre(3) + leg4 = special.legendre(4) + leg5 = special.legendre(5) + assert_equal(leg0.c, [1]) + assert_equal(leg1.c, [1,0]) + assert_almost_equal(leg2.c, np.array([3,0,-1])/2.0, decimal=13) + assert_almost_equal(leg3.c, np.array([5,0,-3,0])/2.0) + assert_almost_equal(leg4.c, np.array([35,0,-30,0,3])/8.0) + assert_almost_equal(leg5.c, np.array([63,0,-70,0,15,0])/8.0) + + @pytest.mark.parametrize('n', [1, 2, 3, 4, 5]) + @pytest.mark.parametrize('zr', [0.5241717, 12.80232, -9.699001, + 0.5122437, 0.1714377]) + @pytest.mark.parametrize('zi', [9.766818, 0.2999083, 8.24726, -22.84843, + -0.8792666]) + def test_lpn_against_clpmn(self, n, zr, zi): + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + reslpn = special.lpn(n, zr + zi*1j) + resclpmn = special.clpmn(0, n, zr+zi*1j) + + assert_allclose(reslpn[0], resclpmn[0][0]) + assert_allclose(reslpn[1], resclpmn[1][0]) + +class TestLegendreP: + @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)]) + def test_ode(self, shape): + rng = np.random.default_rng(1234) + + n = rng.integers(0, 100, shape) + x = rng.uniform(-1, 1, shape) + + p, p_jac, p_hess = legendre_p(n, x, diff_n=2) + + assert p.shape == shape + assert p_jac.shape == p.shape + assert p_hess.shape == p_jac.shape + + err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p + np.testing.assert_allclose(err, 0, atol=1e-10) + + @pytest.mark.parametrize("n_max", [1, 2, 4, 8, 16, 32]) + @pytest.mark.parametrize("x_shape", [(10,), (4, 9), (3, 5, 7)]) + def test_all_ode(self, n_max, x_shape): + rng = np.random.default_rng(1234) + + x = rng.uniform(-1, 1, x_shape) + p, p_jac, p_hess = legendre_p_all(n_max, x, diff_n=2) + + n = np.arange(n_max + 1) + n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 1))) + + assert p.shape == (len(n),) + x.shape + assert p_jac.shape == p.shape + assert p_hess.shape == p_jac.shape + + err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p + np.testing.assert_allclose(err, 0, atol=1e-10) + + def test_legacy(self): + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + p, pd = special.lpn(2, 0.5) + + assert_array_almost_equal(p, [1.00000, 0.50000, -0.12500], 4) + assert_array_almost_equal(pd, [0.00000, 1.00000, 1.50000], 4) + +class TestAssocLegendreP: + @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)]) + @pytest.mark.parametrize("m_max", [5, 4]) + @pytest.mark.parametrize("n_max", [7, 10]) + def test_lpmn(self, shape, n_max, m_max): + rng = np.random.default_rng(1234) + + x = rng.uniform(-0.99, 0.99, shape) + p_all, p_all_jac, p_all_hess = \ + assoc_legendre_p_all(n_max, m_max, x, diff_n=2) + + n = np.arange(n_max + 1) + n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2))) + + m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)]) + m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2))) + + x = np.expand_dims(x, axis = (0, 1)) + p, p_jac, p_hess = assoc_legendre_p(n, m, x, diff_n=2) + + np.testing.assert_allclose(p, p_all) + np.testing.assert_allclose(p_jac, p_all_jac) + np.testing.assert_allclose(p_hess, p_all_hess) + + @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)]) + @pytest.mark.parametrize("norm", [True, False]) + def test_ode(self, shape, norm): + rng = np.random.default_rng(1234) + + n = rng.integers(0, 10, shape) + m = rng.integers(-10, 10, shape) + x = rng.uniform(-1, 1, shape) + + p, p_jac, p_hess = assoc_legendre_p(n, m, x, norm=norm, diff_n=2) + + assert p.shape == shape + assert p_jac.shape == p.shape + assert p_hess.shape == p_jac.shape + + np.testing.assert_allclose((1 - x * x) * p_hess, + 2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p, + rtol=1e-05, atol=1e-08) + + @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)]) + def test_all(self, shape): + rng = np.random.default_rng(1234) + + n_max = 20 + m_max = 20 + + x = rng.uniform(-0.99, 0.99, shape) + + p, p_jac, p_hess = assoc_legendre_p_all(n_max, m_max, x, diff_n=2) + + m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)]) + n = np.arange(n_max + 1) + + n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2))) + m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2))) + np.testing.assert_allclose((1 - x * x) * p_hess, + 2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p, + rtol=1e-05, atol=1e-08) + + @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)]) + @pytest.mark.parametrize("norm", [True, False]) + def test_specific(self, shape, norm): + rng = np.random.default_rng(1234) + + x = rng.uniform(-0.99, 0.99, shape) + + p, p_jac = assoc_legendre_p_all(4, 4, x, norm=norm, diff_n=1) + + np.testing.assert_allclose(p[0, 0], + assoc_legendre_p_0_0(x, norm=norm)) + np.testing.assert_allclose(p[0, 1], 0) + np.testing.assert_allclose(p[0, 2], 0) + np.testing.assert_allclose(p[0, 3], 0) + np.testing.assert_allclose(p[0, 4], 0) + np.testing.assert_allclose(p[0, -3], 0) + np.testing.assert_allclose(p[0, -2], 0) + np.testing.assert_allclose(p[0, -1], 0) + + np.testing.assert_allclose(p[1, 0], + assoc_legendre_p_1_0(x, norm=norm)) + np.testing.assert_allclose(p[1, 1], + assoc_legendre_p_1_1(x, norm=norm)) + np.testing.assert_allclose(p[1, 2], 0) + np.testing.assert_allclose(p[1, 3], 0) + np.testing.assert_allclose(p[1, 4], 0) + np.testing.assert_allclose(p[1, -4], 0) + np.testing.assert_allclose(p[1, -3], 0) + np.testing.assert_allclose(p[1, -2], 0) + np.testing.assert_allclose(p[1, -1], + assoc_legendre_p_1_m1(x, norm=norm)) + + np.testing.assert_allclose(p[2, 0], + assoc_legendre_p_2_0(x, norm=norm)) + np.testing.assert_allclose(p[2, 1], + assoc_legendre_p_2_1(x, norm=norm)) + np.testing.assert_allclose(p[2, 2], + assoc_legendre_p_2_2(x, norm=norm)) + np.testing.assert_allclose(p[2, 3], 0) + np.testing.assert_allclose(p[2, 4], 0) + np.testing.assert_allclose(p[2, -4], 0) + np.testing.assert_allclose(p[2, -3], 0) + np.testing.assert_allclose(p[2, -2], + assoc_legendre_p_2_m2(x, norm=norm)) + np.testing.assert_allclose(p[2, -1], + assoc_legendre_p_2_m1(x, norm=norm)) + + np.testing.assert_allclose(p[3, 0], + assoc_legendre_p_3_0(x, norm=norm)) + np.testing.assert_allclose(p[3, 1], + assoc_legendre_p_3_1(x, norm=norm)) + np.testing.assert_allclose(p[3, 2], + assoc_legendre_p_3_2(x, norm=norm)) + np.testing.assert_allclose(p[3, 3], + assoc_legendre_p_3_3(x, norm=norm)) + np.testing.assert_allclose(p[3, 4], 0) + np.testing.assert_allclose(p[3, -4], 0) + np.testing.assert_allclose(p[3, -3], + assoc_legendre_p_3_m3(x, norm=norm)) + np.testing.assert_allclose(p[3, -2], + assoc_legendre_p_3_m2(x, norm=norm)) + np.testing.assert_allclose(p[3, -1], + assoc_legendre_p_3_m1(x, norm=norm)) + + np.testing.assert_allclose(p[4, 0], + assoc_legendre_p_4_0(x, norm=norm)) + np.testing.assert_allclose(p[4, 1], + assoc_legendre_p_4_1(x, norm=norm)) + np.testing.assert_allclose(p[4, 2], + assoc_legendre_p_4_2(x, norm=norm)) + np.testing.assert_allclose(p[4, 3], + assoc_legendre_p_4_3(x, norm=norm)) + np.testing.assert_allclose(p[4, 4], + assoc_legendre_p_4_4(x, norm=norm)) + np.testing.assert_allclose(p[4, -4], + assoc_legendre_p_4_m4(x, norm=norm)) + np.testing.assert_allclose(p[4, -3], + assoc_legendre_p_4_m3(x, norm=norm)) + np.testing.assert_allclose(p[4, -2], + assoc_legendre_p_4_m2(x, norm=norm)) + np.testing.assert_allclose(p[4, -1], + assoc_legendre_p_4_m1(x, norm=norm)) + + np.testing.assert_allclose(p_jac[0, 0], + assoc_legendre_p_0_0_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[0, 1], 0) + np.testing.assert_allclose(p_jac[0, 2], 0) + np.testing.assert_allclose(p_jac[0, 3], 0) + np.testing.assert_allclose(p_jac[0, 4], 0) + np.testing.assert_allclose(p_jac[0, -4], 0) + np.testing.assert_allclose(p_jac[0, -3], 0) + np.testing.assert_allclose(p_jac[0, -2], 0) + np.testing.assert_allclose(p_jac[0, -1], 0) + + np.testing.assert_allclose(p_jac[1, 0], + assoc_legendre_p_1_0_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[1, 1], + assoc_legendre_p_1_1_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[1, 2], 0) + np.testing.assert_allclose(p_jac[1, 3], 0) + np.testing.assert_allclose(p_jac[1, 4], 0) + np.testing.assert_allclose(p_jac[1, -4], 0) + np.testing.assert_allclose(p_jac[1, -3], 0) + np.testing.assert_allclose(p_jac[1, -2], 0) + np.testing.assert_allclose(p_jac[1, -1], + assoc_legendre_p_1_m1_jac(x, norm=norm)) + + np.testing.assert_allclose(p_jac[2, 0], + assoc_legendre_p_2_0_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[2, 1], + assoc_legendre_p_2_1_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[2, 2], + assoc_legendre_p_2_2_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[2, 3], 0) + np.testing.assert_allclose(p_jac[2, 4], 0) + np.testing.assert_allclose(p_jac[2, -4], 0) + np.testing.assert_allclose(p_jac[2, -3], 0) + np.testing.assert_allclose(p_jac[2, -2], + assoc_legendre_p_2_m2_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[2, -1], + assoc_legendre_p_2_m1_jac(x, norm=norm)) + + np.testing.assert_allclose(p_jac[3, 0], + assoc_legendre_p_3_0_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[3, 1], + assoc_legendre_p_3_1_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[3, 2], + assoc_legendre_p_3_2_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[3, 3], + assoc_legendre_p_3_3_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[3, 4], 0) + np.testing.assert_allclose(p_jac[3, -4], 0) + np.testing.assert_allclose(p_jac[3, -3], + assoc_legendre_p_3_m3_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[3, -2], + assoc_legendre_p_3_m2_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[3, -1], + assoc_legendre_p_3_m1_jac(x, norm=norm)) + + np.testing.assert_allclose(p_jac[4, 0], + assoc_legendre_p_4_0_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, 1], + assoc_legendre_p_4_1_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, 2], + assoc_legendre_p_4_2_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, 3], + assoc_legendre_p_4_3_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, 4], + assoc_legendre_p_4_4_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, -4], + assoc_legendre_p_4_m4_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, -3], + assoc_legendre_p_4_m3_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, -2], + assoc_legendre_p_4_m2_jac(x, norm=norm)) + np.testing.assert_allclose(p_jac[4, -1], + assoc_legendre_p_4_m1_jac(x, norm=norm)) + + @pytest.mark.parametrize("m_max", [7]) + @pytest.mark.parametrize("n_max", [10]) + @pytest.mark.parametrize("x", [1, -1]) + def test_all_limits(self, m_max, n_max, x): + p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1) + + n = np.arange(n_max + 1) + + np.testing.assert_allclose(p_jac[:, 0], + pow(x, n + 1) * n * (n + 1) / 2) + np.testing.assert_allclose(p_jac[:, 1], + np.where(n >= 1, pow(x, n) * np.inf, 0)) + np.testing.assert_allclose(p_jac[:, 2], + np.where(n >= 2, -pow(x, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0)) + np.testing.assert_allclose(p_jac[:, -2], + np.where(n >= 2, -pow(x, n + 1) / 4, 0)) + np.testing.assert_allclose(p_jac[:, -1], + np.where(n >= 1, -pow(x, n) * np.inf, 0)) + + for m in range(3, m_max + 1): + np.testing.assert_allclose(p_jac[:, m], 0) + np.testing.assert_allclose(p_jac[:, -m], 0) + + @pytest.mark.parametrize("m_max", [3, 5, 10]) + @pytest.mark.parametrize("n_max", [10]) + def test_legacy(self, m_max, n_max): + x = 0.5 + p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1) + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + + p_legacy, p_jac_legacy = special.lpmn(m_max, n_max, x) + for m in range(m_max + 1): + np.testing.assert_allclose(p_legacy[m], p[:, m]) + + p_legacy, p_jac_legacy = special.lpmn(-m_max, n_max, x) + for m in range(m_max + 1): + np.testing.assert_allclose(p_legacy[m], p[:, -m]) + +class TestMultiAssocLegendreP: + @pytest.mark.parametrize("shape", [(1000,), (4, 9), (3, 5, 7)]) + @pytest.mark.parametrize("branch_cut", [2, 3]) + @pytest.mark.parametrize("z_min, z_max", [(-10 - 10j, 10 + 10j), + (-1, 1), (-10j, 10j)]) + @pytest.mark.parametrize("norm", [True, False]) + def test_specific(self, shape, branch_cut, z_min, z_max, norm): + rng = np.random.default_rng(1234) + + z = rng.uniform(z_min.real, z_max.real, shape) + \ + 1j * rng.uniform(z_min.imag, z_max.imag, shape) + + p, p_jac = assoc_legendre_p_all(4, 4, + z, branch_cut=branch_cut, norm=norm, diff_n=1) + + np.testing.assert_allclose(p[0, 0], + assoc_legendre_p_0_0(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[0, 1], 0) + np.testing.assert_allclose(p[0, 2], 0) + np.testing.assert_allclose(p[0, 3], 0) + np.testing.assert_allclose(p[0, 4], 0) + np.testing.assert_allclose(p[0, -4], 0) + np.testing.assert_allclose(p[0, -3], 0) + np.testing.assert_allclose(p[0, -2], 0) + np.testing.assert_allclose(p[0, -1], 0) + + np.testing.assert_allclose(p[1, 0], + assoc_legendre_p_1_0(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[1, 1], + assoc_legendre_p_1_1(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[1, 2], 0) + np.testing.assert_allclose(p[1, 3], 0) + np.testing.assert_allclose(p[1, 4], 0) + np.testing.assert_allclose(p[1, -4], 0) + np.testing.assert_allclose(p[1, -3], 0) + np.testing.assert_allclose(p[1, -2], 0) + np.testing.assert_allclose(p[1, -1], + assoc_legendre_p_1_m1(z, branch_cut=branch_cut, norm=norm)) + + np.testing.assert_allclose(p[2, 0], + assoc_legendre_p_2_0(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[2, 1], + assoc_legendre_p_2_1(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[2, 2], + assoc_legendre_p_2_2(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[2, 3], 0) + np.testing.assert_allclose(p[2, 4], 0) + np.testing.assert_allclose(p[2, -4], 0) + np.testing.assert_allclose(p[2, -3], 0) + np.testing.assert_allclose(p[2, -2], + assoc_legendre_p_2_m2(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[2, -1], + assoc_legendre_p_2_m1(z, branch_cut=branch_cut, norm=norm)) + + np.testing.assert_allclose(p[3, 0], + assoc_legendre_p_3_0(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[3, 1], + assoc_legendre_p_3_1(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[3, 2], + assoc_legendre_p_3_2(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[3, 3], + assoc_legendre_p_3_3(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[3, 4], 0) + np.testing.assert_allclose(p[3, -4], 0) + np.testing.assert_allclose(p[3, -3], + assoc_legendre_p_3_m3(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[3, -2], + assoc_legendre_p_3_m2(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[3, -1], + assoc_legendre_p_3_m1(z, branch_cut=branch_cut, norm=norm)) + + np.testing.assert_allclose(p[4, 0], + assoc_legendre_p_4_0(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, 1], + assoc_legendre_p_4_1(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, 2], + assoc_legendre_p_4_2(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, 3], + assoc_legendre_p_4_3(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, 4], + assoc_legendre_p_4_4(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, -4], + assoc_legendre_p_4_m4(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, -3], + assoc_legendre_p_4_m3(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, -2], + assoc_legendre_p_4_m2(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p[4, -1], + assoc_legendre_p_4_m1(z, branch_cut=branch_cut, norm=norm)) + + np.testing.assert_allclose(p_jac[0, 0], + assoc_legendre_p_0_0_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[0, 1], 0) + np.testing.assert_allclose(p_jac[0, 2], 0) + np.testing.assert_allclose(p_jac[0, 3], 0) + np.testing.assert_allclose(p_jac[0, 4], 0) + np.testing.assert_allclose(p_jac[0, -4], 0) + np.testing.assert_allclose(p_jac[0, -3], 0) + np.testing.assert_allclose(p_jac[0, -2], 0) + np.testing.assert_allclose(p_jac[0, -1], 0) + + np.testing.assert_allclose(p_jac[1, 0], + assoc_legendre_p_1_0_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[1, 1], + assoc_legendre_p_1_1_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[1, 2], 0) + np.testing.assert_allclose(p_jac[1, 3], 0) + np.testing.assert_allclose(p_jac[1, 4], 0) + np.testing.assert_allclose(p_jac[1, -4], 0) + np.testing.assert_allclose(p_jac[1, -3], 0) + np.testing.assert_allclose(p_jac[1, -2], 0) + np.testing.assert_allclose(p_jac[1, -1], + assoc_legendre_p_1_m1_jac(z, branch_cut=branch_cut, norm=norm)) + + np.testing.assert_allclose(p_jac[2, 0], + assoc_legendre_p_2_0_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[2, 1], + assoc_legendre_p_2_1_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[2, 2], + assoc_legendre_p_2_2_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[2, 3], 0) + np.testing.assert_allclose(p_jac[2, 4], 0) + np.testing.assert_allclose(p_jac[2, -4], 0) + np.testing.assert_allclose(p_jac[2, -3], 0) + np.testing.assert_allclose(p_jac[2, -2], + assoc_legendre_p_2_m2_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[2, -1], + assoc_legendre_p_2_m1_jac(z, branch_cut=branch_cut, norm=norm)) + + np.testing.assert_allclose(p_jac[3, 0], + assoc_legendre_p_3_0_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[3, 1], + assoc_legendre_p_3_1_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[3, 2], + assoc_legendre_p_3_2_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[3, 3], + assoc_legendre_p_3_3_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[3, 4], 0) + np.testing.assert_allclose(p_jac[3, -4], 0) + np.testing.assert_allclose(p_jac[3, -3], + assoc_legendre_p_3_m3_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[3, -2], + assoc_legendre_p_3_m2_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[3, -1], + assoc_legendre_p_3_m1_jac(z, branch_cut=branch_cut, norm=norm)) + + np.testing.assert_allclose(p_jac[4, 0], + assoc_legendre_p_4_0_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, 1], + assoc_legendre_p_4_1_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, 2], + assoc_legendre_p_4_2_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, 3], + assoc_legendre_p_4_3_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, 4], + assoc_legendre_p_4_4_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, -4], + assoc_legendre_p_4_m4_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, -3], + assoc_legendre_p_4_m3_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, -2], + assoc_legendre_p_4_m2_jac(z, branch_cut=branch_cut, norm=norm)) + np.testing.assert_allclose(p_jac[4, -1], + assoc_legendre_p_4_m1_jac(z, branch_cut=branch_cut, norm=norm)) + +class TestSphLegendreP: + @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)]) + def test_specific(self, shape): + rng = np.random.default_rng(1234) + + theta = rng.uniform(-np.pi, np.pi, shape) + + p, p_jac = sph_legendre_p_all(4, 4, theta, diff_n=1) + + np.testing.assert_allclose(p[0, 0], + sph_legendre_p_0_0(theta)) + np.testing.assert_allclose(p[0, 1], 0) + np.testing.assert_allclose(p[0, 2], 0) + np.testing.assert_allclose(p[0, 3], 0) + np.testing.assert_allclose(p[0, 4], 0) + np.testing.assert_allclose(p[0, -3], 0) + np.testing.assert_allclose(p[0, -2], 0) + np.testing.assert_allclose(p[0, -1], 0) + + np.testing.assert_allclose(p[1, 0], + sph_legendre_p_1_0(theta)) + np.testing.assert_allclose(p[1, 1], + sph_legendre_p_1_1(theta)) + np.testing.assert_allclose(p[1, 2], 0) + np.testing.assert_allclose(p[1, 3], 0) + np.testing.assert_allclose(p[1, 4], 0) + np.testing.assert_allclose(p[1, -4], 0) + np.testing.assert_allclose(p[1, -3], 0) + np.testing.assert_allclose(p[1, -2], 0) + np.testing.assert_allclose(p[1, -1], + sph_legendre_p_1_m1(theta)) + + np.testing.assert_allclose(p[2, 0], + sph_legendre_p_2_0(theta)) + np.testing.assert_allclose(p[2, 1], + sph_legendre_p_2_1(theta)) + np.testing.assert_allclose(p[2, 2], + sph_legendre_p_2_2(theta)) + np.testing.assert_allclose(p[2, 3], 0) + np.testing.assert_allclose(p[2, 4], 0) + np.testing.assert_allclose(p[2, -4], 0) + np.testing.assert_allclose(p[2, -3], 0) + np.testing.assert_allclose(p[2, -2], + sph_legendre_p_2_m2(theta)) + np.testing.assert_allclose(p[2, -1], + sph_legendre_p_2_m1(theta)) + + np.testing.assert_allclose(p[3, 0], + sph_legendre_p_3_0(theta)) + np.testing.assert_allclose(p[3, 1], + sph_legendre_p_3_1(theta)) + np.testing.assert_allclose(p[3, 2], + sph_legendre_p_3_2(theta)) + np.testing.assert_allclose(p[3, 3], + sph_legendre_p_3_3(theta)) + np.testing.assert_allclose(p[3, 4], 0) + np.testing.assert_allclose(p[3, -4], 0) + np.testing.assert_allclose(p[3, -3], + sph_legendre_p_3_m3(theta)) + np.testing.assert_allclose(p[3, -2], + sph_legendre_p_3_m2(theta)) + np.testing.assert_allclose(p[3, -1], + sph_legendre_p_3_m1(theta)) + + np.testing.assert_allclose(p[4, 0], + sph_legendre_p_4_0(theta)) + np.testing.assert_allclose(p[4, 1], + sph_legendre_p_4_1(theta)) + np.testing.assert_allclose(p[4, 2], + sph_legendre_p_4_2(theta)) + np.testing.assert_allclose(p[4, 3], + sph_legendre_p_4_3(theta)) + np.testing.assert_allclose(p[4, 4], + sph_legendre_p_4_4(theta)) + np.testing.assert_allclose(p[4, -4], + sph_legendre_p_4_m4(theta)) + np.testing.assert_allclose(p[4, -3], + sph_legendre_p_4_m3(theta)) + np.testing.assert_allclose(p[4, -2], + sph_legendre_p_4_m2(theta)) + np.testing.assert_allclose(p[4, -1], + sph_legendre_p_4_m1(theta)) + + np.testing.assert_allclose(p_jac[0, 0], + sph_legendre_p_0_0_jac(theta)) + np.testing.assert_allclose(p_jac[0, 1], 0) + np.testing.assert_allclose(p_jac[0, 2], 0) + np.testing.assert_allclose(p_jac[0, 3], 0) + np.testing.assert_allclose(p_jac[0, 4], 0) + np.testing.assert_allclose(p_jac[0, -3], 0) + np.testing.assert_allclose(p_jac[0, -2], 0) + np.testing.assert_allclose(p_jac[0, -1], 0) + + np.testing.assert_allclose(p_jac[1, 0], + sph_legendre_p_1_0_jac(theta)) + np.testing.assert_allclose(p_jac[1, 1], + sph_legendre_p_1_1_jac(theta)) + np.testing.assert_allclose(p_jac[1, 2], 0) + np.testing.assert_allclose(p_jac[1, 3], 0) + np.testing.assert_allclose(p_jac[1, 4], 0) + np.testing.assert_allclose(p_jac[1, -4], 0) + np.testing.assert_allclose(p_jac[1, -3], 0) + np.testing.assert_allclose(p_jac[1, -2], 0) + np.testing.assert_allclose(p_jac[1, -1], + sph_legendre_p_1_m1_jac(theta)) + + np.testing.assert_allclose(p_jac[2, 0], + sph_legendre_p_2_0_jac(theta)) + np.testing.assert_allclose(p_jac[2, 1], + sph_legendre_p_2_1_jac(theta)) + np.testing.assert_allclose(p_jac[2, 2], + sph_legendre_p_2_2_jac(theta)) + np.testing.assert_allclose(p_jac[2, 3], 0) + np.testing.assert_allclose(p_jac[2, 4], 0) + np.testing.assert_allclose(p_jac[2, -4], 0) + np.testing.assert_allclose(p_jac[2, -3], 0) + np.testing.assert_allclose(p_jac[2, -2], + sph_legendre_p_2_m2_jac(theta)) + np.testing.assert_allclose(p_jac[2, -1], + sph_legendre_p_2_m1_jac(theta)) + + np.testing.assert_allclose(p_jac[3, 0], + sph_legendre_p_3_0_jac(theta)) + np.testing.assert_allclose(p_jac[3, 1], + sph_legendre_p_3_1_jac(theta)) + np.testing.assert_allclose(p_jac[3, 2], + sph_legendre_p_3_2_jac(theta)) + np.testing.assert_allclose(p_jac[3, 3], + sph_legendre_p_3_3_jac(theta)) + np.testing.assert_allclose(p_jac[3, 4], 0) + np.testing.assert_allclose(p_jac[3, -4], 0) + np.testing.assert_allclose(p_jac[3, -3], + sph_legendre_p_3_m3_jac(theta)) + np.testing.assert_allclose(p_jac[3, -2], + sph_legendre_p_3_m2_jac(theta)) + np.testing.assert_allclose(p_jac[3, -1], + sph_legendre_p_3_m1_jac(theta)) + + np.testing.assert_allclose(p_jac[4, 0], + sph_legendre_p_4_0_jac(theta)) + np.testing.assert_allclose(p_jac[4, 1], + sph_legendre_p_4_1_jac(theta)) + np.testing.assert_allclose(p_jac[4, 2], + sph_legendre_p_4_2_jac(theta)) + np.testing.assert_allclose(p_jac[4, 3], + sph_legendre_p_4_3_jac(theta)) + np.testing.assert_allclose(p_jac[4, 4], + sph_legendre_p_4_4_jac(theta)) + np.testing.assert_allclose(p_jac[4, -4], + sph_legendre_p_4_m4_jac(theta)) + np.testing.assert_allclose(p_jac[4, -3], + sph_legendre_p_4_m3_jac(theta)) + np.testing.assert_allclose(p_jac[4, -2], + sph_legendre_p_4_m2_jac(theta)) + np.testing.assert_allclose(p_jac[4, -1], + sph_legendre_p_4_m1_jac(theta)) + + @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)]) + def test_ode(self, shape): + rng = np.random.default_rng(1234) + + n = rng.integers(0, 10, shape) + m = rng.integers(-10, 10, shape) + theta = rng.uniform(-np.pi, np.pi, shape) + + p, p_jac, p_hess = sph_legendre_p(n, m, theta, diff_n=2) + + assert p.shape == shape + assert p_jac.shape == p.shape + assert p_hess.shape == p_jac.shape + + np.testing.assert_allclose(np.sin(theta) * p_hess, -np.cos(theta) * p_jac + - (n * (n + 1) * np.sin(theta) - m * m / np.sin(theta)) * p, + rtol=1e-05, atol=1e-08) + +class TestLegendreFunctions: + def test_clpmn(self): + z = 0.5+0.3j + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + clp = special.clpmn(2, 2, z, 3) + + assert_array_almost_equal(clp, + (np.array([[1.0000, z, 0.5*(3*z*z-1)], + [0.0000, np.sqrt(z*z-1), 3*z*np.sqrt(z*z-1)], + [0.0000, 0.0000, 3*(z*z-1)]]), + np.array([[0.0000, 1.0000, 3*z], + [0.0000, z/np.sqrt(z*z-1), 3*(2*z*z-1)/np.sqrt(z*z-1)], + [0.0000, 0.0000, 6*z]])), + 7) + + def test_clpmn_close_to_real_2(self): + eps = 1e-10 + m = 1 + n = 3 + x = 0.5 + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] + clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] + + assert_array_almost_equal(np.array([clp_plus, clp_minus]), + np.array([special.lpmv(m, n, x), + special.lpmv(m, n, x)]), + 7) + + def test_clpmn_close_to_real_3(self): + eps = 1e-10 + m = 1 + n = 3 + x = 0.5 + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] + clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] + + assert_array_almost_equal(np.array([clp_plus, clp_minus]), + np.array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), + special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), + 7) + + def test_clpmn_across_unit_circle(self): + eps = 1e-7 + m = 1 + n = 1 + x = 1j + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + for type in [2, 3]: + assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], + special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) + + def test_inf(self): + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + for z in (1, -1): + for n in range(4): + for m in range(1, n): + lp = special.clpmn(m, n, z) + assert np.isinf(lp[1][1,1:]).all() + lp = special.lpmn(m, n, z) + assert np.isinf(lp[1][1,1:]).all() + + def test_deriv_clpmn(self): + # data inside and outside of the unit circle + zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, + 1+1j, -1+1j, -1-1j, 1-1j] + m = 2 + n = 3 + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + for type in [2, 3]: + for z in zvals: + for h in [1e-3, 1e-3j]: + approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] + - special.clpmn(m, n, z-0.5*h, type)[0])/h + assert_allclose(special.clpmn(m, n, z, type)[1], + approx_derivative, + rtol=1e-4) + + """ + @pytest.mark.parametrize("m_max", [3]) + @pytest.mark.parametrize("n_max", [5]) + @pytest.mark.parametrize("z", [-1]) + def test_clpmn_all_limits(self, m_max, n_max, z): + rng = np.random.default_rng(1234) + + type = 2 + + p, p_jac = special.clpmn_all(m_max, n_max, type, z, diff_n=1) + + n = np.arange(n_max + 1) + + np.testing.assert_allclose(p_jac[0], pow(z, n + 1) * n * (n + 1) / 2) + np.testing.assert_allclose(p_jac[1], np.where(n >= 1, pow(z, n) * np.inf, 0)) + np.testing.assert_allclose(p_jac[2], np.where(n >= 2, + -pow(z, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0)) + np.testing.assert_allclose(p_jac[-2], np.where(n >= 2, -pow(z, n + 1) / 4, 0)) + np.testing.assert_allclose(p_jac[-1], np.where(n >= 1, -pow(z, n) * np.inf, 0)) + + for m in range(3, m_max + 1): + np.testing.assert_allclose(p_jac[m], 0) + np.testing.assert_allclose(p_jac[-m], 0) + """ + + def test_lpmv(self): + lp = special.lpmv(0,2,.5) + assert_almost_equal(lp,-0.125,7) + lp = special.lpmv(0,40,.001) + assert_almost_equal(lp,0.1252678976534484,7) + + # XXX: this is outside the domain of the current implementation, + # so ensure it returns a NaN rather than a wrong answer. + with np.errstate(all='ignore'): + lp = special.lpmv(-1,-1,.001) + assert lp != 0 or np.isnan(lp) + + def test_lqmn(self): + lqmnf = special.lqmn(0,2,.5) + lqf = special.lqn(2,.5) + assert_array_almost_equal(lqmnf[0][0],lqf[0],4) + assert_array_almost_equal(lqmnf[1][0],lqf[1],4) + + def test_lqmn_gt1(self): + """algorithm for real arguments changes at 1.0001 + test against analytical result for m=2, n=1 + """ + x0 = 1.0001 + delta = 0.00002 + for x in (x0-delta, x0+delta): + lq = special.lqmn(2, 1, x)[0][-1, -1] + expected = 2/(x*x-1) + assert_almost_equal(lq, expected) + + def test_lqmn_shape(self): + a, b = special.lqmn(4, 4, 1.1) + assert_equal(a.shape, (5, 5)) + assert_equal(b.shape, (5, 5)) + + a, b = special.lqmn(4, 0, 1.1) + assert_equal(a.shape, (5, 1)) + assert_equal(b.shape, (5, 1)) + + def test_lqn(self): + lqf = special.lqn(2,.5) + assert_array_almost_equal(lqf,(np.array([0.5493, -0.7253, -0.8187]), + np.array([1.3333, 1.216, -0.8427])),4) + + @pytest.mark.parametrize("function", [special.lpn, special.lqn]) + @pytest.mark.parametrize("n", [1, 2, 4, 8, 16, 32]) + @pytest.mark.parametrize("z_complex", [False, True]) + @pytest.mark.parametrize("z_inexact", [False, True]) + @pytest.mark.parametrize( + "input_shape", + [ + (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1), (2, 2, 2) + ] + ) + def test_array_inputs_lxn(self, function, n, z_complex, z_inexact, input_shape): + """Tests for correct output shapes.""" + rng = np.random.default_rng(1234) + if z_inexact: + z = rng.integers(-3, 3, size=input_shape) + else: + z = rng.uniform(-1, 1, size=input_shape) + + if z_complex: + z = 1j * z + 0.5j * z + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + P_z, P_d_z = function(n, z) + assert P_z.shape == (n + 1, ) + input_shape + assert P_d_z.shape == (n + 1, ) + input_shape + + @pytest.mark.parametrize("function", [special.lqmn]) + @pytest.mark.parametrize( + "m,n", + [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)] + ) + @pytest.mark.parametrize("z_inexact", [False, True]) + @pytest.mark.parametrize( + "input_shape", [ + (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1) + ] + ) + def test_array_inputs_lxmn(self, function, m, n, z_inexact, input_shape): + """Tests for correct output shapes and dtypes.""" + rng = np.random.default_rng(1234) + if z_inexact: + z = rng.integers(-3, 3, size=input_shape) + else: + z = rng.uniform(-1, 1, size=input_shape) + + P_z, P_d_z = function(m, n, z) + assert P_z.shape == (m + 1, n + 1) + input_shape + assert P_d_z.shape == (m + 1, n + 1) + input_shape + + @pytest.mark.parametrize("function", [special.clpmn, special.lqmn]) + @pytest.mark.parametrize( + "m,n", + [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)] + ) + @pytest.mark.parametrize( + "input_shape", [ + (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1) + ] + ) + def test_array_inputs_clxmn(self, function, m, n, input_shape): + """Tests for correct output shapes and dtypes.""" + rng = np.random.default_rng(1234) + z = rng.uniform(-1, 1, size=input_shape) + z = 1j * z + 0.5j * z + + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + P_z, P_d_z = function(m, n, z) + + assert P_z.shape == (m + 1, n + 1) + input_shape + assert P_d_z.shape == (m + 1, n + 1) + input_shape + +def assoc_legendre_factor(n, m, norm): + if norm: + return (math.sqrt((2 * n + 1) * + math.factorial(n - m) / (2 * math.factorial(n + m)))) + + return 1 + +def assoc_legendre_p_0_0(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(0, 0, norm) + + return np.full_like(z, fac) + +def assoc_legendre_p_1_0(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(1, 0, norm) + + return fac * z + +def assoc_legendre_p_1_1(z, *, branch_cut=2, norm=False): + branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1) + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(1, 1, norm) + + w = np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z)) + + return branch_cut_sign * branch_sign * fac * w + +def assoc_legendre_p_1_m1(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(1, -1, norm) + + return (-branch_cut_sign * fac * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_2_0(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(2, 0, norm) + + return fac * (3 * z * z - 1) / 2 + +def assoc_legendre_p_2_1(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(2, 1, norm) + + return (3 * fac * z * + assoc_legendre_p_1_1(z, branch_cut=branch_cut)) + +def assoc_legendre_p_2_2(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(2, 2, norm) + + return 3 * branch_cut_sign * fac * (1 - z * z) + +def assoc_legendre_p_2_m2(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(2, -2, norm) + + return branch_cut_sign * fac * (1 - z * z) / 8 + +def assoc_legendre_p_2_m1(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(2, -1, norm) + + return (-branch_cut_sign * fac * z * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_3_0(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(3, 0, norm) + + return fac * (5 * z * z - 3) * z / 2 + +def assoc_legendre_p_3_1(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(3, 1, norm) + + return (3 * fac * (5 * z * z - 1) * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_3_2(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, 2, norm) + + return 15 * branch_cut_sign * fac * (1 - z * z) * z + +def assoc_legendre_p_3_3(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, 3, norm) + + return (15 * branch_cut_sign * fac * (1 - z * z) * + assoc_legendre_p_1_1(z, branch_cut=branch_cut)) + +def assoc_legendre_p_3_m3(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(3, -3, norm) + + return (fac * (z * z - 1) * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48) + +def assoc_legendre_p_3_m2(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, -2, norm) + + return branch_cut_sign * fac * (1 - z * z) * z / 8 + +def assoc_legendre_p_3_m1(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, -1, norm) + + return (branch_cut_sign * fac * (1 - 5 * z * z) * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8) + +def assoc_legendre_p_4_0(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, 0, norm) + + return fac * ((35 * z * z - 30) * z * z + 3) / 8 + +def assoc_legendre_p_4_1(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, 1, norm) + + return (5 * fac * (7 * z * z - 3) * z * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_4_2(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, 2, norm) + + return 15 * branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 2 + +def assoc_legendre_p_4_3(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, 3, norm) + + return (105 * branch_cut_sign * fac * (1 - z * z) * z * + assoc_legendre_p_1_1(z, branch_cut=branch_cut)) + +def assoc_legendre_p_4_4(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, 4, norm) + + return 105 * fac * np.square(z * z - 1) + +def assoc_legendre_p_4_m4(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, -4, norm) + + return fac * np.square(z * z - 1) / 384 + +def assoc_legendre_p_4_m3(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, -3, norm) + + return (fac * (z * z - 1) * z * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48) + +def assoc_legendre_p_4_m2(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, -2, norm) + + return branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 48 + +def assoc_legendre_p_4_m1(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, -1, norm) + + return (branch_cut_sign * fac * (3 - 7 * z * z) * z * + assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8) + +def assoc_legendre_p_1_1_jac_div_z(z, branch_cut=2): + branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1) + + out11_div_z = (-branch_sign / + np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z))) + + return out11_div_z + +def assoc_legendre_p_0_0_jac(z, *, branch_cut=2, norm=False): + return np.zeros_like(z) + +def assoc_legendre_p_1_0_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(1, 0, norm) + + return np.full_like(z, fac) + +def assoc_legendre_p_1_1_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(1, 1, norm) + + return (fac * z * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut)) + +def assoc_legendre_p_1_m1_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(1, -1, norm) + + return (-branch_cut_sign * fac * z * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_2_0_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(2, 0, norm) + + return 3 * fac * z + +def assoc_legendre_p_2_1_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(2, 1, norm) + + return (3 * fac * (2 * z * z - 1) * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut)) + +def assoc_legendre_p_2_2_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(2, 2, norm) + + return -6 * branch_cut_sign * fac * z + +def assoc_legendre_p_2_m1_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(2, -1, norm) + + return (branch_cut_sign * fac * (1 - 2 * z * z) * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_2_m2_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(2, -2, norm) + + return -branch_cut_sign * fac * z / 4 + +def assoc_legendre_p_3_0_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(3, 0, norm) + + return 3 * fac * (5 * z * z - 1) / 2 + +def assoc_legendre_p_3_1_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(3, 1, norm) + + return (3 * fac * (15 * z * z - 11) * z * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_3_2_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, 2, norm) + + return 15 * branch_cut_sign * fac * (1 - 3 * z * z) + +def assoc_legendre_p_3_3_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, 3, norm) + + return (45 * branch_cut_sign * fac * (1 - z * z) * z * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut)) + +def assoc_legendre_p_3_m3_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(3, -3, norm) + + return (fac * (z * z - 1) * z * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 16) + +def assoc_legendre_p_3_m2_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, -2, norm) + + return branch_cut_sign * fac * (1 - 3 * z * z) / 8 + +def assoc_legendre_p_3_m1_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(3, -1, norm) + + return (branch_cut_sign * fac * (11 - 15 * z * z) * z * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8) + +def assoc_legendre_p_4_0_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, 0, norm) + + return 5 * fac * (7 * z * z - 3) * z / 2 + +def assoc_legendre_p_4_1_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, 1, norm) + + return (5 * fac * ((28 * z * z - 27) * z * z + 3) * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2) + +def assoc_legendre_p_4_2_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, 2, norm) + + return 30 * branch_cut_sign * fac * (4 - 7 * z * z) * z + +def assoc_legendre_p_4_3_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, 3, norm) + + return (105 * branch_cut_sign * fac * ((5 - 4 * z * z) * z * z - 1) * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut)) + +def assoc_legendre_p_4_4_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, 4, norm) + + return 420 * fac * (z * z - 1) * z + +def assoc_legendre_p_4_m4_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, -4, norm) + + return fac * (z * z - 1) * z / 96 + +def assoc_legendre_p_4_m3_jac(z, *, branch_cut=2, norm=False): + fac = assoc_legendre_factor(4, -3, norm) + + return (fac * ((4 * z * z - 5) * z * z + 1) * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 48) + +def assoc_legendre_p_4_m2_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, -2, norm) + + return branch_cut_sign * fac * (4 - 7 * z * z) * z / 12 + +def assoc_legendre_p_4_m1_jac(z, *, branch_cut=2, norm=False): + branch_cut_sign = np.where(branch_cut == 3, -1, 1) + fac = assoc_legendre_factor(4, -1, norm) + + return (branch_cut_sign * fac * ((27 - 28 * z * z) * z * z - 3) * + assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8) + +def sph_legendre_factor(n, m): + return assoc_legendre_factor(n, m, norm=True) / np.sqrt(2 * np.pi) + +def sph_legendre_p_0_0(theta): + fac = sph_legendre_factor(0, 0) + + return np.full_like(theta, fac) + +def sph_legendre_p_1_0(theta): + fac = sph_legendre_factor(1, 0) + + return fac * np.cos(theta) + +def sph_legendre_p_1_1(theta): + fac = sph_legendre_factor(1, 1) + + return -fac * np.abs(np.sin(theta)) + +def sph_legendre_p_1_m1(theta): + fac = sph_legendre_factor(1, -1) + + return fac * np.abs(np.sin(theta)) / 2 + +def sph_legendre_p_2_0(theta): + fac = sph_legendre_factor(2, 0) + + return fac * (3 * np.square(np.cos(theta)) - 1) / 2 + +def sph_legendre_p_2_1(theta): + fac = sph_legendre_factor(2, 1) + + return -3 * fac * np.abs(np.sin(theta)) * np.cos(theta) + +def sph_legendre_p_2_2(theta): + fac = sph_legendre_factor(2, 2) + + return 3 * fac * (1 - np.square(np.cos(theta))) + +def sph_legendre_p_2_m2(theta): + fac = sph_legendre_factor(2, -2) + + return fac * (1 - np.square(np.cos(theta))) / 8 + +def sph_legendre_p_2_m1(theta): + fac = sph_legendre_factor(2, -1) + + return fac * np.cos(theta) * np.abs(np.sin(theta)) / 2 + +def sph_legendre_p_3_0(theta): + fac = sph_legendre_factor(3, 0) + + return (fac * (5 * np.square(np.cos(theta)) - 3) * + np.cos(theta) / 2) + +def sph_legendre_p_3_1(theta): + fac = sph_legendre_factor(3, 1) + + return (-3 * fac * (5 * np.square(np.cos(theta)) - 1) * + np.abs(np.sin(theta)) / 2) + +def sph_legendre_p_3_2(theta): + fac = sph_legendre_factor(3, 2) + + return (-15 * fac * (np.square(np.cos(theta)) - 1) * + np.cos(theta)) + +def sph_legendre_p_3_3(theta): + fac = sph_legendre_factor(3, 3) + + return -15 * fac * np.power(np.abs(np.sin(theta)), 3) + +def sph_legendre_p_3_m3(theta): + fac = sph_legendre_factor(3, -3) + + return fac * np.power(np.abs(np.sin(theta)), 3) / 48 + +def sph_legendre_p_3_m2(theta): + fac = sph_legendre_factor(3, -2) + + return (-fac * (np.square(np.cos(theta)) - 1) * + np.cos(theta) / 8) + +def sph_legendre_p_3_m1(theta): + fac = sph_legendre_factor(3, -1) + + return (fac * (5 * np.square(np.cos(theta)) - 1) * + np.abs(np.sin(theta)) / 8) + +def sph_legendre_p_4_0(theta): + fac = sph_legendre_factor(4, 0) + + return (fac * (35 * np.square(np.square(np.cos(theta))) - + 30 * np.square(np.cos(theta)) + 3) / 8) + +def sph_legendre_p_4_1(theta): + fac = sph_legendre_factor(4, 1) + + return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) * + np.cos(theta) * np.abs(np.sin(theta)) / 2) + +def sph_legendre_p_4_2(theta): + fac = sph_legendre_factor(4, 2) + + return (-15 * fac * (7 * np.square(np.cos(theta)) - 1) * + (np.square(np.cos(theta)) - 1) / 2) + +def sph_legendre_p_4_3(theta): + fac = sph_legendre_factor(4, 3) + + return -105 * fac * np.power(np.abs(np.sin(theta)), 3) * np.cos(theta) + +def sph_legendre_p_4_4(theta): + fac = sph_legendre_factor(4, 4) + + return 105 * fac * np.square(np.square(np.cos(theta)) - 1) + +def sph_legendre_p_4_m4(theta): + fac = sph_legendre_factor(4, -4) + + return fac * np.square(np.square(np.cos(theta)) - 1) / 384 + +def sph_legendre_p_4_m3(theta): + fac = sph_legendre_factor(4, -3) + + return (fac * np.power(np.abs(np.sin(theta)), 3) * + np.cos(theta) / 48) + +def sph_legendre_p_4_m2(theta): + fac = sph_legendre_factor(4, -2) + + return (-fac * (7 * np.square(np.cos(theta)) - 1) * + (np.square(np.cos(theta)) - 1) / 48) + +def sph_legendre_p_4_m1(theta): + fac = sph_legendre_factor(4, -1) + + return (fac * (7 * np.square(np.cos(theta)) - 3) * + np.cos(theta) * np.abs(np.sin(theta)) / 8) + +def sph_legendre_p_0_0_jac(theta): + return np.zeros_like(theta) + +def sph_legendre_p_1_0_jac(theta): + fac = sph_legendre_factor(1, 0) + + return -fac * np.sin(theta) + +def sph_legendre_p_1_1_jac(theta): + fac = sph_legendre_factor(1, 1) + + return -fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1) + +def sph_legendre_p_1_m1_jac(theta): + fac = sph_legendre_factor(1, -1) + + return fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1) / 2 + +def sph_legendre_p_2_0_jac(theta): + fac = sph_legendre_factor(2, 0) + + return -3 * fac * np.cos(theta) * np.sin(theta) + +def sph_legendre_p_2_1_jac(theta): + fac = sph_legendre_factor(2, 1) + + return (3 * fac * (-np.square(np.cos(theta)) * + (2 * np.heaviside(np.sin(theta), 1) - 1) + + np.abs(np.sin(theta)) * np.sin(theta))) + +def sph_legendre_p_2_2_jac(theta): + fac = sph_legendre_factor(2, 2) + + return 6 * fac * np.sin(theta) * np.cos(theta) + +def sph_legendre_p_2_m2_jac(theta): + fac = sph_legendre_factor(2, -2) + + return fac * np.sin(theta) * np.cos(theta) / 4 + +def sph_legendre_p_2_m1_jac(theta): + fac = sph_legendre_factor(2, -1) + + return (-fac * (-np.square(np.cos(theta)) * + (2 * np.heaviside(np.sin(theta), 1) - 1) + + np.abs(np.sin(theta)) * np.sin(theta)) / 2) + +def sph_legendre_p_3_0_jac(theta): + fac = sph_legendre_factor(3, 0) + + return 3 * fac * (1 - 5 * np.square(np.cos(theta))) * np.sin(theta) / 2 + +def sph_legendre_p_3_1_jac(theta): + fac = sph_legendre_factor(3, 1) + + return (3 * fac * (11 - 15 * np.square(np.cos(theta))) * np.cos(theta) * + (2 * np.heaviside(np.sin(theta), 1) - 1) / 2) + +def sph_legendre_p_3_2_jac(theta): + fac = sph_legendre_factor(3, 2) + + return 15 * fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta) + +def sph_legendre_p_3_3_jac(theta): + fac = sph_legendre_factor(3, 3) + + return -45 * fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta) + +def sph_legendre_p_3_m3_jac(theta): + fac = sph_legendre_factor(3, -3) + + return fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta) / 16 + +def sph_legendre_p_3_m2_jac(theta): + fac = sph_legendre_factor(3, -2) + + return fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta) / 8 + +def sph_legendre_p_3_m1_jac(theta): + fac = sph_legendre_factor(3, -1) + + return (-fac * (11 - 15 * np.square(np.cos(theta))) * + np.cos(theta) * + (2 * np.heaviside(np.sin(theta), 1) - 1) / 8) + +def sph_legendre_p_4_0_jac(theta): + fac = sph_legendre_factor(4, 0) + + return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) * + np.sin(theta) * np.cos(theta) / 2) + +def sph_legendre_p_4_1_jac(theta): + fac = sph_legendre_factor(4, 1) + + return (5 * fac * (-3 + 27 * np.square(np.cos(theta)) - + 28 * np.square(np.square(np.cos(theta)))) * + (2 * np.heaviside(np.sin(theta), 1) - 1) / 2) + +def sph_legendre_p_4_2_jac(theta): + fac = sph_legendre_factor(4, 2) + + return (30 * fac * (7 * np.square(np.cos(theta)) - 4) * + np.sin(theta) * np.cos(theta)) + +def sph_legendre_p_4_3_jac(theta): + fac = sph_legendre_factor(4, 3) + + return (-105 * fac * (4 * np.square(np.cos(theta)) - 1) * + np.abs(np.sin(theta)) * np.sin(theta)) + +def sph_legendre_p_4_4_jac(theta): + fac = sph_legendre_factor(4, 4) + + return (-420 * fac * (np.square(np.cos(theta)) - 1) * + np.sin(theta) * np.cos(theta)) + +def sph_legendre_p_4_m4_jac(theta): + fac = sph_legendre_factor(4, -4) + + return (-fac * (np.square(np.cos(theta)) - 1) * + np.sin(theta) * np.cos(theta) / 96) + +def sph_legendre_p_4_m3_jac(theta): + fac = sph_legendre_factor(4, -3) + + return (fac * (4 * np.square(np.cos(theta)) - 1) * + np.abs(np.sin(theta)) * np.sin(theta) / 48) + +def sph_legendre_p_4_m2_jac(theta): + fac = sph_legendre_factor(4, -2) + + return (fac * (7 * np.square(np.cos(theta)) - 4) * np.sin(theta) * + np.cos(theta) / 12) + +def sph_legendre_p_4_m1_jac(theta): + fac = sph_legendre_factor(4, -1) + + return (-fac * (-3 + 27 * np.square(np.cos(theta)) - + 28 * np.square(np.square(np.cos(theta)))) * + (2 * np.heaviside(np.sin(theta), 1) - 1) / 8) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3a5071fc671d8d4a7ef6c7655ca4212ced4f45 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py @@ -0,0 +1,109 @@ +import numpy as np +from numpy.testing import assert_allclose + +import pytest + +import scipy.special as sc + + +@pytest.mark.parametrize('x, expected', [ + (np.array([1000, 1]), np.array([0, -999])), + + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + (np.arange(4), np.array([-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533])) +]) +def test_log_softmax(x, expected): + assert_allclose(sc.log_softmax(x), expected, rtol=1e-13) + + +@pytest.fixture +def log_softmax_x(): + x = np.arange(4) + return x + + +@pytest.fixture +def log_softmax_expected(): + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + expected = np.array([-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533]) + return expected + + +def test_log_softmax_translation(log_softmax_x, log_softmax_expected): + # Translation property. If all the values are changed by the same amount, + # the softmax result does not change. + x = log_softmax_x + 100 + expected = log_softmax_expected + assert_allclose(sc.log_softmax(x), expected, rtol=1e-13) + + +def test_log_softmax_noneaxis(log_softmax_x, log_softmax_expected): + # When axis=None, softmax operates on the entire array, and preserves + # the shape. + x = log_softmax_x.reshape(2, 2) + expected = log_softmax_expected.reshape(2, 2) + assert_allclose(sc.log_softmax(x), expected, rtol=1e-13) + + +@pytest.mark.parametrize('axis_2d, expected_2d', [ + (0, np.log(0.5) * np.ones((2, 2))), + (1, np.array([[0, -999], [0, -999]])) +]) +def test_axes(axis_2d, expected_2d): + assert_allclose( + sc.log_softmax([[1000, 1], [1000, 1]], axis=axis_2d), + expected_2d, + rtol=1e-13, + ) + + +@pytest.fixture +def log_softmax_2d_x(): + x = np.arange(8).reshape(2, 4) + return x + + +@pytest.fixture +def log_softmax_2d_expected(): + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + expected = np.array([[-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533], + [-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533]]) + return expected + + +def test_log_softmax_2d_axis1(log_softmax_2d_x, log_softmax_2d_expected): + x = log_softmax_2d_x + expected = log_softmax_2d_expected + assert_allclose(sc.log_softmax(x, axis=1), expected, rtol=1e-13) + + +def test_log_softmax_2d_axis0(log_softmax_2d_x, log_softmax_2d_expected): + x = log_softmax_2d_x.T + expected = log_softmax_2d_expected.T + assert_allclose(sc.log_softmax(x, axis=0), expected, rtol=1e-13) + + +def test_log_softmax_3d(log_softmax_2d_x, log_softmax_2d_expected): + # 3-d input, with a tuple for the axis. + x_3d = log_softmax_2d_x.reshape(2, 2, 2) + expected_3d = log_softmax_2d_expected.reshape(2, 2, 2) + assert_allclose(sc.log_softmax(x_3d, axis=(1, 2)), expected_3d, rtol=1e-13) + + +def test_log_softmax_scalar(): + assert_allclose(sc.log_softmax(1.0), 0.0, rtol=1e-13) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py new file mode 100644 index 0000000000000000000000000000000000000000..2fcb5a20037de46df939895d38fbe5fe6b85c9aa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py @@ -0,0 +1,70 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_ + +from scipy.special._testutils import FuncData +from scipy.special import gamma, gammaln, loggamma + + +def test_identities1(): + # test the identity exp(loggamma(z)) = gamma(z) + x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]) + y = x.copy() + x, y = np.meshgrid(x, y) + z = (x + 1J*y).flatten() + dataset = np.vstack((z, gamma(z))).T + + def f(z): + return np.exp(loggamma(z)) + + FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + + +def test_identities2(): + # test the identity loggamma(z + 1) = log(z) + loggamma(z) + x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]) + y = x.copy() + x, y = np.meshgrid(x, y) + z = (x + 1J*y).flatten() + dataset = np.vstack((z, np.log(z) + loggamma(z))).T + + def f(z): + return loggamma(z + 1) + + FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + + +def test_complex_dispatch_realpart(): + # Test that the real parts of loggamma and gammaln agree on the + # real axis. + x = np.r_[-np.logspace(10, -10), np.logspace(-10, 10)] + 0.5 + + dataset = np.vstack((x, gammaln(x))).T + + def f(z): + z = np.array(z, dtype='complex128') + return loggamma(z).real + + FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + + +def test_real_dispatch(): + x = np.logspace(-10, 10) + 0.5 + dataset = np.vstack((x, gammaln(x))).T + + FuncData(loggamma, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + assert_(loggamma(0) == np.inf) + assert_(np.isnan(loggamma(-1))) + + +def test_gh_6536(): + z = loggamma(complex(-3.4, +0.0)) + zbar = loggamma(complex(-3.4, -0.0)) + assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0) + + +def test_branch_cut(): + # Make sure negative zero is treated correctly + x = -np.logspace(300, -30, 100) + z = np.asarray([complex(x0, 0.0) for x0 in x]) + zbar = np.asarray([complex(x0, -0.0) for x0 in x]) + assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py new file mode 100644 index 0000000000000000000000000000000000000000..050e8db5cb408c5c576c6cd292175d2df7c8f756 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py @@ -0,0 +1,162 @@ +import numpy as np +from numpy.testing import (assert_equal, assert_almost_equal, + assert_allclose) +from scipy.special import logit, expit, log_expit + + +class TestLogit: + + def check_logit_out(self, a, expected): + actual = logit(a) + assert_equal(actual.dtype, a.dtype) + rtol = 16*np.finfo(a.dtype).eps + assert_allclose(actual, expected, rtol=rtol) + + def test_float32(self): + a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float32), + [np.float32(0.0001), np.float32(0.49999), + np.float32(0.50001)])) + # Expected values computed with mpmath from float32 inputs, e.g. + # from mpmath import mp + # mp.dps = 200 + # a = np.float32(1/9) + # print(np.float32(mp.log(a) - mp.log1p(-a))) + # prints `-2.0794415`. + expected = np.array([-np.inf, -2.0794415, -1.2527629, -6.9314712e-01, + -2.2314353e-01, 2.2314365e-01, 6.9314724e-01, + 1.2527630, 2.0794415, np.inf, + -9.2102404, -4.0054321e-05, 4.0054321e-05], + dtype=np.float32) + self.check_logit_out(a, expected) + + def test_float64(self): + a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float64), + [1e-8, 0.4999999999999, 0.50000000001])) + # Expected values computed with mpmath. + expected = np.array([-np.inf, + -2.079441541679836, + -1.252762968495368, + -0.6931471805599454, + -0.22314355131420985, + 0.22314355131420985, + 0.6931471805599452, + 1.2527629684953674, + 2.0794415416798353, + np.inf, + -18.420680733952366, + -3.999023334699814e-13, + 4.000000330961484e-11]) + self.check_logit_out(a, expected) + + def test_nan(self): + expected = np.array([np.nan]*4) + with np.errstate(invalid='ignore'): + actual = logit(np.array([-3., -2., 2., 3.])) + + assert_equal(expected, actual) + + +class TestExpit: + def check_expit_out(self, dtype, expected): + a = np.linspace(-4, 4, 10) + a = np.array(a, dtype=dtype) + actual = expit(a) + assert_almost_equal(actual, expected) + assert_equal(actual.dtype, np.dtype(dtype)) + + def test_float32(self): + expected = np.array([0.01798621, 0.04265125, + 0.09777259, 0.20860852, + 0.39068246, 0.60931754, + 0.79139149, 0.9022274, + 0.95734876, 0.98201376], dtype=np.float32) + self.check_expit_out('f4', expected) + + def test_float64(self): + expected = np.array([0.01798621, 0.04265125, + 0.0977726, 0.20860853, + 0.39068246, 0.60931754, + 0.79139147, 0.9022274, + 0.95734875, 0.98201379]) + self.check_expit_out('f8', expected) + + def test_large(self): + for dtype in (np.float32, np.float64, np.longdouble): + for n in (88, 89, 709, 710, 11356, 11357): + n = np.array(n, dtype=dtype) + assert_allclose(expit(n), 1.0, atol=1e-20) + assert_allclose(expit(-n), 0.0, atol=1e-20) + assert_equal(expit(n).dtype, dtype) + assert_equal(expit(-n).dtype, dtype) + + +class TestLogExpit: + + def test_large_negative(self): + x = np.array([-10000.0, -750.0, -500.0, -35.0]) + y = log_expit(x) + assert_equal(y, x) + + def test_large_positive(self): + x = np.array([750.0, 1000.0, 10000.0]) + y = log_expit(x) + # y will contain -0.0, and -0.0 is used in the expected value, + # but assert_equal does not check the sign of zeros, and I don't + # think the sign is an essential part of the test (i.e. it would + # probably be OK if log_expit(1000) returned 0.0 instead of -0.0). + assert_equal(y, np.array([-0.0, -0.0, -0.0])) + + def test_basic_float64(self): + x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9, + 0, 1e-9, 0.1, 1, 10, 100, 500, 710, 725, 735]) + y = log_expit(x) + # + # Expected values were computed with mpmath: + # + # import mpmath + # + # mpmath.mp.dps = 100 + # + # def mp_log_expit(x): + # return -mpmath.log1p(mpmath.exp(-x)) + # + # expected = [float(mp_log_expit(t)) for t in x] + # + expected = [-32.000000000000014, -20.000000002061153, + -10.000045398899218, -3.048587351573742, + -1.3132616875182228, -0.7443966600735709, + -0.6931471810599453, -0.6931471805599453, + -0.6931471800599454, -0.6443966600735709, + -0.3132616875182228, -4.539889921686465e-05, + -3.720075976020836e-44, -7.124576406741286e-218, + -4.47628622567513e-309, -1.36930634e-315, + -6.217e-320] + + # When tested locally, only one value in y was not exactly equal to + # expected. That was for x=1, and the y value differed from the + # expected by 1 ULP. For this test, however, I'll use rtol=1e-15. + assert_allclose(y, expected, rtol=1e-15) + + def test_basic_float32(self): + x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9, + 0, 1e-9, 0.1, 1, 10, 100], dtype=np.float32) + y = log_expit(x) + # + # Expected values were computed with mpmath: + # + # import mpmath + # + # mpmath.mp.dps = 100 + # + # def mp_log_expit(x): + # return -mpmath.log1p(mpmath.exp(-x)) + # + # expected = [np.float32(mp_log_expit(t)) for t in x] + # + expected = np.array([-32.0, -20.0, -10.000046, -3.0485873, + -1.3132616, -0.7443967, -0.6931472, + -0.6931472, -0.6931472, -0.64439666, + -0.3132617, -4.5398898e-05, -3.8e-44], + dtype=np.float32) + + assert_allclose(y, expected, rtol=5e-7) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py new file mode 100644 index 0000000000000000000000000000000000000000..420c0d89f438701b57c4786ce7fa62279c668e5e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py @@ -0,0 +1,327 @@ +import math +import pytest + +import numpy as np +from numpy.testing import assert_allclose + +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import array_namespace, is_array_api_strict +from scipy._lib._array_api_no_0d import (xp_assert_equal, xp_assert_close, + xp_assert_less) + +from scipy.special import logsumexp, softmax +from scipy.special._logsumexp import _wrap_radians + + +dtypes = ['float32', 'float64', 'int32', 'int64', 'complex64', 'complex128'] +integral_dtypes = ['int32', 'int64'] + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +@pytest.mark.skip_xp_backends('jax.numpy', + reason="JAX arrays do not support item assignment") +def test_wrap_radians(xp): + x = xp.asarray([-math.pi-1, -math.pi, -1, -1e-300, + 0, 1e-300, 1, math.pi, math.pi+1]) + ref = xp.asarray([math.pi-1, math.pi, -1, -1e-300, + 0, 1e-300, 1, math.pi, -math.pi+1]) + res = _wrap_radians(x, xp) + xp_assert_close(res, ref, atol=0) + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +@pytest.mark.skip_xp_backends('jax.numpy', + reason="JAX arrays do not support item assignment") +class TestLogSumExp: + def test_logsumexp(self, xp): + # Test with zero-size array + a = xp.asarray([]) + desired = xp.asarray(-xp.inf) + xp_assert_equal(logsumexp(a), desired) + + # Test whether logsumexp() function correctly handles large inputs. + a = xp.arange(200., dtype=xp.float64) + desired = xp.log(xp.sum(xp.exp(a))) + xp_assert_close(logsumexp(a), desired) + + # Now test with large numbers + b = xp.asarray([1000., 1000.]) + desired = xp.asarray(1000.0 + math.log(2.0)) + xp_assert_close(logsumexp(b), desired) + + n = 1000 + b = xp.full((n,), 10000) + desired = xp.asarray(10000.0 + math.log(n)) + xp_assert_close(logsumexp(b), desired) + + x = xp.asarray([1e-40] * 1000000) + logx = xp.log(x) + X = xp.stack([x, x]) + logX = xp.stack([logx, logx]) + xp_assert_close(xp.exp(logsumexp(logX)), xp.sum(X)) + xp_assert_close(xp.exp(logsumexp(logX, axis=0)), xp.sum(X, axis=0)) + xp_assert_close(xp.exp(logsumexp(logX, axis=1)), xp.sum(X, axis=1)) + + # Handling special values properly + inf = xp.asarray([xp.inf]) + nan = xp.asarray([xp.nan]) + xp_assert_equal(logsumexp(inf), inf[0]) + xp_assert_equal(logsumexp(-inf), -inf[0]) + xp_assert_equal(logsumexp(nan), nan[0]) + xp_assert_equal(logsumexp(xp.asarray([-xp.inf, -xp.inf])), -inf[0]) + + # Handling an array with different magnitudes on the axes + a = xp.asarray([[1e10, 1e-10], + [-1e10, -np.inf]]) + ref = xp.asarray([1e10, -1e10]) + xp_assert_close(logsumexp(a, axis=-1), ref) + + # Test keeping dimensions + xp_test = array_namespace(a) # `torch` needs `expand_dims` + ref = xp_test.expand_dims(ref, axis=-1) + xp_assert_close(logsumexp(a, axis=-1, keepdims=True), ref) + + # Test multiple axes + xp_assert_close(logsumexp(a, axis=(-1, -2)), xp.asarray(1e10)) + + def test_logsumexp_b(self, xp): + a = xp.arange(200., dtype=xp.float64) + b = xp.arange(200., 0., -1.) + desired = xp.log(xp.sum(b*xp.exp(a))) + xp_assert_close(logsumexp(a, b=b), desired) + + a = xp.asarray([1000, 1000]) + b = xp.asarray([1.2, 1.2]) + desired = xp.asarray(1000 + math.log(2 * 1.2)) + xp_assert_close(logsumexp(a, b=b), desired) + + x = xp.asarray([1e-40] * 100000) + b = xp.linspace(1, 1000, 100000) + logx = xp.log(x) + X = xp.stack((x, x)) + logX = xp.stack((logx, logx)) + B = xp.stack((b, b)) + xp_assert_close(xp.exp(logsumexp(logX, b=B)), xp.sum(B * X)) + xp_assert_close(xp.exp(logsumexp(logX, b=B, axis=0)), xp.sum(B * X, axis=0)) + xp_assert_close(xp.exp(logsumexp(logX, b=B, axis=1)), xp.sum(B * X, axis=1)) + + def test_logsumexp_sign(self, xp): + a = xp.asarray([1, 1, 1]) + b = xp.asarray([1, -1, -1]) + + r, s = logsumexp(a, b=b, return_sign=True) + xp_assert_close(r, xp.asarray(1.)) + xp_assert_equal(s, xp.asarray(-1.)) + + def test_logsumexp_sign_zero(self, xp): + a = xp.asarray([1, 1]) + b = xp.asarray([1, -1]) + + r, s = logsumexp(a, b=b, return_sign=True) + assert not xp.isfinite(r) + assert not xp.isnan(r) + assert r < 0 + assert s == 0 + + def test_logsumexp_sign_shape(self, xp): + a = xp.ones((1, 2, 3, 4)) + b = xp.ones_like(a) + + r, s = logsumexp(a, axis=2, b=b, return_sign=True) + assert r.shape == s.shape == (1, 2, 4) + + r, s = logsumexp(a, axis=(1, 3), b=b, return_sign=True) + assert r.shape == s.shape == (1,3) + + def test_logsumexp_complex_sign(self, xp): + a = xp.asarray([1 + 1j, 2 - 1j, -2 + 3j]) + + r, s = logsumexp(a, return_sign=True) + + expected_sumexp = xp.sum(xp.exp(a)) + # This is the numpy>=2.0 convention for np.sign + expected_sign = expected_sumexp / xp.abs(expected_sumexp) + + xp_assert_close(s, expected_sign) + xp_assert_close(s * xp.exp(r), expected_sumexp) + + def test_logsumexp_shape(self, xp): + a = xp.ones((1, 2, 3, 4)) + b = xp.ones_like(a) + + r = logsumexp(a, axis=2, b=b) + assert r.shape == (1, 2, 4) + + r = logsumexp(a, axis=(1, 3), b=b) + assert r.shape == (1, 3) + + def test_logsumexp_b_zero(self, xp): + a = xp.asarray([1, 10000]) + b = xp.asarray([1, 0]) + + xp_assert_close(logsumexp(a, b=b), xp.asarray(1.)) + + def test_logsumexp_b_shape(self, xp): + a = xp.zeros((4, 1, 2, 1)) + b = xp.ones((3, 1, 5)) + + logsumexp(a, b=b) + + @pytest.mark.parametrize('arg', (1, [1, 2, 3])) + @pytest.mark.skip_xp_backends(np_only=True) + def test_xp_invalid_input(self, arg, xp): + assert logsumexp(arg) == logsumexp(np.asarray(np.atleast_1d(arg))) + + @pytest.mark.skip_xp_backends(np_only=True, + reason="Lists correspond with NumPy backend") + def test_list(self, xp): + a = [1000, 1000] + desired = xp.asarray(1000.0 + math.log(2.0), dtype=np.float64) + xp_assert_close(logsumexp(a), desired) + + @pytest.mark.parametrize('dtype', dtypes) + def test_dtypes_a(self, dtype, xp): + dtype = getattr(xp, dtype) + a = xp.asarray([1000., 1000.], dtype=dtype) + xp_test = array_namespace(a) # torch needs compatible `isdtype` + desired_dtype = (xp.asarray(1.).dtype if xp_test.isdtype(dtype, 'integral') + else dtype) # true for all libraries tested + desired = xp.asarray(1000.0 + math.log(2.0), dtype=desired_dtype) + xp_assert_close(logsumexp(a), desired) + + @pytest.mark.parametrize('dtype_a', dtypes) + @pytest.mark.parametrize('dtype_b', dtypes) + def test_dtypes_ab(self, dtype_a, dtype_b, xp): + xp_dtype_a = getattr(xp, dtype_a) + xp_dtype_b = getattr(xp, dtype_b) + a = xp.asarray([2, 1], dtype=xp_dtype_a) + b = xp.asarray([1, -1], dtype=xp_dtype_b) + xp_test = array_namespace(a, b) # torch needs compatible result_type + if is_array_api_strict(xp): + xp_float_dtypes = [dtype for dtype in [xp_dtype_a, xp_dtype_b] + if not xp_test.isdtype(dtype, 'integral')] + if len(xp_float_dtypes) < 2: # at least one is integral + xp_float_dtypes.append(xp.asarray(1.).dtype) + desired_dtype = xp_test.result_type(*xp_float_dtypes) + else: + # True for all libraries tested + desired_dtype = xp_test.result_type(xp_dtype_a, xp_dtype_b, xp.float32) + desired = xp.asarray(math.log(math.exp(2) - math.exp(1)), dtype=desired_dtype) + xp_assert_close(logsumexp(a, b=b), desired) + + def test_gh18295(self, xp): + # gh-18295 noted loss of precision when real part of one element is much + # larger than the rest. Check that this is resolved. + a = xp.asarray([0.0, -40.0]) + res = logsumexp(a) + ref = xp.logaddexp(a[0], a[1]) + xp_assert_close(res, ref) + + @pytest.mark.parametrize('dtype', ['complex64', 'complex128']) + def test_gh21610(self, xp, dtype): + # gh-21610 noted that `logsumexp` could return imaginary components + # outside the range (-pi, pi]. Check that this is resolved. + # While working on this, I noticed that all other tests passed even + # when the imaginary component of the result was zero. This suggested + # the need of a stronger test with imaginary dtype. + rng = np.random.default_rng(324984329582349862) + dtype = getattr(xp, dtype) + shape = (10, 100) + x = rng.uniform(1, 40, shape) + 1.j * rng.uniform(1, 40, shape) + x = xp.asarray(x, dtype=dtype) + + res = logsumexp(x, axis=1) + ref = xp.log(xp.sum(xp.exp(x), axis=1)) + max = xp.full_like(xp.imag(res), xp.asarray(xp.pi)) + xp_assert_less(xp.abs(xp.imag(res)), max) + xp_assert_close(res, ref) + + out, sgn = logsumexp(x, return_sign=True, axis=1) + ref = xp.sum(xp.exp(x), axis=1) + xp_assert_less(xp.abs(xp.imag(sgn)), max) + xp_assert_close(out, xp.real(xp.log(ref))) + xp_assert_close(sgn, ref/xp.abs(ref)) + + def test_gh21709_small_imaginary(self, xp): + # Test that `logsumexp` does not lose relative precision of + # small imaginary components + x = xp.asarray([0, 0.+2.2204460492503132e-17j]) + res = logsumexp(x) + # from mpmath import mp + # mp.dps = 100 + # x, y = mp.mpc(0), mp.mpc('0', '2.2204460492503132e-17') + # ref = complex(mp.log(mp.exp(x) + mp.exp(y))) + ref = xp.asarray(0.6931471805599453+1.1102230246251566e-17j) + xp_assert_close(xp.real(res), xp.real(ref)) + xp_assert_close(xp.imag(res), xp.imag(ref), atol=0, rtol=1e-15) + + def test_gh22903(self, xp): + # gh-22903 reported that `logsumexp` produced NaN where the weight associated + # with the max magnitude element was negative and `return_sign=False`, even if + # the net result should be the log of a positive number. + + # result is log of positive number + a = xp.asarray([3.06409428, 0.37251854, 3.87471931]) + b = xp.asarray([1.88190708, 2.84174795, -0.85016884]) + xp_assert_close(logsumexp(a, b=b), logsumexp(a, b=b, return_sign=True)[0]) + + # result is log of negative number + b = xp.asarray([1.88190708, 2.84174795, -3.85016884]) + xp_assert_close(logsumexp(a, b=b), xp.asarray(xp.nan)) + + +class TestSoftmax: + def test_softmax_fixtures(self): + assert_allclose(softmax([1000, 0, 0, 0]), np.array([1, 0, 0, 0]), + rtol=1e-13) + assert_allclose(softmax([1, 1]), np.array([.5, .5]), rtol=1e-13) + assert_allclose(softmax([0, 1]), np.array([1, np.e])/(1 + np.e), + rtol=1e-13) + + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + x = np.arange(4) + expected = np.array([0.03205860328008499, + 0.08714431874203256, + 0.23688281808991013, + 0.6439142598879722]) + + assert_allclose(softmax(x), expected, rtol=1e-13) + + # Translation property. If all the values are changed by the same amount, + # the softmax result does not change. + assert_allclose(softmax(x + 100), expected, rtol=1e-13) + + # When axis=None, softmax operates on the entire array, and preserves + # the shape. + assert_allclose(softmax(x.reshape(2, 2)), expected.reshape(2, 2), + rtol=1e-13) + + + def test_softmax_multi_axes(self): + assert_allclose(softmax([[1000, 0], [1000, 0]], axis=0), + np.array([[.5, .5], [.5, .5]]), rtol=1e-13) + assert_allclose(softmax([[1000, 0], [1000, 0]], axis=1), + np.array([[1, 0], [1, 0]]), rtol=1e-13) + + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + x = np.array([[-25, 0, 25, 50], + [1, 325, 749, 750]]) + expected = np.array([[2.678636961770877e-33, + 1.9287498479371314e-22, + 1.3887943864771144e-11, + 0.999999999986112], + [0.0, + 1.9444526359919372e-185, + 0.2689414213699951, + 0.7310585786300048]]) + assert_allclose(softmax(x, axis=1), expected, rtol=1e-13) + assert_allclose(softmax(x.T, axis=0), expected.T, rtol=1e-13) + + # 3-d input, with a tuple for the axis. + x3d = x.reshape(2, 2, 2) + assert_allclose(softmax(x3d, axis=(1, 2)), expected.reshape(2, 2, 2), + rtol=1e-13) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py new file mode 100644 index 0000000000000000000000000000000000000000..43e84e444f2eda03aef77ea923ca2d498aef4126 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py @@ -0,0 +1,2292 @@ +""" +Test SciPy functions versus mpmath, if available. + +""" +import numpy as np +from numpy.testing import assert_, assert_allclose, suppress_warnings +from numpy import pi +import pytest +import itertools + +from scipy._lib import _pep440 + +import scipy.special as sc +from scipy.special._testutils import ( + MissingModule, check_version, FuncData, + assert_func_equal) +from scipy.special._mptestutils import ( + Arg, FixedArg, ComplexArg, IntArg, assert_mpmath_equal, + nonfunctional_tooslow, trace_args, time_limited, exception_to_nan, + inf_to_nan) +from scipy.special._ufuncs import ( + _sinpi, _cospi, _lgam1p, _lanczos_sum_expg_scaled, _log1pmx, + _igam_fac) + +try: + import mpmath +except ImportError: + mpmath = MissingModule('mpmath') + + +# ------------------------------------------------------------------------------ +# expi +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.10') +def test_expi_complex(): + dataset = [] + for r in np.logspace(-99, 2, 10): + for p in np.linspace(0, 2*np.pi, 30): + z = r*np.exp(1j*p) + dataset.append((z, complex(mpmath.ei(z)))) + dataset = np.array(dataset, dtype=np.cdouble) + + FuncData(sc.expi, dataset, 0, 1).check() + + +# ------------------------------------------------------------------------------ +# expn +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +def test_expn_large_n(): + # Test the transition to the asymptotic regime of n. + dataset = [] + for n in [50, 51]: + for x in np.logspace(0, 4, 200): + with mpmath.workdps(100): + dataset.append((n, x, float(mpmath.expint(n, x)))) + dataset = np.asarray(dataset) + + FuncData(sc.expn, dataset, (0, 1), 2, rtol=1e-13).check() + +# ------------------------------------------------------------------------------ +# hyp0f1 +# ------------------------------------------------------------------------------ + + +@check_version(mpmath, '0.19') +def test_hyp0f1_gh5764(): + # Do a small and somewhat systematic test that runs quickly + dataset = [] + axis = [-99.5, -9.5, -0.5, 0.5, 9.5, 99.5] + for v in axis: + for x in axis: + for y in axis: + z = x + 1j*y + # mpmath computes the answer correctly at dps ~ 17 but + # fails for 20 < dps < 120 (uses a different method); + # set the dps high enough that this isn't an issue + with mpmath.workdps(120): + res = complex(mpmath.hyp0f1(v, z)) + dataset.append((v, z, res)) + dataset = np.array(dataset) + + FuncData(lambda v, z: sc.hyp0f1(v.real, z), dataset, (0, 1), 2, + rtol=1e-13).check() + + +@check_version(mpmath, '0.19') +def test_hyp0f1_gh_1609(): + # this is a regression test for gh-1609 + vv = np.linspace(150, 180, 21) + af = sc.hyp0f1(vv, 0.5) + mf = np.array([mpmath.hyp0f1(v, 0.5) for v in vv]) + assert_allclose(af, mf.astype(float), rtol=1e-12) + + +# ------------------------------------------------------------------------------ +# hyperu +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '1.1.0') +def test_hyperu_around_0(): + dataset = [] + # DLMF 13.2.14-15 test points. + for n in np.arange(-5, 5): + for b in np.linspace(-5, 5, 20): + a = -n + dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0)))) + a = -n + b - 1 + dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0)))) + # DLMF 13.2.16-22 test points. + for a in [-10.5, -1.5, -0.5, 0, 0.5, 1, 10]: + for b in [-1.0, -0.5, 0, 0.5, 1, 1.5, 2, 2.5]: + dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0)))) + dataset = np.array(dataset) + + FuncData(sc.hyperu, dataset, (0, 1, 2), 3, rtol=1e-15, atol=5e-13).check() + + +# ------------------------------------------------------------------------------ +# hyp2f1 +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '1.0.0') +def test_hyp2f1_strange_points(): + pts = [ + (2, -1, -1, 0.7), # expected: 2.4 + (2, -2, -2, 0.7), # expected: 3.87 + ] + pts += list(itertools.product([2, 1, -0.7, -1000], repeat=4)) + pts = [ + (a, b, c, x) for a, b, c, x in pts + if b == c and round(b) == b and b < 0 and b != -1000 + ] + kw = dict(eliminate=True) + dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() + + +@check_version(mpmath, '0.13') +def test_hyp2f1_real_some_points(): + pts = [ + (1, 2, 3, 0), + (1./3, 2./3, 5./6, 27./32), + (1./4, 1./2, 3./4, 80./81), + (2,-2, -3, 3), + (2, -3, -2, 3), + (2, -1.5, -1.5, 3), + (1, 2, 3, 0), + (0.7235, -1, -5, 0.3), + (0.25, 1./3, 2, 0.999), + (0.25, 1./3, 2, -1), + (2, 3, 5, 0.99), + (3./2, -0.5, 3, 0.99), + (2, 2.5, -3.25, 0.999), + (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001), + (-10, 900, -10.5, 0.99), + (-10, 900, 10.5, 0.99), + (-1, 2, 1, 1.0), + (-1, 2, 1, -1.0), + (-3, 13, 5, 1.0), + (-3, 13, 5, -1.0), + (0.5, 1 - 270.5, 1.5, 0.999**2), # from issue 1561 + ] + dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + with np.errstate(invalid='ignore'): + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() + + +@check_version(mpmath, '0.14') +def test_hyp2f1_some_points_2(): + # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but + # was fixed in their SVN since then + pts = [ + (112, (51,10), (-9,10), -0.99999), + (10,-900,10.5,0.99), + (10,-900,-10.5,0.99), + ] + + def fev(x): + if isinstance(x, tuple): + return float(x[0]) / x[1] + else: + return x + + dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() + + +@check_version(mpmath, '0.13') +def test_hyp2f1_real_some(): + dataset = [] + for a in [-10, -5, -1.8, 1.8, 5, 10]: + for b in [-2.5, -1, 1, 7.4]: + for c in [-9, -1.8, 5, 20.4]: + for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]: + try: + v = float(mpmath.hyp2f1(a, b, c, z)) + except Exception: + continue + dataset.append((a, b, c, z, v)) + dataset = np.array(dataset, dtype=np.float64) + + with np.errstate(invalid='ignore'): + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9, + ignore_inf_sign=True).check() + + +@check_version(mpmath, '0.12') +@pytest.mark.slow +def test_hyp2f1_real_random(): + npoints = 500 + dataset = np.zeros((npoints, 5), np.float64) + + np.random.seed(1234) + dataset[:, 0] = np.random.pareto(1.5, npoints) + dataset[:, 1] = np.random.pareto(1.5, npoints) + dataset[:, 2] = np.random.pareto(1.5, npoints) + dataset[:, 3] = 2*np.random.rand(npoints) - 1 + + dataset[:, 0] *= (-1)**np.random.randint(2, npoints) + dataset[:, 1] *= (-1)**np.random.randint(2, npoints) + dataset[:, 2] *= (-1)**np.random.randint(2, npoints) + + for ds in dataset: + if mpmath.__version__ < '0.14': + # mpmath < 0.14 fails for c too much smaller than a, b + if abs(ds[:2]).max() > abs(ds[2]): + ds[2] = abs(ds[:2]).max() + ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4]))) + + FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check() + + +# ------------------------------------------------------------------------------ +# erf (complex) +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.14') +def test_erf_complex(): + # need to increase mpmath precision for this test + old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec + try: + mpmath.mp.dps = 70 + x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11)) + x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11)) + points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(), y2.ravel()] + + assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points, + vectorized=False, rtol=1e-13) + assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points, + vectorized=False, rtol=1e-13) + finally: + mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec + + +# ------------------------------------------------------------------------------ +# lpmv +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.15') +def test_lpmv(): + pts = [] + for x in [-0.99, -0.557, 1e-6, 0.132, 1]: + pts.extend([ + (1, 1, x), + (1, -1, x), + (-1, 1, x), + (-1, -2, x), + (1, 1.7, x), + (1, -1.7, x), + (-1, 1.7, x), + (-1, -2.7, x), + (1, 10, x), + (1, 11, x), + (3, 8, x), + (5, 11, x), + (-3, 8, x), + (-5, 11, x), + (3, -8, x), + (5, -11, x), + (-3, -8, x), + (-5, -11, x), + (3, 8.3, x), + (5, 11.3, x), + (-3, 8.3, x), + (-5, 11.3, x), + (3, -8.3, x), + (5, -11.3, x), + (-3, -8.3, x), + (-5, -11.3, x), + ]) + + def mplegenp(nu, mu, x): + if mu == int(mu) and x == 1: + # mpmath 0.17 gets this wrong + if mu == 0: + return 1 + else: + return 0 + return mpmath.legenp(nu, mu, x) + + dataset = [p + (mplegenp(p[1], p[0], p[2]),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + def evf(mu, nu, x): + return sc.lpmv(mu.astype(int), nu, x) + + with np.errstate(invalid='ignore'): + FuncData(evf, dataset, (0,1,2), 3, rtol=1e-10, atol=1e-14).check() + + +# ------------------------------------------------------------------------------ +# beta +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.15') +def test_beta(): + np.random.seed(1234) + + b = np.r_[np.logspace(-200, 200, 4), + np.logspace(-10, 10, 4), + np.logspace(-1, 1, 4), + np.arange(-10, 11, 1), + np.arange(-10, 11, 1) + 0.5, + -1, -2.3, -3, -100.3, -10003.4] + a = b + + ab = np.array(np.broadcast_arrays(a[:,None], b[None,:])).reshape(2, -1).T + + old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec + try: + mpmath.mp.dps = 400 + + assert_func_equal(sc.beta, + lambda a, b: float(mpmath.beta(a, b)), + ab, + vectorized=False, + rtol=1e-10, + ignore_inf_sign=True) + + assert_func_equal( + sc.betaln, + lambda a, b: float(mpmath.log(abs(mpmath.beta(a, b)))), + ab, + vectorized=False, + rtol=1e-10) + finally: + mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec + + +# ------------------------------------------------------------------------------ +# loggamma +# ------------------------------------------------------------------------------ + +LOGGAMMA_TAYLOR_RADIUS = 0.2 + + +@check_version(mpmath, '0.19') +def test_loggamma_taylor_transition(): + # Make sure there isn't a big jump in accuracy when we move from + # using the Taylor series to using the recurrence relation. + + r = LOGGAMMA_TAYLOR_RADIUS + np.array([-0.1, -0.01, 0, 0.01, 0.1]) + theta = np.linspace(0, 2*np.pi, 20) + r, theta = np.meshgrid(r, theta) + dz = r*np.exp(1j*theta) + z = np.r_[1 + dz, 2 + dz].flatten() + + dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z] + dataset = np.array(dataset) + + FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check() + + +@check_version(mpmath, '0.19') +def test_loggamma_taylor(): + # Test around the zeros at z = 1, 2. + + r = np.logspace(-16, np.log10(LOGGAMMA_TAYLOR_RADIUS), 10) + theta = np.linspace(0, 2*np.pi, 20) + r, theta = np.meshgrid(r, theta) + dz = r*np.exp(1j*theta) + z = np.r_[1 + dz, 2 + dz].flatten() + + dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z] + dataset = np.array(dataset) + + FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check() + + +# ------------------------------------------------------------------------------ +# rgamma +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_rgamma_zeros(): + # Test around the zeros at z = 0, -1, -2, ..., -169. (After -169 we + # get values that are out of floating point range even when we're + # within 0.1 of the zero.) + + # Can't use too many points here or the test takes forever. + dx = np.r_[-np.logspace(-1, -13, 3), 0, np.logspace(-13, -1, 3)] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + zeros = np.arange(0, -170, -1).reshape(1, 1, -1) + z = (zeros + np.dstack((dz,)*zeros.size)).flatten() + with mpmath.workdps(100): + dataset = [(z0, complex(mpmath.rgamma(z0))) for z0 in z] + + dataset = np.array(dataset) + FuncData(sc.rgamma, dataset, 0, 1, rtol=1e-12).check() + + +# ------------------------------------------------------------------------------ +# digamma +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_digamma_roots(): + # Test the special-cased roots for digamma. + root = mpmath.findroot(mpmath.digamma, 1.5) + roots = [float(root)] + root = mpmath.findroot(mpmath.digamma, -0.5) + roots.append(float(root)) + roots = np.array(roots) + + # If we test beyond a radius of 0.24 mpmath will take forever. + dx = np.r_[-0.24, -np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10), 0.24] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + z = (roots + np.dstack((dz,)*roots.size)).flatten() + with mpmath.workdps(30): + dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z] + + dataset = np.array(dataset) + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check() + + +@check_version(mpmath, '0.19') +def test_digamma_negreal(): + # Test digamma around the negative real axis. Don't do this in + # TestSystematic because the points need some jiggering so that + # mpmath doesn't take forever. + + digamma = exception_to_nan(mpmath.digamma) + + x = -np.logspace(300, -30, 100) + y = np.r_[-np.logspace(0, -3, 5), 0, np.logspace(-3, 0, 5)] + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + with mpmath.workdps(40): + dataset = [(z0, complex(digamma(z0))) for z0 in z] + dataset = np.asarray(dataset) + + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check() + + +@check_version(mpmath, '0.19') +def test_digamma_boundary(): + # Check that there isn't a jump in accuracy when we switch from + # using the asymptotic series to the reflection formula. + + x = -np.logspace(300, -30, 100) + y = np.array([-6.1, -5.9, 5.9, 6.1]) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + with mpmath.workdps(30): + dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z] + dataset = np.asarray(dataset) + + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check() + + +# ------------------------------------------------------------------------------ +# gammainc +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_gammainc_boundary(): + # Test the transition to the asymptotic series. + small = 20 + a = np.linspace(0.5*small, 2*small, 50) + x = a.copy() + a, x = np.meshgrid(a, x) + a, x = a.flatten(), x.flatten() + with mpmath.workdps(100): + dataset = [(a0, x0, float(mpmath.gammainc(a0, b=x0, regularized=True))) + for a0, x0 in zip(a, x)] + dataset = np.array(dataset) + + FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-12).check() + + +# ------------------------------------------------------------------------------ +# spence +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_spence_circle(): + # The trickiest region for spence is around the circle |z - 1| = 1, + # so test that region carefully. + + def spence(z): + return complex(mpmath.polylog(2, 1 - z)) + + r = np.linspace(0.5, 1.5) + theta = np.linspace(0, 2*pi) + z = (1 + np.outer(r, np.exp(1j*theta))).flatten() + dataset = np.asarray([(z0, spence(z0)) for z0 in z]) + + FuncData(sc.spence, dataset, 0, 1, rtol=1e-14).check() + + +# ------------------------------------------------------------------------------ +# sinpi and cospi +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +def test_sinpi_zeros(): + eps = np.finfo(float).eps + dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + zeros = np.arange(-100, 100, 1).reshape(1, 1, -1) + z = (zeros + np.dstack((dz,)*zeros.size)).flatten() + dataset = np.asarray([(z0, complex(mpmath.sinpi(z0))) + for z0 in z]) + FuncData(_sinpi, dataset, 0, 1, rtol=2*eps).check() + + +@check_version(mpmath, '0.19') +def test_cospi_zeros(): + eps = np.finfo(float).eps + dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + zeros = (np.arange(-100, 100, 1) + 0.5).reshape(1, 1, -1) + z = (zeros + np.dstack((dz,)*zeros.size)).flatten() + dataset = np.asarray([(z0, complex(mpmath.cospi(z0))) + for z0 in z]) + + FuncData(_cospi, dataset, 0, 1, rtol=2*eps).check() + + +# ------------------------------------------------------------------------------ +# ellipj +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +def test_dn_quarter_period(): + def dn(u, m): + return sc.ellipj(u, m)[2] + + def mpmath_dn(u, m): + return float(mpmath.ellipfun("dn", u=u, m=m)) + + m = np.linspace(0, 1, 20) + du = np.r_[-np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10)] + dataset = [] + for m0 in m: + u0 = float(mpmath.ellipk(m0)) + for du0 in du: + p = u0 + du0 + dataset.append((p, m0, mpmath_dn(p, m0))) + dataset = np.asarray(dataset) + + FuncData(dn, dataset, (0, 1), 2, rtol=1e-10).check() + + +# ------------------------------------------------------------------------------ +# Wright Omega +# ------------------------------------------------------------------------------ + +def _mpmath_wrightomega(z, dps): + with mpmath.workdps(dps): + z = mpmath.mpc(z) + unwind = mpmath.ceil((z.imag - mpmath.pi)/(2*mpmath.pi)) + res = mpmath.lambertw(mpmath.exp(z), unwind) + return res + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_wrightomega_branch(): + x = -np.logspace(10, 0, 25) + picut_above = [np.nextafter(np.pi, np.inf)] + picut_below = [np.nextafter(np.pi, -np.inf)] + npicut_above = [np.nextafter(-np.pi, np.inf)] + npicut_below = [np.nextafter(-np.pi, -np.inf)] + for i in range(50): + picut_above.append(np.nextafter(picut_above[-1], np.inf)) + picut_below.append(np.nextafter(picut_below[-1], -np.inf)) + npicut_above.append(np.nextafter(npicut_above[-1], np.inf)) + npicut_below.append(np.nextafter(npicut_below[-1], -np.inf)) + y = np.hstack((picut_above, picut_below, npicut_above, npicut_below)) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25))) + for z0 in z]) + + FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-8).check() + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_wrightomega_region1(): + # This region gets less coverage in the TestSystematic test + x = np.linspace(-2, 1) + y = np.linspace(1, 2*np.pi) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25))) + for z0 in z]) + + FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check() + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_wrightomega_region2(): + # This region gets less coverage in the TestSystematic test + x = np.linspace(-2, 1) + y = np.linspace(-2*np.pi, -1) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25))) + for z0 in z]) + + FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check() + + +# ------------------------------------------------------------------------------ +# lambertw +# ------------------------------------------------------------------------------ + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_lambertw_smallz(): + x, y = np.linspace(-1, 1, 25), np.linspace(-1, 1, 25) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(mpmath.lambertw(z0))) + for z0 in z]) + + FuncData(sc.lambertw, dataset, 0, 1, rtol=1e-13).check() + + +# ------------------------------------------------------------------------------ +# Systematic tests +# ------------------------------------------------------------------------------ + +# The functions lpn, lpmn, clpmn, and sph_harm appearing below are +# deprecated in favor of legendre_p_all, assoc_legendre_p_all, +# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn), +# and sph_harm_y respectively. The deprecated functions listed above are +# implemented as shims around their respective replacements. The replacements +# are tested separately, but tests for the deprecated functions remain to +# verify the correctness of the shims. + +HYPERKW = dict(maxprec=200, maxterms=200) + + +@pytest.mark.slow +@check_version(mpmath, '0.17') +class TestSystematic: + + def test_airyai(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[0], + mpmath.airyai, + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[0], + mpmath.airyai, + [Arg(-1e3, 1e3)]) + + def test_airyai_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[0], + mpmath.airyai, + [ComplexArg()]) + + def test_airyai_prime(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: + mpmath.airyai(z, derivative=1), + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: + mpmath.airyai(z, derivative=1), + [Arg(-1e3, 1e3)]) + + def test_airyai_prime_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: + mpmath.airyai(z, derivative=1), + [ComplexArg()]) + + def test_airybi(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: + mpmath.airybi(z), + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: + mpmath.airybi(z), + [Arg(-1e3, 1e3)]) + + def test_airybi_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: + mpmath.airybi(z), + [ComplexArg()]) + + def test_airybi_prime(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: + mpmath.airybi(z, derivative=1), + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: + mpmath.airybi(z, derivative=1), + [Arg(-1e3, 1e3)]) + + def test_airybi_prime_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: + mpmath.airybi(z, derivative=1), + [ComplexArg()]) + + def test_bei(self): + assert_mpmath_equal(sc.bei, + exception_to_nan(lambda z: mpmath.bei(0, z, **HYPERKW)), + [Arg(-1e3, 1e3)]) + + def test_ber(self): + assert_mpmath_equal(sc.ber, + exception_to_nan(lambda z: mpmath.ber(0, z, **HYPERKW)), + [Arg(-1e3, 1e3)]) + + def test_bernoulli(self): + assert_mpmath_equal(lambda n: sc.bernoulli(int(n))[int(n)], + lambda n: float(mpmath.bernoulli(int(n))), + [IntArg(0, 13000)], + rtol=1e-9, n=13000) + + def test_besseli(self): + assert_mpmath_equal( + sc.iv, + exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), Arg()], + atol=1e-270, + ) + + def test_besseli_complex(self): + assert_mpmath_equal( + lambda v, z: sc.iv(v.real, z), + exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), ComplexArg()], + ) + + def test_besselj(self): + assert_mpmath_equal( + sc.jv, + exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), Arg(-1e3, 1e3)], + ignore_inf_sign=True, + ) + + # loss of precision at large arguments due to oscillation + assert_mpmath_equal( + sc.jv, + exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), Arg(-1e8, 1e8)], + ignore_inf_sign=True, + rtol=1e-5, + ) + + def test_besselj_complex(self): + assert_mpmath_equal( + lambda v, z: sc.jv(v.real, z), + exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), + [Arg(), ComplexArg()] + ) + + def test_besselk(self): + assert_mpmath_equal( + sc.kv, + mpmath.besselk, + [Arg(-200, 200), Arg(0, np.inf)], + nan_ok=False, + rtol=1e-12, + ) + + def test_besselk_int(self): + assert_mpmath_equal( + sc.kn, + mpmath.besselk, + [IntArg(-200, 200), Arg(0, np.inf)], + nan_ok=False, + rtol=1e-12, + ) + + def test_besselk_complex(self): + assert_mpmath_equal( + lambda v, z: sc.kv(v.real, z), + exception_to_nan(lambda v, z: mpmath.besselk(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), ComplexArg()], + ) + + def test_bessely(self): + def mpbessely(v, x): + r = float(mpmath.bessely(v, x, **HYPERKW)) + if abs(r) > 1e305: + # overflowing to inf a bit earlier is OK + r = np.inf * np.sign(r) + if abs(r) == 0 and x == 0: + # invalid result from mpmath, point x=0 is a divergence + return np.nan + return r + assert_mpmath_equal( + sc.yv, + exception_to_nan(mpbessely), + [Arg(-1e100, 1e100), Arg(-1e8, 1e8)], + n=5000, + ) + + def test_bessely_complex(self): + def mpbessely(v, x): + r = complex(mpmath.bessely(v, x, **HYPERKW)) + if abs(r) > 1e305: + # overflowing to inf a bit earlier is OK + with np.errstate(invalid='ignore'): + r = np.inf * np.sign(r) + return r + assert_mpmath_equal( + lambda v, z: sc.yv(v.real, z), + exception_to_nan(mpbessely), + [Arg(), ComplexArg()], + n=15000, + ) + + def test_bessely_int(self): + def mpbessely(v, x): + r = float(mpmath.bessely(v, x)) + if abs(r) == 0 and x == 0: + # invalid result from mpmath, point x=0 is a divergence + return np.nan + return r + assert_mpmath_equal( + lambda v, z: sc.yn(int(v), z), + exception_to_nan(mpbessely), + [IntArg(-1000, 1000), Arg(-1e8, 1e8)], + ) + + def test_beta(self): + bad_points = [] + + def beta(a, b, nonzero=False): + if a < -1e12 or b < -1e12: + # Function is defined here only at integers, but due + # to loss of precision this is numerically + # ill-defined. Don't compare values here. + return np.nan + if (a < 0 or b < 0) and (abs(float(a + b)) % 1) == 0: + # close to a zero of the function: mpmath and scipy + # will not round here the same, so the test needs to be + # run with an absolute tolerance + if nonzero: + bad_points.append((float(a), float(b))) + return np.nan + return mpmath.beta(a, b) + + assert_mpmath_equal( + sc.beta, + lambda a, b: beta(a, b, nonzero=True), + [Arg(), Arg()], + dps=400, + ignore_inf_sign=True, + ) + + assert_mpmath_equal( + sc.beta, + beta, + np.array(bad_points), + dps=400, + ignore_inf_sign=True, + atol=1e-11, + ) + + def test_betainc(self): + assert_mpmath_equal( + sc.betainc, + time_limited()( + exception_to_nan( + lambda a, b, x: mpmath.betainc(a, b, 0, x, regularized=True) + ) + ), + [Arg(), Arg(), Arg()], + ) + + def test_betaincc(self): + assert_mpmath_equal( + sc.betaincc, + time_limited()( + exception_to_nan( + lambda a, b, x: mpmath.betainc(a, b, x, 1, regularized=True) + ) + ), + [Arg(), Arg(), Arg()], + dps=400, + ) + + def test_binom(self): + bad_points = [] + + def binomial(n, k, nonzero=False): + if abs(k) > 1e8*(abs(n) + 1): + # The binomial is rapidly oscillating in this region, + # and the function is numerically ill-defined. Don't + # compare values here. + return np.nan + if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15: + # close to a zero of the function: mpmath and scipy + # will not round here the same, so the test needs to be + # run with an absolute tolerance + if nonzero: + bad_points.append((float(n), float(k))) + return np.nan + return mpmath.binomial(n, k) + + assert_mpmath_equal( + sc.binom, + lambda n, k: binomial(n, k, nonzero=True), + [Arg(), Arg()], + dps=400, + ) + + assert_mpmath_equal( + sc.binom, + binomial, + np.array(bad_points), + dps=400, + atol=1e-14, + ) + + def test_chebyt_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_chebyt(int(n), x), + exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)), + [IntArg(), Arg()], + dps=50, + ) + + @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate") + def test_chebyt(self): + assert_mpmath_equal( + sc.eval_chebyt, + lambda n, x: time_limited()( + exception_to_nan(mpmath.chebyt) + )(n, x, **HYPERKW), + [Arg(-101, 101), Arg()], + n=10000, + ) + + def test_chebyu_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_chebyu(int(n), x), + exception_to_nan(lambda n, x: mpmath.chebyu(n, x, **HYPERKW)), + [IntArg(), Arg()], + dps=50, + ) + + @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate") + def test_chebyu(self): + assert_mpmath_equal( + sc.eval_chebyu, + lambda n, x: time_limited()( + exception_to_nan(mpmath.chebyu) + )(n, x, **HYPERKW), + [Arg(-101, 101), Arg()], + ) + + def test_chi(self): + def chi(x): + return sc.shichi(x)[1] + assert_mpmath_equal(chi, mpmath.chi, [Arg()]) + # check asymptotic series cross-over + assert_mpmath_equal(chi, mpmath.chi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])]) + + def test_chi_complex(self): + def chi(z): + return sc.shichi(z)[1] + # chi oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + chi, + mpmath.chi, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-12, + ) + + def test_ci(self): + def ci(x): + return sc.sici(x)[1] + # oscillating function: limit range + assert_mpmath_equal(ci, mpmath.ci, [Arg(-1e8, 1e8)]) + + def test_ci_complex(self): + def ci(z): + return sc.sici(z)[1] + # ci oscillates as Re[z] -> +- inf, so limit range + assert_mpmath_equal( + ci, + mpmath.ci, + [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))], + rtol=1e-8, + ) + + def test_cospi(self): + eps = np.finfo(float).eps + assert_mpmath_equal(_cospi, mpmath.cospi, [Arg()], nan_ok=False, rtol=2*eps) + + def test_cospi_complex(self): + assert_mpmath_equal( + _cospi, + mpmath.cospi, + [ComplexArg()], + nan_ok=False, + rtol=1e-13, + ) + + def test_digamma(self): + assert_mpmath_equal( + sc.digamma, + exception_to_nan(mpmath.digamma), + [Arg()], + rtol=1e-12, + dps=50, + ) + + def test_digamma_complex(self): + # Test on a cut plane because mpmath will hang. See + # test_digamma_negreal for tests on the negative real axis. + def param_filter(z): + return np.where((z.real < 0) & (np.abs(z.imag) < 1.12), False, True) + + assert_mpmath_equal( + sc.digamma, + exception_to_nan(mpmath.digamma), + [ComplexArg()], + rtol=1e-13, + dps=40, + param_filter=param_filter + ) + + def test_e1(self): + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + [Arg()], + rtol=1e-14, + ) + + def test_e1_complex(self): + # E_1 oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-11, + ) + + # Check cross-over region + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + (np.linspace(-50, 50, 171)[:, None] + + np.r_[0, np.logspace(-3, 2, 61), -np.logspace(-3, 2, 11)]*1j).ravel(), + rtol=1e-11, + ) + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + (np.linspace(-50, -35, 10000) + 0j), + rtol=1e-11, + ) + + def test_exprel(self): + assert_mpmath_equal( + sc.exprel, + lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'), + [Arg(a=-np.log(np.finfo(np.float64).max), + b=np.log(np.finfo(np.float64).max))], + ) + assert_mpmath_equal( + sc.exprel, + lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'), + np.array([1e-12, 1e-24, 0, 1e12, 1e24, np.inf]), + rtol=1e-11, + ) + assert_(np.isinf(sc.exprel(np.inf))) + assert_(sc.exprel(-np.inf) == 0) + + def test_expm1_complex(self): + # Oscillates as a function of Im[z], so limit range to avoid loss of precision + assert_mpmath_equal( + sc.expm1, + mpmath.expm1, + [ComplexArg(complex(-np.inf, -1e7), complex(np.inf, 1e7))], + ) + + def test_log1p_complex(self): + assert_mpmath_equal( + sc.log1p, + lambda x: mpmath.log(x+1), + [ComplexArg()], + dps=60, + ) + + def test_log1pmx(self): + assert_mpmath_equal( + _log1pmx, + lambda x: mpmath.log(x + 1) - x, + [Arg()], + dps=60, + rtol=1e-14, + ) + + def test_ei(self): + assert_mpmath_equal(sc.expi, mpmath.ei, [Arg()], rtol=1e-11) + + def test_ei_complex(self): + # Ei oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + sc.expi, + mpmath.ei, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-9, + ) + + def test_ellipe(self): + assert_mpmath_equal(sc.ellipe, mpmath.ellipe, [Arg(b=1.0)]) + + def test_ellipeinc(self): + assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(-1e3, 1e3), Arg(b=1.0)]) + + def test_ellipeinc_largephi(self): + assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(), Arg()]) + + def test_ellipf(self): + assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(-1e3, 1e3), Arg()]) + + def test_ellipf_largephi(self): + assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(), Arg()]) + + def test_ellipk(self): + assert_mpmath_equal(sc.ellipk, mpmath.ellipk, [Arg(b=1.0)]) + assert_mpmath_equal( + sc.ellipkm1, + lambda m: mpmath.ellipk(1 - m), + [Arg(a=0.0)], + dps=400, + ) + + def test_ellipkinc(self): + def ellipkinc(phi, m): + return mpmath.ellippi(0, phi, m) + assert_mpmath_equal( + sc.ellipkinc, + ellipkinc, + [Arg(-1e3, 1e3), Arg(b=1.0)], + ignore_inf_sign=True, + ) + + def test_ellipkinc_largephi(self): + def ellipkinc(phi, m): + return mpmath.ellippi(0, phi, m) + assert_mpmath_equal( + sc.ellipkinc, + ellipkinc, + [Arg(), Arg(b=1.0)], + ignore_inf_sign=True, + ) + + def test_ellipfun_sn(self): + def sn(u, m): + # mpmath doesn't get the zero at u = 0--fix that + if u == 0: + return 0 + else: + return mpmath.ellipfun("sn", u=u, m=m) + + # Oscillating function --- limit range of first argument; the + # loss of precision there is an expected numerical feature + # rather than an actual bug + assert_mpmath_equal( + lambda u, m: sc.ellipj(u, m)[0], + sn, + [Arg(-1e6, 1e6), Arg(a=0, b=1)], + rtol=1e-8, + ) + + def test_ellipfun_cn(self): + # see comment in ellipfun_sn + assert_mpmath_equal( + lambda u, m: sc.ellipj(u, m)[1], + lambda u, m: mpmath.ellipfun("cn", u=u, m=m), + [Arg(-1e6, 1e6), Arg(a=0, b=1)], + rtol=1e-8, + ) + + def test_ellipfun_dn(self): + # see comment in ellipfun_sn + assert_mpmath_equal( + lambda u, m: sc.ellipj(u, m)[2], + lambda u, m: mpmath.ellipfun("dn", u=u, m=m), + [Arg(-1e6, 1e6), Arg(a=0, b=1)], + rtol=1e-8, + ) + + def test_erf(self): + assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [Arg()]) + + def test_erf_complex(self): + assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [ComplexArg()], n=200) + + def test_erfc(self): + assert_mpmath_equal( + sc.erfc, + exception_to_nan(lambda z: mpmath.erfc(z)), + [Arg()], + rtol=1e-13, + ) + + def test_erfc_complex(self): + assert_mpmath_equal( + sc.erfc, + exception_to_nan(lambda z: mpmath.erfc(z)), + [ComplexArg()], + n=200, + ) + + def test_erfi(self): + assert_mpmath_equal(sc.erfi, mpmath.erfi, [Arg()], n=200) + + def test_erfi_complex(self): + assert_mpmath_equal(sc.erfi, mpmath.erfi, [ComplexArg()], n=200) + + def test_ndtr(self): + assert_mpmath_equal( + sc.ndtr, + exception_to_nan(lambda z: mpmath.ncdf(z)), + [Arg()], + n=200, + ) + + def test_ndtr_complex(self): + assert_mpmath_equal( + sc.ndtr, + lambda z: mpmath.erfc(-z/np.sqrt(2.))/2., + [ComplexArg(a=complex(-10000, -10000), b=complex(10000, 10000))], + n=400, + ) + + def test_log_ndtr(self): + assert_mpmath_equal( + sc.log_ndtr, + exception_to_nan(lambda z: mpmath.log(mpmath.ncdf(z))), + [Arg()], n=600, dps=300, rtol=1e-13, + ) + + def test_log_ndtr_complex(self): + assert_mpmath_equal( + sc.log_ndtr, + exception_to_nan(lambda z: mpmath.log(mpmath.erfc(-z/np.sqrt(2.))/2.)), + [ComplexArg(a=complex(-10000, -100), b=complex(10000, 100))], + n=200, dps=300, + ) + + def test_eulernum(self): + assert_mpmath_equal( + lambda n: sc.euler(n)[-1], + mpmath.eulernum, + [IntArg(1, 10000)], + n=10000, + ) + + def test_expint(self): + assert_mpmath_equal( + sc.expn, + mpmath.expint, + [IntArg(0, 200), Arg(0, np.inf)], + rtol=1e-13, + dps=160, + ) + + def test_fresnels(self): + def fresnels(x): + return sc.fresnel(x)[0] + assert_mpmath_equal(fresnels, mpmath.fresnels, [Arg()]) + + def test_fresnelc(self): + def fresnelc(x): + return sc.fresnel(x)[1] + assert_mpmath_equal(fresnelc, mpmath.fresnelc, [Arg()]) + + def test_gamma(self): + assert_mpmath_equal(sc.gamma, exception_to_nan(mpmath.gamma), [Arg()]) + + def test_gamma_complex(self): + assert_mpmath_equal( + sc.gamma, + exception_to_nan(mpmath.gamma), + [ComplexArg()], + rtol=5e-13, + ) + + def test_gammainc(self): + # Larger arguments are tested in test_data.py:test_local + assert_mpmath_equal( + sc.gammainc, + lambda z, b: mpmath.gammainc(z, b=b, regularized=True), + [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)], + nan_ok=False, + rtol=1e-11, + ) + + def test_gammaincc(self): + # Larger arguments are tested in test_data.py:test_local + assert_mpmath_equal( + sc.gammaincc, + lambda z, a: mpmath.gammainc(z, a=a, regularized=True), + [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)], + nan_ok=False, + rtol=1e-11, + ) + + def test_gammaln(self): + # The real part of loggamma is log(|gamma(z)|). + def f(z): + return mpmath.loggamma(z).real + + assert_mpmath_equal(sc.gammaln, exception_to_nan(f), [Arg()]) + + @pytest.mark.xfail(run=False) + def test_gegenbauer(self): + assert_mpmath_equal( + sc.eval_gegenbauer, + exception_to_nan(mpmath.gegenbauer), + [Arg(-1e3, 1e3), Arg(), Arg()], + ) + + def test_gegenbauer_int(self): + # Redefine functions to deal with numerical + mpmath issues + def gegenbauer(n, a, x): + # Avoid overflow at large `a` (mpmath would need an even larger + # dps to handle this correctly, so just skip this region) + if abs(a) > 1e100: + return np.nan + + # Deal with n=0, n=1 correctly; mpmath 0.17 doesn't do these + # always correctly + if n == 0: + r = 1.0 + elif n == 1: + r = 2*a*x + else: + r = mpmath.gegenbauer(n, a, x) + + # Mpmath 0.17 gives wrong results (spurious zero) in some cases, so + # compute the value by perturbing the result + if float(r) == 0 and a < -1 and float(a) == int(float(a)): + r = mpmath.gegenbauer(n, a + mpmath.mpf('1e-50'), x) + if abs(r) < mpmath.mpf('1e-50'): + r = mpmath.mpf('0.0') + + # Differing overflow thresholds in scipy vs. mpmath + if abs(r) > 1e270: + return np.inf + return r + + def sc_gegenbauer(n, a, x): + r = sc.eval_gegenbauer(int(n), a, x) + # Differing overflow thresholds in scipy vs. mpmath + if abs(r) > 1e270: + return np.inf + return r + assert_mpmath_equal( + sc_gegenbauer, + exception_to_nan(gegenbauer), + [IntArg(0, 100), Arg(-1e9, 1e9), Arg()], + n=40000, dps=100, ignore_inf_sign=True, rtol=1e-6, + ) + + # Check the small-x expansion + assert_mpmath_equal( + sc_gegenbauer, + exception_to_nan(gegenbauer), + [IntArg(0, 100), Arg(), FixedArg(np.logspace(-30, -4, 30))], + dps=100, ignore_inf_sign=True, + ) + + @pytest.mark.xfail(run=False) + def test_gegenbauer_complex(self): + assert_mpmath_equal( + lambda n, a, x: sc.eval_gegenbauer(int(n), a.real, x), + exception_to_nan(mpmath.gegenbauer), + [IntArg(0, 100), Arg(), ComplexArg()], + ) + + @nonfunctional_tooslow + def test_gegenbauer_complex_general(self): + assert_mpmath_equal( + lambda n, a, x: sc.eval_gegenbauer(n.real, a.real, x), + exception_to_nan(mpmath.gegenbauer), + [Arg(-1e3, 1e3), Arg(), ComplexArg()], + ) + + def test_hankel1(self): + assert_mpmath_equal( + sc.hankel1, + exception_to_nan(lambda v, x: mpmath.hankel1(v, x, **HYPERKW)), + [Arg(-1e20, 1e20), Arg()], + ) + + def test_hankel2(self): + assert_mpmath_equal( + sc.hankel2, + exception_to_nan(lambda v, x: mpmath.hankel2(v, x, **HYPERKW)), + [Arg(-1e20, 1e20), Arg()], + ) + + @pytest.mark.xfail(run=False, reason="issues at intermediately large orders") + def test_hermite(self): + assert_mpmath_equal( + lambda n, x: sc.eval_hermite(int(n), x), + exception_to_nan(mpmath.hermite), + [IntArg(0, 10000), Arg()], + ) + + # hurwitz: same as zeta + + def test_hyp0f1(self): + # mpmath reports no convergence unless maxterms is large enough + KW = dict(maxprec=400, maxterms=1500) + # n=500 (non-xslow default) fails for one bad point + assert_mpmath_equal( + sc.hyp0f1, + lambda a, x: mpmath.hyp0f1(a, x, **KW), + [Arg(-1e7, 1e7), Arg(0, 1e5)], + n=5000, + ) + # NB: The range of the second parameter ("z") is limited from below + # because of an overflow in the intermediate calculations. The way + # for fix it is to implement an asymptotic expansion for Bessel J + # (similar to what is implemented for Bessel I here). + + def test_hyp0f1_complex(self): + assert_mpmath_equal( + lambda a, z: sc.hyp0f1(a.real, z), + exception_to_nan(lambda a, x: mpmath.hyp0f1(a, x, **HYPERKW)), + [Arg(-10, 10), ComplexArg(complex(-120, -120), complex(120, 120))], + ) + # NB: The range of the first parameter ("v") are limited by an overflow + # in the intermediate calculations. Can be fixed by implementing an + # asymptotic expansion for Bessel functions for large order. + + def test_hyp1f1(self): + def mpmath_hyp1f1(a, b, x): + try: + return mpmath.hyp1f1(a, b, x) + except ZeroDivisionError: + return np.inf + + assert_mpmath_equal( + sc.hyp1f1, + mpmath_hyp1f1, + [Arg(-50, 50), Arg(1, 50, inclusive_a=False), Arg(-50, 50)], + n=500, + nan_ok=False, + ) + + @pytest.mark.xfail(run=False) + def test_hyp1f1_complex(self): + assert_mpmath_equal( + inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)), + exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)), + [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()], + n=2000, + ) + + @nonfunctional_tooslow + def test_hyp2f1_complex(self): + # SciPy's hyp2f1 seems to have performance and accuracy problems + assert_mpmath_equal( + lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x), + exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)), + [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()], + n=10, + ) + + @pytest.mark.xfail(run=False) + def test_hyperu(self): + assert_mpmath_equal( + sc.hyperu, + exception_to_nan(lambda a, b, x: mpmath.hyperu(a, b, x, **HYPERKW)), + [Arg(), Arg(), Arg()], + ) + + @pytest.mark.xfail_on_32bit("mpmath issue gh-342: " + "unsupported operand mpz, long for pow") + def test_igam_fac(self): + def mp_igam_fac(a, x): + return mpmath.power(x, a)*mpmath.exp(-x)/mpmath.gamma(a) + + assert_mpmath_equal( + _igam_fac, + mp_igam_fac, + [Arg(0, 1e14, inclusive_a=False), Arg(0, 1e14)], + rtol=1e-10, + dps=29, + ) + + def test_j0(self): + # The Bessel function at large arguments is j0(x) ~ cos(x + phi)/sqrt(x) + # and at large arguments the phase of the cosine loses precision. + # + # This is numerically expected behavior, so we compare only up to + # 1e8 = 1e15 * 1e-7 + assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e3, 1e3)]) + assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e8, 1e8)], rtol=1e-5) + + def test_j1(self): + # See comment in test_j0 + assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e3, 1e3)]) + assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e8, 1e8)], rtol=1e-5) + + @pytest.mark.xfail(run=False) + def test_jacobi(self): + assert_mpmath_equal( + sc.eval_jacobi, + exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)), + [Arg(), Arg(), Arg(), Arg()], + ) + assert_mpmath_equal( + lambda n, b, c, x: sc.eval_jacobi(int(n), b, c, x), + exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)), + [IntArg(), Arg(), Arg(), Arg()], + ) + + def test_jacobi_int(self): + # Redefine functions to deal with numerical + mpmath issues + def jacobi(n, a, b, x): + # Mpmath does not handle n=0 case always correctly + if n == 0: + return 1.0 + return mpmath.jacobi(n, a, b, x) + assert_mpmath_equal( + lambda n, a, b, x: sc.eval_jacobi(int(n), a, b, x), + lambda n, a, b, x: exception_to_nan(jacobi)(n, a, b, x, **HYPERKW), + [IntArg(), Arg(), Arg(), Arg()], + n=20000, + dps=50, + ) + + def test_kei(self): + def kei(x): + if x == 0: + # work around mpmath issue at x=0 + return -pi/4 + return exception_to_nan(mpmath.kei)(0, x, **HYPERKW) + assert_mpmath_equal(sc.kei, kei, [Arg(-1e30, 1e30)], n=1000) + + def test_ker(self): + assert_mpmath_equal( + sc.ker, + exception_to_nan(lambda x: mpmath.ker(0, x, **HYPERKW)), + [Arg(-1e30, 1e30)], + n=1000, + ) + + @nonfunctional_tooslow + def test_laguerre(self): + assert_mpmath_equal( + trace_args(sc.eval_laguerre), + lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW), + [Arg(), Arg()], + ) + + def test_laguerre_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_laguerre(int(n), x), + lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW), + [IntArg(), Arg()], + n=20000, + ) + + @pytest.mark.xfail_on_32bit("see gh-3551 for bad points") + def test_lambertw_real(self): + assert_mpmath_equal( + lambda x, k: sc.lambertw(x, int(k.real)), + lambda x, k: mpmath.lambertw(x, int(k.real)), + [ComplexArg(-np.inf, np.inf), IntArg(0, 10)], + rtol=1e-13, nan_ok=False, + ) + + def test_lanczos_sum_expg_scaled(self): + maxgamma = 171.624376956302725 + e = np.exp(1) + g = 6.024680040776729583740234375 + + def gamma(x): + with np.errstate(over='ignore'): + fac = ((x + g - 0.5)/e)**(x - 0.5) + if fac != np.inf: + res = fac*_lanczos_sum_expg_scaled(x) + else: + fac = ((x + g - 0.5)/e)**(0.5*(x - 0.5)) + res = fac*_lanczos_sum_expg_scaled(x) + res *= fac + return res + + assert_mpmath_equal( + gamma, + mpmath.gamma, + [Arg(0, maxgamma, inclusive_a=False)], + rtol=1e-13, + ) + + @nonfunctional_tooslow + def test_legendre(self): + assert_mpmath_equal(sc.eval_legendre, mpmath.legendre, [Arg(), Arg()]) + + def test_legendre_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_legendre(int(n), x), + lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW), + [IntArg(), Arg()], + n=20000, + ) + + # Check the small-x expansion + assert_mpmath_equal( + lambda n, x: sc.eval_legendre(int(n), x), + lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW), + [IntArg(), FixedArg(np.logspace(-30, -4, 20))], + ) + + def test_legenp(self): + def lpnm(n, m, z): + try: + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + v = sc.lpmn(m, n, z)[0][-1,-1] + except ValueError: + return np.nan + if abs(v) > 1e306: + # harmonize overflow to inf + v = np.inf * np.sign(v.real) + return v + + def lpnm_2(n, m, z): + v = sc.lpmv(m, n, z) + if abs(v) > 1e306: + # harmonize overflow to inf + v = np.inf * np.sign(v.real) + return v + + def legenp(n, m, z): + if (z == 1 or z == -1) and int(n) == n: + # Special case (mpmath may give inf, we take the limit by + # continuity) + if m == 0: + if n < 0: + n = -n - 1 + return mpmath.power(mpmath.sign(z), n) + else: + return 0 + + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + + typ = 2 if abs(z) <= 1 else 3 + v = exception_to_nan(mpmath.legenp)(n, m, z, type=typ) + + if abs(v) > 1e306: + # harmonize overflow to inf + v = mpmath.inf * mpmath.sign(v.real) + + return v + + assert_mpmath_equal(lpnm, legenp, [IntArg(-100, 100), IntArg(-100, 100), Arg()]) + + assert_mpmath_equal( + lpnm_2, + legenp, + [IntArg(-100, 100), Arg(-100, 100), Arg(-1, 1)], + atol=1e-10, + ) + + def test_legenp_complex_2(self): + def clpnm(n, m, z): + try: + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + return sc.clpmn(m.real, n.real, z, type=2)[0][-1,-1] + except ValueError: + return np.nan + + def legenp(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=2) + + # mpmath is quite slow here + x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3]) + y = np.array([-1e3, -0.5, 0.5, 1.3]) + z = (x[:,None] + 1j*y[None,:]).ravel() + + assert_mpmath_equal( + clpnm, + legenp, + [FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg(z)], + rtol=1e-6, + n=500, + ) + + def test_legenp_complex_3(self): + def clpnm(n, m, z): + try: + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + return sc.clpmn(m.real, n.real, z, type=3)[0][-1,-1] + except ValueError: + return np.nan + + def legenp(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=3) + + # mpmath is quite slow here + x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3]) + y = np.array([-1e3, -0.5, 0.5, 1.3]) + z = (x[:,None] + 1j*y[None,:]).ravel() + + assert_mpmath_equal( + clpnm, + legenp, + [FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg(z)], + rtol=1e-6, + n=500, + ) + + @pytest.mark.xfail(run=False, reason="apparently picks wrong function at |z| > 1") + def test_legenq(self): + def lqnm(n, m, z): + return sc.lqmn(m, n, z)[0][-1,-1] + + def legenq(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenq)(n, m, z, type=2) + + assert_mpmath_equal( + lqnm, + legenq, + [IntArg(0, 100), IntArg(0, 100), Arg()], + ) + + @nonfunctional_tooslow + def test_legenq_complex(self): + def lqnm(n, m, z): + return sc.lqmn(int(m.real), int(n.real), z)[0][-1,-1] + + def legenq(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenq)(int(n.real), int(m.real), z, type=2) + + assert_mpmath_equal( + lqnm, + legenq, + [IntArg(0, 100), IntArg(0, 100), ComplexArg()], + n=100, + ) + + def test_lgam1p(self): + def param_filter(x): + # Filter the poles + return np.where((np.floor(x) == x) & (x <= 0), False, True) + + def mp_lgam1p(z): + # The real part of loggamma is log(|gamma(z)|) + return mpmath.loggamma(1 + z).real + + assert_mpmath_equal( + _lgam1p, + mp_lgam1p, + [Arg()], + rtol=1e-13, + dps=100, + param_filter=param_filter, + ) + + def test_loggamma(self): + def mpmath_loggamma(z): + try: + res = mpmath.loggamma(z) + except ValueError: + res = complex(np.nan, np.nan) + return res + + assert_mpmath_equal( + sc.loggamma, + mpmath_loggamma, + [ComplexArg()], + nan_ok=False, + distinguish_nan_and_inf=False, + rtol=5e-14, + ) + + @pytest.mark.xfail(run=False) + def test_pcfd(self): + def pcfd(v, x): + return sc.pbdv(v, x)[0] + assert_mpmath_equal( + pcfd, + exception_to_nan(lambda v, x: mpmath.pcfd(v, x, **HYPERKW)), + [Arg(), Arg()], + ) + + @pytest.mark.xfail(run=False, reason="it's not the same as the mpmath function --- " + "maybe different definition?") + def test_pcfv(self): + def pcfv(v, x): + return sc.pbvv(v, x)[0] + assert_mpmath_equal( + pcfv, + lambda v, x: time_limited()(exception_to_nan(mpmath.pcfv))(v, x, **HYPERKW), + [Arg(), Arg()], + n=1000, + ) + + def test_pcfw(self): + def pcfw(a, x): + return sc.pbwa(a, x)[0] + + def dpcfw(a, x): + return sc.pbwa(a, x)[1] + + def mpmath_dpcfw(a, x): + return mpmath.diff(mpmath.pcfw, (a, x), (0, 1)) + + # The Zhang and Jin implementation only uses Taylor series and + # is thus accurate in only a very small range. + assert_mpmath_equal( + pcfw, + mpmath.pcfw, + [Arg(-5, 5), Arg(-5, 5)], + rtol=2e-8, + n=100, + ) + + assert_mpmath_equal( + dpcfw, + mpmath_dpcfw, + [Arg(-5, 5), Arg(-5, 5)], + rtol=2e-9, + n=100, + ) + + @pytest.mark.xfail(run=False, + reason="issues at large arguments (atol OK, rtol not) " + "and = _pep440.Version("1.0.0"): + # no workarounds needed + mppoch = mpmath.rf + else: + def mppoch(a, m): + # deal with cases where the result in double precision + # hits exactly a non-positive integer, but the + # corresponding extended-precision mpf floats don't + if float(a + m) == int(a + m) and float(a + m) <= 0: + a = mpmath.mpf(a) + m = int(a + m) - a + return mpmath.rf(a, m) + + assert_mpmath_equal(sc.poch, mppoch, [Arg(), Arg()], dps=400) + + def test_sinpi(self): + eps = np.finfo(float).eps + assert_mpmath_equal( + _sinpi, + mpmath.sinpi, + [Arg()], + nan_ok=False, + rtol=2*eps, + ) + + def test_sinpi_complex(self): + assert_mpmath_equal( + _sinpi, + mpmath.sinpi, + [ComplexArg()], + nan_ok=False, + rtol=2e-14, + ) + + def test_shi(self): + def shi(x): + return sc.shichi(x)[0] + assert_mpmath_equal(shi, mpmath.shi, [Arg()]) + # check asymptotic series cross-over + assert_mpmath_equal(shi, mpmath.shi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])]) + + def test_shi_complex(self): + def shi(z): + return sc.shichi(z)[0] + # shi oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + shi, + mpmath.shi, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-12, + ) + + def test_si(self): + def si(x): + return sc.sici(x)[0] + assert_mpmath_equal(si, mpmath.si, [Arg()]) + + def test_si_complex(self): + def si(z): + return sc.sici(z)[0] + # si oscillates as Re[z] -> +- inf, so limit range + assert_mpmath_equal( + si, + mpmath.si, + [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))], + rtol=1e-12, + ) + + def test_spence(self): + # mpmath uses a different convention for the dilogarithm + def dilog(x): + return mpmath.polylog(2, 1 - x) + # Spence has a branch cut on the negative real axis + assert_mpmath_equal( + sc.spence, + exception_to_nan(dilog), + [Arg(0, np.inf)], + rtol=1e-14, + ) + + def test_spence_complex(self): + def dilog(z): + return mpmath.polylog(2, 1 - z) + assert_mpmath_equal( + sc.spence, + exception_to_nan(dilog), + [ComplexArg()], + rtol=1e-14, + ) + + def test_spherharm(self): + def spherharm(l, m, theta, phi): + if m > l: + return np.nan + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + return sc.sph_harm(m, l, phi, theta) + assert_mpmath_equal( + spherharm, + mpmath.spherharm, + [IntArg(0, 100), IntArg(0, 100), Arg(a=0, b=pi), Arg(a=0, b=2*pi)], + atol=1e-8, + n=6000, + dps=150, + ) + + def test_struveh(self): + assert_mpmath_equal( + sc.struve, + exception_to_nan(mpmath.struveh), + [Arg(-1e4, 1e4), Arg(0, 1e4)], + rtol=5e-10, + ) + + def test_struvel(self): + def mp_struvel(v, z): + if v < 0 and z < -v and abs(v) > 1000: + # larger DPS needed for correct results + old_dps = mpmath.mp.dps + try: + mpmath.mp.dps = 500 + return mpmath.struvel(v, z) + finally: + mpmath.mp.dps = old_dps + return mpmath.struvel(v, z) + + assert_mpmath_equal( + sc.modstruve, + exception_to_nan(mp_struvel), + [Arg(-1e4, 1e4), Arg(0, 1e4)], + rtol=5e-10, + ignore_inf_sign=True, + ) + + def test_wrightomega_real(self): + def mpmath_wrightomega_real(x): + return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5')) + + # For x < -1000 the Wright Omega function is just 0 to double + # precision, and for x > 1e21 it is just x to double + # precision. + assert_mpmath_equal( + sc.wrightomega, + mpmath_wrightomega_real, + [Arg(-1000, 1e21)], + rtol=5e-15, + atol=0, + nan_ok=False, + ) + + def test_wrightomega(self): + assert_mpmath_equal( + sc.wrightomega, + lambda z: _mpmath_wrightomega(z, 25), + [ComplexArg()], + rtol=1e-14, + nan_ok=False, + ) + + def test_hurwitz_zeta(self): + assert_mpmath_equal( + sc.zeta, + exception_to_nan(mpmath.zeta), + [Arg(a=1, b=1e10, inclusive_a=False), Arg(a=0, inclusive_a=False)], + ) + + def test_riemann_zeta(self): + assert_mpmath_equal( + sc.zeta, + lambda x: mpmath.zeta(x) if x != 1 else mpmath.inf, + [Arg(-100, 100)], + nan_ok=False, + rtol=5e-13, + ) + + def test_zetac(self): + assert_mpmath_equal( + sc.zetac, + lambda x: mpmath.zeta(x) - 1 if x != 1 else mpmath.inf, + [Arg(-100, 100)], + nan_ok=False, + dps=45, + rtol=5e-13, + ) + + def test_boxcox(self): + + def mp_boxcox(x, lmbda): + x = mpmath.mp.mpf(x) + lmbda = mpmath.mp.mpf(lmbda) + if lmbda == 0: + return mpmath.mp.log(x) + else: + return mpmath.mp.powm1(x, lmbda) / lmbda + + assert_mpmath_equal( + sc.boxcox, + exception_to_nan(mp_boxcox), + [Arg(a=0, inclusive_a=False), Arg()], + n=200, + dps=60, + rtol=1e-13, + ) + + def test_boxcox1p(self): + + def mp_boxcox1p(x, lmbda): + x = mpmath.mp.mpf(x) + lmbda = mpmath.mp.mpf(lmbda) + one = mpmath.mp.mpf(1) + if lmbda == 0: + return mpmath.mp.log(one + x) + else: + return mpmath.mp.powm1(one + x, lmbda) / lmbda + + assert_mpmath_equal( + sc.boxcox1p, + exception_to_nan(mp_boxcox1p), + [Arg(a=-1, inclusive_a=False), Arg()], + n=200, + dps=60, + rtol=1e-13, + ) + + def test_spherical_jn(self): + def mp_spherical_jn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if arg.imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_jn(int(n), z), + exception_to_nan(mp_spherical_jn), + [IntArg(0, 200), Arg(-1e8, 1e8)], + dps=300, + # underflow of `spherical_jn` is a bit premature; see gh-21629 + param_filter=(None, lambda z: np.abs(z) > 1e-20), + ) + + def test_spherical_jn_complex(self): + def mp_spherical_jn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if arg.imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_jn(int(n.real), z), + exception_to_nan(mp_spherical_jn), + [IntArg(0, 200), ComplexArg()] + ) + + def test_spherical_yn(self): + def mp_spherical_yn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if arg.imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_yn(int(n), z), + exception_to_nan(mp_spherical_yn), + [IntArg(0, 200), Arg(-1e10, 1e10)], + dps=100, + ) + + def test_spherical_yn_complex(self): + def mp_spherical_yn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if arg.imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_yn(int(n.real), z), + exception_to_nan(mp_spherical_yn), + [IntArg(0, 200), ComplexArg()], + ) + + def test_spherical_in(self): + def mp_spherical_in(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if arg.imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_in(int(n), z), + exception_to_nan(mp_spherical_in), + [IntArg(0, 200), Arg()], + dps=200, + atol=10**(-278), + ) + + def test_spherical_in_complex(self): + def mp_spherical_in(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if arg.imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_in(int(n.real), z), + exception_to_nan(mp_spherical_in), + [IntArg(0, 200), ComplexArg()], + ) + + def test_spherical_kn(self): + def mp_spherical_kn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if mpmath.mpmathify(z).imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_kn(int(n), z), + exception_to_nan(mp_spherical_kn), + [IntArg(0, 150), Arg()], + dps=100, + ) + + @pytest.mark.xfail(run=False, + reason="Accuracy issues near z = -1 inherited from kv.") + def test_spherical_kn_complex(self): + def mp_spherical_kn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) / + mpmath.sqrt(2*arg/mpmath.pi)) + if arg.imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_kn(int(n.real), z), + exception_to_nan(mp_spherical_kn), + [IntArg(0, 200), ComplexArg()], + dps=200, + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3e574da056bc9ba7d472567caf992d6638c20a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py @@ -0,0 +1,65 @@ +"""Test how the ufuncs in special handle nan inputs. + +""" +from typing import Callable + +import numpy as np +from numpy.testing import assert_array_equal, assert_, suppress_warnings +import pytest +import scipy.special as sc + + +KNOWNFAILURES: dict[str, Callable] = {} + +POSTPROCESSING: dict[str, Callable] = {} + + +def _get_ufuncs(): + ufuncs = [] + ufunc_names = [] + for name in sorted(sc.__dict__): + obj = sc.__dict__[name] + if not isinstance(obj, np.ufunc): + continue + msg = KNOWNFAILURES.get(obj) + if msg is None: + ufuncs.append(obj) + ufunc_names.append(name) + else: + fail = pytest.mark.xfail(run=False, reason=msg) + ufuncs.append(pytest.param(obj, marks=fail)) + ufunc_names.append(name) + return ufuncs, ufunc_names + + +UFUNCS, UFUNC_NAMES = _get_ufuncs() + + +@pytest.mark.thread_unsafe +@pytest.mark.parametrize("func", UFUNCS, ids=UFUNC_NAMES) +def test_nan_inputs(func): + args = (np.nan,)*func.nin + with suppress_warnings() as sup: + # Ignore warnings about unsafe casts from legacy wrappers + sup.filter(RuntimeWarning, + "floating point number truncated to an integer") + try: + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + res = func(*args) + except TypeError: + # One of the arguments doesn't take real inputs + return + if func in POSTPROCESSING: + res = POSTPROCESSING[func](*res) + + msg = f"got {res} instead of nan" + assert_array_equal(np.isnan(res), True, err_msg=msg) + + +def test_legacy_cast(): + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, + "floating point number truncated to an integer") + res = sc.bdtrc(np.nan, 1, 0.5) + assert_(np.isnan(res)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9b689b34384585cc65204000febcb99c910d55 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py @@ -0,0 +1,77 @@ +import numpy as np +from numpy.testing import assert_equal, assert_allclose +import scipy.special as sc + + +def test_ndtr(): + assert_equal(sc.ndtr(0), 0.5) + assert_allclose(sc.ndtr(1), 0.8413447460685429) + + +class TestNdtri: + + def test_zero(self): + assert sc.ndtri(0.5) == 0.0 + + def test_asymptotes(self): + assert_equal(sc.ndtri([0.0, 1.0]), [-np.inf, np.inf]) + + def test_outside_of_domain(self): + assert all(np.isnan(sc.ndtri([-1.5, 1.5]))) + + +class TestLogNdtr: + + # The expected values in these tests were computed with mpmath: + # + # def log_ndtr_mp(x): + # return mpmath.log(mpmath.ncdf(x)) + # + + def test_log_ndtr_moderate_le8(self): + x = np.array([-0.75, -0.25, 0, 0.5, 1.5, 2.5, 3, 4, 5, 7, 8]) + expected = np.array([-1.4844482299196562, + -0.9130617648111351, + -0.6931471805599453, + -0.3689464152886564, + -0.06914345561223398, + -0.006229025485860002, + -0.0013508099647481938, + -3.167174337748927e-05, + -2.866516129637636e-07, + -1.279812543886654e-12, + -6.220960574271786e-16]) + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=1e-14) + + def test_log_ndtr_values_8_16(self): + x = np.array([8.001, 8.06, 8.15, 8.5, 10, 12, 14, 16]) + expected = [-6.170639424817055e-16, + -3.814722443652823e-16, + -1.819621363526629e-16, + -9.479534822203318e-18, + -7.619853024160525e-24, + -1.776482112077679e-33, + -7.7935368191928e-45, + -6.388754400538087e-58] + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=5e-14) + + def test_log_ndtr_values_16_31(self): + x = np.array([16.15, 20.3, 21.4, 26.2, 30.9]) + expected = [-5.678084565148492e-59, + -6.429244467698346e-92, + -6.680402412553295e-102, + -1.328698078458869e-151, + -5.972288641838264e-210] + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=2e-13) + + def test_log_ndtr_values_gt31(self): + x = np.array([31.6, 32.8, 34.9, 37.1]) + expected = [-1.846036234858162e-219, + -2.9440539964066835e-236, + -3.71721649450857e-267, + -1.4047119663106221e-301] + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=3e-13) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py new file mode 100644 index 0000000000000000000000000000000000000000..82a9fbd3bcda117770e00018facda3f56630a6bc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py @@ -0,0 +1,94 @@ +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose +from scipy.special import log_ndtr, ndtri_exp +from scipy.special._testutils import assert_func_equal + + +def log_ndtr_ndtri_exp(y): + return log_ndtr(ndtri_exp(y)) + + +@pytest.fixture(scope="class") +def uniform_random_points(): + random_state = np.random.RandomState(1234) + points = random_state.random_sample(1000) + return points + + +class TestNdtriExp: + """Tests that ndtri_exp is sufficiently close to an inverse of log_ndtr. + + We have separate tests for the five intervals (-inf, -10), + [-10, -2), [-2, -0.14542), [-0.14542, -1e-6), and [-1e-6, 0). + ndtri_exp(y) is computed in three different ways depending on if y + is in (-inf, -2), [-2, log(1 - exp(-2))], or [log(1 - exp(-2), 0). + Each of these intervals is given its own test with two additional tests + for handling very small values and values very close to zero. + """ + + @pytest.mark.parametrize( + "test_input", [-1e1, -1e2, -1e10, -1e20, -np.finfo(float).max] + ) + def test_very_small_arg(self, test_input, uniform_random_points): + scale = test_input + points = scale * (0.5 * uniform_random_points + 0.5) + assert_func_equal( + log_ndtr_ndtri_exp, + lambda y: y, points, + rtol=1e-14, + nan_ok=True + ) + + @pytest.mark.parametrize( + "interval,expected_rtol", + [ + ((-10, -2), 1e-14), + ((-2, -0.14542), 1e-12), + ((-0.14542, -1e-6), 1e-10), + ((-1e-6, 0), 1e-6), + ], + ) + def test_in_interval(self, interval, expected_rtol, uniform_random_points): + left, right = interval + points = (right - left) * uniform_random_points + left + assert_func_equal( + log_ndtr_ndtri_exp, + lambda y: y, points, + rtol=expected_rtol, + nan_ok=True + ) + + def test_extreme(self): + # bigneg is not quite the largest negative double precision value. + # Here's why: + # The round-trip calculation + # y = ndtri_exp(bigneg) + # bigneg2 = log_ndtr(y) + # where bigneg is a very large negative value, would--with infinite + # precision--result in bigneg2 == bigneg. When bigneg is large enough, + # y is effectively equal to -sqrt(2)*sqrt(-bigneg), and log_ndtr(y) is + # effectively -(y/sqrt(2))**2. If we use bigneg = np.finfo(float).min, + # then by construction, the theoretical value is the most negative + # finite value that can be represented with 64 bit float point. This + # means tiny changes in how the computation proceeds can result in the + # return value being -inf. (E.g. changing the constant representation + # of 1/sqrt(2) from 0.7071067811865475--which is the value returned by + # 1/np.sqrt(2)--to 0.7071067811865476--which is the most accurate 64 + # bit floating point representation of 1/sqrt(2)--results in the + # round-trip that starts with np.finfo(float).min returning -inf. So + # we'll move the bigneg value a few ULPs towards 0 to avoid this + # sensitivity. + # Use the reduce method to apply nextafter four times. + bigneg = np.nextafter.reduce([np.finfo(float).min, 0, 0, 0, 0]) + # tinyneg is approx. -2.225e-308. + tinyneg = -np.finfo(float).tiny + x = np.array([tinyneg, bigneg]) + result = log_ndtr_ndtri_exp(x) + assert_allclose(result, x, rtol=1e-12) + + def test_asymptotes(self): + assert_equal(ndtri_exp([-np.inf, 0.0]), [-np.inf, np.inf]) + + def test_outside_domain(self): + assert np.isnan(ndtri_exp(1.0)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py new file mode 100644 index 0000000000000000000000000000000000000000..47831c18ab6fa48925cae576f6c664767df99d05 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py @@ -0,0 +1,822 @@ +import pytest +from pytest import raises as assert_raises + +import numpy as np +from numpy import array, sqrt +from numpy.testing import (assert_array_almost_equal, assert_equal, + assert_almost_equal, assert_allclose) + +from scipy import integrate +import scipy.special as sc +from scipy.special import gamma +import scipy.special._orthogonal as orth + + +class TestCheby: + def test_chebyc(self): + C0 = orth.chebyc(0) + C1 = orth.chebyc(1) + with np.errstate(all='ignore'): + C2 = orth.chebyc(2) + C3 = orth.chebyc(3) + C4 = orth.chebyc(4) + C5 = orth.chebyc(5) + + assert_array_almost_equal(C0.c,[2],13) + assert_array_almost_equal(C1.c,[1,0],13) + assert_array_almost_equal(C2.c,[1,0,-2],13) + assert_array_almost_equal(C3.c,[1,0,-3,0],13) + assert_array_almost_equal(C4.c,[1,0,-4,0,2],13) + assert_array_almost_equal(C5.c,[1,0,-5,0,5,0],13) + + def test_chebys(self): + S0 = orth.chebys(0) + S1 = orth.chebys(1) + S2 = orth.chebys(2) + S3 = orth.chebys(3) + S4 = orth.chebys(4) + S5 = orth.chebys(5) + assert_array_almost_equal(S0.c,[1],13) + assert_array_almost_equal(S1.c,[1,0],13) + assert_array_almost_equal(S2.c,[1,0,-1],13) + assert_array_almost_equal(S3.c,[1,0,-2,0],13) + assert_array_almost_equal(S4.c,[1,0,-3,0,1],13) + assert_array_almost_equal(S5.c,[1,0,-4,0,3,0],13) + + def test_chebyt(self): + T0 = orth.chebyt(0) + T1 = orth.chebyt(1) + T2 = orth.chebyt(2) + T3 = orth.chebyt(3) + T4 = orth.chebyt(4) + T5 = orth.chebyt(5) + assert_array_almost_equal(T0.c,[1],13) + assert_array_almost_equal(T1.c,[1,0],13) + assert_array_almost_equal(T2.c,[2,0,-1],13) + assert_array_almost_equal(T3.c,[4,0,-3,0],13) + assert_array_almost_equal(T4.c,[8,0,-8,0,1],13) + assert_array_almost_equal(T5.c,[16,0,-20,0,5,0],13) + + def test_chebyu(self): + U0 = orth.chebyu(0) + U1 = orth.chebyu(1) + U2 = orth.chebyu(2) + U3 = orth.chebyu(3) + U4 = orth.chebyu(4) + U5 = orth.chebyu(5) + assert_array_almost_equal(U0.c,[1],13) + assert_array_almost_equal(U1.c,[2,0],13) + assert_array_almost_equal(U2.c,[4,0,-1],13) + assert_array_almost_equal(U3.c,[8,0,-4,0],13) + assert_array_almost_equal(U4.c,[16,0,-12,0,1],13) + assert_array_almost_equal(U5.c,[32,0,-32,0,6,0],13) + + +class TestGegenbauer: + + def test_gegenbauer(self): + a = 5*np.random.random() - 0.5 + if np.any(a == 0): + a = -0.2 + Ca0 = orth.gegenbauer(0,a) + Ca1 = orth.gegenbauer(1,a) + Ca2 = orth.gegenbauer(2,a) + Ca3 = orth.gegenbauer(3,a) + Ca4 = orth.gegenbauer(4,a) + Ca5 = orth.gegenbauer(5,a) + + assert_array_almost_equal(Ca0.c,array([1]),13) + assert_array_almost_equal(Ca1.c,array([2*a,0]),13) + assert_array_almost_equal(Ca2.c,array([2*a*(a+1),0,-a]),13) + assert_array_almost_equal(Ca3.c,array([4*sc.poch(a,3),0,-6*a*(a+1), + 0])/3.0,11) + assert_array_almost_equal(Ca4.c,array([4*sc.poch(a,4),0,-12*sc.poch(a,3), + 0,3*a*(a+1)])/6.0,11) + assert_array_almost_equal(Ca5.c,array([4*sc.poch(a,5),0,-20*sc.poch(a,4), + 0,15*sc.poch(a,3),0])/15.0,11) + + @pytest.mark.parametrize('a', [0, 1]) + def test_n_zero_gh8888(self, a): + # gh-8888 reported that gegenbauer(0, 0) returns NaN polynomial + Cn0 = orth.gegenbauer(0, a) + assert_equal(Cn0.c, np.asarray([1.])) + + def test_valid_alpha(self): + # Check input validation of `alpha` + message = '`alpha` must be a finite number greater...' + with pytest.raises(ValueError, match=message): + orth.gegenbauer(0, np.nan) + with pytest.raises(ValueError, match=message): + orth.gegenbauer(1, -0.5) + with pytest.raises(ValueError, match=message): + orth.gegenbauer(2, -np.inf) + + +class TestHermite: + def test_hermite(self): + H0 = orth.hermite(0) + H1 = orth.hermite(1) + H2 = orth.hermite(2) + H3 = orth.hermite(3) + H4 = orth.hermite(4) + H5 = orth.hermite(5) + assert_array_almost_equal(H0.c,[1],13) + assert_array_almost_equal(H1.c,[2,0],13) + assert_array_almost_equal(H2.c,[4,0,-2],13) + assert_array_almost_equal(H3.c,[8,0,-12,0],13) + assert_array_almost_equal(H4.c,[16,0,-48,0,12],12) + assert_array_almost_equal(H5.c,[32,0,-160,0,120,0],12) + + def test_hermitenorm(self): + # He_n(x) = 2**(-n/2) H_n(x/sqrt(2)) + psub = np.poly1d([1.0/sqrt(2),0]) + H0 = orth.hermitenorm(0) + H1 = orth.hermitenorm(1) + H2 = orth.hermitenorm(2) + H3 = orth.hermitenorm(3) + H4 = orth.hermitenorm(4) + H5 = orth.hermitenorm(5) + he0 = orth.hermite(0)(psub) + he1 = orth.hermite(1)(psub) / sqrt(2) + he2 = orth.hermite(2)(psub) / 2.0 + he3 = orth.hermite(3)(psub) / (2*sqrt(2)) + he4 = orth.hermite(4)(psub) / 4.0 + he5 = orth.hermite(5)(psub) / (4.0*sqrt(2)) + + assert_array_almost_equal(H0.c,he0.c,13) + assert_array_almost_equal(H1.c,he1.c,13) + assert_array_almost_equal(H2.c,he2.c,13) + assert_array_almost_equal(H3.c,he3.c,13) + assert_array_almost_equal(H4.c,he4.c,13) + assert_array_almost_equal(H5.c,he5.c,13) + + +class TestShLegendre: + def test_sh_legendre(self): + # P*_n(x) = P_n(2x-1) + psub = np.poly1d([2,-1]) + Ps0 = orth.sh_legendre(0) + Ps1 = orth.sh_legendre(1) + Ps2 = orth.sh_legendre(2) + Ps3 = orth.sh_legendre(3) + Ps4 = orth.sh_legendre(4) + Ps5 = orth.sh_legendre(5) + pse0 = orth.legendre(0)(psub) + pse1 = orth.legendre(1)(psub) + pse2 = orth.legendre(2)(psub) + pse3 = orth.legendre(3)(psub) + pse4 = orth.legendre(4)(psub) + pse5 = orth.legendre(5)(psub) + assert_array_almost_equal(Ps0.c,pse0.c,13) + assert_array_almost_equal(Ps1.c,pse1.c,13) + assert_array_almost_equal(Ps2.c,pse2.c,13) + assert_array_almost_equal(Ps3.c,pse3.c,13) + assert_array_almost_equal(Ps4.c,pse4.c,12) + assert_array_almost_equal(Ps5.c,pse5.c,12) + + +class TestShChebyt: + def test_sh_chebyt(self): + # T*_n(x) = T_n(2x-1) + psub = np.poly1d([2,-1]) + Ts0 = orth.sh_chebyt(0) + Ts1 = orth.sh_chebyt(1) + Ts2 = orth.sh_chebyt(2) + Ts3 = orth.sh_chebyt(3) + Ts4 = orth.sh_chebyt(4) + Ts5 = orth.sh_chebyt(5) + tse0 = orth.chebyt(0)(psub) + tse1 = orth.chebyt(1)(psub) + tse2 = orth.chebyt(2)(psub) + tse3 = orth.chebyt(3)(psub) + tse4 = orth.chebyt(4)(psub) + tse5 = orth.chebyt(5)(psub) + assert_array_almost_equal(Ts0.c,tse0.c,13) + assert_array_almost_equal(Ts1.c,tse1.c,13) + assert_array_almost_equal(Ts2.c,tse2.c,13) + assert_array_almost_equal(Ts3.c,tse3.c,13) + assert_array_almost_equal(Ts4.c,tse4.c,12) + assert_array_almost_equal(Ts5.c,tse5.c,12) + + +class TestShChebyu: + def test_sh_chebyu(self): + # U*_n(x) = U_n(2x-1) + psub = np.poly1d([2,-1]) + Us0 = orth.sh_chebyu(0) + Us1 = orth.sh_chebyu(1) + Us2 = orth.sh_chebyu(2) + Us3 = orth.sh_chebyu(3) + Us4 = orth.sh_chebyu(4) + Us5 = orth.sh_chebyu(5) + use0 = orth.chebyu(0)(psub) + use1 = orth.chebyu(1)(psub) + use2 = orth.chebyu(2)(psub) + use3 = orth.chebyu(3)(psub) + use4 = orth.chebyu(4)(psub) + use5 = orth.chebyu(5)(psub) + assert_array_almost_equal(Us0.c,use0.c,13) + assert_array_almost_equal(Us1.c,use1.c,13) + assert_array_almost_equal(Us2.c,use2.c,13) + assert_array_almost_equal(Us3.c,use3.c,13) + assert_array_almost_equal(Us4.c,use4.c,12) + assert_array_almost_equal(Us5.c,use5.c,11) + + +class TestShJacobi: + def test_sh_jacobi(self): + # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1) + def conv(n, p): + return gamma(n + 1) * gamma(n + p) / gamma(2 * n + p) + psub = np.poly1d([2,-1]) + q = 4 * np.random.random() + p = q-1 + 2*np.random.random() + # print("shifted jacobi p,q = ", p, q) + G0 = orth.sh_jacobi(0,p,q) + G1 = orth.sh_jacobi(1,p,q) + G2 = orth.sh_jacobi(2,p,q) + G3 = orth.sh_jacobi(3,p,q) + G4 = orth.sh_jacobi(4,p,q) + G5 = orth.sh_jacobi(5,p,q) + ge0 = orth.jacobi(0,p-q,q-1)(psub) * conv(0,p) + ge1 = orth.jacobi(1,p-q,q-1)(psub) * conv(1,p) + ge2 = orth.jacobi(2,p-q,q-1)(psub) * conv(2,p) + ge3 = orth.jacobi(3,p-q,q-1)(psub) * conv(3,p) + ge4 = orth.jacobi(4,p-q,q-1)(psub) * conv(4,p) + ge5 = orth.jacobi(5,p-q,q-1)(psub) * conv(5,p) + + assert_array_almost_equal(G0.c,ge0.c,13) + assert_array_almost_equal(G1.c,ge1.c,13) + assert_array_almost_equal(G2.c,ge2.c,13) + assert_array_almost_equal(G3.c,ge3.c,13) + assert_array_almost_equal(G4.c,ge4.c,13) + assert_array_almost_equal(G5.c,ge5.c,13) + + +class TestCall: + def test_call(self): + poly = [] + for n in range(5): + poly.extend([x.strip() for x in + (""" + orth.jacobi(%(n)d,0.3,0.9) + orth.sh_jacobi(%(n)d,0.3,0.9) + orth.genlaguerre(%(n)d,0.3) + orth.laguerre(%(n)d) + orth.hermite(%(n)d) + orth.hermitenorm(%(n)d) + orth.gegenbauer(%(n)d,0.3) + orth.chebyt(%(n)d) + orth.chebyu(%(n)d) + orth.chebyc(%(n)d) + orth.chebys(%(n)d) + orth.sh_chebyt(%(n)d) + orth.sh_chebyu(%(n)d) + orth.legendre(%(n)d) + orth.sh_legendre(%(n)d) + """ % dict(n=n)).split() + ]) + with np.errstate(all='ignore'): + for pstr in poly: + p = eval(pstr) + assert_almost_equal(p(0.315), np.poly1d(p.coef)(0.315), + err_msg=pstr) + + +class TestGenlaguerre: + def test_regression(self): + assert_equal(orth.genlaguerre(1, 1, monic=False)(0), 2.) + assert_equal(orth.genlaguerre(1, 1, monic=True)(0), -2.) + assert_equal(orth.genlaguerre(1, 1, monic=False), np.poly1d([-1, 2])) + assert_equal(orth.genlaguerre(1, 1, monic=True), np.poly1d([1, -2])) + + +def verify_gauss_quad(root_func, eval_func, weight_func, a, b, N, + rtol=1e-15, atol=5e-14): + # this test is copied from numpy's TestGauss in test_hermite.py + x, w, mu = root_func(N, True) + + n = np.arange(N, dtype=np.dtype("long")) + v = eval_func(n[:,np.newaxis], x) + vv = np.dot(v*w, v.T) + vd = 1 / np.sqrt(vv.diagonal()) + vv = vd[:, np.newaxis] * vv * vd + assert_allclose(vv, np.eye(N), rtol, atol) + + # check that the integral of 1 is correct + assert_allclose(w.sum(), mu, rtol, atol) + + # compare the results of integrating a function with quad. + def f(x): + return x ** 3 - 3 * x ** 2 + x - 2 + resI = integrate.quad(lambda x: f(x)*weight_func(x), a, b) + resG = np.vdot(f(x), w) + rtol = 1e-6 if 1e-6 < resI[1] else resI[1] * 10 + assert_allclose(resI[0], resG, rtol=rtol) + +def test_roots_jacobi(): + def rf(a, b): + return lambda n, mu: sc.roots_jacobi(n, a, b, mu) + def ef(a, b): + return lambda n, x: sc.eval_jacobi(n, a, b, x) + def wf(a, b): + return lambda x: (1 - x) ** a * (1 + x) ** b + + vgq = verify_gauss_quad + vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., 5) + vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., + 25, atol=1e-12) + vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., + 100, atol=1e-11) + + vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 5) + vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 25, atol=1.5e-13) + vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 100, atol=2e-12) + + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 5, atol=2e-13) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 25, atol=2e-13) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 100, atol=1e-12) + + vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 5) + vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 25, atol=1e-13) + vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 100, atol=3e-13) + + vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 5) + vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 25, + atol=1.1e-14) + vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., + 100, atol=1e-13) + + vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 5, atol=1e-13) + vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 25, atol=2e-13) + vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., + 100, atol=1e-11) + + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 5, atol=2e-13) + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 25, atol=1e-12) + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 100, atol=1e-11) + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 250, atol=1e-11) + + vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 5, + atol=1e-12) + vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 25, + atol=1e-11) + vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 100, + atol=1e-10) + + vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 5, + atol=1e-12) + vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 25, + atol=1e-11) + vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 100, + atol=1e-10) + + vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 5, + atol=1e-12) + vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 25, + atol=1e-11) + vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 100, + atol=1e-10) + + vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 5) + vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 25, + atol=1e-13) + vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 100, + atol=1e-13) + + # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x) + xj, wj = sc.roots_jacobi(6, 0.0, 0.0) + xl, wl = sc.roots_legendre(6) + assert_allclose(xj, xl, 1e-14, 1e-14) + assert_allclose(wj, wl, 1e-14, 1e-14) + + # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x) + xj, wj = sc.roots_jacobi(6, 4.0, 4.0) + xc, wc = sc.roots_gegenbauer(6, 4.5) + assert_allclose(xj, xc, 1e-14, 1e-14) + assert_allclose(wj, wc, 1e-14, 1e-14) + + x, w = sc.roots_jacobi(5, 2, 3, False) + y, v, m = sc.roots_jacobi(5, 2, 3, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(wf(2,3), -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_jacobi, 0, 1, 1) + assert_raises(ValueError, sc.roots_jacobi, 3.3, 1, 1) + assert_raises(ValueError, sc.roots_jacobi, 3, -2, 1) + assert_raises(ValueError, sc.roots_jacobi, 3, 1, -2) + assert_raises(ValueError, sc.roots_jacobi, 3, -2, -2) + +def test_roots_sh_jacobi(): + def rf(a, b): + return lambda n, mu: sc.roots_sh_jacobi(n, a, b, mu) + def ef(a, b): + return lambda n, x: sc.eval_sh_jacobi(n, a, b, x) + def wf(a, b): + return lambda x: (1.0 - x) ** (a - b) * x ** (b - 1.0) + + vgq = verify_gauss_quad + vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., 5) + vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., + 25, atol=1e-12) + vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., + 100, atol=1e-11) + + vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 5) + vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 25, atol=1e-13) + vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 100, atol=1e-12) + + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 5) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 25, atol=1.5e-13) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 100, atol=2e-12) + + vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 5) + vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 25, atol=1e-13) + vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 100, atol=1e-12) + + vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 5) + vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 25) + vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., + 100, atol=1e-13) + + vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 5, atol=1e-12) + vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 25, atol=1e-11) + vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 100, atol=1e-10) + + vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 5, atol=3.5e-14) + vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 25, atol=2e-13) + vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., + 100, atol=1e-12) + + x, w = sc.roots_sh_jacobi(5, 3, 2, False) + y, v, m = sc.roots_sh_jacobi(5, 3, 2, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(wf(3,2), 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_jacobi, 0, 1, 1) + assert_raises(ValueError, sc.roots_sh_jacobi, 3.3, 1, 1) + assert_raises(ValueError, sc.roots_sh_jacobi, 3, 1, 2) # p - q <= -1 + assert_raises(ValueError, sc.roots_sh_jacobi, 3, 2, -1) # q <= 0 + assert_raises(ValueError, sc.roots_sh_jacobi, 3, -2, -1) # both + +def test_roots_hermite(): + rootf = sc.roots_hermite + evalf = sc.eval_hermite + weightf = orth.hermite(5).weight_func + + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12) + + # Golub-Welsch branch + x, w = sc.roots_hermite(5, False) + y, v, m = sc.roots_hermite(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -np.inf, np.inf) + assert_allclose(m, muI, rtol=muI_err) + + # Asymptotic branch (switch over at n >= 150) + x, w = sc.roots_hermite(200, False) + y, v, m = sc.roots_hermite(200, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + assert_allclose(sum(v), m, 1e-14, 1e-14) + + assert_raises(ValueError, sc.roots_hermite, 0) + assert_raises(ValueError, sc.roots_hermite, 3.3) + +def test_roots_hermite_asy(): + # Recursion for Hermite functions + def hermite_recursion(n, nodes): + H = np.zeros((n, nodes.size)) + H[0,:] = np.pi**(-0.25) * np.exp(-0.5*nodes**2) + if n > 1: + H[1,:] = sqrt(2.0) * nodes * H[0,:] + for k in range(2, n): + H[k,:] = sqrt(2.0/k) * nodes * H[k-1,:] - sqrt((k-1.0)/k) * H[k-2,:] + return H + + # This tests only the nodes + def test(N, rtol=1e-15, atol=1e-14): + x, w = orth._roots_hermite_asy(N) + H = hermite_recursion(N+1, x) + assert_allclose(H[-1,:], np.zeros(N), rtol, atol) + assert_allclose(sum(w), sqrt(np.pi), rtol, atol) + + test(150, atol=1e-12) + test(151, atol=1e-12) + test(300, atol=1e-12) + test(301, atol=1e-12) + test(500, atol=1e-12) + test(501, atol=1e-12) + test(999, atol=1e-12) + test(1000, atol=1e-12) + test(2000, atol=1e-12) + test(5000, atol=1e-12) + +def test_roots_hermitenorm(): + rootf = sc.roots_hermitenorm + evalf = sc.eval_hermitenorm + weightf = orth.hermitenorm(5).weight_func + + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12) + + x, w = sc.roots_hermitenorm(5, False) + y, v, m = sc.roots_hermitenorm(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -np.inf, np.inf) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_hermitenorm, 0) + assert_raises(ValueError, sc.roots_hermitenorm, 3.3) + +def test_roots_gegenbauer(): + def rootf(a): + return lambda n, mu: sc.roots_gegenbauer(n, a, mu) + def evalf(a): + return lambda n, x: sc.eval_gegenbauer(n, a, x) + def weightf(a): + return lambda x: (1 - x ** 2) ** (a - 0.5) + + vgq = verify_gauss_quad + vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 5) + vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 25, atol=1e-12) + vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 100, atol=1e-11) + + vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 5) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 25, atol=1e-13) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 100, atol=1e-12) + + vgq(rootf(1), evalf(1), weightf(1), -1., 1., 5) + vgq(rootf(1), evalf(1), weightf(1), -1., 1., 25, atol=1e-13) + vgq(rootf(1), evalf(1), weightf(1), -1., 1., 100, atol=1e-12) + + vgq(rootf(10), evalf(10), weightf(10), -1., 1., 5) + vgq(rootf(10), evalf(10), weightf(10), -1., 1., 25, atol=1e-13) + vgq(rootf(10), evalf(10), weightf(10), -1., 1., 100, atol=1e-12) + + vgq(rootf(50), evalf(50), weightf(50), -1., 1., 5, atol=1e-13) + vgq(rootf(50), evalf(50), weightf(50), -1., 1., 25, atol=1e-12) + vgq(rootf(50), evalf(50), weightf(50), -1., 1., 100, atol=1e-11) + + # Alpha=170 is where the approximation used in roots_gegenbauer changes + vgq(rootf(170), evalf(170), weightf(170), -1., 1., 5, atol=1e-13) + vgq(rootf(170), evalf(170), weightf(170), -1., 1., 25, atol=1e-12) + vgq(rootf(170), evalf(170), weightf(170), -1., 1., 100, atol=1e-11) + vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 5, atol=1.25e-13) + vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 25, atol=1e-12) + vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 100, atol=1e-11) + + # Test for failures, e.g. overflows, resulting from large alphas + vgq(rootf(238), evalf(238), weightf(238), -1., 1., 5, atol=1e-13) + vgq(rootf(238), evalf(238), weightf(238), -1., 1., 25, atol=1e-12) + vgq(rootf(238), evalf(238), weightf(238), -1., 1., 100, atol=1e-11) + vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 5, atol=1e-12) + vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 25, atol=1e-11) + vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 100, atol=1e-10) + + # this is a special case that the old code supported. + # when alpha = 0, the gegenbauer polynomial is uniformly 0. but it goes + # to a scaled down copy of T_n(x) there. + vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 5) + vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 25) + vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 100, atol=1e-12) + + x, w = sc.roots_gegenbauer(5, 2, False) + y, v, m = sc.roots_gegenbauer(5, 2, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf(2), -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_gegenbauer, 0, 2) + assert_raises(ValueError, sc.roots_gegenbauer, 3.3, 2) + assert_raises(ValueError, sc.roots_gegenbauer, 3, -.75) + +def test_roots_chebyt(): + weightf = orth.chebyt(5).weight_func + verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 5) + verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 25) + verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 100, + atol=1e-12) + + x, w = sc.roots_chebyt(5, False) + y, v, m = sc.roots_chebyt(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebyt, 0) + assert_raises(ValueError, sc.roots_chebyt, 3.3) + +def test_chebyt_symmetry(): + x, w = sc.roots_chebyt(21) + pos, neg = x[:10], x[11:] + assert_equal(neg, -pos[::-1]) + assert_equal(x[10], 0) + +def test_roots_chebyu(): + weightf = orth.chebyu(5).weight_func + verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 5) + verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 25) + verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 100) + + x, w = sc.roots_chebyu(5, False) + y, v, m = sc.roots_chebyu(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebyu, 0) + assert_raises(ValueError, sc.roots_chebyu, 3.3) + +def test_roots_chebyc(): + weightf = orth.chebyc(5).weight_func + verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 5) + verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 25) + verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 100, + atol=1e-12) + + x, w = sc.roots_chebyc(5, False) + y, v, m = sc.roots_chebyc(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -2, 2) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebyc, 0) + assert_raises(ValueError, sc.roots_chebyc, 3.3) + +def test_roots_chebys(): + weightf = orth.chebys(5).weight_func + verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 5) + verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 25) + verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 100) + + x, w = sc.roots_chebys(5, False) + y, v, m = sc.roots_chebys(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -2, 2) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebys, 0) + assert_raises(ValueError, sc.roots_chebys, 3.3) + +def test_roots_sh_chebyt(): + weightf = orth.sh_chebyt(5).weight_func + verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 5) + verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 25) + verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., + 100, atol=1e-13) + + x, w = sc.roots_sh_chebyt(5, False) + y, v, m = sc.roots_sh_chebyt(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_chebyt, 0) + assert_raises(ValueError, sc.roots_sh_chebyt, 3.3) + +def test_roots_sh_chebyu(): + weightf = orth.sh_chebyu(5).weight_func + verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 5) + verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 25) + verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., + 100, atol=1e-13) + + x, w = sc.roots_sh_chebyu(5, False) + y, v, m = sc.roots_sh_chebyu(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_chebyu, 0) + assert_raises(ValueError, sc.roots_sh_chebyu, 3.3) + +def test_roots_legendre(): + weightf = orth.legendre(5).weight_func + verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., 5) + verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., + 25, atol=1e-13) + verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., + 100, atol=1e-12) + + x, w = sc.roots_legendre(5, False) + y, v, m = sc.roots_legendre(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_legendre, 0) + assert_raises(ValueError, sc.roots_legendre, 3.3) + +def test_roots_sh_legendre(): + weightf = orth.sh_legendre(5).weight_func + verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., 5) + verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., + 25, atol=1e-13) + verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., + 100, atol=1e-12) + + x, w = sc.roots_sh_legendre(5, False) + y, v, m = sc.roots_sh_legendre(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_legendre, 0) + assert_raises(ValueError, sc.roots_sh_legendre, 3.3) + +def test_roots_laguerre(): + weightf = orth.laguerre(5).weight_func + verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, 5) + verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, + 25, atol=1e-13) + verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, + 100, atol=1e-12) + + x, w = sc.roots_laguerre(5, False) + y, v, m = sc.roots_laguerre(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, np.inf) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_laguerre, 0) + assert_raises(ValueError, sc.roots_laguerre, 3.3) + +def test_roots_genlaguerre(): + def rootf(a): + return lambda n, mu: sc.roots_genlaguerre(n, a, mu) + def evalf(a): + return lambda n, x: sc.eval_genlaguerre(n, a, x) + def weightf(a): + return lambda x: x ** a * np.exp(-x) + + vgq = verify_gauss_quad + vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 5) + vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 25, atol=1e-13) + vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 100, atol=1e-12) + + vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 5) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 25, atol=1e-13) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 100, atol=1.6e-13) + + vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 5) + vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 25, atol=1e-13) + vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 100, atol=1.03e-13) + + vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 5) + vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 25, atol=1e-13) + vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 100, atol=1e-12) + + vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 5) + vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 25, atol=1e-13) + vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 100, rtol=1e-14, atol=2e-13) + + x, w = sc.roots_genlaguerre(5, 2, False) + y, v, m = sc.roots_genlaguerre(5, 2, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf(2.), 0., np.inf) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_genlaguerre, 0, 2) + assert_raises(ValueError, sc.roots_genlaguerre, 3.3, 2) + assert_raises(ValueError, sc.roots_genlaguerre, 3, -1.1) + + +def test_gh_6721(): + # Regression test for gh_6721. This should not raise. + sc.chebyt(65)(0.2) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..8a4f379effdc9c3aa18bd2948fbd9f716b1f8d57 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py @@ -0,0 +1,275 @@ +import numpy as np +from numpy.testing import assert_, assert_allclose +import pytest + +from scipy.special import _ufuncs +import scipy.special._orthogonal as orth +from scipy.special._testutils import FuncData + + +def test_eval_chebyt(): + n = np.arange(0, 10000, 7, dtype=np.dtype("long")) + x = 2*np.random.rand() - 1 + v1 = np.cos(n*np.arccos(x)) + v2 = _ufuncs.eval_chebyt(n, x) + assert_(np.allclose(v1, v2, rtol=1e-15)) + + +def test_eval_chebyt_gh20129(): + # https://github.com/scipy/scipy/issues/20129 + assert _ufuncs.eval_chebyt(7, 2 + 0j) == 5042.0 + + +def test_eval_genlaguerre_restriction(): + # check it returns nan for alpha <= -1 + assert_(np.isnan(_ufuncs.eval_genlaguerre(0, -1, 0))) + assert_(np.isnan(_ufuncs.eval_genlaguerre(0.1, -1, 0))) + + +def test_warnings(): + # ticket 1334 + with np.errstate(all='raise'): + # these should raise no fp warnings + _ufuncs.eval_legendre(1, 0) + _ufuncs.eval_laguerre(1, 1) + _ufuncs.eval_gegenbauer(1, 1, 0) + + +class TestPolys: + """ + Check that the eval_* functions agree with the constructed polynomials + + """ + + def check_poly(self, func, cls, param_ranges=(), x_range=(), nn=10, + nparam=10, nx=10, rtol=1e-8): + rng = np.random.RandomState(1234) + + dataset = [] + for n in np.arange(nn): + params = [a + (b-a)*rng.rand(nparam) for a,b in param_ranges] + params = np.asarray(params).T + if not param_ranges: + params = [0] + for p in params: + if param_ranges: + p = (n,) + tuple(p) + else: + p = (n,) + x = x_range[0] + (x_range[1] - x_range[0])*rng.rand(nx) + x[0] = x_range[0] # always include domain start point + x[1] = x_range[1] # always include domain end point + poly = np.poly1d(cls(*p).coef) + z = np.c_[np.tile(p, (nx,1)), x, poly(x)] + dataset.append(z) + + dataset = np.concatenate(dataset, axis=0) + + def polyfunc(*p): + p = (p[0].astype(np.dtype("long")),) + p[1:] + return func(*p) + + with np.errstate(all='raise'): + ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1, + rtol=rtol) + ds.check() + + def test_jacobi(self): + self.check_poly(_ufuncs.eval_jacobi, orth.jacobi, + param_ranges=[(-0.99, 10), (-0.99, 10)], + x_range=[-1, 1], rtol=1e-5) + + def test_sh_jacobi(self): + self.check_poly(_ufuncs.eval_sh_jacobi, orth.sh_jacobi, + param_ranges=[(1, 10), (0, 1)], x_range=[0, 1], + rtol=1e-5) + + def test_gegenbauer(self): + self.check_poly(_ufuncs.eval_gegenbauer, orth.gegenbauer, + param_ranges=[(-0.499, 10)], x_range=[-1, 1], + rtol=1e-7) + + def test_chebyt(self): + self.check_poly(_ufuncs.eval_chebyt, orth.chebyt, + param_ranges=[], x_range=[-1, 1]) + + def test_chebyu(self): + self.check_poly(_ufuncs.eval_chebyu, orth.chebyu, + param_ranges=[], x_range=[-1, 1]) + + def test_chebys(self): + self.check_poly(_ufuncs.eval_chebys, orth.chebys, + param_ranges=[], x_range=[-2, 2]) + + def test_chebyc(self): + self.check_poly(_ufuncs.eval_chebyc, orth.chebyc, + param_ranges=[], x_range=[-2, 2]) + + def test_sh_chebyt(self): + with np.errstate(all='ignore'): + self.check_poly(_ufuncs.eval_sh_chebyt, orth.sh_chebyt, + param_ranges=[], x_range=[0, 1]) + + def test_sh_chebyu(self): + self.check_poly(_ufuncs.eval_sh_chebyu, orth.sh_chebyu, + param_ranges=[], x_range=[0, 1]) + + def test_legendre(self): + self.check_poly(_ufuncs.eval_legendre, orth.legendre, + param_ranges=[], x_range=[-1, 1]) + + def test_sh_legendre(self): + with np.errstate(all='ignore'): + self.check_poly(_ufuncs.eval_sh_legendre, orth.sh_legendre, + param_ranges=[], x_range=[0, 1]) + + def test_genlaguerre(self): + self.check_poly(_ufuncs.eval_genlaguerre, orth.genlaguerre, + param_ranges=[(-0.99, 10)], x_range=[0, 100]) + + def test_laguerre(self): + self.check_poly(_ufuncs.eval_laguerre, orth.laguerre, + param_ranges=[], x_range=[0, 100]) + + def test_hermite(self): + self.check_poly(_ufuncs.eval_hermite, orth.hermite, + param_ranges=[], x_range=[-100, 100]) + + def test_hermitenorm(self): + self.check_poly(_ufuncs.eval_hermitenorm, orth.hermitenorm, + param_ranges=[], x_range=[-100, 100]) + + +class TestRecurrence: + """ + Check that the eval_* functions sig='ld->d' and 'dd->d' agree. + + """ + + def check_poly(self, func, param_ranges=(), x_range=(), nn=10, + nparam=10, nx=10, rtol=1e-8): + np.random.seed(1234) + + dataset = [] + for n in np.arange(nn): + params = [a + (b-a)*np.random.rand(nparam) for a,b in param_ranges] + params = np.asarray(params).T + if not param_ranges: + params = [0] + for p in params: + if param_ranges: + p = (n,) + tuple(p) + else: + p = (n,) + x = x_range[0] + (x_range[1] - x_range[0])*np.random.rand(nx) + x[0] = x_range[0] # always include domain start point + x[1] = x_range[1] # always include domain end point + kw = dict(sig=(len(p)+1)*'d'+'->d') + z = np.c_[np.tile(p, (nx,1)), x, func(*(p + (x,)), **kw)] + dataset.append(z) + + dataset = np.concatenate(dataset, axis=0) + + def polyfunc(*p): + p0 = p[0].astype(np.intp) + p = (p0,) + p[1:] + p0_type_char = p0.dtype.char + kw = dict(sig=p0_type_char + (len(p)-1)*'d' + '->d') + return func(*p, **kw) + + with np.errstate(all='raise'): + ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1, + rtol=rtol) + ds.check() + + def test_jacobi(self): + self.check_poly(_ufuncs.eval_jacobi, + param_ranges=[(-0.99, 10), (-0.99, 10)], + x_range=[-1, 1]) + + def test_sh_jacobi(self): + self.check_poly(_ufuncs.eval_sh_jacobi, + param_ranges=[(1, 10), (0, 1)], x_range=[0, 1]) + + def test_gegenbauer(self): + self.check_poly(_ufuncs.eval_gegenbauer, + param_ranges=[(-0.499, 10)], x_range=[-1, 1]) + + def test_chebyt(self): + self.check_poly(_ufuncs.eval_chebyt, + param_ranges=[], x_range=[-1, 1]) + + def test_chebyu(self): + self.check_poly(_ufuncs.eval_chebyu, + param_ranges=[], x_range=[-1, 1]) + + def test_chebys(self): + self.check_poly(_ufuncs.eval_chebys, + param_ranges=[], x_range=[-2, 2]) + + def test_chebyc(self): + self.check_poly(_ufuncs.eval_chebyc, + param_ranges=[], x_range=[-2, 2]) + + def test_sh_chebyt(self): + self.check_poly(_ufuncs.eval_sh_chebyt, + param_ranges=[], x_range=[0, 1]) + + def test_sh_chebyu(self): + self.check_poly(_ufuncs.eval_sh_chebyu, + param_ranges=[], x_range=[0, 1]) + + def test_legendre(self): + self.check_poly(_ufuncs.eval_legendre, + param_ranges=[], x_range=[-1, 1]) + + def test_sh_legendre(self): + self.check_poly(_ufuncs.eval_sh_legendre, + param_ranges=[], x_range=[0, 1]) + + def test_genlaguerre(self): + self.check_poly(_ufuncs.eval_genlaguerre, + param_ranges=[(-0.99, 10)], x_range=[0, 100]) + + def test_laguerre(self): + self.check_poly(_ufuncs.eval_laguerre, + param_ranges=[], x_range=[0, 100]) + + def test_hermite(self): + v = _ufuncs.eval_hermite(70, 1.0) + a = -1.457076485701412e60 + assert_allclose(v, a) + + +def test_hermite_domain(): + # Regression test for gh-11091. + assert np.isnan(_ufuncs.eval_hermite(-1, 1.0)) + assert np.isnan(_ufuncs.eval_hermitenorm(-1, 1.0)) + + +@pytest.mark.parametrize("n", [0, 1, 2]) +@pytest.mark.parametrize("x", [0, 1, np.nan]) +def test_hermite_nan(n, x): + # Regression test for gh-11369. + assert np.isnan(_ufuncs.eval_hermite(n, x)) == np.any(np.isnan([n, x])) + assert np.isnan(_ufuncs.eval_hermitenorm(n, x)) == np.any(np.isnan([n, x])) + + +@pytest.mark.parametrize('n', [0, 1, 2, 3.2]) +@pytest.mark.parametrize('alpha', [1, np.nan]) +@pytest.mark.parametrize('x', [2, np.nan]) +def test_genlaguerre_nan(n, alpha, x): + # Regression test for gh-11361. + nan_laguerre = np.isnan(_ufuncs.eval_genlaguerre(n, alpha, x)) + nan_arg = np.any(np.isnan([n, alpha, x])) + assert nan_laguerre == nan_arg + + +@pytest.mark.parametrize('n', [0, 1, 2, 3.2]) +@pytest.mark.parametrize('alpha', [0.0, 1, np.nan]) +@pytest.mark.parametrize('x', [1e-6, 2, np.nan]) +def test_gegenbauer_nan(n, alpha, x): + # Regression test for gh-11370. + nan_gegenbauer = np.isnan(_ufuncs.eval_gegenbauer(n, alpha, x)) + nan_arg = np.any(np.isnan([n, alpha, x])) + assert nan_gegenbauer == nan_arg diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py new file mode 100644 index 0000000000000000000000000000000000000000..8d15aead25302023c5f07d8392c0931995764ced --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py @@ -0,0 +1,53 @@ +import numpy as np +from numpy.testing import assert_equal, assert_allclose + +import scipy.special as sc + + +def test_symmetries(): + np.random.seed(1234) + a, h = np.random.rand(100), np.random.rand(100) + assert_equal(sc.owens_t(h, a), sc.owens_t(-h, a)) + assert_equal(sc.owens_t(h, a), -sc.owens_t(h, -a)) + + +def test_special_cases(): + assert_equal(sc.owens_t(5, 0), 0) + assert_allclose(sc.owens_t(0, 5), 0.5*np.arctan(5)/np.pi, + rtol=5e-14) + # Target value is 0.5*Phi(5)*(1 - Phi(5)) for Phi the CDF of the + # standard normal distribution + assert_allclose(sc.owens_t(5, 1), 1.4332574485503512543e-07, + rtol=5e-14) + + +def test_nans(): + assert_equal(sc.owens_t(20, np.nan), np.nan) + assert_equal(sc.owens_t(np.nan, 20), np.nan) + assert_equal(sc.owens_t(np.nan, np.nan), np.nan) + + +def test_infs(): + h, a = 0, np.inf + # T(0, a) = 1/2π * arctan(a) + res = 1/(2*np.pi) * np.arctan(a) + assert_allclose(sc.owens_t(h, a), res, rtol=5e-14) + assert_allclose(sc.owens_t(h, -a), -res, rtol=5e-14) + + h = 1 + # Refer Owens T function definition in Wikipedia + # https://en.wikipedia.org/wiki/Owen%27s_T_function + # Value approximated through Numerical Integration + # using scipy.integrate.quad + # quad(lambda x: 1/(2*pi)*(exp(-0.5*(1*1)*(1+x*x))/(1+x*x)), 0, inf) + res = 0.07932762696572854 + assert_allclose(sc.owens_t(h, np.inf), res, rtol=5e-14) + assert_allclose(sc.owens_t(h, -np.inf), -res, rtol=5e-14) + + assert_equal(sc.owens_t(np.inf, 1), 0) + assert_equal(sc.owens_t(-np.inf, 1), 0) + + assert_equal(sc.owens_t(np.inf, np.inf), 0) + assert_equal(sc.owens_t(-np.inf, np.inf), 0) + assert_equal(sc.owens_t(np.inf, -np.inf), -0.0) + assert_equal(sc.owens_t(-np.inf, -np.inf), -0.0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c42aa688081fb58f79ad2c8ea932d03b33523b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py @@ -0,0 +1,24 @@ +"""Tests for parabolic cylinder functions. + +""" +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import scipy.special as sc + + +def test_pbwa_segfault(): + # Regression test for https://github.com/scipy/scipy/issues/6208. + # + # Data generated by mpmath. + # + w = 1.02276567211316867161 + wp = -0.48887053372346189882 + assert_allclose(sc.pbwa(0, 0), (w, wp), rtol=1e-13, atol=0) + + +def test_pbwa_nan(): + # Check that NaN's are returned outside of the range in which the + # implementation is accurate. + pts = [(-6, -6), (-6, 6), (6, -6), (6, 6)] + for p in pts: + assert_equal(sc.pbwa(*p), (np.nan, np.nan)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py new file mode 100644 index 0000000000000000000000000000000000000000..122e6009bd71e77ae39f55da5cf056500ff526a9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py @@ -0,0 +1,48 @@ +import numpy as np +import scipy.special as sc +from numpy.testing import assert_almost_equal, assert_array_equal + + +class TestPdtr: + def test(self): + val = sc.pdtr(0, 1) + assert_almost_equal(val, np.exp(-1)) + + def test_m_zero(self): + val = sc.pdtr([0, 1, 2], 0) + assert_array_equal(val, [1, 1, 1]) + + def test_rounding(self): + double_val = sc.pdtr([0.1, 1.1, 2.1], 1.0) + int_val = sc.pdtr([0, 1, 2], 1.0) + assert_array_equal(double_val, int_val) + + def test_inf(self): + val = sc.pdtr(np.inf, 1.0) + assert_almost_equal(val, 1.0) + + def test_domain(self): + val = sc.pdtr(-1.1, 1.0) + assert np.isnan(val) + +class TestPdtrc: + def test_value(self): + val = sc.pdtrc(0, 1) + assert_almost_equal(val, 1 - np.exp(-1)) + + def test_m_zero(self): + val = sc.pdtrc([0, 1, 2], 0.0) + assert_array_equal(val, [0, 0, 0]) + + def test_rounding(self): + double_val = sc.pdtrc([0.1, 1.1, 2.1], 1.0) + int_val = sc.pdtrc([0, 1, 2], 1.0) + assert_array_equal(double_val, int_val) + + def test_inf(self): + val = sc.pdtrc(np.inf, 1.0) + assert_almost_equal(val, 0.0) + + def test_domain(self): + val = sc.pdtrc(-1.1, 1.0) + assert np.isnan(val) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py new file mode 100644 index 0000000000000000000000000000000000000000..3d809963f64ddaedf6b59de80dcd5f7ca8fa18a9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py @@ -0,0 +1,65 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose +from scipy.special import powm1 + + +# Expected values were computed with mpmath, e.g. +# +# >>> import mpmath +# >>> mpmath.np.dps = 200 +# >>> print(float(mpmath.powm1(2.0, 1e-7)) +# 6.931472045825965e-08 +# +powm1_test_cases = [ + (1.25, 0.75, 0.18217701125396976, 1e-15), + (2.0, 1e-7, 6.931472045825965e-08, 1e-15), + (25.0, 5e-11, 1.6094379125636148e-10, 1e-15), + (0.99996, 0.75, -3.0000150002530058e-05, 1e-15), + (0.9999999999990905, 20, -1.81898940353014e-11, 1e-15), + (-1.25, 751.0, -6.017550852453444e+72, 2e-15) +] + + +@pytest.mark.parametrize('x, y, expected, rtol', powm1_test_cases) +def test_powm1(x, y, expected, rtol): + p = powm1(x, y) + assert_allclose(p, expected, rtol=rtol) + + +@pytest.mark.parametrize('x, y, expected', + [(0.0, 0.0, 0.0), + (0.0, -1.5, np.inf), + (0.0, 1.75, -1.0), + (-1.5, 2.0, 1.25), + (-1.5, 3.0, -4.375), + (np.nan, 0.0, 0.0), + (1.0, np.nan, 0.0), + (1.0, np.inf, 0.0), + (1.0, -np.inf, 0.0), + (np.inf, 7.5, np.inf), + (np.inf, -7.5, -1.0), + (3.25, np.inf, np.inf), + (np.inf, np.inf, np.inf), + (np.inf, -np.inf, -1.0), + (np.inf, 0.0, 0.0), + (-np.inf, 0.0, 0.0), + (-np.inf, 2.0, np.inf), + (-np.inf, 3.0, -np.inf), + (-1.0, float(2**53 - 1), -2.0)]) +def test_powm1_exact_cases(x, y, expected): + # Test cases where we have an exact expected value. + p = powm1(x, y) + assert p == expected + + +@pytest.mark.parametrize('x, y', + [(-1.25, 751.03), + (-1.25, np.inf), + (np.nan, np.nan), + (-np.inf, -np.inf), + (-np.inf, 2.5)]) +def test_powm1_return_nan(x, y): + # Test cases where the expected return value is nan. + p = powm1(x, y) + assert np.isnan(p) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py new file mode 100644 index 0000000000000000000000000000000000000000..7b6c6cba21d5c1d5fdfab879153ba8f125e98d5f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py @@ -0,0 +1,24 @@ +from numpy.testing import assert_equal + +from scipy.special._testutils import check_version, MissingModule +from scipy.special._precompute.expn_asy import generate_A + +try: + import sympy + from sympy import Poly +except ImportError: + sympy = MissingModule("sympy") + + +@check_version(sympy, "1.0") +def test_generate_A(): + # Data from DLMF 8.20.5 + x = sympy.symbols('x') + Astd = [Poly(1, x), + Poly(1, x), + Poly(1 - 2*x), + Poly(1 - 8*x + 6*x**2)] + Ares = generate_A(len(Astd)) + + for p, q in zip(Astd, Ares): + assert_equal(p, q) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c46b456d0a1b545b29e0b8b81b39dafb6b0610 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py @@ -0,0 +1,108 @@ +import pytest + +from scipy.special._testutils import MissingModule, check_version +from scipy.special._mptestutils import ( + Arg, IntArg, mp_assert_allclose, assert_mpmath_equal) +from scipy.special._precompute.gammainc_asy import ( + compute_g, compute_alpha, compute_d) +from scipy.special._precompute.gammainc_data import gammainc, gammaincc + +try: + import sympy +except ImportError: + sympy = MissingModule('sympy') + +try: + import mpmath as mp +except ImportError: + mp = MissingModule('mpmath') + + +@check_version(mp, '0.19') +def test_g(): + # Test data for the g_k. See DLMF 5.11.4. + with mp.workdps(30): + g = [mp.mpf(1), mp.mpf(1)/12, mp.mpf(1)/288, + -mp.mpf(139)/51840, -mp.mpf(571)/2488320, + mp.mpf(163879)/209018880, mp.mpf(5246819)/75246796800] + mp_assert_allclose(compute_g(7), g) + + +@pytest.mark.slow +@check_version(mp, '0.19') +@check_version(sympy, '0.7') +@pytest.mark.xfail_on_32bit("rtol only 2e-11, see gh-6938") +def test_alpha(): + # Test data for the alpha_k. See DLMF 8.12.14. + with mp.workdps(30): + alpha = [mp.mpf(0), mp.mpf(1), mp.mpf(1)/3, mp.mpf(1)/36, + -mp.mpf(1)/270, mp.mpf(1)/4320, mp.mpf(1)/17010, + -mp.mpf(139)/5443200, mp.mpf(1)/204120] + mp_assert_allclose(compute_alpha(9), alpha) + + +@pytest.mark.xslow +@check_version(mp, '0.19') +@check_version(sympy, '0.7') +def test_d(): + # Compare the d_{k, n} to the results in appendix F of [1]. + # + # Sources + # ------- + # [1] DiDonato and Morris, Computation of the Incomplete Gamma + # Function Ratios and their Inverse, ACM Transactions on + # Mathematical Software, 1986. + + with mp.workdps(50): + dataset = [(0, 0, -mp.mpf('0.333333333333333333333333333333')), + (0, 12, mp.mpf('0.102618097842403080425739573227e-7')), + (1, 0, -mp.mpf('0.185185185185185185185185185185e-2')), + (1, 12, mp.mpf('0.119516285997781473243076536700e-7')), + (2, 0, mp.mpf('0.413359788359788359788359788360e-2')), + (2, 12, -mp.mpf('0.140925299108675210532930244154e-7')), + (3, 0, mp.mpf('0.649434156378600823045267489712e-3')), + (3, 12, -mp.mpf('0.191111684859736540606728140873e-7')), + (4, 0, -mp.mpf('0.861888290916711698604702719929e-3')), + (4, 12, mp.mpf('0.288658297427087836297341274604e-7')), + (5, 0, -mp.mpf('0.336798553366358150308767592718e-3')), + (5, 12, mp.mpf('0.482409670378941807563762631739e-7')), + (6, 0, mp.mpf('0.531307936463992223165748542978e-3')), + (6, 12, -mp.mpf('0.882860074633048352505085243179e-7')), + (7, 0, mp.mpf('0.344367606892377671254279625109e-3')), + (7, 12, -mp.mpf('0.175629733590604619378669693914e-6')), + (8, 0, -mp.mpf('0.652623918595309418922034919727e-3')), + (8, 12, mp.mpf('0.377358774161109793380344937299e-6')), + (9, 0, -mp.mpf('0.596761290192746250124390067179e-3')), + (9, 12, mp.mpf('0.870823417786464116761231237189e-6'))] + d = compute_d(10, 13) + res = [d[k][n] for k, n, std in dataset] + std = [x[2] for x in dataset] + mp_assert_allclose(res, std) + + +@check_version(mp, '0.19') +def test_gammainc(): + # Quick check that the gammainc in + # special._precompute.gammainc_data agrees with mpmath's + # gammainc. + assert_mpmath_equal(gammainc, + lambda a, x: mp.gammainc(a, b=x, regularized=True), + [Arg(0, 100, inclusive_a=False), Arg(0, 100)], + nan_ok=False, rtol=1e-17, n=50, dps=50) + + +@pytest.mark.xslow +@check_version(mp, '0.19') +def test_gammaincc(): + # Check that the gammaincc in special._precompute.gammainc_data + # agrees with mpmath's gammainc. + assert_mpmath_equal(lambda a, x: gammaincc(a, x, dps=1000), + lambda a, x: mp.gammainc(a, a=x, regularized=True), + [Arg(20, 100), Arg(20, 100)], + nan_ok=False, rtol=1e-17, n=50, dps=1000) + + # Test the fast integer path + assert_mpmath_equal(gammaincc, + lambda a, x: mp.gammainc(a, a=x, regularized=True), + [IntArg(1, 100), Arg(0, 100)], + nan_ok=False, rtol=1e-17, n=50, dps=50) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..89616b92329691ca76039fe11a7e08f7f3db1150 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py @@ -0,0 +1,36 @@ +import pytest + +from scipy.special._testutils import MissingModule, check_version +from scipy.special._mptestutils import mp_assert_allclose +from scipy.special._precompute.utils import lagrange_inversion + +try: + import sympy +except ImportError: + sympy = MissingModule('sympy') + +try: + import mpmath as mp +except ImportError: + mp = MissingModule('mpmath') + + +@pytest.mark.slow +@check_version(sympy, '0.7') +@check_version(mp, '0.19') +class TestInversion: + @pytest.mark.xfail_on_32bit("rtol only 2e-9, see gh-6938") + def test_log(self): + with mp.workdps(30): + logcoeffs = mp.taylor(lambda x: mp.log(1 + x), 0, 10) + expcoeffs = mp.taylor(lambda x: mp.exp(x) - 1, 0, 10) + invlogcoeffs = lagrange_inversion(logcoeffs) + mp_assert_allclose(invlogcoeffs, expcoeffs) + + @pytest.mark.xfail_on_32bit("rtol only 1e-15, see gh-6938") + def test_sin(self): + with mp.workdps(30): + sincoeffs = mp.taylor(mp.sin, 0, 10) + asincoeffs = mp.taylor(mp.asin, 0, 10) + invsincoeffs = lagrange_inversion(sincoeffs) + mp_assert_allclose(invsincoeffs, asincoeffs, atol=1e-30) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py new file mode 100644 index 0000000000000000000000000000000000000000..ba28b7c1cff95327df0ed69086dd92b93399c3c4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py @@ -0,0 +1,18 @@ +import numpy as np +import pytest + +from scipy.special import _test_internal + + +@pytest.mark.fail_slow(20) +@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()") +def test_add_round_up(): + rng = np.random.RandomState(1234) + _test_internal.test_add_round(10**5, 'up', rng) + + +@pytest.mark.fail_slow(20) +@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()") +def test_add_round_down(): + rng = np.random.RandomState(1234) + _test_internal.test_add_round(10**5, 'down', rng) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py new file mode 100644 index 0000000000000000000000000000000000000000..2dfe8287ee4f53a51a5654edc975c5c521a7d747 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py @@ -0,0 +1,145 @@ +import sys +import warnings + +import numpy as np +from numpy.testing import assert_, assert_equal, IS_PYPY +import pytest +from pytest import raises as assert_raises + +import scipy.special as sc +from scipy.special._ufuncs import _sf_error_test_function + +_sf_error_code_map = { + # skip 'ok' + 'singular': 1, + 'underflow': 2, + 'overflow': 3, + 'slow': 4, + 'loss': 5, + 'no_result': 6, + 'domain': 7, + 'arg': 8, + 'other': 9, + 'memory': 10, +} + +_sf_error_actions = [ + 'ignore', + 'warn', + 'raise' +] + + +def _check_action(fun, args, action): + # TODO: special expert should correct + # the coercion at the true location? + args = np.asarray(args, dtype=np.dtype("long")) + if action == 'warn': + with pytest.warns(sc.SpecialFunctionWarning): + fun(*args) + elif action == 'raise': + with assert_raises(sc.SpecialFunctionError): + fun(*args) + else: + # action == 'ignore', make sure there are no warnings/exceptions + with warnings.catch_warnings(): + warnings.simplefilter("error") + fun(*args) + + +def test_geterr(): + err = sc.geterr() + for key, value in err.items(): + assert_(key in _sf_error_code_map) + assert_(value in _sf_error_actions) + + +@pytest.mark.thread_unsafe +def test_seterr(): + entry_err = sc.geterr() + try: + for category, error_code in _sf_error_code_map.items(): + for action in _sf_error_actions: + geterr_olderr = sc.geterr() + seterr_olderr = sc.seterr(**{category: action}) + assert_(geterr_olderr == seterr_olderr) + newerr = sc.geterr() + assert_(newerr[category] == action) + geterr_olderr.pop(category) + newerr.pop(category) + assert_(geterr_olderr == newerr) + _check_action(_sf_error_test_function, (error_code,), action) + finally: + sc.seterr(**entry_err) + + +@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy") +def test_sf_error_special_refcount(): + # Regression test for gh-16233. + # Check that the reference count of scipy.special is not increased + # when a SpecialFunctionError is raised. + refcount_before = sys.getrefcount(sc) + with sc.errstate(all='raise'): + with pytest.raises(sc.SpecialFunctionError, match='domain error'): + sc.ndtri(2.0) + refcount_after = sys.getrefcount(sc) + assert refcount_after == refcount_before + + +def test_errstate_pyx_basic(): + olderr = sc.geterr() + with sc.errstate(singular='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.loggamma(0) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_c_basic(): + olderr = sc.geterr() + with sc.errstate(domain='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.spence(-1) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_cpp_basic(): + olderr = sc.geterr() + with sc.errstate(underflow='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.wrightomega(-1000) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_cpp_scipy_special(): + olderr = sc.geterr() + with sc.errstate(singular='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.lambertw(0, 1) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_cpp_alt_ufunc_machinery(): + olderr = sc.geterr() + with sc.errstate(singular='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.gammaln(0) + assert_equal(olderr, sc.geterr()) + + +@pytest.mark.thread_unsafe +def test_errstate(): + for category, error_code in _sf_error_code_map.items(): + for action in _sf_error_actions: + olderr = sc.geterr() + with sc.errstate(**{category: action}): + _check_action(_sf_error_test_function, (error_code,), action) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_all_but_one(): + olderr = sc.geterr() + with sc.errstate(all='raise', singular='ignore'): + sc.gammaln(0) + with assert_raises(sc.SpecialFunctionError): + sc.spence(-1.0) + assert_equal(olderr, sc.geterr()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py new file mode 100644 index 0000000000000000000000000000000000000000..d33c1795641ba74f777fcfdcffe80d86463477e3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py @@ -0,0 +1,36 @@ +import numpy as np + +import scipy.special as sc +from scipy.special._testutils import FuncData + + +def test_sici_consistency(): + # Make sure the implementation of sici for real arguments agrees + # with the implementation of sici for complex arguments. + + # On the negative real axis Cephes drops the imaginary part in ci + def sici(x): + si, ci = sc.sici(x + 0j) + return si.real, ci.real + + x = np.r_[-np.logspace(8, -30, 200), 0, np.logspace(-30, 8, 200)] + si, ci = sc.sici(x) + dataset = np.column_stack((x, si, ci)) + FuncData(sici, dataset, 0, (1, 2), rtol=1e-12).check() + + +def test_shichi_consistency(): + # Make sure the implementation of shichi for real arguments agrees + # with the implementation of shichi for complex arguments. + + # On the negative real axis Cephes drops the imaginary part in chi + def shichi(x): + shi, chi = sc.shichi(x + 0j) + return shi.real, chi.real + + # Overflow happens quickly, so limit range + x = np.r_[-np.logspace(np.log10(700), -30, 200), 0, + np.logspace(-30, np.log10(700), 200)] + shi, chi = sc.shichi(x) + dataset = np.column_stack((x, shi, chi)) + FuncData(shichi, dataset, 0, (1, 2), rtol=1e-14).check() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py new file mode 100644 index 0000000000000000000000000000000000000000..f36fd2915be8c8d14138493c34dfd5733a2a1e6d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py @@ -0,0 +1,48 @@ +""" +Various made-up tests to hit different branches of the code in specfun.c +""" + +import numpy as np +from numpy.testing import assert_allclose +from scipy import special + + +def test_cva2_cv0_branches(): + res, resp = special.mathieu_cem([40, 129], [13, 14], [30, 45]) + assert_allclose(res, np.array([-0.3741211, 0.74441928])) + assert_allclose(resp, np.array([-37.02872758, -86.13549877])) + + res, resp = special.mathieu_sem([40, 129], [13, 14], [30, 45]) + assert_allclose(res, np.array([0.92955551, 0.66771207])) + assert_allclose(resp, np.array([-14.91073448, 96.02954185])) + + +def test_chgm_branches(): + res = special.eval_genlaguerre(-3.2, 3, 2.5) + assert_allclose(res, -0.7077721935779854) + + +def test_hygfz_branches(): + """(z == 1.0) && (c-a-b > 0.0)""" + res = special.hyp2f1(1.5, 2.5, 4.5, 1.+0.j) + assert_allclose(res, 10.30835089459151+0j) + """(cabs(z+1) < eps) && (fabs(c-a+b - 1.0) < eps)""" + res = special.hyp2f1(5+5e-16, 2, 2, -1.0 + 5e-16j) + assert_allclose(res, 0.031249999999999986+3.9062499999999994e-17j) + + +def test_pro_rad1(): + # https://github.com/scipy/scipy/issues/21058 + # Reference values taken from WolframAlpha + # SpheroidalS1(1, 1, 30, 1.1) + # SpheroidalS1Prime(1, 1, 30, 1.1) + res = special.pro_rad1(1, 1, 30, 1.1) + assert_allclose(res, (0.009657872296166435, 3.253369651472877), rtol=2e-5) + +def test_pro_rad2(): + # https://github.com/scipy/scipy/issues/21461 + # Reference values taken from WolframAlpha + # SpheroidalS2(0, 0, 3, 1.02) + # SpheroidalS2Prime(0, 0, 3, 1.02) + res = special.pro_rad2(0, 0, 3, 1.02) + assert_allclose(res, (-0.35089596858528077, 13.652764213480872), rtol=10e-10) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb26ac281dff81ea71b30318731065fe5a78f94 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py @@ -0,0 +1,32 @@ +import numpy as np +from numpy import sqrt, log, pi +from scipy.special._testutils import FuncData +from scipy.special import spence + + +def test_consistency(): + # Make sure the implementation of spence for real arguments + # agrees with the implementation of spence for imaginary arguments. + + x = np.logspace(-30, 300, 200) + dataset = np.vstack((x + 0j, spence(x))).T + FuncData(spence, dataset, 0, 1, rtol=1e-14).check() + + +def test_special_points(): + # Check against known values of Spence's function. + + phi = (1 + sqrt(5))/2 + dataset = [(1, 0), + (2, -pi**2/12), + (0.5, pi**2/12 - log(2)**2/2), + (0, pi**2/6), + (-1, pi**2/4 - 1j*pi*log(2)), + ((-1 + sqrt(5))/2, pi**2/15 - log(phi)**2), + ((3 - sqrt(5))/2, pi**2/10 - log(phi)**2), + (phi, -pi**2/15 + log(phi)**2/2), + # Corrected from Zagier, "The Dilogarithm Function" + ((3 + sqrt(5))/2, -pi**2/10 - log(phi)**2)] + + dataset = np.asarray(dataset) + FuncData(spence, dataset, 0, 1, rtol=1e-14).check() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a047c78fb8542bd0abbb75a4815d777e1414b0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py @@ -0,0 +1,61 @@ +import numpy as np +from numpy.testing import (assert_array_equal, + assert_array_almost_equal_nulp, assert_almost_equal) +from pytest import raises as assert_raises + +from scipy.special import gammaln, multigammaln + + +class TestMultiGammaLn: + + def test1(self): + # A test of the identity + # Gamma_1(a) = Gamma(a) + np.random.seed(1234) + a = np.abs(np.random.randn()) + assert_array_equal(multigammaln(a, 1), gammaln(a)) + + def test2(self): + # A test of the identity + # Gamma_2(a) = sqrt(pi) * Gamma(a) * Gamma(a - 0.5) + a = np.array([2.5, 10.0]) + result = multigammaln(a, 2) + expected = np.log(np.sqrt(np.pi)) + gammaln(a) + gammaln(a - 0.5) + assert_almost_equal(result, expected) + + def test_bararg(self): + assert_raises(ValueError, multigammaln, 0.5, 1.2) + + +def _check_multigammaln_array_result(a, d): + # Test that the shape of the array returned by multigammaln + # matches the input shape, and that all the values match + # the value computed when multigammaln is called with a scalar. + result = multigammaln(a, d) + assert_array_equal(a.shape, result.shape) + a1 = a.ravel() + result1 = result.ravel() + for i in range(a.size): + assert_array_almost_equal_nulp(result1[i], multigammaln(a1[i], d)) + + +def test_multigammaln_array_arg(): + # Check that the array returned by multigammaln has the correct + # shape and contains the correct values. The cases have arrays + # with several different shapes. + # The cases include a regression test for ticket #1849 + # (a = np.array([2.0]), an array with a single element). + np.random.seed(1234) + + cases = [ + # a, d + (np.abs(np.random.randn(3, 2)) + 5, 5), + (np.abs(np.random.randn(1, 2)) + 5, 5), + (np.arange(10.0, 18.0).reshape(2, 2, 2), 3), + (np.array([2.0]), 3), + (np.float64(2.0), 3), + ] + + for a, d in cases: + _check_multigammaln_array_result(a, d) + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py new file mode 100644 index 0000000000000000000000000000000000000000..310bda00b4d8b715cddcd94f5aa7142a0bdae6fa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py @@ -0,0 +1,86 @@ +import numpy as np +import pytest + +from numpy.testing import assert_allclose, suppress_warnings +import scipy.special as sc + +class TestSphHarm: + @pytest.mark.slow + def test_p(self): + m_max = 20 + n_max = 10 + + theta = np.linspace(0, np.pi) + phi = np.linspace(0, 2*np.pi) + theta, phi = np.meshgrid(theta, phi) + + y, y_jac, y_hess = sc.sph_harm_y_all(n_max, m_max, theta, phi, diff_n=2) + p, p_jac, p_hess = sc.sph_legendre_p_all(n_max, m_max, theta, diff_n=2) + + m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)]) + m = np.expand_dims(m, axis=(0,)+tuple(range(2,theta.ndim+2))) + + assert_allclose(y, p * np.exp(1j * m * phi)) + + assert_allclose(y_jac[..., 0], p_jac * np.exp(1j * m * phi)) + assert_allclose(y_jac[..., 1], 1j * m * p * np.exp(1j * m * phi)) + + assert_allclose(y_hess[..., 0, 0], p_hess * np.exp(1j * m * phi)) + assert_allclose(y_hess[..., 0, 1], 1j * m * p_jac * np.exp(1j * m * phi)) + assert_allclose(y_hess[..., 1, 0], y_hess[..., 0, 1]) + assert_allclose(y_hess[..., 1, 1], -m * m * p * np.exp(1j * m * phi)) + + @pytest.mark.parametrize("n_max", [7, 10, 50]) + @pytest.mark.parametrize("m_max", [1, 4, 5, 9, 14]) + def test_all(self, n_max, m_max): + theta = np.linspace(0, np.pi) + phi = np.linspace(0, 2 * np.pi) + + n = np.arange(n_max + 1) + n = np.expand_dims(n, axis=tuple(range(1,theta.ndim+2))) + + m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)]) + m = np.expand_dims(m, axis=(0,)+tuple(range(2,theta.ndim+2))) + + y_actual = sc.sph_harm_y_all(n_max, m_max, theta, phi) + y_desired = sc.sph_harm_y(n, m, theta, phi) + + np.testing.assert_allclose(y_actual, y_desired, rtol=1e-05) + +def test_first_harmonics(): + # Test against explicit representations of the first four + # spherical harmonics which use `theta` as the azimuthal angle, + # `phi` as the polar angle, and include the Condon-Shortley + # phase. + + # sph_harm is deprecated and is implemented as a shim around sph_harm_y. + # This test is maintained to verify the correctness of the shim. + + # Notation is Ymn + def Y00(theta, phi): + return 0.5*np.sqrt(1/np.pi) + + def Yn11(theta, phi): + return 0.5*np.sqrt(3/(2*np.pi))*np.exp(-1j*theta)*np.sin(phi) + + def Y01(theta, phi): + return 0.5*np.sqrt(3/np.pi)*np.cos(phi) + + def Y11(theta, phi): + return -0.5*np.sqrt(3/(2*np.pi))*np.exp(1j*theta)*np.sin(phi) + + harms = [Y00, Yn11, Y01, Y11] + m = [0, -1, 0, 1] + n = [0, 1, 1, 1] + + theta = np.linspace(0, 2*np.pi) + phi = np.linspace(0, np.pi) + theta, phi = np.meshgrid(theta, phi) + + for harm, m, n in zip(harms, m, n): + with suppress_warnings() as sup: + sup.filter(category=DeprecationWarning) + assert_allclose(sc.sph_harm(m, n, theta, phi), + harm(theta, phi), + rtol=1e-15, atol=1e-15, + err_msg=f"Y^{m}_{n} incorrect") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0173152c25eca57670b7ee6eadb57cd965266c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py @@ -0,0 +1,400 @@ +# +# Tests of spherical Bessel functions. +# +import numpy as np +from numpy.testing import (assert_almost_equal, assert_allclose, + assert_array_almost_equal, suppress_warnings) +import pytest +from numpy import sin, cos, sinh, cosh, exp, inf, nan, r_, pi + +from scipy.special import spherical_jn, spherical_yn, spherical_in, spherical_kn +from scipy.integrate import quad + + +class TestSphericalJn: + def test_spherical_jn_exact(self): + # https://dlmf.nist.gov/10.49.E3 + # Note: exact expression is numerically stable only for small + # n or z >> n. + x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5]) + assert_allclose(spherical_jn(2, x), + (-1/x + 3/x**3)*sin(x) - 3/x**2*cos(x)) + + def test_spherical_jn_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1, x), + (2*n + 1)/x*spherical_jn(n, x)) + + def test_spherical_jn_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1,x), + (2*n + 1)/x*spherical_jn(n, x)) + + def test_spherical_jn_inf_real(self): + # https://dlmf.nist.gov/10.52.E3 + n = 6 + x = np.array([-inf, inf]) + assert_allclose(spherical_jn(n, x), np.array([0, 0])) + + def test_spherical_jn_inf_complex(self): + # https://dlmf.nist.gov/10.52.E3 + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + assert_allclose(spherical_jn(n, x), np.array([0, 0, inf*(1+1j)])) + + def test_spherical_jn_large_arg_1(self): + # https://github.com/scipy/scipy/issues/2165 + # Reference value computed using mpmath, via + # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z)) + assert_allclose(spherical_jn(2, 3350.507), -0.00029846226538040747) + + def test_spherical_jn_large_arg_2(self): + # https://github.com/scipy/scipy/issues/1641 + # Reference value computed using mpmath, via + # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z)) + assert_allclose(spherical_jn(2, 10000), 3.0590002633029811e-05) + + def test_spherical_jn_at_zero(self): + # https://dlmf.nist.gov/10.52.E1 + # But note that n = 0 is a special case: j0 = sin(x)/x -> 1 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_jn(n, x), np.array([1, 0, 0, 0, 0, 0])) + + +class TestSphericalYn: + def test_spherical_yn_exact(self): + # https://dlmf.nist.gov/10.49.E5 + # Note: exact expression is numerically stable only for small + # n or z >> n. + x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5]) + assert_allclose(spherical_yn(2, x), + (1/x - 3/x**3)*cos(x) - 3/x**2*sin(x)) + + def test_spherical_yn_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1,x), + (2*n + 1)/x*spherical_yn(n, x)) + + def test_spherical_yn_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1, x), + (2*n + 1)/x*spherical_yn(n, x)) + + def test_spherical_yn_inf_real(self): + # https://dlmf.nist.gov/10.52.E3 + n = 6 + x = np.array([-inf, inf]) + assert_allclose(spherical_yn(n, x), np.array([0, 0])) + + def test_spherical_yn_inf_complex(self): + # https://dlmf.nist.gov/10.52.E3 + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + assert_allclose(spherical_yn(n, x), np.array([0, 0, inf*(1+1j)])) + + def test_spherical_yn_at_zero(self): + # https://dlmf.nist.gov/10.52.E2 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_yn(n, x), np.full(n.shape, -inf)) + + def test_spherical_yn_at_zero_complex(self): + # Consistently with numpy: + # >>> -np.cos(0)/0 + # -inf + # >>> -np.cos(0+0j)/(0+0j) + # (-inf + nan*j) + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + 0j + assert_allclose(spherical_yn(n, x), np.full(n.shape, nan)) + + +class TestSphericalJnYnCrossProduct: + def test_spherical_jn_yn_cross_product_1(self): + # https://dlmf.nist.gov/10.50.E3 + n = np.array([1, 5, 8]) + x = np.array([0.1, 1, 10]) + left = (spherical_jn(n + 1, x) * spherical_yn(n, x) - + spherical_jn(n, x) * spherical_yn(n + 1, x)) + right = 1/x**2 + assert_allclose(left, right) + + def test_spherical_jn_yn_cross_product_2(self): + # https://dlmf.nist.gov/10.50.E3 + n = np.array([1, 5, 8]) + x = np.array([0.1, 1, 10]) + left = (spherical_jn(n + 2, x) * spherical_yn(n, x) - + spherical_jn(n, x) * spherical_yn(n + 2, x)) + right = (2*n + 3)/x**3 + assert_allclose(left, right) + + +class TestSphericalIn: + def test_spherical_in_exact(self): + # https://dlmf.nist.gov/10.49.E9 + x = np.array([0.12, 1.23, 12.34, 123.45]) + assert_allclose(spherical_in(2, x), + (1/x + 3/x**3)*sinh(x) - 3/x**2*cosh(x)) + + def test_spherical_in_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E4 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x), + (2*n + 1)/x*spherical_in(n, x)) + + def test_spherical_in_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x), + (2*n + 1)/x*spherical_in(n, x)) + + def test_spherical_in_inf_real(self): + # https://dlmf.nist.gov/10.52.E3 + n = 5 + x = np.array([-inf, inf]) + assert_allclose(spherical_in(n, x), np.array([-inf, inf])) + + def test_spherical_in_inf_complex(self): + # https://dlmf.nist.gov/10.52.E5 + # Ideally, i1n(n, 1j*inf) = 0 and i1n(n, (1+1j)*inf) = (1+1j)*inf, but + # this appears impossible to achieve because C99 regards any complex + # value with at least one infinite part as a complex infinity, so + # 1j*inf cannot be distinguished from (1+1j)*inf. Therefore, nan is + # the correct return value. + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + assert_allclose(spherical_in(n, x), np.array([-inf, inf, nan])) + + def test_spherical_in_at_zero(self): + # https://dlmf.nist.gov/10.52.E1 + # But note that n = 0 is a special case: i0 = sinh(x)/x -> 1 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_in(n, x), np.array([1, 0, 0, 0, 0, 0])) + + +class TestSphericalKn: + def test_spherical_kn_exact(self): + # https://dlmf.nist.gov/10.49.E13 + x = np.array([0.12, 1.23, 12.34, 123.45]) + assert_allclose(spherical_kn(2, x), + pi/2*exp(-x)*(1/x + 3/x**2 + 3/x**3)) + + def test_spherical_kn_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E4 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose( + (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x), + (-1)**n*(2*n + 1)/x*spherical_kn(n, x) + ) + + def test_spherical_kn_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E4 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose( + (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x), + (-1)**n*(2*n + 1)/x*spherical_kn(n, x) + ) + + def test_spherical_kn_inf_real(self): + # https://dlmf.nist.gov/10.52.E6 + n = 5 + x = np.array([-inf, inf]) + assert_allclose(spherical_kn(n, x), np.array([-inf, 0])) + + def test_spherical_kn_inf_complex(self): + # https://dlmf.nist.gov/10.52.E6 + # The behavior at complex infinity depends on the sign of the real + # part: if Re(z) >= 0, then the limit is 0; if Re(z) < 0, then it's + # z*inf. This distinction cannot be captured, so we return nan. + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + assert_allclose(spherical_kn(n, x), np.array([-inf, 0, nan])) + + def test_spherical_kn_at_zero(self): + # https://dlmf.nist.gov/10.52.E2 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_kn(n, x), np.full(n.shape, inf)) + + def test_spherical_kn_at_zero_complex(self): + # https://dlmf.nist.gov/10.52.E2 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + 0j + assert_allclose(spherical_kn(n, x), np.full(n.shape, nan)) + + +class SphericalDerivativesTestCase: + def fundamental_theorem(self, n, a, b): + integral, tolerance = quad(lambda z: self.df(n, z), a, b) + assert_allclose(integral, + self.f(n, b) - self.f(n, a), + atol=tolerance) + + @pytest.mark.slow + def test_fundamental_theorem_0(self): + self.fundamental_theorem(0, 3.0, 15.0) + + @pytest.mark.slow + def test_fundamental_theorem_7(self): + self.fundamental_theorem(7, 0.5, 1.2) + + +class TestSphericalJnDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_jn(n, z) + + def df(self, n, z): + return spherical_jn(n, z, derivative=True) + + def test_spherical_jn_d_zero(self): + n = np.array([0, 1, 2, 3, 7, 15]) + assert_allclose(spherical_jn(n, 0, derivative=True), + np.array([0, 1/3, 0, 0, 0, 0])) + + +class TestSphericalYnDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_yn(n, z) + + def df(self, n, z): + return spherical_yn(n, z, derivative=True) + + +class TestSphericalInDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_in(n, z) + + def df(self, n, z): + return spherical_in(n, z, derivative=True) + + def test_spherical_in_d_zero(self): + n = np.array([0, 1, 2, 3, 7, 15]) + spherical_in(n, 0, derivative=False) + assert_allclose(spherical_in(n, 0, derivative=True), + np.array([0, 1/3, 0, 0, 0, 0])) + + +class TestSphericalKnDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_kn(n, z) + + def df(self, n, z): + return spherical_kn(n, z, derivative=True) + + +class TestSphericalOld: + # These are tests from the TestSpherical class of test_basic.py, + # rewritten to use spherical_* instead of sph_* but otherwise unchanged. + + def test_sph_in(self): + # This test reproduces test_basic.TestSpherical.test_sph_in. + i1n = np.empty((2,2)) + x = 0.2 + + i1n[0][0] = spherical_in(0, x) + i1n[0][1] = spherical_in(1, x) + i1n[1][0] = spherical_in(0, x, derivative=True) + i1n[1][1] = spherical_in(1, x, derivative=True) + + inp0 = (i1n[0][1]) + inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1]) + assert_array_almost_equal(i1n[0],np.array([1.0066800127054699381, + 0.066933714568029540839]),12) + assert_array_almost_equal(i1n[1],[inp0,inp1],12) + + def test_sph_in_kn_order0(self): + x = 1. + sph_i0 = np.empty((2,)) + sph_i0[0] = spherical_in(0, x) + sph_i0[1] = spherical_in(0, x, derivative=True) + sph_i0_expected = np.array([np.sinh(x)/x, + np.cosh(x)/x-np.sinh(x)/x**2]) + assert_array_almost_equal(r_[sph_i0], sph_i0_expected) + + sph_k0 = np.empty((2,)) + sph_k0[0] = spherical_kn(0, x) + sph_k0[1] = spherical_kn(0, x, derivative=True) + sph_k0_expected = np.array([0.5*pi*exp(-x)/x, + -0.5*pi*exp(-x)*(1/x+1/x**2)]) + assert_array_almost_equal(r_[sph_k0], sph_k0_expected) + + def test_sph_jn(self): + s1 = np.empty((2,3)) + x = 0.2 + + s1[0][0] = spherical_jn(0, x) + s1[0][1] = spherical_jn(1, x) + s1[0][2] = spherical_jn(2, x) + s1[1][0] = spherical_jn(0, x, derivative=True) + s1[1][1] = spherical_jn(1, x, derivative=True) + s1[1][2] = spherical_jn(2, x, derivative=True) + + s10 = -s1[0][1] + s11 = s1[0][0]-2.0/0.2*s1[0][1] + s12 = s1[0][1]-3.0/0.2*s1[0][2] + assert_array_almost_equal(s1[0],[0.99334665397530607731, + 0.066400380670322230863, + 0.0026590560795273856680],12) + assert_array_almost_equal(s1[1],[s10,s11,s12],12) + + def test_sph_kn(self): + kn = np.empty((2,3)) + x = 0.2 + + kn[0][0] = spherical_kn(0, x) + kn[0][1] = spherical_kn(1, x) + kn[0][2] = spherical_kn(2, x) + kn[1][0] = spherical_kn(0, x, derivative=True) + kn[1][1] = spherical_kn(1, x, derivative=True) + kn[1][2] = spherical_kn(2, x, derivative=True) + + kn0 = -kn[0][1] + kn1 = -kn[0][0]-2.0/0.2*kn[0][1] + kn2 = -kn[0][1]-3.0/0.2*kn[0][2] + assert_array_almost_equal(kn[0],[6.4302962978445670140, + 38.581777787067402086, + 585.15696310385559829],12) + assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9) + + def test_sph_yn(self): + sy1 = spherical_yn(2, 0.2) + sy2 = spherical_yn(0, 0.2) + assert_almost_equal(sy1,-377.52483,5) # previous values in the system + assert_almost_equal(sy2,-4.9003329,5) + sphpy = (spherical_yn(0, 0.2) - 2*spherical_yn(2, 0.2))/3 + sy3 = spherical_yn(1, 0.2, derivative=True) + # compare correct derivative val. (correct =-system val). + assert_almost_equal(sy3,sphpy,4) + + +@pytest.mark.parametrize('derivative', [False, True]) +@pytest.mark.parametrize('fun', [spherical_jn, spherical_in, + spherical_yn, spherical_kn]) +def test_negative_real_gh14582(derivative, fun): + # gh-14582 reported that the spherical Bessel functions did not work + # with negative real argument `z`. Check that this is resolved. + rng = np.random.default_rng(3598435982345987234) + size = 25 + n = rng.integers(0, 10, size=size) + z = rng.standard_normal(size=size) + res = fun(n, z, derivative=derivative) + ref = fun(n, z+0j, derivative=derivative) + np.testing.assert_allclose(res, ref.real) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..48cfe5bfb64c15486f4b0b2d911846b96e29f3df --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py @@ -0,0 +1,113 @@ +import pytest + +from scipy.special._support_alternative_backends import (get_array_special_func, + array_special_func_map) +from scipy.conftest import array_api_compatible +from scipy import special +from scipy._lib._array_api_no_0d import xp_assert_close +from scipy._lib._array_api import is_jax, is_torch, SCIPY_DEVICE +from scipy._lib.array_api_compat import numpy as np + +try: + import array_api_strict + HAVE_ARRAY_API_STRICT = True +except ImportError: + HAVE_ARRAY_API_STRICT = False + + +@pytest.mark.skipif(not HAVE_ARRAY_API_STRICT, + reason="`array_api_strict` not installed") +def test_dispatch_to_unrecognize_library(): + xp = array_api_strict + f = get_array_special_func('ndtr', xp=xp, n_array_args=1) + x = [1, 2, 3] + res = f(xp.asarray(x)) + ref = xp.asarray(special.ndtr(np.asarray(x))) + xp_assert_close(res, ref, xp=xp) + + +@pytest.mark.parametrize('dtype', ['float32', 'float64', 'int64']) +@pytest.mark.skipif(not HAVE_ARRAY_API_STRICT, + reason="`array_api_strict` not installed") +def test_rel_entr_generic(dtype): + xp = array_api_strict + f = get_array_special_func('rel_entr', xp=xp, n_array_args=2) + dtype_np = getattr(np, dtype) + dtype_xp = getattr(xp, dtype) + x, y = [-1, 0, 0, 1], [1, 0, 2, 3] + + x_xp, y_xp = xp.asarray(x, dtype=dtype_xp), xp.asarray(y, dtype=dtype_xp) + res = f(x_xp, y_xp) + + x_np, y_np = np.asarray(x, dtype=dtype_np), np.asarray(y, dtype=dtype_np) + ref = special.rel_entr(x_np[-1], y_np[-1]) + ref = np.asarray([np.inf, 0, 0, ref], dtype=ref.dtype) + + xp_assert_close(res, xp.asarray(ref), xp=xp) + + +@pytest.mark.fail_slow(5) +@array_api_compatible +# @pytest.mark.skip_xp_backends('numpy', reason='skip while debugging') +# @pytest.mark.usefixtures("skip_xp_backends") +# `reversed` is for developer convenience: test new function first = less waiting +@pytest.mark.parametrize('f_name_n_args', reversed(array_special_func_map.items())) +@pytest.mark.parametrize('dtype', ['float32', 'float64']) +@pytest.mark.parametrize('shapes', [[(0,)]*4, [tuple()]*4, [(10,)]*4, + [(10,), (11, 1), (12, 1, 1), (13, 1, 1, 1)]]) +def test_support_alternative_backends(xp, f_name_n_args, dtype, shapes): + f_name, n_args = f_name_n_args + + if (SCIPY_DEVICE != 'cpu' + and is_torch(xp) + and f_name in {'stdtr', 'betaincc', 'betainc'} + ): + pytest.skip(f"`{f_name}` does not have an array-agnostic implementation " + f"and cannot delegate to PyTorch.") + + shapes = shapes[:n_args] + f = getattr(special, f_name) + + dtype_np = getattr(np, dtype) + dtype_xp = getattr(xp, dtype) + + # # To test the robustness of the alternative backend's implementation, + # # use Hypothesis to generate arguments + # from hypothesis import given, strategies, reproduce_failure, assume + # import hypothesis.extra.numpy as npst + # @given(data=strategies.data()) + # mbs = npst.mutually_broadcastable_shapes(num_shapes=n_args) + # shapes, final_shape = data.draw(mbs) + # elements = dict(allow_subnormal=False) # consider min_value, max_value + # args_np = [np.asarray(data.draw(npst.arrays(dtype_np, shape, elements=elements)), + # dtype=dtype_np) + # for shape in shapes] + + # For CI, be a little more forgiving; just generate normally distributed arguments + rng = np.random.default_rng(984254252920492019) + args_np = [rng.standard_normal(size=shape, dtype=dtype_np) for shape in shapes] + + if (is_jax(xp) and f_name == 'gammaincc' # google/jax#20699 + or f_name == 'chdtrc'): # gh-20972 + args_np[0] = np.abs(args_np[0]) + args_np[1] = np.abs(args_np[1]) + + args_xp = [xp.asarray(arg[()], dtype=dtype_xp) for arg in args_np] + + res = f(*args_xp) + ref = xp.asarray(f(*args_np), dtype=dtype_xp) + + eps = np.finfo(dtype_np).eps + xp_assert_close(res, ref, atol=10*eps) + + +@array_api_compatible +def test_chdtr_gh21311(xp): + # the edge case behavior of generic chdtr was not right; see gh-21311 + # be sure to test at least these cases + # should add `np.nan` into the mix when gh-21317 is resolved + x = np.asarray([-np.inf, -1., 0., 1., np.inf]) + v = x.reshape(-1, 1) + ref = special.chdtr(v, x) + res = special.chdtr(xp.asarray(v), xp.asarray(x)) + xp_assert_close(res, xp.asarray(ref)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py new file mode 100644 index 0000000000000000000000000000000000000000..578dfbd5e95e6c44b1828716a74c93d645efcb1e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py @@ -0,0 +1,72 @@ +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose, suppress_warnings + +from scipy.special._ufuncs import _sinpi as sinpi +from scipy.special._ufuncs import _cospi as cospi + + +def test_integer_real_part(): + x = np.arange(-100, 101) + y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10))) + x, y = np.meshgrid(x, y) + z = x + 1j*y + # In the following we should be *exactly* right + res = sinpi(z) + assert_equal(res.real, 0.0) + res = cospi(z) + assert_equal(res.imag, 0.0) + + +def test_half_integer_real_part(): + x = np.arange(-100, 101) + 0.5 + y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10))) + x, y = np.meshgrid(x, y) + z = x + 1j*y + # In the following we should be *exactly* right + res = sinpi(z) + assert_equal(res.imag, 0.0) + res = cospi(z) + assert_equal(res.real, 0.0) + + +@pytest.mark.skip("Temporary skip while gh-19526 is being resolved") +def test_intermediate_overlow(): + # Make sure we avoid overflow in situations where cosh/sinh would + # overflow but the product with sin/cos would not + sinpi_pts = [complex(1 + 1e-14, 227), + complex(1e-35, 250), + complex(1e-301, 445)] + # Data generated with mpmath + sinpi_std = [complex(-8.113438309924894e+295, -np.inf), + complex(1.9507801934611995e+306, np.inf), + complex(2.205958493464539e+306, np.inf)] + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + for p, std in zip(sinpi_pts, sinpi_std): + res = sinpi(p) + assert_allclose(res.real, std.real) + assert_allclose(res.imag, std.imag) + + # Test for cosine, less interesting because cos(0) = 1. + p = complex(0.5 + 1e-14, 227) + std = complex(-8.113438309924894e+295, -np.inf) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + res = cospi(p) + assert_allclose(res.real, std.real) + assert_allclose(res.imag, std.imag) + + +def test_zero_sign(): + y = sinpi(-0.0) + assert y == 0.0 + assert np.signbit(y) + + y = sinpi(0.0) + assert y == 0.0 + assert not np.signbit(y) + + y = cospi(0.5) + assert y == 0.0 + assert not np.signbit(y) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py new file mode 100644 index 0000000000000000000000000000000000000000..6bc3ffae15ab4620c4e752df166721825cb7449c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py @@ -0,0 +1,46 @@ +"""Test that all ufuncs have float32-preserving signatures. + +This was once guaranteed through the code generation script for +generating ufuncs, `scipy/special/_generate_pyx.py`. Starting with +gh-20260, SciPy developers have begun moving to generate ufuncs +through direct use of the NumPy C API (through C++). Existence of +float32 preserving signatures must now be tested since it is no +longer guaranteed. +""" + +import numpy as np +import pytest +import scipy.special._ufuncs +import scipy.special._gufuncs + +_ufuncs = [] +for funcname in dir(scipy.special._ufuncs): + _ufuncs.append(getattr(scipy.special._ufuncs, funcname)) +for funcname in dir(scipy.special._gufuncs): + _ufuncs.append(getattr(scipy.special._gufuncs, funcname)) + +# Not all module members are actually ufuncs +_ufuncs = [func for func in _ufuncs if isinstance(func, np.ufunc)] + +@pytest.mark.parametrize("ufunc", _ufuncs) +def test_ufunc_signatures(ufunc): + + # From _generate_pyx.py + # "Don't add float32 versions of ufuncs with integer arguments, as this + # can lead to incorrect dtype selection if the integer arguments are + # arrays, but float arguments are scalars. + # For instance sph_harm(0,[0],0,0).dtype == complex64 + # This may be a NumPy bug, but we need to work around it. + # cf. gh-4895, https://github.com/numpy/numpy/issues/5895" + types = set(sig for sig in ufunc.types + if not ("l" in sig or "i" in sig or "q" in sig or "p" in sig)) + + # Generate the full expanded set of signatures which should exist. There + # should be matching float and double versions of any existing signature. + expanded_types = set() + for sig in types: + expanded_types.update( + [sig.replace("d", "f").replace("D", "F"), + sig.replace("f", "d").replace("F", "D")] + ) + assert types == expanded_types diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..ef30163f55c90850fe32ca600eb47547e4fa5e03 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py @@ -0,0 +1,205 @@ +# Reference MPMATH implementation: +# +# import mpmath +# from mpmath import nsum +# +# def Wright_Series_MPMATH(a, b, z, dps=50, method='r+s+e', steps=[1000]): +# """Compute Wright' generalized Bessel function as Series. +# +# This uses mpmath for arbitrary precision. +# """ +# with mpmath.workdps(dps): +# res = nsum(lambda k: z**k/mpmath.fac(k) * mpmath.rgamma(a*k+b), +# [0, mpmath.inf], +# tol=dps, method=method, steps=steps +# ) +# +# return res + +from itertools import product + +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose + +import scipy.special as sc +from scipy.special import log_wright_bessel, loggamma, rgamma, wright_bessel + + +@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10]) +@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10]) +def test_wright_bessel_zero(a, b): + """Test at x = 0.""" + assert_equal(wright_bessel(a, b, 0.), rgamma(b)) + assert_allclose(log_wright_bessel(a, b, 0.), -loggamma(b)) + + +@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10]) +@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1]) +def test_wright_bessel_iv(b, x): + """Test relation of wright_bessel and modified bessel function iv. + + iv(z) = (1/2*z)**v * Phi(1, v+1; 1/4*z**2). + See https://dlmf.nist.gov/10.46.E2 + """ + if x != 0: + v = b - 1 + wb = wright_bessel(1, v + 1, x**2 / 4.) + # Note: iv(v, x) has precision of less than 1e-12 for some cases + # e.g v=1-1e-6 and x=1e-06) + assert_allclose(np.power(x / 2., v) * wb, + sc.iv(v, x), + rtol=1e-11, atol=1e-11) + + +@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10]) +@pytest.mark.parametrize('b', [1, 1 + 1e-3, 2, 5, 10]) +@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1, 5, 10, 100]) +def test_wright_functional(a, b, x): + """Test functional relation of wright_bessel. + + Phi(a, b-1, z) = a*z*Phi(a, b+a, z) + (b-1)*Phi(a, b, z) + + Note that d/dx Phi(a, b, x) = Phi(a, b-1, x) + See Eq. (22) of + B. Stankovic, On the Function of E. M. Wright, + Publ. de l' Institut Mathematique, Beograd, + Nouvelle S`er. 10 (1970), 113-124. + """ + assert_allclose(wright_bessel(a, b - 1, x), + a * x * wright_bessel(a, b + a, x) + + (b - 1) * wright_bessel(a, b, x), + rtol=1e-8, atol=1e-8) + + +# grid of rows [a, b, x, value, accuracy] that do not reach 1e-11 accuracy +# see output of: +# cd scipy/scipy/_precompute +# python wright_bessel_data.py +grid_a_b_x_value_acc = np.array([ + [0.1, 100.0, 709.7827128933841, 8.026353022981087e+34, 2e-8], + [0.5, 10.0, 709.7827128933841, 2.680788404494657e+48, 9e-8], + [0.5, 10.0, 1000.0, 2.005901980702872e+64, 1e-8], + [0.5, 100.0, 1000.0, 3.4112367580445246e-117, 6e-8], + [1.0, 20.0, 100000.0, 1.7717158630699857e+225, 3e-11], + [1.0, 100.0, 100000.0, 1.0269334596230763e+22, np.nan], + [1.0000000000000222, 20.0, 100000.0, 1.7717158630001672e+225, 3e-11], + [1.0000000000000222, 100.0, 100000.0, 1.0269334595866202e+22, np.nan], + [1.5, 0.0, 500.0, 15648961196.432373, 3e-11], + [1.5, 2.220446049250313e-14, 500.0, 15648961196.431465, 3e-11], + [1.5, 1e-10, 500.0, 15648961192.344728, 3e-11], + [1.5, 1e-05, 500.0, 15648552437.334162, 3e-11], + [1.5, 0.1, 500.0, 12049870581.10317, 2e-11], + [1.5, 20.0, 100000.0, 7.81930438331405e+43, 3e-9], + [1.5, 100.0, 100000.0, 9.653370857459075e-130, np.nan], + ]) + + +@pytest.mark.xfail +@pytest.mark.parametrize( + 'a, b, x, phi', + grid_a_b_x_value_acc[:, :4].tolist()) +def test_wright_data_grid_failures(a, b, x, phi): + """Test cases of test_data that do not reach relative accuracy of 1e-11""" + assert_allclose(wright_bessel(a, b, x), phi, rtol=1e-11) + + +@pytest.mark.parametrize( + 'a, b, x, phi, accuracy', + grid_a_b_x_value_acc.tolist()) +def test_wright_data_grid_less_accurate(a, b, x, phi, accuracy): + """Test cases of test_data that do not reach relative accuracy of 1e-11 + + Here we test for reduced accuracy or even nan. + """ + if np.isnan(accuracy): + assert np.isnan(wright_bessel(a, b, x)) + else: + assert_allclose(wright_bessel(a, b, x), phi, rtol=accuracy) + + +@pytest.mark.parametrize( + 'a, b, x', + list( + product([0, 0.1, 0.5, 1.5, 5, 10], [1, 2], [1e-3, 1, 1.5, 5, 10]) + ) +) +def test_log_wright_bessel_same_as_wright_bessel(a, b, x): + """Test that log_wright_bessel equals log of wright_bessel.""" + assert_allclose( + log_wright_bessel(a, b, x), + np.log(wright_bessel(a, b, x)), + rtol=1e-8, + ) + + +# Computed with, see also mp_wright_bessel from wright_bessel_data.py: +# +# from functools import lru_cache +# import mpmath as mp +# +# @lru_cache(maxsize=1_000_000) +# def rgamma_cached(x, dps): +# with mp.workdps(dps): +# return mp.rgamma(x) +# +# def mp_log_wright_bessel(a, b, x, dps=100, maxterms=10_000, method="d"): +# """Compute log of Wright's generalized Bessel function as Series with mpmath.""" +# with mp.workdps(dps): +# a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x) +# res = mp.nsum(lambda k: x**k / mp.fac(k) +# * rgamma_cached(a * k + b, dps=dps), +# [0, mp.inf], +# tol=dps, method=method, steps=[maxterms] +# ) +# return mp.log(res) +# +# Sometimes, one needs to set maxterms as high as 1_00_000 to get accurate results for +# phi. +# At the end of the day, we can only hope that results are correct for very large x, +# e.g. by the asymptotic series, as there is no way to produce those in "exact" +# arithmetic. +# Note: accuracy = np.nan means log_wright_bessel returns nan. +@pytest.mark.parametrize( + 'a, b, x, phi, accuracy', + [ + (0, 0, 0, -np.inf, 1e-11), + (0, 0, 1, -np.inf, 1e-11), + (0, 1, 1.23, 1.23, 1e-11), + (0, 1, 1e50, 1e50, 1e-11), + (1e-5, 0, 700, 695.0421608273609, 1e-11), + (1e-5, 0, 1e3, 995.40052566540066, 1e-11), + (1e-5, 100, 1e3, 640.8197935670078, 1e-11), + (1e-3, 0, 1e4, 9987.2229532297262, 1e-11), + (1e-3, 0, 1e5, 99641.920687169507, 1e-11), + (1e-3, 0, 1e6, 994118.55560054416, 1e-11), # maxterms=1_000_000 + (1e-3, 10, 1e5, 99595.47710802537, 1e-11), + (1e-3, 50, 1e5, 99401.240922855647, 1e-3), + (1e-3, 100, 1e5, 99143.465191656527, np.nan), + (0.5, 0, 1e5, 4074.1112442197941, 1e-11), + (0.5, 0, 1e7, 87724.552120038896, 1e-11), + (0.5, 100, 1e5, 3350.3928746306163, np.nan), + (0.5, 100, 1e7, 86696.109975301719, 1e-11), + (1, 0, 1e5, 634.06765787997266, 1e-11), + (1, 0, 1e8, 20003.339639312035, 1e-11), + (1.5, 0, 1e5, 197.01777556071194, 1e-11), + (1.5, 0, 1e8, 3108.987414395706, 1e-11), + (1.5, 100, 1e8, 2354.8915946283275, np.nan), + (5, 0, 1e5, 9.8980480013203547, 1e-11), + (5, 0, 1e8, 33.642337258687465, 1e-11), + (5, 0, 1e12, 157.53704288117429, 1e-11), + (5, 100, 1e5, -359.13419630792148, 1e-11), + (5, 100, 1e12, -337.07722086995229, 1e-4), + (5, 100, 1e20, 2588.2471229986845, 2e-6), + (100, 0, 1e5, -347.62127990460517, 1e-11), + (100, 0, 1e20, -313.08250350969449, 1e-11), + (100, 100, 1e5, -359.1342053695754, 1e-11), + (100, 100, 1e20, -359.1342053695754, 1e-11), + ] +) +def test_log_wright_bessel(a, b, x, phi, accuracy): + """Test for log_wright_bessel, in particular for large x.""" + if np.isnan(accuracy): + assert np.isnan(log_wright_bessel(a, b, x)) + else: + assert_allclose(log_wright_bessel(a, b, x), phi, rtol=accuracy) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py new file mode 100644 index 0000000000000000000000000000000000000000..c1a93ca007e42fea3a0dec634c51b37f03effa9e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py @@ -0,0 +1,117 @@ +import pytest +import numpy as np +from numpy.testing import assert_, assert_equal, assert_allclose + +import scipy.special as sc +from scipy.special._testutils import assert_func_equal + + +def test_wrightomega_nan(): + pts = [complex(np.nan, 0), + complex(0, np.nan), + complex(np.nan, np.nan), + complex(np.nan, 1), + complex(1, np.nan)] + for p in pts: + res = sc.wrightomega(p) + assert_(np.isnan(res.real)) + assert_(np.isnan(res.imag)) + + +def test_wrightomega_inf_branch(): + pts = [complex(-np.inf, np.pi/4), + complex(-np.inf, -np.pi/4), + complex(-np.inf, 3*np.pi/4), + complex(-np.inf, -3*np.pi/4)] + expected_results = [complex(0.0, 0.0), + complex(0.0, -0.0), + complex(-0.0, 0.0), + complex(-0.0, -0.0)] + for p, expected in zip(pts, expected_results): + res = sc.wrightomega(p) + # We can't use assert_equal(res, expected) because in older versions of + # numpy, assert_equal doesn't check the sign of the real and imaginary + # parts when comparing complex zeros. It does check the sign when the + # arguments are *real* scalars. + assert_equal(res.real, expected.real) + assert_equal(res.imag, expected.imag) + + +def test_wrightomega_inf(): + pts = [complex(np.inf, 10), + complex(-np.inf, 10), + complex(10, np.inf), + complex(10, -np.inf)] + for p in pts: + assert_equal(sc.wrightomega(p), p) + + +def test_wrightomega_singular(): + pts = [complex(-1.0, np.pi), + complex(-1.0, -np.pi)] + for p in pts: + res = sc.wrightomega(p) + assert_equal(res, -1.0) + assert_(np.signbit(res.imag) == np.bool_(False)) + + +@pytest.mark.parametrize('x, desired', [ + (-np.inf, 0), + (np.inf, np.inf), +]) +def test_wrightomega_real_infinities(x, desired): + assert sc.wrightomega(x) == desired + + +def test_wrightomega_real_nan(): + assert np.isnan(sc.wrightomega(np.nan)) + + +def test_wrightomega_real_series_crossover(): + desired_error = 2 * np.finfo(float).eps + crossover = 1e20 + x_before_crossover = np.nextafter(crossover, -np.inf) + x_after_crossover = np.nextafter(crossover, np.inf) + # Computed using Mpmath + desired_before_crossover = 99999999999999983569.948 + desired_after_crossover = 100000000000000016337.948 + assert_allclose( + sc.wrightomega(x_before_crossover), + desired_before_crossover, + atol=0, + rtol=desired_error, + ) + assert_allclose( + sc.wrightomega(x_after_crossover), + desired_after_crossover, + atol=0, + rtol=desired_error, + ) + + +def test_wrightomega_exp_approximation_crossover(): + desired_error = 2 * np.finfo(float).eps + crossover = -50 + x_before_crossover = np.nextafter(crossover, np.inf) + x_after_crossover = np.nextafter(crossover, -np.inf) + # Computed using Mpmath + desired_before_crossover = 1.9287498479639314876e-22 + desired_after_crossover = 1.9287498479639040784e-22 + assert_allclose( + sc.wrightomega(x_before_crossover), + desired_before_crossover, + atol=0, + rtol=desired_error, + ) + assert_allclose( + sc.wrightomega(x_after_crossover), + desired_after_crossover, + atol=0, + rtol=desired_error, + ) + + +def test_wrightomega_real_versus_complex(): + x = np.linspace(-500, 500, 1001) + results = sc.wrightomega(x + 0j).real + assert_func_equal(sc.wrightomega, results, x, atol=0, rtol=1e-14) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..dc39c2eeaf43196d4bf25964a0c2aefec2c8c0b4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py @@ -0,0 +1,114 @@ +import os +import pytest +import scipy.special as sc +import shutil +import tempfile + +from uuid import uuid4 + +from scipy.special._testutils import check_version +from scipy.special._testutils import MissingModule + +try: + import cupy # type: ignore +except (ImportError, AttributeError): + cupy = MissingModule('cupy') + + +def get_test_cases(): + cases_source = [ + (sc.beta, "cephes/beta.h", "out0 = xsf::cephes::beta(in0, in1)"), + (sc.binom, "binom.h", "out0 = xsf::binom(in0, in1)"), + (sc.digamma, "digamma.h", "xsf::digamma(in0)"), + (sc.expn, "cephes/expn.h", "out0 = xsf::cephes::expn(in0, in1)"), + (sc.hyp2f1, "hyp2f1.h", "out0 = xsf::hyp2f1(in0, in1, in2, in3)"), + (sc._ufuncs._lambertw, "lambertw.h", "out0 = xsf::lambertw(in0, in1, in2)"), + (sc.ellipkinc, "cephes/ellik.h", "out0 = xsf::cephes::ellik(in0, in1)"), + (sc.ellipeinc, "cephes/ellie.h", "out0 = xsf::cephes::ellie(in0, in1)"), + (sc.gdtrib, "cdflib.h", "out0 = xsf::gdtrib(in0, in1, in2)"), + (sc.sici, "sici.h", "xsf::sici(in0, &out0, &out1)"), + (sc.shichi, "sici.h", "xsf::shichi(in0, &out0, &out1)"), + ] + + cases = [] + for ufunc, header, routine in cases_source: + preamble = f"#include " + for signature in ufunc.types: + cases.append((signature, preamble, routine)) + return cases + + +dtype_map = { + "f": "float32", + "d": "float64", + "F": "complex64", + "D": "complex128", + "i": "int32", + "l": "int64", +} + + +def get_params(signature): + in_, out = signature.split("->") + in_params = [] + out_params = [] + for i, typecode in enumerate(in_): + in_params.append(f"{dtype_map[typecode]} in{i}") + for i, typecode in enumerate(out): + out_params.append(f"{dtype_map[typecode]} out{i}") + in_params = ", ".join(in_params) + out_params = ", ".join(out_params) + return in_params, out_params + + +def get_sample_input(signature, xp): + dtype_map = { + "f": xp.float32, + "d": xp.float64, + "F": xp.complex64, + "D": xp.complex128, + "i": xp.int32, + "l": xp.int64, + } + + in_, _ = signature.split("->") + args = [] + for typecode in in_: + args.append(xp.zeros(2, dtype=dtype_map[typecode])) + return args + + +@pytest.fixture(scope="module", autouse=True) +def manage_cupy_cache(): + # Temporarily change cupy kernel cache location so kernel cache will not be polluted + # by these tests. Remove temporary cache in teardown. + temp_cache_dir = tempfile.mkdtemp() + original_cache_dir = os.environ.get('CUPY_CACHE_DIR', None) + os.environ['CUPY_CACHE_DIR'] = temp_cache_dir + + yield + + if original_cache_dir is not None: + os.environ['CUPY_CACHE_DIR'] = original_cache_dir + else: + del os.environ['CUPY_CACHE_DIR'] + shutil.rmtree(temp_cache_dir) + + +@check_version(cupy, "13.0.0") +@pytest.mark.parametrize("signature,preamble,routine", get_test_cases()) +@pytest.mark.xslow +def test_compiles_in_cupy(signature, preamble, routine, manage_cupy_cache): + name = f"x{uuid4().hex}" + in_params, out_params = get_params(signature) + + func = cupy.ElementwiseKernel( + in_params, + out_params, + routine, + name, + preamble=preamble, + options=(f"--include-path={sc._get_include()}", "-std=c++17") + ) + + _ = func(*get_sample_input(signature, cupy)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py new file mode 100644 index 0000000000000000000000000000000000000000..988f9a716196fb8f65a92a0a2e894038c2474cfa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py @@ -0,0 +1,301 @@ +import scipy +import scipy.special as sc +import sys +import numpy as np +import pytest + +from numpy.testing import assert_equal, assert_allclose + + +def test_zeta(): + assert_allclose(sc.zeta(2,2), np.pi**2/6 - 1, rtol=1e-12) + + +def test_zetac(): + # Expected values in the following were computed using Wolfram + # Alpha's `Zeta[x] - 1` + x = [-2.1, 0.8, 0.9999, 9, 50, 75] + desired = [ + -0.9972705002153750, + -5.437538415895550, + -10000.42279161673, + 0.002008392826082214, + 8.881784210930816e-16, + 2.646977960169853e-23, + ] + assert_allclose(sc.zetac(x), desired, rtol=1e-12) + + +def test_zetac_special_cases(): + assert sc.zetac(np.inf) == 0 + assert np.isnan(sc.zetac(-np.inf)) + assert sc.zetac(0) == -1.5 + assert sc.zetac(1.0) == np.inf + + assert_equal(sc.zetac([-2, -50, -100]), -1) + + +def test_riemann_zeta_special_cases(): + assert np.isnan(sc.zeta(np.nan)) + assert sc.zeta(np.inf) == 1 + assert sc.zeta(0) == -0.5 + + # Riemann zeta is zero add negative even integers. + assert_equal(sc.zeta([-2, -4, -6, -8, -10]), 0) + + assert_allclose(sc.zeta(2), np.pi**2/6, rtol=1e-12) + assert_allclose(sc.zeta(4), np.pi**4/90, rtol=1e-12) + + +def test_riemann_zeta_avoid_overflow(): + s = -260.00000000001 + desired = -5.6966307844402683127e+297 # Computed with Mpmath + assert_allclose(sc.zeta(s), desired, atol=0, rtol=5e-14) + + +@pytest.mark.parametrize( + "z, desired, rtol", + [ + ## Test cases taken from mpmath with the script: + + # import numpy as np + # import scipy.stats as stats + + # from mpmath import mp + + # # seed = np.random.SeedSequence().entropy + # seed = 154689806791763421822480125722191067828 + # rng = np.random.default_rng(seed) + # default_rtol = 1e-13 + + # # A small point in each quadrant outside of the critical strip + # cases = [] + # for x_sign, y_sign in [1, 1], [1, -1], [-1, 1], [-1, -1]: + # x = x_sign * rng.uniform(2, 8) + # y = y_sign * rng.uniform(2, 8) + # z = x + y*1j + # reference = complex(mp.zeta(z)) + # cases.append((z, reference, default_rtol)) + + # # Moderately large imaginary part in each quadrant outside of critical strip + # for x_sign, y_sign in [1, 1], [1, -1], [-1, 1], [-1, -1]: + # x = x_sign * rng.uniform(2, 8) + # y = y_sign * rng.uniform(50, 80) + # z = x + y*1j + # reference = complex(mp.zeta(z)) + # cases.append((z, reference, default_rtol)) + + # # points in critical strip + # x = rng.uniform(0.0, 1.0, size=5) + # y = np.exp(rng.uniform(0, 5, size=5)) + # z = x + y*1j + # for t in z: + # reference = complex(mp.zeta(t)) + # cases.append((complex(t), reference, default_rtol)) + # z = x - y*1j + # for t in z: + # reference = complex(mp.zeta(t)) + # cases.append((complex(t), reference, default_rtol)) + + # # Near small trivial zeros + # x = np.array([-2, -4, -6, -8]) + # y = np.array([1e-15, -1e-15]) + # x, y = np.meshgrid(x, y) + # x, y = x.ravel(), y.ravel() + # z = x + y*1j + # for t in z: + # reference = complex(mp.zeta(t)) + # cases.append((complex(t), reference, 1e-7)) + + # # Some other points near real axis + # x = np.array([-0.5, 0, 0.2, 0.75]) + # y = np.array([1e-15, -1e-15]) + # x, y = np.meshgrid(x, y) + # x, y = x.ravel(), y.ravel() + # z = x + y*1j + # for t in z: + # reference = complex(mp.zeta(t)) + # cases.append((complex(t), reference, 1e-7)) + + # # Moderately large real part + # x = np.array([49.33915930750887, 50.55805244181687]) + # y = rng.uniform(20, 100, size=3) + # x, y = np.meshgrid(x, y) + # x, y = x.ravel(), y.ravel() + # z = x + y*1j + # for t in z: + # reference = complex(mp.zeta(t)) + # cases.append((complex(t), reference, default_rtol)) + + # # Very large imaginary part + # x = np.array([0.5, 34.812847097948854, 50.55805244181687]) + # y = np.array([1e6, -1e6]) + # x, y = np.meshgrid(x, y) + # x, y = x.ravel(), y.ravel() + # z = x + y*1j + # for t in z: + # reference = complex(mp.zeta(t)) + # rtol = 1e-7 if t.real == 0.5 else default_rtol + # cases.append((complex(t), reference, rtol)) + # + # # Naive implementation of reflection formula suffers internal overflow + # x = -rng.uniform(200, 300, 3) + # y = np.array([rng.uniform(10, 30), -rng.uniform(10, 30)]) + # x, y = np.meshgrid(x, y) + # x, y = x.ravel(), y.ravel() + # z = x + y*1j + # for t in z: + # reference = complex(mp.zeta(t)) + # cases.append((complex(t), reference, default_rtol)) + # + # A small point in each quadrant outside of the critical strip + ((3.12838509346655+7.111085974836645j), + (1.0192654793474945+0.08795174413289127j), + 1e-13), + ((7.06791362314716-7.219497492626728j), + (1.0020740683598117-0.006752725913243711j), + 1e-13), + ((-6.806227077655519+2.724411451005281j), + (0.06312488213559667-0.061641496333765956j), + 1e-13), + ((-3.0170751511621026-6.3686522550665945j), + (-0.10330747857150148-1.214541994832571j), + 1e-13), + # Moderately large imaginary part in each quadrant outside of critical strip + ((6.133994402212294+60.03091448000761j), + (0.9885701843417336+0.009636925981078128j), + 1e-13), + ((6.17268142822657-64.74883149743795j), + (1.0080474225840865+0.012032804974965354j), + 1e-13), + ((-3.462191939791879+76.16258975567534j), + (18672.072070850158+2908.5104826247184j), + 1e-13), + ((-6.955735216531752-74.75791554155748j), + (-77672258.72276545+71625206.0401107j), + 1e-13), + # Points in critical strip + ((0.4088038289823922+1.4596830498094384j), + (0.3032837969400845-0.47272237994110344j), + 1e-13), + ((0.9673493951209633+4.918968547259143j), + (0.7488756907431944+0.17281553371482428j), + 1e-13), + ((0.8692482679977754+66.6142398421354j), + (0.5831942469552066-0.26848904799062334j), + 1e-13), + ((0.42771847720003764+21.783747851715468j), + (0.4767032638444329+0.6898148744603123j), + 1e-13), + ((0.20479494678428956+33.17656449538932j), + (-0.6983038977487848+0.18060923618150224j), + 1e-13), + ((0.4088038289823922-1.4596830498094384j), + (0.3032837969400845+0.47272237994110344j), + 1e-13), + ((0.9673493951209633-4.918968547259143j), + (0.7488756907431944-0.17281553371482428j), + 1e-13), + ((0.8692482679977754-66.6142398421354j), + (0.5831942469552066+0.26848904799062334j), + 1e-13), + ((0.42771847720003764-21.783747851715468j), + (0.4767032638444329-0.6898148744603123j), + 1e-13), + ((0.20479494678428956-33.17656449538932j), + (-0.6983038977487848-0.18060923618150224j), + 1e-13), + # Near small trivial zeros + ((-2+1e-15j), (3.288175809370978e-32-3.0448457058393275e-17j), 1e-07), + ((-4+1e-15j), (-2.868707923051182e-33+7.983811450268625e-18j), 1e-07), + ((-6+1e-15j), (-1.7064292323640116e-34-5.8997591435159376e-18j), 1e-07), + ((-8+1e-15j), (2.5060859548261706e-33+8.316161985602247e-18j), 1e-07), + ((-2-1e-15j), (3.288175809371319e-32+3.0448457058393275e-17j), 1e-07), + ((-4-1e-15j), (-2.8687079230520114e-33-7.983811450268625e-18j), 1e-07), + ((-6-1e-15j), (-1.70642923235801e-34+5.8997591435159376e-18j), 1e-07), + ((-8-1e-15j), (2.5060859548253293e-33-8.316161985602247e-18j), 1e-07), + # Some other points near real axis + ((-0.5+1e-15j), (-0.20788622497735457-3.608543395999408e-16j), 1e-07), + (1e-15j, (-0.5-9.189384239689193e-16j), 1e-07), + ((0.2+1e-15j), (-0.7339209248963406-1.4828001150329085e-15j), 1e-07), + ((0.75+1e-15j), (-3.4412853869452227-1.5924832114302393e-14j), 1e-13), + ((-0.5-1e-15j), (-0.20788622497735457+3.608543395999408e-16j), 1e-07), + (-1e-15j, (-0.5+9.189387416062746e-16j), 1e-07), + ((0.2-1e-15j), (-0.7339209248963406+1.4828004007675122e-15j), 1e-07), + ((0.75-1e-15j), (-3.4412853869452227+1.5924831974403957e-14j), 1e-13), + # Moderately large real part + ((49.33915930750887+53.213478698903955j), + (1.0000000000000009+1.0212452494616078e-15j), + 1e-13), + ((50.55805244181687+53.213478698903955j), + (1.0000000000000004+4.387394180390787e-16j), + 1e-13), + ((49.33915930750887+40.6366015728302j), + (0.9999999999999986-1.502268709924849e-16j), + 1e-13), + ((50.55805244181687+40.6366015728302j), + (0.9999999999999994-6.453929613571651e-17j), + 1e-13), + ((49.33915930750887+85.83555435273925j), + (0.9999999999999987-2.7014400611995846e-16j), + 1e-13), + ((50.55805244181687+85.83555435273925j), + (0.9999999999999994-1.160571605555322e-16j), + 1e-13), + # Very large imaginary part + ((0.5+1e6j), (0.0760890697382271+2.805102101019299j), 1e-07), + ((34.812847097948854+1e6j), + (1.0000000000102545+3.150848654056419e-11j), + 1e-13), + ((50.55805244181687+1e6j), + (1.0000000000000002+5.736517078070873e-16j), + 1e-13), + ((0.5-1e6j), (0.0760890697382271-2.805102101019299j), 1e-07), + ((34.812847097948854-1e6j), + (1.0000000000102545-3.150848654056419e-11j), + 1e-13), + ((50.55805244181687-1e6j), + (1.0000000000000002-5.736517078070873e-16j), + 1e-13), + ((-294.86605461349745+13.992648136816397j), (-np.inf+np.inf*1j), 1e-13), + ((-294.86605461349745-16.147667799398363j), (np.inf-np.inf*1j), 1e-13), + ] +) +def test_riemann_zeta_complex(z, desired, rtol): + assert_allclose(sc.zeta(z), desired, rtol=rtol) + + +# Some of the test cases below fail for intel compilers +cpp_compiler = scipy.__config__.CONFIG["Compilers"]["c++"]["name"] +gcc_linux = cpp_compiler == "gcc" and sys.platform == "linux" +clang_macOS = cpp_compiler == "clang" and sys.platform == "darwin" + + +@pytest.mark.skipif( + not (gcc_linux or clang_macOS), + reason="Underflow may not be avoided on other platforms", +) +@pytest.mark.parametrize( + "z, desired, rtol", + [ + # Test cases generated as part of same script for + # test_riemann_zeta_complex. These cases are split off because + # they fail on some platforms. + # + # Naive implementation of reflection formula suffers internal overflow + ((-217.40285743524163+13.992648136816397j), + (-6.012818500554211e+249-1.926943776932387e+250j), + 5e-13,), + ((-237.71710702931668+13.992648136816397j), + (-8.823803086106129e+281-5.009074181335139e+281j), + 1e-13,), + ((-217.40285743524163-16.147667799398363j), + (-5.111612904844256e+251-4.907132127666742e+250j), + 5e-13,), + ((-237.71710702931668-16.147667799398363j), + (-1.3256112779883167e+283-2.253002003455494e+283j), + 5e-13,), + ], +) +def test_riemann_zeta_complex_avoid_underflow(z, desired, rtol): + assert_allclose(sc.zeta(z), desired, rtol=rtol) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h new file mode 100644 index 0000000000000000000000000000000000000000..6a9b9ead9d7d458b47c5a51fd3104c9f72ff20a5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h @@ -0,0 +1,89 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * + * Original authors: Pauli Virtanen, Eric Moore + */ + +// Binomial coefficient + +#pragma once + +#include "config.h" + +#include "cephes/beta.h" +#include "cephes/gamma.h" + +namespace xsf { + +XSF_HOST_DEVICE inline double binom(double n, double k) { + double kx, nx, num, den, dk, sgn; + + if (n < 0) { + nx = std::floor(n); + if (n == nx) { + // Undefined + return std::numeric_limits::quiet_NaN(); + } + } + + kx = std::floor(k); + if (k == kx && (std::abs(n) > 1E-8 || n == 0)) { + /* Integer case: use multiplication formula for less rounding + * error for cases where the result is an integer. + * + * This cannot be used for small nonzero n due to loss of + * precision. */ + nx = std::floor(n); + if (nx == n && kx > nx / 2 && nx > 0) { + // Reduce kx by symmetry + kx = nx - kx; + } + + if (kx >= 0 && kx < 20) { + num = 1.0; + den = 1.0; + for (int i = 1; i < 1 + static_cast(kx); i++) { + num *= i + n - kx; + den *= i; + if (std::abs(num) > 1E50) { + num /= den; + den = 1.0; + } + } + return num / den; + } + } + + // general case + if (n >= 1E10 * k and k > 0) { + // avoid under/overflows intermediate results + return std::exp(-cephes::lbeta(1 + n - k, 1 + k) - std::log(n + 1)); + } + if (k > 1E8 * std::abs(n)) { + // avoid loss of precision + num = cephes::Gamma(1 + n) / std::abs(k) + cephes::Gamma(1 + n) * n / (2 * k * k); // + ... + num /= M_PI * std::pow(std::abs(k), n); + if (k > 0) { + kx = std::floor(k); + if (static_cast(kx) == kx) { + dk = k - kx; + sgn = (static_cast(kx) % 2 == 0) ? 1 : -1; + } else { + dk = k; + sgn = 1; + } + return num * std::sin((dk - n) * M_PI) * sgn; + } + kx = std::floor(k); + if (static_cast(kx) == kx) { + return 0; + } + return num * std::sin(k * M_PI); + } + return 1 / (n + 1) / cephes::beta(1 + n - k, 1 + k); +} + +XSF_HOST_DEVICE inline float binom(float n, float k) { + return binom(static_cast(n), static_cast(k)); +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h new file mode 100644 index 0000000000000000000000000000000000000000..1ce5550efb6d2b13a45e22c0cbea7952bbd7938c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h @@ -0,0 +1,100 @@ + +#pragma once + +#include "cephes/igam.h" +#include "config.h" +#include "error.h" +#include "tools.h" + +namespace xsf { + +XSF_HOST_DEVICE inline double gdtrib(double a, double p, double x) { + if (std::isnan(p) || std::isnan(a) || std::isnan(x)) { + return std::numeric_limits::quiet_NaN(); + } + if (!((0 <= p) && (p <= 1))) { + set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter p is out of range"); + return std::numeric_limits::quiet_NaN(); + } + if (!(a > 0) || std::isinf(a)) { + set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter a is out of range"); + return std::numeric_limits::quiet_NaN(); + } + if (!(x >= 0) || std::isinf(x)) { + set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter x is out of range"); + return std::numeric_limits::quiet_NaN(); + } + if (x == 0.0) { + if (p == 0.0) { + set_error("gdtrib", SF_ERROR_DOMAIN, "Indeterminate result for (x, p) == (0, 0)."); + return std::numeric_limits::quiet_NaN(); + } + /* gdtrib(a, p, x) tends to 0 as x -> 0 when p > 0 */ + return 0.0; + } + if (p == 0.0) { + /* gdtrib(a, p, x) tends to infinity as p -> 0 from the right when x > 0. */ + set_error("gdtrib", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } + if (p == 1.0) { + /* gdtrib(a, p, x) tends to 0 as p -> 1.0 from the left when x > 0. */ + return 0.0; + } + double q = 1.0 - p; + auto func = [a, p, q, x](double b) { + if (p <= q) { + return cephes::igam(b, a * x) - p; + } + return q - cephes::igamc(b, a * x); + }; + double lower_bound = std::numeric_limits::min(); + double upper_bound = std::numeric_limits::max(); + /* To explain the magic constants used below: + * 1.0 is the initial guess for the root. -0.875 is the initial step size + * for the leading bracket endpoint if the bracket search will proceed to the + * left, likewise 7.0 is the initial step size when the bracket search will + * proceed to the right. 0.125 is the scale factor for a left moving bracket + * search and 8.0 the scale factor for a right moving bracket search. These + * constants are chosen so that: + * + * 1. The scale factor and bracket endpoints remain powers of 2, allowing for + * exact arithmetic, preventing roundoff error from causing numerical catastrophe + * which could lead to unexpected results. + * 2. The bracket sizes remain constant in a relative sense. Each candidate bracket + * will contain roughly the same number of floating point values. This means that + * the number of necessary function evaluations in the worst case scenario for + * Chandrupatla's algorithm will remain constant. + * + * false specifies that the function is not decreasing. 342 is equal to + * max(ceil(log_8(DBL_MAX)), ceil(log_(1/8)(DBL_MIN))). An upper bound for the + * number of iterations needed in this bracket search to check all normalized + * floating point values. + */ + auto [xl, xr, f_xl, f_xr, bracket_status] = detail::bracket_root_for_cdf_inversion( + func, 1.0, lower_bound, upper_bound, -0.875, 7.0, 0.125, 8, false, 342 + ); + if (bracket_status == 1) { + set_error("gdtrib", SF_ERROR_UNDERFLOW, NULL); + return 0.0; + } + if (bracket_status == 2) { + set_error("gdtrib", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity(); + } + if (bracket_status >= 3) { + set_error("gdtrib", SF_ERROR_OTHER, "Computational Error"); + return std::numeric_limits::quiet_NaN(); + } + auto [result, root_status] = detail::find_root_chandrupatla( + func, xl, xr, f_xl, f_xr, std::numeric_limits::epsilon(), 1e-100, 100 + ); + if (root_status) { + /* The root finding return should only fail if there's a bug in our code. */ + set_error("gdtrib", SF_ERROR_OTHER, "Computational Error, (%.17g, %.17g, %.17g)", a, p, x); + return std::numeric_limits::quiet_NaN(); + } + return result; +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h new file mode 100644 index 0000000000000000000000000000000000000000..8db31fa9b3830b1e561a27a349154fc96ab071d3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h @@ -0,0 +1,307 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* airy.c + * + * Airy function + * + * + * + * SYNOPSIS: + * + * double x, ai, aip, bi, bip; + * int airy(); + * + * airy( x, _&ai, _&aip, _&bi, _&bip ); + * + * + * + * DESCRIPTION: + * + * Solution of the differential equation + * + * y"(x) = xy. + * + * The function returns the two independent solutions Ai, Bi + * and their first derivatives Ai'(x), Bi'(x). + * + * Evaluation is by power series summation for small x, + * by rational minimax approximations for large x. + * + * + * + * ACCURACY: + * Error criterion is absolute when function <= 1, relative + * when function > 1, except * denotes relative error criterion. + * For large negative x, the absolute error increases as x^1.5. + * For large positive x, the relative error increases as x^1.5. + * + * Arithmetic domain function # trials peak rms + * IEEE -10, 0 Ai 10000 1.6e-15 2.7e-16 + * IEEE 0, 10 Ai 10000 2.3e-14* 1.8e-15* + * IEEE -10, 0 Ai' 10000 4.6e-15 7.6e-16 + * IEEE 0, 10 Ai' 10000 1.8e-14* 1.5e-15* + * IEEE -10, 10 Bi 30000 4.2e-15 5.3e-16 + * IEEE -10, 10 Bi' 30000 4.9e-15 7.3e-16 + * + */ +/* airy.c */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double airy_c1 = 0.35502805388781723926; + constexpr double airy_c2 = 0.258819403792806798405; + constexpr double MAXAIRY = 103.892; + + constexpr double airy_AN[8] = { + 3.46538101525629032477E-1, 1.20075952739645805542E1, 7.62796053615234516538E1, 1.68089224934630576269E2, + 1.59756391350164413639E2, 7.05360906840444183113E1, 1.40264691163389668864E1, 9.99999999999999995305E-1, + }; + + constexpr double airy_AD[8] = { + 5.67594532638770212846E-1, 1.47562562584847203173E1, 8.45138970141474626562E1, 1.77318088145400459522E2, + 1.64234692871529701831E2, 7.14778400825575695274E1, 1.40959135607834029598E1, 1.00000000000000000470E0, + }; + + constexpr double airy_APN[8] = { + 6.13759184814035759225E-1, 1.47454670787755323881E1, 8.20584123476060982430E1, 1.71184781360976385540E2, + 1.59317847137141783523E2, 6.99778599330103016170E1, 1.39470856980481566958E1, 1.00000000000000000550E0, + }; + + constexpr double airy_APD[8] = { + 3.34203677749736953049E-1, 1.11810297306158156705E1, 7.11727352147859965283E1, 1.58778084372838313640E2, + 1.53206427475809220834E2, 6.86752304592780337944E1, 1.38498634758259442477E1, 9.99999999999999994502E-1, + }; + + constexpr double airy_BN16[5] = { + -2.53240795869364152689E-1, 5.75285167332467384228E-1, -3.29907036873225371650E-1, + 6.44404068948199951727E-2, -3.82519546641336734394E-3, + }; + + constexpr double airy_BD16[5] = { + /* 1.00000000000000000000E0, */ + -7.15685095054035237902E0, 1.06039580715664694291E1, -5.23246636471251500874E0, + 9.57395864378383833152E-1, -5.50828147163549611107E-2, + }; + + constexpr double airy_BPPN[5] = { + 4.65461162774651610328E-1, -1.08992173800493920734E0, 6.38800117371827987759E-1, + -1.26844349553102907034E-1, 7.62487844342109852105E-3, + }; + + constexpr double airy_BPPD[5] = { + /* 1.00000000000000000000E0, */ + -8.70622787633159124240E0, 1.38993162704553213172E1, -7.14116144616431159572E0, + 1.34008595960680518666E0, -7.84273211323341930448E-2, + }; + + constexpr double airy_AFN[9] = { + -1.31696323418331795333E-1, -6.26456544431912369773E-1, -6.93158036036933542233E-1, + -2.79779981545119124951E-1, -4.91900132609500318020E-2, -4.06265923594885404393E-3, + -1.59276496239262096340E-4, -2.77649108155232920844E-6, -1.67787698489114633780E-8, + }; + + constexpr double airy_AFD[9] = { + /* 1.00000000000000000000E0, */ + 1.33560420706553243746E1, 3.26825032795224613948E1, 2.67367040941499554804E1, + 9.18707402907259625840E0, 1.47529146771666414581E0, 1.15687173795188044134E-1, + 4.40291641615211203805E-3, 7.54720348287414296618E-5, 4.51850092970580378464E-7, + }; + + constexpr double airy_AGN[11] = { + 1.97339932091685679179E-2, 3.91103029615688277255E-1, 1.06579897599595591108E0, 9.39169229816650230044E-1, + 3.51465656105547619242E-1, 6.33888919628925490927E-2, 5.85804113048388458567E-3, 2.82851600836737019778E-4, + 6.98793669997260967291E-6, 8.11789239554389293311E-8, 3.41551784765923618484E-10, + }; + + constexpr double airy_AGD[10] = { + /* 1.00000000000000000000E0, */ + 9.30892908077441974853E0, 1.98352928718312140417E1, 1.55646628932864612953E1, 5.47686069422975497931E0, + 9.54293611618961883998E-1, 8.64580826352392193095E-2, 4.12656523824222607191E-3, 1.01259085116509135510E-4, + 1.17166733214413521882E-6, 4.91834570062930015649E-9, + }; + + constexpr double airy_APFN[9] = { + 1.85365624022535566142E-1, 8.86712188052584095637E-1, 9.87391981747398547272E-1, + 4.01241082318003734092E-1, 7.10304926289631174579E-2, 5.90618657995661810071E-3, + 2.33051409401776799569E-4, 4.08718778289035454598E-6, 2.48379932900442457853E-8, + }; + + constexpr double airy_APFD[9] = { + /* 1.00000000000000000000E0, */ + 1.47345854687502542552E1, 3.75423933435489594466E1, 3.14657751203046424330E1, + 1.09969125207298778536E1, 1.78885054766999417817E0, 1.41733275753662636873E-1, + 5.44066067017226003627E-3, 9.39421290654511171663E-5, 5.65978713036027009243E-7, + }; + + constexpr double airy_APGN[11] = { + -3.55615429033082288335E-2, -6.37311518129435504426E-1, -1.70856738884312371053E0, + -1.50221872117316635393E0, -5.63606665822102676611E-1, -1.02101031120216891789E-1, + -9.48396695961445269093E-3, -4.60325307486780994357E-4, -1.14300836484517375919E-5, + -1.33415518685547420648E-7, -5.63803833958893494476E-10, + }; + + constexpr double airy_APGD[11] = { + /* 1.00000000000000000000E0, */ + 9.85865801696130355144E0, 2.16401867356585941885E1, 1.73130776389749389525E1, 6.17872175280828766327E0, + 1.08848694396321495475E0, 9.95005543440888479402E-2, 4.78468199683886610842E-3, 1.18159633322838625562E-4, + 1.37480673554219441465E-6, 5.79912514929147598821E-9, + }; + + } // namespace detail + + XSF_HOST_DEVICE inline int airy(double x, double *ai, double *aip, double *bi, double *bip) { + double z, zz, t, f, g, uf, ug, k, zeta, theta; + int domflg; + + domflg = 0; + if (x > detail::MAXAIRY) { + *ai = 0; + *aip = 0; + *bi = std::numeric_limits::infinity(); + *bip = std::numeric_limits::infinity(); + return (-1); + } + + if (x < -2.09) { + domflg = 15; + t = std::sqrt(-x); + zeta = -2.0 * x * t / 3.0; + t = std::sqrt(t); + k = detail::SQRT1OPI / t; + z = 1.0 / zeta; + zz = z * z; + uf = 1.0 + zz * polevl(zz, detail::airy_AFN, 8) / p1evl(zz, detail::airy_AFD, 9); + ug = z * polevl(zz, detail::airy_AGN, 10) / p1evl(zz, detail::airy_AGD, 10); + theta = zeta + 0.25 * M_PI; + f = std::sin(theta); + g = std::cos(theta); + *ai = k * (f * uf - g * ug); + *bi = k * (g * uf + f * ug); + uf = 1.0 + zz * polevl(zz, detail::airy_APFN, 8) / p1evl(zz, detail::airy_APFD, 9); + ug = z * polevl(zz, detail::airy_APGN, 10) / p1evl(zz, detail::airy_APGD, 10); + k = detail::SQRT1OPI * t; + *aip = -k * (g * uf + f * ug); + *bip = k * (f * uf - g * ug); + return (0); + } + + if (x >= 2.09) { /* cbrt(9) */ + domflg = 5; + t = std::sqrt(x); + zeta = 2.0 * x * t / 3.0; + g = std::exp(zeta); + t = std::sqrt(t); + k = 2.0 * t * g; + z = 1.0 / zeta; + f = polevl(z, detail::airy_AN, 7) / polevl(z, detail::airy_AD, 7); + *ai = detail::SQRT1OPI * f / k; + k = -0.5 * detail::SQRT1OPI * t / g; + f = polevl(z, detail::airy_APN, 7) / polevl(z, detail::airy_APD, 7); + *aip = f * k; + + if (x > 8.3203353) { /* zeta > 16 */ + f = z * polevl(z, detail::airy_BN16, 4) / p1evl(z, detail::airy_BD16, 5); + k = detail::SQRT1OPI * g; + *bi = k * (1.0 + f) / t; + f = z * polevl(z, detail::airy_BPPN, 4) / p1evl(z, detail::airy_BPPD, 5); + *bip = k * t * (1.0 + f); + return (0); + } + } + + f = 1.0; + g = x; + t = 1.0; + uf = 1.0; + ug = x; + k = 1.0; + z = x * x * x; + while (t > detail::MACHEP) { + uf *= z; + k += 1.0; + uf /= k; + ug *= z; + k += 1.0; + ug /= k; + uf /= k; + f += uf; + k += 1.0; + ug /= k; + g += ug; + t = std::abs(uf / f); + } + uf = detail::airy_c1 * f; + ug = detail::airy_c2 * g; + if ((domflg & 1) == 0) { + *ai = uf - ug; + } + if ((domflg & 2) == 0) { + *bi = detail::SQRT3 * (uf + ug); + } + + /* the deriviative of ai */ + k = 4.0; + uf = x * x / 2.0; + ug = z / 3.0; + f = uf; + g = 1.0 + ug; + uf /= 3.0; + t = 1.0; + + while (t > detail::MACHEP) { + uf *= z; + ug /= k; + k += 1.0; + ug *= z; + uf /= k; + f += uf; + k += 1.0; + ug /= k; + uf /= k; + g += ug; + k += 1.0; + t = std::abs(ug / g); + } + + uf = detail::airy_c1 * f; + ug = detail::airy_c2 * g; + if ((domflg & 4) == 0) { + *aip = uf - ug; + } + if ((domflg & 8) == 0) { + *bip = detail::SQRT3 * (uf + ug); + }; + return (0); + } + + inline int airy(float xf, float *aif, float *aipf, float *bif, float *bipf) { + double ai; + double aip; + double bi; + double bip; + int res = cephes::airy(xf, &ai, &aip, &bi, &bip); + + *aif = ai; + *aipf = aip; + *bif = bi; + *bipf = bip; + return res; + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h new file mode 100644 index 0000000000000000000000000000000000000000..d113b8b7d0f4ae4e7ad9da2faf66d3ab7406d736 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h @@ -0,0 +1,51 @@ +/* Translated into C++ by SciPy developers in 2024. + * + * This was not part of the original cephes library. + */ +#pragma once + +#include "../config.h" +#include "gamma.h" + +namespace xsf { +namespace cephes { + namespace detail { + + constexpr double besselpoly_EPS = 1.0e-17; + } + + XSF_HOST_DEVICE inline double besselpoly(double a, double lambda, double nu) { + + int m, factor = 0; + double Sm, relerr, Sol; + double sum = 0.0; + + /* Special handling for a = 0.0 */ + if (a == 0.0) { + if (nu == 0.0) { + return 1.0 / (lambda + 1); + } else { + return 0.0; + } + } + /* Special handling for negative and integer nu */ + if ((nu < 0) && (std::floor(nu) == nu)) { + nu = -nu; + factor = static_cast(nu) % 2; + } + Sm = std::exp(nu * std::log(a)) / (Gamma(nu + 1) * (lambda + nu + 1)); + m = 0; + do { + sum += Sm; + Sol = Sm; + Sm *= -a * a * (lambda + nu + 1 + 2 * m) / ((nu + m + 1) * (m + 1) * (lambda + nu + 1 + 2 * m + 2)); + m++; + relerr = std::abs((Sm - Sol) / Sm); + } while (relerr > detail::besselpoly_EPS && m < 1000); + if (!factor) + return sum; + else + return -sum; + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h new file mode 100644 index 0000000000000000000000000000000000000000..437262793e8f94b229671978b23a638820ff1290 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h @@ -0,0 +1,257 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* beta.c + * + * Beta function + * + * + * + * SYNOPSIS: + * + * double a, b, y, beta(); + * + * y = beta( a, b ); + * + * + * + * DESCRIPTION: + * + * - - + * | (a) | (b) + * beta( a, b ) = -----------. + * - + * | (a+b) + * + * For large arguments the logarithm of the function is + * evaluated using lgam(), then exponentiated. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 8.1e-14 1.1e-14 + * + * ERROR MESSAGES: + * + * message condition value returned + * beta overflow log(beta) > MAXLOG 0.0 + * a or b <0 integer 0.0 + * + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "const.h" +#include "gamma.h" +#include "rgamma.h" + +namespace xsf { +namespace cephes { + + XSF_HOST_DEVICE double beta(double, double); + XSF_HOST_DEVICE double lbeta(double, double); + + namespace detail { + constexpr double beta_ASYMP_FACTOR = 1e6; + + /* + * Asymptotic expansion for ln(|B(a, b)|) for a > ASYMP_FACTOR*max(|b|, 1). + */ + XSF_HOST_DEVICE inline double lbeta_asymp(double a, double b, int *sgn) { + double r = lgam_sgn(b, sgn); + r -= b * std::log(a); + + r += b * (1 - b) / (2 * a); + r += b * (1 - b) * (1 - 2 * b) / (12 * a * a); + r += -b * b * (1 - b) * (1 - b) / (12 * a * a * a); + + return r; + } + + /* + * Special case for a negative integer argument + */ + + XSF_HOST_DEVICE inline double beta_negint(int a, double b) { + int sgn; + if (b == static_cast(b) && 1 - a - b > 0) { + sgn = (static_cast(b) % 2 == 0) ? 1 : -1; + return sgn * xsf::cephes::beta(1 - a - b, b); + } else { + set_error("lbeta", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity(); + } + } + + XSF_HOST_DEVICE inline double lbeta_negint(int a, double b) { + double r; + if (b == static_cast(b) && 1 - a - b > 0) { + r = xsf::cephes::lbeta(1 - a - b, b); + return r; + } else { + set_error("lbeta", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity(); + } + } + } // namespace detail + + XSF_HOST_DEVICE inline double beta(double a, double b) { + double y; + int sign = 1; + + if (a <= 0.0) { + if (a == std::floor(a)) { + if (a == static_cast(a)) { + return detail::beta_negint(static_cast(a), b); + } else { + goto overflow; + } + } + } + + if (b <= 0.0) { + if (b == std::floor(b)) { + if (b == static_cast(b)) { + return detail::beta_negint(static_cast(b), a); + } else { + goto overflow; + } + } + } + + if (std::abs(a) < std::abs(b)) { + y = a; + a = b; + b = y; + } + + if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) { + /* Avoid loss of precision in lgam(a + b) - lgam(a) */ + y = detail::lbeta_asymp(a, b, &sign); + return sign * std::exp(y); + } + + y = a + b; + if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) { + int sgngam; + y = detail::lgam_sgn(y, &sgngam); + sign *= sgngam; /* keep track of the sign */ + y = detail::lgam_sgn(b, &sgngam) - y; + sign *= sgngam; + y = detail::lgam_sgn(a, &sgngam) + y; + sign *= sgngam; + if (y > detail::MAXLOG) { + goto overflow; + } + return (sign * std::exp(y)); + } + + y = rgamma(y); + a = Gamma(a); + b = Gamma(b); + if (std::isinf(y)) { + goto overflow; + } + + if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) { + y = b * y; + y *= a; + } else { + y = a * y; + y *= b; + } + + return (y); + + overflow: + set_error("beta", SF_ERROR_OVERFLOW, NULL); + return (sign * std::numeric_limits::infinity()); + } + + /* Natural log of |beta|. */ + + XSF_HOST_DEVICE inline double lbeta(double a, double b) { + double y; + int sign; + + sign = 1; + + if (a <= 0.0) { + if (a == std::floor(a)) { + if (a == static_cast(a)) { + return detail::lbeta_negint(static_cast(a), b); + } else { + goto over; + } + } + } + + if (b <= 0.0) { + if (b == std::floor(b)) { + if (b == static_cast(b)) { + return detail::lbeta_negint(static_cast(b), a); + } else { + goto over; + } + } + } + + if (std::abs(a) < std::abs(b)) { + y = a; + a = b; + b = y; + } + + if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) { + /* Avoid loss of precision in lgam(a + b) - lgam(a) */ + y = detail::lbeta_asymp(a, b, &sign); + return y; + } + + y = a + b; + if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) { + int sgngam; + y = detail::lgam_sgn(y, &sgngam); + sign *= sgngam; /* keep track of the sign */ + y = detail::lgam_sgn(b, &sgngam) - y; + sign *= sgngam; + y = detail::lgam_sgn(a, &sgngam) + y; + sign *= sgngam; + return (y); + } + + y = rgamma(y); + a = Gamma(a); + b = Gamma(b); + if (std::isinf(y)) { + over: + set_error("lbeta", SF_ERROR_OVERFLOW, NULL); + return (sign * std::numeric_limits::infinity()); + } + + if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) { + y = b * y; + y *= a; + } else { + y = a * y; + y *= b; + } + + if (y < 0) { + y = -y; + } + + return (std::log(y)); + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h new file mode 100644 index 0000000000000000000000000000000000000000..3e9fbd4eab45b24f1caa8b509c9d1d3c536867fe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h @@ -0,0 +1,131 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* cbrt.c + * + * Cube root + * + * + * + * SYNOPSIS: + * + * double x, y, cbrt(); + * + * y = cbrt( x ); + * + * + * + * DESCRIPTION: + * + * Returns the cube root of the argument, which may be negative. + * + * Range reduction involves determining the power of 2 of + * the argument. A polynomial of degree 2 applied to the + * mantissa, and multiplication by the cube root of 1, 2, or 4 + * approximates the root to within about 0.1%. Then Newton's + * iteration is used three times to converge to an accurate + * result. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,1e308 30000 1.5e-16 5.0e-17 + * + */ +/* cbrt.c */ + +/* + * Cephes Math Library Release 2.2: January, 1991 + * Copyright 1984, 1991 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double CBRT2 = 1.2599210498948731647672; + constexpr double CBRT4 = 1.5874010519681994747517; + constexpr double CBRT2I = 0.79370052598409973737585; + constexpr double CBRT4I = 0.62996052494743658238361; + + XSF_HOST_DEVICE inline double cbrt(double x) { + int e, rem, sign; + double z; + + if (!std::isfinite(x)) { + return x; + } + if (x == 0) { + return (x); + } + if (x > 0) { + sign = 1; + } else { + sign = -1; + x = -x; + } + + z = x; + /* extract power of 2, leaving + * mantissa between 0.5 and 1 + */ + x = std::frexp(x, &e); + + /* Approximate cube root of number between .5 and 1, + * peak relative error = 9.2e-6 + */ + x = (((-1.3466110473359520655053e-1 * x + 5.4664601366395524503440e-1) * x - 9.5438224771509446525043e-1) * + x + + 1.1399983354717293273738e0) * + x + + 4.0238979564544752126924e-1; + + /* exponent divided by 3 */ + if (e >= 0) { + rem = e; + e /= 3; + rem -= 3 * e; + if (rem == 1) { + x *= CBRT2; + } else if (rem == 2) { + x *= CBRT4; + } + } + /* argument less than 1 */ + else { + e = -e; + rem = e; + e /= 3; + rem -= 3 * e; + if (rem == 1) { + x *= CBRT2I; + } else if (rem == 2) { + x *= CBRT4I; + } + e = -e; + } + + /* multiply by power of 2 */ + x = std::ldexp(x, e); + + /* Newton iteration */ + x -= (x - (z / (x * x))) * 0.33333333333333333333; + x -= (x - (z / (x * x))) * 0.33333333333333333333; + + if (sign < 0) + x = -x; + return (x); + } + } // namespace detail + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h new file mode 100644 index 0000000000000000000000000000000000000000..caaa74fc7b81015784608cc38aed5987ca145526 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h @@ -0,0 +1,85 @@ +/* chbevl.c + * + * Evaluate Chebyshev series + * + * + * + * SYNOPSIS: + * + * int N; + * double x, y, coef[N], chebevl(); + * + * y = chbevl( x, coef, N ); + * + * + * + * DESCRIPTION: + * + * Evaluates the series + * + * N-1 + * - ' + * y = > coef[i] T (x/2) + * - i + * i=0 + * + * of Chebyshev polynomials Ti at argument x/2. + * + * Coefficients are stored in reverse order, i.e. the zero + * order term is last in the array. Note N is the number of + * coefficients, not the order. + * + * If coefficients are for the interval a to b, x must + * have been transformed to x -> 2(2x - b - a)/(b-a) before + * entering the routine. This maps x from (a, b) to (-1, 1), + * over which the Chebyshev polynomials are defined. + * + * If the coefficients are for the inverted interval, in + * which (a, b) is mapped to (1/b, 1/a), the transformation + * required is x -> 2(2ab/x - b - a)/(b-a). If b is infinity, + * this becomes x -> 4a/x - 1. + * + * + * + * SPEED: + * + * Taking advantage of the recurrence properties of the + * Chebyshev polynomials, the routine requires one more + * addition per loop than evaluating a nested polynomial of + * the same degree. + * + */ +/* chbevl.c */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1985, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" + +namespace xsf { +namespace cephes { + + XSF_HOST_DEVICE double chbevl(double x, const double array[], int n) { + double b0, b1, b2; + const double *p; + int i; + + p = array; + b0 = *p++; + b1 = 0.0; + i = n - 1; + + do { + b2 = b1; + b1 = b0; + b0 = x * b1 - b2 + *p++; + } while (--i); + + return (0.5 * (b0 - b2)); + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h new file mode 100644 index 0000000000000000000000000000000000000000..0a97def6d00baa18eaffaca73c92d7b6dd2b5e32 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h @@ -0,0 +1,193 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* chdtr.c + * + * Chi-square distribution + * + * + * + * SYNOPSIS: + * + * double df, x, y, chdtr(); + * + * y = chdtr( df, x ); + * + * + * + * DESCRIPTION: + * + * Returns the area under the left hand tail (from 0 to x) + * of the Chi square probability density function with + * v degrees of freedom. + * + * + * inf. + * - + * 1 | | v/2-1 -t/2 + * P( x | v ) = ----------- | t e dt + * v/2 - | | + * 2 | (v/2) - + * x + * + * where x is the Chi-square variable. + * + * The incomplete Gamma integral is used, according to the + * formula + * + * y = chdtr( v, x ) = igam( v/2.0, x/2.0 ). + * + * + * The arguments must both be positive. + * + * + * + * ACCURACY: + * + * See igam(). + * + * ERROR MESSAGES: + * + * message condition value returned + * chdtr domain x < 0 or v < 1 0.0 + */ +/* chdtrc() + * + * Complemented Chi-square distribution + * + * + * + * SYNOPSIS: + * + * double v, x, y, chdtrc(); + * + * y = chdtrc( v, x ); + * + * + * + * DESCRIPTION: + * + * Returns the area under the right hand tail (from x to + * infinity) of the Chi square probability density function + * with v degrees of freedom: + * + * + * inf. + * - + * 1 | | v/2-1 -t/2 + * P( x | v ) = ----------- | t e dt + * v/2 - | | + * 2 | (v/2) - + * x + * + * where x is the Chi-square variable. + * + * The incomplete Gamma integral is used, according to the + * formula + * + * y = chdtr( v, x ) = igamc( v/2.0, x/2.0 ). + * + * + * The arguments must both be positive. + * + * + * + * ACCURACY: + * + * See igamc(). + * + * ERROR MESSAGES: + * + * message condition value returned + * chdtrc domain x < 0 or v < 1 0.0 + */ +/* chdtri() + * + * Inverse of complemented Chi-square distribution + * + * + * + * SYNOPSIS: + * + * double df, x, y, chdtri(); + * + * x = chdtri( df, y ); + * + * + * + * + * DESCRIPTION: + * + * Finds the Chi-square argument x such that the integral + * from x to infinity of the Chi-square density is equal + * to the given cumulative probability y. + * + * This is accomplished using the inverse Gamma integral + * function and the relation + * + * x/2 = igamci( df/2, y ); + * + * + * + * + * ACCURACY: + * + * See igami.c. + * + * ERROR MESSAGES: + * + * message condition value returned + * chdtri domain y < 0 or y > 1 0.0 + * v < 1 + * + */ + +/* chdtr() */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "igam.h" +#include "igami.h" + +namespace xsf { +namespace cephes { + + XSF_HOST_DEVICE inline double chdtrc(double df, double x) { + + if (x < 0.0) + return 1.0; /* modified by T. Oliphant */ + return (igamc(df / 2.0, x / 2.0)); + } + + XSF_HOST_DEVICE inline double chdtr(double df, double x) { + + if ((x < 0.0)) { /* || (df < 1.0) ) */ + set_error("chdtr", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + return (igam(df / 2.0, x / 2.0)); + } + + XSF_HOST_DEVICE double chdtri(double df, double y) { + double x; + + if ((y < 0.0) || (y > 1.0)) { /* || (df < 1.0) ) */ + set_error("chdtri", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + + x = igamci(0.5 * df, y); + return (2.0 * x); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h new file mode 100644 index 0000000000000000000000000000000000000000..d7b162c5efc8e11f407c6108d55c117820e9e76d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h @@ -0,0 +1,87 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + * + * Since we support only IEEE-754 floating point numbers, conditional logic + * supporting other arithmetic types has been removed. + */ + +/* + * + * + * const.c + * + * Globally declared constants + * + * + * + * SYNOPSIS: + * + * extern double nameofconstant; + * + * + * + * + * DESCRIPTION: + * + * This file contains a number of mathematical constants and + * also some needed size parameters of the computer arithmetic. + * The values are supplied as arrays of hexadecimal integers + * for IEEE arithmetic, and in a normal decimal scientific notation for + * other machines. The particular notation used is determined + * by a symbol (IBMPC, or UNK) defined in the include file + * mconf.h. + * + * The default size parameters are as follows. + * + * For UNK mode: + * MACHEP = 1.38777878078144567553E-17 2**-56 + * MAXLOG = 8.8029691931113054295988E1 log(2**127) + * MINLOG = -8.872283911167299960540E1 log(2**-128) + * + * For IEEE arithmetic (IBMPC): + * MACHEP = 1.11022302462515654042E-16 2**-53 + * MAXLOG = 7.09782712893383996843E2 log(2**1024) + * MINLOG = -7.08396418532264106224E2 log(2**-1022) + * + * The global symbols for mathematical constants are + * SQ2OPI = 7.9788456080286535587989E-1 sqrt( 2/pi ) + * LOGSQ2 = 3.46573590279972654709E-1 log(2)/2 + * THPIO4 = 2.35619449019234492885 3*pi/4 + * + * These lists are subject to change. + */ +/* const.c */ + +/* + * Cephes Math Library Release 2.3: March, 1995 + * Copyright 1984, 1995 by Stephen L. Moshier + */ +#pragma once + +namespace xsf { +namespace cephes { + namespace detail { + constexpr std::uint64_t MAXITER = 500; + constexpr double MACHEP = 1.11022302462515654042E-16; // 2**-53 + constexpr double MAXLOG = 7.09782712893383996732E2; // log(DBL_MAX) + constexpr double MINLOG = -7.451332191019412076235E2; // log 2**-1022 + constexpr double SQRT1OPI = 5.64189583547756286948E-1; // sqrt( 1/pi) + constexpr double SQRT2OPI = 7.9788456080286535587989E-1; // sqrt( 2/pi ) + constexpr double SQRT2PI = 0.79788456080286535587989; // sqrt(2pi) + constexpr double LOGSQ2 = 3.46573590279972654709E-1; // log(2)/2 + constexpr double THPIO4 = 2.35619449019234492885; // 3*pi/4 + constexpr double SQRT3 = 1.732050807568877293527; // sqrt(3) + constexpr double PI180 = 1.74532925199432957692E-2; // pi/180 + constexpr double SQRTPI = 2.50662827463100050242E0; // sqrt(pi) + constexpr double LOGPI = 1.14472988584940017414; // log(pi) + constexpr double MAXGAM = 171.624376956302725; + constexpr double LOGSQRT2PI = 0.9189385332046727; // log(sqrt(pi)) + + // Following two added by SciPy developers. + // Euler's constant + constexpr double SCIPY_EULER = 0.577215664901532860606512090082402431; + // e as long double + constexpr long double SCIPY_El = 2.718281828459045235360287471352662498L; + } // namespace detail +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h new file mode 100644 index 0000000000000000000000000000000000000000..a455599b4a95b3c69d23df188669e84deac4e31c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h @@ -0,0 +1,293 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* ellie.c + * + * Incomplete elliptic integral of the second kind + * + * + * + * SYNOPSIS: + * + * double phi, m, y, ellie(); + * + * y = ellie( phi, m ); + * + * + * + * DESCRIPTION: + * + * Approximates the integral + * + * + * phi + * - + * | | + * | 2 + * E(phi_\m) = | sqrt( 1 - m sin t ) dt + * | + * | | + * - + * 0 + * + * of amplitude phi and modulus m, using the arithmetic - + * geometric mean algorithm. + * + * + * + * ACCURACY: + * + * Tested at random arguments with phi in [-10, 10] and m in + * [0, 1]. + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -10,10 150000 3.3e-15 1.4e-16 + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987, 1993 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +/* Copyright 2014, Eric W. Moore */ + +/* Incomplete elliptic integral of second kind */ +#pragma once + +#include "../config.h" +#include "const.h" +#include "ellpe.h" +#include "ellpk.h" +#include "unity.h" + +namespace xsf { +namespace cephes { + namespace detail { + + /* To calculate legendre's incomplete elliptical integral of the second kind for + * negative m, we use a power series in phi for small m*phi*phi, an asymptotic + * series in m for large m*phi*phi* and the relation to Carlson's symmetric + * integrals, R_F(x,y,z) and R_D(x,y,z). + * + * E(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0) + * - m * sin(phi)^3 * R_D(cos(phi)^2, 1 - m * sin(phi)^2, 1.0) / 3 + * + * = R_F(c-1, c-m, c) - m * R_D(c-1, c-m, c) / 3 + * + * where c = csc(phi)^2. We use the second form of this for (approximately) + * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we + * use the first form, accounting for the smallness of phi. + * + * The algorithm used is described in Carlson, B. C. Numerical computation of + * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227 + * Most variable names reflect Carlson's usage. + * + * In this routine, we assume m < 0 and 0 > phi > pi/2. + */ + XSF_HOST_DEVICE inline double ellie_neg_m(double phi, double m) { + double x, y, z, x1, y1, z1, ret, Q; + double A0f, Af, Xf, Yf, Zf, E2f, E3f, scalef; + double A0d, Ad, seriesn, seriesd, Xd, Yd, Zd, E2d, E3d, E4d, E5d, scaled; + int n = 0; + double mpp = (m * phi) * phi; + + if (-mpp < 1e-6 && phi < -m) { + return phi + (mpp * phi * phi / 30.0 - mpp * mpp / 40.0 - mpp / 6.0) * phi; + } + + if (-mpp > 1e6) { + double sm = std::sqrt(-m); + double sp = std::sin(phi); + double cp = std::cos(phi); + + double a = -cosm1(phi); + double b1 = std::log(4 * sp * sm / (1 + cp)); + double b = -(0.5 + b1) / 2.0 / m; + double c = (0.75 + cp / sp / sp - b1) / 16.0 / m / m; + return (a + b + c) * sm; + } + + if (phi > 1e-153 && m > -1e200) { + double s = std::sin(phi); + double csc2 = 1.0 / s / s; + scalef = 1.0; + scaled = m / 3.0; + x = 1.0 / std::tan(phi) / std::tan(phi); + y = csc2 - m; + z = csc2; + } else { + scalef = phi; + scaled = mpp * phi / 3.0; + x = 1.0; + y = 1 - mpp; + z = 1.0; + } + + if (x == y && x == z) { + return (scalef + scaled / x) / std::sqrt(x); + } + + A0f = (x + y + z) / 3.0; + Af = A0f; + A0d = (x + y + 3.0 * z) / 5.0; + Ad = A0d; + x1 = x; + y1 = y; + z1 = z; + seriesd = 0.0; + seriesn = 1.0; + /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps, + * it is ~338.38. */ + + /* N.B. This will evaluate its arguments multiple times. */ + Q = 400.0 * std::fmax(std::abs(A0f - x), std::fmax(std::abs(A0f - y), std::abs(A0f - z))); + + while (Q > std::abs(Af) && Q > std::abs(Ad) && n <= 100) { + double sx = std::sqrt(x1); + double sy = std::sqrt(y1); + double sz = std::sqrt(z1); + double lam = sx * sy + sx * sz + sy * sz; + seriesd += seriesn / (sz * (z1 + lam)); + x1 = (x1 + lam) / 4.0; + y1 = (y1 + lam) / 4.0; + z1 = (z1 + lam) / 4.0; + Af = (x1 + y1 + z1) / 3.0; + Ad = (Ad + lam) / 4.0; + n += 1; + Q /= 4.0; + seriesn /= 4.0; + } + + Xf = (A0f - x) / Af / (1 << 2 * n); + Yf = (A0f - y) / Af / (1 << 2 * n); + Zf = -(Xf + Yf); + + E2f = Xf * Yf - Zf * Zf; + E3f = Xf * Yf * Zf; + + ret = scalef * (1.0 - E2f / 10.0 + E3f / 14.0 + E2f * E2f / 24.0 - 3.0 * E2f * E3f / 44.0) / sqrt(Af); + + Xd = (A0d - x) / Ad / (1 << 2 * n); + Yd = (A0d - y) / Ad / (1 << 2 * n); + Zd = -(Xd + Yd) / 3.0; + + E2d = Xd * Yd - 6.0 * Zd * Zd; + E3d = (3 * Xd * Yd - 8.0 * Zd * Zd) * Zd; + E4d = 3.0 * (Xd * Yd - Zd * Zd) * Zd * Zd; + E5d = Xd * Yd * Zd * Zd * Zd; + + ret -= scaled * + (1.0 - 3.0 * E2d / 14.0 + E3d / 6.0 + 9.0 * E2d * E2d / 88.0 - 3.0 * E4d / 22.0 - + 9.0 * E2d * E3d / 52.0 + 3.0 * E5d / 26.0) / + (1 << 2 * n) / Ad / sqrt(Ad); + ret -= 3.0 * scaled * seriesd; + return ret; + } + + } // namespace detail + + XSF_HOST_DEVICE inline double ellie(double phi, double m) { + double a, b, c, e, temp; + double lphi, t, E, denom, npio2; + int d, mod, sign; + + if (std::isnan(phi) || std::isnan(m)) + return std::numeric_limits::quiet_NaN(); + if (m > 1.0) + return std::numeric_limits::quiet_NaN(); + ; + if (std::isinf(phi)) + return phi; + if (std::isinf(m)) + return -m; + if (m == 0.0) + return (phi); + lphi = phi; + npio2 = std::floor(lphi / M_PI_2); + if (std::fmod(std::abs(npio2), 2.0) == 1.0) + npio2 += 1; + lphi = lphi - npio2 * M_PI_2; + if (lphi < 0.0) { + lphi = -lphi; + sign = -1; + } else { + sign = 1; + } + a = 1.0 - m; + E = ellpe(m); + if (a == 0.0) { + temp = std::sin(lphi); + goto done; + } + if (a > 1.0) { + temp = detail::ellie_neg_m(lphi, m); + goto done; + } + + if (lphi < 0.135) { + double m11 = (((((-7.0 / 2816.0) * m + (5.0 / 1056.0)) * m - (7.0 / 2640.0)) * m + (17.0 / 41580.0)) * m - + (1.0 / 155925.0)) * + m; + double m9 = ((((-5.0 / 1152.0) * m + (1.0 / 144.0)) * m - (1.0 / 360.0)) * m + (1.0 / 5670.0)) * m; + double m7 = ((-m / 112.0 + (1.0 / 84.0)) * m - (1.0 / 315.0)) * m; + double m5 = (-m / 40.0 + (1.0 / 30)) * m; + double m3 = -m / 6.0; + double p2 = lphi * lphi; + + temp = ((((m11 * p2 + m9) * p2 + m7) * p2 + m5) * p2 + m3) * p2 * lphi + lphi; + goto done; + } + t = std::tan(lphi); + b = std::sqrt(a); + /* Thanks to Brian Fitzgerald + * for pointing out an instability near odd multiples of pi/2. */ + if (std::abs(t) > 10.0) { + /* Transform the amplitude */ + e = 1.0 / (b * t); + /* ... but avoid multiple recursions. */ + if (std::abs(e) < 10.0) { + e = std::atan(e); + temp = E + m * std::sin(lphi) * std::sin(e) - ellie(e, m); + goto done; + } + } + c = std::sqrt(m); + a = 1.0; + d = 1; + e = 0.0; + mod = 0; + + while (std::abs(c / a) > detail::MACHEP) { + temp = b / a; + lphi = lphi + atan(t * temp) + mod * M_PI; + denom = 1 - temp * t * t; + if (std::abs(denom) > 10 * detail::MACHEP) { + t = t * (1.0 + temp) / denom; + mod = (lphi + M_PI_2) / M_PI; + } else { + t = std::tan(lphi); + mod = static_cast(std::floor((lphi - std::atan(t)) / M_PI)); + } + c = (a - b) / 2.0; + temp = std::sqrt(a * b); + a = (a + b) / 2.0; + b = temp; + d += d; + e += c * std::sin(lphi); + } + + temp = E / ellpk(1.0 - m); + temp *= (std::atan(t) + mod * M_PI) / (d * a); + temp += e; + + done: + + if (sign < 0) + temp = -temp; + temp += npio2 * E; + return (temp); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h new file mode 100644 index 0000000000000000000000000000000000000000..c05b3ec76c2e9a3acbc947842e0a849f5ba837e0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h @@ -0,0 +1,251 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* ellik.c + * + * Incomplete elliptic integral of the first kind + * + * + * + * SYNOPSIS: + * + * double phi, m, y, ellik(); + * + * y = ellik( phi, m ); + * + * + * + * DESCRIPTION: + * + * Approximates the integral + * + * + * + * phi + * - + * | | + * | dt + * F(phi | m) = | ------------------ + * | 2 + * | | sqrt( 1 - m sin t ) + * - + * 0 + * + * of amplitude phi and modulus m, using the arithmetic - + * geometric mean algorithm. + * + * + * + * + * ACCURACY: + * + * Tested at random points with m in [0, 1] and phi as indicated. + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -10,10 200000 7.4e-16 1.0e-16 + * + * + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +/* Copyright 2014, Eric W. Moore */ + +/* Incomplete elliptic integral of first kind */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" +#include "ellpk.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* To calculate legendre's incomplete elliptical integral of the first kind for + * negative m, we use a power series in phi for small m*phi*phi, an asymptotic + * series in m for large m*phi*phi* and the relation to Carlson's symmetric + * integral of the first kind. + * + * F(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0) + * = R_F(c-1, c-m, c) + * + * where c = csc(phi)^2. We use the second form of this for (approximately) + * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we + * use the first form, accounting for the smallness of phi. + * + * The algorithm used is described in Carlson, B. C. Numerical computation of + * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227 + * Most variable names reflect Carlson's usage. + * + * In this routine, we assume m < 0 and 0 > phi > pi/2. + */ + XSF_HOST_DEVICE inline double ellik_neg_m(double phi, double m) { + double x, y, z, x1, y1, z1, A0, A, Q, X, Y, Z, E2, E3, scale; + int n = 0; + double mpp = (m * phi) * phi; + + if (-mpp < 1e-6 && phi < -m) { + return phi + (-mpp * phi * phi / 30.0 + 3.0 * mpp * mpp / 40.0 + mpp / 6.0) * phi; + } + + if (-mpp > 4e7) { + double sm = std::sqrt(-m); + double sp = std::sin(phi); + double cp = std::cos(phi); + + double a = std::log(4 * sp * sm / (1 + cp)); + double b = -(1 + cp / sp / sp - a) / 4 / m; + return (a + b) / sm; + } + + if (phi > 1e-153 && m > -1e305) { + double s = std::sin(phi); + double csc2 = 1.0 / (s * s); + scale = 1.0; + x = 1.0 / (std::tan(phi) * std::tan(phi)); + y = csc2 - m; + z = csc2; + } else { + scale = phi; + x = 1.0; + y = 1 - m * scale * scale; + z = 1.0; + } + + if (x == y && x == z) { + return scale / std::sqrt(x); + } + + A0 = (x + y + z) / 3.0; + A = A0; + x1 = x; + y1 = y; + z1 = z; + /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps, + * it is ~338.38. */ + Q = 400.0 * std::fmax(std::abs(A0 - x), std::fmax(std::abs(A0 - y), std::abs(A0 - z))); + + while (Q > std::abs(A) && n <= 100) { + double sx = std::sqrt(x1); + double sy = std::sqrt(y1); + double sz = std::sqrt(z1); + double lam = sx * sy + sx * sz + sy * sz; + x1 = (x1 + lam) / 4.0; + y1 = (y1 + lam) / 4.0; + z1 = (z1 + lam) / 4.0; + A = (x1 + y1 + z1) / 3.0; + n += 1; + Q /= 4; + } + X = (A0 - x) / A / (1 << 2 * n); + Y = (A0 - y) / A / (1 << 2 * n); + Z = -(X + Y); + + E2 = X * Y - Z * Z; + E3 = X * Y * Z; + + return scale * (1.0 - E2 / 10.0 + E3 / 14.0 + E2 * E2 / 24.0 - 3.0 * E2 * E3 / 44.0) / sqrt(A); + } + + } // namespace detail + + XSF_HOST_DEVICE inline double ellik(double phi, double m) { + double a, b, c, e, temp, t, K, denom, npio2; + int d, mod, sign; + + if (std::isnan(phi) || std::isnan(m)) + return std::numeric_limits::quiet_NaN(); + if (m > 1.0) + return std::numeric_limits::quiet_NaN(); + if (std::isinf(phi) || std::isinf(m)) { + if (std::isinf(m) && std::isfinite(phi)) + return 0.0; + else if (std::isinf(phi) && std::isfinite(m)) + return phi; + else + return std::numeric_limits::quiet_NaN(); + } + if (m == 0.0) + return (phi); + a = 1.0 - m; + if (a == 0.0) { + if (std::abs(phi) >= (double) M_PI_2) { + set_error("ellik", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::infinity()); + } + /* DLMF 19.6.8, and 4.23.42 */ + return std::asinh(std::tan(phi)); + } + npio2 = floor(phi / M_PI_2); + if (std::fmod(std::abs(npio2), 2.0) == 1.0) + npio2 += 1; + if (npio2 != 0.0) { + K = ellpk(a); + phi = phi - npio2 * M_PI_2; + } else + K = 0.0; + if (phi < 0.0) { + phi = -phi; + sign = -1; + } else + sign = 0; + if (a > 1.0) { + temp = detail::ellik_neg_m(phi, m); + goto done; + } + b = std::sqrt(a); + t = std::tan(phi); + if (std::abs(t) > 10.0) { + /* Transform the amplitude */ + e = 1.0 / (b * t); + /* ... but avoid multiple recursions. */ + if (std::abs(e) < 10.0) { + e = std::atan(e); + if (npio2 == 0) + K = ellpk(a); + temp = K - ellik(e, m); + goto done; + } + } + a = 1.0; + c = std::sqrt(m); + d = 1; + mod = 0; + + while (std::abs(c / a) > detail::MACHEP) { + temp = b / a; + phi = phi + atan(t * temp) + mod * M_PI; + denom = 1.0 - temp * t * t; + if (std::abs(denom) > 10 * detail::MACHEP) { + t = t * (1.0 + temp) / denom; + mod = (phi + M_PI_2) / M_PI; + } else { + t = std::tan(phi); + mod = static_cast(std::floor((phi - std::atan(t)) / M_PI)); + } + c = (a - b) / 2.0; + temp = std::sqrt(a * b); + a = (a + b) / 2.0; + b = temp; + d += d; + } + + temp = (std::atan(t) + mod * M_PI) / (d * a); + + done: + if (sign < 0) + temp = -temp; + temp += npio2 * K; + return (temp); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h new file mode 100644 index 0000000000000000000000000000000000000000..bc7c51f11acb13179aaffb301d052308722f8cfa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h @@ -0,0 +1,107 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* ellpe.c + * + * Complete elliptic integral of the second kind + * + * + * + * SYNOPSIS: + * + * double m, y, ellpe(); + * + * y = ellpe( m ); + * + * + * + * DESCRIPTION: + * + * Approximates the integral + * + * + * pi/2 + * - + * | | 2 + * E(m) = | sqrt( 1 - m sin t ) dt + * | | + * - + * 0 + * + * Where m = 1 - m1, using the approximation + * + * P(x) - x log x Q(x). + * + * Though there are no singularities, the argument m1 is used + * internally rather than m for compatibility with ellpk(). + * + * E(1) = 1; E(0) = pi/2. + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 1 10000 2.1e-16 7.3e-17 + * + * + * ERROR MESSAGES: + * + * message condition value returned + * ellpe domain x<0, x>1 0.0 + * + */ + +/* ellpe.c */ + +/* Elliptic integral of second kind */ + +/* + * Cephes Math Library, Release 2.1: February, 1989 + * Copyright 1984, 1987, 1989 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + * + * Feb, 2002: altered by Travis Oliphant + * so that it is called with argument m + * (which gets immediately converted to m1 = 1-m) + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double ellpe_P[] = {1.53552577301013293365E-4, 2.50888492163602060990E-3, 8.68786816565889628429E-3, + 1.07350949056076193403E-2, 7.77395492516787092951E-3, 7.58395289413514708519E-3, + 1.15688436810574127319E-2, 2.18317996015557253103E-2, 5.68051945617860553470E-2, + 4.43147180560990850618E-1, 1.00000000000000000299E0}; + + constexpr double ellpe_Q[] = {3.27954898576485872656E-5, 1.00962792679356715133E-3, 6.50609489976927491433E-3, + 1.68862163993311317300E-2, 2.61769742454493659583E-2, 3.34833904888224918614E-2, + 4.27180926518931511717E-2, 5.85936634471101055642E-2, 9.37499997197644278445E-2, + 2.49999999999888314361E-1}; + + } // namespace detail + + XSF_HOST_DEVICE inline double ellpe(double x) { + x = 1.0 - x; + if (x <= 0.0) { + if (x == 0.0) + return (1.0); + set_error("ellpe", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + if (x > 1.0) { + return ellpe(1.0 - 1 / x) * std::sqrt(x); + } + return (polevl(x, detail::ellpe_P, 10) - std::log(x) * (x * polevl(x, detail::ellpe_Q, 9))); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h new file mode 100644 index 0000000000000000000000000000000000000000..39ebf7e80b193d385acb45feead4b91632830642 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h @@ -0,0 +1,117 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* ellpk.c + * + * Complete elliptic integral of the first kind + * + * + * + * SYNOPSIS: + * + * double m1, y, ellpk(); + * + * y = ellpk( m1 ); + * + * + * + * DESCRIPTION: + * + * Approximates the integral + * + * + * + * pi/2 + * - + * | | + * | dt + * K(m) = | ------------------ + * | 2 + * | | sqrt( 1 - m sin t ) + * - + * 0 + * + * where m = 1 - m1, using the approximation + * + * P(x) - log x Q(x). + * + * The argument m1 is used internally rather than m so that the logarithmic + * singularity at m = 1 will be shifted to the origin; this + * preserves maximum accuracy. + * + * K(0) = pi/2. + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,1 30000 2.5e-16 6.8e-17 + * + * ERROR MESSAGES: + * + * message condition value returned + * ellpk domain x<0, x>1 0.0 + * + */ + +/* ellpk.c */ + +/* + * Cephes Math Library, Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double ellpk_P[] = {1.37982864606273237150E-4, 2.28025724005875567385E-3, 7.97404013220415179367E-3, + 9.85821379021226008714E-3, 6.87489687449949877925E-3, 6.18901033637687613229E-3, + 8.79078273952743772254E-3, 1.49380448916805252718E-2, 3.08851465246711995998E-2, + 9.65735902811690126535E-2, 1.38629436111989062502E0}; + + constexpr double ellpk_Q[] = {2.94078955048598507511E-5, 9.14184723865917226571E-4, 5.94058303753167793257E-3, + 1.54850516649762399335E-2, 2.39089602715924892727E-2, 3.01204715227604046988E-2, + 3.73774314173823228969E-2, 4.88280347570998239232E-2, 7.03124996963957469739E-2, + 1.24999999999870820058E-1, 4.99999999999999999821E-1}; + + constexpr double ellpk_C1 = 1.3862943611198906188E0; /* log(4) */ + + } // namespace detail + + XSF_HOST_DEVICE inline double ellpk(double x) { + + if (x < 0.0) { + set_error("ellpk", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + + if (x > 1.0) { + if (std::isinf(x)) { + return 0.0; + } + return ellpk(1 / x) / std::sqrt(x); + } + + if (x > detail::MACHEP) { + return (polevl(x, detail::ellpk_P, 10) - std::log(x) * polevl(x, detail::ellpk_Q, 10)); + } else { + if (x == 0.0) { + set_error("ellpk", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::infinity()); + } else { + return (detail::ellpk_C1 - 0.5 * std::log(x)); + } + } + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h new file mode 100644 index 0000000000000000000000000000000000000000..8b0b07eab7a94fb1519566da4ef9036fb67edec6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h @@ -0,0 +1,260 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* expn.c + * + * Exponential integral En + * + * + * + * SYNOPSIS: + * + * int n; + * double x, y, expn(); + * + * y = expn( n, x ); + * + * + * + * DESCRIPTION: + * + * Evaluates the exponential integral + * + * inf. + * - + * | | -xt + * | e + * E (x) = | ---- dt. + * n | n + * | | t + * - + * 1 + * + * + * Both n and x must be nonnegative. + * + * The routine employs either a power series, a continued + * fraction, or an asymptotic formula depending on the + * relative values of n and x. + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 10000 1.7e-15 3.6e-16 + * + */ + +/* expn.c */ + +/* Cephes Math Library Release 1.1: March, 1985 + * Copyright 1985 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */ + +/* Sources + * [1] NIST, "The Digital Library of Mathematical Functions", dlmf.nist.gov + */ + +/* Scipy changes: + * - 09-10-2016: improved asymptotic expansion for large n + */ + +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" +#include "rgamma.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr int expn_nA = 13; + constexpr double expn_A0[] = {1.00000000000000000}; + constexpr double expn_A1[] = {1.00000000000000000}; + constexpr double expn_A2[] = {-2.00000000000000000, 1.00000000000000000}; + constexpr double expn_A3[] = {6.00000000000000000, -8.00000000000000000, 1.00000000000000000}; + constexpr double expn_A4[] = {-24.0000000000000000, 58.0000000000000000, -22.0000000000000000, + 1.00000000000000000}; + constexpr double expn_A5[] = {120.000000000000000, -444.000000000000000, 328.000000000000000, + -52.0000000000000000, 1.00000000000000000}; + constexpr double expn_A6[] = {-720.000000000000000, 3708.00000000000000, -4400.00000000000000, + 1452.00000000000000, -114.000000000000000, 1.00000000000000000}; + constexpr double expn_A7[] = {5040.00000000000000, -33984.0000000000000, 58140.0000000000000, + -32120.0000000000000, 5610.00000000000000, -240.000000000000000, + 1.00000000000000000}; + constexpr double expn_A8[] = {-40320.0000000000000, 341136.000000000000, -785304.000000000000, + 644020.000000000000, -195800.000000000000, 19950.0000000000000, + -494.000000000000000, 1.00000000000000000}; + constexpr double expn_A9[] = {362880.000000000000, -3733920.00000000000, 11026296.0000000000, + -12440064.0000000000, 5765500.00000000000, -1062500.00000000000, + 67260.0000000000000, -1004.00000000000000, 1.00000000000000000}; + constexpr double expn_A10[] = {-3628800.00000000000, 44339040.0000000000, -162186912.000000000, + 238904904.000000000, -155357384.000000000, 44765000.0000000000, + -5326160.00000000000, 218848.000000000000, -2026.00000000000000, + 1.00000000000000000}; + constexpr double expn_A11[] = {39916800.0000000000, -568356480.000000000, 2507481216.00000000, + -4642163952.00000000, 4002695088.00000000, -1648384304.00000000, + 314369720.000000000, -25243904.0000000000, 695038.000000000000, + -4072.00000000000000, 1.00000000000000000}; + constexpr double expn_A12[] = {-479001600.000000000, 7827719040.00000000, -40788301824.0000000, + 92199790224.0000000, -101180433024.000000, 56041398784.0000000, + -15548960784.0000000, 2051482776.00000000, -114876376.000000000, + 2170626.00000000000, -8166.00000000000000, 1.00000000000000000}; + constexpr const double *expn_A[] = {expn_A0, expn_A1, expn_A2, expn_A3, expn_A4, expn_A5, expn_A6, + expn_A7, expn_A8, expn_A9, expn_A10, expn_A11, expn_A12}; + constexpr int expn_Adegs[] = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + + /* Asymptotic expansion for large n, DLMF 8.20(ii) */ + XSF_HOST_DEVICE double expn_large_n(int n, double x) { + int k; + double p = n; + double lambda = x / p; + double multiplier = 1 / p / (lambda + 1) / (lambda + 1); + double fac = 1; + double res = 1; /* A[0] = 1 */ + double expfac, term; + + expfac = std::exp(-lambda * p) / (lambda + 1) / p; + if (expfac == 0) { + set_error("expn", SF_ERROR_UNDERFLOW, NULL); + return 0; + } + + /* Do the k = 1 term outside the loop since A[1] = 1 */ + fac *= multiplier; + res += fac; + + for (k = 2; k < expn_nA; k++) { + fac *= multiplier; + term = fac * polevl(lambda, expn_A[k], expn_Adegs[k]); + res += term; + if (std::abs(term) < MACHEP * std::abs(res)) { + break; + } + } + + return expfac * res; + } + } // namespace detail + + XSF_HOST_DEVICE double expn(int n, double x) { + double ans, r, t, yk, xk; + double pk, pkm1, pkm2, qk, qkm1, qkm2; + double psi, z; + int i, k; + constexpr double big = 1.44115188075855872E+17; + + if (std::isnan(x)) { + return std::numeric_limits::quiet_NaN(); + } else if (n < 0 || x < 0) { + set_error("expn", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + if (x > detail::MAXLOG) { + return (0.0); + } + + if (x == 0.0) { + if (n < 2) { + set_error("expn", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } else { + return (1.0 / (n - 1.0)); + } + } + + if (n == 0) { + return (std::exp(-x) / x); + } + + /* Asymptotic expansion for large n, DLMF 8.20(ii) */ + if (n > 50) { + ans = detail::expn_large_n(n, x); + return ans; + } + + /* Continued fraction, DLMF 8.19.17 */ + if (x > 1.0) { + k = 1; + pkm2 = 1.0; + qkm2 = x; + pkm1 = 1.0; + qkm1 = x + n; + ans = pkm1 / qkm1; + + do { + k += 1; + if (k & 1) { + yk = 1.0; + xk = n + (k - 1) / 2; + } else { + yk = x; + xk = k / 2; + } + pk = pkm1 * yk + pkm2 * xk; + qk = qkm1 * yk + qkm2 * xk; + if (qk != 0) { + r = pk / qk; + t = std::abs((ans - r) / r); + ans = r; + } else { + t = 1.0; + } + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if (std::abs(pk) > big) { + pkm2 /= big; + pkm1 /= big; + qkm2 /= big; + qkm1 /= big; + } + } while (t > detail::MACHEP); + + ans *= std::exp(-x); + return ans; + } + + /* Power series expansion, DLMF 8.19.8 */ + psi = -detail::SCIPY_EULER - std::log(x); + for (i = 1; i < n; i++) { + psi = psi + 1.0 / i; + } + + z = -x; + xk = 0.0; + yk = 1.0; + pk = 1.0 - n; + if (n == 1) { + ans = 0.0; + } else { + ans = 1.0 / pk; + } + do { + xk += 1.0; + yk *= z / xk; + pk += 1.0; + if (pk != 0.0) { + ans += yk / pk; + } + if (ans != 0.0) + t = std::abs(yk / ans); + else + t = 1.0; + } while (t > detail::MACHEP); + k = xk; + t = n; + r = n - 1; + ans = (std::pow(z, r) * psi * rgamma(t)) - ans; + return ans; + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h new file mode 100644 index 0000000000000000000000000000000000000000..1ede1571a67ec9ce54bb6aa1afa1f17f5708f0c0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h @@ -0,0 +1,398 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* + * Gamma function + * + * + * + * SYNOPSIS: + * + * double x, y, Gamma(); + * + * y = Gamma( x ); + * + * + * + * DESCRIPTION: + * + * Returns Gamma function of the argument. The result is + * correctly signed. + * + * Arguments |x| <= 34 are reduced by recurrence and the function + * approximated by a rational function of degree 6/7 in the + * interval (2,3). Large arguments are handled by Stirling's + * formula. Large negative arguments are made positive using + * a reflection formula. + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -170,-33 20000 2.3e-15 3.3e-16 + * IEEE -33, 33 20000 9.4e-16 2.2e-16 + * IEEE 33, 171.6 20000 2.3e-15 3.2e-16 + * + * Error for arguments outside the test range will be larger + * owing to error amplification by the exponential function. + * + */ + +/* lgam() + * + * Natural logarithm of Gamma function + * + * + * + * SYNOPSIS: + * + * double x, y, lgam(); + * + * y = lgam( x ); + * + * + * + * DESCRIPTION: + * + * Returns the base e (2.718...) logarithm of the absolute + * value of the Gamma function of the argument. + * + * For arguments greater than 13, the logarithm of the Gamma + * function is approximated by the logarithmic version of + * Stirling's formula using a polynomial approximation of + * degree 4. Arguments between -33 and +33 are reduced by + * recurrence to the interval [2,3] of a rational approximation. + * The cosecant reflection formula is employed for arguments + * less than -33. + * + * Arguments greater than MAXLGM return INFINITY and an error + * message. MAXLGM = 2.556348e305 for IEEE arithmetic. + * + * + * + * ACCURACY: + * + * + * arithmetic domain # trials peak rms + * IEEE 0, 3 28000 5.4e-16 1.1e-16 + * IEEE 2.718, 2.556e305 40000 3.5e-16 8.3e-17 + * The error criterion was relative when the function magnitude + * was greater than one but absolute when it was less than one. + * + * The following test used the relative error criterion, though + * at certain points the relative error could be much higher than + * indicated. + * IEEE -200, -4 10000 4.8e-16 1.3e-16 + * + */ + +/* + * Cephes Math Library Release 2.2: July, 1992 + * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" +#include "polevl.h" +#include "trig.h" + +namespace xsf { +namespace cephes { + namespace detail { + constexpr double gamma_P[] = {1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2, + 4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1, + 9.99999999999999996796E-1}; + + constexpr double gamma_Q[] = {-2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3, + 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1, + 7.14304917030273074085E-2, 1.00000000000000000320E0}; + + /* Stirling's formula for the Gamma function */ + constexpr double gamma_STIR[5] = { + 7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3, + 3.47222221605458667310E-3, 8.33333333333482257126E-2, + }; + + constexpr double MAXSTIR = 143.01608; + + /* Gamma function computed by Stirling's formula. + * The polynomial STIR is valid for 33 <= x <= 172. + */ + XSF_HOST_DEVICE inline double stirf(double x) { + double y, w, v; + + if (x >= MAXGAM) { + return (std::numeric_limits::infinity()); + } + w = 1.0 / x; + w = 1.0 + w * xsf::cephes::polevl(w, gamma_STIR, 4); + y = std::exp(x); + if (x > MAXSTIR) { /* Avoid overflow in pow() */ + v = std::pow(x, 0.5 * x - 0.25); + y = v * (v / y); + } else { + y = std::pow(x, x - 0.5) / y; + } + y = SQRTPI * y * w; + return (y); + } + } // namespace detail + + XSF_HOST_DEVICE inline double Gamma(double x) { + double p, q, z; + int i; + int sgngam = 1; + + if (!std::isfinite(x)) { + if (x > 0) { + // gamma(+inf) = +inf + return x; + } + // gamma(NaN) and gamma(-inf) both should equal NaN. + return std::numeric_limits::quiet_NaN(); + } + + if (x == 0) { + /* For pole at zero, value depends on sign of zero. + * +inf when approaching from right, -inf when approaching + * from left. */ + return std::copysign(std::numeric_limits::infinity(), x); + } + + q = std::abs(x); + + if (q > 33.0) { + if (x < 0.0) { + p = std::floor(q); + if (p == q) { + // x is a negative integer. This is a pole. + set_error("Gamma", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::quiet_NaN()); + } + i = p; + if ((i & 1) == 0) { + sgngam = -1; + } + z = q - p; + if (z > 0.5) { + p += 1.0; + z = q - p; + } + z = q * sinpi(z); + if (z == 0.0) { + return (sgngam * std::numeric_limits::infinity()); + } + z = std::abs(z); + z = M_PI / (z * detail::stirf(q)); + } else { + z = detail::stirf(x); + } + return (sgngam * z); + } + + z = 1.0; + while (x >= 3.0) { + x -= 1.0; + z *= x; + } + + while (x < 0.0) { + if (x > -1.E-9) { + goto small; + } + z /= x; + x += 1.0; + } + + while (x < 2.0) { + if (x < 1.e-9) { + goto small; + } + z /= x; + x += 1.0; + } + + if (x == 2.0) { + return (z); + } + + x -= 2.0; + p = polevl(x, detail::gamma_P, 6); + q = polevl(x, detail::gamma_Q, 7); + return (z * p / q); + + small: + if (x == 0.0) { + /* For this to have happened, x must have started as a negative integer. */ + set_error("Gamma", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::quiet_NaN()); + } else + return (z / ((1.0 + 0.5772156649015329 * x) * x)); + } + + namespace detail { + /* A[]: Stirling's formula expansion of log Gamma + * B[], C[]: log Gamma function between 2 and 3 + */ + constexpr double gamma_A[] = {8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4, + -2.77777777730099687205E-3, 8.33333333333331927722E-2}; + + constexpr double gamma_B[] = {-1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5, + -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5}; + + constexpr double gamma_C[] = { + /* 1.00000000000000000000E0, */ + -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5, + -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6}; + + /* log( sqrt( 2*pi ) ) */ + constexpr double LS2PI = 0.91893853320467274178; + + constexpr double MAXLGM = 2.556348e305; + + /* Disable optimizations for this function on 32 bit systems when compiling with GCC. + * We've found that enabling optimizations can result in degraded precision + * for this asymptotic approximation in that case. */ +#if defined(__GNUC__) && defined(__i386__) +#pragma GCC push_options +#pragma GCC optimize("00") +#endif + XSF_HOST_DEVICE inline double lgam_large_x(double x) { + double q = (x - 0.5) * std::log(x) - x + LS2PI; + if (x > 1.0e8) { + return (q); + } + double p = 1.0 / (x * x); + p = ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) / x; + return q + p; + } +#if defined(__GNUC__) && defined(__i386__) +#pragma GCC pop_options +#endif + + XSF_HOST_DEVICE inline double lgam_sgn(double x, int *sign) { + double p, q, u, w, z; + int i; + + *sign = 1; + + if (!std::isfinite(x)) { + return x; + } + + if (x < -34.0) { + q = -x; + w = lgam_sgn(q, sign); + p = std::floor(q); + if (p == q) { + lgsing: + set_error("lgam", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::infinity()); + } + i = p; + if ((i & 1) == 0) { + *sign = -1; + } else { + *sign = 1; + } + z = q - p; + if (z > 0.5) { + p += 1.0; + z = p - q; + } + z = q * sinpi(z); + if (z == 0.0) { + goto lgsing; + } + /* z = log(M_PI) - log( z ) - w; */ + z = LOGPI - std::log(z) - w; + return (z); + } + + if (x < 13.0) { + z = 1.0; + p = 0.0; + u = x; + while (u >= 3.0) { + p -= 1.0; + u = x + p; + z *= u; + } + while (u < 2.0) { + if (u == 0.0) { + goto lgsing; + } + z /= u; + p += 1.0; + u = x + p; + } + if (z < 0.0) { + *sign = -1; + z = -z; + } else { + *sign = 1; + } + if (u == 2.0) { + return (std::log(z)); + } + p -= 2.0; + x = x + p; + p = x * polevl(x, gamma_B, 5) / p1evl(x, gamma_C, 6); + return (std::log(z) + p); + } + + if (x > MAXLGM) { + return (*sign * std::numeric_limits::infinity()); + } + + if (x >= 1000.0) { + return lgam_large_x(x); + } + + q = (x - 0.5) * std::log(x) - x + LS2PI; + p = 1.0 / (x * x); + return q + polevl(p, gamma_A, 4) / x; + } + } // namespace detail + + /* Logarithm of Gamma function */ + XSF_HOST_DEVICE inline double lgam(double x) { + int sign; + return detail::lgam_sgn(x, &sign); + } + + /* Sign of the Gamma function */ + XSF_HOST_DEVICE inline double gammasgn(double x) { + double fx; + + if (std::isnan(x)) { + return x; + } + if (x > 0) { + return 1.0; + } + if (x == 0) { + return std::copysign(1.0, x); + } + if (std::isinf(x)) { + // x > 0 case handled, so x must be negative infinity. + return std::numeric_limits::quiet_NaN(); + } + fx = std::floor(x); + if (x - fx == 0.0) { + return std::numeric_limits::quiet_NaN(); + } + // sign of gamma for x in (-n, -n+1) for positive integer n is (-1)^n. + if (static_cast(fx) % 2) { + return -1.0; + } + return 1.0; + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h new file mode 100644 index 0000000000000000000000000000000000000000..f9ec54bb20326552f5748ad9360dfecfbe18d660 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h @@ -0,0 +1,596 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* hyp2f1.c + * + * Gauss hypergeometric function F + * 2 1 + * + * + * SYNOPSIS: + * + * double a, b, c, x, y, hyp2f1(); + * + * y = hyp2f1( a, b, c, x ); + * + * + * DESCRIPTION: + * + * + * hyp2f1( a, b, c, x ) = F ( a, b; c; x ) + * 2 1 + * + * inf. + * - a(a+1)...(a+k) b(b+1)...(b+k) k+1 + * = 1 + > ----------------------------- x . + * - c(c+1)...(c+k) (k+1)! + * k = 0 + * + * Cases addressed are + * Tests and escapes for negative integer a, b, or c + * Linear transformation if c - a or c - b negative integer + * Special case c = a or c = b + * Linear transformation for x near +1 + * Transformation for x < -0.5 + * Psi function expansion if x > 0.5 and c - a - b integer + * Conditionally, a recurrence on c to make c-a-b > 0 + * + * x < -1 AMS 15.3.7 transformation applied (Travis Oliphant) + * valid for b,a,c,(b-a) != integer and (c-a),(c-b) != negative integer + * + * x >= 1 is rejected (unless special cases are present) + * + * The parameters a, b, c are considered to be integer + * valued if they are within 1.0e-14 of the nearest integer + * (1.0e-13 for IEEE arithmetic). + * + * ACCURACY: + * + * + * Relative error (-1 < x < 1): + * arithmetic domain # trials peak rms + * IEEE -1,7 230000 1.2e-11 5.2e-14 + * + * Several special cases also tested with a, b, c in + * the range -7 to 7. + * + * ERROR MESSAGES: + * + * A "partial loss of precision" message is printed if + * the internally estimated relative error exceeds 1^-12. + * A "singularity" message is printed on overflow or + * in cases not addressed (such as x < -1). + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier + */ + +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "gamma.h" +#include "rgamma.h" +#include "psi.h" + +namespace xsf { +namespace cephes { + + namespace detail { + constexpr double hyp2f1_EPS = 1.0e-13; + + constexpr double hyp2f1_ETHRESH = 1.0e-12; + constexpr std::uint64_t hyp2f1_MAXITER = 10000; + + /* hys2f1 and hyp2f1ra depend on each other, so we need this prototype */ + XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss); + + /* Defining power series expansion of Gauss hypergeometric function */ + /* The `loss` parameter estimates loss of significance */ + XSF_HOST_DEVICE double hys2f1(double a, double b, double c, double x, double *loss) { + double f, g, h, k, m, s, u, umax; + std::uint64_t i; + int ib, intflag = 0; + + if (std::abs(b) > std::abs(a)) { + /* Ensure that |a| > |b| ... */ + f = b; + b = a; + a = f; + } + + ib = std::round(b); + + if (std::abs(b - ib) < hyp2f1_EPS && ib <= 0 && std::abs(b) < std::abs(a)) { + /* .. except when `b` is a smaller negative integer */ + f = b; + b = a; + a = f; + intflag = 1; + } + + if ((std::abs(a) > std::abs(c) + 1 || intflag) && std::abs(c - a) > 2 && std::abs(a) > 2) { + /* |a| >> |c| implies that large cancellation error is to be expected. + * + * We try to reduce it with the recurrence relations + */ + return hyp2f1ra(a, b, c, x, loss); + } + + i = 0; + umax = 0.0; + f = a; + g = b; + h = c; + s = 1.0; + u = 1.0; + k = 0.0; + do { + if (std::abs(h) < hyp2f1_EPS) { + *loss = 1.0; + return std::numeric_limits::infinity(); + } + m = k + 1.0; + u = u * ((f + k) * (g + k) * x / ((h + k) * m)); + s += u; + k = std::abs(u); /* remember largest term summed */ + if (k > umax) + umax = k; + k = m; + if (++i > hyp2f1_MAXITER) { /* should never happen */ + *loss = 1.0; + return (s); + } + } while (s == 0 || std::abs(u / s) > MACHEP); + + /* return estimated relative error */ + *loss = (MACHEP * umax) / fabs(s) + (MACHEP * i); + + return (s); + } + + /* Apply transformations for |x| near 1 then call the power series */ + XSF_HOST_DEVICE double hyt2f1(double a, double b, double c, double x, double *loss) { + double p, q, r, s, t, y, w, d, err, err1; + double ax, id, d1, d2, e, y1; + int i, aid, sign; + + int ia, ib, neg_int_a = 0, neg_int_b = 0; + + ia = std::round(a); + ib = std::round(b); + + if (a <= 0 && std::abs(a - ia) < hyp2f1_EPS) { /* a is a negative integer */ + neg_int_a = 1; + } + + if (b <= 0 && std::abs(b - ib) < hyp2f1_EPS) { /* b is a negative integer */ + neg_int_b = 1; + } + + err = 0.0; + s = 1.0 - x; + if (x < -0.5 && !(neg_int_a || neg_int_b)) { + if (b > a) + y = std::pow(s, -a) * hys2f1(a, c - b, c, -x / s, &err); + + else + y = std::pow(s, -b) * hys2f1(c - a, b, c, -x / s, &err); + + goto done; + } + + d = c - a - b; + id = std::round(d); /* nearest integer to d */ + + if (x > 0.9 && !(neg_int_a || neg_int_b)) { + if (std::abs(d - id) > MACHEP) { + int sgngam; + + /* test for integer c-a-b */ + /* Try the power series first */ + y = hys2f1(a, b, c, x, &err); + if (err < hyp2f1_ETHRESH) { + goto done; + } + /* If power series fails, then apply AMS55 #15.3.6 */ + q = hys2f1(a, b, 1.0 - d, s, &err); + sign = 1; + w = lgam_sgn(d, &sgngam); + sign *= sgngam; + w -= lgam_sgn(c - a, &sgngam); + sign *= sgngam; + w -= lgam_sgn(c - b, &sgngam); + sign *= sgngam; + q *= sign * std::exp(w); + r = std::pow(s, d) * hys2f1(c - a, c - b, d + 1.0, s, &err1); + sign = 1; + w = lgam_sgn(-d, &sgngam); + sign *= sgngam; + w -= lgam_sgn(a, &sgngam); + sign *= sgngam; + w -= lgam_sgn(b, &sgngam); + sign *= sgngam; + r *= sign * std::exp(w); + y = q + r; + + q = std::abs(q); /* estimate cancellation error */ + r = std::abs(r); + if (q > r) { + r = q; + } + err += err1 + (MACHEP * r) / y; + + y *= xsf::cephes::Gamma(c); + goto done; + } else { + /* Psi function expansion, AMS55 #15.3.10, #15.3.11, #15.3.12 + * + * Although AMS55 does not explicitly state it, this expansion fails + * for negative integer a or b, since the psi and Gamma functions + * involved have poles. + */ + + if (id >= 0.0) { + e = d; + d1 = d; + d2 = 0.0; + aid = id; + } else { + e = -d; + d1 = 0.0; + d2 = d; + aid = -id; + } + + ax = std::log(s); + + /* sum for t = 0 */ + y = xsf::cephes::psi(1.0) + xsf::cephes::psi(1.0 + e) - xsf::cephes::psi(a + d1) - + xsf::cephes::psi(b + d1) - ax; + y *= xsf::cephes::rgamma(e + 1.0); + + p = (a + d1) * (b + d1) * s * xsf::cephes::rgamma(e + 2.0); /* Poch for t=1 */ + t = 1.0; + do { + r = xsf::cephes::psi(1.0 + t) + xsf::cephes::psi(1.0 + t + e) - + xsf::cephes::psi(a + t + d1) - xsf::cephes::psi(b + t + d1) - ax; + q = p * r; + y += q; + p *= s * (a + t + d1) / (t + 1.0); + p *= (b + t + d1) / (t + 1.0 + e); + t += 1.0; + if (t > hyp2f1_MAXITER) { /* should never happen */ + set_error("hyp2f1", SF_ERROR_SLOW, NULL); + *loss = 1.0; + return std::numeric_limits::quiet_NaN(); + } + } while (y == 0 || std::abs(q / y) > hyp2f1_EPS); + + if (id == 0.0) { + y *= xsf::cephes::Gamma(c) / (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b)); + goto psidon; + } + + y1 = 1.0; + + if (aid == 1) + goto nosum; + + t = 0.0; + p = 1.0; + for (i = 1; i < aid; i++) { + r = 1.0 - e + t; + p *= s * (a + t + d2) * (b + t + d2) / r; + t += 1.0; + p /= t; + y1 += p; + } + nosum: + p = xsf::cephes::Gamma(c); + y1 *= xsf::cephes::Gamma(e) * p * + (xsf::cephes::rgamma(a + d1) * xsf::cephes::rgamma(b + d1)); + + y *= p * (xsf::cephes::rgamma(a + d2) * xsf::cephes::rgamma(b + d2)); + if ((aid & 1) != 0) + y = -y; + + q = std::pow(s, id); /* s to the id power */ + if (id > 0.0) + y *= q; + else + y1 *= q; + + y += y1; + psidon: + goto done; + } + } + + /* Use defining power series if no special cases */ + y = hys2f1(a, b, c, x, &err); + + done: + *loss = err; + return (y); + } + + /* + 15.4.2 Abramowitz & Stegun. + */ + XSF_HOST_DEVICE double hyp2f1_neg_c_equal_bc(double a, double b, double x) { + double k; + double collector = 1; + double sum = 1; + double collector_max = 1; + + if (!(std::abs(b) < 1e5)) { + return std::numeric_limits::quiet_NaN(); + } + + for (k = 1; k <= -b; k++) { + collector *= (a + k - 1) * x / k; + collector_max = std::fmax(std::abs(collector), collector_max); + sum += collector; + } + + if (1e-16 * (1 + collector_max / std::abs(sum)) > 1e-7) { + return std::numeric_limits::quiet_NaN(); + } + + return sum; + } + + /* + * Evaluate hypergeometric function by two-term recurrence in `a`. + * + * This avoids some of the loss of precision in the strongly alternating + * hypergeometric series, and can be used to reduce the `a` and `b` parameters + * to smaller values. + * + * AMS55 #15.2.10 + */ + XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss) { + double f2, f1, f0; + int n; + double t, err, da; + + /* Don't cross c or zero */ + if ((c < 0 && a <= c) || (c >= 0 && a >= c)) { + da = std::round(a - c); + } else { + da = std::round(a); + } + t = a - da; + + *loss = 0; + + XSF_ASSERT(da != 0); + + if (std::abs(da) > hyp2f1_MAXITER) { + /* Too expensive to compute this value, so give up */ + set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL); + *loss = 1.0; + return std::numeric_limits::quiet_NaN(); + } + + if (da < 0) { + /* Recurse down */ + f2 = 0; + f1 = hys2f1(t, b, c, x, &err); + *loss += err; + f0 = hys2f1(t - 1, b, c, x, &err); + *loss += err; + t -= 1; + for (n = 1; n < -da; ++n) { + f2 = f1; + f1 = f0; + f0 = -(2 * t - c - t * x + b * x) / (c - t) * f1 - t * (x - 1) / (c - t) * f2; + t -= 1; + } + } else { + /* Recurse up */ + f2 = 0; + f1 = hys2f1(t, b, c, x, &err); + *loss += err; + f0 = hys2f1(t + 1, b, c, x, &err); + *loss += err; + t += 1; + for (n = 1; n < da; ++n) { + f2 = f1; + f1 = f0; + f0 = -((2 * t - c - t * x + b * x) * f1 + (c - t) * f2) / (t * (x - 1)); + t += 1; + } + } + + return f0; + } + } // namespace detail + + XSF_HOST_DEVICE double hyp2f1(double a, double b, double c, double x) { + double d, d1, d2, e; + double p, q, r, s, y, ax; + double ia, ib, ic, id, err; + double t1; + int i, aid; + int neg_int_a = 0, neg_int_b = 0; + int neg_int_ca_or_cb = 0; + + err = 0.0; + ax = std::abs(x); + s = 1.0 - x; + ia = std::round(a); /* nearest integer to a */ + ib = std::round(b); + + if (x == 0.0) { + return 1.0; + } + + d = c - a - b; + id = std::round(d); + + if ((a == 0 || b == 0) && c != 0) { + return 1.0; + } + + if (a <= 0 && std::abs(a - ia) < detail::hyp2f1_EPS) { /* a is a negative integer */ + neg_int_a = 1; + } + + if (b <= 0 && std::abs(b - ib) < detail::hyp2f1_EPS) { /* b is a negative integer */ + neg_int_b = 1; + } + + if (d <= -1 && !(std::abs(d - id) > detail::hyp2f1_EPS && s < 0) && !(neg_int_a || neg_int_b)) { + return std::pow(s, d) * hyp2f1(c - a, c - b, c, x); + } + if (d <= 0 && x == 1 && !(neg_int_a || neg_int_b)) + goto hypdiv; + + if (ax < 1.0 || x == -1.0) { + /* 2F1(a,b;b;x) = (1-x)**(-a) */ + if (std::abs(b - c) < detail::hyp2f1_EPS) { /* b = c */ + if (neg_int_b) { + y = detail::hyp2f1_neg_c_equal_bc(a, b, x); + } else { + y = std::pow(s, -a); /* s to the -a power */ + } + goto hypdon; + } + if (std::abs(a - c) < detail::hyp2f1_EPS) { /* a = c */ + y = std::pow(s, -b); /* s to the -b power */ + goto hypdon; + } + } + + if (c <= 0.0) { + ic = std::round(c); /* nearest integer to c */ + if (std::abs(c - ic) < detail::hyp2f1_EPS) { /* c is a negative integer */ + /* check if termination before explosion */ + if (neg_int_a && (ia > ic)) + goto hypok; + if (neg_int_b && (ib > ic)) + goto hypok; + goto hypdiv; + } + } + + if (neg_int_a || neg_int_b) /* function is a polynomial */ + goto hypok; + + t1 = std::abs(b - a); + if (x < -2.0 && std::abs(t1 - round(t1)) > detail::hyp2f1_EPS) { + /* This transform has a pole for b-a integer, and + * may produce large cancellation errors for |1/x| close 1 + */ + p = hyp2f1(a, 1 - c + a, 1 - b + a, 1.0 / x); + q = hyp2f1(b, 1 - c + b, 1 - a + b, 1.0 / x); + p *= std::pow(-x, -a); + q *= std::pow(-x, -b); + t1 = Gamma(c); + s = t1 * Gamma(b - a) * (rgamma(b) * rgamma(c - a)); + y = t1 * Gamma(a - b) * (rgamma(a) * rgamma(c - b)); + return s * p + y * q; + } else if (x < -1.0) { + if (std::abs(a) < std::abs(b)) { + return std::pow(s, -a) * hyp2f1(a, c - b, c, x / (x - 1)); + } else { + return std::pow(s, -b) * hyp2f1(b, c - a, c, x / (x - 1)); + } + } + + if (ax > 1.0) /* series diverges */ + goto hypdiv; + + p = c - a; + ia = std::round(p); /* nearest integer to c-a */ + if ((ia <= 0.0) && (std::abs(p - ia) < detail::hyp2f1_EPS)) /* negative int c - a */ + neg_int_ca_or_cb = 1; + + r = c - b; + ib = std::round(r); /* nearest integer to c-b */ + if ((ib <= 0.0) && (std::abs(r - ib) < detail::hyp2f1_EPS)) /* negative int c - b */ + neg_int_ca_or_cb = 1; + + id = std::round(d); /* nearest integer to d */ + q = std::abs(d - id); + + /* Thanks to Christian Burger + * for reporting a bug here. */ + if (std::abs(ax - 1.0) < detail::hyp2f1_EPS) { /* |x| == 1.0 */ + if (x > 0.0) { + if (neg_int_ca_or_cb) { + if (d >= 0.0) + goto hypf; + else + goto hypdiv; + } + if (d <= 0.0) + goto hypdiv; + y = Gamma(c) * Gamma(d) * (rgamma(p) * rgamma(r)); + goto hypdon; + } + if (d <= -1.0) + goto hypdiv; + } + + /* Conditionally make d > 0 by recurrence on c + * AMS55 #15.2.27 + */ + if (d < 0.0) { + /* Try the power series first */ + y = detail::hyt2f1(a, b, c, x, &err); + if (err < detail::hyp2f1_ETHRESH) + goto hypdon; + /* Apply the recurrence if power series fails */ + err = 0.0; + aid = 2 - id; + e = c + aid; + d2 = hyp2f1(a, b, e, x); + d1 = hyp2f1(a, b, e + 1.0, x); + q = a + b + 1.0; + for (i = 0; i < aid; i++) { + r = e - 1.0; + y = (e * (r - (2.0 * e - q) * x) * d2 + (e - a) * (e - b) * x * d1) / (e * r * s); + e = r; + d1 = d2; + d2 = y; + } + goto hypdon; + } + + if (neg_int_ca_or_cb) { + goto hypf; /* negative integer c-a or c-b */ + } + + hypok: + y = detail::hyt2f1(a, b, c, x, &err); + + hypdon: + if (err > detail::hyp2f1_ETHRESH) { + set_error("hyp2f1", SF_ERROR_LOSS, NULL); + /* printf( "Estimated err = %.2e\n", err ); */ + } + return (y); + + /* The transformation for c-a or c-b negative integer + * AMS55 #15.3.3 + */ + hypf: + y = std::pow(s, d) * detail::hys2f1(c - a, c - b, c, x, &err); + goto hypdon; + + /* The alarm exit */ + hypdiv: + set_error("hyp2f1", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity(); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h new file mode 100644 index 0000000000000000000000000000000000000000..18ebcff69ba4f9d9a7d5660aa8c63f858c56c7b3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h @@ -0,0 +1,361 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* hyperg.c + * + * Confluent hypergeometric function + * + * + * + * SYNOPSIS: + * + * double a, b, x, y, hyperg(); + * + * y = hyperg( a, b, x ); + * + * + * + * DESCRIPTION: + * + * Computes the confluent hypergeometric function + * + * 1 2 + * a x a(a+1) x + * F ( a,b;x ) = 1 + ---- + --------- + ... + * 1 1 b 1! b(b+1) 2! + * + * Many higher transcendental functions are special cases of + * this power series. + * + * As is evident from the formula, b must not be a negative + * integer or zero unless a is an integer with 0 >= a > b. + * + * The routine attempts both a direct summation of the series + * and an asymptotic expansion. In each case error due to + * roundoff, cancellation, and nonconvergence is estimated. + * The result with smaller estimated error is returned. + * + * + * + * ACCURACY: + * + * Tested at random points (a, b, x), all three variables + * ranging from 0 to 30. + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 1.8e-14 1.1e-15 + * + * Larger errors can be observed when b is near a negative + * integer or zero. Certain combinations of arguments yield + * serious cancellation error in the power series summation + * and also are not in the region of near convergence of the + * asymptotic series. An error message is printed if the + * self-estimated relative error is greater than 1.0e-12. + * + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier + */ + +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "gamma.h" +#include "rgamma.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* the `type` parameter determines what converging factor to use */ + XSF_HOST_DEVICE inline double hyp2f0(double a, double b, double x, int type, double *err) { + double a0, alast, t, tlast, maxt; + double n, an, bn, u, sum, temp; + + an = a; + bn = b; + a0 = 1.0e0; + alast = 1.0e0; + sum = 0.0; + n = 1.0e0; + t = 1.0e0; + tlast = 1.0e9; + maxt = 0.0; + + do { + if (an == 0) + goto pdone; + if (bn == 0) + goto pdone; + + u = an * (bn * x / n); + + /* check for blowup */ + temp = std::abs(u); + if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp))) + goto error; + + a0 *= u; + t = std::abs(a0); + + /* terminating condition for asymptotic series: + * the series is divergent (if a or b is not a negative integer), + * but its leading part can be used as an asymptotic expansion + */ + if (t > tlast) + goto ndone; + + tlast = t; + sum += alast; /* the sum is one term behind */ + alast = a0; + + if (n > 200) + goto ndone; + + an += 1.0e0; + bn += 1.0e0; + n += 1.0e0; + if (t > maxt) + maxt = t; + } while (t > MACHEP); + + pdone: /* series converged! */ + + /* estimate error due to roundoff and cancellation */ + *err = std::abs(MACHEP * (n + maxt)); + + alast = a0; + goto done; + + ndone: /* series did not converge */ + + /* The following "Converging factors" are supposed to improve accuracy, + * but do not actually seem to accomplish very much. */ + + n -= 1.0; + x = 1.0 / x; + + switch (type) { /* "type" given as subroutine argument */ + case 1: + alast *= (0.5 + (0.125 + 0.25 * b - 0.5 * a + 0.25 * x - 0.25 * n) / x); + break; + + case 2: + alast *= 2.0 / 3.0 - b + 2.0 * a + x - n; + break; + + default:; + } + + /* estimate error due to roundoff, cancellation, and nonconvergence */ + *err = MACHEP * (n + maxt) + std::abs(a0); + + done: + sum += alast; + return (sum); + + /* series blew up: */ + error: + *err = std::numeric_limits::infinity(); + set_error("hyperg", SF_ERROR_NO_RESULT, NULL); + return (sum); + } + + /* asymptotic formula for hypergeometric function: + * + * ( -a + * -- ( |z| + * | (b) ( -------- 2f0( a, 1+a-b, -1/x ) + * ( -- + * ( | (b-a) + * + * + * x a-b ) + * e |x| ) + * + -------- 2f0( b-a, 1-a, 1/x ) ) + * -- ) + * | (a) ) + */ + + XSF_HOST_DEVICE inline double hy1f1a(double a, double b, double x, double *err) { + double h1, h2, t, u, temp, acanc, asum, err1, err2; + + if (x == 0) { + acanc = 1.0; + asum = std::numeric_limits::infinity(); + goto adone; + } + temp = std::log(std::abs(x)); + t = x + temp * (a - b); + u = -temp * a; + + if (b > 0) { + temp = xsf::cephes::lgam(b); + t += temp; + u += temp; + } + + h1 = hyp2f0(a, a - b + 1, -1.0 / x, 1, &err1); + + temp = std::exp(u) * xsf::cephes::rgamma(b - a); + h1 *= temp; + err1 *= temp; + + h2 = hyp2f0(b - a, 1.0 - a, 1.0 / x, 2, &err2); + + if (a < 0) + temp = std::exp(t) * xsf::cephes::rgamma(a); + else + temp = std::exp(t - xsf::cephes::lgam(a)); + + h2 *= temp; + err2 *= temp; + + if (x < 0.0) + asum = h1; + else + asum = h2; + + acanc = std::abs(err1) + std::abs(err2); + + if (b < 0) { + temp = xsf::cephes::Gamma(b); + asum *= temp; + acanc *= std::abs(temp); + } + + if (asum != 0.0) + acanc /= std::abs(asum); + + if (acanc != acanc) + /* nan */ + acanc = 1.0; + + if (std::isinf(asum)) + /* infinity */ + acanc = 0; + + acanc *= 30.0; /* fudge factor, since error of asymptotic formula + * often seems this much larger than advertised */ + adone: + *err = acanc; + return (asum); + } + + /* Power series summation for confluent hypergeometric function */ + XSF_HOST_DEVICE inline double hy1f1p(double a, double b, double x, double *err) { + double n, a0, sum, t, u, temp, maxn; + double an, bn, maxt; + double y, c, sumc; + + /* set up for power series summation */ + an = a; + bn = b; + a0 = 1.0; + sum = 1.0; + c = 0.0; + n = 1.0; + t = 1.0; + maxt = 0.0; + *err = 1.0; + + maxn = 200.0 + 2 * fabs(a) + 2 * fabs(b); + + while (t > MACHEP) { + if (bn == 0) { /* check bn first since if both */ + sf_error("hyperg", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::infinity()); /* an and bn are zero it is */ + } + if (an == 0) /* a singularity */ + return (sum); + if (n > maxn) { + /* too many terms; take the last one as error estimate */ + c = std::abs(c) + std::abs(t) * 50.0; + goto pdone; + } + u = x * (an / (bn * n)); + + /* check for blowup */ + temp = std::abs(u); + if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp))) { + *err = 1.0; /* blowup: estimate 100% error */ + return sum; + } + + a0 *= u; + + y = a0 - c; + sumc = sum + y; + c = (sumc - sum) - y; + sum = sumc; + + t = std::abs(a0); + + an += 1.0; + bn += 1.0; + n += 1.0; + } + + pdone: + + /* estimate error due to roundoff and cancellation */ + if (sum != 0.0) { + *err = std::abs(c / sum); + } else { + *err = std::abs(c); + } + + if (*err != *err) { + /* nan */ + *err = 1.0; + } + + return (sum); + } + + } // namespace detail + + XSF_HOST_DEVICE inline double hyperg(double a, double b, double x) { + double asum, psum, acanc, pcanc, temp; + + /* See if a Kummer transformation will help */ + temp = b - a; + if (std::abs(temp) < 0.001 * std::abs(a)) + return (exp(x) * hyperg(temp, b, -x)); + + /* Try power & asymptotic series, starting from the one that is likely OK */ + if (std::abs(x) < 10 + std::abs(a) + std::abs(b)) { + psum = detail::hy1f1p(a, b, x, &pcanc); + if (pcanc < 1.0e-15) + goto done; + asum = detail::hy1f1a(a, b, x, &acanc); + } else { + psum = detail::hy1f1a(a, b, x, &pcanc); + if (pcanc < 1.0e-15) + goto done; + asum = detail::hy1f1p(a, b, x, &acanc); + } + + /* Pick the result with less estimated error */ + + if (acanc < pcanc) { + pcanc = acanc; + psum = asum; + } + + done: + if (pcanc > 1.0e-12) + set_error("hyperg", SF_ERROR_LOSS, NULL); + + return (psum); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h new file mode 100644 index 0000000000000000000000000000000000000000..f61e7b12fd22d92e741f53e2acee8a7f65278658 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h @@ -0,0 +1,149 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* i0.c + * + * Modified Bessel function of order zero + * + * + * + * SYNOPSIS: + * + * double x, y, i0(); + * + * y = i0( x ); + * + * + * + * DESCRIPTION: + * + * Returns modified Bessel function of order zero of the + * argument. + * + * The function is defined as i0(x) = j0( ix ). + * + * The range is partitioned into the two intervals [0,8] and + * (8, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 5.8e-16 1.4e-16 + * + */ +/* i0e.c + * + * Modified Bessel function of order zero, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, i0e(); + * + * y = i0e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of order zero of the argument. + * + * The function is defined as i0e(x) = exp(-|x|) j0( ix ). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 5.4e-16 1.2e-16 + * See i0(). + * + */ + +/* i0.c */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "chbevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* Chebyshev coefficients for exp(-x) I0(x) + * in the interval [0,8]. + * + * lim(x->0){ exp(-x) I0(x) } = 1. + */ + constexpr double i0_A[] = { + -4.41534164647933937950E-18, 3.33079451882223809783E-17, -2.43127984654795469359E-16, + 1.71539128555513303061E-15, -1.16853328779934516808E-14, 7.67618549860493561688E-14, + -4.85644678311192946090E-13, 2.95505266312963983461E-12, -1.72682629144155570723E-11, + 9.67580903537323691224E-11, -5.18979560163526290666E-10, 2.65982372468238665035E-9, + -1.30002500998624804212E-8, 6.04699502254191894932E-8, -2.67079385394061173391E-7, + 1.11738753912010371815E-6, -4.41673835845875056359E-6, 1.64484480707288970893E-5, + -5.75419501008210370398E-5, 1.88502885095841655729E-4, -5.76375574538582365885E-4, + 1.63947561694133579842E-3, -4.32430999505057594430E-3, 1.05464603945949983183E-2, + -2.37374148058994688156E-2, 4.93052842396707084878E-2, -9.49010970480476444210E-2, + 1.71620901522208775349E-1, -3.04682672343198398683E-1, 6.76795274409476084995E-1}; + + /* Chebyshev coefficients for exp(-x) sqrt(x) I0(x) + * in the inverted interval [8,infinity]. + * + * lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi). + */ + constexpr double i0_B[] = { + -7.23318048787475395456E-18, -4.83050448594418207126E-18, 4.46562142029675999901E-17, + 3.46122286769746109310E-17, -2.82762398051658348494E-16, -3.42548561967721913462E-16, + 1.77256013305652638360E-15, 3.81168066935262242075E-15, -9.55484669882830764870E-15, + -4.15056934728722208663E-14, 1.54008621752140982691E-14, 3.85277838274214270114E-13, + 7.18012445138366623367E-13, -1.79417853150680611778E-12, -1.32158118404477131188E-11, + -3.14991652796324136454E-11, 1.18891471078464383424E-11, 4.94060238822496958910E-10, + 3.39623202570838634515E-9, 2.26666899049817806459E-8, 2.04891858946906374183E-7, + 2.89137052083475648297E-6, 6.88975834691682398426E-5, 3.36911647825569408990E-3, + 8.04490411014108831608E-1}; + } // namespace detail + + XSF_HOST_DEVICE inline double i0(double x) { + double y; + + if (x < 0) + x = -x; + if (x <= 8.0) { + y = (x / 2.0) - 2.0; + return (std::exp(x) * chbevl(y, detail::i0_A, 30)); + } + + return (std::exp(x) * chbevl(32.0 / x - 2.0, detail::i0_B, 25) / sqrt(x)); + } + + XSF_HOST_DEVICE inline double i0e(double x) { + double y; + + if (x < 0) + x = -x; + if (x <= 8.0) { + y = (x / 2.0) - 2.0; + return (chbevl(y, detail::i0_A, 30)); + } + + return (chbevl(32.0 / x - 2.0, detail::i0_B, 25) / std::sqrt(x)); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h new file mode 100644 index 0000000000000000000000000000000000000000..49e2690391cf5af19ca36c72cbd38034920c1fd2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h @@ -0,0 +1,158 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* i1.c + * + * Modified Bessel function of order one + * + * + * + * SYNOPSIS: + * + * double x, y, i1(); + * + * y = i1( x ); + * + * + * + * DESCRIPTION: + * + * Returns modified Bessel function of order one of the + * argument. + * + * The function is defined as i1(x) = -i j1( ix ). + * + * The range is partitioned into the two intervals [0,8] and + * (8, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.9e-15 2.1e-16 + * + * + */ +/* i1e.c + * + * Modified Bessel function of order one, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, i1e(); + * + * y = i1e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of order one of the argument. + * + * The function is defined as i1(x) = -i exp(-|x|) j1( ix ). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 2.0e-15 2.0e-16 + * See i1(). + * + */ + +/* i1.c 2 */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1985, 1987, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "chbevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* Chebyshev coefficients for exp(-x) I1(x) / x + * in the interval [0,8]. + * + * lim(x->0){ exp(-x) I1(x) / x } = 1/2. + */ + + constexpr double i1_A[] = { + 2.77791411276104639959E-18, -2.11142121435816608115E-17, 1.55363195773620046921E-16, + -1.10559694773538630805E-15, 7.60068429473540693410E-15, -5.04218550472791168711E-14, + 3.22379336594557470981E-13, -1.98397439776494371520E-12, 1.17361862988909016308E-11, + -6.66348972350202774223E-11, 3.62559028155211703701E-10, -1.88724975172282928790E-9, + 9.38153738649577178388E-9, -4.44505912879632808065E-8, 2.00329475355213526229E-7, + -8.56872026469545474066E-7, 3.47025130813767847674E-6, -1.32731636560394358279E-5, + 4.78156510755005422638E-5, -1.61760815825896745588E-4, 5.12285956168575772895E-4, + -1.51357245063125314899E-3, 4.15642294431288815669E-3, -1.05640848946261981558E-2, + 2.47264490306265168283E-2, -5.29459812080949914269E-2, 1.02643658689847095384E-1, + -1.76416518357834055153E-1, 2.52587186443633654823E-1}; + + /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x) + * in the inverted interval [8,infinity]. + * + * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi). + */ + constexpr double i1_B[] = { + 7.51729631084210481353E-18, 4.41434832307170791151E-18, -4.65030536848935832153E-17, + -3.20952592199342395980E-17, 2.96262899764595013876E-16, 3.30820231092092828324E-16, + -1.88035477551078244854E-15, -3.81440307243700780478E-15, 1.04202769841288027642E-14, + 4.27244001671195135429E-14, -2.10154184277266431302E-14, -4.08355111109219731823E-13, + -7.19855177624590851209E-13, 2.03562854414708950722E-12, 1.41258074366137813316E-11, + 3.25260358301548823856E-11, -1.89749581235054123450E-11, -5.58974346219658380687E-10, + -3.83538038596423702205E-9, -2.63146884688951950684E-8, -2.51223623787020892529E-7, + -3.88256480887769039346E-6, -1.10588938762623716291E-4, -9.76109749136146840777E-3, + 7.78576235018280120474E-1}; + + } // namespace detail + + XSF_HOST_DEVICE inline double i1(double x) { + double y, z; + + z = std::abs(x); + if (z <= 8.0) { + y = (z / 2.0) - 2.0; + z = chbevl(y, detail::i1_A, 29) * z * std::exp(z); + } else { + z = std::exp(z) * chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z); + } + if (x < 0.0) + z = -z; + return (z); + } + + /* i1e() */ + + XSF_HOST_DEVICE inline double i1e(double x) { + double y, z; + + z = std::abs(x); + if (z <= 8.0) { + y = (z / 2.0) - 2.0; + z = chbevl(y, detail::i1_A, 29) * z; + } else { + z = chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z); + } + if (x < 0.0) + z = -z; + return (z); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h new file mode 100644 index 0000000000000000000000000000000000000000..dbe4f6519b13111d520306c5eec75bf811b02d0d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h @@ -0,0 +1,421 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* igam.c + * + * Incomplete Gamma integral + * + * + * + * SYNOPSIS: + * + * double a, x, y, igam(); + * + * y = igam( a, x ); + * + * DESCRIPTION: + * + * The function is defined by + * + * x + * - + * 1 | | -t a-1 + * igam(a,x) = ----- | e t dt. + * - | | + * | (a) - + * 0 + * + * + * In this implementation both arguments must be positive. + * The integral is evaluated by either a power series or + * continued fraction expansion, depending on the relative + * values of a and x. + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 200000 3.6e-14 2.9e-15 + * IEEE 0,100 300000 9.9e-14 1.5e-14 + */ +/* igamc() + * + * Complemented incomplete Gamma integral + * + * + * + * SYNOPSIS: + * + * double a, x, y, igamc(); + * + * y = igamc( a, x ); + * + * DESCRIPTION: + * + * The function is defined by + * + * + * igamc(a,x) = 1 - igam(a,x) + * + * inf. + * - + * 1 | | -t a-1 + * = ----- | e t dt. + * - | | + * | (a) - + * x + * + * + * In this implementation both arguments must be positive. + * The integral is evaluated by either a power series or + * continued fraction expansion, depending on the relative + * values of a and x. + * + * ACCURACY: + * + * Tested at random a, x. + * a x Relative error: + * arithmetic domain domain # trials peak rms + * IEEE 0.5,100 0,100 200000 1.9e-14 1.7e-15 + * IEEE 0.01,0.5 0,100 200000 1.4e-13 1.6e-15 + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1985, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ + +/* Sources + * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov + * [2] Maddock et. al., "Incomplete Gamma Functions", + * https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/sf_gamma/igamma.html + */ + +/* Scipy changes: + * - 05-01-2016: added asymptotic expansion for igam to improve the + * a ~ x regime. + * - 06-19-2016: additional series expansion added for igamc to + * improve accuracy at small arguments. + * - 06-24-2016: better choice of domain for the asymptotic series; + * improvements in accuracy for the asymptotic series when a and x + * are very close. + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "gamma.h" +#include "igam_asymp_coeff.h" +#include "lanczos.h" +#include "ndtr.h" +#include "unity.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr int igam_MAXITER = 2000; + constexpr int IGAM = 1; + constexpr int IGAMC = 0; + constexpr double igam_SMALL = 20; + constexpr double igam_LARGE = 200; + constexpr double igam_SMALLRATIO = 0.3; + constexpr double igam_LARGERATIO = 4.5; + + constexpr double igam_big = 4.503599627370496e15; + constexpr double igam_biginv = 2.22044604925031308085e-16; + + /* Compute + * + * x^a * exp(-x) / gamma(a) + * + * corrected from (15) and (16) in [2] by replacing exp(x - a) with + * exp(a - x). + */ + XSF_HOST_DEVICE inline double igam_fac(double a, double x) { + double ax, fac, res, num; + + if (std::abs(a - x) > 0.4 * std::abs(a)) { + ax = a * std::log(x) - x - xsf::cephes::lgam(a); + if (ax < -MAXLOG) { + set_error("igam", SF_ERROR_UNDERFLOW, NULL); + return 0.0; + } + return std::exp(ax); + } + + fac = a + xsf::cephes::lanczos_g - 0.5; + res = std::sqrt(fac / std::exp(1)) / xsf::cephes::lanczos_sum_expg_scaled(a); + + if ((a < 200) && (x < 200)) { + res *= std::exp(a - x) * std::pow(x / fac, a); + } else { + num = x - a - xsf::cephes::lanczos_g + 0.5; + res *= std::exp(a * xsf::cephes::log1pmx(num / fac) + x * (0.5 - xsf::cephes::lanczos_g) / fac); + } + + return res; + } + + /* Compute igamc using DLMF 8.9.2. */ + XSF_HOST_DEVICE inline double igamc_continued_fraction(double a, double x) { + int i; + double ans, ax, c, yc, r, t, y, z; + double pk, pkm1, pkm2, qk, qkm1, qkm2; + + ax = igam_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* continued fraction */ + y = 1.0 - a; + z = x + y + 1.0; + c = 0.0; + pkm2 = 1.0; + qkm2 = x; + pkm1 = x + 1.0; + qkm1 = z * x; + ans = pkm1 / qkm1; + + for (i = 0; i < igam_MAXITER; i++) { + c += 1.0; + y += 1.0; + z += 2.0; + yc = y * c; + pk = pkm1 * z - pkm2 * yc; + qk = qkm1 * z - qkm2 * yc; + if (qk != 0) { + r = pk / qk; + t = std::abs((ans - r) / r); + ans = r; + } else + t = 1.0; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if (std::abs(pk) > igam_big) { + pkm2 *= igam_biginv; + pkm1 *= igam_biginv; + qkm2 *= igam_biginv; + qkm1 *= igam_biginv; + } + if (t <= MACHEP) { + break; + } + } + + return (ans * ax); + } + + /* Compute igam using DLMF 8.11.4. */ + XSF_HOST_DEVICE inline double igam_series(double a, double x) { + int i; + double ans, ax, c, r; + + ax = igam_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* power series */ + r = a; + c = 1.0; + ans = 1.0; + + for (i = 0; i < igam_MAXITER; i++) { + r += 1.0; + c *= x / r; + ans += c; + if (c <= MACHEP * ans) { + break; + } + } + + return (ans * ax / a); + } + + /* Compute igamc using DLMF 8.7.3. This is related to the series in + * igam_series but extra care is taken to avoid cancellation. + */ + XSF_HOST_DEVICE inline double igamc_series(double a, double x) { + int n; + double fac = 1; + double sum = 0; + double term, logx; + + for (n = 1; n < igam_MAXITER; n++) { + fac *= -x / n; + term = fac / (a + n); + sum += term; + if (std::abs(term) <= MACHEP * std::abs(sum)) { + break; + } + } + + logx = std::log(x); + term = -xsf::cephes::expm1(a * logx - xsf::cephes::lgam1p(a)); + return term - std::exp(a * logx - xsf::cephes::lgam(a)) * sum; + } + + /* Compute igam/igamc using DLMF 8.12.3/8.12.4. */ + XSF_HOST_DEVICE inline double asymptotic_series(double a, double x, int func) { + int k, n, sgn; + int maxpow = 0; + double lambda = x / a; + double sigma = (x - a) / a; + double eta, res, ck, ckterm, term, absterm; + double absoldterm = std::numeric_limits::infinity(); + double etapow[detail::igam_asymp_coeff_N] = {1}; + double sum = 0; + double afac = 1; + + if (func == detail::IGAM) { + sgn = -1; + } else { + sgn = 1; + } + + if (lambda > 1) { + eta = std::sqrt(-2 * xsf::cephes::log1pmx(sigma)); + } else if (lambda < 1) { + eta = -std::sqrt(-2 * xsf::cephes::log1pmx(sigma)); + } else { + eta = 0; + } + res = 0.5 * xsf::cephes::erfc(sgn * eta * std::sqrt(a / 2)); + + for (k = 0; k < igam_asymp_coeff_K; k++) { + ck = igam_asymp_coeff_d[k][0]; + for (n = 1; n < igam_asymp_coeff_N; n++) { + if (n > maxpow) { + etapow[n] = eta * etapow[n - 1]; + maxpow += 1; + } + ckterm = igam_asymp_coeff_d[k][n] * etapow[n]; + ck += ckterm; + if (std::abs(ckterm) < MACHEP * std::abs(ck)) { + break; + } + } + term = ck * afac; + absterm = std::abs(term); + if (absterm > absoldterm) { + break; + } + sum += term; + if (absterm < MACHEP * std::abs(sum)) { + break; + } + absoldterm = absterm; + afac /= a; + } + res += sgn * std::exp(-0.5 * a * eta * eta) * sum / std::sqrt(2 * M_PI * a); + + return res; + } + + } // namespace detail + + XSF_HOST_DEVICE inline double igamc(double a, double x); + + XSF_HOST_DEVICE inline double igam(double a, double x) { + double absxma_a; + + if (x < 0 || a < 0) { + set_error("gammainc", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } else if (a == 0) { + if (x > 0) { + return 1; + } else { + return std::numeric_limits::quiet_NaN(); + } + } else if (x == 0) { + /* Zero integration limit */ + return 0; + } else if (std::isinf(a)) { + if (std::isinf(x)) { + return std::numeric_limits::quiet_NaN(); + } + return 0; + } else if (std::isinf(x)) { + return 1; + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = std::abs(x - a) / a; + if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) { + return detail::asymptotic_series(a, x, detail::IGAM); + } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) { + return detail::asymptotic_series(a, x, detail::IGAM); + } + + if ((x > 1.0) && (x > a)) { + return (1.0 - igamc(a, x)); + } + + return detail::igam_series(a, x); + } + + XSF_HOST_DEVICE double igamc(double a, double x) { + double absxma_a; + + if (x < 0 || a < 0) { + set_error("gammaincc", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } else if (a == 0) { + if (x > 0) { + return 0; + } else { + return std::numeric_limits::quiet_NaN(); + } + } else if (x == 0) { + return 1; + } else if (std::isinf(a)) { + if (std::isinf(x)) { + return std::numeric_limits::quiet_NaN(); + } + return 1; + } else if (std::isinf(x)) { + return 0; + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = std::abs(x - a) / a; + if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) { + return detail::asymptotic_series(a, x, detail::IGAMC); + } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) { + return detail::asymptotic_series(a, x, detail::IGAMC); + } + + /* Everywhere else; see [2]. */ + if (x > 1.1) { + if (x < a) { + return 1.0 - detail::igam_series(a, x); + } else { + return detail::igamc_continued_fraction(a, x); + } + } else if (x <= 0.5) { + if (-0.4 / std::log(x) < a) { + return 1.0 - detail::igam_series(a, x); + } else { + return detail::igamc_series(a, x); + } + } else { + if (x * 1.1 < a) { + return 1.0 - detail::igam_series(a, x); + } else { + return detail::igamc_series(a, x); + } + } + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h new file mode 100644 index 0000000000000000000000000000000000000000..98404c65ebca79239022c0bae10cfe5e43c361c0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h @@ -0,0 +1,195 @@ +/* Translated into C++ by SciPy developers in 2024. */ + +/* This file was automatically generated by _precomp/gammainc.py. + * Do not edit it manually! + */ +#pragma once + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr int igam_asymp_coeff_K = 25; + constexpr int igam_asymp_coeff_N = 25; + + static const double igam_asymp_coeff_d[igam_asymp_coeff_K][igam_asymp_coeff_N] = { + {-3.3333333333333333e-1, 8.3333333333333333e-2, -1.4814814814814815e-2, 1.1574074074074074e-3, + 3.527336860670194e-4, -1.7875514403292181e-4, 3.9192631785224378e-5, -2.1854485106799922e-6, + -1.85406221071516e-6, 8.296711340953086e-7, -1.7665952736826079e-7, 6.7078535434014986e-9, + 1.0261809784240308e-8, -4.3820360184533532e-9, 9.1476995822367902e-10, -2.551419399494625e-11, + -5.8307721325504251e-11, 2.4361948020667416e-11, -5.0276692801141756e-12, 1.1004392031956135e-13, + 3.3717632624009854e-13, -1.3923887224181621e-13, 2.8534893807047443e-14, -5.1391118342425726e-16, + -1.9752288294349443e-15}, + {-1.8518518518518519e-3, -3.4722222222222222e-3, 2.6455026455026455e-3, -9.9022633744855967e-4, + 2.0576131687242798e-4, -4.0187757201646091e-7, -1.8098550334489978e-5, 7.6491609160811101e-6, + -1.6120900894563446e-6, 4.6471278028074343e-9, 1.378633446915721e-7, -5.752545603517705e-8, + 1.1951628599778147e-8, -1.7543241719747648e-11, -1.0091543710600413e-9, 4.1627929918425826e-10, + -8.5639070264929806e-11, 6.0672151016047586e-14, 7.1624989648114854e-12, -2.9331866437714371e-12, + 5.9966963656836887e-13, -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14, + -4.13125571381061e-15}, + {4.1335978835978836e-3, -2.6813271604938272e-3, 7.7160493827160494e-4, 2.0093878600823045e-6, + -1.0736653226365161e-4, 5.2923448829120125e-5, -1.2760635188618728e-5, 3.4235787340961381e-8, + 1.3721957309062933e-6, -6.298992138380055e-7, 1.4280614206064242e-7, -2.0477098421990866e-10, + -1.4092529910867521e-8, 6.228974084922022e-9, -1.3670488396617113e-9, 9.4283561590146782e-13, + 1.2872252400089318e-10, -5.5645956134363321e-11, 1.1975935546366981e-11, -4.1689782251838635e-15, + -1.0940640427884594e-12, 4.6622399463901357e-13, -9.905105763906906e-14, 1.8931876768373515e-17, + 8.8592218725911273e-15}, + {6.4943415637860082e-4, 2.2947209362139918e-4, -4.6918949439525571e-4, 2.6772063206283885e-4, + -7.5618016718839764e-5, -2.3965051138672967e-7, 1.1082654115347302e-5, -5.6749528269915966e-6, + 1.4230900732435884e-6, -2.7861080291528142e-11, -1.6958404091930277e-7, 8.0994649053880824e-8, + -1.9111168485973654e-8, 2.3928620439808118e-12, 2.0620131815488798e-9, -9.4604966618551322e-10, + 2.1541049775774908e-10, -1.388823336813903e-14, -2.1894761681963939e-11, 9.7909989511716851e-12, + -2.1782191880180962e-12, 6.2088195734079014e-17, 2.126978363279737e-13, -9.3446887915174333e-14, + 2.0453671226782849e-14}, + {-8.618882909167117e-4, 7.8403922172006663e-4, -2.9907248030319018e-4, -1.4638452578843418e-6, + 6.6414982154651222e-5, -3.9683650471794347e-5, 1.1375726970678419e-5, 2.5074972262375328e-10, + -1.6954149536558306e-6, 8.9075075322053097e-7, -2.2929348340008049e-7, 2.956794137544049e-11, + 2.8865829742708784e-8, -1.4189739437803219e-8, 3.4463580499464897e-9, -2.3024517174528067e-13, + -3.9409233028046405e-10, 1.8602338968504502e-10, -4.356323005056618e-11, 1.2786001016296231e-15, + 4.6792750266579195e-12, -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18, + -5.0453320690800944e-14}, + {-3.3679855336635815e-4, -6.9728137583658578e-5, 2.7727532449593921e-4, -1.9932570516188848e-4, + 6.7977804779372078e-5, 1.419062920643967e-7, -1.3594048189768693e-5, 8.0184702563342015e-6, + -2.2914811765080952e-6, -3.252473551298454e-10, 3.4652846491085265e-7, -1.8447187191171343e-7, + 4.8240967037894181e-8, -1.7989466721743515e-14, -6.3061945000135234e-9, 3.1624176287745679e-9, + -7.8409242536974293e-10, 5.1926791652540407e-15, 9.3589442423067836e-11, -4.5134262161632782e-11, + 1.0799129993116827e-11, -3.661886712685252e-17, -1.210902069055155e-12, 5.6807435849905643e-13, + -1.3249659916340829e-13}, + {5.3130793646399222e-4, -5.9216643735369388e-4, 2.7087820967180448e-4, 7.9023532326603279e-7, + -8.1539693675619688e-5, 5.6116827531062497e-5, -1.8329116582843376e-5, -3.0796134506033048e-9, + 3.4651553688036091e-6, -2.0291327396058604e-6, 5.7887928631490037e-7, 2.338630673826657e-13, + -8.8286007463304835e-8, 4.7435958880408128e-8, -1.2545415020710382e-8, 8.6496488580102925e-14, + 1.6846058979264063e-9, -8.5754928235775947e-10, 2.1598224929232125e-10, -7.6132305204761539e-16, + -2.6639822008536144e-11, 1.3065700536611057e-11, -3.1799163902367977e-12, 4.7109761213674315e-18, + 3.6902800842763467e-13}, + {3.4436760689237767e-4, 5.1717909082605922e-5, -3.3493161081142236e-4, 2.812695154763237e-4, + -1.0976582244684731e-4, -1.2741009095484485e-7, 2.7744451511563644e-5, -1.8263488805711333e-5, + 5.7876949497350524e-6, 4.9387589339362704e-10, -1.0595367014026043e-6, 6.1667143761104075e-7, + -1.7562973359060462e-7, -1.2974473287015439e-12, 2.695423606288966e-8, -1.4578352908731271e-8, + 3.887645959386175e-9, -3.8810022510194121e-17, -5.3279941738772867e-10, 2.7437977643314845e-10, + -6.9957960920705679e-11, 2.5899863874868481e-17, 8.8566890996696381e-12, -4.403168815871311e-12, + 1.0865561947091654e-12}, + {-6.5262391859530942e-4, 8.3949872067208728e-4, -4.3829709854172101e-4, -6.969091458420552e-7, + 1.6644846642067548e-4, -1.2783517679769219e-4, 4.6299532636913043e-5, 4.5579098679227077e-9, + -1.0595271125805195e-5, 6.7833429048651666e-6, -2.1075476666258804e-6, -1.7213731432817145e-11, + 3.7735877416110979e-7, -2.1867506700122867e-7, 6.2202288040189269e-8, 6.5977038267330006e-16, + -9.5903864974256858e-9, 5.2132144922808078e-9, -1.3991589583935709e-9, 5.382058999060575e-16, + 1.9484714275467745e-10, -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18, + -3.3721464474854592e-12}, + {-5.9676129019274625e-4, -7.2048954160200106e-5, 6.7823088376673284e-4, -6.4014752602627585e-4, + 2.7750107634328704e-4, 1.8197008380465151e-7, -8.4795071170685032e-5, 6.105192082501531e-5, + -2.1073920183404862e-5, -8.8585890141255994e-10, 4.5284535953805377e-6, -2.8427815022504408e-6, + 8.7082341778646412e-7, 3.6886101871706965e-12, -1.5344695190702061e-7, 8.862466778790695e-8, + -2.5184812301826817e-8, -1.0225912098215092e-14, 3.8969470758154777e-9, -2.1267304792235635e-9, + 5.7370135528051385e-10, -1.887749850169741e-19, -8.0931538694657866e-11, 4.2382723283449199e-11, + -1.1002224534207726e-11}, + {1.3324454494800656e-3, -1.9144384985654775e-3, 1.1089369134596637e-3, 9.932404122642299e-7, + -5.0874501293093199e-4, 4.2735056665392884e-4, -1.6858853767910799e-4, -8.1301893922784998e-9, + 4.5284402370562147e-5, -3.127053674781734e-5, 1.044986828530338e-5, 4.8435226265680926e-11, + -2.1482565873456258e-6, 1.329369701097492e-6, -4.0295693092101029e-7, -1.7567877666323291e-13, + 7.0145043163668257e-8, -4.040787734999483e-8, 1.1474026743371963e-8, 3.9642746853563325e-18, + -1.7804938269892714e-9, 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18, + 3.7647749553543836e-11}, + {1.579727660730835e-3, 1.6251626278391582e-4, -2.0633421035543276e-3, 2.1389686185689098e-3, + -1.0108559391263003e-3, -3.9912705529919201e-7, 3.6235025084764691e-4, -2.8143901463712154e-4, + 1.0449513336495887e-4, 2.1211418491830297e-9, -2.5779417251947842e-5, 1.7281818956040463e-5, + -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6, -6.8693396379526735e-7, + 2.0653236975414887e-7, 4.6714772409838506e-14, -3.5609886164949055e-8, 2.0470855345905963e-8, + -5.8091738633283358e-9, -1.332821287582869e-16, 9.0354604391335133e-10, -4.9598782517330834e-10, + 1.3481607129399749e-10}, + {-4.0725121195140166e-3, 6.4033628338080698e-3, -4.0410161081676618e-3, -2.183732802866233e-6, + 2.1740441801254639e-3, -1.9700440518418892e-3, 8.3595469747962458e-4, 1.9445447567109655e-8, + -2.5779387120421696e-4, 1.9009987368139304e-4, -6.7696499937438965e-5, -1.4440629666426572e-10, + 1.5712512518742269e-5, -1.0304008744776893e-5, 3.304517767401387e-6, 7.9829760242325709e-13, + -6.4097794149313004e-7, 3.8894624761300056e-7, -1.1618347644948869e-7, -2.816808630596451e-15, + 1.9878012911297093e-8, -1.1407719956357511e-8, 3.2355857064185555e-9, 4.1759468293455945e-20, + -5.0423112718105824e-10}, + {-5.9475779383993003e-3, -5.4016476789260452e-4, 8.7910413550767898e-3, -9.8576315587856125e-3, + 5.0134695031021538e-3, 1.2807521786221875e-6, -2.0626019342754683e-3, 1.7109128573523058e-3, + -6.7695312714133799e-4, -6.9011545676562133e-9, 1.8855128143995902e-4, -1.3395215663491969e-4, + 4.6263183033528039e-5, 4.0034230613321351e-11, -1.0255652921494033e-5, 6.612086372797651e-6, + -2.0913022027253008e-6, -2.0951775649603837e-13, 3.9756029041993247e-7, -2.3956211978815887e-7, + 7.1182883382145864e-8, 8.925574873053455e-16, -1.2101547235064676e-8, 6.9350618248334386e-9, + -1.9661464453856102e-9}, + {1.7402027787522711e-2, -2.9527880945699121e-2, 2.0045875571402799e-2, 7.0289515966903407e-6, + -1.2375421071343148e-2, 1.1976293444235254e-2, -5.4156038466518525e-3, -6.3290893396418616e-8, + 1.8855118129005065e-3, -1.473473274825001e-3, 5.5515810097708387e-4, 5.2406834412550662e-10, + -1.4357913535784836e-4, 9.9181293224943297e-5, -3.3460834749478311e-5, -3.5755837291098993e-12, + 7.1560851960630076e-6, -4.5516802628155526e-6, 1.4236576649271475e-6, 1.8803149082089664e-14, + -2.6623403898929211e-7, 1.5950642189595716e-7, -4.7187514673841102e-8, -6.5107872958755177e-17, + 7.9795091026746235e-9}, + {3.0249124160905891e-2, 2.4817436002649977e-3, -4.9939134373457022e-2, 5.9915643009307869e-2, + -3.2483207601623391e-2, -5.7212968652103441e-6, 1.5085251778569354e-2, -1.3261324005088445e-2, + 5.5515262632426148e-3, 3.0263182257030016e-8, -1.7229548406756723e-3, 1.2893570099929637e-3, + -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4, -7.7378565221244477e-5, + 2.5625836246985201e-5, 1.0766165333192814e-12, -5.3246809282422621e-6, 3.349634863064464e-6, + -1.0381253128684018e-6, -5.608909920621128e-15, 1.9150821930676591e-7, -1.1418365800203486e-7, + 3.3654425209171788e-8}, + {-9.9051020880159045e-2, 1.7954011706123486e-1, -1.2989606383463778e-1, -3.1478872752284357e-5, + 9.0510635276848131e-2, -9.2828824411184397e-2, 4.4412112839877808e-2, 2.7779236316835888e-7, + -1.7229543805449697e-2, 1.4182925050891573e-2, -5.6214161633747336e-3, -2.39598509186381e-9, + 1.6029634366079908e-3, -1.1606784674435773e-3, 4.1001337768153873e-4, 1.8365800754090661e-11, + -9.5844256563655903e-5, 6.3643062337764708e-5, -2.076250624489065e-5, -1.1806020912804483e-13, + 4.2131808239120649e-6, -2.6262241337012467e-6, 8.0770620494930662e-7, 6.0125912123632725e-16, + -1.4729737374018841e-7}, + {-1.9994542198219728e-1, -1.5056113040026424e-2, 3.6470239469348489e-1, -4.6435192311733545e-1, + 2.6640934719197893e-1, 3.4038266027147191e-5, -1.3784338709329624e-1, 1.276467178337056e-1, + -5.6213828755200985e-2, -1.753150885483011e-7, 1.9235592956768113e-2, -1.5088821281095315e-2, + 5.7401854451350123e-3, 1.0622382710310225e-9, -1.5335082692563998e-3, 1.0819320643228214e-3, + -3.7372510193945659e-4, -6.6170909729031985e-12, 8.4263617380909628e-5, -5.5150706827483479e-5, + 1.7769536448348069e-5, 3.8827923210205533e-14, -3.53513697488768e-6, 2.1865832130045269e-6, + -6.6812849447625594e-7}, + {7.2438608504029431e-1, -1.3918010932653375, 1.0654143352413968, 1.876173868950258e-4, + -8.2705501176152696e-1, 8.9352433347828414e-1, -4.4971003995291339e-1, -1.6107401567546652e-6, + 1.9235590165271091e-1, -1.6597702160042609e-1, 6.8882222681814333e-2, 1.3910091724608687e-8, + -2.146911561508663e-2, 1.6228980898865892e-2, -5.9796016172584256e-3, -1.1287469112826745e-10, + 1.5167451119784857e-3, -1.0478634293553899e-3, 3.5539072889126421e-4, 8.1704322111801517e-13, + -7.7773013442452395e-5, 5.0291413897007722e-5, -1.6035083867000518e-5, 1.2469354315487605e-14, + 3.1369106244517615e-6}, + {1.6668949727276811, 1.165462765994632e-1, -3.3288393225018906, 4.4692325482864037, + -2.6977693045875807, -2.600667859891061e-4, 1.5389017615694539, -1.4937962361134612, + 6.8881964633233148e-1, 1.3077482004552385e-6, -2.5762963325596288e-1, 2.1097676102125449e-1, + -8.3714408359219882e-2, -7.7920428881354753e-9, 2.4267923064833599e-2, -1.7813678334552311e-2, + 6.3970330388900056e-3, 4.9430807090480523e-11, -1.5554602758465635e-3, 1.0561196919903214e-3, + -3.5277184460472902e-4, 9.3002334645022459e-14, 7.5285855026557172e-5, -4.8186515569156351e-5, + 1.5227271505597605e-5}, + {-6.6188298861372935, 1.3397985455142589e+1, -1.0789350606845146e+1, -1.4352254537875018e-3, + 9.2333694596189809, -1.0456552819547769e+1, 5.5105526029033471, 1.2024439690716742e-5, + -2.5762961164755816, 2.3207442745387179, -1.0045728797216284, -1.0207833290021914e-7, + 3.3975092171169466e-1, -2.6720517450757468e-1, 1.0235252851562706e-1, 8.4329730484871625e-10, + -2.7998284958442595e-2, 2.0066274144976813e-2, -7.0554368915086242e-3, 1.9402238183698188e-12, + 1.6562888105449611e-3, -1.1082898580743683e-3, 3.654545161310169e-4, -5.1290032026971794e-11, + -7.6340103696869031e-5}, + {-1.7112706061976095e+1, -1.1208044642899116, 3.7131966511885444e+1, -5.2298271025348962e+1, + 3.3058589696624618e+1, 2.4791298976200222e-3, -2.061089403411526e+1, 2.088672775145582e+1, + -1.0045703956517752e+1, -1.2238783449063012e-5, 4.0770134274221141, -3.473667358470195, + 1.4329352617312006, 7.1359914411879712e-8, -4.4797257159115612e-1, 3.4112666080644461e-1, + -1.2699786326594923e-1, -2.8953677269081528e-10, 3.3125776278259863e-2, -2.3274087021036101e-2, + 8.0399993503648882e-3, -1.177805216235265e-9, -1.8321624891071668e-3, 1.2108282933588665e-3, + -3.9479941246822517e-4}, + {7.389033153567425e+1, -1.5680141270402273e+2, 1.322177542759164e+2, 1.3692876877324546e-2, + -1.2366496885920151e+2, 1.4620689391062729e+2, -8.0365587724865346e+1, -1.1259851148881298e-4, + 4.0770132196179938e+1, -3.8210340013273034e+1, 1.719522294277362e+1, 9.3519707955168356e-7, + -6.2716159907747034, 5.1168999071852637, -2.0319658112299095, -4.9507215582761543e-9, + 5.9626397294332597e-1, -4.4220765337238094e-1, 1.6079998700166273e-1, -2.4733786203223402e-8, + -4.0307574759979762e-2, 2.7849050747097869e-2, -9.4751858992054221e-3, 6.419922235909132e-6, + 2.1250180774699461e-3}, + {2.1216837098382522e+2, 1.3107863022633868e+1, -4.9698285932871748e+2, 7.3121595266969204e+2, + -4.8213821720890847e+2, -2.8817248692894889e-2, 3.2616720302947102e+2, -3.4389340280087117e+2, + 1.7195193870816232e+2, 1.4038077378096158e-4, -7.52594195897599e+1, 6.651969984520934e+1, + -2.8447519748152462e+1, -7.613702615875391e-7, 9.5402237105304373, -7.5175301113311376, + 2.8943997568871961, -4.6612194999538201e-7, -8.0615149598794088e-1, 5.8483006570631029e-1, + -2.0845408972964956e-1, 1.4765818959305817e-4, 5.1000433863753019e-2, -3.3066252141883665e-2, + 1.5109265210467774e-2}, + {-9.8959643098322368e+2, 2.1925555360905233e+3, -1.9283586782723356e+3, -1.5925738122215253e-1, + 1.9569985945919857e+3, -2.4072514765081556e+3, 1.3756149959336496e+3, 1.2920735237496668e-3, + -7.525941715948055e+2, 7.3171668742208716e+2, -3.4137023466220065e+2, -9.9857390260608043e-6, + 1.3356313181291573e+2, -1.1276295161252794e+2, 4.6310396098204458e+1, -7.9237387133614756e-6, + -1.4510726927018646e+1, 1.1111771248100563e+1, -4.1690817945270892, 3.1008219800117808e-3, + 1.1220095449981468, -7.6052379926149916e-1, 3.6262236505085254e-1, 2.216867741940747e-1, + 4.8683443692930507e-1}}; + + } // namespace detail +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h new file mode 100644 index 0000000000000000000000000000000000000000..ff82c35f682b04a250f6a86721312f860b3fe7cb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h @@ -0,0 +1,313 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* + * (C) Copyright John Maddock 2006. + * Use, modification and distribution are subject to the + * Boost Software License, Version 1.0. (See accompanying file + * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "gamma.h" +#include "igam.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + XSF_HOST_DEVICE double find_inverse_s(double p, double q) { + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 32. + */ + double s, t; + constexpr double a[4] = {0.213623493715853, 4.28342155967104, 11.6616720288968, 3.31125922108741}; + constexpr double b[5] = {0.3611708101884203e-1, 1.27364489782223, 6.40691597760039, 6.61053765625462, 1}; + + if (p < 0.5) { + t = std::sqrt(-2 * std::log(p)); + } else { + t = std::sqrt(-2 * std::log(q)); + } + s = t - polevl(t, a, 3) / polevl(t, b, 4); + if (p < 0.5) + s = -s; + return s; + } + + XSF_HOST_DEVICE inline double didonato_SN(double a, double x, unsigned N, double tolerance) { + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 34. + */ + double sum = 1.0; + + if (N >= 1) { + unsigned i; + double partial = x / (a + 1); + + sum += partial; + for (i = 2; i <= N; ++i) { + partial *= x / (a + i); + sum += partial; + if (partial < tolerance) { + break; + } + } + } + return sum; + } + + XSF_HOST_DEVICE inline double find_inverse_gamma(double a, double p, double q) { + /* + * In order to understand what's going on here, you will + * need to refer to: + * + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + */ + double result; + + if (a == 1) { + if (q > 0.9) { + result = -std::log1p(-p); + } else { + result = -std::log(q); + } + } else if (a < 1) { + double g = xsf::cephes::Gamma(a); + double b = q * g; + + if ((b > 0.6) || ((b >= 0.45) && (a >= 0.3))) { + /* DiDonato & Morris Eq 21: + * + * There is a slight variation from DiDonato and Morris here: + * the first form given here is unstable when p is close to 1, + * making it impossible to compute the inverse of Q(a,x) for small + * q. Fortunately the second form works perfectly well in this case. + */ + double u; + if ((b * q > 1e-8) && (q > 1e-5)) { + u = std::pow(p * g * a, 1 / a); + } else { + u = std::exp((-q / a) - SCIPY_EULER); + } + result = u / (1 - (u / (a + 1))); + } else if ((a < 0.3) && (b >= 0.35)) { + /* DiDonato & Morris Eq 22: */ + double t = std::exp(-SCIPY_EULER - b); + double u = t * std::exp(t); + result = t * std::exp(u); + } else if ((b > 0.15) || (a >= 0.3)) { + /* DiDonato & Morris Eq 23: */ + double y = -std::log(b); + double u = y - (1 - a) * std::log(y); + result = y - (1 - a) * std::log(u) - std::log(1 + (1 - a) / (1 + u)); + } else if (b > 0.1) { + /* DiDonato & Morris Eq 24: */ + double y = -std::log(b); + double u = y - (1 - a) * std::log(y); + result = y - (1 - a) * std::log(u) - + std::log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) / (u * u + (5 - a) * u + 2)); + } else { + /* DiDonato & Morris Eq 25: */ + double y = -std::log(b); + double c1 = (a - 1) * std::log(y); + double c1_2 = c1 * c1; + double c1_3 = c1_2 * c1; + double c1_4 = c1_2 * c1_2; + double a_2 = a * a; + double a_3 = a_2 * a; + + double c2 = (a - 1) * (1 + c1); + double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2); + double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + double c5 = (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + double y_2 = y * y; + double y_3 = y_2 * y; + double y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4); + } + } else { + /* DiDonato and Morris Eq 31: */ + double s = find_inverse_s(p, q); + + double s_2 = s * s; + double s_3 = s_2 * s; + double s_4 = s_2 * s_2; + double s_5 = s_4 * s; + double ra = std::sqrt(a); + + double w = a + s * ra + (s_2 - 1) / 3; + w += (s_3 - 7 * s) / (36 * ra); + w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a); + w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra); + + if ((a >= 500) && (std::abs(1 - w / a) < 1e-6)) { + result = w; + } else if (p > 0.5) { + if (w < 3 * a) { + result = w; + } else { + double D = std::fmax(2, a * (a - 1)); + double lg = xsf::cephes::lgam(a); + double lb = std::log(q) + lg; + if (lb < -D * 2.3) { + /* DiDonato and Morris Eq 25: */ + double y = -lb; + double c1 = (a - 1) * std::log(y); + double c1_2 = c1 * c1; + double c1_3 = c1_2 * c1; + double c1_4 = c1_2 * c1_2; + double a_2 = a * a; + double a_3 = a_2 * a; + + double c2 = (a - 1) * (1 + c1); + double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2); + double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + double c5 = + (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + double y_2 = y * y; + double y_3 = y_2 * y; + double y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4); + } else { + /* DiDonato and Morris Eq 33: */ + double u = -lb + (a - 1) * std::log(w) - std::log(1 + (1 - a) / (1 + w)); + result = -lb + (a - 1) * std::log(u) - std::log(1 + (1 - a) / (1 + u)); + } + } + } else { + double z = w; + double ap1 = a + 1; + double ap2 = a + 2; + if (w < 0.15 * ap1) { + /* DiDonato and Morris Eq 35: */ + double v = std::log(p) + xsf::cephes::lgam(ap1); + z = std::exp((v + w) / a); + s = std::log1p(z / ap1 * (1 + z / ap2)); + z = std::exp((v + z - s) / a); + s = std::log1p(z / ap1 * (1 + z / ap2)); + z = std::exp((v + z - s) / a); + s = std::log1p(z / ap1 * (1 + z / ap2 * (1 + z / (a + 3)))); + z = std::exp((v + z - s) / a); + } + + if ((z <= 0.01 * ap1) || (z > 0.7 * ap1)) { + result = z; + } else { + /* DiDonato and Morris Eq 36: */ + double ls = std::log(didonato_SN(a, z, 100, 1e-4)); + double v = std::log(p) + xsf::cephes::lgam(ap1); + z = std::exp((v + z - ls) / a); + result = z * (1 - (a * std::log(z) - z - v + ls) / (a - z)); + } + } + } + return result; + } + + } // namespace detail + + XSF_HOST_DEVICE inline double igamci(double a, double q); + + XSF_HOST_DEVICE inline double igami(double a, double p) { + int i; + double x, fac, f_fp, fpp_fp; + + if (std::isnan(a) || std::isnan(p)) { + return std::numeric_limits::quiet_NaN(); + ; + } else if ((a < 0) || (p < 0) || (p > 1)) { + set_error("gammaincinv", SF_ERROR_DOMAIN, NULL); + } else if (p == 0.0) { + return 0.0; + } else if (p == 1.0) { + return std::numeric_limits::infinity(); + } else if (p > 0.9) { + return igamci(a, 1 - p); + } + + x = detail::find_inverse_gamma(a, p, 1 - p); + /* Halley's method */ + for (i = 0; i < 3; i++) { + fac = detail::igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (igam(a, x) - p) * x / fac; + /* The ratio of the first and second derivatives simplifies */ + fpp_fp = -1.0 + (a - 1) / x; + if (std::isinf(fpp_fp)) { + /* Resort to Newton's method in the case of overflow */ + x = x - f_fp; + } else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; + } + + XSF_HOST_DEVICE inline double igamci(double a, double q) { + int i; + double x, fac, f_fp, fpp_fp; + + if (std::isnan(a) || std::isnan(q)) { + return std::numeric_limits::quiet_NaN(); + } else if ((a < 0.0) || (q < 0.0) || (q > 1.0)) { + set_error("gammainccinv", SF_ERROR_DOMAIN, NULL); + } else if (q == 0.0) { + return std::numeric_limits::infinity(); + } else if (q == 1.0) { + return 0.0; + } else if (q > 0.9) { + return igami(a, 1 - q); + } + + x = detail::find_inverse_gamma(a, 1 - q, q); + for (i = 0; i < 3; i++) { + fac = detail::igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (igamc(a, x) - q) * x / (-fac); + fpp_fp = -1.0 + (a - 1) / x; + if (std::isinf(fpp_fp)) { + x = x - f_fp; + } else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h new file mode 100644 index 0000000000000000000000000000000000000000..29236ef966e05f615920b381489e627950e78740 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h @@ -0,0 +1,225 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* j0.c + * + * Bessel function of order zero + * + * + * + * SYNOPSIS: + * + * double x, y, j0(); + * + * y = j0( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of order zero of the argument. + * + * The domain is divided into the intervals [0, 5] and + * (5, infinity). In the first interval the following rational + * approximation is used: + * + * + * 2 2 + * (w - r ) (w - r ) P (w) / Q (w) + * 1 2 3 8 + * + * 2 + * where w = x and the two r's are zeros of the function. + * + * In the second interval, the Hankel asymptotic expansion + * is employed with two rational functions of degree 6/6 + * and 7/7. + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 60000 4.2e-16 1.1e-16 + * + */ +/* y0.c + * + * Bessel function of the second kind, order zero + * + * + * + * SYNOPSIS: + * + * double x, y, y0(); + * + * y = y0( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of the second kind, of order + * zero, of the argument. + * + * The domain is divided into the intervals [0, 5] and + * (5, infinity). In the first interval a rational approximation + * R(x) is employed to compute + * y0(x) = R(x) + 2 * log(x) * j0(x) / M_PI. + * Thus a call to j0() is required. + * + * In the second interval, the Hankel asymptotic expansion + * is employed with two rational functions of degree 6/6 + * and 7/7. + * + * + * + * ACCURACY: + * + * Absolute error, when y0(x) < 1; else relative error: + * + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.3e-15 1.6e-16 + * + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier + */ + +/* Note: all coefficients satisfy the relative error criterion + * except YP, YQ which are designed for absolute error. */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double j0_PP[7] = { + 7.96936729297347051624E-4, 8.28352392107440799803E-2, 1.23953371646414299388E0, 5.44725003058768775090E0, + 8.74716500199817011941E0, 5.30324038235394892183E0, 9.99999999999999997821E-1, + }; + + constexpr double j0_PQ[7] = { + 9.24408810558863637013E-4, 8.56288474354474431428E-2, 1.25352743901058953537E0, 5.47097740330417105182E0, + 8.76190883237069594232E0, 5.30605288235394617618E0, 1.00000000000000000218E0, + }; + + constexpr double j0_QP[8] = { + -1.13663838898469149931E-2, -1.28252718670509318512E0, -1.95539544257735972385E1, -9.32060152123768231369E1, + -1.77681167980488050595E2, -1.47077505154951170175E2, -5.14105326766599330220E1, -6.05014350600728481186E0, + }; + + constexpr double j0_QQ[7] = { + /* 1.00000000000000000000E0, */ + 6.43178256118178023184E1, 8.56430025976980587198E2, 3.88240183605401609683E3, 7.24046774195652478189E3, + 5.93072701187316984827E3, 2.06209331660327847417E3, 2.42005740240291393179E2, + }; + + constexpr double j0_YP[8] = { + 1.55924367855235737965E4, -1.46639295903971606143E7, 5.43526477051876500413E9, + -9.82136065717911466409E11, 8.75906394395366999549E13, -3.46628303384729719441E15, + 4.42733268572569800351E16, -1.84950800436986690637E16, + }; + + constexpr double j0_YQ[7] = { + /* 1.00000000000000000000E0, */ + 1.04128353664259848412E3, 6.26107330137134956842E5, 2.68919633393814121987E8, 8.64002487103935000337E10, + 2.02979612750105546709E13, 3.17157752842975028269E15, 2.50596256172653059228E17, + }; + + /* 5.783185962946784521175995758455807035071 */ + constexpr double j0_DR1 = 5.78318596294678452118E0; + + /* 30.47126234366208639907816317502275584842 */ + constexpr double j0_DR2 = 3.04712623436620863991E1; + + constexpr double j0_RP[4] = { + -4.79443220978201773821E9, + 1.95617491946556577543E12, + -2.49248344360967716204E14, + 9.70862251047306323952E15, + }; + + constexpr double j0_RQ[8] = { + /* 1.00000000000000000000E0, */ + 4.99563147152651017219E2, 1.73785401676374683123E5, 4.84409658339962045305E7, 1.11855537045356834862E10, + 2.11277520115489217587E12, 3.10518229857422583814E14, 3.18121955943204943306E16, 1.71086294081043136091E18, + }; + + } // namespace detail + + XSF_HOST_DEVICE inline double j0(double x) { + double w, z, p, q, xn; + + if (x < 0) { + x = -x; + } + + if (x <= 5.0) { + z = x * x; + if (x < 1.0e-5) { + return (1.0 - z / 4.0); + } + + p = (z - detail::j0_DR1) * (z - detail::j0_DR2); + p = p * polevl(z, detail::j0_RP, 3) / p1evl(z, detail::j0_RQ, 8); + return (p); + } + + w = 5.0 / x; + q = 25.0 / (x * x); + p = polevl(q, detail::j0_PP, 6) / polevl(q, detail::j0_PQ, 6); + q = polevl(q, detail::j0_QP, 7) / p1evl(q, detail::j0_QQ, 7); + xn = x - M_PI_4; + p = p * std::cos(xn) - w * q * std::sin(xn); + return (p * detail::SQRT2OPI / std::sqrt(x)); + } + + /* y0() 2 */ + /* Bessel function of second kind, order zero */ + + /* Rational approximation coefficients YP[], YQ[] are used here. + * The function computed is y0(x) - 2 * log(x) * j0(x) / M_PI, + * whose value at x = 0 is 2 * ( log(0.5) + EUL ) / M_PI + * = 0.073804295108687225. + */ + + XSF_HOST_DEVICE inline double y0(double x) { + double w, z, p, q, xn; + + if (x <= 5.0) { + if (x == 0.0) { + set_error("y0", SF_ERROR_SINGULAR, NULL); + return -std::numeric_limits::infinity(); + } else if (x < 0.0) { + set_error("y0", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + z = x * x; + w = polevl(z, detail::j0_YP, 7) / p1evl(z, detail::j0_YQ, 7); + w += M_2_PI * std::log(x) * j0(x); + return (w); + } + + w = 5.0 / x; + z = 25.0 / (x * x); + p = polevl(z, detail::j0_PP, 6) / polevl(z, detail::j0_PQ, 6); + q = polevl(z, detail::j0_QP, 7) / p1evl(z, detail::j0_QQ, 7); + xn = x - M_PI_4; + p = p * std::sin(xn) + w * q * std::cos(xn); + return (p * detail::SQRT2OPI / std::sqrt(x)); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h new file mode 100644 index 0000000000000000000000000000000000000000..46532249550d214723291f7ca9874bb4a31380ac --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h @@ -0,0 +1,198 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* j1.c + * + * Bessel function of order one + * + * + * + * SYNOPSIS: + * + * double x, y, j1(); + * + * y = j1( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of order one of the argument. + * + * The domain is divided into the intervals [0, 8] and + * (8, infinity). In the first interval a 24 term Chebyshev + * expansion is used. In the second, the asymptotic + * trigonometric representation is employed using two + * rational functions of degree 5/5. + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 2.6e-16 1.1e-16 + * + * + */ +/* y1.c + * + * Bessel function of second kind of order one + * + * + * + * SYNOPSIS: + * + * double x, y, y1(); + * + * y = y1( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of the second kind of order one + * of the argument. + * + * The domain is divided into the intervals [0, 8] and + * (8, infinity). In the first interval a 25 term Chebyshev + * expansion is used, and a call to j1() is required. + * In the second, the asymptotic trigonometric representation + * is employed using two rational functions of degree 5/5. + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.0e-15 1.3e-16 + * + * (error criterion relative when |y1| > 1). + * + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier + */ + +/* + * #define PIO4 .78539816339744830962 + * #define THPIO4 2.35619449019234492885 + * #define SQ2OPI .79788456080286535588 + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + constexpr double j1_RP[4] = { + -8.99971225705559398224E8, + 4.52228297998194034323E11, + -7.27494245221818276015E13, + 3.68295732863852883286E15, + }; + + constexpr double j1_RQ[8] = { + /* 1.00000000000000000000E0, */ + 6.20836478118054335476E2, 2.56987256757748830383E5, 8.35146791431949253037E7, 2.21511595479792499675E10, + 4.74914122079991414898E12, 7.84369607876235854894E14, 8.95222336184627338078E16, 5.32278620332680085395E18, + }; + + constexpr double j1_PP[7] = { + 7.62125616208173112003E-4, 7.31397056940917570436E-2, 1.12719608129684925192E0, 5.11207951146807644818E0, + 8.42404590141772420927E0, 5.21451598682361504063E0, 1.00000000000000000254E0, + }; + + constexpr double j1_PQ[7] = { + 5.71323128072548699714E-4, 6.88455908754495404082E-2, 1.10514232634061696926E0, 5.07386386128601488557E0, + 8.39985554327604159757E0, 5.20982848682361821619E0, 9.99999999999999997461E-1, + }; + + constexpr double j1_QP[8] = { + 5.10862594750176621635E-2, 4.98213872951233449420E0, 7.58238284132545283818E1, 3.66779609360150777800E2, + 7.10856304998926107277E2, 5.97489612400613639965E2, 2.11688757100572135698E2, 2.52070205858023719784E1, + }; + + constexpr double j1_QQ[7] = { + /* 1.00000000000000000000E0, */ + 7.42373277035675149943E1, 1.05644886038262816351E3, 4.98641058337653607651E3, 9.56231892404756170795E3, + 7.99704160447350683650E3, 2.82619278517639096600E3, 3.36093607810698293419E2, + }; + + constexpr double j1_YP[6] = { + 1.26320474790178026440E9, -6.47355876379160291031E11, 1.14509511541823727583E14, + -8.12770255501325109621E15, 2.02439475713594898196E17, -7.78877196265950026825E17, + }; + + constexpr double j1_YQ[8] = { + /* 1.00000000000000000000E0, */ + 5.94301592346128195359E2, 2.35564092943068577943E5, 7.34811944459721705660E7, 1.87601316108706159478E10, + 3.88231277496238566008E12, 6.20557727146953693363E14, 6.87141087355300489866E16, 3.97270608116560655612E18, + }; + + constexpr double j1_Z1 = 1.46819706421238932572E1; + constexpr double j1_Z2 = 4.92184563216946036703E1; + + } // namespace detail + + XSF_HOST_DEVICE inline double j1(double x) { + double w, z, p, q, xn; + + w = x; + if (x < 0) { + return -j1(-x); + } + + if (w <= 5.0) { + z = x * x; + w = polevl(z, detail::j1_RP, 3) / p1evl(z, detail::j1_RQ, 8); + w = w * x * (z - detail::j1_Z1) * (z - detail::j1_Z2); + return (w); + } + + w = 5.0 / x; + z = w * w; + p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6); + q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7); + xn = x - detail::THPIO4; + p = p * std::cos(xn) - w * q * std::sin(xn); + return (p * detail::SQRT2OPI / std::sqrt(x)); + } + + XSF_HOST_DEVICE inline double y1(double x) { + double w, z, p, q, xn; + + if (x <= 5.0) { + if (x == 0.0) { + set_error("y1", SF_ERROR_SINGULAR, NULL); + return -std::numeric_limits::infinity(); + } else if (x <= 0.0) { + set_error("y1", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + z = x * x; + w = x * (polevl(z, detail::j1_YP, 5) / p1evl(z, detail::j1_YQ, 8)); + w += M_2_PI * (j1(x) * std::log(x) - 1.0 / x); + return (w); + } + + w = 5.0 / x; + z = w * w; + p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6); + q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7); + xn = x - detail::THPIO4; + p = p * std::sin(xn) + w * q * std::cos(xn); + return (p * detail::SQRT2OPI / std::sqrt(x)); + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h new file mode 100644 index 0000000000000000000000000000000000000000..db5272f27fb4e6619dafaa02f9fc2cd2b2f57f9e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h @@ -0,0 +1,715 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* jv.c + * + * Bessel function of noninteger order + * + * + * + * SYNOPSIS: + * + * double v, x, y, jv(); + * + * y = jv( v, x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of order v of the argument, + * where v is real. Negative x is allowed if v is an integer. + * + * Several expansions are included: the ascending power + * series, the Hankel expansion, and two transitional + * expansions for large v. If v is not too large, it + * is reduced by recurrence to a region of best accuracy. + * The transitional expansions give 12D accuracy for v > 500. + * + * + * + * ACCURACY: + * Results for integer v are indicated by *, where x and v + * both vary from -125 to +125. Otherwise, + * x ranges from 0 to 125, v ranges as indicated by "domain." + * Error criterion is absolute, except relative when |jv()| > 1. + * + * arithmetic v domain x domain # trials peak rms + * IEEE 0,125 0,125 100000 4.6e-15 2.2e-16 + * IEEE -125,0 0,125 40000 5.4e-11 3.7e-13 + * IEEE 0,500 0,500 20000 4.4e-15 4.0e-16 + * Integer v: + * IEEE -125,125 -125,125 50000 3.5e-15* 1.9e-16* + * + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "airy.h" +#include "cbrt.h" +#include "rgamma.h" +#include "j0.h" +#include "j1.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double jv_BIG = 1.44115188075855872E+17; + + /* Reduce the order by backward recurrence. + * AMS55 #9.1.27 and 9.1.73. + */ + + XSF_HOST_DEVICE inline double jv_recur(double *n, double x, double *newn, int cancel) { + double pkm2, pkm1, pk, qkm2, qkm1; + + /* double pkp1; */ + double k, ans, qk, xk, yk, r, t, kf; + constexpr double big = jv_BIG; + int nflag, ctr; + int miniter, maxiter; + + /* Continued fraction for Jn(x)/Jn-1(x) + * AMS 9.1.73 + * + * x -x^2 -x^2 + * ------ --------- --------- ... + * 2 n + 2(n+1) + 2(n+2) + + * + * Compute it with the simplest possible algorithm. + * + * This continued fraction starts to converge when (|n| + m) > |x|. + * Hence, at least |x|-|n| iterations are necessary before convergence is + * achieved. There is a hard limit set below, m <= 30000, which is chosen + * so that no branch in `jv` requires more iterations to converge. + * The exact maximum number is (500/3.6)^2 - 500 ~ 19000 + */ + + maxiter = 22000; + miniter = std::abs(x) - std::abs(*n); + if (miniter < 1) { + miniter = 1; + } + + if (*n < 0.0) { + nflag = 1; + } else { + nflag = 0; + } + + fstart: + pkm2 = 0.0; + qkm2 = 1.0; + pkm1 = x; + qkm1 = *n + *n; + xk = -x * x; + yk = qkm1; + ans = 0.0; /* ans=0.0 ensures that t=1.0 in the first iteration */ + ctr = 0; + do { + yk += 2.0; + pk = pkm1 * yk + pkm2 * xk; + qk = qkm1 * yk + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + + /* check convergence */ + if (qk != 0 && ctr > miniter) + r = pk / qk; + else + r = 0.0; + + if (r != 0) { + t = std::abs((ans - r) / r); + ans = r; + } else { + t = 1.0; + } + + if (++ctr > maxiter) { + set_error("jv", SF_ERROR_UNDERFLOW, NULL); + goto done; + } + if (t < MACHEP) { + goto done; + } + + /* renormalize coefficients */ + if (std::abs(pk) > big) { + pkm2 /= big; + pkm1 /= big; + qkm2 /= big; + qkm1 /= big; + } + } while (t > MACHEP); + + done: + if (ans == 0) + ans = 1.0; + + /* Change n to n-1 if n < 0 and the continued fraction is small */ + if (nflag > 0) { + if (std::abs(ans) < 0.125) { + nflag = -1; + *n = *n - 1.0; + goto fstart; + } + } + + kf = *newn; + + /* backward recurrence + * 2k + * J (x) = --- J (x) - J (x) + * k-1 x k k+1 + */ + + pk = 1.0; + pkm1 = 1.0 / ans; + k = *n - 1.0; + r = 2 * k; + do { + pkm2 = (pkm1 * r - pk * x) / x; + /* pkp1 = pk; */ + pk = pkm1; + pkm1 = pkm2; + r -= 2.0; + /* + * t = fabs(pkp1) + fabs(pk); + * if( (k > (kf + 2.5)) && (fabs(pkm1) < 0.25*t) ) + * { + * k -= 1.0; + * t = x*x; + * pkm2 = ( (r*(r+2.0)-t)*pk - r*x*pkp1 )/t; + * pkp1 = pk; + * pk = pkm1; + * pkm1 = pkm2; + * r -= 2.0; + * } + */ + k -= 1.0; + } while (k > (kf + 0.5)); + + /* Take the larger of the last two iterates + * on the theory that it may have less cancellation error. + */ + + if (cancel) { + if ((kf >= 0.0) && (std::abs(pk) > std::abs(pkm1))) { + k += 1.0; + pkm2 = pk; + } + } + *newn = k; + return (pkm2); + } + + /* Ascending power series for Jv(x). + * AMS55 #9.1.10. + */ + + XSF_HOST_DEVICE inline double jv_jvs(double n, double x) { + double t, u, y, z, k; + int ex, sgngam; + + z = -x * x / 4.0; + u = 1.0; + y = u; + k = 1.0; + t = 1.0; + + while (t > MACHEP) { + u *= z / (k * (n + k)); + y += u; + k += 1.0; + if (y != 0) + t = std::abs(u / y); + } + t = std::frexp(0.5 * x, &ex); + ex = ex * n; + if ((ex > -1023) && (ex < 1023) && (n > 0.0) && (n < (MAXGAM - 1.0))) { + t = std::pow(0.5 * x, n) * xsf::cephes::rgamma(n + 1.0); + y *= t; + } else { + t = n * std::log(0.5 * x) - lgam_sgn(n + 1.0, &sgngam); + if (y < 0) { + sgngam = -sgngam; + y = -y; + } + t += std::log(y); + if (t < -MAXLOG) { + return (0.0); + } + if (t > MAXLOG) { + set_error("Jv", SF_ERROR_OVERFLOW, NULL); + return (std::numeric_limits::infinity()); + } + y = sgngam * std::exp(t); + } + return (y); + } + + /* Hankel's asymptotic expansion + * for large x. + * AMS55 #9.2.5. + */ + + XSF_HOST_DEVICE inline double jv_hankel(double n, double x) { + double t, u, z, k, sign, conv; + double p, q, j, m, pp, qq; + int flag; + + m = 4.0 * n * n; + j = 1.0; + z = 8.0 * x; + k = 1.0; + p = 1.0; + u = (m - 1.0) / z; + q = u; + sign = 1.0; + conv = 1.0; + flag = 0; + t = 1.0; + pp = 1.0e38; + qq = 1.0e38; + + while (t > MACHEP) { + k += 2.0; + j += 1.0; + sign = -sign; + u *= (m - k * k) / (j * z); + p += sign * u; + k += 2.0; + j += 1.0; + u *= (m - k * k) / (j * z); + q += sign * u; + t = std::abs(u / p); + if (t < conv) { + conv = t; + qq = q; + pp = p; + flag = 1; + } + /* stop if the terms start getting larger */ + if ((flag != 0) && (t > conv)) { + goto hank1; + } + } + + hank1: + u = x - (0.5 * n + 0.25) * M_PI; + t = std::sqrt(2.0 / (M_PI * x)) * (pp * std::cos(u) - qq * std::sin(u)); + return (t); + } + + /* Asymptotic expansion for transition region, + * n large and x close to n. + * AMS55 #9.3.23. + */ + + constexpr double jv_PF2[] = {-9.0000000000000000000e-2, 8.5714285714285714286e-2}; + + constexpr double jv_PF3[] = {1.3671428571428571429e-1, -5.4920634920634920635e-2, -4.4444444444444444444e-3}; + + constexpr double jv_PF4[] = {1.3500000000000000000e-3, -1.6036054421768707483e-1, 4.2590187590187590188e-2, + 2.7330447330447330447e-3}; + + constexpr double jv_PG1[] = {-2.4285714285714285714e-1, 1.4285714285714285714e-2}; + + constexpr double jv_PG2[] = {-9.0000000000000000000e-3, 1.9396825396825396825e-1, -1.1746031746031746032e-2}; + + constexpr double jv_PG3[] = {1.9607142857142857143e-2, -1.5983694083694083694e-1, 6.3838383838383838384e-3}; + + XSF_HOST_DEVICE inline double jv_jnt(double n, double x) { + double z, zz, z3; + double cbn, n23, cbtwo; + double ai, aip, bi, bip; /* Airy functions */ + double nk, fk, gk, pp, qq; + double F[5], G[4]; + int k; + + cbn = cbrt(n); + z = (x - n) / cbn; + cbtwo = cbrt(2.0); + + /* Airy function */ + zz = -cbtwo * z; + xsf::cephes::airy(zz, &ai, &aip, &bi, &bip); + + /* polynomials in expansion */ + zz = z * z; + z3 = zz * z; + F[0] = 1.0; + F[1] = -z / 5.0; + F[2] = xsf::cephes::polevl(z3, jv_PF2, 1) * zz; + F[3] = xsf::cephes::polevl(z3, jv_PF3, 2); + F[4] = xsf::cephes::polevl(z3, jv_PF4, 3) * z; + G[0] = 0.3 * zz; + G[1] = xsf::cephes::polevl(z3, jv_PG1, 1); + G[2] = xsf::cephes::polevl(z3, jv_PG2, 2) * z; + G[3] = xsf::cephes::polevl(z3, jv_PG3, 2) * zz; + + pp = 0.0; + qq = 0.0; + nk = 1.0; + n23 = cbrt(n * n); + + for (k = 0; k <= 4; k++) { + fk = F[k] * nk; + pp += fk; + if (k != 4) { + gk = G[k] * nk; + qq += gk; + } + nk /= n23; + } + + fk = cbtwo * ai * pp / cbn + cbrt(4.0) * aip * qq / n; + return (fk); + } + + /* Asymptotic expansion for large n. + * AMS55 #9.3.35. + */ + + constexpr double jv_lambda[] = {1.0, + 1.041666666666666666666667E-1, + 8.355034722222222222222222E-2, + 1.282265745563271604938272E-1, + 2.918490264641404642489712E-1, + 8.816272674437576524187671E-1, + 3.321408281862767544702647E+0, + 1.499576298686255465867237E+1, + 7.892301301158651813848139E+1, + 4.744515388682643231611949E+2, + 3.207490090890661934704328E+3}; + + constexpr double jv_mu[] = {1.0, + -1.458333333333333333333333E-1, + -9.874131944444444444444444E-2, + -1.433120539158950617283951E-1, + -3.172272026784135480967078E-1, + -9.424291479571202491373028E-1, + -3.511203040826354261542798E+0, + -1.572726362036804512982712E+1, + -8.228143909718594444224656E+1, + -4.923553705236705240352022E+2, + -3.316218568547972508762102E+3}; + + constexpr double jv_P1[] = {-2.083333333333333333333333E-1, 1.250000000000000000000000E-1}; + + constexpr double jv_P2[] = {3.342013888888888888888889E-1, -4.010416666666666666666667E-1, + 7.031250000000000000000000E-2}; + + constexpr double jv_P3[] = {-1.025812596450617283950617E+0, 1.846462673611111111111111E+0, + -8.912109375000000000000000E-1, 7.324218750000000000000000E-2}; + + constexpr double jv_P4[] = {4.669584423426247427983539E+0, -1.120700261622299382716049E+1, + 8.789123535156250000000000E+0, -2.364086914062500000000000E+0, + 1.121520996093750000000000E-1}; + + constexpr double jv_P5[] = {-2.8212072558200244877E1, 8.4636217674600734632E1, -9.1818241543240017361E1, + 4.2534998745388454861E1, -7.3687943594796316964E0, 2.27108001708984375E-1}; + + constexpr double jv_P6[] = {2.1257013003921712286E2, -7.6525246814118164230E2, 1.0599904525279998779E3, + -6.9957962737613254123E2, 2.1819051174421159048E2, -2.6491430486951555525E1, + 5.7250142097473144531E-1}; + + constexpr double jv_P7[] = {-1.9194576623184069963E3, 8.0617221817373093845E3, -1.3586550006434137439E4, + 1.1655393336864533248E4, -5.3056469786134031084E3, 1.2009029132163524628E3, + -1.0809091978839465550E2, 1.7277275025844573975E0}; + + XSF_HOST_DEVICE inline double jv_jnx(double n, double x) { + double zeta, sqz, zz, zp, np; + double cbn, n23, t, z, sz; + double pp, qq, z32i, zzi; + double ak, bk, akl, bkl; + int sign, doa, dob, nflg, k, s, tk, tkp1, m; + double u[8]; + double ai, aip, bi, bip; + + /* Test for x very close to n. Use expansion for transition region if so. */ + cbn = cbrt(n); + z = (x - n) / cbn; + if (std::abs(z) <= 0.7) { + return (jv_jnt(n, x)); + } + + z = x / n; + zz = 1.0 - z * z; + if (zz == 0.0) { + return (0.0); + } + + if (zz > 0.0) { + sz = std::sqrt(zz); + t = 1.5 * (std::log((1.0 + sz) / z) - sz); /* zeta ** 3/2 */ + zeta = cbrt(t * t); + nflg = 1; + } else { + sz = std::sqrt(-zz); + t = 1.5 * (sz - std::acos(1.0 / z)); + zeta = -cbrt(t * t); + nflg = -1; + } + z32i = std::abs(1.0 / t); + sqz = cbrt(t); + + /* Airy function */ + n23 = cbrt(n * n); + t = n23 * zeta; + + xsf::cephes::airy(t, &ai, &aip, &bi, &bip); + + /* polynomials in expansion */ + u[0] = 1.0; + zzi = 1.0 / zz; + u[1] = xsf::cephes::polevl(zzi, jv_P1, 1) / sz; + u[2] = xsf::cephes::polevl(zzi, jv_P2, 2) / zz; + u[3] = xsf::cephes::polevl(zzi, jv_P3, 3) / (sz * zz); + pp = zz * zz; + u[4] = xsf::cephes::polevl(zzi, jv_P4, 4) / pp; + u[5] = xsf::cephes::polevl(zzi, jv_P5, 5) / (pp * sz); + pp *= zz; + u[6] = xsf::cephes::polevl(zzi, jv_P6, 6) / pp; + u[7] = xsf::cephes::polevl(zzi, jv_P7, 7) / (pp * sz); + + pp = 0.0; + qq = 0.0; + np = 1.0; + /* flags to stop when terms get larger */ + doa = 1; + dob = 1; + akl = std::numeric_limits::infinity(); + bkl = std::numeric_limits::infinity(); + + for (k = 0; k <= 3; k++) { + tk = 2 * k; + tkp1 = tk + 1; + zp = 1.0; + ak = 0.0; + bk = 0.0; + for (s = 0; s <= tk; s++) { + if (doa) { + if ((s & 3) > 1) + sign = nflg; + else + sign = 1; + ak += sign * jv_mu[s] * zp * u[tk - s]; + } + + if (dob) { + m = tkp1 - s; + if (((m + 1) & 3) > 1) + sign = nflg; + else + sign = 1; + bk += sign * jv_lambda[s] * zp * u[m]; + } + zp *= z32i; + } + + if (doa) { + ak *= np; + t = std::abs(ak); + if (t < akl) { + akl = t; + pp += ak; + } else + doa = 0; + } + + if (dob) { + bk += jv_lambda[tkp1] * zp * u[0]; + bk *= -np / sqz; + t = std::abs(bk); + if (t < bkl) { + bkl = t; + qq += bk; + } else + dob = 0; + } + if (np < MACHEP) + break; + np /= n * n; + } + + /* normalizing factor ( 4*zeta/(1 - z**2) )**1/4 */ + t = 4.0 * zeta / zz; + t = sqrt(sqrt(t)); + + t *= ai * pp / cbrt(n) + aip * qq / (n23 * n); + return (t); + } + + } // namespace detail + + XSF_HOST_DEVICE inline double jv(double n, double x) { + double k, q, t, y, an; + int i, sign, nint; + + nint = 0; /* Flag for integer n */ + sign = 1; /* Flag for sign inversion */ + an = std::abs(n); + y = std::floor(an); + if (y == an) { + nint = 1; + i = an - 16384.0 * std::floor(an / 16384.0); + if (n < 0.0) { + if (i & 1) + sign = -sign; + n = an; + } + if (x < 0.0) { + if (i & 1) + sign = -sign; + x = -x; + } + if (n == 0.0) + return (j0(x)); + if (n == 1.0) + return (sign * j1(x)); + } + + if ((x < 0.0) && (y != an)) { + set_error("Jv", SF_ERROR_DOMAIN, NULL); + y = std::numeric_limits::quiet_NaN(); + goto done; + } + + if (x == 0 && n < 0 && !nint) { + set_error("Jv", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity() * rgamma(n + 1); + } + + y = std::abs(x); + + if (y * y < std::abs(n + 1) * detail::MACHEP) { + return std::pow(0.5 * x, n) * rgamma(n + 1); + } + + k = 3.6 * std::sqrt(y); + t = 3.6 * std::sqrt(an); + if ((y < t) && (an > 21.0)) { + return (sign * detail::jv_jvs(n, x)); + } + if ((an < k) && (y > 21.0)) + return (sign * detail::jv_hankel(n, x)); + + if (an < 500.0) { + /* Note: if x is too large, the continued fraction will fail; but then the + * Hankel expansion can be used. */ + if (nint != 0) { + k = 0.0; + q = detail::jv_recur(&n, x, &k, 1); + if (k == 0.0) { + y = j0(x) / q; + goto done; + } + if (k == 1.0) { + y = j1(x) / q; + goto done; + } + } + + if (an > 2.0 * y) + goto rlarger; + + if ((n >= 0.0) && (n < 20.0) && (y > 6.0) && (y < 20.0)) { + /* Recur backwards from a larger value of n */ + rlarger: + k = n; + + y = y + an + 1.0; + if (y < 30.0) + y = 30.0; + y = n + std::floor(y - n); + q = detail::jv_recur(&y, x, &k, 0); + y = detail::jv_jvs(y, x) * q; + goto done; + } + + if (k <= 30.0) { + k = 2.0; + } else if (k < 90.0) { + k = (3 * k) / 4; + } + if (an > (k + 3.0)) { + if (n < 0.0) { + k = -k; + } + q = n - std::floor(n); + k = std::floor(k) + q; + if (n > 0.0) { + q = detail::jv_recur(&n, x, &k, 1); + } else { + t = k; + k = n; + q = detail::jv_recur(&t, x, &k, 1); + k = t; + } + if (q == 0.0) { + y = 0.0; + goto done; + } + } else { + k = n; + q = 1.0; + } + + /* boundary between convergence of + * power series and Hankel expansion + */ + y = std::abs(k); + if (y < 26.0) + t = (0.0083 * y + 0.09) * y + 12.9; + else + t = 0.9 * y; + + if (x > t) + y = detail::jv_hankel(k, x); + else + y = detail::jv_jvs(k, x); + if (n > 0.0) + y /= q; + else + y *= q; + } + + else { + /* For large n, use the uniform expansion or the transitional expansion. + * But if x is of the order of n**2, these may blow up, whereas the + * Hankel expansion will then work. + */ + if (n < 0.0) { + set_error("jv", SF_ERROR_LOSS, NULL); + y = std::numeric_limits::quiet_NaN(); + goto done; + } + t = x / n; + t /= n; + if (t > 0.3) + y = detail::jv_hankel(n, x); + else + y = detail::jv_jnx(n, x); + } + + done: + return (sign * y); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h new file mode 100644 index 0000000000000000000000000000000000000000..f617b93c73009072498fe4f6f20671a9f83d84e1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h @@ -0,0 +1,164 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* k0.c + * + * Modified Bessel function, third kind, order zero + * + * + * + * SYNOPSIS: + * + * double x, y, k0(); + * + * y = k0( x ); + * + * + * + * DESCRIPTION: + * + * Returns modified Bessel function of the third kind + * of order zero of the argument. + * + * The range is partitioned into the two intervals [0,8] and + * (8, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Tested at 2000 random points between 0 and 8. Peak absolute + * error (relative when K0 > 1) was 1.46e-14; rms, 4.26e-15. + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.2e-15 1.6e-16 + * + * ERROR MESSAGES: + * + * message condition value returned + * K0 domain x <= 0 INFINITY + * + */ +/* k0e() + * + * Modified Bessel function, third kind, order zero, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, k0e(); + * + * y = k0e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order zero of the argument. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.4e-15 1.4e-16 + * See k0(). + * + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "chbevl.h" +#include "i0.h" + +namespace xsf { +namespace cephes { + + namespace detail { + /* Chebyshev coefficients for K0(x) + log(x/2) I0(x) + * in the interval [0,2]. The odd order coefficients are all + * zero; only the even order coefficients are listed. + * + * lim(x->0){ K0(x) + log(x/2) I0(x) } = -EUL. + */ + + constexpr double k0_A[] = {1.37446543561352307156E-16, 4.25981614279661018399E-14, 1.03496952576338420167E-11, + 1.90451637722020886025E-9, 2.53479107902614945675E-7, 2.28621210311945178607E-5, + 1.26461541144692592338E-3, 3.59799365153615016266E-2, 3.44289899924628486886E-1, + -5.35327393233902768720E-1}; + + /* Chebyshev coefficients for exp(x) sqrt(x) K0(x) + * in the inverted interval [2,infinity]. + * + * lim(x->inf){ exp(x) sqrt(x) K0(x) } = sqrt(pi/2). + */ + constexpr double k0_B[] = { + 5.30043377268626276149E-18, -1.64758043015242134646E-17, 5.21039150503902756861E-17, + -1.67823109680541210385E-16, 5.51205597852431940784E-16, -1.84859337734377901440E-15, + 6.34007647740507060557E-15, -2.22751332699166985548E-14, 8.03289077536357521100E-14, + -2.98009692317273043925E-13, 1.14034058820847496303E-12, -4.51459788337394416547E-12, + 1.85594911495471785253E-11, -7.95748924447710747776E-11, 3.57739728140030116597E-10, + -1.69753450938905987466E-9, 8.57403401741422608519E-9, -4.66048989768794782956E-8, + 2.76681363944501510342E-7, -1.83175552271911948767E-6, 1.39498137188764993662E-5, + -1.28495495816278026384E-4, 1.56988388573005337491E-3, -3.14481013119645005427E-2, + 2.44030308206595545468E0}; + + } // namespace detail + + XSF_HOST_DEVICE inline double k0(double x) { + double y, z; + + if (x == 0.0) { + set_error("k0", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } else if (x < 0.0) { + set_error("k0", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + if (x <= 2.0) { + y = x * x - 2.0; + y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x); + return (y); + } + z = 8.0 / x - 2.0; + y = std::exp(-x) * chbevl(z, detail::k0_B, 25) / std::sqrt(x); + return (y); + } + + XSF_HOST_DEVICE double inline k0e(double x) { + double y; + + if (x == 0.0) { + set_error("k0e", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } else if (x < 0.0) { + set_error("k0e", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + if (x <= 2.0) { + y = x * x - 2.0; + y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x); + return (y * exp(x)); + } + + y = chbevl(8.0 / x - 2.0, detail::k0_B, 25) / std::sqrt(x); + return (y); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h new file mode 100644 index 0000000000000000000000000000000000000000..96594fd9c345e6fd2ecf02a269601cd2d9592525 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h @@ -0,0 +1,163 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* k1.c + * + * Modified Bessel function, third kind, order one + * + * + * + * SYNOPSIS: + * + * double x, y, k1(); + * + * y = k1( x ); + * + * + * + * DESCRIPTION: + * + * Computes the modified Bessel function of the third kind + * of order one of the argument. + * + * The range is partitioned into the two intervals [0,2] and + * (2, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.2e-15 1.6e-16 + * + * ERROR MESSAGES: + * + * message condition value returned + * k1 domain x <= 0 INFINITY + * + */ +/* k1e.c + * + * Modified Bessel function, third kind, order one, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, k1e(); + * + * y = k1e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order one of the argument: + * + * k1e(x) = exp(x) * k1(x). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 7.8e-16 1.2e-16 + * See k1(). + * + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "chbevl.h" +#include "const.h" + +namespace xsf { +namespace cephes { + + namespace detail { + /* Chebyshev coefficients for x(K1(x) - log(x/2) I1(x)) + * in the interval [0,2]. + * + * lim(x->0){ x(K1(x) - log(x/2) I1(x)) } = 1. + */ + + constexpr double k1_A[] = { + -7.02386347938628759343E-18, -2.42744985051936593393E-15, -6.66690169419932900609E-13, + -1.41148839263352776110E-10, -2.21338763073472585583E-8, -2.43340614156596823496E-6, + -1.73028895751305206302E-4, -6.97572385963986435018E-3, -1.22611180822657148235E-1, + -3.53155960776544875667E-1, 1.52530022733894777053E0}; + + /* Chebyshev coefficients for exp(x) sqrt(x) K1(x) + * in the interval [2,infinity]. + * + * lim(x->inf){ exp(x) sqrt(x) K1(x) } = sqrt(pi/2). + */ + constexpr double k1_B[] = { + -5.75674448366501715755E-18, 1.79405087314755922667E-17, -5.68946255844285935196E-17, + 1.83809354436663880070E-16, -6.05704724837331885336E-16, 2.03870316562433424052E-15, + -7.01983709041831346144E-15, 2.47715442448130437068E-14, -8.97670518232499435011E-14, + 3.34841966607842919884E-13, -1.28917396095102890680E-12, 5.13963967348173025100E-12, + -2.12996783842756842877E-11, 9.21831518760500529508E-11, -4.19035475934189648750E-10, + 2.01504975519703286596E-9, -1.03457624656780970260E-8, 5.74108412545004946722E-8, + -3.50196060308781257119E-7, 2.40648494783721712015E-6, -1.93619797416608296024E-5, + 1.95215518471351631108E-4, -2.85781685962277938680E-3, 1.03923736576817238437E-1, + 2.72062619048444266945E0}; + + } // namespace detail + + XSF_HOST_DEVICE inline double k1(double x) { + double y, z; + + if (x == 0.0) { + set_error("k1", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } else if (x < 0.0) { + set_error("k1", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + z = 0.5 * x; + + if (x <= 2.0) { + y = x * x - 2.0; + y = std::log(z) * i1(x) + chbevl(y, detail::k1_A, 11) / x; + return (y); + } + + return (std::exp(-x) * chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x)); + } + + XSF_HOST_DEVICE double k1e(double x) { + double y; + + if (x == 0.0) { + set_error("k1e", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } else if (x < 0.0) { + set_error("k1e", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + if (x <= 2.0) { + y = x * x - 2.0; + y = std::log(0.5 * x) * i1(x) + chbevl(y, detail::k1_A, 11) / x; + return (y * exp(x)); + } + + return (chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x)); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h new file mode 100644 index 0000000000000000000000000000000000000000..31bc9fd7f735002f3381749f8d14c02545155c69 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h @@ -0,0 +1,243 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* kn.c + * + * Modified Bessel function, third kind, integer order + * + * + * + * SYNOPSIS: + * + * double x, y, kn(); + * int n; + * + * y = kn( n, x ); + * + * + * + * DESCRIPTION: + * + * Returns modified Bessel function of the third kind + * of order n of the argument. + * + * The range is partitioned into the two intervals [0,9.55] and + * (9.55, infinity). An ascending power series is used in the + * low range, and an asymptotic expansion in the high range. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 90000 1.8e-8 3.0e-10 + * + * Error is high only near the crossover point x = 9.55 + * between the two expansions used. + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier + */ + +/* + * Algorithm for Kn. + * n-1 + * -n - (n-k-1)! 2 k + * K (x) = 0.5 (x/2) > -------- (-x /4) + * n - k! + * k=0 + * + * inf. 2 k + * n n - (x /4) + * + (-1) 0.5(x/2) > {p(k+1) + p(n+k+1) - 2log(x/2)} --------- + * - k! (n+k)! + * k=0 + * + * where p(m) is the psi function: p(1) = -EUL and + * + * m-1 + * - + * p(m) = -EUL + > 1/k + * - + * k=1 + * + * For large x, + * 2 2 2 + * u-1 (u-1 )(u-3 ) + * K (z) = sqrt(pi/2z) exp(-z) { 1 + ------- + ------------ + ...} + * v 1 2 + * 1! (8z) 2! (8z) + * asymptotically, where + * + * 2 + * u = 4 v . + * + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr int kn_MAXFAC = 31; + + } + + XSF_HOST_DEVICE inline double kn(int nn, double x) { + double k, kf, nk1f, nkf, zn, t, s, z0, z; + double ans, fn, pn, pk, zmn, tlg, tox; + int i, n; + + if (nn < 0) + n = -nn; + else + n = nn; + + if (n > detail::kn_MAXFAC) { + overf: + set_error("kn", SF_ERROR_OVERFLOW, NULL); + return (std::numeric_limits::infinity()); + } + + if (x <= 0.0) { + if (x < 0.0) { + set_error("kn", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } else { + set_error("kn", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } + } + + if (x > 9.55) + goto asymp; + + ans = 0.0; + z0 = 0.25 * x * x; + fn = 1.0; + pn = 0.0; + zmn = 1.0; + tox = 2.0 / x; + + if (n > 0) { + /* compute factorial of n and psi(n) */ + pn = -detail::SCIPY_EULER; + k = 1.0; + for (i = 1; i < n; i++) { + pn += 1.0 / k; + k += 1.0; + fn *= k; + } + + zmn = tox; + + if (n == 1) { + ans = 1.0 / x; + } else { + nk1f = fn / n; + kf = 1.0; + s = nk1f; + z = -z0; + zn = 1.0; + for (i = 1; i < n; i++) { + nk1f = nk1f / (n - i); + kf = kf * i; + zn *= z; + t = nk1f * zn / kf; + s += t; + if ((std::numeric_limits::max() - std::abs(t)) < std::abs(s)) { + goto overf; + } + if ((tox > 1.0) && ((std::numeric_limits::max() / tox) < zmn)) { + goto overf; + } + zmn *= tox; + } + s *= 0.5; + t = std::abs(s); + if ((zmn > 1.0) && ((std::numeric_limits::max() / zmn) < t)) { + goto overf; + } + if ((t > 1.0) && ((std::numeric_limits::max() / t) < zmn)) { + goto overf; + } + ans = s * zmn; + } + } + + tlg = 2.0 * log(0.5 * x); + pk = -detail::SCIPY_EULER; + if (n == 0) { + pn = pk; + t = 1.0; + } else { + pn = pn + 1.0 / n; + t = 1.0 / fn; + } + s = (pk + pn - tlg) * t; + k = 1.0; + do { + t *= z0 / (k * (k + n)); + pk += 1.0 / k; + pn += 1.0 / (k + n); + s += (pk + pn - tlg) * t; + k += 1.0; + } while (fabs(t / s) > detail::MACHEP); + + s = 0.5 * s / zmn; + if (n & 1) { + s = -s; + } + ans += s; + + return (ans); + + /* Asymptotic expansion for Kn(x) */ + /* Converges to 1.4e-17 for x > 18.4 */ + + asymp: + + if (x > detail::MAXLOG) { + set_error("kn", SF_ERROR_UNDERFLOW, NULL); + return (0.0); + } + k = n; + pn = 4.0 * k * k; + pk = 1.0; + z0 = 8.0 * x; + fn = 1.0; + t = 1.0; + s = t; + nkf = std::numeric_limits::infinity(); + i = 0; + do { + z = pn - pk * pk; + t = t * z / (fn * z0); + nk1f = std::abs(t); + if ((i >= n) && (nk1f > nkf)) { + goto adone; + } + nkf = nk1f; + s += t; + fn += 1.0; + pk += 2.0; + i += 1; + } while (std::abs(t / s) > detail::MACHEP); + + adone: + ans = std::exp(-x) * std::sqrt(M_PI / (2.0 * x)) * s; + return (ans); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h new file mode 100644 index 0000000000000000000000000000000000000000..a8cbbe1d693f99e96d74cd40a1a15e32b8035871 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h @@ -0,0 +1,112 @@ +/* (C) Copyright John Maddock 2006. + * Use, modification and distribution are subject to the + * Boost Software License, Version 1.0. (See accompanying file + * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) + */ + +/* Both lanczos.h and lanczos.c were formed from Boost's lanczos.hpp + * + * Scipy changes: + * - 06-22-2016: Removed all code not related to double precision and + * ported to c for use in Cephes. Note that the order of the + * coefficients is reversed to match the behavior of polevl. + */ + +/* + * Optimal values for G for each N are taken from + * https://web.viu.ca/pughg/phdThesis/phdThesis.pdf, + * as are the theoretical error bounds. + * + * Constants calculated using the method described by Godfrey + * https://my.fit.edu/~gabdo/gamma.txt and elaborated by Toth at + * https://www.rskey.org/gamma.htm using NTL::RR at 1000 bit precision. + */ + +/* + * Lanczos Coefficients for N=13 G=6.024680040776729583740234375 + * Max experimental error (with arbitrary precision arithmetic) 1.196214e-17 + * Generated with compiler: Microsoft Visual C++ version 8.0 on Win32 at Mar 23 2006 + * + * Use for double precision. + */ + +#pragma once + +#include "../config.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double lanczos_num[] = { + 2.506628274631000270164908177133837338626, 210.8242777515793458725097339207133627117, + 8071.672002365816210638002902272250613822, 186056.2653952234950402949897160456992822, + 2876370.628935372441225409051620849613599, 31426415.58540019438061423162831820536287, + 248874557.8620541565114603864132294232163, 1439720407.311721673663223072794912393972, + 6039542586.35202800506429164430729792107, 17921034426.03720969991975575445893111267, + 35711959237.35566804944018545154716670596, 42919803642.64909876895789904700198885093, + 23531376880.41075968857200767445163675473}; + + constexpr double lanczos_denom[] = {1, 66, 1925, 32670, 357423, 2637558, 13339535, + 45995730, 105258076, 150917976, 120543840, 39916800, 0}; + + constexpr double lanczos_sum_expg_scaled_num[] = { + 0.006061842346248906525783753964555936883222, 0.5098416655656676188125178644804694509993, + 19.51992788247617482847860966235652136208, 449.9445569063168119446858607650988409623, + 6955.999602515376140356310115515198987526, 75999.29304014542649875303443598909137092, + 601859.6171681098786670226533699352302507, 3481712.15498064590882071018964774556468, + 14605578.08768506808414169982791359218571, 43338889.32467613834773723740590533316085, + 86363131.28813859145546927288977868422342, 103794043.1163445451906271053616070238554, + 56906521.91347156388090791033559122686859}; + + constexpr double lanczos_sum_expg_scaled_denom[] = { + 1, 66, 1925, 32670, 357423, 2637558, 13339535, 45995730, 105258076, 150917976, 120543840, 39916800, 0}; + + constexpr double lanczos_sum_near_1_d[] = { + 0.3394643171893132535170101292240837927725e-9, -0.2499505151487868335680273909354071938387e-8, + 0.8690926181038057039526127422002498960172e-8, -0.1933117898880828348692541394841204288047e-7, + 0.3075580174791348492737947340039992829546e-7, -0.2752907702903126466004207345038327818713e-7, + -0.1515973019871092388943437623825208095123e-5, 0.004785200610085071473880915854204301886437, + -0.1993758927614728757314233026257810172008, 1.483082862367253753040442933770164111678, + -3.327150580651624233553677113928873034916, 2.208709979316623790862569924861841433016}; + + constexpr double lanczos_sum_near_2_d[] = { + 0.1009141566987569892221439918230042368112e-8, -0.7430396708998719707642735577238449585822e-8, + 0.2583592566524439230844378948704262291927e-7, -0.5746670642147041587497159649318454348117e-7, + 0.9142922068165324132060550591210267992072e-7, -0.8183698410724358930823737982119474130069e-7, + -0.4506604409707170077136555010018549819192e-5, 0.01422519127192419234315002746252160965831, + -0.5926941084905061794445733628891024027949, 4.408830289125943377923077727900630927902, + -9.8907772644920670589288081640128194231, 6.565936202082889535528455955485877361223}; + + XSF_HOST_DEVICE double lanczos_sum(double x) { return ratevl(x, lanczos_num, 12, lanczos_denom, 12); } + + XSF_HOST_DEVICE double lanczos_sum_near_1(double dx) { + double result = 0; + unsigned k; + + for (k = 1; k <= 12; ++k) { + result += (-lanczos_sum_near_1_d[k - 1] * dx) / (k * dx + k * k); + } + return result; + } + + XSF_HOST_DEVICE double lanczos_sum_near_2(double dx) { + double result = 0; + double x = dx + 2; + unsigned k; + + for (k = 1; k <= 12; ++k) { + result += (-lanczos_sum_near_2_d[k - 1] * dx) / (x + k * x + k * k - 1); + } + return result; + } + } // namespace detail + + constexpr double lanczos_g = 6.024680040776729583740234375; + XSF_HOST_DEVICE double lanczos_sum_expg_scaled(double x) { + return ratevl(x, detail::lanczos_sum_expg_scaled_num, 12, detail::lanczos_sum_expg_scaled_denom, 12); + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h new file mode 100644 index 0000000000000000000000000000000000000000..a3611d26ba44a78ab69736f9c69fe5dd4d2bc538 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h @@ -0,0 +1,275 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* ndtr.c + * + * Normal distribution function + * + * + * + * SYNOPSIS: + * + * double x, y, ndtr(); + * + * y = ndtr( x ); + * + * + * + * DESCRIPTION: + * + * Returns the area under the Gaussian probability density + * function, integrated from minus infinity to x: + * + * x + * - + * 1 | | 2 + * ndtr(x) = --------- | exp( - t /2 ) dt + * sqrt(2pi) | | + * - + * -inf. + * + * = ( 1 + erf(z) ) / 2 + * = erfc(z) / 2 + * + * where z = x/sqrt(2). Computation is via the functions + * erf and erfc. + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -13,0 30000 3.4e-14 6.7e-15 + * + * + * ERROR MESSAGES: + * + * message condition value returned + * erfc underflow x > 37.519379347 0.0 + * + */ +/* erf.c + * + * Error function + * + * + * + * SYNOPSIS: + * + * double x, y, erf(); + * + * y = erf( x ); + * + * + * + * DESCRIPTION: + * + * The integral is + * + * x + * - + * 2 | | 2 + * erf(x) = -------- | exp( - t ) dt. + * sqrt(pi) | | + * - + * 0 + * + * For 0 <= |x| < 1, erf(x) = x * P4(x**2)/Q5(x**2); otherwise + * erf(x) = 1 - erfc(x). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,1 30000 3.7e-16 1.0e-16 + * + */ +/* erfc.c + * + * Complementary error function + * + * + * + * SYNOPSIS: + * + * double x, y, erfc(); + * + * y = erfc( x ); + * + * + * + * DESCRIPTION: + * + * + * 1 - erf(x) = + * + * inf. + * - + * 2 | | 2 + * erfc(x) = -------- | exp( - t ) dt + * sqrt(pi) | | + * - + * x + * + * + * For small x, erfc(x) = 1 - erf(x); otherwise rational + * approximations are computed. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,26.6417 30000 5.7e-14 1.5e-14 + */ + +/* + * Cephes Math Library Release 2.2: June, 1992 + * Copyright 1984, 1987, 1988, 1992 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" + +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double ndtr_P[] = {2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0, + 4.86371970985681366614E1, 1.96520832956077098242E2, 5.26445194995477358631E2, + 9.34528527171957607540E2, 1.02755188689515710272E3, 5.57535335369399327526E2}; + + constexpr double ndtr_Q[] = { + /* 1.00000000000000000000E0, */ + 1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, 9.75708501743205489753E2, + 1.82390916687909736289E3, 2.24633760818710981792E3, 1.65666309194161350182E3, 5.57535340817727675546E2}; + + constexpr double ndtr_R[] = {5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0, + 6.16021097993053585195E0, 7.40974269950448939160E0, 2.97886665372100240670E0}; + + constexpr double ndtr_S[] = { + /* 1.00000000000000000000E0, */ + 2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1, + 1.70814450747565897222E1, 9.60896809063285878198E0, 3.36907645100081516050E0}; + + constexpr double ndtr_T[] = {9.60497373987051638749E0, 9.00260197203842689217E1, 2.23200534594684319226E3, + 7.00332514112805075473E3, 5.55923013010394962768E4}; + + constexpr double ndtr_U[] = { + /* 1.00000000000000000000E0, */ + 3.35617141647503099647E1, 5.21357949780152679795E2, 4.59432382970980127987E3, 2.26290000613890934246E4, + 4.92673942608635921086E4}; + + constexpr double ndtri_UTHRESH = 37.519379347; + + } // namespace detail + + XSF_HOST_DEVICE inline double erf(double x); + + XSF_HOST_DEVICE inline double erfc(double a) { + double p, q, x, y, z; + + if (std::isnan(a)) { + set_error("erfc", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + if (a < 0.0) { + x = -a; + } else { + x = a; + } + + if (x < 1.0) { + return 1.0 - erf(a); + } + + z = -a * a; + + if (z < -detail::MAXLOG) { + goto under; + } + + z = std::exp(z); + + if (x < 8.0) { + p = polevl(x, detail::ndtr_P, 8); + q = p1evl(x, detail::ndtr_Q, 8); + } else { + p = polevl(x, detail::ndtr_R, 5); + q = p1evl(x, detail::ndtr_S, 6); + } + y = (z * p) / q; + + if (a < 0) { + y = 2.0 - y; + } + + if (y != 0.0) { + return y; + } + + under: + set_error("erfc", SF_ERROR_UNDERFLOW, NULL); + if (a < 0) { + return 2.0; + } else { + return 0.0; + } + } + + XSF_HOST_DEVICE inline double erf(double x) { + double y, z; + + if (std::isnan(x)) { + set_error("erf", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + if (x < 0.0) { + return -erf(-x); + } + + if (std::abs(x) > 1.0) { + return (1.0 - erfc(x)); + } + z = x * x; + + y = x * polevl(z, detail::ndtr_T, 4) / p1evl(z, detail::ndtr_U, 5); + return y; + } + + XSF_HOST_DEVICE inline double ndtr(double a) { + double x, y, z; + + if (std::isnan(a)) { + set_error("ndtr", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + + x = a * M_SQRT1_2; + z = std::abs(x); + + if (z < 1.0) { + y = 0.5 + 0.5 * erf(x); + } else { + y = 0.5 * erfc(z); + if (x > 0) { + y = 1.0 - y; + } + } + + return y; + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h new file mode 100644 index 0000000000000000000000000000000000000000..add3a995f38870cad5155b5fda1730e4fcbf1ee3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h @@ -0,0 +1,85 @@ +/* + * Pochhammer symbol (a)_m = gamma(a + m) / gamma(a) + */ + +#pragma once + +#include "../config.h" +#include "gamma.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + XSF_HOST_DEVICE inline double is_nonpos_int(double x) { + return x <= 0 && x == std::ceil(x) && std::abs(x) < 1e13; + } + } // namespace detail + + XSF_HOST_DEVICE inline double poch(double a, double m) { + double r = 1.0; + + /* + * 1. Reduce magnitude of `m` to |m| < 1 by using recurrence relations. + * + * This may end up in over/underflow, but then the function itself either + * diverges or goes to zero. In case the remainder goes to the opposite + * direction, we end up returning 0*INF = NAN, which is OK. + */ + + /* Recurse down */ + while (m >= 1.0) { + if (a + m == 1) { + break; + } + m -= 1.0; + r *= (a + m); + if (!std::isfinite(r) || r == 0) { + break; + } + } + + /* Recurse up */ + while (m <= -1.0) { + if (a + m == 0) { + break; + } + r /= (a + m); + m += 1.0; + if (!std::isfinite(r) || r == 0) { + break; + } + } + + /* + * 2. Evaluate function with reduced `m` + * + * Now either `m` is not big, or the `r` product has over/underflown. + * If so, the function itself does similarly. + */ + + if (m == 0) { + /* Easy case */ + return r; + } else if (a > 1e4 && std::abs(m) <= 1) { + /* Avoid loss of precision */ + return r * std::pow(a, m) * + (1 + m * (m - 1) / (2 * a) + m * (m - 1) * (m - 2) * (3 * m - 1) / (24 * a * a) + + m * m * (m - 1) * (m - 1) * (m - 2) * (m - 3) / (48 * a * a * a)); + } + + /* Check for infinity */ + if (detail::is_nonpos_int(a + m) && !detail::is_nonpos_int(a) && a + m != m) { + return std::numeric_limits::infinity(); + } + + /* Check for zero */ + if (!detail::is_nonpos_int(a + m) && detail::is_nonpos_int(a)) { + return 0; + } + + return r * std::exp(lgam(a + m) - lgam(a)) * gammasgn(a + m) * gammasgn(a); + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h new file mode 100644 index 0000000000000000000000000000000000000000..912a506cfb6c0d5fe75ead2d14576ddd57698788 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h @@ -0,0 +1,167 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* polevl.c + * p1evl.c + * + * Evaluate polynomial + * + * + * + * SYNOPSIS: + * + * int N; + * double x, y, coef[N+1], polevl[]; + * + * y = polevl( x, coef, N ); + * + * + * + * DESCRIPTION: + * + * Evaluates polynomial of degree N: + * + * 2 N + * y = C + C x + C x +...+ C x + * 0 1 2 N + * + * Coefficients are stored in reverse order: + * + * coef[0] = C , ..., coef[N] = C . + * N 0 + * + * The function p1evl() assumes that c_N = 1.0 so that coefficent + * is omitted from the array. Its calling arguments are + * otherwise the same as polevl(). + * + * + * SPEED: + * + * In the interest of speed, there are no checks for out + * of bounds arithmetic. This routine is used by most of + * the functions in the library. Depending on available + * equipment features, the user may wish to rewrite the + * program in microcode or assembly language. + * + */ + +/* + * Cephes Math Library Release 2.1: December, 1988 + * Copyright 1984, 1987, 1988 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ + +/* Sources: + * [1] Holin et. al., "Polynomial and Rational Function Evaluation", + * https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/roots/rational.html + */ + +/* Scipy changes: + * - 06-23-2016: add code for evaluating rational functions + */ + +#pragma once + +#include "../config.h" + +namespace xsf { +namespace cephes { + XSF_HOST_DEVICE inline double polevl(double x, const double coef[], int N) { + double ans; + int i; + const double *p; + + p = coef; + ans = *p++; + i = N; + + do { + ans = ans * x + *p++; + } while (--i); + + return (ans); + } + + /* p1evl() */ + /* N + * Evaluate polynomial when coefficient of x is 1.0. + * That is, C_{N} is assumed to be 1, and that coefficient + * is not included in the input array coef. + * coef must have length N and contain the polynomial coefficients + * stored as + * coef[0] = C_{N-1} + * coef[1] = C_{N-2} + * ... + * coef[N-2] = C_1 + * coef[N-1] = C_0 + * Otherwise same as polevl. + */ + + XSF_HOST_DEVICE inline double p1evl(double x, const double coef[], int N) { + double ans; + const double *p; + int i; + + p = coef; + ans = x + *p++; + i = N - 1; + + do + ans = ans * x + *p++; + while (--i); + + return (ans); + } + + /* Evaluate a rational function. See [1]. */ + + /* The function ratevl is only used once in cephes/lanczos.h. */ + XSF_HOST_DEVICE inline double ratevl(double x, const double num[], int M, const double denom[], int N) { + int i, dir; + double y, num_ans, denom_ans; + double absx = std::abs(x); + const double *p; + + if (absx > 1) { + /* Evaluate as a polynomial in 1/x. */ + dir = -1; + p = num + M; + y = 1 / x; + } else { + dir = 1; + p = num; + y = x; + } + + /* Evaluate the numerator */ + num_ans = *p; + p += dir; + for (i = 1; i <= M; i++) { + num_ans = num_ans * y + *p; + p += dir; + } + + /* Evaluate the denominator */ + if (absx > 1) { + p = denom + N; + } else { + p = denom; + } + + denom_ans = *p; + p += dir; + for (i = 1; i <= N; i++) { + denom_ans = denom_ans * y + *p; + p += dir; + } + + if (absx > 1) { + i = M - N; + return std::pow(x, i) * num_ans / denom_ans; + } else { + return num_ans / denom_ans; + } + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h new file mode 100644 index 0000000000000000000000000000000000000000..c028e9ea14e0066c3b8c13d2c26c2773e61f767a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h @@ -0,0 +1,194 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* psi.c + * + * Psi (digamma) function + * + * + * SYNOPSIS: + * + * double x, y, psi(); + * + * y = psi( x ); + * + * + * DESCRIPTION: + * + * d - + * psi(x) = -- ln | (x) + * dx + * + * is the logarithmic derivative of the gamma function. + * For integer x, + * n-1 + * - + * psi(n) = -EUL + > 1/k. + * - + * k=1 + * + * This formula is used for 0 < n <= 10. If x is negative, it + * is transformed to a positive argument by the reflection + * formula psi(1-x) = psi(x) + pi cot(pi x). + * For general positive x, the argument is made greater than 10 + * using the recurrence psi(x+1) = psi(x) + 1/x. + * Then the following asymptotic expansion is applied: + * + * inf. B + * - 2k + * psi(x) = log(x) - 1/2x - > ------- + * - 2k + * k=1 2k x + * + * where the B2k are Bernoulli numbers. + * + * ACCURACY: + * Relative error (except absolute when |psi| < 1): + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 1.3e-15 1.4e-16 + * IEEE -30,0 40000 1.5e-15 2.2e-16 + * + * ERROR MESSAGES: + * message condition value returned + * psi singularity x integer <=0 INFINITY + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier + */ + +/* + * Code for the rational approximation on [1, 2] is: + * + * (C) Copyright John Maddock 2006. + * Use, modification and distribution are subject to the + * Boost Software License, Version 1.0. (See accompanying file + * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + namespace detail { + constexpr double psi_A[] = {8.33333333333333333333E-2, -2.10927960927960927961E-2, 7.57575757575757575758E-3, + -4.16666666666666666667E-3, 3.96825396825396825397E-3, -8.33333333333333333333E-3, + 8.33333333333333333333E-2}; + + constexpr float psi_Y = 0.99558162689208984f; + + constexpr double psi_root1 = 1569415565.0 / 1073741824.0; + constexpr double psi_root2 = (381566830.0 / 1073741824.0) / 1073741824.0; + constexpr double psi_root3 = 0.9016312093258695918615325266959189453125e-19; + + constexpr double psi_P[] = {-0.0020713321167745952, -0.045251321448739056, -0.28919126444774784, + -0.65031853770896507, -0.32555031186804491, 0.25479851061131551}; + constexpr double psi_Q[] = {-0.55789841321675513e-6, + 0.0021284987017821144, + 0.054151797245674225, + 0.43593529692665969, + 1.4606242909763515, + 2.0767117023730469, + 1.0}; + + XSF_HOST_DEVICE double digamma_imp_1_2(double x) { + /* + * Rational approximation on [1, 2] taken from Boost. + * + * Now for the approximation, we use the form: + * + * digamma(x) = (x - root) * (Y + R(x-1)) + * + * Where root is the location of the positive root of digamma, + * Y is a constant, and R is optimised for low absolute error + * compared to Y. + * + * Maximum Deviation Found: 1.466e-18 + * At double precision, max error found: 2.452e-17 + */ + double r, g; + + g = x - psi_root1; + g -= psi_root2; + g -= psi_root3; + r = xsf::cephes::polevl(x - 1.0, psi_P, 5) / xsf::cephes::polevl(x - 1.0, psi_Q, 6); + + return g * psi_Y + g * r; + } + + XSF_HOST_DEVICE double psi_asy(double x) { + double y, z; + + if (x < 1.0e17) { + z = 1.0 / (x * x); + y = z * xsf::cephes::polevl(z, psi_A, 6); + } else { + y = 0.0; + } + + return std::log(x) - (0.5 / x) - y; + } + } // namespace detail + + XSF_HOST_DEVICE double psi(double x) { + double y = 0.0; + double q, r; + int i, n; + + if (std::isnan(x)) { + return x; + } else if (x == std::numeric_limits::infinity()) { + return x; + } else if (x == -std::numeric_limits::infinity()) { + return std::numeric_limits::quiet_NaN(); + } else if (x == 0) { + set_error("psi", SF_ERROR_SINGULAR, NULL); + return std::copysign(std::numeric_limits::infinity(), -x); + } else if (x < 0.0) { + /* argument reduction before evaluating tan(pi * x) */ + r = std::modf(x, &q); + if (r == 0.0) { + set_error("psi", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::quiet_NaN(); + } + y = -M_PI / std::tan(M_PI * r); + x = 1.0 - x; + } + + /* check for positive integer up to 10 */ + if ((x <= 10.0) && (x == std::floor(x))) { + n = static_cast(x); + for (i = 1; i < n; i++) { + y += 1.0 / i; + } + y -= detail::SCIPY_EULER; + return y; + } + + /* use the recurrence relation to move x into [1, 2] */ + if (x < 1.0) { + y -= 1.0 / x; + x += 1.0; + } else if (x < 10.0) { + while (x > 2.0) { + x -= 1.0; + y += 1.0 / x; + } + } + if ((1.0 <= x) && (x <= 2.0)) { + y += detail::digamma_imp_1_2(x); + return y; + } + + /* x is large, use the asymptotic series */ + y += detail::psi_asy(x); + return y; + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h new file mode 100644 index 0000000000000000000000000000000000000000..97f29b33ab50abb01f4ee4b71d0f2fbc6ffd1858 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h @@ -0,0 +1,111 @@ +/* rgamma.c + * + * Reciprocal Gamma function + * + * + * + * SYNOPSIS: + * + * double x, y, rgamma(); + * + * y = rgamma( x ); + * + * + * + * DESCRIPTION: + * + * Returns one divided by the Gamma function of the argument. + * + * The function is approximated by a Chebyshev expansion in + * the interval [0,1]. Range reduction is by recurrence + * for arguments between -34.034 and +34.84425627277176174. + * 0 is returned for positive arguments outside this + * range. For arguments less than -34.034 the cosecant + * reflection formula is applied; lograrithms are employed + * to avoid unnecessary overflow. + * + * The reciprocal Gamma function has no singularities, + * but overflow and underflow may occur for large arguments. + * These conditions return either INFINITY or 0 with + * appropriate sign. + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -30,+30 30000 1.1e-15 2.0e-16 + * For arguments less than -34.034 the peak error is on the + * order of 5e-15 (DEC), excepting overflow or underflow. + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1985, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "chbevl.h" +#include "const.h" +#include "gamma.h" +#include "trig.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* Chebyshev coefficients for reciprocal Gamma function + * in interval 0 to 1. Function is 1/(x Gamma(x)) - 1 + */ + + constexpr double rgamma_R[] = { + 3.13173458231230000000E-17, -6.70718606477908000000E-16, 2.20039078172259550000E-15, + 2.47691630348254132600E-13, -6.60074100411295197440E-12, 5.13850186324226978840E-11, + 1.08965386454418662084E-9, -3.33964630686836942556E-8, 2.68975996440595483619E-7, + 2.96001177518801696639E-6, -8.04814124978471142852E-5, 4.16609138709688864714E-4, + 5.06579864028608725080E-3, -6.41925436109158228810E-2, -4.98558728684003594785E-3, + 1.27546015610523951063E-1}; + + } // namespace detail + + XSF_HOST_DEVICE double rgamma(double x) { + double w, y, z; + + if (x == 0) { + // This case is separate from below to get correct sign for zero. + return x; + } + + if (x < 0 && x == std::floor(x)) { + // Gamma poles. + return 0.0; + } + + if (std::abs(x) > 4.0) { + return 1.0 / Gamma(x); + } + + z = 1.0; + w = x; + + while (w > 1.0) { /* Downward recurrence */ + w -= 1.0; + z *= w; + } + while (w < 0.0) { /* Upward recurrence */ + z /= w; + w += 1.0; + } + if (w == 0.0) /* Nonpositive integer */ + return (0.0); + if (w == 1.0) /* Other integer */ + return (1.0 / z); + + y = w * (1.0 + chbevl(4.0 * w - 2.0, detail::rgamma_R, 16)) / z; + return (y); + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h new file mode 100644 index 0000000000000000000000000000000000000000..fe0c631e34582d32132afdf41e2e6904fda90c82 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h @@ -0,0 +1,811 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* iv.c + * + * Modified Bessel function of noninteger order + * + * + * + * SYNOPSIS: + * + * double v, x, y, iv(); + * + * y = iv( v, x ); + * + * + * + * DESCRIPTION: + * + * Returns modified Bessel function of order v of the + * argument. If x is negative, v must be integer valued. + * + */ +/* iv.c */ +/* Modified Bessel function of noninteger order */ +/* If x < 0, then v must be an integer. */ + +/* + * Parts of the code are copyright: + * + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier + * + * And other parts: + * + * Copyright (c) 2006 Xiaogang Zhang + * Use, modification and distribution are subject to the + * Boost Software License, Version 1.0. + * + * Boost Software License - Version 1.0 - August 17th, 2003 + * + * Permission is hereby granted, free of charge, to any person or + * organization obtaining a copy of the software and accompanying + * documentation covered by this license (the "Software") to use, reproduce, + * display, distribute, execute, and transmit the Software, and to prepare + * derivative works of the Software, and to permit third-parties to whom the + * Software is furnished to do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, + * including the above license grant, this restriction and the following + * disclaimer, must be included in all copies of the Software, in whole or + * in part, and all derivative works of the Software, unless such copies or + * derivative works are solely in the form of machine-executable object code + * generated by a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE + * DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, + * WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * And the rest are: + * + * Copyright (C) 2009 Pauli Virtanen + * Distributed under the same license as Scipy. + * + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "gamma.h" +#include "trig.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* + * Compute Iv from (AMS5 9.7.1), asymptotic expansion for large |z| + * Iv ~ exp(x)/sqrt(2 pi x) ( 1 + (4*v*v-1)/8x + (4*v*v-1)(4*v*v-9)/8x/2! + ...) + */ + XSF_HOST_DEVICE inline double iv_asymptotic(double v, double x) { + double mu; + double sum, term, prefactor, factor; + int k; + + prefactor = std::exp(x) / std::sqrt(2 * M_PI * x); + + if (prefactor == std::numeric_limits::infinity()) { + return prefactor; + } + + mu = 4 * v * v; + sum = 1.0; + term = 1.0; + k = 1; + + do { + factor = (mu - (2 * k - 1) * (2 * k - 1)) / (8 * x) / k; + if (k > 100) { + /* didn't converge */ + set_error("iv(iv_asymptotic)", SF_ERROR_NO_RESULT, NULL); + break; + } + term *= -factor; + sum += term; + ++k; + } while (std::abs(term) > MACHEP * std::abs(sum)); + return sum * prefactor; + } + + /* + * Uniform asymptotic expansion factors, (AMS5 9.3.9; AMS5 9.3.10) + * + * Computed with: + * -------------------- + import numpy as np + t = np.poly1d([1,0]) + def up1(p): + return .5*t*t*(1-t*t)*p.deriv() + 1/8. * ((1-5*t*t)*p).integ() + us = [np.poly1d([1])] + for k in range(10): + us.append(up1(us[-1])) + n = us[-1].order + for p in us: + print "{" + ", ".join(["0"]*(n-p.order) + map(repr, p)) + "}," + print "N_UFACTORS", len(us) + print "N_UFACTOR_TERMS", us[-1].order + 1 + * -------------------- + */ + constexpr int iv_N_UFACTORS = 11; + constexpr int iv_N_UFACTOR_TERMS = 31; + + constexpr double iv_asymptotic_ufactors[iv_N_UFACTORS][iv_N_UFACTOR_TERMS] = { + {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, 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.20833333333333334, + 0.0, 0.125, 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.3342013888888889, + 0.0, + -0.40104166666666669, + 0.0, + 0.0703125, + 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, -1.0258125964506173, + 0.0, 1.8464626736111112, + 0.0, -0.89121093750000002, + 0.0, 0.0732421875, + 0.0, 0.0, + 0.0}, + {0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4.6695844234262474, + 0.0, + -11.207002616222995, + 0.0, + 8.78912353515625, + 0.0, + -2.3640869140624998, + 0.0, + 0.112152099609375, + 0.0, + 0.0, + 0.0, + 0.0}, + {0, 0, + 0, 0, + 0, 0, + 0, 0, + 0, 0, + 0, 0, + 0, 0, + 0, -28.212072558200244, + 0.0, 84.636217674600744, + 0.0, -91.818241543240035, + 0.0, 42.534998745388457, + 0.0, -7.3687943594796312, + 0.0, 0.22710800170898438, + 0.0, 0.0, + 0.0, 0.0, + 0.0}, + {0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 212.5701300392171, + 0.0, + -765.25246814118157, + 0.0, + 1059.9904525279999, + 0.0, + -699.57962737613275, + 0.0, + 218.19051174421159, + 0.0, + -26.491430486951554, + 0.0, + 0.57250142097473145, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0}, + {0, 0, + 0, 0, + 0, 0, + 0, 0, + 0, -1919.4576623184068, + 0.0, 8061.7221817373083, + 0.0, -13586.550006434136, + 0.0, 11655.393336864536, + 0.0, -5305.6469786134048, + 0.0, 1200.9029132163525, + 0.0, -108.09091978839464, + 0.0, 1.7277275025844574, + 0.0, 0.0, + 0.0, 0.0, + 0.0, 0.0, + 0.0}, + {0, + 0, + 0, + 0, + 0, + 0, + 20204.291330966149, + 0.0, + -96980.598388637503, + 0.0, + 192547.0012325315, + 0.0, + -203400.17728041555, + 0.0, + 122200.46498301747, + 0.0, + -41192.654968897557, + 0.0, + 7109.5143024893641, + 0.0, + -493.915304773088, + 0.0, + 6.074042001273483, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0}, + {0, 0, + 0, -242919.18790055133, + 0.0, 1311763.6146629769, + 0.0, -2998015.9185381061, + 0.0, 3763271.2976564039, + 0.0, -2813563.2265865342, + 0.0, 1268365.2733216248, + 0.0, -331645.17248456361, + 0.0, 45218.768981362737, + 0.0, -2499.8304818112092, + 0.0, 24.380529699556064, + 0.0, 0.0, + 0.0, 0.0, + 0.0, 0.0, + 0.0, 0.0, + 0.0}, + {3284469.8530720375, + 0.0, + -19706819.11843222, + 0.0, + 50952602.492664628, + 0.0, + -74105148.211532637, + 0.0, + 66344512.274729028, + 0.0, + -37567176.660763353, + 0.0, + 13288767.166421819, + 0.0, + -2785618.1280864552, + 0.0, + 308186.40461266245, + 0.0, + -13886.089753717039, + 0.0, + 110.01714026924674, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0}}; + + /* + * Compute Iv, Kv from (AMS5 9.7.7 + 9.7.8), asymptotic expansion for large v + */ + XSF_HOST_DEVICE inline void ikv_asymptotic_uniform(double v, double x, double *i_value, double *k_value) { + double i_prefactor, k_prefactor; + double t, t2, eta, z; + double i_sum, k_sum, term, divisor; + int k, n; + int sign = 1; + + if (v < 0) { + /* Negative v; compute I_{-v} and K_{-v} and use (AMS 9.6.2) */ + sign = -1; + v = -v; + } + + z = x / v; + t = 1 / std::sqrt(1 + z * z); + t2 = t * t; + eta = std::sqrt(1 + z * z) + std::log(z / (1 + 1 / t)); + + i_prefactor = std::sqrt(t / (2 * M_PI * v)) * std::exp(v * eta); + i_sum = 1.0; + + k_prefactor = std::sqrt(M_PI * t / (2 * v)) * std::exp(-v * eta); + k_sum = 1.0; + + divisor = v; + for (n = 1; n < iv_N_UFACTORS; ++n) { + /* + * Evaluate u_k(t) with Horner's scheme; + * (using the knowledge about which coefficients are zero) + */ + term = 0; + for (k = iv_N_UFACTOR_TERMS - 1 - 3 * n; k < iv_N_UFACTOR_TERMS - n; k += 2) { + term *= t2; + term += iv_asymptotic_ufactors[n][k]; + } + for (k = 1; k < n; k += 2) { + term *= t2; + } + if (n % 2 == 1) { + term *= t; + } + + /* Sum terms */ + term /= divisor; + i_sum += term; + k_sum += (n % 2 == 0) ? term : -term; + + /* Check convergence */ + if (std::abs(term) < MACHEP) { + break; + } + + divisor *= v; + } + + if (std::abs(term) > 1e-3 * std::abs(i_sum)) { + /* Didn't converge */ + set_error("ikv_asymptotic_uniform", SF_ERROR_NO_RESULT, NULL); + } + if (std::abs(term) > MACHEP * std::abs(i_sum)) { + /* Some precision lost */ + set_error("ikv_asymptotic_uniform", SF_ERROR_LOSS, NULL); + } + + if (k_value != NULL) { + /* symmetric in v */ + *k_value = k_prefactor * k_sum; + } + + if (i_value != NULL) { + if (sign == 1) { + *i_value = i_prefactor * i_sum; + } else { + /* (AMS 9.6.2) */ + *i_value = (i_prefactor * i_sum + (2 / M_PI) * xsf::cephes::sinpi(v) * k_prefactor * k_sum); + } + } + } + + /* + * The following code originates from the Boost C++ library, + * from file `boost/math/special_functions/detail/bessel_ik.hpp`, + * converted from C++ to C. + */ + + /* + * Modified Bessel functions of the first and second kind of fractional order + * + * Calculate K(v, x) and K(v+1, x) by method analogous to + * Temme, Journal of Computational Physics, vol 21, 343 (1976) + */ + XSF_HOST_DEVICE inline int temme_ik_series(double v, double x, double *K, double *K1) { + double f, h, p, q, coef, sum, sum1, tolerance; + double a, b, c, d, sigma, gamma1, gamma2; + std::uint64_t k; + double gp; + double gm; + + /* + * |x| <= 2, Temme series converge rapidly + * |x| > 2, the larger the |x|, the slower the convergence + */ + XSF_ASSERT(std::abs(x) <= 2); + XSF_ASSERT(std::abs(v) <= 0.5f); + + gp = xsf::cephes::Gamma(v + 1) - 1; + gm = xsf::cephes::Gamma(-v + 1) - 1; + + a = std::log(x / 2); + b = std::exp(v * a); + sigma = -a * v; + c = std::abs(v) < MACHEP ? 1 : xsf::cephes::sinpi(v) / (v * M_PI); + d = std::abs(sigma) < MACHEP ? 1 : std::sinh(sigma) / sigma; + gamma1 = std::abs(v) < MACHEP ? -SCIPY_EULER : (0.5 / v) * (gp - gm) * c; + gamma2 = (2 + gp + gm) * c / 2; + + /* initial values */ + p = (gp + 1) / (2 * b); + q = (1 + gm) * b / 2; + f = (std::cosh(sigma) * gamma1 + d * (-a) * gamma2) / c; + h = p; + coef = 1; + sum = coef * f; + sum1 = coef * h; + + /* series summation */ + tolerance = MACHEP; + for (k = 1; k < MAXITER; k++) { + f = (k * f + p + q) / (k * k - v * v); + p /= k - v; + q /= k + v; + h = p - k * f; + coef *= x * x / (4 * k); + sum += coef * f; + sum1 += coef * h; + if (std::abs(coef * f) < std::abs(sum) * tolerance) { + break; + } + } + if (k == MAXITER) { + set_error("ikv_temme(temme_ik_series)", SF_ERROR_NO_RESULT, NULL); + } + + *K = sum; + *K1 = 2 * sum1 / x; + + return 0; + } + + /* Evaluate continued fraction fv = I_(v+1) / I_v, derived from + * Abramowitz and Stegun, Handbook of Mathematical Functions, 1972, 9.1.73 */ + XSF_HOST_DEVICE inline int CF1_ik(double v, double x, double *fv) { + double C, D, f, a, b, delta, tiny, tolerance; + std::uint64_t k; + + /* + * |x| <= |v|, CF1_ik converges rapidly + * |x| > |v|, CF1_ik needs O(|x|) iterations to converge + */ + + /* + * modified Lentz's method, see + * Lentz, Applied Optics, vol 15, 668 (1976) + */ + tolerance = 2 * MACHEP; + tiny = 1 / std::sqrt(std::numeric_limits::max()); + C = f = tiny; /* b0 = 0, replace with tiny */ + D = 0; + for (k = 1; k < MAXITER; k++) { + a = 1; + b = 2 * (v + k) / x; + C = b + a / C; + D = b + a * D; + if (C == 0) { + C = tiny; + } + if (D == 0) { + D = tiny; + } + D = 1 / D; + delta = C * D; + f *= delta; + if (std::abs(delta - 1) <= tolerance) { + break; + } + } + if (k == MAXITER) { + set_error("ikv_temme(CF1_ik)", SF_ERROR_NO_RESULT, NULL); + } + + *fv = f; + + return 0; + } + + /* + * Calculate K(v, x) and K(v+1, x) by evaluating continued fraction + * z1 / z0 = U(v+1.5, 2v+1, 2x) / U(v+0.5, 2v+1, 2x), see + * Thompson and Barnett, Computer Physics Communications, vol 47, 245 (1987) + */ + XSF_HOST_DEVICE inline int CF2_ik(double v, double x, double *Kv, double *Kv1) { + + double S, C, Q, D, f, a, b, q, delta, tolerance, current, prev; + std::uint64_t k; + + /* + * |x| >= |v|, CF2_ik converges rapidly + * |x| -> 0, CF2_ik fails to converge + */ + + XSF_ASSERT(std::abs(x) > 1); + + /* + * Steed's algorithm, see Thompson and Barnett, + * Journal of Computational Physics, vol 64, 490 (1986) + */ + tolerance = MACHEP; + a = v * v - 0.25; + b = 2 * (x + 1); /* b1 */ + D = 1 / b; /* D1 = 1 / b1 */ + f = delta = D; /* f1 = delta1 = D1, coincidence */ + prev = 0; /* q0 */ + current = 1; /* q1 */ + Q = C = -a; /* Q1 = C1 because q1 = 1 */ + S = 1 + Q * delta; /* S1 */ + for (k = 2; k < MAXITER; k++) { /* starting from 2 */ + /* continued fraction f = z1 / z0 */ + a -= 2 * (k - 1); + b += 2; + D = 1 / (b + a * D); + delta *= b * D - 1; + f += delta; + + /* series summation S = 1 + \sum_{n=1}^{\infty} C_n * z_n / z_0 */ + q = (prev - (b - 2) * current) / a; + prev = current; + current = q; /* forward recurrence for q */ + C *= -a / k; + Q += C * q; + S += Q * delta; + + /* S converges slower than f */ + if (std::abs(Q * delta) < std::abs(S) * tolerance) { + break; + } + } + if (k == MAXITER) { + set_error("ikv_temme(CF2_ik)", SF_ERROR_NO_RESULT, NULL); + } + + *Kv = std::sqrt(M_PI / (2 * x)) * std::exp(-x) / S; + *Kv1 = *Kv * (0.5 + v + x + (v * v - 0.25) * f) / x; + + return 0; + } + + /* Flags for what to compute */ + enum { ikv_temme_need_i = 0x1, ikv_temme_need_k = 0x2 }; + + /* + * Compute I(v, x) and K(v, x) simultaneously by Temme's method, see + * Temme, Journal of Computational Physics, vol 19, 324 (1975) + */ + XSF_HOST_DEVICE inline void ikv_temme(double v, double x, double *Iv_p, double *Kv_p) { + /* Kv1 = K_(v+1), fv = I_(v+1) / I_v */ + /* Ku1 = K_(u+1), fu = I_(u+1) / I_u */ + double u, Iv, Kv, Kv1, Ku, Ku1, fv; + double W, current, prev, next; + int reflect = 0; + unsigned n, k; + int kind; + + kind = 0; + if (Iv_p != NULL) { + kind |= ikv_temme_need_i; + } + if (Kv_p != NULL) { + kind |= ikv_temme_need_k; + } + + if (v < 0) { + reflect = 1; + v = -v; /* v is non-negative from here */ + kind |= ikv_temme_need_k; + } + n = std::round(v); + u = v - n; /* -1/2 <= u < 1/2 */ + + if (x < 0) { + if (Iv_p != NULL) + *Iv_p = std::numeric_limits::quiet_NaN(); + if (Kv_p != NULL) + *Kv_p = std::numeric_limits::quiet_NaN(); + set_error("ikv_temme", SF_ERROR_DOMAIN, NULL); + return; + } + if (x == 0) { + Iv = (v == 0) ? 1 : 0; + if (kind & ikv_temme_need_k) { + set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL); + Kv = std::numeric_limits::infinity(); + } else { + Kv = std::numeric_limits::quiet_NaN(); /* any value will do */ + } + + if (reflect && (kind & ikv_temme_need_i)) { + double z = (u + n % 2); + + Iv = xsf::cephes::sinpi(z) == 0 ? Iv : std::numeric_limits::infinity(); + if (std::isinf(Iv)) { + set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL); + } + } + + if (Iv_p != NULL) { + *Iv_p = Iv; + } + if (Kv_p != NULL) { + *Kv_p = Kv; + } + return; + } + /* x is positive until reflection */ + W = 1 / x; /* Wronskian */ + if (x <= 2) { /* x in (0, 2] */ + temme_ik_series(u, x, &Ku, &Ku1); /* Temme series */ + } else { /* x in (2, \infty) */ + CF2_ik(u, x, &Ku, &Ku1); /* continued fraction CF2_ik */ + } + prev = Ku; + current = Ku1; + for (k = 1; k <= n; k++) { /* forward recurrence for K */ + next = 2 * (u + k) * current / x + prev; + prev = current; + current = next; + } + Kv = prev; + Kv1 = current; + if (kind & ikv_temme_need_i) { + double lim = (4 * v * v + 10) / (8 * x); + + lim *= lim; + lim *= lim; + lim /= 24; + if ((lim < MACHEP * 10) && (x > 100)) { + /* + * x is huge compared to v, CF1 may be very slow + * to converge so use asymptotic expansion for large + * x case instead. Note that the asymptotic expansion + * isn't very accurate - so it's deliberately very hard + * to get here - probably we're going to overflow: + */ + Iv = iv_asymptotic(v, x); + } else { + CF1_ik(v, x, &fv); /* continued fraction CF1_ik */ + Iv = W / (Kv * fv + Kv1); /* Wronskian relation */ + } + } else { + Iv = std::numeric_limits::quiet_NaN(); /* any value will do */ + } + + if (reflect) { + double z = (u + n % 2); + + if (Iv_p != NULL) { + *Iv_p = Iv + (2 / M_PI) * xsf::cephes::sinpi(z) * Kv; /* reflection formula */ + } + if (Kv_p != NULL) { + *Kv_p = Kv; + } + } else { + if (Iv_p != NULL) { + *Iv_p = Iv; + } + if (Kv_p != NULL) { + *Kv_p = Kv; + } + } + return; + } + + } // namespace detail + + XSF_HOST_DEVICE inline double iv(double v, double x) { + int sign; + double t, ax, res; + + if (std::isnan(v) || std::isnan(x)) { + return std::numeric_limits::quiet_NaN(); + } + + /* If v is a negative integer, invoke symmetry */ + t = std::floor(v); + if (v < 0.0) { + if (t == v) { + v = -v; /* symmetry */ + t = -t; + } + } + /* If x is negative, require v to be an integer */ + sign = 1; + if (x < 0.0) { + if (t != v) { + set_error("iv", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + if (v != 2.0 * std::floor(v / 2.0)) { + sign = -1; + } + } + + /* Avoid logarithm singularity */ + if (x == 0.0) { + if (v == 0.0) { + return 1.0; + } + if (v < 0.0) { + set_error("iv", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity(); + } else + return 0.0; + } + + ax = std::abs(x); + if (std::abs(v) > 50) { + /* + * Uniform asymptotic expansion for large orders. + * + * This appears to overflow slightly later than the Boost + * implementation of Temme's method. + */ + detail::ikv_asymptotic_uniform(v, ax, &res, NULL); + } else { + /* Otherwise: Temme's method */ + detail::ikv_temme(v, ax, &res, NULL); + } + res *= sign; + return res; + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h new file mode 100644 index 0000000000000000000000000000000000000000..fcdd2d7986466e33bff8bf15235c2d2814206d61 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h @@ -0,0 +1,248 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* shichi.c + * + * Hyperbolic sine and cosine integrals + * + * + * + * SYNOPSIS: + * + * double x, Chi, Shi, shichi(); + * + * shichi( x, &Chi, &Shi ); + * + * + * DESCRIPTION: + * + * Approximates the integrals + * + * x + * - + * | | cosh t - 1 + * Chi(x) = eul + ln x + | ----------- dt, + * | | t + * - + * 0 + * + * x + * - + * | | sinh t + * Shi(x) = | ------ dt + * | | t + * - + * 0 + * + * where eul = 0.57721566490153286061 is Euler's constant. + * The integrals are evaluated by power series for x < 8 + * and by Chebyshev expansions for x between 8 and 88. + * For large x, both functions approach exp(x)/2x. + * Arguments greater than 88 in magnitude return INFINITY. + * + * + * ACCURACY: + * + * Test interval 0 to 88. + * Relative error: + * arithmetic function # trials peak rms + * IEEE Shi 30000 6.9e-16 1.6e-16 + * Absolute error, except relative when |Chi| > 1: + * IEEE Chi 30000 8.4e-16 1.4e-16 + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" + +#include "chbevl.h" +#include "const.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* x exp(-x) shi(x), inverted interval 8 to 18 */ + constexpr double shichi_S1[] = { + 1.83889230173399459482E-17, -9.55485532279655569575E-17, 2.04326105980879882648E-16, + 1.09896949074905343022E-15, -1.31313534344092599234E-14, 5.93976226264314278932E-14, + -3.47197010497749154755E-14, -1.40059764613117131000E-12, 9.49044626224223543299E-12, + -1.61596181145435454033E-11, -1.77899784436430310321E-10, 1.35455469767246947469E-9, + -1.03257121792819495123E-9, -3.56699611114982536845E-8, 1.44818877384267342057E-7, + 7.82018215184051295296E-7, -5.39919118403805073710E-6, -3.12458202168959833422E-5, + 8.90136741950727517826E-5, 2.02558474743846862168E-3, 2.96064440855633256972E-2, + 1.11847751047257036625E0}; + + /* x exp(-x) shi(x), inverted interval 18 to 88 */ + constexpr double shichi_S2[] = { + -1.05311574154850938805E-17, 2.62446095596355225821E-17, 8.82090135625368160657E-17, + -3.38459811878103047136E-16, -8.30608026366935789136E-16, 3.93397875437050071776E-15, + 1.01765565969729044505E-14, -4.21128170307640802703E-14, -1.60818204519802480035E-13, + 3.34714954175994481761E-13, 2.72600352129153073807E-12, 1.66894954752839083608E-12, + -3.49278141024730899554E-11, -1.58580661666482709598E-10, -1.79289437183355633342E-10, + 1.76281629144264523277E-9, 1.69050228879421288846E-8, 1.25391771228487041649E-7, + 1.16229947068677338732E-6, 1.61038260117376323993E-5, 3.49810375601053973070E-4, + 1.28478065259647610779E-2, 1.03665722588798326712E0}; + + /* x exp(-x) chin(x), inverted interval 8 to 18 */ + constexpr double shichi_C1[] = { + -8.12435385225864036372E-18, 2.17586413290339214377E-17, 5.22624394924072204667E-17, + -9.48812110591690559363E-16, 5.35546311647465209166E-15, -1.21009970113732918701E-14, + -6.00865178553447437951E-14, 7.16339649156028587775E-13, -2.93496072607599856104E-12, + -1.40359438136491256904E-12, 8.76302288609054966081E-11, -4.40092476213282340617E-10, + -1.87992075640569295479E-10, 1.31458150989474594064E-8, -4.75513930924765465590E-8, + -2.21775018801848880741E-7, 1.94635531373272490962E-6, 4.33505889257316408893E-6, + -6.13387001076494349496E-5, -3.13085477492997465138E-4, 4.97164789823116062801E-4, + 2.64347496031374526641E-2, 1.11446150876699213025E0}; + + /* x exp(-x) chin(x), inverted interval 18 to 88 */ + constexpr double shichi_C2[] = { + 8.06913408255155572081E-18, -2.08074168180148170312E-17, -5.98111329658272336816E-17, + 2.68533951085945765591E-16, 4.52313941698904694774E-16, -3.10734917335299464535E-15, + -4.42823207332531972288E-15, 3.49639695410806959872E-14, 6.63406731718911586609E-14, + -3.71902448093119218395E-13, -1.27135418132338309016E-12, 2.74851141935315395333E-12, + 2.33781843985453438400E-11, 2.71436006377612442764E-11, -2.56600180000355990529E-10, + -1.61021375163803438552E-9, -4.72543064876271773512E-9, -3.00095178028681682282E-9, + 7.79387474390914922337E-8, 1.06942765566401507066E-6, 1.59503164802313196374E-5, + 3.49592575153777996871E-4, 1.28475387530065247392E-2, 1.03665693917934275131E0}; + + /* + * Evaluate 3F0(a1, a2, a3; z) + * + * The series is only asymptotic, so this requires z large enough. + */ + XSF_HOST_DEVICE inline double hyp3f0(double a1, double a2, double a3, double z) { + int n, maxiter; + double err, sum, term, m; + + m = std::pow(z, -1.0 / 3); + if (m < 50) { + maxiter = m; + } else { + maxiter = 50; + } + + term = 1.0; + sum = term; + for (n = 0; n < maxiter; ++n) { + term *= (a1 + n) * (a2 + n) * (a3 + n) * z / (n + 1); + sum += term; + if (std::abs(term) < 1e-13 * std::abs(sum) || term == 0) { + break; + } + } + + err = std::abs(term); + + if (err > 1e-13 * std::abs(sum)) { + return std::numeric_limits::quiet_NaN(); + } + + return sum; + } + + } // namespace detail + + /* Sine and cosine integrals */ + XSF_HOST_DEVICE inline int shichi(double x, double *si, double *ci) { + double k, z, c, s, a, b; + short sign; + + if (x < 0.0) { + sign = -1; + x = -x; + } else { + sign = 0; + } + + if (x == 0.0) { + *si = 0.0; + *ci = -std::numeric_limits::infinity(); + return (0); + } + + if (x >= 8.0) { + goto chb; + } + + if (x >= 88.0) { + goto asymp; + } + + z = x * x; + + /* Direct power series expansion */ + a = 1.0; + s = 1.0; + c = 0.0; + k = 2.0; + + do { + a *= z / k; + c += a / k; + k += 1.0; + a /= k; + s += a / k; + k += 1.0; + } while (std::abs(a / s) > detail::MACHEP); + + s *= x; + goto done; + + chb: + /* Chebyshev series expansions */ + if (x < 18.0) { + a = (576.0 / x - 52.0) / 10.0; + k = std::exp(x) / x; + s = k * chbevl(a, detail::shichi_S1, 22); + c = k * chbevl(a, detail::shichi_C1, 23); + goto done; + } + + if (x <= 88.0) { + a = (6336.0 / x - 212.0) / 70.0; + k = std::exp(x) / x; + s = k * chbevl(a, detail::shichi_S2, 23); + c = k * chbevl(a, detail::shichi_C2, 24); + goto done; + } + + asymp: + if (x > 1000) { + *si = std::numeric_limits::infinity(); + *ci = std::numeric_limits::infinity(); + } else { + /* Asymptotic expansions + * http://functions.wolfram.com/GammaBetaErf/CoshIntegral/06/02/ + * http://functions.wolfram.com/GammaBetaErf/SinhIntegral/06/02/0001/ + */ + a = detail::hyp3f0(0.5, 1, 1, 4.0 / (x * x)); + b = detail::hyp3f0(1, 1, 1.5, 4.0 / (x * x)); + *si = std::cosh(x) / x * a + std::sinh(x) / (x * x) * b; + *ci = std::sinh(x) / x * a + std::cosh(x) / (x * x) * b; + } + if (sign) { + *si = -*si; + } + return 0; + + done: + if (sign) { + s = -s; + } + + *si = s; + + *ci = detail::SCIPY_EULER + std::log(x) + c; + return (0); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h new file mode 100644 index 0000000000000000000000000000000000000000..c22612ccc9abfd0594467ad40ad466b4559db2bc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h @@ -0,0 +1,224 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* sici.c + * + * Sine and cosine integrals + * + * + * + * SYNOPSIS: + * + * double x, Ci, Si, sici(); + * + * sici( x, &Si, &Ci ); + * + * + * DESCRIPTION: + * + * Evaluates the integrals + * + * x + * - + * | cos t - 1 + * Ci(x) = eul + ln x + | --------- dt, + * | t + * - + * 0 + * x + * - + * | sin t + * Si(x) = | ----- dt + * | t + * - + * 0 + * + * where eul = 0.57721566490153286061 is Euler's constant. + * The integrals are approximated by rational functions. + * For x > 8 auxiliary functions f(x) and g(x) are employed + * such that + * + * Ci(x) = f(x) sin(x) - g(x) cos(x) + * Si(x) = pi/2 - f(x) cos(x) - g(x) sin(x) + * + * + * ACCURACY: + * Test interval = [0,50]. + * Absolute error, except relative when > 1: + * arithmetic function # trials peak rms + * IEEE Si 30000 4.4e-16 7.3e-17 + * IEEE Ci 30000 6.9e-16 5.1e-17 + */ + +/* + * Cephes Math Library Release 2.1: January, 1989 + * Copyright 1984, 1987, 1989 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" + +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double sici_SN[] = { + -8.39167827910303881427E-11, 4.62591714427012837309E-8, -9.75759303843632795789E-6, + 9.76945438170435310816E-4, -4.13470316229406538752E-2, 1.00000000000000000302E0, + }; + + constexpr double sici_SD[] = { + 2.03269266195951942049E-12, 1.27997891179943299903E-9, 4.41827842801218905784E-7, + 9.96412122043875552487E-5, 1.42085239326149893930E-2, 9.99999999999999996984E-1, + }; + + constexpr double sici_CN[] = { + 2.02524002389102268789E-11, -1.35249504915790756375E-8, 3.59325051419993077021E-6, + -4.74007206873407909465E-4, 2.89159652607555242092E-2, -1.00000000000000000080E0, + }; + + constexpr double sici_CD[] = { + 4.07746040061880559506E-12, 3.06780997581887812692E-9, 1.23210355685883423679E-6, + 3.17442024775032769882E-4, 5.10028056236446052392E-2, 4.00000000000000000080E0, + }; + + constexpr double sici_FN4[] = { + 4.23612862892216586994E0, 5.45937717161812843388E0, 1.62083287701538329132E0, 1.67006611831323023771E-1, + 6.81020132472518137426E-3, 1.08936580650328664411E-4, 5.48900223421373614008E-7, + }; + + constexpr double sici_FD4[] = { + /* 1.00000000000000000000E0, */ + 8.16496634205391016773E0, 7.30828822505564552187E0, 1.86792257950184183883E0, 1.78792052963149907262E-1, + 7.01710668322789753610E-3, 1.10034357153915731354E-4, 5.48900252756255700982E-7, + }; + + constexpr double sici_FN8[] = { + 4.55880873470465315206E-1, 7.13715274100146711374E-1, 1.60300158222319456320E-1, + 1.16064229408124407915E-2, 3.49556442447859055605E-4, 4.86215430826454749482E-6, + 3.20092790091004902806E-8, 9.41779576128512936592E-11, 9.70507110881952024631E-14, + }; + + constexpr double sici_FD8[] = { + /* 1.00000000000000000000E0, */ + 9.17463611873684053703E-1, 1.78685545332074536321E-1, 1.22253594771971293032E-2, + 3.58696481881851580297E-4, 4.92435064317881464393E-6, 3.21956939101046018377E-8, + 9.43720590350276732376E-11, 9.70507110881952025725E-14, + }; + + constexpr double sici_GN4[] = { + 8.71001698973114191777E-2, 6.11379109952219284151E-1, 3.97180296392337498885E-1, 7.48527737628469092119E-2, + 5.38868681462177273157E-3, 1.61999794598934024525E-4, 1.97963874140963632189E-6, 7.82579040744090311069E-9, + }; + + constexpr double sici_GD4[] = { + /* 1.00000000000000000000E0, */ + 1.64402202413355338886E0, 6.66296701268987968381E-1, 9.88771761277688796203E-2, 6.22396345441768420760E-3, + 1.73221081474177119497E-4, 2.02659182086343991969E-6, 7.82579218933534490868E-9, + }; + + constexpr double sici_GN8[] = { + 6.97359953443276214934E-1, 3.30410979305632063225E-1, 3.84878767649974295920E-2, + 1.71718239052347903558E-3, 3.48941165502279436777E-5, 3.47131167084116673800E-7, + 1.70404452782044526189E-9, 3.85945925430276600453E-12, 3.14040098946363334640E-15, + }; + + constexpr double sici_GD8[] = { + /* 1.00000000000000000000E0, */ + 1.68548898811011640017E0, 4.87852258695304967486E-1, 4.67913194259625806320E-2, + 1.90284426674399523638E-3, 3.68475504442561108162E-5, 3.57043223443740838771E-7, + 1.72693748966316146736E-9, 3.87830166023954706752E-12, 3.14040098946363335242E-15, + }; + + } // namespace detail + + XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) { + double z, c, s, f, g; + short sign; + + if (x < 0.0) { + sign = -1; + x = -x; + } else { + sign = 0; + } + + if (x == 0.0) { + *si = 0.0; + *ci = -std::numeric_limits::infinity(); + return (0); + } + + if (x > 1.0e9) { + if (std::isinf(x)) { + if (sign == -1) { + *si = -M_PI_2; + *ci = std::numeric_limits::quiet_NaN(); + } else { + *si = M_PI_2; + *ci = 0; + } + return 0; + } + *si = M_PI_2 - std::cos(x) / x; + *ci = std::sin(x) / x; + } + + if (x > 4.0) { + goto asympt; + } + + z = x * x; + s = x * polevl(z, detail::sici_SN, 5) / polevl(z, detail::sici_SD, 5); + c = z * polevl(z, detail::sici_CN, 5) / polevl(z, detail::sici_CD, 5); + + if (sign) { + s = -s; + } + *si = s; + *ci = detail::SCIPY_EULER + std::log(x) + c; /* real part if x < 0 */ + return (0); + + /* The auxiliary functions are: + * + * + * *si = *si - M_PI_2; + * c = cos(x); + * s = sin(x); + * + * t = *ci * s - *si * c; + * a = *ci * c + *si * s; + * + * *si = t; + * *ci = -a; + */ + + asympt: + + s = std::sin(x); + c = std::cos(x); + z = 1.0 / (x * x); + if (x < 8.0) { + f = polevl(z, detail::sici_FN4, 6) / (x * p1evl(z, detail::sici_FD4, 7)); + g = z * polevl(z, detail::sici_GN4, 7) / p1evl(z, detail::sici_GD4, 7); + } else { + f = polevl(z, detail::sici_FN8, 8) / (x * p1evl(z, detail::sici_FD8, 8)); + g = z * polevl(z, detail::sici_GN8, 8) / p1evl(z, detail::sici_GD8, 9); + } + *si = M_PI_2 - f * c - g * s; + if (sign) { + *si = -(*si); + } + *ci = f * s - g * c; + + return (0); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h new file mode 100644 index 0000000000000000000000000000000000000000..63adb1698f4c6e51d971484c92b3cf2c98dcba6f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h @@ -0,0 +1,221 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* sindg.c + * + * Circular sine of angle in degrees + * + * + * + * SYNOPSIS: + * + * double x, y, sindg(); + * + * y = sindg( x ); + * + * + * + * DESCRIPTION: + * + * Range reduction is into intervals of 45 degrees. + * + * Two polynomial approximating functions are employed. + * Between 0 and pi/4 the sine is approximated by + * x + x**3 P(x**2). + * Between pi/4 and pi/2 the cosine is represented as + * 1 - x**2 P(x**2). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE +-1000 30000 2.3e-16 5.6e-17 + * + * ERROR MESSAGES: + * + * message condition value returned + * sindg total loss x > 1.0e14 (IEEE) 0.0 + * + */ +/* cosdg.c + * + * Circular cosine of angle in degrees + * + * + * + * SYNOPSIS: + * + * double x, y, cosdg(); + * + * y = cosdg( x ); + * + * + * + * DESCRIPTION: + * + * Range reduction is into intervals of 45 degrees. + * + * Two polynomial approximating functions are employed. + * Between 0 and pi/4 the cosine is approximated by + * 1 - x**2 P(x**2). + * Between pi/4 and pi/2 the sine is represented as + * x + x**3 P(x**2). + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE +-1000 30000 2.1e-16 5.7e-17 + * See also sin(). + * + */ + +/* Cephes Math Library Release 2.0: April, 1987 + * Copyright 1985, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double sincof[] = {1.58962301572218447952E-10, -2.50507477628503540135E-8, + 2.75573136213856773549E-6, -1.98412698295895384658E-4, + 8.33333333332211858862E-3, -1.66666666666666307295E-1}; + + constexpr double coscof[] = {1.13678171382044553091E-11, -2.08758833757683644217E-9, 2.75573155429816611547E-7, + -2.48015872936186303776E-5, 1.38888888888806666760E-3, -4.16666666666666348141E-2, + 4.99999999999999999798E-1}; + + constexpr double sindg_lossth = 1.0e14; + + } // namespace detail + + XSF_HOST_DEVICE inline double sindg(double x) { + double y, z, zz; + int j, sign; + + /* make argument positive but save the sign */ + sign = 1; + if (x < 0) { + x = -x; + sign = -1; + } + + if (x > detail::sindg_lossth) { + set_error("sindg", SF_ERROR_NO_RESULT, NULL); + return (0.0); + } + + y = std::floor(x / 45.0); /* integer part of x/M_PI_4 */ + + /* strip high bits of integer part to prevent integer overflow */ + z = std::ldexp(y, -4); + z = std::floor(z); /* integer part of y/8 */ + z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */ + + j = z; /* convert to integer for tests on the phase angle */ + /* map zeros to origin */ + if (j & 1) { + j += 1; + y += 1.0; + } + j = j & 07; /* octant modulo 360 degrees */ + /* reflect in x axis */ + if (j > 3) { + sign = -sign; + j -= 4; + } + + z = x - y * 45.0; /* x mod 45 degrees */ + z *= detail::PI180; /* multiply by pi/180 to convert to radians */ + zz = z * z; + + if ((j == 1) || (j == 2)) { + y = 1.0 - zz * polevl(zz, detail::coscof, 6); + } else { + y = z + z * (zz * polevl(zz, detail::sincof, 5)); + } + + if (sign < 0) + y = -y; + + return (y); + } + + XSF_HOST_DEVICE inline double cosdg(double x) { + double y, z, zz; + int j, sign; + + /* make argument positive */ + sign = 1; + if (x < 0) + x = -x; + + if (x > detail::sindg_lossth) { + set_error("cosdg", SF_ERROR_NO_RESULT, NULL); + return (0.0); + } + + y = std::floor(x / 45.0); + z = std::ldexp(y, -4); + z = std::floor(z); /* integer part of y/8 */ + z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */ + + /* integer and fractional part modulo one octant */ + j = z; + if (j & 1) { /* map zeros to origin */ + j += 1; + y += 1.0; + } + j = j & 07; + if (j > 3) { + j -= 4; + sign = -sign; + } + + if (j > 1) + sign = -sign; + + z = x - y * 45.0; /* x mod 45 degrees */ + z *= detail::PI180; /* multiply by pi/180 to convert to radians */ + + zz = z * z; + + if ((j == 1) || (j == 2)) { + y = z + z * (zz * polevl(zz, detail::sincof, 5)); + } else { + y = 1.0 - zz * polevl(zz, detail::coscof, 6); + } + + if (sign < 0) + y = -y; + + return (y); + } + + /* Degrees, minutes, seconds to radians: */ + + /* 1 arc second, in radians = 4.848136811095359935899141023579479759563533023727e-6 */ + + namespace detail { + constexpr double sindg_P64800 = 4.848136811095359935899141023579479759563533023727e-6; + } + + XSF_HOST_DEVICE inline double radian(double d, double m, double s) { + return (((d * 60.0 + m) * 60.0 + s) * detail::sindg_P64800); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h new file mode 100644 index 0000000000000000000000000000000000000000..071b1a81d8bd5467fabf99fa54881f5862c0218b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h @@ -0,0 +1,139 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* tandg.c + * + * Circular tangent of argument in degrees + * + * + * + * SYNOPSIS: + * + * double x, y, tandg(); + * + * y = tandg( x ); + * + * + * + * DESCRIPTION: + * + * Returns the circular tangent of the argument x in degrees. + * + * Range reduction is modulo pi/4. A rational function + * x + x**3 P(x**2)/Q(x**2) + * is employed in the basic interval [0, pi/4]. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,10 30000 3.2e-16 8.4e-17 + * + * ERROR MESSAGES: + * + * message condition value returned + * tandg total loss x > 1.0e14 (IEEE) 0.0 + * tandg singularity x = 180 k + 90 INFINITY + */ +/* cotdg.c + * + * Circular cotangent of argument in degrees + * + * + * + * SYNOPSIS: + * + * double x, y, cotdg(); + * + * y = cotdg( x ); + * + * + * + * DESCRIPTION: + * + * Returns the circular cotangent of the argument x in degrees. + * + * Range reduction is modulo pi/4. A rational function + * x + x**3 P(x**2)/Q(x**2) + * is employed in the basic interval [0, pi/4]. + * + * + * ERROR MESSAGES: + * + * message condition value returned + * cotdg total loss x > 1.0e14 (IEEE) 0.0 + * cotdg singularity x = 180 k INFINITY + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +namespace xsf { +namespace cephes { + + namespace detail { + constexpr double tandg_lossth = 1.0e14; + + XSF_HOST_DEVICE inline double tancot(double xx, int cotflg) { + double x; + int sign; + + /* make argument positive but save the sign */ + if (xx < 0) { + x = -xx; + sign = -1; + } else { + x = xx; + sign = 1; + } + + if (x > detail::tandg_lossth) { + set_error("tandg", SF_ERROR_NO_RESULT, NULL); + return 0.0; + } + + /* modulo 180 */ + x = x - 180.0 * std::floor(x / 180.0); + if (cotflg) { + if (x <= 90.0) { + x = 90.0 - x; + } else { + x = x - 90.0; + sign *= -1; + } + } else { + if (x > 90.0) { + x = 180.0 - x; + sign *= -1; + } + } + if (x == 0.0) { + return 0.0; + } else if (x == 45.0) { + return sign * 1.0; + } else if (x == 90.0) { + set_error((cotflg ? "cotdg" : "tandg"), SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::infinity(); + } + /* x is now transformed into [0, 90) */ + return sign * std::tan(x * detail::PI180); + } + + } // namespace detail + + XSF_HOST_DEVICE inline double tandg(double x) { return (detail::tancot(x, 0)); } + + XSF_HOST_DEVICE inline double cotdg(double x) { return (detail::tancot(x, 1)); } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h new file mode 100644 index 0000000000000000000000000000000000000000..47dcdbe6ab3c72e91dcd13f7f432572260ca3c62 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h @@ -0,0 +1,58 @@ +/* Translated into C++ by SciPy developers in 2024. + * + * Original author: Josh Wilson, 2020. + */ + +/* + * Implement sin(pi * x) and cos(pi * x) for real x. Since the periods + * of these functions are integral (and thus representable in double + * precision), it's possible to compute them with greater accuracy + * than sin(x) and cos(x). + */ +#pragma once + +#include "../config.h" + +namespace xsf { +namespace cephes { + + /* Compute sin(pi * x). */ + template + XSF_HOST_DEVICE T sinpi(T x) { + T s = 1.0; + + if (x < 0.0) { + x = -x; + s = -1.0; + } + + T r = std::fmod(x, 2.0); + if (r < 0.5) { + return s * std::sin(M_PI * r); + } else if (r > 1.5) { + return s * std::sin(M_PI * (r - 2.0)); + } else { + return -s * std::sin(M_PI * (r - 1.0)); + } + } + + /* Compute cos(pi * x) */ + template + XSF_HOST_DEVICE T cospi(T x) { + if (x < 0.0) { + x = -x; + } + + T r = std::fmod(x, 2.0); + if (r == 0.5) { + // We don't want to return -0.0 + return 0.0; + } + if (r < 1.0) { + return -std::sin(M_PI * (r - 0.5)); + } else { + return std::sin(M_PI * (r - 1.5)); + } + } +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h new file mode 100644 index 0000000000000000000000000000000000000000..eb045edda2122e206fc866b180c1fbd71670a553 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h @@ -0,0 +1,186 @@ +/* Translated into C++ by SciPy developers in 2024. */ + +/* unity.c + * + * Relative error approximations for function arguments near + * unity. + * + * log1p(x) = log(1+x) + * expm1(x) = exp(x) - 1 + * cosm1(x) = cos(x) - 1 + * lgam1p(x) = lgam(1+x) + * + */ + +/* Scipy changes: + * - 06-10-2016: added lgam1p + */ +#pragma once + +#include "../config.h" + +#include "const.h" +#include "gamma.h" +#include "polevl.h" +#include "zeta.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* log1p(x) = log(1 + x) */ + + /* Coefficients for log(1+x) = x - x**2/2 + x**3 P(x)/Q(x) + * 1/sqrt(2) <= x < sqrt(2) + * Theoretical peak relative error = 2.32e-20 + */ + + constexpr double unity_LP[] = { + 4.5270000862445199635215E-5, 4.9854102823193375972212E-1, 6.5787325942061044846969E0, + 2.9911919328553073277375E1, 6.0949667980987787057556E1, 5.7112963590585538103336E1, + 2.0039553499201281259648E1, + }; + + constexpr double unity_LQ[] = { + /* 1.0000000000000000000000E0, */ + 1.5062909083469192043167E1, 8.3047565967967209469434E1, 2.2176239823732856465394E2, + 3.0909872225312059774938E2, 2.1642788614495947685003E2, 6.0118660497603843919306E1, + }; + + } // namespace detail + + XSF_HOST_DEVICE inline double log1p(double x) { + double z; + + z = 1.0 + x; + if ((z < M_SQRT1_2) || (z > M_SQRT2)) + return (std::log(z)); + z = x * x; + z = -0.5 * z + x * (z * polevl(x, detail::unity_LP, 6) / p1evl(x, detail::unity_LQ, 6)); + return (x + z); + } + + /* log(1 + x) - x */ + XSF_HOST_DEVICE inline double log1pmx(double x) { + if (std::abs(x) < 0.5) { + uint64_t n; + double xfac = x; + double term; + double res = 0; + + for (n = 2; n < detail::MAXITER; n++) { + xfac *= -x; + term = xfac / n; + res += term; + if (std::abs(term) < detail::MACHEP * std::abs(res)) { + break; + } + } + return res; + } else { + return log1p(x) - x; + } + } + + /* expm1(x) = exp(x) - 1 */ + + /* e^x = 1 + 2x P(x^2)/( Q(x^2) - P(x^2) ) + * -0.5 <= x <= 0.5 + */ + + namespace detail { + + constexpr double unity_EP[3] = { + 1.2617719307481059087798E-4, + 3.0299440770744196129956E-2, + 9.9999999999999999991025E-1, + }; + + constexpr double unity_EQ[4] = { + 3.0019850513866445504159E-6, + 2.5244834034968410419224E-3, + 2.2726554820815502876593E-1, + 2.0000000000000000000897E0, + }; + + } // namespace detail + + XSF_HOST_DEVICE inline double expm1(double x) { + double r, xx; + + if (!std::isfinite(x)) { + if (std::isnan(x)) { + return x; + } else if (x > 0) { + return x; + } else { + return -1.0; + } + } + if ((x < -0.5) || (x > 0.5)) + return (std::exp(x) - 1.0); + xx = x * x; + r = x * polevl(xx, detail::unity_EP, 2); + r = r / (polevl(xx, detail::unity_EQ, 3) - r); + return (r + r); + } + + /* cosm1(x) = cos(x) - 1 */ + + namespace detail { + constexpr double unity_coscof[7] = { + 4.7377507964246204691685E-14, -1.1470284843425359765671E-11, 2.0876754287081521758361E-9, + -2.7557319214999787979814E-7, 2.4801587301570552304991E-5, -1.3888888888888872993737E-3, + 4.1666666666666666609054E-2, + }; + + } + + XSF_HOST_DEVICE inline double cosm1(double x) { + double xx; + + if ((x < -M_PI_4) || (x > M_PI_4)) + return (std::cos(x) - 1.0); + xx = x * x; + xx = -0.5 * xx + xx * xx * polevl(xx, detail::unity_coscof, 6); + return xx; + } + + namespace detail { + /* Compute lgam(x + 1) around x = 0 using its Taylor series. */ + XSF_HOST_DEVICE inline double lgam1p_taylor(double x) { + int n; + double xfac, coeff, res; + + if (x == 0) { + return 0; + } + res = -SCIPY_EULER * x; + xfac = -x; + for (n = 2; n < 42; n++) { + xfac *= -x; + coeff = xsf::cephes::zeta(n, 1) * xfac / n; + res += coeff; + if (std::abs(coeff) < detail::MACHEP * std::abs(res)) { + break; + } + } + + return res; + } + } // namespace detail + + /* Compute lgam(x + 1). */ + XSF_HOST_DEVICE inline double lgam1p(double x) { + if (std::abs(x) <= 0.5) { + return detail::lgam1p_taylor(x); + } else if (std::abs(x - 1) < 0.5) { + return std::log(x) + detail::lgam1p_taylor(x - 1); + } else { + return lgam(x + 1); + } + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h new file mode 100644 index 0000000000000000000000000000000000000000..6f9d68e0bdced0edf70c17cdacf9a676341a908a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h @@ -0,0 +1,172 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* zeta.c + * + * Riemann zeta function of two arguments + * + * + * + * SYNOPSIS: + * + * double x, q, y, zeta(); + * + * y = zeta( x, q ); + * + * + * + * DESCRIPTION: + * + * + * + * inf. + * - -x + * zeta(x,q) = > (k+q) + * - + * k=0 + * + * where x > 1 and q is not a negative integer or zero. + * The Euler-Maclaurin summation formula is used to obtain + * the expansion + * + * n + * - -x + * zeta(x,q) = > (k+q) + * - + * k=1 + * + * 1-x inf. B x(x+1)...(x+2j) + * (n+q) 1 - 2j + * + --------- - ------- + > -------------------- + * x-1 x - x+2j+1 + * 2(n+q) j=1 (2j)! (n+q) + * + * where the B2j are Bernoulli numbers. Note that (see zetac.c) + * zeta(x,1) = zetac(x) + 1. + * + * + * + * ACCURACY: + * + * + * + * REFERENCE: + * + * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals, + * Series, and Products, p. 1073; Academic Press, 1980. + * + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" + +namespace xsf { +namespace cephes { + + namespace detail { + /* Expansion coefficients + * for Euler-Maclaurin summation formula + * (2k)! / B2k + * where B2k are Bernoulli numbers + */ + constexpr double zeta_A[] = { + 12.0, + -720.0, + 30240.0, + -1209600.0, + 47900160.0, + -1.8924375803183791606e9, /*1.307674368e12/691 */ + 7.47242496e10, + -2.950130727918164224e12, /*1.067062284288e16/3617 */ + 1.1646782814350067249e14, /*5.109094217170944e18/43867 */ + -4.5979787224074726105e15, /*8.028576626982912e20/174611 */ + 1.8152105401943546773e17, /*1.5511210043330985984e23/854513 */ + -7.1661652561756670113e18 /*1.6938241367317436694528e27/236364091 */ + }; + + /* 30 Nov 86 -- error in third coefficient fixed */ + } // namespace detail + + XSF_HOST_DEVICE double inline zeta(double x, double q) { + int i; + double a, b, k, s, t, w; + + if (x == 1.0) + goto retinf; + + if (x < 1.0) { + domerr: + set_error("zeta", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + + if (q <= 0.0) { + if (q == floor(q)) { + set_error("zeta", SF_ERROR_SINGULAR, NULL); + retinf: + return (std::numeric_limits::infinity()); + } + if (x != std::floor(x)) + goto domerr; /* because q^-x not defined */ + } + + /* Asymptotic expansion + * https://dlmf.nist.gov/25.11#E43 + */ + if (q > 1e8) { + return (1 / (x - 1) + 1 / (2 * q)) * std::pow(q, 1 - x); + } + + /* Euler-Maclaurin summation formula */ + + /* Permit negative q but continue sum until n+q > +9 . + * This case should be handled by a reflection formula. + * If q<0 and x is an integer, there is a relation to + * the polyGamma function. + */ + s = std::pow(q, -x); + a = q; + i = 0; + b = 0.0; + while ((i < 9) || (a <= 9.0)) { + i += 1; + a += 1.0; + b = std::pow(a, -x); + s += b; + if (std::abs(b / s) < detail::MACHEP) + goto done; + } + + w = a; + s += b * w / (x - 1.0); + s -= 0.5 * b; + a = 1.0; + k = 0.0; + for (i = 0; i < 12; i++) { + a *= x + k; + b /= w; + t = a * b / detail::zeta_A[i]; + s = s + t; + t = std::abs(t / s); + if (t < detail::MACHEP) + goto done; + k += 1.0; + a *= x + k; + b /= w; + k += 1.0; + } + done: + return (s); + } + +} // namespace cephes +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h new file mode 100644 index 0000000000000000000000000000000000000000..5cb40ed1e1e095a8c99414f891a697c263845784 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h @@ -0,0 +1,304 @@ +#pragma once + +// Define math constants if they are not available +#ifndef M_E +#define M_E 2.71828182845904523536 +#endif + +#ifndef M_LOG2E +#define M_LOG2E 1.44269504088896340736 +#endif + +#ifndef M_LOG10E +#define M_LOG10E 0.434294481903251827651 +#endif + +#ifndef M_LN2 +#define M_LN2 0.693147180559945309417 +#endif + +#ifndef M_LN10 +#define M_LN10 2.30258509299404568402 +#endif + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#ifndef M_PI_2 +#define M_PI_2 1.57079632679489661923 +#endif + +#ifndef M_PI_4 +#define M_PI_4 0.785398163397448309616 +#endif + +#ifndef M_1_PI +#define M_1_PI 0.318309886183790671538 +#endif + +#ifndef M_2_PI +#define M_2_PI 0.636619772367581343076 +#endif + +#ifndef M_2_SQRTPI +#define M_2_SQRTPI 1.12837916709551257390 +#endif + +#ifndef M_SQRT2 +#define M_SQRT2 1.41421356237309504880 +#endif + +#ifndef M_SQRT1_2 +#define M_SQRT1_2 0.707106781186547524401 +#endif + +#ifdef __CUDACC__ +#define XSF_HOST_DEVICE __host__ __device__ + +#include +#include +#include +#include +#include +#include +#include + +// Fallback to global namespace for functions unsupported on NVRTC Jit +#ifdef _LIBCUDACXX_COMPILER_NVRTC +#include +#endif + +namespace std { + +XSF_HOST_DEVICE inline double abs(double num) { return cuda::std::abs(num); } + +XSF_HOST_DEVICE inline double exp(double num) { return cuda::std::exp(num); } + +XSF_HOST_DEVICE inline double log(double num) { return cuda::std::log(num); } + +XSF_HOST_DEVICE inline double sqrt(double num) { return cuda::std::sqrt(num); } + +XSF_HOST_DEVICE inline bool isinf(double num) { return cuda::std::isinf(num); } + +XSF_HOST_DEVICE inline bool isnan(double num) { return cuda::std::isnan(num); } + +XSF_HOST_DEVICE inline bool isfinite(double num) { return cuda::std::isfinite(num); } + +XSF_HOST_DEVICE inline double pow(double x, double y) { return cuda::std::pow(x, y); } + +XSF_HOST_DEVICE inline double sin(double x) { return cuda::std::sin(x); } + +XSF_HOST_DEVICE inline double cos(double x) { return cuda::std::cos(x); } + +XSF_HOST_DEVICE inline double tan(double x) { return cuda::std::tan(x); } + +XSF_HOST_DEVICE inline double atan(double x) { return cuda::std::atan(x); } + +XSF_HOST_DEVICE inline double acos(double x) { return cuda::std::acos(x); } + +XSF_HOST_DEVICE inline double sinh(double x) { return cuda::std::sinh(x); } + +XSF_HOST_DEVICE inline double cosh(double x) { return cuda::std::cosh(x); } + +XSF_HOST_DEVICE inline double asinh(double x) { return cuda::std::asinh(x); } + +XSF_HOST_DEVICE inline bool signbit(double x) { return cuda::std::signbit(x); } + +// Fallback to global namespace for functions unsupported on NVRTC +#ifndef _LIBCUDACXX_COMPILER_NVRTC +XSF_HOST_DEVICE inline double ceil(double x) { return cuda::std::ceil(x); } +XSF_HOST_DEVICE inline double floor(double x) { return cuda::std::floor(x); } +XSF_HOST_DEVICE inline double round(double x) { return cuda::std::round(x); } +XSF_HOST_DEVICE inline double trunc(double x) { return cuda::std::trunc(x); } +XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return cuda::std::fma(x, y, z); } +XSF_HOST_DEVICE inline double copysign(double x, double y) { return cuda::std::copysign(x, y); } +XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return cuda::std::modf(value, iptr); } +XSF_HOST_DEVICE inline double fmax(double x, double y) { return cuda::std::fmax(x, y); } +XSF_HOST_DEVICE inline double fmin(double x, double y) { return cuda::std::fmin(x, y); } +XSF_HOST_DEVICE inline double log10(double num) { return cuda::std::log10(num); } +XSF_HOST_DEVICE inline double log1p(double num) { return cuda::std::log1p(num); } +XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return cuda::std::frexp(num, exp); } +XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return cuda::std::ldexp(num, exp); } +XSF_HOST_DEVICE inline double fmod(double x, double y) { return cuda::std::fmod(x, y); } +XSF_HOST_DEVICE inline double nextafter(double from, double to) { return cuda::std::nextafter(from, to); } +#else +XSF_HOST_DEVICE inline double ceil(double x) { return ::ceil(x); } +XSF_HOST_DEVICE inline double floor(double x) { return ::floor(x); } +XSF_HOST_DEVICE inline double round(double x) { return ::round(x); } +XSF_HOST_DEVICE inline double trunc(double x) { return ::trunc(x); } +XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return ::fma(x, y, z); } +XSF_HOST_DEVICE inline double copysign(double x, double y) { return ::copysign(x, y); } +XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return ::modf(value, iptr); } +XSF_HOST_DEVICE inline double fmax(double x, double y) { return ::fmax(x, y); } +XSF_HOST_DEVICE inline double fmin(double x, double y) { return ::fmin(x, y); } +XSF_HOST_DEVICE inline double log10(double num) { return ::log10(num); } +XSF_HOST_DEVICE inline double log1p(double num) { return ::log1p(num); } +XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return ::frexp(num, exp); } +XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return ::ldexp(num, exp); } +XSF_HOST_DEVICE inline double fmod(double x, double y) { return ::fmod(x, y); } +XSF_HOST_DEVICE inline double nextafter(double from, double to) { return ::nextafter(from, to); } +#endif + +template +XSF_HOST_DEVICE void swap(T &a, T &b) { + cuda::std::swap(a, b); +} + +// Reimplement std::clamp until it's available in CuPy +template +XSF_HOST_DEVICE constexpr T clamp(T &v, T &lo, T &hi) { + return v < lo ? lo : (v > hi ? lo : v); +} + +template +using numeric_limits = cuda::std::numeric_limits; + +// Must use thrust for complex types in order to support CuPy +template +using complex = thrust::complex; + +template +XSF_HOST_DEVICE T abs(const complex &z) { + return thrust::abs(z); +} + +template +XSF_HOST_DEVICE complex exp(const complex &z) { + return thrust::exp(z); +} + +template +XSF_HOST_DEVICE complex log(const complex &z) { + return thrust::log(z); +} + +template +XSF_HOST_DEVICE T norm(const complex &z) { + return thrust::norm(z); +} + +template +XSF_HOST_DEVICE complex sqrt(const complex &z) { + return thrust::sqrt(z); +} + +template +XSF_HOST_DEVICE complex conj(const complex &z) { + return thrust::conj(z); +} + +template +XSF_HOST_DEVICE complex pow(const complex &x, const complex &y) { + return thrust::pow(x, y); +} + +template +XSF_HOST_DEVICE complex pow(const complex &x, const T &y) { + return thrust::pow(x, y); +} + +// Other types and utilities +template +using is_floating_point = cuda::std::is_floating_point; + +template +using enable_if = cuda::std::enable_if; + +template +using decay = cuda::std::decay; + +template +using invoke_result = cuda::std::invoke_result; + +template +using pair = cuda::std::pair; + +template +using tuple = cuda::std::tuple; + +using cuda::std::ptrdiff_t; +using cuda::std::size_t; +using cuda::std::uint64_t; + +#define XSF_ASSERT(a) + +} // namespace std + +#else +#define XSF_HOST_DEVICE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef DEBUG +#define XSF_ASSERT(a) assert(a) +#else +#define XSF_ASSERT(a) +#endif + +namespace xsf { + +// basic +using std::abs; + +// exponential +using std::exp; + +// power +using std::sqrt; + +// trigonometric +using std::cos; +using std::sin; + +// floating-point manipulation +using std::copysign; + +// classification and comparison +using std::isfinite; +using std::isinf; +using std::isnan; +using std::signbit; + +// complex +using std::imag; +using std::real; + +template +struct remove_complex { + using type = T; +}; + +template +struct remove_complex> { + using type = T; +}; + +template +using remove_complex_t = typename remove_complex::type; + +template +struct complex_type { + using type = std::complex; +}; + +template +using complex_type_t = typename complex_type::type; + +template +using complex = complex_type_t; + +} // namespace xsf + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h new file mode 100644 index 0000000000000000000000000000000000000000..db51362ce03907ee7c86c0995836e6d5d18160c6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h @@ -0,0 +1,205 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * Original header comment appears below. + */ + +/* An implementation of the digamma function for complex arguments. + * + * Author: Josh Wilson + * + * Distributed under the same license as Scipy. + * + * Sources: + * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov + * + * [2] mpmath (version 0.19), http://mpmath.org + */ + +#pragma once + +#include "cephes/psi.h" +#include "cephes/zeta.h" +#include "config.h" +#include "error.h" +#include "trig.h" + +namespace xsf { +namespace detail { + // All of the following were computed with mpmath + // Location of the positive root + constexpr double digamma_posroot = 1.4616321449683623; + // Value of the positive root + constexpr double digamma_posrootval = -9.2412655217294275e-17; + // Location of the negative root + constexpr double digamma_negroot = -0.504083008264455409; + // Value of the negative root + constexpr double digamma_negrootval = 7.2897639029768949e-17; + + template + XSF_HOST_DEVICE T digamma_zeta_series(T z, double root, double rootval) { + T res = rootval; + T coeff = -1.0; + + z = z - root; + T term; + for (int n = 1; n < 100; n++) { + coeff *= -z; + term = coeff * cephes::zeta(n + 1, root); + res += term; + if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) { + break; + } + } + return res; + } + + XSF_HOST_DEVICE inline std::complex + digamma_forward_recurrence(std::complex z, std::complex psiz, int n) { + /* Compute digamma(z + n) using digamma(z) using the recurrence + * relation + * + * digamma(z + 1) = digamma(z) + 1/z. + * + * See https://dlmf.nist.gov/5.5#E2 */ + std::complex res = psiz; + + for (int k = 0; k < n; k++) { + res += 1.0 / (z + static_cast(k)); + } + return res; + } + + XSF_HOST_DEVICE inline std::complex + digamma_backward_recurrence(std::complex z, std::complex psiz, int n) { + /* Compute digamma(z - n) using digamma(z) and a recurrence relation. */ + std::complex res = psiz; + + for (int k = 1; k < n + 1; k++) { + res -= 1.0 / (z - static_cast(k)); + } + return res; + } + + XSF_HOST_DEVICE inline std::complex digamma_asymptotic_series(std::complex z) { + /* Evaluate digamma using an asymptotic series. See + * + * https://dlmf.nist.gov/5.11#E2 */ + double bernoulli2k[] = {0.166666666666666667, -0.0333333333333333333, 0.0238095238095238095, + -0.0333333333333333333, 0.0757575757575757576, -0.253113553113553114, + 1.16666666666666667, -7.09215686274509804, 54.9711779448621554, + -529.124242424242424, 6192.12318840579710, -86580.2531135531136, + 1425517.16666666667, -27298231.0678160920, 601580873.900642368, + -15116315767.0921569}; + std::complex rzz = 1.0 / z / z; + std::complex zfac = 1.0; + std::complex term; + std::complex res; + + if (!(std::isfinite(z.real()) && std::isfinite(z.imag()))) { + /* Check for infinity (or nan) and return early. + * Result of division by complex infinity is implementation dependent. + * and has been observed to vary between C++ stdlib and CUDA stdlib. + */ + return std::log(z); + } + + res = std::log(z) - 0.5 / z; + + for (int k = 1; k < 17; k++) { + zfac *= rzz; + term = -bernoulli2k[k - 1] * zfac / (2 * static_cast(k)); + res += term; + if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) { + break; + } + } + return res; + } + +} // namespace detail + +XSF_HOST_DEVICE inline double digamma(double z) { + /* Wrap Cephes' psi to take advantage of the series expansion around + * the smallest negative zero. + */ + if (std::abs(z - detail::digamma_negroot) < 0.3) { + return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval); + } + return cephes::psi(z); +} + +XSF_HOST_DEVICE inline float digamma(float z) { return static_cast(digamma(static_cast(z))); } + +XSF_HOST_DEVICE inline std::complex digamma(std::complex z) { + /* + * Compute the digamma function for complex arguments. The strategy + * is: + * + * - Around the two zeros closest to the origin (posroot and negroot) + * use a Taylor series with precomputed zero order coefficient. + * - If close to the origin, use a recurrence relation to step away + * from the origin. + * - If close to the negative real axis, use the reflection formula + * to move to the right halfplane. + * - If |z| is large (> 16), use the asymptotic series. + * - If |z| is small, use a recurrence relation to make |z| large + * enough to use the asymptotic series. + */ + double absz = std::abs(z); + std::complex res = 0; + /* Use the asymptotic series for z away from the negative real axis + * with abs(z) > smallabsz. */ + int smallabsz = 16; + /* Use the reflection principle for z with z.real < 0 that are within + * smallimag of the negative real axis. + * int smallimag = 6 # unused below except in a comment */ + + if (z.real() <= 0.0 && std::ceil(z.real()) == z) { + // Poles + set_error("digamma", SF_ERROR_SINGULAR, NULL); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + if (std::abs(z - detail::digamma_negroot) < 0.3) { + // First negative root. + return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval); + } + + if (z.real() < 0 and std::abs(z.imag()) < smallabsz) { + /* Reflection formula for digamma. See + * + *https://dlmf.nist.gov/5.5#E4 + */ + res = -M_PI * cospi(z) / sinpi(z); + z = 1.0 - z; + absz = std::abs(z); + } + + if (absz < 0.5) { + /* Use one step of the recurrence relation to step away from + * the pole. */ + res = -1.0 / z; + z += 1.0; + absz = std::abs(z); + } + + if (std::abs(z - detail::digamma_posroot) < 0.5) { + res += detail::digamma_zeta_series(z, detail::digamma_posroot, detail::digamma_posrootval); + } else if (absz > smallabsz) { + res += detail::digamma_asymptotic_series(z); + } else if (z.real() >= 0.0) { + double n = std::trunc(smallabsz - absz) + 1; + std::complex init = detail::digamma_asymptotic_series(z + n); + res += detail::digamma_backward_recurrence(z + n, init, n); + } else { + // z.real() < 0, absz < smallabsz, and z.imag() > smallimag + double n = std::trunc(smallabsz - absz) - 1; + std::complex init = detail::digamma_asymptotic_series(z - n); + res += detail::digamma_forward_recurrence(z - n, init, n); + } + return res; +} + +XSF_HOST_DEVICE inline std::complex digamma(std::complex z) { + return static_cast>(digamma(static_cast>(z))); +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h new file mode 100644 index 0000000000000000000000000000000000000000..7221b5e6c4051b82f80dfb360f9fab896be6a6bd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h @@ -0,0 +1,57 @@ +#pragma once + +typedef enum { + SF_ERROR_OK = 0, /* no error */ + SF_ERROR_SINGULAR, /* singularity encountered */ + SF_ERROR_UNDERFLOW, /* floating point underflow */ + SF_ERROR_OVERFLOW, /* floating point overflow */ + SF_ERROR_SLOW, /* too many iterations required */ + SF_ERROR_LOSS, /* loss of precision */ + SF_ERROR_NO_RESULT, /* no result obtained */ + SF_ERROR_DOMAIN, /* out of domain */ + SF_ERROR_ARG, /* invalid input parameter */ + SF_ERROR_OTHER, /* unclassified error */ + SF_ERROR_MEMORY, /* memory allocation failed */ + SF_ERROR__LAST +} sf_error_t; + +#ifdef __cplusplus + +#include "config.h" + +namespace xsf { + +#ifndef SP_SPECFUN_ERROR +XSF_HOST_DEVICE inline void set_error(const char *func_name, sf_error_t code, const char *fmt, ...) { + // nothing +} +#else +void set_error(const char *func_name, sf_error_t code, const char *fmt, ...); +#endif + +template +XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, T &value) { + if (code != SF_ERROR_OK) { + set_error(name, code, nullptr); + + if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) { + value = std::numeric_limits::quiet_NaN(); + } + } +} + +template +XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, std::complex &value) { + if (code != SF_ERROR_OK) { + set_error(name, code, nullptr); + + if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) { + value.real(std::numeric_limits::quiet_NaN()); + value.imag(std::numeric_limits::quiet_NaN()); + } + } +} + +} // namespace xsf + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h new file mode 100644 index 0000000000000000000000000000000000000000..b126fb608fae47620431e05cea21ac66e6847e59 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h @@ -0,0 +1,47 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * + * Original author: Josh Wilson, 2016. + */ + +/* Evaluate polynomials. + * + * All of the coefficients are stored in reverse order, i.e. if the + * polynomial is + * + * u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0, + * + * then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0. + * + * References + * ---------- + * [1] Knuth, "The Art of Computer Programming, Volume II" + */ + +#pragma once + +#include "config.h" + +namespace xsf { + +XSF_HOST_DEVICE inline std::complex cevalpoly(const double *coeffs, int degree, std::complex z) { + /* Evaluate a polynomial with real coefficients at a complex point. + * + * Uses equation (3) in section 4.6.4 of [1]. Note that it is more + * efficient than Horner's method. + */ + double a = coeffs[0]; + double b = coeffs[1]; + double r = 2 * z.real(); + double s = std::norm(z); + double tmp; + + for (int j = 2; j < degree + 1; j++) { + tmp = b; + b = std::fma(-s, a, coeffs[j]); + a = std::fma(r, a, tmp); + } + + return z * a + b; +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h new file mode 100644 index 0000000000000000000000000000000000000000..600448aeb7f7a525aef76d4c59c31fa2489bcb1d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h @@ -0,0 +1,266 @@ +/* The functions exp1, expi below are based on translations of the Fortran code + * by Shanjie Zhang and Jianming Jin from the book + * + * Shanjie Zhang, Jianming Jin, + * Computation of Special Functions, + * Wiley, 1996, + * ISBN: 0-471-11963-6, + * LC: QA351.C45. + */ + +#pragma once + +#include "config.h" +#include "error.h" + +#include "cephes/const.h" + + +namespace xsf { + + +XSF_HOST_DEVICE inline double exp1(double x) { + // ============================================ + // Purpose: Compute exponential integral E1(x) + // Input : x --- Argument of E1(x) + // Output: E1 --- E1(x) ( x > 0 ) + // ============================================ + int k, m; + double e1, r, t, t0; + constexpr double ga = cephes::detail::SCIPY_EULER; + + if (x == 0.0) { + return std::numeric_limits::infinity(); + } + if (x <= 1.0) { + e1 = 1.0; + r = 1.0; + for (k = 1; k < 26; k++) { + r = -r*k*x/std::pow(k+1.0, 2); + e1 += r; + if (std::abs(r) <= std::abs(e1)*1e-15) { break; } + } + return -ga - std::log(x) + x*e1; + } + m = 20 + (int)(80.0/x); + t0 = 0.0; + for (k = m; k > 0; k--) { + t0 = k / (1.0 + k / (x+t0)); + } + t = 1.0 / (x + t0); + return std::exp(-x)*t; +} + +XSF_HOST_DEVICE inline float exp1(float x) { return exp1(static_cast(x)); } + +XSF_HOST_DEVICE inline std::complex exp1(std::complex z) { + // ==================================================== + // Purpose: Compute complex exponential integral E1(z) + // Input : z --- Argument of E1(z) + // Output: CE1 --- E1(z) + // ==================================================== + constexpr double el = cephes::detail::SCIPY_EULER; + int k; + std::complex ce1, cr, zc, zd, zdc; + double x = z.real(); + double a0 = std::abs(z); + // Continued fraction converges slowly near negative real axis, + // so use power series in a wedge around it until radius 40.0 + double xt = -2.0*std::abs(z.imag()); + + if (a0 == 0.0) { return std::numeric_limits::infinity(); } + if ((a0 < 5.0) || ((x < xt) && (a0 < 40.0))) { + // Power series + ce1 = 1.0; + cr = 1.0; + for (k = 1; k < 501; k++) { + cr = -cr*z*static_cast(k / std::pow(k + 1, 2)); + ce1 += cr; + if (std::abs(cr) < std::abs(ce1)*1e-15) { break; } + } + if ((x <= 0.0) && (z.imag() == 0.0)) { + //Careful on the branch cut -- use the sign of the imaginary part + // to get the right sign on the factor if pi. + ce1 = -el - std::log(-z) + z*ce1 - std::copysign(M_PI, z.imag())*std::complex(0.0, 1.0); + } else { + ce1 = -el - std::log(z) + z*ce1; + } + } else { + // Continued fraction https://dlmf.nist.gov/6.9 + // 1 1 1 2 2 3 3 + // E1 = exp(-z) * ----- ----- ----- ----- ----- ----- ----- ... + // Z + 1 + Z + 1 + Z + 1 + Z + + zc = 0.0; + zd = static_cast(1) / z; + zdc = zd; + zc += zdc; + for (k = 1; k < 501; k++) { + zd = static_cast(1) / (zd*static_cast(k) + static_cast(1)); + zdc *= (zd - static_cast(1)); + zc += zdc; + + zd = static_cast(1) / (zd*static_cast(k) + z); + zdc *= (z*zd - static_cast(1)); + zc += zdc; + if ((std::abs(zdc) <= std::abs(zc)*1e-15) && (k > 20)) { break; } + } + ce1 = std::exp(-z)*zc; + if ((x <= 0.0) && (z.imag() == 0.0)) { + ce1 -= M_PI*std::complex(0.0, 1.0); + } + } + return ce1; +} + +XSF_HOST_DEVICE inline std::complex exp1(std::complex z) { + return static_cast>(exp1(static_cast>(z))); +} + +XSF_HOST_DEVICE inline double expi(double x) { + // ============================================ + // Purpose: Compute exponential integral Ei(x) + // Input : x --- Argument of Ei(x) + // Output: EI --- Ei(x) + // ============================================ + + constexpr double ga = cephes::detail::SCIPY_EULER; + double ei, r; + + if (x == 0.0) { + ei = -std::numeric_limits::infinity(); + } else if (x < 0) { + ei = -exp1(-x); + } else if (std::abs(x) <= 40.0) { + // Power series around x=0 + ei = 1.0; + r = 1.0; + + for (int k = 1; k <= 100; k++) { + r = r * k * x / ((k + 1.0) * (k + 1.0)); + ei += r; + if (std::abs(r / ei) <= 1.0e-15) { break; } + } + ei = ga + std::log(x) + x * ei; + } else { + // Asymptotic expansion (the series is not convergent) + ei = 1.0; + r = 1.0; + for (int k = 1; k <= 20; k++) { + r = r * k / x; + ei += r; + } + ei = std::exp(x) / x * ei; + } + return ei; +} + +XSF_HOST_DEVICE inline float expi(float x) { return expi(static_cast(x)); } + +std::complex expi(std::complex z) { + // ============================================ + // Purpose: Compute exponential integral Ei(x) + // Input : x --- Complex argument of Ei(x) + // Output: EI --- Ei(x) + // ============================================ + + std::complex cei; + cei = - exp1(-z); + if (z.imag() > 0.0) { + cei += std::complex(0.0, M_PI); + } else if (z.imag() < 0.0 ) { + cei -= std::complex(0.0, M_PI); + } else { + if (z.real() > 0.0) { + cei += std::complex(0.0, copysign(M_PI, z.imag())); + } + } + return cei; +} + + +XSF_HOST_DEVICE inline std::complex expi(std::complex z) { + return static_cast>(expi(static_cast>(z))); +} + +namespace detail { + + // + // Compute a factor of the exponential integral E1. + // This is used in scaled_exp1(x) for moderate values of x. + // + // The function uses the continued fraction expansion given in equation 5.1.22 + // of Abramowitz & Stegun, "Handbook of Mathematical Functions". + // For n=1, this is + // + // E1(x) = exp(-x)*C(x) + // + // where C(x), expressed in the notation used in A&S, is the continued fraction + // + // 1 1 1 2 2 3 3 + // C(x) = --- --- --- --- --- --- --- ... + // x + 1 + x + 1 + x + 1 + x + + // + // Here, we pull a factor of 1/z out of C(x), so + // + // E1(x) = (exp(-x)/x)*F(x) + // + // and a bit of algebra gives the continued fraction expansion of F(x) to be + // + // 1 1 1 2 2 3 3 + // F(x) = --- --- --- --- --- --- --- ... + // 1 + x + 1 + x + 1 + x + 1 + + // + XSF_HOST_DEVICE inline double expint1_factor_cont_frac(double x) { + // The number of terms to use in the truncated continued fraction + // depends on x. Larger values of x require fewer terms. + int m = 20 + (int) (80.0 / x); + double t0 = 0.0; + for (int k = m; k > 0; --k) { + t0 = k / (x + k / (1 + t0)); + } + return 1 / (1 + t0); + } + +} // namespace detail + +// +// Scaled version of the exponential integral E_1(x). +// +// Factor E_1(x) as +// +// E_1(x) = exp(-x)/x * F(x) +// +// This function computes F(x). +// +// F(x) has the properties: +// * F(0) = 0 +// * F is increasing on [0, inf) +// * lim_{x->inf} F(x) = 1. +// +XSF_HOST_DEVICE inline double scaled_exp1(double x) { + if (x < 0) { + return std::numeric_limits::quiet_NaN(); + } + + if (x == 0) { + return 0.0; + } + + if (x <= 1) { + // For small x, the naive implementation is sufficiently accurate. + return x * std::exp(x) * exp1(x); + } + + if (x <= 1250) { + // For moderate x, use the continued fraction expansion. + return detail::expint1_factor_cont_frac(x); + } + + // For large x, use the asymptotic expansion. This is equation 5.1.51 + // from Abramowitz & Stegun, "Handbook of Mathematical Functions". + return 1 + (-1 + (2 + (-6 + (24 - 120 / x) / x) / x) / x) / x; +} + +XSF_HOST_DEVICE inline float scaled_exp1(float x) { return scaled_exp1(static_cast(x)); } + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h new file mode 100644 index 0000000000000000000000000000000000000000..9d4eff7532202380bcd5dbd2978d46d5f613d5eb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h @@ -0,0 +1,694 @@ +/* Implementation of Gauss's hypergeometric function for complex values. + * + * This implementation is based on the Fortran implementation by Shanjie Zhang and + * Jianming Jin included in specfun.f [1]_. Computation of Gauss's hypergeometric + * function involves handling a patchwork of special cases. By default the Zhang and + * Jin implementation has been followed as closely as possible except for situations where + * an improvement was obvious. We've attempted to document the reasons behind decisions + * made by Zhang and Jin and to document the reasons for deviating from their implementation + * when this has been done. References to the NIST Digital Library of Mathematical + * Functions [2]_ have been added where they are appropriate. The review paper by + * Pearson et al [3]_ is an excellent resource for best practices for numerical + * computation of hypergeometric functions. We have followed this review paper + * when making improvements to and correcting defects in Zhang and Jin's + * implementation. When Pearson et al propose several competing alternatives for a + * given case, we've used our best judgment to decide on the method to use. + * + * Author: Albert Steppi + * + * Distributed under the same license as Scipy. + * + * References + * ---------- + * .. [1] S. Zhang and J.M. Jin, "Computation of Special Functions", Wiley 1996 + * .. [2] NIST Digital Library of Mathematical Functions. http://dlmf.nist.gov/, + * Release 1.1.1 of 2021-03-15. F. W. J. Olver, A. B. Olde Daalhuis, + * D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R. Miller, + * B. V. Saunders, H. S. Cohl, and M. A. McClain, eds. + * .. [3] Pearson, J.W., Olver, S. & Porter, M.A. + * "Numerical methods for the computation of the confluent and Gauss + * hypergeometric functions." + * Numer Algor 74, 821-866 (2017). https://doi.org/10.1007/s11075-016-0173-0 + * .. [4] Raimundas Vidunas, "Degenerate Gauss Hypergeometric Functions", + * Kyushu Journal of Mathematics, 2007, Volume 61, Issue 1, Pages 109-135, + * .. [5] López, J.L., Temme, N.M. New series expansions of the Gauss hypergeometric + * function. Adv Comput Math 39, 349-365 (2013). + * https://doi.org/10.1007/s10444-012-9283-y + * """ + */ + +#pragma once + +#include "config.h" +#include "error.h" +#include "tools.h" + +#include "binom.h" +#include "cephes/gamma.h" +#include "cephes/lanczos.h" +#include "cephes/poch.h" +#include "cephes/hyp2f1.h" +#include "digamma.h" + +namespace xsf { +namespace detail { + constexpr double hyp2f1_EPS = 1e-15; + /* The original implementation in SciPy from Zhang and Jin used 1500 for the + * maximum number of series iterations in some cases and 500 in others. + * Through the empirical results on the test cases in + * scipy/special/_precompute/hyp2f1_data.py, it was determined that these values + * can lead to early termination of series which would have eventually converged + * at a reasonable level of accuracy. We've bumped the iteration limit to 3000, + * and may adjust it again based on further analysis. */ + constexpr std::uint64_t hyp2f1_MAXITER = 3000; + + XSF_HOST_DEVICE inline double four_gammas_lanczos(double u, double v, double w, double x) { + /* Compute ratio of gamma functions using lanczos approximation. + * + * Computes gamma(u)*gamma(v)/(gamma(w)*gamma(x)) + * + * It is assumed that x = u + v - w, but it is left to the user to + * ensure this. + * + * The lanczos approximation takes the form + * + * gamma(x) = factor(x) * lanczos_sum_expg_scaled(x) + * + * where factor(x) = ((x + lanczos_g - 0.5)/e)**(x - 0.5). + * + * The formula above is only valid for x >= 0.5, but can be extended to + * x < 0.5 with the reflection principle. + * + * Using the lanczos approximation when computing this ratio of gamma functions + * allows factors to be combined analytically to avoid underflow and overflow + * and produce a more accurate result. The condition x = u + v - w makes it + * possible to cancel the factors in the expression + * + * factor(u) * factor(v) / (factor(w) * factor(x)) + * + * by taking one factor and absorbing it into the others. Currently, this + * implementation takes the factor corresponding to the argument with largest + * absolute value and absorbs it into the others. + * + * Since this is only called internally by four_gammas. It is assumed that + * |u| >= |v| and |w| >= |x|. + */ + + /* The below implementation may incorrectly return finite results + * at poles of the gamma function. Handle these cases explicitly. */ + if ((u == std::trunc(u) && u <= 0) || (v == std::trunc(v) && v <= 0)) { + /* Return nan if numerator has pole. Diverges to +- infinity + * depending on direction so value is undefined. */ + return std::numeric_limits::quiet_NaN(); + } + if ((w == std::trunc(w) && w <= 0) || (x == std::trunc(x) && x <= 0)) { + // Return 0 if denominator has pole but not numerator. + return 0.0; + } + + double result = 1.0; + double ugh, vgh, wgh, xgh, u_prime, v_prime, w_prime, x_prime; + + if (u >= 0.5) { + result *= cephes::lanczos_sum_expg_scaled(u); + ugh = u + cephes::lanczos_g - 0.5; + u_prime = u; + } else { + result /= cephes::lanczos_sum_expg_scaled(1 - u) * std::sin(M_PI * u) * M_1_PI; + ugh = 0.5 - u + cephes::lanczos_g; + u_prime = 1 - u; + } + + if (v >= 0.5) { + result *= cephes::lanczos_sum_expg_scaled(v); + vgh = v + cephes::lanczos_g - 0.5; + v_prime = v; + } else { + result /= cephes::lanczos_sum_expg_scaled(1 - v) * std::sin(M_PI * v) * M_1_PI; + vgh = 0.5 - v + cephes::lanczos_g; + v_prime = 1 - v; + } + + if (w >= 0.5) { + result /= cephes::lanczos_sum_expg_scaled(w); + wgh = w + cephes::lanczos_g - 0.5; + w_prime = w; + } else { + result *= cephes::lanczos_sum_expg_scaled(1 - w) * std::sin(M_PI * w) * M_1_PI; + wgh = 0.5 - w + cephes::lanczos_g; + w_prime = 1 - w; + } + + if (x >= 0.5) { + result /= cephes::lanczos_sum_expg_scaled(x); + xgh = x + cephes::lanczos_g - 0.5; + x_prime = x; + } else { + result *= cephes::lanczos_sum_expg_scaled(1 - x) * std::sin(M_PI * x) * M_1_PI; + xgh = 0.5 - x + cephes::lanczos_g; + x_prime = 1 - x; + } + + if (std::abs(u) >= std::abs(w)) { + // u has greatest absolute value. Absorb ugh into the others. + if (std::abs((v_prime - u_prime) * (v - 0.5)) < 100 * ugh and v > 100) { + /* Special case where base is close to 1. Condition taken from + * Boost's beta function implementation. */ + result *= std::exp((v - 0.5) * std::log1p((v_prime - u_prime) / ugh)); + } else { + result *= std::pow(vgh / ugh, v - 0.5); + } + + if (std::abs((u_prime - w_prime) * (w - 0.5)) < 100 * wgh and u > 100) { + result *= std::exp((w - 0.5) * std::log1p((u_prime - w_prime) / wgh)); + } else { + result *= std::pow(ugh / wgh, w - 0.5); + } + + if (std::abs((u_prime - x_prime) * (x - 0.5)) < 100 * xgh and u > 100) { + result *= std::exp((x - 0.5) * std::log1p((u_prime - x_prime) / xgh)); + } else { + result *= std::pow(ugh / xgh, x - 0.5); + } + } else { + // w has greatest absolute value. Absorb wgh into the others. + if (std::abs((u_prime - w_prime) * (u - 0.5)) < 100 * wgh and u > 100) { + result *= std::exp((u - 0.5) * std::log1p((u_prime - w_prime) / wgh)); + } else { + result *= pow(ugh / wgh, u - 0.5); + } + if (std::abs((v_prime - w_prime) * (v - 0.5)) < 100 * wgh and v > 100) { + result *= std::exp((v - 0.5) * std::log1p((v_prime - w_prime) / wgh)); + } else { + result *= std::pow(vgh / wgh, v - 0.5); + } + if (std::abs((w_prime - x_prime) * (x - 0.5)) < 100 * xgh and x > 100) { + result *= std::exp((x - 0.5) * std::log1p((w_prime - x_prime) / xgh)); + } else { + result *= std::pow(wgh / xgh, x - 0.5); + } + } + // This exhausts all cases because we assume |u| >= |v| and |w| >= |x|. + + return result; + } + + XSF_HOST_DEVICE inline double four_gammas(double u, double v, double w, double x) { + double result; + + // Without loss of generality, ensure |u| >= |v| and |w| >= |x|. + if (std::abs(v) > std::abs(u)) { + std::swap(u, v); + } + if (std::abs(x) > std::abs(w)) { + std::swap(x, w); + } + /* Direct ratio tends to be more accurate for arguments in this range. Range + * chosen empirically based on the relevant benchmarks in + * scipy/special/_precompute/hyp2f1_data.py */ + if (std::abs(u) <= 100 && std::abs(v) <= 100 && std::abs(w) <= 100 && std::abs(x) <= 100) { + result = cephes::Gamma(u) * cephes::Gamma(v) * (cephes::rgamma(w) * cephes::rgamma(x)); + if (std::isfinite(result) && result != 0.0) { + return result; + } + } + result = four_gammas_lanczos(u, v, w, x); + if (std::isfinite(result) && result != 0.0) { + return result; + } + // If overflow or underflow, try again with logs. + result = std::exp(cephes::lgam(v) - cephes::lgam(x) + cephes::lgam(u) - cephes::lgam(w)); + result *= cephes::gammasgn(u) * cephes::gammasgn(w) * cephes::gammasgn(v) * cephes::gammasgn(x); + return result; + } + + class HypergeometricSeriesGenerator { + /* Maclaurin series for hyp2f1. + * + * Series is convergent for |z| < 1 but is only practical for numerical + * computation when |z| < 0.9. + */ + public: + XSF_HOST_DEVICE HypergeometricSeriesGenerator(double a, double b, double c, std::complex z) + : a_(a), b_(b), c_(c), z_(z), term_(1.0), k_(0) {} + + XSF_HOST_DEVICE std::complex operator()() { + std::complex output = term_; + term_ = term_ * (a_ + k_) * (b_ + k_) / ((k_ + 1) * (c_ + k_)) * z_; + ++k_; + return output; + } + + private: + double a_, b_, c_; + std::complex z_, term_; + std::uint64_t k_; + }; + + class Hyp2f1Transform1Generator { + /* 1 -z transformation of standard series.*/ + public: + XSF_HOST_DEVICE Hyp2f1Transform1Generator(double a, double b, double c, std::complex z) + : factor1_(four_gammas(c, c - a - b, c - a, c - b)), + factor2_(four_gammas(c, a + b - c, a, b) * std::pow(1.0 - z, c - a - b)), + generator1_(HypergeometricSeriesGenerator(a, b, a + b - c + 1, 1.0 - z)), + generator2_(HypergeometricSeriesGenerator(c - a, c - b, c - a - b + 1, 1.0 - z)) {} + + XSF_HOST_DEVICE std::complex operator()() { + return factor1_ * generator1_() + factor2_ * generator2_(); + } + + private: + std::complex factor1_, factor2_; + HypergeometricSeriesGenerator generator1_, generator2_; + }; + + class Hyp2f1Transform1LimitSeriesGenerator { + /* 1 - z transform in limit as c - a - b approaches an integer m. */ + public: + XSF_HOST_DEVICE Hyp2f1Transform1LimitSeriesGenerator(double a, double b, double m, std::complex z) + : d1_(xsf::digamma(a)), d2_(xsf::digamma(b)), d3_(xsf::digamma(1 + m)), + d4_(xsf::digamma(1.0)), a_(a), b_(b), m_(m), z_(z), log_1_z_(std::log(1.0 - z)), + factor_(cephes::rgamma(m + 1)), k_(0) {} + + XSF_HOST_DEVICE std::complex operator()() { + std::complex term_ = (d1_ + d2_ - d3_ - d4_ + log_1_z_) * factor_; + // Use digamma(x + 1) = digamma(x) + 1/x + d1_ += 1 / (a_ + k_); // d1 = digamma(a + k) + d2_ += 1 / (b_ + k_); // d2 = digamma(b + k) + d3_ += 1 / (1.0 + m_ + k_); // d3 = digamma(1 + m + k) + d4_ += 1 / (1.0 + k_); // d4 = digamma(1 + k) + factor_ *= (a_ + k_) * (b_ + k_) / ((k_ + 1.0) * (m_ + k_ + 1)) * (1.0 - z_); + ++k_; + return term_; + } + + private: + double d1_, d2_, d3_, d4_, a_, b_, m_; + std::complex z_, log_1_z_, factor_; + int k_; + }; + + class Hyp2f1Transform2Generator { + /* 1/z transformation of standard series.*/ + public: + XSF_HOST_DEVICE Hyp2f1Transform2Generator(double a, double b, double c, std::complex z) + : factor1_(four_gammas(c, b - a, b, c - a) * std::pow(-z, -a)), + factor2_(four_gammas(c, a - b, a, c - b) * std::pow(-z, -b)), + generator1_(HypergeometricSeriesGenerator(a, a - c + 1, a - b + 1, 1.0 / z)), + generator2_(HypergeometricSeriesGenerator(b, b - c + 1, b - a + 1, 1.0 / z)) {} + + XSF_HOST_DEVICE std::complex operator()() { + return factor1_ * generator1_() + factor2_ * generator2_(); + } + + private: + std::complex factor1_, factor2_; + HypergeometricSeriesGenerator generator1_, generator2_; + }; + + class Hyp2f1Transform2LimitSeriesGenerator { + /* 1/z transform in limit as a - b approaches a non-negative integer m. (Can swap a and b to + * handle the m a negative integer case. */ + public: + XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesGenerator(double a, double b, double c, double m, + std::complex z) + : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)), + d4_(xsf::digamma(c - a)), a_(a), b_(b), c_(c), m_(m), z_(z), log_neg_z_(std::log(-z)), + factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) * + xsf::cephes::rgamma(m + 1)), + k_(0) {} + + XSF_HOST_DEVICE std::complex operator()() { + std::complex term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_; + // Use digamma(x + 1) = digamma(x) + 1/x + d1_ += 1 / (1.0 + k_); // d1 = digamma(1 + k) + d2_ += 1 / (1.0 + m_ + k_); // d2 = digamma(1 + m + k) + d3_ += 1 / (a_ + k_); // d3 = digamma(a + k) + d4_ -= 1 / (c_ - a_ - k_ - 1); // d4 = digamma(c - a - k) + factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_; + ++k_; + return term; + } + + private: + double d1_, d2_, d3_, d4_, a_, b_, c_, m_; + std::complex z_, log_neg_z_, factor_; + std::uint64_t k_; + }; + + class Hyp2f1Transform2LimitSeriesCminusAIntGenerator { + /* 1/z transform in limit as a - b approaches a non-negative integer m, and c - a approaches + * a positive integer n. */ + public: + XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesCminusAIntGenerator(double a, double b, double c, double m, + double n, std::complex z) + : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)), + d4_(xsf::digamma(n)), a_(a), b_(b), c_(c), m_(m), n_(n), z_(z), log_neg_z_(std::log(-z)), + factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) * + xsf::cephes::rgamma(m + 1)), + k_(0) {} + + XSF_HOST_DEVICE std::complex operator()() { + std::complex term; + if (k_ < n_) { + term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_; + // Use digamma(x + 1) = digamma(x) + 1/x + d1_ += 1 / (1.0 + k_); // d1 = digamma(1 + k) + d2_ += 1 / (1 + m_ + k_); // d2 = digamma(1 + m + k) + d3_ += 1 / (a_ + k_); // d3 = digamma(a + k) + d4_ -= 1 / (n_ - k_ - 1); // d4 = digamma(c - a - k) + factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_; + ++k_; + return term; + } + if (k_ == n_) { + /* When c - a approaches a positive integer and k_ >= c - a = n then + * poch(1 - c + b + m + k) = poch(1 - c + a + k) = approaches zero and + * digamma(c - a - k) approaches a pole. However we can use the limit + * digamma(-n + epsilon) / gamma(-n + epsilon) -> (-1)**(n + 1) * (n+1)! as epsilon -> 0 + * to continue the series. + * + * poch(1 - c + b, m + k) = gamma(1 - c + b + m + k)/gamma(1 - c + b) + * + * If a - b is an integer and c - a is an integer, then a and b must both be integers, so assume + * a and b are integers and take the limit as c approaches an integer. + * + * gamma(1 - c + epsilon + a + k)/gamma(1 - c - epsilon + b) = + * (gamma(c + epsilon - b) / gamma(c + epsilon - a - k)) * + * (sin(pi * (c + epsilon - b)) / sin(pi * (c + epsilon - a - k))) (reflection principle) + * + * In the limit as epsilon goes to zero, the ratio of sines will approach + * (-1)**(a - b + k) = (-1)**(m + k) + * + * We may then replace + * + * poch(1 - c - epsilon + b, m + k)*digamma(c + epsilon - a - k) + * + * with + * + * (-1)**(a - b + k)*gamma(c + epsilon - b) * digamma(c + epsilon - a - k) / gamma(c + epsilon - a - k) + * + * and taking the limit epsilon -> 0 gives + * + * (-1)**(a - b + k) * gamma(c - b) * (-1)**(k + a - c + 1)(k + a - c)! + * = (-1)**(c - b - 1)*Gamma(k + a - c + 1) + */ + factor_ = std::pow(-1, m_ + n_) * xsf::binom(c_ - 1, b_ - 1) * + xsf::cephes::poch(c_ - a_ + 1, m_ - 1) / std::pow(z_, static_cast(k_)); + } + term = factor_; + factor_ *= (b_ + m_ + k_) * (k_ + a_ - c_ + 1) / ((k_ + 1) * (m_ + k_ + 1)) / z_; + ++k_; + return term; + } + + private: + double d1_, d2_, d3_, d4_, a_, b_, c_, m_, n_; + std::complex z_, log_neg_z_, factor_; + std::uint64_t k_; + }; + + class Hyp2f1Transform2LimitFinitePartGenerator { + /* Initial finite sum in limit as a - b approaches a non-negative integer m. The limiting series + * for the 1 - z transform also has an initial finite sum, but it is a standard hypergeometric + * series. */ + public: + XSF_HOST_DEVICE Hyp2f1Transform2LimitFinitePartGenerator(double b, double c, double m, + std::complex z) + : b_(b), c_(c), m_(m), z_(z), term_(cephes::Gamma(m) * cephes::rgamma(c - b)), k_(0) {} + + XSF_HOST_DEVICE std::complex operator()() { + std::complex output = term_; + term_ = term_ * (b_ + k_) * (c_ - b_ - k_ - 1) / ((k_ + 1) * (m_ - k_ - 1)) / z_; + ++k_; + return output; + } + + private: + double b_, c_, m_; + std::complex z_, term_; + std::uint64_t k_; + }; + + class LopezTemmeSeriesGenerator { + /* Lopez-Temme Series for Gaussian hypergeometric function [4]. + * + * Converges for all z with real(z) < 1, including in the regions surrounding + * the points exp(+- i*pi/3) that are not covered by any of the standard + * transformations. + */ + public: + XSF_HOST_DEVICE LopezTemmeSeriesGenerator(double a, double b, double c, std::complex z) + : n_(0), a_(a), b_(b), c_(c), phi_previous_(1.0), phi_(1 - 2 * b / c), z_(z), Z_(a * z / (z - 2.0)) {} + + XSF_HOST_DEVICE std::complex operator()() { + if (n_ == 0) { + ++n_; + return 1.0; + } + if (n_ > 1) { // Update phi and Z for n>=2 + double new_phi = ((n_ - 1) * phi_previous_ - (2.0 * b_ - c_) * phi_) / (c_ + (n_ - 1)); + phi_previous_ = phi_; + phi_ = new_phi; + Z_ = Z_ * z_ / (z_ - 2.0) * ((a_ + (n_ - 1)) / n_); + } + ++n_; + return Z_ * phi_; + } + + private: + std::uint64_t n_; + double a_, b_, c_, phi_previous_, phi_; + std::complex z_, Z_; + }; + + XSF_HOST_DEVICE std::complex hyp2f1_transform1_limiting_case(double a, double b, double c, double m, + std::complex z) { + /* 1 - z transform in limiting case where c - a - b approaches an integer m. */ + std::complex result = 0.0; + if (m >= 0) { + if (m != 0) { + auto series_generator = HypergeometricSeriesGenerator(a, b, 1 - m, 1.0 - z); + result += four_gammas(m, c, a + m, b + m) * series_eval_fixed_length(series_generator, + std::complex{0.0, 0.0}, + static_cast(m)); + } + std::complex prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) / + (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b)) * + std::pow(1.0 - z, m); + auto series_generator = Hyp2f1Transform1LimitSeriesGenerator(a + m, b + m, m, z); + result += prefactor * series_eval(series_generator, std::complex{0.0, 0.0}, hyp2f1_EPS, + hyp2f1_MAXITER, "hyp2f1"); + return result; + } else { + result = four_gammas(-m, c, a, b) * std::pow(1.0 - z, m); + auto series_generator1 = HypergeometricSeriesGenerator(a + m, b + m, 1 + m, 1.0 - z); + result *= series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0}, + static_cast(-m)); + double prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) * + (xsf::cephes::rgamma(a + m) * xsf::cephes::rgamma(b + m)); + auto series_generator2 = Hyp2f1Transform1LimitSeriesGenerator(a, b, -m, z); + result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS, + hyp2f1_MAXITER, "hyp2f1"); + return result; + } + } + + XSF_HOST_DEVICE std::complex hyp2f1_transform2_limiting_case(double a, double b, double c, double m, + std::complex z) { + /* 1 / z transform in limiting case where a - b approaches a non-negative integer m. Negative integer case + * can be handled by swapping a and b. */ + auto series_generator1 = Hyp2f1Transform2LimitFinitePartGenerator(b, c, m, z); + std::complex result = cephes::Gamma(c) * cephes::rgamma(a) * std::pow(-z, -b); + result *= + series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0}, static_cast(m)); + std::complex prefactor = cephes::Gamma(c) * (cephes::rgamma(a) * cephes::rgamma(c - b) * std::pow(-z, -a)); + double n = c - a; + if (abs(n - std::round(n)) < hyp2f1_EPS) { + auto series_generator2 = Hyp2f1Transform2LimitSeriesCminusAIntGenerator(a, b, c, m, n, z); + result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS, + hyp2f1_MAXITER, "hyp2f1"); + return result; + } + auto series_generator2 = Hyp2f1Transform2LimitSeriesGenerator(a, b, c, m, z); + result += prefactor * + series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS, hyp2f1_MAXITER, "hyp2f1"); + return result; + } + +} // namespace detail + +XSF_HOST_DEVICE inline std::complex hyp2f1(double a, double b, double c, std::complex z) { + /* Special Cases + * ----------------------------------------------------------------------- + * Takes constant value 1 when a = 0 or b = 0, even if c is a non-positive + * integer. This follows mpmath. */ + if (a == 0 || b == 0) { + return 1.0; + } + double z_abs = std::abs(z); + // Equals 1 when z i 0, unless c is 0. + if (z_abs == 0) { + if (c != 0) { + return 1.0; + } else { + // Returning real part NAN and imaginary part 0 follows mpmath. + return std::complex{std::numeric_limits::quiet_NaN(), 0}; + } + } + bool a_neg_int = a == std::trunc(a) && a < 0; + bool b_neg_int = b == std::trunc(b) && b < 0; + bool c_non_pos_int = c == std::trunc(c) and c <= 0; + /* Diverges when c is a non-positive integer unless a is an integer with + * c <= a <= 0 or b is an integer with c <= b <= 0, (or z equals 0 with + * c != 0) Cases z = 0, a = 0, or b = 0 have already been handled. We follow + * mpmath in handling the degenerate cases where any of a, b, c are + * non-positive integers. See [3] for a treatment of degenerate cases. */ + if (c_non_pos_int && !((a_neg_int && c <= a && a < 0) || (b_neg_int && c <= b && b < 0))) { + return std::complex{std::numeric_limits::infinity(), 0}; + } + /* Reduces to a polynomial when a or b is a negative integer. + * If a and b are both negative integers, we take care to terminate + * the series at a or b of smaller magnitude. This is to ensure proper + * handling of situations like a < c < b <= 0, a, b, c all non-positive + * integers, where terminating at a would lead to a term of the form 0 / 0. */ + double max_degree; + if (a_neg_int || b_neg_int) { + if (a_neg_int && b_neg_int) { + max_degree = a > b ? std::abs(a) : std::abs(b); + } else if (a_neg_int) { + max_degree = std::abs(a); + } else { + max_degree = std::abs(b); + } + if (max_degree <= (double) UINT64_MAX) { + auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z); + return detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 1); + } else { + set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL); + return std::complex{std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()}; + } + } + // Kummer's Theorem for z = -1; c = 1 + a - b (DLMF 15.4.26) + if (std::abs(z + 1.0) < detail::hyp2f1_EPS && std::abs(1 + a - b - c) < detail::hyp2f1_EPS && !c_non_pos_int) { + return detail::four_gammas(a - b + 1, 0.5 * a + 1, a + 1, 0.5 * a - b + 1); + } + std::complex result; + bool c_minus_a_neg_int = c - a == std::trunc(c - a) && c - a < 0; + bool c_minus_b_neg_int = c - b == std::trunc(c - b) && c - b < 0; + /* If one of c - a or c - b is a negative integer, reduces to evaluating + * a polynomial through an Euler hypergeometric transformation. + * (DLMF 15.8.1) */ + if (c_minus_a_neg_int || c_minus_b_neg_int) { + max_degree = c_minus_b_neg_int ? std::abs(c - b) : std::abs(c - a); + if (max_degree <= (double) UINT64_MAX) { + result = std::pow(1.0 - z, c - a - b); + auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z); + result *= + detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 2); + return result; + } else { + set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL); + return std::complex{std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()}; + } + } + /* Diverges as real(z) -> 1 when c <= a + b. + * Todo: Actually check for overflow instead of using a fixed tolerance for + * all parameter combinations like in the Fortran original. */ + if (std::abs(1 - z.real()) < detail::hyp2f1_EPS && z.imag() == 0 && c - a - b <= 0 && !c_non_pos_int) { + return std::complex{std::numeric_limits::infinity(), 0}; + } + // Gauss's Summation Theorem for z = 1; c - a - b > 0 (DLMF 15.4.20). + if (z == 1.0 && c - a - b > 0 && !c_non_pos_int) { + return detail::four_gammas(c, c - a - b, c - a, c - b); + } + /* |z| < 0, z.real() >= 0. Use the Maclaurin Series. + * ----------------------------------------------------------------------- + * Apply Euler Hypergeometric Transformation (DLMF 15.8.1) to reduce + * size of a and b if possible. We follow Zhang and Jin's + * implementation [1] although there is very likely a better heuristic + * to determine when this transformation should be applied. As it + * stands, this hurts precision in some cases. */ + if (z_abs < 0.9 && z.real() >= 0) { + if (c - a < a && c - b < b) { + result = std::pow(1.0 - z, c - a - b); + auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z); + result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS, + detail::hyp2f1_MAXITER, "hyp2f1"); + return result; + } + auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z); + return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS, + detail::hyp2f1_MAXITER, "hyp2f1"); + } + /* Points near exp(iπ/3), exp(-iπ/3) not handled by any of the standard + * transformations. Use series of López and Temme [5]. These regions + * were not correctly handled by Zhang and Jin's implementation. + * -------------------------------------------------------------------------*/ + if (0.9 <= z_abs && z_abs < 1.1 && std::abs(1.0 - z) >= 0.9 && z.real() >= 0) { + /* This condition for applying Euler Transformation (DLMF 15.8.1) + * was determined empirically to work better for this case than that + * used in Zhang and Jin's implementation for |z| < 0.9, + * real(z) >= 0. */ + if ((c - a <= a && c - b < b) || (c - a < a && c - b <= b)) { + auto series_generator = detail::LopezTemmeSeriesGenerator(c - a, c - b, c, z); + result = std::pow(1.0 - 0.5 * z, a - c); // Lopez-Temme prefactor + result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS, + detail::hyp2f1_MAXITER, "hyp2f1"); + return std::pow(1.0 - z, c - a - b) * result; // Euler transform prefactor. + } + auto series_generator = detail::LopezTemmeSeriesGenerator(a, b, c, z); + result = detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS, + detail::hyp2f1_MAXITER, "hyp2f1"); + return std::pow(1.0 - 0.5 * z, -a) * result; // Lopez-Temme prefactor. + } + /* z/(z - 1) transformation (DLMF 15.8.1). Avoids cancellation issues that + * occur with Maclaurin series for real(z) < 0. + * -------------------------------------------------------------------------*/ + if (z_abs < 1.1 && z.real() < 0) { + if (0 < b && b < a && a < c) { + std::swap(a, b); + } + auto series_generator = detail::HypergeometricSeriesGenerator(a, c - b, c, z / (z - 1.0)); + return std::pow(1.0 - z, -a) * detail::series_eval(series_generator, std::complex{0.0, 0.0}, + detail::hyp2f1_EPS, detail::hyp2f1_MAXITER, "hyp2f1"); + } + /* 1 - z transformation (DLMF 15.8.4). */ + if (0.9 <= z_abs && z_abs < 1.1) { + if (std::abs(c - a - b - std::round(c - a - b)) < detail::hyp2f1_EPS) { + // Removable singularity when c - a - b is an integer. Need to use limiting formula. + double m = std::round(c - a - b); + return detail::hyp2f1_transform1_limiting_case(a, b, c, m, z); + } + auto series_generator = detail::Hyp2f1Transform1Generator(a, b, c, z); + return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS, + detail::hyp2f1_MAXITER, "hyp2f1"); + } + /* 1/z transformation (DLMF 15.8.2). */ + if (std::abs(a - b - std::round(a - b)) < detail::hyp2f1_EPS) { + if (b > a) { + std::swap(a, b); + } + double m = std::round(a - b); + return detail::hyp2f1_transform2_limiting_case(a, b, c, m, z); + } + auto series_generator = detail::Hyp2f1Transform2Generator(a, b, c, z); + return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS, + detail::hyp2f1_MAXITER, "hyp2f1"); +} + +XSF_HOST_DEVICE inline std::complex hyp2f1(float a, float b, float c, std::complex x) { + return static_cast>(hyp2f1(static_cast(a), static_cast(b), + static_cast(c), static_cast>(x))); +} + +XSF_HOST_DEVICE inline double hyp2f1(double a, double b, double c, double x) { return cephes::hyp2f1(a, b, c, x); } + +XSF_HOST_DEVICE inline float hyp2f1(float a, float b, float c, float x) { + return hyp2f1(static_cast(a), static_cast(b), static_cast(c), static_cast(x)); +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h new file mode 100644 index 0000000000000000000000000000000000000000..e5dc871bd003937a483a39001d796b1bacc26d01 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h @@ -0,0 +1,173 @@ +// Numerically stable computation of iv(v+1, x) / iv(v, x) + +#pragma once + +#include "config.h" +#include "tools.h" +#include "error.h" +#include "cephes/dd_real.h" + +namespace xsf { + +/* Generates the "tail" of Perron's continued fraction for iv(v,x)/iv(v-1,x). + * + * The Perron continued fraction is studied in [1]. It is given by + * + * iv(v, x) x -(2v+1)x -(2v+3)x -(2v+5)x + * R := --------- = ------ ---------- ---------- ---------- ... + * iv(v-1,x) x+2v + 2(v+x)+1 + 2(v+x)+2 + 2(v+x)+3 + + * + * Given a suitable constant c, the continued fraction may be rearranged + * into the following form to avoid premature floating point overflow: + * + * xc -(2vc+c)(xc) -(2vc+3c)(xc) -(2vc+5c)(xc) + * R = -----, fc = 2vc + ------------ ------------- ------------- ... + * xc+fc 2(vc+xc)+c + 2(vc+xc)+2c + 2(vc+xc)+3c + + * + * This class generates the fractions of fc after 2vc. + * + * [1] Gautschi, W. and Slavik, J. (1978). "On the computation of modified + * Bessel function ratios." Mathematics of Computation, 32(143):865-875. + */ +template +struct IvRatioCFTailGenerator { + + XSF_HOST_DEVICE IvRatioCFTailGenerator(T vc, T xc, T c) noexcept { + a0_ = -(2*vc-c)*xc; + as_ = -2*c*xc; + b0_ = 2*(vc+xc); + bs_ = c; + k_ = 0; + } + + XSF_HOST_DEVICE std::pair operator()() noexcept { + using std::fma; + ++k_; + return {fma(static_cast(k_), as_, a0_), + fma(static_cast(k_), bs_, b0_)}; + } + +private: + T a0_, as_; // a[k] == a0 + as*k, k >= 1 + T b0_, bs_; // b[k] == b0 + bs*k, k >= 1 + std::uint64_t k_; // current index +}; + +// Computes f(v, x) using Perron's continued fraction. +// +// T specifies the working type. This allows the function to perform +// calculations in a higher precision, such as double-double, even if +// the return type is hardcoded to be double. +template +XSF_HOST_DEVICE inline std::pair +_iv_ratio_cf(double v, double x, bool complement) { + + int e; + std::frexp(std::fmax(v, x), &e); + T c = T(std::ldexp(1, 2-e)); // rescaling multiplier + T vc = v * c; + T xc = x * c; + + IvRatioCFTailGenerator cf(vc, xc, c); + auto [fc, terms] = detail::series_eval_kahan( + detail::continued_fraction_series(cf), + T(std::numeric_limits::epsilon()), + 1000, + 2*vc); + + T ret = (complement ? fc : xc) / (xc + fc); + return {static_cast(ret), terms}; +} + +XSF_HOST_DEVICE inline double iv_ratio(double v, double x) { + + if (std::isnan(v) || std::isnan(x)) { + return std::numeric_limits::quiet_NaN(); + } + if (v < 0.5 || x < 0) { + set_error("iv_ratio", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (std::isinf(v) && std::isinf(x)) { + // There is not a unique limit as both v and x tends to infinity. + set_error("iv_ratio", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (x == 0.0) { + return x; // keep sign of x because iv_ratio is an odd function + } + if (std::isinf(v)) { + return 0.0; + } + if (std::isinf(x)) { + return 1.0; + } + + auto [ret, terms] = _iv_ratio_cf(v, x, false); + if (terms == 0) { // failed to converge; should not happen + set_error("iv_ratio", SF_ERROR_NO_RESULT, NULL); + return std::numeric_limits::quiet_NaN(); + } + return ret; +} + +XSF_HOST_DEVICE inline float iv_ratio(float v, float x) { + return iv_ratio(static_cast(v), static_cast(x)); +} + +XSF_HOST_DEVICE inline double iv_ratio_c(double v, double x) { + + if (std::isnan(v) || std::isnan(x)) { + return std::numeric_limits::quiet_NaN(); + } + if (v < 0.5 || x < 0) { + set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (std::isinf(v) && std::isinf(x)) { + // There is not a unique limit as both v and x tends to infinity. + set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (x == 0.0) { + return 1.0; + } + if (std::isinf(v)) { + return 1.0; + } + if (std::isinf(x)) { + return 0.0; + } + + if (v >= 1) { + // Numerical experiments show that evaluating the Perron c.f. + // in double precision is sufficiently accurate if v >= 1. + auto [ret, terms] = _iv_ratio_cf(v, x, true); + if (terms == 0) { // failed to converge; should not happen + set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL); + return std::numeric_limits::quiet_NaN(); + } + return ret; + } else if (v > 0.5) { + // double-double arithmetic is needed for 0.5 < v < 1 to + // achieve relative error on the scale of machine precision. + using cephes::detail::double_double; + auto [ret, terms] = _iv_ratio_cf(v, x, true); + if (terms == 0) { // failed to converge; should not happen + set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL); + return std::numeric_limits::quiet_NaN(); + } + return ret; + } else { + // The previous branch (v > 0.5) also works for v == 0.5, but + // the closed-form formula "1 - tanh(x)" is more efficient. + double t = std::exp(-2*x); + return (2 * t) / (1 + t); + } +} + +XSF_HOST_DEVICE inline float iv_ratio_c(float v, float x) { + return iv_ratio_c(static_cast(v), static_cast(x)); +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h new file mode 100644 index 0000000000000000000000000000000000000000..9eb1882eaec464b5e5dcf47f2168f9125996a816 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h @@ -0,0 +1,150 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * Original header with Copyright information appears below. + */ + +/* Implementation of the Lambert W function [1]. Based on MPMath + * Implementation [2], and documentation [3]. + * + * Copyright: Yosef Meller, 2009 + * Author email: mellerf@netvision.net.il + * + * Distributed under the same license as SciPy + * + * + * References: + * [1] On the Lambert W function, Adv. Comp. Math. 5 (1996) 329-359, + * available online: https://web.archive.org/web/20230123211413/https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf + * [2] mpmath source code, + https://github.com/mpmath/mpmath/blob/c5939823669e1bcce151d89261b802fe0d8978b4/mpmath/functions/functions.py#L435-L461 + * [3] + https://web.archive.org/web/20230504171447/https://mpmath.org/doc/current/functions/powers.html#lambert-w-function + * + + * TODO: use a series expansion when extremely close to the branch point + * at `-1/e` and make sure that the proper branch is chosen there. + */ + +#pragma once + +#include "config.h" +#include "error.h" +#include "evalpoly.h" + +namespace xsf { +constexpr double EXPN1 = 0.36787944117144232159553; // exp(-1) +constexpr double OMEGA = 0.56714329040978387299997; // W(1, 0) + +namespace detail { + XSF_HOST_DEVICE inline std::complex lambertw_branchpt(std::complex z) { + // Series for W(z, 0) around the branch point; see 4.22 in [1]. + double coeffs[] = {-1.0 / 3.0, 1.0, -1.0}; + std::complex p = std::sqrt(2.0 * (M_E * z + 1.0)); + + return cevalpoly(coeffs, 2, p); + } + + XSF_HOST_DEVICE inline std::complex lambertw_pade0(std::complex z) { + // (3, 2) Pade approximation for W(z, 0) around 0. + double num[] = {12.85106382978723404255, 12.34042553191489361902, 1.0}; + double denom[] = {32.53191489361702127660, 14.34042553191489361702, 1.0}; + + /* This only gets evaluated close to 0, so we don't need a more + * careful algorithm that avoids overflow in the numerator for + * large z. */ + return z * cevalpoly(num, 2, z) / cevalpoly(denom, 2, z); + } + + XSF_HOST_DEVICE inline std::complex lambertw_asy(std::complex z, long k) { + /* Compute the W function using the first two terms of the + * asymptotic series. See 4.20 in [1]. + */ + std::complex w = std::log(z) + 2.0 * M_PI * k * std::complex(0, 1); + return w - std::log(w); + } + +} // namespace detail + +XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, double tol) { + double absz; + std::complex w; + std::complex ew, wew, wewz, wn; + + if (std::isnan(z.real()) || std::isnan(z.imag())) { + return z; + } + if (z.real() == std::numeric_limits::infinity()) { + return z + 2.0 * M_PI * k * std::complex(0, 1); + } + if (z.real() == -std::numeric_limits::infinity()) { + return -z + (2.0 * M_PI * k + M_PI) * std::complex(0, 1); + } + if (z == 0.0) { + if (k == 0) { + return z; + } + set_error("lambertw", SF_ERROR_SINGULAR, NULL); + return -std::numeric_limits::infinity(); + } + if (z == 1.0 && k == 0) { + // Split out this case because the asymptotic series blows up + return OMEGA; + } + + absz = std::abs(z); + // Get an initial guess for Halley's method + if (k == 0) { + if (std::abs(z + EXPN1) < 0.3) { + w = detail::lambertw_branchpt(z); + } else if (-1.0 < z.real() && z.real() < 1.5 && std::abs(z.imag()) < 1.0 && + -2.5 * std::abs(z.imag()) - 0.2 < z.real()) { + /* Empirically determined decision boundary where the Pade + * approximation is more accurate. */ + w = detail::lambertw_pade0(z); + } else { + w = detail::lambertw_asy(z, k); + } + } else if (k == -1) { + if (absz <= EXPN1 && z.imag() == 0.0 && z.real() < 0.0) { + w = std::log(-z.real()); + } else { + w = detail::lambertw_asy(z, k); + } + } else { + w = detail::lambertw_asy(z, k); + } + + // Halley's method; see 5.9 in [1] + if (w.real() >= 0) { + // Rearrange the formula to avoid overflow in exp + for (int i = 0; i < 100; i++) { + ew = std::exp(-w); + wewz = w - z * ew; + wn = w - wewz / (w + 1.0 - (w + 2.0) * wewz / (2.0 * w + 2.0)); + if (std::abs(wn - w) <= tol * std::abs(wn)) { + return wn; + } + w = wn; + } + } else { + for (int i = 0; i < 100; i++) { + ew = std::exp(w); + wew = w * ew; + wewz = wew - z; + wn = w - wewz / (wew + ew - (w + 2.0) * wewz / (2.0 * w + 2.0)); + if (std::abs(wn - w) <= tol * std::abs(wn)) { + return wn; + } + w = wn; + } + } + + set_error("lambertw", SF_ERROR_SLOW, "iteration failed to converge: %g + %gj", z.real(), z.imag()); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; +} + +XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, float tol) { + return static_cast>( + lambertw(static_cast>(z), k, static_cast(tol))); +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h new file mode 100644 index 0000000000000000000000000000000000000000..eaae479b2054177153b8671e7fe3174f1b09f20a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h @@ -0,0 +1,163 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * Original header comment appears below. + */ + +/* An implementation of the principal branch of the logarithm of + * Gamma. Also contains implementations of Gamma and 1/Gamma which are + * easily computed from log-Gamma. + * + * Author: Josh Wilson + * + * Distributed under the same license as Scipy. + * + * References + * ---------- + * [1] Hare, "Computing the Principal Branch of log-Gamma", + * Journal of Algorithms, 1997. + * + * [2] Julia, + * https://github.com/JuliaLang/julia/blob/master/base/special/gamma.jl + */ + +#pragma once + +#include "cephes/gamma.h" +#include "cephes/rgamma.h" +#include "config.h" +#include "error.h" +#include "evalpoly.h" +#include "trig.h" +#include "zlog1.h" + +namespace xsf { + +namespace detail { + constexpr double loggamma_SMALLX = 7; + constexpr double loggamma_SMALLY = 7; + constexpr double loggamma_HLOG2PI = 0.918938533204672742; // log(2*pi)/2 + constexpr double loggamma_LOGPI = 1.1447298858494001741434262; // log(pi) + constexpr double loggamma_TAYLOR_RADIUS = 0.2; + + XSF_HOST_DEVICE std::complex loggamma_stirling(std::complex z) { + /* Stirling series for log-Gamma + * + * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the + * (2*n)th Bernoulli number. See (1.1) in [1]. + */ + double coeffs[] = {-2.955065359477124183E-2, 6.4102564102564102564E-3, -1.9175269175269175269E-3, + 8.4175084175084175084E-4, -5.952380952380952381E-4, 7.9365079365079365079E-4, + -2.7777777777777777778E-3, 8.3333333333333333333E-2}; + std::complex rz = 1.0 / z; + std::complex rzz = rz / z; + + return (z - 0.5) * std::log(z) - z + loggamma_HLOG2PI + rz * cevalpoly(coeffs, 7, rzz); + } + + XSF_HOST_DEVICE std::complex loggamma_recurrence(std::complex z) { + /* Backward recurrence relation. + * + * See Proposition 2.2 in [1] and the Julia implementation [2]. + * + */ + int signflips = 0; + int sb = 0; + std::complex shiftprod = z; + + z += 1.0; + int nsb; + while (z.real() <= loggamma_SMALLX) { + shiftprod *= z; + nsb = std::signbit(shiftprod.imag()); + signflips += nsb != 0 && sb == 0 ? 1 : 0; + sb = nsb; + z += 1.0; + } + return loggamma_stirling(z) - std::log(shiftprod) - signflips * 2 * M_PI * std::complex(0, 1); + } + + XSF_HOST_DEVICE std::complex loggamma_taylor(std::complex z) { + /* Taylor series for log-Gamma around z = 1. + * + * It is + * + * loggamma(z + 1) = -gamma*z + zeta(2)*z**2/2 - zeta(3)*z**3/3 ... + * + * where gamma is the Euler-Mascheroni constant. + */ + + double coeffs[] = { + -4.3478266053040259361E-2, 4.5454556293204669442E-2, -4.7619070330142227991E-2, 5.000004769810169364E-2, + -5.2631679379616660734E-2, 5.5555767627403611102E-2, -5.8823978658684582339E-2, 6.2500955141213040742E-2, + -6.6668705882420468033E-2, 7.1432946295361336059E-2, -7.6932516411352191473E-2, 8.3353840546109004025E-2, + -9.0954017145829042233E-2, 1.0009945751278180853E-1, -1.1133426586956469049E-1, 1.2550966952474304242E-1, + -1.4404989676884611812E-1, 1.6955717699740818995E-1, -2.0738555102867398527E-1, 2.7058080842778454788E-1, + -4.0068563438653142847E-1, 8.2246703342411321824E-1, -5.7721566490153286061E-1}; + + z -= 1.0; + return z * cevalpoly(coeffs, 22, z); + } +} // namespace detail + +XSF_HOST_DEVICE inline double loggamma(double x) { + if (x < 0.0) { + return std::numeric_limits::quiet_NaN(); + } + return cephes::lgam(x); +} + +XSF_HOST_DEVICE inline float loggamma(float x) { return loggamma(static_cast(x)); } + +XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) { + // Compute the principal branch of log-Gamma + + if (std::isnan(z.real()) || std::isnan(z.imag())) { + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + if (z.real() <= 0 and z == std::floor(z.real())) { + set_error("loggamma", SF_ERROR_SINGULAR, NULL); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + if (z.real() > detail::loggamma_SMALLX || std::abs(z.imag()) > detail::loggamma_SMALLY) { + return detail::loggamma_stirling(z); + } + if (std::abs(z - 1.0) < detail::loggamma_TAYLOR_RADIUS) { + return detail::loggamma_taylor(z); + } + if (std::abs(z - 2.0) < detail::loggamma_TAYLOR_RADIUS) { + // Recurrence relation and the Taylor series around 1. + return detail::zlog1(z - 1.0) + detail::loggamma_taylor(z - 1.0); + } + if (z.real() < 0.1) { + // Reflection formula; see Proposition 3.1 in [1] + double tmp = std::copysign(2 * M_PI, z.imag()) * std::floor(0.5 * z.real() + 0.25); + return std::complex(detail::loggamma_LOGPI, tmp) - std::log(sinpi(z)) - loggamma(1.0 - z); + } + if (std::signbit(z.imag()) == 0) { + // z.imag() >= 0 but is not -0.0 + return detail::loggamma_recurrence(z); + } + return std::conj(detail::loggamma_recurrence(std::conj(z))); +} + +XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) { + return static_cast>(loggamma(static_cast>(z))); +} + +XSF_HOST_DEVICE inline double rgamma(double z) { return cephes::rgamma(z); } + +XSF_HOST_DEVICE inline float rgamma(float z) { return rgamma(static_cast(z)); } + +XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) { + // Compute 1/Gamma(z) using loggamma. + if (z.real() <= 0 && z == std::floor(z.real())) { + // Zeros at 0, -1, -2, ... + return 0.0; + } + return std::exp(-loggamma(z)); +} + +XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) { + return static_cast>(rgamma(static_cast>(z))); +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h new file mode 100644 index 0000000000000000000000000000000000000000..4d26b64e02aa3f65a97d99160047efd76e7f121d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h @@ -0,0 +1,200 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* Implementation of sin/cos/sinh/cosh integrals for complex arguments + * + * Sources + * [1] Fredrik Johansson and others. mpmath: a Python library for + * arbitrary-precision floating-point arithmetic (version 0.19), + * December 2013. http://mpmath.org/. + * [2] NIST, "Digital Library of Mathematical Functions", + * https://dlmf.nist.gov/ + */ + +#pragma once + +#include "config.h" +#include "error.h" + +#include "expint.h" +#include "cephes/const.h" +#include "cephes/sici.h" +#include "cephes/shichi.h" + +namespace xsf { +namespace detail { + + XSF_HOST_DEVICE inline void sici_power_series(int sgn, std::complex z, + std::complex *s, std::complex *c) { + /* DLMF 6.6.5 and 6.6.6. If sgn = -1 computes si/ci, and if sgn = 1 + * computes shi/chi. + */ + std::complex fac = z; + *s = fac; + *c = 0; + std::complex term1, term2; + for (int n = 1; n < 100; n++) { + fac *= static_cast(sgn)*z/(2.0*n); + term2 = fac/(2.0*n); + *c += term2; + fac *= z/(2.0*n + 1.0); + term1 = fac/(2.0*n + 1.0); + *s += term1; + constexpr double tol = std::numeric_limits::epsilon(); + if (std::abs(term1) < tol*std::abs(*s) && std::abs(term2) < tol*std::abs(*c)) { + break; + } + } + } + +} + + +XSF_HOST_DEVICE inline int sici(std::complex z, + std::complex *si, std::complex *ci) { + /* Compute sin/cos integrals at complex arguments. The algorithm + * largely follows that of [1]. + */ + + constexpr double EULER = xsf::cephes::detail::SCIPY_EULER; + + if (z == std::numeric_limits::infinity()) { + *si = M_PI_2; + *ci = 0; + return 0; + } + if (z == -std::numeric_limits::infinity()) { + *si = -M_PI_2; + *ci = {0.0, M_PI}; + return 0; + } + + if (std::abs(z) < 0.8) { + // Use the series to avoid cancellation in si + detail::sici_power_series(-1, z, si, ci); + + if (z == 0.0) { + set_error("sici", SF_ERROR_DOMAIN, NULL); + *ci = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()}; + } else { + *ci += EULER + std::log(z); + } + return 0; + } + + // DLMF 6.5.5/6.5.6 plus DLMF 6.4.4/6.4.6/6.4.7 + std::complex jz = std::complex(0.0, 1.0) * z; + std::complex term1 = expi(jz); + std::complex term2 = expi(-jz); + *si = std::complex(0.0, -0.5)*(term1 - term2); + *ci = 0.5*(term1 + term2); + if (z.real() == 0) { + if (z.imag() > 0) { + *ci += std::complex(0.0, M_PI_2); + } else if (z.imag() < 0) { + *ci -= std::complex(0.0, M_PI_2); + } + } else if (z.real() > 0) { + *si -= M_PI_2; + } else { + *si += M_PI_2; + if (z.imag() >= 0) { + *ci += std::complex(0.0, M_PI); + } else { + *ci -= std::complex(0.0, M_PI); + } + } + return 0; +} + +XSF_HOST_DEVICE inline int sici(std::complex z, + std::complex *si_f, std::complex *ci_f) { + std::complex si; + std::complex ci; + int res = sici(z, &si, &ci); + *si_f = si; + *ci_f = ci; + return res; +} + +XSF_HOST_DEVICE inline int shichi(std::complex z, + std::complex *shi, std::complex *chi) { + /* Compute sinh/cosh integrals at complex arguments. The algorithm + * largely follows that of [1]. + */ + constexpr double EULER = xsf::cephes::detail::SCIPY_EULER; + if (z == std::numeric_limits::infinity()) { + *shi = std::numeric_limits::infinity(); + *chi = std::numeric_limits::infinity(); + return 0; + } + if (z == -std::numeric_limits::infinity()) { + *shi = -std::numeric_limits::infinity(); + *chi = std::numeric_limits::infinity(); + return 0; + } + if (std::abs(z) < 0.8) { + // Use the series to avoid cancellation in shi + detail::sici_power_series(1, z, shi, chi); + if (z == 0.0) { + set_error("shichi", SF_ERROR_DOMAIN, NULL); + *chi = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()}; + } else { + *chi += EULER + std::log(z); + } + return 0; + } + + std::complex term1 = expi(z); + std::complex term2 = expi(-z); + *shi = 0.5*(term1 - term2); + *chi = 0.5*(term1 + term2); + if (z.imag() > 0) { + *shi -= std::complex(0.0, 0.5*M_PI); + *chi += std::complex(0.0, 0.5*M_PI); + } else if (z.imag() < 0) { + *shi += std::complex(0.0, 0.5*M_PI); + *chi -= std::complex(0.0, 0.5*M_PI); + } else if (z.real() < 0) { + *chi += std::complex(0.0, M_PI); + } + return 0; +} + +XSF_HOST_DEVICE inline int shichi(std::complex z, + std::complex *shi_f, std::complex *chi_f) { + std::complex shi; + std::complex chi; + int res = shichi(z, &shi, &chi); + *shi_f = shi; + *chi_f = chi; + return res; +} + +XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) { + return cephes::sici(x, si, ci); +} + +XSF_HOST_DEVICE inline int shichi(double x, double *shi, double *chi) { + return cephes::shichi(x, shi, chi); +} + +XSF_HOST_DEVICE inline int sici(float x, float *si_f, float *ci_f) { + double si; + double ci; + int res = cephes::sici(x, &si, &ci); + *si_f = si; + *ci_f = ci; + return res; +} + +XSF_HOST_DEVICE inline int shichi(float x, float *shi_f, float *chi_f) { + double shi; + double chi; + int res = cephes::shichi(x, &shi, &chi); + *shi_f = shi; + *chi_f = chi; + return res; +} +} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h new file mode 100644 index 0000000000000000000000000000000000000000..e349f6a5fb4f45b4718cb746dd7b0b2c1fd23ddd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h @@ -0,0 +1,427 @@ +/* Building blocks for implementing special functions */ + +#pragma once + +#include "config.h" +#include "error.h" + +namespace xsf { +namespace detail { + + /* Result type of a "generator", a callable object that produces a value + * each time it is called. + */ + template + using generator_result_t = typename std::decay::type>::type; + + /* Used to deduce the type of the numerator/denominator of a fraction. */ + template + struct pair_traits; + + template + struct pair_traits> { + using value_type = T; + }; + + template + using pair_value_t = typename pair_traits::value_type; + + /* Used to extract the "value type" of a complex type. */ + template + struct real_type { + using type = T; + }; + + template + struct real_type> { + using type = T; + }; + + template + using real_type_t = typename real_type::type; + + // Return NaN, handling both real and complex types. + template + XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() { + return std::numeric_limits::quiet_NaN(); + } + + template + XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() { + using V = typename T::value_type; + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + + // Series evaluators. + template > + XSF_HOST_DEVICE T + series_eval(Generator &g, T init_val, real_type_t tol, std::uint64_t max_terms, const char *func_name) { + /* Sum an infinite series to a given precision. + * + * g : a generator of terms for the series. + * + * init_val : A starting value that terms are added to. This argument determines the + * type of the result. + * + * tol : relative tolerance for stopping criterion. + * + * max_terms : The maximum number of terms to add before giving up and declaring + * non-convergence. + * + * func_name : The name of the function within SciPy where this call to series_eval + * will ultimately be used. This is needed to pass to set_error in case + * of non-convergence. + */ + T result = init_val; + T term; + for (std::uint64_t i = 0; i < max_terms; ++i) { + term = g(); + result += term; + if (std::abs(term) < std::abs(result) * tol) { + return result; + } + } + // Exceeded max terms without converging. Return NaN. + set_error(func_name, SF_ERROR_NO_RESULT, NULL); + return maybe_complex_NaN(); + } + + template > + XSF_HOST_DEVICE T series_eval_fixed_length(Generator &g, T init_val, std::uint64_t num_terms) { + /* Sum a fixed number of terms from a series. + * + * g : a generator of terms for the series. + * + * init_val : A starting value that terms are added to. This argument determines the + * type of the result. + * + * max_terms : The number of terms from the series to sum. + * + */ + T result = init_val; + for (std::uint64_t i = 0; i < num_terms; ++i) { + result += g(); + } + return result; + } + + /* Performs one step of Kahan summation. */ + template + XSF_HOST_DEVICE void kahan_step(T &sum, T &comp, T x) { + T y = x - comp; + T t = sum + y; + comp = (t - sum) - y; + sum = t; + } + + /* Evaluates an infinite series using Kahan summation. + * + * Denote the series by + * + * S = a[0] + a[1] + a[2] + ... + * + * And for n = 0, 1, 2, ..., denote its n-th partial sum by + * + * S[n] = a[0] + a[1] + ... + a[n] + * + * This function computes S[0], S[1], ... until a[n] is sufficiently + * small or if the maximum number of terms have been evaluated. + * + * Parameters + * ---------- + * g + * Reference to generator that yields the sequence of values a[1], + * a[2], a[3], ... + * + * tol + * Relative tolerance for convergence. Specifically, stop iteration + * as soon as `abs(a[n]) <= tol * abs(S[n])` for some n >= 1. + * + * max_terms + * Maximum number of terms after a[0] to evaluate. It should be set + * large enough such that the convergence criterion is guaranteed + * to have been satisfied within that many terms if there is no + * rounding error. + * + * init_val + * a[0]. Default is zero. The type of this parameter (T) is used + * for intermediary computations as well as the result. + * + * Return Value + * ------------ + * If the convergence criterion is satisfied by some `n <= max_terms`, + * returns `(S[n], n)`. Otherwise, returns `(S[max_terms], 0)`. + */ + template > + XSF_HOST_DEVICE std::pair + series_eval_kahan(Generator &&g, real_type_t tol, std::uint64_t max_terms, T init_val = T(0)) { + + using std::abs; + T sum = init_val; + T comp = T(0); + for (std::uint64_t i = 0; i < max_terms; ++i) { + T term = g(); + kahan_step(sum, comp, term); + if (abs(term) <= tol * abs(sum)) { + return {sum, i + 1}; + } + } + return {sum, 0}; + } + + /* Generator that yields the difference of successive convergents of a + * continued fraction. + * + * Let f[n] denote the n-th convergent of a continued fraction: + * + * a[1] a[2] a[n] + * f[n] = b[0] + ------ ------ ... ---- + * b[1] + b[2] + b[n] + * + * with f[0] = b[0]. This generator yields the sequence of values + * f[1]-f[0], f[2]-f[1], f[3]-f[2], ... + * + * Constructor Arguments + * --------------------- + * cf + * Reference to generator that yields the terms of the continued + * fraction as (numerator, denominator) pairs, starting from + * (a[1], b[1]). + * + * `cf` must outlive the ContinuedFractionSeriesGenerator object. + * + * The constructed object always eagerly retrieves the next term + * of the continued fraction. Specifically, (a[1], b[1]) is + * retrieved upon construction, and (a[n], b[n]) is retrieved after + * (n-1) calls of `()`. + * + * Type Arguments + * -------------- + * T + * Type in which computations are performed and results are turned. + * + * Remarks + * ------- + * The series is computed using the recurrence relation described in [1]. + * Let v[n], n >= 1 denote the terms of the series. Then + * + * v[1] = a[1] / b[1] + * v[n] = v[n-1] * r[n-1], n >= 2 + * + * where + * + * -(a[n] + a[n] * r[n-1]) + * r[1] = 0, r[n] = ------------------------------------------, n >= 2 + * (a[n] + a[n] * r[n-1]) + (b[n] * b[n-1]) + * + * No error checking is performed. The caller must ensure that all terms + * are finite and that intermediary computations do not trigger floating + * point exceptions such as overflow. + * + * The numerical stability of this method depends on the characteristics + * of the continued fraction being evaluated. + * + * Reference + * --------- + * [1] Gautschi, W. (1967). “Computational Aspects of Three-Term + * Recurrence Relations.” SIAM Review, 9(1):24-82. + */ + template >> + class ContinuedFractionSeriesGenerator { + + public: + XSF_HOST_DEVICE explicit ContinuedFractionSeriesGenerator(Generator &cf) : cf_(cf) { init(); } + + XSF_HOST_DEVICE T operator()() { + T v = v_; + advance(); + return v; + } + + private: + XSF_HOST_DEVICE void init() { + auto [num, denom] = cf_(); + T a = num; + T b = denom; + r_ = T(0); + v_ = a / b; + b_ = b; + } + + XSF_HOST_DEVICE void advance() { + auto [num, denom] = cf_(); + T a = num; + T b = denom; + T p = a + a * r_; + T q = p + b * b_; + r_ = -p / q; + v_ = v_ * r_; + b_ = b; + } + + Generator &cf_; // reference to continued fraction generator + T v_; // v[n] == f[n] - f[n-1], n >= 1 + T r_; // r[1] = 0, r[n] = v[n]/v[n-1], n >= 2 + T b_; // last denominator, i.e. b[n-1] + }; + + /* Converts a continued fraction into a series whose terms are the + * difference of its successive convergents. + * + * See ContinuedFractionSeriesGenerator for details. + */ + template >> + XSF_HOST_DEVICE ContinuedFractionSeriesGenerator continued_fraction_series(Generator &cf) { + return ContinuedFractionSeriesGenerator(cf); + } + + /* Find initial bracket for a bracketing scalar root finder. A valid bracket is a pair of points a < b for + * which the signs of f(a) and f(b) differ. If f(x0) = 0, where x0 is the initial guess, this bracket finder + * will return the bracket (x0, x0). It is expected that the rootfinder will check if the bracket + * endpoints are roots. + * + * This is a private function intended specifically for the situation where + * the goal is to invert a CDF function F for a parametrized family of distributions with respect to one + * parameter, when the other parameters are known, and where F is monotonic with respect to the unknown parameter. + */ + template + XSF_HOST_DEVICE inline std::tuple bracket_root_for_cdf_inversion( + Function func, double x0, double xmin, double xmax, double step0_left, + double step0_right, double factor_left, double factor_right, bool increasing, std::uint64_t maxiter + ) { + double y0 = func(x0); + + if (y0 == 0) { + // Initial guess is correct. + return {x0, x0, y0, y0, 0}; + } + + double y0_sgn = std::signbit(y0); + + bool search_left; + /* The frontier is the new leading endpoint of the expanding bracket. The + * interior endpoint trails behind the frontier. In each step, the old frontier + * endpoint becomes the new interior endpoint. */ + double interior, frontier, y_interior, y_frontier, y_interior_sgn, y_frontier_sgn, boundary, factor; + if ((increasing && y0 < 0) || (!increasing && y0 > 0)) { + /* If func is increasing and func(x_right) < 0 or if func is decreasing and + * f(y_right) > 0, we should expand the bracket to the right. */ + interior = x0, y_interior = y0; + frontier = x0 + step0_right; + y_interior_sgn = y0_sgn; + search_left = false; + boundary = xmax; + factor = factor_right; + } else { + /* Otherwise we move and expand the bracket to the left. */ + interior = x0, y_interior = y0; + frontier = x0 + step0_left; + y_interior_sgn = y0_sgn; + search_left = true; + boundary = xmin; + factor = factor_left; + } + + bool reached_boundary = false; + for (std::uint64_t i = 0; i < maxiter; i++) { + y_frontier = func(frontier); + y_frontier_sgn = std::signbit(y_frontier); + if (y_frontier_sgn != y_interior_sgn || (y_frontier == 0.0)) { + /* Stopping condition, func evaluated at endpoints of bracket has opposing signs, + * meeting requirement for bracketing root finder. (Or endpoint has reached a + * zero.) */ + if (search_left) { + /* Ensure we return an interval (a, b) with a < b. */ + std::swap(interior, frontier); + std::swap(y_interior, y_frontier); + } + return {interior, frontier, y_interior, y_frontier, 0}; + } + if (reached_boundary) { + /* We've reached a boundary point without finding a root . */ + return { + std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), + search_left ? 1 : 2 + }; + } + double step = (frontier - interior) * factor; + interior = frontier; + y_interior = y_frontier; + y_interior_sgn = y_frontier_sgn; + frontier += step; + if ((search_left && frontier <= boundary) || (!search_left && frontier >= boundary)) { + /* If the frontier has reached the boundary, set a flag so the algorithm will know + * not to search beyond this point. */ + frontier = boundary; + reached_boundary = true; + } + } + /* Failed to converge within maxiter iterations. If maxiter is sufficiently high and + * factor_left and factor_right are set appropriately, this should only happen due to + * a bug in this function. Limiting the number of iterations is a defensive programming measure. */ + return { + std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), 3 + }; + } + + /* Find root of a scalar function using Chandrupatla's algorithm */ + template + XSF_HOST_DEVICE inline std::pair find_root_chandrupatla( + Function func, double x1, double x2, double f1, double f2, double rtol, + double atol, std::uint64_t maxiter + ) { + if (f1 == 0) { + return {x1, 0}; + } + if (f2 == 0) { + return {x2, 0}; + } + double t = 0.5, x3, f3; + for (uint64_t i = 0; i < maxiter; i++) { + double x = x1 + t * (x2 - x1); + double f = func(x); + if (std::signbit(f) == std::signbit(f1)) { + x3 = x1; + x1 = x; + f3 = f1; + f1 = f; + } else { + x3 = x2; + x2 = x1; + x1 = x; + f3 = f2; + f2 = f1; + f1 = f; + } + double xm, fm; + if (std::abs(f2) < std::abs(f1)) { + xm = x2; + fm = f2; + } else { + xm = x1; + fm = f1; + } + double tol = 2.0 * rtol * std::abs(xm) + 0.5 * atol; + double tl = tol / std::abs(x2 - x1); + if (tl > 0.5 || fm == 0) { + return {xm, 0}; + } + double xi = (x1 - x2) / (x3 - x2); + double phi = (f1 - f2) / (f3 - f2); + double fl = 1.0 - std::sqrt(1.0 - xi); + double fh = std::sqrt(xi); + + if ((fl < phi) && (phi < fh)) { + t = (f1 / (f2 - f1)) * (f3 / (f2 - f3)) + (f1 / (f3 - f1)) * (f2 / (f3 - f2)) * ((x3 - x1) / (x2 - x1)); + } else { + t = 0.5; + } + t = std::fmin(std::fmax(t, tl), 1.0 - tl); + } + return {std::numeric_limits::quiet_NaN(), 1}; + } + +} // namespace detail +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h new file mode 100644 index 0000000000000000000000000000000000000000..a0221e00bbe358519c1586eb539310a5be6cddd1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h @@ -0,0 +1,164 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * + * Original author: Josh Wilson, 2016. + */ + +/* Implement sin(pi*z) and cos(pi*z) for complex z. Since the periods + * of these functions are integral (and thus better representable in + * floating point), it's possible to compute them with greater accuracy + * than sin(z), cos(z). + */ + +#pragma once + +#include "cephes/sindg.h" +#include "cephes/tandg.h" +#include "cephes/trig.h" +#include "cephes/unity.h" +#include "config.h" +#include "evalpoly.h" + +namespace xsf { + +template +XSF_HOST_DEVICE T sinpi(T x) { + return cephes::sinpi(x); +} + +template +XSF_HOST_DEVICE std::complex sinpi(std::complex z) { + T x = z.real(); + T piy = M_PI * z.imag(); + T abspiy = std::abs(piy); + T sinpix = cephes::sinpi(x); + T cospix = cephes::cospi(x); + + if (abspiy < 700) { + return {sinpix * std::cosh(piy), cospix * std::sinh(piy)}; + } + + /* Have to be careful--sinh/cosh could overflow while cos/sin are small. + * At this large of values + * + * cosh(y) ~ exp(y)/2 + * sinh(y) ~ sgn(y)*exp(y)/2 + * + * so we can compute exp(y/2), scale by the right factor of sin/cos + * and then multiply by exp(y/2) to avoid overflow. */ + T exphpiy = std::exp(abspiy / 2); + T coshfac; + T sinhfac; + if (exphpiy == std::numeric_limits::infinity()) { + if (sinpix == 0.0) { + // Preserve the sign of zero. + coshfac = std::copysign(0.0, sinpix); + } else { + coshfac = std::copysign(std::numeric_limits::infinity(), sinpix); + } + if (cospix == 0.0) { + // Preserve the sign of zero. + sinhfac = std::copysign(0.0, cospix); + } else { + sinhfac = std::copysign(std::numeric_limits::infinity(), cospix); + } + return {coshfac, sinhfac}; + } + + coshfac = 0.5 * sinpix * exphpiy; + sinhfac = 0.5 * cospix * exphpiy; + return {coshfac * exphpiy, sinhfac * exphpiy}; +} + +template +XSF_HOST_DEVICE T cospi(T x) { + return cephes::cospi(x); +} + +template +XSF_HOST_DEVICE std::complex cospi(std::complex z) { + T x = z.real(); + T piy = M_PI * z.imag(); + T abspiy = std::abs(piy); + T sinpix = cephes::sinpi(x); + T cospix = cephes::cospi(x); + + if (abspiy < 700) { + return {cospix * std::cosh(piy), -sinpix * std::sinh(piy)}; + } + + // See csinpi(z) for an idea of what's going on here. + T exphpiy = std::exp(abspiy / 2); + T coshfac; + T sinhfac; + if (exphpiy == std::numeric_limits::infinity()) { + if (sinpix == 0.0) { + // Preserve the sign of zero. + coshfac = std::copysign(0.0, cospix); + } else { + coshfac = std::copysign(std::numeric_limits::infinity(), cospix); + } + if (cospix == 0.0) { + // Preserve the sign of zero. + sinhfac = std::copysign(0.0, sinpix); + } else { + sinhfac = std::copysign(std::numeric_limits::infinity(), sinpix); + } + return {coshfac, sinhfac}; + } + + coshfac = 0.5 * cospix * exphpiy; + sinhfac = 0.5 * sinpix * exphpiy; + return {coshfac * exphpiy, sinhfac * exphpiy}; +} + +template +XSF_HOST_DEVICE T sindg(T x) { + return cephes::sindg(x); +} + +template <> +XSF_HOST_DEVICE inline float sindg(float x) { + return sindg(static_cast(x)); +} + +template +XSF_HOST_DEVICE T cosdg(T x) { + return cephes::cosdg(x); +} + +template <> +XSF_HOST_DEVICE inline float cosdg(float x) { + return cosdg(static_cast(x)); +} + +template +XSF_HOST_DEVICE T tandg(T x) { + return cephes::tandg(x); +} + +template <> +XSF_HOST_DEVICE inline float tandg(float x) { + return tandg(static_cast(x)); +} + +template +XSF_HOST_DEVICE T cotdg(T x) { + return cephes::cotdg(x); +} + +template <> +XSF_HOST_DEVICE inline float cotdg(float x) { + return cotdg(static_cast(x)); +} + +inline double radian(double d, double m, double s) { return cephes::radian(d, m, s); } + +inline float radian(float d, float m, float s) { + return radian(static_cast(d), static_cast(m), static_cast(s)); +} + +inline double cosm1(double x) { return cephes::cosm1(x); } + +inline float cosm1(float x) { return cosm1(static_cast(x)); } + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h new file mode 100644 index 0000000000000000000000000000000000000000..77cf165a0fc303a2ee425dff7083889908dcf887 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h @@ -0,0 +1,843 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * Original header with Copyright information appears below. + */ + +/* Implementation of Wright's generalized Bessel function Phi, see + * https://dlmf.nist.gov/10.46.E1 + * + * Copyright: Christian Lorentzen + * + * Distributed under the same license as SciPy + * + * + * Implementation Overview: + * + * First, different functions are implemented valid for certain domains of the + * three arguments. + * Finally they are put together in wright_bessel. See the docstring of + * that function for more details. + */ + +#pragma once + +#include "cephes/lanczos.h" +#include "cephes/polevl.h" +#include "cephes/rgamma.h" +#include "config.h" +#include "digamma.h" +#include "error.h" + +namespace xsf { + +namespace detail { + // rgamma_zero: smallest value x for which rgamma(x) == 0 as x gets large + constexpr double rgamma_zero = 178.47241115886637; + + XSF_HOST_DEVICE inline double exp_rgamma(double x, double y) { + /* Compute exp(x) / gamma(y) = exp(x) * rgamma(y). + * + * This helper function avoids overflow by using the lanczos + * approximation of the gamma function. + */ + return std::exp(x + (1 - std::log(y + cephes::lanczos_g - 0.5)) * (y - 0.5)) / + cephes::lanczos_sum_expg_scaled(y); + } + + XSF_HOST_DEVICE inline double wb_series(double a, double b, double x, unsigned int nstart, unsigned int nstop) { + /* 1. Taylor series expansion in x=0 for x <= 1. + * + * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b) + * + * Note that every term, and therefore also Phi(a, b, x) is + * monotone decreasing with increasing a or b. + */ + double xk_k = std::pow(x, nstart) * cephes::rgamma(nstart + 1); // x^k/k! + double res = xk_k * cephes::rgamma(nstart * a + b); + // term k=nstart+1, +2, +3, ... + if (nstop > nstart) { + // series expansion until term k such that a*k+b <= rgamma_zero + unsigned int k_max = std::floor((rgamma_zero - b) / a); + if (nstop > k_max) { + nstop = k_max; + } + for (unsigned int k = nstart + 1; k < nstop; k++) { + xk_k *= x / k; + res += xk_k * cephes::rgamma(a * k + b); + } + } + return res; + } + + template + XSF_HOST_DEVICE inline double wb_large_a(double a, double b, double x, int n) { + /* 2. Taylor series expansion in x=0, for large a. + * + * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b) + * + * Use Stirling's formula to find k=k_max, the maximum term. + * Then use n terms of Taylor series around k_max. + */ + int k_max = static_cast(std::pow(std::pow(a, -a) * x, 1.0 / (1 + a))); + + int nstart = k_max - n / 2; + if (nstart < 0) { + nstart = 0; + } + + double res = 0; + double lnx = std::log(x); + // For numerical stability, we factor out the maximum term exp(..) with k=k_max + // but only if it is larger than 0. + double max_exponent = std::fmax(0, k_max * lnx - cephes::lgam(k_max + 1) - cephes::lgam(a * k_max + b)); + for (int k = nstart; k < nstart + n; k++) { + res += std::exp(k * lnx - cephes::lgam(k + 1) - cephes::lgam(a * k + b) - max_exponent); + } + + if (!log_wb) { + res *= std::exp(max_exponent); + } else { + // logarithm of Wright's function + res = max_exponent + std::log(res); + } + return res; + } + + template + XSF_HOST_DEVICE inline double wb_small_a(double a, double b, double x, int order) { + /* 3. Taylor series in a=0 up to order 5, for tiny a and not too large x + * + * Phi(a, b, x) = exp(x)/Gamma(b) + * (1 - a*x * Psi(b) + a^2/2*x*(1+x) * (Psi(b)^2 - Psi'(b) + + ... ) + + O(a^6)) + * + * where Psi is the digamma function. + * + * Parameter order takes effect only when b > 1e-3 and 2 <= order <= 5, + * otherwise it defaults to 2, or if b <= 1e-3, to 5. The lower order is, + * the fewer polygamma functions have to be computed. + * + * Call: python _precompute/wright_bessel.py 1 + * + * For small b, i.e. b <= 1e-3, cancellation of poles of digamma(b)/Gamma(b) + * and polygamma needs to be carried out => series expansion in a=0 to order 5 + * and in b=0 to order 4. + * Call: python _precompute/wright_bessel.py 2 + */ + double A[6]; // coefficients of a^k (1, -x * Psi(b), ...) + double B[6]; // powers of b^k/k! or terms in polygamma functions + constexpr double C[5] = { // coefficients of a^k1 * b^k2 + 1.0000000000000000, // C[0] + 1.1544313298030657, // C[1] + -3.9352684291215233, // C[2] + -1.0080632408182857, // C[3] + 19.984633365874979, // C[4] + }; + double X[6] = { // polynomials in x; + 1, // X[0] + x, // X[1] + x * (x + 1), // X[2] + x * (x * (x + 3) + 1), // X[3] + x * (x * (x * (x + 6) + 7) + 1), // X[4] + x * (x * (x * (x * (x + 10) + 25) + 15) + 1), // X[5] + }; + double res; + + if (b <= 1E-3) { + /* Series expansion of both a and b up to order 5: + * M_PI = pi + * M_EG = Euler Gamma aka Euler Mascheroni constant + * M_Z3 = zeta(3) + * C[0] = 1 + * C[1] = 2*M_EG + * C[2] = 3*M_EG^2 - M_PI^2/2 + * C[3] = 4*M_EG^3 - 2*M_EG*M_PI^2 + 8*M_Z3 + * C[4] = 5*M_EG^4 - 5*M_EG^2*M_PI^2 + 40*M_EG*M_Z3 + M_PI^4/12 + */ + B[0] = 1.; + for (int k = 1; k < 5; k++) { + B[k] = b / k * B[k - 1]; + } + // Note that polevl assumes inverse ordering => A[5] = 0th term + A[5] = cephes::rgamma(b); + A[4] = X[1] * (C[0] + C[1] * b + C[2] * B[2] + C[3] * B[3] + C[4] * B[4]); + A[3] = X[2] / 2. * (C[1] + C[2] * b + C[3] * B[2] + C[4] * B[3]); + A[2] = X[3] / 6. * (C[2] + C[3] * b + C[4] * B[2]); + A[1] = X[4] / 24. * (C[3] + C[4] * b); + A[0] = X[5] / 120. * C[4]; + // res = exp(x) * (A[5] + A[4] * a + A[3] * a^2 + A[2] * a^3 + ...) + if (!log_wb) { + res = exp(x) * cephes::polevl(a, A, 5); + } else { + // logarithm of Wright's function + res = x + std::log(cephes::polevl(a, A, 5)); + } + } else { + /* Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5) + * A[n] = a^n/n! + * But here, we repurpose A[n] = X[n] * B[n] / n! + * Note that polevl assumes inverse ordering => A[order] = 0th term */ + double dg = digamma(b); + // pg1 = polygamma(1, b) + double pg1 = cephes::zeta(2, b); + if (order <= 2) { + res = 1 + a * x * (-dg + 0.5 * a * (1 + x) * (dg * dg - pg1)); + } else { + if (order > 5) { + order = 5; + } + // pg2 = polygamma(2, b) + double pg2 = -2 * cephes::zeta(3, b); + B[0] = 1; + B[1] = -dg; + B[2] = dg * dg - pg1; + B[3] = (-dg * dg + 3 * pg1) * dg - pg2; + A[order] = 1; + A[order - 1] = X[1] * B[1]; + A[order - 2] = X[2] * B[2] / 2.; + A[order - 3] = X[3] * B[3] / 6.; + if (order >= 4) { + // double pg3 = polygamma(3, b) + double pg3 = 6 * cephes::zeta(4, b); + B[4] = ((dg * dg - 6 * pg1) * dg + 4 * pg2) * dg + 3 * pg1 * pg1 - pg3; + A[order - 4] = X[4] * B[4] / 24.; + if (order >= 5) { + // pg4 = polygamma(4, b) + double pg4 = -24 * cephes::zeta(5, b); + B[5] = + ((((-dg * dg + 10 * pg1) * dg - 10 * pg2) * dg - 15 * pg1 * pg1 + 5 * pg3) * dg + + 10 * pg1 * pg2 - pg4); + A[order - 5] = X[5] * B[5] / 120.; + } + } + res = cephes::polevl(a, A, order); + } + // res *= exp(x) * rgamma(b) + if (!log_wb) { + res *= exp_rgamma(x, b); + } else { + // logarithm of Wright's function + res = x - cephes::lgam(b) + std::log(res); + } + } + return res; + } + + template + XSF_HOST_DEVICE inline double wb_asymptotic(double a, double b, double x) { + /* 4. Asymptotic expansion for large x up to order 8 + * + * Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k + * + * with Z = (a*x)^(1/(1+a)). + * Call: python _precompute/wright_bessel.py 3 + */ + double A[15]; // powers of a + double B[17]; // powers of b + double Ap1[9]; // powers of (1+a) + double C[9]; // coefficients of asymptotic series a_k + + A[0] = 1.; + B[0] = 1.; + Ap1[0] = 1.; + for (int k = 1; k < 15; k++) { + A[k] = A[k - 1] * a; + } + for (int k = 1; k < 17; k++) { + B[k] = B[k - 1] * b; + } + for (int k = 1; k < 9; k++) { + Ap1[k] = Ap1[k - 1] * (1 + a); + } + + C[0] = 1. / std::sqrt(2. * M_PI * Ap1[1]); + + C[1] = C[0] / (24 * Ap1[1]); + C[1] *= (2 * a + 1) * (2 + a) - 12 * b * (1 + a - b); + + C[2] = C[0] / (1152 * Ap1[2]); + C[2] *= + (144 * B[4] - 96 * B[3] * (5 * a + 1) + 24 * B[2] * (20 * A[2] + 5 * a - 4) - + 24 * b * Ap1[1] * (6 * A[2] - 7 * a - 2) + (a + 2) * (2 * a + 1) * (2 * A[2] - 19 * a + 2)); + + C[3] = C[0] / (414720 * Ap1[3]); + C[3] *= + (8640 * B[6] - 8640 * B[5] * (7 * a - 1) + 10800 * B[4] * (14 * A[2] - 7 * a - 2) - + 1440 * B[3] * (112 * A[3] - 147 * A[2] - 63 * a + 8) + + 180 * B[2] * (364 * A[4] - 1288 * A[3] - 567 * A[2] + 392 * a + 76) - + 180 * b * Ap1[1] * (20 * A[4] - 516 * A[3] + 417 * A[2] + 172 * a - 12) - + (a + 2) * (2 * a + 1) * (556 * A[4] + 1628 * A[3] - 9093 * A[2] + 1628 * a + 556)); + + C[4] = C[0] / (39813120 * Ap1[4]); + C[4] *= + (103680 * B[8] - 414720 * B[7] * (3 * a - 1) + 725760 * B[6] * a * (8 * a - 7) - + 48384 * B[5] * (274 * A[3] - 489 * A[2] + 39 * a + 26) + + 30240 * B[4] * (500 * A[4] - 1740 * A[3] + 495 * A[2] + 340 * a - 12) - + 2880 * B[3] * (2588 * A[5] - 19780 * A[4] + 14453 * A[3] + 9697 * A[2] - 1892 * a - 404) + + 48 * B[2] * + (11488 * A[6] - 547836 * A[5] + 1007484 * A[4] + 593353 * A[3] - 411276 * A[2] - 114396 * a + 4288) + + 48 * b * Ap1[1] * + (7784 * A[6] + 48180 * A[5] - 491202 * A[4] + 336347 * A[3] + 163734 * A[2] - 28908 * a - 5560) - + (a + 2) * (2 * a + 1) * + (4568 * A[6] - 226668 * A[5] - 465702 * A[4] + 2013479 * A[3] - 465702 * A[2] - 226668 * a + 4568)); + + C[5] = C[0] / (6688604160. * Ap1[5]); + C[5] *= + (1741824 * B[10] - 2903040 * B[9] * (11 * a - 5) + 2177280 * B[8] * (110 * A[2] - 121 * a + 14) - + 580608 * B[7] * (1628 * A[3] - 3333 * A[2] + 1023 * a + 52) + + 169344 * B[6] * (12364 * A[4] - 43648 * A[3] + 26763 * A[2] + 1232 * a - 788) - + 24192 * B[5] * (104852 * A[5] - 646624 * A[4] + 721391 * A[3] - 16841 * A[2] - 74096 * a + 148) + + 2016 * B[4] * + (710248 * A[6] - 8878716 * A[5] + 17928834 * A[4] - 3333407 * A[3] - 4339566 * A[2] + 287364 * a + + 89128) - + 1344 * B[3] * + (87824 * A[7] - 7150220 * A[6] + 29202756 * A[5] - 15113527 * A[4] - 14223011 * A[3] + 3462492 * A[2] + + 1137092 * a - 18896) - + 84 * B[2] * + (1690480 * A[8] + 14139136 * A[7] - 232575464 * A[6] + 296712592 * A[5] + 215856619 * A[4] - + 152181392 * A[3] - 47718440 * A[2] + 5813632 * a + 943216) + + 84 * b * Ap1[1] * + (82224 * A[8] - 5628896 * A[7] - 26466520 * A[6] + 168779208 * A[5] - 104808005 * A[4] - + 56259736 * A[3] + 15879912 * A[2] + 4020640 * a - 63952) + + (a + 2) * (2 * a + 1) * + (2622064 * A[8] + 12598624 * A[7] - 167685080 * A[6] - 302008904 * A[5] + 1115235367. * A[4] - + 302008904 * A[3] - 167685080 * A[2] + 12598624 * a + 2622064)); + + C[6] = C[0] / (4815794995200. * Ap1[6]); + C[6] *= + (104509440 * B[12] - 209018880 * B[11] * (13 * a - 7) + 574801920 * B[10] * (52 * A[2] - 65 * a + 12) - + 63866880 * B[9] * (2834 * A[3] - 6279 * A[2] + 2769 * a - 134) + + 23950080 * B[8] * (27404 * A[4] - 98228 * A[3] + 78663 * A[2] - 10868 * a - 1012) - + 13685760 * B[7] * (105612 * A[5] - 599196 * A[4] + 791843 * A[3] - 224913 * A[2] - 27612 * a + 4540) + + 2661120 * B[6] * + (693680 * A[6] - 6473532 * A[5] + 13736424 * A[4] - 7047469 * A[3] - 723840 * A[2] + 471588 * a + 7376 + ) - + 2661120 * B[5] * + (432536 * A[7] - 7850804 * A[6] + 27531114 * A[5] - 24234457 * A[4] - 703001 * A[3] + 3633474 * A[2] - + 36244 * a - 45128) + + 166320 * B[4] * + (548912 * A[8] - 75660832 * A[7] + 502902712 * A[6] - 764807992 * A[5] + 91248287 * A[4] + + 217811464 * A[3] - 20365384 * A[2] - 9776416 * a + 37936) + + 10080 * B[3] * + (18759728 * A[9] + 165932208 * A[8] - 4710418440. * A[7] + 13686052536. * A[6] - 5456818809. * A[5] - + 6834514245. * A[4] + 1919299512. * A[3] + 752176152 * A[2] - 45661200 * a - 8616848) - + 360 * B[2] * + (32743360 * A[10] - 3381871792. * A[9] - 21488827776. * A[8] + 200389923864. * A[7] - + 198708005340. * A[6] - 171633799779. * A[5] + 123124874028. * A[4] + 40072774872. * A[3] - + 9137993280. * A[2] - 1895843248. * a + 18929728) - + 360 * b * Ap1[1] * + (57685408 * A[10] + 406929456 * A[9] - 6125375760. * A[8] - 27094918920. * A[7] + + 128752249410. * A[6] - 74866710561. * A[5] - 42917416470. * A[4] + 16256951352. * A[3] + + 4375268400. * A[2] - 316500688 * a - 47197152) + + (a + 2) * (2 * a + 1) * + (167898208 * A[10] - 22774946512. * A[9] - 88280004528. * A[8] + 611863976472. * A[7] + + 1041430242126. * A[6] - 3446851131657. * A[5] + 1041430242126. * A[4] + 611863976472. * A[3] - + 88280004528. * A[2] - 22774946512. * a + 167898208)); + + C[7] = C[0] / (115579079884800. * Ap1[7]); + C[7] *= + (179159040 * B[14] - 1254113280. * B[13] * (5 * a - 3) + 1358622720. * B[12] * (70 * A[2] - 95 * a + 22) - + 905748480 * B[11] * (904 * A[3] - 2109 * A[2] + 1119 * a - 112) + + 1245404160. * B[10] * (3532 * A[4] - 12824 * A[3] + 11829 * A[2] - 2824 * a + 44) - + 59304960 * B[9] * (256820 * A[5] - 1397680 * A[4] + 2025545 * A[3] - 869495 * A[2] + 52000 * a + 8788) + + 14826240 * B[8] * + (2274536 * A[6] - 18601572 * A[5] + 40698318 * A[4] - 28230079 * A[3] + 3916398 * A[2] + 832668 * a - + 65176) - + 59304960 * B[7] * + (760224 * A[7] - 9849164 * A[6] + 32495784 * A[5] - 34813869 * A[4] + 9175207 * A[3] + 1898688 * A[2] - + 469788 * a - 13184) + + 25945920 * B[6] * + (1167504 * A[8] - 28779840 * A[7] + 149752856 * A[6] - 246026112 * A[5] + 111944073 * A[4] + + 18341600 * A[3] - 12131496 * A[2] - 274368 * a + 102800) - + 157248 * B[5] * + (12341872 * A[9] - 3122991216. * A[8] + 29900054232. * A[7] - 78024816720. * A[6] + + 58914656739. * A[5] + 4637150811. * A[4] - 11523402480. * A[3] + 236218968 * A[2] + 337923216 * a + + 1592048) - + 28080 * B[4] * + (265154912 * A[10] + 2276098704. * A[9] - 105569461008. * A[8] + 496560666360. * A[7] - + 627891462858. * A[6] + 41935358025. * A[5] + 203913875814. * A[4] - 23984801544. * A[3] - + 13869306000. * A[2] + 372786832 * a + 103532640) + + 1440 * B[3] * + (310292864 * A[11] - 55169117872. * A[10] - 358957020112. * A[9] + 5714152556088. * A[8] - + 13241597459352. * A[7] + 4220720097141. * A[6] + 6845418090249. * A[5] - 2129559215808. * A[4] - + 909225098472. * A[3] + 107518582576. * A[2] + 25619444368. * a - 113832704) + + 12 * B[2] * + (135319651136. * A[12] + 1119107842176. * A[11] - 22193518174320. * A[10] - 133421793595520. * A[9] + + 860103051087996. * A[8] - 703353374803080. * A[7] - 704240127687381. * A[6] + + 513111704637960. * A[5] + 166909061348316. * A[4] - 57671564069120. * A[3] - 12453426246000. * A[2] + + 695901207936. * a + 93786157376.) - + 12 * b * Ap1[1] * + (4365353408. * A[12] - 720248637504. * A[11] - 4222331152560. * A[10] + 29413934270560. * A[9] + + 132123980710980. * A[8] - 511247376962820. * A[7] + 283403639131779. * A[6] + + 170415792320940. * A[5] - 79274388426588. * A[4] - 21009953050400. * A[3] + 3284035340880. * A[2] + + 589294339776. * a - 3693760576.) - + (a + 2) * (2 * a + 1) * + (34221025984. * A[12] + 226022948160. * A[11] - 5067505612464. * A[10] - 18868361443936. * A[9] + + 86215425028308. * A[8] + 143500920544692. * A[7] - 437682618704613. * A[6] + 143500920544692. * A[5] + + 86215425028308. * A[4] - 18868361443936. * A[3] - 5067505612464. * A[2] + 226022948160. * a + + 34221025984.)); + + C[8] = C[0] / (22191183337881600. * Ap1[8]); + C[8] *= + (2149908480. * B[16] - 5733089280. * B[15] * (17 * a - 11) + + 7166361600. * B[14] * (272 * A[2] - 391 * a + 104) - + 3344302080. * B[13] * (6766 * A[3] - 16371 * A[2] + 9741 * a - 1306) + + 1811496960. * B[12] * (93092 * A[4] - 341564 * A[3] + 344199 * A[2] - 104924 * a + 6308) - + 517570560 * B[11] * + (1626220 * A[5] - 8641508 * A[4] + 13274773 * A[3] - 6952303 * A[2] + 1007420 * a + 5564) + + 284663808 * B[10] * + (9979136 * A[6] - 75766892 * A[5] + 169256148 * A[4] - 136824959 * A[3] + 35714348 * A[2] - + 463692 * a - 293664) - + 1423319040. * B[9] * + (4466648 * A[7] - 49231116 * A[6] + 157507414 * A[5] - 187114257 * A[4] + 78372295 * A[3] - + 4470082 * A[2] - 1913996 * a + 82424) + + 266872320 * B[8] * + (33133136 * A[8] - 564264544 * A[7] + 2618606424. * A[6] - 4491310104. * A[5] + 2853943765. * A[4] - + 374694552 * A[3] - 135365288 * A[2] + 17623968 * a + 696912) - + 2156544 * B[7] * + (2914256144. * A[9] - 93491712432. * A[8] + 664876176984. * A[7] - 1661362937880. * A[6] + + 1563719627313. * A[5] - 382840842843. * A[4] - 115399415640. * A[3] + 34565562936. * A[2] + + 1609337232. * a - 217321904) + + 179712 * B[6] * + (1266018560. * A[10] - 789261834512. * A[9] + 10186841596896. * A[8] - 38877799073352. * A[7] + + 54334425968952. * A[6] - 22529574889533. * A[5] - 5132942328000. * A[4] + 3438377465592. * A[3] + + 84287641248. * A[2] - 72493479440. * a - 807415936) + + 13824 * B[5] * + (156356794976. * A[11] + 1180898077328. * A[10] - 90615270907936. * A[9] + 609258947056248. * A[8] - + 1312655191366722. * A[7] + 885900509321745. * A[6] + 112162151855265. * A[5] - + 212803071513258. * A[4] + 6805217831352. * A[3] + 10051742651296. * A[2] - 55035924848. * a - + 52946379296.) - + 576 * B[4] * + (143943926464. * A[12] - 60115486481856. * A[11] - 376366989757200. * A[10] + + 9534223075576160. * A[9] - 35603777465262396. * A[8] + 39375990156664980. * A[7] - + 868175004137259. * A[6] - 14279180718355020. * A[5] + 1985747535239364. * A[4] + + 1264001337603680. * A[3] - 75972792514320. * A[2] - 23855850572736. * a - 4996648256.) - + 384 * B[3] * + (2038525473856. * A[13] + 16057322146112. * A[12] - 502133360559024. * A[11] - + 2985686417468080. * A[10] + 32418922182093292. * A[9] - 63665380623022452. * A[8] + + 16481208821092575. * A[7] + 34161547357596099. * A[6] - 11490298497454932. * A[5] - + 5117272758337156. * A[4] + 933703210750480. * A[3] + 234855186762000. * A[2] - 7860524600000. * a - + 1226607567040.) + + 96 * B[2] * + (324439754752. * A[14] - 77231415197120. * A[13] - 539102931841856. * A[12] + + 4618258299956336. * A[11] + 28588485529469792. * A[10] - 141383982651179428. * A[9] + + 98783147840417772. * A[8] + 112831723492305801. * A[7] - 83329761150975036. * A[6] - + 26553582937192900. * A[5] + 12469117738765952. * A[4] + 2587165396642160. * A[3] - + 340406368038080. * A[2] - 53659641606080. * a + 219671272960.) + + 96 * b * Ap1[1] * + (1026630779520. * A[14] + 8781958472768. * A[13] - 210659786204384. * A[12] - + 1222283505284208. * A[11] + 5064251967491416. * A[10] + 24013052207628140. * A[9] - + 79710880160087370. * A[8] + 42596558293213227. * A[7] + 26570293386695790. * A[6] - + 14407831324576884. * A[5] - 3617322833922440. * A[4] + 950664948554384. * A[3] + + 172358006894496. * A[2] - 7430887938496. * a - 889746675584.) - + (a + 2) * (2 * a + 1) * + (573840801152. * A[14] - 156998277198784. * A[13] - 898376974770592. * A[12] + + 8622589006459984. * A[11] + 32874204024803560. * A[10] - 111492707520083828. * A[9] - + 184768503480287646. * A[8] + 528612016938984183. * A[7] - 184768503480287646. * A[6] - + 111492707520083828. * A[5] + 32874204024803560. * A[4] + 8622589006459984. * A[3] - + 898376974770592. * A[2] - 156998277198784. * a + 573840801152.)); + + double Z = std::pow(a * x, 1 / Ap1[1]); + double Zp = 1.; + double res = C[0]; + for (int k = 1; k < 9; k++) { + Zp /= Z; + res += (k % 2 == 0 ? 1 : -1) * C[k] * Zp; + } + if (!log_wb) { + res *= std::pow(Z, 0.5 - b) * std::exp(Ap1[1] / a * Z); + } else { + // logarithm of Wright's function + res = std::log(Z) * (0.5 - b) + Ap1[1] / a * Z + std::log(res); + } + return res; + } + + XSF_HOST_DEVICE inline double wb_Kmod(double exp_term, double eps, double a, double b, double x, double r) { + /* Compute integrand Kmod(eps, a, b, x, r) for Gauss-Laguerre quadrature. + * + * K(a, b, x, r+eps) = exp(-r-eps) * Kmod(eps, a, b, x, r) + * + * Kmod(eps, a, b, x, r) = exp(x * (r+eps)^(-a) * cos(pi*a)) * (r+eps)^(-b) + * * sin(x * (r+eps)^(-a) * sin(pi*a) + pi * b) + * + * Note that we additionally factor out exp(exp_term) which helps with large + * terms in the exponent of exp(...) + */ + double x_r_a = x * std::pow(r + eps, -a); + return std::exp(x_r_a * cephes::cospi(a) + exp_term) * std::pow(r + eps, -b) * + std::sin(x_r_a * cephes::sinpi(a) + M_PI * b); + } + + XSF_HOST_DEVICE inline double wb_P(double exp_term, double eps, double a, double b, double x, double phi) { + /* Compute integrand P for Gauss-Legendre quadrature. + * + * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi)) + * * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi) + * + (1-b)*phi) + * + * Note that we additionally factor out exp(exp_term) which helps with large + * terms in the exponent of exp(...) + */ + double x_eps_a = x * std::pow(eps, -a); + return std::exp(eps * std::cos(phi) + x_eps_a * std::cos(a * phi) + exp_term) * + std::cos(eps * std::sin(phi) - x_eps_a * std::sin(a * phi) + (1 - b) * phi); + } + + /* roots of laguerre polynomial of order 50 + * scipy.special.roots_laguerre(50)[0] or + * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[0] */ + constexpr double wb_x_laguerre[] = { + 0.02863051833937908, 0.1508829356769337, 0.3709487815348964, 0.6890906998810479, 1.105625023539913, + 1.620961751102501, 2.23561037591518, 2.950183366641835, 3.765399774405782, 4.682089387559285, + 5.70119757478489, 6.823790909794551, 8.051063669390792, 9.384345308258407, 10.82510903154915, + 12.37498160875746, 14.03575459982991, 15.80939719784467, 17.69807093335025, 19.70414653546156, + 21.83022330657825, 24.0791514444115, 26.45405784125298, 28.95837601193738, 31.59588095662286, + 34.37072996309045, 37.28751061055049, 40.35129757358607, 43.56772026999502, 46.94304399160304, + 50.48426796312992, 54.19924488016862, 58.09682801724853, 62.18705417568891, 66.48137387844482, + 70.99294482661949, 75.73701154772731, 80.73140480247769, 85.99721113646323, 91.55969041253388, + 97.44956561485056, 103.7048912366923, 110.3738588076403, 117.5191982031112, 125.2254701334734, + 133.6120279227287, 142.8583254892541, 153.2603719726036, 165.3856433166825, 180.6983437092145 + }; + /* weights for laguerre polynomial of order 50 + * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[1] */ + constexpr double wb_w_laguerre[] = { + 0.07140472613518988, 0.1471486069645884, 0.1856716275748313, 0.1843853825273539, + 0.1542011686063556, 0.1116853699022688, 0.07105288549019586, 0.04002027691150833, + 0.02005062308007171, 0.008960851203646281, 0.00357811241531566, 0.00127761715678905, + 0.0004080302449837189, 0.0001165288322309724, 2.974170493694165e-5, 6.777842526542028e-6, + 1.37747950317136e-6, 2.492886181720092e-7, 4.010354350427827e-8, 5.723331748141425e-9, + 7.229434249182665e-10, 8.061710142281779e-11, 7.913393099943723e-12, 6.81573661767678e-13, + 5.13242671658949e-14, 3.365624762437814e-15, 1.913476326965035e-16, 9.385589781827253e-18, + 3.950069964503411e-19, 1.417749517827512e-20, 4.309970276292175e-22, 1.101257519845548e-23, + 2.344617755608987e-25, 4.11854415463823e-27, 5.902246763596448e-29, 6.812008916553065e-31, + 6.237449498812102e-33, 4.452440579683377e-35, 2.426862352250487e-37, 9.852971481049686e-40, + 2.891078872318428e-42, 5.906162708112361e-45, 8.01287459750397e-48, 6.789575424396417e-51, + 3.308173010849252e-54, 8.250964876440456e-58, 8.848728128298018e-62, 3.064894889844417e-66, + 1.988708229330752e-71, 6.049567152238783e-78 + }; + /* roots of legendre polynomial of order 50 + * sympy.integrals.quadrature.import gauss_legendre(50, 16)[0] */ + constexpr double wb_x_legendre[] = { + -0.998866404420071, -0.9940319694320907, -0.9853540840480059, -0.9728643851066921, -0.9566109552428079, + -0.9366566189448779, -0.9130785566557919, -0.885967979523613, -0.8554297694299461, -0.8215820708593359, + -0.7845558329003993, -0.7444943022260685, -0.7015524687068223, -0.6558964656854394, -0.6077029271849502, + -0.5571583045146501, -0.5044581449074642, -0.4498063349740388, -0.3934143118975651, -0.3355002454194374, + -0.276288193779532, -0.2160072368760418, -0.1548905899981459, -0.09317470156008614, -0.03109833832718888, + 0.03109833832718888, 0.09317470156008614, 0.1548905899981459, 0.2160072368760418, 0.276288193779532, + 0.3355002454194374, 0.3934143118975651, 0.4498063349740388, 0.5044581449074642, 0.5571583045146501, + 0.6077029271849502, 0.6558964656854394, 0.7015524687068223, 0.7444943022260685, 0.7845558329003993, + 0.8215820708593359, 0.8554297694299461, 0.885967979523613, 0.9130785566557919, 0.9366566189448779, + 0.9566109552428079, 0.9728643851066921, 0.9853540840480059, 0.9940319694320907, 0.998866404420071 + }; + /* weights for legendre polynomial of order 50 + * sympy.integrals.quadrature.import gauss_legendre(50, 16)[1] */ + constexpr double wb_w_legendre[] = { + 0.002908622553155141, 0.006759799195745401, 0.01059054838365097, 0.01438082276148557, 0.01811556071348939, + 0.02178024317012479, 0.02536067357001239, 0.0288429935805352, 0.03221372822357802, 0.03545983561514615, + 0.03856875661258768, 0.0415284630901477, 0.04432750433880328, 0.04695505130394843, 0.04940093844946632, + 0.05165570306958114, 0.05371062188899625, 0.05555774480621252, 0.05718992564772838, 0.05860084981322245, + 0.05978505870426546, 0.06073797084177022, 0.06145589959031666, 0.06193606742068324, 0.06217661665534726, + 0.06217661665534726, 0.06193606742068324, 0.06145589959031666, 0.06073797084177022, 0.05978505870426546, + 0.05860084981322245, 0.05718992564772838, 0.05555774480621252, 0.05371062188899625, 0.05165570306958114, + 0.04940093844946632, 0.04695505130394843, 0.04432750433880328, 0.0415284630901477, 0.03856875661258768, + 0.03545983561514615, 0.03221372822357802, 0.0288429935805352, 0.02536067357001239, 0.02178024317012479, + 0.01811556071348939, 0.01438082276148557, 0.01059054838365097, 0.006759799195745401, 0.002908622553155141 + }; + /* Fitted parameters for optimal choice of eps + * Call: python _precompute/wright_bessel.py 4 */ + constexpr double wb_A[] = {0.41037, 0.30833, 6.9952, 18.382, -2.8566, 2.1122}; + + template + XSF_HOST_DEVICE inline double wright_bessel_integral(double a, double b, double x) { + /* 5. Integral representation + * + * K(a, b, x, r) = exp(-r + x * r^(-a) * cos(pi*a)) * r^(-b) + * * sin(x * r^(-a) * sin(pi*a) + pi * b) + * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi)) + * * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi) + * + (1-b)*phi) + * + * Phi(a, b, x) = 1/pi * int_eps^inf K(a, b, x, r) * dr + * + eps^(1-b)/pi * int_0^pi P(eps, a, b, x, phi) * dphi + * + * for any eps > 0. + * + * Note that P has a misprint in Luchko (2008) Eq. 9, the cos(phi(beta-1)) at + * the end of the first line should be removed and the −sin(phi(beta−1)) at + * the end of the second line should read +(1-b)*phi. + * This integral representation introduced the free parameter eps (from the + * radius of complex contour integration). We try to choose eps such that + * the integrand behaves smoothly. Note that this is quite diffrent from how + * Luchko (2008) deals with eps: he is either looking for the limit eps -> 0 + * or he sets (silently) eps=1. But having the freedom to set eps is much more + * powerful for numerical evaluation. + * + * As K has a leading exp(-r), we factor this out and apply Gauss-Laguerre + * quadrature rule: + * + * int_0^inf K(a, b, x, r+eps) dr = exp(-eps) int_0^inf exp(-r) Kmod(.., r) dr + * + * Note the shift r -> r+eps to have integation from 0 to infinity. + * The integral over P is done via a Gauss-Legendre quadrature rule. + * + * Note: Hardest argument range is large z, large b and small eps. + */ + + /* We use the free choice of eps to make the integral better behaved. + * 1. Concern is oscillatory behaviour of P. Therefore, we'd like to + * make the change in the argument of cosine small, i.e. make arc length + * int_0^phi sqrt(1 + f'(phi)^2) dphi small, with + * f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a*phi) + (1-b)*phi + * Proxy, make |f'(phi)| small. + * 2. Concern is int_0 K ~ int_0 (r+eps)^(-b) .. dr + * This is difficult as r -> 0 for large b. It behaves better for larger + * values of eps. + */ + + // Minimize oscillatory behavoir of P + double eps = + (wb_A[0] * b * std::exp(-0.5 * a) + + std::exp( + wb_A[1] + 1 / (1 + a) * std::log(x) - wb_A[2] * std::exp(-wb_A[3] * a) + + wb_A[4] / (1 + std::exp(wb_A[5] * a)) + )); + + if (a >= 4 && x >= 100) { + eps += 1; // This part is hard to fit + } + + // Large b + if (b >= 8) { + /* Make P small compared to K by setting eps large enough. + * int K ~ exp(-eps) and int P ~ eps^(1-b) */ + eps = std::fmax(eps, std::pow(b, -b / (1. - b)) + 0.1 * b); + } + + // safeguard, higher better for larger a, lower better for tiny a. + eps = std::fmin(eps, 150.); + eps = std::fmax(eps, 3.); // 3 seems to be a pretty good choice in general. + + // We factor out exp(-exp_term) from wb_Kmod and wb_P to avoid overflow of + // exp(..). + double exp_term = 0; + // From the exponent of K: + double r = wb_x_laguerre[50-1]; // largest value of x used in wb_Kmod + double x_r_a = x * std::pow(r + eps, -a); + exp_term = std::fmax(exp_term, x_r_a * cephes::cospi(a)); + // From the exponent of P: + double x_eps_a = x * std::pow(eps, -a); + // phi = 0 => cos(phi) = cos(a * phi) = 1 + exp_term = std::fmax(exp_term, eps + x_eps_a); + // phi = pi => cos(phi) = -1 + exp_term = std::fmax(exp_term, -eps + x_eps_a * cephes::cospi(a)); + + double res1 = 0; + double res2 = 0; + + double y; + for (int k = 0; k < 50; k++) { + res1 += wb_w_laguerre[k] * wb_Kmod(-exp_term, eps, a, b, x, wb_x_laguerre[k]); + // y = (b-a)*(x+1)/2.0 + a for integration from a=0 to b=pi + y = M_PI * (wb_x_legendre[k] + 1) / 2.0; + res2 += wb_w_legendre[k] * wb_P(-exp_term, eps, a, b, x, y); + } + res1 *= std::exp(-eps); + // (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1) + res2 *= M_PI / 2.0; + res2 *= std::pow(eps, 1 - b); + + if (!log_wb) { + // Remember the factored out exp_term from wb_Kmod and wb_P + return std::exp(exp_term) / M_PI * (res1 + res2); + } else { + // logarithm of Wright's function + return exp_term + std::log((res1 + res2) / M_PI); + } + } +} // namespace detail + +template +XSF_HOST_DEVICE inline double wright_bessel_t(double a, double b, double x) { + /* Compute Wright's generalized Bessel function for scalar arguments. + * + * According to [1], it is an entire function defined as + * + * .. math:: \Phi(a, b; x) = \sum_{k=0}^\infty \frac{x^k}{k! \Gamma(a k + b)} + * + * So far, only non-negative values of rho=a, beta=b and z=x are implemented. + * There are 5 different approaches depending on the ranges of the arguments: + * + * 1. Taylor series expansion in x=0 [1], for x <= 1. + * Involves gamma funtions in each term. + * 2. Taylor series expansion in x=0 [2], for large a. + * 3. Taylor series in a=0, for tiny a and not too large x. + * 4. Asymptotic expansion for large x [3, 4]. + * Suitable for large x while still small a and b. + * 5. Integral representation [5], in principle for all arguments. + * + * References + * ---------- + * [1] https://dlmf.nist.gov/10.46.E1 + * [2] P. K. Dunn, G. K. Smyth (2005), Series evaluation of Tweedie exponential + * dispersion model densities. Statistics and Computing 15 (2005): 267-280. + * [3] E. M. Wright (1935), The asymptotic expansion of the generalized Bessel + * function. Proc. London Math. Soc. (2) 38, pp. 257-270. + * https://doi.org/10.1112/plms/s2-38.1.257 + * [4] R. B. Paris (2017), The asymptotics of the generalised Bessel function, + * Mathematica Aeterna, Vol. 7, 2017, no. 4, 381 - 406, + * https://arxiv.org/abs/1711.03006 + * [5] Y. F. Luchko (2008), Algorithms for Evaluation of the Wright Function for + * the Real Arguments' Values, Fractional Calculus and Applied Analysis 11(1) + * http://sci-gems.math.bas.bg/jspui/bitstream/10525/1298/1/fcaa-vol11-num1-2008-57p-75p.pdf + */ + if (std::isnan(a) || std::isnan(b) || std::isnan(x)) { + return std::numeric_limits::quiet_NaN(); + } + if (a < 0 || b < 0 || x < 0) { + set_error("wright_bessel", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (std::isinf(x)) { + if (std::isinf(a) || std::isinf(b)) { + return std::numeric_limits::quiet_NaN(); + } + return std::numeric_limits::infinity(); + } + if (std::isinf(a) || std::isinf(b)) { + return std::numeric_limits::quiet_NaN(); // or 0 + } + if (a >= detail::rgamma_zero || b >= detail::rgamma_zero) { + set_error("wright_bessel", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (x == 0) { + // return rgamma(b) + if (!log_wb) { + return cephes::rgamma(b); + } else { + // logarithm of Wright's function + return -cephes::lgam(b); + } + } + if (a == 0) { + // return exp(x) * rgamma(b) + if (!log_wb) { + return detail::exp_rgamma(x, b); + } else { + // logarithm of Wright's function + return x - cephes::lgam(b); + } + } + + constexpr double exp_inf = 709.78271289338403; + int order; + if ((a <= 1e-3 && b <= 50 && x <= 9) || (a <= 1e-4 && b <= 70 && x <= 100) || + (a <= 1e-5 && b <= 170 && (x < exp_inf || (log_wb && x <= 1e3)))) { + /* Taylor Series expansion in a=0 to order=order => precision <= 1e-11 + * If beta is also small => precision <= 1e-11. + * max order = 5 */ + if (a <= 1e-5) { + if (x <= 1) { + order = 2; + } else if (x <= 10) { + order = 3; + } else if (x <= 100) { + order = 4; + } else { // x < exp_inf + order = 5; + } + } else if (a <= 1e-4) { + if (x <= 1e-2) { + order = 2; + } else if (x <= 1) { + order = 3; + } else if (x <= 10) { + order = 4; + } else { // x <= 100 + order = 5; + } + } else { // a <= 1e-3 + if (x <= 1e-5) { + order = 2; + } else if (x <= 1e-1) { + order = 3; + } else if (x <= 1) { + order = 4; + } else { // x <= 9 + order = 5; + } + } + + return detail::wb_small_a(a, b, x, order); + } + + if (x <= 1) { + // 18 term Taylor Series => error mostly smaller 5e-14 + double res = detail::wb_series(a, b, x, 0, 18); + if (log_wb) res = std::log(res); + return res; + } + if (x <= 2) { + // 20 term Taylor Series => error mostly smaller 1e-12 to 1e-13 + double res = detail::wb_series(a, b, x, 0, 20); + if (log_wb) res = std::log(res); + return res; + } + if (a >= 5) { + /* Taylor series around the approximate maximum term. + * Set number of terms=order. */ + if (a >= 10) { + if (x <= 1e11) { + order = 6; + } else { + order = static_cast(std::fmin(std::log10(x) - 5 + b / 10, 30)); + } + } else { + if (x <= 1e4) { + order = 6; + } else if (x <= 1e8) { + order = static_cast(2 * std::log10(x)); + } else if (x <= 1e10) { + order = static_cast(4 * std::log10(x) - 16); + } else { + order = static_cast(std::fmin(6 * std::log10(x) - 36, 100)); + } + } + return detail::wb_large_a(a, b, x, order); + } + if (std::pow(a * x, 1 / (1. + a)) >= 14 + b * b / (2 * (1 + a))) { + /* Asymptotic expansion in Z = (a*x)^(1/(1+a)) up to 8th term 1/Z^8. + * For 1/Z^k, the highest term in b is b^(2*k) * a0 / (2^k k! (1+a)^k). + * As a0 is a common factor to all orders, this explains a bit the + * domain of good convergence set above. + * => precision ~ 1e-11 but can go down to ~1e-8 or 1e-7 + * Note: We ensured a <= 5 as this is a bad approximation for large a. */ + return detail::wb_asymptotic(a, b, x); + } + if (0.5 <= a && a <= 1.8 && 100 <= b && 1e5 <= x) { + // This is a very hard domain. This condition is placed after wb_asymptotic. + // TODO: Explore ways to cover this domain. + return std::numeric_limits::quiet_NaN(); + } + return detail::wright_bessel_integral(a, b, x); +} + + +XSF_HOST_DEVICE inline double wright_bessel(double a, double b, double x) { + return wright_bessel_t(a, b, x); +} + +XSF_HOST_DEVICE inline float wright_bessel(float a, float b, float x) { + return wright_bessel(static_cast(a), static_cast(b), static_cast(x)); +} + +XSF_HOST_DEVICE inline double log_wright_bessel(double a, double b, double x) { + return wright_bessel_t(a, b, x); +} + +XSF_HOST_DEVICE inline float log_wright_bessel(float a, float b, float x) { + return log_wright_bessel(static_cast(a), static_cast(b), static_cast(x)); +} + +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h new file mode 100644 index 0000000000000000000000000000000000000000..64e83ca390a094b85380ff69c24ba2cdead33d7f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h @@ -0,0 +1,35 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * + * Original author: Josh Wilson, 2016. + */ + +#pragma once + +#include "config.h" + +namespace xsf { +namespace detail { + + XSF_HOST_DEVICE inline std::complex zlog1(std::complex z) { + /* Compute log, paying special attention to accuracy around 1. We + * implement this ourselves because some systems (most notably the + * Travis CI machines) are weak in this regime. */ + std::complex coeff = -1.0; + std::complex res = 0.0; + + if (std::abs(z - 1.0) > 0.1) { + return std::log(z); + } + + z -= 1.0; + for (int n = 1; n < 17; n++) { + coeff *= -z; + res += coeff / static_cast(n); + if (std::abs(res / coeff) < std::numeric_limits::epsilon()) { + break; + } + } + return res; + } +} // namespace detail +} // namespace xsf diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a73e7b7814175c9e19977fc2ebff2367fc1dca --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__init__.py @@ -0,0 +1,667 @@ +""" +.. _statsrefmanual: + +========================================== +Statistical functions (:mod:`scipy.stats`) +========================================== + +.. currentmodule:: scipy.stats + +This module contains a large number of probability distributions, +summary and frequency statistics, correlation functions and statistical +tests, masked statistics, kernel density estimation, quasi-Monte Carlo +functionality, and more. + +Statistics is a very large area, and there are topics that are out of scope +for SciPy and are covered by other packages. Some of the most important ones +are: + +- `statsmodels `__: + regression, linear models, time series analysis, extensions to topics + also covered by ``scipy.stats``. +- `Pandas `__: tabular data, time series + functionality, interfaces to other statistical languages. +- `PyMC `__: Bayesian statistical + modeling, probabilistic machine learning. +- `scikit-learn `__: classification, regression, + model selection. +- `Seaborn `__: statistical data visualization. +- `rpy2 `__: Python to R bridge. + + +Probability distributions +========================= + +Each univariate distribution is an instance of a subclass of `rv_continuous` +(`rv_discrete` for discrete distributions): + +.. autosummary:: + :toctree: generated/ + + rv_continuous + rv_discrete + rv_histogram + +Continuous distributions +------------------------ + +.. autosummary:: + :toctree: generated/ + + alpha -- Alpha + anglit -- Anglit + arcsine -- Arcsine + argus -- Argus + beta -- Beta + betaprime -- Beta Prime + bradford -- Bradford + burr -- Burr (Type III) + burr12 -- Burr (Type XII) + cauchy -- Cauchy + chi -- Chi + chi2 -- Chi-squared + cosine -- Cosine + crystalball -- Crystalball + dgamma -- Double Gamma + dpareto_lognorm -- Double Pareto Lognormal + dweibull -- Double Weibull + erlang -- Erlang + expon -- Exponential + exponnorm -- Exponentially Modified Normal + exponweib -- Exponentiated Weibull + exponpow -- Exponential Power + f -- F (Snecdor F) + fatiguelife -- Fatigue Life (Birnbaum-Saunders) + fisk -- Fisk + foldcauchy -- Folded Cauchy + foldnorm -- Folded Normal + genlogistic -- Generalized Logistic + gennorm -- Generalized normal + genpareto -- Generalized Pareto + genexpon -- Generalized Exponential + genextreme -- Generalized Extreme Value + gausshyper -- Gauss Hypergeometric + gamma -- Gamma + gengamma -- Generalized gamma + genhalflogistic -- Generalized Half Logistic + genhyperbolic -- Generalized Hyperbolic + geninvgauss -- Generalized Inverse Gaussian + gibrat -- Gibrat + gompertz -- Gompertz (Truncated Gumbel) + gumbel_r -- Right Sided Gumbel, Log-Weibull, Fisher-Tippett, Extreme Value Type I + gumbel_l -- Left Sided Gumbel, etc. + halfcauchy -- Half Cauchy + halflogistic -- Half Logistic + halfnorm -- Half Normal + halfgennorm -- Generalized Half Normal + hypsecant -- Hyperbolic Secant + invgamma -- Inverse Gamma + invgauss -- Inverse Gaussian + invweibull -- Inverse Weibull + irwinhall -- Irwin-Hall + jf_skew_t -- Jones and Faddy Skew-T + johnsonsb -- Johnson SB + johnsonsu -- Johnson SU + kappa4 -- Kappa 4 parameter + kappa3 -- Kappa 3 parameter + ksone -- Distribution of Kolmogorov-Smirnov one-sided test statistic + kstwo -- Distribution of Kolmogorov-Smirnov two-sided test statistic + kstwobign -- Limiting Distribution of scaled Kolmogorov-Smirnov two-sided test statistic. + landau -- Landau + laplace -- Laplace + laplace_asymmetric -- Asymmetric Laplace + levy -- Levy + levy_l + levy_stable + logistic -- Logistic + loggamma -- Log-Gamma + loglaplace -- Log-Laplace (Log Double Exponential) + lognorm -- Log-Normal + loguniform -- Log-Uniform + lomax -- Lomax (Pareto of the second kind) + maxwell -- Maxwell + mielke -- Mielke's Beta-Kappa + moyal -- Moyal + nakagami -- Nakagami + ncx2 -- Non-central chi-squared + ncf -- Non-central F + nct -- Non-central Student's T + norm -- Normal (Gaussian) + norminvgauss -- Normal Inverse Gaussian + pareto -- Pareto + pearson3 -- Pearson type III + powerlaw -- Power-function + powerlognorm -- Power log normal + powernorm -- Power normal + rdist -- R-distribution + rayleigh -- Rayleigh + rel_breitwigner -- Relativistic Breit-Wigner + rice -- Rice + recipinvgauss -- Reciprocal Inverse Gaussian + semicircular -- Semicircular + skewcauchy -- Skew Cauchy + skewnorm -- Skew normal + studentized_range -- Studentized Range + t -- Student's T + trapezoid -- Trapezoidal + triang -- Triangular + truncexpon -- Truncated Exponential + truncnorm -- Truncated Normal + truncpareto -- Truncated Pareto + truncweibull_min -- Truncated minimum Weibull distribution + tukeylambda -- Tukey-Lambda + uniform -- Uniform + vonmises -- Von-Mises (Circular) + vonmises_line -- Von-Mises (Line) + wald -- Wald + weibull_min -- Minimum Weibull (see Frechet) + weibull_max -- Maximum Weibull (see Frechet) + wrapcauchy -- Wrapped Cauchy + +The ``fit`` method of the univariate continuous distributions uses +maximum likelihood estimation to fit the distribution to a data set. +The ``fit`` method can accept regular data or *censored data*. +Censored data is represented with instances of the `CensoredData` +class. + +.. autosummary:: + :toctree: generated/ + + CensoredData + + +Multivariate distributions +-------------------------- + +.. autosummary:: + :toctree: generated/ + + multivariate_normal -- Multivariate normal distribution + matrix_normal -- Matrix normal distribution + dirichlet -- Dirichlet + dirichlet_multinomial -- Dirichlet multinomial distribution + wishart -- Wishart + invwishart -- Inverse Wishart + multinomial -- Multinomial distribution + special_ortho_group -- SO(N) group + ortho_group -- O(N) group + unitary_group -- U(N) group + random_correlation -- random correlation matrices + multivariate_t -- Multivariate t-distribution + multivariate_hypergeom -- Multivariate hypergeometric distribution + normal_inverse_gamma -- Normal-inverse-gamma distribution + random_table -- Distribution of random tables with given marginals + uniform_direction -- Uniform distribution on S(N-1) + vonmises_fisher -- Von Mises-Fisher distribution + +`scipy.stats.multivariate_normal` methods accept instances +of the following class to represent the covariance. + +.. autosummary:: + :toctree: generated/ + + Covariance -- Representation of a covariance matrix + + +Discrete distributions +---------------------- + +.. autosummary:: + :toctree: generated/ + + bernoulli -- Bernoulli + betabinom -- Beta-Binomial + betanbinom -- Beta-Negative Binomial + binom -- Binomial + boltzmann -- Boltzmann (Truncated Discrete Exponential) + dlaplace -- Discrete Laplacian + geom -- Geometric + hypergeom -- Hypergeometric + logser -- Logarithmic (Log-Series, Series) + nbinom -- Negative Binomial + nchypergeom_fisher -- Fisher's Noncentral Hypergeometric + nchypergeom_wallenius -- Wallenius's Noncentral Hypergeometric + nhypergeom -- Negative Hypergeometric + planck -- Planck (Discrete Exponential) + poisson -- Poisson + poisson_binom -- Poisson Binomial + randint -- Discrete Uniform + skellam -- Skellam + yulesimon -- Yule-Simon + zipf -- Zipf (Zeta) + zipfian -- Zipfian + + +An overview of statistical functions is given below. Many of these functions +have a similar version in `scipy.stats.mstats` which work for masked arrays. + +Summary statistics +================== + +.. autosummary:: + :toctree: generated/ + + describe -- Descriptive statistics + gmean -- Geometric mean + hmean -- Harmonic mean + pmean -- Power mean + kurtosis -- Fisher or Pearson kurtosis + mode -- Modal value + moment -- Central moment + lmoment + expectile -- Expectile + skew -- Skewness + kstat -- + kstatvar -- + tmean -- Truncated arithmetic mean + tvar -- Truncated variance + tmin -- + tmax -- + tstd -- + tsem -- + variation -- Coefficient of variation + find_repeats + rankdata + tiecorrect + trim_mean + gstd -- Geometric Standard Deviation + iqr + sem + bayes_mvs + mvsdist + entropy + differential_entropy + median_abs_deviation + +Frequency statistics +==================== + +.. autosummary:: + :toctree: generated/ + + cumfreq + percentileofscore + scoreatpercentile + relfreq + +.. autosummary:: + :toctree: generated/ + + binned_statistic -- Compute a binned statistic for a set of data. + binned_statistic_2d -- Compute a 2-D binned statistic for a set of data. + binned_statistic_dd -- Compute a d-D binned statistic for a set of data. + +.. _hypotests: + +Hypothesis Tests and related functions +====================================== +SciPy has many functions for performing hypothesis tests that return a +test statistic and a p-value, and several of them return confidence intervals +and/or other related information. + +The headings below are based on common uses of the functions within, but due to +the wide variety of statistical procedures, any attempt at coarse-grained +categorization will be imperfect. Also, note that tests within the same heading +are not interchangeable in general (e.g. many have different distributional +assumptions). + +One Sample Tests / Paired Sample Tests +-------------------------------------- +One sample tests are typically used to assess whether a single sample was +drawn from a specified distribution or a distribution with specified properties +(e.g. zero mean). + +.. autosummary:: + :toctree: generated/ + + ttest_1samp + binomtest + quantile_test + skewtest + kurtosistest + normaltest + jarque_bera + shapiro + anderson + cramervonmises + ks_1samp + goodness_of_fit + chisquare + power_divergence + +Paired sample tests are often used to assess whether two samples were drawn +from the same distribution; they differ from the independent sample tests below +in that each observation in one sample is treated as paired with a +closely-related observation in the other sample (e.g. when environmental +factors are controlled between observations within a pair but not among pairs). +They can also be interpreted or used as one-sample tests (e.g. tests on the +mean or median of *differences* between paired observations). + +.. autosummary:: + :toctree: generated/ + + ttest_rel + wilcoxon + +Association/Correlation Tests +----------------------------- + +These tests are often used to assess whether there is a relationship (e.g. +linear) between paired observations in multiple samples or among the +coordinates of multivariate observations. + +.. autosummary:: + :toctree: generated/ + + linregress + pearsonr + spearmanr + pointbiserialr + kendalltau + chatterjeexi + weightedtau + somersd + siegelslopes + theilslopes + page_trend_test + multiscale_graphcorr + +These association tests and are to work with samples in the form of contingency +tables. Supporting functions are available in `scipy.stats.contingency`. + +.. autosummary:: + :toctree: generated/ + + chi2_contingency + fisher_exact + barnard_exact + boschloo_exact + +Independent Sample Tests +------------------------ +Independent sample tests are typically used to assess whether multiple samples +were independently drawn from the same distribution or different distributions +with a shared property (e.g. equal means). + +Some tests are specifically for comparing two samples. + +.. autosummary:: + :toctree: generated/ + + ttest_ind_from_stats + poisson_means_test + ttest_ind + mannwhitneyu + bws_test + ranksums + brunnermunzel + mood + ansari + cramervonmises_2samp + epps_singleton_2samp + ks_2samp + kstest + +Others are generalized to multiple samples. + +.. autosummary:: + :toctree: generated/ + + f_oneway + tukey_hsd + dunnett + kruskal + alexandergovern + fligner + levene + bartlett + median_test + friedmanchisquare + anderson_ksamp + +Resampling and Monte Carlo Methods +---------------------------------- +The following functions can reproduce the p-value and confidence interval +results of most of the functions above, and often produce accurate results in a +wider variety of conditions. They can also be used to perform hypothesis tests +and generate confidence intervals for custom statistics. This flexibility comes +at the cost of greater computational requirements and stochastic results. + +.. autosummary:: + :toctree: generated/ + + monte_carlo_test + permutation_test + bootstrap + power + +Instances of the following object can be passed into some hypothesis test +functions to perform a resampling or Monte Carlo version of the hypothesis +test. + +.. autosummary:: + :toctree: generated/ + + MonteCarloMethod + PermutationMethod + BootstrapMethod + +Multiple Hypothesis Testing and Meta-Analysis +--------------------------------------------- +These functions are for assessing the results of individual tests as a whole. +Functions for performing specific multiple hypothesis tests (e.g. post hoc +tests) are listed above. + +.. autosummary:: + :toctree: generated/ + + combine_pvalues + false_discovery_control + + +The following functions are related to the tests above but do not belong in the +above categories. + +Random Variables +================ + +.. autosummary:: + :toctree: generated/ + + make_distribution + Normal + Uniform + Mixture + order_statistic + truncate + abs + exp + log + +Quasi-Monte Carlo +================= + +.. toctree:: + :maxdepth: 4 + + stats.qmc + +Contingency Tables +================== + +.. toctree:: + :maxdepth: 4 + + stats.contingency + +Masked statistics functions +=========================== + +.. toctree:: + + stats.mstats + + +Other statistical functionality +=============================== + +Transformations +--------------- + +.. autosummary:: + :toctree: generated/ + + boxcox + boxcox_normmax + boxcox_llf + yeojohnson + yeojohnson_normmax + yeojohnson_llf + obrientransform + sigmaclip + trimboth + trim1 + zmap + zscore + gzscore + +Statistical distances +--------------------- + +.. autosummary:: + :toctree: generated/ + + wasserstein_distance + wasserstein_distance_nd + energy_distance + +Sampling +-------- + +.. toctree:: + :maxdepth: 4 + + stats.sampling + +Fitting / Survival Analysis +--------------------------- + +.. autosummary:: + :toctree: generated/ + + fit + ecdf + logrank + +Directional statistical functions +--------------------------------- + +.. autosummary:: + :toctree: generated/ + + directional_stats + circmean + circvar + circstd + +Sensitivity Analysis +-------------------- + +.. autosummary:: + :toctree: generated/ + + sobol_indices + +Plot-tests +---------- + +.. autosummary:: + :toctree: generated/ + + ppcc_max + ppcc_plot + probplot + boxcox_normplot + yeojohnson_normplot + +Univariate and multivariate kernel density estimation +----------------------------------------------------- + +.. autosummary:: + :toctree: generated/ + + gaussian_kde + +Warnings / Errors used in :mod:`scipy.stats` +-------------------------------------------- + +.. autosummary:: + :toctree: generated/ + + DegenerateDataWarning + ConstantInputWarning + NearConstantInputWarning + FitError + +Result classes used in :mod:`scipy.stats` +----------------------------------------- + +.. warning:: + + These classes are private, but they are included here because instances + of them are returned by other statistical functions. User import and + instantiation is not supported. + +.. toctree:: + :maxdepth: 2 + + stats._result_classes + +""" # noqa: E501 + +from ._warnings_errors import (ConstantInputWarning, NearConstantInputWarning, + DegenerateDataWarning, FitError) +from ._stats_py import * +from ._variation import variation +from .distributions import * +from ._morestats import * +from ._multicomp import * +from ._binomtest import binomtest +from ._binned_statistic import * +from ._kde import gaussian_kde +from . import mstats +from . import qmc +from ._multivariate import * +from . import contingency +from .contingency import chi2_contingency +from ._censored_data import CensoredData +from ._resampling import (bootstrap, monte_carlo_test, permutation_test, power, + MonteCarloMethod, PermutationMethod, BootstrapMethod) +from ._entropy import * +from ._hypotests import * +from ._page_trend_test import page_trend_test +from ._mannwhitneyu import mannwhitneyu +from ._bws_test import bws_test +from ._fit import fit, goodness_of_fit +from ._covariance import Covariance +from ._sensitivity_analysis import * +from ._survival import * +from ._distribution_infrastructure import ( + make_distribution, Mixture, order_statistic, truncate, exp, log, abs +) +from ._new_distributions import Normal, Uniform +from ._mgc import multiscale_graphcorr +from ._correlation import chatterjeexi + + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ( + biasedurn, kde, morestats, mstats_basic, mstats_extras, mvn, stats +) + + +__all__ = [s for s in dir() if not s.startswith("_")] # Remove dunders. + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b3fd9c3be31a22df91cb887b26733795fc18cb6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..416a2aaab95c985f71109bbaab5d2f8e0dae77da Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binned_statistic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binned_statistic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e7d42f2f80c203a48812998f17c074a23ad96ce Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binned_statistic.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a07c0e2345f6b12ee202d133a8017deb8bdd4bec Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93366a1934613eef767e4c49534bf1a00128ebb0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50250ee896511c9b6226a5eda9245f247f3a6737 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d21aa53ee08f0d16605747d04938e9357750f11b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70f6420761f2f0a679398ccc4c3356308fc8f9ad Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_correlation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_correlation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25def70d50026f9bcd00b190e148a9aeeee00595 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_correlation.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69298820948bb6ceec7a6511d36564ef9ccbfcd5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaea99fd02a07b1543e20d91cc82e57df16ddfaf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11ea5f190340fa5ee91779733590885b3695e0ac Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24f848d4afdd0f4514936c401e6b30244902e9aa Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_entropy.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_entropy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c386d30c1f6e43bca8aa123b6e94ebc73b8aa7d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_entropy.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1167038e96ce3ed5585b87e2ff5e44160ae1e583 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f1929a262a412caf86fdb65ea6f2347b8c92f74 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b91e54c156afd147f7e1b3eadaab40e0bdf092d8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_ksstats.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_ksstats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ebd53abe66b65a6ae56b04ffad1a6b16c937a85 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_ksstats.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08d978af1aae1d17bbf070e1b16121f4db91d979 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e75cc7c2d9ef684c1e647124687e178b3812d112 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..755547bf7ee939570cc69ec33d2fe900eed7a30c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b8cd11a3a491678593bfd9495ee242b6b3f22a8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_new_distributions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_new_distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9579c7b2f2242054da74b2cd2853f3469158584f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_new_distributions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306995c8b1ad2b8e762e17949858dda1d34142df Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cff72255886a3292c997a0c2ee42f2206fc0080 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_probability_distribution.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_probability_distribution.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e69fc8515733bb29a4fdb0e34ecf6b5b7480fd0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_probability_distribution.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..027ee66215bb0736d1d94895d47505d2365beb10 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8048fb6cef51ca2dfc5bb54da64444e7592c15cc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b939abe3174af01c56deccf6f49b5dbe59ebdf8f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a42ca86e2f67d7556ef118fe93ccc427bf6e7aa Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc3ea42c831ef9e9a3aea6d10f464898d50b33b2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fff228eadf4bd6124b88531b0294333d3a2268f4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ec28fe2912b96589c89290479447b7a18212348 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f38c6de5085f9c15e03ea2afe230f0788e127e54 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e53848203f755e4de91c699a099f23619f8a98e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b37d492a0c81aad6268e7f66ea127695310238a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f5173d1269216486241f1e2917af54046f4cc45 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62204af04b3be35fb5c0a985d95f55a49740636d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09a8332902a8082c885a8f878a0235d27d3e16b1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36a656176c574092216b764a6adb7756ccb6ec14 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/kde.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/kde.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5586a56d6616f9e3af5deacee74b35d2b4680030 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/kde.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b77eea7aef9e25bef80b21cd3642896726baf074 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3043b6c05fe282de5e7934d5972d717bd2b8f790 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_basic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_basic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1f90480d4575630b8f04acebb60ef9ed096c90e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_basic.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..526f451a0caeb7330fb8b6229183ca99813d761f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8faa144557f08a12403b697569c9eb9b9044e32d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06219031dc15fda91fa0112d1c24cd154a1f291f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5da8c1a9bf53a1e976e34b3178506226c834ab9f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_axis_nan_policy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_axis_nan_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..26a4492056f83647059fbf72b0bf6538474b7451 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_axis_nan_policy.py @@ -0,0 +1,699 @@ +# Many scipy.stats functions support `axis` and `nan_policy` parameters. +# When the two are combined, it can be tricky to get all the behavior just +# right. This file contains utility functions useful for scipy.stats functions +# that support `axis` and `nan_policy`, including a decorator that +# automatically adds `axis` and `nan_policy` arguments to a function. + +import warnings +import numpy as np +from functools import wraps +from scipy._lib._docscrape import FunctionDoc, Parameter +from scipy._lib._util import _contains_nan, AxisError, _get_nan +from scipy._lib._array_api import array_namespace, is_numpy + +import inspect + +too_small_1d_not_omit = ( + "One or more sample arguments is too small; all " + "returned values will be NaN. " + "See documentation for sample size requirements.") + +too_small_1d_omit = ( + "After omitting NaNs, one or more sample arguments " + "is too small; all returned values will be NaN. " + "See documentation for sample size requirements.") + +too_small_nd_not_omit = ( + "All axis-slices of one or more sample arguments are " + "too small; all elements of returned arrays will be NaN. " + "See documentation for sample size requirements.") + +too_small_nd_omit = ( + "After omitting NaNs, one or more axis-slices of one " + "or more sample arguments is too small; corresponding " + "elements of returned arrays will be NaN. " + "See documentation for sample size requirements.") + +class SmallSampleWarning(RuntimeWarning): + pass + + +def _broadcast_arrays(arrays, axis=None, xp=None): + """ + Broadcast shapes of arrays, ignoring incompatibility of specified axes + """ + if not arrays: + return arrays + xp = array_namespace(*arrays) if xp is None else xp + arrays = [xp.asarray(arr) for arr in arrays] + shapes = [arr.shape for arr in arrays] + new_shapes = _broadcast_shapes(shapes, axis) + if axis is None: + new_shapes = [new_shapes]*len(arrays) + return [xp.broadcast_to(array, new_shape) + for array, new_shape in zip(arrays, new_shapes)] + + +def _broadcast_shapes(shapes, axis=None): + """ + Broadcast shapes, ignoring incompatibility of specified axes + """ + if not shapes: + return shapes + + # input validation + if axis is not None: + axis = np.atleast_1d(axis) + message = '`axis` must be an integer, a tuple of integers, or `None`.' + try: + with np.errstate(invalid='ignore'): + axis_int = axis.astype(int) + except ValueError as e: + raise AxisError(message) from e + if not np.array_equal(axis_int, axis): + raise AxisError(message) + axis = axis_int + + # First, ensure all shapes have same number of dimensions by prepending 1s. + n_dims = max([len(shape) for shape in shapes]) + new_shapes = np.ones((len(shapes), n_dims), dtype=int) + for row, shape in zip(new_shapes, shapes): + row[len(row)-len(shape):] = shape # can't use negative indices (-0:) + + # Remove the shape elements of the axes to be ignored, but remember them. + if axis is not None: + axis[axis < 0] = n_dims + axis[axis < 0] + axis = np.sort(axis) + if axis[-1] >= n_dims or axis[0] < 0: + message = (f"`axis` is out of bounds " + f"for array of dimension {n_dims}") + raise AxisError(message) + + if len(np.unique(axis)) != len(axis): + raise AxisError("`axis` must contain only distinct elements") + + removed_shapes = new_shapes[:, axis] + new_shapes = np.delete(new_shapes, axis, axis=1) + + # If arrays are broadcastable, shape elements that are 1 may be replaced + # with a corresponding non-1 shape element. Assuming arrays are + # broadcastable, that final shape element can be found with: + new_shape = np.max(new_shapes, axis=0) + # except in case of an empty array: + new_shape *= new_shapes.all(axis=0) + + # Among all arrays, there can only be one unique non-1 shape element. + # Therefore, if any non-1 shape element does not match what we found + # above, the arrays must not be broadcastable after all. + if np.any(~((new_shapes == 1) | (new_shapes == new_shape))): + raise ValueError("Array shapes are incompatible for broadcasting.") + + if axis is not None: + # Add back the shape elements that were ignored + new_axis = axis - np.arange(len(axis)) + new_shapes = [tuple(np.insert(new_shape, new_axis, removed_shape)) + for removed_shape in removed_shapes] + return new_shapes + else: + return tuple(new_shape) + + +def _broadcast_array_shapes_remove_axis(arrays, axis=None): + """ + Broadcast shapes of arrays, dropping specified axes + + Given a sequence of arrays `arrays` and an integer or tuple `axis`, find + the shape of the broadcast result after consuming/dropping `axis`. + In other words, return output shape of a typical hypothesis test on + `arrays` vectorized along `axis`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats._axis_nan_policy import _broadcast_array_shapes_remove_axis + >>> a = np.zeros((5, 2, 1)) + >>> b = np.zeros((9, 3)) + >>> _broadcast_array_shapes_remove_axis((a, b), 1) + (5, 3) + """ + # Note that here, `axis=None` means do not consume/drop any axes - _not_ + # ravel arrays before broadcasting. + shapes = [arr.shape for arr in arrays] + return _broadcast_shapes_remove_axis(shapes, axis) + + +def _broadcast_shapes_remove_axis(shapes, axis=None): + """ + Broadcast shapes, dropping specified axes + + Same as _broadcast_array_shapes_remove_axis, but given a sequence + of array shapes `shapes` instead of the arrays themselves. + """ + shapes = _broadcast_shapes(shapes, axis) + shape = shapes[0] + if axis is not None: + shape = np.delete(shape, axis) + return tuple(shape) + + +def _broadcast_concatenate(arrays, axis, paired=False): + """Concatenate arrays along an axis with broadcasting.""" + arrays = _broadcast_arrays(arrays, axis if not paired else None) + res = np.concatenate(arrays, axis=axis) + return res + + +# TODO: add support for `axis` tuples +def _remove_nans(samples, paired): + "Remove nans from paired or unpaired 1D samples" + # potential optimization: don't copy arrays that don't contain nans + if not paired: + return [sample[~np.isnan(sample)] for sample in samples] + + # for paired samples, we need to remove the whole pair when any part + # has a nan + nans = np.isnan(samples[0]) + for sample in samples[1:]: + nans = nans | np.isnan(sample) + not_nans = ~nans + return [sample[not_nans] for sample in samples] + + +def _remove_sentinel(samples, paired, sentinel): + "Remove sentinel values from paired or unpaired 1D samples" + # could consolidate with `_remove_nans`, but it's not quite as simple as + # passing `sentinel=np.nan` because `(np.nan == np.nan) is False` + + # potential optimization: don't copy arrays that don't contain sentinel + if not paired: + return [sample[sample != sentinel] for sample in samples] + + # for paired samples, we need to remove the whole pair when any part + # has a nan + sentinels = (samples[0] == sentinel) + for sample in samples[1:]: + sentinels = sentinels | (sample == sentinel) + not_sentinels = ~sentinels + return [sample[not_sentinels] for sample in samples] + + +def _masked_arrays_2_sentinel_arrays(samples): + # masked arrays in `samples` are converted to regular arrays, and values + # corresponding with masked elements are replaced with a sentinel value + + # return without modifying arrays if none have a mask + has_mask = False + for sample in samples: + mask = getattr(sample, 'mask', False) + has_mask = has_mask or np.any(mask) + if not has_mask: + return samples, None # None means there is no sentinel value + + # Choose a sentinel value. We can't use `np.nan`, because sentinel (masked) + # values are always omitted, but there are different nan policies. + dtype = np.result_type(*samples) + dtype = dtype if np.issubdtype(dtype, np.number) else np.float64 + for i in range(len(samples)): + # Things get more complicated if the arrays are of different types. + # We could have different sentinel values for each array, but + # the purpose of this code is convenience, not efficiency. + samples[i] = samples[i].astype(dtype, copy=False) + + inexact = np.issubdtype(dtype, np.inexact) + info = np.finfo if inexact else np.iinfo + max_possible, min_possible = info(dtype).max, info(dtype).min + nextafter = np.nextafter if inexact else (lambda x, _: x - 1) + + sentinel = max_possible + # For simplicity, min_possible/np.infs are not candidate sentinel values + while sentinel > min_possible: + for sample in samples: + if np.any(sample == sentinel): # choose a new sentinel value + sentinel = nextafter(sentinel, -np.inf) + break + else: # when sentinel value is OK, break the while loop + break + else: + message = ("This function replaces masked elements with sentinel " + "values, but the data contains all distinct values of this " + "data type. Consider promoting the dtype to `np.float64`.") + raise ValueError(message) + + # replace masked elements with sentinel value + out_samples = [] + for sample in samples: + mask = getattr(sample, 'mask', None) + if mask is not None: # turn all masked arrays into sentinel arrays + mask = np.broadcast_to(mask, sample.shape) + sample = sample.data.copy() if np.any(mask) else sample.data + sample = np.asarray(sample) # `sample.data` could be a memoryview? + sample[mask] = sentinel + out_samples.append(sample) + + return out_samples, sentinel + + +def _check_empty_inputs(samples, axis): + """ + Check for empty sample; return appropriate output for a vectorized hypotest + """ + # if none of the samples are empty, we need to perform the test + if not any(sample.size == 0 for sample in samples): + return None + # otherwise, the statistic and p-value will be either empty arrays or + # arrays with NaNs. Produce the appropriate array and return it. + output_shape = _broadcast_array_shapes_remove_axis(samples, axis) + output = np.ones(output_shape) * _get_nan(*samples) + return output + + +def _add_reduced_axes(res, reduced_axes, keepdims): + """ + Add reduced axes back to all the arrays in the result object + if keepdims = True. + """ + return ([np.expand_dims(output, reduced_axes) + if not isinstance(output, int) else output for output in res] + if keepdims else res) + + +# Standard docstring / signature entries for `axis`, `nan_policy`, `keepdims` +_name = 'axis' +_desc = ( + """If an int, the axis of the input along which to compute the statistic. +The statistic of each axis-slice (e.g. row) of the input will appear in a +corresponding element of the output. +If ``None``, the input will be raveled before computing the statistic.""" + .split('\n')) + + +def _get_axis_params(default_axis=0, _name=_name, _desc=_desc): # bind NOW + _type = f"int or None, default: {default_axis}" + _axis_parameter_doc = Parameter(_name, _type, _desc) + _axis_parameter = inspect.Parameter(_name, + inspect.Parameter.KEYWORD_ONLY, + default=default_axis) + return _axis_parameter_doc, _axis_parameter + + +_name = 'nan_policy' +_type = "{'propagate', 'omit', 'raise'}" +_desc = ( + """Defines how to handle input NaNs. + +- ``propagate``: if a NaN is present in the axis slice (e.g. row) along + which the statistic is computed, the corresponding entry of the output + will be NaN. +- ``omit``: NaNs will be omitted when performing the calculation. + If insufficient data remains in the axis slice along which the + statistic is computed, the corresponding entry of the output will be + NaN. +- ``raise``: if a NaN is present, a ``ValueError`` will be raised.""" + .split('\n')) +_nan_policy_parameter_doc = Parameter(_name, _type, _desc) +_nan_policy_parameter = inspect.Parameter(_name, + inspect.Parameter.KEYWORD_ONLY, + default='propagate') + +_name = 'keepdims' +_type = "bool, default: False" +_desc = ( + """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.""" + .split('\n')) +_keepdims_parameter_doc = Parameter(_name, _type, _desc) +_keepdims_parameter = inspect.Parameter(_name, + inspect.Parameter.KEYWORD_ONLY, + default=False) + +_standard_note_addition = ( + """\nBeginning in SciPy 1.9, ``np.matrix`` inputs (not recommended for new +code) are converted to ``np.ndarray`` before the calculation is performed. In +this case, the output will be a scalar or ``np.ndarray`` of appropriate shape +rather than a 2D ``np.matrix``. Similarly, while masked elements of masked +arrays are ignored, the output will be a scalar or ``np.ndarray`` rather than a +masked array with ``mask=False``.""").split('\n') + + +def _axis_nan_policy_factory(tuple_to_result, default_axis=0, + n_samples=1, paired=False, + result_to_tuple=None, too_small=0, + n_outputs=2, kwd_samples=(), override=None): + """Factory for a wrapper that adds axis/nan_policy params to a function. + + Parameters + ---------- + tuple_to_result : callable + Callable that returns an object of the type returned by the function + being wrapped (e.g. the namedtuple or dataclass returned by a + statistical test) provided the separate components (e.g. statistic, + pvalue). + default_axis : int, default: 0 + The default value of the axis argument. Standard is 0 except when + backwards compatibility demands otherwise (e.g. `None`). + n_samples : int or callable, default: 1 + The number of data samples accepted by the function + (e.g. `mannwhitneyu`), a callable that accepts a dictionary of + parameters passed into the function and returns the number of data + samples (e.g. `wilcoxon`), or `None` to indicate an arbitrary number + of samples (e.g. `kruskal`). + paired : {False, True} + Whether the function being wrapped treats the samples as paired (i.e. + corresponding elements of each sample should be considered as different + components of the same sample.) + result_to_tuple : callable, optional + Function that unpacks the results of the function being wrapped into + a tuple. This is essentially the inverse of `tuple_to_result`. Default + is `None`, which is appropriate for statistical tests that return a + statistic, pvalue tuple (rather than, e.g., a non-iterable datalass). + too_small : int or callable, default: 0 + The largest unnacceptably small sample for the function being wrapped. + For example, some functions require samples of size two or more or they + raise an error. This argument prevents the error from being raised when + input is not 1D and instead places a NaN in the corresponding element + of the result. If callable, it must accept a list of samples, axis, + and a dictionary of keyword arguments passed to the wrapper function as + arguments and return a bool indicating weather the samples passed are + too small. + n_outputs : int or callable, default: 2 + The number of outputs produced by the function given 1d sample(s). For + example, hypothesis tests that return a namedtuple or result object + with attributes ``statistic`` and ``pvalue`` use the default + ``n_outputs=2``; summary statistics with scalar output use + ``n_outputs=1``. Alternatively, may be a callable that accepts a + dictionary of arguments passed into the wrapped function and returns + the number of outputs corresponding with those arguments. + kwd_samples : sequence, default: () + The names of keyword parameters that should be treated as samples. For + example, `gmean` accepts as its first argument a sample `a` but + also `weights` as a fourth, optional keyword argument. In this case, we + use `n_samples=1` and kwd_samples=['weights']. + override : dict, default: {'vectorization': False, 'nan_propagation': True} + Pass a dictionary with ``'vectorization': True`` to ensure that the + decorator overrides the function's behavior for multimensional input. + Use ``'nan_propagation': False`` to ensure that the decorator does not + override the function's behavior for ``nan_policy='propagate'``. + """ + # Specify which existing behaviors the decorator must override + temp = override or {} + override = {'vectorization': False, + 'nan_propagation': True} + override.update(temp) + + if result_to_tuple is None: + def result_to_tuple(res): + return res + + # The only `result_to_tuple` that needs the second argument (number of + # outputs) is the one for `moment`, and this was realized very late. + # Rather than changing all `result_to_tuple` definitions, we wrap them + # here to accept a second argument if they don't already. + if len(inspect.signature(result_to_tuple).parameters) == 1: + def result_to_tuple(res, _, f=result_to_tuple): + return f(res) + + if not callable(too_small): + def is_too_small(samples, *ts_args, axis=-1, **ts_kwargs): + for sample in samples: + if sample.shape[axis] <= too_small: + return True + return False + else: + is_too_small = too_small + + def axis_nan_policy_decorator(hypotest_fun_in): + @wraps(hypotest_fun_in) + def axis_nan_policy_wrapper(*args, _no_deco=False, **kwds): + + if _no_deco: # for testing, decorator does nothing + return hypotest_fun_in(*args, **kwds) + + # For now, skip the decorator entirely if using array API. In the future, + # we'll probably want to use it for `keepdims`, `axis` tuples, etc. + if len(args) == 0: # extract sample from `kwds` if there are no `args` + used_kwd_samples = list(set(kwds).intersection(set(kwd_samples))) + temp = used_kwd_samples[:1] + else: + temp = args[0] + + if not is_numpy(array_namespace(temp)): + msg = ("Use of `nan_policy` and `keepdims` " + "is incompatible with non-NumPy arrays.") + if 'nan_policy' in kwds or 'keepdims' in kwds: + raise NotImplementedError(msg) + return hypotest_fun_in(*args, **kwds) + + # We need to be flexible about whether position or keyword + # arguments are used, but we need to make sure users don't pass + # both for the same parameter. To complicate matters, some + # functions accept samples with *args, and some functions already + # accept `axis` and `nan_policy` as positional arguments. + # The strategy is to make sure that there is no duplication + # between `args` and `kwds`, combine the two into `kwds`, then + # the samples, `nan_policy`, and `axis` from `kwds`, as they are + # dealt with separately. + + # Check for intersection between positional and keyword args + params = list(inspect.signature(hypotest_fun_in).parameters) + if n_samples is None: + # Give unique names to each positional sample argument + # Note that *args can't be provided as a keyword argument + params = [f"arg{i}" for i in range(len(args))] + params[1:] + + # raise if there are too many positional args + maxarg = (np.inf if inspect.getfullargspec(hypotest_fun_in).varargs + else len(inspect.getfullargspec(hypotest_fun_in).args)) + if len(args) > maxarg: # let the function raise the right error + hypotest_fun_in(*args, **kwds) + + # raise if multiple values passed for same parameter + d_args = dict(zip(params, args)) + intersection = set(d_args) & set(kwds) + if intersection: # let the function raise the right error + hypotest_fun_in(*args, **kwds) + + # Consolidate other positional and keyword args into `kwds` + kwds.update(d_args) + + # rename avoids UnboundLocalError + if callable(n_samples): + # Future refactoring idea: no need for callable n_samples. + # Just replace `n_samples` and `kwd_samples` with a single + # list of the names of all samples, and treat all of them + # as `kwd_samples` are treated below. + n_samp = n_samples(kwds) + else: + n_samp = n_samples or len(args) + + # get the number of outputs + n_out = n_outputs # rename to avoid UnboundLocalError + if callable(n_out): + n_out = n_out(kwds) + + # If necessary, rearrange function signature: accept other samples + # as positional args right after the first n_samp args + kwd_samp = [name for name in kwd_samples + if kwds.get(name, None) is not None] + n_kwd_samp = len(kwd_samp) + if not kwd_samp: + hypotest_fun_out = hypotest_fun_in + else: + def hypotest_fun_out(*samples, **kwds): + new_kwds = dict(zip(kwd_samp, samples[n_samp:])) + kwds.update(new_kwds) + return hypotest_fun_in(*samples[:n_samp], **kwds) + + # Extract the things we need here + try: # if something is missing + samples = [np.atleast_1d(kwds.pop(param)) + for param in (params[:n_samp] + kwd_samp)] + except KeyError: # let the function raise the right error + # might need to revisit this if required arg is not a "sample" + hypotest_fun_in(*args, **kwds) + vectorized = True if 'axis' in params else False + vectorized = vectorized and not override['vectorization'] + axis = kwds.pop('axis', default_axis) + nan_policy = kwds.pop('nan_policy', 'propagate') + keepdims = kwds.pop("keepdims", False) + del args # avoid the possibility of passing both `args` and `kwds` + + # convert masked arrays to regular arrays with sentinel values + samples, sentinel = _masked_arrays_2_sentinel_arrays(samples) + + # standardize to always work along last axis + reduced_axes = axis + if axis is None: + if samples: + # when axis=None, take the maximum of all dimensions since + # all the dimensions are reduced. + n_dims = np.max([sample.ndim for sample in samples]) + reduced_axes = tuple(range(n_dims)) + samples = [np.asarray(sample.ravel()) for sample in samples] + else: + # don't ignore any axes when broadcasting if paired + samples = _broadcast_arrays(samples, axis=axis if not paired else None) + axis = np.atleast_1d(axis) + n_axes = len(axis) + # move all axes in `axis` to the end to be raveled + samples = [np.moveaxis(sample, axis, range(-len(axis), 0)) + for sample in samples] + shapes = [sample.shape for sample in samples] + # New shape is unchanged for all axes _not_ in `axis` + # At the end, we append the product of the shapes of the axes + # in `axis`. Appending -1 doesn't work for zero-size arrays! + new_shapes = [shape[:-n_axes] + (np.prod(shape[-n_axes:]),) + for shape in shapes] + samples = [sample.reshape(new_shape) + for sample, new_shape in zip(samples, new_shapes)] + axis = -1 # work over the last axis + NaN = _get_nan(*samples) if samples else np.nan + + # if axis is not needed, just handle nan_policy and return + ndims = np.array([sample.ndim for sample in samples]) + if np.all(ndims <= 1): + # Addresses nan_policy == "raise" + if nan_policy != 'propagate' or override['nan_propagation']: + contains_nan = [_contains_nan(sample, nan_policy)[0] + for sample in samples] + else: + # Behave as though there are no NaNs (even if there are) + contains_nan = [False]*len(samples) + + # Addresses nan_policy == "propagate" + if any(contains_nan) and (nan_policy == 'propagate' + and override['nan_propagation']): + res = np.full(n_out, NaN) + res = _add_reduced_axes(res, reduced_axes, keepdims) + return tuple_to_result(*res) + + # Addresses nan_policy == "omit" + too_small_msg = too_small_1d_not_omit + if any(contains_nan) and nan_policy == 'omit': + # consider passing in contains_nan + samples = _remove_nans(samples, paired) + too_small_msg = too_small_1d_omit + + if sentinel: + samples = _remove_sentinel(samples, paired, sentinel) + + if is_too_small(samples, kwds): + warnings.warn(too_small_msg, SmallSampleWarning, stacklevel=2) + res = np.full(n_out, NaN) + res = _add_reduced_axes(res, reduced_axes, keepdims) + return tuple_to_result(*res) + + res = hypotest_fun_out(*samples, **kwds) + res = result_to_tuple(res, n_out) + res = _add_reduced_axes(res, reduced_axes, keepdims) + return tuple_to_result(*res) + + # check for empty input + empty_output = _check_empty_inputs(samples, axis) + # only return empty output if zero sized input is too small. + if ( + empty_output is not None + and (is_too_small(samples, kwds) or empty_output.size == 0) + ): + if is_too_small(samples, kwds) and empty_output.size != 0: + warnings.warn(too_small_nd_not_omit, SmallSampleWarning, + stacklevel=2) + res = [empty_output.copy() for i in range(n_out)] + res = _add_reduced_axes(res, reduced_axes, keepdims) + return tuple_to_result(*res) + + # otherwise, concatenate all samples along axis, remembering where + # each separate sample begins + lengths = np.array([sample.shape[axis] for sample in samples]) + split_indices = np.cumsum(lengths) + x = _broadcast_concatenate(samples, axis, paired=paired) + + # Addresses nan_policy == "raise" + if nan_policy != 'propagate' or override['nan_propagation']: + contains_nan, _ = _contains_nan(x, nan_policy) + else: + contains_nan = False # behave like there are no NaNs + + if vectorized and not contains_nan and not sentinel: + res = hypotest_fun_out(*samples, axis=axis, **kwds) + res = result_to_tuple(res, n_out) + res = _add_reduced_axes(res, reduced_axes, keepdims) + return tuple_to_result(*res) + + # Addresses nan_policy == "omit" + if contains_nan and nan_policy == 'omit': + def hypotest_fun(x): + samples = np.split(x, split_indices)[:n_samp+n_kwd_samp] + samples = _remove_nans(samples, paired) + if sentinel: + samples = _remove_sentinel(samples, paired, sentinel) + if is_too_small(samples, kwds): + warnings.warn(too_small_nd_omit, SmallSampleWarning, + stacklevel=4) + return np.full(n_out, NaN) + return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out) + + # Addresses nan_policy == "propagate" + elif (contains_nan and nan_policy == 'propagate' + and override['nan_propagation']): + def hypotest_fun(x): + if np.isnan(x).any(): + return np.full(n_out, NaN) + + samples = np.split(x, split_indices)[:n_samp+n_kwd_samp] + if sentinel: + samples = _remove_sentinel(samples, paired, sentinel) + if is_too_small(samples, kwds): + return np.full(n_out, NaN) + return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out) + + else: + def hypotest_fun(x): + samples = np.split(x, split_indices)[:n_samp+n_kwd_samp] + if sentinel: + samples = _remove_sentinel(samples, paired, sentinel) + if is_too_small(samples, kwds): + return np.full(n_out, NaN) + return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out) + + x = np.moveaxis(x, axis, 0) + res = np.apply_along_axis(hypotest_fun, axis=0, arr=x) + res = _add_reduced_axes(res, reduced_axes, keepdims) + return tuple_to_result(*res) + + _axis_parameter_doc, _axis_parameter = _get_axis_params(default_axis) + doc = FunctionDoc(axis_nan_policy_wrapper) + parameter_names = [param.name for param in doc['Parameters']] + if 'axis' in parameter_names: + doc['Parameters'][parameter_names.index('axis')] = ( + _axis_parameter_doc) + else: + doc['Parameters'].append(_axis_parameter_doc) + if 'nan_policy' in parameter_names: + doc['Parameters'][parameter_names.index('nan_policy')] = ( + _nan_policy_parameter_doc) + else: + doc['Parameters'].append(_nan_policy_parameter_doc) + if 'keepdims' in parameter_names: + doc['Parameters'][parameter_names.index('keepdims')] = ( + _keepdims_parameter_doc) + else: + doc['Parameters'].append(_keepdims_parameter_doc) + doc['Notes'] += _standard_note_addition + doc = str(doc).split("\n", 1)[1] # remove signature + axis_nan_policy_wrapper.__doc__ = str(doc) + + sig = inspect.signature(axis_nan_policy_wrapper) + parameters = sig.parameters + parameter_list = list(parameters.values()) + if 'axis' not in parameters: + parameter_list.append(_axis_parameter) + if 'nan_policy' not in parameters: + parameter_list.append(_nan_policy_parameter) + if 'keepdims' not in parameters: + parameter_list.append(_keepdims_parameter) + sig = sig.replace(parameters=parameter_list) + axis_nan_policy_wrapper.__signature__ = sig + + return axis_nan_policy_wrapper + return axis_nan_policy_decorator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_biasedurn.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_biasedurn.pxd new file mode 100644 index 0000000000000000000000000000000000000000..92785f08dbec30a4db286fcb85b42d7221e2228e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_biasedurn.pxd @@ -0,0 +1,27 @@ +# Declare the class with cdef +cdef extern from "biasedurn/stocc.h" nogil: + cdef cppclass CFishersNCHypergeometric: + CFishersNCHypergeometric(int, int, int, double, double) except + + int mode() + double mean() + double variance() + double probability(int x) + double moments(double * mean, double * var) + + cdef cppclass CWalleniusNCHypergeometric: + CWalleniusNCHypergeometric() except + + CWalleniusNCHypergeometric(int, int, int, double, double) except + + int mode() + double mean() + double variance() + double probability(int x) + double moments(double * mean, double * var) + + cdef cppclass StochasticLib3: + StochasticLib3(int seed) except + + double Random() except + + void SetAccuracy(double accur) + int FishersNCHyp (int n, int m, int N, double odds) except + + int WalleniusNCHyp (int n, int m, int N, double odds) except + + double(*next_double)() + double(*next_normal)(const double m, const double s) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_binned_statistic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_binned_statistic.py new file mode 100644 index 0000000000000000000000000000000000000000..c87492ce9e77dc2f11b3138f9294e421621a8292 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_binned_statistic.py @@ -0,0 +1,795 @@ +import builtins +from warnings import catch_warnings, simplefilter +import numpy as np +from operator import index +from collections import namedtuple + +__all__ = ['binned_statistic', + 'binned_statistic_2d', + 'binned_statistic_dd'] + + +BinnedStatisticResult = namedtuple('BinnedStatisticResult', + ('statistic', 'bin_edges', 'binnumber')) + + +def binned_statistic(x, values, statistic='mean', + bins=10, range=None): + """ + Compute a binned statistic for one or more sets of data. + + This is a generalization of a histogram function. A histogram divides + the space into bins, and returns the count of the number of points in + each bin. This function allows the computation of the sum, mean, median, + or other statistic of the values (or set of values) within each bin. + + Parameters + ---------- + x : (N,) array_like + A sequence of values to be binned. + values : (N,) array_like or list of (N,) array_like + The data on which the statistic will be computed. This must be + the same shape as `x`, or a set of sequences - each the same shape as + `x`. If `values` is a set of sequences, the statistic will be computed + on each independently. + statistic : string or callable, optional + The statistic to compute (default is 'mean'). + The following statistics are available: + + * 'mean' : compute the mean of values for points within each bin. + Empty bins will be represented by NaN. + * 'std' : compute the standard deviation within each bin. This + is implicitly calculated with ddof=0. + * 'median' : compute the median of values for points within each + bin. Empty bins will be represented by NaN. + * 'count' : compute the count of points within each bin. This is + identical to an unweighted histogram. `values` array is not + referenced. + * 'sum' : compute the sum of values for points within each bin. + This is identical to a weighted histogram. + * 'min' : compute the minimum of values for points within each bin. + Empty bins will be represented by NaN. + * 'max' : compute the maximum of values for point within each bin. + Empty bins will be represented by NaN. + * function : a user-defined function which takes a 1D array of + values, and outputs a single numerical statistic. This function + will be called on the values in each bin. Empty bins will be + represented by function([]), or NaN if this returns an error. + + bins : int or sequence of scalars, optional + If `bins` is an int, it defines the number of equal-width bins in the + given range (10 by default). If `bins` is a sequence, it defines the + bin edges, including the rightmost edge, allowing for non-uniform bin + widths. Values in `x` that are smaller than lowest bin edge are + assigned to bin number 0, values beyond the highest bin are assigned to + ``bins[-1]``. If the bin edges are specified, the number of bins will + be, (nx = len(bins)-1). + range : (float, float) or [(float, float)], optional + The lower and upper range of the bins. If not provided, range + is simply ``(x.min(), x.max())``. Values outside the range are + ignored. + + Returns + ------- + statistic : array + The values of the selected statistic in each bin. + bin_edges : array of dtype float + Return the bin edges ``(length(statistic)+1)``. + binnumber: 1-D ndarray of ints + Indices of the bins (corresponding to `bin_edges`) in which each value + of `x` belongs. Same length as `values`. A binnumber of `i` means the + corresponding value is between (bin_edges[i-1], bin_edges[i]). + + See Also + -------- + numpy.digitize, numpy.histogram, binned_statistic_2d, binned_statistic_dd + + Notes + ----- + All but the last (righthand-most) bin is half-open. In other words, if + `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1, + but excluding 2) and the second ``[2, 3)``. The last bin, however, is + ``[3, 4]``, which *includes* 4. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + First some basic examples: + + Create two evenly spaced bins in the range of the given sample, and sum the + corresponding values in each of those bins: + + >>> values = [1.0, 1.0, 2.0, 1.5, 3.0] + >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2) + BinnedStatisticResult(statistic=array([4. , 4.5]), + bin_edges=array([1., 4., 7.]), binnumber=array([1, 1, 1, 2, 2])) + + Multiple arrays of values can also be passed. The statistic is calculated + on each set independently: + + >>> values = [[1.0, 1.0, 2.0, 1.5, 3.0], [2.0, 2.0, 4.0, 3.0, 6.0]] + >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2) + BinnedStatisticResult(statistic=array([[4. , 4.5], + [8. , 9. ]]), bin_edges=array([1., 4., 7.]), + binnumber=array([1, 1, 1, 2, 2])) + + >>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean', + ... bins=3) + BinnedStatisticResult(statistic=array([1., 2., 4.]), + bin_edges=array([1., 2., 3., 4.]), + binnumber=array([1, 2, 1, 2, 3])) + + As a second example, we now generate some random data of sailing boat speed + as a function of wind speed, and then determine how fast our boat is for + certain wind speeds: + + >>> rng = np.random.default_rng() + >>> windspeed = 8 * rng.random(500) + >>> boatspeed = .3 * windspeed**.5 + .2 * rng.random(500) + >>> bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed, + ... boatspeed, statistic='median', bins=[1,2,3,4,5,6,7]) + >>> plt.figure() + >>> plt.plot(windspeed, boatspeed, 'b.', label='raw data') + >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5, + ... label='binned statistic of data') + >>> plt.legend() + + Now we can use ``binnumber`` to select all datapoints with a windspeed + below 1: + + >>> low_boatspeed = boatspeed[binnumber == 0] + + As a final example, we will use ``bin_edges`` and ``binnumber`` to make a + plot of a distribution that shows the mean and distribution around that + mean per bin, on top of a regular histogram and the probability + distribution function: + + >>> x = np.linspace(0, 5, num=500) + >>> x_pdf = stats.maxwell.pdf(x) + >>> samples = stats.maxwell.rvs(size=10000) + + >>> bin_means, bin_edges, binnumber = stats.binned_statistic(x, x_pdf, + ... statistic='mean', bins=25) + >>> bin_width = (bin_edges[1] - bin_edges[0]) + >>> bin_centers = bin_edges[1:] - bin_width/2 + + >>> plt.figure() + >>> plt.hist(samples, bins=50, density=True, histtype='stepfilled', + ... alpha=0.2, label='histogram of data') + >>> plt.plot(x, x_pdf, 'r-', label='analytical pdf') + >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=2, + ... label='binned statistic of data') + >>> plt.plot((binnumber - 0.5) * bin_width, x_pdf, 'g.', alpha=0.5) + >>> plt.legend(fontsize=10) + >>> plt.show() + + """ + try: + N = len(bins) + except TypeError: + N = 1 + + if N != 1: + bins = [np.asarray(bins, float)] + + if range is not None: + if len(range) == 2: + range = [range] + + medians, edges, binnumbers = binned_statistic_dd( + [x], values, statistic, bins, range) + + return BinnedStatisticResult(medians, edges[0], binnumbers) + + +BinnedStatistic2dResult = namedtuple('BinnedStatistic2dResult', + ('statistic', 'x_edge', 'y_edge', + 'binnumber')) + + +def binned_statistic_2d(x, y, values, statistic='mean', + bins=10, range=None, expand_binnumbers=False): + """ + Compute a bidimensional binned statistic for one or more sets of data. + + This is a generalization of a histogram2d function. A histogram divides + the space into bins, and returns the count of the number of points in + each bin. This function allows the computation of the sum, mean, median, + or other statistic of the values (or set of values) within each bin. + + Parameters + ---------- + x : (N,) array_like + A sequence of values to be binned along the first dimension. + y : (N,) array_like + A sequence of values to be binned along the second dimension. + values : (N,) array_like or list of (N,) array_like + The data on which the statistic will be computed. This must be + the same shape as `x`, or a list of sequences - each with the same + shape as `x`. If `values` is such a list, the statistic will be + computed on each independently. + statistic : string or callable, optional + The statistic to compute (default is 'mean'). + The following statistics are available: + + * 'mean' : compute the mean of values for points within each bin. + Empty bins will be represented by NaN. + * 'std' : compute the standard deviation within each bin. This + is implicitly calculated with ddof=0. + * 'median' : compute the median of values for points within each + bin. Empty bins will be represented by NaN. + * 'count' : compute the count of points within each bin. This is + identical to an unweighted histogram. `values` array is not + referenced. + * 'sum' : compute the sum of values for points within each bin. + This is identical to a weighted histogram. + * 'min' : compute the minimum of values for points within each bin. + Empty bins will be represented by NaN. + * 'max' : compute the maximum of values for point within each bin. + Empty bins will be represented by NaN. + * function : a user-defined function which takes a 1D array of + values, and outputs a single numerical statistic. This function + will be called on the values in each bin. Empty bins will be + represented by function([]), or NaN if this returns an error. + + bins : int or [int, int] or array_like or [array, array], optional + The bin specification: + + * the number of bins for the two dimensions (nx = ny = bins), + * the number of bins in each dimension (nx, ny = bins), + * the bin edges for the two dimensions (x_edge = y_edge = bins), + * the bin edges in each dimension (x_edge, y_edge = bins). + + If the bin edges are specified, the number of bins will be, + (nx = len(x_edge)-1, ny = len(y_edge)-1). + + range : (2,2) array_like, optional + The leftmost and rightmost edges of the bins along each dimension + (if not specified explicitly in the `bins` parameters): + [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be + considered outliers and not tallied in the histogram. + expand_binnumbers : bool, optional + 'False' (default): the returned `binnumber` is a shape (N,) array of + linearized bin indices. + 'True': the returned `binnumber` is 'unraveled' into a shape (2,N) + ndarray, where each row gives the bin numbers in the corresponding + dimension. + See the `binnumber` returned value, and the `Examples` section. + + .. versionadded:: 0.17.0 + + Returns + ------- + statistic : (nx, ny) ndarray + The values of the selected statistic in each two-dimensional bin. + x_edge : (nx + 1) ndarray + The bin edges along the first dimension. + y_edge : (ny + 1) ndarray + The bin edges along the second dimension. + binnumber : (N,) array of ints or (2,N) ndarray of ints + This assigns to each element of `sample` an integer that represents the + bin in which this observation falls. The representation depends on the + `expand_binnumbers` argument. See `Notes` for details. + + + See Also + -------- + numpy.digitize, numpy.histogram2d, binned_statistic, binned_statistic_dd + + Notes + ----- + Binedges: + All but the last (righthand-most) bin is half-open. In other words, if + `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1, + but excluding 2) and the second ``[2, 3)``. The last bin, however, is + ``[3, 4]``, which *includes* 4. + + `binnumber`: + This returned argument assigns to each element of `sample` an integer that + represents the bin in which it belongs. The representation depends on the + `expand_binnumbers` argument. If 'False' (default): The returned + `binnumber` is a shape (N,) array of linearized indices mapping each + element of `sample` to its corresponding bin (using row-major ordering). + Note that the returned linearized bin indices are used for an array with + extra bins on the outer binedges to capture values outside of the defined + bin bounds. + If 'True': The returned `binnumber` is a shape (2,N) ndarray where + each row indicates bin placements for each dimension respectively. In each + dimension, a binnumber of `i` means the corresponding value is between + (D_edge[i-1], D_edge[i]), where 'D' is either 'x' or 'y'. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> from scipy import stats + + Calculate the counts with explicit bin-edges: + + >>> x = [0.1, 0.1, 0.1, 0.6] + >>> y = [2.1, 2.6, 2.1, 2.1] + >>> binx = [0.0, 0.5, 1.0] + >>> biny = [2.0, 2.5, 3.0] + >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny]) + >>> ret.statistic + array([[2., 1.], + [1., 0.]]) + + The bin in which each sample is placed is given by the `binnumber` + returned parameter. By default, these are the linearized bin indices: + + >>> ret.binnumber + array([5, 6, 5, 9]) + + The bin indices can also be expanded into separate entries for each + dimension using the `expand_binnumbers` parameter: + + >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny], + ... expand_binnumbers=True) + >>> ret.binnumber + array([[1, 1, 1, 2], + [1, 2, 1, 1]]) + + Which shows that the first three elements belong in the xbin 1, and the + fourth into xbin 2; and so on for y. + + """ + + # This code is based on np.histogram2d + try: + N = len(bins) + except TypeError: + N = 1 + + if N != 1 and N != 2: + xedges = yedges = np.asarray(bins, float) + bins = [xedges, yedges] + + medians, edges, binnumbers = binned_statistic_dd( + [x, y], values, statistic, bins, range, + expand_binnumbers=expand_binnumbers) + + return BinnedStatistic2dResult(medians, edges[0], edges[1], binnumbers) + + +BinnedStatisticddResult = namedtuple('BinnedStatisticddResult', + ('statistic', 'bin_edges', + 'binnumber')) + + +def _bincount(x, weights): + if np.iscomplexobj(weights): + a = np.bincount(x, np.real(weights)) + b = np.bincount(x, np.imag(weights)) + z = a + b*1j + + else: + z = np.bincount(x, weights) + return z + + +def binned_statistic_dd(sample, values, statistic='mean', + bins=10, range=None, expand_binnumbers=False, + binned_statistic_result=None): + """ + Compute a multidimensional binned statistic for a set of data. + + This is a generalization of a histogramdd function. A histogram divides + the space into bins, and returns the count of the number of points in + each bin. This function allows the computation of the sum, mean, median, + or other statistic of the values within each bin. + + Parameters + ---------- + sample : array_like + Data to histogram passed as a sequence of N arrays of length D, or + as an (N,D) array. + values : (N,) array_like or list of (N,) array_like + The data on which the statistic will be computed. This must be + the same shape as `sample`, or a list of sequences - each with the + same shape as `sample`. If `values` is such a list, the statistic + will be computed on each independently. + statistic : string or callable, optional + The statistic to compute (default is 'mean'). + The following statistics are available: + + * 'mean' : compute the mean of values for points within each bin. + Empty bins will be represented by NaN. + * 'median' : compute the median of values for points within each + bin. Empty bins will be represented by NaN. + * 'count' : compute the count of points within each bin. This is + identical to an unweighted histogram. `values` array is not + referenced. + * 'sum' : compute the sum of values for points within each bin. + This is identical to a weighted histogram. + * 'std' : compute the standard deviation within each bin. This + is implicitly calculated with ddof=0. If the number of values + within a given bin is 0 or 1, the computed standard deviation value + will be 0 for the bin. + * 'min' : compute the minimum of values for points within each bin. + Empty bins will be represented by NaN. + * 'max' : compute the maximum of values for point within each bin. + Empty bins will be represented by NaN. + * function : a user-defined function which takes a 1D array of + values, and outputs a single numerical statistic. This function + will be called on the values in each bin. Empty bins will be + represented by function([]), or NaN if this returns an error. + + bins : sequence or positive int, optional + The bin specification must be in one of the following forms: + + * A sequence of arrays describing the bin edges along each dimension. + * The number of bins for each dimension (nx, ny, ... = bins). + * The number of bins for all dimensions (nx = ny = ... = bins). + range : sequence, optional + A sequence of lower and upper bin edges to be used if the edges are + not given explicitly in `bins`. Defaults to the minimum and maximum + values along each dimension. + expand_binnumbers : bool, optional + 'False' (default): the returned `binnumber` is a shape (N,) array of + linearized bin indices. + 'True': the returned `binnumber` is 'unraveled' into a shape (D,N) + ndarray, where each row gives the bin numbers in the corresponding + dimension. + See the `binnumber` returned value, and the `Examples` section of + `binned_statistic_2d`. + binned_statistic_result : binnedStatisticddResult + Result of a previous call to the function in order to reuse bin edges + and bin numbers with new values and/or a different statistic. + To reuse bin numbers, `expand_binnumbers` must have been set to False + (the default) + + .. versionadded:: 0.17.0 + + Returns + ------- + statistic : ndarray, shape(nx1, nx2, nx3,...) + The values of the selected statistic in each two-dimensional bin. + bin_edges : list of ndarrays + A list of D arrays describing the (nxi + 1) bin edges for each + dimension. + binnumber : (N,) array of ints or (D,N) ndarray of ints + This assigns to each element of `sample` an integer that represents the + bin in which this observation falls. The representation depends on the + `expand_binnumbers` argument. See `Notes` for details. + + + See Also + -------- + numpy.digitize, numpy.histogramdd, binned_statistic, binned_statistic_2d + + Notes + ----- + Binedges: + All but the last (righthand-most) bin is half-open in each dimension. In + other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is + ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The + last bin, however, is ``[3, 4]``, which *includes* 4. + + `binnumber`: + This returned argument assigns to each element of `sample` an integer that + represents the bin in which it belongs. The representation depends on the + `expand_binnumbers` argument. If 'False' (default): The returned + `binnumber` is a shape (N,) array of linearized indices mapping each + element of `sample` to its corresponding bin (using row-major ordering). + If 'True': The returned `binnumber` is a shape (D,N) ndarray where + each row indicates bin placements for each dimension respectively. In each + dimension, a binnumber of `i` means the corresponding value is between + (bin_edges[D][i-1], bin_edges[D][i]), for each dimension 'D'. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.mplot3d import Axes3D + + Take an array of 600 (x, y) coordinates as an example. + `binned_statistic_dd` can handle arrays of higher dimension `D`. But a plot + of dimension `D+1` is required. + + >>> mu = np.array([0., 1.]) + >>> sigma = np.array([[1., -0.5],[-0.5, 1.5]]) + >>> multinormal = stats.multivariate_normal(mu, sigma) + >>> data = multinormal.rvs(size=600, random_state=235412) + >>> data.shape + (600, 2) + + Create bins and count how many arrays fall in each bin: + + >>> N = 60 + >>> x = np.linspace(-3, 3, N) + >>> y = np.linspace(-3, 4, N) + >>> ret = stats.binned_statistic_dd(data, np.arange(600), bins=[x, y], + ... statistic='count') + >>> bincounts = ret.statistic + + Set the volume and the location of bars: + + >>> dx = x[1] - x[0] + >>> dy = y[1] - y[0] + >>> x, y = np.meshgrid(x[:-1]+dx/2, y[:-1]+dy/2) + >>> z = 0 + + >>> bincounts = bincounts.ravel() + >>> x = x.ravel() + >>> y = y.ravel() + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111, projection='3d') + >>> with np.errstate(divide='ignore'): # silence random axes3d warning + ... ax.bar3d(x, y, z, dx, dy, bincounts) + + Reuse bin numbers and bin edges with new values: + + >>> ret2 = stats.binned_statistic_dd(data, -np.arange(600), + ... binned_statistic_result=ret, + ... statistic='mean') + """ + known_stats = ['mean', 'median', 'count', 'sum', 'std', 'min', 'max'] + if not callable(statistic) and statistic not in known_stats: + raise ValueError(f'invalid statistic {statistic!r}') + + try: + bins = index(bins) + except TypeError: + # bins is not an integer + pass + # If bins was an integer-like object, now it is an actual Python int. + + # NOTE: for _bin_edges(), see e.g. gh-11365 + if isinstance(bins, int) and not np.isfinite(sample).all(): + raise ValueError(f'{sample!r} contains non-finite values.') + + # `Ndim` is the number of dimensions (e.g. `2` for `binned_statistic_2d`) + # `Dlen` is the length of elements along each dimension. + # This code is based on np.histogramdd + try: + # `sample` is an ND-array. + Dlen, Ndim = sample.shape + except (AttributeError, ValueError): + # `sample` is a sequence of 1D arrays. + sample = np.atleast_2d(sample).T + Dlen, Ndim = sample.shape + + # Store initial shape of `values` to preserve it in the output + values = np.asarray(values) + input_shape = list(values.shape) + # Make sure that `values` is 2D to iterate over rows + values = np.atleast_2d(values) + Vdim, Vlen = values.shape + + # Make sure `values` match `sample` + if statistic != 'count' and Vlen != Dlen: + raise AttributeError('The number of `values` elements must match the ' + 'length of each `sample` dimension.') + + try: + M = len(bins) + if M != Ndim: + raise AttributeError('The dimension of bins must be equal ' + 'to the dimension of the sample x.') + except TypeError: + bins = Ndim * [bins] + + if binned_statistic_result is None: + nbin, edges, dedges = _bin_edges(sample, bins, range) + binnumbers = _bin_numbers(sample, nbin, edges, dedges) + else: + edges = binned_statistic_result.bin_edges + nbin = np.array([len(edges[i]) + 1 for i in builtins.range(Ndim)]) + # +1 for outlier bins + dedges = [np.diff(edges[i]) for i in builtins.range(Ndim)] + binnumbers = binned_statistic_result.binnumber + + # Avoid overflow with double precision. Complex `values` -> `complex128`. + result_type = np.result_type(values, np.float64) + result = np.empty([Vdim, nbin.prod()], dtype=result_type) + + if statistic in {'mean', np.mean}: + result.fill(np.nan) + flatcount = _bincount(binnumbers, None) + a = flatcount.nonzero() + for vv in builtins.range(Vdim): + flatsum = _bincount(binnumbers, values[vv]) + result[vv, a] = flatsum[a] / flatcount[a] + elif statistic in {'std', np.std}: + result.fill(np.nan) + flatcount = _bincount(binnumbers, None) + a = flatcount.nonzero() + for vv in builtins.range(Vdim): + flatsum = _bincount(binnumbers, values[vv]) + delta = values[vv] - flatsum[binnumbers] / flatcount[binnumbers] + std = np.sqrt( + _bincount(binnumbers, delta*np.conj(delta))[a] / flatcount[a] + ) + result[vv, a] = std + result = np.real(result) + elif statistic == 'count': + result = np.empty([Vdim, nbin.prod()], dtype=np.float64) + result.fill(0) + flatcount = _bincount(binnumbers, None) + a = np.arange(len(flatcount)) + result[:, a] = flatcount[np.newaxis, :] + elif statistic in {'sum', np.sum}: + result.fill(0) + for vv in builtins.range(Vdim): + flatsum = _bincount(binnumbers, values[vv]) + a = np.arange(len(flatsum)) + result[vv, a] = flatsum + elif statistic in {'median', np.median}: + result.fill(np.nan) + for vv in builtins.range(Vdim): + i = np.lexsort((values[vv], binnumbers)) + _, j, counts = np.unique(binnumbers[i], + return_index=True, return_counts=True) + mid = j + (counts - 1) / 2 + mid_a = values[vv, i][np.floor(mid).astype(int)] + mid_b = values[vv, i][np.ceil(mid).astype(int)] + medians = (mid_a + mid_b) / 2 + result[vv, binnumbers[i][j]] = medians + elif statistic in {'min', np.min}: + result.fill(np.nan) + for vv in builtins.range(Vdim): + i = np.argsort(values[vv])[::-1] # Reversed so the min is last + result[vv, binnumbers[i]] = values[vv, i] + elif statistic in {'max', np.max}: + result.fill(np.nan) + for vv in builtins.range(Vdim): + i = np.argsort(values[vv]) + result[vv, binnumbers[i]] = values[vv, i] + elif callable(statistic): + with np.errstate(invalid='ignore'), catch_warnings(): + simplefilter("ignore", RuntimeWarning) + try: + null = statistic([]) + except Exception: + null = np.nan + if np.iscomplexobj(null): + result = result.astype(np.complex128) + result.fill(null) + try: + _calc_binned_statistic( + Vdim, binnumbers, result, values, statistic + ) + except ValueError: + result = result.astype(np.complex128) + _calc_binned_statistic( + Vdim, binnumbers, result, values, statistic + ) + + # Shape into a proper matrix + result = result.reshape(np.append(Vdim, nbin)) + + # Remove outliers (indices 0 and -1 for each bin-dimension). + core = tuple([slice(None)] + Ndim * [slice(1, -1)]) + result = result[core] + + # Unravel binnumbers into an ndarray, each row the bins for each dimension + if expand_binnumbers and Ndim > 1: + binnumbers = np.asarray(np.unravel_index(binnumbers, nbin)) + + if np.any(result.shape[1:] != nbin - 2): + raise RuntimeError('Internal Shape Error') + + # Reshape to have output (`result`) match input (`values`) shape + result = result.reshape(input_shape[:-1] + list(nbin-2)) + + return BinnedStatisticddResult(result, edges, binnumbers) + + +def _calc_binned_statistic(Vdim, bin_numbers, result, values, stat_func): + unique_bin_numbers = np.unique(bin_numbers) + for vv in builtins.range(Vdim): + bin_map = _create_binned_data(bin_numbers, unique_bin_numbers, + values, vv) + for i in unique_bin_numbers: + stat = stat_func(np.array(bin_map[i])) + if np.iscomplexobj(stat) and not np.iscomplexobj(result): + raise ValueError("The statistic function returns complex ") + result[vv, i] = stat + + +def _create_binned_data(bin_numbers, unique_bin_numbers, values, vv): + """ Create hashmap of bin ids to values in bins + key: bin number + value: list of binned data + """ + bin_map = dict() + for i in unique_bin_numbers: + bin_map[i] = [] + for i in builtins.range(len(bin_numbers)): + bin_map[bin_numbers[i]].append(values[vv, i]) + return bin_map + + +def _bin_edges(sample, bins=None, range=None): + """ Create edge arrays + """ + Dlen, Ndim = sample.shape + + nbin = np.empty(Ndim, int) # Number of bins in each dimension + edges = Ndim * [None] # Bin edges for each dim (will be 2D array) + dedges = Ndim * [None] # Spacing between edges (will be 2D array) + + # Select range for each dimension + # Used only if number of bins is given. + if range is None: + smin = np.atleast_1d(np.array(sample.min(axis=0), float)) + smax = np.atleast_1d(np.array(sample.max(axis=0), float)) + else: + if len(range) != Ndim: + raise ValueError( + f"range given for {len(range)} dimensions; {Ndim} required") + smin = np.empty(Ndim) + smax = np.empty(Ndim) + for i in builtins.range(Ndim): + if range[i][1] < range[i][0]: + raise ValueError( + f"In {f'dimension {i + 1} of ' if Ndim > 1 else ''}range," + " start must be <= stop") + smin[i], smax[i] = range[i] + + # Make sure the bins have a finite width. + for i in builtins.range(len(smin)): + if smin[i] == smax[i]: + smin[i] = smin[i] - .5 + smax[i] = smax[i] + .5 + + # Preserve sample floating point precision in bin edges + edges_dtype = (sample.dtype if np.issubdtype(sample.dtype, np.floating) + else float) + + # Create edge arrays + for i in builtins.range(Ndim): + if np.isscalar(bins[i]): + nbin[i] = bins[i] + 2 # +2 for outlier bins + edges[i] = np.linspace(smin[i], smax[i], nbin[i] - 1, + dtype=edges_dtype) + else: + edges[i] = np.asarray(bins[i], edges_dtype) + nbin[i] = len(edges[i]) + 1 # +1 for outlier bins + dedges[i] = np.diff(edges[i]) + + nbin = np.asarray(nbin) + + return nbin, edges, dedges + + +def _bin_numbers(sample, nbin, edges, dedges): + """Compute the bin number each sample falls into, in each dimension + """ + Dlen, Ndim = sample.shape + + sampBin = [ + np.digitize(sample[:, i], edges[i]) + for i in range(Ndim) + ] + + # Using `digitize`, values that fall on an edge are put in the right bin. + # For the rightmost bin, we want values equal to the right + # edge to be counted in the last bin, and not as an outlier. + for i in range(Ndim): + # Find the rounding precision + dedges_min = dedges[i].min() + if dedges_min == 0: + raise ValueError('The smallest edge difference is numerically 0.') + decimal = int(-np.log10(dedges_min)) + 6 + # Find which points are on the rightmost edge. + on_edge = np.where((sample[:, i] >= edges[i][-1]) & + (np.around(sample[:, i], decimal) == + np.around(edges[i][-1], decimal)))[0] + # Shift these points one bin to the left. + sampBin[i][on_edge] -= 1 + + # Compute the sample indices in the flattened statistic matrix. + binnumbers = np.ravel_multi_index(sampBin, nbin) + + return binnumbers diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_binomtest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_binomtest.py new file mode 100644 index 0000000000000000000000000000000000000000..bdf21117383374e730ab052fcbb0b5b7fca029c1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_binomtest.py @@ -0,0 +1,375 @@ +from math import sqrt +import numpy as np +from scipy._lib._util import _validate_int +from scipy.optimize import brentq +from scipy.special import ndtri +from ._discrete_distns import binom +from ._common import ConfidenceInterval + + +class BinomTestResult: + """ + Result of `scipy.stats.binomtest`. + + Attributes + ---------- + k : int + The number of successes (copied from `binomtest` input). + n : int + The number of trials (copied from `binomtest` input). + alternative : str + Indicates the alternative hypothesis specified in the input + to `binomtest`. It will be one of ``'two-sided'``, ``'greater'``, + or ``'less'``. + statistic: float + The estimate of the proportion of successes. + pvalue : float + The p-value of the hypothesis test. + + """ + def __init__(self, k, n, alternative, statistic, pvalue): + self.k = k + self.n = n + self.alternative = alternative + self.statistic = statistic + self.pvalue = pvalue + + # add alias for backward compatibility + self.proportion_estimate = statistic + + def __repr__(self): + s = ("BinomTestResult(" + f"k={self.k}, " + f"n={self.n}, " + f"alternative={self.alternative!r}, " + f"statistic={self.statistic}, " + f"pvalue={self.pvalue})") + return s + + def proportion_ci(self, confidence_level=0.95, method='exact'): + """ + Compute the confidence interval for ``statistic``. + + Parameters + ---------- + confidence_level : float, optional + Confidence level for the computed confidence interval + of the estimated proportion. Default is 0.95. + method : {'exact', 'wilson', 'wilsoncc'}, optional + Selects the method used to compute the confidence interval + for the estimate of the proportion: + + 'exact' : + Use the Clopper-Pearson exact method [1]_. + 'wilson' : + Wilson's method, without continuity correction ([2]_, [3]_). + 'wilsoncc' : + Wilson's method, with continuity correction ([2]_, [3]_). + + Default is ``'exact'``. + + Returns + ------- + ci : ``ConfidenceInterval`` object + The object has attributes ``low`` and ``high`` that hold the + lower and upper bounds of the confidence interval. + + References + ---------- + .. [1] C. J. Clopper and E. S. Pearson, The use of confidence or + fiducial limits illustrated in the case of the binomial, + Biometrika, Vol. 26, No. 4, pp 404-413 (Dec. 1934). + .. [2] E. B. Wilson, Probable inference, the law of succession, and + statistical inference, J. Amer. Stat. Assoc., 22, pp 209-212 + (1927). + .. [3] Robert G. Newcombe, Two-sided confidence intervals for the + single proportion: comparison of seven methods, Statistics + in Medicine, 17, pp 857-872 (1998). + + Examples + -------- + >>> from scipy.stats import binomtest + >>> result = binomtest(k=7, n=50, p=0.1) + >>> result.statistic + 0.14 + >>> result.proportion_ci() + ConfidenceInterval(low=0.05819170033997342, high=0.26739600249700846) + """ + if method not in ('exact', 'wilson', 'wilsoncc'): + raise ValueError(f"method ('{method}') must be one of 'exact', " + "'wilson' or 'wilsoncc'.") + if not (0 <= confidence_level <= 1): + raise ValueError(f'confidence_level ({confidence_level}) must be in ' + 'the interval [0, 1].') + if method == 'exact': + low, high = _binom_exact_conf_int(self.k, self.n, + confidence_level, + self.alternative) + else: + # method is 'wilson' or 'wilsoncc' + low, high = _binom_wilson_conf_int(self.k, self.n, + confidence_level, + self.alternative, + correction=method == 'wilsoncc') + return ConfidenceInterval(low=low, high=high) + + +def _findp(func): + try: + p = brentq(func, 0, 1) + except RuntimeError: + raise RuntimeError('numerical solver failed to converge when ' + 'computing the confidence limits') from None + except ValueError as exc: + raise ValueError('brentq raised a ValueError; report this to the ' + 'SciPy developers') from exc + return p + + +def _binom_exact_conf_int(k, n, confidence_level, alternative): + """ + Compute the estimate and confidence interval for the binomial test. + + Returns proportion, prop_low, prop_high + """ + if alternative == 'two-sided': + alpha = (1 - confidence_level) / 2 + if k == 0: + plow = 0.0 + else: + plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha) + if k == n: + phigh = 1.0 + else: + phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha) + elif alternative == 'less': + alpha = 1 - confidence_level + plow = 0.0 + if k == n: + phigh = 1.0 + else: + phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha) + elif alternative == 'greater': + alpha = 1 - confidence_level + if k == 0: + plow = 0.0 + else: + plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha) + phigh = 1.0 + return plow, phigh + + +def _binom_wilson_conf_int(k, n, confidence_level, alternative, correction): + # This function assumes that the arguments have already been validated. + # In particular, `alternative` must be one of 'two-sided', 'less' or + # 'greater'. + p = k / n + if alternative == 'two-sided': + z = ndtri(0.5 + 0.5*confidence_level) + else: + z = ndtri(confidence_level) + + # For reference, the formulas implemented here are from + # Newcombe (1998) (ref. [3] in the proportion_ci docstring). + denom = 2*(n + z**2) + center = (2*n*p + z**2)/denom + q = 1 - p + if correction: + if alternative == 'less' or k == 0: + lo = 0.0 + else: + dlo = (1 + z*sqrt(z**2 - 2 - 1/n + 4*p*(n*q + 1))) / denom + lo = center - dlo + if alternative == 'greater' or k == n: + hi = 1.0 + else: + dhi = (1 + z*sqrt(z**2 + 2 - 1/n + 4*p*(n*q - 1))) / denom + hi = center + dhi + else: + delta = z/denom * sqrt(4*n*p*q + z**2) + if alternative == 'less' or k == 0: + lo = 0.0 + else: + lo = center - delta + if alternative == 'greater' or k == n: + hi = 1.0 + else: + hi = center + delta + + return lo, hi + + +def binomtest(k, n, p=0.5, alternative='two-sided'): + """ + Perform a test that the probability of success is p. + + The binomial test [1]_ is a test of the null hypothesis that the + probability of success in a Bernoulli experiment is `p`. + + Details of the test can be found in many texts on statistics, such + as section 24.5 of [2]_. + + Parameters + ---------- + k : int + The number of successes. + n : int + The number of trials. + p : float, optional + The hypothesized probability of success, i.e. the expected + proportion of successes. The value must be in the interval + ``0 <= p <= 1``. The default value is ``p = 0.5``. + alternative : {'two-sided', 'greater', 'less'}, optional + Indicates the alternative hypothesis. The default value is + 'two-sided'. + + Returns + ------- + result : `~scipy.stats._result_classes.BinomTestResult` instance + The return value is an object with the following attributes: + + k : int + The number of successes (copied from `binomtest` input). + n : int + The number of trials (copied from `binomtest` input). + alternative : str + Indicates the alternative hypothesis specified in the input + to `binomtest`. It will be one of ``'two-sided'``, ``'greater'``, + or ``'less'``. + statistic : float + The estimate of the proportion of successes. + pvalue : float + The p-value of the hypothesis test. + + The object has the following methods: + + proportion_ci(confidence_level=0.95, method='exact') : + Compute the confidence interval for ``statistic``. + + Notes + ----- + .. versionadded:: 1.7.0 + + References + ---------- + .. [1] Binomial test, https://en.wikipedia.org/wiki/Binomial_test + .. [2] Jerrold H. Zar, Biostatistical Analysis (fifth edition), + Prentice Hall, Upper Saddle River, New Jersey USA (2010) + + Examples + -------- + >>> from scipy.stats import binomtest + + A car manufacturer claims that no more than 10% of their cars are unsafe. + 15 cars are inspected for safety, 3 were found to be unsafe. Test the + manufacturer's claim: + + >>> result = binomtest(3, n=15, p=0.1, alternative='greater') + >>> result.pvalue + 0.18406106910639114 + + The null hypothesis cannot be rejected at the 5% level of significance + because the returned p-value is greater than the critical value of 5%. + + The test statistic is equal to the estimated proportion, which is simply + ``3/15``: + + >>> result.statistic + 0.2 + + We can use the `proportion_ci()` method of the result to compute the + confidence interval of the estimate: + + >>> result.proportion_ci(confidence_level=0.95) + ConfidenceInterval(low=0.05684686759024681, high=1.0) + + """ + k = _validate_int(k, 'k', minimum=0) + n = _validate_int(n, 'n', minimum=1) + if k > n: + raise ValueError(f'k ({k}) must not be greater than n ({n}).') + + if not (0 <= p <= 1): + raise ValueError(f"p ({p}) must be in range [0,1]") + + if alternative not in ('two-sided', 'less', 'greater'): + raise ValueError(f"alternative ('{alternative}') not recognized; \n" + "must be 'two-sided', 'less' or 'greater'") + if alternative == 'less': + pval = binom.cdf(k, n, p) + elif alternative == 'greater': + pval = binom.sf(k-1, n, p) + else: + # alternative is 'two-sided' + d = binom.pmf(k, n, p) + rerr = 1 + 1e-7 + if k == p * n: + # special case as shortcut, would also be handled by `else` below + pval = 1. + elif k < p * n: + ix = _binary_search_for_binom_tst(lambda x1: -binom.pmf(x1, n, p), + -d*rerr, np.ceil(p * n), n) + # y is the number of terms between mode and n that are <= d*rerr. + # ix gave us the first term where a(ix) <= d*rerr < a(ix-1) + # if the first equality doesn't hold, y=n-ix. Otherwise, we + # need to include ix as well as the equality holds. Note that + # the equality will hold in very very rare situations due to rerr. + y = n - ix + int(d*rerr == binom.pmf(ix, n, p)) + pval = binom.cdf(k, n, p) + binom.sf(n - y, n, p) + else: + ix = _binary_search_for_binom_tst(lambda x1: binom.pmf(x1, n, p), + d*rerr, 0, np.floor(p * n)) + # y is the number of terms between 0 and mode that are <= d*rerr. + # we need to add a 1 to account for the 0 index. + # For comparing this with old behavior, see + # tst_binary_srch_for_binom_tst method in test_morestats. + y = ix + 1 + pval = binom.cdf(y-1, n, p) + binom.sf(k-1, n, p) + + pval = min(1.0, pval) + + result = BinomTestResult(k=k, n=n, alternative=alternative, + statistic=k/n, pvalue=pval) + return result + + +def _binary_search_for_binom_tst(a, d, lo, hi): + """ + Conducts an implicit binary search on a function specified by `a`. + + Meant to be used on the binomial PMF for the case of two-sided tests + to obtain the value on the other side of the mode where the tail + probability should be computed. The values on either side of + the mode are always in order, meaning binary search is applicable. + + Parameters + ---------- + a : callable + The function over which to perform binary search. Its values + for inputs lo and hi should be in ascending order. + d : float + The value to search. + lo : int + The lower end of range to search. + hi : int + The higher end of the range to search. + + Returns + ------- + int + The index, i between lo and hi + such that a(i)<=d d: + hi = mid-1 + else: + return mid + if a(lo) <= d: + return lo + else: + return lo-1 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_bws_test.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_bws_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6496ecfba798dc7ad719f784a57896e296590675 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_bws_test.py @@ -0,0 +1,177 @@ +import numpy as np +from functools import partial +from scipy import stats + + +def _bws_input_validation(x, y, alternative, method): + ''' Input validation and standardization for bws test''' + x, y = np.atleast_1d(x, y) + if x.ndim > 1 or y.ndim > 1: + raise ValueError('`x` and `y` must be exactly one-dimensional.') + if np.isnan(x).any() or np.isnan(y).any(): + raise ValueError('`x` and `y` must not contain NaNs.') + if np.size(x) == 0 or np.size(y) == 0: + raise ValueError('`x` and `y` must be of nonzero size.') + + z = stats.rankdata(np.concatenate((x, y))) + x, y = z[:len(x)], z[len(x):] + + alternatives = {'two-sided', 'less', 'greater'} + alternative = alternative.lower() + if alternative not in alternatives: + raise ValueError(f'`alternative` must be one of {alternatives}.') + + method = stats.PermutationMethod() if method is None else method + if not isinstance(method, stats.PermutationMethod): + raise ValueError('`method` must be an instance of ' + '`scipy.stats.PermutationMethod`') + + return x, y, alternative, method + + +def _bws_statistic(x, y, alternative, axis): + '''Compute the BWS test statistic for two independent samples''' + # Public function currently does not accept `axis`, but `permutation_test` + # uses `axis` to make vectorized call. + + Ri, Hj = np.sort(x, axis=axis), np.sort(y, axis=axis) + n, m = Ri.shape[axis], Hj.shape[axis] + i, j = np.arange(1, n+1), np.arange(1, m+1) + + Bx_num = Ri - (m + n)/n * i + By_num = Hj - (m + n)/m * j + + if alternative == 'two-sided': + Bx_num *= Bx_num + By_num *= By_num + else: + Bx_num *= np.abs(Bx_num) + By_num *= np.abs(By_num) + + Bx_den = i/(n+1) * (1 - i/(n+1)) * m*(m+n)/n + By_den = j/(m+1) * (1 - j/(m+1)) * n*(m+n)/m + + Bx = 1/n * np.sum(Bx_num/Bx_den, axis=axis) + By = 1/m * np.sum(By_num/By_den, axis=axis) + + B = (Bx + By) / 2 if alternative == 'two-sided' else (Bx - By) / 2 + + return B + + +def bws_test(x, y, *, alternative="two-sided", method=None): + r'''Perform the Baumgartner-Weiss-Schindler test on two independent samples. + + The Baumgartner-Weiss-Schindler (BWS) test is a nonparametric test of + the null hypothesis that the distribution underlying sample `x` + is the same as the distribution underlying sample `y`. Unlike + the Kolmogorov-Smirnov, Wilcoxon, and Cramer-Von Mises tests, + the BWS test weights the integral by the variance of the difference + in cumulative distribution functions (CDFs), emphasizing the tails of the + distributions, which increases the power of the test in many applications. + + Parameters + ---------- + x, y : array-like + 1-d arrays of samples. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + Let *F(u)* and *G(u)* be the cumulative distribution functions of the + distributions underlying `x` and `y`, respectively. Then the following + alternative hypotheses are available: + + * 'two-sided': the distributions are not equal, i.e. *F(u) ≠ G(u)* for + at least one *u*. + * 'less': the distribution underlying `x` is stochastically less than + the distribution underlying `y`, i.e. *F(u) >= G(u)* for all *u*. + * 'greater': the distribution underlying `x` is stochastically greater + than the distribution underlying `y`, i.e. *F(u) <= G(u)* for all + *u*. + + Under a more restrictive set of assumptions, the alternative hypotheses + can be expressed in terms of the locations of the distributions; + see [2] section 5.1. + method : PermutationMethod, optional + Configures the method used to compute the p-value. The default is + the default `PermutationMethod` object. + + Returns + ------- + res : PermutationTestResult + An object with attributes: + + statistic : float + The observed test statistic of the data. + pvalue : float + The p-value for the given alternative. + null_distribution : ndarray + The values of the test statistic generated under the null hypothesis. + + See also + -------- + scipy.stats.wilcoxon, scipy.stats.mannwhitneyu, scipy.stats.ttest_ind + + Notes + ----- + When ``alternative=='two-sided'``, the statistic is defined by the + equations given in [1]_ Section 2. This statistic is not appropriate for + one-sided alternatives; in that case, the statistic is the *negative* of + that given by the equations in [1]_ Section 2. Consequently, when the + distribution of the first sample is stochastically greater than that of the + second sample, the statistic will tend to be positive. + + References + ---------- + .. [1] Neuhäuser, M. (2005). Exact Tests Based on the + Baumgartner-Weiss-Schindler Statistic: A Survey. Statistical Papers, + 46(1), 1-29. + .. [2] Fay, M. P., & Proschan, M. A. (2010). Wilcoxon-Mann-Whitney or t-test? + On assumptions for hypothesis tests and multiple interpretations of + decision rules. Statistics surveys, 4, 1. + + Examples + -------- + We follow the example of table 3 in [1]_: Fourteen children were divided + randomly into two groups. Their ranks at performing a specific tests are + as follows. + + >>> import numpy as np + >>> x = [1, 2, 3, 4, 6, 7, 8] + >>> y = [5, 9, 10, 11, 12, 13, 14] + + We use the BWS test to assess whether there is a statistically significant + difference between the two groups. + The null hypothesis is that there is no difference in the distributions of + performance between the two groups. We decide that a significance level of + 1% is required to reject the null hypothesis in favor of the alternative + that the distributions are different. + Since the number of samples is very small, we can compare the observed test + statistic against the *exact* distribution of the test statistic under the + null hypothesis. + + >>> from scipy.stats import bws_test + >>> res = bws_test(x, y) + >>> print(res.statistic) + 5.132167152575315 + + This agrees with :math:`B = 5.132` reported in [1]_. The *p*-value produced + by `bws_test` also agrees with :math:`p = 0.0029` reported in [1]_. + + >>> print(res.pvalue) + 0.002913752913752914 + + Because the p-value is below our threshold of 1%, we take this as evidence + against the null hypothesis in favor of the alternative that there is a + difference in performance between the two groups. + ''' + + x, y, alternative, method = _bws_input_validation(x, y, alternative, + method) + bws_statistic = partial(_bws_statistic, alternative=alternative) + + permutation_alternative = 'less' if alternative == 'less' else 'greater' + res = stats.permutation_test((x, y), bws_statistic, + alternative=permutation_alternative, + **method._asdict()) + + return res diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_censored_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_censored_data.py new file mode 100644 index 0000000000000000000000000000000000000000..f6fee500f1d97db0bae9ebff26824d4d894c7f39 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_censored_data.py @@ -0,0 +1,459 @@ +import numpy as np + + +def _validate_1d(a, name, allow_inf=False): + if np.ndim(a) != 1: + raise ValueError(f'`{name}` must be a one-dimensional sequence.') + if np.isnan(a).any(): + raise ValueError(f'`{name}` must not contain nan.') + if not allow_inf and np.isinf(a).any(): + raise ValueError(f'`{name}` must contain only finite values.') + + +def _validate_interval(interval): + interval = np.asarray(interval) + if interval.shape == (0,): + # The input was a sequence with length 0. + interval = interval.reshape((0, 2)) + if interval.ndim != 2 or interval.shape[-1] != 2: + raise ValueError('`interval` must be a two-dimensional array with ' + 'shape (m, 2), where m is the number of ' + 'interval-censored values, but got shape ' + f'{interval.shape}') + + if np.isnan(interval).any(): + raise ValueError('`interval` must not contain nan.') + if np.isinf(interval).all(axis=1).any(): + raise ValueError('In each row in `interval`, both values must not' + ' be infinite.') + if (interval[:, 0] > interval[:, 1]).any(): + raise ValueError('In each row of `interval`, the left value must not' + ' exceed the right value.') + + uncensored_mask = interval[:, 0] == interval[:, 1] + left_mask = np.isinf(interval[:, 0]) + right_mask = np.isinf(interval[:, 1]) + interval_mask = np.isfinite(interval).all(axis=1) & ~uncensored_mask + + uncensored2 = interval[uncensored_mask, 0] + left2 = interval[left_mask, 1] + right2 = interval[right_mask, 0] + interval2 = interval[interval_mask] + + return uncensored2, left2, right2, interval2 + + +def _validate_x_censored(x, censored): + x = np.asarray(x) + if x.ndim != 1: + raise ValueError('`x` must be one-dimensional.') + censored = np.asarray(censored) + if censored.ndim != 1: + raise ValueError('`censored` must be one-dimensional.') + if (~np.isfinite(x)).any(): + raise ValueError('`x` must not contain nan or inf.') + if censored.size != x.size: + raise ValueError('`x` and `censored` must have the same length.') + return x, censored.astype(bool) + + +class CensoredData: + """ + Instances of this class represent censored data. + + Instances may be passed to the ``fit`` method of continuous + univariate SciPy distributions for maximum likelihood estimation. + The *only* method of the univariate continuous distributions that + understands `CensoredData` is the ``fit`` method. An instance of + `CensoredData` can not be passed to methods such as ``pdf`` and + ``cdf``. + + An observation is said to be *censored* when the precise value is unknown, + but it has a known upper and/or lower bound. The conventional terminology + is: + + * left-censored: an observation is below a certain value but it is + unknown by how much. + * right-censored: an observation is above a certain value but it is + unknown by how much. + * interval-censored: an observation lies somewhere on an interval between + two values. + + Left-, right-, and interval-censored data can be represented by + `CensoredData`. + + For convenience, the class methods ``left_censored`` and + ``right_censored`` are provided to create a `CensoredData` + instance from a single one-dimensional array of measurements + and a corresponding boolean array to indicate which measurements + are censored. The class method ``interval_censored`` accepts two + one-dimensional arrays that hold the lower and upper bounds of the + intervals. + + Parameters + ---------- + uncensored : array_like, 1D + Uncensored observations. + left : array_like, 1D + Left-censored observations. + right : array_like, 1D + Right-censored observations. + interval : array_like, 2D, with shape (m, 2) + Interval-censored observations. Each row ``interval[k, :]`` + represents the interval for the kth interval-censored observation. + + Notes + ----- + In the input array `interval`, the lower bound of the interval may + be ``-inf``, and the upper bound may be ``inf``, but at least one must be + finite. When the lower bound is ``-inf``, the row represents a left- + censored observation, and when the upper bound is ``inf``, the row + represents a right-censored observation. If the length of an interval + is 0 (i.e. ``interval[k, 0] == interval[k, 1]``, the observation is + treated as uncensored. So one can represent all the types of censored + and uncensored data in ``interval``, but it is generally more convenient + to use `uncensored`, `left` and `right` for uncensored, left-censored and + right-censored observations, respectively. + + Examples + -------- + In the most general case, a censored data set may contain values that + are left-censored, right-censored, interval-censored, and uncensored. + For example, here we create a data set with five observations. Two + are uncensored (values 1 and 1.5), one is a left-censored observation + of 0, one is a right-censored observation of 10 and one is + interval-censored in the interval [2, 3]. + + >>> import numpy as np + >>> from scipy.stats import CensoredData + >>> data = CensoredData(uncensored=[1, 1.5], left=[0], right=[10], + ... interval=[[2, 3]]) + >>> print(data) + CensoredData(5 values: 2 not censored, 1 left-censored, + 1 right-censored, 1 interval-censored) + + Equivalently, + + >>> data = CensoredData(interval=[[1, 1], + ... [1.5, 1.5], + ... [-np.inf, 0], + ... [10, np.inf], + ... [2, 3]]) + >>> print(data) + CensoredData(5 values: 2 not censored, 1 left-censored, + 1 right-censored, 1 interval-censored) + + A common case is to have a mix of uncensored observations and censored + observations that are all right-censored (or all left-censored). For + example, consider an experiment in which six devices are started at + various times and left running until they fail. Assume that time is + measured in hours, and the experiment is stopped after 30 hours, even + if all the devices have not failed by that time. We might end up with + data such as this:: + + Device Start-time Fail-time Time-to-failure + 1 0 13 13 + 2 2 24 22 + 3 5 22 17 + 4 8 23 15 + 5 10 *** >20 + 6 12 *** >18 + + Two of the devices had not failed when the experiment was stopped; + the observations of the time-to-failure for these two devices are + right-censored. We can represent this data with + + >>> data = CensoredData(uncensored=[13, 22, 17, 15], right=[20, 18]) + >>> print(data) + CensoredData(6 values: 4 not censored, 2 right-censored) + + Alternatively, we can use the method `CensoredData.right_censored` to + create a representation of this data. The time-to-failure observations + are put the list ``ttf``. The ``censored`` list indicates which values + in ``ttf`` are censored. + + >>> ttf = [13, 22, 17, 15, 20, 18] + >>> censored = [False, False, False, False, True, True] + + Pass these lists to `CensoredData.right_censored` to create an + instance of `CensoredData`. + + >>> data = CensoredData.right_censored(ttf, censored) + >>> print(data) + CensoredData(6 values: 4 not censored, 2 right-censored) + + If the input data is interval censored and already stored in two + arrays, one holding the low end of the intervals and another + holding the high ends, the class method ``interval_censored`` can + be used to create the `CensoredData` instance. + + This example creates an instance with four interval-censored values. + The intervals are [10, 11], [0.5, 1], [2, 3], and [12.5, 13.5]. + + >>> a = [10, 0.5, 2, 12.5] # Low ends of the intervals + >>> b = [11, 1.0, 3, 13.5] # High ends of the intervals + >>> data = CensoredData.interval_censored(low=a, high=b) + >>> print(data) + CensoredData(4 values: 0 not censored, 4 interval-censored) + + Finally, we create and censor some data from the `weibull_min` + distribution, and then fit `weibull_min` to that data. We'll assume + that the location parameter is known to be 0. + + >>> from scipy.stats import weibull_min + >>> rng = np.random.default_rng() + + Create the random data set. + + >>> x = weibull_min.rvs(2.5, loc=0, scale=30, size=250, random_state=rng) + >>> x[x > 40] = 40 # Right-censor values greater or equal to 40. + + Create the `CensoredData` instance with the `right_censored` method. + The censored values are those where the value is 40. + + >>> data = CensoredData.right_censored(x, x == 40) + >>> print(data) + CensoredData(250 values: 215 not censored, 35 right-censored) + + 35 values have been right-censored. + + Fit `weibull_min` to the censored data. We expect to shape and scale + to be approximately 2.5 and 30, respectively. + + >>> weibull_min.fit(data, floc=0) + (2.3575922823897315, 0, 30.40650074451254) + + """ + + def __init__(self, uncensored=None, *, left=None, right=None, + interval=None): + if uncensored is None: + uncensored = [] + if left is None: + left = [] + if right is None: + right = [] + if interval is None: + interval = np.empty((0, 2)) + + _validate_1d(uncensored, 'uncensored') + _validate_1d(left, 'left') + _validate_1d(right, 'right') + uncensored2, left2, right2, interval2 = _validate_interval(interval) + + self._uncensored = np.concatenate((uncensored, uncensored2)) + self._left = np.concatenate((left, left2)) + self._right = np.concatenate((right, right2)) + # Note that by construction, the private attribute _interval + # will be a 2D array that contains only finite values representing + # intervals with nonzero but finite length. + self._interval = interval2 + + def __repr__(self): + uncensored_str = " ".join(np.array_repr(self._uncensored).split()) + left_str = " ".join(np.array_repr(self._left).split()) + right_str = " ".join(np.array_repr(self._right).split()) + interval_str = " ".join(np.array_repr(self._interval).split()) + return (f"CensoredData(uncensored={uncensored_str}, left={left_str}, " + f"right={right_str}, interval={interval_str})") + + def __str__(self): + num_nc = len(self._uncensored) + num_lc = len(self._left) + num_rc = len(self._right) + num_ic = len(self._interval) + n = num_nc + num_lc + num_rc + num_ic + parts = [f'{num_nc} not censored'] + if num_lc > 0: + parts.append(f'{num_lc} left-censored') + if num_rc > 0: + parts.append(f'{num_rc} right-censored') + if num_ic > 0: + parts.append(f'{num_ic} interval-censored') + return f'CensoredData({n} values: ' + ', '.join(parts) + ')' + + # This is not a complete implementation of the arithmetic operators. + # All we need is subtracting a scalar and dividing by a scalar. + + def __sub__(self, other): + return CensoredData(uncensored=self._uncensored - other, + left=self._left - other, + right=self._right - other, + interval=self._interval - other) + + def __truediv__(self, other): + return CensoredData(uncensored=self._uncensored / other, + left=self._left / other, + right=self._right / other, + interval=self._interval / other) + + def __len__(self): + """ + The number of values (censored and not censored). + """ + return (len(self._uncensored) + len(self._left) + len(self._right) + + len(self._interval)) + + def num_censored(self): + """ + Number of censored values. + """ + return len(self._left) + len(self._right) + len(self._interval) + + @classmethod + def right_censored(cls, x, censored): + """ + Create a `CensoredData` instance of right-censored data. + + Parameters + ---------- + x : array_like + `x` is the array of observed data or measurements. + `x` must be a one-dimensional sequence of finite numbers. + censored : array_like of bool + `censored` must be a one-dimensional sequence of boolean + values. If ``censored[k]`` is True, the corresponding value + in `x` is right-censored. That is, the value ``x[k]`` + is the lower bound of the true (but unknown) value. + + Returns + ------- + data : `CensoredData` + An instance of `CensoredData` that represents the + collection of uncensored and right-censored values. + + Examples + -------- + >>> from scipy.stats import CensoredData + + Two uncensored values (4 and 10) and two right-censored values + (24 and 25). + + >>> data = CensoredData.right_censored([4, 10, 24, 25], + ... [False, False, True, True]) + >>> data + CensoredData(uncensored=array([ 4., 10.]), + left=array([], dtype=float64), right=array([24., 25.]), + interval=array([], shape=(0, 2), dtype=float64)) + >>> print(data) + CensoredData(4 values: 2 not censored, 2 right-censored) + """ + x, censored = _validate_x_censored(x, censored) + return cls(uncensored=x[~censored], right=x[censored]) + + @classmethod + def left_censored(cls, x, censored): + """ + Create a `CensoredData` instance of left-censored data. + + Parameters + ---------- + x : array_like + `x` is the array of observed data or measurements. + `x` must be a one-dimensional sequence of finite numbers. + censored : array_like of bool + `censored` must be a one-dimensional sequence of boolean + values. If ``censored[k]`` is True, the corresponding value + in `x` is left-censored. That is, the value ``x[k]`` + is the upper bound of the true (but unknown) value. + + Returns + ------- + data : `CensoredData` + An instance of `CensoredData` that represents the + collection of uncensored and left-censored values. + + Examples + -------- + >>> from scipy.stats import CensoredData + + Two uncensored values (0.12 and 0.033) and two left-censored values + (both 1e-3). + + >>> data = CensoredData.left_censored([0.12, 0.033, 1e-3, 1e-3], + ... [False, False, True, True]) + >>> data + CensoredData(uncensored=array([0.12 , 0.033]), + left=array([0.001, 0.001]), right=array([], dtype=float64), + interval=array([], shape=(0, 2), dtype=float64)) + >>> print(data) + CensoredData(4 values: 2 not censored, 2 left-censored) + """ + x, censored = _validate_x_censored(x, censored) + return cls(uncensored=x[~censored], left=x[censored]) + + @classmethod + def interval_censored(cls, low, high): + """ + Create a `CensoredData` instance of interval-censored data. + + This method is useful when all the data is interval-censored, and + the low and high ends of the intervals are already stored in + separate one-dimensional arrays. + + Parameters + ---------- + low : array_like + The one-dimensional array containing the low ends of the + intervals. + high : array_like + The one-dimensional array containing the high ends of the + intervals. + + Returns + ------- + data : `CensoredData` + An instance of `CensoredData` that represents the + collection of censored values. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import CensoredData + + ``a`` and ``b`` are the low and high ends of a collection of + interval-censored values. + + >>> a = [0.5, 2.0, 3.0, 5.5] + >>> b = [1.0, 2.5, 3.5, 7.0] + >>> data = CensoredData.interval_censored(low=a, high=b) + >>> print(data) + CensoredData(4 values: 0 not censored, 4 interval-censored) + """ + _validate_1d(low, 'low', allow_inf=True) + _validate_1d(high, 'high', allow_inf=True) + if len(low) != len(high): + raise ValueError('`low` and `high` must have the same length.') + interval = np.column_stack((low, high)) + uncensored, left, right, interval = _validate_interval(interval) + return cls(uncensored=uncensored, left=left, right=right, + interval=interval) + + def _uncensor(self): + """ + This function is used when a non-censored version of the data + is needed to create a rough estimate of the parameters of a + distribution via the method of moments or some similar method. + The data is "uncensored" by taking the given endpoints as the + data for the left- or right-censored data, and the mean for the + interval-censored data. + """ + data = np.concatenate((self._uncensored, self._left, self._right, + self._interval.mean(axis=1))) + return data + + def _supported(self, a, b): + """ + Return a subset of self containing the values that are in + (or overlap with) the interval (a, b). + """ + uncensored = self._uncensored + uncensored = uncensored[(a < uncensored) & (uncensored < b)] + left = self._left + left = left[a < left] + right = self._right + right = right[right < b] + interval = self._interval + interval = interval[(a < interval[:, 1]) & (interval[:, 0] < b)] + return CensoredData(uncensored, left=left, right=right, + interval=interval) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_common.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..4011d425cc4afea3c7ee8937526b13f1f92b0850 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_common.py @@ -0,0 +1,5 @@ +from collections import namedtuple + + +ConfidenceInterval = namedtuple("ConfidenceInterval", ["low", "high"]) +ConfidenceInterval. __doc__ = "Class for confidence intervals." diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_constants.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b539ce8146ebdbc8e08c66143461b04d742804f2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_constants.py @@ -0,0 +1,42 @@ +""" +Statistics-related constants. + +""" +import numpy as np + + +# The smallest representable positive number such that 1.0 + _EPS != 1.0. +_EPS = np.finfo(float).eps + +# The largest [in magnitude] usable floating value. +_XMAX = np.finfo(float).max + +# The log of the largest usable floating value; useful for knowing +# when exp(something) will overflow +_LOGXMAX = np.log(_XMAX) + +# The smallest [in magnitude] usable (i.e. not subnormal) double precision +# floating value. +_XMIN = np.finfo(float).tiny + +# The log of the smallest [in magnitude] usable (i.e not subnormal) +# double precision floating value. +_LOGXMIN = np.log(_XMIN) + +# -special.psi(1) +_EULER = 0.577215664901532860606512090082402431042 + +# special.zeta(3, 1) Apery's constant +_ZETA3 = 1.202056903159594285399738161511449990765 + +# sqrt(pi) +_SQRT_PI = 1.772453850905516027298167483341145182798 + +# sqrt(2/pi) +_SQRT_2_OVER_PI = 0.7978845608028654 + +# log(pi) +_LOG_PI = 1.1447298858494002 + +# log(sqrt(2/pi)) +_LOG_SQRT_2_OVER_PI = -0.22579135264472744 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_continuous_distns.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_continuous_distns.py new file mode 100644 index 0000000000000000000000000000000000000000..d391a946205c975101a9e329fb35052f64be7287 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_continuous_distns.py @@ -0,0 +1,12516 @@ +# +# Author: Travis Oliphant 2002-2011 with contributions from +# SciPy Developers 2004-2011 +# +import warnings +from collections.abc import Iterable +from functools import wraps, cached_property +import ctypes + +import numpy as np +from numpy.polynomial import Polynomial +from scipy.interpolate import BSpline +from scipy._lib.doccer import (extend_notes_in_docstring, + replace_notes_in_docstring, + inherit_docstring_from) +from scipy._lib._ccallback import LowLevelCallable +from scipy import optimize +from scipy import integrate +import scipy.special as sc + +import scipy.special._ufuncs as scu +from scipy._lib._util import _lazyselect, _lazywhere + +from . import _stats +from ._tukeylambda_stats import (tukeylambda_variance as _tlvar, + tukeylambda_kurtosis as _tlkurt) +from ._distn_infrastructure import (_vectorize_rvs_over_shapes, + get_distribution_names, _kurtosis, _isintegral, + rv_continuous, _skew, _get_fixed_fit_value, _check_shape, _ShapeInfo) +from scipy.stats._distribution_infrastructure import _log1mexp +from ._ksstats import kolmogn, kolmognp, kolmogni +from ._constants import (_XMIN, _LOGXMIN, _EULER, _ZETA3, _SQRT_PI, + _SQRT_2_OVER_PI, _LOG_PI, _LOG_SQRT_2_OVER_PI) +from ._censored_data import CensoredData +from scipy.optimize import root_scalar +from scipy.stats._warnings_errors import FitError +import scipy.stats as stats + +def _remove_optimizer_parameters(kwds): + """ + Remove the optimizer-related keyword arguments 'loc', 'scale' and + 'optimizer' from `kwds`. Then check that `kwds` is empty, and + raise `TypeError("Unknown arguments: %s." % kwds)` if it is not. + + This function is used in the fit method of distributions that override + the default method and do not use the default optimization code. + + `kwds` is modified in-place. + """ + kwds.pop('loc', None) + kwds.pop('scale', None) + kwds.pop('optimizer', None) + kwds.pop('method', None) + if kwds: + raise TypeError(f"Unknown arguments: {kwds}.") + + +def _call_super_mom(fun): + # If fit method is overridden only for MLE and doesn't specify what to do + # if method == 'mm' or with censored data, this decorator calls the generic + # implementation. + @wraps(fun) + def wrapper(self, data, *args, **kwds): + method = kwds.get('method', 'mle').lower() + censored = isinstance(data, CensoredData) + if method == 'mm' or (censored and data.num_censored() > 0): + return super(type(self), self).fit(data, *args, **kwds) + else: + if censored: + # data is an instance of CensoredData, but actually holds + # no censored values, so replace it with the array of + # uncensored values. + data = data._uncensored + return fun(self, data, *args, **kwds) + + return wrapper + + +def _get_left_bracket(fun, rbrack, lbrack=None): + # find left bracket for `root_scalar`. A guess for lbrack may be provided. + lbrack = lbrack or rbrack - 1 + diff = rbrack - lbrack + + # if there is no sign change in `fun` between the brackets, expand + # rbrack - lbrack until a sign change occurs + def interval_contains_root(lbrack, rbrack): + # return true if the signs disagree. + return np.sign(fun(lbrack)) != np.sign(fun(rbrack)) + + while not interval_contains_root(lbrack, rbrack): + diff *= 2 + lbrack = rbrack - diff + + msg = ("The solver could not find a bracket containing a " + "root to an MLE first order condition.") + if np.isinf(lbrack): + raise FitSolverError(msg) + + return lbrack + + +class ksone_gen(rv_continuous): + r"""Kolmogorov-Smirnov one-sided test statistic distribution. + + This is the distribution of the one-sided Kolmogorov-Smirnov (KS) + statistics :math:`D_n^+` and :math:`D_n^-` + for a finite sample size ``n >= 1`` (the shape parameter). + + %(before_notes)s + + See Also + -------- + kstwobign, kstwo, kstest + + Notes + ----- + :math:`D_n^+` and :math:`D_n^-` are given by + + .. math:: + + D_n^+ &= \text{sup}_x (F_n(x) - F(x)),\\ + D_n^- &= \text{sup}_x (F(x) - F_n(x)),\\ + + where :math:`F` is a continuous CDF and :math:`F_n` is an empirical CDF. + `ksone` describes the distribution under the null hypothesis of the KS test + that the empirical CDF corresponds to :math:`n` i.i.d. random variates + with CDF :math:`F`. + + %(after_notes)s + + References + ---------- + .. [1] Birnbaum, Z. W. and Tingey, F.H. "One-sided confidence contours + for probability distribution functions", The Annals of Mathematical + Statistics, 22(4), pp 592-596 (1951). + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import ksone + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + + Display the probability density function (``pdf``): + + >>> n = 1e+03 + >>> x = np.linspace(ksone.ppf(0.01, n), + ... ksone.ppf(0.99, n), 100) + >>> ax.plot(x, ksone.pdf(x, n), + ... 'r-', lw=5, alpha=0.6, label='ksone pdf') + + Alternatively, the distribution object can be called (as a function) + to fix the shape, location and scale parameters. This returns a "frozen" + RV object holding the given parameters fixed. + + Freeze the distribution and display the frozen ``pdf``: + + >>> rv = ksone(n) + >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + >>> ax.legend(loc='best', frameon=False) + >>> plt.show() + + Check accuracy of ``cdf`` and ``ppf``: + + >>> vals = ksone.ppf([0.001, 0.5, 0.999], n) + >>> np.allclose([0.001, 0.5, 0.999], ksone.cdf(vals, n)) + True + + """ + def _argcheck(self, n): + return (n >= 1) & (n == np.round(n)) + + def _shape_info(self): + return [_ShapeInfo("n", True, (1, np.inf), (True, False))] + + def _pdf(self, x, n): + return -scu._smirnovp(n, x) + + def _cdf(self, x, n): + return scu._smirnovc(n, x) + + def _sf(self, x, n): + return sc.smirnov(n, x) + + def _ppf(self, q, n): + return scu._smirnovci(n, q) + + def _isf(self, q, n): + return sc.smirnovi(n, q) + + +ksone = ksone_gen(a=0.0, b=1.0, name='ksone') + + +class kstwo_gen(rv_continuous): + r"""Kolmogorov-Smirnov two-sided test statistic distribution. + + This is the distribution of the two-sided Kolmogorov-Smirnov (KS) + statistic :math:`D_n` for a finite sample size ``n >= 1`` + (the shape parameter). + + %(before_notes)s + + See Also + -------- + kstwobign, ksone, kstest + + Notes + ----- + :math:`D_n` is given by + + .. math:: + + D_n = \text{sup}_x |F_n(x) - F(x)| + + where :math:`F` is a (continuous) CDF and :math:`F_n` is an empirical CDF. + `kstwo` describes the distribution under the null hypothesis of the KS test + that the empirical CDF corresponds to :math:`n` i.i.d. random variates + with CDF :math:`F`. + + %(after_notes)s + + References + ---------- + .. [1] Simard, R., L'Ecuyer, P. "Computing the Two-Sided + Kolmogorov-Smirnov Distribution", Journal of Statistical Software, + Vol 39, 11, 1-18 (2011). + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import kstwo + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + + Display the probability density function (``pdf``): + + >>> n = 10 + >>> x = np.linspace(kstwo.ppf(0.01, n), + ... kstwo.ppf(0.99, n), 100) + >>> ax.plot(x, kstwo.pdf(x, n), + ... 'r-', lw=5, alpha=0.6, label='kstwo pdf') + + Alternatively, the distribution object can be called (as a function) + to fix the shape, location and scale parameters. This returns a "frozen" + RV object holding the given parameters fixed. + + Freeze the distribution and display the frozen ``pdf``: + + >>> rv = kstwo(n) + >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + >>> ax.legend(loc='best', frameon=False) + >>> plt.show() + + Check accuracy of ``cdf`` and ``ppf``: + + >>> vals = kstwo.ppf([0.001, 0.5, 0.999], n) + >>> np.allclose([0.001, 0.5, 0.999], kstwo.cdf(vals, n)) + True + + """ + def _argcheck(self, n): + return (n >= 1) & (n == np.round(n)) + + def _shape_info(self): + return [_ShapeInfo("n", True, (1, np.inf), (True, False))] + + def _get_support(self, n): + return (0.5/(n if not isinstance(n, Iterable) else np.asanyarray(n)), + 1.0) + + def _pdf(self, x, n): + return kolmognp(n, x) + + def _cdf(self, x, n): + return kolmogn(n, x) + + def _sf(self, x, n): + return kolmogn(n, x, cdf=False) + + def _ppf(self, q, n): + return kolmogni(n, q, cdf=True) + + def _isf(self, q, n): + return kolmogni(n, q, cdf=False) + + +# Use the pdf, (not the ppf) to compute moments +kstwo = kstwo_gen(momtype=0, a=0.0, b=1.0, name='kstwo') + + +class kstwobign_gen(rv_continuous): + r"""Limiting distribution of scaled Kolmogorov-Smirnov two-sided test statistic. + + This is the asymptotic distribution of the two-sided Kolmogorov-Smirnov + statistic :math:`\sqrt{n} D_n` that measures the maximum absolute + distance of the theoretical (continuous) CDF from the empirical CDF. + (see `kstest`). + + %(before_notes)s + + See Also + -------- + ksone, kstwo, kstest + + Notes + ----- + :math:`\sqrt{n} D_n` is given by + + .. math:: + + D_n = \text{sup}_x |F_n(x) - F(x)| + + where :math:`F` is a continuous CDF and :math:`F_n` is an empirical CDF. + `kstwobign` describes the asymptotic distribution (i.e. the limit of + :math:`\sqrt{n} D_n`) under the null hypothesis of the KS test that the + empirical CDF corresponds to i.i.d. random variates with CDF :math:`F`. + + %(after_notes)s + + References + ---------- + .. [1] Feller, W. "On the Kolmogorov-Smirnov Limit Theorems for Empirical + Distributions", Ann. Math. Statist. Vol 19, 177-189 (1948). + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + return -scu._kolmogp(x) + + def _cdf(self, x): + return scu._kolmogc(x) + + def _sf(self, x): + return sc.kolmogorov(x) + + def _ppf(self, q): + return scu._kolmogci(q) + + def _isf(self, q): + return sc.kolmogi(q) + + +kstwobign = kstwobign_gen(a=0.0, name='kstwobign') + + +## Normal distribution + +# loc = mu, scale = std +# Keep these implementations out of the class definition so they can be reused +# by other distributions. +_norm_pdf_C = np.sqrt(2*np.pi) +_norm_pdf_logC = np.log(_norm_pdf_C) + + +def _norm_pdf(x): + return np.exp(-x**2/2.0) / _norm_pdf_C + + +def _norm_logpdf(x): + return -x**2 / 2.0 - _norm_pdf_logC + + +def _norm_cdf(x): + return sc.ndtr(x) + + +def _norm_logcdf(x): + return sc.log_ndtr(x) + + +def _norm_ppf(q): + return sc.ndtri(q) + + +def _norm_sf(x): + return _norm_cdf(-x) + + +def _norm_logsf(x): + return _norm_logcdf(-x) + + +def _norm_isf(q): + return -_norm_ppf(q) + + +class norm_gen(rv_continuous): + r"""A normal continuous random variable. + + The location (``loc``) keyword specifies the mean. + The scale (``scale``) keyword specifies the standard deviation. + + %(before_notes)s + + Notes + ----- + The probability density function for `norm` is: + + .. math:: + + f(x) = \frac{\exp(-x^2/2)}{\sqrt{2\pi}} + + for a real number :math:`x`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return random_state.standard_normal(size) + + def _pdf(self, x): + # norm.pdf(x) = exp(-x**2/2)/sqrt(2*pi) + return _norm_pdf(x) + + def _logpdf(self, x): + return _norm_logpdf(x) + + def _cdf(self, x): + return _norm_cdf(x) + + def _logcdf(self, x): + return _norm_logcdf(x) + + def _sf(self, x): + return _norm_sf(x) + + def _logsf(self, x): + return _norm_logsf(x) + + def _ppf(self, q): + return _norm_ppf(q) + + def _isf(self, q): + return _norm_isf(q) + + def _stats(self): + return 0.0, 1.0, 0.0, 0.0 + + def _entropy(self): + return 0.5*(np.log(2*np.pi)+1) + + @_call_super_mom + @replace_notes_in_docstring(rv_continuous, notes="""\ + For the normal distribution, method of moments and maximum likelihood + estimation give identical fits, and explicit formulas for the estimates + are available. + This function uses these explicit formulas for the maximum likelihood + estimation of the normal distribution parameters, so the + `optimizer` and `method` arguments are ignored.\n\n""") + def fit(self, data, **kwds): + floc = kwds.pop('floc', None) + fscale = kwds.pop('fscale', None) + + _remove_optimizer_parameters(kwds) + + if floc is not None and fscale is not None: + # This check is for consistency with `rv_continuous.fit`. + # Without this check, this function would just return the + # parameters that were given. + raise ValueError("All parameters fixed. There is nothing to " + "optimize.") + + data = np.asarray(data) + + if not np.isfinite(data).all(): + raise ValueError("The data contains non-finite values.") + + if floc is None: + loc = data.mean() + else: + loc = floc + + if fscale is None: + scale = np.sqrt(((data - loc)**2).mean()) + else: + scale = fscale + + return loc, scale + + def _munp(self, n): + """ + @returns Moments of standard normal distribution for integer n >= 0 + + See eq. 16 of https://arxiv.org/abs/1209.4340v2 + """ + if n == 0: + return 1. + if n % 2 == 0: + return sc.factorial2(int(n) - 1) + else: + return 0. + + +norm = norm_gen(name='norm') + + +class alpha_gen(rv_continuous): + r"""An alpha continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `alpha` ([1]_, [2]_) is: + + .. math:: + + f(x, a) = \frac{1}{x^2 \Phi(a) \sqrt{2\pi}} * + \exp(-\frac{1}{2} (a-1/x)^2) + + where :math:`\Phi` is the normal CDF, :math:`x > 0`, and :math:`a > 0`. + + `alpha` takes ``a`` as a shape parameter. + + %(after_notes)s + + References + ---------- + .. [1] Johnson, Kotz, and Balakrishnan, "Continuous Univariate + Distributions, Volume 1", Second Edition, John Wiley and Sons, + p. 173 (1994). + .. [2] Anthony A. Salvia, "Reliability applications of the Alpha + Distribution", IEEE Transactions on Reliability, Vol. R-34, + No. 3, pp. 251-252 (1985). + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (False, False))] + + def _pdf(self, x, a): + # alpha.pdf(x, a) = 1/(x**2*Phi(a)*sqrt(2*pi)) * exp(-1/2 * (a-1/x)**2) + return 1.0/(x**2)/_norm_cdf(a)*_norm_pdf(a-1.0/x) + + def _logpdf(self, x, a): + return -2*np.log(x) + _norm_logpdf(a-1.0/x) - np.log(_norm_cdf(a)) + + def _cdf(self, x, a): + return _norm_cdf(a-1.0/x) / _norm_cdf(a) + + def _ppf(self, q, a): + return 1.0/np.asarray(a - _norm_ppf(q*_norm_cdf(a))) + + def _stats(self, a): + return [np.inf]*2 + [np.nan]*2 + + +alpha = alpha_gen(a=0.0, name='alpha') + + +class anglit_gen(rv_continuous): + r"""An anglit continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `anglit` is: + + .. math:: + + f(x) = \sin(2x + \pi/2) = \cos(2x) + + for :math:`-\pi/4 \le x \le \pi/4`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # anglit.pdf(x) = sin(2*x + \pi/2) = cos(2*x) + return np.cos(2*x) + + def _cdf(self, x): + return np.sin(x+np.pi/4)**2.0 + + def _sf(self, x): + return np.cos(x + np.pi / 4) ** 2.0 + + def _ppf(self, q): + return np.arcsin(np.sqrt(q))-np.pi/4 + + def _stats(self): + return 0.0, np.pi*np.pi/16-0.5, 0.0, -2*(np.pi**4 - 96)/(np.pi*np.pi-8)**2 + + def _entropy(self): + return 1-np.log(2) + + +anglit = anglit_gen(a=-np.pi/4, b=np.pi/4, name='anglit') + + +class arcsine_gen(rv_continuous): + r"""An arcsine continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `arcsine` is: + + .. math:: + + f(x) = \frac{1}{\pi \sqrt{x (1-x)}} + + for :math:`0 < x < 1`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # arcsine.pdf(x) = 1/(pi*sqrt(x*(1-x))) + with np.errstate(divide='ignore'): + return 1.0/np.pi/np.sqrt(x*(1-x)) + + def _cdf(self, x): + return 2.0/np.pi*np.arcsin(np.sqrt(x)) + + def _ppf(self, q): + return np.sin(np.pi/2.0*q)**2.0 + + def _stats(self): + mu = 0.5 + mu2 = 1.0/8 + g1 = 0 + g2 = -3.0/2.0 + return mu, mu2, g1, g2 + + def _entropy(self): + return -0.24156447527049044468 + + +arcsine = arcsine_gen(a=0.0, b=1.0, name='arcsine') + + +class FitDataError(ValueError): + """Raised when input data is inconsistent with fixed parameters.""" + # This exception is raised by, for example, beta_gen.fit when both floc + # and fscale are fixed and there are values in the data not in the open + # interval (floc, floc+fscale). + def __init__(self, distr, lower, upper): + self.args = ( + "Invalid values in `data`. Maximum likelihood " + f"estimation with {distr!r} requires that {lower!r} < " + f"(x - loc)/scale < {upper!r} for each x in `data`.", + ) + + +class FitSolverError(FitError): + """ + Raised when a solver fails to converge while fitting a distribution. + """ + # This exception is raised by, for example, beta_gen.fit when + # optimize.fsolve returns with ier != 1. + def __init__(self, mesg): + emsg = "Solver for the MLE equations failed to converge: " + emsg += mesg.replace('\n', '') + self.args = (emsg,) + + +def _beta_mle_a(a, b, n, s1): + # The zeros of this function give the MLE for `a`, with + # `b`, `n` and `s1` given. `s1` is the sum of the logs of + # the data. `n` is the number of data points. + psiab = sc.psi(a + b) + func = s1 - n * (-psiab + sc.psi(a)) + return func + + +def _beta_mle_ab(theta, n, s1, s2): + # Zeros of this function are critical points of + # the maximum likelihood function. Solving this system + # for theta (which contains a and b) gives the MLE for a and b + # given `n`, `s1` and `s2`. `s1` is the sum of the logs of the data, + # and `s2` is the sum of the logs of 1 - data. `n` is the number + # of data points. + a, b = theta + psiab = sc.psi(a + b) + func = [s1 - n * (-psiab + sc.psi(a)), + s2 - n * (-psiab + sc.psi(b))] + return func + + +class beta_gen(rv_continuous): + r"""A beta continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `beta` is: + + .. math:: + + f(x, a, b) = \frac{\Gamma(a+b) x^{a-1} (1-x)^{b-1}} + {\Gamma(a) \Gamma(b)} + + for :math:`0 <= x <= 1`, :math:`a > 0`, :math:`b > 0`, where + :math:`\Gamma` is the gamma function (`scipy.special.gamma`). + + `beta` takes :math:`a` and :math:`b` as shape parameters. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf`` + methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + """ + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ia, ib] + + def _rvs(self, a, b, size=None, random_state=None): + return random_state.beta(a, b, size) + + def _pdf(self, x, a, b): + # gamma(a+b) * x**(a-1) * (1-x)**(b-1) + # beta.pdf(x, a, b) = ------------------------------------ + # gamma(a)*gamma(b) + with np.errstate(over='ignore'): + return scu._beta_pdf(x, a, b) + + def _logpdf(self, x, a, b): + lPx = sc.xlog1py(b - 1.0, -x) + sc.xlogy(a - 1.0, x) + lPx -= sc.betaln(a, b) + return lPx + + def _cdf(self, x, a, b): + return sc.betainc(a, b, x) + + def _sf(self, x, a, b): + return sc.betaincc(a, b, x) + + def _isf(self, x, a, b): + return sc.betainccinv(a, b, x) + + def _ppf(self, q, a, b): + return scu._beta_ppf(q, a, b) + + def _stats(self, a, b): + a_plus_b = a + b + _beta_mean = a/a_plus_b + _beta_variance = a*b / (a_plus_b**2 * (a_plus_b + 1)) + _beta_skewness = ((2 * (b - a) * np.sqrt(a_plus_b + 1)) / + ((a_plus_b + 2) * np.sqrt(a * b))) + _beta_kurtosis_excess_n = 6 * ((a - b)**2 * (a_plus_b + 1) - + a * b * (a_plus_b + 2)) + _beta_kurtosis_excess_d = a * b * (a_plus_b + 2) * (a_plus_b + 3) + _beta_kurtosis_excess = _beta_kurtosis_excess_n / _beta_kurtosis_excess_d + return ( + _beta_mean, + _beta_variance, + _beta_skewness, + _beta_kurtosis_excess) + + def _fitstart(self, data): + if isinstance(data, CensoredData): + data = data._uncensor() + + g1 = _skew(data) + g2 = _kurtosis(data) + + def func(x): + a, b = x + sk = 2*(b-a)*np.sqrt(a + b + 1) / (a + b + 2) / np.sqrt(a*b) + ku = a**3 - a**2*(2*b-1) + b**2*(b+1) - 2*a*b*(b+2) + ku /= a*b*(a+b+2)*(a+b+3) + ku *= 6 + return [sk-g1, ku-g2] + a, b = optimize.fsolve(func, (1.0, 1.0)) + return super()._fitstart(data, args=(a, b)) + + @_call_super_mom + @extend_notes_in_docstring(rv_continuous, notes="""\ + In the special case where `method="MLE"` and + both `floc` and `fscale` are given, a + `ValueError` is raised if any value `x` in `data` does not satisfy + `floc < x < floc + fscale`.\n\n""") + def fit(self, data, *args, **kwds): + # Override rv_continuous.fit, so we can more efficiently handle the + # case where floc and fscale are given. + + floc = kwds.get('floc', None) + fscale = kwds.get('fscale', None) + + if floc is None or fscale is None: + # do general fit + return super().fit(data, *args, **kwds) + + # We already got these from kwds, so just pop them. + kwds.pop('floc', None) + kwds.pop('fscale', None) + + f0 = _get_fixed_fit_value(kwds, ['f0', 'fa', 'fix_a']) + f1 = _get_fixed_fit_value(kwds, ['f1', 'fb', 'fix_b']) + + _remove_optimizer_parameters(kwds) + + if f0 is not None and f1 is not None: + # This check is for consistency with `rv_continuous.fit`. + raise ValueError("All parameters fixed. There is nothing to " + "optimize.") + + # Special case: loc and scale are constrained, so we are fitting + # just the shape parameters. This can be done much more efficiently + # than the method used in `rv_continuous.fit`. (See the subsection + # "Two unknown parameters" in the section "Maximum likelihood" of + # the Wikipedia article on the Beta distribution for the formulas.) + + if not np.isfinite(data).all(): + raise ValueError("The data contains non-finite values.") + + # Normalize the data to the interval [0, 1]. + data = (np.ravel(data) - floc) / fscale + if np.any(data <= 0) or np.any(data >= 1): + raise FitDataError("beta", lower=floc, upper=floc + fscale) + + xbar = data.mean() + + if f0 is not None or f1 is not None: + # One of the shape parameters is fixed. + + if f0 is not None: + # The shape parameter a is fixed, so swap the parameters + # and flip the data. We always solve for `a`. The result + # will be swapped back before returning. + b = f0 + data = 1 - data + xbar = 1 - xbar + else: + b = f1 + + # Initial guess for a. Use the formula for the mean of the beta + # distribution, E[x] = a / (a + b), to generate a reasonable + # starting point based on the mean of the data and the given + # value of b. + a = b * xbar / (1 - xbar) + + # Compute the MLE for `a` by solving _beta_mle_a. + theta, info, ier, mesg = optimize.fsolve( + _beta_mle_a, a, + args=(b, len(data), np.log(data).sum()), + full_output=True + ) + if ier != 1: + raise FitSolverError(mesg=mesg) + a = theta[0] + + if f0 is not None: + # The shape parameter a was fixed, so swap back the + # parameters. + a, b = b, a + + else: + # Neither of the shape parameters is fixed. + + # s1 and s2 are used in the extra arguments passed to _beta_mle_ab + # by optimize.fsolve. + s1 = np.log(data).sum() + s2 = sc.log1p(-data).sum() + + # Use the "method of moments" to estimate the initial + # guess for a and b. + fac = xbar * (1 - xbar) / data.var(ddof=0) - 1 + a = xbar * fac + b = (1 - xbar) * fac + + # Compute the MLE for a and b by solving _beta_mle_ab. + theta, info, ier, mesg = optimize.fsolve( + _beta_mle_ab, [a, b], + args=(len(data), s1, s2), + full_output=True + ) + if ier != 1: + raise FitSolverError(mesg=mesg) + a, b = theta + + return a, b, floc, fscale + + def _entropy(self, a, b): + def regular(a, b): + return (sc.betaln(a, b) - (a - 1) * sc.psi(a) - + (b - 1) * sc.psi(b) + (a + b - 2) * sc.psi(a + b)) + + def asymptotic_ab_large(a, b): + sum_ab = a + b + log_term = 0.5 * ( + np.log(2*np.pi) + np.log(a) + np.log(b) - 3*np.log(sum_ab) + 1 + ) + t1 = 110/sum_ab + 20*sum_ab**-2.0 + sum_ab**-3.0 - 2*sum_ab**-4.0 + t2 = -50/a - 10*a**-2.0 - a**-3.0 + a**-4.0 + t3 = -50/b - 10*b**-2.0 - b**-3.0 + b**-4.0 + return log_term + (t1 + t2 + t3) / 120 + + def asymptotic_b_large(a, b): + sum_ab = a + b + t1 = sc.gammaln(a) - (a - 1) * sc.psi(a) + t2 = ( + - 1/(2*b) + 1/(12*b) - b**-2.0/12 - b**-3.0/120 + b**-4.0/120 + + b**-5.0/252 - b**-6.0/252 + 1/sum_ab - 1/(12*sum_ab) + + sum_ab**-2.0/6 + sum_ab**-3.0/120 - sum_ab**-4.0/60 + - sum_ab**-5.0/252 + sum_ab**-6.0/126 + ) + log_term = sum_ab*np.log1p(a/b) + np.log(b) - 2*np.log(sum_ab) + return t1 + t2 + log_term + + def threshold_large(v): + if v == 1.0: + return 1000 + + j = np.log10(v) + digits = int(j) + d = int(v / 10 ** digits) + 2 + return d*10**(7 + j) + + if a >= 4.96e6 and b >= 4.96e6: + return asymptotic_ab_large(a, b) + elif a <= 4.9e6 and b - a >= 1e6 and b >= threshold_large(a): + return asymptotic_b_large(a, b) + elif b <= 4.9e6 and a - b >= 1e6 and a >= threshold_large(b): + return asymptotic_b_large(b, a) + else: + return regular(a, b) + + +beta = beta_gen(a=0.0, b=1.0, name='beta') + + +class betaprime_gen(rv_continuous): + r"""A beta prime continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `betaprime` is: + + .. math:: + + f(x, a, b) = \frac{x^{a-1} (1+x)^{-a-b}}{\beta(a, b)} + + for :math:`x >= 0`, :math:`a > 0`, :math:`b > 0`, where + :math:`\beta(a, b)` is the beta function (see `scipy.special.beta`). + + `betaprime` takes ``a`` and ``b`` as shape parameters. + + The distribution is related to the `beta` distribution as follows: + If :math:`X` follows a beta distribution with parameters :math:`a, b`, + then :math:`Y = X/(1-X)` has a beta prime distribution with + parameters :math:`a, b` ([1]_). + + The beta prime distribution is a reparametrized version of the + F distribution. The beta prime distribution with shape parameters + ``a`` and ``b`` and ``scale = s`` is equivalent to the F distribution + with parameters ``d1 = 2*a``, ``d2 = 2*b`` and ``scale = (a/b)*s``. + For example, + + >>> from scipy.stats import betaprime, f + >>> x = [1, 2, 5, 10] + >>> a = 12 + >>> b = 5 + >>> betaprime.pdf(x, a, b, scale=2) + array([0.00541179, 0.08331299, 0.14669185, 0.03150079]) + >>> f.pdf(x, 2*a, 2*b, scale=(a/b)*2) + array([0.00541179, 0.08331299, 0.14669185, 0.03150079]) + + %(after_notes)s + + References + ---------- + .. [1] Beta prime distribution, Wikipedia, + https://en.wikipedia.org/wiki/Beta_prime_distribution + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ia, ib] + + def _rvs(self, a, b, size=None, random_state=None): + u1 = gamma.rvs(a, size=size, random_state=random_state) + u2 = gamma.rvs(b, size=size, random_state=random_state) + return u1 / u2 + + def _pdf(self, x, a, b): + # betaprime.pdf(x, a, b) = x**(a-1) * (1+x)**(-a-b) / beta(a, b) + return np.exp(self._logpdf(x, a, b)) + + def _logpdf(self, x, a, b): + return sc.xlogy(a - 1.0, x) - sc.xlog1py(a + b, x) - sc.betaln(a, b) + + def _cdf(self, x, a, b): + # note: f2 is the direct way to compute the cdf if the relationship + # to the beta distribution is used. + # however, for very large x, x/(1+x) == 1. since the distribution + # has very fat tails if b is small, this can cause inaccurate results + # use the following relationship of the incomplete beta function: + # betainc(x, a, b) = 1 - betainc(1-x, b, a) + # see gh-17631 + return _lazywhere( + x > 1, [x, a, b], + lambda x_, a_, b_: beta._sf(1/(1+x_), b_, a_), + f2=lambda x_, a_, b_: beta._cdf(x_/(1+x_), a_, b_)) + + def _sf(self, x, a, b): + return _lazywhere( + x > 1, [x, a, b], + lambda x_, a_, b_: beta._cdf(1/(1+x_), b_, a_), + f2=lambda x_, a_, b_: beta._sf(x_/(1+x_), a_, b_) + ) + + def _ppf(self, p, a, b): + p, a, b = np.broadcast_arrays(p, a, b) + # By default, compute the ppf by solving the following: + # p = beta._cdf(x/(1+x), a, b). This implies x = r/(1-r) with + # r = beta._ppf(p, a, b). This can cause numerical issues if r is + # very close to 1. In that case, invert the alternative expression of + # the cdf: p = beta._sf(1/(1+x), b, a). + r = stats.beta._ppf(p, a, b) + with np.errstate(divide='ignore'): + out = r / (1 - r) + rnear1 = r > 0.9999 + if np.isscalar(r): + if rnear1: + out = 1/stats.beta._isf(p, b, a) - 1 + else: + out[rnear1] = 1/stats.beta._isf(p[rnear1], b[rnear1], a[rnear1]) - 1 + return out + + def _munp(self, n, a, b): + return _lazywhere( + b > n, (a, b), + lambda a, b: np.prod([(a+i-1)/(b-i) for i in range(1, int(n)+1)], axis=0), + fillvalue=np.inf) + + +betaprime = betaprime_gen(a=0.0, name='betaprime') + + +class bradford_gen(rv_continuous): + r"""A Bradford continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `bradford` is: + + .. math:: + + f(x, c) = \frac{c}{\log(1+c) (1+cx)} + + for :math:`0 <= x <= 1` and :math:`c > 0`. + + `bradford` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # bradford.pdf(x, c) = c / (k * (1+c*x)) + return c / (c*x + 1.0) / sc.log1p(c) + + def _cdf(self, x, c): + return sc.log1p(c*x) / sc.log1p(c) + + def _ppf(self, q, c): + return sc.expm1(q * sc.log1p(c)) / c + + def _stats(self, c, moments='mv'): + k = np.log(1.0+c) + mu = (c-k)/(c*k) + mu2 = ((c+2.0)*k-2.0*c)/(2*c*k*k) + g1 = None + g2 = None + if 's' in moments: + g1 = np.sqrt(2)*(12*c*c-9*c*k*(c+2)+2*k*k*(c*(c+3)+3)) + g1 /= np.sqrt(c*(c*(k-2)+2*k))*(3*c*(k-2)+6*k) + if 'k' in moments: + g2 = (c**3*(k-3)*(k*(3*k-16)+24)+12*k*c*c*(k-4)*(k-3) + + 6*c*k*k*(3*k-14) + 12*k**3) + g2 /= 3*c*(c*(k-2)+2*k)**2 + return mu, mu2, g1, g2 + + def _entropy(self, c): + k = np.log(1+c) + return k/2.0 - np.log(c/k) + + +bradford = bradford_gen(a=0.0, b=1.0, name='bradford') + + +class burr_gen(rv_continuous): + r"""A Burr (Type III) continuous random variable. + + %(before_notes)s + + See Also + -------- + fisk : a special case of either `burr` or `burr12` with ``d=1`` + burr12 : Burr Type XII distribution + mielke : Mielke Beta-Kappa / Dagum distribution + + Notes + ----- + The probability density function for `burr` is: + + .. math:: + + f(x; c, d) = c d \frac{x^{-c - 1}} + {{(1 + x^{-c})}^{d + 1}} + + for :math:`x >= 0` and :math:`c, d > 0`. + + `burr` takes ``c`` and ``d`` as shape parameters for :math:`c` and + :math:`d`. + + This is the PDF corresponding to the third CDF given in Burr's list; + specifically, it is equation (11) in Burr's paper [1]_. The distribution + is also commonly referred to as the Dagum distribution [2]_. If the + parameter :math:`c < 1` then the mean of the distribution does not + exist and if :math:`c < 2` the variance does not exist [2]_. + The PDF is finite at the left endpoint :math:`x = 0` if :math:`c * d >= 1`. + + %(after_notes)s + + References + ---------- + .. [1] Burr, I. W. "Cumulative frequency functions", Annals of + Mathematical Statistics, 13(2), pp 215-232 (1942). + .. [2] https://en.wikipedia.org/wiki/Dagum_distribution + .. [3] Kleiber, Christian. "A guide to the Dagum distributions." + Modeling Income Distributions and Lorenz Curves pp 97-117 (2008). + + %(example)s + + """ + # Do not set _support_mask to rv_continuous._open_support_mask + # Whether the left-hand endpoint is suitable for pdf evaluation is dependent + # on the values of c and d: if c*d >= 1, the pdf is finite, otherwise infinite. + + def _shape_info(self): + ic = _ShapeInfo("c", False, (0, np.inf), (False, False)) + id = _ShapeInfo("d", False, (0, np.inf), (False, False)) + return [ic, id] + + def _pdf(self, x, c, d): + # burr.pdf(x, c, d) = c * d * x**(-c-1) * (1+x**(-c))**(-d-1) + output = _lazywhere( + x == 0, [x, c, d], + lambda x_, c_, d_: c_ * d_ * (x_**(c_*d_-1)) / (1 + x_**c_), + f2=lambda x_, c_, d_: (c_ * d_ * (x_ ** (-c_ - 1.0)) / + ((1 + x_ ** (-c_)) ** (d_ + 1.0)))) + if output.ndim == 0: + return output[()] + return output + + def _logpdf(self, x, c, d): + output = _lazywhere( + x == 0, [x, c, d], + lambda x_, c_, d_: (np.log(c_) + np.log(d_) + sc.xlogy(c_*d_ - 1, x_) + - (d_+1) * sc.log1p(x_**(c_))), + f2=lambda x_, c_, d_: (np.log(c_) + np.log(d_) + + sc.xlogy(-c_ - 1, x_) + - sc.xlog1py(d_+1, x_**(-c_)))) + if output.ndim == 0: + return output[()] + return output + + def _cdf(self, x, c, d): + return (1 + x**(-c))**(-d) + + def _logcdf(self, x, c, d): + return sc.log1p(x**(-c)) * (-d) + + def _sf(self, x, c, d): + return np.exp(self._logsf(x, c, d)) + + def _logsf(self, x, c, d): + return np.log1p(- (1 + x**(-c))**(-d)) + + def _ppf(self, q, c, d): + return (q**(-1.0/d) - 1)**(-1.0/c) + + def _isf(self, q, c, d): + _q = sc.xlog1py(-1.0 / d, -q) + return sc.expm1(_q) ** (-1.0 / c) + + def _stats(self, c, d): + nc = np.arange(1, 5).reshape(4,1) / c + # ek is the kth raw moment, e1 is the mean e2-e1**2 variance etc. + e1, e2, e3, e4 = sc.beta(d + nc, 1. - nc) * d + mu = np.where(c > 1.0, e1, np.nan) + mu2_if_c = e2 - mu**2 + mu2 = np.where(c > 2.0, mu2_if_c, np.nan) + g1 = _lazywhere( + c > 3.0, + (c, e1, e2, e3, mu2_if_c), + lambda c, e1, e2, e3, mu2_if_c: ((e3 - 3*e2*e1 + 2*e1**3) + / np.sqrt((mu2_if_c)**3)), + fillvalue=np.nan) + g2 = _lazywhere( + c > 4.0, + (c, e1, e2, e3, e4, mu2_if_c), + lambda c, e1, e2, e3, e4, mu2_if_c: ( + ((e4 - 4*e3*e1 + 6*e2*e1**2 - 3*e1**4) / mu2_if_c**2) - 3), + fillvalue=np.nan) + if np.ndim(c) == 0: + return mu.item(), mu2.item(), g1.item(), g2.item() + return mu, mu2, g1, g2 + + def _munp(self, n, c, d): + def __munp(n, c, d): + nc = 1. * n / c + return d * sc.beta(1.0 - nc, d + nc) + n, c, d = np.asarray(n), np.asarray(c), np.asarray(d) + return _lazywhere((c > n) & (n == n) & (d == d), (c, d, n), + lambda c, d, n: __munp(n, c, d), + np.nan) + + +burr = burr_gen(a=0.0, name='burr') + + +class burr12_gen(rv_continuous): + r"""A Burr (Type XII) continuous random variable. + + %(before_notes)s + + See Also + -------- + fisk : a special case of either `burr` or `burr12` with ``d=1`` + burr : Burr Type III distribution + + Notes + ----- + The probability density function for `burr12` is: + + .. math:: + + f(x; c, d) = c d \frac{x^{c-1}} + {(1 + x^c)^{d + 1}} + + for :math:`x >= 0` and :math:`c, d > 0`. + + `burr12` takes ``c`` and ``d`` as shape parameters for :math:`c` + and :math:`d`. + + This is the PDF corresponding to the twelfth CDF given in Burr's list; + specifically, it is equation (20) in Burr's paper [1]_. + + %(after_notes)s + + The Burr type 12 distribution is also sometimes referred to as + the Singh-Maddala distribution from NIST [2]_. + + References + ---------- + .. [1] Burr, I. W. "Cumulative frequency functions", Annals of + Mathematical Statistics, 13(2), pp 215-232 (1942). + + .. [2] https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/b12pdf.htm + + .. [3] "Burr distribution", + https://en.wikipedia.org/wiki/Burr_distribution + + %(example)s + + """ + def _shape_info(self): + ic = _ShapeInfo("c", False, (0, np.inf), (False, False)) + id = _ShapeInfo("d", False, (0, np.inf), (False, False)) + return [ic, id] + + def _pdf(self, x, c, d): + # burr12.pdf(x, c, d) = c * d * x**(c-1) * (1+x**(c))**(-d-1) + return np.exp(self._logpdf(x, c, d)) + + def _logpdf(self, x, c, d): + return np.log(c) + np.log(d) + sc.xlogy(c - 1, x) + sc.xlog1py(-d-1, x**c) + + def _cdf(self, x, c, d): + return -sc.expm1(self._logsf(x, c, d)) + + def _logcdf(self, x, c, d): + return sc.log1p(-(1 + x**c)**(-d)) + + def _sf(self, x, c, d): + return np.exp(self._logsf(x, c, d)) + + def _logsf(self, x, c, d): + return sc.xlog1py(-d, x**c) + + def _ppf(self, q, c, d): + # The following is an implementation of + # ((1 - q)**(-1.0/d) - 1)**(1.0/c) + # that does a better job handling small values of q. + return sc.expm1(-1/d * sc.log1p(-q))**(1/c) + + def _isf(self, p, c, d): + return sc.expm1(-1/d * np.log(p))**(1/c) + + def _munp(self, n, c, d): + def moment_if_exists(n, c, d): + nc = 1. * n / c + return d * sc.beta(1.0 + nc, d - nc) + + return _lazywhere(c * d > n, (n, c, d), moment_if_exists, + fillvalue=np.nan) + + +burr12 = burr12_gen(a=0.0, name='burr12') + + +class fisk_gen(burr_gen): + r"""A Fisk continuous random variable. + + The Fisk distribution is also known as the log-logistic distribution. + + %(before_notes)s + + See Also + -------- + burr + + Notes + ----- + The probability density function for `fisk` is: + + .. math:: + + f(x, c) = \frac{c x^{c-1}} + {(1 + x^c)^2} + + for :math:`x >= 0` and :math:`c > 0`. + + Please note that the above expression can be transformed into the following + one, which is also commonly used: + + .. math:: + + f(x, c) = \frac{c x^{-c-1}} + {(1 + x^{-c})^2} + + `fisk` takes ``c`` as a shape parameter for :math:`c`. + + `fisk` is a special case of `burr` or `burr12` with ``d=1``. + + Suppose ``X`` is a logistic random variable with location ``l`` + and scale ``s``. Then ``Y = exp(X)`` is a Fisk (log-logistic) + random variable with ``scale = exp(l)`` and shape ``c = 1/s``. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # fisk.pdf(x, c) = c * x**(-c-1) * (1 + x**(-c))**(-2) + return burr._pdf(x, c, 1.0) + + def _cdf(self, x, c): + return burr._cdf(x, c, 1.0) + + def _sf(self, x, c): + return burr._sf(x, c, 1.0) + + def _logpdf(self, x, c): + # fisk.pdf(x, c) = c * x**(-c-1) * (1 + x**(-c))**(-2) + return burr._logpdf(x, c, 1.0) + + def _logcdf(self, x, c): + return burr._logcdf(x, c, 1.0) + + def _logsf(self, x, c): + return burr._logsf(x, c, 1.0) + + def _ppf(self, x, c): + return burr._ppf(x, c, 1.0) + + def _isf(self, q, c): + return burr._isf(q, c, 1.0) + + def _munp(self, n, c): + return burr._munp(n, c, 1.0) + + def _stats(self, c): + return burr._stats(c, 1.0) + + def _entropy(self, c): + return 2 - np.log(c) + + +fisk = fisk_gen(a=0.0, name='fisk') + + +class cauchy_gen(rv_continuous): + r"""A Cauchy continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `cauchy` is + + .. math:: + + f(x) = \frac{1}{\pi (1 + x^2)} + + for a real number :math:`x`. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``ppf` and ``isf`` methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # cauchy.pdf(x) = 1 / (pi * (1 + x**2)) + with np.errstate(over='ignore'): + return 1.0/np.pi/(1.0+x*x) + + def _logpdf(self, x): + # The formulas + # log(1/(pi*(1 + x**2))) = -log(pi) - log(1 + x**2) + # = -log(pi) - log(x**2*(1 + 1/x**2)) + # = -log(pi) - (2log(|x|) + log1p(1/x**2)) + # are used here. + absx = np.abs(x) + # In the following _lazywhere, `f` provides better precision than `f2` + # for small and moderate x, while `f2` avoids the overflow that can + # occur with absx**2. + y = _lazywhere(absx < 1, (absx,), + f=lambda absx: -_LOG_PI - np.log1p(absx**2), + f2=lambda absx: (-_LOG_PI - + (2*np.log(absx) + np.log1p((1/absx)**2)))) + return y + + def _cdf(self, x): + return np.arctan2(1, -x)/np.pi + + def _ppf(self, q): + return scu._cauchy_ppf(q, 0, 1) + + def _sf(self, x): + return np.arctan2(1, x)/np.pi + + def _isf(self, q): + return scu._cauchy_isf(q, 0, 1) + + def _stats(self): + return np.nan, np.nan, np.nan, np.nan + + def _entropy(self): + return np.log(4*np.pi) + + def _fitstart(self, data, args=None): + # Initialize ML guesses using quartiles instead of moments. + if isinstance(data, CensoredData): + data = data._uncensor() + p25, p50, p75 = np.percentile(data, [25, 50, 75]) + return p50, (p75 - p25)/2 + + +cauchy = cauchy_gen(name='cauchy') + + +class chi_gen(rv_continuous): + r"""A chi continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `chi` is: + + .. math:: + + f(x, k) = \frac{1}{2^{k/2-1} \Gamma \left( k/2 \right)} + x^{k-1} \exp \left( -x^2/2 \right) + + for :math:`x >= 0` and :math:`k > 0` (degrees of freedom, denoted ``df`` + in the implementation). :math:`\Gamma` is the gamma function + (`scipy.special.gamma`). + + Special cases of `chi` are: + + - ``chi(1, loc, scale)`` is equivalent to `halfnorm` + - ``chi(2, 0, scale)`` is equivalent to `rayleigh` + - ``chi(3, 0, scale)`` is equivalent to `maxwell` + + `chi` takes ``df`` as a shape parameter. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("df", False, (0, np.inf), (False, False))] + + def _rvs(self, df, size=None, random_state=None): + return np.sqrt(chi2.rvs(df, size=size, random_state=random_state)) + + def _pdf(self, x, df): + # x**(df-1) * exp(-x**2/2) + # chi.pdf(x, df) = ------------------------- + # 2**(df/2-1) * gamma(df/2) + return np.exp(self._logpdf(x, df)) + + def _logpdf(self, x, df): + l = np.log(2) - .5*np.log(2)*df - sc.gammaln(.5*df) + return l + sc.xlogy(df - 1., x) - .5*x**2 + + def _cdf(self, x, df): + return sc.gammainc(.5*df, .5*x**2) + + def _sf(self, x, df): + return sc.gammaincc(.5*df, .5*x**2) + + def _ppf(self, q, df): + return np.sqrt(2*sc.gammaincinv(.5*df, q)) + + def _isf(self, q, df): + return np.sqrt(2*sc.gammainccinv(.5*df, q)) + + def _stats(self, df): + # poch(df/2, 1/2) = gamma(df/2 + 1/2) / gamma(df/2) + mu = np.sqrt(2) * sc.poch(0.5 * df, 0.5) + mu2 = df - mu*mu + g1 = (2*mu**3.0 + mu*(1-2*df))/np.asarray(np.power(mu2, 1.5)) + g2 = 2*df*(1.0-df)-6*mu**4 + 4*mu**2 * (2*df-1) + g2 /= np.asarray(mu2**2.0) + return mu, mu2, g1, g2 + + def _entropy(self, df): + + def regular_formula(df): + return (sc.gammaln(.5 * df) + + 0.5 * (df - np.log(2) - (df - 1) * sc.digamma(0.5 * df))) + + def asymptotic_formula(df): + return (0.5 + np.log(np.pi)/2 - (df**-1)/6 - (df**-2)/6 + - 4/45*(df**-3) + (df**-4)/15) + + return _lazywhere(df < 3e2, (df, ), regular_formula, + f2=asymptotic_formula) + + +chi = chi_gen(a=0.0, name='chi') + + +class chi2_gen(rv_continuous): + r"""A chi-squared continuous random variable. + + For the noncentral chi-square distribution, see `ncx2`. + + %(before_notes)s + + See Also + -------- + ncx2 + + Notes + ----- + The probability density function for `chi2` is: + + .. math:: + + f(x, k) = \frac{1}{2^{k/2} \Gamma \left( k/2 \right)} + x^{k/2-1} \exp \left( -x/2 \right) + + for :math:`x > 0` and :math:`k > 0` (degrees of freedom, denoted ``df`` + in the implementation). + + `chi2` takes ``df`` as a shape parameter. + + The chi-squared distribution is a special case of the gamma + distribution, with gamma parameters ``a = df/2``, ``loc = 0`` and + ``scale = 2``. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("df", False, (0, np.inf), (False, False))] + + def _rvs(self, df, size=None, random_state=None): + return random_state.chisquare(df, size) + + def _pdf(self, x, df): + # chi2.pdf(x, df) = 1 / (2*gamma(df/2)) * (x/2)**(df/2-1) * exp(-x/2) + return np.exp(self._logpdf(x, df)) + + def _logpdf(self, x, df): + return sc.xlogy(df/2.-1, x) - x/2. - sc.gammaln(df/2.) - (np.log(2)*df)/2. + + def _cdf(self, x, df): + return sc.chdtr(df, x) + + def _sf(self, x, df): + return sc.chdtrc(df, x) + + def _isf(self, p, df): + return sc.chdtri(df, p) + + def _ppf(self, p, df): + return 2*sc.gammaincinv(df/2, p) + + def _stats(self, df): + mu = df + mu2 = 2*df + g1 = 2*np.sqrt(2.0/df) + g2 = 12.0/df + return mu, mu2, g1, g2 + + def _entropy(self, df): + half_df = 0.5 * df + + def regular_formula(half_df): + return (half_df + np.log(2) + sc.gammaln(half_df) + + (1 - half_df) * sc.psi(half_df)) + + def asymptotic_formula(half_df): + # plug in the above formula the following asymptotic + # expansions: + # ln(gamma(a)) ~ (a - 0.5) * ln(a) - a + 0.5 * ln(2 * pi) + + # 1/(12 * a) - 1/(360 * a**3) + # psi(a) ~ ln(a) - 1/(2 * a) - 1/(3 * a**2) + 1/120 * a**4) + c = np.log(2) + 0.5*(1 + np.log(2*np.pi)) + h = 0.5/half_df + return (h*(-2/3 + h*(-1/3 + h*(-4/45 + h/7.5))) + + 0.5*np.log(half_df) + c) + + return _lazywhere(half_df < 125, (half_df, ), + regular_formula, + f2=asymptotic_formula) + + +chi2 = chi2_gen(a=0.0, name='chi2') + + +class cosine_gen(rv_continuous): + r"""A cosine continuous random variable. + + %(before_notes)s + + Notes + ----- + The cosine distribution is an approximation to the normal distribution. + The probability density function for `cosine` is: + + .. math:: + + f(x) = \frac{1}{2\pi} (1+\cos(x)) + + for :math:`-\pi \le x \le \pi`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # cosine.pdf(x) = 1/(2*pi) * (1+cos(x)) + return 1.0/2/np.pi*(1+np.cos(x)) + + def _logpdf(self, x): + c = np.cos(x) + return _lazywhere(c != -1, (c,), + lambda c: np.log1p(c) - np.log(2*np.pi), + fillvalue=-np.inf) + + def _cdf(self, x): + return scu._cosine_cdf(x) + + def _sf(self, x): + return scu._cosine_cdf(-x) + + def _ppf(self, p): + return scu._cosine_invcdf(p) + + def _isf(self, p): + return -scu._cosine_invcdf(p) + + def _stats(self): + v = (np.pi * np.pi / 3.0) - 2.0 + k = -6.0 * (np.pi**4 - 90) / (5.0 * (np.pi * np.pi - 6)**2) + return 0.0, v, 0.0, k + + def _entropy(self): + return np.log(4*np.pi)-1.0 + + +cosine = cosine_gen(a=-np.pi, b=np.pi, name='cosine') + + +class dgamma_gen(rv_continuous): + r"""A double gamma continuous random variable. + + The double gamma distribution is also known as the reflected gamma + distribution [1]_. + + %(before_notes)s + + Notes + ----- + The probability density function for `dgamma` is: + + .. math:: + + f(x, a) = \frac{1}{2\Gamma(a)} |x|^{a-1} \exp(-|x|) + + for a real number :math:`x` and :math:`a > 0`. :math:`\Gamma` is the + gamma function (`scipy.special.gamma`). + + `dgamma` takes ``a`` as a shape parameter for :math:`a`. + + %(after_notes)s + + References + ---------- + .. [1] Johnson, Kotz, and Balakrishnan, "Continuous Univariate + Distributions, Volume 1", Second Edition, John Wiley and Sons + (1994). + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (False, False))] + + def _rvs(self, a, size=None, random_state=None): + u = random_state.uniform(size=size) + gm = gamma.rvs(a, size=size, random_state=random_state) + return gm * np.where(u >= 0.5, 1, -1) + + def _pdf(self, x, a): + # dgamma.pdf(x, a) = 1 / (2*gamma(a)) * abs(x)**(a-1) * exp(-abs(x)) + ax = abs(x) + return 1.0/(2*sc.gamma(a))*ax**(a-1.0) * np.exp(-ax) + + def _logpdf(self, x, a): + ax = abs(x) + return sc.xlogy(a - 1.0, ax) - ax - np.log(2) - sc.gammaln(a) + + def _cdf(self, x, a): + return np.where(x > 0, + 0.5 + 0.5*sc.gammainc(a, x), + 0.5*sc.gammaincc(a, -x)) + + def _sf(self, x, a): + return np.where(x > 0, + 0.5*sc.gammaincc(a, x), + 0.5 + 0.5*sc.gammainc(a, -x)) + + def _entropy(self, a): + return stats.gamma._entropy(a) - np.log(0.5) + + def _ppf(self, q, a): + return np.where(q > 0.5, + sc.gammaincinv(a, 2*q - 1), + -sc.gammainccinv(a, 2*q)) + + def _isf(self, q, a): + return np.where(q > 0.5, + -sc.gammaincinv(a, 2*q - 1), + sc.gammainccinv(a, 2*q)) + + def _stats(self, a): + mu2 = a*(a+1.0) + return 0.0, mu2, 0.0, (a+2.0)*(a+3.0)/mu2-3.0 + + +dgamma = dgamma_gen(name='dgamma') + + +class dpareto_lognorm_gen(rv_continuous): + r"""A double Pareto lognormal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `dpareto_lognorm` is: + + .. math:: + + f(x, \mu, \sigma, \alpha, \beta) = + \frac{\alpha \beta}{(\alpha + \beta) x} + \phi\left( \frac{\log x - \mu}{\sigma} \right) + \left( R(y_1) + R(y_2) \right) + + where :math:`R(t) = \frac{1 - \Phi(t)}{\phi(t)}`, + :math:`\phi` and :math:`\Phi` are the normal PDF and CDF, respectively, + :math:`y_1 = \alpha \sigma - \frac{\log x - \mu}{\sigma}`, + and :math:`y_2 = \beta \sigma + \frac{\log x - \mu}{\sigma}` + for real numbers :math:`x` and :math:`\mu`, :math:`\sigma > 0`, + :math:`\alpha > 0`, and :math:`\beta > 0` [1]_. + + `dpareto_lognorm` takes + ``u`` as a shape parameter for :math:`\mu`, + ``s`` as a shape parameter for :math:`\sigma`, + ``a`` as a shape parameter for :math:`\alpha`, and + ``b`` as a shape parameter for :math:`\beta`. + + A random variable :math:`X` distributed according to the PDF above + can be represented as :math:`X = U \frac{V_1}{V_2}` where :math:`U`, + :math:`V_1`, and :math:`V_2` are independent, :math:`U` is lognormally + distributed such that :math:`\log U \sim N(\mu, \sigma^2)`, and + :math:`V_1` and :math:`V_2` follow Pareto distributions with parameters + :math:`\alpha` and :math:`\beta`, respectively [2]_. + + %(after_notes)s + + References + ---------- + .. [1] Hajargasht, Gholamreza, and William E. Griffiths. "Pareto-lognormal + distributions: Inequality, poverty, and estimation from grouped income + data." Economic Modelling 33 (2013): 593-604. + .. [2] Reed, William J., and Murray Jorgensen. "The double Pareto-lognormal + distribution - a new parametric model for size distributions." + Communications in Statistics - Theory and Methods 33.8 (2004): 1733-1753. + + %(example)s + + """ + _logphi = norm._logpdf + _logPhi = norm._logcdf + _logPhic = norm._logsf + _phi = norm._pdf + _Phi = norm._cdf + _Phic = norm._sf + + def _R(self, z): + return self._Phic(z) / self._phi(z) + + def _logR(self, z): + return self._logPhic(z) - self._logphi(z) + + def _shape_info(self): + return [_ShapeInfo("u", False, (-np.inf, np.inf), (False, False)), + _ShapeInfo("s", False, (0, np.inf), (False, False)), + _ShapeInfo("a", False, (0, np.inf), (False, False)), + _ShapeInfo("b", False, (0, np.inf), (False, False))] + + def _argcheck(self, u, s, a, b): + return (s > 0) & (a > 0) & (b > 0) + + def _rvs(self, u, s, a, b, size=None, random_state=None): + # From [1] after Equation (12): "To generate pseudo-random + # deviates from the dPlN distribution, one can exponentiate + # pseudo-random deviates from NL generated using (6)." + Z = random_state.normal(u, s, size=size) + E1 = random_state.standard_exponential(size=size) + E2 = random_state.standard_exponential(size=size) + return np.exp(Z + E1 / a - E2 / b) + + def _logpdf(self, x, u, s, a, b): + with np.errstate(invalid='ignore', divide='ignore'): + log_y, m = np.log(x), u # compare against [1] Eq. 1 + z = (log_y - m) / s + x1 = a * s - z + x2 = b * s + z + out = np.asarray(np.log(a) + np.log(b) - np.log(a + b) - log_y) + out += self._logphi(z) + out += np.logaddexp(self._logR(x1), self._logR(x2)) + out[(x == 0) | np.isinf(x)] = -np.inf + return out[()] + + def _logcdf(self, x, u, s, a, b): + with np.errstate(invalid='ignore', divide='ignore'): + log_y, m = np.log(x), u # compare against [1] Eq. 2 + z = (log_y - m) / s + x1 = a * s - z + x2 = b * s + z + t1 = self._logPhi(z) + t2 = self._logphi(z) + t3 = (np.log(b) + self._logR(x1)) + t4 = (np.log(a) + self._logR(x2)) + t1, t2, t3, t4, one = np.broadcast_arrays(t1, t2, t3, t4, 1) + # t3 can be smaller than t4, so we have to consider log of negative number + # This would be much simpler, but `return_sign` is available, so use it? + # t5 = sc.logsumexp([t3, t4 + np.pi*1j]) + t5, sign = sc.logsumexp([t3, t4], b=[one, -one], axis=0, return_sign=True) + temp = [t1, t2 + t5 - np.log(a + b)] + out = np.asarray(sc.logsumexp(temp, b=[one, -one*sign], axis=0)) + out[x == 0] = -np.inf + return out[()] + + def _logsf(self, x, u, s, a, b): + return _log1mexp(self._logcdf(x, u, s, a, b)) + + # Infrastructure doesn't seem to do this, so... + + def _pdf(self, x, u, s, a, b): + return np.exp(self._logpdf(x, u, s, a, b)) + + def _cdf(self, x, u, s, a, b): + return np.exp(self._logcdf(x, u, s, a, b)) + + def _sf(self, x, u, s, a, b): + return np.exp(self._logsf(x, u, s, a, b)) + + def _munp(self, n, u, s, a, b): + m, k = u, float(n) # compare against [1] Eq. 6 + out = (a * b) / ((a - k) * (b + k)) * np.exp(k * m + k ** 2 * s ** 2 / 2) + out = np.asarray(out) + out[a <= k] = np.nan + return out + + +dpareto_lognorm = dpareto_lognorm_gen(a=0, name='dpareto_lognorm') + + +class dweibull_gen(rv_continuous): + r"""A double Weibull continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `dweibull` is given by + + .. math:: + + f(x, c) = c / 2 |x|^{c-1} \exp(-|x|^c) + + for a real number :math:`x` and :math:`c > 0`. + + `dweibull` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _rvs(self, c, size=None, random_state=None): + u = random_state.uniform(size=size) + w = weibull_min.rvs(c, size=size, random_state=random_state) + return w * (np.where(u >= 0.5, 1, -1)) + + def _pdf(self, x, c): + # dweibull.pdf(x, c) = c / 2 * abs(x)**(c-1) * exp(-abs(x)**c) + ax = abs(x) + Px = c / 2.0 * ax**(c-1.0) * np.exp(-ax**c) + return Px + + def _logpdf(self, x, c): + ax = abs(x) + return np.log(c) - np.log(2.0) + sc.xlogy(c - 1.0, ax) - ax**c + + def _cdf(self, x, c): + Cx1 = 0.5 * np.exp(-abs(x)**c) + return np.where(x > 0, 1 - Cx1, Cx1) + + def _ppf(self, q, c): + fac = 2. * np.where(q <= 0.5, q, 1. - q) + fac = np.power(-np.log(fac), 1.0 / c) + return np.where(q > 0.5, fac, -fac) + + def _sf(self, x, c): + half_weibull_min_sf = 0.5 * stats.weibull_min._sf(np.abs(x), c) + return np.where(x > 0, half_weibull_min_sf, 1 - half_weibull_min_sf) + + def _isf(self, q, c): + double_q = 2. * np.where(q <= 0.5, q, 1. - q) + weibull_min_isf = stats.weibull_min._isf(double_q, c) + return np.where(q > 0.5, -weibull_min_isf, weibull_min_isf) + + def _munp(self, n, c): + return (1 - (n % 2)) * sc.gamma(1.0 + 1.0 * n / c) + + # since we know that all odd moments are zeros, return them at once. + # returning Nones from _stats makes the public stats call _munp + # so overall we're saving one or two gamma function evaluations here. + def _stats(self, c): + return 0, None, 0, None + + def _entropy(self, c): + h = stats.weibull_min._entropy(c) - np.log(0.5) + return h + + +dweibull = dweibull_gen(name='dweibull') + + +class expon_gen(rv_continuous): + r"""An exponential continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `expon` is: + + .. math:: + + f(x) = \exp(-x) + + for :math:`x \ge 0`. + + %(after_notes)s + + A common parameterization for `expon` is in terms of the rate parameter + ``lambda``, such that ``pdf = lambda * exp(-lambda * x)``. This + parameterization corresponds to using ``scale = 1 / lambda``. + + The exponential distribution is a special case of the gamma + distributions, with gamma shape parameter ``a = 1``. + + %(example)s + + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return random_state.standard_exponential(size) + + def _pdf(self, x): + # expon.pdf(x) = exp(-x) + return np.exp(-x) + + def _logpdf(self, x): + return -x + + def _cdf(self, x): + return -sc.expm1(-x) + + def _ppf(self, q): + return -sc.log1p(-q) + + def _sf(self, x): + return np.exp(-x) + + def _logsf(self, x): + return -x + + def _isf(self, q): + return -np.log(q) + + def _stats(self): + return 1.0, 1.0, 2.0, 6.0 + + def _entropy(self): + return 1.0 + + @_call_super_mom + @replace_notes_in_docstring(rv_continuous, notes="""\ + When `method='MLE'`, + this function uses explicit formulas for the maximum likelihood + estimation of the exponential distribution parameters, so the + `optimizer`, `loc` and `scale` keyword arguments are + ignored.\n\n""") + def fit(self, data, *args, **kwds): + if len(args) > 0: + raise TypeError("Too many arguments.") + + floc = kwds.pop('floc', None) + fscale = kwds.pop('fscale', None) + + _remove_optimizer_parameters(kwds) + + if floc is not None and fscale is not None: + # This check is for consistency with `rv_continuous.fit`. + raise ValueError("All parameters fixed. There is nothing to " + "optimize.") + + data = np.asarray(data) + + if not np.isfinite(data).all(): + raise ValueError("The data contains non-finite values.") + + data_min = data.min() + + if floc is None: + # ML estimate of the location is the minimum of the data. + loc = data_min + else: + loc = floc + if data_min < loc: + # There are values that are less than the specified loc. + raise FitDataError("expon", lower=floc, upper=np.inf) + + if fscale is None: + # ML estimate of the scale is the shifted mean. + scale = data.mean() - loc + else: + scale = fscale + + # We expect the return values to be floating point, so ensure it + # by explicitly converting to float. + return float(loc), float(scale) + + +expon = expon_gen(a=0.0, name='expon') + + +class exponnorm_gen(rv_continuous): + r"""An exponentially modified Normal continuous random variable. + + Also known as the exponentially modified Gaussian distribution [1]_. + + %(before_notes)s + + Notes + ----- + The probability density function for `exponnorm` is: + + .. math:: + + f(x, K) = \frac{1}{2K} \exp\left(\frac{1}{2 K^2} - x / K \right) + \text{erfc}\left(-\frac{x - 1/K}{\sqrt{2}}\right) + + where :math:`x` is a real number and :math:`K > 0`. + + It can be thought of as the sum of a standard normal random variable + and an independent exponentially distributed random variable with rate + ``1/K``. + + %(after_notes)s + + An alternative parameterization of this distribution (for example, in + the Wikipedia article [1]_) involves three parameters, :math:`\mu`, + :math:`\lambda` and :math:`\sigma`. + + In the present parameterization this corresponds to having ``loc`` and + ``scale`` equal to :math:`\mu` and :math:`\sigma`, respectively, and + shape parameter :math:`K = 1/(\sigma\lambda)`. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] Exponentially modified Gaussian distribution, Wikipedia, + https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("K", False, (0, np.inf), (False, False))] + + def _rvs(self, K, size=None, random_state=None): + expval = random_state.standard_exponential(size) * K + gval = random_state.standard_normal(size) + return expval + gval + + def _pdf(self, x, K): + return np.exp(self._logpdf(x, K)) + + def _logpdf(self, x, K): + invK = 1.0 / K + exparg = invK * (0.5 * invK - x) + return exparg + _norm_logcdf(x - invK) - np.log(K) + + def _cdf(self, x, K): + invK = 1.0 / K + expval = invK * (0.5 * invK - x) + logprod = expval + _norm_logcdf(x - invK) + return _norm_cdf(x) - np.exp(logprod) + + def _sf(self, x, K): + invK = 1.0 / K + expval = invK * (0.5 * invK - x) + logprod = expval + _norm_logcdf(x - invK) + return _norm_cdf(-x) + np.exp(logprod) + + def _stats(self, K): + K2 = K * K + opK2 = 1.0 + K2 + skw = 2 * K**3 * opK2**(-1.5) + krt = 6.0 * K2 * K2 * opK2**(-2) + return K, opK2, skw, krt + + +exponnorm = exponnorm_gen(name='exponnorm') + + +def _pow1pm1(x, y): + """ + Compute (1 + x)**y - 1. + + Uses expm1 and xlog1py to avoid loss of precision when + (1 + x)**y is close to 1. + + Note that the inverse of this function with respect to x is + ``_pow1pm1(x, 1/y)``. That is, if + + t = _pow1pm1(x, y) + + then + + x = _pow1pm1(t, 1/y) + """ + return np.expm1(sc.xlog1py(y, x)) + + +class exponweib_gen(rv_continuous): + r"""An exponentiated Weibull continuous random variable. + + %(before_notes)s + + See Also + -------- + weibull_min, numpy.random.Generator.weibull + + Notes + ----- + The probability density function for `exponweib` is: + + .. math:: + + f(x, a, c) = a c [1-\exp(-x^c)]^{a-1} \exp(-x^c) x^{c-1} + + and its cumulative distribution function is: + + .. math:: + + F(x, a, c) = [1-\exp(-x^c)]^a + + for :math:`x > 0`, :math:`a > 0`, :math:`c > 0`. + + `exponweib` takes :math:`a` and :math:`c` as shape parameters: + + * :math:`a` is the exponentiation parameter, + with the special case :math:`a=1` corresponding to the + (non-exponentiated) Weibull distribution `weibull_min`. + * :math:`c` is the shape parameter of the non-exponentiated Weibull law. + + %(after_notes)s + + References + ---------- + https://en.wikipedia.org/wiki/Exponentiated_Weibull_distribution + + %(example)s + + """ + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ic = _ShapeInfo("c", False, (0, np.inf), (False, False)) + return [ia, ic] + + def _pdf(self, x, a, c): + # exponweib.pdf(x, a, c) = + # a * c * (1-exp(-x**c))**(a-1) * exp(-x**c)*x**(c-1) + return np.exp(self._logpdf(x, a, c)) + + def _logpdf(self, x, a, c): + negxc = -x**c + exm1c = -sc.expm1(negxc) + logp = (np.log(a) + np.log(c) + sc.xlogy(a - 1.0, exm1c) + + negxc + sc.xlogy(c - 1.0, x)) + return logp + + def _cdf(self, x, a, c): + exm1c = -sc.expm1(-x**c) + return exm1c**a + + def _ppf(self, q, a, c): + return (-sc.log1p(-q**(1.0/a)))**np.asarray(1.0/c) + + def _sf(self, x, a, c): + return -_pow1pm1(-np.exp(-x**c), a) + + def _isf(self, p, a, c): + return (-np.log(-_pow1pm1(-p, 1/a)))**(1/c) + + +exponweib = exponweib_gen(a=0.0, name='exponweib') + + +class exponpow_gen(rv_continuous): + r"""An exponential power continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `exponpow` is: + + .. math:: + + f(x, b) = b x^{b-1} \exp(1 + x^b - \exp(x^b)) + + for :math:`x \ge 0`, :math:`b > 0`. Note that this is a different + distribution from the exponential power distribution that is also known + under the names "generalized normal" or "generalized Gaussian". + + `exponpow` takes ``b`` as a shape parameter for :math:`b`. + + %(after_notes)s + + References + ---------- + http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Exponentialpower.pdf + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("b", False, (0, np.inf), (False, False))] + + def _pdf(self, x, b): + # exponpow.pdf(x, b) = b * x**(b-1) * exp(1 + x**b - exp(x**b)) + return np.exp(self._logpdf(x, b)) + + def _logpdf(self, x, b): + xb = x**b + f = 1 + np.log(b) + sc.xlogy(b - 1.0, x) + xb - np.exp(xb) + return f + + def _cdf(self, x, b): + return -sc.expm1(-sc.expm1(x**b)) + + def _sf(self, x, b): + return np.exp(-sc.expm1(x**b)) + + def _isf(self, x, b): + return (sc.log1p(-np.log(x)))**(1./b) + + def _ppf(self, q, b): + return pow(sc.log1p(-sc.log1p(-q)), 1.0/b) + + +exponpow = exponpow_gen(a=0.0, name='exponpow') + + +class fatiguelife_gen(rv_continuous): + r"""A fatigue-life (Birnbaum-Saunders) continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `fatiguelife` is: + + .. math:: + + f(x, c) = \frac{x+1}{2c\sqrt{2\pi x^3}} \exp(-\frac{(x-1)^2}{2x c^2}) + + for :math:`x >= 0` and :math:`c > 0`. + + `fatiguelife` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + References + ---------- + .. [1] "Birnbaum-Saunders distribution", + https://en.wikipedia.org/wiki/Birnbaum-Saunders_distribution + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _rvs(self, c, size=None, random_state=None): + z = random_state.standard_normal(size) + x = 0.5*c*z + x2 = x*x + t = 1.0 + 2*x2 + 2*x*np.sqrt(1 + x2) + return t + + def _pdf(self, x, c): + # fatiguelife.pdf(x, c) = + # (x+1) / (2*c*sqrt(2*pi*x**3)) * exp(-(x-1)**2/(2*x*c**2)) + return np.exp(self._logpdf(x, c)) + + def _logpdf(self, x, c): + return (np.log(x+1) - (x-1)**2 / (2.0*x*c**2) - np.log(2*c) - + 0.5*(np.log(2*np.pi) + 3*np.log(x))) + + def _cdf(self, x, c): + return _norm_cdf(1.0 / c * (np.sqrt(x) - 1.0/np.sqrt(x))) + + def _ppf(self, q, c): + tmp = c * _norm_ppf(q) + return 0.25 * (tmp + np.sqrt(tmp**2 + 4))**2 + + def _sf(self, x, c): + return _norm_sf(1.0 / c * (np.sqrt(x) - 1.0/np.sqrt(x))) + + def _isf(self, q, c): + tmp = -c * _norm_ppf(q) + return 0.25 * (tmp + np.sqrt(tmp**2 + 4))**2 + + def _stats(self, c): + # NB: the formula for kurtosis in wikipedia seems to have an error: + # it's 40, not 41. At least it disagrees with the one from Wolfram + # Alpha. And the latter one, below, passes the tests, while the wiki + # one doesn't So far I didn't have the guts to actually check the + # coefficients from the expressions for the raw moments. + c2 = c*c + mu = c2 / 2.0 + 1.0 + den = 5.0 * c2 + 4.0 + mu2 = c2*den / 4.0 + g1 = 4 * c * (11*c2 + 6.0) / np.power(den, 1.5) + g2 = 6 * c2 * (93*c2 + 40.0) / den**2.0 + return mu, mu2, g1, g2 + + +fatiguelife = fatiguelife_gen(a=0.0, name='fatiguelife') + + +class foldcauchy_gen(rv_continuous): + r"""A folded Cauchy continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `foldcauchy` is: + + .. math:: + + f(x, c) = \frac{1}{\pi (1+(x-c)^2)} + \frac{1}{\pi (1+(x+c)^2)} + + for :math:`x \ge 0` and :math:`c \ge 0`. + + `foldcauchy` takes ``c`` as a shape parameter for :math:`c`. + + %(example)s + + """ + def _argcheck(self, c): + return c >= 0 + + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (True, False))] + + def _rvs(self, c, size=None, random_state=None): + return abs(cauchy.rvs(loc=c, size=size, + random_state=random_state)) + + def _pdf(self, x, c): + # foldcauchy.pdf(x, c) = 1/(pi*(1+(x-c)**2)) + 1/(pi*(1+(x+c)**2)) + return 1.0/np.pi*(1.0/(1+(x-c)**2) + 1.0/(1+(x+c)**2)) + + def _cdf(self, x, c): + return 1.0/np.pi*(np.arctan(x-c) + np.arctan(x+c)) + + def _sf(self, x, c): + # 1 - CDF(x, c) = 1 - (atan(x - c) + atan(x + c))/pi + # = ((pi/2 - atan(x - c)) + (pi/2 - atan(x + c)))/pi + # = (acot(x - c) + acot(x + c))/pi + # = (atan2(1, x - c) + atan2(1, x + c))/pi + return (np.arctan2(1, x - c) + np.arctan2(1, x + c))/np.pi + + def _stats(self, c): + return np.inf, np.inf, np.nan, np.nan + + +foldcauchy = foldcauchy_gen(a=0.0, name='foldcauchy') + + +class f_gen(rv_continuous): + r"""An F continuous random variable. + + For the noncentral F distribution, see `ncf`. + + %(before_notes)s + + See Also + -------- + ncf + + Notes + ----- + The F distribution with :math:`df_1 > 0` and :math:`df_2 > 0` degrees of freedom is + the distribution of the ratio of two independent chi-squared distributions with + :math:`df_1` and :math:`df_2` degrees of freedom, after rescaling by + :math:`df_2 / df_1`. + + The probability density function for `f` is: + + .. math:: + + f(x, df_1, df_2) = \frac{df_2^{df_2/2} df_1^{df_1/2} x^{df_1 / 2-1}} + {(df_2+df_1 x)^{(df_1+df_2)/2} + B(df_1/2, df_2/2)} + + for :math:`x > 0`. + + `f` accepts shape parameters ``dfn`` and ``dfd`` for :math:`df_1`, the degrees of + freedom of the chi-squared distribution in the numerator, and :math:`df_2`, the + degrees of freedom of the chi-squared distribution in the denominator, respectively. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + idfn = _ShapeInfo("dfn", False, (0, np.inf), (False, False)) + idfd = _ShapeInfo("dfd", False, (0, np.inf), (False, False)) + return [idfn, idfd] + + def _rvs(self, dfn, dfd, size=None, random_state=None): + return random_state.f(dfn, dfd, size) + + def _pdf(self, x, dfn, dfd): + # df2**(df2/2) * df1**(df1/2) * x**(df1/2-1) + # F.pdf(x, df1, df2) = -------------------------------------------- + # (df2+df1*x)**((df1+df2)/2) * B(df1/2, df2/2) + return np.exp(self._logpdf(x, dfn, dfd)) + + def _logpdf(self, x, dfn, dfd): + n = 1.0 * dfn + m = 1.0 * dfd + lPx = (m/2 * np.log(m) + n/2 * np.log(n) + sc.xlogy(n/2 - 1, x) + - (((n+m)/2) * np.log(m + n*x) + sc.betaln(n/2, m/2))) + return lPx + + def _cdf(self, x, dfn, dfd): + return sc.fdtr(dfn, dfd, x) + + def _sf(self, x, dfn, dfd): + return sc.fdtrc(dfn, dfd, x) + + def _ppf(self, q, dfn, dfd): + return sc.fdtri(dfn, dfd, q) + + def _stats(self, dfn, dfd): + v1, v2 = 1. * dfn, 1. * dfd + v2_2, v2_4, v2_6, v2_8 = v2 - 2., v2 - 4., v2 - 6., v2 - 8. + + mu = _lazywhere( + v2 > 2, (v2, v2_2), + lambda v2, v2_2: v2 / v2_2, + np.inf) + + mu2 = _lazywhere( + v2 > 4, (v1, v2, v2_2, v2_4), + lambda v1, v2, v2_2, v2_4: + 2 * v2 * v2 * (v1 + v2_2) / (v1 * v2_2**2 * v2_4), + np.inf) + + g1 = _lazywhere( + v2 > 6, (v1, v2_2, v2_4, v2_6), + lambda v1, v2_2, v2_4, v2_6: + (2 * v1 + v2_2) / v2_6 * np.sqrt(v2_4 / (v1 * (v1 + v2_2))), + np.nan) + g1 *= np.sqrt(8.) + + g2 = _lazywhere( + v2 > 8, (g1, v2_6, v2_8), + lambda g1, v2_6, v2_8: (8 + g1 * g1 * v2_6) / v2_8, + np.nan) + g2 *= 3. / 2. + + return mu, mu2, g1, g2 + + def _entropy(self, dfn, dfd): + # the formula found in literature is incorrect. This one yields the + # same result as numerical integration using the generic entropy + # definition. This is also tested in tests/test_conntinous_basic + half_dfn = 0.5 * dfn + half_dfd = 0.5 * dfd + half_sum = 0.5 * (dfn + dfd) + + return (np.log(dfd) - np.log(dfn) + sc.betaln(half_dfn, half_dfd) + + (1 - half_dfn) * sc.psi(half_dfn) - (1 + half_dfd) * + sc.psi(half_dfd) + half_sum * sc.psi(half_sum)) + + +f = f_gen(a=0.0, name='f') + + +## Folded Normal +## abs(Z) where (Z is normal with mu=L and std=S so that c=abs(L)/S) +## +## note: regress docs have scale parameter correct, but first parameter +## he gives is a shape parameter A = c * scale + +## Half-normal is folded normal with shape-parameter c=0. + +class foldnorm_gen(rv_continuous): + r"""A folded normal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `foldnorm` is: + + .. math:: + + f(x, c) = \sqrt{2/\pi} cosh(c x) \exp(-\frac{x^2+c^2}{2}) + + for :math:`x \ge 0` and :math:`c \ge 0`. + + `foldnorm` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + def _argcheck(self, c): + return c >= 0 + + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (True, False))] + + def _rvs(self, c, size=None, random_state=None): + return abs(random_state.standard_normal(size) + c) + + def _pdf(self, x, c): + # foldnormal.pdf(x, c) = sqrt(2/pi) * cosh(c*x) * exp(-(x**2+c**2)/2) + return _norm_pdf(x + c) + _norm_pdf(x-c) + + def _cdf(self, x, c): + sqrt_two = np.sqrt(2) + return 0.5 * (sc.erf((x - c)/sqrt_two) + sc.erf((x + c)/sqrt_two)) + + def _sf(self, x, c): + return _norm_sf(x - c) + _norm_sf(x + c) + + def _stats(self, c): + # Regina C. Elandt, Technometrics 3, 551 (1961) + # https://www.jstor.org/stable/1266561 + # + c2 = c*c + expfac = np.exp(-0.5*c2) / np.sqrt(2.*np.pi) + + mu = 2.*expfac + c * sc.erf(c/np.sqrt(2)) + mu2 = c2 + 1 - mu*mu + + g1 = 2. * (mu*mu*mu - c2*mu - expfac) + g1 /= np.power(mu2, 1.5) + + g2 = c2 * (c2 + 6.) + 3 + 8.*expfac*mu + g2 += (2. * (c2 - 3.) - 3. * mu**2) * mu**2 + g2 = g2 / mu2**2.0 - 3. + + return mu, mu2, g1, g2 + + +foldnorm = foldnorm_gen(a=0.0, name='foldnorm') + + +class weibull_min_gen(rv_continuous): + r"""Weibull minimum continuous random variable. + + The Weibull Minimum Extreme Value distribution, from extreme value theory + (Fisher-Gnedenko theorem), is also often simply called the Weibull + distribution. It arises as the limiting distribution of the rescaled + minimum of iid random variables. + + %(before_notes)s + + See Also + -------- + weibull_max, numpy.random.Generator.weibull, exponweib + + Notes + ----- + The probability density function for `weibull_min` is: + + .. math:: + + f(x, c) = c x^{c-1} \exp(-x^c) + + for :math:`x > 0`, :math:`c > 0`. + + `weibull_min` takes ``c`` as a shape parameter for :math:`c`. + (named :math:`k` in Wikipedia article and :math:`a` in + ``numpy.random.weibull``). Special shape values are :math:`c=1` and + :math:`c=2` where Weibull distribution reduces to the `expon` and + `rayleigh` distributions respectively. + + Suppose ``X`` is an exponentially distributed random variable with + scale ``s``. Then ``Y = X**k`` is `weibull_min` distributed with shape + ``c = 1/k`` and scale ``s**k``. + + %(after_notes)s + + References + ---------- + https://en.wikipedia.org/wiki/Weibull_distribution + + https://en.wikipedia.org/wiki/Fisher-Tippett-Gnedenko_theorem + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # weibull_min.pdf(x, c) = c * x**(c-1) * exp(-x**c) + return c*pow(x, c-1)*np.exp(-pow(x, c)) + + def _logpdf(self, x, c): + return np.log(c) + sc.xlogy(c - 1, x) - pow(x, c) + + def _cdf(self, x, c): + return -sc.expm1(-pow(x, c)) + + def _ppf(self, q, c): + return pow(-sc.log1p(-q), 1.0/c) + + def _sf(self, x, c): + return np.exp(self._logsf(x, c)) + + def _logsf(self, x, c): + return -pow(x, c) + + def _isf(self, q, c): + return (-np.log(q))**(1/c) + + def _munp(self, n, c): + return sc.gamma(1.0+n*1.0/c) + + def _entropy(self, c): + return -_EULER / c - np.log(c) + _EULER + 1 + + @extend_notes_in_docstring(rv_continuous, notes="""\ + If ``method='mm'``, parameters fixed by the user are respected, and the + remaining parameters are used to match distribution and sample moments + where possible. For example, if the user fixes the location with + ``floc``, the parameters will only match the distribution skewness and + variance to the sample skewness and variance; no attempt will be made + to match the means or minimize a norm of the errors. + \n\n""") + def fit(self, data, *args, **kwds): + + if isinstance(data, CensoredData): + if data.num_censored() == 0: + data = data._uncensor() + else: + return super().fit(data, *args, **kwds) + + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + # this extracts fixed shape, location, and scale however they + # are specified, and also leaves them in `kwds` + data, fc, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + method = kwds.get("method", "mle").lower() + + # See https://en.wikipedia.org/wiki/Weibull_distribution#Moments for + # moment formulas. + def skew(c): + gamma1 = sc.gamma(1+1/c) + gamma2 = sc.gamma(1+2/c) + gamma3 = sc.gamma(1+3/c) + num = 2 * gamma1**3 - 3*gamma1*gamma2 + gamma3 + den = (gamma2 - gamma1**2)**(3/2) + return num/den + + # For c in [1e2, 3e4], population skewness appears to approach + # asymptote near -1.139, but past c > 3e4, skewness begins to vary + # wildly, and MoM won't provide a good guess. Get out early. + s = stats.skew(data) + max_c = 1e4 + s_min = skew(max_c) + if s < s_min and method != "mm" and fc is None and not args: + return super().fit(data, *args, **kwds) + + # If method is method of moments, we don't need the user's guesses. + # Otherwise, extract the guesses from args and kwds. + if method == "mm": + c, loc, scale = None, None, None + else: + c = args[0] if len(args) else None + loc = kwds.pop('loc', None) + scale = kwds.pop('scale', None) + + if fc is None and c is None: # not fixed and no guess: use MoM + # Solve for c that matches sample distribution skewness to sample + # skewness. + # we start having numerical issues with `weibull_min` with + # parameters outside this range - and not just in this method. + # We could probably improve the situation by doing everything + # in the log space, but that is for another time. + c = root_scalar(lambda c: skew(c) - s, bracket=[0.02, max_c], + method='bisect').root + elif fc is not None: # fixed: use it + c = fc + + if fscale is None and scale is None: + v = np.var(data) + scale = np.sqrt(v / (sc.gamma(1+2/c) - sc.gamma(1+1/c)**2)) + elif fscale is not None: + scale = fscale + + if floc is None and loc is None: + m = np.mean(data) + loc = m - scale*sc.gamma(1 + 1/c) + elif floc is not None: + loc = floc + + if method == 'mm': + return c, loc, scale + else: + # At this point, parameter "guesses" may equal the fixed parameters + # in kwds. No harm in passing them as guesses, too. + return super().fit(data, c, loc=loc, scale=scale, **kwds) + + +weibull_min = weibull_min_gen(a=0.0, name='weibull_min') + + +class truncweibull_min_gen(rv_continuous): + r"""A doubly truncated Weibull minimum continuous random variable. + + %(before_notes)s + + See Also + -------- + weibull_min, truncexpon + + Notes + ----- + The probability density function for `truncweibull_min` is: + + .. math:: + + f(x, a, b, c) = \frac{c x^{c-1} \exp(-x^c)}{\exp(-a^c) - \exp(-b^c)} + + for :math:`a < x <= b`, :math:`0 \le a < b` and :math:`c > 0`. + + `truncweibull_min` takes :math:`a`, :math:`b`, and :math:`c` as shape + parameters. + + Notice that the truncation values, :math:`a` and :math:`b`, are defined in + standardized form: + + .. math:: + + a = (u_l - loc)/scale + b = (u_r - loc)/scale + + where :math:`u_l` and :math:`u_r` are the specific left and right + truncation values, respectively. In other words, the support of the + distribution becomes :math:`(a*scale + loc) < x <= (b*scale + loc)` when + :math:`loc` and/or :math:`scale` are provided. + + %(after_notes)s + + References + ---------- + + .. [1] Rinne, H. "The Weibull Distribution: A Handbook". CRC Press (2009). + + %(example)s + + """ + def _argcheck(self, c, a, b): + return (a >= 0.) & (b > a) & (c > 0.) + + def _shape_info(self): + ic = _ShapeInfo("c", False, (0, np.inf), (False, False)) + ia = _ShapeInfo("a", False, (0, np.inf), (True, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ic, ia, ib] + + def _fitstart(self, data): + # Arbitrary, but default a=b=c=1 is not valid + return super()._fitstart(data, args=(1, 0, 1)) + + def _get_support(self, c, a, b): + return a, b + + def _pdf(self, x, c, a, b): + denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c))) + return (c * pow(x, c-1) * np.exp(-pow(x, c))) / denum + + def _logpdf(self, x, c, a, b): + logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c))) + return np.log(c) + sc.xlogy(c - 1, x) - pow(x, c) - logdenum + + def _cdf(self, x, c, a, b): + num = (np.exp(-pow(a, c)) - np.exp(-pow(x, c))) + denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c))) + return num / denum + + def _logcdf(self, x, c, a, b): + lognum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(x, c))) + logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c))) + return lognum - logdenum + + def _sf(self, x, c, a, b): + num = (np.exp(-pow(x, c)) - np.exp(-pow(b, c))) + denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c))) + return num / denum + + def _logsf(self, x, c, a, b): + lognum = np.log(np.exp(-pow(x, c)) - np.exp(-pow(b, c))) + logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c))) + return lognum - logdenum + + def _isf(self, q, c, a, b): + return pow( + -np.log((1 - q) * np.exp(-pow(b, c)) + q * np.exp(-pow(a, c))), 1/c + ) + + def _ppf(self, q, c, a, b): + return pow( + -np.log((1 - q) * np.exp(-pow(a, c)) + q * np.exp(-pow(b, c))), 1/c + ) + + def _munp(self, n, c, a, b): + gamma_fun = sc.gamma(n/c + 1.) * ( + sc.gammainc(n/c + 1., pow(b, c)) - sc.gammainc(n/c + 1., pow(a, c)) + ) + denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c))) + return gamma_fun / denum + + +truncweibull_min = truncweibull_min_gen(name='truncweibull_min') +truncweibull_min._support = ('a', 'b') + + +class weibull_max_gen(rv_continuous): + r"""Weibull maximum continuous random variable. + + The Weibull Maximum Extreme Value distribution, from extreme value theory + (Fisher-Gnedenko theorem), is the limiting distribution of rescaled + maximum of iid random variables. This is the distribution of -X + if X is from the `weibull_min` function. + + %(before_notes)s + + See Also + -------- + weibull_min + + Notes + ----- + The probability density function for `weibull_max` is: + + .. math:: + + f(x, c) = c (-x)^{c-1} \exp(-(-x)^c) + + for :math:`x < 0`, :math:`c > 0`. + + `weibull_max` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + References + ---------- + https://en.wikipedia.org/wiki/Weibull_distribution + + https://en.wikipedia.org/wiki/Fisher-Tippett-Gnedenko_theorem + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # weibull_max.pdf(x, c) = c * (-x)**(c-1) * exp(-(-x)**c) + return c*pow(-x, c-1)*np.exp(-pow(-x, c)) + + def _logpdf(self, x, c): + return np.log(c) + sc.xlogy(c-1, -x) - pow(-x, c) + + def _cdf(self, x, c): + return np.exp(-pow(-x, c)) + + def _logcdf(self, x, c): + return -pow(-x, c) + + def _sf(self, x, c): + return -sc.expm1(-pow(-x, c)) + + def _ppf(self, q, c): + return -pow(-np.log(q), 1.0/c) + + def _munp(self, n, c): + val = sc.gamma(1.0+n*1.0/c) + if int(n) % 2: + sgn = -1 + else: + sgn = 1 + return sgn * val + + def _entropy(self, c): + return -_EULER / c - np.log(c) + _EULER + 1 + + +weibull_max = weibull_max_gen(b=0.0, name='weibull_max') + + +class genlogistic_gen(rv_continuous): + r"""A generalized logistic continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `genlogistic` is: + + .. math:: + + f(x, c) = c \frac{\exp(-x)} + {(1 + \exp(-x))^{c+1}} + + for real :math:`x` and :math:`c > 0`. In literature, different + generalizations of the logistic distribution can be found. This is the type 1 + generalized logistic distribution according to [1]_. It is also referred to + as the skew-logistic distribution [2]_. + + `genlogistic` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + References + ---------- + .. [1] Johnson et al. "Continuous Univariate Distributions", Volume 2, + Wiley. 1995. + .. [2] "Generalized Logistic Distribution", Wikipedia, + https://en.wikipedia.org/wiki/Generalized_logistic_distribution + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # genlogistic.pdf(x, c) = c * exp(-x) / (1 + exp(-x))**(c+1) + return np.exp(self._logpdf(x, c)) + + def _logpdf(self, x, c): + # Two mathematically equivalent expressions for log(pdf(x, c)): + # log(pdf(x, c)) = log(c) - x - (c + 1)*log(1 + exp(-x)) + # = log(c) + c*x - (c + 1)*log(1 + exp(x)) + mult = -(c - 1) * (x < 0) - 1 + absx = np.abs(x) + return np.log(c) + mult*absx - (c+1) * sc.log1p(np.exp(-absx)) + + def _cdf(self, x, c): + Cx = (1+np.exp(-x))**(-c) + return Cx + + def _logcdf(self, x, c): + return -c * np.log1p(np.exp(-x)) + + def _ppf(self, q, c): + return -np.log(sc.powm1(q, -1.0/c)) + + def _sf(self, x, c): + return -sc.expm1(self._logcdf(x, c)) + + def _isf(self, q, c): + return self._ppf(1 - q, c) + + def _stats(self, c): + mu = _EULER + sc.psi(c) + mu2 = np.pi*np.pi/6.0 + sc.zeta(2, c) + g1 = -2*sc.zeta(3, c) + 2*_ZETA3 + g1 /= np.power(mu2, 1.5) + g2 = np.pi**4/15.0 + 6*sc.zeta(4, c) + g2 /= mu2**2.0 + return mu, mu2, g1, g2 + + def _entropy(self, c): + return _lazywhere(c < 8e6, (c, ), + lambda c: -np.log(c) + sc.psi(c + 1) + _EULER + 1, + # asymptotic expansion: psi(c) ~ log(c) - 1/(2 * c) + # a = -log(c) + psi(c + 1) + # = -log(c) + psi(c) + 1/c + # ~ -log(c) + log(c) - 1/(2 * c) + 1/c + # = 1/(2 * c) + f2=lambda c: 1/(2 * c) + _EULER + 1) + + +genlogistic = genlogistic_gen(name='genlogistic') + + +class genpareto_gen(rv_continuous): + r"""A generalized Pareto continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `genpareto` is: + + .. math:: + + f(x, c) = (1 + c x)^{-1 - 1/c} + + defined for :math:`x \ge 0` if :math:`c \ge 0`, and for + :math:`0 \le x \le -1/c` if :math:`c < 0`. + + `genpareto` takes ``c`` as a shape parameter for :math:`c`. + + For :math:`c=0`, `genpareto` reduces to the exponential + distribution, `expon`: + + .. math:: + + f(x, 0) = \exp(-x) + + For :math:`c=-1`, `genpareto` is uniform on ``[0, 1]``: + + .. math:: + + f(x, -1) = 1 + + %(after_notes)s + + %(example)s + + """ + def _argcheck(self, c): + return np.isfinite(c) + + def _shape_info(self): + return [_ShapeInfo("c", False, (-np.inf, np.inf), (False, False))] + + def _get_support(self, c): + c = np.asarray(c) + b = _lazywhere(c < 0, (c,), + lambda c: -1. / c, + np.inf) + a = np.where(c >= 0, self.a, self.a) + return a, b + + def _pdf(self, x, c): + # genpareto.pdf(x, c) = (1 + c * x)**(-1 - 1/c) + return np.exp(self._logpdf(x, c)) + + def _logpdf(self, x, c): + return _lazywhere((x == x) & (c != 0), (x, c), + lambda x, c: -sc.xlog1py(c + 1., c*x) / c, + -x) + + def _cdf(self, x, c): + return -sc.inv_boxcox1p(-x, -c) + + def _sf(self, x, c): + return sc.inv_boxcox(-x, -c) + + def _logsf(self, x, c): + return _lazywhere((x == x) & (c != 0), (x, c), + lambda x, c: -sc.log1p(c*x) / c, + -x) + + def _ppf(self, q, c): + return -sc.boxcox1p(-q, -c) + + def _isf(self, q, c): + return -sc.boxcox(q, -c) + + def _stats(self, c, moments='mv'): + if 'm' not in moments: + m = None + else: + m = _lazywhere(c < 1, (c,), + lambda xi: 1/(1 - xi), + np.inf) + if 'v' not in moments: + v = None + else: + v = _lazywhere(c < 1/2, (c,), + lambda xi: 1 / (1 - xi)**2 / (1 - 2*xi), + np.nan) + if 's' not in moments: + s = None + else: + s = _lazywhere(c < 1/3, (c,), + lambda xi: (2 * (1 + xi) * np.sqrt(1 - 2*xi) / + (1 - 3*xi)), + np.nan) + if 'k' not in moments: + k = None + else: + k = _lazywhere(c < 1/4, (c,), + lambda xi: (3 * (1 - 2*xi) * (2*xi**2 + xi + 3) / + (1 - 3*xi) / (1 - 4*xi) - 3), + np.nan) + return m, v, s, k + + def _munp(self, n, c): + def __munp(n, c): + val = 0.0 + k = np.arange(0, n + 1) + for ki, cnk in zip(k, sc.comb(n, k)): + val = val + cnk * (-1) ** ki / (1.0 - c * ki) + return np.where(c * n < 1, val * (-1.0 / c) ** n, np.inf) + return _lazywhere(c != 0, (c,), + lambda c: __munp(n, c), + sc.gamma(n + 1)) + + def _entropy(self, c): + return 1. + c + + +genpareto = genpareto_gen(a=0.0, name='genpareto') + + +class genexpon_gen(rv_continuous): + r"""A generalized exponential continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `genexpon` is: + + .. math:: + + f(x, a, b, c) = (a + b (1 - \exp(-c x))) + \exp(-a x - b x + \frac{b}{c} (1-\exp(-c x))) + + for :math:`x \ge 0`, :math:`a, b, c > 0`. + + `genexpon` takes :math:`a`, :math:`b` and :math:`c` as shape parameters. + + %(after_notes)s + + References + ---------- + H.K. Ryu, "An Extension of Marshall and Olkin's Bivariate Exponential + Distribution", Journal of the American Statistical Association, 1993. + + N. Balakrishnan, Asit P. Basu (editors), *The Exponential Distribution: + Theory, Methods and Applications*, Gordon and Breach, 1995. + ISBN 10: 2884491929 + + %(example)s + + """ + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + ic = _ShapeInfo("c", False, (0, np.inf), (False, False)) + return [ia, ib, ic] + + def _pdf(self, x, a, b, c): + # genexpon.pdf(x, a, b, c) = (a + b * (1 - exp(-c*x))) * \ + # exp(-a*x - b*x + b/c * (1-exp(-c*x))) + return (a + b*(-sc.expm1(-c*x)))*np.exp((-a-b)*x + + b*(-sc.expm1(-c*x))/c) + + def _logpdf(self, x, a, b, c): + return np.log(a+b*(-sc.expm1(-c*x))) + (-a-b)*x+b*(-sc.expm1(-c*x))/c + + def _cdf(self, x, a, b, c): + return -sc.expm1((-a-b)*x + b*(-sc.expm1(-c*x))/c) + + def _ppf(self, p, a, b, c): + s = a + b + t = (b - c*np.log1p(-p))/s + return (t + sc.lambertw(-b/s * np.exp(-t)).real)/c + + def _sf(self, x, a, b, c): + return np.exp((-a-b)*x + b*(-sc.expm1(-c*x))/c) + + def _isf(self, p, a, b, c): + s = a + b + t = (b - c*np.log(p))/s + return (t + sc.lambertw(-b/s * np.exp(-t)).real)/c + + +genexpon = genexpon_gen(a=0.0, name='genexpon') + + +class genextreme_gen(rv_continuous): + r"""A generalized extreme value continuous random variable. + + %(before_notes)s + + See Also + -------- + gumbel_r + + Notes + ----- + For :math:`c=0`, `genextreme` is equal to `gumbel_r` with + probability density function + + .. math:: + + f(x) = \exp(-\exp(-x)) \exp(-x), + + where :math:`-\infty < x < \infty`. + + For :math:`c \ne 0`, the probability density function for `genextreme` is: + + .. math:: + + f(x, c) = \exp(-(1-c x)^{1/c}) (1-c x)^{1/c-1}, + + where :math:`-\infty < x \le 1/c` if :math:`c > 0` and + :math:`1/c \le x < \infty` if :math:`c < 0`. + + Note that several sources and software packages use the opposite + convention for the sign of the shape parameter :math:`c`. + + `genextreme` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + def _argcheck(self, c): + return np.isfinite(c) + + def _shape_info(self): + return [_ShapeInfo("c", False, (-np.inf, np.inf), (False, False))] + + def _get_support(self, c): + _b = np.where(c > 0, 1.0 / np.maximum(c, _XMIN), np.inf) + _a = np.where(c < 0, 1.0 / np.minimum(c, -_XMIN), -np.inf) + return _a, _b + + def _loglogcdf(self, x, c): + # Returns log(-log(cdf(x, c))) + return _lazywhere((x == x) & (c != 0), (x, c), + lambda x, c: sc.log1p(-c*x)/c, -x) + + def _pdf(self, x, c): + # genextreme.pdf(x, c) = + # exp(-exp(-x))*exp(-x), for c==0 + # exp(-(1-c*x)**(1/c))*(1-c*x)**(1/c-1), for x \le 1/c, c > 0 + return np.exp(self._logpdf(x, c)) + + def _logpdf(self, x, c): + cx = _lazywhere((x == x) & (c != 0), (x, c), lambda x, c: c*x, 0.0) + logex2 = sc.log1p(-cx) + logpex2 = self._loglogcdf(x, c) + pex2 = np.exp(logpex2) + # Handle special cases + np.putmask(logpex2, (c == 0) & (x == -np.inf), 0.0) + logpdf = _lazywhere(~((cx == 1) | (cx == -np.inf)), + (pex2, logpex2, logex2), + lambda pex2, lpex2, lex2: -pex2 + lpex2 - lex2, + fillvalue=-np.inf) + np.putmask(logpdf, (c == 1) & (x == 1), 0.0) + return logpdf + + def _logcdf(self, x, c): + return -np.exp(self._loglogcdf(x, c)) + + def _cdf(self, x, c): + return np.exp(self._logcdf(x, c)) + + def _sf(self, x, c): + return -sc.expm1(self._logcdf(x, c)) + + def _ppf(self, q, c): + x = -np.log(-np.log(q)) + return _lazywhere((x == x) & (c != 0), (x, c), + lambda x, c: -sc.expm1(-c * x) / c, x) + + def _isf(self, q, c): + x = -np.log(-sc.log1p(-q)) + return _lazywhere((x == x) & (c != 0), (x, c), + lambda x, c: -sc.expm1(-c * x) / c, x) + + def _stats(self, c): + def g(n): + return sc.gamma(n * c + 1) + g1 = g(1) + g2 = g(2) + g3 = g(3) + g4 = g(4) + g2mg12 = np.where(abs(c) < 1e-7, (c*np.pi)**2.0/6.0, g2-g1**2.0) + def gam2k_f(c): + return sc.expm1(sc.gammaln(2.0*c+1.0)-2*sc.gammaln(c + 1.0))/c**2.0 + gam2k = _lazywhere(abs(c) >= 1e-7, (c,), f=gam2k_f, fillvalue=np.pi**2.0/6.0) + eps = 1e-14 + def gamk_f(c): + return sc.expm1(sc.gammaln(c + 1))/c + gamk = _lazywhere(abs(c) >= eps, (c,), f=gamk_f, fillvalue=-_EULER) + + # mean + m = np.where(c < -1.0, np.nan, -gamk) + + # variance + v = np.where(c < -0.5, np.nan, g1**2.0*gam2k) + + # skewness + def sk1_eval(c, *args): + def sk1_eval_f(c, g1, g2, g3, g2mg12): + return np.sign(c)*(-g3 + (g2 + 2*g2mg12)*g1)/g2mg12**1.5 + return _lazywhere(c >= -1./3, (c,)+args, f=sk1_eval_f, fillvalue=np.nan) + + sk_fill = 12*np.sqrt(6)*_ZETA3/np.pi**3 + args = (g1, g2, g3, g2mg12) + sk = _lazywhere(abs(c) > eps**0.29, (c,)+args, f=sk1_eval, fillvalue=sk_fill) + + # kurtosis + def ku1_eval(c, *args): + def ku1_eval_f(g1, g2, g3, g4, g2mg12): + return (g4 + (-4*g3 + 3*(g2 + g2mg12)*g1)*g1)/g2mg12**2 - 3 + return _lazywhere(c >= -1./4, args, ku1_eval_f, fillvalue=np.nan) + + args = (g1, g2, g3, g4, g2mg12) + ku = _lazywhere(abs(c) > eps**0.23, (c,)+args, f=ku1_eval, fillvalue=12.0/5.0) + + return m, v, sk, ku + + def _fitstart(self, data): + if isinstance(data, CensoredData): + data = data._uncensor() + # This is better than the default shape of (1,). + g = _skew(data) + if g < 0: + a = 0.5 + else: + a = -0.5 + return super()._fitstart(data, args=(a,)) + + def _munp(self, n, c): + k = np.arange(0, n+1) + vals = 1.0/c**n * np.sum( + sc.comb(n, k) * (-1)**k * sc.gamma(c*k + 1), + axis=0) + return np.where(c*n > -1, vals, np.inf) + + def _entropy(self, c): + return _EULER*(1 - c) + 1 + + +genextreme = genextreme_gen(name='genextreme') + + +def _digammainv(y): + """Inverse of the digamma function (real positive arguments only). + + This function is used in the `fit` method of `gamma_gen`. + The function uses either optimize.fsolve or optimize.newton + to solve `sc.digamma(x) - y = 0`. There is probably room for + improvement, but currently it works over a wide range of y: + + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> y = 64*rng.standard_normal(1000000) + >>> y.min(), y.max() + (-311.43592651416662, 351.77388222276869) + >>> x = [_digammainv(t) for t in y] + >>> np.abs(sc.digamma(x) - y).max() + 1.1368683772161603e-13 + + """ + _em = 0.5772156649015328606065120 + + def func(x): + return sc.digamma(x) - y + + if y > -0.125: + x0 = np.exp(y) + 0.5 + if y < 10: + # Some experimentation shows that newton reliably converges + # must faster than fsolve in this y range. For larger y, + # newton sometimes fails to converge. + value = optimize.newton(func, x0, tol=1e-10) + return value + elif y > -3: + x0 = np.exp(y/2.332) + 0.08661 + else: + x0 = 1.0 / (-y - _em) + + value, info, ier, mesg = optimize.fsolve(func, x0, xtol=1e-11, + full_output=True) + if ier != 1: + raise RuntimeError(f"_digammainv: fsolve failed, y = {y!r}") + + return value[0] + + +## Gamma (Use MATLAB and MATHEMATICA (b=theta=scale, a=alpha=shape) definition) + +## gamma(a, loc, scale) with a an integer is the Erlang distribution +## gamma(1, loc, scale) is the Exponential distribution +## gamma(df/2, 0, 2) is the chi2 distribution with df degrees of freedom. + +class gamma_gen(rv_continuous): + r"""A gamma continuous random variable. + + %(before_notes)s + + See Also + -------- + erlang, expon + + Notes + ----- + The probability density function for `gamma` is: + + .. math:: + + f(x, a) = \frac{x^{a-1} e^{-x}}{\Gamma(a)} + + for :math:`x \ge 0`, :math:`a > 0`. Here :math:`\Gamma(a)` refers to the + gamma function. + + `gamma` takes ``a`` as a shape parameter for :math:`a`. + + When :math:`a` is an integer, `gamma` reduces to the Erlang + distribution, and when :math:`a=1` to the exponential distribution. + + Gamma distributions are sometimes parameterized with two variables, + with a probability density function of: + + .. math:: + + f(x, \alpha, \beta) = + \frac{\beta^\alpha x^{\alpha - 1} e^{-\beta x }}{\Gamma(\alpha)} + + Note that this parameterization is equivalent to the above, with + ``scale = 1 / beta``. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (False, False))] + + def _rvs(self, a, size=None, random_state=None): + return random_state.standard_gamma(a, size) + + def _pdf(self, x, a): + # gamma.pdf(x, a) = x**(a-1) * exp(-x) / gamma(a) + return np.exp(self._logpdf(x, a)) + + def _logpdf(self, x, a): + return sc.xlogy(a-1.0, x) - x - sc.gammaln(a) + + def _cdf(self, x, a): + return sc.gammainc(a, x) + + def _sf(self, x, a): + return sc.gammaincc(a, x) + + def _ppf(self, q, a): + return sc.gammaincinv(a, q) + + def _isf(self, q, a): + return sc.gammainccinv(a, q) + + def _stats(self, a): + return a, a, 2.0/np.sqrt(a), 6.0/a + + def _munp(self, n, a): + return sc.poch(a, n) + + def _entropy(self, a): + + def regular_formula(a): + return sc.psi(a) * (1-a) + a + sc.gammaln(a) + + def asymptotic_formula(a): + # plug in above formula the expansions: + # psi(a) ~ ln(a) - 1/2a - 1/12a^2 + 1/120a^4 + # gammaln(a) ~ a * ln(a) - a - 1/2 * ln(a) + 1/2 ln(2 * pi) + + # 1/12a - 1/360a^3 + return (0.5 * (1. + np.log(2*np.pi) + np.log(a)) - 1/(3 * a) + - (a**-2.)/12 - (a**-3.)/90 + (a**-4.)/120) + + return _lazywhere(a < 250, (a, ), regular_formula, + f2=asymptotic_formula) + + def _fitstart(self, data): + # The skewness of the gamma distribution is `2 / np.sqrt(a)`. + # We invert that to estimate the shape `a` using the skewness + # of the data. The formula is regularized with 1e-8 in the + # denominator to allow for degenerate data where the skewness + # is close to 0. + if isinstance(data, CensoredData): + data = data._uncensor() + sk = _skew(data) + a = 4 / (1e-8 + sk**2) + return super()._fitstart(data, args=(a,)) + + @extend_notes_in_docstring(rv_continuous, notes="""\ + When the location is fixed by using the argument `floc` + and `method='MLE'`, this + function uses explicit formulas or solves a simpler numerical + problem than the full ML optimization problem. So in that case, + the `optimizer`, `loc` and `scale` arguments are ignored. + \n\n""") + def fit(self, data, *args, **kwds): + floc = kwds.get('floc', None) + method = kwds.get('method', 'mle') + + if (isinstance(data, CensoredData) or + floc is None and method.lower() != 'mm'): + # loc is not fixed or we're not doing standard MLE. + # Use the default fit method. + return super().fit(data, *args, **kwds) + + # We already have this value, so just pop it from kwds. + kwds.pop('floc', None) + + f0 = _get_fixed_fit_value(kwds, ['f0', 'fa', 'fix_a']) + fscale = kwds.pop('fscale', None) + + _remove_optimizer_parameters(kwds) + + if f0 is not None and floc is not None and fscale is not None: + # This check is for consistency with `rv_continuous.fit`. + # Without this check, this function would just return the + # parameters that were given. + raise ValueError("All parameters fixed. There is nothing to " + "optimize.") + + # Fixed location is handled by shifting the data. + data = np.asarray(data) + + if not np.isfinite(data).all(): + raise ValueError("The data contains non-finite values.") + + # Use explicit formulas for mm (gh-19884) + if method.lower() == 'mm': + m1 = np.mean(data) + m2 = np.var(data) + m3 = np.mean((data - m1) ** 3) + a, loc, scale = f0, floc, fscale + # Three unknowns + if a is None and loc is None and scale is None: + scale = m3 / (2 * m2) + # Two unknowns + if loc is None and scale is None: + scale = np.sqrt(m2 / a) + if a is None and scale is None: + scale = m2 / (m1 - loc) + if a is None and loc is None: + a = m2 / (scale ** 2) + # One unknown + if a is None: + a = (m1 - loc) / scale + if loc is None: + loc = m1 - a * scale + if scale is None: + scale = (m1 - loc) / a + return a, loc, scale + + # Special case: loc is fixed. + + # NB: data == loc is ok if a >= 1; the below check is more strict. + if np.any(data <= floc): + raise FitDataError("gamma", lower=floc, upper=np.inf) + + if floc != 0: + # Don't do the subtraction in-place, because `data` might be a + # view of the input array. + data = data - floc + xbar = data.mean() + + # Three cases to handle: + # * shape and scale both free + # * shape fixed, scale free + # * shape free, scale fixed + + if fscale is None: + # scale is free + if f0 is not None: + # shape is fixed + a = f0 + else: + # shape and scale are both free. + # The MLE for the shape parameter `a` is the solution to: + # np.log(a) - sc.digamma(a) - np.log(xbar) + + # np.log(data).mean() = 0 + s = np.log(xbar) - np.log(data).mean() + aest = (3-s + np.sqrt((s-3)**2 + 24*s)) / (12*s) + xa = aest*(1-0.4) + xb = aest*(1+0.4) + a = optimize.brentq(lambda a: np.log(a) - sc.digamma(a) - s, + xa, xb, disp=0) + + # The MLE for the scale parameter is just the data mean + # divided by the shape parameter. + scale = xbar / a + else: + # scale is fixed, shape is free + # The MLE for the shape parameter `a` is the solution to: + # sc.digamma(a) - np.log(data).mean() + np.log(fscale) = 0 + c = np.log(data).mean() - np.log(fscale) + a = _digammainv(c) + scale = fscale + + return a, floc, scale + + +gamma = gamma_gen(a=0.0, name='gamma') + + +class erlang_gen(gamma_gen): + """An Erlang continuous random variable. + + %(before_notes)s + + See Also + -------- + gamma + + Notes + ----- + The Erlang distribution is a special case of the Gamma distribution, with + the shape parameter `a` an integer. Note that this restriction is not + enforced by `erlang`. It will, however, generate a warning the first time + a non-integer value is used for the shape parameter. + + Refer to `gamma` for examples. + + """ + + def _argcheck(self, a): + allint = np.all(np.floor(a) == a) + if not allint: + # An Erlang distribution shouldn't really have a non-integer + # shape parameter, so warn the user. + message = ('The shape parameter of the erlang distribution ' + f'has been given a non-integer value {a!r}.') + warnings.warn(message, RuntimeWarning, stacklevel=3) + return a > 0 + + def _shape_info(self): + return [_ShapeInfo("a", True, (1, np.inf), (True, False))] + + def _fitstart(self, data): + # Override gamma_gen_fitstart so that an integer initial value is + # used. (Also regularize the division, to avoid issues when + # _skew(data) is 0 or close to 0.) + if isinstance(data, CensoredData): + data = data._uncensor() + a = int(4.0 / (1e-8 + _skew(data)**2)) + return super(gamma_gen, self)._fitstart(data, args=(a,)) + + # Trivial override of the fit method, so we can monkey-patch its + # docstring. + @extend_notes_in_docstring(rv_continuous, notes="""\ + The Erlang distribution is generally defined to have integer values + for the shape parameter. This is not enforced by the `erlang` class. + When fitting the distribution, it will generally return a non-integer + value for the shape parameter. By using the keyword argument + `f0=`, the fit method can be constrained to fit the data to + a specific integer shape parameter.""") + def fit(self, data, *args, **kwds): + return super().fit(data, *args, **kwds) + + +erlang = erlang_gen(a=0.0, name='erlang') + + +class gengamma_gen(rv_continuous): + r"""A generalized gamma continuous random variable. + + %(before_notes)s + + See Also + -------- + gamma, invgamma, weibull_min + + Notes + ----- + The probability density function for `gengamma` is ([1]_): + + .. math:: + + f(x, a, c) = \frac{|c| x^{c a-1} \exp(-x^c)}{\Gamma(a)} + + for :math:`x \ge 0`, :math:`a > 0`, and :math:`c \ne 0`. + :math:`\Gamma` is the gamma function (`scipy.special.gamma`). + + `gengamma` takes :math:`a` and :math:`c` as shape parameters. + + %(after_notes)s + + References + ---------- + .. [1] E.W. Stacy, "A Generalization of the Gamma Distribution", + Annals of Mathematical Statistics, Vol 33(3), pp. 1187--1192. + + %(example)s + + """ + def _argcheck(self, a, c): + return (a > 0) & (c != 0) + + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ic = _ShapeInfo("c", False, (-np.inf, np.inf), (False, False)) + return [ia, ic] + + def _pdf(self, x, a, c): + return np.exp(self._logpdf(x, a, c)) + + def _logpdf(self, x, a, c): + return _lazywhere((x != 0) | (c > 0), (x, c), + lambda x, c: (np.log(abs(c)) + sc.xlogy(c*a - 1, x) + - x**c - sc.gammaln(a)), + fillvalue=-np.inf) + + def _cdf(self, x, a, c): + xc = x**c + val1 = sc.gammainc(a, xc) + val2 = sc.gammaincc(a, xc) + return np.where(c > 0, val1, val2) + + def _rvs(self, a, c, size=None, random_state=None): + r = random_state.standard_gamma(a, size=size) + return r**(1./c) + + def _sf(self, x, a, c): + xc = x**c + val1 = sc.gammainc(a, xc) + val2 = sc.gammaincc(a, xc) + return np.where(c > 0, val2, val1) + + def _ppf(self, q, a, c): + val1 = sc.gammaincinv(a, q) + val2 = sc.gammainccinv(a, q) + return np.where(c > 0, val1, val2)**(1.0/c) + + def _isf(self, q, a, c): + val1 = sc.gammaincinv(a, q) + val2 = sc.gammainccinv(a, q) + return np.where(c > 0, val2, val1)**(1.0/c) + + def _munp(self, n, a, c): + # Pochhammer symbol: sc.pocha,n) = gamma(a+n)/gamma(a) + return sc.poch(a, n*1.0/c) + + def _entropy(self, a, c): + def regular(a, c): + val = sc.psi(a) + A = a * (1 - val) + val / c + B = sc.gammaln(a) - np.log(abs(c)) + h = A + B + return h + + def asymptotic(a, c): + # using asymptotic expansions for gammaln and psi (see gh-18093) + return (norm._entropy() - np.log(a)/2 + - np.log(np.abs(c)) + (a**-1.)/6 - (a**-3.)/90 + + (np.log(a) - (a**-1.)/2 - (a**-2.)/12 + (a**-4.)/120)/c) + + h = _lazywhere(a >= 2e2, (a, c), f=asymptotic, f2=regular) + return h + + +gengamma = gengamma_gen(a=0.0, name='gengamma') + + +class genhalflogistic_gen(rv_continuous): + r"""A generalized half-logistic continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `genhalflogistic` is: + + .. math:: + + f(x, c) = \frac{2 (1 - c x)^{1/(c-1)}}{[1 + (1 - c x)^{1/c}]^2} + + for :math:`0 \le x \le 1/c`, and :math:`c > 0`. + + `genhalflogistic` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _get_support(self, c): + return self.a, 1.0/c + + def _pdf(self, x, c): + # genhalflogistic.pdf(x, c) = + # 2 * (1-c*x)**(1/c-1) / (1+(1-c*x)**(1/c))**2 + limit = 1.0/c + tmp = np.asarray(1-c*x) + tmp0 = tmp**(limit-1) + tmp2 = tmp0*tmp + return 2*tmp0 / (1+tmp2)**2 + + def _cdf(self, x, c): + limit = 1.0/c + tmp = np.asarray(1-c*x) + tmp2 = tmp**(limit) + return (1.0-tmp2) / (1+tmp2) + + def _ppf(self, q, c): + return 1.0/c*(1-((1.0-q)/(1.0+q))**c) + + def _entropy(self, c): + return 2 - (2*c+1)*np.log(2) + + +genhalflogistic = genhalflogistic_gen(a=0.0, name='genhalflogistic') + + +class genhyperbolic_gen(rv_continuous): + r"""A generalized hyperbolic continuous random variable. + + %(before_notes)s + + See Also + -------- + t, norminvgauss, geninvgauss, laplace, cauchy + + Notes + ----- + The probability density function for `genhyperbolic` is: + + .. math:: + + f(x, p, a, b) = + \frac{(a^2 - b^2)^{p/2}} + {\sqrt{2\pi}a^{p-1/2} + K_p\Big(\sqrt{a^2 - b^2}\Big)} + e^{bx} \times \frac{K_{p - 1/2} + (a \sqrt{1 + x^2})} + {(\sqrt{1 + x^2})^{1/2 - p}} + + for :math:`x, p \in ( - \infty; \infty)`, + :math:`|b| < a` if :math:`p \ge 0`, + :math:`|b| \le a` if :math:`p < 0`. + :math:`K_{p}(.)` denotes the modified Bessel function of the second + kind and order :math:`p` (`scipy.special.kv`) + + `genhyperbolic` takes ``p`` as a tail parameter, + ``a`` as a shape parameter, + ``b`` as a skewness parameter. + + %(after_notes)s + + The original parameterization of the Generalized Hyperbolic Distribution + is found in [1]_ as follows + + .. math:: + + f(x, \lambda, \alpha, \beta, \delta, \mu) = + \frac{(\gamma/\delta)^\lambda}{\sqrt{2\pi}K_\lambda(\delta \gamma)} + e^{\beta (x - \mu)} \times \frac{K_{\lambda - 1/2} + (\alpha \sqrt{\delta^2 + (x - \mu)^2})} + {(\sqrt{\delta^2 + (x - \mu)^2} / \alpha)^{1/2 - \lambda}} + + for :math:`x \in ( - \infty; \infty)`, + :math:`\gamma := \sqrt{\alpha^2 - \beta^2}`, + :math:`\lambda, \mu \in ( - \infty; \infty)`, + :math:`\delta \ge 0, |\beta| < \alpha` if :math:`\lambda \ge 0`, + :math:`\delta > 0, |\beta| \le \alpha` if :math:`\lambda < 0`. + + The location-scale-based parameterization implemented in + SciPy is based on [2]_, where :math:`a = \alpha\delta`, + :math:`b = \beta\delta`, :math:`p = \lambda`, + :math:`scale=\delta` and :math:`loc=\mu` + + Moments are implemented based on [3]_ and [4]_. + + For the distributions that are a special case such as Student's t, + it is not recommended to rely on the implementation of genhyperbolic. + To avoid potential numerical problems and for performance reasons, + the methods of the specific distributions should be used. + + References + ---------- + .. [1] O. Barndorff-Nielsen, "Hyperbolic Distributions and Distributions + on Hyperbolae", Scandinavian Journal of Statistics, Vol. 5(3), + pp. 151-157, 1978. https://www.jstor.org/stable/4615705 + + .. [2] Eberlein E., Prause K. (2002) The Generalized Hyperbolic Model: + Financial Derivatives and Risk Measures. In: Geman H., Madan D., + Pliska S.R., Vorst T. (eds) Mathematical Finance - Bachelier + Congress 2000. Springer Finance. Springer, Berlin, Heidelberg. + :doi:`10.1007/978-3-662-12429-1_12` + + .. [3] Scott, David J, Würtz, Diethelm, Dong, Christine and Tran, + Thanh Tam, (2009), Moments of the generalized hyperbolic + distribution, MPRA Paper, University Library of Munich, Germany, + https://EconPapers.repec.org/RePEc:pra:mprapa:19081. + + .. [4] E. Eberlein and E. A. von Hammerstein. Generalized hyperbolic + and inverse Gaussian distributions: Limiting cases and approximation + of processes. FDM Preprint 80, April 2003. University of Freiburg. + https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content + + %(example)s + + """ + + def _argcheck(self, p, a, b): + return (np.logical_and(np.abs(b) < a, p >= 0) + | np.logical_and(np.abs(b) <= a, p < 0)) + + def _shape_info(self): + ip = _ShapeInfo("p", False, (-np.inf, np.inf), (False, False)) + ia = _ShapeInfo("a", False, (0, np.inf), (True, False)) + ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, False)) + return [ip, ia, ib] + + def _fitstart(self, data): + # Arbitrary, but the default p = a = b = 1 is not valid; the + # distribution requires |b| < a if p >= 0. + return super()._fitstart(data, args=(1, 1, 0.5)) + + def _logpdf(self, x, p, a, b): + # kve instead of kv works better for large values of p + # and smaller values of sqrt(a^2 - b^2) + @np.vectorize + def _logpdf_single(x, p, a, b): + return _stats.genhyperbolic_logpdf(x, p, a, b) + + return _logpdf_single(x, p, a, b) + + def _pdf(self, x, p, a, b): + # kve instead of kv works better for large values of p + # and smaller values of sqrt(a^2 - b^2) + @np.vectorize + def _pdf_single(x, p, a, b): + return _stats.genhyperbolic_pdf(x, p, a, b) + + return _pdf_single(x, p, a, b) + + # np.vectorize isn't currently designed to be used as a decorator, + # so use a lambda instead. This allows us to decorate the function + # with `np.vectorize` and still provide the `otypes` parameter. + @lambda func: np.vectorize(func, otypes=[np.float64]) + @staticmethod + def _integrate_pdf(x0, x1, p, a, b): + """ + Integrate the pdf of the genhyberbolic distribution from x0 to x1. + This is a private function used by _cdf() and _sf() only; either x0 + will be -inf or x1 will be inf. + """ + user_data = np.array([p, a, b], float).ctypes.data_as(ctypes.c_void_p) + llc = LowLevelCallable.from_cython(_stats, '_genhyperbolic_pdf', + user_data) + d = np.sqrt((a + b)*(a - b)) + mean = b/d * sc.kv(p + 1, d) / sc.kv(p, d) + epsrel = 1e-10 + epsabs = 0 + if x0 < mean < x1: + # If the interval includes the mean, integrate over the two + # intervals [x0, mean] and [mean, x1] and add. If we try to do + # the integral in one call of quad and the non-infinite endpoint + # is far in the tail, quad might return an incorrect result + # because it does not "see" the peak of the PDF. + intgrl = (integrate.quad(llc, x0, mean, + epsrel=epsrel, epsabs=epsabs)[0] + + integrate.quad(llc, mean, x1, + epsrel=epsrel, epsabs=epsabs)[0]) + else: + intgrl = integrate.quad(llc, x0, x1, + epsrel=epsrel, epsabs=epsabs)[0] + if np.isnan(intgrl): + msg = ("Infinite values encountered in scipy.special.kve. " + "Values replaced by NaN to avoid incorrect results.") + warnings.warn(msg, RuntimeWarning, stacklevel=3) + return max(0.0, min(1.0, intgrl)) + + def _cdf(self, x, p, a, b): + return self._integrate_pdf(-np.inf, x, p, a, b) + + def _sf(self, x, p, a, b): + return self._integrate_pdf(x, np.inf, p, a, b) + + def _rvs(self, p, a, b, size=None, random_state=None): + # note: X = b * V + sqrt(V) * X has a + # generalized hyperbolic distribution + # if X is standard normal and V is + # geninvgauss(p = p, b = t2, loc = loc, scale = t3) + t1 = np.float_power(a, 2) - np.float_power(b, 2) + # b in the GIG + t2 = np.float_power(t1, 0.5) + # scale in the GIG + t3 = np.float_power(t1, - 0.5) + gig = geninvgauss.rvs( + p=p, + b=t2, + scale=t3, + size=size, + random_state=random_state + ) + normst = norm.rvs(size=size, random_state=random_state) + + return b * gig + np.sqrt(gig) * normst + + def _stats(self, p, a, b): + # https://mpra.ub.uni-muenchen.de/19081/1/MPRA_paper_19081.pdf + # https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content + # standardized moments + p, a, b = np.broadcast_arrays(p, a, b) + t1 = np.float_power(a, 2) - np.float_power(b, 2) + t1 = np.float_power(t1, 0.5) + t2 = np.float_power(1, 2) * np.float_power(t1, - 1) + integers = np.linspace(0, 4, 5) + # make integers perpendicular to existing dimensions + integers = integers.reshape(integers.shape + (1,) * p.ndim) + b0, b1, b2, b3, b4 = sc.kv(p + integers, t1) + r1, r2, r3, r4 = (b / b0 for b in (b1, b2, b3, b4)) + + m = b * t2 * r1 + v = ( + t2 * r1 + np.float_power(b, 2) * np.float_power(t2, 2) * + (r2 - np.float_power(r1, 2)) + ) + m3e = ( + np.float_power(b, 3) * np.float_power(t2, 3) * + (r3 - 3 * b2 * b1 * np.float_power(b0, -2) + + 2 * np.float_power(r1, 3)) + + 3 * b * np.float_power(t2, 2) * + (r2 - np.float_power(r1, 2)) + ) + s = m3e * np.float_power(v, - 3 / 2) + m4e = ( + np.float_power(b, 4) * np.float_power(t2, 4) * + (r4 - 4 * b3 * b1 * np.float_power(b0, - 2) + + 6 * b2 * np.float_power(b1, 2) * np.float_power(b0, - 3) - + 3 * np.float_power(r1, 4)) + + np.float_power(b, 2) * np.float_power(t2, 3) * + (6 * r3 - 12 * b2 * b1 * np.float_power(b0, - 2) + + 6 * np.float_power(r1, 3)) + + 3 * np.float_power(t2, 2) * r2 + ) + k = m4e * np.float_power(v, -2) - 3 + + return m, v, s, k + + +genhyperbolic = genhyperbolic_gen(name='genhyperbolic') + + +class gompertz_gen(rv_continuous): + r"""A Gompertz (or truncated Gumbel) continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `gompertz` is: + + .. math:: + + f(x, c) = c \exp(x) \exp(-c (e^x-1)) + + for :math:`x \ge 0`, :math:`c > 0`. + + `gompertz` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # gompertz.pdf(x, c) = c * exp(x) * exp(-c*(exp(x)-1)) + return np.exp(self._logpdf(x, c)) + + def _logpdf(self, x, c): + return np.log(c) + x - c * sc.expm1(x) + + def _cdf(self, x, c): + return -sc.expm1(-c * sc.expm1(x)) + + def _ppf(self, q, c): + return sc.log1p(-1.0 / c * sc.log1p(-q)) + + def _sf(self, x, c): + return np.exp(-c * sc.expm1(x)) + + def _isf(self, p, c): + return sc.log1p(-np.log(p)/c) + + def _entropy(self, c): + return 1.0 - np.log(c) - sc._ufuncs._scaled_exp1(c)/c + + +gompertz = gompertz_gen(a=0.0, name='gompertz') + + +def _average_with_log_weights(x, logweights): + x = np.asarray(x) + logweights = np.asarray(logweights) + maxlogw = logweights.max() + weights = np.exp(logweights - maxlogw) + return np.average(x, weights=weights) + + +class gumbel_r_gen(rv_continuous): + r"""A right-skewed Gumbel continuous random variable. + + %(before_notes)s + + See Also + -------- + gumbel_l, gompertz, genextreme + + Notes + ----- + The probability density function for `gumbel_r` is: + + .. math:: + + f(x) = \exp(-(x + e^{-x})) + + for real :math:`x`. + + The Gumbel distribution is sometimes referred to as a type I Fisher-Tippett + distribution. It is also related to the extreme value distribution, + log-Weibull and Gompertz distributions. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # gumbel_r.pdf(x) = exp(-(x + exp(-x))) + return np.exp(self._logpdf(x)) + + def _logpdf(self, x): + return -x - np.exp(-x) + + def _cdf(self, x): + return np.exp(-np.exp(-x)) + + def _logcdf(self, x): + return -np.exp(-x) + + def _ppf(self, q): + return -np.log(-np.log(q)) + + def _sf(self, x): + return -sc.expm1(-np.exp(-x)) + + def _isf(self, p): + return -np.log(-np.log1p(-p)) + + def _stats(self): + return _EULER, np.pi*np.pi/6.0, 12*np.sqrt(6)/np.pi**3 * _ZETA3, 12.0/5 + + def _entropy(self): + # https://en.wikipedia.org/wiki/Gumbel_distribution + return _EULER + 1. + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + data, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + + # By the method of maximum likelihood, the estimators of the + # location and scale are the roots of the equations defined in + # `func` and the value of the expression for `loc` that follows. + # The first `func` is a first order derivative of the log-likelihood + # equation and the second is from Source: Statistical Distributions, + # 3rd Edition. Evans, Hastings, and Peacock (2000), Page 101. + + def get_loc_from_scale(scale): + return -scale * (sc.logsumexp(-data / scale) - np.log(len(data))) + + if fscale is not None: + # if the scale is fixed, the location can be analytically + # determined. + scale = fscale + loc = get_loc_from_scale(scale) + else: + # A different function is solved depending on whether the location + # is fixed. + if floc is not None: + loc = floc + + # equation to use if the location is fixed. + # note that one cannot use the equation in Evans, Hastings, + # and Peacock (2000) (since it assumes that the derivative + # w.r.t. the log-likelihood is zero). however, it is easy to + # derive the MLE condition directly if loc is fixed + def func(scale): + term1 = (loc - data) * np.exp((loc - data) / scale) + data + term2 = len(data) * (loc + scale) + return term1.sum() - term2 + else: + + # equation to use if both location and scale are free + def func(scale): + sdata = -data / scale + wavg = _average_with_log_weights(data, logweights=sdata) + return data.mean() - wavg - scale + + # set brackets for `root_scalar` to use when optimizing over the + # scale such that a root is likely between them. Use user supplied + # guess or default 1. + brack_start = kwds.get('scale', 1) + lbrack, rbrack = brack_start / 2, brack_start * 2 + + # if a root is not between the brackets, iteratively expand them + # until they include a sign change, checking after each bracket is + # modified. + def interval_contains_root(lbrack, rbrack): + # return true if the signs disagree. + return (np.sign(func(lbrack)) != + np.sign(func(rbrack))) + while (not interval_contains_root(lbrack, rbrack) + and (lbrack > 0 or rbrack < np.inf)): + lbrack /= 2 + rbrack *= 2 + + res = optimize.root_scalar(func, bracket=(lbrack, rbrack), + rtol=1e-14, xtol=1e-14) + scale = res.root + loc = floc if floc is not None else get_loc_from_scale(scale) + return loc, scale + + +gumbel_r = gumbel_r_gen(name='gumbel_r') + + +class gumbel_l_gen(rv_continuous): + r"""A left-skewed Gumbel continuous random variable. + + %(before_notes)s + + See Also + -------- + gumbel_r, gompertz, genextreme + + Notes + ----- + The probability density function for `gumbel_l` is: + + .. math:: + + f(x) = \exp(x - e^x) + + for real :math:`x`. + + The Gumbel distribution is sometimes referred to as a type I Fisher-Tippett + distribution. It is also related to the extreme value distribution, + log-Weibull and Gompertz distributions. + + %(after_notes)s + + %(example)s + + """ + + def _shape_info(self): + return [] + + def _pdf(self, x): + # gumbel_l.pdf(x) = exp(x - exp(x)) + return np.exp(self._logpdf(x)) + + def _logpdf(self, x): + return x - np.exp(x) + + def _cdf(self, x): + return -sc.expm1(-np.exp(x)) + + def _ppf(self, q): + return np.log(-sc.log1p(-q)) + + def _logsf(self, x): + return -np.exp(x) + + def _sf(self, x): + return np.exp(-np.exp(x)) + + def _isf(self, x): + return np.log(-np.log(x)) + + def _stats(self): + return -_EULER, np.pi*np.pi/6.0, \ + -12*np.sqrt(6)/np.pi**3 * _ZETA3, 12.0/5 + + def _entropy(self): + return _EULER + 1. + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + # The fit method of `gumbel_r` can be used for this distribution with + # small modifications. The process to do this is + # 1. pass the sign negated data into `gumbel_r.fit` + # - if the location is fixed, it should also be negated. + # 2. negate the sign of the resulting location, leaving the scale + # unmodified. + # `gumbel_r.fit` holds necessary input checks. + + if kwds.get('floc') is not None: + kwds['floc'] = -kwds['floc'] + loc_r, scale_r, = gumbel_r.fit(-np.asarray(data), *args, **kwds) + return -loc_r, scale_r + + +gumbel_l = gumbel_l_gen(name='gumbel_l') + + +class halfcauchy_gen(rv_continuous): + r"""A Half-Cauchy continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `halfcauchy` is: + + .. math:: + + f(x) = \frac{2}{\pi (1 + x^2)} + + for :math:`x \ge 0`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # halfcauchy.pdf(x) = 2 / (pi * (1 + x**2)) + return 2.0/np.pi/(1.0+x*x) + + def _logpdf(self, x): + return np.log(2.0/np.pi) - sc.log1p(x*x) + + def _cdf(self, x): + return 2.0/np.pi*np.arctan(x) + + def _ppf(self, q): + return np.tan(np.pi/2*q) + + def _sf(self, x): + return 2.0/np.pi * np.arctan2(1, x) + + def _isf(self, p): + return 1.0/np.tan(np.pi*p/2) + + def _stats(self): + return np.inf, np.inf, np.nan, np.nan + + def _entropy(self): + return np.log(2*np.pi) + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + data, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + + # location is independent from the scale + data_min = np.min(data) + if floc is not None: + if data_min < floc: + # There are values that are less than the specified loc. + raise FitDataError("halfcauchy", lower=floc, upper=np.inf) + loc = floc + else: + # if not provided, location MLE is the minimal data point + loc = data_min + + # find scale + def find_scale(loc, data): + shifted_data = data - loc + n = data.size + shifted_data_squared = np.square(shifted_data) + + def fun_to_solve(scale): + denominator = scale**2 + shifted_data_squared + return 2 * np.sum(shifted_data_squared/denominator) - n + + small = np.finfo(1.0).tiny**0.5 # avoid underflow + res = root_scalar(fun_to_solve, bracket=(small, np.max(shifted_data))) + return res.root + + if fscale is not None: + scale = fscale + else: + scale = find_scale(loc, data) + + return loc, scale + + +halfcauchy = halfcauchy_gen(a=0.0, name='halfcauchy') + + +class halflogistic_gen(rv_continuous): + r"""A half-logistic continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `halflogistic` is: + + .. math:: + + f(x) = \frac{ 2 e^{-x} }{ (1+e^{-x})^2 } + = \frac{1}{2} \text{sech}(x/2)^2 + + for :math:`x \ge 0`. + + %(after_notes)s + + References + ---------- + .. [1] Asgharzadeh et al (2011). "Comparisons of Methods of Estimation for the + Half-Logistic Distribution". Selcuk J. Appl. Math. 93-108. + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # halflogistic.pdf(x) = 2 * exp(-x) / (1+exp(-x))**2 + # = 1/2 * sech(x/2)**2 + return np.exp(self._logpdf(x)) + + def _logpdf(self, x): + return np.log(2) - x - 2. * sc.log1p(np.exp(-x)) + + def _cdf(self, x): + return np.tanh(x/2.0) + + def _ppf(self, q): + return 2*np.arctanh(q) + + def _sf(self, x): + return 2 * sc.expit(-x) + + def _isf(self, q): + return _lazywhere(q < 0.5, (q, ), + lambda q: -sc.logit(0.5 * q), + f2=lambda q: 2*np.arctanh(1 - q)) + + def _munp(self, n): + if n == 0: + return 1 # otherwise returns NaN + if n == 1: + return 2*np.log(2) + if n == 2: + return np.pi*np.pi/3.0 + if n == 3: + return 9*_ZETA3 + if n == 4: + return 7*np.pi**4 / 15.0 + return 2*(1-pow(2.0, 1-n))*sc.gamma(n+1)*sc.zeta(n, 1) + + def _entropy(self): + return 2-np.log(2) + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + data, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + + def find_scale(data, loc): + # scale is solution to a fix point problem ([1] 2.6) + # use approximate MLE as starting point ([1] 3.1) + n_observations = data.shape[0] + sorted_data = np.sort(data, axis=0) + p = np.arange(1, n_observations + 1)/(n_observations + 1) + q = 1 - p + pp1 = 1 + p + alpha = p - 0.5 * q * pp1 * np.log(pp1 / q) + beta = 0.5 * q * pp1 + sorted_data = sorted_data - loc + B = 2 * np.sum(alpha[1:] * sorted_data[1:]) + C = 2 * np.sum(beta[1:] * sorted_data[1:]**2) + # starting guess + scale = ((B + np.sqrt(B**2 + 8 * n_observations * C)) + /(4 * n_observations)) + + # relative tolerance of fix point iterator + rtol = 1e-8 + relative_residual = 1 + shifted_mean = sorted_data.mean() # y_mean - y_min + + # find fix point by repeated application of eq. (2.6) + # simplify as + # exp(-x) / (1 + exp(-x)) = 1 / (1 + exp(x)) + # = expit(-x)) + while relative_residual > rtol: + sum_term = sorted_data * sc.expit(-sorted_data/scale) + scale_new = shifted_mean - 2/n_observations * sum_term.sum() + relative_residual = abs((scale - scale_new)/scale) + scale = scale_new + return scale + + # location is independent from the scale + data_min = np.min(data) + if floc is not None: + if data_min < floc: + # There are values that are less than the specified loc. + raise FitDataError("halflogistic", lower=floc, upper=np.inf) + loc = floc + else: + # if not provided, location MLE is the minimal data point + loc = data_min + + # scale depends on location + scale = fscale if fscale is not None else find_scale(data, loc) + + return loc, scale + + +halflogistic = halflogistic_gen(a=0.0, name='halflogistic') + + +class halfnorm_gen(rv_continuous): + r"""A half-normal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `halfnorm` is: + + .. math:: + + f(x) = \sqrt{2/\pi} \exp(-x^2 / 2) + + for :math:`x >= 0`. + + `halfnorm` is a special case of `chi` with ``df=1``. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return abs(random_state.standard_normal(size=size)) + + def _pdf(self, x): + # halfnorm.pdf(x) = sqrt(2/pi) * exp(-x**2/2) + return np.sqrt(2.0/np.pi)*np.exp(-x*x/2.0) + + def _logpdf(self, x): + return 0.5 * np.log(2.0/np.pi) - x*x/2.0 + + def _cdf(self, x): + return sc.erf(x / np.sqrt(2)) + + def _ppf(self, q): + return _norm_ppf((1+q)/2.0) + + def _sf(self, x): + return 2 * _norm_sf(x) + + def _isf(self, p): + return _norm_isf(p/2) + + def _stats(self): + return (np.sqrt(2.0/np.pi), + 1-2.0/np.pi, + np.sqrt(2)*(4-np.pi)/(np.pi-2)**1.5, + 8*(np.pi-3)/(np.pi-2)**2) + + def _entropy(self): + return 0.5*np.log(np.pi/2.0)+0.5 + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + data, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + + data_min = np.min(data) + + if floc is not None: + if data_min < floc: + # There are values that are less than the specified loc. + raise FitDataError("halfnorm", lower=floc, upper=np.inf) + loc = floc + else: + loc = data_min + + if fscale is not None: + scale = fscale + else: + scale = stats.moment(data, order=2, center=loc)**0.5 + + return loc, scale + + +halfnorm = halfnorm_gen(a=0.0, name='halfnorm') + + +class hypsecant_gen(rv_continuous): + r"""A hyperbolic secant continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `hypsecant` is: + + .. math:: + + f(x) = \frac{1}{\pi} \text{sech}(x) + + for a real number :math:`x`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + # hypsecant.pdf(x) = 1/pi * sech(x) + return 1.0/(np.pi*np.cosh(x)) + + def _cdf(self, x): + return 2.0/np.pi*np.arctan(np.exp(x)) + + def _ppf(self, q): + return np.log(np.tan(np.pi*q/2.0)) + + def _sf(self, x): + return 2.0/np.pi*np.arctan(np.exp(-x)) + + def _isf(self, q): + return -np.log(np.tan(np.pi*q/2.0)) + + def _stats(self): + return 0, np.pi*np.pi/4, 0, 2 + + def _entropy(self): + return np.log(2*np.pi) + + +hypsecant = hypsecant_gen(name='hypsecant') + + +class gausshyper_gen(rv_continuous): + r"""A Gauss hypergeometric continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `gausshyper` is: + + .. math:: + + f(x, a, b, c, z) = C x^{a-1} (1-x)^{b-1} (1+zx)^{-c} + + for :math:`0 \le x \le 1`, :math:`a,b > 0`, :math:`c` a real number, + :math:`z > -1`, and :math:`C = \frac{1}{B(a, b) F[2, 1](c, a; a+b; -z)}`. + :math:`F[2, 1]` is the Gauss hypergeometric function + `scipy.special.hyp2f1`. + + `gausshyper` takes :math:`a`, :math:`b`, :math:`c` and :math:`z` as shape + parameters. + + %(after_notes)s + + References + ---------- + .. [1] Armero, C., and M. J. Bayarri. "Prior Assessments for Prediction in + Queues." *Journal of the Royal Statistical Society*. Series D (The + Statistician) 43, no. 1 (1994): 139-53. doi:10.2307/2348939 + + %(example)s + + """ + + def _argcheck(self, a, b, c, z): + # z > -1 per gh-10134 + return (a > 0) & (b > 0) & (c == c) & (z > -1) + + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + ic = _ShapeInfo("c", False, (-np.inf, np.inf), (False, False)) + iz = _ShapeInfo("z", False, (-1, np.inf), (False, False)) + return [ia, ib, ic, iz] + + def _pdf(self, x, a, b, c, z): + normalization_constant = sc.beta(a, b) * sc.hyp2f1(c, a, a + b, -z) + return (1./normalization_constant * x**(a - 1.) * (1. - x)**(b - 1.0) + / (1.0 + z*x)**c) + + def _munp(self, n, a, b, c, z): + fac = sc.beta(n+a, b) / sc.beta(a, b) + num = sc.hyp2f1(c, a+n, a+b+n, -z) + den = sc.hyp2f1(c, a, a+b, -z) + return fac*num / den + + +gausshyper = gausshyper_gen(a=0.0, b=1.0, name='gausshyper') + + +class invgamma_gen(rv_continuous): + r"""An inverted gamma continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `invgamma` is: + + .. math:: + + f(x, a) = \frac{x^{-a-1}}{\Gamma(a)} \exp(-\frac{1}{x}) + + for :math:`x >= 0`, :math:`a > 0`. :math:`\Gamma` is the gamma function + (`scipy.special.gamma`). + + `invgamma` takes ``a`` as a shape parameter for :math:`a`. + + `invgamma` is a special case of `gengamma` with ``c=-1``, and it is a + different parameterization of the scaled inverse chi-squared distribution. + Specifically, if the scaled inverse chi-squared distribution is + parameterized with degrees of freedom :math:`\nu` and scaling parameter + :math:`\tau^2`, then it can be modeled using `invgamma` with + ``a=`` :math:`\nu/2` and ``scale=`` :math:`\nu \tau^2/2`. + + %(after_notes)s + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (False, False))] + + def _pdf(self, x, a): + # invgamma.pdf(x, a) = x**(-a-1) / gamma(a) * exp(-1/x) + return np.exp(self._logpdf(x, a)) + + def _logpdf(self, x, a): + return -(a+1) * np.log(x) - sc.gammaln(a) - 1.0/x + + def _cdf(self, x, a): + return sc.gammaincc(a, 1.0 / x) + + def _ppf(self, q, a): + return 1.0 / sc.gammainccinv(a, q) + + def _sf(self, x, a): + return sc.gammainc(a, 1.0 / x) + + def _isf(self, q, a): + return 1.0 / sc.gammaincinv(a, q) + + def _stats(self, a, moments='mvsk'): + m1 = _lazywhere(a > 1, (a,), lambda x: 1. / (x - 1.), np.inf) + m2 = _lazywhere(a > 2, (a,), lambda x: 1. / (x - 1.)**2 / (x - 2.), + np.inf) + + g1, g2 = None, None + if 's' in moments: + g1 = _lazywhere( + a > 3, (a,), + lambda x: 4. * np.sqrt(x - 2.) / (x - 3.), np.nan) + if 'k' in moments: + g2 = _lazywhere( + a > 4, (a,), + lambda x: 6. * (5. * x - 11.) / (x - 3.) / (x - 4.), np.nan) + return m1, m2, g1, g2 + + def _entropy(self, a): + def regular(a): + h = a - (a + 1.0) * sc.psi(a) + sc.gammaln(a) + return h + + def asymptotic(a): + # gammaln(a) ~ a * ln(a) - a - 0.5 * ln(a) + 0.5 * ln(2 * pi) + # psi(a) ~ ln(a) - 1 / (2 * a) + h = ((1 - 3*np.log(a) + np.log(2) + np.log(np.pi))/2 + + 2/3*a**-1. + a**-2./12 - a**-3./90 - a**-4./120) + return h + + h = _lazywhere(a >= 2e2, (a,), f=asymptotic, f2=regular) + return h + + +invgamma = invgamma_gen(a=0.0, name='invgamma') + + +class invgauss_gen(rv_continuous): + r"""An inverse Gaussian continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `invgauss` is: + + .. math:: + + f(x; \mu) = \frac{1}{\sqrt{2 \pi x^3}} + \exp\left(-\frac{(x-\mu)^2}{2 \mu^2 x}\right) + + for :math:`x \ge 0` and :math:`\mu > 0`. + + `invgauss` takes ``mu`` as a shape parameter for :math:`\mu`. + + %(after_notes)s + + A common shape-scale parameterization of the inverse Gaussian distribution + has density + + .. math:: + + f(x; \nu, \lambda) = \sqrt{\frac{\lambda}{2 \pi x^3}} + \exp\left( -\frac{\lambda(x-\nu)^2}{2 \nu^2 x}\right) + + Using ``nu`` for :math:`\nu` and ``lam`` for :math:`\lambda`, this + parameterization is equivalent to the one above with ``mu = nu/lam``, + ``loc = 0``, and ``scale = lam``. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``ppf`` and ``isf`` methods. [1]_ + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [_ShapeInfo("mu", False, (0, np.inf), (False, False))] + + def _rvs(self, mu, size=None, random_state=None): + return random_state.wald(mu, 1.0, size=size) + + def _pdf(self, x, mu): + # invgauss.pdf(x, mu) = + # 1 / sqrt(2*pi*x**3) * exp(-(x-mu)**2/(2*x*mu**2)) + return 1.0/np.sqrt(2*np.pi*x**3.0)*np.exp(-1.0/(2*x)*((x-mu)/mu)**2) + + def _logpdf(self, x, mu): + return -0.5*np.log(2*np.pi) - 1.5*np.log(x) - ((x-mu)/mu)**2/(2*x) + + # approach adapted from equations in + # https://journal.r-project.org/archive/2016-1/giner-smyth.pdf, + # not R code. see gh-13616 + + def _logcdf(self, x, mu): + fac = 1 / np.sqrt(x) + a = _norm_logcdf(fac * ((x / mu) - 1)) + b = 2 / mu + _norm_logcdf(-fac * ((x / mu) + 1)) + return a + np.log1p(np.exp(b - a)) + + def _logsf(self, x, mu): + fac = 1 / np.sqrt(x) + a = _norm_logsf(fac * ((x / mu) - 1)) + b = 2 / mu + _norm_logcdf(-fac * (x + mu) / mu) + return a + np.log1p(-np.exp(b - a)) + + def _sf(self, x, mu): + return np.exp(self._logsf(x, mu)) + + def _cdf(self, x, mu): + return np.exp(self._logcdf(x, mu)) + + def _ppf(self, x, mu): + with np.errstate(divide='ignore', over='ignore', invalid='ignore'): + x, mu = np.broadcast_arrays(x, mu) + ppf = np.asarray(scu._invgauss_ppf(x, mu, 1)) + i_wt = x > 0.5 # "wrong tail" - sometimes too inaccurate + ppf[i_wt] = scu._invgauss_isf(1-x[i_wt], mu[i_wt], 1) + i_nan = np.isnan(ppf) + ppf[i_nan] = super()._ppf(x[i_nan], mu[i_nan]) + return ppf + + def _isf(self, x, mu): + with np.errstate(divide='ignore', over='ignore', invalid='ignore'): + x, mu = np.broadcast_arrays(x, mu) + isf = scu._invgauss_isf(x, mu, 1) + i_wt = x > 0.5 # "wrong tail" - sometimes too inaccurate + isf[i_wt] = scu._invgauss_ppf(1-x[i_wt], mu[i_wt], 1) + i_nan = np.isnan(isf) + isf[i_nan] = super()._isf(x[i_nan], mu[i_nan]) + return isf + + def _stats(self, mu): + return mu, mu**3.0, 3*np.sqrt(mu), 15*mu + + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + method = kwds.get('method', 'mle') + + if (isinstance(data, CensoredData) or isinstance(self, wald_gen) + or method.lower() == 'mm'): + return super().fit(data, *args, **kwds) + + data, fshape_s, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + ''' + Source: Statistical Distributions, 3rd Edition. Evans, Hastings, + and Peacock (2000), Page 121. Their shape parameter is equivalent to + SciPy's with the conversion `fshape_s = fshape / scale`. + + MLE formulas are not used in 3 conditions: + - `loc` is not fixed + - `mu` is fixed + These cases fall back on the superclass fit method. + - `loc` is fixed but translation results in negative data raises + a `FitDataError`. + ''' + if floc is None or fshape_s is not None: + return super().fit(data, *args, **kwds) + elif np.any(data - floc < 0): + raise FitDataError("invgauss", lower=0, upper=np.inf) + else: + data = data - floc + fshape_n = np.mean(data) + if fscale is None: + fscale = len(data) / (np.sum(data ** -1 - fshape_n ** -1)) + fshape_s = fshape_n / fscale + return fshape_s, floc, fscale + + def _entropy(self, mu): + """ + Ref.: https://moser-isi.ethz.ch/docs/papers/smos-2012-10.pdf (eq. 9) + """ + # a = log(2*pi*e*mu**3) + # = 1 + log(2*pi) + 3 * log(mu) + a = 1. + np.log(2 * np.pi) + 3 * np.log(mu) + # b = exp(2/mu) * exp1(2/mu) + # = _scaled_exp1(2/mu) / (2/mu) + r = 2/mu + b = sc._ufuncs._scaled_exp1(r)/r + return 0.5 * a - 1.5 * b + + +invgauss = invgauss_gen(a=0.0, name='invgauss') + + +class geninvgauss_gen(rv_continuous): + r"""A Generalized Inverse Gaussian continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `geninvgauss` is: + + .. math:: + + f(x, p, b) = x^{p-1} \exp(-b (x + 1/x) / 2) / (2 K_p(b)) + + where ``x > 0``, `p` is a real number and ``b > 0``\([1]_). + :math:`K_p` is the modified Bessel function of second kind of order `p` + (`scipy.special.kv`). + + %(after_notes)s + + The inverse Gaussian distribution `stats.invgauss(mu)` is a special case of + `geninvgauss` with ``p = -1/2``, ``b = 1 / mu`` and ``scale = mu``. + + Generating random variates is challenging for this distribution. The + implementation is based on [2]_. + + References + ---------- + .. [1] O. Barndorff-Nielsen, P. Blaesild, C. Halgreen, "First hitting time + models for the generalized inverse gaussian distribution", + Stochastic Processes and their Applications 7, pp. 49--54, 1978. + + .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian + random variates", Statistics and Computing, 24(4), p. 547--557, 2014. + + %(example)s + + """ + def _argcheck(self, p, b): + return (p == p) & (b > 0) + + def _shape_info(self): + ip = _ShapeInfo("p", False, (-np.inf, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ip, ib] + + def _logpdf(self, x, p, b): + # kve instead of kv works better for large values of b + # warn if kve produces infinite values and replace by nan + # otherwise c = -inf and the results are often incorrect + def logpdf_single(x, p, b): + return _stats.geninvgauss_logpdf(x, p, b) + + logpdf_single = np.vectorize(logpdf_single, otypes=[np.float64]) + + z = logpdf_single(x, p, b) + if np.isnan(z).any(): + msg = ("Infinite values encountered in scipy.special.kve(p, b). " + "Values replaced by NaN to avoid incorrect results.") + warnings.warn(msg, RuntimeWarning, stacklevel=3) + return z + + def _pdf(self, x, p, b): + # relying on logpdf avoids overflow of x**(p-1) for large x and p + return np.exp(self._logpdf(x, p, b)) + + def _cdf(self, x, p, b): + _a, _b = self._get_support(p, b) + + def _cdf_single(x, p, b): + user_data = np.array([p, b], float).ctypes.data_as(ctypes.c_void_p) + llc = LowLevelCallable.from_cython(_stats, '_geninvgauss_pdf', + user_data) + + return integrate.quad(llc, _a, x)[0] + + _cdf_single = np.vectorize(_cdf_single, otypes=[np.float64]) + + return _cdf_single(x, p, b) + + def _logquasipdf(self, x, p, b): + # log of the quasi-density (w/o normalizing constant) used in _rvs + return _lazywhere(x > 0, (x, p, b), + lambda x, p, b: (p - 1)*np.log(x) - b*(x + 1/x)/2, + -np.inf) + + def _rvs(self, p, b, size=None, random_state=None): + # if p and b are scalar, use _rvs_scalar, otherwise need to create + # output by iterating over parameters + if np.isscalar(p) and np.isscalar(b): + out = self._rvs_scalar(p, b, size, random_state) + elif p.size == 1 and b.size == 1: + out = self._rvs_scalar(p.item(), b.item(), size, random_state) + else: + # When this method is called, size will be a (possibly empty) + # tuple of integers. It will not be None; if `size=None` is passed + # to `rvs()`, size will be the empty tuple (). + + p, b = np.broadcast_arrays(p, b) + # p and b now have the same shape. + + # `shp` is the shape of the blocks of random variates that are + # generated for each combination of parameters associated with + # broadcasting p and b. + # bc is a tuple the same length as size. The values + # in bc are bools. If bc[j] is True, it means that + # entire axis is filled in for a given combination of the + # broadcast arguments. + shp, bc = _check_shape(p.shape, size) + + # `numsamples` is the total number of variates to be generated + # for each combination of the input arguments. + numsamples = int(np.prod(shp)) + + # `out` is the array to be returned. It is filled in the + # loop below. + out = np.empty(size) + + it = np.nditer([p, b], + flags=['multi_index'], + op_flags=[['readonly'], ['readonly']]) + while not it.finished: + # Convert the iterator's multi_index into an index into the + # `out` array where the call to _rvs_scalar() will be stored. + # Where bc is True, we use a full slice; otherwise we use the + # index value from it.multi_index. len(it.multi_index) might + # be less than len(bc), and in that case we want to align these + # two sequences to the right, so the loop variable j runs from + # -len(size) to 0. This doesn't cause an IndexError, as + # bc[j] will be True in those cases where it.multi_index[j] + # would cause an IndexError. + idx = tuple((it.multi_index[j] if not bc[j] else slice(None)) + for j in range(-len(size), 0)) + out[idx] = self._rvs_scalar(it[0], it[1], numsamples, + random_state).reshape(shp) + it.iternext() + + if size == (): + out = out.item() + return out + + def _rvs_scalar(self, p, b, numsamples, random_state): + # following [2], the quasi-pdf is used instead of the pdf for the + # generation of rvs + invert_res = False + if not numsamples: + numsamples = 1 + if p < 0: + # note: if X is geninvgauss(p, b), then 1/X is geninvgauss(-p, b) + p = -p + invert_res = True + m = self._mode(p, b) + + # determine method to be used following [2] + ratio_unif = True + if p >= 1 or b > 1: + # ratio of uniforms with mode shift below + mode_shift = True + elif b >= min(0.5, 2 * np.sqrt(1 - p) / 3): + # ratio of uniforms without mode shift below + mode_shift = False + else: + # new algorithm in [2] + ratio_unif = False + + # prepare sampling of rvs + size1d = tuple(np.atleast_1d(numsamples)) + N = np.prod(size1d) # number of rvs needed, reshape upon return + x = np.zeros(N) + simulated = 0 + + if ratio_unif: + # use ratio of uniforms method + if mode_shift: + a2 = -2 * (p + 1) / b - m + a1 = 2 * m * (p - 1) / b - 1 + # find roots of x**3 + a2*x**2 + a1*x + m (Cardano's formula) + p1 = a1 - a2**2 / 3 + q1 = 2 * a2**3 / 27 - a2 * a1 / 3 + m + phi = np.arccos(-q1 * np.sqrt(-27 / p1**3) / 2) + s1 = -np.sqrt(-4 * p1 / 3) + root1 = s1 * np.cos(phi / 3 + np.pi / 3) - a2 / 3 + root2 = -s1 * np.cos(phi / 3) - a2 / 3 + # root3 = s1 * np.cos(phi / 3 - np.pi / 3) - a2 / 3 + + # if g is the quasipdf, rescale: g(x) / g(m) which we can write + # as exp(log(g(x)) - log(g(m))). This is important + # since for large values of p and b, g cannot be evaluated. + # denote the rescaled quasipdf by h + lm = self._logquasipdf(m, p, b) + d1 = self._logquasipdf(root1, p, b) - lm + d2 = self._logquasipdf(root2, p, b) - lm + # compute the bounding rectangle w.r.t. h. Note that + # np.exp(0.5*d1) = np.sqrt(g(root1)/g(m)) = np.sqrt(h(root1)) + vmin = (root1 - m) * np.exp(0.5 * d1) + vmax = (root2 - m) * np.exp(0.5 * d2) + umax = 1 # umax = sqrt(h(m)) = 1 + + def logqpdf(x): + return self._logquasipdf(x, p, b) - lm + + c = m + else: + # ratio of uniforms without mode shift + # compute np.sqrt(quasipdf(m)) + umax = np.exp(0.5*self._logquasipdf(m, p, b)) + xplus = ((1 + p) + np.sqrt((1 + p)**2 + b**2))/b + vmin = 0 + # compute xplus * np.sqrt(quasipdf(xplus)) + vmax = xplus * np.exp(0.5 * self._logquasipdf(xplus, p, b)) + c = 0 + + def logqpdf(x): + return self._logquasipdf(x, p, b) + + if vmin >= vmax: + raise ValueError("vmin must be smaller than vmax.") + if umax <= 0: + raise ValueError("umax must be positive.") + + i = 1 + while simulated < N: + k = N - simulated + # simulate uniform rvs on [0, umax] and [vmin, vmax] + u = umax * random_state.uniform(size=k) + v = random_state.uniform(size=k) + v = vmin + (vmax - vmin) * v + rvs = v / u + c + # rewrite acceptance condition u**2 <= pdf(rvs) by taking logs + accept = (2*np.log(u) <= logqpdf(rvs)) + num_accept = np.sum(accept) + if num_accept > 0: + x[simulated:(simulated + num_accept)] = rvs[accept] + simulated += num_accept + + if (simulated == 0) and (i*N >= 50000): + msg = ("Not a single random variate could be generated " + f"in {i*N} attempts. Sampling does not appear to " + "work for the provided parameters.") + raise RuntimeError(msg) + i += 1 + else: + # use new algorithm in [2] + x0 = b / (1 - p) + xs = np.max((x0, 2 / b)) + k1 = np.exp(self._logquasipdf(m, p, b)) + A1 = k1 * x0 + if x0 < 2 / b: + k2 = np.exp(-b) + if p > 0: + A2 = k2 * ((2 / b)**p - x0**p) / p + else: + A2 = k2 * np.log(2 / b**2) + else: + k2, A2 = 0, 0 + k3 = xs**(p - 1) + A3 = 2 * k3 * np.exp(-xs * b / 2) / b + A = A1 + A2 + A3 + + # [2]: rejection constant is < 2.73; so expected runtime is finite + while simulated < N: + k = N - simulated + h, rvs = np.zeros(k), np.zeros(k) + # simulate uniform rvs on [x1, x2] and [0, y2] + u = random_state.uniform(size=k) + v = A * random_state.uniform(size=k) + cond1 = v <= A1 + cond2 = np.logical_not(cond1) & (v <= A1 + A2) + cond3 = np.logical_not(cond1 | cond2) + # subdomain (0, x0) + rvs[cond1] = x0 * v[cond1] / A1 + h[cond1] = k1 + # subdomain (x0, 2 / b) + if p > 0: + rvs[cond2] = (x0**p + (v[cond2] - A1) * p / k2)**(1 / p) + else: + rvs[cond2] = b * np.exp((v[cond2] - A1) * np.exp(b)) + h[cond2] = k2 * rvs[cond2]**(p - 1) + # subdomain (xs, infinity) + z = np.exp(-xs * b / 2) - b * (v[cond3] - A1 - A2) / (2 * k3) + rvs[cond3] = -2 / b * np.log(z) + h[cond3] = k3 * np.exp(-rvs[cond3] * b / 2) + # apply rejection method + accept = (np.log(u * h) <= self._logquasipdf(rvs, p, b)) + num_accept = sum(accept) + if num_accept > 0: + x[simulated:(simulated + num_accept)] = rvs[accept] + simulated += num_accept + + rvs = np.reshape(x, size1d) + if invert_res: + rvs = 1 / rvs + return rvs + + def _mode(self, p, b): + # distinguish cases to avoid catastrophic cancellation (see [2]) + if p < 1: + return b / (np.sqrt((p - 1)**2 + b**2) + 1 - p) + else: + return (np.sqrt((1 - p)**2 + b**2) - (1 - p)) / b + + def _munp(self, n, p, b): + num = sc.kve(p + n, b) + denom = sc.kve(p, b) + inf_vals = np.isinf(num) | np.isinf(denom) + if inf_vals.any(): + msg = ("Infinite values encountered in the moment calculation " + "involving scipy.special.kve. Values replaced by NaN to " + "avoid incorrect results.") + warnings.warn(msg, RuntimeWarning, stacklevel=3) + m = np.full_like(num, np.nan, dtype=np.float64) + m[~inf_vals] = num[~inf_vals] / denom[~inf_vals] + else: + m = num / denom + return m + + +geninvgauss = geninvgauss_gen(a=0.0, name="geninvgauss") + + +class norminvgauss_gen(rv_continuous): + r"""A Normal Inverse Gaussian continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `norminvgauss` is: + + .. math:: + + f(x, a, b) = \frac{a \, K_1(a \sqrt{1 + x^2})}{\pi \sqrt{1 + x^2}} \, + \exp(\sqrt{a^2 - b^2} + b x) + + where :math:`x` is a real number, the parameter :math:`a` is the tail + heaviness and :math:`b` is the asymmetry parameter satisfying + :math:`a > 0` and :math:`|b| <= a`. + :math:`K_1` is the modified Bessel function of second kind + (`scipy.special.k1`). + + %(after_notes)s + + A normal inverse Gaussian random variable `Y` with parameters `a` and `b` + can be expressed as a normal mean-variance mixture: + ``Y = b * V + sqrt(V) * X`` where `X` is ``norm(0,1)`` and `V` is + ``invgauss(mu=1/sqrt(a**2 - b**2))``. This representation is used + to generate random variates. + + Another common parametrization of the distribution (see Equation 2.1 in + [2]_) is given by the following expression of the pdf: + + .. math:: + + g(x, \alpha, \beta, \delta, \mu) = + \frac{\alpha\delta K_1\left(\alpha\sqrt{\delta^2 + (x - \mu)^2}\right)} + {\pi \sqrt{\delta^2 + (x - \mu)^2}} \, + e^{\delta \sqrt{\alpha^2 - \beta^2} + \beta (x - \mu)} + + In SciPy, this corresponds to + `a = alpha * delta, b = beta * delta, loc = mu, scale=delta`. + + References + ---------- + .. [1] O. Barndorff-Nielsen, "Hyperbolic Distributions and Distributions on + Hyperbolae", Scandinavian Journal of Statistics, Vol. 5(3), + pp. 151-157, 1978. + + .. [2] O. Barndorff-Nielsen, "Normal Inverse Gaussian Distributions and + Stochastic Volatility Modelling", Scandinavian Journal of + Statistics, Vol. 24, pp. 1-13, 1997. + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _argcheck(self, a, b): + return (a > 0) & (np.absolute(b) < a) + + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, False)) + return [ia, ib] + + def _fitstart(self, data): + # Arbitrary, but the default a = b = 1 is not valid; the distribution + # requires |b| < a. + return super()._fitstart(data, args=(1, 0.5)) + + def _pdf(self, x, a, b): + gamma = np.sqrt(a**2 - b**2) + fac1 = a / np.pi + sq = np.hypot(1, x) # reduce overflows + return fac1 * sc.k1e(a * sq) * np.exp(b*x - a*sq + gamma) / sq + + def _sf(self, x, a, b): + if np.isscalar(x): + # If x is a scalar, then so are a and b. + return integrate.quad(self._pdf, x, np.inf, args=(a, b))[0] + else: + a = np.atleast_1d(a) + b = np.atleast_1d(b) + result = [] + for (x0, a0, b0) in zip(x, a, b): + result.append(integrate.quad(self._pdf, x0, np.inf, + args=(a0, b0))[0]) + return np.array(result) + + def _isf(self, q, a, b): + def _isf_scalar(q, a, b): + + def eq(x, a, b, q): + # Solve eq(x, a, b, q) = 0 to obtain isf(x, a, b) = q. + return self._sf(x, a, b) - q + + # Find a bracketing interval for the root. + # Start at the mean, and grow the length of the interval + # by 2 each iteration until there is a sign change in eq. + xm = self.mean(a, b) + em = eq(xm, a, b, q) + if em == 0: + # Unlikely, but might as well check. + return xm + if em > 0: + delta = 1 + left = xm + right = xm + delta + while eq(right, a, b, q) > 0: + delta = 2*delta + right = xm + delta + else: + # em < 0 + delta = 1 + right = xm + left = xm - delta + while eq(left, a, b, q) < 0: + delta = 2*delta + left = xm - delta + result = optimize.brentq(eq, left, right, args=(a, b, q), + xtol=self.xtol) + return result + + if np.isscalar(q): + return _isf_scalar(q, a, b) + else: + result = [] + for (q0, a0, b0) in zip(q, a, b): + result.append(_isf_scalar(q0, a0, b0)) + return np.array(result) + + def _rvs(self, a, b, size=None, random_state=None): + # note: X = b * V + sqrt(V) * X is norminvgaus(a,b) if X is standard + # normal and V is invgauss(mu=1/sqrt(a**2 - b**2)) + gamma = np.sqrt(a**2 - b**2) + ig = invgauss.rvs(mu=1/gamma, size=size, random_state=random_state) + return b * ig + np.sqrt(ig) * norm.rvs(size=size, + random_state=random_state) + + def _stats(self, a, b): + gamma = np.sqrt(a**2 - b**2) + mean = b / gamma + variance = a**2 / gamma**3 + skewness = 3.0 * b / (a * np.sqrt(gamma)) + kurtosis = 3.0 * (1 + 4 * b**2 / a**2) / gamma + return mean, variance, skewness, kurtosis + + +norminvgauss = norminvgauss_gen(name="norminvgauss") + + +class invweibull_gen(rv_continuous): + """An inverted Weibull continuous random variable. + + This distribution is also known as the Fréchet distribution or the + type II extreme value distribution. + + %(before_notes)s + + Notes + ----- + The probability density function for `invweibull` is: + + .. math:: + + f(x, c) = c x^{-c-1} \\exp(-x^{-c}) + + for :math:`x > 0`, :math:`c > 0`. + + `invweibull` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + References + ---------- + F.R.S. de Gusmao, E.M.M Ortega and G.M. Cordeiro, "The generalized inverse + Weibull distribution", Stat. Papers, vol. 52, pp. 591-619, 2011. + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # invweibull.pdf(x, c) = c * x**(-c-1) * exp(-x**(-c)) + xc1 = np.power(x, -c - 1.0) + xc2 = np.power(x, -c) + xc2 = np.exp(-xc2) + return c * xc1 * xc2 + + def _cdf(self, x, c): + xc1 = np.power(x, -c) + return np.exp(-xc1) + + def _sf(self, x, c): + return -np.expm1(-x**-c) + + def _ppf(self, q, c): + return np.power(-np.log(q), -1.0/c) + + def _isf(self, p, c): + return (-np.log1p(-p))**(-1/c) + + def _munp(self, n, c): + return sc.gamma(1 - n / c) + + def _entropy(self, c): + return 1+_EULER + _EULER / c - np.log(c) + + def _fitstart(self, data, args=None): + # invweibull requires c > 1 for the first moment to exist, so use 2.0 + args = (2.0,) if args is None else args + return super()._fitstart(data, args=args) + + +invweibull = invweibull_gen(a=0, name='invweibull') + + +class jf_skew_t_gen(rv_continuous): + r"""Jones and Faddy skew-t distribution. + + %(before_notes)s + + Notes + ----- + The probability density function for `jf_skew_t` is: + + .. math:: + + f(x; a, b) = C_{a,b}^{-1} + \left(1+\frac{x}{\left(a+b+x^2\right)^{1/2}}\right)^{a+1/2} + \left(1-\frac{x}{\left(a+b+x^2\right)^{1/2}}\right)^{b+1/2} + + for real numbers :math:`a>0` and :math:`b>0`, where + :math:`C_{a,b} = 2^{a+b-1}B(a,b)(a+b)^{1/2}`, and :math:`B` denotes the + beta function (`scipy.special.beta`). + + When :math:`ab`, the distribution is positively skewed. If :math:`a=b`, then + we recover the `t` distribution with :math:`2a` degrees of freedom. + + `jf_skew_t` takes :math:`a` and :math:`b` as shape parameters. + + %(after_notes)s + + References + ---------- + .. [1] M.C. Jones and M.J. Faddy. "A skew extension of the t distribution, + with applications" *Journal of the Royal Statistical Society*. + Series B (Statistical Methodology) 65, no. 1 (2003): 159-174. + :doi:`10.1111/1467-9868.00378` + + %(example)s + + """ + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ia, ib] + + def _pdf(self, x, a, b): + c = 2 ** (a + b - 1) * sc.beta(a, b) * np.sqrt(a + b) + d1 = (1 + x / np.sqrt(a + b + x ** 2)) ** (a + 0.5) + d2 = (1 - x / np.sqrt(a + b + x ** 2)) ** (b + 0.5) + return d1 * d2 / c + + def _rvs(self, a, b, size=None, random_state=None): + d1 = random_state.beta(a, b, size) + d2 = (2 * d1 - 1) * np.sqrt(a + b) + d3 = 2 * np.sqrt(d1 * (1 - d1)) + return d2 / d3 + + def _cdf(self, x, a, b): + y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5 + return sc.betainc(a, b, y) + + def _sf(self, x, a, b): + y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5 + return sc.betaincc(a, b, y) + + def _ppf(self, q, a, b): + d1 = beta.ppf(q, a, b) + d2 = (2 * d1 - 1) * np.sqrt(a + b) + d3 = 2 * np.sqrt(d1 * (1 - d1)) + return d2 / d3 + + def _munp(self, n, a, b): + """Returns the n-th moment(s) where all the following hold: + + - n >= 0 + - a > n / 2 + - b > n / 2 + + The result is np.nan in all other cases. + """ + def nth_moment(n_k, a_k, b_k): + """Computes E[T^(n_k)] where T is skew-t distributed with + parameters a_k and b_k. + """ + num = (a_k + b_k) ** (0.5 * n_k) + denom = 2 ** n_k * sc.beta(a_k, b_k) + + indices = np.arange(n_k + 1) + sgn = np.where(indices % 2 > 0, -1, 1) + d = sc.beta(a_k + 0.5 * n_k - indices, b_k - 0.5 * n_k + indices) + sum_terms = sc.comb(n_k, indices) * sgn * d + + return num / denom * sum_terms.sum() + + nth_moment_valid = (a > 0.5 * n) & (b > 0.5 * n) & (n >= 0) + return _lazywhere( + nth_moment_valid, + (n, a, b), + np.vectorize(nth_moment, otypes=[np.float64]), + np.nan, + ) + + +jf_skew_t = jf_skew_t_gen(name='jf_skew_t') + + +class johnsonsb_gen(rv_continuous): + r"""A Johnson SB continuous random variable. + + %(before_notes)s + + See Also + -------- + johnsonsu + + Notes + ----- + The probability density function for `johnsonsb` is: + + .. math:: + + f(x, a, b) = \frac{b}{x(1-x)} \phi(a + b \log \frac{x}{1-x} ) + + where :math:`x`, :math:`a`, and :math:`b` are real scalars; :math:`b > 0` + and :math:`x \in [0,1]`. :math:`\phi` is the pdf of the normal + distribution. + + `johnsonsb` takes :math:`a` and :math:`b` as shape parameters. + + %(after_notes)s + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _argcheck(self, a, b): + return (b > 0) & (a == a) + + def _shape_info(self): + ia = _ShapeInfo("a", False, (-np.inf, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ia, ib] + + def _pdf(self, x, a, b): + # johnsonsb.pdf(x, a, b) = b / (x*(1-x)) * phi(a + b * log(x/(1-x))) + trm = _norm_pdf(a + b*sc.logit(x)) + return b*1.0/(x*(1-x))*trm + + def _cdf(self, x, a, b): + return _norm_cdf(a + b*sc.logit(x)) + + def _ppf(self, q, a, b): + return sc.expit(1.0 / b * (_norm_ppf(q) - a)) + + def _sf(self, x, a, b): + return _norm_sf(a + b*sc.logit(x)) + + def _isf(self, q, a, b): + return sc.expit(1.0 / b * (_norm_isf(q) - a)) + + +johnsonsb = johnsonsb_gen(a=0.0, b=1.0, name='johnsonsb') + + +class johnsonsu_gen(rv_continuous): + r"""A Johnson SU continuous random variable. + + %(before_notes)s + + See Also + -------- + johnsonsb + + Notes + ----- + The probability density function for `johnsonsu` is: + + .. math:: + + f(x, a, b) = \frac{b}{\sqrt{x^2 + 1}} + \phi(a + b \log(x + \sqrt{x^2 + 1})) + + where :math:`x`, :math:`a`, and :math:`b` are real scalars; :math:`b > 0`. + :math:`\phi` is the pdf of the normal distribution. + + `johnsonsu` takes :math:`a` and :math:`b` as shape parameters. + + The first four central moments are calculated according to the formulas + in [1]_. + + %(after_notes)s + + References + ---------- + .. [1] Taylor Enterprises. "Johnson Family of Distributions". + https://variation.com/wp-content/distribution_analyzer_help/hs126.htm + + %(example)s + + """ + def _argcheck(self, a, b): + return (b > 0) & (a == a) + + def _shape_info(self): + ia = _ShapeInfo("a", False, (-np.inf, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ia, ib] + + def _pdf(self, x, a, b): + # johnsonsu.pdf(x, a, b) = b / sqrt(x**2 + 1) * + # phi(a + b * log(x + sqrt(x**2 + 1))) + x2 = x*x + trm = _norm_pdf(a + b * np.arcsinh(x)) + return b*1.0/np.sqrt(x2+1.0)*trm + + def _cdf(self, x, a, b): + return _norm_cdf(a + b * np.arcsinh(x)) + + def _ppf(self, q, a, b): + return np.sinh((_norm_ppf(q) - a) / b) + + def _sf(self, x, a, b): + return _norm_sf(a + b * np.arcsinh(x)) + + def _isf(self, x, a, b): + return np.sinh((_norm_isf(x) - a) / b) + + def _stats(self, a, b, moments='mv'): + # Naive implementation of first and second moment to address gh-18071. + # https://variation.com/wp-content/distribution_analyzer_help/hs126.htm + # Numerical improvements left to future enhancements. + mu, mu2, g1, g2 = None, None, None, None + + bn2 = b**-2. + expbn2 = np.exp(bn2) + a_b = a / b + + if 'm' in moments: + mu = -expbn2**0.5 * np.sinh(a_b) + if 'v' in moments: + mu2 = 0.5*sc.expm1(bn2)*(expbn2*np.cosh(2*a_b) + 1) + if 's' in moments: + t1 = expbn2**.5 * sc.expm1(bn2)**0.5 + t2 = 3*np.sinh(a_b) + t3 = expbn2 * (expbn2 + 2) * np.sinh(3*a_b) + denom = np.sqrt(2) * (1 + expbn2 * np.cosh(2*a_b))**(3/2) + g1 = -t1 * (t2 + t3) / denom + if 'k' in moments: + t1 = 3 + 6*expbn2 + t2 = 4*expbn2**2 * (expbn2 + 2) * np.cosh(2*a_b) + t3 = expbn2**2 * np.cosh(4*a_b) + t4 = -3 + 3*expbn2**2 + 2*expbn2**3 + expbn2**4 + denom = 2*(1 + expbn2*np.cosh(2*a_b))**2 + g2 = (t1 + t2 + t3*t4) / denom - 3 + return mu, mu2, g1, g2 + + +johnsonsu = johnsonsu_gen(name='johnsonsu') + + +class landau_gen(rv_continuous): + r"""A Landau continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `landau` ([1]_, [2]_) is: + + .. math:: + + f(x) = \frac{1}{\pi}\int_0^\infty \exp(-t \log t - xt)\sin(\pi t) dt + + for a real number :math:`x`. + + %(after_notes)s + + Often (e.g. [2]_), the Landau distribution is parameterized in terms of a + location parameter :math:`\mu` and scale parameter :math:`c`, the latter of + which *also* introduces a location shift. If ``mu`` and ``c`` are used to + represent these parameters, this corresponds with SciPy's parameterization + with ``loc = mu + 2*c / np.pi * np.log(c)`` and ``scale = c``. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf`` + methods. [1]_ + + References + ---------- + .. [1] Landau, L. (1944). "On the energy loss of fast particles by + ionization". J. Phys. (USSR). 8: 201. + .. [2] "Landau Distribution", Wikipedia, + https://en.wikipedia.org/wiki/Landau_distribution + .. [3] Chambers, J. M., Mallows, C. L., & Stuck, B. (1976). + "A method for simulating stable random variables." + Journal of the American Statistical Association, 71(354), 340-344. + .. [4] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + .. [5] Yoshimura, T. "Numerical Evaluation and High Precision Approximation + Formula for Landau Distribution". + :doi:`10.36227/techrxiv.171822215.53612870/v2` + + %(example)s + + """ + def _shape_info(self): + return [] + + def _entropy(self): + # Computed with mpmath - see gh-19145 + return 2.37263644000448182 + + def _pdf(self, x): + return scu._landau_pdf(x, 0, 1) + + def _cdf(self, x): + return scu._landau_cdf(x, 0, 1) + + def _sf(self, x): + return scu._landau_sf(x, 0, 1) + + def _ppf(self, p): + return scu._landau_ppf(p, 0, 1) + + def _isf(self, p): + return scu._landau_isf(p, 0, 1) + + def _stats(self): + return np.nan, np.nan, np.nan, np.nan + + def _munp(self, n): + return np.nan if n > 0 else 1 + + def _fitstart(self, data, args=None): + # Initialize ML guesses using quartiles instead of moments. + if isinstance(data, CensoredData): + data = data._uncensor() + p25, p50, p75 = np.percentile(data, [25, 50, 75]) + return p50, (p75 - p25)/2 + + def _rvs(self, size=None, random_state=None): + # Method from https://www.jstor.org/stable/2285309 Eq. 2.4 + pi_2 = np.pi / 2 + U = random_state.uniform(-np.pi / 2, np.pi / 2, size=size) + W = random_state.standard_exponential(size=size) + S = 2 / np.pi * ((pi_2 + U) * np.tan(U) + - np.log((pi_2 * W * np.cos(U)) / (pi_2 + U))) + return S + + +landau = landau_gen(name='landau') + + +class laplace_gen(rv_continuous): + r"""A Laplace continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `laplace` is + + .. math:: + + f(x) = \frac{1}{2} \exp(-|x|) + + for a real number :math:`x`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return random_state.laplace(0, 1, size=size) + + def _pdf(self, x): + # laplace.pdf(x) = 1/2 * exp(-abs(x)) + return 0.5*np.exp(-abs(x)) + + def _cdf(self, x): + with np.errstate(over='ignore'): + return np.where(x > 0, 1.0 - 0.5*np.exp(-x), 0.5*np.exp(x)) + + def _sf(self, x): + # By symmetry... + return self._cdf(-x) + + def _ppf(self, q): + return np.where(q > 0.5, -np.log(2*(1-q)), np.log(2*q)) + + def _isf(self, q): + # By symmetry... + return -self._ppf(q) + + def _stats(self): + return 0, 2, 0, 3 + + def _entropy(self): + return np.log(2)+1 + + @_call_super_mom + @replace_notes_in_docstring(rv_continuous, notes="""\ + This function uses explicit formulas for the maximum likelihood + estimation of the Laplace distribution parameters, so the keyword + arguments `loc`, `scale`, and `optimizer` are ignored.\n\n""") + def fit(self, data, *args, **kwds): + data, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + + # Source: Statistical Distributions, 3rd Edition. Evans, Hastings, + # and Peacock (2000), Page 124 + + if floc is None: + floc = np.median(data) + + if fscale is None: + fscale = (np.sum(np.abs(data - floc))) / len(data) + + return floc, fscale + + +laplace = laplace_gen(name='laplace') + + +class laplace_asymmetric_gen(rv_continuous): + r"""An asymmetric Laplace continuous random variable. + + %(before_notes)s + + See Also + -------- + laplace : Laplace distribution + + Notes + ----- + The probability density function for `laplace_asymmetric` is + + .. math:: + + f(x, \kappa) &= \frac{1}{\kappa+\kappa^{-1}}\exp(-x\kappa),\quad x\ge0\\ + &= \frac{1}{\kappa+\kappa^{-1}}\exp(x/\kappa),\quad x<0\\ + + for :math:`-\infty < x < \infty`, :math:`\kappa > 0`. + + `laplace_asymmetric` takes ``kappa`` as a shape parameter for + :math:`\kappa`. For :math:`\kappa = 1`, it is identical to a + Laplace distribution. + + %(after_notes)s + + Note that the scale parameter of some references is the reciprocal of + SciPy's ``scale``. For example, :math:`\lambda = 1/2` in the + parameterization of [1]_ is equivalent to ``scale = 2`` with + `laplace_asymmetric`. + + References + ---------- + .. [1] "Asymmetric Laplace distribution", Wikipedia + https://en.wikipedia.org/wiki/Asymmetric_Laplace_distribution + + .. [2] Kozubowski TJ and Podgórski K. A Multivariate and + Asymmetric Generalization of Laplace Distribution, + Computational Statistics 15, 531--540 (2000). + :doi:`10.1007/PL00022717` + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("kappa", False, (0, np.inf), (False, False))] + + def _pdf(self, x, kappa): + return np.exp(self._logpdf(x, kappa)) + + def _logpdf(self, x, kappa): + kapinv = 1/kappa + lPx = x * np.where(x >= 0, -kappa, kapinv) + lPx -= np.log(kappa+kapinv) + return lPx + + def _cdf(self, x, kappa): + kapinv = 1/kappa + kappkapinv = kappa+kapinv + return np.where(x >= 0, + 1 - np.exp(-x*kappa)*(kapinv/kappkapinv), + np.exp(x*kapinv)*(kappa/kappkapinv)) + + def _sf(self, x, kappa): + kapinv = 1/kappa + kappkapinv = kappa+kapinv + return np.where(x >= 0, + np.exp(-x*kappa)*(kapinv/kappkapinv), + 1 - np.exp(x*kapinv)*(kappa/kappkapinv)) + + def _ppf(self, q, kappa): + kapinv = 1/kappa + kappkapinv = kappa+kapinv + return np.where(q >= kappa/kappkapinv, + -np.log((1 - q)*kappkapinv*kappa)*kapinv, + np.log(q*kappkapinv/kappa)*kappa) + + def _isf(self, q, kappa): + kapinv = 1/kappa + kappkapinv = kappa+kapinv + return np.where(q <= kapinv/kappkapinv, + -np.log(q*kappkapinv*kappa)*kapinv, + np.log((1 - q)*kappkapinv/kappa)*kappa) + + def _stats(self, kappa): + kapinv = 1/kappa + mn = kapinv - kappa + var = kapinv*kapinv + kappa*kappa + g1 = 2.0*(1-np.power(kappa, 6))/np.power(1+np.power(kappa, 4), 1.5) + g2 = 6.0*(1+np.power(kappa, 8))/np.power(1+np.power(kappa, 4), 2) + return mn, var, g1, g2 + + def _entropy(self, kappa): + return 1 + np.log(kappa+1/kappa) + + +laplace_asymmetric = laplace_asymmetric_gen(name='laplace_asymmetric') + + +def _check_fit_input_parameters(dist, data, args, kwds): + if not isinstance(data, CensoredData): + data = np.asarray(data) + + floc = kwds.get('floc', None) + fscale = kwds.get('fscale', None) + + num_shapes = len(dist.shapes.split(",")) if dist.shapes else 0 + fshape_keys = [] + fshapes = [] + + # user has many options for fixing the shape, so here we standardize it + # into 'f' + the number of the shape. + # Adapted from `_reduce_func` in `_distn_infrastructure.py`: + if dist.shapes: + shapes = dist.shapes.replace(',', ' ').split() + for j, s in enumerate(shapes): + key = 'f' + str(j) + names = [key, 'f' + s, 'fix_' + s] + val = _get_fixed_fit_value(kwds, names) + fshape_keys.append(key) + fshapes.append(val) + if val is not None: + kwds[key] = val + + # determine if there are any unknown arguments in kwds + known_keys = {'loc', 'scale', 'optimizer', 'method', + 'floc', 'fscale', *fshape_keys} + unknown_keys = set(kwds).difference(known_keys) + if unknown_keys: + raise TypeError(f"Unknown keyword arguments: {unknown_keys}.") + + if len(args) > num_shapes: + raise TypeError("Too many positional arguments.") + + if None not in {floc, fscale, *fshapes}: + # This check is for consistency with `rv_continuous.fit`. + # Without this check, this function would just return the + # parameters that were given. + raise RuntimeError("All parameters fixed. There is nothing to " + "optimize.") + + uncensored = data._uncensor() if isinstance(data, CensoredData) else data + if not np.isfinite(uncensored).all(): + raise ValueError("The data contains non-finite values.") + + return (data, *fshapes, floc, fscale) + + +class levy_gen(rv_continuous): + r"""A Levy continuous random variable. + + %(before_notes)s + + See Also + -------- + levy_stable, levy_l + + Notes + ----- + The probability density function for `levy` is: + + .. math:: + + f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp\left(-\frac{1}{2x}\right) + + for :math:`x > 0`. + + This is the same as the Levy-stable distribution with :math:`a=1/2` and + :math:`b=1`. + + %(after_notes)s + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import levy + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + + Calculate the first four moments: + + >>> mean, var, skew, kurt = levy.stats(moments='mvsk') + + Display the probability density function (``pdf``): + + >>> # `levy` is very heavy-tailed. + >>> # To show a nice plot, let's cut off the upper 40 percent. + >>> a, b = levy.ppf(0), levy.ppf(0.6) + >>> x = np.linspace(a, b, 100) + >>> ax.plot(x, levy.pdf(x), + ... 'r-', lw=5, alpha=0.6, label='levy pdf') + + Alternatively, the distribution object can be called (as a function) + to fix the shape, location and scale parameters. This returns a "frozen" + RV object holding the given parameters fixed. + + Freeze the distribution and display the frozen ``pdf``: + + >>> rv = levy() + >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + + Check accuracy of ``cdf`` and ``ppf``: + + >>> vals = levy.ppf([0.001, 0.5, 0.999]) + >>> np.allclose([0.001, 0.5, 0.999], levy.cdf(vals)) + True + + Generate random numbers: + + >>> r = levy.rvs(size=1000) + + And compare the histogram: + + >>> # manual binning to ignore the tail + >>> bins = np.concatenate((np.linspace(a, b, 20), [np.max(r)])) + >>> ax.hist(r, bins=bins, density=True, histtype='stepfilled', alpha=0.2) + >>> ax.set_xlim([x[0], x[-1]]) + >>> ax.legend(loc='best', frameon=False) + >>> plt.show() + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [] + + def _pdf(self, x): + # levy.pdf(x) = 1 / (x * sqrt(2*pi*x)) * exp(-1/(2*x)) + return 1 / np.sqrt(2*np.pi*x) / x * np.exp(-1/(2*x)) + + def _cdf(self, x): + # Equivalent to 2*norm.sf(np.sqrt(1/x)) + return sc.erfc(np.sqrt(0.5 / x)) + + def _sf(self, x): + return sc.erf(np.sqrt(0.5 / x)) + + def _ppf(self, q): + # Equivalent to 1.0/(norm.isf(q/2)**2) or 0.5/(erfcinv(q)**2) + val = _norm_isf(q/2) + return 1.0 / (val * val) + + def _isf(self, p): + return 1/(2*sc.erfinv(p)**2) + + def _stats(self): + return np.inf, np.inf, np.nan, np.nan + + +levy = levy_gen(a=0.0, name="levy") + + +class levy_l_gen(rv_continuous): + r"""A left-skewed Levy continuous random variable. + + %(before_notes)s + + See Also + -------- + levy, levy_stable + + Notes + ----- + The probability density function for `levy_l` is: + + .. math:: + f(x) = \frac{1}{|x| \sqrt{2\pi |x|}} \exp{ \left(-\frac{1}{2|x|} \right)} + + for :math:`x < 0`. + + This is the same as the Levy-stable distribution with :math:`a=1/2` and + :math:`b=-1`. + + %(after_notes)s + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import levy_l + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + + Calculate the first four moments: + + >>> mean, var, skew, kurt = levy_l.stats(moments='mvsk') + + Display the probability density function (``pdf``): + + >>> # `levy_l` is very heavy-tailed. + >>> # To show a nice plot, let's cut off the lower 40 percent. + >>> a, b = levy_l.ppf(0.4), levy_l.ppf(1) + >>> x = np.linspace(a, b, 100) + >>> ax.plot(x, levy_l.pdf(x), + ... 'r-', lw=5, alpha=0.6, label='levy_l pdf') + + Alternatively, the distribution object can be called (as a function) + to fix the shape, location and scale parameters. This returns a "frozen" + RV object holding the given parameters fixed. + + Freeze the distribution and display the frozen ``pdf``: + + >>> rv = levy_l() + >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + + Check accuracy of ``cdf`` and ``ppf``: + + >>> vals = levy_l.ppf([0.001, 0.5, 0.999]) + >>> np.allclose([0.001, 0.5, 0.999], levy_l.cdf(vals)) + True + + Generate random numbers: + + >>> r = levy_l.rvs(size=1000) + + And compare the histogram: + + >>> # manual binning to ignore the tail + >>> bins = np.concatenate(([np.min(r)], np.linspace(a, b, 20))) + >>> ax.hist(r, bins=bins, density=True, histtype='stepfilled', alpha=0.2) + >>> ax.set_xlim([x[0], x[-1]]) + >>> ax.legend(loc='best', frameon=False) + >>> plt.show() + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [] + + def _pdf(self, x): + # levy_l.pdf(x) = 1 / (abs(x) * sqrt(2*pi*abs(x))) * exp(-1/(2*abs(x))) + ax = abs(x) + return 1/np.sqrt(2*np.pi*ax)/ax*np.exp(-1/(2*ax)) + + def _cdf(self, x): + ax = abs(x) + return 2 * _norm_cdf(1 / np.sqrt(ax)) - 1 + + def _sf(self, x): + ax = abs(x) + return 2 * _norm_sf(1 / np.sqrt(ax)) + + def _ppf(self, q): + val = _norm_ppf((q + 1.0) / 2) + return -1.0 / (val * val) + + def _isf(self, p): + return -1/_norm_isf(p/2)**2 + + def _stats(self): + return np.inf, np.inf, np.nan, np.nan + + +levy_l = levy_l_gen(b=0.0, name="levy_l") + + +class logistic_gen(rv_continuous): + r"""A logistic (or Sech-squared) continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `logistic` is: + + .. math:: + + f(x) = \frac{\exp(-x)} + {(1+\exp(-x))^2} + + `logistic` is a special case of `genlogistic` with ``c=1``. + + Remark that the survival function (``logistic.sf``) is equal to the + Fermi-Dirac distribution describing fermionic statistics. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return random_state.logistic(size=size) + + def _pdf(self, x): + # logistic.pdf(x) = exp(-x) / (1+exp(-x))**2 + return np.exp(self._logpdf(x)) + + def _logpdf(self, x): + y = -np.abs(x) + return y - 2. * sc.log1p(np.exp(y)) + + def _cdf(self, x): + return sc.expit(x) + + def _logcdf(self, x): + return sc.log_expit(x) + + def _ppf(self, q): + return sc.logit(q) + + def _sf(self, x): + return sc.expit(-x) + + def _logsf(self, x): + return sc.log_expit(-x) + + def _isf(self, q): + return -sc.logit(q) + + def _stats(self): + return 0, np.pi*np.pi/3.0, 0, 6.0/5.0 + + def _entropy(self): + # https://en.wikipedia.org/wiki/Logistic_distribution + return 2.0 + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + data, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + n = len(data) + + # rv_continuous provided guesses + loc, scale = self._fitstart(data) + # these are trumped by user-provided guesses + loc, scale = kwds.get('loc', loc), kwds.get('scale', scale) + + # the maximum likelihood estimators `a` and `b` of the location and + # scale parameters are roots of the two equations described in `func`. + # Source: Statistical Distributions, 3rd Edition. Evans, Hastings, and + # Peacock (2000), Page 130 + + def dl_dloc(loc, scale=fscale): + c = (data - loc) / scale + return np.sum(sc.expit(c)) - n/2 + + def dl_dscale(scale, loc=floc): + c = (data - loc) / scale + return np.sum(c*np.tanh(c/2)) - n + + def func(params): + loc, scale = params + return dl_dloc(loc, scale), dl_dscale(scale, loc) + + if fscale is not None and floc is None: + res = optimize.root(dl_dloc, (loc,)) + loc = res.x[0] + scale = fscale + elif floc is not None and fscale is None: + res = optimize.root(dl_dscale, (scale,)) + scale = res.x[0] + loc = floc + else: + res = optimize.root(func, (loc, scale)) + loc, scale = res.x + + # Note: gh-18176 reported data for which the reported MLE had + # `scale < 0`. To fix the bug, we return abs(scale). This is OK because + # `dl_dscale` and `dl_dloc` are even and odd functions of `scale`, + # respectively, so if `-scale` is a solution, so is `scale`. + scale = abs(scale) + return ((loc, scale) if res.success + else super().fit(data, *args, **kwds)) + + +logistic = logistic_gen(name='logistic') + + +class loggamma_gen(rv_continuous): + r"""A log gamma continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `loggamma` is: + + .. math:: + + f(x, c) = \frac{\exp(c x - \exp(x))} + {\Gamma(c)} + + for all :math:`x, c > 0`. Here, :math:`\Gamma` is the + gamma function (`scipy.special.gamma`). + + `loggamma` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _rvs(self, c, size=None, random_state=None): + # Use the property of the gamma distribution Gamma(c) + # Gamma(c) ~ Gamma(c + 1)*U**(1/c), + # where U is uniform on [0, 1]. (See, e.g., + # G. Marsaglia and W.W. Tsang, "A simple method for generating gamma + # variables", https://doi.org/10.1145/358407.358414) + # So + # log(Gamma(c)) ~ log(Gamma(c + 1)) + log(U)/c + # Generating a sample with this formulation is a bit slower + # than the more obvious log(Gamma(c)), but it avoids loss + # of precision when c << 1. + return (np.log(random_state.gamma(c + 1, size=size)) + + np.log(random_state.uniform(size=size))/c) + + def _pdf(self, x, c): + # loggamma.pdf(x, c) = exp(c*x-exp(x)) / gamma(c) + return np.exp(c*x-np.exp(x)-sc.gammaln(c)) + + def _logpdf(self, x, c): + return c*x - np.exp(x) - sc.gammaln(c) + + def _cdf(self, x, c): + # This function is gammainc(c, exp(x)), where gammainc(c, z) is + # the regularized incomplete gamma function. + # The first term in a series expansion of gamminc(c, z) is + # z**c/Gamma(c+1); see 6.5.29 of Abramowitz & Stegun (and refer + # back to 6.5.1, 6.5.2 and 6.5.4 for the relevant notation). + # This can also be found in the wikipedia article + # https://en.wikipedia.org/wiki/Incomplete_gamma_function. + # Here we use that formula when x is sufficiently negative that + # exp(x) will result in subnormal numbers and lose precision. + # We evaluate the log of the expression first to allow the possible + # cancellation of the terms in the division, and then exponentiate. + # That is, + # exp(x)**c/Gamma(c+1) = exp(log(exp(x)**c/Gamma(c+1))) + # = exp(c*x - gammaln(c+1)) + return _lazywhere(x < _LOGXMIN, (x, c), + lambda x, c: np.exp(c*x - sc.gammaln(c+1)), + f2=lambda x, c: sc.gammainc(c, np.exp(x))) + + def _ppf(self, q, c): + # The expression used when g < _XMIN inverts the one term expansion + # given in the comments of _cdf(). + g = sc.gammaincinv(c, q) + return _lazywhere(g < _XMIN, (g, q, c), + lambda g, q, c: (np.log(q) + sc.gammaln(c+1))/c, + f2=lambda g, q, c: np.log(g)) + + def _sf(self, x, c): + # See the comments for _cdf() for how x < _LOGXMIN is handled. + return _lazywhere(x < _LOGXMIN, (x, c), + lambda x, c: -np.expm1(c*x - sc.gammaln(c+1)), + f2=lambda x, c: sc.gammaincc(c, np.exp(x))) + + def _isf(self, q, c): + # The expression used when g < _XMIN inverts the complement of + # the one term expansion given in the comments of _cdf(). + g = sc.gammainccinv(c, q) + return _lazywhere(g < _XMIN, (g, q, c), + lambda g, q, c: (np.log1p(-q) + sc.gammaln(c+1))/c, + f2=lambda g, q, c: np.log(g)) + + def _stats(self, c): + # See, for example, "A Statistical Study of Log-Gamma Distribution", by + # Ping Shing Chan (thesis, McMaster University, 1993). + mean = sc.digamma(c) + var = sc.polygamma(1, c) + skewness = sc.polygamma(2, c) / np.power(var, 1.5) + excess_kurtosis = sc.polygamma(3, c) / (var*var) + return mean, var, skewness, excess_kurtosis + + def _entropy(self, c): + def regular(c): + h = sc.gammaln(c) - c * sc.digamma(c) + c + return h + + def asymptotic(c): + # using asymptotic expansions for gammaln and psi (see gh-18093) + term = -0.5*np.log(c) + c**-1./6 - c**-3./90 + c**-5./210 + h = norm._entropy() + term + return h + + h = _lazywhere(c >= 45, (c, ), f=asymptotic, f2=regular) + return h + + +loggamma = loggamma_gen(name='loggamma') + + +class loglaplace_gen(rv_continuous): + r"""A log-Laplace continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `loglaplace` is: + + .. math:: + + f(x, c) = \begin{cases}\frac{c}{2} x^{ c-1} &\text{for } 0 < x < 1\\ + \frac{c}{2} x^{-c-1} &\text{for } x \ge 1 + \end{cases} + + for :math:`c > 0`. + + `loglaplace` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + Suppose a random variable ``X`` follows the Laplace distribution with + location ``a`` and scale ``b``. Then ``Y = exp(X)`` follows the + log-Laplace distribution with ``c = 1 / b`` and ``scale = exp(a)``. + + References + ---------- + T.J. Kozubowski and K. Podgorski, "A log-Laplace growth rate model", + The Mathematical Scientist, vol. 28, pp. 49-60, 2003. + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # loglaplace.pdf(x, c) = c / 2 * x**(c-1), for 0 < x < 1 + # = c / 2 * x**(-c-1), for x >= 1 + cd2 = c/2.0 + c = np.where(x < 1, c, -c) + return cd2*x**(c-1) + + def _cdf(self, x, c): + return np.where(x < 1, 0.5*x**c, 1-0.5*x**(-c)) + + def _sf(self, x, c): + return np.where(x < 1, 1 - 0.5*x**c, 0.5*x**(-c)) + + def _ppf(self, q, c): + return np.where(q < 0.5, (2.0*q)**(1.0/c), (2*(1.0-q))**(-1.0/c)) + + def _isf(self, q, c): + return np.where(q > 0.5, (2.0*(1.0 - q))**(1.0/c), (2*q)**(-1.0/c)) + + def _munp(self, n, c): + with np.errstate(divide='ignore'): + c2, n2 = c**2, n**2 + return np.where(n2 < c2, c2 / (c2 - n2), np.inf) + + def _entropy(self, c): + return np.log(2.0/c) + 1.0 + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + data, fc, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + + # Specialize MLE only when location is known. + if floc is None: + return super(type(self), self).fit(data, *args, **kwds) + + # Raise an error if any observation has zero likelihood. + if np.any(data <= floc): + raise FitDataError("loglaplace", lower=floc, upper=np.inf) + + # Remove location from data. + if floc != 0: + data = data - floc + + # When location is zero, the log-Laplace distribution is related to + # the Laplace distribution in that if X ~ Laplace(loc=a, scale=b), + # then Y = exp(X) ~ LogLaplace(c=1/b, loc=0, scale=exp(a)). It can + # be shown that the MLE for Y is the same as the MLE for X = ln(Y). + # Therefore, we reuse the formulas from laplace.fit() and transform + # the result back into log-laplace's parameter space. + a, b = laplace.fit(np.log(data), + floc=np.log(fscale) if fscale is not None else None, + fscale=1/fc if fc is not None else None, + method='mle') + loc = floc + scale = np.exp(a) if fscale is None else fscale + c = 1 / b if fc is None else fc + return c, loc, scale + +loglaplace = loglaplace_gen(a=0.0, name='loglaplace') + + +def _lognorm_logpdf(x, s): + return _lazywhere(x != 0, (x, s), + lambda x, s: (-np.log(x)**2 / (2 * s**2) + - np.log(s * x * np.sqrt(2 * np.pi))), + -np.inf) + + +class lognorm_gen(rv_continuous): + r"""A lognormal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `lognorm` is: + + .. math:: + + f(x, s) = \frac{1}{s x \sqrt{2\pi}} + \exp\left(-\frac{\log^2(x)}{2s^2}\right) + + for :math:`x > 0`, :math:`s > 0`. + + `lognorm` takes ``s`` as a shape parameter for :math:`s`. + + %(after_notes)s + + Suppose a normally distributed random variable ``X`` has mean ``mu`` and + standard deviation ``sigma``. Then ``Y = exp(X)`` is lognormally + distributed with ``s = sigma`` and ``scale = exp(mu)``. + + %(example)s + + The logarithm of a log-normally distributed random variable is + normally distributed: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> fig, ax = plt.subplots(1, 1) + >>> mu, sigma = 2, 0.5 + >>> X = stats.norm(loc=mu, scale=sigma) + >>> Y = stats.lognorm(s=sigma, scale=np.exp(mu)) + >>> x = np.linspace(*X.interval(0.999)) + >>> y = Y.rvs(size=10000) + >>> ax.plot(x, X.pdf(x), label='X (pdf)') + >>> ax.hist(np.log(y), density=True, bins=x, label='log(Y) (histogram)') + >>> ax.legend() + >>> plt.show() + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [_ShapeInfo("s", False, (0, np.inf), (False, False))] + + def _rvs(self, s, size=None, random_state=None): + return np.exp(s * random_state.standard_normal(size)) + + def _pdf(self, x, s): + # lognorm.pdf(x, s) = 1 / (s*x*sqrt(2*pi)) * exp(-1/2*(log(x)/s)**2) + return np.exp(self._logpdf(x, s)) + + def _logpdf(self, x, s): + return _lognorm_logpdf(x, s) + + def _cdf(self, x, s): + return _norm_cdf(np.log(x) / s) + + def _logcdf(self, x, s): + return _norm_logcdf(np.log(x) / s) + + def _ppf(self, q, s): + return np.exp(s * _norm_ppf(q)) + + def _sf(self, x, s): + return _norm_sf(np.log(x) / s) + + def _logsf(self, x, s): + return _norm_logsf(np.log(x) / s) + + def _isf(self, q, s): + return np.exp(s * _norm_isf(q)) + + def _stats(self, s): + p = np.exp(s*s) + mu = np.sqrt(p) + mu2 = p*(p-1) + g1 = np.sqrt(p-1)*(2+p) + g2 = np.polyval([1, 2, 3, 0, -6.0], p) + return mu, mu2, g1, g2 + + def _entropy(self, s): + return 0.5 * (1 + np.log(2*np.pi) + 2 * np.log(s)) + + @_call_super_mom + @extend_notes_in_docstring(rv_continuous, notes="""\ + When `method='MLE'` and + the location parameter is fixed by using the `floc` argument, + this function uses explicit formulas for the maximum likelihood + estimation of the log-normal shape and scale parameters, so the + `optimizer`, `loc` and `scale` keyword arguments are ignored. + If the location is free, a likelihood maximum is found by + setting its partial derivative wrt to location to 0, and + solving by substituting the analytical expressions of shape + and scale (or provided parameters). + See, e.g., equation 3.1 in + A. Clifford Cohen & Betty Jones Whitten (1980) + Estimation in the Three-Parameter Lognormal Distribution, + Journal of the American Statistical Association, 75:370, 399-404 + https://doi.org/10.2307/2287466 + \n\n""") + def fit(self, data, *args, **kwds): + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + parameters = _check_fit_input_parameters(self, data, args, kwds) + data, fshape, floc, fscale = parameters + data_min = np.min(data) + + def get_shape_scale(loc): + # Calculate maximum likelihood scale and shape with analytical + # formulas unless provided by the user + if fshape is None or fscale is None: + lndata = np.log(data - loc) + scale = fscale or np.exp(lndata.mean()) + shape = fshape or np.sqrt(np.mean((lndata - np.log(scale))**2)) + return shape, scale + + def dL_dLoc(loc): + # Derivative of (positive) LL w.r.t. loc + shape, scale = get_shape_scale(loc) + shifted = data - loc + return np.sum((1 + np.log(shifted/scale)/shape**2)/shifted) + + def ll(loc): + # (Positive) log-likelihood + shape, scale = get_shape_scale(loc) + return -self.nnlf((shape, loc, scale), data) + + if floc is None: + # The location must be less than the minimum of the data. + # Back off a bit to avoid numerical issues. + spacing = np.spacing(data_min) + rbrack = data_min - spacing + + # Find the right end of the bracket by successive doubling of the + # distance to data_min. We're interested in a maximum LL, so the + # slope dL_dLoc_rbrack should be negative at the right end. + # optimization for later: share shape, scale + dL_dLoc_rbrack = dL_dLoc(rbrack) + ll_rbrack = ll(rbrack) + delta = 2 * spacing # 2 * (data_min - rbrack) + while dL_dLoc_rbrack >= -1e-6: + rbrack = data_min - delta + dL_dLoc_rbrack = dL_dLoc(rbrack) + delta *= 2 + + if not np.isfinite(rbrack) or not np.isfinite(dL_dLoc_rbrack): + # If we never find a negative slope, either we missed it or the + # slope is always positive. It's usually the latter, + # which means + # loc = data_min - spacing + # But sometimes when shape and/or scale are fixed there are + # other issues, so be cautious. + return super().fit(data, *args, **kwds) + + # Now find the left end of the bracket. Guess is `rbrack-1` + # unless that is too small of a difference to resolve. Double + # the size of the interval until the left end is found. + lbrack = np.minimum(np.nextafter(rbrack, -np.inf), rbrack-1) + dL_dLoc_lbrack = dL_dLoc(lbrack) + delta = 2 * (rbrack - lbrack) + while (np.isfinite(lbrack) and np.isfinite(dL_dLoc_lbrack) + and np.sign(dL_dLoc_lbrack) == np.sign(dL_dLoc_rbrack)): + lbrack = rbrack - delta + dL_dLoc_lbrack = dL_dLoc(lbrack) + delta *= 2 + + # I don't recall observing this, but just in case... + if not np.isfinite(lbrack) or not np.isfinite(dL_dLoc_lbrack): + return super().fit(data, *args, **kwds) + + # If we have a valid bracket, find the root + res = root_scalar(dL_dLoc, bracket=(lbrack, rbrack)) + if not res.converged: + return super().fit(data, *args, **kwds) + + # If the slope was positive near the minimum of the data, + # the maximum LL could be there instead of at the root. Compare + # the LL of the two points to decide. + ll_root = ll(res.root) + loc = res.root if ll_root > ll_rbrack else data_min-spacing + + else: + if floc >= data_min: + raise FitDataError("lognorm", lower=0., upper=np.inf) + loc = floc + + shape, scale = get_shape_scale(loc) + if not (self._argcheck(shape) and scale > 0): + return super().fit(data, *args, **kwds) + return shape, loc, scale + + +lognorm = lognorm_gen(a=0.0, name='lognorm') + + +class gibrat_gen(rv_continuous): + r"""A Gibrat continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `gibrat` is: + + .. math:: + + f(x) = \frac{1}{x \sqrt{2\pi}} \exp(-\frac{1}{2} (\log(x))^2) + + for :math:`x >= 0`. + + `gibrat` is a special case of `lognorm` with ``s=1``. + + %(after_notes)s + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return np.exp(random_state.standard_normal(size)) + + def _pdf(self, x): + # gibrat.pdf(x) = 1/(x*sqrt(2*pi)) * exp(-1/2*(log(x))**2) + return np.exp(self._logpdf(x)) + + def _logpdf(self, x): + return _lognorm_logpdf(x, 1.0) + + def _cdf(self, x): + return _norm_cdf(np.log(x)) + + def _ppf(self, q): + return np.exp(_norm_ppf(q)) + + def _sf(self, x): + return _norm_sf(np.log(x)) + + def _isf(self, p): + return np.exp(_norm_isf(p)) + + def _stats(self): + p = np.e + mu = np.sqrt(p) + mu2 = p * (p - 1) + g1 = np.sqrt(p - 1) * (2 + p) + g2 = np.polyval([1, 2, 3, 0, -6.0], p) + return mu, mu2, g1, g2 + + def _entropy(self): + return 0.5 * np.log(2 * np.pi) + 0.5 + + +gibrat = gibrat_gen(a=0.0, name='gibrat') + + +class maxwell_gen(rv_continuous): + r"""A Maxwell continuous random variable. + + %(before_notes)s + + Notes + ----- + A special case of a `chi` distribution, with ``df=3``, ``loc=0.0``, + and given ``scale = a``, where ``a`` is the parameter used in the + Mathworld description [1]_. + + The probability density function for `maxwell` is: + + .. math:: + + f(x) = \sqrt{2/\pi}x^2 \exp(-x^2/2) + + for :math:`x >= 0`. + + %(after_notes)s + + References + ---------- + .. [1] http://mathworld.wolfram.com/MaxwellDistribution.html + + %(example)s + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return chi.rvs(3.0, size=size, random_state=random_state) + + def _pdf(self, x): + # maxwell.pdf(x) = sqrt(2/pi)x**2 * exp(-x**2/2) + return _SQRT_2_OVER_PI*x*x*np.exp(-x*x/2.0) + + def _logpdf(self, x): + # Allow x=0 without 'divide by zero' warnings + with np.errstate(divide='ignore'): + return _LOG_SQRT_2_OVER_PI + 2*np.log(x) - 0.5*x*x + + def _cdf(self, x): + return sc.gammainc(1.5, x*x/2.0) + + def _ppf(self, q): + return np.sqrt(2*sc.gammaincinv(1.5, q)) + + def _sf(self, x): + return sc.gammaincc(1.5, x*x/2.0) + + def _isf(self, q): + return np.sqrt(2*sc.gammainccinv(1.5, q)) + + def _stats(self): + val = 3*np.pi-8 + return (2*np.sqrt(2.0/np.pi), + 3-8/np.pi, + np.sqrt(2)*(32-10*np.pi)/val**1.5, + (-12*np.pi*np.pi + 160*np.pi - 384) / val**2.0) + + def _entropy(self): + return _EULER + 0.5*np.log(2*np.pi)-0.5 + + +maxwell = maxwell_gen(a=0.0, name='maxwell') + + +class mielke_gen(rv_continuous): + r"""A Mielke Beta-Kappa / Dagum continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `mielke` is: + + .. math:: + + f(x, k, s) = \frac{k x^{k-1}}{(1+x^s)^{1+k/s}} + + for :math:`x > 0` and :math:`k, s > 0`. The distribution is sometimes + called Dagum distribution ([2]_). It was already defined in [3]_, called + a Burr Type III distribution (`burr` with parameters ``c=s`` and + ``d=k/s``). + + `mielke` takes ``k`` and ``s`` as shape parameters. + + %(after_notes)s + + References + ---------- + .. [1] Mielke, P.W., 1973 "Another Family of Distributions for Describing + and Analyzing Precipitation Data." J. Appl. Meteor., 12, 275-280 + .. [2] Dagum, C., 1977 "A new model for personal income distribution." + Economie Appliquee, 33, 327-367. + .. [3] Burr, I. W. "Cumulative frequency functions", Annals of + Mathematical Statistics, 13(2), pp 215-232 (1942). + + %(example)s + + """ + def _shape_info(self): + ik = _ShapeInfo("k", False, (0, np.inf), (False, False)) + i_s = _ShapeInfo("s", False, (0, np.inf), (False, False)) + return [ik, i_s] + + def _pdf(self, x, k, s): + return k*x**(k-1.0) / (1.0+x**s)**(1.0+k*1.0/s) + + def _logpdf(self, x, k, s): + # Allow x=0 without 'divide by zero' warnings. + with np.errstate(divide='ignore'): + return np.log(k) + np.log(x)*(k - 1) - np.log1p(x**s)*(1 + k/s) + + def _cdf(self, x, k, s): + return x**k / (1.0+x**s)**(k*1.0/s) + + def _ppf(self, q, k, s): + qsk = pow(q, s*1.0/k) + return pow(qsk/(1.0-qsk), 1.0/s) + + def _munp(self, n, k, s): + def nth_moment(n, k, s): + # n-th moment is defined for -k < n < s + return sc.gamma((k+n)/s)*sc.gamma(1-n/s)/sc.gamma(k/s) + + return _lazywhere(n < s, (n, k, s), nth_moment, np.inf) + + +mielke = mielke_gen(a=0.0, name='mielke') + + +class kappa4_gen(rv_continuous): + r"""Kappa 4 parameter distribution. + + %(before_notes)s + + Notes + ----- + The probability density function for kappa4 is: + + .. math:: + + f(x, h, k) = (1 - k x)^{1/k - 1} (1 - h (1 - k x)^{1/k})^{1/h-1} + + if :math:`h` and :math:`k` are not equal to 0. + + If :math:`h` or :math:`k` are zero then the pdf can be simplified: + + h = 0 and k != 0:: + + kappa4.pdf(x, h, k) = (1.0 - k*x)**(1.0/k - 1.0)* + exp(-(1.0 - k*x)**(1.0/k)) + + h != 0 and k = 0:: + + kappa4.pdf(x, h, k) = exp(-x)*(1.0 - h*exp(-x))**(1.0/h - 1.0) + + h = 0 and k = 0:: + + kappa4.pdf(x, h, k) = exp(-x)*exp(-exp(-x)) + + kappa4 takes :math:`h` and :math:`k` as shape parameters. + + The kappa4 distribution returns other distributions when certain + :math:`h` and :math:`k` values are used. + + +------+-------------+----------------+------------------+ + | h | k=0.0 | k=1.0 | -inf<=k<=inf | + +======+=============+================+==================+ + | -1.0 | Logistic | | Generalized | + | | | | Logistic(1) | + | | | | | + | | logistic(x) | | | + +------+-------------+----------------+------------------+ + | 0.0 | Gumbel | Reverse | Generalized | + | | | Exponential(2) | Extreme Value | + | | | | | + | | gumbel_r(x) | | genextreme(x, k) | + +------+-------------+----------------+------------------+ + | 1.0 | Exponential | Uniform | Generalized | + | | | | Pareto | + | | | | | + | | expon(x) | uniform(x) | genpareto(x, -k) | + +------+-------------+----------------+------------------+ + + (1) There are at least five generalized logistic distributions. + Four are described here: + https://en.wikipedia.org/wiki/Generalized_logistic_distribution + The "fifth" one is the one kappa4 should match which currently + isn't implemented in scipy: + https://en.wikipedia.org/wiki/Talk:Generalized_logistic_distribution + https://www.mathwave.com/help/easyfit/html/analyses/distributions/gen_logistic.html + (2) This distribution is currently not in scipy. + + References + ---------- + J.C. Finney, "Optimization of a Skewed Logistic Distribution With Respect + to the Kolmogorov-Smirnov Test", A Dissertation Submitted to the Graduate + Faculty of the Louisiana State University and Agricultural and Mechanical + College, (August, 2004), + https://digitalcommons.lsu.edu/gradschool_dissertations/3672 + + J.R.M. Hosking, "The four-parameter kappa distribution". IBM J. Res. + Develop. 38 (3), 25 1-258 (1994). + + B. Kumphon, A. Kaew-Man, P. Seenoi, "A Rainfall Distribution for the Lampao + Site in the Chi River Basin, Thailand", Journal of Water Resource and + Protection, vol. 4, 866-869, (2012). + :doi:`10.4236/jwarp.2012.410101` + + C. Winchester, "On Estimation of the Four-Parameter Kappa Distribution", A + Thesis Submitted to Dalhousie University, Halifax, Nova Scotia, (March + 2000). + http://www.nlc-bnc.ca/obj/s4/f2/dsk2/ftp01/MQ57336.pdf + + %(after_notes)s + + %(example)s + + """ + def _argcheck(self, h, k): + shape = np.broadcast_arrays(h, k)[0].shape + return np.full(shape, fill_value=True) + + def _shape_info(self): + ih = _ShapeInfo("h", False, (-np.inf, np.inf), (False, False)) + ik = _ShapeInfo("k", False, (-np.inf, np.inf), (False, False)) + return [ih, ik] + + def _get_support(self, h, k): + condlist = [np.logical_and(h > 0, k > 0), + np.logical_and(h > 0, k == 0), + np.logical_and(h > 0, k < 0), + np.logical_and(h <= 0, k > 0), + np.logical_and(h <= 0, k == 0), + np.logical_and(h <= 0, k < 0)] + + def f0(h, k): + return (1.0 - np.float_power(h, -k))/k + + def f1(h, k): + return np.log(h) + + def f3(h, k): + a = np.empty(np.shape(h)) + a[:] = -np.inf + return a + + def f5(h, k): + return 1.0/k + + _a = _lazyselect(condlist, + [f0, f1, f0, f3, f3, f5], + [h, k], + default=np.nan) + + def f0(h, k): + return 1.0/k + + def f1(h, k): + a = np.empty(np.shape(h)) + a[:] = np.inf + return a + + _b = _lazyselect(condlist, + [f0, f1, f1, f0, f1, f1], + [h, k], + default=np.nan) + return _a, _b + + def _pdf(self, x, h, k): + # kappa4.pdf(x, h, k) = (1.0 - k*x)**(1.0/k - 1.0)* + # (1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h-1) + return np.exp(self._logpdf(x, h, k)) + + def _logpdf(self, x, h, k): + condlist = [np.logical_and(h != 0, k != 0), + np.logical_and(h == 0, k != 0), + np.logical_and(h != 0, k == 0), + np.logical_and(h == 0, k == 0)] + + def f0(x, h, k): + '''pdf = (1.0 - k*x)**(1.0/k - 1.0)*( + 1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h-1.0) + logpdf = ... + ''' + return (sc.xlog1py(1.0/k - 1.0, -k*x) + + sc.xlog1py(1.0/h - 1.0, -h*(1.0 - k*x)**(1.0/k))) + + def f1(x, h, k): + '''pdf = (1.0 - k*x)**(1.0/k - 1.0)*np.exp(-( + 1.0 - k*x)**(1.0/k)) + logpdf = ... + ''' + return sc.xlog1py(1.0/k - 1.0, -k*x) - (1.0 - k*x)**(1.0/k) + + def f2(x, h, k): + '''pdf = np.exp(-x)*(1.0 - h*np.exp(-x))**(1.0/h - 1.0) + logpdf = ... + ''' + return -x + sc.xlog1py(1.0/h - 1.0, -h*np.exp(-x)) + + def f3(x, h, k): + '''pdf = np.exp(-x-np.exp(-x)) + logpdf = ... + ''' + return -x - np.exp(-x) + + return _lazyselect(condlist, + [f0, f1, f2, f3], + [x, h, k], + default=np.nan) + + def _cdf(self, x, h, k): + return np.exp(self._logcdf(x, h, k)) + + def _logcdf(self, x, h, k): + condlist = [np.logical_and(h != 0, k != 0), + np.logical_and(h == 0, k != 0), + np.logical_and(h != 0, k == 0), + np.logical_and(h == 0, k == 0)] + + def f0(x, h, k): + '''cdf = (1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h) + logcdf = ... + ''' + return (1.0/h)*sc.log1p(-h*(1.0 - k*x)**(1.0/k)) + + def f1(x, h, k): + '''cdf = np.exp(-(1.0 - k*x)**(1.0/k)) + logcdf = ... + ''' + return -(1.0 - k*x)**(1.0/k) + + def f2(x, h, k): + '''cdf = (1.0 - h*np.exp(-x))**(1.0/h) + logcdf = ... + ''' + return (1.0/h)*sc.log1p(-h*np.exp(-x)) + + def f3(x, h, k): + '''cdf = np.exp(-np.exp(-x)) + logcdf = ... + ''' + return -np.exp(-x) + + return _lazyselect(condlist, + [f0, f1, f2, f3], + [x, h, k], + default=np.nan) + + def _ppf(self, q, h, k): + condlist = [np.logical_and(h != 0, k != 0), + np.logical_and(h == 0, k != 0), + np.logical_and(h != 0, k == 0), + np.logical_and(h == 0, k == 0)] + + def f0(q, h, k): + return 1.0/k*(1.0 - ((1.0 - (q**h))/h)**k) + + def f1(q, h, k): + return 1.0/k*(1.0 - (-np.log(q))**k) + + def f2(q, h, k): + '''ppf = -np.log((1.0 - (q**h))/h) + ''' + return -sc.log1p(-(q**h)) + np.log(h) + + def f3(q, h, k): + return -np.log(-np.log(q)) + + return _lazyselect(condlist, + [f0, f1, f2, f3], + [q, h, k], + default=np.nan) + + def _get_stats_info(self, h, k): + condlist = [ + np.logical_and(h < 0, k >= 0), + k < 0, + ] + + def f0(h, k): + return (-1.0/h*k).astype(int) + + def f1(h, k): + return (-1.0/k).astype(int) + + return _lazyselect(condlist, [f0, f1], [h, k], default=5) + + def _stats(self, h, k): + maxr = self._get_stats_info(h, k) + outputs = [None if np.any(r < maxr) else np.nan for r in range(1, 5)] + return outputs[:] + + def _mom1_sc(self, m, *args): + maxr = self._get_stats_info(args[0], args[1]) + if m >= maxr: + return np.nan + return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0] + + +kappa4 = kappa4_gen(name='kappa4') + + +class kappa3_gen(rv_continuous): + r"""Kappa 3 parameter distribution. + + %(before_notes)s + + Notes + ----- + The probability density function for `kappa3` is: + + .. math:: + + f(x, a) = a (a + x^a)^{-(a + 1)/a} + + for :math:`x > 0` and :math:`a > 0`. + + `kappa3` takes ``a`` as a shape parameter for :math:`a`. + + References + ---------- + P.W. Mielke and E.S. Johnson, "Three-Parameter Kappa Distribution Maximum + Likelihood and Likelihood Ratio Tests", Methods in Weather Research, + 701-707, (September, 1973), + :doi:`10.1175/1520-0493(1973)101<0701:TKDMLE>2.3.CO;2` + + B. Kumphon, "Maximum Entropy and Maximum Likelihood Estimation for the + Three-Parameter Kappa Distribution", Open Journal of Statistics, vol 2, + 415-419 (2012), :doi:`10.4236/ojs.2012.24050` + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (False, False))] + + def _pdf(self, x, a): + # kappa3.pdf(x, a) = a*(a + x**a)**(-(a + 1)/a), for x > 0 + return a*(a + x**a)**(-1.0/a-1) + + def _cdf(self, x, a): + return x*(a + x**a)**(-1.0/a) + + def _sf(self, x, a): + x, a = np.broadcast_arrays(x, a) # some code paths pass scalars + sf = super()._sf(x, a) + + # When the SF is small, another formulation is typically more accurate. + # However, it blows up for large `a`, so use it only if it also returns + # a small value of the SF. + cutoff = 0.01 + i = sf < cutoff + sf2 = -sc.expm1(sc.xlog1py(-1.0 / a[i], a[i] * x[i]**-a[i])) + i2 = sf2 > cutoff + sf2[i2] = sf[i][i2] # replace bad values with original values + + sf[i] = sf2 + return sf + + def _ppf(self, q, a): + return (a/(q**-a - 1.0))**(1.0/a) + + def _isf(self, q, a): + lg = sc.xlog1py(-a, -q) + denom = sc.expm1(lg) + return (a / denom)**(1.0 / a) + + def _stats(self, a): + outputs = [None if np.any(i < a) else np.nan for i in range(1, 5)] + return outputs[:] + + def _mom1_sc(self, m, *args): + if np.any(m >= args[0]): + return np.nan + return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0] + + +kappa3 = kappa3_gen(a=0.0, name='kappa3') + + +class moyal_gen(rv_continuous): + r"""A Moyal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `moyal` is: + + .. math:: + + f(x) = \exp(-(x + \exp(-x))/2) / \sqrt{2\pi} + + for a real number :math:`x`. + + %(after_notes)s + + This distribution has utility in high-energy physics and radiation + detection. It describes the energy loss of a charged relativistic + particle due to ionization of the medium [1]_. It also provides an + approximation for the Landau distribution. For an in depth description + see [2]_. For additional description, see [3]_. + + References + ---------- + .. [1] J.E. Moyal, "XXX. Theory of ionization fluctuations", + The London, Edinburgh, and Dublin Philosophical Magazine + and Journal of Science, vol 46, 263-280, (1955). + :doi:`10.1080/14786440308521076` (gated) + .. [2] G. Cordeiro et al., "The beta Moyal: a useful skew distribution", + International Journal of Research and Reviews in Applied Sciences, + vol 10, 171-192, (2012). + http://www.arpapress.com/Volumes/Vol10Issue2/IJRRAS_10_2_02.pdf + .. [3] C. Walck, "Handbook on Statistical Distributions for + Experimentalists; International Report SUF-PFY/96-01", Chapter 26, + University of Stockholm: Stockholm, Sweden, (2007). + http://www.stat.rice.edu/~dobelman/textfiles/DistributionsHandbook.pdf + + .. versionadded:: 1.1.0 + + %(example)s + + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + u1 = gamma.rvs(a=0.5, scale=2, size=size, + random_state=random_state) + return -np.log(u1) + + def _pdf(self, x): + return np.exp(-0.5 * (x + np.exp(-x))) / np.sqrt(2*np.pi) + + def _cdf(self, x): + return sc.erfc(np.exp(-0.5 * x) / np.sqrt(2)) + + def _sf(self, x): + return sc.erf(np.exp(-0.5 * x) / np.sqrt(2)) + + def _ppf(self, x): + return -np.log(2 * sc.erfcinv(x)**2) + + def _stats(self): + mu = np.log(2) + np.euler_gamma + mu2 = np.pi**2 / 2 + g1 = 28 * np.sqrt(2) * sc.zeta(3) / np.pi**3 + g2 = 4. + return mu, mu2, g1, g2 + + def _munp(self, n): + if n == 1.0: + return np.log(2) + np.euler_gamma + elif n == 2.0: + return np.pi**2 / 2 + (np.log(2) + np.euler_gamma)**2 + elif n == 3.0: + tmp1 = 1.5 * np.pi**2 * (np.log(2)+np.euler_gamma) + tmp2 = (np.log(2)+np.euler_gamma)**3 + tmp3 = 14 * sc.zeta(3) + return tmp1 + tmp2 + tmp3 + elif n == 4.0: + tmp1 = 4 * 14 * sc.zeta(3) * (np.log(2) + np.euler_gamma) + tmp2 = 3 * np.pi**2 * (np.log(2) + np.euler_gamma)**2 + tmp3 = (np.log(2) + np.euler_gamma)**4 + tmp4 = 7 * np.pi**4 / 4 + return tmp1 + tmp2 + tmp3 + tmp4 + else: + # return generic for higher moments + # return rv_continuous._mom1_sc(self, n, b) + return self._mom1_sc(n) + + +moyal = moyal_gen(name="moyal") + + +class nakagami_gen(rv_continuous): + r"""A Nakagami continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `nakagami` is: + + .. math:: + + f(x, \nu) = \frac{2 \nu^\nu}{\Gamma(\nu)} x^{2\nu-1} \exp(-\nu x^2) + + for :math:`x >= 0`, :math:`\nu > 0`. The distribution was introduced in + [2]_, see also [1]_ for further information. + + `nakagami` takes ``nu`` as a shape parameter for :math:`\nu`. + + %(after_notes)s + + References + ---------- + .. [1] "Nakagami distribution", Wikipedia + https://en.wikipedia.org/wiki/Nakagami_distribution + .. [2] M. Nakagami, "The m-distribution - A general formula of intensity + distribution of rapid fading", Statistical methods in radio wave + propagation, Pergamon Press, 1960, 3-36. + :doi:`10.1016/B978-0-08-009306-2.50005-4` + + %(example)s + + """ + def _argcheck(self, nu): + return nu > 0 + + def _shape_info(self): + return [_ShapeInfo("nu", False, (0, np.inf), (False, False))] + + def _pdf(self, x, nu): + return np.exp(self._logpdf(x, nu)) + + def _logpdf(self, x, nu): + # nakagami.pdf(x, nu) = 2 * nu**nu / gamma(nu) * + # x**(2*nu-1) * exp(-nu*x**2) + return (np.log(2) + sc.xlogy(nu, nu) - sc.gammaln(nu) + + sc.xlogy(2*nu - 1, x) - nu*x**2) + + def _cdf(self, x, nu): + return sc.gammainc(nu, nu*x*x) + + def _ppf(self, q, nu): + return np.sqrt(1.0/nu*sc.gammaincinv(nu, q)) + + def _sf(self, x, nu): + return sc.gammaincc(nu, nu*x*x) + + def _isf(self, p, nu): + return np.sqrt(1/nu * sc.gammainccinv(nu, p)) + + def _stats(self, nu): + mu = sc.poch(nu, 0.5)/np.sqrt(nu) + mu2 = 1.0-mu*mu + g1 = mu * (1 - 4*nu*mu2) / 2.0 / nu / np.power(mu2, 1.5) + g2 = -6*mu**4*nu + (8*nu-2)*mu**2-2*nu + 1 + g2 /= nu*mu2**2.0 + return mu, mu2, g1, g2 + + def _entropy(self, nu): + shape = np.shape(nu) + # because somehow this isn't taken care of by the infrastructure... + nu = np.atleast_1d(nu) + A = sc.gammaln(nu) + B = nu - (nu - 0.5) * sc.digamma(nu) + C = -0.5 * np.log(nu) - np.log(2) + h = A + B + C + # This is the asymptotic sum of A and B (see gh-17868) + norm_entropy = stats.norm._entropy() + # Above, this is lost to rounding error for large nu, so use the + # asymptotic sum when the approximation becomes accurate + i = nu > 5e4 # roundoff error ~ approximation error + # -1 / (12 * nu) is the O(1/nu) term; see gh-17929 + h[i] = C[i] + norm_entropy - 1/(12*nu[i]) + return h.reshape(shape)[()] + + def _rvs(self, nu, size=None, random_state=None): + # this relationship can be found in [1] or by a direct calculation + return np.sqrt(random_state.standard_gamma(nu, size=size) / nu) + + def _fitstart(self, data, args=None): + if isinstance(data, CensoredData): + data = data._uncensor() + if args is None: + args = (1.0,) * self.numargs + # Analytical justified estimates + # see: https://docs.scipy.org/doc/scipy/reference/tutorial/stats/continuous_nakagami.html + loc = np.min(data) + scale = np.sqrt(np.sum((data - loc)**2) / len(data)) + return args + (loc, scale) + + +nakagami = nakagami_gen(a=0.0, name="nakagami") + + +# The function name ncx2 is an abbreviation for noncentral chi squared. +def _ncx2_log_pdf(x, df, nc): + # We use (xs**2 + ns**2)/2 = (xs - ns)**2/2 + xs*ns, and include the + # factor of exp(-xs*ns) into the ive function to improve numerical + # stability at large values of xs. See also `rice.pdf`. + df2 = df/2.0 - 1.0 + xs, ns = np.sqrt(x), np.sqrt(nc) + res = sc.xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2 + corr = sc.ive(df2, xs*ns) / 2.0 + # Return res + np.log(corr) avoiding np.log(0) + return _lazywhere( + corr > 0, + (res, corr), + f=lambda r, c: r + np.log(c), + fillvalue=-np.inf) + + +class ncx2_gen(rv_continuous): + r"""A non-central chi-squared continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `ncx2` is: + + .. math:: + + f(x, k, \lambda) = \frac{1}{2} \exp(-(\lambda+x)/2) + (x/\lambda)^{(k-2)/4} I_{(k-2)/2}(\sqrt{\lambda x}) + + for :math:`x >= 0`, :math:`k > 0` and :math:`\lambda \ge 0`. + :math:`k` specifies the degrees of freedom (denoted ``df`` in the + implementation) and :math:`\lambda` is the non-centrality parameter + (denoted ``nc`` in the implementation). :math:`I_\nu` denotes the + modified Bessel function of first order of degree :math:`\nu` + (`scipy.special.iv`). + + `ncx2` takes ``df`` and ``nc`` as shape parameters. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf`` + methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + """ + def _argcheck(self, df, nc): + return (df > 0) & np.isfinite(df) & (nc >= 0) + + def _shape_info(self): + idf = _ShapeInfo("df", False, (0, np.inf), (False, False)) + inc = _ShapeInfo("nc", False, (0, np.inf), (True, False)) + return [idf, inc] + + def _rvs(self, df, nc, size=None, random_state=None): + return random_state.noncentral_chisquare(df, nc, size) + + def _logpdf(self, x, df, nc): + cond = np.ones_like(x, dtype=bool) & (nc != 0) + return _lazywhere(cond, (x, df, nc), f=_ncx2_log_pdf, + f2=lambda x, df, _: chi2._logpdf(x, df)) + + def _pdf(self, x, df, nc): + cond = np.ones_like(x, dtype=bool) & (nc != 0) + with np.errstate(over='ignore'): # see gh-17432 + return _lazywhere(cond, (x, df, nc), f=scu._ncx2_pdf, + f2=lambda x, df, _: chi2._pdf(x, df)) + + def _cdf(self, x, df, nc): + cond = np.ones_like(x, dtype=bool) & (nc != 0) + with np.errstate(over='ignore'): # see gh-17432 + return _lazywhere(cond, (x, df, nc), f=scu._ncx2_cdf, + f2=lambda x, df, _: chi2._cdf(x, df)) + + def _ppf(self, q, df, nc): + cond = np.ones_like(q, dtype=bool) & (nc != 0) + with np.errstate(over='ignore'): # see gh-17432 + return _lazywhere(cond, (q, df, nc), f=scu._ncx2_ppf, + f2=lambda x, df, _: chi2._ppf(x, df)) + + def _sf(self, x, df, nc): + cond = np.ones_like(x, dtype=bool) & (nc != 0) + with np.errstate(over='ignore'): # see gh-17432 + return _lazywhere(cond, (x, df, nc), f=scu._ncx2_sf, + f2=lambda x, df, _: chi2._sf(x, df)) + + def _isf(self, x, df, nc): + cond = np.ones_like(x, dtype=bool) & (nc != 0) + with np.errstate(over='ignore'): # see gh-17432 + return _lazywhere(cond, (x, df, nc), f=scu._ncx2_isf, + f2=lambda x, df, _: chi2._isf(x, df)) + + def _stats(self, df, nc): + _ncx2_mean = df + nc + def k_plus_cl(k, l, c): + return k + c*l + _ncx2_variance = 2.0 * k_plus_cl(df, nc, 2.0) + _ncx2_skewness = (np.sqrt(8.0) * k_plus_cl(df, nc, 3) / + np.sqrt(k_plus_cl(df, nc, 2.0)**3)) + _ncx2_kurtosis_excess = (12.0 * k_plus_cl(df, nc, 4.0) / + k_plus_cl(df, nc, 2.0)**2) + return ( + _ncx2_mean, + _ncx2_variance, + _ncx2_skewness, + _ncx2_kurtosis_excess, + ) + + +ncx2 = ncx2_gen(a=0.0, name='ncx2') + + +class ncf_gen(rv_continuous): + r"""A non-central F distribution continuous random variable. + + %(before_notes)s + + See Also + -------- + scipy.stats.f : Fisher distribution + + Notes + ----- + The probability density function for `ncf` is: + + .. math:: + + f(x, n_1, n_2, \lambda) = + \exp\left(\frac{\lambda}{2} + + \lambda n_1 \frac{x}{2(n_1 x + n_2)} + \right) + n_1^{n_1/2} n_2^{n_2/2} x^{n_1/2 - 1} \\ + (n_2 + n_1 x)^{-(n_1 + n_2)/2} + \gamma(n_1/2) \gamma(1 + n_2/2) \\ + \frac{L^{\frac{n_1}{2}-1}_{n_2/2} + \left(-\lambda n_1 \frac{x}{2(n_1 x + n_2)}\right)} + {B(n_1/2, n_2/2) + \gamma\left(\frac{n_1 + n_2}{2}\right)} + + for :math:`n_1, n_2 > 0`, :math:`\lambda \ge 0`. Here :math:`n_1` is the + degrees of freedom in the numerator, :math:`n_2` the degrees of freedom in + the denominator, :math:`\lambda` the non-centrality parameter, + :math:`\gamma` is the logarithm of the Gamma function, :math:`L_n^k` is a + generalized Laguerre polynomial and :math:`B` is the beta function. + + `ncf` takes ``dfn``, ``dfd`` and ``nc`` as shape parameters. If ``nc=0``, + the distribution becomes equivalent to the Fisher distribution. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pdf``, ``cdf``, ``ppf``, ``stats``, ``sf`` and + ``isf`` methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + """ + def _argcheck(self, dfn, dfd, nc): + return (dfn > 0) & (dfd > 0) & (nc >= 0) + + def _shape_info(self): + idf1 = _ShapeInfo("dfn", False, (0, np.inf), (False, False)) + idf2 = _ShapeInfo("dfd", False, (0, np.inf), (False, False)) + inc = _ShapeInfo("nc", False, (0, np.inf), (True, False)) + return [idf1, idf2, inc] + + def _rvs(self, dfn, dfd, nc, size=None, random_state=None): + return random_state.noncentral_f(dfn, dfd, nc, size) + + def _pdf(self, x, dfn, dfd, nc): + return scu._ncf_pdf(x, dfn, dfd, nc) + + def _cdf(self, x, dfn, dfd, nc): + return sc.ncfdtr(dfn, dfd, nc, x) + + def _ppf(self, q, dfn, dfd, nc): + with np.errstate(over='ignore'): # see gh-17432 + return sc.ncfdtri(dfn, dfd, nc, q) + + def _sf(self, x, dfn, dfd, nc): + return scu._ncf_sf(x, dfn, dfd, nc) + + def _isf(self, x, dfn, dfd, nc): + with np.errstate(over='ignore'): # see gh-17432 + return scu._ncf_isf(x, dfn, dfd, nc) + + # # Produces bogus values as written - maybe it's close, though? + # def _munp(self, n, dfn, dfd, nc): + # val = (dfn * 1.0/dfd)**n + # term = sc.gammaln(n+0.5*dfn) + sc.gammaln(0.5*dfd-n) - sc.gammaln(dfd*0.5) + # val *= np.exp(-nc / 2.0+term) + # val *= sc.hyp1f1(n+0.5*dfn, 0.5*dfn, 0.5*nc) + # return val + + def _stats(self, dfn, dfd, nc, moments='mv'): + mu = scu._ncf_mean(dfn, dfd, nc) + mu2 = scu._ncf_variance(dfn, dfd, nc) + g1 = scu._ncf_skewness(dfn, dfd, nc) if 's' in moments else None + g2 = scu._ncf_kurtosis_excess( # isn't really excess kurtosis! + dfn, dfd, nc) - 3 if 'k' in moments else None + # Mathematica: Kurtosis[NoncentralFRatioDistribution[27, 27, 0.415784417992261]] + return mu, mu2, g1, g2 + + +ncf = ncf_gen(a=0.0, name='ncf') + + +class t_gen(rv_continuous): + r"""A Student's t continuous random variable. + + For the noncentral t distribution, see `nct`. + + %(before_notes)s + + See Also + -------- + nct + + Notes + ----- + The probability density function for `t` is: + + .. math:: + + f(x, \nu) = \frac{\Gamma((\nu+1)/2)} + {\sqrt{\pi \nu} \Gamma(\nu/2)} + (1+x^2/\nu)^{-(\nu+1)/2} + + where :math:`x` is a real number and the degrees of freedom parameter + :math:`\nu` (denoted ``df`` in the implementation) satisfies + :math:`\nu > 0`. :math:`\Gamma` is the gamma function + (`scipy.special.gamma`). + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("df", False, (0, np.inf), (False, False))] + + def _rvs(self, df, size=None, random_state=None): + return random_state.standard_t(df, size=size) + + def _pdf(self, x, df): + return _lazywhere( + df == np.inf, (x, df), + f=lambda x, df: norm._pdf(x), + f2=lambda x, df: ( + np.exp(self._logpdf(x, df)) + ) + ) + + def _logpdf(self, x, df): + + def t_logpdf(x, df): + return (np.log(sc.poch(0.5 * df, 0.5)) + - 0.5 * (np.log(df) + np.log(np.pi)) + - (df + 1)/2*np.log1p(x * x/df)) + + def norm_logpdf(x, df): + return norm._logpdf(x) + + return _lazywhere(df == np.inf, (x, df, ), f=norm_logpdf, f2=t_logpdf) + + def _cdf(self, x, df): + return sc.stdtr(df, x) + + def _sf(self, x, df): + return sc.stdtr(df, -x) + + def _ppf(self, q, df): + return sc.stdtrit(df, q) + + def _isf(self, q, df): + return -sc.stdtrit(df, q) + + def _stats(self, df): + # infinite df -> normal distribution (0.0, 1.0, 0.0, 0.0) + infinite_df = np.isposinf(df) + + mu = np.where(df > 1, 0.0, np.inf) + + condlist = ((df > 1) & (df <= 2), + (df > 2) & np.isfinite(df), + infinite_df) + choicelist = (lambda df: np.broadcast_to(np.inf, df.shape), + lambda df: df / (df-2.0), + lambda df: np.broadcast_to(1, df.shape)) + mu2 = _lazyselect(condlist, choicelist, (df,), np.nan) + + g1 = np.where(df > 3, 0.0, np.nan) + + condlist = ((df > 2) & (df <= 4), + (df > 4) & np.isfinite(df), + infinite_df) + choicelist = (lambda df: np.broadcast_to(np.inf, df.shape), + lambda df: 6.0 / (df-4.0), + lambda df: np.broadcast_to(0, df.shape)) + g2 = _lazyselect(condlist, choicelist, (df,), np.nan) + + return mu, mu2, g1, g2 + + def _entropy(self, df): + if df == np.inf: + return norm._entropy() + + def regular(df): + half = df/2 + half1 = (df + 1)/2 + return (half1*(sc.digamma(half1) - sc.digamma(half)) + + np.log(np.sqrt(df)*sc.beta(half, 0.5))) + + def asymptotic(df): + # Formula from Wolfram Alpha: + # "asymptotic expansion (d+1)/2 * (digamma((d+1)/2) - digamma(d/2)) + # + log(sqrt(d) * beta(d/2, 1/2))" + h = (norm._entropy() + 1/df + (df**-2.)/4 - (df**-3.)/6 + - (df**-4.)/8 + 3/10*(df**-5.) + (df**-6.)/4) + return h + + h = _lazywhere(df >= 100, (df, ), f=asymptotic, f2=regular) + return h + + +t = t_gen(name='t') + + +class nct_gen(rv_continuous): + r"""A non-central Student's t continuous random variable. + + %(before_notes)s + + Notes + ----- + If :math:`Y` is a standard normal random variable and :math:`V` is + an independent chi-square random variable (`chi2`) with :math:`k` degrees + of freedom, then + + .. math:: + + X = \frac{Y + c}{\sqrt{V/k}} + + has a non-central Student's t distribution on the real line. + The degrees of freedom parameter :math:`k` (denoted ``df`` in the + implementation) satisfies :math:`k > 0` and the noncentrality parameter + :math:`c` (denoted ``nc`` in the implementation) is a real number. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf`` + methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + """ + def _argcheck(self, df, nc): + return (df > 0) & (nc == nc) + + def _shape_info(self): + idf = _ShapeInfo("df", False, (0, np.inf), (False, False)) + inc = _ShapeInfo("nc", False, (-np.inf, np.inf), (False, False)) + return [idf, inc] + + def _rvs(self, df, nc, size=None, random_state=None): + n = norm.rvs(loc=nc, size=size, random_state=random_state) + c2 = chi2.rvs(df, size=size, random_state=random_state) + return n * np.sqrt(df) / np.sqrt(c2) + + def _pdf(self, x, df, nc): + return scu._nct_pdf(x, df, nc) + + def _cdf(self, x, df, nc): + return sc.nctdtr(df, nc, x) + + def _ppf(self, q, df, nc): + with np.errstate(over='ignore'): # see gh-17432 + return scu._nct_ppf(q, df, nc) + + def _sf(self, x, df, nc): + with np.errstate(over='ignore'): # see gh-17432 + return np.clip(scu._nct_sf(x, df, nc), 0, 1) + + def _isf(self, x, df, nc): + with np.errstate(over='ignore'): # see gh-17432 + return scu._nct_isf(x, df, nc) + + def _stats(self, df, nc, moments='mv'): + mu = scu._nct_mean(df, nc) + mu2 = scu._nct_variance(df, nc) + g1 = scu._nct_skewness(df, nc) if 's' in moments else None + g2 = scu._nct_kurtosis_excess(df, nc) if 'k' in moments else None + return mu, mu2, g1, g2 + + +nct = nct_gen(name="nct") + + +class pareto_gen(rv_continuous): + r"""A Pareto continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `pareto` is: + + .. math:: + + f(x, b) = \frac{b}{x^{b+1}} + + for :math:`x \ge 1`, :math:`b > 0`. + + `pareto` takes ``b`` as a shape parameter for :math:`b`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("b", False, (0, np.inf), (False, False))] + + def _pdf(self, x, b): + # pareto.pdf(x, b) = b / x**(b+1) + return b * x**(-b-1) + + def _cdf(self, x, b): + return 1 - x**(-b) + + def _ppf(self, q, b): + return pow(1-q, -1.0/b) + + def _sf(self, x, b): + return x**(-b) + + def _isf(self, q, b): + return np.power(q, -1.0 / b) + + def _stats(self, b, moments='mv'): + mu, mu2, g1, g2 = None, None, None, None + if 'm' in moments: + mask = b > 1 + bt = np.extract(mask, b) + mu = np.full(np.shape(b), fill_value=np.inf) + np.place(mu, mask, bt / (bt-1.0)) + if 'v' in moments: + mask = b > 2 + bt = np.extract(mask, b) + mu2 = np.full(np.shape(b), fill_value=np.inf) + np.place(mu2, mask, bt / (bt-2.0) / (bt-1.0)**2) + if 's' in moments: + mask = b > 3 + bt = np.extract(mask, b) + g1 = np.full(np.shape(b), fill_value=np.nan) + vals = 2 * (bt + 1.0) * np.sqrt(bt - 2.0) / ((bt - 3.0) * np.sqrt(bt)) + np.place(g1, mask, vals) + if 'k' in moments: + mask = b > 4 + bt = np.extract(mask, b) + g2 = np.full(np.shape(b), fill_value=np.nan) + vals = (6.0*np.polyval([1.0, 1.0, -6, -2], bt) / + np.polyval([1.0, -7.0, 12.0, 0.0], bt)) + np.place(g2, mask, vals) + return mu, mu2, g1, g2 + + def _entropy(self, b): + return 1 + 1.0/b - np.log(b) + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + parameters = _check_fit_input_parameters(self, data, args, kwds) + data, fshape, floc, fscale = parameters + + # ensure that any fixed parameters don't violate constraints of the + # distribution before continuing. + if floc is not None and np.min(data) - floc < (fscale or 0): + raise FitDataError("pareto", lower=1, upper=np.inf) + + ndata = data.shape[0] + + def get_shape(scale, location): + # The first-order necessary condition on `shape` can be solved in + # closed form + return ndata / np.sum(np.log((data - location) / scale)) + + if floc is fscale is None: + # The support of the distribution is `(x - loc)/scale > 0`. + # The method of Lagrange multipliers turns this constraint + # into an equation that can be solved numerically. + # See gh-12545 for details. + + def dL_dScale(shape, scale): + # The partial derivative of the log-likelihood function w.r.t. + # the scale. + return ndata * shape / scale + + def dL_dLocation(shape, location): + # The partial derivative of the log-likelihood function w.r.t. + # the location. + return (shape + 1) * np.sum(1 / (data - location)) + + def fun_to_solve(scale): + # optimize the scale by setting the partial derivatives + # w.r.t. to location and scale equal and solving. + location = np.min(data) - scale + shape = fshape or get_shape(scale, location) + return dL_dLocation(shape, location) - dL_dScale(shape, scale) + + def interval_contains_root(lbrack, rbrack): + # return true if the signs disagree. + return (np.sign(fun_to_solve(lbrack)) != + np.sign(fun_to_solve(rbrack))) + + # set brackets for `root_scalar` to use when optimizing over the + # scale such that a root is likely between them. Use user supplied + # guess or default 1. + brack_start = float(kwds.get('scale', 1)) + lbrack, rbrack = brack_start / 2, brack_start * 2 + # if a root is not between the brackets, iteratively expand them + # until they include a sign change, checking after each bracket is + # modified. + while (not interval_contains_root(lbrack, rbrack) + and (lbrack > 0 or rbrack < np.inf)): + lbrack /= 2 + rbrack *= 2 + res = root_scalar(fun_to_solve, bracket=[lbrack, rbrack]) + if res.converged: + scale = res.root + loc = np.min(data) - scale + shape = fshape or get_shape(scale, loc) + + # The Pareto distribution requires that its parameters satisfy + # the condition `fscale + floc <= min(data)`. However, to + # avoid numerical issues, we require that `fscale + floc` + # is strictly less than `min(data)`. If this condition + # is not satisfied, reduce the scale with `np.nextafter` to + # ensure that data does not fall outside of the support. + if not (scale + loc) < np.min(data): + scale = np.min(data) - loc + scale = np.nextafter(scale, 0) + return shape, loc, scale + else: + return super().fit(data, **kwds) + elif floc is None: + loc = np.min(data) - fscale + else: + loc = floc + # Source: Evans, Hastings, and Peacock (2000), Statistical + # Distributions, 3rd. Ed., John Wiley and Sons. Page 149. + scale = fscale or np.min(data) - loc + shape = fshape or get_shape(scale, loc) + return shape, loc, scale + + +pareto = pareto_gen(a=1.0, name="pareto") + + +class lomax_gen(rv_continuous): + r"""A Lomax (Pareto of the second kind) continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `lomax` is: + + .. math:: + + f(x, c) = \frac{c}{(1+x)^{c+1}} + + for :math:`x \ge 0`, :math:`c > 0`. + + `lomax` takes ``c`` as a shape parameter for :math:`c`. + + `lomax` is a special case of `pareto` with ``loc=-1.0``. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # lomax.pdf(x, c) = c / (1+x)**(c+1) + return c*1.0/(1.0+x)**(c+1.0) + + def _logpdf(self, x, c): + return np.log(c) - (c+1)*sc.log1p(x) + + def _cdf(self, x, c): + return -sc.expm1(-c*sc.log1p(x)) + + def _sf(self, x, c): + return np.exp(-c*sc.log1p(x)) + + def _logsf(self, x, c): + return -c*sc.log1p(x) + + def _ppf(self, q, c): + return sc.expm1(-sc.log1p(-q)/c) + + def _isf(self, q, c): + return q**(-1.0 / c) - 1 + + def _stats(self, c): + mu, mu2, g1, g2 = pareto.stats(c, loc=-1.0, moments='mvsk') + return mu, mu2, g1, g2 + + def _entropy(self, c): + return 1+1.0/c-np.log(c) + + +lomax = lomax_gen(a=0.0, name="lomax") + + +class pearson3_gen(rv_continuous): + r"""A pearson type III continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `pearson3` is: + + .. math:: + + f(x, \kappa) = \frac{|\beta|}{\Gamma(\alpha)} + (\beta (x - \zeta))^{\alpha - 1} + \exp(-\beta (x - \zeta)) + + where: + + .. math:: + + \beta = \frac{2}{\kappa} + + \alpha = \beta^2 = \frac{4}{\kappa^2} + + \zeta = -\frac{\alpha}{\beta} = -\beta + + :math:`\Gamma` is the gamma function (`scipy.special.gamma`). + Pass the skew :math:`\kappa` into `pearson3` as the shape parameter + ``skew``. + + %(after_notes)s + + %(example)s + + References + ---------- + R.W. Vogel and D.E. McMartin, "Probability Plot Goodness-of-Fit and + Skewness Estimation Procedures for the Pearson Type 3 Distribution", Water + Resources Research, Vol.27, 3149-3158 (1991). + + L.R. Salvosa, "Tables of Pearson's Type III Function", Ann. Math. Statist., + Vol.1, 191-198 (1930). + + "Using Modern Computing Tools to Fit the Pearson Type III Distribution to + Aviation Loads Data", Office of Aviation Research (2003). + + """ + def _preprocess(self, x, skew): + # The real 'loc' and 'scale' are handled in the calling pdf(...). The + # local variables 'loc' and 'scale' within pearson3._pdf are set to + # the defaults just to keep them as part of the equations for + # documentation. + loc = 0.0 + scale = 1.0 + + # If skew is small, return _norm_pdf. The divide between pearson3 + # and norm was found by brute force and is approximately a skew of + # 0.000016. No one, I hope, would actually use a skew value even + # close to this small. + norm2pearson_transition = 0.000016 + + ans, x, skew = np.broadcast_arrays(1.0, x, skew) + ans = ans.copy() + + # mask is True where skew is small enough to use the normal approx. + mask = np.absolute(skew) < norm2pearson_transition + invmask = ~mask + + beta = 2.0 / (skew[invmask] * scale) + alpha = (scale * beta)**2 + zeta = loc - alpha / beta + + transx = beta * (x[invmask] - zeta) + return ans, x, transx, mask, invmask, beta, alpha, zeta + + def _argcheck(self, skew): + # The _argcheck function in rv_continuous only allows positive + # arguments. The skew argument for pearson3 can be zero (which I want + # to handle inside pearson3._pdf) or negative. So just return True + # for all skew args. + return np.isfinite(skew) + + def _shape_info(self): + return [_ShapeInfo("skew", False, (-np.inf, np.inf), (False, False))] + + def _stats(self, skew): + m = 0.0 + v = 1.0 + s = skew + k = 1.5*skew**2 + return m, v, s, k + + def _pdf(self, x, skew): + # pearson3.pdf(x, skew) = abs(beta) / gamma(alpha) * + # (beta * (x - zeta))**(alpha - 1) * exp(-beta*(x - zeta)) + # Do the calculation in _logpdf since helps to limit + # overflow/underflow problems + ans = np.exp(self._logpdf(x, skew)) + if ans.ndim == 0: + if np.isnan(ans): + return 0.0 + return ans + ans[np.isnan(ans)] = 0.0 + return ans + + def _logpdf(self, x, skew): + # PEARSON3 logpdf GAMMA logpdf + # np.log(abs(beta)) + # + (alpha - 1)*np.log(beta*(x - zeta)) + (a - 1)*np.log(x) + # - beta*(x - zeta) - x + # - sc.gammalnalpha) - sc.gammalna) + ans, x, transx, mask, invmask, beta, alpha, _ = ( + self._preprocess(x, skew)) + + ans[mask] = np.log(_norm_pdf(x[mask])) + # use logpdf instead of _logpdf to fix issue mentioned in gh-12640 + # (_logpdf does not return correct result for alpha = 1) + ans[invmask] = np.log(abs(beta)) + gamma.logpdf(transx, alpha) + return ans + + def _cdf(self, x, skew): + ans, x, transx, mask, invmask, _, alpha, _ = ( + self._preprocess(x, skew)) + + ans[mask] = _norm_cdf(x[mask]) + + skew = np.broadcast_to(skew, invmask.shape) + invmask1a = np.logical_and(invmask, skew > 0) + invmask1b = skew[invmask] > 0 + # use cdf instead of _cdf to fix issue mentioned in gh-12640 + # (_cdf produces NaNs for inputs outside support) + ans[invmask1a] = gamma.cdf(transx[invmask1b], alpha[invmask1b]) + + # The gamma._cdf approach wasn't working with negative skew. + # Note that multiplying the skew by -1 reflects about x=0. + # So instead of evaluating the CDF with negative skew at x, + # evaluate the SF with positive skew at -x. + invmask2a = np.logical_and(invmask, skew < 0) + invmask2b = skew[invmask] < 0 + # gamma._sf produces NaNs when transx < 0, so use gamma.sf + ans[invmask2a] = gamma.sf(transx[invmask2b], alpha[invmask2b]) + + return ans + + def _sf(self, x, skew): + ans, x, transx, mask, invmask, _, alpha, _ = ( + self._preprocess(x, skew)) + + ans[mask] = _norm_sf(x[mask]) + + skew = np.broadcast_to(skew, invmask.shape) + invmask1a = np.logical_and(invmask, skew > 0) + invmask1b = skew[invmask] > 0 + ans[invmask1a] = gamma.sf(transx[invmask1b], alpha[invmask1b]) + + invmask2a = np.logical_and(invmask, skew < 0) + invmask2b = skew[invmask] < 0 + ans[invmask2a] = gamma.cdf(transx[invmask2b], alpha[invmask2b]) + + return ans + + def _rvs(self, skew, size=None, random_state=None): + skew = np.broadcast_to(skew, size) + ans, _, _, mask, invmask, beta, alpha, zeta = ( + self._preprocess([0], skew)) + + nsmall = mask.sum() + nbig = mask.size - nsmall + ans[mask] = random_state.standard_normal(nsmall) + ans[invmask] = random_state.standard_gamma(alpha, nbig)/beta + zeta + + if size == (): + ans = ans[0] + return ans + + def _ppf(self, q, skew): + ans, q, _, mask, invmask, beta, alpha, zeta = ( + self._preprocess(q, skew)) + ans[mask] = _norm_ppf(q[mask]) + q = q[invmask] + q[beta < 0] = 1 - q[beta < 0] # for negative skew; see gh-17050 + ans[invmask] = sc.gammaincinv(alpha, q)/beta + zeta + return ans + + @_call_super_mom + @extend_notes_in_docstring(rv_continuous, notes="""\ + Note that method of moments (`method='MM'`) is not + available for this distribution.\n\n""") + def fit(self, data, *args, **kwds): + if kwds.get("method", None) == 'MM': + raise NotImplementedError("Fit `method='MM'` is not available for " + "the Pearson3 distribution. Please try " + "the default `method='MLE'`.") + else: + return super(type(self), self).fit(data, *args, **kwds) + + +pearson3 = pearson3_gen(name="pearson3") + + +class powerlaw_gen(rv_continuous): + r"""A power-function continuous random variable. + + %(before_notes)s + + See Also + -------- + pareto + + Notes + ----- + The probability density function for `powerlaw` is: + + .. math:: + + f(x, a) = a x^{a-1} + + for :math:`0 \le x \le 1`, :math:`a > 0`. + + `powerlaw` takes ``a`` as a shape parameter for :math:`a`. + + %(after_notes)s + + For example, the support of `powerlaw` can be adjusted from the default + interval ``[0, 1]`` to the interval ``[c, c+d]`` by setting ``loc=c`` and + ``scale=d``. For a power-law distribution with infinite support, see + `pareto`. + + `powerlaw` is a special case of `beta` with ``b=1``. + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (False, False))] + + def _pdf(self, x, a): + # powerlaw.pdf(x, a) = a * x**(a-1) + return a*x**(a-1.0) + + def _logpdf(self, x, a): + return np.log(a) + sc.xlogy(a - 1, x) + + def _cdf(self, x, a): + return x**(a*1.0) + + def _logcdf(self, x, a): + return a*np.log(x) + + def _ppf(self, q, a): + return pow(q, 1.0/a) + + def _sf(self, p, a): + return -sc.powm1(p, a) + + def _munp(self, n, a): + # The following expression is correct for all real n (provided a > 0). + return a / (a + n) + + def _stats(self, a): + return (a / (a + 1.0), + a / (a + 2.0) / (a + 1.0) ** 2, + -2.0 * ((a - 1.0) / (a + 3.0)) * np.sqrt((a + 2.0) / a), + 6 * np.polyval([1, -1, -6, 2], a) / (a * (a + 3.0) * (a + 4))) + + def _entropy(self, a): + return 1 - 1.0/a - np.log(a) + + def _support_mask(self, x, a): + return (super()._support_mask(x, a) + & ((x != 0) | (a >= 1))) + + @_call_super_mom + @extend_notes_in_docstring(rv_continuous, notes="""\ + Notes specifically for ``powerlaw.fit``: If the location is a free + parameter and the value returned for the shape parameter is less than + one, the true maximum likelihood approaches infinity. This causes + numerical difficulties, and the resulting estimates are approximate. + \n\n""") + def fit(self, data, *args, **kwds): + # Summary of the strategy: + # + # 1) If the scale and location are fixed, return the shape according + # to a formula. + # + # 2) If the scale is fixed, there are two possibilities for the other + # parameters - one corresponding with shape less than one, and + # another with shape greater than one. Calculate both, and return + # whichever has the better log-likelihood. + # + # At this point, the scale is known to be free. + # + # 3) If the location is fixed, return the scale and shape according to + # formulas (or, if the shape is fixed, the fixed shape). + # + # At this point, the location and scale are both free. There are + # separate equations depending on whether the shape is less than one or + # greater than one. + # + # 4a) If the shape is less than one, there are formulas for shape, + # location, and scale. + # 4b) If the shape is greater than one, there are formulas for shape + # and scale, but there is a condition for location to be solved + # numerically. + # + # If the shape is fixed and less than one, we use 4a. + # If the shape is fixed and greater than one, we use 4b. + # If the shape is also free, we calculate fits using both 4a and 4b + # and choose the one that results a better log-likelihood. + # + # In many cases, the use of `np.nextafter` is used to avoid numerical + # issues. + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + if len(np.unique(data)) == 1: + return super().fit(data, *args, **kwds) + + data, fshape, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + penalized_nllf_args = [data, (self._fitstart(data),)] + penalized_nllf = self._reduce_func(penalized_nllf_args, {})[1] + + # ensure that any fixed parameters don't violate constraints of the + # distribution before continuing. The support of the distribution + # is `0 < (x - loc)/scale < 1`. + if floc is not None: + if not data.min() > floc: + raise FitDataError('powerlaw', 0, 1) + if fscale is not None and not data.max() <= floc + fscale: + raise FitDataError('powerlaw', 0, 1) + + if fscale is not None: + if fscale <= 0: + raise ValueError("Negative or zero `fscale` is outside the " + "range allowed by the distribution.") + if fscale <= np.ptp(data): + msg = "`fscale` must be greater than the range of data." + raise ValueError(msg) + + def get_shape(data, loc, scale): + # The first-order necessary condition on `shape` can be solved in + # closed form. It can be used no matter the assumption of the + # value of the shape. + N = len(data) + return - N / (np.sum(np.log(data - loc)) - N*np.log(scale)) + + def get_scale(data, loc): + # analytical solution for `scale` based on the location. + # It can be used no matter the assumption of the value of the + # shape. + return data.max() - loc + + # 1) The location and scale are both fixed. Analytically determine the + # shape. + if fscale is not None and floc is not None: + return get_shape(data, floc, fscale), floc, fscale + + # 2) The scale is fixed. There are two possibilities for the other + # parameters. Choose the option with better log-likelihood. + if fscale is not None: + # using `data.min()` as the optimal location + loc_lt1 = np.nextafter(data.min(), -np.inf) + shape_lt1 = fshape or get_shape(data, loc_lt1, fscale) + ll_lt1 = penalized_nllf((shape_lt1, loc_lt1, fscale), data) + + # using `data.max() - scale` as the optimal location + loc_gt1 = np.nextafter(data.max() - fscale, np.inf) + shape_gt1 = fshape or get_shape(data, loc_gt1, fscale) + ll_gt1 = penalized_nllf((shape_gt1, loc_gt1, fscale), data) + + if ll_lt1 < ll_gt1: + return shape_lt1, loc_lt1, fscale + else: + return shape_gt1, loc_gt1, fscale + + # 3) The location is fixed. Return the analytical scale and the + # analytical (or fixed) shape. + if floc is not None: + scale = get_scale(data, floc) + shape = fshape or get_shape(data, floc, scale) + return shape, floc, scale + + # 4) Location and scale are both free + # 4a) Use formulas that assume `shape <= 1`. + + def fit_loc_scale_w_shape_lt_1(): + loc = np.nextafter(data.min(), -np.inf) + if np.abs(loc) < np.finfo(loc.dtype).tiny: + loc = np.sign(loc) * np.finfo(loc.dtype).tiny + scale = np.nextafter(get_scale(data, loc), np.inf) + shape = fshape or get_shape(data, loc, scale) + return shape, loc, scale + + # 4b) Fit under the assumption that `shape > 1`. The support + # of the distribution is `(x - loc)/scale <= 1`. The method of Lagrange + # multipliers turns this constraint into the condition that + # dL_dScale - dL_dLocation must be zero, which is solved numerically. + # (Alternatively, substitute the constraint into the objective + # function before deriving the likelihood equation for location.) + + def dL_dScale(data, shape, scale): + # The partial derivative of the log-likelihood function w.r.t. + # the scale. + return -data.shape[0] * shape / scale + + def dL_dLocation(data, shape, loc): + # The partial derivative of the log-likelihood function w.r.t. + # the location. + return (shape - 1) * np.sum(1 / (loc - data)) # -1/(data-loc) + + def dL_dLocation_star(loc): + # The derivative of the log-likelihood function w.r.t. + # the location, given optimal shape and scale + scale = np.nextafter(get_scale(data, loc), -np.inf) + shape = fshape or get_shape(data, loc, scale) + return dL_dLocation(data, shape, loc) + + def fun_to_solve(loc): + # optimize the location by setting the partial derivatives + # w.r.t. to location and scale equal and solving. + scale = np.nextafter(get_scale(data, loc), -np.inf) + shape = fshape or get_shape(data, loc, scale) + return (dL_dScale(data, shape, scale) + - dL_dLocation(data, shape, loc)) + + def fit_loc_scale_w_shape_gt_1(): + # set brackets for `root_scalar` to use when optimizing over the + # location such that a root is likely between them. + rbrack = np.nextafter(data.min(), -np.inf) + + # if the sign of `dL_dLocation_star` is positive at rbrack, + # we're not going to find the root we're looking for + delta = (data.min() - rbrack) + while dL_dLocation_star(rbrack) > 0: + rbrack = data.min() - delta + delta *= 2 + + def interval_contains_root(lbrack, rbrack): + # Check if the interval (lbrack, rbrack) contains the root. + return (np.sign(fun_to_solve(lbrack)) + != np.sign(fun_to_solve(rbrack))) + + lbrack = rbrack - 1 + + # if the sign doesn't change between the brackets, move the left + # bracket until it does. (The right bracket remains fixed at the + # maximum permissible value.) + i = 1.0 + while (not interval_contains_root(lbrack, rbrack) + and lbrack != -np.inf): + lbrack = (data.min() - i) + i *= 2 + + root = optimize.root_scalar(fun_to_solve, bracket=(lbrack, rbrack)) + + loc = np.nextafter(root.root, -np.inf) + scale = np.nextafter(get_scale(data, loc), np.inf) + shape = fshape or get_shape(data, loc, scale) + return shape, loc, scale + + # Shape is fixed - choose 4a or 4b accordingly. + if fshape is not None and fshape <= 1: + return fit_loc_scale_w_shape_lt_1() + elif fshape is not None and fshape > 1: + return fit_loc_scale_w_shape_gt_1() + + # Shape is free + fit_shape_lt1 = fit_loc_scale_w_shape_lt_1() + ll_lt1 = self.nnlf(fit_shape_lt1, data) + + fit_shape_gt1 = fit_loc_scale_w_shape_gt_1() + ll_gt1 = self.nnlf(fit_shape_gt1, data) + + if ll_lt1 <= ll_gt1 and fit_shape_lt1[0] <= 1: + return fit_shape_lt1 + elif ll_lt1 > ll_gt1 and fit_shape_gt1[0] > 1: + return fit_shape_gt1 + else: + return super().fit(data, *args, **kwds) + + +powerlaw = powerlaw_gen(a=0.0, b=1.0, name="powerlaw") + + +class powerlognorm_gen(rv_continuous): + r"""A power log-normal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `powerlognorm` is: + + .. math:: + + f(x, c, s) = \frac{c}{x s} \phi(\log(x)/s) + (\Phi(-\log(x)/s))^{c-1} + + where :math:`\phi` is the normal pdf, and :math:`\Phi` is the normal cdf, + and :math:`x > 0`, :math:`s, c > 0`. + + `powerlognorm` takes :math:`c` and :math:`s` as shape parameters. + + %(after_notes)s + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + ic = _ShapeInfo("c", False, (0, np.inf), (False, False)) + i_s = _ShapeInfo("s", False, (0, np.inf), (False, False)) + return [ic, i_s] + + def _pdf(self, x, c, s): + return np.exp(self._logpdf(x, c, s)) + + def _logpdf(self, x, c, s): + return (np.log(c) - np.log(x) - np.log(s) + + _norm_logpdf(np.log(x) / s) + + _norm_logcdf(-np.log(x) / s) * (c - 1.)) + + def _cdf(self, x, c, s): + return -sc.expm1(self._logsf(x, c, s)) + + def _ppf(self, q, c, s): + return self._isf(1 - q, c, s) + + def _sf(self, x, c, s): + return np.exp(self._logsf(x, c, s)) + + def _logsf(self, x, c, s): + return _norm_logcdf(-np.log(x) / s) * c + + def _isf(self, q, c, s): + return np.exp(-_norm_ppf(q**(1/c)) * s) + + +powerlognorm = powerlognorm_gen(a=0.0, name="powerlognorm") + + +class powernorm_gen(rv_continuous): + r"""A power normal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `powernorm` is: + + .. math:: + + f(x, c) = c \phi(x) (\Phi(-x))^{c-1} + + where :math:`\phi` is the normal pdf, :math:`\Phi` is the normal cdf, + :math:`x` is any real, and :math:`c > 0` [1]_. + + `powernorm` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + References + ---------- + .. [1] NIST Engineering Statistics Handbook, Section 1.3.6.6.13, + https://www.itl.nist.gov/div898/handbook//eda/section3/eda366d.htm + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + def _pdf(self, x, c): + # powernorm.pdf(x, c) = c * phi(x) * (Phi(-x))**(c-1) + return c*_norm_pdf(x) * (_norm_cdf(-x)**(c-1.0)) + + def _logpdf(self, x, c): + return np.log(c) + _norm_logpdf(x) + (c-1)*_norm_logcdf(-x) + + def _cdf(self, x, c): + return -sc.expm1(self._logsf(x, c)) + + def _ppf(self, q, c): + return -_norm_ppf(pow(1.0 - q, 1.0 / c)) + + def _sf(self, x, c): + return np.exp(self._logsf(x, c)) + + def _logsf(self, x, c): + return c * _norm_logcdf(-x) + + def _isf(self, q, c): + return -_norm_ppf(np.exp(np.log(q) / c)) + + +powernorm = powernorm_gen(name='powernorm') + + +class rdist_gen(rv_continuous): + r"""An R-distributed (symmetric beta) continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `rdist` is: + + .. math:: + + f(x, c) = \frac{(1-x^2)^{c/2-1}}{B(1/2, c/2)} + + for :math:`-1 \le x \le 1`, :math:`c > 0`. `rdist` is also called the + symmetric beta distribution: if B has a `beta` distribution with + parameters (c/2, c/2), then X = 2*B - 1 follows a R-distribution with + parameter c. + + `rdist` takes ``c`` as a shape parameter for :math:`c`. + + This distribution includes the following distribution kernels as + special cases:: + + c = 2: uniform + c = 3: `semicircular` + c = 4: Epanechnikov (parabolic) + c = 6: quartic (biweight) + c = 8: triweight + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("c", False, (0, np.inf), (False, False))] + + # use relation to the beta distribution for pdf, cdf, etc + def _pdf(self, x, c): + return np.exp(self._logpdf(x, c)) + + def _logpdf(self, x, c): + return -np.log(2) + beta._logpdf((x + 1)/2, c/2, c/2) + + def _cdf(self, x, c): + return beta._cdf((x + 1)/2, c/2, c/2) + + def _sf(self, x, c): + return beta._sf((x + 1)/2, c/2, c/2) + + def _ppf(self, q, c): + return 2*beta._ppf(q, c/2, c/2) - 1 + + def _rvs(self, c, size=None, random_state=None): + return 2 * random_state.beta(c/2, c/2, size) - 1 + + def _munp(self, n, c): + numerator = (1 - (n % 2)) * sc.beta((n + 1.0) / 2, c / 2.0) + return numerator / sc.beta(1. / 2, c / 2.) + + +rdist = rdist_gen(a=-1.0, b=1.0, name="rdist") + + +class rayleigh_gen(rv_continuous): + r"""A Rayleigh continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `rayleigh` is: + + .. math:: + + f(x) = x \exp(-x^2/2) + + for :math:`x \ge 0`. + + `rayleigh` is a special case of `chi` with ``df=2``. + + %(after_notes)s + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return chi.rvs(2, size=size, random_state=random_state) + + def _pdf(self, r): + # rayleigh.pdf(r) = r * exp(-r**2/2) + return np.exp(self._logpdf(r)) + + def _logpdf(self, r): + return np.log(r) - 0.5 * r * r + + def _cdf(self, r): + return -sc.expm1(-0.5 * r**2) + + def _ppf(self, q): + return np.sqrt(-2 * sc.log1p(-q)) + + def _sf(self, r): + return np.exp(self._logsf(r)) + + def _logsf(self, r): + return -0.5 * r * r + + def _isf(self, q): + return np.sqrt(-2 * np.log(q)) + + def _stats(self): + val = 4 - np.pi + return (np.sqrt(np.pi/2), + val/2, + 2*(np.pi-3)*np.sqrt(np.pi)/val**1.5, + 6*np.pi/val-16/val**2) + + def _entropy(self): + return _EULER/2.0 + 1 - 0.5*np.log(2) + + @_call_super_mom + @extend_notes_in_docstring(rv_continuous, notes="""\ + Notes specifically for ``rayleigh.fit``: If the location is fixed with + the `floc` parameter, this method uses an analytical formula to find + the scale. Otherwise, this function uses a numerical root finder on + the first order conditions of the log-likelihood function to find the + MLE. Only the (optional) `loc` parameter is used as the initial guess + for the root finder; the `scale` parameter and any other parameters + for the optimizer are ignored.\n\n""") + def fit(self, data, *args, **kwds): + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + data, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + + def scale_mle(loc): + # Source: Statistical Distributions, 3rd Edition. Evans, Hastings, + # and Peacock (2000), Page 175 + return (np.sum((data - loc) ** 2) / (2 * len(data))) ** .5 + + def loc_mle(loc): + # This implicit equation for `loc` is used when + # both `loc` and `scale` are free. + xm = data - loc + s1 = xm.sum() + s2 = (xm**2).sum() + s3 = (1/xm).sum() + return s1 - s2/(2*len(data))*s3 + + def loc_mle_scale_fixed(loc, scale=fscale): + # This implicit equation for `loc` is used when + # `scale` is fixed but `loc` is not. + xm = data - loc + return xm.sum() - scale**2 * (1/xm).sum() + + if floc is not None: + # `loc` is fixed, analytically determine `scale`. + if np.any(data - floc <= 0): + raise FitDataError("rayleigh", lower=1, upper=np.inf) + else: + return floc, scale_mle(floc) + + # Account for user provided guess of `loc`. + loc0 = kwds.get('loc') + if loc0 is None: + # Use _fitstart to estimate loc; ignore the returned scale. + loc0 = self._fitstart(data)[0] + + fun = loc_mle if fscale is None else loc_mle_scale_fixed + rbrack = np.nextafter(np.min(data), -np.inf) + lbrack = _get_left_bracket(fun, rbrack) + res = optimize.root_scalar(fun, bracket=(lbrack, rbrack)) + if not res.converged: + raise FitSolverError(res.flag) + loc = res.root + scale = fscale or scale_mle(loc) + return loc, scale + + +rayleigh = rayleigh_gen(a=0.0, name="rayleigh") + + +class reciprocal_gen(rv_continuous): + r"""A loguniform or reciprocal continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for this class is: + + .. math:: + + f(x, a, b) = \frac{1}{x \log(b/a)} + + for :math:`a \le x \le b`, :math:`b > a > 0`. This class takes + :math:`a` and :math:`b` as shape parameters. + + %(after_notes)s + + %(example)s + + This doesn't show the equal probability of ``0.01``, ``0.1`` and + ``1``. This is best when the x-axis is log-scaled: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + >>> ax.hist(np.log10(r)) + >>> ax.set_ylabel("Frequency") + >>> ax.set_xlabel("Value of random variable") + >>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0])) + >>> ticks = ["$10^{{ {} }}$".format(i) for i in [-2, -1, 0]] + >>> ax.set_xticklabels(ticks) # doctest: +SKIP + >>> plt.show() + + This random variable will be log-uniform regardless of the base chosen for + ``a`` and ``b``. Let's specify with base ``2`` instead: + + >>> rvs = %(name)s(2**-2, 2**0).rvs(size=1000) + + Values of ``1/4``, ``1/2`` and ``1`` are equally likely with this random + variable. Here's the histogram: + + >>> fig, ax = plt.subplots(1, 1) + >>> ax.hist(np.log2(rvs)) + >>> ax.set_ylabel("Frequency") + >>> ax.set_xlabel("Value of random variable") + >>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0])) + >>> ticks = ["$2^{{ {} }}$".format(i) for i in [-2, -1, 0]] + >>> ax.set_xticklabels(ticks) # doctest: +SKIP + >>> plt.show() + + """ + def _argcheck(self, a, b): + return (a > 0) & (b > a) + + def _shape_info(self): + ia = _ShapeInfo("a", False, (0, np.inf), (False, False)) + ib = _ShapeInfo("b", False, (0, np.inf), (False, False)) + return [ia, ib] + + def _fitstart(self, data): + if isinstance(data, CensoredData): + data = data._uncensor() + # Reasonable, since support is [a, b] + return super()._fitstart(data, args=(np.min(data), np.max(data))) + + def _get_support(self, a, b): + return a, b + + def _pdf(self, x, a, b): + # reciprocal.pdf(x, a, b) = 1 / (x*(log(b) - log(a))) + return np.exp(self._logpdf(x, a, b)) + + def _logpdf(self, x, a, b): + return -np.log(x) - np.log(np.log(b) - np.log(a)) + + def _cdf(self, x, a, b): + return (np.log(x)-np.log(a)) / (np.log(b) - np.log(a)) + + def _ppf(self, q, a, b): + return np.exp(np.log(a) + q*(np.log(b) - np.log(a))) + + def _munp(self, n, a, b): + if n == 0: + return 1.0 + t1 = 1 / (np.log(b) - np.log(a)) / n + t2 = np.real(np.exp(_log_diff(n * np.log(b), n*np.log(a)))) + return t1 * t2 + + def _entropy(self, a, b): + return 0.5*(np.log(a) + np.log(b)) + np.log(np.log(b) - np.log(a)) + + fit_note = """\ + `loguniform`/`reciprocal` is over-parameterized. `fit` automatically + fixes `scale` to 1 unless `fscale` is provided by the user.\n\n""" + + @extend_notes_in_docstring(rv_continuous, notes=fit_note) + def fit(self, data, *args, **kwds): + fscale = kwds.pop('fscale', 1) + return super().fit(data, *args, fscale=fscale, **kwds) + + # Details related to the decision of not defining + # the survival function for this distribution can be + # found in the PR: https://github.com/scipy/scipy/pull/18614 + + +loguniform = reciprocal_gen(name="loguniform") +reciprocal = reciprocal_gen(name="reciprocal") +loguniform._support = ('a', 'b') +reciprocal._support = ('a', 'b') + + +class rice_gen(rv_continuous): + r"""A Rice continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `rice` is: + + .. math:: + + f(x, b) = x \exp(- \frac{x^2 + b^2}{2}) I_0(x b) + + for :math:`x >= 0`, :math:`b > 0`. :math:`I_0` is the modified Bessel + function of order zero (`scipy.special.i0`). + + `rice` takes ``b`` as a shape parameter for :math:`b`. + + %(after_notes)s + + The Rice distribution describes the length, :math:`r`, of a 2-D vector with + components :math:`(U+u, V+v)`, where :math:`U, V` are constant, :math:`u, + v` are independent Gaussian random variables with standard deviation + :math:`s`. Let :math:`R = \sqrt{U^2 + V^2}`. Then the pdf of :math:`r` is + ``rice.pdf(x, R/s, scale=s)``. + + %(example)s + + """ + def _argcheck(self, b): + return b >= 0 + + def _shape_info(self): + return [_ShapeInfo("b", False, (0, np.inf), (True, False))] + + def _rvs(self, b, size=None, random_state=None): + # https://en.wikipedia.org/wiki/Rice_distribution + t = b/np.sqrt(2) + random_state.standard_normal(size=(2,) + size) + return np.sqrt((t*t).sum(axis=0)) + + def _cdf(self, x, b): + return sc.chndtr(np.square(x), 2, np.square(b)) + + def _ppf(self, q, b): + return np.sqrt(sc.chndtrix(q, 2, np.square(b))) + + def _pdf(self, x, b): + # rice.pdf(x, b) = x * exp(-(x**2+b**2)/2) * I[0](x*b) + # + # We use (x**2 + b**2)/2 = ((x-b)**2)/2 + xb. + # The factor of np.exp(-xb) is then included in the i0e function + # in place of the modified Bessel function, i0, improving + # numerical stability for large values of xb. + return x * np.exp(-(x-b)*(x-b)/2.0) * sc.i0e(x*b) + + def _munp(self, n, b): + nd2 = n/2.0 + n1 = 1 + nd2 + b2 = b*b/2.0 + return (2.0**(nd2) * np.exp(-b2) * sc.gamma(n1) * + sc.hyp1f1(n1, 1, b2)) + + +rice = rice_gen(a=0.0, name="rice") + +class irwinhall_gen(rv_continuous): + r"""An Irwin-Hall (Uniform Sum) continuous random variable. + + An `Irwin-Hall `_ + continuous random variable is the sum of :math:`n` independent + standard uniform random variables [1]_ [2]_. + + %(before_notes)s + + Notes + ----- + Applications include `Rao's Spacing Test + `_, + a more powerful alternative to the Rayleigh test + when the data are not unimodal, and radar [3]_. + + Conveniently, the pdf and cdf are the :math:`n`-fold convolution of + the ones for the standard uniform distribution, which is also the + definition of the cardinal B-splines of degree :math:`n-1` + having knots evenly spaced from :math:`1` to :math:`n` [4]_ [5]_. + + The Bates distribution, which represents the *mean* of statistically + independent, uniformly distributed random variables, is simply the + Irwin-Hall distribution scaled by :math:`1/n`. For example, the frozen + distribution ``bates = irwinhall(10, scale=1/10)`` represents the + distribution of the mean of 10 uniformly distributed random variables. + + %(after_notes)s + + References + ---------- + .. [1] P. Hall, "The distribution of means for samples of size N drawn + from a population in which the variate takes values between 0 and 1, + all such values being equally probable", + Biometrika, Volume 19, Issue 3-4, December 1927, Pages 240-244, + :doi:`10.1093/biomet/19.3-4.240`. + .. [2] J. O. Irwin, "On the frequency distribution of the means of samples + from a population having any law of frequency with finite moments, + with special reference to Pearson's Type II, + Biometrika, Volume 19, Issue 3-4, December 1927, Pages 225-239, + :doi:`0.1093/biomet/19.3-4.225`. + .. [3] K. Buchanan, T. Adeyemi, C. Flores-Molina, S. Wheeland and D. Overturf, + "Sidelobe behavior and bandwidth characteristics + of distributed antenna arrays," + 2018 United States National Committee of + URSI National Radio Science Meeting (USNC-URSI NRSM), + Boulder, CO, USA, 2018, pp. 1-2. + https://www.usnc-ursi-archive.org/nrsm/2018/papers/B15-9.pdf. + .. [4] Amos Ron, "Lecture 1: Cardinal B-splines and convolution operators", p. 1 + https://pages.cs.wisc.edu/~deboor/887/lec1new.pdf. + .. [5] Trefethen, N. (2012, July). B-splines and convolution. Chebfun. + Retrieved April 30, 2024, from http://www.chebfun.org/examples/approx/BSplineConv.html. + + %(example)s + """ # noqa: E501 + + @replace_notes_in_docstring(rv_continuous, notes="""\ + Raises a ``NotImplementedError`` for the Irwin-Hall distribution because + the generic `fit` implementation is unreliable and no custom implementation + is available. Consider using `scipy.stats.fit`.\n\n""") + def fit(self, data, *args, **kwds): + fit_notes = ("The generic `fit` implementation is unreliable for this " + "distribution, and no custom implementation is available. " + "Consider using `scipy.stats.fit`.") + raise NotImplementedError(fit_notes) + + def _argcheck(self, n): + return (n > 0) & _isintegral(n) & np.isrealobj(n) + + def _get_support(self, n): + return 0, n + + def _shape_info(self): + return [_ShapeInfo("n", True, (1, np.inf), (True, False))] + + def _munp(self, order, n): + # see https://link.springer.com/content/pdf/10.1007/s10959-020-01050-9.pdf + # page 640, with m=n, j=n+order + def vmunp(order, n): + n = np.asarray(n, dtype=np.int64) + return (sc.stirling2(n+order, n, exact=True) + / sc.comb(n+order, n, exact=True)) + + # exact rationals, but we convert to float anyway + return np.vectorize(vmunp, otypes=[np.float64])(order, n) + + @staticmethod + def _cardbspl(n): + t = np.arange(n+1) + return BSpline.basis_element(t) + + def _pdf(self, x, n): + def vpdf(x, n): + return self._cardbspl(n)(x) + return np.vectorize(vpdf, otypes=[np.float64])(x, n) + + def _cdf(self, x, n): + def vcdf(x, n): + return self._cardbspl(n).antiderivative()(x) + return np.vectorize(vcdf, otypes=[np.float64])(x, n) + + def _sf(self, x, n): + def vsf(x, n): + return self._cardbspl(n).antiderivative()(n-x) + return np.vectorize(vsf, otypes=[np.float64])(x, n) + + def _rvs(self, n, size=None, random_state=None, *args): + @_vectorize_rvs_over_shapes + def _rvs1(n, size=None, random_state=None): + n = np.floor(n).astype(int) + usize = (n,) if size is None else (n, *size) + return random_state.uniform(size=usize).sum(axis=0) + return _rvs1(n, size=size, random_state=random_state) + + def _stats(self, n): + # mgf = ((exp(t) - 1)/t)**n + # m'th derivative follows from the generalized Leibniz rule + # Moments follow directly from the definition as the sum of n iid unif(0,1) + # and the summation rules for moments of a sum of iid random variables + # E(IH((n))) = n*E(U(0,1)) = n/2 + # Var(IH((n))) = n*Var(U(0,1)) = n/12 + # Skew(IH((n))) = Skew(U(0,1))/sqrt(n) = 0 + # Kurt(IH((n))) = Kurt(U(0,1))/n = -6/(5*n) -- Fisher's excess kurtosis + # See e.g. https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution + + return n/2, n/12, 0, -6/(5*n) + + +irwinhall = irwinhall_gen(name="irwinhall") +irwinhall._support = (0.0, 'n') + + +class recipinvgauss_gen(rv_continuous): + r"""A reciprocal inverse Gaussian continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `recipinvgauss` is: + + .. math:: + + f(x, \mu) = \frac{1}{\sqrt{2\pi x}} + \exp\left(\frac{-(1-\mu x)^2}{2\mu^2x}\right) + + for :math:`x \ge 0`. + + `recipinvgauss` takes ``mu`` as a shape parameter for :math:`\mu`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("mu", False, (0, np.inf), (False, False))] + + def _pdf(self, x, mu): + # recipinvgauss.pdf(x, mu) = + # 1/sqrt(2*pi*x) * exp(-(1-mu*x)**2/(2*x*mu**2)) + return np.exp(self._logpdf(x, mu)) + + def _logpdf(self, x, mu): + return _lazywhere(x > 0, (x, mu), + lambda x, mu: (-(1 - mu*x)**2.0 / (2*x*mu**2.0) + - 0.5*np.log(2*np.pi*x)), + fillvalue=-np.inf) + + def _cdf(self, x, mu): + trm1 = 1.0/mu - x + trm2 = 1.0/mu + x + isqx = 1.0/np.sqrt(x) + return _norm_cdf(-isqx*trm1) - np.exp(2.0/mu)*_norm_cdf(-isqx*trm2) + + def _sf(self, x, mu): + trm1 = 1.0/mu - x + trm2 = 1.0/mu + x + isqx = 1.0/np.sqrt(x) + return _norm_cdf(isqx*trm1) + np.exp(2.0/mu)*_norm_cdf(-isqx*trm2) + + def _rvs(self, mu, size=None, random_state=None): + return 1.0/random_state.wald(mu, 1.0, size=size) + + +recipinvgauss = recipinvgauss_gen(a=0.0, name='recipinvgauss') + + +class semicircular_gen(rv_continuous): + r"""A semicircular continuous random variable. + + %(before_notes)s + + See Also + -------- + rdist + + Notes + ----- + The probability density function for `semicircular` is: + + .. math:: + + f(x) = \frac{2}{\pi} \sqrt{1-x^2} + + for :math:`-1 \le x \le 1`. + + The distribution is a special case of `rdist` with ``c = 3``. + + %(after_notes)s + + References + ---------- + .. [1] "Wigner semicircle distribution", + https://en.wikipedia.org/wiki/Wigner_semicircle_distribution + + %(example)s + + """ + def _shape_info(self): + return [] + + def _pdf(self, x): + return 2.0/np.pi*np.sqrt(1-x*x) + + def _logpdf(self, x): + return np.log(2/np.pi) + 0.5*sc.log1p(-x*x) + + def _cdf(self, x): + return 0.5+1.0/np.pi*(x*np.sqrt(1-x*x) + np.arcsin(x)) + + def _ppf(self, q): + return rdist._ppf(q, 3) + + def _rvs(self, size=None, random_state=None): + # generate values uniformly distributed on the area under the pdf + # (semi-circle) by randomly generating the radius and angle + r = np.sqrt(random_state.uniform(size=size)) + a = np.cos(np.pi * random_state.uniform(size=size)) + return r * a + + def _stats(self): + return 0, 0.25, 0, -1.0 + + def _entropy(self): + return 0.64472988584940017414 + + +semicircular = semicircular_gen(a=-1.0, b=1.0, name="semicircular") + + +class skewcauchy_gen(rv_continuous): + r"""A skewed Cauchy random variable. + + %(before_notes)s + + See Also + -------- + cauchy : Cauchy distribution + + Notes + ----- + + The probability density function for `skewcauchy` is: + + .. math:: + + f(x) = \frac{1}{\pi \left(\frac{x^2}{\left(a\, \text{sign}(x) + 1 + \right)^2} + 1 \right)} + + for a real number :math:`x` and skewness parameter :math:`-1 < a < 1`. + + When :math:`a=0`, the distribution reduces to the usual Cauchy + distribution. + + %(after_notes)s + + References + ---------- + .. [1] "Skewed generalized *t* distribution", Wikipedia + https://en.wikipedia.org/wiki/Skewed_generalized_t_distribution#Skewed_Cauchy_distribution + + %(example)s + + """ + def _argcheck(self, a): + return np.abs(a) < 1 + + def _shape_info(self): + return [_ShapeInfo("a", False, (-1.0, 1.0), (False, False))] + + def _pdf(self, x, a): + return 1 / (np.pi * (x**2 / (a * np.sign(x) + 1)**2 + 1)) + + def _cdf(self, x, a): + return np.where(x <= 0, + (1 - a) / 2 + (1 - a) / np.pi * np.arctan(x / (1 - a)), + (1 - a) / 2 + (1 + a) / np.pi * np.arctan(x / (1 + a))) + + def _ppf(self, x, a): + i = x < self._cdf(0, a) + return np.where(i, + np.tan(np.pi / (1 - a) * (x - (1 - a) / 2)) * (1 - a), + np.tan(np.pi / (1 + a) * (x - (1 - a) / 2)) * (1 + a)) + + def _stats(self, a, moments='mvsk'): + return np.nan, np.nan, np.nan, np.nan + + def _fitstart(self, data): + # Use 0 as the initial guess of the skewness shape parameter. + # For the location and scale, estimate using the median and + # quartiles. + if isinstance(data, CensoredData): + data = data._uncensor() + p25, p50, p75 = np.percentile(data, [25, 50, 75]) + return 0.0, p50, (p75 - p25)/2 + + +skewcauchy = skewcauchy_gen(name='skewcauchy') + + +class skewnorm_gen(rv_continuous): + r"""A skew-normal random variable. + + %(before_notes)s + + Notes + ----- + The pdf is:: + + skewnorm.pdf(x, a) = 2 * norm.pdf(x) * norm.cdf(a*x) + + `skewnorm` takes a real number :math:`a` as a skewness parameter + When ``a = 0`` the distribution is identical to a normal distribution + (`norm`). `rvs` implements the method of [1]_. + + This distribution uses routines from the Boost Math C++ library for + the computation of ``cdf``, ``ppf`` and ``isf`` methods. [2]_ + + %(after_notes)s + + References + ---------- + .. [1] A. Azzalini and A. Capitanio (1999). Statistical applications of + the multivariate skew-normal distribution. J. Roy. Statist. Soc., + B 61, 579-602. :arxiv:`0911.2093` + .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + """ + def _argcheck(self, a): + return np.isfinite(a) + + def _shape_info(self): + return [_ShapeInfo("a", False, (-np.inf, np.inf), (False, False))] + + def _pdf(self, x, a): + return _lazywhere( + a == 0, (x, a), lambda x, a: _norm_pdf(x), + f2=lambda x, a: 2.*_norm_pdf(x)*_norm_cdf(a*x) + ) + + def _logpdf(self, x, a): + return _lazywhere( + a == 0, (x, a), lambda x, a: _norm_logpdf(x), + f2=lambda x, a: np.log(2)+_norm_logpdf(x)+_norm_logcdf(a*x), + ) + + def _cdf(self, x, a): + a = np.atleast_1d(a) + cdf = scu._skewnorm_cdf(x, 0.0, 1.0, a) + # for some reason, a isn't broadcasted if some of x are invalid + a = np.broadcast_to(a, cdf.shape) + # Boost is not accurate in left tail when a > 0 + i_small_cdf = (cdf < 1e-6) & (a > 0) + cdf[i_small_cdf] = super()._cdf(x[i_small_cdf], a[i_small_cdf]) + return np.clip(cdf, 0, 1) + + def _ppf(self, x, a): + return scu._skewnorm_ppf(x, 0.0, 1.0, a) + + def _sf(self, x, a): + # Boost's SF is implemented this way. Use whatever customizations + # we made in the _cdf. + return self._cdf(-x, -a) + + def _isf(self, x, a): + return scu._skewnorm_isf(x, 0.0, 1.0, a) + + def _rvs(self, a, size=None, random_state=None): + u0 = random_state.normal(size=size) + v = random_state.normal(size=size) + d = a/np.sqrt(1 + a**2) + u1 = d*u0 + v*np.sqrt(1 - d**2) + return np.where(u0 >= 0, u1, -u1) + + def _stats(self, a, moments='mvsk'): + output = [None, None, None, None] + const = np.sqrt(2/np.pi) * a/np.sqrt(1 + a**2) + + if 'm' in moments: + output[0] = const + if 'v' in moments: + output[1] = 1 - const**2 + if 's' in moments: + output[2] = ((4 - np.pi)/2) * (const/np.sqrt(1 - const**2))**3 + if 'k' in moments: + output[3] = (2*(np.pi - 3)) * (const**4/(1 - const**2)**2) + + return output + + # For odd order, the each noncentral moment of the skew-normal distribution + # with location 0 and scale 1 can be expressed as a polynomial in delta, + # where delta = a/sqrt(1 + a**2) and `a` is the skew-normal shape + # parameter. The dictionary _skewnorm_odd_moments defines those + # polynomials for orders up to 19. The dict is implemented as a cached + # property to reduce the impact of the creation of the dict on import time. + @cached_property + def _skewnorm_odd_moments(self): + skewnorm_odd_moments = { + 1: Polynomial([1]), + 3: Polynomial([3, -1]), + 5: Polynomial([15, -10, 3]), + 7: Polynomial([105, -105, 63, -15]), + 9: Polynomial([945, -1260, 1134, -540, 105]), + 11: Polynomial([10395, -17325, 20790, -14850, 5775, -945]), + 13: Polynomial([135135, -270270, 405405, -386100, 225225, -73710, + 10395]), + 15: Polynomial([2027025, -4729725, 8513505, -10135125, 7882875, + -3869775, 1091475, -135135]), + 17: Polynomial([34459425, -91891800, 192972780, -275675400, + 268017750, -175429800, 74220300, -18378360, + 2027025]), + 19: Polynomial([654729075, -1964187225, 4714049340, -7856748900, + 9166207050, -7499623950, 4230557100, -1571349780, + 346621275, -34459425]), + } + return skewnorm_odd_moments + + def _munp(self, order, a): + if order % 2: + if order > 19: + raise NotImplementedError("skewnorm noncentral moments not " + "implemented for odd orders greater " + "than 19.") + # Use the precomputed polynomials that were derived from the + # moment generating function. + delta = a/np.sqrt(1 + a**2) + return (delta * self._skewnorm_odd_moments[order](delta**2) + * _SQRT_2_OVER_PI) + else: + # For even order, the moment is just (order-1)!!, where !! is the + # notation for the double factorial; for an odd integer m, m!! is + # m*(m-2)*...*3*1. + # We could use special.factorial2, but we know the argument is odd, + # so avoid the overhead of that function and compute the result + # directly here. + return sc.gamma((order + 1)/2) * 2**(order/2) / _SQRT_PI + + @extend_notes_in_docstring(rv_continuous, notes="""\ + If ``method='mm'``, parameters fixed by the user are respected, and the + remaining parameters are used to match distribution and sample moments + where possible. For example, if the user fixes the location with + ``floc``, the parameters will only match the distribution skewness and + variance to the sample skewness and variance; no attempt will be made + to match the means or minimize a norm of the errors. + Note that the maximum possible skewness magnitude of a + `scipy.stats.skewnorm` distribution is approximately 0.9952717; if the + magnitude of the data's sample skewness exceeds this, the returned + shape parameter ``a`` will be infinite. + \n\n""") + def fit(self, data, *args, **kwds): + if kwds.pop("superfit", False): + return super().fit(data, *args, **kwds) + if isinstance(data, CensoredData): + if data.num_censored() == 0: + data = data._uncensor() + else: + return super().fit(data, *args, **kwds) + + # this extracts fixed shape, location, and scale however they + # are specified, and also leaves them in `kwds` + data, fa, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + method = kwds.get("method", "mle").lower() + + # See https://en.wikipedia.org/wiki/Skew_normal_distribution for + # moment formulas. + def skew_d(d): # skewness in terms of delta + return (4-np.pi)/2 * ((d * np.sqrt(2 / np.pi))**3 + / (1 - 2*d**2 / np.pi)**(3/2)) + + def d_skew(skew): # delta in terms of skewness + s_23 = np.abs(skew)**(2/3) + return np.sign(skew) * np.sqrt( + np.pi/2 * s_23 / (s_23 + ((4 - np.pi)/2)**(2/3)) + ) + + # If method is method of moments, we don't need the user's guesses. + # Otherwise, extract the guesses from args and kwds. + if method == "mm": + a, loc, scale = None, None, None + else: + a = args[0] if len(args) else None + loc = kwds.pop('loc', None) + scale = kwds.pop('scale', None) + + if fa is None and a is None: # not fixed and no guess: use MoM + # Solve for a that matches sample distribution skewness to sample + # skewness. + s = stats.skew(data) + if method == 'mle': + # For MLE initial conditions, clip skewness to a large but + # reasonable value in case the data skewness is out-of-range. + s = np.clip(s, -0.99, 0.99) + else: + s_max = skew_d(1) + s = np.clip(s, -s_max, s_max) + d = d_skew(s) + with np.errstate(divide='ignore'): + a = np.sqrt(np.divide(d**2, (1-d**2)))*np.sign(s) + else: + a = fa if fa is not None else a + d = a / np.sqrt(1 + a**2) + + if fscale is None and scale is None: + v = np.var(data) + scale = np.sqrt(v / (1 - 2*d**2/np.pi)) + elif fscale is not None: + scale = fscale + + if floc is None and loc is None: + m = np.mean(data) + loc = m - scale*d*np.sqrt(2/np.pi) + elif floc is not None: + loc = floc + + if method == 'mm': + return a, loc, scale + else: + # At this point, parameter "guesses" may equal the fixed parameters + # in kwds. No harm in passing them as guesses, too. + return super().fit(data, a, loc=loc, scale=scale, **kwds) + + +skewnorm = skewnorm_gen(name='skewnorm') + + +class trapezoid_gen(rv_continuous): + r"""A trapezoidal continuous random variable. + + %(before_notes)s + + Notes + ----- + The trapezoidal distribution can be represented with an up-sloping line + from ``loc`` to ``(loc + c*scale)``, then constant to ``(loc + d*scale)`` + and then downsloping from ``(loc + d*scale)`` to ``(loc+scale)``. This + defines the trapezoid base from ``loc`` to ``(loc+scale)`` and the flat + top from ``c`` to ``d`` proportional to the position along the base + with ``0 <= c <= d <= 1``. When ``c=d``, this is equivalent to `triang` + with the same values for `loc`, `scale` and `c`. + The method of [1]_ is used for computing moments. + + `trapezoid` takes :math:`c` and :math:`d` as shape parameters. + + %(after_notes)s + + The standard form is in the range [0, 1] with c the mode. + The location parameter shifts the start to `loc`. + The scale parameter changes the width from 1 to `scale`. + + %(example)s + + References + ---------- + .. [1] Kacker, R.N. and Lawrence, J.F. (2007). Trapezoidal and triangular + distributions for Type B evaluation of standard uncertainty. + Metrologia 44, 117-127. :doi:`10.1088/0026-1394/44/2/003` + + + """ + def _argcheck(self, c, d): + return (c >= 0) & (c <= 1) & (d >= 0) & (d <= 1) & (d >= c) + + def _shape_info(self): + ic = _ShapeInfo("c", False, (0, 1.0), (True, True)) + id = _ShapeInfo("d", False, (0, 1.0), (True, True)) + return [ic, id] + + def _pdf(self, x, c, d): + u = 2 / (d-c+1) + + return _lazyselect([x < c, + (c <= x) & (x <= d), + x > d], + [lambda x, c, d, u: u * x / c, + lambda x, c, d, u: u, + lambda x, c, d, u: u * (1-x) / (1-d)], + (x, c, d, u)) + + def _cdf(self, x, c, d): + return _lazyselect([x < c, + (c <= x) & (x <= d), + x > d], + [lambda x, c, d: x**2 / c / (d-c+1), + lambda x, c, d: (c + 2 * (x-c)) / (d-c+1), + lambda x, c, d: 1-((1-x) ** 2 + / (d-c+1) / (1-d))], + (x, c, d)) + + def _ppf(self, q, c, d): + qc, qd = self._cdf(c, c, d), self._cdf(d, c, d) + condlist = [q < qc, q <= qd, q > qd] + choicelist = [np.sqrt(q * c * (1 + d - c)), + 0.5 * q * (1 + d - c) + 0.5 * c, + 1 - np.sqrt((1 - q) * (d - c + 1) * (1 - d))] + return np.select(condlist, choicelist) + + def _munp(self, n, c, d): + # Using the parameterization from Kacker, 2007, with + # a=bottom left, c=top left, d=top right, b=bottom right, then + # E[X^n] = h/(n+1)/(n+2) [(b^{n+2}-d^{n+2})/(b-d) + # - ((c^{n+2} - a^{n+2})/(c-a)] + # with h = 2/((b-a) - (d-c)). The corresponding parameterization + # in scipy, has a'=loc, c'=loc+c*scale, d'=loc+d*scale, b'=loc+scale, + # which for standard form reduces to a'=0, b'=1, c'=c, d'=d. + # Substituting into E[X^n] gives the bd' term as (1 - d^{n+2})/(1 - d) + # and the ac' term as c^{n-1} for the standard form. The bd' term has + # numerical difficulties near d=1, so replace (1 - d^{n+2})/(1-d) + # with expm1((n+2)*log(d))/(d-1). + # Testing with n=18 for c=(1e-30,1-eps) shows that this is stable. + # We still require an explicit test for d=1 to prevent divide by zero, + # and now a test for d=0 to prevent log(0). + ab_term = c**(n+1) + dc_term = _lazyselect( + [d == 0.0, (0.0 < d) & (d < 1.0), d == 1.0], + [lambda d: 1.0, + lambda d: np.expm1((n+2) * np.log(d)) / (d-1.0), + lambda d: n+2], + [d]) + val = 2.0 / (1.0+d-c) * (dc_term - ab_term) / ((n+1) * (n+2)) + return val + + def _entropy(self, c, d): + # Using the parameterization from Wikipedia (van Dorp, 2003) + # with a=bottom left, c=top left, d=top right, b=bottom right + # gives a'=loc, b'=loc+c*scale, c'=loc+d*scale, d'=loc+scale, + # which for loc=0, scale=1 is a'=0, b'=c, c'=d, d'=1. + # Substituting into the entropy formula from Wikipedia gives + # the following result. + return 0.5 * (1.0-d+c) / (1.0+d-c) + np.log(0.5 * (1.0+d-c)) + + +# deprecation of trapz, see #20486 +deprmsg = ("`trapz` is deprecated in favour of `trapezoid` " + "and will be removed in SciPy 1.16.0.") + + +class trapz_gen(trapezoid_gen): + # override __call__ protocol from rv_generic to also + # deprecate instantiation of frozen distributions + """ + + .. deprecated:: 1.14.0 + `trapz` is deprecated and will be removed in SciPy 1.16. + Plese use `trapezoid` instead! + """ + def __call__(self, *args, **kwds): + warnings.warn(deprmsg, DeprecationWarning, stacklevel=2) + return self.freeze(*args, **kwds) + + +trapezoid = trapezoid_gen(a=0.0, b=1.0, name="trapezoid") +trapz = trapz_gen(a=0.0, b=1.0, name="trapz") + +# since the deprecated class gets intantiated upon import (and we only want to +# warn upon use), add the deprecation to each class method +_method_names = [ + "cdf", "entropy", "expect", "fit", "interval", "isf", "logcdf", "logpdf", + "logsf", "mean", "median", "moment", "pdf", "ppf", "rvs", "sf", "stats", + "std", "var" +] + + +class _DeprecationWrapper: + def __init__(self, method): + self.msg = (f"`trapz.{method}` is deprecated in favour of trapezoid.{method}. " + "Please replace all uses of the distribution class " + "`trapz` with `trapezoid`. `trapz` will be removed in SciPy 1.16.") + self.method = getattr(trapezoid, method) + + def __call__(self, *args, **kwargs): + warnings.warn(self.msg, DeprecationWarning, stacklevel=2) + return self.method(*args, **kwargs) + + +for m in _method_names: + setattr(trapz, m, _DeprecationWrapper(m)) + + +class triang_gen(rv_continuous): + r"""A triangular continuous random variable. + + %(before_notes)s + + Notes + ----- + The triangular distribution can be represented with an up-sloping line from + ``loc`` to ``(loc + c*scale)`` and then downsloping for ``(loc + c*scale)`` + to ``(loc + scale)``. + + `triang` takes ``c`` as a shape parameter for :math:`0 \le c \le 1`. + + %(after_notes)s + + The standard form is in the range [0, 1] with c the mode. + The location parameter shifts the start to `loc`. + The scale parameter changes the width from 1 to `scale`. + + %(example)s + + """ + def _rvs(self, c, size=None, random_state=None): + return random_state.triangular(0, c, 1, size) + + def _argcheck(self, c): + return (c >= 0) & (c <= 1) + + def _shape_info(self): + return [_ShapeInfo("c", False, (0, 1.0), (True, True))] + + def _pdf(self, x, c): + # 0: edge case where c=0 + # 1: generalised case for x < c, don't use x <= c, as it doesn't cope + # with c = 0. + # 2: generalised case for x >= c, but doesn't cope with c = 1 + # 3: edge case where c=1 + r = _lazyselect([c == 0, + x < c, + (x >= c) & (c != 1), + c == 1], + [lambda x, c: 2 - 2 * x, + lambda x, c: 2 * x / c, + lambda x, c: 2 * (1 - x) / (1 - c), + lambda x, c: 2 * x], + (x, c)) + return r + + def _cdf(self, x, c): + r = _lazyselect([c == 0, + x < c, + (x >= c) & (c != 1), + c == 1], + [lambda x, c: 2*x - x*x, + lambda x, c: x * x / c, + lambda x, c: (x*x - 2*x + c) / (c-1), + lambda x, c: x * x], + (x, c)) + return r + + def _ppf(self, q, c): + return np.where(q < c, np.sqrt(c * q), 1-np.sqrt((1-c) * (1-q))) + + def _stats(self, c): + return ((c+1.0)/3.0, + (1.0-c+c*c)/18, + np.sqrt(2)*(2*c-1)*(c+1)*(c-2) / (5*np.power((1.0-c+c*c), 1.5)), + -3.0/5.0) + + def _entropy(self, c): + return 0.5-np.log(2) + + +triang = triang_gen(a=0.0, b=1.0, name="triang") + + +class truncexpon_gen(rv_continuous): + r"""A truncated exponential continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `truncexpon` is: + + .. math:: + + f(x, b) = \frac{\exp(-x)}{1 - \exp(-b)} + + for :math:`0 <= x <= b`. + + `truncexpon` takes ``b`` as a shape parameter for :math:`b`. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("b", False, (0, np.inf), (False, False))] + + def _get_support(self, b): + return self.a, b + + def _pdf(self, x, b): + # truncexpon.pdf(x, b) = exp(-x) / (1-exp(-b)) + return np.exp(-x)/(-sc.expm1(-b)) + + def _logpdf(self, x, b): + return -x - np.log(-sc.expm1(-b)) + + def _cdf(self, x, b): + return sc.expm1(-x)/sc.expm1(-b) + + def _ppf(self, q, b): + return -sc.log1p(q*sc.expm1(-b)) + + def _sf(self, x, b): + return (np.exp(-b) - np.exp(-x))/sc.expm1(-b) + + def _isf(self, q, b): + return -np.log(np.exp(-b) - q * sc.expm1(-b)) + + def _munp(self, n, b): + # wrong answer with formula, same as in continuous.pdf + # return sc.gamman+1)-sc.gammainc1+n, b) + if n == 1: + return (1-(b+1)*np.exp(-b))/(-sc.expm1(-b)) + elif n == 2: + return 2*(1-0.5*(b*b+2*b+2)*np.exp(-b))/(-sc.expm1(-b)) + else: + # return generic for higher moments + return super()._munp(n, b) + + def _entropy(self, b): + eB = np.exp(b) + return np.log(eB-1)+(1+eB*(b-1.0))/(1.0-eB) + + +truncexpon = truncexpon_gen(a=0.0, name='truncexpon') +truncexpon._support = (0.0, 'b') + + +# logsumexp trick for log(p + q) with only log(p) and log(q) +def _log_sum(log_p, log_q): + return sc.logsumexp([log_p, log_q], axis=0) + + +# same as above, but using -exp(x) = exp(x + πi) +def _log_diff(log_p, log_q): + return sc.logsumexp([log_p, log_q+np.pi*1j], axis=0) + + +def _log_gauss_mass(a, b): + """Log of Gaussian probability mass within an interval""" + a, b = np.broadcast_arrays(a, b) + + # Calculations in right tail are inaccurate, so we'll exploit the + # symmetry and work only in the left tail + case_left = b <= 0 + case_right = a > 0 + case_central = ~(case_left | case_right) + + def mass_case_left(a, b): + return _log_diff(_norm_logcdf(b), _norm_logcdf(a)) + + def mass_case_right(a, b): + return mass_case_left(-b, -a) + + def mass_case_central(a, b): + # Previously, this was implemented as: + # left_mass = mass_case_left(a, 0) + # right_mass = mass_case_right(0, b) + # return _log_sum(left_mass, right_mass) + # Catastrophic cancellation occurs as np.exp(log_mass) approaches 1. + # Correct for this with an alternative formulation. + # We're not concerned with underflow here: if only one term + # underflows, it was insignificant; if both terms underflow, + # the result can't accurately be represented in logspace anyway + # because sc.log1p(x) ~ x for small x. + return sc.log1p(-_norm_cdf(a) - _norm_cdf(-b)) + + # _lazyselect not working; don't care to debug it + out = np.full_like(a, fill_value=np.nan, dtype=np.complex128) + if a[case_left].size: + out[case_left] = mass_case_left(a[case_left], b[case_left]) + if a[case_right].size: + out[case_right] = mass_case_right(a[case_right], b[case_right]) + if a[case_central].size: + out[case_central] = mass_case_central(a[case_central], b[case_central]) + return np.real(out) # discard ~0j + + +class truncnorm_gen(rv_continuous): + r"""A truncated normal continuous random variable. + + %(before_notes)s + + Notes + ----- + This distribution is the normal distribution centered on ``loc`` (default + 0), with standard deviation ``scale`` (default 1), and truncated at ``a`` + and ``b`` *standard deviations* from ``loc``. For arbitrary ``loc`` and + ``scale``, ``a`` and ``b`` are *not* the abscissae at which the shifted + and scaled distribution is truncated. + + .. note:: + If ``a_trunc`` and ``b_trunc`` are the abscissae at which we wish + to truncate the distribution (as opposed to the number of standard + deviations from ``loc``), then we can calculate the distribution + parameters ``a`` and ``b`` as follows:: + + a, b = (a_trunc - loc) / scale, (b_trunc - loc) / scale + + This is a common point of confusion. For additional clarification, + please see the example below. + + %(example)s + + In the examples above, ``loc=0`` and ``scale=1``, so the plot is truncated + at ``a`` on the left and ``b`` on the right. However, suppose we were to + produce the same histogram with ``loc = 1`` and ``scale=0.5``. + + >>> loc, scale = 1, 0.5 + >>> rv = truncnorm(a, b, loc=loc, scale=scale) + >>> x = np.linspace(truncnorm.ppf(0.01, a, b), + ... truncnorm.ppf(0.99, a, b), 100) + >>> r = rv.rvs(size=1000) + + >>> fig, ax = plt.subplots(1, 1) + >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + >>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2) + >>> ax.set_xlim(a, b) + >>> ax.legend(loc='best', frameon=False) + >>> plt.show() + + Note that the distribution is no longer appears to be truncated at + abscissae ``a`` and ``b``. That is because the *standard* normal + distribution is first truncated at ``a`` and ``b``, *then* the resulting + distribution is scaled by ``scale`` and shifted by ``loc``. If we instead + want the shifted and scaled distribution to be truncated at ``a`` and + ``b``, we need to transform these values before passing them as the + distribution parameters. + + >>> a_transformed, b_transformed = (a - loc) / scale, (b - loc) / scale + >>> rv = truncnorm(a_transformed, b_transformed, loc=loc, scale=scale) + >>> x = np.linspace(truncnorm.ppf(0.01, a, b), + ... truncnorm.ppf(0.99, a, b), 100) + >>> r = rv.rvs(size=10000) + + >>> fig, ax = plt.subplots(1, 1) + >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + >>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2) + >>> ax.set_xlim(a-0.1, b+0.1) + >>> ax.legend(loc='best', frameon=False) + >>> plt.show() + """ + + def _argcheck(self, a, b): + return a < b + + def _shape_info(self): + ia = _ShapeInfo("a", False, (-np.inf, np.inf), (True, False)) + ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, True)) + return [ia, ib] + + def _fitstart(self, data): + # Reasonable, since support is [a, b] + if isinstance(data, CensoredData): + data = data._uncensor() + return super()._fitstart(data, args=(np.min(data), np.max(data))) + + def _get_support(self, a, b): + return a, b + + def _pdf(self, x, a, b): + return np.exp(self._logpdf(x, a, b)) + + def _logpdf(self, x, a, b): + return _norm_logpdf(x) - _log_gauss_mass(a, b) + + def _cdf(self, x, a, b): + return np.exp(self._logcdf(x, a, b)) + + def _logcdf(self, x, a, b): + x, a, b = np.broadcast_arrays(x, a, b) + logcdf = np.asarray(_log_gauss_mass(a, x) - _log_gauss_mass(a, b)) + i = logcdf > -0.1 # avoid catastrophic cancellation + if np.any(i): + logcdf[i] = np.log1p(-np.exp(self._logsf(x[i], a[i], b[i]))) + return logcdf + + def _sf(self, x, a, b): + return np.exp(self._logsf(x, a, b)) + + def _logsf(self, x, a, b): + x, a, b = np.broadcast_arrays(x, a, b) + logsf = np.asarray(_log_gauss_mass(x, b) - _log_gauss_mass(a, b)) + i = logsf > -0.1 # avoid catastrophic cancellation + if np.any(i): + logsf[i] = np.log1p(-np.exp(self._logcdf(x[i], a[i], b[i]))) + return logsf + + def _entropy(self, a, b): + A = _norm_cdf(a) + B = _norm_cdf(b) + Z = B - A + C = np.log(np.sqrt(2 * np.pi * np.e) * Z) + D = (a * _norm_pdf(a) - b * _norm_pdf(b)) / (2 * Z) + h = C + D + return h + + def _ppf(self, q, a, b): + q, a, b = np.broadcast_arrays(q, a, b) + + case_left = a < 0 + case_right = ~case_left + + def ppf_left(q, a, b): + log_Phi_x = _log_sum(_norm_logcdf(a), + np.log(q) + _log_gauss_mass(a, b)) + return sc.ndtri_exp(log_Phi_x) + + def ppf_right(q, a, b): + log_Phi_x = _log_sum(_norm_logcdf(-b), + np.log1p(-q) + _log_gauss_mass(a, b)) + return -sc.ndtri_exp(log_Phi_x) + + out = np.empty_like(q) + + q_left = q[case_left] + q_right = q[case_right] + + if q_left.size: + out[case_left] = ppf_left(q_left, a[case_left], b[case_left]) + if q_right.size: + out[case_right] = ppf_right(q_right, a[case_right], b[case_right]) + + return out + + def _isf(self, q, a, b): + # Mostly copy-paste of _ppf, but I think this is simpler than combining + q, a, b = np.broadcast_arrays(q, a, b) + + case_left = b < 0 + case_right = ~case_left + + def isf_left(q, a, b): + log_Phi_x = _log_diff(_norm_logcdf(b), + np.log(q) + _log_gauss_mass(a, b)) + return sc.ndtri_exp(np.real(log_Phi_x)) + + def isf_right(q, a, b): + log_Phi_x = _log_diff(_norm_logcdf(-a), + np.log1p(-q) + _log_gauss_mass(a, b)) + return -sc.ndtri_exp(np.real(log_Phi_x)) + + out = np.empty_like(q) + + q_left = q[case_left] + q_right = q[case_right] + + if q_left.size: + out[case_left] = isf_left(q_left, a[case_left], b[case_left]) + if q_right.size: + out[case_right] = isf_right(q_right, a[case_right], b[case_right]) + + return out + + def _munp(self, n, a, b): + def n_th_moment(n, a, b): + """ + Returns n-th moment. Defined only if n >= 0. + Function cannot broadcast due to the loop over n + """ + pA, pB = self._pdf(np.asarray([a, b]), a, b) + probs = [pA, -pB] + moments = [0, 1] + for k in range(1, n+1): + # a or b might be infinite, and the corresponding pdf value + # is 0 in that case, but nan is returned for the + # multiplication. However, as b->infinity, pdf(b)*b**k -> 0. + # So it is safe to use _lazywhere to avoid the nan. + vals = _lazywhere(probs, [probs, [a, b]], + lambda x, y: x * y**(k-1), fillvalue=0) + mk = np.sum(vals) + (k-1) * moments[-2] + moments.append(mk) + return moments[-1] + + return _lazywhere((n >= 0) & (a == a) & (b == b), (n, a, b), + np.vectorize(n_th_moment, otypes=[np.float64]), + np.nan) + + def _stats(self, a, b, moments='mv'): + pA, pB = self.pdf(np.array([a, b]), a, b) + + def _truncnorm_stats_scalar(a, b, pA, pB, moments): + m1 = pA - pB + mu = m1 + # use _lazywhere to avoid nan (See detailed comment in _munp) + probs = [pA, -pB] + vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y, + fillvalue=0) + m2 = 1 + np.sum(vals) + vals = _lazywhere(probs, [probs, [a-mu, b-mu]], lambda x, y: x*y, + fillvalue=0) + # mu2 = m2 - mu**2, but not as numerically stable as: + # mu2 = (a-mu)*pA - (b-mu)*pB + 1 + mu2 = 1 + np.sum(vals) + vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y**2, + fillvalue=0) + m3 = 2*m1 + np.sum(vals) + vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y**3, + fillvalue=0) + m4 = 3*m2 + np.sum(vals) + + mu3 = m3 + m1 * (-3*m2 + 2*m1**2) + g1 = mu3 / np.power(mu2, 1.5) + mu4 = m4 + m1*(-4*m3 + 3*m1*(2*m2 - m1**2)) + g2 = mu4 / mu2**2 - 3 + return mu, mu2, g1, g2 + + _truncnorm_stats = np.vectorize(_truncnorm_stats_scalar, + excluded=('moments',)) + return _truncnorm_stats(a, b, pA, pB, moments) + + +truncnorm = truncnorm_gen(name='truncnorm', momtype=1) +truncnorm._support = ('a', 'b') + + +class truncpareto_gen(rv_continuous): + r"""An upper truncated Pareto continuous random variable. + + %(before_notes)s + + See Also + -------- + pareto : Pareto distribution + + Notes + ----- + The probability density function for `truncpareto` is: + + .. math:: + + f(x, b, c) = \frac{b}{1 - c^{-b}} \frac{1}{x^{b+1}} + + for :math:`b > 0`, :math:`c > 1` and :math:`1 \le x \le c`. + + `truncpareto` takes `b` and `c` as shape parameters for :math:`b` and + :math:`c`. + + Notice that the upper truncation value :math:`c` is defined in + standardized form so that random values of an unscaled, unshifted variable + are within the range ``[1, c]``. + If ``u_r`` is the upper bound to a scaled and/or shifted variable, + then ``c = (u_r - loc) / scale``. In other words, the support of the + distribution becomes ``(scale + loc) <= x <= (c*scale + loc)`` when + `scale` and/or `loc` are provided. + + %(after_notes)s + + References + ---------- + .. [1] Burroughs, S. M., and Tebbens S. F. + "Upper-truncated power laws in natural systems." + Pure and Applied Geophysics 158.4 (2001): 741-757. + + %(example)s + + """ + + def _shape_info(self): + ib = _ShapeInfo("b", False, (0.0, np.inf), (False, False)) + ic = _ShapeInfo("c", False, (1.0, np.inf), (False, False)) + return [ib, ic] + + def _argcheck(self, b, c): + return (b > 0.) & (c > 1.) + + def _get_support(self, b, c): + return self.a, c + + def _pdf(self, x, b, c): + return b * x**-(b+1) / (1 - 1/c**b) + + def _logpdf(self, x, b, c): + return np.log(b) - np.log(-np.expm1(-b*np.log(c))) - (b+1)*np.log(x) + + def _cdf(self, x, b, c): + return (1 - x**-b) / (1 - 1/c**b) + + def _logcdf(self, x, b, c): + return np.log1p(-x**-b) - np.log1p(-1/c**b) + + def _ppf(self, q, b, c): + return pow(1 - (1 - 1/c**b)*q, -1/b) + + def _sf(self, x, b, c): + return (x**-b - 1/c**b) / (1 - 1/c**b) + + def _logsf(self, x, b, c): + return np.log(x**-b - 1/c**b) - np.log1p(-1/c**b) + + def _isf(self, q, b, c): + return pow(1/c**b + (1 - 1/c**b)*q, -1/b) + + def _entropy(self, b, c): + return -(np.log(b/(1 - 1/c**b)) + + (b+1)*(np.log(c)/(c**b - 1) - 1/b)) + + def _munp(self, n, b, c): + if (n == b).all(): + return b*np.log(c) / (1 - 1/c**b) + else: + return b / (b-n) * (c**b - c**n) / (c**b - 1) + + def _fitstart(self, data): + if isinstance(data, CensoredData): + data = data._uncensor() + b, loc, scale = pareto.fit(data) + c = (max(data) - loc)/scale + return b, c, loc, scale + + @_call_super_mom + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + if kwds.pop("superfit", False): + return super().fit(data, *args, **kwds) + + def log_mean(x): + return np.mean(np.log(x)) + + def harm_mean(x): + return 1/np.mean(1/x) + + def get_b(c, loc, scale): + u = (data-loc)/scale + harm_m = harm_mean(u) + log_m = log_mean(u) + quot = (harm_m-1)/log_m + return (1 - (quot-1) / (quot - (1 - 1/c)*harm_m/np.log(c)))/log_m + + def get_c(loc, scale): + return (mx - loc)/scale + + def get_loc(fc, fscale): + if fscale: # (fscale and fc) or (fscale and not fc) + loc = mn - fscale + return loc + if fc: + loc = (fc*mn - mx)/(fc - 1) + return loc + + def get_scale(loc): + return mn - loc + + # Functions used for optimisation; partial derivatives of + # the Lagrangian, set to equal 0. + + def dL_dLoc(loc, b_=None): + # Partial derivative wrt location. + # Optimised upon when no parameters, or only b, are fixed. + scale = get_scale(loc) + c = get_c(loc, scale) + b = get_b(c, loc, scale) if b_ is None else b_ + harm_m = harm_mean((data - loc)/scale) + return 1 - (1 + (c - 1)/(c**(b+1) - c)) * (1 - 1/(b+1)) * harm_m + + def dL_dB(b, logc, logm): + # Partial derivative wrt b. + # Optimised upon whenever at least one parameter but b is fixed, + # and b is free. + return b - np.log1p(b*logc / (1 - b*logm)) / logc + + def fallback(data, *args, **kwargs): + # Should any issue arise, default to the general fit method. + return super(truncpareto_gen, self).fit(data, *args, **kwargs) + + parameters = _check_fit_input_parameters(self, data, args, kwds) + data, fb, fc, floc, fscale = parameters + mn, mx = data.min(), data.max() + mn_inf = np.nextafter(mn, -np.inf) + + if (fb is not None + and fc is not None + and floc is not None + and fscale is not None): + raise ValueError("All parameters fixed." + "There is nothing to optimize.") + elif fc is None and floc is None and fscale is None: + if fb is None: + def cond_b(loc): + # b is positive only if this function is positive + scale = get_scale(loc) + c = get_c(loc, scale) + harm_m = harm_mean((data - loc)/scale) + return (1 + 1/(c-1)) * np.log(c) / harm_m - 1 + + # This gives an upper bound on loc allowing for a positive b. + # Iteratively look for a bracket for root_scalar. + mn_inf = np.nextafter(mn, -np.inf) + rbrack = mn_inf + i = 0 + lbrack = rbrack - 1 + while ((lbrack > -np.inf) + and (cond_b(lbrack)*cond_b(rbrack) >= 0)): + i += 1 + lbrack = rbrack - np.power(2., i) + if not lbrack > -np.inf: + return fallback(data, *args, **kwds) + res = root_scalar(cond_b, bracket=(lbrack, rbrack)) + if not res.converged: + return fallback(data, *args, **kwds) + + # Determine the MLE for loc. + # Iteratively look for a bracket for root_scalar. + rbrack = res.root - 1e-3 # grad_loc is numerically ill-behaved + lbrack = rbrack - 1 + i = 0 + while ((lbrack > -np.inf) + and (dL_dLoc(lbrack)*dL_dLoc(rbrack) >= 0)): + i += 1 + lbrack = rbrack - np.power(2., i) + if not lbrack > -np.inf: + return fallback(data, *args, **kwds) + res = root_scalar(dL_dLoc, bracket=(lbrack, rbrack)) + if not res.converged: + return fallback(data, *args, **kwds) + loc = res.root + scale = get_scale(loc) + c = get_c(loc, scale) + b = get_b(c, loc, scale) + + std_data = (data - loc)/scale + # The expression of b relies on b being bounded above. + up_bound_b = min(1/log_mean(std_data), + 1/(harm_mean(std_data)-1)) + if not (b < up_bound_b): + return fallback(data, *args, **kwds) + else: + # We know b is positive (or a FitError will be triggered) + # so we let loc get close to min(data). + rbrack = mn_inf + lbrack = mn_inf - 1 + i = 0 + # Iteratively look for a bracket for root_scalar. + while (lbrack > -np.inf + and (dL_dLoc(lbrack, fb) + * dL_dLoc(rbrack, fb) >= 0)): + i += 1 + lbrack = rbrack - 2**i + if not lbrack > -np.inf: + return fallback(data, *args, **kwds) + res = root_scalar(dL_dLoc, (fb,), + bracket=(lbrack, rbrack)) + if not res.converged: + return fallback(data, *args, **kwds) + loc = res.root + scale = get_scale(loc) + c = get_c(loc, scale) + b = fb + else: + # At least one of the parameters determining the support is fixed; + # the others then have analytical expressions from the constraints. + # The completely determined case (fixed c, loc and scale) + # has to be checked for not overflowing the support. + # If not fixed, b has to be determined numerically. + loc = floc if floc is not None else get_loc(fc, fscale) + scale = fscale or get_scale(loc) + c = fc or get_c(loc, scale) + + # Unscaled, translated values should be positive when the location + # is fixed. If it is not the case, we end up with negative `scale` + # and `c`, which would trigger a FitError before exiting the + # method. + if floc is not None and data.min() - floc < 0: + raise FitDataError("truncpareto", lower=1, upper=c) + + # Standardised values should be within the distribution support + # when all parameters controlling it are fixed. If it not the case, + # `fc` is overridden by `c` determined from `floc` and `fscale` when + # raising the exception. + if fc and (floc is not None) and fscale: + if data.max() > fc*fscale + floc: + raise FitDataError("truncpareto", lower=1, + upper=get_c(loc, scale)) + + # The other constraints should be automatically satisfied + # from the analytical expressions of the parameters. + # If fc or fscale are respectively less than one or less than 0, + # a FitError is triggered before exiting the method. + + if fb is None: + std_data = (data - loc)/scale + logm = log_mean(std_data) + logc = np.log(c) + # Condition for a positive root to exist. + if not (2*logm < logc): + return fallback(data, *args, **kwds) + + lbrack = 1/logm + 1/(logm - logc) + rbrack = np.nextafter(1/logm, 0) + try: + res = root_scalar(dL_dB, (logc, logm), + bracket=(lbrack, rbrack)) + # we should then never get there + if not res.converged: + return fallback(data, *args, **kwds) + b = res.root + except ValueError: + b = rbrack + else: + b = fb + + # The distribution requires that `scale+loc <= data <= c*scale+loc`. + # To avoid numerical issues, some tuning may be necessary. + # We adjust `scale` to satisfy the lower bound, and we adjust + # `c` to satisfy the upper bound. + if not (scale+loc) < mn: + if fscale: + loc = np.nextafter(loc, -np.inf) + else: + scale = get_scale(loc) + scale = np.nextafter(scale, 0) + if not (c*scale+loc) > mx: + c = get_c(loc, scale) + c = np.nextafter(c, np.inf) + + if not (np.all(self._argcheck(b, c)) and (scale > 0)): + return fallback(data, *args, **kwds) + + params_override = b, c, loc, scale + if floc is None and fscale is None: + # Based on testing in gh-16782, the following methods are only + # reliable if either `floc` or `fscale` are provided. They are + # fast, though, so might as well see if they are better than the + # generic method. + params_super = fallback(data, *args, **kwds) + nllf_override = self.nnlf(params_override, data) + nllf_super = self.nnlf(params_super, data) + if nllf_super < nllf_override: + return params_super + + return params_override + + +truncpareto = truncpareto_gen(a=1.0, name='truncpareto') +truncpareto._support = (1.0, 'c') + + +class tukeylambda_gen(rv_continuous): + r"""A Tukey-Lamdba continuous random variable. + + %(before_notes)s + + Notes + ----- + A flexible distribution, able to represent and interpolate between the + following distributions: + + - Cauchy (:math:`lambda = -1`) + - logistic (:math:`lambda = 0`) + - approx Normal (:math:`lambda = 0.14`) + - uniform from -1 to 1 (:math:`lambda = 1`) + + `tukeylambda` takes a real number :math:`lambda` (denoted ``lam`` + in the implementation) as a shape parameter. + + %(after_notes)s + + %(example)s + + """ + _support_mask = rv_continuous._open_support_mask + + def _argcheck(self, lam): + return np.isfinite(lam) + + def _shape_info(self): + return [_ShapeInfo("lam", False, (-np.inf, np.inf), (False, False))] + + def _get_support(self, lam): + b = _lazywhere(lam > 0, (lam,), + f=lambda lam: 1/lam, + fillvalue=np.inf) + return -b, b + + def _pdf(self, x, lam): + Fx = np.asarray(sc.tklmbda(x, lam)) + Px = Fx**(lam-1.0) + (np.asarray(1-Fx))**(lam-1.0) + with np.errstate(divide='ignore'): + Px = 1.0/np.asarray(Px) + return np.where((lam <= 0) | (abs(x) < 1.0/np.asarray(lam)), Px, 0.0) + + def _cdf(self, x, lam): + return sc.tklmbda(x, lam) + + def _ppf(self, q, lam): + return sc.boxcox(q, lam) - sc.boxcox1p(-q, lam) + + def _stats(self, lam): + return 0, _tlvar(lam), 0, _tlkurt(lam) + + def _entropy(self, lam): + def integ(p): + return np.log(pow(p, lam-1)+pow(1-p, lam-1)) + return integrate.quad(integ, 0, 1)[0] + + +tukeylambda = tukeylambda_gen(name='tukeylambda') + + +class FitUniformFixedScaleDataError(FitDataError): + def __init__(self, ptp, fscale): + self.args = ( + "Invalid values in `data`. Maximum likelihood estimation with " + "the uniform distribution and fixed scale requires that " + f"np.ptp(data) <= fscale, but np.ptp(data) = {ptp} and " + f"fscale = {fscale}." + ) + + +class uniform_gen(rv_continuous): + r"""A uniform continuous random variable. + + In the standard form, the distribution is uniform on ``[0, 1]``. Using + the parameters ``loc`` and ``scale``, one obtains the uniform distribution + on ``[loc, loc + scale]``. + + %(before_notes)s + + %(example)s + + """ + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return random_state.uniform(0.0, 1.0, size) + + def _pdf(self, x): + return 1.0*(x == x) + + def _cdf(self, x): + return x + + def _ppf(self, q): + return q + + def _stats(self): + return 0.5, 1.0/12, 0, -1.2 + + def _entropy(self): + return 0.0 + + @_call_super_mom + def fit(self, data, *args, **kwds): + """ + Maximum likelihood estimate for the location and scale parameters. + + `uniform.fit` uses only the following parameters. Because exact + formulas are used, the parameters related to optimization that are + available in the `fit` method of other distributions are ignored + here. The only positional argument accepted is `data`. + + Parameters + ---------- + data : array_like + Data to use in calculating the maximum likelihood estimate. + floc : float, optional + Hold the location parameter fixed to the specified value. + fscale : float, optional + Hold the scale parameter fixed to the specified value. + + Returns + ------- + loc, scale : float + Maximum likelihood estimates for the location and scale. + + Notes + ----- + An error is raised if `floc` is given and any values in `data` are + less than `floc`, or if `fscale` is given and `fscale` is less + than ``data.max() - data.min()``. An error is also raised if both + `floc` and `fscale` are given. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import uniform + + We'll fit the uniform distribution to `x`: + + >>> x = np.array([2, 2.5, 3.1, 9.5, 13.0]) + + For a uniform distribution MLE, the location is the minimum of the + data, and the scale is the maximum minus the minimum. + + >>> loc, scale = uniform.fit(x) + >>> loc + 2.0 + >>> scale + 11.0 + + If we know the data comes from a uniform distribution where the support + starts at 0, we can use ``floc=0``: + + >>> loc, scale = uniform.fit(x, floc=0) + >>> loc + 0.0 + >>> scale + 13.0 + + Alternatively, if we know the length of the support is 12, we can use + ``fscale=12``: + + >>> loc, scale = uniform.fit(x, fscale=12) + >>> loc + 1.5 + >>> scale + 12.0 + + In that last example, the support interval is [1.5, 13.5]. This + solution is not unique. For example, the distribution with ``loc=2`` + and ``scale=12`` has the same likelihood as the one above. When + `fscale` is given and it is larger than ``data.max() - data.min()``, + the parameters returned by the `fit` method center the support over + the interval ``[data.min(), data.max()]``. + + """ + if len(args) > 0: + raise TypeError("Too many arguments.") + + floc = kwds.pop('floc', None) + fscale = kwds.pop('fscale', None) + + _remove_optimizer_parameters(kwds) + + if floc is not None and fscale is not None: + # This check is for consistency with `rv_continuous.fit`. + raise ValueError("All parameters fixed. There is nothing to " + "optimize.") + + data = np.asarray(data) + + if not np.isfinite(data).all(): + raise ValueError("The data contains non-finite values.") + + # MLE for the uniform distribution + # -------------------------------- + # The PDF is + # + # f(x, loc, scale) = {1/scale for loc <= x <= loc + scale + # {0 otherwise} + # + # The likelihood function is + # L(x, loc, scale) = (1/scale)**n + # where n is len(x), assuming loc <= x <= loc + scale for all x. + # The log-likelihood is + # l(x, loc, scale) = -n*log(scale) + # The log-likelihood is maximized by making scale as small as possible, + # while keeping loc <= x <= loc + scale. So if neither loc nor scale + # are fixed, the log-likelihood is maximized by choosing + # loc = x.min() + # scale = np.ptp(x) + # If loc is fixed, it must be less than or equal to x.min(), and then + # the scale is + # scale = x.max() - loc + # If scale is fixed, it must not be less than np.ptp(x). If scale is + # greater than np.ptp(x), the solution is not unique. Note that the + # likelihood does not depend on loc, except for the requirement that + # loc <= x <= loc + scale. All choices of loc for which + # x.max() - scale <= loc <= x.min() + # have the same log-likelihood. In this case, we choose loc such that + # the support is centered over the interval [data.min(), data.max()]: + # loc = x.min() = 0.5*(scale - np.ptp(x)) + + if fscale is None: + # scale is not fixed. + if floc is None: + # loc is not fixed, scale is not fixed. + loc = data.min() + scale = np.ptp(data) + else: + # loc is fixed, scale is not fixed. + loc = floc + scale = data.max() - loc + if data.min() < loc: + raise FitDataError("uniform", lower=loc, upper=loc + scale) + else: + # loc is not fixed, scale is fixed. + ptp = np.ptp(data) + if ptp > fscale: + raise FitUniformFixedScaleDataError(ptp=ptp, fscale=fscale) + # If ptp < fscale, the ML estimate is not unique; see the comments + # above. We choose the distribution for which the support is + # centered over the interval [data.min(), data.max()]. + loc = data.min() - 0.5*(fscale - ptp) + scale = fscale + + # We expect the return values to be floating point, so ensure it + # by explicitly converting to float. + return float(loc), float(scale) + + +uniform = uniform_gen(a=0.0, b=1.0, name='uniform') + + +class vonmises_gen(rv_continuous): + r"""A Von Mises continuous random variable. + + %(before_notes)s + + See Also + -------- + scipy.stats.vonmises_fisher : Von-Mises Fisher distribution on a + hypersphere + + Notes + ----- + The probability density function for `vonmises` and `vonmises_line` is: + + .. math:: + + f(x, \kappa) = \frac{ \exp(\kappa \cos(x)) }{ 2 \pi I_0(\kappa) } + + for :math:`-\pi \le x \le \pi`, :math:`\kappa \ge 0`. :math:`I_0` is the + modified Bessel function of order zero (`scipy.special.i0`). + + `vonmises` is a circular distribution which does not restrict the + distribution to a fixed interval. Currently, there is no circular + distribution framework in SciPy. The ``cdf`` is implemented such that + ``cdf(x + 2*np.pi) == cdf(x) + 1``. + + `vonmises_line` is the same distribution, defined on :math:`[-\pi, \pi]` + on the real line. This is a regular (i.e. non-circular) distribution. + + Note about distribution parameters: `vonmises` and `vonmises_line` take + ``kappa`` as a shape parameter (concentration) and ``loc`` as the location + (circular mean). A ``scale`` parameter is accepted but does not have any + effect. + + Examples + -------- + Import the necessary modules. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import vonmises + + Define distribution parameters. + + >>> loc = 0.5 * np.pi # circular mean + >>> kappa = 1 # concentration + + Compute the probability density at ``x=0`` via the ``pdf`` method. + + >>> vonmises.pdf(0, loc=loc, kappa=kappa) + 0.12570826359722018 + + Verify that the percentile function ``ppf`` inverts the cumulative + distribution function ``cdf`` up to floating point accuracy. + + >>> x = 1 + >>> cdf_value = vonmises.cdf(x, loc=loc, kappa=kappa) + >>> ppf_value = vonmises.ppf(cdf_value, loc=loc, kappa=kappa) + >>> x, cdf_value, ppf_value + (1, 0.31489339900904967, 1.0000000000000004) + + Draw 1000 random variates by calling the ``rvs`` method. + + >>> sample_size = 1000 + >>> sample = vonmises(loc=loc, kappa=kappa).rvs(sample_size) + + Plot the von Mises density on a Cartesian and polar grid to emphasize + that it is a circular distribution. + + >>> fig = plt.figure(figsize=(12, 6)) + >>> left = plt.subplot(121) + >>> right = plt.subplot(122, projection='polar') + >>> x = np.linspace(-np.pi, np.pi, 500) + >>> vonmises_pdf = vonmises.pdf(x, loc=loc, kappa=kappa) + >>> ticks = [0, 0.15, 0.3] + + The left image contains the Cartesian plot. + + >>> left.plot(x, vonmises_pdf) + >>> left.set_yticks(ticks) + >>> number_of_bins = int(np.sqrt(sample_size)) + >>> left.hist(sample, density=True, bins=number_of_bins) + >>> left.set_title("Cartesian plot") + >>> left.set_xlim(-np.pi, np.pi) + >>> left.grid(True) + + The right image contains the polar plot. + + >>> right.plot(x, vonmises_pdf, label="PDF") + >>> right.set_yticks(ticks) + >>> right.hist(sample, density=True, bins=number_of_bins, + ... label="Histogram") + >>> right.set_title("Polar plot") + >>> right.legend(bbox_to_anchor=(0.15, 1.06)) + + """ + def _shape_info(self): + return [_ShapeInfo("kappa", False, (0, np.inf), (True, False))] + + def _argcheck(self, kappa): + return kappa >= 0 + + def _rvs(self, kappa, size=None, random_state=None): + return random_state.vonmises(0.0, kappa, size=size) + + @inherit_docstring_from(rv_continuous) + def rvs(self, *args, **kwds): + rvs = super().rvs(*args, **kwds) + return np.mod(rvs + np.pi, 2*np.pi) - np.pi + + def _pdf(self, x, kappa): + # vonmises.pdf(x, kappa) = exp(kappa * cos(x)) / (2*pi*I[0](kappa)) + # = exp(kappa * (cos(x) - 1)) / + # (2*pi*exp(-kappa)*I[0](kappa)) + # = exp(kappa * cosm1(x)) / (2*pi*i0e(kappa)) + return np.exp(kappa*sc.cosm1(x)) / (2*np.pi*sc.i0e(kappa)) + + def _logpdf(self, x, kappa): + # vonmises.pdf(x, kappa) = exp(kappa * cosm1(x)) / (2*pi*i0e(kappa)) + return kappa * sc.cosm1(x) - np.log(2*np.pi) - np.log(sc.i0e(kappa)) + + def _cdf(self, x, kappa): + return _stats.von_mises_cdf(kappa, x) + + def _stats_skip(self, kappa): + return 0, None, 0, None + + def _entropy(self, kappa): + # vonmises.entropy(kappa) = -kappa * I[1](kappa) / I[0](kappa) + + # log(2 * np.pi * I[0](kappa)) + # = -kappa * I[1](kappa) * exp(-kappa) / + # (I[0](kappa) * exp(-kappa)) + + # log(2 * np.pi * + # I[0](kappa) * exp(-kappa) / exp(-kappa)) + # = -kappa * sc.i1e(kappa) / sc.i0e(kappa) + + # log(2 * np.pi * i0e(kappa)) + kappa + return (-kappa * sc.i1e(kappa) / sc.i0e(kappa) + + np.log(2 * np.pi * sc.i0e(kappa)) + kappa) + + @extend_notes_in_docstring(rv_continuous, notes="""\ + The default limits of integration are endpoints of the interval + of width ``2*pi`` centered at `loc` (e.g. ``[-pi, pi]`` when + ``loc=0``).\n\n""") + def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, + conditional=False, **kwds): + _a, _b = -np.pi, np.pi + + if lb is None: + lb = loc + _a + if ub is None: + ub = loc + _b + + return super().expect(func, args, loc, + scale, lb, ub, conditional, **kwds) + + @_call_super_mom + @extend_notes_in_docstring(rv_continuous, notes="""\ + Fit data is assumed to represent angles and will be wrapped onto the + unit circle. `f0` and `fscale` are ignored; the returned shape is + always the maximum likelihood estimate and the scale is always + 1. Initial guesses are ignored.\n\n""") + def fit(self, data, *args, **kwds): + if kwds.pop('superfit', False): + return super().fit(data, *args, **kwds) + + data, fshape, floc, fscale = _check_fit_input_parameters(self, data, + args, kwds) + if self.a == -np.pi: + # vonmises line case, here the default fit method will be used + return super().fit(data, *args, **kwds) + + # wrap data to interval [0, 2*pi] + data = np.mod(data, 2 * np.pi) + + def find_mu(data): + return stats.circmean(data) + + def find_kappa(data, loc): + # Usually, sources list the following as the equation to solve for + # the MLE of the shape parameter: + # r = I[1](kappa)/I[0](kappa), where r = mean resultant length + # This is valid when the location is the MLE of location. + # More generally, when the location may be fixed at an arbitrary + # value, r should be defined as follows: + r = np.sum(np.cos(loc - data))/len(data) + # See gh-18128 for more information. + + # The function r[0](kappa) := I[1](kappa)/I[0](kappa) is monotonic + # increasing from r[0](0) = 0 to r[0](+inf) = 1. The partial + # derivative of the log likelihood function with respect to kappa + # is monotonic decreasing in kappa. + if r == 1: + # All observations are (almost) equal to the mean. Return + # some large kappa such that r[0](kappa) = 1.0 numerically. + return 1e16 + elif r > 0: + def solve_for_kappa(kappa): + return sc.i1e(kappa)/sc.i0e(kappa) - r + + # The bounds of the root of r[0](kappa) = r are derived from + # selected bounds of r[0](x) given in [1, Eq. 11 & 16]. See + # gh-20102 for details. + # + # [1] Amos, D. E. (1973). Computation of Modified Bessel + # Functions and Their Ratios. Mathematics of Computation, + # 28(125): 239-251. + lower_bound = r/(1-r)/(1+r) + upper_bound = 2*lower_bound + + # The bounds are violated numerically for certain values of r, + # where solve_for_kappa evaluated at the bounds have the same + # sign. This indicates numerical imprecision of i1e()/i0e(). + # Return the violated bound in this case as it's more accurate. + if solve_for_kappa(lower_bound) >= 0: + return lower_bound + elif solve_for_kappa(upper_bound) <= 0: + return upper_bound + else: + root_res = root_scalar(solve_for_kappa, method="brentq", + bracket=(lower_bound, upper_bound)) + return root_res.root + else: + # if the provided floc is very far from the circular mean, + # the mean resultant length r can become negative. + # In that case, the equation + # I[1](kappa)/I[0](kappa) = r does not have a solution. + # The maximum likelihood kappa is then 0 which practically + # results in the uniform distribution on the circle. As + # vonmises is defined for kappa > 0, return instead the + # smallest floating point value. + # See gh-18190 for more information + return np.finfo(float).tiny + + # location likelihood equation has a solution independent of kappa + loc = floc if floc is not None else find_mu(data) + # shape likelihood equation depends on location + shape = fshape if fshape is not None else find_kappa(data, loc) + + loc = np.mod(loc + np.pi, 2 * np.pi) - np.pi # ensure in [-pi, pi] + return shape, loc, 1 # scale is not handled + + +vonmises = vonmises_gen(name='vonmises') +vonmises_line = vonmises_gen(a=-np.pi, b=np.pi, name='vonmises_line') + + +class wald_gen(invgauss_gen): + r"""A Wald continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `wald` is: + + .. math:: + + f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp(- \frac{ (x-1)^2 }{ 2x }) + + for :math:`x >= 0`. + + `wald` is a special case of `invgauss` with ``mu=1``. + + %(after_notes)s + + %(example)s + """ + _support_mask = rv_continuous._open_support_mask + + def _shape_info(self): + return [] + + def _rvs(self, size=None, random_state=None): + return random_state.wald(1.0, 1.0, size=size) + + def _pdf(self, x): + # wald.pdf(x) = 1/sqrt(2*pi*x**3) * exp(-(x-1)**2/(2*x)) + return invgauss._pdf(x, 1.0) + + def _cdf(self, x): + return invgauss._cdf(x, 1.0) + + def _sf(self, x): + return invgauss._sf(x, 1.0) + + def _ppf(self, x): + return invgauss._ppf(x, 1.0) + + def _isf(self, x): + return invgauss._isf(x, 1.0) + + def _logpdf(self, x): + return invgauss._logpdf(x, 1.0) + + def _logcdf(self, x): + return invgauss._logcdf(x, 1.0) + + def _logsf(self, x): + return invgauss._logsf(x, 1.0) + + def _stats(self): + return 1.0, 1.0, 3.0, 15.0 + + def _entropy(self): + return invgauss._entropy(1.0) + + +wald = wald_gen(a=0.0, name="wald") + + +class wrapcauchy_gen(rv_continuous): + r"""A wrapped Cauchy continuous random variable. + + %(before_notes)s + + Notes + ----- + The probability density function for `wrapcauchy` is: + + .. math:: + + f(x, c) = \frac{1-c^2}{2\pi (1+c^2 - 2c \cos(x))} + + for :math:`0 \le x \le 2\pi`, :math:`0 < c < 1`. + + `wrapcauchy` takes ``c`` as a shape parameter for :math:`c`. + + %(after_notes)s + + %(example)s + + """ + def _argcheck(self, c): + return (c > 0) & (c < 1) + + def _shape_info(self): + return [_ShapeInfo("c", False, (0, 1), (False, False))] + + def _pdf(self, x, c): + # wrapcauchy.pdf(x, c) = (1-c**2) / (2*pi*(1+c**2-2*c*cos(x))) + return (1.0-c*c)/(2*np.pi*(1+c*c-2*c*np.cos(x))) + + def _cdf(self, x, c): + + def f1(x, cr): + # CDF for 0 <= x < pi + return 1/np.pi * np.arctan(cr*np.tan(x/2)) + + def f2(x, cr): + # CDF for pi <= x <= 2*pi + return 1 - 1/np.pi * np.arctan(cr*np.tan((2*np.pi - x)/2)) + + cr = (1 + c)/(1 - c) + return _lazywhere(x < np.pi, (x, cr), f=f1, f2=f2) + + def _ppf(self, q, c): + val = (1.0-c)/(1.0+c) + rcq = 2*np.arctan(val*np.tan(np.pi*q)) + rcmq = 2*np.pi-2*np.arctan(val*np.tan(np.pi*(1-q))) + return np.where(q < 1.0/2, rcq, rcmq) + + def _entropy(self, c): + return np.log(2*np.pi*(1-c*c)) + + def _fitstart(self, data): + # Use 0.5 as the initial guess of the shape parameter. + # For the location and scale, use the minimum and + # peak-to-peak/(2*pi), respectively. + if isinstance(data, CensoredData): + data = data._uncensor() + return 0.5, np.min(data), np.ptp(data)/(2*np.pi) + + +wrapcauchy = wrapcauchy_gen(a=0.0, b=2*np.pi, name='wrapcauchy') + + +class gennorm_gen(rv_continuous): + r"""A generalized normal continuous random variable. + + %(before_notes)s + + See Also + -------- + laplace : Laplace distribution + norm : normal distribution + + Notes + ----- + The probability density function for `gennorm` is [1]_: + + .. math:: + + f(x, \beta) = \frac{\beta}{2 \Gamma(1/\beta)} \exp(-|x|^\beta), + + where :math:`x` is a real number, :math:`\beta > 0` and + :math:`\Gamma` is the gamma function (`scipy.special.gamma`). + + `gennorm` takes ``beta`` as a shape parameter for :math:`\beta`. + For :math:`\beta = 1`, it is identical to a Laplace distribution. + For :math:`\beta = 2`, it is identical to a normal distribution + (with ``scale=1/sqrt(2)``). + + References + ---------- + + .. [1] "Generalized normal distribution, Version 1", + https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1 + + .. [2] Nardon, Martina, and Paolo Pianca. "Simulation techniques for + generalized Gaussian densities." Journal of Statistical + Computation and Simulation 79.11 (2009): 1317-1329 + + .. [3] Wicklin, Rick. "Simulate data from a generalized Gaussian + distribution" in The DO Loop blog, September 21, 2016, + https://blogs.sas.com/content/iml/2016/09/21/simulate-generalized-gaussian-sas.html + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("beta", False, (0, np.inf), (False, False))] + + def _pdf(self, x, beta): + return np.exp(self._logpdf(x, beta)) + + def _logpdf(self, x, beta): + return np.log(0.5*beta) - sc.gammaln(1.0/beta) - abs(x)**beta + + def _cdf(self, x, beta): + c = 0.5 * np.sign(x) + # evaluating (.5 + c) first prevents numerical cancellation + return (0.5 + c) - c * sc.gammaincc(1.0/beta, abs(x)**beta) + + def _ppf(self, x, beta): + c = np.sign(x - 0.5) + # evaluating (1. + c) first prevents numerical cancellation + return c * sc.gammainccinv(1.0/beta, (1.0 + c) - 2.0*c*x)**(1.0/beta) + + def _sf(self, x, beta): + return self._cdf(-x, beta) + + def _isf(self, x, beta): + return -self._ppf(x, beta) + + def _stats(self, beta): + c1, c3, c5 = sc.gammaln([1.0/beta, 3.0/beta, 5.0/beta]) + return 0., np.exp(c3 - c1), 0., np.exp(c5 + c1 - 2.0*c3) - 3. + + def _entropy(self, beta): + return 1. / beta - np.log(.5 * beta) + sc.gammaln(1. / beta) + + def _rvs(self, beta, size=None, random_state=None): + # see [2]_ for the algorithm + # see [3]_ for reference implementation in SAS + z = random_state.gamma(1/beta, size=size) + y = z ** (1/beta) + # convert y to array to ensure masking support + y = np.asarray(y) + mask = random_state.random(size=y.shape) < 0.5 + y[mask] = -y[mask] + return y + + +gennorm = gennorm_gen(name='gennorm') + + +class halfgennorm_gen(rv_continuous): + r"""The upper half of a generalized normal continuous random variable. + + %(before_notes)s + + See Also + -------- + gennorm : generalized normal distribution + expon : exponential distribution + halfnorm : half normal distribution + + Notes + ----- + The probability density function for `halfgennorm` is: + + .. math:: + + f(x, \beta) = \frac{\beta}{\Gamma(1/\beta)} \exp(-|x|^\beta) + + for :math:`x, \beta > 0`. :math:`\Gamma` is the gamma function + (`scipy.special.gamma`). + + `halfgennorm` takes ``beta`` as a shape parameter for :math:`\beta`. + For :math:`\beta = 1`, it is identical to an exponential distribution. + For :math:`\beta = 2`, it is identical to a half normal distribution + (with ``scale=1/sqrt(2)``). + + References + ---------- + + .. [1] "Generalized normal distribution, Version 1", + https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1 + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("beta", False, (0, np.inf), (False, False))] + + def _pdf(self, x, beta): + # beta + # halfgennorm.pdf(x, beta) = ------------- exp(-|x|**beta) + # gamma(1/beta) + return np.exp(self._logpdf(x, beta)) + + def _logpdf(self, x, beta): + return np.log(beta) - sc.gammaln(1.0/beta) - x**beta + + def _cdf(self, x, beta): + return sc.gammainc(1.0/beta, x**beta) + + def _ppf(self, x, beta): + return sc.gammaincinv(1.0/beta, x)**(1.0/beta) + + def _sf(self, x, beta): + return sc.gammaincc(1.0/beta, x**beta) + + def _isf(self, x, beta): + return sc.gammainccinv(1.0/beta, x)**(1.0/beta) + + def _entropy(self, beta): + return 1.0/beta - np.log(beta) + sc.gammaln(1.0/beta) + + +halfgennorm = halfgennorm_gen(a=0, name='halfgennorm') + + +class crystalball_gen(rv_continuous): + r""" + Crystalball distribution + + %(before_notes)s + + Notes + ----- + The probability density function for `crystalball` is: + + .. math:: + + f(x, \beta, m) = \begin{cases} + N \exp(-x^2 / 2), &\text{for } x > -\beta\\ + N A (B - x)^{-m} &\text{for } x \le -\beta + \end{cases} + + where :math:`A = (m / |\beta|)^m \exp(-\beta^2 / 2)`, + :math:`B = m/|\beta| - |\beta|` and :math:`N` is a normalisation constant. + + `crystalball` takes :math:`\beta > 0` and :math:`m > 1` as shape + parameters. :math:`\beta` defines the point where the pdf changes + from a power-law to a Gaussian distribution. :math:`m` is the power + of the power-law tail. + + %(after_notes)s + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] "Crystal Ball Function", + https://en.wikipedia.org/wiki/Crystal_Ball_function + + %(example)s + """ + def _argcheck(self, beta, m): + """ + Shape parameter bounds are m > 1 and beta > 0. + """ + return (m > 1) & (beta > 0) + + def _shape_info(self): + ibeta = _ShapeInfo("beta", False, (0, np.inf), (False, False)) + im = _ShapeInfo("m", False, (1, np.inf), (False, False)) + return [ibeta, im] + + def _fitstart(self, data): + # Arbitrary, but the default m=1 is not valid + return super()._fitstart(data, args=(1, 1.5)) + + def _pdf(self, x, beta, m): + """ + Return PDF of the crystalball function. + + -- + | exp(-x**2 / 2), for x > -beta + crystalball.pdf(x, beta, m) = N * | + | A * (B - x)**(-m), for x <= -beta + -- + """ + N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + + _norm_pdf_C * _norm_cdf(beta)) + + def rhs(x, beta, m): + return np.exp(-x**2 / 2) + + def lhs(x, beta, m): + return ((m/beta)**m * np.exp(-beta**2 / 2.0) * + (m/beta - beta - x)**(-m)) + + return N * _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs) + + def _logpdf(self, x, beta, m): + """ + Return the log of the PDF of the crystalball function. + """ + N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + + _norm_pdf_C * _norm_cdf(beta)) + + def rhs(x, beta, m): + return -x**2/2 + + def lhs(x, beta, m): + return m*np.log(m/beta) - beta**2/2 - m*np.log(m/beta - beta - x) + + return np.log(N) + _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs) + + def _cdf(self, x, beta, m): + """ + Return CDF of the crystalball function + """ + N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + + _norm_pdf_C * _norm_cdf(beta)) + + def rhs(x, beta, m): + return ((m/beta) * np.exp(-beta**2 / 2.0) / (m-1) + + _norm_pdf_C * (_norm_cdf(x) - _norm_cdf(-beta))) + + def lhs(x, beta, m): + return ((m/beta)**m * np.exp(-beta**2 / 2.0) * + (m/beta - beta - x)**(-m+1) / (m-1)) + + return N * _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs) + + def _sf(self, x, beta, m): + """ + Survival function of the crystalball distribution. + """ + + def rhs(x, beta, m): + # M is the same as 1/N used elsewhere. + M = m/beta/(m - 1)*np.exp(-beta**2/2) + _norm_pdf_C*_norm_cdf(beta) + return _norm_pdf_C*_norm_sf(x)/M + + def lhs(x, beta, m): + # Default behavior is OK in the left tail of the SF. + return 1 - self._cdf(x, beta, m) + + return _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs) + + def _ppf(self, p, beta, m): + N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + + _norm_pdf_C * _norm_cdf(beta)) + pbeta = N * (m/beta) * np.exp(-beta**2/2) / (m - 1) + + def ppf_less(p, beta, m): + eb2 = np.exp(-beta**2/2) + C = (m/beta) * eb2 / (m-1) + N = 1/(C + _norm_pdf_C * _norm_cdf(beta)) + return (m/beta - beta - + ((m - 1)*(m/beta)**(-m)/eb2*p/N)**(1/(1-m))) + + def ppf_greater(p, beta, m): + eb2 = np.exp(-beta**2/2) + C = (m/beta) * eb2 / (m-1) + N = 1/(C + _norm_pdf_C * _norm_cdf(beta)) + return _norm_ppf(_norm_cdf(-beta) + (1/_norm_pdf_C)*(p/N - C)) + + return _lazywhere(p < pbeta, (p, beta, m), f=ppf_less, f2=ppf_greater) + + def _munp(self, n, beta, m): + """ + Returns the n-th non-central moment of the crystalball function. + """ + N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + + _norm_pdf_C * _norm_cdf(beta)) + + def n_th_moment(n, beta, m): + """ + Returns n-th moment. Defined only if n+1 < m + Function cannot broadcast due to the loop over n + """ + A = (m/beta)**m * np.exp(-beta**2 / 2.0) + B = m/beta - beta + rhs = (2**((n-1)/2.0) * sc.gamma((n+1)/2) * + (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2))) + lhs = np.zeros(rhs.shape) + for k in range(int(n) + 1): + lhs += (sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) * + (m/beta)**(-m + k + 1)) + return A * lhs + rhs + + return N * _lazywhere(n + 1 < m, (n, beta, m), + np.vectorize(n_th_moment, otypes=[np.float64]), + np.inf) + + +crystalball = crystalball_gen(name='crystalball', longname="A Crystalball Function") + + +def _argus_phi(chi): + """ + Utility function for the argus distribution used in the pdf, sf and + moment calculation. + Note that for all x > 0: + gammainc(1.5, x**2/2) = 2 * (_norm_cdf(x) - x * _norm_pdf(x) - 0.5). + This can be verified directly by noting that the cdf of Gamma(1.5) can + be written as erf(sqrt(x)) - 2*sqrt(x)*exp(-x)/sqrt(Pi). + We use gammainc instead of the usual definition because it is more precise + for small chi. + """ + return sc.gammainc(1.5, chi**2/2) / 2 + + +class argus_gen(rv_continuous): + r""" + Argus distribution + + %(before_notes)s + + Notes + ----- + The probability density function for `argus` is: + + .. math:: + + f(x, \chi) = \frac{\chi^3}{\sqrt{2\pi} \Psi(\chi)} x \sqrt{1-x^2} + \exp(-\chi^2 (1 - x^2)/2) + + for :math:`0 < x < 1` and :math:`\chi > 0`, where + + .. math:: + + \Psi(\chi) = \Phi(\chi) - \chi \phi(\chi) - 1/2 + + with :math:`\Phi` and :math:`\phi` being the CDF and PDF of a standard + normal distribution, respectively. + + `argus` takes :math:`\chi` as shape a parameter. Details about sampling + from the ARGUS distribution can be found in [2]_. + + %(after_notes)s + + References + ---------- + .. [1] "ARGUS distribution", + https://en.wikipedia.org/wiki/ARGUS_distribution + .. [2] Christoph Baumgarten "Random variate generation by fast numerical + inversion in the varying parameter case." Research in Statistics, + vol. 1, 2023, doi:10.1080/27684520.2023.2279060. + + .. versionadded:: 0.19.0 + + %(example)s + """ + def _shape_info(self): + return [_ShapeInfo("chi", False, (0, np.inf), (False, False))] + + def _logpdf(self, x, chi): + # for x = 0 or 1, logpdf returns -np.inf + with np.errstate(divide='ignore'): + y = 1.0 - x*x + A = 3*np.log(chi) - _norm_pdf_logC - np.log(_argus_phi(chi)) + return A + np.log(x) + 0.5*np.log1p(-x*x) - chi**2 * y / 2 + + def _pdf(self, x, chi): + return np.exp(self._logpdf(x, chi)) + + def _cdf(self, x, chi): + return 1.0 - self._sf(x, chi) + + def _sf(self, x, chi): + return _argus_phi(chi * np.sqrt((1 - x)*(1 + x))) / _argus_phi(chi) + + def _rvs(self, chi, size=None, random_state=None): + chi = np.asarray(chi) + if chi.size == 1: + out = self._rvs_scalar(chi, numsamples=size, + random_state=random_state) + else: + shp, bc = _check_shape(chi.shape, size) + numsamples = int(np.prod(shp)) + out = np.empty(size) + it = np.nditer([chi], + flags=['multi_index'], + op_flags=[['readonly']]) + while not it.finished: + idx = tuple((it.multi_index[j] if not bc[j] else slice(None)) + for j in range(-len(size), 0)) + r = self._rvs_scalar(it[0], numsamples=numsamples, + random_state=random_state) + out[idx] = r.reshape(shp) + it.iternext() + + if size == (): + out = out[()] + return out + + def _rvs_scalar(self, chi, numsamples=None, random_state=None): + # if chi <= 1.8: + # use rejection method, see Devroye: + # Non-Uniform Random Variate Generation, 1986, section II.3.2. + # write: PDF f(x) = c * g(x) * h(x), where + # h is [0,1]-valued and g is a density + # we use two ways to write f + # + # Case 1: + # write g(x) = 3*x*sqrt(1-x**2), h(x) = exp(-chi**2 (1-x**2) / 2) + # If X has a distribution with density g its ppf G_inv is given by: + # G_inv(u) = np.sqrt(1 - u**(2/3)) + # + # Case 2: + # g(x) = chi**2 * x * exp(-chi**2 * (1-x**2)/2) / (1 - exp(-chi**2 /2)) + # h(x) = sqrt(1 - x**2), 0 <= x <= 1 + # one can show that + # G_inv(u) = np.sqrt(2*np.log(u*(np.exp(chi**2/2)-1)+1))/chi + # = np.sqrt(1 + 2*np.log(np.exp(-chi**2/2)*(1-u)+u)/chi**2) + # the latter expression is used for precision with small chi + # + # In both cases, the inverse cdf of g can be written analytically, and + # we can apply the rejection method: + # + # REPEAT + # Generate U uniformly distributed on [0, 1] + # Generate X with density g (e.g. via inverse transform sampling: + # X = G_inv(V) with V uniformly distributed on [0, 1]) + # UNTIL X <= h(X) + # RETURN X + # + # We use case 1 for chi <= 0.5 as it maintains precision for small chi + # and case 2 for 0.5 < chi <= 1.8 due to its speed for moderate chi. + # + # if chi > 1.8: + # use relation to the Gamma distribution: if X is ARGUS with parameter + # chi), then Y = chi**2 * (1 - X**2) / 2 has density proportional to + # sqrt(u) * exp(-u) on [0, chi**2 / 2], i.e. a Gamma(3/2) distribution + # conditioned on [0, chi**2 / 2]). Therefore, to sample X from the + # ARGUS distribution, we sample Y from the gamma distribution, keeping + # only samples on [0, chi**2 / 2], and apply the inverse + # transformation X = (1 - 2*Y/chi**2)**(1/2). Since we only + # look at chi > 1.8, gamma(1.5).cdf(chi**2/2) is large enough such + # Y falls in the interval [0, chi**2 / 2] with a high probability: + # stats.gamma(1.5).cdf(1.8**2/2) = 0.644... + # + # The points to switch between the different methods are determined + # by a comparison of the runtime of the different methods. However, + # the runtime is platform-dependent. The implemented values should + # ensure a good overall performance and are supported by an analysis + # of the rejection constants of different methods. + + size1d = tuple(np.atleast_1d(numsamples)) + N = int(np.prod(size1d)) + x = np.zeros(N) + simulated = 0 + chi2 = chi * chi + if chi <= 0.5: + d = -chi2 / 2 + while simulated < N: + k = N - simulated + u = random_state.uniform(size=k) + v = random_state.uniform(size=k) + z = v**(2/3) + # acceptance condition: u <= h(G_inv(v)). This simplifies to + accept = (np.log(u) <= d * z) + num_accept = np.sum(accept) + if num_accept > 0: + # we still need to transform z=v**(2/3) to X = G_inv(v) + rvs = np.sqrt(1 - z[accept]) + x[simulated:(simulated + num_accept)] = rvs + simulated += num_accept + elif chi <= 1.8: + echi = np.exp(-chi2 / 2) + while simulated < N: + k = N - simulated + u = random_state.uniform(size=k) + v = random_state.uniform(size=k) + z = 2 * np.log(echi * (1 - v) + v) / chi2 + # as in case one, simplify u <= h(G_inv(v)) and then transform + # z to the target distribution X = G_inv(v) + accept = (u**2 + z <= 0) + num_accept = np.sum(accept) + if num_accept > 0: + rvs = np.sqrt(1 + z[accept]) + x[simulated:(simulated + num_accept)] = rvs + simulated += num_accept + else: + # conditional Gamma for chi > 1.8 + while simulated < N: + k = N - simulated + g = random_state.standard_gamma(1.5, size=k) + accept = (g <= chi2 / 2) + num_accept = np.sum(accept) + if num_accept > 0: + x[simulated:(simulated + num_accept)] = g[accept] + simulated += num_accept + x = np.sqrt(1 - 2 * x / chi2) + + return np.reshape(x, size1d) + + def _stats(self, chi): + # need to ensure that dtype is float + # otherwise the mask below does not work for integers + chi = np.asarray(chi, dtype=float) + phi = _argus_phi(chi) + m = np.sqrt(np.pi/8) * chi * sc.ive(1, chi**2/4) / phi + # compute second moment, use Taylor expansion for small chi (<= 0.1) + mu2 = np.empty_like(chi) + mask = chi > 0.1 + c = chi[mask] + mu2[mask] = 1 - 3 / c**2 + c * _norm_pdf(c) / phi[mask] + c = chi[~mask] + coef = [-358/65690625, 0, -94/1010625, 0, 2/2625, 0, 6/175, 0, 0.4] + mu2[~mask] = np.polyval(coef, c) + return m, mu2 - m**2, None, None + + +argus = argus_gen(name='argus', longname="An Argus Function", a=0.0, b=1.0) + + +class rv_histogram(rv_continuous): + """ + Generates a distribution given by a histogram. + This is useful to generate a template distribution from a binned + datasample. + + As a subclass of the `rv_continuous` class, `rv_histogram` inherits from it + a collection of generic methods (see `rv_continuous` for the full list), + and implements them based on the properties of the provided binned + datasample. + + Parameters + ---------- + histogram : tuple of array_like + Tuple containing two array_like objects. + The first containing the content of n bins, + the second containing the (n+1) bin boundaries. + In particular, the return value of `numpy.histogram` is accepted. + + density : bool, optional + If False, assumes the histogram is proportional to counts per bin; + otherwise, assumes it is proportional to a density. + For constant bin widths, these are equivalent, but the distinction + is important when bin widths vary (see Notes). + If None (default), sets ``density=True`` for backwards compatibility, + but warns if the bin widths are variable. Set `density` explicitly + to silence the warning. + + .. versionadded:: 1.10.0 + + Notes + ----- + When a histogram has unequal bin widths, there is a distinction between + histograms that are proportional to counts per bin and histograms that are + proportional to probability density over a bin. If `numpy.histogram` is + called with its default ``density=False``, the resulting histogram is the + number of counts per bin, so ``density=False`` should be passed to + `rv_histogram`. If `numpy.histogram` is called with ``density=True``, the + resulting histogram is in terms of probability density, so ``density=True`` + should be passed to `rv_histogram`. To avoid warnings, always pass + ``density`` explicitly when the input histogram has unequal bin widths. + + There are no additional shape parameters except for the loc and scale. + The pdf is defined as a stepwise function from the provided histogram. + The cdf is a linear interpolation of the pdf. + + .. versionadded:: 0.19.0 + + Examples + -------- + + Create a scipy.stats distribution from a numpy histogram + + >>> import scipy.stats + >>> import numpy as np + >>> data = scipy.stats.norm.rvs(size=100000, loc=0, scale=1.5, + ... random_state=123) + >>> hist = np.histogram(data, bins=100) + >>> hist_dist = scipy.stats.rv_histogram(hist, density=False) + + Behaves like an ordinary scipy rv_continuous distribution + + >>> hist_dist.pdf(1.0) + 0.20538577847618705 + >>> hist_dist.cdf(2.0) + 0.90818568543056499 + + PDF is zero above (below) the highest (lowest) bin of the histogram, + defined by the max (min) of the original dataset + + >>> hist_dist.pdf(np.max(data)) + 0.0 + >>> hist_dist.cdf(np.max(data)) + 1.0 + >>> hist_dist.pdf(np.min(data)) + 7.7591907244498314e-05 + >>> hist_dist.cdf(np.min(data)) + 0.0 + + PDF and CDF follow the histogram + + >>> import matplotlib.pyplot as plt + >>> X = np.linspace(-5.0, 5.0, 100) + >>> fig, ax = plt.subplots() + >>> ax.set_title("PDF from Template") + >>> ax.hist(data, density=True, bins=100) + >>> ax.plot(X, hist_dist.pdf(X), label='PDF') + >>> ax.plot(X, hist_dist.cdf(X), label='CDF') + >>> ax.legend() + >>> fig.show() + + """ + _support_mask = rv_continuous._support_mask + + def __init__(self, histogram, *args, density=None, **kwargs): + """ + Create a new distribution using the given histogram + + Parameters + ---------- + histogram : tuple of array_like + Tuple containing two array_like objects. + The first containing the content of n bins, + the second containing the (n+1) bin boundaries. + In particular, the return value of np.histogram is accepted. + density : bool, optional + If False, assumes the histogram is proportional to counts per bin; + otherwise, assumes it is proportional to a density. + For constant bin widths, these are equivalent. + If None (default), sets ``density=True`` for backward + compatibility, but warns if the bin widths are variable. Set + `density` explicitly to silence the warning. + """ + self._histogram = histogram + self._density = density + if len(histogram) != 2: + raise ValueError("Expected length 2 for parameter histogram") + self._hpdf = np.asarray(histogram[0]) + self._hbins = np.asarray(histogram[1]) + if len(self._hpdf) + 1 != len(self._hbins): + raise ValueError("Number of elements in histogram content " + "and histogram boundaries do not match, " + "expected n and n+1.") + self._hbin_widths = self._hbins[1:] - self._hbins[:-1] + bins_vary = not np.allclose(self._hbin_widths, self._hbin_widths[0]) + if density is None and bins_vary: + message = ("Bin widths are not constant. Assuming `density=True`." + "Specify `density` explicitly to silence this warning.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + density = True + elif not density: + self._hpdf = self._hpdf / self._hbin_widths + + self._hpdf = self._hpdf / float(np.sum(self._hpdf * self._hbin_widths)) + self._hcdf = np.cumsum(self._hpdf * self._hbin_widths) + self._hpdf = np.hstack([0.0, self._hpdf, 0.0]) + self._hcdf = np.hstack([0.0, self._hcdf]) + # Set support + kwargs['a'] = self.a = self._hbins[0] + kwargs['b'] = self.b = self._hbins[-1] + super().__init__(*args, **kwargs) + + def _pdf(self, x): + """ + PDF of the histogram + """ + return self._hpdf[np.searchsorted(self._hbins, x, side='right')] + + def _cdf(self, x): + """ + CDF calculated from the histogram + """ + return np.interp(x, self._hbins, self._hcdf) + + def _ppf(self, x): + """ + Percentile function calculated from the histogram + """ + return np.interp(x, self._hcdf, self._hbins) + + def _munp(self, n): + """Compute the n-th non-central moment.""" + integrals = (self._hbins[1:]**(n+1) - self._hbins[:-1]**(n+1)) / (n+1) + return np.sum(self._hpdf[1:-1] * integrals) + + def _entropy(self): + """Compute entropy of distribution""" + res = _lazywhere(self._hpdf[1:-1] > 0.0, + (self._hpdf[1:-1],), + np.log, + 0.0) + return -np.sum(self._hpdf[1:-1] * res * self._hbin_widths) + + def _updated_ctor_param(self): + """ + Set the histogram as additional constructor argument + """ + dct = super()._updated_ctor_param() + dct['histogram'] = self._histogram + dct['density'] = self._density + return dct + + +class studentized_range_gen(rv_continuous): + r"""A studentized range continuous random variable. + + %(before_notes)s + + See Also + -------- + t: Student's t distribution + + Notes + ----- + The probability density function for `studentized_range` is: + + .. math:: + + f(x; k, \nu) = \frac{k(k-1)\nu^{\nu/2}}{\Gamma(\nu/2) + 2^{\nu/2-1}} \int_{0}^{\infty} \int_{-\infty}^{\infty} + s^{\nu} e^{-\nu s^2/2} \phi(z) \phi(sx + z) + [\Phi(sx + z) - \Phi(z)]^{k-2} \,dz \,ds + + for :math:`x ≥ 0`, :math:`k > 1`, and :math:`\nu > 0`. + + `studentized_range` takes ``k`` for :math:`k` and ``df`` for :math:`\nu` + as shape parameters. + + When :math:`\nu` exceeds 100,000, an asymptotic approximation (infinite + degrees of freedom) is used to compute the cumulative distribution + function [4]_ and probability distribution function. + + %(after_notes)s + + References + ---------- + + .. [1] "Studentized range distribution", + https://en.wikipedia.org/wiki/Studentized_range_distribution + .. [2] Batista, Ben Dêivide, et al. "Externally Studentized Normal Midrange + Distribution." Ciência e Agrotecnologia, vol. 41, no. 4, 2017, pp. + 378-389., doi:10.1590/1413-70542017414047716. + .. [3] Harter, H. Leon. "Tables of Range and Studentized Range." The Annals + of Mathematical Statistics, vol. 31, no. 4, 1960, pp. 1122-1147. + JSTOR, www.jstor.org/stable/2237810. Accessed 18 Feb. 2021. + .. [4] Lund, R. E., and J. R. Lund. "Algorithm AS 190: Probabilities and + Upper Quantiles for the Studentized Range." Journal of the Royal + Statistical Society. Series C (Applied Statistics), vol. 32, no. 2, + 1983, pp. 204-210. JSTOR, www.jstor.org/stable/2347300. Accessed 18 + Feb. 2021. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import studentized_range + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + + Display the probability density function (``pdf``): + + >>> k, df = 3, 10 + >>> x = np.linspace(studentized_range.ppf(0.01, k, df), + ... studentized_range.ppf(0.99, k, df), 100) + >>> ax.plot(x, studentized_range.pdf(x, k, df), + ... 'r-', lw=5, alpha=0.6, label='studentized_range pdf') + + Alternatively, the distribution object can be called (as a function) + to fix the shape, location and scale parameters. This returns a "frozen" + RV object holding the given parameters fixed. + + Freeze the distribution and display the frozen ``pdf``: + + >>> rv = studentized_range(k, df) + >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + + Check accuracy of ``cdf`` and ``ppf``: + + >>> vals = studentized_range.ppf([0.001, 0.5, 0.999], k, df) + >>> np.allclose([0.001, 0.5, 0.999], studentized_range.cdf(vals, k, df)) + True + + Rather than using (``studentized_range.rvs``) to generate random variates, + which is very slow for this distribution, we can approximate the inverse + CDF using an interpolator, and then perform inverse transform sampling + with this approximate inverse CDF. + + This distribution has an infinite but thin right tail, so we focus our + attention on the leftmost 99.9 percent. + + >>> a, b = studentized_range.ppf([0, .999], k, df) + >>> a, b + 0, 7.41058083802274 + + >>> from scipy.interpolate import interp1d + >>> rng = np.random.default_rng() + >>> xs = np.linspace(a, b, 50) + >>> cdf = studentized_range.cdf(xs, k, df) + # Create an interpolant of the inverse CDF + >>> ppf = interp1d(cdf, xs, fill_value='extrapolate') + # Perform inverse transform sampling using the interpolant + >>> r = ppf(rng.uniform(size=1000)) + + And compare the histogram: + + >>> ax.hist(r, density=True, histtype='stepfilled', alpha=0.2) + >>> ax.legend(loc='best', frameon=False) + >>> plt.show() + + """ + + def _argcheck(self, k, df): + return (k > 1) & (df > 0) + + def _shape_info(self): + ik = _ShapeInfo("k", False, (1, np.inf), (False, False)) + idf = _ShapeInfo("df", False, (0, np.inf), (False, False)) + return [ik, idf] + + def _fitstart(self, data): + # Default is k=1, but that is not a valid value of the parameter. + return super()._fitstart(data, args=(2, 1)) + + def _munp(self, K, k, df): + cython_symbol = '_studentized_range_moment' + _a, _b = self._get_support() + # all three of these are used to create a numpy array so they must + # be the same shape. + + def _single_moment(K, k, df): + log_const = _stats._studentized_range_pdf_logconst(k, df) + arg = [K, k, df, log_const] + usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p) + + llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data) + + ranges = [(-np.inf, np.inf), (0, np.inf), (_a, _b)] + opts = dict(epsabs=1e-11, epsrel=1e-12) + + return integrate.nquad(llc, ranges=ranges, opts=opts)[0] + + ufunc = np.frompyfunc(_single_moment, 3, 1) + return np.asarray(ufunc(K, k, df), dtype=np.float64)[()] + + def _pdf(self, x, k, df): + + def _single_pdf(q, k, df): + # The infinite form of the PDF is derived from the infinite + # CDF. + if df < 100000: + cython_symbol = '_studentized_range_pdf' + log_const = _stats._studentized_range_pdf_logconst(k, df) + arg = [q, k, df, log_const] + usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p) + ranges = [(-np.inf, np.inf), (0, np.inf)] + + else: + cython_symbol = '_studentized_range_pdf_asymptotic' + arg = [q, k] + usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p) + ranges = [(-np.inf, np.inf)] + + llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data) + opts = dict(epsabs=1e-11, epsrel=1e-12) + return integrate.nquad(llc, ranges=ranges, opts=opts)[0] + + ufunc = np.frompyfunc(_single_pdf, 3, 1) + return np.asarray(ufunc(x, k, df), dtype=np.float64)[()] + + def _cdf(self, x, k, df): + + def _single_cdf(q, k, df): + # "When the degrees of freedom V are infinite the probability + # integral takes [on a] simpler form," and a single asymptotic + # integral is evaluated rather than the standard double integral. + # (Lund, Lund, page 205) + if df < 100000: + cython_symbol = '_studentized_range_cdf' + log_const = _stats._studentized_range_cdf_logconst(k, df) + arg = [q, k, df, log_const] + usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p) + ranges = [(-np.inf, np.inf), (0, np.inf)] + + else: + cython_symbol = '_studentized_range_cdf_asymptotic' + arg = [q, k] + usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p) + ranges = [(-np.inf, np.inf)] + + llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data) + opts = dict(epsabs=1e-11, epsrel=1e-12) + return integrate.nquad(llc, ranges=ranges, opts=opts)[0] + + ufunc = np.frompyfunc(_single_cdf, 3, 1) + + # clip p-values to ensure they are in [0, 1]. + return np.clip(np.asarray(ufunc(x, k, df), dtype=np.float64)[()], 0, 1) + + +studentized_range = studentized_range_gen(name='studentized_range', a=0, + b=np.inf) + + +class rel_breitwigner_gen(rv_continuous): + r"""A relativistic Breit-Wigner random variable. + + %(before_notes)s + + See Also + -------- + cauchy: Cauchy distribution, also known as the Breit-Wigner distribution. + + Notes + ----- + + The probability density function for `rel_breitwigner` is + + .. math:: + + f(x, \rho) = \frac{k}{(x^2 - \rho^2)^2 + \rho^2} + + where + + .. math:: + k = \frac{2\sqrt{2}\rho^2\sqrt{\rho^2 + 1}} + {\pi\sqrt{\rho^2 + \rho\sqrt{\rho^2 + 1}}} + + The relativistic Breit-Wigner distribution is used in high energy physics + to model resonances [1]_. It gives the uncertainty in the invariant mass, + :math:`M` [2]_, of a resonance with characteristic mass :math:`M_0` and + decay-width :math:`\Gamma`, where :math:`M`, :math:`M_0` and :math:`\Gamma` + are expressed in natural units. In SciPy's parametrization, the shape + parameter :math:`\rho` is equal to :math:`M_0/\Gamma` and takes values in + :math:`(0, \infty)`. + + Equivalently, the relativistic Breit-Wigner distribution is said to give + the uncertainty in the center-of-mass energy :math:`E_{\text{cm}}`. In + natural units, the speed of light :math:`c` is equal to 1 and the invariant + mass :math:`M` is equal to the rest energy :math:`Mc^2`. In the + center-of-mass frame, the rest energy is equal to the total energy [3]_. + + %(after_notes)s + + :math:`\rho = M/\Gamma` and :math:`\Gamma` is the scale parameter. For + example, if one seeks to model the :math:`Z^0` boson with :math:`M_0 + \approx 91.1876 \text{ GeV}` and :math:`\Gamma \approx 2.4952\text{ GeV}` + [4]_ one can set ``rho=91.1876/2.4952`` and ``scale=2.4952``. + + To ensure a physically meaningful result when using the `fit` method, one + should set ``floc=0`` to fix the location parameter to 0. + + References + ---------- + .. [1] Relativistic Breit-Wigner distribution, Wikipedia, + https://en.wikipedia.org/wiki/Relativistic_Breit-Wigner_distribution + .. [2] Invariant mass, Wikipedia, + https://en.wikipedia.org/wiki/Invariant_mass + .. [3] Center-of-momentum frame, Wikipedia, + https://en.wikipedia.org/wiki/Center-of-momentum_frame + .. [4] M. Tanabashi et al. (Particle Data Group) Phys. Rev. D 98, 030001 - + Published 17 August 2018 + + %(example)s + + """ + def _argcheck(self, rho): + return rho > 0 + + def _shape_info(self): + return [_ShapeInfo("rho", False, (0, np.inf), (False, False))] + + def _pdf(self, x, rho): + # C = k / rho**2 + C = np.sqrt( + 2 * (1 + 1/rho**2) / (1 + np.sqrt(1 + 1/rho**2)) + ) * 2 / np.pi + with np.errstate(over='ignore'): + return C / (((x - rho)*(x + rho)/rho)**2 + 1) + + def _cdf(self, x, rho): + # C = k / (2 * rho**2) / np.sqrt(1 + 1/rho**2) + C = np.sqrt(2/(1 + np.sqrt(1 + 1/rho**2)))/np.pi + result = ( + np.sqrt(-1 + 1j/rho) + * np.arctan(x/np.sqrt(-rho*(rho + 1j))) + ) + result = C * 2 * np.imag(result) + # Sometimes above formula produces values greater than 1. + return np.clip(result, None, 1) + + def _munp(self, n, rho): + if n == 0: + return 1. + if n == 1: + # C = k / (2 * rho) + C = np.sqrt( + 2 * (1 + 1/rho**2) / (1 + np.sqrt(1 + 1/rho**2)) + ) / np.pi * rho + return C * (np.pi/2 + np.arctan(rho)) + if n == 2: + # C = pi * k / (4 * rho) + C = np.sqrt( + (1 + 1/rho**2) / (2 * (1 + np.sqrt(1 + 1/rho**2))) + ) * rho + result = (1 - rho * 1j) / np.sqrt(-1 - 1j/rho) + return 2 * C * np.real(result) + else: + return np.inf + + def _stats(self, rho): + # Returning None from stats makes public stats use _munp. + # nan values will be omitted from public stats. Skew and + # kurtosis are actually infinite. + return None, None, np.nan, np.nan + + @inherit_docstring_from(rv_continuous) + def fit(self, data, *args, **kwds): + # Override rv_continuous.fit to better handle case where floc is set. + data, _, floc, fscale = _check_fit_input_parameters( + self, data, args, kwds + ) + + censored = isinstance(data, CensoredData) + if censored: + if data.num_censored() == 0: + # There are no censored values in data, so replace the + # CensoredData instance with a regular array. + data = data._uncensored + censored = False + + if floc is None or censored: + return super().fit(data, *args, **kwds) + + if fscale is None: + # The interquartile range approximates the scale parameter gamma. + # The median approximates rho * gamma. + p25, p50, p75 = np.quantile(data - floc, [0.25, 0.5, 0.75]) + scale_0 = p75 - p25 + rho_0 = p50 / scale_0 + if not args: + args = [rho_0] + if "scale" not in kwds: + kwds["scale"] = scale_0 + else: + M_0 = np.median(data - floc) + rho_0 = M_0 / fscale + if not args: + args = [rho_0] + return super().fit(data, *args, **kwds) + + +rel_breitwigner = rel_breitwigner_gen(a=0.0, name="rel_breitwigner") + + +# Collect names of classes and objects in this module. +pairs = list(globals().copy().items()) +_distn_names, _distn_gen_names = get_distribution_names(pairs, rv_continuous) + +__all__ = _distn_names + _distn_gen_names + ['rv_histogram'] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_correlation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..2e47cd6180448c43e5f323ac003e80f1792c061b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_correlation.py @@ -0,0 +1,210 @@ +import numpy as np +from scipy import stats +from scipy.stats._stats_py import _SimpleNormal, SignificanceResult, _get_pvalue +from scipy.stats._axis_nan_policy import _axis_nan_policy_factory + + +__all__ = ['chatterjeexi'] + + +# TODO: +# - Adjust to respect dtype + + +def _xi_statistic(x, y, y_continuous): + # Compute xi correlation statistic + + # `axis=-1` is guaranteed by _axis_nan_policy decorator + n = x.shape[-1] + + # "Rearrange the data as (X(1), Y(1)), . . . ,(X(n), Y(n)) + # such that X(1) ≤ ··· ≤ X(n)" + j = np.argsort(x, axis=-1) + j, y = np.broadcast_arrays(j, y) + y = np.take_along_axis(y, j, axis=-1) + + # "Let ri be the rank of Y(i), that is, the number of j such that Y(j) ≤ Y(i)" + r = stats.rankdata(y, method='max', axis=-1) + # " additionally define li to be the number of j such that Y(j) ≥ Y(i)" + # Could probably compute this from r, but that can be an enhancement + l = stats.rankdata(-y, method='max', axis=-1) + + num = np.sum(np.abs(np.diff(r, axis=-1)), axis=-1) + if y_continuous: # [1] Eq. 1.1 + statistic = 1 - 3 * num / (n ** 2 - 1) + else: # [1] Eq. 1.2 + den = 2 * np.sum((n - l) * l, axis=-1) + statistic = 1 - n * num / den + + return statistic, r, l + + +def _xi_std(r, l, y_continuous): + # Compute asymptotic standard deviation of xi under null hypothesis of independence + + # `axis=-1` is guaranteed by _axis_nan_policy decorator + n = np.float64(r.shape[-1]) + + # "Suppose that X and Y are independent and Y is continuous. Then + # √n·ξn(X, Y) → N(0, 2/5) in distribution as n → ∞" + if y_continuous: # [1] Theorem 2.1 + return np.sqrt(2 / 5) / np.sqrt(n) + + # "Suppose that X and Y are independent. Then √n·ξn(X, Y) + # converges to N(0, τ²) in distribution as n → ∞ + # [1] Eq. 2.2 and surrounding math + i = np.arange(1, n + 1) + u = np.sort(r, axis=-1) + v = np.cumsum(u, axis=-1) + an = 1 / n**4 * np.sum((2*n - 2*i + 1) * u**2, axis=-1) + bn = 1 / n**5 * np.sum((v + (n - i)*u)**2, axis=-1) + cn = 1 / n**3 * np.sum((2*n - 2*i + 1) * u, axis=-1) + dn = 1 / n**3 * np.sum((l * (n - l)), axis=-1) + tau2 = (an - 2*bn + cn**2) / dn**2 + + return np.sqrt(tau2) / np.sqrt(n) + + +def _chatterjeexi_iv(y_continuous, method): + # Input validation for `chatterjeexi` + # x, y, `axis` input validation taken care of by decorator + + if y_continuous not in {True, False}: + raise ValueError('`y_continuous` must be boolean.') + + if not isinstance(method, stats.PermutationMethod): + method = method.lower() + message = "`method` must be 'asymptotic' or a `PermutationMethod` instance." + if method != 'asymptotic': + raise ValueError(message) + + return y_continuous, method + + +def _unpack(res): + return res.statistic, res.pvalue + + +@_axis_nan_policy_factory(SignificanceResult, paired=True, n_samples=2, + result_to_tuple=_unpack, n_outputs=2, too_small=1) +def chatterjeexi(x, y, *, axis=0, y_continuous=False, method='asymptotic'): + r"""Compute the xi correlation and perform a test of independence + + The xi correlation coefficient is a measure of association between two + variables; the value tends to be close to zero when the variables are + independent and close to 1 when there is a strong association. Unlike + other correlation coefficients, the xi correlation is effective even + when the association is not monotonic. + + Parameters + ---------- + x, y : array-like + The samples: corresponding observations of the independent and + dependent variable. The (N-d) arrays must be broadcastable. + axis : int, default: 0 + Axis along which to perform the test. + method : 'asymptotic' or `PermutationMethod` instance, optional + Selects the method used to calculate the *p*-value. + Default is 'asymptotic'. The following options are available. + + * ``'asymptotic'``: compares the standardized test statistic + against the normal distribution. + * `PermutationMethod` instance. In this case, the p-value + is computed using `permutation_test` with the provided + configuration options and other appropriate settings. + + y_continuous : bool, default: False + Whether `y` is assumed to be drawn from a continuous distribution. + If `y` is drawn from a continuous distribution, results are valid + whether this is assumed or not, but enabling this assumption will + result in faster computation and typically produce similar results. + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + The xi correlation statistic. + pvalue : float + The associated *p*-value: the probability of a statistic at least as + high as the observed value under the null hypothesis of independence. + + See Also + -------- + scipy.stats.pearsonr, scipy.stats.spearmanr, scipy.stats.kendalltau + + Notes + ----- + There is currently no special handling of ties in `x`; they are broken arbitrarily + by the implementation. + + [1]_ notes that the statistic is not symmetric in `x` and `y` *by design*: + "...we may want to understand if :math:`Y` is a function :math:`X`, and not just + if one of the variables is a function of the other." See [1]_ Remark 1. + + References + ---------- + .. [1] Chatterjee, Sourav. "A new coefficient of correlation." Journal of + the American Statistical Association 116.536 (2021): 2009-2022. + :doi:`10.1080/01621459.2020.1758115`. + + Examples + -------- + Generate perfectly correlated data, and observe that the xi correlation is + nearly 1.0. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(348932549825235) + >>> x = rng.uniform(0, 10, size=100) + >>> y = np.sin(x) + >>> res = stats.chatterjeexi(x, y) + >>> res.statistic + np.float64(0.9012901290129013) + + The probability of observing such a high value of the statistic under the + null hypothesis of independence is very low. + + >>> res.pvalue + np.float64(2.2206974648177804e-46) + + As noise is introduced, the correlation coefficient decreases. + + >>> noise = rng.normal(scale=[[0.1], [0.5], [1]], size=(3, 100)) + >>> res = stats.chatterjeexi(x, y + noise, axis=-1) + >>> res.statistic + array([0.79507951, 0.41824182, 0.16651665]) + + Because the distribution of `y` is continuous, it is valid to pass + ``y_continuous=True``. The statistic is identical, and the p-value + (not shown) is only slightly different. + + >>> stats.chatterjeexi(x, y + noise, y_continuous=True, axis=-1).statistic + array([0.79507951, 0.41824182, 0.16651665]) + + """ + # x, y, `axis` input validation taken care of by decorator + # In fact, `axis` is guaranteed to be -1 + y_continuous, method = _chatterjeexi_iv(y_continuous, method) + + # A highly negative statistic is possible, e.g. + # x = np.arange(100.), y = (x % 2 == 0) + # Unclear whether we should expose `alternative`, though. + alternative = 'greater' + + if method == 'asymptotic': + xi, r, l = _xi_statistic(x, y, y_continuous) + std = _xi_std(r, l, y_continuous) + norm = _SimpleNormal() + pvalue = _get_pvalue(xi / std, norm, alternative=alternative) + elif isinstance(method, stats.PermutationMethod): + res = stats.permutation_test( + # Could be faster if we just permuted the ranks; for now, keep it simple. + data=(y,), statistic=lambda y, axis: _xi_statistic(x, y, y_continuous)[0], + alternative=alternative, permutation_type='pairings', **method._asdict(), + axis=-1) # `axis=-1` is guaranteed by _axis_nan_policy decorator + + xi, pvalue = res.statistic, res.pvalue + + return SignificanceResult(xi, pvalue) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_covariance.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_covariance.py new file mode 100644 index 0000000000000000000000000000000000000000..2dde85d0bac9c5f38e9a97ca71194132f3a865af --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_covariance.py @@ -0,0 +1,633 @@ +from functools import cached_property + +import numpy as np +from scipy import linalg +from scipy.stats import _multivariate + + +__all__ = ["Covariance"] + + +class Covariance: + """ + Representation of a covariance matrix + + Calculations involving covariance matrices (e.g. data whitening, + multivariate normal function evaluation) are often performed more + efficiently using a decomposition of the covariance matrix instead of the + covariance matrix itself. This class allows the user to construct an + object representing a covariance matrix using any of several + decompositions and perform calculations using a common interface. + + .. note:: + + The `Covariance` class cannot be instantiated directly. Instead, use + one of the factory methods (e.g. `Covariance.from_diagonal`). + + Examples + -------- + The `Covariance` class is used by calling one of its + factory methods to create a `Covariance` object, then pass that + representation of the `Covariance` matrix as a shape parameter of a + multivariate distribution. + + For instance, the multivariate normal distribution can accept an array + representing a covariance matrix: + + >>> from scipy import stats + >>> import numpy as np + >>> d = [1, 2, 3] + >>> A = np.diag(d) # a diagonal covariance matrix + >>> x = [4, -2, 5] # a point of interest + >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=A) + >>> dist.pdf(x) + 4.9595685102808205e-08 + + but the calculations are performed in a very generic way that does not + take advantage of any special properties of the covariance matrix. Because + our covariance matrix is diagonal, we can use ``Covariance.from_diagonal`` + to create an object representing the covariance matrix, and + `multivariate_normal` can use this to compute the probability density + function more efficiently. + + >>> cov = stats.Covariance.from_diagonal(d) + >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=cov) + >>> dist.pdf(x) + 4.9595685102808205e-08 + + """ + def __init__(self): + message = ("The `Covariance` class cannot be instantiated directly. " + "Please use one of the factory methods " + "(e.g. `Covariance.from_diagonal`).") + raise NotImplementedError(message) + + @staticmethod + def from_diagonal(diagonal): + r""" + Return a representation of a covariance matrix from its diagonal. + + Parameters + ---------- + diagonal : array_like + The diagonal elements of a diagonal matrix. + + Notes + ----- + Let the diagonal elements of a diagonal covariance matrix :math:`D` be + stored in the vector :math:`d`. + + When all elements of :math:`d` are strictly positive, whitening of a + data point :math:`x` is performed by computing + :math:`x \cdot d^{-1/2}`, where the inverse square root can be taken + element-wise. + :math:`\log\det{D}` is calculated as :math:`-2 \sum(\log{d})`, + where the :math:`\log` operation is performed element-wise. + + This `Covariance` class supports singular covariance matrices. When + computing ``_log_pdet``, non-positive elements of :math:`d` are + ignored. Whitening is not well defined when the point to be whitened + does not lie in the span of the columns of the covariance matrix. The + convention taken here is to treat the inverse square root of + non-positive elements of :math:`d` as zeros. + + Examples + -------- + Prepare a symmetric positive definite covariance matrix ``A`` and a + data point ``x``. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> n = 5 + >>> A = np.diag(rng.random(n)) + >>> x = rng.random(size=n) + + Extract the diagonal from ``A`` and create the `Covariance` object. + + >>> d = np.diag(A) + >>> cov = stats.Covariance.from_diagonal(d) + + Compare the functionality of the `Covariance` object against a + reference implementations. + + >>> res = cov.whiten(x) + >>> ref = np.diag(d**-0.5) @ x + >>> np.allclose(res, ref) + True + >>> res = cov.log_pdet + >>> ref = np.linalg.slogdet(A)[-1] + >>> np.allclose(res, ref) + True + + """ + return CovViaDiagonal(diagonal) + + @staticmethod + def from_precision(precision, covariance=None): + r""" + Return a representation of a covariance from its precision matrix. + + Parameters + ---------- + precision : array_like + The precision matrix; that is, the inverse of a square, symmetric, + positive definite covariance matrix. + covariance : array_like, optional + The square, symmetric, positive definite covariance matrix. If not + provided, this may need to be calculated (e.g. to evaluate the + cumulative distribution function of + `scipy.stats.multivariate_normal`) by inverting `precision`. + + Notes + ----- + Let the covariance matrix be :math:`A`, its precision matrix be + :math:`P = A^{-1}`, and :math:`L` be the lower Cholesky factor such + that :math:`L L^T = P`. + Whitening of a data point :math:`x` is performed by computing + :math:`x^T L`. :math:`\log\det{A}` is calculated as + :math:`-2tr(\log{L})`, where the :math:`\log` operation is performed + element-wise. + + This `Covariance` class does not support singular covariance matrices + because the precision matrix does not exist for a singular covariance + matrix. + + Examples + -------- + Prepare a symmetric positive definite precision matrix ``P`` and a + data point ``x``. (If the precision matrix is not already available, + consider the other factory methods of the `Covariance` class.) + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> n = 5 + >>> P = rng.random(size=(n, n)) + >>> P = P @ P.T # a precision matrix must be positive definite + >>> x = rng.random(size=n) + + Create the `Covariance` object. + + >>> cov = stats.Covariance.from_precision(P) + + Compare the functionality of the `Covariance` object against + reference implementations. + + >>> res = cov.whiten(x) + >>> ref = x @ np.linalg.cholesky(P) + >>> np.allclose(res, ref) + True + >>> res = cov.log_pdet + >>> ref = -np.linalg.slogdet(P)[-1] + >>> np.allclose(res, ref) + True + + """ + return CovViaPrecision(precision, covariance) + + @staticmethod + def from_cholesky(cholesky): + r""" + Representation of a covariance provided via the (lower) Cholesky factor + + Parameters + ---------- + cholesky : array_like + The lower triangular Cholesky factor of the covariance matrix. + + Notes + ----- + Let the covariance matrix be :math:`A` and :math:`L` be the lower + Cholesky factor such that :math:`L L^T = A`. + Whitening of a data point :math:`x` is performed by computing + :math:`L^{-1} x`. :math:`\log\det{A}` is calculated as + :math:`2tr(\log{L})`, where the :math:`\log` operation is performed + element-wise. + + This `Covariance` class does not support singular covariance matrices + because the Cholesky decomposition does not exist for a singular + covariance matrix. + + Examples + -------- + Prepare a symmetric positive definite covariance matrix ``A`` and a + data point ``x``. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> n = 5 + >>> A = rng.random(size=(n, n)) + >>> A = A @ A.T # make the covariance symmetric positive definite + >>> x = rng.random(size=n) + + Perform the Cholesky decomposition of ``A`` and create the + `Covariance` object. + + >>> L = np.linalg.cholesky(A) + >>> cov = stats.Covariance.from_cholesky(L) + + Compare the functionality of the `Covariance` object against + reference implementation. + + >>> from scipy.linalg import solve_triangular + >>> res = cov.whiten(x) + >>> ref = solve_triangular(L, x, lower=True) + >>> np.allclose(res, ref) + True + >>> res = cov.log_pdet + >>> ref = np.linalg.slogdet(A)[-1] + >>> np.allclose(res, ref) + True + + """ + return CovViaCholesky(cholesky) + + @staticmethod + def from_eigendecomposition(eigendecomposition): + r""" + Representation of a covariance provided via eigendecomposition + + Parameters + ---------- + eigendecomposition : sequence + A sequence (nominally a tuple) containing the eigenvalue and + eigenvector arrays as computed by `scipy.linalg.eigh` or + `numpy.linalg.eigh`. + + Notes + ----- + Let the covariance matrix be :math:`A`, let :math:`V` be matrix of + eigenvectors, and let :math:`W` be the diagonal matrix of eigenvalues + such that `V W V^T = A`. + + When all of the eigenvalues are strictly positive, whitening of a + data point :math:`x` is performed by computing + :math:`x^T (V W^{-1/2})`, where the inverse square root can be taken + element-wise. + :math:`\log\det{A}` is calculated as :math:`tr(\log{W})`, + where the :math:`\log` operation is performed element-wise. + + This `Covariance` class supports singular covariance matrices. When + computing ``_log_pdet``, non-positive eigenvalues are ignored. + Whitening is not well defined when the point to be whitened + does not lie in the span of the columns of the covariance matrix. The + convention taken here is to treat the inverse square root of + non-positive eigenvalues as zeros. + + Examples + -------- + Prepare a symmetric positive definite covariance matrix ``A`` and a + data point ``x``. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> n = 5 + >>> A = rng.random(size=(n, n)) + >>> A = A @ A.T # make the covariance symmetric positive definite + >>> x = rng.random(size=n) + + Perform the eigendecomposition of ``A`` and create the `Covariance` + object. + + >>> w, v = np.linalg.eigh(A) + >>> cov = stats.Covariance.from_eigendecomposition((w, v)) + + Compare the functionality of the `Covariance` object against + reference implementations. + + >>> res = cov.whiten(x) + >>> ref = x @ (v @ np.diag(w**-0.5)) + >>> np.allclose(res, ref) + True + >>> res = cov.log_pdet + >>> ref = np.linalg.slogdet(A)[-1] + >>> np.allclose(res, ref) + True + + """ + return CovViaEigendecomposition(eigendecomposition) + + def whiten(self, x): + """ + Perform a whitening transformation on data. + + "Whitening" ("white" as in "white noise", in which each frequency has + equal magnitude) transforms a set of random variables into a new set of + random variables with unit-diagonal covariance. When a whitening + transform is applied to a sample of points distributed according to + a multivariate normal distribution with zero mean, the covariance of + the transformed sample is approximately the identity matrix. + + Parameters + ---------- + x : array_like + An array of points. The last dimension must correspond with the + dimensionality of the space, i.e., the number of columns in the + covariance matrix. + + Returns + ------- + x_ : array_like + The transformed array of points. + + References + ---------- + .. [1] "Whitening Transformation". Wikipedia. + https://en.wikipedia.org/wiki/Whitening_transformation + .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of + coloring linear transformation". Transactions of VSB 18.2 + (2018): 31-35. :doi:`10.31490/tces-2018-0013` + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> n = 3 + >>> A = rng.random(size=(n, n)) + >>> cov_array = A @ A.T # make matrix symmetric positive definite + >>> precision = np.linalg.inv(cov_array) + >>> cov_object = stats.Covariance.from_precision(precision) + >>> x = rng.multivariate_normal(np.zeros(n), cov_array, size=(10000)) + >>> x_ = cov_object.whiten(x) + >>> np.cov(x_, rowvar=False) # near-identity covariance + array([[0.97862122, 0.00893147, 0.02430451], + [0.00893147, 0.96719062, 0.02201312], + [0.02430451, 0.02201312, 0.99206881]]) + + """ + return self._whiten(np.asarray(x)) + + def colorize(self, x): + """ + Perform a colorizing transformation on data. + + "Colorizing" ("color" as in "colored noise", in which different + frequencies may have different magnitudes) transforms a set of + uncorrelated random variables into a new set of random variables with + the desired covariance. When a coloring transform is applied to a + sample of points distributed according to a multivariate normal + distribution with identity covariance and zero mean, the covariance of + the transformed sample is approximately the covariance matrix used + in the coloring transform. + + Parameters + ---------- + x : array_like + An array of points. The last dimension must correspond with the + dimensionality of the space, i.e., the number of columns in the + covariance matrix. + + Returns + ------- + x_ : array_like + The transformed array of points. + + References + ---------- + .. [1] "Whitening Transformation". Wikipedia. + https://en.wikipedia.org/wiki/Whitening_transformation + .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of + coloring linear transformation". Transactions of VSB 18.2 + (2018): 31-35. :doi:`10.31490/tces-2018-0013` + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(1638083107694713882823079058616272161) + >>> n = 3 + >>> A = rng.random(size=(n, n)) + >>> cov_array = A @ A.T # make matrix symmetric positive definite + >>> cholesky = np.linalg.cholesky(cov_array) + >>> cov_object = stats.Covariance.from_cholesky(cholesky) + >>> x = rng.multivariate_normal(np.zeros(n), np.eye(n), size=(10000)) + >>> x_ = cov_object.colorize(x) + >>> cov_data = np.cov(x_, rowvar=False) + >>> np.allclose(cov_data, cov_array, rtol=3e-2) + True + """ + return self._colorize(np.asarray(x)) + + @property + def log_pdet(self): + """ + Log of the pseudo-determinant of the covariance matrix + """ + return np.array(self._log_pdet, dtype=float)[()] + + @property + def rank(self): + """ + Rank of the covariance matrix + """ + return np.array(self._rank, dtype=int)[()] + + @property + def covariance(self): + """ + Explicit representation of the covariance matrix + """ + return self._covariance + + @property + def shape(self): + """ + Shape of the covariance array + """ + return self._shape + + def _validate_matrix(self, A, name): + A = np.atleast_2d(A) + m, n = A.shape[-2:] + if m != n or A.ndim != 2 or not (np.issubdtype(A.dtype, np.integer) or + np.issubdtype(A.dtype, np.floating)): + message = (f"The input `{name}` must be a square, " + "two-dimensional array of real numbers.") + raise ValueError(message) + return A + + def _validate_vector(self, A, name): + A = np.atleast_1d(A) + if A.ndim != 1 or not (np.issubdtype(A.dtype, np.integer) or + np.issubdtype(A.dtype, np.floating)): + message = (f"The input `{name}` must be a one-dimensional array " + "of real numbers.") + raise ValueError(message) + return A + + +class CovViaPrecision(Covariance): + + def __init__(self, precision, covariance=None): + precision = self._validate_matrix(precision, 'precision') + if covariance is not None: + covariance = self._validate_matrix(covariance, 'covariance') + message = "`precision.shape` must equal `covariance.shape`." + if precision.shape != covariance.shape: + raise ValueError(message) + + self._chol_P = np.linalg.cholesky(precision) + self._log_pdet = -2*np.log(np.diag(self._chol_P)).sum(axis=-1) + self._rank = precision.shape[-1] # must be full rank if invertible + self._precision = precision + self._cov_matrix = covariance + self._shape = precision.shape + self._allow_singular = False + + def _whiten(self, x): + return x @ self._chol_P + + @cached_property + def _covariance(self): + n = self._shape[-1] + return (linalg.cho_solve((self._chol_P, True), np.eye(n)) + if self._cov_matrix is None else self._cov_matrix) + + def _colorize(self, x): + return linalg.solve_triangular(self._chol_P.T, x.T, lower=False).T + + +def _dot_diag(x, d): + # If d were a full diagonal matrix, x @ d would always do what we want. + # Special treatment is needed for n-dimensional `d` in which each row + # includes only the diagonal elements of a covariance matrix. + return x * d if x.ndim < 2 else x * np.expand_dims(d, -2) + + +class CovViaDiagonal(Covariance): + + def __init__(self, diagonal): + diagonal = self._validate_vector(diagonal, 'diagonal') + + i_zero = diagonal <= 0 + positive_diagonal = np.array(diagonal, dtype=np.float64) + + positive_diagonal[i_zero] = 1 # ones don't affect determinant + self._log_pdet = np.sum(np.log(positive_diagonal), axis=-1) + + psuedo_reciprocals = 1 / np.sqrt(positive_diagonal) + psuedo_reciprocals[i_zero] = 0 + + self._sqrt_diagonal = np.sqrt(diagonal) + self._LP = psuedo_reciprocals + self._rank = positive_diagonal.shape[-1] - i_zero.sum(axis=-1) + self._covariance = np.apply_along_axis(np.diag, -1, diagonal) + self._i_zero = i_zero + self._shape = self._covariance.shape + self._allow_singular = True + + def _whiten(self, x): + return _dot_diag(x, self._LP) + + def _colorize(self, x): + return _dot_diag(x, self._sqrt_diagonal) + + def _support_mask(self, x): + """ + Check whether x lies in the support of the distribution. + """ + return ~np.any(_dot_diag(x, self._i_zero), axis=-1) + + +class CovViaCholesky(Covariance): + + def __init__(self, cholesky): + L = self._validate_matrix(cholesky, 'cholesky') + + self._factor = L + self._log_pdet = 2*np.log(np.diag(self._factor)).sum(axis=-1) + self._rank = L.shape[-1] # must be full rank for cholesky + self._shape = L.shape + self._allow_singular = False + + @cached_property + def _covariance(self): + return self._factor @ self._factor.T + + def _whiten(self, x): + res = linalg.solve_triangular(self._factor, x.T, lower=True).T + return res + + def _colorize(self, x): + return x @ self._factor.T + + +class CovViaEigendecomposition(Covariance): + + def __init__(self, eigendecomposition): + eigenvalues, eigenvectors = eigendecomposition + eigenvalues = self._validate_vector(eigenvalues, 'eigenvalues') + eigenvectors = self._validate_matrix(eigenvectors, 'eigenvectors') + message = ("The shapes of `eigenvalues` and `eigenvectors` " + "must be compatible.") + try: + eigenvalues = np.expand_dims(eigenvalues, -2) + eigenvectors, eigenvalues = np.broadcast_arrays(eigenvectors, + eigenvalues) + eigenvalues = eigenvalues[..., 0, :] + except ValueError: + raise ValueError(message) + + i_zero = eigenvalues <= 0 + positive_eigenvalues = np.array(eigenvalues, dtype=np.float64) + + positive_eigenvalues[i_zero] = 1 # ones don't affect determinant + self._log_pdet = np.sum(np.log(positive_eigenvalues), axis=-1) + + psuedo_reciprocals = 1 / np.sqrt(positive_eigenvalues) + psuedo_reciprocals[i_zero] = 0 + + self._LP = eigenvectors * psuedo_reciprocals + self._LA = eigenvectors * np.sqrt(eigenvalues) + self._rank = positive_eigenvalues.shape[-1] - i_zero.sum(axis=-1) + self._w = eigenvalues + self._v = eigenvectors + self._shape = eigenvectors.shape + self._null_basis = eigenvectors * i_zero + # This is only used for `_support_mask`, not to decide whether + # the covariance is singular or not. + self._eps = _multivariate._eigvalsh_to_eps(eigenvalues) * 10**3 + self._allow_singular = True + + def _whiten(self, x): + return x @ self._LP + + def _colorize(self, x): + return x @ self._LA.T + + @cached_property + def _covariance(self): + return (self._v * self._w) @ self._v.T + + def _support_mask(self, x): + """ + Check whether x lies in the support of the distribution. + """ + residual = np.linalg.norm(x @ self._null_basis, axis=-1) + in_support = residual < self._eps + return in_support + + +class CovViaPSD(Covariance): + """ + Representation of a covariance provided via an instance of _PSD + """ + + def __init__(self, psd): + self._LP = psd.U + self._log_pdet = psd.log_pdet + self._rank = psd.rank + self._covariance = psd._M + self._shape = psd._M.shape + self._psd = psd + self._allow_singular = False # by default + + def _whiten(self, x): + return x @ self._LP + + def _support_mask(self, x): + return self._psd._support_mask(x) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_crosstab.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_crosstab.py new file mode 100644 index 0000000000000000000000000000000000000000..e938eacad04467068985aacc7134248ab6ec44a6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_crosstab.py @@ -0,0 +1,204 @@ +import numpy as np +from scipy.sparse import coo_matrix +from scipy._lib._bunch import _make_tuple_bunch + + +CrosstabResult = _make_tuple_bunch( + "CrosstabResult", ["elements", "count"] +) + + +def crosstab(*args, levels=None, sparse=False): + """ + Return table of counts for each possible unique combination in ``*args``. + + When ``len(args) > 1``, the array computed by this function is + often referred to as a *contingency table* [1]_. + + The arguments must be sequences with the same length. The second return + value, `count`, is an integer array with ``len(args)`` dimensions. If + `levels` is None, the shape of `count` is ``(n0, n1, ...)``, where ``nk`` + is the number of unique elements in ``args[k]``. + + Parameters + ---------- + *args : sequences + A sequence of sequences whose unique aligned elements are to be + counted. The sequences in args must all be the same length. + levels : sequence, optional + If `levels` is given, it must be a sequence that is the same length as + `args`. Each element in `levels` is either a sequence or None. If it + is a sequence, it gives the values in the corresponding sequence in + `args` that are to be counted. If any value in the sequences in `args` + does not occur in the corresponding sequence in `levels`, that value + is ignored and not counted in the returned array `count`. The default + value of `levels` for ``args[i]`` is ``np.unique(args[i])`` + sparse : bool, optional + If True, return a sparse matrix. The matrix will be an instance of + the `scipy.sparse.coo_matrix` class. Because SciPy's sparse matrices + must be 2-d, only two input sequences are allowed when `sparse` is + True. Default is False. + + Returns + ------- + res : CrosstabResult + An object containing the following attributes: + + elements : tuple of numpy.ndarrays. + Tuple of length ``len(args)`` containing the arrays of elements + that are counted in `count`. These can be interpreted as the + labels of the corresponding dimensions of `count`. If `levels` was + given, then if ``levels[i]`` is not None, ``elements[i]`` will + hold the values given in ``levels[i]``. + count : numpy.ndarray or scipy.sparse.coo_matrix + Counts of the unique elements in ``zip(*args)``, stored in an + array. Also known as a *contingency table* when ``len(args) > 1``. + + See Also + -------- + numpy.unique + + Notes + ----- + .. versionadded:: 1.7.0 + + References + ---------- + .. [1] "Contingency table", http://en.wikipedia.org/wiki/Contingency_table + + Examples + -------- + >>> from scipy.stats.contingency import crosstab + + Given the lists `a` and `x`, create a contingency table that counts the + frequencies of the corresponding pairs. + + >>> a = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'] + >>> x = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z'] + >>> res = crosstab(a, x) + >>> avals, xvals = res.elements + >>> avals + array(['A', 'B'], dtype='>> xvals + array(['X', 'Y', 'Z'], dtype='>> res.count + array([[2, 3, 0], + [1, 0, 4]]) + + So ``('A', 'X')`` occurs twice, ``('A', 'Y')`` occurs three times, etc. + + Higher dimensional contingency tables can be created. + + >>> p = [0, 0, 0, 0, 1, 1, 1, 0, 0, 1] + >>> res = crosstab(a, x, p) + >>> res.count + array([[[2, 0], + [2, 1], + [0, 0]], + [[1, 0], + [0, 0], + [1, 3]]]) + >>> res.count.shape + (2, 3, 2) + + The values to be counted can be set by using the `levels` argument. + It allows the elements of interest in each input sequence to be + given explicitly instead finding the unique elements of the sequence. + + For example, suppose one of the arguments is an array containing the + answers to a survey question, with integer values 1 to 4. Even if the + value 1 does not occur in the data, we want an entry for it in the table. + + >>> q1 = [2, 3, 3, 2, 4, 4, 2, 3, 4, 4, 4, 3, 3, 3, 4] # 1 does not occur. + >>> q2 = [4, 4, 2, 2, 2, 4, 1, 1, 2, 2, 4, 2, 2, 2, 4] # 3 does not occur. + >>> options = [1, 2, 3, 4] + >>> res = crosstab(q1, q2, levels=(options, options)) + >>> res.count + array([[0, 0, 0, 0], + [1, 1, 0, 1], + [1, 4, 0, 1], + [0, 3, 0, 3]]) + + If `levels` is given, but an element of `levels` is None, the unique values + of the corresponding argument are used. For example, + + >>> res = crosstab(q1, q2, levels=(None, options)) + >>> res.elements + [array([2, 3, 4]), [1, 2, 3, 4]] + >>> res.count + array([[1, 1, 0, 1], + [1, 4, 0, 1], + [0, 3, 0, 3]]) + + If we want to ignore the pairs where 4 occurs in ``q2``, we can + give just the values [1, 2] to `levels`, and the 4 will be ignored: + + >>> res = crosstab(q1, q2, levels=(None, [1, 2])) + >>> res.elements + [array([2, 3, 4]), [1, 2]] + >>> res.count + array([[1, 1], + [1, 4], + [0, 3]]) + + Finally, let's repeat the first example, but return a sparse matrix: + + >>> res = crosstab(a, x, sparse=True) + >>> res.count + + >>> res.count.toarray() + array([[2, 3, 0], + [1, 0, 4]]) + + """ + nargs = len(args) + if nargs == 0: + raise TypeError("At least one input sequence is required.") + + len0 = len(args[0]) + if not all(len(a) == len0 for a in args[1:]): + raise ValueError("All input sequences must have the same length.") + + if sparse and nargs != 2: + raise ValueError("When `sparse` is True, only two input sequences " + "are allowed.") + + if levels is None: + # Call np.unique with return_inverse=True on each argument. + actual_levels, indices = zip(*[np.unique(a, return_inverse=True) + for a in args]) + else: + # `levels` is not None... + if len(levels) != nargs: + raise ValueError('len(levels) must equal the number of input ' + 'sequences') + + args = [np.asarray(arg) for arg in args] + mask = np.zeros((nargs, len0), dtype=np.bool_) + inv = np.zeros((nargs, len0), dtype=np.intp) + actual_levels = [] + for k, (levels_list, arg) in enumerate(zip(levels, args)): + if levels_list is None: + levels_list, inv[k, :] = np.unique(arg, return_inverse=True) + mask[k, :] = True + else: + q = arg == np.asarray(levels_list).reshape(-1, 1) + mask[k, :] = np.any(q, axis=0) + qnz = q.T.nonzero() + inv[k, qnz[0]] = qnz[1] + actual_levels.append(levels_list) + + mask_all = mask.all(axis=0) + indices = tuple(inv[:, mask_all]) + + if sparse: + count = coo_matrix((np.ones(len(indices[0]), dtype=int), + (indices[0], indices[1]))) + count.sum_duplicates() + else: + shape = [len(u) for u in actual_levels] + count = np.zeros(shape, dtype=int) + np.add.at(count, indices, 1) + + return CrosstabResult(actual_levels, count) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_discrete_distns.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_discrete_distns.py new file mode 100644 index 0000000000000000000000000000000000000000..138c56d76a09591533268db35a9bd613f2a034f8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_discrete_distns.py @@ -0,0 +1,2091 @@ +# +# Author: Travis Oliphant 2002-2011 with contributions from +# SciPy Developers 2004-2011 +# +from functools import partial + +from scipy import special +from scipy.special import entr, logsumexp, betaln, gammaln as gamln, zeta +from scipy._lib._util import _lazywhere, rng_integers +from scipy.interpolate import interp1d + +from numpy import floor, ceil, log, exp, sqrt, log1p, expm1, tanh, cosh, sinh + +import numpy as np + +from ._distn_infrastructure import (rv_discrete, get_distribution_names, + _vectorize_rvs_over_shapes, + _ShapeInfo, _isintegral, + rv_discrete_frozen) +from ._biasedurn import (_PyFishersNCHypergeometric, + _PyWalleniusNCHypergeometric, + _PyStochasticLib3) +from ._stats_pythran import _poisson_binom + +import scipy.special._ufuncs as scu + + + +class binom_gen(rv_discrete): + r"""A binomial discrete random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `binom` is: + + .. math:: + + f(k) = \binom{n}{k} p^k (1-p)^{n-k} + + for :math:`k \in \{0, 1, \dots, n\}`, :math:`0 \leq p \leq 1` + + `binom` takes :math:`n` and :math:`p` as shape parameters, + where :math:`p` is the probability of a single success + and :math:`1-p` is the probability of a single failure. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pmf``, ``cdf``, ``sf``, ``ppf`` and ``isf`` + methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + See Also + -------- + hypergeom, nbinom, nhypergeom + + """ + def _shape_info(self): + return [_ShapeInfo("n", True, (0, np.inf), (True, False)), + _ShapeInfo("p", False, (0, 1), (True, True))] + + def _rvs(self, n, p, size=None, random_state=None): + return random_state.binomial(n, p, size) + + def _argcheck(self, n, p): + return (n >= 0) & _isintegral(n) & (p >= 0) & (p <= 1) + + def _get_support(self, n, p): + return self.a, n + + def _logpmf(self, x, n, p): + k = floor(x) + combiln = (gamln(n+1) - (gamln(k+1) + gamln(n-k+1))) + return combiln + special.xlogy(k, p) + special.xlog1py(n-k, -p) + + def _pmf(self, x, n, p): + # binom.pmf(k) = choose(n, k) * p**k * (1-p)**(n-k) + return scu._binom_pmf(x, n, p) + + def _cdf(self, x, n, p): + k = floor(x) + return scu._binom_cdf(k, n, p) + + def _sf(self, x, n, p): + k = floor(x) + return scu._binom_sf(k, n, p) + + def _isf(self, x, n, p): + return scu._binom_isf(x, n, p) + + def _ppf(self, q, n, p): + return scu._binom_ppf(q, n, p) + + def _stats(self, n, p, moments='mv'): + mu = n * p + var = mu - n * np.square(p) + g1, g2 = None, None + if 's' in moments: + pq = p - np.square(p) + npq_sqrt = np.sqrt(n * pq) + t1 = np.reciprocal(npq_sqrt) + t2 = (2.0 * p) / npq_sqrt + g1 = t1 - t2 + if 'k' in moments: + pq = p - np.square(p) + npq = n * pq + t1 = np.reciprocal(npq) + t2 = 6.0/n + g2 = t1 - t2 + return mu, var, g1, g2 + + def _entropy(self, n, p): + k = np.r_[0:n + 1] + vals = self._pmf(k, n, p) + return np.sum(entr(vals), axis=0) + + +binom = binom_gen(name='binom') + + +class bernoulli_gen(binom_gen): + r"""A Bernoulli discrete random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `bernoulli` is: + + .. math:: + + f(k) = \begin{cases}1-p &\text{if } k = 0\\ + p &\text{if } k = 1\end{cases} + + for :math:`k` in :math:`\{0, 1\}`, :math:`0 \leq p \leq 1` + + `bernoulli` takes :math:`p` as shape parameter, + where :math:`p` is the probability of a single success + and :math:`1-p` is the probability of a single failure. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("p", False, (0, 1), (True, True))] + + def _rvs(self, p, size=None, random_state=None): + return binom_gen._rvs(self, 1, p, size=size, random_state=random_state) + + def _argcheck(self, p): + return (p >= 0) & (p <= 1) + + def _get_support(self, p): + # Overrides binom_gen._get_support!x + return self.a, self.b + + def _logpmf(self, x, p): + return binom._logpmf(x, 1, p) + + def _pmf(self, x, p): + # bernoulli.pmf(k) = 1-p if k = 0 + # = p if k = 1 + return binom._pmf(x, 1, p) + + def _cdf(self, x, p): + return binom._cdf(x, 1, p) + + def _sf(self, x, p): + return binom._sf(x, 1, p) + + def _isf(self, x, p): + return binom._isf(x, 1, p) + + def _ppf(self, q, p): + return binom._ppf(q, 1, p) + + def _stats(self, p): + return binom._stats(1, p) + + def _entropy(self, p): + return entr(p) + entr(1-p) + + +bernoulli = bernoulli_gen(b=1, name='bernoulli') + + +class betabinom_gen(rv_discrete): + r"""A beta-binomial discrete random variable. + + %(before_notes)s + + Notes + ----- + The beta-binomial distribution is a binomial distribution with a + probability of success `p` that follows a beta distribution. + + The probability mass function for `betabinom` is: + + .. math:: + + f(k) = \binom{n}{k} \frac{B(k + a, n - k + b)}{B(a, b)} + + for :math:`k \in \{0, 1, \dots, n\}`, :math:`n \geq 0`, :math:`a > 0`, + :math:`b > 0`, where :math:`B(a, b)` is the beta function. + + `betabinom` takes :math:`n`, :math:`a`, and :math:`b` as shape parameters. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution + + %(after_notes)s + + .. versionadded:: 1.4.0 + + See Also + -------- + beta, binom + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("n", True, (0, np.inf), (True, False)), + _ShapeInfo("a", False, (0, np.inf), (False, False)), + _ShapeInfo("b", False, (0, np.inf), (False, False))] + + def _rvs(self, n, a, b, size=None, random_state=None): + p = random_state.beta(a, b, size) + return random_state.binomial(n, p, size) + + def _get_support(self, n, a, b): + return 0, n + + def _argcheck(self, n, a, b): + return (n >= 0) & _isintegral(n) & (a > 0) & (b > 0) + + def _logpmf(self, x, n, a, b): + k = floor(x) + combiln = -log(n + 1) - betaln(n - k + 1, k + 1) + return combiln + betaln(k + a, n - k + b) - betaln(a, b) + + def _pmf(self, x, n, a, b): + return exp(self._logpmf(x, n, a, b)) + + def _stats(self, n, a, b, moments='mv'): + e_p = a / (a + b) + e_q = 1 - e_p + mu = n * e_p + var = n * (a + b + n) * e_p * e_q / (a + b + 1) + g1, g2 = None, None + if 's' in moments: + g1 = 1.0 / sqrt(var) + g1 *= (a + b + 2 * n) * (b - a) + g1 /= (a + b + 2) * (a + b) + if 'k' in moments: + g2 = (a + b).astype(e_p.dtype) + g2 *= (a + b - 1 + 6 * n) + g2 += 3 * a * b * (n - 2) + g2 += 6 * n ** 2 + g2 -= 3 * e_p * b * n * (6 - n) + g2 -= 18 * e_p * e_q * n ** 2 + g2 *= (a + b) ** 2 * (1 + a + b) + g2 /= (n * a * b * (a + b + 2) * (a + b + 3) * (a + b + n)) + g2 -= 3 + return mu, var, g1, g2 + + +betabinom = betabinom_gen(name='betabinom') + + +class nbinom_gen(rv_discrete): + r"""A negative binomial discrete random variable. + + %(before_notes)s + + Notes + ----- + Negative binomial distribution describes a sequence of i.i.d. Bernoulli + trials, repeated until a predefined, non-random number of successes occurs. + + The probability mass function of the number of failures for `nbinom` is: + + .. math:: + + f(k) = \binom{k+n-1}{n-1} p^n (1-p)^k + + for :math:`k \ge 0`, :math:`0 < p \leq 1` + + `nbinom` takes :math:`n` and :math:`p` as shape parameters where :math:`n` + is the number of successes, :math:`p` is the probability of a single + success, and :math:`1-p` is the probability of a single failure. + + Another common parameterization of the negative binomial distribution is + in terms of the mean number of failures :math:`\mu` to achieve :math:`n` + successes. The mean :math:`\mu` is related to the probability of success + as + + .. math:: + + p = \frac{n}{n + \mu} + + The number of successes :math:`n` may also be specified in terms of a + "dispersion", "heterogeneity", or "aggregation" parameter :math:`\alpha`, + which relates the mean :math:`\mu` to the variance :math:`\sigma^2`, + e.g. :math:`\sigma^2 = \mu + \alpha \mu^2`. Regardless of the convention + used for :math:`\alpha`, + + .. math:: + + p &= \frac{\mu}{\sigma^2} \\ + n &= \frac{\mu^2}{\sigma^2 - \mu} + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pmf``, ``cdf``, ``sf``, ``ppf``, ``isf`` + and ``stats`` methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + %(example)s + + See Also + -------- + hypergeom, binom, nhypergeom + + """ + def _shape_info(self): + return [_ShapeInfo("n", True, (0, np.inf), (True, False)), + _ShapeInfo("p", False, (0, 1), (True, True))] + + def _rvs(self, n, p, size=None, random_state=None): + return random_state.negative_binomial(n, p, size) + + def _argcheck(self, n, p): + return (n > 0) & (p > 0) & (p <= 1) + + def _pmf(self, x, n, p): + # nbinom.pmf(k) = choose(k+n-1, n-1) * p**n * (1-p)**k + return scu._nbinom_pmf(x, n, p) + + def _logpmf(self, x, n, p): + coeff = gamln(n+x) - gamln(x+1) - gamln(n) + return coeff + n*log(p) + special.xlog1py(x, -p) + + def _cdf(self, x, n, p): + k = floor(x) + return scu._nbinom_cdf(k, n, p) + + def _logcdf(self, x, n, p): + k = floor(x) + k, n, p = np.broadcast_arrays(k, n, p) + cdf = self._cdf(k, n, p) + cond = cdf > 0.5 + def f1(k, n, p): + return np.log1p(-special.betainc(k + 1, n, 1 - p)) + + # do calc in place + logcdf = cdf + with np.errstate(divide='ignore'): + logcdf[cond] = f1(k[cond], n[cond], p[cond]) + logcdf[~cond] = np.log(cdf[~cond]) + return logcdf + + def _sf(self, x, n, p): + k = floor(x) + return scu._nbinom_sf(k, n, p) + + def _isf(self, x, n, p): + with np.errstate(over='ignore'): # see gh-17432 + return scu._nbinom_isf(x, n, p) + + def _ppf(self, q, n, p): + with np.errstate(over='ignore'): # see gh-17432 + return scu._nbinom_ppf(q, n, p) + + def _stats(self, n, p): + return ( + scu._nbinom_mean(n, p), + scu._nbinom_variance(n, p), + scu._nbinom_skewness(n, p), + scu._nbinom_kurtosis_excess(n, p), + ) + + +nbinom = nbinom_gen(name='nbinom') + + +class betanbinom_gen(rv_discrete): + r"""A beta-negative-binomial discrete random variable. + + %(before_notes)s + + Notes + ----- + The beta-negative-binomial distribution is a negative binomial + distribution with a probability of success `p` that follows a + beta distribution. + + The probability mass function for `betanbinom` is: + + .. math:: + + f(k) = \binom{n + k - 1}{k} \frac{B(a + n, b + k)}{B(a, b)} + + for :math:`k \ge 0`, :math:`n \geq 0`, :math:`a > 0`, + :math:`b > 0`, where :math:`B(a, b)` is the beta function. + + `betanbinom` takes :math:`n`, :math:`a`, and :math:`b` as shape parameters. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Beta_negative_binomial_distribution + + %(after_notes)s + + .. versionadded:: 1.12.0 + + See Also + -------- + betabinom : Beta binomial distribution + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("n", True, (0, np.inf), (True, False)), + _ShapeInfo("a", False, (0, np.inf), (False, False)), + _ShapeInfo("b", False, (0, np.inf), (False, False))] + + def _rvs(self, n, a, b, size=None, random_state=None): + p = random_state.beta(a, b, size) + return random_state.negative_binomial(n, p, size) + + def _argcheck(self, n, a, b): + return (n >= 0) & _isintegral(n) & (a > 0) & (b > 0) + + def _logpmf(self, x, n, a, b): + k = floor(x) + combiln = -np.log(n + k) - betaln(n, k + 1) + return combiln + betaln(a + n, b + k) - betaln(a, b) + + def _pmf(self, x, n, a, b): + return exp(self._logpmf(x, n, a, b)) + + def _stats(self, n, a, b, moments='mv'): + # reference: Wolfram Alpha input + # BetaNegativeBinomialDistribution[a, b, n] + def mean(n, a, b): + return n * b / (a - 1.) + mu = _lazywhere(a > 1, (n, a, b), f=mean, fillvalue=np.inf) + def var(n, a, b): + return (n * b * (n + a - 1.) * (a + b - 1.) + / ((a - 2.) * (a - 1.)**2.)) + var = _lazywhere(a > 2, (n, a, b), f=var, fillvalue=np.inf) + g1, g2 = None, None + def skew(n, a, b): + return ((2 * n + a - 1.) * (2 * b + a - 1.) + / (a - 3.) / sqrt(n * b * (n + a - 1.) * (b + a - 1.) + / (a - 2.))) + if 's' in moments: + g1 = _lazywhere(a > 3, (n, a, b), f=skew, fillvalue=np.inf) + def kurtosis(n, a, b): + term = (a - 2.) + term_2 = ((a - 1.)**2. * (a**2. + a * (6 * b - 1.) + + 6. * (b - 1.) * b) + + 3. * n**2. * ((a + 5.) * b**2. + (a + 5.) + * (a - 1.) * b + 2. * (a - 1.)**2) + + 3 * (a - 1.) * n + * ((a + 5.) * b**2. + (a + 5.) * (a - 1.) * b + + 2. * (a - 1.)**2.)) + denominator = ((a - 4.) * (a - 3.) * b * n + * (a + b - 1.) * (a + n - 1.)) + # Wolfram Alpha uses Pearson kurtosis, so we subtract 3 to get + # scipy's Fisher kurtosis + return term * term_2 / denominator - 3. + if 'k' in moments: + g2 = _lazywhere(a > 4, (n, a, b), f=kurtosis, fillvalue=np.inf) + return mu, var, g1, g2 + + +betanbinom = betanbinom_gen(name='betanbinom') + + +class geom_gen(rv_discrete): + r"""A geometric discrete random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `geom` is: + + .. math:: + + f(k) = (1-p)^{k-1} p + + for :math:`k \ge 1`, :math:`0 < p \leq 1` + + `geom` takes :math:`p` as shape parameter, + where :math:`p` is the probability of a single success + and :math:`1-p` is the probability of a single failure. + + Note that when drawing random samples, the probability of observations that exceed + ``np.iinfo(np.int64).max`` increases rapidly as $p$ decreases below $10^{-17}$. For + $p < 10^{-20}$, almost all observations would exceed the maximum ``int64``; however, + the output dtype is always ``int64``, so these values are clipped to the maximum. + + %(after_notes)s + + See Also + -------- + planck + + %(example)s + + """ + + def _shape_info(self): + return [_ShapeInfo("p", False, (0, 1), (True, True))] + + def _rvs(self, p, size=None, random_state=None): + res = random_state.geometric(p, size=size) + # RandomState.geometric can wrap around to negative values; make behavior + # consistent with Generator.geometric by replacing with maximum integer. + max_int = np.iinfo(res.dtype).max + return np.where(res < 0, max_int, res) + + def _argcheck(self, p): + return (p <= 1) & (p > 0) + + def _pmf(self, k, p): + return np.power(1-p, k-1) * p + + def _logpmf(self, k, p): + return special.xlog1py(k - 1, -p) + log(p) + + def _cdf(self, x, p): + k = floor(x) + return -expm1(log1p(-p)*k) + + def _sf(self, x, p): + return np.exp(self._logsf(x, p)) + + def _logsf(self, x, p): + k = floor(x) + return k*log1p(-p) + + def _ppf(self, q, p): + vals = ceil(log1p(-q) / log1p(-p)) + temp = self._cdf(vals-1, p) + return np.where((temp >= q) & (vals > 0), vals-1, vals) + + def _stats(self, p): + mu = 1.0/p + qr = 1.0-p + var = qr / p / p + g1 = (2.0-p) / sqrt(qr) + g2 = np.polyval([1, -6, 6], p)/(1.0-p) + return mu, var, g1, g2 + + def _entropy(self, p): + return -np.log(p) - np.log1p(-p) * (1.0-p) / p + + +geom = geom_gen(a=1, name='geom', longname="A geometric") + + +class hypergeom_gen(rv_discrete): + r"""A hypergeometric discrete random variable. + + The hypergeometric distribution models drawing objects from a bin. + `M` is the total number of objects, `n` is total number of Type I objects. + The random variate represents the number of Type I objects in `N` drawn + without replacement from the total population. + + %(before_notes)s + + Notes + ----- + The symbols used to denote the shape parameters (`M`, `n`, and `N`) are not + universally accepted. See the Examples for a clarification of the + definitions used here. + + The probability mass function is defined as, + + .. math:: p(k, M, n, N) = \frac{\binom{n}{k} \binom{M - n}{N - k}} + {\binom{M}{N}} + + for :math:`k \in [\max(0, N - M + n), \min(n, N)]`, where the binomial + coefficients are defined as, + + .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}. + + This distribution uses routines from the Boost Math C++ library for + the computation of the ``pmf``, ``cdf``, ``sf`` and ``stats`` methods. [1]_ + + %(after_notes)s + + References + ---------- + .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import hypergeom + >>> import matplotlib.pyplot as plt + + Suppose we have a collection of 20 animals, of which 7 are dogs. Then if + we want to know the probability of finding a given number of dogs if we + choose at random 12 of the 20 animals, we can initialize a frozen + distribution and plot the probability mass function: + + >>> [M, n, N] = [20, 7, 12] + >>> rv = hypergeom(M, n, N) + >>> x = np.arange(0, n+1) + >>> pmf_dogs = rv.pmf(x) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(x, pmf_dogs, 'bo') + >>> ax.vlines(x, 0, pmf_dogs, lw=2) + >>> ax.set_xlabel('# of dogs in our group of chosen animals') + >>> ax.set_ylabel('hypergeom PMF') + >>> plt.show() + + Instead of using a frozen distribution we can also use `hypergeom` + methods directly. To for example obtain the cumulative distribution + function, use: + + >>> prb = hypergeom.cdf(x, M, n, N) + + And to generate random numbers: + + >>> R = hypergeom.rvs(M, n, N, size=10) + + See Also + -------- + nhypergeom, binom, nbinom + + """ + def _shape_info(self): + return [_ShapeInfo("M", True, (0, np.inf), (True, False)), + _ShapeInfo("n", True, (0, np.inf), (True, False)), + _ShapeInfo("N", True, (0, np.inf), (True, False))] + + def _rvs(self, M, n, N, size=None, random_state=None): + return random_state.hypergeometric(n, M-n, N, size=size) + + def _get_support(self, M, n, N): + return np.maximum(N-(M-n), 0), np.minimum(n, N) + + def _argcheck(self, M, n, N): + cond = (M > 0) & (n >= 0) & (N >= 0) + cond &= (n <= M) & (N <= M) + cond &= _isintegral(M) & _isintegral(n) & _isintegral(N) + return cond + + def _logpmf(self, k, M, n, N): + tot, good = M, n + bad = tot - good + result = (betaln(good+1, 1) + betaln(bad+1, 1) + betaln(tot-N+1, N+1) - + betaln(k+1, good-k+1) - betaln(N-k+1, bad-N+k+1) - + betaln(tot+1, 1)) + return result + + def _pmf(self, k, M, n, N): + return scu._hypergeom_pmf(k, n, N, M) + + def _cdf(self, k, M, n, N): + return scu._hypergeom_cdf(k, n, N, M) + + def _stats(self, M, n, N): + M, n, N = 1. * M, 1. * n, 1. * N + m = M - n + + # Boost kurtosis_excess doesn't return the same as the value + # computed here. + g2 = M * (M + 1) - 6. * N * (M - N) - 6. * n * m + g2 *= (M - 1) * M * M + g2 += 6. * n * N * (M - N) * m * (5. * M - 6) + g2 /= n * N * (M - N) * m * (M - 2.) * (M - 3.) + return ( + scu._hypergeom_mean(n, N, M), + scu._hypergeom_variance(n, N, M), + scu._hypergeom_skewness(n, N, M), + g2, + ) + + def _entropy(self, M, n, N): + k = np.r_[N - (M - n):min(n, N) + 1] + vals = self.pmf(k, M, n, N) + return np.sum(entr(vals), axis=0) + + def _sf(self, k, M, n, N): + return scu._hypergeom_sf(k, n, N, M) + + def _logsf(self, k, M, n, N): + res = [] + for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)): + if (quant + 0.5) * (tot + 0.5) < (good - 0.5) * (draw - 0.5): + # Less terms to sum if we calculate log(1-cdf) + res.append(log1p(-exp(self.logcdf(quant, tot, good, draw)))) + else: + # Integration over probability mass function using logsumexp + k2 = np.arange(quant + 1, draw + 1) + res.append(logsumexp(self._logpmf(k2, tot, good, draw))) + return np.asarray(res) + + def _logcdf(self, k, M, n, N): + res = [] + for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)): + if (quant + 0.5) * (tot + 0.5) > (good - 0.5) * (draw - 0.5): + # Less terms to sum if we calculate log(1-sf) + res.append(log1p(-exp(self.logsf(quant, tot, good, draw)))) + else: + # Integration over probability mass function using logsumexp + k2 = np.arange(0, quant + 1) + res.append(logsumexp(self._logpmf(k2, tot, good, draw))) + return np.asarray(res) + + +hypergeom = hypergeom_gen(name='hypergeom') + + +class nhypergeom_gen(rv_discrete): + r"""A negative hypergeometric discrete random variable. + + Consider a box containing :math:`M` balls:, :math:`n` red and + :math:`M-n` blue. We randomly sample balls from the box, one + at a time and *without* replacement, until we have picked :math:`r` + blue balls. `nhypergeom` is the distribution of the number of + red balls :math:`k` we have picked. + + %(before_notes)s + + Notes + ----- + The symbols used to denote the shape parameters (`M`, `n`, and `r`) are not + universally accepted. See the Examples for a clarification of the + definitions used here. + + The probability mass function is defined as, + + .. math:: f(k; M, n, r) = \frac{{{k+r-1}\choose{k}}{{M-r-k}\choose{n-k}}} + {{M \choose n}} + + for :math:`k \in [0, n]`, :math:`n \in [0, M]`, :math:`r \in [0, M-n]`, + and the binomial coefficient is: + + .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}. + + It is equivalent to observing :math:`k` successes in :math:`k+r-1` + samples with :math:`k+r`'th sample being a failure. The former + can be modelled as a hypergeometric distribution. The probability + of the latter is simply the number of failures remaining + :math:`M-n-(r-1)` divided by the size of the remaining population + :math:`M-(k+r-1)`. This relationship can be shown as: + + .. math:: NHG(k;M,n,r) = HG(k;M,n,k+r-1)\frac{(M-n-(r-1))}{(M-(k+r-1))} + + where :math:`NHG` is probability mass function (PMF) of the + negative hypergeometric distribution and :math:`HG` is the + PMF of the hypergeometric distribution. + + %(after_notes)s + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import nhypergeom + >>> import matplotlib.pyplot as plt + + Suppose we have a collection of 20 animals, of which 7 are dogs. + Then if we want to know the probability of finding a given number + of dogs (successes) in a sample with exactly 12 animals that + aren't dogs (failures), we can initialize a frozen distribution + and plot the probability mass function: + + >>> M, n, r = [20, 7, 12] + >>> rv = nhypergeom(M, n, r) + >>> x = np.arange(0, n+2) + >>> pmf_dogs = rv.pmf(x) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(x, pmf_dogs, 'bo') + >>> ax.vlines(x, 0, pmf_dogs, lw=2) + >>> ax.set_xlabel('# of dogs in our group with given 12 failures') + >>> ax.set_ylabel('nhypergeom PMF') + >>> plt.show() + + Instead of using a frozen distribution we can also use `nhypergeom` + methods directly. To for example obtain the probability mass + function, use: + + >>> prb = nhypergeom.pmf(x, M, n, r) + + And to generate random numbers: + + >>> R = nhypergeom.rvs(M, n, r, size=10) + + To verify the relationship between `hypergeom` and `nhypergeom`, use: + + >>> from scipy.stats import hypergeom, nhypergeom + >>> M, n, r = 45, 13, 8 + >>> k = 6 + >>> nhypergeom.pmf(k, M, n, r) + 0.06180776620271643 + >>> hypergeom.pmf(k, M, n, k+r-1) * (M - n - (r-1)) / (M - (k+r-1)) + 0.06180776620271644 + + See Also + -------- + hypergeom, binom, nbinom + + References + ---------- + .. [1] Negative Hypergeometric Distribution on Wikipedia + https://en.wikipedia.org/wiki/Negative_hypergeometric_distribution + + .. [2] Negative Hypergeometric Distribution from + http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Negativehypergeometric.pdf + + """ + + def _shape_info(self): + return [_ShapeInfo("M", True, (0, np.inf), (True, False)), + _ShapeInfo("n", True, (0, np.inf), (True, False)), + _ShapeInfo("r", True, (0, np.inf), (True, False))] + + def _get_support(self, M, n, r): + return 0, n + + def _argcheck(self, M, n, r): + cond = (n >= 0) & (n <= M) & (r >= 0) & (r <= M-n) + cond &= _isintegral(M) & _isintegral(n) & _isintegral(r) + return cond + + def _rvs(self, M, n, r, size=None, random_state=None): + + @_vectorize_rvs_over_shapes + def _rvs1(M, n, r, size, random_state): + # invert cdf by calculating all values in support, scalar M, n, r + a, b = self.support(M, n, r) + ks = np.arange(a, b+1) + cdf = self.cdf(ks, M, n, r) + ppf = interp1d(cdf, ks, kind='next', fill_value='extrapolate') + rvs = ppf(random_state.uniform(size=size)).astype(int) + if size is None: + return rvs.item() + return rvs + + return _rvs1(M, n, r, size=size, random_state=random_state) + + def _logpmf(self, k, M, n, r): + cond = ((r == 0) & (k == 0)) + result = _lazywhere(~cond, (k, M, n, r), + lambda k, M, n, r: + (-betaln(k+1, r) + betaln(k+r, 1) - + betaln(n-k+1, M-r-n+1) + betaln(M-r-k+1, 1) + + betaln(n+1, M-n+1) - betaln(M+1, 1)), + fillvalue=0.0) + return result + + def _pmf(self, k, M, n, r): + # same as the following but numerically more precise + # return comb(k+r-1, k) * comb(M-r-k, n-k) / comb(M, n) + return exp(self._logpmf(k, M, n, r)) + + def _stats(self, M, n, r): + # Promote the datatype to at least float + # mu = rn / (M-n+1) + M, n, r = 1.*M, 1.*n, 1.*r + mu = r*n / (M-n+1) + + var = r*(M+1)*n / ((M-n+1)*(M-n+2)) * (1 - r / (M-n+1)) + + # The skew and kurtosis are mathematically + # intractable so return `None`. See [2]_. + g1, g2 = None, None + return mu, var, g1, g2 + + +nhypergeom = nhypergeom_gen(name='nhypergeom') + + +# FIXME: Fails _cdfvec +class logser_gen(rv_discrete): + r"""A Logarithmic (Log-Series, Series) discrete random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `logser` is: + + .. math:: + + f(k) = - \frac{p^k}{k \log(1-p)} + + for :math:`k \ge 1`, :math:`0 < p < 1` + + `logser` takes :math:`p` as shape parameter, + where :math:`p` is the probability of a single success + and :math:`1-p` is the probability of a single failure. + + %(after_notes)s + + %(example)s + + """ + + def _shape_info(self): + return [_ShapeInfo("p", False, (0, 1), (True, True))] + + def _rvs(self, p, size=None, random_state=None): + # looks wrong for p>0.5, too few k=1 + # trying to use generic is worse, no k=1 at all + return random_state.logseries(p, size=size) + + def _argcheck(self, p): + return (p > 0) & (p < 1) + + def _pmf(self, k, p): + # logser.pmf(k) = - p**k / (k*log(1-p)) + return -np.power(p, k) * 1.0 / k / special.log1p(-p) + + def _stats(self, p): + r = special.log1p(-p) + mu = p / (p - 1.0) / r + mu2p = -p / r / (p - 1.0)**2 + var = mu2p - mu*mu + mu3p = -p / r * (1.0+p) / (1.0 - p)**3 + mu3 = mu3p - 3*mu*mu2p + 2*mu**3 + g1 = mu3 / np.power(var, 1.5) + + mu4p = -p / r * ( + 1.0 / (p-1)**2 - 6*p / (p - 1)**3 + 6*p*p / (p-1)**4) + mu4 = mu4p - 4*mu3p*mu + 6*mu2p*mu*mu - 3*mu**4 + g2 = mu4 / var**2 - 3.0 + return mu, var, g1, g2 + + +logser = logser_gen(a=1, name='logser', longname='A logarithmic') + + +class poisson_gen(rv_discrete): + r"""A Poisson discrete random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `poisson` is: + + .. math:: + + f(k) = \exp(-\mu) \frac{\mu^k}{k!} + + for :math:`k \ge 0`. + + `poisson` takes :math:`\mu \geq 0` as shape parameter. + When :math:`\mu = 0`, the ``pmf`` method + returns ``1.0`` at quantile :math:`k = 0`. + + %(after_notes)s + + %(example)s + + """ + + def _shape_info(self): + return [_ShapeInfo("mu", False, (0, np.inf), (True, False))] + + # Override rv_discrete._argcheck to allow mu=0. + def _argcheck(self, mu): + return mu >= 0 + + def _rvs(self, mu, size=None, random_state=None): + return random_state.poisson(mu, size) + + def _logpmf(self, k, mu): + Pk = special.xlogy(k, mu) - gamln(k + 1) - mu + return Pk + + def _pmf(self, k, mu): + # poisson.pmf(k) = exp(-mu) * mu**k / k! + return exp(self._logpmf(k, mu)) + + def _cdf(self, x, mu): + k = floor(x) + return special.pdtr(k, mu) + + def _sf(self, x, mu): + k = floor(x) + return special.pdtrc(k, mu) + + def _ppf(self, q, mu): + vals = ceil(special.pdtrik(q, mu)) + vals1 = np.maximum(vals - 1, 0) + temp = special.pdtr(vals1, mu) + return np.where(temp >= q, vals1, vals) + + def _stats(self, mu): + var = mu + tmp = np.asarray(mu) + mu_nonzero = tmp > 0 + g1 = _lazywhere(mu_nonzero, (tmp,), lambda x: sqrt(1.0/x), np.inf) + g2 = _lazywhere(mu_nonzero, (tmp,), lambda x: 1.0/x, np.inf) + return mu, var, g1, g2 + + +poisson = poisson_gen(name="poisson", longname='A Poisson') + + +class planck_gen(rv_discrete): + r"""A Planck discrete exponential random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `planck` is: + + .. math:: + + f(k) = (1-\exp(-\lambda)) \exp(-\lambda k) + + for :math:`k \ge 0` and :math:`\lambda > 0`. + + `planck` takes :math:`\lambda` as shape parameter. The Planck distribution + can be written as a geometric distribution (`geom`) with + :math:`p = 1 - \exp(-\lambda)` shifted by ``loc = -1``. + + %(after_notes)s + + See Also + -------- + geom + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("lambda", False, (0, np.inf), (False, False))] + + def _argcheck(self, lambda_): + return lambda_ > 0 + + def _pmf(self, k, lambda_): + return -expm1(-lambda_)*exp(-lambda_*k) + + def _cdf(self, x, lambda_): + k = floor(x) + return -expm1(-lambda_*(k+1)) + + def _sf(self, x, lambda_): + return exp(self._logsf(x, lambda_)) + + def _logsf(self, x, lambda_): + k = floor(x) + return -lambda_*(k+1) + + def _ppf(self, q, lambda_): + vals = ceil(-1.0/lambda_ * log1p(-q)-1) + vals1 = (vals-1).clip(*(self._get_support(lambda_))) + temp = self._cdf(vals1, lambda_) + return np.where(temp >= q, vals1, vals) + + def _rvs(self, lambda_, size=None, random_state=None): + # use relation to geometric distribution for sampling + p = -expm1(-lambda_) + return random_state.geometric(p, size=size) - 1.0 + + def _stats(self, lambda_): + mu = 1/expm1(lambda_) + var = exp(-lambda_)/(expm1(-lambda_))**2 + g1 = 2*cosh(lambda_/2.0) + g2 = 4+2*cosh(lambda_) + return mu, var, g1, g2 + + def _entropy(self, lambda_): + C = -expm1(-lambda_) + return lambda_*exp(-lambda_)/C - log(C) + + +planck = planck_gen(a=0, name='planck', longname='A discrete exponential ') + + +class boltzmann_gen(rv_discrete): + r"""A Boltzmann (Truncated Discrete Exponential) random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `boltzmann` is: + + .. math:: + + f(k) = (1-\exp(-\lambda)) \exp(-\lambda k) / (1-\exp(-\lambda N)) + + for :math:`k = 0,..., N-1`. + + `boltzmann` takes :math:`\lambda > 0` and :math:`N > 0` as shape parameters. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("lambda_", False, (0, np.inf), (False, False)), + _ShapeInfo("N", True, (0, np.inf), (False, False))] + + def _argcheck(self, lambda_, N): + return (lambda_ > 0) & (N > 0) & _isintegral(N) + + def _get_support(self, lambda_, N): + return self.a, N - 1 + + def _pmf(self, k, lambda_, N): + # boltzmann.pmf(k) = + # (1-exp(-lambda_)*exp(-lambda_*k)/(1-exp(-lambda_*N)) + fact = (1-exp(-lambda_))/(1-exp(-lambda_*N)) + return fact*exp(-lambda_*k) + + def _cdf(self, x, lambda_, N): + k = floor(x) + return (1-exp(-lambda_*(k+1)))/(1-exp(-lambda_*N)) + + def _ppf(self, q, lambda_, N): + qnew = q*(1-exp(-lambda_*N)) + vals = ceil(-1.0/lambda_ * log(1-qnew)-1) + vals1 = (vals-1).clip(0.0, np.inf) + temp = self._cdf(vals1, lambda_, N) + return np.where(temp >= q, vals1, vals) + + def _stats(self, lambda_, N): + z = exp(-lambda_) + zN = exp(-lambda_*N) + mu = z/(1.0-z)-N*zN/(1-zN) + var = z/(1.0-z)**2 - N*N*zN/(1-zN)**2 + trm = (1-zN)/(1-z) + trm2 = (z*trm**2 - N*N*zN) + g1 = z*(1+z)*trm**3 - N**3*zN*(1+zN) + g1 = g1 / trm2**(1.5) + g2 = z*(1+4*z+z*z)*trm**4 - N**4 * zN*(1+4*zN+zN*zN) + g2 = g2 / trm2 / trm2 + return mu, var, g1, g2 + + +boltzmann = boltzmann_gen(name='boltzmann', a=0, + longname='A truncated discrete exponential ') + + +class randint_gen(rv_discrete): + r"""A uniform discrete random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `randint` is: + + .. math:: + + f(k) = \frac{1}{\texttt{high} - \texttt{low}} + + for :math:`k \in \{\texttt{low}, \dots, \texttt{high} - 1\}`. + + `randint` takes :math:`\texttt{low}` and :math:`\texttt{high}` as shape + parameters. + + %(after_notes)s + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import randint + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + + Calculate the first four moments: + + >>> low, high = 7, 31 + >>> mean, var, skew, kurt = randint.stats(low, high, moments='mvsk') + + Display the probability mass function (``pmf``): + + >>> x = np.arange(low - 5, high + 5) + >>> ax.plot(x, randint.pmf(x, low, high), 'bo', ms=8, label='randint pmf') + >>> ax.vlines(x, 0, randint.pmf(x, low, high), colors='b', lw=5, alpha=0.5) + + Alternatively, the distribution object can be called (as a function) to + fix the shape and location. This returns a "frozen" RV object holding the + given parameters fixed. + + Freeze the distribution and display the frozen ``pmf``: + + >>> rv = randint(low, high) + >>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', + ... lw=1, label='frozen pmf') + >>> ax.legend(loc='lower center') + >>> plt.show() + + Check the relationship between the cumulative distribution function + (``cdf``) and its inverse, the percent point function (``ppf``): + + >>> q = np.arange(low, high) + >>> p = randint.cdf(q, low, high) + >>> np.allclose(q, randint.ppf(p, low, high)) + True + + Generate random numbers: + + >>> r = randint.rvs(low, high, size=1000) + + """ + + def _shape_info(self): + return [_ShapeInfo("low", True, (-np.inf, np.inf), (False, False)), + _ShapeInfo("high", True, (-np.inf, np.inf), (False, False))] + + def _argcheck(self, low, high): + return (high > low) & _isintegral(low) & _isintegral(high) + + def _get_support(self, low, high): + return low, high-1 + + def _pmf(self, k, low, high): + # randint.pmf(k) = 1./(high - low) + p = np.ones_like(k) / (np.asarray(high, dtype=np.int64) - low) + return np.where((k >= low) & (k < high), p, 0.) + + def _cdf(self, x, low, high): + k = floor(x) + return (k - low + 1.) / (high - low) + + def _ppf(self, q, low, high): + vals = ceil(q * (high - low) + low) - 1 + vals1 = (vals - 1).clip(low, high) + temp = self._cdf(vals1, low, high) + return np.where(temp >= q, vals1, vals) + + def _stats(self, low, high): + m2, m1 = np.asarray(high), np.asarray(low) + mu = (m2 + m1 - 1.0) / 2 + d = m2 - m1 + var = (d*d - 1) / 12.0 + g1 = 0.0 + g2 = -6.0/5.0 * (d*d + 1.0) / (d*d - 1.0) + return mu, var, g1, g2 + + def _rvs(self, low, high, size=None, random_state=None): + """An array of *size* random integers >= ``low`` and < ``high``.""" + if np.asarray(low).size == 1 and np.asarray(high).size == 1: + # no need to vectorize in that case + return rng_integers(random_state, low, high, size=size) + + if size is not None: + # NumPy's RandomState.randint() doesn't broadcast its arguments. + # Use `broadcast_to()` to extend the shapes of low and high + # up to size. Then we can use the numpy.vectorize'd + # randint without needing to pass it a `size` argument. + low = np.broadcast_to(low, size) + high = np.broadcast_to(high, size) + randint = np.vectorize(partial(rng_integers, random_state), + otypes=[np.dtype(int)]) + return randint(low, high) + + def _entropy(self, low, high): + return log(high - low) + + +randint = randint_gen(name='randint', longname='A discrete uniform ' + '(random integer)') + + +# FIXME: problems sampling. +class zipf_gen(rv_discrete): + r"""A Zipf (Zeta) discrete random variable. + + %(before_notes)s + + See Also + -------- + zipfian + + Notes + ----- + The probability mass function for `zipf` is: + + .. math:: + + f(k, a) = \frac{1}{\zeta(a) k^a} + + for :math:`k \ge 1`, :math:`a > 1`. + + `zipf` takes :math:`a > 1` as shape parameter. :math:`\zeta` is the + Riemann zeta function (`scipy.special.zeta`) + + The Zipf distribution is also known as the zeta distribution, which is + a special case of the Zipfian distribution (`zipfian`). + + %(after_notes)s + + References + ---------- + .. [1] "Zeta Distribution", Wikipedia, + https://en.wikipedia.org/wiki/Zeta_distribution + + %(example)s + + Confirm that `zipf` is the large `n` limit of `zipfian`. + + >>> import numpy as np + >>> from scipy.stats import zipf, zipfian + >>> k = np.arange(11) + >>> np.allclose(zipf.pmf(k, a), zipfian.pmf(k, a, n=10000000)) + True + + """ + + def _shape_info(self): + return [_ShapeInfo("a", False, (1, np.inf), (False, False))] + + def _rvs(self, a, size=None, random_state=None): + return random_state.zipf(a, size=size) + + def _argcheck(self, a): + return a > 1 + + def _pmf(self, k, a): + k = k.astype(np.float64) + # zipf.pmf(k, a) = 1/(zeta(a) * k**a) + Pk = 1.0 / special.zeta(a, 1) * k**-a + return Pk + + def _munp(self, n, a): + return _lazywhere( + a > n + 1, (a, n), + lambda a, n: special.zeta(a - n, 1) / special.zeta(a, 1), + np.inf) + + +zipf = zipf_gen(a=1, name='zipf', longname='A Zipf') + + +def _gen_harmonic_gt1(n, a): + """Generalized harmonic number, a > 1""" + # See https://en.wikipedia.org/wiki/Harmonic_number; search for "hurwitz" + return zeta(a, 1) - zeta(a, n+1) + + +def _gen_harmonic_leq1(n, a): + """Generalized harmonic number, a <= 1""" + if not np.size(n): + return n + n_max = np.max(n) # loop starts at maximum of all n + out = np.zeros_like(a, dtype=float) + # add terms of harmonic series; starting from smallest to avoid roundoff + for i in np.arange(n_max, 0, -1, dtype=float): + mask = i <= n # don't add terms after nth + out[mask] += 1/i**a[mask] + return out + + +def _gen_harmonic(n, a): + """Generalized harmonic number""" + n, a = np.broadcast_arrays(n, a) + return _lazywhere(a > 1, (n, a), + f=_gen_harmonic_gt1, f2=_gen_harmonic_leq1) + + +class zipfian_gen(rv_discrete): + r"""A Zipfian discrete random variable. + + %(before_notes)s + + See Also + -------- + zipf + + Notes + ----- + The probability mass function for `zipfian` is: + + .. math:: + + f(k, a, n) = \frac{1}{H_{n,a} k^a} + + for :math:`k \in \{1, 2, \dots, n-1, n\}`, :math:`a \ge 0`, + :math:`n \in \{1, 2, 3, \dots\}`. + + `zipfian` takes :math:`a` and :math:`n` as shape parameters. + :math:`H_{n,a}` is the :math:`n`:sup:`th` generalized harmonic + number of order :math:`a`. + + The Zipfian distribution reduces to the Zipf (zeta) distribution as + :math:`n \rightarrow \infty`. + + %(after_notes)s + + References + ---------- + .. [1] "Zipf's Law", Wikipedia, https://en.wikipedia.org/wiki/Zipf's_law + .. [2] Larry Leemis, "Zipf Distribution", Univariate Distribution + Relationships. http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf + + %(example)s + + Confirm that `zipfian` reduces to `zipf` for large `n`, ``a > 1``. + + >>> import numpy as np + >>> from scipy.stats import zipf, zipfian + >>> k = np.arange(11) + >>> np.allclose(zipfian.pmf(k, a=3.5, n=10000000), zipf.pmf(k, a=3.5)) + True + + """ + + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (True, False)), + _ShapeInfo("n", True, (0, np.inf), (False, False))] + + def _argcheck(self, a, n): + # we need np.asarray here because moment (maybe others) don't convert + return (a >= 0) & (n > 0) & (n == np.asarray(n, dtype=int)) + + def _get_support(self, a, n): + return 1, n + + def _pmf(self, k, a, n): + k = k.astype(np.float64) + return 1.0 / _gen_harmonic(n, a) * k**-a + + def _cdf(self, k, a, n): + return _gen_harmonic(k, a) / _gen_harmonic(n, a) + + def _sf(self, k, a, n): + k = k + 1 # # to match SciPy convention + # see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf + return ((k**a*(_gen_harmonic(n, a) - _gen_harmonic(k, a)) + 1) + / (k**a*_gen_harmonic(n, a))) + + def _stats(self, a, n): + # see # see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf + Hna = _gen_harmonic(n, a) + Hna1 = _gen_harmonic(n, a-1) + Hna2 = _gen_harmonic(n, a-2) + Hna3 = _gen_harmonic(n, a-3) + Hna4 = _gen_harmonic(n, a-4) + mu1 = Hna1/Hna + mu2n = (Hna2*Hna - Hna1**2) + mu2d = Hna**2 + mu2 = mu2n / mu2d + g1 = (Hna3/Hna - 3*Hna1*Hna2/Hna**2 + 2*Hna1**3/Hna**3)/mu2**(3/2) + g2 = (Hna**3*Hna4 - 4*Hna**2*Hna1*Hna3 + 6*Hna*Hna1**2*Hna2 + - 3*Hna1**4) / mu2n**2 + g2 -= 3 + return mu1, mu2, g1, g2 + + +zipfian = zipfian_gen(a=1, name='zipfian', longname='A Zipfian') + + +class dlaplace_gen(rv_discrete): + r"""A Laplacian discrete random variable. + + %(before_notes)s + + Notes + ----- + The probability mass function for `dlaplace` is: + + .. math:: + + f(k) = \tanh(a/2) \exp(-a |k|) + + for integers :math:`k` and :math:`a > 0`. + + `dlaplace` takes :math:`a` as shape parameter. + + %(after_notes)s + + %(example)s + + """ + + def _shape_info(self): + return [_ShapeInfo("a", False, (0, np.inf), (False, False))] + + def _pmf(self, k, a): + # dlaplace.pmf(k) = tanh(a/2) * exp(-a*abs(k)) + return tanh(a/2.0) * exp(-a * abs(k)) + + def _cdf(self, x, a): + k = floor(x) + + def f(k, a): + return 1.0 - exp(-a * k) / (exp(a) + 1) + + def f2(k, a): + return exp(a * (k + 1)) / (exp(a) + 1) + + return _lazywhere(k >= 0, (k, a), f=f, f2=f2) + + def _ppf(self, q, a): + const = 1 + exp(a) + vals = ceil(np.where(q < 1.0 / (1 + exp(-a)), + log(q*const) / a - 1, + -log((1-q) * const) / a)) + vals1 = vals - 1 + return np.where(self._cdf(vals1, a) >= q, vals1, vals) + + def _stats(self, a): + ea = exp(a) + mu2 = 2.*ea/(ea-1.)**2 + mu4 = 2.*ea*(ea**2+10.*ea+1.) / (ea-1.)**4 + return 0., mu2, 0., mu4/mu2**2 - 3. + + def _entropy(self, a): + return a / sinh(a) - log(tanh(a/2.0)) + + def _rvs(self, a, size=None, random_state=None): + # The discrete Laplace is equivalent to the two-sided geometric + # distribution with PMF: + # f(k) = (1 - alpha)/(1 + alpha) * alpha^abs(k) + # Reference: + # https://www.sciencedirect.com/science/ + # article/abs/pii/S0378375804003519 + # Furthermore, the two-sided geometric distribution is + # equivalent to the difference between two iid geometric + # distributions. + # Reference (page 179): + # https://pdfs.semanticscholar.org/61b3/ + # b99f466815808fd0d03f5d2791eea8b541a1.pdf + # Thus, we can leverage the following: + # 1) alpha = e^-a + # 2) probability_of_success = 1 - alpha (Bernoulli trial) + probOfSuccess = -np.expm1(-np.asarray(a)) + x = random_state.geometric(probOfSuccess, size=size) + y = random_state.geometric(probOfSuccess, size=size) + return x - y + + +dlaplace = dlaplace_gen(a=-np.inf, + name='dlaplace', longname='A discrete Laplacian') + + +class poisson_binom_gen(rv_discrete): + r"""A Poisson Binomial discrete random variable. + + %(before_notes)s + + See Also + -------- + binom + + Notes + ----- + The probability mass function for `poisson_binom` is: + + .. math:: + + f(k; p_1, p_2, ..., p_n) = \sum_{A \in F_k} \prod_{i \in A} p_i \prod_{j \in A^C} 1 - p_j + + where :math:`k \in \{0, 1, \dots, n-1, n\}`, :math:`F_k` is the set of all + subsets of :math:`k` integers that can be selected :math:`\{0, 1, \dots, n-1, n\}`, + and :math:`A^C` is the complement of a set :math:`A`. + + `poisson_binom` accepts a single array argument ``p`` for shape parameters + :math:`0 ≤ p_i ≤ 1`, where the last axis corresponds with the index :math:`i` and + any others are for batch dimensions. Broadcasting behaves according to the usual + rules except that the last axis of ``p`` is ignored. Instances of this class do + not support serialization/unserialization. + + %(after_notes)s + + References + ---------- + .. [1] "Poisson binomial distribution", Wikipedia, + https://en.wikipedia.org/wiki/Poisson_binomial_distribution + .. [2] Biscarri, William, Sihai Dave Zhao, and Robert J. Brunner. "A simple and + fast method for computing the Poisson binomial distribution function". + Computational Statistics & Data Analysis 122 (2018) 92-100. + :doi:`10.1016/j.csda.2018.01.007` + + %(example)s + + """ # noqa: E501 + def _shape_info(self): + # message = 'Fitting is not implemented for this distribution." + # raise NotImplementedError(message) + return [] + + def _argcheck(self, *args): + p = np.stack(args, axis=0) + conds = (0 <= p) & (p <= 1) + return np.all(conds, axis=0) + + def _rvs(self, *args, size=None, random_state=None): + # convenient to work along the last axis here to avoid interference with `size` + p = np.stack(args, axis=-1) + # Size passed by the user is the *shape of the returned array*, so it won't + # contain the length of the last axis of p. + size = (p.shape if size is None else + (size, 1) if np.isscalar(size) else tuple(size) + (1,)) + size = np.broadcast_shapes(p.shape, size) + return bernoulli._rvs(p, size=size, random_state=random_state).sum(axis=-1) + + def _get_support(self, *args): + return 0, len(args) + + def _pmf(self, k, *args): + k = np.atleast_1d(k).astype(np.int64) + k, *args = np.broadcast_arrays(k, *args) + args = np.asarray(args, dtype=np.float64) + return _poisson_binom(k, args, 'pmf') + + def _cdf(self, k, *args): + k = np.atleast_1d(k).astype(np.int64) + k, *args = np.broadcast_arrays(k, *args) + args = np.asarray(args, dtype=np.float64) + return _poisson_binom(k, args, 'cdf') + + def _stats(self, *args, **kwds): + p = np.stack(args, axis=0) + mean = np.sum(p, axis=0) + var = np.sum(p * (1-p), axis=0) + return (mean, var, None, None) + + def __call__(self, *args, **kwds): + return poisson_binomial_frozen(self, *args, **kwds) + + +poisson_binom = poisson_binom_gen(name='poisson_binom', longname='A Poisson binomial', + shapes='p') + +# The _parse_args methods don't work with vector-valued shape parameters, so we rewrite +# them. Note that `p` is accepted as an array with the index `i` of `p_i` corresponding +# with the last axis; we return it as a tuple (p_1, p_2, ..., p_n) so that it looks +# like `n` scalar (or arrays of scalar-valued) shape parameters to the infrastructure. + +def _parse_args_rvs(self, p, loc=0, size=None): + return tuple(np.moveaxis(p, -1, 0)), loc, 1.0, size + +def _parse_args_stats(self, p, loc=0, moments='mv'): + return tuple(np.moveaxis(p, -1, 0)), loc, 1.0, moments + +def _parse_args(self, p, loc=0): + return tuple(np.moveaxis(p, -1, 0)), loc, 1.0 + +# The infrastructure manually binds these methods to the instance, so +# we can only override them by manually binding them, too. +_pb_obj, _pb_cls = poisson_binom, poisson_binom_gen # shorter names (for PEP8) +poisson_binom._parse_args_rvs = _parse_args_rvs.__get__(_pb_obj, _pb_cls) +poisson_binom._parse_args_stats = _parse_args_stats.__get__(_pb_obj, _pb_cls) +poisson_binom._parse_args = _parse_args.__get__(_pb_obj, _pb_cls) + +class poisson_binomial_frozen(rv_discrete_frozen): + # copied from rv_frozen; we just need to bind the `_parse_args` methods + def __init__(self, dist, *args, **kwds): # verbatim + self.args = args # verbatim + self.kwds = kwds # verbatim + + # create a new instance # verbatim + self.dist = dist.__class__(**dist._updated_ctor_param()) # verbatim + + # Here is the only modification + self.dist._parse_args_rvs = _parse_args_rvs.__get__(_pb_obj, _pb_cls) + self.dist._parse_args_stats = _parse_args_stats.__get__(_pb_obj, _pb_cls) + self.dist._parse_args = _parse_args.__get__(_pb_obj, _pb_cls) + + shapes, _, _ = self.dist._parse_args(*args, **kwds) # verbatim + self.a, self.b = self.dist._get_support(*shapes) # verbatim + + def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds): + a, loc, scale = self.dist._parse_args(*self.args, **self.kwds) + # Here's the modification: we pass all args (including `loc`) into the `args` + # parameter of `expect` so the shape only goes through `_parse_args` once. + return self.dist.expect(func, self.args, loc, lb, ub, conditional, **kwds) + + +class skellam_gen(rv_discrete): + r"""A Skellam discrete random variable. + + %(before_notes)s + + Notes + ----- + Probability distribution of the difference of two correlated or + uncorrelated Poisson random variables. + + Let :math:`k_1` and :math:`k_2` be two Poisson-distributed r.v. with + expected values :math:`\lambda_1` and :math:`\lambda_2`. Then, + :math:`k_1 - k_2` follows a Skellam distribution with parameters + :math:`\mu_1 = \lambda_1 - \rho \sqrt{\lambda_1 \lambda_2}` and + :math:`\mu_2 = \lambda_2 - \rho \sqrt{\lambda_1 \lambda_2}`, where + :math:`\rho` is the correlation coefficient between :math:`k_1` and + :math:`k_2`. If the two Poisson-distributed r.v. are independent then + :math:`\rho = 0`. + + Parameters :math:`\mu_1` and :math:`\mu_2` must be strictly positive. + + For details see: https://en.wikipedia.org/wiki/Skellam_distribution + + `skellam` takes :math:`\mu_1` and :math:`\mu_2` as shape parameters. + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("mu1", False, (0, np.inf), (False, False)), + _ShapeInfo("mu2", False, (0, np.inf), (False, False))] + + def _rvs(self, mu1, mu2, size=None, random_state=None): + n = size + return (random_state.poisson(mu1, n) - + random_state.poisson(mu2, n)) + + def _pmf(self, x, mu1, mu2): + with np.errstate(over='ignore'): # see gh-17432 + px = np.where(x < 0, + scu._ncx2_pdf(2*mu2, 2*(1-x), 2*mu1)*2, + scu._ncx2_pdf(2*mu1, 2*(1+x), 2*mu2)*2) + # ncx2.pdf() returns nan's for extremely low probabilities + return px + + def _cdf(self, x, mu1, mu2): + x = floor(x) + with np.errstate(over='ignore'): # see gh-17432 + px = np.where(x < 0, + scu._ncx2_cdf(2*mu2, -2*x, 2*mu1), + 1 - scu._ncx2_cdf(2*mu1, 2*(x+1), 2*mu2)) + return px + + def _stats(self, mu1, mu2): + mean = mu1 - mu2 + var = mu1 + mu2 + g1 = mean / sqrt((var)**3) + g2 = 1 / var + return mean, var, g1, g2 + + +skellam = skellam_gen(a=-np.inf, name="skellam", longname='A Skellam') + + +class yulesimon_gen(rv_discrete): + r"""A Yule-Simon discrete random variable. + + %(before_notes)s + + Notes + ----- + + The probability mass function for the `yulesimon` is: + + .. math:: + + f(k) = \alpha B(k, \alpha+1) + + for :math:`k=1,2,3,...`, where :math:`\alpha>0`. + Here :math:`B` refers to the `scipy.special.beta` function. + + The sampling of random variates is based on pg 553, Section 6.3 of [1]_. + Our notation maps to the referenced logic via :math:`\alpha=a-1`. + + For details see the wikipedia entry [2]_. + + References + ---------- + .. [1] Devroye, Luc. "Non-uniform Random Variate Generation", + (1986) Springer, New York. + + .. [2] https://en.wikipedia.org/wiki/Yule-Simon_distribution + + %(after_notes)s + + %(example)s + + """ + def _shape_info(self): + return [_ShapeInfo("alpha", False, (0, np.inf), (False, False))] + + def _rvs(self, alpha, size=None, random_state=None): + E1 = random_state.standard_exponential(size) + E2 = random_state.standard_exponential(size) + ans = ceil(-E1 / log1p(-exp(-E2 / alpha))) + return ans + + def _pmf(self, x, alpha): + return alpha * special.beta(x, alpha + 1) + + def _argcheck(self, alpha): + return (alpha > 0) + + def _logpmf(self, x, alpha): + return log(alpha) + special.betaln(x, alpha + 1) + + def _cdf(self, x, alpha): + return 1 - x * special.beta(x, alpha + 1) + + def _sf(self, x, alpha): + return x * special.beta(x, alpha + 1) + + def _logsf(self, x, alpha): + return log(x) + special.betaln(x, alpha + 1) + + def _stats(self, alpha): + mu = np.where(alpha <= 1, np.inf, alpha / (alpha - 1)) + mu2 = np.where(alpha > 2, + alpha**2 / ((alpha - 2.0) * (alpha - 1)**2), + np.inf) + mu2 = np.where(alpha <= 1, np.nan, mu2) + g1 = np.where(alpha > 3, + sqrt(alpha - 2) * (alpha + 1)**2 / (alpha * (alpha - 3)), + np.inf) + g1 = np.where(alpha <= 2, np.nan, g1) + g2 = np.where(alpha > 4, + alpha + 3 + ((11 * alpha**3 - 49 * alpha - 22) / + (alpha * (alpha - 4) * (alpha - 3))), + np.inf) + g2 = np.where(alpha <= 2, np.nan, g2) + return mu, mu2, g1, g2 + + +yulesimon = yulesimon_gen(name='yulesimon', a=1) + + +class _nchypergeom_gen(rv_discrete): + r"""A noncentral hypergeometric discrete random variable. + + For subclassing by nchypergeom_fisher_gen and nchypergeom_wallenius_gen. + + """ + + rvs_name = None + dist = None + + def _shape_info(self): + return [_ShapeInfo("M", True, (0, np.inf), (True, False)), + _ShapeInfo("n", True, (0, np.inf), (True, False)), + _ShapeInfo("N", True, (0, np.inf), (True, False)), + _ShapeInfo("odds", False, (0, np.inf), (False, False))] + + def _get_support(self, M, n, N, odds): + N, m1, n = M, n, N # follow Wikipedia notation + m2 = N - m1 + x_min = np.maximum(0, n - m2) + x_max = np.minimum(n, m1) + return x_min, x_max + + def _argcheck(self, M, n, N, odds): + M, n = np.asarray(M), np.asarray(n), + N, odds = np.asarray(N), np.asarray(odds) + cond1 = (M.astype(int) == M) & (M >= 0) + cond2 = (n.astype(int) == n) & (n >= 0) + cond3 = (N.astype(int) == N) & (N >= 0) + cond4 = odds > 0 + cond5 = N <= M + cond6 = n <= M + return cond1 & cond2 & cond3 & cond4 & cond5 & cond6 + + def _rvs(self, M, n, N, odds, size=None, random_state=None): + + @_vectorize_rvs_over_shapes + def _rvs1(M, n, N, odds, size, random_state): + length = np.prod(size) + urn = _PyStochasticLib3() + rv_gen = getattr(urn, self.rvs_name) + rvs = rv_gen(N, n, M, odds, length, random_state) + rvs = rvs.reshape(size) + return rvs + + return _rvs1(M, n, N, odds, size=size, random_state=random_state) + + def _pmf(self, x, M, n, N, odds): + + x, M, n, N, odds = np.broadcast_arrays(x, M, n, N, odds) + if x.size == 0: # np.vectorize doesn't work with zero size input + return np.empty_like(x) + + @np.vectorize + def _pmf1(x, M, n, N, odds): + urn = self.dist(N, n, M, odds, 1e-12) + return urn.probability(x) + + return _pmf1(x, M, n, N, odds) + + def _stats(self, M, n, N, odds, moments): + + @np.vectorize + def _moments1(M, n, N, odds): + urn = self.dist(N, n, M, odds, 1e-12) + return urn.moments() + + m, v = (_moments1(M, n, N, odds) if ("m" in moments or "v" in moments) + else (None, None)) + s, k = None, None + return m, v, s, k + + +class nchypergeom_fisher_gen(_nchypergeom_gen): + r"""A Fisher's noncentral hypergeometric discrete random variable. + + Fisher's noncentral hypergeometric distribution models drawing objects of + two types from a bin. `M` is the total number of objects, `n` is the + number of Type I objects, and `odds` is the odds ratio: the odds of + selecting a Type I object rather than a Type II object when there is only + one object of each type. + The random variate represents the number of Type I objects drawn if we + take a handful of objects from the bin at once and find out afterwards + that we took `N` objects. + + %(before_notes)s + + See Also + -------- + nchypergeom_wallenius, hypergeom, nhypergeom + + Notes + ----- + Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond + with parameters `N`, `n`, and `M` (respectively) as defined above. + + The probability mass function is defined as + + .. math:: + + p(x; M, n, N, \omega) = + \frac{\binom{n}{x}\binom{M - n}{N-x}\omega^x}{P_0}, + + for + :math:`x \in [x_l, x_u]`, + :math:`M \in {\mathbb N}`, + :math:`n \in [0, M]`, + :math:`N \in [0, M]`, + :math:`\omega > 0`, + where + :math:`x_l = \max(0, N - (M - n))`, + :math:`x_u = \min(N, n)`, + + .. math:: + + P_0 = \sum_{y=x_l}^{x_u} \binom{n}{y}\binom{M - n}{N-y}\omega^y, + + and the binomial coefficients are defined as + + .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}. + + `nchypergeom_fisher` uses the BiasedUrn package by Agner Fog with + permission for it to be distributed under SciPy's license. + + The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not + universally accepted; they are chosen for consistency with `hypergeom`. + + Note that Fisher's noncentral hypergeometric distribution is distinct + from Wallenius' noncentral hypergeometric distribution, which models + drawing a pre-determined `N` objects from a bin one by one. + When the odds ratio is unity, however, both distributions reduce to the + ordinary hypergeometric distribution. + + %(after_notes)s + + References + ---------- + .. [1] Agner Fog, "Biased Urn Theory". + https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf + + .. [2] "Fisher's noncentral hypergeometric distribution", Wikipedia, + https://en.wikipedia.org/wiki/Fisher's_noncentral_hypergeometric_distribution + + %(example)s + + """ + + rvs_name = "rvs_fisher" + dist = _PyFishersNCHypergeometric + + +nchypergeom_fisher = nchypergeom_fisher_gen( + name='nchypergeom_fisher', + longname="A Fisher's noncentral hypergeometric") + + +class nchypergeom_wallenius_gen(_nchypergeom_gen): + r"""A Wallenius' noncentral hypergeometric discrete random variable. + + Wallenius' noncentral hypergeometric distribution models drawing objects of + two types from a bin. `M` is the total number of objects, `n` is the + number of Type I objects, and `odds` is the odds ratio: the odds of + selecting a Type I object rather than a Type II object when there is only + one object of each type. + The random variate represents the number of Type I objects drawn if we + draw a pre-determined `N` objects from a bin one by one. + + %(before_notes)s + + See Also + -------- + nchypergeom_fisher, hypergeom, nhypergeom + + Notes + ----- + Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond + with parameters `N`, `n`, and `M` (respectively) as defined above. + + The probability mass function is defined as + + .. math:: + + p(x; N, n, M) = \binom{n}{x} \binom{M - n}{N-x} + \int_0^1 \left(1-t^{\omega/D}\right)^x\left(1-t^{1/D}\right)^{N-x} dt + + for + :math:`x \in [x_l, x_u]`, + :math:`M \in {\mathbb N}`, + :math:`n \in [0, M]`, + :math:`N \in [0, M]`, + :math:`\omega > 0`, + where + :math:`x_l = \max(0, N - (M - n))`, + :math:`x_u = \min(N, n)`, + + .. math:: + + D = \omega(n - x) + ((M - n)-(N-x)), + + and the binomial coefficients are defined as + + .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}. + + `nchypergeom_wallenius` uses the BiasedUrn package by Agner Fog with + permission for it to be distributed under SciPy's license. + + The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not + universally accepted; they are chosen for consistency with `hypergeom`. + + Note that Wallenius' noncentral hypergeometric distribution is distinct + from Fisher's noncentral hypergeometric distribution, which models + take a handful of objects from the bin at once, finding out afterwards + that `N` objects were taken. + When the odds ratio is unity, however, both distributions reduce to the + ordinary hypergeometric distribution. + + %(after_notes)s + + References + ---------- + .. [1] Agner Fog, "Biased Urn Theory". + https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf + + .. [2] "Wallenius' noncentral hypergeometric distribution", Wikipedia, + https://en.wikipedia.org/wiki/Wallenius'_noncentral_hypergeometric_distribution + + %(example)s + + """ + + rvs_name = "rvs_wallenius" + dist = _PyWalleniusNCHypergeometric + + +nchypergeom_wallenius = nchypergeom_wallenius_gen( + name='nchypergeom_wallenius', + longname="A Wallenius' noncentral hypergeometric") + + +# Collect names of classes and objects in this module. +pairs = list(globals().copy().items()) +_distn_names, _distn_gen_names = get_distribution_names(pairs, rv_discrete) + +__all__ = _distn_names + _distn_gen_names diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distn_infrastructure.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distn_infrastructure.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2d8134f8679332a58e1c522332b96e50256116 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distn_infrastructure.py @@ -0,0 +1,4174 @@ +# +# Author: Travis Oliphant 2002-2011 with contributions from +# SciPy Developers 2004-2011 +# +from scipy._lib._util import getfullargspec_no_self as _getfullargspec + +import sys +import keyword +import re +import types +import warnings +from itertools import zip_longest + +from scipy._lib import doccer +from ._distr_params import distcont, distdiscrete +from scipy._lib._util import check_random_state, _lazywhere + +from scipy.special import comb, entr + + +# for root finding for continuous distribution ppf, and maximum likelihood +# estimation +from scipy import optimize + +# for functions of continuous distributions (e.g. moments, entropy, cdf) +from scipy import integrate + +# to approximate the pdf of a continuous distribution given its cdf +from scipy._lib._finite_differences import _derivative + +# for scipy.stats.entropy. Attempts to import just that function or file +# have cause import problems +from scipy import stats + +from numpy import (arange, putmask, ones, shape, ndarray, zeros, floor, + logical_and, log, sqrt, place, argmax, vectorize, asarray, + nan, inf, isinf, empty) + +import numpy as np +from ._constants import _XMAX, _LOGXMAX +from ._censored_data import CensoredData +from scipy.stats._warnings_errors import FitError + +# These are the docstring parts used for substitution in specific +# distribution docstrings + +docheaders = {'methods': """\nMethods\n-------\n""", + 'notes': """\nNotes\n-----\n""", + 'examples': """\nExamples\n--------\n"""} + +_doc_rvs = """\ +rvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None) + Random variates. +""" +_doc_pdf = """\ +pdf(x, %(shapes)s, loc=0, scale=1) + Probability density function. +""" +_doc_logpdf = """\ +logpdf(x, %(shapes)s, loc=0, scale=1) + Log of the probability density function. +""" +_doc_pmf = """\ +pmf(k, %(shapes)s, loc=0, scale=1) + Probability mass function. +""" +_doc_logpmf = """\ +logpmf(k, %(shapes)s, loc=0, scale=1) + Log of the probability mass function. +""" +_doc_cdf = """\ +cdf(x, %(shapes)s, loc=0, scale=1) + Cumulative distribution function. +""" +_doc_logcdf = """\ +logcdf(x, %(shapes)s, loc=0, scale=1) + Log of the cumulative distribution function. +""" +_doc_sf = """\ +sf(x, %(shapes)s, loc=0, scale=1) + Survival function (also defined as ``1 - cdf``, but `sf` is sometimes more accurate). +""" # noqa: E501 +_doc_logsf = """\ +logsf(x, %(shapes)s, loc=0, scale=1) + Log of the survival function. +""" +_doc_ppf = """\ +ppf(q, %(shapes)s, loc=0, scale=1) + Percent point function (inverse of ``cdf`` --- percentiles). +""" +_doc_isf = """\ +isf(q, %(shapes)s, loc=0, scale=1) + Inverse survival function (inverse of ``sf``). +""" +_doc_moment = """\ +moment(order, %(shapes)s, loc=0, scale=1) + Non-central moment of the specified order. +""" +_doc_stats = """\ +stats(%(shapes)s, loc=0, scale=1, moments='mv') + Mean('m'), variance('v'), skew('s'), and/or kurtosis('k'). +""" +_doc_entropy = """\ +entropy(%(shapes)s, loc=0, scale=1) + (Differential) entropy of the RV. +""" +_doc_fit = """\ +fit(data) + Parameter estimates for generic data. + See `scipy.stats.rv_continuous.fit `__ for detailed documentation of the + keyword arguments. +""" # noqa: E501 +_doc_expect = """\ +expect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds) + Expected value of a function (of one argument) with respect to the distribution. +""" # noqa: E501 +_doc_expect_discrete = """\ +expect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False) + Expected value of a function (of one argument) with respect to the distribution. +""" +_doc_median = """\ +median(%(shapes)s, loc=0, scale=1) + Median of the distribution. +""" +_doc_mean = """\ +mean(%(shapes)s, loc=0, scale=1) + Mean of the distribution. +""" +_doc_var = """\ +var(%(shapes)s, loc=0, scale=1) + Variance of the distribution. +""" +_doc_std = """\ +std(%(shapes)s, loc=0, scale=1) + Standard deviation of the distribution. +""" +_doc_interval = """\ +interval(confidence, %(shapes)s, loc=0, scale=1) + Confidence interval with equal areas around the median. +""" +_doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf, + _doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf, + _doc_logsf, _doc_ppf, _doc_isf, _doc_moment, + _doc_stats, _doc_entropy, _doc_fit, + _doc_expect, _doc_median, + _doc_mean, _doc_var, _doc_std, _doc_interval]) + +_doc_default_longsummary = """\ +As an instance of the `rv_continuous` class, `%(name)s` object inherits from it +a collection of generic methods (see below for the full list), +and completes them with details specific for this particular distribution. +""" + +_doc_default_frozen_note = """ +Alternatively, the object may be called (as a function) to fix the shape, +location, and scale parameters returning a "frozen" continuous RV object: + +rv = %(name)s(%(shapes)s, loc=0, scale=1) + - Frozen RV object with the same methods but holding the given shape, + location, and scale fixed. +""" +_doc_default_example = """\ +Examples +-------- +>>> import numpy as np +>>> from scipy.stats import %(name)s +>>> import matplotlib.pyplot as plt +>>> fig, ax = plt.subplots(1, 1) + +Calculate the first four moments: + +%(set_vals_stmt)s +>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') + +Display the probability density function (``pdf``): + +>>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s), +... %(name)s.ppf(0.99, %(shapes)s), 100) +>>> ax.plot(x, %(name)s.pdf(x, %(shapes)s), +... 'r-', lw=5, alpha=0.6, label='%(name)s pdf') + +Alternatively, the distribution object can be called (as a function) +to fix the shape, location and scale parameters. This returns a "frozen" +RV object holding the given parameters fixed. + +Freeze the distribution and display the frozen ``pdf``: + +>>> rv = %(name)s(%(shapes)s) +>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') + +Check accuracy of ``cdf`` and ``ppf``: + +>>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s) +>>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s)) +True + +Generate random numbers: + +>>> r = %(name)s.rvs(%(shapes)s, size=1000) + +And compare the histogram: + +>>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2) +>>> ax.set_xlim([x[0], x[-1]]) +>>> ax.legend(loc='best', frameon=False) +>>> plt.show() + +""" + +_doc_default_locscale = """\ +The probability density above is defined in the "standardized" form. To shift +and/or scale the distribution use the ``loc`` and ``scale`` parameters. +Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically +equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with +``y = (x - loc) / scale``. Note that shifting the location of a distribution +does not make it a "noncentral" distribution; noncentral generalizations of +some distributions are available in separate classes. +""" + +_doc_default = ''.join([_doc_default_longsummary, + _doc_allmethods, + '\n', + _doc_default_example]) + +_doc_default_before_notes = ''.join([_doc_default_longsummary, + _doc_allmethods]) + +docdict = { + 'rvs': _doc_rvs, + 'pdf': _doc_pdf, + 'logpdf': _doc_logpdf, + 'cdf': _doc_cdf, + 'logcdf': _doc_logcdf, + 'sf': _doc_sf, + 'logsf': _doc_logsf, + 'ppf': _doc_ppf, + 'isf': _doc_isf, + 'stats': _doc_stats, + 'entropy': _doc_entropy, + 'fit': _doc_fit, + 'moment': _doc_moment, + 'expect': _doc_expect, + 'interval': _doc_interval, + 'mean': _doc_mean, + 'std': _doc_std, + 'var': _doc_var, + 'median': _doc_median, + 'allmethods': _doc_allmethods, + 'longsummary': _doc_default_longsummary, + 'frozennote': _doc_default_frozen_note, + 'example': _doc_default_example, + 'default': _doc_default, + 'before_notes': _doc_default_before_notes, + 'after_notes': _doc_default_locscale +} + +# Reuse common content between continuous and discrete docs, change some +# minor bits. +docdict_discrete = docdict.copy() + +docdict_discrete['pmf'] = _doc_pmf +docdict_discrete['logpmf'] = _doc_logpmf +docdict_discrete['expect'] = _doc_expect_discrete +_doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf', + 'ppf', 'isf', 'stats', 'entropy', 'expect', 'median', + 'mean', 'var', 'std', 'interval'] +for obj in _doc_disc_methods: + docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '') + +_doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf'] +for obj in _doc_disc_methods_err_varname: + docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ') + +docdict_discrete.pop('pdf') +docdict_discrete.pop('logpdf') + +_doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods]) +docdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods + +docdict_discrete['longsummary'] = _doc_default_longsummary.replace( + 'rv_continuous', 'rv_discrete') + +_doc_default_frozen_note = """ +Alternatively, the object may be called (as a function) to fix the shape and +location parameters returning a "frozen" discrete RV object: + +rv = %(name)s(%(shapes)s, loc=0) + - Frozen RV object with the same methods but holding the given shape and + location fixed. +""" +docdict_discrete['frozennote'] = _doc_default_frozen_note + +_doc_default_discrete_example = """\ +Examples +-------- +>>> import numpy as np +>>> from scipy.stats import %(name)s +>>> import matplotlib.pyplot as plt +>>> fig, ax = plt.subplots(1, 1) + +Calculate the first four moments: + +%(set_vals_stmt)s +>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') + +Display the probability mass function (``pmf``): + +>>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s), +... %(name)s.ppf(0.99, %(shapes)s)) +>>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf') +>>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5) + +Alternatively, the distribution object can be called (as a function) +to fix the shape and location. This returns a "frozen" RV object holding +the given parameters fixed. + +Freeze the distribution and display the frozen ``pmf``: + +>>> rv = %(name)s(%(shapes)s) +>>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1, +... label='frozen pmf') +>>> ax.legend(loc='best', frameon=False) +>>> plt.show() + +Check accuracy of ``cdf`` and ``ppf``: + +>>> prob = %(name)s.cdf(x, %(shapes)s) +>>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s)) +True + +Generate random numbers: + +>>> r = %(name)s.rvs(%(shapes)s, size=1000) +""" + + +_doc_default_discrete_locscale = """\ +The probability mass function above is defined in the "standardized" form. +To shift distribution use the ``loc`` parameter. +Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically +equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``. +""" + +docdict_discrete['example'] = _doc_default_discrete_example +docdict_discrete['after_notes'] = _doc_default_discrete_locscale + +_doc_default_before_notes = ''.join([docdict_discrete['longsummary'], + docdict_discrete['allmethods']]) +docdict_discrete['before_notes'] = _doc_default_before_notes + +_doc_default_disc = ''.join([docdict_discrete['longsummary'], + docdict_discrete['allmethods'], + docdict_discrete['frozennote'], + docdict_discrete['example']]) +docdict_discrete['default'] = _doc_default_disc + +# clean up all the separate docstring elements, we do not need them anymore +for obj in [s for s in dir() if s.startswith('_doc_')]: + exec('del ' + obj) +del obj + + +def _moment(data, n, mu=None): + if mu is None: + mu = data.mean() + return ((data - mu)**n).mean() + + +def _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args): + if (n == 0): + return 1.0 + elif (n == 1): + if mu is None: + val = moment_func(1, *args) + else: + val = mu + elif (n == 2): + if mu2 is None or mu is None: + val = moment_func(2, *args) + else: + val = mu2 + mu*mu + elif (n == 3): + if g1 is None or mu2 is None or mu is None: + val = moment_func(3, *args) + else: + mu3 = g1 * np.power(mu2, 1.5) # 3rd central moment + val = mu3+3*mu*mu2+mu*mu*mu # 3rd non-central moment + elif (n == 4): + if g1 is None or g2 is None or mu2 is None or mu is None: + val = moment_func(4, *args) + else: + mu4 = (g2+3.0)*(mu2**2.0) # 4th central moment + mu3 = g1*np.power(mu2, 1.5) # 3rd central moment + val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu + else: + val = moment_func(n, *args) + + return val + + +def _skew(data): + """ + skew is third central moment / variance**(1.5) + """ + data = np.ravel(data) + mu = data.mean() + m2 = ((data - mu)**2).mean() + m3 = ((data - mu)**3).mean() + return m3 / np.power(m2, 1.5) + + +def _kurtosis(data): + """Fisher's excess kurtosis is fourth central moment / variance**2 - 3.""" + data = np.ravel(data) + mu = data.mean() + m2 = ((data - mu)**2).mean() + m4 = ((data - mu)**4).mean() + return m4 / m2**2 - 3 + +def _vectorize_rvs_over_shapes(_rvs1): + """Decorator that vectorizes _rvs method to work on ndarray shapes""" + # _rvs1 must be a _function_ that accepts _scalar_ args as positional + # arguments, `size` and `random_state` as keyword arguments. + # _rvs1 must return a random variate array with shape `size`. If `size` is + # None, _rvs1 must return a scalar. + # When applied to _rvs1, this decorator broadcasts ndarray args + # and loops over them, calling _rvs1 for each set of scalar args. + # For usage example, see _nchypergeom_gen + def _rvs(*args, size, random_state): + _rvs1_size, _rvs1_indices = _check_shape(args[0].shape, size) + + size = np.array(size) + _rvs1_size = np.array(_rvs1_size) + _rvs1_indices = np.array(_rvs1_indices) + + if np.all(_rvs1_indices): # all args are scalars + return _rvs1(*args, size, random_state) + + out = np.empty(size) + + # out.shape can mix dimensions associated with arg_shape and _rvs1_size + # Sort them to arg_shape + _rvs1_size for easy indexing of dimensions + # corresponding with the different sets of scalar args + j0 = np.arange(out.ndim) + j1 = np.hstack((j0[~_rvs1_indices], j0[_rvs1_indices])) + out = np.moveaxis(out, j1, j0) + + for i in np.ndindex(*size[~_rvs1_indices]): + # arg can be squeezed because singleton dimensions will be + # associated with _rvs1_size, not arg_shape per _check_shape + out[i] = _rvs1(*[np.squeeze(arg)[i] for arg in args], + _rvs1_size, random_state) + + return np.moveaxis(out, j0, j1) # move axes back before returning + return _rvs + + +def _fit_determine_optimizer(optimizer): + if not callable(optimizer) and isinstance(optimizer, str): + if not optimizer.startswith('fmin_'): + optimizer = "fmin_"+optimizer + if optimizer == 'fmin_': + optimizer = 'fmin' + try: + optimizer = getattr(optimize, optimizer) + except AttributeError as e: + raise ValueError(f"{optimizer} is not a valid optimizer") from e + return optimizer + +def _isintegral(x): + return x == np.round(x) + +def _sum_finite(x): + """ + For a 1D array x, return a tuple containing the sum of the + finite values of x and the number of nonfinite values. + + This is a utility function used when evaluating the negative + loglikelihood for a distribution and an array of samples. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats._distn_infrastructure import _sum_finite + >>> tot, nbad = _sum_finite(np.array([-2, -np.inf, 5, 1])) + >>> tot + 4.0 + >>> nbad + 1 + """ + finite_x = np.isfinite(x) + bad_count = finite_x.size - np.count_nonzero(finite_x) + return np.sum(x[finite_x]), bad_count + + +# Frozen RV class +class rv_frozen: + + def __init__(self, dist, *args, **kwds): + self.args = args + self.kwds = kwds + + # create a new instance + self.dist = dist.__class__(**dist._updated_ctor_param()) + + shapes, _, _ = self.dist._parse_args(*args, **kwds) + self.a, self.b = self.dist._get_support(*shapes) + + @property + def random_state(self): + return self.dist._random_state + + @random_state.setter + def random_state(self, seed): + self.dist._random_state = check_random_state(seed) + + def cdf(self, x): + return self.dist.cdf(x, *self.args, **self.kwds) + + def logcdf(self, x): + return self.dist.logcdf(x, *self.args, **self.kwds) + + def ppf(self, q): + return self.dist.ppf(q, *self.args, **self.kwds) + + def isf(self, q): + return self.dist.isf(q, *self.args, **self.kwds) + + def rvs(self, size=None, random_state=None): + kwds = self.kwds.copy() + kwds.update({'size': size, 'random_state': random_state}) + return self.dist.rvs(*self.args, **kwds) + + def sf(self, x): + return self.dist.sf(x, *self.args, **self.kwds) + + def logsf(self, x): + return self.dist.logsf(x, *self.args, **self.kwds) + + def stats(self, moments='mv'): + kwds = self.kwds.copy() + kwds.update({'moments': moments}) + return self.dist.stats(*self.args, **kwds) + + def median(self): + return self.dist.median(*self.args, **self.kwds) + + def mean(self): + return self.dist.mean(*self.args, **self.kwds) + + def var(self): + return self.dist.var(*self.args, **self.kwds) + + def std(self): + return self.dist.std(*self.args, **self.kwds) + + def moment(self, order=None): + return self.dist.moment(order, *self.args, **self.kwds) + + def entropy(self): + return self.dist.entropy(*self.args, **self.kwds) + + def interval(self, confidence=None): + return self.dist.interval(confidence, *self.args, **self.kwds) + + def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds): + # expect method only accepts shape parameters as positional args + # hence convert self.args, self.kwds, also loc/scale + # See the .expect method docstrings for the meaning of + # other parameters. + a, loc, scale = self.dist._parse_args(*self.args, **self.kwds) + if isinstance(self.dist, rv_discrete): + return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds) + else: + return self.dist.expect(func, a, loc, scale, lb, ub, + conditional, **kwds) + + def support(self): + return self.dist.support(*self.args, **self.kwds) + + +class rv_discrete_frozen(rv_frozen): + + def pmf(self, k): + return self.dist.pmf(k, *self.args, **self.kwds) + + def logpmf(self, k): # No error + return self.dist.logpmf(k, *self.args, **self.kwds) + + +class rv_continuous_frozen(rv_frozen): + + def pdf(self, x): + return self.dist.pdf(x, *self.args, **self.kwds) + + def logpdf(self, x): + return self.dist.logpdf(x, *self.args, **self.kwds) + + +def argsreduce(cond, *args): + """Clean arguments to: + + 1. Ensure all arguments are iterable (arrays of dimension at least one + 2. If cond != True and size > 1, ravel(args[i]) where ravel(condition) is + True, in 1D. + + Return list of processed arguments. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats._distn_infrastructure import argsreduce + >>> rng = np.random.default_rng() + >>> A = rng.random((4, 5)) + >>> B = 2 + >>> C = rng.random((1, 5)) + >>> cond = np.ones(A.shape) + >>> [A1, B1, C1] = argsreduce(cond, A, B, C) + >>> A1.shape + (4, 5) + >>> B1.shape + (1,) + >>> C1.shape + (1, 5) + >>> cond[2,:] = 0 + >>> [A1, B1, C1] = argsreduce(cond, A, B, C) + >>> A1.shape + (15,) + >>> B1.shape + (1,) + >>> C1.shape + (15,) + + """ + # some distributions assume arguments are iterable. + newargs = np.atleast_1d(*args) + + # np.atleast_1d returns an array if only one argument, or a list of arrays + # if more than one argument. + if not isinstance(newargs, (list | tuple)): + newargs = (newargs,) + + if np.all(cond): + # broadcast arrays with cond + *newargs, cond = np.broadcast_arrays(*newargs, cond) + return [arg.ravel() for arg in newargs] + + s = cond.shape + # np.extract returns flattened arrays, which are not broadcastable together + # unless they are either the same size or size == 1. + return [(arg if np.size(arg) == 1 + else np.extract(cond, np.broadcast_to(arg, s))) + for arg in newargs] + + +parse_arg_template = """ +def _parse_args(self, %(shape_arg_str)s %(locscale_in)s): + return (%(shape_arg_str)s), %(locscale_out)s + +def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None): + return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size) + +def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'): + return (%(shape_arg_str)s), %(locscale_out)s, moments +""" + + +class rv_generic: + """Class which encapsulates common functionality between rv_discrete + and rv_continuous. + + """ + + def __init__(self, seed=None): + super().__init__() + + # figure out if _stats signature has 'moments' keyword + sig = _getfullargspec(self._stats) + self._stats_has_moments = ((sig.varkw is not None) or + ('moments' in sig.args) or + ('moments' in sig.kwonlyargs)) + self._random_state = check_random_state(seed) + + @property + def random_state(self): + """Get or set the generator object for generating random variates. + + If `random_state` is None (or `np.random`), the + `numpy.random.RandomState` singleton is used. + If `random_state` is an int, a new ``RandomState`` instance is used, + seeded with `random_state`. + If `random_state` is already a ``Generator`` or ``RandomState`` + instance, that instance is used. + + """ + return self._random_state + + @random_state.setter + def random_state(self, seed): + self._random_state = check_random_state(seed) + + def __setstate__(self, state): + try: + self.__dict__.update(state) + # attaches the dynamically created methods on each instance. + # if a subclass overrides rv_generic.__setstate__, or implements + # it's own _attach_methods, then it must make sure that + # _attach_argparser_methods is called. + self._attach_methods() + except ValueError: + # reconstitute an old pickle scipy<1.6, that contains + # (_ctor_param, random_state) as state + self._ctor_param = state[0] + self._random_state = state[1] + self.__init__() + + def _attach_methods(self): + """Attaches dynamically created methods to the rv_* instance. + + This method must be overridden by subclasses, and must itself call + _attach_argparser_methods. This method is called in __init__ in + subclasses, and in __setstate__ + """ + raise NotImplementedError + + def _attach_argparser_methods(self): + """ + Generates the argument-parsing functions dynamically and attaches + them to the instance. + + Should be called from `_attach_methods`, typically in __init__ and + during unpickling (__setstate__) + """ + ns = {} + exec(self._parse_arg_template, ns) + # NB: attach to the instance, not class + for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']: + setattr(self, name, types.MethodType(ns[name], self)) + + def _construct_argparser( + self, meths_to_inspect, locscale_in, locscale_out): + """Construct the parser string for the shape arguments. + + This method should be called in __init__ of a class for each + distribution. It creates the `_parse_arg_template` attribute that is + then used by `_attach_argparser_methods` to dynamically create and + attach the `_parse_args`, `_parse_args_stats`, `_parse_args_rvs` + methods to the instance. + + If self.shapes is a non-empty string, interprets it as a + comma-separated list of shape parameters. + + Otherwise inspects the call signatures of `meths_to_inspect` + and constructs the argument-parsing functions from these. + In this case also sets `shapes` and `numargs`. + """ + + if self.shapes: + # sanitize the user-supplied shapes + if not isinstance(self.shapes, str): + raise TypeError('shapes must be a string.') + + shapes = self.shapes.replace(',', ' ').split() + + for field in shapes: + if keyword.iskeyword(field): + raise SyntaxError('keywords cannot be used as shapes.') + if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field): + raise SyntaxError( + 'shapes must be valid python identifiers') + else: + # find out the call signatures (_pdf, _cdf etc), deduce shape + # arguments. Generic methods only have 'self, x', any further args + # are shapes. + shapes_list = [] + for meth in meths_to_inspect: + shapes_args = _getfullargspec(meth) # NB does not contain self + args = shapes_args.args[1:] # peel off 'x', too + + if args: + shapes_list.append(args) + + # *args or **kwargs are not allowed w/automatic shapes + if shapes_args.varargs is not None: + raise TypeError( + '*args are not allowed w/out explicit shapes') + if shapes_args.varkw is not None: + raise TypeError( + '**kwds are not allowed w/out explicit shapes') + if shapes_args.kwonlyargs: + raise TypeError( + 'kwonly args are not allowed w/out explicit shapes') + if shapes_args.defaults is not None: + raise TypeError('defaults are not allowed for shapes') + + if shapes_list: + shapes = shapes_list[0] + + # make sure the signatures are consistent + for item in shapes_list: + if item != shapes: + raise TypeError('Shape arguments are inconsistent.') + else: + shapes = [] + + # have the arguments, construct the method from template + shapes_str = ', '.join(shapes) + ', ' if shapes else '' # NB: not None + dct = dict(shape_arg_str=shapes_str, + locscale_in=locscale_in, + locscale_out=locscale_out, + ) + + # this string is used by _attach_argparser_methods + self._parse_arg_template = parse_arg_template % dct + + self.shapes = ', '.join(shapes) if shapes else None + if not hasattr(self, 'numargs'): + # allows more general subclassing with *args + self.numargs = len(shapes) + + def _construct_doc(self, docdict, shapes_vals=None): + """Construct the instance docstring with string substitutions.""" + tempdict = docdict.copy() + tempdict['name'] = self.name or 'distname' + tempdict['shapes'] = self.shapes or '' + + if shapes_vals is None: + shapes_vals = () + try: + vals = ', '.join(f'{val:.3g}' for val in shapes_vals) + except TypeError: + vals = ', '.join(f'{val}' for val in shapes_vals) + tempdict['vals'] = vals + + tempdict['shapes_'] = self.shapes or '' + if self.shapes and self.numargs == 1: + tempdict['shapes_'] += ',' + + if self.shapes: + tempdict['set_vals_stmt'] = f'>>> {self.shapes} = {vals}' + else: + tempdict['set_vals_stmt'] = '' + + if self.shapes is None: + # remove shapes from call parameters if there are none + for item in ['default', 'before_notes']: + tempdict[item] = tempdict[item].replace( + "\n%(shapes)s : array_like\n shape parameters", "") + for i in range(2): + if self.shapes is None: + # necessary because we use %(shapes)s in two forms (w w/o ", ") + self.__doc__ = self.__doc__.replace("%(shapes)s, ", "") + try: + self.__doc__ = doccer.docformat(self.__doc__, tempdict) + except TypeError as e: + raise Exception("Unable to construct docstring for " + f"distribution \"{self.name}\": {repr(e)}") from e + + # correct for empty shapes + self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')') + + def _construct_default_doc(self, longname=None, + docdict=None, discrete='continuous'): + """Construct instance docstring from the default template.""" + if longname is None: + longname = 'A' + self.__doc__ = ''.join([f'{longname} {discrete} random variable.', + '\n\n%(before_notes)s\n', docheaders['notes'], + '\n%(example)s']) + self._construct_doc(docdict) + + def freeze(self, *args, **kwds): + """Freeze the distribution for the given arguments. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution. Should include all + the non-optional arguments, may include ``loc`` and ``scale``. + + Returns + ------- + rv_frozen : rv_frozen instance + The frozen distribution. + + """ + if isinstance(self, rv_continuous): + return rv_continuous_frozen(self, *args, **kwds) + else: + return rv_discrete_frozen(self, *args, **kwds) + + def __call__(self, *args, **kwds): + return self.freeze(*args, **kwds) + __call__.__doc__ = freeze.__doc__ + + # The actual calculation functions (no basic checking need be done) + # If these are defined, the others won't be looked at. + # Otherwise, the other set can be defined. + def _stats(self, *args, **kwds): + return None, None, None, None + + # Noncentral moments (also known as the moment about the origin). + # Expressed in LaTeX, munp would be $\mu'_{n}$, i.e. "mu-sub-n-prime". + # The primed mu is a widely used notation for the noncentral moment. + def _munp(self, n, *args): + # Silence floating point warnings from integration. + with np.errstate(all='ignore'): + vals = self.generic_moment(n, *args) + return vals + + def _argcheck_rvs(self, *args, **kwargs): + # Handle broadcasting and size validation of the rvs method. + # Subclasses should not have to override this method. + # The rule is that if `size` is not None, then `size` gives the + # shape of the result (integer values of `size` are treated as + # tuples with length 1; i.e. `size=3` is the same as `size=(3,)`.) + # + # `args` is expected to contain the shape parameters (if any), the + # location and the scale in a flat tuple (e.g. if there are two + # shape parameters `a` and `b`, `args` will be `(a, b, loc, scale)`). + # The only keyword argument expected is 'size'. + size = kwargs.get('size', None) + all_bcast = np.broadcast_arrays(*args) + + def squeeze_left(a): + while a.ndim > 0 and a.shape[0] == 1: + a = a[0] + return a + + # Eliminate trivial leading dimensions. In the convention + # used by numpy's random variate generators, trivial leading + # dimensions are effectively ignored. In other words, when `size` + # is given, trivial leading dimensions of the broadcast parameters + # in excess of the number of dimensions in size are ignored, e.g. + # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3) + # array([ 1.00104267, 3.00422496, 4.99799278]) + # If `size` is not given, the exact broadcast shape is preserved: + # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]]) + # array([[[[ 1.00862899, 3.00061431, 4.99867122]]]]) + # + all_bcast = [squeeze_left(a) for a in all_bcast] + bcast_shape = all_bcast[0].shape + bcast_ndim = all_bcast[0].ndim + + if size is None: + size_ = bcast_shape + else: + size_ = tuple(np.atleast_1d(size)) + + # Check compatibility of size_ with the broadcast shape of all + # the parameters. This check is intended to be consistent with + # how the numpy random variate generators (e.g. np.random.normal, + # np.random.beta) handle their arguments. The rule is that, if size + # is given, it determines the shape of the output. Broadcasting + # can't change the output size. + + # This is the standard broadcasting convention of extending the + # shape with fewer dimensions with enough dimensions of length 1 + # so that the two shapes have the same number of dimensions. + ndiff = bcast_ndim - len(size_) + if ndiff < 0: + bcast_shape = (1,)*(-ndiff) + bcast_shape + elif ndiff > 0: + size_ = (1,)*ndiff + size_ + + # This compatibility test is not standard. In "regular" broadcasting, + # two shapes are compatible if for each dimension, the lengths are the + # same or one of the lengths is 1. Here, the length of a dimension in + # size_ must not be less than the corresponding length in bcast_shape. + ok = all([bcdim == 1 or bcdim == szdim + for (bcdim, szdim) in zip(bcast_shape, size_)]) + if not ok: + raise ValueError("size does not match the broadcast shape of " + f"the parameters. {size}, {size_}, {bcast_shape}") + + param_bcast = all_bcast[:-2] + loc_bcast = all_bcast[-2] + scale_bcast = all_bcast[-1] + + return param_bcast, loc_bcast, scale_bcast, size_ + + # These are the methods you must define (standard form functions) + # NB: generic _pdf, _logpdf, _cdf are different for + # rv_continuous and rv_discrete hence are defined in there + def _argcheck(self, *args): + """Default check for correct values on args and keywords. + + Returns condition array of 1's where arguments are correct and + 0's where they are not. + + """ + cond = 1 + for arg in args: + cond = logical_and(cond, (asarray(arg) > 0)) + return cond + + def _get_support(self, *args, **kwargs): + """Return the support of the (unscaled, unshifted) distribution. + + *Must* be overridden by distributions which have support dependent + upon the shape parameters of the distribution. Any such override + *must not* set or change any of the class members, as these members + are shared amongst all instances of the distribution. + + Parameters + ---------- + arg1, arg2, ... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + + Returns + ------- + a, b : numeric (float, or int or +/-np.inf) + end-points of the distribution's support for the specified + shape parameters. + """ + return self.a, self.b + + def _support_mask(self, x, *args): + a, b = self._get_support(*args) + with np.errstate(invalid='ignore'): + return (a <= x) & (x <= b) + + def _open_support_mask(self, x, *args): + a, b = self._get_support(*args) + with np.errstate(invalid='ignore'): + return (a < x) & (x < b) + + def _rvs(self, *args, size=None, random_state=None): + # This method must handle size being a tuple, and it must + # properly broadcast *args and size. size might be + # an empty tuple, which means a scalar random variate is to be + # generated. + + # Use basic inverse cdf algorithm for RV generation as default. + U = random_state.uniform(size=size) + Y = self._ppf(U, *args) + return Y + + def _logcdf(self, x, *args): + with np.errstate(divide='ignore'): + return log(self._cdf(x, *args)) + + def _sf(self, x, *args): + return 1.0-self._cdf(x, *args) + + def _logsf(self, x, *args): + with np.errstate(divide='ignore'): + return log(self._sf(x, *args)) + + def _ppf(self, q, *args): + return self._ppfvec(q, *args) + + def _isf(self, q, *args): + return self._ppf(1.0-q, *args) # use correct _ppf for subclasses + + # These are actually called, and should not be overwritten if you + # want to keep error checking. + def rvs(self, *args, **kwds): + """Random variates of given type. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + scale : array_like, optional + Scale parameter (default=1). + size : int or tuple of ints, optional + Defining number of random variates (default is 1). + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `random_state` is None (or `np.random`), the + `numpy.random.RandomState` singleton is used. + If `random_state` is an int, a new ``RandomState`` instance is + used, seeded with `random_state`. + If `random_state` is already a ``Generator`` or ``RandomState`` + instance, that instance is used. + + Returns + ------- + rvs : ndarray or scalar + Random variates of given `size`. + + """ + discrete = kwds.pop('discrete', None) + rndm = kwds.pop('random_state', None) + args, loc, scale, size = self._parse_args_rvs(*args, **kwds) + cond = logical_and(self._argcheck(*args), (scale >= 0)) + if not np.all(cond): + message = ("Domain error in arguments. The `scale` parameter must " + "be positive for all distributions, and many " + "distributions have restrictions on shape parameters. " + f"Please see the `scipy.stats.{self.name}` " + "documentation for details.") + raise ValueError(message) + + if np.all(scale == 0): + return loc*ones(size, 'd') + + # extra gymnastics needed for a custom random_state + if rndm is not None: + random_state_saved = self._random_state + random_state = check_random_state(rndm) + else: + random_state = self._random_state + + vals = self._rvs(*args, size=size, random_state=random_state) + + vals = vals * scale + loc + + # do not forget to restore the _random_state + if rndm is not None: + self._random_state = random_state_saved + + # Cast to int if discrete + if discrete and not isinstance(self, rv_sample): + if size == (): + vals = int(vals) + else: + vals = vals.astype(np.int64) + + return vals + + def stats(self, *args, **kwds): + """Some statistics of the given RV. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional (continuous RVs only) + scale parameter (default=1) + moments : str, optional + composed of letters ['mvsk'] defining which moments to compute: + 'm' = mean, + 'v' = variance, + 's' = (Fisher's) skew, + 'k' = (Fisher's) kurtosis. + (default is 'mv') + + Returns + ------- + stats : sequence + of requested moments. + + """ + args, loc, scale, moments = self._parse_args_stats(*args, **kwds) + # scale = 1 by construction for discrete RVs + loc, scale = map(asarray, (loc, scale)) + args = tuple(map(asarray, args)) + cond = self._argcheck(*args) & (scale > 0) & (loc == loc) + output = [] + default = np.full(shape(cond), fill_value=self.badvalue) + + # Use only entries that are valid in calculation + if np.any(cond): + goodargs = argsreduce(cond, *(args+(scale, loc))) + scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] + + if self._stats_has_moments: + mu, mu2, g1, g2 = self._stats(*goodargs, + **{'moments': moments}) + else: + mu, mu2, g1, g2 = self._stats(*goodargs) + + if 'm' in moments: + if mu is None: + mu = self._munp(1, *goodargs) + out0 = default.copy() + place(out0, cond, mu * scale + loc) + output.append(out0) + + if 'v' in moments: + if mu2 is None: + mu2p = self._munp(2, *goodargs) + if mu is None: + mu = self._munp(1, *goodargs) + # if mean is inf then var is also inf + with np.errstate(invalid='ignore'): + mu2 = np.where(~np.isinf(mu), mu2p - mu**2, np.inf) + out0 = default.copy() + place(out0, cond, mu2 * scale * scale) + output.append(out0) + + if 's' in moments: + if g1 is None: + mu3p = self._munp(3, *goodargs) + if mu is None: + mu = self._munp(1, *goodargs) + if mu2 is None: + mu2p = self._munp(2, *goodargs) + with np.errstate(invalid='ignore'): + mu2 = mu2p - mu * mu + with np.errstate(invalid='ignore'): + mu3 = (-mu*mu - 3*mu2)*mu + mu3p + g1 = mu3 / np.power(mu2, 1.5) + out0 = default.copy() + place(out0, cond, g1) + output.append(out0) + + if 'k' in moments: + if g2 is None: + mu4p = self._munp(4, *goodargs) + if mu is None: + mu = self._munp(1, *goodargs) + if mu2 is None: + mu2p = self._munp(2, *goodargs) + with np.errstate(invalid='ignore'): + mu2 = mu2p - mu * mu + if g1 is None: + mu3 = None + else: + # (mu2**1.5) breaks down for nan and inf + mu3 = g1 * np.power(mu2, 1.5) + if mu3 is None: + mu3p = self._munp(3, *goodargs) + with np.errstate(invalid='ignore'): + mu3 = (-mu * mu - 3 * mu2) * mu + mu3p + with np.errstate(invalid='ignore'): + mu4 = ((-mu**2 - 6*mu2) * mu - 4*mu3)*mu + mu4p + g2 = mu4 / mu2**2.0 - 3.0 + out0 = default.copy() + place(out0, cond, g2) + output.append(out0) + else: # no valid args + output = [default.copy() for _ in moments] + + output = [out[()] for out in output] + if len(output) == 1: + return output[0] + else: + return tuple(output) + + def entropy(self, *args, **kwds): + """Differential entropy of the RV. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + scale : array_like, optional (continuous distributions only). + Scale parameter (default=1). + + Notes + ----- + Entropy is defined base `e`: + + >>> import numpy as np + >>> from scipy.stats._distn_infrastructure import rv_discrete + >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5))) + >>> np.allclose(drv.entropy(), np.log(2.0)) + True + + """ + args, loc, scale = self._parse_args(*args, **kwds) + # NB: for discrete distributions scale=1 by construction in _parse_args + loc, scale = map(asarray, (loc, scale)) + args = tuple(map(asarray, args)) + cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) + output = zeros(shape(cond0), 'd') + place(output, (1-cond0), self.badvalue) + goodargs = argsreduce(cond0, scale, *args) + goodscale = goodargs[0] + goodargs = goodargs[1:] + place(output, cond0, self.vecentropy(*goodargs) + log(goodscale)) + return output[()] + + def moment(self, order, *args, **kwds): + """non-central moment of distribution of specified order. + + Parameters + ---------- + order : int, order >= 1 + Order of moment. + arg1, arg2, arg3,... : float + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + """ + n = order + shapes, loc, scale = self._parse_args(*args, **kwds) + args = np.broadcast_arrays(*(*shapes, loc, scale)) + *shapes, loc, scale = args + + i0 = np.logical_and(self._argcheck(*shapes), scale > 0) + i1 = np.logical_and(i0, loc == 0) + i2 = np.logical_and(i0, loc != 0) + + args = argsreduce(i0, *shapes, loc, scale) + *shapes, loc, scale = args + + if (floor(n) != n): + raise ValueError("Moment must be an integer.") + if (n < 0): + raise ValueError("Moment must be positive.") + mu, mu2, g1, g2 = None, None, None, None + if (n > 0) and (n < 5): + if self._stats_has_moments: + mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'mvsk'}[n]} + else: + mdict = {} + mu, mu2, g1, g2 = self._stats(*shapes, **mdict) + val = np.empty(loc.shape) # val needs to be indexed by loc + val[...] = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, shapes) + + # Convert to transformed X = L + S*Y + # E[X^n] = E[(L+S*Y)^n] = L^n sum(comb(n, k)*(S/L)^k E[Y^k], k=0...n) + result = zeros(i0.shape) + place(result, ~i0, self.badvalue) + + if i1.any(): + res1 = scale[loc == 0]**n * val[loc == 0] + place(result, i1, res1) + + if i2.any(): + mom = [mu, mu2, g1, g2] + arrs = [i for i in mom if i is not None] + idx = [i for i in range(4) if mom[i] is not None] + if any(idx): + arrs = argsreduce(loc != 0, *arrs) + j = 0 + for i in idx: + mom[i] = arrs[j] + j += 1 + mu, mu2, g1, g2 = mom + args = argsreduce(loc != 0, *shapes, loc, scale, val) + *shapes, loc, scale, val = args + + res2 = zeros(loc.shape, dtype='d') + fac = scale / loc + for k in range(n): + valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp, + shapes) + res2 += comb(n, k, exact=True)*fac**k * valk + res2 += fac**n * val + res2 *= loc**n + place(result, i2, res2) + + return result[()] + + def median(self, *args, **kwds): + """Median of the distribution. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + Location parameter, Default is 0. + scale : array_like, optional + Scale parameter, Default is 1. + + Returns + ------- + median : float + The median of the distribution. + + See Also + -------- + rv_discrete.ppf + Inverse of the CDF + + """ + return self.ppf(0.5, *args, **kwds) + + def mean(self, *args, **kwds): + """Mean of the distribution. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + mean : float + the mean of the distribution + + """ + kwds['moments'] = 'm' + res = self.stats(*args, **kwds) + if isinstance(res, ndarray) and res.ndim == 0: + return res[()] + return res + + def var(self, *args, **kwds): + """Variance of the distribution. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + var : float + the variance of the distribution + + """ + kwds['moments'] = 'v' + res = self.stats(*args, **kwds) + if isinstance(res, ndarray) and res.ndim == 0: + return res[()] + return res + + def std(self, *args, **kwds): + """Standard deviation of the distribution. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + std : float + standard deviation of the distribution + + """ + kwds['moments'] = 'v' + res = sqrt(self.stats(*args, **kwds)) + return res + + def interval(self, confidence, *args, **kwds): + """Confidence interval with equal areas around the median. + + Parameters + ---------- + confidence : array_like of float + Probability that an rv will be drawn from the returned range. + Each value should be in the range [0, 1]. + arg1, arg2, ... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + location parameter, Default is 0. + scale : array_like, optional + scale parameter, Default is 1. + + Returns + ------- + a, b : ndarray of float + end-points of range that contain ``100 * alpha %`` of the rv's + possible values. + + Notes + ----- + This is implemented as ``ppf([p_tail, 1-p_tail])``, where + ``ppf`` is the inverse cumulative distribution function and + ``p_tail = (1-confidence)/2``. Suppose ``[c, d]`` is the support of a + discrete distribution; then ``ppf([0, 1]) == (c-1, d)``. Therefore, + when ``confidence=1`` and the distribution is discrete, the left end + of the interval will be beyond the support of the distribution. + For discrete distributions, the interval will limit the probability + in each tail to be less than or equal to ``p_tail`` (usually + strictly less). + + """ + alpha = confidence + + alpha = asarray(alpha) + if np.any((alpha > 1) | (alpha < 0)): + raise ValueError("alpha must be between 0 and 1 inclusive") + q1 = (1.0-alpha)/2 + q2 = (1.0+alpha)/2 + a = self.ppf(q1, *args, **kwds) + b = self.ppf(q2, *args, **kwds) + return a, b + + def support(self, *args, **kwargs): + """Support of the distribution. + + Parameters + ---------- + arg1, arg2, ... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + location parameter, Default is 0. + scale : array_like, optional + scale parameter, Default is 1. + + Returns + ------- + a, b : array_like + end-points of the distribution's support. + + """ + args, loc, scale = self._parse_args(*args, **kwargs) + arrs = np.broadcast_arrays(*args, loc, scale) + args, loc, scale = arrs[:-2], arrs[-2], arrs[-1] + cond = self._argcheck(*args) & (scale > 0) + _a, _b = self._get_support(*args) + if cond.all(): + return _a * scale + loc, _b * scale + loc + elif cond.ndim == 0: + return self.badvalue, self.badvalue + # promote bounds to at least float to fill in the badvalue + _a, _b = np.asarray(_a).astype('d'), np.asarray(_b).astype('d') + out_a, out_b = _a * scale + loc, _b * scale + loc + place(out_a, 1-cond, self.badvalue) + place(out_b, 1-cond, self.badvalue) + return out_a, out_b + + def nnlf(self, theta, x): + """Negative loglikelihood function. + Notes + ----- + This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the + parameters (including loc and scale). + """ + loc, scale, args = self._unpack_loc_scale(theta) + if not self._argcheck(*args) or scale <= 0: + return inf + x = (asarray(x)-loc) / scale + n_log_scale = len(x) * log(scale) + if np.any(~self._support_mask(x, *args)): + return inf + return self._nnlf(x, *args) + n_log_scale + + def _nnlf(self, x, *args): + return -np.sum(self._logpxf(x, *args), axis=0) + + def _nlff_and_penalty(self, x, args, log_fitfun): + # negative log fit function + cond0 = ~self._support_mask(x, *args) + n_bad = np.count_nonzero(cond0, axis=0) + if n_bad > 0: + x = argsreduce(~cond0, x)[0] + logff = log_fitfun(x, *args) + finite_logff = np.isfinite(logff) + n_bad += np.sum(~finite_logff, axis=0) + if n_bad > 0: + penalty = n_bad * log(_XMAX) * 100 + return -np.sum(logff[finite_logff], axis=0) + penalty + return -np.sum(logff, axis=0) + + def _penalized_nnlf(self, theta, x): + """Penalized negative loglikelihood function. + i.e., - sum (log pdf(x, theta), axis=0) + penalty + where theta are the parameters (including loc and scale) + """ + loc, scale, args = self._unpack_loc_scale(theta) + if not self._argcheck(*args) or scale <= 0: + return inf + x = asarray((x-loc) / scale) + n_log_scale = len(x) * log(scale) + return self._nlff_and_penalty(x, args, self._logpxf) + n_log_scale + + def _penalized_nlpsf(self, theta, x): + """Penalized negative log product spacing function. + i.e., - sum (log (diff (cdf (x, theta))), axis=0) + penalty + where theta are the parameters (including loc and scale) + Follows reference [1] of scipy.stats.fit + """ + loc, scale, args = self._unpack_loc_scale(theta) + if not self._argcheck(*args) or scale <= 0: + return inf + x = (np.sort(x) - loc)/scale + + def log_psf(x, *args): + x, lj = np.unique(x, return_counts=True) # fast for sorted x + cdf_data = self._cdf(x, *args) if x.size else [] + if not (x.size and 1 - cdf_data[-1] <= 0): + cdf = np.concatenate(([0], cdf_data, [1])) + lj = np.concatenate((lj, [1])) + else: + cdf = np.concatenate(([0], cdf_data)) + # here we could use logcdf w/ logsumexp trick to take differences, + # but in the context of the method, it seems unlikely to matter + return lj * np.log(np.diff(cdf) / lj) + + return self._nlff_and_penalty(x, args, log_psf) + + +class _ShapeInfo: + def __init__(self, name, integrality=False, domain=(-np.inf, np.inf), + inclusive=(True, True)): + self.name = name + self.integrality = integrality + self.endpoints = domain + self.inclusive = inclusive + + domain = list(domain) + if np.isfinite(domain[0]) and not inclusive[0]: + domain[0] = np.nextafter(domain[0], np.inf) + if np.isfinite(domain[1]) and not inclusive[1]: + domain[1] = np.nextafter(domain[1], -np.inf) + self.domain = domain + + +def _get_fixed_fit_value(kwds, names): + """ + Given names such as ``['f0', 'fa', 'fix_a']``, check that there is + at most one non-None value in `kwds` associated with those names. + Return that value, or None if none of the names occur in `kwds`. + As a side effect, all occurrences of those names in `kwds` are + removed. + """ + vals = [(name, kwds.pop(name)) for name in names if name in kwds] + if len(vals) > 1: + repeated = [name for name, val in vals] + raise ValueError("fit method got multiple keyword arguments to " + "specify the same fixed parameter: " + + ', '.join(repeated)) + return vals[0][1] if vals else None + + +# continuous random variables: implement maybe later +# +# hf --- Hazard Function (PDF / SF) +# chf --- Cumulative hazard function (-log(SF)) +# psf --- Probability sparsity function (reciprocal of the pdf) in +# units of percent-point-function (as a function of q). +# Also, the derivative of the percent-point function. + + +class rv_continuous(rv_generic): + """A generic continuous random variable class meant for subclassing. + + `rv_continuous` is a base class to construct specific distribution classes + and instances for continuous random variables. It cannot be used + directly as a distribution. + + Parameters + ---------- + momtype : int, optional + The type of generic moment calculation to use: 0 for pdf, 1 (default) + for ppf. + a : float, optional + Lower bound of the support of the distribution, default is minus + infinity. + b : float, optional + Upper bound of the support of the distribution, default is plus + infinity. + xtol : float, optional + The tolerance for fixed point calculation for generic ppf. + badvalue : float, optional + The value in a result arrays that indicates a value that for which + some argument restriction is violated, default is np.nan. + name : str, optional + The name of the instance. This string is used to construct the default + example for distributions. + longname : str, optional + This string is used as part of the first line of the docstring returned + when a subclass has no docstring of its own. Note: `longname` exists + for backwards compatibility, do not use for new subclasses. + shapes : str, optional + The shape of the distribution. For example ``"m, n"`` for a + distribution that takes two integers as the two shape arguments for all + its methods. If not provided, shape parameters will be inferred from + the signature of the private methods, ``_pdf`` and ``_cdf`` of the + instance. + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Methods + ------- + rvs + pdf + logpdf + cdf + logcdf + sf + logsf + ppf + isf + moment + stats + entropy + expect + median + mean + std + var + interval + __call__ + fit + fit_loc_scale + nnlf + support + + Notes + ----- + Public methods of an instance of a distribution class (e.g., ``pdf``, + ``cdf``) check their arguments and pass valid arguments to private, + computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid + if it is within the support of the distribution. + Whether a shape parameter is valid is decided by an ``_argcheck`` method + (which defaults to checking that its arguments are strictly positive.) + + **Subclassing** + + New random variables can be defined by subclassing the `rv_continuous` class + and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized + to location 0 and scale 1). + + If positive argument checking is not correct for your RV + then you will also need to re-define the ``_argcheck`` method. + + For most of the scipy.stats distributions, the support interval doesn't + depend on the shape parameters. ``x`` being in the support interval is + equivalent to ``self.a <= x <= self.b``. If either of the endpoints of + the support do depend on the shape parameters, then + i) the distribution must implement the ``_get_support`` method; and + ii) those dependent endpoints must be omitted from the distribution's + call to the ``rv_continuous`` initializer. + + Correct, but potentially slow defaults exist for the remaining + methods but for speed and/or accuracy you can over-ride:: + + _logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf + + The default method ``_rvs`` relies on the inverse of the cdf, ``_ppf``, + applied to a uniform random variate. In order to generate random variates + efficiently, either the default ``_ppf`` needs to be overwritten (e.g. + if the inverse cdf can expressed in an explicit form) or a sampling + method needs to be implemented in a custom ``_rvs`` method. + + If possible, you should override ``_isf``, ``_sf`` or ``_logsf``. + The main reason would be to improve numerical accuracy: for example, + the survival function ``_sf`` is computed as ``1 - _cdf`` which can + result in loss of precision if ``_cdf(x)`` is close to one. + + **Methods that can be overwritten by subclasses** + :: + + _rvs + _pdf + _cdf + _sf + _ppf + _isf + _stats + _munp + _entropy + _argcheck + _get_support + + There are additional (internal and private) generic methods that can + be useful for cross-checking and for debugging, but might work in all + cases when directly called. + + A note on ``shapes``: subclasses need not specify them explicitly. In this + case, `shapes` will be automatically deduced from the signatures of the + overridden methods (`pdf`, `cdf` etc). + If, for some reason, you prefer to avoid relying on introspection, you can + specify ``shapes`` explicitly as an argument to the instance constructor. + + + **Frozen Distributions** + + Normally, you must provide shape parameters (and, optionally, location and + scale parameters to each call of a method of a distribution. + + Alternatively, the object may be called (as a function) to fix the shape, + location, and scale parameters returning a "frozen" continuous RV object: + + rv = generic(, loc=0, scale=1) + `rv_frozen` object with the same methods but holding the given shape, + location, and scale fixed + + **Statistics** + + Statistics are computed using numerical integration by default. + For speed you can redefine this using ``_stats``: + + - take shape parameters and return mu, mu2, g1, g2 + - If you can't compute one of these, return it as None + - Can also be defined with a keyword argument ``moments``, which is a + string composed of "m", "v", "s", and/or "k". + Only the components appearing in string should be computed and + returned in the order "m", "v", "s", or "k" with missing values + returned as None. + + Alternatively, you can override ``_munp``, which takes ``n`` and shape + parameters and returns the n-th non-central moment of the distribution. + + **Deepcopying / Pickling** + + If a distribution or frozen distribution is deepcopied (pickled/unpickled, + etc.), any underlying random number generator is deepcopied with it. An + implication is that if a distribution relies on the singleton RandomState + before copying, it will rely on a copy of that random state after copying, + and ``np.random.seed`` will no longer control the state. + + Examples + -------- + To create a new Gaussian distribution, we would do the following: + + >>> from scipy.stats import rv_continuous + >>> class gaussian_gen(rv_continuous): + ... "Gaussian distribution" + ... def _pdf(self, x): + ... return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi) + >>> gaussian = gaussian_gen(name='gaussian') + + ``scipy.stats`` distributions are *instances*, so here we subclass + `rv_continuous` and create an instance. With this, we now have + a fully functional distribution with all relevant methods automagically + generated by the framework. + + Note that above we defined a standard normal distribution, with zero mean + and unit variance. Shifting and scaling of the distribution can be done + by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)`` + essentially computes ``y = (x - loc) / scale`` and + ``gaussian._pdf(y) / scale``. + + """ + + def __init__(self, momtype=1, a=None, b=None, xtol=1e-14, + badvalue=None, name=None, longname=None, + shapes=None, seed=None): + + super().__init__(seed) + + # save the ctor parameters, cf generic freeze + self._ctor_param = dict( + momtype=momtype, a=a, b=b, xtol=xtol, + badvalue=badvalue, name=name, longname=longname, + shapes=shapes, seed=seed) + + if badvalue is None: + badvalue = nan + if name is None: + name = 'Distribution' + self.badvalue = badvalue + self.name = name + self.a = a + self.b = b + if a is None: + self.a = -inf + if b is None: + self.b = inf + self.xtol = xtol + self.moment_type = momtype + self.shapes = shapes + + self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf], + locscale_in='loc=0, scale=1', + locscale_out='loc, scale') + self._attach_methods() + + if longname is None: + if name[0] in ['aeiouAEIOU']: + hstr = "An " + else: + hstr = "A " + longname = hstr + name + + if sys.flags.optimize < 2: + # Skip adding docstrings if interpreter is run with -OO + if self.__doc__ is None: + self._construct_default_doc(longname=longname, + docdict=docdict, + discrete='continuous') + else: + dct = dict(distcont) + self._construct_doc(docdict, dct.get(self.name)) + + def __getstate__(self): + dct = self.__dict__.copy() + + # these methods will be remade in __setstate__ + # _random_state attribute is taken care of by rv_generic + attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs", + "_cdfvec", "_ppfvec", "vecentropy", "generic_moment"] + [dct.pop(attr, None) for attr in attrs] + return dct + + def _attach_methods(self): + """ + Attaches dynamically created methods to the rv_continuous instance. + """ + # _attach_methods is responsible for calling _attach_argparser_methods + self._attach_argparser_methods() + + # nin correction + self._ppfvec = vectorize(self._ppf_single, otypes='d') + self._ppfvec.nin = self.numargs + 1 + self.vecentropy = vectorize(self._entropy, otypes='d') + self._cdfvec = vectorize(self._cdf_single, otypes='d') + self._cdfvec.nin = self.numargs + 1 + + if self.moment_type == 0: + self.generic_moment = vectorize(self._mom0_sc, otypes='d') + else: + self.generic_moment = vectorize(self._mom1_sc, otypes='d') + # Because of the *args argument of _mom0_sc, vectorize cannot count the + # number of arguments correctly. + self.generic_moment.nin = self.numargs + 1 + + def _updated_ctor_param(self): + """Return the current version of _ctor_param, possibly updated by user. + + Used by freezing. + Keep this in sync with the signature of __init__. + """ + dct = self._ctor_param.copy() + dct['a'] = self.a + dct['b'] = self.b + dct['xtol'] = self.xtol + dct['badvalue'] = self.badvalue + dct['name'] = self.name + dct['shapes'] = self.shapes + return dct + + def _ppf_to_solve(self, x, q, *args): + return self.cdf(*(x, )+args)-q + + def _ppf_single(self, q, *args): + factor = 10. + left, right = self._get_support(*args) + + if np.isinf(left): + left = min(-factor, right) + while self._ppf_to_solve(left, q, *args) > 0.: + left, right = left * factor, left + # left is now such that cdf(left) <= q + # if right has changed, then cdf(right) > q + + if np.isinf(right): + right = max(factor, left) + while self._ppf_to_solve(right, q, *args) < 0.: + left, right = right, right * factor + # right is now such that cdf(right) >= q + + return optimize.brentq(self._ppf_to_solve, + left, right, args=(q,)+args, xtol=self.xtol) + + # moment from definition + def _mom_integ0(self, x, m, *args): + return x**m * self.pdf(x, *args) + + def _mom0_sc(self, m, *args): + _a, _b = self._get_support(*args) + return integrate.quad(self._mom_integ0, _a, _b, + args=(m,)+args)[0] + + # moment calculated using ppf + def _mom_integ1(self, q, m, *args): + return (self.ppf(q, *args))**m + + def _mom1_sc(self, m, *args): + return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0] + + def _pdf(self, x, *args): + return _derivative(self._cdf, x, dx=1e-5, args=args, order=5) + + # Could also define any of these + def _logpdf(self, x, *args): + p = self._pdf(x, *args) + with np.errstate(divide='ignore'): + return log(p) + + def _logpxf(self, x, *args): + # continuous distributions have PDF, discrete have PMF, but sometimes + # the distinction doesn't matter. This lets us use `_logpxf` for both + # discrete and continuous distributions. + return self._logpdf(x, *args) + + def _cdf_single(self, x, *args): + _a, _b = self._get_support(*args) + return integrate.quad(self._pdf, _a, x, args=args)[0] + + def _cdf(self, x, *args): + return self._cdfvec(x, *args) + + def _logcdf(self, x, *args): + median = self._ppf(0.5, *args) + with np.errstate(divide='ignore'): + return _lazywhere(x < median, (x,) + args, + f=lambda x, *args: np.log(self._cdf(x, *args)), + f2=lambda x, *args: np.log1p(-self._sf(x, *args))) + + def _logsf(self, x, *args): + median = self._ppf(0.5, *args) + with np.errstate(divide='ignore'): + return _lazywhere(x > median, (x,) + args, + f=lambda x, *args: np.log(self._sf(x, *args)), + f2=lambda x, *args: np.log1p(-self._cdf(x, *args))) + + # generic _argcheck, _sf, _ppf, _isf, _rvs are defined + # in rv_generic + + def pdf(self, x, *args, **kwds): + """Probability density function at x of the given RV. + + Parameters + ---------- + x : array_like + quantiles + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + pdf : ndarray + Probability density function evaluated at x + + """ + args, loc, scale = self._parse_args(*args, **kwds) + x, loc, scale = map(asarray, (x, loc, scale)) + args = tuple(map(asarray, args)) + dtyp = np.promote_types(x.dtype, np.float64) + x = np.asarray((x - loc)/scale, dtype=dtyp) + cond0 = self._argcheck(*args) & (scale > 0) + cond1 = self._support_mask(x, *args) & (scale > 0) + cond = cond0 & cond1 + output = zeros(shape(cond), dtyp) + putmask(output, (1-cond0)+np.isnan(x), self.badvalue) + if np.any(cond): + goodargs = argsreduce(cond, *((x,)+args+(scale,))) + scale, goodargs = goodargs[-1], goodargs[:-1] + place(output, cond, self._pdf(*goodargs) / scale) + if output.ndim == 0: + return output[()] + return output + + def logpdf(self, x, *args, **kwds): + """Log of the probability density function at x of the given RV. + + This uses a more numerically accurate calculation if available. + + Parameters + ---------- + x : array_like + quantiles + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + logpdf : array_like + Log of the probability density function evaluated at x + + """ + args, loc, scale = self._parse_args(*args, **kwds) + x, loc, scale = map(asarray, (x, loc, scale)) + args = tuple(map(asarray, args)) + dtyp = np.promote_types(x.dtype, np.float64) + x = np.asarray((x - loc)/scale, dtype=dtyp) + cond0 = self._argcheck(*args) & (scale > 0) + cond1 = self._support_mask(x, *args) & (scale > 0) + cond = cond0 & cond1 + output = empty(shape(cond), dtyp) + output.fill(-inf) + putmask(output, (1-cond0)+np.isnan(x), self.badvalue) + if np.any(cond): + goodargs = argsreduce(cond, *((x,)+args+(scale,))) + scale, goodargs = goodargs[-1], goodargs[:-1] + place(output, cond, self._logpdf(*goodargs) - log(scale)) + if output.ndim == 0: + return output[()] + return output + + def cdf(self, x, *args, **kwds): + """ + Cumulative distribution function of the given RV. + + Parameters + ---------- + x : array_like + quantiles + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + cdf : ndarray + Cumulative distribution function evaluated at `x` + + """ + args, loc, scale = self._parse_args(*args, **kwds) + x, loc, scale = map(asarray, (x, loc, scale)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + dtyp = np.promote_types(x.dtype, np.float64) + x = np.asarray((x - loc)/scale, dtype=dtyp) + cond0 = self._argcheck(*args) & (scale > 0) + cond1 = self._open_support_mask(x, *args) & (scale > 0) + cond2 = (x >= np.asarray(_b)) & cond0 + cond = cond0 & cond1 + output = zeros(shape(cond), dtyp) + place(output, (1-cond0)+np.isnan(x), self.badvalue) + place(output, cond2, 1.0) + if np.any(cond): # call only if at least 1 entry + goodargs = argsreduce(cond, *((x,)+args)) + place(output, cond, self._cdf(*goodargs)) + if output.ndim == 0: + return output[()] + return output + + def logcdf(self, x, *args, **kwds): + """Log of the cumulative distribution function at x of the given RV. + + Parameters + ---------- + x : array_like + quantiles + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + logcdf : array_like + Log of the cumulative distribution function evaluated at x + + """ + args, loc, scale = self._parse_args(*args, **kwds) + x, loc, scale = map(asarray, (x, loc, scale)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + dtyp = np.promote_types(x.dtype, np.float64) + x = np.asarray((x - loc)/scale, dtype=dtyp) + cond0 = self._argcheck(*args) & (scale > 0) + cond1 = self._open_support_mask(x, *args) & (scale > 0) + cond2 = (x >= _b) & cond0 + cond = cond0 & cond1 + output = empty(shape(cond), dtyp) + output.fill(-inf) + place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue) + place(output, cond2, 0.0) + if np.any(cond): # call only if at least 1 entry + goodargs = argsreduce(cond, *((x,)+args)) + place(output, cond, self._logcdf(*goodargs)) + if output.ndim == 0: + return output[()] + return output + + def sf(self, x, *args, **kwds): + """Survival function (1 - `cdf`) at x of the given RV. + + Parameters + ---------- + x : array_like + quantiles + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + sf : array_like + Survival function evaluated at x + + """ + args, loc, scale = self._parse_args(*args, **kwds) + x, loc, scale = map(asarray, (x, loc, scale)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + dtyp = np.promote_types(x.dtype, np.float64) + x = np.asarray((x - loc)/scale, dtype=dtyp) + cond0 = self._argcheck(*args) & (scale > 0) + cond1 = self._open_support_mask(x, *args) & (scale > 0) + cond2 = cond0 & (x <= _a) + cond = cond0 & cond1 + output = zeros(shape(cond), dtyp) + place(output, (1-cond0)+np.isnan(x), self.badvalue) + place(output, cond2, 1.0) + if np.any(cond): + goodargs = argsreduce(cond, *((x,)+args)) + place(output, cond, self._sf(*goodargs)) + if output.ndim == 0: + return output[()] + return output + + def logsf(self, x, *args, **kwds): + """Log of the survival function of the given RV. + + Returns the log of the "survival function," defined as (1 - `cdf`), + evaluated at `x`. + + Parameters + ---------- + x : array_like + quantiles + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + logsf : ndarray + Log of the survival function evaluated at `x`. + + """ + args, loc, scale = self._parse_args(*args, **kwds) + x, loc, scale = map(asarray, (x, loc, scale)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + dtyp = np.promote_types(x.dtype, np.float64) + x = np.asarray((x - loc)/scale, dtype=dtyp) + cond0 = self._argcheck(*args) & (scale > 0) + cond1 = self._open_support_mask(x, *args) & (scale > 0) + cond2 = cond0 & (x <= _a) + cond = cond0 & cond1 + output = empty(shape(cond), dtyp) + output.fill(-inf) + place(output, (1-cond0)+np.isnan(x), self.badvalue) + place(output, cond2, 0.0) + if np.any(cond): + goodargs = argsreduce(cond, *((x,)+args)) + place(output, cond, self._logsf(*goodargs)) + if output.ndim == 0: + return output[()] + return output + + def ppf(self, q, *args, **kwds): + """Percent point function (inverse of `cdf`) at q of the given RV. + + Parameters + ---------- + q : array_like + lower tail probability + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + x : array_like + quantile corresponding to the lower tail probability q. + + """ + args, loc, scale = self._parse_args(*args, **kwds) + q, loc, scale = map(asarray, (q, loc, scale)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) + cond1 = (0 < q) & (q < 1) + cond2 = cond0 & (q == 0) + cond3 = cond0 & (q == 1) + cond = cond0 & cond1 + output = np.full(shape(cond), fill_value=self.badvalue) + + lower_bound = _a * scale + loc + upper_bound = _b * scale + loc + place(output, cond2, argsreduce(cond2, lower_bound)[0]) + place(output, cond3, argsreduce(cond3, upper_bound)[0]) + + if np.any(cond): # call only if at least 1 entry + goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) + scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] + place(output, cond, self._ppf(*goodargs) * scale + loc) + if output.ndim == 0: + return output[()] + return output + + def isf(self, q, *args, **kwds): + """Inverse survival function (inverse of `sf`) at q of the given RV. + + Parameters + ---------- + q : array_like + upper tail probability + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + location parameter (default=0) + scale : array_like, optional + scale parameter (default=1) + + Returns + ------- + x : ndarray or scalar + Quantile corresponding to the upper tail probability q. + + """ + args, loc, scale = self._parse_args(*args, **kwds) + q, loc, scale = map(asarray, (q, loc, scale)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) + cond1 = (0 < q) & (q < 1) + cond2 = cond0 & (q == 1) + cond3 = cond0 & (q == 0) + cond = cond0 & cond1 + output = np.full(shape(cond), fill_value=self.badvalue) + + lower_bound = _a * scale + loc + upper_bound = _b * scale + loc + place(output, cond2, argsreduce(cond2, lower_bound)[0]) + place(output, cond3, argsreduce(cond3, upper_bound)[0]) + + if np.any(cond): + goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) + scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] + place(output, cond, self._isf(*goodargs) * scale + loc) + if output.ndim == 0: + return output[()] + return output + + def _unpack_loc_scale(self, theta): + try: + loc = theta[-2] + scale = theta[-1] + args = tuple(theta[:-2]) + except IndexError as e: + raise ValueError("Not enough input arguments.") from e + return loc, scale, args + + def _nnlf_and_penalty(self, x, args): + """ + Compute the penalized negative log-likelihood for the + "standardized" data (i.e. already shifted by loc and + scaled by scale) for the shape parameters in `args`. + + `x` can be a 1D numpy array or a CensoredData instance. + """ + if isinstance(x, CensoredData): + # Filter out the data that is not in the support. + xs = x._supported(*self._get_support(*args)) + n_bad = len(x) - len(xs) + i1, i2 = xs._interval.T + terms = [ + # logpdf of the noncensored data. + self._logpdf(xs._uncensored, *args), + # logcdf of the left-censored data. + self._logcdf(xs._left, *args), + # logsf of the right-censored data. + self._logsf(xs._right, *args), + # log of probability of the interval-censored data. + np.log(self._delta_cdf(i1, i2, *args)), + ] + else: + cond0 = ~self._support_mask(x, *args) + n_bad = np.count_nonzero(cond0) + if n_bad > 0: + x = argsreduce(~cond0, x)[0] + terms = [self._logpdf(x, *args)] + + totals, bad_counts = zip(*[_sum_finite(term) for term in terms]) + total = sum(totals) + n_bad += sum(bad_counts) + + return -total + n_bad * _LOGXMAX * 100 + + def _penalized_nnlf(self, theta, x): + """Penalized negative loglikelihood function. + + i.e., - sum (log pdf(x, theta), axis=0) + penalty + where theta are the parameters (including loc and scale) + """ + loc, scale, args = self._unpack_loc_scale(theta) + if not self._argcheck(*args) or scale <= 0: + return inf + if isinstance(x, CensoredData): + x = (x - loc) / scale + n_log_scale = (len(x) - x.num_censored()) * log(scale) + else: + x = (x - loc) / scale + n_log_scale = len(x) * log(scale) + + return self._nnlf_and_penalty(x, args) + n_log_scale + + def _fitstart(self, data, args=None): + """Starting point for fit (shape arguments + loc + scale).""" + if args is None: + args = (1.0,)*self.numargs + loc, scale = self._fit_loc_scale_support(data, *args) + return args + (loc, scale) + + def _reduce_func(self, args, kwds, data=None): + """ + Return the (possibly reduced) function to optimize in order to find MLE + estimates for the .fit method. + """ + # Convert fixed shape parameters to the standard numeric form: e.g. for + # stats.beta, shapes='a, b'. To fix `a`, the caller can give a value + # for `f0`, `fa` or 'fix_a'. The following converts the latter two + # into the first (numeric) form. + shapes = [] + if self.shapes: + shapes = self.shapes.replace(',', ' ').split() + for j, s in enumerate(shapes): + key = 'f' + str(j) + names = [key, 'f' + s, 'fix_' + s] + val = _get_fixed_fit_value(kwds, names) + if val is not None: + kwds[key] = val + + args = list(args) + Nargs = len(args) + fixedn = [] + names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale'] + x0 = [] + for n, key in enumerate(names): + if key in kwds: + fixedn.append(n) + args[n] = kwds.pop(key) + else: + x0.append(args[n]) + + methods = {"mle", "mm"} + method = kwds.pop('method', "mle").lower() + if method == "mm": + n_params = len(shapes) + 2 - len(fixedn) + exponents = (np.arange(1, n_params+1))[:, np.newaxis] + data_moments = np.sum(data[None, :]**exponents/len(data), axis=1) + + def objective(theta, x): + return self._moment_error(theta, x, data_moments) + + elif method == "mle": + objective = self._penalized_nnlf + else: + raise ValueError(f"Method '{method}' not available; " + f"must be one of {methods}") + + if len(fixedn) == 0: + func = objective + restore = None + else: + if len(fixedn) == Nargs: + raise ValueError( + "All parameters fixed. There is nothing to optimize.") + + def restore(args, theta): + # Replace with theta for all numbers not in fixedn + # This allows the non-fixed values to vary, but + # we still call self.nnlf with all parameters. + i = 0 + for n in range(Nargs): + if n not in fixedn: + args[n] = theta[i] + i += 1 + return args + + def func(theta, x): + newtheta = restore(args[:], theta) + return objective(newtheta, x) + + return x0, func, restore, args + + def _moment_error(self, theta, x, data_moments): + loc, scale, args = self._unpack_loc_scale(theta) + if not self._argcheck(*args) or scale <= 0: + return inf + + dist_moments = np.array([self.moment(i+1, *args, loc=loc, scale=scale) + for i in range(len(data_moments))]) + if np.any(np.isnan(dist_moments)): + raise ValueError("Method of moments encountered a non-finite " + "distribution moment and cannot continue. " + "Consider trying method='MLE'.") + + return (((data_moments - dist_moments) / + np.maximum(np.abs(data_moments), 1e-8))**2).sum() + + def fit(self, data, *args, **kwds): + r""" + Return estimates of shape (if applicable), location, and scale + parameters from data. The default estimation method is Maximum + Likelihood Estimation (MLE), but Method of Moments (MM) + is also available. + + Starting estimates for the fit are given by input arguments; + for any arguments not provided with starting estimates, + ``self._fitstart(data)`` is called to generate such. + + One can hold some parameters fixed to specific values by passing in + keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters) + and ``floc`` and ``fscale`` (for location and scale parameters, + respectively). + + Parameters + ---------- + data : array_like or `CensoredData` instance + Data to use in estimating the distribution parameters. + arg1, arg2, arg3,... : floats, optional + Starting value(s) for any shape-characterizing arguments (those not + provided will be determined by a call to ``_fitstart(data)``). + No default value. + **kwds : floats, optional + - `loc`: initial guess of the distribution's location parameter. + - `scale`: initial guess of the distribution's scale parameter. + + Special keyword arguments are recognized as holding certain + parameters fixed: + + - f0...fn : hold respective shape parameters fixed. + Alternatively, shape parameters to fix can be specified by name. + For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a`` + are equivalent to ``f0``, and ``fb`` and ``fix_b`` are + equivalent to ``f1``. + + - floc : hold location parameter fixed to specified value. + + - fscale : hold scale parameter fixed to specified value. + + - optimizer : The optimizer to use. The optimizer must take + ``func`` and starting position as the first two arguments, + plus ``args`` (for extra arguments to pass to the + function to be optimized) and ``disp``. + The ``fit`` method calls the optimizer with ``disp=0`` to suppress output. + The optimizer must return the estimated parameters. + + - method : The method to use. The default is "MLE" (Maximum + Likelihood Estimate); "MM" (Method of Moments) + is also available. + + Raises + ------ + TypeError, ValueError + If an input is invalid + `~scipy.stats.FitError` + If fitting fails or the fit produced would be invalid + + Returns + ------- + parameter_tuple : tuple of floats + Estimates for any shape parameters (if applicable), followed by + those for location and scale. For most random variables, shape + statistics will be returned, but there are exceptions (e.g. + ``norm``). + + Notes + ----- + With ``method="MLE"`` (default), the fit is computed by minimizing + the negative log-likelihood function. A large, finite penalty + (rather than infinite negative log-likelihood) is applied for + observations beyond the support of the distribution. + + With ``method="MM"``, the fit is computed by minimizing the L2 norm + of the relative errors between the first *k* raw (about zero) data + moments and the corresponding distribution moments, where *k* is the + number of non-fixed parameters. + More precisely, the objective function is:: + + (((data_moments - dist_moments) + / np.maximum(np.abs(data_moments), 1e-8))**2).sum() + + where the constant ``1e-8`` avoids division by zero in case of + vanishing data moments. Typically, this error norm can be reduced to + zero. + Note that the standard method of moments can produce parameters for + which some data are outside the support of the fitted distribution; + this implementation does nothing to prevent this. + + For either method, + the returned answer is not guaranteed to be globally optimal; it + may only be locally optimal, or the optimization may fail altogether. + If the data contain any of ``np.nan``, ``np.inf``, or ``-np.inf``, + the `fit` method will raise a ``RuntimeError``. + + When passing a ``CensoredData`` instance to ``data``, the log-likelihood + function is defined as: + + .. math:: + + l(\pmb{\theta}; k) & = \sum + \log(f(k_u; \pmb{\theta})) + + \sum + \log(F(k_l; \pmb{\theta})) \\ + & + \sum + \log(1 - F(k_r; \pmb{\theta})) \\ + & + \sum + \log(F(k_{\text{high}, i}; \pmb{\theta}) + - F(k_{\text{low}, i}; \pmb{\theta})) + + where :math:`f` and :math:`F` are the pdf and cdf, respectively, of the + function being fitted, :math:`\pmb{\theta}` is the parameter vector, + :math:`u` are the indices of uncensored observations, + :math:`l` are the indices of left-censored observations, + :math:`r` are the indices of right-censored observations, + subscripts "low"/"high" denote endpoints of interval-censored observations, and + :math:`i` are the indices of interval-censored observations. + + Examples + -------- + + Generate some data to fit: draw random variates from the `beta` + distribution + + >>> import numpy as np + >>> from scipy.stats import beta + >>> a, b = 1., 2. + >>> rng = np.random.default_rng(172786373191770012695001057628748821561) + >>> x = beta.rvs(a, b, size=1000, random_state=rng) + + Now we can fit all four parameters (``a``, ``b``, ``loc`` and + ``scale``): + + >>> a1, b1, loc1, scale1 = beta.fit(x) + >>> a1, b1, loc1, scale1 + (1.0198945204435628, 1.9484708982737828, 4.372241314917588e-05, 0.9979078845964814) + + The fit can be done also using a custom optimizer: + + >>> from scipy.optimize import minimize + >>> def custom_optimizer(func, x0, args=(), disp=0): + ... res = minimize(func, x0, args, method="slsqp", options={"disp": disp}) + ... if res.success: + ... return res.x + ... raise RuntimeError('optimization routine failed') + >>> a1, b1, loc1, scale1 = beta.fit(x, method="MLE", optimizer=custom_optimizer) + >>> a1, b1, loc1, scale1 + (1.0198821087258905, 1.948484145914738, 4.3705304486881485e-05, 0.9979104663953395) + + We can also use some prior knowledge about the dataset: let's keep + ``loc`` and ``scale`` fixed: + + >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) + >>> loc1, scale1 + (0, 1) + + We can also keep shape parameters fixed by using ``f``-keywords. To + keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or, + equivalently, ``fa=1``: + + >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) + >>> a1 + 1 + + Not all distributions return estimates for the shape parameters. + ``norm`` for example just returns estimates for location and scale: + + >>> from scipy.stats import norm + >>> x = norm.rvs(a, b, size=1000, random_state=123) + >>> loc1, scale1 = norm.fit(x) + >>> loc1, scale1 + (0.92087172783841631, 2.0015750750324668) + """ # noqa: E501 + method = kwds.get('method', "mle").lower() + + censored = isinstance(data, CensoredData) + if censored: + if method != 'mle': + raise ValueError('For censored data, the method must' + ' be "MLE".') + if data.num_censored() == 0: + # There are no censored values in data, so replace the + # CensoredData instance with a regular array. + data = data._uncensored + censored = False + + Narg = len(args) + if Narg > self.numargs: + raise TypeError("Too many input arguments.") + + # Check the finiteness of data only if data is not an instance of + # CensoredData. The arrays in a CensoredData instance have already + # been validated. + if not censored: + # Note: `ravel()` is called for backwards compatibility. + data = np.asarray(data).ravel() + if not np.isfinite(data).all(): + raise ValueError("The data contains non-finite values.") + + start = [None]*2 + if (Narg < self.numargs) or not ('loc' in kwds and + 'scale' in kwds): + # get distribution specific starting locations + start = self._fitstart(data) + args += start[Narg:-2] + loc = kwds.pop('loc', start[-2]) + scale = kwds.pop('scale', start[-1]) + args += (loc, scale) + x0, func, restore, args = self._reduce_func(args, kwds, data=data) + optimizer = kwds.pop('optimizer', optimize.fmin) + # convert string to function in scipy.optimize + optimizer = _fit_determine_optimizer(optimizer) + # by now kwds must be empty, since everybody took what they needed + if kwds: + raise TypeError(f"Unknown arguments: {kwds}.") + + # In some cases, method of moments can be done with fsolve/root + # instead of an optimizer, but sometimes no solution exists, + # especially when the user fixes parameters. Minimizing the sum + # of squares of the error generalizes to these cases. + vals = optimizer(func, x0, args=(data,), disp=0) + obj = func(vals, data) + + if restore is not None: + vals = restore(args, vals) + vals = tuple(vals) + + loc, scale, shapes = self._unpack_loc_scale(vals) + if not (np.all(self._argcheck(*shapes)) and scale > 0): + raise FitError("Optimization converged to parameters that are " + "outside the range allowed by the distribution.") + + if method == 'mm': + if not np.isfinite(obj): + raise FitError("Optimization failed: either a data moment " + "or fitted distribution moment is " + "non-finite.") + + return vals + + def _fit_loc_scale_support(self, data, *args): + """Estimate loc and scale parameters from data accounting for support. + + Parameters + ---------- + data : array_like + Data to fit. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + + Returns + ------- + Lhat : float + Estimated location parameter for the data. + Shat : float + Estimated scale parameter for the data. + + """ + if isinstance(data, CensoredData): + # For this estimate, "uncensor" the data by taking the + # given endpoints as the data for the left- or right-censored + # data, and the mean for the interval-censored data. + data = data._uncensor() + else: + data = np.asarray(data) + + # Estimate location and scale according to the method of moments. + loc_hat, scale_hat = self.fit_loc_scale(data, *args) + + # Compute the support according to the shape parameters. + self._argcheck(*args) + _a, _b = self._get_support(*args) + a, b = _a, _b + support_width = b - a + + # If the support is empty then return the moment-based estimates. + if support_width <= 0: + return loc_hat, scale_hat + + # Compute the proposed support according to the loc and scale + # estimates. + a_hat = loc_hat + a * scale_hat + b_hat = loc_hat + b * scale_hat + + # Use the moment-based estimates if they are compatible with the data. + data_a = np.min(data) + data_b = np.max(data) + if a_hat < data_a and data_b < b_hat: + return loc_hat, scale_hat + + # Otherwise find other estimates that are compatible with the data. + data_width = data_b - data_a + rel_margin = 0.1 + margin = data_width * rel_margin + + # For a finite interval, both the location and scale + # should have interesting values. + if support_width < np.inf: + loc_hat = (data_a - a) - margin + scale_hat = (data_width + 2 * margin) / support_width + return loc_hat, scale_hat + + # For a one-sided interval, use only an interesting location parameter. + if a > -np.inf: + return (data_a - a) - margin, 1 + elif b < np.inf: + return (data_b - b) + margin, 1 + else: + raise RuntimeError + + def fit_loc_scale(self, data, *args): + """ + Estimate loc and scale parameters from data using 1st and 2nd moments. + + Parameters + ---------- + data : array_like + Data to fit. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + + Returns + ------- + Lhat : float + Estimated location parameter for the data. + Shat : float + Estimated scale parameter for the data. + + """ + mu, mu2 = self.stats(*args, **{'moments': 'mv'}) + tmp = asarray(data) + muhat = tmp.mean() + mu2hat = tmp.var() + Shat = sqrt(mu2hat / mu2) + with np.errstate(invalid='ignore'): + Lhat = muhat - Shat*mu + if not np.isfinite(Lhat): + Lhat = 0 + if not (np.isfinite(Shat) and (0 < Shat)): + Shat = 1 + return Lhat, Shat + + def _entropy(self, *args): + def integ(x): + val = self._pdf(x, *args) + return entr(val) + + # upper limit is often inf, so suppress warnings when integrating + _a, _b = self._get_support(*args) + with np.errstate(over='ignore'): + h = integrate.quad(integ, _a, _b)[0] + + if not np.isnan(h): + return h + else: + # try with different limits if integration problems + low, upp = self.ppf([1e-10, 1. - 1e-10], *args) + if np.isinf(_b): + upper = upp + else: + upper = _b + if np.isinf(_a): + lower = low + else: + lower = _a + return integrate.quad(integ, lower, upper)[0] + + def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, + conditional=False, **kwds): + """Calculate expected value of a function with respect to the + distribution by numerical integration. + + The expected value of a function ``f(x)`` with respect to a + distribution ``dist`` is defined as:: + + ub + E[f(x)] = Integral(f(x) * dist.pdf(x)), + lb + + where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)`` + distribution. If the bounds ``lb`` and ``ub`` correspond to the + support of the distribution, e.g. ``[-inf, inf]`` in the default + case, then the integral is the unrestricted expectation of ``f(x)``. + Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0`` + outside a finite interval in which case the expectation is + calculated within the finite range ``[lb, ub]``. + + Parameters + ---------- + func : callable, optional + Function for which integral is calculated. Takes only one argument. + The default is the identity mapping f(x) = x. + args : tuple, optional + Shape parameters of the distribution. + loc : float, optional + Location parameter (default=0). + scale : float, optional + Scale parameter (default=1). + lb, ub : scalar, optional + Lower and upper bound for integration. Default is set to the + support of the distribution. + conditional : bool, optional + If True, the integral is corrected by the conditional probability + of the integration interval. The return value is the expectation + of the function, conditional on being in the given interval. + Default is False. + + Additional keyword arguments are passed to the integration routine. + + Returns + ------- + expect : float + The calculated expected value. + + Notes + ----- + The integration behavior of this function is inherited from + `scipy.integrate.quad`. Neither this function nor + `scipy.integrate.quad` can verify whether the integral exists or is + finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and + ``cauchy(0).expect()`` returns ``0.0``. + + Likewise, the accuracy of results is not verified by the function. + `scipy.integrate.quad` is typically reliable for integrals that are + numerically favorable, but it is not guaranteed to converge + to a correct value for all possible intervals and integrands. This + function is provided for convenience; for critical applications, + check results against other integration methods. + + The function is not vectorized. + + Examples + -------- + + To understand the effect of the bounds of integration consider + + >>> from scipy.stats import expon + >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0) + 0.6321205588285578 + + This is close to + + >>> expon(1).cdf(2.0) - expon(1).cdf(0.0) + 0.6321205588285577 + + If ``conditional=True`` + + >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True) + 1.0000000000000002 + + The slight deviation from 1 is due to numerical integration. + + The integrand can be treated as a complex-valued function + by passing ``complex_func=True`` to `scipy.integrate.quad` . + + >>> import numpy as np + >>> from scipy.stats import vonmises + >>> res = vonmises(loc=2, kappa=1).expect(lambda x: np.exp(1j*x), + ... complex_func=True) + >>> res + (-0.18576377217422957+0.40590124735052263j) + + >>> np.angle(res) # location of the (circular) distribution + 2.0 + + """ + lockwds = {'loc': loc, + 'scale': scale} + self._argcheck(*args) + _a, _b = self._get_support(*args) + if func is None: + def fun(x, *args): + return x * self.pdf(x, *args, **lockwds) + else: + def fun(x, *args): + return func(x) * self.pdf(x, *args, **lockwds) + if lb is None: + lb = loc + _a * scale + if ub is None: + ub = loc + _b * scale + + cdf_bounds = self.cdf([lb, ub], *args, **lockwds) + invfac = cdf_bounds[1] - cdf_bounds[0] + + kwds['args'] = args + + # split interval to help integrator w/ infinite support; see gh-8928 + alpha = 0.05 # split body from tails at probability mass `alpha` + inner_bounds = np.array([alpha, 1-alpha]) + cdf_inner_bounds = cdf_bounds[0] + invfac * inner_bounds + c, d = loc + self._ppf(cdf_inner_bounds, *args) * scale + + # Do not silence warnings from integration. + lbc = integrate.quad(fun, lb, c, **kwds)[0] + cd = integrate.quad(fun, c, d, **kwds)[0] + dub = integrate.quad(fun, d, ub, **kwds)[0] + vals = (lbc + cd + dub) + + if conditional: + vals /= invfac + return np.array(vals)[()] # make it a numpy scalar like other methods + + def _param_info(self): + shape_info = self._shape_info() + loc_info = _ShapeInfo("loc", False, (-np.inf, np.inf), (False, False)) + scale_info = _ShapeInfo("scale", False, (0, np.inf), (False, False)) + param_info = shape_info + [loc_info, scale_info] + return param_info + + # For now, _delta_cdf is a private method. + def _delta_cdf(self, x1, x2, *args, loc=0, scale=1): + """ + Compute CDF(x2) - CDF(x1). + + Where x1 is greater than the median, compute SF(x1) - SF(x2), + otherwise compute CDF(x2) - CDF(x1). + + This function is only useful if `dist.sf(x, ...)` has an implementation + that is numerically more accurate than `1 - dist.cdf(x, ...)`. + """ + cdf1 = self.cdf(x1, *args, loc=loc, scale=scale) + # Possible optimizations (needs investigation-these might not be + # better): + # * Use _lazywhere instead of np.where + # * Instead of cdf1 > 0.5, compare x1 to the median. + result = np.where(cdf1 > 0.5, + (self.sf(x1, *args, loc=loc, scale=scale) + - self.sf(x2, *args, loc=loc, scale=scale)), + self.cdf(x2, *args, loc=loc, scale=scale) - cdf1) + if result.ndim == 0: + result = result[()] + return result + + +# Helpers for the discrete distributions +def _drv2_moment(self, n, *args): + """Non-central moment of discrete distribution.""" + def fun(x): + return np.power(x, n) * self._pmf(x, *args) + + _a, _b = self._get_support(*args) + return _expect(fun, _a, _b, self._ppf(0.5, *args), self.inc) + + +def _drv2_ppfsingle(self, q, *args): # Use basic bisection algorithm + _a, _b = self._get_support(*args) + b = _b + a = _a + + step = 10 + if isinf(b): # Be sure ending point is > q + b = float(max(100*q, 10)) + while 1: + if b >= _b: + qb = 1.0 + break + qb = self._cdf(b, *args) + if (qb < q): + b += step + step *= 2 + else: + break + else: + qb = 1.0 + + step = 10 + if isinf(a): # be sure starting point < q + a = float(min(-100*q, -10)) + while 1: + if a <= _a: + qb = 0.0 + break + qa = self._cdf(a, *args) + if (qa > q): + a -= step + step *= 2 + else: + break + else: + qa = self._cdf(a, *args) + + if np.isinf(a) or np.isinf(b): + message = "Arguments that bracket the requested quantile could not be found." + raise RuntimeError(message) + + # maximum number of bisections within the normal float64s + # maxiter = int(np.log2(finfo.max) - np.log2(finfo.smallest_normal)) + maxiter = 2046 + for i in range(maxiter): + if (qa == q): + return a + if (qb == q): + return b + if b <= a+1: + if qa > q: + return a + else: + return b + c = int((a+b)/2.0) + qc = self._cdf(c, *args) + if (qc < q): + if a != c: + a = c + else: + raise RuntimeError('updating stopped, endless loop') + qa = qc + elif (qc > q): + if b != c: + b = c + else: + raise RuntimeError('updating stopped, endless loop') + qb = qc + else: + return c + + +# Must over-ride one of _pmf or _cdf or pass in +# x_k, p(x_k) lists in initialization + + +class rv_discrete(rv_generic): + """A generic discrete random variable class meant for subclassing. + + `rv_discrete` is a base class to construct specific distribution classes + and instances for discrete random variables. It can also be used + to construct an arbitrary distribution defined by a list of support + points and corresponding probabilities. + + Parameters + ---------- + a : float, optional + Lower bound of the support of the distribution, default: 0 + b : float, optional + Upper bound of the support of the distribution, default: plus infinity + moment_tol : float, optional + The tolerance for the generic calculation of moments. + values : tuple of two array_like, optional + ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero + probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk`` + and ``pk`` must have the same shape, and ``xk`` must be unique. + inc : integer, optional + Increment for the support of the distribution. + Default is 1. (other values have not been tested) + badvalue : float, optional + The value in a result arrays that indicates a value that for which + some argument restriction is violated, default is np.nan. + name : str, optional + The name of the instance. This string is used to construct the default + example for distributions. + longname : str, optional + This string is used as part of the first line of the docstring returned + when a subclass has no docstring of its own. Note: `longname` exists + for backwards compatibility, do not use for new subclasses. + shapes : str, optional + The shape of the distribution. For example "m, n" for a distribution + that takes two integers as the two shape arguments for all its methods + If not provided, shape parameters will be inferred from + the signatures of the private methods, ``_pmf`` and ``_cdf`` of + the instance. + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Methods + ------- + rvs + pmf + logpmf + cdf + logcdf + sf + logsf + ppf + isf + moment + stats + entropy + expect + median + mean + std + var + interval + __call__ + support + + Notes + ----- + This class is similar to `rv_continuous`. Whether a shape parameter is + valid is decided by an ``_argcheck`` method (which defaults to checking + that its arguments are strictly positive.) + The main differences are as follows. + + - The support of the distribution is a set of integers. + - Instead of the probability density function, ``pdf`` (and the + corresponding private ``_pdf``), this class defines the + *probability mass function*, `pmf` (and the corresponding + private ``_pmf``.) + - There is no ``scale`` parameter. + - The default implementations of methods (e.g. ``_cdf``) are not designed + for distributions with support that is unbounded below (i.e. + ``a=-np.inf``), so they must be overridden. + + To create a new discrete distribution, we would do the following: + + >>> from scipy.stats import rv_discrete + >>> class poisson_gen(rv_discrete): + ... "Poisson distribution" + ... def _pmf(self, k, mu): + ... return exp(-mu) * mu**k / factorial(k) + + and create an instance:: + + >>> poisson = poisson_gen(name="poisson") + + Note that above we defined the Poisson distribution in the standard form. + Shifting the distribution can be done by providing the ``loc`` parameter + to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)`` + delegates the work to ``poisson._pmf(x-loc, mu)``. + + **Discrete distributions from a list of probabilities** + + Alternatively, you can construct an arbitrary discrete rv defined + on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the + ``values`` keyword argument to the `rv_discrete` constructor. + + **Deepcopying / Pickling** + + If a distribution or frozen distribution is deepcopied (pickled/unpickled, + etc.), any underlying random number generator is deepcopied with it. An + implication is that if a distribution relies on the singleton RandomState + before copying, it will rely on a copy of that random state after copying, + and ``np.random.seed`` will no longer control the state. + + Examples + -------- + Custom made discrete distribution: + + >>> import numpy as np + >>> from scipy import stats + >>> xk = np.arange(7) + >>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2) + >>> custm = stats.rv_discrete(name='custm', values=(xk, pk)) + >>> + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + >>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r') + >>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4) + >>> plt.show() + + Random number generation: + + >>> R = custm.rvs(size=100) + + """ + def __new__(cls, a=0, b=inf, name=None, badvalue=None, + moment_tol=1e-8, values=None, inc=1, longname=None, + shapes=None, seed=None): + + if values is not None: + # dispatch to a subclass + return super().__new__(rv_sample) + else: + # business as usual + return super().__new__(cls) + + def __init__(self, a=0, b=inf, name=None, badvalue=None, + moment_tol=1e-8, values=None, inc=1, longname=None, + shapes=None, seed=None): + + super().__init__(seed) + + # cf generic freeze + self._ctor_param = dict( + a=a, b=b, name=name, badvalue=badvalue, + moment_tol=moment_tol, values=values, inc=inc, + longname=longname, shapes=shapes, seed=seed) + + if badvalue is None: + badvalue = nan + self.badvalue = badvalue + self.a = a + self.b = b + self.moment_tol = moment_tol + self.inc = inc + self.shapes = shapes + + if values is not None: + raise ValueError("rv_discrete.__init__(..., values != None, ...)") + + self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf], + locscale_in='loc=0', + # scale=1 for discrete RVs + locscale_out='loc, 1') + self._attach_methods() + self._construct_docstrings(name, longname) + + def __getstate__(self): + dct = self.__dict__.copy() + # these methods will be remade in __setstate__ + attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs", + "_cdfvec", "_ppfvec", "generic_moment"] + [dct.pop(attr, None) for attr in attrs] + return dct + + def _attach_methods(self): + """Attaches dynamically created methods to the rv_discrete instance.""" + self._cdfvec = vectorize(self._cdf_single, otypes='d') + self.vecentropy = vectorize(self._entropy) + + # _attach_methods is responsible for calling _attach_argparser_methods + self._attach_argparser_methods() + + # nin correction needs to be after we know numargs + # correct nin for generic moment vectorization + _vec_generic_moment = vectorize(_drv2_moment, otypes='d') + _vec_generic_moment.nin = self.numargs + 2 + self.generic_moment = types.MethodType(_vec_generic_moment, self) + + # correct nin for ppf vectorization + _vppf = vectorize(_drv2_ppfsingle, otypes='d') + _vppf.nin = self.numargs + 2 + self._ppfvec = types.MethodType(_vppf, self) + + # now that self.numargs is defined, we can adjust nin + self._cdfvec.nin = self.numargs + 1 + + def _construct_docstrings(self, name, longname): + if name is None: + name = 'Distribution' + self.name = name + + # generate docstring for subclass instances + if longname is None: + if name[0] in ['aeiouAEIOU']: + hstr = "An " + else: + hstr = "A " + longname = hstr + name + + if sys.flags.optimize < 2: + # Skip adding docstrings if interpreter is run with -OO + if self.__doc__ is None: + self._construct_default_doc(longname=longname, + docdict=docdict_discrete, + discrete='discrete') + else: + dct = dict(distdiscrete) + self._construct_doc(docdict_discrete, dct.get(self.name)) + + # discrete RV do not have the scale parameter, remove it + self.__doc__ = self.__doc__.replace( + '\n scale : array_like, ' + 'optional\n scale parameter (default=1)', '') + + def _updated_ctor_param(self): + """Return the current version of _ctor_param, possibly updated by user. + + Used by freezing. + Keep this in sync with the signature of __init__. + """ + dct = self._ctor_param.copy() + dct['a'] = self.a + dct['b'] = self.b + dct['badvalue'] = self.badvalue + dct['moment_tol'] = self.moment_tol + dct['inc'] = self.inc + dct['name'] = self.name + dct['shapes'] = self.shapes + return dct + + def _nonzero(self, k, *args): + return floor(k) == k + + def _pmf(self, k, *args): + return self._cdf(k, *args) - self._cdf(k-1, *args) + + def _logpmf(self, k, *args): + with np.errstate(divide='ignore'): + return log(self._pmf(k, *args)) + + def _logpxf(self, k, *args): + # continuous distributions have PDF, discrete have PMF, but sometimes + # the distinction doesn't matter. This lets us use `_logpxf` for both + # discrete and continuous distributions. + return self._logpmf(k, *args) + + def _unpack_loc_scale(self, theta): + try: + loc = theta[-1] + scale = 1 + args = tuple(theta[:-1]) + except IndexError as e: + raise ValueError("Not enough input arguments.") from e + return loc, scale, args + + def _cdf_single(self, k, *args): + _a, _b = self._get_support(*args) + m = arange(int(_a), k+1) + return np.sum(self._pmf(m, *args), axis=0) + + def _cdf(self, x, *args): + k = floor(x).astype(np.float64) + return self._cdfvec(k, *args) + + # generic _logcdf, _sf, _logsf, _ppf, _isf, _rvs defined in rv_generic + + def rvs(self, *args, **kwargs): + """Random variates of given type. + + Parameters + ---------- + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + size : int or tuple of ints, optional + Defining number of random variates (Default is 1). Note that `size` + has to be given as keyword, not as positional argument. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `random_state` is None (or `np.random`), the + `numpy.random.RandomState` singleton is used. + If `random_state` is an int, a new ``RandomState`` instance is + used, seeded with `random_state`. + If `random_state` is already a ``Generator`` or ``RandomState`` + instance, that instance is used. + + Returns + ------- + rvs : ndarray or scalar + Random variates of given `size`. + + """ + kwargs['discrete'] = True + return super().rvs(*args, **kwargs) + + def pmf(self, k, *args, **kwds): + """Probability mass function at k of the given RV. + + Parameters + ---------- + k : array_like + Quantiles. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + loc : array_like, optional + Location parameter (default=0). + + Returns + ------- + pmf : array_like + Probability mass function evaluated at k + + """ + args, loc, _ = self._parse_args(*args, **kwds) + k, loc = map(asarray, (k, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + k = asarray(k-loc) + cond0 = self._argcheck(*args) + cond1 = (k >= _a) & (k <= _b) + if not isinstance(self, rv_sample): + cond1 = cond1 & self._nonzero(k, *args) + cond = cond0 & cond1 + output = zeros(shape(cond), 'd') + place(output, (1-cond0) + np.isnan(k), self.badvalue) + if np.any(cond): + goodargs = argsreduce(cond, *((k,)+args)) + place(output, cond, np.clip(self._pmf(*goodargs), 0, 1)) + if output.ndim == 0: + return output[()] + return output + + def logpmf(self, k, *args, **kwds): + """Log of the probability mass function at k of the given RV. + + Parameters + ---------- + k : array_like + Quantiles. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter. Default is 0. + + Returns + ------- + logpmf : array_like + Log of the probability mass function evaluated at k. + + """ + args, loc, _ = self._parse_args(*args, **kwds) + k, loc = map(asarray, (k, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + k = asarray(k-loc) + cond0 = self._argcheck(*args) + cond1 = (k >= _a) & (k <= _b) + if not isinstance(self, rv_sample): + cond1 = cond1 & self._nonzero(k, *args) + cond = cond0 & cond1 + output = empty(shape(cond), 'd') + output.fill(-inf) + place(output, (1-cond0) + np.isnan(k), self.badvalue) + if np.any(cond): + goodargs = argsreduce(cond, *((k,)+args)) + place(output, cond, self._logpmf(*goodargs)) + if output.ndim == 0: + return output[()] + return output + + def cdf(self, k, *args, **kwds): + """Cumulative distribution function of the given RV. + + Parameters + ---------- + k : array_like, int + Quantiles. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + + Returns + ------- + cdf : ndarray + Cumulative distribution function evaluated at `k`. + + """ + args, loc, _ = self._parse_args(*args, **kwds) + k, loc = map(asarray, (k, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + k = asarray(k-loc) + cond0 = self._argcheck(*args) + cond1 = (k >= _a) & (k < _b) + cond2 = (k >= _b) + cond3 = np.isneginf(k) + cond = cond0 & cond1 & np.isfinite(k) + + output = zeros(shape(cond), 'd') + place(output, cond2*(cond0 == cond0), 1.0) + place(output, cond3*(cond0 == cond0), 0.0) + place(output, (1-cond0) + np.isnan(k), self.badvalue) + + if np.any(cond): + goodargs = argsreduce(cond, *((k,)+args)) + place(output, cond, np.clip(self._cdf(*goodargs), 0, 1)) + if output.ndim == 0: + return output[()] + return output + + def logcdf(self, k, *args, **kwds): + """Log of the cumulative distribution function at k of the given RV. + + Parameters + ---------- + k : array_like, int + Quantiles. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + + Returns + ------- + logcdf : array_like + Log of the cumulative distribution function evaluated at k. + + """ + args, loc, _ = self._parse_args(*args, **kwds) + k, loc = map(asarray, (k, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + k = asarray(k-loc) + cond0 = self._argcheck(*args) + cond1 = (k >= _a) & (k < _b) + cond2 = (k >= _b) + cond = cond0 & cond1 + output = empty(shape(cond), 'd') + output.fill(-inf) + place(output, (1-cond0) + np.isnan(k), self.badvalue) + place(output, cond2*(cond0 == cond0), 0.0) + + if np.any(cond): + goodargs = argsreduce(cond, *((k,)+args)) + place(output, cond, self._logcdf(*goodargs)) + if output.ndim == 0: + return output[()] + return output + + def sf(self, k, *args, **kwds): + """Survival function (1 - `cdf`) at k of the given RV. + + Parameters + ---------- + k : array_like + Quantiles. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + + Returns + ------- + sf : array_like + Survival function evaluated at k. + + """ + args, loc, _ = self._parse_args(*args, **kwds) + k, loc = map(asarray, (k, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + k = asarray(k-loc) + cond0 = self._argcheck(*args) + cond1 = (k >= _a) & (k < _b) + cond2 = ((k < _a) | np.isneginf(k)) & cond0 + cond = cond0 & cond1 & np.isfinite(k) + output = zeros(shape(cond), 'd') + place(output, (1-cond0) + np.isnan(k), self.badvalue) + place(output, cond2, 1.0) + if np.any(cond): + goodargs = argsreduce(cond, *((k,)+args)) + place(output, cond, np.clip(self._sf(*goodargs), 0, 1)) + if output.ndim == 0: + return output[()] + return output + + def logsf(self, k, *args, **kwds): + """Log of the survival function of the given RV. + + Returns the log of the "survival function," defined as 1 - `cdf`, + evaluated at `k`. + + Parameters + ---------- + k : array_like + Quantiles. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + + Returns + ------- + logsf : ndarray + Log of the survival function evaluated at `k`. + + """ + args, loc, _ = self._parse_args(*args, **kwds) + k, loc = map(asarray, (k, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + k = asarray(k-loc) + cond0 = self._argcheck(*args) + cond1 = (k >= _a) & (k < _b) + cond2 = (k < _a) & cond0 + cond = cond0 & cond1 + output = empty(shape(cond), 'd') + output.fill(-inf) + place(output, (1-cond0) + np.isnan(k), self.badvalue) + place(output, cond2, 0.0) + if np.any(cond): + goodargs = argsreduce(cond, *((k,)+args)) + place(output, cond, self._logsf(*goodargs)) + if output.ndim == 0: + return output[()] + return output + + def ppf(self, q, *args, **kwds): + """Percent point function (inverse of `cdf`) at q of the given RV. + + Parameters + ---------- + q : array_like + Lower tail probability. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + + Returns + ------- + k : array_like + Quantile corresponding to the lower tail probability, q. + + """ + args, loc, _ = self._parse_args(*args, **kwds) + q, loc = map(asarray, (q, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + cond0 = self._argcheck(*args) & (loc == loc) + cond1 = (q > 0) & (q < 1) + cond2 = (q == 1) & cond0 + cond = cond0 & cond1 + output = np.full(shape(cond), fill_value=self.badvalue, dtype='d') + # output type 'd' to handle nin and inf + place(output, (q == 0)*(cond == cond), _a-1 + loc) + place(output, cond2, _b + loc) + if np.any(cond): + goodargs = argsreduce(cond, *((q,)+args+(loc,))) + loc, goodargs = goodargs[-1], goodargs[:-1] + place(output, cond, self._ppf(*goodargs) + loc) + + if output.ndim == 0: + return output[()] + return output + + def isf(self, q, *args, **kwds): + """Inverse survival function (inverse of `sf`) at q of the given RV. + + Parameters + ---------- + q : array_like + Upper tail probability. + arg1, arg2, arg3,... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + loc : array_like, optional + Location parameter (default=0). + + Returns + ------- + k : ndarray or scalar + Quantile corresponding to the upper tail probability, q. + + """ + args, loc, _ = self._parse_args(*args, **kwds) + q, loc = map(asarray, (q, loc)) + args = tuple(map(asarray, args)) + _a, _b = self._get_support(*args) + cond0 = self._argcheck(*args) & (loc == loc) + cond1 = (q > 0) & (q < 1) + cond2 = (q == 1) & cond0 + cond3 = (q == 0) & cond0 + cond = cond0 & cond1 + + # same problem as with ppf; copied from ppf and changed + output = np.full(shape(cond), fill_value=self.badvalue, dtype='d') + # output type 'd' to handle nin and inf + lower_bound = _a - 1 + loc + upper_bound = _b + loc + place(output, cond2*(cond == cond), lower_bound) + place(output, cond3*(cond == cond), upper_bound) + + # call place only if at least 1 valid argument + if np.any(cond): + goodargs = argsreduce(cond, *((q,)+args+(loc,))) + loc, goodargs = goodargs[-1], goodargs[:-1] + # PB same as ticket 766 + place(output, cond, self._isf(*goodargs) + loc) + + if output.ndim == 0: + return output[()] + return output + + def _entropy(self, *args): + if hasattr(self, 'pk'): + return stats.entropy(self.pk) + else: + _a, _b = self._get_support(*args) + return _expect(lambda x: entr(self._pmf(x, *args)), + _a, _b, self._ppf(0.5, *args), self.inc) + + def expect(self, func=None, args=(), loc=0, lb=None, ub=None, + conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32): + """ + Calculate expected value of a function with respect to the distribution + for discrete distribution by numerical summation. + + Parameters + ---------- + func : callable, optional + Function for which the expectation value is calculated. + Takes only one argument. + The default is the identity mapping f(k) = k. + args : tuple, optional + Shape parameters of the distribution. + loc : float, optional + Location parameter. + Default is 0. + lb, ub : int, optional + Lower and upper bound for the summation, default is set to the + support of the distribution, inclusive (``lb <= k <= ub``). + conditional : bool, optional + If true then the expectation is corrected by the conditional + probability of the summation interval. The return value is the + expectation of the function, `func`, conditional on being in + the given interval (k such that ``lb <= k <= ub``). + Default is False. + maxcount : int, optional + Maximal number of terms to evaluate (to avoid an endless loop for + an infinite sum). Default is 1000. + tolerance : float, optional + Absolute tolerance for the summation. Default is 1e-10. + chunksize : int, optional + Iterate over the support of a distributions in chunks of this size. + Default is 32. + + Returns + ------- + expect : float + Expected value. + + Notes + ----- + For heavy-tailed distributions, the expected value may or + may not exist, + depending on the function, `func`. If it does exist, but the + sum converges + slowly, the accuracy of the result may be rather low. For instance, for + ``zipf(4)``, accuracy for mean, variance in example is only 1e-5. + increasing `maxcount` and/or `chunksize` may improve the result, + but may also make zipf very slow. + + The function is not vectorized. + + """ + # Although `args` is just the shape parameters, `poisson_binom` needs this + # to split the vector-valued shape into a tuple of separate shapes + args, _, _ = self._parse_args(*args) + + if func is None: + def fun(x): + # loc and args from outer scope + return (x+loc)*self._pmf(x, *args) + else: + def fun(x): + # loc and args from outer scope + return func(x+loc)*self._pmf(x, *args) + # used pmf because _pmf does not check support in randint and there + # might be problems(?) with correct self.a, self.b at this stage maybe + # not anymore, seems to work now with _pmf + + _a, _b = self._get_support(*args) + if lb is None: + lb = _a + else: + lb = lb - loc # convert bound for standardized distribution + if ub is None: + ub = _b + else: + ub = ub - loc # convert bound for standardized distribution + if conditional: + invfac = self.sf(lb-1, *args) - self.sf(ub, *args) + else: + invfac = 1.0 + + if isinstance(self, rv_sample): + res = self._expect(fun, lb, ub) + return res / invfac + + # iterate over the support, starting from the median + x0 = self._ppf(0.5, *args) + res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize) + return res / invfac + + def _param_info(self): + shape_info = self._shape_info() + loc_info = _ShapeInfo("loc", True, (-np.inf, np.inf), (False, False)) + param_info = shape_info + [loc_info] + return param_info + + +def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10, + chunksize=32): + """Helper for computing the expectation value of `fun`.""" + # short-circuit if the support size is small enough + if (ub - lb) <= chunksize: + supp = np.arange(lb, ub+1, inc) + vals = fun(supp) + return np.sum(vals) + + # otherwise, iterate starting from x0 + if x0 < lb: + x0 = lb + if x0 > ub: + x0 = ub + + count, tot = 0, 0. + # iterate over [x0, ub] inclusive + for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc): + count += x.size + delta = np.sum(fun(x)) + tot += delta + if abs(delta) < tolerance * x.size: + break + if count > maxcount: + warnings.warn('expect(): sum did not converge', + RuntimeWarning, stacklevel=3) + return tot + + # iterate over [lb, x0) + for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc): + count += x.size + delta = np.sum(fun(x)) + tot += delta + if abs(delta) < tolerance * x.size: + break + if count > maxcount: + warnings.warn('expect(): sum did not converge', + RuntimeWarning, stacklevel=3) + break + + return tot + + +def _iter_chunked(x0, x1, chunksize=4, inc=1): + """Iterate from x0 to x1 in chunks of chunksize and steps inc. + + x0 must be finite, x1 need not be. In the latter case, the iterator is + infinite. + Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards + (make sure to set inc < 0.) + + >>> from scipy.stats._distn_infrastructure import _iter_chunked + >>> [x for x in _iter_chunked(2, 5, inc=2)] + [array([2, 4])] + >>> [x for x in _iter_chunked(2, 11, inc=2)] + [array([2, 4, 6, 8]), array([10])] + >>> [x for x in _iter_chunked(2, -5, inc=-2)] + [array([ 2, 0, -2, -4])] + >>> [x for x in _iter_chunked(2, -9, inc=-2)] + [array([ 2, 0, -2, -4]), array([-6, -8])] + + """ + if inc == 0: + raise ValueError('Cannot increment by zero.') + if chunksize <= 0: + raise ValueError(f'Chunk size must be positive; got {chunksize}.') + + s = 1 if inc > 0 else -1 + stepsize = abs(chunksize * inc) + + x = np.copy(x0) + while (x - x1) * inc < 0: + delta = min(stepsize, abs(x - x1)) + step = delta * s + supp = np.arange(x, x + step, inc) + x += step + yield supp + + +class rv_sample(rv_discrete): + """A 'sample' discrete distribution defined by the support and values. + + The ctor ignores most of the arguments, only needs the `values` argument. + """ + + def __init__(self, a=0, b=inf, name=None, badvalue=None, + moment_tol=1e-8, values=None, inc=1, longname=None, + shapes=None, seed=None): + + super(rv_discrete, self).__init__(seed) + + if values is None: + raise ValueError("rv_sample.__init__(..., values=None,...)") + + # cf generic freeze + self._ctor_param = dict( + a=a, b=b, name=name, badvalue=badvalue, + moment_tol=moment_tol, values=values, inc=inc, + longname=longname, shapes=shapes, seed=seed) + + if badvalue is None: + badvalue = nan + self.badvalue = badvalue + self.moment_tol = moment_tol + self.inc = inc + self.shapes = shapes + self.vecentropy = self._entropy + + xk, pk = values + + if np.shape(xk) != np.shape(pk): + raise ValueError("xk and pk must have the same shape.") + if np.less(pk, 0.0).any(): + raise ValueError("All elements of pk must be non-negative.") + if not np.allclose(np.sum(pk), 1): + raise ValueError("The sum of provided pk is not 1.") + if not len(set(np.ravel(xk))) == np.size(xk): + raise ValueError("xk may not contain duplicate values.") + + indx = np.argsort(np.ravel(xk)) + self.xk = np.take(np.ravel(xk), indx, 0) + self.pk = np.take(np.ravel(pk), indx, 0) + self.a = self.xk[0] + self.b = self.xk[-1] + + self.qvals = np.cumsum(self.pk, axis=0) + + self.shapes = ' ' # bypass inspection + + self._construct_argparser(meths_to_inspect=[self._pmf], + locscale_in='loc=0', + # scale=1 for discrete RVs + locscale_out='loc, 1') + + self._attach_methods() + + self._construct_docstrings(name, longname) + + def __getstate__(self): + dct = self.__dict__.copy() + + # these methods will be remade in rv_generic.__setstate__, + # which calls rv_generic._attach_methods + attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs"] + [dct.pop(attr, None) for attr in attrs] + + return dct + + def _attach_methods(self): + """Attaches dynamically created argparser methods.""" + self._attach_argparser_methods() + + def _get_support(self, *args): + """Return the support of the (unscaled, unshifted) distribution. + + Parameters + ---------- + arg1, arg2, ... : array_like + The shape parameter(s) for the distribution (see docstring of the + instance object for more information). + + Returns + ------- + a, b : numeric (float, or int or +/-np.inf) + end-points of the distribution's support. + """ + return self.a, self.b + + def _pmf(self, x): + return np.select([x == k for k in self.xk], + [np.broadcast_arrays(p, x)[0] for p in self.pk], 0) + + def _cdf(self, x): + xx, xxk = np.broadcast_arrays(x[:, None], self.xk) + indx = np.argmax(xxk > xx, axis=-1) - 1 + return self.qvals[indx] + + def _ppf(self, q): + qq, sqq = np.broadcast_arrays(q[..., None], self.qvals) + indx = argmax(sqq >= qq, axis=-1) + return self.xk[indx] + + def _rvs(self, size=None, random_state=None): + # Need to define it explicitly, otherwise .rvs() with size=None + # fails due to explicit broadcasting in _ppf + U = random_state.uniform(size=size) + if size is None: + U = np.array(U, ndmin=1) + Y = self._ppf(U)[0] + else: + Y = self._ppf(U) + return Y + + def _entropy(self): + return stats.entropy(self.pk) + + def generic_moment(self, n): + n = asarray(n) + return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0) + + def _expect(self, fun, lb, ub, *args, **kwds): + # ignore all args, just do a brute force summation + supp = self.xk[(lb <= self.xk) & (self.xk <= ub)] + vals = fun(supp) + return np.sum(vals) + + +def _check_shape(argshape, size): + """ + This is a utility function used by `_rvs()` in the class geninvgauss_gen. + It compares the tuple argshape to the tuple size. + + Parameters + ---------- + argshape : tuple of integers + Shape of the arguments. + size : tuple of integers or integer + Size argument of rvs(). + + Returns + ------- + The function returns two tuples, scalar_shape and bc. + + scalar_shape : tuple + Shape to which the 1-d array of random variates returned by + _rvs_scalar() is converted when it is copied into the + output array of _rvs(). + + bc : tuple of booleans + bc is an tuple the same length as size. bc[j] is True if the data + associated with that index is generated in one call of _rvs_scalar(). + + """ + scalar_shape = [] + bc = [] + for argdim, sizedim in zip_longest(argshape[::-1], size[::-1], + fillvalue=1): + if sizedim > argdim or (argdim == sizedim == 1): + scalar_shape.append(sizedim) + bc.append(True) + else: + bc.append(False) + return tuple(scalar_shape[::-1]), tuple(bc[::-1]) + + +def get_distribution_names(namespace_pairs, rv_base_class): + """Collect names of statistical distributions and their generators. + + Parameters + ---------- + namespace_pairs : sequence + A snapshot of (name, value) pairs in the namespace of a module. + rv_base_class : class + The base class of random variable generator classes in a module. + + Returns + ------- + distn_names : list of strings + Names of the statistical distributions. + distn_gen_names : list of strings + Names of the generators of the statistical distributions. + Note that these are not simply the names of the statistical + distributions, with a _gen suffix added. + + """ + distn_names = [] + distn_gen_names = [] + for name, value in namespace_pairs: + if name.startswith('_'): + continue + if name.endswith('_gen') and issubclass(value, rv_base_class): + distn_gen_names.append(name) + if isinstance(value, rv_base_class): + distn_names.append(name) + return distn_names, distn_gen_names diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distr_params.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distr_params.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc2a09c78a524a5914cebee7429bf4e0db769f0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distr_params.py @@ -0,0 +1,299 @@ +""" +Sane parameters for stats.distributions. +""" +import numpy as np + +distcont = [ + ['alpha', (3.5704770516650459,)], + ['anglit', ()], + ['arcsine', ()], + ['argus', (1.0,)], + ['beta', (2.3098496451481823, 0.62687954300963677)], + ['betaprime', (5, 6)], + ['bradford', (0.29891359763170633,)], + ['burr', (10.5, 4.3)], + ['burr12', (10, 4)], + ['cauchy', ()], + ['chi', (78,)], + ['chi2', (55,)], + ['cosine', ()], + ['crystalball', (2.0, 3.0)], + ['dgamma', (1.1023326088288166,)], + ['dpareto_lognorm', (3, 1.2, 1.5, 2)], + ['dweibull', (2.0685080649914673,)], + ['erlang', (10,)], + ['expon', ()], + ['exponnorm', (1.5,)], + ['exponpow', (2.697119160358469,)], + ['exponweib', (2.8923945291034436, 1.9505288745913174)], + ['f', (29, 18)], + ['fatiguelife', (29,)], # correction numargs = 1 + ['fisk', (3.0857548622253179,)], + ['foldcauchy', (4.7164673455831894,)], + ['foldnorm', (1.9521253373555869,)], + ['gamma', (1.9932305483800778,)], + ['gausshyper', (13.763771604130699, 3.1189636648681431, + 2.5145980350183019, 5.1811649903971615)], # veryslow + ['genexpon', (9.1325976465418908, 16.231956600590632, 3.2819552690843983)], + ['genextreme', (-0.1,)], + ['gengamma', (4.4162385429431925, 3.1193091679242761)], + ['gengamma', (4.4162385429431925, -3.1193091679242761)], + ['genhalflogistic', (0.77274727809929322,)], + ['genhyperbolic', (0.5, 1.5, -0.5,)], + ['geninvgauss', (2.3, 1.5)], + ['genlogistic', (0.41192440799679475,)], + ['gennorm', (1.2988442399460265,)], + ['halfgennorm', (0.6748054997000371,)], + ['genpareto', (0.1,)], # use case with finite moments + ['gibrat', ()], + ['gompertz', (0.94743713075105251,)], + ['gumbel_l', ()], + ['gumbel_r', ()], + ['halfcauchy', ()], + ['halflogistic', ()], + ['halfnorm', ()], + ['hypsecant', ()], + ['invgamma', (4.0668996136993067,)], + ['invgauss', (0.14546264555347513,)], + ['invweibull', (10.58,)], + ['irwinhall', (10,)], + ['jf_skew_t', (8, 4)], + ['johnsonsb', (4.3172675099141058, 3.1837781130785063)], + ['johnsonsu', (2.554395574161155, 2.2482281679651965)], + ['kappa4', (0.0, 0.0)], + ['kappa4', (-0.1, 0.1)], + ['kappa4', (0.0, 0.1)], + ['kappa4', (0.1, 0.0)], + ['kappa3', (1.0,)], + ['ksone', (1000,)], # replace 22 by 100 to avoid failing range, ticket 956 + ['kstwo', (10,)], + ['kstwobign', ()], + ['landau', ()], + ['laplace', ()], + ['laplace_asymmetric', (2,)], + ['levy', ()], + ['levy_l', ()], + ['levy_stable', (1.8, -0.5)], + ['loggamma', (0.41411931826052117,)], + ['logistic', ()], + ['loglaplace', (3.2505926592051435,)], + ['lognorm', (0.95368226960575331,)], + ['loguniform', (0.01, 1.25)], + ['lomax', (1.8771398388773268,)], + ['maxwell', ()], + ['mielke', (10.4, 4.6)], + ['moyal', ()], + ['nakagami', (4.9673794866666237,)], + ['ncf', (27, 27, 0.41578441799226107)], + ['nct', (14, 0.24045031331198066)], + ['ncx2', (21, 1.0560465975116415)], + ['norm', ()], + ['norminvgauss', (1.25, 0.5)], + ['pareto', (2.621716532144454,)], + ['pearson3', (0.1,)], + ['pearson3', (-2,)], + ['powerlaw', (1.6591133289905851,)], + ['powerlaw', (0.6591133289905851,)], + ['powerlognorm', (2.1413923530064087, 0.44639540782048337)], + ['powernorm', (4.4453652254590779,)], + ['rayleigh', ()], + ['rdist', (1.6,)], + ['recipinvgauss', (0.63004267809369119,)], + ['reciprocal', (0.01, 1.25)], + ['rel_breitwigner', (36.545206797050334, )], + ['rice', (0.7749725210111873,)], + ['semicircular', ()], + ['skewcauchy', (0.5,)], + ['skewnorm', (4.0,)], + ['studentized_range', (3.0, 10.0)], + ['t', (2.7433514990818093,)], + ['trapezoid', (0.2, 0.8)], + ['triang', (0.15785029824528218,)], + ['truncexpon', (4.6907725456810478,)], + ['truncnorm', (-1.0978730080013919, 2.7306754109031979)], + ['truncnorm', (0.1, 2.)], + ['truncpareto', (1.8, 5.3)], + ['truncpareto', (2, 5)], + ['truncweibull_min', (2.5, 0.25, 1.75)], + ['tukeylambda', (3.1321477856738267,)], + ['uniform', ()], + ['vonmises', (3.9939042581071398,)], + ['vonmises_line', (3.9939042581071398,)], + ['wald', ()], + ['weibull_max', (2.8687961709100187,)], + ['weibull_min', (1.7866166930421596,)], + ['wrapcauchy', (0.031071279018614728,)] +] + + +distdiscrete = [ + ['bernoulli',(0.3,)], + ['betabinom', (5, 2.3, 0.63)], + ['betanbinom', (5, 9.3, 1)], + ['binom', (5, 0.4)], + ['boltzmann',(1.4, 19)], + ['dlaplace', (0.8,)], # 0.5 + ['geom', (0.5,)], + ['hypergeom',(30, 12, 6)], + ['hypergeom',(21,3,12)], # numpy.random (3,18,12) numpy ticket:921 + ['hypergeom',(21,18,11)], # numpy.random (18,3,11) numpy ticket:921 + ['nchypergeom_fisher', (140, 80, 60, 0.5)], + ['nchypergeom_wallenius', (140, 80, 60, 0.5)], + ['logser', (0.6,)], # re-enabled, numpy ticket:921 + ['nbinom', (0.4, 0.4)], # from tickets: 583 + ['nbinom', (5, 0.5)], + ['planck', (0.51,)], # 4.1 + ['poisson', (0.6,)], + ['poisson_binom', ([0.1, 0.6, 0.7, 0.8],)], + ['randint', (7, 31)], + ['skellam', (15, 8)], + ['zipf', (6.6,)], + ['zipfian', (0.75, 15)], + ['zipfian', (1.25, 10)], + ['yulesimon', (11.0,)], + ['nhypergeom', (20, 7, 1)] +] + + +invdistdiscrete = [ + # In each of the following, at least one shape parameter is invalid + ['hypergeom', (3, 3, 4)], + ['nhypergeom', (5, 2, 8)], + ['nchypergeom_fisher', (3, 3, 4, 1)], + ['nchypergeom_wallenius', (3, 3, 4, 1)], + ['bernoulli', (1.5, )], + ['binom', (10, 1.5)], + ['betabinom', (10, -0.4, -0.5)], + ['betanbinom', (10, -0.4, -0.5)], + ['boltzmann', (-1, 4)], + ['dlaplace', (-0.5, )], + ['geom', (1.5, )], + ['logser', (1.5, )], + ['nbinom', (10, 1.5)], + ['planck', (-0.5, )], + ['poisson', (-0.5, )], + ['poisson_binom', ([-1, 2, 0.5],)], + ['randint', (5, 2)], + ['skellam', (-5, -2)], + ['zipf', (-2, )], + ['yulesimon', (-2, )], + ['zipfian', (-0.75, 15)] +] + + +invdistcont = [ + # In each of the following, at least one shape parameter is invalid + ['alpha', (-1, )], + ['anglit', ()], + ['arcsine', ()], + ['argus', (-1, )], + ['beta', (-2, 2)], + ['betaprime', (-2, 2)], + ['bradford', (-1, )], + ['burr', (-1, 1)], + ['burr12', (-1, 1)], + ['cauchy', ()], + ['chi', (-1, )], + ['chi2', (-1, )], + ['cosine', ()], + ['crystalball', (-1, 2)], + ['dgamma', (-1, )], + ['dpareto_lognorm', (3, -1.2, 1.5, 2)], + ['dweibull', (-1, )], + ['erlang', (-1, )], + ['expon', ()], + ['exponnorm', (-1, )], + ['exponweib', (1, -1)], + ['exponpow', (-1, )], + ['f', (10, -10)], + ['fatiguelife', (-1, )], + ['fisk', (-1, )], + ['foldcauchy', (-1, )], + ['foldnorm', (-1, )], + ['genlogistic', (-1, )], + ['gennorm', (-1, )], + ['genpareto', (np.inf, )], + ['genexpon', (1, 2, -3)], + ['genextreme', (np.inf, )], + ['genhyperbolic', (0.5, -0.5, -1.5,)], + ['gausshyper', (1, 2, 3, -4)], + ['gamma', (-1, )], + ['gengamma', (-1, 0)], + ['genhalflogistic', (-1, )], + ['geninvgauss', (1, 0)], + ['gibrat', ()], + ['gompertz', (-1, )], + ['gumbel_r', ()], + ['gumbel_l', ()], + ['halfcauchy', ()], + ['halflogistic', ()], + ['halfnorm', ()], + ['halfgennorm', (-1, )], + ['hypsecant', ()], + ['invgamma', (-1, )], + ['invgauss', (-1, )], + ['invweibull', (-1, )], + ['irwinhall', (-1,)], + ['irwinhall', (0,)], + ['irwinhall', (2.5,)], + ['jf_skew_t', (-1, 0)], + ['johnsonsb', (1, -2)], + ['johnsonsu', (1, -2)], + ['kappa4', (np.nan, 0)], + ['kappa3', (-1, )], + ['ksone', (-1, )], + ['kstwo', (-1, )], + ['kstwobign', ()], + ['landau', ()], + ['laplace', ()], + ['laplace_asymmetric', (-1, )], + ['levy', ()], + ['levy_l', ()], + ['levy_stable', (-1, 1)], + ['logistic', ()], + ['loggamma', (-1, )], + ['loglaplace', (-1, )], + ['lognorm', (-1, )], + ['loguniform', (10, 5)], + ['lomax', (-1, )], + ['maxwell', ()], + ['mielke', (1, -2)], + ['moyal', ()], + ['nakagami', (-1, )], + ['ncx2', (-1, 2)], + ['ncf', (10, 20, -1)], + ['nct', (-1, 2)], + ['norm', ()], + ['norminvgauss', (5, -10)], + ['pareto', (-1, )], + ['pearson3', (np.nan, )], + ['powerlaw', (-1, )], + ['powerlognorm', (1, -2)], + ['powernorm', (-1, )], + ['rdist', (-1, )], + ['rayleigh', ()], + ['rice', (-1, )], + ['recipinvgauss', (-1, )], + ['semicircular', ()], + ['skewnorm', (np.inf, )], + ['studentized_range', (-1, 1)], + ['rel_breitwigner', (-2, )], + ['t', (-1, )], + ['trapezoid', (0, 2)], + ['triang', (2, )], + ['truncexpon', (-1, )], + ['truncnorm', (10, 5)], + ['truncpareto', (-1, 5)], + ['truncpareto', (1.8, .5)], + ['truncweibull_min', (-2.5, 0.25, 1.75)], + ['tukeylambda', (np.nan, )], + ['uniform', ()], + ['vonmises', (-1, )], + ['vonmises_line', (-1, )], + ['wald', ()], + ['weibull_min', (-1, )], + ['weibull_max', (-1, )], + ['wrapcauchy', (2, )], + ['reciprocal', (15, 10)], + ['skewcauchy', (2, )] +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distribution_infrastructure.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distribution_infrastructure.py new file mode 100644 index 0000000000000000000000000000000000000000..53691f96ebb275c284f54dc374b03fba44c6b7f1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_distribution_infrastructure.py @@ -0,0 +1,5068 @@ +import functools +from abc import ABC, abstractmethod +from functools import cached_property +import math + +import numpy as np +from numpy import inf + +from scipy._lib._util import _lazywhere, _rng_spawn +from scipy._lib._docscrape import ClassDoc, NumpyDocString +from scipy import special, stats +from scipy.integrate import tanhsinh as _tanhsinh +from scipy.optimize._bracket import _bracket_root, _bracket_minimum +from scipy.optimize._chandrupatla import _chandrupatla, _chandrupatla_minimize +from scipy.stats._probability_distribution import _ProbabilityDistribution +from scipy.stats import qmc + +# in case we need to distinguish between None and not specified +# Typically this is used to determine whether the tolerance has been set by the +# user and make a decision about which method to use to evaluate a distribution +# function. Sometimes, the logic does not consider the value of the tolerance, +# only whether this has been defined or not. This is not intended to be the +# best possible logic; the intent is to establish the structure, which can +# be refined in follow-up work. +# See https://github.com/scipy/scipy/pull/21050#discussion_r1714195433. +_null = object() +def _isnull(x): + return type(x) is object or x is None + +__all__ = ['make_distribution', 'Mixture', 'order_statistic', + 'truncate', 'abs', 'exp', 'log'] + +# Could add other policies for broadcasting and edge/out-of-bounds case handling +# For instance, when edge case handling is known not to be needed, it's much +# faster to turn it off, but it might still be nice to have array conversion +# and shaping done so the user doesn't need to be so careful. +_SKIP_ALL = "skip_all" +# Other cache policies would be useful, too. +_NO_CACHE = "no_cache" + +# TODO: +# Test sample dtypes +# Add dtype kwarg (especially for distributions with no parameters) +# When drawing endpoint/out-of-bounds values of a parameter, draw them from +# the endpoints/out-of-bounds region of the full `domain`, not `typical`. +# Distributions without shape parameters probably need to accept a `dtype` parameter; +# right now they default to float64. If we have them default to float16, they will +# need to determine result_type when input is not float16 (overhead). +# Test _solve_bounded bracket logic, and decide what to do about warnings +# Get test coverage to 100% +# Raise when distribution method returns wrong shape/dtype? +# Consider ensuring everything is at least 1D for calculations? Would avoid needing +# to sprinkle `np.asarray` throughout due to indescriminate conversion of 0D arrays +# to scalars +# Break up `test_basic`: test each method separately +# Fix `sample` for QMCEngine (implementation does not match documentation) +# When a parameter is invalid, set only the offending parameter to NaN (if possible)? +# `_tanhsinh` special case when there are no abscissae between the limits +# example: cdf of uniform betweeen 1.0 and np.nextafter(1.0, np.inf) +# check behavior of moment methods when moments are undefined/infinite - +# basically OK but needs tests +# investigate use of median +# implement symmetric distribution +# implement composite distribution +# implement wrapped distribution +# profile/optimize +# general cleanup (choose keyword-only parameters) +# compare old/new distribution timing +# make video +# add array API support +# why does dist.ilogcdf(-100) not converge to bound? Check solver response to inf +# _chandrupatla_minimize should not report xm = fm = NaN when it fails +# integrate `logmoment` into `moment`? (Not hard, but enough time and code +# complexity to wait for reviewer feedback before adding.) +# Eliminate bracket_root error "`min <= a < b <= max` must be True" +# Test repr? +# use `median` information to improve integration? In some cases this will +# speed things up. If it's not needed, it may be about twice as slow. I think +# it should depend on the accuracy setting. +# in tests, check reference value against that produced using np.vectorize? +# add `axis` to `ks_1samp` +# User tips for faster execution: +# - pass NumPy arrays +# - pass inputs of floating point type (not integers) +# - prefer NumPy scalars or 0d arrays over other size 1 arrays +# - pass no invalid parameters and disable invalid parameter checks with iv_profile +# - provide a Generator if you're going to do sampling +# add options for drawing parameters: log-spacing +# accuracy benchmark suite +# Should caches be attributes so we can more easily ensure that they are not +# modified when caching is turned off? +# Make ShiftedScaledDistribution more efficient - only process underlying +# distribution parameters as necessary. +# Reconsider `all_inclusive` +# Should process_parameters update kwargs rather than returning? Should we +# update parameters rather than setting to what process_parameters returns? + +# Questions: +# 1. I override `__getattr__` so that distribution parameters can be read as +# attributes. We don't want uses to try to change them. +# - To prevent replacements (dist.a = b), I could override `__setattr__`. +# - To prevent in-place modifications, `__getattr__` could return a copy, +# or it could set the WRITEABLE flag of the array to false. +# Which should I do? +# 2. `cache_policy` is supported in several methods where I imagine it being +# useful, but it needs to be tested. Before doing that: +# - What should the default value be? +# - What should the other values be? +# Or should we just eliminate this policy? +# 3. `validation_policy` is supported in a few places, but it should be checked for +# consistency. I have the same questions as for `cache_policy`. +# 4. `tol` is currently notional. I think there needs to be way to set +# separate `atol` and `rtol`. Some ways I imagine it being used: +# - Values can be passed to iterative functions (quadrature, root-finder). +# - To control which "method" of a distribution function is used. For +# example, if `atol` is set to `1e-12`, it may be acceptable to compute +# the complementary CDF as 1 - CDF even when CDF is nearly 1; otherwise, +# a (potentially more time-consuming) method would need to be used. +# I'm looking for unified suggestions for the interface, not ad hoc ideas +# for using tolerances. Suppose the user wants to have more control over +# the tolerances used for each method - how do they specify it? It would +# probably be easiest for the user if they could pass tolerances into each +# method, but it's easiest for us if they can only set it as a property of +# the class. Perhaps a dictionary of tolerance settings? +# 5. I also envision that accuracy estimates should be reported to the user +# somehow. I think my preference would be to return a subclass of an array +# with an `error` attribute - yes, really. But this is unlikely to be +# popular, so what are other ideas? Again, we need a unified vision here, +# not just pointing out difficulties (not all errors are known or easy +# to estimate, what to do when errors could compound, etc.). +# 6. The term "method" is used to refer to public instance functions, +# private instance functions, the "method" string argument, and the means +# of calculating the desired quantity (represented by the string argument). +# For the sake of disambiguation, shall I rename the "method" string to +# "strategy" and refer to the means of calculating the quantity as the +# "strategy"? + +# Originally, I planned to filter out invalid distribution parameters; +# distribution implementation functions would always work with "compressed", +# 1D arrays containing only valid distribution parameters. There are two +# problems with this: +# - This essentially requires copying all arrays, even if there is only a +# single invalid parameter combination. This is expensive. Then, to output +# the original size data to the user, we need to "decompress" the arrays +# and fill in the NaNs, so more copying. Unless we branch the code when +# there are no invalid data, these copies happen even in the normal case, +# where there are no invalid parameter combinations. We should not incur +# all this overhead in the normal case. +# - For methods that accept arguments other than distribution parameters, the +# user will pass in arrays that are broadcastable with the original arrays, +# not the compressed arrays. This means that this same sort of invalid +# value detection needs to be repeated every time one of these methods is +# called. +# The much simpler solution is to keep the data uncompressed but to replace +# the invalid parameters and arguments with NaNs (and only if some are +# invalid). With this approach, the copying happens only if/when it is +# needed. Most functions involved in stats distribution calculations don't +# mind NaNs; they just return NaN. The behavior "If x_i is NaN, the result +# is NaN" is explicit in the array API. So this should be fine. +# +# Currently, I am still leaving the parameters and function arguments +# in their broadcasted shapes rather than, say, raveling. The intent +# is to avoid back and forth reshaping. If authors of distributions have +# trouble dealing with N-D arrays, we can reconsider this. +# +# Another important decision is that the *private* methods must accept +# the distribution parameters as inputs rather than relying on these +# cached properties directly (although the public methods typically pass +# the cached values to the private methods). This is because the elementwise +# algorithms for quadrature, differentiation, root-finding, and minimization +# prefer that the input functions are strictly elementwise in the sense +# that the value output for a given input element does not depend on the +# shape of the input or that element's location within the input array. +# When the computation has converged for an element, it is removed from +# the computation entirely. As a result, the shape of the arrays passed to +# the function will almost never be broadcastable with the shape of the +# cached parameter arrays. +# +# I've sprinkled in some optimizations for scalars and same-shape/type arrays +# throughout. The biggest time sinks before were: +# - broadcast_arrays +# - result_dtype +# - is_subdtype +# It is much faster to check whether these are necessary than to do them. + + +class _Domain(ABC): + r""" Representation of the applicable domain of a parameter or variable. + + A `_Domain` object is responsible for storing information about the + domain of a parameter or variable, determining whether a value is within + the domain (`contains`), and providing a text/mathematical representation + of itself (`__str__`). Because the domain of a parameter/variable can have + a complicated relationship with other parameters and variables of a + distribution, `_Domain` itself does not try to represent all possibilities; + in fact, it has no implementation and is meant for subclassing. + + Attributes + ---------- + symbols : dict + A map from special numerical values to symbols for use in `__str__` + + Methods + ------- + contains(x) + Determine whether the argument is contained within the domain (True) + or not (False). Used for input validation. + get_numerical_endpoints() + Gets the numerical values of the domain endpoints, which may have been + defined symbolically. + __str__() + Returns a text representation of the domain (e.g. ``[0, b)``). + Used for generating documentation. + + """ + symbols = {np.inf: r"\infty", -np.inf: r"-\infty", np.pi: r"\pi", -np.pi: r"-\pi"} + + @abstractmethod + def contains(self, x): + raise NotImplementedError() + + @abstractmethod + def draw(self, n): + raise NotImplementedError() + + @abstractmethod + def get_numerical_endpoints(self, x): + raise NotImplementedError() + + @abstractmethod + def __str__(self): + raise NotImplementedError() + + +class _SimpleDomain(_Domain): + r""" Representation of a simply-connected domain defined by two endpoints. + + Each endpoint may be a finite scalar, positive or negative infinity, or + be given by a single parameter. The domain may include the endpoints or + not. + + This class still does not provide an implementation of the __str__ method, + so it is meant for subclassing (e.g. a subclass for domains on the real + line). + + Attributes + ---------- + symbols : dict + Inherited. A map from special values to symbols for use in `__str__`. + endpoints : 2-tuple of float(s) and/or str(s) + A tuple with two values. Each may be either a float (the numerical + value of the endpoints of the domain) or a string (the name of the + parameters that will define the endpoint). + inclusive : 2-tuple of bools + A tuple with two boolean values; each indicates whether the + corresponding endpoint is included within the domain or not. + + Methods + ------- + define_parameters(*parameters) + Records any parameters used to define the endpoints of the domain + get_numerical_endpoints(parameter_values) + Gets the numerical values of the domain endpoints, which may have been + defined symbolically. + contains(item, parameter_values) + Determines whether the argument is contained within the domain + + """ + def __init__(self, endpoints=(-inf, inf), inclusive=(False, False)): + self.symbols = super().symbols.copy() + a, b = endpoints + self.endpoints = np.asarray(a)[()], np.asarray(b)[()] + self.inclusive = inclusive + + def define_parameters(self, *parameters): + r""" Records any parameters used to define the endpoints of the domain. + + Adds the keyword name of each parameter and its text representation + to the `symbols` attribute as key:value pairs. + For instance, a parameter may be passed into to a distribution's + initializer using the keyword `log_a`, and the corresponding + string representation may be '\log(a)'. To form the text + representation of the domain for use in documentation, the + _Domain object needs to map from the keyword name used in the code + to the string representation. + + Returns None, but updates the `symbols` attribute. + + Parameters + ---------- + *parameters : _Parameter objects + Parameters that may define the endpoints of the domain. + + """ + new_symbols = {param.name: param.symbol for param in parameters} + self.symbols.update(new_symbols) + + def get_numerical_endpoints(self, parameter_values): + r""" Get the numerical values of the domain endpoints. + + Domain endpoints may be defined symbolically. This returns numerical + values of the endpoints given numerical values for any variables. + + Parameters + ---------- + parameter_values : dict + A dictionary that maps between string variable names and numerical + values of parameters, which may define the endpoints. + + Returns + ------- + a, b : ndarray + Numerical values of the endpoints + + """ + # TODO: ensure outputs are floats + a, b = self.endpoints + # If `a` (`b`) is a string - the name of the parameter that defines + # the endpoint of the domain - then corresponding numerical values + # will be found in the `parameter_values` dictionary. Otherwise, it is + # itself the array of numerical values of the endpoint. + try: + a = np.asarray(parameter_values.get(a, a)) + b = np.asarray(parameter_values.get(b, b)) + except TypeError as e: + message = ("The endpoints of the distribution are defined by " + "parameters, but their values were not provided. When " + f"using a private method of {self.__class__}, pass " + "all required distribution parameters as keyword " + "arguments.") + raise TypeError(message) from e + + return a, b + + def contains(self, item, parameter_values=None): + r"""Determine whether the argument is contained within the domain. + + Parameters + ---------- + item : ndarray + The argument + parameter_values : dict + A dictionary that maps between string variable names and numerical + values of parameters, which may define the endpoints. + + Returns + ------- + out : bool + True if `item` is within the domain; False otherwise. + + """ + parameter_values = parameter_values or {} + # if self.all_inclusive: + # # Returning a 0d value here makes things much faster. + # # I'm not sure if it's safe, though. If it causes a bug someday, + # # I guess it wasn't. + # # Even if there is no bug because of the shape, it is incorrect for + # # `contains` to return True when there are invalid (e.g. NaN) + # # parameters. + # return np.asarray(True) + + a, b = self.get_numerical_endpoints(parameter_values) + left_inclusive, right_inclusive = self.inclusive + + in_left = item >= a if left_inclusive else item > a + in_right = item <= b if right_inclusive else item < b + return in_left & in_right + + +class _RealDomain(_SimpleDomain): + r""" Represents a simply-connected subset of the real line; i.e., an interval + + Completes the implementation of the `_SimpleDomain` class for simple + domains on the real line. + + Methods + ------- + define_parameters(*parameters) + (Inherited) Records any parameters used to define the endpoints of the + domain. + get_numerical_endpoints(parameter_values) + (Inherited) Gets the numerical values of the domain endpoints, which + may have been defined symbolically. + contains(item, parameter_values) + (Inherited) Determines whether the argument is contained within the + domain + __str__() + Returns a string representation of the domain, e.g. "[a, b)". + draw(size, rng, proportions, parameter_values) + Draws random values based on the domain. Proportions of values within + the domain, on the endpoints of the domain, outside the domain, + and having value NaN are specified by `proportions`. + + """ + + def __str__(self): + a, b = self.endpoints + left_inclusive, right_inclusive = self.inclusive + + left = "[" if left_inclusive else "(" + a = self.symbols.get(a, f"{a}") + right = "]" if right_inclusive else ")" + b = self.symbols.get(b, f"{b}") + + return f"{left}{a}, {b}{right}" + + def draw(self, n, type_, min, max, squeezed_base_shape, rng=None): + r""" Draw random values from the domain. + + Parameters + ---------- + n : int + The number of values to be drawn from the domain. + type_ : str + A string indicating whether the values are + + - strictly within the domain ('in'), + - at one of the two endpoints ('on'), + - strictly outside the domain ('out'), or + - NaN ('nan'). + min, max : ndarray + The endpoints of the domain. + squeezed_based_shape : tuple of ints + See _RealParameter.draw. + rng : np.Generator + The Generator used for drawing random values. + + """ + rng = np.random.default_rng(rng) + + # get copies of min and max with no nans so that uniform doesn't fail + min_nn, max_nn = min.copy(), max.copy() + i = np.isnan(min_nn) | np.isnan(max_nn) + min_nn[i] = 0 + max_nn[i] = 1 + + shape = (n,) + squeezed_base_shape + + if type_ == 'in': + z = rng.uniform(min_nn, max_nn, size=shape) + + elif type_ == 'on': + z_on_shape = shape + z = np.ones(z_on_shape) + i = rng.random(size=n) < 0.5 + z[i] = min + z[~i] = max + + elif type_ == 'out': + # make this work for infinite bounds + z = min_nn - rng.uniform(size=shape) + zr = max_nn + rng.uniform(size=shape) + i = rng.random(size=n) < 0.5 + z[i] = zr[i] + + elif type_ == 'nan': + z = np.full(shape, np.nan) + + return z + + +class _IntegerDomain(_SimpleDomain): + r""" Representation of a domain of consecutive integers. + + Completes the implementation of the `_SimpleDomain` class for domains + composed of consecutive integer values. + + To be completed when needed. + """ + def __init__(self): + raise NotImplementedError + + +class _Parameter(ABC): + r""" Representation of a distribution parameter or variable. + + A `_Parameter` object is responsible for storing information about a + parameter or variable, providing input validation/standardization of + values passed for that parameter, providing a text/mathematical + representation of the parameter for the documentation (`__str__`), and + drawing random values of itself for testing and benchmarking. It does + not provide a complete implementation of this functionality and is meant + for subclassing. + + Attributes + ---------- + name : str + The keyword used to pass numerical values of the parameter into the + initializer of the distribution + symbol : str + The text representation of the variable in the documentation. May + include LaTeX. + domain : _Domain + The domain of the parameter for which the distribution is valid. + typical : 2-tuple of floats or strings (consider making a _Domain) + Defines the endpoints of a typical range of values of the parameter. + Used for sampling. + + Methods + ------- + __str__(): + Returns a string description of the variable for use in documentation, + including the keyword used to represent it in code, the symbol used to + represent it mathemtatically, and a description of the valid domain. + draw(size, *, rng, domain, proportions) + Draws random values of the parameter. Proportions of values within + the valid domain, on the endpoints of the domain, outside the domain, + and having value NaN are specified by `proportions`. + validate(x): + Validates and standardizes the argument for use as numerical values + of the parameter. + + """ + def __init__(self, name, *, domain, symbol=None, typical=None): + self.name = name + self.symbol = symbol or name + self.domain = domain + if typical is not None and not isinstance(typical, _Domain): + typical = _RealDomain(typical) + self.typical = typical or domain + + def __str__(self): + r""" String representation of the parameter for use in documentation.""" + return f"`{self.name}` for :math:`{self.symbol} \\in {str(self.domain)}`" + + def draw(self, size=None, *, rng=None, region='domain', proportions=None, + parameter_values=None): + r""" Draw random values of the parameter for use in testing. + + Parameters + ---------- + size : tuple of ints + The shape of the array of valid values to be drawn. + rng : np.Generator + The Generator used for drawing random values. + region : str + The region of the `_Parameter` from which to draw. Default is + "domain" (the *full* domain); alternative is "typical". An + enhancement would give a way to interpolate between the two. + proportions : tuple of numbers + A tuple of four non-negative numbers that indicate the expected + relative proportion of elements that: + + - are strictly within the domain, + - are at one of the two endpoints, + - are strictly outside the domain, and + - are NaN, + + respectively. Default is (1, 0, 0, 0). The number of elements in + each category is drawn from the multinomial distribution with + `np.prod(size)` as the number of trials and `proportions` as the + event probabilities. The values in `proportions` are automatically + normalized to sum to 1. + parameter_values : dict + Map between the names of parameters (that define the endpoints of + `typical`) and numerical values (arrays). + + """ + parameter_values = parameter_values or {} + domain = self.domain + proportions = (1, 0, 0, 0) if proportions is None else proportions + + pvals = proportions / np.sum(proportions) + + a, b = domain.get_numerical_endpoints(parameter_values) + a, b = np.broadcast_arrays(a, b) + + base_shape = a.shape + extended_shape = np.broadcast_shapes(size, base_shape) + n_extended = np.prod(extended_shape) + n_base = np.prod(base_shape) + n = int(n_extended / n_base) if n_extended else 0 + + rng = np.random.default_rng(rng) + n_in, n_on, n_out, n_nan = rng.multinomial(n, pvals) + + # `min` and `max` can have singleton dimensions that correspond with + # non-singleton dimensions in `size`. We need to be careful to avoid + # shuffling results (e.g. a value that was generated for the domain + # [min[i], max[i]] ends up at index j). To avoid this: + # - Squeeze the singleton dimensions out of `min`/`max`. Squeezing is + # often not the right thing to do, but here is equivalent to moving + # all the dimensions that are singleton in `min`/`max` (which may be + # non-singleton in the result) to the left. This is what we want. + # - Now all the non-singleton dimensions of the result are on the left. + # Ravel them to a single dimension of length `n`, which is now along + # the 0th axis. + # - Reshape the 0th axis back to the required dimensions, and move + # these axes back to their original places. + base_shape_padded = ((1,)*(len(extended_shape) - len(base_shape)) + + base_shape) + base_singletons = np.where(np.asarray(base_shape_padded)==1)[0] + new_base_singletons = tuple(range(len(base_singletons))) + # Base singleton dimensions are going to get expanded to these lengths + shape_expansion = np.asarray(extended_shape)[base_singletons] + + # assert(np.prod(shape_expansion) == n) # check understanding + # min = np.reshape(min, base_shape_padded) + # max = np.reshape(max, base_shape_padded) + # min = np.moveaxis(min, base_singletons, new_base_singletons) + # max = np.moveaxis(max, base_singletons, new_base_singletons) + # squeezed_base_shape = max.shape[len(base_singletons):] + # assert np.all(min.reshape(squeezed_base_shape) == min.squeeze()) + # assert np.all(max.reshape(squeezed_base_shape) == max.squeeze()) + + # min = np.maximum(a, _fiinfo(a).min/10) if np.any(np.isinf(a)) else a + # max = np.minimum(b, _fiinfo(b).max/10) if np.any(np.isinf(b)) else b + min = np.asarray(a.squeeze()) + max = np.asarray(b.squeeze()) + squeezed_base_shape = max.shape + + if region == 'typical': + typical = self.typical + a, b = typical.get_numerical_endpoints(parameter_values) + a, b = np.broadcast_arrays(a, b) + min_here = np.asarray(a.squeeze()) + max_here = np.asarray(b.squeeze()) + z_in = typical.draw(n_in, 'in', min_here, max_here, squeezed_base_shape, + rng=rng) + else: + z_in = domain.draw(n_in, 'in', min, max, squeezed_base_shape, rng=rng) + z_on = domain.draw(n_on, 'on', min, max, squeezed_base_shape, rng=rng) + z_out = domain.draw(n_out, 'out', min, max, squeezed_base_shape, rng=rng) + z_nan= domain.draw(n_nan, 'nan', min, max, squeezed_base_shape, rng=rng) + + z = np.concatenate((z_in, z_on, z_out, z_nan), axis=0) + z = rng.permuted(z, axis=0) + + z = np.reshape(z, tuple(shape_expansion) + squeezed_base_shape) + z = np.moveaxis(z, new_base_singletons, base_singletons) + return z + + @abstractmethod + def validate(self, arr): + raise NotImplementedError() + + +class _RealParameter(_Parameter): + r""" Represents a real-valued parameter. + + Implements the remaining methods of _Parameter for real parameters. + All attributes are inherited. + + """ + def validate(self, arr, parameter_values): + r""" Input validation/standardization of numerical values of a parameter. + + Checks whether elements of the argument `arr` are reals, ensuring that + the dtype reflects this. Also produces a logical array that indicates + which elements meet the requirements. + + Parameters + ---------- + arr : ndarray + The argument array to be validated and standardized. + parameter_values : dict + Map of parameter names to parameter value arrays. + + Returns + ------- + arr : ndarray + The argument array that has been validated and standardized + (converted to an appropriate dtype, if necessary). + dtype : NumPy dtype + The appropriate floating point dtype of the parameter. + valid : boolean ndarray + Logical array indicating which elements are valid (True) and + which are not (False). The arrays of all distribution parameters + will be broadcasted, and elements for which any parameter value + does not meet the requirements will be replaced with NaN. + + """ + arr = np.asarray(arr) + + valid_dtype = None + # minor optimization - fast track the most common types to avoid + # overhead of np.issubdtype. Checking for `in {...}` doesn't work : / + if arr.dtype == np.float64 or arr.dtype == np.float32: + pass + elif arr.dtype == np.int32 or arr.dtype == np.int64: + arr = np.asarray(arr, dtype=np.float64) + elif np.issubdtype(arr.dtype, np.floating): + pass + elif np.issubdtype(arr.dtype, np.integer): + arr = np.asarray(arr, dtype=np.float64) + else: + message = f"Parameter `{self.name}` must be of real dtype." + raise TypeError(message) + + valid = self.domain.contains(arr, parameter_values) + valid = valid & valid_dtype if valid_dtype is not None else valid + + return arr[()], arr.dtype, valid + + +class _Parameterization: + r""" Represents a parameterization of a distribution. + + Distributions can have multiple parameterizations. A `_Parameterization` + object is responsible for recording the parameters used by the + parameterization, checking whether keyword arguments passed to the + distribution match the parameterization, and performing input validation + of the numerical values of these parameters. + + Attributes + ---------- + parameters : dict + String names (of keyword arguments) and the corresponding _Parameters. + + Methods + ------- + __len__() + Returns the number of parameters in the parameterization. + __str__() + Returns a string representation of the parameterization. + copy + Returns a copy of the parameterization. This is needed for transformed + distributions that add parameters to the parameterization. + matches(parameters) + Checks whether the keyword arguments match the parameterization. + validation(parameter_values) + Input validation / standardization of parameterization. Validates the + numerical values of all parameters. + draw(sizes, rng, proportions) + Draw random values of all parameters of the parameterization for use + in testing. + """ + def __init__(self, *parameters): + self.parameters = {param.name: param for param in parameters} + + def __len__(self): + return len(self.parameters) + + def copy(self): + return _Parameterization(*self.parameters.values()) + + def matches(self, parameters): + r""" Checks whether the keyword arguments match the parameterization. + + Parameters + ---------- + parameters : set + Set of names of parameters passed into the distribution as keyword + arguments. + + Returns + ------- + out : bool + True if the keyword arguments names match the names of the + parameters of this parameterization. + """ + return parameters == set(self.parameters.keys()) + + def validation(self, parameter_values): + r""" Input validation / standardization of parameterization. + + Parameters + ---------- + parameter_values : dict + The keyword arguments passed as parameter values to the + distribution. + + Returns + ------- + all_valid : ndarray + Logical array indicating the elements of the broadcasted arrays + for which all parameter values are valid. + dtype : dtype + The common dtype of the parameter arrays. This will determine + the dtype of the output of distribution methods. + """ + all_valid = True + dtypes = set() # avoid np.result_type if there's only one type + for name, arr in parameter_values.items(): + parameter = self.parameters[name] + arr, dtype, valid = parameter.validate(arr, parameter_values) + dtypes.add(dtype) + all_valid = all_valid & valid + parameter_values[name] = arr + dtype = arr.dtype if len(dtypes)==1 else np.result_type(*list(dtypes)) + + return all_valid, dtype + + def __str__(self): + r"""Returns a string representation of the parameterization.""" + messages = [str(param) for name, param in self.parameters.items()] + return ", ".join(messages) + + def draw(self, sizes=None, rng=None, proportions=None, region='domain'): + r"""Draw random values of all parameters for use in testing. + + Parameters + ---------- + sizes : iterable of shape tuples + The size of the array to be generated for each parameter in the + parameterization. Note that the order of sizes is arbitary; the + size of the array generated for a specific parameter is not + controlled individually as written. + rng : NumPy Generator + The generator used to draw random values. + proportions : tuple + A tuple of four non-negative numbers that indicate the expected + relative proportion of elements that are within the parameter's + domain, are on the boundary of the parameter's domain, are outside + the parameter's domain, and have value NaN. For more information, + see the `draw` method of the _Parameter subclasses. + domain : str + The domain of the `_Parameter` from which to draw. Default is + "domain" (the *full* domain); alternative is "typical". + + Returns + ------- + parameter_values : dict (string: array) + A dictionary of parameter name/value pairs. + """ + # ENH: be smart about the order. The domains of some parameters + # depend on others. If the relationshp is simple (e.g. a < b < c), + # we can draw values in order a, b, c. + parameter_values = {} + + if not len(sizes) or not np.iterable(sizes[0]): + sizes = [sizes]*len(self.parameters) + + for size, param in zip(sizes, self.parameters.values()): + parameter_values[param.name] = param.draw( + size, rng=rng, proportions=proportions, + parameter_values=parameter_values, + region=region + ) + + return parameter_values + + +def _set_invalid_nan(f): + # Wrapper for input / output validation and standardization of distribution + # functions that accept either the quantile or percentile as an argument: + # logpdf, pdf + # logcdf, cdf + # logccdf, ccdf + # ilogcdf, icdf + # ilogccdf, iccdf + # Arguments that are outside the required range are replaced by NaN before + # passing them into the underlying function. The corresponding outputs + # are replaced by the appropriate value before being returned to the user. + # For example, when the argument of `cdf` exceeds the right end of the + # distribution's support, the wrapper replaces the argument with NaN, + # ignores the output of the underlying function, and returns 1.0. It also + # ensures that output is of the appropriate shape and dtype. + + endpoints = {'icdf': (0, 1), 'iccdf': (0, 1), + 'ilogcdf': (-np.inf, 0), 'ilogccdf': (-np.inf, 0)} + replacements = {'logpdf': (-inf, -inf), 'pdf': (0, 0), + '_logcdf1': (-inf, 0), '_logccdf1': (0, -inf), + '_cdf1': (0, 1), '_ccdf1': (1, 0)} + replace_strict = {'pdf', 'logpdf'} + replace_exact = {'icdf', 'iccdf', 'ilogcdf', 'ilogccdf'} + clip = {'_cdf1', '_ccdf1'} + clip_log = {'_logcdf1', '_logccdf1'} + + @functools.wraps(f) + def filtered(self, x, *args, **kwargs): + if self.validation_policy == _SKIP_ALL: + return f(self, x, *args, **kwargs) + + method_name = f.__name__ + x = np.asarray(x) + dtype = self._dtype + shape = self._shape + + # Ensure that argument is at least as precise as distribution + # parameters, which are already at least floats. This will avoid issues + # with raising integers to negative integer powers and failure to replace + # invalid integers with NaNs. + if x.dtype != dtype: + dtype = np.result_type(x.dtype, dtype) + x = np.asarray(x, dtype=dtype) + + # Broadcasting is slow. Do it only if necessary. + if not x.shape == shape: + try: + shape = np.broadcast_shapes(x.shape, shape) + x = np.broadcast_to(x, shape) + # Should we broadcast the distribution parameters to this shape, too? + except ValueError as e: + message = ( + f"The argument provided to `{self.__class__.__name__}" + f".{method_name}` cannot be be broadcast to the same " + "shape as the distribution parameters.") + raise ValueError(message) from e + + low, high = endpoints.get(method_name, self.support()) + + # Check for arguments outside of domain. They'll be replaced with NaNs, + # and the result will be set to the appropriate value. + left_inc, right_inc = self._variable.domain.inclusive + mask_low = (x < low if (method_name in replace_strict and left_inc) + else x <= low) + mask_high = (x > high if (method_name in replace_strict and right_inc) + else x >= high) + mask_invalid = (mask_low | mask_high) + any_invalid = (mask_invalid if mask_invalid.shape == () + else np.any(mask_invalid)) + + # Check for arguments at domain endpoints, whether they + # are part of the domain or not. + any_endpoint = False + if method_name in replace_exact: + mask_low_endpoint = (x == low) + mask_high_endpoint = (x == high) + mask_endpoint = (mask_low_endpoint | mask_high_endpoint) + any_endpoint = (mask_endpoint if mask_endpoint.shape == () + else np.any(mask_endpoint)) + + # Set out-of-domain arguments to NaN. The result will be set to the + # appropriate value later. + if any_invalid: + x = np.array(x, dtype=dtype, copy=True) + x[mask_invalid] = np.nan + + res = np.asarray(f(self, x, *args, **kwargs)) + + # Ensure that the result is the correct dtype and shape, + # copying (only once) if necessary. + res_needs_copy = False + if res.dtype != dtype: + dtype = np.result_type(dtype, self._dtype) + res_needs_copy = True + + if res.shape != shape: # faster to check first + res = np.broadcast_to(res, self._shape) + res_needs_copy = res_needs_copy or any_invalid or any_endpoint + + if res_needs_copy: + res = np.array(res, dtype=dtype, copy=True) + + # For arguments outside the function domain, replace results + if any_invalid: + replace_low, replace_high = ( + replacements.get(method_name, (np.nan, np.nan))) + res[mask_low] = replace_low + res[mask_high] = replace_high + + # For arguments at the endpoints of the domain, replace results + if any_endpoint: + a, b = self.support() + if a.shape != shape: + a = np.array(np.broadcast_to(a, shape), copy=True) + b = np.array(np.broadcast_to(b, shape), copy=True) + + replace_low_endpoint = ( + b[mask_low_endpoint] if method_name.endswith('ccdf') + else a[mask_low_endpoint]) + replace_high_endpoint = ( + a[mask_high_endpoint] if method_name.endswith('ccdf') + else b[mask_high_endpoint]) + + res[mask_low_endpoint] = replace_low_endpoint + res[mask_high_endpoint] = replace_high_endpoint + + # Clip probabilities to [0, 1] + if method_name in clip: + res = np.clip(res, 0., 1.) + elif method_name in clip_log: + res = res.real # exp(res) > 0 + res = np.clip(res, None, 0.) # exp(res) < 1 + + return res[()] + + return filtered + + +def _set_invalid_nan_property(f): + # Wrapper for input / output validation and standardization of distribution + # functions that represent properties of the distribution itself: + # logentropy, entropy + # median, mode + # moment + # It ensures that the output is of the correct shape and dtype and that + # there are NaNs wherever the distribution parameters were invalid. + + @functools.wraps(f) + def filtered(self, *args, **kwargs): + if self.validation_policy == _SKIP_ALL: + return f(self, *args, **kwargs) + + res = f(self, *args, **kwargs) + if res is None: + # message could be more appropriate + raise NotImplementedError(self._not_implemented) + + res = np.asarray(res) + needs_copy = False + dtype = res.dtype + + if dtype != self._dtype: # this won't work for logmoments (complex) + dtype = np.result_type(dtype, self._dtype) + needs_copy = True + + if res.shape != self._shape: # faster to check first + res = np.broadcast_to(res, self._shape) + needs_copy = needs_copy or self._any_invalid + + if needs_copy: + res = res.astype(dtype=dtype, copy=True) + + if self._any_invalid: + # may be redundant when quadrature is used, but not necessarily + # when formulas are used. + res[self._invalid] = np.nan + + return res[()] + + return filtered + + +def _dispatch(f): + # For each public method (instance function) of a distribution (e.g. ccdf), + # there may be several ways ("method"s) that it can be computed (e.g. a + # formula, as the complement of the CDF, or via numerical integration). + # Each "method" is implemented by a different private method (instance + # function). + # This wrapper calls the appropriate private method based on the public + # method and any specified `method` keyword option. + # - If `method` is specified as a string (by the user), the appropriate + # private method is called. + # - If `method` is None: + # - The appropriate private method for the public method is looked up + # in a cache. + # - If the cache does not have an entry for the public method, the + # appropriate "dispatch " function is called to determine which method + # is most appropriate given the available private methods and + # settings (e.g. tolerance). + + @functools.wraps(f) + def wrapped(self, *args, method=None, **kwargs): + func_name = f.__name__ + method = method or self._method_cache.get(func_name, None) + if callable(method): + pass + elif method is not None: + method = 'logexp' if method == 'log/exp' else method + method_name = func_name.replace('dispatch', method) + method = getattr(self, method_name) + else: + method = f(self, *args, method=method, **kwargs) + if func_name != '_sample_dispatch' and self.cache_policy != _NO_CACHE: + self._method_cache[func_name] = method + + try: + return method(*args, **kwargs) + except KeyError as e: + raise NotImplementedError(self._not_implemented) from e + + return wrapped + + +def _cdf2_input_validation(f): + # Wrapper that does the job of `_set_invalid_nan` when `cdf` or `logcdf` + # is called with two quantile arguments. + # Let's keep it simple; no special cases for speed right now. + # The strategy is a bit different than for 1-arg `cdf` (and other methods + # covered by `_set_invalid_nan`). For 1-arg `cdf`, elements of `x` that + # are outside (or at the edge of) the support get replaced by `nan`, + # and then the results get replaced by the appropriate value (0 or 1). + # We *could* do something similar, dispatching to `_cdf1` in these + # cases. That would be a bit more robust, but it would also be quite + # a bit more complex, since we'd have to do different things when + # `x` and `y` are both out of bounds, when just `x` is out of bounds, + # when just `y` is out of bounds, and when both are out of bounds. + # I'm not going to do that right now. Instead, simply replace values + # outside the support by those at the edge of the support. Here, we also + # omit some of the optimizations that make `_set_invalid_nan` faster for + # simple arguments (e.g. float64 scalars). + + @functools.wraps(f) + def wrapped(self, x, y, *args, **kwargs): + func_name = f.__name__ + + low, high = self.support() + x, y, low, high = np.broadcast_arrays(x, y, low, high) + dtype = np.result_type(x.dtype, y.dtype, self._dtype) + # yes, copy to avoid modifying input arrays + x, y = x.astype(dtype, copy=True), y.astype(dtype, copy=True) + + # Swap arguments to ensure that x < y, and replace + # out-of domain arguments with domain endpoints. We'll + # transform the result later. + i_swap = y < x + x[i_swap], y[i_swap] = y[i_swap], x[i_swap] + i = x < low + x[i] = low[i] + i = y < low + y[i] = low[i] + i = x > high + x[i] = high[i] + i = y > high + y[i] = high[i] + + res = f(self, x, y, *args, **kwargs) + + # Clipping probability to [0, 1] + if func_name in {'_cdf2', '_ccdf2'}: + res = np.clip(res, 0., 1.) + else: + res = np.clip(res, None, 0.) # exp(res) < 1 + + # Transform the result to account for swapped argument order + res = np.asarray(res) + if func_name == '_cdf2': + res[i_swap] *= -1. + elif func_name == '_ccdf2': + res[i_swap] *= -1 + res[i_swap] += 2. + elif func_name == '_logcdf2': + res = np.asarray(res + 0j) if np.any(i_swap) else res + res[i_swap] = res[i_swap] + np.pi*1j + else: + # res[i_swap] is always positive and less than 1, so it's + # safe to ensure that the result is real + res[i_swap] = _logexpxmexpy(np.log(2), res[i_swap]).real + return res[()] + + return wrapped + + +def _fiinfo(x): + if np.issubdtype(x.dtype, np.inexact): + return np.finfo(x.dtype) + else: + return np.iinfo(x) + + +def _kwargs2args(f, args=None, kwargs=None): + # Wraps a function that accepts a primary argument `x`, secondary + # arguments `args`, and secondary keyward arguments `kwargs` such that the + # wrapper accepts only `x` and `args`. The keyword arguments are extracted + # from `args` passed into the wrapper, and these are passed to the + # underlying function as `kwargs`. + # This is a temporary workaround until the scalar algorithms `_tanhsinh`, + # `_chandrupatla`, etc., support `kwargs` or can operate with compressing + # arguments to the callable. + args = args or [] + kwargs = kwargs or {} + names = list(kwargs.keys()) + n_args = len(args) + + def wrapped(x, *args): + return f(x, *args[:n_args], **dict(zip(names, args[n_args:]))) + + args = list(args) + list(kwargs.values()) + + return wrapped, args + + +def _log1mexp(x): + r"""Compute the log of the complement of the exponential. + + This function is equivalent to:: + + log1mexp(x) = np.log(1-np.exp(x)) + + but avoids loss of precision when ``np.exp(x)`` is nearly 0 or 1. + + Parameters + ---------- + x : array_like + Input array. + + Returns + ------- + y : ndarray + An array of the same shape as `x`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats._distribution_infrastructure import _log1mexp + >>> x = 1e-300 # log of a number very close to 1 + >>> _log1mexp(x) # log of the complement of a number very close to 1 + -690.7755278982137 + >>> # np.log1p(-np.exp(x)) # -inf; emits warning + + """ + def f1(x): + # good for exp(x) close to 0 + return np.log1p(-np.exp(x)) + + def f2(x): + # good for exp(x) close to 1 + with np.errstate(divide='ignore'): + return np.real(np.log(-special.expm1(x + 0j))) + + return _lazywhere(x < -1, (x,), f=f1, f2=f2)[()] + + +def _logexpxmexpy(x, y): + """ Compute the log of the difference of the exponentials of two arguments. + + Avoids over/underflow, but does not prevent loss of precision otherwise. + """ + # TODO: properly avoid NaN when y is negative infinity + # TODO: silence warning with taking log of complex nan + # TODO: deal with x == y better + i = np.isneginf(np.real(y)) + if np.any(i): + y = np.asarray(y.copy()) + y[i] = np.finfo(y.dtype).min + x, y = np.broadcast_arrays(x, y) + res = np.asarray(special.logsumexp([x, y+np.pi*1j], axis=0)) + i = (x == y) + res[i] = -np.inf + return res + + +def _guess_bracket(xmin, xmax): + a = np.full_like(xmin, -1.0) + b = np.ones_like(xmax) + + i = np.isfinite(xmin) & np.isfinite(xmax) + a[i] = xmin[i] + b[i] = xmax[i] + + i = np.isfinite(xmin) & ~np.isfinite(xmax) + a[i] = xmin[i] + b[i] = xmin[i] + 1 + + i = np.isfinite(xmax) & ~np.isfinite(xmin) + a[i] = xmax[i] - 1 + b[i] = xmax[i] + + return a, b + + +def _log_real_standardize(x): + """Standardizes the (complex) logarithm of a real number. + + The logarithm of a real number may be represented by a complex number with + imaginary part that is a multiple of pi*1j. Even multiples correspond with + a positive real and odd multiples correspond with a negative real. + + Given a logarithm of a real number `x`, this function returns an equivalent + representation in a standard form: the log of a positive real has imaginary + part `0` and the log of a negative real has imaginary part `pi`. + + """ + shape = x.shape + x = np.atleast_1d(x) + real = np.real(x).astype(x.dtype) + complex = np.imag(x) + y = real + negative = np.exp(complex*1j) < 0.5 + y[negative] = y[negative] + np.pi * 1j + return y.reshape(shape)[()] + + +def _combine_docs(dist_family, *, include_examples=True): + fields = set(NumpyDocString.sections) + fields.remove('index') + if not include_examples: + fields.remove('Examples') + + doc = ClassDoc(dist_family) + superdoc = ClassDoc(ContinuousDistribution) + for field in fields: + if field in {"Methods", "Attributes"}: + doc[field] = superdoc[field] + elif field in {"Summary"}: + pass + elif field == "Extended Summary": + doc[field].append(_generate_domain_support(dist_family)) + elif field == 'Examples': + doc[field] = [_generate_example(dist_family)] + else: + doc[field] += superdoc[field] + return str(doc) + + +def _generate_domain_support(dist_family): + n_parameterizations = len(dist_family._parameterizations) + + domain = f"\nfor :math:`x` in {dist_family._variable.domain}.\n" + + if n_parameterizations == 0: + support = """ + This class accepts no distribution parameters. + """ + elif n_parameterizations == 1: + support = f""" + This class accepts one parameterization: + {str(dist_family._parameterizations[0])}. + """ + else: + number = {2: 'two', 3: 'three', 4: 'four', 5: 'five'}[ + n_parameterizations] + parameterizations = [f"- {str(p)}" for p in + dist_family._parameterizations] + parameterizations = "\n".join(parameterizations) + support = f""" + This class accepts {number} parameterizations: + + {parameterizations} + """ + support = "\n".join([line.lstrip() for line in support.split("\n")][1:]) + return domain + support + + +def _generate_example(dist_family): + n_parameters = dist_family._num_parameters(0) + shapes = [()] * n_parameters + rng = np.random.default_rng(615681484984984) + i = 0 + dist = dist_family._draw(shapes, rng=rng, i_parameterization=i) + + rng = np.random.default_rng(2354873452) + name = dist_family.__name__ + if n_parameters: + parameter_names = list(dist._parameterizations[i].parameters) + parameter_values = [round(getattr(dist, name), 2) for name in + parameter_names] + name_values = [f"{name}={value}" for name, value in + zip(parameter_names, parameter_values)] + instantiation = f"{name}({', '.join(name_values)})" + attributes = ", ".join([f"X.{param}" for param in dist._parameters]) + X = dist_family(**dict(zip(parameter_names, parameter_values))) + else: + instantiation = f"{name}()" + X = dist + + p = 0.32 + x = round(X.icdf(p), 2) + y = round(X.icdf(2 * p), 2) + + example = f""" + To use the distribution class, it must be instantiated using keyword + parameters corresponding with one of the accepted parameterizations. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> from scipy.stats import {name} + >>> X = {instantiation} + + For convenience, the ``plot`` method can be used to visualize the density + and other functions of the distribution. + + >>> X.plot() + >>> plt.show() + + The support of the underlying distribution is available using the ``support`` + method. + + >>> X.support() + {X.support()} + """ + + if n_parameters: + example += f""" + The numerical values of parameters associated with all parameterizations + are available as attributes. + + >>> {attributes} + {tuple(X._parameters.values())} + """ + + example += f""" + To evaluate the probability density function of the underlying distribution + at argument ``x={x}``: + + >>> x = {x} + >>> X.pdf(x) + {X.pdf(x)} + + The cumulative distribution function, its complement, and the logarithm + of these functions are evaluated similarly. + + >>> np.allclose(np.exp(X.logccdf(x)), 1 - X.cdf(x)) + True + + The inverse of these functions with respect to the argument ``x`` is also + available. + + >>> logp = np.log(1 - X.ccdf(x)) + >>> np.allclose(X.ilogcdf(logp), x) + True + + Note that distribution functions and their logarithms also have two-argument + versions for working with the probability mass between two arguments. The + result tends to be more accurate than the naive implementation because it avoids + subtractive cancellation. + + >>> y = {y} + >>> np.allclose(X.ccdf(x, y), 1 - (X.cdf(y) - X.cdf(x))) + True + + There are methods for computing measures of central tendency, + dispersion, higher moments, and entropy. + + >>> X.mean(), X.median(), X.mode() + {X.mean(), X.median(), X.mode()} + >>> X.variance(), X.standard_deviation() + {X.variance(), X.standard_deviation()} + >>> X.skewness(), X.kurtosis() + {X.skewness(), X.kurtosis()} + >>> np.allclose(X.moment(order=6, kind='standardized'), + ... X.moment(order=6, kind='central') / X.variance()**3) + True + >>> np.allclose(np.exp(X.logentropy()), X.entropy()) + True + + Pseudo-random samples can be drawn from + the underlying distribution using ``sample``. + + >>> X.sample(shape=(4,)) + {repr(X.sample(shape=(4,)))} # may vary + """ + # remove the indentation due to use of block quote within function; + # eliminate blank first line + example = "\n".join([line.lstrip() for line in example.split("\n")][1:]) + return example + + +class ContinuousDistribution(_ProbabilityDistribution): + r""" Class that represents a continuous statistical distribution. + + Parameters + ---------- + tol : positive float, optional + The desired relative tolerance of calculations. Left unspecified, + calculations may be faster; when provided, calculations may be + more likely to meet the desired accuracy. + validation_policy : {None, "skip_all"} + Specifies the level of input validation to perform. Left unspecified, + input validation is performed to ensure appropriate behavior in edge + case (e.g. parameters out of domain, argument outside of distribution + support, etc.) and improve consistency of output dtype, shape, etc. + Pass ``'skip_all'`` to avoid the computational overhead of these + checks when rough edges are acceptable. + cache_policy : {None, "no_cache"} + Specifies the extent to which intermediate results are cached. Left + unspecified, intermediate results of some calculations (e.g. distribution + support, moments, etc.) are cached to improve performance of future + calculations. Pass ``'no_cache'`` to reduce memory reserved by the class + instance. + + Attributes + ---------- + All parameters are available as attributes. + + Methods + ------- + support + + plot + + sample + + moment + + mean + median + mode + + variance + standard_deviation + + skewness + kurtosis + + pdf + logpdf + + cdf + icdf + ccdf + iccdf + + logcdf + ilogcdf + logccdf + ilogccdf + + entropy + logentropy + + See Also + -------- + :ref:`rv_infrastructure` : Tutorial + + Notes + ----- + The following abbreviations are used throughout the documentation. + + - PDF: probability density function + - CDF: cumulative distribution function + - CCDF: complementary CDF + - entropy: differential entropy + - log-*F*: logarithm of *F* (e.g. log-CDF) + - inverse *F*: inverse function of *F* (e.g. inverse CDF) + + The API documentation is written to describe the API, not to serve as + a statistical reference. Effort is made to be correct at the level + required to use the functionality, not to be mathematically rigorous. + For example, continuity and differentiability may be implicitly assumed. + For precise mathematical definitions, consult your preferred mathematical + text. + + """ + __array_priority__ = 1 + _parameterizations = [] # type: ignore[var-annotated] + + ### Initialization + + def __init__(self, *, tol=_null, validation_policy=None, cache_policy=None, + **parameters): + self.tol = tol + self.validation_policy = validation_policy + self.cache_policy = cache_policy + self._not_implemented = ( + f"`{self.__class__.__name__}` does not provide an accurate " + "implementation of the required method. Consider leaving " + "`method` and `tol` unspecified to use another implementation." + ) + self._original_parameters = {} + # We may want to override the `__init__` method with parameters so + # IDEs can suggest parameter names. If there are multiple parameterizations, + # we'll need the default values of parameters to be None; this will + # filter out the parameters that were not actually specified by the user. + parameters = {key: val for key, val in + sorted(parameters.items()) if val is not None} + self._update_parameters(**parameters) + + def _update_parameters(self, *, validation_policy=None, **params): + r""" Update the numerical values of distribution parameters. + + Parameters + ---------- + **params : array_like + Desired numerical values of the distribution parameters. Any or all + of the parameters initially used to instantiate the distribution + may be modified. Parameters used in alternative parameterizations + are not accepted. + + validation_policy : str + To be documented. See Question 3 at the top. + """ + + parameters = original_parameters = self._original_parameters.copy() + parameters.update(**params) + parameterization = None + self._invalid = np.asarray(False) + self._any_invalid = False + self._shape = tuple() + self._ndim = 0 + self._size = 1 + self._dtype = np.float64 + + if (validation_policy or self.validation_policy) == _SKIP_ALL: + parameters = self._process_parameters(**parameters) + elif not len(self._parameterizations): + if parameters: + message = (f"The `{self.__class__.__name__}` distribution " + "family does not accept parameters, but parameters " + f"`{set(parameters)}` were provided.") + raise ValueError(message) + else: + # This is default behavior, which re-runs all parameter validations + # even when only a single parameter is modified. For many + # distributions, the domain of a parameter doesn't depend on other + # parameters, so parameters could safely be modified without + # re-validating all other parameters. To handle these cases more + # efficiently, we could allow the developer to override this + # behavior. + + # Currently the user can only update the original parameterization. + # Even though that parameterization is already known, + # `_identify_parameterization` is called to produce a nice error + # message if the user passes other values. To be a little more + # efficient, we could detect whether the values passed are + # consistent with the original parameterization rather than finding + # it from scratch. However, we might want other parameterizations + # to be accepted, which would require other changes, so I didn't + # optimize this. + + parameterization = self._identify_parameterization(parameters) + parameters, shape, size, ndim = self._broadcast(parameters) + parameters, invalid, any_invalid, dtype = ( + self._validate(parameterization, parameters)) + parameters = self._process_parameters(**parameters) + + self._invalid = invalid + self._any_invalid = any_invalid + self._shape = shape + self._size = size + self._ndim = ndim + self._dtype = dtype + + self.reset_cache() + self._parameters = parameters + self._parameterization = parameterization + self._original_parameters = original_parameters + for name in self._parameters.keys(): + # Make parameters properties of the class; return values from the instance + if hasattr(self.__class__, name): + continue + setattr(self.__class__, name, property(lambda self_, name_=name: + self_._parameters[name_].copy()[()])) + + def reset_cache(self): + r""" Clear all cached values. + + To improve the speed of some calculations, the distribution's support + and moments are cached. + + This function is called automatically whenever the distribution + parameters are updated. + + """ + # We could offer finer control over what is cleared. + # For simplicity, these will still exist even if cache_policy is + # NO_CACHE; they just won't be populated. This allows caching to be + # turned on and off easily. + self._moment_raw_cache = {} + self._moment_central_cache = {} + self._moment_standardized_cache = {} + self._support_cache = None + self._method_cache = {} + self._constant_cache = None + + def _identify_parameterization(self, parameters): + # Determine whether a `parameters` dictionary matches is consistent + # with one of the parameterizations of the distribution. If so, + # return that parameterization object; if not, raise an error. + # + # I've come back to this a few times wanting to avoid this explicit + # loop. I've considered several possibilities, but they've all been a + # little unusual. For example, we could override `_eq_` so we can + # use _parameterizations.index() to retrieve the parameterization, + # or the user could put the parameterizations in a dictionary so we + # could look them up with a key (e.g. frozenset of parameter names). + # I haven't been sure enough of these approaches to implement them. + parameter_names_set = set(parameters) + + for parameterization in self._parameterizations: + if parameterization.matches(parameter_names_set): + break + else: + if not parameter_names_set: + message = (f"The `{self.__class__.__name__}` distribution " + "family requires parameters, but none were " + "provided.") + else: + parameter_names = self._get_parameter_str(parameters) + message = (f"The provided parameters `{parameter_names}` " + "do not match a supported parameterization of the " + f"`{self.__class__.__name__}` distribution family.") + raise ValueError(message) + + return parameterization + + def _broadcast(self, parameters): + # Broadcast the distribution parameters to the same shape. If the + # arrays are not broadcastable, raise a meaningful error. + # + # We always make sure that the parameters *are* the same shape + # and not just broadcastable. Users can access parameters as + # attributes, and I think they should see the arrays as the same shape. + # More importantly, arrays should be the same shape before logical + # indexing operations, which are needed in infrastructure code when + # there are invalid parameters, and may be needed in + # distribution-specific code. We don't want developers to need to + # broadcast in implementation functions. + + # It's much faster to check whether broadcasting is necessary than to + # broadcast when it's not necessary. + parameter_vals = [np.asarray(parameter) + for parameter in parameters.values()] + parameter_shapes = set(parameter.shape for parameter in parameter_vals) + if len(parameter_shapes) == 1: + return (parameters, parameter_vals[0].shape, + parameter_vals[0].size, parameter_vals[0].ndim) + + try: + parameter_vals = np.broadcast_arrays(*parameter_vals) + except ValueError as e: + parameter_names = self._get_parameter_str(parameters) + message = (f"The parameters `{parameter_names}` provided to the " + f"`{self.__class__.__name__}` distribution family " + "cannot be broadcast to the same shape.") + raise ValueError(message) from e + return (dict(zip(parameters.keys(), parameter_vals)), + parameter_vals[0].shape, + parameter_vals[0].size, + parameter_vals[0].ndim) + + def _validate(self, parameterization, parameters): + # Broadcasts distribution parameter arrays and converts them to a + # consistent dtype. Replaces invalid parameters with `np.nan`. + # Returns the validated parameters, a boolean mask indicated *which* + # elements are invalid, a boolean scalar indicating whether *any* + # are invalid (to skip special treatments if none are invalid), and + # the common dtype. + valid, dtype = parameterization.validation(parameters) + invalid = ~valid + any_invalid = invalid if invalid.shape == () else np.any(invalid) + # If necessary, make the arrays contiguous and replace invalid with NaN + if any_invalid: + for parameter_name in parameters: + parameters[parameter_name] = np.copy( + parameters[parameter_name]) + parameters[parameter_name][invalid] = np.nan + + return parameters, invalid, any_invalid, dtype + + def _process_parameters(self, **params): + r""" Process and cache distribution parameters for reuse. + + This is intended to be overridden by subclasses. It allows distribution + authors to pre-process parameters for re-use. For instance, when a user + parameterizes a LogUniform distribution with `a` and `b`, it makes + sense to calculate `log(a)` and `log(b)` because these values will be + used in almost all distribution methods. The dictionary returned by + this method is passed to all private methods that calculate functions + of the distribution. + """ + return params + + def _get_parameter_str(self, parameters): + # Get a string representation of the parameters like "{a, b, c}". + return f"{{{', '.join(parameters.keys())}}}" + + def _copy_parameterization(self): + self._parameterizations = self._parameterizations.copy() + for i in range(len(self._parameterizations)): + self._parameterizations[i] = self._parameterizations[i].copy() + + ### Attributes + + # `tol` attribute is just notional right now. See Question 4 above. + @property + def tol(self): + r"""positive float: + The desired relative tolerance of calculations. Left unspecified, + calculations may be faster; when provided, calculations may be + more likely to meet the desired accuracy. + """ + return self._tol + + @tol.setter + def tol(self, tol): + if _isnull(tol): + self._tol = tol + return + + tol = np.asarray(tol) + if (tol.shape != () or not tol > 0 or # catches NaNs + not np.issubdtype(tol.dtype, np.floating)): + message = (f"Attribute `tol` of `{self.__class__.__name__}` must " + "be a positive float, if specified.") + raise ValueError(message) + self._tol = tol[()] + + @property + def cache_policy(self): + r"""{None, "no_cache"}: + Specifies the extent to which intermediate results are cached. Left + unspecified, intermediate results of some calculations (e.g. distribution + support, moments, etc.) are cached to improve performance of future + calculations. Pass ``'no_cache'`` to reduce memory reserved by the class + instance. + """ + return self._cache_policy + + @cache_policy.setter + def cache_policy(self, cache_policy): + cache_policy = str(cache_policy).lower() if cache_policy is not None else None + cache_policies = {None, 'no_cache'} + if cache_policy not in cache_policies: + message = (f"Attribute `cache_policy` of `{self.__class__.__name__}` " + f"must be one of {cache_policies}, if specified.") + raise ValueError(message) + self._cache_policy = cache_policy + + @property + def validation_policy(self): + r"""{None, "skip_all"}: + Specifies the level of input validation to perform. Left unspecified, + input validation is performed to ensure appropriate behavior in edge + case (e.g. parameters out of domain, argument outside of distribution + support, etc.) and improve consistency of output dtype, shape, etc. + Use ``'skip_all'`` to avoid the computational overhead of these + checks when rough edges are acceptable. + """ + return self._validation_policy + + @validation_policy.setter + def validation_policy(self, validation_policy): + validation_policy = (str(validation_policy).lower() + if validation_policy is not None else None) + iv_policies = {None, 'skip_all'} + if validation_policy not in iv_policies: + message = (f"Attribute `validation_policy` of `{self.__class__.__name__}` " + f"must be one of {iv_policies}, if specified.") + raise ValueError(message) + self._validation_policy = validation_policy + + ### Other magic methods + + def __repr__(self): + r""" Returns a string representation of the distribution. + + Includes the name of the distribution family, the names of the + parameters and the `repr` of each of their values. + + + """ + class_name = self.__class__.__name__ + parameters = list(self._original_parameters.items()) + info = [] + with np.printoptions(threshold=10): + str_parameters = [f"{symbol}={repr(value)}" for symbol, value in parameters] + str_parameters = f"{', '.join(str_parameters)}" + info.append(str_parameters) + return f"{class_name}({', '.join(info)})" + + def __str__(self): + class_name = self.__class__.__name__ + parameters = list(self._original_parameters.items()) + info = [] + with np.printoptions(threshold=10): + str_parameters = [f"{symbol}={str(value)}" for symbol, value in parameters] + str_parameters = f"{', '.join(str_parameters)}" + info.append(str_parameters) + return f"{class_name}({', '.join(info)})" + + def __add__(self, loc): + return ShiftedScaledDistribution(self, loc=loc) + + def __sub__(self, loc): + return ShiftedScaledDistribution(self, loc=-loc) + + def __mul__(self, scale): + return ShiftedScaledDistribution(self, scale=scale) + + def __truediv__(self, scale): + return ShiftedScaledDistribution(self, scale=1/scale) + + def __pow__(self, other): + if not np.isscalar(other) or other <= 0 or other != int(other): + message = ("Raising a random variable to the power of an argument is only " + "implemented when the argument is a positive integer.") + raise NotImplementedError(message) + + # Fill in repr_pattern with the repr of self before taking abs. + # Avoids having unnecessary abs in the repr. + with np.printoptions(threshold=10): + repr_pattern = f"({repr(self)})**{repr(other)}" + str_pattern = f"({str(self)})**{str(other)}" + X = abs(self) if other % 2 == 0 else self + + funcs = dict(g=lambda u: u**other, repr_pattern=repr_pattern, + str_pattern=str_pattern, + h=lambda u: np.sign(u) * np.abs(u)**(1 / other), + dh=lambda u: 1/other * np.abs(u)**(1/other - 1)) + + return MonotonicTransformedDistribution(X, **funcs, increasing=True) + + def __radd__(self, other): + return self.__add__(other) + + def __rsub__(self, other): + return self.__neg__().__add__(other) + + def __rmul__(self, other): + return self.__mul__(other) + + def __rtruediv__(self, other): + a, b = self.support() + with np.printoptions(threshold=10): + funcs = dict(g=lambda u: 1 / u, + repr_pattern=f"{repr(other)}/({repr(self)})", + str_pattern=f"{str(other)}/({str(self)})", + h=lambda u: 1 / u, dh=lambda u: 1 / u ** 2) + if np.all(a >= 0) or np.all(b <= 0): + out = MonotonicTransformedDistribution(self, **funcs, increasing=False) + else: + message = ("Division by a random variable is only implemented " + "when the support is either non-negative or non-positive.") + raise NotImplementedError(message) + if np.all(other == 1): + return out + else: + return out * other + + def __rpow__(self, other): + with np.printoptions(threshold=10): + funcs = dict(g=lambda u: other**u, + h=lambda u: np.log(u) / np.log(other), + dh=lambda u: 1 / np.abs(u * np.log(other)), + repr_pattern=f"{repr(other)}**({repr(self)})", + str_pattern=f"{str(other)}**({str(self)})",) + + if not np.isscalar(other) or other <= 0 or other == 1: + message = ("Raising an argument to the power of a random variable is only " + "implemented when the argument is a positive scalar other than " + "1.") + raise NotImplementedError(message) + + if other > 1: + return MonotonicTransformedDistribution(self, **funcs, increasing=True) + else: + return MonotonicTransformedDistribution(self, **funcs, increasing=False) + + def __neg__(self): + return self * -1 + + def __abs__(self): + return FoldedDistribution(self) + + ### Utilities + + ## Input validation + + def _validate_order_kind(self, order, kind, kinds): + # Yet another integer validating function. Unlike others in SciPy, it + # Is quite flexible about what is allowed as an integer, and it + # raises a distribution-specific error message to facilitate + # identification of the source of the error. + if self.validation_policy == _SKIP_ALL: + return order + + order = np.asarray(order, dtype=self._dtype)[()] + message = (f"Argument `order` of `{self.__class__.__name__}.moment` " + "must be a finite, positive integer.") + try: + order_int = round(order.item()) + # If this fails for any reason (e.g. it's an array, it's infinite) + # it's not a valid `order`. + except Exception as e: + raise ValueError(message) from e + + if order_int <0 or order_int != order: + raise ValueError(message) + + message = (f"Argument `kind` of `{self.__class__.__name__}.moment` " + f"must be one of {set(kinds)}.") + if kind.lower() not in kinds: + raise ValueError(message) + + return order + + def _preserve_type(self, x): + x = np.asarray(x) + if x.dtype != self._dtype: + x = x.astype(self._dtype) + return x[()] + + ## Testing + + @classmethod + def _draw(cls, sizes=None, rng=None, i_parameterization=None, + proportions=None): + r""" Draw a specific (fully-defined) distribution from the family. + + See _Parameterization.draw for documentation details. + """ + rng = np.random.default_rng(rng) + if len(cls._parameterizations) == 0: + return cls() + if i_parameterization is None: + n = cls._num_parameterizations() + i_parameterization = rng.integers(0, max(0, n - 1), endpoint=True) + + parameterization = cls._parameterizations[i_parameterization] + parameters = parameterization.draw(sizes, rng, proportions=proportions, + region='typical') + return cls(**parameters) + + @classmethod + def _num_parameterizations(cls): + # Returns the number of parameterizations accepted by the family. + return len(cls._parameterizations) + + @classmethod + def _num_parameters(cls, i_parameterization=0): + # Returns the number of parameters used in the specified + # parameterization. + return (0 if not cls._num_parameterizations() + else len(cls._parameterizations[i_parameterization])) + + ## Algorithms + + def _quadrature(self, integrand, limits=None, args=None, + params=None, log=False): + # Performs numerical integration of an integrand between limits. + # Much of this should be added to `_tanhsinh`. + a, b = self._support(**params) if limits is None else limits + a, b = np.broadcast_arrays(a, b) + if not a.size: + # maybe need to figure out result type from a, b + return np.empty(a.shape, dtype=self._dtype) + args = [] if args is None else args + params = {} if params is None else params + f, args = _kwargs2args(integrand, args=args, kwargs=params) + args = np.broadcast_arrays(*args) + # If we know the median or mean, consider breaking up the interval + rtol = None if _isnull(self.tol) else self.tol + res = _tanhsinh(f, a, b, args=args, log=log, rtol=rtol) + # For now, we ignore the status, but I want to return the error + # estimate - see question 5 at the top. + return res.integral + + def _solve_bounded(self, f, p, *, bounds=None, params=None): + # Finds the argument of a function that produces the desired output. + # Much of this should be added to _bracket_root / _chandrupatla. + xmin, xmax = self._support(**params) if bounds is None else bounds + params = {} if params is None else params + + p, xmin, xmax = np.broadcast_arrays(p, xmin, xmax) + if not p.size: + # might need to figure out result type based on p + return np.empty(p.shape, dtype=self._dtype) + + def f2(x, _p, **kwargs): # named `_p` to avoid conflict with shape `p` + return f(x, **kwargs) - _p + + f3, args = _kwargs2args(f2, args=[p], kwargs=params) + # If we know the median or mean, should use it + + # Any operations between 0d array and a scalar produces a scalar, so... + shape = xmin.shape + xmin, xmax = np.atleast_1d(xmin, xmax) + + xl0, xr0 = _guess_bracket(xmin, xmax) + xmin = xmin.reshape(shape) + xmax = xmax.reshape(shape) + xl0 = xl0.reshape(shape) + xr0 = xr0.reshape(shape) + + res = _bracket_root(f3, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=args) + # For now, we ignore the status, but I want to use the bracket width + # as an error estimate - see question 5 at the top. + xrtol = None if _isnull(self.tol) else self.tol + return _chandrupatla(f3, a=res.xl, b=res.xr, args=args, xrtol=xrtol).x + + ## Other + + def _overrides(self, method_name): + # Determines whether a class overrides a specified method. + # Returns True if the method implementation exists and is the same as + # that of the `ContinuousDistribution` class; otherwise returns False. + + # Sometimes we use `_overrides` to check whether a certain method is overridden + # and if so, call it. This begs the questions of why we don't do the more + # obvious thing: restructure so that if the private method is overridden, + # Python will call it instead of the inherited version automatically. The short + # answer is that there are multiple ways a use might wish to evaluate a method, + # and simply overriding the method with a formula is not always the best option. + # For more complete discussion of the considerations, see: + # https://github.com/scipy/scipy/pull/21050#discussion_r1707798901 + method = getattr(self.__class__, method_name, None) + super_method = getattr(ContinuousDistribution, method_name, None) + return method is not super_method + + ### Distribution properties + # The following "distribution properties" are exposed via a public method + # that accepts only options (not distribution parameters or quantile/ + # percentile argument). + # support + # logentropy, entropy, + # median, mode, mean, + # variance, standard_deviation + # skewness, kurtosis + # Common options are: + # method - a string that indicates which method should be used to compute + # the quantity (e.g. a formula or numerical integration). + # Input/output validation is provided by the `_set_invalid_nan_property` + # decorator. These are the methods meant to be called by users. + # + # Each public method calls a private "dispatch" method that + # determines which "method" (strategy for calculating the desired quantity) + # to use by default and, via the `@_dispatch` decorator, calls the + # method and computes the result. + # Dispatch methods always accept: + # method - as passed from the public method + # params - a dictionary of distribution shape parameters passed by + # the public method. + # Dispatch methods accept `params` rather than relying on the state of the + # object because iterative algorithms like `_tanhsinh` and `_chandrupatla` + # need their callable to follow a strict elementwise protocol: each element + # of the output is determined solely by the values of the inputs at the + # corresponding location. The public methods do not satisfy this protocol + # because they do not accept the parameters as arguments, producing an + # output that generally has a different shape than that of the input. Also, + # by calling "dispatch" methods rather than the public methods, the + # iterative algorithms avoid the overhead of input validation. + # + # Each dispatch method can designate the responsibility of computing + # the required value to any of several "implementation" methods. These + # methods accept only `**params`, the parameter dictionary passed from + # the public method via the dispatch method. We separate the implementation + # methods from the dispatch methods for the sake of simplicity (via + # compartmentalization) and to allow subclasses to override certain + # implementation methods (typically only the "formula" methods). The names + # of implementation methods are combinations of the public method name and + # the name of the "method" (strategy for calculating the desired quantity) + # string. (In fact, the name of the implementation method is calculated + # from these two strings in the `_dispatch` decorator.) Common method + # strings are: + # formula - distribution-specific analytical expressions to be implemented + # by subclasses. + # log/exp - Compute the log of a number and then exponentiate it or vice + # versa. + # quadrature - Compute the value via numerical integration. + # + # The default method (strategy) is determined based on what implementation + # methods are available and the error tolerance of the user. Typically, + # a formula is always used if available. We fall back to "log/exp" if a + # formula for the logarithm or exponential of the quantity is available, + # and we use quadrature otherwise. + + def support(self): + # If this were a `cached_property`, we couldn't update the value + # when the distribution parameters change. + # Caching is important, though, because calls to _support take a few + # microseconds even when `a` and `b` are already the same shape. + if self._support_cache is not None: + return self._support_cache + + a, b = self._support(**self._parameters) + if a.shape != self._shape: + a = np.broadcast_to(a, self._shape) + if b.shape != self._shape: + b = np.broadcast_to(b, self._shape) + + if self._any_invalid: + a, b = np.asarray(a).copy(), np.asarray(b).copy() + a[self._invalid], b[self._invalid] = np.nan, np.nan + a, b = a[()], b[()] + + support = (a, b) + + if self.cache_policy != _NO_CACHE: + self._support_cache = support + + return support + + def _support(self, **params): + # Computes the support given distribution parameters + a, b = self._variable.domain.get_numerical_endpoints(params) + if len(params): + # the parameters should all be of the same dtype and shape at this point + vals = list(params.values()) + shape = vals[0].shape + a = np.broadcast_to(a, shape) if a.shape != shape else a + b = np.broadcast_to(b, shape) if b.shape != shape else b + return self._preserve_type(a), self._preserve_type(b) + + @_set_invalid_nan_property + def logentropy(self, *, method=None): + return self._logentropy_dispatch(method=method, **self._parameters) + 0j + + @_dispatch + def _logentropy_dispatch(self, method=None, **params): + if self._overrides('_logentropy_formula'): + method = self._logentropy_formula + elif self._overrides('_entropy_formula'): + method = self._logentropy_logexp_safe + else: + method = self._logentropy_quadrature + return method + + def _logentropy_formula(self, **params): + raise NotImplementedError(self._not_implemented) + + def _logentropy_logexp(self, **params): + res = np.log(self._entropy_dispatch(**params)+0j) + return _log_real_standardize(res) + + def _logentropy_logexp_safe(self, **params): + out = self._logentropy_logexp(**params) + mask = np.isinf(out.real) + if np.any(mask): + params_mask = {key:val[mask] for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._logentropy_quadrature(**params_mask) + return out[()] + + def _logentropy_quadrature(self, **params): + def logintegrand(x, **params): + logpdf = self._logpdf_dispatch(x, **params) + return logpdf + np.log(0j+logpdf) + res = self._quadrature(logintegrand, params=params, log=True) + return _log_real_standardize(res + np.pi*1j) + + @_set_invalid_nan_property + def entropy(self, *, method=None): + return self._entropy_dispatch(method=method, **self._parameters) + + @_dispatch + def _entropy_dispatch(self, method=None, **params): + if self._overrides('_entropy_formula'): + method = self._entropy_formula + elif self._overrides('_logentropy_formula'): + method = self._entropy_logexp + else: + method = self._entropy_quadrature + return method + + def _entropy_formula(self, **params): + raise NotImplementedError(self._not_implemented) + + def _entropy_logexp(self, **params): + return np.real(np.exp(self._logentropy_dispatch(**params))) + + def _entropy_quadrature(self, **params): + def integrand(x, **params): + pdf = self._pdf_dispatch(x, **params) + logpdf = self._logpdf_dispatch(x, **params) + return logpdf * pdf + return -self._quadrature(integrand, params=params) + + @_set_invalid_nan_property + def median(self, *, method=None): + return self._median_dispatch(method=method, **self._parameters) + + @_dispatch + def _median_dispatch(self, method=None, **params): + if self._overrides('_median_formula'): + method = self._median_formula + else: + method = self._median_icdf + return method + + def _median_formula(self, **params): + raise NotImplementedError(self._not_implemented) + + def _median_icdf(self, **params): + return self._icdf_dispatch(0.5, **params) + + @_set_invalid_nan_property + def mode(self, *, method=None): + return self._mode_dispatch(method=method, **self._parameters) + + @_dispatch + def _mode_dispatch(self, method=None, **params): + # We could add a method that looks for a critical point with + # differentiation and the root finder + if self._overrides('_mode_formula'): + method = self._mode_formula + else: + method = self._mode_optimization + return method + + def _mode_formula(self, **params): + raise NotImplementedError(self._not_implemented) + + def _mode_optimization(self, **params): + if not self._size: + return np.empty(self._shape, dtype=self._dtype) + + a, b = self._support(**params) + m = self._median_dispatch(**params) + + f, args = _kwargs2args(lambda x, **params: -self._pdf_dispatch(x, **params), + args=(), kwargs=params) + res_b = _bracket_minimum(f, m, xmin=a, xmax=b, args=args) + res = _chandrupatla_minimize(f, res_b.xl, res_b.xm, res_b.xr, args=args) + mode = np.asarray(res.x) + mode_at_boundary = res_b.status == -1 + mode_at_left = mode_at_boundary & (res_b.fl <= res_b.fm) + mode_at_right = mode_at_boundary & (res_b.fr < res_b.fm) + mode[mode_at_left] = a[mode_at_left] + mode[mode_at_right] = b[mode_at_right] + return mode[()] + + def mean(self, *, method=None): + return self.moment(1, kind='raw', method=method) + + def variance(self, *, method=None): + return self.moment(2, kind='central', method=method) + + def standard_deviation(self, *, method=None): + return np.sqrt(self.variance(method=method)) + + def skewness(self, *, method=None): + return self.moment(3, kind='standardized', method=method) + + def kurtosis(self, *, method=None, convention='non-excess'): + conventions = {'non-excess', 'excess'} + message = (f'Parameter `convention` of `{self.__class__.__name__}.kurtosis` ' + f"must be one of {conventions}.") + convention = convention.lower() + if convention not in conventions: + raise ValueError(message) + k = self.moment(4, kind='standardized', method=method) + return k - 3 if convention == 'excess' else k + + ### Distribution functions + # The following functions related to the distribution PDF and CDF are + # exposed via a public method that accepts one positional argument - the + # quantile - and keyword options (but not distribution parameters). + # logpdf, pdf + # logcdf, cdf + # logccdf, ccdf + # The `logcdf` and `cdf` functions can also be called with two positional + # arguments - lower and upper quantiles - and they return the probability + # mass (integral of the PDF) between them. The 2-arg versions of `logccdf` + # and `ccdf` return the complement of this quantity. + # All the (1-arg) cumulative distribution functions have inverse + # functions, which accept one positional argument - the percentile. + # ilogcdf, icdf + # ilogccdf, iccdf + # Common keyword options include: + # method - a string that indicates which method should be used to compute + # the quantity (e.g. a formula or numerical integration). + # Tolerance options should be added. + # Input/output validation is provided by the `_set_invalid_nan` + # decorator. These are the methods meant to be called by users. + # + # Each public method calls a private "dispatch" method that + # determines which "method" (strategy for calculating the desired quantity) + # to use by default and, via the `@_dispatch` decorator, calls the + # method and computes the result. + # Each dispatch method can designate the responsibility of computing + # the required value to any of several "implementation" methods. These + # methods accept only `**params`, the parameter dictionary passed from + # the public method via the dispatch method. + # See the note corresponding with the "Distribution Parameters" for more + # information. + + ## Probability Density Functions + + @_set_invalid_nan + def logpdf(self, x, /, *, method=None): + return self._logpdf_dispatch(x, method=method, **self._parameters) + + @_dispatch + def _logpdf_dispatch(self, x, *, method=None, **params): + if self._overrides('_logpdf_formula'): + method = self._logpdf_formula + elif _isnull(self.tol): # ensure that developers override _logpdf + method = self._logpdf_logexp + return method + + def _logpdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _logpdf_logexp(self, x, **params): + return np.log(self._pdf_dispatch(x, **params)) + + @_set_invalid_nan + def pdf(self, x, /, *, method=None): + return self._pdf_dispatch(x, method=method, **self._parameters) + + @_dispatch + def _pdf_dispatch(self, x, *, method=None, **params): + if self._overrides('_pdf_formula'): + method = self._pdf_formula + else: + method = self._pdf_logexp + return method + + def _pdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _pdf_logexp(self, x, **params): + return np.exp(self._logpdf_dispatch(x, **params)) + + ## Cumulative Distribution Functions + + def logcdf(self, x, y=None, /, *, method=None): + if y is None: + return self._logcdf1(x, method=method) + else: + return self._logcdf2(x, y, method=method) + + @_cdf2_input_validation + def _logcdf2(self, x, y, *, method): + out = self._logcdf2_dispatch(x, y, method=method, **self._parameters) + return (out + 0j) if not np.issubdtype(out.dtype, np.complexfloating) else out + + @_dispatch + def _logcdf2_dispatch(self, x, y, *, method=None, **params): + # dtype is complex if any x > y, else real + # Should revisit this logic. + if self._overrides('_logcdf2_formula'): + method = self._logcdf2_formula + elif (self._overrides('_logcdf_formula') + or self._overrides('_logccdf_formula')): + method = self._logcdf2_subtraction + elif (self._overrides('_cdf_formula') + or self._overrides('_ccdf_formula')): + method = self._logcdf2_logexp_safe + else: + method = self._logcdf2_quadrature + return method + + def _logcdf2_formula(self, x, y, **params): + raise NotImplementedError(self._not_implemented) + + def _logcdf2_subtraction(self, x, y, **params): + flip_sign = x > y # some results will be negative + x, y = np.minimum(x, y), np.maximum(x, y) + logcdf_x = self._logcdf_dispatch(x, **params) + logcdf_y = self._logcdf_dispatch(y, **params) + logccdf_x = self._logccdf_dispatch(x, **params) + logccdf_y = self._logccdf_dispatch(y, **params) + case_left = (logcdf_x < -1) & (logcdf_y < -1) + case_right = (logccdf_x < -1) & (logccdf_y < -1) + case_central = ~(case_left | case_right) + log_mass = _logexpxmexpy(logcdf_y, logcdf_x) + log_mass[case_right] = _logexpxmexpy(logccdf_x, logccdf_y)[case_right] + log_tail = np.logaddexp(logcdf_x, logccdf_y)[case_central] + log_mass[case_central] = _log1mexp(log_tail) + log_mass[flip_sign] += np.pi * 1j + return log_mass[()] if np.any(flip_sign) else log_mass.real[()] + + def _logcdf2_logexp(self, x, y, **params): + expres = self._cdf2_dispatch(x, y, **params) + expres = expres + 0j if np.any(x > y) else expres + return np.log(expres) + + def _logcdf2_logexp_safe(self, x, y, **params): + out = self._logcdf2_logexp(x, y, **params) + mask = np.isinf(out.real) + if np.any(mask): + params_mask = {key: np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._logcdf2_quadrature(x[mask], y[mask], **params_mask) + return out[()] + + def _logcdf2_quadrature(self, x, y, **params): + logres = self._quadrature(self._logpdf_dispatch, limits=(x, y), + log=True, params=params) + return logres + + @_set_invalid_nan + def _logcdf1(self, x, *, method=None): + return self._logcdf_dispatch(x, method=method, **self._parameters) + + @_dispatch + def _logcdf_dispatch(self, x, *, method=None, **params): + if self._overrides('_logcdf_formula'): + method = self._logcdf_formula + elif self._overrides('_logccdf_formula'): + method = self._logcdf_complement + elif self._overrides('_cdf_formula'): + method = self._logcdf_logexp_safe + else: + method = self._logcdf_quadrature + return method + + def _logcdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _logcdf_complement(self, x, **params): + return _log1mexp(self._logccdf_dispatch(x, **params)) + + def _logcdf_logexp(self, x, **params): + return np.log(self._cdf_dispatch(x, **params)) + + def _logcdf_logexp_safe(self, x, **params): + out = self._logcdf_logexp(x, **params) + mask = np.isinf(out) + if np.any(mask): + params_mask = {key:np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._logcdf_quadrature(x[mask], **params_mask) + return out[()] + + def _logcdf_quadrature(self, x, **params): + a, _ = self._support(**params) + return self._quadrature(self._logpdf_dispatch, limits=(a, x), + params=params, log=True) + + def cdf(self, x, y=None, /, *, method=None): + if y is None: + return self._cdf1(x, method=method) + else: + return self._cdf2(x, y, method=method) + + @_cdf2_input_validation + def _cdf2(self, x, y, *, method): + return self._cdf2_dispatch(x, y, method=method, **self._parameters) + + @_dispatch + def _cdf2_dispatch(self, x, y, *, method=None, **params): + # Should revisit this logic. + if self._overrides('_cdf2_formula'): + method = self._cdf2_formula + elif (self._overrides('_logcdf_formula') + or self._overrides('_logccdf_formula')): + method = self._cdf2_logexp + elif self._overrides('_cdf_formula') or self._overrides('_ccdf_formula'): + method = self._cdf2_subtraction_safe + else: + method = self._cdf2_quadrature + return method + + def _cdf2_formula(self, x, y, **params): + raise NotImplementedError(self._not_implemented) + + def _cdf2_logexp(self, x, y, **params): + return np.real(np.exp(self._logcdf2_dispatch(x, y, **params))) + + def _cdf2_subtraction(self, x, y, **params): + # Improvements: + # Lazy evaluation of cdf/ccdf only where needed + # Stack x and y to reduce function calls? + cdf_x = self._cdf_dispatch(x, **params) + cdf_y = self._cdf_dispatch(y, **params) + ccdf_x = self._ccdf_dispatch(x, **params) + ccdf_y = self._ccdf_dispatch(y, **params) + i = (ccdf_x < 0.5) & (ccdf_y < 0.5) + return np.where(i, ccdf_x-ccdf_y, cdf_y-cdf_x) + + def _cdf2_subtraction_safe(self, x, y, **params): + cdf_x = self._cdf_dispatch(x, **params) + cdf_y = self._cdf_dispatch(y, **params) + ccdf_x = self._ccdf_dispatch(x, **params) + ccdf_y = self._ccdf_dispatch(y, **params) + i = (ccdf_x < 0.5) & (ccdf_y < 0.5) + out = np.where(i, ccdf_x-ccdf_y, cdf_y-cdf_x) + + eps = np.finfo(self._dtype).eps + tol = self.tol if not _isnull(self.tol) else np.sqrt(eps) + + cdf_max = np.maximum(cdf_x, cdf_y) + ccdf_max = np.maximum(ccdf_x, ccdf_y) + spacing = np.spacing(np.where(i, ccdf_max, cdf_max)) + mask = np.abs(tol * out) < spacing + + if np.any(mask): + params_mask = {key: np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._cdf2_quadrature(x[mask], y[mask], *params_mask) + return out[()] + + def _cdf2_quadrature(self, x, y, **params): + return self._quadrature(self._pdf_dispatch, limits=(x, y), params=params) + + @_set_invalid_nan + def _cdf1(self, x, *, method): + return self._cdf_dispatch(x, method=method, **self._parameters) + + @_dispatch + def _cdf_dispatch(self, x, *, method=None, **params): + if self._overrides('_cdf_formula'): + method = self._cdf_formula + elif self._overrides('_logcdf_formula'): + method = self._cdf_logexp + elif self._overrides('_ccdf_formula'): + method = self._cdf_complement_safe + else: + method = self._cdf_quadrature + return method + + def _cdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _cdf_logexp(self, x, **params): + return np.exp(self._logcdf_dispatch(x, **params)) + + def _cdf_complement(self, x, **params): + return 1 - self._ccdf_dispatch(x, **params) + + def _cdf_complement_safe(self, x, **params): + ccdf = self._ccdf_dispatch(x, **params) + out = 1 - ccdf + eps = np.finfo(self._dtype).eps + tol = self.tol if not _isnull(self.tol) else np.sqrt(eps) + mask = tol * out < np.spacing(ccdf) + if np.any(mask): + params_mask = {key: np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._cdf_quadrature(x[mask], *params_mask) + return out[()] + + def _cdf_quadrature(self, x, **params): + a, _ = self._support(**params) + return self._quadrature(self._pdf_dispatch, limits=(a, x), + params=params) + + def logccdf(self, x, y=None, /, *, method=None): + if y is None: + return self._logccdf1(x, method=method) + else: + return self._logccdf2(x, y, method=method) + + @_cdf2_input_validation + def _logccdf2(self, x, y, *, method): + return self._logccdf2_dispatch(x, y, method=method, **self._parameters) + + @_dispatch + def _logccdf2_dispatch(self, x, y, *, method=None, **params): + # if _logccdf2_formula exists, we could use the complement + # if _ccdf2_formula exists, we could use log/exp + if self._overrides('_logccdf2_formula'): + method = self._logccdf2_formula + else: + method = self._logccdf2_addition + return method + + def _logccdf2_formula(self, x, y, **params): + raise NotImplementedError(self._not_implemented) + + def _logccdf2_addition(self, x, y, **params): + logcdf_x = self._logcdf_dispatch(x, **params) + logccdf_y = self._logccdf_dispatch(y, **params) + return special.logsumexp([logcdf_x, logccdf_y], axis=0) + + @_set_invalid_nan + def _logccdf1(self, x, *, method=None): + return self._logccdf_dispatch(x, method=method, **self._parameters) + + @_dispatch + def _logccdf_dispatch(self, x, method=None, **params): + if self._overrides('_logccdf_formula'): + method = self._logccdf_formula + elif self._overrides('_logcdf_formula'): + method = self._logccdf_complement + elif self._overrides('_ccdf_formula'): + method = self._logccdf_logexp_safe + else: + method = self._logccdf_quadrature + return method + + def _logccdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _logccdf_complement(self, x, **params): + return _log1mexp(self._logcdf_dispatch(x, **params)) + + def _logccdf_logexp(self, x, **params): + return np.log(self._ccdf_dispatch(x, **params)) + + def _logccdf_logexp_safe(self, x, **params): + out = self._logccdf_logexp(x, **params) + mask = np.isinf(out) + if np.any(mask): + params_mask = {key: np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._logccdf_quadrature(x[mask], **params_mask) + return out[()] + + def _logccdf_quadrature(self, x, **params): + _, b = self._support(**params) + return self._quadrature(self._logpdf_dispatch, limits=(x, b), + params=params, log=True) + + def ccdf(self, x, y=None, /, *, method=None): + if y is None: + return self._ccdf1(x, method=method) + else: + return self._ccdf2(x, y, method=method) + + @_cdf2_input_validation + def _ccdf2(self, x, y, *, method): + return self._ccdf2_dispatch(x, y, method=method, **self._parameters) + + @_dispatch + def _ccdf2_dispatch(self, x, y, *, method=None, **params): + if self._overrides('_ccdf2_formula'): + method = self._ccdf2_formula + else: + method = self._ccdf2_addition + return method + + def _ccdf2_formula(self, x, y, **params): + raise NotImplementedError(self._not_implemented) + + def _ccdf2_addition(self, x, y, **params): + cdf_x = self._cdf_dispatch(x, **params) + ccdf_y = self._ccdf_dispatch(y, **params) + # even if x > y, cdf(x, y) + ccdf(x,y) sums to 1 + return cdf_x + ccdf_y + + @_set_invalid_nan + def _ccdf1(self, x, *, method): + return self._ccdf_dispatch(x, method=method, **self._parameters) + + @_dispatch + def _ccdf_dispatch(self, x, method=None, **params): + if self._overrides('_ccdf_formula'): + method = self._ccdf_formula + elif self._overrides('_logccdf_formula'): + method = self._ccdf_logexp + elif self._overrides('_cdf_formula'): + method = self._ccdf_complement_safe + else: + method = self._ccdf_quadrature + return method + + def _ccdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _ccdf_logexp(self, x, **params): + return np.exp(self._logccdf_dispatch(x, **params)) + + def _ccdf_complement(self, x, **params): + return 1 - self._cdf_dispatch(x, **params) + + def _ccdf_complement_safe(self, x, **params): + cdf = self._cdf_dispatch(x, **params) + out = 1 - cdf + eps = np.finfo(self._dtype).eps + tol = self.tol if not _isnull(self.tol) else np.sqrt(eps) + mask = tol * out < np.spacing(cdf) + if np.any(mask): + params_mask = {key: np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._ccdf_quadrature(x[mask], **params_mask) + return out[()] + + def _ccdf_quadrature(self, x, **params): + _, b = self._support(**params) + return self._quadrature(self._pdf_dispatch, limits=(x, b), + params=params) + + ## Inverse cumulative distribution functions + + @_set_invalid_nan + def ilogcdf(self, logp, /, *, method=None): + return self._ilogcdf_dispatch(logp, method=method, **self._parameters) + + @_dispatch + def _ilogcdf_dispatch(self, x, method=None, **params): + if self._overrides('_ilogcdf_formula'): + method = self._ilogcdf_formula + elif self._overrides('_ilogccdf_formula'): + method = self._ilogcdf_complement + else: + method = self._ilogcdf_inversion + return method + + def _ilogcdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _ilogcdf_complement(self, x, **params): + return self._ilogccdf_dispatch(_log1mexp(x), **params) + + def _ilogcdf_inversion(self, x, **params): + return self._solve_bounded(self._logcdf_dispatch, x, params=params) + + @_set_invalid_nan + def icdf(self, p, /, *, method=None): + return self._icdf_dispatch(p, method=method, **self._parameters) + + @_dispatch + def _icdf_dispatch(self, x, method=None, **params): + if self._overrides('_icdf_formula'): + method = self._icdf_formula + elif self._overrides('_iccdf_formula'): + method = self._icdf_complement_safe + else: + method = self._icdf_inversion + return method + + def _icdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _icdf_complement(self, x, **params): + return self._iccdf_dispatch(1 - x, **params) + + def _icdf_complement_safe(self, x, **params): + out = self._icdf_complement(x, **params) + eps = np.finfo(self._dtype).eps + tol = self.tol if not _isnull(self.tol) else np.sqrt(eps) + mask = tol * x < np.spacing(1 - x) + if np.any(mask): + params_mask = {key: np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._icdf_inversion(x[mask], *params_mask) + return out[()] + + def _icdf_inversion(self, x, **params): + return self._solve_bounded(self._cdf_dispatch, x, params=params) + + @_set_invalid_nan + def ilogccdf(self, logp, /, *, method=None): + return self._ilogccdf_dispatch(logp, method=method, **self._parameters) + + @_dispatch + def _ilogccdf_dispatch(self, x, method=None, **params): + if self._overrides('_ilogccdf_formula'): + method = self._ilogccdf_formula + elif self._overrides('_ilogcdf_formula'): + method = self._ilogccdf_complement + else: + method = self._ilogccdf_inversion + return method + + def _ilogccdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _ilogccdf_complement(self, x, **params): + return self._ilogcdf_dispatch(_log1mexp(x), **params) + + def _ilogccdf_inversion(self, x, **params): + return self._solve_bounded(self._logccdf_dispatch, x, params=params) + + @_set_invalid_nan + def iccdf(self, p, /, *, method=None): + return self._iccdf_dispatch(p, method=method, **self._parameters) + + @_dispatch + def _iccdf_dispatch(self, x, method=None, **params): + if self._overrides('_iccdf_formula'): + method = self._iccdf_formula + elif self._overrides('_icdf_formula'): + method = self._iccdf_complement_safe + else: + method = self._iccdf_inversion + return method + + def _iccdf_formula(self, x, **params): + raise NotImplementedError(self._not_implemented) + + def _iccdf_complement(self, x, **params): + return self._icdf_dispatch(1 - x, **params) + + def _iccdf_complement_safe(self, x, **params): + out = self._iccdf_complement(x, **params) + eps = np.finfo(self._dtype).eps + tol = self.tol if not _isnull(self.tol) else np.sqrt(eps) + mask = tol * x < np.spacing(1 - x) + if np.any(mask): + params_mask = {key: np.broadcast_to(val, mask.shape)[mask] + for key, val in params.items()} + out = np.asarray(out) + out[mask] = self._iccdf_inversion(x[mask], *params_mask) + return out[()] + + def _iccdf_inversion(self, x, **params): + return self._solve_bounded(self._ccdf_dispatch, x, params=params) + + ### Sampling Functions + # The following functions for drawing samples from the distribution are + # exposed via a public method that accepts one positional argument - the + # shape of the sample - and keyword options (but not distribution + # parameters). + # sample + # ~~qmc_sample~~ built into sample now + # + # Common keyword options include: + # method - a string that indicates which method should be used to compute + # the quantity (e.g. a formula or numerical integration). + # rng - the NumPy Generator/SciPy QMCEngine object to used for drawing numbers. + # + # Input/output validation is included in each function, since there is + # little code to be shared. + # These are the methods meant to be called by users. + # + # Each public method calls a private "dispatch" method that + # determines which "method" (strategy for calculating the desired quantity) + # to use by default and, via the `@_dispatch` decorator, calls the + # method and computes the result. + # Each dispatch method can designate the responsibility of sampling to any + # of several "implementation" methods. These methods accept only + # `**params`, the parameter dictionary passed from the public method via + # the "dispatch" method. + # See the note corresponding with the "Distribution Parameters" for more + # information. + + # TODO: + # - should we accept a QRNG with `d != 1`? + def sample(self, shape=(), *, method=None, rng=None): + # needs output validation to ensure that developer returns correct + # dtype and shape + sample_shape = (shape,) if not np.iterable(shape) else tuple(shape) + full_shape = sample_shape + self._shape + rng = np.random.default_rng(rng) if not isinstance(rng, qmc.QMCEngine) else rng + res = self._sample_dispatch(sample_shape, full_shape, method=method, + rng=rng, **self._parameters) + + return res.astype(self._dtype, copy=False) + + @_dispatch + def _sample_dispatch(self, sample_shape, full_shape, *, method, rng, **params): + # make sure that tests catch if sample is 0d array + if self._overrides('_sample_formula') and not isinstance(rng, qmc.QMCEngine): + method = self._sample_formula + else: + method = self._sample_inverse_transform + return method + + def _sample_formula(self, sample_shape, full_shape, *, rng, **params): + raise NotImplementedError(self._not_implemented) + + def _sample_inverse_transform(self, sample_shape, full_shape, *, rng, **params): + if isinstance(rng, qmc.QMCEngine): + uniform = self._qmc_uniform(sample_shape, full_shape, qrng=rng, **params) + else: + uniform = rng.random(size=full_shape, dtype=self._dtype) + return self._icdf_dispatch(uniform, **params) + + def _qmc_uniform(self, sample_shape, full_shape, *, qrng, **params): + # Generate QMC uniform sample(s) on unit interval with specified shape; + # if `sample_shape != ()`, then each slice along axis 0 is independent. + + # Determine the number of independent sequences and the length of each. + n_low_discrepancy = sample_shape[0] if sample_shape else 1 + n_independent = math.prod(full_shape[1:] if sample_shape else full_shape) + + # For each independent sequence, we'll need a new QRNG of the appropriate class + # with its own RNG. (If scramble=False, we don't really need all the separate + # rngs, but I'm not going to add a special code path right now.) + rngs = _rng_spawn(qrng.rng, n_independent) + qrng_class = qrng.__class__ + kwargs = dict(d=1, scramble=qrng.scramble, optimization=qrng._optimization) + if isinstance(qrng, qmc.Sobol): + kwargs['bits'] = qrng.bits + + # Draw uniform low-discrepancy sequences scrambled with each RNG + uniforms = [] + for rng in rngs: + qrng = qrng_class(seed=rng, **kwargs) + uniform = qrng.random(n_low_discrepancy) + uniform = uniform.reshape(n_low_discrepancy if sample_shape else ())[()] + uniforms.append(uniform) + + # Reorder the axes and ensure that the shape is correct + uniform = np.moveaxis(np.stack(uniforms), -1, 0) if uniforms else np.asarray([]) + return uniform.reshape(full_shape) + + ### Moments + # The `moment` method accepts two positional arguments - the order and kind + # (raw, central, or standard) of the moment - and a keyword option: + # method - a string that indicates which method should be used to compute + # the quantity (e.g. a formula or numerical integration). + # Like the distribution properties, input/output validation is provided by + # the `_set_invalid_nan_property` decorator. + # + # Unlike most public methods above, `moment` dispatches to one of three + # private methods - one for each 'kind'. Like most *public* methods above, + # each of these private methods calls a private "dispatch" method that + # determines which "method" (strategy for calculating the desired quantity) + # to use. Also, each dispatch method can designate the responsibility + # computing the moment to one of several "implementation" methods. + # Unlike the dispatch methods above, however, the `@_dispatch` decorator + # is not used, and both logic and method calls are included in the function + # itself. + # Instead of determining which method will be used based solely on the + # implementation methods available and calling only the corresponding + # implementation method, *all* the implementation methods are called + # in sequence until one returns the desired information. When an + # implementation methods cannot provide the requested information, it + # returns the object None (which is distinct from arrays with NaNs or infs, + # which are valid values of moments). + # The reason for this approach is that although formulae for the first + # few moments of a distribution may be found, general formulae that work + # for all orders are not always easy to find. This approach allows the + # developer to write "formula" implementation functions that return the + # desired moment when it is available and None otherwise. + # + # Note that the first implementation method called is a cache. This is + # important because lower-order moments are often needed to compute + # higher moments from formulae, so we eliminate redundant calculations + # when moments of several orders are needed. + + @cached_property + def _moment_methods(self): + return {'cache', 'formula', 'transform', + 'normalize', 'general', 'quadrature'} + + @property + def _zero(self): + return self._constants()[0] + + @property + def _one(self): + return self._constants()[1] + + def _constants(self): + if self._constant_cache is not None: + return self._constant_cache + + constants = self._preserve_type([0, 1]) + + if self.cache_policy != _NO_CACHE: + self._constant_cache = constants + + return constants + + @_set_invalid_nan_property + def moment(self, order=1, kind='raw', *, method=None): + kinds = {'raw': self._moment_raw, + 'central': self._moment_central, + 'standardized': self._moment_standardized} + order = self._validate_order_kind(order, kind, kinds) + moment_kind = kinds[kind] + return moment_kind(order, method=method) + + def _moment_raw(self, order=1, *, method=None): + """Raw distribution moment about the origin.""" + # Consider exposing the point about which moments are taken as an + # option. This is easy to support, since `_moment_transform_center` + # does all the work. + methods = self._moment_methods if method is None else {method} + return self._moment_raw_dispatch(order, methods=methods, **self._parameters) + + def _moment_raw_dispatch(self, order, *, methods, **params): + moment = None + + if 'cache' in methods: + moment = self._moment_raw_cache.get(order, None) + + if moment is None and 'formula' in methods: + moment = self._moment_raw_formula(order, **params) + + if moment is None and 'transform' in methods and order > 1: + moment = self._moment_raw_transform(order, **params) + + if moment is None and 'general' in methods: + moment = self._moment_raw_general(order, **params) + + if moment is None and 'quadrature' in methods: + moment = self._moment_integrate_pdf(order, center=self._zero, **params) + + if moment is None and 'quadrature_icdf' in methods: + moment = self._moment_integrate_icdf(order, center=self._zero, **params) + + if moment is not None and self.cache_policy != _NO_CACHE: + self._moment_raw_cache[order] = moment + + return moment + + def _moment_raw_formula(self, order, **params): + return None + + def _moment_raw_transform(self, order, **params): + central_moments = [] + for i in range(int(order) + 1): + methods = {'cache', 'formula', 'normalize', 'general'} + moment_i = self._moment_central_dispatch(order=i, methods=methods, **params) + if moment_i is None: + return None + central_moments.append(moment_i) + + # Doesn't make sense to get the mean by "transform", since that's + # how we got here. Questionable whether 'quadrature' should be here. + mean_methods = {'cache', 'formula', 'quadrature'} + mean = self._moment_raw_dispatch(self._one, methods=mean_methods, **params) + if mean is None: + return None + + moment = self._moment_transform_center(order, central_moments, mean, self._zero) + return moment + + def _moment_raw_general(self, order, **params): + # This is the only general formula for a raw moment of a probability + # distribution + return self._one if order == 0 else None + + def _moment_central(self, order=1, *, method=None): + """Distribution moment about the mean.""" + methods = self._moment_methods if method is None else {method} + return self._moment_central_dispatch(order, methods=methods, **self._parameters) + + def _moment_central_dispatch(self, order, *, methods, **params): + moment = None + + if 'cache' in methods: + moment = self._moment_central_cache.get(order, None) + + if moment is None and 'formula' in methods: + moment = self._moment_central_formula(order, **params) + + if moment is None and 'transform' in methods: + moment = self._moment_central_transform(order, **params) + + if moment is None and 'normalize' in methods and order > 2: + moment = self._moment_central_normalize(order, **params) + + if moment is None and 'general' in methods: + moment = self._moment_central_general(order, **params) + + if moment is None and 'quadrature' in methods: + mean = self._moment_raw_dispatch(self._one, **params, + methods=self._moment_methods) + moment = self._moment_integrate_pdf(order, center=mean, **params) + + if moment is None and 'quadrature_icdf' in methods: + mean = self._moment_raw_dispatch(self._one, **params, + methods=self._moment_methods) + moment = self._moment_integrate_icdf(order, center=mean, **params) + + if moment is not None and self.cache_policy != _NO_CACHE: + self._moment_central_cache[order] = moment + + return moment + + def _moment_central_formula(self, order, **params): + return None + + def _moment_central_transform(self, order, **params): + + raw_moments = [] + for i in range(int(order) + 1): + methods = {'cache', 'formula', 'general'} + moment_i = self._moment_raw_dispatch(order=i, methods=methods, **params) + if moment_i is None: + return None + raw_moments.append(moment_i) + + mean_methods = self._moment_methods + mean = self._moment_raw_dispatch(self._one, methods=mean_methods, **params) + + moment = self._moment_transform_center(order, raw_moments, self._zero, mean) + return moment + + def _moment_central_normalize(self, order, **params): + methods = {'cache', 'formula', 'general'} + standard_moment = self._moment_standardized_dispatch(order, **params, + methods=methods) + if standard_moment is None: + return None + var = self._moment_central_dispatch(2, methods=self._moment_methods, **params) + return standard_moment*var**(order/2) + + def _moment_central_general(self, order, **params): + general_central_moments = {0: self._one, 1: self._zero} + return general_central_moments.get(order, None) + + def _moment_standardized(self, order=1, *, method=None): + """Standardized distribution moment.""" + methods = self._moment_methods if method is None else {method} + return self._moment_standardized_dispatch(order, methods=methods, + **self._parameters) + + def _moment_standardized_dispatch(self, order, *, methods, **params): + moment = None + + if 'cache' in methods: + moment = self._moment_standardized_cache.get(order, None) + + if moment is None and 'formula' in methods: + moment = self._moment_standardized_formula(order, **params) + + if moment is None and 'normalize' in methods: + moment = self._moment_standardized_normalize(order, False, **params) + + if moment is None and 'general' in methods: + moment = self._moment_standardized_general(order, **params) + + if moment is None and 'normalize' in methods: + moment = self._moment_standardized_normalize(order, True, **params) + + if moment is not None and self.cache_policy != _NO_CACHE: + self._moment_standardized_cache[order] = moment + + return moment + + def _moment_standardized_formula(self, order, **params): + return None + + def _moment_standardized_normalize(self, order, use_quadrature, **params): + methods = ({'quadrature'} if use_quadrature + else {'cache', 'formula', 'transform'}) + central_moment = self._moment_central_dispatch(order, **params, + methods=methods) + if central_moment is None: + return None + var = self._moment_central_dispatch(2, methods=self._moment_methods, + **params) + return central_moment/var**(order/2) + + def _moment_standardized_general(self, order, **params): + general_standard_moments = {0: self._one, 1: self._zero, 2: self._one} + return general_standard_moments.get(order, None) + + def _moment_integrate_pdf(self, order, center, **params): + def integrand(x, order, center, **params): + pdf = self._pdf_dispatch(x, **params) + return pdf*(x-center)**order + return self._quadrature(integrand, args=(order, center), params=params) + + def _moment_integrate_icdf(self, order, center, **params): + def integrand(x, order, center, **params): + x = self._icdf_dispatch(x, **params) + return (x-center)**order + return self._quadrature(integrand, limits=(0., 1.), + args=(order, center), params=params) + + def _moment_transform_center(self, order, moment_as, a, b): + a, b, *moment_as = np.broadcast_arrays(a, b, *moment_as) + n = order + i = np.arange(n+1).reshape([-1]+[1]*a.ndim) # orthogonal to other axes + i = self._preserve_type(i) + n_choose_i = special.binom(n, i) + with np.errstate(invalid='ignore'): # can happen with infinite moment + moment_b = np.sum(n_choose_i*moment_as*(a-b)**(n-i), axis=0) + return moment_b + + def _logmoment(self, order=1, *, logcenter=None, standardized=False): + # make this private until it is worked into moment + if logcenter is None or standardized is True: + logmean = self._logmoment_quad(self._one, -np.inf, **self._parameters) + else: + logmean = None + + logcenter = logmean if logcenter is None else logcenter + res = self._logmoment_quad(order, logcenter, **self._parameters) + if standardized: + logvar = self._logmoment_quad(2, logmean, **self._parameters) + res = res - logvar * (order/2) + return res + + def _logmoment_quad(self, order, logcenter, **params): + def logintegrand(x, order, logcenter, **params): + logpdf = self._logpdf_dispatch(x, **params) + return logpdf + order * _logexpxmexpy(np.log(x + 0j), logcenter) + ## if logx == logcenter, `_logexpxmexpy` returns (-inf + 0j) + ## multiplying by order produces (-inf + nan j) - bad + ## We're skipping logmoment tests, so we might don't need to fix + ## now, but if we ever do use run them, this might help: + # logx = np.log(x+0j) + # out = np.asarray(logpdf + order*_logexpxmexpy(logx, logcenter)) + # i = (logx == logcenter) + # out[i] = logpdf[i] + # return out + return self._quadrature(logintegrand, args=(order, logcenter), + params=params, log=True) + + ### Convenience + + def plot(self, x='x', y='pdf', *, t=('cdf', 0.0005, 0.9995), ax=None): + r"""Plot a function of the distribution. + + Convenience function for quick visualization of the distribution + underlying the random variable. + + Parameters + ---------- + x, y : str, optional + String indicating the quantities to be used as the abscissa and + ordinate (horizontal and vertical coordinates), respectively. + Defaults are ``'x'`` (the domain of the random variable) and + ``'pdf'`` (the probability density function). Valid values are: + 'x', 'pdf', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logpdf', 'logcdf', + 'logccdf', 'ilogcdf', 'ilogccdf'. + t : 3-tuple of (str, float, float), optional + Tuple indicating the limits within which the quantities are plotted. + Default is ``('cdf', 0.001, 0.999)`` indicating that the central + 99.9% of the distribution is to be shown. Valid values are: + 'x', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logcdf', 'logccdf', + 'ilogcdf', 'ilogccdf'. + ax : `matplotlib.axes`, optional + Axes on which to generate the plot. If not provided, use the + current axes. + + Returns + ------- + ax : `matplotlib.axes` + Axes on which the plot was generated. + The plot can be customized by manipulating this object. + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Plot the PDF over the central 99.9% of the distribution. + Compare against a histogram of a random sample. + + >>> ax = X.plot() + >>> sample = X.sample(10000) + >>> ax.hist(sample, density=True, bins=50, alpha=0.5) + >>> plt.show() + + Plot ``logpdf(x)`` as a function of ``x`` in the left tail, + where the log of the CDF is between -10 and ``np.log(0.5)``. + + >>> X.plot('x', 'logpdf', t=('logcdf', -10, np.log(0.5))) + >>> plt.show() + + Plot the PDF of the normal distribution as a function of the + CDF for various values of the scale parameter. + + >>> X = stats.Normal(mu=0., sigma=[0.5, 1., 2]) + >>> X.plot('cdf', 'pdf') + >>> plt.show() + + """ + + # Strategy: given t limits, get quantile limits. Form grid of + # quantiles, compute requested x and y at quantiles, and plot. + # Currently, the grid of quantiles is always linearly spaced. + # Instead of always computing linearly-spaced quantiles, it + # would be better to choose: + # a) quantiles or probabilities + # b) linearly or logarithmically spaced + # based on the specified `t`. + # TODO: + # - smart spacing of points + # - when the parameters of the distribution are an array, + # use the full range of abscissae for all curves + + t_is_quantile = {'x', 'icdf', 'iccdf', 'ilogcdf', 'ilogccdf'} + t_is_probability = {'cdf', 'ccdf', 'logcdf', 'logccdf'} + valid_t = t_is_quantile.union(t_is_probability) + valid_xy = valid_t.union({'pdf', 'logpdf'}) + + ndim = self._ndim + x_name, y_name = x, y + t_name, tlim = t[0], np.asarray(t[1:]) + tlim = tlim[:, np.newaxis] if ndim else tlim + + # pdf/logpdf are not valid for `t` because we can't easily invert them + message = (f'Argument `t` of `{self.__class__.__name__}.plot` "' + f'must be one of {valid_t}') + if t_name not in valid_t: + raise ValueError(message) + + message = (f'Argument `x` of `{self.__class__.__name__}.plot` "' + f'must be one of {valid_xy}') + if x_name not in valid_xy: + raise ValueError(message) + + message = (f'Argument `y` of `{self.__class__.__name__}.plot` "' + f'must be one of {valid_xy}') + if t_name not in valid_xy: + raise ValueError(message) + + # This could just be a warning + message = (f'`{self.__class__.__name__}.plot` was called on a random ' + 'variable with at least one invalid shape parameters. When ' + 'a parameter is invalid, no plot can be shown.') + if self._any_invalid: + raise ValueError(message) + + # We could automatically ravel, but do we want to? For now, raise. + message = ("To use `plot`, distribution parameters must be " + "scalars or arrays with one or fewer dimensions.") + if ndim > 1: + raise ValueError(message) + + try: + import matplotlib.pyplot as plt # noqa: F401, E402 + except ModuleNotFoundError as exc: + message = ("`matplotlib` must be installed to use " + f"`{self.__class__.__name__}.plot`.") + raise ModuleNotFoundError(message) from exc + ax = plt.gca() if ax is None else ax + + # get quantile limits given t limits + qlim = tlim if t_name in t_is_quantile else getattr(self, 'i'+t_name)(tlim) + + message = (f"`{self.__class__.__name__}.plot` received invalid input for `t`: " + f"calling {'i'+t_name}({tlim}) produced {qlim}.") + if not np.all(np.isfinite(qlim)): + raise ValueError(message) + + # form quantile grid + grid = np.linspace(0, 1, 300) + grid = grid[:, np.newaxis] if ndim else grid + q = qlim[0] + (qlim[1] - qlim[0]) * grid + + # compute requested x and y at quantile grid + x = q if x_name in t_is_quantile else getattr(self, x_name)(q) + y = q if y_name in t_is_quantile else getattr(self, y_name)(q) + + # make plot + ax.plot(x, y) + ax.set_xlabel(f"${x_name}$") + ax.set_ylabel(f"${y_name}$") + ax.set_title(str(self)) + + # only need a legend if distribution has parameters + if len(self._parameters): + label = [] + parameters = self._parameterization.parameters + param_names = list(parameters) + param_arrays = [np.atleast_1d(self._parameters[pname]) + for pname in param_names] + for param_vals in zip(*param_arrays): + assignments = [f"${parameters[name].symbol}$ = {val:.4g}" + for name, val in zip(param_names, param_vals)] + label.append(", ".join(assignments)) + ax.legend(label) + + return ax + + + ### Fitting + # All methods above treat the distribution parameters as fixed, and the + # variable argument may be a quantile or probability. The fitting functions + # are fundamentally different because the quantiles (often observations) + # are considered to be fixed, and the distribution parameters are the + # variables. In a sense, they are like an inverse of the sampling + # functions. + # + # At first glance, it would seem ideal for `fit` to be a classmethod, + # called like `LogUniform.fit(sample=sample)`. + # I tried this. I insisted on it for a while. But if `fit` is a + # classmethod, it cannot call instance methods. If we want to support MLE, + # MPS, MoM, MoLM, then we end up with most of the distribution functions + # above needing to be classmethods, too. All state information, such as + # tolerances and the underlying distribution of `ShiftedScaledDistribution` + # and `OrderStatisticDistribution`, would need to be passed into all + # methods. And I'm not really sure how we would call `fit` as a + # classmethod of a transformed distribution - maybe + # ShiftedScaledDistribution.fit would accept the class of the + # shifted/scaled distribution as an argument? + # + # In any case, it was a conscious decision for the infrastructure to + # treat the parameters as "fixed" and the quantile/percentile arguments + # as "variable". There are a lot of advantages to this structure, and I + # don't think the fact that a few methods reverse the fixed and variable + # quantities should make us question that choice. It can still accomodate + # these methods reasonably efficiently. + + +# Special case the names of some new-style distributions in `make_distribution` +_distribution_names = { + 'argus': 'ARGUS', + 'betaprime': 'BetaPrime', + 'chi2': 'ChiSquared', + 'crystalball': 'CrystalBall', + 'dgamma': 'DoubleGamma', + 'dweibull': 'DoubleWeibull', + 'expon': 'Exponential', + 'exponnorm': 'ExponentiallyModifiedNormal', + 'exponweib': 'ExponentialWeibull', + 'exponpow': 'ExponentialPower', + 'fatiguelife': 'FatigueLife', + 'foldcauchy': 'FoldedCauchy', + 'foldnorm': 'FoldedNormal', + 'genlogistic': 'GeneralizedLogistic', + 'gennorm': 'GeneralizedNormal', + 'genpareto': 'GeneralizedPareto', + 'genexpon': 'GeneralizedExponential', + 'genextreme': 'GeneralizedExtremeValue', + 'gausshyper': 'GaussHypergeometric', + 'gengamma': 'GeneralizedGamma', + 'genhalflogistic': 'GeneralizedHalfLogistic', + 'geninvgauss': 'GeneralizedInverseGaussian', + 'gumbel_r': 'Gumbel', + 'gumbel_l': 'ReflectedGumbel', + 'halfcauchy': 'HalfCauchy', + 'halflogistic': 'HalfLogistic', + 'halfnorm': 'HalfNormal', + 'halfgennorm': 'HalfGeneralizedNormal', + 'hypsecant': 'HyperbolicSecant', + 'invgamma': 'InverseGammma', + 'invgauss': 'InverseGaussian', + 'invweibull': 'InverseWeibull', + 'irwinhall': 'IrwinHall', + 'jf_skew_t': 'JonesFaddySkewT', + 'johnsonsb': 'JohnsonSB', + 'johnsonsu': 'JohnsonSU', + 'ksone': 'KSOneSided', + 'kstwo': 'KSTwoSided', + 'kstwobign': 'KSTwoSidedAsymptotic', + 'laplace_asymmetric': 'LaplaceAsymmetric', + 'levy_l': 'LevyLeft', + 'levy_stable': 'LevyStable', + 'loggamma': 'ExpGamma', # really the Exponential Gamma Distribution + 'loglaplace': 'LogLaplace', + 'lognorm': 'LogNormal', + 'loguniform': 'LogUniform', + 'ncx2': 'NoncentralChiSquared', + 'nct': 'NoncentralT', + 'norm': 'Normal', + 'norminvgauss': 'NormalInverseGaussian', + 'powerlaw': 'PowerLaw', + 'powernorm': 'PowerNormal', + 'rdist': 'R', + 'rel_breitwigner': 'RelativisticBreitWigner', + 'recipinvgauss': 'ReciprocalInverseGaussian', + 'reciprocal': 'LogUniform', + 'semicircular': 'SemiCircular', + 'skewcauchy': 'SkewCauchy', + 'skewnorm': 'SkewNormal', + 'studentized_range': 'StudentizedRange', + 't': 'StudentT', + 'trapezoid': 'Trapezoidal', + 'triang': 'Triangular', + 'truncexpon': 'TruncatedExponential', + 'truncnorm': 'TruncatedNormal', + 'truncpareto': 'TruncatedPareto', + 'truncweibull_min': 'TruncatedWeibull', + 'tukeylambda': 'TukeyLambda', + 'vonmises_line': 'VonMisesLine', + 'weibull_min': 'Weibull', + 'weibull_max': 'ReflectedWeibull', + 'wrapcauchy': 'WrappedCauchyLine', +} + + +# beta, genextreme, gengamma, t, tukeylambda need work for 1D arrays +def make_distribution(dist): + """Generate a `ContinuousDistribution` from an instance of `rv_continuous` + + The returned value is a `ContinuousDistribution` subclass. Like any subclass + of `ContinuousDistribution`, it must be instantiated (i.e. by passing all shape + parameters as keyword arguments) before use. Once instantiated, the resulting + object will have the same interface as any other instance of + `ContinuousDistribution`; e.g., `scipy.stats.Normal`. + + .. note:: + + `make_distribution` does not work perfectly with all instances of + `rv_continuous`. Known failures include `levy_stable` and `vonmises`, + and some methods of some distributions will not support array shape + parameters. + + Parameters + ---------- + dist : `rv_continuous` + Instance of `rv_continuous`. + + Returns + ------- + CustomDistribution : `ContinuousDistribution` + A subclass of `ContinuousDistribution` corresponding with `dist`. The + initializer requires all shape parameters to be passed as keyword arguments + (using the same names as the instance of `rv_continuous`). + + Notes + ----- + The documentation of `ContinuousDistribution` is not rendered. See below for + an example of how to instantiate the class (i.e. pass all shape parameters of + `dist` to the initializer as keyword arguments). Documentation of all methods + is identical to that of `scipy.stats.Normal`. Use ``help`` on the returned + class or its methods for more information. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> LogU = stats.make_distribution(stats.loguniform) + >>> X = LogU(a=1.0, b=3.0) + >>> np.isclose((X + 0.25).median(), stats.loguniform.ppf(0.5, 1, 3, loc=0.25)) + np.True_ + >>> X.plot() + >>> sample = X.sample(10000, rng=np.random.default_rng()) + >>> plt.hist(sample, density=True, bins=30) + >>> plt.legend(('pdf', 'histogram')) + >>> plt.show() + + """ + if dist in {stats.levy_stable, stats.vonmises}: + raise NotImplementedError(f"`{dist.name}` is not supported.") + + if not isinstance(dist, stats.rv_continuous): + message = "The argument must be an instance of `rv_continuous`." + raise ValueError(message) + + parameters = [] + names = [] + support = getattr(dist, '_support', (dist.a, dist.b)) + for shape_info in dist._shape_info(): + domain = _RealDomain(endpoints=shape_info.endpoints, + inclusive=shape_info.inclusive) + param = _RealParameter(shape_info.name, domain=domain) + parameters.append(param) + names.append(shape_info.name) + + _x_support = _RealDomain(endpoints=support, inclusive=(True, True)) + _x_param = _RealParameter('x', domain=_x_support, typical=(-1, 1)) + + repr_str = _distribution_names.get(dist.name, dist.name.capitalize()) + + class CustomDistribution(ContinuousDistribution): + _parameterizations = ([_Parameterization(*parameters)] if parameters + else []) + _variable = _x_param + + def __repr__(self): + s = super().__repr__() + return s.replace('CustomDistribution', repr_str) + + def __str__(self): + s = super().__str__() + return s.replace('CustomDistribution', repr_str) + + # override the domain's `get_numerical_endpoints` rather than the + # distribution's `_support` to ensure that `_support` takes care + # of any required broadcasting, etc. + def get_numerical_endpoints(parameter_values): + a, b = dist._get_support(**parameter_values) + return np.asarray(a)[()], np.asarray(b)[()] + + def _sample_formula(self, _, full_shape=(), *, rng=None, **kwargs): + return dist._rvs(size=full_shape, random_state=rng, **kwargs) + + def _moment_raw_formula(self, order, **kwargs): + return dist._munp(int(order), **kwargs) + + def _moment_raw_formula_1(self, order, **kwargs): + if order != 1: + return None + return dist._stats(**kwargs)[0] + + def _moment_central_formula(self, order, **kwargs): + if order != 2: + return None + return dist._stats(**kwargs)[1] + + def _moment_standard_formula(self, order, **kwargs): + if order == 3: + if dist._stats_has_moments: + kwargs['moments'] = 's' + return dist._stats(**kwargs)[int(order - 1)] + elif order == 4: + if dist._stats_has_moments: + kwargs['moments'] = 'k' + k = dist._stats(**kwargs)[int(order - 1)] + return k if k is None else k + 3 + else: + return None + + methods = {'_logpdf': '_logpdf_formula', + '_pdf': '_pdf_formula', + '_logcdf': '_logcdf_formula', + '_cdf': '_cdf_formula', + '_logsf': '_logccdf_formula', + '_sf': '_ccdf_formula', + '_ppf': '_icdf_formula', + '_isf': '_iccdf_formula', + '_entropy': '_entropy_formula', + '_median': '_median_formula'} + + # These are not desirable overrides for the new infrastructure + skip_override = {'norminvgauss': {'_sf', '_isf'}} + + for old_method, new_method in methods.items(): + if dist.name in skip_override and old_method in skip_override[dist.name]: + continue + # If method of old distribution overrides generic implementation... + method = getattr(dist.__class__, old_method, None) + super_method = getattr(stats.rv_continuous, old_method, None) + if method is not super_method: + # Make it an attribute of the new object with the new name + setattr(CustomDistribution, new_method, getattr(dist, old_method)) + + def _overrides(method_name): + return (getattr(dist.__class__, method_name, None) + is not getattr(stats.rv_continuous, method_name, None)) + + if _overrides('_get_support'): + domain = CustomDistribution._variable.domain + domain.get_numerical_endpoints = get_numerical_endpoints + + if _overrides('_munp'): + CustomDistribution._moment_raw_formula = _moment_raw_formula + + if _overrides('_rvs'): + CustomDistribution._sample_formula = _sample_formula + + if _overrides('_stats'): + CustomDistribution._moment_standardized_formula = _moment_standard_formula + if not _overrides('_munp'): + CustomDistribution._moment_raw_formula = _moment_raw_formula_1 + CustomDistribution._moment_central_formula = _moment_central_formula + + support_etc = _combine_docs(CustomDistribution, include_examples=False).lstrip() + docs = [ + f"This class represents `scipy.stats.{dist.name}` as a subclass of " + "`ContinuousDistribution`.", + f"The `repr`/`str` of class instances is `{repr_str}`.", + f"The PDF of the distribution is defined {support_etc}" + ] + CustomDistribution.__doc__ = ("\n".join(docs)) + + return CustomDistribution + + +# Rough sketch of how we might shift/scale distributions. The purpose of +# making it a separate class is for +# a) simplicity of the ContinuousDistribution class and +# b) avoiding the requirement that every distribution accept loc/scale. +# The simplicity of ContinuousDistribution is important, because there are +# several other distribution transformations to be supported; e.g., truncation, +# wrapping, folding, and doubling. We wouldn't want to cram all of this +# into the `ContinuousDistribution` class. Also, the order of the composition +# matters (e.g. truncate then shift/scale or vice versa). It's easier to +# accommodate different orders if the transformation is built up from +# components rather than all built into `ContinuousDistribution`. + +def _shift_scale_distribution_function_2arg(func): + def wrapped(self, x, y, *args, loc, scale, sign, **kwargs): + item = func.__name__ + + f = getattr(self._dist, item) + + # Obviously it's possible to get away with half of the work here. + # Let's focus on correct results first and optimize later. + xt = self._transform(x, loc, scale) + yt = self._transform(y, loc, scale) + fxy = f(xt, yt, *args, **kwargs) + fyx = f(yt, xt, *args, **kwargs) + return np.real_if_close(np.where(sign, fxy, fyx))[()] + + return wrapped + +def _shift_scale_distribution_function(func): + # c is for complementary + citem = {'_logcdf_dispatch': '_logccdf_dispatch', + '_cdf_dispatch': '_ccdf_dispatch', + '_logccdf_dispatch': '_logcdf_dispatch', + '_ccdf_dispatch': '_cdf_dispatch'} + def wrapped(self, x, *args, loc, scale, sign, **kwargs): + item = func.__name__ + + f = getattr(self._dist, item) + cf = getattr(self._dist, citem[item]) + + # Obviously it's possible to get away with half of the work here. + # Let's focus on correct results first and optimize later. + xt = self._transform(x, loc, scale) + fx = f(xt, *args, **kwargs) + cfx = cf(xt, *args, **kwargs) + return np.where(sign, fx, cfx)[()] + + return wrapped + +def _shift_scale_inverse_function(func): + citem = {'_ilogcdf_dispatch': '_ilogccdf_dispatch', + '_icdf_dispatch': '_iccdf_dispatch', + '_ilogccdf_dispatch': '_ilogcdf_dispatch', + '_iccdf_dispatch': '_icdf_dispatch'} + def wrapped(self, p, *args, loc, scale, sign, **kwargs): + item = func.__name__ + + f = getattr(self._dist, item) + cf = getattr(self._dist, citem[item]) + + # Obviously it's possible to get away with half of the work here. + # Let's focus on correct results first and optimize later. + fx = self._itransform(f(p, *args, **kwargs), loc, scale) + cfx = self._itransform(cf(p, *args, **kwargs), loc, scale) + return np.where(sign, fx, cfx)[()] + + return wrapped + + +class TransformedDistribution(ContinuousDistribution): + def __init__(self, X, /, *args, **kwargs): + self._copy_parameterization() + self._variable = X._variable + self._dist = X + if X._parameterization: + # Add standard distribution parameters to our parameterization + dist_parameters = X._parameterization.parameters + set_params = set(dist_parameters) + if not self._parameterizations: + self._parameterizations.append(_Parameterization()) + for parameterization in self._parameterizations: + if set_params.intersection(parameterization.parameters): + message = (f"One or more of the parameters of {X} has " + "the same name as a parameter of " + f"{self.__class__.__name__}. Name collisions " + "create ambiguities and are not supported.") + raise ValueError(message) + parameterization.parameters.update(dist_parameters) + super().__init__(*args, **kwargs) + + def _overrides(self, method_name): + return (self._dist._overrides(method_name) + or super()._overrides(method_name)) + + def reset_cache(self): + self._dist.reset_cache() + super().reset_cache() + + def _update_parameters(self, *, validation_policy=None, **params): + # maybe broadcast everything before processing? + parameters = {} + # There may be some issues with _original_parameters + # We only want to update with _dist._original_parameters during + # initialization. Afterward that, we want to start with + # self._original_parameters. + parameters.update(self._dist._original_parameters) + parameters.update(params) + super()._update_parameters(validation_policy=validation_policy, **parameters) + + def _process_parameters(self, **params): + return self._dist._process_parameters(**params) + + def __repr__(self): + raise NotImplementedError() + + def __str__(self): + raise NotImplementedError() + + +class TruncatedDistribution(TransformedDistribution): + """Truncated distribution.""" + # TODO: + # - consider avoiding catastropic cancellation by using appropriate tail + # - if the mode of `_dist` is within the support, it's still the mode + # - rejection sampling might be more efficient than inverse transform + + _lb_domain = _RealDomain(endpoints=(-inf, 'ub'), inclusive=(True, False)) + _lb_param = _RealParameter('lb', symbol=r'b_l', + domain=_lb_domain, typical=(0.1, 0.2)) + + _ub_domain = _RealDomain(endpoints=('lb', inf), inclusive=(False, True)) + _ub_param = _RealParameter('ub', symbol=r'b_u', + domain=_ub_domain, typical=(0.8, 0.9)) + + _parameterizations = [_Parameterization(_lb_param, _ub_param), + _Parameterization(_lb_param), + _Parameterization(_ub_param)] + + def __init__(self, X, /, *args, lb=-np.inf, ub=np.inf, **kwargs): + return super().__init__(X, *args, lb=lb, ub=ub, **kwargs) + + def _process_parameters(self, lb=None, ub=None, **params): + lb = lb if lb is not None else np.full_like(lb, -np.inf)[()] + ub = ub if ub is not None else np.full_like(ub, np.inf)[()] + parameters = self._dist._process_parameters(**params) + a, b = self._support(lb=lb, ub=ub, **parameters) + logmass = self._dist._logcdf2_dispatch(a, b, **parameters) + parameters.update(dict(lb=lb, ub=ub, _a=a, _b=b, logmass=logmass)) + return parameters + + def _support(self, lb, ub, **params): + a, b = self._dist._support(**params) + return np.maximum(a, lb), np.minimum(b, ub) + + def _overrides(self, method_name): + return False + + def _logpdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params): + logpdf = self._dist._logpdf_dispatch(x, *args, **params) + return logpdf - logmass + + def _logcdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params): + logcdf = self._dist._logcdf2_dispatch(_a, x, *args, **params) + # of course, if this result is small we could compute with the other tail + return logcdf - logmass + + def _logccdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params): + logccdf = self._dist._logcdf2_dispatch(x, _b, *args, **params) + return logccdf - logmass + + def _logcdf2_dispatch(self, x, y, *args, lb, ub, _a, _b, logmass, **params): + logcdf2 = self._dist._logcdf2_dispatch(x, y, *args, **params) + return logcdf2 - logmass + + def _ilogcdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params): + log_Fa = self._dist._logcdf_dispatch(_a, *args, **params) + logp_adjusted = np.logaddexp(log_Fa, logp + logmass) + return self._dist._ilogcdf_dispatch(logp_adjusted, *args, **params) + + def _ilogccdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params): + log_cFb = self._dist._logccdf_dispatch(_b, *args, **params) + logp_adjusted = np.logaddexp(log_cFb, logp + logmass) + return self._dist._ilogccdf_dispatch(logp_adjusted, *args, **params) + + def _icdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params): + Fa = self._dist._cdf_dispatch(_a, *args, **params) + p_adjusted = Fa + p*np.exp(logmass) + return self._dist._icdf_dispatch(p_adjusted, *args, **params) + + def _iccdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params): + cFb = self._dist._ccdf_dispatch(_b, *args, **params) + p_adjusted = cFb + p*np.exp(logmass) + return self._dist._iccdf_dispatch(p_adjusted, *args, **params) + + def __repr__(self): + with np.printoptions(threshold=10): + return (f"truncate({repr(self._dist)}, " + f"lb={repr(self.lb)}, ub={repr(self.ub)})") + + def __str__(self): + with np.printoptions(threshold=10): + return (f"truncate({str(self._dist)}, " + f"lb={str(self.lb)}, ub={str(self.ub)})") + + +def truncate(X, lb=-np.inf, ub=np.inf): + """Truncate the support of a random variable. + + Given a random variable `X`, `truncate` returns a random variable with + support truncated to the interval between `lb` and `ub`. The underlying + probability density function is normalized accordingly. + + Parameters + ---------- + X : `ContinuousDistribution` + The random variable to be truncated. + lb, ub : float array-like + The lower and upper truncation points, respectively. Must be + broadcastable with one another and the shape of `X`. + + Returns + ------- + X : `ContinuousDistribution` + The truncated random variable. + + References + ---------- + .. [1] "Truncated Distribution". *Wikipedia*. + https://en.wikipedia.org/wiki/Truncated_distribution + + Examples + -------- + Compare against `scipy.stats.truncnorm`, which truncates a standard normal, + *then* shifts and scales it. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> loc, scale, lb, ub = 1, 2, -2, 2 + >>> X = stats.truncnorm(lb, ub, loc, scale) + >>> Y = scale * stats.truncate(stats.Normal(), lb, ub) + loc + >>> x = np.linspace(-3, 5, 300) + >>> plt.plot(x, X.pdf(x), '-', label='X') + >>> plt.plot(x, Y.pdf(x), '--', label='Y') + >>> plt.xlabel('x') + >>> plt.ylabel('PDF') + >>> plt.title('Truncated, then Shifted/Scaled Normal') + >>> plt.legend() + >>> plt.show() + + However, suppose we wish to shift and scale a normal random variable, + then truncate its support to given values. This is straightforward with + `truncate`. + + >>> Z = stats.truncate(scale * stats.Normal() + loc, lb, ub) + >>> Z.plot() + >>> plt.show() + + Furthermore, `truncate` can be applied to any random variable: + + >>> Rayleigh = stats.make_distribution(stats.rayleigh) + >>> W = stats.truncate(Rayleigh(), lb=0, ub=3) + >>> W.plot() + >>> plt.show() + + """ + return TruncatedDistribution(X, lb=lb, ub=ub) + + +class ShiftedScaledDistribution(TransformedDistribution): + """Distribution with a standard shift/scale transformation.""" + # Unclear whether infinite loc/scale will work reasonably in all cases + _loc_domain = _RealDomain(endpoints=(-inf, inf), inclusive=(True, True)) + _loc_param = _RealParameter('loc', symbol=r'\mu', + domain=_loc_domain, typical=(1, 2)) + + _scale_domain = _RealDomain(endpoints=(-inf, inf), inclusive=(True, True)) + _scale_param = _RealParameter('scale', symbol=r'\sigma', + domain=_scale_domain, typical=(0.1, 10)) + + _parameterizations = [_Parameterization(_loc_param, _scale_param), + _Parameterization(_loc_param), + _Parameterization(_scale_param)] + + def _process_parameters(self, loc=None, scale=None, **params): + loc = loc if loc is not None else np.zeros_like(scale)[()] + scale = scale if scale is not None else np.ones_like(loc)[()] + sign = scale > 0 + parameters = self._dist._process_parameters(**params) + parameters.update(dict(loc=loc, scale=scale, sign=sign)) + return parameters + + def _transform(self, x, loc, scale, **kwargs): + return (x - loc)/scale + + def _itransform(self, x, loc, scale, **kwargs): + return x * scale + loc + + def _support(self, loc, scale, sign, **params): + # Add shortcut for infinite support? + a, b = self._dist._support(**params) + a, b = self._itransform(a, loc, scale), self._itransform(b, loc, scale) + return np.where(sign, a, b)[()], np.where(sign, b, a)[()] + + def __repr__(self): + with np.printoptions(threshold=10): + result = f"{repr(self.scale)}*{repr(self._dist)}" + if not self.loc.ndim and self.loc < 0: + result += f" - {repr(-self.loc)}" + elif (np.any(self.loc != 0) + or not np.can_cast(self.loc.dtype, self.scale.dtype)): + # We don't want to hide a zero array loc if it can cause + # a type promotion. + result += f" + {repr(self.loc)}" + return result + + def __str__(self): + with np.printoptions(threshold=10): + result = f"{str(self.scale)}*{str(self._dist)}" + if not self.loc.ndim and self.loc < 0: + result += f" - {str(-self.loc)}" + elif (np.any(self.loc != 0) + or not np.can_cast(self.loc.dtype, self.scale.dtype)): + # We don't want to hide a zero array loc if it can cause + # a type promotion. + result += f" + {str(self.loc)}" + return result + + # Here, we override all the `_dispatch` methods rather than the public + # methods or _function methods. Why not the public methods? + # If we were to override the public methods, then other + # TransformedDistribution classes (which could transform a + # ShiftedScaledDistribution) would need to call the public methods of + # ShiftedScaledDistribution, which would run the input validation again. + # Why not the _function methods? For distributions that rely on the + # default implementation of methods (e.g. `quadrature`, `inversion`), + # the implementation would "see" the location and scale like other + # distribution parameters, so they could affect the accuracy of the + # calculations. I think it is cleaner if `loc` and `scale` do not affect + # the underlying calculations at all. + + def _entropy_dispatch(self, *args, loc, scale, sign, **params): + return (self._dist._entropy_dispatch(*args, **params) + + np.log(np.abs(scale))) + + def _logentropy_dispatch(self, *args, loc, scale, sign, **params): + lH0 = self._dist._logentropy_dispatch(*args, **params) + lls = np.log(np.log(np.abs(scale))+0j) + return special.logsumexp(np.broadcast_arrays(lH0, lls), axis=0) + + def _median_dispatch(self, *, method, loc, scale, sign, **params): + raw = self._dist._median_dispatch(method=method, **params) + return self._itransform(raw, loc, scale) + + def _mode_dispatch(self, *, method, loc, scale, sign, **params): + raw = self._dist._mode_dispatch(method=method, **params) + return self._itransform(raw, loc, scale) + + def _logpdf_dispatch(self, x, *args, loc, scale, sign, **params): + x = self._transform(x, loc, scale) + logpdf = self._dist._logpdf_dispatch(x, *args, **params) + return logpdf - np.log(np.abs(scale)) + + def _pdf_dispatch(self, x, *args, loc, scale, sign, **params): + x = self._transform(x, loc, scale) + pdf = self._dist._pdf_dispatch(x, *args, **params) + return pdf / np.abs(scale) + + # Sorry about the magic. This is just a draft to show the behavior. + @_shift_scale_distribution_function + def _logcdf_dispatch(self, x, *, method=None, **params): + pass + + @_shift_scale_distribution_function + def _cdf_dispatch(self, x, *, method=None, **params): + pass + + @_shift_scale_distribution_function + def _logccdf_dispatch(self, x, *, method=None, **params): + pass + + @_shift_scale_distribution_function + def _ccdf_dispatch(self, x, *, method=None, **params): + pass + + @_shift_scale_distribution_function_2arg + def _logcdf2_dispatch(self, x, y, *, method=None, **params): + pass + + @_shift_scale_distribution_function_2arg + def _cdf2_dispatch(self, x, y, *, method=None, **params): + pass + + @_shift_scale_distribution_function_2arg + def _logccdf2_dispatch(self, x, y, *, method=None, **params): + pass + + @_shift_scale_distribution_function_2arg + def _ccdf2_dispatch(self, x, y, *, method=None, **params): + pass + + @_shift_scale_inverse_function + def _ilogcdf_dispatch(self, x, *, method=None, **params): + pass + + @_shift_scale_inverse_function + def _icdf_dispatch(self, x, *, method=None, **params): + pass + + @_shift_scale_inverse_function + def _ilogccdf_dispatch(self, x, *, method=None, **params): + pass + + @_shift_scale_inverse_function + def _iccdf_dispatch(self, x, *, method=None, **params): + pass + + def _moment_standardized_dispatch(self, order, *, loc, scale, sign, methods, + **params): + res = (self._dist._moment_standardized_dispatch( + order, methods=methods, **params)) + return None if res is None else res * np.sign(scale)**order + + def _moment_central_dispatch(self, order, *, loc, scale, sign, methods, + **params): + res = (self._dist._moment_central_dispatch( + order, methods=methods, **params)) + return None if res is None else res * scale**order + + def _moment_raw_dispatch(self, order, *, loc, scale, sign, methods, + **params): + raw_moments = [] + methods_highest_order = methods + for i in range(int(order) + 1): + methods = (self._moment_methods if i < order + else methods_highest_order) + raw = self._dist._moment_raw_dispatch(i, methods=methods, **params) + if raw is None: + return None + moment_i = raw * scale**i + raw_moments.append(moment_i) + + return self._moment_transform_center( + order, raw_moments, loc, self._zero) + + def _sample_dispatch(self, sample_shape, full_shape, *, + rng, loc, scale, sign, method, **params): + rvs = self._dist._sample_dispatch( + sample_shape, full_shape, method=method, rng=rng, **params) + return self._itransform(rvs, loc=loc, scale=scale, sign=sign, **params) + + def __add__(self, loc): + return ShiftedScaledDistribution(self._dist, loc=self.loc + loc, + scale=self.scale) + + def __sub__(self, loc): + return ShiftedScaledDistribution(self._dist, loc=self.loc - loc, + scale=self.scale) + + def __mul__(self, scale): + return ShiftedScaledDistribution(self._dist, + loc=self.loc * scale, + scale=self.scale * scale) + + def __truediv__(self, scale): + return ShiftedScaledDistribution(self._dist, + loc=self.loc / scale, + scale=self.scale / scale) + + +class OrderStatisticDistribution(TransformedDistribution): + r"""Probability distribution of an order statistic + + An instance of this class represents a random variable that follows the + distribution underlying the :math:`r^{\text{th}}` order statistic of a + sample of :math:`n` observations of a random variable :math:`X`. + + Parameters + ---------- + dist : `ContinuousDistribution` + The random variable :math:`X` + n : array_like + The (integer) sample size :math:`n` + r : array_like + The (integer) rank of the order statistic :math:`r` + + + Notes + ----- + If we make :math:`n` observations of a continuous random variable + :math:`X` and sort them in increasing order + :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`, + :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic. + + If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`, + :math:`F`, and :math:`F'`, respectively, then the PDF underlying + math:`X_{(r)}` is given by: + + .. math:: + + f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r} + + The CDF and other methods of the distribution underlying :math:`X_{(r)}` + are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is + a standard uniform random variable, and that the order statistics of + observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`. + + References + ---------- + .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic + + Examples + -------- + Suppose we are interested in order statistics of samples of size five drawn + from the standard normal distribution. Plot the PDF underlying the fourth + order statistic and compare with a normalized histogram from simulation. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> from scipy.stats._distribution_infrastructure import OrderStatisticDistribution + >>> + >>> X = stats.Normal() + >>> data = X.sample(shape=(10000, 5)) + >>> ranks = np.sort(data, axis=1) + >>> Y = OrderStatisticDistribution(X, r=4, n=5) + >>> + >>> ax = plt.gca() + >>> Y.plot(ax=ax) + >>> ax.hist(ranks[:, 3], density=True, bins=30) + >>> plt.show() + + """ + + # These can be restricted to _IntegerDomain/_IntegerParameter in a separate + # PR if desired. + _r_domain = _RealDomain(endpoints=(1, 'n'), inclusive=(True, True)) + _r_param = _RealParameter('r', domain=_r_domain, typical=(1, 2)) + + _n_domain = _RealDomain(endpoints=(1, np.inf), inclusive=(True, True)) + _n_param = _RealParameter('n', domain=_n_domain, typical=(1, 4)) + + _r_domain.define_parameters(_n_param) + + _parameterizations = [_Parameterization(_r_param, _n_param)] + + def __init__(self, dist, /, *args, r, n, **kwargs): + super().__init__(dist, *args, r=r, n=n, **kwargs) + + def _support(self, *args, r, n, **kwargs): + return self._dist._support(*args, **kwargs) + + def _process_parameters(self, r=None, n=None, **params): + parameters = self._dist._process_parameters(**params) + parameters.update(dict(r=r, n=n)) + return parameters + + def _overrides(self, method_name): + return method_name in {'_logpdf_formula', '_pdf_formula', + '_cdf_formula', '_ccdf_formula', + '_icdf_formula', '_iccdf_formula'} + + def _logpdf_formula(self, x, r, n, **kwargs): + log_factor = special.betaln(r, n - r + 1) + log_fX = self._dist._logpdf_dispatch(x, **kwargs) + # log-methods sometimes use complex dtype with 0 imaginary component, + # but `_tanhsinh` doesn't accept complex limits of integration; take `real`. + log_FX = self._dist._logcdf_dispatch(x.real, **kwargs) + log_cFX = self._dist._logccdf_dispatch(x.real, **kwargs) + # This can be problematic when (r - 1)|(n-r) = 0 and `log_FX`|log_cFX = -inf + # The PDF in these cases is 0^0, so these should be replaced with log(1)=0 + # return log_fX + (r-1)*log_FX + (n-r)*log_cFX - log_factor + rm1_log_FX = np.where((r - 1 == 0) & np.isneginf(log_FX), 0, (r-1)*log_FX) + nmr_log_cFX = np.where((n - r == 0) & np.isneginf(log_cFX), 0, (n-r)*log_cFX) + return log_fX + rm1_log_FX + nmr_log_cFX - log_factor + + def _pdf_formula(self, x, r, n, **kwargs): + # 1 / factor = factorial(n) / (factorial(r-1) * factorial(n-r)) + factor = special.beta(r, n - r + 1) + fX = self._dist._pdf_dispatch(x, **kwargs) + FX = self._dist._cdf_dispatch(x, **kwargs) + cFX = self._dist._ccdf_dispatch(x, **kwargs) + return fX * FX**(r-1) * cFX**(n-r) / factor + + def _cdf_formula(self, x, r, n, **kwargs): + x_ = self._dist._cdf_dispatch(x, **kwargs) + return special.betainc(r, n-r+1, x_) + + def _ccdf_formula(self, x, r, n, **kwargs): + x_ = self._dist._cdf_dispatch(x, **kwargs) + return special.betaincc(r, n-r+1, x_) + + def _icdf_formula(self, p, r, n, **kwargs): + p_ = special.betaincinv(r, n-r+1, p) + return self._dist._icdf_dispatch(p_, **kwargs) + + def _iccdf_formula(self, p, r, n, **kwargs): + p_ = special.betainccinv(r, n-r+1, p) + return self._dist._icdf_dispatch(p_, **kwargs) + + def __repr__(self): + with np.printoptions(threshold=10): + return (f"order_statistic({repr(self._dist)}, r={repr(self.r)}, " + f"n={repr(self.n)})") + + def __str__(self): + with np.printoptions(threshold=10): + return (f"order_statistic({str(self._dist)}, r={str(self.r)}, " + f"n={str(self.n)})") + + +def order_statistic(X, /, *, r, n): + r"""Probability distribution of an order statistic + + Returns a random variable that follows the distribution underlying the + :math:`r^{\text{th}}` order statistic of a sample of :math:`n` + observations of a random variable :math:`X`. + + Parameters + ---------- + X : `ContinuousDistribution` + The random variable :math:`X` + r : array_like + The (positive integer) rank of the order statistic :math:`r` + n : array_like + The (positive integer) sample size :math:`n` + + Returns + ------- + Y : `ContinuousDistribution` + A random variable that follows the distribution of the prescribed + order statistic. + + Notes + ----- + If we make :math:`n` observations of a continuous random variable + :math:`X` and sort them in increasing order + :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`, + :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic. + + If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`, + :math:`F`, and :math:`F'`, respectively, then the PDF underlying + math:`X_{(r)}` is given by: + + .. math:: + + f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r} + + The CDF and other methods of the distribution underlying :math:`X_{(r)}` + are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is + a standard uniform random variable, and that the order statistics of + observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`. + + References + ---------- + .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic + + Examples + -------- + Suppose we are interested in order statistics of samples of size five drawn + from the standard normal distribution. Plot the PDF underlying each + order statistic and compare with a normalized histogram from simulation. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> + >>> X = stats.Normal() + >>> data = X.sample(shape=(10000, 5)) + >>> sorted = np.sort(data, axis=1) + >>> Y = stats.order_statistic(X, r=[1, 2, 3, 4, 5], n=5) + >>> + >>> ax = plt.gca() + >>> colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] + >>> for i in range(5): + ... y = sorted[:, i] + ... ax.hist(y, density=True, bins=30, alpha=0.1, color=colors[i]) + >>> Y.plot(ax=ax) + >>> plt.show() + + """ + r, n = np.asarray(r), np.asarray(n) + if np.any((r != np.floor(r)) | (r < 0)) or np.any((n != np.floor(n)) | (n < 0)): + message = "`r` and `n` must contain only positive integers." + raise ValueError(message) + return OrderStatisticDistribution(X, r=r, n=n) + + +class Mixture(_ProbabilityDistribution): + r"""Representation of a mixture distribution. + + A mixture distribution is the distribution of a random variable + defined in the following way: first, a random variable is selected + from `components` according to the probabilities given by `weights`, then + the selected random variable is realized. + + Parameters + ---------- + components : sequence of `ContinuousDistribution` + The underlying instances of `ContinuousDistribution`. + All must have scalar shape parameters (if any); e.g., the `pdf` evaluated + at a scalar argument must return a scalar. + weights : sequence of floats, optional + The corresponding probabilities of selecting each random variable. + Must be non-negative and sum to one. The default behavior is to weight + all components equally. + + Attributes + ---------- + components : sequence of `ContinuousDistribution` + The underlying instances of `ContinuousDistribution`. + weights : ndarray + The corresponding probabilities of selecting each random variable. + + Methods + ------- + support + + sample + + moment + + mean + median + mode + + variance + standard_deviation + + skewness + kurtosis + + pdf + logpdf + + cdf + icdf + ccdf + iccdf + + logcdf + ilogcdf + logccdf + ilogccdf + + entropy + + Notes + ----- + The following abbreviations are used throughout the documentation. + + - PDF: probability density function + - CDF: cumulative distribution function + - CCDF: complementary CDF + - entropy: differential entropy + - log-*F*: logarithm of *F* (e.g. log-CDF) + - inverse *F*: inverse function of *F* (e.g. inverse CDF) + + References + ---------- + .. [1] Mixture distribution, *Wikipedia*, + https://en.wikipedia.org/wiki/Mixture_distribution + + """ + # Todo: + # Add support for array shapes, weights + + def _input_validation(self, components, weights): + if len(components) == 0: + message = ("`components` must contain at least one random variable.") + raise ValueError(message) + + for var in components: + # will generalize to other kinds of distributions when there + # *are* other kinds of distributions + if not isinstance(var, ContinuousDistribution): + message = ("Each element of `components` must be an instance of " + "`ContinuousDistribution`.") + raise ValueError(message) + if not var._shape == (): + message = "All elements of `components` must have scalar shapes." + raise ValueError(message) + + if weights is None: + return components, weights + + weights = np.asarray(weights) + if weights.shape != (len(components),): + message = "`components` and `weights` must have the same length." + raise ValueError(message) + + if not np.issubdtype(weights.dtype, np.inexact): + message = "`weights` must have floating point dtype." + raise ValueError(message) + + if not np.isclose(np.sum(weights), 1.0): + message = "`weights` must sum to 1.0." + raise ValueError(message) + + if not np.all(weights >= 0): + message = "All `weights` must be non-negative." + raise ValueError(message) + + return components, weights + + def __init__(self, components, *, weights=None): + components, weights = self._input_validation(components, weights) + n = len(components) + dtype = np.result_type(*(var._dtype for var in components)) + self._shape = np.broadcast_shapes(*(var._shape for var in components)) + self._dtype, self._components = dtype, components + self._weights = np.full(n, 1/n, dtype=dtype) if weights is None else weights + self.validation_policy = None + + @property + def components(self): + return list(self._components) + + @property + def weights(self): + return self._weights.copy() + + def _full(self, val, *args): + args = [np.asarray(arg) for arg in args] + dtype = np.result_type(self._dtype, *(arg.dtype for arg in args)) + shape = np.broadcast_shapes(self._shape, *(arg.shape for arg in args)) + return np.full(shape, val, dtype=dtype) + + def _sum(self, fun, *args): + out = self._full(0, *args) + for var, weight in zip(self._components, self._weights): + out += getattr(var, fun)(*args) * weight + return out[()] + + def _logsum(self, fun, *args): + out = self._full(-np.inf, *args) + for var, log_weight in zip(self._components, np.log(self._weights)): + np.logaddexp(out, getattr(var, fun)(*args) + log_weight, out=out) + return out[()] + + def support(self): + a = self._full(np.inf) + b = self._full(-np.inf) + for var in self._components: + a = np.minimum(a, var.support()[0]) + b = np.maximum(b, var.support()[1]) + return a, b + + def _raise_if_method(self, method): + if method is not None: + raise NotImplementedError("`method` not implemented for this distribution.") + + def logentropy(self, *, method=None): + self._raise_if_method(method) + def log_integrand(x): + # `x` passed by `_tanhsinh` will be of complex dtype because + # `log_integrand` returns complex values, but the imaginary + # component is always zero. Extract the real part because + # `logpdf` uses `logaddexp`, which fails for complex input. + return self.logpdf(x.real) + np.log(self.logpdf(x.real) + 0j) + + res = _tanhsinh(log_integrand, *self.support(), log=True).integral + return _log_real_standardize(res + np.pi*1j) + + def entropy(self, *, method=None): + self._raise_if_method(method) + return _tanhsinh(lambda x: -self.pdf(x) * self.logpdf(x), + *self.support()).integral + + def mode(self, *, method=None): + self._raise_if_method(method) + a, b = self.support() + def f(x): return -self.pdf(x) + res = _bracket_minimum(f, 1., xmin=a, xmax=b) + res = _chandrupatla_minimize(f, res.xl, res.xm, res.xr) + return res.x + + def median(self, *, method=None): + self._raise_if_method(method) + return self.icdf(0.5) + + def mean(self, *, method=None): + self._raise_if_method(method) + return self._sum('mean') + + def variance(self, *, method=None): + self._raise_if_method(method) + return self._moment_central(2) + + def standard_deviation(self, *, method=None): + self._raise_if_method(method) + return self.variance()**0.5 + + def skewness(self, *, method=None): + self._raise_if_method(method) + return self._moment_standardized(3) + + def kurtosis(self, *, method=None): + self._raise_if_method(method) + return self._moment_standardized(4) + + def moment(self, order=1, kind='raw', *, method=None): + self._raise_if_method(method) + kinds = {'raw': self._moment_raw, + 'central': self._moment_central, + 'standardized': self._moment_standardized} + order = ContinuousDistribution._validate_order_kind(self, order, kind, kinds) + moment_kind = kinds[kind] + return moment_kind(order) + + def _moment_raw(self, order): + out = self._full(0) + for var, weight in zip(self._components, self._weights): + out += var.moment(order, kind='raw') * weight + return out[()] + + def _moment_central(self, order): + order = int(order) + out = self._full(0) + for var, weight in zip(self._components, self._weights): + moment_as = [var.moment(order, kind='central') + for order in range(order + 1)] + a, b = var.mean(), self.mean() + moment = var._moment_transform_center(order, moment_as, a, b) + out += moment * weight + return out[()] + + def _moment_standardized(self, order): + return self._moment_central(order) / self.standard_deviation()**order + + def pdf(self, x, /, *, method=None): + self._raise_if_method(method) + return self._sum('pdf', x) + + def logpdf(self, x, /, *, method=None): + self._raise_if_method(method) + return self._logsum('logpdf', x) + + def cdf(self, x, y=None, /, *, method=None): + self._raise_if_method(method) + args = (x,) if y is None else (x, y) + return self._sum('cdf', *args) + + def logcdf(self, x, y=None, /, *, method=None): + self._raise_if_method(method) + args = (x,) if y is None else (x, y) + return self._logsum('logcdf', *args) + + def ccdf(self, x, y=None, /, *, method=None): + self._raise_if_method(method) + args = (x,) if y is None else (x, y) + return self._sum('ccdf', *args) + + def logccdf(self, x, y=None, /, *, method=None): + self._raise_if_method(method) + args = (x,) if y is None else (x, y) + return self._logsum('logccdf', *args) + + def _invert(self, fun, p): + xmin, xmax = self.support() + fun = getattr(self, fun) + f = lambda x, p: fun(x) - p # noqa: E731 is silly + xl0, xr0 = _guess_bracket(xmin, xmax) + res = _bracket_root(f, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=(p,)) + return _chandrupatla(f, a=res.xl, b=res.xr, args=(p,)).x + + def icdf(self, p, /, *, method=None): + self._raise_if_method(method) + return self._invert('cdf', p) + + def iccdf(self, p, /, *, method=None): + self._raise_if_method(method) + return self._invert('ccdf', p) + + def ilogcdf(self, p, /, *, method=None): + self._raise_if_method(method) + return self._invert('logcdf', p) + + def ilogccdf(self, p, /, *, method=None): + self._raise_if_method(method) + return self._invert('logccdf', p) + + def sample(self, shape=(), *, rng=None, method=None): + self._raise_if_method(method) + rng = np.random.default_rng(rng) + size = np.prod(np.atleast_1d(shape)) + ns = rng.multinomial(size, self._weights) + x = [var.sample(shape=n, rng=rng) for n, var in zip(ns, self._components)] + x = np.reshape(rng.permuted(np.concatenate(x)), shape) + return x[()] + + def __repr__(self): + result = "Mixture(\n" + result += " [\n" + with np.printoptions(threshold=10): + for component in self.components: + result += f" {repr(component)},\n" + result += " ],\n" + result += f" weights={repr(self.weights)},\n" + result += ")" + return result + + def __str__(self): + result = "Mixture(\n" + result += " [\n" + with np.printoptions(threshold=10): + for component in self.components: + result += f" {str(component)},\n" + result += " ],\n" + result += f" weights={str(self.weights)},\n" + result += ")" + return result + + +class MonotonicTransformedDistribution(TransformedDistribution): + r"""Distribution underlying a strictly monotonic function of a random variable + + Given a random variable :math:`X`; a strictly monotonic function + :math:`g(u)`, its inverse :math:`h(u) = g^{-1}(u)`, and the derivative magnitude + :math: `|h'(u)| = \left| \frac{dh(u)}{du} \right|`, define the distribution + underlying the random variable :math:`Y = g(X)`. + + Parameters + ---------- + X : `ContinuousDistribution` + The random variable :math:`X`. + g, h, dh : callable + Elementwise functions representing the mathematical functions + :math:`g(u)`, :math:`h(u)`, and :math:`|h'(u)|` + logdh : callable, optional + Elementwise function representing :math:`\log(h'(u))`. + The default is ``lambda u: np.log(dh(u))``, but providing + a custom implementation may avoid over/underflow. + increasing : bool, optional + Whether the function is strictly increasing (True, default) + or strictly decreasing (False). + repr_pattern : str, optional + A string pattern for determining the __repr__. The __repr__ + for X will be substituted into the position where `***` appears. + For example: + ``"exp(***)"`` for the repr of an exponentially transformed + distribution + The default is ``f"{g.__name__}(***)"``. + str_pattern : str, optional + A string pattern for determining `__str__`. The `__str__` + for X will be substituted into the position where `***` appears. + For example: + ``"exp(***)"`` for the repr of an exponentially transformed + distribution + The default is the value `repr_pattern` takes. + """ + + def __init__(self, X, /, *args, g, h, dh, logdh=None, + increasing=True, repr_pattern=None, + str_pattern=None, **kwargs): + super().__init__(X, *args, **kwargs) + self._g = g + self._h = h + self._dh = dh + self._logdh = (logdh if logdh is not None + else lambda u: np.log(dh(u))) + if increasing: + self._xdf = self._dist._cdf_dispatch + self._cxdf = self._dist._ccdf_dispatch + self._ixdf = self._dist._icdf_dispatch + self._icxdf = self._dist._iccdf_dispatch + self._logxdf = self._dist._logcdf_dispatch + self._logcxdf = self._dist._logccdf_dispatch + self._ilogxdf = self._dist._ilogcdf_dispatch + self._ilogcxdf = self._dist._ilogccdf_dispatch + else: + self._xdf = self._dist._ccdf_dispatch + self._cxdf = self._dist._cdf_dispatch + self._ixdf = self._dist._iccdf_dispatch + self._icxdf = self._dist._icdf_dispatch + self._logxdf = self._dist._logccdf_dispatch + self._logcxdf = self._dist._logcdf_dispatch + self._ilogxdf = self._dist._ilogccdf_dispatch + self._ilogcxdf = self._dist._ilogcdf_dispatch + self._increasing = increasing + self._repr_pattern = repr_pattern or f"{g.__name__}(***)" + self._str_pattern = str_pattern or self._repr_pattern + + def __repr__(self): + with np.printoptions(threshold=10): + return self._repr_pattern.replace("***", repr(self._dist)) + + def __str__(self): + with np.printoptions(threshold=10): + return self._str_pattern.replace("***", str(self._dist)) + + def _overrides(self, method_name): + # Do not use the generic overrides of TransformedDistribution + return False + + def _support(self, **params): + a, b = self._dist._support(**params) + # For reciprocal transformation, we want this zero to become -inf + b = np.where(b==0, np.asarray("-0", dtype=b.dtype), b) + with np.errstate(divide='ignore'): + if self._increasing: + return self._g(a), self._g(b) + else: + return self._g(b), self._g(a) + + def _logpdf_dispatch(self, x, *args, **params): + return self._dist._logpdf_dispatch(self._h(x), *args, **params) + self._logdh(x) + + def _pdf_dispatch(self, x, *args, **params): + return self._dist._pdf_dispatch(self._h(x), *args, **params) * self._dh(x) + + def _logcdf_dispatch(self, x, *args, **params): + return self._logxdf(self._h(x), *args, **params) + + def _cdf_dispatch(self, x, *args, **params): + return self._xdf(self._h(x), *args, **params) + + def _logccdf_dispatch(self, x, *args, **params): + return self._logcxdf(self._h(x), *args, **params) + + def _ccdf_dispatch(self, x, *args, **params): + return self._cxdf(self._h(x), *args, **params) + + def _ilogcdf_dispatch(self, p, *args, **params): + return self._g(self._ilogxdf(p, *args, **params)) + + def _icdf_dispatch(self, p, *args, **params): + return self._g(self._ixdf(p, *args, **params)) + + def _ilogccdf_dispatch(self, p, *args, **params): + return self._g(self._ilogcxdf(p, *args, **params)) + + def _iccdf_dispatch(self, p, *args, **params): + return self._g(self._icxdf(p, *args, **params)) + + def _sample_dispatch(self, sample_shape, full_shape, *, + method, rng, **params): + rvs = self._dist._sample_dispatch( + sample_shape, full_shape, method=method, rng=rng, **params) + return self._g(rvs) + + +class FoldedDistribution(TransformedDistribution): + r"""Distribution underlying the absolute value of a random variable + + Given a random variable :math:`X`; define the distribution + underlying the random variable :math:`Y = |X|`. + + Parameters + ---------- + X : `ContinuousDistribution` + The random variable :math:`X`. + + Returns + ------- + Y : `ContinuousDistribution` + The random variable :math:`Y = |X|` + + """ + # Many enhancements are possible if distribution is symmetric. Start + # with the general case; enhance later. + + def __init__(self, X, /, *args, **kwargs): + super().__init__(X, *args, **kwargs) + # I think we need to allow `_support` to define whether the endpoints + # are inclusive or not. In the meantime, it's best to ensure that the lower + # endpoint (typically 0 for folded distribution) is inclusive so PDF evaluates + # correctly at that point. + self._variable.domain.inclusive = (True, self._variable.domain.inclusive[1]) + + def _overrides(self, method_name): + # Do not use the generic overrides of TransformedDistribution + return False + + def _support(self, **params): + a, b = self._dist._support(**params) + a_, b_ = np.abs(a), np.abs(b) + a_, b_ = np.minimum(a_, b_), np.maximum(a_, b_) + i = (a < 0) & (b > 0) + a_ = np.asarray(a_) + a_[i] = 0 + return a_[()], b_[()] + + def _logpdf_dispatch(self, x, *args, method=None, **params): + x = np.abs(x) + right = self._dist._logpdf_dispatch(x, *args, method=method, **params) + left = self._dist._logpdf_dispatch(-x, *args, method=method, **params) + left = np.asarray(left) + right = np.asarray(right) + a, b = self._dist._support(**params) + left[-x < a] = -np.inf + right[x > b] = -np.inf + logpdfs = np.stack([left, right]) + return special.logsumexp(logpdfs, axis=0) + + def _pdf_dispatch(self, x, *args, method=None, **params): + x = np.abs(x) + right = self._dist._pdf_dispatch(x, *args, method=method, **params) + left = self._dist._pdf_dispatch(-x, *args, method=method, **params) + left = np.asarray(left) + right = np.asarray(right) + a, b = self._dist._support(**params) + left[-x < a] = 0 + right[x > b] = 0 + return left + right + + def _logcdf_dispatch(self, x, *args, method=None, **params): + x = np.abs(x) + a, b = self._dist._support(**params) + xl = np.maximum(-x, a) + xr = np.minimum(x, b) + return self._dist._logcdf2_dispatch(xl, xr, *args, method=method, **params).real + + def _cdf_dispatch(self, x, *args, method=None, **params): + x = np.abs(x) + a, b = self._dist._support(**params) + xl = np.maximum(-x, a) + xr = np.minimum(x, b) + return self._dist._cdf2_dispatch(xl, xr, *args, **params) + + def _logccdf_dispatch(self, x, *args, method=None, **params): + x = np.abs(x) + a, b = self._dist._support(**params) + xl = np.maximum(-x, a) + xr = np.minimum(x, b) + return self._dist._logccdf2_dispatch(xl, xr, *args, method=method, + **params).real + + def _ccdf_dispatch(self, x, *args, method=None, **params): + x = np.abs(x) + a, b = self._dist._support(**params) + xl = np.maximum(-x, a) + xr = np.minimum(x, b) + return self._dist._ccdf2_dispatch(xl, xr, *args, method=method, **params) + + def _sample_dispatch(self, sample_shape, full_shape, *, + method, rng, **params): + rvs = self._dist._sample_dispatch( + sample_shape, full_shape, method=method, rng=rng, **params) + return np.abs(rvs) + + def __repr__(self): + with np.printoptions(threshold=10): + return f"abs({repr(self._dist)})" + + def __str__(self): + with np.printoptions(threshold=10): + return f"abs({str(self._dist)})" + + +def abs(X, /): + r"""Absolute value of a random variable + + Parameters + ---------- + X : `ContinuousDistribution` + The random variable :math:`X`. + + Returns + ------- + Y : `ContinuousDistribution` + A random variable :math:`Y = |X|`. + + Examples + -------- + Suppose we have a normally distributed random variable :math:`X`: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Normal() + + We wish to have a random variable :math:`Y` distributed according to + the folded normal distribution; that is, a random variable :math:`|X|`. + + >>> Y = stats.abs(X) + + The PDF of the distribution in the left half plane is "folded" over to + the right half plane. Because the normal PDF is symmetric, the resulting + PDF is zero for negative arguments and doubled for positive arguments. + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0, 5, 300) + >>> ax = plt.gca() + >>> Y.plot(x='x', y='pdf', t=('x', -1, 5), ax=ax) + >>> plt.plot(x, 2 * X.pdf(x), '--') + >>> plt.legend(('PDF of `Y`', 'Doubled PDF of `X`')) + >>> plt.show() + + """ + return FoldedDistribution(X) + + +def exp(X, /): + r"""Natural exponential of a random variable + + Parameters + ---------- + X : `ContinuousDistribution` + The random variable :math:`X`. + + Returns + ------- + Y : `ContinuousDistribution` + A random variable :math:`Y = \exp(X)`. + + Examples + -------- + Suppose we have a normally distributed random variable :math:`X`: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Normal() + + We wish to have a lognormally distributed random variable :math:`Y`, + a random variable whose natural logarithm is :math:`X`. + If :math:`X` is to be the natural logarithm of :math:`Y`, then we + must take :math:`Y` to be the natural exponential of :math:`X`. + + >>> Y = stats.exp(X) + + To demonstrate that ``X`` represents the logarithm of ``Y``, + we plot a normalized histogram of the logarithm of observations of + ``Y`` against the PDF underlying ``X``. + + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng(435383595582522) + >>> y = Y.sample(shape=10000, rng=rng) + >>> ax = plt.gca() + >>> ax.hist(np.log(y), bins=50, density=True) + >>> X.plot(ax=ax) + >>> plt.legend(('PDF of `X`', 'histogram of `log(y)`')) + >>> plt.show() + + """ + return MonotonicTransformedDistribution(X, g=np.exp, h=np.log, dh=lambda u: 1 / u, + logdh=lambda u: -np.log(u)) + + +def log(X, /): + r"""Natural logarithm of a non-negative random variable + + Parameters + ---------- + X : `ContinuousDistribution` + The random variable :math:`X` with positive support. + + Returns + ------- + Y : `ContinuousDistribution` + A random variable :math:`Y = \exp(X)`. + + Examples + -------- + Suppose we have a gamma distributed random variable :math:`X`: + + >>> import numpy as np + >>> from scipy import stats + >>> Gamma = stats.make_distribution(stats.gamma) + >>> X = Gamma(a=1.0) + + We wish to have a exp-gamma distributed random variable :math:`Y`, + a random variable whose natural exponential is :math:`X`. + If :math:`X` is to be the natural exponential of :math:`Y`, then we + must take :math:`Y` to be the natural logarithm of :math:`X`. + + >>> Y = stats.log(X) + + To demonstrate that ``X`` represents the exponential of ``Y``, + we plot a normalized histogram of the exponential of observations of + ``Y`` against the PDF underlying ``X``. + + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng(435383595582522) + >>> y = Y.sample(shape=10000, rng=rng) + >>> ax = plt.gca() + >>> ax.hist(np.exp(y), bins=50, density=True) + >>> X.plot(ax=ax) + >>> plt.legend(('PDF of `X`', 'histogram of `exp(y)`')) + >>> plt.show() + + """ + if np.any(X.support()[0] < 0): + message = ("The logarithm of a random variable is only implemented when the " + "support is non-negative.") + raise NotImplementedError(message) + return MonotonicTransformedDistribution(X, g=np.log, h=np.exp, dh=np.exp, + logdh=lambda u: u) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_entropy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..932c64cf93b1b5dcf7ab07884374c16499098ca3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_entropy.py @@ -0,0 +1,429 @@ +""" +Created on Fri Apr 2 09:06:05 2021 + +@author: matth +""" + +import math +import numpy as np +from scipy import special +from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays +from scipy._lib._array_api import array_namespace, xp_moveaxis_to_end + +__all__ = ['entropy', 'differential_entropy'] + + +@_axis_nan_policy_factory( + lambda x: x, + n_samples=lambda kwgs: ( + 2 if ("qk" in kwgs and kwgs["qk"] is not None) + else 1 + ), + n_outputs=1, result_to_tuple=lambda x: (x,), paired=True, + too_small=-1 # entropy doesn't have too small inputs +) +def entropy(pk: np.typing.ArrayLike, + qk: np.typing.ArrayLike | None = None, + base: float | None = None, + axis: int = 0 + ) -> np.number | np.ndarray: + """ + Calculate the Shannon entropy/relative entropy of given distribution(s). + + If only probabilities `pk` are given, the Shannon entropy is calculated as + ``H = -sum(pk * log(pk))``. + + If `qk` is not None, then compute the relative entropy + ``D = sum(pk * log(pk / qk))``. This quantity is also known + as the Kullback-Leibler divergence. + + This routine will normalize `pk` and `qk` if they don't sum to 1. + + Parameters + ---------- + pk : array_like + Defines the (discrete) distribution. Along each axis-slice of ``pk``, + element ``i`` is the (possibly unnormalized) probability of event + ``i``. + qk : array_like, optional + Sequence against which the relative entropy is computed. Should be in + the same format as `pk`. + base : float, optional + The logarithmic base to use, defaults to ``e`` (natural logarithm). + axis : int, optional + The axis along which the entropy is calculated. Default is 0. + + Returns + ------- + S : {float, array_like} + The calculated entropy. + + Notes + ----- + Informally, the Shannon entropy quantifies the expected uncertainty + inherent in the possible outcomes of a discrete random variable. + For example, + if messages consisting of sequences of symbols from a set are to be + encoded and transmitted over a noiseless channel, then the Shannon entropy + ``H(pk)`` gives a tight lower bound for the average number of units of + information needed per symbol if the symbols occur with frequencies + governed by the discrete distribution `pk` [1]_. The choice of base + determines the choice of units; e.g., ``e`` for nats, ``2`` for bits, etc. + + The relative entropy, ``D(pk|qk)``, quantifies the increase in the average + number of units of information needed per symbol if the encoding is + optimized for the probability distribution `qk` instead of the true + distribution `pk`. Informally, the relative entropy quantifies the expected + excess in surprise experienced if one believes the true distribution is + `qk` when it is actually `pk`. + + A related quantity, the cross entropy ``CE(pk, qk)``, satisfies the + equation ``CE(pk, qk) = H(pk) + D(pk|qk)`` and can also be calculated with + the formula ``CE = -sum(pk * log(qk))``. It gives the average + number of units of information needed per symbol if an encoding is + optimized for the probability distribution `qk` when the true distribution + is `pk`. It is not computed directly by `entropy`, but it can be computed + using two calls to the function (see Examples). + + See [2]_ for more information. + + References + ---------- + .. [1] Shannon, C.E. (1948), A Mathematical Theory of Communication. + Bell System Technical Journal, 27: 379-423. + https://doi.org/10.1002/j.1538-7305.1948.tb01338.x + .. [2] Thomas M. Cover and Joy A. Thomas. 2006. Elements of Information + Theory (Wiley Series in Telecommunications and Signal Processing). + Wiley-Interscience, USA. + + + Examples + -------- + The outcome of a fair coin is the most uncertain: + + >>> import numpy as np + >>> from scipy.stats import entropy + >>> base = 2 # work in units of bits + >>> pk = np.array([1/2, 1/2]) # fair coin + >>> H = entropy(pk, base=base) + >>> H + 1.0 + >>> H == -np.sum(pk * np.log(pk)) / np.log(base) + True + + The outcome of a biased coin is less uncertain: + + >>> qk = np.array([9/10, 1/10]) # biased coin + >>> entropy(qk, base=base) + 0.46899559358928117 + + The relative entropy between the fair coin and biased coin is calculated + as: + + >>> D = entropy(pk, qk, base=base) + >>> D + 0.7369655941662062 + >>> np.isclose(D, np.sum(pk * np.log(pk/qk)) / np.log(base), rtol=4e-16, atol=0) + True + + The cross entropy can be calculated as the sum of the entropy and + relative entropy`: + + >>> CE = entropy(pk, base=base) + entropy(pk, qk, base=base) + >>> CE + 1.736965594166206 + >>> CE == -np.sum(pk * np.log(qk)) / np.log(base) + True + + """ + if base is not None and base <= 0: + raise ValueError("`base` must be a positive number or `None`.") + + xp = array_namespace(pk) if qk is None else array_namespace(pk, qk) + + pk = xp.asarray(pk) + with np.errstate(invalid='ignore'): + pk = 1.0*pk / xp.sum(pk, axis=axis, keepdims=True) # type: ignore[operator] + if qk is None: + vec = special.entr(pk) + else: + qk = xp.asarray(qk) + pk, qk = _broadcast_arrays((pk, qk), axis=None, xp=xp) # don't ignore any axes + sum_kwargs = dict(axis=axis, keepdims=True) + qk = 1.0*qk / xp.sum(qk, **sum_kwargs) # type: ignore[operator, call-overload] + vec = special.rel_entr(pk, qk) + S = xp.sum(vec, axis=axis) + if base is not None: + S /= math.log(base) + return S + + +def _differential_entropy_is_too_small(samples, kwargs, axis=-1): + values = samples[0] + n = values.shape[axis] + window_length = kwargs.get("window_length", + math.floor(math.sqrt(n) + 0.5)) + if not 2 <= 2 * window_length < n: + return True + return False + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,), + too_small=_differential_entropy_is_too_small +) +def differential_entropy( + values: np.typing.ArrayLike, + *, + window_length: int | None = None, + base: float | None = None, + axis: int = 0, + method: str = "auto", +) -> np.number | np.ndarray: + r"""Given a sample of a distribution, estimate the differential entropy. + + Several estimation methods are available using the `method` parameter. By + default, a method is selected based the size of the sample. + + Parameters + ---------- + values : sequence + Sample from a continuous distribution. + window_length : int, optional + Window length for computing Vasicek estimate. Must be an integer + between 1 and half of the sample size. If ``None`` (the default), it + uses the heuristic value + + .. math:: + \left \lfloor \sqrt{n} + 0.5 \right \rfloor + + where :math:`n` is the sample size. This heuristic was originally + proposed in [2]_ and has become common in the literature. + base : float, optional + The logarithmic base to use, defaults to ``e`` (natural logarithm). + axis : int, optional + The axis along which the differential entropy is calculated. + Default is 0. + method : {'vasicek', 'van es', 'ebrahimi', 'correa', 'auto'}, optional + The method used to estimate the differential entropy from the sample. + Default is ``'auto'``. See Notes for more information. + + Returns + ------- + entropy : float + The calculated differential entropy. + + Notes + ----- + This function will converge to the true differential entropy in the limit + + .. math:: + n \to \infty, \quad m \to \infty, \quad \frac{m}{n} \to 0 + + The optimal choice of ``window_length`` for a given sample size depends on + the (unknown) distribution. Typically, the smoother the density of the + distribution, the larger the optimal value of ``window_length`` [1]_. + + The following options are available for the `method` parameter. + + * ``'vasicek'`` uses the estimator presented in [1]_. This is + one of the first and most influential estimators of differential entropy. + * ``'van es'`` uses the bias-corrected estimator presented in [3]_, which + is not only consistent but, under some conditions, asymptotically normal. + * ``'ebrahimi'`` uses an estimator presented in [4]_, which was shown + in simulation to have smaller bias and mean squared error than + the Vasicek estimator. + * ``'correa'`` uses the estimator presented in [5]_ based on local linear + regression. In a simulation study, it had consistently smaller mean + square error than the Vasiceck estimator, but it is more expensive to + compute. + * ``'auto'`` selects the method automatically (default). Currently, + this selects ``'van es'`` for very small samples (<10), ``'ebrahimi'`` + for moderate sample sizes (11-1000), and ``'vasicek'`` for larger + samples, but this behavior is subject to change in future versions. + + All estimators are implemented as described in [6]_. + + References + ---------- + .. [1] Vasicek, O. (1976). A test for normality based on sample entropy. + Journal of the Royal Statistical Society: + Series B (Methodological), 38(1), 54-59. + .. [2] Crzcgorzewski, P., & Wirczorkowski, R. (1999). Entropy-based + goodness-of-fit test for exponentiality. Communications in + Statistics-Theory and Methods, 28(5), 1183-1202. + .. [3] Van Es, B. (1992). Estimating functionals related to a density by a + class of statistics based on spacings. Scandinavian Journal of + Statistics, 61-72. + .. [4] Ebrahimi, N., Pflughoeft, K., & Soofi, E. S. (1994). Two measures + of sample entropy. Statistics & Probability Letters, 20(3), 225-234. + .. [5] Correa, J. C. (1995). A new estimator of entropy. Communications + in Statistics-Theory and Methods, 24(10), 2439-2449. + .. [6] Noughabi, H. A. (2015). Entropy Estimation Using Numerical Methods. + Annals of Data Science, 2(2), 231-241. + https://link.springer.com/article/10.1007/s40745-015-0045-9 + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import differential_entropy, norm + + Entropy of a standard normal distribution: + + >>> rng = np.random.default_rng() + >>> values = rng.standard_normal(100) + >>> differential_entropy(values) + 1.3407817436640392 + + Compare with the true entropy: + + >>> float(norm.entropy()) + 1.4189385332046727 + + For several sample sizes between 5 and 1000, compare the accuracy of + the ``'vasicek'``, ``'van es'``, and ``'ebrahimi'`` methods. Specifically, + compare the root mean squared error (over 1000 trials) between the estimate + and the true differential entropy of the distribution. + + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> + >>> + >>> def rmse(res, expected): + ... '''Root mean squared error''' + ... return np.sqrt(np.mean((res - expected)**2)) + >>> + >>> + >>> a, b = np.log10(5), np.log10(1000) + >>> ns = np.round(np.logspace(a, b, 10)).astype(int) + >>> reps = 1000 # number of repetitions for each sample size + >>> expected = stats.expon.entropy() + >>> + >>> method_errors = {'vasicek': [], 'van es': [], 'ebrahimi': []} + >>> for method in method_errors: + ... for n in ns: + ... rvs = stats.expon.rvs(size=(reps, n), random_state=rng) + ... res = stats.differential_entropy(rvs, method=method, axis=-1) + ... error = rmse(res, expected) + ... method_errors[method].append(error) + >>> + >>> for method, errors in method_errors.items(): + ... plt.loglog(ns, errors, label=method) + >>> + >>> plt.legend() + >>> plt.xlabel('sample size') + >>> plt.ylabel('RMSE (1000 trials)') + >>> plt.title('Entropy Estimator Error (Exponential Distribution)') + + """ + xp = array_namespace(values) + values = xp.asarray(values) + if xp.isdtype(values.dtype, "integral"): # type: ignore[union-attr] + values = xp.astype(values, xp.asarray(1.).dtype) + values = xp_moveaxis_to_end(values, axis, xp=xp) + n = values.shape[-1] # type: ignore[union-attr] + + if window_length is None: + window_length = math.floor(math.sqrt(n) + 0.5) + + if not 2 <= 2 * window_length < n: + raise ValueError( + f"Window length ({window_length}) must be positive and less " + f"than half the sample size ({n}).", + ) + + if base is not None and base <= 0: + raise ValueError("`base` must be a positive number or `None`.") + + sorted_data = xp.sort(values, axis=-1) + + methods = {"vasicek": _vasicek_entropy, + "van es": _van_es_entropy, + "correa": _correa_entropy, + "ebrahimi": _ebrahimi_entropy, + "auto": _vasicek_entropy} + method = method.lower() + if method not in methods: + message = f"`method` must be one of {set(methods)}" + raise ValueError(message) + + if method == "auto": + if n <= 10: + method = 'van es' + elif n <= 1000: + method = 'ebrahimi' + else: + method = 'vasicek' + + res = methods[method](sorted_data, window_length, xp=xp) + + if base is not None: + res /= math.log(base) + + # avoid dtype changes due to data-apis/array-api-compat#152 + # can be removed when data-apis/array-api-compat#152 is resolved + return xp.astype(res, values.dtype) # type: ignore[union-attr] + + +def _pad_along_last_axis(X, m, *, xp): + """Pad the data for computing the rolling window difference.""" + # scales a bit better than method in _vasicek_like_entropy + shape = X.shape[:-1] + (m,) + Xl = xp.broadcast_to(X[..., :1], shape) # :1 vs 0 to maintain shape + Xr = xp.broadcast_to(X[..., -1:], shape) + return xp.concat((Xl, X, Xr), axis=-1) + + +def _vasicek_entropy(X, m, *, xp): + """Compute the Vasicek estimator as described in [6] Eq. 1.3.""" + n = X.shape[-1] + X = _pad_along_last_axis(X, m, xp=xp) + differences = X[..., 2 * m:] - X[..., : -2 * m:] + logs = xp.log(n/(2*m) * differences) + return xp.mean(logs, axis=-1) + + +def _van_es_entropy(X, m, *, xp): + """Compute the van Es estimator as described in [6].""" + # No equation number, but referred to as HVE_mn. + # Typo: there should be a log within the summation. + n = X.shape[-1] + difference = X[..., m:] - X[..., :-m] + term1 = 1/(n-m) * xp.sum(xp.log((n+1)/m * difference), axis=-1) + k = xp.arange(m, n+1, dtype=term1.dtype) + return term1 + xp.sum(1/k) + math.log(m) - math.log(n+1) + + +def _ebrahimi_entropy(X, m, *, xp): + """Compute the Ebrahimi estimator as described in [6].""" + # No equation number, but referred to as HE_mn + n = X.shape[-1] + X = _pad_along_last_axis(X, m, xp=xp) + + differences = X[..., 2 * m:] - X[..., : -2 * m:] + + i = xp.arange(1, n+1, dtype=X.dtype) + ci = xp.ones_like(i)*2 + ci[i <= m] = 1 + (i[i <= m] - 1)/m + ci[i >= n - m + 1] = 1 + (n - i[i >= n-m+1])/m + + logs = xp.log(n * differences / (ci * m)) + return xp.mean(logs, axis=-1) + + +def _correa_entropy(X, m, *, xp): + """Compute the Correa estimator as described in [6].""" + # No equation number, but referred to as HC_mn + n = X.shape[-1] + X = _pad_along_last_axis(X, m, xp=xp) + + i = xp.arange(1, n+1) + dj = xp.arange(-m, m+1)[:, None] + j = i + dj + j0 = j + m - 1 # 0-indexed version of j + + Xibar = xp.mean(X[..., j0], axis=-2, keepdims=True) + difference = X[..., j0] - Xibar + num = xp.sum(difference*dj, axis=-2) # dj is d-i + den = n*xp.sum(difference**2, axis=-2) + return -xp.mean(xp.log(num/den), axis=-1) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_fit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb10606fdf60eed02790bbf27fe5152293a2b3b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_fit.py @@ -0,0 +1,1351 @@ +import warnings +from collections import namedtuple +import numpy as np +from scipy import optimize, stats +from scipy._lib._util import check_random_state, _transition_to_rng + + +def _combine_bounds(name, user_bounds, shape_domain, integral): + """Intersection of user-defined bounds and distribution PDF/PMF domain""" + + user_bounds = np.atleast_1d(user_bounds) + + if user_bounds[0] > user_bounds[1]: + message = (f"There are no values for `{name}` on the interval " + f"{list(user_bounds)}.") + raise ValueError(message) + + bounds = (max(user_bounds[0], shape_domain[0]), + min(user_bounds[1], shape_domain[1])) + + if integral and (np.ceil(bounds[0]) > np.floor(bounds[1])): + message = (f"There are no integer values for `{name}` on the interval " + f"defined by the user-provided bounds and the domain " + "of the distribution.") + raise ValueError(message) + elif not integral and (bounds[0] > bounds[1]): + message = (f"There are no values for `{name}` on the interval " + f"defined by the user-provided bounds and the domain " + "of the distribution.") + raise ValueError(message) + + if not np.all(np.isfinite(bounds)): + message = (f"The intersection of user-provided bounds for `{name}` " + f"and the domain of the distribution is not finite. Please " + f"provide finite bounds for shape `{name}` in `bounds`.") + raise ValueError(message) + + return bounds + + +class FitResult: + r"""Result of fitting a discrete or continuous distribution to data + + Attributes + ---------- + params : namedtuple + A namedtuple containing the maximum likelihood estimates of the + shape parameters, location, and (if applicable) scale of the + distribution. + success : bool or None + Whether the optimizer considered the optimization to terminate + successfully or not. + message : str or None + Any status message provided by the optimizer. + + """ + + def __init__(self, dist, data, discrete, res): + self._dist = dist + self._data = data + self.discrete = discrete + self.pxf = getattr(dist, "pmf", None) or getattr(dist, "pdf", None) + + shape_names = [] if dist.shapes is None else dist.shapes.split(", ") + if not discrete: + FitParams = namedtuple('FitParams', shape_names + ['loc', 'scale']) + else: + FitParams = namedtuple('FitParams', shape_names + ['loc']) + + self.params = FitParams(*res.x) + + # Optimizer can report success even when nllf is infinite + if res.success and not np.isfinite(self.nllf()): + res.success = False + res.message = ("Optimization converged to parameter values that " + "are inconsistent with the data.") + self.success = getattr(res, "success", None) + self.message = getattr(res, "message", None) + + def __repr__(self): + keys = ["params", "success", "message"] + m = max(map(len, keys)) + 1 + return '\n'.join([key.rjust(m) + ': ' + repr(getattr(self, key)) + for key in keys if getattr(self, key) is not None]) + + def nllf(self, params=None, data=None): + """Negative log-likelihood function + + Evaluates the negative of the log-likelihood function of the provided + data at the provided parameters. + + Parameters + ---------- + params : tuple, optional + The shape parameters, location, and (if applicable) scale of the + distribution as a single tuple. Default is the maximum likelihood + estimates (``self.params``). + data : array_like, optional + The data for which the log-likelihood function is to be evaluated. + Default is the data to which the distribution was fit. + + Returns + ------- + nllf : float + The negative of the log-likelihood function. + + """ + params = params if params is not None else self.params + data = data if data is not None else self._data + return self._dist.nnlf(theta=params, x=data) + + def plot(self, ax=None, *, plot_type="hist"): + """Visually compare the data against the fitted distribution. + + Available only if `matplotlib` is installed. + + Parameters + ---------- + ax : `matplotlib.axes.Axes` + Axes object to draw the plot onto, otherwise uses the current Axes. + plot_type : {"hist", "qq", "pp", "cdf"} + Type of plot to draw. Options include: + + - "hist": Superposes the PDF/PMF of the fitted distribution + over a normalized histogram of the data. + - "qq": Scatter plot of theoretical quantiles against the + empirical quantiles. Specifically, the x-coordinates are the + values of the fitted distribution PPF evaluated at the + percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is the + number of data points, and the y-coordinates are the sorted + data points. + - "pp": Scatter plot of theoretical percentiles against the + observed percentiles. Specifically, the x-coordinates are the + percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is + the number of data points, and the y-coordinates are the values + of the fitted distribution CDF evaluated at the sorted + data points. + - "cdf": Superposes the CDF of the fitted distribution over the + empirical CDF. Specifically, the x-coordinates of the empirical + CDF are the sorted data points, and the y-coordinates are the + percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is + the number of data points. + + Returns + ------- + ax : `matplotlib.axes.Axes` + The matplotlib Axes object on which the plot was drawn. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt # matplotlib must be installed + >>> rng = np.random.default_rng() + >>> data = stats.nbinom(5, 0.5).rvs(size=1000, random_state=rng) + >>> bounds = [(0, 30), (0, 1)] + >>> res = stats.fit(stats.nbinom, data, bounds) + >>> ax = res.plot() # save matplotlib Axes object + + The `matplotlib.axes.Axes` object can be used to customize the plot. + See `matplotlib.axes.Axes` documentation for details. + + >>> ax.set_xlabel('number of trials') # customize axis label + >>> ax.get_children()[0].set_linewidth(5) # customize line widths + >>> ax.legend() + >>> plt.show() + """ + try: + import matplotlib # noqa: F401 + except ModuleNotFoundError as exc: + message = "matplotlib must be installed to use method `plot`." + raise ModuleNotFoundError(message) from exc + + plots = {'histogram': self._hist_plot, 'qq': self._qq_plot, + 'pp': self._pp_plot, 'cdf': self._cdf_plot, + 'hist': self._hist_plot} + if plot_type.lower() not in plots: + message = f"`plot_type` must be one of {set(plots.keys())}" + raise ValueError(message) + plot = plots[plot_type.lower()] + + if ax is None: + import matplotlib.pyplot as plt + ax = plt.gca() + + fit_params = np.atleast_1d(self.params) + + return plot(ax=ax, fit_params=fit_params) + + def _hist_plot(self, ax, fit_params): + from matplotlib.ticker import MaxNLocator + + support = self._dist.support(*fit_params) + lb = support[0] if np.isfinite(support[0]) else min(self._data) + ub = support[1] if np.isfinite(support[1]) else max(self._data) + pxf = "PMF" if self.discrete else "PDF" + + if self.discrete: + x = np.arange(lb, ub + 2) + y = self.pxf(x, *fit_params) + ax.vlines(x[:-1], 0, y[:-1], label='Fitted Distribution PMF', + color='C0') + options = dict(density=True, bins=x, align='left', color='C1') + ax.xaxis.set_major_locator(MaxNLocator(integer=True)) + ax.set_xlabel('k') + ax.set_ylabel('PMF') + else: + x = np.linspace(lb, ub, 200) + y = self.pxf(x, *fit_params) + ax.plot(x, y, '--', label='Fitted Distribution PDF', color='C0') + options = dict(density=True, bins=50, align='mid', color='C1') + ax.set_xlabel('x') + ax.set_ylabel('PDF') + + if len(self._data) > 50 or self.discrete: + ax.hist(self._data, label="Histogram of Data", **options) + else: + ax.plot(self._data, np.zeros_like(self._data), "*", + label='Data', color='C1') + + ax.set_title(rf"Fitted $\tt {self._dist.name}$ {pxf} and Histogram") + ax.legend(*ax.get_legend_handles_labels()) + return ax + + def _qp_plot(self, ax, fit_params, qq): + data = np.sort(self._data) + ps = self._plotting_positions(len(self._data)) + + if qq: + qp = "Quantiles" + plot_type = 'Q-Q' + x = self._dist.ppf(ps, *fit_params) + y = data + else: + qp = "Percentiles" + plot_type = 'P-P' + x = ps + y = self._dist.cdf(data, *fit_params) + + ax.plot(x, y, '.', label=f'Fitted Distribution {plot_type}', + color='C0', zorder=1) + xlim = ax.get_xlim() + ylim = ax.get_ylim() + lim = [min(xlim[0], ylim[0]), max(xlim[1], ylim[1])] + if not qq: + lim = max(lim[0], 0), min(lim[1], 1) + + if self.discrete and qq: + q_min, q_max = int(lim[0]), int(lim[1]+1) + q_ideal = np.arange(q_min, q_max) + # q_ideal = np.unique(self._dist.ppf(ps, *fit_params)) + ax.plot(q_ideal, q_ideal, 'o', label='Reference', color='k', + alpha=0.25, markerfacecolor='none', clip_on=True) + elif self.discrete and not qq: + # The intent of this is to match the plot that would be produced + # if x were continuous on [0, 1] and y were cdf(ppf(x)). + # It can be approximated by letting x = np.linspace(0, 1, 1000), + # but this might not look great when zooming in. The vertical + # portions are included to indicate where the transition occurs + # where the data completely obscures the horizontal portions. + p_min, p_max = lim + a, b = self._dist.support(*fit_params) + p_min = max(p_min, 0 if np.isfinite(a) else 1e-3) + p_max = min(p_max, 1 if np.isfinite(b) else 1-1e-3) + q_min, q_max = self._dist.ppf([p_min, p_max], *fit_params) + qs = np.arange(q_min-1, q_max+1) + ps = self._dist.cdf(qs, *fit_params) + ax.step(ps, ps, '-', label='Reference', color='k', alpha=0.25, + clip_on=True) + else: + ax.plot(lim, lim, '-', label='Reference', color='k', alpha=0.25, + clip_on=True) + + ax.set_xlim(lim) + ax.set_ylim(lim) + ax.set_xlabel(rf"Fitted $\tt {self._dist.name}$ Theoretical {qp}") + ax.set_ylabel(f"Data {qp}") + ax.set_title(rf"Fitted $\tt {self._dist.name}$ {plot_type} Plot") + ax.legend(*ax.get_legend_handles_labels()) + ax.set_aspect('equal') + return ax + + def _qq_plot(self, **kwargs): + return self._qp_plot(qq=True, **kwargs) + + def _pp_plot(self, **kwargs): + return self._qp_plot(qq=False, **kwargs) + + def _plotting_positions(self, n, a=.5): + # See https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot#Plotting_positions + k = np.arange(1, n+1) + return (k-a) / (n + 1 - 2*a) + + def _cdf_plot(self, ax, fit_params): + data = np.sort(self._data) + ecdf = self._plotting_positions(len(self._data)) + ls = '--' if len(np.unique(data)) < 30 else '.' + xlabel = 'k' if self.discrete else 'x' + ax.step(data, ecdf, ls, label='Empirical CDF', color='C1', zorder=0) + + xlim = ax.get_xlim() + q = np.linspace(*xlim, 300) + tcdf = self._dist.cdf(q, *fit_params) + + ax.plot(q, tcdf, label='Fitted Distribution CDF', color='C0', zorder=1) + ax.set_xlim(xlim) + ax.set_ylim(0, 1) + ax.set_xlabel(xlabel) + ax.set_ylabel("CDF") + ax.set_title(rf"Fitted $\tt {self._dist.name}$ and Empirical CDF") + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles[::-1], labels[::-1]) + return ax + + +def fit(dist, data, bounds=None, *, guess=None, method='mle', + optimizer=optimize.differential_evolution): + r"""Fit a discrete or continuous distribution to data + + Given a distribution, data, and bounds on the parameters of the + distribution, return maximum likelihood estimates of the parameters. + + Parameters + ---------- + dist : `scipy.stats.rv_continuous` or `scipy.stats.rv_discrete` + The object representing the distribution to be fit to the data. + data : 1D array_like + The data to which the distribution is to be fit. If the data contain + any of ``np.nan``, ``np.inf``, or -``np.inf``, the fit method will + raise a ``ValueError``. + bounds : dict or sequence of tuples, optional + If a dictionary, each key is the name of a parameter of the + distribution, and the corresponding value is a tuple containing the + lower and upper bound on that parameter. If the distribution is + defined only for a finite range of values of that parameter, no entry + for that parameter is required; e.g., some distributions have + parameters which must be on the interval [0, 1]. Bounds for parameters + location (``loc``) and scale (``scale``) are optional; by default, + they are fixed to 0 and 1, respectively. + + If a sequence, element *i* is a tuple containing the lower and upper + bound on the *i*\ th parameter of the distribution. In this case, + bounds for *all* distribution shape parameters must be provided. + Optionally, bounds for location and scale may follow the + distribution shape parameters. + + If a shape is to be held fixed (e.g. if it is known), the + lower and upper bounds may be equal. If a user-provided lower or upper + bound is beyond a bound of the domain for which the distribution is + defined, the bound of the distribution's domain will replace the + user-provided value. Similarly, parameters which must be integral + will be constrained to integral values within the user-provided bounds. + guess : dict or array_like, optional + If a dictionary, each key is the name of a parameter of the + distribution, and the corresponding value is a guess for the value + of the parameter. + + If a sequence, element *i* is a guess for the *i*\ th parameter of the + distribution. In this case, guesses for *all* distribution shape + parameters must be provided. + + If `guess` is not provided, guesses for the decision variables will + not be passed to the optimizer. If `guess` is provided, guesses for + any missing parameters will be set at the mean of the lower and + upper bounds. Guesses for parameters which must be integral will be + rounded to integral values, and guesses that lie outside the + intersection of the user-provided bounds and the domain of the + distribution will be clipped. + method : {'mle', 'mse'} + With ``method="mle"`` (default), the fit is computed by minimizing + the negative log-likelihood function. A large, finite penalty + (rather than infinite negative log-likelihood) is applied for + observations beyond the support of the distribution. + With ``method="mse"``, the fit is computed by minimizing + the negative log-product spacing function. The same penalty is applied + for observations beyond the support. We follow the approach of [1]_, + which is generalized for samples with repeated observations. + optimizer : callable, optional + `optimizer` is a callable that accepts the following positional + argument. + + fun : callable + The objective function to be optimized. `fun` accepts one argument + ``x``, candidate shape parameters of the distribution, and returns + the objective function value given ``x``, `dist`, and the provided + `data`. + The job of `optimizer` is to find values of the decision variables + that minimizes `fun`. + + `optimizer` must also accept the following keyword argument. + + bounds : sequence of tuples + The bounds on values of the decision variables; each element will + be a tuple containing the lower and upper bound on a decision + variable. + + If `guess` is provided, `optimizer` must also accept the following + keyword argument. + + x0 : array_like + The guesses for each decision variable. + + If the distribution has any shape parameters that must be integral or + if the distribution is discrete and the location parameter is not + fixed, `optimizer` must also accept the following keyword argument. + + integrality : array_like of bools + For each decision variable, True if the decision variable + must be constrained to integer values and False if the decision + variable is continuous. + + `optimizer` must return an object, such as an instance of + `scipy.optimize.OptimizeResult`, which holds the optimal values of + the decision variables in an attribute ``x``. If attributes + ``fun``, ``status``, or ``message`` are provided, they will be + included in the result object returned by `fit`. + + Returns + ------- + result : `~scipy.stats._result_classes.FitResult` + An object with the following fields. + + params : namedtuple + A namedtuple containing the maximum likelihood estimates of the + shape parameters, location, and (if applicable) scale of the + distribution. + success : bool or None + Whether the optimizer considered the optimization to terminate + successfully or not. + message : str or None + Any status message provided by the optimizer. + + The object has the following method: + + nllf(params=None, data=None) + By default, the negative log-likelihood function at the fitted + `params` for the given `data`. Accepts a tuple containing + alternative shapes, location, and scale of the distribution and + an array of alternative data. + + plot(ax=None) + Superposes the PDF/PMF of the fitted distribution over a normalized + histogram of the data. + + See Also + -------- + rv_continuous, rv_discrete + + Notes + ----- + Optimization is more likely to converge to the maximum likelihood estimate + when the user provides tight bounds containing the maximum likelihood + estimate. For example, when fitting a binomial distribution to data, the + number of experiments underlying each sample may be known, in which case + the corresponding shape parameter ``n`` can be fixed. + + References + ---------- + .. [1] Shao, Yongzhao, and Marjorie G. Hahn. "Maximum product of spacings + method: a unified formulation with illustration of strong + consistency." Illinois Journal of Mathematics 43.3 (1999): 489-499. + + Examples + -------- + Suppose we wish to fit a distribution to the following data. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> dist = stats.nbinom + >>> shapes = (5, 0.5) + >>> data = dist.rvs(*shapes, size=1000, random_state=rng) + + Suppose we do not know how the data were generated, but we suspect that + it follows a negative binomial distribution with parameters *n* and *p*\. + (See `scipy.stats.nbinom`.) We believe that the parameter *n* was fewer + than 30, and we know that the parameter *p* must lie on the interval + [0, 1]. We record this information in a variable `bounds` and pass + this information to `fit`. + + >>> bounds = [(0, 30), (0, 1)] + >>> res = stats.fit(dist, data, bounds) + + `fit` searches within the user-specified `bounds` for the + values that best match the data (in the sense of maximum likelihood + estimation). In this case, it found shape values similar to those + from which the data were actually generated. + + >>> res.params + FitParams(n=5.0, p=0.5028157644634368, loc=0.0) # may vary + + We can visualize the results by superposing the probability mass function + of the distribution (with the shapes fit to the data) over a normalized + histogram of the data. + + >>> import matplotlib.pyplot as plt # matplotlib must be installed to plot + >>> res.plot() + >>> plt.show() + + Note that the estimate for *n* was exactly integral; this is because + the domain of the `nbinom` PMF includes only integral *n*, and the `nbinom` + object "knows" that. `nbinom` also knows that the shape *p* must be a + value between 0 and 1. In such a case - when the domain of the distribution + with respect to a parameter is finite - we are not required to specify + bounds for the parameter. + + >>> bounds = {'n': (0, 30)} # omit parameter p using a `dict` + >>> res2 = stats.fit(dist, data, bounds) + >>> res2.params + FitParams(n=5.0, p=0.5016492009232932, loc=0.0) # may vary + + If we wish to force the distribution to be fit with *n* fixed at 6, we can + set both the lower and upper bounds on *n* to 6. Note, however, that the + value of the objective function being optimized is typically worse (higher) + in this case. + + >>> bounds = {'n': (6, 6)} # fix parameter `n` + >>> res3 = stats.fit(dist, data, bounds) + >>> res3.params + FitParams(n=6.0, p=0.5486556076755706, loc=0.0) # may vary + >>> res3.nllf() > res.nllf() + True # may vary + + Note that the numerical results of the previous examples are typical, but + they may vary because the default optimizer used by `fit`, + `scipy.optimize.differential_evolution`, is stochastic. However, we can + customize the settings used by the optimizer to ensure reproducibility - + or even use a different optimizer entirely - using the `optimizer` + parameter. + + >>> from scipy.optimize import differential_evolution + >>> rng = np.random.default_rng(767585560716548) + >>> def optimizer(fun, bounds, *, integrality): + ... return differential_evolution(fun, bounds, strategy='best2bin', + ... rng=rng, integrality=integrality) + >>> bounds = [(0, 30), (0, 1)] + >>> res4 = stats.fit(dist, data, bounds, optimizer=optimizer) + >>> res4.params + FitParams(n=5.0, p=0.5015183149259951, loc=0.0) + + """ + # --- Input Validation / Standardization --- # + user_bounds = bounds + user_guess = guess + + # distribution input validation and information collection + if hasattr(dist, "pdf"): # can't use isinstance for types + default_bounds = {'loc': (0, 0), 'scale': (1, 1)} + discrete = False + elif hasattr(dist, "pmf"): + default_bounds = {'loc': (0, 0)} + discrete = True + else: + message = ("`dist` must be an instance of `rv_continuous` " + "or `rv_discrete.`") + raise ValueError(message) + + try: + param_info = dist._param_info() + except AttributeError as e: + message = (f"Distribution `{dist.name}` is not yet supported by " + "`scipy.stats.fit` because shape information has " + "not been defined.") + raise ValueError(message) from e + + # data input validation + data = np.asarray(data) + if data.ndim != 1: + message = "`data` must be exactly one-dimensional." + raise ValueError(message) + if not (np.issubdtype(data.dtype, np.number) + and np.all(np.isfinite(data))): + message = "All elements of `data` must be finite numbers." + raise ValueError(message) + + # bounds input validation and information collection + n_params = len(param_info) + n_shapes = n_params - (1 if discrete else 2) + param_list = [param.name for param in param_info] + param_names = ", ".join(param_list) + shape_names = ", ".join(param_list[:n_shapes]) + + if user_bounds is None: + user_bounds = {} + + if isinstance(user_bounds, dict): + default_bounds.update(user_bounds) + user_bounds = default_bounds + user_bounds_array = np.empty((n_params, 2)) + for i in range(n_params): + param_name = param_info[i].name + user_bound = user_bounds.pop(param_name, None) + if user_bound is None: + user_bound = param_info[i].domain + user_bounds_array[i] = user_bound + if user_bounds: + message = ("Bounds provided for the following unrecognized " + f"parameters will be ignored: {set(user_bounds)}") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + else: + try: + user_bounds = np.asarray(user_bounds, dtype=float) + if user_bounds.size == 0: + user_bounds = np.empty((0, 2)) + except ValueError as e: + message = ("Each element of a `bounds` sequence must be a tuple " + "containing two elements: the lower and upper bound of " + "a distribution parameter.") + raise ValueError(message) from e + if (user_bounds.ndim != 2 or user_bounds.shape[1] != 2): + message = ("Each element of `bounds` must be a tuple specifying " + "the lower and upper bounds of a shape parameter") + raise ValueError(message) + if user_bounds.shape[0] < n_shapes: + message = (f"A `bounds` sequence must contain at least {n_shapes} " + "elements: tuples specifying the lower and upper " + f"bounds of all shape parameters {shape_names}.") + raise ValueError(message) + if user_bounds.shape[0] > n_params: + message = ("A `bounds` sequence may not contain more than " + f"{n_params} elements: tuples specifying the lower and " + "upper bounds of distribution parameters " + f"{param_names}.") + raise ValueError(message) + + user_bounds_array = np.empty((n_params, 2)) + user_bounds_array[n_shapes:] = list(default_bounds.values()) + user_bounds_array[:len(user_bounds)] = user_bounds + + user_bounds = user_bounds_array + validated_bounds = [] + for i in range(n_params): + name = param_info[i].name + user_bound = user_bounds_array[i] + param_domain = param_info[i].domain + integral = param_info[i].integrality + combined = _combine_bounds(name, user_bound, param_domain, integral) + validated_bounds.append(combined) + + bounds = np.asarray(validated_bounds) + integrality = [param.integrality for param in param_info] + + # guess input validation + + if user_guess is None: + guess_array = None + elif isinstance(user_guess, dict): + default_guess = {param.name: np.mean(bound) + for param, bound in zip(param_info, bounds)} + unrecognized = set(user_guess) - set(default_guess) + if unrecognized: + message = ("Guesses provided for the following unrecognized " + f"parameters will be ignored: {unrecognized}") + warnings.warn(message, RuntimeWarning, stacklevel=2) + default_guess.update(user_guess) + + message = ("Each element of `guess` must be a scalar " + "guess for a distribution parameter.") + try: + guess_array = np.asarray([default_guess[param.name] + for param in param_info], dtype=float) + except ValueError as e: + raise ValueError(message) from e + + else: + message = ("Each element of `guess` must be a scalar " + "guess for a distribution parameter.") + try: + user_guess = np.asarray(user_guess, dtype=float) + except ValueError as e: + raise ValueError(message) from e + if user_guess.ndim != 1: + raise ValueError(message) + if user_guess.shape[0] < n_shapes: + message = (f"A `guess` sequence must contain at least {n_shapes} " + "elements: scalar guesses for the distribution shape " + f"parameters {shape_names}.") + raise ValueError(message) + if user_guess.shape[0] > n_params: + message = ("A `guess` sequence may not contain more than " + f"{n_params} elements: scalar guesses for the " + f"distribution parameters {param_names}.") + raise ValueError(message) + + guess_array = np.mean(bounds, axis=1) + guess_array[:len(user_guess)] = user_guess + + if guess_array is not None: + guess_rounded = guess_array.copy() + + guess_rounded[integrality] = np.round(guess_rounded[integrality]) + rounded = np.where(guess_rounded != guess_array)[0] + for i in rounded: + message = (f"Guess for parameter `{param_info[i].name}` " + f"rounded from {guess_array[i]} to {guess_rounded[i]}.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + guess_clipped = np.clip(guess_rounded, bounds[:, 0], bounds[:, 1]) + clipped = np.where(guess_clipped != guess_rounded)[0] + for i in clipped: + message = (f"Guess for parameter `{param_info[i].name}` " + f"clipped from {guess_rounded[i]} to " + f"{guess_clipped[i]}.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + guess = guess_clipped + else: + guess = None + + # --- Fitting --- # + def nllf(free_params, data=data): # bind data NOW + with np.errstate(invalid='ignore', divide='ignore'): + return dist._penalized_nnlf(free_params, data) + + def nlpsf(free_params, data=data): # bind data NOW + with np.errstate(invalid='ignore', divide='ignore'): + return dist._penalized_nlpsf(free_params, data) + + methods = {'mle': nllf, 'mse': nlpsf} + objective = methods[method.lower()] + + with np.errstate(invalid='ignore', divide='ignore'): + kwds = {} + if bounds is not None: + kwds['bounds'] = bounds + if np.any(integrality): + kwds['integrality'] = integrality + if guess is not None: + kwds['x0'] = guess + res = optimizer(objective, **kwds) + + return FitResult(dist, data, discrete, res) + + +GoodnessOfFitResult = namedtuple('GoodnessOfFitResult', + ('fit_result', 'statistic', 'pvalue', + 'null_distribution')) + + +@_transition_to_rng('random_state') +def goodness_of_fit(dist, data, *, known_params=None, fit_params=None, + guessed_params=None, statistic='ad', n_mc_samples=9999, + rng=None): + r""" + Perform a goodness of fit test comparing data to a distribution family. + + Given a distribution family and data, perform a test of the null hypothesis + that the data were drawn from a distribution in that family. Any known + parameters of the distribution may be specified. Remaining parameters of + the distribution will be fit to the data, and the p-value of the test + is computed accordingly. Several statistics for comparing the distribution + to data are available. + + Parameters + ---------- + dist : `scipy.stats.rv_continuous` + The object representing the distribution family under the null + hypothesis. + data : 1D array_like + Finite, uncensored data to be tested. + known_params : dict, optional + A dictionary containing name-value pairs of known distribution + parameters. Monte Carlo samples are randomly drawn from the + null-hypothesized distribution with these values of the parameters. + Before the statistic is evaluated for the observed `data` and each + Monte Carlo sample, only remaining unknown parameters of the + null-hypothesized distribution family are fit to the samples; the + known parameters are held fixed. If all parameters of the distribution + family are known, then the step of fitting the distribution family to + each sample is omitted. + fit_params : dict, optional + A dictionary containing name-value pairs of distribution parameters + that have already been fit to the data, e.g. using `scipy.stats.fit` + or the ``fit`` method of `dist`. Monte Carlo samples are drawn from the + null-hypothesized distribution with these specified values of the + parameter. However, these and all other unknown parameters of the + null-hypothesized distribution family are always fit to the sample, + whether that is the observed `data` or a Monte Carlo sample, before + the statistic is evaluated. + guessed_params : dict, optional + A dictionary containing name-value pairs of distribution parameters + which have been guessed. These parameters are always considered as + free parameters and are fit both to the provided `data` as well as + to the Monte Carlo samples drawn from the null-hypothesized + distribution. The purpose of these `guessed_params` is to be used as + initial values for the numerical fitting procedure. + statistic : {"ad", "ks", "cvm", "filliben"} or callable, optional + The statistic used to compare data to a distribution after fitting + unknown parameters of the distribution family to the data. The + Anderson-Darling ("ad") [1]_, Kolmogorov-Smirnov ("ks") [1]_, + Cramer-von Mises ("cvm") [1]_, and Filliben ("filliben") [7]_ + statistics are available. Alternatively, a callable with signature + ``(dist, data, axis)`` may be supplied to compute the statistic. Here + ``dist`` is a frozen distribution object (potentially with array + parameters), ``data`` is an array of Monte Carlo samples (of + compatible shape), and ``axis`` is the axis of ``data`` along which + the statistic must be computed. + n_mc_samples : int, default: 9999 + The number of Monte Carlo samples drawn from the null hypothesized + distribution to form the null distribution of the statistic. The + sample size of each is the same as the given `data`. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + res : GoodnessOfFitResult + An object with the following attributes. + + fit_result : `~scipy.stats._result_classes.FitResult` + An object representing the fit of the provided `dist` to `data`. + This object includes the values of distribution family parameters + that fully define the null-hypothesized distribution, that is, + the distribution from which Monte Carlo samples are drawn. + statistic : float + The value of the statistic comparing provided `data` to the + null-hypothesized distribution. + pvalue : float + The proportion of elements in the null distribution with + statistic values at least as extreme as the statistic value of the + provided `data`. + null_distribution : ndarray + The value of the statistic for each Monte Carlo sample + drawn from the null-hypothesized distribution. + + Notes + ----- + This is a generalized Monte Carlo goodness-of-fit procedure, special cases + of which correspond with various Anderson-Darling tests, Lilliefors' test, + etc. The test is described in [2]_, [3]_, and [4]_ as a parametric + bootstrap test. This is a Monte Carlo test in which parameters that + specify the distribution from which samples are drawn have been estimated + from the data. We describe the test using "Monte Carlo" rather than + "parametric bootstrap" throughout to avoid confusion with the more familiar + nonparametric bootstrap, and describe how the test is performed below. + + *Traditional goodness of fit tests* + + Traditionally, critical values corresponding with a fixed set of + significance levels are pre-calculated using Monte Carlo methods. Users + perform the test by calculating the value of the test statistic only for + their observed `data` and comparing this value to tabulated critical + values. This practice is not very flexible, as tables are not available for + all distributions and combinations of known and unknown parameter values. + Also, results can be inaccurate when critical values are interpolated from + limited tabulated data to correspond with the user's sample size and + fitted parameter values. To overcome these shortcomings, this function + allows the user to perform the Monte Carlo trials adapted to their + particular data. + + *Algorithmic overview* + + In brief, this routine executes the following steps: + + 1. Fit unknown parameters to the given `data`, thereby forming the + "null-hypothesized" distribution, and compute the statistic of + this pair of data and distribution. + 2. Draw random samples from this null-hypothesized distribution. + 3. Fit the unknown parameters to each random sample. + 4. Calculate the statistic between each sample and the distribution that + has been fit to the sample. + 5. Compare the value of the statistic corresponding with `data` from (1) + against the values of the statistic corresponding with the random + samples from (4). The p-value is the proportion of samples with a + statistic value greater than or equal to the statistic of the observed + data. + + In more detail, the steps are as follows. + + First, any unknown parameters of the distribution family specified by + `dist` are fit to the provided `data` using maximum likelihood estimation. + (One exception is the normal distribution with unknown location and scale: + we use the bias-corrected standard deviation ``np.std(data, ddof=1)`` for + the scale as recommended in [1]_.) + These values of the parameters specify a particular member of the + distribution family referred to as the "null-hypothesized distribution", + that is, the distribution from which the data were sampled under the null + hypothesis. The `statistic`, which compares data to a distribution, is + computed between `data` and the null-hypothesized distribution. + + Next, many (specifically `n_mc_samples`) new samples, each containing the + same number of observations as `data`, are drawn from the + null-hypothesized distribution. All unknown parameters of the distribution + family `dist` are fit to *each resample*, and the `statistic` is computed + between each sample and its corresponding fitted distribution. These + values of the statistic form the Monte Carlo null distribution (not to be + confused with the "null-hypothesized distribution" above). + + The p-value of the test is the proportion of statistic values in the Monte + Carlo null distribution that are at least as extreme as the statistic value + of the provided `data`. More precisely, the p-value is given by + + .. math:: + + p = \frac{b + 1} + {m + 1} + + where :math:`b` is the number of statistic values in the Monte Carlo null + distribution that are greater than or equal to the statistic value + calculated for `data`, and :math:`m` is the number of elements in the + Monte Carlo null distribution (`n_mc_samples`). The addition of :math:`1` + to the numerator and denominator can be thought of as including the + value of the statistic corresponding with `data` in the null distribution, + but a more formal explanation is given in [5]_. + + *Limitations* + + The test can be very slow for some distribution families because unknown + parameters of the distribution family must be fit to each of the Monte + Carlo samples, and for most distributions in SciPy, distribution fitting + performed via numerical optimization. + + *Anti-Pattern* + + For this reason, it may be tempting + to treat parameters of the distribution pre-fit to `data` (by the user) + as though they were `known_params`, as specification of all parameters of + the distribution precludes the need to fit the distribution to each Monte + Carlo sample. (This is essentially how the original Kilmogorov-Smirnov + test is performed.) Although such a test can provide evidence against the + null hypothesis, the test is conservative in the sense that small p-values + will tend to (greatly) *overestimate* the probability of making a type I + error (that is, rejecting the null hypothesis although it is true), and the + power of the test is low (that is, it is less likely to reject the null + hypothesis even when the null hypothesis is false). + This is because the Monte Carlo samples are less likely to agree with the + null-hypothesized distribution as well as `data`. This tends to increase + the values of the statistic recorded in the null distribution, so that a + larger number of them exceed the value of statistic for `data`, thereby + inflating the p-value. + + References + ---------- + .. [1] M. A. Stephens (1974). "EDF Statistics for Goodness of Fit and + Some Comparisons." Journal of the American Statistical Association, + Vol. 69, pp. 730-737. + .. [2] W. Stute, W. G. Manteiga, and M. P. Quindimil (1993). + "Bootstrap based goodness-of-fit-tests." Metrika 40.1: 243-256. + .. [3] C. Genest, & B Rémillard. (2008). "Validity of the parametric + bootstrap for goodness-of-fit testing in semiparametric models." + Annales de l'IHP Probabilités et statistiques. Vol. 44. No. 6. + .. [4] I. Kojadinovic and J. Yan (2012). "Goodness-of-fit testing based on + a weighted bootstrap: A fast large-sample alternative to the + parametric bootstrap." Canadian Journal of Statistics 40.3: 480-500. + .. [5] B. Phipson and G. K. Smyth (2010). "Permutation P-values Should + Never Be Zero: Calculating Exact P-values When Permutations Are + Randomly Drawn." Statistical Applications in Genetics and Molecular + Biology 9.1. + .. [6] H. W. Lilliefors (1967). "On the Kolmogorov-Smirnov test for + normality with mean and variance unknown." Journal of the American + statistical Association 62.318: 399-402. + .. [7] Filliben, James J. "The probability plot correlation coefficient + test for normality." Technometrics 17.1 (1975): 111-117. + + Examples + -------- + A well-known test of the null hypothesis that data were drawn from a + given distribution is the Kolmogorov-Smirnov (KS) test, available in SciPy + as `scipy.stats.ks_1samp`. Suppose we wish to test whether the following + data: + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = stats.uniform.rvs(size=75, random_state=rng) + + were sampled from a normal distribution. To perform a KS test, the + empirical distribution function of the observed data will be compared + against the (theoretical) cumulative distribution function of a normal + distribution. Of course, to do this, the normal distribution under the null + hypothesis must be fully specified. This is commonly done by first fitting + the ``loc`` and ``scale`` parameters of the distribution to the observed + data, then performing the test. + + >>> loc, scale = np.mean(x), np.std(x, ddof=1) + >>> cdf = stats.norm(loc, scale).cdf + >>> stats.ks_1samp(x, cdf) + KstestResult(statistic=0.1119257570456813, + pvalue=0.2827756409939257, + statistic_location=0.7751845155861765, + statistic_sign=-1) + + An advantage of the KS-test is that the p-value - the probability of + obtaining a value of the test statistic under the null hypothesis as + extreme as the value obtained from the observed data - can be calculated + exactly and efficiently. `goodness_of_fit` can only approximate these + results. + + >>> known_params = {'loc': loc, 'scale': scale} + >>> res = stats.goodness_of_fit(stats.norm, x, known_params=known_params, + ... statistic='ks', rng=rng) + >>> res.statistic, res.pvalue + (0.1119257570456813, 0.2788) + + The statistic matches exactly, but the p-value is estimated by forming + a "Monte Carlo null distribution", that is, by explicitly drawing random + samples from `scipy.stats.norm` with the provided parameters and + calculating the stastic for each. The fraction of these statistic values + at least as extreme as ``res.statistic`` approximates the exact p-value + calculated by `scipy.stats.ks_1samp`. + + However, in many cases, we would prefer to test only that the data were + sampled from one of *any* member of the normal distribution family, not + specifically from the normal distribution with the location and scale + fitted to the observed sample. In this case, Lilliefors [6]_ argued that + the KS test is far too conservative (that is, the p-value overstates + the actual probability of rejecting a true null hypothesis) and thus lacks + power - the ability to reject the null hypothesis when the null hypothesis + is actually false. + Indeed, our p-value above is approximately 0.28, which is far too large + to reject the null hypothesis at any common significance level. + + Consider why this might be. Note that in the KS test above, the statistic + always compares data against the CDF of a normal distribution fitted to the + *observed data*. This tends to reduce the value of the statistic for the + observed data, but it is "unfair" when computing the statistic for other + samples, such as those we randomly draw to form the Monte Carlo null + distribution. It is easy to correct for this: whenever we compute the KS + statistic of a sample, we use the CDF of a normal distribution fitted + to *that sample*. The null distribution in this case has not been + calculated exactly and is tyically approximated using Monte Carlo methods + as described above. This is where `goodness_of_fit` excels. + + >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ks', + ... rng=rng) + >>> res.statistic, res.pvalue + (0.1119257570456813, 0.0196) + + Indeed, this p-value is much smaller, and small enough to (correctly) + reject the null hypothesis at common significance levels, including 5% and + 2.5%. + + However, the KS statistic is not very sensitive to all deviations from + normality. The original advantage of the KS statistic was the ability + to compute the null distribution theoretically, but a more sensitive + statistic - resulting in a higher test power - can be used now that we can + approximate the null distribution + computationally. The Anderson-Darling statistic [1]_ tends to be more + sensitive, and critical values of the this statistic have been tabulated + for various significance levels and sample sizes using Monte Carlo methods. + + >>> res = stats.anderson(x, 'norm') + >>> print(res.statistic) + 1.2139573337497467 + >>> print(res.critical_values) + [0.549 0.625 0.75 0.875 1.041] + >>> print(res.significance_level) + [15. 10. 5. 2.5 1. ] + + Here, the observed value of the statistic exceeds the critical value + corresponding with a 1% significance level. This tells us that the p-value + of the observed data is less than 1%, but what is it? We could interpolate + from these (already-interpolated) values, but `goodness_of_fit` can + estimate it directly. + + >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ad', + ... rng=rng) + >>> res.statistic, res.pvalue + (1.2139573337497467, 0.0034) + + A further advantage is that use of `goodness_of_fit` is not limited to + a particular set of distributions or conditions on which parameters + are known versus which must be estimated from data. Instead, + `goodness_of_fit` can estimate p-values relatively quickly for any + distribution with a sufficiently fast and reliable ``fit`` method. For + instance, here we perform a goodness of fit test using the Cramer-von Mises + statistic against the Rayleigh distribution with known location and unknown + scale. + + >>> rng = np.random.default_rng() + >>> x = stats.chi(df=2.2, loc=0, scale=2).rvs(size=1000, random_state=rng) + >>> res = stats.goodness_of_fit(stats.rayleigh, x, statistic='cvm', + ... known_params={'loc': 0}, rng=rng) + + This executes fairly quickly, but to check the reliability of the ``fit`` + method, we should inspect the fit result. + + >>> res.fit_result # location is as specified, and scale is reasonable + params: FitParams(loc=0.0, scale=2.1026719844231243) + success: True + message: 'The fit was performed successfully.' + >>> import matplotlib.pyplot as plt # matplotlib must be installed to plot + >>> res.fit_result.plot() + >>> plt.show() + + If the distribution is not fit to the observed data as well as possible, + the test may not control the type I error rate, that is, the chance of + rejecting the null hypothesis even when it is true. + + We should also look for extreme outliers in the null distribution that + may be caused by unreliable fitting. These do not necessarily invalidate + the result, but they tend to reduce the test's power. + + >>> _, ax = plt.subplots() + >>> ax.hist(np.log10(res.null_distribution)) + >>> ax.set_xlabel("log10 of CVM statistic under the null hypothesis") + >>> ax.set_ylabel("Frequency") + >>> ax.set_title("Histogram of the Monte Carlo null distribution") + >>> plt.show() + + This plot seems reassuring. + + If ``fit`` method is working reliably, and if the distribution of the test + statistic is not particularly sensitive to the values of the fitted + parameters, then the p-value provided by `goodness_of_fit` is expected to + be a good approximation. + + >>> res.statistic, res.pvalue + (0.2231991510248692, 0.0525) + + """ + args = _gof_iv(dist, data, known_params, fit_params, guessed_params, + statistic, n_mc_samples, rng) + (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params, + guessed_rfd_params, statistic, n_mc_samples_int, rng) = args + + # Fit null hypothesis distribution to data + nhd_fit_fun = _get_fit_fun(dist, data, guessed_nhd_params, + fixed_nhd_params) + nhd_vals = nhd_fit_fun(data) + nhd_dist = dist(*nhd_vals) + + def rvs(size): + return nhd_dist.rvs(size=size, random_state=rng) + + # Define statistic + fit_fun = _get_fit_fun(dist, data, guessed_rfd_params, fixed_rfd_params) + if callable(statistic): + compare_fun = statistic + else: + compare_fun = _compare_dict[statistic] + alternative = getattr(compare_fun, 'alternative', 'greater') + + def statistic_fun(data, axis): + # Make things simple by always working along the last axis. + data = np.moveaxis(data, axis, -1) + rfd_vals = fit_fun(data) + rfd_dist = dist(*rfd_vals) + return compare_fun(rfd_dist, data, axis=-1) + + res = stats.monte_carlo_test(data, rvs, statistic_fun, vectorized=True, + n_resamples=n_mc_samples, axis=-1, + alternative=alternative) + opt_res = optimize.OptimizeResult() + opt_res.success = True + opt_res.message = "The fit was performed successfully." + opt_res.x = nhd_vals + # Only continuous distributions for now, hence discrete=False + # There's no fundamental limitation; it's just that we're not using + # stats.fit, discrete distributions don't have `fit` method, and + # we haven't written any vectorized fit functions for a discrete + # distribution yet. + return GoodnessOfFitResult(FitResult(dist, data, False, opt_res), + res.statistic, res.pvalue, + res.null_distribution) + + +def _get_fit_fun(dist, data, guessed_params, fixed_params): + + shape_names = [] if dist.shapes is None else dist.shapes.split(", ") + param_names = shape_names + ['loc', 'scale'] + fparam_names = ['f'+name for name in param_names] + all_fixed = not set(fparam_names).difference(fixed_params) + guessed_shapes = [guessed_params.pop(x, None) + for x in shape_names if x in guessed_params] + + if all_fixed: + def fit_fun(data): + return [fixed_params[name] for name in fparam_names] + # Define statistic, including fitting distribution to data + elif dist in _fit_funs: + def fit_fun(data): + params = _fit_funs[dist](data, **fixed_params) + params = np.asarray(np.broadcast_arrays(*params)) + if params.ndim > 1: + params = params[..., np.newaxis] + return params + else: + def fit_fun_1d(data): + return dist.fit(data, *guessed_shapes, **guessed_params, + **fixed_params) + + def fit_fun(data): + params = np.apply_along_axis(fit_fun_1d, axis=-1, arr=data) + if params.ndim > 1: + params = params.T[..., np.newaxis] + return params + + return fit_fun + + +# Vectorized fitting functions. These are to accept ND `data` in which each +# row (slice along last axis) is a sample to fit and scalar fixed parameters. +# They return a tuple of shape parameter arrays, each of shape data.shape[:-1]. +def _fit_norm(data, floc=None, fscale=None): + loc = floc + scale = fscale + if loc is None and scale is None: + loc = np.mean(data, axis=-1) + scale = np.std(data, ddof=1, axis=-1) + elif loc is None: + loc = np.mean(data, axis=-1) + elif scale is None: + scale = np.sqrt(((data - loc)**2).mean(axis=-1)) + return loc, scale + + +_fit_funs = {stats.norm: _fit_norm} # type: ignore[attr-defined] + + +# Vectorized goodness of fit statistic functions. These accept a frozen +# distribution object and `data` in which each row (slice along last axis) is +# a sample. + + +def _anderson_darling(dist, data, axis): + x = np.sort(data, axis=-1) + n = data.shape[-1] + i = np.arange(1, n+1) + Si = (2*i - 1)/n * (dist.logcdf(x) + dist.logsf(x[..., ::-1])) + S = np.sum(Si, axis=-1) + return -n - S + + +def _compute_dplus(cdfvals): # adapted from _stats_py before gh-17062 + n = cdfvals.shape[-1] + return (np.arange(1.0, n + 1) / n - cdfvals).max(axis=-1) + + +def _compute_dminus(cdfvals): + n = cdfvals.shape[-1] + return (cdfvals - np.arange(0.0, n)/n).max(axis=-1) + + +def _kolmogorov_smirnov(dist, data, axis=-1): + x = np.sort(data, axis=axis) + cdfvals = dist.cdf(x) + cdfvals = np.moveaxis(cdfvals, axis, -1) + Dplus = _compute_dplus(cdfvals) # always works along last axis + Dminus = _compute_dminus(cdfvals) + return np.maximum(Dplus, Dminus) + + +def _corr(X, M): + # Correlation coefficient r, simplified and vectorized as we need it. + # See [7] Equation (2). Lemma 1/2 are only for distributions symmetric + # about 0. + Xm = X.mean(axis=-1, keepdims=True) + Mm = M.mean(axis=-1, keepdims=True) + num = np.sum((X - Xm) * (M - Mm), axis=-1) + den = np.sqrt(np.sum((X - Xm)**2, axis=-1) * np.sum((M - Mm)**2, axis=-1)) + return num/den + + +def _filliben(dist, data, axis): + # [7] Section 8 # 1 + X = np.sort(data, axis=-1) + + # [7] Section 8 # 2 + n = data.shape[-1] + k = np.arange(1, n+1) + # Filliben used an approximation for the uniform distribution order + # statistic medians. + # m = (k - .3175)/(n + 0.365) + # m[-1] = 0.5**(1/n) + # m[0] = 1 - m[-1] + # We can just as easily use the (theoretically) exact values. See e.g. + # https://en.wikipedia.org/wiki/Order_statistic + # "Order statistics sampled from a uniform distribution" + m = stats.beta(k, n + 1 - k).median() + + # [7] Section 8 # 3 + M = dist.ppf(m) + + # [7] Section 8 # 4 + return _corr(X, M) +_filliben.alternative = 'less' # type: ignore[attr-defined] + + +def _cramer_von_mises(dist, data, axis): + x = np.sort(data, axis=-1) + n = data.shape[-1] + cdfvals = dist.cdf(x) + u = (2*np.arange(1, n+1) - 1)/(2*n) + w = 1 / (12*n) + np.sum((u - cdfvals)**2, axis=-1) + return w + + +_compare_dict = {"ad": _anderson_darling, "ks": _kolmogorov_smirnov, + "cvm": _cramer_von_mises, "filliben": _filliben} + + +def _gof_iv(dist, data, known_params, fit_params, guessed_params, statistic, + n_mc_samples, rng): + + if not isinstance(dist, stats.rv_continuous): + message = ("`dist` must be a (non-frozen) instance of " + "`stats.rv_continuous`.") + raise TypeError(message) + + data = np.asarray(data, dtype=float) + if not data.ndim == 1: + message = "`data` must be a one-dimensional array of numbers." + raise ValueError(message) + + # Leave validation of these key/value pairs to the `fit` method, + # but collect these into dictionaries that will be used + known_params = known_params or dict() + fit_params = fit_params or dict() + guessed_params = guessed_params or dict() + + known_params_f = {("f"+key): val for key, val in known_params.items()} + fit_params_f = {("f"+key): val for key, val in fit_params.items()} + + # These are the values of parameters of the null distribution family + # with which resamples are drawn + fixed_nhd_params = known_params_f.copy() + fixed_nhd_params.update(fit_params_f) + + # These are fixed when fitting the distribution family to resamples + fixed_rfd_params = known_params_f.copy() + + # These are used as guesses when fitting the distribution family to + # the original data + guessed_nhd_params = guessed_params.copy() + + # These are used as guesses when fitting the distribution family to + # resamples + guessed_rfd_params = fit_params.copy() + guessed_rfd_params.update(guessed_params) + + if not callable(statistic): + statistic = statistic.lower() + statistics = {'ad', 'ks', 'cvm', 'filliben'} + if statistic not in statistics: + message = f"`statistic` must be one of {statistics}." + raise ValueError(message) + + n_mc_samples_int = int(n_mc_samples) + if n_mc_samples_int != n_mc_samples: + message = "`n_mc_samples` must be an integer." + raise TypeError(message) + + rng = check_random_state(rng) + + return (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params, + guessed_rfd_params, statistic, n_mc_samples_int, rng) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_hypotests.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_hypotests.py new file mode 100644 index 0000000000000000000000000000000000000000..3764b96bdcacd38c44cda9aa841103f8cff67a0b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_hypotests.py @@ -0,0 +1,2027 @@ +from collections import namedtuple +from dataclasses import dataclass +from math import comb +import numpy as np +import warnings +from itertools import combinations +import scipy.stats +from scipy.optimize import shgo +from . import distributions +from ._common import ConfidenceInterval +from ._continuous_distns import norm +from scipy.special import gamma, kv, gammaln +from scipy.fft import ifft +from ._stats_pythran import _a_ij_Aij_Dij2 +from ._stats_pythran import ( + _concordant_pairs as _P, _discordant_pairs as _Q +) +from ._axis_nan_policy import _axis_nan_policy_factory +from scipy.stats import _stats_py + +__all__ = ['epps_singleton_2samp', 'cramervonmises', 'somersd', + 'barnard_exact', 'boschloo_exact', 'cramervonmises_2samp', + 'tukey_hsd', 'poisson_means_test'] + +Epps_Singleton_2sampResult = namedtuple('Epps_Singleton_2sampResult', + ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(Epps_Singleton_2sampResult, n_samples=2, too_small=4) +def epps_singleton_2samp(x, y, t=(0.4, 0.8)): + """Compute the Epps-Singleton (ES) test statistic. + + Test the null hypothesis that two samples have the same underlying + probability distribution. + + Parameters + ---------- + x, y : array-like + The two samples of observations to be tested. Input must not have more + than one dimension. Samples can have different lengths, but both + must have at least five observations. + t : array-like, optional + The points (t1, ..., tn) where the empirical characteristic function is + to be evaluated. It should be positive distinct numbers. The default + value (0.4, 0.8) is proposed in [1]_. Input must not have more than + one dimension. + + Returns + ------- + statistic : float + The test statistic. + pvalue : float + The associated p-value based on the asymptotic chi2-distribution. + + See Also + -------- + ks_2samp, anderson_ksamp + + Notes + ----- + Testing whether two samples are generated by the same underlying + distribution is a classical question in statistics. A widely used test is + the Kolmogorov-Smirnov (KS) test which relies on the empirical + distribution function. Epps and Singleton introduce a test based on the + empirical characteristic function in [1]_. + + One advantage of the ES test compared to the KS test is that is does + not assume a continuous distribution. In [1]_, the authors conclude + that the test also has a higher power than the KS test in many + examples. They recommend the use of the ES test for discrete samples as + well as continuous samples with at least 25 observations each, whereas + `anderson_ksamp` is recommended for smaller sample sizes in the + continuous case. + + The p-value is computed from the asymptotic distribution of the test + statistic which follows a `chi2` distribution. If the sample size of both + `x` and `y` is below 25, the small sample correction proposed in [1]_ is + applied to the test statistic. + + The default values of `t` are determined in [1]_ by considering + various distributions and finding good values that lead to a high power + of the test in general. Table III in [1]_ gives the optimal values for + the distributions tested in that study. The values of `t` are scaled by + the semi-interquartile range in the implementation, see [1]_. + + References + ---------- + .. [1] T. W. Epps and K. J. Singleton, "An omnibus test for the two-sample + problem using the empirical characteristic function", Journal of + Statistical Computation and Simulation 26, p. 177--203, 1986. + + .. [2] S. J. Goerg and J. Kaiser, "Nonparametric testing of distributions + - the Epps-Singleton two-sample test using the empirical characteristic + function", The Stata Journal 9(3), p. 454--465, 2009. + + """ + # x and y are converted to arrays by the decorator + t = np.asarray(t) + # check if x and y are valid inputs + nx, ny = len(x), len(y) + if (nx < 5) or (ny < 5): + raise ValueError('x and y should have at least 5 elements, but len(x) ' + f'= {nx} and len(y) = {ny}.') + if not np.isfinite(x).all(): + raise ValueError('x must not contain nonfinite values.') + if not np.isfinite(y).all(): + raise ValueError('y must not contain nonfinite values.') + n = nx + ny + + # check if t is valid + if t.ndim > 1: + raise ValueError(f't must be 1d, but t.ndim equals {t.ndim}.') + if np.less_equal(t, 0).any(): + raise ValueError('t must contain positive elements only.') + + # rescale t with semi-iqr as proposed in [1]; import iqr here to avoid + # circular import + from scipy.stats import iqr + sigma = iqr(np.hstack((x, y))) / 2 + ts = np.reshape(t, (-1, 1)) / sigma + + # covariance estimation of ES test + gx = np.vstack((np.cos(ts*x), np.sin(ts*x))).T # shape = (nx, 2*len(t)) + gy = np.vstack((np.cos(ts*y), np.sin(ts*y))).T + cov_x = np.cov(gx.T, bias=True) # the test uses biased cov-estimate + cov_y = np.cov(gy.T, bias=True) + est_cov = (n/nx)*cov_x + (n/ny)*cov_y + est_cov_inv = np.linalg.pinv(est_cov) + r = np.linalg.matrix_rank(est_cov_inv) + if r < 2*len(t): + warnings.warn('Estimated covariance matrix does not have full rank. ' + 'This indicates a bad choice of the input t and the ' + 'test might not be consistent.', # see p. 183 in [1]_ + stacklevel=2) + + # compute test statistic w distributed asympt. as chisquare with df=r + g_diff = np.mean(gx, axis=0) - np.mean(gy, axis=0) + w = n*np.dot(g_diff.T, np.dot(est_cov_inv, g_diff)) + + # apply small-sample correction + if (max(nx, ny) < 25): + corr = 1.0/(1.0 + n**(-0.45) + 10.1*(nx**(-1.7) + ny**(-1.7))) + w = corr * w + + chi2 = _stats_py._SimpleChi2(r) + p = _stats_py._get_pvalue(w, chi2, alternative='greater', symmetric=False, xp=np) + + return Epps_Singleton_2sampResult(w, p) + + +def poisson_means_test(k1, n1, k2, n2, *, diff=0, alternative='two-sided'): + r""" + Performs the Poisson means test, AKA the "E-test". + + This is a test of the null hypothesis that the difference between means of + two Poisson distributions is `diff`. The samples are provided as the + number of events `k1` and `k2` observed within measurement intervals + (e.g. of time, space, number of observations) of sizes `n1` and `n2`. + + Parameters + ---------- + k1 : int + Number of events observed from distribution 1. + n1: float + Size of sample from distribution 1. + k2 : int + Number of events observed from distribution 2. + n2 : float + Size of sample from distribution 2. + diff : float, default=0 + The hypothesized difference in means between the distributions + underlying the samples. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the difference between distribution means is not + equal to `diff` + * 'less': the difference between distribution means is less than + `diff` + * 'greater': the difference between distribution means is greater + than `diff` + + Returns + ------- + statistic : float + The test statistic (see [1]_ equation 3.3). + pvalue : float + The probability of achieving such an extreme value of the test + statistic under the null hypothesis. + + Notes + ----- + + Let: + + .. math:: X_1 \sim \mbox{Poisson}(\mathtt{n1}\lambda_1) + + be a random variable independent of + + .. math:: X_2 \sim \mbox{Poisson}(\mathtt{n2}\lambda_2) + + and let ``k1`` and ``k2`` be the observed values of :math:`X_1` + and :math:`X_2`, respectively. Then `poisson_means_test` uses the number + of observed events ``k1`` and ``k2`` from samples of size ``n1`` and + ``n2``, respectively, to test the null hypothesis that + + .. math:: + H_0: \lambda_1 - \lambda_2 = \mathtt{diff} + + A benefit of the E-test is that it has good power for small sample sizes, + which can reduce sampling costs [1]_. It has been evaluated and determined + to be more powerful than the comparable C-test, sometimes referred to as + the Poisson exact test. + + References + ---------- + .. [1] Krishnamoorthy, K., & Thomson, J. (2004). A more powerful test for + comparing two Poisson means. Journal of Statistical Planning and + Inference, 119(1), 23-35. + + .. [2] Przyborowski, J., & Wilenski, H. (1940). Homogeneity of results in + testing samples from Poisson series: With an application to testing + clover seed for dodder. Biometrika, 31(3/4), 313-323. + + Examples + -------- + + Suppose that a gardener wishes to test the number of dodder (weed) seeds + in a sack of clover seeds that they buy from a seed company. It has + previously been established that the number of dodder seeds in clover + follows the Poisson distribution. + + A 100 gram sample is drawn from the sack before being shipped to the + gardener. The sample is analyzed, and it is found to contain no dodder + seeds; that is, `k1` is 0. However, upon arrival, the gardener draws + another 100 gram sample from the sack. This time, three dodder seeds are + found in the sample; that is, `k2` is 3. The gardener would like to + know if the difference is significant and not due to chance. The + null hypothesis is that the difference between the two samples is merely + due to chance, or that :math:`\lambda_1 - \lambda_2 = \mathtt{diff}` + where :math:`\mathtt{diff} = 0`. The alternative hypothesis is that the + difference is not due to chance, or :math:`\lambda_1 - \lambda_2 \ne 0`. + The gardener selects a significance level of 5% to reject the null + hypothesis in favor of the alternative [2]_. + + >>> import scipy.stats as stats + >>> res = stats.poisson_means_test(0, 100, 3, 100) + >>> res.statistic, res.pvalue + (-1.7320508075688772, 0.08837900929018157) + + The p-value is .088, indicating a near 9% chance of observing a value of + the test statistic under the null hypothesis. This exceeds 5%, so the + gardener does not reject the null hypothesis as the difference cannot be + regarded as significant at this level. + """ + + _poisson_means_test_iv(k1, n1, k2, n2, diff, alternative) + + # "for a given k_1 and k_2, an estimate of \lambda_2 is given by" [1] (3.4) + lmbd_hat2 = ((k1 + k2) / (n1 + n2) - diff * n1 / (n1 + n2)) + + # "\hat{\lambda_{2k}} may be less than or equal to zero ... and in this + # case the null hypothesis cannot be rejected ... [and] it is not necessary + # to compute the p-value". [1] page 26 below eq. (3.6). + if lmbd_hat2 <= 0: + return _stats_py.SignificanceResult(0, 1) + + # The unbiased variance estimate [1] (3.2) + var = k1 / (n1 ** 2) + k2 / (n2 ** 2) + + # The _observed_ pivot statistic from the input. It follows the + # unnumbered equation following equation (3.3) This is used later in + # comparison with the computed pivot statistics in an indicator function. + t_k1k2 = (k1 / n1 - k2 / n2 - diff) / np.sqrt(var) + + # Equation (3.5) of [1] is lengthy, so it is broken into several parts, + # beginning here. Note that the probability mass function of poisson is + # exp^(-\mu)*\mu^k/k!, so and this is called with shape \mu, here noted + # here as nlmbd_hat*. The strategy for evaluating the double summation in + # (3.5) is to create two arrays of the values of the two products inside + # the summation and then broadcast them together into a matrix, and then + # sum across the entire matrix. + + # Compute constants (as seen in the first and second separated products in + # (3.5).). (This is the shape (\mu) parameter of the poisson distribution.) + nlmbd_hat1 = n1 * (lmbd_hat2 + diff) + nlmbd_hat2 = n2 * lmbd_hat2 + + # Determine summation bounds for tail ends of distribution rather than + # summing to infinity. `x1*` is for the outer sum and `x2*` is the inner + # sum. + x1_lb, x1_ub = distributions.poisson.ppf([1e-10, 1 - 1e-16], nlmbd_hat1) + x2_lb, x2_ub = distributions.poisson.ppf([1e-10, 1 - 1e-16], nlmbd_hat2) + + # Construct arrays to function as the x_1 and x_2 counters on the summation + # in (3.5). `x1` is in columns and `x2` is in rows to allow for + # broadcasting. + x1 = np.arange(x1_lb, x1_ub + 1) + x2 = np.arange(x2_lb, x2_ub + 1)[:, None] + + # These are the two products in equation (3.5) with `prob_x1` being the + # first (left side) and `prob_x2` being the second (right side). (To + # make as clear as possible: the 1st contains a "+ d" term, the 2nd does + # not.) + prob_x1 = distributions.poisson.pmf(x1, nlmbd_hat1) + prob_x2 = distributions.poisson.pmf(x2, nlmbd_hat2) + + # compute constants for use in the "pivot statistic" per the + # unnumbered equation following (3.3). + lmbd_x1 = x1 / n1 + lmbd_x2 = x2 / n2 + lmbds_diff = lmbd_x1 - lmbd_x2 - diff + var_x1x2 = lmbd_x1 / n1 + lmbd_x2 / n2 + + # This is the 'pivot statistic' for use in the indicator of the summation + # (left side of "I[.]"). + with np.errstate(invalid='ignore', divide='ignore'): + t_x1x2 = lmbds_diff / np.sqrt(var_x1x2) + + # `[indicator]` implements the "I[.] ... the indicator function" per + # the paragraph following equation (3.5). + if alternative == 'two-sided': + indicator = np.abs(t_x1x2) >= np.abs(t_k1k2) + elif alternative == 'less': + indicator = t_x1x2 <= t_k1k2 + else: + indicator = t_x1x2 >= t_k1k2 + + # Multiply all combinations of the products together, exclude terms + # based on the `indicator` and then sum. (3.5) + pvalue = np.sum((prob_x1 * prob_x2)[indicator]) + return _stats_py.SignificanceResult(t_k1k2, pvalue) + + +def _poisson_means_test_iv(k1, n1, k2, n2, diff, alternative): + # """check for valid types and values of input to `poisson_mean_test`.""" + if k1 != int(k1) or k2 != int(k2): + raise TypeError('`k1` and `k2` must be integers.') + + count_err = '`k1` and `k2` must be greater than or equal to 0.' + if k1 < 0 or k2 < 0: + raise ValueError(count_err) + + if n1 <= 0 or n2 <= 0: + raise ValueError('`n1` and `n2` must be greater than 0.') + + if diff < 0: + raise ValueError('diff must be greater than or equal to 0.') + + alternatives = {'two-sided', 'less', 'greater'} + if alternative.lower() not in alternatives: + raise ValueError(f"Alternative must be one of '{alternatives}'.") + + +class CramerVonMisesResult: + def __init__(self, statistic, pvalue): + self.statistic = statistic + self.pvalue = pvalue + + def __repr__(self): + return (f"{self.__class__.__name__}(statistic={self.statistic}, " + f"pvalue={self.pvalue})") + + +def _psi1_mod(x): + """ + psi1 is defined in equation 1.10 in Csörgő, S. and Faraway, J. (1996). + This implements a modified version by excluding the term V(x) / 12 + (here: _cdf_cvm_inf(x) / 12) to avoid evaluating _cdf_cvm_inf(x) + twice in _cdf_cvm. + + Implementation based on MAPLE code of Julian Faraway and R code of the + function pCvM in the package goftest (v1.1.1), permission granted + by Adrian Baddeley. Main difference in the implementation: the code + here keeps adding terms of the series until the terms are small enough. + """ + + def _ed2(y): + z = y**2 / 4 + b = kv(1/4, z) + kv(3/4, z) + return np.exp(-z) * (y/2)**(3/2) * b / np.sqrt(np.pi) + + def _ed3(y): + z = y**2 / 4 + c = np.exp(-z) / np.sqrt(np.pi) + return c * (y/2)**(5/2) * (2*kv(1/4, z) + 3*kv(3/4, z) - kv(5/4, z)) + + def _Ak(k, x): + m = 2*k + 1 + sx = 2 * np.sqrt(x) + y1 = x**(3/4) + y2 = x**(5/4) + + e1 = m * gamma(k + 1/2) * _ed2((4 * k + 3)/sx) / (9 * y1) + e2 = gamma(k + 1/2) * _ed3((4 * k + 1) / sx) / (72 * y2) + e3 = 2 * (m + 2) * gamma(k + 3/2) * _ed3((4 * k + 5) / sx) / (12 * y2) + e4 = 7 * m * gamma(k + 1/2) * _ed2((4 * k + 1) / sx) / (144 * y1) + e5 = 7 * m * gamma(k + 1/2) * _ed2((4 * k + 5) / sx) / (144 * y1) + + return e1 + e2 + e3 + e4 + e5 + + x = np.asarray(x) + tot = np.zeros_like(x, dtype='float') + cond = np.ones_like(x, dtype='bool') + k = 0 + while np.any(cond): + z = -_Ak(k, x[cond]) / (np.pi * gamma(k + 1)) + tot[cond] = tot[cond] + z + cond[cond] = np.abs(z) >= 1e-7 + k += 1 + + return tot + + +def _cdf_cvm_inf(x): + """ + Calculate the cdf of the Cramér-von Mises statistic (infinite sample size). + + See equation 1.2 in Csörgő, S. and Faraway, J. (1996). + + Implementation based on MAPLE code of Julian Faraway and R code of the + function pCvM in the package goftest (v1.1.1), permission granted + by Adrian Baddeley. Main difference in the implementation: the code + here keeps adding terms of the series until the terms are small enough. + + The function is not expected to be accurate for large values of x, say + x > 4, when the cdf is very close to 1. + """ + x = np.asarray(x) + + def term(x, k): + # this expression can be found in [2], second line of (1.3) + u = np.exp(gammaln(k + 0.5) - gammaln(k+1)) / (np.pi**1.5 * np.sqrt(x)) + y = 4*k + 1 + q = y**2 / (16*x) + b = kv(0.25, q) + return u * np.sqrt(y) * np.exp(-q) * b + + tot = np.zeros_like(x, dtype='float') + cond = np.ones_like(x, dtype='bool') + k = 0 + while np.any(cond): + z = term(x[cond], k) + tot[cond] = tot[cond] + z + cond[cond] = np.abs(z) >= 1e-7 + k += 1 + + return tot + + +def _cdf_cvm(x, n=None): + """ + Calculate the cdf of the Cramér-von Mises statistic for a finite sample + size n. If N is None, use the asymptotic cdf (n=inf). + + See equation 1.8 in Csörgő, S. and Faraway, J. (1996) for finite samples, + 1.2 for the asymptotic cdf. + + The function is not expected to be accurate for large values of x, say + x > 2, when the cdf is very close to 1 and it might return values > 1 + in that case, e.g. _cdf_cvm(2.0, 12) = 1.0000027556716846. Moreover, it + is not accurate for small values of n, especially close to the bounds of + the distribution's domain, [1/(12*n), n/3], where the value jumps to 0 + and 1, respectively. These are limitations of the approximation by Csörgő + and Faraway (1996) implemented in this function. + """ + x = np.asarray(x) + if n is None: + y = _cdf_cvm_inf(x) + else: + # support of the test statistic is [12/n, n/3], see 1.1 in [2] + y = np.zeros_like(x, dtype='float') + sup = (1./(12*n) < x) & (x < n/3.) + # note: _psi1_mod does not include the term _cdf_cvm_inf(x) / 12 + # therefore, we need to add it here + y[sup] = _cdf_cvm_inf(x[sup]) * (1 + 1./(12*n)) + _psi1_mod(x[sup]) / n + y[x >= n/3] = 1 + + if y.ndim == 0: + return y[()] + return y + + +def _cvm_result_to_tuple(res): + return res.statistic, res.pvalue + + +@_axis_nan_policy_factory(CramerVonMisesResult, n_samples=1, too_small=1, + result_to_tuple=_cvm_result_to_tuple) +def cramervonmises(rvs, cdf, args=()): + """Perform the one-sample Cramér-von Mises test for goodness of fit. + + This performs a test of the goodness of fit of a cumulative distribution + function (cdf) :math:`F` compared to the empirical distribution function + :math:`F_n` of observed random variates :math:`X_1, ..., X_n` that are + assumed to be independent and identically distributed ([1]_). + The null hypothesis is that the :math:`X_i` have cumulative distribution + :math:`F`. + + Parameters + ---------- + rvs : array_like + A 1-D array of observed values of the random variables :math:`X_i`. + The sample must contain at least two observations. + cdf : str or callable + The cumulative distribution function :math:`F` to test the + observations against. If a string, it should be the name of a + distribution in `scipy.stats`. If a callable, that callable is used + to calculate the cdf: ``cdf(x, *args) -> float``. + args : tuple, optional + Distribution parameters. These are assumed to be known; see Notes. + + Returns + ------- + res : object with attributes + statistic : float + Cramér-von Mises statistic. + pvalue : float + The p-value. + + See Also + -------- + kstest, cramervonmises_2samp + + Notes + ----- + .. versionadded:: 1.6.0 + + The p-value relies on the approximation given by equation 1.8 in [2]_. + It is important to keep in mind that the p-value is only accurate if + one tests a simple hypothesis, i.e. the parameters of the reference + distribution are known. If the parameters are estimated from the data + (composite hypothesis), the computed p-value is not reliable. + + References + ---------- + .. [1] Cramér-von Mises criterion, Wikipedia, + https://en.wikipedia.org/wiki/Cram%C3%A9r%E2%80%93von_Mises_criterion + .. [2] Csörgő, S. and Faraway, J. (1996). The Exact and Asymptotic + Distribution of Cramér-von Mises Statistics. Journal of the + Royal Statistical Society, pp. 221-234. + + Examples + -------- + + Suppose we wish to test whether data generated by ``scipy.stats.norm.rvs`` + were, in fact, drawn from the standard normal distribution. We choose a + significance level of ``alpha=0.05``. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(165417232101553420507139617764912913465) + >>> x = stats.norm.rvs(size=500, random_state=rng) + >>> res = stats.cramervonmises(x, 'norm') + >>> res.statistic, res.pvalue + (0.1072085112565724, 0.5508482238203407) + + The p-value exceeds our chosen significance level, so we do not + reject the null hypothesis that the observed sample is drawn from the + standard normal distribution. + + Now suppose we wish to check whether the same samples shifted by 2.1 is + consistent with being drawn from a normal distribution with a mean of 2. + + >>> y = x + 2.1 + >>> res = stats.cramervonmises(y, 'norm', args=(2,)) + >>> res.statistic, res.pvalue + (0.8364446265294695, 0.00596286797008283) + + Here we have used the `args` keyword to specify the mean (``loc``) + of the normal distribution to test the data against. This is equivalent + to the following, in which we create a frozen normal distribution with + mean 2.1, then pass its ``cdf`` method as an argument. + + >>> frozen_dist = stats.norm(loc=2) + >>> res = stats.cramervonmises(y, frozen_dist.cdf) + >>> res.statistic, res.pvalue + (0.8364446265294695, 0.00596286797008283) + + In either case, we would reject the null hypothesis that the observed + sample is drawn from a normal distribution with a mean of 2 (and default + variance of 1) because the p-value is less than our chosen + significance level. + + """ + if isinstance(cdf, str): + cdf = getattr(distributions, cdf).cdf + + vals = np.sort(np.asarray(rvs)) + + if vals.size <= 1: + raise ValueError('The sample must contain at least two observations.') + + n = len(vals) + cdfvals = cdf(vals, *args) + + u = (2*np.arange(1, n+1) - 1)/(2*n) + w = 1/(12*n) + np.sum((u - cdfvals)**2) + + # avoid small negative values that can occur due to the approximation + p = np.clip(1. - _cdf_cvm(w, n), 0., None) + + return CramerVonMisesResult(statistic=w, pvalue=p) + + +def _get_wilcoxon_distr(n): + """ + Distribution of probability of the Wilcoxon ranksum statistic r_plus (sum + of ranks of positive differences). + Returns an array with the probabilities of all the possible ranks + r = 0, ..., n*(n+1)/2 + """ + c = np.ones(1, dtype=np.float64) + for k in range(1, n + 1): + prev_c = c + c = np.zeros(k * (k + 1) // 2 + 1, dtype=np.float64) + m = len(prev_c) + c[:m] = prev_c * 0.5 + c[-m:] += prev_c * 0.5 + return c + + +def _get_wilcoxon_distr2(n): + """ + Distribution of probability of the Wilcoxon ranksum statistic r_plus (sum + of ranks of positive differences). + Returns an array with the probabilities of all the possible ranks + r = 0, ..., n*(n+1)/2 + This is a slower reference function + References + ---------- + .. [1] 1. Harris T, Hardin JW. Exact Wilcoxon Signed-Rank and Wilcoxon + Mann-Whitney Ranksum Tests. The Stata Journal. 2013;13(2):337-343. + """ + ai = np.arange(1, n+1)[:, None] + t = n*(n+1)/2 + q = 2*t + j = np.arange(q) + theta = 2*np.pi/q*j + phi_sp = np.prod(np.cos(theta*ai), axis=0) + phi_s = np.exp(1j*theta*t) * phi_sp + p = np.real(ifft(phi_s)) + res = np.zeros(int(t)+1) + res[:-1:] = p[::2] + res[0] /= 2 + res[-1] = res[0] + return res + + +def _tau_b(A): + """Calculate Kendall's tau-b and p-value from contingency table.""" + # See [2] 2.2 and 4.2 + + # contingency table must be truly 2D + if A.shape[0] == 1 or A.shape[1] == 1: + return np.nan, np.nan + + NA = A.sum() + PA = _P(A) + QA = _Q(A) + Sri2 = (A.sum(axis=1)**2).sum() + Scj2 = (A.sum(axis=0)**2).sum() + denominator = (NA**2 - Sri2)*(NA**2 - Scj2) + + tau = (PA-QA)/(denominator)**0.5 + + numerator = 4*(_a_ij_Aij_Dij2(A) - (PA - QA)**2 / NA) + s02_tau_b = numerator/denominator + if s02_tau_b == 0: # Avoid divide by zero + return tau, 0 + Z = tau/s02_tau_b**0.5 + p = 2*norm.sf(abs(Z)) # 2-sided p-value + + return tau, p + + +def _somers_d(A, alternative='two-sided'): + """Calculate Somers' D and p-value from contingency table.""" + # See [3] page 1740 + + # contingency table must be truly 2D + if A.shape[0] <= 1 or A.shape[1] <= 1: + return np.nan, np.nan + + NA = A.sum() + NA2 = NA**2 + PA = _P(A) + QA = _Q(A) + Sri2 = (A.sum(axis=1)**2).sum() + + d = (PA - QA)/(NA2 - Sri2) + + S = _a_ij_Aij_Dij2(A) - (PA-QA)**2/NA + + with np.errstate(divide='ignore'): + Z = (PA - QA)/(4*(S))**0.5 + + norm = _stats_py._SimpleNormal() + p = _stats_py._get_pvalue(Z, norm, alternative, xp=np) + + return d, p + + +@dataclass +class SomersDResult: + statistic: float + pvalue: float + table: np.ndarray + + +def somersd(x, y=None, alternative='two-sided'): + r"""Calculates Somers' D, an asymmetric measure of ordinal association. + + Like Kendall's :math:`\tau`, Somers' :math:`D` is a measure of the + correspondence between two rankings. Both statistics consider the + difference between the number of concordant and discordant pairs in two + rankings :math:`X` and :math:`Y`, and both are normalized such that values + close to 1 indicate strong agreement and values close to -1 indicate + strong disagreement. They differ in how they are normalized. To show the + relationship, Somers' :math:`D` can be defined in terms of Kendall's + :math:`\tau_a`: + + .. math:: + D(Y|X) = \frac{\tau_a(X, Y)}{\tau_a(X, X)} + + Suppose the first ranking :math:`X` has :math:`r` distinct ranks and the + second ranking :math:`Y` has :math:`s` distinct ranks. These two lists of + :math:`n` rankings can also be viewed as an :math:`r \times s` contingency + table in which element :math:`i, j` is the number of rank pairs with rank + :math:`i` in ranking :math:`X` and rank :math:`j` in ranking :math:`Y`. + Accordingly, `somersd` also allows the input data to be supplied as a + single, 2D contingency table instead of as two separate, 1D rankings. + + Note that the definition of Somers' :math:`D` is asymmetric: in general, + :math:`D(Y|X) \neq D(X|Y)`. ``somersd(x, y)`` calculates Somers' + :math:`D(Y|X)`: the "row" variable :math:`X` is treated as an independent + variable, and the "column" variable :math:`Y` is dependent. For Somers' + :math:`D(X|Y)`, swap the input lists or transpose the input table. + + Parameters + ---------- + x : array_like + 1D array of rankings, treated as the (row) independent variable. + Alternatively, a 2D contingency table. + y : array_like, optional + If `x` is a 1D array of rankings, `y` is a 1D array of rankings of the + same length, treated as the (column) dependent variable. + If `x` is 2D, `y` is ignored. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + * 'two-sided': the rank correlation is nonzero + * 'less': the rank correlation is negative (less than zero) + * 'greater': the rank correlation is positive (greater than zero) + + Returns + ------- + res : SomersDResult + A `SomersDResult` object with the following fields: + + statistic : float + The Somers' :math:`D` statistic. + pvalue : float + The p-value for a hypothesis test whose null + hypothesis is an absence of association, :math:`D=0`. + See notes for more information. + table : 2D array + The contingency table formed from rankings `x` and `y` (or the + provided contingency table, if `x` is a 2D array) + + See Also + -------- + kendalltau : Calculates Kendall's tau, another correlation measure. + weightedtau : Computes a weighted version of Kendall's tau. + spearmanr : Calculates a Spearman rank-order correlation coefficient. + pearsonr : Calculates a Pearson correlation coefficient. + + Notes + ----- + This function follows the contingency table approach of [2]_ and + [3]_. *p*-values are computed based on an asymptotic approximation of + the test statistic distribution under the null hypothesis :math:`D=0`. + + Theoretically, hypothesis tests based on Kendall's :math:`tau` and Somers' + :math:`D` should be identical. + However, the *p*-values returned by `kendalltau` are based + on the null hypothesis of *independence* between :math:`X` and :math:`Y` + (i.e. the population from which pairs in :math:`X` and :math:`Y` are + sampled contains equal numbers of all possible pairs), which is more + specific than the null hypothesis :math:`D=0` used here. If the null + hypothesis of independence is desired, it is acceptable to use the + *p*-value returned by `kendalltau` with the statistic returned by + `somersd` and vice versa. For more information, see [2]_. + + Contingency tables are formatted according to the convention used by + SAS and R: the first ranking supplied (``x``) is the "row" variable, and + the second ranking supplied (``y``) is the "column" variable. This is + opposite the convention of Somers' original paper [1]_. + + References + ---------- + .. [1] Robert H. Somers, "A New Asymmetric Measure of Association for + Ordinal Variables", *American Sociological Review*, Vol. 27, No. 6, + pp. 799--811, 1962. + + .. [2] Morton B. Brown and Jacqueline K. Benedetti, "Sampling Behavior of + Tests for Correlation in Two-Way Contingency Tables", *Journal of + the American Statistical Association* Vol. 72, No. 358, pp. + 309--315, 1977. + + .. [3] SAS Institute, Inc., "The FREQ Procedure (Book Excerpt)", + *SAS/STAT 9.2 User's Guide, Second Edition*, SAS Publishing, 2009. + + .. [4] Laerd Statistics, "Somers' d using SPSS Statistics", *SPSS + Statistics Tutorials and Statistical Guides*, + https://statistics.laerd.com/spss-tutorials/somers-d-using-spss-statistics.php, + Accessed July 31, 2020. + + Examples + -------- + We calculate Somers' D for the example given in [4]_, in which a hotel + chain owner seeks to determine the association between hotel room + cleanliness and customer satisfaction. The independent variable, hotel + room cleanliness, is ranked on an ordinal scale: "below average (1)", + "average (2)", or "above average (3)". The dependent variable, customer + satisfaction, is ranked on a second scale: "very dissatisfied (1)", + "moderately dissatisfied (2)", "neither dissatisfied nor satisfied (3)", + "moderately satisfied (4)", or "very satisfied (5)". 189 customers + respond to the survey, and the results are cast into a contingency table + with the hotel room cleanliness as the "row" variable and customer + satisfaction as the "column" variable. + + +-----+-----+-----+-----+-----+-----+ + | | (1) | (2) | (3) | (4) | (5) | + +=====+=====+=====+=====+=====+=====+ + | (1) | 27 | 25 | 14 | 7 | 0 | + +-----+-----+-----+-----+-----+-----+ + | (2) | 7 | 14 | 18 | 35 | 12 | + +-----+-----+-----+-----+-----+-----+ + | (3) | 1 | 3 | 2 | 7 | 17 | + +-----+-----+-----+-----+-----+-----+ + + For example, 27 customers assigned their room a cleanliness ranking of + "below average (1)" and a corresponding satisfaction of "very + dissatisfied (1)". We perform the analysis as follows. + + >>> from scipy.stats import somersd + >>> table = [[27, 25, 14, 7, 0], [7, 14, 18, 35, 12], [1, 3, 2, 7, 17]] + >>> res = somersd(table) + >>> res.statistic + 0.6032766111513396 + >>> res.pvalue + 1.0007091191074533e-27 + + The value of the Somers' D statistic is approximately 0.6, indicating + a positive correlation between room cleanliness and customer satisfaction + in the sample. + The *p*-value is very small, indicating a very small probability of + observing such an extreme value of the statistic under the null + hypothesis that the statistic of the entire population (from which + our sample of 189 customers is drawn) is zero. This supports the + alternative hypothesis that the true value of Somers' D for the population + is nonzero. + + """ + x, y = np.array(x), np.array(y) + if x.ndim == 1: + if x.size != y.size: + raise ValueError("Rankings must be of equal length.") + table = scipy.stats.contingency.crosstab(x, y)[1] + elif x.ndim == 2: + if np.any(x < 0): + raise ValueError("All elements of the contingency table must be " + "non-negative.") + if np.any(x != x.astype(int)): + raise ValueError("All elements of the contingency table must be " + "integer.") + if x.nonzero()[0].size < 2: + raise ValueError("At least two elements of the contingency table " + "must be nonzero.") + table = x + else: + raise ValueError("x must be either a 1D or 2D array") + # The table type is converted to a float to avoid an integer overflow + d, p = _somers_d(table.astype(float), alternative) + + # add alias for consistency with other correlation functions + res = SomersDResult(d, p, table) + res.correlation = d + return res + + +# This could be combined with `_all_partitions` in `_resampling.py` +def _all_partitions(nx, ny): + """ + Partition a set of indices into two fixed-length sets in all possible ways + + Partition a set of indices 0 ... nx + ny - 1 into two sets of length nx and + ny in all possible ways (ignoring order of elements). + """ + z = np.arange(nx+ny) + for c in combinations(z, nx): + x = np.array(c) + mask = np.ones(nx+ny, bool) + mask[x] = False + y = z[mask] + yield x, y + + +def _compute_log_combinations(n): + """Compute all log combination of C(n, k).""" + gammaln_arr = gammaln(np.arange(n + 1) + 1) + return gammaln(n + 1) - gammaln_arr - gammaln_arr[::-1] + + +@dataclass +class BarnardExactResult: + statistic: float + pvalue: float + + +def barnard_exact(table, alternative="two-sided", pooled=True, n=32): + r"""Perform a Barnard exact test on a 2x2 contingency table. + + Parameters + ---------- + table : array_like of ints + A 2x2 contingency table. Elements should be non-negative integers. + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes section below. + + pooled : bool, optional + Whether to compute score statistic with pooled variance (as in + Student's t-test, for example) or unpooled variance (as in Welch's + t-test). Default is ``True``. + + n : int, optional + Number of sampling points used in the construction of the sampling + method. Note that this argument will automatically be converted to + the next higher power of 2 since `scipy.stats.qmc.Sobol` is used to + select sample points. Default is 32. Must be positive. In most cases, + 32 points is enough to reach good precision. More points comes at + performance cost. + + Returns + ------- + ber : BarnardExactResult + A result object with the following attributes. + + statistic : float + The Wald statistic with pooled or unpooled variance, depending + on the user choice of `pooled`. + + pvalue : float + P-value, the probability of obtaining a distribution at least as + extreme as the one that was actually observed, assuming that the + null hypothesis is true. + + See Also + -------- + chi2_contingency : Chi-square test of independence of variables in a + contingency table. + fisher_exact : Fisher exact test on a 2x2 contingency table. + boschloo_exact : Boschloo's exact test on a 2x2 contingency table, + which is an uniformly more powerful alternative to Fisher's exact test. + + Notes + ----- + Barnard's test is an exact test used in the analysis of contingency + tables. It examines the association of two categorical variables, and + is a more powerful alternative than Fisher's exact test + for 2x2 contingency tables. + + Let's define :math:`X_0` a 2x2 matrix representing the observed sample, + where each column stores the binomial experiment, as in the example + below. Let's also define :math:`p_1, p_2` the theoretical binomial + probabilities for :math:`x_{11}` and :math:`x_{12}`. When using + Barnard exact test, we can assert three different null hypotheses : + + - :math:`H_0 : p_1 \geq p_2` versus :math:`H_1 : p_1 < p_2`, + with `alternative` = "less" + + - :math:`H_0 : p_1 \leq p_2` versus :math:`H_1 : p_1 > p_2`, + with `alternative` = "greater" + + - :math:`H_0 : p_1 = p_2` versus :math:`H_1 : p_1 \neq p_2`, + with `alternative` = "two-sided" (default one) + + In order to compute Barnard's exact test, we are using the Wald + statistic [3]_ with pooled or unpooled variance. + Under the default assumption that both variances are equal + (``pooled = True``), the statistic is computed as: + + .. math:: + + T(X) = \frac{ + \hat{p}_1 - \hat{p}_2 + }{ + \sqrt{ + \hat{p}(1 - \hat{p}) + (\frac{1}{c_1} + + \frac{1}{c_2}) + } + } + + with :math:`\hat{p}_1, \hat{p}_2` and :math:`\hat{p}` the estimator of + :math:`p_1, p_2` and :math:`p`, the latter being the combined probability, + given the assumption that :math:`p_1 = p_2`. + + If this assumption is invalid (``pooled = False``), the statistic is: + + .. math:: + + T(X) = \frac{ + \hat{p}_1 - \hat{p}_2 + }{ + \sqrt{ + \frac{\hat{p}_1 (1 - \hat{p}_1)}{c_1} + + \frac{\hat{p}_2 (1 - \hat{p}_2)}{c_2} + } + } + + The p-value is then computed as: + + .. math:: + + \sum + \binom{c_1}{x_{11}} + \binom{c_2}{x_{12}} + \pi^{x_{11} + x_{12}} + (1 - \pi)^{t - x_{11} - x_{12}} + + where the sum is over all 2x2 contingency tables :math:`X` such that: + * :math:`T(X) \leq T(X_0)` when `alternative` = "less", + * :math:`T(X) \geq T(X_0)` when `alternative` = "greater", or + * :math:`T(X) \geq |T(X_0)|` when `alternative` = "two-sided". + Above, :math:`c_1, c_2` are the sum of the columns 1 and 2, + and :math:`t` the total (sum of the 4 sample's element). + + The returned p-value is the maximum p-value taken over the nuisance + parameter :math:`\pi`, where :math:`0 \leq \pi \leq 1`. + + This function's complexity is :math:`O(n c_1 c_2)`, where `n` is the + number of sample points. + + References + ---------- + .. [1] Barnard, G. A. "Significance Tests for 2x2 Tables". *Biometrika*. + 34.1/2 (1947): 123-138. :doi:`dpgkg3` + + .. [2] Mehta, Cyrus R., and Pralay Senchaudhuri. "Conditional versus + unconditional exact tests for comparing two binomials." + *Cytel Software Corporation* 675 (2003): 1-5. + + .. [3] "Wald Test". *Wikipedia*. https://en.wikipedia.org/wiki/Wald_test + + Examples + -------- + An example use of Barnard's test is presented in [2]_. + + Consider the following example of a vaccine efficacy study + (Chan, 1998). In a randomized clinical trial of 30 subjects, 15 were + inoculated with a recombinant DNA influenza vaccine and the 15 were + inoculated with a placebo. Twelve of the 15 subjects in the placebo + group (80%) eventually became infected with influenza whereas for the + vaccine group, only 7 of the 15 subjects (47%) became infected. The + data are tabulated as a 2 x 2 table:: + + Vaccine Placebo + Yes 7 12 + No 8 3 + + When working with statistical hypothesis testing, we usually use a + threshold probability or significance level upon which we decide + to reject the null hypothesis :math:`H_0`. Suppose we choose the common + significance level of 5%. + + Our alternative hypothesis is that the vaccine will lower the chance of + becoming infected with the virus; that is, the probability :math:`p_1` of + catching the virus with the vaccine will be *less than* the probability + :math:`p_2` of catching the virus without the vaccine. Therefore, we call + `barnard_exact` with the ``alternative="less"`` option: + + >>> import scipy.stats as stats + >>> res = stats.barnard_exact([[7, 12], [8, 3]], alternative="less") + >>> res.statistic + -1.894 + >>> res.pvalue + 0.03407 + + Under the null hypothesis that the vaccine will not lower the chance of + becoming infected, the probability of obtaining test results at least as + extreme as the observed data is approximately 3.4%. Since this p-value is + less than our chosen significance level, we have evidence to reject + :math:`H_0` in favor of the alternative. + + Suppose we had used Fisher's exact test instead: + + >>> _, pvalue = stats.fisher_exact([[7, 12], [8, 3]], alternative="less") + >>> pvalue + 0.0640 + + With the same threshold significance of 5%, we would not have been able + to reject the null hypothesis in favor of the alternative. As stated in + [2]_, Barnard's test is uniformly more powerful than Fisher's exact test + because Barnard's test does not condition on any margin. Fisher's test + should only be used when both sets of marginals are fixed. + + """ + if n <= 0: + raise ValueError( + "Number of points `n` must be strictly positive, " + f"found {n!r}" + ) + + table = np.asarray(table, dtype=np.int64) + + if not table.shape == (2, 2): + raise ValueError("The input `table` must be of shape (2, 2).") + + if np.any(table < 0): + raise ValueError("All values in `table` must be nonnegative.") + + if 0 in table.sum(axis=0): + # If both values in column are zero, the p-value is 1 and + # the score's statistic is NaN. + return BarnardExactResult(np.nan, 1.0) + + total_col_1, total_col_2 = table.sum(axis=0) + + x1 = np.arange(total_col_1 + 1, dtype=np.int64).reshape(-1, 1) + x2 = np.arange(total_col_2 + 1, dtype=np.int64).reshape(1, -1) + + # We need to calculate the wald statistics for each combination of x1 and + # x2. + p1, p2 = x1 / total_col_1, x2 / total_col_2 + + if pooled: + p = (x1 + x2) / (total_col_1 + total_col_2) + variances = p * (1 - p) * (1 / total_col_1 + 1 / total_col_2) + else: + variances = p1 * (1 - p1) / total_col_1 + p2 * (1 - p2) / total_col_2 + + # To avoid warning when dividing by 0 + with np.errstate(divide="ignore", invalid="ignore"): + wald_statistic = np.divide((p1 - p2), np.sqrt(variances)) + + wald_statistic[p1 == p2] = 0 # Removing NaN values + + wald_stat_obs = wald_statistic[table[0, 0], table[0, 1]] + + if alternative == "two-sided": + index_arr = np.abs(wald_statistic) >= abs(wald_stat_obs) + elif alternative == "less": + index_arr = wald_statistic <= wald_stat_obs + elif alternative == "greater": + index_arr = wald_statistic >= wald_stat_obs + else: + msg = ( + "`alternative` should be one of {'two-sided', 'less', 'greater'}," + f" found {alternative!r}" + ) + raise ValueError(msg) + + x1_sum_x2 = x1 + x2 + + x1_log_comb = _compute_log_combinations(total_col_1) + x2_log_comb = _compute_log_combinations(total_col_2) + x1_sum_x2_log_comb = x1_log_comb[x1] + x2_log_comb[x2] + + result = shgo( + _get_binomial_log_p_value_with_nuisance_param, + args=(x1_sum_x2, x1_sum_x2_log_comb, index_arr), + bounds=((0, 1),), + n=n, + sampling_method="sobol", + ) + + # result.fun is the negative log pvalue and therefore needs to be + # changed before return + p_value = np.clip(np.exp(-result.fun), a_min=0, a_max=1) + return BarnardExactResult(wald_stat_obs, p_value) + + +@dataclass +class BoschlooExactResult: + statistic: float + pvalue: float + + +def boschloo_exact(table, alternative="two-sided", n=32): + r"""Perform Boschloo's exact test on a 2x2 contingency table. + + Parameters + ---------- + table : array_like of ints + A 2x2 contingency table. Elements should be non-negative integers. + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes section below. + + n : int, optional + Number of sampling points used in the construction of the sampling + method. Note that this argument will automatically be converted to + the next higher power of 2 since `scipy.stats.qmc.Sobol` is used to + select sample points. Default is 32. Must be positive. In most cases, + 32 points is enough to reach good precision. More points comes at + performance cost. + + Returns + ------- + ber : BoschlooExactResult + A result object with the following attributes. + + statistic : float + The statistic used in Boschloo's test; that is, the p-value + from Fisher's exact test. + + pvalue : float + P-value, the probability of obtaining a distribution at least as + extreme as the one that was actually observed, assuming that the + null hypothesis is true. + + See Also + -------- + chi2_contingency : Chi-square test of independence of variables in a + contingency table. + fisher_exact : Fisher exact test on a 2x2 contingency table. + barnard_exact : Barnard's exact test, which is a more powerful alternative + than Fisher's exact test for 2x2 contingency tables. + + Notes + ----- + Boschloo's test is an exact test used in the analysis of contingency + tables. It examines the association of two categorical variables, and + is a uniformly more powerful alternative to Fisher's exact test + for 2x2 contingency tables. + + Boschloo's exact test uses the p-value of Fisher's exact test as a + statistic, and Boschloo's p-value is the probability under the null + hypothesis of observing such an extreme value of this statistic. + + Let's define :math:`X_0` a 2x2 matrix representing the observed sample, + where each column stores the binomial experiment, as in the example + below. Let's also define :math:`p_1, p_2` the theoretical binomial + probabilities for :math:`x_{11}` and :math:`x_{12}`. When using + Boschloo exact test, we can assert three different alternative hypotheses: + + - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 < p_2`, + with `alternative` = "less" + + - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 > p_2`, + with `alternative` = "greater" + + - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 \neq p_2`, + with `alternative` = "two-sided" (default) + + There are multiple conventions for computing a two-sided p-value when the + null distribution is asymmetric. Here, we apply the convention that the + p-value of a two-sided test is twice the minimum of the p-values of the + one-sided tests (clipped to 1.0). Note that `fisher_exact` follows a + different convention, so for a given `table`, the statistic reported by + `boschloo_exact` may differ from the p-value reported by `fisher_exact` + when ``alternative='two-sided'``. + + .. versionadded:: 1.7.0 + + References + ---------- + .. [1] R.D. Boschloo. "Raised conditional level of significance for the + 2 x 2-table when testing the equality of two probabilities", + Statistica Neerlandica, 24(1), 1970 + + .. [2] "Boschloo's test", Wikipedia, + https://en.wikipedia.org/wiki/Boschloo%27s_test + + .. [3] Lise M. Saari et al. "Employee attitudes and job satisfaction", + Human Resource Management, 43(4), 395-407, 2004, + :doi:`10.1002/hrm.20032`. + + Examples + -------- + In the following example, we consider the article "Employee + attitudes and job satisfaction" [3]_ + which reports the results of a survey from 63 scientists and 117 college + professors. Of the 63 scientists, 31 said they were very satisfied with + their jobs, whereas 74 of the college professors were very satisfied + with their work. Is this significant evidence that college + professors are happier with their work than scientists? + The following table summarizes the data mentioned above:: + + college professors scientists + Very Satisfied 74 31 + Dissatisfied 43 32 + + When working with statistical hypothesis testing, we usually use a + threshold probability or significance level upon which we decide + to reject the null hypothesis :math:`H_0`. Suppose we choose the common + significance level of 5%. + + Our alternative hypothesis is that college professors are truly more + satisfied with their work than scientists. Therefore, we expect + :math:`p_1` the proportion of very satisfied college professors to be + greater than :math:`p_2`, the proportion of very satisfied scientists. + We thus call `boschloo_exact` with the ``alternative="greater"`` option: + + >>> import scipy.stats as stats + >>> res = stats.boschloo_exact([[74, 31], [43, 32]], alternative="greater") + >>> res.statistic + 0.0483 + >>> res.pvalue + 0.0355 + + Under the null hypothesis that scientists are happier in their work than + college professors, the probability of obtaining test + results at least as extreme as the observed data is approximately 3.55%. + Since this p-value is less than our chosen significance level, we have + evidence to reject :math:`H_0` in favor of the alternative hypothesis. + + """ + hypergeom = distributions.hypergeom + + if n <= 0: + raise ValueError( + "Number of points `n` must be strictly positive," + f" found {n!r}" + ) + + table = np.asarray(table, dtype=np.int64) + + if not table.shape == (2, 2): + raise ValueError("The input `table` must be of shape (2, 2).") + + if np.any(table < 0): + raise ValueError("All values in `table` must be nonnegative.") + + if 0 in table.sum(axis=0): + # If both values in column are zero, the p-value is 1 and + # the score's statistic is NaN. + return BoschlooExactResult(np.nan, np.nan) + + total_col_1, total_col_2 = table.sum(axis=0) + total = total_col_1 + total_col_2 + x1 = np.arange(total_col_1 + 1, dtype=np.int64).reshape(1, -1) + x2 = np.arange(total_col_2 + 1, dtype=np.int64).reshape(-1, 1) + x1_sum_x2 = x1 + x2 + + if alternative == 'less': + pvalues = hypergeom.cdf(x1, total, x1_sum_x2, total_col_1).T + elif alternative == 'greater': + # Same formula as the 'less' case, but with the second column. + pvalues = hypergeom.cdf(x2, total, x1_sum_x2, total_col_2).T + elif alternative == 'two-sided': + boschloo_less = boschloo_exact(table, alternative="less", n=n) + boschloo_greater = boschloo_exact(table, alternative="greater", n=n) + + res = ( + boschloo_less if boschloo_less.pvalue < boschloo_greater.pvalue + else boschloo_greater + ) + + # Two-sided p-value is defined as twice the minimum of the one-sided + # p-values + pvalue = np.clip(2 * res.pvalue, a_min=0, a_max=1) + return BoschlooExactResult(res.statistic, pvalue) + else: + msg = ( + f"`alternative` should be one of {'two-sided', 'less', 'greater'}," + f" found {alternative!r}" + ) + raise ValueError(msg) + + fisher_stat = pvalues[table[0, 0], table[0, 1]] + + # fisher_stat * (1+1e-13) guards us from small numerical error. It is + # equivalent to np.isclose with relative tol of 1e-13 and absolute tol of 0 + # For more throughout explanations, see gh-14178 + index_arr = pvalues <= fisher_stat * (1+1e-13) + + x1, x2, x1_sum_x2 = x1.T, x2.T, x1_sum_x2.T + x1_log_comb = _compute_log_combinations(total_col_1) + x2_log_comb = _compute_log_combinations(total_col_2) + x1_sum_x2_log_comb = x1_log_comb[x1] + x2_log_comb[x2] + + result = shgo( + _get_binomial_log_p_value_with_nuisance_param, + args=(x1_sum_x2, x1_sum_x2_log_comb, index_arr), + bounds=((0, 1),), + n=n, + sampling_method="sobol", + ) + + # result.fun is the negative log pvalue and therefore needs to be + # changed before return + p_value = np.clip(np.exp(-result.fun), a_min=0, a_max=1) + return BoschlooExactResult(fisher_stat, p_value) + + +def _get_binomial_log_p_value_with_nuisance_param( + nuisance_param, x1_sum_x2, x1_sum_x2_log_comb, index_arr +): + r""" + Compute the log pvalue in respect of a nuisance parameter considering + a 2x2 sample space. + + Parameters + ---------- + nuisance_param : float + nuisance parameter used in the computation of the maximisation of + the p-value. Must be between 0 and 1 + + x1_sum_x2 : ndarray + Sum of x1 and x2 inside barnard_exact + + x1_sum_x2_log_comb : ndarray + sum of the log combination of x1 and x2 + + index_arr : ndarray of boolean + + Returns + ------- + p_value : float + Return the maximum p-value considering every nuisance parameter + between 0 and 1 + + Notes + ----- + + Both Barnard's test and Boschloo's test iterate over a nuisance parameter + :math:`\pi \in [0, 1]` to find the maximum p-value. To search this + maxima, this function return the negative log pvalue with respect to the + nuisance parameter passed in params. This negative log p-value is then + used in `shgo` to find the minimum negative pvalue which is our maximum + pvalue. + + Also, to compute the different combination used in the + p-values' computation formula, this function uses `gammaln` which is + more tolerant for large value than `scipy.special.comb`. `gammaln` gives + a log combination. For the little precision loss, performances are + improved a lot. + """ + t1, t2 = x1_sum_x2.shape + n = t1 + t2 - 2 + with np.errstate(divide="ignore", invalid="ignore"): + log_nuisance = np.log( + nuisance_param, + out=np.zeros_like(nuisance_param), + where=nuisance_param >= 0, + ) + log_1_minus_nuisance = np.log( + 1 - nuisance_param, + out=np.zeros_like(nuisance_param), + where=1 - nuisance_param >= 0, + ) + + nuisance_power_x1_x2 = log_nuisance * x1_sum_x2 + nuisance_power_x1_x2[(x1_sum_x2 == 0)[:, :]] = 0 + + nuisance_power_n_minus_x1_x2 = log_1_minus_nuisance * (n - x1_sum_x2) + nuisance_power_n_minus_x1_x2[(x1_sum_x2 == n)[:, :]] = 0 + + tmp_log_values_arr = ( + x1_sum_x2_log_comb + + nuisance_power_x1_x2 + + nuisance_power_n_minus_x1_x2 + ) + + tmp_values_from_index = tmp_log_values_arr[index_arr] + + # To avoid dividing by zero in log function and getting inf value, + # values are centered according to the max + max_value = tmp_values_from_index.max() + + # To have better result's precision, the log pvalue is taken here. + # Indeed, pvalue is included inside [0, 1] interval. Passing the + # pvalue to log makes the interval a lot bigger ([-inf, 0]), and thus + # help us to achieve better precision + with np.errstate(divide="ignore", invalid="ignore"): + log_probs = np.exp(tmp_values_from_index - max_value).sum() + log_pvalue = max_value + np.log( + log_probs, + out=np.full_like(log_probs, -np.inf), + where=log_probs > 0, + ) + + # Since shgo find the minima, minus log pvalue is returned + return -log_pvalue + + +def _pval_cvm_2samp_exact(s, m, n): + """ + Compute the exact p-value of the Cramer-von Mises two-sample test + for a given value s of the test statistic. + m and n are the sizes of the samples. + + [1] Y. Xiao, A. Gordon, and A. Yakovlev, "A C++ Program for + the Cramér-Von Mises Two-Sample Test", J. Stat. Soft., + vol. 17, no. 8, pp. 1-15, Dec. 2006. + [2] T. W. Anderson "On the Distribution of the Two-Sample Cramer-von Mises + Criterion," The Annals of Mathematical Statistics, Ann. Math. Statist. + 33(3), 1148-1159, (September, 1962) + """ + + # [1, p. 3] + lcm = np.lcm(m, n) + # [1, p. 4], below eq. 3 + a = lcm // m + b = lcm // n + # Combine Eq. 9 in [2] with Eq. 2 in [1] and solve for $\zeta$ + # Hint: `s` is $U$ in [2], and $T_2$ in [1] is $T$ in [2] + mn = m * n + zeta = lcm ** 2 * (m + n) * (6 * s - mn * (4 * mn - 1)) // (6 * mn ** 2) + + # bound maximum value that may appear in `gs` (remember both rows!) + zeta_bound = lcm**2 * (m + n) # bound elements in row 1 + combinations = comb(m + n, m) # sum of row 2 + max_gs = max(zeta_bound, combinations) + dtype = np.min_scalar_type(max_gs) + + # the frequency table of $g_{u, v}^+$ defined in [1, p. 6] + gs = ([np.array([[0], [1]], dtype=dtype)] + + [np.empty((2, 0), dtype=dtype) for _ in range(m)]) + for u in range(n + 1): + next_gs = [] + tmp = np.empty((2, 0), dtype=dtype) + for v, g in enumerate(gs): + # Calculate g recursively with eq. 11 in [1]. Even though it + # doesn't look like it, this also does 12/13 (all of Algorithm 1). + vi, i0, i1 = np.intersect1d(tmp[0], g[0], return_indices=True) + tmp = np.concatenate([ + np.stack([vi, tmp[1, i0] + g[1, i1]]), + np.delete(tmp, i0, 1), + np.delete(g, i1, 1) + ], 1) + res = (a * v - b * u) ** 2 + tmp[0] += res.astype(dtype) + next_gs.append(tmp) + gs = next_gs + value, freq = gs[m] + return np.float64(np.sum(freq[value >= zeta]) / combinations) + + +@_axis_nan_policy_factory(CramerVonMisesResult, n_samples=2, too_small=1, + result_to_tuple=_cvm_result_to_tuple) +def cramervonmises_2samp(x, y, method='auto'): + """Perform the two-sample Cramér-von Mises test for goodness of fit. + + This is the two-sample version of the Cramér-von Mises test ([1]_): + for two independent samples :math:`X_1, ..., X_n` and + :math:`Y_1, ..., Y_m`, the null hypothesis is that the samples + come from the same (unspecified) continuous distribution. + + Parameters + ---------- + x : array_like + A 1-D array of observed values of the random variables :math:`X_i`. + Must contain at least two observations. + y : array_like + A 1-D array of observed values of the random variables :math:`Y_i`. + Must contain at least two observations. + method : {'auto', 'asymptotic', 'exact'}, optional + The method used to compute the p-value, see Notes for details. + The default is 'auto'. + + Returns + ------- + res : object with attributes + statistic : float + Cramér-von Mises statistic. + pvalue : float + The p-value. + + See Also + -------- + cramervonmises, anderson_ksamp, epps_singleton_2samp, ks_2samp + + Notes + ----- + .. versionadded:: 1.7.0 + + The statistic is computed according to equation 9 in [2]_. The + calculation of the p-value depends on the keyword `method`: + + - ``asymptotic``: The p-value is approximated by using the limiting + distribution of the test statistic. + - ``exact``: The exact p-value is computed by enumerating all + possible combinations of the test statistic, see [2]_. + + If ``method='auto'``, the exact approach is used + if both samples contain equal to or less than 20 observations, + otherwise the asymptotic distribution is used. + + If the underlying distribution is not continuous, the p-value is likely to + be conservative (Section 6.2 in [3]_). When ranking the data to compute + the test statistic, midranks are used if there are ties. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Cramer-von_Mises_criterion + .. [2] Anderson, T.W. (1962). On the distribution of the two-sample + Cramer-von-Mises criterion. The Annals of Mathematical + Statistics, pp. 1148-1159. + .. [3] Conover, W.J., Practical Nonparametric Statistics, 1971. + + Examples + -------- + + Suppose we wish to test whether two samples generated by + ``scipy.stats.norm.rvs`` have the same distribution. We choose a + significance level of alpha=0.05. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = stats.norm.rvs(size=100, random_state=rng) + >>> y = stats.norm.rvs(size=70, random_state=rng) + >>> res = stats.cramervonmises_2samp(x, y) + >>> res.statistic, res.pvalue + (0.29376470588235293, 0.1412873014573014) + + The p-value exceeds our chosen significance level, so we do not + reject the null hypothesis that the observed samples are drawn from the + same distribution. + + For small sample sizes, one can compute the exact p-values: + + >>> x = stats.norm.rvs(size=7, random_state=rng) + >>> y = stats.t.rvs(df=2, size=6, random_state=rng) + >>> res = stats.cramervonmises_2samp(x, y, method='exact') + >>> res.statistic, res.pvalue + (0.197802197802198, 0.31643356643356646) + + The p-value based on the asymptotic distribution is a good approximation + even though the sample size is small. + + >>> res = stats.cramervonmises_2samp(x, y, method='asymptotic') + >>> res.statistic, res.pvalue + (0.197802197802198, 0.2966041181527128) + + Independent of the method, one would not reject the null hypothesis at the + chosen significance level in this example. + + """ + xa = np.sort(np.asarray(x)) + ya = np.sort(np.asarray(y)) + + if xa.size <= 1 or ya.size <= 1: + raise ValueError('x and y must contain at least two observations.') + if method not in ['auto', 'exact', 'asymptotic']: + raise ValueError('method must be either auto, exact or asymptotic.') + + nx = len(xa) + ny = len(ya) + + if method == 'auto': + if max(nx, ny) > 20: + method = 'asymptotic' + else: + method = 'exact' + + # get ranks of x and y in the pooled sample + z = np.concatenate([xa, ya]) + # in case of ties, use midrank (see [1]) + r = scipy.stats.rankdata(z, method='average') + rx = r[:nx] + ry = r[nx:] + + # compute U (eq. 10 in [2]) + u = nx * np.sum((rx - np.arange(1, nx+1))**2) + u += ny * np.sum((ry - np.arange(1, ny+1))**2) + + # compute T (eq. 9 in [2]) + k, N = nx*ny, nx + ny + t = u / (k*N) - (4*k - 1)/(6*N) + + if method == 'exact': + p = _pval_cvm_2samp_exact(u, nx, ny) + else: + # compute expected value and variance of T (eq. 11 and 14 in [2]) + et = (1 + 1/N)/6 + vt = (N+1) * (4*k*N - 3*(nx**2 + ny**2) - 2*k) + vt = vt / (45 * N**2 * 4 * k) + + # computed the normalized statistic (eq. 15 in [2]) + tn = 1/6 + (t - et) / np.sqrt(45 * vt) + + # approximate distribution of tn with limiting distribution + # of the one-sample test statistic + # if tn < 0.003, the _cdf_cvm_inf(tn) < 1.28*1e-18, return 1.0 directly + if tn < 0.003: + p = 1.0 + else: + p = max(0, 1. - _cdf_cvm_inf(tn)) + + return CramerVonMisesResult(statistic=t, pvalue=p) + + +class TukeyHSDResult: + """Result of `scipy.stats.tukey_hsd`. + + Attributes + ---------- + statistic : float ndarray + The computed statistic of the test for each comparison. The element + at index ``(i, j)`` is the statistic for the comparison between groups + ``i`` and ``j``. + pvalue : float ndarray + The associated p-value from the studentized range distribution. The + element at index ``(i, j)`` is the p-value for the comparison + between groups ``i`` and ``j``. + + Notes + ----- + The string representation of this object displays the most recently + calculated confidence interval, and if none have been previously + calculated, it will evaluate ``confidence_interval()``. + + References + ---------- + .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1. Tukey's + Method." + https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm, + 28 November 2020. + """ + + def __init__(self, statistic, pvalue, _nobs, _ntreatments, _stand_err): + self.statistic = statistic + self.pvalue = pvalue + self._ntreatments = _ntreatments + self._nobs = _nobs + self._stand_err = _stand_err + self._ci = None + self._ci_cl = None + + def __str__(self): + # Note: `__str__` prints the confidence intervals from the most + # recent call to `confidence_interval`. If it has not been called, + # it will be called with the default CL of .95. + if self._ci is None: + self.confidence_interval(confidence_level=.95) + s = ("Tukey's HSD Pairwise Group Comparisons" + f" ({self._ci_cl*100:.1f}% Confidence Interval)\n") + s += "Comparison Statistic p-value Lower CI Upper CI\n" + for i in range(self.pvalue.shape[0]): + for j in range(self.pvalue.shape[0]): + if i != j: + s += (f" ({i} - {j}) {self.statistic[i, j]:>10.3f}" + f"{self.pvalue[i, j]:>10.3f}" + f"{self._ci.low[i, j]:>10.3f}" + f"{self._ci.high[i, j]:>10.3f}\n") + return s + + def confidence_interval(self, confidence_level=.95): + """Compute the confidence interval for the specified confidence level. + + Parameters + ---------- + confidence_level : float, optional + Confidence level for the computed confidence interval + of the estimated proportion. Default is .95. + + Returns + ------- + ci : ``ConfidenceInterval`` object + The object has attributes ``low`` and ``high`` that hold the + lower and upper bounds of the confidence intervals for each + comparison. The high and low values are accessible for each + comparison at index ``(i, j)`` between groups ``i`` and ``j``. + + References + ---------- + .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1. + Tukey's Method." + https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm, + 28 November 2020. + + Examples + -------- + >>> from scipy.stats import tukey_hsd + >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9] + >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1] + >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8] + >>> result = tukey_hsd(group0, group1, group2) + >>> ci = result.confidence_interval() + >>> ci.low + array([[-3.649159, -8.249159, -3.909159], + [ 0.950841, -3.649159, 0.690841], + [-3.389159, -7.989159, -3.649159]]) + >>> ci.high + array([[ 3.649159, -0.950841, 3.389159], + [ 8.249159, 3.649159, 7.989159], + [ 3.909159, -0.690841, 3.649159]]) + """ + # check to see if the supplied confidence level matches that of the + # previously computed CI. + if (self._ci is not None and self._ci_cl is not None and + confidence_level == self._ci_cl): + return self._ci + + if not 0 < confidence_level < 1: + raise ValueError("Confidence level must be between 0 and 1.") + # determine the critical value of the studentized range using the + # appropriate confidence level, number of treatments, and degrees + # of freedom as determined by the number of data less the number of + # treatments. ("Confidence limits for Tukey's method")[1]. Note that + # in the cases of unequal sample sizes there will be a criterion for + # each group comparison. + params = (confidence_level, self._nobs, self._ntreatments - self._nobs) + srd = distributions.studentized_range.ppf(*params) + # also called maximum critical value, the Tukey criterion is the + # studentized range critical value * the square root of mean square + # error over the sample size. + tukey_criterion = srd * self._stand_err + # the confidence levels are determined by the + # `mean_differences` +- `tukey_criterion` + upper_conf = self.statistic + tukey_criterion + lower_conf = self.statistic - tukey_criterion + self._ci = ConfidenceInterval(low=lower_conf, high=upper_conf) + self._ci_cl = confidence_level + return self._ci + + +def _tukey_hsd_iv(args): + if (len(args)) < 2: + raise ValueError("There must be more than 1 treatment.") + args = [np.asarray(arg) for arg in args] + for arg in args: + if arg.ndim != 1: + raise ValueError("Input samples must be one-dimensional.") + if arg.size <= 1: + raise ValueError("Input sample size must be greater than one.") + if np.isinf(arg).any(): + raise ValueError("Input samples must be finite.") + return args + + +def tukey_hsd(*args): + """Perform Tukey's HSD test for equality of means over multiple treatments. + + Tukey's honestly significant difference (HSD) test performs pairwise + comparison of means for a set of samples. Whereas ANOVA (e.g. `f_oneway`) + assesses whether the true means underlying each sample are identical, + Tukey's HSD is a post hoc test used to compare the mean of each sample + to the mean of each other sample. + + The null hypothesis is that the distributions underlying the samples all + have the same mean. The test statistic, which is computed for every + possible pairing of samples, is simply the difference between the sample + means. For each pair, the p-value is the probability under the null + hypothesis (and other assumptions; see notes) of observing such an extreme + value of the statistic, considering that many pairwise comparisons are + being performed. Confidence intervals for the difference between each pair + of means are also available. + + Parameters + ---------- + sample1, sample2, ... : array_like + The sample measurements for each group. There must be at least + two arguments. + + Returns + ------- + result : `~scipy.stats._result_classes.TukeyHSDResult` instance + The return value is an object with the following attributes: + + statistic : float ndarray + The computed statistic of the test for each comparison. The element + at index ``(i, j)`` is the statistic for the comparison between + groups ``i`` and ``j``. + pvalue : float ndarray + The computed p-value of the test for each comparison. The element + at index ``(i, j)`` is the p-value for the comparison between + groups ``i`` and ``j``. + + The object has the following methods: + + confidence_interval(confidence_level=0.95): + Compute the confidence interval for the specified confidence level. + + See Also + -------- + dunnett : performs comparison of means against a control group. + + Notes + ----- + The use of this test relies on several assumptions. + + 1. The observations are independent within and among groups. + 2. The observations within each group are normally distributed. + 3. The distributions from which the samples are drawn have the same finite + variance. + + The original formulation of the test was for samples of equal size [6]_. + In case of unequal sample sizes, the test uses the Tukey-Kramer method + [4]_. + + References + ---------- + .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1. Tukey's + Method." + https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm, + 28 November 2020. + .. [2] Abdi, Herve & Williams, Lynne. (2021). "Tukey's Honestly Significant + Difference (HSD) Test." + https://personal.utdallas.edu/~herve/abdi-HSD2010-pretty.pdf + .. [3] "One-Way ANOVA Using SAS PROC ANOVA & PROC GLM." SAS + Tutorials, 2007, www.stattutorials.com/SAS/TUTORIAL-PROC-GLM.htm. + .. [4] Kramer, Clyde Young. "Extension of Multiple Range Tests to Group + Means with Unequal Numbers of Replications." Biometrics, vol. 12, + no. 3, 1956, pp. 307-310. JSTOR, www.jstor.org/stable/3001469. + Accessed 25 May 2021. + .. [5] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.3.3. + The ANOVA table and tests of hypotheses about means" + https://www.itl.nist.gov/div898/handbook/prc/section4/prc433.htm, + 2 June 2021. + .. [6] Tukey, John W. "Comparing Individual Means in the Analysis of + Variance." Biometrics, vol. 5, no. 2, 1949, pp. 99-114. JSTOR, + www.jstor.org/stable/3001913. Accessed 14 June 2021. + + + Examples + -------- + Here are some data comparing the time to relief of three brands of + headache medicine, reported in minutes. Data adapted from [3]_. + + >>> import numpy as np + >>> from scipy.stats import tukey_hsd + >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9] + >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1] + >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8] + + We would like to see if the means between any of the groups are + significantly different. First, visually examine a box and whisker plot. + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1, 1) + >>> ax.boxplot([group0, group1, group2]) + >>> ax.set_xticklabels(["group0", "group1", "group2"]) # doctest: +SKIP + >>> ax.set_ylabel("mean") # doctest: +SKIP + >>> plt.show() + + From the box and whisker plot, we can see overlap in the interquartile + ranges group 1 to group 2 and group 3, but we can apply the ``tukey_hsd`` + test to determine if the difference between means is significant. We + set a significance level of .05 to reject the null hypothesis. + + >>> res = tukey_hsd(group0, group1, group2) + >>> print(res) + Tukey's HSD Pairwise Group Comparisons (95.0% Confidence Interval) + Comparison Statistic p-value Lower CI Upper CI + (0 - 1) -4.600 0.014 -8.249 -0.951 + (0 - 2) -0.260 0.980 -3.909 3.389 + (1 - 0) 4.600 0.014 0.951 8.249 + (1 - 2) 4.340 0.020 0.691 7.989 + (2 - 0) 0.260 0.980 -3.389 3.909 + (2 - 1) -4.340 0.020 -7.989 -0.691 + + The null hypothesis is that each group has the same mean. The p-value for + comparisons between ``group0`` and ``group1`` as well as ``group1`` and + ``group2`` do not exceed .05, so we reject the null hypothesis that they + have the same means. The p-value of the comparison between ``group0`` + and ``group2`` exceeds .05, so we accept the null hypothesis that there + is not a significant difference between their means. + + We can also compute the confidence interval associated with our chosen + confidence level. + + >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9] + >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1] + >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8] + >>> result = tukey_hsd(group0, group1, group2) + >>> conf = res.confidence_interval(confidence_level=.99) + >>> for ((i, j), l) in np.ndenumerate(conf.low): + ... # filter out self comparisons + ... if i != j: + ... h = conf.high[i,j] + ... print(f"({i} - {j}) {l:>6.3f} {h:>6.3f}") + (0 - 1) -9.480 0.280 + (0 - 2) -5.140 4.620 + (1 - 0) -0.280 9.480 + (1 - 2) -0.540 9.220 + (2 - 0) -4.620 5.140 + (2 - 1) -9.220 0.540 + """ + args = _tukey_hsd_iv(args) + ntreatments = len(args) + means = np.asarray([np.mean(arg) for arg in args]) + nsamples_treatments = np.asarray([a.size for a in args]) + nobs = np.sum(nsamples_treatments) + + # determine mean square error [5]. Note that this is sometimes called + # mean square error within. + mse = (np.sum([np.var(arg, ddof=1) for arg in args] * + (nsamples_treatments - 1)) / (nobs - ntreatments)) + + # The calculation of the standard error differs when treatments differ in + # size. See ("Unequal sample sizes")[1]. + if np.unique(nsamples_treatments).size == 1: + # all input groups are the same length, so only one value needs to be + # calculated [1]. + normalize = 2 / nsamples_treatments[0] + else: + # to compare groups of differing sizes, we must compute a variance + # value for each individual comparison. Use broadcasting to get the + # resulting matrix. [3], verified against [4] (page 308). + normalize = 1 / nsamples_treatments + 1 / nsamples_treatments[None].T + + # the standard error is used in the computation of the tukey criterion and + # finding the p-values. + stand_err = np.sqrt(normalize * mse / 2) + + # the mean difference is the test statistic. + mean_differences = means[None].T - means + + # Calculate the t-statistic to use within the survival function of the + # studentized range to get the p-value. + t_stat = np.abs(mean_differences) / stand_err + + params = t_stat, ntreatments, nobs - ntreatments + pvalues = distributions.studentized_range.sf(*params) + + return TukeyHSDResult(mean_differences, pvalues, ntreatments, + nobs, stand_err) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_kde.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..a967fcf44eedf040fb795618d535d8fe24c33a98 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_kde.py @@ -0,0 +1,728 @@ +#------------------------------------------------------------------------------- +# +# Define classes for (uni/multi)-variate kernel density estimation. +# +# Currently, only Gaussian kernels are implemented. +# +# Written by: Robert Kern +# +# Date: 2004-08-09 +# +# Modified: 2005-02-10 by Robert Kern. +# Contributed to SciPy +# 2005-10-07 by Robert Kern. +# Some fixes to match the new scipy_core +# +# Copyright 2004-2005 by Enthought, Inc. +# +#------------------------------------------------------------------------------- + +# Standard library imports. +import threading +import warnings + +# SciPy imports. +from scipy import linalg, special +from scipy._lib._util import check_random_state + +from numpy import (asarray, atleast_2d, reshape, zeros, newaxis, exp, pi, + sqrt, ravel, power, atleast_1d, squeeze, sum, transpose, + ones, cov) +import numpy as np + +# Local imports. +from . import _mvn +from ._stats import gaussian_kernel_estimate, gaussian_kernel_estimate_log + + +__all__ = ['gaussian_kde'] + +MVN_LOCK = threading.Lock() + + +class gaussian_kde: + """Representation of a kernel-density estimate using Gaussian kernels. + + Kernel density estimation is a way to estimate the probability density + function (PDF) of a random variable in a non-parametric way. + `gaussian_kde` works for both uni-variate and multi-variate data. It + includes automatic bandwidth determination. The estimation works best for + a unimodal distribution; bimodal or multi-modal distributions tend to be + oversmoothed. + + Parameters + ---------- + dataset : array_like + Datapoints to estimate from. In case of univariate data this is a 1-D + array, otherwise a 2-D array with shape (# of dims, # of data). + bw_method : str, scalar or callable, optional + The method used to calculate the estimator bandwidth. This can be + 'scott', 'silverman', a scalar constant or a callable. If a scalar, + this will be used directly as `kde.factor`. If a callable, it should + take a `gaussian_kde` instance as only parameter and return a scalar. + If None (default), 'scott' is used. See Notes for more details. + weights : array_like, optional + weights of datapoints. This must be the same shape as dataset. + If None (default), the samples are assumed to be equally weighted + + Attributes + ---------- + dataset : ndarray + The dataset with which `gaussian_kde` was initialized. + d : int + Number of dimensions. + n : int + Number of datapoints. + neff : int + Effective number of datapoints. + + .. versionadded:: 1.2.0 + factor : float + The bandwidth factor, obtained from `kde.covariance_factor`. The square + of `kde.factor` multiplies the covariance matrix of the data in the kde + estimation. + covariance : ndarray + The covariance matrix of `dataset`, scaled by the calculated bandwidth + (`kde.factor`). + inv_cov : ndarray + The inverse of `covariance`. + + Methods + ------- + evaluate + __call__ + integrate_gaussian + integrate_box_1d + integrate_box + integrate_kde + pdf + logpdf + resample + set_bandwidth + covariance_factor + + Notes + ----- + Bandwidth selection strongly influences the estimate obtained from the KDE + (much more so than the actual shape of the kernel). Bandwidth selection + can be done by a "rule of thumb", by cross-validation, by "plug-in + methods" or by other means; see [3]_, [4]_ for reviews. `gaussian_kde` + uses a rule of thumb, the default is Scott's Rule. + + Scott's Rule [1]_, implemented as `scotts_factor`, is:: + + n**(-1./(d+4)), + + with ``n`` the number of data points and ``d`` the number of dimensions. + In the case of unequally weighted points, `scotts_factor` becomes:: + + neff**(-1./(d+4)), + + with ``neff`` the effective number of datapoints. + Silverman's Rule [2]_, implemented as `silverman_factor`, is:: + + (n * (d + 2) / 4.)**(-1. / (d + 4)). + + or in the case of unequally weighted points:: + + (neff * (d + 2) / 4.)**(-1. / (d + 4)). + + Good general descriptions of kernel density estimation can be found in [1]_ + and [2]_, the mathematics for this multi-dimensional implementation can be + found in [1]_. + + With a set of weighted samples, the effective number of datapoints ``neff`` + is defined by:: + + neff = sum(weights)^2 / sum(weights^2) + + as detailed in [5]_. + + `gaussian_kde` does not currently support data that lies in a + lower-dimensional subspace of the space in which it is expressed. For such + data, consider performing principal component analysis / dimensionality + reduction and using `gaussian_kde` with the transformed data. + + References + ---------- + .. [1] D.W. Scott, "Multivariate Density Estimation: Theory, Practice, and + Visualization", John Wiley & Sons, New York, Chicester, 1992. + .. [2] B.W. Silverman, "Density Estimation for Statistics and Data + Analysis", Vol. 26, Monographs on Statistics and Applied Probability, + Chapman and Hall, London, 1986. + .. [3] B.A. Turlach, "Bandwidth Selection in Kernel Density Estimation: A + Review", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993. + .. [4] D.M. Bashtannyk and R.J. Hyndman, "Bandwidth selection for kernel + conditional density estimation", Computational Statistics & Data + Analysis, Vol. 36, pp. 279-298, 2001. + .. [5] Gray P. G., 1969, Journal of the Royal Statistical Society. + Series A (General), 132, 272 + + Examples + -------- + Generate some random two-dimensional data: + + >>> import numpy as np + >>> from scipy import stats + >>> def measure(n): + ... "Measurement model, return two coupled measurements." + ... m1 = np.random.normal(size=n) + ... m2 = np.random.normal(scale=0.5, size=n) + ... return m1+m2, m1-m2 + + >>> m1, m2 = measure(2000) + >>> xmin = m1.min() + >>> xmax = m1.max() + >>> ymin = m2.min() + >>> ymax = m2.max() + + Perform a kernel density estimate on the data: + + >>> X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] + >>> positions = np.vstack([X.ravel(), Y.ravel()]) + >>> values = np.vstack([m1, m2]) + >>> kernel = stats.gaussian_kde(values) + >>> Z = np.reshape(kernel(positions).T, X.shape) + + Plot the results: + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r, + ... extent=[xmin, xmax, ymin, ymax]) + >>> ax.plot(m1, m2, 'k.', markersize=2) + >>> ax.set_xlim([xmin, xmax]) + >>> ax.set_ylim([ymin, ymax]) + >>> plt.show() + + """ + def __init__(self, dataset, bw_method=None, weights=None): + self.dataset = atleast_2d(asarray(dataset)) + if not self.dataset.size > 1: + raise ValueError("`dataset` input should have multiple elements.") + + self.d, self.n = self.dataset.shape + + if weights is not None: + self._weights = atleast_1d(weights).astype(float) + self._weights /= sum(self._weights) + if self.weights.ndim != 1: + raise ValueError("`weights` input should be one-dimensional.") + if len(self._weights) != self.n: + raise ValueError("`weights` input should be of length n") + self._neff = 1/sum(self._weights**2) + + # This can be converted to a warning once gh-10205 is resolved + if self.d > self.n: + msg = ("Number of dimensions is greater than number of samples. " + "This results in a singular data covariance matrix, which " + "cannot be treated using the algorithms implemented in " + "`gaussian_kde`. Note that `gaussian_kde` interprets each " + "*column* of `dataset` to be a point; consider transposing " + "the input to `dataset`.") + raise ValueError(msg) + + try: + self.set_bandwidth(bw_method=bw_method) + except linalg.LinAlgError as e: + msg = ("The data appears to lie in a lower-dimensional subspace " + "of the space in which it is expressed. This has resulted " + "in a singular data covariance matrix, which cannot be " + "treated using the algorithms implemented in " + "`gaussian_kde`. Consider performing principal component " + "analysis / dimensionality reduction and using " + "`gaussian_kde` with the transformed data.") + raise linalg.LinAlgError(msg) from e + + def evaluate(self, points): + """Evaluate the estimated pdf on a set of points. + + Parameters + ---------- + points : (# of dimensions, # of points)-array + Alternatively, a (# of dimensions,) vector can be passed in and + treated as a single point. + + Returns + ------- + values : (# of points,)-array + The values at each point. + + Raises + ------ + ValueError : if the dimensionality of the input points is different than + the dimensionality of the KDE. + + """ + points = atleast_2d(asarray(points)) + + d, m = points.shape + if d != self.d: + if d == 1 and m == self.d: + # points was passed in as a row vector + points = reshape(points, (self.d, 1)) + m = 1 + else: + msg = (f"points have dimension {d}, " + f"dataset has dimension {self.d}") + raise ValueError(msg) + + output_dtype, spec = _get_output_dtype(self.covariance, points) + result = gaussian_kernel_estimate[spec]( + self.dataset.T, self.weights[:, None], + points.T, self.cho_cov, output_dtype) + + return result[:, 0] + + __call__ = evaluate + + def integrate_gaussian(self, mean, cov): + """ + Multiply estimated density by a multivariate Gaussian and integrate + over the whole space. + + Parameters + ---------- + mean : aray_like + A 1-D array, specifying the mean of the Gaussian. + cov : array_like + A 2-D array, specifying the covariance matrix of the Gaussian. + + Returns + ------- + result : scalar + The value of the integral. + + Raises + ------ + ValueError + If the mean or covariance of the input Gaussian differs from + the KDE's dimensionality. + + """ + mean = atleast_1d(squeeze(mean)) + cov = atleast_2d(cov) + + if mean.shape != (self.d,): + raise ValueError(f"mean does not have dimension {self.d}") + if cov.shape != (self.d, self.d): + raise ValueError(f"covariance does not have dimension {self.d}") + + # make mean a column vector + mean = mean[:, newaxis] + + sum_cov = self.covariance + cov + + # This will raise LinAlgError if the new cov matrix is not s.p.d + # cho_factor returns (ndarray, bool) where bool is a flag for whether + # or not ndarray is upper or lower triangular + sum_cov_chol = linalg.cho_factor(sum_cov) + + diff = self.dataset - mean + tdiff = linalg.cho_solve(sum_cov_chol, diff) + + sqrt_det = np.prod(np.diagonal(sum_cov_chol[0])) + norm_const = power(2 * pi, sum_cov.shape[0] / 2.0) * sqrt_det + + energies = sum(diff * tdiff, axis=0) / 2.0 + result = sum(exp(-energies)*self.weights, axis=0) / norm_const + + return result + + def integrate_box_1d(self, low, high): + """ + Computes the integral of a 1D pdf between two bounds. + + Parameters + ---------- + low : scalar + Lower bound of integration. + high : scalar + Upper bound of integration. + + Returns + ------- + value : scalar + The result of the integral. + + Raises + ------ + ValueError + If the KDE is over more than one dimension. + + """ + if self.d != 1: + raise ValueError("integrate_box_1d() only handles 1D pdfs") + + stdev = ravel(sqrt(self.covariance))[0] + + normalized_low = ravel((low - self.dataset) / stdev) + normalized_high = ravel((high - self.dataset) / stdev) + + value = np.sum(self.weights*( + special.ndtr(normalized_high) - + special.ndtr(normalized_low))) + return value + + def integrate_box(self, low_bounds, high_bounds, maxpts=None): + """Computes the integral of a pdf over a rectangular interval. + + Parameters + ---------- + low_bounds : array_like + A 1-D array containing the lower bounds of integration. + high_bounds : array_like + A 1-D array containing the upper bounds of integration. + maxpts : int, optional + The maximum number of points to use for integration. + + Returns + ------- + value : scalar + The result of the integral. + + """ + if maxpts is not None: + extra_kwds = {'maxpts': maxpts} + else: + extra_kwds = {} + + with MVN_LOCK: + value, inform = _mvn.mvnun_weighted(low_bounds, high_bounds, + self.dataset, self.weights, + self.covariance, **extra_kwds) + if inform: + msg = f'An integral in _mvn.mvnun requires more points than {self.d * 1000}' + warnings.warn(msg, stacklevel=2) + + return value + + def integrate_kde(self, other): + """ + Computes the integral of the product of this kernel density estimate + with another. + + Parameters + ---------- + other : gaussian_kde instance + The other kde. + + Returns + ------- + value : scalar + The result of the integral. + + Raises + ------ + ValueError + If the KDEs have different dimensionality. + + """ + if other.d != self.d: + raise ValueError("KDEs are not the same dimensionality") + + # we want to iterate over the smallest number of points + if other.n < self.n: + small = other + large = self + else: + small = self + large = other + + sum_cov = small.covariance + large.covariance + sum_cov_chol = linalg.cho_factor(sum_cov) + result = 0.0 + for i in range(small.n): + mean = small.dataset[:, i, newaxis] + diff = large.dataset - mean + tdiff = linalg.cho_solve(sum_cov_chol, diff) + + energies = sum(diff * tdiff, axis=0) / 2.0 + result += sum(exp(-energies)*large.weights, axis=0)*small.weights[i] + + sqrt_det = np.prod(np.diagonal(sum_cov_chol[0])) + norm_const = power(2 * pi, sum_cov.shape[0] / 2.0) * sqrt_det + + result /= norm_const + + return result + + def resample(self, size=None, seed=None): + """Randomly sample a dataset from the estimated pdf. + + Parameters + ---------- + size : int, optional + The number of samples to draw. If not provided, then the size is + the same as the effective number of samples in the underlying + dataset. + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Returns + ------- + resample : (self.d, `size`) ndarray + The sampled dataset. + + """ # numpy/numpydoc#87 # noqa: E501 + if size is None: + size = int(self.neff) + + random_state = check_random_state(seed) + norm = transpose(random_state.multivariate_normal( + zeros((self.d,), float), self.covariance, size=size + )) + indices = random_state.choice(self.n, size=size, p=self.weights) + means = self.dataset[:, indices] + + return means + norm + + def scotts_factor(self): + """Compute Scott's factor. + + Returns + ------- + s : float + Scott's factor. + """ + return power(self.neff, -1./(self.d+4)) + + def silverman_factor(self): + """Compute the Silverman factor. + + Returns + ------- + s : float + The silverman factor. + """ + return power(self.neff*(self.d+2.0)/4.0, -1./(self.d+4)) + + # Default method to calculate bandwidth, can be overwritten by subclass + covariance_factor = scotts_factor + covariance_factor.__doc__ = """Computes the coefficient (`kde.factor`) that + multiplies the data covariance matrix to obtain the kernel covariance + matrix. The default is `scotts_factor`. A subclass can overwrite this + method to provide a different method, or set it through a call to + `kde.set_bandwidth`.""" + + def set_bandwidth(self, bw_method=None): + """Compute the estimator bandwidth with given method. + + The new bandwidth calculated after a call to `set_bandwidth` is used + for subsequent evaluations of the estimated density. + + Parameters + ---------- + bw_method : str, scalar or callable, optional + The method used to calculate the estimator bandwidth. This can be + 'scott', 'silverman', a scalar constant or a callable. If a + scalar, this will be used directly as `kde.factor`. If a callable, + it should take a `gaussian_kde` instance as only parameter and + return a scalar. If None (default), nothing happens; the current + `kde.covariance_factor` method is kept. + + Notes + ----- + .. versionadded:: 0.11 + + Examples + -------- + >>> import numpy as np + >>> import scipy.stats as stats + >>> x1 = np.array([-7, -5, 1, 4, 5.]) + >>> kde = stats.gaussian_kde(x1) + >>> xs = np.linspace(-10, 10, num=50) + >>> y1 = kde(xs) + >>> kde.set_bandwidth(bw_method='silverman') + >>> y2 = kde(xs) + >>> kde.set_bandwidth(bw_method=kde.factor / 3.) + >>> y3 = kde(xs) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.plot(x1, np.full(x1.shape, 1 / (4. * x1.size)), 'bo', + ... label='Data points (rescaled)') + >>> ax.plot(xs, y1, label='Scott (default)') + >>> ax.plot(xs, y2, label='Silverman') + >>> ax.plot(xs, y3, label='Const (1/3 * Silverman)') + >>> ax.legend() + >>> plt.show() + + """ + if bw_method is None: + pass + elif bw_method == 'scott': + self.covariance_factor = self.scotts_factor + elif bw_method == 'silverman': + self.covariance_factor = self.silverman_factor + elif np.isscalar(bw_method) and not isinstance(bw_method, str): + self._bw_method = 'use constant' + self.covariance_factor = lambda: bw_method + elif callable(bw_method): + self._bw_method = bw_method + self.covariance_factor = lambda: self._bw_method(self) + else: + msg = "`bw_method` should be 'scott', 'silverman', a scalar " \ + "or a callable." + raise ValueError(msg) + + self._compute_covariance() + + def _compute_covariance(self): + """Computes the covariance matrix for each Gaussian kernel using + covariance_factor(). + """ + self.factor = self.covariance_factor() + # Cache covariance and Cholesky decomp of covariance + if not hasattr(self, '_data_cho_cov'): + self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1, + bias=False, + aweights=self.weights)) + self._data_cho_cov = linalg.cholesky(self._data_covariance, + lower=True) + + self.covariance = self._data_covariance * self.factor**2 + self.cho_cov = (self._data_cho_cov * self.factor).astype(np.float64) + self.log_det = 2*np.log(np.diag(self.cho_cov + * np.sqrt(2*pi))).sum() + + @property + def inv_cov(self): + # Re-compute from scratch each time because I'm not sure how this is + # used in the wild. (Perhaps users change the `dataset`, since it's + # not a private attribute?) `_compute_covariance` used to recalculate + # all these, so we'll recalculate everything now that this is a + # a property. + self.factor = self.covariance_factor() + self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1, + bias=False, aweights=self.weights)) + return linalg.inv(self._data_covariance) / self.factor**2 + + def pdf(self, x): + """ + Evaluate the estimated pdf on a provided set of points. + + Notes + ----- + This is an alias for `gaussian_kde.evaluate`. See the ``evaluate`` + docstring for more details. + + """ + return self.evaluate(x) + + def logpdf(self, x): + """ + Evaluate the log of the estimated pdf on a provided set of points. + """ + points = atleast_2d(x) + + d, m = points.shape + if d != self.d: + if d == 1 and m == self.d: + # points was passed in as a row vector + points = reshape(points, (self.d, 1)) + m = 1 + else: + msg = (f"points have dimension {d}, " + f"dataset has dimension {self.d}") + raise ValueError(msg) + + output_dtype, spec = _get_output_dtype(self.covariance, points) + result = gaussian_kernel_estimate_log[spec]( + self.dataset.T, self.weights[:, None], + points.T, self.cho_cov, output_dtype) + + return result[:, 0] + + def marginal(self, dimensions): + """Return a marginal KDE distribution + + Parameters + ---------- + dimensions : int or 1-d array_like + The dimensions of the multivariate distribution corresponding + with the marginal variables, that is, the indices of the dimensions + that are being retained. The other dimensions are marginalized out. + + Returns + ------- + marginal_kde : gaussian_kde + An object representing the marginal distribution. + + Notes + ----- + .. versionadded:: 1.10.0 + + """ + + dims = np.atleast_1d(dimensions) + + if not np.issubdtype(dims.dtype, np.integer): + msg = ("Elements of `dimensions` must be integers - the indices " + "of the marginal variables being retained.") + raise ValueError(msg) + + n = len(self.dataset) # number of dimensions + original_dims = dims.copy() + + dims[dims < 0] = n + dims[dims < 0] + + if len(np.unique(dims)) != len(dims): + msg = ("All elements of `dimensions` must be unique.") + raise ValueError(msg) + + i_invalid = (dims < 0) | (dims >= n) + if np.any(i_invalid): + msg = (f"Dimensions {original_dims[i_invalid]} are invalid " + f"for a distribution in {n} dimensions.") + raise ValueError(msg) + + dataset = self.dataset[dims] + weights = self.weights + + return gaussian_kde(dataset, bw_method=self.covariance_factor(), + weights=weights) + + @property + def weights(self): + try: + return self._weights + except AttributeError: + self._weights = ones(self.n)/self.n + return self._weights + + @property + def neff(self): + try: + return self._neff + except AttributeError: + self._neff = 1/sum(self.weights**2) + return self._neff + + +def _get_output_dtype(covariance, points): + """ + Calculates the output dtype and the "spec" (=C type name). + + This was necessary in order to deal with the fused types in the Cython + routine `gaussian_kernel_estimate`. See gh-10824 for details. + """ + output_dtype = np.common_type(covariance, points) + itemsize = np.dtype(output_dtype).itemsize + if itemsize == 4: + spec = 'float' + elif itemsize == 8: + spec = 'double' + elif itemsize in (12, 16): + spec = 'long double' + else: + raise ValueError( + f"{output_dtype} has unexpected item size: {itemsize}" + ) + + return output_dtype, spec diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_ksstats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_ksstats.py new file mode 100644 index 0000000000000000000000000000000000000000..a25d07e3233b40d791d4ce5332490f6e74cde290 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_ksstats.py @@ -0,0 +1,600 @@ +# Compute the two-sided one-sample Kolmogorov-Smirnov Prob(Dn <= d) where: +# D_n = sup_x{|F_n(x) - F(x)|}, +# F_n(x) is the empirical CDF for a sample of size n {x_i: i=1,...,n}, +# F(x) is the CDF of a probability distribution. +# +# Exact methods: +# Prob(D_n >= d) can be computed via a matrix algorithm of Durbin[1] +# or a recursion algorithm due to Pomeranz[2]. +# Marsaglia, Tsang & Wang[3] gave a computation-efficient way to perform +# the Durbin algorithm. +# D_n >= d <==> D_n+ >= d or D_n- >= d (the one-sided K-S statistics), hence +# Prob(D_n >= d) = 2*Prob(D_n+ >= d) - Prob(D_n+ >= d and D_n- >= d). +# For d > 0.5, the latter intersection probability is 0. +# +# Approximate methods: +# For d close to 0.5, ignoring that intersection term may still give a +# reasonable approximation. +# Li-Chien[4] and Korolyuk[5] gave an asymptotic formula extending +# Kolmogorov's initial asymptotic, suitable for large d. (See +# scipy.special.kolmogorov for that asymptotic) +# Pelz-Good[6] used the functional equation for Jacobi theta functions to +# transform the Li-Chien/Korolyuk formula produce a computational formula +# suitable for small d. +# +# Simard and L'Ecuyer[7] provided an algorithm to decide when to use each of +# the above approaches and it is that which is used here. +# +# Other approaches: +# Carvalho[8] optimizes Durbin's matrix algorithm for large values of d. +# Moscovich and Nadler[9] use FFTs to compute the convolutions. + +# References: +# [1] Durbin J (1968). +# "The Probability that the Sample Distribution Function Lies Between Two +# Parallel Straight Lines." +# Annals of Mathematical Statistics, 39, 398-411. +# [2] Pomeranz J (1974). +# "Exact Cumulative Distribution of the Kolmogorov-Smirnov Statistic for +# Small Samples (Algorithm 487)." +# Communications of the ACM, 17(12), 703-704. +# [3] Marsaglia G, Tsang WW, Wang J (2003). +# "Evaluating Kolmogorov's Distribution." +# Journal of Statistical Software, 8(18), 1-4. +# [4] LI-CHIEN, C. (1956). +# "On the exact distribution of the statistics of A. N. Kolmogorov and +# their asymptotic expansion." +# Acta Matematica Sinica, 6, 55-81. +# [5] KOROLYUK, V. S. (1960). +# "Asymptotic analysis of the distribution of the maximum deviation in +# the Bernoulli scheme." +# Theor. Probability Appl., 4, 339-366. +# [6] Pelz W, Good IJ (1976). +# "Approximating the Lower Tail-areas of the Kolmogorov-Smirnov One-sample +# Statistic." +# Journal of the Royal Statistical Society, Series B, 38(2), 152-156. +# [7] Simard, R., L'Ecuyer, P. (2011) +# "Computing the Two-Sided Kolmogorov-Smirnov Distribution", +# Journal of Statistical Software, Vol 39, 11, 1-18. +# [8] Carvalho, Luis (2015) +# "An Improved Evaluation of Kolmogorov's Distribution" +# Journal of Statistical Software, Code Snippets; Vol 65(3), 1-8. +# [9] Amit Moscovich, Boaz Nadler (2017) +# "Fast calculation of boundary crossing probabilities for Poisson +# processes", +# Statistics & Probability Letters, Vol 123, 177-182. + + +import numpy as np +import scipy.special +import scipy.special._ufuncs as scu +from scipy._lib._finite_differences import _derivative + +_E128 = 128 +_EP128 = np.ldexp(np.longdouble(1), _E128) +_EM128 = np.ldexp(np.longdouble(1), -_E128) + +_SQRT2PI = np.sqrt(2 * np.pi) +_LOG_2PI = np.log(2 * np.pi) +_MIN_LOG = -708 +_SQRT3 = np.sqrt(3) +_PI_SQUARED = np.pi ** 2 +_PI_FOUR = np.pi ** 4 +_PI_SIX = np.pi ** 6 + +# [Lifted from _loggamma.pxd.] If B_m are the Bernoulli numbers, +# then Stirling coeffs are B_{2j}/(2j)/(2j-1) for j=8,...1. +_STIRLING_COEFFS = [-2.955065359477124183e-2, 6.4102564102564102564e-3, + -1.9175269175269175269e-3, 8.4175084175084175084e-4, + -5.952380952380952381e-4, 7.9365079365079365079e-4, + -2.7777777777777777778e-3, 8.3333333333333333333e-2] + + +def _log_nfactorial_div_n_pow_n(n): + # Computes n! / n**n + # = (n-1)! / n**(n-1) + # Uses Stirling's approximation, but removes n*log(n) up-front to + # avoid subtractive cancellation. + # = log(n)/2 - n + log(sqrt(2pi)) + sum B_{2j}/(2j)/(2j-1)/n**(2j-1) + rn = 1.0/n + return np.log(n)/2 - n + _LOG_2PI/2 + rn * np.polyval(_STIRLING_COEFFS, rn/n) + + +def _clip_prob(p): + """clips a probability to range 0<=p<=1.""" + return np.clip(p, 0.0, 1.0) + + +def _select_and_clip_prob(cdfprob, sfprob, cdf=True): + """Selects either the CDF or SF, and then clips to range 0<=p<=1.""" + p = np.where(cdf, cdfprob, sfprob) + return _clip_prob(p) + + +def _kolmogn_DMTW(n, d, cdf=True): + r"""Computes the Kolmogorov CDF: Pr(D_n <= d) using the MTW approach to + the Durbin matrix algorithm. + + Durbin (1968); Marsaglia, Tsang, Wang (2003). [1], [3]. + """ + # Write d = (k-h)/n, where k is positive integer and 0 <= h < 1 + # Generate initial matrix H of size m*m where m=(2k-1) + # Compute k-th row of (n!/n^n) * H^n, scaling intermediate results. + # Requires memory O(m^2) and computation O(m^2 log(n)). + # Most suitable for small m. + + if d >= 1.0: + return _select_and_clip_prob(1.0, 0.0, cdf) + nd = n * d + if nd <= 0.5: + return _select_and_clip_prob(0.0, 1.0, cdf) + k = int(np.ceil(nd)) + h = k - nd + m = 2 * k - 1 + + H = np.zeros([m, m]) + + # Initialize: v is first column (and last row) of H + # v[j] = (1-h^(j+1)/(j+1)! (except for v[-1]) + # w[j] = 1/(j)! + # q = k-th row of H (actually i!/n^i*H^i) + intm = np.arange(1, m + 1) + v = 1.0 - h ** intm + w = np.empty(m) + fac = 1.0 + for j in intm: + w[j - 1] = fac + fac /= j # This might underflow. Isn't a problem. + v[j - 1] *= fac + tt = max(2 * h - 1.0, 0)**m - 2*h**m + v[-1] = (1.0 + tt) * fac + + for i in range(1, m): + H[i - 1:, i] = w[:m - i + 1] + H[:, 0] = v + H[-1, :] = np.flip(v, axis=0) + + Hpwr = np.eye(np.shape(H)[0]) # Holds intermediate powers of H + nn = n + expnt = 0 # Scaling of Hpwr + Hexpnt = 0 # Scaling of H + while nn > 0: + if nn % 2: + Hpwr = np.matmul(Hpwr, H) + expnt += Hexpnt + H = np.matmul(H, H) + Hexpnt *= 2 + # Scale as needed. + if np.abs(H[k - 1, k - 1]) > _EP128: + H /= _EP128 + Hexpnt += _E128 + nn = nn // 2 + + p = Hpwr[k - 1, k - 1] + + # Multiply by n!/n^n + for i in range(1, n + 1): + p = i * p / n + if np.abs(p) < _EM128: + p *= _EP128 + expnt -= _E128 + + # unscale + if expnt != 0: + p = np.ldexp(p, expnt) + + return _select_and_clip_prob(p, 1.0-p, cdf) + + +def _pomeranz_compute_j1j2(i, n, ll, ceilf, roundf): + """Compute the endpoints of the interval for row i.""" + if i == 0: + j1, j2 = -ll - ceilf - 1, ll + ceilf - 1 + else: + # i + 1 = 2*ip1div2 + ip1mod2 + ip1div2, ip1mod2 = divmod(i + 1, 2) + if ip1mod2 == 0: # i is odd + if ip1div2 == n + 1: + j1, j2 = n - ll - ceilf - 1, n + ll + ceilf - 1 + else: + j1, j2 = ip1div2 - 1 - ll - roundf - 1, ip1div2 + ll - 1 + ceilf - 1 + else: + j1, j2 = ip1div2 - 1 - ll - 1, ip1div2 + ll + roundf - 1 + + return max(j1 + 2, 0), min(j2, n) + + +def _kolmogn_Pomeranz(n, x, cdf=True): + r"""Computes Pr(D_n <= d) using the Pomeranz recursion algorithm. + + Pomeranz (1974) [2] + """ + + # V is n*(2n+2) matrix. + # Each row is convolution of the previous row and probabilities from a + # Poisson distribution. + # Desired CDF probability is n! V[n-1, 2n+1] (final entry in final row). + # Only two rows are needed at any given stage: + # - Call them V0 and V1. + # - Swap each iteration + # Only a few (contiguous) entries in each row can be non-zero. + # - Keep track of start and end (j1 and j2 below) + # - V0s and V1s track the start in the two rows + # Scale intermediate results as needed. + # Only a few different Poisson distributions can occur + t = n * x + ll = int(np.floor(t)) + f = 1.0 * (t - ll) # fractional part of t + g = min(f, 1.0 - f) + ceilf = (1 if f > 0 else 0) + roundf = (1 if f > 0.5 else 0) + npwrs = 2 * (ll + 1) # Maximum number of powers needed in convolutions + gpower = np.empty(npwrs) # gpower = (g/n)^m/m! + twogpower = np.empty(npwrs) # twogpower = (2g/n)^m/m! + onem2gpower = np.empty(npwrs) # onem2gpower = ((1-2g)/n)^m/m! + # gpower etc are *almost* Poisson probs, just missing normalizing factor. + + gpower[0] = 1.0 + twogpower[0] = 1.0 + onem2gpower[0] = 1.0 + expnt = 0 + g_over_n, two_g_over_n, one_minus_two_g_over_n = g/n, 2*g/n, (1 - 2*g)/n + for m in range(1, npwrs): + gpower[m] = gpower[m - 1] * g_over_n / m + twogpower[m] = twogpower[m - 1] * two_g_over_n / m + onem2gpower[m] = onem2gpower[m - 1] * one_minus_two_g_over_n / m + + V0 = np.zeros([npwrs]) + V1 = np.zeros([npwrs]) + V1[0] = 1 # first row + V0s, V1s = 0, 0 # start indices of the two rows + + j1, j2 = _pomeranz_compute_j1j2(0, n, ll, ceilf, roundf) + for i in range(1, 2 * n + 2): + # Preserve j1, V1, V1s, V0s from last iteration + k1 = j1 + V0, V1 = V1, V0 + V0s, V1s = V1s, V0s + V1.fill(0.0) + j1, j2 = _pomeranz_compute_j1j2(i, n, ll, ceilf, roundf) + if i == 1 or i == 2 * n + 1: + pwrs = gpower + else: + pwrs = (twogpower if i % 2 else onem2gpower) + ln2 = j2 - k1 + 1 + if ln2 > 0: + conv = np.convolve(V0[k1 - V0s:k1 - V0s + ln2], pwrs[:ln2]) + conv_start = j1 - k1 # First index to use from conv + conv_len = j2 - j1 + 1 # Number of entries to use from conv + V1[:conv_len] = conv[conv_start:conv_start + conv_len] + # Scale to avoid underflow. + if 0 < np.max(V1) < _EM128: + V1 *= _EP128 + expnt -= _E128 + V1s = V0s + j1 - k1 + + # multiply by n! + ans = V1[n - V1s] + for m in range(1, n + 1): + if np.abs(ans) > _EP128: + ans *= _EM128 + expnt += _E128 + ans *= m + + # Undo any intermediate scaling + if expnt != 0: + ans = np.ldexp(ans, expnt) + ans = _select_and_clip_prob(ans, 1.0 - ans, cdf) + return ans + + +def _kolmogn_PelzGood(n, x, cdf=True): + """Computes the Pelz-Good approximation to Prob(Dn <= x) with 0<=x<=1. + + Start with Li-Chien, Korolyuk approximation: + Prob(Dn <= x) ~ K0(z) + K1(z)/sqrt(n) + K2(z)/n + K3(z)/n**1.5 + where z = x*sqrt(n). + Transform each K_(z) using Jacobi theta functions into a form suitable + for small z. + Pelz-Good (1976). [6] + """ + if x <= 0.0: + return _select_and_clip_prob(0.0, 1.0, cdf=cdf) + if x >= 1.0: + return _select_and_clip_prob(1.0, 0.0, cdf=cdf) + + z = np.sqrt(n) * x + zsquared, zthree, zfour, zsix = z**2, z**3, z**4, z**6 + + qlog = -_PI_SQUARED / 8 / zsquared + if qlog < _MIN_LOG: # z ~ 0.041743441416853426 + return _select_and_clip_prob(0.0, 1.0, cdf=cdf) + + q = np.exp(qlog) + + # Coefficients of terms in the sums for K1, K2 and K3 + k1a = -zsquared + k1b = _PI_SQUARED / 4 + + k2a = 6 * zsix + 2 * zfour + k2b = (2 * zfour - 5 * zsquared) * _PI_SQUARED / 4 + k2c = _PI_FOUR * (1 - 2 * zsquared) / 16 + + k3d = _PI_SIX * (5 - 30 * zsquared) / 64 + k3c = _PI_FOUR * (-60 * zsquared + 212 * zfour) / 16 + k3b = _PI_SQUARED * (135 * zfour - 96 * zsix) / 4 + k3a = -30 * zsix - 90 * z**8 + + K0to3 = np.zeros(4) + # Use a Horner scheme to evaluate sum c_i q^(i^2) + # Reduces to a sum over odd integers. + maxk = int(np.ceil(16 * z / np.pi)) + for k in range(maxk, 0, -1): + m = 2 * k - 1 + msquared, mfour, msix = m**2, m**4, m**6 + qpower = np.power(q, 8 * k) + coeffs = np.array([1.0, + k1a + k1b*msquared, + k2a + k2b*msquared + k2c*mfour, + k3a + k3b*msquared + k3c*mfour + k3d*msix]) + K0to3 *= qpower + K0to3 += coeffs + K0to3 *= q + K0to3 *= _SQRT2PI + # z**10 > 0 as z > 0.04 + K0to3 /= np.array([z, 6 * zfour, 72 * z**7, 6480 * z**10]) + + # Now do the other sum over the other terms, all integers k + # K_2: (pi^2 k^2) q^(k^2), + # K_3: (3pi^2 k^2 z^2 - pi^4 k^4)*q^(k^2) + # Don't expect much subtractive cancellation so use direct calculation + q = np.exp(-_PI_SQUARED / 2 / zsquared) + ks = np.arange(maxk, 0, -1) + ksquared = ks ** 2 + sqrt3z = _SQRT3 * z + kspi = np.pi * ks + qpwers = q ** ksquared + k2extra = np.sum(ksquared * qpwers) + k2extra *= _PI_SQUARED * _SQRT2PI/(-36 * zthree) + K0to3[2] += k2extra + k3extra = np.sum((sqrt3z + kspi) * (sqrt3z - kspi) * ksquared * qpwers) + k3extra *= _PI_SQUARED * _SQRT2PI/(216 * zsix) + K0to3[3] += k3extra + powers_of_n = np.power(n * 1.0, np.arange(len(K0to3)) / 2.0) + K0to3 /= powers_of_n + + if not cdf: + K0to3 *= -1 + K0to3[0] += 1 + + Ksum = sum(K0to3) + return Ksum + + +def _kolmogn(n, x, cdf=True): + """Computes the CDF(or SF) for the two-sided Kolmogorov-Smirnov statistic. + + x must be of type float, n of type integer. + + Simard & L'Ecuyer (2011) [7]. + """ + if np.isnan(n): + return n # Keep the same type of nan + if int(n) != n or n <= 0: + return np.nan + if x >= 1.0: + return _select_and_clip_prob(1.0, 0.0, cdf=cdf) + if x <= 0.0: + return _select_and_clip_prob(0.0, 1.0, cdf=cdf) + t = n * x + if t <= 1.0: # Ruben-Gambino: 1/2n <= x <= 1/n + if t <= 0.5: + return _select_and_clip_prob(0.0, 1.0, cdf=cdf) + if n <= 140: + prob = np.prod(np.arange(1, n+1) * (1.0/n) * (2*t - 1)) + else: + prob = np.exp(_log_nfactorial_div_n_pow_n(n) + n * np.log(2*t-1)) + return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf) + if t >= n - 1: # Ruben-Gambino + prob = 2 * (1.0 - x)**n + return _select_and_clip_prob(1 - prob, prob, cdf=cdf) + if x >= 0.5: # Exact: 2 * smirnov + prob = 2 * scipy.special.smirnov(n, x) + return _select_and_clip_prob(1.0 - prob, prob, cdf=cdf) + + nxsquared = t * x + if n <= 140: + if nxsquared <= 0.754693: + prob = _kolmogn_DMTW(n, x, cdf=True) + return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf) + if nxsquared <= 4: + prob = _kolmogn_Pomeranz(n, x, cdf=True) + return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf) + # Now use Miller approximation of 2*smirnov + prob = 2 * scipy.special.smirnov(n, x) + return _select_and_clip_prob(1.0 - prob, prob, cdf=cdf) + + # Split CDF and SF as they have different cutoffs on nxsquared. + if not cdf: + if nxsquared >= 370.0: + return 0.0 + if nxsquared >= 2.2: + prob = 2 * scipy.special.smirnov(n, x) + return _clip_prob(prob) + # Fall through and compute the SF as 1.0-CDF + if nxsquared >= 18.0: + cdfprob = 1.0 + elif n <= 100000 and n * x**1.5 <= 1.4: + cdfprob = _kolmogn_DMTW(n, x, cdf=True) + else: + cdfprob = _kolmogn_PelzGood(n, x, cdf=True) + return _select_and_clip_prob(cdfprob, 1.0 - cdfprob, cdf=cdf) + + +def _kolmogn_p(n, x): + """Computes the PDF for the two-sided Kolmogorov-Smirnov statistic. + + x must be of type float, n of type integer. + """ + if np.isnan(n): + return n # Keep the same type of nan + if int(n) != n or n <= 0: + return np.nan + if x >= 1.0 or x <= 0: + return 0 + t = n * x + if t <= 1.0: + # Ruben-Gambino: n!/n^n * (2t-1)^n -> 2 n!/n^n * n^2 * (2t-1)^(n-1) + if t <= 0.5: + return 0.0 + if n <= 140: + prd = np.prod(np.arange(1, n) * (1.0 / n) * (2 * t - 1)) + else: + prd = np.exp(_log_nfactorial_div_n_pow_n(n) + (n-1) * np.log(2 * t - 1)) + return prd * 2 * n**2 + if t >= n - 1: + # Ruben-Gambino : 1-2(1-x)**n -> 2n*(1-x)**(n-1) + return 2 * (1.0 - x) ** (n-1) * n + if x >= 0.5: + return 2 * scipy.stats.ksone.pdf(x, n) + + # Just take a small delta. + # Ideally x +/- delta would stay within [i/n, (i+1)/n] for some integer a. + # as the CDF is a piecewise degree n polynomial. + # It has knots at 1/n, 2/n, ... (n-1)/n + # and is not a C-infinity function at the knots + delta = x / 2.0**16 + delta = min(delta, x - 1.0/n) + delta = min(delta, 0.5 - x) + + def _kk(_x): + return kolmogn(n, _x) + + return _derivative(_kk, x, dx=delta, order=5) + + +def _kolmogni(n, p, q): + """Computes the PPF/ISF of kolmogn. + + n of type integer, n>= 1 + p is the CDF, q the SF, p+q=1 + """ + if np.isnan(n): + return n # Keep the same type of nan + if int(n) != n or n <= 0: + return np.nan + if p <= 0: + return 1.0/n + if q <= 0: + return 1.0 + delta = np.exp((np.log(p) - scipy.special.loggamma(n+1))/n) + if delta <= 1.0/n: + return (delta + 1.0 / n) / 2 + x = -np.expm1(np.log(q/2.0)/n) + if x >= 1 - 1.0/n: + return x + x1 = scu._kolmogci(p)/np.sqrt(n) + x1 = min(x1, 1.0 - 1.0/n) + + def _f(x): + return _kolmogn(n, x) - p + + return scipy.optimize.brentq(_f, 1.0/n, x1, xtol=1e-14) + + +def kolmogn(n, x, cdf=True): + """Computes the CDF for the two-sided Kolmogorov-Smirnov distribution. + + The two-sided Kolmogorov-Smirnov distribution has as its CDF Pr(D_n <= x), + for a sample of size n drawn from a distribution with CDF F(t), where + :math:`D_n &= sup_t |F_n(t) - F(t)|`, and + :math:`F_n(t)` is the Empirical Cumulative Distribution Function of the sample. + + Parameters + ---------- + n : integer, array_like + the number of samples + x : float, array_like + The K-S statistic, float between 0 and 1 + cdf : bool, optional + whether to compute the CDF(default=true) or the SF. + + Returns + ------- + cdf : ndarray + CDF (or SF it cdf is False) at the specified locations. + + The return value has shape the result of numpy broadcasting n and x. + """ + it = np.nditer([n, x, cdf, None], flags=['zerosize_ok'], + op_dtypes=[None, np.float64, np.bool_, np.float64]) + for _n, _x, _cdf, z in it: + if np.isnan(_n): + z[...] = _n + continue + if int(_n) != _n: + raise ValueError(f'n is not integral: {_n}') + z[...] = _kolmogn(int(_n), _x, cdf=_cdf) + result = it.operands[-1] + return result + + +def kolmognp(n, x): + """Computes the PDF for the two-sided Kolmogorov-Smirnov distribution. + + Parameters + ---------- + n : integer, array_like + the number of samples + x : float, array_like + The K-S statistic, float between 0 and 1 + + Returns + ------- + pdf : ndarray + The PDF at the specified locations + + The return value has shape the result of numpy broadcasting n and x. + """ + it = np.nditer([n, x, None]) + for _n, _x, z in it: + if np.isnan(_n): + z[...] = _n + continue + if int(_n) != _n: + raise ValueError(f'n is not integral: {_n}') + z[...] = _kolmogn_p(int(_n), _x) + result = it.operands[-1] + return result + + +def kolmogni(n, q, cdf=True): + """Computes the PPF(or ISF) for the two-sided Kolmogorov-Smirnov distribution. + + Parameters + ---------- + n : integer, array_like + the number of samples + q : float, array_like + Probabilities, float between 0 and 1 + cdf : bool, optional + whether to compute the PPF(default=true) or the ISF. + + Returns + ------- + ppf : ndarray + PPF (or ISF if cdf is False) at the specified locations + + The return value has shape the result of numpy broadcasting n and x. + """ + it = np.nditer([n, q, cdf, None]) + for _n, _q, _cdf, z in it: + if np.isnan(_n): + z[...] = _n + continue + if int(_n) != _n: + raise ValueError(f'n is not integral: {_n}') + _pcdf, _psf = (_q, 1-_q) if _cdf else (1-_q, _q) + z[...] = _kolmogni(int(_n), _pcdf, _psf) + result = it.operands[-1] + return result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..96ae567e41429e652f1d4ad61b0512f1bc5c6615 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py @@ -0,0 +1,1239 @@ +# + +import warnings +from functools import partial + +import numpy as np + +from scipy import optimize +from scipy import integrate +from scipy.integrate._quadrature import _builtincoeffs +from scipy import interpolate +from scipy.interpolate import RectBivariateSpline +import scipy.special as sc +from scipy._lib._util import _lazywhere +from .._distn_infrastructure import rv_continuous, _ShapeInfo, rv_continuous_frozen +from .._continuous_distns import uniform, expon, _norm_pdf, _norm_cdf +from .levyst import Nolan +from scipy._lib.doccer import inherit_docstring_from + + +__all__ = ["levy_stable", "levy_stable_gen", "pdf_from_cf_with_fft"] + +# Stable distributions are known for various parameterisations +# some being advantageous for numerical considerations and others +# useful due to their location/scale awareness. +# +# Here we follow [NO] convention (see the references in the docstring +# for levy_stable_gen below). +# +# S0 / Z0 / x0 (aka Zoleterav's M) +# S1 / Z1 / x1 +# +# Where S* denotes parameterisation, Z* denotes standardized +# version where gamma = 1, delta = 0 and x* denotes variable. +# +# Scipy's original Stable was a random variate generator. It +# uses S1 and unfortunately is not a location/scale aware. + + +# default numerical integration tolerance +# used for epsrel in piecewise and both epsrel and epsabs in dni +# (epsabs needed in dni since weighted quad requires epsabs > 0) +_QUAD_EPS = 1.2e-14 + + +def _Phi_Z0(alpha, t): + return ( + -np.tan(np.pi * alpha / 2) * (np.abs(t) ** (1 - alpha) - 1) + if alpha != 1 + else -2.0 * np.log(np.abs(t)) / np.pi + ) + + +def _Phi_Z1(alpha, t): + return ( + np.tan(np.pi * alpha / 2) + if alpha != 1 + else -2.0 * np.log(np.abs(t)) / np.pi + ) + + +def _cf(Phi, t, alpha, beta): + """Characteristic function.""" + return np.exp( + -(np.abs(t) ** alpha) * (1 - 1j * beta * np.sign(t) * Phi(alpha, t)) + ) + + +_cf_Z0 = partial(_cf, _Phi_Z0) +_cf_Z1 = partial(_cf, _Phi_Z1) + + +def _pdf_single_value_cf_integrate(Phi, x, alpha, beta, **kwds): + """To improve DNI accuracy convert characteristic function in to real + valued integral using Euler's formula, then exploit cosine symmetry to + change limits to [0, inf). Finally use cosine addition formula to split + into two parts that can be handled by weighted quad pack. + """ + quad_eps = kwds.get("quad_eps", _QUAD_EPS) + + def integrand1(t): + if t == 0: + return 0 + return np.exp(-(t ** alpha)) * ( + np.cos(beta * (t ** alpha) * Phi(alpha, t)) + ) + + def integrand2(t): + if t == 0: + return 0 + return np.exp(-(t ** alpha)) * ( + np.sin(beta * (t ** alpha) * Phi(alpha, t)) + ) + + with np.errstate(invalid="ignore"): + int1, *ret1 = integrate.quad( + integrand1, + 0, + np.inf, + weight="cos", + wvar=x, + limit=1000, + epsabs=quad_eps, + epsrel=quad_eps, + full_output=1, + ) + + int2, *ret2 = integrate.quad( + integrand2, + 0, + np.inf, + weight="sin", + wvar=x, + limit=1000, + epsabs=quad_eps, + epsrel=quad_eps, + full_output=1, + ) + + return (int1 + int2) / np.pi + + +_pdf_single_value_cf_integrate_Z0 = partial( + _pdf_single_value_cf_integrate, _Phi_Z0 +) +_pdf_single_value_cf_integrate_Z1 = partial( + _pdf_single_value_cf_integrate, _Phi_Z1 +) + + +def _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta): + """Round x close to zeta for Nolan's method in [NO].""" + # "8. When |x0-beta*tan(pi*alpha/2)| is small, the + # computations of the density and cumulative have numerical problems. + # The program works around this by setting + # z = beta*tan(pi*alpha/2) when + # |z-beta*tan(pi*alpha/2)| < tol(5)*alpha**(1/alpha). + # (The bound on the right is ad hoc, to get reasonable behavior + # when alpha is small)." + # where tol(5) = 0.5e-2 by default. + # + # We seem to have partially addressed this through re-expression of + # g(theta) here, but it still needs to be used in some extreme cases. + # Perhaps tol(5) = 0.5e-2 could be reduced for our implementation. + if np.abs(x0 - zeta) < x_tol_near_zeta * alpha ** (1 / alpha): + x0 = zeta + return x0 + + +def _nolan_round_difficult_input( + x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one +): + """Round difficult input values for Nolan's method in [NO].""" + + # following Nolan's STABLE, + # "1. When 0 < |alpha-1| < 0.005, the program has numerical problems + # evaluating the pdf and cdf. The current version of the program sets + # alpha=1 in these cases. This approximation is not bad in the S0 + # parameterization." + if np.abs(alpha - 1) < alpha_tol_near_one: + alpha = 1.0 + + # "2. When alpha=1 and |beta| < 0.005, the program has numerical + # problems. The current version sets beta=0." + # We seem to have addressed this through re-expression of g(theta) here + + x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta) + return x0, alpha, beta + + +def _pdf_single_value_piecewise_Z1(x, alpha, beta, **kwds): + # convert from Nolan's S_1 (aka S) to S_0 (aka Zolaterev M) + # parameterization + + zeta = -beta * np.tan(np.pi * alpha / 2.0) + x0 = x + zeta if alpha != 1 else x + + return _pdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds) + + +def _pdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds): + + quad_eps = kwds.get("quad_eps", _QUAD_EPS) + x_tol_near_zeta = kwds.get("piecewise_x_tol_near_zeta", 0.005) + alpha_tol_near_one = kwds.get("piecewise_alpha_tol_near_one", 0.005) + + zeta = -beta * np.tan(np.pi * alpha / 2.0) + x0, alpha, beta = _nolan_round_difficult_input( + x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one + ) + + # some other known distribution pdfs / analytical cases + # TODO: add more where possible with test coverage, + # eg https://en.wikipedia.org/wiki/Stable_distribution#Other_analytic_cases + if alpha == 2.0: + # normal + return _norm_pdf(x0 / np.sqrt(2)) / np.sqrt(2) + elif alpha == 0.5 and beta == 1.0: + # levy + # since S(1/2, 1, gamma, delta; ) == + # S(1/2, 1, gamma, gamma + delta; ). + _x = x0 + 1 + if _x <= 0: + return 0 + + return 1 / np.sqrt(2 * np.pi * _x) / _x * np.exp(-1 / (2 * _x)) + elif alpha == 0.5 and beta == 0.0 and x0 != 0: + # analytical solution [HO] + S, C = sc.fresnel([1 / np.sqrt(2 * np.pi * np.abs(x0))]) + arg = 1 / (4 * np.abs(x0)) + return ( + np.sin(arg) * (0.5 - S[0]) + np.cos(arg) * (0.5 - C[0]) + ) / np.sqrt(2 * np.pi * np.abs(x0) ** 3) + elif alpha == 1.0 and beta == 0.0: + # cauchy + return 1 / (1 + x0 ** 2) / np.pi + + return _pdf_single_value_piecewise_post_rounding_Z0( + x0, alpha, beta, quad_eps, x_tol_near_zeta + ) + + +def _pdf_single_value_piecewise_post_rounding_Z0(x0, alpha, beta, quad_eps, + x_tol_near_zeta): + """Calculate pdf using Nolan's methods as detailed in [NO].""" + + _nolan = Nolan(alpha, beta, x0) + zeta = _nolan.zeta + xi = _nolan.xi + c2 = _nolan.c2 + g = _nolan.g + + # round x0 to zeta again if needed. zeta was recomputed and may have + # changed due to floating point differences. + # See https://github.com/scipy/scipy/pull/18133 + x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta) + # handle Nolan's initial case logic + if x0 == zeta: + return ( + sc.gamma(1 + 1 / alpha) + * np.cos(xi) + / np.pi + / ((1 + zeta ** 2) ** (1 / alpha / 2)) + ) + elif x0 < zeta: + return _pdf_single_value_piecewise_post_rounding_Z0( + -x0, alpha, -beta, quad_eps, x_tol_near_zeta + ) + + # following Nolan, we may now assume + # x0 > zeta when alpha != 1 + # beta != 0 when alpha == 1 + + # spare calculating integral on null set + # use isclose as macos has fp differences + if np.isclose(-xi, np.pi / 2, rtol=1e-014, atol=1e-014): + return 0.0 + + def integrand(theta): + # limit any numerical issues leading to g_1 < 0 near theta limits + g_1 = g(theta) + if not np.isfinite(g_1) or g_1 < 0: + g_1 = 0 + return g_1 * np.exp(-g_1) + + with np.errstate(all="ignore"): + peak = optimize.bisect( + lambda t: g(t) - 1, -xi, np.pi / 2, xtol=quad_eps + ) + + # this integrand can be very peaked, so we need to force + # QUADPACK to evaluate the function inside its support + # + + # lastly, we add additional samples at + # ~exp(-100), ~exp(-10), ~exp(-5), ~exp(-1) + # to improve QUADPACK's detection of rapidly descending tail behavior + # (this choice is fairly ad hoc) + tail_points = [ + optimize.bisect(lambda t: g(t) - exp_height, -xi, np.pi / 2) + for exp_height in [100, 10, 5] + # exp_height = 1 is handled by peak + ] + intg_points = [0, peak] + tail_points + intg, *ret = integrate.quad( + integrand, + -xi, + np.pi / 2, + points=intg_points, + limit=100, + epsrel=quad_eps, + epsabs=0, + full_output=1, + ) + + return c2 * intg + + +def _cdf_single_value_piecewise_Z1(x, alpha, beta, **kwds): + # convert from Nolan's S_1 (aka S) to S_0 (aka Zolaterev M) + # parameterization + + zeta = -beta * np.tan(np.pi * alpha / 2.0) + x0 = x + zeta if alpha != 1 else x + + return _cdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds) + + +def _cdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds): + + quad_eps = kwds.get("quad_eps", _QUAD_EPS) + x_tol_near_zeta = kwds.get("piecewise_x_tol_near_zeta", 0.005) + alpha_tol_near_one = kwds.get("piecewise_alpha_tol_near_one", 0.005) + + zeta = -beta * np.tan(np.pi * alpha / 2.0) + x0, alpha, beta = _nolan_round_difficult_input( + x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one + ) + + # some other known distribution cdfs / analytical cases + # TODO: add more where possible with test coverage, + # eg https://en.wikipedia.org/wiki/Stable_distribution#Other_analytic_cases + if alpha == 2.0: + # normal + return _norm_cdf(x0 / np.sqrt(2)) + elif alpha == 0.5 and beta == 1.0: + # levy + # since S(1/2, 1, gamma, delta; ) == + # S(1/2, 1, gamma, gamma + delta; ). + _x = x0 + 1 + if _x <= 0: + return 0 + + return sc.erfc(np.sqrt(0.5 / _x)) + elif alpha == 1.0 and beta == 0.0: + # cauchy + return 0.5 + np.arctan(x0) / np.pi + + return _cdf_single_value_piecewise_post_rounding_Z0( + x0, alpha, beta, quad_eps, x_tol_near_zeta + ) + + +def _cdf_single_value_piecewise_post_rounding_Z0(x0, alpha, beta, quad_eps, + x_tol_near_zeta): + """Calculate cdf using Nolan's methods as detailed in [NO].""" + _nolan = Nolan(alpha, beta, x0) + zeta = _nolan.zeta + xi = _nolan.xi + c1 = _nolan.c1 + # c2 = _nolan.c2 + c3 = _nolan.c3 + g = _nolan.g + # round x0 to zeta again if needed. zeta was recomputed and may have + # changed due to floating point differences. + # See https://github.com/scipy/scipy/pull/18133 + x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta) + # handle Nolan's initial case logic + if (alpha == 1 and beta < 0) or x0 < zeta: + # NOTE: Nolan's paper has a typo here! + # He states F(x) = 1 - F(x, alpha, -beta), but this is clearly + # incorrect since F(-infty) would be 1.0 in this case + # Indeed, the alpha != 1, x0 < zeta case is correct here. + return 1 - _cdf_single_value_piecewise_post_rounding_Z0( + -x0, alpha, -beta, quad_eps, x_tol_near_zeta + ) + elif x0 == zeta: + return 0.5 - xi / np.pi + + # following Nolan, we may now assume + # x0 > zeta when alpha != 1 + # beta > 0 when alpha == 1 + + # spare calculating integral on null set + # use isclose as macos has fp differences + if np.isclose(-xi, np.pi / 2, rtol=1e-014, atol=1e-014): + return c1 + + def integrand(theta): + g_1 = g(theta) + return np.exp(-g_1) + + with np.errstate(all="ignore"): + # shrink supports where required + left_support = -xi + right_support = np.pi / 2 + if alpha > 1: + # integrand(t) monotonic 0 to 1 + if integrand(-xi) != 0.0: + res = optimize.minimize( + integrand, + (-xi,), + method="L-BFGS-B", + bounds=[(-xi, np.pi / 2)], + ) + left_support = res.x[0] + else: + # integrand(t) monotonic 1 to 0 + if integrand(np.pi / 2) != 0.0: + res = optimize.minimize( + integrand, + (np.pi / 2,), + method="L-BFGS-B", + bounds=[(-xi, np.pi / 2)], + ) + right_support = res.x[0] + + intg, *ret = integrate.quad( + integrand, + left_support, + right_support, + points=[left_support, right_support], + limit=100, + epsrel=quad_eps, + epsabs=0, + full_output=1, + ) + + return c1 + c3 * intg + + +def _rvs_Z1(alpha, beta, size=None, random_state=None): + """Simulate random variables using Nolan's methods as detailed in [NO]. + """ + + def alpha1func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W): + return ( + 2 + / np.pi + * ( + (np.pi / 2 + bTH) * tanTH + - beta * np.log((np.pi / 2 * W * cosTH) / (np.pi / 2 + bTH)) + ) + ) + + def beta0func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W): + return ( + W + / (cosTH / np.tan(aTH) + np.sin(TH)) + * ((np.cos(aTH) + np.sin(aTH) * tanTH) / W) ** (1.0 / alpha) + ) + + def otherwise(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W): + # alpha is not 1 and beta is not 0 + val0 = beta * np.tan(np.pi * alpha / 2) + th0 = np.arctan(val0) / alpha + val3 = W / (cosTH / np.tan(alpha * (th0 + TH)) + np.sin(TH)) + res3 = val3 * ( + ( + np.cos(aTH) + + np.sin(aTH) * tanTH + - val0 * (np.sin(aTH) - np.cos(aTH) * tanTH) + ) + / W + ) ** (1.0 / alpha) + return res3 + + def alphanot1func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W): + res = _lazywhere( + beta == 0, + (alpha, beta, TH, aTH, bTH, cosTH, tanTH, W), + beta0func, + f2=otherwise, + ) + return res + + alpha = np.broadcast_to(alpha, size) + beta = np.broadcast_to(beta, size) + TH = uniform.rvs( + loc=-np.pi / 2.0, scale=np.pi, size=size, random_state=random_state + ) + W = expon.rvs(size=size, random_state=random_state) + aTH = alpha * TH + bTH = beta * TH + cosTH = np.cos(TH) + tanTH = np.tan(TH) + res = _lazywhere( + alpha == 1, + (alpha, beta, TH, aTH, bTH, cosTH, tanTH, W), + alpha1func, + f2=alphanot1func, + ) + return res + + +def _fitstart_S0(data): + alpha, beta, delta1, gamma = _fitstart_S1(data) + + # Formulas for mapping parameters in S1 parameterization to + # those in S0 parameterization can be found in [NO]. Note that + # only delta changes. + if alpha != 1: + delta0 = delta1 + beta * gamma * np.tan(np.pi * alpha / 2.0) + else: + delta0 = delta1 + 2 * beta * gamma * np.log(gamma) / np.pi + + return alpha, beta, delta0, gamma + + +def _fitstart_S1(data): + # We follow McCullock 1986 method - Simple Consistent Estimators + # of Stable Distribution Parameters + + # fmt: off + # Table III and IV + nu_alpha_range = [2.439, 2.5, 2.6, 2.7, 2.8, 3, 3.2, 3.5, 4, + 5, 6, 8, 10, 15, 25] + nu_beta_range = [0, 0.1, 0.2, 0.3, 0.5, 0.7, 1] + + # table III - alpha = psi_1(nu_alpha, nu_beta) + alpha_table = np.array([ + [2.000, 2.000, 2.000, 2.000, 2.000, 2.000, 2.000], + [1.916, 1.924, 1.924, 1.924, 1.924, 1.924, 1.924], + [1.808, 1.813, 1.829, 1.829, 1.829, 1.829, 1.829], + [1.729, 1.730, 1.737, 1.745, 1.745, 1.745, 1.745], + [1.664, 1.663, 1.663, 1.668, 1.676, 1.676, 1.676], + [1.563, 1.560, 1.553, 1.548, 1.547, 1.547, 1.547], + [1.484, 1.480, 1.471, 1.460, 1.448, 1.438, 1.438], + [1.391, 1.386, 1.378, 1.364, 1.337, 1.318, 1.318], + [1.279, 1.273, 1.266, 1.250, 1.210, 1.184, 1.150], + [1.128, 1.121, 1.114, 1.101, 1.067, 1.027, 0.973], + [1.029, 1.021, 1.014, 1.004, 0.974, 0.935, 0.874], + [0.896, 0.892, 0.884, 0.883, 0.855, 0.823, 0.769], + [0.818, 0.812, 0.806, 0.801, 0.780, 0.756, 0.691], + [0.698, 0.695, 0.692, 0.689, 0.676, 0.656, 0.597], + [0.593, 0.590, 0.588, 0.586, 0.579, 0.563, 0.513]]).T + # transpose because interpolation with `RectBivariateSpline` is with + # `nu_beta` as `x` and `nu_alpha` as `y` + + # table IV - beta = psi_2(nu_alpha, nu_beta) + beta_table = np.array([ + [0, 2.160, 1.000, 1.000, 1.000, 1.000, 1.000], + [0, 1.592, 3.390, 1.000, 1.000, 1.000, 1.000], + [0, 0.759, 1.800, 1.000, 1.000, 1.000, 1.000], + [0, 0.482, 1.048, 1.694, 1.000, 1.000, 1.000], + [0, 0.360, 0.760, 1.232, 2.229, 1.000, 1.000], + [0, 0.253, 0.518, 0.823, 1.575, 1.000, 1.000], + [0, 0.203, 0.410, 0.632, 1.244, 1.906, 1.000], + [0, 0.165, 0.332, 0.499, 0.943, 1.560, 1.000], + [0, 0.136, 0.271, 0.404, 0.689, 1.230, 2.195], + [0, 0.109, 0.216, 0.323, 0.539, 0.827, 1.917], + [0, 0.096, 0.190, 0.284, 0.472, 0.693, 1.759], + [0, 0.082, 0.163, 0.243, 0.412, 0.601, 1.596], + [0, 0.074, 0.147, 0.220, 0.377, 0.546, 1.482], + [0, 0.064, 0.128, 0.191, 0.330, 0.478, 1.362], + [0, 0.056, 0.112, 0.167, 0.285, 0.428, 1.274]]).T + + # Table V and VII + # These are ordered with decreasing `alpha_range`; so we will need to + # reverse them as required by RectBivariateSpline. + alpha_range = [2, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1, + 1, 0.9, 0.8, 0.7, 0.6, 0.5][::-1] + beta_range = [0, 0.25, 0.5, 0.75, 1] + + # Table V - nu_c = psi_3(alpha, beta) + nu_c_table = np.array([ + [1.908, 1.908, 1.908, 1.908, 1.908], + [1.914, 1.915, 1.916, 1.918, 1.921], + [1.921, 1.922, 1.927, 1.936, 1.947], + [1.927, 1.930, 1.943, 1.961, 1.987], + [1.933, 1.940, 1.962, 1.997, 2.043], + [1.939, 1.952, 1.988, 2.045, 2.116], + [1.946, 1.967, 2.022, 2.106, 2.211], + [1.955, 1.984, 2.067, 2.188, 2.333], + [1.965, 2.007, 2.125, 2.294, 2.491], + [1.980, 2.040, 2.205, 2.435, 2.696], + [2.000, 2.085, 2.311, 2.624, 2.973], + [2.040, 2.149, 2.461, 2.886, 3.356], + [2.098, 2.244, 2.676, 3.265, 3.912], + [2.189, 2.392, 3.004, 3.844, 4.775], + [2.337, 2.634, 3.542, 4.808, 6.247], + [2.588, 3.073, 4.534, 6.636, 9.144]])[::-1].T + # transpose because interpolation with `RectBivariateSpline` is with + # `beta` as `x` and `alpha` as `y` + + # Table VII - nu_zeta = psi_5(alpha, beta) + nu_zeta_table = np.array([ + [0, 0.000, 0.000, 0.000, 0.000], + [0, -0.017, -0.032, -0.049, -0.064], + [0, -0.030, -0.061, -0.092, -0.123], + [0, -0.043, -0.088, -0.132, -0.179], + [0, -0.056, -0.111, -0.170, -0.232], + [0, -0.066, -0.134, -0.206, -0.283], + [0, -0.075, -0.154, -0.241, -0.335], + [0, -0.084, -0.173, -0.276, -0.390], + [0, -0.090, -0.192, -0.310, -0.447], + [0, -0.095, -0.208, -0.346, -0.508], + [0, -0.098, -0.223, -0.380, -0.576], + [0, -0.099, -0.237, -0.424, -0.652], + [0, -0.096, -0.250, -0.469, -0.742], + [0, -0.089, -0.262, -0.520, -0.853], + [0, -0.078, -0.272, -0.581, -0.997], + [0, -0.061, -0.279, -0.659, -1.198]])[::-1].T + # fmt: on + + psi_1 = RectBivariateSpline(nu_beta_range, nu_alpha_range, + alpha_table, kx=1, ky=1, s=0) + + def psi_1_1(nu_beta, nu_alpha): + return psi_1(nu_beta, nu_alpha) \ + if nu_beta > 0 else psi_1(-nu_beta, nu_alpha) + + psi_2 = RectBivariateSpline(nu_beta_range, nu_alpha_range, + beta_table, kx=1, ky=1, s=0) + + def psi_2_1(nu_beta, nu_alpha): + return psi_2(nu_beta, nu_alpha) \ + if nu_beta > 0 else -psi_2(-nu_beta, nu_alpha) + + phi_3 = RectBivariateSpline(beta_range, alpha_range, nu_c_table, + kx=1, ky=1, s=0) + + def phi_3_1(beta, alpha): + return phi_3(beta, alpha) if beta > 0 else phi_3(-beta, alpha) + + phi_5 = RectBivariateSpline(beta_range, alpha_range, nu_zeta_table, + kx=1, ky=1, s=0) + + def phi_5_1(beta, alpha): + return phi_5(beta, alpha) if beta > 0 else -phi_5(-beta, alpha) + + # quantiles + p05 = np.percentile(data, 5) + p50 = np.percentile(data, 50) + p95 = np.percentile(data, 95) + p25 = np.percentile(data, 25) + p75 = np.percentile(data, 75) + + nu_alpha = (p95 - p05) / (p75 - p25) + nu_beta = (p95 + p05 - 2 * p50) / (p95 - p05) + + if nu_alpha >= 2.439: + eps = np.finfo(float).eps + alpha = np.clip(psi_1_1(nu_beta, nu_alpha)[0, 0], eps, 2.) + beta = np.clip(psi_2_1(nu_beta, nu_alpha)[0, 0], -1.0, 1.0) + else: + alpha = 2.0 + beta = np.sign(nu_beta) + c = (p75 - p25) / phi_3_1(beta, alpha)[0, 0] + zeta = p50 + c * phi_5_1(beta, alpha)[0, 0] + delta = zeta-beta*c*np.tan(np.pi*alpha/2.) if alpha != 1. else zeta + + return (alpha, beta, delta, c) + + +class levy_stable_gen(rv_continuous): + r"""A Levy-stable continuous random variable. + + %(before_notes)s + + See Also + -------- + levy, levy_l, cauchy, norm + + Notes + ----- + The distribution for `levy_stable` has characteristic function: + + .. math:: + + \varphi(t, \alpha, \beta, c, \mu) = + e^{it\mu -|ct|^{\alpha}(1-i\beta\operatorname{sign}(t)\Phi(\alpha, t))} + + where two different parameterizations are supported. The first :math:`S_1`: + + .. math:: + + \Phi = \begin{cases} + \tan \left({\frac {\pi \alpha }{2}}\right)&\alpha \neq 1\\ + -{\frac {2}{\pi }}\log |t|&\alpha =1 + \end{cases} + + The second :math:`S_0`: + + .. math:: + + \Phi = \begin{cases} + -\tan \left({\frac {\pi \alpha }{2}}\right)(|ct|^{1-\alpha}-1) + &\alpha \neq 1\\ + -{\frac {2}{\pi }}\log |ct|&\alpha =1 + \end{cases} + + + The probability density function for `levy_stable` is: + + .. math:: + + f(x) = \frac{1}{2\pi}\int_{-\infty}^\infty \varphi(t)e^{-ixt}\,dt + + where :math:`-\infty < t < \infty`. This integral does not have a known + closed form. + + `levy_stable` generalizes several distributions. Where possible, they + should be used instead. Specifically, when the shape parameters + assume the values in the table below, the corresponding equivalent + distribution should be used. + + ========= ======== =========== + ``alpha`` ``beta`` Equivalent + ========= ======== =========== + 1/2 -1 `levy_l` + 1/2 1 `levy` + 1 0 `cauchy` + 2 any `norm` (with ``scale=sqrt(2)``) + ========= ======== =========== + + Evaluation of the pdf uses Nolan's piecewise integration approach with the + Zolotarev :math:`M` parameterization by default. There is also the option + to use direct numerical integration of the standard parameterization of the + characteristic function or to evaluate by taking the FFT of the + characteristic function. + + The default method can changed by setting the class variable + ``levy_stable.pdf_default_method`` to one of 'piecewise' for Nolan's + approach, 'dni' for direct numerical integration, or 'fft-simpson' for the + FFT based approach. For the sake of backwards compatibility, the methods + 'best' and 'zolotarev' are equivalent to 'piecewise' and the method + 'quadrature' is equivalent to 'dni'. + + The parameterization can be changed by setting the class variable + ``levy_stable.parameterization`` to either 'S0' or 'S1'. + The default is 'S1'. + + To improve performance of piecewise and direct numerical integration one + can specify ``levy_stable.quad_eps`` (defaults to 1.2e-14). This is used + as both the absolute and relative quadrature tolerance for direct numerical + integration and as the relative quadrature tolerance for the piecewise + method. One can also specify ``levy_stable.piecewise_x_tol_near_zeta`` + (defaults to 0.005) for how close x is to zeta before it is considered the + same as x [NO]. The exact check is + ``abs(x0 - zeta) < piecewise_x_tol_near_zeta*alpha**(1/alpha)``. One can + also specify ``levy_stable.piecewise_alpha_tol_near_one`` (defaults to + 0.005) for how close alpha is to 1 before being considered equal to 1. + + To increase accuracy of FFT calculation one can specify + ``levy_stable.pdf_fft_grid_spacing`` (defaults to 0.001) and + ``pdf_fft_n_points_two_power`` (defaults to None which means a value is + calculated that sufficiently covers the input range). + + Further control over FFT calculation is available by setting + ``pdf_fft_interpolation_degree`` (defaults to 3) for spline order and + ``pdf_fft_interpolation_level`` for determining the number of points to use + in the Newton-Cotes formula when approximating the characteristic function + (considered experimental). + + Evaluation of the cdf uses Nolan's piecewise integration approach with the + Zolatarev :math:`S_0` parameterization by default. There is also the option + to evaluate through integration of an interpolated spline of the pdf + calculated by means of the FFT method. The settings affecting FFT + calculation are the same as for pdf calculation. The default cdf method can + be changed by setting ``levy_stable.cdf_default_method`` to either + 'piecewise' or 'fft-simpson'. For cdf calculations the Zolatarev method is + superior in accuracy, so FFT is disabled by default. + + Fitting estimate uses quantile estimation method in [MC]. MLE estimation of + parameters in fit method uses this quantile estimate initially. Note that + MLE doesn't always converge if using FFT for pdf calculations; this will be + the case if alpha <= 1 where the FFT approach doesn't give good + approximations. + + Any non-missing value for the attribute + ``levy_stable.pdf_fft_min_points_threshold`` will set + ``levy_stable.pdf_default_method`` to 'fft-simpson' if a valid + default method is not otherwise set. + + + + .. warning:: + + For pdf calculations FFT calculation is considered experimental. + + For cdf calculations FFT calculation is considered experimental. Use + Zolatarev's method instead (default). + + The probability density above is defined in the "standardized" form. To + shift and/or scale the distribution use the ``loc`` and ``scale`` + parameters. + Generally ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically + equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with + ``y = (x - loc) / scale``, except in the ``S1`` parameterization if + ``alpha == 1``. In that case ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` + is identically equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with + ``y = (x - loc - 2 * beta * scale * np.log(scale) / np.pi) / scale``. + See [NO2]_ Definition 1.8 for more information. + Note that shifting the location of a distribution + does not make it a "noncentral" distribution. + + References + ---------- + .. [MC] McCulloch, J., 1986. Simple consistent estimators of stable + distribution parameters. Communications in Statistics - Simulation and + Computation 15, 11091136. + .. [WZ] Wang, Li and Zhang, Ji-Hong, 2008. Simpson's rule based FFT method + to compute densities of stable distribution. + .. [NO] Nolan, J., 1997. Numerical Calculation of Stable Densities and + distributions Functions. + .. [NO2] Nolan, J., 2018. Stable Distributions: Models for Heavy Tailed + Data. + .. [HO] Hopcraft, K. I., Jakeman, E., Tanner, R. M. J., 1999. Lévy random + walks with fluctuating step number and multiscale behavior. + + %(example)s + + """ + # Configurable options as class variables + # (accessible from self by attribute lookup). + parameterization = "S1" + pdf_default_method = "piecewise" + cdf_default_method = "piecewise" + quad_eps = _QUAD_EPS + piecewise_x_tol_near_zeta = 0.005 + piecewise_alpha_tol_near_one = 0.005 + pdf_fft_min_points_threshold = None + pdf_fft_grid_spacing = 0.001 + pdf_fft_n_points_two_power = None + pdf_fft_interpolation_level = 3 + pdf_fft_interpolation_degree = 3 + + def __call__(self, *args, **params): + dist = levy_stable_frozen(self, *args, **params) + dist.parameterization = self.parameterization + return dist + + def _argcheck(self, alpha, beta): + return (alpha > 0) & (alpha <= 2) & (beta <= 1) & (beta >= -1) + + def _shape_info(self): + ialpha = _ShapeInfo("alpha", False, (0, 2), (False, True)) + ibeta = _ShapeInfo("beta", False, (-1, 1), (True, True)) + return [ialpha, ibeta] + + def _parameterization(self): + allowed = ("S0", "S1") + pz = self.parameterization + if pz not in allowed: + raise RuntimeError( + f"Parameterization '{pz}' in supported list: {allowed}" + ) + return pz + + @inherit_docstring_from(rv_continuous) + def rvs(self, *args, **kwds): + X1 = super().rvs(*args, **kwds) + + kwds.pop("discrete", None) + kwds.pop("random_state", None) + (alpha, beta), delta, gamma, size = self._parse_args_rvs(*args, **kwds) + + # shift location for this parameterisation (S1) + X1 = np.where( + alpha == 1.0, X1 + 2 * beta * gamma * np.log(gamma) / np.pi, X1 + ) + + if self._parameterization() == "S0": + return np.where( + alpha == 1.0, + X1 - (beta * 2 * gamma * np.log(gamma) / np.pi), + X1 - gamma * beta * np.tan(np.pi * alpha / 2.0), + ) + elif self._parameterization() == "S1": + return X1 + + def _rvs(self, alpha, beta, size=None, random_state=None): + return _rvs_Z1(alpha, beta, size, random_state) + + @inherit_docstring_from(rv_continuous) + def pdf(self, x, *args, **kwds): + # override base class version to correct + # location for S1 parameterization + if self._parameterization() == "S0": + return super().pdf(x, *args, **kwds) + elif self._parameterization() == "S1": + (alpha, beta), delta, gamma = self._parse_args(*args, **kwds) + if np.all(np.reshape(alpha, (1, -1))[0, :] != 1): + return super().pdf(x, *args, **kwds) + else: + # correct location for this parameterisation + x = np.reshape(x, (1, -1))[0, :] + x, alpha, beta = np.broadcast_arrays(x, alpha, beta) + + data_in = np.dstack((x, alpha, beta))[0] + data_out = np.empty(shape=(len(data_in), 1)) + # group data in unique arrays of alpha, beta pairs + uniq_param_pairs = np.unique(data_in[:, 1:], axis=0) + for pair in uniq_param_pairs: + _alpha, _beta = pair + _delta = ( + delta + 2 * _beta * gamma * np.log(gamma) / np.pi + if _alpha == 1.0 + else delta + ) + data_mask = np.all(data_in[:, 1:] == pair, axis=-1) + _x = data_in[data_mask, 0] + data_out[data_mask] = ( + super() + .pdf(_x, _alpha, _beta, loc=_delta, scale=gamma) + .reshape(len(_x), 1) + ) + output = data_out.T[0] + if output.shape == (1,): + return output[0] + return output + + def _pdf(self, x, alpha, beta): + if self._parameterization() == "S0": + _pdf_single_value_piecewise = _pdf_single_value_piecewise_Z0 + _pdf_single_value_cf_integrate = _pdf_single_value_cf_integrate_Z0 + _cf = _cf_Z0 + elif self._parameterization() == "S1": + _pdf_single_value_piecewise = _pdf_single_value_piecewise_Z1 + _pdf_single_value_cf_integrate = _pdf_single_value_cf_integrate_Z1 + _cf = _cf_Z1 + + x = np.asarray(x).reshape(1, -1)[0, :] + + x, alpha, beta = np.broadcast_arrays(x, alpha, beta) + + data_in = np.dstack((x, alpha, beta))[0] + data_out = np.empty(shape=(len(data_in), 1)) + + pdf_default_method_name = self.pdf_default_method + if pdf_default_method_name in ("piecewise", "best", "zolotarev"): + pdf_single_value_method = _pdf_single_value_piecewise + elif pdf_default_method_name in ("dni", "quadrature"): + pdf_single_value_method = _pdf_single_value_cf_integrate + elif ( + pdf_default_method_name == "fft-simpson" + or self.pdf_fft_min_points_threshold is not None + ): + pdf_single_value_method = None + + pdf_single_value_kwds = { + "quad_eps": self.quad_eps, + "piecewise_x_tol_near_zeta": self.piecewise_x_tol_near_zeta, + "piecewise_alpha_tol_near_one": self.piecewise_alpha_tol_near_one, + } + + fft_grid_spacing = self.pdf_fft_grid_spacing + fft_n_points_two_power = self.pdf_fft_n_points_two_power + fft_interpolation_level = self.pdf_fft_interpolation_level + fft_interpolation_degree = self.pdf_fft_interpolation_degree + + # group data in unique arrays of alpha, beta pairs + uniq_param_pairs = np.unique(data_in[:, 1:], axis=0) + for pair in uniq_param_pairs: + data_mask = np.all(data_in[:, 1:] == pair, axis=-1) + data_subset = data_in[data_mask] + if pdf_single_value_method is not None: + data_out[data_mask] = np.array( + [ + pdf_single_value_method( + _x, _alpha, _beta, **pdf_single_value_kwds + ) + for _x, _alpha, _beta in data_subset + ] + ).reshape(len(data_subset), 1) + else: + warnings.warn( + "Density calculations experimental for FFT method." + + " Use combination of piecewise and dni methods instead.", + RuntimeWarning, stacklevel=3, + ) + _alpha, _beta = pair + _x = data_subset[:, (0,)] + + if _alpha < 1.0: + raise RuntimeError( + "FFT method does not work well for alpha less than 1." + ) + + # need enough points to "cover" _x for interpolation + if fft_grid_spacing is None and fft_n_points_two_power is None: + raise ValueError( + "One of fft_grid_spacing or fft_n_points_two_power " + + "needs to be set." + ) + max_abs_x = np.max(np.abs(_x)) + h = ( + 2 ** (3 - fft_n_points_two_power) * max_abs_x + if fft_grid_spacing is None + else fft_grid_spacing + ) + q = ( + np.ceil(np.log(2 * max_abs_x / h) / np.log(2)) + 2 + if fft_n_points_two_power is None + else int(fft_n_points_two_power) + ) + + # for some parameters, the range of x can be quite + # large, let's choose an arbitrary cut off (8GB) to save on + # computer memory. + MAX_Q = 30 + if q > MAX_Q: + raise RuntimeError( + "fft_n_points_two_power has a maximum " + + f"value of {MAX_Q}" + ) + + density_x, density = pdf_from_cf_with_fft( + lambda t: _cf(t, _alpha, _beta), + h=h, + q=q, + level=fft_interpolation_level, + ) + f = interpolate.InterpolatedUnivariateSpline( + density_x, np.real(density), k=fft_interpolation_degree + ) # patch FFT to use cubic + data_out[data_mask] = f(_x) + + return data_out.T[0] + + @inherit_docstring_from(rv_continuous) + def cdf(self, x, *args, **kwds): + # override base class version to correct + # location for S1 parameterization + # NOTE: this is near identical to pdf() above + if self._parameterization() == "S0": + return super().cdf(x, *args, **kwds) + elif self._parameterization() == "S1": + (alpha, beta), delta, gamma = self._parse_args(*args, **kwds) + if np.all(np.reshape(alpha, (1, -1))[0, :] != 1): + return super().cdf(x, *args, **kwds) + else: + # correct location for this parameterisation + x = np.reshape(x, (1, -1))[0, :] + x, alpha, beta = np.broadcast_arrays(x, alpha, beta) + + data_in = np.dstack((x, alpha, beta))[0] + data_out = np.empty(shape=(len(data_in), 1)) + # group data in unique arrays of alpha, beta pairs + uniq_param_pairs = np.unique(data_in[:, 1:], axis=0) + for pair in uniq_param_pairs: + _alpha, _beta = pair + _delta = ( + delta + 2 * _beta * gamma * np.log(gamma) / np.pi + if _alpha == 1.0 + else delta + ) + data_mask = np.all(data_in[:, 1:] == pair, axis=-1) + _x = data_in[data_mask, 0] + data_out[data_mask] = ( + super() + .cdf(_x, _alpha, _beta, loc=_delta, scale=gamma) + .reshape(len(_x), 1) + ) + output = data_out.T[0] + if output.shape == (1,): + return output[0] + return output + + def _cdf(self, x, alpha, beta): + if self._parameterization() == "S0": + _cdf_single_value_piecewise = _cdf_single_value_piecewise_Z0 + _cf = _cf_Z0 + elif self._parameterization() == "S1": + _cdf_single_value_piecewise = _cdf_single_value_piecewise_Z1 + _cf = _cf_Z1 + + x = np.asarray(x).reshape(1, -1)[0, :] + + x, alpha, beta = np.broadcast_arrays(x, alpha, beta) + + data_in = np.dstack((x, alpha, beta))[0] + data_out = np.empty(shape=(len(data_in), 1)) + + cdf_default_method_name = self.cdf_default_method + if cdf_default_method_name == "piecewise": + cdf_single_value_method = _cdf_single_value_piecewise + elif cdf_default_method_name == "fft-simpson": + cdf_single_value_method = None + + cdf_single_value_kwds = { + "quad_eps": self.quad_eps, + "piecewise_x_tol_near_zeta": self.piecewise_x_tol_near_zeta, + "piecewise_alpha_tol_near_one": self.piecewise_alpha_tol_near_one, + } + + fft_grid_spacing = self.pdf_fft_grid_spacing + fft_n_points_two_power = self.pdf_fft_n_points_two_power + fft_interpolation_level = self.pdf_fft_interpolation_level + fft_interpolation_degree = self.pdf_fft_interpolation_degree + + # group data in unique arrays of alpha, beta pairs + uniq_param_pairs = np.unique(data_in[:, 1:], axis=0) + for pair in uniq_param_pairs: + data_mask = np.all(data_in[:, 1:] == pair, axis=-1) + data_subset = data_in[data_mask] + if cdf_single_value_method is not None: + data_out[data_mask] = np.array( + [ + cdf_single_value_method( + _x, _alpha, _beta, **cdf_single_value_kwds + ) + for _x, _alpha, _beta in data_subset + ] + ).reshape(len(data_subset), 1) + else: + warnings.warn( + "Cumulative density calculations experimental for FFT" + + " method. Use piecewise method instead.", + RuntimeWarning, stacklevel=3, + ) + _alpha, _beta = pair + _x = data_subset[:, (0,)] + + # need enough points to "cover" _x for interpolation + if fft_grid_spacing is None and fft_n_points_two_power is None: + raise ValueError( + "One of fft_grid_spacing or fft_n_points_two_power " + + "needs to be set." + ) + max_abs_x = np.max(np.abs(_x)) + h = ( + 2 ** (3 - fft_n_points_two_power) * max_abs_x + if fft_grid_spacing is None + else fft_grid_spacing + ) + q = ( + np.ceil(np.log(2 * max_abs_x / h) / np.log(2)) + 2 + if fft_n_points_two_power is None + else int(fft_n_points_two_power) + ) + + density_x, density = pdf_from_cf_with_fft( + lambda t: _cf(t, _alpha, _beta), + h=h, + q=q, + level=fft_interpolation_level, + ) + f = interpolate.InterpolatedUnivariateSpline( + density_x, np.real(density), k=fft_interpolation_degree + ) + data_out[data_mask] = np.array( + [f.integral(self.a, float(x_1.squeeze())) for x_1 in _x] + ).reshape(data_out[data_mask].shape) + + return data_out.T[0] + + def _fitstart(self, data): + if self._parameterization() == "S0": + _fitstart = _fitstart_S0 + elif self._parameterization() == "S1": + _fitstart = _fitstart_S1 + return _fitstart(data) + + def _stats(self, alpha, beta): + mu = 0 if alpha > 1 else np.nan + mu2 = 2 if alpha == 2 else np.inf + g1 = 0.0 if alpha == 2.0 else np.nan + g2 = 0.0 if alpha == 2.0 else np.nan + return mu, mu2, g1, g2 + + +# cotes numbers - see sequence from http://oeis.org/A100642 +Cotes_table = np.array( + [[], [1]] + [v[2] for v in _builtincoeffs.values()], dtype=object +) +Cotes = np.array( + [ + np.pad(r, (0, len(Cotes_table) - 1 - len(r)), mode='constant') + for r in Cotes_table + ] +) + + +def pdf_from_cf_with_fft(cf, h=0.01, q=9, level=3): + """Calculates pdf from characteristic function. + + Uses fast Fourier transform with Newton-Cotes integration following [WZ]. + Defaults to using Simpson's method (3-point Newton-Cotes integration). + + Parameters + ---------- + cf : callable + Single argument function from float -> complex expressing a + characteristic function for some distribution. + h : Optional[float] + Step size for Newton-Cotes integration. Default: 0.01 + q : Optional[int] + Use 2**q steps when performing Newton-Cotes integration. + The infinite integral in the inverse Fourier transform will then + be restricted to the interval [-2**q * h / 2, 2**q * h / 2]. Setting + the number of steps equal to a power of 2 allows the fft to be + calculated in O(n*log(n)) time rather than O(n**2). + Default: 9 + level : Optional[int] + Calculate integral using n-point Newton-Cotes integration for + n = level. The 3-point Newton-Cotes formula corresponds to Simpson's + rule. Default: 3 + + Returns + ------- + x_l : ndarray + Array of points x at which pdf is estimated. 2**q equally spaced + points from -pi/h up to but not including pi/h. + density : ndarray + Estimated values of pdf corresponding to cf at points in x_l. + + References + ---------- + .. [WZ] Wang, Li and Zhang, Ji-Hong, 2008. Simpson's rule based FFT method + to compute densities of stable distribution. + """ + n = level + N = 2**q + steps = np.arange(0, N) + L = N * h / 2 + x_l = np.pi * (steps - N / 2) / L + if level > 1: + indices = np.arange(n).reshape(n, 1) + s1 = np.sum( + (-1) ** steps * Cotes[n, indices] * np.fft.fft( + (-1)**steps * cf(-L + h * steps + h * indices / (n - 1)) + ) * np.exp( + 1j * np.pi * indices / (n - 1) + - 2 * 1j * np.pi * indices * steps / + (N * (n - 1)) + ), + axis=0 + ) + else: + s1 = (-1) ** steps * Cotes[n, 0] * np.fft.fft( + (-1) ** steps * cf(-L + h * steps) + ) + density = h * s1 / (2 * np.pi * np.sum(Cotes[n])) + return (x_l, density) + + +levy_stable = levy_stable_gen(name="levy_stable") + + +class levy_stable_frozen(rv_continuous_frozen): + @property + def parameterization(self): + return self.dist.parameterization + + @parameterization.setter + def parameterization(self, value): + self.dist.parameterization = value diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbafdb8177437df3b0cc8d932eb5bcdb9a53f7c6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8707fa7b505a9f3a08c963acea727c15d56b175e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mannwhitneyu.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mannwhitneyu.py new file mode 100644 index 0000000000000000000000000000000000000000..a0ab9a427fe78845c880992235a40e034fe7f2dd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mannwhitneyu.py @@ -0,0 +1,492 @@ +import threading +import numpy as np +from collections import namedtuple +from scipy import special +from scipy import stats +from scipy.stats._stats_py import _rankdata +from ._axis_nan_policy import _axis_nan_policy_factory + + +def _broadcast_concatenate(x, y, axis): + '''Broadcast then concatenate arrays, leaving concatenation axis last''' + x = np.moveaxis(x, axis, -1) + y = np.moveaxis(y, axis, -1) + z = np.broadcast(x[..., 0], y[..., 0]) + x = np.broadcast_to(x, z.shape + (x.shape[-1],)) + y = np.broadcast_to(y, z.shape + (y.shape[-1],)) + z = np.concatenate((x, y), axis=-1) + return x, y, z + + +class _MWU: + '''Distribution of MWU statistic under the null hypothesis''' + + def __init__(self, n1, n2): + self._reset(n1, n2) + + def set_shapes(self, n1, n2): + n1, n2 = min(n1, n2), max(n1, n2) + if (n1, n2) == (self.n1, self.n2): + return + + self.n1 = n1 + self.n2 = n2 + self.s_array = np.zeros(0, dtype=int) + self.configurations = np.zeros(0, dtype=np.uint64) + + def reset(self): + self._reset(self.n1, self.n2) + + def _reset(self, n1, n2): + self.n1 = None + self.n2 = None + self.set_shapes(n1, n2) + + def pmf(self, k): + + # In practice, `pmf` is never called with k > m*n/2. + # If it were, we'd exploit symmetry here: + # k = np.array(k, copy=True) + # k2 = m*n - k + # i = k2 < k + # k[i] = k2[i] + + pmfs = self.build_u_freqs_array(np.max(k)) + return pmfs[k] + + def cdf(self, k): + '''Cumulative distribution function''' + + # In practice, `cdf` is never called with k > m*n/2. + # If it were, we'd exploit symmetry here rather than in `sf` + pmfs = self.build_u_freqs_array(np.max(k)) + cdfs = np.cumsum(pmfs) + return cdfs[k] + + def sf(self, k): + '''Survival function''' + # Note that both CDF and SF include the PMF at k. The p-value is + # calculated from the SF and should include the mass at k, so this + # is desirable + + # Use the fact that the distribution is symmetric and sum from the left + kc = np.asarray(self.n1*self.n2 - k) # complement of k + i = k < kc + if np.any(i): + kc[i] = k[i] + cdfs = np.asarray(self.cdf(kc)) + cdfs[i] = 1. - cdfs[i] + self.pmf(kc[i]) + else: + cdfs = np.asarray(self.cdf(kc)) + return cdfs[()] + + # build_sigma_array and build_u_freqs_array adapted from code + # by @toobaz with permission. Thanks to @andreasloe for the suggestion. + # See https://github.com/scipy/scipy/pull/4933#issuecomment-1898082691 + def build_sigma_array(self, a): + n1, n2 = self.n1, self.n2 + if a + 1 <= self.s_array.size: + return self.s_array[1:a+1] + + s_array = np.zeros(a + 1, dtype=int) + + for d in np.arange(1, n1 + 1): + # All multiples of d, except 0: + indices = np.arange(d, a + 1, d) + # \epsilon_d = 1: + s_array[indices] += d + + for d in np.arange(n2 + 1, n2 + n1 + 1): + # All multiples of d, except 0: + indices = np.arange(d, a + 1, d) + # \epsilon_d = -1: + s_array[indices] -= d + + # We don't need 0: + self.s_array = s_array + return s_array[1:] + + def build_u_freqs_array(self, maxu): + """ + Build all the array of frequencies for u from 0 to maxu. + Assumptions: + n1 <= n2 + maxu <= n1 * n2 / 2 + """ + n1, n2 = self.n1, self.n2 + total = special.binom(n1 + n2, n1) + + if maxu + 1 <= self.configurations.size: + return self.configurations[:maxu + 1] / total + + s_array = self.build_sigma_array(maxu) + + # Start working with ints, for maximum precision and efficiency: + configurations = np.zeros(maxu + 1, dtype=np.uint64) + configurations_is_uint = True + uint_max = np.iinfo(np.uint64).max + # How many ways to have U=0? 1 + configurations[0] = 1 + + for u in np.arange(1, maxu + 1): + coeffs = s_array[u - 1::-1] + new_val = np.dot(configurations[:u], coeffs) / u + if new_val > uint_max and configurations_is_uint: + # OK, we got into numbers too big for uint64. + # So now we start working with floats. + # By doing this since the beginning, we would have lost precision. + # (And working on python long ints would be unbearably slow) + configurations = configurations.astype(float) + configurations_is_uint = False + configurations[u] = new_val + + self.configurations = configurations + return configurations / total + + +# Maintain state for faster repeat calls to `mannwhitneyu`. +# _MWU() is calculated once per thread and stored as an attribute on +# this thread-local variable inside mannwhitneyu(). +_mwu_state = threading.local() + + +def _get_mwu_z(U, n1, n2, t, axis=0, continuity=True): + '''Standardized MWU statistic''' + # Follows mannwhitneyu [2] + mu = n1 * n2 / 2 + n = n1 + n2 + + # Tie correction according to [2], "Normal approximation and tie correction" + # "A more computationally-efficient form..." + tie_term = (t**3 - t).sum(axis=-1) + s = np.sqrt(n1*n2/12 * ((n + 1) - tie_term/(n*(n-1)))) + + numerator = U - mu + + # Continuity correction. + # Because SF is always used to calculate the p-value, we can always + # _subtract_ 0.5 for the continuity correction. This always increases the + # p-value to account for the rest of the probability mass _at_ q = U. + if continuity: + numerator -= 0.5 + + # no problem evaluating the norm SF at an infinity + with np.errstate(divide='ignore', invalid='ignore'): + z = numerator / s + return z + + +def _mwu_input_validation(x, y, use_continuity, alternative, axis, method): + ''' Input validation and standardization for mannwhitneyu ''' + # Would use np.asarray_chkfinite, but infs are OK + x, y = np.atleast_1d(x), np.atleast_1d(y) + if np.isnan(x).any() or np.isnan(y).any(): + raise ValueError('`x` and `y` must not contain NaNs.') + if np.size(x) == 0 or np.size(y) == 0: + raise ValueError('`x` and `y` must be of nonzero size.') + + bools = {True, False} + if use_continuity not in bools: + raise ValueError(f'`use_continuity` must be one of {bools}.') + + alternatives = {"two-sided", "less", "greater"} + alternative = alternative.lower() + if alternative not in alternatives: + raise ValueError(f'`alternative` must be one of {alternatives}.') + + axis_int = int(axis) + if axis != axis_int: + raise ValueError('`axis` must be an integer.') + + if not isinstance(method, stats.PermutationMethod): + methods = {"asymptotic", "exact", "auto"} + method = method.lower() + if method not in methods: + raise ValueError(f'`method` must be one of {methods}.') + + return x, y, use_continuity, alternative, axis_int, method + + +def _mwu_choose_method(n1, n2, ties): + """Choose method 'asymptotic' or 'exact' depending on input size, ties""" + + # if both inputs are large, asymptotic is OK + if n1 > 8 and n2 > 8: + return "asymptotic" + + # if there are any ties, asymptotic is preferred + if ties: + return "asymptotic" + + return "exact" + + +MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(MannwhitneyuResult, n_samples=2) +def mannwhitneyu(x, y, use_continuity=True, alternative="two-sided", + axis=0, method="auto"): + r'''Perform the Mann-Whitney U rank test on two independent samples. + + The Mann-Whitney U test is a nonparametric test of the null hypothesis + that the distribution underlying sample `x` is the same as the + distribution underlying sample `y`. It is often used as a test of + difference in location between distributions. + + Parameters + ---------- + x, y : array-like + N-d arrays of samples. The arrays must be broadcastable except along + the dimension given by `axis`. + use_continuity : bool, optional + Whether a continuity correction (1/2) should be applied. + Default is True when `method` is ``'asymptotic'``; has no effect + otherwise. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + Let *SX(u)* and *SY(u)* be the survival functions of the + distributions underlying `x` and `y`, respectively. Then the following + alternative hypotheses are available: + + * 'two-sided': the distributions are not equal, i.e. *SX(u) ≠ SY(u)* for + at least one *u*. + * 'less': the distribution underlying `x` is stochastically less + than the distribution underlying `y`, i.e. *SX(u) < SY(u)* for all *u*. + * 'greater': the distribution underlying `x` is stochastically greater + than the distribution underlying `y`, i.e. *SX(u) > SY(u)* for all *u*. + + Under a more restrictive set of assumptions, the alternative hypotheses + can be expressed in terms of the locations of the distributions; + see [5]_ section 5.1. + axis : int, optional + Axis along which to perform the test. Default is 0. + method : {'auto', 'asymptotic', 'exact'} or `PermutationMethod` instance, optional + Selects the method used to calculate the *p*-value. + Default is 'auto'. The following options are available. + + * ``'asymptotic'``: compares the standardized test statistic + against the normal distribution, correcting for ties. + * ``'exact'``: computes the exact *p*-value by comparing the observed + :math:`U` statistic against the exact distribution of the :math:`U` + statistic under the null hypothesis. No correction is made for ties. + * ``'auto'``: chooses ``'exact'`` when the size of one of the samples + is less than or equal to 8 and there are no ties; + chooses ``'asymptotic'`` otherwise. + * `PermutationMethod` instance. In this case, the p-value + is computed using `permutation_test` with the provided + configuration options and other appropriate settings. + + Returns + ------- + res : MannwhitneyuResult + An object containing attributes: + + statistic : float + The Mann-Whitney U statistic corresponding with sample `x`. See + Notes for the test statistic corresponding with sample `y`. + pvalue : float + The associated *p*-value for the chosen `alternative`. + + Notes + ----- + If ``U1`` is the statistic corresponding with sample `x`, then the + statistic corresponding with sample `y` is + ``U2 = x.shape[axis] * y.shape[axis] - U1``. + + `mannwhitneyu` is for independent samples. For related / paired samples, + consider `scipy.stats.wilcoxon`. + + `method` ``'exact'`` is recommended when there are no ties and when either + sample size is less than 8 [1]_. The implementation follows the algorithm + reported in [3]_. + Note that the exact method is *not* corrected for ties, but + `mannwhitneyu` will not raise errors or warnings if there are ties in the + data. If there are ties and either samples is small (fewer than ~10 + observations), consider passing an instance of `PermutationMethod` + as the `method` to perform a permutation test. + + The Mann-Whitney U test is a non-parametric version of the t-test for + independent samples. When the means of samples from the populations + are normally distributed, consider `scipy.stats.ttest_ind`. + + See Also + -------- + scipy.stats.wilcoxon, scipy.stats.ranksums, scipy.stats.ttest_ind + + References + ---------- + .. [1] H.B. Mann and D.R. Whitney, "On a test of whether one of two random + variables is stochastically larger than the other", The Annals of + Mathematical Statistics, Vol. 18, pp. 50-60, 1947. + .. [2] Mann-Whitney U Test, Wikipedia, + http://en.wikipedia.org/wiki/Mann-Whitney_U_test + .. [3] Andreas Löffler, + "Über eine Partition der nat. Zahlen und ihr Anwendung beim U-Test", + Wiss. Z. Univ. Halle, XXXII'83 pp. 87-89. + .. [4] Rosie Shier, "Statistics: 2.3 The Mann-Whitney U Test", Mathematics + Learning Support Centre, 2004. + .. [5] Michael P. Fay and Michael A. Proschan. "Wilcoxon-Mann-Whitney + or t-test? On assumptions for hypothesis tests and multiple \ + interpretations of decision rules." Statistics surveys, Vol. 4, pp. + 1-39, 2010. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2857732/ + + Examples + -------- + We follow the example from [4]_: nine randomly sampled young adults were + diagnosed with type II diabetes at the ages below. + + >>> males = [19, 22, 16, 29, 24] + >>> females = [20, 11, 17, 12] + + We use the Mann-Whitney U test to assess whether there is a statistically + significant difference in the diagnosis age of males and females. + The null hypothesis is that the distribution of male diagnosis ages is + the same as the distribution of female diagnosis ages. We decide + that a confidence level of 95% is required to reject the null hypothesis + in favor of the alternative that the distributions are different. + Since the number of samples is very small and there are no ties in the + data, we can compare the observed test statistic against the *exact* + distribution of the test statistic under the null hypothesis. + + >>> from scipy.stats import mannwhitneyu + >>> U1, p = mannwhitneyu(males, females, method="exact") + >>> print(U1) + 17.0 + + `mannwhitneyu` always reports the statistic associated with the first + sample, which, in this case, is males. This agrees with :math:`U_M = 17` + reported in [4]_. The statistic associated with the second statistic + can be calculated: + + >>> nx, ny = len(males), len(females) + >>> U2 = nx*ny - U1 + >>> print(U2) + 3.0 + + This agrees with :math:`U_F = 3` reported in [4]_. The two-sided + *p*-value can be calculated from either statistic, and the value produced + by `mannwhitneyu` agrees with :math:`p = 0.11` reported in [4]_. + + >>> print(p) + 0.1111111111111111 + + The exact distribution of the test statistic is asymptotically normal, so + the example continues by comparing the exact *p*-value against the + *p*-value produced using the normal approximation. + + >>> _, pnorm = mannwhitneyu(males, females, method="asymptotic") + >>> print(pnorm) + 0.11134688653314041 + + Here `mannwhitneyu`'s reported *p*-value appears to conflict with the + value :math:`p = 0.09` given in [4]_. The reason is that [4]_ + does not apply the continuity correction performed by `mannwhitneyu`; + `mannwhitneyu` reduces the distance between the test statistic and the + mean :math:`\mu = n_x n_y / 2` by 0.5 to correct for the fact that the + discrete statistic is being compared against a continuous distribution. + Here, the :math:`U` statistic used is less than the mean, so we reduce + the distance by adding 0.5 in the numerator. + + >>> import numpy as np + >>> from scipy.stats import norm + >>> U = min(U1, U2) + >>> N = nx + ny + >>> z = (U - nx*ny/2 + 0.5) / np.sqrt(nx*ny * (N + 1)/ 12) + >>> p = 2 * norm.cdf(z) # use CDF to get p-value from smaller statistic + >>> print(p) + 0.11134688653314041 + + If desired, we can disable the continuity correction to get a result + that agrees with that reported in [4]_. + + >>> _, pnorm = mannwhitneyu(males, females, use_continuity=False, + ... method="asymptotic") + >>> print(pnorm) + 0.0864107329737 + + Regardless of whether we perform an exact or asymptotic test, the + probability of the test statistic being as extreme or more extreme by + chance exceeds 5%, so we do not consider the results statistically + significant. + + Suppose that, before seeing the data, we had hypothesized that females + would tend to be diagnosed at a younger age than males. + In that case, it would be natural to provide the female ages as the + first input, and we would have performed a one-sided test using + ``alternative = 'less'``: females are diagnosed at an age that is + stochastically less than that of males. + + >>> res = mannwhitneyu(females, males, alternative="less", method="exact") + >>> print(res) + MannwhitneyuResult(statistic=3.0, pvalue=0.05555555555555555) + + Again, the probability of getting a sufficiently low value of the + test statistic by chance under the null hypothesis is greater than 5%, + so we do not reject the null hypothesis in favor of our alternative. + + If it is reasonable to assume that the means of samples from the + populations are normally distributed, we could have used a t-test to + perform the analysis. + + >>> from scipy.stats import ttest_ind + >>> res = ttest_ind(females, males, alternative="less") + >>> print(res) + TtestResult(statistic=-2.239334696520584, + pvalue=0.030068441095757924, + df=7.0) + + Under this assumption, the *p*-value would be low enough to reject the + null hypothesis in favor of the alternative. + + ''' + + x, y, use_continuity, alternative, axis_int, method = ( + _mwu_input_validation(x, y, use_continuity, alternative, axis, method)) + + x, y, xy = _broadcast_concatenate(x, y, axis) + + n1, n2 = x.shape[-1], y.shape[-1] + + # Follows [2] + ranks, t = _rankdata(xy, 'average', return_ties=True) # method 2, step 1 + R1 = ranks[..., :n1].sum(axis=-1) # method 2, step 2 + U1 = R1 - n1*(n1+1)/2 # method 2, step 3 + U2 = n1 * n2 - U1 # as U1 + U2 = n1 * n2 + + if alternative == "greater": + U, f = U1, 1 # U is the statistic to use for p-value, f is a factor + elif alternative == "less": + U, f = U2, 1 # Due to symmetry, use SF of U2 rather than CDF of U1 + else: + U, f = np.maximum(U1, U2), 2 # multiply SF by two for two-sided test + + if method == "auto": + method = _mwu_choose_method(n1, n2, np.any(t > 1)) + + if method == "exact": + if not hasattr(_mwu_state, 's'): + _mwu_state.s = _MWU(0, 0) + _mwu_state.s.set_shapes(n1, n2) + p = _mwu_state.s.sf(U.astype(int)) + elif method == "asymptotic": + z = _get_mwu_z(U, n1, n2, t, continuity=use_continuity) + p = stats.norm.sf(z) + else: # `PermutationMethod` instance (already validated) + def statistic(x, y, axis): + return mannwhitneyu(x, y, use_continuity=use_continuity, + alternative=alternative, axis=axis, + method="asymptotic").statistic + + res = stats.permutation_test((x, y), statistic, axis=axis, + **method._asdict(), alternative=alternative) + p = res.pvalue + f = 1 + + p *= f + + # Ensure that test statistic is not greater than 1 + # This could happen for exact test when U = m*n/2 + p = np.clip(p, 0, 1) + + return MannwhitneyuResult(U1, p) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mgc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mgc.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec433c585146fe89a88dfe6e98888b20b886284 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mgc.py @@ -0,0 +1,550 @@ +import warnings +import numpy as np + +from scipy._lib._util import check_random_state, MapWrapper, rng_integers, _contains_nan +from scipy._lib._bunch import _make_tuple_bunch +from scipy.spatial.distance import cdist +from scipy.ndimage import _measurements + +from ._stats import _local_correlations # type: ignore[import-not-found] +from . import distributions + +__all__ = ['multiscale_graphcorr'] + +# FROM MGCPY: https://github.com/neurodata/mgcpy + + +class _ParallelP: + """Helper function to calculate parallel p-value.""" + + def __init__(self, x, y, random_states): + self.x = x + self.y = y + self.random_states = random_states + + def __call__(self, index): + order = self.random_states[index].permutation(self.y.shape[0]) + permy = self.y[order][:, order] + + # calculate permuted stats, store in null distribution + perm_stat = _mgc_stat(self.x, permy)[0] + + return perm_stat + + +def _perm_test(x, y, stat, reps=1000, workers=-1, random_state=None): + r"""Helper function that calculates the p-value. See below for uses. + + Parameters + ---------- + x, y : ndarray + `x` and `y` have shapes ``(n, p)`` and ``(n, q)``. + stat : float + The sample test statistic. + reps : int, optional + The number of replications used to estimate the null when using the + permutation test. The default is 1000 replications. + workers : int or map-like callable, optional + If `workers` is an int the population is subdivided into `workers` + sections and evaluated in parallel (uses + `multiprocessing.Pool `). Supply `-1` to use all cores + available to the Process. Alternatively supply a map-like callable, + such as `multiprocessing.Pool.map` for evaluating the population in + parallel. This evaluation is carried out as `workers(func, iterable)`. + Requires that `func` be pickleable. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Returns + ------- + pvalue : float + The sample test p-value. + null_dist : list + The approximated null distribution. + + """ + # generate seeds for each rep (change to new parallel random number + # capabilities in numpy >= 1.17+) + random_state = check_random_state(random_state) + random_states = [np.random.RandomState(rng_integers(random_state, 1 << 32, + size=4, dtype=np.uint32)) for _ in range(reps)] + + # parallelizes with specified workers over number of reps and set seeds + parallelp = _ParallelP(x=x, y=y, random_states=random_states) + with MapWrapper(workers) as mapwrapper: + null_dist = np.array(list(mapwrapper(parallelp, range(reps)))) + + # calculate p-value and significant permutation map through list + pvalue = (1 + (null_dist >= stat).sum()) / (1 + reps) + + return pvalue, null_dist + + +def _euclidean_dist(x): + return cdist(x, x) + + +MGCResult = _make_tuple_bunch('MGCResult', + ['statistic', 'pvalue', 'mgc_dict'], []) + + +def multiscale_graphcorr(x, y, compute_distance=_euclidean_dist, reps=1000, + workers=1, is_twosamp=False, random_state=None): + r"""Computes the Multiscale Graph Correlation (MGC) test statistic. + + Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for + one property (e.g. cloud density), and the :math:`l`-nearest neighbors for + the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is + called the "scale". A priori, however, it is not know which scales will be + most informative. So, MGC computes all distance pairs, and then efficiently + computes the distance correlations for all scales. The local correlations + illustrate which scales are relatively informative about the relationship. + The key, therefore, to successfully discover and decipher relationships + between disparate data modalities is to adaptively determine which scales + are the most informative, and the geometric implication for the most + informative scales. Doing so not only provides an estimate of whether the + modalities are related, but also provides insight into how the + determination was made. This is especially important in high-dimensional + data, where simple visualizations do not reveal relationships to the + unaided human eye. Characterizations of this implementation in particular + have been derived from and benchmarked within in [2]_. + + Parameters + ---------- + x, y : ndarray + If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is + the number of samples and `p` and `q` are the number of dimensions, + then the MGC independence test will be run. Alternatively, ``x`` and + ``y`` can have shapes ``(n, n)`` if they are distance or similarity + matrices, and ``compute_distance`` must be sent to ``None``. If ``x`` + and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired + two-sample MGC test will be run. + compute_distance : callable, optional + A function that computes the distance or similarity among the samples + within each data matrix. Set to ``None`` if ``x`` and ``y`` are + already distance matrices. The default uses the euclidean norm metric. + If you are calling a custom function, either create the distance + matrix before-hand or create a function of the form + ``compute_distance(x)`` where `x` is the data matrix for which + pairwise distances are calculated. + reps : int, optional + The number of replications used to estimate the null when using the + permutation test. The default is ``1000``. + workers : int or map-like callable, optional + If ``workers`` is an int the population is subdivided into ``workers`` + sections and evaluated in parallel (uses ``multiprocessing.Pool + ``). Supply ``-1`` to use all cores available to the + Process. Alternatively supply a map-like callable, such as + ``multiprocessing.Pool.map`` for evaluating the p-value in parallel. + This evaluation is carried out as ``workers(func, iterable)``. + Requires that `func` be pickleable. The default is ``1``. + is_twosamp : bool, optional + If `True`, a two sample test will be run. If ``x`` and ``y`` have + shapes ``(n, p)`` and ``(m, p)``, this optional will be overridden and + set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes + ``(n, p)`` and a two sample test is desired. The default is ``False``. + Note that this will not run if inputs are distance matrices. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Returns + ------- + res : MGCResult + An object containing attributes: + + statistic : float + The sample MGC test statistic within ``[-1, 1]``. + pvalue : float + The p-value obtained via permutation. + mgc_dict : dict + Contains additional useful results: + + - mgc_map : ndarray + A 2D representation of the latent geometry of the + relationship. + - opt_scale : (int, int) + The estimated optimal scale as a ``(x, y)`` pair. + - null_dist : list + The null distribution derived from the permuted matrices. + + See Also + -------- + pearsonr : Pearson correlation coefficient and p-value for testing + non-correlation. + kendalltau : Calculates Kendall's tau. + spearmanr : Calculates a Spearman rank-order correlation coefficient. + + Notes + ----- + A description of the process of MGC and applications on neuroscience data + can be found in [1]_. It is performed using the following steps: + + #. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and + modified to be mean zero columnwise. This results in two + :math:`n \times n` distance matrices :math:`A` and :math:`B` (the + centering and unbiased modification) [3]_. + + #. For all values :math:`k` and :math:`l` from :math:`1, ..., n`, + + * The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs + are calculated for each property. Here, :math:`G_k (i, j)` indicates + the :math:`k`-smallest values of the :math:`i`-th row of :math:`A` + and :math:`H_l (i, j)` indicates the :math:`l` smallested values of + the :math:`i`-th row of :math:`B` + + * Let :math:`\circ` denotes the entry-wise matrix product, then local + correlations are summed and normalized using the following statistic: + + .. math:: + + c^{kl} = \frac{\sum_{ij} A G_k B H_l} + {\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}} + + #. The MGC test statistic is the smoothed optimal local correlation of + :math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)` + (which essentially set all isolated large correlations) as 0 and + connected large correlations the same as before, see [3]_.) MGC is, + + .. math:: + + MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right) + \right) + + The test statistic returns a value between :math:`(-1, 1)` since it is + normalized. + + The p-value returned is calculated using a permutation test. This process + is completed by first randomly permuting :math:`y` to estimate the null + distribution and then calculating the probability of observing a test + statistic, under the null, at least as extreme as the observed test + statistic. + + MGC requires at least 5 samples to run with reliable results. It can also + handle high-dimensional data sets. + In addition, by manipulating the input data matrices, the two-sample + testing problem can be reduced to the independence testing problem [4]_. + Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n` + :math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as + follows: + + .. math:: + + X = [U | V] \in \mathcal{R}^{p \times (n + m)} + Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)} + + Then, the MGC statistic can be calculated as normal. This methodology can + be extended to similar tests such as distance correlation [4]_. + + .. versionadded:: 1.4.0 + + References + ---------- + .. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E., + Maggioni, M., & Shen, C. (2019). Discovering and deciphering + relationships across disparate data modalities. ELife. + .. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A., + Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019). + mgcpy: A Comprehensive High Dimensional Independence Testing Python + Package. :arXiv:`1907.02088` + .. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance + correlation to multiscale graph correlation. Journal of the American + Statistical Association. + .. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of + Distance and Kernel Methods for Hypothesis Testing. + :arXiv:`1806.05514` + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import multiscale_graphcorr + >>> x = np.arange(100) + >>> y = x + >>> res = multiscale_graphcorr(x, y) + >>> res.statistic, res.pvalue + (1.0, 0.001) + + To run an unpaired two-sample test, + + >>> x = np.arange(100) + >>> y = np.arange(79) + >>> res = multiscale_graphcorr(x, y) + >>> res.statistic, res.pvalue # doctest: +SKIP + (0.033258146255703246, 0.023) + + or, if shape of the inputs are the same, + + >>> x = np.arange(100) + >>> y = x + >>> res = multiscale_graphcorr(x, y, is_twosamp=True) + >>> res.statistic, res.pvalue # doctest: +SKIP + (-0.008021809890200488, 1.0) + + """ + if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray): + raise ValueError("x and y must be ndarrays") + + # convert arrays of type (n,) to (n, 1) + if x.ndim == 1: + x = x[:, np.newaxis] + elif x.ndim != 2: + raise ValueError(f"Expected a 2-D array `x`, found shape {x.shape}") + if y.ndim == 1: + y = y[:, np.newaxis] + elif y.ndim != 2: + raise ValueError(f"Expected a 2-D array `y`, found shape {y.shape}") + + nx, px = x.shape + ny, py = y.shape + + # check for NaNs + _contains_nan(x, nan_policy='raise') + _contains_nan(y, nan_policy='raise') + + # check for positive or negative infinity and raise error + if np.sum(np.isinf(x)) > 0 or np.sum(np.isinf(y)) > 0: + raise ValueError("Inputs contain infinities") + + if nx != ny: + if px == py: + # reshape x and y for two sample testing + is_twosamp = True + else: + raise ValueError("Shape mismatch, x and y must have shape [n, p] " + "and [n, q] or have shape [n, p] and [m, p].") + + if nx < 5 or ny < 5: + raise ValueError("MGC requires at least 5 samples to give reasonable " + "results.") + + # convert x and y to float + x = x.astype(np.float64) + y = y.astype(np.float64) + + # check if compute_distance_matrix if a callable() + if not callable(compute_distance) and compute_distance is not None: + raise ValueError("Compute_distance must be a function.") + + # check if number of reps exists, integer, or > 0 (if under 1000 raises + # warning) + if not isinstance(reps, int) or reps < 0: + raise ValueError("Number of reps must be an integer greater than 0.") + elif reps < 1000: + msg = ("The number of replications is low (under 1000), and p-value " + "calculations may be unreliable. Use the p-value result, with " + "caution!") + warnings.warn(msg, RuntimeWarning, stacklevel=2) + + if is_twosamp: + if compute_distance is None: + raise ValueError("Cannot run if inputs are distance matrices") + x, y = _two_sample_transform(x, y) + + if compute_distance is not None: + # compute distance matrices for x and y + x = compute_distance(x) + y = compute_distance(y) + + # calculate MGC stat + stat, stat_dict = _mgc_stat(x, y) + stat_mgc_map = stat_dict["stat_mgc_map"] + opt_scale = stat_dict["opt_scale"] + + # calculate permutation MGC p-value + pvalue, null_dist = _perm_test(x, y, stat, reps=reps, workers=workers, + random_state=random_state) + + # save all stats (other than stat/p-value) in dictionary + mgc_dict = {"mgc_map": stat_mgc_map, + "opt_scale": opt_scale, + "null_dist": null_dist} + + # create result object with alias for backward compatibility + res = MGCResult(stat, pvalue, mgc_dict) + res.stat = stat + return res + + +def _mgc_stat(distx, disty): + r"""Helper function that calculates the MGC stat. See above for use. + + Parameters + ---------- + distx, disty : ndarray + `distx` and `disty` have shapes ``(n, p)`` and ``(n, q)`` or + ``(n, n)`` and ``(n, n)`` + if distance matrices. + + Returns + ------- + stat : float + The sample MGC test statistic within ``[-1, 1]``. + stat_dict : dict + Contains additional useful additional returns containing the following + keys: + + - stat_mgc_map : ndarray + MGC-map of the statistics. + - opt_scale : (float, float) + The estimated optimal scale as a ``(x, y)`` pair. + + """ + # calculate MGC map and optimal scale + stat_mgc_map = _local_correlations(distx, disty, global_corr='mgc') + + n, m = stat_mgc_map.shape + if m == 1 or n == 1: + # the global scale at is the statistic calculated at maximal nearest + # neighbors. There is not enough local scale to search over, so + # default to global scale + stat = stat_mgc_map[m - 1][n - 1] + opt_scale = m * n + else: + samp_size = len(distx) - 1 + + # threshold to find connected region of significant local correlations + sig_connect = _threshold_mgc_map(stat_mgc_map, samp_size) + + # maximum within the significant region + stat, opt_scale = _smooth_mgc_map(sig_connect, stat_mgc_map) + + stat_dict = {"stat_mgc_map": stat_mgc_map, + "opt_scale": opt_scale} + + return stat, stat_dict + + +def _threshold_mgc_map(stat_mgc_map, samp_size): + r""" + Finds a connected region of significance in the MGC-map by thresholding. + + Parameters + ---------- + stat_mgc_map : ndarray + All local correlations within ``[-1,1]``. + samp_size : int + The sample size of original data. + + Returns + ------- + sig_connect : ndarray + A binary matrix with 1's indicating the significant region. + + """ + m, n = stat_mgc_map.shape + + # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05 + # with varying levels of performance. Threshold is based on a beta + # approximation. + per_sig = 1 - (0.02 / samp_size) # Percentile to consider as significant + threshold = samp_size * (samp_size - 3)/4 - 1/2 # Beta approximation + threshold = distributions.beta.ppf(per_sig, threshold, threshold) * 2 - 1 + + # the global scale at is the statistic calculated at maximal nearest + # neighbors. Threshold is the maximum on the global and local scales + threshold = max(threshold, stat_mgc_map[m - 1][n - 1]) + + # find the largest connected component of significant correlations + sig_connect = stat_mgc_map > threshold + if np.sum(sig_connect) > 0: + sig_connect, _ = _measurements.label(sig_connect) + _, label_counts = np.unique(sig_connect, return_counts=True) + + # skip the first element in label_counts, as it is count(zeros) + max_label = np.argmax(label_counts[1:]) + 1 + sig_connect = sig_connect == max_label + else: + sig_connect = np.array([[False]]) + + return sig_connect + + +def _smooth_mgc_map(sig_connect, stat_mgc_map): + """Finds the smoothed maximal within the significant region R. + + If area of R is too small it returns the last local correlation. Otherwise, + returns the maximum within significant_connected_region. + + Parameters + ---------- + sig_connect : ndarray + A binary matrix with 1's indicating the significant region. + stat_mgc_map : ndarray + All local correlations within ``[-1, 1]``. + + Returns + ------- + stat : float + The sample MGC statistic within ``[-1, 1]``. + opt_scale: (float, float) + The estimated optimal scale as an ``(x, y)`` pair. + + """ + m, n = stat_mgc_map.shape + + # the global scale at is the statistic calculated at maximal nearest + # neighbors. By default, statistic and optimal scale are global. + stat = stat_mgc_map[m - 1][n - 1] + opt_scale = [m, n] + + if np.linalg.norm(sig_connect) != 0: + # proceed only when the connected region's area is sufficiently large + # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05 + # with varying levels of performance + if np.sum(sig_connect) >= np.ceil(0.02 * max(m, n)) * min(m, n): + max_corr = max(stat_mgc_map[sig_connect]) + + # find all scales within significant_connected_region that maximize + # the local correlation + max_corr_index = np.where((stat_mgc_map >= max_corr) & sig_connect) + + if max_corr >= stat: + stat = max_corr + + k, l = max_corr_index + one_d_indices = k * n + l # 2D to 1D indexing + k = np.max(one_d_indices) // n + l = np.max(one_d_indices) % n + opt_scale = [k+1, l+1] # adding 1s to match R indexing + + return stat, opt_scale + + +def _two_sample_transform(u, v): + """Helper function that concatenates x and y for two sample MGC stat. + + See above for use. + + Parameters + ---------- + u, v : ndarray + `u` and `v` have shapes ``(n, p)`` and ``(m, p)``. + + Returns + ------- + x : ndarray + Concatenate `u` and `v` along the ``axis = 0``. `x` thus has shape + ``(2n, p)``. + y : ndarray + Label matrix for `x` where 0 refers to samples that comes from `u` and + 1 refers to samples that come from `v`. `y` thus has shape ``(2n, 1)``. + + """ + nx = u.shape[0] + ny = v.shape[0] + x = np.concatenate([u, v], axis=0) + y = np.concatenate([np.zeros(nx), np.ones(ny)], axis=0).reshape(-1, 1) + return x, y diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_morestats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_morestats.py new file mode 100644 index 0000000000000000000000000000000000000000..2858a49125998d082280418af338d8f15529c843 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_morestats.py @@ -0,0 +1,4581 @@ +import math +import warnings +import threading +from collections import namedtuple + +import numpy as np +from numpy import (isscalar, r_, log, around, unique, asarray, zeros, + arange, sort, amin, amax, sqrt, array, + pi, exp, ravel, count_nonzero) + +from scipy import optimize, special, interpolate, stats +from scipy._lib._bunch import _make_tuple_bunch +from scipy._lib._util import _rename_parameter, _contains_nan, _get_nan + +from scipy._lib._array_api import ( + array_namespace, + xp_size, + xp_moveaxis_to_end, + xp_vector_norm, +) + +from ._ansari_swilk_statistics import gscale, swilk +from . import _stats_py, _wilcoxon +from ._fit import FitResult +from ._stats_py import (find_repeats, _get_pvalue, SignificanceResult, # noqa:F401 + _SimpleNormal, _SimpleChi2) +from .contingency import chi2_contingency +from . import distributions +from ._distn_infrastructure import rv_generic +from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays + + +__all__ = ['mvsdist', + 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', + 'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot', + 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene', + 'fligner', 'mood', 'wilcoxon', 'median_test', + 'circmean', 'circvar', 'circstd', 'anderson_ksamp', + 'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax', + 'yeojohnson_normplot', 'directional_stats', + 'false_discovery_control' + ] + + +Mean = namedtuple('Mean', ('statistic', 'minmax')) +Variance = namedtuple('Variance', ('statistic', 'minmax')) +Std_dev = namedtuple('Std_dev', ('statistic', 'minmax')) + + +def bayes_mvs(data, alpha=0.90): + r""" + Bayesian confidence intervals for the mean, var, and std. + + Parameters + ---------- + data : array_like + Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`. + Requires 2 or more data points. + alpha : float, optional + Probability that the returned confidence interval contains + the true parameter. + + Returns + ------- + mean_cntr, var_cntr, std_cntr : tuple + The three results are for the mean, variance and standard deviation, + respectively. Each result is a tuple of the form:: + + (center, (lower, upper)) + + with ``center`` the mean of the conditional pdf of the value given the + data, and ``(lower, upper)`` a confidence interval, centered on the + median, containing the estimate to a probability ``alpha``. + + See Also + -------- + mvsdist + + Notes + ----- + Each tuple of mean, variance, and standard deviation estimates represent + the (center, (lower, upper)) with center the mean of the conditional pdf + of the value given the data and (lower, upper) is a confidence interval + centered on the median, containing the estimate to a probability + ``alpha``. + + Converts data to 1-D and assumes all data has the same mean and variance. + Uses Jeffrey's prior for variance and std. + + Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))`` + + References + ---------- + T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and + standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278, + 2006. + + Examples + -------- + First a basic example to demonstrate the outputs: + + >>> from scipy import stats + >>> data = [6, 9, 12, 7, 8, 8, 13] + >>> mean, var, std = stats.bayes_mvs(data) + >>> mean + Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467)) + >>> var + Variance(statistic=10.0, minmax=(3.176724206, 24.45910382)) + >>> std + Std_dev(statistic=2.9724954732045084, + minmax=(1.7823367265645143, 4.945614605014631)) + + Now we generate some normally distributed random data, and get estimates of + mean and standard deviation with 95% confidence intervals for those + estimates: + + >>> n_samples = 100000 + >>> data = stats.norm.rvs(size=n_samples) + >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.hist(data, bins=100, density=True, label='Histogram of data') + >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean') + >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r', + ... alpha=0.2, label=r'Estimated mean (95% limits)') + >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale') + >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2, + ... label=r'Estimated scale (95% limits)') + + >>> ax.legend(fontsize=10) + >>> ax.set_xlim([-4, 4]) + >>> ax.set_ylim([0, 0.5]) + >>> plt.show() + + """ + m, v, s = mvsdist(data) + if alpha >= 1 or alpha <= 0: + raise ValueError(f"0 < alpha < 1 is required, but {alpha=} was given.") + + m_res = Mean(m.mean(), m.interval(alpha)) + v_res = Variance(v.mean(), v.interval(alpha)) + s_res = Std_dev(s.mean(), s.interval(alpha)) + + return m_res, v_res, s_res + + +def mvsdist(data): + """ + 'Frozen' distributions for mean, variance, and standard deviation of data. + + Parameters + ---------- + data : array_like + Input array. Converted to 1-D using ravel. + Requires 2 or more data-points. + + Returns + ------- + mdist : "frozen" distribution object + Distribution object representing the mean of the data. + vdist : "frozen" distribution object + Distribution object representing the variance of the data. + sdist : "frozen" distribution object + Distribution object representing the standard deviation of the data. + + See Also + -------- + bayes_mvs + + Notes + ----- + The return values from ``bayes_mvs(data)`` is equivalent to + ``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``. + + In other words, calling ``.mean()`` and ``.interval(0.90)`` + on the three distribution objects returned from this function will give + the same results that are returned from `bayes_mvs`. + + References + ---------- + T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and + standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278, + 2006. + + Examples + -------- + >>> from scipy import stats + >>> data = [6, 9, 12, 7, 8, 8, 13] + >>> mean, var, std = stats.mvsdist(data) + + We now have frozen distribution objects "mean", "var" and "std" that we can + examine: + + >>> mean.mean() + 9.0 + >>> mean.interval(0.95) + (6.6120585482655692, 11.387941451734431) + >>> mean.std() + 1.1952286093343936 + + """ + x = ravel(data) + n = len(x) + if n < 2: + raise ValueError("Need at least 2 data-points.") + xbar = x.mean() + C = x.var() + if n > 1000: # gaussian approximations for large n + mdist = distributions.norm(loc=xbar, scale=math.sqrt(C / n)) + sdist = distributions.norm(loc=math.sqrt(C), scale=math.sqrt(C / (2. * n))) + vdist = distributions.norm(loc=C, scale=math.sqrt(2.0 / n) * C) + else: + nm1 = n - 1 + fac = n * C / 2. + val = nm1 / 2. + mdist = distributions.t(nm1, loc=xbar, scale=math.sqrt(C / nm1)) + sdist = distributions.gengamma(val, -2, scale=math.sqrt(fac)) + vdist = distributions.invgamma(val, scale=fac) + return mdist, vdist, sdist + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None +) +def kstat(data, n=2, *, axis=None): + r""" + Return the `n` th k-statistic ( ``1<=n<=4`` so far). + + The `n` th k-statistic ``k_n`` is the unique symmetric unbiased estimator of the + `n` th cumulant :math:`\kappa_n` [1]_ [2]_. + + Parameters + ---------- + data : array_like + Input array. + n : int, {1, 2, 3, 4}, optional + Default is equal to 2. + axis : int or None, default: None + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If ``None``, the input will + be raveled before computing the statistic. + + Returns + ------- + kstat : float + The `n` th k-statistic. + + See Also + -------- + kstatvar : Returns an unbiased estimator of the variance of the k-statistic + moment : Returns the n-th central moment about the mean for a sample. + + Notes + ----- + For a sample size :math:`n`, the first few k-statistics are given by + + .. math:: + + k_1 &= \frac{S_1}{n}, \\ + k_2 &= \frac{nS_2 - S_1^2}{n(n-1)}, \\ + k_3 &= \frac{2S_1^3 - 3nS_1S_2 + n^2S_3}{n(n-1)(n-2)}, \\ + k_4 &= \frac{-6S_1^4 + 12nS_1^2S_2 - 3n(n-1)S_2^2 - 4n(n+1)S_1S_3 + + n^2(n+1)S_4}{n (n-1)(n-2)(n-3)}, + + where + + .. math:: + + S_r \equiv \sum_{i=1}^n X_i^r, + + and :math:`X_i` is the :math:`i` th data point. + + References + ---------- + .. [1] http://mathworld.wolfram.com/k-Statistic.html + + .. [2] http://mathworld.wolfram.com/Cumulant.html + + Examples + -------- + >>> from scipy import stats + >>> from numpy.random import default_rng + >>> rng = default_rng() + + As sample size increases, `n`-th moment and `n`-th k-statistic converge to the + same number (although they aren't identical). In the case of the normal + distribution, they converge to zero. + + >>> for i in range(2,8): + ... x = rng.normal(size=10**i) + ... m, k = stats.moment(x, 3), stats.kstat(x, 3) + ... print(f"{i=}: {m=:.3g}, {k=:.3g}, {(m-k)=:.3g}") + i=2: m=-0.631, k=-0.651, (m-k)=0.0194 # random + i=3: m=0.0282, k=0.0283, (m-k)=-8.49e-05 + i=4: m=-0.0454, k=-0.0454, (m-k)=1.36e-05 + i=6: m=7.53e-05, k=7.53e-05, (m-k)=-2.26e-09 + i=7: m=0.00166, k=0.00166, (m-k)=-4.99e-09 + i=8: m=-2.88e-06 k=-2.88e-06, (m-k)=8.63e-13 + """ + xp = array_namespace(data) + data = xp.asarray(data) + if n > 4 or n < 1: + raise ValueError("k-statistics only supported for 1<=n<=4") + n = int(n) + if axis is None: + data = xp.reshape(data, (-1,)) + axis = 0 + + N = data.shape[axis] + + S = [None] + [xp.sum(data**k, axis=axis) for k in range(1, n + 1)] + if n == 1: + return S[1] * 1.0/N + elif n == 2: + return (N*S[2] - S[1]**2.0) / (N*(N - 1.0)) + elif n == 3: + return (2*S[1]**3 - 3*N*S[1]*S[2] + N*N*S[3]) / (N*(N - 1.0)*(N - 2.0)) + elif n == 4: + return ((-6*S[1]**4 + 12*N*S[1]**2 * S[2] - 3*N*(N-1.0)*S[2]**2 - + 4*N*(N+1)*S[1]*S[3] + N*N*(N+1)*S[4]) / + (N*(N-1.0)*(N-2.0)*(N-3.0))) + else: + raise ValueError("Should not be here.") + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None +) +def kstatvar(data, n=2, *, axis=None): + r"""Return an unbiased estimator of the variance of the k-statistic. + + See `kstat` and [1]_ for more details about the k-statistic. + + Parameters + ---------- + data : array_like + Input array. + n : int, {1, 2}, optional + Default is equal to 2. + axis : int or None, default: None + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If ``None``, the input will + be raveled before computing the statistic. + + Returns + ------- + kstatvar : float + The `n` th k-statistic variance. + + See Also + -------- + kstat : Returns the n-th k-statistic. + moment : Returns the n-th central moment about the mean for a sample. + + Notes + ----- + Unbiased estimators of the variances of the first two k-statistics are given by + + .. math:: + + \mathrm{var}(k_1) &= \frac{k_2}{n}, \\ + \mathrm{var}(k_2) &= \frac{2k_2^2n + (n-1)k_4}{n(n - 1)}. + + References + ---------- + .. [1] http://mathworld.wolfram.com/k-Statistic.html + + """ # noqa: E501 + xp = array_namespace(data) + data = xp.asarray(data) + if axis is None: + data = xp.reshape(data, (-1,)) + axis = 0 + N = data.shape[axis] + + if n == 1: + return kstat(data, n=2, axis=axis, _no_deco=True) * 1.0/N + elif n == 2: + k2 = kstat(data, n=2, axis=axis, _no_deco=True) + k4 = kstat(data, n=4, axis=axis, _no_deco=True) + return (2*N*k2**2 + (N-1)*k4) / (N*(N+1)) + else: + raise ValueError("Only n=1 or n=2 supported.") + + +def _calc_uniform_order_statistic_medians(n): + """Approximations of uniform order statistic medians. + + Parameters + ---------- + n : int + Sample size. + + Returns + ------- + v : 1d float array + Approximations of the order statistic medians. + + References + ---------- + .. [1] James J. Filliben, "The Probability Plot Correlation Coefficient + Test for Normality", Technometrics, Vol. 17, pp. 111-117, 1975. + + Examples + -------- + Order statistics of the uniform distribution on the unit interval + are marginally distributed according to beta distributions. + The expectations of these order statistic are evenly spaced across + the interval, but the distributions are skewed in a way that + pushes the medians slightly towards the endpoints of the unit interval: + + >>> import numpy as np + >>> n = 4 + >>> k = np.arange(1, n+1) + >>> from scipy.stats import beta + >>> a = k + >>> b = n-k+1 + >>> beta.mean(a, b) + array([0.2, 0.4, 0.6, 0.8]) + >>> beta.median(a, b) + array([0.15910358, 0.38572757, 0.61427243, 0.84089642]) + + The Filliben approximation uses the exact medians of the smallest + and greatest order statistics, and the remaining medians are approximated + by points spread evenly across a sub-interval of the unit interval: + + >>> from scipy.stats._morestats import _calc_uniform_order_statistic_medians + >>> _calc_uniform_order_statistic_medians(n) + array([0.15910358, 0.38545246, 0.61454754, 0.84089642]) + + This plot shows the skewed distributions of the order statistics + of a sample of size four from a uniform distribution on the unit interval: + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0.0, 1.0, num=50, endpoint=True) + >>> pdfs = [beta.pdf(x, a[i], b[i]) for i in range(n)] + >>> plt.figure() + >>> plt.plot(x, pdfs[0], x, pdfs[1], x, pdfs[2], x, pdfs[3]) + + """ + v = np.empty(n, dtype=np.float64) + v[-1] = 0.5**(1.0 / n) + v[0] = 1 - v[-1] + i = np.arange(2, n) + v[1:-1] = (i - 0.3175) / (n + 0.365) + return v + + +def _parse_dist_kw(dist, enforce_subclass=True): + """Parse `dist` keyword. + + Parameters + ---------- + dist : str or stats.distributions instance. + Several functions take `dist` as a keyword, hence this utility + function. + enforce_subclass : bool, optional + If True (default), `dist` needs to be a + `_distn_infrastructure.rv_generic` instance. + It can sometimes be useful to set this keyword to False, if a function + wants to accept objects that just look somewhat like such an instance + (for example, they have a ``ppf`` method). + + """ + if isinstance(dist, rv_generic): + pass + elif isinstance(dist, str): + try: + dist = getattr(distributions, dist) + except AttributeError as e: + raise ValueError(f"{dist} is not a valid distribution name") from e + elif enforce_subclass: + msg = ("`dist` should be a stats.distributions instance or a string " + "with the name of such a distribution.") + raise ValueError(msg) + + return dist + + +def _add_axis_labels_title(plot, xlabel, ylabel, title): + """Helper function to add axes labels and a title to stats plots.""" + try: + if hasattr(plot, 'set_title'): + # Matplotlib Axes instance or something that looks like it + plot.set_title(title) + plot.set_xlabel(xlabel) + plot.set_ylabel(ylabel) + else: + # matplotlib.pyplot module + plot.title(title) + plot.xlabel(xlabel) + plot.ylabel(ylabel) + except Exception: + # Not an MPL object or something that looks (enough) like it. + # Don't crash on adding labels or title + pass + + +def probplot(x, sparams=(), dist='norm', fit=True, plot=None, rvalue=False): + """ + Calculate quantiles for a probability plot, and optionally show the plot. + + Generates a probability plot of sample data against the quantiles of a + specified theoretical distribution (the normal distribution by default). + `probplot` optionally calculates a best-fit line for the data and plots the + results using Matplotlib or a given plot function. + + Parameters + ---------- + x : array_like + Sample/response data from which `probplot` creates the plot. + sparams : tuple, optional + Distribution-specific shape parameters (shape parameters plus location + and scale). + dist : str or stats.distributions instance, optional + Distribution or distribution function name. The default is 'norm' for a + normal probability plot. Objects that look enough like a + stats.distributions instance (i.e. they have a ``ppf`` method) are also + accepted. + fit : bool, optional + Fit a least-squares regression (best-fit) line to the sample data if + True (default). + plot : object, optional + If given, plots the quantiles. + If given and `fit` is True, also plots the least squares fit. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + rvalue : bool, optional + If `plot` is provided and `fit` is True, setting `rvalue` to True + includes the coefficient of determination on the plot. + Default is False. + + Returns + ------- + (osm, osr) : tuple of ndarrays + Tuple of theoretical quantiles (osm, or order statistic medians) and + ordered responses (osr). `osr` is simply sorted input `x`. + For details on how `osm` is calculated see the Notes section. + (slope, intercept, r) : tuple of floats, optional + Tuple containing the result of the least-squares fit, if that is + performed by `probplot`. `r` is the square root of the coefficient of + determination. If ``fit=False`` and ``plot=None``, this tuple is not + returned. + + Notes + ----- + Even if `plot` is given, the figure is not shown or saved by `probplot`; + ``plt.show()`` or ``plt.savefig('figname.png')`` should be used after + calling `probplot`. + + `probplot` generates a probability plot, which should not be confused with + a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this + type, see ``statsmodels.api.ProbPlot``. + + The formula used for the theoretical quantiles (horizontal axis of the + probability plot) is Filliben's estimate:: + + quantiles = dist.ppf(val), for + + 0.5**(1/n), for i = n + val = (i - 0.3175) / (n + 0.365), for i = 2, ..., n-1 + 1 - 0.5**(1/n), for i = 1 + + where ``i`` indicates the i-th ordered value and ``n`` is the total number + of values. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> nsample = 100 + >>> rng = np.random.default_rng() + + A t distribution with small degrees of freedom: + + >>> ax1 = plt.subplot(221) + >>> x = stats.t.rvs(3, size=nsample, random_state=rng) + >>> res = stats.probplot(x, plot=plt) + + A t distribution with larger degrees of freedom: + + >>> ax2 = plt.subplot(222) + >>> x = stats.t.rvs(25, size=nsample, random_state=rng) + >>> res = stats.probplot(x, plot=plt) + + A mixture of two normal distributions with broadcasting: + + >>> ax3 = plt.subplot(223) + >>> x = stats.norm.rvs(loc=[0,5], scale=[1,1.5], + ... size=(nsample//2,2), random_state=rng).ravel() + >>> res = stats.probplot(x, plot=plt) + + A standard normal distribution: + + >>> ax4 = plt.subplot(224) + >>> x = stats.norm.rvs(loc=0, scale=1, size=nsample, random_state=rng) + >>> res = stats.probplot(x, plot=plt) + + Produce a new figure with a loggamma distribution, using the ``dist`` and + ``sparams`` keywords: + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> x = stats.loggamma.rvs(c=2.5, size=500, random_state=rng) + >>> res = stats.probplot(x, dist=stats.loggamma, sparams=(2.5,), plot=ax) + >>> ax.set_title("Probplot for loggamma dist with shape parameter 2.5") + + Show the results with Matplotlib: + + >>> plt.show() + + """ + x = np.asarray(x) + if x.size == 0: + if fit: + return (x, x), (np.nan, np.nan, 0.0) + else: + return x, x + + osm_uniform = _calc_uniform_order_statistic_medians(len(x)) + dist = _parse_dist_kw(dist, enforce_subclass=False) + if sparams is None: + sparams = () + if isscalar(sparams): + sparams = (sparams,) + if not isinstance(sparams, tuple): + sparams = tuple(sparams) + + osm = dist.ppf(osm_uniform, *sparams) + osr = sort(x) + if fit: + # perform a linear least squares fit. + slope, intercept, r, prob, _ = _stats_py.linregress(osm, osr) + + if plot is not None: + plot.plot(osm, osr, 'bo') + if fit: + plot.plot(osm, slope*osm + intercept, 'r-') + _add_axis_labels_title(plot, xlabel='Theoretical quantiles', + ylabel='Ordered Values', + title='Probability Plot') + + # Add R^2 value to the plot as text + if fit and rvalue: + xmin = amin(osm) + xmax = amax(osm) + ymin = amin(x) + ymax = amax(x) + posx = xmin + 0.70 * (xmax - xmin) + posy = ymin + 0.01 * (ymax - ymin) + plot.text(posx, posy, f"$R^2={r ** 2:1.4f}$") + + if fit: + return (osm, osr), (slope, intercept, r) + else: + return osm, osr + + +def ppcc_max(x, brack=(0.0, 1.0), dist='tukeylambda'): + """Calculate the shape parameter that maximizes the PPCC. + + The probability plot correlation coefficient (PPCC) plot can be used + to determine the optimal shape parameter for a one-parameter family + of distributions. ``ppcc_max`` returns the shape parameter that would + maximize the probability plot correlation coefficient for the given + data to a one-parameter family of distributions. + + Parameters + ---------- + x : array_like + Input array. + brack : tuple, optional + Triple (a,b,c) where (a>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> c = 2.5 + >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng) + + Generate the PPCC plot for this data with the Weibull distribution. + + >>> fig, ax = plt.subplots(figsize=(8, 6)) + >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax) + + We calculate the value where the shape should reach its maximum and a + red line is drawn there. The line should coincide with the highest + point in the PPCC graph. + + >>> cmax = stats.ppcc_max(x, brack=(c/2, 2*c), dist='weibull_min') + >>> ax.axvline(cmax, color='r') + >>> plt.show() + + """ + dist = _parse_dist_kw(dist) + osm_uniform = _calc_uniform_order_statistic_medians(len(x)) + osr = sort(x) + + # this function computes the x-axis values of the probability plot + # and computes a linear regression (including the correlation) + # and returns 1-r so that a minimization function maximizes the + # correlation + def tempfunc(shape, mi, yvals, func): + xvals = func(mi, shape) + r, prob = _stats_py.pearsonr(xvals, yvals) + return 1 - r + + return optimize.brent(tempfunc, brack=brack, + args=(osm_uniform, osr, dist.ppf)) + + +def ppcc_plot(x, a, b, dist='tukeylambda', plot=None, N=80): + """Calculate and optionally plot probability plot correlation coefficient. + + The probability plot correlation coefficient (PPCC) plot can be used to + determine the optimal shape parameter for a one-parameter family of + distributions. It cannot be used for distributions without shape + parameters + (like the normal distribution) or with multiple shape parameters. + + By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A + Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed + distributions via an approximately normal one, and is therefore + particularly useful in practice. + + Parameters + ---------- + x : array_like + Input array. + a, b : scalar + Lower and upper bounds of the shape parameter to use. + dist : str or stats.distributions instance, optional + Distribution or distribution function name. Objects that look enough + like a stats.distributions instance (i.e. they have a ``ppf`` method) + are also accepted. The default is ``'tukeylambda'``. + plot : object, optional + If given, plots PPCC against the shape parameter. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + N : int, optional + Number of points on the horizontal axis (equally distributed from + `a` to `b`). + + Returns + ------- + svals : ndarray + The shape values for which `ppcc` was calculated. + ppcc : ndarray + The calculated probability plot correlation coefficient values. + + See Also + -------- + ppcc_max, probplot, boxcox_normplot, tukeylambda + + References + ---------- + J.J. Filliben, "The Probability Plot Correlation Coefficient Test for + Normality", Technometrics, Vol. 17, pp. 111-117, 1975. + + Examples + -------- + First we generate some random data from a Weibull distribution + with shape parameter 2.5, and plot the histogram of the data: + + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> c = 2.5 + >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng) + + Take a look at the histogram of the data. + + >>> fig1, ax = plt.subplots(figsize=(9, 4)) + >>> ax.hist(x, bins=50) + >>> ax.set_title('Histogram of x') + >>> plt.show() + + Now we explore this data with a PPCC plot as well as the related + probability plot and Box-Cox normplot. A red line is drawn where we + expect the PPCC value to be maximal (at the shape parameter ``c`` + used above): + + >>> fig2 = plt.figure(figsize=(12, 4)) + >>> ax1 = fig2.add_subplot(1, 3, 1) + >>> ax2 = fig2.add_subplot(1, 3, 2) + >>> ax3 = fig2.add_subplot(1, 3, 3) + >>> res = stats.probplot(x, plot=ax1) + >>> res = stats.boxcox_normplot(x, -4, 4, plot=ax2) + >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax3) + >>> ax3.axvline(c, color='r') + >>> plt.show() + + """ + if b <= a: + raise ValueError("`b` has to be larger than `a`.") + + svals = np.linspace(a, b, num=N) + ppcc = np.empty_like(svals) + for k, sval in enumerate(svals): + _, r2 = probplot(x, sval, dist=dist, fit=True) + ppcc[k] = r2[-1] + + if plot is not None: + plot.plot(svals, ppcc, 'x') + _add_axis_labels_title(plot, xlabel='Shape Values', + ylabel='Prob Plot Corr. Coef.', + title=f'({dist}) PPCC Plot') + + return svals, ppcc + + +def _log_mean(logx): + # compute log of mean of x from log(x) + res = special.logsumexp(logx, axis=0) - math.log(logx.shape[0]) + return res + + +def _log_var(logx, xp): + # compute log of variance of x from log(x) + logmean = _log_mean(logx) + # get complex dtype with component dtypes same as `logx` dtype; + # see data-apis/array-api#841 + dtype = xp.result_type(logx.dtype, xp.complex64) + pij = xp.full(logx.shape, pi * 1j, dtype=dtype) + logxmu = special.logsumexp(xp.stack((logx, logmean + pij)), axis=0) + res = (xp.real(xp.asarray(special.logsumexp(2 * logxmu, axis=0))) + - math.log(logx.shape[0])) + return res + + +def boxcox_llf(lmb, data): + r"""The boxcox log-likelihood function. + + Parameters + ---------- + lmb : scalar + Parameter for Box-Cox transformation. See `boxcox` for details. + data : array_like + Data to calculate Box-Cox log-likelihood for. If `data` is + multi-dimensional, the log-likelihood is calculated along the first + axis. + + Returns + ------- + llf : float or ndarray + Box-Cox log-likelihood of `data` given `lmb`. A float for 1-D `data`, + an array otherwise. + + See Also + -------- + boxcox, probplot, boxcox_normplot, boxcox_normmax + + Notes + ----- + The Box-Cox log-likelihood function is defined here as + + .. math:: + + llf = (\lambda - 1) \sum_i(\log(x_i)) - + N/2 \log(\sum_i (y_i - \bar{y})^2 / N), + + where ``y`` is the Box-Cox transformed input data ``x``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes + + Generate some random variates and calculate Box-Cox log-likelihood values + for them for a range of ``lmbda`` values: + + >>> rng = np.random.default_rng() + >>> x = stats.loggamma.rvs(5, loc=10, size=1000, random_state=rng) + >>> lmbdas = np.linspace(-2, 10) + >>> llf = np.zeros(lmbdas.shape, dtype=float) + >>> for ii, lmbda in enumerate(lmbdas): + ... llf[ii] = stats.boxcox_llf(lmbda, x) + + Also find the optimal lmbda value with `boxcox`: + + >>> x_most_normal, lmbda_optimal = stats.boxcox(x) + + Plot the log-likelihood as function of lmbda. Add the optimal lmbda as a + horizontal line to check that that's really the optimum: + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(lmbdas, llf, 'b.-') + >>> ax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r') + >>> ax.set_xlabel('lmbda parameter') + >>> ax.set_ylabel('Box-Cox log-likelihood') + + Now add some probability plots to show that where the log-likelihood is + maximized the data transformed with `boxcox` looks closest to normal: + + >>> locs = [3, 10, 4] # 'lower left', 'center', 'lower right' + >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs): + ... xt = stats.boxcox(x, lmbda=lmbda) + ... (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt) + ... ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc) + ... ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-') + ... ax_inset.set_xticklabels([]) + ... ax_inset.set_yticklabels([]) + ... ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda) + + >>> plt.show() + + """ + xp = array_namespace(data) + data = xp.asarray(data) + N = data.shape[0] + if N == 0: + return xp.nan + + dt = data.dtype + if xp.isdtype(dt, 'integral'): + data = xp.asarray(data, dtype=xp.float64) + dt = xp.float64 + + logdata = xp.log(data) + + # Compute the variance of the transformed data. + if lmb == 0: + logvar = xp.log(xp.var(logdata, axis=0)) + else: + # Transform without the constant offset 1/lmb. The offset does + # not affect the variance, and the subtraction of the offset can + # lead to loss of precision. + # Division by lmb can be factored out to enhance numerical stability. + logx = lmb * logdata + logvar = _log_var(logx, xp) - 2 * math.log(abs(lmb)) + + res = (lmb - 1) * xp.sum(logdata, axis=0) - N/2 * logvar + res = xp.astype(res, dt) + res = res[()] if res.ndim == 0 else res + return res + + +def _boxcox_conf_interval(x, lmax, alpha): + # Need to find the lambda for which + # f(x,lmbda) >= f(x,lmax) - 0.5*chi^2_alpha;1 + fac = 0.5 * distributions.chi2.ppf(1 - alpha, 1) + target = boxcox_llf(lmax, x) - fac + + def rootfunc(lmbda, data, target): + return boxcox_llf(lmbda, data) - target + + # Find positive endpoint of interval in which answer is to be found + newlm = lmax + 0.5 + N = 0 + while (rootfunc(newlm, x, target) > 0.0) and (N < 500): + newlm += 0.1 + N += 1 + + if N == 500: + raise RuntimeError("Could not find endpoint.") + + lmplus = optimize.brentq(rootfunc, lmax, newlm, args=(x, target)) + + # Now find negative interval in the same way + newlm = lmax - 0.5 + N = 0 + while (rootfunc(newlm, x, target) > 0.0) and (N < 500): + newlm -= 0.1 + N += 1 + + if N == 500: + raise RuntimeError("Could not find endpoint.") + + lmminus = optimize.brentq(rootfunc, newlm, lmax, args=(x, target)) + return lmminus, lmplus + + +def boxcox(x, lmbda=None, alpha=None, optimizer=None): + r"""Return a dataset transformed by a Box-Cox power transformation. + + Parameters + ---------- + x : ndarray + Input array to be transformed. + + If `lmbda` is not None, this is an alias of + `scipy.special.boxcox`. + Returns nan if ``x < 0``; returns -inf if ``x == 0 and lmbda < 0``. + + If `lmbda` is None, array must be positive, 1-dimensional, and + non-constant. + + lmbda : scalar, optional + If `lmbda` is None (default), find the value of `lmbda` that maximizes + the log-likelihood function and return it as the second output + argument. + + If `lmbda` is not None, do the transformation for that value. + + alpha : float, optional + If `lmbda` is None and `alpha` is not None (default), return the + ``100 * (1-alpha)%`` confidence interval for `lmbda` as the third + output argument. Must be between 0.0 and 1.0. + + If `lmbda` is not None, `alpha` is ignored. + optimizer : callable, optional + If `lmbda` is None, `optimizer` is the scalar optimizer used to find + the value of `lmbda` that minimizes the negative log-likelihood + function. `optimizer` is a callable that accepts one argument: + + fun : callable + The objective function, which evaluates the negative + log-likelihood function at a provided value of `lmbda` + + and returns an object, such as an instance of + `scipy.optimize.OptimizeResult`, which holds the optimal value of + `lmbda` in an attribute `x`. + + See the example in `boxcox_normmax` or the documentation of + `scipy.optimize.minimize_scalar` for more information. + + If `lmbda` is not None, `optimizer` is ignored. + + Returns + ------- + boxcox : ndarray + Box-Cox power transformed array. + maxlog : float, optional + If the `lmbda` parameter is None, the second returned argument is + the `lmbda` that maximizes the log-likelihood function. + (min_ci, max_ci) : tuple of float, optional + If `lmbda` parameter is None and `alpha` is not None, this returned + tuple of floats represents the minimum and maximum confidence limits + given `alpha`. + + See Also + -------- + probplot, boxcox_normplot, boxcox_normmax, boxcox_llf + + Notes + ----- + The Box-Cox transform is given by:: + + y = (x**lmbda - 1) / lmbda, for lmbda != 0 + log(x), for lmbda = 0 + + `boxcox` requires the input data to be positive. Sometimes a Box-Cox + transformation provides a shift parameter to achieve this; `boxcox` does + not. Such a shift parameter is equivalent to adding a positive constant to + `x` before calling `boxcox`. + + The confidence limits returned when `alpha` is provided give the interval + where: + + .. math:: + + llf(\hat{\lambda}) - llf(\lambda) < \frac{1}{2}\chi^2(1 - \alpha, 1), + + with ``llf`` the log-likelihood function and :math:`\chi^2` the chi-squared + function. + + References + ---------- + G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal of the + Royal Statistical Society B, 26, 211-252 (1964). + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + We generate some random variates from a non-normal distribution and make a + probability plot for it, to show it is non-normal in the tails: + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(211) + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1) + >>> ax1.set_xlabel('') + >>> ax1.set_title('Probplot against normal distribution') + + We now use `boxcox` to transform the data so it's closest to normal: + + >>> ax2 = fig.add_subplot(212) + >>> xt, _ = stats.boxcox(x) + >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2) + >>> ax2.set_title('Probplot after Box-Cox transformation') + + >>> plt.show() + + """ + x = np.asarray(x) + + if lmbda is not None: # single transformation + return special.boxcox(x, lmbda) + + if x.ndim != 1: + raise ValueError("Data must be 1-dimensional.") + + if x.size == 0: + return x + + if np.all(x == x[0]): + raise ValueError("Data must not be constant.") + + if np.any(x <= 0): + raise ValueError("Data must be positive.") + + # If lmbda=None, find the lmbda that maximizes the log-likelihood function. + lmax = boxcox_normmax(x, method='mle', optimizer=optimizer) + y = boxcox(x, lmax) + + if alpha is None: + return y, lmax + else: + # Find confidence interval + interval = _boxcox_conf_interval(x, lmax, alpha) + return y, lmax, interval + + +def _boxcox_inv_lmbda(x, y): + # compute lmbda given x and y for Box-Cox transformation + num = special.lambertw(-(x ** (-1 / y)) * np.log(x) / y, k=-1) + return np.real(-num / np.log(x) - 1 / y) + + +class _BigFloat: + def __repr__(self): + return "BIG_FLOAT" + + +_BigFloat_singleton = _BigFloat() + + +def boxcox_normmax( + x, brack=None, method='pearsonr', optimizer=None, *, ymax=_BigFloat_singleton +): + """Compute optimal Box-Cox transform parameter for input data. + + Parameters + ---------- + x : array_like + Input array. All entries must be positive, finite, real numbers. + brack : 2-tuple, optional, default (-2.0, 2.0) + The starting interval for a downhill bracket search for the default + `optimize.brent` solver. Note that this is in most cases not + critical; the final result is allowed to be outside this bracket. + If `optimizer` is passed, `brack` must be None. + method : str, optional + The method to determine the optimal transform parameter (`boxcox` + ``lmbda`` parameter). Options are: + + 'pearsonr' (default) + Maximizes the Pearson correlation coefficient between + ``y = boxcox(x)`` and the expected values for ``y`` if `x` would be + normally-distributed. + + 'mle' + Maximizes the log-likelihood `boxcox_llf`. This is the method used + in `boxcox`. + + 'all' + Use all optimization methods available, and return all results. + Useful to compare different methods. + optimizer : callable, optional + `optimizer` is a callable that accepts one argument: + + fun : callable + The objective function to be minimized. `fun` accepts one argument, + the Box-Cox transform parameter `lmbda`, and returns the value of + the function (e.g., the negative log-likelihood) at the provided + argument. The job of `optimizer` is to find the value of `lmbda` + that *minimizes* `fun`. + + and returns an object, such as an instance of + `scipy.optimize.OptimizeResult`, which holds the optimal value of + `lmbda` in an attribute `x`. + + See the example below or the documentation of + `scipy.optimize.minimize_scalar` for more information. + ymax : float, optional + The unconstrained optimal transform parameter may cause Box-Cox + transformed data to have extreme magnitude or even overflow. + This parameter constrains MLE optimization such that the magnitude + of the transformed `x` does not exceed `ymax`. The default is + the maximum value of the input dtype. If set to infinity, + `boxcox_normmax` returns the unconstrained optimal lambda. + Ignored when ``method='pearsonr'``. + + Returns + ------- + maxlog : float or ndarray + The optimal transform parameter found. An array instead of a scalar + for ``method='all'``. + + See Also + -------- + boxcox, boxcox_llf, boxcox_normplot, scipy.optimize.minimize_scalar + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + We can generate some data and determine the optimal ``lmbda`` in various + ways: + + >>> rng = np.random.default_rng() + >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5 + >>> y, lmax_mle = stats.boxcox(x) + >>> lmax_pearsonr = stats.boxcox_normmax(x) + + >>> lmax_mle + 2.217563431465757 + >>> lmax_pearsonr + 2.238318660200961 + >>> stats.boxcox_normmax(x, method='all') + array([2.23831866, 2.21756343]) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.boxcox_normplot(x, -10, 10, plot=ax) + >>> ax.axvline(lmax_mle, color='r') + >>> ax.axvline(lmax_pearsonr, color='g', ls='--') + + >>> plt.show() + + Alternatively, we can define our own `optimizer` function. Suppose we + are only interested in values of `lmbda` on the interval [6, 7], we + want to use `scipy.optimize.minimize_scalar` with ``method='bounded'``, + and we want to use tighter tolerances when optimizing the log-likelihood + function. To do this, we define a function that accepts positional argument + `fun` and uses `scipy.optimize.minimize_scalar` to minimize `fun` subject + to the provided bounds and tolerances: + + >>> from scipy import optimize + >>> options = {'xatol': 1e-12} # absolute tolerance on `x` + >>> def optimizer(fun): + ... return optimize.minimize_scalar(fun, bounds=(6, 7), + ... method="bounded", options=options) + >>> stats.boxcox_normmax(x, optimizer=optimizer) + 6.000000000 + """ + x = np.asarray(x) + + if not np.all(np.isfinite(x) & (x >= 0)): + message = ("The `x` argument of `boxcox_normmax` must contain " + "only positive, finite, real numbers.") + raise ValueError(message) + + end_msg = "exceed specified `ymax`." + if ymax is _BigFloat_singleton: + dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64 + # 10000 is a safety factor because `special.boxcox` overflows prematurely. + ymax = np.finfo(dtype).max / 10000 + end_msg = f"overflow in {dtype}." + elif ymax <= 0: + raise ValueError("`ymax` must be strictly positive") + + # If optimizer is not given, define default 'brent' optimizer. + if optimizer is None: + + # Set default value for `brack`. + if brack is None: + brack = (-2.0, 2.0) + + def _optimizer(func, args): + return optimize.brent(func, args=args, brack=brack) + + # Otherwise check optimizer. + else: + if not callable(optimizer): + raise ValueError("`optimizer` must be a callable") + + if brack is not None: + raise ValueError("`brack` must be None if `optimizer` is given") + + # `optimizer` is expected to return a `OptimizeResult` object, we here + # get the solution to the optimization problem. + def _optimizer(func, args): + def func_wrapped(x): + return func(x, *args) + return getattr(optimizer(func_wrapped), 'x', None) + + def _pearsonr(x): + osm_uniform = _calc_uniform_order_statistic_medians(len(x)) + xvals = distributions.norm.ppf(osm_uniform) + + def _eval_pearsonr(lmbda, xvals, samps): + # This function computes the x-axis values of the probability plot + # and computes a linear regression (including the correlation) and + # returns ``1 - r`` so that a minimization function maximizes the + # correlation. + y = boxcox(samps, lmbda) + yvals = np.sort(y) + r, prob = _stats_py.pearsonr(xvals, yvals) + return 1 - r + + return _optimizer(_eval_pearsonr, args=(xvals, x)) + + def _mle(x): + def _eval_mle(lmb, data): + # function to minimize + return -boxcox_llf(lmb, data) + + return _optimizer(_eval_mle, args=(x,)) + + def _all(x): + maxlog = np.empty(2, dtype=float) + maxlog[0] = _pearsonr(x) + maxlog[1] = _mle(x) + return maxlog + + methods = {'pearsonr': _pearsonr, + 'mle': _mle, + 'all': _all} + if method not in methods.keys(): + raise ValueError(f"Method {method} not recognized.") + + optimfunc = methods[method] + + res = optimfunc(x) + + if res is None: + message = ("The `optimizer` argument of `boxcox_normmax` must return " + "an object containing the optimal `lmbda` in attribute `x`.") + raise ValueError(message) + elif not np.isinf(ymax): # adjust the final lambda + # x > 1, boxcox(x) > 0; x < 1, boxcox(x) < 0 + xmax, xmin = np.max(x), np.min(x) + if xmin >= 1: + x_treme = xmax + elif xmax <= 1: + x_treme = xmin + else: # xmin < 1 < xmax + indicator = special.boxcox(xmax, res) > abs(special.boxcox(xmin, res)) + if isinstance(res, np.ndarray): + indicator = indicator[1] # select corresponds with 'mle' + x_treme = xmax if indicator else xmin + + mask = abs(special.boxcox(x_treme, res)) > ymax + if np.any(mask): + message = ( + f"The optimal lambda is {res}, but the returned lambda is the " + f"constrained optimum to ensure that the maximum or the minimum " + f"of the transformed data does not " + end_msg + ) + warnings.warn(message, stacklevel=2) + + # Return the constrained lambda to ensure the transformation + # does not cause overflow or exceed specified `ymax` + constrained_res = _boxcox_inv_lmbda(x_treme, ymax * np.sign(x_treme - 1)) + + if isinstance(res, np.ndarray): + res[mask] = constrained_res + else: + res = constrained_res + return res + + +def _normplot(method, x, la, lb, plot=None, N=80): + """Compute parameters for a Box-Cox or Yeo-Johnson normality plot, + optionally show it. + + See `boxcox_normplot` or `yeojohnson_normplot` for details. + """ + + if method == 'boxcox': + title = 'Box-Cox Normality Plot' + transform_func = boxcox + else: + title = 'Yeo-Johnson Normality Plot' + transform_func = yeojohnson + + x = np.asarray(x) + if x.size == 0: + return x + + if lb <= la: + raise ValueError("`lb` has to be larger than `la`.") + + if method == 'boxcox' and np.any(x <= 0): + raise ValueError("Data must be positive.") + + lmbdas = np.linspace(la, lb, num=N) + ppcc = lmbdas * 0.0 + for i, val in enumerate(lmbdas): + # Determine for each lmbda the square root of correlation coefficient + # of transformed x + z = transform_func(x, lmbda=val) + _, (_, _, r) = probplot(z, dist='norm', fit=True) + ppcc[i] = r + + if plot is not None: + plot.plot(lmbdas, ppcc, 'x') + _add_axis_labels_title(plot, xlabel='$\\lambda$', + ylabel='Prob Plot Corr. Coef.', + title=title) + + return lmbdas, ppcc + + +def boxcox_normplot(x, la, lb, plot=None, N=80): + """Compute parameters for a Box-Cox normality plot, optionally show it. + + A Box-Cox normality plot shows graphically what the best transformation + parameter is to use in `boxcox` to obtain a distribution that is close + to normal. + + Parameters + ---------- + x : array_like + Input array. + la, lb : scalar + The lower and upper bounds for the ``lmbda`` values to pass to `boxcox` + for Box-Cox transformations. These are also the limits of the + horizontal axis of the plot if that is generated. + plot : object, optional + If given, plots the quantiles and least squares fit. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + N : int, optional + Number of points on the horizontal axis (equally distributed from + `la` to `lb`). + + Returns + ------- + lmbdas : ndarray + The ``lmbda`` values for which a Box-Cox transform was done. + ppcc : ndarray + Probability Plot Correlation Coefficient, as obtained from `probplot` + when fitting the Box-Cox transformed input `x` against a normal + distribution. + + See Also + -------- + probplot, boxcox, boxcox_normmax, boxcox_llf, ppcc_max + + Notes + ----- + Even if `plot` is given, the figure is not shown or saved by + `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')`` + should be used after calling `probplot`. + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Generate some non-normally distributed data, and create a Box-Cox plot: + + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.boxcox_normplot(x, -20, 20, plot=ax) + + Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in + the same plot: + + >>> _, maxlog = stats.boxcox(x) + >>> ax.axvline(maxlog, color='r') + + >>> plt.show() + + """ + return _normplot('boxcox', x, la, lb, plot, N) + + +def yeojohnson(x, lmbda=None): + r"""Return a dataset transformed by a Yeo-Johnson power transformation. + + Parameters + ---------- + x : ndarray + Input array. Should be 1-dimensional. + lmbda : float, optional + If ``lmbda`` is ``None``, find the lambda that maximizes the + log-likelihood function and return it as the second output argument. + Otherwise the transformation is done for the given value. + + Returns + ------- + yeojohnson: ndarray + Yeo-Johnson power transformed array. + maxlog : float, optional + If the `lmbda` parameter is None, the second returned argument is + the lambda that maximizes the log-likelihood function. + + See Also + -------- + probplot, yeojohnson_normplot, yeojohnson_normmax, yeojohnson_llf, boxcox + + Notes + ----- + The Yeo-Johnson transform is given by:: + + y = ((x + 1)**lmbda - 1) / lmbda, for x >= 0, lmbda != 0 + log(x + 1), for x >= 0, lmbda = 0 + -((-x + 1)**(2 - lmbda) - 1) / (2 - lmbda), for x < 0, lmbda != 2 + -log(-x + 1), for x < 0, lmbda = 2 + + Unlike `boxcox`, `yeojohnson` does not require the input data to be + positive. + + .. versionadded:: 1.2.0 + + + References + ---------- + I. Yeo and R.A. Johnson, "A New Family of Power Transformations to + Improve Normality or Symmetry", Biometrika 87.4 (2000): + + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + We generate some random variates from a non-normal distribution and make a + probability plot for it, to show it is non-normal in the tails: + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(211) + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1) + >>> ax1.set_xlabel('') + >>> ax1.set_title('Probplot against normal distribution') + + We now use `yeojohnson` to transform the data so it's closest to normal: + + >>> ax2 = fig.add_subplot(212) + >>> xt, lmbda = stats.yeojohnson(x) + >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2) + >>> ax2.set_title('Probplot after Yeo-Johnson transformation') + + >>> plt.show() + + """ + x = np.asarray(x) + if x.size == 0: + return x + + if np.issubdtype(x.dtype, np.complexfloating): + raise ValueError('Yeo-Johnson transformation is not defined for ' + 'complex numbers.') + + if np.issubdtype(x.dtype, np.integer): + x = x.astype(np.float64, copy=False) + + if lmbda is not None: + return _yeojohnson_transform(x, lmbda) + + # if lmbda=None, find the lmbda that maximizes the log-likelihood function. + lmax = yeojohnson_normmax(x) + y = _yeojohnson_transform(x, lmax) + + return y, lmax + + +def _yeojohnson_transform(x, lmbda): + """Returns `x` transformed by the Yeo-Johnson power transform with given + parameter `lmbda`. + """ + dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64 + out = np.zeros_like(x, dtype=dtype) + pos = x >= 0 # binary mask + + # when x >= 0 + if abs(lmbda) < np.spacing(1.): + out[pos] = np.log1p(x[pos]) + else: # lmbda != 0 + # more stable version of: ((x + 1) ** lmbda - 1) / lmbda + out[pos] = np.expm1(lmbda * np.log1p(x[pos])) / lmbda + + # when x < 0 + if abs(lmbda - 2) > np.spacing(1.): + out[~pos] = -np.expm1((2 - lmbda) * np.log1p(-x[~pos])) / (2 - lmbda) + else: # lmbda == 2 + out[~pos] = -np.log1p(-x[~pos]) + + return out + + +def yeojohnson_llf(lmb, data): + r"""The yeojohnson log-likelihood function. + + Parameters + ---------- + lmb : scalar + Parameter for Yeo-Johnson transformation. See `yeojohnson` for + details. + data : array_like + Data to calculate Yeo-Johnson log-likelihood for. If `data` is + multi-dimensional, the log-likelihood is calculated along the first + axis. + + Returns + ------- + llf : float + Yeo-Johnson log-likelihood of `data` given `lmb`. + + See Also + -------- + yeojohnson, probplot, yeojohnson_normplot, yeojohnson_normmax + + Notes + ----- + The Yeo-Johnson log-likelihood function is defined here as + + .. math:: + + llf = -N/2 \log(\hat{\sigma}^2) + (\lambda - 1) + \sum_i \text{ sign }(x_i)\log(|x_i| + 1) + + where :math:`\hat{\sigma}^2` is estimated variance of the Yeo-Johnson + transformed input data ``x``. + + .. versionadded:: 1.2.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes + + Generate some random variates and calculate Yeo-Johnson log-likelihood + values for them for a range of ``lmbda`` values: + + >>> x = stats.loggamma.rvs(5, loc=10, size=1000) + >>> lmbdas = np.linspace(-2, 10) + >>> llf = np.zeros(lmbdas.shape, dtype=float) + >>> for ii, lmbda in enumerate(lmbdas): + ... llf[ii] = stats.yeojohnson_llf(lmbda, x) + + Also find the optimal lmbda value with `yeojohnson`: + + >>> x_most_normal, lmbda_optimal = stats.yeojohnson(x) + + Plot the log-likelihood as function of lmbda. Add the optimal lmbda as a + horizontal line to check that that's really the optimum: + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(lmbdas, llf, 'b.-') + >>> ax.axhline(stats.yeojohnson_llf(lmbda_optimal, x), color='r') + >>> ax.set_xlabel('lmbda parameter') + >>> ax.set_ylabel('Yeo-Johnson log-likelihood') + + Now add some probability plots to show that where the log-likelihood is + maximized the data transformed with `yeojohnson` looks closest to normal: + + >>> locs = [3, 10, 4] # 'lower left', 'center', 'lower right' + >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs): + ... xt = stats.yeojohnson(x, lmbda=lmbda) + ... (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt) + ... ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc) + ... ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-') + ... ax_inset.set_xticklabels([]) + ... ax_inset.set_yticklabels([]) + ... ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda) + + >>> plt.show() + + """ + data = np.asarray(data) + n_samples = data.shape[0] + + if n_samples == 0: + return np.nan + + trans = _yeojohnson_transform(data, lmb) + trans_var = trans.var(axis=0) + loglike = np.empty_like(trans_var) + + # Avoid RuntimeWarning raised by np.log when the variance is too low + tiny_variance = trans_var < np.finfo(trans_var.dtype).tiny + loglike[tiny_variance] = np.inf + + loglike[~tiny_variance] = ( + -n_samples / 2 * np.log(trans_var[~tiny_variance])) + loglike[~tiny_variance] += ( + (lmb - 1) * (np.sign(data) * np.log1p(np.abs(data))).sum(axis=0)) + return loglike + + +def yeojohnson_normmax(x, brack=None): + """Compute optimal Yeo-Johnson transform parameter. + + Compute optimal Yeo-Johnson transform parameter for input data, using + maximum likelihood estimation. + + Parameters + ---------- + x : array_like + Input array. + brack : 2-tuple, optional + The starting interval for a downhill bracket search with + `optimize.brent`. Note that this is in most cases not critical; the + final result is allowed to be outside this bracket. If None, + `optimize.fminbound` is used with bounds that avoid overflow. + + Returns + ------- + maxlog : float + The optimal transform parameter found. + + See Also + -------- + yeojohnson, yeojohnson_llf, yeojohnson_normplot + + Notes + ----- + .. versionadded:: 1.2.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Generate some data and determine optimal ``lmbda`` + + >>> rng = np.random.default_rng() + >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5 + >>> lmax = stats.yeojohnson_normmax(x) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.yeojohnson_normplot(x, -10, 10, plot=ax) + >>> ax.axvline(lmax, color='r') + + >>> plt.show() + + """ + def _neg_llf(lmbda, data): + llf = yeojohnson_llf(lmbda, data) + # reject likelihoods that are inf which are likely due to small + # variance in the transformed space + llf[np.isinf(llf)] = -np.inf + return -llf + + with np.errstate(invalid='ignore'): + if not np.all(np.isfinite(x)): + raise ValueError('Yeo-Johnson input must be finite.') + if np.all(x == 0): + return 1.0 + if brack is not None: + return optimize.brent(_neg_llf, brack=brack, args=(x,)) + x = np.asarray(x) + dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64 + # Allow values up to 20 times the maximum observed value to be safely + # transformed without over- or underflow. + log1p_max_x = np.log1p(20 * np.max(np.abs(x))) + # Use half of floating point's exponent range to allow safe computation + # of the variance of the transformed data. + log_eps = np.log(np.finfo(dtype).eps) + log_tiny_float = (np.log(np.finfo(dtype).tiny) - log_eps) / 2 + log_max_float = (np.log(np.finfo(dtype).max) + log_eps) / 2 + # Compute the bounds by approximating the inverse of the Yeo-Johnson + # transform on the smallest and largest floating point exponents, given + # the largest data we expect to observe. See [1] for further details. + # [1] https://github.com/scipy/scipy/pull/18852#issuecomment-1630286174 + lb = log_tiny_float / log1p_max_x + ub = log_max_float / log1p_max_x + # Convert the bounds if all or some of the data is negative. + if np.all(x < 0): + lb, ub = 2 - ub, 2 - lb + elif np.any(x < 0): + lb, ub = max(2 - ub, lb), min(2 - lb, ub) + # Match `optimize.brent`'s tolerance. + tol_brent = 1.48e-08 + return optimize.fminbound(_neg_llf, lb, ub, args=(x,), xtol=tol_brent) + + +def yeojohnson_normplot(x, la, lb, plot=None, N=80): + """Compute parameters for a Yeo-Johnson normality plot, optionally show it. + + A Yeo-Johnson normality plot shows graphically what the best + transformation parameter is to use in `yeojohnson` to obtain a + distribution that is close to normal. + + Parameters + ---------- + x : array_like + Input array. + la, lb : scalar + The lower and upper bounds for the ``lmbda`` values to pass to + `yeojohnson` for Yeo-Johnson transformations. These are also the + limits of the horizontal axis of the plot if that is generated. + plot : object, optional + If given, plots the quantiles and least squares fit. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + N : int, optional + Number of points on the horizontal axis (equally distributed from + `la` to `lb`). + + Returns + ------- + lmbdas : ndarray + The ``lmbda`` values for which a Yeo-Johnson transform was done. + ppcc : ndarray + Probability Plot Correlation Coefficient, as obtained from `probplot` + when fitting the Box-Cox transformed input `x` against a normal + distribution. + + See Also + -------- + probplot, yeojohnson, yeojohnson_normmax, yeojohnson_llf, ppcc_max + + Notes + ----- + Even if `plot` is given, the figure is not shown or saved by + `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')`` + should be used after calling `probplot`. + + .. versionadded:: 1.2.0 + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Generate some non-normally distributed data, and create a Yeo-Johnson plot: + + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.yeojohnson_normplot(x, -20, 20, plot=ax) + + Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in + the same plot: + + >>> _, maxlog = stats.yeojohnson(x) + >>> ax.axvline(maxlog, color='r') + + >>> plt.show() + + """ + return _normplot('yeojohnson', x, la, lb, plot, N) + + +ShapiroResult = namedtuple('ShapiroResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(ShapiroResult, n_samples=1, too_small=2, default_axis=None) +def shapiro(x): + r"""Perform the Shapiro-Wilk test for normality. + + The Shapiro-Wilk test tests the null hypothesis that the + data was drawn from a normal distribution. + + Parameters + ---------- + x : array_like + Array of sample data. Must contain at least three observations. + + Returns + ------- + statistic : float + The test statistic. + p-value : float + The p-value for the hypothesis test. + + See Also + -------- + anderson : The Anderson-Darling test for normality + kstest : The Kolmogorov-Smirnov test for goodness of fit. + :ref:`hypothesis_shapiro` : Extended example + + Notes + ----- + The algorithm used is described in [4]_ but censoring parameters as + described are not implemented. For N > 5000 the W test statistic is + accurate, but the p-value may not be. + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm + :doi:`10.18434/M32189` + .. [2] Shapiro, S. S. & Wilk, M.B, "An analysis of variance test for + normality (complete samples)", Biometrika, 1965, Vol. 52, + pp. 591-611, :doi:`10.2307/2333709` + .. [3] Razali, N. M. & Wah, Y. B., "Power comparisons of Shapiro-Wilk, + Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests", Journal + of Statistical Modeling and Analytics, 2011, Vol. 2, pp. 21-33. + .. [4] Royston P., "Remark AS R94: A Remark on Algorithm AS 181: The + W-test for Normality", 1995, Applied Statistics, Vol. 44, + :doi:`10.2307/2986146` + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = stats.norm.rvs(loc=5, scale=3, size=100, random_state=rng) + >>> shapiro_test = stats.shapiro(x) + >>> shapiro_test + ShapiroResult(statistic=0.9813305735588074, pvalue=0.16855233907699585) + >>> shapiro_test.statistic + 0.9813305735588074 + >>> shapiro_test.pvalue + 0.16855233907699585 + + For a more detailed example, see :ref:`hypothesis_shapiro`. + """ + x = np.ravel(x).astype(np.float64) + + N = len(x) + if N < 3: + raise ValueError("Data must be at least length 3.") + + a = zeros(N//2, dtype=np.float64) + init = 0 + + y = sort(x) + y -= x[N//2] # subtract the median (or a nearby value); see gh-15777 + + w, pw, ifault = swilk(y, a, init) + if ifault not in [0, 2]: + warnings.warn("scipy.stats.shapiro: Input data has range zero. The" + " results may not be accurate.", stacklevel=2) + if N > 5000: + warnings.warn("scipy.stats.shapiro: For N > 5000, computed p-value " + f"may not be accurate. Current N is {N}.", + stacklevel=2) + + # `w` and `pw` are always Python floats, which are double precision. + # We want to ensure that they are NumPy floats, so until dtypes are + # respected, we can explicitly convert each to float64 (faster than + # `np.array([w, pw])`). + return ShapiroResult(np.float64(w), np.float64(pw)) + + +# Values from Stephens, M A, "EDF Statistics for Goodness of Fit and +# Some Comparisons", Journal of the American Statistical +# Association, Vol. 69, Issue 347, Sept. 1974, pp 730-737 +_Avals_norm = array([0.576, 0.656, 0.787, 0.918, 1.092]) +_Avals_expon = array([0.922, 1.078, 1.341, 1.606, 1.957]) +# From Stephens, M A, "Goodness of Fit for the Extreme Value Distribution", +# Biometrika, Vol. 64, Issue 3, Dec. 1977, pp 583-588. +_Avals_gumbel = array([0.474, 0.637, 0.757, 0.877, 1.038]) +# From Stephens, M A, "Tests of Fit for the Logistic Distribution Based +# on the Empirical Distribution Function.", Biometrika, +# Vol. 66, Issue 3, Dec. 1979, pp 591-595. +_Avals_logistic = array([0.426, 0.563, 0.660, 0.769, 0.906, 1.010]) +# From Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of +# Fit for the Three-Parameter Weibull Distribution" +# Journal of the Royal Statistical Society.Series B(Methodological) +# Vol. 56, No. 3 (1994), pp. 491-500, table 1. Keys are c*100 +_Avals_weibull = [[0.292, 0.395, 0.467, 0.522, 0.617, 0.711, 0.836, 0.931], + [0.295, 0.399, 0.471, 0.527, 0.623, 0.719, 0.845, 0.941], + [0.298, 0.403, 0.476, 0.534, 0.631, 0.728, 0.856, 0.954], + [0.301, 0.408, 0.483, 0.541, 0.640, 0.738, 0.869, 0.969], + [0.305, 0.414, 0.490, 0.549, 0.650, 0.751, 0.885, 0.986], + [0.309, 0.421, 0.498, 0.559, 0.662, 0.765, 0.902, 1.007], + [0.314, 0.429, 0.508, 0.570, 0.676, 0.782, 0.923, 1.030], + [0.320, 0.438, 0.519, 0.583, 0.692, 0.802, 0.947, 1.057], + [0.327, 0.448, 0.532, 0.598, 0.711, 0.824, 0.974, 1.089], + [0.334, 0.469, 0.547, 0.615, 0.732, 0.850, 1.006, 1.125], + [0.342, 0.472, 0.563, 0.636, 0.757, 0.879, 1.043, 1.167]] +_Avals_weibull = np.array(_Avals_weibull) +_cvals_weibull = np.linspace(0, 0.5, 11) +_get_As_weibull = interpolate.interp1d(_cvals_weibull, _Avals_weibull.T, + kind='linear', bounds_error=False, + fill_value=_Avals_weibull[-1]) + + +def _weibull_fit_check(params, x): + # Refine the fit returned by `weibull_min.fit` to ensure that the first + # order necessary conditions are satisfied. If not, raise an error. + # Here, use `m` for the shape parameter to be consistent with [7] + # and avoid confusion with `c` as defined in [7]. + n = len(x) + m, u, s = params + + def dnllf_dm(m, u): + # Partial w.r.t. shape w/ optimal scale. See [7] Equation 5. + xu = x-u + return (1/m - (xu**m*np.log(xu)).sum()/(xu**m).sum() + + np.log(xu).sum()/n) + + def dnllf_du(m, u): + # Partial w.r.t. loc w/ optimal scale. See [7] Equation 6. + xu = x-u + return (m-1)/m*(xu**-1).sum() - n*(xu**(m-1)).sum()/(xu**m).sum() + + def get_scale(m, u): + # Partial w.r.t. scale solved in terms of shape and location. + # See [7] Equation 7. + return ((x-u)**m/n).sum()**(1/m) + + def dnllf(params): + # Partial derivatives of the NLLF w.r.t. parameters, i.e. + # first order necessary conditions for MLE fit. + return [dnllf_dm(*params), dnllf_du(*params)] + + suggestion = ("Maximum likelihood estimation is known to be challenging " + "for the three-parameter Weibull distribution. Consider " + "performing a custom goodness-of-fit test using " + "`scipy.stats.monte_carlo_test`.") + + if np.allclose(u, np.min(x)) or m < 1: + # The critical values provided by [7] don't seem to control the + # Type I error rate in this case. Error out. + message = ("Maximum likelihood estimation has converged to " + "a solution in which the location is equal to the minimum " + "of the data, the shape parameter is less than 2, or both. " + "The table of critical values in [7] does not " + "include this case. " + suggestion) + raise ValueError(message) + + try: + # Refine the MLE / verify that first-order necessary conditions are + # satisfied. If so, the critical values provided in [7] seem reliable. + with np.errstate(over='raise', invalid='raise'): + res = optimize.root(dnllf, params[:-1]) + + message = ("Solution of MLE first-order conditions failed: " + f"{res.message}. `anderson` cannot continue. " + suggestion) + if not res.success: + raise ValueError(message) + + except (FloatingPointError, ValueError) as e: + message = ("An error occurred while fitting the Weibull distribution " + "to the data, so `anderson` cannot continue. " + suggestion) + raise ValueError(message) from e + + m, u = res.x + s = get_scale(m, u) + return m, u, s + + +AndersonResult = _make_tuple_bunch('AndersonResult', + ['statistic', 'critical_values', + 'significance_level'], ['fit_result']) + + +def anderson(x, dist='norm'): + """Anderson-Darling test for data coming from a particular distribution. + + The Anderson-Darling test tests the null hypothesis that a sample is + drawn from a population that follows a particular distribution. + For the Anderson-Darling test, the critical values depend on + which distribution is being tested against. This function works + for normal, exponential, logistic, weibull_min, or Gumbel (Extreme Value + Type I) distributions. + + Parameters + ---------- + x : array_like + Array of sample data. + dist : {'norm', 'expon', 'logistic', 'gumbel', 'gumbel_l', 'gumbel_r', 'extreme1', 'weibull_min'}, optional + The type of distribution to test against. The default is 'norm'. + The names 'extreme1', 'gumbel_l' and 'gumbel' are synonyms for the + same distribution. + + Returns + ------- + result : AndersonResult + An object with the following attributes: + + statistic : float + The Anderson-Darling test statistic. + critical_values : list + The critical values for this distribution. + significance_level : list + The significance levels for the corresponding critical values + in percents. The function returns critical values for a + differing set of significance levels depending on the + distribution that is being tested against. + fit_result : `~scipy.stats._result_classes.FitResult` + An object containing the results of fitting the distribution to + the data. + + See Also + -------- + kstest : The Kolmogorov-Smirnov test for goodness-of-fit. + + Notes + ----- + Critical values provided are for the following significance levels: + + normal/exponential + 15%, 10%, 5%, 2.5%, 1% + logistic + 25%, 10%, 5%, 2.5%, 1%, 0.5% + gumbel_l / gumbel_r + 25%, 10%, 5%, 2.5%, 1% + weibull_min + 50%, 25%, 15%, 10%, 5%, 2.5%, 1%, 0.5% + + If the returned statistic is larger than these critical values then + for the corresponding significance level, the null hypothesis that + the data come from the chosen distribution can be rejected. + The returned statistic is referred to as 'A2' in the references. + + For `weibull_min`, maximum likelihood estimation is known to be + challenging. If the test returns successfully, then the first order + conditions for a maximum likelihood estimate have been verified and + the critical values correspond relatively well to the significance levels, + provided that the sample is sufficiently large (>10 observations [7]). + However, for some data - especially data with no left tail - `anderson` + is likely to result in an error message. In this case, consider + performing a custom goodness of fit test using + `scipy.stats.monte_carlo_test`. + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm + .. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and + Some Comparisons, Journal of the American Statistical Association, + Vol. 69, pp. 730-737. + .. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit + Statistics with Unknown Parameters, Annals of Statistics, Vol. 4, + pp. 357-369. + .. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value + Distribution, Biometrika, Vol. 64, pp. 583-588. + .. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference + to Tests for Exponentiality , Technical Report No. 262, + Department of Statistics, Stanford University, Stanford, CA. + .. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution + Based on the Empirical Distribution Function, Biometrika, Vol. 66, + pp. 591-595. + .. [7] Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of + Fit for the Three-Parameter Weibull Distribution" + Journal of the Royal Statistical Society.Series B(Methodological) + Vol. 56, No. 3 (1994), pp. 491-500, Table 0. + + Examples + -------- + Test the null hypothesis that a random sample was drawn from a normal + distribution (with unspecified mean and standard deviation). + + >>> import numpy as np + >>> from scipy.stats import anderson + >>> rng = np.random.default_rng() + >>> data = rng.random(size=35) + >>> res = anderson(data) + >>> res.statistic + 0.8398018749744764 + >>> res.critical_values + array([0.527, 0.6 , 0.719, 0.839, 0.998]) + >>> res.significance_level + array([15. , 10. , 5. , 2.5, 1. ]) + + The value of the statistic (barely) exceeds the critical value associated + with a significance level of 2.5%, so the null hypothesis may be rejected + at a significance level of 2.5%, but not at a significance level of 1%. + + """ # numpy/numpydoc#87 # noqa: E501 + dist = dist.lower() + if dist in {'extreme1', 'gumbel'}: + dist = 'gumbel_l' + dists = {'norm', 'expon', 'gumbel_l', + 'gumbel_r', 'logistic', 'weibull_min'} + + if dist not in dists: + raise ValueError(f"Invalid distribution; dist must be in {dists}.") + y = sort(x) + xbar = np.mean(x, axis=0) + N = len(y) + if dist == 'norm': + s = np.std(x, ddof=1, axis=0) + w = (y - xbar) / s + fit_params = xbar, s + logcdf = distributions.norm.logcdf(w) + logsf = distributions.norm.logsf(w) + sig = array([15, 10, 5, 2.5, 1]) + critical = around(_Avals_norm / (1.0 + 4.0/N - 25.0/N/N), 3) + elif dist == 'expon': + w = y / xbar + fit_params = 0, xbar + logcdf = distributions.expon.logcdf(w) + logsf = distributions.expon.logsf(w) + sig = array([15, 10, 5, 2.5, 1]) + critical = around(_Avals_expon / (1.0 + 0.6/N), 3) + elif dist == 'logistic': + def rootfunc(ab, xj, N): + a, b = ab + tmp = (xj - a) / b + tmp2 = exp(tmp) + val = [np.sum(1.0/(1+tmp2), axis=0) - 0.5*N, + np.sum(tmp*(1.0-tmp2)/(1+tmp2), axis=0) + N] + return array(val) + + sol0 = array([xbar, np.std(x, ddof=1, axis=0)]) + sol = optimize.fsolve(rootfunc, sol0, args=(x, N), xtol=1e-5) + w = (y - sol[0]) / sol[1] + fit_params = sol + logcdf = distributions.logistic.logcdf(w) + logsf = distributions.logistic.logsf(w) + sig = array([25, 10, 5, 2.5, 1, 0.5]) + critical = around(_Avals_logistic / (1.0 + 0.25/N), 3) + elif dist == 'gumbel_r': + xbar, s = distributions.gumbel_r.fit(x) + w = (y - xbar) / s + fit_params = xbar, s + logcdf = distributions.gumbel_r.logcdf(w) + logsf = distributions.gumbel_r.logsf(w) + sig = array([25, 10, 5, 2.5, 1]) + critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3) + elif dist == 'gumbel_l': + xbar, s = distributions.gumbel_l.fit(x) + w = (y - xbar) / s + fit_params = xbar, s + logcdf = distributions.gumbel_l.logcdf(w) + logsf = distributions.gumbel_l.logsf(w) + sig = array([25, 10, 5, 2.5, 1]) + critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3) + elif dist == 'weibull_min': + message = ("Critical values of the test statistic are given for the " + "asymptotic distribution. These may not be accurate for " + "samples with fewer than 10 observations. Consider using " + "`scipy.stats.monte_carlo_test`.") + if N < 10: + warnings.warn(message, stacklevel=2) + # [7] writes our 'c' as 'm', and they write `c = 1/m`. Use their names. + m, loc, scale = distributions.weibull_min.fit(y) + m, loc, scale = _weibull_fit_check((m, loc, scale), y) + fit_params = m, loc, scale + logcdf = stats.weibull_min(*fit_params).logcdf(y) + logsf = stats.weibull_min(*fit_params).logsf(y) + c = 1 / m # m and c are as used in [7] + sig = array([0.5, 0.75, 0.85, 0.9, 0.95, 0.975, 0.99, 0.995]) + critical = _get_As_weibull(c) + # Goodness-of-fit tests should only be used to provide evidence + # _against_ the null hypothesis. Be conservative and round up. + critical = np.round(critical + 0.0005, decimals=3) + + i = arange(1, N + 1) + A2 = -N - np.sum((2*i - 1.0) / N * (logcdf + logsf[::-1]), axis=0) + + # FitResult initializer expects an optimize result, so let's work with it + message = '`anderson` successfully fit the distribution to the data.' + res = optimize.OptimizeResult(success=True, message=message) + res.x = np.array(fit_params) + fit_result = FitResult(getattr(distributions, dist), y, + discrete=False, res=res) + + return AndersonResult(A2, critical, sig, fit_result=fit_result) + + +def _anderson_ksamp_midrank(samples, Z, Zstar, k, n, N): + """Compute A2akN equation 7 of Scholz and Stephens. + + Parameters + ---------- + samples : sequence of 1-D array_like + Array of sample arrays. + Z : array_like + Sorted array of all observations. + Zstar : array_like + Sorted array of unique observations. + k : int + Number of samples. + n : array_like + Number of observations in each sample. + N : int + Total number of observations. + + Returns + ------- + A2aKN : float + The A2aKN statistics of Scholz and Stephens 1987. + + """ + A2akN = 0. + Z_ssorted_left = Z.searchsorted(Zstar, 'left') + if N == Zstar.size: + lj = 1. + else: + lj = Z.searchsorted(Zstar, 'right') - Z_ssorted_left + Bj = Z_ssorted_left + lj / 2. + for i in arange(0, k): + s = np.sort(samples[i]) + s_ssorted_right = s.searchsorted(Zstar, side='right') + Mij = s_ssorted_right.astype(float) + fij = s_ssorted_right - s.searchsorted(Zstar, 'left') + Mij -= fij / 2. + inner = lj / float(N) * (N*Mij - Bj*n[i])**2 / (Bj*(N - Bj) - N*lj/4.) + A2akN += inner.sum() / n[i] + A2akN *= (N - 1.) / N + return A2akN + + +def _anderson_ksamp_right(samples, Z, Zstar, k, n, N): + """Compute A2akN equation 6 of Scholz & Stephens. + + Parameters + ---------- + samples : sequence of 1-D array_like + Array of sample arrays. + Z : array_like + Sorted array of all observations. + Zstar : array_like + Sorted array of unique observations. + k : int + Number of samples. + n : array_like + Number of observations in each sample. + N : int + Total number of observations. + + Returns + ------- + A2KN : float + The A2KN statistics of Scholz and Stephens 1987. + + """ + A2kN = 0. + lj = Z.searchsorted(Zstar[:-1], 'right') - Z.searchsorted(Zstar[:-1], + 'left') + Bj = lj.cumsum() + for i in arange(0, k): + s = np.sort(samples[i]) + Mij = s.searchsorted(Zstar[:-1], side='right') + inner = lj / float(N) * (N * Mij - Bj * n[i])**2 / (Bj * (N - Bj)) + A2kN += inner.sum() / n[i] + return A2kN + + +Anderson_ksampResult = _make_tuple_bunch( + 'Anderson_ksampResult', + ['statistic', 'critical_values', 'pvalue'], [] +) + + +def anderson_ksamp(samples, midrank=True, *, method=None): + """The Anderson-Darling test for k-samples. + + The k-sample Anderson-Darling test is a modification of the + one-sample Anderson-Darling test. It tests the null hypothesis + that k-samples are drawn from the same population without having + to specify the distribution function of that population. The + critical values depend on the number of samples. + + Parameters + ---------- + samples : sequence of 1-D array_like + Array of sample data in arrays. + midrank : bool, optional + Type of Anderson-Darling test which is computed. Default + (True) is the midrank test applicable to continuous and + discrete populations. If False, the right side empirical + distribution is used. + method : PermutationMethod, optional + Defines the method used to compute the p-value. If `method` is an + instance of `PermutationMethod`, the p-value is computed using + `scipy.stats.permutation_test` with the provided configuration options + and other appropriate settings. Otherwise, the p-value is interpolated + from tabulated values. + + Returns + ------- + res : Anderson_ksampResult + An object containing attributes: + + statistic : float + Normalized k-sample Anderson-Darling test statistic. + critical_values : array + The critical values for significance levels 25%, 10%, 5%, 2.5%, 1%, + 0.5%, 0.1%. + pvalue : float + The approximate p-value of the test. If `method` is not + provided, the value is floored / capped at 0.1% / 25%. + + Raises + ------ + ValueError + If fewer than 2 samples are provided, a sample is empty, or no + distinct observations are in the samples. + + See Also + -------- + ks_2samp : 2 sample Kolmogorov-Smirnov test + anderson : 1 sample Anderson-Darling test + + Notes + ----- + [1]_ defines three versions of the k-sample Anderson-Darling test: + one for continuous distributions and two for discrete + distributions, in which ties between samples may occur. The + default of this routine is to compute the version based on the + midrank empirical distribution function. This test is applicable + to continuous and discrete data. If midrank is set to False, the + right side empirical distribution is used for a test for discrete + data. According to [1]_, the two discrete test statistics differ + only slightly if a few collisions due to round-off errors occur in + the test not adjusted for ties between samples. + + The critical values corresponding to the significance levels from 0.01 + to 0.25 are taken from [1]_. p-values are floored / capped + at 0.1% / 25%. Since the range of critical values might be extended in + future releases, it is recommended not to test ``p == 0.25``, but rather + ``p >= 0.25`` (analogously for the lower bound). + + .. versionadded:: 0.14.0 + + References + ---------- + .. [1] Scholz, F. W and Stephens, M. A. (1987), K-Sample + Anderson-Darling Tests, Journal of the American Statistical + Association, Vol. 82, pp. 918-924. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> res = stats.anderson_ksamp([rng.normal(size=50), + ... rng.normal(loc=0.5, size=30)]) + >>> res.statistic, res.pvalue + (1.974403288713695, 0.04991293614572478) + >>> res.critical_values + array([0.325, 1.226, 1.961, 2.718, 3.752, 4.592, 6.546]) + + The null hypothesis that the two random samples come from the same + distribution can be rejected at the 5% level because the returned + test value is greater than the critical value for 5% (1.961) but + not at the 2.5% level. The interpolation gives an approximate + p-value of 4.99%. + + >>> samples = [rng.normal(size=50), rng.normal(size=30), + ... rng.normal(size=20)] + >>> res = stats.anderson_ksamp(samples) + >>> res.statistic, res.pvalue + (-0.29103725200789504, 0.25) + >>> res.critical_values + array([ 0.44925884, 1.3052767 , 1.9434184 , 2.57696569, 3.41634856, + 4.07210043, 5.56419101]) + + The null hypothesis cannot be rejected for three samples from an + identical distribution. The reported p-value (25%) has been capped and + may not be very accurate (since it corresponds to the value 0.449 + whereas the statistic is -0.291). + + In such cases where the p-value is capped or when sample sizes are + small, a permutation test may be more accurate. + + >>> method = stats.PermutationMethod(n_resamples=9999, random_state=rng) + >>> res = stats.anderson_ksamp(samples, method=method) + >>> res.pvalue + 0.5254 + + """ + k = len(samples) + if (k < 2): + raise ValueError("anderson_ksamp needs at least two samples") + + samples = list(map(np.asarray, samples)) + Z = np.sort(np.hstack(samples)) + N = Z.size + Zstar = np.unique(Z) + if Zstar.size < 2: + raise ValueError("anderson_ksamp needs more than one distinct " + "observation") + + n = np.array([sample.size for sample in samples]) + if np.any(n == 0): + raise ValueError("anderson_ksamp encountered sample without " + "observations") + + if midrank: + A2kN_fun = _anderson_ksamp_midrank + else: + A2kN_fun = _anderson_ksamp_right + A2kN = A2kN_fun(samples, Z, Zstar, k, n, N) + + def statistic(*samples): + return A2kN_fun(samples, Z, Zstar, k, n, N) + + if method is not None: + res = stats.permutation_test(samples, statistic, **method._asdict(), + alternative='greater') + + H = (1. / n).sum() + hs_cs = (1. / arange(N - 1, 1, -1)).cumsum() + h = hs_cs[-1] + 1 + g = (hs_cs / arange(2, N)).sum() + + a = (4*g - 6) * (k - 1) + (10 - 6*g)*H + b = (2*g - 4)*k**2 + 8*h*k + (2*g - 14*h - 4)*H - 8*h + 4*g - 6 + c = (6*h + 2*g - 2)*k**2 + (4*h - 4*g + 6)*k + (2*h - 6)*H + 4*h + d = (2*h + 6)*k**2 - 4*h*k + sigmasq = (a*N**3 + b*N**2 + c*N + d) / ((N - 1.) * (N - 2.) * (N - 3.)) + m = k - 1 + A2 = (A2kN - m) / math.sqrt(sigmasq) + + # The b_i values are the interpolation coefficients from Table 2 + # of Scholz and Stephens 1987 + b0 = np.array([0.675, 1.281, 1.645, 1.96, 2.326, 2.573, 3.085]) + b1 = np.array([-0.245, 0.25, 0.678, 1.149, 1.822, 2.364, 3.615]) + b2 = np.array([-0.105, -0.305, -0.362, -0.391, -0.396, -0.345, -0.154]) + critical = b0 + b1 / math.sqrt(m) + b2 / m + + sig = np.array([0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.001]) + + if A2 < critical.min() and method is None: + p = sig.max() + msg = (f"p-value capped: true value larger than {p}. Consider " + "specifying `method` " + "(e.g. `method=stats.PermutationMethod()`.)") + warnings.warn(msg, stacklevel=2) + elif A2 > critical.max() and method is None: + p = sig.min() + msg = (f"p-value floored: true value smaller than {p}. Consider " + "specifying `method` " + "(e.g. `method=stats.PermutationMethod()`.)") + warnings.warn(msg, stacklevel=2) + elif method is None: + # interpolation of probit of significance level + pf = np.polyfit(critical, log(sig), 2) + p = math.exp(np.polyval(pf, A2)) + else: + p = res.pvalue if method is not None else p + + # create result object with alias for backward compatibility + res = Anderson_ksampResult(A2, critical, p) + res.significance_level = p + return res + + +AnsariResult = namedtuple('AnsariResult', ('statistic', 'pvalue')) + + +class _ABW: + """Distribution of Ansari-Bradley W-statistic under the null hypothesis.""" + # TODO: calculate exact distribution considering ties + # We could avoid summing over more than half the frequencies, + # but initially it doesn't seem worth the extra complexity + + def __init__(self): + """Minimal initializer.""" + self.m = None + self.n = None + self.astart = None + self.total = None + self.freqs = None + + def _recalc(self, n, m): + """When necessary, recalculate exact distribution.""" + if n != self.n or m != self.m: + self.n, self.m = n, m + # distribution is NOT symmetric when m + n is odd + # n is len(x), m is len(y), and ratio of scales is defined x/y + astart, a1, _ = gscale(n, m) + self.astart = astart # minimum value of statistic + # Exact distribution of test statistic under null hypothesis + # expressed as frequencies/counts/integers to maintain precision. + # Stored as floats to avoid overflow of sums. + self.freqs = a1.astype(np.float64) + self.total = self.freqs.sum() # could calculate from m and n + # probability mass is self.freqs / self.total; + + def pmf(self, k, n, m): + """Probability mass function.""" + self._recalc(n, m) + # The convention here is that PMF at k = 12.5 is the same as at k = 12, + # -> use `floor` in case of ties. + ind = np.floor(k - self.astart).astype(int) + return self.freqs[ind] / self.total + + def cdf(self, k, n, m): + """Cumulative distribution function.""" + self._recalc(n, m) + # Null distribution derived without considering ties is + # approximate. Round down to avoid Type I error. + ind = np.ceil(k - self.astart).astype(int) + return self.freqs[:ind+1].sum() / self.total + + def sf(self, k, n, m): + """Survival function.""" + self._recalc(n, m) + # Null distribution derived without considering ties is + # approximate. Round down to avoid Type I error. + ind = np.floor(k - self.astart).astype(int) + return self.freqs[ind:].sum() / self.total + + +# Maintain state for faster repeat calls to ansari w/ method='exact' +# _ABW() is calculated once per thread and stored as an attribute on +# this thread-local variable inside ansari(). +_abw_state = threading.local() + + +@_axis_nan_policy_factory(AnsariResult, n_samples=2) +def ansari(x, y, alternative='two-sided'): + """Perform the Ansari-Bradley test for equal scale parameters. + + The Ansari-Bradley test ([1]_, [2]_) is a non-parametric test + for the equality of the scale parameter of the distributions + from which two samples were drawn. The null hypothesis states that + the ratio of the scale of the distribution underlying `x` to the scale + of the distribution underlying `y` is 1. + + Parameters + ---------- + x, y : array_like + Arrays of sample data. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the ratio of scales is not equal to 1. + * 'less': the ratio of scales is less than 1. + * 'greater': the ratio of scales is greater than 1. + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The Ansari-Bradley test statistic. + pvalue : float + The p-value of the hypothesis test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + mood : A non-parametric test for the equality of two scale parameters + + Notes + ----- + The p-value given is exact when the sample sizes are both less than + 55 and there are no ties, otherwise a normal approximation for the + p-value is used. + + References + ---------- + .. [1] Ansari, A. R. and Bradley, R. A. (1960) Rank-sum tests for + dispersions, Annals of Mathematical Statistics, 31, 1174-1189. + .. [2] Sprent, Peter and N.C. Smeeton. Applied nonparametric + statistical methods. 3rd ed. Chapman and Hall/CRC. 2001. + Section 5.8.2. + .. [3] Nathaniel E. Helwig "Nonparametric Dispersion and Equality + Tests" at http://users.stat.umn.edu/~helwig/notes/npde-Notes.pdf + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import ansari + >>> rng = np.random.default_rng() + + For these examples, we'll create three random data sets. The first + two, with sizes 35 and 25, are drawn from a normal distribution with + mean 0 and standard deviation 2. The third data set has size 25 and + is drawn from a normal distribution with standard deviation 1.25. + + >>> x1 = rng.normal(loc=0, scale=2, size=35) + >>> x2 = rng.normal(loc=0, scale=2, size=25) + >>> x3 = rng.normal(loc=0, scale=1.25, size=25) + + First we apply `ansari` to `x1` and `x2`. These samples are drawn + from the same distribution, so we expect the Ansari-Bradley test + should not lead us to conclude that the scales of the distributions + are different. + + >>> ansari(x1, x2) + AnsariResult(statistic=541.0, pvalue=0.9762532927399098) + + With a p-value close to 1, we cannot conclude that there is a + significant difference in the scales (as expected). + + Now apply the test to `x1` and `x3`: + + >>> ansari(x1, x3) + AnsariResult(statistic=425.0, pvalue=0.0003087020407974518) + + The probability of observing such an extreme value of the statistic + under the null hypothesis of equal scales is only 0.03087%. We take this + as evidence against the null hypothesis in favor of the alternative: + the scales of the distributions from which the samples were drawn + are not equal. + + We can use the `alternative` parameter to perform a one-tailed test. + In the above example, the scale of `x1` is greater than `x3` and so + the ratio of scales of `x1` and `x3` is greater than 1. This means + that the p-value when ``alternative='greater'`` should be near 0 and + hence we should be able to reject the null hypothesis: + + >>> ansari(x1, x3, alternative='greater') + AnsariResult(statistic=425.0, pvalue=0.0001543510203987259) + + As we can see, the p-value is indeed quite low. Use of + ``alternative='less'`` should thus yield a large p-value: + + >>> ansari(x1, x3, alternative='less') + AnsariResult(statistic=425.0, pvalue=0.9998643258449039) + + """ + if alternative not in {'two-sided', 'greater', 'less'}: + raise ValueError("'alternative' must be 'two-sided'," + " 'greater', or 'less'.") + + if not hasattr(_abw_state, 'a'): + _abw_state.a = _ABW() + + x, y = asarray(x), asarray(y) + n = len(x) + m = len(y) + if m < 1: + raise ValueError("Not enough other observations.") + if n < 1: + raise ValueError("Not enough test observations.") + + N = m + n + xy = r_[x, y] # combine + rank = _stats_py.rankdata(xy) + symrank = amin(array((rank, N - rank + 1)), 0) + AB = np.sum(symrank[:n], axis=0) + uxy = unique(xy) + repeats = (len(uxy) != len(xy)) + exact = ((m < 55) and (n < 55) and not repeats) + if repeats and (m < 55 or n < 55): + warnings.warn("Ties preclude use of exact statistic.", stacklevel=2) + if exact: + if alternative == 'two-sided': + pval = 2.0 * np.minimum(_abw_state.a.cdf(AB, n, m), + _abw_state.a.sf(AB, n, m)) + elif alternative == 'greater': + # AB statistic is _smaller_ when ratio of scales is larger, + # so this is the opposite of the usual calculation + pval = _abw_state.a.cdf(AB, n, m) + else: + pval = _abw_state.a.sf(AB, n, m) + return AnsariResult(AB, min(1.0, pval)) + + # otherwise compute normal approximation + if N % 2: # N odd + mnAB = n * (N+1.0)**2 / 4.0 / N + varAB = n * m * (N+1.0) * (3+N**2) / (48.0 * N**2) + else: + mnAB = n * (N+2.0) / 4.0 + varAB = m * n * (N+2) * (N-2.0) / 48 / (N-1.0) + if repeats: # adjust variance estimates + # compute np.sum(tj * rj**2,axis=0) + fac = np.sum(symrank**2, axis=0) + if N % 2: # N odd + varAB = m * n * (16*N*fac - (N+1)**4) / (16.0 * N**2 * (N-1)) + else: # N even + varAB = m * n * (16*fac - N*(N+2)**2) / (16.0 * N * (N-1)) + + # Small values of AB indicate larger dispersion for the x sample. + # Large values of AB indicate larger dispersion for the y sample. + # This is opposite to the way we define the ratio of scales. see [1]_. + z = (mnAB - AB) / sqrt(varAB) + pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + return AnsariResult(AB[()], pvalue[()]) + + +BartlettResult = namedtuple('BartlettResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(BartlettResult, n_samples=None) +def bartlett(*samples, axis=0): + r"""Perform Bartlett's test for equal variances. + + Bartlett's test tests the null hypothesis that all input samples + are from populations with equal variances. For samples + from significantly non-normal populations, Levene's test + `levene` is more robust. + + Parameters + ---------- + sample1, sample2, ... : array_like + arrays of sample data. Only 1d arrays are accepted, they may have + different lengths. + + Returns + ------- + statistic : float + The test statistic. + pvalue : float + The p-value of the test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + levene : A robust parametric test for equality of k variances + :ref:`hypothesis_bartlett` : Extended example + + Notes + ----- + Conover et al. (1981) examine many of the existing parametric and + nonparametric tests by extensive simulations and they conclude that the + tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be + superior in terms of robustness of departures from normality and power + ([3]_). + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm + .. [2] Snedecor, George W. and Cochran, William G. (1989), Statistical + Methods, Eighth Edition, Iowa State University Press. + .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and + Hypothesis Testing based on Quadratic Inference Function. Technical + Report #99-03, Center for Likelihood Studies, Pennsylvania State + University. + .. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical + Tests. Proceedings of the Royal Society of London. Series A, + Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282. + + Examples + -------- + + Test whether the lists `a`, `b` and `c` come from populations + with equal variances. + + >>> import numpy as np + >>> from scipy import stats + >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99] + >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05] + >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98] + >>> stat, p = stats.bartlett(a, b, c) + >>> p + 1.1254782518834628e-05 + + The very small p-value suggests that the populations do not have equal + variances. + + This is not surprising, given that the sample variance of `b` is much + larger than that of `a` and `c`: + + >>> [np.var(x, ddof=1) for x in [a, b, c]] + [0.007054444444444413, 0.13073888888888888, 0.008890000000000002] + + For a more detailed example, see :ref:`hypothesis_bartlett`. + """ + xp = array_namespace(*samples) + + k = len(samples) + if k < 2: + raise ValueError("Must enter at least two input sample vectors.") + + samples = _broadcast_arrays(samples, axis=axis, xp=xp) + samples = [xp_moveaxis_to_end(sample, axis, xp=xp) for sample in samples] + + Ni = [xp.asarray(sample.shape[-1], dtype=sample.dtype) for sample in samples] + Ni = [xp.broadcast_to(N, samples[0].shape[:-1]) for N in Ni] + ssq = [xp.var(sample, correction=1, axis=-1) for sample in samples] + Ni = [arr[xp.newaxis, ...] for arr in Ni] + ssq = [arr[xp.newaxis, ...] for arr in ssq] + Ni = xp.concat(Ni, axis=0) + ssq = xp.concat(ssq, axis=0) + # sum dtype can be removed when 2023.12 rules kick in + dtype = Ni.dtype + Ntot = xp.sum(Ni, axis=0, dtype=dtype) + spsq = xp.sum((Ni - 1)*ssq, axis=0, dtype=dtype) / (Ntot - k) + numer = ((Ntot - k) * xp.log(spsq) + - xp.sum((Ni - 1)*xp.log(ssq), axis=0, dtype=dtype)) + denom = (1 + 1/(3*(k - 1)) + * ((xp.sum(1/(Ni - 1), axis=0, dtype=dtype)) - 1/(Ntot - k))) + T = numer / denom + + chi2 = _SimpleChi2(xp.asarray(k-1)) + pvalue = _get_pvalue(T, chi2, alternative='greater', symmetric=False, xp=xp) + + T = xp.clip(T, min=0., max=xp.inf) + T = T[()] if T.ndim == 0 else T + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return BartlettResult(T, pvalue) + + +LeveneResult = namedtuple('LeveneResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(LeveneResult, n_samples=None) +def levene(*samples, center='median', proportiontocut=0.05): + r"""Perform Levene test for equal variances. + + The Levene test tests the null hypothesis that all input samples + are from populations with equal variances. Levene's test is an + alternative to Bartlett's test `bartlett` in the case where + there are significant deviations from normality. + + Parameters + ---------- + sample1, sample2, ... : array_like + The sample data, possibly with different lengths. Only one-dimensional + samples are accepted. + center : {'mean', 'median', 'trimmed'}, optional + Which function of the data to use in the test. The default + is 'median'. + proportiontocut : float, optional + When `center` is 'trimmed', this gives the proportion of data points + to cut from each end. (See `scipy.stats.trim_mean`.) + Default is 0.05. + + Returns + ------- + statistic : float + The test statistic. + pvalue : float + The p-value for the test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + bartlett : A parametric test for equality of k variances in normal samples + :ref:`hypothesis_levene` : Extended example + + Notes + ----- + Three variations of Levene's test are possible. The possibilities + and their recommended usages are: + + * 'median' : Recommended for skewed (non-normal) distributions> + * 'mean' : Recommended for symmetric, moderate-tailed distributions. + * 'trimmed' : Recommended for heavy-tailed distributions. + + The test version using the mean was proposed in the original article + of Levene ([2]_) while the median and trimmed mean have been studied by + Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe + test. + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm + .. [2] Levene, H. (1960). In Contributions to Probability and Statistics: + Essays in Honor of Harold Hotelling, I. Olkin et al. eds., + Stanford University Press, pp. 278-292. + .. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American + Statistical Association, 69, 364-367 + + Examples + -------- + + Test whether the lists `a`, `b` and `c` come from populations + with equal variances. + + >>> import numpy as np + >>> from scipy import stats + >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99] + >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05] + >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98] + >>> stat, p = stats.levene(a, b, c) + >>> p + 0.002431505967249681 + + The small p-value suggests that the populations do not have equal + variances. + + This is not surprising, given that the sample variance of `b` is much + larger than that of `a` and `c`: + + >>> [np.var(x, ddof=1) for x in [a, b, c]] + [0.007054444444444413, 0.13073888888888888, 0.008890000000000002] + + For a more detailed example, see :ref:`hypothesis_levene`. + """ + if center not in ['mean', 'median', 'trimmed']: + raise ValueError("center must be 'mean', 'median' or 'trimmed'.") + + k = len(samples) + if k < 2: + raise ValueError("Must enter at least two input sample vectors.") + + Ni = np.empty(k) + Yci = np.empty(k, 'd') + + if center == 'median': + + def func(x): + return np.median(x, axis=0) + + elif center == 'mean': + + def func(x): + return np.mean(x, axis=0) + + else: # center == 'trimmed' + samples = tuple(_stats_py.trimboth(np.sort(sample), proportiontocut) + for sample in samples) + + def func(x): + return np.mean(x, axis=0) + + for j in range(k): + Ni[j] = len(samples[j]) + Yci[j] = func(samples[j]) + Ntot = np.sum(Ni, axis=0) + + # compute Zij's + Zij = [None] * k + for i in range(k): + Zij[i] = abs(asarray(samples[i]) - Yci[i]) + + # compute Zbari + Zbari = np.empty(k, 'd') + Zbar = 0.0 + for i in range(k): + Zbari[i] = np.mean(Zij[i], axis=0) + Zbar += Zbari[i] * Ni[i] + + Zbar /= Ntot + numer = (Ntot - k) * np.sum(Ni * (Zbari - Zbar)**2, axis=0) + + # compute denom_variance + dvar = 0.0 + for i in range(k): + dvar += np.sum((Zij[i] - Zbari[i])**2, axis=0) + + denom = (k - 1.0) * dvar + + W = numer / denom + pval = distributions.f.sf(W, k-1, Ntot-k) # 1 - cdf + return LeveneResult(W, pval) + + +def _apply_func(x, g, func): + # g is list of indices into x + # separating x into different groups + # func should be applied over the groups + g = unique(r_[0, g, len(x)]) + output = [func(x[g[k]:g[k+1]]) for k in range(len(g) - 1)] + + return asarray(output) + + +FlignerResult = namedtuple('FlignerResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(FlignerResult, n_samples=None) +def fligner(*samples, center='median', proportiontocut=0.05): + r"""Perform Fligner-Killeen test for equality of variance. + + Fligner's test tests the null hypothesis that all input samples + are from populations with equal variances. Fligner-Killeen's test is + distribution free when populations are identical [2]_. + + Parameters + ---------- + sample1, sample2, ... : array_like + Arrays of sample data. Need not be the same length. + center : {'mean', 'median', 'trimmed'}, optional + Keyword argument controlling which function of the data is used in + computing the test statistic. The default is 'median'. + proportiontocut : float, optional + When `center` is 'trimmed', this gives the proportion of data points + to cut from each end. (See `scipy.stats.trim_mean`.) + Default is 0.05. + + Returns + ------- + statistic : float + The test statistic. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + bartlett : A parametric test for equality of k variances in normal samples + levene : A robust parametric test for equality of k variances + :ref:`hypothesis_fligner` : Extended example + + Notes + ----- + As with Levene's test there are three variants of Fligner's test that + differ by the measure of central tendency used in the test. See `levene` + for more information. + + Conover et al. (1981) examine many of the existing parametric and + nonparametric tests by extensive simulations and they conclude that the + tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be + superior in terms of robustness of departures from normality and power + [3]_. + + References + ---------- + .. [1] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and + Hypothesis Testing based on Quadratic Inference Function. Technical + Report #99-03, Center for Likelihood Studies, Pennsylvania State + University. + https://cecas.clemson.edu/~cspark/cv/paper/qif/draftqif2.pdf + .. [2] Fligner, M.A. and Killeen, T.J. (1976). Distribution-free two-sample + tests for scale. Journal of the American Statistical Association. + 71(353), 210-213. + .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and + Hypothesis Testing based on Quadratic Inference Function. Technical + Report #99-03, Center for Likelihood Studies, Pennsylvania State + University. + .. [4] Conover, W. J., Johnson, M. E. and Johnson M. M. (1981). A + comparative study of tests for homogeneity of variances, with + applications to the outer continental shelf bidding data. + Technometrics, 23(4), 351-361. + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + + Test whether the lists `a`, `b` and `c` come from populations + with equal variances. + + >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99] + >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05] + >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98] + >>> stat, p = stats.fligner(a, b, c) + >>> p + 0.00450826080004775 + + The small p-value suggests that the populations do not have equal + variances. + + This is not surprising, given that the sample variance of `b` is much + larger than that of `a` and `c`: + + >>> [np.var(x, ddof=1) for x in [a, b, c]] + [0.007054444444444413, 0.13073888888888888, 0.008890000000000002] + + For a more detailed example, see :ref:`hypothesis_fligner`. + """ + if center not in ['mean', 'median', 'trimmed']: + raise ValueError("center must be 'mean', 'median' or 'trimmed'.") + + k = len(samples) + if k < 2: + raise ValueError("Must enter at least two input sample vectors.") + + # Handle empty input + for sample in samples: + if sample.size == 0: + NaN = _get_nan(*samples) + return FlignerResult(NaN, NaN) + + if center == 'median': + + def func(x): + return np.median(x, axis=0) + + elif center == 'mean': + + def func(x): + return np.mean(x, axis=0) + + else: # center == 'trimmed' + samples = tuple(_stats_py.trimboth(sample, proportiontocut) + for sample in samples) + + def func(x): + return np.mean(x, axis=0) + + Ni = asarray([len(samples[j]) for j in range(k)]) + Yci = asarray([func(samples[j]) for j in range(k)]) + Ntot = np.sum(Ni, axis=0) + # compute Zij's + Zij = [abs(asarray(samples[i]) - Yci[i]) for i in range(k)] + allZij = [] + g = [0] + for i in range(k): + allZij.extend(list(Zij[i])) + g.append(len(allZij)) + + ranks = _stats_py.rankdata(allZij) + sample = distributions.norm.ppf(ranks / (2*(Ntot + 1.0)) + 0.5) + + # compute Aibar + Aibar = _apply_func(sample, g, np.sum) / Ni + anbar = np.mean(sample, axis=0) + varsq = np.var(sample, axis=0, ddof=1) + statistic = np.sum(Ni * (asarray(Aibar) - anbar)**2.0, axis=0) / varsq + chi2 = _SimpleChi2(k-1) + pval = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np) + return FlignerResult(statistic, pval) + + +@_axis_nan_policy_factory(lambda x1: (x1,), n_samples=4, n_outputs=1) +def _mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N) -> float: + # Obtain the unique values and their frequencies from the pooled samples. + # "a_j, + b_j, = t_j, for j = 1, ... k" where `k` is the number of unique + # classes, and "[t]he number of values associated with the x's and y's in + # the jth class will be denoted by a_j, and b_j respectively." + # (Mielke, 312) + # Reuse previously computed sorted array and `diff` arrays to obtain the + # unique values and counts. Prepend `diffs` with a non-zero to indicate + # that the first element should be marked as not matching what preceded it. + diffs_prep = np.concatenate(([1], diffs)) + # Unique elements are where the was a difference between elements in the + # sorted array + uniques = sorted_xy[diffs_prep != 0] + # The count of each element is the bin size for each set of consecutive + # differences where the difference is zero. Replace nonzero differences + # with 1 and then use the cumulative sum to count the indices. + t = np.bincount(np.cumsum(np.asarray(diffs_prep != 0, dtype=int)))[1:] + k = len(uniques) + js = np.arange(1, k + 1, dtype=int) + # the `b` array mentioned in the paper is not used, outside of the + # calculation of `t`, so we do not need to calculate it separately. Here + # we calculate `a`. In plain language, `a[j]` is the number of values in + # `x` that equal `uniques[j]`. + sorted_xyx = np.sort(np.concatenate((xy, x))) + diffs = np.diff(sorted_xyx) + diffs_prep = np.concatenate(([1], diffs)) + diff_is_zero = np.asarray(diffs_prep != 0, dtype=int) + xyx_counts = np.bincount(np.cumsum(diff_is_zero))[1:] + a = xyx_counts - t + # "Define .. a_0 = b_0 = t_0 = S_0 = 0" (Mielke 312) so we shift `a` + # and `t` arrays over 1 to allow a first element of 0 to accommodate this + # indexing. + t = np.concatenate(([0], t)) + a = np.concatenate(([0], a)) + # S is built from `t`, so it does not need a preceding zero added on. + S = np.cumsum(t) + # define a copy of `S` with a prepending zero for later use to avoid + # the need for indexing. + S_i_m1 = np.concatenate(([0], S[:-1])) + + # Psi, as defined by the 6th unnumbered equation on page 313 (Mielke). + # Note that in the paper there is an error where the denominator `2` is + # squared when it should be the entire equation. + def psi(indicator): + return (indicator - (N + 1)/2)**2 + + # define summation range for use in calculation of phi, as seen in sum + # in the unnumbered equation on the bottom of page 312 (Mielke). + s_lower = S[js - 1] + 1 + s_upper = S[js] + 1 + phi_J = [np.arange(s_lower[idx], s_upper[idx]) for idx in range(k)] + + # for every range in the above array, determine the sum of psi(I) for + # every element in the range. Divide all the sums by `t`. Following the + # last unnumbered equation on page 312. + phis = [np.sum(psi(I_j)) for I_j in phi_J] / t[js] + + # `T` is equal to a[j] * phi[j], per the first unnumbered equation on + # page 312. `phis` is already in the order based on `js`, so we index + # into `a` with `js` as well. + T = sum(phis * a[js]) + + # The approximate statistic + E_0_T = n * (N * N - 1) / 12 + + varM = (m * n * (N + 1.0) * (N ** 2 - 4) / 180 - + m * n / (180 * N * (N - 1)) * np.sum( + t * (t**2 - 1) * (t**2 - 4 + (15 * (N - S - S_i_m1) ** 2)) + )) + + return ((T - E_0_T) / np.sqrt(varM),) + + +def _mood_too_small(samples, kwargs, axis=-1): + x, y = samples + n = x.shape[axis] + m = y.shape[axis] + N = m + n + return N < 3 + + +@_axis_nan_policy_factory(SignificanceResult, n_samples=2, too_small=_mood_too_small) +def mood(x, y, axis=0, alternative="two-sided"): + """Perform Mood's test for equal scale parameters. + + Mood's two-sample test for scale parameters is a non-parametric + test for the null hypothesis that two samples are drawn from the + same distribution with the same scale parameter. + + Parameters + ---------- + x, y : array_like + Arrays of sample data. There must be at least three observations + total. + axis : int, optional + The axis along which the samples are tested. `x` and `y` can be of + different length along `axis`. + If `axis` is None, `x` and `y` are flattened and the test is done on + all values in the flattened arrays. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the scales of the distributions underlying `x` and `y` + are different. + * 'less': the scale of the distribution underlying `x` is less than + the scale of the distribution underlying `y`. + * 'greater': the scale of the distribution underlying `x` is greater + than the scale of the distribution underlying `y`. + + .. versionadded:: 1.7.0 + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : scalar or ndarray + The z-score for the hypothesis test. For 1-D inputs a scalar is + returned. + pvalue : scalar ndarray + The p-value for the hypothesis test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + ansari : A non-parametric test for the equality of 2 variances + bartlett : A parametric test for equality of k variances in normal samples + levene : A parametric test for equality of k variances + + Notes + ----- + The data are assumed to be drawn from probability distributions ``f(x)`` + and ``f(x/s) / s`` respectively, for some probability density function f. + The null hypothesis is that ``s == 1``. + + For multi-dimensional arrays, if the inputs are of shapes + ``(n0, n1, n2, n3)`` and ``(n0, m1, n2, n3)``, then if ``axis=1``, the + resulting z and p values will have shape ``(n0, n2, n3)``. Note that + ``n1`` and ``m1`` don't have to be equal, but the other dimensions do. + + References + ---------- + [1] Mielke, Paul W. "Note on Some Squared Rank Tests with Existing Ties." + Technometrics, vol. 9, no. 2, 1967, pp. 312-14. JSTOR, + https://doi.org/10.2307/1266427. Accessed 18 May 2022. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x2 = rng.standard_normal((2, 45, 6, 7)) + >>> x1 = rng.standard_normal((2, 30, 6, 7)) + >>> res = stats.mood(x1, x2, axis=1) + >>> res.pvalue.shape + (2, 6, 7) + + Find the number of points where the difference in scale is not significant: + + >>> (res.pvalue > 0.1).sum() + 78 + + Perform the test with different scales: + + >>> x1 = rng.standard_normal((2, 30)) + >>> x2 = rng.standard_normal((2, 35)) * 10.0 + >>> stats.mood(x1, x2, axis=1) + SignificanceResult(statistic=array([-5.76174136, -6.12650783]), + pvalue=array([8.32505043e-09, 8.98287869e-10])) + + """ + x = np.asarray(x, dtype=float) + y = np.asarray(y, dtype=float) + + if axis < 0: + axis = x.ndim + axis + + # Determine shape of the result arrays + res_shape = tuple([x.shape[ax] for ax in range(len(x.shape)) if ax != axis]) + if not (res_shape == tuple([y.shape[ax] for ax in range(len(y.shape)) if + ax != axis])): + raise ValueError("Dimensions of x and y on all axes except `axis` " + "should match") + + n = x.shape[axis] + m = y.shape[axis] + N = m + n + if N < 3: + raise ValueError("Not enough observations.") + + xy = np.concatenate((x, y), axis=axis) + # determine if any of the samples contain ties + sorted_xy = np.sort(xy, axis=axis) + diffs = np.diff(sorted_xy, axis=axis) + if 0 in diffs: + z = np.asarray(_mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N, + axis=axis)) + else: + if axis != 0: + xy = np.moveaxis(xy, axis, 0) + + xy = xy.reshape(xy.shape[0], -1) + # Generalized to the n-dimensional case by adding the axis argument, + # and using for loops, since rankdata is not vectorized. For improving + # performance consider vectorizing rankdata function. + all_ranks = np.empty_like(xy) + for j in range(xy.shape[1]): + all_ranks[:, j] = _stats_py.rankdata(xy[:, j]) + + Ri = all_ranks[:n] + M = np.sum((Ri - (N + 1.0) / 2) ** 2, axis=0) + # Approx stat. + mnM = n * (N * N - 1.0) / 12 + varM = m * n * (N + 1.0) * (N + 2) * (N - 2) / 180 + z = (M - mnM) / sqrt(varM) + pval = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + + if res_shape == (): + # Return scalars, not 0-D arrays + z = z[0] + pval = pval[0] + else: + z.shape = res_shape + pval.shape = res_shape + return SignificanceResult(z[()], pval[()]) + + +WilcoxonResult = _make_tuple_bunch('WilcoxonResult', ['statistic', 'pvalue']) + + +def wilcoxon_result_unpacker(res): + if hasattr(res, 'zstatistic'): + return res.statistic, res.pvalue, res.zstatistic + else: + return res.statistic, res.pvalue + + +def wilcoxon_result_object(statistic, pvalue, zstatistic=None): + res = WilcoxonResult(statistic, pvalue) + if zstatistic is not None: + res.zstatistic = zstatistic + return res + + +def wilcoxon_outputs(kwds): + method = kwds.get('method', 'auto') + if method == 'asymptotic': + return 3 + return 2 + + +@_rename_parameter("mode", "method") +@_axis_nan_policy_factory( + wilcoxon_result_object, paired=True, + n_samples=lambda kwds: 2 if kwds.get('y', None) is not None else 1, + result_to_tuple=wilcoxon_result_unpacker, n_outputs=wilcoxon_outputs, +) +def wilcoxon(x, y=None, zero_method="wilcox", correction=False, + alternative="two-sided", method='auto', *, axis=0): + """Calculate the Wilcoxon signed-rank test. + + The Wilcoxon signed-rank test tests the null hypothesis that two + related paired samples come from the same distribution. In particular, + it tests whether the distribution of the differences ``x - y`` is symmetric + about zero. It is a non-parametric version of the paired T-test. + + Parameters + ---------- + x : array_like + Either the first set of measurements (in which case ``y`` is the second + set of measurements), or the differences between two sets of + measurements (in which case ``y`` is not to be specified.) Must be + one-dimensional. + y : array_like, optional + Either the second set of measurements (if ``x`` is the first set of + measurements), or not specified (if ``x`` is the differences between + two sets of measurements.) Must be one-dimensional. + + .. warning:: + When `y` is provided, `wilcoxon` calculates the test statistic + based on the ranks of the absolute values of ``d = x - y``. + Roundoff error in the subtraction can result in elements of ``d`` + being assigned different ranks even when they would be tied with + exact arithmetic. Rather than passing `x` and `y` separately, + consider computing the difference ``x - y``, rounding as needed to + ensure that only truly unique elements are numerically distinct, + and passing the result as `x`, leaving `y` at the default (None). + + zero_method : {"wilcox", "pratt", "zsplit"}, optional + There are different conventions for handling pairs of observations + with equal values ("zero-differences", or "zeros"). + + * "wilcox": Discards all zero-differences (default); see [4]_. + * "pratt": Includes zero-differences in the ranking process, + but drops the ranks of the zeros (more conservative); see [3]_. + In this case, the normal approximation is adjusted as in [5]_. + * "zsplit": Includes zero-differences in the ranking process and + splits the zero rank between positive and negative ones. + + correction : bool, optional + If True, apply continuity correction by adjusting the Wilcoxon rank + statistic by 0.5 towards the mean value when computing the + z-statistic if a normal approximation is used. Default is False. + alternative : {"two-sided", "greater", "less"}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + In the following, let ``d`` represent the difference between the paired + samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or + ``d = x`` otherwise. + + * 'two-sided': the distribution underlying ``d`` is not symmetric + about zero. + * 'less': the distribution underlying ``d`` is stochastically less + than a distribution symmetric about zero. + * 'greater': the distribution underlying ``d`` is stochastically + greater than a distribution symmetric about zero. + + method : {"auto", "exact", "asymptotic"} or `PermutationMethod` instance, optional + Method to calculate the p-value, see Notes. Default is "auto". + + axis : int or None, default: 0 + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If ``None``, the input will + be raveled before computing the statistic. + + Returns + ------- + An object with the following attributes. + + statistic : array_like + If `alternative` is "two-sided", the sum of the ranks of the + differences above or below zero, whichever is smaller. + Otherwise the sum of the ranks of the differences above zero. + pvalue : array_like + The p-value for the test depending on `alternative` and `method`. + zstatistic : array_like + When ``method = 'asymptotic'``, this is the normalized z-statistic:: + + z = (T - mn - d) / se + + where ``T`` is `statistic` as defined above, ``mn`` is the mean of the + distribution under the null hypothesis, ``d`` is a continuity + correction, and ``se`` is the standard error. + When ``method != 'asymptotic'``, this attribute is not available. + + See Also + -------- + kruskal, mannwhitneyu + + Notes + ----- + In the following, let ``d`` represent the difference between the paired + samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or ``d = x`` + otherwise. Assume that all elements of ``d`` are independent and + identically distributed observations, and all are distinct and nonzero. + + - When ``len(d)`` is sufficiently large, the null distribution of the + normalized test statistic (`zstatistic` above) is approximately normal, + and ``method = 'asymptotic'`` can be used to compute the p-value. + + - When ``len(d)`` is small, the normal approximation may not be accurate, + and ``method='exact'`` is preferred (at the cost of additional + execution time). + + - The default, ``method='auto'``, selects between the two: + ``method='exact'`` is used when ``len(d) <= 50``, and + ``method='asymptotic'`` is used otherwise. + + The presence of "ties" (i.e. not all elements of ``d`` are unique) or + "zeros" (i.e. elements of ``d`` are zero) changes the null distribution + of the test statistic, and ``method='exact'`` no longer calculates + the exact p-value. If ``method='asymptotic'``, the z-statistic is adjusted + for more accurate comparison against the standard normal, but still, + for finite sample sizes, the standard normal is only an approximation of + the true null distribution of the z-statistic. For such situations, the + `method` parameter also accepts instances of `PermutationMethod`. In this + case, the p-value is computed using `permutation_test` with the provided + configuration options and other appropriate settings. + + The presence of ties and zeros affects the resolution of ``method='auto'`` + accordingly: exhasutive permutations are performed when ``len(d) <= 13``, + and the asymptotic method is used otherwise. Note that they asymptotic + method may not be very accurate even for ``len(d) > 14``; the threshold + was chosen as a compromise between execution time and accuracy under the + constraint that the results must be deterministic. Consider providing an + instance of `PermutationMethod` method manually, choosing the + ``n_resamples`` parameter to balance time constraints and accuracy + requirements. + + Please also note that in the edge case that all elements of ``d`` are zero, + the p-value relying on the normal approximaton cannot be computed (NaN) + if ``zero_method='wilcox'`` or ``zero_method='pratt'``. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test + .. [2] Conover, W.J., Practical Nonparametric Statistics, 1971. + .. [3] Pratt, J.W., Remarks on Zeros and Ties in the Wilcoxon Signed + Rank Procedures, Journal of the American Statistical Association, + Vol. 54, 1959, pp. 655-667. :doi:`10.1080/01621459.1959.10501526` + .. [4] Wilcoxon, F., Individual Comparisons by Ranking Methods, + Biometrics Bulletin, Vol. 1, 1945, pp. 80-83. :doi:`10.2307/3001968` + .. [5] Cureton, E.E., The Normal Approximation to the Signed-Rank + Sampling Distribution When Zero Differences are Present, + Journal of the American Statistical Association, Vol. 62, 1967, + pp. 1068-1069. :doi:`10.1080/01621459.1967.10500917` + + Examples + -------- + In [4]_, the differences in height between cross- and self-fertilized + corn plants is given as follows: + + >>> d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75] + + Cross-fertilized plants appear to be higher. To test the null + hypothesis that there is no height difference, we can apply the + two-sided test: + + >>> from scipy.stats import wilcoxon + >>> res = wilcoxon(d) + >>> res.statistic, res.pvalue + (24.0, 0.041259765625) + + Hence, we would reject the null hypothesis at a confidence level of 5%, + concluding that there is a difference in height between the groups. + To confirm that the median of the differences can be assumed to be + positive, we use: + + >>> res = wilcoxon(d, alternative='greater') + >>> res.statistic, res.pvalue + (96.0, 0.0206298828125) + + This shows that the null hypothesis that the median is negative can be + rejected at a confidence level of 5% in favor of the alternative that + the median is greater than zero. The p-values above are exact. Using the + normal approximation gives very similar values: + + >>> res = wilcoxon(d, method='asymptotic') + >>> res.statistic, res.pvalue + (24.0, 0.04088813291185591) + + Note that the statistic changed to 96 in the one-sided case (the sum + of ranks of positive differences) whereas it is 24 in the two-sided + case (the minimum of sum of ranks above and below zero). + + In the example above, the differences in height between paired plants are + provided to `wilcoxon` directly. Alternatively, `wilcoxon` accepts two + samples of equal length, calculates the differences between paired + elements, then performs the test. Consider the samples ``x`` and ``y``: + + >>> import numpy as np + >>> x = np.array([0.5, 0.825, 0.375, 0.5]) + >>> y = np.array([0.525, 0.775, 0.325, 0.55]) + >>> res = wilcoxon(x, y, alternative='greater') + >>> res + WilcoxonResult(statistic=5.0, pvalue=0.5625) + + Note that had we calculated the differences by hand, the test would have + produced different results: + + >>> d = [-0.025, 0.05, 0.05, -0.05] + >>> ref = wilcoxon(d, alternative='greater') + >>> ref + WilcoxonResult(statistic=6.0, pvalue=0.5) + + The substantial difference is due to roundoff error in the results of + ``x-y``: + + >>> d - (x-y) + array([2.08166817e-17, 6.93889390e-17, 1.38777878e-17, 4.16333634e-17]) + + Even though we expected all the elements of ``(x-y)[1:]`` to have the same + magnitude ``0.05``, they have slightly different magnitudes in practice, + and therefore are assigned different ranks in the test. Before performing + the test, consider calculating ``d`` and adjusting it as necessary to + ensure that theoretically identically values are not numerically distinct. + For example: + + >>> d2 = np.around(x - y, decimals=3) + >>> wilcoxon(d2, alternative='greater') + WilcoxonResult(statistic=6.0, pvalue=0.5) + + """ + # replace approx by asymptotic to ensure backwards compatability + if method == "approx": + method = "asymptotic" + return _wilcoxon._wilcoxon_nd(x, y, zero_method, correction, alternative, + method, axis) + + +MedianTestResult = _make_tuple_bunch( + 'MedianTestResult', + ['statistic', 'pvalue', 'median', 'table'], [] +) + + +def median_test(*samples, ties='below', correction=True, lambda_=1, + nan_policy='propagate'): + """Perform a Mood's median test. + + Test that two or more samples come from populations with the same median. + + Let ``n = len(samples)`` be the number of samples. The "grand median" of + all the data is computed, and a contingency table is formed by + classifying the values in each sample as being above or below the grand + median. The contingency table, along with `correction` and `lambda_`, + are passed to `scipy.stats.chi2_contingency` to compute the test statistic + and p-value. + + Parameters + ---------- + sample1, sample2, ... : array_like + The set of samples. There must be at least two samples. + Each sample must be a one-dimensional sequence containing at least + one value. The samples are not required to have the same length. + ties : str, optional + Determines how values equal to the grand median are classified in + the contingency table. The string must be one of:: + + "below": + Values equal to the grand median are counted as "below". + "above": + Values equal to the grand median are counted as "above". + "ignore": + Values equal to the grand median are not counted. + + The default is "below". + correction : bool, optional + If True, *and* there are just two samples, apply Yates' correction + for continuity when computing the test statistic associated with + the contingency table. Default is True. + lambda_ : float or str, optional + By default, the statistic computed in this test is Pearson's + chi-squared statistic. `lambda_` allows a statistic from the + Cressie-Read power divergence family to be used instead. See + `power_divergence` for details. + Default is 1 (Pearson's chi-squared statistic). + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. + + Returns + ------- + res : MedianTestResult + An object containing attributes: + + statistic : float + The test statistic. The statistic that is returned is determined + by `lambda_`. The default is Pearson's chi-squared statistic. + pvalue : float + The p-value of the test. + median : float + The grand median. + table : ndarray + The contingency table. The shape of the table is (2, n), where + n is the number of samples. The first row holds the counts of the + values above the grand median, and the second row holds the counts + of the values below the grand median. The table allows further + analysis with, for example, `scipy.stats.chi2_contingency`, or with + `scipy.stats.fisher_exact` if there are two samples, without having + to recompute the table. If ``nan_policy`` is "propagate" and there + are nans in the input, the return value for ``table`` is ``None``. + + See Also + -------- + kruskal : Compute the Kruskal-Wallis H-test for independent samples. + mannwhitneyu : Computes the Mann-Whitney rank test on samples x and y. + + Notes + ----- + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Mood, A. M., Introduction to the Theory of Statistics. McGraw-Hill + (1950), pp. 394-399. + .. [2] Zar, J. H., Biostatistical Analysis, 5th ed. Prentice Hall (2010). + See Sections 8.12 and 10.15. + + Examples + -------- + A biologist runs an experiment in which there are three groups of plants. + Group 1 has 16 plants, group 2 has 15 plants, and group 3 has 17 plants. + Each plant produces a number of seeds. The seed counts for each group + are:: + + Group 1: 10 14 14 18 20 22 24 25 31 31 32 39 43 43 48 49 + Group 2: 28 30 31 33 34 35 36 40 44 55 57 61 91 92 99 + Group 3: 0 3 9 22 23 25 25 33 34 34 40 45 46 48 62 67 84 + + The following code applies Mood's median test to these samples. + + >>> g1 = [10, 14, 14, 18, 20, 22, 24, 25, 31, 31, 32, 39, 43, 43, 48, 49] + >>> g2 = [28, 30, 31, 33, 34, 35, 36, 40, 44, 55, 57, 61, 91, 92, 99] + >>> g3 = [0, 3, 9, 22, 23, 25, 25, 33, 34, 34, 40, 45, 46, 48, 62, 67, 84] + >>> from scipy.stats import median_test + >>> res = median_test(g1, g2, g3) + + The median is + + >>> res.median + 34.0 + + and the contingency table is + + >>> res.table + array([[ 5, 10, 7], + [11, 5, 10]]) + + `p` is too large to conclude that the medians are not the same: + + >>> res.pvalue + 0.12609082774093244 + + The "G-test" can be performed by passing ``lambda_="log-likelihood"`` to + `median_test`. + + >>> res = median_test(g1, g2, g3, lambda_="log-likelihood") + >>> res.pvalue + 0.12224779737117837 + + The median occurs several times in the data, so we'll get a different + result if, for example, ``ties="above"`` is used: + + >>> res = median_test(g1, g2, g3, ties="above") + >>> res.pvalue + 0.063873276069553273 + + >>> res.table + array([[ 5, 11, 9], + [11, 4, 8]]) + + This example demonstrates that if the data set is not large and there + are values equal to the median, the p-value can be sensitive to the + choice of `ties`. + + """ + if len(samples) < 2: + raise ValueError('median_test requires two or more samples.') + + ties_options = ['below', 'above', 'ignore'] + if ties not in ties_options: + raise ValueError(f"invalid 'ties' option '{ties}'; 'ties' must be one " + f"of: {str(ties_options)[1:-1]}") + + data = [np.asarray(sample) for sample in samples] + + # Validate the sizes and shapes of the arguments. + for k, d in enumerate(data): + if d.size == 0: + raise ValueError("Sample %d is empty. All samples must " + "contain at least one value." % (k + 1)) + if d.ndim != 1: + raise ValueError("Sample %d has %d dimensions. All " + "samples must be one-dimensional sequences." % + (k + 1, d.ndim)) + + cdata = np.concatenate(data) + contains_nan, nan_policy = _contains_nan(cdata, nan_policy) + if contains_nan and nan_policy == 'propagate': + return MedianTestResult(np.nan, np.nan, np.nan, None) + + if contains_nan: + grand_median = np.median(cdata[~np.isnan(cdata)]) + else: + grand_median = np.median(cdata) + # When the minimum version of numpy supported by scipy is 1.9.0, + # the above if/else statement can be replaced by the single line: + # grand_median = np.nanmedian(cdata) + + # Create the contingency table. + table = np.zeros((2, len(data)), dtype=np.int64) + for k, sample in enumerate(data): + sample = sample[~np.isnan(sample)] + + nabove = count_nonzero(sample > grand_median) + nbelow = count_nonzero(sample < grand_median) + nequal = sample.size - (nabove + nbelow) + table[0, k] += nabove + table[1, k] += nbelow + if ties == "below": + table[1, k] += nequal + elif ties == "above": + table[0, k] += nequal + + # Check that no row or column of the table is all zero. + # Such a table can not be given to chi2_contingency, because it would have + # a zero in the table of expected frequencies. + rowsums = table.sum(axis=1) + if rowsums[0] == 0: + raise ValueError(f"All values are below the grand median ({grand_median}).") + if rowsums[1] == 0: + raise ValueError(f"All values are above the grand median ({grand_median}).") + if ties == "ignore": + # We already checked that each sample has at least one value, but it + # is possible that all those values equal the grand median. If `ties` + # is "ignore", that would result in a column of zeros in `table`. We + # check for that case here. + zero_cols = np.nonzero((table == 0).all(axis=0))[0] + if len(zero_cols) > 0: + msg = ("All values in sample %d are equal to the grand " + "median (%r), so they are ignored, resulting in an " + "empty sample." % (zero_cols[0] + 1, grand_median)) + raise ValueError(msg) + + stat, p, dof, expected = chi2_contingency(table, lambda_=lambda_, + correction=correction) + return MedianTestResult(stat, p, grand_median, table) + + +def _circfuncs_common(samples, period, xp=None): + xp = array_namespace(samples) if xp is None else xp + + if xp.isdtype(samples.dtype, 'integral'): + dtype = xp.asarray(1.).dtype # get default float type + samples = xp.asarray(samples, dtype=dtype) + + # Recast samples as radians that range between 0 and 2 pi and calculate + # the sine and cosine + scaled_samples = samples * ((2.0 * pi) / period) + sin_samp = xp.sin(scaled_samples) + cos_samp = xp.cos(scaled_samples) + + return samples, sin_samp, cos_samp + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def circmean(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'): + r"""Compute the circular mean of a sample of angle observations. + + Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in + radians, their *circular mean* is defined by ([1]_, Eq. 2.2.4) + + .. math:: + + \mathrm{Arg} \left( \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right) + + where :math:`i` is the imaginary unit and :math:`\mathop{\mathrm{Arg}} z` + gives the principal value of the argument of complex number :math:`z`, + restricted to the range :math:`[0,2\pi]` by default. :math:`z` in the + above expression is known as the `mean resultant vector`. + + Parameters + ---------- + samples : array_like + Input array of angle observations. The value of a full angle is + equal to ``(high - low)``. + high : float, optional + Upper boundary of the principal value of an angle. Default is ``2*pi``. + low : float, optional + Lower boundary of the principal value of an angle. Default is ``0``. + + Returns + ------- + circmean : float + Circular mean, restricted to the range ``[low, high]``. + + If the mean resultant vector is zero, an input-dependent, + implementation-defined number between ``[low, high]`` is returned. + If the input array is empty, ``np.nan`` is returned. + + See Also + -------- + circstd : Circular standard deviation. + circvar : Circular variance. + + References + ---------- + .. [1] Mardia, K. V. and Jupp, P. E. *Directional Statistics*. + John Wiley & Sons, 1999. + + Examples + -------- + For readability, all angles are printed out in degrees. + + >>> import numpy as np + >>> from scipy.stats import circmean + >>> import matplotlib.pyplot as plt + >>> angles = np.deg2rad(np.array([20, 30, 330])) + >>> circmean = circmean(angles) + >>> np.rad2deg(circmean) + 7.294976657784009 + + >>> mean = angles.mean() + >>> np.rad2deg(mean) + 126.66666666666666 + + Plot and compare the circular mean against the arithmetic mean. + + >>> plt.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + >>> plt.scatter(np.cos(angles), np.sin(angles), c='k') + >>> plt.scatter(np.cos(circmean), np.sin(circmean), c='b', + ... label='circmean') + >>> plt.scatter(np.cos(mean), np.sin(mean), c='r', label='mean') + >>> plt.legend() + >>> plt.axis('equal') + >>> plt.show() + + """ + xp = array_namespace(samples) + # Needed for non-NumPy arrays to get appropriate NaN result + # Apparently atan2(0, 0) is 0, even though it is mathematically undefined + if xp_size(samples) == 0: + return xp.mean(samples, axis=axis) + period = high - low + samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp) + sin_sum = xp.sum(sin_samp, axis=axis) + cos_sum = xp.sum(cos_samp, axis=axis) + res = xp.atan2(sin_sum, cos_sum) + + res = res[()] if res.ndim == 0 else res + return (res * (period / (2.0 * pi)) - low) % period + low + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def circvar(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'): + r"""Compute the circular variance of a sample of angle observations. + + Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in + radians, their *circular variance* is defined by ([2]_, Eq. 2.3.3) + + .. math:: + + 1 - \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| + + where :math:`i` is the imaginary unit and :math:`|z|` gives the length + of the complex number :math:`z`. :math:`|z|` in the above expression + is known as the `mean resultant length`. + + Parameters + ---------- + samples : array_like + Input array of angle observations. The value of a full angle is + equal to ``(high - low)``. + high : float, optional + Upper boundary of the principal value of an angle. Default is ``2*pi``. + low : float, optional + Lower boundary of the principal value of an angle. Default is ``0``. + + Returns + ------- + circvar : float + Circular variance. The returned value is in the range ``[0, 1]``, + where ``0`` indicates no variance and ``1`` indicates large variance. + + If the input array is empty, ``np.nan`` is returned. + + See Also + -------- + circmean : Circular mean. + circstd : Circular standard deviation. + + Notes + ----- + In the limit of small angles, the circular variance is close to + half the 'linear' variance if measured in radians. + + References + ---------- + .. [1] Fisher, N.I. *Statistical analysis of circular data*. Cambridge + University Press, 1993. + .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*. + John Wiley & Sons, 1999. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import circvar + >>> import matplotlib.pyplot as plt + >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286, + ... 0.133, -0.473, -0.001, -0.348, 0.131]) + >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421, + ... 0.104, -0.136, -0.867, 0.012, 0.105]) + >>> circvar_1 = circvar(samples_1) + >>> circvar_2 = circvar(samples_2) + + Plot the samples. + + >>> fig, (left, right) = plt.subplots(ncols=2) + >>> for image in (left, right): + ... image.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + ... image.axis('equal') + ... image.axis('off') + >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15) + >>> left.set_title(f"circular variance: {np.round(circvar_1, 2)!r}") + >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15) + >>> right.set_title(f"circular variance: {np.round(circvar_2, 2)!r}") + >>> plt.show() + + """ + xp = array_namespace(samples) + period = high - low + samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp) + sin_mean = xp.mean(sin_samp, axis=axis) + cos_mean = xp.mean(cos_samp, axis=axis) + hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5 + # hypotenuse can go slightly above 1 due to rounding errors + R = xp.clip(hypotenuse, max=1.) + + res = 1. - R + return res + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def circstd(samples, high=2*pi, low=0, axis=None, nan_policy='propagate', *, + normalize=False): + r""" + Compute the circular standard deviation of a sample of angle observations. + + Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in + radians, their `circular standard deviation` is defined by + ([2]_, Eq. 2.3.11) + + .. math:: + + \sqrt{ -2 \log \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| } + + where :math:`i` is the imaginary unit and :math:`|z|` gives the length + of the complex number :math:`z`. :math:`|z|` in the above expression + is known as the `mean resultant length`. + + Parameters + ---------- + samples : array_like + Input array of angle observations. The value of a full angle is + equal to ``(high - low)``. + high : float, optional + Upper boundary of the principal value of an angle. Default is ``2*pi``. + low : float, optional + Lower boundary of the principal value of an angle. Default is ``0``. + normalize : boolean, optional + If ``False`` (the default), the return value is computed from the + above formula with the input scaled by ``(2*pi)/(high-low)`` and + the output scaled (back) by ``(high-low)/(2*pi)``. If ``True``, + the output is not scaled and is returned directly. + + Returns + ------- + circstd : float + Circular standard deviation, optionally normalized. + + If the input array is empty, ``np.nan`` is returned. + + See Also + -------- + circmean : Circular mean. + circvar : Circular variance. + + Notes + ----- + In the limit of small angles, the circular standard deviation is close + to the 'linear' standard deviation if ``normalize`` is ``False``. + + References + ---------- + .. [1] Mardia, K. V. (1972). 2. In *Statistics of Directional Data* + (pp. 18-24). Academic Press. :doi:`10.1016/C2013-0-07425-7`. + .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*. + John Wiley & Sons, 1999. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import circstd + >>> import matplotlib.pyplot as plt + >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286, + ... 0.133, -0.473, -0.001, -0.348, 0.131]) + >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421, + ... 0.104, -0.136, -0.867, 0.012, 0.105]) + >>> circstd_1 = circstd(samples_1) + >>> circstd_2 = circstd(samples_2) + + Plot the samples. + + >>> fig, (left, right) = plt.subplots(ncols=2) + >>> for image in (left, right): + ... image.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + ... image.axis('equal') + ... image.axis('off') + >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15) + >>> left.set_title(f"circular std: {np.round(circstd_1, 2)!r}") + >>> right.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15) + >>> right.set_title(f"circular std: {np.round(circstd_2, 2)!r}") + >>> plt.show() + + """ + xp = array_namespace(samples) + period = high - low + samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp) + sin_mean = xp.mean(sin_samp, axis=axis) # [1] (2.2.3) + cos_mean = xp.mean(cos_samp, axis=axis) # [1] (2.2.3) + hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5 + # hypotenuse can go slightly above 1 due to rounding errors + R = xp.clip(hypotenuse, max=1.) # [1] (2.2.4) + + res = (-2*xp.log(R))**0.5+0.0 # torch.pow returns -0.0 if R==1 + if not normalize: + res *= (high-low)/(2.*pi) # [1] (2.3.14) w/ (2.3.7) + return res + + +class DirectionalStats: + def __init__(self, mean_direction, mean_resultant_length): + self.mean_direction = mean_direction + self.mean_resultant_length = mean_resultant_length + + def __repr__(self): + return (f"DirectionalStats(mean_direction={self.mean_direction}," + f" mean_resultant_length={self.mean_resultant_length})") + + +def directional_stats(samples, *, axis=0, normalize=True): + """ + Computes sample statistics for directional data. + + Computes the directional mean (also called the mean direction vector) and + mean resultant length of a sample of vectors. + + The directional mean is a measure of "preferred direction" of vector data. + It is analogous to the sample mean, but it is for use when the length of + the data is irrelevant (e.g. unit vectors). + + The mean resultant length is a value between 0 and 1 used to quantify the + dispersion of directional data: the smaller the mean resultant length, the + greater the dispersion. Several definitions of directional variance + involving the mean resultant length are given in [1]_ and [2]_. + + Parameters + ---------- + samples : array_like + Input array. Must be at least two-dimensional, and the last axis of the + input must correspond with the dimensionality of the vector space. + When the input is exactly two dimensional, this means that each row + of the data is a vector observation. + axis : int, default: 0 + Axis along which the directional mean is computed. + normalize: boolean, default: True + If True, normalize the input to ensure that each observation is a + unit vector. It the observations are already unit vectors, consider + setting this to False to avoid unnecessary computation. + + Returns + ------- + res : DirectionalStats + An object containing attributes: + + mean_direction : ndarray + Directional mean. + mean_resultant_length : ndarray + The mean resultant length [1]_. + + See Also + -------- + circmean: circular mean; i.e. directional mean for 2D *angles* + circvar: circular variance; i.e. directional variance for 2D *angles* + + Notes + ----- + This uses a definition of directional mean from [1]_. + Assuming the observations are unit vectors, the calculation is as follows. + + .. code-block:: python + + mean = samples.mean(axis=0) + mean_resultant_length = np.linalg.norm(mean) + mean_direction = mean / mean_resultant_length + + This definition is appropriate for *directional* data (i.e. vector data + for which the magnitude of each observation is irrelevant) but not + for *axial* data (i.e. vector data for which the magnitude and *sign* of + each observation is irrelevant). + + Several definitions of directional variance involving the mean resultant + length ``R`` have been proposed, including ``1 - R`` [1]_, ``1 - R**2`` + [2]_, and ``2 * (1 - R)`` [2]_. Rather than choosing one, this function + returns ``R`` as attribute `mean_resultant_length` so the user can compute + their preferred measure of dispersion. + + References + ---------- + .. [1] Mardia, Jupp. (2000). *Directional Statistics* + (p. 163). Wiley. + + .. [2] https://en.wikipedia.org/wiki/Directional_statistics + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import directional_stats + >>> data = np.array([[3, 4], # first observation, 2D vector space + ... [6, -8]]) # second observation + >>> dirstats = directional_stats(data) + >>> dirstats.mean_direction + array([1., 0.]) + + In contrast, the regular sample mean of the vectors would be influenced + by the magnitude of each observation. Furthermore, the result would not be + a unit vector. + + >>> data.mean(axis=0) + array([4.5, -2.]) + + An exemplary use case for `directional_stats` is to find a *meaningful* + center for a set of observations on a sphere, e.g. geographical locations. + + >>> data = np.array([[0.8660254, 0.5, 0.], + ... [0.8660254, -0.5, 0.]]) + >>> dirstats = directional_stats(data) + >>> dirstats.mean_direction + array([1., 0., 0.]) + + The regular sample mean on the other hand yields a result which does not + lie on the surface of the sphere. + + >>> data.mean(axis=0) + array([0.8660254, 0., 0.]) + + The function also returns the mean resultant length, which + can be used to calculate a directional variance. For example, using the + definition ``Var(z) = 1 - R`` from [2]_ where ``R`` is the + mean resultant length, we can calculate the directional variance of the + vectors in the above example as: + + >>> 1 - dirstats.mean_resultant_length + 0.13397459716167093 + """ + xp = array_namespace(samples) + samples = xp.asarray(samples) + + if samples.ndim < 2: + raise ValueError("samples must at least be two-dimensional. " + f"Instead samples has shape: {tuple(samples.shape)}") + samples = xp.moveaxis(samples, axis, 0) + if normalize: + vectornorms = xp_vector_norm(samples, axis=-1, keepdims=True, xp=xp) + samples = samples/vectornorms + mean = xp.mean(samples, axis=0) + mean_resultant_length = xp_vector_norm(mean, axis=-1, keepdims=True, xp=xp) + mean_direction = mean / mean_resultant_length + mrl = xp.squeeze(mean_resultant_length, axis=-1) + mean_resultant_length = mrl[()] if mrl.ndim == 0 else mrl + return DirectionalStats(mean_direction, mean_resultant_length) + + +def false_discovery_control(ps, *, axis=0, method='bh'): + """Adjust p-values to control the false discovery rate. + + The false discovery rate (FDR) is the expected proportion of rejected null + hypotheses that are actually true. + If the null hypothesis is rejected when the *adjusted* p-value falls below + a specified level, the false discovery rate is controlled at that level. + + Parameters + ---------- + ps : 1D array_like + The p-values to adjust. Elements must be real numbers between 0 and 1. + axis : int + The axis along which to perform the adjustment. The adjustment is + performed independently along each axis-slice. If `axis` is None, `ps` + is raveled before performing the adjustment. + method : {'bh', 'by'} + The false discovery rate control procedure to apply: ``'bh'`` is for + Benjamini-Hochberg [1]_ (Eq. 1), ``'by'`` is for Benjaminini-Yekutieli + [2]_ (Theorem 1.3). The latter is more conservative, but it is + guaranteed to control the FDR even when the p-values are not from + independent tests. + + Returns + ------- + ps_adusted : array_like + The adjusted p-values. If the null hypothesis is rejected where these + fall below a specified level, the false discovery rate is controlled + at that level. + + See Also + -------- + combine_pvalues + statsmodels.stats.multitest.multipletests + + Notes + ----- + In multiple hypothesis testing, false discovery control procedures tend to + offer higher power than familywise error rate control procedures (e.g. + Bonferroni correction [1]_). + + If the p-values correspond with independent tests (or tests with + "positive regression dependencies" [2]_), rejecting null hypotheses + corresponding with Benjamini-Hochberg-adjusted p-values below :math:`q` + controls the false discovery rate at a level less than or equal to + :math:`q m_0 / m`, where :math:`m_0` is the number of true null hypotheses + and :math:`m` is the total number of null hypotheses tested. The same is + true even for dependent tests when the p-values are adjusted accorded to + the more conservative Benjaminini-Yekutieli procedure. + + The adjusted p-values produced by this function are comparable to those + produced by the R function ``p.adjust`` and the statsmodels function + `statsmodels.stats.multitest.multipletests`. Please consider the latter + for more advanced methods of multiple comparison correction. + + References + ---------- + .. [1] Benjamini, Yoav, and Yosef Hochberg. "Controlling the false + discovery rate: a practical and powerful approach to multiple + testing." Journal of the Royal statistical society: series B + (Methodological) 57.1 (1995): 289-300. + + .. [2] Benjamini, Yoav, and Daniel Yekutieli. "The control of the false + discovery rate in multiple testing under dependency." Annals of + statistics (2001): 1165-1188. + + .. [3] TileStats. FDR - Benjamini-Hochberg explained - Youtube. + https://www.youtube.com/watch?v=rZKa4tW2NKs. + + .. [4] Neuhaus, Karl-Ludwig, et al. "Improved thrombolysis in acute + myocardial infarction with front-loaded administration of alteplase: + results of the rt-PA-APSAC patency study (TAPS)." Journal of the + American College of Cardiology 19.5 (1992): 885-891. + + Examples + -------- + We follow the example from [1]_. + + Thrombolysis with recombinant tissue-type plasminogen activator (rt-PA) + and anisoylated plasminogen streptokinase activator (APSAC) in + myocardial infarction has been proved to reduce mortality. [4]_ + investigated the effects of a new front-loaded administration of rt-PA + versus those obtained with a standard regimen of APSAC, in a randomized + multicentre trial in 421 patients with acute myocardial infarction. + + There were four families of hypotheses tested in the study, the last of + which was "cardiac and other events after the start of thrombolitic + treatment". FDR control may be desired in this family of hypotheses + because it would not be appropriate to conclude that the front-loaded + treatment is better if it is merely equivalent to the previous treatment. + + The p-values corresponding with the 15 hypotheses in this family were + + >>> ps = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344, + ... 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000] + + If the chosen significance level is 0.05, we may be tempted to reject the + null hypotheses for the tests corresponding with the first nine p-values, + as the first nine p-values fall below the chosen significance level. + However, this would ignore the problem of "multiplicity": if we fail to + correct for the fact that multiple comparisons are being performed, we + are more likely to incorrectly reject true null hypotheses. + + One approach to the multiplicity problem is to control the family-wise + error rate (FWER), that is, the rate at which the null hypothesis is + rejected when it is actually true. A common procedure of this kind is the + Bonferroni correction [1]_. We begin by multiplying the p-values by the + number of hypotheses tested. + + >>> import numpy as np + >>> np.array(ps) * len(ps) + array([1.5000e-03, 6.0000e-03, 2.8500e-02, 1.4250e-01, 3.0150e-01, + 4.1700e-01, 4.4700e-01, 5.1600e-01, 6.8850e-01, 4.8600e+00, + 6.3930e+00, 8.5785e+00, 9.7920e+00, 1.1385e+01, 1.5000e+01]) + + To control the FWER at 5%, we reject only the hypotheses corresponding + with adjusted p-values less than 0.05. In this case, only the hypotheses + corresponding with the first three p-values can be rejected. According to + [1]_, these three hypotheses concerned "allergic reaction" and "two + different aspects of bleeding." + + An alternative approach is to control the false discovery rate: the + expected fraction of rejected null hypotheses that are actually true. The + advantage of this approach is that it typically affords greater power: an + increased rate of rejecting the null hypothesis when it is indeed false. To + control the false discovery rate at 5%, we apply the Benjamini-Hochberg + p-value adjustment. + + >>> from scipy import stats + >>> stats.false_discovery_control(ps) + array([0.0015 , 0.003 , 0.0095 , 0.035625 , 0.0603 , + 0.06385714, 0.06385714, 0.0645 , 0.0765 , 0.486 , + 0.58118182, 0.714875 , 0.75323077, 0.81321429, 1. ]) + + Now, the first *four* adjusted p-values fall below 0.05, so we would reject + the null hypotheses corresponding with these *four* p-values. Rejection + of the fourth null hypothesis was particularly important to the original + study as it led to the conclusion that the new treatment had a + "substantially lower in-hospital mortality rate." + + """ + # Input Validation and Special Cases + ps = np.asarray(ps) + + ps_in_range = (np.issubdtype(ps.dtype, np.number) + and np.all(ps == np.clip(ps, 0, 1))) + if not ps_in_range: + raise ValueError("`ps` must include only numbers between 0 and 1.") + + methods = {'bh', 'by'} + if method.lower() not in methods: + raise ValueError(f"Unrecognized `method` '{method}'." + f"Method must be one of {methods}.") + method = method.lower() + + if axis is None: + axis = 0 + ps = ps.ravel() + + axis = np.asarray(axis)[()] + if not np.issubdtype(axis.dtype, np.integer) or axis.size != 1: + raise ValueError("`axis` must be an integer or `None`") + + if ps.size <= 1 or ps.shape[axis] <= 1: + return ps[()] + + ps = np.moveaxis(ps, axis, -1) + m = ps.shape[-1] + + # Main Algorithm + # Equivalent to the ideas of [1] and [2], except that this adjusts the + # p-values as described in [3]. The results are similar to those produced + # by R's p.adjust. + + # "Let [ps] be the ordered observed p-values..." + order = np.argsort(ps, axis=-1) + ps = np.take_along_axis(ps, order, axis=-1) # this copies ps + + # Equation 1 of [1] rearranged to reject when p is less than specified q + i = np.arange(1, m+1) + ps *= m / i + + # Theorem 1.3 of [2] + if method == 'by': + ps *= np.sum(1 / i) + + # accounts for rejecting all null hypotheses i for i < k, where k is + # defined in Eq. 1 of either [1] or [2]. See [3]. Starting with the index j + # of the second to last element, we replace element j with element j+1 if + # the latter is smaller. + np.minimum.accumulate(ps[..., ::-1], out=ps[..., ::-1], axis=-1) + + # Restore original order of axes and data + np.put_along_axis(ps, order, values=ps.copy(), axis=-1) + ps = np.moveaxis(ps, -1, axis) + + return np.clip(ps, 0, 1) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..bce32dcbafcce32fb1511538c06655445c2417bf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_basic.py @@ -0,0 +1,3662 @@ +""" +An extension of scipy.stats._stats_py to support masked arrays + +""" +# Original author (2007): Pierre GF Gerard-Marchant + + +__all__ = ['argstoarray', + 'count_tied_groups', + 'describe', + 'f_oneway', 'find_repeats','friedmanchisquare', + 'kendalltau','kendalltau_seasonal','kruskal','kruskalwallis', + 'ks_twosamp', 'ks_2samp', 'kurtosis', 'kurtosistest', + 'ks_1samp', 'kstest', + 'linregress', + 'mannwhitneyu', 'meppf','mode','moment','mquantiles','msign', + 'normaltest', + 'obrientransform', + 'pearsonr','plotting_positions','pointbiserialr', + 'rankdata', + 'scoreatpercentile','sem', + 'sen_seasonal_slopes','skew','skewtest','spearmanr', + 'siegelslopes', 'theilslopes', + 'tmax','tmean','tmin','trim','trimboth', + 'trimtail','trima','trimr','trimmed_mean','trimmed_std', + 'trimmed_stde','trimmed_var','tsem','ttest_1samp','ttest_onesamp', + 'ttest_ind','ttest_rel','tvar', + 'variation', + 'winsorize', + 'brunnermunzel', + ] + +import numpy as np +from numpy import ndarray +import numpy.ma as ma +from numpy.ma import masked, nomask +import math + +import itertools +import warnings +from collections import namedtuple + +from . import distributions +from scipy._lib._util import _rename_parameter, _contains_nan +from scipy._lib._bunch import _make_tuple_bunch +import scipy.special as special +import scipy.stats._stats_py +import scipy.stats._stats_py as _stats_py + +from ._stats_mstats_common import ( + _find_repeats, + theilslopes as stats_theilslopes, + siegelslopes as stats_siegelslopes + ) + + +def _chk_asarray(a, axis): + # Always returns a masked array, raveled for axis=None + a = ma.asanyarray(a) + if axis is None: + a = ma.ravel(a) + outaxis = 0 + else: + outaxis = axis + return a, outaxis + + +def _chk2_asarray(a, b, axis): + a = ma.asanyarray(a) + b = ma.asanyarray(b) + if axis is None: + a = ma.ravel(a) + b = ma.ravel(b) + outaxis = 0 + else: + outaxis = axis + return a, b, outaxis + + +def _chk_size(a, b): + a = ma.asanyarray(a) + b = ma.asanyarray(b) + (na, nb) = (a.size, b.size) + if na != nb: + raise ValueError("The size of the input array should match!" + f" ({na} <> {nb})") + return (a, b, na) + + +def _ttest_finish(df, t, alternative): + """Common code between all 3 t-test functions.""" + # We use ``stdtr`` directly here to preserve masked arrays + + if alternative == 'less': + pval = special._ufuncs.stdtr(df, t) + elif alternative == 'greater': + pval = special._ufuncs.stdtr(df, -t) + elif alternative == 'two-sided': + pval = special._ufuncs.stdtr(df, -np.abs(t))*2 + else: + raise ValueError("alternative must be " + "'less', 'greater' or 'two-sided'") + + if t.ndim == 0: + t = t[()] + if pval.ndim == 0: + pval = pval[()] + + return t, pval + + +def argstoarray(*args): + """ + Constructs a 2D array from a group of sequences. + + Sequences are filled with missing values to match the length of the longest + sequence. + + Parameters + ---------- + *args : sequences + Group of sequences. + + Returns + ------- + argstoarray : MaskedArray + A ( `m` x `n` ) masked array, where `m` is the number of arguments and + `n` the length of the longest argument. + + Notes + ----- + `numpy.ma.vstack` has identical behavior, but is called with a sequence + of sequences. + + Examples + -------- + A 2D masked array constructed from a group of sequences is returned. + + >>> from scipy.stats.mstats import argstoarray + >>> argstoarray([1, 2, 3], [4, 5, 6]) + masked_array( + data=[[1.0, 2.0, 3.0], + [4.0, 5.0, 6.0]], + mask=[[False, False, False], + [False, False, False]], + fill_value=1e+20) + + The returned masked array filled with missing values when the lengths of + sequences are different. + + >>> argstoarray([1, 3], [4, 5, 6]) + masked_array( + data=[[1.0, 3.0, --], + [4.0, 5.0, 6.0]], + mask=[[False, False, True], + [False, False, False]], + fill_value=1e+20) + + """ + if len(args) == 1 and not isinstance(args[0], ndarray): + output = ma.asarray(args[0]) + if output.ndim != 2: + raise ValueError("The input should be 2D") + else: + n = len(args) + m = max([len(k) for k in args]) + output = ma.array(np.empty((n,m), dtype=float), mask=True) + for (k,v) in enumerate(args): + output[k,:len(v)] = v + + output[np.logical_not(np.isfinite(output._data))] = masked + return output + + +def find_repeats(arr): + """Find repeats in arr and return a tuple (repeats, repeat_count). + + The input is cast to float64. Masked values are discarded. + + Parameters + ---------- + arr : sequence + Input array. The array is flattened if it is not 1D. + + Returns + ------- + repeats : ndarray + Array of repeated values. + counts : ndarray + Array of counts. + + Examples + -------- + >>> from scipy.stats import mstats + >>> mstats.find_repeats([2, 1, 2, 3, 2, 2, 5]) + (array([2.]), array([4])) + + In the above example, 2 repeats 4 times. + + >>> mstats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]]) + (array([4., 5.]), array([2, 2])) + + In the above example, both 4 and 5 repeat 2 times. + + """ + # Make sure we get a copy. ma.compressed promises a "new array", but can + # actually return a reference. + compr = np.asarray(ma.compressed(arr), dtype=np.float64) + try: + need_copy = np.may_share_memory(compr, arr) + except AttributeError: + # numpy < 1.8.2 bug: np.may_share_memory([], []) raises, + # while in numpy 1.8.2 and above it just (correctly) returns False. + need_copy = False + if need_copy: + compr = compr.copy() + return _find_repeats(compr) + + +def count_tied_groups(x, use_missing=False): + """ + Counts the number of tied values. + + Parameters + ---------- + x : sequence + Sequence of data on which to counts the ties + use_missing : bool, optional + Whether to consider missing values as tied. + + Returns + ------- + count_tied_groups : dict + Returns a dictionary (nb of ties: nb of groups). + + Examples + -------- + >>> from scipy.stats import mstats + >>> import numpy as np + >>> z = [0, 0, 0, 2, 2, 2, 3, 3, 4, 5, 6] + >>> mstats.count_tied_groups(z) + {2: 1, 3: 2} + + In the above example, the ties were 0 (3x), 2 (3x) and 3 (2x). + + >>> z = np.ma.array([0, 0, 1, 2, 2, 2, 3, 3, 4, 5, 6]) + >>> mstats.count_tied_groups(z) + {2: 2, 3: 1} + >>> z[[1,-1]] = np.ma.masked + >>> mstats.count_tied_groups(z, use_missing=True) + {2: 2, 3: 1} + + """ + nmasked = ma.getmask(x).sum() + # We need the copy as find_repeats will overwrite the initial data + data = ma.compressed(x).copy() + (ties, counts) = find_repeats(data) + nties = {} + if len(ties): + nties = dict(zip(np.unique(counts), itertools.repeat(1))) + nties.update(dict(zip(*find_repeats(counts)))) + + if nmasked and use_missing: + try: + nties[nmasked] += 1 + except KeyError: + nties[nmasked] = 1 + + return nties + + +def rankdata(data, axis=None, use_missing=False): + """Returns the rank (also known as order statistics) of each data point + along the given axis. + + If some values are tied, their rank is averaged. + If some values are masked, their rank is set to 0 if use_missing is False, + or set to the average rank of the unmasked values if use_missing is True. + + Parameters + ---------- + data : sequence + Input data. The data is transformed to a masked array + axis : {None,int}, optional + Axis along which to perform the ranking. + If None, the array is first flattened. An exception is raised if + the axis is specified for arrays with a dimension larger than 2 + use_missing : bool, optional + Whether the masked values have a rank of 0 (False) or equal to the + average rank of the unmasked values (True). + + """ + def _rank1d(data, use_missing=False): + n = data.count() + rk = np.empty(data.size, dtype=float) + idx = data.argsort() + rk[idx[:n]] = np.arange(1,n+1) + + if use_missing: + rk[idx[n:]] = (n+1)/2. + else: + rk[idx[n:]] = 0 + + repeats = find_repeats(data.copy()) + for r in repeats[0]: + condition = (data == r).filled(False) + rk[condition] = rk[condition].mean() + return rk + + data = ma.array(data, copy=False) + if axis is None: + if data.ndim > 1: + return _rank1d(data.ravel(), use_missing).reshape(data.shape) + else: + return _rank1d(data, use_missing) + else: + return ma.apply_along_axis(_rank1d,axis,data,use_missing).view(ndarray) + + +ModeResult = namedtuple('ModeResult', ('mode', 'count')) + + +def mode(a, axis=0): + """ + Returns an array of the modal (most common) value in the passed array. + + Parameters + ---------- + a : array_like + n-dimensional array of which to find mode(s). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + mode : ndarray + Array of modal values. + count : ndarray + Array of counts for each mode. + + Notes + ----- + For more details, see `scipy.stats.mode`. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> from scipy.stats import mstats + >>> m_arr = np.ma.array([1, 1, 0, 0, 0, 0], mask=[0, 0, 1, 1, 1, 0]) + >>> mstats.mode(m_arr) # note that most zeros are masked + ModeResult(mode=array([1.]), count=array([2.])) + + """ + return _mode(a, axis=axis, keepdims=True) + + +def _mode(a, axis=0, keepdims=True): + # Don't want to expose `keepdims` from the public `mstats.mode` + a, axis = _chk_asarray(a, axis) + + def _mode1D(a): + (rep,cnt) = find_repeats(a) + if not cnt.ndim: + return (0, 0) + elif cnt.size: + return (rep[cnt.argmax()], cnt.max()) + else: + return (a.min(), 1) + + if axis is None: + output = _mode1D(ma.ravel(a)) + output = (ma.array(output[0]), ma.array(output[1])) + else: + output = ma.apply_along_axis(_mode1D, axis, a) + if keepdims is None or keepdims: + newshape = list(a.shape) + newshape[axis] = 1 + slices = [slice(None)] * output.ndim + slices[axis] = 0 + modes = output[tuple(slices)].reshape(newshape) + slices[axis] = 1 + counts = output[tuple(slices)].reshape(newshape) + output = (modes, counts) + else: + output = np.moveaxis(output, axis, 0) + + return ModeResult(*output) + + +def _betai(a, b, x): + x = np.asanyarray(x) + x = ma.where(x < 1.0, x, 1.0) # if x > 1 then return 1.0 + return special.betainc(a, b, x) + + +def msign(x): + """Returns the sign of x, or 0 if x is masked.""" + return ma.filled(np.sign(x), 0) + + +def pearsonr(x, y): + r""" + Pearson correlation coefficient and p-value for testing non-correlation. + + The Pearson correlation coefficient [1]_ measures the linear relationship + between two datasets. The calculation of the p-value relies on the + assumption that each dataset is normally distributed. (See Kowalski [3]_ + for a discussion of the effects of non-normality of the input on the + distribution of the correlation coefficient.) Like other correlation + coefficients, this one varies between -1 and +1 with 0 implying no + correlation. Correlations of -1 or +1 imply an exact linear relationship. + + Parameters + ---------- + x : (N,) array_like + Input array. + y : (N,) array_like + Input array. + + Returns + ------- + r : float + Pearson's correlation coefficient. + p-value : float + Two-tailed p-value. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Raised if an input is a constant array. The correlation coefficient + is not defined in this case, so ``np.nan`` is returned. + + `~scipy.stats.NearConstantInputWarning` + Raised if an input is "nearly" constant. The array ``x`` is considered + nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``. + Numerical errors in the calculation ``x - mean(x)`` in this case might + result in an inaccurate calculation of r. + + See Also + -------- + spearmanr : Spearman rank-order correlation coefficient. + kendalltau : Kendall's tau, a correlation measure for ordinal data. + + Notes + ----- + The correlation coefficient is calculated as follows: + + .. math:: + + r = \frac{\sum (x - m_x) (y - m_y)} + {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}} + + where :math:`m_x` is the mean of the vector x and :math:`m_y` is + the mean of the vector y. + + Under the assumption that x and y are drawn from + independent normal distributions (so the population correlation coefficient + is 0), the probability density function of the sample correlation + coefficient r is ([1]_, [2]_): + + .. math:: + + f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)} + + where n is the number of samples, and B is the beta function. This + is sometimes referred to as the exact distribution of r. This is + the distribution that is used in `pearsonr` to compute the p-value. + The distribution is a beta distribution on the interval [-1, 1], + with equal shape parameters a = b = n/2 - 1. In terms of SciPy's + implementation of the beta distribution, the distribution of r is:: + + dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2) + + The p-value returned by `pearsonr` is a two-sided p-value. The p-value + roughly indicates the probability of an uncorrelated system + producing datasets that have a Pearson correlation at least as extreme + as the one computed from these datasets. More precisely, for a + given sample with correlation coefficient r, the p-value is + the probability that abs(r') of a random sample x' and y' drawn from + the population with zero correlation would be greater than or equal + to abs(r). In terms of the object ``dist`` shown above, the p-value + for a given r and length n can be computed as:: + + p = 2*dist.cdf(-abs(r)) + + When n is 2, the above continuous distribution is not well-defined. + One can interpret the limit of the beta distribution as the shape + parameters a and b approach a = b = 0 as a discrete distribution with + equal probability masses at r = 1 and r = -1. More directly, one + can observe that, given the data x = [x1, x2] and y = [y1, y2], and + assuming x1 != x2 and y1 != y2, the only possible values for r are 1 + and -1. Because abs(r') for any sample x' and y' with length 2 will + be 1, the two-sided p-value for a sample of length 2 is always 1. + + References + ---------- + .. [1] "Pearson correlation coefficient", Wikipedia, + https://en.wikipedia.org/wiki/Pearson_correlation_coefficient + .. [2] Student, "Probable error of a correlation coefficient", + Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310. + .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution + of the Sample Product-Moment Correlation Coefficient" + Journal of the Royal Statistical Society. Series C (Applied + Statistics), Vol. 21, No. 1 (1972), pp. 1-12. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> from scipy.stats import mstats + >>> mstats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4]) + (-0.7426106572325057, 0.1505558088534455) + + There is a linear dependence between x and y if y = a + b*x + e, where + a,b are constants and e is a random error term, assumed to be independent + of x. For simplicity, assume that x is standard normal, a=0, b=1 and let + e follow a normal distribution with mean zero and standard deviation s>0. + + >>> s = 0.5 + >>> x = stats.norm.rvs(size=500) + >>> e = stats.norm.rvs(scale=s, size=500) + >>> y = x + e + >>> mstats.pearsonr(x, y) + (0.9029601878969703, 8.428978827629898e-185) # may vary + + This should be close to the exact value given by + + >>> 1/np.sqrt(1 + s**2) + 0.8944271909999159 + + For s=0.5, we observe a high level of correlation. In general, a large + variance of the noise reduces the correlation, while the correlation + approaches one as the variance of the error goes to zero. + + It is important to keep in mind that no correlation does not imply + independence unless (x, y) is jointly normal. Correlation can even be zero + when there is a very simple dependence structure: if X follows a + standard normal distribution, let y = abs(x). Note that the correlation + between x and y is zero. Indeed, since the expectation of x is zero, + cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero + by symmetry. The following lines of code illustrate this observation: + + >>> y = np.abs(x) + >>> mstats.pearsonr(x, y) + (-0.016172891856853524, 0.7182823678751942) # may vary + + A non-zero correlation coefficient can be misleading. For example, if X has + a standard normal distribution, define y = x if x < 0 and y = 0 otherwise. + A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797..., + implying a high level of correlation: + + >>> y = np.where(x < 0, x, 0) + >>> mstats.pearsonr(x, y) + (0.8537091583771509, 3.183461621422181e-143) # may vary + + This is unintuitive since there is no dependence of x and y if x is larger + than zero which happens in about half of the cases if we sample x and y. + """ + (x, y, n) = _chk_size(x, y) + (x, y) = (x.ravel(), y.ravel()) + # Get the common mask and the total nb of unmasked elements + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) + n -= m.sum() + df = n-2 + if df < 0: + return (masked, masked) + + return scipy.stats._stats_py.pearsonr( + ma.masked_array(x, mask=m).compressed(), + ma.masked_array(y, mask=m).compressed()) + + +def spearmanr(x, y=None, use_ties=True, axis=None, nan_policy='propagate', + alternative='two-sided'): + """ + Calculates a Spearman rank-order correlation coefficient and the p-value + to test for non-correlation. + + The Spearman correlation is a nonparametric measure of the linear + relationship between two datasets. Unlike the Pearson correlation, the + Spearman correlation does not assume that both datasets are normally + distributed. Like other correlation coefficients, this one varies + between -1 and +1 with 0 implying no correlation. Correlations of -1 or + +1 imply a monotonic relationship. Positive correlations imply that + as `x` increases, so does `y`. Negative correlations imply that as `x` + increases, `y` decreases. + + Missing values are discarded pair-wise: if a value is missing in `x`, the + corresponding value in `y` is masked. + + The p-value roughly indicates the probability of an uncorrelated system + producing datasets that have a Spearman correlation at least as extreme + as the one computed from these datasets. The p-values are not entirely + reliable but are probably reasonable for datasets larger than 500 or so. + + Parameters + ---------- + x, y : 1D or 2D array_like, y is optional + One or two 1-D or 2-D arrays containing multiple variables and + observations. When these are 1-D, each represents a vector of + observations of a single variable. For the behavior in the 2-D case, + see under ``axis``, below. + use_ties : bool, optional + DO NOT USE. Does not do anything, keyword is only left in place for + backwards compatibility reasons. + axis : int or None, optional + If axis=0 (default), then each column represents a variable, with + observations in the rows. If axis=1, the relationship is transposed: + each row represents a variable, while the columns contain observations. + If axis=None, then both arrays will be raveled. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the correlation is nonzero + * 'less': the correlation is negative (less than zero) + * 'greater': the correlation is positive (greater than zero) + + .. versionadded:: 1.7.0 + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float or ndarray (2-D square) + Spearman correlation matrix or correlation coefficient (if only 2 + variables are given as parameters). Correlation matrix is square + with length equal to total number of variables (columns or rows) in + ``a`` and ``b`` combined. + pvalue : float + The p-value for a hypothesis test whose null hypothesis + is that two sets of data are linearly uncorrelated. See + `alternative` above for alternative hypotheses. `pvalue` has the + same shape as `statistic`. + + References + ---------- + [CRCProbStat2000] section 14.7 + + """ + if not use_ties: + raise ValueError("`use_ties=False` is not supported in SciPy >= 1.2.0") + + # Always returns a masked array, raveled if axis=None + x, axisout = _chk_asarray(x, axis) + if y is not None: + # Deal only with 2-D `x` case. + y, _ = _chk_asarray(y, axis) + if axisout == 0: + x = ma.column_stack((x, y)) + else: + x = ma.vstack((x, y)) + + if axisout == 1: + # To simplify the code that follow (always use `n_obs, n_vars` shape) + x = x.T + + if nan_policy == 'omit': + x = ma.masked_invalid(x) + + def _spearmanr_2cols(x): + # Mask the same observations for all variables, and then drop those + # observations (can't leave them masked, rankdata is weird). + x = ma.mask_rowcols(x, axis=0) + x = x[~x.mask.any(axis=1), :] + + # If either column is entirely NaN or Inf + if not np.any(x.data): + res = scipy.stats._stats_py.SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + m = ma.getmask(x) + n_obs = x.shape[0] + dof = n_obs - 2 - int(m.sum(axis=0)[0]) + if dof < 0: + raise ValueError("The input must have at least 3 entries!") + + # Gets the ranks and rank differences + x_ranked = rankdata(x, axis=0) + rs = ma.corrcoef(x_ranked, rowvar=False).data + + # rs can have elements equal to 1, so avoid zero division warnings + with np.errstate(divide='ignore'): + # clip the small negative values possibly caused by rounding + # errors before taking the square root + t = rs * np.sqrt((dof / ((rs+1.0) * (1.0-rs))).clip(0)) + + t, prob = _ttest_finish(dof, t, alternative) + + # For backwards compatibility, return scalars when comparing 2 columns + if rs.shape == (2, 2): + res = scipy.stats._stats_py.SignificanceResult(rs[1, 0], + prob[1, 0]) + res.correlation = rs[1, 0] + return res + else: + res = scipy.stats._stats_py.SignificanceResult(rs, prob) + res.correlation = rs + return res + + # Need to do this per pair of variables, otherwise the dropped observations + # in a third column mess up the result for a pair. + n_vars = x.shape[1] + if n_vars == 2: + return _spearmanr_2cols(x) + else: + rs = np.ones((n_vars, n_vars), dtype=float) + prob = np.zeros((n_vars, n_vars), dtype=float) + for var1 in range(n_vars - 1): + for var2 in range(var1+1, n_vars): + result = _spearmanr_2cols(x[:, [var1, var2]]) + rs[var1, var2] = result.correlation + rs[var2, var1] = result.correlation + prob[var1, var2] = result.pvalue + prob[var2, var1] = result.pvalue + + res = scipy.stats._stats_py.SignificanceResult(rs, prob) + res.correlation = rs + return res + + +def _kendall_p_exact(n, c, alternative='two-sided'): + + # Use the fact that distribution is symmetric: always calculate a CDF in + # the left tail. + # This will be the one-sided p-value if `c` is on the side of + # the null distribution predicted by the alternative hypothesis. + # The two-sided p-value will be twice this value. + # If `c` is on the other side of the null distribution, we'll need to + # take the complement and add back the probability mass at `c`. + in_right_tail = (c >= (n*(n-1))//2 - c) + alternative_greater = (alternative == 'greater') + c = int(min(c, (n*(n-1))//2 - c)) + + # Exact p-value, see Maurice G. Kendall, "Rank Correlation Methods" + # (4th Edition), Charles Griffin & Co., 1970. + if n <= 0: + raise ValueError(f'n ({n}) must be positive') + elif c < 0 or 4*c > n*(n-1): + raise ValueError(f'c ({c}) must satisfy 0 <= 4c <= n(n-1) = {n*(n-1)}.') + elif n == 1: + prob = 1.0 + p_mass_at_c = 1 + elif n == 2: + prob = 1.0 + p_mass_at_c = 0.5 + elif c == 0: + prob = 2.0/math.factorial(n) if n < 171 else 0.0 + p_mass_at_c = prob/2 + elif c == 1: + prob = 2.0/math.factorial(n-1) if n < 172 else 0.0 + p_mass_at_c = (n-1)/math.factorial(n) + elif 4*c == n*(n-1) and alternative == 'two-sided': + # I'm sure there's a simple formula for p_mass_at_c in this + # case, but I don't know it. Use generic formula for one-sided p-value. + prob = 1.0 + elif n < 171: + new = np.zeros(c+1) + new[0:2] = 1.0 + for j in range(3,n+1): + new = np.cumsum(new) + if j <= c: + new[j:] -= new[:c+1-j] + prob = 2.0*np.sum(new)/math.factorial(n) + p_mass_at_c = new[-1]/math.factorial(n) + else: + new = np.zeros(c+1) + new[0:2] = 1.0 + for j in range(3, n+1): + new = np.cumsum(new)/j + if j <= c: + new[j:] -= new[:c+1-j] + prob = np.sum(new) + p_mass_at_c = new[-1]/2 + + if alternative != 'two-sided': + # if the alternative hypothesis and alternative agree, + # one-sided p-value is half the two-sided p-value + if in_right_tail == alternative_greater: + prob /= 2 + else: + prob = 1 - prob/2 + p_mass_at_c + + prob = np.clip(prob, 0, 1) + + return prob + + +def kendalltau(x, y, use_ties=True, use_missing=False, method='auto', + alternative='two-sided'): + """ + Computes Kendall's rank correlation tau on two variables *x* and *y*. + + Parameters + ---------- + x : sequence + First data list (for example, time). + y : sequence + Second data list. + use_ties : {True, False}, optional + Whether ties correction should be performed. + use_missing : {False, True}, optional + Whether missing data should be allocated a rank of 0 (False) or the + average rank (True) + method : {'auto', 'asymptotic', 'exact'}, optional + Defines which method is used to calculate the p-value [1]_. + 'asymptotic' uses a normal approximation valid for large samples. + 'exact' computes the exact p-value, but can only be used if no ties + are present. As the sample size increases, the 'exact' computation + time may grow and the result may lose some precision. + 'auto' is the default and selects the appropriate + method based on a trade-off between speed and accuracy. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the rank correlation is nonzero + * 'less': the rank correlation is negative (less than zero) + * 'greater': the rank correlation is positive (greater than zero) + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + The tau statistic. + pvalue : float + The p-value for a hypothesis test whose null hypothesis is + an absence of association, tau = 0. + + References + ---------- + .. [1] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition), + Charles Griffin & Co., 1970. + + """ + (x, y, n) = _chk_size(x, y) + (x, y) = (x.flatten(), y.flatten()) + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) + if m is not nomask: + x = ma.array(x, mask=m, copy=True) + y = ma.array(y, mask=m, copy=True) + # need int() here, otherwise numpy defaults to 32 bit + # integer on all Windows architectures, causing overflow. + # int() will keep it infinite precision. + n -= int(m.sum()) + + if n < 2: + res = scipy.stats._stats_py.SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + rx = ma.masked_equal(rankdata(x, use_missing=use_missing), 0) + ry = ma.masked_equal(rankdata(y, use_missing=use_missing), 0) + idx = rx.argsort() + (rx, ry) = (rx[idx], ry[idx]) + C = np.sum([((ry[i+1:] > ry[i]) * (rx[i+1:] > rx[i])).filled(0).sum() + for i in range(len(ry)-1)], dtype=float) + D = np.sum([((ry[i+1:] < ry[i])*(rx[i+1:] > rx[i])).filled(0).sum() + for i in range(len(ry)-1)], dtype=float) + xties = count_tied_groups(x) + yties = count_tied_groups(y) + if use_ties: + corr_x = np.sum([v*k*(k-1) for (k,v) in xties.items()], dtype=float) + corr_y = np.sum([v*k*(k-1) for (k,v) in yties.items()], dtype=float) + denom = ma.sqrt((n*(n-1)-corr_x)/2. * (n*(n-1)-corr_y)/2.) + else: + denom = n*(n-1)/2. + tau = (C-D) / denom + + if method == 'exact' and (xties or yties): + raise ValueError("Ties found, exact method cannot be used.") + + if method == 'auto': + if (not xties and not yties) and (n <= 33 or min(C, n*(n-1)/2.0-C) <= 1): + method = 'exact' + else: + method = 'asymptotic' + + if not xties and not yties and method == 'exact': + prob = _kendall_p_exact(n, C, alternative) + + elif method == 'asymptotic': + var_s = n*(n-1)*(2*n+5) + if use_ties: + var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in xties.items()]) + var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in yties.items()]) + v1 = (np.sum([v*k*(k-1) for (k, v) in xties.items()], dtype=float) * + np.sum([v*k*(k-1) for (k, v) in yties.items()], dtype=float)) + v1 /= 2.*n*(n-1) + if n > 2: + v2 = np.sum([v*k*(k-1)*(k-2) for (k,v) in xties.items()], + dtype=float) * \ + np.sum([v*k*(k-1)*(k-2) for (k,v) in yties.items()], + dtype=float) + v2 /= 9.*n*(n-1)*(n-2) + else: + v2 = 0 + else: + v1 = v2 = 0 + + var_s /= 18. + var_s += (v1 + v2) + z = (C-D)/np.sqrt(var_s) + prob = scipy.stats._stats_py._get_pvalue(z, distributions.norm, alternative) + else: + raise ValueError("Unknown method "+str(method)+" specified, please " + "use auto, exact or asymptotic.") + + res = scipy.stats._stats_py.SignificanceResult(tau[()], prob[()]) + res.correlation = tau + return res + + +def kendalltau_seasonal(x): + """ + Computes a multivariate Kendall's rank correlation tau, for seasonal data. + + Parameters + ---------- + x : 2-D ndarray + Array of seasonal data, with seasons in columns. + + """ + x = ma.array(x, subok=True, copy=False, ndmin=2) + (n,m) = x.shape + n_p = x.count(0) + + S_szn = sum(msign(x[i:]-x[i]).sum(0) for i in range(n)) + S_tot = S_szn.sum() + + n_tot = x.count() + ties = count_tied_groups(x.compressed()) + corr_ties = sum(v*k*(k-1) for (k,v) in ties.items()) + denom_tot = ma.sqrt(1.*n_tot*(n_tot-1)*(n_tot*(n_tot-1)-corr_ties))/2. + + R = rankdata(x, axis=0, use_missing=True) + K = ma.empty((m,m), dtype=int) + covmat = ma.empty((m,m), dtype=float) + denom_szn = ma.empty(m, dtype=float) + for j in range(m): + ties_j = count_tied_groups(x[:,j].compressed()) + corr_j = sum(v*k*(k-1) for (k,v) in ties_j.items()) + cmb = n_p[j]*(n_p[j]-1) + for k in range(j,m,1): + K[j,k] = sum(msign((x[i:,j]-x[i,j])*(x[i:,k]-x[i,k])).sum() + for i in range(n)) + covmat[j,k] = (K[j,k] + 4*(R[:,j]*R[:,k]).sum() - + n*(n_p[j]+1)*(n_p[k]+1))/3. + K[k,j] = K[j,k] + covmat[k,j] = covmat[j,k] + + denom_szn[j] = ma.sqrt(cmb*(cmb-corr_j)) / 2. + + var_szn = covmat.diagonal() + + z_szn = msign(S_szn) * (abs(S_szn)-1) / ma.sqrt(var_szn) + z_tot_ind = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(var_szn.sum()) + z_tot_dep = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(covmat.sum()) + + prob_szn = special.erfc(abs(z_szn.data)/np.sqrt(2)) + prob_tot_ind = special.erfc(abs(z_tot_ind)/np.sqrt(2)) + prob_tot_dep = special.erfc(abs(z_tot_dep)/np.sqrt(2)) + + chi2_tot = (z_szn*z_szn).sum() + chi2_trd = m * z_szn.mean()**2 + output = {'seasonal tau': S_szn/denom_szn, + 'global tau': S_tot/denom_tot, + 'global tau (alt)': S_tot/denom_szn.sum(), + 'seasonal p-value': prob_szn, + 'global p-value (indep)': prob_tot_ind, + 'global p-value (dep)': prob_tot_dep, + 'chi2 total': chi2_tot, + 'chi2 trend': chi2_trd, + } + return output + + +PointbiserialrResult = namedtuple('PointbiserialrResult', ('correlation', + 'pvalue')) + + +def pointbiserialr(x, y): + """Calculates a point biserial correlation coefficient and its p-value. + + Parameters + ---------- + x : array_like of bools + Input array. + y : array_like + Input array. + + Returns + ------- + correlation : float + R value + pvalue : float + 2-tailed p-value + + Notes + ----- + Missing values are considered pair-wise: if a value is missing in x, + the corresponding value in y is masked. + + For more details on `pointbiserialr`, see `scipy.stats.pointbiserialr`. + + """ + x = ma.fix_invalid(x, copy=True).astype(bool) + y = ma.fix_invalid(y, copy=True).astype(float) + # Get rid of the missing data + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) + if m is not nomask: + unmask = np.logical_not(m) + x = x[unmask] + y = y[unmask] + + n = len(x) + # phat is the fraction of x values that are True + phat = x.sum() / float(n) + y0 = y[~x] # y-values where x is False + y1 = y[x] # y-values where x is True + y0m = y0.mean() + y1m = y1.mean() + + rpb = (y1m - y0m)*np.sqrt(phat * (1-phat)) / y.std() + + df = n-2 + t = rpb*ma.sqrt(df/(1.0-rpb**2)) + prob = _betai(0.5*df, 0.5, df/(df+t*t)) + + return PointbiserialrResult(rpb, prob) + + +def linregress(x, y=None): + r""" + Calculate a linear least-squares regression for two sets of measurements. + + Parameters + ---------- + x, y : array_like + Two sets of measurements. Both arrays should have the same length N. If + only `x` is given (and ``y=None``), then it must be a two-dimensional + array where one dimension has length 2. The two sets of measurements + are then found by splitting the array along the length-2 dimension. In + the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is + equivalent to ``linregress(x[0], x[1])``. + + Returns + ------- + result : ``LinregressResult`` instance + The return value is an object with the following attributes: + + slope : float + Slope of the regression line. + intercept : float + Intercept of the regression line. + rvalue : float + The Pearson correlation coefficient. The square of ``rvalue`` + is equal to the coefficient of determination. + pvalue : float + The p-value for a hypothesis test whose null hypothesis is + that the slope is zero, using Wald Test with t-distribution of + the test statistic. See `alternative` above for alternative + hypotheses. + stderr : float + Standard error of the estimated slope (gradient), under the + assumption of residual normality. + intercept_stderr : float + Standard error of the estimated intercept, under the assumption + of residual normality. + + See Also + -------- + scipy.optimize.curve_fit : + Use non-linear least squares to fit a function to data. + scipy.optimize.leastsq : + Minimize the sum of squares of a set of equations. + + Notes + ----- + Missing values are considered pair-wise: if a value is missing in `x`, + the corresponding value in `y` is masked. + + For compatibility with older versions of SciPy, the return value acts + like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``, + ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write:: + + slope, intercept, r, p, se = linregress(x, y) + + With that style, however, the standard error of the intercept is not + available. To have access to all the computed values, including the + standard error of the intercept, use the return value as an object + with attributes, e.g.:: + + result = linregress(x, y) + print(result.intercept, result.intercept_stderr) + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> rng = np.random.default_rng() + + Generate some data: + + >>> x = rng.random(10) + >>> y = 1.6*x + rng.random(10) + + Perform the linear regression: + + >>> res = stats.mstats.linregress(x, y) + + Coefficient of determination (R-squared): + + >>> print(f"R-squared: {res.rvalue**2:.6f}") + R-squared: 0.717533 + + Plot the data along with the fitted line: + + >>> plt.plot(x, y, 'o', label='original data') + >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line') + >>> plt.legend() + >>> plt.show() + + Calculate 95% confidence interval on slope and intercept: + + >>> # Two-sided inverse Students t-distribution + >>> # p - probability, df - degrees of freedom + >>> from scipy.stats import t + >>> tinv = lambda p, df: abs(t.ppf(p/2, df)) + + >>> ts = tinv(0.05, len(x)-2) + >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}") + slope (95%): 1.453392 +/- 0.743465 + >>> print(f"intercept (95%): {res.intercept:.6f}" + ... f" +/- {ts*res.intercept_stderr:.6f}") + intercept (95%): 0.616950 +/- 0.544475 + + """ + if y is None: + x = ma.array(x) + if x.shape[0] == 2: + x, y = x + elif x.shape[1] == 2: + x, y = x.T + else: + raise ValueError("If only `x` is given as input, " + "it has to be of shape (2, N) or (N, 2), " + f"provided shape was {x.shape}") + else: + x = ma.array(x) + y = ma.array(y) + + x = x.flatten() + y = y.flatten() + + if np.amax(x) == np.amin(x) and len(x) > 1: + raise ValueError("Cannot calculate a linear regression " + "if all x values are identical") + + m = ma.mask_or(ma.getmask(x), ma.getmask(y), shrink=False) + if m is not nomask: + x = ma.array(x, mask=m) + y = ma.array(y, mask=m) + if np.any(~m): + result = _stats_py.linregress(x.data[~m], y.data[~m]) + else: + # All data is masked + result = _stats_py.LinregressResult(slope=None, intercept=None, + rvalue=None, pvalue=None, + stderr=None, + intercept_stderr=None) + else: + result = _stats_py.linregress(x.data, y.data) + + return result + + +def theilslopes(y, x=None, alpha=0.95, method='separate'): + r""" + Computes the Theil-Sen estimator for a set of points (x, y). + + `theilslopes` implements a method for robust linear regression. It + computes the slope as the median of all slopes between paired values. + + Parameters + ---------- + y : array_like + Dependent variable. + x : array_like or None, optional + Independent variable. If None, use ``arange(len(y))`` instead. + alpha : float, optional + Confidence degree between 0 and 1. Default is 95% confidence. + Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are + interpreted as "find the 90% confidence interval". + method : {'joint', 'separate'}, optional + Method to be used for computing estimate for intercept. + Following methods are supported, + + * 'joint': Uses np.median(y - slope * x) as intercept. + * 'separate': Uses np.median(y) - slope * np.median(x) + as intercept. + + The default is 'separate'. + + .. versionadded:: 1.8.0 + + Returns + ------- + result : ``TheilslopesResult`` instance + The return value is an object with the following attributes: + + slope : float + Theil slope. + intercept : float + Intercept of the Theil line. + low_slope : float + Lower bound of the confidence interval on `slope`. + high_slope : float + Upper bound of the confidence interval on `slope`. + + See Also + -------- + siegelslopes : a similar technique using repeated medians + + + Notes + ----- + For more details on `theilslopes`, see `scipy.stats.theilslopes`. + + """ + y = ma.asarray(y).flatten() + if x is None: + x = ma.arange(len(y), dtype=float) + else: + x = ma.asarray(x).flatten() + if len(x) != len(y): + raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})") + + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) + y._mask = x._mask = m + # Disregard any masked elements of x or y + y = y.compressed() + x = x.compressed().astype(float) + # We now have unmasked arrays so can use `scipy.stats.theilslopes` + return stats_theilslopes(y, x, alpha=alpha, method=method) + + +def siegelslopes(y, x=None, method="hierarchical"): + r""" + Computes the Siegel estimator for a set of points (x, y). + + `siegelslopes` implements a method for robust linear regression + using repeated medians to fit a line to the points (x, y). + The method is robust to outliers with an asymptotic breakdown point + of 50%. + + Parameters + ---------- + y : array_like + Dependent variable. + x : array_like or None, optional + Independent variable. If None, use ``arange(len(y))`` instead. + method : {'hierarchical', 'separate'} + If 'hierarchical', estimate the intercept using the estimated + slope ``slope`` (default option). + If 'separate', estimate the intercept independent of the estimated + slope. See Notes for details. + + Returns + ------- + result : ``SiegelslopesResult`` instance + The return value is an object with the following attributes: + + slope : float + Estimate of the slope of the regression line. + intercept : float + Estimate of the intercept of the regression line. + + See Also + -------- + theilslopes : a similar technique without repeated medians + + Notes + ----- + For more details on `siegelslopes`, see `scipy.stats.siegelslopes`. + + """ + y = ma.asarray(y).ravel() + if x is None: + x = ma.arange(len(y), dtype=float) + else: + x = ma.asarray(x).ravel() + if len(x) != len(y): + raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})") + + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) + y._mask = x._mask = m + # Disregard any masked elements of x or y + y = y.compressed() + x = x.compressed().astype(float) + # We now have unmasked arrays so can use `scipy.stats.siegelslopes` + return stats_siegelslopes(y, x, method=method) + + +SenSeasonalSlopesResult = _make_tuple_bunch('SenSeasonalSlopesResult', + ['intra_slope', 'inter_slope']) + + +def sen_seasonal_slopes(x): + r""" + Computes seasonal Theil-Sen and Kendall slope estimators. + + The seasonal generalization of Sen's slope computes the slopes between all + pairs of values within a "season" (column) of a 2D array. It returns an + array containing the median of these "within-season" slopes for each + season (the Theil-Sen slope estimator of each season), and it returns the + median of the within-season slopes across all seasons (the seasonal Kendall + slope estimator). + + Parameters + ---------- + x : 2D array_like + Each column of `x` contains measurements of the dependent variable + within a season. The independent variable (usually time) of each season + is assumed to be ``np.arange(x.shape[0])``. + + Returns + ------- + result : ``SenSeasonalSlopesResult`` instance + The return value is an object with the following attributes: + + intra_slope : ndarray + For each season, the Theil-Sen slope estimator: the median of + within-season slopes. + inter_slope : float + The seasonal Kendall slope estimator: the median of within-season + slopes *across all* seasons. + + See Also + -------- + theilslopes : the analogous function for non-seasonal data + scipy.stats.theilslopes : non-seasonal slopes for non-masked arrays + + Notes + ----- + The slopes :math:`d_{ijk}` within season :math:`i` are: + + .. math:: + + d_{ijk} = \frac{x_{ij} - x_{ik}} + {j - k} + + for pairs of distinct integer indices :math:`j, k` of :math:`x`. + + Element :math:`i` of the returned `intra_slope` array is the median of the + :math:`d_{ijk}` over all :math:`j < k`; this is the Theil-Sen slope + estimator of season :math:`i`. The returned `inter_slope` value, better + known as the seasonal Kendall slope estimator, is the median of the + :math:`d_{ijk}` over all :math:`i, j, k`. + + References + ---------- + .. [1] Hirsch, Robert M., James R. Slack, and Richard A. Smith. + "Techniques of trend analysis for monthly water quality data." + *Water Resources Research* 18.1 (1982): 107-121. + + Examples + -------- + Suppose we have 100 observations of a dependent variable for each of four + seasons: + + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> x = rng.random(size=(100, 4)) + + We compute the seasonal slopes as: + + >>> from scipy import stats + >>> intra_slope, inter_slope = stats.mstats.sen_seasonal_slopes(x) + + If we define a function to compute all slopes between observations within + a season: + + >>> def dijk(yi): + ... n = len(yi) + ... x = np.arange(n) + ... dy = yi - yi[:, np.newaxis] + ... dx = x - x[:, np.newaxis] + ... # we only want unique pairs of distinct indices + ... mask = np.triu(np.ones((n, n), dtype=bool), k=1) + ... return dy[mask]/dx[mask] + + then element ``i`` of ``intra_slope`` is the median of ``dijk[x[:, i]]``: + + >>> i = 2 + >>> np.allclose(np.median(dijk(x[:, i])), intra_slope[i]) + True + + and ``inter_slope`` is the median of the values returned by ``dijk`` for + all seasons: + + >>> all_slopes = np.concatenate([dijk(x[:, i]) for i in range(x.shape[1])]) + >>> np.allclose(np.median(all_slopes), inter_slope) + True + + Because the data are randomly generated, we would expect the median slopes + to be nearly zero both within and across all seasons, and indeed they are: + + >>> intra_slope.data + array([ 0.00124504, -0.00277761, -0.00221245, -0.00036338]) + >>> inter_slope + -0.0010511779872922058 + + """ + x = ma.array(x, subok=True, copy=False, ndmin=2) + (n,_) = x.shape + # Get list of slopes per season + szn_slopes = ma.vstack([(x[i+1:]-x[i])/np.arange(1,n-i)[:,None] + for i in range(n)]) + szn_medslopes = ma.median(szn_slopes, axis=0) + medslope = ma.median(szn_slopes, axis=None) + return SenSeasonalSlopesResult(szn_medslopes, medslope) + + +Ttest_1sampResult = namedtuple('Ttest_1sampResult', ('statistic', 'pvalue')) + + +def ttest_1samp(a, popmean, axis=0, alternative='two-sided'): + """ + Calculates the T-test for the mean of ONE group of scores. + + Parameters + ---------- + a : array_like + sample observation + popmean : float or array_like + expected value in null hypothesis, if array_like than it must have the + same shape as `a` excluding the axis dimension + axis : int or None, optional + Axis along which to compute test. If None, compute over the whole + array `a`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the mean of the underlying distribution of the sample + is different than the given population mean (`popmean`) + * 'less': the mean of the underlying distribution of the sample is + less than the given population mean (`popmean`) + * 'greater': the mean of the underlying distribution of the sample is + greater than the given population mean (`popmean`) + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float or array + t-statistic + pvalue : float or array + The p-value + + Notes + ----- + For more details on `ttest_1samp`, see `scipy.stats.ttest_1samp`. + + """ + a, axis = _chk_asarray(a, axis) + if a.size == 0: + return (np.nan, np.nan) + + x = a.mean(axis=axis) + v = a.var(axis=axis, ddof=1) + n = a.count(axis=axis) + # force df to be an array for masked division not to throw a warning + df = ma.asanyarray(n - 1.0) + svar = ((n - 1.0) * v) / df + with np.errstate(divide='ignore', invalid='ignore'): + t = (x - popmean) / ma.sqrt(svar / n) + + t, prob = _ttest_finish(df, t, alternative) + return Ttest_1sampResult(t, prob) + + +ttest_onesamp = ttest_1samp + + +Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue')) + + +def ttest_ind(a, b, axis=0, equal_var=True, alternative='two-sided'): + """ + Calculates the T-test for the means of TWO INDEPENDENT samples of scores. + + Parameters + ---------- + a, b : array_like + The arrays must have the same shape, except in the dimension + corresponding to `axis` (the first, by default). + axis : int or None, optional + Axis along which to compute test. If None, compute over the whole + arrays, `a`, and `b`. + equal_var : bool, optional + If True, perform a standard independent 2 sample test that assumes equal + population variances. + If False, perform Welch's t-test, which does not assume equal population + variance. + + .. versionadded:: 0.17.0 + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions underlying the samples + are unequal. + * 'less': the mean of the distribution underlying the first sample + is less than the mean of the distribution underlying the second + sample. + * 'greater': the mean of the distribution underlying the first + sample is greater than the mean of the distribution underlying + the second sample. + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float or array + The calculated t-statistic. + pvalue : float or array + The p-value. + + Notes + ----- + For more details on `ttest_ind`, see `scipy.stats.ttest_ind`. + + """ + a, b, axis = _chk2_asarray(a, b, axis) + + if a.size == 0 or b.size == 0: + return Ttest_indResult(np.nan, np.nan) + + (x1, x2) = (a.mean(axis), b.mean(axis)) + (v1, v2) = (a.var(axis=axis, ddof=1), b.var(axis=axis, ddof=1)) + (n1, n2) = (a.count(axis), b.count(axis)) + + if equal_var: + # force df to be an array for masked division not to throw a warning + df = ma.asanyarray(n1 + n2 - 2.0) + svar = ((n1-1)*v1+(n2-1)*v2) / df + denom = ma.sqrt(svar*(1.0/n1 + 1.0/n2)) # n-D computation here! + else: + vn1 = v1/n1 + vn2 = v2/n2 + with np.errstate(divide='ignore', invalid='ignore'): + df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1)) + + # If df is undefined, variances are zero. + # It doesn't matter what df is as long as it is not NaN. + df = np.where(np.isnan(df), 1, df) + denom = ma.sqrt(vn1 + vn2) + + with np.errstate(divide='ignore', invalid='ignore'): + t = (x1-x2) / denom + + t, prob = _ttest_finish(df, t, alternative) + return Ttest_indResult(t, prob) + + +Ttest_relResult = namedtuple('Ttest_relResult', ('statistic', 'pvalue')) + + +def ttest_rel(a, b, axis=0, alternative='two-sided'): + """ + Calculates the T-test on TWO RELATED samples of scores, a and b. + + Parameters + ---------- + a, b : array_like + The arrays must have the same shape. + axis : int or None, optional + Axis along which to compute test. If None, compute over the whole + arrays, `a`, and `b`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions underlying the samples + are unequal. + * 'less': the mean of the distribution underlying the first sample + is less than the mean of the distribution underlying the second + sample. + * 'greater': the mean of the distribution underlying the first + sample is greater than the mean of the distribution underlying + the second sample. + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float or array + t-statistic + pvalue : float or array + two-tailed p-value + + Notes + ----- + For more details on `ttest_rel`, see `scipy.stats.ttest_rel`. + + """ + a, b, axis = _chk2_asarray(a, b, axis) + if len(a) != len(b): + raise ValueError('unequal length arrays') + + if a.size == 0 or b.size == 0: + return Ttest_relResult(np.nan, np.nan) + + n = a.count(axis) + df = ma.asanyarray(n-1.0) + d = (a-b).astype('d') + dm = d.mean(axis) + v = d.var(axis=axis, ddof=1) + denom = ma.sqrt(v / n) + with np.errstate(divide='ignore', invalid='ignore'): + t = dm / denom + + t, prob = _ttest_finish(df, t, alternative) + return Ttest_relResult(t, prob) + + +MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic', + 'pvalue')) + + +def mannwhitneyu(x,y, use_continuity=True): + """ + Computes the Mann-Whitney statistic + + Missing values in `x` and/or `y` are discarded. + + Parameters + ---------- + x : sequence + Input + y : sequence + Input + use_continuity : {True, False}, optional + Whether a continuity correction (1/2.) should be taken into account. + + Returns + ------- + statistic : float + The minimum of the Mann-Whitney statistics + pvalue : float + Approximate two-sided p-value assuming a normal distribution. + + """ + x = ma.asarray(x).compressed().view(ndarray) + y = ma.asarray(y).compressed().view(ndarray) + ranks = rankdata(np.concatenate([x,y])) + (nx, ny) = (len(x), len(y)) + nt = nx + ny + U = ranks[:nx].sum() - nx*(nx+1)/2. + U = max(U, nx*ny - U) + u = nx*ny - U + + mu = (nx*ny)/2. + sigsq = (nt**3 - nt)/12. + ties = count_tied_groups(ranks) + sigsq -= sum(v*(k**3-k) for (k,v) in ties.items())/12. + sigsq *= nx*ny/float(nt*(nt-1)) + + if use_continuity: + z = (U - 1/2. - mu) / ma.sqrt(sigsq) + else: + z = (U - mu) / ma.sqrt(sigsq) + + prob = special.erfc(abs(z)/np.sqrt(2)) + return MannwhitneyuResult(u, prob) + + +KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue')) + + +def kruskal(*args): + """ + Compute the Kruskal-Wallis H-test for independent samples + + Parameters + ---------- + sample1, sample2, ... : array_like + Two or more arrays with the sample measurements can be given as + arguments. + + Returns + ------- + statistic : float + The Kruskal-Wallis H statistic, corrected for ties + pvalue : float + The p-value for the test using the assumption that H has a chi + square distribution + + Notes + ----- + For more details on `kruskal`, see `scipy.stats.kruskal`. + + Examples + -------- + >>> from scipy.stats.mstats import kruskal + + Random samples from three different brands of batteries were tested + to see how long the charge lasted. Results were as follows: + + >>> a = [6.3, 5.4, 5.7, 5.2, 5.0] + >>> b = [6.9, 7.0, 6.1, 7.9] + >>> c = [7.2, 6.9, 6.1, 6.5] + + Test the hypothesis that the distribution functions for all of the brands' + durations are identical. Use 5% level of significance. + + >>> kruskal(a, b, c) + KruskalResult(statistic=7.113812154696133, pvalue=0.028526948491942164) + + The null hypothesis is rejected at the 5% level of significance + because the returned p-value is less than the critical value of 5%. + + """ + output = argstoarray(*args) + ranks = ma.masked_equal(rankdata(output, use_missing=False), 0) + sumrk = ranks.sum(-1) + ngrp = ranks.count(-1) + ntot = ranks.count() + H = 12./(ntot*(ntot+1)) * (sumrk**2/ngrp).sum() - 3*(ntot+1) + # Tie correction + ties = count_tied_groups(ranks) + T = 1. - sum(v*(k**3-k) for (k,v) in ties.items())/float(ntot**3-ntot) + if T == 0: + raise ValueError('All numbers are identical in kruskal') + + H /= T + df = len(output) - 1 + prob = distributions.chi2.sf(H, df) + return KruskalResult(H, prob) + + +kruskalwallis = kruskal + + +@_rename_parameter("mode", "method") +def ks_1samp(x, cdf, args=(), alternative="two-sided", method='auto'): + """ + Computes the Kolmogorov-Smirnov test on one sample of masked values. + + Missing values in `x` are discarded. + + Parameters + ---------- + x : array_like + a 1-D array of observations of random variables. + cdf : str or callable + If a string, it should be the name of a distribution in `scipy.stats`. + If a callable, that callable is used to calculate the cdf. + args : tuple, sequence, optional + Distribution parameters, used if `cdf` is a string. + alternative : {'two-sided', 'less', 'greater'}, optional + Indicates the alternative hypothesis. Default is 'two-sided'. + method : {'auto', 'exact', 'asymp'}, optional + Defines the method used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : use 'exact' for small size arrays, 'asymp' for large + * 'exact' : use approximation to exact distribution of test statistic + * 'asymp' : use asymptotic distribution of test statistic + + Returns + ------- + d : float + Value of the Kolmogorov Smirnov test + p : float + Corresponding p-value. + + """ + alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( + alternative.lower()[0], alternative) + return scipy.stats._stats_py.ks_1samp( + x, cdf, args=args, alternative=alternative, method=method) + + +@_rename_parameter("mode", "method") +def ks_2samp(data1, data2, alternative="two-sided", method='auto'): + """ + Computes the Kolmogorov-Smirnov test on two samples. + + Missing values in `x` and/or `y` are discarded. + + Parameters + ---------- + data1 : array_like + First data set + data2 : array_like + Second data set + alternative : {'two-sided', 'less', 'greater'}, optional + Indicates the alternative hypothesis. Default is 'two-sided'. + method : {'auto', 'exact', 'asymp'}, optional + Defines the method used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : use 'exact' for small size arrays, 'asymp' for large + * 'exact' : use approximation to exact distribution of test statistic + * 'asymp' : use asymptotic distribution of test statistic + + Returns + ------- + d : float + Value of the Kolmogorov Smirnov test + p : float + Corresponding p-value. + + """ + # Ideally this would be accomplished by + # ks_2samp = scipy.stats._stats_py.ks_2samp + # but the circular dependencies between _mstats_basic and stats prevent that. + alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( + alternative.lower()[0], alternative) + return scipy.stats._stats_py.ks_2samp(data1, data2, + alternative=alternative, + method=method) + + +ks_twosamp = ks_2samp + + +@_rename_parameter("mode", "method") +def kstest(data1, data2, args=(), alternative='two-sided', method='auto'): + """ + + Parameters + ---------- + data1 : array_like + data2 : str, callable or array_like + args : tuple, sequence, optional + Distribution parameters, used if `data1` or `data2` are strings. + alternative : str, as documented in stats.kstest + method : str, as documented in stats.kstest + + Returns + ------- + tuple of (K-S statistic, probability) + + """ + return scipy.stats._stats_py.kstest(data1, data2, args, + alternative=alternative, method=method) + + +def trima(a, limits=None, inclusive=(True,True)): + """ + Trims an array by masking the data outside some given limits. + + Returns a masked version of the input array. + + Parameters + ---------- + a : array_like + Input array. + limits : {None, tuple}, optional + Tuple of (lower limit, upper limit) in absolute values. + Values of the input array lower (greater) than the lower (upper) limit + will be masked. A limit is None indicates an open interval. + inclusive : (bool, bool) tuple, optional + Tuple of (lower flag, upper flag), indicating whether values exactly + equal to the lower (upper) limit are allowed. + + Examples + -------- + >>> from scipy.stats.mstats import trima + >>> import numpy as np + + >>> a = np.arange(10) + + The interval is left-closed and right-open, i.e., `[2, 8)`. + Trim the array by keeping only values in the interval. + + >>> trima(a, limits=(2, 8), inclusive=(True, False)) + masked_array(data=[--, --, 2, 3, 4, 5, 6, 7, --, --], + mask=[ True, True, False, False, False, False, False, False, + True, True], + fill_value=999999) + + """ + a = ma.asarray(a) + a.unshare_mask() + if (limits is None) or (limits == (None, None)): + return a + + (lower_lim, upper_lim) = limits + (lower_in, upper_in) = inclusive + condition = False + if lower_lim is not None: + if lower_in: + condition |= (a < lower_lim) + else: + condition |= (a <= lower_lim) + + if upper_lim is not None: + if upper_in: + condition |= (a > upper_lim) + else: + condition |= (a >= upper_lim) + + a[condition.filled(True)] = masked + return a + + +def trimr(a, limits=None, inclusive=(True, True), axis=None): + """ + Trims an array by masking some proportion of the data on each end. + Returns a masked version of the input array. + + Parameters + ---------- + a : sequence + Input array. + limits : {None, tuple}, optional + Tuple of the percentages to cut on each side of the array, with respect + to the number of unmasked data, as floats between 0. and 1. + Noting n the number of unmasked data before trimming, the + (n*limits[0])th smallest data and the (n*limits[1])th largest data are + masked, and the total number of unmasked data after trimming is + n*(1.-sum(limits)). The value of one limit can be set to None to + indicate an open interval. + inclusive : {(True,True) tuple}, optional + Tuple of flags indicating whether the number of data being masked on + the left (right) end should be truncated (True) or rounded (False) to + integers. + axis : {None,int}, optional + Axis along which to trim. If None, the whole array is trimmed, but its + shape is maintained. + + """ + def _trimr1D(a, low_limit, up_limit, low_inclusive, up_inclusive): + n = a.count() + idx = a.argsort() + if low_limit: + if low_inclusive: + lowidx = int(low_limit*n) + else: + lowidx = int(np.round(low_limit*n)) + a[idx[:lowidx]] = masked + if up_limit is not None: + if up_inclusive: + upidx = n - int(n*up_limit) + else: + upidx = n - int(np.round(n*up_limit)) + a[idx[upidx:]] = masked + return a + + a = ma.asarray(a) + a.unshare_mask() + if limits is None: + return a + + # Check the limits + (lolim, uplim) = limits + errmsg = "The proportion to cut from the %s should be between 0. and 1." + if lolim is not None: + if lolim > 1. or lolim < 0: + raise ValueError(errmsg % 'beginning' + f"(got {lolim})") + if uplim is not None: + if uplim > 1. or uplim < 0: + raise ValueError(errmsg % 'end' + f"(got {uplim})") + + (loinc, upinc) = inclusive + + if axis is None: + shp = a.shape + return _trimr1D(a.ravel(),lolim,uplim,loinc,upinc).reshape(shp) + else: + return ma.apply_along_axis(_trimr1D, axis, a, lolim,uplim,loinc,upinc) + + +trimdoc = """ + Parameters + ---------- + a : sequence + Input array + limits : {None, tuple}, optional + If `relative` is False, tuple (lower limit, upper limit) in absolute values. + Values of the input array lower (greater) than the lower (upper) limit are + masked. + + If `relative` is True, tuple (lower percentage, upper percentage) to cut + on each side of the array, with respect to the number of unmasked data. + + Noting n the number of unmasked data before trimming, the (n*limits[0])th + smallest data and the (n*limits[1])th largest data are masked, and the + total number of unmasked data after trimming is n*(1.-sum(limits)) + In each case, the value of one limit can be set to None to indicate an + open interval. + + If limits is None, no trimming is performed + inclusive : {(bool, bool) tuple}, optional + If `relative` is False, tuple indicating whether values exactly equal + to the absolute limits are allowed. + If `relative` is True, tuple indicating whether the number of data + being masked on each side should be rounded (True) or truncated + (False). + relative : bool, optional + Whether to consider the limits as absolute values (False) or proportions + to cut (True). + axis : int, optional + Axis along which to trim. +""" + + +def trim(a, limits=None, inclusive=(True,True), relative=False, axis=None): + """ + Trims an array by masking the data outside some given limits. + + Returns a masked version of the input array. + + %s + + Examples + -------- + >>> from scipy.stats.mstats import trim + >>> z = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10] + >>> print(trim(z,(3,8))) + [-- -- 3 4 5 6 7 8 -- --] + >>> print(trim(z,(0.1,0.2),relative=True)) + [-- 2 3 4 5 6 7 8 -- --] + + """ + if relative: + return trimr(a, limits=limits, inclusive=inclusive, axis=axis) + else: + return trima(a, limits=limits, inclusive=inclusive) + + +if trim.__doc__: + trim.__doc__ = trim.__doc__ % trimdoc + + +def trimboth(data, proportiontocut=0.2, inclusive=(True,True), axis=None): + """ + Trims the smallest and largest data values. + + Trims the `data` by masking the ``int(proportiontocut * n)`` smallest and + ``int(proportiontocut * n)`` largest values of data along the given axis, + where n is the number of unmasked values before trimming. + + Parameters + ---------- + data : ndarray + Data to trim. + proportiontocut : float, optional + Percentage of trimming (as a float between 0 and 1). + If n is the number of unmasked values before trimming, the number of + values after trimming is ``(1 - 2*proportiontocut) * n``. + Default is 0.2. + inclusive : {(bool, bool) tuple}, optional + Tuple indicating whether the number of data being masked on each side + should be rounded (True) or truncated (False). + axis : int, optional + Axis along which to perform the trimming. + If None, the input array is first flattened. + + """ + return trimr(data, limits=(proportiontocut,proportiontocut), + inclusive=inclusive, axis=axis) + + +def trimtail(data, proportiontocut=0.2, tail='left', inclusive=(True,True), + axis=None): + """ + Trims the data by masking values from one tail. + + Parameters + ---------- + data : array_like + Data to trim. + proportiontocut : float, optional + Percentage of trimming. If n is the number of unmasked values + before trimming, the number of values after trimming is + ``(1 - proportiontocut) * n``. Default is 0.2. + tail : {'left','right'}, optional + If 'left' the `proportiontocut` lowest values will be masked. + If 'right' the `proportiontocut` highest values will be masked. + Default is 'left'. + inclusive : {(bool, bool) tuple}, optional + Tuple indicating whether the number of data being masked on each side + should be rounded (True) or truncated (False). Default is + (True, True). + axis : int, optional + Axis along which to perform the trimming. + If None, the input array is first flattened. Default is None. + + Returns + ------- + trimtail : ndarray + Returned array of same shape as `data` with masked tail values. + + """ + tail = str(tail).lower()[0] + if tail == 'l': + limits = (proportiontocut,None) + elif tail == 'r': + limits = (None, proportiontocut) + else: + raise TypeError("The tail argument should be in ('left','right')") + + return trimr(data, limits=limits, axis=axis, inclusive=inclusive) + + +trim1 = trimtail + + +def trimmed_mean(a, limits=(0.1,0.1), inclusive=(1,1), relative=True, + axis=None): + """Returns the trimmed mean of the data along the given axis. + + %s + + """ + if (not isinstance(limits,tuple)) and isinstance(limits,float): + limits = (limits, limits) + if relative: + return trimr(a,limits=limits,inclusive=inclusive,axis=axis).mean(axis=axis) + else: + return trima(a,limits=limits,inclusive=inclusive).mean(axis=axis) + + +if trimmed_mean.__doc__: + trimmed_mean.__doc__ = trimmed_mean.__doc__ % trimdoc + + +def trimmed_var(a, limits=(0.1,0.1), inclusive=(1,1), relative=True, + axis=None, ddof=0): + """Returns the trimmed variance of the data along the given axis. + + %s + ddof : {0,integer}, optional + Means Delta Degrees of Freedom. The denominator used during computations + is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un- + biased estimate of the variance. + + """ + if (not isinstance(limits,tuple)) and isinstance(limits,float): + limits = (limits, limits) + if relative: + out = trimr(a,limits=limits, inclusive=inclusive,axis=axis) + else: + out = trima(a,limits=limits,inclusive=inclusive) + + return out.var(axis=axis, ddof=ddof) + + +if trimmed_var.__doc__: + trimmed_var.__doc__ = trimmed_var.__doc__ % trimdoc + + +def trimmed_std(a, limits=(0.1,0.1), inclusive=(1,1), relative=True, + axis=None, ddof=0): + """Returns the trimmed standard deviation of the data along the given axis. + + %s + ddof : {0,integer}, optional + Means Delta Degrees of Freedom. The denominator used during computations + is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un- + biased estimate of the variance. + + """ + if (not isinstance(limits,tuple)) and isinstance(limits,float): + limits = (limits, limits) + if relative: + out = trimr(a,limits=limits,inclusive=inclusive,axis=axis) + else: + out = trima(a,limits=limits,inclusive=inclusive) + return out.std(axis=axis,ddof=ddof) + + +if trimmed_std.__doc__: + trimmed_std.__doc__ = trimmed_std.__doc__ % trimdoc + + +def trimmed_stde(a, limits=(0.1,0.1), inclusive=(1,1), axis=None): + """ + Returns the standard error of the trimmed mean along the given axis. + + Parameters + ---------- + a : sequence + Input array + limits : {(0.1,0.1), tuple of float}, optional + tuple (lower percentage, upper percentage) to cut on each side of the + array, with respect to the number of unmasked data. + + If n is the number of unmasked data before trimming, the values + smaller than ``n * limits[0]`` and the values larger than + ``n * `limits[1]`` are masked, and the total number of unmasked + data after trimming is ``n * (1.-sum(limits))``. In each case, + the value of one limit can be set to None to indicate an open interval. + If `limits` is None, no trimming is performed. + inclusive : {(bool, bool) tuple} optional + Tuple indicating whether the number of data being masked on each side + should be rounded (True) or truncated (False). + axis : int, optional + Axis along which to trim. + + Returns + ------- + trimmed_stde : scalar or ndarray + + """ + def _trimmed_stde_1D(a, low_limit, up_limit, low_inclusive, up_inclusive): + "Returns the standard error of the trimmed mean for a 1D input data." + n = a.count() + idx = a.argsort() + if low_limit: + if low_inclusive: + lowidx = int(low_limit*n) + else: + lowidx = np.round(low_limit*n) + a[idx[:lowidx]] = masked + if up_limit is not None: + if up_inclusive: + upidx = n - int(n*up_limit) + else: + upidx = n - np.round(n*up_limit) + a[idx[upidx:]] = masked + a[idx[:lowidx]] = a[idx[lowidx]] + a[idx[upidx:]] = a[idx[upidx-1]] + winstd = a.std(ddof=1) + return winstd / ((1-low_limit-up_limit)*np.sqrt(len(a))) + + a = ma.array(a, copy=True, subok=True) + a.unshare_mask() + if limits is None: + return a.std(axis=axis,ddof=1)/ma.sqrt(a.count(axis)) + if (not isinstance(limits,tuple)) and isinstance(limits,float): + limits = (limits, limits) + + # Check the limits + (lolim, uplim) = limits + errmsg = "The proportion to cut from the %s should be between 0. and 1." + if lolim is not None: + if lolim > 1. or lolim < 0: + raise ValueError(errmsg % 'beginning' + f"(got {lolim})") + if uplim is not None: + if uplim > 1. or uplim < 0: + raise ValueError(errmsg % 'end' + f"(got {uplim})") + + (loinc, upinc) = inclusive + if (axis is None): + return _trimmed_stde_1D(a.ravel(),lolim,uplim,loinc,upinc) + else: + if a.ndim > 2: + raise ValueError("Array 'a' must be at most two dimensional, " + "but got a.ndim = %d" % a.ndim) + return ma.apply_along_axis(_trimmed_stde_1D, axis, a, + lolim,uplim,loinc,upinc) + + +def _mask_to_limits(a, limits, inclusive): + """Mask an array for values outside of given limits. + + This is primarily a utility function. + + Parameters + ---------- + a : array + limits : (float or None, float or None) + A tuple consisting of the (lower limit, upper limit). Values in the + input array less than the lower limit or greater than the upper limit + will be masked out. None implies no limit. + inclusive : (bool, bool) + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to lower or upper are allowed. + + Returns + ------- + A MaskedArray. + + Raises + ------ + A ValueError if there are no values within the given limits. + """ + lower_limit, upper_limit = limits + lower_include, upper_include = inclusive + am = ma.MaskedArray(a) + if lower_limit is not None: + if lower_include: + am = ma.masked_less(am, lower_limit) + else: + am = ma.masked_less_equal(am, lower_limit) + + if upper_limit is not None: + if upper_include: + am = ma.masked_greater(am, upper_limit) + else: + am = ma.masked_greater_equal(am, upper_limit) + + if am.count() == 0: + raise ValueError("No array values within given limits") + + return am + + +def tmean(a, limits=None, inclusive=(True, True), axis=None): + """ + Compute the trimmed mean. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None (default), then all + values are used. Either of the limit values in the tuple can also be + None representing a half-open interval. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. If None, compute over the + whole array. Default is None. + + Returns + ------- + tmean : float + + Notes + ----- + For more details on `tmean`, see `scipy.stats.tmean`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import mstats + >>> a = np.array([[6, 8, 3, 0], + ... [3, 9, 1, 2], + ... [8, 7, 8, 2], + ... [5, 6, 0, 2], + ... [4, 5, 5, 2]]) + ... + ... + >>> mstats.tmean(a, (2,5)) + 3.3 + >>> mstats.tmean(a, (2,5), axis=0) + masked_array(data=[4.0, 5.0, 4.0, 2.0], + mask=[False, False, False, False], + fill_value=1e+20) + + """ + return trima(a, limits=limits, inclusive=inclusive).mean(axis=axis) + + +def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """ + Compute the trimmed variance + + This function computes the sample variance of an array of values, + while ignoring values which are outside of given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. If None, compute over the + whole array. Default is zero. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tvar : float + Trimmed variance. + + Notes + ----- + For more details on `tvar`, see `scipy.stats.tvar`. + + """ + a = a.astype(float).ravel() + if limits is None: + n = (~a.mask).sum() # todo: better way to do that? + return np.ma.var(a) * n/(n-1.) + am = _mask_to_limits(a, limits=limits, inclusive=inclusive) + + return np.ma.var(am, axis=axis, ddof=ddof) + + +def tmin(a, lowerlimit=None, axis=0, inclusive=True): + """ + Compute the trimmed minimum + + Parameters + ---------- + a : array_like + array of values + lowerlimit : None or float, optional + Values in the input array less than the given limit will be ignored. + When lowerlimit is None, then all values are used. The default value + is None. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + inclusive : {True, False}, optional + This flag determines whether values exactly equal to the lower limit + are included. The default value is True. + + Returns + ------- + tmin : float, int or ndarray + + Notes + ----- + For more details on `tmin`, see `scipy.stats.tmin`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import mstats + >>> a = np.array([[6, 8, 3, 0], + ... [3, 2, 1, 2], + ... [8, 1, 8, 2], + ... [5, 3, 0, 2], + ... [4, 7, 5, 2]]) + ... + >>> mstats.tmin(a, 5) + masked_array(data=[5, 7, 5, --], + mask=[False, False, False, True], + fill_value=999999) + + """ + a, axis = _chk_asarray(a, axis) + am = trima(a, (lowerlimit, None), (inclusive, False)) + return ma.minimum.reduce(am, axis) + + +def tmax(a, upperlimit=None, axis=0, inclusive=True): + """ + Compute the trimmed maximum + + This function computes the maximum value of an array along a given axis, + while ignoring values larger than a specified upper limit. + + Parameters + ---------- + a : array_like + array of values + upperlimit : None or float, optional + Values in the input array greater than the given limit will be ignored. + When upperlimit is None, then all values are used. The default value + is None. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + inclusive : {True, False}, optional + This flag determines whether values exactly equal to the upper limit + are included. The default value is True. + + Returns + ------- + tmax : float, int or ndarray + + Notes + ----- + For more details on `tmax`, see `scipy.stats.tmax`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import mstats + >>> a = np.array([[6, 8, 3, 0], + ... [3, 9, 1, 2], + ... [8, 7, 8, 2], + ... [5, 6, 0, 2], + ... [4, 5, 5, 2]]) + ... + ... + >>> mstats.tmax(a, 4) + masked_array(data=[4, --, 3, 2], + mask=[False, True, False, False], + fill_value=999999) + + """ + a, axis = _chk_asarray(a, axis) + am = trima(a, (None, upperlimit), (False, inclusive)) + return ma.maximum.reduce(am, axis) + + +def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """ + Compute the trimmed standard error of the mean. + + This function finds the standard error of the mean for given + values, ignoring values outside the given `limits`. + + Parameters + ---------- + a : array_like + array of values + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. If None, compute over the + whole array. Default is zero. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tsem : float + + Notes + ----- + For more details on `tsem`, see `scipy.stats.tsem`. + + """ + a = ma.asarray(a).ravel() + if limits is None: + n = float(a.count()) + return a.std(axis=axis, ddof=ddof)/ma.sqrt(n) + + am = trima(a.ravel(), limits, inclusive) + sd = np.sqrt(am.var(axis=axis, ddof=ddof)) + return sd / np.sqrt(am.count()) + + +def winsorize(a, limits=None, inclusive=(True, True), inplace=False, + axis=None, nan_policy='propagate'): + """Returns a Winsorized version of the input array. + + The (limits[0])th lowest values are set to the (limits[0])th percentile, + and the (limits[1])th highest values are set to the (1 - limits[1])th + percentile. + Masked values are skipped. + + + Parameters + ---------- + a : sequence + Input array. + limits : {None, tuple of float}, optional + Tuple of the percentages to cut on each side of the array, with respect + to the number of unmasked data, as floats between 0. and 1. + Noting n the number of unmasked data before trimming, the + (n*limits[0])th smallest data and the (n*limits[1])th largest data are + masked, and the total number of unmasked data after trimming + is n*(1.-sum(limits)) The value of one limit can be set to None to + indicate an open interval. + inclusive : {(True, True) tuple}, optional + Tuple indicating whether the number of data being masked on each side + should be truncated (True) or rounded (False). + inplace : {False, True}, optional + Whether to winsorize in place (True) or to use a copy (False) + axis : {None, int}, optional + Axis along which to trim. If None, the whole array is trimmed, but its + shape is maintained. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': allows nan values and may overwrite or propagate them + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Notes + ----- + This function is applied to reduce the effect of possibly spurious outliers + by limiting the extreme values. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats.mstats import winsorize + + A shuffled array contains integers from 1 to 10. + + >>> a = np.array([10, 4, 9, 8, 5, 3, 7, 2, 1, 6]) + + The 10% of the lowest value (i.e., ``1``) and the 20% of the highest + values (i.e., ``9`` and ``10``) are replaced. + + >>> winsorize(a, limits=[0.1, 0.2]) + masked_array(data=[8, 4, 8, 8, 5, 3, 7, 2, 2, 6], + mask=False, + fill_value=999999) + + """ + def _winsorize1D(a, low_limit, up_limit, low_include, up_include, + contains_nan, nan_policy): + n = a.count() + idx = a.argsort() + if contains_nan: + nan_count = np.count_nonzero(np.isnan(a)) + if low_limit: + if low_include: + lowidx = int(low_limit * n) + else: + lowidx = np.round(low_limit * n).astype(int) + if contains_nan and nan_policy == 'omit': + lowidx = min(lowidx, n-nan_count-1) + a[idx[:lowidx]] = a[idx[lowidx]] + if up_limit is not None: + if up_include: + upidx = n - int(n * up_limit) + else: + upidx = n - np.round(n * up_limit).astype(int) + if contains_nan and nan_policy == 'omit': + a[idx[upidx:-nan_count]] = a[idx[upidx - 1]] + else: + a[idx[upidx:]] = a[idx[upidx - 1]] + return a + + contains_nan, nan_policy = _contains_nan(a, nan_policy) + # We are going to modify a: better make a copy + a = ma.array(a, copy=np.logical_not(inplace)) + + if limits is None: + return a + if (not isinstance(limits, tuple)) and isinstance(limits, float): + limits = (limits, limits) + + # Check the limits + (lolim, uplim) = limits + errmsg = "The proportion to cut from the %s should be between 0. and 1." + if lolim is not None: + if lolim > 1. or lolim < 0: + raise ValueError(errmsg % 'beginning' + f"(got {lolim})") + if uplim is not None: + if uplim > 1. or uplim < 0: + raise ValueError(errmsg % 'end' + f"(got {uplim})") + + (loinc, upinc) = inclusive + + if axis is None: + shp = a.shape + return _winsorize1D(a.ravel(), lolim, uplim, loinc, upinc, + contains_nan, nan_policy).reshape(shp) + else: + return ma.apply_along_axis(_winsorize1D, axis, a, lolim, uplim, loinc, + upinc, contains_nan, nan_policy) + + +def moment(a, moment=1, axis=0): + """ + Calculates the nth moment about the mean for a sample. + + Parameters + ---------- + a : array_like + data + moment : int, optional + order of central moment that is returned + axis : int or None, optional + Axis along which the central moment is computed. Default is 0. + If None, compute over the whole array `a`. + + Returns + ------- + n-th central moment : ndarray or float + The appropriate moment along the given axis or over all values if axis + is None. The denominator for the moment calculation is the number of + observations, no degrees of freedom correction is done. + + Notes + ----- + For more details about `moment`, see `scipy.stats.moment`. + + """ + a, axis = _chk_asarray(a, axis) + if a.size == 0: + moment_shape = list(a.shape) + del moment_shape[axis] + dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64 + # empty array, return nan(s) with shape matching `moment` + out_shape = (moment_shape if np.isscalar(moment) + else [len(moment)] + moment_shape) + if len(out_shape) == 0: + return dtype(np.nan) + else: + return ma.array(np.full(out_shape, np.nan, dtype=dtype)) + + # for array_like moment input, return a value for each. + if not np.isscalar(moment): + mean = a.mean(axis, keepdims=True) + mmnt = [_moment(a, i, axis, mean=mean) for i in moment] + return ma.array(mmnt) + else: + return _moment(a, moment, axis) + + +# Moment with optional pre-computed mean, equal to a.mean(axis, keepdims=True) +def _moment(a, moment, axis, *, mean=None): + if np.abs(moment - np.round(moment)) > 0: + raise ValueError("All moment parameters must be integers") + + if moment == 0 or moment == 1: + # By definition the zeroth moment about the mean is 1, and the first + # moment is 0. + shape = list(a.shape) + del shape[axis] + dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64 + + if len(shape) == 0: + return dtype(1.0 if moment == 0 else 0.0) + else: + return (ma.ones(shape, dtype=dtype) if moment == 0 + else ma.zeros(shape, dtype=dtype)) + else: + # Exponentiation by squares: form exponent sequence + n_list = [moment] + current_n = moment + while current_n > 2: + if current_n % 2: + current_n = (current_n-1)/2 + else: + current_n /= 2 + n_list.append(current_n) + + # Starting point for exponentiation by squares + mean = a.mean(axis, keepdims=True) if mean is None else mean + a_zero_mean = a - mean + if n_list[-1] == 1: + s = a_zero_mean.copy() + else: + s = a_zero_mean**2 + + # Perform multiplications + for n in n_list[-2::-1]: + s = s**2 + if n % 2: + s *= a_zero_mean + return s.mean(axis) + + +def variation(a, axis=0, ddof=0): + """ + Compute the coefficient of variation. + + The coefficient of variation is the standard deviation divided by the + mean. This function is equivalent to:: + + np.std(x, axis=axis, ddof=ddof) / np.mean(x) + + The default for ``ddof`` is 0, but many definitions of the coefficient + of variation use the square root of the unbiased sample variance + for the sample standard deviation, which corresponds to ``ddof=1``. + + Parameters + ---------- + a : array_like + Input array. + axis : int or None, optional + Axis along which to calculate the coefficient of variation. Default + is 0. If None, compute over the whole array `a`. + ddof : int, optional + Delta degrees of freedom. Default is 0. + + Returns + ------- + variation : ndarray + The calculated variation along the requested axis. + + Notes + ----- + For more details about `variation`, see `scipy.stats.variation`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats.mstats import variation + >>> a = np.array([2,8,4]) + >>> variation(a) + 0.5345224838248487 + >>> b = np.array([2,8,3,4]) + >>> c = np.ma.masked_array(b, mask=[0,0,1,0]) + >>> variation(c) + 0.5345224838248487 + + In the example above, it can be seen that this works the same as + `scipy.stats.variation` except 'stats.mstats.variation' ignores masked + array elements. + + """ + a, axis = _chk_asarray(a, axis) + return a.std(axis, ddof=ddof)/a.mean(axis) + + +def skew(a, axis=0, bias=True): + """ + Computes the skewness of a data set. + + Parameters + ---------- + a : ndarray + data + axis : int or None, optional + Axis along which skewness is calculated. Default is 0. + If None, compute over the whole array `a`. + bias : bool, optional + If False, then the calculations are corrected for statistical bias. + + Returns + ------- + skewness : ndarray + The skewness of values along an axis, returning 0 where all values are + equal. + + Notes + ----- + For more details about `skew`, see `scipy.stats.skew`. + + """ + a, axis = _chk_asarray(a,axis) + mean = a.mean(axis, keepdims=True) + m2 = _moment(a, 2, axis, mean=mean) + m3 = _moment(a, 3, axis, mean=mean) + zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2) + with np.errstate(all='ignore'): + vals = ma.where(zero, 0, m3 / m2**1.5) + + if not bias and zero is not ma.masked and m2 is not ma.masked: + n = a.count(axis) + can_correct = ~zero & (n > 2) + if can_correct.any(): + n = np.extract(can_correct, n) + m2 = np.extract(can_correct, m2) + m3 = np.extract(can_correct, m3) + nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5 + np.place(vals, can_correct, nval) + return vals + + +def kurtosis(a, axis=0, fisher=True, bias=True): + """ + Computes the kurtosis (Fisher or Pearson) of a dataset. + + Kurtosis is the fourth central moment divided by the square of the + variance. If Fisher's definition is used, then 3.0 is subtracted from + the result to give 0.0 for a normal distribution. + + If bias is False then the kurtosis is calculated using k statistics to + eliminate bias coming from biased moment estimators + + Use `kurtosistest` to see if result is close enough to normal. + + Parameters + ---------- + a : array + data for which the kurtosis is calculated + axis : int or None, optional + Axis along which the kurtosis is calculated. Default is 0. + If None, compute over the whole array `a`. + fisher : bool, optional + If True, Fisher's definition is used (normal ==> 0.0). If False, + Pearson's definition is used (normal ==> 3.0). + bias : bool, optional + If False, then the calculations are corrected for statistical bias. + + Returns + ------- + kurtosis : array + The kurtosis of values along an axis. If all values are equal, + return -3 for Fisher's definition and 0 for Pearson's definition. + + Notes + ----- + For more details about `kurtosis`, see `scipy.stats.kurtosis`. + + """ + a, axis = _chk_asarray(a, axis) + mean = a.mean(axis, keepdims=True) + m2 = _moment(a, 2, axis, mean=mean) + m4 = _moment(a, 4, axis, mean=mean) + zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2) + with np.errstate(all='ignore'): + vals = ma.where(zero, 0, m4 / m2**2.0) + + if not bias and zero is not ma.masked and m2 is not ma.masked: + n = a.count(axis) + can_correct = ~zero & (n > 3) + if can_correct.any(): + n = np.extract(can_correct, n) + m2 = np.extract(can_correct, m2) + m4 = np.extract(can_correct, m4) + nval = 1.0/(n-2)/(n-3)*((n*n-1.0)*m4/m2**2.0-3*(n-1)**2.0) + np.place(vals, can_correct, nval+3.0) + if fisher: + return vals - 3 + else: + return vals + + +DescribeResult = namedtuple('DescribeResult', ('nobs', 'minmax', 'mean', + 'variance', 'skewness', + 'kurtosis')) + + +def describe(a, axis=0, ddof=0, bias=True): + """ + Computes several descriptive statistics of the passed array. + + Parameters + ---------- + a : array_like + Data array + axis : int or None, optional + Axis along which to calculate statistics. Default 0. If None, + compute over the whole array `a`. + ddof : int, optional + degree of freedom (default 0); note that default ddof is different + from the same routine in stats.describe + bias : bool, optional + If False, then the skewness and kurtosis calculations are corrected for + statistical bias. + + Returns + ------- + nobs : int + (size of the data (discarding missing values) + + minmax : (int, int) + min, max + + mean : float + arithmetic mean + + variance : float + unbiased variance + + skewness : float + biased skewness + + kurtosis : float + biased kurtosis + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats.mstats import describe + >>> ma = np.ma.array(range(6), mask=[0, 0, 0, 1, 1, 1]) + >>> describe(ma) + DescribeResult(nobs=np.int64(3), minmax=(masked_array(data=0, + mask=False, + fill_value=999999), masked_array(data=2, + mask=False, + fill_value=999999)), mean=np.float64(1.0), + variance=np.float64(0.6666666666666666), + skewness=masked_array(data=0., mask=False, fill_value=1e+20), + kurtosis=np.float64(-1.5)) + + """ + a, axis = _chk_asarray(a, axis) + n = a.count(axis) + mm = (ma.minimum.reduce(a, axis=axis), ma.maximum.reduce(a, axis=axis)) + m = a.mean(axis) + v = a.var(axis, ddof=ddof) + sk = skew(a, axis, bias=bias) + kurt = kurtosis(a, axis, bias=bias) + + return DescribeResult(n, mm, m, v, sk, kurt) + + +def stde_median(data, axis=None): + """Returns the McKean-Schrader estimate of the standard error of the sample + median along the given axis. masked values are discarded. + + Parameters + ---------- + data : ndarray + Data to trim. + axis : {None,int}, optional + Axis along which to perform the trimming. + If None, the input array is first flattened. + + """ + def _stdemed_1D(data): + data = np.sort(data.compressed()) + n = len(data) + z = 2.5758293035489004 + k = int(np.round((n+1)/2. - z * np.sqrt(n/4.),0)) + return ((data[n-k] - data[k-1])/(2.*z)) + + data = ma.array(data, copy=False, subok=True) + if (axis is None): + return _stdemed_1D(data) + else: + if data.ndim > 2: + raise ValueError("Array 'data' must be at most two dimensional, " + "but got data.ndim = %d" % data.ndim) + return ma.apply_along_axis(_stdemed_1D, axis, data) + + +SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue')) + + +def skewtest(a, axis=0, alternative='two-sided'): + """ + Tests whether the skew is different from the normal distribution. + + Parameters + ---------- + a : array_like + The data to be tested + axis : int or None, optional + Axis along which statistics are calculated. Default is 0. + If None, compute over the whole array `a`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the skewness of the distribution underlying the sample + is different from that of the normal distribution (i.e. 0) + * 'less': the skewness of the distribution underlying the sample + is less than that of the normal distribution + * 'greater': the skewness of the distribution underlying the sample + is greater than that of the normal distribution + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : array_like + The computed z-score for this test. + pvalue : array_like + A p-value for the hypothesis test + + Notes + ----- + For more details about `skewtest`, see `scipy.stats.skewtest`. + + """ + a, axis = _chk_asarray(a, axis) + if axis is None: + a = a.ravel() + axis = 0 + b2 = skew(a,axis) + n = a.count(axis) + if np.min(n) < 8: + raise ValueError( + "skewtest is not valid with less than 8 samples; %i samples" + " were given." % np.min(n)) + + y = b2 * ma.sqrt(((n+1)*(n+3)) / (6.0*(n-2))) + beta2 = (3.0*(n*n+27*n-70)*(n+1)*(n+3)) / ((n-2.0)*(n+5)*(n+7)*(n+9)) + W2 = -1 + ma.sqrt(2*(beta2-1)) + delta = 1/ma.sqrt(0.5*ma.log(W2)) + alpha = ma.sqrt(2.0/(W2-1)) + y = ma.where(y == 0, 1, y) + Z = delta*ma.log(y/alpha + ma.sqrt((y/alpha)**2+1)) + pvalue = scipy.stats._stats_py._get_pvalue(Z, distributions.norm, alternative) + + return SkewtestResult(Z[()], pvalue[()]) + + +KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue')) + + +def kurtosistest(a, axis=0, alternative='two-sided'): + """ + Tests whether a dataset has normal kurtosis + + Parameters + ---------- + a : array_like + array of the sample data + axis : int or None, optional + Axis along which to compute test. Default is 0. If None, + compute over the whole array `a`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the kurtosis of the distribution underlying the sample + is different from that of the normal distribution + * 'less': the kurtosis of the distribution underlying the sample + is less than that of the normal distribution + * 'greater': the kurtosis of the distribution underlying the sample + is greater than that of the normal distribution + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : array_like + The computed z-score for this test. + pvalue : array_like + The p-value for the hypothesis test + + Notes + ----- + For more details about `kurtosistest`, see `scipy.stats.kurtosistest`. + + """ + a, axis = _chk_asarray(a, axis) + n = a.count(axis=axis) + if np.min(n) < 5: + raise ValueError( + "kurtosistest requires at least 5 observations; %i observations" + " were given." % np.min(n)) + if np.min(n) < 20: + warnings.warn( + "kurtosistest only valid for n>=20 ... continuing anyway, n=%i" % np.min(n), + stacklevel=2, + ) + + b2 = kurtosis(a, axis, fisher=False) + E = 3.0*(n-1) / (n+1) + varb2 = 24.0*n*(n-2.)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) + x = (b2-E)/ma.sqrt(varb2) + sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5)) / + (n*(n-2)*(n-3))) + A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2))) + term1 = 1 - 2./(9.0*A) + denom = 1 + x*ma.sqrt(2/(A-4.0)) + if np.ma.isMaskedArray(denom): + # For multi-dimensional array input + denom[denom == 0.0] = masked + elif denom == 0.0: + denom = masked + + term2 = np.ma.where(denom > 0, ma.power((1-2.0/A)/denom, 1/3.0), + -ma.power(-(1-2.0/A)/denom, 1/3.0)) + Z = (term1 - term2) / np.sqrt(2/(9.0*A)) + pvalue = scipy.stats._stats_py._get_pvalue(Z, distributions.norm, alternative) + + return KurtosistestResult(Z[()], pvalue[()]) + + +NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue')) + + +def normaltest(a, axis=0): + """ + Tests whether a sample differs from a normal distribution. + + Parameters + ---------- + a : array_like + The array containing the data to be tested. + axis : int or None, optional + Axis along which to compute test. Default is 0. If None, + compute over the whole array `a`. + + Returns + ------- + statistic : float or array + ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and + ``k`` is the z-score returned by `kurtosistest`. + pvalue : float or array + A 2-sided chi squared probability for the hypothesis test. + + Notes + ----- + For more details about `normaltest`, see `scipy.stats.normaltest`. + + """ + a, axis = _chk_asarray(a, axis) + s, _ = skewtest(a, axis) + k, _ = kurtosistest(a, axis) + k2 = s*s + k*k + + return NormaltestResult(k2, distributions.chi2.sf(k2, 2)) + + +def mquantiles(a, prob=(.25, .5, .75), alphap=.4, betap=.4, axis=None, + limit=()): + """ + Computes empirical quantiles for a data array. + + Samples quantile are defined by ``Q(p) = (1-gamma)*x[j] + gamma*x[j+1]``, + where ``x[j]`` is the j-th order statistic, and gamma is a function of + ``j = floor(n*p + m)``, ``m = alphap + p*(1 - alphap - betap)`` and + ``g = n*p + m - j``. + + Reinterpreting the above equations to compare to **R** lead to the + equation: ``p(k) = (k - alphap)/(n + 1 - alphap - betap)`` + + Typical values of (alphap,betap) are: + - (0,1) : ``p(k) = k/n`` : linear interpolation of cdf + (**R** type 4) + - (.5,.5) : ``p(k) = (k - 1/2.)/n`` : piecewise linear function + (**R** type 5) + - (0,0) : ``p(k) = k/(n+1)`` : + (**R** type 6) + - (1,1) : ``p(k) = (k-1)/(n-1)``: p(k) = mode[F(x[k])]. + (**R** type 7, **R** default) + - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``: Then p(k) ~ median[F(x[k])]. + The resulting quantile estimates are approximately median-unbiased + regardless of the distribution of x. + (**R** type 8) + - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``: Blom. + The resulting quantile estimates are approximately unbiased + if x is normally distributed + (**R** type 9) + - (.4,.4) : approximately quantile unbiased (Cunnane) + - (.35,.35): APL, used with PWM + + Parameters + ---------- + a : array_like + Input data, as a sequence or array of dimension at most 2. + prob : array_like, optional + List of quantiles to compute. + alphap : float, optional + Plotting positions parameter, default is 0.4. + betap : float, optional + Plotting positions parameter, default is 0.4. + axis : int, optional + Axis along which to perform the trimming. + If None (default), the input array is first flattened. + limit : tuple, optional + Tuple of (lower, upper) values. + Values of `a` outside this open interval are ignored. + + Returns + ------- + mquantiles : MaskedArray + An array containing the calculated quantiles. + + Notes + ----- + This formulation is very similar to **R** except the calculation of + ``m`` from ``alphap`` and ``betap``, where in **R** ``m`` is defined + with each type. + + References + ---------- + .. [1] *R* statistical software: https://www.r-project.org/ + .. [2] *R* ``quantile`` function: + http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats.mstats import mquantiles + >>> a = np.array([6., 47., 49., 15., 42., 41., 7., 39., 43., 40., 36.]) + >>> mquantiles(a) + array([ 19.2, 40. , 42.8]) + + Using a 2D array, specifying axis and limit. + + >>> data = np.array([[ 6., 7., 1.], + ... [ 47., 15., 2.], + ... [ 49., 36., 3.], + ... [ 15., 39., 4.], + ... [ 42., 40., -999.], + ... [ 41., 41., -999.], + ... [ 7., -999., -999.], + ... [ 39., -999., -999.], + ... [ 43., -999., -999.], + ... [ 40., -999., -999.], + ... [ 36., -999., -999.]]) + >>> print(mquantiles(data, axis=0, limit=(0, 50))) + [[19.2 14.6 1.45] + [40. 37.5 2.5 ] + [42.8 40.05 3.55]] + + >>> data[:, 2] = -999. + >>> print(mquantiles(data, axis=0, limit=(0, 50))) + [[19.200000000000003 14.6 --] + [40.0 37.5 --] + [42.800000000000004 40.05 --]] + + """ + def _quantiles1D(data,m,p): + x = np.sort(data.compressed()) + n = len(x) + if n == 0: + return ma.array(np.empty(len(p), dtype=float), mask=True) + elif n == 1: + return ma.array(np.resize(x, p.shape), mask=nomask) + aleph = (n*p + m) + k = np.floor(aleph.clip(1, n-1)).astype(int) + gamma = (aleph-k).clip(0,1) + return (1.-gamma)*x[(k-1).tolist()] + gamma*x[k.tolist()] + + data = ma.array(a, copy=False) + if data.ndim > 2: + raise TypeError("Array should be 2D at most !") + + if limit: + condition = (limit[0] < data) & (data < limit[1]) + data[~condition.filled(True)] = masked + + p = np.atleast_1d(np.asarray(prob)) + m = alphap + p*(1.-alphap-betap) + # Computes quantiles along axis (or globally) + if (axis is None): + return _quantiles1D(data, m, p) + + return ma.apply_along_axis(_quantiles1D, axis, data, m, p) + + +def scoreatpercentile(data, per, limit=(), alphap=.4, betap=.4): + """Calculate the score at the given 'per' percentile of the + sequence a. For example, the score at per=50 is the median. + + This function is a shortcut to mquantile + + """ + if (per < 0) or (per > 100.): + raise ValueError(f"The percentile should be between 0. and 100. ! (got {per})") + + return mquantiles(data, prob=[per/100.], alphap=alphap, betap=betap, + limit=limit, axis=0).squeeze() + + +def plotting_positions(data, alpha=0.4, beta=0.4): + """ + Returns plotting positions (or empirical percentile points) for the data. + + Plotting positions are defined as ``(i-alpha)/(n+1-alpha-beta)``, where: + - i is the rank order statistics + - n is the number of unmasked values along the given axis + - `alpha` and `beta` are two parameters. + + Typical values for `alpha` and `beta` are: + - (0,1) : ``p(k) = k/n``, linear interpolation of cdf (R, type 4) + - (.5,.5) : ``p(k) = (k-1/2.)/n``, piecewise linear function + (R, type 5) + - (0,0) : ``p(k) = k/(n+1)``, Weibull (R type 6) + - (1,1) : ``p(k) = (k-1)/(n-1)``, in this case, + ``p(k) = mode[F(x[k])]``. That's R default (R type 7) + - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``, then + ``p(k) ~ median[F(x[k])]``. + The resulting quantile estimates are approximately median-unbiased + regardless of the distribution of x. (R type 8) + - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``, Blom. + The resulting quantile estimates are approximately unbiased + if x is normally distributed (R type 9) + - (.4,.4) : approximately quantile unbiased (Cunnane) + - (.35,.35): APL, used with PWM + - (.3175, .3175): used in scipy.stats.probplot + + Parameters + ---------- + data : array_like + Input data, as a sequence or array of dimension at most 2. + alpha : float, optional + Plotting positions parameter. Default is 0.4. + beta : float, optional + Plotting positions parameter. Default is 0.4. + + Returns + ------- + positions : MaskedArray + The calculated plotting positions. + + """ + data = ma.array(data, copy=False).reshape(1,-1) + n = data.count() + plpos = np.empty(data.size, dtype=float) + plpos[n:] = 0 + plpos[data.argsort(axis=None)[:n]] = ((np.arange(1, n+1) - alpha) / + (n + 1.0 - alpha - beta)) + return ma.array(plpos, mask=data._mask) + + +meppf = plotting_positions + + +def obrientransform(*args): + """ + Computes a transform on input data (any number of columns). Used to + test for homogeneity of variance prior to running one-way stats. Each + array in ``*args`` is one level of a factor. If an `f_oneway()` run on + the transformed data and found significant, variances are unequal. From + Maxwell and Delaney, p.112. + + Returns: transformed data for use in an ANOVA + """ + data = argstoarray(*args).T + v = data.var(axis=0,ddof=1) + m = data.mean(0) + n = data.count(0).astype(float) + # result = ((N-1.5)*N*(a-m)**2 - 0.5*v*(n-1))/((n-1)*(n-2)) + data -= m + data **= 2 + data *= (n-1.5)*n + data -= 0.5*v*(n-1) + data /= (n-1.)*(n-2.) + if not ma.allclose(v,data.mean(0)): + raise ValueError("Lack of convergence in obrientransform.") + + return data + + +def sem(a, axis=0, ddof=1): + """ + Calculates the standard error of the mean of the input array. + + Also sometimes called standard error of measurement. + + Parameters + ---------- + a : array_like + An array containing the values for which the standard error is + returned. + axis : int or None, optional + If axis is None, ravel `a` first. If axis is an integer, this will be + the axis over which to operate. Defaults to 0. + ddof : int, optional + Delta degrees-of-freedom. How many degrees of freedom to adjust + for bias in limited samples relative to the population estimate + of variance. Defaults to 1. + + Returns + ------- + s : ndarray or float + The standard error of the mean in the sample(s), along the input axis. + + Notes + ----- + The default value for `ddof` changed in scipy 0.15.0 to be consistent with + `scipy.stats.sem` as well as with the most common definition used (like in + the R documentation). + + Examples + -------- + Find standard error along the first axis: + + >>> import numpy as np + >>> from scipy import stats + >>> a = np.arange(20).reshape(5,4) + >>> print(stats.mstats.sem(a)) + [2.8284271247461903 2.8284271247461903 2.8284271247461903 + 2.8284271247461903] + + Find standard error across the whole array, using n degrees of freedom: + + >>> print(stats.mstats.sem(a, axis=None, ddof=0)) + 1.2893796958227628 + + """ + a, axis = _chk_asarray(a, axis) + n = a.count(axis=axis) + s = a.std(axis=axis, ddof=ddof) / ma.sqrt(n) + return s + + +F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue')) + + +def f_oneway(*args): + """ + Performs a 1-way ANOVA, returning an F-value and probability given + any number of groups. From Heiman, pp.394-7. + + Usage: ``f_oneway(*args)``, where ``*args`` is 2 or more arrays, + one per treatment group. + + Returns + ------- + statistic : float + The computed F-value of the test. + pvalue : float + The associated p-value from the F-distribution. + + """ + # Construct a single array of arguments: each row is a group + data = argstoarray(*args) + ngroups = len(data) + ntot = data.count() + sstot = (data**2).sum() - (data.sum())**2/float(ntot) + ssbg = (data.count(-1) * (data.mean(-1)-data.mean())**2).sum() + sswg = sstot-ssbg + dfbg = ngroups-1 + dfwg = ntot - ngroups + msb = ssbg/float(dfbg) + msw = sswg/float(dfwg) + f = msb/msw + prob = special.fdtrc(dfbg, dfwg, f) # equivalent to stats.f.sf + + return F_onewayResult(f, prob) + + +FriedmanchisquareResult = namedtuple('FriedmanchisquareResult', + ('statistic', 'pvalue')) + + +def friedmanchisquare(*args): + """Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. + This function calculates the Friedman Chi-square test for repeated measures + and returns the result, along with the associated probability value. + + Each input is considered a given group. Ideally, the number of treatments + among each group should be equal. If this is not the case, only the first + n treatments are taken into account, where n is the number of treatments + of the smallest group. + If a group has some missing values, the corresponding treatments are masked + in the other groups. + The test statistic is corrected for ties. + + Masked values in one group are propagated to the other groups. + + Returns + ------- + statistic : float + the test statistic. + pvalue : float + the associated p-value. + + """ + data = argstoarray(*args).astype(float) + k = len(data) + if k < 3: + raise ValueError("Less than 3 groups (%i): " % k + + "the Friedman test is NOT appropriate.") + + ranked = ma.masked_values(rankdata(data, axis=0), 0) + if ranked._mask is not nomask: + ranked = ma.mask_cols(ranked) + ranked = ranked.compressed().reshape(k,-1).view(ndarray) + else: + ranked = ranked._data + (k,n) = ranked.shape + # Ties correction + repeats = [find_repeats(row) for row in ranked.T] + ties = np.array([y for x, y in repeats if x.size > 0]) + tie_correction = 1 - (ties**3-ties).sum()/float(n*(k**3-k)) + + ssbg = np.sum((ranked.sum(-1) - n*(k+1)/2.)**2) + chisq = ssbg * 12./(n*k*(k+1)) * 1./tie_correction + + return FriedmanchisquareResult(chisq, + distributions.chi2.sf(chisq, k-1)) + + +BrunnerMunzelResult = namedtuple('BrunnerMunzelResult', ('statistic', 'pvalue')) + + +def brunnermunzel(x, y, alternative="two-sided", distribution="t"): + """ + Compute the Brunner-Munzel test on samples x and y. + + Any missing values in `x` and/or `y` are discarded. + + The Brunner-Munzel test is a nonparametric test of the null hypothesis that + when values are taken one by one from each group, the probabilities of + getting large values in both groups are equal. + Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the + assumption of equivariance of two groups. Note that this does not assume + the distributions are same. This test works on two independent samples, + which may have different sizes. + + Parameters + ---------- + x, y : array_like + Array of samples, should be one-dimensional. + alternative : 'less', 'two-sided', or 'greater', optional + Whether to get the p-value for the one-sided hypothesis ('less' + or 'greater') or for the two-sided hypothesis ('two-sided'). + Defaults value is 'two-sided' . + distribution : 't' or 'normal', optional + Whether to get the p-value by t-distribution or by standard normal + distribution. + Defaults value is 't' . + + Returns + ------- + statistic : float + The Brunner-Munzer W statistic. + pvalue : float + p-value assuming an t distribution. One-sided or + two-sided, depending on the choice of `alternative` and `distribution`. + + See Also + -------- + mannwhitneyu : Mann-Whitney rank test on two samples. + + Notes + ----- + For more details on `brunnermunzel`, see `scipy.stats.brunnermunzel`. + + Examples + -------- + >>> from scipy.stats.mstats import brunnermunzel + >>> import numpy as np + >>> x1 = [1, 2, np.nan, np.nan, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1] + >>> x2 = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4] + >>> brunnermunzel(x1, x2) + BrunnerMunzelResult(statistic=1.4723186918922935, pvalue=0.15479415300426624) # may vary + + """ # noqa: E501 + x = ma.asarray(x).compressed().view(ndarray) + y = ma.asarray(y).compressed().view(ndarray) + nx = len(x) + ny = len(y) + if nx == 0 or ny == 0: + return BrunnerMunzelResult(np.nan, np.nan) + rankc = rankdata(np.concatenate((x,y))) + rankcx = rankc[0:nx] + rankcy = rankc[nx:nx+ny] + rankcx_mean = np.mean(rankcx) + rankcy_mean = np.mean(rankcy) + rankx = rankdata(x) + ranky = rankdata(y) + rankx_mean = np.mean(rankx) + ranky_mean = np.mean(ranky) + + Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0)) + Sx /= nx - 1 + Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0)) + Sy /= ny - 1 + + wbfn = nx * ny * (rankcy_mean - rankcx_mean) + wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy) + + if distribution == "t": + df_numer = np.power(nx * Sx + ny * Sy, 2.0) + df_denom = np.power(nx * Sx, 2.0) / (nx - 1) + df_denom += np.power(ny * Sy, 2.0) / (ny - 1) + df = df_numer / df_denom + p = distributions.t.cdf(wbfn, df) + elif distribution == "normal": + p = distributions.norm.cdf(wbfn) + else: + raise ValueError( + "distribution should be 't' or 'normal'") + + if alternative == "greater": + pass + elif alternative == "less": + p = 1 - p + elif alternative == "two-sided": + p = 2 * np.min([p, 1-p]) + else: + raise ValueError( + "alternative should be 'less', 'greater' or 'two-sided'") + + return BrunnerMunzelResult(wbfn, p) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_extras.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_extras.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea1e56a99d530ded03210ee72c3cd4755b15d44 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_extras.py @@ -0,0 +1,521 @@ +""" +Additional statistics functions with support for masked arrays. + +""" + +# Original author (2007): Pierre GF Gerard-Marchant + + +__all__ = ['compare_medians_ms', + 'hdquantiles', 'hdmedian', 'hdquantiles_sd', + 'idealfourths', + 'median_cihs','mjci','mquantiles_cimj', + 'rsh', + 'trimmed_mean_ci',] + + +import numpy as np +from numpy import float64, ndarray + +import numpy.ma as ma +from numpy.ma import MaskedArray + +from . import _mstats_basic as mstats + +from scipy.stats.distributions import norm, beta, t, binom + + +def hdquantiles(data, prob=(.25, .5, .75), axis=None, var=False,): + """ + Computes quantile estimates with the Harrell-Davis method. + + The quantile estimates are calculated as a weighted linear combination + of order statistics. + + Parameters + ---------- + data : array_like + Data array. + prob : sequence, optional + Sequence of probabilities at which to compute the quantiles. + axis : int or None, optional + Axis along which to compute the quantiles. If None, use a flattened + array. + var : bool, optional + Whether to return the variance of the estimate. + + Returns + ------- + hdquantiles : MaskedArray + A (p,) array of quantiles (if `var` is False), or a (2,p) array of + quantiles and variances (if `var` is True), where ``p`` is the + number of quantiles. + + See Also + -------- + hdquantiles_sd + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats.mstats import hdquantiles + >>> + >>> # Sample data + >>> data = np.array([1.2, 2.5, 3.7, 4.0, 5.1, 6.3, 7.0, 8.2, 9.4]) + >>> + >>> # Probabilities at which to compute quantiles + >>> probabilities = [0.25, 0.5, 0.75] + >>> + >>> # Compute Harrell-Davis quantile estimates + >>> quantile_estimates = hdquantiles(data, prob=probabilities) + >>> + >>> # Display the quantile estimates + >>> for i, quantile in enumerate(probabilities): + ... print(f"{int(quantile * 100)}th percentile: {quantile_estimates[i]}") + 25th percentile: 3.1505820231763066 # may vary + 50th percentile: 5.194344084883956 + 75th percentile: 7.430626414674935 + + """ + def _hd_1D(data,prob,var): + "Computes the HD quantiles for a 1D array. Returns nan for invalid data." + xsorted = np.squeeze(np.sort(data.compressed().view(ndarray))) + # Don't use length here, in case we have a numpy scalar + n = xsorted.size + + hd = np.empty((2,len(prob)), float64) + if n < 2: + hd.flat = np.nan + if var: + return hd + return hd[0] + + v = np.arange(n+1) / float(n) + betacdf = beta.cdf + for (i,p) in enumerate(prob): + _w = betacdf(v, (n+1)*p, (n+1)*(1-p)) + w = _w[1:] - _w[:-1] + hd_mean = np.dot(w, xsorted) + hd[0,i] = hd_mean + # + hd[1,i] = np.dot(w, (xsorted-hd_mean)**2) + # + hd[0, prob == 0] = xsorted[0] + hd[0, prob == 1] = xsorted[-1] + if var: + hd[1, prob == 0] = hd[1, prob == 1] = np.nan + return hd + return hd[0] + # Initialization & checks + data = ma.array(data, copy=False, dtype=float64) + p = np.atleast_1d(np.asarray(prob)) + # Computes quantiles along axis (or globally) + if (axis is None) or (data.ndim == 1): + result = _hd_1D(data, p, var) + else: + if data.ndim > 2: + raise ValueError("Array 'data' must be at most two dimensional, " + "but got data.ndim = %d" % data.ndim) + result = ma.apply_along_axis(_hd_1D, axis, data, p, var) + + return ma.fix_invalid(result, copy=False) + + +def hdmedian(data, axis=-1, var=False): + """ + Returns the Harrell-Davis estimate of the median along the given axis. + + Parameters + ---------- + data : ndarray + Data array. + axis : int, optional + Axis along which to compute the quantiles. If None, use a flattened + array. + var : bool, optional + Whether to return the variance of the estimate. + + Returns + ------- + hdmedian : MaskedArray + The median values. If ``var=True``, the variance is returned inside + the masked array. E.g. for a 1-D array the shape change from (1,) to + (2,). + + """ + result = hdquantiles(data,[0.5], axis=axis, var=var) + return result.squeeze() + + +def hdquantiles_sd(data, prob=(.25, .5, .75), axis=None): + """ + The standard error of the Harrell-Davis quantile estimates by jackknife. + + Parameters + ---------- + data : array_like + Data array. + prob : sequence, optional + Sequence of quantiles to compute. + axis : int, optional + Axis along which to compute the quantiles. If None, use a flattened + array. + + Returns + ------- + hdquantiles_sd : MaskedArray + Standard error of the Harrell-Davis quantile estimates. + + See Also + -------- + hdquantiles + + """ + def _hdsd_1D(data, prob): + "Computes the std error for 1D arrays." + xsorted = np.sort(data.compressed()) + n = len(xsorted) + + hdsd = np.empty(len(prob), float64) + if n < 2: + hdsd.flat = np.nan + + vv = np.arange(n) / float(n-1) + betacdf = beta.cdf + + for (i,p) in enumerate(prob): + _w = betacdf(vv, n*p, n*(1-p)) + w = _w[1:] - _w[:-1] + # cumulative sum of weights and data points if + # ith point is left out for jackknife + mx_ = np.zeros_like(xsorted) + mx_[1:] = np.cumsum(w * xsorted[:-1]) + # similar but from the right + mx_[:-1] += np.cumsum(w[::-1] * xsorted[:0:-1])[::-1] + hdsd[i] = np.sqrt(mx_.var() * (n - 1)) + return hdsd + + # Initialization & checks + data = ma.array(data, copy=False, dtype=float64) + p = np.atleast_1d(np.asarray(prob)) + # Computes quantiles along axis (or globally) + if (axis is None): + result = _hdsd_1D(data, p) + else: + if data.ndim > 2: + raise ValueError("Array 'data' must be at most two dimensional, " + "but got data.ndim = %d" % data.ndim) + result = ma.apply_along_axis(_hdsd_1D, axis, data, p) + + return ma.fix_invalid(result, copy=False).ravel() + + +def trimmed_mean_ci(data, limits=(0.2,0.2), inclusive=(True,True), + alpha=0.05, axis=None): + """ + Selected confidence interval of the trimmed mean along the given axis. + + Parameters + ---------- + data : array_like + Input data. + limits : {None, tuple}, optional + None or a two item tuple. + Tuple of the percentages to cut on each side of the array, with respect + to the number of unmasked data, as floats between 0. and 1. If ``n`` + is the number of unmasked data before trimming, then + (``n * limits[0]``)th smallest data and (``n * limits[1]``)th + largest data are masked. The total number of unmasked data after + trimming is ``n * (1. - sum(limits))``. + The value of one limit can be set to None to indicate an open interval. + + Defaults to (0.2, 0.2). + inclusive : (2,) tuple of boolean, optional + If relative==False, tuple indicating whether values exactly equal to + the absolute limits are allowed. + If relative==True, tuple indicating whether the number of data being + masked on each side should be rounded (True) or truncated (False). + + Defaults to (True, True). + alpha : float, optional + Confidence level of the intervals. + + Defaults to 0.05. + axis : int, optional + Axis along which to cut. If None, uses a flattened version of `data`. + + Defaults to None. + + Returns + ------- + trimmed_mean_ci : (2,) ndarray + The lower and upper confidence intervals of the trimmed data. + + """ + data = ma.array(data, copy=False) + trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis) + tmean = trimmed.mean(axis) + tstde = mstats.trimmed_stde(data,limits=limits,inclusive=inclusive,axis=axis) + df = trimmed.count(axis) - 1 + tppf = t.ppf(1-alpha/2.,df) + return np.array((tmean - tppf*tstde, tmean+tppf*tstde)) + + +def mjci(data, prob=(0.25, 0.5, 0.75), axis=None): + """ + Returns the Maritz-Jarrett estimators of the standard error of selected + experimental quantiles of the data. + + Parameters + ---------- + data : ndarray + Data array. + prob : sequence, optional + Sequence of quantiles to compute. + axis : int or None, optional + Axis along which to compute the quantiles. If None, use a flattened + array. + + """ + def _mjci_1D(data, p): + data = np.sort(data.compressed()) + n = data.size + prob = (np.array(p) * n + 0.5).astype(int) + betacdf = beta.cdf + + mj = np.empty(len(prob), float64) + x = np.arange(1,n+1, dtype=float64) / n + y = x - 1./n + for (i,m) in enumerate(prob): + W = betacdf(x,m-1,n-m) - betacdf(y,m-1,n-m) + C1 = np.dot(W,data) + C2 = np.dot(W,data**2) + mj[i] = np.sqrt(C2 - C1**2) + return mj + + data = ma.array(data, copy=False) + if data.ndim > 2: + raise ValueError("Array 'data' must be at most two dimensional, " + "but got data.ndim = %d" % data.ndim) + + p = np.atleast_1d(np.asarray(prob)) + # Computes quantiles along axis (or globally) + if (axis is None): + return _mjci_1D(data, p) + else: + return ma.apply_along_axis(_mjci_1D, axis, data, p) + + +def mquantiles_cimj(data, prob=(0.25, 0.50, 0.75), alpha=0.05, axis=None): + """ + Computes the alpha confidence interval for the selected quantiles of the + data, with Maritz-Jarrett estimators. + + Parameters + ---------- + data : ndarray + Data array. + prob : sequence, optional + Sequence of quantiles to compute. + alpha : float, optional + Confidence level of the intervals. + axis : int or None, optional + Axis along which to compute the quantiles. + If None, use a flattened array. + + Returns + ------- + ci_lower : ndarray + The lower boundaries of the confidence interval. Of the same length as + `prob`. + ci_upper : ndarray + The upper boundaries of the confidence interval. Of the same length as + `prob`. + + """ + alpha = min(alpha, 1 - alpha) + z = norm.ppf(1 - alpha/2.) + xq = mstats.mquantiles(data, prob, alphap=0, betap=0, axis=axis) + smj = mjci(data, prob, axis=axis) + return (xq - z * smj, xq + z * smj) + + +def median_cihs(data, alpha=0.05, axis=None): + """ + Computes the alpha-level confidence interval for the median of the data. + + Uses the Hettmasperger-Sheather method. + + Parameters + ---------- + data : array_like + Input data. Masked values are discarded. The input should be 1D only, + or `axis` should be set to None. + alpha : float, optional + Confidence level of the intervals. + axis : int or None, optional + Axis along which to compute the quantiles. If None, use a flattened + array. + + Returns + ------- + median_cihs + Alpha level confidence interval. + + """ + def _cihs_1D(data, alpha): + data = np.sort(data.compressed()) + n = len(data) + alpha = min(alpha, 1-alpha) + k = int(binom._ppf(alpha/2., n, 0.5)) + gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5) + if gk < 1-alpha: + k -= 1 + gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5) + gkk = binom.cdf(n-k-1,n,0.5) - binom.cdf(k,n,0.5) + I = (gk - 1 + alpha)/(gk - gkk) + lambd = (n-k) * I / float(k + (n-2*k)*I) + lims = (lambd*data[k] + (1-lambd)*data[k-1], + lambd*data[n-k-1] + (1-lambd)*data[n-k]) + return lims + data = ma.array(data, copy=False) + # Computes quantiles along axis (or globally) + if (axis is None): + result = _cihs_1D(data, alpha) + else: + if data.ndim > 2: + raise ValueError("Array 'data' must be at most two dimensional, " + "but got data.ndim = %d" % data.ndim) + result = ma.apply_along_axis(_cihs_1D, axis, data, alpha) + + return result + + +def compare_medians_ms(group_1, group_2, axis=None): + """ + Compares the medians from two independent groups along the given axis. + + The comparison is performed using the McKean-Schrader estimate of the + standard error of the medians. + + Parameters + ---------- + group_1 : array_like + First dataset. Has to be of size >=7. + group_2 : array_like + Second dataset. Has to be of size >=7. + axis : int, optional + Axis along which the medians are estimated. If None, the arrays are + flattened. If `axis` is not None, then `group_1` and `group_2` + should have the same shape. + + Returns + ------- + compare_medians_ms : {float, ndarray} + If `axis` is None, then returns a float, otherwise returns a 1-D + ndarray of floats with a length equal to the length of `group_1` + along `axis`. + + Examples + -------- + + >>> from scipy import stats + >>> a = [1, 2, 3, 4, 5, 6, 7] + >>> b = [8, 9, 10, 11, 12, 13, 14] + >>> stats.mstats.compare_medians_ms(a, b, axis=None) + 1.0693225866553746e-05 + + The function is vectorized to compute along a given axis. + + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> x = rng.random(size=(3, 7)) + >>> y = rng.random(size=(3, 8)) + >>> stats.mstats.compare_medians_ms(x, y, axis=1) + array([0.36908985, 0.36092538, 0.2765313 ]) + + References + ---------- + .. [1] McKean, Joseph W., and Ronald M. Schrader. "A comparison of methods + for studentizing the sample median." Communications in + Statistics-Simulation and Computation 13.6 (1984): 751-773. + + """ + (med_1, med_2) = (ma.median(group_1,axis=axis), ma.median(group_2,axis=axis)) + (std_1, std_2) = (mstats.stde_median(group_1, axis=axis), + mstats.stde_median(group_2, axis=axis)) + W = np.abs(med_1 - med_2) / ma.sqrt(std_1**2 + std_2**2) + return 1 - norm.cdf(W) + + +def idealfourths(data, axis=None): + """ + Returns an estimate of the lower and upper quartiles. + + Uses the ideal fourths algorithm. + + Parameters + ---------- + data : array_like + Input array. + axis : int, optional + Axis along which the quartiles are estimated. If None, the arrays are + flattened. + + Returns + ------- + idealfourths : {list of floats, masked array} + Returns the two internal values that divide `data` into four parts + using the ideal fourths algorithm either along the flattened array + (if `axis` is None) or along `axis` of `data`. + + """ + def _idf(data): + x = data.compressed() + n = len(x) + if n < 3: + return [np.nan,np.nan] + (j,h) = divmod(n/4. + 5/12.,1) + j = int(j) + qlo = (1-h)*x[j-1] + h*x[j] + k = n - j + qup = (1-h)*x[k] + h*x[k-1] + return [qlo, qup] + data = ma.sort(data, axis=axis).view(MaskedArray) + if (axis is None): + return _idf(data) + else: + return ma.apply_along_axis(_idf, axis, data) + + +def rsh(data, points=None): + """ + Evaluates Rosenblatt's shifted histogram estimators for each data point. + + Rosenblatt's estimator is a centered finite-difference approximation to the + derivative of the empirical cumulative distribution function. + + Parameters + ---------- + data : sequence + Input data, should be 1-D. Masked values are ignored. + points : sequence or None, optional + Sequence of points where to evaluate Rosenblatt shifted histogram. + If None, use the data. + + """ + data = ma.array(data, copy=False) + if points is None: + points = data + else: + points = np.atleast_1d(np.asarray(points)) + + if data.ndim != 1: + raise AttributeError("The input array should be 1D only !") + + n = data.count() + r = idealfourths(data, axis=None) + h = 1.2 * (r[-1]-r[0]) / n**(1./5) + nhi = (data[:,None] <= points[None,:] + h).sum(0) + nlo = (data[:,None] < points[None,:] - h).sum(0) + return (nhi-nlo) / (2.*n*h) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_multicomp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_multicomp.py new file mode 100644 index 0000000000000000000000000000000000000000..164a57650dca442702b45f89168d5b4a747ef030 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_multicomp.py @@ -0,0 +1,449 @@ +import warnings +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal + +import numpy as np + +from scipy import stats +from scipy.optimize import minimize_scalar +from scipy.stats._common import ConfidenceInterval +from scipy.stats._qmc import check_random_state +from scipy.stats._stats_py import _var +from scipy._lib._util import _transition_to_rng, DecimalNumber, SeedType + + +if TYPE_CHECKING: + import numpy.typing as npt + + +__all__ = [ + 'dunnett' +] + + +@dataclass +class DunnettResult: + """Result object returned by `scipy.stats.dunnett`. + + Attributes + ---------- + statistic : float ndarray + The computed statistic of the test for each comparison. The element + at index ``i`` is the statistic for the comparison between + groups ``i`` and the control. + pvalue : float ndarray + The computed p-value of the test for each comparison. The element + at index ``i`` is the p-value for the comparison between + group ``i`` and the control. + """ + statistic: np.ndarray + pvalue: np.ndarray + _alternative: Literal['two-sided', 'less', 'greater'] = field(repr=False) + _rho: np.ndarray = field(repr=False) + _df: int = field(repr=False) + _std: float = field(repr=False) + _mean_samples: np.ndarray = field(repr=False) + _mean_control: np.ndarray = field(repr=False) + _n_samples: np.ndarray = field(repr=False) + _n_control: int = field(repr=False) + _rng: SeedType = field(repr=False) + _ci: ConfidenceInterval | None = field(default=None, repr=False) + _ci_cl: DecimalNumber | None = field(default=None, repr=False) + + def __str__(self): + # Note: `__str__` prints the confidence intervals from the most + # recent call to `confidence_interval`. If it has not been called, + # it will be called with the default CL of .95. + if self._ci is None: + self.confidence_interval(confidence_level=.95) + s = ( + "Dunnett's test" + f" ({self._ci_cl*100:.1f}% Confidence Interval)\n" + "Comparison Statistic p-value Lower CI Upper CI\n" + ) + for i in range(self.pvalue.size): + s += (f" (Sample {i} - Control) {self.statistic[i]:>10.3f}" + f"{self.pvalue[i]:>10.3f}" + f"{self._ci.low[i]:>10.3f}" + f"{self._ci.high[i]:>10.3f}\n") + + return s + + def _allowance( + self, confidence_level: DecimalNumber = 0.95, tol: DecimalNumber = 1e-3 + ) -> float: + """Allowance. + + It is the quantity to add/subtract from the observed difference + between the means of observed groups and the mean of the control + group. The result gives confidence limits. + + Parameters + ---------- + confidence_level : float, optional + Confidence level for the computed confidence interval. + Default is .95. + tol : float, optional + A tolerance for numerical optimization: the allowance will produce + a confidence within ``10*tol*(1 - confidence_level)`` of the + specified level, or a warning will be emitted. Tight tolerances + may be impractical due to noisy evaluation of the objective. + Default is 1e-3. + + Returns + ------- + allowance : float + Allowance around the mean. + """ + alpha = 1 - confidence_level + + def pvalue_from_stat(statistic): + statistic = np.array(statistic) + sf = _pvalue_dunnett( + rho=self._rho, df=self._df, + statistic=statistic, alternative=self._alternative, + rng=self._rng + ) + return abs(sf - alpha)/alpha + + # Evaluation of `pvalue_from_stat` is noisy due to the use of RQMC to + # evaluate `multivariate_t.cdf`. `minimize_scalar` is not designed + # to tolerate a noisy objective function and may fail to find the + # minimum accurately. We mitigate this possibility with the validation + # step below, but implementation of a noise-tolerant root finder or + # minimizer would be a welcome enhancement. See gh-18150. + res = minimize_scalar(pvalue_from_stat, method='brent', tol=tol) + critical_value = res.x + + # validation + # tol*10 because tol=1e-3 means we tolerate a 1% change at most + if res.success is False or res.fun >= tol*10: + warnings.warn( + "Computation of the confidence interval did not converge to " + "the desired level. The confidence level corresponding with " + f"the returned interval is approximately {alpha*(1+res.fun)}.", + stacklevel=3 + ) + + # From [1] p. 1101 between (1) and (3) + allowance = critical_value*self._std*np.sqrt( + 1/self._n_samples + 1/self._n_control + ) + return abs(allowance) + + def confidence_interval( + self, confidence_level: DecimalNumber = 0.95 + ) -> ConfidenceInterval: + """Compute the confidence interval for the specified confidence level. + + Parameters + ---------- + confidence_level : float, optional + Confidence level for the computed confidence interval. + Default is .95. + + Returns + ------- + ci : ``ConfidenceInterval`` object + The object has attributes ``low`` and ``high`` that hold the + lower and upper bounds of the confidence intervals for each + comparison. The high and low values are accessible for each + comparison at index ``i`` for each group ``i``. + + """ + # check to see if the supplied confidence level matches that of the + # previously computed CI. + if (self._ci is not None) and (confidence_level == self._ci_cl): + return self._ci + + if not (0 < confidence_level < 1): + raise ValueError("Confidence level must be between 0 and 1.") + + allowance = self._allowance(confidence_level=confidence_level) + diff_means = self._mean_samples - self._mean_control + + low = diff_means-allowance + high = diff_means+allowance + + if self._alternative == 'greater': + high = [np.inf] * len(diff_means) + elif self._alternative == 'less': + low = [-np.inf] * len(diff_means) + + self._ci_cl = confidence_level + self._ci = ConfidenceInterval( + low=low, + high=high + ) + return self._ci + + +@_transition_to_rng('random_state', replace_doc=False) +def dunnett( + *samples: "npt.ArrayLike", # noqa: D417 + control: "npt.ArrayLike", + alternative: Literal['two-sided', 'less', 'greater'] = "two-sided", + rng: SeedType = None +) -> DunnettResult: + """Dunnett's test: multiple comparisons of means against a control group. + + This is an implementation of Dunnett's original, single-step test as + described in [1]_. + + Parameters + ---------- + sample1, sample2, ... : 1D array_like + The sample measurements for each experimental group. + control : 1D array_like + The sample measurements for the control group. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + + The null hypothesis is that the means of the distributions underlying + the samples and control are equal. The following alternative + hypotheses are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions underlying the samples + and control are unequal. + * 'less': the means of the distributions underlying the samples + are less than the mean of the distribution underlying the control. + * 'greater': the means of the distributions underlying the + samples are greater than the mean of the distribution underlying + the control. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `random_state` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `random_state` keyword will emit warnings. Following a + deprecation period, the `random_state` keyword will be removed. + + Returns + ------- + res : `~scipy.stats._result_classes.DunnettResult` + An object containing attributes: + + statistic : float ndarray + The computed statistic of the test for each comparison. The element + at index ``i`` is the statistic for the comparison between + groups ``i`` and the control. + pvalue : float ndarray + The computed p-value of the test for each comparison. The element + at index ``i`` is the p-value for the comparison between + group ``i`` and the control. + + And the following method: + + confidence_interval(confidence_level=0.95) : + Compute the difference in means of the groups + with the control +- the allowance. + + See Also + -------- + tukey_hsd : performs pairwise comparison of means. + :ref:`hypothesis_dunnett` : Extended example + + Notes + ----- + Like the independent-sample t-test, Dunnett's test [1]_ is used to make + inferences about the means of distributions from which samples were drawn. + However, when multiple t-tests are performed at a fixed significance level, + the "family-wise error rate" - the probability of incorrectly rejecting the + null hypothesis in at least one test - will exceed the significance level. + Dunnett's test is designed to perform multiple comparisons while + controlling the family-wise error rate. + + Dunnett's test compares the means of multiple experimental groups + against a single control group. Tukey's Honestly Significant Difference Test + is another multiple-comparison test that controls the family-wise error + rate, but `tukey_hsd` performs *all* pairwise comparisons between groups. + When pairwise comparisons between experimental groups are not needed, + Dunnett's test is preferable due to its higher power. + + The use of this test relies on several assumptions. + + 1. The observations are independent within and among groups. + 2. The observations within each group are normally distributed. + 3. The distributions from which the samples are drawn have the same finite + variance. + + References + ---------- + .. [1] Dunnett, Charles W. (1955) "A Multiple Comparison Procedure for + Comparing Several Treatments with a Control." Journal of the American + Statistical Association, 50:272, 1096-1121, + :doi:`10.1080/01621459.1955.10501294` + .. [2] Thomson, M. L., & Short, M. D. (1969). Mucociliary function in + health, chronic obstructive airway disease, and asbestosis. Journal + of applied physiology, 26(5), 535-539. + :doi:`10.1152/jappl.1969.26.5.535` + + Examples + -------- + We'll use data from [2]_, Table 1. The null hypothesis is that the means of + the distributions underlying the samples and control are equal. + + First, we test that the means of the distributions underlying the samples + and control are unequal (``alternative='two-sided'``, the default). + + >>> import numpy as np + >>> from scipy.stats import dunnett + >>> samples = [[3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]] + >>> control = [2.9, 3.0, 2.5, 2.6, 3.2] + >>> res = dunnett(*samples, control=control) + >>> res.statistic + array([ 0.90874545, -0.05007117]) + >>> res.pvalue + array([0.58325114, 0.99819341]) + + Now, we test that the means of the distributions underlying the samples are + greater than the mean of the distribution underlying the control. + + >>> res = dunnett(*samples, control=control, alternative='greater') + >>> res.statistic + array([ 0.90874545, -0.05007117]) + >>> res.pvalue + array([0.30230596, 0.69115597]) + + For a more detailed example, see :ref:`hypothesis_dunnett`. + """ + samples_, control_, rng = _iv_dunnett( + samples=samples, control=control, + alternative=alternative, rng=rng + ) + + rho, df, n_group, n_samples, n_control = _params_dunnett( + samples=samples_, control=control_ + ) + + statistic, std, mean_control, mean_samples = _statistic_dunnett( + samples_, control_, df, n_samples, n_control + ) + + pvalue = _pvalue_dunnett( + rho=rho, df=df, statistic=statistic, alternative=alternative, rng=rng + ) + + return DunnettResult( + statistic=statistic, pvalue=pvalue, + _alternative=alternative, + _rho=rho, _df=df, _std=std, + _mean_samples=mean_samples, + _mean_control=mean_control, + _n_samples=n_samples, + _n_control=n_control, + _rng=rng + ) + + +def _iv_dunnett( + samples: Sequence["npt.ArrayLike"], + control: "npt.ArrayLike", + alternative: Literal['two-sided', 'less', 'greater'], + rng: SeedType +) -> tuple[list[np.ndarray], np.ndarray, SeedType]: + """Input validation for Dunnett's test.""" + rng = check_random_state(rng) + + if alternative not in {'two-sided', 'less', 'greater'}: + raise ValueError( + "alternative must be 'less', 'greater' or 'two-sided'" + ) + + ndim_msg = "Control and samples groups must be 1D arrays" + n_obs_msg = "Control and samples groups must have at least 1 observation" + + control = np.asarray(control) + samples_ = [np.asarray(sample) for sample in samples] + + # samples checks + samples_control: list[np.ndarray] = samples_ + [control] + for sample in samples_control: + if sample.ndim > 1: + raise ValueError(ndim_msg) + + if sample.size < 1: + raise ValueError(n_obs_msg) + + return samples_, control, rng + + +def _params_dunnett( + samples: list[np.ndarray], control: np.ndarray +) -> tuple[np.ndarray, int, int, np.ndarray, int]: + """Specific parameters for Dunnett's test. + + Degree of freedom is the number of observations minus the number of groups + including the control. + """ + n_samples = np.array([sample.size for sample in samples]) + + # From [1] p. 1100 d.f. = (sum N)-(p+1) + n_sample = n_samples.sum() + n_control = control.size + n = n_sample + n_control + n_groups = len(samples) + df = n - n_groups - 1 + + # From [1] p. 1103 rho_ij = 1/sqrt((N0/Ni+1)(N0/Nj+1)) + rho = n_control/n_samples + 1 + rho = 1/np.sqrt(rho[:, None] * rho[None, :]) + np.fill_diagonal(rho, 1) + + return rho, df, n_groups, n_samples, n_control + + +def _statistic_dunnett( + samples: list[np.ndarray], control: np.ndarray, df: int, + n_samples: np.ndarray, n_control: int +) -> tuple[np.ndarray, float, np.ndarray, np.ndarray]: + """Statistic of Dunnett's test. + + Computation based on the original single-step test from [1]. + """ + mean_control = np.mean(control) + mean_samples = np.array([np.mean(sample) for sample in samples]) + all_samples = [control] + samples + all_means = np.concatenate([[mean_control], mean_samples]) + + # Variance estimate s^2 from [1] Eq. 1 + s2 = np.sum([_var(sample, mean=mean)*sample.size + for sample, mean in zip(all_samples, all_means)]) / df + std = np.sqrt(s2) + + # z score inferred from [1] unlabeled equation after Eq. 1 + z = (mean_samples - mean_control) / np.sqrt(1/n_samples + 1/n_control) + + return z / std, std, mean_control, mean_samples + + +def _pvalue_dunnett( + rho: np.ndarray, df: int, statistic: np.ndarray, + alternative: Literal['two-sided', 'less', 'greater'], + rng: SeedType = None +) -> np.ndarray: + """pvalue from the multivariate t-distribution. + + Critical values come from the multivariate student-t distribution. + """ + statistic = statistic.reshape(-1, 1) + + mvt = stats.multivariate_t(shape=rho, df=df, seed=rng) + if alternative == "two-sided": + statistic = abs(statistic) + pvalue = 1 - mvt.cdf(statistic, lower_limit=-statistic) + elif alternative == "greater": + pvalue = 1 - mvt.cdf(statistic, lower_limit=-np.inf) + else: + pvalue = 1 - mvt.cdf(np.inf, lower_limit=statistic) + + return np.atleast_1d(pvalue) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_multivariate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_multivariate.py new file mode 100644 index 0000000000000000000000000000000000000000..be303fe087bd45eb63ee0c9c1b4244fafc1adcdc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_multivariate.py @@ -0,0 +1,7305 @@ +# +# Author: Joris Vankerschaver 2013 +# +import math +import threading +import numpy as np +import scipy.linalg +from scipy._lib import doccer +from scipy.special import (gammaln, psi, multigammaln, xlogy, entr, betaln, + ive, loggamma) +from scipy import special +from scipy._lib._util import check_random_state, _lazywhere +from scipy.linalg.blas import drot, get_blas_funcs +from ._continuous_distns import norm, invgamma +from ._discrete_distns import binom +from . import _mvn, _covariance, _rcont +from ._qmvnt import _qmvt +from ._morestats import directional_stats +from scipy.optimize import root_scalar + +__all__ = ['multivariate_normal', + 'matrix_normal', + 'dirichlet', + 'dirichlet_multinomial', + 'wishart', + 'invwishart', + 'multinomial', + 'special_ortho_group', + 'ortho_group', + 'random_correlation', + 'unitary_group', + 'multivariate_t', + 'multivariate_hypergeom', + 'random_table', + 'uniform_direction', + 'vonmises_fisher', + 'normal_inverse_gamma'] + +_LOG_2PI = np.log(2 * np.pi) +_LOG_2 = np.log(2) +_LOG_PI = np.log(np.pi) +MVN_LOCK = threading.Lock() + + +_doc_random_state = """\ +seed : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. +""" + + +def _squeeze_output(out): + """ + Remove single-dimensional entries from array and convert to scalar, + if necessary. + """ + out = out.squeeze() + if out.ndim == 0: + out = out[()] + return out + + +def _eigvalsh_to_eps(spectrum, cond=None, rcond=None): + """Determine which eigenvalues are "small" given the spectrum. + + This is for compatibility across various linear algebra functions + that should agree about whether or not a Hermitian matrix is numerically + singular and what is its numerical matrix rank. + This is designed to be compatible with scipy.linalg.pinvh. + + Parameters + ---------- + spectrum : 1d ndarray + Array of eigenvalues of a Hermitian matrix. + cond, rcond : float, optional + Cutoff for small eigenvalues. + Singular values smaller than rcond * largest_eigenvalue are + considered zero. + If None or -1, suitable machine precision is used. + + Returns + ------- + eps : float + Magnitude cutoff for numerical negligibility. + + """ + if rcond is not None: + cond = rcond + if cond in [None, -1]: + t = spectrum.dtype.char.lower() + factor = {'f': 1E3, 'd': 1E6} + cond = factor[t] * np.finfo(t).eps + eps = cond * np.max(abs(spectrum)) + return eps + + +def _pinv_1d(v, eps=1e-5): + """A helper function for computing the pseudoinverse. + + Parameters + ---------- + v : iterable of numbers + This may be thought of as a vector of eigenvalues or singular values. + eps : float + Values with magnitude no greater than eps are considered negligible. + + Returns + ------- + v_pinv : 1d float ndarray + A vector of pseudo-inverted numbers. + + """ + return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float) + + +class _PSD: + """ + Compute coordinated functions of a symmetric positive semidefinite matrix. + + This class addresses two issues. Firstly it allows the pseudoinverse, + the logarithm of the pseudo-determinant, and the rank of the matrix + to be computed using one call to eigh instead of three. + Secondly it allows these functions to be computed in a way + that gives mutually compatible results. + All of the functions are computed with a common understanding as to + which of the eigenvalues are to be considered negligibly small. + The functions are designed to coordinate with scipy.linalg.pinvh() + but not necessarily with np.linalg.det() or with np.linalg.matrix_rank(). + + Parameters + ---------- + M : array_like + Symmetric positive semidefinite matrix (2-D). + cond, rcond : float, optional + Cutoff for small eigenvalues. + Singular values smaller than rcond * largest_eigenvalue are + considered zero. + If None or -1, suitable machine precision is used. + lower : bool, optional + Whether the pertinent array data is taken from the lower + or upper triangle of M. (Default: lower) + check_finite : bool, optional + Whether to check that the input matrices contain only finite + numbers. Disabling may give a performance gain, but may result + in problems (crashes, non-termination) if the inputs do contain + infinities or NaNs. + allow_singular : bool, optional + Whether to allow a singular matrix. (Default: True) + + Notes + ----- + The arguments are similar to those of scipy.linalg.pinvh(). + + """ + + def __init__(self, M, cond=None, rcond=None, lower=True, + check_finite=True, allow_singular=True): + self._M = np.asarray(M) + + # Compute the symmetric eigendecomposition. + # Note that eigh takes care of array conversion, chkfinite, + # and assertion that the matrix is square. + s, u = scipy.linalg.eigh(M, lower=lower, check_finite=check_finite) + + eps = _eigvalsh_to_eps(s, cond, rcond) + if np.min(s) < -eps: + msg = "The input matrix must be symmetric positive semidefinite." + raise ValueError(msg) + d = s[s > eps] + if len(d) < len(s) and not allow_singular: + msg = ("When `allow_singular is False`, the input matrix must be " + "symmetric positive definite.") + raise np.linalg.LinAlgError(msg) + s_pinv = _pinv_1d(s, eps) + U = np.multiply(u, np.sqrt(s_pinv)) + + # Save the eigenvector basis, and tolerance for testing support + self.eps = 1e3*eps + self.V = u[:, s <= eps] + + # Initialize the eagerly precomputed attributes. + self.rank = len(d) + self.U = U + self.log_pdet = np.sum(np.log(d)) + + # Initialize attributes to be lazily computed. + self._pinv = None + + def _support_mask(self, x): + """ + Check whether x lies in the support of the distribution. + """ + residual = np.linalg.norm(x @ self.V, axis=-1) + in_support = residual < self.eps + return in_support + + @property + def pinv(self): + if self._pinv is None: + self._pinv = np.dot(self.U, self.U.T) + return self._pinv + + +class multi_rv_generic: + """ + Class which encapsulates common functionality between all multivariate + distributions. + """ + def __init__(self, seed=None): + super().__init__() + self._random_state = check_random_state(seed) + + @property + def random_state(self): + """ Get or set the Generator object for generating random variates. + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + """ + return self._random_state + + @random_state.setter + def random_state(self, seed): + self._random_state = check_random_state(seed) + + def _get_random_state(self, random_state): + if random_state is not None: + return check_random_state(random_state) + else: + return self._random_state + + +class multi_rv_frozen: + """ + Class which encapsulates common functionality between all frozen + multivariate distributions. + """ + @property + def random_state(self): + return self._dist._random_state + + @random_state.setter + def random_state(self, seed): + self._dist._random_state = check_random_state(seed) + + +_mvn_doc_default_callparams = """\ +mean : array_like, default: ``[0]`` + Mean of the distribution. +cov : array_like or `Covariance`, default: ``[1]`` + Symmetric positive (semi)definite covariance matrix of the distribution. +allow_singular : bool, default: ``False`` + Whether to allow a singular covariance matrix. This is ignored if `cov` is + a `Covariance` object. +""" + +_mvn_doc_callparams_note = """\ +Setting the parameter `mean` to `None` is equivalent to having `mean` +be the zero-vector. The parameter `cov` can be a scalar, in which case +the covariance matrix is the identity times that value, a vector of +diagonal entries for the covariance matrix, a two-dimensional array_like, +or a `Covariance` object. +""" + +_mvn_doc_frozen_callparams = "" + +_mvn_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +mvn_docdict_params = { + '_mvn_doc_default_callparams': _mvn_doc_default_callparams, + '_mvn_doc_callparams_note': _mvn_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +mvn_docdict_noparams = { + '_mvn_doc_default_callparams': _mvn_doc_frozen_callparams, + '_mvn_doc_callparams_note': _mvn_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class multivariate_normal_gen(multi_rv_generic): + r"""A multivariate normal random variable. + + The `mean` keyword specifies the mean. The `cov` keyword specifies the + covariance matrix. + + Methods + ------- + pdf(x, mean=None, cov=1, allow_singular=False) + Probability density function. + logpdf(x, mean=None, cov=1, allow_singular=False) + Log of the probability density function. + cdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5, lower_limit=None) + Cumulative distribution function. + logcdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5) + Log of the cumulative distribution function. + rvs(mean=None, cov=1, size=1, random_state=None) + Draw random samples from a multivariate normal distribution. + entropy(mean=None, cov=1) + Compute the differential entropy of the multivariate normal. + fit(x, fix_mean=None, fix_cov=None) + Fit a multivariate normal distribution to data. + + Parameters + ---------- + %(_mvn_doc_default_callparams)s + %(_doc_random_state)s + + Notes + ----- + %(_mvn_doc_callparams_note)s + + The covariance matrix `cov` may be an instance of a subclass of + `Covariance`, e.g. `scipy.stats.CovViaPrecision`. If so, `allow_singular` + is ignored. + + Otherwise, `cov` must be a symmetric positive semidefinite + matrix when `allow_singular` is True; it must be (strictly) positive + definite when `allow_singular` is False. + Symmetry is not checked; only the lower triangular portion is used. + The determinant and inverse of `cov` are computed + as the pseudo-determinant and pseudo-inverse, respectively, so + that `cov` does not need to have full rank. + + The probability density function for `multivariate_normal` is + + .. math:: + + f(x) = \frac{1}{\sqrt{(2 \pi)^k \det \Sigma}} + \exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right), + + where :math:`\mu` is the mean, :math:`\Sigma` the covariance matrix, + :math:`k` the rank of :math:`\Sigma`. In case of singular :math:`\Sigma`, + SciPy extends this definition according to [1]_. + + .. versionadded:: 0.14.0 + + References + ---------- + .. [1] Multivariate Normal Distribution - Degenerate Case, Wikipedia, + https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Degenerate_case + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import multivariate_normal + + >>> x = np.linspace(0, 5, 10, endpoint=False) + >>> y = multivariate_normal.pdf(x, mean=2.5, cov=0.5); y + array([ 0.00108914, 0.01033349, 0.05946514, 0.20755375, 0.43939129, + 0.56418958, 0.43939129, 0.20755375, 0.05946514, 0.01033349]) + >>> fig1 = plt.figure() + >>> ax = fig1.add_subplot(111) + >>> ax.plot(x, y) + >>> plt.show() + + Alternatively, the object may be called (as a function) to fix the mean + and covariance parameters, returning a "frozen" multivariate normal + random variable: + + >>> rv = multivariate_normal(mean=None, cov=1, allow_singular=False) + >>> # Frozen object with the same methods but holding the given + >>> # mean and covariance fixed. + + The input quantiles can be any shape of array, as long as the last + axis labels the components. This allows us for instance to + display the frozen pdf for a non-isotropic random variable in 2D as + follows: + + >>> x, y = np.mgrid[-1:1:.01, -1:1:.01] + >>> pos = np.dstack((x, y)) + >>> rv = multivariate_normal([0.5, -0.2], [[2.0, 0.3], [0.3, 0.5]]) + >>> fig2 = plt.figure() + >>> ax2 = fig2.add_subplot(111) + >>> ax2.contourf(x, y, rv.pdf(pos)) + + """ # noqa: E501 + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, mvn_docdict_params) + + def __call__(self, mean=None, cov=1, allow_singular=False, seed=None): + """Create a frozen multivariate normal distribution. + + See `multivariate_normal_frozen` for more information. + """ + return multivariate_normal_frozen(mean, cov, + allow_singular=allow_singular, + seed=seed) + + def _process_parameters(self, mean, cov, allow_singular=True): + """ + Infer dimensionality from mean or covariance matrix, ensure that + mean and covariance are full vector resp. matrix. + """ + if isinstance(cov, _covariance.Covariance): + return self._process_parameters_Covariance(mean, cov) + else: + # Before `Covariance` classes were introduced, + # `multivariate_normal` accepted plain arrays as `cov` and used the + # following input validation. To avoid disturbing the behavior of + # `multivariate_normal` when plain arrays are used, we use the + # original input validation here. + dim, mean, cov = self._process_parameters_psd(None, mean, cov) + # After input validation, some methods then processed the arrays + # with a `_PSD` object and used that to perform computation. + # To avoid branching statements in each method depending on whether + # `cov` is an array or `Covariance` object, we always process the + # array with `_PSD`, and then use wrapper that satisfies the + # `Covariance` interface, `CovViaPSD`. + psd = _PSD(cov, allow_singular=allow_singular) + cov_object = _covariance.CovViaPSD(psd) + return dim, mean, cov_object + + def _process_parameters_Covariance(self, mean, cov): + dim = cov.shape[-1] + mean = np.array([0.]) if mean is None else mean + message = (f"`cov` represents a covariance matrix in {dim} dimensions," + f"and so `mean` must be broadcastable to shape {(dim,)}") + try: + mean = np.broadcast_to(mean, dim) + except ValueError as e: + raise ValueError(message) from e + return dim, mean, cov + + def _process_parameters_psd(self, dim, mean, cov): + # Try to infer dimensionality + if dim is None: + if mean is None: + if cov is None: + dim = 1 + else: + cov = np.asarray(cov, dtype=float) + if cov.ndim < 2: + dim = 1 + else: + dim = cov.shape[0] + else: + mean = np.asarray(mean, dtype=float) + dim = mean.size + else: + if not np.isscalar(dim): + raise ValueError("Dimension of random variable must be " + "a scalar.") + + # Check input sizes and return full arrays for mean and cov if + # necessary + if mean is None: + mean = np.zeros(dim) + mean = np.asarray(mean, dtype=float) + + if cov is None: + cov = 1.0 + cov = np.asarray(cov, dtype=float) + + if dim == 1: + mean = mean.reshape(1) + cov = cov.reshape(1, 1) + + if mean.ndim != 1 or mean.shape[0] != dim: + raise ValueError("Array 'mean' must be a vector of length %d." % + dim) + if cov.ndim == 0: + cov = cov * np.eye(dim) + elif cov.ndim == 1: + cov = np.diag(cov) + elif cov.ndim == 2 and cov.shape != (dim, dim): + rows, cols = cov.shape + if rows != cols: + msg = ("Array 'cov' must be square if it is two dimensional," + f" but cov.shape = {str(cov.shape)}.") + else: + msg = ("Dimension mismatch: array 'cov' is of shape %s," + " but 'mean' is a vector of length %d.") + msg = msg % (str(cov.shape), len(mean)) + raise ValueError(msg) + elif cov.ndim > 2: + raise ValueError("Array 'cov' must be at most two-dimensional," + " but cov.ndim = %d" % cov.ndim) + + return dim, mean, cov + + def _process_quantiles(self, x, dim): + """ + Adjust quantiles array so that last axis labels the components of + each data point. + """ + x = np.asarray(x, dtype=float) + + if x.ndim == 0: + x = x[np.newaxis] + elif x.ndim == 1: + if dim == 1: + x = x[:, np.newaxis] + else: + x = x[np.newaxis, :] + + return x + + def _logpdf(self, x, mean, cov_object): + """Log of the multivariate normal probability density function. + + Parameters + ---------- + x : ndarray + Points at which to evaluate the log of the probability + density function + mean : ndarray + Mean of the distribution + cov_object : Covariance + An object representing the Covariance matrix + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'logpdf' instead. + + """ + log_det_cov, rank = cov_object.log_pdet, cov_object.rank + dev = x - mean + if dev.ndim > 1: + log_det_cov = log_det_cov[..., np.newaxis] + rank = rank[..., np.newaxis] + maha = np.sum(np.square(cov_object.whiten(dev)), axis=-1) + return -0.5 * (rank * _LOG_2PI + log_det_cov + maha) + + def logpdf(self, x, mean=None, cov=1, allow_singular=False): + """Log of the multivariate normal probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + + Returns + ------- + pdf : ndarray or scalar + Log of the probability density function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + params = self._process_parameters(mean, cov, allow_singular) + dim, mean, cov_object = params + x = self._process_quantiles(x, dim) + out = self._logpdf(x, mean, cov_object) + if np.any(cov_object.rank < dim): + out_of_bounds = ~cov_object._support_mask(x-mean) + out[out_of_bounds] = -np.inf + return _squeeze_output(out) + + def pdf(self, x, mean=None, cov=1, allow_singular=False): + """Multivariate normal probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + + Returns + ------- + pdf : ndarray or scalar + Probability density function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + params = self._process_parameters(mean, cov, allow_singular) + dim, mean, cov_object = params + x = self._process_quantiles(x, dim) + out = np.exp(self._logpdf(x, mean, cov_object)) + if np.any(cov_object.rank < dim): + out_of_bounds = ~cov_object._support_mask(x-mean) + out[out_of_bounds] = 0.0 + return _squeeze_output(out) + + def _cdf(self, x, mean, cov, maxpts, abseps, releps, lower_limit): + """Multivariate normal cumulative distribution function. + + Parameters + ---------- + x : ndarray + Points at which to evaluate the cumulative distribution function. + mean : ndarray + Mean of the distribution + cov : array_like + Covariance matrix of the distribution + maxpts : integer + The maximum number of points to use for integration + abseps : float + Absolute error tolerance + releps : float + Relative error tolerance + lower_limit : array_like, optional + Lower limit of integration of the cumulative distribution function. + Default is negative infinity. Must be broadcastable with `x`. + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'cdf' instead. + + + .. versionadded:: 1.0.0 + + """ + lower = (np.full(mean.shape, -np.inf) + if lower_limit is None else lower_limit) + # In 2d, _mvn.mvnun accepts input in which `lower` bound elements + # are greater than `x`. Not so in other dimensions. Fix this by + # ensuring that lower bounds are indeed lower when passed, then + # set signs of resulting CDF manually. + b, a = np.broadcast_arrays(x, lower) + i_swap = b < a + signs = (-1)**(i_swap.sum(axis=-1)) # odd # of swaps -> negative + a, b = a.copy(), b.copy() + a[i_swap], b[i_swap] = b[i_swap], a[i_swap] + n = x.shape[-1] + limits = np.concatenate((a, b), axis=-1) + + # mvnun expects 1-d arguments, so process points sequentially + def func1d(limits): + with MVN_LOCK: + return _mvn.mvnun(limits[:n], limits[n:], mean, cov, + maxpts, abseps, releps)[0] + + out = np.apply_along_axis(func1d, -1, limits) * signs + return _squeeze_output(out) + + def logcdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None, + abseps=1e-5, releps=1e-5, *, lower_limit=None): + """Log of the multivariate normal cumulative distribution function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + maxpts : integer, optional + The maximum number of points to use for integration + (default ``1000000*dim``) + abseps : float, optional + Absolute error tolerance (default 1e-5) + releps : float, optional + Relative error tolerance (default 1e-5) + lower_limit : array_like, optional + Lower limit of integration of the cumulative distribution function. + Default is negative infinity. Must be broadcastable with `x`. + + Returns + ------- + cdf : ndarray or scalar + Log of the cumulative distribution function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + .. versionadded:: 1.0.0 + + """ + params = self._process_parameters(mean, cov, allow_singular) + dim, mean, cov_object = params + cov = cov_object.covariance + x = self._process_quantiles(x, dim) + if not maxpts: + maxpts = 1000000 * dim + cdf = self._cdf(x, mean, cov, maxpts, abseps, releps, lower_limit) + # the log of a negative real is complex, and cdf can be negative + # if lower limit is greater than upper limit + cdf = cdf + 0j if np.any(cdf < 0) else cdf + out = np.log(cdf) + return out + + def cdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None, + abseps=1e-5, releps=1e-5, *, lower_limit=None): + """Multivariate normal cumulative distribution function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + maxpts : integer, optional + The maximum number of points to use for integration + (default ``1000000*dim``) + abseps : float, optional + Absolute error tolerance (default 1e-5) + releps : float, optional + Relative error tolerance (default 1e-5) + lower_limit : array_like, optional + Lower limit of integration of the cumulative distribution function. + Default is negative infinity. Must be broadcastable with `x`. + + Returns + ------- + cdf : ndarray or scalar + Cumulative distribution function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + .. versionadded:: 1.0.0 + + """ + params = self._process_parameters(mean, cov, allow_singular) + dim, mean, cov_object = params + cov = cov_object.covariance + x = self._process_quantiles(x, dim) + if not maxpts: + maxpts = 1000000 * dim + out = self._cdf(x, mean, cov, maxpts, abseps, releps, lower_limit) + return out + + def rvs(self, mean=None, cov=1, size=1, random_state=None): + """Draw random samples from a multivariate normal distribution. + + Parameters + ---------- + %(_mvn_doc_default_callparams)s + size : integer, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray or scalar + Random variates of size (`size`, `N`), where `N` is the + dimension of the random variable. + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + dim, mean, cov_object = self._process_parameters(mean, cov) + random_state = self._get_random_state(random_state) + + if isinstance(cov_object, _covariance.CovViaPSD): + cov = cov_object.covariance + out = random_state.multivariate_normal(mean, cov, size) + out = _squeeze_output(out) + else: + size = size or tuple() + if not np.iterable(size): + size = (size,) + shape = tuple(size) + (cov_object.shape[-1],) + x = random_state.normal(size=shape) + out = mean + cov_object.colorize(x) + return out + + def entropy(self, mean=None, cov=1): + """Compute the differential entropy of the multivariate normal. + + Parameters + ---------- + %(_mvn_doc_default_callparams)s + + Returns + ------- + h : scalar + Entropy of the multivariate normal distribution + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + dim, mean, cov_object = self._process_parameters(mean, cov) + return 0.5 * (cov_object.rank * (_LOG_2PI + 1) + cov_object.log_pdet) + + def fit(self, x, fix_mean=None, fix_cov=None): + """Fit a multivariate normal distribution to data. + + Parameters + ---------- + x : ndarray (m, n) + Data the distribution is fitted to. Must have two axes. + The first axis of length `m` represents the number of vectors + the distribution is fitted to. The second axis of length `n` + determines the dimensionality of the fitted distribution. + fix_mean : ndarray(n, ) + Fixed mean vector. Must have length `n`. + fix_cov: ndarray (n, n) + Fixed covariance matrix. Must have shape ``(n, n)``. + + Returns + ------- + mean : ndarray (n, ) + Maximum likelihood estimate of the mean vector + cov : ndarray (n, n) + Maximum likelihood estimate of the covariance matrix + + """ + # input validation for data to be fitted + x = np.asarray(x) + if x.ndim != 2: + raise ValueError("`x` must be two-dimensional.") + + n_vectors, dim = x.shape + + # parameter estimation + # reference: https://home.ttic.edu/~shubhendu/Slides/Estimation.pdf + if fix_mean is not None: + # input validation for `fix_mean` + fix_mean = np.atleast_1d(fix_mean) + if fix_mean.shape != (dim, ): + msg = ("`fix_mean` must be a one-dimensional array the same " + "length as the dimensionality of the vectors `x`.") + raise ValueError(msg) + mean = fix_mean + else: + mean = x.mean(axis=0) + + if fix_cov is not None: + # input validation for `fix_cov` + fix_cov = np.atleast_2d(fix_cov) + # validate shape + if fix_cov.shape != (dim, dim): + msg = ("`fix_cov` must be a two-dimensional square array " + "of same side length as the dimensionality of the " + "vectors `x`.") + raise ValueError(msg) + # validate positive semidefiniteness + # a trimmed down copy from _PSD + s, u = scipy.linalg.eigh(fix_cov, lower=True, check_finite=True) + eps = _eigvalsh_to_eps(s) + if np.min(s) < -eps: + msg = "`fix_cov` must be symmetric positive semidefinite." + raise ValueError(msg) + cov = fix_cov + else: + centered_data = x - mean + cov = centered_data.T @ centered_data / n_vectors + return mean, cov + + +multivariate_normal = multivariate_normal_gen() + + +class multivariate_normal_frozen(multi_rv_frozen): + def __init__(self, mean=None, cov=1, allow_singular=False, seed=None, + maxpts=None, abseps=1e-5, releps=1e-5): + """Create a frozen multivariate normal distribution. + + Parameters + ---------- + mean : array_like, default: ``[0]`` + Mean of the distribution. + cov : array_like, default: ``[1]`` + Symmetric positive (semi)definite covariance matrix of the + distribution. + allow_singular : bool, default: ``False`` + Whether to allow a singular covariance matrix. + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + maxpts : integer, optional + The maximum number of points to use for integration of the + cumulative distribution function (default ``1000000*dim``) + abseps : float, optional + Absolute error tolerance for the cumulative distribution function + (default 1e-5) + releps : float, optional + Relative error tolerance for the cumulative distribution function + (default 1e-5) + + Examples + -------- + When called with the default parameters, this will create a 1D random + variable with mean 0 and covariance 1: + + >>> from scipy.stats import multivariate_normal + >>> r = multivariate_normal() + >>> r.mean + array([ 0.]) + >>> r.cov + array([[1.]]) + + """ # numpy/numpydoc#87 # noqa: E501 + self._dist = multivariate_normal_gen(seed) + self.dim, self.mean, self.cov_object = ( + self._dist._process_parameters(mean, cov, allow_singular)) + self.allow_singular = allow_singular or self.cov_object._allow_singular + if not maxpts: + maxpts = 1000000 * self.dim + self.maxpts = maxpts + self.abseps = abseps + self.releps = releps + + @property + def cov(self): + return self.cov_object.covariance + + def logpdf(self, x): + x = self._dist._process_quantiles(x, self.dim) + out = self._dist._logpdf(x, self.mean, self.cov_object) + if np.any(self.cov_object.rank < self.dim): + out_of_bounds = ~self.cov_object._support_mask(x-self.mean) + out[out_of_bounds] = -np.inf + return _squeeze_output(out) + + def pdf(self, x): + return np.exp(self.logpdf(x)) + + def logcdf(self, x, *, lower_limit=None): + cdf = self.cdf(x, lower_limit=lower_limit) + # the log of a negative real is complex, and cdf can be negative + # if lower limit is greater than upper limit + cdf = cdf + 0j if np.any(cdf < 0) else cdf + out = np.log(cdf) + return out + + def cdf(self, x, *, lower_limit=None): + x = self._dist._process_quantiles(x, self.dim) + out = self._dist._cdf(x, self.mean, self.cov_object.covariance, + self.maxpts, self.abseps, self.releps, + lower_limit) + return _squeeze_output(out) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.mean, self.cov_object, size, random_state) + + def entropy(self): + """Computes the differential entropy of the multivariate normal. + + Returns + ------- + h : scalar + Entropy of the multivariate normal distribution + + """ + log_pdet = self.cov_object.log_pdet + rank = self.cov_object.rank + return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet) + + +# Set frozen generator docstrings from corresponding docstrings in +# multivariate_normal_gen and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'logcdf', 'cdf', 'rvs']: + method = multivariate_normal_gen.__dict__[name] + method_frozen = multivariate_normal_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat(method.__doc__, + mvn_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params) + +_matnorm_doc_default_callparams = """\ +mean : array_like, optional + Mean of the distribution (default: `None`) +rowcov : array_like, optional + Among-row covariance matrix of the distribution (default: ``1``) +colcov : array_like, optional + Among-column covariance matrix of the distribution (default: ``1``) +""" + +_matnorm_doc_callparams_note = """\ +If `mean` is set to `None` then a matrix of zeros is used for the mean. +The dimensions of this matrix are inferred from the shape of `rowcov` and +`colcov`, if these are provided, or set to ``1`` if ambiguous. + +`rowcov` and `colcov` can be two-dimensional array_likes specifying the +covariance matrices directly. Alternatively, a one-dimensional array will +be be interpreted as the entries of a diagonal matrix, and a scalar or +zero-dimensional array will be interpreted as this value times the +identity matrix. +""" + +_matnorm_doc_frozen_callparams = "" + +_matnorm_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +matnorm_docdict_params = { + '_matnorm_doc_default_callparams': _matnorm_doc_default_callparams, + '_matnorm_doc_callparams_note': _matnorm_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +matnorm_docdict_noparams = { + '_matnorm_doc_default_callparams': _matnorm_doc_frozen_callparams, + '_matnorm_doc_callparams_note': _matnorm_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class matrix_normal_gen(multi_rv_generic): + r"""A matrix normal random variable. + + The `mean` keyword specifies the mean. The `rowcov` keyword specifies the + among-row covariance matrix. The 'colcov' keyword specifies the + among-column covariance matrix. + + Methods + ------- + pdf(X, mean=None, rowcov=1, colcov=1) + Probability density function. + logpdf(X, mean=None, rowcov=1, colcov=1) + Log of the probability density function. + rvs(mean=None, rowcov=1, colcov=1, size=1, random_state=None) + Draw random samples. + entropy(rowcol=1, colcov=1) + Differential entropy. + + Parameters + ---------- + %(_matnorm_doc_default_callparams)s + %(_doc_random_state)s + + Notes + ----- + %(_matnorm_doc_callparams_note)s + + The covariance matrices specified by `rowcov` and `colcov` must be + (symmetric) positive definite. If the samples in `X` are + :math:`m \times n`, then `rowcov` must be :math:`m \times m` and + `colcov` must be :math:`n \times n`. `mean` must be the same shape as `X`. + + The probability density function for `matrix_normal` is + + .. math:: + + f(X) = (2 \pi)^{-\frac{mn}{2}}|U|^{-\frac{n}{2}} |V|^{-\frac{m}{2}} + \exp\left( -\frac{1}{2} \mathrm{Tr}\left[ U^{-1} (X-M) V^{-1} + (X-M)^T \right] \right), + + where :math:`M` is the mean, :math:`U` the among-row covariance matrix, + :math:`V` the among-column covariance matrix. + + The `allow_singular` behaviour of the `multivariate_normal` + distribution is not currently supported. Covariance matrices must be + full rank. + + The `matrix_normal` distribution is closely related to the + `multivariate_normal` distribution. Specifically, :math:`\mathrm{Vec}(X)` + (the vector formed by concatenating the columns of :math:`X`) has a + multivariate normal distribution with mean :math:`\mathrm{Vec}(M)` + and covariance :math:`V \otimes U` (where :math:`\otimes` is the Kronecker + product). Sampling and pdf evaluation are + :math:`\mathcal{O}(m^3 + n^3 + m^2 n + m n^2)` for the matrix normal, but + :math:`\mathcal{O}(m^3 n^3)` for the equivalent multivariate normal, + making this equivalent form algorithmically inefficient. + + .. versionadded:: 0.17.0 + + Examples + -------- + + >>> import numpy as np + >>> from scipy.stats import matrix_normal + + >>> M = np.arange(6).reshape(3,2); M + array([[0, 1], + [2, 3], + [4, 5]]) + >>> U = np.diag([1,2,3]); U + array([[1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + >>> V = 0.3*np.identity(2); V + array([[ 0.3, 0. ], + [ 0. , 0.3]]) + >>> X = M + 0.1; X + array([[ 0.1, 1.1], + [ 2.1, 3.1], + [ 4.1, 5.1]]) + >>> matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V) + 0.023410202050005054 + + >>> # Equivalent multivariate normal + >>> from scipy.stats import multivariate_normal + >>> vectorised_X = X.T.flatten() + >>> equiv_mean = M.T.flatten() + >>> equiv_cov = np.kron(V,U) + >>> multivariate_normal.pdf(vectorised_X, mean=equiv_mean, cov=equiv_cov) + 0.023410202050005054 + + Alternatively, the object may be called (as a function) to fix the mean + and covariance parameters, returning a "frozen" matrix normal + random variable: + + >>> rv = matrix_normal(mean=None, rowcov=1, colcov=1) + >>> # Frozen object with the same methods but holding the given + >>> # mean and covariance fixed. + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, matnorm_docdict_params) + + def __call__(self, mean=None, rowcov=1, colcov=1, seed=None): + """Create a frozen matrix normal distribution. + + See `matrix_normal_frozen` for more information. + + """ + return matrix_normal_frozen(mean, rowcov, colcov, seed=seed) + + def _process_parameters(self, mean, rowcov, colcov): + """ + Infer dimensionality from mean or covariance matrices. Handle + defaults. Ensure compatible dimensions. + """ + + # Process mean + if mean is not None: + mean = np.asarray(mean, dtype=float) + meanshape = mean.shape + if len(meanshape) != 2: + raise ValueError("Array `mean` must be two dimensional.") + if np.any(meanshape == 0): + raise ValueError("Array `mean` has invalid shape.") + + # Process among-row covariance + rowcov = np.asarray(rowcov, dtype=float) + if rowcov.ndim == 0: + if mean is not None: + rowcov = rowcov * np.identity(meanshape[0]) + else: + rowcov = rowcov * np.identity(1) + elif rowcov.ndim == 1: + rowcov = np.diag(rowcov) + rowshape = rowcov.shape + if len(rowshape) != 2: + raise ValueError("`rowcov` must be a scalar or a 2D array.") + if rowshape[0] != rowshape[1]: + raise ValueError("Array `rowcov` must be square.") + if rowshape[0] == 0: + raise ValueError("Array `rowcov` has invalid shape.") + numrows = rowshape[0] + + # Process among-column covariance + colcov = np.asarray(colcov, dtype=float) + if colcov.ndim == 0: + if mean is not None: + colcov = colcov * np.identity(meanshape[1]) + else: + colcov = colcov * np.identity(1) + elif colcov.ndim == 1: + colcov = np.diag(colcov) + colshape = colcov.shape + if len(colshape) != 2: + raise ValueError("`colcov` must be a scalar or a 2D array.") + if colshape[0] != colshape[1]: + raise ValueError("Array `colcov` must be square.") + if colshape[0] == 0: + raise ValueError("Array `colcov` has invalid shape.") + numcols = colshape[0] + + # Ensure mean and covariances compatible + if mean is not None: + if meanshape[0] != numrows: + raise ValueError("Arrays `mean` and `rowcov` must have the " + "same number of rows.") + if meanshape[1] != numcols: + raise ValueError("Arrays `mean` and `colcov` must have the " + "same number of columns.") + else: + mean = np.zeros((numrows, numcols)) + + dims = (numrows, numcols) + + return dims, mean, rowcov, colcov + + def _process_quantiles(self, X, dims): + """ + Adjust quantiles array so that last two axes labels the components of + each data point. + """ + X = np.asarray(X, dtype=float) + if X.ndim == 2: + X = X[np.newaxis, :] + if X.shape[-2:] != dims: + raise ValueError("The shape of array `X` is not compatible " + "with the distribution parameters.") + return X + + def _logpdf(self, dims, X, mean, row_prec_rt, log_det_rowcov, + col_prec_rt, log_det_colcov): + """Log of the matrix normal probability density function. + + Parameters + ---------- + dims : tuple + Dimensions of the matrix variates + X : ndarray + Points at which to evaluate the log of the probability + density function + mean : ndarray + Mean of the distribution + row_prec_rt : ndarray + A decomposition such that np.dot(row_prec_rt, row_prec_rt.T) + is the inverse of the among-row covariance matrix + log_det_rowcov : float + Logarithm of the determinant of the among-row covariance matrix + col_prec_rt : ndarray + A decomposition such that np.dot(col_prec_rt, col_prec_rt.T) + is the inverse of the among-column covariance matrix + log_det_colcov : float + Logarithm of the determinant of the among-column covariance matrix + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'logpdf' instead. + + """ + numrows, numcols = dims + roll_dev = np.moveaxis(X-mean, -1, 0) + scale_dev = np.tensordot(col_prec_rt.T, + np.dot(roll_dev, row_prec_rt), 1) + maha = np.sum(np.sum(np.square(scale_dev), axis=-1), axis=0) + return -0.5 * (numrows*numcols*_LOG_2PI + numcols*log_det_rowcov + + numrows*log_det_colcov + maha) + + def logpdf(self, X, mean=None, rowcov=1, colcov=1): + """Log of the matrix normal probability density function. + + Parameters + ---------- + X : array_like + Quantiles, with the last two axes of `X` denoting the components. + %(_matnorm_doc_default_callparams)s + + Returns + ------- + logpdf : ndarray + Log of the probability density function evaluated at `X` + + Notes + ----- + %(_matnorm_doc_callparams_note)s + + """ + dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov, + colcov) + X = self._process_quantiles(X, dims) + rowpsd = _PSD(rowcov, allow_singular=False) + colpsd = _PSD(colcov, allow_singular=False) + out = self._logpdf(dims, X, mean, rowpsd.U, rowpsd.log_pdet, colpsd.U, + colpsd.log_pdet) + return _squeeze_output(out) + + def pdf(self, X, mean=None, rowcov=1, colcov=1): + """Matrix normal probability density function. + + Parameters + ---------- + X : array_like + Quantiles, with the last two axes of `X` denoting the components. + %(_matnorm_doc_default_callparams)s + + Returns + ------- + pdf : ndarray + Probability density function evaluated at `X` + + Notes + ----- + %(_matnorm_doc_callparams_note)s + + """ + return np.exp(self.logpdf(X, mean, rowcov, colcov)) + + def rvs(self, mean=None, rowcov=1, colcov=1, size=1, random_state=None): + """Draw random samples from a matrix normal distribution. + + Parameters + ---------- + %(_matnorm_doc_default_callparams)s + size : integer, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray or scalar + Random variates of size (`size`, `dims`), where `dims` is the + dimension of the random matrices. + + Notes + ----- + %(_matnorm_doc_callparams_note)s + + """ + size = int(size) + dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov, + colcov) + rowchol = scipy.linalg.cholesky(rowcov, lower=True) + colchol = scipy.linalg.cholesky(colcov, lower=True) + random_state = self._get_random_state(random_state) + # We aren't generating standard normal variates with size=(size, + # dims[0], dims[1]) directly to ensure random variates remain backwards + # compatible. See https://github.com/scipy/scipy/pull/12312 for more + # details. + std_norm = random_state.standard_normal( + size=(dims[1], size, dims[0]) + ).transpose(1, 2, 0) + out = mean + np.einsum('jp,ipq,kq->ijk', + rowchol, std_norm, colchol, + optimize=True) + if size == 1: + out = out.reshape(mean.shape) + return out + + def entropy(self, rowcov=1, colcov=1): + """Log of the matrix normal probability density function. + + Parameters + ---------- + rowcov : array_like, optional + Among-row covariance matrix of the distribution (default: ``1``) + colcov : array_like, optional + Among-column covariance matrix of the distribution (default: ``1``) + + Returns + ------- + entropy : float + Entropy of the distribution + + Notes + ----- + %(_matnorm_doc_callparams_note)s + + """ + dummy_mean = np.zeros((rowcov.shape[0], colcov.shape[0])) + dims, _, rowcov, colcov = self._process_parameters(dummy_mean, + rowcov, + colcov) + rowpsd = _PSD(rowcov, allow_singular=False) + colpsd = _PSD(colcov, allow_singular=False) + + return self._entropy(dims, rowpsd.log_pdet, colpsd.log_pdet) + + def _entropy(self, dims, row_cov_logdet, col_cov_logdet): + n, p = dims + return (0.5 * n * p * (1 + _LOG_2PI) + 0.5 * p * row_cov_logdet + + 0.5 * n * col_cov_logdet) + + +matrix_normal = matrix_normal_gen() + + +class matrix_normal_frozen(multi_rv_frozen): + """ + Create a frozen matrix normal distribution. + + Parameters + ---------- + %(_matnorm_doc_default_callparams)s + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is `None` the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import matrix_normal + + >>> distn = matrix_normal(mean=np.zeros((3,3))) + >>> X = distn.rvs(); X + array([[-0.02976962, 0.93339138, -0.09663178], + [ 0.67405524, 0.28250467, -0.93308929], + [-0.31144782, 0.74535536, 1.30412916]]) + >>> distn.pdf(X) + 2.5160642368346784e-05 + >>> distn.logpdf(X) + -10.590229595124615 + """ + + def __init__(self, mean=None, rowcov=1, colcov=1, seed=None): + self._dist = matrix_normal_gen(seed) + self.dims, self.mean, self.rowcov, self.colcov = \ + self._dist._process_parameters(mean, rowcov, colcov) + self.rowpsd = _PSD(self.rowcov, allow_singular=False) + self.colpsd = _PSD(self.colcov, allow_singular=False) + + def logpdf(self, X): + X = self._dist._process_quantiles(X, self.dims) + out = self._dist._logpdf(self.dims, X, self.mean, self.rowpsd.U, + self.rowpsd.log_pdet, self.colpsd.U, + self.colpsd.log_pdet) + return _squeeze_output(out) + + def pdf(self, X): + return np.exp(self.logpdf(X)) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.mean, self.rowcov, self.colcov, size, + random_state) + + def entropy(self): + return self._dist._entropy(self.dims, self.rowpsd.log_pdet, + self.colpsd.log_pdet) + + +# Set frozen generator docstrings from corresponding docstrings in +# matrix_normal_gen and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'rvs', 'entropy']: + method = matrix_normal_gen.__dict__[name] + method_frozen = matrix_normal_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat(method.__doc__, + matnorm_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, matnorm_docdict_params) + +_dirichlet_doc_default_callparams = """\ +alpha : array_like + The concentration parameters. The number of entries determines the + dimensionality of the distribution. +""" +_dirichlet_doc_frozen_callparams = "" + +_dirichlet_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +dirichlet_docdict_params = { + '_dirichlet_doc_default_callparams': _dirichlet_doc_default_callparams, + '_doc_random_state': _doc_random_state +} + +dirichlet_docdict_noparams = { + '_dirichlet_doc_default_callparams': _dirichlet_doc_frozen_callparams, + '_doc_random_state': _doc_random_state +} + + +def _dirichlet_check_parameters(alpha): + alpha = np.asarray(alpha) + if np.min(alpha) <= 0: + raise ValueError("All parameters must be greater than 0") + elif alpha.ndim != 1: + raise ValueError("Parameter vector 'a' must be one dimensional, " + f"but a.shape = {alpha.shape}.") + return alpha + + +def _dirichlet_check_input(alpha, x): + x = np.asarray(x) + + if x.shape[0] + 1 != alpha.shape[0] and x.shape[0] != alpha.shape[0]: + raise ValueError("Vector 'x' must have either the same number " + "of entries as, or one entry fewer than, " + f"parameter vector 'a', but alpha.shape = {alpha.shape} " + f"and x.shape = {x.shape}.") + + if x.shape[0] != alpha.shape[0]: + xk = np.array([1 - np.sum(x, 0)]) + if xk.ndim == 1: + x = np.append(x, xk) + elif xk.ndim == 2: + x = np.vstack((x, xk)) + else: + raise ValueError("The input must be one dimensional or a two " + "dimensional matrix containing the entries.") + + if np.min(x) < 0: + raise ValueError("Each entry in 'x' must be greater than or equal " + "to zero.") + + if np.max(x) > 1: + raise ValueError("Each entry in 'x' must be smaller or equal one.") + + # Check x_i > 0 or alpha_i > 1 + xeq0 = (x == 0) + alphalt1 = (alpha < 1) + if x.shape != alpha.shape: + alphalt1 = np.repeat(alphalt1, x.shape[-1], axis=-1).reshape(x.shape) + chk = np.logical_and(xeq0, alphalt1) + + if np.sum(chk): + raise ValueError("Each entry in 'x' must be greater than zero if its " + "alpha is less than one.") + + if (np.abs(np.sum(x, 0) - 1.0) > 10e-10).any(): + raise ValueError("The input vector 'x' must lie within the normal " + f"simplex. but np.sum(x, 0) = {np.sum(x, 0)}.") + + return x + + +def _lnB(alpha): + r"""Internal helper function to compute the log of the useful quotient. + + .. math:: + + B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)} + {\Gamma\left(\sum_{i=1}^{K} \alpha_i \right)} + + Parameters + ---------- + %(_dirichlet_doc_default_callparams)s + + Returns + ------- + B : scalar + Helper quotient, internal use only + + """ + return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha)) + + +class dirichlet_gen(multi_rv_generic): + r"""A Dirichlet random variable. + + The ``alpha`` keyword specifies the concentration parameters of the + distribution. + + .. versionadded:: 0.15.0 + + Methods + ------- + pdf(x, alpha) + Probability density function. + logpdf(x, alpha) + Log of the probability density function. + rvs(alpha, size=1, random_state=None) + Draw random samples from a Dirichlet distribution. + mean(alpha) + The mean of the Dirichlet distribution + var(alpha) + The variance of the Dirichlet distribution + cov(alpha) + The covariance of the Dirichlet distribution + entropy(alpha) + Compute the differential entropy of the Dirichlet distribution. + + Parameters + ---------- + %(_dirichlet_doc_default_callparams)s + %(_doc_random_state)s + + Notes + ----- + Each :math:`\alpha` entry must be positive. The distribution has only + support on the simplex defined by + + .. math:: + \sum_{i=1}^{K} x_i = 1 + + where :math:`0 < x_i < 1`. + + If the quantiles don't lie within the simplex, a ValueError is raised. + + The probability density function for `dirichlet` is + + .. math:: + + f(x) = \frac{1}{\mathrm{B}(\boldsymbol\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1} + + where + + .. math:: + + \mathrm{B}(\boldsymbol\alpha) = \frac{\prod_{i=1}^K \Gamma(\alpha_i)} + {\Gamma\bigl(\sum_{i=1}^K \alpha_i\bigr)} + + and :math:`\boldsymbol\alpha=(\alpha_1,\ldots,\alpha_K)`, the + concentration parameters and :math:`K` is the dimension of the space + where :math:`x` takes values. + + Note that the `dirichlet` interface is somewhat inconsistent. + The array returned by the rvs function is transposed + with respect to the format expected by the pdf and logpdf. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import dirichlet + + Generate a dirichlet random variable + + >>> quantiles = np.array([0.2, 0.2, 0.6]) # specify quantiles + >>> alpha = np.array([0.4, 5, 15]) # specify concentration parameters + >>> dirichlet.pdf(quantiles, alpha) + 0.2843831684937255 + + The same PDF but following a log scale + + >>> dirichlet.logpdf(quantiles, alpha) + -1.2574327653159187 + + Once we specify the dirichlet distribution + we can then calculate quantities of interest + + >>> dirichlet.mean(alpha) # get the mean of the distribution + array([0.01960784, 0.24509804, 0.73529412]) + >>> dirichlet.var(alpha) # get variance + array([0.00089829, 0.00864603, 0.00909517]) + >>> dirichlet.entropy(alpha) # calculate the differential entropy + -4.3280162474082715 + + We can also return random samples from the distribution + + >>> dirichlet.rvs(alpha, size=1, random_state=1) + array([[0.00766178, 0.24670518, 0.74563305]]) + >>> dirichlet.rvs(alpha, size=2, random_state=2) + array([[0.01639427, 0.1292273 , 0.85437844], + [0.00156917, 0.19033695, 0.80809388]]) + + Alternatively, the object may be called (as a function) to fix + concentration parameters, returning a "frozen" Dirichlet + random variable: + + >>> rv = dirichlet(alpha) + >>> # Frozen object with the same methods but holding the given + >>> # concentration parameters fixed. + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, dirichlet_docdict_params) + + def __call__(self, alpha, seed=None): + return dirichlet_frozen(alpha, seed=seed) + + def _logpdf(self, x, alpha): + """Log of the Dirichlet probability density function. + + Parameters + ---------- + x : ndarray + Points at which to evaluate the log of the probability + density function + %(_dirichlet_doc_default_callparams)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'logpdf' instead. + + """ + lnB = _lnB(alpha) + return - lnB + np.sum((xlogy(alpha - 1, x.T)).T, 0) + + def logpdf(self, x, alpha): + """Log of the Dirichlet probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_dirichlet_doc_default_callparams)s + + Returns + ------- + pdf : ndarray or scalar + Log of the probability density function evaluated at `x`. + + """ + alpha = _dirichlet_check_parameters(alpha) + x = _dirichlet_check_input(alpha, x) + + out = self._logpdf(x, alpha) + return _squeeze_output(out) + + def pdf(self, x, alpha): + """The Dirichlet probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_dirichlet_doc_default_callparams)s + + Returns + ------- + pdf : ndarray or scalar + The probability density function evaluated at `x`. + + """ + alpha = _dirichlet_check_parameters(alpha) + x = _dirichlet_check_input(alpha, x) + + out = np.exp(self._logpdf(x, alpha)) + return _squeeze_output(out) + + def mean(self, alpha): + """Mean of the Dirichlet distribution. + + Parameters + ---------- + %(_dirichlet_doc_default_callparams)s + + Returns + ------- + mu : ndarray or scalar + Mean of the Dirichlet distribution. + + """ + alpha = _dirichlet_check_parameters(alpha) + + out = alpha / (np.sum(alpha)) + return _squeeze_output(out) + + def var(self, alpha): + """Variance of the Dirichlet distribution. + + Parameters + ---------- + %(_dirichlet_doc_default_callparams)s + + Returns + ------- + v : ndarray or scalar + Variance of the Dirichlet distribution. + + """ + + alpha = _dirichlet_check_parameters(alpha) + + alpha0 = np.sum(alpha) + out = (alpha * (alpha0 - alpha)) / ((alpha0 * alpha0) * (alpha0 + 1)) + return _squeeze_output(out) + + def cov(self, alpha): + """Covariance matrix of the Dirichlet distribution. + + Parameters + ---------- + %(_dirichlet_doc_default_callparams)s + + Returns + ------- + cov : ndarray + The covariance matrix of the distribution. + """ + + alpha = _dirichlet_check_parameters(alpha) + alpha0 = np.sum(alpha) + a = alpha / alpha0 + + cov = (np.diag(a) - np.outer(a, a)) / (alpha0 + 1) + return _squeeze_output(cov) + + def entropy(self, alpha): + """ + Differential entropy of the Dirichlet distribution. + + Parameters + ---------- + %(_dirichlet_doc_default_callparams)s + + Returns + ------- + h : scalar + Entropy of the Dirichlet distribution + + """ + + alpha = _dirichlet_check_parameters(alpha) + + alpha0 = np.sum(alpha) + lnB = _lnB(alpha) + K = alpha.shape[0] + + out = lnB + (alpha0 - K) * scipy.special.psi(alpha0) - np.sum( + (alpha - 1) * scipy.special.psi(alpha)) + return _squeeze_output(out) + + def rvs(self, alpha, size=1, random_state=None): + """ + Draw random samples from a Dirichlet distribution. + + Parameters + ---------- + %(_dirichlet_doc_default_callparams)s + size : int, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray or scalar + Random variates of size (`size`, `N`), where `N` is the + dimension of the random variable. + + """ + alpha = _dirichlet_check_parameters(alpha) + random_state = self._get_random_state(random_state) + return random_state.dirichlet(alpha, size=size) + + +dirichlet = dirichlet_gen() + + +class dirichlet_frozen(multi_rv_frozen): + def __init__(self, alpha, seed=None): + self.alpha = _dirichlet_check_parameters(alpha) + self._dist = dirichlet_gen(seed) + + def logpdf(self, x): + return self._dist.logpdf(x, self.alpha) + + def pdf(self, x): + return self._dist.pdf(x, self.alpha) + + def mean(self): + return self._dist.mean(self.alpha) + + def var(self): + return self._dist.var(self.alpha) + + def cov(self): + return self._dist.cov(self.alpha) + + def entropy(self): + return self._dist.entropy(self.alpha) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.alpha, size, random_state) + + +# Set frozen generator docstrings from corresponding docstrings in +# multivariate_normal_gen and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'rvs', 'mean', 'var', 'cov', 'entropy']: + method = dirichlet_gen.__dict__[name] + method_frozen = dirichlet_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat( + method.__doc__, dirichlet_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, dirichlet_docdict_params) + + +_wishart_doc_default_callparams = """\ +df : int + Degrees of freedom, must be greater than or equal to dimension of the + scale matrix +scale : array_like + Symmetric positive definite scale matrix of the distribution +""" + +_wishart_doc_callparams_note = "" + +_wishart_doc_frozen_callparams = "" + +_wishart_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +wishart_docdict_params = { + '_doc_default_callparams': _wishart_doc_default_callparams, + '_doc_callparams_note': _wishart_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +wishart_docdict_noparams = { + '_doc_default_callparams': _wishart_doc_frozen_callparams, + '_doc_callparams_note': _wishart_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class wishart_gen(multi_rv_generic): + r"""A Wishart random variable. + + The `df` keyword specifies the degrees of freedom. The `scale` keyword + specifies the scale matrix, which must be symmetric and positive definite. + In this context, the scale matrix is often interpreted in terms of a + multivariate normal precision matrix (the inverse of the covariance + matrix). These arguments must satisfy the relationship + ``df > scale.ndim - 1``, but see notes on using the `rvs` method with + ``df < scale.ndim``. + + Methods + ------- + pdf(x, df, scale) + Probability density function. + logpdf(x, df, scale) + Log of the probability density function. + rvs(df, scale, size=1, random_state=None) + Draw random samples from a Wishart distribution. + entropy() + Compute the differential entropy of the Wishart distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + %(_doc_random_state)s + + Raises + ------ + scipy.linalg.LinAlgError + If the scale matrix `scale` is not positive definite. + + See Also + -------- + invwishart, chi2 + + Notes + ----- + %(_doc_callparams_note)s + + The scale matrix `scale` must be a symmetric positive definite + matrix. Singular matrices, including the symmetric positive semi-definite + case, are not supported. Symmetry is not checked; only the lower triangular + portion is used. + + The Wishart distribution is often denoted + + .. math:: + + W_p(\nu, \Sigma) + + where :math:`\nu` is the degrees of freedom and :math:`\Sigma` is the + :math:`p \times p` scale matrix. + + The probability density function for `wishart` has support over positive + definite matrices :math:`S`; if :math:`S \sim W_p(\nu, \Sigma)`, then + its PDF is given by: + + .. math:: + + f(S) = \frac{|S|^{\frac{\nu - p - 1}{2}}}{2^{ \frac{\nu p}{2} } + |\Sigma|^\frac{\nu}{2} \Gamma_p \left ( \frac{\nu}{2} \right )} + \exp\left( -tr(\Sigma^{-1} S) / 2 \right) + + If :math:`S \sim W_p(\nu, \Sigma)` (Wishart) then + :math:`S^{-1} \sim W_p^{-1}(\nu, \Sigma^{-1})` (inverse Wishart). + + If the scale matrix is 1-dimensional and equal to one, then the Wishart + distribution :math:`W_1(\nu, 1)` collapses to the :math:`\chi^2(\nu)` + distribution. + + The algorithm [2]_ implemented by the `rvs` method may + produce numerically singular matrices with :math:`p - 1 < \nu < p`; the + user may wish to check for this condition and generate replacement samples + as necessary. + + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach", + Wiley, 1983. + .. [2] W.B. Smith and R.R. Hocking, "Algorithm AS 53: Wishart Variate + Generator", Applied Statistics, vol. 21, pp. 341-345, 1972. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import wishart, chi2 + >>> x = np.linspace(1e-5, 8, 100) + >>> w = wishart.pdf(x, df=3, scale=1); w[:5] + array([ 0.00126156, 0.10892176, 0.14793434, 0.17400548, 0.1929669 ]) + >>> c = chi2.pdf(x, 3); c[:5] + array([ 0.00126156, 0.10892176, 0.14793434, 0.17400548, 0.1929669 ]) + >>> plt.plot(x, w) + >>> plt.show() + + The input quantiles can be any shape of array, as long as the last + axis labels the components. + + Alternatively, the object may be called (as a function) to fix the degrees + of freedom and scale parameters, returning a "frozen" Wishart random + variable: + + >>> rv = wishart(df=1, scale=1) + >>> # Frozen object with the same methods but holding the given + >>> # degrees of freedom and scale fixed. + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params) + + def __call__(self, df=None, scale=None, seed=None): + """Create a frozen Wishart distribution. + + See `wishart_frozen` for more information. + """ + return wishart_frozen(df, scale, seed) + + def _process_parameters(self, df, scale): + if scale is None: + scale = 1.0 + scale = np.asarray(scale, dtype=float) + + if scale.ndim == 0: + scale = scale[np.newaxis, np.newaxis] + elif scale.ndim == 1: + scale = np.diag(scale) + elif scale.ndim == 2 and not scale.shape[0] == scale.shape[1]: + raise ValueError("Array 'scale' must be square if it is two dimensional," + f" but scale.scale = {str(scale.shape)}.") + elif scale.ndim > 2: + raise ValueError("Array 'scale' must be at most two-dimensional," + " but scale.ndim = %d" % scale.ndim) + + dim = scale.shape[0] + + if df is None: + df = dim + elif not np.isscalar(df): + raise ValueError("Degrees of freedom must be a scalar.") + elif df <= dim - 1: + raise ValueError("Degrees of freedom must be greater than the " + "dimension of scale matrix minus 1.") + + return dim, df, scale + + def _process_quantiles(self, x, dim): + """ + Adjust quantiles array so that last axis labels the components of + each data point. + """ + x = np.asarray(x, dtype=float) + + if x.ndim == 0: + x = x * np.eye(dim)[:, :, np.newaxis] + if x.ndim == 1: + if dim == 1: + x = x[np.newaxis, np.newaxis, :] + else: + x = np.diag(x)[:, :, np.newaxis] + elif x.ndim == 2: + if not x.shape[0] == x.shape[1]: + raise ValueError( + "Quantiles must be square if they are two dimensional," + f" but x.shape = {str(x.shape)}.") + x = x[:, :, np.newaxis] + elif x.ndim == 3: + if not x.shape[0] == x.shape[1]: + raise ValueError( + "Quantiles must be square in the first two dimensions " + f"if they are three dimensional, but x.shape = {str(x.shape)}.") + elif x.ndim > 3: + raise ValueError("Quantiles must be at most two-dimensional with" + " an additional dimension for multiple" + "components, but x.ndim = %d" % x.ndim) + + # Now we have 3-dim array; should have shape [dim, dim, *] + if not x.shape[0:2] == (dim, dim): + raise ValueError('Quantiles have incompatible dimensions: should' + f' be {(dim, dim)}, got {x.shape[0:2]}.') + + return x + + def _process_size(self, size): + size = np.asarray(size) + + if size.ndim == 0: + size = size[np.newaxis] + elif size.ndim > 1: + raise ValueError('Size must be an integer or tuple of integers;' + ' thus must have dimension <= 1.' + f' Got size.ndim = {str(tuple(size))}') + n = size.prod() + shape = tuple(size) + + return n, shape + + def _logpdf(self, x, dim, df, scale, log_det_scale, C): + """Log of the Wishart probability density function. + + Parameters + ---------- + x : ndarray + Points at which to evaluate the log of the probability + density function + dim : int + Dimension of the scale matrix + df : int + Degrees of freedom + scale : ndarray + Scale matrix + log_det_scale : float + Logarithm of the determinant of the scale matrix + C : ndarray + Cholesky factorization of the scale matrix, lower triangular. + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'logpdf' instead. + + """ + # log determinant of x + # Note: x has components along the last axis, so that x.T has + # components alone the 0-th axis. Then since det(A) = det(A'), this + # gives us a 1-dim vector of determinants + + # Retrieve tr(scale^{-1} x) + log_det_x = np.empty(x.shape[-1]) + scale_inv_x = np.empty(x.shape) + tr_scale_inv_x = np.empty(x.shape[-1]) + for i in range(x.shape[-1]): + _, log_det_x[i] = self._cholesky_logdet(x[:, :, i]) + scale_inv_x[:, :, i] = scipy.linalg.cho_solve((C, True), x[:, :, i]) + tr_scale_inv_x[i] = scale_inv_x[:, :, i].trace() + + # Log PDF + out = ((0.5 * (df - dim - 1) * log_det_x - 0.5 * tr_scale_inv_x) - + (0.5 * df * dim * _LOG_2 + 0.5 * df * log_det_scale + + multigammaln(0.5*df, dim))) + + return out + + def logpdf(self, x, df, scale): + """Log of the Wishart probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + Each quantile must be a symmetric positive definite matrix. + %(_doc_default_callparams)s + + Returns + ------- + pdf : ndarray + Log of the probability density function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + + """ + dim, df, scale = self._process_parameters(df, scale) + x = self._process_quantiles(x, dim) + + # Cholesky decomposition of scale, get log(det(scale)) + C, log_det_scale = self._cholesky_logdet(scale) + + out = self._logpdf(x, dim, df, scale, log_det_scale, C) + return _squeeze_output(out) + + def pdf(self, x, df, scale): + """Wishart probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + Each quantile must be a symmetric positive definite matrix. + %(_doc_default_callparams)s + + Returns + ------- + pdf : ndarray + Probability density function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + + """ + return np.exp(self.logpdf(x, df, scale)) + + def _mean(self, dim, df, scale): + """Mean of the Wishart distribution. + + Parameters + ---------- + dim : int + Dimension of the scale matrix + %(_doc_default_callparams)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'mean' instead. + + """ + return df * scale + + def mean(self, df, scale): + """Mean of the Wishart distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + mean : float + The mean of the distribution + """ + dim, df, scale = self._process_parameters(df, scale) + out = self._mean(dim, df, scale) + return _squeeze_output(out) + + def _mode(self, dim, df, scale): + """Mode of the Wishart distribution. + + Parameters + ---------- + dim : int + Dimension of the scale matrix + %(_doc_default_callparams)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'mode' instead. + + """ + if df >= dim + 1: + out = (df-dim-1) * scale + else: + out = None + return out + + def mode(self, df, scale): + """Mode of the Wishart distribution + + Only valid if the degrees of freedom are greater than the dimension of + the scale matrix. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + mode : float or None + The Mode of the distribution + """ + dim, df, scale = self._process_parameters(df, scale) + out = self._mode(dim, df, scale) + return _squeeze_output(out) if out is not None else out + + def _var(self, dim, df, scale): + """Variance of the Wishart distribution. + + Parameters + ---------- + dim : int + Dimension of the scale matrix + %(_doc_default_callparams)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'var' instead. + + """ + var = scale**2 + diag = scale.diagonal() # 1 x dim array + var += np.outer(diag, diag) + var *= df + return var + + def var(self, df, scale): + """Variance of the Wishart distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + var : float + The variance of the distribution + """ + dim, df, scale = self._process_parameters(df, scale) + out = self._var(dim, df, scale) + return _squeeze_output(out) + + def _standard_rvs(self, n, shape, dim, df, random_state): + """ + Parameters + ---------- + n : integer + Number of variates to generate + shape : iterable + Shape of the variates to generate + dim : int + Dimension of the scale matrix + df : int + Degrees of freedom + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'rvs' instead. + + """ + # Random normal variates for off-diagonal elements + n_tril = dim * (dim-1) // 2 + covariances = random_state.normal( + size=n*n_tril).reshape(shape+(n_tril,)) + + # Random chi-square variates for diagonal elements + variances = (np.r_[[random_state.chisquare(df-(i+1)+1, size=n)**0.5 + for i in range(dim)]].reshape((dim,) + + shape[::-1]).T) + + # Create the A matri(ces) - lower triangular + A = np.zeros(shape + (dim, dim)) + + # Input the covariances + size_idx = tuple([slice(None, None, None)]*len(shape)) + tril_idx = np.tril_indices(dim, k=-1) + A[size_idx + tril_idx] = covariances + + # Input the variances + diag_idx = np.diag_indices(dim) + A[size_idx + diag_idx] = variances + + return A + + def _rvs(self, n, shape, dim, df, C, random_state): + """Draw random samples from a Wishart distribution. + + Parameters + ---------- + n : integer + Number of variates to generate + shape : iterable + Shape of the variates to generate + dim : int + Dimension of the scale matrix + df : int + Degrees of freedom + C : ndarray + Cholesky factorization of the scale matrix, lower triangular. + %(_doc_random_state)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'rvs' instead. + + """ + random_state = self._get_random_state(random_state) + # Calculate the matrices A, which are actually lower triangular + # Cholesky factorizations of a matrix B such that B ~ W(df, I) + A = self._standard_rvs(n, shape, dim, df, random_state) + + # Calculate SA = C A A' C', where SA ~ W(df, scale) + # Note: this is the product of a (lower) (lower) (lower)' (lower)' + # or, denoting B = AA', it is C B C' where C is the lower + # triangular Cholesky factorization of the scale matrix. + # this appears to conflict with the instructions in [1]_, which + # suggest that it should be D' B D where D is the lower + # triangular factorization of the scale matrix. However, it is + # meant to refer to the Bartlett (1933) representation of a + # Wishart random variate as L A A' L' where L is lower triangular + # so it appears that understanding D' to be upper triangular + # is either a typo in or misreading of [1]_. + for index in np.ndindex(shape): + CA = np.dot(C, A[index]) + A[index] = np.dot(CA, CA.T) + + return A + + def rvs(self, df, scale, size=1, random_state=None): + """Draw random samples from a Wishart distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + size : integer or iterable of integers, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray + Random variates of shape (`size`) + (``dim``, ``dim``), where + ``dim`` is the dimension of the scale matrix. + + Notes + ----- + %(_doc_callparams_note)s + + """ + n, shape = self._process_size(size) + dim, df, scale = self._process_parameters(df, scale) + + # Cholesky decomposition of scale + C = scipy.linalg.cholesky(scale, lower=True) + + out = self._rvs(n, shape, dim, df, C, random_state) + + return _squeeze_output(out) + + def _entropy(self, dim, df, log_det_scale): + """Compute the differential entropy of the Wishart. + + Parameters + ---------- + dim : int + Dimension of the scale matrix + df : int + Degrees of freedom + log_det_scale : float + Logarithm of the determinant of the scale matrix + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'entropy' instead. + + """ + return ( + 0.5 * (dim+1) * log_det_scale + + 0.5 * dim * (dim+1) * _LOG_2 + + multigammaln(0.5*df, dim) - + 0.5 * (df - dim - 1) * np.sum( + [psi(0.5*(df + 1 - (i+1))) for i in range(dim)] + ) + + 0.5 * df * dim + ) + + def entropy(self, df, scale): + """Compute the differential entropy of the Wishart. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + h : scalar + Entropy of the Wishart distribution + + Notes + ----- + %(_doc_callparams_note)s + + """ + dim, df, scale = self._process_parameters(df, scale) + _, log_det_scale = self._cholesky_logdet(scale) + return self._entropy(dim, df, log_det_scale) + + def _cholesky_logdet(self, scale): + """Compute Cholesky decomposition and determine (log(det(scale)). + + Parameters + ---------- + scale : ndarray + Scale matrix. + + Returns + ------- + c_decomp : ndarray + The Cholesky decomposition of `scale`. + logdet : scalar + The log of the determinant of `scale`. + + Notes + ----- + This computation of ``logdet`` is equivalent to + ``np.linalg.slogdet(scale)``. It is ~2x faster though. + + """ + c_decomp = scipy.linalg.cholesky(scale, lower=True) + logdet = 2 * np.sum(np.log(c_decomp.diagonal())) + return c_decomp, logdet + + +wishart = wishart_gen() + + +class wishart_frozen(multi_rv_frozen): + """Create a frozen Wishart distribution. + + Parameters + ---------- + df : array_like + Degrees of freedom of the distribution + scale : array_like + Scale matrix of the distribution + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + """ + def __init__(self, df, scale, seed=None): + self._dist = wishart_gen(seed) + self.dim, self.df, self.scale = self._dist._process_parameters( + df, scale) + self.C, self.log_det_scale = self._dist._cholesky_logdet(self.scale) + + def logpdf(self, x): + x = self._dist._process_quantiles(x, self.dim) + + out = self._dist._logpdf(x, self.dim, self.df, self.scale, + self.log_det_scale, self.C) + return _squeeze_output(out) + + def pdf(self, x): + return np.exp(self.logpdf(x)) + + def mean(self): + out = self._dist._mean(self.dim, self.df, self.scale) + return _squeeze_output(out) + + def mode(self): + out = self._dist._mode(self.dim, self.df, self.scale) + return _squeeze_output(out) if out is not None else out + + def var(self): + out = self._dist._var(self.dim, self.df, self.scale) + return _squeeze_output(out) + + def rvs(self, size=1, random_state=None): + n, shape = self._dist._process_size(size) + out = self._dist._rvs(n, shape, self.dim, self.df, + self.C, random_state) + return _squeeze_output(out) + + def entropy(self): + return self._dist._entropy(self.dim, self.df, self.log_det_scale) + + +# Set frozen generator docstrings from corresponding docstrings in +# Wishart and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs', 'entropy']: + method = wishart_gen.__dict__[name] + method_frozen = wishart_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat( + method.__doc__, wishart_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params) + + +class invwishart_gen(wishart_gen): + r"""An inverse Wishart random variable. + + The `df` keyword specifies the degrees of freedom. The `scale` keyword + specifies the scale matrix, which must be symmetric and positive definite. + In this context, the scale matrix is often interpreted in terms of a + multivariate normal covariance matrix. + + Methods + ------- + pdf(x, df, scale) + Probability density function. + logpdf(x, df, scale) + Log of the probability density function. + rvs(df, scale, size=1, random_state=None) + Draw random samples from an inverse Wishart distribution. + entropy(df, scale) + Differential entropy of the distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + %(_doc_random_state)s + + Raises + ------ + scipy.linalg.LinAlgError + If the scale matrix `scale` is not positive definite. + + See Also + -------- + wishart + + Notes + ----- + %(_doc_callparams_note)s + + The scale matrix `scale` must be a symmetric positive definite + matrix. Singular matrices, including the symmetric positive semi-definite + case, are not supported. Symmetry is not checked; only the lower triangular + portion is used. + + The inverse Wishart distribution is often denoted + + .. math:: + + W_p^{-1}(\nu, \Psi) + + where :math:`\nu` is the degrees of freedom and :math:`\Psi` is the + :math:`p \times p` scale matrix. + + The probability density function for `invwishart` has support over positive + definite matrices :math:`S`; if :math:`S \sim W^{-1}_p(\nu, \Sigma)`, + then its PDF is given by: + + .. math:: + + f(S) = \frac{|\Sigma|^\frac{\nu}{2}}{2^{ \frac{\nu p}{2} } + |S|^{\frac{\nu + p + 1}{2}} \Gamma_p \left(\frac{\nu}{2} \right)} + \exp\left( -tr(\Sigma S^{-1}) / 2 \right) + + If :math:`S \sim W_p^{-1}(\nu, \Psi)` (inverse Wishart) then + :math:`S^{-1} \sim W_p(\nu, \Psi^{-1})` (Wishart). + + If the scale matrix is 1-dimensional and equal to one, then the inverse + Wishart distribution :math:`W_1(\nu, 1)` collapses to the + inverse Gamma distribution with parameters shape = :math:`\frac{\nu}{2}` + and scale = :math:`\frac{1}{2}`. + + Instead of inverting a randomly generated Wishart matrix as described in [2], + here the algorithm in [4] is used to directly generate a random inverse-Wishart + matrix without inversion. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach", + Wiley, 1983. + .. [2] M.C. Jones, "Generating Inverse Wishart Matrices", Communications + in Statistics - Simulation and Computation, vol. 14.2, pp.511-514, + 1985. + .. [3] Gupta, M. and Srivastava, S. "Parametric Bayesian Estimation of + Differential Entropy and Relative Entropy". Entropy 12, 818 - 843. + 2010. + .. [4] S.D. Axen, "Efficiently generating inverse-Wishart matrices and + their Cholesky factors", :arXiv:`2310.15884v1`. 2023. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import invwishart, invgamma + >>> x = np.linspace(0.01, 1, 100) + >>> iw = invwishart.pdf(x, df=6, scale=1) + >>> iw[:3] + array([ 1.20546865e-15, 5.42497807e-06, 4.45813929e-03]) + >>> ig = invgamma.pdf(x, 6/2., scale=1./2) + >>> ig[:3] + array([ 1.20546865e-15, 5.42497807e-06, 4.45813929e-03]) + >>> plt.plot(x, iw) + >>> plt.show() + + The input quantiles can be any shape of array, as long as the last + axis labels the components. + + Alternatively, the object may be called (as a function) to fix the degrees + of freedom and scale parameters, returning a "frozen" inverse Wishart + random variable: + + >>> rv = invwishart(df=1, scale=1) + >>> # Frozen object with the same methods but holding the given + >>> # degrees of freedom and scale fixed. + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params) + + def __call__(self, df=None, scale=None, seed=None): + """Create a frozen inverse Wishart distribution. + + See `invwishart_frozen` for more information. + + """ + return invwishart_frozen(df, scale, seed) + + def _logpdf(self, x, dim, df, log_det_scale, C): + """Log of the inverse Wishart probability density function. + + Parameters + ---------- + x : ndarray + Points at which to evaluate the log of the probability + density function. + dim : int + Dimension of the scale matrix + df : int + Degrees of freedom + log_det_scale : float + Logarithm of the determinant of the scale matrix + C : ndarray + Cholesky factorization of the scale matrix, lower triangular. + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'logpdf' instead. + + """ + # Retrieve tr(scale x^{-1}) + log_det_x = np.empty(x.shape[-1]) + tr_scale_x_inv = np.empty(x.shape[-1]) + trsm = get_blas_funcs(('trsm'), (x,)) + if dim > 1: + for i in range(x.shape[-1]): + Cx, log_det_x[i] = self._cholesky_logdet(x[:, :, i]) + A = trsm(1., Cx, C, side=0, lower=True) + tr_scale_x_inv[i] = np.linalg.norm(A)**2 + else: + log_det_x[:] = np.log(x[0, 0]) + tr_scale_x_inv[:] = C[0, 0]**2 / x[0, 0] + + # Log PDF + out = ((0.5 * df * log_det_scale - 0.5 * tr_scale_x_inv) - + (0.5 * df * dim * _LOG_2 + 0.5 * (df + dim + 1) * log_det_x) - + multigammaln(0.5*df, dim)) + + return out + + def logpdf(self, x, df, scale): + """Log of the inverse Wishart probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + Each quantile must be a symmetric positive definite matrix. + %(_doc_default_callparams)s + + Returns + ------- + pdf : ndarray + Log of the probability density function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + + """ + dim, df, scale = self._process_parameters(df, scale) + x = self._process_quantiles(x, dim) + C, log_det_scale = self._cholesky_logdet(scale) + out = self._logpdf(x, dim, df, log_det_scale, C) + return _squeeze_output(out) + + def pdf(self, x, df, scale): + """Inverse Wishart probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + Each quantile must be a symmetric positive definite matrix. + %(_doc_default_callparams)s + + Returns + ------- + pdf : ndarray + Probability density function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + + """ + return np.exp(self.logpdf(x, df, scale)) + + def _mean(self, dim, df, scale): + """Mean of the inverse Wishart distribution. + + Parameters + ---------- + dim : int + Dimension of the scale matrix + %(_doc_default_callparams)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'mean' instead. + + """ + if df > dim + 1: + out = scale / (df - dim - 1) + else: + out = None + return out + + def mean(self, df, scale): + """Mean of the inverse Wishart distribution. + + Only valid if the degrees of freedom are greater than the dimension of + the scale matrix plus one. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + mean : float or None + The mean of the distribution + + """ + dim, df, scale = self._process_parameters(df, scale) + out = self._mean(dim, df, scale) + return _squeeze_output(out) if out is not None else out + + def _mode(self, dim, df, scale): + """Mode of the inverse Wishart distribution. + + Parameters + ---------- + dim : int + Dimension of the scale matrix + %(_doc_default_callparams)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'mode' instead. + + """ + return scale / (df + dim + 1) + + def mode(self, df, scale): + """Mode of the inverse Wishart distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + mode : float + The Mode of the distribution + + """ + dim, df, scale = self._process_parameters(df, scale) + out = self._mode(dim, df, scale) + return _squeeze_output(out) + + def _var(self, dim, df, scale): + """Variance of the inverse Wishart distribution. + + Parameters + ---------- + dim : int + Dimension of the scale matrix + %(_doc_default_callparams)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'var' instead. + + """ + if df > dim + 3: + var = (df - dim + 1) * scale**2 + diag = scale.diagonal() # 1 x dim array + var += (df - dim - 1) * np.outer(diag, diag) + var /= (df - dim) * (df - dim - 1)**2 * (df - dim - 3) + else: + var = None + return var + + def var(self, df, scale): + """Variance of the inverse Wishart distribution. + + Only valid if the degrees of freedom are greater than the dimension of + the scale matrix plus three. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + var : float + The variance of the distribution + """ + dim, df, scale = self._process_parameters(df, scale) + out = self._var(dim, df, scale) + return _squeeze_output(out) if out is not None else out + + def _inv_standard_rvs(self, n, shape, dim, df, random_state): + """ + Parameters + ---------- + n : integer + Number of variates to generate + shape : iterable + Shape of the variates to generate + dim : int + Dimension of the scale matrix + df : int + Degrees of freedom + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + Returns + ------- + A : ndarray + Random variates of shape (`shape`) + (``dim``, ``dim``). + Each slice `A[..., :, :]` is lower-triangular, and its + inverse is the lower Cholesky factor of a draw from + `invwishart(df, np.eye(dim))`. + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'rvs' instead. + + """ + A = np.zeros(shape + (dim, dim)) + + # Random normal variates for off-diagonal elements + tri_rows, tri_cols = np.tril_indices(dim, k=-1) + n_tril = dim * (dim-1) // 2 + A[..., tri_rows, tri_cols] = random_state.normal( + size=(*shape, n_tril), + ) + + # Random chi variates for diagonal elements + rows = np.arange(dim) + chi_dfs = (df - dim + 1) + rows + A[..., rows, rows] = random_state.chisquare( + df=chi_dfs, size=(*shape, dim), + )**0.5 + + return A + + def _rvs(self, n, shape, dim, df, C, random_state): + """Draw random samples from an inverse Wishart distribution. + + Parameters + ---------- + n : integer + Number of variates to generate + shape : iterable + Shape of the variates to generate + dim : int + Dimension of the scale matrix + df : int + Degrees of freedom + C : ndarray + Cholesky factorization of the scale matrix, lower triangular. + %(_doc_random_state)s + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'rvs' instead. + + """ + random_state = self._get_random_state(random_state) + # Get random draws A such that inv(A) ~ iW(df, I) + A = self._inv_standard_rvs(n, shape, dim, df, random_state) + + # Calculate SA = (CA)'^{-1} (CA)^{-1} ~ iW(df, scale) + trsm = get_blas_funcs(('trsm'), (A,)) + trmm = get_blas_funcs(('trmm'), (A,)) + + for index in np.ndindex(A.shape[:-2]): + if dim > 1: + # Calculate CA + # Get CA = C A^{-1} via triangular solver + CA = trsm(1., A[index], C, side=1, lower=True) + # get SA + A[index] = trmm(1., CA, CA, side=1, lower=True, trans_a=True) + else: + A[index][0, 0] = (C[0, 0] / A[index][0, 0])**2 + + return A + + def rvs(self, df, scale, size=1, random_state=None): + """Draw random samples from an inverse Wishart distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + size : integer or iterable of integers, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray + Random variates of shape (`size`) + (``dim``, ``dim``), where + ``dim`` is the dimension of the scale matrix. + + Notes + ----- + %(_doc_callparams_note)s + + """ + n, shape = self._process_size(size) + dim, df, scale = self._process_parameters(df, scale) + + # Cholesky decomposition of scale + C = scipy.linalg.cholesky(scale, lower=True) + + out = self._rvs(n, shape, dim, df, C, random_state) + + return _squeeze_output(out) + + def _entropy(self, dim, df, log_det_scale): + # reference: eq. (17) from ref. 3 + psi_eval_points = [0.5 * (df - dim + i) for i in range(1, dim + 1)] + psi_eval_points = np.asarray(psi_eval_points) + return multigammaln(0.5 * df, dim) + 0.5 * dim * df + \ + 0.5 * (dim + 1) * (log_det_scale - _LOG_2) - \ + 0.5 * (df + dim + 1) * \ + psi(psi_eval_points, out=psi_eval_points).sum() + + def entropy(self, df, scale): + dim, df, scale = self._process_parameters(df, scale) + _, log_det_scale = self._cholesky_logdet(scale) + return self._entropy(dim, df, log_det_scale) + + +invwishart = invwishart_gen() + + +class invwishart_frozen(multi_rv_frozen): + def __init__(self, df, scale, seed=None): + """Create a frozen inverse Wishart distribution. + + Parameters + ---------- + df : array_like + Degrees of freedom of the distribution + scale : array_like + Scale matrix of the distribution + seed : {None, int, `numpy.random.Generator`}, optional + If `seed` is None the `numpy.random.Generator` singleton is used. + If `seed` is an int, a new ``Generator`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` instance then that instance is + used. + + """ + self._dist = invwishart_gen(seed) + self.dim, self.df, self.scale = self._dist._process_parameters( + df, scale + ) + + # Get the determinant via Cholesky factorization + self.C = scipy.linalg.cholesky(self.scale, lower=True) + self.log_det_scale = 2 * np.sum(np.log(self.C.diagonal())) + + def logpdf(self, x): + x = self._dist._process_quantiles(x, self.dim) + out = self._dist._logpdf(x, self.dim, self.df, + self.log_det_scale, self.C) + return _squeeze_output(out) + + def pdf(self, x): + return np.exp(self.logpdf(x)) + + def mean(self): + out = self._dist._mean(self.dim, self.df, self.scale) + return _squeeze_output(out) if out is not None else out + + def mode(self): + out = self._dist._mode(self.dim, self.df, self.scale) + return _squeeze_output(out) + + def var(self): + out = self._dist._var(self.dim, self.df, self.scale) + return _squeeze_output(out) if out is not None else out + + def rvs(self, size=1, random_state=None): + n, shape = self._dist._process_size(size) + + out = self._dist._rvs(n, shape, self.dim, self.df, + self.C, random_state) + + return _squeeze_output(out) + + def entropy(self): + return self._dist._entropy(self.dim, self.df, self.log_det_scale) + + +# Set frozen generator docstrings from corresponding docstrings in +# inverse Wishart and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs']: + method = invwishart_gen.__dict__[name] + method_frozen = wishart_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat( + method.__doc__, wishart_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params) + +_multinomial_doc_default_callparams = """\ +n : int + Number of trials +p : array_like + Probability of a trial falling into each category; should sum to 1 +""" + +_multinomial_doc_callparams_note = """\ +`n` should be a nonnegative integer. Each element of `p` should be in the +interval :math:`[0,1]` and the elements should sum to 1. If they do not sum to +1, the last element of the `p` array is not used and is replaced with the +remaining probability left over from the earlier elements. +""" + +_multinomial_doc_frozen_callparams = "" + +_multinomial_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +multinomial_docdict_params = { + '_doc_default_callparams': _multinomial_doc_default_callparams, + '_doc_callparams_note': _multinomial_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +multinomial_docdict_noparams = { + '_doc_default_callparams': _multinomial_doc_frozen_callparams, + '_doc_callparams_note': _multinomial_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class multinomial_gen(multi_rv_generic): + r"""A multinomial random variable. + + Methods + ------- + pmf(x, n, p) + Probability mass function. + logpmf(x, n, p) + Log of the probability mass function. + rvs(n, p, size=1, random_state=None) + Draw random samples from a multinomial distribution. + entropy(n, p) + Compute the entropy of the multinomial distribution. + cov(n, p) + Compute the covariance matrix of the multinomial distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + %(_doc_random_state)s + + Notes + ----- + %(_doc_callparams_note)s + + The probability mass function for `multinomial` is + + .. math:: + + f(x) = \frac{n!}{x_1! \cdots x_k!} p_1^{x_1} \cdots p_k^{x_k}, + + supported on :math:`x=(x_1, \ldots, x_k)` where each :math:`x_i` is a + nonnegative integer and their sum is :math:`n`. + + .. versionadded:: 0.19.0 + + Examples + -------- + + >>> from scipy.stats import multinomial + >>> rv = multinomial(8, [0.3, 0.2, 0.5]) + >>> rv.pmf([1, 3, 4]) + 0.042000000000000072 + + The multinomial distribution for :math:`k=2` is identical to the + corresponding binomial distribution (tiny numerical differences + notwithstanding): + + >>> from scipy.stats import binom + >>> multinomial.pmf([3, 4], n=7, p=[0.4, 0.6]) + 0.29030399999999973 + >>> binom.pmf(3, 7, 0.4) + 0.29030400000000012 + + The functions ``pmf``, ``logpmf``, ``entropy``, and ``cov`` support + broadcasting, under the convention that the vector parameters (``x`` and + ``p``) are interpreted as if each row along the last axis is a single + object. For instance: + + >>> multinomial.pmf([[3, 4], [3, 5]], n=[7, 8], p=[.3, .7]) + array([0.2268945, 0.25412184]) + + Here, ``x.shape == (2, 2)``, ``n.shape == (2,)``, and ``p.shape == (2,)``, + but following the rules mentioned above they behave as if the rows + ``[3, 4]`` and ``[3, 5]`` in ``x`` and ``[.3, .7]`` in ``p`` were a single + object, and as if we had ``x.shape = (2,)``, ``n.shape = (2,)``, and + ``p.shape = ()``. To obtain the individual elements without broadcasting, + we would do this: + + >>> multinomial.pmf([3, 4], n=7, p=[.3, .7]) + 0.2268945 + >>> multinomial.pmf([3, 5], 8, p=[.3, .7]) + 0.25412184 + + This broadcasting also works for ``cov``, where the output objects are + square matrices of size ``p.shape[-1]``. For example: + + >>> multinomial.cov([4, 5], [[.3, .7], [.4, .6]]) + array([[[ 0.84, -0.84], + [-0.84, 0.84]], + [[ 1.2 , -1.2 ], + [-1.2 , 1.2 ]]]) + + In this example, ``n.shape == (2,)`` and ``p.shape == (2, 2)``, and + following the rules above, these broadcast as if ``p.shape == (2,)``. + Thus the result should also be of shape ``(2,)``, but since each output is + a :math:`2 \times 2` matrix, the result in fact has shape ``(2, 2, 2)``, + where ``result[0]`` is equal to ``multinomial.cov(n=4, p=[.3, .7])`` and + ``result[1]`` is equal to ``multinomial.cov(n=5, p=[.4, .6])``. + + Alternatively, the object may be called (as a function) to fix the `n` and + `p` parameters, returning a "frozen" multinomial random variable: + + >>> rv = multinomial(n=7, p=[.3, .7]) + >>> # Frozen object with the same methods but holding the given + >>> # degrees of freedom and scale fixed. + + See also + -------- + scipy.stats.binom : The binomial distribution. + numpy.random.Generator.multinomial : Sampling from the multinomial distribution. + scipy.stats.multivariate_hypergeom : + The multivariate hypergeometric distribution. + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = \ + doccer.docformat(self.__doc__, multinomial_docdict_params) + + def __call__(self, n, p, seed=None): + """Create a frozen multinomial distribution. + + See `multinomial_frozen` for more information. + """ + return multinomial_frozen(n, p, seed) + + def _process_parameters(self, n, p, eps=1e-15): + """Returns: n_, p_, npcond. + + n_ and p_ are arrays of the correct shape; npcond is a boolean array + flagging values out of the domain. + """ + p = np.array(p, dtype=np.float64, copy=True) + p_adjusted = 1. - p[..., :-1].sum(axis=-1) + i_adjusted = np.abs(p_adjusted) > eps + p[i_adjusted, -1] = p_adjusted[i_adjusted] + + # true for bad p + pcond = np.any(p < 0, axis=-1) + pcond |= np.any(p > 1, axis=-1) + + n = np.array(n, dtype=int, copy=True) + + # true for bad n + ncond = n < 0 + + return n, p, ncond | pcond + + def _process_quantiles(self, x, n, p): + """Returns: x_, xcond. + + x_ is an int array; xcond is a boolean array flagging values out of the + domain. + """ + xx = np.asarray(x, dtype=int) + + if xx.ndim == 0: + raise ValueError("x must be an array.") + + if xx.size != 0 and not xx.shape[-1] == p.shape[-1]: + raise ValueError("Size of each quantile should be size of p: " + "received %d, but expected %d." % + (xx.shape[-1], p.shape[-1])) + + # true for x out of the domain + cond = np.any(xx != x, axis=-1) + cond |= np.any(xx < 0, axis=-1) + cond = cond | (np.sum(xx, axis=-1) != n) + + return xx, cond + + def _checkresult(self, result, cond, bad_value): + result = np.asarray(result) + + if cond.ndim != 0: + result[cond] = bad_value + elif cond: + if result.ndim == 0: + return bad_value + result[...] = bad_value + return result + + def _logpmf(self, x, n, p): + return gammaln(n+1) + np.sum(xlogy(x, p) - gammaln(x+1), axis=-1) + + def logpmf(self, x, n, p): + """Log of the Multinomial probability mass function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_doc_default_callparams)s + + Returns + ------- + logpmf : ndarray or scalar + Log of the probability mass function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + """ + n, p, npcond = self._process_parameters(n, p) + x, xcond = self._process_quantiles(x, n, p) + + result = self._logpmf(x, n, p) + + # replace values for which x was out of the domain; broadcast + # xcond to the right shape + xcond_ = xcond | np.zeros(npcond.shape, dtype=np.bool_) + result = self._checkresult(result, xcond_, -np.inf) + + # replace values bad for n or p; broadcast npcond to the right shape + npcond_ = npcond | np.zeros(xcond.shape, dtype=np.bool_) + return self._checkresult(result, npcond_, np.nan) + + def pmf(self, x, n, p): + """Multinomial probability mass function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_doc_default_callparams)s + + Returns + ------- + pmf : ndarray or scalar + Probability density function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + """ + return np.exp(self.logpmf(x, n, p)) + + def mean(self, n, p): + """Mean of the Multinomial distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + mean : float + The mean of the distribution + """ + n, p, npcond = self._process_parameters(n, p) + result = n[..., np.newaxis]*p + return self._checkresult(result, npcond, np.nan) + + def cov(self, n, p): + """Covariance matrix of the multinomial distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + cov : ndarray + The covariance matrix of the distribution + """ + n, p, npcond = self._process_parameters(n, p) + + nn = n[..., np.newaxis, np.newaxis] + result = nn * np.einsum('...j,...k->...jk', -p, p) + + # change the diagonal + for i in range(p.shape[-1]): + result[..., i, i] += n*p[..., i] + + return self._checkresult(result, npcond, np.nan) + + def entropy(self, n, p): + r"""Compute the entropy of the multinomial distribution. + + The entropy is computed using this expression: + + .. math:: + + f(x) = - \log n! - n\sum_{i=1}^k p_i \log p_i + + \sum_{i=1}^k \sum_{x=0}^n \binom n x p_i^x(1-p_i)^{n-x} \log x! + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + h : scalar + Entropy of the Multinomial distribution + + Notes + ----- + %(_doc_callparams_note)s + """ + n, p, npcond = self._process_parameters(n, p) + + x = np.r_[1:np.max(n)+1] + + term1 = n*np.sum(entr(p), axis=-1) + term1 -= gammaln(n+1) + + n = n[..., np.newaxis] + new_axes_needed = max(p.ndim, n.ndim) - x.ndim + 1 + x.shape += (1,)*new_axes_needed + + term2 = np.sum(binom.pmf(x, n, p)*gammaln(x+1), + axis=(-1, -1-new_axes_needed)) + + return self._checkresult(term1 + term2, npcond, np.nan) + + def rvs(self, n, p, size=None, random_state=None): + """Draw random samples from a Multinomial distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + size : integer or iterable of integers, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray or scalar + Random variates of shape (`size`, `len(p)`) + + Notes + ----- + %(_doc_callparams_note)s + """ + n, p, npcond = self._process_parameters(n, p) + random_state = self._get_random_state(random_state) + return random_state.multinomial(n, p, size) + + +multinomial = multinomial_gen() + + +class multinomial_frozen(multi_rv_frozen): + r"""Create a frozen Multinomial distribution. + + Parameters + ---------- + n : int + number of trials + p: array_like + probability of a trial falling into each category; should sum to 1 + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + """ + def __init__(self, n, p, seed=None): + self._dist = multinomial_gen(seed) + self.n, self.p, self.npcond = self._dist._process_parameters(n, p) + + # monkey patch self._dist + def _process_parameters(n, p): + return self.n, self.p, self.npcond + + self._dist._process_parameters = _process_parameters + + def logpmf(self, x): + return self._dist.logpmf(x, self.n, self.p) + + def pmf(self, x): + return self._dist.pmf(x, self.n, self.p) + + def mean(self): + return self._dist.mean(self.n, self.p) + + def cov(self): + return self._dist.cov(self.n, self.p) + + def entropy(self): + return self._dist.entropy(self.n, self.p) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.n, self.p, size, random_state) + + +# Set frozen generator docstrings from corresponding docstrings in +# multinomial and fill in default strings in class docstrings +for name in ['logpmf', 'pmf', 'mean', 'cov', 'rvs']: + method = multinomial_gen.__dict__[name] + method_frozen = multinomial_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat( + method.__doc__, multinomial_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, + multinomial_docdict_params) + + +class special_ortho_group_gen(multi_rv_generic): + r"""A Special Orthogonal matrix (SO(N)) random variable. + + Return a random rotation matrix, drawn from the Haar distribution + (the only uniform distribution on SO(N)) with a determinant of +1. + + The `dim` keyword specifies the dimension N. + + Methods + ------- + rvs(dim=None, size=1, random_state=None) + Draw random samples from SO(N). + + Parameters + ---------- + dim : scalar + Dimension of matrices + seed : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + Notes + ----- + This class is wrapping the random_rot code from the MDP Toolkit, + https://github.com/mdp-toolkit/mdp-toolkit + + Return a random rotation matrix, drawn from the Haar distribution + (the only uniform distribution on SO(N)). + The algorithm is described in the paper + Stewart, G.W., "The efficient generation of random orthogonal + matrices with an application to condition estimators", SIAM Journal + on Numerical Analysis, 17(3), pp. 403-409, 1980. + For more information see + https://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization + + See also the similar `ortho_group`. For a random rotation in three + dimensions, see `scipy.spatial.transform.Rotation.random`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import special_ortho_group + >>> x = special_ortho_group.rvs(3) + + >>> np.dot(x, x.T) + array([[ 1.00000000e+00, 1.13231364e-17, -2.86852790e-16], + [ 1.13231364e-17, 1.00000000e+00, -1.46845020e-16], + [ -2.86852790e-16, -1.46845020e-16, 1.00000000e+00]]) + + >>> import scipy.linalg + >>> scipy.linalg.det(x) + 1.0 + + This generates one random matrix from SO(3). It is orthogonal and + has a determinant of 1. + + Alternatively, the object may be called (as a function) to fix the `dim` + parameter, returning a "frozen" special_ortho_group random variable: + + >>> rv = special_ortho_group(5) + >>> # Frozen object with the same methods but holding the + >>> # dimension parameter fixed. + + See Also + -------- + ortho_group, scipy.spatial.transform.Rotation.random + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__) + + def __call__(self, dim=None, seed=None): + """Create a frozen SO(N) distribution. + + See `special_ortho_group_frozen` for more information. + """ + return special_ortho_group_frozen(dim, seed=seed) + + def _process_parameters(self, dim): + """Dimension N must be specified; it cannot be inferred.""" + if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim): + raise ValueError("""Dimension of rotation must be specified, + and must be a scalar greater than 1.""") + + return dim + + def rvs(self, dim, size=1, random_state=None): + """Draw random samples from SO(N). + + Parameters + ---------- + dim : integer + Dimension of rotation space (N). + size : integer, optional + Number of samples to draw (default 1). + + Returns + ------- + rvs : ndarray or scalar + Random size N-dimensional matrices, dimension (size, dim, dim) + + """ + random_state = self._get_random_state(random_state) + + size = int(size) + size = (size,) if size > 1 else () + + dim = self._process_parameters(dim) + + # H represents a (dim, dim) matrix, while D represents the diagonal of + # a (dim, dim) diagonal matrix. The algorithm that follows is + # broadcasted on the leading shape in `size` to vectorize along + # samples. + H = np.empty(size + (dim, dim)) + H[..., :, :] = np.eye(dim) + D = np.empty(size + (dim,)) + + for n in range(dim-1): + + # x is a vector with length dim-n, xrow and xcol are views of it as + # a row vector and column vector respectively. It's important they + # are views and not copies because we are going to modify x + # in-place. + x = random_state.normal(size=size + (dim-n,)) + xrow = x[..., None, :] + xcol = x[..., :, None] + + # This is the squared norm of x, without vectorization it would be + # dot(x, x), to have proper broadcasting we use matmul and squeeze + # out (convert to scalar) the resulting 1x1 matrix + norm2 = np.matmul(xrow, xcol).squeeze((-2, -1)) + + x0 = x[..., 0].copy() + D[..., n] = np.where(x0 != 0, np.sign(x0), 1) + x[..., 0] += D[..., n]*np.sqrt(norm2) + + # In renormalizing x we have to append an additional axis with + # [..., None] to broadcast the scalar against the vector x + x /= np.sqrt((norm2 - x0**2 + x[..., 0]**2) / 2.)[..., None] + + # Householder transformation, without vectorization the RHS can be + # written as outer(H @ x, x) (apart from the slicing) + H[..., :, n:] -= np.matmul(H[..., :, n:], xcol) * xrow + + D[..., -1] = (-1)**(dim-1)*D[..., :-1].prod(axis=-1) + + # Without vectorization this could be written as H = diag(D) @ H, + # left-multiplication by a diagonal matrix amounts to multiplying each + # row of H by an element of the diagonal, so we add a dummy axis for + # the column index + H *= D[..., :, None] + return H + + +special_ortho_group = special_ortho_group_gen() + + +class special_ortho_group_frozen(multi_rv_frozen): + def __init__(self, dim=None, seed=None): + """Create a frozen SO(N) distribution. + + Parameters + ---------- + dim : scalar + Dimension of matrices + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + Examples + -------- + >>> from scipy.stats import special_ortho_group + >>> g = special_ortho_group(5) + >>> x = g.rvs() + + """ # numpy/numpydoc#87 # noqa: E501 + self._dist = special_ortho_group_gen(seed) + self.dim = self._dist._process_parameters(dim) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.dim, size, random_state) + + +class ortho_group_gen(multi_rv_generic): + r"""An Orthogonal matrix (O(N)) random variable. + + Return a random orthogonal matrix, drawn from the O(N) Haar + distribution (the only uniform distribution on O(N)). + + The `dim` keyword specifies the dimension N. + + Methods + ------- + rvs(dim=None, size=1, random_state=None) + Draw random samples from O(N). + + Parameters + ---------- + dim : scalar + Dimension of matrices + seed : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + Notes + ----- + This class is closely related to `special_ortho_group`. + + Some care is taken to avoid numerical error, as per the paper by Mezzadri. + + References + ---------- + .. [1] F. Mezzadri, "How to generate random matrices from the classical + compact groups", :arXiv:`math-ph/0609050v2`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import ortho_group + >>> x = ortho_group.rvs(3) + + >>> np.dot(x, x.T) + array([[ 1.00000000e+00, 1.13231364e-17, -2.86852790e-16], + [ 1.13231364e-17, 1.00000000e+00, -1.46845020e-16], + [ -2.86852790e-16, -1.46845020e-16, 1.00000000e+00]]) + + >>> import scipy.linalg + >>> np.fabs(scipy.linalg.det(x)) + 1.0 + + This generates one random matrix from O(3). It is orthogonal and + has a determinant of +1 or -1. + + Alternatively, the object may be called (as a function) to fix the `dim` + parameter, returning a "frozen" ortho_group random variable: + + >>> rv = ortho_group(5) + >>> # Frozen object with the same methods but holding the + >>> # dimension parameter fixed. + + See Also + -------- + special_ortho_group + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__) + + def __call__(self, dim=None, seed=None): + """Create a frozen O(N) distribution. + + See `ortho_group_frozen` for more information. + """ + return ortho_group_frozen(dim, seed=seed) + + def _process_parameters(self, dim): + """Dimension N must be specified; it cannot be inferred.""" + if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim): + raise ValueError("Dimension of rotation must be specified," + "and must be a scalar greater than 1.") + + return dim + + def rvs(self, dim, size=1, random_state=None): + """Draw random samples from O(N). + + Parameters + ---------- + dim : integer + Dimension of rotation space (N). + size : integer, optional + Number of samples to draw (default 1). + + Returns + ------- + rvs : ndarray or scalar + Random size N-dimensional matrices, dimension (size, dim, dim) + + """ + random_state = self._get_random_state(random_state) + + size = int(size) + + dim = self._process_parameters(dim) + + size = (size,) if size > 1 else () + z = random_state.normal(size=size + (dim, dim)) + q, r = np.linalg.qr(z) + # The last two dimensions are the rows and columns of R matrices. + # Extract the diagonals. Note that this eliminates a dimension. + d = r.diagonal(offset=0, axis1=-2, axis2=-1) + # Add back a dimension for proper broadcasting: we're dividing + # each row of each R matrix by the diagonal of the R matrix. + q *= (d/abs(d))[..., np.newaxis, :] # to broadcast properly + return q + + +ortho_group = ortho_group_gen() + + +class ortho_group_frozen(multi_rv_frozen): + def __init__(self, dim=None, seed=None): + """Create a frozen O(N) distribution. + + Parameters + ---------- + dim : scalar + Dimension of matrices + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + Examples + -------- + >>> from scipy.stats import ortho_group + >>> g = ortho_group(5) + >>> x = g.rvs() + + """ # numpy/numpydoc#87 # noqa: E501 + self._dist = ortho_group_gen(seed) + self.dim = self._dist._process_parameters(dim) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.dim, size, random_state) + + +class random_correlation_gen(multi_rv_generic): + r"""A random correlation matrix. + + Return a random correlation matrix, given a vector of eigenvalues. + + The `eigs` keyword specifies the eigenvalues of the correlation matrix, + and implies the dimension. + + Methods + ------- + rvs(eigs=None, random_state=None) + Draw random correlation matrices, all with eigenvalues eigs. + + Parameters + ---------- + eigs : 1d ndarray + Eigenvalues of correlation matrix + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + tol : float, optional + Tolerance for input parameter checks + diag_tol : float, optional + Tolerance for deviation of the diagonal of the resulting + matrix. Default: 1e-7 + + Raises + ------ + RuntimeError + Floating point error prevented generating a valid correlation + matrix. + + Returns + ------- + rvs : ndarray or scalar + Random size N-dimensional matrices, dimension (size, dim, dim), + each having eigenvalues eigs. + + Notes + ----- + + Generates a random correlation matrix following a numerically stable + algorithm spelled out by Davies & Higham. This algorithm uses a single O(N) + similarity transformation to construct a symmetric positive semi-definite + matrix, and applies a series of Givens rotations to scale it to have ones + on the diagonal. + + References + ---------- + + .. [1] Davies, Philip I; Higham, Nicholas J; "Numerically stable generation + of correlation matrices and their factors", BIT 2000, Vol. 40, + No. 4, pp. 640 651 + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import random_correlation + >>> rng = np.random.default_rng() + >>> x = random_correlation.rvs((.5, .8, 1.2, 1.5), random_state=rng) + >>> x + array([[ 1. , -0.02423399, 0.03130519, 0.4946965 ], + [-0.02423399, 1. , 0.20334736, 0.04039817], + [ 0.03130519, 0.20334736, 1. , 0.02694275], + [ 0.4946965 , 0.04039817, 0.02694275, 1. ]]) + >>> import scipy.linalg + >>> e, v = scipy.linalg.eigh(x) + >>> e + array([ 0.5, 0.8, 1.2, 1.5]) + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__) + + def __call__(self, eigs, seed=None, tol=1e-13, diag_tol=1e-7): + """Create a frozen random correlation matrix. + + See `random_correlation_frozen` for more information. + """ + return random_correlation_frozen(eigs, seed=seed, tol=tol, + diag_tol=diag_tol) + + def _process_parameters(self, eigs, tol): + eigs = np.asarray(eigs, dtype=float) + dim = eigs.size + + if eigs.ndim != 1 or eigs.shape[0] != dim or dim <= 1: + raise ValueError("Array 'eigs' must be a vector of length " + "greater than 1.") + + if np.fabs(np.sum(eigs) - dim) > tol: + raise ValueError("Sum of eigenvalues must equal dimensionality.") + + for x in eigs: + if x < -tol: + raise ValueError("All eigenvalues must be non-negative.") + + return dim, eigs + + def _givens_to_1(self, aii, ajj, aij): + """Computes a 2x2 Givens matrix to put 1's on the diagonal. + + The input matrix is a 2x2 symmetric matrix M = [ aii aij ; aij ajj ]. + + The output matrix g is a 2x2 anti-symmetric matrix of the form + [ c s ; -s c ]; the elements c and s are returned. + + Applying the output matrix to the input matrix (as b=g.T M g) + results in a matrix with bii=1, provided tr(M) - det(M) >= 1 + and floating point issues do not occur. Otherwise, some other + valid rotation is returned. When tr(M)==2, also bjj=1. + + """ + aiid = aii - 1. + ajjd = ajj - 1. + + if ajjd == 0: + # ajj==1, so swap aii and ajj to avoid division by zero + return 0., 1. + + dd = math.sqrt(max(aij**2 - aiid*ajjd, 0)) + + # The choice of t should be chosen to avoid cancellation [1] + t = (aij + math.copysign(dd, aij)) / ajjd + c = 1. / math.sqrt(1. + t*t) + if c == 0: + # Underflow + s = 1.0 + else: + s = c*t + return c, s + + def _to_corr(self, m): + """ + Given a psd matrix m, rotate to put one's on the diagonal, turning it + into a correlation matrix. This also requires the trace equal the + dimensionality. Note: modifies input matrix + """ + # Check requirements for in-place Givens + if not (m.flags.c_contiguous and m.dtype == np.float64 and + m.shape[0] == m.shape[1]): + raise ValueError() + + d = m.shape[0] + for i in range(d-1): + if m[i, i] == 1: + continue + elif m[i, i] > 1: + for j in range(i+1, d): + if m[j, j] < 1: + break + else: + for j in range(i+1, d): + if m[j, j] > 1: + break + + c, s = self._givens_to_1(m[i, i], m[j, j], m[i, j]) + + # Use BLAS to apply Givens rotations in-place. Equivalent to: + # g = np.eye(d) + # g[i, i] = g[j,j] = c + # g[j, i] = -s; g[i, j] = s + # m = np.dot(g.T, np.dot(m, g)) + mv = m.ravel() + drot(mv, mv, c, -s, n=d, + offx=i*d, incx=1, offy=j*d, incy=1, + overwrite_x=True, overwrite_y=True) + drot(mv, mv, c, -s, n=d, + offx=i, incx=d, offy=j, incy=d, + overwrite_x=True, overwrite_y=True) + + return m + + def rvs(self, eigs, random_state=None, tol=1e-13, diag_tol=1e-7): + """Draw random correlation matrices. + + Parameters + ---------- + eigs : 1d ndarray + Eigenvalues of correlation matrix + tol : float, optional + Tolerance for input parameter checks + diag_tol : float, optional + Tolerance for deviation of the diagonal of the resulting + matrix. Default: 1e-7 + + Raises + ------ + RuntimeError + Floating point error prevented generating a valid correlation + matrix. + + Returns + ------- + rvs : ndarray or scalar + Random size N-dimensional matrices, dimension (size, dim, dim), + each having eigenvalues eigs. + + """ + dim, eigs = self._process_parameters(eigs, tol=tol) + + random_state = self._get_random_state(random_state) + + m = ortho_group.rvs(dim, random_state=random_state) + m = np.dot(np.dot(m, np.diag(eigs)), m.T) # Set the trace of m + m = self._to_corr(m) # Carefully rotate to unit diagonal + + # Check diagonal + if abs(m.diagonal() - 1).max() > diag_tol: + raise RuntimeError("Failed to generate a valid correlation matrix") + + return m + + +random_correlation = random_correlation_gen() + + +class random_correlation_frozen(multi_rv_frozen): + def __init__(self, eigs, seed=None, tol=1e-13, diag_tol=1e-7): + """Create a frozen random correlation matrix distribution. + + Parameters + ---------- + eigs : 1d ndarray + Eigenvalues of correlation matrix + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + tol : float, optional + Tolerance for input parameter checks + diag_tol : float, optional + Tolerance for deviation of the diagonal of the resulting + matrix. Default: 1e-7 + + Raises + ------ + RuntimeError + Floating point error prevented generating a valid correlation + matrix. + + Returns + ------- + rvs : ndarray or scalar + Random size N-dimensional matrices, dimension (size, dim, dim), + each having eigenvalues eigs. + """ # numpy/numpydoc#87 # noqa: E501 + + self._dist = random_correlation_gen(seed) + self.tol = tol + self.diag_tol = diag_tol + _, self.eigs = self._dist._process_parameters(eigs, tol=self.tol) + + def rvs(self, random_state=None): + return self._dist.rvs(self.eigs, random_state=random_state, + tol=self.tol, diag_tol=self.diag_tol) + + +class unitary_group_gen(multi_rv_generic): + r"""A matrix-valued U(N) random variable. + + Return a random unitary matrix. + + The `dim` keyword specifies the dimension N. + + Methods + ------- + rvs(dim=None, size=1, random_state=None) + Draw random samples from U(N). + + Parameters + ---------- + dim : scalar + Dimension of matrices, must be greater than 1. + seed : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + Notes + ----- + This class is similar to `ortho_group`. + + References + ---------- + .. [1] F. Mezzadri, "How to generate random matrices from the classical + compact groups", :arXiv:`math-ph/0609050v2`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import unitary_group + >>> x = unitary_group.rvs(3) + + >>> np.dot(x, x.conj().T) + array([[ 1.00000000e+00, 1.13231364e-17, -2.86852790e-16], + [ 1.13231364e-17, 1.00000000e+00, -1.46845020e-16], + [ -2.86852790e-16, -1.46845020e-16, 1.00000000e+00]]) # may vary + + This generates one random matrix from U(3). The dot product confirms that + it is unitary up to machine precision. + + Alternatively, the object may be called (as a function) to fix the `dim` + parameter, return a "frozen" unitary_group random variable: + + >>> rv = unitary_group(5) + + See Also + -------- + ortho_group + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__) + + def __call__(self, dim=None, seed=None): + """Create a frozen (U(N)) n-dimensional unitary matrix distribution. + + See `unitary_group_frozen` for more information. + """ + return unitary_group_frozen(dim, seed=seed) + + def _process_parameters(self, dim): + """Dimension N must be specified; it cannot be inferred.""" + if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim): + raise ValueError("Dimension of rotation must be specified," + "and must be a scalar greater than 1.") + + return dim + + def rvs(self, dim, size=1, random_state=None): + """Draw random samples from U(N). + + Parameters + ---------- + dim : integer + Dimension of space (N). + size : integer, optional + Number of samples to draw (default 1). + + Returns + ------- + rvs : ndarray or scalar + Random size N-dimensional matrices, dimension (size, dim, dim) + + """ + random_state = self._get_random_state(random_state) + + size = int(size) + + dim = self._process_parameters(dim) + + size = (size,) if size > 1 else () + z = 1/math.sqrt(2)*(random_state.normal(size=size + (dim, dim)) + + 1j*random_state.normal(size=size + (dim, dim))) + q, r = np.linalg.qr(z) + # The last two dimensions are the rows and columns of R matrices. + # Extract the diagonals. Note that this eliminates a dimension. + d = r.diagonal(offset=0, axis1=-2, axis2=-1) + # Add back a dimension for proper broadcasting: we're dividing + # each row of each R matrix by the diagonal of the R matrix. + q *= (d/abs(d))[..., np.newaxis, :] # to broadcast properly + return q + + +unitary_group = unitary_group_gen() + + +class unitary_group_frozen(multi_rv_frozen): + def __init__(self, dim=None, seed=None): + """Create a frozen (U(N)) n-dimensional unitary matrix distribution. + + Parameters + ---------- + dim : scalar + Dimension of matrices + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + Examples + -------- + >>> from scipy.stats import unitary_group + >>> x = unitary_group(3) + >>> x.rvs() + + """ # numpy/numpydoc#87 # noqa: E501 + self._dist = unitary_group_gen(seed) + self.dim = self._dist._process_parameters(dim) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.dim, size, random_state) + + +_mvt_doc_default_callparams = """\ +loc : array_like, optional + Location of the distribution. (default ``0``) +shape : array_like, optional + Positive semidefinite matrix of the distribution. (default ``1``) +df : float, optional + Degrees of freedom of the distribution; must be greater than zero. + If ``np.inf`` then results are multivariate normal. The default is ``1``. +allow_singular : bool, optional + Whether to allow a singular matrix. (default ``False``) +""" + +_mvt_doc_callparams_note = """\ +Setting the parameter `loc` to ``None`` is equivalent to having `loc` +be the zero-vector. The parameter `shape` can be a scalar, in which case +the shape matrix is the identity times that value, a vector of +diagonal entries for the shape matrix, or a two-dimensional array_like. +""" + +_mvt_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +mvt_docdict_params = { + '_mvt_doc_default_callparams': _mvt_doc_default_callparams, + '_mvt_doc_callparams_note': _mvt_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +mvt_docdict_noparams = { + '_mvt_doc_default_callparams': "", + '_mvt_doc_callparams_note': _mvt_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class multivariate_t_gen(multi_rv_generic): + r"""A multivariate t-distributed random variable. + + The `loc` parameter specifies the location. The `shape` parameter specifies + the positive semidefinite shape matrix. The `df` parameter specifies the + degrees of freedom. + + In addition to calling the methods below, the object itself may be called + as a function to fix the location, shape matrix, and degrees of freedom + parameters, returning a "frozen" multivariate t-distribution random. + + Methods + ------- + pdf(x, loc=None, shape=1, df=1, allow_singular=False) + Probability density function. + logpdf(x, loc=None, shape=1, df=1, allow_singular=False) + Log of the probability density function. + cdf(x, loc=None, shape=1, df=1, allow_singular=False, *, + maxpts=None, lower_limit=None, random_state=None) + Cumulative distribution function. + rvs(loc=None, shape=1, df=1, size=1, random_state=None) + Draw random samples from a multivariate t-distribution. + entropy(loc=None, shape=1, df=1) + Differential entropy of a multivariate t-distribution. + + Parameters + ---------- + %(_mvt_doc_default_callparams)s + %(_doc_random_state)s + + Notes + ----- + %(_mvt_doc_callparams_note)s + The matrix `shape` must be a (symmetric) positive semidefinite matrix. The + determinant and inverse of `shape` are computed as the pseudo-determinant + and pseudo-inverse, respectively, so that `shape` does not need to have + full rank. + + The probability density function for `multivariate_t` is + + .. math:: + + f(x) = \frac{\Gamma((\nu + p)/2)}{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}|\Sigma|^{1/2}} + \left[1 + \frac{1}{\nu} (\mathbf{x} - \boldsymbol{\mu})^{\top} + \boldsymbol{\Sigma}^{-1} + (\mathbf{x} - \boldsymbol{\mu}) \right]^{-(\nu + p)/2}, + + where :math:`p` is the dimension of :math:`\mathbf{x}`, + :math:`\boldsymbol{\mu}` is the :math:`p`-dimensional location, + :math:`\boldsymbol{\Sigma}` the :math:`p \times p`-dimensional shape + matrix, and :math:`\nu` is the degrees of freedom. + + .. versionadded:: 1.6.0 + + References + ---------- + .. [1] Arellano-Valle et al. "Shannon Entropy and Mutual Information for + Multivariate Skew-Elliptical Distributions". Scandinavian Journal + of Statistics. Vol. 40, issue 1. + + Examples + -------- + The object may be called (as a function) to fix the `loc`, `shape`, + `df`, and `allow_singular` parameters, returning a "frozen" + multivariate_t random variable: + + >>> import numpy as np + >>> from scipy.stats import multivariate_t + >>> rv = multivariate_t([1.0, -0.5], [[2.1, 0.3], [0.3, 1.5]], df=2) + >>> # Frozen object with the same methods but holding the given location, + >>> # scale, and degrees of freedom fixed. + + Create a contour plot of the PDF. + + >>> import matplotlib.pyplot as plt + >>> x, y = np.mgrid[-1:3:.01, -2:1.5:.01] + >>> pos = np.dstack((x, y)) + >>> fig, ax = plt.subplots(1, 1) + >>> ax.set_aspect('equal') + >>> plt.contourf(x, y, rv.pdf(pos)) + + """ + + def __init__(self, seed=None): + """Initialize a multivariate t-distributed random variable. + + Parameters + ---------- + seed : Random state. + + """ + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, mvt_docdict_params) + self._random_state = check_random_state(seed) + + def __call__(self, loc=None, shape=1, df=1, allow_singular=False, + seed=None): + """Create a frozen multivariate t-distribution. + + See `multivariate_t_frozen` for parameters. + """ + if df == np.inf: + return multivariate_normal_frozen(mean=loc, cov=shape, + allow_singular=allow_singular, + seed=seed) + return multivariate_t_frozen(loc=loc, shape=shape, df=df, + allow_singular=allow_singular, seed=seed) + + def pdf(self, x, loc=None, shape=1, df=1, allow_singular=False): + """Multivariate t-distribution probability density function. + + Parameters + ---------- + x : array_like + Points at which to evaluate the probability density function. + %(_mvt_doc_default_callparams)s + + Returns + ------- + pdf : Probability density function evaluated at `x`. + + Examples + -------- + >>> from scipy.stats import multivariate_t + >>> x = [0.4, 5] + >>> loc = [0, 1] + >>> shape = [[1, 0.1], [0.1, 1]] + >>> df = 7 + >>> multivariate_t.pdf(x, loc, shape, df) + 0.00075713 + + """ + dim, loc, shape, df = self._process_parameters(loc, shape, df) + x = self._process_quantiles(x, dim) + shape_info = _PSD(shape, allow_singular=allow_singular) + logpdf = self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, + dim, shape_info.rank) + return np.exp(logpdf) + + def logpdf(self, x, loc=None, shape=1, df=1): + """Log of the multivariate t-distribution probability density function. + + Parameters + ---------- + x : array_like + Points at which to evaluate the log of the probability density + function. + %(_mvt_doc_default_callparams)s + + Returns + ------- + logpdf : Log of the probability density function evaluated at `x`. + + Examples + -------- + >>> from scipy.stats import multivariate_t + >>> x = [0.4, 5] + >>> loc = [0, 1] + >>> shape = [[1, 0.1], [0.1, 1]] + >>> df = 7 + >>> multivariate_t.logpdf(x, loc, shape, df) + -7.1859802 + + See Also + -------- + pdf : Probability density function. + + """ + dim, loc, shape, df = self._process_parameters(loc, shape, df) + x = self._process_quantiles(x, dim) + shape_info = _PSD(shape) + return self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, dim, + shape_info.rank) + + def _logpdf(self, x, loc, prec_U, log_pdet, df, dim, rank): + """Utility method `pdf`, `logpdf` for parameters. + + Parameters + ---------- + x : ndarray + Points at which to evaluate the log of the probability density + function. + loc : ndarray + Location of the distribution. + prec_U : ndarray + A decomposition such that `np.dot(prec_U, prec_U.T)` is the inverse + of the shape matrix. + log_pdet : float + Logarithm of the determinant of the shape matrix. + df : float + Degrees of freedom of the distribution. + dim : int + Dimension of the quantiles x. + rank : int + Rank of the shape matrix. + + Notes + ----- + As this function does no argument checking, it should not be called + directly; use 'logpdf' instead. + + """ + if df == np.inf: + return multivariate_normal._logpdf(x, loc, prec_U, log_pdet, rank) + + dev = x - loc + maha = np.square(np.dot(dev, prec_U)).sum(axis=-1) + + t = 0.5 * (df + dim) + A = gammaln(t) + B = gammaln(0.5 * df) + C = dim/2. * np.log(df * np.pi) + D = 0.5 * log_pdet + E = -t * np.log(1 + (1./df) * maha) + + return _squeeze_output(A - B - C - D + E) + + def _cdf(self, x, loc, shape, df, dim, maxpts=None, lower_limit=None, + random_state=None): + + # All of this - random state validation, maxpts, apply_along_axis, + # etc. needs to go in this private method unless we want + # frozen distribution's `cdf` method to duplicate it or call `cdf`, + # which would require re-processing parameters + if random_state is not None: + rng = check_random_state(random_state) + else: + rng = self._random_state + + if not maxpts: + maxpts = 1000 * dim + + x = self._process_quantiles(x, dim) + lower_limit = (np.full(loc.shape, -np.inf) + if lower_limit is None else lower_limit) + + # remove the mean + x, lower_limit = x - loc, lower_limit - loc + + b, a = np.broadcast_arrays(x, lower_limit) + i_swap = b < a + signs = (-1)**(i_swap.sum(axis=-1)) # odd # of swaps -> negative + a, b = a.copy(), b.copy() + a[i_swap], b[i_swap] = b[i_swap], a[i_swap] + n = x.shape[-1] + limits = np.concatenate((a, b), axis=-1) + + def func1d(limits): + a, b = limits[:n], limits[n:] + return _qmvt(maxpts, df, shape, a, b, rng)[0] + + res = np.apply_along_axis(func1d, -1, limits) * signs + # Fixing the output shape for existing distributions is a separate + # issue. For now, let's keep this consistent with pdf. + return _squeeze_output(res) + + def cdf(self, x, loc=None, shape=1, df=1, allow_singular=False, *, + maxpts=None, lower_limit=None, random_state=None): + """Multivariate t-distribution cumulative distribution function. + + Parameters + ---------- + x : array_like + Points at which to evaluate the cumulative distribution function. + %(_mvt_doc_default_callparams)s + maxpts : int, optional + Maximum number of points to use for integration. The default is + 1000 times the number of dimensions. + lower_limit : array_like, optional + Lower limit of integration of the cumulative distribution function. + Default is negative infinity. Must be broadcastable with `x`. + %(_doc_random_state)s + + Returns + ------- + cdf : ndarray or scalar + Cumulative distribution function evaluated at `x`. + + Examples + -------- + >>> from scipy.stats import multivariate_t + >>> x = [0.4, 5] + >>> loc = [0, 1] + >>> shape = [[1, 0.1], [0.1, 1]] + >>> df = 7 + >>> multivariate_t.cdf(x, loc, shape, df) + 0.64798491 + + """ + dim, loc, shape, df = self._process_parameters(loc, shape, df) + shape = _PSD(shape, allow_singular=allow_singular)._M + + return self._cdf(x, loc, shape, df, dim, maxpts, + lower_limit, random_state) + + def _entropy(self, dim, df=1, shape=1): + if df == np.inf: + return multivariate_normal(None, cov=shape).entropy() + + shape_info = _PSD(shape) + shape_term = 0.5 * shape_info.log_pdet + + def regular(dim, df): + halfsum = 0.5 * (dim + df) + half_df = 0.5 * df + return ( + -gammaln(halfsum) + gammaln(half_df) + + 0.5 * dim * np.log(df * np.pi) + halfsum + * (psi(halfsum) - psi(half_df)) + + shape_term + ) + + def asymptotic(dim, df): + # Formula from Wolfram Alpha: + # "asymptotic expansion -gammaln((m+d)/2) + gammaln(d/2) + (m*log(d*pi))/2 + # + ((m+d)/2) * (digamma((m+d)/2) - digamma(d/2))" + return ( + dim * norm._entropy() + dim / df + - dim * (dim - 2) * df**-2.0 / 4 + + dim**2 * (dim - 2) * df**-3.0 / 6 + + dim * (-3 * dim**3 + 8 * dim**2 - 8) * df**-4.0 / 24 + + dim**2 * (3 * dim**3 - 10 * dim**2 + 16) * df**-5.0 / 30 + + shape_term + )[()] + + # preserves ~12 digits accuracy up to at least `dim=1e5`. See gh-18465. + threshold = dim * 100 * 4 / (np.log(dim) + 1) + return _lazywhere(df >= threshold, (dim, df), f=asymptotic, f2=regular) + + def entropy(self, loc=None, shape=1, df=1): + """Calculate the differential entropy of a multivariate + t-distribution. + + Parameters + ---------- + %(_mvt_doc_default_callparams)s + + Returns + ------- + h : float + Differential entropy + + """ + dim, loc, shape, df = self._process_parameters(None, shape, df) + return self._entropy(dim, df, shape) + + def rvs(self, loc=None, shape=1, df=1, size=1, random_state=None): + """Draw random samples from a multivariate t-distribution. + + Parameters + ---------- + %(_mvt_doc_default_callparams)s + size : integer, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray or scalar + Random variates of size (`size`, `P`), where `P` is the + dimension of the random variable. + + Examples + -------- + >>> from scipy.stats import multivariate_t + >>> x = [0.4, 5] + >>> loc = [0, 1] + >>> shape = [[1, 0.1], [0.1, 1]] + >>> df = 7 + >>> multivariate_t.rvs(loc, shape, df) + array([[0.93477495, 3.00408716]]) + + """ + # For implementation details, see equation (3): + # + # Hofert, "On Sampling from the Multivariatet Distribution", 2013 + # http://rjournal.github.io/archive/2013-2/hofert.pdf + # + dim, loc, shape, df = self._process_parameters(loc, shape, df) + if random_state is not None: + rng = check_random_state(random_state) + else: + rng = self._random_state + + if np.isinf(df): + x = np.ones(size) + else: + x = rng.chisquare(df, size=size) / df + + z = rng.multivariate_normal(np.zeros(dim), shape, size=size) + samples = loc + z / np.sqrt(x)[..., None] + return _squeeze_output(samples) + + def _process_quantiles(self, x, dim): + """ + Adjust quantiles array so that last axis labels the components of + each data point. + """ + x = np.asarray(x, dtype=float) + if x.ndim == 0: + x = x[np.newaxis] + elif x.ndim == 1: + if dim == 1: + x = x[:, np.newaxis] + else: + x = x[np.newaxis, :] + return x + + def _process_parameters(self, loc, shape, df): + """ + Infer dimensionality from location array and shape matrix, handle + defaults, and ensure compatible dimensions. + """ + if loc is None and shape is None: + loc = np.asarray(0, dtype=float) + shape = np.asarray(1, dtype=float) + dim = 1 + elif loc is None: + shape = np.asarray(shape, dtype=float) + if shape.ndim < 2: + dim = 1 + else: + dim = shape.shape[0] + loc = np.zeros(dim) + elif shape is None: + loc = np.asarray(loc, dtype=float) + dim = loc.size + shape = np.eye(dim) + else: + shape = np.asarray(shape, dtype=float) + loc = np.asarray(loc, dtype=float) + dim = loc.size + + if dim == 1: + loc = loc.reshape(1) + shape = shape.reshape(1, 1) + + if loc.ndim != 1 or loc.shape[0] != dim: + raise ValueError("Array 'loc' must be a vector of length %d." % + dim) + if shape.ndim == 0: + shape = shape * np.eye(dim) + elif shape.ndim == 1: + shape = np.diag(shape) + elif shape.ndim == 2 and shape.shape != (dim, dim): + rows, cols = shape.shape + if rows != cols: + msg = ("Array 'cov' must be square if it is two dimensional," + f" but cov.shape = {str(shape.shape)}.") + else: + msg = ("Dimension mismatch: array 'cov' is of shape %s," + " but 'loc' is a vector of length %d.") + msg = msg % (str(shape.shape), len(loc)) + raise ValueError(msg) + elif shape.ndim > 2: + raise ValueError("Array 'cov' must be at most two-dimensional," + " but cov.ndim = %d" % shape.ndim) + + # Process degrees of freedom. + if df is None: + df = 1 + elif df <= 0: + raise ValueError("'df' must be greater than zero.") + elif np.isnan(df): + raise ValueError("'df' is 'nan' but must be greater than zero or 'np.inf'.") + + return dim, loc, shape, df + + +class multivariate_t_frozen(multi_rv_frozen): + + def __init__(self, loc=None, shape=1, df=1, allow_singular=False, + seed=None): + """Create a frozen multivariate t distribution. + + Parameters + ---------- + %(_mvt_doc_default_callparams)s + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import multivariate_t + >>> loc = np.zeros(3) + >>> shape = np.eye(3) + >>> df = 10 + >>> dist = multivariate_t(loc, shape, df) + >>> dist.rvs() + array([[ 0.81412036, -1.53612361, 0.42199647]]) + >>> dist.pdf([1, 1, 1]) + array([0.01237803]) + + """ + self._dist = multivariate_t_gen(seed) + dim, loc, shape, df = self._dist._process_parameters(loc, shape, df) + self.dim, self.loc, self.shape, self.df = dim, loc, shape, df + self.shape_info = _PSD(shape, allow_singular=allow_singular) + + def logpdf(self, x): + x = self._dist._process_quantiles(x, self.dim) + U = self.shape_info.U + log_pdet = self.shape_info.log_pdet + return self._dist._logpdf(x, self.loc, U, log_pdet, self.df, self.dim, + self.shape_info.rank) + + def cdf(self, x, *, maxpts=None, lower_limit=None, random_state=None): + x = self._dist._process_quantiles(x, self.dim) + return self._dist._cdf(x, self.loc, self.shape, self.df, self.dim, + maxpts, lower_limit, random_state) + + def pdf(self, x): + return np.exp(self.logpdf(x)) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(loc=self.loc, + shape=self.shape, + df=self.df, + size=size, + random_state=random_state) + + def entropy(self): + return self._dist._entropy(self.dim, self.df, self.shape) + + +multivariate_t = multivariate_t_gen() + + +# Set frozen generator docstrings from corresponding docstrings in +# multivariate_t_gen and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'rvs', 'cdf', 'entropy']: + method = multivariate_t_gen.__dict__[name] + method_frozen = multivariate_t_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat(method.__doc__, + mvt_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, mvt_docdict_params) + + +_mhg_doc_default_callparams = """\ +m : array_like + The number of each type of object in the population. + That is, :math:`m[i]` is the number of objects of + type :math:`i`. +n : array_like + The number of samples taken from the population. +""" + +_mhg_doc_callparams_note = """\ +`m` must be an array of positive integers. If the quantile +:math:`i` contains values out of the range :math:`[0, m_i]` +where :math:`m_i` is the number of objects of type :math:`i` +in the population or if the parameters are inconsistent with one +another (e.g. ``x.sum() != n``), methods return the appropriate +value (e.g. ``0`` for ``pmf``). If `m` or `n` contain negative +values, the result will contain ``nan`` there. +""" + +_mhg_doc_frozen_callparams = "" + +_mhg_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +mhg_docdict_params = { + '_doc_default_callparams': _mhg_doc_default_callparams, + '_doc_callparams_note': _mhg_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +mhg_docdict_noparams = { + '_doc_default_callparams': _mhg_doc_frozen_callparams, + '_doc_callparams_note': _mhg_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class multivariate_hypergeom_gen(multi_rv_generic): + r"""A multivariate hypergeometric random variable. + + Methods + ------- + pmf(x, m, n) + Probability mass function. + logpmf(x, m, n) + Log of the probability mass function. + rvs(m, n, size=1, random_state=None) + Draw random samples from a multivariate hypergeometric + distribution. + mean(m, n) + Mean of the multivariate hypergeometric distribution. + var(m, n) + Variance of the multivariate hypergeometric distribution. + cov(m, n) + Compute the covariance matrix of the multivariate + hypergeometric distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + %(_doc_random_state)s + + Notes + ----- + %(_doc_callparams_note)s + + The probability mass function for `multivariate_hypergeom` is + + .. math:: + + P(X_1 = x_1, X_2 = x_2, \ldots, X_k = x_k) = \frac{\binom{m_1}{x_1} + \binom{m_2}{x_2} \cdots \binom{m_k}{x_k}}{\binom{M}{n}}, \\ \quad + (x_1, x_2, \ldots, x_k) \in \mathbb{N}^k \text{ with } + \sum_{i=1}^k x_i = n + + where :math:`m_i` are the number of objects of type :math:`i`, :math:`M` + is the total number of objects in the population (sum of all the + :math:`m_i`), and :math:`n` is the size of the sample to be taken + from the population. + + .. versionadded:: 1.6.0 + + Examples + -------- + To evaluate the probability mass function of the multivariate + hypergeometric distribution, with a dichotomous population of size + :math:`10` and :math:`20`, at a sample of size :math:`12` with + :math:`8` objects of the first type and :math:`4` objects of the + second type, use: + + >>> from scipy.stats import multivariate_hypergeom + >>> multivariate_hypergeom.pmf(x=[8, 4], m=[10, 20], n=12) + 0.0025207176631464523 + + The `multivariate_hypergeom` distribution is identical to the + corresponding `hypergeom` distribution (tiny numerical differences + notwithstanding) when only two types (good and bad) of objects + are present in the population as in the example above. Consider + another example for a comparison with the hypergeometric distribution: + + >>> from scipy.stats import hypergeom + >>> multivariate_hypergeom.pmf(x=[3, 1], m=[10, 5], n=4) + 0.4395604395604395 + >>> hypergeom.pmf(k=3, M=15, n=4, N=10) + 0.43956043956044005 + + The functions ``pmf``, ``logpmf``, ``mean``, ``var``, ``cov``, and ``rvs`` + support broadcasting, under the convention that the vector parameters + (``x``, ``m``, and ``n``) are interpreted as if each row along the last + axis is a single object. For instance, we can combine the previous two + calls to `multivariate_hypergeom` as + + >>> multivariate_hypergeom.pmf(x=[[8, 4], [3, 1]], m=[[10, 20], [10, 5]], + ... n=[12, 4]) + array([0.00252072, 0.43956044]) + + This broadcasting also works for ``cov``, where the output objects are + square matrices of size ``m.shape[-1]``. For example: + + >>> multivariate_hypergeom.cov(m=[[7, 9], [10, 15]], n=[8, 12]) + array([[[ 1.05, -1.05], + [-1.05, 1.05]], + [[ 1.56, -1.56], + [-1.56, 1.56]]]) + + That is, ``result[0]`` is equal to + ``multivariate_hypergeom.cov(m=[7, 9], n=8)`` and ``result[1]`` is equal + to ``multivariate_hypergeom.cov(m=[10, 15], n=12)``. + + Alternatively, the object may be called (as a function) to fix the `m` + and `n` parameters, returning a "frozen" multivariate hypergeometric + random variable. + + >>> rv = multivariate_hypergeom(m=[10, 20], n=12) + >>> rv.pmf(x=[8, 4]) + 0.0025207176631464523 + + See Also + -------- + scipy.stats.hypergeom : The hypergeometric distribution. + scipy.stats.multinomial : The multinomial distribution. + + References + ---------- + .. [1] The Multivariate Hypergeometric Distribution, + http://www.randomservices.org/random/urn/MultiHypergeometric.html + .. [2] Thomas J. Sargent and John Stachurski, 2020, + Multivariate Hypergeometric Distribution + https://python.quantecon.org/multi_hyper.html + """ + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, mhg_docdict_params) + + def __call__(self, m, n, seed=None): + """Create a frozen multivariate_hypergeom distribution. + + See `multivariate_hypergeom_frozen` for more information. + """ + return multivariate_hypergeom_frozen(m, n, seed=seed) + + def _process_parameters(self, m, n): + m = np.asarray(m) + n = np.asarray(n) + if m.size == 0: + m = m.astype(int) + if n.size == 0: + n = n.astype(int) + if not np.issubdtype(m.dtype, np.integer): + raise TypeError("'m' must an array of integers.") + if not np.issubdtype(n.dtype, np.integer): + raise TypeError("'n' must an array of integers.") + if m.ndim == 0: + raise ValueError("'m' must be an array with" + " at least one dimension.") + + # check for empty arrays + if m.size != 0: + n = n[..., np.newaxis] + + m, n = np.broadcast_arrays(m, n) + + # check for empty arrays + if m.size != 0: + n = n[..., 0] + + mcond = m < 0 + + M = m.sum(axis=-1) + + ncond = (n < 0) | (n > M) + return M, m, n, mcond, ncond, np.any(mcond, axis=-1) | ncond + + def _process_quantiles(self, x, M, m, n): + x = np.asarray(x) + if not np.issubdtype(x.dtype, np.integer): + raise TypeError("'x' must an array of integers.") + if x.ndim == 0: + raise ValueError("'x' must be an array with" + " at least one dimension.") + if not x.shape[-1] == m.shape[-1]: + raise ValueError(f"Size of each quantile must be size of 'm': " + f"received {x.shape[-1]}, " + f"but expected {m.shape[-1]}.") + + # check for empty arrays + if m.size != 0: + n = n[..., np.newaxis] + M = M[..., np.newaxis] + + x, m, n, M = np.broadcast_arrays(x, m, n, M) + + # check for empty arrays + if m.size != 0: + n, M = n[..., 0], M[..., 0] + + xcond = (x < 0) | (x > m) + return (x, M, m, n, xcond, + np.any(xcond, axis=-1) | (x.sum(axis=-1) != n)) + + def _checkresult(self, result, cond, bad_value): + result = np.asarray(result) + if cond.ndim != 0: + result[cond] = bad_value + elif cond: + return bad_value + if result.ndim == 0: + return result[()] + return result + + def _logpmf(self, x, M, m, n, mxcond, ncond): + # This equation of the pmf comes from the relation, + # n combine r = beta(n+1, 1) / beta(r+1, n-r+1) + num = np.zeros_like(m, dtype=np.float64) + den = np.zeros_like(n, dtype=np.float64) + m, x = m[~mxcond], x[~mxcond] + M, n = M[~ncond], n[~ncond] + num[~mxcond] = (betaln(m+1, 1) - betaln(x+1, m-x+1)) + den[~ncond] = (betaln(M+1, 1) - betaln(n+1, M-n+1)) + num[mxcond] = np.nan + den[ncond] = np.nan + num = num.sum(axis=-1) + return num - den + + def logpmf(self, x, m, n): + """Log of the multivariate hypergeometric probability mass function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_doc_default_callparams)s + + Returns + ------- + logpmf : ndarray or scalar + Log of the probability mass function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + """ + M, m, n, mcond, ncond, mncond = self._process_parameters(m, n) + (x, M, m, n, xcond, + xcond_reduced) = self._process_quantiles(x, M, m, n) + mxcond = mcond | xcond + ncond = ncond | np.zeros(n.shape, dtype=np.bool_) + + result = self._logpmf(x, M, m, n, mxcond, ncond) + + # replace values for which x was out of the domain; broadcast + # xcond to the right shape + xcond_ = xcond_reduced | np.zeros(mncond.shape, dtype=np.bool_) + result = self._checkresult(result, xcond_, -np.inf) + + # replace values bad for n or m; broadcast + # mncond to the right shape + mncond_ = mncond | np.zeros(xcond_reduced.shape, dtype=np.bool_) + return self._checkresult(result, mncond_, np.nan) + + def pmf(self, x, m, n): + """Multivariate hypergeometric probability mass function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_doc_default_callparams)s + + Returns + ------- + pmf : ndarray or scalar + Probability density function evaluated at `x` + + Notes + ----- + %(_doc_callparams_note)s + """ + out = np.exp(self.logpmf(x, m, n)) + return out + + def mean(self, m, n): + """Mean of the multivariate hypergeometric distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + mean : array_like or scalar + The mean of the distribution + """ + M, m, n, _, _, mncond = self._process_parameters(m, n) + # check for empty arrays + if m.size != 0: + M, n = M[..., np.newaxis], n[..., np.newaxis] + cond = (M == 0) + M = np.ma.masked_array(M, mask=cond) + mu = n*(m/M) + if m.size != 0: + mncond = (mncond[..., np.newaxis] | + np.zeros(mu.shape, dtype=np.bool_)) + return self._checkresult(mu, mncond, np.nan) + + def var(self, m, n): + """Variance of the multivariate hypergeometric distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + array_like + The variances of the components of the distribution. This is + the diagonal of the covariance matrix of the distribution + """ + M, m, n, _, _, mncond = self._process_parameters(m, n) + # check for empty arrays + if m.size != 0: + M, n = M[..., np.newaxis], n[..., np.newaxis] + cond = (M == 0) & (M-1 == 0) + M = np.ma.masked_array(M, mask=cond) + output = n * m/M * (M-m)/M * (M-n)/(M-1) + if m.size != 0: + mncond = (mncond[..., np.newaxis] | + np.zeros(output.shape, dtype=np.bool_)) + return self._checkresult(output, mncond, np.nan) + + def cov(self, m, n): + """Covariance matrix of the multivariate hypergeometric distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + + Returns + ------- + cov : array_like + The covariance matrix of the distribution + """ + # see [1]_ for the formula and [2]_ for implementation + # cov( x_i,x_j ) = -n * (M-n)/(M-1) * (K_i*K_j) / (M**2) + M, m, n, _, _, mncond = self._process_parameters(m, n) + # check for empty arrays + if m.size != 0: + M = M[..., np.newaxis, np.newaxis] + n = n[..., np.newaxis, np.newaxis] + cond = (M == 0) & (M-1 == 0) + M = np.ma.masked_array(M, mask=cond) + output = (-n * (M-n)/(M-1) * + np.einsum("...i,...j->...ij", m, m) / (M**2)) + # check for empty arrays + if m.size != 0: + M, n = M[..., 0, 0], n[..., 0, 0] + cond = cond[..., 0, 0] + dim = m.shape[-1] + # diagonal entries need to be computed differently + for i in range(dim): + output[..., i, i] = (n * (M-n) * m[..., i]*(M-m[..., i])) + output[..., i, i] = output[..., i, i] / (M-1) + output[..., i, i] = output[..., i, i] / (M**2) + if m.size != 0: + mncond = (mncond[..., np.newaxis, np.newaxis] | + np.zeros(output.shape, dtype=np.bool_)) + return self._checkresult(output, mncond, np.nan) + + def rvs(self, m, n, size=None, random_state=None): + """Draw random samples from a multivariate hypergeometric distribution. + + Parameters + ---------- + %(_doc_default_callparams)s + size : integer or iterable of integers, optional + Number of samples to draw. Default is ``None``, in which case a + single variate is returned as an array with shape ``m.shape``. + %(_doc_random_state)s + + Returns + ------- + rvs : array_like + Random variates of shape ``size`` or ``m.shape`` + (if ``size=None``). + + Notes + ----- + %(_doc_callparams_note)s + + Also note that NumPy's `multivariate_hypergeometric` sampler is not + used as it doesn't support broadcasting. + """ + M, m, n, _, _, _ = self._process_parameters(m, n) + + random_state = self._get_random_state(random_state) + + if size is not None and isinstance(size, int): + size = (size, ) + + if size is None: + rvs = np.empty(m.shape, dtype=m.dtype) + else: + rvs = np.empty(size + (m.shape[-1], ), dtype=m.dtype) + rem = M + + # This sampler has been taken from numpy gh-13794 + # https://github.com/numpy/numpy/pull/13794 + for c in range(m.shape[-1] - 1): + rem = rem - m[..., c] + n0mask = n == 0 + rvs[..., c] = (~n0mask * + random_state.hypergeometric(m[..., c], + rem + n0mask, + n + n0mask, + size=size)) + n = n - rvs[..., c] + rvs[..., m.shape[-1] - 1] = n + + return rvs + + +multivariate_hypergeom = multivariate_hypergeom_gen() + + +class multivariate_hypergeom_frozen(multi_rv_frozen): + def __init__(self, m, n, seed=None): + self._dist = multivariate_hypergeom_gen(seed) + (self.M, self.m, self.n, + self.mcond, self.ncond, + self.mncond) = self._dist._process_parameters(m, n) + + # monkey patch self._dist + def _process_parameters(m, n): + return (self.M, self.m, self.n, + self.mcond, self.ncond, + self.mncond) + self._dist._process_parameters = _process_parameters + + def logpmf(self, x): + return self._dist.logpmf(x, self.m, self.n) + + def pmf(self, x): + return self._dist.pmf(x, self.m, self.n) + + def mean(self): + return self._dist.mean(self.m, self.n) + + def var(self): + return self._dist.var(self.m, self.n) + + def cov(self): + return self._dist.cov(self.m, self.n) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.m, self.n, + size=size, + random_state=random_state) + + +# Set frozen generator docstrings from corresponding docstrings in +# multivariate_hypergeom and fill in default strings in class docstrings +for name in ['logpmf', 'pmf', 'mean', 'var', 'cov', 'rvs']: + method = multivariate_hypergeom_gen.__dict__[name] + method_frozen = multivariate_hypergeom_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat( + method.__doc__, mhg_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, + mhg_docdict_params) + + +class random_table_gen(multi_rv_generic): + r"""Contingency tables from independent samples with fixed marginal sums. + + This is the distribution of random tables with given row and column vector + sums. This distribution represents the set of random tables under the null + hypothesis that rows and columns are independent. It is used in hypothesis + tests of independence. + + Because of assumed independence, the expected frequency of each table + element can be computed from the row and column sums, so that the + distribution is completely determined by these two vectors. + + Methods + ------- + logpmf(x) + Log-probability of table `x` to occur in the distribution. + pmf(x) + Probability of table `x` to occur in the distribution. + mean(row, col) + Mean table. + rvs(row, col, size=None, method=None, random_state=None) + Draw random tables with given row and column vector sums. + + Parameters + ---------- + %(_doc_row_col)s + %(_doc_random_state)s + + Notes + ----- + %(_doc_row_col_note)s + + Random elements from the distribution are generated either with Boyett's + [1]_ or Patefield's algorithm [2]_. Boyett's algorithm has + O(N) time and space complexity, where N is the total sum of entries in the + table. Patefield's algorithm has O(K x log(N)) time complexity, where K is + the number of cells in the table and requires only a small constant work + space. By default, the `rvs` method selects the fastest algorithm based on + the input, but you can specify the algorithm with the keyword `method`. + Allowed values are "boyett" and "patefield". + + .. versionadded:: 1.10.0 + + Examples + -------- + >>> from scipy.stats import random_table + + >>> row = [1, 5] + >>> col = [2, 3, 1] + >>> random_table.mean(row, col) + array([[0.33333333, 0.5 , 0.16666667], + [1.66666667, 2.5 , 0.83333333]]) + + Alternatively, the object may be called (as a function) to fix the row + and column vector sums, returning a "frozen" distribution. + + >>> dist = random_table(row, col) + >>> dist.rvs(random_state=123) + array([[1, 0, 0], + [1, 3, 1]]) + + References + ---------- + .. [1] J. Boyett, AS 144 Appl. Statist. 28 (1979) 329-332 + .. [2] W.M. Patefield, AS 159 Appl. Statist. 30 (1981) 91-97 + """ + + def __init__(self, seed=None): + super().__init__(seed) + + def __call__(self, row, col, *, seed=None): + """Create a frozen distribution of tables with given marginals. + + See `random_table_frozen` for more information. + """ + return random_table_frozen(row, col, seed=seed) + + def logpmf(self, x, row, col): + """Log-probability of table to occur in the distribution. + + Parameters + ---------- + %(_doc_x)s + %(_doc_row_col)s + + Returns + ------- + logpmf : ndarray or scalar + Log of the probability mass function evaluated at `x`. + + Notes + ----- + %(_doc_row_col_note)s + + If row and column marginals of `x` do not match `row` and `col`, + negative infinity is returned. + + Examples + -------- + >>> from scipy.stats import random_table + >>> import numpy as np + + >>> x = [[1, 5, 1], [2, 3, 1]] + >>> row = np.sum(x, axis=1) + >>> col = np.sum(x, axis=0) + >>> random_table.logpmf(x, row, col) + -1.6306401200847027 + + Alternatively, the object may be called (as a function) to fix the row + and column vector sums, returning a "frozen" distribution. + + >>> d = random_table(row, col) + >>> d.logpmf(x) + -1.6306401200847027 + """ + r, c, n = self._process_parameters(row, col) + x = np.asarray(x) + + if x.ndim < 2: + raise ValueError("`x` must be at least two-dimensional") + + dtype_is_int = np.issubdtype(x.dtype, np.integer) + with np.errstate(invalid='ignore'): + if not dtype_is_int and not np.all(x.astype(int) == x): + raise ValueError("`x` must contain only integral values") + + # x does not contain NaN if we arrive here + if np.any(x < 0): + raise ValueError("`x` must contain only non-negative values") + + r2 = np.sum(x, axis=-1) + c2 = np.sum(x, axis=-2) + + if r2.shape[-1] != len(r): + raise ValueError("shape of `x` must agree with `row`") + + if c2.shape[-1] != len(c): + raise ValueError("shape of `x` must agree with `col`") + + res = np.empty(x.shape[:-2]) + + mask = np.all(r2 == r, axis=-1) & np.all(c2 == c, axis=-1) + + def lnfac(x): + return gammaln(x + 1) + + res[mask] = (np.sum(lnfac(r), axis=-1) + np.sum(lnfac(c), axis=-1) + - lnfac(n) - np.sum(lnfac(x[mask]), axis=(-1, -2))) + res[~mask] = -np.inf + + return res[()] + + def pmf(self, x, row, col): + """Probability of table to occur in the distribution. + + Parameters + ---------- + %(_doc_x)s + %(_doc_row_col)s + + Returns + ------- + pmf : ndarray or scalar + Probability mass function evaluated at `x`. + + Notes + ----- + %(_doc_row_col_note)s + + If row and column marginals of `x` do not match `row` and `col`, + zero is returned. + + Examples + -------- + >>> from scipy.stats import random_table + >>> import numpy as np + + >>> x = [[1, 5, 1], [2, 3, 1]] + >>> row = np.sum(x, axis=1) + >>> col = np.sum(x, axis=0) + >>> random_table.pmf(x, row, col) + 0.19580419580419592 + + Alternatively, the object may be called (as a function) to fix the row + and column vector sums, returning a "frozen" distribution. + + >>> d = random_table(row, col) + >>> d.pmf(x) + 0.19580419580419592 + """ + return np.exp(self.logpmf(x, row, col)) + + def mean(self, row, col): + """Mean of distribution of conditional tables. + %(_doc_mean_params)s + + Returns + ------- + mean: ndarray + Mean of the distribution. + + Notes + ----- + %(_doc_row_col_note)s + + Examples + -------- + >>> from scipy.stats import random_table + + >>> row = [1, 5] + >>> col = [2, 3, 1] + >>> random_table.mean(row, col) + array([[0.33333333, 0.5 , 0.16666667], + [1.66666667, 2.5 , 0.83333333]]) + + Alternatively, the object may be called (as a function) to fix the row + and column vector sums, returning a "frozen" distribution. + + >>> d = random_table(row, col) + >>> d.mean() + array([[0.33333333, 0.5 , 0.16666667], + [1.66666667, 2.5 , 0.83333333]]) + """ + r, c, n = self._process_parameters(row, col) + return np.outer(r, c) / n + + def rvs(self, row, col, *, size=None, method=None, random_state=None): + """Draw random tables with fixed column and row marginals. + + Parameters + ---------- + %(_doc_row_col)s + size : integer, optional + Number of samples to draw (default 1). + method : str, optional + Which method to use, "boyett" or "patefield". If None (default), + selects the fastest method for this input. + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray + Random 2D tables of shape (`size`, `len(row)`, `len(col)`). + + Notes + ----- + %(_doc_row_col_note)s + + Examples + -------- + >>> from scipy.stats import random_table + + >>> row = [1, 5] + >>> col = [2, 3, 1] + >>> random_table.rvs(row, col, random_state=123) + array([[1., 0., 0.], + [1., 3., 1.]]) + + Alternatively, the object may be called (as a function) to fix the row + and column vector sums, returning a "frozen" distribution. + + >>> d = random_table(row, col) + >>> d.rvs(random_state=123) + array([[1., 0., 0.], + [1., 3., 1.]]) + """ + r, c, n = self._process_parameters(row, col) + size, shape = self._process_size_shape(size, r, c) + + random_state = self._get_random_state(random_state) + meth = self._process_rvs_method(method, r, c, n) + + return meth(r, c, n, size, random_state).reshape(shape) + + @staticmethod + def _process_parameters(row, col): + """ + Check that row and column vectors are one-dimensional, that they do + not contain negative or non-integer entries, and that the sums over + both vectors are equal. + """ + r = np.array(row, dtype=np.int64, copy=True) + c = np.array(col, dtype=np.int64, copy=True) + + if np.ndim(r) != 1: + raise ValueError("`row` must be one-dimensional") + if np.ndim(c) != 1: + raise ValueError("`col` must be one-dimensional") + + if np.any(r < 0): + raise ValueError("each element of `row` must be non-negative") + if np.any(c < 0): + raise ValueError("each element of `col` must be non-negative") + + n = np.sum(r) + if n != np.sum(c): + raise ValueError("sums over `row` and `col` must be equal") + + if not np.all(r == np.asarray(row)): + raise ValueError("each element of `row` must be an integer") + if not np.all(c == np.asarray(col)): + raise ValueError("each element of `col` must be an integer") + + return r, c, n + + @staticmethod + def _process_size_shape(size, r, c): + """ + Compute the number of samples to be drawn and the shape of the output + """ + shape = (len(r), len(c)) + + if size is None: + return 1, shape + + size = np.atleast_1d(size) + if not np.issubdtype(size.dtype, np.integer) or np.any(size < 0): + raise ValueError("`size` must be a non-negative integer or `None`") + + return np.prod(size), tuple(size) + shape + + @classmethod + def _process_rvs_method(cls, method, r, c, n): + known_methods = { + None: cls._rvs_select(r, c, n), + "boyett": cls._rvs_boyett, + "patefield": cls._rvs_patefield, + } + try: + return known_methods[method] + except KeyError: + raise ValueError(f"'{method}' not recognized, " + f"must be one of {set(known_methods)}") + + @classmethod + def _rvs_select(cls, r, c, n): + fac = 1.0 # benchmarks show that this value is about 1 + k = len(r) * len(c) # number of cells + # n + 1 guards against failure if n == 0 + if n > fac * np.log(n + 1) * k: + return cls._rvs_patefield + return cls._rvs_boyett + + @staticmethod + def _rvs_boyett(row, col, ntot, size, random_state): + return _rcont.rvs_rcont1(row, col, ntot, size, random_state) + + @staticmethod + def _rvs_patefield(row, col, ntot, size, random_state): + return _rcont.rvs_rcont2(row, col, ntot, size, random_state) + + +random_table = random_table_gen() + + +class random_table_frozen(multi_rv_frozen): + def __init__(self, row, col, *, seed=None): + self._dist = random_table_gen(seed) + self._params = self._dist._process_parameters(row, col) + + # monkey patch self._dist + def _process_parameters(r, c): + return self._params + self._dist._process_parameters = _process_parameters + + def logpmf(self, x): + return self._dist.logpmf(x, None, None) + + def pmf(self, x): + return self._dist.pmf(x, None, None) + + def mean(self): + return self._dist.mean(None, None) + + def rvs(self, size=None, method=None, random_state=None): + # optimisations are possible here + return self._dist.rvs(None, None, size=size, method=method, + random_state=random_state) + + +_ctab_doc_row_col = """\ +row : array_like + Sum of table entries in each row. +col : array_like + Sum of table entries in each column.""" + +_ctab_doc_x = """\ +x : array-like + Two-dimensional table of non-negative integers, or a + multi-dimensional array with the last two dimensions + corresponding with the tables.""" + +_ctab_doc_row_col_note = """\ +The row and column vectors must be one-dimensional, not empty, +and each sum up to the same value. They cannot contain negative +or noninteger entries.""" + +_ctab_doc_mean_params = f""" +Parameters +---------- +{_ctab_doc_row_col}""" + +_ctab_doc_row_col_note_frozen = """\ +See class definition for a detailed description of parameters.""" + +_ctab_docdict = { + "_doc_random_state": _doc_random_state, + "_doc_row_col": _ctab_doc_row_col, + "_doc_x": _ctab_doc_x, + "_doc_mean_params": _ctab_doc_mean_params, + "_doc_row_col_note": _ctab_doc_row_col_note, +} + +_ctab_docdict_frozen = _ctab_docdict.copy() +_ctab_docdict_frozen.update({ + "_doc_row_col": "", + "_doc_mean_params": "", + "_doc_row_col_note": _ctab_doc_row_col_note_frozen, +}) + + +def _docfill(obj, docdict, template=None): + obj.__doc__ = doccer.docformat(template or obj.__doc__, docdict) + + +# Set frozen generator docstrings from corresponding docstrings in +# random_table and fill in default strings in class docstrings +_docfill(random_table_gen, _ctab_docdict) +for name in ['logpmf', 'pmf', 'mean', 'rvs']: + method = random_table_gen.__dict__[name] + method_frozen = random_table_frozen.__dict__[name] + _docfill(method_frozen, _ctab_docdict_frozen, method.__doc__) + _docfill(method, _ctab_docdict) + + +class uniform_direction_gen(multi_rv_generic): + r"""A vector-valued uniform direction. + + Return a random direction (unit vector). The `dim` keyword specifies + the dimensionality of the space. + + Methods + ------- + rvs(dim=None, size=1, random_state=None) + Draw random directions. + + Parameters + ---------- + dim : scalar + Dimension of directions. + seed : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + Notes + ----- + This distribution generates unit vectors uniformly distributed on + the surface of a hypersphere. These can be interpreted as random + directions. + For example, if `dim` is 3, 3D vectors from the surface of :math:`S^2` + will be sampled. + + References + ---------- + .. [1] Marsaglia, G. (1972). "Choosing a Point from the Surface of a + Sphere". Annals of Mathematical Statistics. 43 (2): 645-646. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import uniform_direction + >>> x = uniform_direction.rvs(3) + >>> np.linalg.norm(x) + 1. + + This generates one random direction, a vector on the surface of + :math:`S^2`. + + Alternatively, the object may be called (as a function) to return a frozen + distribution with fixed `dim` parameter. Here, + we create a `uniform_direction` with ``dim=3`` and draw 5 observations. + The samples are then arranged in an array of shape 5x3. + + >>> rng = np.random.default_rng() + >>> uniform_sphere_dist = uniform_direction(3) + >>> unit_vectors = uniform_sphere_dist.rvs(5, random_state=rng) + >>> unit_vectors + array([[ 0.56688642, -0.1332634 , -0.81294566], + [-0.427126 , -0.74779278, 0.50830044], + [ 0.3793989 , 0.92346629, 0.05715323], + [ 0.36428383, -0.92449076, -0.11231259], + [-0.27733285, 0.94410968, -0.17816678]]) + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__) + + def __call__(self, dim=None, seed=None): + """Create a frozen n-dimensional uniform direction distribution. + + See `uniform_direction` for more information. + """ + return uniform_direction_frozen(dim, seed=seed) + + def _process_parameters(self, dim): + """Dimension N must be specified; it cannot be inferred.""" + if dim is None or not np.isscalar(dim) or dim < 1 or dim != int(dim): + raise ValueError("Dimension of vector must be specified, " + "and must be an integer greater than 0.") + + return int(dim) + + def rvs(self, dim, size=None, random_state=None): + """Draw random samples from S(N-1). + + Parameters + ---------- + dim : integer + Dimension of space (N). + size : int or tuple of ints, optional + Given a shape of, for example, (m,n,k), m*n*k samples are + generated, and packed in an m-by-n-by-k arrangement. + Because each sample is N-dimensional, the output shape + is (m,n,k,N). If no shape is specified, a single (N-D) + sample is returned. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + Pseudorandom number generator state used to generate resamples. + + If `random_state` is ``None`` (or `np.random`), the + `numpy.random.RandomState` singleton is used. + If `random_state` is an int, a new ``RandomState`` instance is + used, seeded with `random_state`. + If `random_state` is already a ``Generator`` or ``RandomState`` + instance then that instance is used. + + Returns + ------- + rvs : ndarray + Random direction vectors + + """ + random_state = self._get_random_state(random_state) + if size is None: + size = np.array([], dtype=int) + size = np.atleast_1d(size) + + dim = self._process_parameters(dim) + + samples = _sample_uniform_direction(dim, size, random_state) + return samples + + +uniform_direction = uniform_direction_gen() + + +class uniform_direction_frozen(multi_rv_frozen): + def __init__(self, dim=None, seed=None): + """Create a frozen n-dimensional uniform direction distribution. + + Parameters + ---------- + dim : int + Dimension of matrices + seed : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + Examples + -------- + >>> from scipy.stats import uniform_direction + >>> x = uniform_direction(3) + >>> x.rvs() + + """ + self._dist = uniform_direction_gen(seed) + self.dim = self._dist._process_parameters(dim) + + def rvs(self, size=None, random_state=None): + return self._dist.rvs(self.dim, size, random_state) + + +def _sample_uniform_direction(dim, size, random_state): + """ + Private method to generate uniform directions + Reference: Marsaglia, G. (1972). "Choosing a Point from the Surface of a + Sphere". Annals of Mathematical Statistics. 43 (2): 645-646. + """ + samples_shape = np.append(size, dim) + samples = random_state.standard_normal(samples_shape) + samples /= np.linalg.norm(samples, axis=-1, keepdims=True) + return samples + + +_dirichlet_mn_doc_default_callparams = """\ +alpha : array_like + The concentration parameters. The number of entries along the last axis + determines the dimensionality of the distribution. Each entry must be + strictly positive. +n : int or array_like + The number of trials. Each element must be a strictly positive integer. +""" + +_dirichlet_mn_doc_frozen_callparams = "" + +_dirichlet_mn_doc_frozen_callparams_note = """\ +See class definition for a detailed description of parameters.""" + +dirichlet_mn_docdict_params = { + '_dirichlet_mn_doc_default_callparams': _dirichlet_mn_doc_default_callparams, + '_doc_random_state': _doc_random_state +} + +dirichlet_mn_docdict_noparams = { + '_dirichlet_mn_doc_default_callparams': _dirichlet_mn_doc_frozen_callparams, + '_doc_random_state': _doc_random_state +} + + +def _dirichlet_multinomial_check_parameters(alpha, n, x=None): + + alpha = np.asarray(alpha) + n = np.asarray(n) + + if x is not None: + # Ensure that `x` and `alpha` are arrays. If the shapes are + # incompatible, NumPy will raise an appropriate error. + try: + x, alpha = np.broadcast_arrays(x, alpha) + except ValueError as e: + msg = "`x` and `alpha` must be broadcastable." + raise ValueError(msg) from e + + x_int = np.floor(x) + if np.any(x < 0) or np.any(x != x_int): + raise ValueError("`x` must contain only non-negative integers.") + x = x_int + + if np.any(alpha <= 0): + raise ValueError("`alpha` must contain only positive values.") + + n_int = np.floor(n) + if np.any(n <= 0) or np.any(n != n_int): + raise ValueError("`n` must be a positive integer.") + n = n_int + + sum_alpha = np.sum(alpha, axis=-1) + sum_alpha, n = np.broadcast_arrays(sum_alpha, n) + + return (alpha, sum_alpha, n) if x is None else (alpha, sum_alpha, n, x) + + +class dirichlet_multinomial_gen(multi_rv_generic): + r"""A Dirichlet multinomial random variable. + + The Dirichlet multinomial distribution is a compound probability + distribution: it is the multinomial distribution with number of trials + `n` and class probabilities ``p`` randomly sampled from a Dirichlet + distribution with concentration parameters ``alpha``. + + Methods + ------- + logpmf(x, alpha, n): + Log of the probability mass function. + pmf(x, alpha, n): + Probability mass function. + mean(alpha, n): + Mean of the Dirichlet multinomial distribution. + var(alpha, n): + Variance of the Dirichlet multinomial distribution. + cov(alpha, n): + The covariance of the Dirichlet multinomial distribution. + + Parameters + ---------- + %(_dirichlet_mn_doc_default_callparams)s + %(_doc_random_state)s + + See Also + -------- + scipy.stats.dirichlet : The dirichlet distribution. + scipy.stats.multinomial : The multinomial distribution. + + References + ---------- + .. [1] Dirichlet-multinomial distribution, Wikipedia, + https://www.wikipedia.org/wiki/Dirichlet-multinomial_distribution + + Examples + -------- + >>> from scipy.stats import dirichlet_multinomial + + Get the PMF + + >>> n = 6 # number of trials + >>> alpha = [3, 4, 5] # concentration parameters + >>> x = [1, 2, 3] # counts + >>> dirichlet_multinomial.pmf(x, alpha, n) + 0.08484162895927604 + + If the sum of category counts does not equal the number of trials, + the probability mass is zero. + + >>> dirichlet_multinomial.pmf(x, alpha, n=7) + 0.0 + + Get the log of the PMF + + >>> dirichlet_multinomial.logpmf(x, alpha, n) + -2.4669689491013327 + + Get the mean + + >>> dirichlet_multinomial.mean(alpha, n) + array([1.5, 2. , 2.5]) + + Get the variance + + >>> dirichlet_multinomial.var(alpha, n) + array([1.55769231, 1.84615385, 2.01923077]) + + Get the covariance + + >>> dirichlet_multinomial.cov(alpha, n) + array([[ 1.55769231, -0.69230769, -0.86538462], + [-0.69230769, 1.84615385, -1.15384615], + [-0.86538462, -1.15384615, 2.01923077]]) + + Alternatively, the object may be called (as a function) to fix the + `alpha` and `n` parameters, returning a "frozen" Dirichlet multinomial + random variable. + + >>> dm = dirichlet_multinomial(alpha, n) + >>> dm.pmf(x) + 0.08484162895927579 + + All methods are fully vectorized. Each element of `x` and `alpha` is + a vector (along the last axis), each element of `n` is an + integer (scalar), and the result is computed element-wise. + + >>> x = [[1, 2, 3], [4, 5, 6]] + >>> alpha = [[1, 2, 3], [4, 5, 6]] + >>> n = [6, 15] + >>> dirichlet_multinomial.pmf(x, alpha, n) + array([0.06493506, 0.02626937]) + + >>> dirichlet_multinomial.cov(alpha, n).shape # both covariance matrices + (2, 3, 3) + + Broadcasting according to standard NumPy conventions is supported. Here, + we have four sets of concentration parameters (each a two element vector) + for each of three numbers of trials (each a scalar). + + >>> alpha = [[3, 4], [4, 5], [5, 6], [6, 7]] + >>> n = [[6], [7], [8]] + >>> dirichlet_multinomial.mean(alpha, n).shape + (3, 4, 2) + + """ + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, + dirichlet_mn_docdict_params) + + def __call__(self, alpha, n, seed=None): + return dirichlet_multinomial_frozen(alpha, n, seed=seed) + + def logpmf(self, x, alpha, n): + """The log of the probability mass function. + + Parameters + ---------- + x: ndarray + Category counts (non-negative integers). Must be broadcastable + with shape parameter ``alpha``. If multidimensional, the last axis + must correspond with the categories. + %(_dirichlet_mn_doc_default_callparams)s + + Returns + ------- + out: ndarray or scalar + Log of the probability mass function. + + """ + + a, Sa, n, x = _dirichlet_multinomial_check_parameters(alpha, n, x) + + out = np.asarray(loggamma(Sa) + loggamma(n + 1) - loggamma(n + Sa)) + out += (loggamma(x + a) - (loggamma(a) + loggamma(x + 1))).sum(axis=-1) + np.place(out, n != x.sum(axis=-1), -np.inf) + return out[()] + + def pmf(self, x, alpha, n): + """Probability mass function for a Dirichlet multinomial distribution. + + Parameters + ---------- + x: ndarray + Category counts (non-negative integers). Must be broadcastable + with shape parameter ``alpha``. If multidimensional, the last axis + must correspond with the categories. + %(_dirichlet_mn_doc_default_callparams)s + + Returns + ------- + out: ndarray or scalar + Probability mass function. + + """ + return np.exp(self.logpmf(x, alpha, n)) + + def mean(self, alpha, n): + """Mean of a Dirichlet multinomial distribution. + + Parameters + ---------- + %(_dirichlet_mn_doc_default_callparams)s + + Returns + ------- + out: ndarray + Mean of a Dirichlet multinomial distribution. + + """ + a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n) + n, Sa = n[..., np.newaxis], Sa[..., np.newaxis] + return n * a / Sa + + def var(self, alpha, n): + """The variance of the Dirichlet multinomial distribution. + + Parameters + ---------- + %(_dirichlet_mn_doc_default_callparams)s + + Returns + ------- + out: array_like + The variances of the components of the distribution. This is + the diagonal of the covariance matrix of the distribution. + + """ + a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n) + n, Sa = n[..., np.newaxis], Sa[..., np.newaxis] + return n * a / Sa * (1 - a/Sa) * (n + Sa) / (1 + Sa) + + def cov(self, alpha, n): + """Covariance matrix of a Dirichlet multinomial distribution. + + Parameters + ---------- + %(_dirichlet_mn_doc_default_callparams)s + + Returns + ------- + out : array_like + The covariance matrix of the distribution. + + """ + a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n) + var = dirichlet_multinomial.var(a, n) + + n, Sa = n[..., np.newaxis, np.newaxis], Sa[..., np.newaxis, np.newaxis] + aiaj = a[..., :, np.newaxis] * a[..., np.newaxis, :] + cov = -n * aiaj / Sa ** 2 * (n + Sa) / (1 + Sa) + + ii = np.arange(cov.shape[-1]) + cov[..., ii, ii] = var + return cov + + +dirichlet_multinomial = dirichlet_multinomial_gen() + + +class dirichlet_multinomial_frozen(multi_rv_frozen): + def __init__(self, alpha, n, seed=None): + alpha, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n) + self.alpha = alpha + self.n = n + self._dist = dirichlet_multinomial_gen(seed) + + def logpmf(self, x): + return self._dist.logpmf(x, self.alpha, self.n) + + def pmf(self, x): + return self._dist.pmf(x, self.alpha, self.n) + + def mean(self): + return self._dist.mean(self.alpha, self.n) + + def var(self): + return self._dist.var(self.alpha, self.n) + + def cov(self): + return self._dist.cov(self.alpha, self.n) + + +# Set frozen generator docstrings from corresponding docstrings in +# dirichlet_multinomial and fill in default strings in class docstrings. +for name in ['logpmf', 'pmf', 'mean', 'var', 'cov']: + method = dirichlet_multinomial_gen.__dict__[name] + method_frozen = dirichlet_multinomial_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat( + method.__doc__, dirichlet_mn_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, + dirichlet_mn_docdict_params) + + +class vonmises_fisher_gen(multi_rv_generic): + r"""A von Mises-Fisher variable. + + The `mu` keyword specifies the mean direction vector. The `kappa` keyword + specifies the concentration parameter. + + Methods + ------- + pdf(x, mu=None, kappa=1) + Probability density function. + logpdf(x, mu=None, kappa=1) + Log of the probability density function. + rvs(mu=None, kappa=1, size=1, random_state=None) + Draw random samples from a von Mises-Fisher distribution. + entropy(mu=None, kappa=1) + Compute the differential entropy of the von Mises-Fisher distribution. + fit(data) + Fit a von Mises-Fisher distribution to data. + + Parameters + ---------- + mu : array_like + Mean direction of the distribution. Must be a one-dimensional unit + vector of norm 1. + kappa : float + Concentration parameter. Must be positive. + seed : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + See Also + -------- + scipy.stats.vonmises : Von-Mises Fisher distribution in 2D on a circle + uniform_direction : uniform distribution on the surface of a hypersphere + + Notes + ----- + The von Mises-Fisher distribution is a directional distribution on the + surface of the unit hypersphere. The probability density + function of a unit vector :math:`\mathbf{x}` is + + .. math:: + + f(\mathbf{x}) = \frac{\kappa^{d/2-1}}{(2\pi)^{d/2}I_{d/2-1}(\kappa)} + \exp\left(\kappa \mathbf{\mu}^T\mathbf{x}\right), + + where :math:`\mathbf{\mu}` is the mean direction, :math:`\kappa` the + concentration parameter, :math:`d` the dimension and :math:`I` the + modified Bessel function of the first kind. As :math:`\mu` represents + a direction, it must be a unit vector or in other words, a point + on the hypersphere: :math:`\mathbf{\mu}\in S^{d-1}`. :math:`\kappa` is a + concentration parameter, which means that it must be positive + (:math:`\kappa>0`) and that the distribution becomes more narrow with + increasing :math:`\kappa`. In that sense, the reciprocal value + :math:`1/\kappa` resembles the variance parameter of the normal + distribution. + + The von Mises-Fisher distribution often serves as an analogue of the + normal distribution on the sphere. Intuitively, for unit vectors, a + useful distance measure is given by the angle :math:`\alpha` between + them. This is exactly what the scalar product + :math:`\mathbf{\mu}^T\mathbf{x}=\cos(\alpha)` in the + von Mises-Fisher probability density function describes: the angle + between the mean direction :math:`\mathbf{\mu}` and the vector + :math:`\mathbf{x}`. The larger the angle between them, the smaller the + probability to observe :math:`\mathbf{x}` for this particular mean + direction :math:`\mathbf{\mu}`. + + In dimensions 2 and 3, specialized algorithms are used for fast sampling + [2]_, [3]_. For dimensions of 4 or higher the rejection sampling algorithm + described in [4]_ is utilized. This implementation is partially based on + the geomstats package [5]_, [6]_. + + .. versionadded:: 1.11 + + References + ---------- + .. [1] Von Mises-Fisher distribution, Wikipedia, + https://en.wikipedia.org/wiki/Von_Mises%E2%80%93Fisher_distribution + .. [2] Mardia, K., and Jupp, P. Directional statistics. Wiley, 2000. + .. [3] J. Wenzel. Numerically stable sampling of the von Mises Fisher + distribution on S2. + https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf + .. [4] Wood, A. Simulation of the von mises fisher distribution. + Communications in statistics-simulation and computation 23, + 1 (1994), 157-164. https://doi.org/10.1080/03610919408813161 + .. [5] geomstats, Github. MIT License. Accessed: 06.01.2023. + https://github.com/geomstats/geomstats + .. [6] Miolane, N. et al. Geomstats: A Python Package for Riemannian + Geometry in Machine Learning. Journal of Machine Learning Research + 21 (2020). http://jmlr.org/papers/v21/19-027.html + + Examples + -------- + **Visualization of the probability density** + + Plot the probability density in three dimensions for increasing + concentration parameter. The density is calculated by the ``pdf`` + method. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import vonmises_fisher + >>> from matplotlib.colors import Normalize + >>> n_grid = 100 + >>> u = np.linspace(0, np.pi, n_grid) + >>> v = np.linspace(0, 2 * np.pi, n_grid) + >>> u_grid, v_grid = np.meshgrid(u, v) + >>> vertices = np.stack([np.cos(v_grid) * np.sin(u_grid), + ... np.sin(v_grid) * np.sin(u_grid), + ... np.cos(u_grid)], + ... axis=2) + >>> x = np.outer(np.cos(v), np.sin(u)) + >>> y = np.outer(np.sin(v), np.sin(u)) + >>> z = np.outer(np.ones_like(u), np.cos(u)) + >>> def plot_vmf_density(ax, x, y, z, vertices, mu, kappa): + ... vmf = vonmises_fisher(mu, kappa) + ... pdf_values = vmf.pdf(vertices) + ... pdfnorm = Normalize(vmin=pdf_values.min(), vmax=pdf_values.max()) + ... ax.plot_surface(x, y, z, rstride=1, cstride=1, + ... facecolors=plt.cm.viridis(pdfnorm(pdf_values)), + ... linewidth=0) + ... ax.set_aspect('equal') + ... ax.view_init(azim=-130, elev=0) + ... ax.axis('off') + ... ax.set_title(rf"$\kappa={kappa}$") + >>> fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 4), + ... subplot_kw={"projection": "3d"}) + >>> left, middle, right = axes + >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0]) + >>> plot_vmf_density(left, x, y, z, vertices, mu, 5) + >>> plot_vmf_density(middle, x, y, z, vertices, mu, 20) + >>> plot_vmf_density(right, x, y, z, vertices, mu, 100) + >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0, right=1.0, wspace=0.) + >>> plt.show() + + As we increase the concentration parameter, the points are getting more + clustered together around the mean direction. + + **Sampling** + + Draw 5 samples from the distribution using the ``rvs`` method resulting + in a 5x3 array. + + >>> rng = np.random.default_rng() + >>> mu = np.array([0, 0, 1]) + >>> samples = vonmises_fisher(mu, 20).rvs(5, random_state=rng) + >>> samples + array([[ 0.3884594 , -0.32482588, 0.86231516], + [ 0.00611366, -0.09878289, 0.99509023], + [-0.04154772, -0.01637135, 0.99900239], + [-0.14613735, 0.12553507, 0.98126695], + [-0.04429884, -0.23474054, 0.97104814]]) + + These samples are unit vectors on the sphere :math:`S^2`. To verify, + let us calculate their euclidean norms: + + >>> np.linalg.norm(samples, axis=1) + array([1., 1., 1., 1., 1.]) + + Plot 20 observations drawn from the von Mises-Fisher distribution for + increasing concentration parameter :math:`\kappa`. The red dot highlights + the mean direction :math:`\mu`. + + >>> def plot_vmf_samples(ax, x, y, z, mu, kappa): + ... vmf = vonmises_fisher(mu, kappa) + ... samples = vmf.rvs(20) + ... ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0, + ... alpha=0.2) + ... ax.scatter(samples[:, 0], samples[:, 1], samples[:, 2], c='k', s=5) + ... ax.scatter(mu[0], mu[1], mu[2], c='r', s=30) + ... ax.set_aspect('equal') + ... ax.view_init(azim=-130, elev=0) + ... ax.axis('off') + ... ax.set_title(rf"$\kappa={kappa}$") + >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0]) + >>> fig, axes = plt.subplots(nrows=1, ncols=3, + ... subplot_kw={"projection": "3d"}, + ... figsize=(9, 4)) + >>> left, middle, right = axes + >>> plot_vmf_samples(left, x, y, z, mu, 5) + >>> plot_vmf_samples(middle, x, y, z, mu, 20) + >>> plot_vmf_samples(right, x, y, z, mu, 100) + >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0, + ... right=1.0, wspace=0.) + >>> plt.show() + + The plots show that with increasing concentration :math:`\kappa` the + resulting samples are centered more closely around the mean direction. + + **Fitting the distribution parameters** + + The distribution can be fitted to data using the ``fit`` method returning + the estimated parameters. As a toy example let's fit the distribution to + samples drawn from a known von Mises-Fisher distribution. + + >>> mu, kappa = np.array([0, 0, 1]), 20 + >>> samples = vonmises_fisher(mu, kappa).rvs(1000, random_state=rng) + >>> mu_fit, kappa_fit = vonmises_fisher.fit(samples) + >>> mu_fit, kappa_fit + (array([0.01126519, 0.01044501, 0.99988199]), 19.306398751730995) + + We see that the estimated parameters `mu_fit` and `kappa_fit` are + very close to the ground truth parameters. + + """ + def __init__(self, seed=None): + super().__init__(seed) + + def __call__(self, mu=None, kappa=1, seed=None): + """Create a frozen von Mises-Fisher distribution. + + See `vonmises_fisher_frozen` for more information. + """ + return vonmises_fisher_frozen(mu, kappa, seed=seed) + + def _process_parameters(self, mu, kappa): + """ + Infer dimensionality from mu and ensure that mu is a one-dimensional + unit vector and kappa positive. + """ + mu = np.asarray(mu) + if mu.ndim > 1: + raise ValueError("'mu' must have one-dimensional shape.") + if not np.allclose(np.linalg.norm(mu), 1.): + raise ValueError("'mu' must be a unit vector of norm 1.") + if not mu.size > 1: + raise ValueError("'mu' must have at least two entries.") + kappa_error_msg = "'kappa' must be a positive scalar." + if not np.isscalar(kappa) or kappa < 0: + raise ValueError(kappa_error_msg) + if float(kappa) == 0.: + raise ValueError("For 'kappa=0' the von Mises-Fisher distribution " + "becomes the uniform distribution on the sphere " + "surface. Consider using " + "'scipy.stats.uniform_direction' instead.") + dim = mu.size + + return dim, mu, kappa + + def _check_data_vs_dist(self, x, dim): + if x.shape[-1] != dim: + raise ValueError("The dimensionality of the last axis of 'x' must " + "match the dimensionality of the " + "von Mises Fisher distribution.") + if not np.allclose(np.linalg.norm(x, axis=-1), 1.): + msg = "'x' must be unit vectors of norm 1 along last dimension." + raise ValueError(msg) + + def _log_norm_factor(self, dim, kappa): + # normalization factor is given by + # c = kappa**(dim/2-1)/((2*pi)**(dim/2)*I[dim/2-1](kappa)) + # = kappa**(dim/2-1)*exp(-kappa) / + # ((2*pi)**(dim/2)*I[dim/2-1](kappa)*exp(-kappa) + # = kappa**(dim/2-1)*exp(-kappa) / + # ((2*pi)**(dim/2)*ive[dim/2-1](kappa) + # Then the log is given by + # log c = 1/2*(dim -1)*log(kappa) - kappa - -1/2*dim*ln(2*pi) - + # ive[dim/2-1](kappa) + halfdim = 0.5 * dim + return (0.5 * (dim - 2)*np.log(kappa) - halfdim * _LOG_2PI - + np.log(ive(halfdim - 1, kappa)) - kappa) + + def _logpdf(self, x, dim, mu, kappa): + """Log of the von Mises-Fisher probability density function. + + As this function does no argument checking, it should not be + called directly; use 'logpdf' instead. + + """ + x = np.asarray(x) + self._check_data_vs_dist(x, dim) + dotproducts = np.einsum('i,...i->...', mu, x) + return self._log_norm_factor(dim, kappa) + kappa * dotproducts + + def logpdf(self, x, mu=None, kappa=1): + """Log of the von Mises-Fisher probability density function. + + Parameters + ---------- + x : array_like + Points at which to evaluate the log of the probability + density function. The last axis of `x` must correspond + to unit vectors of the same dimensionality as the distribution. + mu : array_like, default: None + Mean direction of the distribution. Must be a one-dimensional unit + vector of norm 1. + kappa : float, default: 1 + Concentration parameter. Must be positive. + + Returns + ------- + logpdf : ndarray or scalar + Log of the probability density function evaluated at `x`. + + """ + dim, mu, kappa = self._process_parameters(mu, kappa) + return self._logpdf(x, dim, mu, kappa) + + def pdf(self, x, mu=None, kappa=1): + """Von Mises-Fisher probability density function. + + Parameters + ---------- + x : array_like + Points at which to evaluate the probability + density function. The last axis of `x` must correspond + to unit vectors of the same dimensionality as the distribution. + mu : array_like + Mean direction of the distribution. Must be a one-dimensional unit + vector of norm 1. + kappa : float + Concentration parameter. Must be positive. + + Returns + ------- + pdf : ndarray or scalar + Probability density function evaluated at `x`. + + """ + dim, mu, kappa = self._process_parameters(mu, kappa) + return np.exp(self._logpdf(x, dim, mu, kappa)) + + def _rvs_2d(self, mu, kappa, size, random_state): + """ + In 2D, the von Mises-Fisher distribution reduces to the + von Mises distribution which can be efficiently sampled by numpy. + This method is much faster than the general rejection + sampling based algorithm. + + """ + mean_angle = np.arctan2(mu[1], mu[0]) + angle_samples = random_state.vonmises(mean_angle, kappa, size=size) + samples = np.stack([np.cos(angle_samples), np.sin(angle_samples)], + axis=-1) + return samples + + def _rvs_3d(self, kappa, size, random_state): + """ + Generate samples from a von Mises-Fisher distribution + with mu = [1, 0, 0] and kappa. Samples then have to be + rotated towards the desired mean direction mu. + This method is much faster than the general rejection + sampling based algorithm. + Reference: https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf + + """ + if size is None: + sample_size = 1 + else: + sample_size = size + + # compute x coordinate acc. to equation from section 3.1 + x = random_state.random(sample_size) + x = 1. + np.log(x + (1. - x) * np.exp(-2 * kappa))/kappa + + # (y, z) are random 2D vectors that only have to be + # normalized accordingly. Then (x, y z) follow a VMF distribution + temp = np.sqrt(1. - np.square(x)) + uniformcircle = _sample_uniform_direction(2, sample_size, random_state) + samples = np.stack([x, temp * uniformcircle[..., 0], + temp * uniformcircle[..., 1]], + axis=-1) + if size is None: + samples = np.squeeze(samples) + return samples + + def _rejection_sampling(self, dim, kappa, size, random_state): + """ + Generate samples from a n-dimensional von Mises-Fisher distribution + with mu = [1, 0, ..., 0] and kappa via rejection sampling. + Samples then have to be rotated towards the desired mean direction mu. + Reference: https://doi.org/10.1080/03610919408813161 + """ + dim_minus_one = dim - 1 + # calculate number of requested samples + if size is not None: + if not np.iterable(size): + size = (size, ) + n_samples = math.prod(size) + else: + n_samples = 1 + # calculate envelope for rejection sampler (eq. 4) + sqrt = np.sqrt(4 * kappa ** 2. + dim_minus_one ** 2) + envelop_param = (-2 * kappa + sqrt) / dim_minus_one + if envelop_param == 0: + # the regular formula suffers from loss of precision for high + # kappa. This can only be detected by checking for 0 here. + # Workaround: expansion for sqrt variable + # https://www.wolframalpha.com/input?i=sqrt%284*x%5E2%2Bd%5E2%29 + # e = (-2 * k + sqrt(k**2 + d**2)) / d + # ~ (-2 * k + 2 * k + d**2/(4 * k) - d**4/(64 * k**3)) / d + # = d/(4 * k) - d**3/(64 * k**3) + envelop_param = (dim_minus_one/4 * kappa**-1. + - dim_minus_one**3/64 * kappa**-3.) + # reference step 0 + node = (1. - envelop_param) / (1. + envelop_param) + # t = ln(1 - ((1-x)/(1+x))**2) + # = ln(4 * x / (1+x)**2) + # = ln(4) + ln(x) - 2*log1p(x) + correction = (kappa * node + dim_minus_one + * (np.log(4) + np.log(envelop_param) + - 2 * np.log1p(envelop_param))) + n_accepted = 0 + x = np.zeros((n_samples, )) + halfdim = 0.5 * dim_minus_one + # main loop + while n_accepted < n_samples: + # generate candidates acc. to reference step 1 + sym_beta = random_state.beta(halfdim, halfdim, + size=n_samples - n_accepted) + coord_x = (1 - (1 + envelop_param) * sym_beta) / ( + 1 - (1 - envelop_param) * sym_beta) + # accept or reject: reference step 2 + # reformulation for numerical stability: + # t = ln(1 - (1-x)/(1+x) * y) + # = ln((1 + x - y +x*y)/(1 +x)) + accept_tol = random_state.random(n_samples - n_accepted) + criterion = ( + kappa * coord_x + + dim_minus_one * (np.log((1 + envelop_param - coord_x + + coord_x * envelop_param) / (1 + envelop_param))) + - correction) > np.log(accept_tol) + accepted_iter = np.sum(criterion) + x[n_accepted:n_accepted + accepted_iter] = coord_x[criterion] + n_accepted += accepted_iter + # concatenate x and remaining coordinates: step 3 + coord_rest = _sample_uniform_direction(dim_minus_one, n_accepted, + random_state) + coord_rest = np.einsum( + '...,...i->...i', np.sqrt(1 - x ** 2), coord_rest) + samples = np.concatenate([x[..., None], coord_rest], axis=1) + # reshape output to (size, dim) + if size is not None: + samples = samples.reshape(size + (dim, )) + else: + samples = np.squeeze(samples) + return samples + + def _rotate_samples(self, samples, mu, dim): + """A QR decomposition is used to find the rotation that maps the + north pole (1, 0,...,0) to the vector mu. This rotation is then + applied to all samples. + + Parameters + ---------- + samples: array_like, shape = [..., n] + mu : array-like, shape=[n, ] + Point to parametrise the rotation. + + Returns + ------- + samples : rotated samples + + """ + base_point = np.zeros((dim, )) + base_point[0] = 1. + embedded = np.concatenate([mu[None, :], np.zeros((dim - 1, dim))]) + rotmatrix, _ = np.linalg.qr(np.transpose(embedded)) + if np.allclose(np.matmul(rotmatrix, base_point[:, None])[:, 0], mu): + rotsign = 1 + else: + rotsign = -1 + + # apply rotation + samples = np.einsum('ij,...j->...i', rotmatrix, samples) * rotsign + return samples + + def _rvs(self, dim, mu, kappa, size, random_state): + if dim == 2: + samples = self._rvs_2d(mu, kappa, size, random_state) + elif dim == 3: + samples = self._rvs_3d(kappa, size, random_state) + else: + samples = self._rejection_sampling(dim, kappa, size, + random_state) + + if dim != 2: + samples = self._rotate_samples(samples, mu, dim) + return samples + + def rvs(self, mu=None, kappa=1, size=1, random_state=None): + """Draw random samples from a von Mises-Fisher distribution. + + Parameters + ---------- + mu : array_like + Mean direction of the distribution. Must be a one-dimensional unit + vector of norm 1. + kappa : float + Concentration parameter. Must be positive. + size : int or tuple of ints, optional + Given a shape of, for example, (m,n,k), m*n*k samples are + generated, and packed in an m-by-n-by-k arrangement. + Because each sample is N-dimensional, the output shape + is (m,n,k,N). If no shape is specified, a single (N-D) + sample is returned. + random_state : {None, int, np.random.RandomState, np.random.Generator}, + optional + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + Returns + ------- + rvs : ndarray + Random variates of shape (`size`, `N`), where `N` is the + dimension of the distribution. + + """ + dim, mu, kappa = self._process_parameters(mu, kappa) + random_state = self._get_random_state(random_state) + samples = self._rvs(dim, mu, kappa, size, random_state) + return samples + + def _entropy(self, dim, kappa): + halfdim = 0.5 * dim + return (-self._log_norm_factor(dim, kappa) - kappa * + ive(halfdim, kappa) / ive(halfdim - 1, kappa)) + + def entropy(self, mu=None, kappa=1): + """Compute the differential entropy of the von Mises-Fisher + distribution. + + Parameters + ---------- + mu : array_like, default: None + Mean direction of the distribution. Must be a one-dimensional unit + vector of norm 1. + kappa : float, default: 1 + Concentration parameter. Must be positive. + + Returns + ------- + h : scalar + Entropy of the von Mises-Fisher distribution. + + """ + dim, _, kappa = self._process_parameters(mu, kappa) + return self._entropy(dim, kappa) + + def fit(self, x): + """Fit the von Mises-Fisher distribution to data. + + Parameters + ---------- + x : array-like + Data the distribution is fitted to. Must be two dimensional. + The second axis of `x` must be unit vectors of norm 1 and + determine the dimensionality of the fitted + von Mises-Fisher distribution. + + Returns + ------- + mu : ndarray + Estimated mean direction. + kappa : float + Estimated concentration parameter. + + """ + # validate input data + x = np.asarray(x) + if x.ndim != 2: + raise ValueError("'x' must be two dimensional.") + if not np.allclose(np.linalg.norm(x, axis=-1), 1.): + msg = "'x' must be unit vectors of norm 1 along last dimension." + raise ValueError(msg) + dim = x.shape[-1] + + # mu is simply the directional mean + dirstats = directional_stats(x) + mu = dirstats.mean_direction + r = dirstats.mean_resultant_length + + # kappa is the solution to the equation: + # r = I[dim/2](kappa) / I[dim/2 -1](kappa) + # = I[dim/2](kappa) * exp(-kappa) / I[dim/2 -1](kappa) * exp(-kappa) + # = ive(dim/2, kappa) / ive(dim/2 -1, kappa) + + halfdim = 0.5 * dim + + def solve_for_kappa(kappa): + bessel_vals = ive([halfdim, halfdim - 1], kappa) + return bessel_vals[0]/bessel_vals[1] - r + + root_res = root_scalar(solve_for_kappa, method="brentq", + bracket=(1e-8, 1e9)) + kappa = root_res.root + return mu, kappa + + +vonmises_fisher = vonmises_fisher_gen() + + +class vonmises_fisher_frozen(multi_rv_frozen): + def __init__(self, mu=None, kappa=1, seed=None): + """Create a frozen von Mises-Fisher distribution. + + Parameters + ---------- + mu : array_like, default: None + Mean direction of the distribution. + kappa : float, default: 1 + Concentration parameter. Must be positive. + seed : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + """ + self._dist = vonmises_fisher_gen(seed) + self.dim, self.mu, self.kappa = ( + self._dist._process_parameters(mu, kappa) + ) + + def logpdf(self, x): + """ + Parameters + ---------- + x : array_like + Points at which to evaluate the log of the probability + density function. The last axis of `x` must correspond + to unit vectors of the same dimensionality as the distribution. + + Returns + ------- + logpdf : ndarray or scalar + Log of probability density function evaluated at `x`. + + """ + return self._dist._logpdf(x, self.dim, self.mu, self.kappa) + + def pdf(self, x): + """ + Parameters + ---------- + x : array_like + Points at which to evaluate the log of the probability + density function. The last axis of `x` must correspond + to unit vectors of the same dimensionality as the distribution. + + Returns + ------- + pdf : ndarray or scalar + Probability density function evaluated at `x`. + + """ + return np.exp(self.logpdf(x)) + + def rvs(self, size=1, random_state=None): + """Draw random variates from the Von Mises-Fisher distribution. + + Parameters + ---------- + size : int or tuple of ints, optional + Given a shape of, for example, (m,n,k), m*n*k samples are + generated, and packed in an m-by-n-by-k arrangement. + Because each sample is N-dimensional, the output shape + is (m,n,k,N). If no shape is specified, a single (N-D) + sample is returned. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance + then that instance is used. + + Returns + ------- + rvs : ndarray or scalar + Random variates of size (`size`, `N`), where `N` is the + dimension of the distribution. + + """ + random_state = self._dist._get_random_state(random_state) + return self._dist._rvs(self.dim, self.mu, self.kappa, size, + random_state) + + def entropy(self): + """ + Calculate the differential entropy of the von Mises-Fisher + distribution. + + Returns + ------- + h: float + Entropy of the Von Mises-Fisher distribution. + + """ + return self._dist._entropy(self.dim, self.kappa) + + +class normal_inverse_gamma_gen(multi_rv_generic): + r"""Normal-inverse-gamma distribution. + + The normal-inverse-gamma distribution is the conjugate prior of a normal + distribution with unknown mean and variance. + + Methods + ------- + pdf(x, s2, mu=0, lmbda=1, a=1, b=1) + Probability density function. + logpdf(x, s2, mu=0, lmbda=1, a=1, b=1) + Log of the probability density function. + mean(mu=0, lmbda=1, a=1, b=1) + Distribution mean. + var(mu=0, lmbda=1, a=1, b=1) + Distribution variance. + rvs(mu=0, lmbda=1, a=1, b=1, size=None, random_state=None) + Draw random samples. + + Parameters + ---------- + mu, lmbda, a, b : array_like + Shape parameters of the distribution. See notes. + seed : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `seed` is `None`, the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + See Also + -------- + norm + invgamma + + Notes + ----- + + The probability density function of `normal_inverse_gamma` is: + + .. math:: + + f(x, \sigma^2; \mu, \lambda, \alpha, \beta) = + \frac{\sqrt{\lambda}}{\sqrt{2 \pi \sigma^2}} + \frac{\beta^\alpha}{\Gamma(\alpha)} + \left( \frac{1}{\sigma^2} \right)^{\alpha + 1} + \exp \left(- \frac{2 \beta + \lambda (x - \mu)^2} {2 \sigma^2} \right) + + where all parameters are real and finite, and :math:`\sigma^2 > 0`, + :math:`\lambda > 0`, :math:`\alpha > 0`, and :math:`\beta > 0`. + + Methods ``normal_inverse_gamma.pdf`` and ``normal_inverse_gamma.logpdf`` + accept `x` and `s2` for arguments :math:`x` and :math:`\sigma^2`. + All methods accept `mu`, `lmbda`, `a`, and `b` for shape parameters + :math:`\mu`, :math:`\lambda`, :math:`\alpha`, and :math:`\beta`, + respectively. + + .. versionadded:: 1.15 + + References + ---------- + .. [1] Normal-inverse-gamma distribution, Wikipedia, + https://en.wikipedia.org/wiki/Normal-inverse-gamma_distribution + + Examples + -------- + Suppose we wish to investigate the relationship between the + normal-inverse-gamma distribution and the inverse gamma distribution. + + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng(527484872345) + >>> mu, lmbda, a, b = 0, 1, 20, 20 + >>> norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b) + >>> inv_gamma = stats.invgamma(a, scale=b) + + One approach is to compare the distribution of the `s2` elements of + random variates against the PDF of an inverse gamma distribution. + + >>> _, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng) + >>> bins = np.linspace(s2.min(), s2.max(), 50) + >>> plt.hist(s2, bins=bins, density=True, label='Frequency density') + >>> s2 = np.linspace(s2.min(), s2.max(), 300) + >>> plt.plot(s2, inv_gamma.pdf(s2), label='PDF') + >>> plt.xlabel(r'$\sigma^2$') + >>> plt.ylabel('Frequency density / PMF') + >>> plt.show() + + Similarly, we can compare the marginal distribution of `s2` against + an inverse gamma distribution. + + >>> from scipy.integrate import quad_vec + >>> from scipy import integrate + >>> s2 = np.linspace(0.5, 3, 6) + >>> res = quad_vec(lambda x: norm_inv_gamma.pdf(x, s2), -np.inf, np.inf)[0] + >>> np.allclose(res, inv_gamma.pdf(s2)) + True + + The sample mean is comparable to the mean of the distribution. + + >>> x, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng) + >>> x.mean(), s2.mean() + (np.float64(-0.005254750127304425), np.float64(1.050438111436508)) + >>> norm_inv_gamma.mean() + (np.float64(0.0), np.float64(1.0526315789473684)) + + Similarly, for the variance: + + >>> x.var(ddof=1), s2.var(ddof=1) + (np.float64(1.0546150578185023), np.float64(0.061829865266330754)) + >>> norm_inv_gamma.var() + (np.float64(1.0526315789473684), np.float64(0.061557402277623886)) + + """ + def rvs(self, mu=0, lmbda=1, a=1, b=1, size=None, random_state=None): + """Draw random samples from the distribution. + + Parameters + ---------- + mu, lmbda, a, b : array_like, optional + Shape parameters. `lmbda`, `a`, and `b` must be greater + than zero. + size : int or tuple of ints, optional + Shape of samples to draw. + random_state : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `random_state` is `None`, the `~np.random.RandomState` singleton is used. + If `random_state` is an int, a new ``RandomState`` instance is used, seeded + with `random_state`. + If `random_state` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is `None`. + + Returns + ------- + x, s2 : ndarray + Random variates. + + """ + random_state = self._get_random_state(random_state) + s2 = invgamma(a, scale=b).rvs(size=size, random_state=random_state) + scale = (s2 / lmbda)**0.5 + x = norm(loc=mu, scale=scale).rvs(size=size, random_state=random_state) + dtype = np.result_type(1.0, mu, lmbda, a, b) + return x.astype(dtype), s2.astype(dtype) + + def _logpdf(self, x, s2, mu, lmbda, a, b): + t1 = 0.5 * (np.log(lmbda) - np.log(2 * np.pi * s2)) + t2 = a*np.log(b) - special.gammaln(a).astype(a.dtype) + t3 = -(a + 1) * np.log(s2) + t4 = -(2*b + lmbda*(x - mu)**2) / (2*s2) + return t1 + t2 + t3 + t4 + + def logpdf(self, x, s2, mu=0, lmbda=1, a=1, b=1): + """Log of the probability density function. + + Parameters + ---------- + x, s2 : array_like + Arguments. `s2` must be greater than zero. + mu, lmbda, a, b : array_like, optional + Shape parameters. `lmbda`, `a`, and `b` must be greater + than zero. + + Returns + ------- + logpdf : ndarray or scalar + Log of the probability density function. + + """ + invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b) + s2 = args[1] + # Keep it simple for now; lazyselect later, perhaps. + with np.errstate(all='ignore'): + logpdf = np.asarray(self._logpdf(*args)) + logpdf[s2 <= 0] = -np.inf + logpdf[invalid] = np.nan + return logpdf[()] + + def _pdf(self, x, s2, mu, lmbda, a, b): + t1 = np.sqrt(lmbda / (2 * np.pi * s2)) + t2 = b**a / special.gamma(a).astype(a.dtype) + t3 = (1 / s2)**(a + 1) + t4 = np.exp(-(2*b + lmbda*(x - mu)**2) / (2*s2)) + return t1 * t2 * t3 * t4 + + def pdf(self, x, s2, mu=0, lmbda=1, a=1, b=1): + """The probability density function. + + Parameters + ---------- + x, s2 : array_like + Arguments. `s2` must be greater than zero. + mu, lmbda, a, b : array_like, optional + Shape parameters. `lmbda`, `a`, and `b` must be greater + than zero. + + Returns + ------- + logpdf : ndarray or scalar + The probability density function. + + """ + invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b) + s2 = args[1] + # Keep it simple for now; lazyselect later, perhaps. + with np.errstate(all='ignore'): + pdf = np.asarray(self._pdf(*args)) + pdf[s2 <= 0] = 0 + pdf[invalid] = np.nan + return pdf[()] + + def mean(self, mu=0, lmbda=1, a=1, b=1): + """The mean of the distribution. + + Parameters + ---------- + mu, lmbda, a, b : array_like, optional + Shape parameters. `lmbda` and `b` must be greater + than zero, and `a` must be greater than one. + + Returns + ------- + x, s2 : ndarray + The mean of the distribution. + + """ + invalid, args = self._process_shapes(mu, lmbda, a, b) + mu, lmbda, a, b = args + invalid |= ~(a > 1) + mean_x = np.asarray(mu).copy() + mean_s2 = np.asarray(b / (a - 1)) + mean_x[invalid] = np.nan + mean_s2[invalid] = np.nan + return mean_x[()], mean_s2[()] + + def var(self, mu=0, lmbda=1, a=1, b=1): + """The variance of the distribution. + + Parameters + ---------- + mu, lmbda, a, b : array_like, optional + Shape parameters. `lmbda` and `b` must be greater + than zero, and `a` must be greater than two. + + Returns + ------- + x, s2 : ndarray + The variance of the distribution. + + """ + invalid, args = self._process_shapes(mu, lmbda, a, b) + mu, lmbda, a, b = args + invalid_x = invalid | ~(a > 1) + invalid_s2 = invalid | ~(a > 2) + var_x = b / ((a - 1) * lmbda) + var_s2 = b**2 / ((a - 1)**2 * (a - 2)) + var_x, var_s2 = np.asarray(var_x), np.asarray(var_s2) + var_x[invalid_x] = np.nan + var_s2[invalid_s2] = np.nan + return var_x[()], var_s2[()] + + def _process_parameters_pdf(self, x, s2, mu, lmbda, a, b): + args = np.broadcast_arrays(x, s2, mu, lmbda, a, b) + dtype = np.result_type(1.0, *(arg.dtype for arg in args)) + args = [arg.astype(dtype, copy=False) for arg in args] + x, s2, mu, lmbda, a, b = args + invalid = ~((lmbda > 0) & (a > 0) & (b > 0)) + return invalid, args + + def _process_shapes(self, mu, lmbda, a, b): + args = np.broadcast_arrays(mu, lmbda, a, b) + dtype = np.result_type(1.0, *(arg.dtype for arg in args)) + args = [arg.astype(dtype, copy=False) for arg in args] + mu, lmbda, a, b = args + invalid = ~((lmbda > 0) & (a > 0) & (b > 0)) + return invalid, args + + def __call__(self, mu=0, lmbda=1, a=1, b=1, seed=None): + return normal_inverse_gamma_frozen(mu, lmbda, a, b, seed=seed) + + +normal_inverse_gamma = normal_inverse_gamma_gen() + + +class normal_inverse_gamma_frozen(multi_rv_frozen): + + def __init__(self, mu=0, lmbda=1, a=1, b=1, seed=None): + self._dist = normal_inverse_gamma_gen(seed) + self._shapes = mu, lmbda, a, b + + def logpdf(self, x, s2): + return self._dist.logpdf(x, s2, *self._shapes) + + def pdf(self, x, s2): + return self._dist.pdf(x, s2, *self._shapes) + + def mean(self): + return self._dist.mean(*self._shapes) + + def var(self): + return self._dist.var(*self._shapes) + + def rvs(self, size=None, random_state=None): + return self._dist.rvs(*self._shapes, size=size, random_state=random_state) + + +# Set frozen generator docstrings from corresponding docstrings in +# normal_inverse_gamma_gen and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'mean', 'var', 'rvs']: + method = normal_inverse_gamma_gen.__dict__[name] + method_frozen = normal_inverse_gamma_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat(method.__doc__, + mvn_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mvn.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mvn.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8be6c3f0f4be1b734fc308c17dee7facb1cff0ce Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_mvn.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_new_distributions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_new_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..894117e295426b29feafc9b3e5afe7cdfaa1a576 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_new_distributions.py @@ -0,0 +1,375 @@ +import sys + +import numpy as np +from numpy import inf + +from scipy import special +from scipy.stats._distribution_infrastructure import ( + ContinuousDistribution, _RealDomain, _RealParameter, _Parameterization, + _combine_docs) + +__all__ = ['Normal', 'Uniform'] + + +class Normal(ContinuousDistribution): + r"""Normal distribution with prescribed mean and standard deviation. + + The probability density function of the normal distribution is: + + .. math:: + + f(x) = \frac{1}{\sigma \sqrt{2 \pi}} \exp { + \left( -\frac{1}{2}\left( \frac{x - \mu}{\sigma} \right)^2 \right)} + + """ + # `ShiftedScaledDistribution` allows this to be generated automatically from + # an instance of `StandardNormal`, but the normal distribution is so frequently + # used that it's worth a bit of code duplication to get better performance. + _mu_domain = _RealDomain(endpoints=(-inf, inf)) + _sigma_domain = _RealDomain(endpoints=(0, inf)) + _x_support = _RealDomain(endpoints=(-inf, inf)) + + _mu_param = _RealParameter('mu', symbol=r'\mu', domain=_mu_domain, + typical=(-1, 1)) + _sigma_param = _RealParameter('sigma', symbol=r'\sigma', domain=_sigma_domain, + typical=(0.5, 1.5)) + _x_param = _RealParameter('x', domain=_x_support, typical=(-1, 1)) + + _parameterizations = [_Parameterization(_mu_param, _sigma_param)] + + _variable = _x_param + _normalization = 1/np.sqrt(2*np.pi) + _log_normalization = np.log(2*np.pi)/2 + + def __new__(cls, mu=None, sigma=None, **kwargs): + if mu is None and sigma is None: + return super().__new__(StandardNormal) + return super().__new__(cls) + + def __init__(self, *, mu=0., sigma=1., **kwargs): + super().__init__(mu=mu, sigma=sigma, **kwargs) + + def _logpdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._logpdf_formula(self, (x - mu)/sigma) - np.log(sigma) + + def _pdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._pdf_formula(self, (x - mu)/sigma) / sigma + + def _logcdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._logcdf_formula(self, (x - mu)/sigma) + + def _cdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._cdf_formula(self, (x - mu)/sigma) + + def _logccdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._logccdf_formula(self, (x - mu)/sigma) + + def _ccdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._ccdf_formula(self, (x - mu)/sigma) + + def _icdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._icdf_formula(self, x) * sigma + mu + + def _ilogcdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._ilogcdf_formula(self, x) * sigma + mu + + def _iccdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._iccdf_formula(self, x) * sigma + mu + + def _ilogccdf_formula(self, x, *, mu, sigma, **kwargs): + return StandardNormal._ilogccdf_formula(self, x) * sigma + mu + + def _entropy_formula(self, *, mu, sigma, **kwargs): + return StandardNormal._entropy_formula(self) + np.log(abs(sigma)) + + def _logentropy_formula(self, *, mu, sigma, **kwargs): + lH0 = StandardNormal._logentropy_formula(self) + with np.errstate(divide='ignore'): + # sigma = 1 -> log(sigma) = 0 -> log(log(sigma)) = -inf + # Silence the unnecessary runtime warning + lls = np.log(np.log(abs(sigma))+0j) + return special.logsumexp(np.broadcast_arrays(lH0, lls), axis=0) + + def _median_formula(self, *, mu, sigma, **kwargs): + return mu + + def _mode_formula(self, *, mu, sigma, **kwargs): + return mu + + def _moment_raw_formula(self, order, *, mu, sigma, **kwargs): + if order == 0: + return np.ones_like(mu) + elif order == 1: + return mu + else: + return None + _moment_raw_formula.orders = [0, 1] # type: ignore[attr-defined] + + def _moment_central_formula(self, order, *, mu, sigma, **kwargs): + if order == 0: + return np.ones_like(mu) + elif order % 2: + return np.zeros_like(mu) + else: + # exact is faster (and obviously more accurate) for reasonable orders + return sigma**order * special.factorial2(int(order) - 1, exact=True) + + def _sample_formula(self, sample_shape, full_shape, rng, *, mu, sigma, **kwargs): + return rng.normal(loc=mu, scale=sigma, size=full_shape)[()] + + +def _log_diff(log_p, log_q): + return special.logsumexp([log_p, log_q+np.pi*1j], axis=0) + + +class StandardNormal(Normal): + r"""Standard normal distribution. + + The probability density function of the standard normal distribution is: + + .. math:: + + f(x) = \frac{1}{\sqrt{2 \pi}} \exp \left( -\frac{1}{2} x^2 \right) + + """ + _x_support = _RealDomain(endpoints=(-inf, inf)) + _x_param = _RealParameter('x', domain=_x_support, typical=(-5, 5)) + _variable = _x_param + _parameterizations = [] + _normalization = 1/np.sqrt(2*np.pi) + _log_normalization = np.log(2*np.pi)/2 + mu = np.float64(0.) + sigma = np.float64(1.) + + def __init__(self, **kwargs): + ContinuousDistribution.__init__(self, **kwargs) + + def _logpdf_formula(self, x, **kwargs): + return -(self._log_normalization + x**2/2) + + def _pdf_formula(self, x, **kwargs): + return self._normalization * np.exp(-x**2/2) + + def _logcdf_formula(self, x, **kwargs): + return special.log_ndtr(x) + + def _cdf_formula(self, x, **kwargs): + return special.ndtr(x) + + def _logccdf_formula(self, x, **kwargs): + return special.log_ndtr(-x) + + def _ccdf_formula(self, x, **kwargs): + return special.ndtr(-x) + + def _icdf_formula(self, x, **kwargs): + return special.ndtri(x) + + def _ilogcdf_formula(self, x, **kwargs): + return special.ndtri_exp(x) + + def _iccdf_formula(self, x, **kwargs): + return -special.ndtri(x) + + def _ilogccdf_formula(self, x, **kwargs): + return -special.ndtri_exp(x) + + def _entropy_formula(self, **kwargs): + return (1 + np.log(2*np.pi))/2 + + def _logentropy_formula(self, **kwargs): + return np.log1p(np.log(2*np.pi)) - np.log(2) + + def _median_formula(self, **kwargs): + return 0 + + def _mode_formula(self, **kwargs): + return 0 + + def _moment_raw_formula(self, order, **kwargs): + raw_moments = {0: 1, 1: 0, 2: 1, 3: 0, 4: 3, 5: 0} + return raw_moments.get(order, None) + + def _moment_central_formula(self, order, **kwargs): + return self._moment_raw_formula(order, **kwargs) + + def _moment_standardized_formula(self, order, **kwargs): + return self._moment_raw_formula(order, **kwargs) + + def _sample_formula(self, sample_shape, full_shape, rng, **kwargs): + return rng.normal(size=full_shape)[()] + + +# currently for testing only +class _LogUniform(ContinuousDistribution): + r"""Log-uniform distribution. + + The probability density function of the log-uniform distribution is: + + .. math:: + + f(x; a, b) = \frac{1} + {x (\log(b) - \log(a))} + + If :math:`\log(X)` is a random variable that follows a uniform distribution + between :math:`\log(a)` and :math:`\log(b)`, then :math:`X` is log-uniformly + distributed with shape parameters :math:`a` and :math:`b`. + + """ + + _a_domain = _RealDomain(endpoints=(0, inf)) + _b_domain = _RealDomain(endpoints=('a', inf)) + _log_a_domain = _RealDomain(endpoints=(-inf, inf)) + _log_b_domain = _RealDomain(endpoints=('log_a', inf)) + _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True)) + + _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9)) + _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3)) + _log_a_param = _RealParameter('log_a', symbol=r'\log(a)', + domain=_log_a_domain, typical=(-3, -0.1)) + _log_b_param = _RealParameter('log_b', symbol=r'\log(b)', + domain=_log_b_domain, typical=(0.1, 3)) + _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b')) + + _b_domain.define_parameters(_a_param) + _log_b_domain.define_parameters(_log_a_param) + _x_support.define_parameters(_a_param, _b_param) + + _parameterizations = [_Parameterization(_log_a_param, _log_b_param), + _Parameterization(_a_param, _b_param)] + _variable = _x_param + + def __init__(self, *, a=None, b=None, log_a=None, log_b=None, **kwargs): + super().__init__(a=a, b=b, log_a=log_a, log_b=log_b, **kwargs) + + def _process_parameters(self, a=None, b=None, log_a=None, log_b=None, **kwargs): + a = np.exp(log_a) if a is None else a + b = np.exp(log_b) if b is None else b + log_a = np.log(a) if log_a is None else log_a + log_b = np.log(b) if log_b is None else log_b + kwargs.update(dict(a=a, b=b, log_a=log_a, log_b=log_b)) + return kwargs + + # def _logpdf_formula(self, x, *, log_a, log_b, **kwargs): + # return -np.log(x) - np.log(log_b - log_a) + + def _pdf_formula(self, x, *, log_a, log_b, **kwargs): + return ((log_b - log_a)*x)**-1 + + # def _cdf_formula(self, x, *, log_a, log_b, **kwargs): + # return (np.log(x) - log_a)/(log_b - log_a) + + def _moment_raw_formula(self, order, log_a, log_b, **kwargs): + if order == 0: + return self._one + t1 = self._one / (log_b - log_a) / order + t2 = np.real(np.exp(_log_diff(order * log_b, order * log_a))) + return t1 * t2 + + +class Uniform(ContinuousDistribution): + r"""Uniform distribution. + + The probability density function of the uniform distribution is: + + .. math:: + + f(x; a, b) = \frac{1} + {b - a} + + """ + + _a_domain = _RealDomain(endpoints=(-inf, inf)) + _b_domain = _RealDomain(endpoints=('a', inf)) + _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True)) + + _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9)) + _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3)) + _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b')) + + _b_domain.define_parameters(_a_param) + _x_support.define_parameters(_a_param, _b_param) + + _parameterizations = [_Parameterization(_a_param, _b_param)] + _variable = _x_param + + def __init__(self, *, a=None, b=None, **kwargs): + super().__init__(a=a, b=b, **kwargs) + + def _process_parameters(self, a=None, b=None, ab=None, **kwargs): + ab = b - a + kwargs.update(dict(a=a, b=b, ab=ab)) + return kwargs + + def _logpdf_formula(self, x, *, ab, **kwargs): + return np.where(np.isnan(x), np.nan, -np.log(ab)) + + def _pdf_formula(self, x, *, ab, **kwargs): + return np.where(np.isnan(x), np.nan, 1/ab) + + def _logcdf_formula(self, x, *, a, ab, **kwargs): + with np.errstate(divide='ignore'): + return np.log(x - a) - np.log(ab) + + def _cdf_formula(self, x, *, a, ab, **kwargs): + return (x - a) / ab + + def _logccdf_formula(self, x, *, b, ab, **kwargs): + with np.errstate(divide='ignore'): + return np.log(b - x) - np.log(ab) + + def _ccdf_formula(self, x, *, b, ab, **kwargs): + return (b - x) / ab + + def _icdf_formula(self, p, *, a, ab, **kwargs): + return a + ab*p + + def _iccdf_formula(self, p, *, b, ab, **kwargs): + return b - ab*p + + def _entropy_formula(self, *, ab, **kwargs): + return np.log(ab) + + def _mode_formula(self, *, a, b, ab, **kwargs): + return a + 0.5*ab + + def _median_formula(self, *, a, b, ab, **kwargs): + return a + 0.5*ab + + def _moment_raw_formula(self, order, a, b, ab, **kwargs): + np1 = order + 1 + return (b**np1 - a**np1) / (np1 * ab) + + def _moment_central_formula(self, order, ab, **kwargs): + return ab**2/12 if order == 2 else None + + _moment_central_formula.orders = [2] # type: ignore[attr-defined] + + def _sample_formula(self, sample_shape, full_shape, rng, a, b, ab, **kwargs): + try: + return rng.uniform(a, b, size=full_shape)[()] + except OverflowError: # happens when there are NaNs + return rng.uniform(0, 1, size=full_shape)*ab + a + + +class _Gamma(ContinuousDistribution): + # Gamma distribution for testing only + _a_domain = _RealDomain(endpoints=(0, inf)) + _x_support = _RealDomain(endpoints=(0, inf), inclusive=(False, False)) + + _a_param = _RealParameter('a', domain=_a_domain, typical=(0.1, 10)) + _x_param = _RealParameter('x', domain=_x_support, typical=(0.1, 10)) + + _parameterizations = [_Parameterization(_a_param)] + _variable = _x_param + + def _pdf_formula(self, x, *, a, **kwargs): + return x ** (a - 1) * np.exp(-x) / special.gamma(a) + + +# Distribution classes need only define the summary and beginning of the extended +# summary portion of the class documentation. All other documentation, including +# examples, is generated automatically. +_module = sys.modules[__name__].__dict__ +for dist_name in __all__: + _module[dist_name].__doc__ = _combine_docs(_module[dist_name]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_odds_ratio.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_odds_ratio.py new file mode 100644 index 0000000000000000000000000000000000000000..bc593f5adc9a700c618c721b6c37c801809d868b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_odds_ratio.py @@ -0,0 +1,466 @@ +import numpy as np + +from scipy.special import ndtri +from scipy.optimize import brentq +from ._discrete_distns import nchypergeom_fisher +from ._common import ConfidenceInterval + + +def _sample_odds_ratio(table): + """ + Given a table [[a, b], [c, d]], compute a*d/(b*c). + + Return nan if the numerator and denominator are 0. + Return inf if just the denominator is 0. + """ + # table must be a 2x2 numpy array. + if table[1, 0] > 0 and table[0, 1] > 0: + oddsratio = table[0, 0] * table[1, 1] / (table[1, 0] * table[0, 1]) + elif table[0, 0] == 0 or table[1, 1] == 0: + oddsratio = np.nan + else: + oddsratio = np.inf + return oddsratio + + +def _solve(func): + """ + Solve func(nc) = 0. func must be an increasing function. + """ + # We could just as well call the variable `x` instead of `nc`, but we + # always call this function with functions for which nc (the noncentrality + # parameter) is the variable for which we are solving. + nc = 1.0 + value = func(nc) + if value == 0: + return nc + + # Multiplicative factor by which to increase or decrease nc when + # searching for a bracketing interval. + factor = 2.0 + # Find a bracketing interval. + if value > 0: + nc /= factor + while func(nc) > 0: + nc /= factor + lo = nc + hi = factor*nc + else: + nc *= factor + while func(nc) < 0: + nc *= factor + lo = nc/factor + hi = nc + + # lo and hi bracket the solution for nc. + nc = brentq(func, lo, hi, xtol=1e-13) + return nc + + +def _nc_hypergeom_mean_inverse(x, M, n, N): + """ + For the given noncentral hypergeometric parameters x, M, n,and N + (table[0,0], total, row 0 sum and column 0 sum, resp., of a 2x2 + contingency table), find the noncentrality parameter of Fisher's + noncentral hypergeometric distribution whose mean is x. + """ + nc = _solve(lambda nc: nchypergeom_fisher.mean(M, n, N, nc) - x) + return nc + + +def _hypergeom_params_from_table(table): + # The notation M, n and N is consistent with stats.hypergeom and + # stats.nchypergeom_fisher. + x = table[0, 0] + M = table.sum() + n = table[0].sum() + N = table[:, 0].sum() + return x, M, n, N + + +def _ci_upper(table, alpha): + """ + Compute the upper end of the confidence interval. + """ + if _sample_odds_ratio(table) == np.inf: + return np.inf + + x, M, n, N = _hypergeom_params_from_table(table) + + # nchypergeom_fisher.cdf is a decreasing function of nc, so we negate + # it in the lambda expression. + nc = _solve(lambda nc: -nchypergeom_fisher.cdf(x, M, n, N, nc) + alpha) + return nc + + +def _ci_lower(table, alpha): + """ + Compute the lower end of the confidence interval. + """ + if _sample_odds_ratio(table) == 0: + return 0 + + x, M, n, N = _hypergeom_params_from_table(table) + + nc = _solve(lambda nc: nchypergeom_fisher.sf(x - 1, M, n, N, nc) - alpha) + return nc + + +def _conditional_oddsratio(table): + """ + Conditional MLE of the odds ratio for the 2x2 contingency table. + """ + x, M, n, N = _hypergeom_params_from_table(table) + # Get the bounds of the support. The support of the noncentral + # hypergeometric distribution with parameters M, n, and N is the same + # for all values of the noncentrality parameter, so we can use 1 here. + lo, hi = nchypergeom_fisher.support(M, n, N, 1) + + # Check if x is at one of the extremes of the support. If so, we know + # the odds ratio is either 0 or inf. + if x == lo: + # x is at the low end of the support. + return 0 + if x == hi: + # x is at the high end of the support. + return np.inf + + nc = _nc_hypergeom_mean_inverse(x, M, n, N) + return nc + + +def _conditional_oddsratio_ci(table, confidence_level=0.95, + alternative='two-sided'): + """ + Conditional exact confidence interval for the odds ratio. + """ + if alternative == 'two-sided': + alpha = 0.5*(1 - confidence_level) + lower = _ci_lower(table, alpha) + upper = _ci_upper(table, alpha) + elif alternative == 'less': + lower = 0.0 + upper = _ci_upper(table, 1 - confidence_level) + else: + # alternative == 'greater' + lower = _ci_lower(table, 1 - confidence_level) + upper = np.inf + + return lower, upper + + +def _sample_odds_ratio_ci(table, confidence_level=0.95, + alternative='two-sided'): + oddsratio = _sample_odds_ratio(table) + log_or = np.log(oddsratio) + se = np.sqrt((1/table).sum()) + if alternative == 'less': + z = ndtri(confidence_level) + loglow = -np.inf + loghigh = log_or + z*se + elif alternative == 'greater': + z = ndtri(confidence_level) + loglow = log_or - z*se + loghigh = np.inf + else: + # alternative is 'two-sided' + z = ndtri(0.5*confidence_level + 0.5) + loglow = log_or - z*se + loghigh = log_or + z*se + + return np.exp(loglow), np.exp(loghigh) + + +class OddsRatioResult: + """ + Result of `scipy.stats.contingency.odds_ratio`. See the + docstring for `odds_ratio` for more details. + + Attributes + ---------- + statistic : float + The computed odds ratio. + + * If `kind` is ``'sample'``, this is sample (or unconditional) + estimate, given by + ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``. + * If `kind` is ``'conditional'``, this is the conditional + maximum likelihood estimate for the odds ratio. It is + the noncentrality parameter of Fisher's noncentral + hypergeometric distribution with the same hypergeometric + parameters as `table` and whose mean is ``table[0, 0]``. + + Methods + ------- + confidence_interval : + Confidence interval for the odds ratio. + """ + + def __init__(self, _table, _kind, statistic): + # for now, no need to make _table and _kind public, since this sort of + # information is returned in very few `scipy.stats` results + self._table = _table + self._kind = _kind + self.statistic = statistic + + def __repr__(self): + return f"OddsRatioResult(statistic={self.statistic})" + + def confidence_interval(self, confidence_level=0.95, + alternative='two-sided'): + """ + Confidence interval for the odds ratio. + + Parameters + ---------- + confidence_level: float + Desired confidence level for the confidence interval. + The value must be given as a fraction between 0 and 1. + Default is 0.95 (meaning 95%). + + alternative : {'two-sided', 'less', 'greater'}, optional + The alternative hypothesis of the hypothesis test to which the + confidence interval corresponds. That is, suppose the null + hypothesis is that the true odds ratio equals ``OR`` and the + confidence interval is ``(low, high)``. Then the following options + for `alternative` are available (default is 'two-sided'): + + * 'two-sided': the true odds ratio is not equal to ``OR``. There + is evidence against the null hypothesis at the chosen + `confidence_level` if ``high < OR`` or ``low > OR``. + * 'less': the true odds ratio is less than ``OR``. The ``low`` end + of the confidence interval is 0, and there is evidence against + the null hypothesis at the chosen `confidence_level` if + ``high < OR``. + * 'greater': the true odds ratio is greater than ``OR``. The + ``high`` end of the confidence interval is ``np.inf``, and there + is evidence against the null hypothesis at the chosen + `confidence_level` if ``low > OR``. + + Returns + ------- + ci : ``ConfidenceInterval`` instance + The confidence interval, represented as an object with + attributes ``low`` and ``high``. + + Notes + ----- + When `kind` is ``'conditional'``, the limits of the confidence + interval are the conditional "exact confidence limits" as described + by Fisher [1]_. The conditional odds ratio and confidence interval are + also discussed in Section 4.1.2 of the text by Sahai and Khurshid [2]_. + + When `kind` is ``'sample'``, the confidence interval is computed + under the assumption that the logarithm of the odds ratio is normally + distributed with standard error given by:: + + se = sqrt(1/a + 1/b + 1/c + 1/d) + + where ``a``, ``b``, ``c`` and ``d`` are the elements of the + contingency table. (See, for example, [2]_, section 3.1.3.2, + or [3]_, section 2.3.3). + + References + ---------- + .. [1] R. A. Fisher (1935), The logic of inductive inference, + Journal of the Royal Statistical Society, Vol. 98, No. 1, + pp. 39-82. + .. [2] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology: + Methods, Techniques, and Applications, CRC Press LLC, Boca + Raton, Florida. + .. [3] Alan Agresti, An Introduction to Categorical Data Analysis + (second edition), Wiley, Hoboken, NJ, USA (2007). + """ + if alternative not in ['two-sided', 'less', 'greater']: + raise ValueError("`alternative` must be 'two-sided', 'less' or " + "'greater'.") + + if confidence_level < 0 or confidence_level > 1: + raise ValueError('confidence_level must be between 0 and 1') + + if self._kind == 'conditional': + ci = self._conditional_odds_ratio_ci(confidence_level, alternative) + else: + ci = self._sample_odds_ratio_ci(confidence_level, alternative) + return ci + + def _conditional_odds_ratio_ci(self, confidence_level=0.95, + alternative='two-sided'): + """ + Confidence interval for the conditional odds ratio. + """ + + table = self._table + if 0 in table.sum(axis=0) or 0 in table.sum(axis=1): + # If both values in a row or column are zero, the p-value is 1, + # the odds ratio is NaN and the confidence interval is (0, inf). + ci = (0, np.inf) + else: + ci = _conditional_oddsratio_ci(table, + confidence_level=confidence_level, + alternative=alternative) + return ConfidenceInterval(low=ci[0], high=ci[1]) + + def _sample_odds_ratio_ci(self, confidence_level=0.95, + alternative='two-sided'): + """ + Confidence interval for the sample odds ratio. + """ + if confidence_level < 0 or confidence_level > 1: + raise ValueError('confidence_level must be between 0 and 1') + + table = self._table + if 0 in table.sum(axis=0) or 0 in table.sum(axis=1): + # If both values in a row or column are zero, the p-value is 1, + # the odds ratio is NaN and the confidence interval is (0, inf). + ci = (0, np.inf) + else: + ci = _sample_odds_ratio_ci(table, + confidence_level=confidence_level, + alternative=alternative) + return ConfidenceInterval(low=ci[0], high=ci[1]) + + +def odds_ratio(table, *, kind='conditional'): + r""" + Compute the odds ratio for a 2x2 contingency table. + + Parameters + ---------- + table : array_like of ints + A 2x2 contingency table. Elements must be non-negative integers. + kind : str, optional + Which kind of odds ratio to compute, either the sample + odds ratio (``kind='sample'``) or the conditional odds ratio + (``kind='conditional'``). Default is ``'conditional'``. + + Returns + ------- + result : `~scipy.stats._result_classes.OddsRatioResult` instance + The returned object has two computed attributes: + + statistic : float + * If `kind` is ``'sample'``, this is sample (or unconditional) + estimate, given by + ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``. + * If `kind` is ``'conditional'``, this is the conditional + maximum likelihood estimate for the odds ratio. It is + the noncentrality parameter of Fisher's noncentral + hypergeometric distribution with the same hypergeometric + parameters as `table` and whose mean is ``table[0, 0]``. + + The object has the method `confidence_interval` that computes + the confidence interval of the odds ratio. + + See Also + -------- + scipy.stats.fisher_exact + relative_risk + :ref:`hypothesis_odds_ratio` : Extended example + + Notes + ----- + The conditional odds ratio was discussed by Fisher (see "Example 1" + of [1]_). Texts that cover the odds ratio include [2]_ and [3]_. + + .. versionadded:: 1.10.0 + + References + ---------- + .. [1] R. A. Fisher (1935), The logic of inductive inference, + Journal of the Royal Statistical Society, Vol. 98, No. 1, + pp. 39-82. + .. [2] Breslow NE, Day NE (1980). Statistical methods in cancer research. + Volume I - The analysis of case-control studies. IARC Sci Publ. + (32):5-338. PMID: 7216345. (See section 4.2.) + .. [3] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology: + Methods, Techniques, and Applications, CRC Press LLC, Boca + Raton, Florida. + + Examples + -------- + In epidemiology, individuals are classified as "exposed" or + "unexposed" to some factor or treatment. If the occurrence of some + illness is under study, those who have the illness are often + classified as "cases", and those without it are "noncases". The + counts of the occurrences of these classes gives a contingency + table:: + + exposed unexposed + cases a b + noncases c d + + The sample odds ratio may be written ``(a/c) / (b/d)``. ``a/c`` can + be interpreted as the odds of a case occurring in the exposed group, + and ``b/d`` as the odds of a case occurring in the unexposed group. + The sample odds ratio is the ratio of these odds. If the odds ratio + is greater than 1, it suggests that there is a positive association + between being exposed and being a case. + + Interchanging the rows or columns of the contingency table inverts + the odds ratio, so it is important to understand the meaning of labels + given to the rows and columns of the table when interpreting the + odds ratio. + + Consider a hypothetical example where it is hypothesized that exposure to a + certain chemical is associated with increased occurrence of a certain + disease. Suppose we have the following table for a collection of 410 people:: + + exposed unexposed + cases 7 15 + noncases 58 472 + + The question we ask is "Is exposure to the chemical associated with + increased risk of the disease?" + + Compute the odds ratio: + + >>> from scipy.stats.contingency import odds_ratio + >>> res = odds_ratio([[7, 15], [58, 472]]) + >>> res.statistic + 3.7836687705553493 + + For this sample, the odds of getting the disease for those who have been + exposed to the chemical are almost 3.8 times that of those who have not been + exposed. + + We can compute the 95% confidence interval for the odds ratio: + + >>> res.confidence_interval(confidence_level=0.95) + ConfidenceInterval(low=1.2514829132266785, high=10.363493716701269) + + The 95% confidence interval for the conditional odds ratio is approximately + (1.25, 10.4). + + For a more detailed example, see :ref:`hypothesis_odds_ratio`. + """ + if kind not in ['conditional', 'sample']: + raise ValueError("`kind` must be 'conditional' or 'sample'.") + + c = np.asarray(table) + + if c.shape != (2, 2): + raise ValueError(f"Invalid shape {c.shape}. The input `table` must be " + "of shape (2, 2).") + + if not np.issubdtype(c.dtype, np.integer): + raise ValueError("`table` must be an array of integers, but got " + f"type {c.dtype}") + c = c.astype(np.int64) + + if np.any(c < 0): + raise ValueError("All values in `table` must be nonnegative.") + + if 0 in c.sum(axis=0) or 0 in c.sum(axis=1): + # If both values in a row or column are zero, the p-value is NaN and + # the odds ratio is NaN. + result = OddsRatioResult(_table=c, _kind=kind, statistic=np.nan) + return result + + if kind == 'sample': + oddsratio = _sample_odds_ratio(c) + else: # kind is 'conditional' + oddsratio = _conditional_oddsratio(c) + + result = OddsRatioResult(_table=c, _kind=kind, statistic=oddsratio) + return result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_page_trend_test.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_page_trend_test.py new file mode 100644 index 0000000000000000000000000000000000000000..87a4d0d17c07ce609cc575fc7dc61af75d2b9c51 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_page_trend_test.py @@ -0,0 +1,479 @@ +from itertools import permutations +import numpy as np +import math +from ._continuous_distns import norm +import scipy.stats +from dataclasses import dataclass + + +@dataclass +class PageTrendTestResult: + statistic: float + pvalue: float + method: str + + +def page_trend_test(data, ranked=False, predicted_ranks=None, method='auto'): + r""" + Perform Page's Test, a measure of trend in observations between treatments. + + Page's Test (also known as Page's :math:`L` test) is useful when: + + * there are :math:`n \geq 3` treatments, + * :math:`m \geq 2` subjects are observed for each treatment, and + * the observations are hypothesized to have a particular order. + + Specifically, the test considers the null hypothesis that + + .. math:: + + m_1 = m_2 = m_3 \cdots = m_n, + + where :math:`m_j` is the mean of the observed quantity under treatment + :math:`j`, against the alternative hypothesis that + + .. math:: + + m_1 \leq m_2 \leq m_3 \leq \cdots \leq m_n, + + where at least one inequality is strict. + + As noted by [4]_, Page's :math:`L` test has greater statistical power than + the Friedman test against the alternative that there is a difference in + trend, as Friedman's test only considers a difference in the means of the + observations without considering their order. Whereas Spearman :math:`\rho` + considers the correlation between the ranked observations of two variables + (e.g. the airspeed velocity of a swallow vs. the weight of the coconut it + carries), Page's :math:`L` is concerned with a trend in an observation + (e.g. the airspeed velocity of a swallow) across several distinct + treatments (e.g. carrying each of five coconuts of different weight) even + as the observation is repeated with multiple subjects (e.g. one European + swallow and one African swallow). + + Parameters + ---------- + data : array-like + A :math:`m \times n` array; the element in row :math:`i` and + column :math:`j` is the observation corresponding with subject + :math:`i` and treatment :math:`j`. By default, the columns are + assumed to be arranged in order of increasing predicted mean. + + ranked : boolean, optional + By default, `data` is assumed to be observations rather than ranks; + it will be ranked with `scipy.stats.rankdata` along ``axis=1``. If + `data` is provided in the form of ranks, pass argument ``True``. + + predicted_ranks : array-like, optional + The predicted ranks of the column means. If not specified, + the columns are assumed to be arranged in order of increasing + predicted mean, so the default `predicted_ranks` are + :math:`[1, 2, \dots, n-1, n]`. + + method : {'auto', 'asymptotic', 'exact'}, optional + Selects the method used to calculate the *p*-value. The following + options are available. + + * 'auto': selects between 'exact' and 'asymptotic' to + achieve reasonably accurate results in reasonable time (default) + * 'asymptotic': compares the standardized test statistic against + the normal distribution + * 'exact': computes the exact *p*-value by comparing the observed + :math:`L` statistic against those realized by all possible + permutations of ranks (under the null hypothesis that each + permutation is equally likely) + + Returns + ------- + res : PageTrendTestResult + An object containing attributes: + + statistic : float + Page's :math:`L` test statistic. + pvalue : float + The associated *p*-value + method : {'asymptotic', 'exact'} + The method used to compute the *p*-value + + See Also + -------- + rankdata, friedmanchisquare, spearmanr + + Notes + ----- + As noted in [1]_, "the :math:`n` 'treatments' could just as well represent + :math:`n` objects or events or performances or persons or trials ranked." + Similarly, the :math:`m` 'subjects' could equally stand for :math:`m` + "groupings by ability or some other control variable, or judges doing + the ranking, or random replications of some other sort." + + The procedure for calculating the :math:`L` statistic, adapted from + [1]_, is: + + 1. "Predetermine with careful logic the appropriate hypotheses + concerning the predicted ordering of the experimental results. + If no reasonable basis for ordering any treatments is known, the + :math:`L` test is not appropriate." + 2. "As in other experiments, determine at what level of confidence + you will reject the null hypothesis that there is no agreement of + experimental results with the monotonic hypothesis." + 3. "Cast the experimental material into a two-way table of :math:`n` + columns (treatments, objects ranked, conditions) and :math:`m` + rows (subjects, replication groups, levels of control variables)." + 4. "When experimental observations are recorded, rank them across each + row", e.g. ``ranks = scipy.stats.rankdata(data, axis=1)``. + 5. "Add the ranks in each column", e.g. + ``colsums = np.sum(ranks, axis=0)``. + 6. "Multiply each sum of ranks by the predicted rank for that same + column", e.g. ``products = predicted_ranks * colsums``. + 7. "Sum all such products", e.g. ``L = products.sum()``. + + [1]_ continues by suggesting use of the standardized statistic + + .. math:: + + \chi_L^2 = \frac{\left[12L-3mn(n+1)^2\right]^2}{mn^2(n^2-1)(n+1)} + + "which is distributed approximately as chi-square with 1 degree of + freedom. The ordinary use of :math:`\chi^2` tables would be + equivalent to a two-sided test of agreement. If a one-sided test + is desired, *as will almost always be the case*, the probability + discovered in the chi-square table should be *halved*." + + However, this standardized statistic does not distinguish between the + observed values being well correlated with the predicted ranks and being + _anti_-correlated with the predicted ranks. Instead, we follow [2]_ + and calculate the standardized statistic + + .. math:: + + \Lambda = \frac{L - E_0}{\sqrt{V_0}}, + + where :math:`E_0 = \frac{1}{4} mn(n+1)^2` and + :math:`V_0 = \frac{1}{144} mn^2(n+1)(n^2-1)`, "which is asymptotically + normal under the null hypothesis". + + The *p*-value for ``method='exact'`` is generated by comparing the observed + value of :math:`L` against the :math:`L` values generated for all + :math:`(n!)^m` possible permutations of ranks. The calculation is performed + using the recursive method of [5]. + + The *p*-values are not adjusted for the possibility of ties. When + ties are present, the reported ``'exact'`` *p*-values may be somewhat + larger (i.e. more conservative) than the true *p*-value [2]_. The + ``'asymptotic'``` *p*-values, however, tend to be smaller (i.e. less + conservative) than the ``'exact'`` *p*-values. + + References + ---------- + .. [1] Ellis Batten Page, "Ordered hypotheses for multiple treatments: + a significant test for linear ranks", *Journal of the American + Statistical Association* 58(301), p. 216--230, 1963. + + .. [2] Markus Neuhauser, *Nonparametric Statistical Test: A computational + approach*, CRC Press, p. 150--152, 2012. + + .. [3] Statext LLC, "Page's L Trend Test - Easy Statistics", *Statext - + Statistics Study*, https://www.statext.com/practice/PageTrendTest03.php, + Accessed July 12, 2020. + + .. [4] "Page's Trend Test", *Wikipedia*, WikimediaFoundation, + https://en.wikipedia.org/wiki/Page%27s_trend_test, + Accessed July 12, 2020. + + .. [5] Robert E. Odeh, "The exact distribution of Page's L-statistic in + the two-way layout", *Communications in Statistics - Simulation and + Computation*, 6(1), p. 49--61, 1977. + + Examples + -------- + We use the example from [3]_: 10 students are asked to rate three + teaching methods - tutorial, lecture, and seminar - on a scale of 1-5, + with 1 being the lowest and 5 being the highest. We have decided that + a confidence level of 99% is required to reject the null hypothesis in + favor of our alternative: that the seminar will have the highest ratings + and the tutorial will have the lowest. Initially, the data have been + tabulated with each row representing an individual student's ratings of + the three methods in the following order: tutorial, lecture, seminar. + + >>> table = [[3, 4, 3], + ... [2, 2, 4], + ... [3, 3, 5], + ... [1, 3, 2], + ... [2, 3, 2], + ... [2, 4, 5], + ... [1, 2, 4], + ... [3, 4, 4], + ... [2, 4, 5], + ... [1, 3, 4]] + + Because the tutorial is hypothesized to have the lowest ratings, the + column corresponding with tutorial rankings should be first; the seminar + is hypothesized to have the highest ratings, so its column should be last. + Since the columns are already arranged in this order of increasing + predicted mean, we can pass the table directly into `page_trend_test`. + + >>> from scipy.stats import page_trend_test + >>> res = page_trend_test(table) + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822, + method='exact') + + This *p*-value indicates that there is a 0.1819% chance that + the :math:`L` statistic would reach such an extreme value under the null + hypothesis. Because 0.1819% is less than 1%, we have evidence to reject + the null hypothesis in favor of our alternative at a 99% confidence level. + + The value of the :math:`L` statistic is 133.5. To check this manually, + we rank the data such that high scores correspond with high ranks, settling + ties with an average rank: + + >>> from scipy.stats import rankdata + >>> ranks = rankdata(table, axis=1) + >>> ranks + array([[1.5, 3. , 1.5], + [1.5, 1.5, 3. ], + [1.5, 1.5, 3. ], + [1. , 3. , 2. ], + [1.5, 3. , 1.5], + [1. , 2. , 3. ], + [1. , 2. , 3. ], + [1. , 2.5, 2.5], + [1. , 2. , 3. ], + [1. , 2. , 3. ]]) + + We add the ranks within each column, multiply the sums by the + predicted ranks, and sum the products. + + >>> import numpy as np + >>> m, n = ranks.shape + >>> predicted_ranks = np.arange(1, n+1) + >>> L = (predicted_ranks * np.sum(ranks, axis=0)).sum() + >>> res.statistic == L + True + + As presented in [3]_, the asymptotic approximation of the *p*-value is the + survival function of the normal distribution evaluated at the standardized + test statistic: + + >>> from scipy.stats import norm + >>> E0 = (m*n*(n+1)**2)/4 + >>> V0 = (m*n**2*(n+1)*(n**2-1))/144 + >>> Lambda = (L-E0)/np.sqrt(V0) + >>> p = norm.sf(Lambda) + >>> p + 0.0012693433690751756 + + This does not precisely match the *p*-value reported by `page_trend_test` + above. The asymptotic distribution is not very accurate, nor conservative, + for :math:`m \leq 12` and :math:`n \leq 8`, so `page_trend_test` chose to + use ``method='exact'`` based on the dimensions of the table and the + recommendations in Page's original paper [1]_. To override + `page_trend_test`'s choice, provide the `method` argument. + + >>> res = page_trend_test(table, method="asymptotic") + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0012693433690751756, + method='asymptotic') + + If the data are already ranked, we can pass in the ``ranks`` instead of + the ``table`` to save computation time. + + >>> res = page_trend_test(ranks, # ranks of data + ... ranked=True, # data is already ranked + ... ) + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822, + method='exact') + + Suppose the raw data had been tabulated in an order different from the + order of predicted means, say lecture, seminar, tutorial. + + >>> table = np.asarray(table)[:, [1, 2, 0]] + + Since the arrangement of this table is not consistent with the assumed + ordering, we can either rearrange the table or provide the + `predicted_ranks`. Remembering that the lecture is predicted + to have the middle rank, the seminar the highest, and tutorial the lowest, + we pass: + + >>> res = page_trend_test(table, # data as originally tabulated + ... predicted_ranks=[2, 3, 1], # our predicted order + ... ) + >>> res + PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822, + method='exact') + + """ + + # Possible values of the method parameter and the corresponding function + # used to evaluate the p value + methods = {"asymptotic": _l_p_asymptotic, + "exact": _l_p_exact, + "auto": None} + if method not in methods: + raise ValueError(f"`method` must be in {set(methods)}") + + ranks = np.asarray(data) + if ranks.ndim != 2: # TODO: relax this to accept 3d arrays? + raise ValueError("`data` must be a 2d array.") + + m, n = ranks.shape + if m < 2 or n < 3: + raise ValueError("Page's L is only appropriate for data with two " + "or more rows and three or more columns.") + + if np.any(np.isnan(data)): + raise ValueError("`data` contains NaNs, which cannot be ranked " + "meaningfully") + + # ensure NumPy array and rank the data if it's not already ranked + if ranked: + # Only a basic check on whether data is ranked. Checking that the data + # is properly ranked could take as much time as ranking it. + if not (ranks.min() >= 1 and ranks.max() <= ranks.shape[1]): + raise ValueError("`data` is not properly ranked. Rank the data or " + "pass `ranked=False`.") + else: + ranks = scipy.stats.rankdata(data, axis=-1) + + # generate predicted ranks if not provided, ensure valid NumPy array + if predicted_ranks is None: + predicted_ranks = np.arange(1, n+1) + else: + predicted_ranks = np.asarray(predicted_ranks) + if (predicted_ranks.ndim < 1 or + (set(predicted_ranks) != set(range(1, n+1)) or + len(predicted_ranks) != n)): + raise ValueError(f"`predicted_ranks` must include each integer " + f"from 1 to {n} (the number of columns in " + f"`data`) exactly once.") + + if not isinstance(ranked, bool): + raise TypeError("`ranked` must be boolean.") + + # Calculate the L statistic + L = _l_vectorized(ranks, predicted_ranks) + + # Calculate the p-value + if method == "auto": + method = _choose_method(ranks) + p_fun = methods[method] # get the function corresponding with the method + p = p_fun(L, m, n) + + page_result = PageTrendTestResult(statistic=L, pvalue=p, method=method) + return page_result + + +def _choose_method(ranks): + '''Choose method for computing p-value automatically''' + m, n = ranks.shape + if n > 8 or (m > 12 and n > 3) or m > 20: # as in [1], [4] + method = "asymptotic" + else: + method = "exact" + return method + + +def _l_vectorized(ranks, predicted_ranks): + '''Calculate's Page's L statistic for each page of a 3d array''' + colsums = ranks.sum(axis=-2, keepdims=True) + products = predicted_ranks * colsums + Ls = products.sum(axis=-1) + Ls = Ls[0] if Ls.size == 1 else Ls.ravel() + return Ls + + +def _l_p_asymptotic(L, m, n): + '''Calculate the p-value of Page's L from the asymptotic distribution''' + # Using [1] as a reference, the asymptotic p-value would be calculated as: + # chi_L = (12*L - 3*m*n*(n+1)**2)**2/(m*n**2*(n**2-1)*(n+1)) + # p = chi2.sf(chi_L, df=1, loc=0, scale=1)/2 + # but this is insensitive to the direction of the hypothesized ranking + + # See [2] page 151 + E0 = (m*n*(n+1)**2)/4 + V0 = (m*n**2*(n+1)*(n**2-1))/144 + Lambda = (L-E0)/np.sqrt(V0) + # This is a one-sided "greater" test - calculate the probability that the + # L statistic under H0 would be greater than the observed L statistic + p = norm.sf(Lambda) + return p + + +def _l_p_exact(L, m, n): + '''Calculate the p-value of Page's L exactly''' + # [1] uses m, n; [5] uses n, k. + # Switch convention here because exact calculation code references [5]. + L, n, k = int(L), int(m), int(n) + _pagel_state.set_k(k) + return _pagel_state.sf(L, n) + + +class _PageL: + '''Maintains state between `page_trend_test` executions''' + + def __init__(self): + '''Lightweight initialization''' + self.all_pmfs = {} + + def set_k(self, k): + '''Calculate lower and upper limits of L for single row''' + self.k = k + # See [5] top of page 52 + self.a, self.b = (k*(k+1)*(k+2))//6, (k*(k+1)*(2*k+1))//6 + + def sf(self, l, n): + '''Survival function of Page's L statistic''' + ps = [self.pmf(l, n) for l in range(l, n*self.b + 1)] + return np.sum(ps) + + def p_l_k_1(self): + '''Relative frequency of each L value over all possible single rows''' + + # See [5] Equation (6) + ranks = range(1, self.k+1) + # generate all possible rows of length k + rank_perms = np.array(list(permutations(ranks))) + # compute Page's L for all possible rows + Ls = (ranks*rank_perms).sum(axis=1) + # count occurrences of each L value + counts = np.histogram(Ls, np.arange(self.a-0.5, self.b+1.5))[0] + # factorial(k) is number of possible permutations + return counts/math.factorial(self.k) + + def pmf(self, l, n): + '''Recursive function to evaluate p(l, k, n); see [5] Equation 1''' + + if n not in self.all_pmfs: + self.all_pmfs[n] = {} + if self.k not in self.all_pmfs[n]: + self.all_pmfs[n][self.k] = {} + + # Cache results to avoid repeating calculation. Initially this was + # written with lru_cache, but this seems faster? Also, we could add + # an option to save this for future lookup. + if l in self.all_pmfs[n][self.k]: + return self.all_pmfs[n][self.k][l] + + if n == 1: + ps = self.p_l_k_1() # [5] Equation 6 + ls = range(self.a, self.b+1) + # not fast, but we'll only be here once + self.all_pmfs[n][self.k] = {l: p for l, p in zip(ls, ps)} + return self.all_pmfs[n][self.k][l] + + p = 0 + low = max(l-(n-1)*self.b, self.a) # [5] Equation 2 + high = min(l-(n-1)*self.a, self.b) + + # [5] Equation 1 + for t in range(low, high+1): + p1 = self.pmf(l-t, n-1) + p2 = self.pmf(t, 1) + p += p1*p2 + self.all_pmfs[n][self.k][l] = p + return p + + +# Maintain state for faster repeat calls to page_trend_test w/ method='exact' +_pagel_state = _PageL() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_probability_distribution.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_probability_distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..9b092694240e88c226128fae6c0cd42792540058 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_probability_distribution.py @@ -0,0 +1,1742 @@ +# Temporary file separated from _distribution_infrastructure.py +# to simplify the diff during PR review. +from abc import ABC, abstractmethod + +class _ProbabilityDistribution(ABC): + @abstractmethod + def support(self): + r"""Support of the random variable + + The support of a random variable is set of all possible outcomes; + i.e., the subset of the domain of argument :math:`x` for which + the probability density function :math:`f(x)` is nonzero. + + This function returns lower and upper bounds of the support. + + Returns + ------- + out : tuple of Array + The lower and upper bounds of the support. + + See Also + -------- + pdf + + References + ---------- + .. [1] Support (mathematics), *Wikipedia*, + https://en.wikipedia.org/wiki/Support_(mathematics) + + Notes + ----- + Suppose a continuous probability distribution has support ``(l, r)``. + The following table summarizes the value returned by methods + of ``ContinuousDistribution`` for arguments outside the support. + + +----------------+---------------------+---------------------+ + | Method | Value for ``x < l`` | Value for ``x > r`` | + +================+=====================+=====================+ + | ``pdf(x)`` | 0 | 0 | + +----------------+---------------------+---------------------+ + | ``logpdf(x)`` | -inf | -inf | + +----------------+---------------------+---------------------+ + | ``cdf(x)`` | 0 | 1 | + +----------------+---------------------+---------------------+ + | ``logcdf(x)`` | -inf | 0 | + +----------------+---------------------+---------------------+ + | ``ccdf(x)`` | 1 | 0 | + +----------------+---------------------+---------------------+ + | ``logccdf(x)`` | 0 | -inf | + +----------------+---------------------+---------------------+ + + For the ``cdf`` and related methods, the inequality need not be + strict; i.e. the tabulated value is returned when the method is + evaluated *at* the corresponding boundary. + + The following table summarizes the value returned by the inverse + methods of ``ContinuousDistribution`` for arguments at the boundaries + of the domain ``0`` to ``1``. + + +-------------+-----------+-----------+ + | Method | ``x = 0`` | ``x = 1`` | + +=============+===========+===========+ + | ``icdf(x)`` | ``l`` | ``r`` | + +-------------+-----------+-----------+ + | ``icdf(x)`` | ``r`` | ``l`` | + +-------------+-----------+-----------+ + + For the inverse log-functions, the same values are returned for + for ``x = log(0)`` and ``x = log(1)``. All inverse functions return + ``nan`` when evaluated at an argument outside the domain ``0`` to ``1``. + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Retrieve the support of the distribution: + + >>> X.support() + (-0.5, 0.5) + + For a distribution with infinite support, + + >>> X = stats.Normal() + >>> X.support() + (-inf, inf) + + Due to underflow, the numerical value returned by the PDF may be zero + even for arguments within the support, even if the true value is + nonzero. In such cases, the log-PDF may be useful. + + >>> X.pdf([-100., 100.]) + array([0., 0.]) + >>> X.logpdf([-100., 100.]) + array([-5000.91893853, -5000.91893853]) + + Use cases for the log-CDF and related methods are analogous. + + """ + raise NotImplementedError() + + @abstractmethod + def sample(self, shape, *, method, rng): + r"""Random sample from the distribution. + + Parameters + ---------- + shape : tuple of ints, default: () + The shape of the sample to draw. If the parameters of the distribution + underlying the random variable are arrays of shape ``param_shape``, + the output array will be of shape ``shape + param_shape``. + method : {None, 'formula', 'inverse_transform'} + The strategy used to produce the sample. By default (``None``), + the infrastructure chooses between the following options, + listed in order of precedence. + + - ``'formula'``: an implementation specific to the distribution + - ``'inverse_transform'``: generate a uniformly distributed sample and + return the inverse CDF at these arguments. + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a `NotImplementedError`` + will be raised. + rng : `numpy.random.Generator` or `scipy.stats.QMCEngine`, optional + Pseudo- or quasi-random number generator state. When `rng` is None, + a new `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` and + `scipy.stats.QMCEngine` are passed to `numpy.random.default_rng` + to instantiate a ``Generator``. + + If `rng` is an instance of `scipy.stats.QMCEngine` configured to use + scrambling and `shape` is not empty, then each slice along the zeroth + axis of the result is a "quasi-independent", low-discrepancy sequence; + that is, they are distinct sequences that can be treated as statistically + independent for most practical purposes. Separate calls to `sample` + produce new quasi-independent, low-discrepancy sequences. + + References + ---------- + .. [1] Sampling (statistics), *Wikipedia*, + https://en.wikipedia.org/wiki/Sampling_(statistics) + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=0., b=1.) + + Generate a pseudorandom sample: + + >>> x = X.sample((1000, 1)) + >>> octiles = (np.arange(8) + 1) / 8 + >>> np.count_nonzero(x <= octiles, axis=0) + array([ 148, 263, 387, 516, 636, 751, 865, 1000]) # may vary + + >>> X = stats.Uniform(a=np.zeros((3, 1)), b=np.ones(2)) + >>> X.a.shape, + (3, 2) + >>> x = X.sample(shape=(5, 4)) + >>> x.shape + (5, 4, 3, 2) + + """ + raise NotImplementedError() + + @abstractmethod + def moment(self, order, kind, *, method): + r"""Raw, central, or standard moment of positive integer order. + + In terms of probability density function :math:`f(x)` and support + :math:`\chi`, the "raw" moment (about the origin) of order :math:`n` of + a random variable :math:`X` is: + + .. math:: + + \mu'_n(X) = \int_{\chi} x^n f(x) dx + + The "central" moment is the raw moment taken about the mean, + :math:`\mu = \mu'_1`: + + .. math:: + + \mu_n(X) = \int_{\chi} (x - \mu) ^n f(x) dx + + The "standardized" moment is the central moment normalized by the + :math:`n^\text{th}` power of the standard deviation + :math:`\sigma = \sqrt{\mu_2}` to produce a scale invariant quantity: + + .. math:: + + \tilde{\mu}_n(X) = \frac{\mu_n(X)} + {\sigma^n} + + Parameters + ---------- + order : int + The integer order of the moment; i.e. :math:`n` in the formulae above. + kind : {'raw', 'central', 'standardized'} + Whether to return the raw (default), central, or standardized moment + defined above. + method : {None, 'formula', 'general', 'transform', 'normalize', 'quadrature', 'cache'} + The strategy used to evaluate the moment. By default (``None``), + the infrastructure chooses between the following options, + listed in order of precedence. + + - ``'cache'``: use the value of the moment most recently calculated + via another method + - ``'formula'``: use a formula for the moment itself + - ``'general'``: use a general result that is true for all distributions + with finite moments; for instance, the zeroth raw moment is + identically 1 + - ``'transform'``: transform a raw moment to a central moment or + vice versa (see Notes) + - ``'normalize'``: normalize a central moment to get a standardized + or vice versa + - ``'quadrature'``: numerically integrate according to the definition + + Not all `method` options are available for all orders, kinds, and + distributions. If the selected `method` is not available, a + ``NotImplementedError`` will be raised. + + Returns + ------- + out : array + The moment of the random variable of the specified order and kind. + + See Also + -------- + pdf + mean + variance + standard_deviation + skewness + kurtosis + + Notes + ----- + Not all distributions have finite moments of all orders; moments of some + orders may be undefined or infinite. If a formula for the moment is not + specifically implemented for the chosen distribution, SciPy will attempt + to compute the moment via a generic method, which may yield a finite + result where none exists. This is not a critical bug, but an opportunity + for an enhancement. + + The definition of a raw moment in the summary is specific to the raw moment + about the origin. The raw moment about any point :math:`a` is: + + .. math:: + + E[(X-a)^n] = \int_{\chi} (x-a)^n f(x) dx + + In this notation, a raw moment about the origin is :math:`\mu'_n = E[x^n]`, + and a central moment is :math:`\mu_n = E[(x-\mu)^n]`, where :math:`\mu` + is the first raw moment; i.e. the mean. + + The ``'transform'`` method takes advantage of the following relationships + between moments taken about different points :math:`a` and :math:`b`. + + .. math:: + + E[(X-b)^n] = \sum_{i=0}^n E[(X-a)^i] {n \choose i} (a - b)^{n-i} + + For instance, to transform the raw moment to the central moment, we let + :math:`b = \mu` and :math:`a = 0`. + + The distribution infrastructure provides flexibility for distribution + authors to implement separate formulas for raw moments, central moments, + and standardized moments of any order. By default, the moment of the + desired order and kind is evaluated from the formula if such a formula + is available; if not, the infrastructure uses any formulas that are + available rather than resorting directly to numerical integration. + For instance, if formulas for the first three raw moments are + available and the third standardized moments is desired, the + infrastructure will evaluate the raw moments and perform the transforms + and standardization required. The decision tree is somewhat complex, + but the strategy for obtaining a moment of a given order and kind + (possibly as an intermediate step due to the recursive nature of the + transform formula above) roughly follows this order of priority: + + #. Use cache (if order of same moment and kind has been calculated) + #. Use formula (if available) + #. Transform between raw and central moment and/or normalize to convert + between central and standardized moments (if efficient) + #. Use a generic result true for most distributions (if available) + #. Use quadrature + + References + ---------- + .. [1] Moment, *Wikipedia*, + https://en.wikipedia.org/wiki/Moment_(mathematics) + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Evaluate the first raw moment: + + >>> X.moment(order=1, kind='raw') + 1.0 + >>> X.moment(order=1, kind='raw') == X.mean() == X.mu + True + + Evaluate the second central moment: + + >>> X.moment(order=2, kind='central') + 4.0 + >>> X.moment(order=2, kind='central') == X.variance() == X.sigma**2 + True + + Evaluate the fourth standardized moment: + + >>> X.moment(order=4, kind='standardized') + 3.0 + >>> X.moment(order=4, kind='standardized') == X.kurtosis(convention='non-excess') + True + + """ # noqa:E501 + raise NotImplementedError() + + @abstractmethod + def mean(self, *, method): + r"""Mean (raw first moment about the origin) + + Parameters + ---------- + method : {None, 'formula', 'transform', 'quadrature', 'cache'} + Method used to calculate the raw first moment. Not + all methods are available for all distributions. See + `moment` for details. + + See Also + -------- + moment + median + mode + + References + ---------- + .. [1] Mean, *Wikipedia*, + https://en.wikipedia.org/wiki/Mean#Mean_of_a_probability_distribution + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Evaluate the variance: + + >>> X.mean() + 1.0 + >>> X.mean() == X.moment(order=1, kind='raw') == X.mu + True + + """ + raise NotImplementedError() + + @abstractmethod + def median(self, *, method): + r"""Median (50th percentil) + + If a continuous random variable :math:`X` has probability :math:`0.5` of + taking on a value less than :math:`m`, then :math:`m` is the median. + That is, the median is the value :math:`m` for which: + + .. math:: + + P(X ≤ m) = 0.5 = P(X ≥ m) + + Parameters + ---------- + method : {None, 'formula', 'icdf'} + The strategy used to evaluate the median. + By default (``None``), the infrastructure chooses between the + following options, listed in order of precedence. + + - ``'formula'``: use a formula for the median + - ``'icdf'``: evaluate the inverse CDF of 0.5 + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The median + + See Also + -------- + mean + mode + icdf + + References + ---------- + .. [1] Median, *Wikipedia*, + https://en.wikipedia.org/wiki/Median#Probability_distributions + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Uniform(a=0., b=10.) + + Compute the median: + + >>> X.median() + np.float64(5.0) + >>> X.median() == X.icdf(0.5) == X.iccdf(0.5) + True + + """ + raise NotImplementedError() + + @abstractmethod + def mode(self, *, method): + r"""Mode (most likely value) + + Informally, the mode is a value that a random variable has the highest + probability (density) of assuming. That is, the mode is the element of + the support :math:`\chi` that maximizes the probability density + function :math:`f(x)`: + + .. math:: + + \text{mode} = \arg\max_{x \in \chi} f(x) + + Parameters + ---------- + method : {None, 'formula', 'optimization'} + The strategy used to evaluate the mode. + By default (``None``), the infrastructure chooses between the + following options, listed in order of precedence. + + - ``'formula'``: use a formula for the median + - ``'optimization'``: numerically maximize the PDF + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The mode + + See Also + -------- + mean + median + pdf + + Notes + ----- + For some distributions + + #. the mode is not unique (e.g. the uniform distribution); + #. the PDF has one or more singularities, and it is debateable whether + a singularity is considered to be in the domain and called the mode + (e.g. the gamma distribution with shape parameter less than 1); and/or + #. the probability density function may have one or more local maxima + that are not a global maximum (e.g. mixture distributions). + + In such cases, `mode` will + + #. return a single value, + #. consider the mode to occur at a singularity, and/or + #. return a local maximum which may or may not be a global maximum. + + If a formula for the mode is not specifically implemented for the + chosen distribution, SciPy will attempt to compute the mode + numerically, which may not meet the user's preferred definition of a + mode. In such cases, the user is encouraged to subclass the + distribution and override ``mode``. + + References + ---------- + .. [1] Mode (statistics), *Wikipedia*, + https://en.wikipedia.org/wiki/Mode_(statistics) + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Evaluate the mode: + + >>> X.mode() + 1.0 + + If the mode is not uniquely defined, ``mode`` nonetheless returns a + single value. + + >>> X = stats.Uniform(a=0., b=1.) + >>> X.mode() + 0.5 + + If this choice does not satisfy your requirements, subclass the + distribution and override ``mode``: + + >>> class BetterUniform(stats.Uniform): + ... def mode(self): + ... return self.b + >>> X = BetterUniform(a=0., b=1.) + >>> X.mode() + 1.0 + + """ + raise NotImplementedError() + + @abstractmethod + def variance(self, *, method): + r"""Variance (central second moment) + + Parameters + ---------- + method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'} + Method used to calculate the central second moment. Not + all methods are available for all distributions. See + `moment` for details. + + See Also + -------- + moment + standard_deviation + mean + + References + ---------- + .. [1] Variance, *Wikipedia*, + https://en.wikipedia.org/wiki/Variance#Absolutely_continuous_random_variable + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Evaluate the variance: + + >>> X.variance() + 4.0 + >>> X.variance() == X.moment(order=2, kind='central') == X.sigma**2 + True + + """ + raise NotImplementedError() + + @abstractmethod + def standard_deviation(self, *, method): + r"""Standard deviation (square root of the second central moment) + + Parameters + ---------- + method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'} + Method used to calculate the central second moment. Not + all methods are available for all distributions. See + `moment` for details. + + See Also + -------- + variance + mean + moment + + References + ---------- + .. [1] Standard deviation, *Wikipedia*, + https://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Evaluate the standard deviation: + + >>> X.standard_deviation() + 2.0 + >>> X.standard_deviation() == X.moment(order=2, kind='central')**0.5 == X.sigma + True + + """ + raise NotImplementedError() + + @abstractmethod + def skewness(self, *, method): + r"""Skewness (standardized third moment) + + Parameters + ---------- + method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'} + Method used to calculate the standardized third moment. Not + all methods are available for all distributions. See + `moment` for details. + + See Also + -------- + moment + mean + variance + + References + ---------- + .. [1] Skewness, *Wikipedia*, + https://en.wikipedia.org/wiki/Skewness + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Evaluate the skewness: + + >>> X.skewness() + 0.0 + >>> X.skewness() == X.moment(order=3, kind='standardized') + True + + """ + raise NotImplementedError() + + @abstractmethod + def kurtosis(self, *, method): + r"""Kurtosis (standardized fourth moment) + + By default, this is the standardized fourth moment, also known as the + "non-excess" or "Pearson" kurtosis (e.g. the kurtosis of the normal + distribution is 3). The "excess" or "Fisher" kurtosis (the standardized + fourth moment minus 3) is available via the `convention` parameter. + + Parameters + ---------- + method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'} + Method used to calculate the standardized fourth moment. Not + all methods are available for all distributions. See + `moment` for details. + convention : {'non-excess', 'excess'} + Two distinct conventions are available: + + - ``'non-excess'``: the standardized fourth moment (Pearson's kurtosis) + - ``'excess'``: the standardized fourth moment minus 3 (Fisher's kurtosis) + + The default is ``'non-excess'``. + + See Also + -------- + moment + mean + variance + + References + ---------- + .. [1] Kurtosis, *Wikipedia*, + https://en.wikipedia.org/wiki/Kurtosis + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Normal(mu=1., sigma=2.) + + Evaluate the kurtosis: + + >>> X.kurtosis() + 3.0 + >>> (X.kurtosis() + ... == X.kurtosis(convention='excess') + 3. + ... == X.moment(order=4, kind='standardized')) + True + + """ + raise NotImplementedError() + + @abstractmethod + def pdf(self, x, /, *, method): + r"""Probability density function + + The probability density function ("PDF"), denoted :math:`f(x)`, is the + probability *per unit length* that the random variable will assume the + value :math:`x`. Mathematically, it can be defined as the derivative + of the cumulative distribution function :math:`F(x)`: + + .. math:: + + f(x) = \frac{d}{dx} F(x) + + `pdf` accepts `x` for :math:`x`. + + Parameters + ---------- + x : array_like + The argument of the PDF. + method : {None, 'formula', 'logexp'} + The strategy used to evaluate the PDF. By default (``None``), the + infrastructure chooses between the following options, listed in + order of precedence. + + - ``'formula'``: use a formula for the PDF itself + - ``'logexp'``: evaluate the log-PDF and exponentiate + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The PDF evaluated at the argument `x`. + + See Also + -------- + cdf + logpdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. + By definition of the support, the PDF evaluates to its minimum value + of :math:`0` outside the support; i.e. for :math:`x < l` or + :math:`x > r`. The maximum of the PDF may be less than or greater than + :math:`1`; since the valus is a probability *density*, only its integral + over the support must equal :math:`1`. + + References + ---------- + .. [1] Probability density function, *Wikipedia*, + https://en.wikipedia.org/wiki/Probability_density_function + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Uniform(a=-1., b=1.) + + Evaluate the PDF at the desired argument: + + >>> X.pdf(0.25) + 0.5 + + """ + raise NotImplementedError() + + @abstractmethod + def logpdf(self, x, /, *, method): + r"""Log of the probability density function + + The probability density function ("PDF"), denoted :math:`f(x)`, is the + probability *per unit length* that the random variable will assume the + value :math:`x`. Mathematically, it can be defined as the derivative + of the cumulative distribution function :math:`F(x)`: + + .. math:: + + f(x) = \frac{d}{dx} F(x) + + `logpdf` computes the logarithm of the probability density function + ("log-PDF"), :math:`\log(f(x))`, but it may be numerically favorable + compared to the naive implementation (computing :math:`f(x)` and + taking the logarithm). + + `logpdf` accepts `x` for :math:`x`. + + Parameters + ---------- + x : array_like + The argument of the log-PDF. + method : {None, 'formula', 'logexp'} + The strategy used to evaluate the log-PDF. By default (``None``), the + infrastructure chooses between the following options, listed in order + of precedence. + + - ``'formula'``: use a formula for the log-PDF itself + - ``'logexp'``: evaluate the PDF and takes its logarithm + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The log-PDF evaluated at the argument `x`. + + See Also + -------- + pdf + logcdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. + By definition of the support, the log-PDF evaluates to its minimum value + of :math:`-\infty` (i.e. :math:`\log(0)`) outside the support; i.e. for + :math:`x < l` or :math:`x > r`. The maximum of the log-PDF may be less + than or greater than :math:`\log(1) = 0` because the maximum of the PDF + can be any positive real. + + For distributions with infinite support, it is common for `pdf` to return + a value of ``0`` when the argument is theoretically within the support; + this can occur because the true value of the PDF is too small to be + represented by the chosen dtype. The log-PDF, however, will often be finite + (not ``-inf``) over a much larger domain. Consequently, it may be preferred + to work with the logarithms of probabilities and probability densities to + avoid underflow. + + References + ---------- + .. [1] Probability density function, *Wikipedia*, + https://en.wikipedia.org/wiki/Probability_density_function + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-1.0, b=1.0) + + Evaluate the log-PDF at the desired argument: + + >>> X.logpdf(0.5) + -0.6931471805599453 + >>> np.allclose(X.logpdf(0.5), np.log(X.pdf(0.5))) + True + + """ + raise NotImplementedError() + + @abstractmethod + def cdf(self, x, y, /, *, method): + r"""Cumulative distribution function + + The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is + the probability the random variable :math:`X` will assume a value + less than or equal to :math:`x`: + + .. math:: + + F(x) = P(X ≤ x) + + A two-argument variant of this function is also defined as the + probability the random variable :math:`X` will assume a value between + :math:`x` and :math:`y`. + + .. math:: + + F(x, y) = P(x ≤ X ≤ y) + + `cdf` accepts `x` for :math:`x` and `y` for :math:`y`. + + Parameters + ---------- + x, y : array_like + The arguments of the CDF. `x` is required; `y` is optional. + method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'} + The strategy used to evaluate the CDF. + By default (``None``), the one-argument form of the function + chooses between the following options, listed in order of precedence. + + - ``'formula'``: use a formula for the CDF itself + - ``'logexp'``: evaluate the log-CDF and exponentiate + - ``'complement'``: evaluate the CCDF and take the complement + - ``'quadrature'``: numerically integrate the PDF + + In place of ``'complement'``, the two-argument form accepts: + + - ``'subtraction'``: compute the CDF at each argument and take + the difference. + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The CDF evaluated at the provided argument(s). + + See Also + -------- + logcdf + ccdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. + The CDF :math:`F(x)` is related to the probability density function + :math:`f(x)` by: + + .. math:: + + F(x) = \int_l^x f(u) du + + The two argument version is: + + .. math:: + + F(x, y) = \int_x^y f(u) du = F(y) - F(x) + + The CDF evaluates to its minimum value of :math:`0` for :math:`x ≤ l` + and its maximum value of :math:`1` for :math:`x ≥ r`. + + The CDF is also known simply as the "distribution function". + + References + ---------- + .. [1] Cumulative distribution function, *Wikipedia*, + https://en.wikipedia.org/wiki/Cumulative_distribution_function + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the CDF at the desired argument: + + >>> X.cdf(0.25) + 0.75 + + Evaluate the cumulative probability between two arguments: + + >>> X.cdf(-0.25, 0.25) == X.cdf(0.25) - X.cdf(-0.25) + True + + """ # noqa: E501 + raise NotImplementedError() + + @abstractmethod + def icdf(self, p, /, *, method): + r"""Inverse of the cumulative distribution function. + + The inverse of the cumulative distribution function ("inverse CDF"), + denoted :math:`F^{-1}(p)`, is the argument :math:`x` for which the + cumulative distribution function :math:`F(x)` evaluates to :math:`p`. + + .. math:: + + F^{-1}(p) = x \quad \text{s.t.} \quad F(x) = p + + `icdf` accepts `p` for :math:`p \in [0, 1]`. + + Parameters + ---------- + p : array_like + The argument of the inverse CDF. + method : {None, 'formula', 'complement', 'inversion'} + The strategy used to evaluate the inverse CDF. + By default (``None``), the infrastructure chooses between the + following options, listed in order of precedence. + + - ``'formula'``: use a formula for the inverse CDF itself + - ``'complement'``: evaluate the inverse CCDF at the + complement of `p` + - ``'inversion'``: solve numerically for the argument at which the + CDF is equal to `p` + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The inverse CDF evaluated at the provided argument. + + See Also + -------- + cdf + ilogcdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. The + inverse CDF returns its minimum value of :math:`l` at :math:`p = 0` + and its maximum value of :math:`r` at :math:`p = 1`. Because the CDF + has range :math:`[0, 1]`, the inverse CDF is only defined on the + domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, `icdf` + returns ``nan``. + + The inverse CDF is also known as the quantile function, percentile function, + and percent-point function. + + References + ---------- + .. [1] Quantile function, *Wikipedia*, + https://en.wikipedia.org/wiki/Quantile_function + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the inverse CDF at the desired argument: + + >>> X.icdf(0.25) + -0.25 + >>> np.allclose(X.cdf(X.icdf(0.25)), 0.25) + True + + This function returns NaN when the argument is outside the domain. + + >>> X.icdf([-0.1, 0, 1, 1.1]) + array([ nan, -0.5, 0.5, nan]) + + """ + raise NotImplementedError() + + @abstractmethod + def ccdf(self, x, y, /, *, method): + r"""Complementary cumulative distribution function + + The complementary cumulative distribution function ("CCDF"), denoted + :math:`G(x)`, is the complement of the cumulative distribution function + :math:`F(x)`; i.e., probability the random variable :math:`X` will + assume a value greater than :math:`x`: + + .. math:: + + G(x) = 1 - F(x) = P(X > x) + + A two-argument variant of this function is: + + .. math:: + + G(x, y) = 1 - F(x, y) = P(X < x \text{ or } X > y) + + `ccdf` accepts `x` for :math:`x` and `y` for :math:`y`. + + Parameters + ---------- + x, y : array_like + The arguments of the CCDF. `x` is required; `y` is optional. + method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'} + The strategy used to evaluate the CCDF. + By default (``None``), the infrastructure chooses between the + following options, listed in order of precedence. + + - ``'formula'``: use a formula for the CCDF itself + - ``'logexp'``: evaluate the log-CCDF and exponentiate + - ``'complement'``: evaluate the CDF and take the complement + - ``'quadrature'``: numerically integrate the PDF + + The two-argument form chooses between: + + - ``'formula'``: use a formula for the CCDF itself + - ``'addition'``: compute the CDF at `x` and the CCDF at `y`, then add + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The CCDF evaluated at the provided argument(s). + + See Also + -------- + cdf + logccdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. + The CCDF :math:`G(x)` is related to the probability density function + :math:`f(x)` by: + + .. math:: + + G(x) = \int_x^r f(u) du + + The two argument version is: + + .. math:: + + G(x, y) = \int_l^x f(u) du + \int_y^r f(u) du + + The CCDF returns its minimum value of :math:`0` for :math:`x ≥ r` + and its maximum value of :math:`1` for :math:`x ≤ l`. + + The CCDF is also known as the "survival function". + + References + ---------- + .. [1] Cumulative distribution function, *Wikipedia*, + https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the CCDF at the desired argument: + + >>> X.ccdf(0.25) + 0.25 + >>> np.allclose(X.ccdf(0.25), 1-X.cdf(0.25)) + True + + Evaluate the complement of the cumulative probability between two arguments: + + >>> X.ccdf(-0.25, 0.25) == X.cdf(-0.25) + X.ccdf(0.25) + True + + """ # noqa: E501 + raise NotImplementedError() + + @abstractmethod + def iccdf(self, p, /, *, method): + r"""Inverse complementary cumulative distribution function. + + The inverse complementary cumulative distribution function ("inverse CCDF"), + denoted :math:`G^{-1}(p)`, is the argument :math:`x` for which the + complementary cumulative distribution function :math:`G(x)` evaluates to + :math:`p`. + + .. math:: + + G^{-1}(p) = x \quad \text{s.t.} \quad G(x) = p + + `iccdf` accepts `p` for :math:`p \in [0, 1]`. + + Parameters + ---------- + p : array_like + The argument of the inverse CCDF. + method : {None, 'formula', 'complement', 'inversion'} + The strategy used to evaluate the inverse CCDF. + By default (``None``), the infrastructure chooses between the + following options, listed in order of precedence. + + - ``'formula'``: use a formula for the inverse CCDF itself + - ``'complement'``: evaluate the inverse CDF at the + complement of `p` + - ``'inversion'``: solve numerically for the argument at which the + CCDF is equal to `p` + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The inverse CCDF evaluated at the provided argument. + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. The + inverse CCDF returns its minimum value of :math:`l` at :math:`p = 1` + and its maximum value of :math:`r` at :math:`p = 0`. Because the CCDF + has range :math:`[0, 1]`, the inverse CCDF is only defined on the + domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, ``iccdf`` + returns ``nan``. + + See Also + -------- + icdf + ilogccdf + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the inverse CCDF at the desired argument: + + >>> X.iccdf(0.25) + 0.25 + >>> np.allclose(X.iccdf(0.25), X.icdf(1-0.25)) + True + + This function returns NaN when the argument is outside the domain. + + >>> X.iccdf([-0.1, 0, 1, 1.1]) + array([ nan, 0.5, -0.5, nan]) + + """ + raise NotImplementedError() + + @abstractmethod + def logcdf(self, x, y, /, *, method): + r"""Log of the cumulative distribution function + + The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is + the probability the random variable :math:`X` will assume a value + less than or equal to :math:`x`: + + .. math:: + + F(x) = P(X ≤ x) + + A two-argument variant of this function is also defined as the + probability the random variable :math:`X` will assume a value between + :math:`x` and :math:`y`. + + .. math:: + + F(x, y) = P(x ≤ X ≤ y) + + `logcdf` computes the logarithm of the cumulative distribution function + ("log-CDF"), :math:`\log(F(x))`/:math:`\log(F(x, y))`, but it may be + numerically favorable compared to the naive implementation (computing + the CDF and taking the logarithm). + + `logcdf` accepts `x` for :math:`x` and `y` for :math:`y`. + + Parameters + ---------- + x, y : array_like + The arguments of the log-CDF. `x` is required; `y` is optional. + method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'} + The strategy used to evaluate the log-CDF. + By default (``None``), the one-argument form of the function + chooses between the following options, listed in order of precedence. + + - ``'formula'``: use a formula for the log-CDF itself + - ``'logexp'``: evaluate the CDF and take the logarithm + - ``'complement'``: evaluate the log-CCDF and take the + logarithmic complement (see Notes) + - ``'quadrature'``: numerically log-integrate the log-PDF + + In place of ``'complement'``, the two-argument form accepts: + + - ``'subtraction'``: compute the log-CDF at each argument and take + the logarithmic difference (see Notes) + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The log-CDF evaluated at the provided argument(s). + + See Also + -------- + cdf + logccdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. + The log-CDF evaluates to its minimum value of :math:`\log(0) = -\infty` + for :math:`x ≤ l` and its maximum value of :math:`\log(1) = 0` for + :math:`x ≥ r`. + + For distributions with infinite support, it is common for + `cdf` to return a value of ``0`` when the argument + is theoretically within the support; this can occur because the true value + of the CDF is too small to be represented by the chosen dtype. `logcdf`, + however, will often return a finite (not ``-inf``) result over a much larger + domain. Similarly, `logcdf` may provided a strictly negative result with + arguments for which `cdf` would return ``1.0``. Consequently, it may be + preferred to work with the logarithms of probabilities to avoid underflow + and related limitations of floating point numbers. + + The "logarithmic complement" of a number :math:`z` is mathematically + equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss + of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`. + Similarly, the term "logarithmic difference" of :math:`w` and :math:`z` + is used here to mean :math:`\log(\exp(w)-\exp(z))`. + + If ``y < x``, the CDF is negative, and therefore the log-CCDF + is complex with imaginary part :math:`\pi`. For + consistency, the result of this function always has complex dtype + when `y` is provided, regardless of the value of the imaginary part. + + References + ---------- + .. [1] Cumulative distribution function, *Wikipedia*, + https://en.wikipedia.org/wiki/Cumulative_distribution_function + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the log-CDF at the desired argument: + + >>> X.logcdf(0.25) + -0.287682072451781 + >>> np.allclose(X.logcdf(0.), np.log(X.cdf(0.))) + True + + """ # noqa: E501 + raise NotImplementedError() + + @abstractmethod + def ilogcdf(self, logp, /, *, method): + r"""Inverse of the logarithm of the cumulative distribution function. + + The inverse of the logarithm of the cumulative distribution function + ("inverse log-CDF") is the argument :math:`x` for which the logarithm + of the cumulative distribution function :math:`\log(F(x))` evaluates + to :math:`\log(p)`. + + Mathematically, it is equivalent to :math:`F^{-1}(\exp(y))`, where + :math:`y = \log(p)`, but it may be numerically favorable compared to + the naive implementation (computing :math:`p = \exp(y)`, then + :math:`F^{-1}(p)`). + + `ilogcdf` accepts `logp` for :math:`\log(p) ≤ 0`. + + Parameters + ---------- + logp : array_like + The argument of the inverse log-CDF. + method : {None, 'formula', 'complement', 'inversion'} + The strategy used to evaluate the inverse log-CDF. + By default (``None``), the infrastructure chooses between the + following options, listed in order of precedence. + + - ``'formula'``: use a formula for the inverse log-CDF itself + - ``'complement'``: evaluate the inverse log-CCDF at the + logarithmic complement of `logp` (see Notes) + - ``'inversion'``: solve numerically for the argument at which the + log-CDF is equal to `logp` + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The inverse log-CDF evaluated at the provided argument. + + See Also + -------- + icdf + logcdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. + The inverse log-CDF returns its minimum value of :math:`l` at + :math:`\log(p) = \log(0) = -\infty` and its maximum value of :math:`r` at + :math:`\log(p) = \log(1) = 0`. Because the log-CDF has range + :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the + negative reals; for :math:`\log(p) > 0`, `ilogcdf` returns ``nan``. + + Occasionally, it is needed to find the argument of the CDF for which + the resulting probability is very close to ``0`` or ``1`` - too close to + represent accurately with floating point arithmetic. In many cases, + however, the *logarithm* of this resulting probability may be + represented in floating point arithmetic, in which case this function + may be used to find the argument of the CDF for which the *logarithm* + of the resulting probability is :math:`y = \log(p)`. + + The "logarithmic complement" of a number :math:`z` is mathematically + equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss + of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`. + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the inverse log-CDF at the desired argument: + + >>> X.ilogcdf(-0.25) + 0.2788007830714034 + >>> np.allclose(X.ilogcdf(-0.25), X.icdf(np.exp(-0.25))) + True + + """ + raise NotImplementedError() + + @abstractmethod + def logccdf(self, x, y, /, *, method): + r"""Log of the complementary cumulative distribution function + + The complementary cumulative distribution function ("CCDF"), denoted + :math:`G(x)` is the complement of the cumulative distribution function + :math:`F(x)`; i.e., probability the random variable :math:`X` will + assume a value greater than :math:`x`: + + .. math:: + + G(x) = 1 - F(x) = P(X > x) + + A two-argument variant of this function is: + + .. math:: + + G(x, y) = 1 - F(x, y) = P(X < x \quad \text{or} \quad X > y) + + `logccdf` computes the logarithm of the complementary cumulative + distribution function ("log-CCDF"), :math:`\log(G(x))`/:math:`\log(G(x, y))`, + but it may be numerically favorable compared to the naive implementation + (computing the CDF and taking the logarithm). + + `logccdf` accepts `x` for :math:`x` and `y` for :math:`y`. + + Parameters + ---------- + x, y : array_like + The arguments of the log-CCDF. `x` is required; `y` is optional. + method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'} + The strategy used to evaluate the log-CCDF. + By default (``None``), the one-argument form of the function + chooses between the following options, listed in order of precedence. + + - ``'formula'``: use a formula for the log CCDF itself + - ``'logexp'``: evaluate the CCDF and take the logarithm + - ``'complement'``: evaluate the log-CDF and take the + logarithmic complement (see Notes) + - ``'quadrature'``: numerically log-integrate the log-PDF + + The two-argument form chooses between: + + - ``'formula'``: use a formula for the log CCDF itself + - ``'addition'``: compute the log-CDF at `x` and the log-CCDF at `y`, + then take the logarithmic sum (see Notes) + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The log-CCDF evaluated at the provided argument(s). + + See Also + -------- + ccdf + logcdf + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. + The log-CCDF returns its minimum value of :math:`\log(0)=-\infty` for + :math:`x ≥ r` and its maximum value of :math:`\log(1) = 0` for + :math:`x ≤ l`. + + For distributions with infinite support, it is common for + `ccdf` to return a value of ``0`` when the argument + is theoretically within the support; this can occur because the true value + of the CCDF is too small to be represented by the chosen dtype. The log + of the CCDF, however, will often be finite (not ``-inf``) over a much larger + domain. Similarly, `logccdf` may provided a strictly negative result with + arguments for which `ccdf` would return ``1.0``. Consequently, it may be + preferred to work with the logarithms of probabilities to avoid underflow + and related limitations of floating point numbers. + + The "logarithmic complement" of a number :math:`z` is mathematically + equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss + of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`. + Similarly, the term "logarithmic sum" of :math:`w` and :math:`z` + is used here to mean the :math:`\log(\exp(w)+\exp(z))`, AKA + :math:`\text{LogSumExp}(w, z)`. + + References + ---------- + .. [1] Cumulative distribution function, *Wikipedia*, + https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the log-CCDF at the desired argument: + + >>> X.logccdf(0.25) + -1.3862943611198906 + >>> np.allclose(X.logccdf(0.), np.log(X.ccdf(0.))) + True + + """ # noqa: E501 + raise NotImplementedError() + + @abstractmethod + def ilogccdf(self, logp, /, *, method): + r"""Inverse of the log of the complementary cumulative distribution function. + + The inverse of the logarithm of the complementary cumulative distribution + function ("inverse log-CCDF") is the argument :math:`x` for which the logarithm + of the complementary cumulative distribution function :math:`\log(G(x))` + evaluates to :math:`\log(p)`. + + Mathematically, it is equivalent to :math:`G^{-1}(\exp(y))`, where + :math:`y = \log(p)`, but it may be numerically favorable compared to the naive + implementation (computing :math:`p = \exp(y)`, then :math:`G^{-1}(p)`). + + `ilogccdf` accepts `logp` for :math:`\log(p) ≤ 0`. + + Parameters + ---------- + x : array_like + The argument of the inverse log-CCDF. + method : {None, 'formula', 'complement', 'inversion'} + The strategy used to evaluate the inverse log-CCDF. + By default (``None``), the infrastructure chooses between the + following options, listed in order of precedence. + + - ``'formula'``: use a formula for the inverse log-CCDF itself + - ``'complement'``: evaluate the inverse log-CDF at the + logarithmic complement of `x` (see Notes) + - ``'inversion'``: solve numerically for the argument at which the + log-CCDF is equal to `x` + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The inverse log-CCDF evaluated at the provided argument. + + Notes + ----- + Suppose a continuous probability distribution has support :math:`[l, r]`. The + inverse log-CCDF returns its minimum value of :math:`l` at + :math:`\log(p) = \log(1) = 0` and its maximum value of :math:`r` at + :math:`\log(p) = \log(0) = -\infty`. Because the log-CCDF has range + :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the + negative reals; for :math:`\log(p) > 0`, `ilogccdf` returns ``nan``. + + Occasionally, it is needed to find the argument of the CCDF for which + the resulting probability is very close to ``0`` or ``1`` - too close to + represent accurately with floating point arithmetic. In many cases, + however, the *logarithm* of this resulting probability may be + represented in floating point arithmetic, in which case this function + may be used to find the argument of the CCDF for which the *logarithm* + of the resulting probability is `y = \log(p)`. + + The "logarithmic complement" of a number :math:`z` is mathematically + equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss + of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`. + + See Also + -------- + iccdf + ilogccdf + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-0.5, b=0.5) + + Evaluate the inverse log-CCDF at the desired argument: + + >>> X.ilogccdf(-0.25) + -0.2788007830714034 + >>> np.allclose(X.ilogccdf(-0.25), X.iccdf(np.exp(-0.25))) + True + + """ + raise NotImplementedError() + + @abstractmethod + def logentropy(self, *, method): + r"""Logarithm of the differential entropy + + In terms of probability density function :math:`f(x)` and support + :math:`\chi`, the differential entropy (or simply "entropy") of a random + variable :math:`X` is: + + .. math:: + + h(X) = - \int_{\chi} f(x) \log f(x) dx + + `logentropy` computes the logarithm of the differential entropy + ("log-entropy"), :math:`log(h(X))`, but it may be numerically favorable + compared to the naive implementation (computing :math:`h(X)` then + taking the logarithm). + + Parameters + ---------- + method : {None, 'formula', 'logexp', 'quadrature} + The strategy used to evaluate the log-entropy. By default + (``None``), the infrastructure chooses between the following options, + listed in order of precedence. + + - ``'formula'``: use a formula for the log-entropy itself + - ``'logexp'``: evaluate the entropy and take the logarithm + - ``'quadrature'``: numerically log-integrate the logarithm of the + entropy integrand + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The log-entropy. + + See Also + -------- + entropy + logpdf + + Notes + ----- + If the entropy of a distribution is negative, then the log-entropy + is complex with imaginary part :math:`\pi`. For + consistency, the result of this function always has complex dtype, + regardless of the value of the imaginary part. + + References + ---------- + .. [1] Differential entropy, *Wikipedia*, + https://en.wikipedia.org/wiki/Differential_entropy + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> import numpy as np + >>> from scipy import stats + >>> X = stats.Uniform(a=-1., b=1.) + + Evaluate the log-entropy: + + >>> X.logentropy() + (-0.3665129205816642+0j) + >>> np.allclose(np.exp(X.logentropy()), X.entropy()) + True + + For a random variable with negative entropy, the log-entropy has an + imaginary part equal to `np.pi`. + + >>> X = stats.Uniform(a=-.1, b=.1) + >>> X.entropy(), X.logentropy() + (-1.6094379124341007, (0.4758849953271105+3.141592653589793j)) + + """ + raise NotImplementedError() + + @abstractmethod + def entropy(self, *, method): + r"""Differential entropy + + In terms of probability density function :math:`f(x)` and support + :math:`\chi`, the differential entropy (or simply "entropy") of a + continuous random variable :math:`X` is: + + .. math:: + + h(X) = - \int_{\chi} f(x) \log f(x) dx + + Parameters + ---------- + method : {None, 'formula', 'logexp', 'quadrature'} + The strategy used to evaluate the entropy. By default (``None``), + the infrastructure chooses between the following options, listed + in order of precedence. + + - ``'formula'``: use a formula for the entropy itself + - ``'logexp'``: evaluate the log-entropy and exponentiate + - ``'quadrature'``: use numerical integration + + Not all `method` options are available for all distributions. + If the selected `method` is not available, a ``NotImplementedError`` + will be raised. + + Returns + ------- + out : array + The entropy of the random variable. + + See Also + -------- + logentropy + pdf + + Notes + ----- + This function calculates the entropy using the natural logarithm; i.e. + the logarithm with base :math:`e`. Consequently, the value is expressed + in (dimensionless) "units" of nats. To convert the entropy to different + units (i.e. corresponding with a different base), divide the result by + the natural logarithm of the desired base. + + References + ---------- + .. [1] Differential entropy, *Wikipedia*, + https://en.wikipedia.org/wiki/Differential_entropy + + Examples + -------- + Instantiate a distribution with the desired parameters: + + >>> from scipy import stats + >>> X = stats.Uniform(a=-1., b=1.) + + Evaluate the entropy: + + >>> X.entropy() + 0.6931471805599454 + + """ + raise NotImplementedError() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmc.py new file mode 100644 index 0000000000000000000000000000000000000000..3287dceaca830b54fc46677fada36a8223d13ef0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmc.py @@ -0,0 +1,2951 @@ +"""Quasi-Monte Carlo engines and helpers.""" +import copy +import math +import numbers +import os +import warnings +from abc import ABC, abstractmethod +from functools import partial +from typing import ( + ClassVar, + Literal, + overload, + TYPE_CHECKING, +) +from collections.abc import Callable + +import numpy as np + +from scipy._lib._util import DecimalNumber, GeneratorType, IntNumber, SeedType + +if TYPE_CHECKING: + import numpy.typing as npt + +import scipy.stats as stats +from scipy._lib._util import rng_integers, _rng_spawn, _transition_to_rng +from scipy.sparse.csgraph import minimum_spanning_tree +from scipy.spatial import distance, Voronoi +from scipy.special import gammainc +from ._sobol import ( + _initialize_v, _cscramble, _fill_p_cumulative, _draw, _fast_forward, + _categorize, _MAXDIM +) +from ._qmc_cy import ( + _cy_wrapper_centered_discrepancy, + _cy_wrapper_wrap_around_discrepancy, + _cy_wrapper_mixture_discrepancy, + _cy_wrapper_l2_star_discrepancy, + _cy_wrapper_update_discrepancy, + _cy_van_der_corput_scrambled, + _cy_van_der_corput, +) + + +__all__ = ['scale', 'discrepancy', 'geometric_discrepancy', 'update_discrepancy', + 'QMCEngine', 'Sobol', 'Halton', 'LatinHypercube', 'PoissonDisk', + 'MultinomialQMC', 'MultivariateNormalQMC'] + + +@overload +def check_random_state(seed: IntNumber | None = ...) -> np.random.Generator: + ... + + +@overload +def check_random_state(seed: GeneratorType) -> GeneratorType: + ... + + +# Based on scipy._lib._util.check_random_state +# This is going to be removed at the end of the SPEC 7 transition, +# so I'll just leave the argument name `seed` alone +def check_random_state(seed=None): + """Turn `seed` into a `numpy.random.Generator` instance. + + Parameters + ---------- + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is an int or None, a new `numpy.random.Generator` is + created using ``np.random.default_rng(seed)``. + If `seed` is already a ``Generator`` or ``RandomState`` instance, then + the provided instance is used. + + Returns + ------- + seed : {`numpy.random.Generator`, `numpy.random.RandomState`} + Random number generator. + + """ + if seed is None or isinstance(seed, (numbers.Integral, np.integer)): + return np.random.default_rng(seed) + elif isinstance(seed, (np.random.RandomState, np.random.Generator)): + return seed + else: + raise ValueError(f'{seed!r} cannot be used to seed a' + ' numpy.random.Generator instance') + + +def scale( + sample: "npt.ArrayLike", + l_bounds: "npt.ArrayLike", + u_bounds: "npt.ArrayLike", + *, + reverse: bool = False +) -> np.ndarray: + r"""Sample scaling from unit hypercube to different bounds. + + To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`, + with :math:`a` the lower bounds and :math:`b` the upper bounds. + The following transformation is used: + + .. math:: + + (b - a) \cdot \text{sample} + a + + Parameters + ---------- + sample : array_like (n, d) + Sample to scale. + l_bounds, u_bounds : array_like (d,) + Lower and upper bounds (resp. :math:`a`, :math:`b`) of transformed + data. If `reverse` is True, range of the original data to transform + to the unit hypercube. + reverse : bool, optional + Reverse the transformation from different bounds to the unit hypercube. + Default is False. + + Returns + ------- + sample : array_like (n, d) + Scaled sample. + + Examples + -------- + Transform 3 samples in the unit hypercube to bounds: + + >>> from scipy.stats import qmc + >>> l_bounds = [-2, 0] + >>> u_bounds = [6, 5] + >>> sample = [[0.5 , 0.75], + ... [0.5 , 0.5], + ... [0.75, 0.25]] + >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds) + >>> sample_scaled + array([[2. , 3.75], + [2. , 2.5 ], + [4. , 1.25]]) + + And convert back to the unit hypercube: + + >>> sample_ = qmc.scale(sample_scaled, l_bounds, u_bounds, reverse=True) + >>> sample_ + array([[0.5 , 0.75], + [0.5 , 0.5 ], + [0.75, 0.25]]) + + """ + sample = np.asarray(sample) + + # Checking bounds and sample + if not sample.ndim == 2: + raise ValueError('Sample is not a 2D array') + + lower, upper = _validate_bounds( + l_bounds=l_bounds, u_bounds=u_bounds, d=sample.shape[1] + ) + + if not reverse: + # Checking that sample is within the hypercube + if (sample.max() > 1.) or (sample.min() < 0.): + raise ValueError('Sample is not in unit hypercube') + + return sample * (upper - lower) + lower + else: + # Checking that sample is within the bounds + if not (np.all(sample >= lower) and np.all(sample <= upper)): + raise ValueError('Sample is out of bounds') + + return (sample - lower) / (upper - lower) + + +def _ensure_in_unit_hypercube(sample: "npt.ArrayLike") -> np.ndarray: + """Ensure that sample is a 2D array and is within a unit hypercube + + Parameters + ---------- + sample : array_like (n, d) + A 2D array of points. + + Returns + ------- + np.ndarray + The array interpretation of the input sample + + Raises + ------ + ValueError + If the input is not a 2D array or contains points outside of + a unit hypercube. + """ + sample = np.asarray(sample, dtype=np.float64, order="C") + + if not sample.ndim == 2: + raise ValueError("Sample is not a 2D array") + + if (sample.max() > 1.) or (sample.min() < 0.): + raise ValueError("Sample is not in unit hypercube") + + return sample + + +def discrepancy( + sample: "npt.ArrayLike", + *, + iterative: bool = False, + method: Literal["CD", "WD", "MD", "L2-star"] = "CD", + workers: IntNumber = 1) -> float: + """Discrepancy of a given sample. + + Parameters + ---------- + sample : array_like (n, d) + The sample to compute the discrepancy from. + iterative : bool, optional + Must be False if not using it for updating the discrepancy. + Default is False. Refer to the notes for more details. + method : str, optional + Type of discrepancy, can be ``CD``, ``WD``, ``MD`` or ``L2-star``. + Refer to the notes for more details. Default is ``CD``. + workers : int, optional + Number of workers to use for parallel processing. If -1 is given all + CPU threads are used. Default is 1. + + Returns + ------- + discrepancy : float + Discrepancy. + + See Also + -------- + geometric_discrepancy + + Notes + ----- + The discrepancy is a uniformity criterion used to assess the space filling + of a number of samples in a hypercube. A discrepancy quantifies the + distance between the continuous uniform distribution on a hypercube and the + discrete uniform distribution on :math:`n` distinct sample points. + + The lower the value is, the better the coverage of the parameter space is. + + For a collection of subsets of the hypercube, the discrepancy is the + difference between the fraction of sample points in one of those + subsets and the volume of that subset. There are different definitions of + discrepancy corresponding to different collections of subsets. Some + versions take a root mean square difference over subsets instead of + a maximum. + + A measure of uniformity is reasonable if it satisfies the following + criteria [1]_: + + 1. It is invariant under permuting factors and/or runs. + 2. It is invariant under rotation of the coordinates. + 3. It can measure not only uniformity of the sample over the hypercube, + but also the projection uniformity of the sample over non-empty + subset of lower dimension hypercubes. + 4. There is some reasonable geometric meaning. + 5. It is easy to compute. + 6. It satisfies the Koksma-Hlawka-like inequality. + 7. It is consistent with other criteria in experimental design. + + Four methods are available: + + * ``CD``: Centered Discrepancy - subspace involves a corner of the + hypercube + * ``WD``: Wrap-around Discrepancy - subspace can wrap around bounds + * ``MD``: Mixture Discrepancy - mix between CD/WD covering more criteria + * ``L2-star``: L2-star discrepancy - like CD BUT variant to rotation + + See [2]_ for precise definitions of each method. + + Lastly, using ``iterative=True``, it is possible to compute the + discrepancy as if we had :math:`n+1` samples. This is useful if we want + to add a point to a sampling and check the candidate which would give the + lowest discrepancy. Then you could just update the discrepancy with + each candidate using `update_discrepancy`. This method is faster than + computing the discrepancy for a large number of candidates. + + References + ---------- + .. [1] Fang et al. "Design and modeling for computer experiments". + Computer Science and Data Analysis Series, 2006. + .. [2] Zhou Y.-D. et al. "Mixture discrepancy for quasi-random point sets." + Journal of Complexity, 29 (3-4) , pp. 283-301, 2013. + .. [3] T. T. Warnock. "Computational investigations of low discrepancy + point sets." Applications of Number Theory to Numerical + Analysis, Academic Press, pp. 319-343, 1972. + + Examples + -------- + Calculate the quality of the sample using the discrepancy: + + >>> import numpy as np + >>> from scipy.stats import qmc + >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]]) + >>> l_bounds = [0.5, 0.5] + >>> u_bounds = [6.5, 6.5] + >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True) + >>> space + array([[0.08333333, 0.41666667], + [0.25 , 0.91666667], + [0.41666667, 0.25 ], + [0.58333333, 0.75 ], + [0.75 , 0.08333333], + [0.91666667, 0.58333333]]) + >>> qmc.discrepancy(space) + 0.008142039609053464 + + We can also compute iteratively the ``CD`` discrepancy by using + ``iterative=True``. + + >>> disc_init = qmc.discrepancy(space[:-1], iterative=True) + >>> disc_init + 0.04769081147119336 + >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init) + 0.008142039609053513 + + """ + sample = _ensure_in_unit_hypercube(sample) + + workers = _validate_workers(workers) + + methods = { + "CD": _cy_wrapper_centered_discrepancy, + "WD": _cy_wrapper_wrap_around_discrepancy, + "MD": _cy_wrapper_mixture_discrepancy, + "L2-star": _cy_wrapper_l2_star_discrepancy, + } + + if method in methods: + return methods[method](sample, iterative, workers=workers) + else: + raise ValueError(f"{method!r} is not a valid method. It must be one of" + f" {set(methods)!r}") + + +def geometric_discrepancy( + sample: "npt.ArrayLike", + method: Literal["mindist", "mst"] = "mindist", + metric: str = "euclidean") -> float: + """Discrepancy of a given sample based on its geometric properties. + + Parameters + ---------- + sample : array_like (n, d) + The sample to compute the discrepancy from. + method : {"mindist", "mst"}, optional + The method to use. One of ``mindist`` for minimum distance (default) + or ``mst`` for minimum spanning tree. + metric : str or callable, optional + The distance metric to use. See the documentation + for `scipy.spatial.distance.pdist` for the available metrics and + the default. + + Returns + ------- + discrepancy : float + Discrepancy (higher values correspond to greater sample uniformity). + + See Also + -------- + discrepancy + + Notes + ----- + The discrepancy can serve as a simple measure of quality of a random sample. + This measure is based on the geometric properties of the distribution of points + in the sample, such as the minimum distance between any pair of points, or + the mean edge length in a minimum spanning tree. + + The higher the value is, the better the coverage of the parameter space is. + Note that this is different from `scipy.stats.qmc.discrepancy`, where lower + values correspond to higher quality of the sample. + + Also note that when comparing different sampling strategies using this function, + the sample size must be kept constant. + + It is possible to calculate two metrics from the minimum spanning tree: + the mean edge length and the standard deviation of edges lengths. Using + both metrics offers a better picture of uniformity than either metric alone, + with higher mean and lower standard deviation being preferable (see [1]_ + for a brief discussion). This function currently only calculates the mean + edge length. + + References + ---------- + .. [1] Franco J. et al. "Minimum Spanning Tree: A new approach to assess the quality + of the design of computer experiments." Chemometrics and Intelligent Laboratory + Systems, 97 (2), pp. 164-169, 2009. + + Examples + -------- + Calculate the quality of the sample using the minimum euclidean distance + (the defaults): + + >>> import numpy as np + >>> from scipy.stats import qmc + >>> rng = np.random.default_rng(191468432622931918890291693003068437394) + >>> sample = qmc.LatinHypercube(d=2, rng=rng).random(50) + >>> qmc.geometric_discrepancy(sample) + 0.03708161435687876 + + Calculate the quality using the mean edge length in the minimum + spanning tree: + + >>> qmc.geometric_discrepancy(sample, method='mst') + 0.1105149978798376 + + Display the minimum spanning tree and the points with + the smallest distance: + + >>> import matplotlib.pyplot as plt + >>> from matplotlib.lines import Line2D + >>> from scipy.sparse.csgraph import minimum_spanning_tree + >>> from scipy.spatial.distance import pdist, squareform + >>> dist = pdist(sample) + >>> mst = minimum_spanning_tree(squareform(dist)) + >>> edges = np.where(mst.toarray() > 0) + >>> edges = np.asarray(edges).T + >>> min_dist = np.min(dist) + >>> min_idx = np.argwhere(squareform(dist) == min_dist)[0] + >>> fig, ax = plt.subplots(figsize=(10, 5)) + >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$', + ... xlim=[0, 1], ylim=[0, 1]) + >>> for edge in edges: + ... ax.plot(sample[edge, 0], sample[edge, 1], c='k') + >>> ax.scatter(sample[:, 0], sample[:, 1]) + >>> ax.add_patch(plt.Circle(sample[min_idx[0]], min_dist, color='red', fill=False)) + >>> markers = [ + ... Line2D([0], [0], marker='o', lw=0, label='Sample points'), + ... Line2D([0], [0], color='k', label='Minimum spanning tree'), + ... Line2D([0], [0], marker='o', lw=0, markerfacecolor='w', markeredgecolor='r', + ... label='Minimum point-to-point distance'), + ... ] + >>> ax.legend(handles=markers, loc='center left', bbox_to_anchor=(1, 0.5)); + >>> plt.show() + + """ + sample = _ensure_in_unit_hypercube(sample) + if sample.shape[0] < 2: + raise ValueError("Sample must contain at least two points") + + distances = distance.pdist(sample, metric=metric) # type: ignore[call-overload] + + if np.any(distances == 0.0): + warnings.warn("Sample contains duplicate points.", stacklevel=2) + + if method == "mindist": + return np.min(distances[distances.nonzero()]) + elif method == "mst": + fully_connected_graph = distance.squareform(distances) + mst = minimum_spanning_tree(fully_connected_graph) + distances = mst[mst.nonzero()] + # TODO consider returning both the mean and the standard deviation + # see [1] for a discussion + return np.mean(distances) + else: + raise ValueError(f"{method!r} is not a valid method. " + f"It must be one of {{'mindist', 'mst'}}") + + +def update_discrepancy( + x_new: "npt.ArrayLike", + sample: "npt.ArrayLike", + initial_disc: DecimalNumber) -> float: + """Update the centered discrepancy with a new sample. + + Parameters + ---------- + x_new : array_like (1, d) + The new sample to add in `sample`. + sample : array_like (n, d) + The initial sample. + initial_disc : float + Centered discrepancy of the `sample`. + + Returns + ------- + discrepancy : float + Centered discrepancy of the sample composed of `x_new` and `sample`. + + Examples + -------- + We can also compute iteratively the discrepancy by using + ``iterative=True``. + + >>> import numpy as np + >>> from scipy.stats import qmc + >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]]) + >>> l_bounds = [0.5, 0.5] + >>> u_bounds = [6.5, 6.5] + >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True) + >>> disc_init = qmc.discrepancy(space[:-1], iterative=True) + >>> disc_init + 0.04769081147119336 + >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init) + 0.008142039609053513 + + """ + sample = np.asarray(sample, dtype=np.float64, order="C") + x_new = np.asarray(x_new, dtype=np.float64, order="C") + + # Checking that sample is within the hypercube and 2D + if not sample.ndim == 2: + raise ValueError('Sample is not a 2D array') + + if (sample.max() > 1.) or (sample.min() < 0.): + raise ValueError('Sample is not in unit hypercube') + + # Checking that x_new is within the hypercube and 1D + if not x_new.ndim == 1: + raise ValueError('x_new is not a 1D array') + + if not (np.all(x_new >= 0) and np.all(x_new <= 1)): + raise ValueError('x_new is not in unit hypercube') + + if x_new.shape[0] != sample.shape[1]: + raise ValueError("x_new and sample must be broadcastable") + + return _cy_wrapper_update_discrepancy(x_new, sample, initial_disc) + + +def _perturb_discrepancy(sample: np.ndarray, i1: int, i2: int, k: int, + disc: float): + """Centered discrepancy after an elementary perturbation of a LHS. + + An elementary perturbation consists of an exchange of coordinates between + two points: ``sample[i1, k] <-> sample[i2, k]``. By construction, + this operation conserves the LHS properties. + + Parameters + ---------- + sample : array_like (n, d) + The sample (before permutation) to compute the discrepancy from. + i1 : int + The first line of the elementary permutation. + i2 : int + The second line of the elementary permutation. + k : int + The column of the elementary permutation. + disc : float + Centered discrepancy of the design before permutation. + + Returns + ------- + discrepancy : float + Centered discrepancy of the design after permutation. + + References + ---------- + .. [1] Jin et al. "An efficient algorithm for constructing optimal design + of computer experiments", Journal of Statistical Planning and + Inference, 2005. + + """ + n = sample.shape[0] + + z_ij = sample - 0.5 + + # Eq (19) + c_i1j = (1. / n ** 2. + * np.prod(0.5 * (2. + abs(z_ij[i1, :]) + + abs(z_ij) - abs(z_ij[i1, :] - z_ij)), axis=1)) + c_i2j = (1. / n ** 2. + * np.prod(0.5 * (2. + abs(z_ij[i2, :]) + + abs(z_ij) - abs(z_ij[i2, :] - z_ij)), axis=1)) + + # Eq (20) + c_i1i1 = (1. / n ** 2 * np.prod(1 + abs(z_ij[i1, :])) + - 2. / n * np.prod(1. + 0.5 * abs(z_ij[i1, :]) + - 0.5 * z_ij[i1, :] ** 2)) + c_i2i2 = (1. / n ** 2 * np.prod(1 + abs(z_ij[i2, :])) + - 2. / n * np.prod(1. + 0.5 * abs(z_ij[i2, :]) + - 0.5 * z_ij[i2, :] ** 2)) + + # Eq (22), typo in the article in the denominator i2 -> i1 + num = (2 + abs(z_ij[i2, k]) + abs(z_ij[:, k]) + - abs(z_ij[i2, k] - z_ij[:, k])) + denum = (2 + abs(z_ij[i1, k]) + abs(z_ij[:, k]) + - abs(z_ij[i1, k] - z_ij[:, k])) + gamma = num / denum + + # Eq (23) + c_p_i1j = gamma * c_i1j + # Eq (24) + c_p_i2j = c_i2j / gamma + + alpha = (1 + abs(z_ij[i2, k])) / (1 + abs(z_ij[i1, k])) + beta = (2 - abs(z_ij[i2, k])) / (2 - abs(z_ij[i1, k])) + + g_i1 = np.prod(1. + abs(z_ij[i1, :])) + g_i2 = np.prod(1. + abs(z_ij[i2, :])) + h_i1 = np.prod(1. + 0.5 * abs(z_ij[i1, :]) - 0.5 * (z_ij[i1, :] ** 2)) + h_i2 = np.prod(1. + 0.5 * abs(z_ij[i2, :]) - 0.5 * (z_ij[i2, :] ** 2)) + + # Eq (25), typo in the article g is missing + c_p_i1i1 = ((g_i1 * alpha) / (n ** 2) - 2. * alpha * beta * h_i1 / n) + # Eq (26), typo in the article n ** 2 + c_p_i2i2 = ((g_i2 / ((n ** 2) * alpha)) - (2. * h_i2 / (n * alpha * beta))) + + # Eq (26) + sum_ = c_p_i1j - c_i1j + c_p_i2j - c_i2j + + mask = np.ones(n, dtype=bool) + mask[[i1, i2]] = False + sum_ = sum(sum_[mask]) + + disc_ep = (disc + c_p_i1i1 - c_i1i1 + c_p_i2i2 - c_i2i2 + 2 * sum_) + + return disc_ep + + +def primes_from_2_to(n: int) -> np.ndarray: + """Prime numbers from 2 to *n*. + + Parameters + ---------- + n : int + Sup bound with ``n >= 6``. + + Returns + ------- + primes : list(int) + Primes in ``2 <= p < n``. + + Notes + ----- + Taken from [1]_ by P.T. Roy, written consent given on 23.04.2021 + by the original author, Bruno Astrolino, for free use in SciPy under + the 3-clause BSD. + + References + ---------- + .. [1] `StackOverflow `_. + + """ + sieve = np.ones(n // 3 + (n % 6 == 2), dtype=bool) + for i in range(1, int(n ** 0.5) // 3 + 1): + k = 3 * i + 1 | 1 + sieve[k * k // 3::2 * k] = False + sieve[k * (k - 2 * (i & 1) + 4) // 3::2 * k] = False + return np.r_[2, 3, ((3 * np.nonzero(sieve)[0][1:] + 1) | 1)] + + +def n_primes(n: IntNumber) -> list[int]: + """List of the n-first prime numbers. + + Parameters + ---------- + n : int + Number of prime numbers wanted. + + Returns + ------- + primes : list(int) + List of primes. + + """ + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, + 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, + 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, + 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, + 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, + 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, + 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, + 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, + 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, + 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, + 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, + 953, 967, 971, 977, 983, 991, 997][:n] + + if len(primes) < n: + big_number = 2000 + while 'Not enough primes': + primes = primes_from_2_to(big_number)[:n] # type: ignore + if len(primes) == n: + break + big_number += 1000 + + return primes + + +def _van_der_corput_permutations( + base: IntNumber, *, rng: SeedType = None +) -> np.ndarray: + """Permutations for scrambling a Van der Corput sequence. + + Parameters + ---------- + base : int + Base of the sequence. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. During the transition, the behavior documented above is not + accurate; see `check_random_state` for actual behavior. After the + transition, this admonition can be removed. + + Returns + ------- + permutations : array_like + Permutation indices. + + Notes + ----- + In Algorithm 1 of Owen 2017, a permutation of `np.arange(base)` is + created for each positive integer `k` such that ``1 - base**-k < 1`` + using floating-point arithmetic. For double precision floats, the + condition ``1 - base**-k < 1`` can also be written as ``base**-k > + 2**-54``, which makes it more apparent how many permutations we need + to create. + """ + rng = check_random_state(rng) + count = math.ceil(54 / math.log2(base)) - 1 + permutations = np.repeat(np.arange(base)[None], count, axis=0) + for perm in permutations: + rng.shuffle(perm) + + return permutations + + +def van_der_corput( + n: IntNumber, + base: IntNumber = 2, + *, + start_index: IntNumber = 0, + scramble: bool = False, + permutations: "npt.ArrayLike | None" = None, + rng: SeedType = None, + workers: IntNumber = 1) -> np.ndarray: + """Van der Corput sequence. + + Pseudo-random number generator based on a b-adic expansion. + + Scrambling uses permutations of the remainders (see [1]_). Multiple + permutations are applied to construct a point. The sequence of + permutations has to be the same for all points of the sequence. + + Parameters + ---------- + n : int + Number of element of the sequence. + base : int, optional + Base of the sequence. Default is 2. + start_index : int, optional + Index to start the sequence from. Default is 0. + scramble : bool, optional + If True, use Owen scrambling. Otherwise no scrambling is done. + Default is True. + permutations : array_like, optional + Permutations used for scrambling. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + workers : int, optional + Number of workers to use for parallel processing. If -1 is + given all CPU threads are used. Default is 1. + + Returns + ------- + sequence : list (n,) + Sequence of Van der Corput. + + References + ---------- + .. [1] A. B. Owen. "A randomized Halton algorithm in R", + :arxiv:`1706.02808`, 2017. + + """ + if base < 2: + raise ValueError("'base' must be at least 2") + + if scramble: + if permutations is None: + permutations = _van_der_corput_permutations( + base=base, rng=rng + ) + else: + permutations = np.asarray(permutations) + + permutations = permutations.astype(np.int64) + return _cy_van_der_corput_scrambled(n, base, start_index, + permutations, workers) + + else: + return _cy_van_der_corput(n, base, start_index, workers) + + +class QMCEngine(ABC): + """A generic Quasi-Monte Carlo sampler class meant for subclassing. + + QMCEngine is a base class to construct a specific Quasi-Monte Carlo + sampler. It cannot be used directly as a sampler. + + Parameters + ---------- + d : int + Dimension of the parameter space. + optimization : {None, "random-cd", "lloyd"}, optional + Whether to use an optimization scheme to improve the quality after + sampling. Note that this is a post-processing step that does not + guarantee that all properties of the sample will be conserved. + Default is None. + + * ``random-cd``: random permutations of coordinates to lower the + centered discrepancy. The best sample based on the centered + discrepancy is constantly updated. Centered discrepancy-based + sampling shows better space-filling robustness toward 2D and 3D + subprojections compared to using other discrepancy measures. + * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm. + The process converges to equally spaced samples. + + .. versionadded:: 1.10.0 + + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `seed` keyword will emit warnings. Following a + deprecation period, the `seed` keyword will be removed. + + Notes + ----- + By convention samples are distributed over the half-open interval + ``[0, 1)``. Instances of the class can access the attributes: ``d`` for + the dimension; and ``rng`` for the random number generator. + + **Subclassing** + + When subclassing `QMCEngine` to create a new sampler, ``__init__`` and + ``random`` must be redefined. + + * ``__init__(d, rng=None)``: at least fix the dimension. If the sampler + does not take advantage of a ``rng`` (deterministic methods like + Halton), this parameter can be omitted. + * ``_random(n, *, workers=1)``: draw ``n`` from the engine. ``workers`` + is used for parallelism. See `Halton` for example. + + Optionally, two other methods can be overwritten by subclasses: + + * ``reset``: Reset the engine to its original state. + * ``fast_forward``: If the sequence is deterministic (like Halton + sequence), then ``fast_forward(n)`` is skipping the ``n`` first draw. + + Examples + -------- + To create a random sampler based on ``np.random.random``, we would do the + following: + + >>> from scipy.stats import qmc + >>> class RandomEngine(qmc.QMCEngine): + ... def __init__(self, d, rng=None): + ... super().__init__(d=d, rng=rng) + ... + ... + ... def _random(self, n=1, *, workers=1): + ... return self.rng.random((n, self.d)) + ... + ... + ... def reset(self): + ... super().__init__(d=self.d, rng=self.rng_seed) + ... return self + ... + ... + ... def fast_forward(self, n): + ... self.random(n) + ... return self + + After subclassing `QMCEngine` to define the sampling strategy we want to + use, we can create an instance to sample from. + + >>> engine = RandomEngine(2) + >>> engine.random(5) + array([[0.22733602, 0.31675834], # random + [0.79736546, 0.67625467], + [0.39110955, 0.33281393], + [0.59830875, 0.18673419], + [0.67275604, 0.94180287]]) + + We can also reset the state of the generator and resample again. + + >>> _ = engine.reset() + >>> engine.random(5) + array([[0.22733602, 0.31675834], # random + [0.79736546, 0.67625467], + [0.39110955, 0.33281393], + [0.59830875, 0.18673419], + [0.67275604, 0.94180287]]) + + """ + + @abstractmethod + @_transition_to_rng('seed', replace_doc=False) + def __init__( + self, + d: IntNumber, + *, + optimization: Literal["random-cd", "lloyd"] | None = None, + rng: SeedType = None + ) -> None: + self._initialize(d, optimization=optimization, rng=rng) + + # During SPEC 7 transition: + # `__init__` has to be wrapped with @_transition_to_rng decorator + # because it is public. Subclasses previously called `__init__` + # directly, but this was problematic because arguments passed to + # subclass `__init__` as `seed` would get passed to superclass + # `__init__` as `rng`, rejecting `RandomState` arguments. + def _initialize( + self, + d: IntNumber, + *, + optimization: Literal["random-cd", "lloyd"] | None = None, + rng: SeedType = None + ) -> None: + if not np.issubdtype(type(d), np.integer) or d < 0: + raise ValueError('d must be a non-negative integer value') + + self.d = d + + if isinstance(rng, np.random.Generator): + # Spawn a Generator that we can own and reset. + self.rng = _rng_spawn(rng, 1)[0] + else: + # Create our instance of Generator, does not need spawning + # Also catch RandomState which cannot be spawned + self.rng = check_random_state(rng) + self.rng_seed = copy.deepcopy(self.rng) + + self.num_generated = 0 + + config = { + # random-cd + "n_nochange": 100, + "n_iters": 10_000, + "rng": self.rng, + + # lloyd + "tol": 1e-5, + "maxiter": 10, + "qhull_options": None, + } + self._optimization = optimization + self.optimization_method = _select_optimizer(optimization, config) + + @abstractmethod + def _random( + self, n: IntNumber = 1, *, workers: IntNumber = 1 + ) -> np.ndarray: + ... + + def random( + self, n: IntNumber = 1, *, workers: IntNumber = 1 + ) -> np.ndarray: + """Draw `n` in the half-open interval ``[0, 1)``. + + Parameters + ---------- + n : int, optional + Number of samples to generate in the parameter space. + Default is 1. + workers : int, optional + Only supported with `Halton`. + Number of workers to use for parallel processing. If -1 is + given all CPU threads are used. Default is 1. It becomes faster + than one worker for `n` greater than :math:`10^3`. + + Returns + ------- + sample : array_like (n, d) + QMC sample. + + """ + sample = self._random(n, workers=workers) + if self.optimization_method is not None: + sample = self.optimization_method(sample) + + self.num_generated += n + return sample + + def integers( + self, + l_bounds: "npt.ArrayLike", + *, + u_bounds: "npt.ArrayLike | None" = None, + n: IntNumber = 1, + endpoint: bool = False, + workers: IntNumber = 1 + ) -> np.ndarray: + r""" + Draw `n` integers from `l_bounds` (inclusive) to `u_bounds` + (exclusive), or if endpoint=True, `l_bounds` (inclusive) to + `u_bounds` (inclusive). + + Parameters + ---------- + l_bounds : int or array-like of ints + Lowest (signed) integers to be drawn (unless ``u_bounds=None``, + in which case this parameter is 0 and this value is used for + `u_bounds`). + u_bounds : int or array-like of ints, optional + If provided, one above the largest (signed) integer to be drawn + (see above for behavior if ``u_bounds=None``). + If array-like, must contain integer values. + n : int, optional + Number of samples to generate in the parameter space. + Default is 1. + endpoint : bool, optional + If true, sample from the interval ``[l_bounds, u_bounds]`` instead + of the default ``[l_bounds, u_bounds)``. Defaults is False. + workers : int, optional + Number of workers to use for parallel processing. If -1 is + given all CPU threads are used. Only supported when using `Halton` + Default is 1. + + Returns + ------- + sample : array_like (n, d) + QMC sample. + + Notes + ----- + It is safe to just use the same ``[0, 1)`` to integer mapping + with QMC that you would use with MC. You still get unbiasedness, + a strong law of large numbers, an asymptotically infinite variance + reduction and a finite sample variance bound. + + To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`, + with :math:`a` the lower bounds and :math:`b` the upper bounds, + the following transformation is used: + + .. math:: + + \text{floor}((b - a) \cdot \text{sample} + a) + + """ + if u_bounds is None: + u_bounds = l_bounds + l_bounds = 0 + + u_bounds = np.atleast_1d(u_bounds) + l_bounds = np.atleast_1d(l_bounds) + + if endpoint: + u_bounds = u_bounds + 1 + + if (not np.issubdtype(l_bounds.dtype, np.integer) or + not np.issubdtype(u_bounds.dtype, np.integer)): + message = ("'u_bounds' and 'l_bounds' must be integers or" + " array-like of integers") + raise ValueError(message) + + if isinstance(self, Halton): + sample = self.random(n=n, workers=workers) + else: + sample = self.random(n=n) + + sample = scale(sample, l_bounds=l_bounds, u_bounds=u_bounds) + sample = np.floor(sample).astype(np.int64) + + return sample + + def reset(self) -> "QMCEngine": + """Reset the engine to base state. + + Returns + ------- + engine : QMCEngine + Engine reset to its base state. + + """ + rng = copy.deepcopy(self.rng_seed) + self.rng = check_random_state(rng) + self.num_generated = 0 + return self + + def fast_forward(self, n: IntNumber) -> "QMCEngine": + """Fast-forward the sequence by `n` positions. + + Parameters + ---------- + n : int + Number of points to skip in the sequence. + + Returns + ------- + engine : QMCEngine + Engine reset to its base state. + + """ + self.random(n=n) + return self + + +class Halton(QMCEngine): + """Halton sequence. + + Pseudo-random number generator that generalize the Van der Corput sequence + for multiple dimensions. The Halton sequence uses the base-two Van der + Corput sequence for the first dimension, base-three for its second and + base-:math:`n` for its n-dimension. + + Parameters + ---------- + d : int + Dimension of the parameter space. + scramble : bool, optional + If True, use Owen scrambling. Otherwise no scrambling is done. + Default is True. + optimization : {None, "random-cd", "lloyd"}, optional + Whether to use an optimization scheme to improve the quality after + sampling. Note that this is a post-processing step that does not + guarantee that all properties of the sample will be conserved. + Default is None. + + * ``random-cd``: random permutations of coordinates to lower the + centered discrepancy. The best sample based on the centered + discrepancy is constantly updated. Centered discrepancy-based + sampling shows better space-filling robustness toward 2D and 3D + subprojections compared to using other discrepancy measures. + * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm. + The process converges to equally spaced samples. + + .. versionadded:: 1.10.0 + + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `seed` keyword will emit warnings. Following a + deprecation period, the `seed` keyword will be removed. + + Notes + ----- + The Halton sequence has severe striping artifacts for even modestly + large dimensions. These can be ameliorated by scrambling. Scrambling + also supports replication-based error estimates and extends + applicability to unbounded integrands. + + References + ---------- + .. [1] Halton, "On the efficiency of certain quasi-random sequences of + points in evaluating multi-dimensional integrals", Numerische + Mathematik, 1960. + .. [2] A. B. Owen. "A randomized Halton algorithm in R", + :arxiv:`1706.02808`, 2017. + + Examples + -------- + Generate samples from a low discrepancy sequence of Halton. + + >>> from scipy.stats import qmc + >>> sampler = qmc.Halton(d=2, scramble=False) + >>> sample = sampler.random(n=5) + >>> sample + array([[0. , 0. ], + [0.5 , 0.33333333], + [0.25 , 0.66666667], + [0.75 , 0.11111111], + [0.125 , 0.44444444]]) + + Compute the quality of the sample using the discrepancy criterion. + + >>> qmc.discrepancy(sample) + 0.088893711419753 + + If some wants to continue an existing design, extra points can be obtained + by calling again `random`. Alternatively, you can skip some points like: + + >>> _ = sampler.fast_forward(5) + >>> sample_continued = sampler.random(n=5) + >>> sample_continued + array([[0.3125 , 0.37037037], + [0.8125 , 0.7037037 ], + [0.1875 , 0.14814815], + [0.6875 , 0.48148148], + [0.4375 , 0.81481481]]) + + Finally, samples can be scaled to bounds. + + >>> l_bounds = [0, 2] + >>> u_bounds = [10, 5] + >>> qmc.scale(sample_continued, l_bounds, u_bounds) + array([[3.125 , 3.11111111], + [8.125 , 4.11111111], + [1.875 , 2.44444444], + [6.875 , 3.44444444], + [4.375 , 4.44444444]]) + + """ + @_transition_to_rng('seed', replace_doc=False) + def __init__( + self, d: IntNumber, *, scramble: bool = True, + optimization: Literal["random-cd", "lloyd"] | None = None, + rng: SeedType = None + ) -> None: + # Used in `scipy.integrate.qmc_quad` + self._init_quad = {'d': d, 'scramble': True, + 'optimization': optimization} + super()._initialize(d=d, optimization=optimization, rng=rng) + + # important to have ``type(bdim) == int`` for performance reason + self.base = [int(bdim) for bdim in n_primes(d)] + self.scramble = scramble + + self._initialize_permutations() + + def _initialize_permutations(self) -> None: + """Initialize permutations for all Van der Corput sequences. + + Permutations are only needed for scrambling. + """ + self._permutations: list = [None] * len(self.base) + if self.scramble: + for i, bdim in enumerate(self.base): + permutations = _van_der_corput_permutations( + base=bdim, rng=self.rng + ) + + self._permutations[i] = permutations + + def _random( + self, n: IntNumber = 1, *, workers: IntNumber = 1 + ) -> np.ndarray: + """Draw `n` in the half-open interval ``[0, 1)``. + + Parameters + ---------- + n : int, optional + Number of samples to generate in the parameter space. Default is 1. + workers : int, optional + Number of workers to use for parallel processing. If -1 is + given all CPU threads are used. Default is 1. It becomes faster + than one worker for `n` greater than :math:`10^3`. + + Returns + ------- + sample : array_like (n, d) + QMC sample. + + """ + workers = _validate_workers(workers) + # Generate a sample using a Van der Corput sequence per dimension. + sample = [van_der_corput(n, bdim, start_index=self.num_generated, + scramble=self.scramble, + permutations=self._permutations[i], + workers=workers) + for i, bdim in enumerate(self.base)] + + return np.array(sample).T.reshape(n, self.d) + + +class LatinHypercube(QMCEngine): + r"""Latin hypercube sampling (LHS). + + A Latin hypercube sample [1]_ generates :math:`n` points in + :math:`[0,1)^{d}`. Each univariate marginal distribution is stratified, + placing exactly one point in :math:`[j/n, (j+1)/n)` for + :math:`j=0,1,...,n-1`. They are still applicable when :math:`n << d`. + + Parameters + ---------- + d : int + Dimension of the parameter space. + scramble : bool, optional + When False, center samples within cells of a multi-dimensional grid. + Otherwise, samples are randomly placed within cells of the grid. + + .. note:: + Setting ``scramble=False`` does not ensure deterministic output. + For that, use the `rng` parameter. + + Default is True. + + .. versionadded:: 1.10.0 + + optimization : {None, "random-cd", "lloyd"}, optional + Whether to use an optimization scheme to improve the quality after + sampling. Note that this is a post-processing step that does not + guarantee that all properties of the sample will be conserved. + Default is None. + + * ``random-cd``: random permutations of coordinates to lower the + centered discrepancy. The best sample based on the centered + discrepancy is constantly updated. Centered discrepancy-based + sampling shows better space-filling robustness toward 2D and 3D + subprojections compared to using other discrepancy measures. + * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm. + The process converges to equally spaced samples. + + .. versionadded:: 1.8.0 + .. versionchanged:: 1.10.0 + Add ``lloyd``. + + strength : {1, 2}, optional + Strength of the LHS. ``strength=1`` produces a plain LHS while + ``strength=2`` produces an orthogonal array based LHS of strength 2 + [7]_, [8]_. In that case, only ``n=p**2`` points can be sampled, + with ``p`` a prime number. It also constrains ``d <= p + 1``. + Default is 1. + + .. versionadded:: 1.8.0 + + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `seed` keyword will emit warnings. Following a + deprecation period, the `seed` keyword will be removed. + + See Also + -------- + :ref:`quasi-monte-carlo` + + Notes + ----- + + When LHS is used for integrating a function :math:`f` over :math:`n`, + LHS is extremely effective on integrands that are nearly additive [2]_. + With a LHS of :math:`n` points, the variance of the integral is always + lower than plain MC on :math:`n-1` points [3]_. There is a central limit + theorem for LHS on the mean and variance of the integral [4]_, but not + necessarily for optimized LHS due to the randomization. + + :math:`A` is called an orthogonal array of strength :math:`t` if in each + n-row-by-t-column submatrix of :math:`A`: all :math:`p^t` possible + distinct rows occur the same number of times. The elements of :math:`A` + are in the set :math:`\{0, 1, ..., p-1\}`, also called symbols. + The constraint that :math:`p` must be a prime number is to allow modular + arithmetic. Increasing strength adds some symmetry to the sub-projections + of a sample. With strength 2, samples are symmetric along the diagonals of + 2D sub-projections. This may be undesirable, but on the other hand, the + sample dispersion is improved. + + Strength 1 (plain LHS) brings an advantage over strength 0 (MC) and + strength 2 is a useful increment over strength 1. Going to strength 3 is + a smaller increment and scrambled QMC like Sobol', Halton are more + performant [7]_. + + To create a LHS of strength 2, the orthogonal array :math:`A` is + randomized by applying a random, bijective map of the set of symbols onto + itself. For example, in column 0, all 0s might become 2; in column 1, + all 0s might become 1, etc. + Then, for each column :math:`i` and symbol :math:`j`, we add a plain, + one-dimensional LHS of size :math:`p` to the subarray where + :math:`A^i = j`. The resulting matrix is finally divided by :math:`p`. + + References + ---------- + .. [1] Mckay et al., "A Comparison of Three Methods for Selecting Values + of Input Variables in the Analysis of Output from a Computer Code." + Technometrics, 1979. + .. [2] M. Stein, "Large sample properties of simulations using Latin + hypercube sampling." Technometrics 29, no. 2: 143-151, 1987. + .. [3] A. B. Owen, "Monte Carlo variance of scrambled net quadrature." + SIAM Journal on Numerical Analysis 34, no. 5: 1884-1910, 1997 + .. [4] Loh, W.-L. "On Latin hypercube sampling." The annals of statistics + 24, no. 5: 2058-2080, 1996. + .. [5] Fang et al. "Design and modeling for computer experiments". + Computer Science and Data Analysis Series, 2006. + .. [6] Damblin et al., "Numerical studies of space filling designs: + optimization of Latin Hypercube Samples and subprojection properties." + Journal of Simulation, 2013. + .. [7] A. B. Owen , "Orthogonal arrays for computer experiments, + integration and visualization." Statistica Sinica, 1992. + .. [8] B. Tang, "Orthogonal Array-Based Latin Hypercubes." + Journal of the American Statistical Association, 1993. + .. [9] Seaholm, Susan K. et al. (1988). Latin hypercube sampling and the + sensitivity analysis of a Monte Carlo epidemic model. Int J Biomed + Comput, 23(1-2), 97-112. :doi:`10.1016/0020-7101(88)90067-0` + + Examples + -------- + Generate samples from a Latin hypercube generator. + + >>> from scipy.stats import qmc + >>> sampler = qmc.LatinHypercube(d=2) + >>> sample = sampler.random(n=5) + >>> sample + array([[0.1545328 , 0.53664833], # random + [0.84052691, 0.06474907], + [0.52177809, 0.93343721], + [0.68033825, 0.36265316], + [0.26544879, 0.61163943]]) + + Compute the quality of the sample using the discrepancy criterion. + + >>> qmc.discrepancy(sample) + 0.0196... # random + + Samples can be scaled to bounds. + + >>> l_bounds = [0, 2] + >>> u_bounds = [10, 5] + >>> qmc.scale(sample, l_bounds, u_bounds) + array([[1.54532796, 3.609945 ], # random + [8.40526909, 2.1942472 ], + [5.2177809 , 4.80031164], + [6.80338249, 3.08795949], + [2.65448791, 3.83491828]]) + + Below are other examples showing alternative ways to construct LHS with + even better coverage of the space. + + Using a base LHS as a baseline. + + >>> sampler = qmc.LatinHypercube(d=2) + >>> sample = sampler.random(n=5) + >>> qmc.discrepancy(sample) + 0.0196... # random + + Use the `optimization` keyword argument to produce a LHS with + lower discrepancy at higher computational cost. + + >>> sampler = qmc.LatinHypercube(d=2, optimization="random-cd") + >>> sample = sampler.random(n=5) + >>> qmc.discrepancy(sample) + 0.0176... # random + + Use the `strength` keyword argument to produce an orthogonal array based + LHS of strength 2. In this case, the number of sample points must be the + square of a prime number. + + >>> sampler = qmc.LatinHypercube(d=2, strength=2) + >>> sample = sampler.random(n=9) + >>> qmc.discrepancy(sample) + 0.00526... # random + + Options could be combined to produce an optimized centered + orthogonal array based LHS. After optimization, the result would not + be guaranteed to be of strength 2. + + **Real-world example** + + In [9]_, a Latin Hypercube sampling (LHS) strategy was used to sample a + parameter space to study the importance of each parameter of an epidemic + model. Such analysis is also called a sensitivity analysis. + + Since the dimensionality of the problem is high (6), it is computationally + expensive to cover the space. When numerical experiments are costly, QMC + enables analysis that may not be possible if using a grid. + + The six parameters of the model represented the probability of illness, + the probability of withdrawal, and four contact probabilities. The + authors assumed uniform distributions for all parameters and generated + 50 samples. + + Using `scipy.stats.qmc.LatinHypercube` to replicate the protocol, + the first step is to create a sample in the unit hypercube: + + >>> from scipy.stats import qmc + >>> sampler = qmc.LatinHypercube(d=6) + >>> sample = sampler.random(n=50) + + Then the sample can be scaled to the appropriate bounds: + + >>> l_bounds = [0.000125, 0.01, 0.0025, 0.05, 0.47, 0.7] + >>> u_bounds = [0.000375, 0.03, 0.0075, 0.15, 0.87, 0.9] + >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds) + + Such a sample was used to run the model 50 times, and a polynomial + response surface was constructed. This allowed the authors to study the + relative importance of each parameter across the range of possibilities + of every other parameter. + + In this computer experiment, they showed a 14-fold reduction in the + number of samples required to maintain an error below 2% on their + response surface when compared to a grid sampling. + + """ + + @_transition_to_rng('seed', replace_doc=False) + def __init__( + self, d: IntNumber, *, + scramble: bool = True, + strength: int = 1, + optimization: Literal["random-cd", "lloyd"] | None = None, + rng: SeedType = None + ) -> None: + # Used in `scipy.integrate.qmc_quad` + self._init_quad = {'d': d, 'scramble': True, 'strength': strength, + 'optimization': optimization} + super()._initialize(d=d, rng=rng, optimization=optimization) + self.scramble = scramble + + lhs_method_strength = { + 1: self._random_lhs, + 2: self._random_oa_lhs + } + + try: + self.lhs_method: Callable = lhs_method_strength[strength] + except KeyError as exc: + message = (f"{strength!r} is not a valid strength. It must be one" + f" of {set(lhs_method_strength)!r}") + raise ValueError(message) from exc + + def _random( + self, n: IntNumber = 1, *, workers: IntNumber = 1 + ) -> np.ndarray: + lhs = self.lhs_method(n) + return lhs + + def _random_lhs(self, n: IntNumber = 1) -> np.ndarray: + """Base LHS algorithm.""" + if not self.scramble: + samples: np.ndarray | float = 0.5 + else: + samples = self.rng.uniform(size=(n, self.d)) + + perms = np.tile(np.arange(1, n + 1), + (self.d, 1)) # type: ignore[arg-type] + for i in range(self.d): + self.rng.shuffle(perms[i, :]) + perms = perms.T + + samples = (perms - samples) / n + return samples + + def _random_oa_lhs(self, n: IntNumber = 4) -> np.ndarray: + """Orthogonal array based LHS of strength 2.""" + p = np.sqrt(n).astype(int) + n_row = p**2 + n_col = p + 1 + + primes = primes_from_2_to(p + 1) + if p not in primes or n != n_row: + raise ValueError( + "n is not the square of a prime number. Close" + f" values are {primes[-2:]**2}" + ) + if self.d > p + 1: + raise ValueError("n is too small for d. Must be n > (d-1)**2") + + oa_sample = np.zeros(shape=(n_row, n_col), dtype=int) + + # OA of strength 2 + arrays = np.tile(np.arange(p), (2, 1)) + oa_sample[:, :2] = np.stack(np.meshgrid(*arrays), + axis=-1).reshape(-1, 2) + for p_ in range(1, p): + oa_sample[:, 2+p_-1] = np.mod(oa_sample[:, 0] + + p_*oa_sample[:, 1], p) + + # scramble the OA + oa_sample_ = np.empty(shape=(n_row, n_col), dtype=int) + for j in range(n_col): + perms = self.rng.permutation(p) + oa_sample_[:, j] = perms[oa_sample[:, j]] + + oa_sample = oa_sample_ + # following is making a scrambled OA into an OA-LHS + oa_lhs_sample = np.zeros(shape=(n_row, n_col)) + lhs_engine = LatinHypercube(d=1, scramble=self.scramble, strength=1, + rng=self.rng) # type: QMCEngine + for j in range(n_col): + for k in range(p): + idx = oa_sample[:, j] == k + lhs = lhs_engine.random(p).flatten() + oa_lhs_sample[:, j][idx] = lhs + oa_sample[:, j][idx] + + oa_lhs_sample /= p + + return oa_lhs_sample[:, :self.d] + + +class Sobol(QMCEngine): + """Engine for generating (scrambled) Sobol' sequences. + + Sobol' sequences are low-discrepancy, quasi-random numbers. Points + can be drawn using two methods: + + * `random_base2`: safely draw :math:`n=2^m` points. This method + guarantees the balance properties of the sequence. + * `random`: draw an arbitrary number of points from the + sequence. See warning below. + + Parameters + ---------- + d : int + Dimensionality of the sequence. Max dimensionality is 21201. + scramble : bool, optional + If True, use LMS+shift scrambling. Otherwise, no scrambling is done. + Default is True. + bits : int, optional + Number of bits of the generator. Control the maximum number of points + that can be generated, which is ``2**bits``. Maximal value is 64. + It does not correspond to the return type, which is always + ``np.float64`` to prevent points from repeating themselves. + Default is None, which for backward compatibility, corresponds to 30. + + .. versionadded:: 1.9.0 + optimization : {None, "random-cd", "lloyd"}, optional + Whether to use an optimization scheme to improve the quality after + sampling. Note that this is a post-processing step that does not + guarantee that all properties of the sample will be conserved. + Default is None. + + * ``random-cd``: random permutations of coordinates to lower the + centered discrepancy. The best sample based on the centered + discrepancy is constantly updated. Centered discrepancy-based + sampling shows better space-filling robustness toward 2D and 3D + subprojections compared to using other discrepancy measures. + * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm. + The process converges to equally spaced samples. + + .. versionadded:: 1.10.0 + + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `seed` keyword will emit warnings. Following a + deprecation period, the `seed` keyword will be removed. + + Notes + ----- + Sobol' sequences [1]_ provide :math:`n=2^m` low discrepancy points in + :math:`[0,1)^{d}`. Scrambling them [3]_ makes them suitable for singular + integrands, provides a means of error estimation, and can improve their + rate of convergence. The scrambling strategy which is implemented is a + (left) linear matrix scramble (LMS) followed by a digital random shift + (LMS+shift) [2]_. + + There are many versions of Sobol' sequences depending on their + 'direction numbers'. This code uses direction numbers from [4]_. Hence, + the maximum number of dimension is 21201. The direction numbers have been + precomputed with search criterion 6 and can be retrieved at + https://web.maths.unsw.edu.au/~fkuo/sobol/. + + .. warning:: + + Sobol' sequences are a quadrature rule and they lose their balance + properties if one uses a sample size that is not a power of 2, or skips + the first point, or thins the sequence [5]_. + + If :math:`n=2^m` points are not enough then one should take :math:`2^M` + points for :math:`M>m`. When scrambling, the number R of independent + replicates does not have to be a power of 2. + + Sobol' sequences are generated to some number :math:`B` of bits. + After :math:`2^B` points have been generated, the sequence would + repeat. Hence, an error is raised. + The number of bits can be controlled with the parameter `bits`. + + References + ---------- + .. [1] I. M. Sobol', "The distribution of points in a cube and the accurate + evaluation of integrals." Zh. Vychisl. Mat. i Mat. Phys., 7:784-802, + 1967. + .. [2] J. Matousek, "On the L2-discrepancy for anchored boxes." + J. of Complexity 14, 527-556, 1998. + .. [3] Art B. Owen, "Scrambling Sobol and Niederreiter-Xing points." + Journal of Complexity, 14(4):466-489, December 1998. + .. [4] S. Joe and F. Y. Kuo, "Constructing sobol sequences with better + two-dimensional projections." SIAM Journal on Scientific Computing, + 30(5):2635-2654, 2008. + .. [5] Art B. Owen, "On dropping the first Sobol' point." + :arxiv:`2008.08051`, 2020. + + Examples + -------- + Generate samples from a low discrepancy sequence of Sobol'. + + >>> from scipy.stats import qmc + >>> sampler = qmc.Sobol(d=2, scramble=False) + >>> sample = sampler.random_base2(m=3) + >>> sample + array([[0. , 0. ], + [0.5 , 0.5 ], + [0.75 , 0.25 ], + [0.25 , 0.75 ], + [0.375, 0.375], + [0.875, 0.875], + [0.625, 0.125], + [0.125, 0.625]]) + + Compute the quality of the sample using the discrepancy criterion. + + >>> qmc.discrepancy(sample) + 0.013882107204860938 + + To continue an existing design, extra points can be obtained + by calling again `random_base2`. Alternatively, you can skip some + points like: + + >>> _ = sampler.reset() + >>> _ = sampler.fast_forward(4) + >>> sample_continued = sampler.random_base2(m=2) + >>> sample_continued + array([[0.375, 0.375], + [0.875, 0.875], + [0.625, 0.125], + [0.125, 0.625]]) + + Finally, samples can be scaled to bounds. + + >>> l_bounds = [0, 2] + >>> u_bounds = [10, 5] + >>> qmc.scale(sample_continued, l_bounds, u_bounds) + array([[3.75 , 3.125], + [8.75 , 4.625], + [6.25 , 2.375], + [1.25 , 3.875]]) + + """ + + MAXDIM: ClassVar[int] = _MAXDIM + + @_transition_to_rng('seed', replace_doc=False) + def __init__( + self, d: IntNumber, *, scramble: bool = True, + bits: IntNumber | None = None, rng: SeedType = None, + optimization: Literal["random-cd", "lloyd"] | None = None + ) -> None: + # Used in `scipy.integrate.qmc_quad` + self._init_quad = {'d': d, 'scramble': True, 'bits': bits, + 'optimization': optimization} + + super()._initialize(d=d, optimization=optimization, rng=rng) + if d > self.MAXDIM: + raise ValueError( + f"Maximum supported dimensionality is {self.MAXDIM}." + ) + + self.bits = bits + self.dtype_i: type + self.scramble = scramble + + if self.bits is None: + self.bits = 30 + + if self.bits <= 32: + self.dtype_i = np.uint32 + elif 32 < self.bits <= 64: + self.dtype_i = np.uint64 + else: + raise ValueError("Maximum supported 'bits' is 64") + + self.maxn = 2**self.bits + + # v is d x maxbit matrix + self._sv: np.ndarray = np.zeros((d, self.bits), dtype=self.dtype_i) + _initialize_v(self._sv, dim=d, bits=self.bits) + + if not scramble: + self._shift: np.ndarray = np.zeros(d, dtype=self.dtype_i) + else: + # scramble self._shift and self._sv + self._scramble() + + self._quasi = self._shift.copy() + + # normalization constant with the largest possible number + # calculate in Python to not overflow int with 2**64 + self._scale = 1.0 / 2 ** self.bits + + self._first_point = (self._quasi * self._scale).reshape(1, -1) + # explicit casting to float64 + self._first_point = self._first_point.astype(np.float64) + + def _scramble(self) -> None: + """Scramble the sequence using LMS+shift.""" + # Generate shift vector + self._shift = np.dot( + rng_integers(self.rng, 2, size=(self.d, self.bits), + dtype=self.dtype_i), + 2 ** np.arange(self.bits, dtype=self.dtype_i), + ) + # Generate lower triangular matrices (stacked across dimensions) + ltm = np.tril(rng_integers(self.rng, 2, + size=(self.d, self.bits, self.bits), + dtype=self.dtype_i)) + _cscramble( + dim=self.d, bits=self.bits, # type: ignore[arg-type] + ltm=ltm, sv=self._sv + ) + + def _random( + self, n: IntNumber = 1, *, workers: IntNumber = 1 + ) -> np.ndarray: + """Draw next point(s) in the Sobol' sequence. + + Parameters + ---------- + n : int, optional + Number of samples to generate in the parameter space. Default is 1. + + Returns + ------- + sample : array_like (n, d) + Sobol' sample. + + """ + sample: np.ndarray = np.empty((n, self.d), dtype=np.float64) + + if n == 0: + return sample + + total_n = self.num_generated + n + if total_n > self.maxn: + msg = ( + f"At most 2**{self.bits}={self.maxn} distinct points can be " + f"generated. {self.num_generated} points have been previously " + f"generated, then: n={self.num_generated}+{n}={total_n}. " + ) + if self.bits != 64: + msg += "Consider increasing `bits`." + raise ValueError(msg) + + if self.num_generated == 0: + # verify n is 2**n + if not (n & (n - 1) == 0): + warnings.warn("The balance properties of Sobol' points require" + " n to be a power of 2.", stacklevel=2) + + if n == 1: + sample = self._first_point + else: + _draw( + n=n - 1, num_gen=self.num_generated, dim=self.d, + scale=self._scale, sv=self._sv, quasi=self._quasi, + sample=sample + ) + sample = np.concatenate( + [self._first_point, sample] + )[:n] + else: + _draw( + n=n, num_gen=self.num_generated - 1, dim=self.d, + scale=self._scale, sv=self._sv, quasi=self._quasi, + sample=sample + ) + + return sample + + def random_base2(self, m: IntNumber) -> np.ndarray: + """Draw point(s) from the Sobol' sequence. + + This function draws :math:`n=2^m` points in the parameter space + ensuring the balance properties of the sequence. + + Parameters + ---------- + m : int + Logarithm in base 2 of the number of samples; i.e., n = 2^m. + + Returns + ------- + sample : array_like (n, d) + Sobol' sample. + + """ + n = 2 ** m + + total_n = self.num_generated + n + if not (total_n & (total_n - 1) == 0): + raise ValueError('The balance properties of Sobol\' points require ' + f'n to be a power of 2. {self.num_generated} points ' + 'have been previously generated, then: ' + f'n={self.num_generated}+2**{m}={total_n}. ' + 'If you still want to do this, the function ' + '\'Sobol.random()\' can be used.' + ) + + return self.random(n) + + def reset(self) -> "Sobol": + """Reset the engine to base state. + + Returns + ------- + engine : Sobol + Engine reset to its base state. + + """ + super().reset() + self._quasi = self._shift.copy() + return self + + def fast_forward(self, n: IntNumber) -> "Sobol": + """Fast-forward the sequence by `n` positions. + + Parameters + ---------- + n : int + Number of points to skip in the sequence. + + Returns + ------- + engine : Sobol + The fast-forwarded engine. + + """ + if self.num_generated == 0: + _fast_forward( + n=n - 1, num_gen=self.num_generated, dim=self.d, + sv=self._sv, quasi=self._quasi + ) + else: + _fast_forward( + n=n, num_gen=self.num_generated - 1, dim=self.d, + sv=self._sv, quasi=self._quasi + ) + self.num_generated += n + return self + + +class PoissonDisk(QMCEngine): + """Poisson disk sampling. + + Parameters + ---------- + d : int + Dimension of the parameter space. + radius : float + Minimal distance to keep between points when sampling new candidates. + hypersphere : {"volume", "surface"}, optional + Sampling strategy to generate potential candidates to be added in the + final sample. Default is "volume". + + * ``volume``: original Bridson algorithm as described in [1]_. + New candidates are sampled *within* the hypersphere. + * ``surface``: only sample the surface of the hypersphere. + ncandidates : int + Number of candidates to sample per iteration. More candidates result + in a denser sampling as more candidates can be accepted per iteration. + optimization : {None, "random-cd", "lloyd"}, optional + Whether to use an optimization scheme to improve the quality after + sampling. Note that this is a post-processing step that does not + guarantee that all properties of the sample will be conserved. + Default is None. + + * ``random-cd``: random permutations of coordinates to lower the + centered discrepancy. The best sample based on the centered + discrepancy is constantly updated. Centered discrepancy-based + sampling shows better space-filling robustness toward 2D and 3D + subprojections compared to using other discrepancy measures. + * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm. + The process converges to equally spaced samples. + + .. versionadded:: 1.10.0 + + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `seed` keyword will emit warnings. Following a + deprecation period, the `seed` keyword will be removed. + + l_bounds, u_bounds : array_like (d,) + Lower and upper bounds of target sample data. + + Notes + ----- + Poisson disk sampling is an iterative sampling strategy. Starting from + a seed sample, `ncandidates` are sampled in the hypersphere + surrounding the seed. Candidates below a certain `radius` or outside the + domain are rejected. New samples are added in a pool of sample seed. The + process stops when the pool is empty or when the number of required + samples is reached. + + The maximum number of point that a sample can contain is directly linked + to the `radius`. As the dimension of the space increases, a higher radius + spreads the points further and help overcome the curse of dimensionality. + See the :ref:`quasi monte carlo tutorial ` for more + details. + + .. warning:: + + The algorithm is more suitable for low dimensions and sampling size + due to its iterative nature and memory requirements. + Selecting a small radius with a high dimension would + mean that the space could contain more samples than using lower + dimension or a bigger radius. + + Some code taken from [2]_, written consent given on 31.03.2021 + by the original author, Shamis, for free use in SciPy under + the 3-clause BSD. + + References + ---------- + .. [1] Robert Bridson, "Fast Poisson Disk Sampling in Arbitrary + Dimensions." SIGGRAPH, 2007. + .. [2] `StackOverflow `__. + + Examples + -------- + Generate a 2D sample using a `radius` of 0.2. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from matplotlib.collections import PatchCollection + >>> from scipy.stats import qmc + >>> + >>> rng = np.random.default_rng() + >>> radius = 0.2 + >>> engine = qmc.PoissonDisk(d=2, radius=radius, rng=rng) + >>> sample = engine.random(20) + + Visualizing the 2D sample and showing that no points are closer than + `radius`. ``radius/2`` is used to visualize non-intersecting circles. + If two samples are exactly at `radius` from each other, then their circle + of radius ``radius/2`` will touch. + + >>> fig, ax = plt.subplots() + >>> _ = ax.scatter(sample[:, 0], sample[:, 1]) + >>> circles = [plt.Circle((xi, yi), radius=radius/2, fill=False) + ... for xi, yi in sample] + >>> collection = PatchCollection(circles, match_original=True) + >>> ax.add_collection(collection) + >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$', + ... xlim=[0, 1], ylim=[0, 1]) + >>> plt.show() + + Such visualization can be seen as circle packing: how many circle can + we put in the space. It is a np-hard problem. The method `fill_space` + can be used to add samples until no more samples can be added. This is + a hard problem and parameters may need to be adjusted manually. Beware of + the dimension: as the dimensionality increases, the number of samples + required to fill the space increases exponentially + (curse-of-dimensionality). + + """ + + @_transition_to_rng('seed', replace_doc=False) + def __init__( + self, + d: IntNumber, + *, + radius: DecimalNumber = 0.05, + hypersphere: Literal["volume", "surface"] = "volume", + ncandidates: IntNumber = 30, + optimization: Literal["random-cd", "lloyd"] | None = None, + rng: SeedType = None, + l_bounds: "npt.ArrayLike | None" = None, + u_bounds: "npt.ArrayLike | None" = None, + ) -> None: + # Used in `scipy.integrate.qmc_quad` + self._init_quad = {'d': d, 'radius': radius, + 'hypersphere': hypersphere, + 'ncandidates': ncandidates, + 'optimization': optimization} + super()._initialize(d=d, optimization=optimization, rng=rng) + + hypersphere_sample = { + "volume": self._hypersphere_volume_sample, + "surface": self._hypersphere_surface_sample + } + + try: + self.hypersphere_method = hypersphere_sample[hypersphere] + except KeyError as exc: + message = ( + f"{hypersphere!r} is not a valid hypersphere sampling" + f" method. It must be one of {set(hypersphere_sample)!r}") + raise ValueError(message) from exc + + # size of the sphere from which the samples are drawn relative to the + # size of a disk (radius) + # for the surface sampler, all new points are almost exactly 1 radius + # away from at least one existing sample +eps to avoid rejection + self.radius_factor = 2 if hypersphere == "volume" else 1.001 + self.radius = radius + self.radius_squared = self.radius**2 + + # sample to generate per iteration in the hypersphere around center + self.ncandidates = ncandidates + + if u_bounds is None: + u_bounds = np.ones(d) + if l_bounds is None: + l_bounds = np.zeros(d) + self.l_bounds, self.u_bounds = _validate_bounds( + l_bounds=l_bounds, u_bounds=u_bounds, d=int(d) + ) + + with np.errstate(divide='ignore'): + self.cell_size = self.radius / np.sqrt(self.d) + self.grid_size = ( + np.ceil((self.u_bounds - self.l_bounds) / self.cell_size) + ).astype(int) + + self._initialize_grid_pool() + + def _initialize_grid_pool(self): + """Sampling pool and sample grid.""" + self.sample_pool = [] + # Positions of cells + # n-dim value for each grid cell + self.sample_grid = np.empty( + np.append(self.grid_size, self.d), + dtype=np.float32 + ) + # Initialise empty cells with NaNs + self.sample_grid.fill(np.nan) + + def _random( + self, n: IntNumber = 1, *, workers: IntNumber = 1 + ) -> np.ndarray: + """Draw `n` in the interval ``[l_bounds, u_bounds]``. + + Note that it can return fewer samples if the space is full. + See the note section of the class. + + Parameters + ---------- + n : int, optional + Number of samples to generate in the parameter space. Default is 1. + + Returns + ------- + sample : array_like (n, d) + QMC sample. + + """ + if n == 0 or self.d == 0: + return np.empty((n, self.d)) + + def in_limits(sample: np.ndarray) -> bool: + for i in range(self.d): + if (sample[i] > self.u_bounds[i] or sample[i] < self.l_bounds[i]): + return False + return True + + def in_neighborhood(candidate: np.ndarray, n: int = 2) -> bool: + """ + Check if there are samples closer than ``radius_squared`` to the + `candidate` sample. + """ + indices = ((candidate - self.l_bounds) / self.cell_size).astype(int) + ind_min = np.maximum(indices - n, self.l_bounds.astype(int)) + ind_max = np.minimum(indices + n + 1, self.grid_size) + + # Check if the center cell is empty + if not np.isnan(self.sample_grid[tuple(indices)][0]): + return True + + a = [slice(ind_min[i], ind_max[i]) for i in range(self.d)] + + # guards against: invalid value encountered in less as we are + # comparing with nan and returns False. Which is wanted. + with np.errstate(invalid='ignore'): + if np.any( + np.sum( + np.square(candidate - self.sample_grid[tuple(a)]), + axis=self.d + ) < self.radius_squared + ): + return True + + return False + + def add_sample(candidate: np.ndarray) -> None: + self.sample_pool.append(candidate) + indices = ((candidate - self.l_bounds) / self.cell_size).astype(int) + self.sample_grid[tuple(indices)] = candidate + curr_sample.append(candidate) + + curr_sample: list[np.ndarray] = [] + + if len(self.sample_pool) == 0: + # the pool is being initialized with a single random sample + add_sample(self.rng.uniform(self.l_bounds, self.u_bounds)) + num_drawn = 1 + else: + num_drawn = 0 + + # exhaust sample pool to have up to n sample + while len(self.sample_pool) and num_drawn < n: + # select a sample from the available pool + idx_center = rng_integers(self.rng, len(self.sample_pool)) + center = self.sample_pool[idx_center] + del self.sample_pool[idx_center] + + # generate candidates around the center sample + candidates = self.hypersphere_method( + center, self.radius * self.radius_factor, self.ncandidates + ) + + # keep candidates that satisfy some conditions + for candidate in candidates: + if in_limits(candidate) and not in_neighborhood(candidate): + add_sample(candidate) + + num_drawn += 1 + if num_drawn >= n: + break + + self.num_generated += num_drawn + return np.array(curr_sample) + + def fill_space(self) -> np.ndarray: + """Draw ``n`` samples in the interval ``[l_bounds, u_bounds]``. + + Unlike `random`, this method will try to add points until + the space is full. Depending on ``candidates`` (and to a lesser extent + other parameters), some empty areas can still be present in the sample. + + .. warning:: + + This can be extremely slow in high dimensions or if the + ``radius`` is very small-with respect to the dimensionality. + + Returns + ------- + sample : array_like (n, d) + QMC sample. + + """ + return self.random(np.inf) # type: ignore[arg-type] + + def reset(self) -> "PoissonDisk": + """Reset the engine to base state. + + Returns + ------- + engine : PoissonDisk + Engine reset to its base state. + + """ + super().reset() + self._initialize_grid_pool() + return self + + def _hypersphere_volume_sample( + self, center: np.ndarray, radius: DecimalNumber, + candidates: IntNumber = 1 + ) -> np.ndarray: + """Uniform sampling within hypersphere.""" + # should remove samples within r/2 + x = self.rng.standard_normal(size=(candidates, self.d)) + ssq = np.sum(x**2, axis=1) + fr = radius * gammainc(self.d/2, ssq/2)**(1/self.d) / np.sqrt(ssq) + fr_tiled = np.tile( + fr.reshape(-1, 1), (1, self.d) # type: ignore[arg-type] + ) + p = center + np.multiply(x, fr_tiled) + return p + + def _hypersphere_surface_sample( + self, center: np.ndarray, radius: DecimalNumber, + candidates: IntNumber = 1 + ) -> np.ndarray: + """Uniform sampling on the hypersphere's surface.""" + vec = self.rng.standard_normal(size=(candidates, self.d)) + vec /= np.linalg.norm(vec, axis=1)[:, None] + p = center + np.multiply(vec, radius) + return p + + +class MultivariateNormalQMC: + r"""QMC sampling from a multivariate Normal :math:`N(\mu, \Sigma)`. + + Parameters + ---------- + mean : array_like (d,) + The mean vector. Where ``d`` is the dimension. + cov : array_like (d, d), optional + The covariance matrix. If omitted, use `cov_root` instead. + If both `cov` and `cov_root` are omitted, use the identity matrix. + cov_root : array_like (d, d'), optional + A root decomposition of the covariance matrix, where ``d'`` may be less + than ``d`` if the covariance is not full rank. If omitted, use `cov`. + inv_transform : bool, optional + If True, use inverse transform instead of Box-Muller. Default is True. + engine : QMCEngine, optional + Quasi-Monte Carlo engine sampler. If None, `Sobol` is used. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `seed` keyword will emit warnings. Following a + deprecation period, the `seed` keyword will be removed. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import qmc + >>> dist = qmc.MultivariateNormalQMC(mean=[0, 5], cov=[[1, 0], [0, 1]]) + >>> sample = dist.random(512) + >>> _ = plt.scatter(sample[:, 0], sample[:, 1]) + >>> plt.show() + + """ + + @_transition_to_rng('seed', replace_doc=False) + def __init__( + self, + mean: "npt.ArrayLike", + cov: "npt.ArrayLike | None" = None, + *, + cov_root: "npt.ArrayLike | None" = None, + inv_transform: bool = True, + engine: QMCEngine | None = None, + rng: SeedType = None, + ) -> None: + mean = np.asarray(np.atleast_1d(mean)) + d = mean.shape[0] + if cov is not None: + # covariance matrix provided + cov = np.asarray(np.atleast_2d(cov)) + # check for square/symmetric cov matrix and mean vector has the + # same d + if not mean.shape[0] == cov.shape[0]: + raise ValueError("Dimension mismatch between mean and " + "covariance.") + if not np.allclose(cov, cov.transpose()): + raise ValueError("Covariance matrix is not symmetric.") + # compute Cholesky decomp; if it fails, do the eigen decomposition + try: + cov_root = np.linalg.cholesky(cov).transpose() + except np.linalg.LinAlgError: + eigval, eigvec = np.linalg.eigh(cov) + if not np.all(eigval >= -1.0e-8): + raise ValueError("Covariance matrix not PSD.") + eigval = np.clip(eigval, 0.0, None) + cov_root = (eigvec * np.sqrt(eigval)).transpose() + elif cov_root is not None: + # root decomposition provided + cov_root = np.atleast_2d(cov_root) + if not mean.shape[0] == cov_root.shape[0]: + raise ValueError("Dimension mismatch between mean and " + "covariance.") + else: + # corresponds to identity covariance matrix + cov_root = None + + self._inv_transform = inv_transform + + if not inv_transform: + # to apply Box-Muller, we need an even number of dimensions + engine_dim = 2 * math.ceil(d / 2) + else: + engine_dim = d + if engine is None: + # Need this during SPEC 7 transition to prevent `RandomState` + # from being passed via `rng`. + kwarg = "seed" if isinstance(rng, np.random.RandomState) else "rng" + kwargs = {kwarg: rng} + self.engine = Sobol( + d=engine_dim, scramble=True, bits=30, **kwargs + ) # type: QMCEngine + elif isinstance(engine, QMCEngine): + if engine.d != engine_dim: + raise ValueError("Dimension of `engine` must be consistent" + " with dimensions of mean and covariance." + " If `inv_transform` is False, it must be" + " an even number.") + self.engine = engine + else: + raise ValueError("`engine` must be an instance of " + "`scipy.stats.qmc.QMCEngine` or `None`.") + + self._mean = mean + self._corr_matrix = cov_root + + self._d = d + + def random(self, n: IntNumber = 1) -> np.ndarray: + """Draw `n` QMC samples from the multivariate Normal. + + Parameters + ---------- + n : int, optional + Number of samples to generate in the parameter space. Default is 1. + + Returns + ------- + sample : array_like (n, d) + Sample. + + """ + base_samples = self._standard_normal_samples(n) + return self._correlate(base_samples) + + def _correlate(self, base_samples: np.ndarray) -> np.ndarray: + if self._corr_matrix is not None: + return base_samples @ self._corr_matrix + self._mean + else: + # avoid multiplying with identity here + return base_samples + self._mean + + def _standard_normal_samples(self, n: IntNumber = 1) -> np.ndarray: + """Draw `n` QMC samples from the standard Normal :math:`N(0, I_d)`. + + Parameters + ---------- + n : int, optional + Number of samples to generate in the parameter space. Default is 1. + + Returns + ------- + sample : array_like (n, d) + Sample. + + """ + # get base samples + samples = self.engine.random(n) + if self._inv_transform: + # apply inverse transform + # (values to close to 0/1 result in inf values) + return stats.norm.ppf(0.5 + (1 - 1e-10) * (samples - 0.5)) # type: ignore[attr-defined] # noqa: E501 + else: + # apply Box-Muller transform (note: indexes starting from 1) + even = np.arange(0, samples.shape[-1], 2) + Rs = np.sqrt(-2 * np.log(samples[:, even])) + thetas = 2 * math.pi * samples[:, 1 + even] + cos = np.cos(thetas) + sin = np.sin(thetas) + transf_samples = np.stack([Rs * cos, Rs * sin], + -1).reshape(n, -1) + # make sure we only return the number of dimension requested + return transf_samples[:, : self._d] + + +class MultinomialQMC: + r"""QMC sampling from a multinomial distribution. + + Parameters + ---------- + pvals : array_like (k,) + Vector of probabilities of size ``k``, where ``k`` is the number + of categories. Elements must be non-negative and sum to 1. + n_trials : int + Number of trials. + engine : QMCEngine, optional + Quasi-Monte Carlo engine sampler. If None, `Sobol` is used. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `seed` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `seed` keyword will emit warnings. Following a + deprecation period, the `seed` keyword will be removed. + + Examples + -------- + Let's define 3 categories and for a given sample, the sum of the trials + of each category is 8. The number of trials per category is determined + by the `pvals` associated to each category. + Then, we sample this distribution 64 times. + + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import qmc + >>> dist = qmc.MultinomialQMC( + ... pvals=[0.2, 0.4, 0.4], n_trials=10, engine=qmc.Halton(d=1) + ... ) + >>> sample = dist.random(64) + + We can plot the sample and verify that the median of number of trials + for each category is following the `pvals`. That would be + ``pvals * n_trials = [2, 4, 4]``. + + >>> fig, ax = plt.subplots() + >>> ax.yaxis.get_major_locator().set_params(integer=True) + >>> _ = ax.boxplot(sample) + >>> ax.set(xlabel="Categories", ylabel="Trials") + >>> plt.show() + + """ + + @_transition_to_rng('seed', replace_doc=False) + def __init__( + self, + pvals: "npt.ArrayLike", + n_trials: IntNumber, + *, + engine: QMCEngine | None = None, + rng: SeedType = None, + ) -> None: + self.pvals = np.atleast_1d(np.asarray(pvals)) + if np.min(pvals) < 0: + raise ValueError('Elements of pvals must be non-negative.') + if not np.isclose(np.sum(pvals), 1): + raise ValueError('Elements of pvals must sum to 1.') + self.n_trials = n_trials + if engine is None: + # Need this during SPEC 7 transition to prevent `RandomState` + # from being passed via `rng`. + kwarg = "seed" if isinstance(rng, np.random.RandomState) else "rng" + kwargs = {kwarg: rng} + self.engine = Sobol( + d=1, scramble=True, bits=30, **kwargs + ) # type: QMCEngine + elif isinstance(engine, QMCEngine): + if engine.d != 1: + raise ValueError("Dimension of `engine` must be 1.") + self.engine = engine + else: + raise ValueError("`engine` must be an instance of " + "`scipy.stats.qmc.QMCEngine` or `None`.") + + def random(self, n: IntNumber = 1) -> np.ndarray: + """Draw `n` QMC samples from the multinomial distribution. + + Parameters + ---------- + n : int, optional + Number of samples to generate in the parameter space. Default is 1. + + Returns + ------- + samples : array_like (n, pvals) + Sample. + + """ + sample = np.empty((n, len(self.pvals))) + for i in range(n): + base_draws = self.engine.random(self.n_trials).ravel() + p_cumulative = np.empty_like(self.pvals, dtype=float) + _fill_p_cumulative(np.array(self.pvals, dtype=float), p_cumulative) + sample_ = np.zeros_like(self.pvals, dtype=np.intp) + _categorize(base_draws, p_cumulative, sample_) + sample[i] = sample_ + return sample + + +def _select_optimizer( + optimization: Literal["random-cd", "lloyd"] | None, config: dict +) -> Callable | None: + """A factory for optimization methods.""" + optimization_method: dict[str, Callable] = { + "random-cd": _random_cd, + "lloyd": _lloyd_centroidal_voronoi_tessellation + } + + optimizer: partial | None + if optimization is not None: + try: + optimization = optimization.lower() # type: ignore[assignment] + optimizer_ = optimization_method[optimization] + except KeyError as exc: + message = (f"{optimization!r} is not a valid optimization" + f" method. It must be one of" + f" {set(optimization_method)!r}") + raise ValueError(message) from exc + + # config + optimizer = partial(optimizer_, **config) + else: + optimizer = None + + return optimizer + + +def _random_cd( + best_sample: np.ndarray, n_iters: int, n_nochange: int, rng: GeneratorType, + **kwargs: dict +) -> np.ndarray: + """Optimal LHS on CD. + + Create a base LHS and do random permutations of coordinates to + lower the centered discrepancy. + Because it starts with a normal LHS, it also works with the + `scramble` keyword argument. + + Two stopping criterion are used to stop the algorithm: at most, + `n_iters` iterations are performed; or if there is no improvement + for `n_nochange` consecutive iterations. + """ + del kwargs # only use keywords which are defined, needed by factory + + n, d = best_sample.shape + + if d == 0 or n == 0: + return np.empty((n, d)) + + if d == 1 or n == 1: + # discrepancy measures are invariant under permuting factors and runs + return best_sample + + best_disc = discrepancy(best_sample) + + bounds = ([0, d - 1], + [0, n - 1], + [0, n - 1]) + + n_nochange_ = 0 + n_iters_ = 0 + while n_nochange_ < n_nochange and n_iters_ < n_iters: + n_iters_ += 1 + + col = rng_integers(rng, *bounds[0], endpoint=True) # type: ignore[misc] + row_1 = rng_integers(rng, *bounds[1], endpoint=True) # type: ignore[misc] + row_2 = rng_integers(rng, *bounds[2], endpoint=True) # type: ignore[misc] + disc = _perturb_discrepancy(best_sample, + row_1, row_2, col, + best_disc) + if disc < best_disc: + best_sample[row_1, col], best_sample[row_2, col] = ( + best_sample[row_2, col], best_sample[row_1, col]) + + best_disc = disc + n_nochange_ = 0 + else: + n_nochange_ += 1 + + return best_sample + + +def _l1_norm(sample: np.ndarray) -> float: + return distance.pdist(sample, 'cityblock').min() + + +def _lloyd_iteration( + sample: np.ndarray, + decay: float, + qhull_options: str +) -> np.ndarray: + """Lloyd-Max algorithm iteration. + + Based on the implementation of Stéfan van der Walt: + + https://github.com/stefanv/lloyd + + which is: + + Copyright (c) 2021-04-21 Stéfan van der Walt + https://github.com/stefanv/lloyd + MIT License + + Parameters + ---------- + sample : array_like (n, d) + The sample to iterate on. + decay : float + Relaxation decay. A positive value would move the samples toward + their centroid, and negative value would move them away. + 1 would move the samples to their centroid. + qhull_options : str + Additional options to pass to Qhull. See Qhull manual + for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and + "Qbb Qc Qz Qj" otherwise.) + + Returns + ------- + sample : array_like (n, d) + The sample after an iteration of Lloyd's algorithm. + + """ + new_sample = np.empty_like(sample) + + voronoi = Voronoi(sample, qhull_options=qhull_options) + + for ii, idx in enumerate(voronoi.point_region): + # the region is a series of indices into self.voronoi.vertices + # remove samples at infinity, designated by index -1 + region = [i for i in voronoi.regions[idx] if i != -1] + + # get the vertices for this region + verts = voronoi.vertices[region] + + # clipping would be wrong, we need to intersect + # verts = np.clip(verts, 0, 1) + + # move samples towards centroids: + # Centroid in n-D is the mean for uniformly distributed nodes + # of a geometry. + centroid = np.mean(verts, axis=0) + new_sample[ii] = sample[ii] + (centroid - sample[ii]) * decay + + # only update sample to centroid within the region + is_valid = np.all(np.logical_and(new_sample >= 0, new_sample <= 1), axis=1) + sample[is_valid] = new_sample[is_valid] + + return sample + + +def _lloyd_centroidal_voronoi_tessellation( + sample: "npt.ArrayLike", + *, + tol: DecimalNumber = 1e-5, + maxiter: IntNumber = 10, + qhull_options: str | None = None, + **kwargs: dict +) -> np.ndarray: + """Approximate Centroidal Voronoi Tessellation. + + Perturb samples in N-dimensions using Lloyd-Max algorithm. + + Parameters + ---------- + sample : array_like (n, d) + The sample to iterate on. With ``n`` the number of samples and ``d`` + the dimension. Samples must be in :math:`[0, 1]^d`, with ``d>=2``. + tol : float, optional + Tolerance for termination. If the min of the L1-norm over the samples + changes less than `tol`, it stops the algorithm. Default is 1e-5. + maxiter : int, optional + Maximum number of iterations. It will stop the algorithm even if + `tol` is above the threshold. + Too many iterations tend to cluster the samples as a hypersphere. + Default is 10. + qhull_options : str, optional + Additional options to pass to Qhull. See Qhull manual + for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and + "Qbb Qc Qz Qj" otherwise.) + + Returns + ------- + sample : array_like (n, d) + The sample after being processed by Lloyd-Max algorithm. + + Notes + ----- + Lloyd-Max algorithm is an iterative process with the purpose of improving + the dispersion of samples. For given sample: (i) compute a Voronoi + Tessellation; (ii) find the centroid of each Voronoi cell; (iii) move the + samples toward the centroid of their respective cell. See [1]_, [2]_. + + A relaxation factor is used to control how fast samples can move at each + iteration. This factor is starting at 2 and ending at 1 after `maxiter` + following an exponential decay. + + The process converges to equally spaced samples. It implies that measures + like the discrepancy could suffer from too many iterations. On the other + hand, L1 and L2 distances should improve. This is especially true with + QMC methods which tend to favor the discrepancy over other criteria. + + .. note:: + + The current implementation does not intersect the Voronoi Tessellation + with the boundaries. This implies that for a low number of samples, + empirically below 20, no Voronoi cell is touching the boundaries. + Hence, samples cannot be moved close to the boundaries. + + Further improvements could consider the samples at infinity so that + all boundaries are segments of some Voronoi cells. This would fix + the computation of the centroid position. + + .. warning:: + + The Voronoi Tessellation step is expensive and quickly becomes + intractable with dimensions as low as 10 even for a sample + of size as low as 1000. + + .. versionadded:: 1.9.0 + + References + ---------- + .. [1] Lloyd. "Least Squares Quantization in PCM". + IEEE Transactions on Information Theory, 1982. + .. [2] Max J. "Quantizing for minimum distortion". + IEEE Transactions on Information Theory, 1960. + + Examples + -------- + >>> import numpy as np + >>> from scipy.spatial import distance + >>> from scipy.stats._qmc import _lloyd_centroidal_voronoi_tessellation + >>> rng = np.random.default_rng() + >>> sample = rng.random((128, 2)) + + .. note:: + + The samples need to be in :math:`[0, 1]^d`. `scipy.stats.qmc.scale` + can be used to scale the samples from their + original bounds to :math:`[0, 1]^d`. And back to their original bounds. + + Compute the quality of the sample using the L1 criterion. + + >>> def l1_norm(sample): + ... return distance.pdist(sample, 'cityblock').min() + + >>> l1_norm(sample) + 0.00161... # random + + Now process the sample using Lloyd's algorithm and check the improvement + on the L1. The value should increase. + + >>> sample = _lloyd_centroidal_voronoi_tessellation(sample) + >>> l1_norm(sample) + 0.0278... # random + + """ + del kwargs # only use keywords which are defined, needed by factory + + sample = np.asarray(sample).copy() + + if not sample.ndim == 2: + raise ValueError('`sample` is not a 2D array') + + if not sample.shape[1] >= 2: + raise ValueError('`sample` dimension is not >= 2') + + # Checking that sample is within the hypercube + if (sample.max() > 1.) or (sample.min() < 0.): + raise ValueError('`sample` is not in unit hypercube') + + if qhull_options is None: + qhull_options = 'Qbb Qc Qz QJ' + + if sample.shape[1] >= 5: + qhull_options += ' Qx' + + # Fit an exponential to be 2 at 0 and 1 at `maxiter`. + # The decay is used for relaxation. + # analytical solution for y=exp(-maxiter/x) - 0.1 + root = -maxiter / np.log(0.1) + decay = [np.exp(-x / root)+0.9 for x in range(maxiter)] + + l1_old = _l1_norm(sample=sample) + for i in range(maxiter): + sample = _lloyd_iteration( + sample=sample, decay=decay[i], + qhull_options=qhull_options, + ) + + l1_new = _l1_norm(sample=sample) + + if abs(l1_new - l1_old) < tol: + break + else: + l1_old = l1_new + + return sample + + +def _validate_workers(workers: IntNumber = 1) -> IntNumber: + """Validate `workers` based on platform and value. + + Parameters + ---------- + workers : int, optional + Number of workers to use for parallel processing. If -1 is + given all CPU threads are used. Default is 1. + + Returns + ------- + Workers : int + Number of CPU used by the algorithm + + """ + workers = int(workers) + if workers == -1: + workers = os.cpu_count() # type: ignore[assignment] + if workers is None: + raise NotImplementedError( + "Cannot determine the number of cpus using os.cpu_count(), " + "cannot use -1 for the number of workers" + ) + elif workers <= 0: + raise ValueError(f"Invalid number of workers: {workers}, must be -1 " + "or > 0") + + return workers + + +def _validate_bounds( + l_bounds: "npt.ArrayLike", u_bounds: "npt.ArrayLike", d: int +) -> "tuple[npt.NDArray[np.generic], npt.NDArray[np.generic]]": + """Bounds input validation. + + Parameters + ---------- + l_bounds, u_bounds : array_like (d,) + Lower and upper bounds. + d : int + Dimension to use for broadcasting. + + Returns + ------- + l_bounds, u_bounds : array_like (d,) + Lower and upper bounds. + + """ + try: + lower = np.broadcast_to(l_bounds, d) + upper = np.broadcast_to(u_bounds, d) + except ValueError as exc: + msg = ("'l_bounds' and 'u_bounds' must be broadcastable and respect" + " the sample dimension") + raise ValueError(msg) from exc + + if not np.all(lower < upper): + raise ValueError("Bounds are not consistent 'l_bounds' < 'u_bounds'") + + return lower, upper diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmc_cy.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmc_cy.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1006385a43179478a9a4a32ae5f825aa5b8b35c4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmc_cy.pyi @@ -0,0 +1,54 @@ +import numpy as np +from scipy._lib._util import DecimalNumber, IntNumber + + +def _cy_wrapper_centered_discrepancy( + sample: np.ndarray, + iterative: bool, + workers: IntNumber, +) -> float: ... + + +def _cy_wrapper_wrap_around_discrepancy( + sample: np.ndarray, + iterative: bool, + workers: IntNumber, +) -> float: ... + + +def _cy_wrapper_mixture_discrepancy( + sample: np.ndarray, + iterative: bool, + workers: IntNumber, +) -> float: ... + + +def _cy_wrapper_l2_star_discrepancy( + sample: np.ndarray, + iterative: bool, + workers: IntNumber, +) -> float: ... + + +def _cy_wrapper_update_discrepancy( + x_new_view: np.ndarray, + sample_view: np.ndarray, + initial_disc: DecimalNumber, +) -> float: ... + + +def _cy_van_der_corput( + n: IntNumber, + base: IntNumber, + start_index: IntNumber, + workers: IntNumber, +) -> np.ndarray: ... + + +def _cy_van_der_corput_scrambled( + n: IntNumber, + base: IntNumber, + start_index: IntNumber, + permutations: np.ndarray, + workers: IntNumber, +) -> np.ndarray: ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmvnt.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmvnt.py new file mode 100644 index 0000000000000000000000000000000000000000..55da67a3b7220a5d7216188335273c96e8cf06f8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_qmvnt.py @@ -0,0 +1,533 @@ +# Integration of multivariate normal and t distributions. + +# Adapted from the MATLAB original implementations by Dr. Alan Genz. + +# http://www.math.wsu.edu/faculty/genz/software/software.html + +# Copyright (C) 2013, Alan Genz, All rights reserved. +# Python implementation is copyright (C) 2022, Robert Kern, All rights +# reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided the following conditions are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. The contributor name(s) may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import numpy as np + +from scipy.fft import fft, ifft +from scipy.special import gammaincinv, ndtr, ndtri +from scipy.stats._qmc import primes_from_2_to + + +phi = ndtr +phinv = ndtri + + +def _factorize_int(n): + """Return a sorted list of the unique prime factors of a positive integer. + """ + # NOTE: There are lots faster ways to do this, but this isn't terrible. + factors = set() + for p in primes_from_2_to(int(np.sqrt(n)) + 1): + while not (n % p): + factors.add(p) + n //= p + if n == 1: + break + if n != 1: + factors.add(n) + return sorted(factors) + + +def _primitive_root(p): + """Compute a primitive root of the prime number `p`. + + Used in the CBC lattice construction. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Primitive_root_modulo_n + """ + # p is prime + pm = p - 1 + factors = _factorize_int(pm) + n = len(factors) + r = 2 + k = 0 + while k < n: + d = pm // factors[k] + # pow() doesn't like numpy scalar types. + rd = pow(int(r), int(d), int(p)) + if rd == 1: + r += 1 + k = 0 + else: + k += 1 + return r + + +def _cbc_lattice(n_dim, n_qmc_samples): + """Compute a QMC lattice generator using a Fast CBC construction. + + Parameters + ---------- + n_dim : int > 0 + The number of dimensions for the lattice. + n_qmc_samples : int > 0 + The desired number of QMC samples. This will be rounded down to the + nearest prime to enable the CBC construction. + + Returns + ------- + q : float array : shape=(n_dim,) + The lattice generator vector. All values are in the open interval + ``(0, 1)``. + actual_n_qmc_samples : int + The prime number of QMC samples that must be used with this lattice, + no more, no less. + + References + ---------- + .. [1] Nuyens, D. and Cools, R. "Fast Component-by-Component Construction, + a Reprise for Different Kernels", In H. Niederreiter and D. Talay, + editors, Monte-Carlo and Quasi-Monte Carlo Methods 2004, + Springer-Verlag, 2006, 371-385. + """ + # Round down to the nearest prime number. + primes = primes_from_2_to(n_qmc_samples + 1) + n_qmc_samples = primes[-1] + + bt = np.ones(n_dim) + gm = np.hstack([1.0, 0.8 ** np.arange(n_dim - 1)]) + q = 1 + w = 0 + z = np.arange(1, n_dim + 1) + m = (n_qmc_samples - 1) // 2 + g = _primitive_root(n_qmc_samples) + # Slightly faster way to compute perm[j] = pow(g, j, n_qmc_samples) + # Shame that we don't have modulo pow() implemented as a ufunc. + perm = np.ones(m, dtype=int) + for j in range(m - 1): + perm[j + 1] = (g * perm[j]) % n_qmc_samples + perm = np.minimum(n_qmc_samples - perm, perm) + pn = perm / n_qmc_samples + c = pn * pn - pn + 1.0 / 6 + fc = fft(c) + for s in range(1, n_dim): + reordered = np.hstack([ + c[:w+1][::-1], + c[w+1:m][::-1], + ]) + q = q * (bt[s-1] + gm[s-1] * reordered) + w = ifft(fc * fft(q)).real.argmin() + z[s] = perm[w] + q = z / n_qmc_samples + return q, n_qmc_samples + + +# Note: this function is not currently used or tested by any SciPy code. It is +# included in this file to facilitate the development of a parameter for users +# to set the desired CDF accuracy, but must be reviewed and tested before use. +def _qauto(func, covar, low, high, rng, error=1e-3, limit=10_000, **kwds): + """Automatically rerun the integration to get the required error bound. + + Parameters + ---------- + func : callable + Either :func:`_qmvn` or :func:`_qmvt`. + covar, low, high : array + As specified in :func:`_qmvn` and :func:`_qmvt`. + rng : Generator, optional + default_rng(), yada, yada + error : float > 0 + The desired error bound. + limit : int > 0: + The rough limit of the number of integration points to consider. The + integration will stop looping once this limit has been *exceeded*. + **kwds : + Other keyword arguments to pass to `func`. When using :func:`_qmvt`, be + sure to include ``nu=`` as one of these. + + Returns + ------- + prob : float + The estimated probability mass within the bounds. + est_error : float + 3 times the standard error of the batch estimates. + n_samples : int + The number of integration points actually used. + """ + n = len(covar) + n_samples = 0 + if n == 1: + prob = phi(high) - phi(low) + # More or less + est_error = 1e-15 + else: + mi = min(limit, n * 1000) + prob = 0.0 + est_error = 1.0 + ei = 0.0 + while est_error > error and n_samples < limit: + mi = round(np.sqrt(2) * mi) + pi, ei, ni = func(mi, covar, low, high, rng=rng, **kwds) + n_samples += ni + wt = 1.0 / (1 + (ei / est_error)**2) + prob += wt * (pi - prob) + est_error = np.sqrt(wt) * ei + return prob, est_error, n_samples + + +# Note: this function is not currently used or tested by any SciPy code. It is +# included in this file to facilitate the resolution of gh-8367, gh-16142, and +# possibly gh-14286, but must be reviewed and tested before use. +def _qmvn(m, covar, low, high, rng, lattice='cbc', n_batches=10): + """Multivariate normal integration over box bounds. + + Parameters + ---------- + m : int > n_batches + The number of points to sample. This number will be divided into + `n_batches` batches that apply random offsets of the sampling lattice + for each batch in order to estimate the error. + covar : (n, n) float array + Possibly singular, positive semidefinite symmetric covariance matrix. + low, high : (n,) float array + The low and high integration bounds. + rng : Generator, optional + default_rng(), yada, yada + lattice : 'cbc' or callable + The type of lattice rule to use to construct the integration points. + n_batches : int > 0, optional + The number of QMC batches to apply. + + Returns + ------- + prob : float + The estimated probability mass within the bounds. + est_error : float + 3 times the standard error of the batch estimates. + """ + cho, lo, hi = _permuted_cholesky(covar, low, high) + n = cho.shape[0] + ct = cho[0, 0] + c = phi(lo[0] / ct) + d = phi(hi[0] / ct) + ci = c + dci = d - ci + prob = 0.0 + error_var = 0.0 + q, n_qmc_samples = _cbc_lattice(n - 1, max(m // n_batches, 1)) + y = np.zeros((n - 1, n_qmc_samples)) + i_samples = np.arange(n_qmc_samples) + 1 + for j in range(n_batches): + c = np.full(n_qmc_samples, ci) + dc = np.full(n_qmc_samples, dci) + pv = dc.copy() + for i in range(1, n): + # Pseudorandomly-shifted lattice coordinate. + z = q[i - 1] * i_samples + rng.random() + # Fast remainder(z, 1.0) + z -= z.astype(int) + # Tent periodization transform. + x = abs(2 * z - 1) + y[i - 1, :] = phinv(c + x * dc) + s = cho[i, :i] @ y[:i, :] + ct = cho[i, i] + c = phi((lo[i] - s) / ct) + d = phi((hi[i] - s) / ct) + dc = d - c + pv = pv * dc + # Accumulate the mean and error variances with online formulations. + d = (pv.mean() - prob) / (j + 1) + prob += d + error_var = (j - 1) * error_var / (j + 1) + d * d + # Error bounds are 3 times the standard error of the estimates. + est_error = 3 * np.sqrt(error_var) + n_samples = n_qmc_samples * n_batches + return prob, est_error, n_samples + + +# Note: this function is not currently used or tested by any SciPy code. It is +# included in this file to facilitate the resolution of gh-8367, gh-16142, and +# possibly gh-14286, but must be reviewed and tested before use. +def _mvn_qmc_integrand(covar, low, high, use_tent=False): + """Transform the multivariate normal integration into a QMC integrand over + a unit hypercube. + + The dimensionality of the resulting hypercube integration domain is one + less than the dimensionality of the original integrand. Note that this + transformation subsumes the integration bounds in order to account for + infinite bounds. The QMC integration one does with the returned integrand + should be on the unit hypercube. + + Parameters + ---------- + covar : (n, n) float array + Possibly singular, positive semidefinite symmetric covariance matrix. + low, high : (n,) float array + The low and high integration bounds. + use_tent : bool, optional + If True, then use tent periodization. Only helpful for lattice rules. + + Returns + ------- + integrand : Callable[[NDArray], NDArray] + The QMC-integrable integrand. It takes an + ``(n_qmc_samples, ndim_integrand)`` array of QMC samples in the unit + hypercube and returns the ``(n_qmc_samples,)`` evaluations of at these + QMC points. + ndim_integrand : int + The dimensionality of the integrand. Equal to ``n-1``. + """ + cho, lo, hi = _permuted_cholesky(covar, low, high) + n = cho.shape[0] + ndim_integrand = n - 1 + ct = cho[0, 0] + c = phi(lo[0] / ct) + d = phi(hi[0] / ct) + ci = c + dci = d - ci + + def integrand(*zs): + ndim_qmc = len(zs) + n_qmc_samples = len(np.atleast_1d(zs[0])) + assert ndim_qmc == ndim_integrand + y = np.zeros((ndim_qmc, n_qmc_samples)) + c = np.full(n_qmc_samples, ci) + dc = np.full(n_qmc_samples, dci) + pv = dc.copy() + for i in range(1, n): + if use_tent: + # Tent periodization transform. + x = abs(2 * zs[i-1] - 1) + else: + x = zs[i-1] + y[i - 1, :] = phinv(c + x * dc) + s = cho[i, :i] @ y[:i, :] + ct = cho[i, i] + c = phi((lo[i] - s) / ct) + d = phi((hi[i] - s) / ct) + dc = d - c + pv = pv * dc + return pv + + return integrand, ndim_integrand + + +def _qmvt(m, nu, covar, low, high, rng, lattice='cbc', n_batches=10): + """Multivariate t integration over box bounds. + + Parameters + ---------- + m : int > n_batches + The number of points to sample. This number will be divided into + `n_batches` batches that apply random offsets of the sampling lattice + for each batch in order to estimate the error. + nu : float >= 0 + The shape parameter of the multivariate t distribution. + covar : (n, n) float array + Possibly singular, positive semidefinite symmetric covariance matrix. + low, high : (n,) float array + The low and high integration bounds. + rng : Generator, optional + default_rng(), yada, yada + lattice : 'cbc' or callable + The type of lattice rule to use to construct the integration points. + n_batches : int > 0, optional + The number of QMC batches to apply. + + Returns + ------- + prob : float + The estimated probability mass within the bounds. + est_error : float + 3 times the standard error of the batch estimates. + n_samples : int + The number of samples actually used. + """ + sn = max(1.0, np.sqrt(nu)) + low = np.asarray(low, dtype=np.float64) + high = np.asarray(high, dtype=np.float64) + cho, lo, hi = _permuted_cholesky(covar, low / sn, high / sn) + n = cho.shape[0] + prob = 0.0 + error_var = 0.0 + q, n_qmc_samples = _cbc_lattice(n, max(m // n_batches, 1)) + i_samples = np.arange(n_qmc_samples) + 1 + for j in range(n_batches): + pv = np.ones(n_qmc_samples) + s = np.zeros((n, n_qmc_samples)) + for i in range(n): + # Pseudorandomly-shifted lattice coordinate. + z = q[i] * i_samples + rng.random() + # Fast remainder(z, 1.0) + z -= z.astype(int) + # Tent periodization transform. + x = abs(2 * z - 1) + # FIXME: Lift the i==0 case out of the loop to make the logic + # easier to follow. + if i == 0: + # We'll use one of the QR variates to pull out the + # t-distribution scaling. + if nu > 0: + r = np.sqrt(2 * gammaincinv(nu / 2, x)) + else: + r = np.ones_like(x) + else: + y = phinv(c + x * dc) # noqa: F821 + with np.errstate(invalid='ignore'): + s[i:, :] += cho[i:, i - 1][:, np.newaxis] * y + si = s[i, :] + + c = np.ones(n_qmc_samples) + d = np.ones(n_qmc_samples) + with np.errstate(invalid='ignore'): + lois = lo[i] * r - si + hiis = hi[i] * r - si + c[lois < -9] = 0.0 + d[hiis < -9] = 0.0 + lo_mask = abs(lois) < 9 + hi_mask = abs(hiis) < 9 + c[lo_mask] = phi(lois[lo_mask]) + d[hi_mask] = phi(hiis[hi_mask]) + + dc = d - c + pv *= dc + + # Accumulate the mean and error variances with online formulations. + d = (pv.mean() - prob) / (j + 1) + prob += d + error_var = (j - 1) * error_var / (j + 1) + d * d + # Error bounds are 3 times the standard error of the estimates. + est_error = 3 * np.sqrt(error_var) + n_samples = n_qmc_samples * n_batches + return prob, est_error, n_samples + + +def _permuted_cholesky(covar, low, high, tol=1e-10): + """Compute a scaled, permuted Cholesky factor, with integration bounds. + + The scaling and permuting of the dimensions accomplishes part of the + transformation of the original integration problem into a more numerically + tractable form. The lower-triangular Cholesky factor will then be used in + the subsequent integration. The integration bounds will be scaled and + permuted as well. + + Parameters + ---------- + covar : (n, n) float array + Possibly singular, positive semidefinite symmetric covariance matrix. + low, high : (n,) float array + The low and high integration bounds. + tol : float, optional + The singularity tolerance. + + Returns + ------- + cho : (n, n) float array + Lower Cholesky factor, scaled and permuted. + new_low, new_high : (n,) float array + The scaled and permuted low and high integration bounds. + """ + # Make copies for outputting. + cho = np.array(covar, dtype=np.float64) + new_lo = np.array(low, dtype=np.float64) + new_hi = np.array(high, dtype=np.float64) + n = cho.shape[0] + if cho.shape != (n, n): + raise ValueError("expected a square symmetric array") + if new_lo.shape != (n,) or new_hi.shape != (n,): + raise ValueError( + "expected integration boundaries the same dimensions " + "as the covariance matrix" + ) + # Scale by the sqrt of the diagonal. + dc = np.sqrt(np.maximum(np.diag(cho), 0.0)) + # But don't divide by 0. + dc[dc == 0.0] = 1.0 + new_lo /= dc + new_hi /= dc + cho /= dc + cho /= dc[:, np.newaxis] + + y = np.zeros(n) + sqtp = np.sqrt(2 * np.pi) + for k in range(n): + epk = (k + 1) * tol + im = k + ck = 0.0 + dem = 1.0 + s = 0.0 + lo_m = 0.0 + hi_m = 0.0 + for i in range(k, n): + if cho[i, i] > tol: + ci = np.sqrt(cho[i, i]) + if i > 0: + s = cho[i, :k] @ y[:k] + lo_i = (new_lo[i] - s) / ci + hi_i = (new_hi[i] - s) / ci + de = phi(hi_i) - phi(lo_i) + if de <= dem: + ck = ci + dem = de + lo_m = lo_i + hi_m = hi_i + im = i + if im > k: + # Swap im and k + cho[im, im] = cho[k, k] + _swap_slices(cho, np.s_[im, :k], np.s_[k, :k]) + _swap_slices(cho, np.s_[im + 1:, im], np.s_[im + 1:, k]) + _swap_slices(cho, np.s_[k + 1:im, k], np.s_[im, k + 1:im]) + _swap_slices(new_lo, k, im) + _swap_slices(new_hi, k, im) + if ck > epk: + cho[k, k] = ck + cho[k, k + 1:] = 0.0 + for i in range(k + 1, n): + cho[i, k] /= ck + cho[i, k + 1:i + 1] -= cho[i, k] * cho[k + 1:i + 1, k] + if abs(dem) > tol: + y[k] = ((np.exp(-lo_m * lo_m / 2) - np.exp(-hi_m * hi_m / 2)) / + (sqtp * dem)) + else: + y[k] = (lo_m + hi_m) / 2 + if lo_m < -10: + y[k] = hi_m + elif hi_m > 10: + y[k] = lo_m + cho[k, :k + 1] /= ck + new_lo[k] /= ck + new_hi[k] /= ck + else: + cho[k:, k] = 0.0 + y[k] = (new_lo[k] + new_hi[k]) / 2 + return cho, new_lo, new_hi + + +def _swap_slices(x, slc1, slc2): + t = x[slc1].copy() + x[slc1] = x[slc2].copy() + x[slc2] = t diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25728ead5f7ea277e6e94c359d5a5603b99eeb38 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py @@ -0,0 +1,4 @@ +# +from .rcont import rvs_rcont1, rvs_rcont2 + +__all__ = ["rvs_rcont1", "rvs_rcont2"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1ed9164010c4f2ec6974bf2e1002dbc16bcab49 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_relative_risk.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_relative_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..51525fd28adb37c72b12106450e4178c786091b2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_relative_risk.py @@ -0,0 +1,263 @@ +import operator +from dataclasses import dataclass +import numpy as np +from scipy.special import ndtri +from ._common import ConfidenceInterval + + +def _validate_int(n, bound, name): + msg = f'{name} must be an integer not less than {bound}, but got {n!r}' + try: + n = operator.index(n) + except TypeError: + raise TypeError(msg) from None + if n < bound: + raise ValueError(msg) + return n + + +@dataclass +class RelativeRiskResult: + """ + Result of `scipy.stats.contingency.relative_risk`. + + Attributes + ---------- + relative_risk : float + This is:: + + (exposed_cases/exposed_total) / (control_cases/control_total) + + exposed_cases : int + The number of "cases" (i.e. occurrence of disease or other event + of interest) among the sample of "exposed" individuals. + exposed_total : int + The total number of "exposed" individuals in the sample. + control_cases : int + The number of "cases" among the sample of "control" or non-exposed + individuals. + control_total : int + The total number of "control" individuals in the sample. + + Methods + ------- + confidence_interval : + Compute the confidence interval for the relative risk estimate. + """ + + relative_risk: float + exposed_cases: int + exposed_total: int + control_cases: int + control_total: int + + def confidence_interval(self, confidence_level=0.95): + """ + Compute the confidence interval for the relative risk. + + The confidence interval is computed using the Katz method + (i.e. "Method C" of [1]_; see also [2]_, section 3.1.2). + + Parameters + ---------- + confidence_level : float, optional + The confidence level to use for the confidence interval. + Default is 0.95. + + Returns + ------- + ci : ConfidenceInterval instance + The return value is an object with attributes ``low`` and + ``high`` that hold the confidence interval. + + References + ---------- + .. [1] D. Katz, J. Baptista, S. P. Azen and M. C. Pike, "Obtaining + confidence intervals for the risk ratio in cohort studies", + Biometrics, 34, 469-474 (1978). + .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology, + CRC Press LLC, Boca Raton, FL, USA (1996). + + + Examples + -------- + >>> from scipy.stats.contingency import relative_risk + >>> result = relative_risk(exposed_cases=10, exposed_total=75, + ... control_cases=12, control_total=225) + >>> result.relative_risk + 2.5 + >>> result.confidence_interval() + ConfidenceInterval(low=1.1261564003469628, high=5.549850800541033) + """ + if not 0 <= confidence_level <= 1: + raise ValueError('confidence_level must be in the interval ' + '[0, 1].') + + # Handle edge cases where either exposed_cases or control_cases + # is zero. We follow the convention of the R function riskratio + # from the epitools library. + if self.exposed_cases == 0 and self.control_cases == 0: + # relative risk is nan. + return ConfidenceInterval(low=np.nan, high=np.nan) + elif self.exposed_cases == 0: + # relative risk is 0. + return ConfidenceInterval(low=0.0, high=np.nan) + elif self.control_cases == 0: + # relative risk is inf + return ConfidenceInterval(low=np.nan, high=np.inf) + + alpha = 1 - confidence_level + z = ndtri(1 - alpha/2) + rr = self.relative_risk + + # Estimate of the variance of log(rr) is + # var(log(rr)) = 1/exposed_cases - 1/exposed_total + + # 1/control_cases - 1/control_total + # and the standard error is the square root of that. + se = np.sqrt(1/self.exposed_cases - 1/self.exposed_total + + 1/self.control_cases - 1/self.control_total) + delta = z*se + katz_lo = rr*np.exp(-delta) + katz_hi = rr*np.exp(delta) + return ConfidenceInterval(low=katz_lo, high=katz_hi) + + +def relative_risk(exposed_cases, exposed_total, control_cases, control_total): + """ + Compute the relative risk (also known as the risk ratio). + + This function computes the relative risk associated with a 2x2 + contingency table ([1]_, section 2.2.3; [2]_, section 3.1.2). Instead + of accepting a table as an argument, the individual numbers that are + used to compute the relative risk are given as separate parameters. + This is to avoid the ambiguity of which row or column of the contingency + table corresponds to the "exposed" cases and which corresponds to the + "control" cases. Unlike, say, the odds ratio, the relative risk is not + invariant under an interchange of the rows or columns. + + Parameters + ---------- + exposed_cases : nonnegative int + The number of "cases" (i.e. occurrence of disease or other event + of interest) among the sample of "exposed" individuals. + exposed_total : positive int + The total number of "exposed" individuals in the sample. + control_cases : nonnegative int + The number of "cases" among the sample of "control" or non-exposed + individuals. + control_total : positive int + The total number of "control" individuals in the sample. + + Returns + ------- + result : instance of `~scipy.stats._result_classes.RelativeRiskResult` + The object has the float attribute ``relative_risk``, which is:: + + rr = (exposed_cases/exposed_total) / (control_cases/control_total) + + The object also has the method ``confidence_interval`` to compute + the confidence interval of the relative risk for a given confidence + level. + + See Also + -------- + odds_ratio + + Notes + ----- + The R package epitools has the function `riskratio`, which accepts + a table with the following layout:: + + disease=0 disease=1 + exposed=0 (ref) n00 n01 + exposed=1 n10 n11 + + With a 2x2 table in the above format, the estimate of the CI is + computed by `riskratio` when the argument method="wald" is given, + or with the function `riskratio.wald`. + + For example, in a test of the incidence of lung cancer among a + sample of smokers and nonsmokers, the "exposed" category would + correspond to "is a smoker" and the "disease" category would + correspond to "has or had lung cancer". + + To pass the same data to ``relative_risk``, use:: + + relative_risk(n11, n10 + n11, n01, n00 + n01) + + .. versionadded:: 1.7.0 + + References + ---------- + .. [1] Alan Agresti, An Introduction to Categorical Data Analysis + (second edition), Wiley, Hoboken, NJ, USA (2007). + .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology, + CRC Press LLC, Boca Raton, FL, USA (1996). + + Examples + -------- + >>> from scipy.stats.contingency import relative_risk + + This example is from Example 3.1 of [2]_. The results of a heart + disease study are summarized in the following table:: + + High CAT Low CAT Total + -------- ------- ----- + CHD 27 44 71 + No CHD 95 443 538 + + Total 122 487 609 + + CHD is coronary heart disease, and CAT refers to the level of + circulating catecholamine. CAT is the "exposure" variable, and + high CAT is the "exposed" category. So the data from the table + to be passed to ``relative_risk`` is:: + + exposed_cases = 27 + exposed_total = 122 + control_cases = 44 + control_total = 487 + + >>> result = relative_risk(27, 122, 44, 487) + >>> result.relative_risk + 2.4495156482861398 + + Find the confidence interval for the relative risk. + + >>> result.confidence_interval(confidence_level=0.95) + ConfidenceInterval(low=1.5836990926700116, high=3.7886786315466354) + + The interval does not contain 1, so the data supports the statement + that high CAT is associated with greater risk of CHD. + """ + # Relative risk is a trivial calculation. The nontrivial part is in the + # `confidence_interval` method of the RelativeRiskResult class. + + exposed_cases = _validate_int(exposed_cases, 0, "exposed_cases") + exposed_total = _validate_int(exposed_total, 1, "exposed_total") + control_cases = _validate_int(control_cases, 0, "control_cases") + control_total = _validate_int(control_total, 1, "control_total") + + if exposed_cases > exposed_total: + raise ValueError('exposed_cases must not exceed exposed_total.') + if control_cases > control_total: + raise ValueError('control_cases must not exceed control_total.') + + if exposed_cases == 0 and control_cases == 0: + # relative risk is 0/0. + rr = np.nan + elif exposed_cases == 0: + # relative risk is 0/nonzero + rr = 0.0 + elif control_cases == 0: + # relative risk is nonzero/0. + rr = np.inf + else: + p1 = exposed_cases / exposed_total + p2 = control_cases / control_total + rr = p1 / p2 + return RelativeRiskResult(relative_risk=rr, + exposed_cases=exposed_cases, + exposed_total=exposed_total, + control_cases=control_cases, + control_total=control_total) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_resampling.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_resampling.py new file mode 100644 index 0000000000000000000000000000000000000000..4314ee353a22606b445288ea0182528777e627a2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_resampling.py @@ -0,0 +1,2377 @@ +import warnings +import numpy as np +from itertools import combinations, permutations, product +from collections.abc import Sequence +from dataclasses import dataclass, field +import inspect + +from scipy._lib._util import (check_random_state, _rename_parameter, rng_integers, + _transition_to_rng) +from scipy._lib._array_api import array_namespace, is_numpy, xp_moveaxis_to_end +from scipy.special import ndtr, ndtri, comb, factorial + +from ._common import ConfidenceInterval +from ._axis_nan_policy import _broadcast_concatenate, _broadcast_arrays +from ._warnings_errors import DegenerateDataWarning + +__all__ = ['bootstrap', 'monte_carlo_test', 'permutation_test'] + + +def _vectorize_statistic(statistic): + """Vectorize an n-sample statistic""" + # This is a little cleaner than np.nditer at the expense of some data + # copying: concatenate samples together, then use np.apply_along_axis + def stat_nd(*data, axis=0): + lengths = [sample.shape[axis] for sample in data] + split_indices = np.cumsum(lengths)[:-1] + z = _broadcast_concatenate(data, axis) + + # move working axis to position 0 so that new dimensions in the output + # of `statistic` are _prepended_. ("This axis is removed, and replaced + # with new dimensions...") + z = np.moveaxis(z, axis, 0) + + def stat_1d(z): + data = np.split(z, split_indices) + return statistic(*data) + + return np.apply_along_axis(stat_1d, 0, z)[()] + return stat_nd + + +def _jackknife_resample(sample, batch=None): + """Jackknife resample the sample. Only one-sample stats for now.""" + n = sample.shape[-1] + batch_nominal = batch or n + + for k in range(0, n, batch_nominal): + # col_start:col_end are the observations to remove + batch_actual = min(batch_nominal, n-k) + + # jackknife - each row leaves out one observation + j = np.ones((batch_actual, n), dtype=bool) + np.fill_diagonal(j[:, k:k+batch_actual], False) + i = np.arange(n) + i = np.broadcast_to(i, (batch_actual, n)) + i = i[j].reshape((batch_actual, n-1)) + + resamples = sample[..., i] + yield resamples + + +def _bootstrap_resample(sample, n_resamples=None, rng=None): + """Bootstrap resample the sample.""" + n = sample.shape[-1] + + # bootstrap - each row is a random resample of original observations + i = rng_integers(rng, 0, n, (n_resamples, n)) + + resamples = sample[..., i] + return resamples + + +def _percentile_of_score(a, score, axis): + """Vectorized, simplified `scipy.stats.percentileofscore`. + Uses logic of the 'mean' value of percentileofscore's kind parameter. + + Unlike `stats.percentileofscore`, the percentile returned is a fraction + in [0, 1]. + """ + B = a.shape[axis] + return ((a < score).sum(axis=axis) + (a <= score).sum(axis=axis)) / (2 * B) + + +def _percentile_along_axis(theta_hat_b, alpha): + """`np.percentile` with different percentile for each slice.""" + # the difference between _percentile_along_axis and np.percentile is that + # np.percentile gets _all_ the qs for each axis slice, whereas + # _percentile_along_axis gets the q corresponding with each axis slice + shape = theta_hat_b.shape[:-1] + alpha = np.broadcast_to(alpha, shape) + percentiles = np.zeros_like(alpha, dtype=np.float64) + for indices, alpha_i in np.ndenumerate(alpha): + if np.isnan(alpha_i): + # e.g. when bootstrap distribution has only one unique element + msg = ( + "The BCa confidence interval cannot be calculated." + " This problem is known to occur when the distribution" + " is degenerate or the statistic is np.min." + ) + warnings.warn(DegenerateDataWarning(msg), stacklevel=3) + percentiles[indices] = np.nan + else: + theta_hat_b_i = theta_hat_b[indices] + percentiles[indices] = np.percentile(theta_hat_b_i, alpha_i) + return percentiles[()] # return scalar instead of 0d array + + +def _bca_interval(data, statistic, axis, alpha, theta_hat_b, batch): + """Bias-corrected and accelerated interval.""" + # closely follows [1] 14.3 and 15.4 (Eq. 15.36) + + # calculate z0_hat + theta_hat = np.asarray(statistic(*data, axis=axis))[..., None] + percentile = _percentile_of_score(theta_hat_b, theta_hat, axis=-1) + z0_hat = ndtri(percentile) + + # calculate a_hat + theta_hat_ji = [] # j is for sample of data, i is for jackknife resample + for j, sample in enumerate(data): + # _jackknife_resample will add an axis prior to the last axis that + # corresponds with the different jackknife resamples. Do the same for + # each sample of the data to ensure broadcastability. We need to + # create a copy of the list containing the samples anyway, so do this + # in the loop to simplify the code. This is not the bottleneck... + samples = [np.expand_dims(sample, -2) for sample in data] + theta_hat_i = [] + for jackknife_sample in _jackknife_resample(sample, batch): + samples[j] = jackknife_sample + broadcasted = _broadcast_arrays(samples, axis=-1) + theta_hat_i.append(statistic(*broadcasted, axis=-1)) + theta_hat_ji.append(theta_hat_i) + + theta_hat_ji = [np.concatenate(theta_hat_i, axis=-1) + for theta_hat_i in theta_hat_ji] + + n_j = [theta_hat_i.shape[-1] for theta_hat_i in theta_hat_ji] + + theta_hat_j_dot = [theta_hat_i.mean(axis=-1, keepdims=True) + for theta_hat_i in theta_hat_ji] + + U_ji = [(n - 1) * (theta_hat_dot - theta_hat_i) + for theta_hat_dot, theta_hat_i, n + in zip(theta_hat_j_dot, theta_hat_ji, n_j)] + + nums = [(U_i**3).sum(axis=-1)/n**3 for U_i, n in zip(U_ji, n_j)] + dens = [(U_i**2).sum(axis=-1)/n**2 for U_i, n in zip(U_ji, n_j)] + a_hat = 1/6 * sum(nums) / sum(dens)**(3/2) + + # calculate alpha_1, alpha_2 + z_alpha = ndtri(alpha) + z_1alpha = -z_alpha + num1 = z0_hat + z_alpha + alpha_1 = ndtr(z0_hat + num1/(1 - a_hat*num1)) + num2 = z0_hat + z_1alpha + alpha_2 = ndtr(z0_hat + num2/(1 - a_hat*num2)) + return alpha_1, alpha_2, a_hat # return a_hat for testing + + +def _bootstrap_iv(data, statistic, vectorized, paired, axis, confidence_level, + alternative, n_resamples, batch, method, bootstrap_result, + rng): + """Input validation and standardization for `bootstrap`.""" + + if vectorized not in {True, False, None}: + raise ValueError("`vectorized` must be `True`, `False`, or `None`.") + + if vectorized is None: + vectorized = 'axis' in inspect.signature(statistic).parameters + + if not vectorized: + statistic = _vectorize_statistic(statistic) + + axis_int = int(axis) + if axis != axis_int: + raise ValueError("`axis` must be an integer.") + + n_samples = 0 + try: + n_samples = len(data) + except TypeError: + raise ValueError("`data` must be a sequence of samples.") + + if n_samples == 0: + raise ValueError("`data` must contain at least one sample.") + + message = ("Ignoring the dimension specified by `axis`, arrays in `data` do not " + "have the same shape. Beginning in SciPy 1.16.0, `bootstrap` will " + "explicitly broadcast elements of `data` to the same shape (ignoring " + "`axis`) before performing the calculation. To avoid this warning in " + "the meantime, ensure that all samples have the same shape (except " + "potentially along `axis`).") + data = [np.atleast_1d(sample) for sample in data] + reduced_shapes = set() + for sample in data: + reduced_shape = list(sample.shape) + reduced_shape.pop(axis) + reduced_shapes.add(tuple(reduced_shape)) + if len(reduced_shapes) != 1: + warnings.warn(message, FutureWarning, stacklevel=3) + + data_iv = [] + for sample in data: + if sample.shape[axis_int] <= 1: + raise ValueError("each sample in `data` must contain two or more " + "observations along `axis`.") + sample = np.moveaxis(sample, axis_int, -1) + data_iv.append(sample) + + if paired not in {True, False}: + raise ValueError("`paired` must be `True` or `False`.") + + if paired: + n = data_iv[0].shape[-1] + for sample in data_iv[1:]: + if sample.shape[-1] != n: + message = ("When `paired is True`, all samples must have the " + "same length along `axis`") + raise ValueError(message) + + # to generate the bootstrap distribution for paired-sample statistics, + # resample the indices of the observations + def statistic(i, axis=-1, data=data_iv, unpaired_statistic=statistic): + data = [sample[..., i] for sample in data] + return unpaired_statistic(*data, axis=axis) + + data_iv = [np.arange(n)] + + confidence_level_float = float(confidence_level) + + alternative = alternative.lower() + alternatives = {'two-sided', 'less', 'greater'} + if alternative not in alternatives: + raise ValueError(f"`alternative` must be one of {alternatives}") + + n_resamples_int = int(n_resamples) + if n_resamples != n_resamples_int or n_resamples_int < 0: + raise ValueError("`n_resamples` must be a non-negative integer.") + + if batch is None: + batch_iv = batch + else: + batch_iv = int(batch) + if batch != batch_iv or batch_iv <= 0: + raise ValueError("`batch` must be a positive integer or None.") + + methods = {'percentile', 'basic', 'bca'} + method = method.lower() + if method not in methods: + raise ValueError(f"`method` must be in {methods}") + + message = "`bootstrap_result` must have attribute `bootstrap_distribution'" + if (bootstrap_result is not None + and not hasattr(bootstrap_result, "bootstrap_distribution")): + raise ValueError(message) + + message = ("Either `bootstrap_result.bootstrap_distribution.size` or " + "`n_resamples` must be positive.") + if ((not bootstrap_result or + not bootstrap_result.bootstrap_distribution.size) + and n_resamples_int == 0): + raise ValueError(message) + + rng = check_random_state(rng) + + return (data_iv, statistic, vectorized, paired, axis_int, + confidence_level_float, alternative, n_resamples_int, batch_iv, + method, bootstrap_result, rng) + + +@dataclass +class BootstrapResult: + """Result object returned by `scipy.stats.bootstrap`. + + Attributes + ---------- + confidence_interval : ConfidenceInterval + The bootstrap confidence interval as an instance of + `collections.namedtuple` with attributes `low` and `high`. + bootstrap_distribution : ndarray + The bootstrap distribution, that is, the value of `statistic` for + each resample. The last dimension corresponds with the resamples + (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``). + standard_error : float or ndarray + The bootstrap standard error, that is, the sample standard + deviation of the bootstrap distribution. + + """ + confidence_interval: ConfidenceInterval + bootstrap_distribution: np.ndarray + standard_error: float | np.ndarray + + +@_transition_to_rng('random_state') +def bootstrap(data, statistic, *, n_resamples=9999, batch=None, + vectorized=None, paired=False, axis=0, confidence_level=0.95, + alternative='two-sided', method='BCa', bootstrap_result=None, + rng=None): + r""" + Compute a two-sided bootstrap confidence interval of a statistic. + + When `method` is ``'percentile'`` and `alternative` is ``'two-sided'``, + a bootstrap confidence interval is computed according to the following + procedure. + + 1. Resample the data: for each sample in `data` and for each of + `n_resamples`, take a random sample of the original sample + (with replacement) of the same size as the original sample. + + 2. Compute the bootstrap distribution of the statistic: for each set of + resamples, compute the test statistic. + + 3. Determine the confidence interval: find the interval of the bootstrap + distribution that is + + - symmetric about the median and + - contains `confidence_level` of the resampled statistic values. + + While the ``'percentile'`` method is the most intuitive, it is rarely + used in practice. Two more common methods are available, ``'basic'`` + ('reverse percentile') and ``'BCa'`` ('bias-corrected and accelerated'); + they differ in how step 3 is performed. + + If the samples in `data` are taken at random from their respective + distributions :math:`n` times, the confidence interval returned by + `bootstrap` will contain the true value of the statistic for those + distributions approximately `confidence_level`:math:`\, \times \, n` times. + + Parameters + ---------- + data : sequence of array-like + Each element of `data` is a sample containing scalar observations from an + underlying distribution. Elements of `data` must be broadcastable to the + same shape (with the possible exception of the dimension specified by `axis`). + + .. versionchanged:: 1.14.0 + `bootstrap` will now emit a ``FutureWarning`` if the shapes of the + elements of `data` are not the same (with the exception of the dimension + specified by `axis`). + Beginning in SciPy 1.16.0, `bootstrap` will explicitly broadcast the + elements to the same shape (except along `axis`) before performing + the calculation. + + statistic : callable + Statistic for which the confidence interval is to be calculated. + `statistic` must be a callable that accepts ``len(data)`` samples + as separate arguments and returns the resulting statistic. + If `vectorized` is set ``True``, + `statistic` must also accept a keyword argument `axis` and be + vectorized to compute the statistic along the provided `axis`. + n_resamples : int, default: ``9999`` + The number of resamples performed to form the bootstrap distribution + of the statistic. + batch : int, optional + The number of resamples to process in each vectorized call to + `statistic`. Memory usage is O( `batch` * ``n`` ), where ``n`` is the + sample size. Default is ``None``, in which case ``batch = n_resamples`` + (or ``batch = max(n_resamples, n)`` for ``method='BCa'``). + vectorized : bool, optional + If `vectorized` is set ``False``, `statistic` will not be passed + keyword argument `axis` and is expected to calculate the statistic + only for 1D samples. If ``True``, `statistic` will be passed keyword + argument `axis` and is expected to calculate the statistic along `axis` + when passed an ND sample array. If ``None`` (default), `vectorized` + will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of + a vectorized statistic typically reduces computation time. + paired : bool, default: ``False`` + Whether the statistic treats corresponding elements of the samples + in `data` as paired. If True, `bootstrap` resamples an array of + *indices* and uses the same indices for all arrays in `data`; otherwise, + `bootstrap` independently resamples the elements of each array. + axis : int, default: ``0`` + The axis of the samples in `data` along which the `statistic` is + calculated. + confidence_level : float, default: ``0.95`` + The confidence level of the confidence interval. + alternative : {'two-sided', 'less', 'greater'}, default: ``'two-sided'`` + Choose ``'two-sided'`` (default) for a two-sided confidence interval, + ``'less'`` for a one-sided confidence interval with the lower bound + at ``-np.inf``, and ``'greater'`` for a one-sided confidence interval + with the upper bound at ``np.inf``. The other bound of the one-sided + confidence intervals is the same as that of a two-sided confidence + interval with `confidence_level` twice as far from 1.0; e.g. the upper + bound of a 95% ``'less'`` confidence interval is the same as the upper + bound of a 90% ``'two-sided'`` confidence interval. + method : {'percentile', 'basic', 'bca'}, default: ``'BCa'`` + Whether to return the 'percentile' bootstrap confidence interval + (``'percentile'``), the 'basic' (AKA 'reverse') bootstrap confidence + interval (``'basic'``), or the bias-corrected and accelerated bootstrap + confidence interval (``'BCa'``). + bootstrap_result : BootstrapResult, optional + Provide the result object returned by a previous call to `bootstrap` + to include the previous bootstrap distribution in the new bootstrap + distribution. This can be used, for example, to change + `confidence_level`, change `method`, or see the effect of performing + additional resampling without repeating computations. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + res : BootstrapResult + An object with attributes: + + confidence_interval : ConfidenceInterval + The bootstrap confidence interval as an instance of + `collections.namedtuple` with attributes `low` and `high`. + bootstrap_distribution : ndarray + The bootstrap distribution, that is, the value of `statistic` for + each resample. The last dimension corresponds with the resamples + (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``). + standard_error : float or ndarray + The bootstrap standard error, that is, the sample standard + deviation of the bootstrap distribution. + + Warns + ----- + `~scipy.stats.DegenerateDataWarning` + Generated when ``method='BCa'`` and the bootstrap distribution is + degenerate (e.g. all elements are identical). + + Notes + ----- + Elements of the confidence interval may be NaN for ``method='BCa'`` if + the bootstrap distribution is degenerate (e.g. all elements are identical). + In this case, consider using another `method` or inspecting `data` for + indications that other analysis may be more appropriate (e.g. all + observations are identical). + + References + ---------- + .. [1] B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap, + Chapman & Hall/CRC, Boca Raton, FL, USA (1993) + .. [2] Nathaniel E. Helwig, "Bootstrap Confidence Intervals", + http://users.stat.umn.edu/~helwig/notes/bootci-Notes.pdf + .. [3] Bootstrapping (statistics), Wikipedia, + https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29 + + Examples + -------- + Suppose we have sampled data from an unknown distribution. + + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> from scipy.stats import norm + >>> dist = norm(loc=2, scale=4) # our "unknown" distribution + >>> data = dist.rvs(size=100, random_state=rng) + + We are interested in the standard deviation of the distribution. + + >>> std_true = dist.std() # the true value of the statistic + >>> print(std_true) + 4.0 + >>> std_sample = np.std(data) # the sample statistic + >>> print(std_sample) + 3.9460644295563863 + + The bootstrap is used to approximate the variability we would expect if we + were to repeatedly sample from the unknown distribution and calculate the + statistic of the sample each time. It does this by repeatedly resampling + values *from the original sample* with replacement and calculating the + statistic of each resample. This results in a "bootstrap distribution" of + the statistic. + + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import bootstrap + >>> data = (data,) # samples must be in a sequence + >>> res = bootstrap(data, np.std, confidence_level=0.9, rng=rng) + >>> fig, ax = plt.subplots() + >>> ax.hist(res.bootstrap_distribution, bins=25) + >>> ax.set_title('Bootstrap Distribution') + >>> ax.set_xlabel('statistic value') + >>> ax.set_ylabel('frequency') + >>> plt.show() + + The standard error quantifies this variability. It is calculated as the + standard deviation of the bootstrap distribution. + + >>> res.standard_error + 0.24427002125829136 + >>> res.standard_error == np.std(res.bootstrap_distribution, ddof=1) + True + + The bootstrap distribution of the statistic is often approximately normal + with scale equal to the standard error. + + >>> x = np.linspace(3, 5) + >>> pdf = norm.pdf(x, loc=std_sample, scale=res.standard_error) + >>> fig, ax = plt.subplots() + >>> ax.hist(res.bootstrap_distribution, bins=25, density=True) + >>> ax.plot(x, pdf) + >>> ax.set_title('Normal Approximation of the Bootstrap Distribution') + >>> ax.set_xlabel('statistic value') + >>> ax.set_ylabel('pdf') + >>> plt.show() + + This suggests that we could construct a 90% confidence interval on the + statistic based on quantiles of this normal distribution. + + >>> norm.interval(0.9, loc=std_sample, scale=res.standard_error) + (3.5442759991341726, 4.3478528599786) + + Due to central limit theorem, this normal approximation is accurate for a + variety of statistics and distributions underlying the samples; however, + the approximation is not reliable in all cases. Because `bootstrap` is + designed to work with arbitrary underlying distributions and statistics, + it uses more advanced techniques to generate an accurate confidence + interval. + + >>> print(res.confidence_interval) + ConfidenceInterval(low=3.57655333533867, high=4.382043696342881) + + If we sample from the original distribution 100 times and form a bootstrap + confidence interval for each sample, the confidence interval + contains the true value of the statistic approximately 90% of the time. + + >>> n_trials = 100 + >>> ci_contains_true_std = 0 + >>> for i in range(n_trials): + ... data = (dist.rvs(size=100, random_state=rng),) + ... res = bootstrap(data, np.std, confidence_level=0.9, + ... n_resamples=999, rng=rng) + ... ci = res.confidence_interval + ... if ci[0] < std_true < ci[1]: + ... ci_contains_true_std += 1 + >>> print(ci_contains_true_std) + 88 + + Rather than writing a loop, we can also determine the confidence intervals + for all 100 samples at once. + + >>> data = (dist.rvs(size=(n_trials, 100), random_state=rng),) + >>> res = bootstrap(data, np.std, axis=-1, confidence_level=0.9, + ... n_resamples=999, rng=rng) + >>> ci_l, ci_u = res.confidence_interval + + Here, `ci_l` and `ci_u` contain the confidence interval for each of the + ``n_trials = 100`` samples. + + >>> print(ci_l[:5]) + [3.86401283 3.33304394 3.52474647 3.54160981 3.80569252] + >>> print(ci_u[:5]) + [4.80217409 4.18143252 4.39734707 4.37549713 4.72843584] + + And again, approximately 90% contain the true value, ``std_true = 4``. + + >>> print(np.sum((ci_l < std_true) & (std_true < ci_u))) + 93 + + `bootstrap` can also be used to estimate confidence intervals of + multi-sample statistics. For example, to get a confidence interval + for the difference between means, we write a function that accepts + two sample arguments and returns only the statistic. The use of the + ``axis`` argument ensures that all mean calculations are perform in + a single vectorized call, which is faster than looping over pairs + of resamples in Python. + + >>> def my_statistic(sample1, sample2, axis=-1): + ... mean1 = np.mean(sample1, axis=axis) + ... mean2 = np.mean(sample2, axis=axis) + ... return mean1 - mean2 + + Here, we use the 'percentile' method with the default 95% confidence level. + + >>> sample1 = norm.rvs(scale=1, size=100, random_state=rng) + >>> sample2 = norm.rvs(scale=2, size=100, random_state=rng) + >>> data = (sample1, sample2) + >>> res = bootstrap(data, my_statistic, method='basic', rng=rng) + >>> print(my_statistic(sample1, sample2)) + 0.16661030792089523 + >>> print(res.confidence_interval) + ConfidenceInterval(low=-0.29087973240818693, high=0.6371338699912273) + + The bootstrap estimate of the standard error is also available. + + >>> print(res.standard_error) + 0.238323948262459 + + Paired-sample statistics work, too. For example, consider the Pearson + correlation coefficient. + + >>> from scipy.stats import pearsonr + >>> n = 100 + >>> x = np.linspace(0, 10, n) + >>> y = x + rng.uniform(size=n) + >>> print(pearsonr(x, y)[0]) # element 0 is the statistic + 0.9954306665125647 + + We wrap `pearsonr` so that it returns only the statistic, ensuring + that we use the `axis` argument because it is available. + + >>> def my_statistic(x, y, axis=-1): + ... return pearsonr(x, y, axis=axis)[0] + + We call `bootstrap` using ``paired=True``. + + >>> res = bootstrap((x, y), my_statistic, paired=True, rng=rng) + >>> print(res.confidence_interval) + ConfidenceInterval(low=0.9941504301315878, high=0.996377412215445) + + The result object can be passed back into `bootstrap` to perform additional + resampling: + + >>> len(res.bootstrap_distribution) + 9999 + >>> res = bootstrap((x, y), my_statistic, paired=True, + ... n_resamples=1000, rng=rng, + ... bootstrap_result=res) + >>> len(res.bootstrap_distribution) + 10999 + + or to change the confidence interval options: + + >>> res2 = bootstrap((x, y), my_statistic, paired=True, + ... n_resamples=0, rng=rng, bootstrap_result=res, + ... method='percentile', confidence_level=0.9) + >>> np.testing.assert_equal(res2.bootstrap_distribution, + ... res.bootstrap_distribution) + >>> res.confidence_interval + ConfidenceInterval(low=0.9941574828235082, high=0.9963781698210212) + + without repeating computation of the original bootstrap distribution. + + """ + # Input validation + args = _bootstrap_iv(data, statistic, vectorized, paired, axis, + confidence_level, alternative, n_resamples, batch, + method, bootstrap_result, rng) + (data, statistic, vectorized, paired, axis, confidence_level, + alternative, n_resamples, batch, method, bootstrap_result, + rng) = args + + theta_hat_b = ([] if bootstrap_result is None + else [bootstrap_result.bootstrap_distribution]) + + batch_nominal = batch or n_resamples or 1 + + for k in range(0, n_resamples, batch_nominal): + batch_actual = min(batch_nominal, n_resamples-k) + # Generate resamples + resampled_data = [] + for sample in data: + resample = _bootstrap_resample(sample, n_resamples=batch_actual, + rng=rng) + resampled_data.append(resample) + + # Compute bootstrap distribution of statistic + theta_hat_b.append(statistic(*resampled_data, axis=-1)) + theta_hat_b = np.concatenate(theta_hat_b, axis=-1) + + # Calculate percentile interval + alpha = ((1 - confidence_level)/2 if alternative == 'two-sided' + else (1 - confidence_level)) + if method == 'bca': + interval = _bca_interval(data, statistic, axis=-1, alpha=alpha, + theta_hat_b=theta_hat_b, batch=batch)[:2] + percentile_fun = _percentile_along_axis + else: + interval = alpha, 1-alpha + + def percentile_fun(a, q): + return np.percentile(a=a, q=q, axis=-1) + + # Calculate confidence interval of statistic + ci_l = percentile_fun(theta_hat_b, interval[0]*100) + ci_u = percentile_fun(theta_hat_b, interval[1]*100) + if method == 'basic': # see [3] + theta_hat = statistic(*data, axis=-1) + ci_l, ci_u = 2*theta_hat - ci_u, 2*theta_hat - ci_l + + if alternative == 'less': + ci_l = np.full_like(ci_l, -np.inf) + elif alternative == 'greater': + ci_u = np.full_like(ci_u, np.inf) + + return BootstrapResult(confidence_interval=ConfidenceInterval(ci_l, ci_u), + bootstrap_distribution=theta_hat_b, + standard_error=np.std(theta_hat_b, ddof=1, axis=-1)) + + +def _monte_carlo_test_iv(data, rvs, statistic, vectorized, n_resamples, + batch, alternative, axis): + """Input validation for `monte_carlo_test`.""" + axis_int = int(axis) + if axis != axis_int: + raise ValueError("`axis` must be an integer.") + + if vectorized not in {True, False, None}: + raise ValueError("`vectorized` must be `True`, `False`, or `None`.") + + if not isinstance(rvs, Sequence): + rvs = (rvs,) + data = (data,) + for rvs_i in rvs: + if not callable(rvs_i): + raise TypeError("`rvs` must be callable or sequence of callables.") + + # At this point, `data` should be a sequence + # If it isn't, the user passed a sequence for `rvs` but not `data` + message = "If `rvs` is a sequence, `len(rvs)` must equal `len(data)`." + try: + len(data) + except TypeError as e: + raise ValueError(message) from e + if not len(rvs) == len(data): + raise ValueError(message) + + if not callable(statistic): + raise TypeError("`statistic` must be callable.") + + if vectorized is None: + try: + signature = inspect.signature(statistic).parameters + except ValueError as e: + message = (f"Signature inspection of {statistic=} failed; " + "pass `vectorize` explicitly.") + raise ValueError(message) from e + vectorized = 'axis' in signature + + xp = array_namespace(*data) + + if not vectorized: + if is_numpy(xp): + statistic_vectorized = _vectorize_statistic(statistic) + else: + message = ("`statistic` must be vectorized (i.e. support an `axis` " + f"argument) when `data` contains {xp.__name__} arrays.") + raise ValueError(message) + else: + statistic_vectorized = statistic + + data = _broadcast_arrays(data, axis, xp=xp) + data_iv = [] + for sample in data: + sample = xp.broadcast_to(sample, (1,)) if sample.ndim == 0 else sample + sample = xp_moveaxis_to_end(sample, axis_int, xp=xp) + data_iv.append(sample) + + n_resamples_int = int(n_resamples) + if n_resamples != n_resamples_int or n_resamples_int <= 0: + raise ValueError("`n_resamples` must be a positive integer.") + + if batch is None: + batch_iv = batch + else: + batch_iv = int(batch) + if batch != batch_iv or batch_iv <= 0: + raise ValueError("`batch` must be a positive integer or None.") + + alternatives = {'two-sided', 'greater', 'less'} + alternative = alternative.lower() + if alternative not in alternatives: + raise ValueError(f"`alternative` must be in {alternatives}") + + # Infer the desired p-value dtype based on the input types + min_float = getattr(xp, 'float16', xp.float32) + dtype = xp.result_type(*data_iv, min_float) + + return (data_iv, rvs, statistic_vectorized, vectorized, n_resamples_int, + batch_iv, alternative, axis_int, dtype, xp) + + +@dataclass +class MonteCarloTestResult: + """Result object returned by `scipy.stats.monte_carlo_test`. + + Attributes + ---------- + statistic : float or ndarray + The observed test statistic of the sample. + pvalue : float or ndarray + The p-value for the given alternative. + null_distribution : ndarray + The values of the test statistic generated under the null + hypothesis. + """ + statistic: float | np.ndarray + pvalue: float | np.ndarray + null_distribution: np.ndarray + + +@_rename_parameter('sample', 'data') +def monte_carlo_test(data, rvs, statistic, *, vectorized=None, + n_resamples=9999, batch=None, alternative="two-sided", + axis=0): + r"""Perform a Monte Carlo hypothesis test. + + `data` contains a sample or a sequence of one or more samples. `rvs` + specifies the distribution(s) of the sample(s) in `data` under the null + hypothesis. The value of `statistic` for the given `data` is compared + against a Monte Carlo null distribution: the value of the statistic for + each of `n_resamples` sets of samples generated using `rvs`. This gives + the p-value, the probability of observing such an extreme value of the + test statistic under the null hypothesis. + + Parameters + ---------- + data : array-like or sequence of array-like + An array or sequence of arrays of observations. + rvs : callable or tuple of callables + A callable or sequence of callables that generates random variates + under the null hypothesis. Each element of `rvs` must be a callable + that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and + returns an N-d array sample of that shape. If `rvs` is a sequence, the + number of callables in `rvs` must match the number of samples in + `data`, i.e. ``len(rvs) == len(data)``. If `rvs` is a single callable, + `data` is treated as a single sample. + statistic : callable + Statistic for which the p-value of the hypothesis test is to be + calculated. `statistic` must be a callable that accepts a sample + (e.g. ``statistic(sample)``) or ``len(rvs)`` separate samples (e.g. + ``statistic(samples1, sample2)`` if `rvs` contains two callables and + `data` contains two samples) and returns the resulting statistic. + If `vectorized` is set ``True``, `statistic` must also accept a keyword + argument `axis` and be vectorized to compute the statistic along the + provided `axis` of the samples in `data`. + vectorized : bool, optional + If `vectorized` is set ``False``, `statistic` will not be passed + keyword argument `axis` and is expected to calculate the statistic + only for 1D samples. If ``True``, `statistic` will be passed keyword + argument `axis` and is expected to calculate the statistic along `axis` + when passed ND sample arrays. If ``None`` (default), `vectorized` + will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of + a vectorized statistic typically reduces computation time. + n_resamples : int, default: 9999 + Number of samples drawn from each of the callables of `rvs`. + Equivalently, the number statistic values under the null hypothesis + used as the Monte Carlo null distribution. + batch : int, optional + The number of Monte Carlo samples to process in each call to + `statistic`. Memory usage is O( `batch` * ``sample.size[axis]`` ). Default + is ``None``, in which case `batch` equals `n_resamples`. + alternative : {'two-sided', 'less', 'greater'} + The alternative hypothesis for which the p-value is calculated. + For each alternative, the p-value is defined as follows. + + - ``'greater'`` : the percentage of the null distribution that is + greater than or equal to the observed value of the test statistic. + - ``'less'`` : the percentage of the null distribution that is + less than or equal to the observed value of the test statistic. + - ``'two-sided'`` : twice the smaller of the p-values above. + + axis : int, default: 0 + The axis of `data` (or each sample within `data`) over which to + calculate the statistic. + + Returns + ------- + res : MonteCarloTestResult + An object with attributes: + + statistic : float or ndarray + The test statistic of the observed `data`. + pvalue : float or ndarray + The p-value for the given alternative. + null_distribution : ndarray + The values of the test statistic generated under the null + hypothesis. + + .. warning:: + The p-value is calculated by counting the elements of the null + distribution that are as extreme or more extreme than the observed + value of the statistic. Due to the use of finite precision arithmetic, + some statistic functions return numerically distinct values when the + theoretical values would be exactly equal. In some cases, this could + lead to a large error in the calculated p-value. `monte_carlo_test` + guards against this by considering elements in the null distribution + that are "close" (within a relative tolerance of 100 times the + floating point epsilon of inexact dtypes) to the observed + value of the test statistic as equal to the observed value of the + test statistic. However, the user is advised to inspect the null + distribution to assess whether this method of comparison is + appropriate, and if not, calculate the p-value manually. + + References + ---------- + + .. [1] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be + Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." + Statistical Applications in Genetics and Molecular Biology 9.1 (2010). + + Examples + -------- + + Suppose we wish to test whether a small sample has been drawn from a normal + distribution. We decide that we will use the skew of the sample as a + test statistic, and we will consider a p-value of 0.05 to be statistically + significant. + + >>> import numpy as np + >>> from scipy import stats + >>> def statistic(x, axis): + ... return stats.skew(x, axis) + + After collecting our data, we calculate the observed value of the test + statistic. + + >>> rng = np.random.default_rng() + >>> x = stats.skewnorm.rvs(a=1, size=50, random_state=rng) + >>> statistic(x, axis=0) + 0.12457412450240658 + + To determine the probability of observing such an extreme value of the + skewness by chance if the sample were drawn from the normal distribution, + we can perform a Monte Carlo hypothesis test. The test will draw many + samples at random from their normal distribution, calculate the skewness + of each sample, and compare our original skewness against this + distribution to determine an approximate p-value. + + >>> from scipy.stats import monte_carlo_test + >>> # because our statistic is vectorized, we pass `vectorized=True` + >>> rvs = lambda size: stats.norm.rvs(size=size, random_state=rng) + >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True) + >>> print(res.statistic) + 0.12457412450240658 + >>> print(res.pvalue) + 0.7012 + + The probability of obtaining a test statistic less than or equal to the + observed value under the null hypothesis is ~70%. This is greater than + our chosen threshold of 5%, so we cannot consider this to be significant + evidence against the null hypothesis. + + Note that this p-value essentially matches that of + `scipy.stats.skewtest`, which relies on an asymptotic distribution of a + test statistic based on the sample skewness. + + >>> stats.skewtest(x).pvalue + 0.6892046027110614 + + This asymptotic approximation is not valid for small sample sizes, but + `monte_carlo_test` can be used with samples of any size. + + >>> x = stats.skewnorm.rvs(a=1, size=7, random_state=rng) + >>> # stats.skewtest(x) would produce an error due to small sample + >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True) + + The Monte Carlo distribution of the test statistic is provided for + further investigation. + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.hist(res.null_distribution, bins=50) + >>> ax.set_title("Monte Carlo distribution of test statistic") + >>> ax.set_xlabel("Value of Statistic") + >>> ax.set_ylabel("Frequency") + >>> plt.show() + + """ + args = _monte_carlo_test_iv(data, rvs, statistic, vectorized, + n_resamples, batch, alternative, axis) + (data, rvs, statistic, vectorized, n_resamples, + batch, alternative, axis, dtype, xp) = args + + # Some statistics return plain floats; ensure they're at least a NumPy float + observed = xp.asarray(statistic(*data, axis=-1)) + observed = observed[()] if observed.ndim == 0 else observed + + n_observations = [sample.shape[-1] for sample in data] + batch_nominal = batch or n_resamples + null_distribution = [] + for k in range(0, n_resamples, batch_nominal): + batch_actual = min(batch_nominal, n_resamples - k) + resamples = [rvs_i(size=(batch_actual, n_observations_i)) + for rvs_i, n_observations_i in zip(rvs, n_observations)] + null_distribution.append(statistic(*resamples, axis=-1)) + null_distribution = xp.concat(null_distribution) + null_distribution = xp.reshape(null_distribution, [-1] + [1]*observed.ndim) + + # relative tolerance for detecting numerically distinct but + # theoretically equal values in the null distribution + eps = (0 if not xp.isdtype(observed.dtype, ('real floating')) + else xp.finfo(observed.dtype).eps*100) + gamma = xp.abs(eps * observed) + + def less(null_distribution, observed): + cmps = null_distribution <= observed + gamma + cmps = xp.asarray(cmps, dtype=dtype) + pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.) + return pvalues + + def greater(null_distribution, observed): + cmps = null_distribution >= observed - gamma + cmps = xp.asarray(cmps, dtype=dtype) + pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.) + return pvalues + + def two_sided(null_distribution, observed): + pvalues_less = less(null_distribution, observed) + pvalues_greater = greater(null_distribution, observed) + pvalues = xp.minimum(pvalues_less, pvalues_greater) * 2 + return pvalues + + compare = {"less": less, + "greater": greater, + "two-sided": two_sided} + + pvalues = compare[alternative](null_distribution, observed) + pvalues = xp.clip(pvalues, 0., 1.) + + return MonteCarloTestResult(observed, pvalues, null_distribution) + + +@dataclass +class PowerResult: + """Result object returned by `scipy.stats.power`. + + Attributes + ---------- + power : float or ndarray + The estimated power. + pvalues : float or ndarray + The simulated p-values. + """ + power: float | np.ndarray + pvalues: float | np.ndarray + + +def _wrap_kwargs(fun): + """Wrap callable to accept arbitrary kwargs and ignore unused ones""" + + try: + keys = set(inspect.signature(fun).parameters.keys()) + except ValueError: + # NumPy Generator methods can't be inspected + keys = {'size'} + + # Set keys=keys/fun=fun to avoid late binding gotcha + def wrapped_rvs_i(*args, keys=keys, fun=fun, **all_kwargs): + kwargs = {key: val for key, val in all_kwargs.items() + if key in keys} + return fun(*args, **kwargs) + return wrapped_rvs_i + + +def _power_iv(rvs, test, n_observations, significance, vectorized, + n_resamples, batch, kwargs): + """Input validation for `monte_carlo_test`.""" + + if vectorized not in {True, False, None}: + raise ValueError("`vectorized` must be `True`, `False`, or `None`.") + + if not isinstance(rvs, Sequence): + rvs = (rvs,) + n_observations = (n_observations,) + for rvs_i in rvs: + if not callable(rvs_i): + raise TypeError("`rvs` must be callable or sequence of callables.") + + if not len(rvs) == len(n_observations): + message = ("If `rvs` is a sequence, `len(rvs)` " + "must equal `len(n_observations)`.") + raise ValueError(message) + + significance = np.asarray(significance)[()] + if (not np.issubdtype(significance.dtype, np.floating) + or np.min(significance) < 0 or np.max(significance) > 1): + raise ValueError("`significance` must contain floats between 0 and 1.") + + kwargs = dict() if kwargs is None else kwargs + if not isinstance(kwargs, dict): + raise TypeError("`kwargs` must be a dictionary that maps keywords to arrays.") + + vals = kwargs.values() + keys = kwargs.keys() + + # Wrap callables to ignore unused keyword arguments + wrapped_rvs = [_wrap_kwargs(rvs_i) for rvs_i in rvs] + + # Broadcast, then ravel nobs/kwarg combinations. In the end, + # `nobs` and `vals` have shape (# of combinations, number of variables) + tmp = np.asarray(np.broadcast_arrays(*n_observations, *vals)) + shape = tmp.shape + if tmp.ndim == 1: + tmp = tmp[np.newaxis, :] + else: + tmp = tmp.reshape((shape[0], -1)).T + nobs, vals = tmp[:, :len(rvs)], tmp[:, len(rvs):] + nobs = nobs.astype(int) + + if not callable(test): + raise TypeError("`test` must be callable.") + + if vectorized is None: + vectorized = 'axis' in inspect.signature(test).parameters + + if not vectorized: + test_vectorized = _vectorize_statistic(test) + else: + test_vectorized = test + # Wrap `test` function to ignore unused kwargs + test_vectorized = _wrap_kwargs(test_vectorized) + + n_resamples_int = int(n_resamples) + if n_resamples != n_resamples_int or n_resamples_int <= 0: + raise ValueError("`n_resamples` must be a positive integer.") + + if batch is None: + batch_iv = batch + else: + batch_iv = int(batch) + if batch != batch_iv or batch_iv <= 0: + raise ValueError("`batch` must be a positive integer or None.") + + return (wrapped_rvs, test_vectorized, nobs, significance, vectorized, + n_resamples_int, batch_iv, vals, keys, shape[1:]) + + +def power(test, rvs, n_observations, *, significance=0.01, vectorized=None, + n_resamples=10000, batch=None, kwargs=None): + r"""Simulate the power of a hypothesis test under an alternative hypothesis. + + Parameters + ---------- + test : callable + Hypothesis test for which the power is to be simulated. + `test` must be a callable that accepts a sample (e.g. ``test(sample)``) + or ``len(rvs)`` separate samples (e.g. ``test(samples1, sample2)`` if + `rvs` contains two callables and `n_observations` contains two values) + and returns the p-value of the test. + If `vectorized` is set to ``True``, `test` must also accept a keyword + argument `axis` and be vectorized to perform the test along the + provided `axis` of the samples. + Any callable from `scipy.stats` with an `axis` argument that returns an + object with a `pvalue` attribute is also acceptable. + rvs : callable or tuple of callables + A callable or sequence of callables that generate(s) random variates + under the alternative hypothesis. Each element of `rvs` must accept + keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and return an + N-d array of that shape. If `rvs` is a sequence, the number of callables + in `rvs` must match the number of elements of `n_observations`, i.e. + ``len(rvs) == len(n_observations)``. If `rvs` is a single callable, + `n_observations` is treated as a single element. + n_observations : tuple of ints or tuple of integer arrays + If a sequence of ints, each is the sizes of a sample to be passed to `test`. + If a sequence of integer arrays, the power is simulated for each + set of corresponding sample sizes. See Examples. + significance : float or array_like of floats, default: 0.01 + The threshold for significance; i.e., the p-value below which the + hypothesis test results will be considered as evidence against the null + hypothesis. Equivalently, the acceptable rate of Type I error under + the null hypothesis. If an array, the power is simulated for each + significance threshold. + kwargs : dict, optional + Keyword arguments to be passed to `rvs` and/or `test` callables. + Introspection is used to determine which keyword arguments may be + passed to each callable. + The value corresponding with each keyword must be an array. + Arrays must be broadcastable with one another and with each array in + `n_observations`. The power is simulated for each set of corresponding + sample sizes and arguments. See Examples. + vectorized : bool, optional + If `vectorized` is set to ``False``, `test` will not be passed keyword + argument `axis` and is expected to perform the test only for 1D samples. + If ``True``, `test` will be passed keyword argument `axis` and is + expected to perform the test along `axis` when passed N-D sample arrays. + If ``None`` (default), `vectorized` will be set ``True`` if ``axis`` is + a parameter of `test`. Use of a vectorized test typically reduces + computation time. + n_resamples : int, default: 10000 + Number of samples drawn from each of the callables of `rvs`. + Equivalently, the number tests performed under the alternative + hypothesis to approximate the power. + batch : int, optional + The number of samples to process in each call to `test`. Memory usage is + proportional to the product of `batch` and the largest sample size. Default + is ``None``, in which case `batch` equals `n_resamples`. + + Returns + ------- + res : PowerResult + An object with attributes: + + power : float or ndarray + The estimated power against the alternative. + pvalues : ndarray + The p-values observed under the alternative hypothesis. + + Notes + ----- + The power is simulated as follows: + + - Draw many random samples (or sets of samples), each of the size(s) + specified by `n_observations`, under the alternative specified by + `rvs`. + - For each sample (or set of samples), compute the p-value according to + `test`. These p-values are recorded in the ``pvalues`` attribute of + the result object. + - Compute the proportion of p-values that are less than the `significance` + level. This is the power recorded in the ``power`` attribute of the + result object. + + Suppose that `significance` is an array with shape ``shape1``, the elements + of `kwargs` and `n_observations` are mutually broadcastable to shape ``shape2``, + and `test` returns an array of p-values of shape ``shape3``. Then the result + object ``power`` attribute will be of shape ``shape1 + shape2 + shape3``, and + the ``pvalues`` attribute will be of shape ``shape2 + shape3 + (n_resamples,)``. + + Examples + -------- + Suppose we wish to simulate the power of the independent sample t-test + under the following conditions: + + - The first sample has 10 observations drawn from a normal distribution + with mean 0. + - The second sample has 12 observations drawn from a normal distribution + with mean 1.0. + - The threshold on p-values for significance is 0.05. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(2549598345528) + >>> + >>> test = stats.ttest_ind + >>> n_observations = (10, 12) + >>> rvs1 = rng.normal + >>> rvs2 = lambda size: rng.normal(loc=1, size=size) + >>> rvs = (rvs1, rvs2) + >>> res = stats.power(test, rvs, n_observations, significance=0.05) + >>> res.power + 0.6116 + + With samples of size 10 and 12, respectively, the power of the t-test + with a significance threshold of 0.05 is approximately 60% under the chosen + alternative. We can investigate the effect of sample size on the power + by passing sample size arrays. + + >>> import matplotlib.pyplot as plt + >>> nobs_x = np.arange(5, 21) + >>> nobs_y = nobs_x + >>> n_observations = (nobs_x, nobs_y) + >>> res = stats.power(test, rvs, n_observations, significance=0.05) + >>> ax = plt.subplot() + >>> ax.plot(nobs_x, res.power) + >>> ax.set_xlabel('Sample Size') + >>> ax.set_ylabel('Simulated Power') + >>> ax.set_title('Simulated Power of `ttest_ind` with Equal Sample Sizes') + >>> plt.show() + + Alternatively, we can investigate the impact that effect size has on the power. + In this case, the effect size is the location of the distribution underlying + the second sample. + + >>> n_observations = (10, 12) + >>> loc = np.linspace(0, 1, 20) + >>> rvs2 = lambda size, loc: rng.normal(loc=loc, size=size) + >>> rvs = (rvs1, rvs2) + >>> res = stats.power(test, rvs, n_observations, significance=0.05, + ... kwargs={'loc': loc}) + >>> ax = plt.subplot() + >>> ax.plot(loc, res.power) + >>> ax.set_xlabel('Effect Size') + >>> ax.set_ylabel('Simulated Power') + >>> ax.set_title('Simulated Power of `ttest_ind`, Varying Effect Size') + >>> plt.show() + + We can also use `power` to estimate the Type I error rate (also referred to by the + ambiguous term "size") of a test and assess whether it matches the nominal level. + For example, the null hypothesis of `jarque_bera` is that the sample was drawn from + a distribution with the same skewness and kurtosis as the normal distribution. To + estimate the Type I error rate, we can consider the null hypothesis to be a true + *alternative* hypothesis and calculate the power. + + >>> test = stats.jarque_bera + >>> n_observations = 10 + >>> rvs = rng.normal + >>> significance = np.linspace(0.0001, 0.1, 1000) + >>> res = stats.power(test, rvs, n_observations, significance=significance) + >>> size = res.power + + As shown below, the Type I error rate of the test is far below the nominal level + for such a small sample, as mentioned in its documentation. + + >>> ax = plt.subplot() + >>> ax.plot(significance, size) + >>> ax.plot([0, 0.1], [0, 0.1], '--') + >>> ax.set_xlabel('nominal significance level') + >>> ax.set_ylabel('estimated test size (Type I error rate)') + >>> ax.set_title('Estimated test size vs nominal significance level') + >>> ax.set_aspect('equal', 'box') + >>> ax.legend(('`ttest_1samp`', 'ideal test')) + >>> plt.show() + + As one might expect from such a conservative test, the power is quite low with + respect to some alternatives. For example, the power of the test under the + alternative that the sample was drawn from the Laplace distribution may not + be much greater than the Type I error rate. + + >>> rvs = rng.laplace + >>> significance = np.linspace(0.0001, 0.1, 1000) + >>> res = stats.power(test, rvs, n_observations, significance=0.05) + >>> print(res.power) + 0.0587 + + This is not a mistake in SciPy's implementation; it is simply due to the fact + that the null distribution of the test statistic is derived under the assumption + that the sample size is large (i.e. approaches infinity), and this asymptotic + approximation is not accurate for small samples. In such cases, resampling + and Monte Carlo methods (e.g. `permutation_test`, `goodness_of_fit`, + `monte_carlo_test`) may be more appropriate. + + """ + tmp = _power_iv(rvs, test, n_observations, significance, + vectorized, n_resamples, batch, kwargs) + (rvs, test, nobs, significance, + vectorized, n_resamples, batch, args, kwds, shape)= tmp + + batch_nominal = batch or n_resamples + pvalues = [] # results of various nobs/kwargs combinations + for nobs_i, args_i in zip(nobs, args): + kwargs_i = dict(zip(kwds, args_i)) + pvalues_i = [] # results of batches; fixed nobs/kwargs combination + for k in range(0, n_resamples, batch_nominal): + batch_actual = min(batch_nominal, n_resamples - k) + resamples = [rvs_j(size=(batch_actual, nobs_ij), **kwargs_i) + for rvs_j, nobs_ij in zip(rvs, nobs_i)] + res = test(*resamples, **kwargs_i, axis=-1) + p = getattr(res, 'pvalue', res) + pvalues_i.append(p) + # Concatenate results from batches + pvalues_i = np.concatenate(pvalues_i, axis=-1) + pvalues.append(pvalues_i) + # `test` can return result with array of p-values + shape += pvalues_i.shape[:-1] + # Concatenate results from various nobs/kwargs combinations + pvalues = np.concatenate(pvalues, axis=0) + # nobs/kwargs arrays were raveled to single axis; unravel + pvalues = pvalues.reshape(shape + (-1,)) + if significance.ndim > 0: + newdims = tuple(range(significance.ndim, pvalues.ndim + significance.ndim)) + significance = np.expand_dims(significance, newdims) + powers = np.mean(pvalues < significance, axis=-1) + + return PowerResult(power=powers, pvalues=pvalues) + + +@dataclass +class PermutationTestResult: + """Result object returned by `scipy.stats.permutation_test`. + + Attributes + ---------- + statistic : float or ndarray + The observed test statistic of the data. + pvalue : float or ndarray + The p-value for the given alternative. + null_distribution : ndarray + The values of the test statistic generated under the null + hypothesis. + """ + statistic: float | np.ndarray + pvalue: float | np.ndarray + null_distribution: np.ndarray + + +def _all_partitions_concatenated(ns): + """ + Generate all partitions of indices of groups of given sizes, concatenated + + `ns` is an iterable of ints. + """ + def all_partitions(z, n): + for c in combinations(z, n): + x0 = set(c) + x1 = z - x0 + yield [x0, x1] + + def all_partitions_n(z, ns): + if len(ns) == 0: + yield [z] + return + for c in all_partitions(z, ns[0]): + for d in all_partitions_n(c[1], ns[1:]): + yield c[0:1] + d + + z = set(range(np.sum(ns))) + for partitioning in all_partitions_n(z, ns[:]): + x = np.concatenate([list(partition) + for partition in partitioning]).astype(int) + yield x + + +def _batch_generator(iterable, batch): + """A generator that yields batches of elements from an iterable""" + iterator = iter(iterable) + if batch <= 0: + raise ValueError("`batch` must be positive.") + z = [item for i, item in zip(range(batch), iterator)] + while z: # we don't want StopIteration without yielding an empty list + yield z + z = [item for i, item in zip(range(batch), iterator)] + + +def _pairings_permutations_gen(n_permutations, n_samples, n_obs_sample, batch, + rng): + # Returns a generator that yields arrays of size + # `(batch, n_samples, n_obs_sample)`. + # Each row is an independent permutation of indices 0 to `n_obs_sample`. + batch = min(batch, n_permutations) + + if hasattr(rng, 'permuted'): + def batched_perm_generator(): + indices = np.arange(n_obs_sample) + indices = np.tile(indices, (batch, n_samples, 1)) + for k in range(0, n_permutations, batch): + batch_actual = min(batch, n_permutations-k) + # Don't permute in place, otherwise results depend on `batch` + permuted_indices = rng.permuted(indices, axis=-1) + yield permuted_indices[:batch_actual] + else: # RandomState and early Generators don't have `permuted` + def batched_perm_generator(): + for k in range(0, n_permutations, batch): + batch_actual = min(batch, n_permutations-k) + size = (batch_actual, n_samples, n_obs_sample) + x = rng.random(size=size) + yield np.argsort(x, axis=-1)[:batch_actual] + + return batched_perm_generator() + + +def _calculate_null_both(data, statistic, n_permutations, batch, + rng=None): + """ + Calculate null distribution for independent sample tests. + """ + n_samples = len(data) + + # compute number of permutations + # (distinct partitions of data into samples of these sizes) + n_obs_i = [sample.shape[-1] for sample in data] # observations per sample + n_obs_ic = np.cumsum(n_obs_i) + n_obs = n_obs_ic[-1] # total number of observations + n_max = np.prod([comb(n_obs_ic[i], n_obs_ic[i-1]) + for i in range(n_samples-1, 0, -1)]) + + # perm_generator is an iterator that produces permutations of indices + # from 0 to n_obs. We'll concatenate the samples, use these indices to + # permute the data, then split the samples apart again. + if n_permutations >= n_max: + exact_test = True + n_permutations = n_max + perm_generator = _all_partitions_concatenated(n_obs_i) + else: + exact_test = False + # Neither RandomState.permutation nor Generator.permutation + # can permute axis-slices independently. If this feature is + # added in the future, batches of the desired size should be + # generated in a single call. + perm_generator = (rng.permutation(n_obs) + for i in range(n_permutations)) + + batch = batch or int(n_permutations) + null_distribution = [] + + # First, concatenate all the samples. In batches, permute samples with + # indices produced by the `perm_generator`, split them into new samples of + # the original sizes, compute the statistic for each batch, and add these + # statistic values to the null distribution. + data = np.concatenate(data, axis=-1) + for indices in _batch_generator(perm_generator, batch=batch): + indices = np.array(indices) + + # `indices` is 2D: each row is a permutation of the indices. + # We use it to index `data` along its last axis, which corresponds + # with observations. + # After indexing, the second to last axis of `data_batch` corresponds + # with permutations, and the last axis corresponds with observations. + data_batch = data[..., indices] + + # Move the permutation axis to the front: we'll concatenate a list + # of batched statistic values along this zeroth axis to form the + # null distribution. + data_batch = np.moveaxis(data_batch, -2, 0) + data_batch = np.split(data_batch, n_obs_ic[:-1], axis=-1) + null_distribution.append(statistic(*data_batch, axis=-1)) + null_distribution = np.concatenate(null_distribution, axis=0) + + return null_distribution, n_permutations, exact_test + + +def _calculate_null_pairings(data, statistic, n_permutations, batch, + rng=None): + """ + Calculate null distribution for association tests. + """ + n_samples = len(data) + + # compute number of permutations (factorial(n) permutations of each sample) + n_obs_sample = data[0].shape[-1] # observations per sample; same for each + n_max = factorial(n_obs_sample)**n_samples + + # `perm_generator` is an iterator that produces a list of permutations of + # indices from 0 to n_obs_sample, one for each sample. + if n_permutations >= n_max: + exact_test = True + n_permutations = n_max + batch = batch or int(n_permutations) + # Cartesian product of the sets of all permutations of indices + perm_generator = product(*(permutations(range(n_obs_sample)) + for i in range(n_samples))) + batched_perm_generator = _batch_generator(perm_generator, batch=batch) + else: + exact_test = False + batch = batch or int(n_permutations) + # Separate random permutations of indices for each sample. + # Again, it would be nice if RandomState/Generator.permutation + # could permute each axis-slice separately. + args = n_permutations, n_samples, n_obs_sample, batch, rng + batched_perm_generator = _pairings_permutations_gen(*args) + + null_distribution = [] + + for indices in batched_perm_generator: + indices = np.array(indices) + + # `indices` is 3D: the zeroth axis is for permutations, the next is + # for samples, and the last is for observations. Swap the first two + # to make the zeroth axis correspond with samples, as it does for + # `data`. + indices = np.swapaxes(indices, 0, 1) + + # When we're done, `data_batch` will be a list of length `n_samples`. + # Each element will be a batch of random permutations of one sample. + # The zeroth axis of each batch will correspond with permutations, + # and the last will correspond with observations. (This makes it + # easy to pass into `statistic`.) + data_batch = [None]*n_samples + for i in range(n_samples): + data_batch[i] = data[i][..., indices[i]] + data_batch[i] = np.moveaxis(data_batch[i], -2, 0) + + null_distribution.append(statistic(*data_batch, axis=-1)) + null_distribution = np.concatenate(null_distribution, axis=0) + + return null_distribution, n_permutations, exact_test + + +def _calculate_null_samples(data, statistic, n_permutations, batch, + rng=None): + """ + Calculate null distribution for paired-sample tests. + """ + n_samples = len(data) + + # By convention, the meaning of the "samples" permutations type for + # data with only one sample is to flip the sign of the observations. + # Achieve this by adding a second sample - the negative of the original. + if n_samples == 1: + data = [data[0], -data[0]] + + # The "samples" permutation strategy is the same as the "pairings" + # strategy except the roles of samples and observations are flipped. + # So swap these axes, then we'll use the function for the "pairings" + # strategy to do all the work! + data = np.swapaxes(data, 0, -1) + + # (Of course, the user's statistic doesn't know what we've done here, + # so we need to pass it what it's expecting.) + def statistic_wrapped(*data, axis): + data = np.swapaxes(data, 0, -1) + if n_samples == 1: + data = data[0:1] + return statistic(*data, axis=axis) + + return _calculate_null_pairings(data, statistic_wrapped, n_permutations, + batch, rng) + + +def _permutation_test_iv(data, statistic, permutation_type, vectorized, + n_resamples, batch, alternative, axis, rng): + """Input validation for `permutation_test`.""" + + axis_int = int(axis) + if axis != axis_int: + raise ValueError("`axis` must be an integer.") + + permutation_types = {'samples', 'pairings', 'independent'} + permutation_type = permutation_type.lower() + if permutation_type not in permutation_types: + raise ValueError(f"`permutation_type` must be in {permutation_types}.") + + if vectorized not in {True, False, None}: + raise ValueError("`vectorized` must be `True`, `False`, or `None`.") + + if vectorized is None: + vectorized = 'axis' in inspect.signature(statistic).parameters + + if not vectorized: + statistic = _vectorize_statistic(statistic) + + message = "`data` must be a tuple containing at least two samples" + try: + if len(data) < 2 and permutation_type == 'independent': + raise ValueError(message) + except TypeError: + raise TypeError(message) + + data = _broadcast_arrays(data, axis) + data_iv = [] + for sample in data: + sample = np.atleast_1d(sample) + if sample.shape[axis] <= 1: + raise ValueError("each sample in `data` must contain two or more " + "observations along `axis`.") + sample = np.moveaxis(sample, axis_int, -1) + data_iv.append(sample) + + n_resamples_int = (int(n_resamples) if not np.isinf(n_resamples) + else np.inf) + if n_resamples != n_resamples_int or n_resamples_int <= 0: + raise ValueError("`n_resamples` must be a positive integer.") + + if batch is None: + batch_iv = batch + else: + batch_iv = int(batch) + if batch != batch_iv or batch_iv <= 0: + raise ValueError("`batch` must be a positive integer or None.") + + alternatives = {'two-sided', 'greater', 'less'} + alternative = alternative.lower() + if alternative not in alternatives: + raise ValueError(f"`alternative` must be in {alternatives}") + + rng = check_random_state(rng) + + return (data_iv, statistic, permutation_type, vectorized, n_resamples_int, + batch_iv, alternative, axis_int, rng) + + +@_transition_to_rng('random_state') +def permutation_test(data, statistic, *, permutation_type='independent', + vectorized=None, n_resamples=9999, batch=None, + alternative="two-sided", axis=0, rng=None): + r""" + Performs a permutation test of a given statistic on provided data. + + For independent sample statistics, the null hypothesis is that the data are + randomly sampled from the same distribution. + For paired sample statistics, two null hypothesis can be tested: + that the data are paired at random or that the data are assigned to samples + at random. + + Parameters + ---------- + data : iterable of array-like + Contains the samples, each of which is an array of observations. + Dimensions of sample arrays must be compatible for broadcasting except + along `axis`. + statistic : callable + Statistic for which the p-value of the hypothesis test is to be + calculated. `statistic` must be a callable that accepts samples + as separate arguments (e.g. ``statistic(*data)``) and returns the + resulting statistic. + If `vectorized` is set ``True``, `statistic` must also accept a keyword + argument `axis` and be vectorized to compute the statistic along the + provided `axis` of the sample arrays. + permutation_type : {'independent', 'samples', 'pairings'}, optional + The type of permutations to be performed, in accordance with the + null hypothesis. The first two permutation types are for paired sample + statistics, in which all samples contain the same number of + observations and observations with corresponding indices along `axis` + are considered to be paired; the third is for independent sample + statistics. + + - ``'samples'`` : observations are assigned to different samples + but remain paired with the same observations from other samples. + This permutation type is appropriate for paired sample hypothesis + tests such as the Wilcoxon signed-rank test and the paired t-test. + - ``'pairings'`` : observations are paired with different observations, + but they remain within the same sample. This permutation type is + appropriate for association/correlation tests with statistics such + as Spearman's :math:`\rho`, Kendall's :math:`\tau`, and Pearson's + :math:`r`. + - ``'independent'`` (default) : observations are assigned to different + samples. Samples may contain different numbers of observations. This + permutation type is appropriate for independent sample hypothesis + tests such as the Mann-Whitney :math:`U` test and the independent + sample t-test. + + Please see the Notes section below for more detailed descriptions + of the permutation types. + + vectorized : bool, optional + If `vectorized` is set ``False``, `statistic` will not be passed + keyword argument `axis` and is expected to calculate the statistic + only for 1D samples. If ``True``, `statistic` will be passed keyword + argument `axis` and is expected to calculate the statistic along `axis` + when passed an ND sample array. If ``None`` (default), `vectorized` + will be set ``True`` if ``axis`` is a parameter of `statistic`. Use + of a vectorized statistic typically reduces computation time. + n_resamples : int or np.inf, default: 9999 + Number of random permutations (resamples) used to approximate the null + distribution. If greater than or equal to the number of distinct + permutations, the exact null distribution will be computed. + Note that the number of distinct permutations grows very rapidly with + the sizes of samples, so exact tests are feasible only for very small + data sets. + batch : int, optional + The number of permutations to process in each call to `statistic`. + Memory usage is O( `batch` * ``n`` ), where ``n`` is the total size + of all samples, regardless of the value of `vectorized`. Default is + ``None``, in which case ``batch`` is the number of permutations. + alternative : {'two-sided', 'less', 'greater'}, optional + The alternative hypothesis for which the p-value is calculated. + For each alternative, the p-value is defined for exact tests as + follows. + + - ``'greater'`` : the percentage of the null distribution that is + greater than or equal to the observed value of the test statistic. + - ``'less'`` : the percentage of the null distribution that is + less than or equal to the observed value of the test statistic. + - ``'two-sided'`` (default) : twice the smaller of the p-values above. + + Note that p-values for randomized tests are calculated according to the + conservative (over-estimated) approximation suggested in [2]_ and [3]_ + rather than the unbiased estimator suggested in [4]_. That is, when + calculating the proportion of the randomized null distribution that is + as extreme as the observed value of the test statistic, the values in + the numerator and denominator are both increased by one. An + interpretation of this adjustment is that the observed value of the + test statistic is always included as an element of the randomized + null distribution. + The convention used for two-sided p-values is not universal; + the observed test statistic and null distribution are returned in + case a different definition is preferred. + + axis : int, default: 0 + The axis of the (broadcasted) samples over which to calculate the + statistic. If samples have a different number of dimensions, + singleton dimensions are prepended to samples with fewer dimensions + before `axis` is considered. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + res : PermutationTestResult + An object with attributes: + + statistic : float or ndarray + The observed test statistic of the data. + pvalue : float or ndarray + The p-value for the given alternative. + null_distribution : ndarray + The values of the test statistic generated under the null + hypothesis. + + Notes + ----- + + The three types of permutation tests supported by this function are + described below. + + **Unpaired statistics** (``permutation_type='independent'``): + + The null hypothesis associated with this permutation type is that all + observations are sampled from the same underlying distribution and that + they have been assigned to one of the samples at random. + + Suppose ``data`` contains two samples; e.g. ``a, b = data``. + When ``1 < n_resamples < binom(n, k)``, where + + * ``k`` is the number of observations in ``a``, + * ``n`` is the total number of observations in ``a`` and ``b``, and + * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``), + + the data are pooled (concatenated), randomly assigned to either the first + or second sample, and the statistic is calculated. This process is + performed repeatedly, `permutation` times, generating a distribution of the + statistic under the null hypothesis. The statistic of the original + data is compared to this distribution to determine the p-value. + + When ``n_resamples >= binom(n, k)``, an exact test is performed: the data + are *partitioned* between the samples in each distinct way exactly once, + and the exact null distribution is formed. + Note that for a given partitioning of the data between the samples, + only one ordering/permutation of the data *within* each sample is + considered. For statistics that do not depend on the order of the data + within samples, this dramatically reduces computational cost without + affecting the shape of the null distribution (because the frequency/count + of each value is affected by the same factor). + + For ``a = [a1, a2, a3, a4]`` and ``b = [b1, b2, b3]``, an example of this + permutation type is ``x = [b3, a1, a2, b2]`` and ``y = [a4, b1, a3]``. + Because only one ordering/permutation of the data *within* each sample + is considered in an exact test, a resampling like ``x = [b3, a1, b2, a2]`` + and ``y = [a4, a3, b1]`` would *not* be considered distinct from the + example above. + + ``permutation_type='independent'`` does not support one-sample statistics, + but it can be applied to statistics with more than two samples. In this + case, if ``n`` is an array of the number of observations within each + sample, the number of distinct partitions is:: + + np.prod([binom(sum(n[i:]), sum(n[i+1:])) for i in range(len(n)-1)]) + + **Paired statistics, permute pairings** (``permutation_type='pairings'``): + + The null hypothesis associated with this permutation type is that + observations within each sample are drawn from the same underlying + distribution and that pairings with elements of other samples are + assigned at random. + + Suppose ``data`` contains only one sample; e.g. ``a, = data``, and we + wish to consider all possible pairings of elements of ``a`` with elements + of a second sample, ``b``. Let ``n`` be the number of observations in + ``a``, which must also equal the number of observations in ``b``. + + When ``1 < n_resamples < factorial(n)``, the elements of ``a`` are + randomly permuted. The user-supplied statistic accepts one data argument, + say ``a_perm``, and calculates the statistic considering ``a_perm`` and + ``b``. This process is performed repeatedly, `permutation` times, + generating a distribution of the statistic under the null hypothesis. + The statistic of the original data is compared to this distribution to + determine the p-value. + + When ``n_resamples >= factorial(n)``, an exact test is performed: + ``a`` is permuted in each distinct way exactly once. Therefore, the + `statistic` is computed for each unique pairing of samples between ``a`` + and ``b`` exactly once. + + For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this + permutation type is ``a_perm = [a3, a1, a2]`` while ``b`` is left + in its original order. + + ``permutation_type='pairings'`` supports ``data`` containing any number + of samples, each of which must contain the same number of observations. + All samples provided in ``data`` are permuted *independently*. Therefore, + if ``m`` is the number of samples and ``n`` is the number of observations + within each sample, then the number of permutations in an exact test is:: + + factorial(n)**m + + Note that if a two-sample statistic, for example, does not inherently + depend on the order in which observations are provided - only on the + *pairings* of observations - then only one of the two samples should be + provided in ``data``. This dramatically reduces computational cost without + affecting the shape of the null distribution (because the frequency/count + of each value is affected by the same factor). + + **Paired statistics, permute samples** (``permutation_type='samples'``): + + The null hypothesis associated with this permutation type is that + observations within each pair are drawn from the same underlying + distribution and that the sample to which they are assigned is random. + + Suppose ``data`` contains two samples; e.g. ``a, b = data``. + Let ``n`` be the number of observations in ``a``, which must also equal + the number of observations in ``b``. + + When ``1 < n_resamples < 2**n``, the elements of ``a`` are ``b`` are + randomly swapped between samples (maintaining their pairings) and the + statistic is calculated. This process is performed repeatedly, + `permutation` times, generating a distribution of the statistic under the + null hypothesis. The statistic of the original data is compared to this + distribution to determine the p-value. + + When ``n_resamples >= 2**n``, an exact test is performed: the observations + are assigned to the two samples in each distinct way (while maintaining + pairings) exactly once. + + For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this + permutation type is ``x = [b1, a2, b3]`` and ``y = [a1, b2, a3]``. + + ``permutation_type='samples'`` supports ``data`` containing any number + of samples, each of which must contain the same number of observations. + If ``data`` contains more than one sample, paired observations within + ``data`` are exchanged between samples *independently*. Therefore, if ``m`` + is the number of samples and ``n`` is the number of observations within + each sample, then the number of permutations in an exact test is:: + + factorial(m)**n + + Several paired-sample statistical tests, such as the Wilcoxon signed rank + test and paired-sample t-test, can be performed considering only the + *difference* between two paired elements. Accordingly, if ``data`` contains + only one sample, then the null distribution is formed by independently + changing the *sign* of each observation. + + .. warning:: + The p-value is calculated by counting the elements of the null + distribution that are as extreme or more extreme than the observed + value of the statistic. Due to the use of finite precision arithmetic, + some statistic functions return numerically distinct values when the + theoretical values would be exactly equal. In some cases, this could + lead to a large error in the calculated p-value. `permutation_test` + guards against this by considering elements in the null distribution + that are "close" (within a relative tolerance of 100 times the + floating point epsilon of inexact dtypes) to the observed + value of the test statistic as equal to the observed value of the + test statistic. However, the user is advised to inspect the null + distribution to assess whether this method of comparison is + appropriate, and if not, calculate the p-value manually. See example + below. + + References + ---------- + + .. [1] R. A. Fisher. The Design of Experiments, 6th Ed (1951). + .. [2] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be + Zero: Calculating Exact P-values When Permutations Are Randomly Drawn." + Statistical Applications in Genetics and Molecular Biology 9.1 (2010). + .. [3] M. D. Ernst. "Permutation Methods: A Basis for Exact Inference". + Statistical Science (2004). + .. [4] B. Efron and R. J. Tibshirani. An Introduction to the Bootstrap + (1993). + + Examples + -------- + + Suppose we wish to test whether two samples are drawn from the same + distribution. Assume that the underlying distributions are unknown to us, + and that before observing the data, we hypothesized that the mean of the + first sample would be less than that of the second sample. We decide that + we will use the difference between the sample means as a test statistic, + and we will consider a p-value of 0.05 to be statistically significant. + + For efficiency, we write the function defining the test statistic in a + vectorized fashion: the samples ``x`` and ``y`` can be ND arrays, and the + statistic will be calculated for each axis-slice along `axis`. + + >>> import numpy as np + >>> def statistic(x, y, axis): + ... return np.mean(x, axis=axis) - np.mean(y, axis=axis) + + After collecting our data, we calculate the observed value of the test + statistic. + + >>> from scipy.stats import norm + >>> rng = np.random.default_rng() + >>> x = norm.rvs(size=5, random_state=rng) + >>> y = norm.rvs(size=6, loc = 3, random_state=rng) + >>> statistic(x, y, 0) + -3.5411688580987266 + + Indeed, the test statistic is negative, suggesting that the true mean of + the distribution underlying ``x`` is less than that of the distribution + underlying ``y``. To determine the probability of this occurring by chance + if the two samples were drawn from the same distribution, we perform + a permutation test. + + >>> from scipy.stats import permutation_test + >>> # because our statistic is vectorized, we pass `vectorized=True` + >>> # `n_resamples=np.inf` indicates that an exact test is to be performed + >>> res = permutation_test((x, y), statistic, vectorized=True, + ... n_resamples=np.inf, alternative='less') + >>> print(res.statistic) + -3.5411688580987266 + >>> print(res.pvalue) + 0.004329004329004329 + + The probability of obtaining a test statistic less than or equal to the + observed value under the null hypothesis is 0.4329%. This is less than our + chosen threshold of 5%, so we consider this to be significant evidence + against the null hypothesis in favor of the alternative. + + Because the size of the samples above was small, `permutation_test` could + perform an exact test. For larger samples, we resort to a randomized + permutation test. + + >>> x = norm.rvs(size=100, random_state=rng) + >>> y = norm.rvs(size=120, loc=0.2, random_state=rng) + >>> res = permutation_test((x, y), statistic, n_resamples=9999, + ... vectorized=True, alternative='less', + ... rng=rng) + >>> print(res.statistic) + -0.4230459671240913 + >>> print(res.pvalue) + 0.0015 + + The approximate probability of obtaining a test statistic less than or + equal to the observed value under the null hypothesis is 0.0225%. This is + again less than our chosen threshold of 5%, so again we have significant + evidence to reject the null hypothesis in favor of the alternative. + + For large samples and number of permutations, the result is comparable to + that of the corresponding asymptotic test, the independent sample t-test. + + >>> from scipy.stats import ttest_ind + >>> res_asymptotic = ttest_ind(x, y, alternative='less') + >>> print(res_asymptotic.pvalue) + 0.0014669545224902675 + + The permutation distribution of the test statistic is provided for + further investigation. + + >>> import matplotlib.pyplot as plt + >>> plt.hist(res.null_distribution, bins=50) + >>> plt.title("Permutation distribution of test statistic") + >>> plt.xlabel("Value of Statistic") + >>> plt.ylabel("Frequency") + >>> plt.show() + + Inspection of the null distribution is essential if the statistic suffers + from inaccuracy due to limited machine precision. Consider the following + case: + + >>> from scipy.stats import pearsonr + >>> x = [1, 2, 4, 3] + >>> y = [2, 4, 6, 8] + >>> def statistic(x, y, axis=-1): + ... return pearsonr(x, y, axis=axis).statistic + >>> res = permutation_test((x, y), statistic, vectorized=True, + ... permutation_type='pairings', + ... alternative='greater') + >>> r, pvalue, null = res.statistic, res.pvalue, res.null_distribution + + In this case, some elements of the null distribution differ from the + observed value of the correlation coefficient ``r`` due to numerical noise. + We manually inspect the elements of the null distribution that are nearly + the same as the observed value of the test statistic. + + >>> r + 0.7999999999999999 + >>> unique = np.unique(null) + >>> unique + array([-1. , -1. , -0.8, -0.8, -0.8, -0.6, -0.4, -0.4, -0.2, -0.2, -0.2, + 0. , 0.2, 0.2, 0.2, 0.4, 0.4, 0.6, 0.8, 0.8, 0.8, 1. , + 1. ]) # may vary + >>> unique[np.isclose(r, unique)].tolist() + [0.7999999999999998, 0.7999999999999999, 0.8] # may vary + + If `permutation_test` were to perform the comparison naively, the + elements of the null distribution with value ``0.7999999999999998`` would + not be considered as extreme or more extreme as the observed value of the + statistic, so the calculated p-value would be too small. + + >>> incorrect_pvalue = np.count_nonzero(null >= r) / len(null) + >>> incorrect_pvalue + 0.14583333333333334 # may vary + + Instead, `permutation_test` treats elements of the null distribution that + are within ``max(1e-14, abs(r)*1e-14)`` of the observed value of the + statistic ``r`` to be equal to ``r``. + + >>> correct_pvalue = np.count_nonzero(null >= r - 1e-14) / len(null) + >>> correct_pvalue + 0.16666666666666666 + >>> res.pvalue == correct_pvalue + True + + This method of comparison is expected to be accurate in most practical + situations, but the user is advised to assess this by inspecting the + elements of the null distribution that are close to the observed value + of the statistic. Also, consider the use of statistics that can be + calculated using exact arithmetic (e.g. integer statistics). + + """ + args = _permutation_test_iv(data, statistic, permutation_type, vectorized, + n_resamples, batch, alternative, axis, + rng) + (data, statistic, permutation_type, vectorized, n_resamples, batch, + alternative, axis, rng) = args + + observed = statistic(*data, axis=-1) + + null_calculators = {"pairings": _calculate_null_pairings, + "samples": _calculate_null_samples, + "independent": _calculate_null_both} + null_calculator_args = (data, statistic, n_resamples, + batch, rng) + calculate_null = null_calculators[permutation_type] + null_distribution, n_resamples, exact_test = ( + calculate_null(*null_calculator_args)) + + # See References [2] and [3] + adjustment = 0 if exact_test else 1 + + # relative tolerance for detecting numerically distinct but + # theoretically equal values in the null distribution + eps = (0 if not np.issubdtype(observed.dtype, np.inexact) + else np.finfo(observed.dtype).eps*100) + gamma = np.abs(eps * observed) + + def less(null_distribution, observed): + cmps = null_distribution <= observed + gamma + pvalues = (cmps.sum(axis=0) + adjustment) / (n_resamples + adjustment) + return pvalues + + def greater(null_distribution, observed): + cmps = null_distribution >= observed - gamma + pvalues = (cmps.sum(axis=0) + adjustment) / (n_resamples + adjustment) + return pvalues + + def two_sided(null_distribution, observed): + pvalues_less = less(null_distribution, observed) + pvalues_greater = greater(null_distribution, observed) + pvalues = np.minimum(pvalues_less, pvalues_greater) * 2 + return pvalues + + compare = {"less": less, + "greater": greater, + "two-sided": two_sided} + + pvalues = compare[alternative](null_distribution, observed) + pvalues = np.clip(pvalues, 0, 1) + + return PermutationTestResult(observed, pvalues, null_distribution) + + +@dataclass +class ResamplingMethod: + """Configuration information for a statistical resampling method. + + Instances of this class can be passed into the `method` parameter of some + hypothesis test functions to perform a resampling or Monte Carlo version + of the hypothesis test. + + Attributes + ---------- + n_resamples : int + The number of resamples to perform or Monte Carlo samples to draw. + batch : int, optional + The number of resamples to process in each vectorized call to + the statistic. Batch sizes >>1 tend to be faster when the statistic + is vectorized, but memory usage scales linearly with the batch size. + Default is ``None``, which processes all resamples in a single batch. + + """ + n_resamples: int = 9999 + batch: int = None # type: ignore[assignment] + + +@dataclass +class MonteCarloMethod(ResamplingMethod): + """Configuration information for a Monte Carlo hypothesis test. + + Instances of this class can be passed into the `method` parameter of some + hypothesis test functions to perform a Monte Carlo version of the + hypothesis tests. + + Attributes + ---------- + n_resamples : int, optional + The number of Monte Carlo samples to draw. Default is 9999. + batch : int, optional + The number of Monte Carlo samples to process in each vectorized call to + the statistic. Batch sizes >>1 tend to be faster when the statistic + is vectorized, but memory usage scales linearly with the batch size. + Default is ``None``, which processes all samples in a single batch. + rvs : callable or tuple of callables, optional + A callable or sequence of callables that generates random variates + under the null hypothesis. Each element of `rvs` must be a callable + that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and + returns an N-d array sample of that shape. If `rvs` is a sequence, the + number of callables in `rvs` must match the number of samples passed + to the hypothesis test in which the `MonteCarloMethod` is used. Default + is ``None``, in which case the hypothesis test function chooses values + to match the standard version of the hypothesis test. For example, + the null hypothesis of `scipy.stats.pearsonr` is typically that the + samples are drawn from the standard normal distribution, so + ``rvs = (rng.normal, rng.normal)`` where + ``rng = np.random.default_rng()``. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + """ + rvs: object = None + rng: object = None + + def __init__(self, n_resamples=9999, batch=None, rvs=None, rng=None): + if (rvs is not None) and (rng is not None): + message = 'Use of `rvs` and `rng` are mutually exclusive.' + raise ValueError(message) + + self.n_resamples = n_resamples + self.batch = batch + self.rvs = rvs + self.rng = rng + + def _asdict(self): + # `dataclasses.asdict` deepcopies; we don't want that. + return dict(n_resamples=self.n_resamples, batch=self.batch, + rvs=self.rvs, rng=self.rng) + + +_rs_deprecation = ("Use of attribute `random_state` is deprecated and replaced by " + "`rng`. Support for `random_state` will be removed in SciPy 1.19.0. " + "To silence this warning and ensure consistent behavior in SciPy " + "1.19.0, control the RNG using attribute `rng`. Values set using " + "attribute `rng` will be validated by `np.random.default_rng`, so " + "the behavior corresponding with a given value may change compared " + "to use of `random_state`. For example, 1) `None` will result in " + "unpredictable random numbers, 2) an integer will result in a " + "different stream of random numbers, (with the same distribution), " + "and 3) `np.random` or `RandomState` instances will result in an " + "error. See the documentation of `default_rng` for more " + "information.") + + +@dataclass +class PermutationMethod(ResamplingMethod): + """Configuration information for a permutation hypothesis test. + + Instances of this class can be passed into the `method` parameter of some + hypothesis test functions to perform a permutation version of the + hypothesis tests. + + Attributes + ---------- + n_resamples : int, optional + The number of resamples to perform. Default is 9999. + batch : int, optional + The number of resamples to process in each vectorized call to + the statistic. Batch sizes >>1 tend to be faster when the statistic + is vectorized, but memory usage scales linearly with the batch size. + Default is ``None``, which processes all resamples in a single batch. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator used to perform resampling. + + If `rng` is passed by keyword to the initializer or the `rng` attribute is used + directly, types other than `numpy.random.Generator` are passed to + `numpy.random.default_rng` to instantiate a ``Generator`` before use. + If `rng` is already a ``Generator`` instance, then the provided instance is + used. Specify `rng` for repeatable behavior. + + If this argument is passed by position, if `random_state` is passed by keyword + into the initializer, or if the `random_state` attribute is used directly, + legacy behavior for `random_state` applies: + + - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState` + singleton is used. + - If `random_state` is an int, a new ``RandomState`` instance is used, + seeded with `random_state`. + - If `random_state` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this attribute name was changed from + `random_state` to `rng`. For an interim period, both names will continue to + work, although only one may be specified at a time. After the interim + period, uses of `random_state` will emit warnings. The behavior of both + `random_state` and `rng` are outlined above, but only `rng` should be used + in new code. + + """ + rng: object # type: ignore[misc] + _rng: object = field(init=False, repr=False, default=None) # type: ignore[assignment] + + @property + def random_state(self): + # Uncomment in SciPy 1.17.0 + # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2) + return self._random_state + + @random_state.setter + def random_state(self, val): + # Uncomment in SciPy 1.17.0 + # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2) + self._random_state = val + + @property # type: ignore[no-redef] + def rng(self): # noqa: F811 + return self._rng + + def __init__(self, n_resamples=9999, batch=None, random_state=None, *, rng=None): + # Uncomment in SciPy 1.17.0 + # warnings.warn(_rs_deprecation.replace('attribute', 'argument'), + # DeprecationWarning, stacklevel=2) + self._rng = rng + self._random_state = random_state + super().__init__(n_resamples=n_resamples, batch=batch) + + def _asdict(self): + # `dataclasses.asdict` deepcopies; we don't want that. + d = dict(n_resamples=self.n_resamples, batch=self.batch) + if self.rng is not None: + d['rng'] = self.rng + if self.random_state is not None: + d['random_state'] = self.random_state + return d + + +@dataclass +class BootstrapMethod(ResamplingMethod): + """Configuration information for a bootstrap confidence interval. + + Instances of this class can be passed into the `method` parameter of some + confidence interval methods to generate a bootstrap confidence interval. + + Attributes + ---------- + n_resamples : int, optional + The number of resamples to perform. Default is 9999. + batch : int, optional + The number of resamples to process in each vectorized call to + the statistic. Batch sizes >>1 tend to be faster when the statistic + is vectorized, but memory usage scales linearly with the batch size. + Default is ``None``, which processes all resamples in a single batch. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator used to perform resampling. + + If `rng` is passed by keyword to the initializer or the `rng` attribute is used + directly, types other than `numpy.random.Generator` are passed to + `numpy.random.default_rng` to instantiate a ``Generator`` before use. + If `rng` is already a ``Generator`` instance, then the provided instance is + used. Specify `rng` for repeatable behavior. + + If this argument is passed by position, if `random_state` is passed by keyword + into the initializer, or if the `random_state` attribute is used directly, + legacy behavior for `random_state` applies: + + - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState` + singleton is used. + - If `random_state` is an int, a new ``RandomState`` instance is used, + seeded with `random_state`. + - If `random_state` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this attribute name was changed from + `random_state` to `rng`. For an interim period, both names will continue to + work, although only one may be specified at a time. After the interim + period, uses of `random_state` will emit warnings. The behavior of both + `random_state` and `rng` are outlined above, but only `rng` should be used + in new code. + + method : {'BCa', 'percentile', 'basic'} + Whether to use the 'percentile' bootstrap ('percentile'), the 'basic' + (AKA 'reverse') bootstrap ('basic'), or the bias-corrected and + accelerated bootstrap ('BCa', default). + + """ + rng: object # type: ignore[misc] + _rng: object = field(init=False, repr=False, default=None) # type: ignore[assignment] + method: str = 'BCa' + + @property + def random_state(self): + # Uncomment in SciPy 1.17.0 + # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2) + return self._random_state + + @random_state.setter + def random_state(self, val): + # Uncomment in SciPy 1.17.0 + # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2) + self._random_state = val + + @property # type: ignore[no-redef] + def rng(self): # noqa: F811 + return self._rng + + def __init__(self, n_resamples=9999, batch=None, random_state=None, + method='BCa', *, rng=None): + # Uncomment in SciPy 1.17.0 + # warnings.warn(_rs_deprecation.replace('attribute', 'argument'), + # DeprecationWarning, stacklevel=2) + self._rng = rng # don't validate with `default_rng` + self._random_state = random_state + self.method = method + super().__init__(n_resamples=n_resamples, batch=batch) + + def _asdict(self): + # `dataclasses.asdict` deepcopies; we don't want that. + d = dict(n_resamples=self.n_resamples, batch=self.batch, + method=self.method) + if self.rng is not None: + d['rng'] = self.rng + if self.random_state is not None: + d['random_state'] = self.random_state + return d diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_result_classes.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_result_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..975af9310efb0c9a414439fd8d531fb95c988951 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_result_classes.py @@ -0,0 +1,40 @@ +# This module exists only to allow Sphinx to generate docs +# for the result objects returned by some functions in stats +# _without_ adding them to the main stats documentation page. + +""" +Result classes +-------------- + +.. currentmodule:: scipy.stats._result_classes + +.. autosummary:: + :toctree: generated/ + + RelativeRiskResult + BinomTestResult + TukeyHSDResult + DunnettResult + PearsonRResult + FitResult + OddsRatioResult + TtestResult + ECDFResult + EmpiricalDistributionFunction + +""" + +__all__ = ['BinomTestResult', 'RelativeRiskResult', 'TukeyHSDResult', + 'PearsonRResult', 'FitResult', 'OddsRatioResult', + 'TtestResult', 'DunnettResult', 'ECDFResult', + 'EmpiricalDistributionFunction'] + + +from ._binomtest import BinomTestResult +from ._odds_ratio import OddsRatioResult +from ._relative_risk import RelativeRiskResult +from ._hypotests import TukeyHSDResult +from ._multicomp import DunnettResult +from ._stats_py import PearsonRResult, TtestResult +from ._fit import FitResult +from ._survival import ECDFResult, EmpiricalDistributionFunction diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sampling.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..44143985a88738c43984347b7787279348fac7f4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sampling.py @@ -0,0 +1,1314 @@ +import math +import numbers +import numpy as np +from scipy import stats +from scipy import special as sc +from ._qmc import (check_random_state as check_random_state_qmc, + Halton, QMCEngine) +from ._unuran.unuran_wrapper import NumericalInversePolynomial +from scipy._lib._util import check_random_state + + +__all__ = ['FastGeneratorInversion', 'RatioUniforms'] + + +# define pdfs and other helper functions to create the generators + +def argus_pdf(x, chi): + # approach follows Baumgarten/Hoermann: Generating ARGUS random variates + # for chi > 5, use relationship of the ARGUS distribution to Gamma(1.5) + if chi <= 5: + y = 1 - x * x + return x * math.sqrt(y) * math.exp(-0.5 * chi**2 * y) + return math.sqrt(x) * math.exp(-x) + + +def argus_gamma_trf(x, chi): + if chi <= 5: + return x + return np.sqrt(1.0 - 2 * x / chi**2) + + +def argus_gamma_inv_trf(x, chi): + if chi <= 5: + return x + return 0.5 * chi**2 * (1 - x**2) + + +def betaprime_pdf(x, a, b): + if x > 0: + logf = (a - 1) * math.log(x) - (a + b) * math.log1p(x) - sc.betaln(a, b) + return math.exp(logf) + else: + # return pdf at x == 0 separately to avoid runtime warnings + if a > 1: + return 0 + elif a < 1: + return np.inf + else: + return 1 / sc.beta(a, b) + + +def beta_valid_params(a, b): + return (min(a, b) >= 0.1) and (max(a, b) <= 700) + + +def gamma_pdf(x, a): + if x > 0: + return math.exp(-math.lgamma(a) + (a - 1.0) * math.log(x) - x) + else: + return 0 if a >= 1 else np.inf + + +def invgamma_pdf(x, a): + if x > 0: + return math.exp(-(a + 1.0) * math.log(x) - math.lgamma(a) - 1 / x) + else: + return 0 if a >= 1 else np.inf + + +def burr_pdf(x, cc, dd): + # note: we use np.exp instead of math.exp, otherwise an overflow + # error can occur in the setup, e.g., for parameters + # 1.89128135, 0.30195177, see test test_burr_overflow + if x > 0: + lx = math.log(x) + return np.exp(-(cc + 1) * lx - (dd + 1) * math.log1p(np.exp(-cc * lx))) + else: + return 0 + + +def burr12_pdf(x, cc, dd): + if x > 0: + lx = math.log(x) + logterm = math.log1p(math.exp(cc * lx)) + return math.exp((cc - 1) * lx - (dd + 1) * logterm + math.log(cc * dd)) + else: + return 0 + + +def chi_pdf(x, a): + if x > 0: + return math.exp( + (a - 1) * math.log(x) + - 0.5 * (x * x) + - (a / 2 - 1) * math.log(2) + - math.lgamma(0.5 * a) + ) + else: + return 0 if a >= 1 else np.inf + + +def chi2_pdf(x, df): + if x > 0: + return math.exp( + (df / 2 - 1) * math.log(x) + - 0.5 * x + - (df / 2) * math.log(2) + - math.lgamma(0.5 * df) + ) + else: + return 0 if df >= 1 else np.inf + + +def alpha_pdf(x, a): + if x > 0: + return math.exp(-2.0 * math.log(x) - 0.5 * (a - 1.0 / x) ** 2) + return 0.0 + + +def bradford_pdf(x, c): + if 0 <= x <= 1: + return 1.0 / (1.0 + c * x) + return 0.0 + + +def crystalball_pdf(x, b, m): + if x > -b: + return math.exp(-0.5 * x * x) + return math.exp(m * math.log(m / b) - 0.5 * b * b - m * math.log(m / b - b - x)) + + +def weibull_min_pdf(x, c): + if x > 0: + return c * math.exp((c - 1) * math.log(x) - x**c) + return 0.0 + + +def weibull_max_pdf(x, c): + if x < 0: + return c * math.exp((c - 1) * math.log(-x) - ((-x) ** c)) + return 0.0 + + +def invweibull_pdf(x, c): + if x > 0: + return c * math.exp(-(c + 1) * math.log(x) - x ** (-c)) + return 0.0 + + +def wald_pdf(x): + if x > 0: + return math.exp(-((x - 1) ** 2) / (2 * x)) / math.sqrt(x**3) + return 0.0 + + +def geninvgauss_mode(p, b): + if p > 1: # equivalent mode formulas numerical more stable versions + return (math.sqrt((1 - p) ** 2 + b**2) - (1 - p)) / b + return b / (math.sqrt((1 - p) ** 2 + b**2) + (1 - p)) + + +def geninvgauss_pdf(x, p, b): + m = geninvgauss_mode(p, b) + lfm = (p - 1) * math.log(m) - 0.5 * b * (m + 1 / m) + if x > 0: + return math.exp((p - 1) * math.log(x) - 0.5 * b * (x + 1 / x) - lfm) + return 0.0 + + +def invgauss_mode(mu): + return 1.0 / (math.sqrt(1.5 * 1.5 + 1 / (mu * mu)) + 1.5) + + +def invgauss_pdf(x, mu): + m = invgauss_mode(mu) + lfm = -1.5 * math.log(m) - (m - mu) ** 2 / (2 * m * mu**2) + if x > 0: + return math.exp(-1.5 * math.log(x) - (x - mu) ** 2 / (2 * x * mu**2) - lfm) + return 0.0 + + +def powerlaw_pdf(x, a): + if x > 0: + return x ** (a - 1) + return 0.0 + + +# Define a dictionary: for a given distribution (keys), another dictionary +# (values) specifies the parameters for NumericalInversePolynomial (PINV). +# The keys of the latter dictionary are: +# - pdf: the pdf of the distribution (callable). The signature of the pdf +# is float -> float (i.e., the function does not have to be vectorized). +# If possible, functions like log or exp from the module math should be +# preferred over functions from numpy since the PINV setup will be faster +# in that case. +# - check_pinv_params: callable f that returns true if the shape parameters +# (args) are recommended parameters for PINV (i.e., the u-error does +# not exceed the default tolerance) +# - center: scalar if the center does not depend on args, otherwise +# callable that returns the center as a function of the shape parameters +# - rvs_transform: a callable that can be used to transform the rvs that +# are distributed according to the pdf to the target distribution +# (as an example, see the entry for the beta distribution) +# - rvs_transform_inv: the inverse of rvs_transform (it is required +# for the transformed ppf) +# - mirror_uniform: boolean or a callable that returns true or false +# depending on the shape parameters. If True, the ppf is applied +# to 1-u instead of u to generate rvs, where u is a uniform rv. +# While both u and 1-u are uniform, it can be required to use 1-u +# to compute the u-error correctly. This is only relevant for the argus +# distribution. +# The only required keys are "pdf" and "check_pinv_params". +# All other keys are optional. + +PINV_CONFIG = { + "alpha": { + "pdf": alpha_pdf, + "check_pinv_params": lambda a: 1.0e-11 <= a < 2.1e5, + "center": lambda a: 0.25 * (math.sqrt(a * a + 8.0) - a), + }, + "anglit": { + "pdf": lambda x: math.cos(2 * x) + 1.0e-13, + # +1.e-13 is necessary, otherwise PINV has strange problems as + # f(upper border) is very close to 0 + "center": 0, + }, + "argus": { + "pdf": argus_pdf, + "center": lambda chi: 0.7 if chi <= 5 else 0.5, + "check_pinv_params": lambda chi: 1e-20 < chi < 901, + "rvs_transform": argus_gamma_trf, + "rvs_transform_inv": argus_gamma_inv_trf, + "mirror_uniform": lambda chi: chi > 5, + }, + "beta": { + "pdf": betaprime_pdf, + "center": lambda a, b: max(0.1, (a - 1) / (b + 1)), + "check_pinv_params": beta_valid_params, + "rvs_transform": lambda x, *args: x / (1 + x), + "rvs_transform_inv": lambda x, *args: x / (1 - x) if x < 1 else np.inf, + }, + "betaprime": { + "pdf": betaprime_pdf, + "center": lambda a, b: max(0.1, (a - 1) / (b + 1)), + "check_pinv_params": beta_valid_params, + }, + "bradford": { + "pdf": bradford_pdf, + "check_pinv_params": lambda a: 1.0e-6 <= a <= 1e9, + "center": 0.5, + }, + "burr": { + "pdf": burr_pdf, + "center": lambda a, b: (2 ** (1 / b) - 1) ** (-1 / a), + "check_pinv_params": lambda a, b: (min(a, b) >= 0.3) and (max(a, b) <= 50), + }, + "burr12": { + "pdf": burr12_pdf, + "center": lambda a, b: (2 ** (1 / b) - 1) ** (1 / a), + "check_pinv_params": lambda a, b: (min(a, b) >= 0.2) and (max(a, b) <= 50), + }, + "cauchy": { + "pdf": lambda x: 1 / (1 + (x * x)), + "center": 0, + }, + "chi": { + "pdf": chi_pdf, + "check_pinv_params": lambda df: 0.05 <= df <= 1.0e6, + "center": lambda a: math.sqrt(a), + }, + "chi2": { + "pdf": chi2_pdf, + "check_pinv_params": lambda df: 0.07 <= df <= 1e6, + "center": lambda a: a, + }, + "cosine": { + "pdf": lambda x: 1 + math.cos(x), + "center": 0, + }, + "crystalball": { + "pdf": crystalball_pdf, + "check_pinv_params": lambda b, m: (0.01 <= b <= 5.5) + and (1.1 <= m <= 75.1), + "center": 0.0, + }, + "expon": { + "pdf": lambda x: math.exp(-x), + "center": 1.0, + }, + "gamma": { + "pdf": gamma_pdf, + "check_pinv_params": lambda a: 0.04 <= a <= 1e6, + "center": lambda a: a, + }, + "gennorm": { + "pdf": lambda x, b: math.exp(-abs(x) ** b), + "check_pinv_params": lambda b: 0.081 <= b <= 45.0, + "center": 0.0, + }, + "geninvgauss": { + "pdf": geninvgauss_pdf, + "check_pinv_params": lambda p, b: (abs(p) <= 1200.0) + and (1.0e-10 <= b <= 1200.0), + "center": geninvgauss_mode, + }, + "gumbel_l": { + "pdf": lambda x: math.exp(x - math.exp(x)), + "center": -0.6, + }, + "gumbel_r": { + "pdf": lambda x: math.exp(-x - math.exp(-x)), + "center": 0.6, + }, + "hypsecant": { + "pdf": lambda x: 1.0 / (math.exp(x) + math.exp(-x)), + "center": 0.0, + }, + "invgamma": { + "pdf": invgamma_pdf, + "check_pinv_params": lambda a: 0.04 <= a <= 1e6, + "center": lambda a: 1 / a, + }, + "invgauss": { + "pdf": invgauss_pdf, + "check_pinv_params": lambda mu: 1.0e-10 <= mu <= 1.0e9, + "center": invgauss_mode, + }, + "invweibull": { + "pdf": invweibull_pdf, + "check_pinv_params": lambda a: 0.12 <= a <= 512, + "center": 1.0, + }, + "laplace": { + "pdf": lambda x: math.exp(-abs(x)), + "center": 0.0, + }, + "logistic": { + "pdf": lambda x: math.exp(-x) / (1 + math.exp(-x)) ** 2, + "center": 0.0, + }, + "maxwell": { + "pdf": lambda x: x * x * math.exp(-0.5 * x * x), + "center": 1.41421, + }, + "moyal": { + "pdf": lambda x: math.exp(-(x + math.exp(-x)) / 2), + "center": 1.2, + }, + "norm": { + "pdf": lambda x: math.exp(-x * x / 2), + "center": 0.0, + }, + "pareto": { + "pdf": lambda x, b: x ** -(b + 1), + "center": lambda b: b / (b - 1) if b > 2 else 1.5, + "check_pinv_params": lambda b: 0.08 <= b <= 400000, + }, + "powerlaw": { + "pdf": powerlaw_pdf, + "center": 1.0, + "check_pinv_params": lambda a: 0.06 <= a <= 1.0e5, + }, + "t": { + "pdf": lambda x, df: (1 + x * x / df) ** (-0.5 * (df + 1)), + "check_pinv_params": lambda a: 0.07 <= a <= 1e6, + "center": 0.0, + }, + "rayleigh": { + "pdf": lambda x: x * math.exp(-0.5 * (x * x)), + "center": 1.0, + }, + "semicircular": { + "pdf": lambda x: math.sqrt(1.0 - (x * x)), + "center": 0, + }, + "wald": { + "pdf": wald_pdf, + "center": 1.0, + }, + "weibull_max": { + "pdf": weibull_max_pdf, + "check_pinv_params": lambda a: 0.25 <= a <= 512, + "center": -1.0, + }, + "weibull_min": { + "pdf": weibull_min_pdf, + "check_pinv_params": lambda a: 0.25 <= a <= 512, + "center": 1.0, + }, +} + + +def _validate_qmc_input(qmc_engine, d, seed): + # Input validation for `qmc_engine` and `d` + # Error messages for invalid `d` are raised by QMCEngine + # we could probably use a stats.qmc.check_qrandom_state + if isinstance(qmc_engine, QMCEngine): + if d is not None and qmc_engine.d != d: + message = "`d` must be consistent with dimension of `qmc_engine`." + raise ValueError(message) + d = qmc_engine.d if d is None else d + elif qmc_engine is None: + d = 1 if d is None else d + qmc_engine = Halton(d, seed=seed) + else: + message = ( + "`qmc_engine` must be an instance of " + "`scipy.stats.qmc.QMCEngine` or `None`." + ) + raise ValueError(message) + + return qmc_engine, d + + +class CustomDistPINV: + def __init__(self, pdf, args): + self._pdf = lambda x: pdf(x, *args) + + def pdf(self, x): + return self._pdf(x) + + +class FastGeneratorInversion: + """ + Fast sampling by numerical inversion of the CDF for a large class of + continuous distributions in `scipy.stats`. + + Parameters + ---------- + dist : rv_frozen object + Frozen distribution object from `scipy.stats`. The list of supported + distributions can be found in the Notes section. The shape parameters, + `loc` and `scale` used to create the distributions must be scalars. + For example, for the Gamma distribution with shape parameter `p`, + `p` has to be a float, and for the beta distribution with shape + parameters (a, b), both a and b have to be floats. + domain : tuple of floats, optional + If one wishes to sample from a truncated/conditional distribution, + the domain has to be specified. + The default is None. In that case, the random variates are not + truncated, and the domain is inferred from the support of the + distribution. + ignore_shape_range : boolean, optional. + If False, shape parameters that are outside of the valid range + of values to ensure that the numerical accuracy (see Notes) is + high, raise a ValueError. If True, any shape parameters that are valid + for the distribution are accepted. This can be useful for testing. + The default is False. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + A NumPy random number generator or seed for the underlying NumPy + random number generator used to generate the stream of uniform + random numbers. + If `random_state` is None, it uses ``self.random_state``. + If `random_state` is an int, + ``np.random.default_rng(random_state)`` is used. + If `random_state` is already a ``Generator`` or ``RandomState`` + instance then that instance is used. + + Attributes + ---------- + loc : float + The location parameter. + random_state : {`numpy.random.Generator`, `numpy.random.RandomState`} + The random state used in relevant methods like `rvs` (unless + another `random_state` is passed as an argument to these methods). + scale : float + The scale parameter. + + Methods + ------- + cdf + evaluate_error + ppf + qrvs + rvs + support + + Notes + ----- + The class creates an object for continuous distributions specified + by `dist`. The method `rvs` uses a generator from + `scipy.stats.sampling` that is created when the object is instantiated. + In addition, the methods `qrvs` and `ppf` are added. + `qrvs` generate samples based on quasi-random numbers from + `scipy.stats.qmc`. `ppf` is the PPF based on the + numerical inversion method in [1]_ (`NumericalInversePolynomial`) that is + used to generate random variates. + + Supported distributions (`distname`) are: + ``alpha``, ``anglit``, ``argus``, ``beta``, ``betaprime``, ``bradford``, + ``burr``, ``burr12``, ``cauchy``, ``chi``, ``chi2``, ``cosine``, + ``crystalball``, ``expon``, ``gamma``, ``gennorm``, ``geninvgauss``, + ``gumbel_l``, ``gumbel_r``, ``hypsecant``, ``invgamma``, ``invgauss``, + ``invweibull``, ``laplace``, ``logistic``, ``maxwell``, ``moyal``, + ``norm``, ``pareto``, ``powerlaw``, ``t``, ``rayleigh``, ``semicircular``, + ``wald``, ``weibull_max``, ``weibull_min``. + + `rvs` relies on the accuracy of the numerical inversion. If very extreme + shape parameters are used, the numerical inversion might not work. However, + for all implemented distributions, the admissible shape parameters have + been tested, and an error will be raised if the user supplies values + outside of the allowed range. The u-error should not exceed 1e-10 for all + valid parameters. Note that warnings might be raised even if parameters + are within the valid range when the object is instantiated. + To check numerical accuracy, the method `evaluate_error` can be used. + + Note that all implemented distributions are also part of `scipy.stats`, and + the object created by `FastGeneratorInversion` relies on methods like + `ppf`, `cdf` and `pdf` from `rv_frozen`. The main benefit of using this + class can be summarized as follows: Once the generator to sample random + variates is created in the setup step, sampling and evaluation of + the PPF using `ppf` are very fast, + and performance is essentially independent of the distribution. Therefore, + a substantial speed-up can be achieved for many distributions if large + numbers of random variates are required. It is important to know that this + fast sampling is achieved by inversion of the CDF. Thus, one uniform + random variate is transformed into a non-uniform variate, which is an + advantage for several simulation methods, e.g., when + the variance reduction methods of common random variates or + antithetic variates are be used ([2]_). + + In addition, inversion makes it possible to + - to use a QMC generator from `scipy.stats.qmc` (method `qrvs`), + - to generate random variates truncated to an interval. For example, if + one aims to sample standard normal random variates from + the interval (2, 4), this can be easily achieved by using the parameter + `domain`. + + The location and scale that are initially defined by `dist` + can be reset without having to rerun the setup + step to create the generator that is used for sampling. The relation + of the distribution `Y` with `loc` and `scale` to the standard + distribution `X` (i.e., ``loc=0`` and ``scale=1``) is given by + ``Y = loc + scale * X``. + + References + ---------- + .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold. + "Random variate generation by numerical inversion when only the + density is known." ACM Transactions on Modeling and Computer + Simulation (TOMACS) 20.4 (2010): 1-25. + .. [2] Hörmann, Wolfgang, Josef Leydold and Gerhard Derflinger. + "Automatic nonuniform random number generation." + Springer, 2004. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> from scipy.stats.sampling import FastGeneratorInversion + + Let's start with a simple example to illustrate the main features: + + >>> gamma_frozen = stats.gamma(1.5) + >>> gamma_dist = FastGeneratorInversion(gamma_frozen) + >>> r = gamma_dist.rvs(size=1000) + + The mean should be approximately equal to the shape parameter 1.5: + + >>> r.mean() + 1.52423591130436 # may vary + + Similarly, we can draw a sample based on quasi-random numbers: + + >>> r = gamma_dist.qrvs(size=1000) + >>> r.mean() + 1.4996639255942914 # may vary + + Compare the PPF against approximation `ppf`. + + >>> q = [0.001, 0.2, 0.5, 0.8, 0.999] + >>> np.max(np.abs(gamma_frozen.ppf(q) - gamma_dist.ppf(q))) + 4.313394796895409e-08 + + To confirm that the numerical inversion is accurate, we evaluate the + approximation error (u-error), which should be below 1e-10 (for more + details, refer to the documentation of `evaluate_error`): + + >>> gamma_dist.evaluate_error() + (7.446320551265581e-11, nan) # may vary + + Note that the location and scale can be changed without instantiating a + new generator: + + >>> gamma_dist.loc = 2 + >>> gamma_dist.scale = 3 + >>> r = gamma_dist.rvs(size=1000) + + The mean should be approximately 2 + 3*1.5 = 6.5. + + >>> r.mean() + 6.399549295242894 # may vary + + Let us also illustrate how truncation can be applied: + + >>> trunc_norm = FastGeneratorInversion(stats.norm(), domain=(3, 4)) + >>> r = trunc_norm.rvs(size=1000) + >>> 3 < r.min() < r.max() < 4 + True + + Check the mean: + + >>> r.mean() + 3.250433367078603 # may vary + + >>> stats.norm.expect(lb=3, ub=4, conditional=True) + 3.260454285589997 + + In this particular, case, `scipy.stats.truncnorm` could also be used to + generate truncated normal random variates. + + """ + + def __init__( + self, + dist, + *, + domain=None, + ignore_shape_range=False, + random_state=None, + ): + + if isinstance(dist, stats.distributions.rv_frozen): + distname = dist.dist.name + if distname not in PINV_CONFIG.keys(): + raise ValueError( + f"Distribution '{distname}' is not supported." + f"It must be one of {list(PINV_CONFIG.keys())}" + ) + else: + raise ValueError("`dist` must be a frozen distribution object") + + loc = dist.kwds.get("loc", 0) + scale = dist.kwds.get("scale", 1) + args = dist.args + if not np.isscalar(loc): + raise ValueError("loc must be scalar.") + if not np.isscalar(scale): + raise ValueError("scale must be scalar.") + + self._frozendist = getattr(stats, distname)( + *args, + loc=loc, + scale=scale, + ) + self._distname = distname + + nargs = np.broadcast_arrays(args)[0].size + nargs_expected = self._frozendist.dist.numargs + if nargs != nargs_expected: + raise ValueError( + f"Each of the {nargs_expected} shape parameters must be a " + f"scalar, but {nargs} values are provided." + ) + + self.random_state = random_state + + if domain is None: + self._domain = self._frozendist.support() + self._p_lower = 0.0 + self._p_domain = 1.0 + else: + self._domain = domain + self._p_lower = self._frozendist.cdf(self._domain[0]) + _p_domain = self._frozendist.cdf(self._domain[1]) - self._p_lower + self._p_domain = _p_domain + self._set_domain_adj() + self._ignore_shape_range = ignore_shape_range + + # the domain to be passed to NumericalInversePolynomial + # define a separate variable since in case of a transformation, + # domain_pinv will not be the same as self._domain + self._domain_pinv = self._domain + + # get information about the distribution from the config to set up + # the generator + dist = self._process_config(distname, args) + + if self._rvs_transform_inv is not None: + d0 = self._rvs_transform_inv(self._domain[0], *args) + d1 = self._rvs_transform_inv(self._domain[1], *args) + if d0 > d1: + # swap values if transformation if decreasing + d0, d1 = d1, d0 + # only update _domain_pinv and not _domain + # _domain refers to the original distribution, _domain_pinv + # to the transformed distribution + self._domain_pinv = d0, d1 + + # self._center has been set by the call self._process_config + # check if self._center is inside the transformed domain + # _domain_pinv, otherwise move it to the endpoint that is closer + if self._center is not None: + if self._center < self._domain_pinv[0]: + self._center = self._domain_pinv[0] + elif self._center > self._domain_pinv[1]: + self._center = self._domain_pinv[1] + + self._rng = NumericalInversePolynomial( + dist, + random_state=self.random_state, + domain=self._domain_pinv, + center=self._center, + ) + + @property + def random_state(self): + return self._random_state + + @random_state.setter + def random_state(self, random_state): + self._random_state = check_random_state_qmc(random_state) + + @property + def loc(self): + return self._frozendist.kwds.get("loc", 0) + + @loc.setter + def loc(self, loc): + if not np.isscalar(loc): + raise ValueError("loc must be scalar.") + self._frozendist.kwds["loc"] = loc + # update the adjusted domain that depends on loc and scale + self._set_domain_adj() + + @property + def scale(self): + return self._frozendist.kwds.get("scale", 0) + + @scale.setter + def scale(self, scale): + if not np.isscalar(scale): + raise ValueError("scale must be scalar.") + self._frozendist.kwds["scale"] = scale + # update the adjusted domain that depends on loc and scale + self._set_domain_adj() + + def _set_domain_adj(self): + """ Adjust the domain based on loc and scale. """ + loc = self.loc + scale = self.scale + lb = self._domain[0] * scale + loc + ub = self._domain[1] * scale + loc + self._domain_adj = (lb, ub) + + def _process_config(self, distname, args): + cfg = PINV_CONFIG[distname] + if "check_pinv_params" in cfg: + if not self._ignore_shape_range: + if not cfg["check_pinv_params"](*args): + msg = ("No generator is defined for the shape parameters " + f"{args}. Use ignore_shape_range to proceed " + "with the selected values.") + raise ValueError(msg) + + if "center" in cfg.keys(): + if not np.isscalar(cfg["center"]): + self._center = cfg["center"](*args) + else: + self._center = cfg["center"] + else: + self._center = None + self._rvs_transform = cfg.get("rvs_transform", None) + self._rvs_transform_inv = cfg.get("rvs_transform_inv", None) + _mirror_uniform = cfg.get("mirror_uniform", None) + if _mirror_uniform is None: + self._mirror_uniform = False + else: + self._mirror_uniform = _mirror_uniform(*args) + + return CustomDistPINV(cfg["pdf"], args) + + def rvs(self, size=None): + """ + Sample from the distribution by inversion. + + Parameters + ---------- + size : int or tuple, optional + The shape of samples. Default is ``None`` in which case a scalar + sample is returned. + + Returns + ------- + rvs : array_like + A NumPy array of random variates. + + Notes + ----- + Random variates are generated by numerical inversion of the CDF, i.e., + `ppf` computed by `NumericalInversePolynomial` when the class + is instantiated. Note that the + default ``rvs`` method of the rv_continuous class is + overwritten. Hence, a different stream of random numbers is generated + even if the same seed is used. + """ + # note: we cannot use self._rng.rvs directly in case + # self._mirror_uniform is true + u = self.random_state.uniform(size=size) + if self._mirror_uniform: + u = 1 - u + r = self._rng.ppf(u) + if self._rvs_transform is not None: + r = self._rvs_transform(r, *self._frozendist.args) + return self.loc + self.scale * r + + def ppf(self, q): + """ + Very fast PPF (inverse CDF) of the distribution which + is a very close approximation of the exact PPF values. + + Parameters + ---------- + u : array_like + Array with probabilities. + + Returns + ------- + ppf : array_like + Quantiles corresponding to the values in `u`. + + Notes + ----- + The evaluation of the PPF is very fast but it may have a large + relative error in the far tails. The numerical precision of the PPF + is controlled by the u-error, that is, + ``max |u - CDF(PPF(u))|`` where the max is taken over points in + the interval [0,1], see `evaluate_error`. + + Note that this PPF is designed to generate random samples. + """ + q = np.asarray(q) + if self._mirror_uniform: + x = self._rng.ppf(1 - q) + else: + x = self._rng.ppf(q) + if self._rvs_transform is not None: + x = self._rvs_transform(x, *self._frozendist.args) + return self.scale * x + self.loc + + def qrvs(self, size=None, d=None, qmc_engine=None): + """ + Quasi-random variates of the given distribution. + + The `qmc_engine` is used to draw uniform quasi-random variates, and + these are converted to quasi-random variates of the given distribution + using inverse transform sampling. + + Parameters + ---------- + size : int, tuple of ints, or None; optional + Defines shape of random variates array. Default is ``None``. + d : int or None, optional + Defines dimension of uniform quasi-random variates to be + transformed. Default is ``None``. + qmc_engine : scipy.stats.qmc.QMCEngine(d=1), optional + Defines the object to use for drawing + quasi-random variates. Default is ``None``, which uses + `scipy.stats.qmc.Halton(1)`. + + Returns + ------- + rvs : ndarray or scalar + Quasi-random variates. See Notes for shape information. + + Notes + ----- + The shape of the output array depends on `size`, `d`, and `qmc_engine`. + The intent is for the interface to be natural, but the detailed rules + to achieve this are complicated. + + - If `qmc_engine` is ``None``, a `scipy.stats.qmc.Halton` instance is + created with dimension `d`. If `d` is not provided, ``d=1``. + - If `qmc_engine` is not ``None`` and `d` is ``None``, `d` is + determined from the dimension of the `qmc_engine`. + - If `qmc_engine` is not ``None`` and `d` is not ``None`` but the + dimensions are inconsistent, a ``ValueError`` is raised. + - After `d` is determined according to the rules above, the output + shape is ``tuple_shape + d_shape``, where: + + - ``tuple_shape = tuple()`` if `size` is ``None``, + - ``tuple_shape = (size,)`` if `size` is an ``int``, + - ``tuple_shape = size`` if `size` is a sequence, + - ``d_shape = tuple()`` if `d` is ``None`` or `d` is 1, and + - ``d_shape = (d,)`` if `d` is greater than 1. + + The elements of the returned array are part of a low-discrepancy + sequence. If `d` is 1, this means that none of the samples are truly + independent. If `d` > 1, each slice ``rvs[..., i]`` will be of a + quasi-independent sequence; see `scipy.stats.qmc.QMCEngine` for + details. Note that when `d` > 1, the samples returned are still those + of the provided univariate distribution, not a multivariate + generalization of that distribution. + + """ + qmc_engine, d = _validate_qmc_input(qmc_engine, d, self.random_state) + # mainly copied from unuran_wrapper.pyx.templ + # `rvs` is flexible about whether `size` is an int or tuple, so this + # should be, too. + try: + if size is None: + tuple_size = (1,) + else: + tuple_size = tuple(size) + except TypeError: + tuple_size = (size,) + # we do not use rng.qrvs directly since we need to be + # able to apply the ppf to 1 - u + N = 1 if size is None else np.prod(size) + u = qmc_engine.random(N) + if self._mirror_uniform: + u = 1 - u + qrvs = self._ppf(u) + if self._rvs_transform is not None: + qrvs = self._rvs_transform(qrvs, *self._frozendist.args) + if size is None: + qrvs = qrvs.squeeze()[()] + else: + if d == 1: + qrvs = qrvs.reshape(tuple_size) + else: + qrvs = qrvs.reshape(tuple_size + (d,)) + return self.loc + self.scale * qrvs + + def evaluate_error(self, size=100000, random_state=None, x_error=False): + """ + Evaluate the numerical accuracy of the inversion (u- and x-error). + + Parameters + ---------- + size : int, optional + The number of random points over which the error is estimated. + Default is ``100000``. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + A NumPy random number generator or seed for the underlying NumPy + random number generator used to generate the stream of uniform + random numbers. + If `random_state` is None, use ``self.random_state``. + If `random_state` is an int, + ``np.random.default_rng(random_state)`` is used. + If `random_state` is already a ``Generator`` or ``RandomState`` + instance then that instance is used. + + Returns + ------- + u_error, x_error : tuple of floats + A NumPy array of random variates. + + Notes + ----- + The numerical precision of the inverse CDF `ppf` is controlled by + the u-error. It is computed as follows: + ``max |u - CDF(PPF(u))|`` where the max is taken `size` random + points in the interval [0,1]. `random_state` determines the random + sample. Note that if `ppf` was exact, the u-error would be zero. + + The x-error measures the direct distance between the exact PPF + and `ppf`. If ``x_error`` is set to ``True`, it is + computed as the maximum of the minimum of the relative and absolute + x-error: + ``max(min(x_error_abs[i], x_error_rel[i]))`` where + ``x_error_abs[i] = |PPF(u[i]) - PPF_fast(u[i])|``, + ``x_error_rel[i] = max |(PPF(u[i]) - PPF_fast(u[i])) / PPF(u[i])|``. + Note that it is important to consider the relative x-error in the case + that ``PPF(u)`` is close to zero or very large. + + By default, only the u-error is evaluated and the x-error is set to + ``np.nan``. Note that the evaluation of the x-error will be very slow + if the implementation of the PPF is slow. + + Further information about these error measures can be found in [1]_. + + References + ---------- + .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold. + "Random variate generation by numerical inversion when only the + density is known." ACM Transactions on Modeling and Computer + Simulation (TOMACS) 20.4 (2010): 1-25. + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> from scipy.stats.sampling import FastGeneratorInversion + + Create an object for the normal distribution: + + >>> d_norm_frozen = stats.norm() + >>> d_norm = FastGeneratorInversion(d_norm_frozen) + + To confirm that the numerical inversion is accurate, we evaluate the + approximation error (u-error and x-error). + + >>> u_error, x_error = d_norm.evaluate_error(x_error=True) + + The u-error should be below 1e-10: + + >>> u_error + 8.785783212061915e-11 # may vary + + Compare the PPF against approximation `ppf`: + + >>> q = [0.001, 0.2, 0.4, 0.6, 0.8, 0.999] + >>> diff = np.abs(d_norm_frozen.ppf(q) - d_norm.ppf(q)) + >>> x_error_abs = np.max(diff) + >>> x_error_abs + 1.2937954707581412e-08 + + This is the absolute x-error evaluated at the points q. The relative + error is given by + + >>> x_error_rel = np.max(diff / np.abs(d_norm_frozen.ppf(q))) + >>> x_error_rel + 4.186725600453555e-09 + + The x_error computed above is derived in a very similar way over a + much larger set of random values q. At each value q[i], the minimum + of the relative and absolute error is taken. The final value is then + derived as the maximum of these values. In our example, we get the + following value: + + >>> x_error + 4.507068014335139e-07 # may vary + + """ + if not isinstance(size, (numbers.Integral, np.integer)): + raise ValueError("size must be an integer.") + # urng will be used to draw the samples for testing the error + # it must not interfere with self.random_state. therefore, do not + # call self.rvs, but draw uniform random numbers and apply + # self.ppf (note: like in rvs, consider self._mirror_uniform) + urng = check_random_state_qmc(random_state) + u = urng.uniform(size=size) + if self._mirror_uniform: + u = 1 - u + x = self.ppf(u) + uerr = np.max(np.abs(self._cdf(x) - u)) + if not x_error: + return uerr, np.nan + ppf_u = self._ppf(u) + x_error_abs = np.abs(self.ppf(u)-ppf_u) + x_error_rel = x_error_abs / np.abs(ppf_u) + x_error_combined = np.array([x_error_abs, x_error_rel]).min(axis=0) + return uerr, np.max(x_error_combined) + + def support(self): + """Support of the distribution. + + Returns + ------- + a, b : float + end-points of the distribution's support. + + Notes + ----- + + Note that the support of the distribution depends on `loc`, + `scale` and `domain`. + + Examples + -------- + + >>> from scipy import stats + >>> from scipy.stats.sampling import FastGeneratorInversion + + Define a truncated normal distribution: + + >>> d_norm = FastGeneratorInversion(stats.norm(), domain=(0, 1)) + >>> d_norm.support() + (0, 1) + + Shift the distribution: + + >>> d_norm.loc = 2.5 + >>> d_norm.support() + (2.5, 3.5) + + """ + return self._domain_adj + + def _cdf(self, x): + """Cumulative distribution function (CDF) + + Parameters + ---------- + x : array_like + The values where the CDF is evaluated + + Returns + ------- + y : ndarray + CDF evaluated at x + + """ + y = self._frozendist.cdf(x) + if self._p_domain == 1.0: + return y + return np.clip((y - self._p_lower) / self._p_domain, 0, 1) + + def _ppf(self, q): + """Percent point function (inverse of `cdf`) + + Parameters + ---------- + q : array_like + lower tail probability + + Returns + ------- + x : array_like + quantile corresponding to the lower tail probability q. + + """ + if self._p_domain == 1.0: + return self._frozendist.ppf(q) + x = self._frozendist.ppf(self._p_domain * np.array(q) + self._p_lower) + return np.clip(x, self._domain_adj[0], self._domain_adj[1]) + + +class RatioUniforms: + """ + Generate random samples from a probability density function using the + ratio-of-uniforms method. + + Parameters + ---------- + pdf : callable + A function with signature `pdf(x)` that is proportional to the + probability density function of the distribution. + umax : float + The upper bound of the bounding rectangle in the u-direction. + vmin : float + The lower bound of the bounding rectangle in the v-direction. + vmax : float + The upper bound of the bounding rectangle in the v-direction. + c : float, optional. + Shift parameter of ratio-of-uniforms method, see Notes. Default is 0. + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Methods + ------- + rvs + + Notes + ----- + Given a univariate probability density function `pdf` and a constant `c`, + define the set ``A = {(u, v) : 0 < u <= sqrt(pdf(v/u + c))}``. + If ``(U, V)`` is a random vector uniformly distributed over ``A``, + then ``V/U + c`` follows a distribution according to `pdf`. + + The above result (see [1]_, [2]_) can be used to sample random variables + using only the PDF, i.e. no inversion of the CDF is required. Typical + choices of `c` are zero or the mode of `pdf`. The set ``A`` is a subset of + the rectangle ``R = [0, umax] x [vmin, vmax]`` where + + - ``umax = sup sqrt(pdf(x))`` + - ``vmin = inf (x - c) sqrt(pdf(x))`` + - ``vmax = sup (x - c) sqrt(pdf(x))`` + + In particular, these values are finite if `pdf` is bounded and + ``x**2 * pdf(x)`` is bounded (i.e. subquadratic tails). + One can generate ``(U, V)`` uniformly on ``R`` and return + ``V/U + c`` if ``(U, V)`` are also in ``A`` which can be directly + verified. + + The algorithm is not changed if one replaces `pdf` by k * `pdf` for any + constant k > 0. Thus, it is often convenient to work with a function + that is proportional to the probability density function by dropping + unnecessary normalization factors. + + Intuitively, the method works well if ``A`` fills up most of the + enclosing rectangle such that the probability is high that ``(U, V)`` + lies in ``A`` whenever it lies in ``R`` as the number of required + iterations becomes too large otherwise. To be more precise, note that + the expected number of iterations to draw ``(U, V)`` uniformly + distributed on ``R`` such that ``(U, V)`` is also in ``A`` is given by + the ratio ``area(R) / area(A) = 2 * umax * (vmax - vmin) / area(pdf)``, + where `area(pdf)` is the integral of `pdf` (which is equal to one if the + probability density function is used but can take on other values if a + function proportional to the density is used). The equality holds since + the area of ``A`` is equal to ``0.5 * area(pdf)`` (Theorem 7.1 in [1]_). + If the sampling fails to generate a single random variate after 50000 + iterations (i.e. not a single draw is in ``A``), an exception is raised. + + If the bounding rectangle is not correctly specified (i.e. if it does not + contain ``A``), the algorithm samples from a distribution different from + the one given by `pdf`. It is therefore recommended to perform a + test such as `~scipy.stats.kstest` as a check. + + References + ---------- + .. [1] L. Devroye, "Non-Uniform Random Variate Generation", + Springer-Verlag, 1986. + + .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian + random variates", Statistics and Computing, 24(4), p. 547--557, 2014. + + .. [3] A.J. Kinderman and J.F. Monahan, "Computer Generation of Random + Variables Using the Ratio of Uniform Deviates", + ACM Transactions on Mathematical Software, 3(3), p. 257--260, 1977. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + + >>> from scipy.stats.sampling import RatioUniforms + >>> rng = np.random.default_rng() + + Simulate normally distributed random variables. It is easy to compute the + bounding rectangle explicitly in that case. For simplicity, we drop the + normalization factor of the density. + + >>> f = lambda x: np.exp(-x**2 / 2) + >>> v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2) + >>> umax = np.sqrt(f(0)) + >>> gen = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=rng) + >>> r = gen.rvs(size=2500) + + The K-S test confirms that the random variates are indeed normally + distributed (normality is not rejected at 5% significance level): + + >>> stats.kstest(r, 'norm')[1] + 0.250634764150542 + + The exponential distribution provides another example where the bounding + rectangle can be determined explicitly. + + >>> gen = RatioUniforms(lambda x: np.exp(-x), umax=1, vmin=0, + ... vmax=2*np.exp(-1), random_state=rng) + >>> r = gen.rvs(1000) + >>> stats.kstest(r, 'expon')[1] + 0.21121052054580314 + + """ + + def __init__(self, pdf, *, umax, vmin, vmax, c=0, random_state=None): + if vmin >= vmax: + raise ValueError("vmin must be smaller than vmax.") + + if umax <= 0: + raise ValueError("umax must be positive.") + + self._pdf = pdf + self._umax = umax + self._vmin = vmin + self._vmax = vmax + self._c = c + self._rng = check_random_state(random_state) + + def rvs(self, size=1): + """Sampling of random variates + + Parameters + ---------- + size : int or tuple of ints, optional + Number of random variates to be generated (default is 1). + + Returns + ------- + rvs : ndarray + The random variates distributed according to the probability + distribution defined by the pdf. + + """ + size1d = tuple(np.atleast_1d(size)) + N = np.prod(size1d) # number of rvs needed, reshape upon return + + # start sampling using ratio of uniforms method + x = np.zeros(N) + simulated, i = 0, 1 + + # loop until N rvs have been generated: expected runtime is finite. + # to avoid infinite loop, raise exception if not a single rv has been + # generated after 50000 tries. even if the expected number of iterations + # is 1000, the probability of this event is (1-1/1000)**50000 + # which is of order 10e-22 + while simulated < N: + k = N - simulated + # simulate uniform rvs on [0, umax] and [vmin, vmax] + u1 = self._umax * self._rng.uniform(size=k) + v1 = self._rng.uniform(self._vmin, self._vmax, size=k) + # apply rejection method + rvs = v1 / u1 + self._c + accept = (u1**2 <= self._pdf(rvs)) + num_accept = np.sum(accept) + if num_accept > 0: + x[simulated:(simulated + num_accept)] = rvs[accept] + simulated += num_accept + + if (simulated == 0) and (i*N >= 50000): + msg = ( + f"Not a single random variate could be generated in {i*N} " + "attempts. The ratio of uniforms method does not appear " + "to work for the provided parameters. Please check the " + "pdf and the bounds." + ) + raise RuntimeError(msg) + i += 1 + + return np.reshape(x, size1d) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sensitivity_analysis.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sensitivity_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1eab7f2e266e076f00059d4570e87e5e9befab79 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sensitivity_analysis.py @@ -0,0 +1,713 @@ +import inspect +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any +from collections.abc import Callable + +import numpy as np + +from scipy.stats._common import ConfidenceInterval +from scipy.stats._qmc import check_random_state +from scipy.stats._resampling import BootstrapResult +from scipy.stats import qmc, bootstrap +from scipy._lib._util import _transition_to_rng + + +if TYPE_CHECKING: + import numpy.typing as npt + from scipy._lib._util import DecimalNumber, IntNumber + + +__all__ = [ + 'sobol_indices' +] + + +def f_ishigami(x: "npt.ArrayLike") -> "npt.NDArray[np.inexact[Any]]": + r"""Ishigami function. + + .. math:: + + Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1 + + with :math:`\mathbf{x} \in [-\pi, \pi]^3`. + + Parameters + ---------- + x : array_like ([x1, x2, x3], n) + + Returns + ------- + f : array_like (n,) + Function evaluation. + + References + ---------- + .. [1] Ishigami, T. and T. Homma. "An importance quantification technique + in uncertainty analysis for computer models." IEEE, + :doi:`10.1109/ISUMA.1990.151285`, 1990. + """ + x = np.atleast_2d(x) + f_eval = ( + np.sin(x[0]) + + 7 * np.sin(x[1])**2 + + 0.1 * (x[2]**4) * np.sin(x[0]) + ) + return f_eval + + +def sample_A_B( + n, + dists, + rng=None +): + """Sample two matrices A and B. + + Uses a Sobol' sequence with 2`d` columns to have 2 uncorrelated matrices. + This is more efficient than using 2 random draw of Sobol'. + See sec. 5 from [1]_. + + Output shape is (d, n). + + References + ---------- + .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and + S. Tarantola. "Variance based sensitivity analysis of model + output. Design and estimator for the total sensitivity index." + Computer Physics Communications, 181(2):259-270, + :doi:`10.1016/j.cpc.2009.09.018`, 2010. + """ + d = len(dists) + A_B = qmc.Sobol(d=2*d, seed=rng, bits=64).random(n).T + A_B = A_B.reshape(2, d, -1) + try: + for d_, dist in enumerate(dists): + A_B[:, d_] = dist.ppf(A_B[:, d_]) + except AttributeError as exc: + message = "Each distribution in `dists` must have method `ppf`." + raise ValueError(message) from exc + return A_B + + +def sample_AB(A: np.ndarray, B: np.ndarray) -> np.ndarray: + """AB matrix. + + AB: rows of B into A. Shape (d, d, n). + - Copy A into d "pages" + - In the first page, replace 1st rows of A with 1st row of B. + ... + - In the dth page, replace dth row of A with dth row of B. + - return the stack of pages + """ + d, n = A.shape + AB = np.tile(A, (d, 1, 1)) + i = np.arange(d) + AB[i, i] = B[i] + return AB + + +def saltelli_2010( + f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray +) -> tuple[np.ndarray, np.ndarray]: + r"""Saltelli2010 formulation. + + .. math:: + + S_i = \frac{1}{N} \sum_{j=1}^N + f(\mathbf{B})_j (f(\mathbf{AB}^{(i)})_j - f(\mathbf{A})_j) + + .. math:: + + S_{T_i} = \frac{1}{N} \sum_{j=1}^N + (f(\mathbf{A})_j - f(\mathbf{AB}^{(i)})_j)^2 + + Parameters + ---------- + f_A, f_B : array_like (s, n) + Function values at A and B, respectively + f_AB : array_like (d, s, n) + Function values at each of the AB pages + + Returns + ------- + s, st : array_like (s, d) + First order and total order Sobol' indices. + + References + ---------- + .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and + S. Tarantola. "Variance based sensitivity analysis of model + output. Design and estimator for the total sensitivity index." + Computer Physics Communications, 181(2):259-270, + :doi:`10.1016/j.cpc.2009.09.018`, 2010. + """ + # Empirical variance calculated using output from A and B which are + # independent. Output of AB is not independent and cannot be used + var = np.var([f_A, f_B], axis=(0, -1)) + + # We divide by the variance to have a ratio of variance + # this leads to eq. 2 + s = np.mean(f_B * (f_AB - f_A), axis=-1) / var # Table 2 (b) + st = 0.5 * np.mean((f_A - f_AB) ** 2, axis=-1) / var # Table 2 (f) + + return s.T, st.T + + +@dataclass +class BootstrapSobolResult: + first_order: BootstrapResult + total_order: BootstrapResult + + +@dataclass +class SobolResult: + first_order: np.ndarray + total_order: np.ndarray + _indices_method: Callable + _f_A: np.ndarray + _f_B: np.ndarray + _f_AB: np.ndarray + _A: np.ndarray | None = None + _B: np.ndarray | None = None + _AB: np.ndarray | None = None + _bootstrap_result: BootstrapResult | None = None + + def bootstrap( + self, + confidence_level: "DecimalNumber" = 0.95, + n_resamples: "IntNumber" = 999 + ) -> BootstrapSobolResult: + """Bootstrap Sobol' indices to provide confidence intervals. + + Parameters + ---------- + confidence_level : float, default: ``0.95`` + The confidence level of the confidence intervals. + n_resamples : int, default: ``999`` + The number of resamples performed to form the bootstrap + distribution of the indices. + + Returns + ------- + res : BootstrapSobolResult + Bootstrap result containing the confidence intervals and the + bootstrap distribution of the indices. + + An object with attributes: + + first_order : BootstrapResult + Bootstrap result of the first order indices. + total_order : BootstrapResult + Bootstrap result of the total order indices. + See `BootstrapResult` for more details. + + """ + def statistic(idx): + f_A_ = self._f_A[:, idx] + f_B_ = self._f_B[:, idx] + f_AB_ = self._f_AB[..., idx] + return self._indices_method(f_A_, f_B_, f_AB_) + + n = self._f_A.shape[1] + + res = bootstrap( + [np.arange(n)], statistic=statistic, method="BCa", + n_resamples=n_resamples, + confidence_level=confidence_level, + bootstrap_result=self._bootstrap_result + ) + self._bootstrap_result = res + + first_order = BootstrapResult( + confidence_interval=ConfidenceInterval( + res.confidence_interval.low[0], res.confidence_interval.high[0] + ), + bootstrap_distribution=res.bootstrap_distribution[0], + standard_error=res.standard_error[0], + ) + total_order = BootstrapResult( + confidence_interval=ConfidenceInterval( + res.confidence_interval.low[1], res.confidence_interval.high[1] + ), + bootstrap_distribution=res.bootstrap_distribution[1], + standard_error=res.standard_error[1], + ) + + return BootstrapSobolResult( + first_order=first_order, total_order=total_order + ) + +@_transition_to_rng('random_state', replace_doc=False) +def sobol_indices( + *, + func, + n, + dists=None, + method='saltelli_2010', + rng=None +): + r"""Global sensitivity indices of Sobol'. + + Parameters + ---------- + func : callable or dict(str, array_like) + If `func` is a callable, function to compute the Sobol' indices from. + Its signature must be:: + + func(x: ArrayLike) -> ArrayLike + + with ``x`` of shape ``(d, n)`` and output of shape ``(s, n)`` where: + + - ``d`` is the input dimensionality of `func` + (number of input variables), + - ``s`` is the output dimensionality of `func` + (number of output variables), and + - ``n`` is the number of samples (see `n` below). + + Function evaluation values must be finite. + + If `func` is a dictionary, contains the function evaluations from three + different arrays. Keys must be: ``f_A``, ``f_B`` and ``f_AB``. + ``f_A`` and ``f_B`` should have a shape ``(s, n)`` and ``f_AB`` + should have a shape ``(d, s, n)``. + This is an advanced feature and misuse can lead to wrong analysis. + n : int + Number of samples used to generate the matrices ``A`` and ``B``. + Must be a power of 2. The total number of points at which `func` is + evaluated will be ``n*(d+2)``. + dists : list(distributions), optional + List of each parameter's distribution. The distribution of parameters + depends on the application and should be carefully chosen. + Parameters are assumed to be independently distributed, meaning there + is no constraint nor relationship between their values. + + Distributions must be an instance of a class with a ``ppf`` + method. + + Must be specified if `func` is a callable, and ignored otherwise. + method : Callable or str, default: 'saltelli_2010' + Method used to compute the first and total Sobol' indices. + + If a callable, its signature must be:: + + func(f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray) + -> Tuple[np.ndarray, np.ndarray] + + with ``f_A, f_B`` of shape ``(s, n)`` and ``f_AB`` of shape + ``(d, s, n)``. + These arrays contain the function evaluations from three different sets + of samples. + The output is a tuple of the first and total indices with + shape ``(s, d)``. + This is an advanced feature and misuse can lead to wrong analysis. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator`, this keyword was changed from `random_state` to + `rng`. For an interim period, both keywords will continue to work, although + only one may be specified at a time. After the interim period, function + calls using the `random_state` keyword will emit warnings. Following a + deprecation period, the `random_state` keyword will be removed. + + Returns + ------- + res : SobolResult + An object with attributes: + + first_order : ndarray of shape (s, d) + First order Sobol' indices. + total_order : ndarray of shape (s, d) + Total order Sobol' indices. + + And method: + + bootstrap(confidence_level: float, n_resamples: int) + -> BootstrapSobolResult + + A method providing confidence intervals on the indices. + See `scipy.stats.bootstrap` for more details. + + The bootstrapping is done on both first and total order indices, + and they are available in `BootstrapSobolResult` as attributes + ``first_order`` and ``total_order``. + + Notes + ----- + The Sobol' method [1]_, [2]_ is a variance-based Sensitivity Analysis which + obtains the contribution of each parameter to the variance of the + quantities of interest (QoIs; i.e., the outputs of `func`). + Respective contributions can be used to rank the parameters and + also gauge the complexity of the model by computing the + model's effective (or mean) dimension. + + .. note:: + + Parameters are assumed to be independently distributed. Each + parameter can still follow any distribution. In fact, the distribution + is very important and should match the real distribution of the + parameters. + + It uses a functional decomposition of the variance of the function to + explore + + .. math:: + + \mathbb{V}(Y) = \sum_{i}^{d} \mathbb{V}_i (Y) + \sum_{i= 2**12``. The more complex the model is, + the more samples will be needed. + + Even for a purely additive model, the indices may not sum to 1 due + to numerical noise. + + References + ---------- + .. [1] Sobol, I. M.. "Sensitivity analysis for nonlinear mathematical + models." Mathematical Modeling and Computational Experiment, 1:407-414, + 1993. + .. [2] Sobol, I. M. (2001). "Global sensitivity indices for nonlinear + mathematical models and their Monte Carlo estimates." Mathematics + and Computers in Simulation, 55(1-3):271-280, + :doi:`10.1016/S0378-4754(00)00270-6`, 2001. + .. [3] Saltelli, A. "Making best use of model evaluations to + compute sensitivity indices." Computer Physics Communications, + 145(2):280-297, :doi:`10.1016/S0010-4655(02)00280-1`, 2002. + .. [4] Saltelli, A., M. Ratto, T. Andres, F. Campolongo, J. Cariboni, + D. Gatelli, M. Saisana, and S. Tarantola. "Global Sensitivity Analysis. + The Primer." 2007. + .. [5] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and + S. Tarantola. "Variance based sensitivity analysis of model + output. Design and estimator for the total sensitivity index." + Computer Physics Communications, 181(2):259-270, + :doi:`10.1016/j.cpc.2009.09.018`, 2010. + .. [6] Ishigami, T. and T. Homma. "An importance quantification technique + in uncertainty analysis for computer models." IEEE, + :doi:`10.1109/ISUMA.1990.151285`, 1990. + + Examples + -------- + The following is an example with the Ishigami function [6]_ + + .. math:: + + Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1, + + with :math:`\mathbf{x} \in [-\pi, \pi]^3`. This function exhibits strong + non-linearity and non-monotonicity. + + Remember, Sobol' indices assumes that samples are independently + distributed. In this case we use a uniform distribution on each marginals. + + >>> import numpy as np + >>> from scipy.stats import sobol_indices, uniform + >>> rng = np.random.default_rng() + >>> def f_ishigami(x): + ... f_eval = ( + ... np.sin(x[0]) + ... + 7 * np.sin(x[1])**2 + ... + 0.1 * (x[2]**4) * np.sin(x[0]) + ... ) + ... return f_eval + >>> indices = sobol_indices( + ... func=f_ishigami, n=1024, + ... dists=[ + ... uniform(loc=-np.pi, scale=2*np.pi), + ... uniform(loc=-np.pi, scale=2*np.pi), + ... uniform(loc=-np.pi, scale=2*np.pi) + ... ], + ... rng=rng + ... ) + >>> indices.first_order + array([0.31637954, 0.43781162, 0.00318825]) + >>> indices.total_order + array([0.56122127, 0.44287857, 0.24229595]) + + Confidence interval can be obtained using bootstrapping. + + >>> boot = indices.bootstrap() + + Then, this information can be easily visualized. + + >>> import matplotlib.pyplot as plt + >>> fig, axs = plt.subplots(1, 2, figsize=(9, 4)) + >>> _ = axs[0].errorbar( + ... [1, 2, 3], indices.first_order, fmt='o', + ... yerr=[ + ... indices.first_order - boot.first_order.confidence_interval.low, + ... boot.first_order.confidence_interval.high - indices.first_order + ... ], + ... ) + >>> axs[0].set_ylabel("First order Sobol' indices") + >>> axs[0].set_xlabel('Input parameters') + >>> axs[0].set_xticks([1, 2, 3]) + >>> _ = axs[1].errorbar( + ... [1, 2, 3], indices.total_order, fmt='o', + ... yerr=[ + ... indices.total_order - boot.total_order.confidence_interval.low, + ... boot.total_order.confidence_interval.high - indices.total_order + ... ], + ... ) + >>> axs[1].set_ylabel("Total order Sobol' indices") + >>> axs[1].set_xlabel('Input parameters') + >>> axs[1].set_xticks([1, 2, 3]) + >>> plt.tight_layout() + >>> plt.show() + + .. note:: + + By default, `scipy.stats.uniform` has support ``[0, 1]``. + Using the parameters ``loc`` and ``scale``, one obtains the uniform + distribution on ``[loc, loc + scale]``. + + This result is particularly interesting because the first order index + :math:`S_{x_3} = 0` whereas its total order is :math:`S_{T_{x_3}} = 0.244`. + This means that higher order interactions with :math:`x_3` are responsible + for the difference. Almost 25% of the observed variance + on the QoI is due to the correlations between :math:`x_3` and :math:`x_1`, + although :math:`x_3` by itself has no impact on the QoI. + + The following gives a visual explanation of Sobol' indices on this + function. Let's generate 1024 samples in :math:`[-\pi, \pi]^3` and + calculate the value of the output. + + >>> from scipy.stats import qmc + >>> n_dim = 3 + >>> p_labels = ['$x_1$', '$x_2$', '$x_3$'] + >>> sample = qmc.Sobol(d=n_dim, seed=rng).random(1024) + >>> sample = qmc.scale( + ... sample=sample, + ... l_bounds=[-np.pi, -np.pi, -np.pi], + ... u_bounds=[np.pi, np.pi, np.pi] + ... ) + >>> output = f_ishigami(sample.T) + + Now we can do scatter plots of the output with respect to each parameter. + This gives a visual way to understand how each parameter impacts the + output of the function. + + >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4)) + >>> for i in range(n_dim): + ... xi = sample[:, i] + ... ax[i].scatter(xi, output, marker='+') + ... ax[i].set_xlabel(p_labels[i]) + >>> ax[0].set_ylabel('Y') + >>> plt.tight_layout() + >>> plt.show() + + Now Sobol' goes a step further: + by conditioning the output value by given values of the parameter + (black lines), the conditional output mean is computed. It corresponds to + the term :math:`\mathbb{E}(Y|x_i)`. Taking the variance of this term gives + the numerator of the Sobol' indices. + + >>> mini = np.min(output) + >>> maxi = np.max(output) + >>> n_bins = 10 + >>> bins = np.linspace(-np.pi, np.pi, num=n_bins, endpoint=False) + >>> dx = bins[1] - bins[0] + >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4)) + >>> for i in range(n_dim): + ... xi = sample[:, i] + ... ax[i].scatter(xi, output, marker='+') + ... ax[i].set_xlabel(p_labels[i]) + ... for bin_ in bins: + ... idx = np.where((bin_ <= xi) & (xi <= bin_ + dx)) + ... xi_ = xi[idx] + ... y_ = output[idx] + ... ave_y_ = np.mean(y_) + ... ax[i].plot([bin_ + dx/2] * 2, [mini, maxi], c='k') + ... ax[i].scatter(bin_ + dx/2, ave_y_, c='r') + >>> ax[0].set_ylabel('Y') + >>> plt.tight_layout() + >>> plt.show() + + Looking at :math:`x_3`, the variance + of the mean is zero leading to :math:`S_{x_3} = 0`. But we can further + observe that the variance of the output is not constant along the parameter + values of :math:`x_3`. This heteroscedasticity is explained by higher order + interactions. Moreover, an heteroscedasticity is also noticeable on + :math:`x_1` leading to an interaction between :math:`x_3` and :math:`x_1`. + On :math:`x_2`, the variance seems to be constant and thus null interaction + with this parameter can be supposed. + + This case is fairly simple to analyse visually---although it is only a + qualitative analysis. Nevertheless, when the number of input parameters + increases such analysis becomes unrealistic as it would be difficult to + conclude on high-order terms. Hence the benefit of using Sobol' indices. + + """ + rng = check_random_state(rng) + + n_ = int(n) + if not (n_ & (n_ - 1) == 0) or n != n_: + raise ValueError( + "The balance properties of Sobol' points require 'n' " + "to be a power of 2." + ) + n = n_ + + if not callable(method): + indices_methods = { + "saltelli_2010": saltelli_2010, + } + try: + method = method.lower() # type: ignore[assignment] + indices_method_ = indices_methods[method] + except KeyError as exc: + message = ( + f"{method!r} is not a valid 'method'. It must be one of" + f" {set(indices_methods)!r} or a callable." + ) + raise ValueError(message) from exc + else: + indices_method_ = method + sig = inspect.signature(indices_method_) + + if set(sig.parameters) != {'f_A', 'f_B', 'f_AB'}: + message = ( + "If 'method' is a callable, it must have the following" + f" signature: {inspect.signature(saltelli_2010)}" + ) + raise ValueError(message) + + def indices_method(f_A, f_B, f_AB): + """Wrap indices method to ensure proper output dimension. + + 1D when single output, 2D otherwise. + """ + return np.squeeze(indices_method_(f_A=f_A, f_B=f_B, f_AB=f_AB)) + + if callable(func): + if dists is None: + raise ValueError( + "'dists' must be defined when 'func' is a callable." + ) + + def wrapped_func(x): + return np.atleast_2d(func(x)) + + A, B = sample_A_B(n=n, dists=dists, rng=rng) + AB = sample_AB(A=A, B=B) + + f_A = wrapped_func(A) + + if f_A.shape[1] != n: + raise ValueError( + "'func' output should have a shape ``(s, -1)`` with ``s`` " + "the number of output." + ) + + def funcAB(AB): + d, d, n = AB.shape + AB = np.moveaxis(AB, 0, -1).reshape(d, n*d) + f_AB = wrapped_func(AB) + return np.moveaxis(f_AB.reshape((-1, n, d)), -1, 0) + + f_B = wrapped_func(B) + f_AB = funcAB(AB) + else: + message = ( + "When 'func' is a dictionary, it must contain the following " + "keys: 'f_A', 'f_B' and 'f_AB'." + "'f_A' and 'f_B' should have a shape ``(s, n)`` and 'f_AB' " + "should have a shape ``(d, s, n)``." + ) + try: + f_A, f_B, f_AB = map(lambda arr: arr.copy(), np.atleast_2d( + func['f_A'], func['f_B'], func['f_AB'] + )) + except KeyError as exc: + raise ValueError(message) from exc + + if f_A.shape[1] != n or f_A.shape != f_B.shape or \ + f_AB.shape == f_A.shape or f_AB.shape[-1] % n != 0: + raise ValueError(message) + + # Normalization by mean + # Sobol', I. and Levitan, Y. L. (1999). On the use of variance reducing + # multipliers in monte carlo computations of a global sensitivity index. + # Computer Physics Communications, 117(1) :52-61. + mean = np.mean([f_A, f_B], axis=(0, -1)).reshape(-1, 1) + f_A -= mean + f_B -= mean + f_AB -= mean + + # Compute indices + # Filter warnings for constant output as var = 0 + with np.errstate(divide='ignore', invalid='ignore'): + first_order, total_order = indices_method(f_A=f_A, f_B=f_B, f_AB=f_AB) + + # null variance means null indices + first_order[~np.isfinite(first_order)] = 0 + total_order[~np.isfinite(total_order)] = 0 + + res = dict( + first_order=first_order, + total_order=total_order, + _indices_method=indices_method, + _f_A=f_A, + _f_B=f_B, + _f_AB=f_AB + ) + + if callable(func): + res.update( + dict( + _A=A, + _B=B, + _AB=AB, + ) + ) + + return SobolResult(**res) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sobol.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sobol.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7ca5e3a9c1a142b25ac26401e9ab1cb6726c877f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_sobol.pyi @@ -0,0 +1,54 @@ +import numpy as np +from scipy._lib._util import IntNumber +from typing import Literal + +def _initialize_v( + v : np.ndarray, + dim : IntNumber, + bits: IntNumber +) -> None: ... + +def _cscramble ( + dim : IntNumber, + bits: IntNumber, + ltm : np.ndarray, + sv: np.ndarray +) -> None: ... + +def _fill_p_cumulative( + p: np.ndarray, + p_cumulative: np.ndarray +) -> None: ... + +def _draw( + n : IntNumber, + num_gen: IntNumber, + dim: IntNumber, + scale: float, + sv: np.ndarray, + quasi: np.ndarray, + sample: np.ndarray + ) -> None: ... + +def _fast_forward( + n: IntNumber, + num_gen: IntNumber, + dim: IntNumber, + sv: np.ndarray, + quasi: np.ndarray + ) -> None: ... + +def _categorize( + draws: np.ndarray, + p_cumulative: np.ndarray, + result: np.ndarray + ) -> None: ... + +_MAXDIM: Literal[21201] +_MAXDEG: Literal[18] + +def _test_find_index( + p_cumulative: np.ndarray, + size: int, + value: float + ) -> int: ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e01565f75fe232446e4b8b0b50fdf645c8506108 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats.pxd @@ -0,0 +1,10 @@ +# destined to be used in a LowLevelCallable + +cdef double _geninvgauss_pdf(double x, void *user_data) noexcept nogil +cdef double _studentized_range_cdf(int n, double[2] x, void *user_data) noexcept nogil +cdef double _studentized_range_cdf_asymptotic(double z, void *user_data) noexcept nogil +cdef double _studentized_range_pdf(int n, double[2] x, void *user_data) noexcept nogil +cdef double _studentized_range_pdf_asymptotic(double z, void *user_data) noexcept nogil +cdef double _studentized_range_moment(int n, double[3] x_arg, void *user_data) noexcept nogil +cdef double _genhyperbolic_pdf(double x, void *user_data) noexcept nogil +cdef double _genhyperbolic_logpdf(double x, void *user_data) noexcept nogil diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats_mstats_common.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats_mstats_common.py new file mode 100644 index 0000000000000000000000000000000000000000..6900eba1fa6157c9de956255c49f5cbce0029c11 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats_mstats_common.py @@ -0,0 +1,303 @@ +import warnings +import numpy as np +from . import distributions +from .._lib._bunch import _make_tuple_bunch +from ._stats_pythran import siegelslopes as siegelslopes_pythran + +__all__ = ['_find_repeats', 'theilslopes', 'siegelslopes'] + +# This is not a namedtuple for backwards compatibility. See PR #12983 +TheilslopesResult = _make_tuple_bunch('TheilslopesResult', + ['slope', 'intercept', + 'low_slope', 'high_slope']) +SiegelslopesResult = _make_tuple_bunch('SiegelslopesResult', + ['slope', 'intercept']) + + +def theilslopes(y, x=None, alpha=0.95, method='separate'): + r""" + Computes the Theil-Sen estimator for a set of points (x, y). + + `theilslopes` implements a method for robust linear regression. It + computes the slope as the median of all slopes between paired values. + + Parameters + ---------- + y : array_like + Dependent variable. + x : array_like or None, optional + Independent variable. If None, use ``arange(len(y))`` instead. + alpha : float, optional + Confidence degree between 0 and 1. Default is 95% confidence. + Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are + interpreted as "find the 90% confidence interval". + method : {'joint', 'separate'}, optional + Method to be used for computing estimate for intercept. + Following methods are supported, + + * 'joint': Uses np.median(y - slope * x) as intercept. + * 'separate': Uses np.median(y) - slope * np.median(x) + as intercept. + + The default is 'separate'. + + .. versionadded:: 1.8.0 + + Returns + ------- + result : ``TheilslopesResult`` instance + The return value is an object with the following attributes: + + slope : float + Theil slope. + intercept : float + Intercept of the Theil line. + low_slope : float + Lower bound of the confidence interval on `slope`. + high_slope : float + Upper bound of the confidence interval on `slope`. + + See Also + -------- + siegelslopes : a similar technique using repeated medians + + Notes + ----- + The implementation of `theilslopes` follows [1]_. The intercept is + not defined in [1]_, and here it is defined as ``median(y) - + slope*median(x)``, which is given in [3]_. Other definitions of + the intercept exist in the literature such as ``median(y - slope*x)`` + in [4]_. The approach to compute the intercept can be determined by the + parameter ``method``. A confidence interval for the intercept is not + given as this question is not addressed in [1]_. + + For compatibility with older versions of SciPy, the return value acts + like a ``namedtuple`` of length 4, with fields ``slope``, ``intercept``, + ``low_slope``, and ``high_slope``, so one can continue to write:: + + slope, intercept, low_slope, high_slope = theilslopes(y, x) + + References + ---------- + .. [1] P.K. Sen, "Estimates of the regression coefficient based on + Kendall's tau", J. Am. Stat. Assoc., Vol. 63, pp. 1379-1389, 1968. + .. [2] H. Theil, "A rank-invariant method of linear and polynomial + regression analysis I, II and III", Nederl. Akad. Wetensch., Proc. + 53:, pp. 386-392, pp. 521-525, pp. 1397-1412, 1950. + .. [3] W.L. Conover, "Practical nonparametric statistics", 2nd ed., + John Wiley and Sons, New York, pp. 493. + .. [4] https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + >>> x = np.linspace(-5, 5, num=150) + >>> y = x + np.random.normal(size=x.size) + >>> y[11:15] += 10 # add outliers + >>> y[-5:] -= 7 + + Compute the slope, intercept and 90% confidence interval. For comparison, + also compute the least-squares fit with `linregress`: + + >>> res = stats.theilslopes(y, x, 0.90, method='separate') + >>> lsq_res = stats.linregress(x, y) + + Plot the results. The Theil-Sen regression line is shown in red, with the + dashed red lines illustrating the confidence interval of the slope (note + that the dashed red lines are not the confidence interval of the regression + as the confidence interval of the intercept is not included). The green + line shows the least-squares fit for comparison. + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(x, y, 'b.') + >>> ax.plot(x, res[1] + res[0] * x, 'r-') + >>> ax.plot(x, res[1] + res[2] * x, 'r--') + >>> ax.plot(x, res[1] + res[3] * x, 'r--') + >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-') + >>> plt.show() + + """ + if method not in ['joint', 'separate']: + raise ValueError("method must be either 'joint' or 'separate'." + f"'{method}' is invalid.") + # We copy both x and y so we can use _find_repeats. + y = np.array(y, dtype=float, copy=True).ravel() + if x is None: + x = np.arange(len(y), dtype=float) + else: + x = np.array(x, dtype=float, copy=True).ravel() + if len(x) != len(y): + raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})") + + # Compute sorted slopes only when deltax > 0 + deltax = x[:, np.newaxis] - x + deltay = y[:, np.newaxis] - y + slopes = deltay[deltax > 0] / deltax[deltax > 0] + if not slopes.size: + msg = "All `x` coordinates are identical." + warnings.warn(msg, RuntimeWarning, stacklevel=2) + slopes.sort() + medslope = np.median(slopes) + if method == 'joint': + medinter = np.median(y - medslope * x) + else: + medinter = np.median(y) - medslope * np.median(x) + # Now compute confidence intervals + if alpha > 0.5: + alpha = 1. - alpha + + z = distributions.norm.ppf(alpha / 2.) + # This implements (2.6) from Sen (1968) + _, nxreps = _find_repeats(x) + _, nyreps = _find_repeats(y) + nt = len(slopes) # N in Sen (1968) + ny = len(y) # n in Sen (1968) + # Equation 2.6 in Sen (1968): + sigsq = 1/18. * (ny * (ny-1) * (2*ny+5) - + sum(k * (k-1) * (2*k + 5) for k in nxreps) - + sum(k * (k-1) * (2*k + 5) for k in nyreps)) + # Find the confidence interval indices in `slopes` + try: + sigma = np.sqrt(sigsq) + Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1) + Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0) + delta = slopes[[Rl, Ru]] + except (ValueError, IndexError): + delta = (np.nan, np.nan) + + return TheilslopesResult(slope=medslope, intercept=medinter, + low_slope=delta[0], high_slope=delta[1]) + + +def _find_repeats(arr): + # This function assumes it may clobber its input. + if len(arr) == 0: + return np.array(0, np.float64), np.array(0, np.intp) + + # XXX This cast was previously needed for the Fortran implementation, + # should we ditch it? + arr = np.asarray(arr, np.float64).ravel() + arr.sort() + + # Taken from NumPy 1.9's np.unique. + change = np.concatenate(([True], arr[1:] != arr[:-1])) + unique = arr[change] + change_idx = np.concatenate(np.nonzero(change) + ([arr.size],)) + freq = np.diff(change_idx) + atleast2 = freq > 1 + return unique[atleast2], freq[atleast2] + + +def siegelslopes(y, x=None, method="hierarchical"): + r""" + Computes the Siegel estimator for a set of points (x, y). + + `siegelslopes` implements a method for robust linear regression + using repeated medians (see [1]_) to fit a line to the points (x, y). + The method is robust to outliers with an asymptotic breakdown point + of 50%. + + Parameters + ---------- + y : array_like + Dependent variable. + x : array_like or None, optional + Independent variable. If None, use ``arange(len(y))`` instead. + method : {'hierarchical', 'separate'} + If 'hierarchical', estimate the intercept using the estimated + slope ``slope`` (default option). + If 'separate', estimate the intercept independent of the estimated + slope. See Notes for details. + + Returns + ------- + result : ``SiegelslopesResult`` instance + The return value is an object with the following attributes: + + slope : float + Estimate of the slope of the regression line. + intercept : float + Estimate of the intercept of the regression line. + + See Also + -------- + theilslopes : a similar technique without repeated medians + + Notes + ----- + With ``n = len(y)``, compute ``m_j`` as the median of + the slopes from the point ``(x[j], y[j])`` to all other `n-1` points. + ``slope`` is then the median of all slopes ``m_j``. + Two ways are given to estimate the intercept in [1]_ which can be chosen + via the parameter ``method``. + The hierarchical approach uses the estimated slope ``slope`` + and computes ``intercept`` as the median of ``y - slope*x``. + The other approach estimates the intercept separately as follows: for + each point ``(x[j], y[j])``, compute the intercepts of all the `n-1` + lines through the remaining points and take the median ``i_j``. + ``intercept`` is the median of the ``i_j``. + + The implementation computes `n` times the median of a vector of size `n` + which can be slow for large vectors. There are more efficient algorithms + (see [2]_) which are not implemented here. + + For compatibility with older versions of SciPy, the return value acts + like a ``namedtuple`` of length 2, with fields ``slope`` and + ``intercept``, so one can continue to write:: + + slope, intercept = siegelslopes(y, x) + + References + ---------- + .. [1] A. Siegel, "Robust Regression Using Repeated Medians", + Biometrika, Vol. 69, pp. 242-244, 1982. + + .. [2] A. Stein and M. Werman, "Finding the repeated median regression + line", Proceedings of the Third Annual ACM-SIAM Symposium on + Discrete Algorithms, pp. 409-413, 1992. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + >>> x = np.linspace(-5, 5, num=150) + >>> y = x + np.random.normal(size=x.size) + >>> y[11:15] += 10 # add outliers + >>> y[-5:] -= 7 + + Compute the slope and intercept. For comparison, also compute the + least-squares fit with `linregress`: + + >>> res = stats.siegelslopes(y, x) + >>> lsq_res = stats.linregress(x, y) + + Plot the results. The Siegel regression line is shown in red. The green + line shows the least-squares fit for comparison. + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(x, y, 'b.') + >>> ax.plot(x, res[1] + res[0] * x, 'r-') + >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-') + >>> plt.show() + + """ + if method not in ['hierarchical', 'separate']: + raise ValueError("method can only be 'hierarchical' or 'separate'") + y = np.asarray(y).ravel() + if x is None: + x = np.arange(len(y), dtype=float) + else: + x = np.asarray(x, dtype=float).ravel() + if len(x) != len(y): + raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})") + dtype = np.result_type(x, y, np.float32) # use at least float32 + y, x = y.astype(dtype), x.astype(dtype) + medslope, medinter = siegelslopes_pythran(y, x, method) + return SiegelslopesResult(slope=medslope, intercept=medinter) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats_py.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats_py.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8c1850cd0dad3d654216ae45dad04dafaa983b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_stats_py.py @@ -0,0 +1,11015 @@ +# Copyright 2002 Gary Strangman. All rights reserved +# Copyright 2002-2016 The SciPy Developers +# +# The original code from Gary Strangman was heavily adapted for +# use in SciPy by Travis Oliphant. The original code came with the +# following disclaimer: +# +# This software is provided "as-is". There are no expressed or implied +# warranties of any kind, including, but not limited to, the warranties +# of merchantability and fitness for a given application. In no event +# shall Gary Strangman be liable for any direct, indirect, incidental, +# special, exemplary or consequential damages (including, but not limited +# to, loss of use, data or profits, or business interruption) however +# caused and on any theory of liability, whether in contract, strict +# liability or tort (including negligence or otherwise) arising in any way +# out of the use of this software, even if advised of the possibility of +# such damage. + +""" +A collection of basic statistical functions for Python. + +References +---------- +.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + +""" +import warnings +import math +from math import gcd +from collections import namedtuple +from collections.abc import Sequence + +import numpy as np +from numpy import array, asarray, ma + +from scipy import sparse +from scipy.spatial import distance_matrix + +from scipy.optimize import milp, LinearConstraint +from scipy._lib._util import (check_random_state, _get_nan, + _rename_parameter, _contains_nan, + AxisError, _lazywhere) +from scipy._lib.deprecation import _deprecate_positional_args + + +import scipy.special as special +# Import unused here but needs to stay until end of deprecation periode +# See https://github.com/scipy/scipy/issues/15765#issuecomment-1875564522 +from scipy import linalg # noqa: F401 +from . import distributions +from . import _mstats_basic as mstats_basic + +from ._stats_mstats_common import _find_repeats, theilslopes, siegelslopes +from ._stats import _kendall_dis, _toint64, _weightedrankedtau + +from dataclasses import dataclass, field +from ._hypotests import _all_partitions +from ._stats_pythran import _compute_outer_prob_inside_method +from ._resampling import (MonteCarloMethod, PermutationMethod, BootstrapMethod, + monte_carlo_test, permutation_test, bootstrap, + _batch_generator) +from ._axis_nan_policy import (_axis_nan_policy_factory, + _broadcast_concatenate, _broadcast_shapes, + _broadcast_array_shapes_remove_axis, SmallSampleWarning, + too_small_1d_not_omit, too_small_1d_omit, + too_small_nd_not_omit, too_small_nd_omit) +from ._binomtest import _binary_search_for_binom_tst as _binary_search +from scipy._lib._bunch import _make_tuple_bunch +from scipy import stats +from scipy.optimize import root_scalar +from scipy._lib._util import normalize_axis_index +from scipy._lib._array_api import ( + _asarray, + array_namespace, + is_numpy, + xp_size, + xp_moveaxis_to_end, + xp_sign, + xp_vector_norm, + xp_broadcast_promote, +) +from scipy._lib import array_api_extra as xpx +from scipy._lib.deprecation import _deprecated + + +# Functions/classes in other files should be added in `__init__.py`, not here +__all__ = ['find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar', + 'tmin', 'tmax', 'tstd', 'tsem', 'moment', + 'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest', + 'normaltest', 'jarque_bera', + 'scoreatpercentile', 'percentileofscore', + 'cumfreq', 'relfreq', 'obrientransform', + 'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd', + 'median_abs_deviation', + 'sigmaclip', 'trimboth', 'trim1', 'trim_mean', + 'f_oneway', 'pearsonr', 'fisher_exact', + 'spearmanr', 'pointbiserialr', + 'kendalltau', 'weightedtau', + 'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp', + 'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel', + 'kstest', 'ks_1samp', 'ks_2samp', + 'chisquare', 'power_divergence', + 'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare', + 'rankdata', 'combine_pvalues', 'quantile_test', + 'wasserstein_distance', 'wasserstein_distance_nd', 'energy_distance', + 'brunnermunzel', 'alexandergovern', + 'expectile', 'lmoment'] + + +def _chk_asarray(a, axis, *, xp=None): + if xp is None: + xp = array_namespace(a) + + if axis is None: + a = xp.reshape(a, (-1,)) + outaxis = 0 + else: + a = xp.asarray(a) + outaxis = axis + + if a.ndim == 0: + a = xp.reshape(a, (-1,)) + + return a, outaxis + + +def _chk2_asarray(a, b, axis): + if axis is None: + a = np.ravel(a) + b = np.ravel(b) + outaxis = 0 + else: + a = np.asarray(a) + b = np.asarray(b) + outaxis = axis + + if a.ndim == 0: + a = np.atleast_1d(a) + if b.ndim == 0: + b = np.atleast_1d(b) + + return a, b, outaxis + + +def _convert_common_float(*arrays, xp=None): + xp = array_namespace(*arrays) if xp is None else xp + arrays = [_asarray(array, subok=True) for array in arrays] + dtypes = [(xp.asarray(1.).dtype if xp.isdtype(array.dtype, 'integral') + else array.dtype) for array in arrays] + dtype = xp.result_type(*dtypes) + arrays = [xp.astype(array, dtype, copy=False) for array in arrays] + return arrays[0] if len(arrays)==1 else tuple(arrays) + + +SignificanceResult = _make_tuple_bunch('SignificanceResult', + ['statistic', 'pvalue'], []) + + +# note that `weights` are paired with `x` +@_axis_nan_policy_factory( + lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, + result_to_tuple=lambda x: (x,), kwd_samples=['weights']) +def gmean(a, axis=0, dtype=None, weights=None): + r"""Compute the weighted geometric mean along the specified axis. + + The weighted geometric mean of the array :math:`a_i` associated to weights + :math:`w_i` is: + + .. math:: + + \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i } + \right) \, , + + and, with equal weights, it gives: + + .. math:: + + \sqrt[n]{ \prod_{i=1}^n a_i } \, . + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + axis : int or None, optional + Axis along which the geometric mean is computed. Default is 0. + If None, compute over the whole array `a`. + dtype : dtype, optional + Type to which the input arrays are cast before the calculation is + performed. + weights : array_like, optional + The `weights` array must be broadcastable to the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + + Returns + ------- + gmean : ndarray + See `dtype` parameter above. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.average : Weighted average + hmean : Harmonic mean + + Notes + ----- + The sample geometric mean is the exponential of the mean of the natural + logarithms of the observations. + Negative observations will produce NaNs in the output because the *natural* + logarithm (as opposed to the *complex* logarithm) is defined only for + non-negative reals. + + References + ---------- + .. [1] "Weighted Geometric Mean", *Wikipedia*, + https://en.wikipedia.org/wiki/Weighted_geometric_mean. + .. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach", + Archimedes Foundation, 1983 + + Examples + -------- + >>> from scipy.stats import gmean + >>> gmean([1, 4]) + 2.0 + >>> gmean([1, 2, 3, 4, 5, 6, 7]) + 3.3800151591412964 + >>> gmean([1, 4, 7], weights=[3, 1, 3]) + 2.80668351922014 + + """ + xp = array_namespace(a, weights) + a = xp.asarray(a, dtype=dtype) + + if weights is not None: + weights = xp.asarray(weights, dtype=dtype) + + with np.errstate(divide='ignore'): + log_a = xp.log(a) + + return xp.exp(_xp_mean(log_a, axis=axis, weights=weights)) + + +@_axis_nan_policy_factory( + lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, + result_to_tuple=lambda x: (x,), kwd_samples=['weights']) +def hmean(a, axis=0, dtype=None, *, weights=None): + r"""Calculate the weighted harmonic mean along the specified axis. + + The weighted harmonic mean of the array :math:`a_i` associated to weights + :math:`w_i` is: + + .. math:: + + \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, , + + and, with equal weights, it gives: + + .. math:: + + \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, . + + Parameters + ---------- + a : array_like + Input array, masked array or object that can be converted to an array. + axis : int or None, optional + Axis along which the harmonic mean is computed. Default is 0. + If None, compute over the whole array `a`. + 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. + weights : array_like, optional + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given `axis`) or of the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + + .. versionadded:: 1.9 + + Returns + ------- + hmean : ndarray + See `dtype` parameter above. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.average : Weighted average + gmean : Geometric mean + + Notes + ----- + The sample harmonic mean is the reciprocal of the mean of the reciprocals + of the observations. + + The harmonic mean is computed over a single dimension of the input + array, axis=0 by default, or all values in the array if axis=None. + float64 intermediate and return values are used for integer inputs. + + The harmonic mean is only defined if all observations are non-negative; + otherwise, the result is NaN. + + References + ---------- + .. [1] "Weighted Harmonic Mean", *Wikipedia*, + https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean + .. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of + the American Statistical Association, vol. 26, pp. 36-40, 1931 + + Examples + -------- + >>> from scipy.stats import hmean + >>> hmean([1, 4]) + 1.6000000000000001 + >>> hmean([1, 2, 3, 4, 5, 6, 7]) + 2.6997245179063363 + >>> hmean([1, 4, 7], weights=[3, 1, 3]) + 1.9029126213592233 + + """ + xp = array_namespace(a, weights) + a = xp.asarray(a, dtype=dtype) + + if weights is not None: + weights = xp.asarray(weights, dtype=dtype) + + negative_mask = a < 0 + if xp.any(negative_mask): + # `where` avoids having to be careful about dtypes and will work with + # JAX. This is the exceptional case, so it's OK to be a little slower. + # Won't work for array_api_strict for now, but see data-apis/array-api#807 + a = xp.where(negative_mask, xp.nan, a) + message = ("The harmonic mean is only defined if all elements are " + "non-negative; otherwise, the result is NaN.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + with np.errstate(divide='ignore'): + return 1.0 / _xp_mean(1.0 / a, axis=axis, weights=weights) + + +@_axis_nan_policy_factory( + lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True, + result_to_tuple=lambda x: (x,), kwd_samples=['weights']) +def pmean(a, p, *, axis=0, dtype=None, weights=None): + r"""Calculate the weighted power mean along the specified axis. + + The weighted power mean of the array :math:`a_i` associated to weights + :math:`w_i` is: + + .. math:: + + \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i } + \right)^{ 1 / p } \, , + + and, with equal weights, it gives: + + .. math:: + + \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p } \, . + + When ``p=0``, it returns the geometric mean. + + This mean is also called generalized mean or Hölder mean, and must not be + confused with the Kolmogorov generalized mean, also called + quasi-arithmetic mean or generalized f-mean [3]_. + + Parameters + ---------- + a : array_like + Input array, masked array or object that can be converted to an array. + p : int or float + Exponent. + axis : int or None, optional + Axis along which the power mean is computed. Default is 0. + If None, compute over the whole array `a`. + 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. + weights : array_like, optional + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given `axis`) or of the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + + Returns + ------- + pmean : ndarray, see `dtype` parameter above. + Output array containing the power mean values. + + See Also + -------- + numpy.average : Weighted average + gmean : Geometric mean + hmean : Harmonic mean + + Notes + ----- + The power mean is computed over a single dimension of the input + array, ``axis=0`` by default, or all values in the array if ``axis=None``. + float64 intermediate and return values are used for integer inputs. + + The power mean is only defined if all observations are non-negative; + otherwise, the result is NaN. + + .. versionadded:: 1.9 + + References + ---------- + .. [1] "Generalized Mean", *Wikipedia*, + https://en.wikipedia.org/wiki/Generalized_mean + .. [2] Norris, N., "Convexity properties of generalized mean value + functions", The Annals of Mathematical Statistics, vol. 8, + pp. 118-120, 1937 + .. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003 + + Examples + -------- + >>> from scipy.stats import pmean, hmean, gmean + >>> pmean([1, 4], 1.3) + 2.639372938300652 + >>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3) + 4.157111214492084 + >>> pmean([1, 4, 7], -2, weights=[3, 1, 3]) + 1.4969684896631954 + + For p=-1, power mean is equal to harmonic mean: + + >>> pmean([1, 4, 7], -1, weights=[3, 1, 3]) + 1.9029126213592233 + >>> hmean([1, 4, 7], weights=[3, 1, 3]) + 1.9029126213592233 + + For p=0, power mean is defined as the geometric mean: + + >>> pmean([1, 4, 7], 0, weights=[3, 1, 3]) + 2.80668351922014 + >>> gmean([1, 4, 7], weights=[3, 1, 3]) + 2.80668351922014 + + """ + if not isinstance(p, (int, float)): + raise ValueError("Power mean only defined for exponent of type int or " + "float.") + if p == 0: + return gmean(a, axis=axis, dtype=dtype, weights=weights) + + xp = array_namespace(a, weights) + a = xp.asarray(a, dtype=dtype) + + if weights is not None: + weights = xp.asarray(weights, dtype=dtype) + + negative_mask = a < 0 + if xp.any(negative_mask): + # `where` avoids having to be careful about dtypes and will work with + # JAX. This is the exceptional case, so it's OK to be a little slower. + # Won't work for array_api_strict for now, but see data-apis/array-api#807 + a = xp.where(negative_mask, np.nan, a) + message = ("The power mean is only defined if all elements are " + "non-negative; otherwise, the result is NaN.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + with np.errstate(divide='ignore', invalid='ignore'): + return _xp_mean(a**float(p), axis=axis, weights=weights)**(1/p) + + +ModeResult = namedtuple('ModeResult', ('mode', 'count')) + + +def _mode_result(mode, count): + # When a slice is empty, `_axis_nan_policy` automatically produces + # NaN for `mode` and `count`. This is a reasonable convention for `mode`, + # but `count` should not be NaN; it should be zero. + i = np.isnan(count) + if i.shape == (): + count = np.asarray(0, dtype=count.dtype)[()] if i else count + else: + count[i] = 0 + return ModeResult(mode, count) + + +@_axis_nan_policy_factory(_mode_result, override={'vectorization': True, + 'nan_propagation': False}) +def mode(a, axis=0, nan_policy='propagate', keepdims=False): + r"""Return an array of the modal (most common) value in the passed array. + + If there is more than one such value, only one is returned. + The bin-count for the modal bins is also returned. + + Parameters + ---------- + a : array_like + Numeric, n-dimensional array of which to find mode(s). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': treats nan as it would treat any other value + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + keepdims : bool, optional + If set to ``False``, the `axis` over which the statistic is taken + is consumed (eliminated from the output array). If set to ``True``, + the `axis` is retained with size one, and the result will broadcast + correctly against the input array. + + Returns + ------- + mode : ndarray + Array of modal values. + count : ndarray + Array of counts for each mode. + + Notes + ----- + The mode is calculated using `numpy.unique`. + In NumPy versions 1.21 and after, all NaNs - even those with different + binary representations - are treated as equivalent and counted as separate + instances of the same value. + + By convention, the mode of an empty array is NaN, and the associated count + is zero. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[3, 0, 3, 7], + ... [3, 2, 6, 2], + ... [1, 7, 2, 8], + ... [3, 0, 6, 1], + ... [3, 2, 5, 5]]) + >>> from scipy import stats + >>> stats.mode(a, keepdims=True) + ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]])) + + To get mode of whole array, specify ``axis=None``: + + >>> stats.mode(a, axis=None, keepdims=True) + ModeResult(mode=[[3]], count=[[5]]) + >>> stats.mode(a, axis=None, keepdims=False) + ModeResult(mode=3, count=5) + + """ + # `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy` + if not np.issubdtype(a.dtype, np.number): + message = ("Argument `a` is not recognized as numeric. " + "Support for input that cannot be coerced to a numeric " + "array was deprecated in SciPy 1.9.0 and removed in SciPy " + "1.11.0. Please consider `np.unique`.") + raise TypeError(message) + + if a.size == 0: + NaN = _get_nan(a) + return ModeResult(*np.array([NaN, 0], dtype=NaN.dtype)) + + vals, cnts = np.unique(a, return_counts=True) + modes, counts = vals[cnts.argmax()], cnts.max() + return ModeResult(modes[()], counts[()]) + + +def _put_val_to_limits(a, limits, inclusive, val=np.nan, xp=None): + """Replace elements outside limits with a value. + + This is primarily a utility function. + + Parameters + ---------- + a : array + limits : (float or None, float or None) + A tuple consisting of the (lower limit, upper limit). Elements in the + input array less than the lower limit or greater than the upper limit + will be replaced with `val`. None implies no limit. + inclusive : (bool, bool) + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to lower or upper are allowed. + val : float, default: NaN + The value with which extreme elements of the array are replaced. + + """ + xp = array_namespace(a) if xp is None else xp + mask = xp.zeros(a.shape, dtype=xp.bool) + if limits is None: + return a, mask + lower_limit, upper_limit = limits + lower_include, upper_include = inclusive + if lower_limit is not None: + mask |= (a < lower_limit) if lower_include else a <= lower_limit + if upper_limit is not None: + mask |= (a > upper_limit) if upper_include else a >= upper_limit + if xp.all(mask): + raise ValueError("No array values within given limits") + if xp.any(mask): + # hopefully this (and many other instances of this idiom) are temporary when + # data-apis/array-api#807 is resolved + dtype = xp.asarray(1.).dtype if xp.isdtype(a.dtype, 'integral') else a.dtype + a = xp.where(mask, xp.asarray(val, dtype=dtype), a) + return a, mask + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def tmean(a, limits=None, inclusive=(True, True), axis=None): + """Compute the trimmed mean. + + This function finds the arithmetic mean of given values, ignoring values + outside the given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None (default), then all + values are used. Either of the limit values in the tuple can also be + None representing a half-open interval. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to compute test. Default is None. + + Returns + ------- + tmean : ndarray + Trimmed mean. + + See Also + -------- + trim_mean : Returns mean after trimming a proportion from both tails. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tmean(x) + 9.5 + >>> stats.tmean(x, (3,17)) + 10.0 + + """ + xp = array_namespace(a) + a, mask = _put_val_to_limits(a, limits, inclusive, val=0., xp=xp) + # explicit dtype specification required due to data-apis/array-api-compat#152 + sum = xp.sum(a, axis=axis, dtype=a.dtype) + n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis, dtype=a.dtype) + mean = _lazywhere(n != 0, (sum, n), xp.divide, xp.nan) + return mean[()] if mean.ndim == 0 else mean + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """Compute the trimmed variance. + + This function computes the sample variance of an array of values, + while ignoring values which are outside of given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tvar : float + Trimmed variance. + + Notes + ----- + `tvar` computes the unbiased sample variance, i.e. it uses a correction + factor ``n / (n - 1)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tvar(x) + 35.0 + >>> stats.tvar(x, (3,17)) + 20.0 + + """ + xp = array_namespace(a) + a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SmallSampleWarning) + # Currently, this behaves like nan_policy='omit' for alternative array + # backends, but nan_policy='propagate' will be handled for other backends + # by the axis_nan_policy decorator shortly. + return _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp) + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'): + """Compute the trimmed minimum. + + This function finds the minimum value of an array `a` along the + specified axis, but only considering values greater than a specified + lower limit. + + Parameters + ---------- + a : array_like + Array of values. + lowerlimit : None or float, optional + Values in the input array less than the given limit will be ignored. + When lowerlimit is None, then all values are used. The default value + is None. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + inclusive : {True, False}, optional + This flag determines whether values exactly equal to the lower limit + are included. The default value is True. + + Returns + ------- + tmin : float, int or ndarray + Trimmed minimum. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tmin(x) + 0 + + >>> stats.tmin(x, 13) + 13 + + >>> stats.tmin(x, 13, inclusive=False) + 14 + + """ + xp = array_namespace(a) + + # remember original dtype; _put_val_to_limits might need to change it + dtype = a.dtype + a, mask = _put_val_to_limits(a, (lowerlimit, None), (inclusive, None), + val=xp.inf, xp=xp) + + min = xp.min(a, axis=axis) + n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis) + res = xp.where(n != 0, min, xp.nan) + + if not xp.any(xp.isnan(res)): + # needed if input is of integer dtype + res = xp.astype(res, dtype, copy=False) + + return res[()] if res.ndim == 0 else res + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'): + """Compute the trimmed maximum. + + This function computes the maximum value of an array along a given axis, + while ignoring values larger than a specified upper limit. + + Parameters + ---------- + a : array_like + Array of values. + upperlimit : None or float, optional + Values in the input array greater than the given limit will be ignored. + When upperlimit is None, then all values are used. The default value + is None. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + inclusive : {True, False}, optional + This flag determines whether values exactly equal to the upper limit + are included. The default value is True. + + Returns + ------- + tmax : float, int or ndarray + Trimmed maximum. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tmax(x) + 19 + + >>> stats.tmax(x, 13) + 13 + + >>> stats.tmax(x, 13, inclusive=False) + 12 + + """ + xp = array_namespace(a) + + # remember original dtype; _put_val_to_limits might need to change it + dtype = a.dtype + a, mask = _put_val_to_limits(a, (None, upperlimit), (None, inclusive), + val=-xp.inf, xp=xp) + + max = xp.max(a, axis=axis) + n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis) + res = xp.where(n != 0, max, xp.nan) + + if not xp.any(xp.isnan(res)): + # needed if input is of integer dtype + res = xp.astype(res, dtype, copy=False) + + return res[()] if res.ndim == 0 else res + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """Compute the trimmed sample standard deviation. + + This function finds the sample standard deviation of given values, + ignoring values outside the given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tstd : float + Trimmed sample standard deviation. + + Notes + ----- + `tstd` computes the unbiased sample standard deviation, i.e. it uses a + correction factor ``n / (n - 1)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tstd(x) + 5.9160797830996161 + >>> stats.tstd(x, (3,17)) + 4.4721359549995796 + + """ + return tvar(a, limits, inclusive, axis, ddof, _no_deco=True)**0.5 + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1): + """Compute the trimmed standard error of the mean. + + This function finds the standard error of the mean for given + values, ignoring values outside the given `limits`. + + Parameters + ---------- + a : array_like + Array of values. + limits : None or (lower limit, upper limit), optional + Values in the input array less than the lower limit or greater than the + upper limit will be ignored. When limits is None, then all values are + used. Either of the limit values in the tuple can also be None + representing a half-open interval. The default value is None. + inclusive : (bool, bool), optional + A tuple consisting of the (lower flag, upper flag). These flags + determine whether values exactly equal to the lower or upper limits + are included. The default value is (True, True). + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over the + whole array `a`. + ddof : int, optional + Delta degrees of freedom. Default is 1. + + Returns + ------- + tsem : float + Trimmed standard error of the mean. + + Notes + ----- + `tsem` uses unbiased sample standard deviation, i.e. it uses a + correction factor ``n / (n - 1)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = np.arange(20) + >>> stats.tsem(x) + 1.3228756555322954 + >>> stats.tsem(x, (3,17)) + 1.1547005383792515 + + """ + xp = array_namespace(a) + a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SmallSampleWarning) + # Currently, this behaves like nan_policy='omit' for alternative array + # backends, but nan_policy='propagate' will be handled for other backends + # by the axis_nan_policy decorator shortly. + sd = _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)**0.5 + + n_obs = xp.sum(~xp.isnan(a), axis=axis, dtype=sd.dtype) + return sd / n_obs**0.5 + + +##################################### +# MOMENTS # +##################################### + + +def _moment_outputs(kwds, default_order=1): + order = np.atleast_1d(kwds.get('order', default_order)) + message = "`order` must be a scalar or a non-empty 1D array." + if order.size == 0 or order.ndim > 1: + raise ValueError(message) + return len(order) + + +def _moment_result_object(*args): + if len(args) == 1: + return args[0] + return np.asarray(args) + + +# When `order` is array-like with size > 1, moment produces an *array* +# rather than a tuple, but the zeroth dimension is to be treated like +# separate outputs. It is important to make the distinction between +# separate outputs when adding the reduced axes back (`keepdims=True`). +def _moment_tuple(x, n_out): + return tuple(x) if n_out > 1 else (x,) + + +# `moment` fits into the `_axis_nan_policy` pattern, but it is a bit unusual +# because the number of outputs is variable. Specifically, +# `result_to_tuple=lambda x: (x,)` may be surprising for a function that +# can produce more than one output, but it is intended here. +# When `moment is called to produce the output: +# - `result_to_tuple` packs the returned array into a single-element tuple, +# - `_moment_result_object` extracts and returns that single element. +# However, when the input array is empty, `moment` is never called. Instead, +# - `_check_empty_inputs` is used to produce an empty array with the +# appropriate dimensions. +# - A list comprehension creates the appropriate number of copies of this +# array, depending on `n_outputs`. +# - This list - which may have multiple elements - is passed into +# `_moment_result_object`. +# - If there is a single output, `_moment_result_object` extracts and returns +# the single output from the list. +# - If there are multiple outputs, and therefore multiple elements in the list, +# `_moment_result_object` converts the list of arrays to a single array and +# returns it. +# Currently, this leads to a slight inconsistency: when the input array is +# empty, there is no distinction between the `moment` function being called +# with parameter `order=1` and `order=[1]`; the latter *should* produce +# the same as the former but with a singleton zeroth dimension. +@_rename_parameter('moment', 'order') +@_axis_nan_policy_factory( # noqa: E302 + _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple, + n_outputs=_moment_outputs +) +def moment(a, order=1, axis=0, nan_policy='propagate', *, center=None): + r"""Calculate the nth moment about the mean for a sample. + + A moment is a specific quantitative measure of the shape of a set of + points. It is often used to calculate coefficients of skewness and kurtosis + due to its close relationship with them. + + Parameters + ---------- + a : array_like + Input array. + order : int or 1-D array_like of ints, optional + Order of central moment that is returned. Default is 1. + axis : int or None, optional + Axis along which the central moment is computed. Default is 0. + If None, compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + center : float or None, optional + The point about which moments are taken. This can be the sample mean, + the origin, or any other be point. If `None` (default) compute the + center as the sample mean. + + Returns + ------- + n-th moment about the `center` : ndarray or float + The appropriate moment along the given axis or over all values if axis + is None. The denominator for the moment calculation is the number of + observations, no degrees of freedom correction is done. + + See Also + -------- + kurtosis, skew, describe + + Notes + ----- + The k-th moment of a data sample is: + + .. math:: + + m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - c)^k + + Where `n` is the number of samples, and `c` is the center around which the + moment is calculated. This function uses exponentiation by squares [1]_ for + efficiency. + + Note that, if `a` is an empty array (``a.size == 0``), array `moment` with + one element (`moment.size == 1`) is treated the same as scalar `moment` + (``np.isscalar(moment)``). This might produce arrays of unexpected shape. + + References + ---------- + .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms + + Examples + -------- + >>> from scipy.stats import moment + >>> moment([1, 2, 3, 4, 5], order=1) + 0.0 + >>> moment([1, 2, 3, 4, 5], order=2) + 2.0 + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + if xp.isdtype(a.dtype, 'integral'): + a = xp.asarray(a, dtype=xp.float64) + else: + a = xp.asarray(a) + + order = xp.asarray(order, dtype=a.dtype) + if xp_size(order) == 0: + # This is tested by `_moment_outputs`, which is run by the `_axis_nan_policy` + # decorator. Currently, the `_axis_nan_policy` decorator is skipped when `a` + # is a non-NumPy array, so we need to check again. When the decorator is + # updated for array API compatibility, we can remove this second check. + raise ValueError("`order` must be a scalar or a non-empty 1D array.") + if xp.any(order != xp.round(order)): + raise ValueError("All elements of `order` must be integral.") + order = order[()] if order.ndim == 0 else order + + # for array_like order input, return a value for each. + if order.ndim > 0: + # Calculated the mean once at most, and only if it will be used + calculate_mean = center is None and xp.any(order > 1) + mean = xp.mean(a, axis=axis, keepdims=True) if calculate_mean else None + mmnt = [] + for i in range(order.shape[0]): + order_i = order[i] + if center is None and order_i > 1: + mmnt.append(_moment(a, order_i, axis, mean=mean)[np.newaxis, ...]) + else: + mmnt.append(_moment(a, order_i, axis, mean=center)[np.newaxis, ...]) + return xp.concat(mmnt, axis=0) + else: + return _moment(a, order, axis, mean=center) + + +def _demean(a, mean, axis, *, xp, precision_warning=True): + # subtracts `mean` from `a` and returns the result, + # warning if there is catastrophic cancellation. `mean` + # must be the mean of `a` along axis with `keepdims=True`. + # Used in e.g. `_moment`, `_zscore`, `_xp_var`. See gh-15905. + a_zero_mean = a - mean + + if xp_size(a_zero_mean) == 0: + return a_zero_mean + + eps = xp.finfo(mean.dtype).eps * 10 + + with np.errstate(divide='ignore', invalid='ignore'): + rel_diff = xp.max(xp.abs(a_zero_mean), axis=axis, + keepdims=True) / xp.abs(mean) + with np.errstate(invalid='ignore'): + precision_loss = xp.any(rel_diff < eps) + n = (xp_size(a) if axis is None + # compact way to deal with axis tuples or ints + else np.prod(np.asarray(a.shape)[np.asarray(axis)])) + + if precision_loss and n > 1 and precision_warning: + message = ("Precision loss occurred in moment calculation due to " + "catastrophic cancellation. This occurs when the data " + "are nearly identical. Results may be unreliable.") + warnings.warn(message, RuntimeWarning, stacklevel=5) + return a_zero_mean + + +def _moment(a, order, axis, *, mean=None, xp=None): + """Vectorized calculation of raw moment about specified center + + When `mean` is None, the mean is computed and used as the center; + otherwise, the provided value is used as the center. + + """ + xp = array_namespace(a) if xp is None else xp + + if xp.isdtype(a.dtype, 'integral'): + a = xp.asarray(a, dtype=xp.float64) + + dtype = a.dtype + + # moment of empty array is the same regardless of order + if xp_size(a) == 0: + return xp.mean(a, axis=axis) + + if order == 0 or (order == 1 and mean is None): + # By definition the zeroth moment is always 1, and the first *central* + # moment is 0. + shape = list(a.shape) + del shape[axis] + + temp = (xp.ones(shape, dtype=dtype) if order == 0 + else xp.zeros(shape, dtype=dtype)) + return temp[()] if temp.ndim == 0 else temp + + # Exponentiation by squares: form exponent sequence + n_list = [order] + current_n = order + while current_n > 2: + if current_n % 2: + current_n = (current_n - 1) / 2 + else: + current_n /= 2 + n_list.append(current_n) + + # Starting point for exponentiation by squares + mean = (xp.mean(a, axis=axis, keepdims=True) if mean is None + else xp.asarray(mean, dtype=dtype)) + mean = mean[()] if mean.ndim == 0 else mean + a_zero_mean = _demean(a, mean, axis, xp=xp) + + if n_list[-1] == 1: + s = xp.asarray(a_zero_mean, copy=True) + else: + s = a_zero_mean**2 + + # Perform multiplications + for n in n_list[-2::-1]: + s = s**2 + if n % 2: + s *= a_zero_mean + return xp.mean(s, axis=axis) + + +def _var(x, axis=0, ddof=0, mean=None, xp=None): + # Calculate variance of sample, warning if precision is lost + xp = array_namespace(x) if xp is None else xp + var = _moment(x, 2, axis, mean=mean, xp=xp) + if ddof != 0: + n = x.shape[axis] if axis is not None else xp_size(x) + var *= np.divide(n, n-ddof) # to avoid error on division by zero + return var + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1 +) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def skew(a, axis=0, bias=True, nan_policy='propagate'): + r"""Compute the sample skewness of a data set. + + For normally distributed data, the skewness should be about zero. For + unimodal continuous distributions, a skewness value greater than zero means + that there is more weight in the right tail of the distribution. The + function `skewtest` can be used to determine if the skewness value + is close enough to zero, statistically speaking. + + Parameters + ---------- + a : ndarray + Input array. + axis : int or None, optional + Axis along which skewness is calculated. Default is 0. + If None, compute over the whole array `a`. + bias : bool, optional + If False, then the calculations are corrected for statistical bias. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + skewness : ndarray + The skewness of values along an axis, returning NaN where all values + are equal. + + Notes + ----- + The sample skewness is computed as the Fisher-Pearson coefficient + of skewness, i.e. + + .. math:: + + g_1=\frac{m_3}{m_2^{3/2}} + + where + + .. math:: + + m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i + + is the biased sample :math:`i\texttt{th}` central moment, and + :math:`\bar{x}` is + the sample mean. If ``bias`` is False, the calculations are + corrected for bias and the value computed is the adjusted + Fisher-Pearson standardized moment coefficient, i.e. + + .. math:: + + G_1=\frac{k_3}{k_2^{3/2}}= + \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}. + + References + ---------- + .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + Section 2.2.24.1 + + Examples + -------- + >>> from scipy.stats import skew + >>> skew([1, 2, 3, 4, 5]) + 0.0 + >>> skew([2, 8, 0, 4, 1, 9, 9, 0]) + 0.2650554122698573 + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + n = a.shape[axis] + + mean = xp.mean(a, axis=axis, keepdims=True) + mean_reduced = xp.squeeze(mean, axis=axis) # needed later + m2 = _moment(a, 2, axis, mean=mean, xp=xp) + m3 = _moment(a, 3, axis, mean=mean, xp=xp) + with np.errstate(all='ignore'): + eps = xp.finfo(m2.dtype).eps + zero = m2 <= (eps * mean_reduced)**2 + vals = xp.where(zero, xp.asarray(xp.nan), m3 / m2**1.5) + if not bias: + can_correct = ~zero & (n > 2) + if xp.any(can_correct): + m2 = m2[can_correct] + m3 = m3[can_correct] + nval = ((n - 1.0) * n)**0.5 / (n - 2.0) * m3 / m2**1.5 + vals[can_correct] = nval + + return vals[()] if vals.ndim == 0 else vals + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1 +) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'): + """Compute the kurtosis (Fisher or Pearson) of a dataset. + + Kurtosis is the fourth central moment divided by the square of the + variance. If Fisher's definition is used, then 3.0 is subtracted from + the result to give 0.0 for a normal distribution. + + If bias is False then the kurtosis is calculated using k statistics to + eliminate bias coming from biased moment estimators + + Use `kurtosistest` to see if result is close enough to normal. + + Parameters + ---------- + a : array + Data for which the kurtosis is calculated. + axis : int or None, optional + Axis along which the kurtosis is calculated. Default is 0. + If None, compute over the whole array `a`. + fisher : bool, optional + If True, Fisher's definition is used (normal ==> 0.0). If False, + Pearson's definition is used (normal ==> 3.0). + bias : bool, optional + If False, then the calculations are corrected for statistical bias. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. + + Returns + ------- + kurtosis : array + The kurtosis of values along an axis, returning NaN where all values + are equal. + + References + ---------- + .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + + Examples + -------- + In Fisher's definition, the kurtosis of the normal distribution is zero. + In the following example, the kurtosis is close to zero, because it was + calculated from the dataset, not from the continuous distribution. + + >>> import numpy as np + >>> from scipy.stats import norm, kurtosis + >>> data = norm.rvs(size=1000, random_state=3) + >>> kurtosis(data) + -0.06928694200380558 + + The distribution with a higher kurtosis has a heavier tail. + The zero valued kurtosis of the normal distribution in Fisher's definition + can serve as a reference point. + + >>> import matplotlib.pyplot as plt + >>> import scipy.stats as stats + >>> from scipy.stats import kurtosis + + >>> x = np.linspace(-5, 5, 100) + >>> ax = plt.subplot() + >>> distnames = ['laplace', 'norm', 'uniform'] + + >>> for distname in distnames: + ... if distname == 'uniform': + ... dist = getattr(stats, distname)(loc=-2, scale=4) + ... else: + ... dist = getattr(stats, distname) + ... data = dist.rvs(size=1000) + ... kur = kurtosis(data, fisher=True) + ... y = dist.pdf(x) + ... ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3))) + ... ax.legend() + + The Laplace distribution has a heavier tail than the normal distribution. + The uniform distribution (which has negative kurtosis) has the thinnest + tail. + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + n = a.shape[axis] + mean = xp.mean(a, axis=axis, keepdims=True) + mean_reduced = xp.squeeze(mean, axis=axis) # needed later + m2 = _moment(a, 2, axis, mean=mean, xp=xp) + m4 = _moment(a, 4, axis, mean=mean, xp=xp) + with np.errstate(all='ignore'): + zero = m2 <= (xp.finfo(m2.dtype).eps * mean_reduced)**2 + NaN = _get_nan(m4, xp=xp) + vals = xp.where(zero, NaN, m4 / m2**2.0) + + if not bias: + can_correct = ~zero & (n > 3) + if xp.any(can_correct): + m2 = m2[can_correct] + m4 = m4[can_correct] + nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0) + vals[can_correct] = nval + 3.0 + + vals = vals - 3 if fisher else vals + return vals[()] if vals.ndim == 0 else vals + + +DescribeResult = namedtuple('DescribeResult', + ('nobs', 'minmax', 'mean', 'variance', 'skewness', + 'kurtosis')) + + +def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'): + """Compute several descriptive statistics of the passed array. + + Parameters + ---------- + a : array_like + Input data. + axis : int or None, optional + Axis along which statistics are calculated. Default is 0. + If None, compute over the whole array `a`. + ddof : int, optional + Delta degrees of freedom (only for variance). Default is 1. + bias : bool, optional + If False, then the skewness and kurtosis calculations are corrected + for statistical bias. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + nobs : int or ndarray of ints + Number of observations (length of data along `axis`). + When 'omit' is chosen as nan_policy, the length along each axis + slice is counted separately. + minmax: tuple of ndarrays or floats + Minimum and maximum value of `a` along the given axis. + mean : ndarray or float + Arithmetic mean of `a` along the given axis. + variance : ndarray or float + Unbiased variance of `a` along the given axis; denominator is number + of observations minus one. + skewness : ndarray or float + Skewness of `a` along the given axis, based on moment calculations + with denominator equal to the number of observations, i.e. no degrees + of freedom correction. + kurtosis : ndarray or float + Kurtosis (Fisher) of `a` along the given axis. The kurtosis is + normalized so that it is zero for the normal distribution. No + degrees of freedom are used. + + Raises + ------ + ValueError + If size of `a` is 0. + + See Also + -------- + skew, kurtosis + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> a = np.arange(10) + >>> stats.describe(a) + DescribeResult(nobs=10, minmax=(0, 9), mean=4.5, + variance=9.166666666666666, skewness=0.0, + kurtosis=-1.2242424242424244) + >>> b = [[1, 2], [3, 4]] + >>> stats.describe(b) + DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])), + mean=array([2., 3.]), variance=array([2., 2.]), + skewness=array([0., 0.]), kurtosis=array([-2., -2.])) + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + contains_nan, nan_policy = _contains_nan(a, nan_policy) + + if contains_nan and nan_policy == 'omit': + # only NumPy gets here; `_contains_nan` raises error for the rest + a = ma.masked_invalid(a) + return mstats_basic.describe(a, axis, ddof, bias) + + if xp_size(a) == 0: + raise ValueError("The input must not be empty.") + + n = a.shape[axis] + mm = (xp.min(a, axis=axis), xp.max(a, axis=axis)) + m = xp.mean(a, axis=axis) + v = _var(a, axis=axis, ddof=ddof, xp=xp) + sk = skew(a, axis, bias=bias) + kurt = kurtosis(a, axis, bias=bias) + + return DescribeResult(n, mm, m, v, sk, kurt) + +##################################### +# NORMALITY TESTS # +##################################### + + +def _get_pvalue(statistic, distribution, alternative, symmetric=True, xp=None): + """Get p-value given the statistic, (continuous) distribution, and alternative""" + xp = array_namespace(statistic) if xp is None else xp + + if alternative == 'less': + pvalue = distribution.cdf(statistic) + elif alternative == 'greater': + pvalue = distribution.sf(statistic) + elif alternative == 'two-sided': + pvalue = 2 * (distribution.sf(xp.abs(statistic)) if symmetric + else xp.minimum(distribution.cdf(statistic), + distribution.sf(statistic))) + else: + message = "`alternative` must be 'less', 'greater', or 'two-sided'." + raise ValueError(message) + + return pvalue + + +SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(SkewtestResult, n_samples=1, too_small=7) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def skewtest(a, axis=0, nan_policy='propagate', alternative='two-sided'): + r"""Test whether the skew is different from the normal distribution. + + This function tests the null hypothesis that the skewness of + the population that the sample was drawn from is the same + as that of a corresponding normal distribution. + + Parameters + ---------- + a : array + The data to be tested. Must contain at least eight observations. + axis : int or None, optional + Axis along which statistics are calculated. Default is 0. + If None, compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the skewness of the distribution underlying the sample + is different from that of the normal distribution (i.e. 0) + * 'less': the skewness of the distribution underlying the sample + is less than that of the normal distribution + * 'greater': the skewness of the distribution underlying the sample + is greater than that of the normal distribution + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The computed z-score for this test. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_skewtest` : Extended example + + Notes + ----- + The sample size must be at least 8. + + References + ---------- + .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr., + "A suggestion for using powerful and informative tests of + normality", American Statistician 44, pp. 316-321, 1990. + + Examples + -------- + + >>> from scipy.stats import skewtest + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8]) + SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897) + >>> skewtest([2, 8, 0, 4, 1, 9, 9, 0]) + SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459) + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000]) + SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133) + >>> skewtest([100, 100, 100, 100, 100, 100, 100, 101]) + SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634) + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='less') + SkewtestResult(statistic=1.0108048609177787, pvalue=0.8439450819289052) + >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='greater') + SkewtestResult(statistic=1.0108048609177787, pvalue=0.15605491807109484) + + For a more detailed example, see :ref:`hypothesis_skewtest`. + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + b2 = skew(a, axis, _no_deco=True) + n = a.shape[axis] + if n < 8: + message = ("`skewtest` requires at least 8 observations; " + f"only {n=} observations were given.") + raise ValueError(message) + + y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2))) + beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) / + ((n-2.0) * (n+5) * (n+7) * (n+9))) + W2 = -1 + math.sqrt(2 * (beta2 - 1)) + delta = 1 / math.sqrt(0.5 * math.log(W2)) + alpha = math.sqrt(2.0 / (W2 - 1)) + y = xp.where(y == 0, xp.asarray(1, dtype=y.dtype), y) + Z = delta * xp.log(y / alpha + xp.sqrt((y / alpha)**2 + 1)) + + pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp) + + Z = Z[()] if Z.ndim == 0 else Z + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + return SkewtestResult(Z, pvalue) + + +KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(KurtosistestResult, n_samples=1, too_small=4) +def kurtosistest(a, axis=0, nan_policy='propagate', alternative='two-sided'): + r"""Test whether a dataset has normal kurtosis. + + This function tests the null hypothesis that the kurtosis + of the population from which the sample was drawn is that + of the normal distribution. + + Parameters + ---------- + a : array + Array of the sample data. Must contain at least five observations. + axis : int or None, optional + Axis along which to compute test. Default is 0. If None, + compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the kurtosis of the distribution underlying the sample + is different from that of the normal distribution + * 'less': the kurtosis of the distribution underlying the sample + is less than that of the normal distribution + * 'greater': the kurtosis of the distribution underlying the sample + is greater than that of the normal distribution + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The computed z-score for this test. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_kurtosistest` : Extended example + + Notes + ----- + Valid only for n>20. This function uses the method described in [1]_. + + References + ---------- + .. [1] F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis + statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.stats import kurtosistest + >>> kurtosistest(list(range(20))) + KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348) + >>> kurtosistest(list(range(20)), alternative='less') + KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.04402169166264174) + >>> kurtosistest(list(range(20)), alternative='greater') + KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.9559783083373583) + >>> rng = np.random.default_rng() + >>> s = rng.normal(0, 1, 1000) + >>> kurtosistest(s) + KurtosistestResult(statistic=-1.475047944490622, pvalue=0.14019965402996987) + + For a more detailed example, see :ref:`hypothesis_kurtosistest`. + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + n = a.shape[axis] + + if n < 5: + message = ("`kurtosistest` requires at least 5 observations; " + f"only {n=} observations were given.") + raise ValueError(message) + if n < 20: + message = ("`kurtosistest` p-value may be inaccurate with fewer than 20 " + f"observations; only {n=} observations were given.") + warnings.warn(message, stacklevel=2) + b2 = kurtosis(a, axis, fisher=False, _no_deco=True) + + E = 3.0*(n-1) / (n+1) + varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) # [1]_ Eq. 1 + x = (b2-E) / varb2**0.5 # [1]_ Eq. 4 + # [1]_ Eq. 2: + sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * ((6.0*(n+3)*(n+5)) + / (n*(n-2)*(n-3)))**0.5 + # [1]_ Eq. 3: + A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + (1+4.0/(sqrtbeta1**2))**0.5) + term1 = 1 - 2/(9.0*A) + denom = 1 + x * (2/(A-4.0))**0.5 + NaN = _get_nan(x, xp=xp) + term2 = xp_sign(denom) * xp.where(denom == 0.0, NaN, + ((1-2.0/A)/xp.abs(denom))**(1/3)) + if xp.any(denom == 0): + msg = ("Test statistic not defined in some cases due to division by " + "zero. Return nan in that case...") + warnings.warn(msg, RuntimeWarning, stacklevel=2) + + Z = (term1 - term2) / (2/(9.0*A))**0.5 # [1]_ Eq. 5 + + pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp) + + Z = Z[()] if Z.ndim == 0 else Z + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + return KurtosistestResult(Z, pvalue) + + +NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(NormaltestResult, n_samples=1, too_small=7) +def normaltest(a, axis=0, nan_policy='propagate'): + r"""Test whether a sample differs from a normal distribution. + + This function tests the null hypothesis that a sample comes + from a normal distribution. It is based on D'Agostino and + Pearson's [1]_, [2]_ test that combines skew and kurtosis to + produce an omnibus test of normality. + + Parameters + ---------- + a : array_like + The array containing the sample to be tested. Must contain + at least eight observations. + axis : int or None, optional + Axis along which to compute test. Default is 0. If None, + compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + statistic : float or array + ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and + ``k`` is the z-score returned by `kurtosistest`. + pvalue : float or array + A 2-sided chi squared probability for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_normaltest` : Extended example + + References + ---------- + .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for + moderate and large sample size", Biometrika, 58, 341-348 + .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from + normality", Biometrika, 60, 613-622 + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> pts = 1000 + >>> a = rng.normal(0, 1, size=pts) + >>> b = rng.normal(2, 1, size=pts) + >>> x = np.concatenate((a, b)) + >>> res = stats.normaltest(x) + >>> res.statistic + 53.619... # random + >>> res.pvalue + 2.273917413209226e-12 # random + + For a more detailed example, see :ref:`hypothesis_normaltest`. + """ + xp = array_namespace(a) + + s, _ = skewtest(a, axis, _no_deco=True) + k, _ = kurtosistest(a, axis, _no_deco=True) + statistic = s*s + k*k + + chi2 = _SimpleChi2(xp.asarray(2.)) + pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp) + + statistic = statistic[()] if statistic.ndim == 0 else statistic + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return NormaltestResult(statistic, pvalue) + + +@_axis_nan_policy_factory(SignificanceResult, default_axis=None) +def jarque_bera(x, *, axis=None): + r"""Perform the Jarque-Bera goodness of fit test on sample data. + + The Jarque-Bera test tests whether the sample data has the skewness and + kurtosis matching a normal distribution. + + Note that this test only works for a large enough number of data samples + (>2000) as the test statistic asymptotically has a Chi-squared distribution + with 2 degrees of freedom. + + Parameters + ---------- + x : array_like + Observations of a random variable. + axis : int or None, default: 0 + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear in + a corresponding element of the output. + If ``None``, the input will be raveled before computing the statistic. + + Returns + ------- + result : SignificanceResult + An object with the following attributes: + + statistic : float + The test statistic. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + :ref:`hypothesis_jarque_bera` : Extended example + + References + ---------- + .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality, + homoscedasticity and serial independence of regression residuals", + 6 Econometric Letters 255-259. + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = rng.normal(0, 1, 100000) + >>> jarque_bera_test = stats.jarque_bera(x) + >>> jarque_bera_test + Jarque_beraResult(statistic=3.3415184718131554, pvalue=0.18810419594996775) + >>> jarque_bera_test.statistic + 3.3415184718131554 + >>> jarque_bera_test.pvalue + 0.18810419594996775 + + For a more detailed example, see :ref:`hypothesis_jarque_bera`. + """ + xp = array_namespace(x) + x = xp.asarray(x) + if axis is None: + x = xp.reshape(x, (-1,)) + axis = 0 + + n = x.shape[axis] + if n == 0: + raise ValueError('At least one observation is required.') + + mu = xp.mean(x, axis=axis, keepdims=True) + diffx = x - mu + s = skew(diffx, axis=axis, _no_deco=True) + k = kurtosis(diffx, axis=axis, _no_deco=True) + statistic = n / 6 * (s**2 + k**2 / 4) + + chi2 = _SimpleChi2(xp.asarray(2.)) + pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp) + + statistic = statistic[()] if statistic.ndim == 0 else statistic + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return SignificanceResult(statistic, pvalue) + + +##################################### +# FREQUENCY FUNCTIONS # +##################################### + + +def scoreatpercentile(a, per, limit=(), interpolation_method='fraction', + axis=None): + """Calculate the score at a given percentile of the input sequence. + + For example, the score at ``per=50`` is the median. If the desired quantile + lies between two data points, we interpolate between them, according to + the value of `interpolation`. If the parameter `limit` is provided, it + should be a tuple (lower, upper) of two values. + + Parameters + ---------- + a : array_like + A 1-D array of values from which to extract score. + per : array_like + Percentile(s) at which to extract score. Values should be in range + [0,100]. + limit : tuple, optional + Tuple of two scalars, the lower and upper limits within which to + compute the percentile. Values of `a` outside + this (closed) interval will be ignored. + interpolation_method : {'fraction', 'lower', 'higher'}, optional + Specifies the interpolation method to use, + when the desired quantile lies between two data points `i` and `j` + The following options are available (default is 'fraction'): + + * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the + fractional part of the index surrounded by ``i`` and ``j`` + * 'lower': ``i`` + * 'higher': ``j`` + + axis : int, optional + Axis along which the percentiles are computed. Default is None. If + None, compute over the whole array `a`. + + Returns + ------- + score : float or ndarray + Score at percentile(s). + + See Also + -------- + percentileofscore, numpy.percentile + + Notes + ----- + This function will become obsolete in the future. + For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality + that `scoreatpercentile` provides. And it's significantly faster. + Therefore it's recommended to use `numpy.percentile` for users that have + numpy >= 1.9. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> a = np.arange(100) + >>> stats.scoreatpercentile(a, 50) + 49.5 + + """ + # adapted from NumPy's percentile function. When we require numpy >= 1.8, + # the implementation of this function can be replaced by np.percentile. + a = np.asarray(a) + if a.size == 0: + # empty array, return nan(s) with shape matching `per` + if np.isscalar(per): + return np.nan + else: + return np.full(np.asarray(per).shape, np.nan, dtype=np.float64) + + if limit: + a = a[(limit[0] <= a) & (a <= limit[1])] + + sorted_ = np.sort(a, axis=axis) + if axis is None: + axis = 0 + + return _compute_qth_percentile(sorted_, per, interpolation_method, axis) + + +# handle sequence of per's without calling sort multiple times +def _compute_qth_percentile(sorted_, per, interpolation_method, axis): + if not np.isscalar(per): + score = [_compute_qth_percentile(sorted_, i, + interpolation_method, axis) + for i in per] + return np.array(score) + + if not (0 <= per <= 100): + raise ValueError("percentile must be in the range [0, 100]") + + indexer = [slice(None)] * sorted_.ndim + idx = per / 100. * (sorted_.shape[axis] - 1) + + if int(idx) != idx: + # round fractional indices according to interpolation method + if interpolation_method == 'lower': + idx = int(np.floor(idx)) + elif interpolation_method == 'higher': + idx = int(np.ceil(idx)) + elif interpolation_method == 'fraction': + pass # keep idx as fraction and interpolate + else: + raise ValueError("interpolation_method can only be 'fraction', " + "'lower' or 'higher'") + + i = int(idx) + if i == idx: + indexer[axis] = slice(i, i + 1) + weights = array(1) + sumval = 1.0 + else: + indexer[axis] = slice(i, i + 2) + j = i + 1 + weights = array([(j - idx), (idx - i)], float) + wshape = [1] * sorted_.ndim + wshape[axis] = 2 + weights.shape = wshape + sumval = weights.sum() + + # Use np.add.reduce (== np.sum but a little faster) to coerce data type + return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval + + +def percentileofscore(a, score, kind='rank', nan_policy='propagate'): + """Compute the percentile rank of a score relative to a list of scores. + + A `percentileofscore` of, for example, 80% means that 80% of the + scores in `a` are below the given score. In the case of gaps or + ties, the exact definition depends on the optional keyword, `kind`. + + Parameters + ---------- + a : array_like + A 1-D array to which `score` is compared. + score : array_like + Scores to compute percentiles for. + kind : {'rank', 'weak', 'strict', 'mean'}, optional + Specifies the interpretation of the resulting score. + The following options are available (default is 'rank'): + + * 'rank': Average percentage ranking of score. In case of multiple + matches, average the percentage rankings of all matching scores. + * 'weak': This kind corresponds to the definition of a cumulative + distribution function. A percentileofscore of 80% means that 80% + of values are less than or equal to the provided score. + * 'strict': Similar to "weak", except that only values that are + strictly less than the given score are counted. + * 'mean': The average of the "weak" and "strict" scores, often used + in testing. See https://en.wikipedia.org/wiki/Percentile_rank + nan_policy : {'propagate', 'raise', 'omit'}, optional + Specifies how to treat `nan` values in `a`. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan (for each value in `score`). + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + pcos : float + Percentile-position of score (0-100) relative to `a`. + + See Also + -------- + numpy.percentile + scipy.stats.scoreatpercentile, scipy.stats.rankdata + + Examples + -------- + Three-quarters of the given values lie below a given score: + + >>> import numpy as np + >>> from scipy import stats + >>> stats.percentileofscore([1, 2, 3, 4], 3) + 75.0 + + With multiple matches, note how the scores of the two matches, 0.6 + and 0.8 respectively, are averaged: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3) + 70.0 + + Only 2/5 values are strictly less than 3: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict') + 40.0 + + But 4/5 values are less than or equal to 3: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak') + 80.0 + + The average between the weak and the strict scores is: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean') + 60.0 + + Score arrays (of any dimensionality) are supported: + + >>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3]) + array([40., 70.]) + + The inputs can be infinite: + + >>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf]) + array([75., 75., 100.]) + + If `a` is empty, then the resulting percentiles are all `nan`: + + >>> stats.percentileofscore([], [1, 2]) + array([nan, nan]) + """ + + a = np.asarray(a) + n = len(a) + score = np.asarray(score) + + # Nan treatment + cna, npa = _contains_nan(a, nan_policy) + cns, nps = _contains_nan(score, nan_policy) + + if (cna or cns) and nan_policy == 'raise': + raise ValueError("The input contains nan values") + + if cns: + # If a score is nan, then the output should be nan + # (also if nan_policy is "omit", because it only applies to `a`) + score = ma.masked_where(np.isnan(score), score) + + if cna: + if nan_policy == "omit": + # Don't count nans + a = ma.masked_where(np.isnan(a), a) + n = a.count() + + if nan_policy == "propagate": + # All outputs should be nans + n = 0 + + # Cannot compare to empty list ==> nan + if n == 0: + perct = np.full_like(score, np.nan, dtype=np.float64) + + else: + # Prepare broadcasting + score = score[..., None] + + def count(x): + return np.count_nonzero(x, -1) + + # Main computations/logic + if kind == 'rank': + left = count(a < score) + right = count(a <= score) + plus1 = left < right + perct = (left + right + plus1) * (50.0 / n) + elif kind == 'strict': + perct = count(a < score) * (100.0 / n) + elif kind == 'weak': + perct = count(a <= score) * (100.0 / n) + elif kind == 'mean': + left = count(a < score) + right = count(a <= score) + perct = (left + right) * (50.0 / n) + else: + raise ValueError( + "kind can only be 'rank', 'strict', 'weak' or 'mean'") + + # Re-insert nan values + perct = ma.filled(perct, np.nan) + + if perct.ndim == 0: + return perct[()] + return perct + + +HistogramResult = namedtuple('HistogramResult', + ('count', 'lowerlimit', 'binsize', 'extrapoints')) + + +def _histogram(a, numbins=10, defaultlimits=None, weights=None, + printextras=False): + """Create a histogram. + + Separate the range into several bins and return the number of instances + in each bin. + + Parameters + ---------- + a : array_like + Array of scores which will be put into bins. + numbins : int, optional + The number of bins to use for the histogram. Default is 10. + defaultlimits : tuple (lower, upper), optional + The lower and upper values for the range of the histogram. + If no value is given, a range slightly larger than the range of the + values in a is used. Specifically ``(a.min() - s, a.max() + s)``, + where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. + weights : array_like, optional + The weights for each value in `a`. Default is None, which gives each + value a weight of 1.0 + printextras : bool, optional + If True, if there are extra points (i.e. the points that fall outside + the bin limits) a warning is raised saying how many of those points + there are. Default is False. + + Returns + ------- + count : ndarray + Number of points (or sum of weights) in each bin. + lowerlimit : float + Lowest value of histogram, the lower limit of the first bin. + binsize : float + The size of the bins (all bins have the same size). + extrapoints : int + The number of points outside the range of the histogram. + + See Also + -------- + numpy.histogram + + Notes + ----- + This histogram is based on numpy's histogram but has a larger range by + default if default limits is not set. + + """ + a = np.ravel(a) + if defaultlimits is None: + if a.size == 0: + # handle empty arrays. Undetermined range, so use 0-1. + defaultlimits = (0, 1) + else: + # no range given, so use values in `a` + data_min = a.min() + data_max = a.max() + # Have bins extend past min and max values slightly + s = (data_max - data_min) / (2. * (numbins - 1.)) + defaultlimits = (data_min - s, data_max + s) + + # use numpy's histogram method to compute bins + hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits, + weights=weights) + # hist are not always floats, convert to keep with old output + hist = np.array(hist, dtype=float) + # fixed width for bins is assumed, as numpy's histogram gives + # fixed width bins for int values for 'bins' + binsize = bin_edges[1] - bin_edges[0] + # calculate number of extra points + extrapoints = len([v for v in a + if defaultlimits[0] > v or v > defaultlimits[1]]) + if extrapoints > 0 and printextras: + warnings.warn(f"Points outside given histogram range = {extrapoints}", + stacklevel=3,) + + return HistogramResult(hist, defaultlimits[0], binsize, extrapoints) + + +CumfreqResult = namedtuple('CumfreqResult', + ('cumcount', 'lowerlimit', 'binsize', + 'extrapoints')) + + +def cumfreq(a, numbins=10, defaultreallimits=None, weights=None): + """Return a cumulative frequency histogram, using the histogram function. + + A cumulative histogram is a mapping that counts the cumulative number of + observations in all of the bins up to the specified bin. + + Parameters + ---------- + a : array_like + Input array. + numbins : int, optional + The number of bins to use for the histogram. Default is 10. + defaultreallimits : tuple (lower, upper), optional + The lower and upper values for the range of the histogram. + If no value is given, a range slightly larger than the range of the + values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``, + where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. + weights : array_like, optional + The weights for each value in `a`. Default is None, which gives each + value a weight of 1.0 + + Returns + ------- + cumcount : ndarray + Binned values of cumulative frequency. + lowerlimit : float + Lower real limit + binsize : float + Width of each bin. + extrapoints : int + Extra points. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = [1, 4, 2, 1, 3, 1] + >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5)) + >>> res.cumcount + array([ 1., 2., 3., 3.]) + >>> res.extrapoints + 3 + + Create a normal distribution with 1000 random values + + >>> samples = stats.norm.rvs(size=1000, random_state=rng) + + Calculate cumulative frequencies + + >>> res = stats.cumfreq(samples, numbins=25) + + Calculate space of values for x + + >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size, + ... res.cumcount.size) + + Plot histogram and cumulative histogram + + >>> fig = plt.figure(figsize=(10, 4)) + >>> ax1 = fig.add_subplot(1, 2, 1) + >>> ax2 = fig.add_subplot(1, 2, 2) + >>> ax1.hist(samples, bins=25) + >>> ax1.set_title('Histogram') + >>> ax2.bar(x, res.cumcount, width=res.binsize) + >>> ax2.set_title('Cumulative histogram') + >>> ax2.set_xlim([x.min(), x.max()]) + + >>> plt.show() + + """ + h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights) + cumhist = np.cumsum(h * 1, axis=0) + return CumfreqResult(cumhist, l, b, e) + + +RelfreqResult = namedtuple('RelfreqResult', + ('frequency', 'lowerlimit', 'binsize', + 'extrapoints')) + + +def relfreq(a, numbins=10, defaultreallimits=None, weights=None): + """Return a relative frequency histogram, using the histogram function. + + A relative frequency histogram is a mapping of the number of + observations in each of the bins relative to the total of observations. + + Parameters + ---------- + a : array_like + Input array. + numbins : int, optional + The number of bins to use for the histogram. Default is 10. + defaultreallimits : tuple (lower, upper), optional + The lower and upper values for the range of the histogram. + If no value is given, a range slightly larger than the range of the + values in a is used. Specifically ``(a.min() - s, a.max() + s)``, + where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. + weights : array_like, optional + The weights for each value in `a`. Default is None, which gives each + value a weight of 1.0 + + Returns + ------- + frequency : ndarray + Binned values of relative frequency. + lowerlimit : float + Lower real limit. + binsize : float + Width of each bin. + extrapoints : int + Extra points. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> a = np.array([2, 4, 1, 2, 3, 2]) + >>> res = stats.relfreq(a, numbins=4) + >>> res.frequency + array([ 0.16666667, 0.5 , 0.16666667, 0.16666667]) + >>> np.sum(res.frequency) # relative frequencies should add up to 1 + 1.0 + + Create a normal distribution with 1000 random values + + >>> samples = stats.norm.rvs(size=1000, random_state=rng) + + Calculate relative frequencies + + >>> res = stats.relfreq(samples, numbins=25) + + Calculate space of values for x + + >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size, + ... res.frequency.size) + + Plot relative frequency histogram + + >>> fig = plt.figure(figsize=(5, 4)) + >>> ax = fig.add_subplot(1, 1, 1) + >>> ax.bar(x, res.frequency, width=res.binsize) + >>> ax.set_title('Relative frequency histogram') + >>> ax.set_xlim([x.min(), x.max()]) + + >>> plt.show() + + """ + a = np.asanyarray(a) + h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights) + h = h / a.shape[0] + + return RelfreqResult(h, l, b, e) + + +##################################### +# VARIABILITY FUNCTIONS # +##################################### + +def obrientransform(*samples): + """Compute the O'Brien transform on input data (any number of arrays). + + Used to test for homogeneity of variance prior to running one-way stats. + Each array in ``*samples`` is one level of a factor. + If `f_oneway` is run on the transformed data and found significant, + the variances are unequal. From Maxwell and Delaney [1]_, p.112. + + Parameters + ---------- + sample1, sample2, ... : array_like + Any number of arrays. + + Returns + ------- + obrientransform : ndarray + Transformed data for use in an ANOVA. The first dimension + of the result corresponds to the sequence of transformed + arrays. If the arrays given are all 1-D of the same length, + the return value is a 2-D array; otherwise it is a 1-D array + of type object, with each element being an ndarray. + + Raises + ------ + ValueError + If the mean of the transformed data is not equal to the original + variance, indicating a lack of convergence in the O'Brien transform. + + References + ---------- + .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and + Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990. + + Examples + -------- + We'll test the following data sets for differences in their variance. + + >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10] + >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15] + + Apply the O'Brien transform to the data. + + >>> from scipy.stats import obrientransform + >>> tx, ty = obrientransform(x, y) + + Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the + transformed data. + + >>> from scipy.stats import f_oneway + >>> F, p = f_oneway(tx, ty) + >>> p + 0.1314139477040335 + + If we require that ``p < 0.05`` for significance, we cannot conclude + that the variances are different. + + """ + TINY = np.sqrt(np.finfo(float).eps) + + # `arrays` will hold the transformed arguments. + arrays = [] + sLast = None + + for sample in samples: + a = np.asarray(sample) + n = len(a) + mu = np.mean(a) + sq = (a - mu)**2 + sumsq = sq.sum() + + # The O'Brien transform. + t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2)) + + # Check that the mean of the transformed data is equal to the + # original variance. + var = sumsq / (n - 1) + if abs(var - np.mean(t)) > TINY: + raise ValueError('Lack of convergence in obrientransform.') + + arrays.append(t) + sLast = a.shape + + if sLast: + for arr in arrays[:-1]: + if sLast != arr.shape: + return np.array(arrays, dtype=object) + return np.array(arrays) + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, too_small=1 +) +def sem(a, axis=0, ddof=1, nan_policy='propagate'): + """Compute standard error of the mean. + + Calculate the standard error of the mean (or standard error of + measurement) of the values in the input array. + + Parameters + ---------- + a : array_like + An array containing the values for which the standard error is + returned. Must contain at least two observations. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Delta degrees-of-freedom. How many degrees of freedom to adjust + for bias in limited samples relative to the population estimate + of variance. Defaults to 1. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + s : ndarray or float + The standard error of the mean in the sample(s), along the input axis. + + Notes + ----- + The default value for `ddof` is different to the default (0) used by other + ddof containing routines, such as np.std and np.nanstd. + + Examples + -------- + Find standard error along the first axis: + + >>> import numpy as np + >>> from scipy import stats + >>> a = np.arange(20).reshape(5,4) + >>> stats.sem(a) + array([ 2.8284, 2.8284, 2.8284, 2.8284]) + + Find standard error across the whole array, using n degrees of freedom: + + >>> stats.sem(a, axis=None, ddof=0) + 1.2893796958227628 + + """ + xp = array_namespace(a) + if axis is None: + a = xp.reshape(a, (-1,)) + axis = 0 + a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp) + n = a.shape[axis] + s = xp.std(a, axis=axis, correction=ddof) / n**0.5 + return s + + +def _isconst(x): + """ + Check if all values in x are the same. nans are ignored. + + x must be a 1d array. + + The return value is a 1d array with length 1, so it can be used + in np.apply_along_axis. + """ + y = x[~np.isnan(x)] + if y.size == 0: + return np.array([True]) + else: + return (y[0] == y).all(keepdims=True) + + +def zscore(a, axis=0, ddof=0, nan_policy='propagate'): + """ + Compute the z score. + + Compute the z score of each value in the sample, relative to the + sample mean and standard deviation. + + Parameters + ---------- + a : array_like + An array like object containing the sample data. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Degrees of freedom correction in the calculation of the + standard deviation. Default is 0. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. Note that when the value is 'omit', + nans in the input also propagate to the output, but they do not affect + the z-scores computed for the non-nan values. + + Returns + ------- + zscore : array_like + The z-scores, standardized by mean and standard deviation of + input array `a`. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.std : Arithmetic standard deviation + scipy.stats.gzscore : Geometric standard score + + Notes + ----- + This function preserves ndarray subclasses, and works also with + matrices and masked arrays (it uses `asanyarray` instead of + `asarray` for parameters). + + References + ---------- + .. [1] "Standard score", *Wikipedia*, + https://en.wikipedia.org/wiki/Standard_score. + .. [2] Huck, S. W., Cross, T. L., Clark, S. B, "Overcoming misconceptions + about Z-scores", Teaching Statistics, vol. 8, pp. 38-40, 1986 + + Examples + -------- + >>> import numpy as np + >>> a = np.array([ 0.7972, 0.0767, 0.4383, 0.7866, 0.8091, + ... 0.1954, 0.6307, 0.6599, 0.1065, 0.0508]) + >>> from scipy import stats + >>> stats.zscore(a) + array([ 1.1273, -1.247 , -0.0552, 1.0923, 1.1664, -0.8559, 0.5786, + 0.6748, -1.1488, -1.3324]) + + Computing along a specified axis, using n-1 degrees of freedom + (``ddof=1``) to calculate the standard deviation: + + >>> b = np.array([[ 0.3148, 0.0478, 0.6243, 0.4608], + ... [ 0.7149, 0.0775, 0.6072, 0.9656], + ... [ 0.6341, 0.1403, 0.9759, 0.4064], + ... [ 0.5918, 0.6948, 0.904 , 0.3721], + ... [ 0.0921, 0.2481, 0.1188, 0.1366]]) + >>> stats.zscore(b, axis=1, ddof=1) + array([[-0.19264823, -1.28415119, 1.07259584, 0.40420358], + [ 0.33048416, -1.37380874, 0.04251374, 1.00081084], + [ 0.26796377, -1.12598418, 1.23283094, -0.37481053], + [-0.22095197, 0.24468594, 1.19042819, -1.21416216], + [-0.82780366, 1.4457416 , -0.43867764, -0.1792603 ]]) + + An example with ``nan_policy='omit'``: + + >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15], + ... [14.95, 16.06, 121.25, 94.35, 29.81]]) + >>> stats.zscore(x, axis=1, nan_policy='omit') + array([[-1.13490897, -0.37830299, nan, -0.08718406, 1.60039602], + [-0.91611681, -0.89090508, 1.4983032 , 0.88731639, -0.5785977 ]]) + """ + return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy) + + +def gzscore(a, *, axis=0, ddof=0, nan_policy='propagate'): + """ + Compute the geometric standard score. + + Compute the geometric z score of each strictly positive value in the + sample, relative to the geometric mean and standard deviation. + Mathematically the geometric z score can be evaluated as:: + + gzscore = log(a/gmu) / log(gsigma) + + where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard + deviation). + + Parameters + ---------- + a : array_like + Sample data. + axis : int or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Degrees of freedom correction in the calculation of the + standard deviation. Default is 0. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. Note that when the value is 'omit', + nans in the input also propagate to the output, but they do not affect + the geometric z scores computed for the non-nan values. + + Returns + ------- + gzscore : array_like + The geometric z scores, standardized by geometric mean and geometric + standard deviation of input array `a`. + + See Also + -------- + gmean : Geometric mean + gstd : Geometric standard deviation + zscore : Standard score + + Notes + ----- + This function preserves ndarray subclasses, and works also with + matrices and masked arrays (it uses ``asanyarray`` instead of + ``asarray`` for parameters). + + .. versionadded:: 1.8 + + References + ---------- + .. [1] "Geometric standard score", *Wikipedia*, + https://en.wikipedia.org/wiki/Geometric_standard_deviation#Geometric_standard_score. + + Examples + -------- + Draw samples from a log-normal distribution: + + >>> import numpy as np + >>> from scipy.stats import zscore, gzscore + >>> import matplotlib.pyplot as plt + + >>> rng = np.random.default_rng() + >>> mu, sigma = 3., 1. # mean and standard deviation + >>> x = rng.lognormal(mu, sigma, size=500) + + Display the histogram of the samples: + + >>> fig, ax = plt.subplots() + >>> ax.hist(x, 50) + >>> plt.show() + + Display the histogram of the samples standardized by the classical zscore. + Distribution is rescaled but its shape is unchanged. + + >>> fig, ax = plt.subplots() + >>> ax.hist(zscore(x), 50) + >>> plt.show() + + Demonstrate that the distribution of geometric zscores is rescaled and + quasinormal: + + >>> fig, ax = plt.subplots() + >>> ax.hist(gzscore(x), 50) + >>> plt.show() + + """ + xp = array_namespace(a) + a = _convert_common_float(a, xp=xp) + log = ma.log if isinstance(a, ma.MaskedArray) else xp.log + return zscore(log(a), axis=axis, ddof=ddof, nan_policy=nan_policy) + + +def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'): + """ + Calculate the relative z-scores. + + Return an array of z-scores, i.e., scores that are standardized to + zero mean and unit variance, where mean and variance are calculated + from the comparison array. + + Parameters + ---------- + scores : array_like + The input for which z-scores are calculated. + compare : array_like + The input from which the mean and standard deviation of the + normalization are taken; assumed to have the same dimension as + `scores`. + axis : int or None, optional + Axis over which mean and variance of `compare` are calculated. + Default is 0. If None, compute over the whole array `scores`. + ddof : int, optional + Degrees of freedom correction in the calculation of the + standard deviation. Default is 0. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle the occurrence of nans in `compare`. + 'propagate' returns nan, 'raise' raises an exception, 'omit' + performs the calculations ignoring nan values. Default is + 'propagate'. Note that when the value is 'omit', nans in `scores` + also propagate to the output, but they do not affect the z-scores + computed for the non-nan values. + + Returns + ------- + zscore : array_like + Z-scores, in the same shape as `scores`. + + Notes + ----- + This function preserves ndarray subclasses, and works also with + matrices and masked arrays (it uses `asanyarray` instead of + `asarray` for parameters). + + Examples + -------- + >>> from scipy.stats import zmap + >>> a = [0.5, 2.0, 2.5, 3] + >>> b = [0, 1, 2, 3, 4] + >>> zmap(a, b) + array([-1.06066017, 0. , 0.35355339, 0.70710678]) + + """ + # The docstring explicitly states that it preserves subclasses. + # Let's table deprecating that and just get the array API version + # working. + + like_zscore = (scores is compare) + xp = array_namespace(scores, compare) + scores, compare = _convert_common_float(scores, compare, xp=xp) + + with warnings.catch_warnings(): + if like_zscore: # zscore should not emit SmallSampleWarning + warnings.simplefilter('ignore', SmallSampleWarning) + + mn = _xp_mean(compare, axis=axis, keepdims=True, nan_policy=nan_policy) + std = _xp_var(compare, axis=axis, correction=ddof, + keepdims=True, nan_policy=nan_policy)**0.5 + + with np.errstate(invalid='ignore', divide='ignore'): + z = _demean(scores, mn, axis, xp=xp, precision_warning=False) / std + + # If we know that scores and compare are identical, we can infer that + # some slices should have NaNs. + if like_zscore: + eps = xp.finfo(z.dtype).eps + zero = std <= xp.abs(eps * mn) + zero = xp.broadcast_to(zero, z.shape) + z[zero] = xp.nan + + return z + + +def gstd(a, axis=0, ddof=1): + r""" + Calculate the geometric standard deviation of an array. + + The geometric standard deviation describes the spread of a set of numbers + where the geometric mean is preferred. It is a multiplicative factor, and + so a dimensionless quantity. + + It is defined as the exponential of the standard deviation of the + natural logarithms of the observations. + + Parameters + ---------- + a : array_like + An array containing finite, strictly positive, real numbers. + + .. deprecated:: 1.14.0 + Support for masked array input was deprecated in + SciPy 1.14.0 and will be removed in version 1.16.0. + + axis : int, tuple or None, optional + Axis along which to operate. Default is 0. If None, compute over + the whole array `a`. + ddof : int, optional + Degree of freedom correction in the calculation of the + geometric standard deviation. Default is 1. + + Returns + ------- + gstd : ndarray or float + An array of the geometric standard deviation. If `axis` is None or `a` + is a 1d array a float is returned. + + See Also + -------- + gmean : Geometric mean + numpy.std : Standard deviation + gzscore : Geometric standard score + + Notes + ----- + Mathematically, the sample geometric standard deviation :math:`s_G` can be + defined in terms of the natural logarithms of the observations + :math:`y_i = \log(x_i)`: + + .. math:: + + s_G = \exp(s), \quad s = \sqrt{\frac{1}{n - d} \sum_{i=1}^n (y_i - \bar y)^2} + + where :math:`n` is the number of observations, :math:`d` is the adjustment `ddof` + to the degrees of freedom, and :math:`\bar y` denotes the mean of the natural + logarithms of the observations. Note that the default ``ddof=1`` is different from + the default value used by similar functions, such as `numpy.std` and `numpy.var`. + + When an observation is infinite, the geometric standard deviation is + NaN (undefined). Non-positive observations will also produce NaNs in the + output because the *natural* logarithm (as opposed to the *complex* + logarithm) is defined and finite only for positive reals. + The geometric standard deviation is sometimes confused with the exponential + of the standard deviation, ``exp(std(a))``. Instead, the geometric standard + deviation is ``exp(std(log(a)))``. + + References + ---------- + .. [1] "Geometric standard deviation", *Wikipedia*, + https://en.wikipedia.org/wiki/Geometric_standard_deviation. + .. [2] Kirkwood, T. B., "Geometric means and measures of dispersion", + Biometrics, vol. 35, pp. 908-909, 1979 + + Examples + -------- + Find the geometric standard deviation of a log-normally distributed sample. + Note that the standard deviation of the distribution is one; on a + log scale this evaluates to approximately ``exp(1)``. + + >>> import numpy as np + >>> from scipy.stats import gstd + >>> rng = np.random.default_rng() + >>> sample = rng.lognormal(mean=0, sigma=1, size=1000) + >>> gstd(sample) + 2.810010162475324 + + Compute the geometric standard deviation of a multidimensional array and + of a given axis. + + >>> a = np.arange(1, 25).reshape(2, 3, 4) + >>> gstd(a, axis=None) + 2.2944076136018947 + >>> gstd(a, axis=2) + array([[1.82424757, 1.22436866, 1.13183117], + [1.09348306, 1.07244798, 1.05914985]]) + >>> gstd(a, axis=(1,2)) + array([2.12939215, 1.22120169]) + + """ + a = np.asanyarray(a) + if isinstance(a, ma.MaskedArray): + message = ("`gstd` support for masked array input was deprecated in " + "SciPy 1.14.0 and will be removed in version 1.16.0.") + warnings.warn(message, DeprecationWarning, stacklevel=2) + log = ma.log + else: + log = np.log + + with np.errstate(invalid='ignore', divide='ignore'): + res = np.exp(np.std(log(a), axis=axis, ddof=ddof)) + + if (a <= 0).any(): + message = ("The geometric standard deviation is only defined if all elements " + "are greater than or equal to zero; otherwise, the result is NaN.") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + return res + +# Private dictionary initialized only once at module level +# See https://en.wikipedia.org/wiki/Robust_measures_of_scale +_scale_conversions = {'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)} + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, + default_axis=None, override={'nan_propagation': False} +) +def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate', + interpolation='linear', keepdims=False): + r""" + Compute the interquartile range of the data along the specified axis. + + The interquartile range (IQR) is the difference between the 75th and + 25th percentile of the data. It is a measure of the dispersion + similar to standard deviation or variance, but is much more robust + against outliers [2]_. + + The ``rng`` parameter allows this function to compute other + percentile ranges than the actual IQR. For example, setting + ``rng=(0, 100)`` is equivalent to `numpy.ptp`. + + The IQR of an empty array is `np.nan`. + + .. versionadded:: 0.18.0 + + Parameters + ---------- + x : array_like + Input array or object that can be converted to an array. + axis : int or sequence of int, optional + Axis along which the range is computed. The default is to + compute the IQR for the entire array. + rng : Two-element sequence containing floats in range of [0,100] optional + Percentiles over which to compute the range. Each must be + between 0 and 100, inclusive. The default is the true IQR: + ``(25, 75)``. The order of the elements is not important. + scale : scalar or str or array_like of reals, optional + The numerical value of scale will be divided out of the final + result. The following string value is also recognized: + + * 'normal' : Scale by + :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`. + + The default is 1.0. + Array-like `scale` of real dtype is also allowed, as long + as it broadcasts correctly to the output such that + ``out / scale`` is a valid operation. The output dimensions + depend on the input array, `x`, the `axis` argument, and the + `keepdims` flag. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + interpolation : str, optional + + Specifies the interpolation method to use when the percentile + boundaries lie between two data points ``i`` and ``j``. + The following options are available (default is 'linear'): + + * 'linear': ``i + (j - i)*fraction``, where ``fraction`` is the + fractional part of the index surrounded by ``i`` and ``j``. + * 'lower': ``i``. + * 'higher': ``j``. + * 'nearest': ``i`` or ``j`` whichever is nearest. + * 'midpoint': ``(i + j)/2``. + + For NumPy >= 1.22.0, the additional options provided by the ``method`` + keyword of `numpy.percentile` are also valid. + + keepdims : bool, optional + If this is set to True, the reduced axes are left in the + result as dimensions with size one. With this option, the result + will broadcast correctly against the original array `x`. + + Returns + ------- + iqr : scalar or ndarray + If ``axis=None``, a scalar is returned. If the input contains + integers or floats of smaller precision than ``np.float64``, then the + output data-type is ``np.float64``. Otherwise, the output data-type is + the same as that of the input. + + See Also + -------- + numpy.std, numpy.var + + References + ---------- + .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range + .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale + .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import iqr + >>> x = np.array([[10, 7, 4], [3, 2, 1]]) + >>> x + array([[10, 7, 4], + [ 3, 2, 1]]) + >>> iqr(x) + 4.0 + >>> iqr(x, axis=0) + array([ 3.5, 2.5, 1.5]) + >>> iqr(x, axis=1) + array([ 3., 1.]) + >>> iqr(x, axis=1, keepdims=True) + array([[ 3.], + [ 1.]]) + + """ + x = asarray(x) + + # This check prevents percentile from raising an error later. Also, it is + # consistent with `np.var` and `np.std`. + if not x.size: + return _get_nan(x) + + # An error may be raised here, so fail-fast, before doing lengthy + # computations, even though `scale` is not used until later + if isinstance(scale, str): + scale_key = scale.lower() + if scale_key not in _scale_conversions: + raise ValueError(f"{scale} not a valid scale for `iqr`") + scale = _scale_conversions[scale_key] + + # Select the percentile function to use based on nans and policy + contains_nan, nan_policy = _contains_nan(x, nan_policy) + + if contains_nan and nan_policy == 'omit': + percentile_func = np.nanpercentile + else: + percentile_func = np.percentile + + if len(rng) != 2: + raise TypeError("quantile range must be two element sequence") + + if np.isnan(rng).any(): + raise ValueError("range must not contain NaNs") + + rng = sorted(rng) + pct = percentile_func(x, rng, axis=axis, method=interpolation, + keepdims=keepdims) + out = np.subtract(pct[1], pct[0]) + + if scale != 1.0: + out /= scale + + return out + + +def _mad_1d(x, center, nan_policy): + # Median absolute deviation for 1-d array x. + # This is a helper function for `median_abs_deviation`; it assumes its + # arguments have been validated already. In particular, x must be a + # 1-d numpy array, center must be callable, and if nan_policy is not + # 'propagate', it is assumed to be 'omit', because 'raise' is handled + # in `median_abs_deviation`. + # No warning is generated if x is empty or all nan. + isnan = np.isnan(x) + if isnan.any(): + if nan_policy == 'propagate': + return np.nan + x = x[~isnan] + if x.size == 0: + # MAD of an empty array is nan. + return np.nan + # Edge cases have been handled, so do the basic MAD calculation. + med = center(x) + mad = np.median(np.abs(x - med)) + return mad + + +def median_abs_deviation(x, axis=0, center=np.median, scale=1.0, + nan_policy='propagate'): + r""" + Compute the median absolute deviation of the data along the given axis. + + The median absolute deviation (MAD, [1]_) computes the median over the + absolute deviations from the median. It is a measure of dispersion + similar to the standard deviation but more robust to outliers [2]_. + + The MAD of an empty array is ``np.nan``. + + .. versionadded:: 1.5.0 + + Parameters + ---------- + x : array_like + Input array or object that can be converted to an array. + axis : int or None, optional + Axis along which the range is computed. Default is 0. If None, compute + the MAD over the entire array. + center : callable, optional + A function that will return the central value. The default is to use + np.median. Any user defined function used will need to have the + function signature ``func(arr, axis)``. + scale : scalar or str, optional + The numerical value of scale will be divided out of the final + result. The default is 1.0. The string "normal" is also accepted, + and results in `scale` being the inverse of the standard normal + quantile function at 0.75, which is approximately 0.67449. + Array-like scale is also allowed, as long as it broadcasts correctly + to the output such that ``out / scale`` is a valid operation. The + output dimensions depend on the input array, `x`, and the `axis` + argument. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + mad : scalar or ndarray + If ``axis=None``, a scalar is returned. If the input contains + integers or floats of smaller precision than ``np.float64``, then the + output data-type is ``np.float64``. Otherwise, the output data-type is + the same as that of the input. + + See Also + -------- + numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean, + scipy.stats.tstd, scipy.stats.tvar + + Notes + ----- + The `center` argument only affects the calculation of the central value + around which the MAD is calculated. That is, passing in ``center=np.mean`` + will calculate the MAD around the mean - it will not calculate the *mean* + absolute deviation. + + The input array may contain `inf`, but if `center` returns `inf`, the + corresponding MAD for that data will be `nan`. + + References + ---------- + .. [1] "Median absolute deviation", + https://en.wikipedia.org/wiki/Median_absolute_deviation + .. [2] "Robust measures of scale", + https://en.wikipedia.org/wiki/Robust_measures_of_scale + + Examples + -------- + When comparing the behavior of `median_abs_deviation` with ``np.std``, + the latter is affected when we change a single value of an array to have an + outlier value while the MAD hardly changes: + + >>> import numpy as np + >>> from scipy import stats + >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456) + >>> x.std() + 0.9973906394005013 + >>> stats.median_abs_deviation(x) + 0.82832610097857 + >>> x[0] = 345.6 + >>> x.std() + 34.42304872314415 + >>> stats.median_abs_deviation(x) + 0.8323442311590675 + + Axis handling example: + + >>> x = np.array([[10, 7, 4], [3, 2, 1]]) + >>> x + array([[10, 7, 4], + [ 3, 2, 1]]) + >>> stats.median_abs_deviation(x) + array([3.5, 2.5, 1.5]) + >>> stats.median_abs_deviation(x, axis=None) + 2.0 + + Scale normal example: + + >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456) + >>> stats.median_abs_deviation(x) + 1.3487398527041636 + >>> stats.median_abs_deviation(x, scale='normal') + 1.9996446978061115 + + """ + if not callable(center): + raise TypeError("The argument 'center' must be callable. The given " + f"value {repr(center)} is not callable.") + + # An error may be raised here, so fail-fast, before doing lengthy + # computations, even though `scale` is not used until later + if isinstance(scale, str): + if scale.lower() == 'normal': + scale = 0.6744897501960817 # special.ndtri(0.75) + else: + raise ValueError(f"{scale} is not a valid scale value.") + + x = asarray(x) + + # Consistent with `np.var` and `np.std`. + if not x.size: + if axis is None: + return np.nan + nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis) + if nan_shape == (): + # Return nan, not array(nan) + return np.nan + return np.full(nan_shape, np.nan) + + contains_nan, nan_policy = _contains_nan(x, nan_policy) + + if contains_nan: + if axis is None: + mad = _mad_1d(x.ravel(), center, nan_policy) + else: + mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy) + else: + if axis is None: + med = center(x, axis=None) + mad = np.median(np.abs(x - med)) + else: + # Wrap the call to center() in expand_dims() so it acts like + # keepdims=True was used. + med = np.expand_dims(center(x, axis=axis), axis) + mad = np.median(np.abs(x - med), axis=axis) + + return mad / scale + + +##################################### +# TRIMMING FUNCTIONS # +##################################### + + +SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper')) + + +def sigmaclip(a, low=4., high=4.): + """Perform iterative sigma-clipping of array elements. + + Starting from the full sample, all elements outside the critical range are + removed, i.e. all elements of the input array `c` that satisfy either of + the following conditions:: + + c < mean(c) - std(c)*low + c > mean(c) + std(c)*high + + The iteration continues with the updated sample until no + elements are outside the (updated) range. + + Parameters + ---------- + a : array_like + Data array, will be raveled if not 1-D. + low : float, optional + Lower bound factor of sigma clipping. Default is 4. + high : float, optional + Upper bound factor of sigma clipping. Default is 4. + + Returns + ------- + clipped : ndarray + Input array with clipped elements removed. + lower : float + Lower threshold value use for clipping. + upper : float + Upper threshold value use for clipping. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import sigmaclip + >>> a = np.concatenate((np.linspace(9.5, 10.5, 31), + ... np.linspace(0, 20, 5))) + >>> fact = 1.5 + >>> c, low, upp = sigmaclip(a, fact, fact) + >>> c + array([ 9.96666667, 10. , 10.03333333, 10. ]) + >>> c.var(), c.std() + (0.00055555555555555165, 0.023570226039551501) + >>> low, c.mean() - fact*c.std(), c.min() + (9.9646446609406727, 9.9646446609406727, 9.9666666666666668) + >>> upp, c.mean() + fact*c.std(), c.max() + (10.035355339059327, 10.035355339059327, 10.033333333333333) + + >>> a = np.concatenate((np.linspace(9.5, 10.5, 11), + ... np.linspace(-100, -50, 3))) + >>> c, low, upp = sigmaclip(a, 1.8, 1.8) + >>> (c == np.linspace(9.5, 10.5, 11)).all() + True + + """ + c = np.asarray(a).ravel() + delta = 1 + while delta: + c_std = c.std() + c_mean = c.mean() + size = c.size + critlower = c_mean - c_std * low + critupper = c_mean + c_std * high + c = c[(c >= critlower) & (c <= critupper)] + delta = size - c.size + + return SigmaclipResult(c, critlower, critupper) + + +def trimboth(a, proportiontocut, axis=0): + """Slice off a proportion of items from both ends of an array. + + Slice off the passed proportion of items from both ends of the passed + array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and** + rightmost 10% of scores). The trimmed values are the lowest and + highest ones. + Slice off less if proportion results in a non-integer slice index (i.e. + conservatively slices off `proportiontocut`). + + Parameters + ---------- + a : array_like + Data to trim. + proportiontocut : float + Proportion (in range 0-1) of total data set to trim of each end. + axis : int or None, optional + Axis along which to trim data. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + out : ndarray + Trimmed version of array `a`. The order of the trimmed content + is undefined. + + See Also + -------- + trim_mean + + Examples + -------- + Create an array of 10 values and trim 10% of those values from each end: + + >>> import numpy as np + >>> from scipy import stats + >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> stats.trimboth(a, 0.1) + array([1, 3, 2, 4, 5, 6, 7, 8]) + + Note that the elements of the input array are trimmed by value, but the + output array is not necessarily sorted. + + The proportion to trim is rounded down to the nearest integer. For + instance, trimming 25% of the values from each end of an array of 10 + values will return an array of 6 values: + + >>> b = np.arange(10) + >>> stats.trimboth(b, 1/4).shape + (6,) + + Multidimensional arrays can be trimmed along any axis or across the entire + array: + + >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9] + >>> d = np.array([a, b, c]) + >>> stats.trimboth(d, 0.4, axis=0).shape + (1, 10) + >>> stats.trimboth(d, 0.4, axis=1).shape + (3, 2) + >>> stats.trimboth(d, 0.4, axis=None).shape + (6,) + + """ + a = np.asarray(a) + + if a.size == 0: + return a + + if axis is None: + a = a.ravel() + axis = 0 + + nobs = a.shape[axis] + lowercut = int(proportiontocut * nobs) + uppercut = nobs - lowercut + if (lowercut >= uppercut): + raise ValueError("Proportion too big.") + + atmp = np.partition(a, (lowercut, uppercut - 1), axis) + + sl = [slice(None)] * atmp.ndim + sl[axis] = slice(lowercut, uppercut) + return atmp[tuple(sl)] + + +def trim1(a, proportiontocut, tail='right', axis=0): + """Slice off a proportion from ONE end of the passed array distribution. + + If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost' + 10% of scores. The lowest or highest values are trimmed (depending on + the tail). + Slice off less if proportion results in a non-integer slice index + (i.e. conservatively slices off `proportiontocut` ). + + Parameters + ---------- + a : array_like + Input array. + proportiontocut : float + Fraction to cut off of 'left' or 'right' of distribution. + tail : {'left', 'right'}, optional + Defaults to 'right'. + axis : int or None, optional + Axis along which to trim data. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + trim1 : ndarray + Trimmed version of array `a`. The order of the trimmed content is + undefined. + + Examples + -------- + Create an array of 10 values and trim 20% of its lowest values: + + >>> import numpy as np + >>> from scipy import stats + >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> stats.trim1(a, 0.2, 'left') + array([2, 4, 3, 5, 6, 7, 8, 9]) + + Note that the elements of the input array are trimmed by value, but the + output array is not necessarily sorted. + + The proportion to trim is rounded down to the nearest integer. For + instance, trimming 25% of the values from an array of 10 values will + return an array of 8 values: + + >>> b = np.arange(10) + >>> stats.trim1(b, 1/4).shape + (8,) + + Multidimensional arrays can be trimmed along any axis or across the entire + array: + + >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9] + >>> d = np.array([a, b, c]) + >>> stats.trim1(d, 0.8, axis=0).shape + (1, 10) + >>> stats.trim1(d, 0.8, axis=1).shape + (3, 2) + >>> stats.trim1(d, 0.8, axis=None).shape + (6,) + + """ + a = np.asarray(a) + if axis is None: + a = a.ravel() + axis = 0 + + nobs = a.shape[axis] + + # avoid possible corner case + if proportiontocut >= 1: + return [] + + if tail.lower() == 'right': + lowercut = 0 + uppercut = nobs - int(proportiontocut * nobs) + + elif tail.lower() == 'left': + lowercut = int(proportiontocut * nobs) + uppercut = nobs + + atmp = np.partition(a, (lowercut, uppercut - 1), axis) + + sl = [slice(None)] * atmp.ndim + sl[axis] = slice(lowercut, uppercut) + return atmp[tuple(sl)] + + +def trim_mean(a, proportiontocut, axis=0): + """Return mean of array after trimming a specified fraction of extreme values + + Removes the specified proportion of elements from *each* end of the + sorted array, then computes the mean of the remaining elements. + + Parameters + ---------- + a : array_like + Input array. + proportiontocut : float + Fraction of the most positive and most negative elements to remove. + When the specified proportion does not result in an integer number of + elements, the number of elements to trim is rounded down. + axis : int or None, default: 0 + Axis along which the trimmed means are computed. + If None, compute over the raveled array. + + Returns + ------- + trim_mean : ndarray + Mean of trimmed array. + + See Also + -------- + trimboth : Remove a proportion of elements from each end of an array. + tmean : Compute the mean after trimming values outside specified limits. + + Notes + ----- + For 1-D array `a`, `trim_mean` is approximately equivalent to the following + calculation:: + + import numpy as np + a = np.sort(a) + m = int(proportiontocut * len(a)) + np.mean(a[m: len(a) - m]) + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = [1, 2, 3, 5] + >>> stats.trim_mean(x, 0.25) + 2.5 + + When the specified proportion does not result in an integer number of + elements, the number of elements to trim is rounded down. + + >>> stats.trim_mean(x, 0.24999) == np.mean(x) + True + + Use `axis` to specify the axis along which the calculation is performed. + + >>> x2 = [[1, 2, 3, 5], + ... [10, 20, 30, 50]] + >>> stats.trim_mean(x2, 0.25) + array([ 5.5, 11. , 16.5, 27.5]) + >>> stats.trim_mean(x2, 0.25, axis=1) + array([ 2.5, 25. ]) + + """ + a = np.asarray(a) + + if a.size == 0: + return np.nan + + if axis is None: + a = a.ravel() + axis = 0 + + nobs = a.shape[axis] + lowercut = int(proportiontocut * nobs) + uppercut = nobs - lowercut + if (lowercut > uppercut): + raise ValueError("Proportion too big.") + + atmp = np.partition(a, (lowercut, uppercut - 1), axis) + + sl = [slice(None)] * atmp.ndim + sl[axis] = slice(lowercut, uppercut) + return np.mean(atmp[tuple(sl)], axis=axis) + + +F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue')) + + +def _create_f_oneway_nan_result(shape, axis, samples): + """ + This is a helper function for f_oneway for creating the return values + in certain degenerate conditions. It creates return values that are + all nan with the appropriate shape for the given `shape` and `axis`. + """ + axis = normalize_axis_index(axis, len(shape)) + shp = shape[:axis] + shape[axis+1:] + f = np.full(shp, fill_value=_get_nan(*samples)) + prob = f.copy() + return F_onewayResult(f[()], prob[()]) + + +def _first(arr, axis): + """Return arr[..., 0:1, ...] where 0:1 is in the `axis` position.""" + return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis) + + +def _f_oneway_is_too_small(samples, kwargs=None, axis=-1): + message = f"At least two samples are required; got {len(samples)}." + if len(samples) < 2: + raise TypeError(message) + + # Check this after forming alldata, so shape errors are detected + # and reported before checking for 0 length inputs. + if any(sample.shape[axis] == 0 for sample in samples): + return True + + # Must have at least one group with length greater than 1. + if all(sample.shape[axis] == 1 for sample in samples): + msg = ('all input arrays have length 1. f_oneway requires that at ' + 'least one input has length greater than 1.') + warnings.warn(SmallSampleWarning(msg), stacklevel=2) + return True + + return False + + +@_axis_nan_policy_factory( + F_onewayResult, n_samples=None, too_small=_f_oneway_is_too_small) +def f_oneway(*samples, axis=0): + """Perform one-way ANOVA. + + The one-way ANOVA tests the null hypothesis that two or more groups have + the same population mean. The test is applied to samples from two or + more groups, possibly with differing sizes. + + Parameters + ---------- + sample1, sample2, ... : array_like + The sample measurements for each group. There must be at least + two arguments. If the arrays are multidimensional, then all the + dimensions of the array must be the same except for `axis`. + axis : int, optional + Axis of the input arrays along which the test is applied. + Default is 0. + + Returns + ------- + statistic : float + The computed F statistic of the test. + pvalue : float + The associated p-value from the F distribution. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Emitted if all values within each of the input arrays are identical. + In this case the F statistic is either infinite or isn't defined, + so ``np.inf`` or ``np.nan`` is returned. + + RuntimeWarning + Emitted if the length of any input array is 0, or if all the input + arrays have length 1. ``np.nan`` is returned for the F statistic + and the p-value in these cases. + + Notes + ----- + The ANOVA test has important assumptions that must be satisfied in order + for the associated p-value to be valid. + + 1. The samples are independent. + 2. Each sample is from a normally distributed population. + 3. The population standard deviations of the groups are all equal. This + property is known as homoscedasticity. + + If these assumptions are not true for a given set of data, it may still + be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or + the Alexander-Govern test (`scipy.stats.alexandergovern`) although with + some loss of power. + + The length of each group must be at least one, and there must be at + least one group with length greater than one. If these conditions + are not satisfied, a warning is generated and (``np.nan``, ``np.nan``) + is returned. + + If all values in each group are identical, and there exist at least two + groups with different values, the function generates a warning and + returns (``np.inf``, 0). + + If all values in all groups are the same, function generates a warning + and returns (``np.nan``, ``np.nan``). + + The algorithm is from Heiman [2]_, pp.394-7. + + References + ---------- + .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics", + Chapter 14, 2014, http://vassarstats.net/textbook/ + + .. [2] G.W. Heiman, "Understanding research methods and statistics: An + integrated introduction for psychology", Houghton, Mifflin and + Company, 2001. + + .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA. + http://www.biostathandbook.com/onewayanova.html + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import f_oneway + + Here are some data [3]_ on a shell measurement (the length of the anterior + adductor muscle scar, standardized by dividing by length) in the mussel + Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon; + Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a + much larger data set used in McDonald et al. (1991). + + >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735, + ... 0.0659, 0.0923, 0.0836] + >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835, + ... 0.0725] + >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105] + >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764, + ... 0.0689] + >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045] + >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne) + F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544) + + `f_oneway` accepts multidimensional input arrays. When the inputs + are multidimensional and `axis` is not given, the test is performed + along the first axis of the input arrays. For the following data, the + test is performed three times, once for each column. + + >>> a = np.array([[9.87, 9.03, 6.81], + ... [7.18, 8.35, 7.00], + ... [8.39, 7.58, 7.68], + ... [7.45, 6.33, 9.35], + ... [6.41, 7.10, 9.33], + ... [8.00, 8.24, 8.44]]) + >>> b = np.array([[6.35, 7.30, 7.16], + ... [6.65, 6.68, 7.63], + ... [5.72, 7.73, 6.72], + ... [7.01, 9.19, 7.41], + ... [7.75, 7.87, 8.30], + ... [6.90, 7.97, 6.97]]) + >>> c = np.array([[3.31, 8.77, 1.01], + ... [8.25, 3.24, 3.62], + ... [6.32, 8.81, 5.19], + ... [7.48, 8.83, 8.91], + ... [8.59, 6.01, 6.07], + ... [3.07, 9.72, 7.48]]) + >>> F = f_oneway(a, b, c) + >>> F.statistic + array([1.75676344, 0.03701228, 3.76439349]) + >>> F.pvalue + array([0.20630784, 0.96375203, 0.04733157]) + + """ + if len(samples) < 2: + raise TypeError('at least two inputs are required;' + f' got {len(samples)}.') + + # ANOVA on N groups, each in its own array + num_groups = len(samples) + + # We haven't explicitly validated axis, but if it is bad, this call of + # np.concatenate will raise np.exceptions.AxisError. The call will raise + # ValueError if the dimensions of all the arrays, except the axis + # dimension, are not the same. + alldata = np.concatenate(samples, axis=axis) + bign = alldata.shape[axis] + + # Check if the inputs are too small + if _f_oneway_is_too_small(samples): + return _create_f_oneway_nan_result(alldata.shape, axis, samples) + + # Check if all values within each group are identical, and if the common + # value in at least one group is different from that in another group. + # Based on https://github.com/scipy/scipy/issues/11669 + + # If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ..., + # then is_const is a boolean array with shape (num_groups, ...). + # It is True if the values within the groups along the axis slice are + # identical. In the typical case where each input array is 1-d, is_const is + # a 1-d array with length num_groups. + is_const = np.concatenate( + [(_first(sample, axis) == sample).all(axis=axis, + keepdims=True) + for sample in samples], + axis=axis + ) + + # all_const is a boolean array with shape (...) (see previous comment). + # It is True if the values within each group along the axis slice are + # the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]). + all_const = is_const.all(axis=axis) + if all_const.any(): + msg = ("Each of the input arrays is constant; " + "the F statistic is not defined or infinite") + warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2) + + # all_same_const is True if all the values in the groups along the axis=0 + # slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]). + all_same_const = (_first(alldata, axis) == alldata).all(axis=axis) + + # Determine the mean of the data, and subtract that from all inputs to a + # variance (via sum_of_sq / sq_of_sum) calculation. Variance is invariant + # to a shift in location, and centering all data around zero vastly + # improves numerical stability. + offset = alldata.mean(axis=axis, keepdims=True) + alldata = alldata - offset + + normalized_ss = _square_of_sums(alldata, axis=axis) / bign + + sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss + + ssbn = 0 + for sample in samples: + smo_ss = _square_of_sums(sample - offset, axis=axis) + ssbn = ssbn + smo_ss / sample.shape[axis] + + # Naming: variables ending in bn/b are for "between treatments", wn/w are + # for "within treatments" + ssbn = ssbn - normalized_ss + sswn = sstot - ssbn + dfbn = num_groups - 1 + dfwn = bign - num_groups + msb = ssbn / dfbn + msw = sswn / dfwn + with np.errstate(divide='ignore', invalid='ignore'): + f = msb / msw + + prob = special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf + + # Fix any f values that should be inf or nan because the corresponding + # inputs were constant. + if np.isscalar(f): + if all_same_const: + f = np.nan + prob = np.nan + elif all_const: + f = np.inf + prob = 0.0 + else: + f[all_const] = np.inf + prob[all_const] = 0.0 + f[all_same_const] = np.nan + prob[all_same_const] = np.nan + + return F_onewayResult(f, prob) + + +@dataclass +class AlexanderGovernResult: + statistic: float + pvalue: float + + +@_axis_nan_policy_factory( + AlexanderGovernResult, n_samples=None, + result_to_tuple=lambda x: (x.statistic, x.pvalue), + too_small=1 +) +def alexandergovern(*samples, nan_policy='propagate', axis=0): + """Performs the Alexander Govern test. + + The Alexander-Govern approximation tests the equality of k independent + means in the face of heterogeneity of variance. The test is applied to + samples from two or more groups, possibly with differing sizes. + + Parameters + ---------- + sample1, sample2, ... : array_like + The sample measurements for each group. There must be at least + two samples, and each sample must contain at least two observations. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + res : AlexanderGovernResult + An object with attributes: + + statistic : float + The computed A statistic of the test. + pvalue : float + The associated p-value from the chi-squared distribution. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Raised if an input is a constant array. The statistic is not defined + in this case, so ``np.nan`` is returned. + + See Also + -------- + f_oneway : one-way ANOVA + + Notes + ----- + The use of this test relies on several assumptions. + + 1. The samples are independent. + 2. Each sample is from a normally distributed population. + 3. Unlike `f_oneway`, this test does not assume on homoscedasticity, + instead relaxing the assumption of equal variances. + + Input samples must be finite, one dimensional, and with size greater than + one. + + References + ---------- + .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler + Approximation for ANOVA under Variance Heterogeneity." Journal + of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101. + JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020. + + Examples + -------- + >>> from scipy.stats import alexandergovern + + Here are some data on annual percentage rate of interest charged on + new car loans at nine of the largest banks in four American cities + taken from the National Institute of Standards and Technology's + ANOVA dataset. + + We use `alexandergovern` to test the null hypothesis that all cities + have the same mean APR against the alternative that the cities do not + all have the same mean APR. We decide that a significance level of 5% + is required to reject the null hypothesis in favor of the alternative. + + >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5] + >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9] + >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5] + >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25, + ... 11.89] + >>> alexandergovern(atlanta, chicago, houston, memphis) + AlexanderGovernResult(statistic=4.65087071883494, + pvalue=0.19922132490385214) + + The p-value is 0.1992, indicating a nearly 20% chance of observing + such an extreme value of the test statistic under the null hypothesis. + This exceeds 5%, so we do not reject the null hypothesis in favor of + the alternative. + + """ + samples = _alexandergovern_input_validation(samples, nan_policy, axis) + + # The following formula numbers reference the equation described on + # page 92 by Alexander, Govern. Formulas 5, 6, and 7 describe other + # tests that serve as the basis for equation (8) but are not needed + # to perform the test. + + # precalculate mean and length of each sample + lengths = [sample.shape[-1] for sample in samples] + means = np.asarray([_xp_mean(sample, axis=-1) for sample in samples]) + + # (1) determine standard error of the mean for each sample + se2 = [(_xp_var(sample, correction=1, axis=-1) / length) + for sample, length in zip(samples, lengths)] + standard_errors_squared = np.asarray(se2) + standard_errors = standard_errors_squared**0.5 + + # Special case: statistic is NaN when variance is zero + eps = np.finfo(standard_errors.dtype).eps + zero = standard_errors <= np.abs(eps * means) + NaN = np.asarray(np.nan, dtype=standard_errors.dtype) + standard_errors = np.where(zero, NaN, standard_errors) + + # (2) define a weight for each sample + inv_sq_se = 1 / standard_errors_squared + weights = inv_sq_se / np.sum(inv_sq_se, axis=0, keepdims=True) + + # (3) determine variance-weighted estimate of the common mean + var_w = np.sum(weights * means, axis=0, keepdims=True) + + # (4) determine one-sample t statistic for each group + t_stats = _demean(means, var_w, axis=0, xp=np) / standard_errors + + # calculate parameters to be used in transformation + v = np.asarray(lengths) - 1 + # align along 0th axis, which corresponds with separate samples + v = np.reshape(v, (-1,) + (1,)*(t_stats.ndim-1)) + a = v - .5 + b = 48 * a**2 + c = (a * np.log(1 + (t_stats ** 2)/v))**.5 + + # (8) perform a normalizing transformation on t statistic + z = (c + ((c**3 + 3*c)/b) - + ((4*c**7 + 33*c**5 + 240*c**3 + 855*c) / + (b**2*10 + 8*b*c**4 + 1000*b))) + + # (9) calculate statistic + A = np.sum(z**2, axis=0) + + # "[the p value is determined from] central chi-square random deviates + # with k - 1 degrees of freedom". Alexander, Govern (94) + df = len(samples) - 1 + chi2 = _SimpleChi2(df) + p = _get_pvalue(A, chi2, alternative='greater', symmetric=False, xp=np) + return AlexanderGovernResult(A, p) + + +def _alexandergovern_input_validation(samples, nan_policy, axis): + if len(samples) < 2: + raise TypeError(f"2 or more inputs required, got {len(samples)}") + + for sample in samples: + if sample.shape[axis] <= 1: + raise ValueError("Input sample size must be greater than one.") + + samples = [np.moveaxis(sample, axis, -1) for sample in samples] + + return samples + + +def _pearsonr_fisher_ci(r, n, confidence_level, alternative): + """ + Compute the confidence interval for Pearson's R. + + Fisher's transformation is used to compute the confidence interval + (https://en.wikipedia.org/wiki/Fisher_transformation). + """ + xp = array_namespace(r) + + with np.errstate(divide='ignore'): + zr = xp.atanh(r) + + ones = xp.ones_like(r) + n = xp.asarray(n, dtype=r.dtype) + confidence_level = xp.asarray(confidence_level, dtype=r.dtype) + if n > 3: + se = xp.sqrt(1 / (n - 3)) + if alternative == "two-sided": + h = special.ndtri(0.5 + confidence_level/2) + zlo = zr - h*se + zhi = zr + h*se + rlo = xp.tanh(zlo) + rhi = xp.tanh(zhi) + elif alternative == "less": + h = special.ndtri(confidence_level) + zhi = zr + h*se + rhi = xp.tanh(zhi) + rlo = -ones + else: + # alternative == "greater": + h = special.ndtri(confidence_level) + zlo = zr - h*se + rlo = xp.tanh(zlo) + rhi = ones + else: + rlo, rhi = -ones, ones + + rlo = rlo[()] if rlo.ndim == 0 else rlo + rhi = rhi[()] if rhi.ndim == 0 else rhi + return ConfidenceInterval(low=rlo, high=rhi) + + +def _pearsonr_bootstrap_ci(confidence_level, method, x, y, alternative, axis): + """ + Compute the confidence interval for Pearson's R using the bootstrap. + """ + def statistic(x, y, axis): + statistic, _ = pearsonr(x, y, axis=axis) + return statistic + + res = bootstrap((x, y), statistic, confidence_level=confidence_level, axis=axis, + paired=True, alternative=alternative, **method._asdict()) + # for one-sided confidence intervals, bootstrap gives +/- inf on one side + res.confidence_interval = np.clip(res.confidence_interval, -1, 1) + + return ConfidenceInterval(*res.confidence_interval) + + +ConfidenceInterval = namedtuple('ConfidenceInterval', ['low', 'high']) + +PearsonRResultBase = _make_tuple_bunch('PearsonRResultBase', + ['statistic', 'pvalue'], []) + + +class PearsonRResult(PearsonRResultBase): + """ + Result of `scipy.stats.pearsonr` + + Attributes + ---------- + statistic : float + Pearson product-moment correlation coefficient. + pvalue : float + The p-value associated with the chosen alternative. + + Methods + ------- + confidence_interval + Computes the confidence interval of the correlation + coefficient `statistic` for the given confidence level. + + """ + def __init__(self, statistic, pvalue, alternative, n, x, y, axis): + super().__init__(statistic, pvalue) + self._alternative = alternative + self._n = n + self._x = x + self._y = y + self._axis = axis + + # add alias for consistency with other correlation functions + self.correlation = statistic + + def confidence_interval(self, confidence_level=0.95, method=None): + """ + The confidence interval for the correlation coefficient. + + Compute the confidence interval for the correlation coefficient + ``statistic`` with the given confidence level. + + If `method` is not provided, + The confidence interval is computed using the Fisher transformation + F(r) = arctanh(r) [1]_. When the sample pairs are drawn from a + bivariate normal distribution, F(r) approximately follows a normal + distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the + length of the original samples along the calculation axis. When + ``n <= 3``, this approximation does not yield a finite, real standard + error, so we define the confidence interval to be -1 to 1. + + If `method` is an instance of `BootstrapMethod`, the confidence + interval is computed using `scipy.stats.bootstrap` with the provided + configuration options and other appropriate settings. In some cases, + confidence limits may be NaN due to a degenerate resample, and this is + typical for very small samples (~6 observations). + + Parameters + ---------- + confidence_level : float + The confidence level for the calculation of the correlation + coefficient confidence interval. Default is 0.95. + + method : BootstrapMethod, optional + Defines the method used to compute the confidence interval. See + method description for details. + + .. versionadded:: 1.11.0 + + Returns + ------- + ci : namedtuple + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + References + ---------- + .. [1] "Pearson correlation coefficient", Wikipedia, + https://en.wikipedia.org/wiki/Pearson_correlation_coefficient + """ + if isinstance(method, BootstrapMethod): + xp = array_namespace(self._x) + message = ('`method` must be `None` if `pearsonr` ' + 'arguments were not NumPy arrays.') + if not is_numpy(xp): + raise ValueError(message) + + ci = _pearsonr_bootstrap_ci(confidence_level, method, self._x, self._y, + self._alternative, self._axis) + elif method is None: + ci = _pearsonr_fisher_ci(self.statistic, self._n, confidence_level, + self._alternative) + else: + message = ('`method` must be an instance of `BootstrapMethod` ' + 'or None.') + raise ValueError(message) + return ci + + +def pearsonr(x, y, *, alternative='two-sided', method=None, axis=0): + r""" + Pearson correlation coefficient and p-value for testing non-correlation. + + The Pearson correlation coefficient [1]_ measures the linear relationship + between two datasets. Like other correlation + coefficients, this one varies between -1 and +1 with 0 implying no + correlation. Correlations of -1 or +1 imply an exact linear relationship. + Positive correlations imply that as x increases, so does y. Negative + correlations imply that as x increases, y decreases. + + This function also performs a test of the null hypothesis that the + distributions underlying the samples are uncorrelated and normally + distributed. (See Kowalski [3]_ + for a discussion of the effects of non-normality of the input on the + distribution of the correlation coefficient.) + The p-value roughly indicates the probability of an uncorrelated system + producing datasets that have a Pearson correlation at least as extreme + as the one computed from these datasets. + + Parameters + ---------- + x : array_like + Input array. + y : array_like + Input array. + axis : int or None, default + Axis along which to perform the calculation. Default is 0. + If None, ravel both arrays before performing the calculation. + + .. versionadded:: 1.13.0 + alternative : {'two-sided', 'greater', 'less'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the correlation is nonzero + * 'less': the correlation is negative (less than zero) + * 'greater': the correlation is positive (greater than zero) + + .. versionadded:: 1.9.0 + method : ResamplingMethod, optional + Defines the method used to compute the p-value. If `method` is an + instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is + computed using + `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the + provided configuration options and other appropriate settings. + Otherwise, the p-value is computed as documented in the notes. + + .. versionadded:: 1.11.0 + + Returns + ------- + result : `~scipy.stats._result_classes.PearsonRResult` + An object with the following attributes: + + statistic : float + Pearson product-moment correlation coefficient. + pvalue : float + The p-value associated with the chosen alternative. + + The object has the following method: + + confidence_interval(confidence_level, method) + This computes the confidence interval of the correlation + coefficient `statistic` for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. If `method` is not provided, the + confidence interval is computed using the Fisher transformation + [1]_. If `method` is an instance of `BootstrapMethod`, the + confidence interval is computed using `scipy.stats.bootstrap` with + the provided configuration options and other appropriate settings. + In some cases, confidence limits may be NaN due to a degenerate + resample, and this is typical for very small samples (~6 + observations). + + Raises + ------ + ValueError + If `x` and `y` do not have length at least 2. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Raised if an input is a constant array. The correlation coefficient + is not defined in this case, so ``np.nan`` is returned. + + `~scipy.stats.NearConstantInputWarning` + Raised if an input is "nearly" constant. The array ``x`` is considered + nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``. + Numerical errors in the calculation ``x - mean(x)`` in this case might + result in an inaccurate calculation of r. + + See Also + -------- + spearmanr : Spearman rank-order correlation coefficient. + kendalltau : Kendall's tau, a correlation measure for ordinal data. + + Notes + ----- + The correlation coefficient is calculated as follows: + + .. math:: + + r = \frac{\sum (x - m_x) (y - m_y)} + {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}} + + where :math:`m_x` is the mean of the vector x and :math:`m_y` is + the mean of the vector y. + + Under the assumption that x and y are drawn from + independent normal distributions (so the population correlation coefficient + is 0), the probability density function of the sample correlation + coefficient r is ([1]_, [2]_): + + .. math:: + f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)} + + where n is the number of samples, and B is the beta function. This + is sometimes referred to as the exact distribution of r. This is + the distribution that is used in `pearsonr` to compute the p-value when + the `method` parameter is left at its default value (None). + The distribution is a beta distribution on the interval [-1, 1], + with equal shape parameters a = b = n/2 - 1. In terms of SciPy's + implementation of the beta distribution, the distribution of r is:: + + dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2) + + The default p-value returned by `pearsonr` is a two-sided p-value. For a + given sample with correlation coefficient r, the p-value is + the probability that abs(r') of a random sample x' and y' drawn from + the population with zero correlation would be greater than or equal + to abs(r). In terms of the object ``dist`` shown above, the p-value + for a given r and length n can be computed as:: + + p = 2*dist.cdf(-abs(r)) + + When n is 2, the above continuous distribution is not well-defined. + One can interpret the limit of the beta distribution as the shape + parameters a and b approach a = b = 0 as a discrete distribution with + equal probability masses at r = 1 and r = -1. More directly, one + can observe that, given the data x = [x1, x2] and y = [y1, y2], and + assuming x1 != x2 and y1 != y2, the only possible values for r are 1 + and -1. Because abs(r') for any sample x' and y' with length 2 will + be 1, the two-sided p-value for a sample of length 2 is always 1. + + For backwards compatibility, the object that is returned also behaves + like a tuple of length two that holds the statistic and the p-value. + + References + ---------- + .. [1] "Pearson correlation coefficient", Wikipedia, + https://en.wikipedia.org/wiki/Pearson_correlation_coefficient + .. [2] Student, "Probable error of a correlation coefficient", + Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310. + .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution + of the Sample Product-Moment Correlation Coefficient" + Journal of the Royal Statistical Society. Series C (Applied + Statistics), Vol. 21, No. 1 (1972), pp. 1-12. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x, y = [1, 2, 3, 4, 5, 6, 7], [10, 9, 2.5, 6, 4, 3, 2] + >>> res = stats.pearsonr(x, y) + >>> res + PearsonRResult(statistic=-0.828503883588428, pvalue=0.021280260007523286) + + To perform an exact permutation version of the test: + + >>> rng = np.random.default_rng(7796654889291491997) + >>> method = stats.PermutationMethod(n_resamples=np.inf, random_state=rng) + >>> stats.pearsonr(x, y, method=method) + PearsonRResult(statistic=-0.828503883588428, pvalue=0.028174603174603175) + + To perform the test under the null hypothesis that the data were drawn from + *uniform* distributions: + + >>> method = stats.MonteCarloMethod(rvs=(rng.uniform, rng.uniform)) + >>> stats.pearsonr(x, y, method=method) + PearsonRResult(statistic=-0.828503883588428, pvalue=0.0188) + + To produce an asymptotic 90% confidence interval: + + >>> res.confidence_interval(confidence_level=0.9) + ConfidenceInterval(low=-0.9644331982722841, high=-0.3460237473272273) + + And for a bootstrap confidence interval: + + >>> method = stats.BootstrapMethod(method='BCa', rng=rng) + >>> res.confidence_interval(confidence_level=0.9, method=method) + ConfidenceInterval(low=-0.9983163756488651, high=-0.22771001702132443) # may vary + + If N-dimensional arrays are provided, multiple tests are performed in a + single call according to the same conventions as most `scipy.stats` functions: + + >>> rng = np.random.default_rng(2348246935601934321) + >>> x = rng.standard_normal((8, 15)) + >>> y = rng.standard_normal((8, 15)) + >>> stats.pearsonr(x, y, axis=0).statistic.shape # between corresponding columns + (15,) + >>> stats.pearsonr(x, y, axis=1).statistic.shape # between corresponding rows + (8,) + + To perform all pairwise comparisons between slices of the arrays, + use standard NumPy broadcasting techniques. For instance, to compute the + correlation between all pairs of rows: + + >>> stats.pearsonr(x[:, np.newaxis, :], y, axis=-1).statistic.shape + (8, 8) + + There is a linear dependence between x and y if y = a + b*x + e, where + a,b are constants and e is a random error term, assumed to be independent + of x. For simplicity, assume that x is standard normal, a=0, b=1 and let + e follow a normal distribution with mean zero and standard deviation s>0. + + >>> rng = np.random.default_rng() + >>> s = 0.5 + >>> x = stats.norm.rvs(size=500, random_state=rng) + >>> e = stats.norm.rvs(scale=s, size=500, random_state=rng) + >>> y = x + e + >>> stats.pearsonr(x, y).statistic + 0.9001942438244763 + + This should be close to the exact value given by + + >>> 1/np.sqrt(1 + s**2) + 0.8944271909999159 + + For s=0.5, we observe a high level of correlation. In general, a large + variance of the noise reduces the correlation, while the correlation + approaches one as the variance of the error goes to zero. + + It is important to keep in mind that no correlation does not imply + independence unless (x, y) is jointly normal. Correlation can even be zero + when there is a very simple dependence structure: if X follows a + standard normal distribution, let y = abs(x). Note that the correlation + between x and y is zero. Indeed, since the expectation of x is zero, + cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero + by symmetry. The following lines of code illustrate this observation: + + >>> y = np.abs(x) + >>> stats.pearsonr(x, y) + PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743) + + A non-zero correlation coefficient can be misleading. For example, if X has + a standard normal distribution, define y = x if x < 0 and y = 0 otherwise. + A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797..., + implying a high level of correlation: + + >>> y = np.where(x < 0, x, 0) + >>> stats.pearsonr(x, y) + PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149) + + This is unintuitive since there is no dependence of x and y if x is larger + than zero which happens in about half of the cases if we sample x and y. + + """ + xp = array_namespace(x, y) + x = xp.asarray(x) + y = xp.asarray(y) + + if not is_numpy(xp) and method is not None: + method = 'invalid' + + if axis is None: + x = xp.reshape(x, (-1,)) + y = xp.reshape(y, (-1,)) + axis = -1 + + axis_int = int(axis) + if axis_int != axis: + raise ValueError('`axis` must be an integer.') + axis = axis_int + + n = x.shape[axis] + if n != y.shape[axis]: + raise ValueError('`x` and `y` must have the same length along `axis`.') + + if n < 2: + raise ValueError('`x` and `y` must have length at least 2.') + + try: + x, y = xp.broadcast_arrays(x, y) + except (ValueError, RuntimeError) as e: + message = '`x` and `y` must be broadcastable.' + raise ValueError(message) from e + + # `moveaxis` only recently added to array API, so it's not yey available in + # array_api_strict. Replace with e.g. `xp.moveaxis(x, axis, -1)` when available. + x = xp_moveaxis_to_end(x, axis, xp=xp) + y = xp_moveaxis_to_end(y, axis, xp=xp) + axis = -1 + + dtype = xp.result_type(x.dtype, y.dtype) + if xp.isdtype(dtype, "integral"): + dtype = xp.asarray(1.).dtype + + if xp.isdtype(dtype, "complex floating"): + raise ValueError('This function does not support complex data') + + x = xp.astype(x, dtype, copy=False) + y = xp.astype(y, dtype, copy=False) + threshold = xp.finfo(dtype).eps ** 0.75 + + # If an input is constant, the correlation coefficient is not defined. + const_x = xp.all(x == x[..., 0:1], axis=-1) + const_y = xp.all(y == y[..., 0:1], axis=-1) + const_xy = const_x | const_y + if xp.any(const_xy): + msg = ("An input array is constant; the correlation coefficient " + "is not defined.") + warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2) + + if isinstance(method, PermutationMethod): + def statistic(y, axis): + statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative) + return statistic + + res = permutation_test((y,), statistic, permutation_type='pairings', + axis=axis, alternative=alternative, **method._asdict()) + + return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n, + alternative=alternative, x=x, y=y, axis=axis) + elif isinstance(method, MonteCarloMethod): + def statistic(x, y, axis): + statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative) + return statistic + + # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng` + # If the user specified an `rng`, replace it with the appropriate callables + method = method._asdict() + if (rng := method.pop('rng', None)) is not None: # goo-goo g'joob + rng = np.random.default_rng(rng) + method['rvs'] = rng.normal, rng.normal + + res = monte_carlo_test((x, y,), statistic=statistic, axis=axis, + alternative=alternative, **method) + + return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n, + alternative=alternative, x=x, y=y, axis=axis) + elif method == 'invalid': + message = '`method` must be `None` if arguments are not NumPy arrays.' + raise ValueError(message) + elif method is not None: + message = ('`method` must be an instance of `PermutationMethod`,' + '`MonteCarloMethod`, or None.') + raise ValueError(message) + + xmean = xp.mean(x, axis=axis, keepdims=True) + ymean = xp.mean(y, axis=axis, keepdims=True) + xm = x - xmean + ym = y - ymean + + # scipy.linalg.norm(xm) avoids premature overflow when xm is e.g. + # [-5e210, 5e210, 3e200, -3e200] + # but not when `axis` is provided, so scale manually. scipy.linalg.norm + # also raises an error with NaN input rather than returning NaN, so + # use np.linalg.norm. + xmax = xp.max(xp.abs(xm), axis=axis, keepdims=True) + ymax = xp.max(xp.abs(ym), axis=axis, keepdims=True) + with np.errstate(invalid='ignore', divide='ignore'): + normxm = xmax * xp_vector_norm(xm/xmax, axis=axis, keepdims=True) + normym = ymax * xp_vector_norm(ym/ymax, axis=axis, keepdims=True) + + nconst_x = xp.any(normxm < threshold*xp.abs(xmean), axis=axis) + nconst_y = xp.any(normym < threshold*xp.abs(ymean), axis=axis) + nconst_xy = nconst_x | nconst_y + if xp.any(nconst_xy & (~const_xy)): + # If all the values in x (likewise y) are very close to the mean, + # the loss of precision that occurs in the subtraction xm = x - xmean + # might result in large errors in r. + msg = ("An input array is nearly constant; the computed " + "correlation coefficient may be inaccurate.") + warnings.warn(stats.NearConstantInputWarning(msg), stacklevel=2) + + with np.errstate(invalid='ignore', divide='ignore'): + r = xp.sum(xm/normxm * ym/normym, axis=axis) + + # Presumably, if abs(r) > 1, then it is only some small artifact of + # floating point arithmetic. + one = xp.asarray(1, dtype=dtype) + r = xp.asarray(xp.clip(r, -one, one)) + r[const_xy] = xp.nan + + # Make sure we return exact 1.0 or -1.0 values for n == 2 case as promised + # in the docs. + if n == 2: + r = xp.round(r) + one = xp.asarray(1, dtype=dtype) + pvalue = xp.where(xp.asarray(xp.isnan(r)), xp.nan*one, one) + else: + # As explained in the docstring, the distribution of `r` under the null + # hypothesis is the beta distribution on (-1, 1) with a = b = n/2 - 1. + ab = xp.asarray(n/2 - 1) + dist = _SimpleBeta(ab, ab, loc=-1, scale=2) + pvalue = _get_pvalue(r, dist, alternative, xp=xp) + + r = r[()] if r.ndim == 0 else r + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + return PearsonRResult(statistic=r, pvalue=pvalue, n=n, + alternative=alternative, x=x, y=y, axis=axis) + + +def fisher_exact(table, alternative=None, *, method=None): + """Perform a Fisher exact test on a contingency table. + + For a 2x2 table, + the null hypothesis is that the true odds ratio of the populations + underlying the observations is one, and the observations were sampled + from these populations under a condition: the marginals of the + resulting table must equal those of the observed table. + The statistic is the unconditional maximum likelihood estimate of the odds + ratio, and the p-value is the probability under the null hypothesis of + obtaining a table at least as extreme as the one that was actually + observed. + + For other table sizes, or if `method` is provided, the null hypothesis + is that the rows and columns of the tables have fixed sums and are + independent; i.e., the table was sampled from a `scipy.stats.random_table` + distribution with the observed marginals. The statistic is the + probability mass of this distribution evaluated at `table`, and the + p-value is the percentage of the population of tables with statistic at + least as extreme (small) as that of `table`. There is only one alternative + hypothesis available: the rows and columns are not independent. + + There are other possible choices of statistic and two-sided + p-value definition associated with Fisher's exact test; please see the + Notes for more information. + + Parameters + ---------- + table : array_like of ints + A contingency table. Elements must be non-negative integers. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis for 2x2 tables; unused for other + table sizes. + The following options are available (default is 'two-sided'): + + * 'two-sided': the odds ratio of the underlying population is not one + * 'less': the odds ratio of the underlying population is less than one + * 'greater': the odds ratio of the underlying population is greater + than one + + See the Notes for more details. + + method : ResamplingMethod, optional + Defines the method used to compute the p-value. + If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`, + the p-value is computed using + `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the + provided configuration options and other appropriate settings. + Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs`` + attribute must be left unspecified; Monte Carlo samples are always drawn + using the ``rvs`` method of `scipy.stats.random_table`. + Otherwise, the p-value is computed as documented in the notes. + + .. versionadded:: 1.15.0 + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + For a 2x2 table with default `method`, this is the odds ratio - the + prior odds ratio not a posterior estimate. In all other cases, this + is the probability density of obtaining the observed table under the + null hypothesis of independence with marginals fixed. + pvalue : float + The probability under the null hypothesis of obtaining a + table at least as extreme as the one that was actually observed. + + Raises + ------ + ValueError + If `table` is not two-dimensional or has negative entries. + + See Also + -------- + chi2_contingency : Chi-square test of independence of variables in a + contingency table. This can be used as an alternative to + `fisher_exact` when the numbers in the table are large. + contingency.odds_ratio : Compute the odds ratio (sample or conditional + MLE) for a 2x2 contingency table. + barnard_exact : Barnard's exact test, which is a more powerful alternative + than Fisher's exact test for 2x2 contingency tables. + boschloo_exact : Boschloo's exact test, which is a more powerful + alternative than Fisher's exact test for 2x2 contingency tables. + :ref:`hypothesis_fisher_exact` : Extended example + + Notes + ----- + *Null hypothesis and p-values* + + The null hypothesis is that the true odds ratio of the populations + underlying the observations is one, and the observations were sampled at + random from these populations under a condition: the marginals of the + resulting table must equal those of the observed table. Equivalently, + the null hypothesis is that the input table is from the hypergeometric + distribution with parameters (as used in `hypergeom`) + ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the + input table is ``[[a, b], [c, d]]``. This distribution has support + ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values + in the input table, ``min(0, a - d) <= x <= a + min(b, c)``. ``x`` + can be interpreted as the upper-left element of a 2x2 table, so the + tables in the distribution have form:: + + [ x n - x ] + [N - x M - (n + N) + x] + + For example, if:: + + table = [6 2] + [1 4] + + then the support is ``2 <= x <= 7``, and the tables in the distribution + are:: + + [2 6] [3 5] [4 4] [5 3] [6 2] [7 1] + [5 0] [4 1] [3 2] [2 3] [1 4] [0 5] + + The probability of each table is given by the hypergeometric distribution + ``hypergeom.pmf(x, M, n, N)``. For this example, these are (rounded to + three significant digits):: + + x 2 3 4 5 6 7 + p 0.0163 0.163 0.408 0.326 0.0816 0.00466 + + These can be computed with:: + + >>> import numpy as np + >>> from scipy.stats import hypergeom + >>> table = np.array([[6, 2], [1, 4]]) + >>> M = table.sum() + >>> n = table[0].sum() + >>> N = table[:, 0].sum() + >>> start, end = hypergeom.support(M, n, N) + >>> hypergeom.pmf(np.arange(start, end+1), M, n, N) + array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508, + 0.004662 ]) + + The two-sided p-value is the probability that, under the null hypothesis, + a random table would have a probability equal to or less than the + probability of the input table. For our example, the probability of + the input table (where ``x = 6``) is 0.0816. The x values where the + probability does not exceed this are 2, 6 and 7, so the two-sided p-value + is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``:: + + >>> from scipy.stats import fisher_exact + >>> res = fisher_exact(table, alternative='two-sided') + >>> res.pvalue + 0.10256410256410257 + + The one-sided p-value for ``alternative='greater'`` is the probability + that a random table has ``x >= a``, which in our example is ``x >= 6``, + or ``0.0816 + 0.00466 ~= 0.08626``:: + + >>> res = fisher_exact(table, alternative='greater') + >>> res.pvalue + 0.08624708624708627 + + This is equivalent to computing the survival function of the + distribution at ``x = 5`` (one less than ``x`` from the input table, + because we want to include the probability of ``x = 6`` in the sum):: + + >>> hypergeom.sf(5, M, n, N) + 0.08624708624708627 + + For ``alternative='less'``, the one-sided p-value is the probability + that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example), + or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``:: + + >>> res = fisher_exact(table, alternative='less') + >>> res.pvalue + 0.9953379953379957 + + This is equivalent to computing the cumulative distribution function + of the distribution at ``x = 6``: + + >>> hypergeom.cdf(6, M, n, N) + 0.9953379953379957 + + *Odds ratio* + + The calculated odds ratio is different from the value computed by the + R function ``fisher.test``. This implementation returns the "sample" + or "unconditional" maximum likelihood estimate, while ``fisher.test`` + in R uses the conditional maximum likelihood estimate. To compute the + conditional maximum likelihood estimate of the odds ratio, use + `scipy.stats.contingency.odds_ratio`. + + References + ---------- + .. [1] Fisher, Sir Ronald A, "The Design of Experiments: + Mathematics of a Lady Tasting Tea." ISBN 978-0-486-41151-4, 1935. + .. [2] "Fisher's exact test", + https://en.wikipedia.org/wiki/Fisher's_exact_test + + Examples + -------- + + >>> from scipy.stats import fisher_exact + >>> res = fisher_exact([[8, 2], [1, 5]]) + >>> res.statistic + 20.0 + >>> res.pvalue + 0.034965034965034975 + + For tables with shape other than ``(2, 2)``, provide an instance of + `scipy.stats.MonteCarloMethod` or `scipy.stats.PermutationMethod` for the + `method` parameter: + + >>> import numpy as np + >>> from scipy.stats import MonteCarloMethod + >>> rng = np.random.default_rng(4507195762371367) + >>> method = MonteCarloMethod(rng=rng) + >>> fisher_exact([[8, 2, 3], [1, 5, 4]], method=method) + SignificanceResult(statistic=np.float64(0.005782), pvalue=np.float64(0.0603)) + + For a more detailed example, see :ref:`hypothesis_fisher_exact`. + """ + hypergeom = distributions.hypergeom + # int32 is not enough for the algorithm + c = np.asarray(table, dtype=np.int64) + if not c.ndim == 2: + raise ValueError("The input `table` must have two dimensions.") + + if np.any(c < 0): + raise ValueError("All values in `table` must be nonnegative.") + + if not c.shape == (2, 2) or method is not None: + return _fisher_exact_rxc(c, alternative, method) + alternative = 'two-sided' if alternative is None else alternative + + if 0 in c.sum(axis=0) or 0 in c.sum(axis=1): + # If both values in a row or column are zero, the p-value is 1 and + # the odds ratio is NaN. + return SignificanceResult(np.nan, 1.0) + + if c[1, 0] > 0 and c[0, 1] > 0: + oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1]) + else: + oddsratio = np.inf + + n1 = c[0, 0] + c[0, 1] + n2 = c[1, 0] + c[1, 1] + n = c[0, 0] + c[1, 0] + + def pmf(x): + return hypergeom.pmf(x, n1 + n2, n1, n) + + if alternative == 'less': + pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n) + elif alternative == 'greater': + # Same formula as the 'less' case, but with the second column. + pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1]) + elif alternative == 'two-sided': + mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2)) + pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n) + pmode = hypergeom.pmf(mode, n1 + n2, n1, n) + + epsilon = 1e-14 + gamma = 1 + epsilon + + if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= epsilon: + return SignificanceResult(oddsratio, 1.) + + elif c[0, 0] < mode: + plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n) + if hypergeom.pmf(n, n1 + n2, n1, n) > pexact * gamma: + return SignificanceResult(oddsratio, plower) + + guess = _binary_search(lambda x: -pmf(x), -pexact * gamma, mode, n) + pvalue = plower + hypergeom.sf(guess, n1 + n2, n1, n) + else: + pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n) + if hypergeom.pmf(0, n1 + n2, n1, n) > pexact * gamma: + return SignificanceResult(oddsratio, pupper) + + guess = _binary_search(pmf, pexact * gamma, 0, mode) + pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n) + else: + msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}" + raise ValueError(msg) + + pvalue = min(pvalue, 1.0) + + return SignificanceResult(oddsratio, pvalue) + + +def _fisher_exact_rxc(table, alternative, method): + if alternative is not None: + message = ('`alternative` must be the default (None) unless ' + '`table` has shape `(2, 2)` and `method is None`.') + raise ValueError(message) + + if table.size == 0: + raise ValueError("`table` must have at least one row and one column.") + + if table.shape[0] == 1 or table.shape[1] == 1 or np.all(table == 0): + # Only one such table with those marginals + return SignificanceResult(1.0, 1.0) + + if method is None: + method = stats.MonteCarloMethod() + + if isinstance(method, stats.PermutationMethod): + res = _fisher_exact_permutation_method(table, method) + elif isinstance(method, stats.MonteCarloMethod): + res = _fisher_exact_monte_carlo_method(table, method) + else: + message = (f'`{method=}` not recognized; if provided, `method` must be an ' + 'instance of `PermutationMethod` or `MonteCarloMethod`.') + raise ValueError(message) + + return SignificanceResult(np.clip(res.statistic, None, 1.0), res.pvalue) + + +def _fisher_exact_permutation_method(table, method): + x, y = _untabulate(table) + colsums = np.sum(table, axis=0) + rowsums = np.sum(table, axis=1) + X = stats.random_table(rowsums, colsums) + + # `permutation_test` with `permutation_type='pairings' permutes the order of `x`, + # which pairs observations in `x` with different observations in `y`. + def statistic(x): + # crosstab the resample and compute the statistic + table = stats.contingency.crosstab(x, y)[1] + return X.pmf(table) + + # tables with *smaller* probability mass are considered to be more extreme + return stats.permutation_test((x,), statistic, permutation_type='pairings', + alternative='less', **method._asdict()) + + +def _fisher_exact_monte_carlo_method(table, method): + method = method._asdict() + + if method.pop('rvs', None) is not None: + message = ('If the `method` argument of `fisher_exact` is an ' + 'instance of `MonteCarloMethod`, its `rvs` attribute ' + 'must be unspecified. Use the `MonteCarloMethod` `rng` argument ' + 'to control the random state.') + raise ValueError(message) + rng = np.random.default_rng(method.pop('rng', None)) + + # `random_table.rvs` produces random contingency tables with the given marginals + # under the null hypothesis of independence + shape = table.shape + colsums = np.sum(table, axis=0) + rowsums = np.sum(table, axis=1) + totsum = np.sum(table) + X = stats.random_table(rowsums, colsums, seed=rng) + + def rvs(size): + n_resamples = size[0] + return X.rvs(size=n_resamples).reshape(size) + + # axis signals to `monte_carlo_test` that statistic is vectorized, but we know + # how it will pass the table(s), so we don't need to use `axis` explicitly. + def statistic(table, axis): + shape_ = (-1,) + shape if table.size > totsum else shape + return X.pmf(table.reshape(shape_)) + + # tables with *smaller* probability mass are considered to be more extreme + return stats.monte_carlo_test(table.ravel(), rvs, statistic, + alternative='less', **method) + + +def _untabulate(table): + # converts a contingency table to paired samples indicating the + # correspondence between row and column indices + r, c = table.shape + x, y = [], [] + for i in range(r): + for j in range(c): + x.append([i] * table[i, j]) + y.append([j] * table[i, j]) + return np.concatenate(x), np.concatenate(y) + + +def spearmanr(a, b=None, axis=0, nan_policy='propagate', + alternative='two-sided'): + r"""Calculate a Spearman correlation coefficient with associated p-value. + + The Spearman rank-order correlation coefficient is a nonparametric measure + of the monotonicity of the relationship between two datasets. + Like other correlation coefficients, + this one varies between -1 and +1 with 0 implying no correlation. + Correlations of -1 or +1 imply an exact monotonic relationship. Positive + correlations imply that as x increases, so does y. Negative correlations + imply that as x increases, y decreases. + + The p-value roughly indicates the probability of an uncorrelated system + producing datasets that have a Spearman correlation at least as extreme + as the one computed from these datasets. Although calculation of the + p-value does not make strong assumptions about the distributions underlying + the samples, it is only accurate for very large samples (>500 + observations). For smaller sample sizes, consider a permutation test (see + Examples section below). + + Parameters + ---------- + a, b : 1D or 2D array_like, b is optional + One or two 1-D or 2-D arrays containing multiple variables and + observations. When these are 1-D, each represents a vector of + observations of a single variable. For the behavior in the 2-D case, + see under ``axis``, below. + Both arrays need to have the same length in the ``axis`` dimension. + axis : int or None, optional + If axis=0 (default), then each column represents a variable, with + observations in the rows. If axis=1, the relationship is transposed: + each row represents a variable, while the columns contain observations. + If axis=None, then both arrays will be raveled. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the correlation is nonzero + * 'less': the correlation is negative (less than zero) + * 'greater': the correlation is positive (greater than zero) + + .. versionadded:: 1.7.0 + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float or ndarray (2-D square) + Spearman correlation matrix or correlation coefficient (if only 2 + variables are given as parameters). Correlation matrix is square + with length equal to total number of variables (columns or rows) in + ``a`` and ``b`` combined. + pvalue : float + The p-value for a hypothesis test whose null hypothesis + is that two samples have no ordinal correlation. See + `alternative` above for alternative hypotheses. `pvalue` has the + same shape as `statistic`. + + Raises + ------ + ValueError + If `axis` is not 0, 1 or None, or if the number of dimensions of `a` + is greater than 2, or if `b` is None and the number of dimensions of + `a` is less than 2. + + Warns + ----- + `~scipy.stats.ConstantInputWarning` + Raised if an input is a constant array. The correlation coefficient + is not defined in this case, so ``np.nan`` is returned. + + See Also + -------- + :ref:`hypothesis_spearmanr` : Extended example + + References + ---------- + .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + Section 14.7 + .. [2] Kendall, M. G. and Stuart, A. (1973). + The Advanced Theory of Statistics, Volume 2: Inference and Relationship. + Griffin. 1973. + Section 31.18 + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> res = stats.spearmanr([1, 2, 3, 4, 5], [5, 6, 7, 8, 7]) + >>> res.statistic + 0.8207826816681233 + >>> res.pvalue + 0.08858700531354381 + + >>> rng = np.random.default_rng() + >>> x2n = rng.standard_normal((100, 2)) + >>> y2n = rng.standard_normal((100, 2)) + >>> res = stats.spearmanr(x2n) + >>> res.statistic, res.pvalue + (-0.07960396039603959, 0.4311168705769747) + + >>> res = stats.spearmanr(x2n[:, 0], x2n[:, 1]) + >>> res.statistic, res.pvalue + (-0.07960396039603959, 0.4311168705769747) + + >>> res = stats.spearmanr(x2n, y2n) + >>> res.statistic + array([[ 1. , -0.07960396, -0.08314431, 0.09662166], + [-0.07960396, 1. , -0.14448245, 0.16738074], + [-0.08314431, -0.14448245, 1. , 0.03234323], + [ 0.09662166, 0.16738074, 0.03234323, 1. ]]) + >>> res.pvalue + array([[0. , 0.43111687, 0.41084066, 0.33891628], + [0.43111687, 0. , 0.15151618, 0.09600687], + [0.41084066, 0.15151618, 0. , 0.74938561], + [0.33891628, 0.09600687, 0.74938561, 0. ]]) + + >>> res = stats.spearmanr(x2n.T, y2n.T, axis=1) + >>> res.statistic + array([[ 1. , -0.07960396, -0.08314431, 0.09662166], + [-0.07960396, 1. , -0.14448245, 0.16738074], + [-0.08314431, -0.14448245, 1. , 0.03234323], + [ 0.09662166, 0.16738074, 0.03234323, 1. ]]) + + >>> res = stats.spearmanr(x2n, y2n, axis=None) + >>> res.statistic, res.pvalue + (0.044981624540613524, 0.5270803651336189) + + >>> res = stats.spearmanr(x2n.ravel(), y2n.ravel()) + >>> res.statistic, res.pvalue + (0.044981624540613524, 0.5270803651336189) + + >>> rng = np.random.default_rng() + >>> xint = rng.integers(10, size=(100, 2)) + >>> res = stats.spearmanr(xint) + >>> res.statistic, res.pvalue + (0.09800224850707953, 0.3320271757932076) + + For small samples, consider performing a permutation test instead of + relying on the asymptotic p-value. Note that to calculate the null + distribution of the statistic (for all possibly pairings between + observations in sample ``x`` and ``y``), only one of the two inputs needs + to be permuted. + + >>> x = [1.76405235, 0.40015721, 0.97873798, + ... 2.2408932, 1.86755799, -0.97727788] + >>> y = [2.71414076, 0.2488, 0.87551913, + ... 2.6514917, 2.01160156, 0.47699563] + + >>> def statistic(x): # permute only `x` + ... return stats.spearmanr(x, y).statistic + >>> res_exact = stats.permutation_test((x,), statistic, + ... permutation_type='pairings') + >>> res_asymptotic = stats.spearmanr(x, y) + >>> res_exact.pvalue, res_asymptotic.pvalue # asymptotic pvalue is too low + (0.10277777777777777, 0.07239650145772594) + + For a more detailed example, see :ref:`hypothesis_spearmanr`. + """ + if axis is not None and axis > 1: + raise ValueError("spearmanr only handles 1-D or 2-D arrays, " + f"supplied axis argument {axis}, please use only " + "values 0, 1 or None for axis") + + a, axisout = _chk_asarray(a, axis) + if a.ndim > 2: + raise ValueError("spearmanr only handles 1-D or 2-D arrays") + + if b is None: + if a.ndim < 2: + raise ValueError("`spearmanr` needs at least 2 " + "variables to compare") + else: + # Concatenate a and b, so that we now only have to handle the case + # of a 2-D `a`. + b, _ = _chk_asarray(b, axis) + if axisout == 0: + a = np.column_stack((a, b)) + else: + a = np.vstack((a, b)) + + n_vars = a.shape[1 - axisout] + n_obs = a.shape[axisout] + if n_obs <= 1: + # Handle empty arrays or single observations. + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + warn_msg = ("An input array is constant; the correlation coefficient " + "is not defined.") + if axisout == 0: + if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all(): + # If an input is constant, the correlation coefficient + # is not defined. + warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2) + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + else: # case when axisout == 1 b/c a is 2 dim only + if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all(): + # If an input is constant, the correlation coefficient + # is not defined. + warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2) + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + a_contains_nan, nan_policy = _contains_nan(a, nan_policy) + variable_has_nan = np.zeros(n_vars, dtype=bool) + if a_contains_nan: + if nan_policy == 'omit': + return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy, + alternative=alternative) + elif nan_policy == 'propagate': + if a.ndim == 1 or n_vars <= 2: + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + else: + # Keep track of variables with NaNs, set the outputs to NaN + # only for those variables + variable_has_nan = np.isnan(a).any(axis=axisout) + + a_ranked = np.apply_along_axis(rankdata, axisout, a) + rs = np.corrcoef(a_ranked, rowvar=axisout) + dof = n_obs - 2 # degrees of freedom + + # rs can have elements equal to 1, so avoid zero division warnings + with np.errstate(divide='ignore'): + # clip the small negative values possibly caused by rounding + # errors before taking the square root + t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0)) + + dist = _SimpleStudentT(dof) + prob = _get_pvalue(t, dist, alternative, xp=np) + + # For backwards compatibility, return scalars when comparing 2 columns + if rs.shape == (2, 2): + res = SignificanceResult(rs[1, 0], prob[1, 0]) + res.correlation = rs[1, 0] + return res + else: + rs[variable_has_nan, :] = np.nan + rs[:, variable_has_nan] = np.nan + res = SignificanceResult(rs[()], prob[()]) + res.correlation = rs + return res + + +def pointbiserialr(x, y): + r"""Calculate a point biserial correlation coefficient and its p-value. + + The point biserial correlation is used to measure the relationship + between a binary variable, x, and a continuous variable, y. Like other + correlation coefficients, this one varies between -1 and +1 with 0 + implying no correlation. Correlations of -1 or +1 imply a determinative + relationship. + + This function may be computed using a shortcut formula but produces the + same result as `pearsonr`. + + Parameters + ---------- + x : array_like of bools + Input array. + y : array_like + Input array. + + Returns + ------- + res: SignificanceResult + An object containing attributes: + + statistic : float + The R value. + pvalue : float + The two-sided p-value. + + Notes + ----- + `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom. + It is equivalent to `pearsonr`. + + The value of the point-biserial correlation can be calculated from: + + .. math:: + + r_{pb} = \frac{\overline{Y_1} - \overline{Y_0}} + {s_y} + \sqrt{\frac{N_0 N_1} + {N (N - 1)}} + + Where :math:`\overline{Y_{0}}` and :math:`\overline{Y_{1}}` are means + of the metric observations coded 0 and 1 respectively; :math:`N_{0}` and + :math:`N_{1}` are number of observations coded 0 and 1 respectively; + :math:`N` is the total number of observations and :math:`s_{y}` is the + standard deviation of all the metric observations. + + A value of :math:`r_{pb}` that is significantly different from zero is + completely equivalent to a significant difference in means between the two + groups. Thus, an independent groups t Test with :math:`N-2` degrees of + freedom may be used to test whether :math:`r_{pb}` is nonzero. The + relation between the t-statistic for comparing two independent groups and + :math:`r_{pb}` is given by: + + .. math:: + + t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}} + + References + ---------- + .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math. + Statist., Vol. 20, no.1, pp. 125-126, 1949. + + .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous + Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25, + np. 3, pp. 603-607, 1954. + + .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef: + Statistics Reference Online (eds N. Balakrishnan, et al.), 2014. + :doi:`10.1002/9781118445112.stat06227` + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> a = np.array([0, 0, 0, 1, 1, 1, 1]) + >>> b = np.arange(7) + >>> stats.pointbiserialr(a, b) + (0.8660254037844386, 0.011724811003954652) + >>> stats.pearsonr(a, b) + (0.86602540378443871, 0.011724811003954626) + >>> np.corrcoef(a, b) + array([[ 1. , 0.8660254], + [ 0.8660254, 1. ]]) + + """ + rpb, prob = pearsonr(x, y) + # create result object with alias for backward compatibility + res = SignificanceResult(rpb, prob) + res.correlation = rpb + return res + + +def kendalltau(x, y, *, nan_policy='propagate', + method='auto', variant='b', alternative='two-sided'): + r"""Calculate Kendall's tau, a correlation measure for ordinal data. + + Kendall's tau is a measure of the correspondence between two rankings. + Values close to 1 indicate strong agreement, and values close to -1 + indicate strong disagreement. This implements two variants of Kendall's + tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These + differ only in how they are normalized to lie within the range -1 to 1; + the hypothesis tests (their p-values) are identical. Kendall's original + tau-a is not implemented separately because both tau-b and tau-c reduce + to tau-a in the absence of ties. + + Parameters + ---------- + x, y : array_like + Arrays of rankings, of the same shape. If arrays are not 1-D, they + will be flattened to 1-D. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + method : {'auto', 'asymptotic', 'exact'}, optional + Defines which method is used to calculate the p-value [5]_. + The following options are available (default is 'auto'): + + * 'auto': selects the appropriate method based on a trade-off + between speed and accuracy + * 'asymptotic': uses a normal approximation valid for large samples + * 'exact': computes the exact p-value, but can only be used if no ties + are present. As the sample size increases, the 'exact' computation + time may grow and the result may lose some precision. + + variant : {'b', 'c'}, optional + Defines which variant of Kendall's tau is returned. Default is 'b'. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the rank correlation is nonzero + * 'less': the rank correlation is negative (less than zero) + * 'greater': the rank correlation is positive (greater than zero) + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + The tau statistic. + pvalue : float + The p-value for a hypothesis test whose null hypothesis is + an absence of association, tau = 0. + + Raises + ------ + ValueError + If `nan_policy` is 'omit' and `variant` is not 'b' or + if `method` is 'exact' and there are ties between `x` and `y`. + + See Also + -------- + spearmanr : Calculates a Spearman rank-order correlation coefficient. + theilslopes : Computes the Theil-Sen estimator for a set of points (x, y). + weightedtau : Computes a weighted version of Kendall's tau. + :ref:`hypothesis_kendalltau` : Extended example + + Notes + ----- + The definition of Kendall's tau that is used is [2]_:: + + tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U)) + + tau_c = 2 (P - Q) / (n**2 * (m - 1) / m) + + where P is the number of concordant pairs, Q the number of discordant + pairs, T the number of ties only in `x`, and U the number of ties only in + `y`. If a tie occurs for the same pair in both `x` and `y`, it is not + added to either T or U. n is the total number of samples, and m is the + number of unique values in either `x` or `y`, whichever is smaller. + + References + ---------- + .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika + Vol. 30, No. 1/2, pp. 81-93, 1938. + .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems", + Biometrika Vol. 33, No. 3, pp. 239-251. 1945. + .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John + Wiley & Sons, 1967. + .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency + tables", Software: Practice and Experience, Vol. 24, No. 3, + pp. 327-336, 1994. + .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition), + Charles Griffin & Co., 1970. + + Examples + -------- + + >>> from scipy import stats + >>> x1 = [12, 2, 1, 12, 2] + >>> x2 = [1, 4, 7, 1, 0] + >>> res = stats.kendalltau(x1, x2) + >>> res.statistic + -0.47140452079103173 + >>> res.pvalue + 0.2827454599327748 + + For a more detailed example, see :ref:`hypothesis_kendalltau`. + """ + x = np.asarray(x).ravel() + y = np.asarray(y).ravel() + + if x.size != y.size: + raise ValueError("All inputs to `kendalltau` must be of the same " + f"size, found x-size {x.size} and y-size {y.size}") + elif not x.size or not y.size: + # Return NaN if arrays are empty + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + # check both x and y + cnx, npx = _contains_nan(x, nan_policy) + cny, npy = _contains_nan(y, nan_policy) + contains_nan = cnx or cny + if npx == 'omit' or npy == 'omit': + nan_policy = 'omit' + + if contains_nan and nan_policy == 'propagate': + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + elif contains_nan and nan_policy == 'omit': + x = ma.masked_invalid(x) + y = ma.masked_invalid(y) + if variant == 'b': + return mstats_basic.kendalltau(x, y, method=method, use_ties=True, + alternative=alternative) + else: + message = ("nan_policy='omit' is currently compatible only with " + "variant='b'.") + raise ValueError(message) + + def count_rank_tie(ranks): + cnt = np.bincount(ranks).astype('int64', copy=False) + cnt = cnt[cnt > 1] + # Python ints to avoid overflow down the line + return (int((cnt * (cnt - 1) // 2).sum()), + int((cnt * (cnt - 1.) * (cnt - 2)).sum()), + int((cnt * (cnt - 1.) * (2*cnt + 5)).sum())) + + size = x.size + perm = np.argsort(y) # sort on y and convert y to dense ranks + x, y = x[perm], y[perm] + y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp) + + # stable sort on x and convert x to dense ranks + perm = np.argsort(x, kind='mergesort') + x, y = x[perm], y[perm] + x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp) + + dis = _kendall_dis(x, y) # discordant pairs + + obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True] + cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False) + + ntie = int((cnt * (cnt - 1) // 2).sum()) # joint ties + xtie, x0, x1 = count_rank_tie(x) # ties in x, stats + ytie, y0, y1 = count_rank_tie(y) # ties in y, stats + + tot = (size * (size - 1)) // 2 + + if xtie == tot or ytie == tot: + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + # Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie + # = con + dis + xtie + ytie - ntie + con_minus_dis = tot - xtie - ytie + ntie - 2 * dis + if variant == 'b': + tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie) + elif variant == 'c': + minclasses = min(len(set(x)), len(set(y))) + tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses) + else: + raise ValueError(f"Unknown variant of the method chosen: {variant}. " + "variant must be 'b' or 'c'.") + + # Limit range to fix computational errors + tau = np.minimum(1., max(-1., tau)) + + # The p-value calculation is the same for all variants since the p-value + # depends only on con_minus_dis. + if method == 'exact' and (xtie != 0 or ytie != 0): + raise ValueError("Ties found, exact method cannot be used.") + + if method == 'auto': + if (xtie == 0 and ytie == 0) and (size <= 33 or + min(dis, tot-dis) <= 1): + method = 'exact' + else: + method = 'asymptotic' + + if xtie == 0 and ytie == 0 and method == 'exact': + pvalue = mstats_basic._kendall_p_exact(size, tot-dis, alternative) + elif method == 'asymptotic': + # con_minus_dis is approx normally distributed with this variance [3]_ + m = size * (size - 1.) + var = ((m * (2*size + 5) - x1 - y1) / 18 + + (2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2))) + z = con_minus_dis / np.sqrt(var) + pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + else: + raise ValueError(f"Unknown method {method} specified. Use 'auto', " + "'exact' or 'asymptotic'.") + + # create result object with alias for backward compatibility + res = SignificanceResult(tau[()], pvalue[()]) + res.correlation = tau[()] + return res + + +def weightedtau(x, y, rank=True, weigher=None, additive=True): + r"""Compute a weighted version of Kendall's :math:`\tau`. + + The weighted :math:`\tau` is a weighted version of Kendall's + :math:`\tau` in which exchanges of high weight are more influential than + exchanges of low weight. The default parameters compute the additive + hyperbolic version of the index, :math:`\tau_\mathrm h`, which has + been shown to provide the best balance between important and + unimportant elements [1]_. + + The weighting is defined by means of a rank array, which assigns a + nonnegative rank to each element (higher importance ranks being + associated with smaller values, e.g., 0 is the highest possible rank), + and a weigher function, which assigns a weight based on the rank to + each element. The weight of an exchange is then the sum or the product + of the weights of the ranks of the exchanged elements. The default + parameters compute :math:`\tau_\mathrm h`: an exchange between + elements with rank :math:`r` and :math:`s` (starting from zero) has + weight :math:`1/(r+1) + 1/(s+1)`. + + Specifying a rank array is meaningful only if you have in mind an + external criterion of importance. If, as it usually happens, you do + not have in mind a specific rank, the weighted :math:`\tau` is + defined by averaging the values obtained using the decreasing + lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the + behavior with default parameters. Note that the convention used + here for ranking (lower values imply higher importance) is opposite + to that used by other SciPy statistical functions. + + Parameters + ---------- + x, y : array_like + Arrays of scores, of the same shape. If arrays are not 1-D, they will + be flattened to 1-D. + rank : array_like of ints or bool, optional + A nonnegative rank assigned to each element. If it is None, the + decreasing lexicographical rank by (`x`, `y`) will be used: elements of + higher rank will be those with larger `x`-values, using `y`-values to + break ties (in particular, swapping `x` and `y` will give a different + result). If it is False, the element indices will be used + directly as ranks. The default is True, in which case this + function returns the average of the values obtained using the + decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`). + weigher : callable, optional + The weigher function. Must map nonnegative integers (zero + representing the most important element) to a nonnegative weight. + The default, None, provides hyperbolic weighing, that is, + rank :math:`r` is mapped to weight :math:`1/(r+1)`. + additive : bool, optional + If True, the weight of an exchange is computed by adding the + weights of the ranks of the exchanged elements; otherwise, the weights + are multiplied. The default is True. + + Returns + ------- + res: SignificanceResult + An object containing attributes: + + statistic : float + The weighted :math:`\tau` correlation index. + pvalue : float + Presently ``np.nan``, as the null distribution of the statistic is + unknown (even in the additive hyperbolic case). + + See Also + -------- + kendalltau : Calculates Kendall's tau. + spearmanr : Calculates a Spearman rank-order correlation coefficient. + theilslopes : Computes the Theil-Sen estimator for a set of points (x, y). + + Notes + ----- + This function uses an :math:`O(n \log n)`, mergesort-based algorithm + [1]_ that is a weighted extension of Knight's algorithm for Kendall's + :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_ + between rankings without ties (i.e., permutations) by setting + `additive` and `rank` to False, as the definition given in [1]_ is a + generalization of Shieh's. + + NaNs are considered the smallest possible score. + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with + ties", Proceedings of the 24th international conference on World + Wide Web, pp. 1166-1176, ACM, 2015. + .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with + Ungrouped Data", Journal of the American Statistical Association, + Vol. 61, No. 314, Part 1, pp. 436-439, 1966. + .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics & + Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, 0] + >>> res = stats.weightedtau(x, y) + >>> res.statistic + -0.56694968153682723 + >>> res.pvalue + nan + >>> res = stats.weightedtau(x, y, additive=False) + >>> res.statistic + -0.62205716951801038 + + NaNs are considered the smallest possible score: + + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, np.nan] + >>> res = stats.weightedtau(x, y) + >>> res.statistic + -0.56694968153682723 + + This is exactly Kendall's tau: + + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, 0] + >>> res = stats.weightedtau(x, y, weigher=lambda x: 1) + >>> res.statistic + -0.47140452079103173 + + >>> x = [12, 2, 1, 12, 2] + >>> y = [1, 4, 7, 1, 0] + >>> stats.weightedtau(x, y, rank=None) + SignificanceResult(statistic=-0.4157652301037516, pvalue=nan) + >>> stats.weightedtau(y, x, rank=None) + SignificanceResult(statistic=-0.7181341329699028, pvalue=nan) + + """ + x = np.asarray(x).ravel() + y = np.asarray(y).ravel() + + if x.size != y.size: + raise ValueError("All inputs to `weightedtau` must be " + "of the same size, " + f"found x-size {x.size} and y-size {y.size}") + if not x.size: + # Return NaN if arrays are empty + res = SignificanceResult(np.nan, np.nan) + res.correlation = np.nan + return res + + # If there are NaNs we apply _toint64() + if np.isnan(np.sum(x)): + x = _toint64(x) + if np.isnan(np.sum(y)): + y = _toint64(y) + + # Reduce to ranks unsupported types + if x.dtype != y.dtype: + if x.dtype != np.int64: + x = _toint64(x) + if y.dtype != np.int64: + y = _toint64(y) + else: + if x.dtype not in (np.int32, np.int64, np.float32, np.float64): + x = _toint64(x) + y = _toint64(y) + + if rank is True: + tau = ( + _weightedrankedtau(x, y, None, weigher, additive) + + _weightedrankedtau(y, x, None, weigher, additive) + ) / 2 + res = SignificanceResult(tau, np.nan) + res.correlation = tau + return res + + if rank is False: + rank = np.arange(x.size, dtype=np.intp) + elif rank is not None: + rank = np.asarray(rank).ravel() + if rank.size != x.size: + raise ValueError( + "All inputs to `weightedtau` must be of the same size, " + f"found x-size {x.size} and rank-size {rank.size}" + ) + + tau = _weightedrankedtau(x, y, rank, weigher, additive) + res = SignificanceResult(tau, np.nan) + res.correlation = tau + return res + + +##################################### +# INFERENTIAL STATISTICS # +##################################### + +TtestResultBase = _make_tuple_bunch('TtestResultBase', + ['statistic', 'pvalue'], ['df']) + + +class TtestResult(TtestResultBase): + """ + Result of a t-test. + + See the documentation of the particular t-test function for more + information about the definition of the statistic and meaning of + the confidence interval. + + Attributes + ---------- + statistic : float or array + The t-statistic of the sample. + pvalue : float or array + The p-value associated with the given alternative. + df : float or array + The number of degrees of freedom used in calculation of the + t-statistic; this is one less than the size of the sample + (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs). + + Methods + ------- + confidence_interval + Computes a confidence interval around the population statistic + for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + """ + + def __init__(self, statistic, pvalue, df, # public + alternative, standard_error, estimate, # private + statistic_np=None, xp=None): # private + super().__init__(statistic, pvalue, df=df) + self._alternative = alternative + self._standard_error = standard_error # denominator of t-statistic + self._estimate = estimate # point estimate of sample mean + self._statistic_np = statistic if statistic_np is None else statistic_np + self._dtype = statistic.dtype + self._xp = array_namespace(statistic, pvalue) if xp is None else xp + + + def confidence_interval(self, confidence_level=0.95): + """ + Parameters + ---------- + confidence_level : float + The confidence level for the calculation of the population mean + confidence interval. Default is 0.95. + + Returns + ------- + ci : namedtuple + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + """ + low, high = _t_confidence_interval(self.df, self._statistic_np, + confidence_level, self._alternative, + self._dtype, self._xp) + low = low * self._standard_error + self._estimate + high = high * self._standard_error + self._estimate + return ConfidenceInterval(low=low, high=high) + + +def pack_TtestResult(statistic, pvalue, df, alternative, standard_error, + estimate): + # this could be any number of dimensions (including 0d), but there is + # at most one unique non-NaN value + alternative = np.atleast_1d(alternative) # can't index 0D object + alternative = alternative[np.isfinite(alternative)] + alternative = alternative[0] if alternative.size else np.nan + return TtestResult(statistic, pvalue, df=df, alternative=alternative, + standard_error=standard_error, estimate=estimate) + + +def unpack_TtestResult(res): + return (res.statistic, res.pvalue, res.df, res._alternative, + res._standard_error, res._estimate) + + +@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, + result_to_tuple=unpack_TtestResult, n_outputs=6) +# nan_policy handled by `_axis_nan_policy`, but needs to be left +# in signature to preserve use as a positional argument +def ttest_1samp(a, popmean, axis=0, nan_policy="propagate", alternative="two-sided"): + """Calculate the T-test for the mean of ONE group of scores. + + This is a test for the null hypothesis that the expected value + (mean) of a sample of independent observations `a` is equal to the given + population mean, `popmean`. + + Parameters + ---------- + a : array_like + Sample observations. + popmean : float or array_like + Expected value in null hypothesis. If array_like, then its length along + `axis` must equal 1, and it must otherwise be broadcastable with `a`. + axis : int or None, optional + Axis along which to compute test; default is 0. If None, compute over + the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the mean of the underlying distribution of the sample + is different than the given population mean (`popmean`) + * 'less': the mean of the underlying distribution of the sample is + less than the given population mean (`popmean`) + * 'greater': the mean of the underlying distribution of the sample is + greater than the given population mean (`popmean`) + + Returns + ------- + result : `~scipy.stats._result_classes.TtestResult` + An object with the following attributes: + + statistic : float or array + The t-statistic. + pvalue : float or array + The p-value associated with the given alternative. + df : float or array + The number of degrees of freedom used in calculation of the + t-statistic; this is one less than the size of the sample + (``a.shape[axis]``). + + .. versionadded:: 1.10.0 + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the population + mean for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + .. versionadded:: 1.10.0 + + Notes + ----- + The statistic is calculated as ``(np.mean(a) - popmean)/se``, where + ``se`` is the standard error. Therefore, the statistic will be positive + when the sample mean is greater than the population mean and negative when + the sample mean is less than the population mean. + + Examples + -------- + Suppose we wish to test the null hypothesis that the mean of a population + is equal to 0.5. We choose a confidence level of 99%; that is, we will + reject the null hypothesis in favor of the alternative if the p-value is + less than 0.01. + + When testing random variates from the standard uniform distribution, which + has a mean of 0.5, we expect the data to be consistent with the null + hypothesis most of the time. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> rvs = stats.uniform.rvs(size=50, random_state=rng) + >>> stats.ttest_1samp(rvs, popmean=0.5) + TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49) + + As expected, the p-value of 0.017 is not below our threshold of 0.01, so + we cannot reject the null hypothesis. + + When testing data from the standard *normal* distribution, which has a mean + of 0, we would expect the null hypothesis to be rejected. + + >>> rvs = stats.norm.rvs(size=50, random_state=rng) + >>> stats.ttest_1samp(rvs, popmean=0.5) + TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49) + + Indeed, the p-value is lower than our threshold of 0.01, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the mean + of the population is *not* equal to 0.5. + + However, suppose we were to test the null hypothesis against the + one-sided alternative that the mean of the population is *greater* than + 0.5. Since the mean of the standard normal is less than 0.5, we would not + expect the null hypothesis to be rejected. + + >>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater') + TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49) + + Unsurprisingly, with a p-value greater than our threshold, we would not + reject the null hypothesis. + + Note that when working with a confidence level of 99%, a true null + hypothesis will be rejected approximately 1% of the time. + + >>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng) + >>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1) + >>> np.sum(res.pvalue < 0.01) + 1 + + Indeed, even though all 100 samples above were drawn from the standard + uniform distribution, which *does* have a population mean of 0.5, we would + mistakenly reject the null hypothesis for one of them. + + `ttest_1samp` can also compute a confidence interval around the population + mean. + + >>> rvs = stats.norm.rvs(size=50, random_state=rng) + >>> res = stats.ttest_1samp(rvs, popmean=0) + >>> ci = res.confidence_interval(confidence_level=0.95) + >>> ci + ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972) + + The bounds of the 95% confidence interval are the + minimum and maximum values of the parameter `popmean` for which the + p-value of the test would be 0.05. + + >>> res = stats.ttest_1samp(rvs, popmean=ci.low) + >>> np.testing.assert_allclose(res.pvalue, 0.05) + >>> res = stats.ttest_1samp(rvs, popmean=ci.high) + >>> np.testing.assert_allclose(res.pvalue, 0.05) + + Under certain assumptions about the population from which a sample + is drawn, the confidence interval with confidence level 95% is expected + to contain the true population mean in 95% of sample replications. + + >>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng) + >>> res = stats.ttest_1samp(rvs, popmean=0) + >>> ci = res.confidence_interval() + >>> contains_pop_mean = (ci.low < 1) & (ci.high > 1) + >>> contains_pop_mean.sum() + 953 + + """ + xp = array_namespace(a) + a, axis = _chk_asarray(a, axis, xp=xp) + + n = a.shape[axis] + df = n - 1 + + if n == 0: + # This is really only needed for *testing* _axis_nan_policy decorator + # It won't happen when the decorator is used. + NaN = _get_nan(a) + return TtestResult(NaN, NaN, df=NaN, alternative=NaN, + standard_error=NaN, estimate=NaN) + + mean = xp.mean(a, axis=axis) + try: + popmean = xp.asarray(popmean) + popmean = xp.squeeze(popmean, axis=axis) if popmean.ndim > 0 else popmean + except ValueError as e: + raise ValueError("`popmean.shape[axis]` must equal 1.") from e + d = mean - popmean + v = _var(a, axis=axis, ddof=1) + denom = xp.sqrt(v / n) + + with np.errstate(divide='ignore', invalid='ignore'): + t = xp.divide(d, denom) + t = t[()] if t.ndim == 0 else t + + dist = _SimpleStudentT(xp.asarray(df, dtype=t.dtype)) + prob = _get_pvalue(t, dist, alternative, xp=xp) + prob = prob[()] if prob.ndim == 0 else prob + + # when nan_policy='omit', `df` can be different for different axis-slices + df = xp.broadcast_to(xp.asarray(df), t.shape) + df = df[()] if df.ndim == 0 else df + # _axis_nan_policy decorator doesn't play well with strings + alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative] + return TtestResult(t, prob, df=df, alternative=alternative_num, + standard_error=denom, estimate=mean, + statistic_np=xp.asarray(t), xp=xp) + + +def _t_confidence_interval(df, t, confidence_level, alternative, dtype=None, xp=None): + # Input validation on `alternative` is already done + # We just need IV on confidence_level + dtype = t.dtype if dtype is None else dtype + xp = array_namespace(t) if xp is None else xp + + # stdtrit not dispatched yet; use NumPy + df, t = np.asarray(df), np.asarray(t) + + if confidence_level < 0 or confidence_level > 1: + message = "`confidence_level` must be a number between 0 and 1." + raise ValueError(message) + + if alternative < 0: # 'less' + p = confidence_level + low, high = np.broadcast_arrays(-np.inf, special.stdtrit(df, p)) + elif alternative > 0: # 'greater' + p = 1 - confidence_level + low, high = np.broadcast_arrays(special.stdtrit(df, p), np.inf) + elif alternative == 0: # 'two-sided' + tail_probability = (1 - confidence_level)/2 + p = tail_probability, 1-tail_probability + # axis of p must be the zeroth and orthogonal to all the rest + p = np.reshape(p, [2] + [1]*np.asarray(df).ndim) + low, high = special.stdtrit(df, p) + else: # alternative is NaN when input is empty (see _axis_nan_policy) + p, nans = np.broadcast_arrays(t, np.nan) + low, high = nans, nans + + low = xp.asarray(low, dtype=dtype) + low = low[()] if low.ndim == 0 else low + high = xp.asarray(high, dtype=dtype) + high = high[()] if high.ndim == 0 else high + return low, high + + +def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative, xp=None): + xp = array_namespace(mean1, mean2, denom) if xp is None else xp + + d = mean1 - mean2 + with np.errstate(divide='ignore', invalid='ignore'): + t = xp.divide(d, denom) + + t_np = np.asarray(t) + df_np = np.asarray(df) + prob = _get_pvalue(t_np, distributions.t(df_np), alternative, xp=np) + prob = xp.asarray(prob, dtype=t.dtype) + + t = t[()] if t.ndim == 0 else t + prob = prob[()] if prob.ndim == 0 else prob + return t, prob + + +def _unequal_var_ttest_denom(v1, n1, v2, n2, xp=None): + xp = array_namespace(v1, v2) if xp is None else xp + vn1 = v1 / n1 + vn2 = v2 / n2 + with np.errstate(divide='ignore', invalid='ignore'): + df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1)) + + # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0). + # Hence it doesn't matter what df is as long as it's not NaN. + df = xp.where(xp.isnan(df), xp.asarray(1.), df) + denom = xp.sqrt(vn1 + vn2) + return df, denom + + +def _equal_var_ttest_denom(v1, n1, v2, n2, xp=None): + xp = array_namespace(v1, v2) if xp is None else xp + + # If there is a single observation in one sample, this formula for pooled + # variance breaks down because the variance of that sample is undefined. + # The pooled variance is still defined, though, because the (n-1) in the + # numerator should cancel with the (n-1) in the denominator, leaving only + # the sum of squared differences from the mean: zero. + zero = xp.asarray(0.) + v1 = xp.where(xp.asarray(n1 == 1), zero, v1) + v2 = xp.where(xp.asarray(n2 == 1), zero, v2) + + df = n1 + n2 - 2.0 + svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df + denom = xp.sqrt(svar * (1.0 / n1 + 1.0 / n2)) + return df, denom + + +Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue')) + + +def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2, + equal_var=True, alternative="two-sided"): + r""" + T-test for means of two independent samples from descriptive statistics. + + This is a test for the null hypothesis that two independent + samples have identical average (expected) values. + + Parameters + ---------- + mean1 : array_like + The mean(s) of sample 1. + std1 : array_like + The corrected sample standard deviation of sample 1 (i.e. ``ddof=1``). + nobs1 : array_like + The number(s) of observations of sample 1. + mean2 : array_like + The mean(s) of sample 2. + std2 : array_like + The corrected sample standard deviation of sample 2 (i.e. ``ddof=1``). + nobs2 : array_like + The number(s) of observations of sample 2. + equal_var : bool, optional + If True (default), perform a standard independent 2 sample test + that assumes equal population variances [1]_. + If False, perform Welch's t-test, which does not assume equal + population variance [2]_. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions are unequal. + * 'less': the mean of the first distribution is less than the + mean of the second distribution. + * 'greater': the mean of the first distribution is greater than the + mean of the second distribution. + + .. versionadded:: 1.6.0 + + Returns + ------- + statistic : float or array + The calculated t-statistics. + pvalue : float or array + The two-tailed p-value. + + See Also + -------- + scipy.stats.ttest_ind + + Notes + ----- + The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the + standard error. Therefore, the statistic will be positive when `mean1` is + greater than `mean2` and negative when `mean1` is less than `mean2`. + + This method does not check whether any of the elements of `std1` or `std2` + are negative. If any elements of the `std1` or `std2` parameters are + negative in a call to this method, this method will return the same result + as if it were passed ``numpy.abs(std1)`` and ``numpy.abs(std2)``, + respectively, instead; no exceptions or warnings will be emitted. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test + + .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test + + Examples + -------- + Suppose we have the summary data for two samples, as follows (with the + Sample Variance being the corrected sample variance):: + + Sample Sample + Size Mean Variance + Sample 1 13 15.0 87.5 + Sample 2 11 12.0 39.0 + + Apply the t-test to this data (with the assumption that the population + variances are equal): + + >>> import numpy as np + >>> from scipy.stats import ttest_ind_from_stats + >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13, + ... mean2=12.0, std2=np.sqrt(39.0), nobs2=11) + Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487) + + For comparison, here is the data from which those summary statistics + were taken. With this data, we can compute the same result using + `scipy.stats.ttest_ind`: + + >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26]) + >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21]) + >>> from scipy.stats import ttest_ind + >>> ttest_ind(a, b) + TtestResult(statistic=0.905135809331027, + pvalue=0.3751996797581486, + df=22.0) + + Suppose we instead have binary data and would like to apply a t-test to + compare the proportion of 1s in two independent groups:: + + Number of Sample Sample + Size ones Mean Variance + Sample 1 150 30 0.2 0.161073 + Sample 2 200 45 0.225 0.175251 + + The sample mean :math:`\hat{p}` is the proportion of ones in the sample + and the variance for a binary observation is estimated by + :math:`\hat{p}(1-\hat{p})`. + + >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.161073), nobs1=150, + ... mean2=0.225, std2=np.sqrt(0.175251), nobs2=200) + Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541) + + For comparison, we could compute the t statistic and p-value using + arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above. + + >>> group1 = np.array([1]*30 + [0]*(150-30)) + >>> group2 = np.array([1]*45 + [0]*(200-45)) + >>> ttest_ind(group1, group2) + TtestResult(statistic=-0.5627179589855622, + pvalue=0.573989277115258, + df=348.0) + + """ + xp = array_namespace(mean1, std1, mean2, std2) + + mean1 = xp.asarray(mean1) + std1 = xp.asarray(std1) + mean2 = xp.asarray(mean2) + std2 = xp.asarray(std2) + + if equal_var: + df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp) + else: + df, denom = _unequal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp) + + res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative) + return Ttest_indResult(*res) + + +_ttest_ind_dep_msg = "Use ``method`` to perform a permutation test." +@_deprecate_positional_args(version='1.17.0', + deprecated_args={'permutations', 'random_state'}, + custom_message=_ttest_ind_dep_msg) +@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, + result_to_tuple=unpack_TtestResult, n_outputs=6) +def ttest_ind(a, b, *, axis=0, equal_var=True, nan_policy='propagate', + permutations=None, random_state=None, alternative="two-sided", + trim=0, method=None): + """ + Calculate the T-test for the means of *two independent* samples of scores. + + This is a test for the null hypothesis that 2 independent samples + have identical average (expected) values. This test assumes that the + populations have identical variances by default. + + Parameters + ---------- + a, b : array_like + The arrays must have the same shape, except in the dimension + corresponding to `axis` (the first, by default). + axis : int or None, optional + Axis along which to compute test. If None, compute over the whole + arrays, `a`, and `b`. + equal_var : bool, optional + If True (default), perform a standard independent 2 sample test + that assumes equal population variances [1]_. + If False, perform Welch's t-test, which does not assume equal + population variance [2]_. + + .. versionadded:: 0.11.0 + + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + The 'omit' option is not currently available for permutation tests or + one-sided asymptotic tests. + + permutations : non-negative int, np.inf, or None (default), optional + If 0 or None (default), use the t-distribution to calculate p-values. + Otherwise, `permutations` is the number of random permutations that + will be used to estimate p-values using a permutation test. If + `permutations` equals or exceeds the number of distinct partitions of + the pooled data, an exact test is performed instead (i.e. each + distinct partition is used exactly once). See Notes for details. + + .. deprecated:: 1.17.0 + `permutations` is deprecated and will be removed in SciPy 1.7.0. + Use the `n_resamples` argument of `PermutationMethod`, instead, + and pass the instance as the `method` argument. + + random_state : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + Pseudorandom number generator state used to generate permutations + (used only when `permutations` is not None). + + .. deprecated:: 1.17.0 + `random_state` is deprecated and will be removed in SciPy 1.7.0. + Use the `rng` argument of `PermutationMethod`, instead, + and pass the instance as the `method` argument. + + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions underlying the samples + are unequal. + * 'less': the mean of the distribution underlying the first sample + is less than the mean of the distribution underlying the second + sample. + * 'greater': the mean of the distribution underlying the first + sample is greater than the mean of the distribution underlying + the second sample. + + trim : float, optional + If nonzero, performs a trimmed (Yuen's) t-test. + Defines the fraction of elements to be trimmed from each end of the + input samples. If 0 (default), no elements will be trimmed from either + side. The number of trimmed elements from each tail is the floor of the + trim times the number of elements. Valid range is [0, .5). + method : ResamplingMethod, optional + Defines the method used to compute the p-value. If `method` is an + instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is + computed using + `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the + provided configuration options and other appropriate settings. + Otherwise, the p-value is computed by comparing the test statistic + against a theoretical t-distribution. + + .. versionadded:: 1.15.0 + + Returns + ------- + result : `~scipy.stats._result_classes.TtestResult` + An object with the following attributes: + + statistic : float or ndarray + The t-statistic. + pvalue : float or ndarray + The p-value associated with the given alternative. + df : float or ndarray + The number of degrees of freedom used in calculation of the + t-statistic. This is always NaN for a permutation t-test. + + .. versionadded:: 1.11.0 + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the difference in + population means for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields ``low`` and ``high``. + When a permutation t-test is performed, the confidence interval + is not computed, and fields ``low`` and ``high`` contain NaN. + + .. versionadded:: 1.11.0 + + Notes + ----- + Suppose we observe two independent samples, e.g. flower petal lengths, and + we are considering whether the two samples were drawn from the same + population (e.g. the same species of flower or two species with similar + petal characteristics) or two different populations. + + The t-test quantifies the difference between the arithmetic means + of the two samples. The p-value quantifies the probability of observing + as or more extreme values assuming the null hypothesis, that the + samples are drawn from populations with the same population means, is true. + A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that + our observation is not so unlikely to have occurred by chance. Therefore, + we do not reject the null hypothesis of equal population means. + If the p-value is smaller than our threshold, then we have evidence + against the null hypothesis of equal population means. + + By default, the p-value is determined by comparing the t-statistic of the + observed data against a theoretical t-distribution. + + (In the following, note that the argument `permutations` itself is + deprecated, but a nearly identical test may be performed by creating + an instance of `scipy.stats.PermutationMethod` with ``n_resamples=permutuations`` + and passing it as the `method` argument.) + When ``1 < permutations < binom(n, k)``, where + + * ``k`` is the number of observations in `a`, + * ``n`` is the total number of observations in `a` and `b`, and + * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``), + + the data are pooled (concatenated), randomly assigned to either group `a` + or `b`, and the t-statistic is calculated. This process is performed + repeatedly (`permutation` times), generating a distribution of the + t-statistic under the null hypothesis, and the t-statistic of the observed + data is compared to this distribution to determine the p-value. + Specifically, the p-value reported is the "achieved significance level" + (ASL) as defined in 4.4 of [3]_. Note that there are other ways of + estimating p-values using randomized permutation tests; for other + options, see the more general `permutation_test`. + + When ``permutations >= binom(n, k)``, an exact test is performed: the data + are partitioned between the groups in each distinct way exactly once. + + The permutation test can be computationally expensive and not necessarily + more accurate than the analytical test, but it does not make strong + assumptions about the shape of the underlying distribution. + + Use of trimming is commonly referred to as the trimmed t-test. At times + called Yuen's t-test, this is an extension of Welch's t-test, with the + difference being the use of winsorized means in calculation of the variance + and the trimmed sample size in calculation of the statistic. Trimming is + recommended if the underlying distribution is long-tailed or contaminated + with outliers [4]_. + + The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where + ``se`` is the standard error. Therefore, the statistic will be positive + when the sample mean of `a` is greater than the sample mean of `b` and + negative when the sample mean of `a` is less than the sample mean of + `b`. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test + + .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test + + .. [3] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016). + + .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population + Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR, + www.jstor.org/stable/2334299. Accessed 30 Mar. 2021. + + .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and + Performance of the Two-Sample Trimmed t." Biometrika, vol. 60, + no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550. + Accessed 30 Mar. 2021. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + + Test with sample with identical means: + + >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs2) + TtestResult(statistic=-0.4390847099199348, + pvalue=0.6606952038870015, + df=998.0) + >>> stats.ttest_ind(rvs1, rvs2, equal_var=False) + TtestResult(statistic=-0.4390847099199348, + pvalue=0.6606952553131064, + df=997.4602304121448) + + `ttest_ind` underestimates p for unequal variances: + + >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs3) + TtestResult(statistic=-1.6370984482905417, + pvalue=0.1019251574705033, + df=998.0) + >>> stats.ttest_ind(rvs1, rvs3, equal_var=False) + TtestResult(statistic=-1.637098448290542, + pvalue=0.10202110497954867, + df=765.1098655246868) + + When ``n1 != n2``, the equal variance t-statistic is no longer equal to the + unequal variance t-statistic: + + >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs4) + TtestResult(statistic=-1.9481646859513422, + pvalue=0.05186270935842703, + df=598.0) + >>> stats.ttest_ind(rvs1, rvs4, equal_var=False) + TtestResult(statistic=-1.3146566100751664, + pvalue=0.1913495266513811, + df=110.41349083985212) + + T-test with different means, variance, and n: + + >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng) + >>> stats.ttest_ind(rvs1, rvs5) + TtestResult(statistic=-2.8415950600298774, + pvalue=0.0046418707568707885, + df=598.0) + >>> stats.ttest_ind(rvs1, rvs5, equal_var=False) + TtestResult(statistic=-1.8686598649188084, + pvalue=0.06434714193919686, + df=109.32167496550137) + + Take these two samples, one of which has an extreme tail. + + >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3) + >>> b = (1.1, 2.9, 4.2) + + Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example, + using 20% trimming, ``trim=.2``, the test will reduce the impact of one + (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will + have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0. + + >>> stats.ttest_ind(a, b, trim=.2) + TtestResult(statistic=3.4463884028073513, + pvalue=0.01369338726499547, + df=6.0) + """ + xp = array_namespace(a, b) + + default_float = xp.asarray(1.).dtype + if xp.isdtype(a.dtype, 'integral'): + a = xp.astype(a, default_float) + if xp.isdtype(b.dtype, 'integral'): + b = xp.astype(b, default_float) + + if not (0 <= trim < .5): + raise ValueError("Trimming percentage should be 0 <= `trim` < .5.") + + if not isinstance(method, PermutationMethod | MonteCarloMethod | None): + message = ("`method` must be an instance of `PermutationMethod`, an instance " + "of `MonteCarloMethod`, or None (default).") + raise ValueError(message) + + if not is_numpy(xp) and method is not None: + message = "Use of resampling methods is compatible only with NumPy arrays." + raise NotImplementedError(message) + + result_shape = _broadcast_array_shapes_remove_axis((a, b), axis=axis) + NaN = xp.full(result_shape, _get_nan(a, b, xp=xp)) + NaN = NaN[()] if NaN.ndim == 0 else NaN + if xp_size(a) == 0 or xp_size(b) == 0: + return TtestResult(NaN, NaN, df=NaN, alternative=NaN, + standard_error=NaN, estimate=NaN) + + alternative_nums = {"less": -1, "two-sided": 0, "greater": 1} + + # This probably should be deprecated and replaced with a `method` argument + if permutations is not None and permutations != 0: + message = "Use of `permutations` is compatible only with NumPy arrays." + if not is_numpy(xp): + raise NotImplementedError(message) + + message = "Use of `permutations` is incompatible with with use of `trim`." + if trim != 0: + raise NotImplementedError(message) + + t, prob = _permutation_ttest(a, b, permutations=permutations, + axis=axis, equal_var=equal_var, + nan_policy=nan_policy, + random_state=random_state, + alternative=alternative) + df, denom, estimate = NaN, NaN, NaN + + # _axis_nan_policy decorator doesn't play well with strings + return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative], + standard_error=denom, estimate=estimate) + + n1 = xp.asarray(a.shape[axis], dtype=a.dtype) + n2 = xp.asarray(b.shape[axis], dtype=b.dtype) + + if trim == 0: + with np.errstate(divide='ignore', invalid='ignore'): + v1 = _var(a, axis, ddof=1, xp=xp) + v2 = _var(b, axis, ddof=1, xp=xp) + + m1 = xp.mean(a, axis=axis) + m2 = xp.mean(b, axis=axis) + else: + message = "Use of `trim` is compatible only with NumPy arrays." + if not is_numpy(xp): + raise NotImplementedError(message) + + v1, m1, n1 = _ttest_trim_var_mean_len(a, trim, axis) + v2, m2, n2 = _ttest_trim_var_mean_len(b, trim, axis) + + if equal_var: + df, denom = _equal_var_ttest_denom(v1, n1, v2, n2, xp=xp) + else: + df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2, xp=xp) + + if method is None: + t, prob = _ttest_ind_from_stats(m1, m2, denom, df, alternative) + else: + # nan_policy is taken care of by axis_nan_policy decorator + ttest_kwargs = dict(equal_var=equal_var, trim=trim) + t, prob = _ttest_resampling(a, b, axis, alternative, ttest_kwargs, method) + + # when nan_policy='omit', `df` can be different for different axis-slices + df = xp.broadcast_to(df, t.shape) + df = df[()] if df.ndim ==0 else df + estimate = m1 - m2 + + return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative], + standard_error=denom, estimate=estimate) + + +def _ttest_resampling(x, y, axis, alternative, ttest_kwargs, method): + def statistic(x, y, axis): + return ttest_ind(x, y, axis=axis, **ttest_kwargs).statistic + + test = (permutation_test if isinstance(method, PermutationMethod) + else monte_carlo_test) + method = method._asdict() + + if test is monte_carlo_test: + # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng` + # If the user specified an `rng`, replace it with the default callables + if (rng := method.pop('rng', None)) is not None: + rng = np.random.default_rng(rng) + method['rvs'] = rng.normal, rng.normal + + res = test((x, y,), statistic=statistic, axis=axis, + alternative=alternative, **method) + + return res.statistic, res.pvalue + + +def _ttest_trim_var_mean_len(a, trim, axis): + """Variance, mean, and length of winsorized input along specified axis""" + # for use with `ttest_ind` when trimming. + # further calculations in this test assume that the inputs are sorted. + # From [4] Section 1 "Let x_1, ..., x_n be n ordered observations..." + a = np.sort(a, axis=axis) + + # `g` is the number of elements to be replaced on each tail, converted + # from a percentage amount of trimming + n = a.shape[axis] + g = int(n * trim) + + # Calculate the Winsorized variance of the input samples according to + # specified `g` + v = _calculate_winsorized_variance(a, g, axis) + + # the total number of elements in the trimmed samples + n -= 2 * g + + # calculate the g-times trimmed mean, as defined in [4] (1-1) + m = trim_mean(a, trim, axis=axis) + return v, m, n + + +def _calculate_winsorized_variance(a, g, axis): + """Calculates g-times winsorized variance along specified axis""" + # it is expected that the input `a` is sorted along the correct axis + if g == 0: + return _var(a, ddof=1, axis=axis) + # move the intended axis to the end that way it is easier to manipulate + a_win = np.moveaxis(a, axis, -1) + + # save where NaNs are for later use. + nans_indices = np.any(np.isnan(a_win), axis=-1) + + # Winsorization and variance calculation are done in one step in [4] + # (1-3), but here winsorization is done first; replace the left and + # right sides with the repeating value. This can be see in effect in ( + # 1-3) in [4], where the leftmost and rightmost tails are replaced with + # `(g + 1) * x_{g + 1}` on the left and `(g + 1) * x_{n - g}` on the + # right. Zero-indexing turns `g + 1` to `g`, and `n - g` to `- g - 1` in + # array indexing. + a_win[..., :g] = a_win[..., [g]] + a_win[..., -g:] = a_win[..., [-g - 1]] + + # Determine the variance. In [4], the degrees of freedom is expressed as + # `h - 1`, where `h = n - 2g` (unnumbered equations in Section 1, end of + # page 369, beginning of page 370). This is converted to NumPy's format, + # `n - ddof` for use with `np.var`. The result is converted to an + # array to accommodate indexing later. + var_win = np.asarray(_var(a_win, ddof=(2 * g + 1), axis=-1)) + + # with `nan_policy='propagate'`, NaNs may be completely trimmed out + # because they were sorted into the tail of the array. In these cases, + # replace computed variances with `np.nan`. + var_win[nans_indices] = np.nan + return var_win + + +def _permutation_distribution_t(data, permutations, size_a, equal_var, + random_state=None): + """Generation permutation distribution of t statistic""" + + random_state = check_random_state(random_state) + + # prepare permutation indices + size = data.shape[-1] + # number of distinct combinations + n_max = special.comb(size, size_a) + + if permutations < n_max: + perm_generator = (random_state.permutation(size) + for i in range(permutations)) + else: + permutations = n_max + perm_generator = (np.concatenate(z) + for z in _all_partitions(size_a, size-size_a)) + + t_stat = [] + for indices in _batch_generator(perm_generator, batch=50): + # get one batch from perm_generator at a time as a list + indices = np.array(indices) + # generate permutations + data_perm = data[..., indices] + # move axis indexing permutations to position 0 to broadcast + # nicely with t_stat_observed, which doesn't have this dimension + data_perm = np.moveaxis(data_perm, -2, 0) + + a = data_perm[..., :size_a] + b = data_perm[..., size_a:] + t_stat.append(_calc_t_stat(a, b, equal_var)) + + t_stat = np.concatenate(t_stat, axis=0) + + return t_stat, permutations, n_max + + +def _calc_t_stat(a, b, equal_var, axis=-1): + """Calculate the t statistic along the given dimension.""" + na = a.shape[axis] + nb = b.shape[axis] + avg_a = np.mean(a, axis=axis) + avg_b = np.mean(b, axis=axis) + var_a = _var(a, axis=axis, ddof=1) + var_b = _var(b, axis=axis, ddof=1) + + if not equal_var: + _, denom = _unequal_var_ttest_denom(var_a, na, var_b, nb) + else: + _, denom = _equal_var_ttest_denom(var_a, na, var_b, nb) + + return (avg_a-avg_b)/denom + + +def _permutation_ttest(a, b, permutations, axis=0, equal_var=True, + nan_policy='propagate', random_state=None, + alternative="two-sided"): + """ + Calculates the T-test for the means of TWO INDEPENDENT samples of scores + using permutation methods. + + This test is similar to `stats.ttest_ind`, except it doesn't rely on an + approximate normality assumption since it uses a permutation test. + This function is only called from ttest_ind when permutations is not None. + + Parameters + ---------- + a, b : array_like + The arrays must be broadcastable, except along the dimension + corresponding to `axis` (the zeroth, by default). + axis : int, optional + The axis over which to operate on a and b. + permutations : int, optional + Number of permutations used to calculate p-value. If greater than or + equal to the number of distinct permutations, perform an exact test. + equal_var : bool, optional + If False, an equal variance (Welch's) t-test is conducted. Otherwise, + an ordinary t-test is conducted. + random_state : {None, int, `numpy.random.Generator`}, optional + If `seed` is None the `numpy.random.Generator` singleton is used. + If `seed` is an int, a new ``Generator`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` instance then that instance is + used. + Pseudorandom number generator state used for generating random + permutations. + + Returns + ------- + statistic : float or array + The calculated t-statistic. + pvalue : float or array + The p-value. + + """ + if permutations < 0 or (np.isfinite(permutations) and + int(permutations) != permutations): + raise ValueError("Permutations must be a non-negative integer.") + + random_state = check_random_state(random_state) + + t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis) + + na = a.shape[axis] + mat = _broadcast_concatenate((a, b), axis=axis) + mat = np.moveaxis(mat, axis, -1) + + t_stat, permutations, n_max = _permutation_distribution_t( + mat, permutations, size_a=na, equal_var=equal_var, + random_state=random_state) + + compare = {"less": np.less_equal, + "greater": np.greater_equal, + "two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))} + + # Calculate the p-values + cmps = compare[alternative](t_stat, t_stat_observed) + # Randomized test p-value calculation should use biased estimate; see e.g. + # https://www.degruyter.com/document/doi/10.2202/1544-6115.1585/ + adjustment = 1 if n_max > permutations else 0 + pvalues = (cmps.sum(axis=0) + adjustment) / (permutations + adjustment) + + # nans propagate naturally in statistic calculation, but need to be + # propagated manually into pvalues + if nan_policy == 'propagate' and np.isnan(t_stat_observed).any(): + if np.ndim(pvalues) == 0: + pvalues = np.float64(np.nan) + else: + pvalues[np.isnan(t_stat_observed)] = np.nan + + return (t_stat_observed, pvalues) + + +def _get_len(a, axis, msg): + try: + n = a.shape[axis] + except IndexError: + raise AxisError(axis, a.ndim, msg) from None + return n + + +@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2, + result_to_tuple=unpack_TtestResult, n_outputs=6, + paired=True) +def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"): + """Calculate the t-test on TWO RELATED samples of scores, a and b. + + This is a test for the null hypothesis that two related or + repeated samples have identical average (expected) values. + + Parameters + ---------- + a, b : array_like + The arrays must have the same shape. + axis : int or None, optional + Axis along which to compute test. If None, compute over the whole + arrays, `a`, and `b`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the means of the distributions underlying the samples + are unequal. + * 'less': the mean of the distribution underlying the first sample + is less than the mean of the distribution underlying the second + sample. + * 'greater': the mean of the distribution underlying the first + sample is greater than the mean of the distribution underlying + the second sample. + + .. versionadded:: 1.6.0 + + Returns + ------- + result : `~scipy.stats._result_classes.TtestResult` + An object with the following attributes: + + statistic : float or array + The t-statistic. + pvalue : float or array + The p-value associated with the given alternative. + df : float or array + The number of degrees of freedom used in calculation of the + t-statistic; this is one less than the size of the sample + (``a.shape[axis]``). + + .. versionadded:: 1.10.0 + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the difference in + population means for the given confidence level. + The confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. + + .. versionadded:: 1.10.0 + + Notes + ----- + Examples for use are scores of the same set of student in + different exams, or repeated sampling from the same units. The + test measures whether the average score differs significantly + across samples (e.g. exams). If we observe a large p-value, for + example greater than 0.05 or 0.1 then we cannot reject the null + hypothesis of identical average scores. If the p-value is smaller + than the threshold, e.g. 1%, 5% or 10%, then we reject the null + hypothesis of equal averages. Small p-values are associated with + large t-statistics. + + The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the + standard error. Therefore, the t-statistic will be positive when the sample + mean of ``a - b`` is greater than zero and negative when the sample mean of + ``a - b`` is less than zero. + + References + ---------- + https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + + >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng)) + >>> stats.ttest_rel(rvs1, rvs2) + TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499) + >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng) + ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng)) + >>> stats.ttest_rel(rvs1, rvs3) + TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499) + + """ + return ttest_1samp(a - b, popmean=0, axis=axis, alternative=alternative, + _no_deco=True) + + +# Map from names to lambda_ values used in power_divergence(). +_power_div_lambda_names = { + "pearson": 1, + "log-likelihood": 0, + "freeman-tukey": -0.5, + "mod-log-likelihood": -1, + "neyman": -2, + "cressie-read": 2/3, +} + + +def _m_count(a, *, axis, xp): + """Count the number of non-masked elements of an array. + + This function behaves like `np.ma.count`, but is much faster + for ndarrays. + """ + if hasattr(a, 'count'): + num = a.count(axis=axis) + if isinstance(num, np.ndarray) and num.ndim == 0: + # In some cases, the `count` method returns a scalar array (e.g. + # np.array(3)), but we want a plain integer. + num = int(num) + else: + if axis is None: + num = xp_size(a) + else: + num = a.shape[axis] + return num + + +def _m_broadcast_to(a, shape, *, xp): + if np.ma.isMaskedArray(a): + return np.ma.masked_array(np.broadcast_to(a, shape), + mask=np.broadcast_to(a.mask, shape)) + return xp.broadcast_to(a, shape) + + +def _m_sum(a, *, axis, preserve_mask, xp): + if np.ma.isMaskedArray(a): + sum = a.sum(axis) + return sum if preserve_mask else np.asarray(sum) + return xp.sum(a, axis=axis) + + +def _m_mean(a, *, axis, keepdims, xp): + if np.ma.isMaskedArray(a): + return np.asarray(a.mean(axis=axis, keepdims=keepdims)) + return xp.mean(a, axis=axis, keepdims=keepdims) + + +Power_divergenceResult = namedtuple('Power_divergenceResult', + ('statistic', 'pvalue')) + + +def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None): + """Cressie-Read power divergence statistic and goodness of fit test. + + This function tests the null hypothesis that the categorical data + has the given frequencies, using the Cressie-Read power divergence + statistic. + + Parameters + ---------- + f_obs : array_like + Observed frequencies in each category. + + .. deprecated:: 1.14.0 + Support for masked array input was deprecated in + SciPy 1.14.0 and will be removed in version 1.16.0. + + f_exp : array_like, optional + Expected frequencies in each category. By default the categories are + assumed to be equally likely. + + .. deprecated:: 1.14.0 + Support for masked array input was deprecated in + SciPy 1.14.0 and will be removed in version 1.16.0. + + ddof : int, optional + "Delta degrees of freedom": adjustment to the degrees of freedom + for the p-value. The p-value is computed using a chi-squared + distribution with ``k - 1 - ddof`` degrees of freedom, where `k` + is the number of observed frequencies. The default value of `ddof` + is 0. + axis : int or None, optional + The axis of the broadcast result of `f_obs` and `f_exp` along which to + apply the test. If axis is None, all values in `f_obs` are treated + as a single data set. Default is 0. + lambda_ : float or str, optional + The power in the Cressie-Read power divergence statistic. The default + is 1. For convenience, `lambda_` may be assigned one of the following + strings, in which case the corresponding numerical value is used: + + * ``"pearson"`` (value 1) + Pearson's chi-squared statistic. In this case, the function is + equivalent to `chisquare`. + * ``"log-likelihood"`` (value 0) + Log-likelihood ratio. Also known as the G-test [3]_. + * ``"freeman-tukey"`` (value -1/2) + Freeman-Tukey statistic. + * ``"mod-log-likelihood"`` (value -1) + Modified log-likelihood ratio. + * ``"neyman"`` (value -2) + Neyman's statistic. + * ``"cressie-read"`` (value 2/3) + The power recommended in [5]_. + + Returns + ------- + res: Power_divergenceResult + An object containing attributes: + + statistic : float or ndarray + The Cressie-Read power divergence test statistic. The value is + a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D. + pvalue : float or ndarray + The p-value of the test. The value is a float if `ddof` and the + return value `stat` are scalars. + + See Also + -------- + chisquare + + Notes + ----- + This test is invalid when the observed or expected frequencies in each + category are too small. A typical rule is that all of the observed + and expected frequencies should be at least 5. + + Also, the sum of the observed and expected frequencies must be the same + for the test to be valid; `power_divergence` raises an error if the sums + do not agree within a relative tolerance of ``eps**0.5``, where ``eps`` + is the precision of the input dtype. + + When `lambda_` is less than zero, the formula for the statistic involves + dividing by `f_obs`, so a warning or error may be generated if any value + in `f_obs` is 0. + + Similarly, a warning or error may be generated if any value in `f_exp` is + zero when `lambda_` >= 0. + + The default degrees of freedom, k-1, are for the case when no parameters + of the distribution are estimated. If p parameters are estimated by + efficient maximum likelihood then the correct degrees of freedom are + k-1-p. If the parameters are estimated in a different way, then the + dof can be between k-1-p and k-1. However, it is also possible that + the asymptotic distribution is not a chisquare, in which case this + test is not appropriate. + + References + ---------- + .. [1] Lowry, Richard. "Concepts and Applications of Inferential + Statistics". Chapter 8. + https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html + .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test + .. [3] "G-test", https://en.wikipedia.org/wiki/G-test + .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and + practice of statistics in biological research", New York: Freeman + (1981) + .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit + Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984), + pp. 440-464. + + Examples + -------- + (See `chisquare` for more examples.) + + When just `f_obs` is given, it is assumed that the expected frequencies + are uniform and given by the mean of the observed frequencies. Here we + perform a G-test (i.e. use the log-likelihood ratio statistic): + + >>> import numpy as np + >>> from scipy.stats import power_divergence + >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood') + (2.006573162632538, 0.84823476779463769) + + The expected frequencies can be given with the `f_exp` argument: + + >>> power_divergence([16, 18, 16, 14, 12, 12], + ... f_exp=[16, 16, 16, 16, 16, 8], + ... lambda_='log-likelihood') + (3.3281031458963746, 0.6495419288047497) + + When `f_obs` is 2-D, by default the test is applied to each column. + + >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T + >>> obs.shape + (6, 2) + >>> power_divergence(obs, lambda_="log-likelihood") + (array([ 2.00657316, 6.77634498]), array([ 0.84823477, 0.23781225])) + + By setting ``axis=None``, the test is applied to all data in the array, + which is equivalent to applying the test to the flattened array. + + >>> power_divergence(obs, axis=None) + (23.31034482758621, 0.015975692534127565) + >>> power_divergence(obs.ravel()) + (23.31034482758621, 0.015975692534127565) + + `ddof` is the change to make to the default degrees of freedom. + + >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1) + (2.0, 0.73575888234288467) + + The calculation of the p-values is done by broadcasting the + test statistic with `ddof`. + + >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2]) + (2.0, array([ 0.84914504, 0.73575888, 0.5724067 ])) + + `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has + shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting + `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared + statistics, we must use ``axis=1``: + + >>> power_divergence([16, 18, 16, 14, 12, 12], + ... f_exp=[[16, 16, 16, 16, 16, 8], + ... [8, 20, 20, 16, 12, 12]], + ... axis=1) + (array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846])) + + """ + return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, lambda_=lambda_) + + +def _power_divergence(f_obs, f_exp, ddof, axis, lambda_, sum_check=True): + xp = array_namespace(f_obs) + default_float = xp.asarray(1.).dtype + + # Convert the input argument `lambda_` to a numerical value. + if isinstance(lambda_, str): + if lambda_ not in _power_div_lambda_names: + names = repr(list(_power_div_lambda_names.keys()))[1:-1] + raise ValueError(f"invalid string for lambda_: {lambda_!r}. " + f"Valid strings are {names}") + lambda_ = _power_div_lambda_names[lambda_] + elif lambda_ is None: + lambda_ = 1 + + def warn_masked(arg): + if isinstance(arg, ma.MaskedArray): + message = ( + "`power_divergence` and `chisquare` support for masked array input was " + "deprecated in SciPy 1.14.0 and will be removed in version 1.16.0.") + warnings.warn(message, DeprecationWarning, stacklevel=2) + + warn_masked(f_obs) + f_obs = f_obs if np.ma.isMaskedArray(f_obs) else xp.asarray(f_obs) + dtype = default_float if xp.isdtype(f_obs.dtype, 'integral') else f_obs.dtype + f_obs = (f_obs.astype(dtype) if np.ma.isMaskedArray(f_obs) + else xp.asarray(f_obs, dtype=dtype)) + f_obs_float = (f_obs.astype(np.float64) if hasattr(f_obs, 'mask') + else xp.asarray(f_obs, dtype=xp.float64)) + + if f_exp is not None: + warn_masked(f_exp) + f_exp = f_exp if np.ma.isMaskedArray(f_obs) else xp.asarray(f_exp) + dtype = default_float if xp.isdtype(f_exp.dtype, 'integral') else f_exp.dtype + f_exp = (f_exp.astype(dtype) if np.ma.isMaskedArray(f_exp) + else xp.asarray(f_exp, dtype=dtype)) + + bshape = _broadcast_shapes((f_obs_float.shape, f_exp.shape)) + f_obs_float = _m_broadcast_to(f_obs_float, bshape, xp=xp) + f_exp = _m_broadcast_to(f_exp, bshape, xp=xp) + + if sum_check: + dtype_res = xp.result_type(f_obs.dtype, f_exp.dtype) + rtol = xp.finfo(dtype_res).eps**0.5 # to pass existing tests + with np.errstate(invalid='ignore'): + f_obs_sum = _m_sum(f_obs_float, axis=axis, preserve_mask=False, xp=xp) + f_exp_sum = _m_sum(f_exp, axis=axis, preserve_mask=False, xp=xp) + relative_diff = (xp.abs(f_obs_sum - f_exp_sum) / + xp.minimum(f_obs_sum, f_exp_sum)) + diff_gt_tol = xp.any(relative_diff > rtol, axis=None) + if diff_gt_tol: + msg = (f"For each axis slice, the sum of the observed " + f"frequencies must agree with the sum of the " + f"expected frequencies to a relative tolerance " + f"of {rtol}, but the percent differences are:\n" + f"{relative_diff}") + raise ValueError(msg) + + else: + # Ignore 'invalid' errors so the edge case of a data set with length 0 + # is handled without spurious warnings. + with np.errstate(invalid='ignore'): + f_exp = _m_mean(f_obs, axis=axis, keepdims=True, xp=xp) + + # `terms` is the array of terms that are summed along `axis` to create + # the test statistic. We use some specialized code for a few special + # cases of lambda_. + if lambda_ == 1: + # Pearson's chi-squared statistic + terms = (f_obs - f_exp)**2 / f_exp + elif lambda_ == 0: + # Log-likelihood ratio (i.e. G-test) + terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp) + elif lambda_ == -1: + # Modified log-likelihood ratio + terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs) + else: + # General Cressie-Read power divergence. + terms = f_obs * ((f_obs / f_exp)**lambda_ - 1) + terms /= 0.5 * lambda_ * (lambda_ + 1) + + stat = _m_sum(terms, axis=axis, preserve_mask=True, xp=xp) + + num_obs = _m_count(terms, axis=axis, xp=xp) + ddof = xp.asarray(ddof) + + df = xp.asarray(num_obs - 1 - ddof) + chi2 = _SimpleChi2(df) + pvalue = _get_pvalue(stat, chi2 , alternative='greater', symmetric=False, xp=xp) + + stat = stat[()] if stat.ndim == 0 else stat + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return Power_divergenceResult(stat, pvalue) + + +def chisquare(f_obs, f_exp=None, ddof=0, axis=0, *, sum_check=True): + """Perform Pearson's chi-squared test. + + Pearson's chi-squared test [1]_ is a goodness-of-fit test for a multinomial + distribution with given probabilities; that is, it assesses the null hypothesis + that the observed frequencies (counts) are obtained by independent + sampling of *N* observations from a categorical distribution with given + expected frequencies. + + Parameters + ---------- + f_obs : array_like + Observed frequencies in each category. + f_exp : array_like, optional + Expected frequencies in each category. By default, the categories are + assumed to be equally likely. + ddof : int, optional + "Delta degrees of freedom": adjustment to the degrees of freedom + for the p-value. The p-value is computed using a chi-squared + distribution with ``k - 1 - ddof`` degrees of freedom, where ``k`` + is the number of categories. The default value of `ddof` is 0. + axis : int or None, optional + The axis of the broadcast result of `f_obs` and `f_exp` along which to + apply the test. If axis is None, all values in `f_obs` are treated + as a single data set. Default is 0. + sum_check : bool, optional + Whether to perform a check that ``sum(f_obs) - sum(f_exp) == 0``. If True, + (default) raise an error when the relative difference exceeds the square root + of the precision of the data type. See Notes for rationale and possible + exceptions. + + Returns + ------- + res: Power_divergenceResult + An object containing attributes: + + statistic : float or ndarray + The chi-squared test statistic. The value is a float if `axis` is + None or `f_obs` and `f_exp` are 1-D. + pvalue : float or ndarray + The p-value of the test. The value is a float if `ddof` and the + result attribute `statistic` are scalars. + + See Also + -------- + scipy.stats.power_divergence + scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table. + scipy.stats.barnard_exact : An unconditional exact test. An alternative + to chi-squared test for small sample sizes. + :ref:`hypothesis_chisquare` : Extended example + + Notes + ----- + This test is invalid when the observed or expected frequencies in each + category are too small. A typical rule is that all of the observed + and expected frequencies should be at least 5. According to [2]_, the + total number of observations is recommended to be greater than 13, + otherwise exact tests (such as Barnard's Exact test) should be used + because they do not overreject. + + The default degrees of freedom, k-1, are for the case when no parameters + of the distribution are estimated. If p parameters are estimated by + efficient maximum likelihood then the correct degrees of freedom are + k-1-p. If the parameters are estimated in a different way, then the + dof can be between k-1-p and k-1. However, it is also possible that + the asymptotic distribution is not chi-square, in which case this test + is not appropriate. + + For Pearson's chi-squared test, the total observed and expected counts must match + for the p-value to accurately reflect the probability of observing such an extreme + value of the statistic under the null hypothesis. + This function may be used to perform other statistical tests that do not require + the total counts to be equal. For instance, to test the null hypothesis that + ``f_obs[i]`` is Poisson-distributed with expectation ``f_exp[i]``, set ``ddof=-1`` + and ``sum_check=False``. This test follows from the fact that a Poisson random + variable with mean and variance ``f_exp[i]`` is approximately normal with the + same mean and variance; the chi-squared statistic standardizes, squares, and sums + the observations; and the sum of ``n`` squared standard normal variables follows + the chi-squared distribution with ``n`` degrees of freedom. + + References + ---------- + .. [1] "Pearson's chi-squared test". + *Wikipedia*. https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test + .. [2] Pearson, Karl. "On the criterion that a given system of deviations from the probable + in the case of a correlated system of variables is such that it can be reasonably + supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50 + (1900), pp. 157-175. + + Examples + -------- + When only the mandatory `f_obs` argument is given, it is assumed that the + expected frequencies are uniform and given by the mean of the observed + frequencies: + + >>> import numpy as np + >>> from scipy.stats import chisquare + >>> chisquare([16, 18, 16, 14, 12, 12]) + Power_divergenceResult(statistic=2.0, pvalue=0.84914503608460956) + + The optional `f_exp` argument gives the expected frequencies. + + >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8]) + Power_divergenceResult(statistic=3.5, pvalue=0.62338762774958223) + + When `f_obs` is 2-D, by default the test is applied to each column. + + >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T + >>> obs.shape + (6, 2) + >>> chisquare(obs) + Power_divergenceResult(statistic=array([2. , 6.66666667]), pvalue=array([0.84914504, 0.24663415])) + + By setting ``axis=None``, the test is applied to all data in the array, + which is equivalent to applying the test to the flattened array. + + >>> chisquare(obs, axis=None) + Power_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565) + >>> chisquare(obs.ravel()) + Power_divergenceResult(statistic=23.310344827586206, pvalue=0.01597569253412758) + + `ddof` is the change to make to the default degrees of freedom. + + >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1) + Power_divergenceResult(statistic=2.0, pvalue=0.7357588823428847) + + The calculation of the p-values is done by broadcasting the + chi-squared statistic with `ddof`. + + >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0, 1, 2]) + Power_divergenceResult(statistic=2.0, pvalue=array([0.84914504, 0.73575888, 0.5724067 ])) + + `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has + shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting + `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared + statistics, we use ``axis=1``: + + >>> chisquare([16, 18, 16, 14, 12, 12], + ... f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]], + ... axis=1) + Power_divergenceResult(statistic=array([3.5 , 9.25]), pvalue=array([0.62338763, 0.09949846])) + + For a more detailed example, see :ref:`hypothesis_chisquare`. + """ # noqa: E501 + return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, + lambda_="pearson", sum_check=sum_check) + + +KstestResult = _make_tuple_bunch('KstestResult', ['statistic', 'pvalue'], + ['statistic_location', 'statistic_sign']) + + +def _compute_dplus(cdfvals, x): + """Computes D+ as used in the Kolmogorov-Smirnov test. + + Parameters + ---------- + cdfvals : array_like + Sorted array of CDF values between 0 and 1 + x: array_like + Sorted array of the stochastic variable itself + + Returns + ------- + res: Pair with the following elements: + - The maximum distance of the CDF values below Uniform(0, 1). + - The location at which the maximum is reached. + + """ + n = len(cdfvals) + dplus = (np.arange(1.0, n + 1) / n - cdfvals) + amax = dplus.argmax() + loc_max = x[amax] + return (dplus[amax], loc_max) + + +def _compute_dminus(cdfvals, x): + """Computes D- as used in the Kolmogorov-Smirnov test. + + Parameters + ---------- + cdfvals : array_like + Sorted array of CDF values between 0 and 1 + x: array_like + Sorted array of the stochastic variable itself + + Returns + ------- + res: Pair with the following elements: + - Maximum distance of the CDF values above Uniform(0, 1) + - The location at which the maximum is reached. + """ + n = len(cdfvals) + dminus = (cdfvals - np.arange(0.0, n)/n) + amax = dminus.argmax() + loc_max = x[amax] + return (dminus[amax], loc_max) + + +def _tuple_to_KstestResult(statistic, pvalue, + statistic_location, statistic_sign): + return KstestResult(statistic, pvalue, + statistic_location=statistic_location, + statistic_sign=statistic_sign) + + +def _KstestResult_to_tuple(res): + return *res, res.statistic_location, res.statistic_sign + + +@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=1, n_outputs=4, + result_to_tuple=_KstestResult_to_tuple) +@_rename_parameter("mode", "method") +def ks_1samp(x, cdf, args=(), alternative='two-sided', method='auto'): + """ + Performs the one-sample Kolmogorov-Smirnov test for goodness of fit. + + This test compares the underlying distribution F(x) of a sample + against a given continuous distribution G(x). See Notes for a description + of the available null and alternative hypotheses. + + Parameters + ---------- + x : array_like + a 1-D array of observations of iid random variables. + cdf : callable + callable used to calculate the cdf. + args : tuple, sequence, optional + Distribution parameters, used with `cdf`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes below. + method : {'auto', 'exact', 'approx', 'asymp'}, optional + Defines the distribution used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : selects one of the other options. + * 'exact' : uses the exact distribution of test statistic. + * 'approx' : approximates the two-sided probability with twice + the one-sided probability + * 'asymp': uses asymptotic distribution of test statistic + + Returns + ------- + res: KstestResult + An object containing attributes: + + statistic : float + KS test statistic, either D+, D-, or D (the maximum of the two) + pvalue : float + One-tailed or two-tailed p-value. + statistic_location : float + Value of `x` corresponding with the KS statistic; i.e., the + distance between the empirical distribution function and the + hypothesized cumulative distribution function is measured at this + observation. + statistic_sign : int + +1 if the KS statistic is the maximum positive difference between + the empirical distribution function and the hypothesized cumulative + distribution function (D+); -1 if the KS statistic is the maximum + negative difference (D-). + + + See Also + -------- + ks_2samp, kstest + + Notes + ----- + There are three options for the null and corresponding alternative + hypothesis that can be selected using the `alternative` parameter. + + - `two-sided`: The null hypothesis is that the two distributions are + identical, F(x)=G(x) for all x; the alternative is that they are not + identical. + + - `less`: The null hypothesis is that F(x) >= G(x) for all x; the + alternative is that F(x) < G(x) for at least one x. + + - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the + alternative is that F(x) > G(x) for at least one x. + + Note that the alternative hypotheses describe the *CDFs* of the + underlying distributions, not the observed values. For example, + suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in + x1 tend to be less than those in x2. + + Examples + -------- + Suppose we wish to test the null hypothesis that a sample is distributed + according to the standard normal. + We choose a confidence level of 95%; that is, we will reject the null + hypothesis in favor of the alternative if the p-value is less than 0.05. + + When testing uniformly distributed data, we would expect the + null hypothesis to be rejected. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng), + ... stats.norm.cdf) + KstestResult(statistic=0.5001899973268688, + pvalue=1.1616392184763533e-23, + statistic_location=0.00047625268963724654, + statistic_sign=-1) + + Indeed, the p-value is lower than our threshold of 0.05, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the data + are *not* distributed according to the standard normal. + + When testing random variates from the standard normal distribution, we + expect the data to be consistent with the null hypothesis most of the time. + + >>> x = stats.norm.rvs(size=100, random_state=rng) + >>> stats.ks_1samp(x, stats.norm.cdf) + KstestResult(statistic=0.05345882212970396, + pvalue=0.9227159037744717, + statistic_location=-1.2451343873745018, + statistic_sign=1) + + As expected, the p-value of 0.92 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + Suppose, however, that the random variates are distributed according to + a normal distribution that is shifted toward greater values. In this case, + the cumulative density function (CDF) of the underlying distribution tends + to be *less* than the CDF of the standard normal. Therefore, we would + expect the null hypothesis to be rejected with ``alternative='less'``: + + >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng) + >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less') + KstestResult(statistic=0.17482387821055168, + pvalue=0.001913921057766743, + statistic_location=0.3713830565352756, + statistic_sign=-1) + + and indeed, with p-value smaller than our threshold, we reject the null + hypothesis in favor of the alternative. + + """ + mode = method + + alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( + alternative.lower()[0], alternative) + if alternative not in ['two-sided', 'greater', 'less']: + raise ValueError(f"Unexpected value {alternative=}") + + N = len(x) + x = np.sort(x) + cdfvals = cdf(x, *args) + np_one = np.int8(1) + + if alternative == 'greater': + Dplus, d_location = _compute_dplus(cdfvals, x) + return KstestResult(Dplus, distributions.ksone.sf(Dplus, N), + statistic_location=d_location, + statistic_sign=np_one) + + if alternative == 'less': + Dminus, d_location = _compute_dminus(cdfvals, x) + return KstestResult(Dminus, distributions.ksone.sf(Dminus, N), + statistic_location=d_location, + statistic_sign=-np_one) + + # alternative == 'two-sided': + Dplus, dplus_location = _compute_dplus(cdfvals, x) + Dminus, dminus_location = _compute_dminus(cdfvals, x) + if Dplus > Dminus: + D = Dplus + d_location = dplus_location + d_sign = np_one + else: + D = Dminus + d_location = dminus_location + d_sign = -np_one + + if mode == 'auto': # Always select exact + mode = 'exact' + if mode == 'exact': + prob = distributions.kstwo.sf(D, N) + elif mode == 'asymp': + prob = distributions.kstwobign.sf(D * np.sqrt(N)) + else: + # mode == 'approx' + prob = 2 * distributions.ksone.sf(D, N) + prob = np.clip(prob, 0, 1) + return KstestResult(D, prob, + statistic_location=d_location, + statistic_sign=d_sign) + + +Ks_2sampResult = KstestResult + + +def _compute_prob_outside_square(n, h): + """ + Compute the proportion of paths that pass outside the two diagonal lines. + + Parameters + ---------- + n : integer + n > 0 + h : integer + 0 <= h <= n + + Returns + ------- + p : float + The proportion of paths that pass outside the lines x-y = +/-h. + + """ + # Compute Pr(D_{n,n} >= h/n) + # Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... ) + # / binom(2n, n) + # This formulation exhibits subtractive cancellation. + # Instead divide each term by binom(2n, n), then factor common terms + # and use a Horner-like algorithm + # P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...))))) + + P = 0.0 + k = int(np.floor(n / h)) + while k >= 0: + p1 = 1.0 + # Each of the Ai terms has numerator and denominator with + # h simple terms. + for j in range(h): + p1 = (n - k * h - j) * p1 / (n + k * h + j + 1) + P = p1 * (1.0 - P) + k -= 1 + return 2 * P + + +def _count_paths_outside_method(m, n, g, h): + """Count the number of paths that pass outside the specified diagonal. + + Parameters + ---------- + m : integer + m > 0 + n : integer + n > 0 + g : integer + g is greatest common divisor of m and n + h : integer + 0 <= h <= lcm(m,n) + + Returns + ------- + p : float + The number of paths that go low. + The calculation may overflow - check for a finite answer. + + Notes + ----- + Count the integer lattice paths from (0, 0) to (m, n), which at some + point (x, y) along the path, satisfy: + m*y <= n*x - h*g + The paths make steps of size +1 in either positive x or positive y + directions. + + We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk. + Hodges, J.L. Jr., + "The Significance Probability of the Smirnov Two-Sample Test," + Arkiv fiur Matematik, 3, No. 43 (1958), 469-86. + + """ + # Compute #paths which stay lower than x/m-y/n = h/lcm(m,n) + # B(x, y) = #{paths from (0,0) to (x,y) without + # previously crossing the boundary} + # = binom(x, y) - #{paths which already reached the boundary} + # Multiply by the number of path extensions going from (x, y) to (m, n) + # Sum. + + # Probability is symmetrical in m, n. Computation below assumes m >= n. + if m < n: + m, n = n, m + mg = m // g + ng = n // g + + # Not every x needs to be considered. + # xj holds the list of x values to be checked. + # Wherever n*x/m + ng*h crosses an integer + lxj = n + (mg-h)//mg + xj = [(h + mg * j + ng-1)//ng for j in range(lxj)] + # B is an array just holding a few values of B(x,y), the ones needed. + # B[j] == B(x_j, j) + if lxj == 0: + return special.binom(m + n, n) + B = np.zeros(lxj) + B[0] = 1 + # Compute the B(x, y) terms + for j in range(1, lxj): + Bj = special.binom(xj[j] + j, j) + for i in range(j): + bin = special.binom(xj[j] - xj[i] + j - i, j-i) + Bj -= bin * B[i] + B[j] = Bj + # Compute the number of path extensions... + num_paths = 0 + for j in range(lxj): + bin = special.binom((m-xj[j]) + (n - j), n-j) + term = B[j] * bin + num_paths += term + return num_paths + + +def _attempt_exact_2kssamp(n1, n2, g, d, alternative): + """Attempts to compute the exact 2sample probability. + + n1, n2 are the sample sizes + g is the gcd(n1, n2) + d is the computed max difference in ECDFs + + Returns (success, d, probability) + """ + lcm = (n1 // g) * n2 + h = int(np.round(d * lcm)) + d = h * 1.0 / lcm + if h == 0: + return True, d, 1.0 + saw_fp_error, prob = False, np.nan + try: + with np.errstate(invalid="raise", over="raise"): + if alternative == 'two-sided': + if n1 == n2: + prob = _compute_prob_outside_square(n1, h) + else: + prob = _compute_outer_prob_inside_method(n1, n2, g, h) + else: + if n1 == n2: + # prob = binom(2n, n-h) / binom(2n, n) + # Evaluating in that form incurs roundoff errors + # from special.binom. Instead calculate directly + jrange = np.arange(h) + prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0)) + else: + with np.errstate(over='raise'): + num_paths = _count_paths_outside_method(n1, n2, g, h) + bin = special.binom(n1 + n2, n1) + if num_paths > bin or np.isinf(bin): + saw_fp_error = True + else: + prob = num_paths / bin + + except (FloatingPointError, OverflowError): + saw_fp_error = True + + if saw_fp_error: + return False, d, np.nan + if not (0 <= prob <= 1): + return False, d, prob + return True, d, prob + + +@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=2, n_outputs=4, + result_to_tuple=_KstestResult_to_tuple) +@_rename_parameter("mode", "method") +def ks_2samp(data1, data2, alternative='two-sided', method='auto'): + """ + Performs the two-sample Kolmogorov-Smirnov test for goodness of fit. + + This test compares the underlying continuous distributions F(x) and G(x) + of two independent samples. See Notes for a description of the available + null and alternative hypotheses. + + Parameters + ---------- + data1, data2 : array_like, 1-Dimensional + Two arrays of sample observations assumed to be drawn from a continuous + distribution, sample sizes can be different. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes below. + method : {'auto', 'exact', 'asymp'}, optional + Defines the method used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : use 'exact' for small size arrays, 'asymp' for large + * 'exact' : use exact distribution of test statistic + * 'asymp' : use asymptotic distribution of test statistic + + Returns + ------- + res: KstestResult + An object containing attributes: + + statistic : float + KS test statistic. + pvalue : float + One-tailed or two-tailed p-value. + statistic_location : float + Value from `data1` or `data2` corresponding with the KS statistic; + i.e., the distance between the empirical distribution functions is + measured at this observation. + statistic_sign : int + +1 if the empirical distribution function of `data1` exceeds + the empirical distribution function of `data2` at + `statistic_location`, otherwise -1. + + See Also + -------- + kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp + + Notes + ----- + There are three options for the null and corresponding alternative + hypothesis that can be selected using the `alternative` parameter. + + - `less`: The null hypothesis is that F(x) >= G(x) for all x; the + alternative is that F(x) < G(x) for at least one x. The statistic + is the magnitude of the minimum (most negative) difference between the + empirical distribution functions of the samples. + + - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the + alternative is that F(x) > G(x) for at least one x. The statistic + is the maximum (most positive) difference between the empirical + distribution functions of the samples. + + - `two-sided`: The null hypothesis is that the two distributions are + identical, F(x)=G(x) for all x; the alternative is that they are not + identical. The statistic is the maximum absolute difference between the + empirical distribution functions of the samples. + + Note that the alternative hypotheses describe the *CDFs* of the + underlying distributions, not the observed values of the data. For example, + suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in + x1 tend to be less than those in x2. + + If the KS statistic is large, then the p-value will be small, and this may + be taken as evidence against the null hypothesis in favor of the + alternative. + + If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value, + that is, the probability under the null hypothesis of obtaining a test + statistic value as extreme as the value computed from the data. + If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is + used to compute an approximate p-value. + If ``method='auto'``, an exact p-value computation is attempted if both + sample sizes are less than 10000; otherwise, the asymptotic method is used. + In any case, if an exact p-value calculation is attempted and fails, a + warning will be emitted, and the asymptotic p-value will be returned. + + The 'two-sided' 'exact' computation computes the complementary probability + and then subtracts from 1. As such, the minimum probability it can return + is about 1e-16. While the algorithm itself is exact, numerical + errors may accumulate for large sample sizes. It is most suited to + situations in which one of the sample sizes is only a few thousand. + + We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_. + + References + ---------- + .. [1] Hodges, J.L. Jr., "The Significance Probability of the Smirnov + Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-486. + + Examples + -------- + Suppose we wish to test the null hypothesis that two samples were drawn + from the same distribution. + We choose a confidence level of 95%; that is, we will reject the null + hypothesis in favor of the alternative if the p-value is less than 0.05. + + If the first sample were drawn from a uniform distribution and the second + were drawn from the standard normal, we would expect the null hypothesis + to be rejected. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> sample1 = stats.uniform.rvs(size=100, random_state=rng) + >>> sample2 = stats.norm.rvs(size=110, random_state=rng) + >>> stats.ks_2samp(sample1, sample2) + KstestResult(statistic=0.5454545454545454, + pvalue=7.37417839555191e-15, + statistic_location=-0.014071496412861274, + statistic_sign=-1) + + + Indeed, the p-value is lower than our threshold of 0.05, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the data + were *not* drawn from the same distribution. + + When both samples are drawn from the same distribution, we expect the data + to be consistent with the null hypothesis most of the time. + + >>> sample1 = stats.norm.rvs(size=105, random_state=rng) + >>> sample2 = stats.norm.rvs(size=95, random_state=rng) + >>> stats.ks_2samp(sample1, sample2) + KstestResult(statistic=0.10927318295739348, + pvalue=0.5438289009927495, + statistic_location=-0.1670157701848795, + statistic_sign=-1) + + As expected, the p-value of 0.54 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + Suppose, however, that the first sample were drawn from + a normal distribution shifted toward greater values. In this case, + the cumulative density function (CDF) of the underlying distribution tends + to be *less* than the CDF underlying the second sample. Therefore, we would + expect the null hypothesis to be rejected with ``alternative='less'``: + + >>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng) + >>> stats.ks_2samp(sample1, sample2, alternative='less') + KstestResult(statistic=0.4055137844611529, + pvalue=3.5474563068855554e-08, + statistic_location=-0.13249370614972575, + statistic_sign=-1) + + and indeed, with p-value smaller than our threshold, we reject the null + hypothesis in favor of the alternative. + + """ + mode = method + + if mode not in ['auto', 'exact', 'asymp']: + raise ValueError(f'Invalid value for mode: {mode}') + alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get( + alternative.lower()[0], alternative) + if alternative not in ['two-sided', 'less', 'greater']: + raise ValueError(f'Invalid value for alternative: {alternative}') + MAX_AUTO_N = 10000 # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N + if np.ma.is_masked(data1): + data1 = data1.compressed() + if np.ma.is_masked(data2): + data2 = data2.compressed() + data1 = np.sort(data1) + data2 = np.sort(data2) + n1 = data1.shape[0] + n2 = data2.shape[0] + if min(n1, n2) == 0: + raise ValueError('Data passed to ks_2samp must not be empty') + + data_all = np.concatenate([data1, data2]) + # using searchsorted solves equal data problem + cdf1 = np.searchsorted(data1, data_all, side='right') / n1 + cdf2 = np.searchsorted(data2, data_all, side='right') / n2 + cddiffs = cdf1 - cdf2 + + # Identify the location of the statistic + argminS = np.argmin(cddiffs) + argmaxS = np.argmax(cddiffs) + loc_minS = data_all[argminS] + loc_maxS = data_all[argmaxS] + + # Ensure sign of minS is not negative. + minS = np.clip(-cddiffs[argminS], 0, 1) + maxS = cddiffs[argmaxS] + + if alternative == 'less' or (alternative == 'two-sided' and minS > maxS): + d = minS + d_location = loc_minS + d_sign = -1 + else: + d = maxS + d_location = loc_maxS + d_sign = 1 + g = gcd(n1, n2) + n1g = n1 // g + n2g = n2 // g + prob = -np.inf + if mode == 'auto': + mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp' + elif mode == 'exact': + # If lcm(n1, n2) is too big, switch from exact to asymp + if n1g >= np.iinfo(np.int32).max / n2g: + mode = 'asymp' + warnings.warn( + f"Exact ks_2samp calculation not possible with samples sizes " + f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning, + stacklevel=3) + + if mode == 'exact': + success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative) + if not success: + mode = 'asymp' + warnings.warn(f"ks_2samp: Exact calculation unsuccessful. " + f"Switching to method={mode}.", RuntimeWarning, + stacklevel=3) + + if mode == 'asymp': + # The product n1*n2 is large. Use Smirnov's asymptotic formula. + # Ensure float to avoid overflow in multiplication + # sorted because the one-sided formula is not symmetric in n1, n2 + m, n = sorted([float(n1), float(n2)], reverse=True) + en = m * n / (m + n) + if alternative == 'two-sided': + prob = distributions.kstwo.sf(d, np.round(en)) + else: + z = np.sqrt(en) * d + # Use Hodges' suggested approximation Eqn 5.3 + # Requires m to be the larger of (n1, n2) + expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0 + prob = np.exp(expt) + + prob = np.clip(prob, 0, 1) + # Currently, `d` is a Python float. We want it to be a NumPy type, so + # float64 is appropriate. An enhancement would be for `d` to respect the + # dtype of the input. + return KstestResult(np.float64(d), prob, statistic_location=d_location, + statistic_sign=np.int8(d_sign)) + + +def _parse_kstest_args(data1, data2, args, N): + # kstest allows many different variations of arguments. + # Pull out the parsing into a separate function + # (xvals, yvals, ) # 2sample + # (xvals, cdf function,..) + # (xvals, name of distribution, ...) + # (name of distribution, name of distribution, ...) + + # Returns xvals, yvals, cdf + # where cdf is a cdf function, or None + # and yvals is either an array_like of values, or None + # and xvals is array_like. + rvsfunc, cdf = None, None + if isinstance(data1, str): + rvsfunc = getattr(distributions, data1).rvs + elif callable(data1): + rvsfunc = data1 + + if isinstance(data2, str): + cdf = getattr(distributions, data2).cdf + data2 = None + elif callable(data2): + cdf = data2 + data2 = None + + data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1) + return data1, data2, cdf + + +def _kstest_n_samples(kwargs): + cdf = kwargs['cdf'] + return 1 if (isinstance(cdf, str) or callable(cdf)) else 2 + + +@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=_kstest_n_samples, + n_outputs=4, result_to_tuple=_KstestResult_to_tuple) +@_rename_parameter("mode", "method") +def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', method='auto'): + """ + Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for + goodness of fit. + + The one-sample test compares the underlying distribution F(x) of a sample + against a given distribution G(x). The two-sample test compares the + underlying distributions of two independent samples. Both tests are valid + only for continuous distributions. + + Parameters + ---------- + rvs : str, array_like, or callable + If an array, it should be a 1-D array of observations of random + variables. + If a callable, it should be a function to generate random variables; + it is required to have a keyword argument `size`. + If a string, it should be the name of a distribution in `scipy.stats`, + which will be used to generate random variables. + cdf : str, array_like or callable + If array_like, it should be a 1-D array of observations of random + variables, and the two-sample test is performed + (and rvs must be array_like). + If a callable, that callable is used to calculate the cdf. + If a string, it should be the name of a distribution in `scipy.stats`, + which will be used as the cdf function. + args : tuple, sequence, optional + Distribution parameters, used if `rvs` or `cdf` are strings or + callables. + N : int, optional + Sample size if `rvs` is string or callable. Default is 20. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the null and alternative hypotheses. Default is 'two-sided'. + Please see explanations in the Notes below. + method : {'auto', 'exact', 'approx', 'asymp'}, optional + Defines the distribution used for calculating the p-value. + The following options are available (default is 'auto'): + + * 'auto' : selects one of the other options. + * 'exact' : uses the exact distribution of test statistic. + * 'approx' : approximates the two-sided probability with twice the + one-sided probability + * 'asymp': uses asymptotic distribution of test statistic + + Returns + ------- + res: KstestResult + An object containing attributes: + + statistic : float + KS test statistic, either D+, D-, or D (the maximum of the two) + pvalue : float + One-tailed or two-tailed p-value. + statistic_location : float + In a one-sample test, this is the value of `rvs` + corresponding with the KS statistic; i.e., the distance between + the empirical distribution function and the hypothesized cumulative + distribution function is measured at this observation. + + In a two-sample test, this is the value from `rvs` or `cdf` + corresponding with the KS statistic; i.e., the distance between + the empirical distribution functions is measured at this + observation. + statistic_sign : int + In a one-sample test, this is +1 if the KS statistic is the + maximum positive difference between the empirical distribution + function and the hypothesized cumulative distribution function + (D+); it is -1 if the KS statistic is the maximum negative + difference (D-). + + In a two-sample test, this is +1 if the empirical distribution + function of `rvs` exceeds the empirical distribution + function of `cdf` at `statistic_location`, otherwise -1. + + See Also + -------- + ks_1samp, ks_2samp + + Notes + ----- + There are three options for the null and corresponding alternative + hypothesis that can be selected using the `alternative` parameter. + + - `two-sided`: The null hypothesis is that the two distributions are + identical, F(x)=G(x) for all x; the alternative is that they are not + identical. + + - `less`: The null hypothesis is that F(x) >= G(x) for all x; the + alternative is that F(x) < G(x) for at least one x. + + - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the + alternative is that F(x) > G(x) for at least one x. + + Note that the alternative hypotheses describe the *CDFs* of the + underlying distributions, not the observed values. For example, + suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in + x1 tend to be less than those in x2. + + + Examples + -------- + Suppose we wish to test the null hypothesis that a sample is distributed + according to the standard normal. + We choose a confidence level of 95%; that is, we will reject the null + hypothesis in favor of the alternative if the p-value is less than 0.05. + + When testing uniformly distributed data, we would expect the + null hypothesis to be rejected. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng), + ... stats.norm.cdf) + KstestResult(statistic=0.5001899973268688, + pvalue=1.1616392184763533e-23, + statistic_location=0.00047625268963724654, + statistic_sign=-1) + + Indeed, the p-value is lower than our threshold of 0.05, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the data + are *not* distributed according to the standard normal. + + When testing random variates from the standard normal distribution, we + expect the data to be consistent with the null hypothesis most of the time. + + >>> x = stats.norm.rvs(size=100, random_state=rng) + >>> stats.kstest(x, stats.norm.cdf) + KstestResult(statistic=0.05345882212970396, + pvalue=0.9227159037744717, + statistic_location=-1.2451343873745018, + statistic_sign=1) + + + As expected, the p-value of 0.92 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + Suppose, however, that the random variates are distributed according to + a normal distribution that is shifted toward greater values. In this case, + the cumulative density function (CDF) of the underlying distribution tends + to be *less* than the CDF of the standard normal. Therefore, we would + expect the null hypothesis to be rejected with ``alternative='less'``: + + >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng) + >>> stats.kstest(x, stats.norm.cdf, alternative='less') + KstestResult(statistic=0.17482387821055168, + pvalue=0.001913921057766743, + statistic_location=0.3713830565352756, + statistic_sign=-1) + + and indeed, with p-value smaller than our threshold, we reject the null + hypothesis in favor of the alternative. + + For convenience, the previous test can be performed using the name of the + distribution as the second argument. + + >>> stats.kstest(x, "norm", alternative='less') + KstestResult(statistic=0.17482387821055168, + pvalue=0.001913921057766743, + statistic_location=0.3713830565352756, + statistic_sign=-1) + + The examples above have all been one-sample tests identical to those + performed by `ks_1samp`. Note that `kstest` can also perform two-sample + tests identical to those performed by `ks_2samp`. For example, when two + samples are drawn from the same distribution, we expect the data to be + consistent with the null hypothesis most of the time. + + >>> sample1 = stats.laplace.rvs(size=105, random_state=rng) + >>> sample2 = stats.laplace.rvs(size=95, random_state=rng) + >>> stats.kstest(sample1, sample2) + KstestResult(statistic=0.11779448621553884, + pvalue=0.4494256912629795, + statistic_location=0.6138814275424155, + statistic_sign=1) + + As expected, the p-value of 0.45 is not below our threshold of 0.05, so + we cannot reject the null hypothesis. + + """ + # to not break compatibility with existing code + if alternative == 'two_sided': + alternative = 'two-sided' + if alternative not in ['two-sided', 'greater', 'less']: + raise ValueError(f"Unexpected alternative: {alternative}") + xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N) + if cdf: + return ks_1samp(xvals, cdf, args=args, alternative=alternative, + method=method, _no_deco=True) + return ks_2samp(xvals, yvals, alternative=alternative, method=method, + _no_deco=True) + + +def tiecorrect(rankvals): + """Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests. + + Parameters + ---------- + rankvals : array_like + A 1-D sequence of ranks. Typically this will be the array + returned by `~scipy.stats.rankdata`. + + Returns + ------- + factor : float + Correction factor for U or H. + + See Also + -------- + rankdata : Assign ranks to the data + mannwhitneyu : Mann-Whitney rank test + kruskal : Kruskal-Wallis H test + + References + ---------- + .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral + Sciences. New York: McGraw-Hill. + + Examples + -------- + >>> from scipy.stats import tiecorrect, rankdata + >>> tiecorrect([1, 2.5, 2.5, 4]) + 0.9 + >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4]) + >>> ranks + array([ 1. , 4. , 2.5, 5.5, 7. , 8. , 2.5, 9. , 5.5]) + >>> tiecorrect(ranks) + 0.9833333333333333 + + """ + arr = np.sort(rankvals) + idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0] + cnt = np.diff(idx).astype(np.float64) + + size = np.float64(arr.size) + return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size) + + +RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(RanksumsResult, n_samples=2) +def ranksums(x, y, alternative='two-sided'): + """Compute the Wilcoxon rank-sum statistic for two samples. + + The Wilcoxon rank-sum test tests the null hypothesis that two sets + of measurements are drawn from the same distribution. The alternative + hypothesis is that values in one sample are more likely to be + larger than the values in the other sample. + + This test should be used to compare two samples from continuous + distributions. It does not handle ties between measurements + in x and y. For tie-handling and an optional continuity correction + see `scipy.stats.mannwhitneyu`. + + Parameters + ---------- + x,y : array_like + The data from the two samples. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': one of the distributions (underlying `x` or `y`) is + stochastically greater than the other. + * 'less': the distribution underlying `x` is stochastically less + than the distribution underlying `y`. + * 'greater': the distribution underlying `x` is stochastically greater + than the distribution underlying `y`. + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The test statistic under the large-sample approximation that the + rank sum statistic is normally distributed. + pvalue : float + The p-value of the test. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test + + Examples + -------- + We can test the hypothesis that two independent unequal-sized samples are + drawn from the same distribution with computing the Wilcoxon rank-sum + statistic. + + >>> import numpy as np + >>> from scipy.stats import ranksums + >>> rng = np.random.default_rng() + >>> sample1 = rng.uniform(-1, 1, 200) + >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution + >>> ranksums(sample1, sample2) + RanksumsResult(statistic=-7.887059, + pvalue=3.09390448e-15) # may vary + >>> ranksums(sample1, sample2, alternative='less') + RanksumsResult(statistic=-7.750585297581713, + pvalue=4.573497606342543e-15) # may vary + >>> ranksums(sample1, sample2, alternative='greater') + RanksumsResult(statistic=-7.750585297581713, + pvalue=0.9999999999999954) # may vary + + The p-value of less than ``0.05`` indicates that this test rejects the + hypothesis at the 5% significance level. + + """ + x, y = map(np.asarray, (x, y)) + n1 = len(x) + n2 = len(y) + alldata = np.concatenate((x, y)) + ranked = rankdata(alldata) + x = ranked[:n1] + s = np.sum(x, axis=0) + expected = n1 * (n1+n2+1) / 2.0 + z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0) + pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + + return RanksumsResult(z[()], pvalue[()]) + + +KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(KruskalResult, n_samples=None) +def kruskal(*samples, nan_policy='propagate'): + """Compute the Kruskal-Wallis H-test for independent samples. + + The Kruskal-Wallis H-test tests the null hypothesis that the population + median of all of the groups are equal. It is a non-parametric version of + ANOVA. The test works on 2 or more independent samples, which may have + different sizes. Note that rejecting the null hypothesis does not + indicate which of the groups differs. Post hoc comparisons between + groups are required to determine which groups are different. + + Parameters + ---------- + sample1, sample2, ... : array_like + Two or more arrays with the sample measurements can be given as + arguments. Samples must be one-dimensional. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + statistic : float + The Kruskal-Wallis H statistic, corrected for ties. + pvalue : float + The p-value for the test using the assumption that H has a chi + square distribution. The p-value returned is the survival function of + the chi square distribution evaluated at H. + + See Also + -------- + f_oneway : 1-way ANOVA. + mannwhitneyu : Mann-Whitney rank test on two samples. + friedmanchisquare : Friedman test for repeated measurements. + + Notes + ----- + Due to the assumption that H has a chi square distribution, the number + of samples in each group must not be too small. A typical rule is + that each sample must have at least 5 measurements. + + References + ---------- + .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in + One-Criterion Variance Analysis", Journal of the American Statistical + Association, Vol. 47, Issue 260, pp. 583-621, 1952. + .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance + + Examples + -------- + >>> from scipy import stats + >>> x = [1, 3, 5, 7, 9] + >>> y = [2, 4, 6, 8, 10] + >>> stats.kruskal(x, y) + KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895) + + >>> x = [1, 1, 1] + >>> y = [2, 2, 2] + >>> z = [2, 2] + >>> stats.kruskal(x, y, z) + KruskalResult(statistic=7.0, pvalue=0.0301973834223185) + + """ + samples = list(map(np.asarray, samples)) + + num_groups = len(samples) + if num_groups < 2: + raise ValueError("Need at least two groups in stats.kruskal()") + + n = np.asarray(list(map(len, samples))) + + alldata = np.concatenate(samples) + ranked = rankdata(alldata) + ties = tiecorrect(ranked) + if ties == 0: + raise ValueError('All numbers are identical in kruskal') + + # Compute sum^2/n for each group and sum + j = np.insert(np.cumsum(n), 0, 0) + ssbn = 0 + for i in range(num_groups): + ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i] + + totaln = np.sum(n, dtype=float) + h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1) + df = num_groups - 1 + h /= ties + + chi2 = _SimpleChi2(df) + pvalue = _get_pvalue(h, chi2, alternative='greater', symmetric=False, xp=np) + return KruskalResult(h, pvalue) + + +FriedmanchisquareResult = namedtuple('FriedmanchisquareResult', + ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(FriedmanchisquareResult, n_samples=None, paired=True) +def friedmanchisquare(*samples): + """Compute the Friedman test for repeated samples. + + The Friedman test tests the null hypothesis that repeated samples of + the same individuals have the same distribution. It is often used + to test for consistency among samples obtained in different ways. + For example, if two sampling techniques are used on the same set of + individuals, the Friedman test can be used to determine if the two + sampling techniques are consistent. + + Parameters + ---------- + sample1, sample2, sample3... : array_like + Arrays of observations. All of the arrays must have the same number + of elements. At least three samples must be given. + + Returns + ------- + statistic : float + The test statistic, correcting for ties. + pvalue : float + The associated p-value assuming that the test statistic has a chi + squared distribution. + + See Also + -------- + :ref:`hypothesis_friedmanchisquare` : Extended example + + Notes + ----- + Due to the assumption that the test statistic has a chi squared + distribution, the p-value is only reliable for n > 10 and more than + 6 repeated samples. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Friedman_test + .. [2] Demsar, J. (2006). Statistical comparisons of classifiers over + multiple data sets. Journal of Machine Learning Research, 7, 1-30. + + Examples + -------- + + >>> import numpy as np + >>> rng = np.random.default_rng(seed=18) + >>> x = rng.random((6, 10)) + >>> from scipy.stats import friedmanchisquare + >>> res = friedmanchisquare(x[0], x[1], x[2], x[3], x[4], x[5]) + >>> res.statistic, res.pvalue + (11.428571428571416, 0.043514520866727614) + + The p-value is less than 0.05; however, as noted above, the results may not + be reliable since we have a small number of repeated samples. + + For a more detailed example, see :ref:`hypothesis_friedmanchisquare`. + """ + k = len(samples) + if k < 3: + raise ValueError('At least 3 sets of samples must be given ' + f'for Friedman test, got {k}.') + + n = len(samples[0]) + for i in range(1, k): + if len(samples[i]) != n: + raise ValueError('Unequal N in friedmanchisquare. Aborting.') + + # Rank data + data = np.vstack(samples).T + data = data.astype(float) + for i in range(len(data)): + data[i] = rankdata(data[i]) + + # Handle ties + ties = 0 + for d in data: + _, repnum = _find_repeats(np.array(d, dtype=np.float64)) + for t in repnum: + ties += t * (t*t - 1) + c = 1 - ties / (k*(k*k - 1)*n) + + ssbn = np.sum(data.sum(axis=0)**2) + statistic = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c + + chi2 = _SimpleChi2(k - 1) + pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np) + return FriedmanchisquareResult(statistic, pvalue) + + +BrunnerMunzelResult = namedtuple('BrunnerMunzelResult', + ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(BrunnerMunzelResult, n_samples=2) +def brunnermunzel(x, y, alternative="two-sided", distribution="t", + nan_policy='propagate'): + """Compute the Brunner-Munzel test on samples x and y. + + The Brunner-Munzel test is a nonparametric test of the null hypothesis that + when values are taken one by one from each group, the probabilities of + getting large values in both groups are equal. + Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the + assumption of equivariance of two groups. Note that this does not assume + the distributions are same. This test works on two independent samples, + which may have different sizes. + + Parameters + ---------- + x, y : array_like + Array of samples, should be one-dimensional. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided' + * 'less': one-sided + * 'greater': one-sided + distribution : {'t', 'normal'}, optional + Defines how to get the p-value. + The following options are available (default is 't'): + + * 't': get the p-value by t-distribution + * 'normal': get the p-value by standard normal distribution. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': returns nan + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + + Returns + ------- + statistic : float + The Brunner-Munzer W statistic. + pvalue : float + p-value assuming an t distribution. One-sided or + two-sided, depending on the choice of `alternative` and `distribution`. + + See Also + -------- + mannwhitneyu : Mann-Whitney rank test on two samples. + + Notes + ----- + Brunner and Munzel recommended to estimate the p-value by t-distribution + when the size of data is 50 or less. If the size is lower than 10, it would + be better to use permuted Brunner Munzel test (see [2]_). + + References + ---------- + .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher + problem: Asymptotic theory and a small-sample approximation". + Biometrical Journal. Vol. 42(2000): 17-25. + .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the + non-parametric Behrens-Fisher problem". Computational Statistics and + Data Analysis. Vol. 51(2007): 5192-5204. + + Examples + -------- + >>> from scipy import stats + >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1] + >>> x2 = [3,3,4,3,1,2,3,1,1,5,4] + >>> w, p_value = stats.brunnermunzel(x1, x2) + >>> w + 3.1374674823029505 + >>> p_value + 0.0057862086661515377 + + """ + nx = len(x) + ny = len(y) + + rankc = rankdata(np.concatenate((x, y))) + rankcx = rankc[0:nx] + rankcy = rankc[nx:nx+ny] + rankcx_mean = np.mean(rankcx) + rankcy_mean = np.mean(rankcy) + rankx = rankdata(x) + ranky = rankdata(y) + rankx_mean = np.mean(rankx) + ranky_mean = np.mean(ranky) + + Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0)) + Sx /= nx - 1 + Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0)) + Sy /= ny - 1 + + wbfn = nx * ny * (rankcy_mean - rankcx_mean) + wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy) + + if distribution == "t": + df_numer = np.power(nx * Sx + ny * Sy, 2.0) + df_denom = np.power(nx * Sx, 2.0) / (nx - 1) + df_denom += np.power(ny * Sy, 2.0) / (ny - 1) + df = df_numer / df_denom + + if (df_numer == 0) and (df_denom == 0): + message = ("p-value cannot be estimated with `distribution='t' " + "because degrees of freedom parameter is undefined " + "(0/0). Try using `distribution='normal'") + warnings.warn(message, RuntimeWarning, stacklevel=2) + + distribution = _SimpleStudentT(df) + elif distribution == "normal": + distribution = _SimpleNormal() + else: + raise ValueError( + "distribution should be 't' or 'normal'") + + p = _get_pvalue(-wbfn, distribution, alternative, xp=np) + + return BrunnerMunzelResult(wbfn, p) + + +@_axis_nan_policy_factory(SignificanceResult, kwd_samples=['weights'], paired=True) +def combine_pvalues(pvalues, method='fisher', weights=None, *, axis=0): + """ + Combine p-values from independent tests that bear upon the same hypothesis. + + These methods are intended only for combining p-values from hypothesis + tests based upon continuous distributions. + + Each method assumes that under the null hypothesis, the p-values are + sampled independently and uniformly from the interval [0, 1]. A test + statistic (different for each method) is computed and a combined + p-value is calculated based upon the distribution of this test statistic + under the null hypothesis. + + Parameters + ---------- + pvalues : array_like + Array of p-values assumed to come from independent tests based on + continuous distributions. + method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'} + + Name of method to use to combine p-values. + + The available methods are (see Notes for details): + + * 'fisher': Fisher's method (Fisher's combined probability test) + * 'pearson': Pearson's method + * 'mudholkar_george': Mudholkar's and George's method + * 'tippett': Tippett's method + * 'stouffer': Stouffer's Z-score method + weights : array_like, optional + Optional array of weights used only for Stouffer's Z-score method. + Ignored by other methods. + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : float + The statistic calculated by the specified method. + pvalue : float + The combined p-value. + + Examples + -------- + Suppose we wish to combine p-values from four independent tests + of the same null hypothesis using Fisher's method (default). + + >>> from scipy.stats import combine_pvalues + >>> pvalues = [0.1, 0.05, 0.02, 0.3] + >>> combine_pvalues(pvalues) + SignificanceResult(statistic=20.828626352604235, pvalue=0.007616871850449092) + + When the individual p-values carry different weights, consider Stouffer's + method. + + >>> weights = [1, 2, 3, 4] + >>> res = combine_pvalues(pvalues, method='stouffer', weights=weights) + >>> res.pvalue + 0.009578891494533616 + + Notes + ----- + If this function is applied to tests with a discrete statistics such as + any rank test or contingency-table test, it will yield systematically + wrong results, e.g. Fisher's method will systematically overestimate the + p-value [1]_. This problem becomes less severe for large sample sizes + when the discrete distributions become approximately continuous. + + The differences between the methods can be best illustrated by their + statistics and what aspects of a combination of p-values they emphasise + when considering significance [2]_. For example, methods emphasising large + p-values are more sensitive to strong false and true negatives; conversely + methods focussing on small p-values are sensitive to positives. + + * The statistics of Fisher's method (also known as Fisher's combined + probability test) [3]_ is :math:`-2\\sum_i \\log(p_i)`, which is + equivalent (as a test statistics) to the product of individual p-values: + :math:`\\prod_i p_i`. Under the null hypothesis, this statistics follows + a :math:`\\chi^2` distribution. This method emphasises small p-values. + * Pearson's method uses :math:`-2\\sum_i\\log(1-p_i)`, which is equivalent + to :math:`\\prod_i \\frac{1}{1-p_i}` [2]_. + It thus emphasises large p-values. + * Mudholkar and George compromise between Fisher's and Pearson's method by + averaging their statistics [4]_. Their method emphasises extreme + p-values, both close to 1 and 0. + * Stouffer's method [5]_ uses Z-scores and the statistic: + :math:`\\sum_i \\Phi^{-1} (p_i)`, where :math:`\\Phi` is the CDF of the + standard normal distribution. The advantage of this method is that it is + straightforward to introduce weights, which can make Stouffer's method + more powerful than Fisher's method when the p-values are from studies + of different size [6]_ [7]_. + * Tippett's method uses the smallest p-value as a statistic. + (Mind that this minimum is not the combined p-value.) + + Fisher's method may be extended to combine p-values from dependent tests + [8]_. Extensions such as Brown's method and Kost's method are not currently + implemented. + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete + Distributions." Journal of the American Statistical Association 57, + no. 297 (1962), 10-19. + .. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of + combining p-values." Biometrika 105.1 (2018): 239-246. + .. [3] https://en.wikipedia.org/wiki/Fisher%27s_method + .. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic + random variables." Metrika 30.1 (1983): 1-13. + .. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method + .. [6] Whitlock, M. C. "Combining probability from independent tests: the + weighted Z-method is superior to Fisher's approach." Journal of + Evolutionary Biology 18, no. 5 (2005): 1368-1373. + .. [7] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method + for combining probabilities in meta-analysis." Journal of + Evolutionary Biology 24, no. 8 (2011): 1836-1841. + .. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method + + """ + xp = array_namespace(pvalues) + pvalues = xp.asarray(pvalues) + if xp_size(pvalues) == 0: + # This is really only needed for *testing* _axis_nan_policy decorator + # It won't happen when the decorator is used. + NaN = _get_nan(pvalues) + return SignificanceResult(NaN, NaN) + + n = pvalues.shape[axis] + # used to convert Python scalar to the right dtype + one = xp.asarray(1, dtype=pvalues.dtype) + + if method == 'fisher': + statistic = -2 * xp.sum(xp.log(pvalues), axis=axis) + chi2 = _SimpleChi2(2*n*one) + pval = _get_pvalue(statistic, chi2, alternative='greater', + symmetric=False, xp=xp) + elif method == 'pearson': + statistic = 2 * xp.sum(xp.log1p(-pvalues), axis=axis) + chi2 = _SimpleChi2(2*n*one) + pval = _get_pvalue(-statistic, chi2, alternative='less', symmetric=False, xp=xp) + elif method == 'mudholkar_george': + normalizing_factor = math.sqrt(3/n)/xp.pi + statistic = (-xp.sum(xp.log(pvalues), axis=axis) + + xp.sum(xp.log1p(-pvalues), axis=axis)) + nu = 5*n + 4 + approx_factor = math.sqrt(nu / (nu - 2)) + t = _SimpleStudentT(nu*one) + pval = _get_pvalue(statistic * normalizing_factor * approx_factor, t, + alternative="greater", xp=xp) + elif method == 'tippett': + statistic = xp.min(pvalues, axis=axis) + beta = _SimpleBeta(one, n*one) + pval = _get_pvalue(statistic, beta, alternative='less', symmetric=False, xp=xp) + elif method == 'stouffer': + if weights is None: + weights = xp.ones_like(pvalues, dtype=pvalues.dtype) + elif weights.shape[axis] != n: + raise ValueError("pvalues and weights must be of the same " + "length along `axis`.") + + norm = _SimpleNormal() + Zi = norm.isf(pvalues) + # could use `einsum` or clever `matmul` for performance, + # but this is the most readable + statistic = (xp.sum(weights * Zi, axis=axis) + / xp_vector_norm(weights, axis=axis)) + pval = _get_pvalue(statistic, norm, alternative="greater", xp=xp) + + else: + raise ValueError( + f"Invalid method {method!r}. Valid methods are 'fisher', " + "'pearson', 'mudholkar_george', 'tippett', and 'stouffer'" + ) + + return SignificanceResult(statistic, pval) + + +@dataclass +class QuantileTestResult: + r""" + Result of `scipy.stats.quantile_test`. + + Attributes + ---------- + statistic: float + The statistic used to calculate the p-value; either ``T1``, the + number of observations less than or equal to the hypothesized quantile, + or ``T2``, the number of observations strictly less than the + hypothesized quantile. Two test statistics are required to handle the + possibility the data was generated from a discrete or mixed + distribution. + + statistic_type : int + ``1`` or ``2`` depending on which of ``T1`` or ``T2`` was used to + calculate the p-value respectively. ``T1`` corresponds to the + ``"greater"`` alternative hypothesis and ``T2`` to the ``"less"``. For + the ``"two-sided"`` case, the statistic type that leads to smallest + p-value is used. For significant tests, ``statistic_type = 1`` means + there is evidence that the population quantile is significantly greater + than the hypothesized value and ``statistic_type = 2`` means there is + evidence that it is significantly less than the hypothesized value. + + pvalue : float + The p-value of the hypothesis test. + """ + statistic: float + statistic_type: int + pvalue: float + _alternative: list[str] = field(repr=False) + _x : np.ndarray = field(repr=False) + _p : float = field(repr=False) + + def confidence_interval(self, confidence_level=0.95): + """ + Compute the confidence interval of the quantile. + + Parameters + ---------- + confidence_level : float, default: 0.95 + Confidence level for the computed confidence interval + of the quantile. Default is 0.95. + + Returns + ------- + ci : ``ConfidenceInterval`` object + The object has attributes ``low`` and ``high`` that hold the + lower and upper bounds of the confidence interval. + + Examples + -------- + >>> import numpy as np + >>> import scipy.stats as stats + >>> p = 0.75 # quantile of interest + >>> q = 0 # hypothesized value of the quantile + >>> x = np.exp(np.arange(0, 1.01, 0.01)) + >>> res = stats.quantile_test(x, q=q, p=p, alternative='less') + >>> lb, ub = res.confidence_interval() + >>> lb, ub + (-inf, 2.293318740264183) + >>> res = stats.quantile_test(x, q=q, p=p, alternative='two-sided') + >>> lb, ub = res.confidence_interval(0.9) + >>> lb, ub + (1.9542373206359396, 2.293318740264183) + """ + + alternative = self._alternative + p = self._p + x = np.sort(self._x) + n = len(x) + bd = stats.binom(n, p) + + if confidence_level <= 0 or confidence_level >= 1: + message = "`confidence_level` must be a number between 0 and 1." + raise ValueError(message) + + low_index = np.nan + high_index = np.nan + + if alternative == 'less': + p = 1 - confidence_level + low = -np.inf + high_index = int(bd.isf(p)) + high = x[high_index] if high_index < n else np.nan + elif alternative == 'greater': + p = 1 - confidence_level + low_index = int(bd.ppf(p)) - 1 + low = x[low_index] if low_index >= 0 else np.nan + high = np.inf + elif alternative == 'two-sided': + p = (1 - confidence_level) / 2 + low_index = int(bd.ppf(p)) - 1 + low = x[low_index] if low_index >= 0 else np.nan + high_index = int(bd.isf(p)) + high = x[high_index] if high_index < n else np.nan + + return ConfidenceInterval(low, high) + + +def quantile_test_iv(x, q, p, alternative): + + x = np.atleast_1d(x) + message = '`x` must be a one-dimensional array of numbers.' + if x.ndim != 1 or not np.issubdtype(x.dtype, np.number): + raise ValueError(message) + + q = np.array(q)[()] + message = "`q` must be a scalar." + if q.ndim != 0 or not np.issubdtype(q.dtype, np.number): + raise ValueError(message) + + p = np.array(p)[()] + message = "`p` must be a float strictly between 0 and 1." + if p.ndim != 0 or p >= 1 or p <= 0: + raise ValueError(message) + + alternatives = {'two-sided', 'less', 'greater'} + message = f"`alternative` must be one of {alternatives}" + if alternative not in alternatives: + raise ValueError(message) + + return x, q, p, alternative + + +def quantile_test(x, *, q=0, p=0.5, alternative='two-sided'): + r""" + Perform a quantile test and compute a confidence interval of the quantile. + + This function tests the null hypothesis that `q` is the value of the + quantile associated with probability `p` of the population underlying + sample `x`. For example, with default parameters, it tests that the + median of the population underlying `x` is zero. The function returns an + object including the test statistic, a p-value, and a method for computing + the confidence interval around the quantile. + + Parameters + ---------- + x : array_like + A one-dimensional sample. + q : float, default: 0 + The hypothesized value of the quantile. + p : float, default: 0.5 + The probability associated with the quantile; i.e. the proportion of + the population less than `q` is `p`. Must be strictly between 0 and + 1. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + The following options are available (default is 'two-sided'): + + * 'two-sided': the quantile associated with the probability `p` + is not `q`. + * 'less': the quantile associated with the probability `p` is less + than `q`. + * 'greater': the quantile associated with the probability `p` is + greater than `q`. + + Returns + ------- + result : QuantileTestResult + An object with the following attributes: + + statistic : float + One of two test statistics that may be used in the quantile test. + The first test statistic, ``T1``, is the proportion of samples in + `x` that are less than or equal to the hypothesized quantile + `q`. The second test statistic, ``T2``, is the proportion of + samples in `x` that are strictly less than the hypothesized + quantile `q`. + + When ``alternative = 'greater'``, ``T1`` is used to calculate the + p-value and ``statistic`` is set to ``T1``. + + When ``alternative = 'less'``, ``T2`` is used to calculate the + p-value and ``statistic`` is set to ``T2``. + + When ``alternative = 'two-sided'``, both ``T1`` and ``T2`` are + considered, and the one that leads to the smallest p-value is used. + + statistic_type : int + Either `1` or `2` depending on which of ``T1`` or ``T2`` was + used to calculate the p-value. + + pvalue : float + The p-value associated with the given alternative. + + The object also has the following method: + + confidence_interval(confidence_level=0.95) + Computes a confidence interval around the the + population quantile associated with the probability `p`. The + confidence interval is returned in a ``namedtuple`` with + fields `low` and `high`. Values are `nan` when there are + not enough observations to compute the confidence interval at + the desired confidence. + + Notes + ----- + This test and its method for computing confidence intervals are + non-parametric. They are valid if and only if the observations are i.i.d. + + The implementation of the test follows Conover [1]_. Two test statistics + are considered. + + ``T1``: The number of observations in `x` less than or equal to `q`. + + ``T1 = (x <= q).sum()`` + + ``T2``: The number of observations in `x` strictly less than `q`. + + ``T2 = (x < q).sum()`` + + The use of two test statistics is necessary to handle the possibility that + `x` was generated from a discrete or mixed distribution. + + The null hypothesis for the test is: + + H0: The :math:`p^{\mathrm{th}}` population quantile is `q`. + + and the null distribution for each test statistic is + :math:`\mathrm{binom}\left(n, p\right)`. When ``alternative='less'``, + the alternative hypothesis is: + + H1: The :math:`p^{\mathrm{th}}` population quantile is less than `q`. + + and the p-value is the probability that the binomial random variable + + .. math:: + Y \sim \mathrm{binom}\left(n, p\right) + + is greater than or equal to the observed value ``T2``. + + When ``alternative='greater'``, the alternative hypothesis is: + + H1: The :math:`p^{\mathrm{th}}` population quantile is greater than `q` + + and the p-value is the probability that the binomial random variable Y + is less than or equal to the observed value ``T1``. + + When ``alternative='two-sided'``, the alternative hypothesis is + + H1: `q` is not the :math:`p^{\mathrm{th}}` population quantile. + + and the p-value is twice the smaller of the p-values for the ``'less'`` + and ``'greater'`` cases. Both of these p-values can exceed 0.5 for the same + data, so the value is clipped into the interval :math:`[0, 1]`. + + The approach for confidence intervals is attributed to Thompson [2]_ and + later proven to be applicable to any set of i.i.d. samples [3]_. The + computation is based on the observation that the probability of a quantile + :math:`q` to be larger than any observations :math:`x_m (1\leq m \leq N)` + can be computed as + + .. math:: + + \mathbb{P}(x_m \leq q) = 1 - \sum_{k=0}^{m-1} \binom{N}{k} + q^k(1-q)^{N-k} + + By default, confidence intervals are computed for a 95% confidence level. + A common interpretation of a 95% confidence intervals is that if i.i.d. + samples are drawn repeatedly from the same population and confidence + intervals are formed each time, the confidence interval will contain the + true value of the specified quantile in approximately 95% of trials. + + A similar function is available in the QuantileNPCI R package [4]_. The + foundation is the same, but it computes the confidence interval bounds by + doing interpolations between the sample values, whereas this function uses + only sample values as bounds. Thus, ``quantile_test.confidence_interval`` + returns more conservative intervals (i.e., larger). + + The same computation of confidence intervals for quantiles is included in + the confintr package [5]_. + + Two-sided confidence intervals are not guaranteed to be optimal; i.e., + there may exist a tighter interval that may contain the quantile of + interest with probability larger than the confidence level. + Without further assumption on the samples (e.g., the nature of the + underlying distribution), the one-sided intervals are optimally tight. + + References + ---------- + .. [1] W. J. Conover. Practical Nonparametric Statistics, 3rd Ed. 1999. + .. [2] W. R. Thompson, "On Confidence Ranges for the Median and Other + Expectation Distributions for Populations of Unknown Distribution + Form," The Annals of Mathematical Statistics, vol. 7, no. 3, + pp. 122-128, 1936, Accessed: Sep. 18, 2019. [Online]. Available: + https://www.jstor.org/stable/2957563. + .. [3] H. A. David and H. N. Nagaraja, "Order Statistics in Nonparametric + Inference" in Order Statistics, John Wiley & Sons, Ltd, 2005, pp. + 159-170. Available: + https://onlinelibrary.wiley.com/doi/10.1002/0471722162.ch7. + .. [4] N. Hutson, A. Hutson, L. Yan, "QuantileNPCI: Nonparametric + Confidence Intervals for Quantiles," R package, + https://cran.r-project.org/package=QuantileNPCI + .. [5] M. Mayer, "confintr: Confidence Intervals," R package, + https://cran.r-project.org/package=confintr + + + Examples + -------- + + Suppose we wish to test the null hypothesis that the median of a population + is equal to 0.5. We choose a confidence level of 99%; that is, we will + reject the null hypothesis in favor of the alternative if the p-value is + less than 0.01. + + When testing random variates from the standard uniform distribution, which + has a median of 0.5, we expect the data to be consistent with the null + hypothesis most of the time. + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(6981396440634228121) + >>> rvs = stats.uniform.rvs(size=100, random_state=rng) + >>> stats.quantile_test(rvs, q=0.5, p=0.5) + QuantileTestResult(statistic=45, statistic_type=1, pvalue=0.36820161732669576) + + As expected, the p-value is not below our threshold of 0.01, so + we cannot reject the null hypothesis. + + When testing data from the standard *normal* distribution, which has a + median of 0, we would expect the null hypothesis to be rejected. + + >>> rvs = stats.norm.rvs(size=100, random_state=rng) + >>> stats.quantile_test(rvs, q=0.5, p=0.5) + QuantileTestResult(statistic=67, statistic_type=2, pvalue=0.0008737198369123724) + + Indeed, the p-value is lower than our threshold of 0.01, so we reject the + null hypothesis in favor of the default "two-sided" alternative: the median + of the population is *not* equal to 0.5. + + However, suppose we were to test the null hypothesis against the + one-sided alternative that the median of the population is *greater* than + 0.5. Since the median of the standard normal is less than 0.5, we would not + expect the null hypothesis to be rejected. + + >>> stats.quantile_test(rvs, q=0.5, p=0.5, alternative='greater') + QuantileTestResult(statistic=67, statistic_type=1, pvalue=0.9997956114162866) + + Unsurprisingly, with a p-value greater than our threshold, we would not + reject the null hypothesis in favor of the chosen alternative. + + The quantile test can be used for any quantile, not only the median. For + example, we can test whether the third quartile of the distribution + underlying the sample is greater than 0.6. + + >>> rvs = stats.uniform.rvs(size=100, random_state=rng) + >>> stats.quantile_test(rvs, q=0.6, p=0.75, alternative='greater') + QuantileTestResult(statistic=64, statistic_type=1, pvalue=0.00940696592998271) + + The p-value is lower than the threshold. We reject the null hypothesis in + favor of the alternative: the third quartile of the distribution underlying + our sample is greater than 0.6. + + `quantile_test` can also compute confidence intervals for any quantile. + + >>> rvs = stats.norm.rvs(size=100, random_state=rng) + >>> res = stats.quantile_test(rvs, q=0.6, p=0.75) + >>> ci = res.confidence_interval(confidence_level=0.95) + >>> ci + ConfidenceInterval(low=0.284491604437432, high=0.8912531024914844) + + When testing a one-sided alternative, the confidence interval contains + all observations such that if passed as `q`, the p-value of the + test would be greater than 0.05, and therefore the null hypothesis + would not be rejected. For example: + + >>> rvs.sort() + >>> q, p, alpha = 0.6, 0.75, 0.95 + >>> res = stats.quantile_test(rvs, q=q, p=p, alternative='less') + >>> ci = res.confidence_interval(confidence_level=alpha) + >>> for x in rvs[rvs <= ci.high]: + ... res = stats.quantile_test(rvs, q=x, p=p, alternative='less') + ... assert res.pvalue > 1-alpha + >>> for x in rvs[rvs > ci.high]: + ... res = stats.quantile_test(rvs, q=x, p=p, alternative='less') + ... assert res.pvalue < 1-alpha + + Also, if a 95% confidence interval is repeatedly generated for random + samples, the confidence interval will contain the true quantile value in + approximately 95% of replications. + + >>> dist = stats.rayleigh() # our "unknown" distribution + >>> p = 0.2 + >>> true_stat = dist.ppf(p) # the true value of the statistic + >>> n_trials = 1000 + >>> quantile_ci_contains_true_stat = 0 + >>> for i in range(n_trials): + ... data = dist.rvs(size=100, random_state=rng) + ... res = stats.quantile_test(data, p=p) + ... ci = res.confidence_interval(0.95) + ... if ci[0] < true_stat < ci[1]: + ... quantile_ci_contains_true_stat += 1 + >>> quantile_ci_contains_true_stat >= 950 + True + + This works with any distribution and any quantile, as long as the samples + are i.i.d. + """ + # Implementation carefully follows [1] 3.2 + # "H0: the p*th quantile of X is x*" + # To facilitate comparison with [1], we'll use variable names that + # best match Conover's notation + X, x_star, p_star, H1 = quantile_test_iv(x, q, p, alternative) + + # "We will use two test statistics in this test. Let T1 equal " + # "the number of observations less than or equal to x*, and " + # "let T2 equal the number of observations less than x*." + T1 = (X <= x_star).sum() + T2 = (X < x_star).sum() + + # "The null distribution of the test statistics T1 and T2 is " + # "the binomial distribution, with parameters n = sample size, and " + # "p = p* as given in the null hypothesis.... Y has the binomial " + # "distribution with parameters n and p*." + n = len(X) + Y = stats.binom(n=n, p=p_star) + + # "H1: the p* population quantile is less than x*" + if H1 == 'less': + # "The p-value is the probability that a binomial random variable Y " + # "is greater than *or equal to* the observed value of T2...using p=p*" + pvalue = Y.sf(T2-1) # Y.pmf(T2) + Y.sf(T2) + statistic = T2 + statistic_type = 2 + # "H1: the p* population quantile is greater than x*" + elif H1 == 'greater': + # "The p-value is the probability that a binomial random variable Y " + # "is less than or equal to the observed value of T1... using p = p*" + pvalue = Y.cdf(T1) + statistic = T1 + statistic_type = 1 + # "H1: x* is not the p*th population quantile" + elif H1 == 'two-sided': + # "The p-value is twice the smaller of the probabilities that a + # binomial random variable Y is less than or equal to the observed + # value of T1 or greater than or equal to the observed value of T2 + # using p=p*." + # Note: both one-sided p-values can exceed 0.5 for the same data, so + # `clip` + pvalues = [Y.cdf(T1), Y.sf(T2 - 1)] # [greater, less] + sorted_idx = np.argsort(pvalues) + pvalue = np.clip(2*pvalues[sorted_idx[0]], 0, 1) + if sorted_idx[0]: + statistic, statistic_type = T2, 2 + else: + statistic, statistic_type = T1, 1 + + return QuantileTestResult( + statistic=statistic, + statistic_type=statistic_type, + pvalue=pvalue, + _alternative=H1, + _x=X, + _p=p_star + ) + + +##################################### +# STATISTICAL DISTANCES # +##################################### + + +def wasserstein_distance_nd(u_values, v_values, u_weights=None, v_weights=None): + r""" + Compute the Wasserstein-1 distance between two N-D discrete distributions. + + The Wasserstein distance, also called the Earth mover's distance or the + optimal transport distance, is a similarity metric between two probability + distributions [1]_. In the discrete case, the Wasserstein distance can be + understood as the cost of an optimal transport plan to convert one + distribution into the other. The cost is calculated as the product of the + amount of probability mass being moved and the distance it is being moved. + A brief and intuitive introduction can be found at [2]_. + + .. versionadded:: 1.13.0 + + Parameters + ---------- + u_values : 2d array_like + A sample from a probability distribution or the support (set of all + possible values) of a probability distribution. Each element along + axis 0 is an observation or possible value, and axis 1 represents the + dimensionality of the distribution; i.e., each row is a vector + observation or possible value. + + v_values : 2d array_like + A sample from or the support of a second distribution. + + u_weights, v_weights : 1d array_like, optional + Weights or counts corresponding with the sample or probability masses + corresponding with the support values. Sum of elements must be positive + and finite. If unspecified, each value is assigned the same weight. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + Given two probability mass functions, :math:`u` + and :math:`v`, the first Wasserstein distance between the distributions + using the Euclidean norm is: + + .. math:: + + l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int \| x-y \|_2 \mathrm{d} \pi (x, y) + + where :math:`\Gamma (u, v)` is the set of (probability) distributions on + :math:`\mathbb{R}^n \times \mathbb{R}^n` whose marginals are :math:`u` and + :math:`v` on the first and second factors respectively. For a given value + :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position + :math:`x`, and the same for :math:`v(x)`. + + This is also called the optimal transport problem or the Monge problem. + Let the finite point sets :math:`\{x_i\}` and :math:`\{y_j\}` denote + the support set of probability mass function :math:`u` and :math:`v` + respectively. The Monge problem can be expressed as follows, + + Let :math:`\Gamma` denote the transport plan, :math:`D` denote the + distance matrix and, + + .. math:: + + x = \text{vec}(\Gamma) \\ + c = \text{vec}(D) \\ + b = \begin{bmatrix} + u\\ + v\\ + \end{bmatrix} + + The :math:`\text{vec}()` function denotes the Vectorization function + that transforms a matrix into a column vector by vertically stacking + the columns of the matrix. + The transport plan :math:`\Gamma` is a matrix :math:`[\gamma_{ij}]` in + which :math:`\gamma_{ij}` is a positive value representing the amount of + probability mass transported from :math:`u(x_i)` to :math:`v(y_i)`. + Summing over the rows of :math:`\Gamma` should give the source distribution + :math:`u` : :math:`\sum_j \gamma_{ij} = u(x_i)` holds for all :math:`i` + and summing over the columns of :math:`\Gamma` should give the target + distribution :math:`v`: :math:`\sum_i \gamma_{ij} = v(y_j)` holds for all + :math:`j`. + The distance matrix :math:`D` is a matrix :math:`[d_{ij}]`, in which + :math:`d_{ij} = d(x_i, y_j)`. + + Given :math:`\Gamma`, :math:`D`, :math:`b`, the Monge problem can be + transformed into a linear programming problem by + taking :math:`A x = b` as constraints and :math:`z = c^T x` as minimization + target (sum of costs) , where matrix :math:`A` has the form + + .. math:: + + \begin{array} {rrrr|rrrr|r|rrrr} + 1 & 1 & \dots & 1 & 0 & 0 & \dots & 0 & \dots & 0 & 0 & \dots & + 0 \cr + 0 & 0 & \dots & 0 & 1 & 1 & \dots & 1 & \dots & 0 & 0 &\dots & + 0 \cr + \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots + & \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr + 0 & 0 & \dots & 0 & 0 & 0 & \dots & 0 & \dots & 1 & 1 & \dots & + 1 \cr \hline + + 1 & 0 & \dots & 0 & 1 & 0 & \dots & \dots & \dots & 1 & 0 & \dots & + 0 \cr + 0 & 1 & \dots & 0 & 0 & 1 & \dots & \dots & \dots & 0 & 1 & \dots & + 0 \cr + \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots & + \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr + 0 & 0 & \dots & 1 & 0 & 0 & \dots & 1 & \dots & 0 & 0 & \dots & 1 + \end{array} + + By solving the dual form of the above linear programming problem (with + solution :math:`y^*`), the Wasserstein distance :math:`l_1 (u, v)` can + be computed as :math:`b^T y^*`. + + The above solution is inspired by Vincent Herrmann's blog [3]_ . For a + more thorough explanation, see [4]_ . + + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] "Wasserstein metric", + https://en.wikipedia.org/wiki/Wasserstein_metric + .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log, + https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance. + .. [3] Hermann, Vincent. "Wasserstein GAN and the Kantorovich-Rubinstein + Duality". https://vincentherrmann.github.io/blog/wasserstein/. + .. [4] Peyré, Gabriel, and Marco Cuturi. "Computational optimal + transport." Center for Research in Economics and Statistics + Working Papers 2017-86 (2017). + + See Also + -------- + wasserstein_distance: Compute the Wasserstein-1 distance between two + 1D discrete distributions. + + Examples + -------- + Compute the Wasserstein distance between two three-dimensional samples, + each with two observations. + + >>> from scipy.stats import wasserstein_distance_nd + >>> wasserstein_distance_nd([[0, 2, 3], [1, 2, 5]], [[3, 2, 3], [4, 2, 5]]) + 3.0 + + Compute the Wasserstein distance between two two-dimensional distributions + with three and two weighted observations, respectively. + + >>> wasserstein_distance_nd([[0, 2.75], [2, 209.3], [0, 0]], + ... [[0.2, 0.322], [4.5, 25.1808]], + ... [0.4, 5.2, 0.114], [0.8, 1.5]) + 174.15840245217169 + """ + m, n = len(u_values), len(v_values) + u_values = asarray(u_values) + v_values = asarray(v_values) + + if u_values.ndim > 2 or v_values.ndim > 2: + raise ValueError('Invalid input values. The inputs must have either ' + 'one or two dimensions.') + # if dimensions are not equal throw error + if u_values.ndim != v_values.ndim: + raise ValueError('Invalid input values. Dimensions of inputs must be ' + 'equal.') + # if data is 1D then call the cdf_distance function + if u_values.ndim == 1 and v_values.ndim == 1: + return _cdf_distance(1, u_values, v_values, u_weights, v_weights) + + u_values, u_weights = _validate_distribution(u_values, u_weights) + v_values, v_weights = _validate_distribution(v_values, v_weights) + # if number of columns is not equal throw error + if u_values.shape[1] != v_values.shape[1]: + raise ValueError('Invalid input values. If two-dimensional, ' + '`u_values` and `v_values` must have the same ' + 'number of columns.') + + # if data contains np.inf then return inf or nan + if np.any(np.isinf(u_values)) ^ np.any(np.isinf(v_values)): + return np.inf + elif np.any(np.isinf(u_values)) and np.any(np.isinf(v_values)): + return np.nan + + # create constraints + A_upper_part = sparse.block_diag((np.ones((1, n)), ) * m) + A_lower_part = sparse.hstack((sparse.eye(n), ) * m) + # sparse constraint matrix of size (m + n)*(m * n) + A = sparse.vstack((A_upper_part, A_lower_part)) + A = sparse.coo_array(A) + + # get cost matrix + D = distance_matrix(u_values, v_values, p=2) + cost = D.ravel() + + # create the minimization target + p_u = np.full(m, 1/m) if u_weights is None else u_weights/np.sum(u_weights) + p_v = np.full(n, 1/n) if v_weights is None else v_weights/np.sum(v_weights) + b = np.concatenate((p_u, p_v), axis=0) + + # solving LP + constraints = LinearConstraint(A=A.T, ub=cost) + opt_res = milp(c=-b, constraints=constraints, bounds=(-np.inf, np.inf)) + return -opt_res.fun + + +def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None): + r""" + Compute the Wasserstein-1 distance between two 1D discrete distributions. + + The Wasserstein distance, also called the Earth mover's distance or the + optimal transport distance, is a similarity metric between two probability + distributions [1]_. In the discrete case, the Wasserstein distance can be + understood as the cost of an optimal transport plan to convert one + distribution into the other. The cost is calculated as the product of the + amount of probability mass being moved and the distance it is being moved. + A brief and intuitive introduction can be found at [2]_. + + .. versionadded:: 1.0.0 + + Parameters + ---------- + u_values : 1d array_like + A sample from a probability distribution or the support (set of all + possible values) of a probability distribution. Each element is an + observation or possible value. + + v_values : 1d array_like + A sample from or the support of a second distribution. + + u_weights, v_weights : 1d array_like, optional + Weights or counts corresponding with the sample or probability masses + corresponding with the support values. Sum of elements must be positive + and finite. If unspecified, each value is assigned the same weight. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + Given two 1D probability mass functions, :math:`u` and :math:`v`, the first + Wasserstein distance between the distributions is: + + .. math:: + + l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times + \mathbb{R}} |x-y| \mathrm{d} \pi (x, y) + + where :math:`\Gamma (u, v)` is the set of (probability) distributions on + :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and + :math:`v` on the first and second factors respectively. For a given value + :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position + :math:`x`, and the same for :math:`v(x)`. + + If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and + :math:`v`, this distance also equals to: + + .. math:: + + l_1(u, v) = \int_{-\infty}^{+\infty} |U-V| + + See [3]_ for a proof of the equivalence of both definitions. + + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric + .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log, + https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance. + .. [3] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related + Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`. + + See Also + -------- + wasserstein_distance_nd: Compute the Wasserstein-1 distance between two N-D + discrete distributions. + + Examples + -------- + >>> from scipy.stats import wasserstein_distance + >>> wasserstein_distance([0, 1, 3], [5, 6, 8]) + 5.0 + >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2]) + 0.25 + >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4], + ... [1.4, 0.9, 3.1, 7.2], [3.2, 3.5]) + 4.0781331438047861 + + """ + return _cdf_distance(1, u_values, v_values, u_weights, v_weights) + + +def energy_distance(u_values, v_values, u_weights=None, v_weights=None): + r"""Compute the energy distance between two 1D distributions. + + .. versionadded:: 1.0.0 + + Parameters + ---------- + u_values, v_values : array_like + Values observed in the (empirical) distribution. + u_weights, v_weights : array_like, optional + Weight for each value. If unspecified, each value is assigned the same + weight. + `u_weights` (resp. `v_weights`) must have the same length as + `u_values` (resp. `v_values`). If the weight sum differs from 1, it + must still be positive and finite so that the weights can be normalized + to sum to 1. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + The energy distance between two distributions :math:`u` and :math:`v`, whose + respective CDFs are :math:`U` and :math:`V`, equals to: + + .. math:: + + D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| - + \mathbb E|Y - Y'| \right)^{1/2} + + where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are + independent random variables whose probability distribution is :math:`u` + (resp. :math:`v`). + + Sometimes the square of this quantity is referred to as the "energy + distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the + definition above satisfies the axioms of a distance function (metric). + + As shown in [2]_, for one-dimensional real-valued variables, the energy + distance is linked to the non-distribution-free version of the Cramér-von + Mises distance: + + .. math:: + + D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2 + \right)^{1/2} + + Note that the common Cramér-von Mises criterion uses the distribution-free + version of the distance. See [2]_ (section 2), for more details about both + versions of the distance. + + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews: + Computational Statistics, 8(1):27-38 (2015). + .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling + Green State University, Department of Mathematics and Statistics, + Technical Report 02-16 (2002). + .. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance + .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer, + Munos "The Cramer Distance as a Solution to Biased Wasserstein + Gradients" (2017). :arXiv:`1705.10743`. + + Examples + -------- + >>> from scipy.stats import energy_distance + >>> energy_distance([0], [2]) + 2.0000000000000004 + >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2]) + 1.0000000000000002 + >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ], + ... [2.1, 4.2, 7.4, 8. ], [7.6, 8.8]) + 0.88003340976158217 + + """ + return np.sqrt(2) * _cdf_distance(2, u_values, v_values, + u_weights, v_weights) + + +def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None): + r""" + Compute, between two one-dimensional distributions :math:`u` and + :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the + statistical distance that is defined as: + + .. math:: + + l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p} + + p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2 + gives the energy distance. + + Parameters + ---------- + u_values, v_values : array_like + Values observed in the (empirical) distribution. + u_weights, v_weights : array_like, optional + Weight for each value. If unspecified, each value is assigned the same + weight. + `u_weights` (resp. `v_weights`) must have the same length as + `u_values` (resp. `v_values`). If the weight sum differs from 1, it + must still be positive and finite so that the weights can be normalized + to sum to 1. + + Returns + ------- + distance : float + The computed distance between the distributions. + + Notes + ----- + The input distributions can be empirical, therefore coming from samples + whose values are effectively inputs of the function, or they can be seen as + generalized functions, in which case they are weighted sums of Dirac delta + functions located at the specified values. + + References + ---------- + .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer, + Munos "The Cramer Distance as a Solution to Biased Wasserstein + Gradients" (2017). :arXiv:`1705.10743`. + + """ + u_values, u_weights = _validate_distribution(u_values, u_weights) + v_values, v_weights = _validate_distribution(v_values, v_weights) + + u_sorter = np.argsort(u_values) + v_sorter = np.argsort(v_values) + + all_values = np.concatenate((u_values, v_values)) + all_values.sort(kind='mergesort') + + # Compute the differences between pairs of successive values of u and v. + deltas = np.diff(all_values) + + # Get the respective positions of the values of u and v among the values of + # both distributions. + u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right') + v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right') + + # Calculate the CDFs of u and v using their weights, if specified. + if u_weights is None: + u_cdf = u_cdf_indices / u_values.size + else: + u_sorted_cumweights = np.concatenate(([0], + np.cumsum(u_weights[u_sorter]))) + u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1] + + if v_weights is None: + v_cdf = v_cdf_indices / v_values.size + else: + v_sorted_cumweights = np.concatenate(([0], + np.cumsum(v_weights[v_sorter]))) + v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1] + + # Compute the value of the integral based on the CDFs. + # If p = 1 or p = 2, we avoid using np.power, which introduces an overhead + # of about 15%. + if p == 1: + return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas)) + if p == 2: + return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas))) + return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p), + deltas)), 1/p) + + +def _validate_distribution(values, weights): + """ + Validate the values and weights from a distribution input of `cdf_distance` + and return them as ndarray objects. + + Parameters + ---------- + values : array_like + Values observed in the (empirical) distribution. + weights : array_like + Weight for each value. + + Returns + ------- + values : ndarray + Values as ndarray. + weights : ndarray + Weights as ndarray. + + """ + # Validate the value array. + values = np.asarray(values, dtype=float) + if len(values) == 0: + raise ValueError("Distribution can't be empty.") + + # Validate the weight array, if specified. + if weights is not None: + weights = np.asarray(weights, dtype=float) + if len(weights) != len(values): + raise ValueError('Value and weight array-likes for the same ' + 'empirical distribution must be of the same size.') + if np.any(weights < 0): + raise ValueError('All weights must be non-negative.') + if not 0 < np.sum(weights) < np.inf: + raise ValueError('Weight array-like sum must be positive and ' + 'finite. Set as None for an equal distribution of ' + 'weight.') + + return values, weights + + return values, None + + +##################################### +# SUPPORT FUNCTIONS # +##################################### + +RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts')) + + +@_deprecated("`scipy.stats.find_repeats` is deprecated as of SciPy 1.15.0 " + "and will be removed in SciPy 1.17.0. Please use " + "`numpy.unique`/`numpy.unique_counts` instead.") +def find_repeats(arr): + """Find repeats and repeat counts. + + .. deprecated:: 1.15.0 + + This function is deprecated as of SciPy 1.15.0 and will be removed + in SciPy 1.17.0. Please use `numpy.unique` / `numpy.unique_counts` instead. + + Parameters + ---------- + arr : array_like + Input array. This is cast to float64. + + Returns + ------- + values : ndarray + The unique values from the (flattened) input that are repeated. + + counts : ndarray + Number of times the corresponding 'value' is repeated. + + Notes + ----- + In numpy >= 1.9 `numpy.unique` provides similar functionality. The main + difference is that `find_repeats` only returns repeated values. + + Examples + -------- + >>> from scipy import stats + >>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5]) + RepeatedResults(values=array([2.]), counts=array([4])) + + >>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]]) + RepeatedResults(values=array([4., 5.]), counts=array([2, 2])) + + """ + # Note: always copies. + return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64))) + + +def _sum_of_squares(a, axis=0): + """Square each element of the input array, and return the sum(s) of that. + + Parameters + ---------- + a : array_like + Input array. + axis : int or None, optional + Axis along which to calculate. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + sum_of_squares : ndarray + The sum along the given axis for (a**2). + + See Also + -------- + _square_of_sums : The square(s) of the sum(s) (the opposite of + `_sum_of_squares`). + + """ + a, axis = _chk_asarray(a, axis) + return np.sum(a*a, axis) + + +def _square_of_sums(a, axis=0): + """Sum elements of the input array, and return the square(s) of that sum. + + Parameters + ---------- + a : array_like + Input array. + axis : int or None, optional + Axis along which to calculate. Default is 0. If None, compute over + the whole array `a`. + + Returns + ------- + square_of_sums : float or ndarray + The square of the sum over `axis`. + + See Also + -------- + _sum_of_squares : The sum of squares (the opposite of `square_of_sums`). + + """ + a, axis = _chk_asarray(a, axis) + s = np.sum(a, axis) + if not np.isscalar(s): + return s.astype(float) * s + else: + return float(s) * s + + +def rankdata(a, method='average', *, axis=None, nan_policy='propagate'): + """Assign ranks to data, dealing with ties appropriately. + + By default (``axis=None``), the data array is first flattened, and a flat + array of ranks is returned. Separately reshape the rank array to the + shape of the data array if desired (see Examples). + + Ranks begin at 1. The `method` argument controls how ranks are assigned + to equal values. See [1]_ for further discussion of ranking methods. + + Parameters + ---------- + a : array_like + The array of values to be ranked. + method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional + The method used to assign ranks to tied elements. + The following methods are available (default is 'average'): + + * 'average': The average of the ranks that would have been assigned to + all the tied values is assigned to each value. + * 'min': The minimum of the ranks that would have been assigned to all + the tied values is assigned to each value. (This is also + referred to as "competition" ranking.) + * 'max': The maximum of the ranks that would have been assigned to all + the tied values is assigned to each value. + * 'dense': Like 'min', but the rank of the next highest element is + assigned the rank immediately after those assigned to the tied + elements. + * 'ordinal': All values are given a distinct rank, corresponding to + the order that the values occur in `a`. + axis : {None, int}, optional + Axis along which to perform the ranking. If ``None``, the data array + is first flattened. + nan_policy : {'propagate', 'omit', 'raise'}, optional + Defines how to handle when input contains nan. + The following options are available (default is 'propagate'): + + * 'propagate': propagates nans through the rank calculation + * 'omit': performs the calculations ignoring nan values + * 'raise': raises an error + + .. note:: + + When `nan_policy` is 'propagate', the output is an array of *all* + nans because ranks relative to nans in the input are undefined. + When `nan_policy` is 'omit', nans in `a` are ignored when ranking + the other values, and the corresponding locations of the output + are nan. + + .. versionadded:: 1.10 + + Returns + ------- + ranks : ndarray + An array of size equal to the size of `a`, containing rank + scores. + + References + ---------- + .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import rankdata + >>> rankdata([0, 2, 3, 2]) + array([ 1. , 2.5, 4. , 2.5]) + >>> rankdata([0, 2, 3, 2], method='min') + array([ 1, 2, 4, 2]) + >>> rankdata([0, 2, 3, 2], method='max') + array([ 1, 3, 4, 3]) + >>> rankdata([0, 2, 3, 2], method='dense') + array([ 1, 2, 3, 2]) + >>> rankdata([0, 2, 3, 2], method='ordinal') + array([ 1, 2, 4, 3]) + >>> rankdata([[0, 2], [3, 2]]).reshape(2,2) + array([[1. , 2.5], + [4. , 2.5]]) + >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1) + array([[1. , 2.5, 2.5], + [2. , 1. , 3. ]]) + >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate") + array([nan, nan, nan, nan, nan, nan]) + >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit") + array([ 2., 3., 4., nan, 1., nan]) + + """ + methods = ('average', 'min', 'max', 'dense', 'ordinal') + if method not in methods: + raise ValueError(f'unknown method "{method}"') + + x = np.asarray(a) + + if axis is None: + x = x.ravel() + axis = -1 + + if x.size == 0: + dtype = float if method == 'average' else np.dtype("long") + return np.empty(x.shape, dtype=dtype) + + contains_nan, nan_policy = _contains_nan(x, nan_policy) + + x = np.swapaxes(x, axis, -1) + ranks = _rankdata(x, method) + + if contains_nan: + i_nan = (np.isnan(x) if nan_policy == 'omit' + else np.isnan(x).any(axis=-1)) + ranks = ranks.astype(float, copy=False) + ranks[i_nan] = np.nan + + ranks = np.swapaxes(ranks, axis, -1) + return ranks + + +def _order_ranks(ranks, j): + # Reorder ascending order `ranks` according to `j` + ordered_ranks = np.empty(j.shape, dtype=ranks.dtype) + np.put_along_axis(ordered_ranks, j, ranks, axis=-1) + return ordered_ranks + + +def _rankdata(x, method, return_ties=False): + # Rank data `x` by desired `method`; `return_ties` if desired + shape = x.shape + + # Get sort order + kind = 'mergesort' if method == 'ordinal' else 'quicksort' + j = np.argsort(x, axis=-1, kind=kind) + ordinal_ranks = np.broadcast_to(np.arange(1, shape[-1]+1, dtype=int), shape) + + # Ordinal ranks is very easy because ties don't matter. We're done. + if method == 'ordinal': + return _order_ranks(ordinal_ranks, j) # never return ties + + # Sort array + y = np.take_along_axis(x, j, axis=-1) + # Logical indices of unique elements + i = np.concatenate([np.ones(shape[:-1] + (1,), dtype=np.bool_), + y[..., :-1] != y[..., 1:]], axis=-1) + + # Integer indices of unique elements + indices = np.arange(y.size)[i.ravel()] + # Counts of unique elements + counts = np.diff(indices, append=y.size) + + # Compute `'min'`, `'max'`, and `'mid'` ranks of unique elements + if method == 'min': + ranks = ordinal_ranks[i] + elif method == 'max': + ranks = ordinal_ranks[i] + counts - 1 + elif method == 'average': + ranks = ordinal_ranks[i] + (counts - 1)/2 + elif method == 'dense': + ranks = np.cumsum(i, axis=-1)[i] + + ranks = np.repeat(ranks, counts).reshape(shape) + ranks = _order_ranks(ranks, j) + + if return_ties: + # Tie information is returned in a format that is useful to functions that + # rely on this (private) function. Example: + # >>> x = np.asarray([3, 2, 1, 2, 2, 2, 1]) + # >>> _, t = _rankdata(x, 'average', return_ties=True) + # >>> t # array([2., 0., 4., 0., 0., 0., 1.]) # two 1s, four 2s, and one 3 + # Unlike ranks, tie counts are *not* reordered to correspond with the order of + # the input; e.g. the number of appearances of the lowest rank element comes + # first. This is a useful format because: + # - The shape of the result is the shape of the input. Different slices can + # have different numbers of tied elements but not result in a ragged array. + # - Functions that use `t` usually don't need to which each element of the + # original array is associated with each tie count; they perform a reduction + # over the tie counts onnly. The tie counts are naturally computed in a + # sorted order, so this does not unnecessarily reorder them. + # - One exception is `wilcoxon`, which needs the number of zeros. Zeros always + # have the lowest rank, so it is easy to find them at the zeroth index. + t = np.zeros(shape, dtype=float) + t[i] = counts + return ranks, t + return ranks + + +def expectile(a, alpha=0.5, *, weights=None): + r"""Compute the expectile at the specified level. + + Expectiles are a generalization of the expectation in the same way as + quantiles are a generalization of the median. The expectile at level + `alpha = 0.5` is the mean (average). See Notes for more details. + + Parameters + ---------- + a : array_like + Array containing numbers whose expectile is desired. + alpha : float, default: 0.5 + The level of the expectile; e.g., ``alpha=0.5`` gives the mean. + weights : array_like, optional + An array of weights associated with the values in `a`. + The `weights` must be broadcastable to the same shape as `a`. + Default is None, which gives each value a weight of 1.0. + An integer valued weight element acts like repeating the corresponding + observation in `a` that many times. See Notes for more details. + + Returns + ------- + expectile : ndarray + The empirical expectile at level `alpha`. + + See Also + -------- + numpy.mean : Arithmetic average + numpy.quantile : Quantile + + Notes + ----- + In general, the expectile at level :math:`\alpha` of a random variable + :math:`X` with cumulative distribution function (CDF) :math:`F` is given + by the unique solution :math:`t` of: + + .. math:: + + \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,. + + Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`. + This equation can be equivalently written as: + + .. math:: + + \alpha \int_t^\infty (x - t)\mathrm{d}F(x) + = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,. + + The empirical expectile at level :math:`\alpha` (`alpha`) of a sample + :math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of + `a`. Given sample or case weights :math:`w` (the array `weights`), it + reads :math:`F_a(x) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{a_i \leq x}` + with indicator function :math:`1_{A}`. This leads to the definition of the + empirical expectile at level `alpha` as the unique solution :math:`t` of: + + .. math:: + + \alpha \sum_{i=1}^n w_i (a_i - t)_+ = + (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,. + + For :math:`\alpha=0.5`, this simplifies to the weighted average. + Furthermore, the larger :math:`\alpha`, the larger the value of the + expectile. + + As a final remark, the expectile at level :math:`\alpha` can also be + written as a minimization problem. One often used choice is + + .. math:: + + \operatorname{argmin}_t + E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,. + + References + ---------- + .. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares + Estimation and Testing," Econometrica, 55, 819-847. + .. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts," + Journal of the American Statistical Association, 106, 746 - 762. + :doi:`10.48550/arXiv.0912.0902` + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import expectile + >>> a = [1, 4, 2, -1] + >>> expectile(a, alpha=0.5) == np.mean(a) + True + >>> expectile(a, alpha=0.2) + 0.42857142857142855 + >>> expectile(a, alpha=0.8) + 2.5714285714285716 + >>> weights = [1, 3, 1, 1] + + """ + if alpha < 0 or alpha > 1: + raise ValueError( + "The expectile level alpha must be in the range [0, 1]." + ) + a = np.asarray(a) + + if weights is not None: + weights = np.broadcast_to(weights, a.shape) + + # This is the empirical equivalent of Eq. (13) with identification + # function from Table 9 (omitting a factor of 2) in [2] (their y is our + # data a, their x is our t) + def first_order(t): + return np.average(np.abs((a <= t) - alpha) * (t - a), weights=weights) + + if alpha >= 0.5: + x0 = np.average(a, weights=weights) + x1 = np.amax(a) + else: + x1 = np.average(a, weights=weights) + x0 = np.amin(a) + + if x0 == x1: + # a has a single unique element + return x0 + + # Note that the expectile is the unique solution, so no worries about + # finding a wrong root. + res = root_scalar(first_order, x0=x0, x1=x1) + return res.root + + +def _lmoment_iv(sample, order, axis, sorted, standardize): + # input validation/standardization for `lmoment` + sample = np.asarray(sample) + message = "`sample` must be an array of real numbers." + if np.issubdtype(sample.dtype, np.integer): + sample = sample.astype(np.float64) + if not np.issubdtype(sample.dtype, np.floating): + raise ValueError(message) + + message = "`order` must be a scalar or a non-empty array of positive integers." + order = np.arange(1, 5) if order is None else np.asarray(order) + if not np.issubdtype(order.dtype, np.integer) or np.any(order <= 0): + raise ValueError(message) + + axis = np.asarray(axis)[()] + message = "`axis` must be an integer." + if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0: + raise ValueError(message) + + sorted = np.asarray(sorted)[()] + message = "`sorted` must be True or False." + if not np.issubdtype(sorted.dtype, np.bool_) or sorted.ndim != 0: + raise ValueError(message) + + standardize = np.asarray(standardize)[()] + message = "`standardize` must be True or False." + if not np.issubdtype(standardize.dtype, np.bool_) or standardize.ndim != 0: + raise ValueError(message) + + sample = np.moveaxis(sample, axis, -1) + sample = np.sort(sample, axis=-1) if not sorted else sample + + return sample, order, axis, sorted, standardize + + +def _br(x, *, r=0): + n = x.shape[-1] + x = np.expand_dims(x, axis=-2) + x = np.broadcast_to(x, x.shape[:-2] + (len(r), n)) + x = np.triu(x) + j = np.arange(n, dtype=x.dtype) + n = np.asarray(n, dtype=x.dtype)[()] + return (np.sum(special.binom(j, r[:, np.newaxis])*x, axis=-1) + / special.binom(n-1, r) / n) + + +def _prk(r, k): + # Writen to match [1] Equation 27 closely to facilitate review. + # This does not protect against overflow, so improvements to + # robustness would be a welcome follow-up. + return (-1)**(r-k)*special.binom(r, k)*special.binom(r+k, k) + + +@_axis_nan_policy_factory( # noqa: E302 + _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple, + n_outputs=lambda kwds: _moment_outputs(kwds, [1, 2, 3, 4]) +) +def lmoment(sample, order=None, *, axis=0, sorted=False, standardize=True): + r"""Compute L-moments of a sample from a continuous distribution + + The L-moments of a probability distribution are summary statistics with + uses similar to those of conventional moments, but they are defined in + terms of the expected values of order statistics. + Sample L-moments are defined analogously to population L-moments, and + they can serve as estimators of population L-moments. They tend to be less + sensitive to extreme observations than conventional moments. + + Parameters + ---------- + sample : array_like + The real-valued sample whose L-moments are desired. + order : array_like, optional + The (positive integer) orders of the desired L-moments. + Must be a scalar or non-empty 1D array. Default is [1, 2, 3, 4]. + axis : int or None, default=0 + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If None, the input will be + raveled before computing the statistic. + sorted : bool, default=False + Whether `sample` is already sorted in increasing order along `axis`. + If False (default), `sample` will be sorted. + standardize : bool, default=True + Whether to return L-moment ratios for orders 3 and higher. + L-moment ratios are analogous to standardized conventional + moments: they are the non-standardized L-moments divided + by the L-moment of order 2. + + Returns + ------- + lmoments : ndarray + The sample L-moments of order `order`. + + See Also + -------- + moment + + References + ---------- + .. [1] D. Bilkova. "L-Moments and TL-Moments as an Alternative Tool of + Statistical Data Analysis". Journal of Applied Mathematics and + Physics. 2014. :doi:`10.4236/jamp.2014.210104` + .. [2] J. R. M. Hosking. "L-Moments: Analysis and Estimation of Distributions + Using Linear Combinations of Order Statistics". Journal of the Royal + Statistical Society. 1990. :doi:`10.1111/j.2517-6161.1990.tb01775.x` + .. [3] "L-moment". *Wikipedia*. https://en.wikipedia.org/wiki/L-moment. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng(328458568356392) + >>> sample = rng.exponential(size=100000) + >>> stats.lmoment(sample) + array([1.00124272, 0.50111437, 0.3340092 , 0.16755338]) + + Note that the first four standardized population L-moments of the standard + exponential distribution are 1, 1/2, 1/3, and 1/6; the sample L-moments + provide reasonable estimates. + + """ + args = _lmoment_iv(sample, order, axis, sorted, standardize) + sample, order, axis, sorted, standardize = args + + n_moments = np.max(order) + k = np.arange(n_moments, dtype=sample.dtype) + prk = _prk(np.expand_dims(k, tuple(range(1, sample.ndim+1))), k) + bk = _br(sample, r=k) + + n = sample.shape[-1] + bk[..., n:] = 0 # remove NaNs due to n_moments > n + + lmoms = np.sum(prk * bk, axis=-1) + if standardize and n_moments > 2: + lmoms[2:] /= lmoms[1] + + lmoms[n:] = np.nan # add NaNs where appropriate + return lmoms[order-1] + + +LinregressResult = _make_tuple_bunch('LinregressResult', + ['slope', 'intercept', 'rvalue', + 'pvalue', 'stderr'], + extra_field_names=['intercept_stderr']) + + +def linregress(x, y=None, alternative='two-sided'): + """ + Calculate a linear least-squares regression for two sets of measurements. + + Parameters + ---------- + x, y : array_like + Two sets of measurements. Both arrays should have the same length N. If + only `x` is given (and ``y=None``), then it must be a two-dimensional + array where one dimension has length 2. The two sets of measurements + are then found by splitting the array along the length-2 dimension. In + the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is + equivalent to ``linregress(x[0], x[1])``. + + .. deprecated:: 1.14.0 + Inference of the two sets of measurements from a single argument `x` + is deprecated will result in an error in SciPy 1.16.0; the sets + must be specified separately as `x` and `y`. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the slope of the regression line is nonzero + * 'less': the slope of the regression line is less than zero + * 'greater': the slope of the regression line is greater than zero + + .. versionadded:: 1.7.0 + + Returns + ------- + result : ``LinregressResult`` instance + The return value is an object with the following attributes: + + slope : float + Slope of the regression line. + intercept : float + Intercept of the regression line. + rvalue : float + The Pearson correlation coefficient. The square of ``rvalue`` + is equal to the coefficient of determination. + pvalue : float + The p-value for a hypothesis test whose null hypothesis is + that the slope is zero, using Wald Test with t-distribution of + the test statistic. See `alternative` above for alternative + hypotheses. + stderr : float + Standard error of the estimated slope (gradient), under the + assumption of residual normality. + intercept_stderr : float + Standard error of the estimated intercept, under the assumption + of residual normality. + + See Also + -------- + scipy.optimize.curve_fit : + Use non-linear least squares to fit a function to data. + scipy.optimize.leastsq : + Minimize the sum of squares of a set of equations. + + Notes + ----- + For compatibility with older versions of SciPy, the return value acts + like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``, + ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write:: + + slope, intercept, r, p, se = linregress(x, y) + + With that style, however, the standard error of the intercept is not + available. To have access to all the computed values, including the + standard error of the intercept, use the return value as an object + with attributes, e.g.:: + + result = linregress(x, y) + print(result.intercept, result.intercept_stderr) + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import stats + >>> rng = np.random.default_rng() + + Generate some data: + + >>> x = rng.random(10) + >>> y = 1.6*x + rng.random(10) + + Perform the linear regression: + + >>> res = stats.linregress(x, y) + + Coefficient of determination (R-squared): + + >>> print(f"R-squared: {res.rvalue**2:.6f}") + R-squared: 0.717533 + + Plot the data along with the fitted line: + + >>> plt.plot(x, y, 'o', label='original data') + >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line') + >>> plt.legend() + >>> plt.show() + + Calculate 95% confidence interval on slope and intercept: + + >>> # Two-sided inverse Students t-distribution + >>> # p - probability, df - degrees of freedom + >>> from scipy.stats import t + >>> tinv = lambda p, df: abs(t.ppf(p/2, df)) + + >>> ts = tinv(0.05, len(x)-2) + >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}") + slope (95%): 1.453392 +/- 0.743465 + >>> print(f"intercept (95%): {res.intercept:.6f}" + ... f" +/- {ts*res.intercept_stderr:.6f}") + intercept (95%): 0.616950 +/- 0.544475 + + """ + TINY = 1.0e-20 + if y is None: # x is a (2, N) or (N, 2) shaped array_like + message = ('Inference of the two sets of measurements from a single "' + 'argument `x` is deprecated will result in an error in "' + 'SciPy 1.16.0; the sets must be specified separately as "' + '`x` and `y`.') + warnings.warn(message, DeprecationWarning, stacklevel=2) + x = np.asarray(x) + if x.shape[0] == 2: + x, y = x + elif x.shape[1] == 2: + x, y = x.T + else: + raise ValueError("If only `x` is given as input, it has to " + "be of shape (2, N) or (N, 2); provided shape " + f"was {x.shape}.") + else: + x = np.asarray(x) + y = np.asarray(y) + + if x.size == 0 or y.size == 0: + raise ValueError("Inputs must not be empty.") + + if np.amax(x) == np.amin(x) and len(x) > 1: + raise ValueError("Cannot calculate a linear regression " + "if all x values are identical") + + n = len(x) + xmean = np.mean(x, None) + ymean = np.mean(y, None) + + # Average sums of square differences from the mean + # ssxm = mean( (x-mean(x))^2 ) + # ssxym = mean( (x-mean(x)) * (y-mean(y)) ) + ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat + + # R-value + # r = ssxym / sqrt( ssxm * ssym ) + if ssxm == 0.0 or ssym == 0.0: + # If the denominator was going to be 0 + r = 0.0 + else: + r = ssxym / np.sqrt(ssxm * ssym) + # Test for numerical error propagation (make sure -1 < r < 1) + if r > 1.0: + r = 1.0 + elif r < -1.0: + r = -1.0 + + slope = ssxym / ssxm + intercept = ymean - slope*xmean + if n == 2: + # handle case when only two points are passed in + if y[0] == y[1]: + prob = 1.0 + else: + prob = 0.0 + slope_stderr = 0.0 + intercept_stderr = 0.0 + else: + df = n - 2 # Number of degrees of freedom + # n-2 degrees of freedom because 2 has been used up + # to estimate the mean and standard deviation + t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY))) + + dist = _SimpleStudentT(df) + prob = _get_pvalue(t, dist, alternative, xp=np) + prob = prob[()] if prob.ndim == 0 else prob + + slope_stderr = np.sqrt((1 - r**2) * ssym / ssxm / df) + + # Also calculate the standard error of the intercept + # The following relationship is used: + # ssxm = mean( (x-mean(x))^2 ) + # = ssx - sx*sx + # = mean( x^2 ) - mean(x)^2 + intercept_stderr = slope_stderr * np.sqrt(ssxm + xmean**2) + + return LinregressResult(slope=slope, intercept=intercept, rvalue=r, + pvalue=prob, stderr=slope_stderr, + intercept_stderr=intercept_stderr) + + +def _xp_mean(x, /, *, axis=None, weights=None, keepdims=False, nan_policy='propagate', + dtype=None, xp=None): + r"""Compute the arithmetic mean along the specified axis. + + Parameters + ---------- + x : real array + Array containing real numbers whose mean is desired. + axis : int or tuple of ints, default: None + If an int or tuple of ints, the axis or axes of the input along which + to compute the statistic. The statistic of each axis-slice (e.g. row) + of the input will appear in a corresponding element of the output. + If ``None``, the input will be raveled before computing the statistic. + weights : real array, optional + If specified, an array of weights associated with the values in `x`; + otherwise ``1``. If `weights` and `x` do not have the same shape, the + arrays will be broadcasted before performing the calculation. See + Notes for details. + keepdims : boolean, optional + If this is set to ``True``, the axes which are reduced are left + in the result as dimensions with length one. With this option, + the result will broadcast correctly against the input array. + nan_policy : {'propagate', 'omit', 'raise'}, default: 'propagate' + Defines how to handle input NaNs. + + - ``propagate``: if a NaN is present in the axis slice (e.g. row) along + which the statistic is computed, the corresponding entry of the output + will be NaN. + - ``omit``: NaNs will be omitted when performing the calculation. + If insufficient data remains in the axis slice along which the + statistic is computed, the corresponding entry of the output will be + NaN. + - ``raise``: if a NaN is present, a ``ValueError`` will be raised. + + dtype : dtype, optional + Type to use in computing the mean. For integer inputs, the default is + the default float type of the array library; for floating point inputs, + the dtype is that of the input. + + Returns + ------- + out : array + The mean of each slice + + Notes + ----- + Let :math:`x_i` represent element :math:`i` of data `x` and let :math:`w_i` + represent the corresponding element of `weights` after broadcasting. Then the + (weighted) mean :math:`\bar{x}_w` is given by: + + .. math:: + + \bar{x}_w = \frac{ \sum_{i=0}^{n-1} w_i x_i } + { \sum_{i=0}^{n-1} w_i } + + where :math:`n` is the number of elements along a slice. Note that this simplifies + to the familiar :math:`(\sum_i x_i) / n` when the weights are all ``1`` (default). + + The behavior of this function with respect to weights is somewhat different + from that of `np.average`. For instance, + `np.average` raises an error when `axis` is not specified and the shapes of `x` + and the `weights` array are not the same; `xp_mean` simply broadcasts the two. + Also, `np.average` raises an error when weights sum to zero along a slice; + `xp_mean` computes the appropriate result. The intent is for this function's + interface to be consistent with the rest of `scipy.stats`. + + Note that according to the formula, including NaNs with zero weights is not + the same as *omitting* NaNs with ``nan_policy='omit'``; in the former case, + the NaNs will continue to propagate through the calculation whereas in the + latter case, the NaNs are excluded entirely. + + """ + # ensure that `x` and `weights` are array-API compatible arrays of identical shape + xp = array_namespace(x) if xp is None else xp + x = _asarray(x, dtype=dtype, subok=True) + weights = xp.asarray(weights, dtype=dtype) if weights is not None else weights + + # to ensure that this matches the behavior of decorated functions when one of the + # arguments has size zero, it's easiest to call a similar decorated function. + if is_numpy(xp) and (xp_size(x) == 0 + or (weights is not None and xp_size(weights) == 0)): + return gmean(x, weights=weights, axis=axis, keepdims=keepdims) + + x, weights = xp_broadcast_promote(x, weights, force_floating=True) + + # handle the special case of zero-sized arrays + message = (too_small_1d_not_omit if (x.ndim == 1 or axis is None) + else too_small_nd_not_omit) + if xp_size(x) == 0: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + res = xp.mean(x, axis=axis, keepdims=keepdims) + if xp_size(res) != 0: + warnings.warn(message, SmallSampleWarning, stacklevel=2) + return res + + contains_nan, _ = _contains_nan(x, nan_policy, xp_omit_okay=True, xp=xp) + if weights is not None: + contains_nan_w, _ = _contains_nan(weights, nan_policy, xp_omit_okay=True, xp=xp) + contains_nan = contains_nan | contains_nan_w + + # Handle `nan_policy='omit'` by giving zero weight to NaNs, whether they + # appear in `x` or `weights`. Emit warning if there is an all-NaN slice. + message = (too_small_1d_omit if (x.ndim == 1 or axis is None) + else too_small_nd_omit) + if contains_nan and nan_policy == 'omit': + nan_mask = xp.isnan(x) + if weights is not None: + nan_mask |= xp.isnan(weights) + if xp.any(xp.all(nan_mask, axis=axis)): + warnings.warn(message, SmallSampleWarning, stacklevel=2) + weights = xp.ones_like(x) if weights is None else weights + x = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), x) + weights = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), weights) + + # Perform the mean calculation itself + if weights is None: + return xp.mean(x, axis=axis, keepdims=keepdims) + + norm = xp.sum(weights, axis=axis) + wsum = xp.sum(x * weights, axis=axis) + with np.errstate(divide='ignore', invalid='ignore'): + res = wsum/norm + + # Respect `keepdims` and convert NumPy 0-D arrays to scalars + if keepdims: + + if axis is None: + final_shape = (1,) * len(x.shape) + else: + # axis can be a scalar or sequence + axes = (axis,) if not isinstance(axis, Sequence) else axis + final_shape = list(x.shape) + for i in axes: + final_shape[i] = 1 + + res = xp.reshape(res, final_shape) + + return res[()] if res.ndim == 0 else res + + +def _xp_var(x, /, *, axis=None, correction=0, keepdims=False, nan_policy='propagate', + dtype=None, xp=None): + # an array-api compatible function for variance with scipy.stats interface + # and features (e.g. `nan_policy`). + xp = array_namespace(x) if xp is None else xp + x = _asarray(x, subok=True) + + # use `_xp_mean` instead of `xp.var` for desired warning behavior + # it would be nice to combine this with `_var`, which uses `_moment` + # and therefore warns when precision is lost, but that does not support + # `axis` tuples or keepdims. Eventually, `_axis_nan_policy` will simplify + # `axis` tuples and implement `keepdims` for non-NumPy arrays; then it will + # be easy. + kwargs = dict(axis=axis, nan_policy=nan_policy, dtype=dtype, xp=xp) + mean = _xp_mean(x, keepdims=True, **kwargs) + x = _asarray(x, dtype=mean.dtype, subok=True) + x_mean = _demean(x, mean, axis, xp=xp) + x_mean_conj = (xp.conj(x_mean) if xp.isdtype(x_mean.dtype, 'complex floating') + else x_mean) # crossref data-apis/array-api#824 + var = _xp_mean(x_mean * x_mean_conj, keepdims=keepdims, **kwargs) + + if correction != 0: + if axis is None: + n = xp_size(x) + elif np.iterable(axis): # note: using NumPy on `axis` is OK + n = math.prod(x.shape[i] for i in axis) + else: + n = x.shape[axis] + # Or two lines with ternaries : ) + # axis = range(x.ndim) if axis is None else axis + # n = math.prod(x.shape[i] for i in axis) if iterable(axis) else x.shape[axis] + + n = xp.asarray(n, dtype=var.dtype) + + if nan_policy == 'omit': + nan_mask = xp.astype(xp.isnan(x), var.dtype) + n = n - xp.sum(nan_mask, axis=axis, keepdims=keepdims) + + # Produce NaNs silently when n - correction <= 0 + factor = _lazywhere(n-correction > 0, (n, n-correction), xp.divide, xp.nan) + var *= factor + + return var[()] if var.ndim == 0 else var + + +class _SimpleNormal: + # A very simple, array-API compatible normal distribution for use in + # hypothesis tests. May be replaced by new infrastructure Normal + # distribution in due time. + + def cdf(self, x): + return special.ndtr(x) + + def sf(self, x): + return special.ndtr(-x) + + def isf(self, x): + return -special.ndtri(x) + + +class _SimpleChi2: + # A very simple, array-API compatible chi-squared distribution for use in + # hypothesis tests. May be replaced by new infrastructure chi-squared + # distribution in due time. + def __init__(self, df): + self.df = df + + def cdf(self, x): + return special.chdtr(self.df, x) + + def sf(self, x): + return special.chdtrc(self.df, x) + + +class _SimpleBeta: + # A very simple, array-API compatible beta distribution for use in + # hypothesis tests. May be replaced by new infrastructure beta + # distribution in due time. + def __init__(self, a, b, *, loc=None, scale=None): + self.a = a + self.b = b + self.loc = loc + self.scale = scale + + def cdf(self, x): + if self.loc is not None or self.scale is not None: + loc = 0 if self.loc is None else self.loc + scale = 1 if self.scale is None else self.scale + return special.betainc(self.a, self.b, (x - loc)/scale) + return special.betainc(self.a, self.b, x) + + def sf(self, x): + if self.loc is not None or self.scale is not None: + loc = 0 if self.loc is None else self.loc + scale = 1 if self.scale is None else self.scale + return special.betaincc(self.a, self.b, (x - loc)/scale) + return special.betaincc(self.a, self.b, x) + + +class _SimpleStudentT: + # A very simple, array-API compatible t distribution for use in + # hypothesis tests. May be replaced by new infrastructure t + # distribution in due time. + def __init__(self, df): + self.df = df + + def cdf(self, t): + return special.stdtr(self.df, t) + + def sf(self, t): + return special.stdtr(self.df, -t) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_survival.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_survival.py new file mode 100644 index 0000000000000000000000000000000000000000..aeea1645102f35460f3429b077aad9a705d331a2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_survival.py @@ -0,0 +1,683 @@ +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal +import warnings + +import numpy as np +from scipy import special, interpolate, stats +from scipy.stats._censored_data import CensoredData +from scipy.stats._common import ConfidenceInterval + +if TYPE_CHECKING: + import numpy.typing as npt + + +__all__ = ['ecdf', 'logrank'] + + +@dataclass +class EmpiricalDistributionFunction: + """An empirical distribution function produced by `scipy.stats.ecdf` + + Attributes + ---------- + quantiles : ndarray + The unique values of the sample from which the + `EmpiricalDistributionFunction` was estimated. + probabilities : ndarray + The point estimates of the cumulative distribution function (CDF) or + its complement, the survival function (SF), corresponding with + `quantiles`. + """ + quantiles: np.ndarray + probabilities: np.ndarray + # Exclude these from __str__ + _n: np.ndarray = field(repr=False) # number "at risk" + _d: np.ndarray = field(repr=False) # number of "deaths" + _sf: np.ndarray = field(repr=False) # survival function for var estimate + _kind: str = field(repr=False) # type of function: "cdf" or "sf" + + def __init__(self, q, p, n, d, kind): + self.probabilities = p + self.quantiles = q + self._n = n + self._d = d + self._sf = p if kind == 'sf' else 1 - p + self._kind = kind + + f0 = 1 if kind == 'sf' else 0 # leftmost function value + f1 = 1 - f0 + # fill_value can't handle edge cases at infinity + x = np.insert(q, [0, len(q)], [-np.inf, np.inf]) + y = np.insert(p, [0, len(p)], [f0, f1]) + # `or` conditions handle the case of empty x, points + self._f = interpolate.interp1d(x, y, kind='previous', + assume_sorted=True) + + def evaluate(self, x): + """Evaluate the empirical CDF/SF function at the input. + + Parameters + ---------- + x : ndarray + Argument to the CDF/SF + + Returns + ------- + y : ndarray + The CDF/SF evaluated at the input + """ + return self._f(x) + + def plot(self, ax=None, **matplotlib_kwargs): + """Plot the empirical distribution function + + Available only if ``matplotlib`` is installed. + + Parameters + ---------- + ax : matplotlib.axes.Axes + Axes object to draw the plot onto, otherwise uses the current Axes. + + **matplotlib_kwargs : dict, optional + Keyword arguments passed directly to `matplotlib.axes.Axes.step`. + Unless overridden, ``where='post'``. + + Returns + ------- + lines : list of `matplotlib.lines.Line2D` + Objects representing the plotted data + """ + try: + import matplotlib # noqa: F401 + except ModuleNotFoundError as exc: + message = "matplotlib must be installed to use method `plot`." + raise ModuleNotFoundError(message) from exc + + if ax is None: + import matplotlib.pyplot as plt + ax = plt.gca() + + kwargs = {'where': 'post'} + kwargs.update(matplotlib_kwargs) + + delta = np.ptp(self.quantiles)*0.05 # how far past sample edge to plot + q = self.quantiles + q = [q[0] - delta] + list(q) + [q[-1] + delta] + + return ax.step(q, self.evaluate(q), **kwargs) + + def confidence_interval(self, confidence_level=0.95, *, method='linear'): + """Compute a confidence interval around the CDF/SF point estimate + + Parameters + ---------- + confidence_level : float, default: 0.95 + Confidence level for the computed confidence interval + + method : str, {"linear", "log-log"} + Method used to compute the confidence interval. Options are + "linear" for the conventional Greenwood confidence interval + (default) and "log-log" for the "exponential Greenwood", + log-negative-log-transformed confidence interval. + + Returns + ------- + ci : ``ConfidenceInterval`` + An object with attributes ``low`` and ``high``, instances of + `~scipy.stats._result_classes.EmpiricalDistributionFunction` that + represent the lower and upper bounds (respectively) of the + confidence interval. + + Notes + ----- + Confidence intervals are computed according to the Greenwood formula + (``method='linear'``) or the more recent "exponential Greenwood" + formula (``method='log-log'``) as described in [1]_. The conventional + Greenwood formula can result in lower confidence limits less than 0 + and upper confidence limits greater than 1; these are clipped to the + unit interval. NaNs may be produced by either method; these are + features of the formulas. + + References + ---------- + .. [1] Sawyer, Stanley. "The Greenwood and Exponential Greenwood + Confidence Intervals in Survival Analysis." + https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf + + """ + message = ("Confidence interval bounds do not implement a " + "`confidence_interval` method.") + if self._n is None: + raise NotImplementedError(message) + + methods = {'linear': self._linear_ci, + 'log-log': self._loglog_ci} + + message = f"`method` must be one of {set(methods)}." + if method.lower() not in methods: + raise ValueError(message) + + message = "`confidence_level` must be a scalar between 0 and 1." + confidence_level = np.asarray(confidence_level)[()] + if confidence_level.shape or not (0 <= confidence_level <= 1): + raise ValueError(message) + + method_fun = methods[method.lower()] + low, high = method_fun(confidence_level) + + message = ("The confidence interval is undefined at some observations." + " This is a feature of the mathematical formula used, not" + " an error in its implementation.") + if np.any(np.isnan(low) | np.isnan(high)): + warnings.warn(message, RuntimeWarning, stacklevel=2) + + low, high = np.clip(low, 0, 1), np.clip(high, 0, 1) + low = EmpiricalDistributionFunction(self.quantiles, low, None, None, + self._kind) + high = EmpiricalDistributionFunction(self.quantiles, high, None, None, + self._kind) + return ConfidenceInterval(low, high) + + def _linear_ci(self, confidence_level): + sf, d, n = self._sf, self._d, self._n + # When n == d, Greenwood's formula divides by zero. + # When s != 0, this can be ignored: var == inf, and CI is [0, 1] + # When s == 0, this results in NaNs. Produce an informative warning. + with np.errstate(divide='ignore', invalid='ignore'): + var = sf ** 2 * np.cumsum(d / (n * (n - d))) + + se = np.sqrt(var) + z = special.ndtri(1 / 2 + confidence_level / 2) + + z_se = z * se + low = self.probabilities - z_se + high = self.probabilities + z_se + + return low, high + + def _loglog_ci(self, confidence_level): + sf, d, n = self._sf, self._d, self._n + + with np.errstate(divide='ignore', invalid='ignore'): + var = 1 / np.log(sf) ** 2 * np.cumsum(d / (n * (n - d))) + + se = np.sqrt(var) + z = special.ndtri(1 / 2 + confidence_level / 2) + + with np.errstate(divide='ignore'): + lnl_points = np.log(-np.log(sf)) + + z_se = z * se + low = np.exp(-np.exp(lnl_points + z_se)) + high = np.exp(-np.exp(lnl_points - z_se)) + if self._kind == "cdf": + low, high = 1-high, 1-low + + return low, high + + +@dataclass +class ECDFResult: + """ Result object returned by `scipy.stats.ecdf` + + Attributes + ---------- + cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction` + An object representing the empirical cumulative distribution function. + sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction` + An object representing the complement of the empirical cumulative + distribution function. + """ + cdf: EmpiricalDistributionFunction + sf: EmpiricalDistributionFunction + + def __init__(self, q, cdf, sf, n, d): + self.cdf = EmpiricalDistributionFunction(q, cdf, n, d, "cdf") + self.sf = EmpiricalDistributionFunction(q, sf, n, d, "sf") + + +def _iv_CensoredData( + sample: "npt.ArrayLike | CensoredData", param_name: str = "sample" +) -> CensoredData: + """Attempt to convert `sample` to `CensoredData`.""" + if not isinstance(sample, CensoredData): + try: # takes care of input standardization/validation + sample = CensoredData(uncensored=sample) + except ValueError as e: + message = str(e).replace('uncensored', param_name) + raise type(e)(message) from e + return sample + + +def ecdf(sample: "npt.ArrayLike | CensoredData") -> ECDFResult: + """Empirical cumulative distribution function of a sample. + + The empirical cumulative distribution function (ECDF) is a step function + estimate of the CDF of the distribution underlying a sample. This function + returns objects representing both the empirical distribution function and + its complement, the empirical survival function. + + Parameters + ---------- + sample : 1D array_like or `scipy.stats.CensoredData` + Besides array_like, instances of `scipy.stats.CensoredData` containing + uncensored and right-censored observations are supported. Currently, + other instances of `scipy.stats.CensoredData` will result in a + ``NotImplementedError``. + + Returns + ------- + res : `~scipy.stats._result_classes.ECDFResult` + An object with the following attributes. + + cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction` + An object representing the empirical cumulative distribution + function. + sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction` + An object representing the empirical survival function. + + The `cdf` and `sf` attributes themselves have the following attributes. + + quantiles : ndarray + The unique values in the sample that defines the empirical CDF/SF. + probabilities : ndarray + The point estimates of the probabilities corresponding with + `quantiles`. + + And the following methods: + + evaluate(x) : + Evaluate the CDF/SF at the argument. + + plot(ax) : + Plot the CDF/SF on the provided axes. + + confidence_interval(confidence_level=0.95) : + Compute the confidence interval around the CDF/SF at the values in + `quantiles`. + + Notes + ----- + When each observation of the sample is a precise measurement, the ECDF + steps up by ``1/len(sample)`` at each of the observations [1]_. + + When observations are lower bounds, upper bounds, or both upper and lower + bounds, the data is said to be "censored", and `sample` may be provided as + an instance of `scipy.stats.CensoredData`. + + For right-censored data, the ECDF is given by the Kaplan-Meier estimator + [2]_; other forms of censoring are not supported at this time. + + Confidence intervals are computed according to the Greenwood formula or the + more recent "Exponential Greenwood" formula as described in [4]_. + + References + ---------- + .. [1] Conover, William Jay. Practical nonparametric statistics. Vol. 350. + John Wiley & Sons, 1999. + + .. [2] Kaplan, Edward L., and Paul Meier. "Nonparametric estimation from + incomplete observations." Journal of the American statistical + association 53.282 (1958): 457-481. + + .. [3] Goel, Manish Kumar, Pardeep Khanna, and Jugal Kishore. + "Understanding survival analysis: Kaplan-Meier estimate." + International journal of Ayurveda research 1.4 (2010): 274. + + .. [4] Sawyer, Stanley. "The Greenwood and Exponential Greenwood Confidence + Intervals in Survival Analysis." + https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf + + Examples + -------- + **Uncensored Data** + + As in the example from [1]_ page 79, five boys were selected at random from + those in a single high school. Their one-mile run times were recorded as + follows. + + >>> sample = [6.23, 5.58, 7.06, 6.42, 5.20] # one-mile run times (minutes) + + The empirical distribution function, which approximates the distribution + function of one-mile run times of the population from which the boys were + sampled, is calculated as follows. + + >>> from scipy import stats + >>> res = stats.ecdf(sample) + >>> res.cdf.quantiles + array([5.2 , 5.58, 6.23, 6.42, 7.06]) + >>> res.cdf.probabilities + array([0.2, 0.4, 0.6, 0.8, 1. ]) + + To plot the result as a step function: + + >>> import matplotlib.pyplot as plt + >>> ax = plt.subplot() + >>> res.cdf.plot(ax) + >>> ax.set_xlabel('One-Mile Run Time (minutes)') + >>> ax.set_ylabel('Empirical CDF') + >>> plt.show() + + **Right-censored Data** + + As in the example from [1]_ page 91, the lives of ten car fanbelts were + tested. Five tests concluded because the fanbelt being tested broke, but + the remaining tests concluded for other reasons (e.g. the study ran out of + funding, but the fanbelt was still functional). The mileage driven + with the fanbelts were recorded as follows. + + >>> broken = [77, 47, 81, 56, 80] # in thousands of miles driven + >>> unbroken = [62, 60, 43, 71, 37] + + Precise survival times of the fanbelts that were still functional at the + end of the tests are unknown, but they are known to exceed the values + recorded in ``unbroken``. Therefore, these observations are said to be + "right-censored", and the data is represented using + `scipy.stats.CensoredData`. + + >>> sample = stats.CensoredData(uncensored=broken, right=unbroken) + + The empirical survival function is calculated as follows. + + >>> res = stats.ecdf(sample) + >>> res.sf.quantiles + array([37., 43., 47., 56., 60., 62., 71., 77., 80., 81.]) + >>> res.sf.probabilities + array([1. , 1. , 0.875, 0.75 , 0.75 , 0.75 , 0.75 , 0.5 , 0.25 , 0. ]) + + To plot the result as a step function: + + >>> ax = plt.subplot() + >>> res.sf.plot(ax) + >>> ax.set_xlabel('Fanbelt Survival Time (thousands of miles)') + >>> ax.set_ylabel('Empirical SF') + >>> plt.show() + + """ + sample = _iv_CensoredData(sample) + + if sample.num_censored() == 0: + res = _ecdf_uncensored(sample._uncensor()) + elif sample.num_censored() == sample._right.size: + res = _ecdf_right_censored(sample) + else: + # Support additional censoring options in follow-up PRs + message = ("Currently, only uncensored and right-censored data is " + "supported.") + raise NotImplementedError(message) + + t, cdf, sf, n, d = res + return ECDFResult(t, cdf, sf, n, d) + + +def _ecdf_uncensored(sample): + sample = np.sort(sample) + x, counts = np.unique(sample, return_counts=True) + + # [1].81 "the fraction of [observations] that are less than or equal to x + events = np.cumsum(counts) + n = sample.size + cdf = events / n + + # [1].89 "the relative frequency of the sample that exceeds x in value" + sf = 1 - cdf + + at_risk = np.concatenate(([n], n - events[:-1])) + return x, cdf, sf, at_risk, counts + + +def _ecdf_right_censored(sample): + # It is conventional to discuss right-censored data in terms of + # "survival time", "death", and "loss" (e.g. [2]). We'll use that + # terminology here. + # This implementation was influenced by the references cited and also + # https://www.youtube.com/watch?v=lxoWsVco_iM + # https://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator + # In retrospect it is probably most easily compared against [3]. + # Ultimately, the data needs to be sorted, so this implementation is + # written to avoid a separate call to `unique` after sorting. In hope of + # better performance on large datasets, it also computes survival + # probabilities at unique times only rather than at each observation. + tod = sample._uncensored # time of "death" + tol = sample._right # time of "loss" + times = np.concatenate((tod, tol)) + died = np.asarray([1]*tod.size + [0]*tol.size) + + # sort by times + i = np.argsort(times) + times = times[i] + died = died[i] + at_risk = np.arange(times.size, 0, -1) + + # logical indices of unique times + j = np.diff(times, prepend=-np.inf, append=np.inf) > 0 + j_l = j[:-1] # first instances of unique times + j_r = j[1:] # last instances of unique times + + # get number at risk and deaths at each unique time + t = times[j_l] # unique times + n = at_risk[j_l] # number at risk at each unique time + cd = np.cumsum(died)[j_r] # cumulative deaths up to/including unique times + d = np.diff(cd, prepend=0) # deaths at each unique time + + # compute survival function + sf = np.cumprod((n - d) / n) + cdf = 1 - sf + return t, cdf, sf, n, d + + +@dataclass +class LogRankResult: + """Result object returned by `scipy.stats.logrank`. + + Attributes + ---------- + statistic : float ndarray + The computed statistic (defined below). Its magnitude is the + square root of the magnitude returned by most other logrank test + implementations. + pvalue : float ndarray + The computed p-value of the test. + """ + statistic: np.ndarray + pvalue: np.ndarray + + +def logrank( + x: "npt.ArrayLike | CensoredData", + y: "npt.ArrayLike | CensoredData", + alternative: Literal['two-sided', 'less', 'greater'] = "two-sided" +) -> LogRankResult: + r"""Compare the survival distributions of two samples via the logrank test. + + Parameters + ---------- + x, y : array_like or CensoredData + Samples to compare based on their empirical survival functions. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. + + The null hypothesis is that the survival distributions of the two + groups, say *X* and *Y*, are identical. + + The following alternative hypotheses [4]_ are available (default is + 'two-sided'): + + * 'two-sided': the survival distributions of the two groups are not + identical. + * 'less': survival of group *X* is favored: the group *X* failure rate + function is less than the group *Y* failure rate function at some + times. + * 'greater': survival of group *Y* is favored: the group *X* failure + rate function is greater than the group *Y* failure rate function at + some times. + + Returns + ------- + res : `~scipy.stats._result_classes.LogRankResult` + An object containing attributes: + + statistic : float ndarray + The computed statistic (defined below). Its magnitude is the + square root of the magnitude returned by most other logrank test + implementations. + pvalue : float ndarray + The computed p-value of the test. + + See Also + -------- + scipy.stats.ecdf + + Notes + ----- + The logrank test [1]_ compares the observed number of events to + the expected number of events under the null hypothesis that the two + samples were drawn from the same distribution. The statistic is + + .. math:: + + Z_i = \frac{\sum_{j=1}^J(O_{i,j}-E_{i,j})}{\sqrt{\sum_{j=1}^J V_{i,j}}} + \rightarrow \mathcal{N}(0,1) + + where + + .. math:: + + E_{i,j} = O_j \frac{N_{i,j}}{N_j}, + \qquad + V_{i,j} = E_{i,j} \left(\frac{N_j-O_j}{N_j}\right) + \left(\frac{N_j-N_{i,j}}{N_j-1}\right), + + :math:`i` denotes the group (i.e. it may assume values :math:`x` or + :math:`y`, or it may be omitted to refer to the combined sample) + :math:`j` denotes the time (at which an event occurred), + :math:`N` is the number of subjects at risk just before an event occurred, + and :math:`O` is the observed number of events at that time. + + The ``statistic`` :math:`Z_x` returned by `logrank` is the (signed) square + root of the statistic returned by many other implementations. Under the + null hypothesis, :math:`Z_x**2` is asymptotically distributed according to + the chi-squared distribution with one degree of freedom. Consequently, + :math:`Z_x` is asymptotically distributed according to the standard normal + distribution. The advantage of using :math:`Z_x` is that the sign + information (i.e. whether the observed number of events tends to be less + than or greater than the number expected under the null hypothesis) is + preserved, allowing `scipy.stats.logrank` to offer one-sided alternative + hypotheses. + + References + ---------- + .. [1] Mantel N. "Evaluation of survival data and two new rank order + statistics arising in its consideration." + Cancer Chemotherapy Reports, 50(3):163-170, PMID: 5910392, 1966 + .. [2] Bland, Altman, "The logrank test", BMJ, 328:1073, + :doi:`10.1136/bmj.328.7447.1073`, 2004 + .. [3] "Logrank test", Wikipedia, + https://en.wikipedia.org/wiki/Logrank_test + .. [4] Brown, Mark. "On the choice of variance for the log rank test." + Biometrika 71.1 (1984): 65-74. + .. [5] Klein, John P., and Melvin L. Moeschberger. Survival analysis: + techniques for censored and truncated data. Vol. 1230. New York: + Springer, 2003. + + Examples + -------- + Reference [2]_ compared the survival times of patients with two different + types of recurrent malignant gliomas. The samples below record the time + (number of weeks) for which each patient participated in the study. The + `scipy.stats.CensoredData` class is used because the data is + right-censored: the uncensored observations correspond with observed deaths + whereas the censored observations correspond with the patient leaving the + study for another reason. + + >>> from scipy import stats + >>> x = stats.CensoredData( + ... uncensored=[6, 13, 21, 30, 37, 38, 49, 50, + ... 63, 79, 86, 98, 202, 219], + ... right=[31, 47, 80, 82, 82, 149] + ... ) + >>> y = stats.CensoredData( + ... uncensored=[10, 10, 12, 13, 14, 15, 16, 17, 18, 20, 24, 24, + ... 25, 28,30, 33, 35, 37, 40, 40, 46, 48, 76, 81, + ... 82, 91, 112, 181], + ... right=[34, 40, 70] + ... ) + + We can calculate and visualize the empirical survival functions + of both groups as follows. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> ax = plt.subplot() + >>> ecdf_x = stats.ecdf(x) + >>> ecdf_x.sf.plot(ax, label='Astrocytoma') + >>> ecdf_y = stats.ecdf(y) + >>> ecdf_y.sf.plot(ax, label='Glioblastoma') + >>> ax.set_xlabel('Time to death (weeks)') + >>> ax.set_ylabel('Empirical SF') + >>> plt.legend() + >>> plt.show() + + Visual inspection of the empirical survival functions suggests that the + survival times tend to be different between the two groups. To formally + assess whether the difference is significant at the 1% level, we use the + logrank test. + + >>> res = stats.logrank(x=x, y=y) + >>> res.statistic + -2.73799 + >>> res.pvalue + 0.00618 + + The p-value is less than 1%, so we can consider the data to be evidence + against the null hypothesis in favor of the alternative that there is a + difference between the two survival functions. + + """ + # Input validation. `alternative` IV handled in `_get_pvalue` below. + x = _iv_CensoredData(sample=x, param_name='x') + y = _iv_CensoredData(sample=y, param_name='y') + + # Combined sample. (Under H0, the two groups are identical.) + xy = CensoredData( + uncensored=np.concatenate((x._uncensored, y._uncensored)), + right=np.concatenate((x._right, y._right)) + ) + + # Extract data from the combined sample + res = ecdf(xy) + idx = res.sf._d.astype(bool) # indices of observed events + times_xy = res.sf.quantiles[idx] # unique times of observed events + at_risk_xy = res.sf._n[idx] # combined number of subjects at risk + deaths_xy = res.sf._d[idx] # combined number of events + + # Get the number at risk within each sample. + # First compute the number at risk in group X at each of the `times_xy`. + # Could use `interpolate_1d`, but this is more compact. + res_x = ecdf(x) + i = np.searchsorted(res_x.sf.quantiles, times_xy) + at_risk_x = np.append(res_x.sf._n, 0)[i] # 0 at risk after last time + # Subtract from the combined number at risk to get number at risk in Y + at_risk_y = at_risk_xy - at_risk_x + + # Compute the variance. + num = at_risk_x * at_risk_y * deaths_xy * (at_risk_xy - deaths_xy) + den = at_risk_xy**2 * (at_risk_xy - 1) + # Note: when `at_risk_xy == 1`, we would have `at_risk_xy - 1 == 0` in the + # numerator and denominator. Simplifying the fraction symbolically, we + # would always find the overall quotient to be zero, so don't compute it. + i = at_risk_xy > 1 + sum_var = np.sum(num[i]/den[i]) + + # Get the observed and expected number of deaths in group X + n_died_x = x._uncensored.size + sum_exp_deaths_x = np.sum(at_risk_x * (deaths_xy/at_risk_xy)) + + # Compute the statistic. This is the square root of that in references. + statistic = (n_died_x - sum_exp_deaths_x)/np.sqrt(sum_var) + + # Equivalent to chi2(df=1).sf(statistic**2) when alternative='two-sided' + norm = stats._stats_py._SimpleNormal() + pvalue = stats._stats_py._get_pvalue(statistic, norm, alternative, xp=np) + + return LogRankResult(statistic=statistic[()], pvalue=pvalue[()]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_tukeylambda_stats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_tukeylambda_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..b77173c136d80eb57f5c993108b7408653acad13 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_tukeylambda_stats.py @@ -0,0 +1,199 @@ +import numpy as np +from numpy import poly1d +from scipy.special import beta + + +# The following code was used to generate the Pade coefficients for the +# Tukey Lambda variance function. Version 0.17 of mpmath was used. +#--------------------------------------------------------------------------- +# import mpmath as mp +# +# mp.mp.dps = 60 +# +# one = mp.mpf(1) +# two = mp.mpf(2) +# +# def mpvar(lam): +# if lam == 0: +# v = mp.pi**2 / three +# else: +# v = (two / lam**2) * (one / (one + two*lam) - +# mp.beta(lam + one, lam + one)) +# return v +# +# t = mp.taylor(mpvar, 0, 8) +# p, q = mp.pade(t, 4, 4) +# print("p =", [mp.fp.mpf(c) for c in p]) +# print("q =", [mp.fp.mpf(c) for c in q]) +#--------------------------------------------------------------------------- + +# Pade coefficients for the Tukey Lambda variance function. +_tukeylambda_var_pc = [3.289868133696453, 0.7306125098871127, + -0.5370742306855439, 0.17292046290190008, + -0.02371146284628187] +_tukeylambda_var_qc = [1.0, 3.683605511659861, 4.184152498888124, + 1.7660926747377275, 0.2643989311168465] + +# numpy.poly1d instances for the numerator and denominator of the +# Pade approximation to the Tukey Lambda variance. +_tukeylambda_var_p = poly1d(_tukeylambda_var_pc[::-1]) +_tukeylambda_var_q = poly1d(_tukeylambda_var_qc[::-1]) + + +def tukeylambda_variance(lam): + """Variance of the Tukey Lambda distribution. + + Parameters + ---------- + lam : array_like + The lambda values at which to compute the variance. + + Returns + ------- + v : ndarray + The variance. For lam < -0.5, the variance is not defined, so + np.nan is returned. For lam = 0.5, np.inf is returned. + + Notes + ----- + In an interval around lambda=0, this function uses the [4,4] Pade + approximation to compute the variance. Otherwise it uses the standard + formula (https://en.wikipedia.org/wiki/Tukey_lambda_distribution). The + Pade approximation is used because the standard formula has a removable + discontinuity at lambda = 0, and does not produce accurate numerical + results near lambda = 0. + """ + lam = np.asarray(lam) + shp = lam.shape + lam = np.atleast_1d(lam).astype(np.float64) + + # For absolute values of lam less than threshold, use the Pade + # approximation. + threshold = 0.075 + + # Play games with masks to implement the conditional evaluation of + # the distribution. + # lambda < -0.5: var = nan + low_mask = lam < -0.5 + # lambda == -0.5: var = inf + neghalf_mask = lam == -0.5 + # abs(lambda) < threshold: use Pade approximation + small_mask = np.abs(lam) < threshold + # else the "regular" case: use the explicit formula. + reg_mask = ~(low_mask | neghalf_mask | small_mask) + + # Get the 'lam' values for the cases where they are needed. + small = lam[small_mask] + reg = lam[reg_mask] + + # Compute the function for each case. + v = np.empty_like(lam) + v[low_mask] = np.nan + v[neghalf_mask] = np.inf + if small.size > 0: + # Use the Pade approximation near lambda = 0. + v[small_mask] = _tukeylambda_var_p(small) / _tukeylambda_var_q(small) + if reg.size > 0: + v[reg_mask] = (2.0 / reg**2) * (1.0 / (1.0 + 2 * reg) - + beta(reg + 1, reg + 1)) + v.shape = shp + return v + + +# The following code was used to generate the Pade coefficients for the +# Tukey Lambda kurtosis function. Version 0.17 of mpmath was used. +#--------------------------------------------------------------------------- +# import mpmath as mp +# +# mp.mp.dps = 60 +# +# one = mp.mpf(1) +# two = mp.mpf(2) +# three = mp.mpf(3) +# four = mp.mpf(4) +# +# def mpkurt(lam): +# if lam == 0: +# k = mp.mpf(6)/5 +# else: +# numer = (one/(four*lam+one) - four*mp.beta(three*lam+one, lam+one) + +# three*mp.beta(two*lam+one, two*lam+one)) +# denom = two*(one/(two*lam+one) - mp.beta(lam+one,lam+one))**2 +# k = numer / denom - three +# return k +# +# # There is a bug in mpmath 0.17: when we use the 'method' keyword of the +# # taylor function and we request a degree 9 Taylor polynomial, we actually +# # get degree 8. +# t = mp.taylor(mpkurt, 0, 9, method='quad', radius=0.01) +# t = [mp.chop(c, tol=1e-15) for c in t] +# p, q = mp.pade(t, 4, 4) +# print("p =", [mp.fp.mpf(c) for c in p]) +# print("q =", [mp.fp.mpf(c) for c in q]) +#--------------------------------------------------------------------------- + +# Pade coefficients for the Tukey Lambda kurtosis function. +_tukeylambda_kurt_pc = [1.2, -5.853465139719495, -22.653447381131077, + 0.20601184383406815, 4.59796302262789] +_tukeylambda_kurt_qc = [1.0, 7.171149192233599, 12.96663094361842, + 0.43075235247853005, -2.789746758009912] + +# numpy.poly1d instances for the numerator and denominator of the +# Pade approximation to the Tukey Lambda kurtosis. +_tukeylambda_kurt_p = poly1d(_tukeylambda_kurt_pc[::-1]) +_tukeylambda_kurt_q = poly1d(_tukeylambda_kurt_qc[::-1]) + + +def tukeylambda_kurtosis(lam): + """Kurtosis of the Tukey Lambda distribution. + + Parameters + ---------- + lam : array_like + The lambda values at which to compute the variance. + + Returns + ------- + v : ndarray + The variance. For lam < -0.25, the variance is not defined, so + np.nan is returned. For lam = 0.25, np.inf is returned. + + """ + lam = np.asarray(lam) + shp = lam.shape + lam = np.atleast_1d(lam).astype(np.float64) + + # For absolute values of lam less than threshold, use the Pade + # approximation. + threshold = 0.055 + + # Use masks to implement the conditional evaluation of the kurtosis. + # lambda < -0.25: kurtosis = nan + low_mask = lam < -0.25 + # lambda == -0.25: kurtosis = inf + negqrtr_mask = lam == -0.25 + # lambda near 0: use Pade approximation + small_mask = np.abs(lam) < threshold + # else the "regular" case: use the explicit formula. + reg_mask = ~(low_mask | negqrtr_mask | small_mask) + + # Get the 'lam' values for the cases where they are needed. + small = lam[small_mask] + reg = lam[reg_mask] + + # Compute the function for each case. + k = np.empty_like(lam) + k[low_mask] = np.nan + k[negqrtr_mask] = np.inf + if small.size > 0: + k[small_mask] = _tukeylambda_kurt_p(small) / _tukeylambda_kurt_q(small) + if reg.size > 0: + numer = (1.0 / (4 * reg + 1) - 4 * beta(3 * reg + 1, reg + 1) + + 3 * beta(2 * reg + 1, 2 * reg + 1)) + denom = 2 * (1.0/(2 * reg + 1) - beta(reg + 1, reg + 1))**2 + k[reg_mask] = numer / denom - 3 + + # The return value will be a numpy array; resetting the shape ensures that + # if `lam` was a scalar, the return value is a 0-d array. + k.shape = shp + return k diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a9fefb77d573156ae7989b656bc1ea9681e877e2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi @@ -0,0 +1,178 @@ +import numpy as np +from typing import (overload, Callable, NamedTuple, Protocol) +import numpy.typing as npt +from scipy._lib._util import SeedType +import scipy.stats as stats + + +ArrayLike0D = bool | int | float | complex | str | bytes | np.generic + + +__all__: list[str] + + +class UNURANError(RuntimeError): + ... + + +class Method: + @overload + def rvs(self, size: None = ...) -> float | int: ... # type: ignore[overload-overlap] + @overload + def rvs(self, size: int | tuple[int, ...] = ...) -> np.ndarray: ... + def set_random_state(self, random_state: SeedType) -> None: ... + + +class TDRDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def dpdf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + + +class TransformedDensityRejection(Method): + def __init__(self, + dist: TDRDist, + *, + mode: None | float = ..., + center: None | float = ..., + domain: None | tuple[float, float] = ..., + c: float = ..., + construction_points: int | npt.ArrayLike = ..., + use_dars: bool = ..., + max_squeeze_hat_ratio: float = ..., + random_state: SeedType = ...) -> None: ... + @property + def squeeze_hat_ratio(self) -> float: ... + @property + def squeeze_area(self) -> float: ... + @overload + def ppf_hat(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap] + @overload + def ppf_hat(self, u: npt.ArrayLike) -> np.ndarray: ... + + +class SROUDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + + +class SimpleRatioUniforms(Method): + def __init__(self, + dist: SROUDist, + *, + mode: None | float = ..., + pdf_area: float = ..., + domain: None | tuple[float, float] = ..., + cdf_at_mode: float = ..., + random_state: SeedType = ...) -> None: ... + + +class UError(NamedTuple): + max_error: float + mean_absolute_error: float + +class PINVDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def cdf(self) -> Callable[..., float]: ... + @property + def logpdf(self) -> Callable[..., float]: ... + + +class NumericalInversePolynomial(Method): + def __init__(self, + dist: PINVDist, + *, + mode: None | float = ..., + center: None | float = ..., + domain: None | tuple[float, float] = ..., + order: int = ..., + u_resolution: float = ..., + random_state: SeedType = ...) -> None: ... + @property + def intervals(self) -> int: ... + @overload + def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap] + @overload + def ppf(self, u: npt.ArrayLike) -> np.ndarray: ... + @overload + def cdf(self, x: ArrayLike0D) -> float: ... # type: ignore[overload-overlap] + @overload + def cdf(self, x: npt.ArrayLike) -> np.ndarray: ... + def u_error(self, sample_size: int = ...) -> UError: ... + def qrvs(self, + size: None | int | tuple[int, ...] = ..., + d: None | int = ..., + qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ... + + +class HINVDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def cdf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + + +class NumericalInverseHermite(Method): + def __init__(self, + dist: HINVDist, + *, + domain: None | tuple[float, float] = ..., + order: int= ..., + u_resolution: float = ..., + construction_points: None | npt.ArrayLike = ..., + max_intervals: int = ..., + random_state: SeedType = ...) -> None: ... + @property + def intervals(self) -> int: ... + @overload + def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap] + @overload + def ppf(self, u: npt.ArrayLike) -> np.ndarray: ... + def qrvs(self, + size: None | int | tuple[int, ...] = ..., + d: None | int = ..., + qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ... + def u_error(self, sample_size: int = ...) -> UError: ... + + +class DAUDist(Protocol): + @property + def pmf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + +class DiscreteAliasUrn(Method): + def __init__(self, + dist: npt.ArrayLike | DAUDist, + *, + domain: None | tuple[float, float] = ..., + urn_factor: float = ..., + random_state: SeedType = ...) -> None: ... + + +class DGTDist(Protocol): + @property + def pmf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + +class DiscreteGuideTable(Method): + def __init__(self, + dist: npt.ArrayLike | DGTDist, + *, + domain: None | tuple[float, float] = ..., + guide_factor: float = ..., + random_state: SeedType = ...) -> None: ... + @overload + def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[overload-overlap] + @overload + def ppf(self, u: npt.ArrayLike) -> np.ndarray: ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_variation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_variation.py new file mode 100644 index 0000000000000000000000000000000000000000..9febde9ec8f1ae967634ed799f5f7ba2d817318e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_variation.py @@ -0,0 +1,128 @@ +import numpy as np + +from scipy._lib._util import _get_nan +from scipy._lib._array_api import array_namespace, xp_copysign + +from ._axis_nan_policy import _axis_nan_policy_factory + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,) +) +def variation(a, axis=0, nan_policy='propagate', ddof=0, *, keepdims=False): + """ + Compute the coefficient of variation. + + The coefficient of variation is the standard deviation divided by the + mean. This function is equivalent to:: + + np.std(x, axis=axis, ddof=ddof) / np.mean(x) + + The default for ``ddof`` is 0, but many definitions of the coefficient + of variation use the square root of the unbiased sample variance + for the sample standard deviation, which corresponds to ``ddof=1``. + + The function does not take the absolute value of the mean of the data, + so the return value is negative if the mean is negative. + + Parameters + ---------- + a : array_like + Input array. + axis : int or None, optional + Axis along which to calculate the coefficient of variation. + Default is 0. If None, compute over the whole array `a`. + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains ``nan``. + The following options are available: + + * 'propagate': return ``nan`` + * 'raise': raise an exception + * 'omit': perform the calculation with ``nan`` values omitted + + The default is 'propagate'. + ddof : int, optional + Gives the "Delta Degrees Of Freedom" used when computing the + standard deviation. The divisor used in the calculation of the + standard deviation is ``N - ddof``, where ``N`` is the number of + elements. `ddof` must be less than ``N``; if it isn't, the result + will be ``nan`` or ``inf``, depending on ``N`` and the values in + the array. By default `ddof` is zero for backwards compatibility, + but it is recommended to use ``ddof=1`` to ensure that the sample + standard deviation is computed as the square root of the unbiased + sample variance. + + Returns + ------- + variation : ndarray + The calculated variation along the requested axis. + + Notes + ----- + There are several edge cases that are handled without generating a + warning: + + * If both the mean and the standard deviation are zero, ``nan`` + is returned. + * If the mean is zero and the standard deviation is nonzero, ``inf`` + is returned. + * If the input has length zero (either because the array has zero + length, or all the input values are ``nan`` and ``nan_policy`` is + ``'omit'``), ``nan`` is returned. + * If the input contains ``inf``, ``nan`` is returned. + + References + ---------- + .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard + Probability and Statistics Tables and Formulae. Chapman & Hall: New + York. 2000. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import variation + >>> variation([1, 2, 3, 4, 5], ddof=1) + 0.5270462766947299 + + Compute the variation along a given dimension of an array that contains + a few ``nan`` values: + + >>> x = np.array([[ 10.0, np.nan, 11.0, 19.0, 23.0, 29.0, 98.0], + ... [ 29.0, 30.0, 32.0, 33.0, 35.0, 56.0, 57.0], + ... [np.nan, np.nan, 12.0, 13.0, 16.0, 16.0, 17.0]]) + >>> variation(x, axis=1, ddof=1, nan_policy='omit') + array([1.05109361, 0.31428986, 0.146483 ]) + + """ + xp = array_namespace(a) + a = xp.asarray(a) + # `nan_policy` and `keepdims` are handled by `_axis_nan_policy` + # `axis=None` is only handled for NumPy backend + if axis is None: + a = xp.reshape(a, (-1,)) + axis = 0 + + n = a.shape[axis] + NaN = _get_nan(a) + + if a.size == 0 or ddof > n: + # Handle as a special case to avoid spurious warnings. + # The return values, if any, are all nan. + shp = list(a.shape) + shp.pop(axis) + result = xp.full(shp, fill_value=NaN) + return result[()] if result.ndim == 0 else result + + mean_a = xp.mean(a, axis=axis) + + if ddof == n: + # Another special case. Result is either inf or nan. + std_a = xp.std(a, axis=axis, correction=0) + result = xp.where(std_a > 0, xp_copysign(xp.asarray(xp.inf), mean_a), NaN) + return result[()] if result.ndim == 0 else result + + with np.errstate(divide='ignore', invalid='ignore'): + std_a = xp.std(a, axis=axis, correction=ddof) + result = std_a / mean_a + + return result[()] if result.ndim == 0 else result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_warnings_errors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_warnings_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..38385b862c9d642b41af8d74279f98c6a427208a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_warnings_errors.py @@ -0,0 +1,38 @@ +# Warnings + + +class DegenerateDataWarning(RuntimeWarning): + """Warns when data is degenerate and results may not be reliable.""" + def __init__(self, msg=None): + if msg is None: + msg = ("Degenerate data encountered; results may not be reliable.") + self.args = (msg,) + + +class ConstantInputWarning(DegenerateDataWarning): + """Warns when all values in data are exactly equal.""" + def __init__(self, msg=None): + if msg is None: + msg = ("All values in data are exactly equal; " + "results may not be reliable.") + self.args = (msg,) + + +class NearConstantInputWarning(DegenerateDataWarning): + """Warns when all values in data are nearly equal.""" + def __init__(self, msg=None): + if msg is None: + msg = ("All values in data are nearly equal; " + "results may not be reliable.") + self.args = (msg,) + + +# Errors + + +class FitError(RuntimeError): + """Represents an error condition when fitting a distribution to data.""" + def __init__(self, msg=None): + if msg is None: + msg = ("An error occurred when fitting a distribution to data.") + self.args = (msg,) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_wilcoxon.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_wilcoxon.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb475614d7d28edaf3ff04bfbda3f5a18242bef --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/_wilcoxon.py @@ -0,0 +1,259 @@ +import numpy as np + +from scipy import stats +from ._stats_py import _get_pvalue, _rankdata, _SimpleNormal +from . import _morestats +from ._axis_nan_policy import _broadcast_arrays +from ._hypotests import _get_wilcoxon_distr +from scipy._lib._util import _lazywhere, _get_nan + + +class WilcoxonDistribution: + + def __init__(self, n): + n = np.asarray(n).astype(int, copy=False) + self.n = n + self._dists = {ni: _get_wilcoxon_distr(ni) for ni in np.unique(n)} + + def _cdf1(self, k, n): + pmfs = self._dists[n] + return pmfs[:k + 1].sum() + + def _cdf(self, k, n): + return np.vectorize(self._cdf1, otypes=[float])(k, n) + + def _sf1(self, k, n): + pmfs = self._dists[n] + return pmfs[k:].sum() + + def _sf(self, k, n): + return np.vectorize(self._sf1, otypes=[float])(k, n) + + def mean(self): + return self.n * (self.n + 1) / 4 + + def _prep(self, k): + k = np.asarray(k).astype(int, copy=False) + mn = self.mean() + out = np.empty(k.shape, dtype=np.float64) + return k, mn, out + + def cdf(self, k): + k, mn, out = self._prep(k) + return _lazywhere(k <= mn, (k, self.n), self._cdf, + f2=lambda k, n: 1 - self._sf(k+1, n))[()] + + def sf(self, k): + k, mn, out = self._prep(k) + return _lazywhere(k <= mn, (k, self.n), self._sf, + f2=lambda k, n: 1 - self._cdf(k-1, n))[()] + + +def _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis): + + axis = np.asarray(axis)[()] + message = "`axis` must be an integer." + if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0: + raise ValueError(message) + + message = '`axis` must be compatible with the shape(s) of `x` (and `y`)' + try: + if y is None: + x = np.asarray(x) + d = x + else: + x, y = _broadcast_arrays((x, y), axis=axis) + d = x - y + d = np.moveaxis(d, axis, -1) + except np.AxisError as e: + raise ValueError(message) from e + + message = "`x` and `y` must have the same length along `axis`." + if y is not None and x.shape[axis] != y.shape[axis]: + raise ValueError(message) + + message = "`x` (and `y`, if provided) must be an array of real numbers." + if np.issubdtype(d.dtype, np.integer): + d = d.astype(np.float64) + if not np.issubdtype(d.dtype, np.floating): + raise ValueError(message) + + zero_method = str(zero_method).lower() + zero_methods = {"wilcox", "pratt", "zsplit"} + message = f"`zero_method` must be one of {zero_methods}." + if zero_method not in zero_methods: + raise ValueError(message) + + corrections = {True, False} + message = f"`correction` must be one of {corrections}." + if correction not in corrections: + raise ValueError(message) + + alternative = str(alternative).lower() + alternatives = {"two-sided", "less", "greater"} + message = f"`alternative` must be one of {alternatives}." + if alternative not in alternatives: + raise ValueError(message) + + if not isinstance(method, stats.PermutationMethod): + methods = {"auto", "asymptotic", "exact"} + message = (f"`method` must be one of {methods} or " + "an instance of `stats.PermutationMethod`.") + if method not in methods: + raise ValueError(message) + output_z = True if method == 'asymptotic' else False + + # For small samples, we decide later whether to perform an exact test or a + # permutation test. The reason is that the presence of ties is not + # known at the input validation stage. + n_zero = np.sum(d == 0) + if method == "auto" and d.shape[-1] > 50: + method = "asymptotic" + + return d, zero_method, correction, alternative, method, axis, output_z, n_zero + + +def _wilcoxon_statistic(d, method, zero_method='wilcox'): + + i_zeros = (d == 0) + + if zero_method == 'wilcox': + # Wilcoxon's method for treating zeros was to remove them from + # the calculation. We do this by replacing 0s with NaNs, which + # are ignored anyway. + if not d.flags['WRITEABLE']: + d = d.copy() + d[i_zeros] = np.nan + + i_nan = np.isnan(d) + n_nan = np.sum(i_nan, axis=-1) + count = d.shape[-1] - n_nan + + r, t = _rankdata(abs(d), 'average', return_ties=True) + + r_plus = np.sum((d > 0) * r, axis=-1) + r_minus = np.sum((d < 0) * r, axis=-1) + + has_ties = (t == 0).any() + + if zero_method == "zsplit": + # The "zero-split" method for treating zeros is to add half their contribution + # to r_plus and half to r_minus. + # See gh-2263 for the origin of this method. + r_zero_2 = np.sum(i_zeros * r, axis=-1) / 2 + r_plus += r_zero_2 + r_minus += r_zero_2 + + mn = count * (count + 1.) * 0.25 + se = count * (count + 1.) * (2. * count + 1.) + + if zero_method == "pratt": + # Pratt's method for treating zeros was just to modify the z-statistic. + + # normal approximation needs to be adjusted, see Cureton (1967) + n_zero = i_zeros.sum(axis=-1) + mn -= n_zero * (n_zero + 1.) * 0.25 + se -= n_zero * (n_zero + 1.) * (2. * n_zero + 1.) + + # zeros are not to be included in tie-correction. + # any tie counts corresponding with zeros are in the 0th column + t[i_zeros.any(axis=-1), 0] = 0 + + tie_correct = (t**3 - t).sum(axis=-1) + se -= tie_correct/2 + se = np.sqrt(se / 24) + + # se = 0 means that no non-zero values are left in d. we only need z + # if method is asymptotic. however, if method="auto", the switch to + # asymptotic might only happen after the statistic is calculated, so z + # needs to be computed. in all other cases, avoid division by zero warning + # (z is not needed anyways) + if method in ["asymptotic", "auto"]: + z = (r_plus - mn) / se + else: + z = np.nan + + return r_plus, r_minus, se, z, count, has_ties + + +def _correction_sign(z, alternative): + if alternative == 'greater': + return 1 + elif alternative == 'less': + return -1 + else: + return np.sign(z) + + +def _wilcoxon_nd(x, y=None, zero_method='wilcox', correction=True, + alternative='two-sided', method='auto', axis=0): + + temp = _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis) + d, zero_method, correction, alternative, method, axis, output_z, n_zero = temp + + if d.size == 0: + NaN = _get_nan(d) + res = _morestats.WilcoxonResult(statistic=NaN, pvalue=NaN) + if method == 'asymptotic': + res.zstatistic = NaN + return res + + r_plus, r_minus, se, z, count, has_ties = _wilcoxon_statistic( + d, method, zero_method + ) + + # we only know if there are ties after computing the statistic and not + # at the input validation stage. if the original method was auto and + # the decision was to use an exact test, we override this to + # a permutation test now (since method='exact' is not exact in the + # presence of ties) + if method == "auto": + if not (has_ties or n_zero > 0): + method = "exact" + elif d.shape[-1] <= 13: + # the possible outcomes to be simulated by the permutation test + # are 2**n, where n is the sample size. + # if n <= 13, the p-value is deterministic since 2**13 is less + # than 9999, the default number of n_resamples + method = stats.PermutationMethod() + else: + # if there are ties and the sample size is too large to + # run a deterministic permutation test, fall back to asymptotic + method = "asymptotic" + + if method == 'asymptotic': + if correction: + sign = _correction_sign(z, alternative) + z -= sign * 0.5 / se + p = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + elif method == 'exact': + dist = WilcoxonDistribution(count) + # The null distribution in `dist` is exact only if there are no ties + # or zeros. If there are ties or zeros, the statistic can be non- + # integral, but the null distribution is only defined for integral + # values of the statistic. Therefore, we're conservative: round + # non-integral statistic up before computing CDF and down before + # computing SF. This preserves symmetry w.r.t. alternatives and + # order of the input arguments. See gh-19872. + if alternative == 'less': + p = dist.cdf(np.ceil(r_plus)) + elif alternative == 'greater': + p = dist.sf(np.floor(r_plus)) + else: + p = 2 * np.minimum(dist.sf(np.floor(r_plus)), + dist.cdf(np.ceil(r_plus))) + p = np.clip(p, 0, 1) + else: # `PermutationMethod` instance (already validated) + p = stats.permutation_test( + (d,), lambda d: _wilcoxon_statistic(d, method, zero_method)[0], + permutation_type='samples', **method._asdict(), + alternative=alternative, axis=-1).pvalue + + # for backward compatibility... + statistic = np.minimum(r_plus, r_minus) if alternative=='two-sided' else r_plus + z = -np.abs(z) if (alternative == 'two-sided' and method == 'asymptotic') else z + + res = _morestats.WilcoxonResult(statistic=statistic, pvalue=p[()]) + if output_z: + res.zstatistic = z[()] + return res diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/biasedurn.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/biasedurn.py new file mode 100644 index 0000000000000000000000000000000000000000..2b1c9f1cf2b3b39acdcaeda97a90e8c11c589d89 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/biasedurn.py @@ -0,0 +1,16 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="stats", module="biasedurn", + private_modules=["_biasedurn"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/contingency.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/contingency.py new file mode 100644 index 0000000000000000000000000000000000000000..809df62e3cdaa2887fab2164afbe01e496ac6315 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/contingency.py @@ -0,0 +1,521 @@ +""" +Contingency table functions (:mod:`scipy.stats.contingency`) +============================================================ + +Functions for creating and analyzing contingency tables. + +.. currentmodule:: scipy.stats.contingency + +.. autosummary:: + :toctree: generated/ + + chi2_contingency + relative_risk + odds_ratio + crosstab + association + + expected_freq + margins + +""" + + +from functools import reduce +import math +import numpy as np +from ._stats_py import power_divergence, _untabulate +from ._relative_risk import relative_risk +from ._crosstab import crosstab +from ._odds_ratio import odds_ratio +from scipy._lib._bunch import _make_tuple_bunch +from scipy import stats + + +__all__ = ['margins', 'expected_freq', 'chi2_contingency', 'crosstab', + 'association', 'relative_risk', 'odds_ratio'] + + +def margins(a): + """Return a list of the marginal sums of the array `a`. + + Parameters + ---------- + a : ndarray + The array for which to compute the marginal sums. + + Returns + ------- + margsums : list of ndarrays + A list of length `a.ndim`. `margsums[k]` is the result + of summing `a` over all axes except `k`; it has the same + number of dimensions as `a`, but the length of each axis + except axis `k` will be 1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats.contingency import margins + + >>> a = np.arange(12).reshape(2, 6) + >>> a + array([[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11]]) + >>> m0, m1 = margins(a) + >>> m0 + array([[15], + [51]]) + >>> m1 + array([[ 6, 8, 10, 12, 14, 16]]) + + >>> b = np.arange(24).reshape(2,3,4) + >>> m0, m1, m2 = margins(b) + >>> m0 + array([[[ 66]], + [[210]]]) + >>> m1 + array([[[ 60], + [ 92], + [124]]]) + >>> m2 + array([[[60, 66, 72, 78]]]) + """ + margsums = [] + ranged = list(range(a.ndim)) + for k in ranged: + marg = np.apply_over_axes(np.sum, a, [j for j in ranged if j != k]) + margsums.append(marg) + return margsums + + +def expected_freq(observed): + """ + Compute the expected frequencies from a contingency table. + + Given an n-dimensional contingency table of observed frequencies, + compute the expected frequencies for the table based on the marginal + sums under the assumption that the groups associated with each + dimension are independent. + + Parameters + ---------- + observed : array_like + The table of observed frequencies. (While this function can handle + a 1-D array, that case is trivial. Generally `observed` is at + least 2-D.) + + Returns + ------- + expected : ndarray of float64 + The expected frequencies, based on the marginal sums of the table. + Same shape as `observed`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats.contingency import expected_freq + >>> observed = np.array([[10, 10, 20],[20, 20, 20]]) + >>> expected_freq(observed) + array([[ 12., 12., 16.], + [ 18., 18., 24.]]) + + """ + # Typically `observed` is an integer array. If `observed` has a large + # number of dimensions or holds large values, some of the following + # computations may overflow, so we first switch to floating point. + observed = np.asarray(observed, dtype=np.float64) + + # Create a list of the marginal sums. + margsums = margins(observed) + + # Create the array of expected frequencies. The shapes of the + # marginal sums returned by apply_over_axes() are just what we + # need for broadcasting in the following product. + d = observed.ndim + expected = reduce(np.multiply, margsums) / observed.sum() ** (d - 1) + return expected + + +Chi2ContingencyResult = _make_tuple_bunch( + 'Chi2ContingencyResult', + ['statistic', 'pvalue', 'dof', 'expected_freq'], [] +) + + +def chi2_contingency(observed, correction=True, lambda_=None, *, method=None): + """Chi-square test of independence of variables in a contingency table. + + This function computes the chi-square statistic and p-value for the + hypothesis test of independence of the observed frequencies in the + contingency table [1]_ `observed`. The expected frequencies are computed + based on the marginal sums under the assumption of independence; see + `scipy.stats.contingency.expected_freq`. The number of degrees of + freedom is (expressed using numpy functions and attributes):: + + dof = observed.size - sum(observed.shape) + observed.ndim - 1 + + + Parameters + ---------- + observed : array_like + The contingency table. The table contains the observed frequencies + (i.e. number of occurrences) in each category. In the two-dimensional + case, the table is often described as an "R x C table". + correction : bool, optional + If True, *and* the degrees of freedom is 1, apply Yates' correction + for continuity. The effect of the correction is to adjust each + observed value by 0.5 towards the corresponding expected value. + lambda_ : float or str, optional + By default, the statistic computed in this test is Pearson's + chi-squared statistic [2]_. `lambda_` allows a statistic from the + Cressie-Read power divergence family [3]_ to be used instead. See + `scipy.stats.power_divergence` for details. + method : ResamplingMethod, optional + Defines the method used to compute the p-value. Compatible only with + `correction=False`, default `lambda_`, and two-way tables. + If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`, + the p-value is computed using + `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the + provided configuration options and other appropriate settings. + Otherwise, the p-value is computed as documented in the notes. + Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs`` + attribute must be left unspecified; Monte Carlo samples are always drawn + using the ``rvs`` method of `scipy.stats.random_table`. + + .. versionadded:: 1.15.0 + + + Returns + ------- + res : Chi2ContingencyResult + An object containing attributes: + + statistic : float + The test statistic. + pvalue : float + The p-value of the test. + dof : int + The degrees of freedom. NaN if `method` is not ``None``. + expected_freq : ndarray, same shape as `observed` + The expected frequencies, based on the marginal sums of the table. + + See Also + -------- + scipy.stats.contingency.expected_freq + scipy.stats.fisher_exact + scipy.stats.chisquare + scipy.stats.power_divergence + scipy.stats.barnard_exact + scipy.stats.boschloo_exact + :ref:`hypothesis_chi2_contingency` : Extended example + + Notes + ----- + An often quoted guideline for the validity of this calculation is that + the test should be used only if the observed and expected frequencies + in each cell are at least 5. + + This is a test for the independence of different categories of a + population. The test is only meaningful when the dimension of + `observed` is two or more. Applying the test to a one-dimensional + table will always result in `expected` equal to `observed` and a + chi-square statistic equal to 0. + + This function does not handle masked arrays, because the calculation + does not make sense with missing values. + + Like `scipy.stats.chisquare`, this function computes a chi-square + statistic; the convenience this function provides is to figure out the + expected frequencies and degrees of freedom from the given contingency + table. If these were already known, and if the Yates' correction was not + required, one could use `scipy.stats.chisquare`. That is, if one calls:: + + res = chi2_contingency(obs, correction=False) + + then the following is true:: + + (res.statistic, res.pvalue) == stats.chisquare(obs.ravel(), + f_exp=ex.ravel(), + ddof=obs.size - 1 - dof) + + The `lambda_` argument was added in version 0.13.0 of scipy. + + References + ---------- + .. [1] "Contingency table", + https://en.wikipedia.org/wiki/Contingency_table + .. [2] "Pearson's chi-squared test", + https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test + .. [3] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit + Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984), + pp. 440-464. + + Examples + -------- + A two-way example (2 x 3): + + >>> import numpy as np + >>> from scipy.stats import chi2_contingency + >>> obs = np.array([[10, 10, 20], [20, 20, 20]]) + >>> res = chi2_contingency(obs) + >>> res.statistic + 2.7777777777777777 + >>> res.pvalue + 0.24935220877729619 + >>> res.dof + 2 + >>> res.expected_freq + array([[ 12., 12., 16.], + [ 18., 18., 24.]]) + + Perform the test using the log-likelihood ratio (i.e. the "G-test") + instead of Pearson's chi-squared statistic. + + >>> res = chi2_contingency(obs, lambda_="log-likelihood") + >>> res.statistic + 2.7688587616781319 + >>> res.pvalue + 0.25046668010954165 + + A four-way example (2 x 2 x 2 x 2): + + >>> obs = np.array( + ... [[[[12, 17], + ... [11, 16]], + ... [[11, 12], + ... [15, 16]]], + ... [[[23, 15], + ... [30, 22]], + ... [[14, 17], + ... [15, 16]]]]) + >>> res = chi2_contingency(obs) + >>> res.statistic + 8.7584514426741897 + >>> res.pvalue + 0.64417725029295503 + + When the sum of the elements in a two-way table is small, the p-value + produced by the default asymptotic approximation may be inaccurate. + Consider passing a `PermutationMethod` or `MonteCarloMethod` as the + `method` parameter with `correction=False`. + + >>> from scipy.stats import PermutationMethod + >>> obs = np.asarray([[12, 3], + ... [17, 16]]) + >>> res = chi2_contingency(obs, correction=False) + >>> ref = chi2_contingency(obs, correction=False, method=PermutationMethod()) + >>> res.pvalue, ref.pvalue + (0.0614122539870913, 0.1074) # may vary + + For a more detailed example, see :ref:`hypothesis_chi2_contingency`. + + """ + observed = np.asarray(observed) + if np.any(observed < 0): + raise ValueError("All values in `observed` must be nonnegative.") + if observed.size == 0: + raise ValueError("No data; `observed` has size 0.") + + expected = expected_freq(observed) + if np.any(expected == 0): + # Include one of the positions where expected is zero in + # the exception message. + zeropos = list(zip(*np.nonzero(expected == 0)))[0] + raise ValueError("The internally computed table of expected " + f"frequencies has a zero element at {zeropos}.") + + if method is not None: + return _chi2_resampling_methods(observed, expected, correction, lambda_, method) + + # The degrees of freedom + dof = expected.size - sum(expected.shape) + expected.ndim - 1 + + if dof == 0: + # Degenerate case; this occurs when `observed` is 1D (or, more + # generally, when it has only one nontrivial dimension). In this + # case, we also have observed == expected, so chi2 is 0. + chi2 = 0.0 + p = 1.0 + else: + if dof == 1 and correction: + # Adjust `observed` according to Yates' correction for continuity. + # Magnitude of correction no bigger than difference; see gh-13875 + diff = expected - observed + direction = np.sign(diff) + magnitude = np.minimum(0.5, np.abs(diff)) + observed = observed + magnitude * direction + + chi2, p = power_divergence(observed, expected, + ddof=observed.size - 1 - dof, axis=None, + lambda_=lambda_) + + return Chi2ContingencyResult(chi2, p, dof, expected) + + +def _chi2_resampling_methods(observed, expected, correction, lambda_, method): + + if observed.ndim != 2: + message = 'Use of `method` is only compatible with two-way tables.' + raise ValueError(message) + + if correction: + message = f'`{correction=}` is not compatible with `{method=}.`' + raise ValueError(message) + + if lambda_ is not None: + message = f'`{lambda_=}` is not compatible with `{method=}.`' + raise ValueError(message) + + if isinstance(method, stats.PermutationMethod): + res = _chi2_permutation_method(observed, expected, method) + elif isinstance(method, stats.MonteCarloMethod): + res = _chi2_monte_carlo_method(observed, expected, method) + else: + message = (f'`{method=}` not recognized; if provided, `method` must be an ' + 'instance of `PermutationMethod` or `MonteCarloMethod`.') + raise ValueError(message) + + return Chi2ContingencyResult(res.statistic, res.pvalue, np.nan, expected) + + +def _chi2_permutation_method(observed, expected, method): + x, y = _untabulate(observed) + # `permutation_test` with `permutation_type='pairings' permutes the order of `x`, + # which pairs observations in `x` with different observations in `y`. + def statistic(x): + # crosstab the resample and compute the statistic + table = crosstab(x, y)[1] + return np.sum((table - expected)**2/expected) + + return stats.permutation_test((x,), statistic, permutation_type='pairings', + alternative='greater', **method._asdict()) + + +def _chi2_monte_carlo_method(observed, expected, method): + method = method._asdict() + + if method.pop('rvs', None) is not None: + message = ('If the `method` argument of `chi2_contingency` is an ' + 'instance of `MonteCarloMethod`, its `rvs` attribute ' + 'must be unspecified. Use the `MonteCarloMethod` `rng` argument ' + 'to control the random state.') + raise ValueError(message) + rng = np.random.default_rng(method.pop('rng', None)) + + # `random_table.rvs` produces random contingency tables with the given marginals + # under the null hypothesis of independence + rowsums, colsums = stats.contingency.margins(observed) + X = stats.random_table(rowsums.ravel(), colsums.ravel(), seed=rng) + def rvs(size): + n_resamples = size[0] + return X.rvs(size=n_resamples).reshape(size) + + expected = expected.ravel() + def statistic(table, axis): + return np.sum((table - expected)**2/expected, axis=axis) + + return stats.monte_carlo_test(observed.ravel(), rvs, statistic, + alternative='greater', **method) + + +def association(observed, method="cramer", correction=False, lambda_=None): + """Calculates degree of association between two nominal variables. + + The function provides the option for computing one of three measures of + association between two nominal variables from the data given in a 2d + contingency table: Tschuprow's T, Pearson's Contingency Coefficient + and Cramer's V. + + Parameters + ---------- + observed : array-like + The array of observed values + method : {"cramer", "tschuprow", "pearson"} (default = "cramer") + The association test statistic. + correction : bool, optional + Inherited from `scipy.stats.contingency.chi2_contingency()` + lambda_ : float or str, optional + Inherited from `scipy.stats.contingency.chi2_contingency()` + + Returns + ------- + statistic : float + Value of the test statistic + + Notes + ----- + Cramer's V, Tschuprow's T and Pearson's Contingency Coefficient, all + measure the degree to which two nominal or ordinal variables are related, + or the level of their association. This differs from correlation, although + many often mistakenly consider them equivalent. Correlation measures in + what way two variables are related, whereas, association measures how + related the variables are. As such, association does not subsume + independent variables, and is rather a test of independence. A value of + 1.0 indicates perfect association, and 0.0 means the variables have no + association. + + Both the Cramer's V and Tschuprow's T are extensions of the phi + coefficient. Moreover, due to the close relationship between the + Cramer's V and Tschuprow's T the returned values can often be similar + or even equivalent. They are likely to diverge more as the array shape + diverges from a 2x2. + + References + ---------- + .. [1] "Tschuprow's T", + https://en.wikipedia.org/wiki/Tschuprow's_T + .. [2] Tschuprow, A. A. (1939) + Principles of the Mathematical Theory of Correlation; + translated by M. Kantorowitsch. W. Hodge & Co. + .. [3] "Cramer's V", https://en.wikipedia.org/wiki/Cramer's_V + .. [4] "Nominal Association: Phi and Cramer's V", + http://www.people.vcu.edu/~pdattalo/702SuppRead/MeasAssoc/NominalAssoc.html + .. [5] Gingrich, Paul, "Association Between Variables", + http://uregina.ca/~gingrich/ch11a.pdf + + Examples + -------- + An example with a 4x2 contingency table: + + >>> import numpy as np + >>> from scipy.stats.contingency import association + >>> obs4x2 = np.array([[100, 150], [203, 322], [420, 700], [320, 210]]) + + Pearson's contingency coefficient + + >>> association(obs4x2, method="pearson") + 0.18303298140595667 + + Cramer's V + + >>> association(obs4x2, method="cramer") + 0.18617813077483678 + + Tschuprow's T + + >>> association(obs4x2, method="tschuprow") + 0.14146478765062995 + """ + arr = np.asarray(observed) + if not np.issubdtype(arr.dtype, np.integer): + raise ValueError("`observed` must be an integer array.") + + if len(arr.shape) != 2: + raise ValueError("method only accepts 2d arrays") + + chi2_stat = chi2_contingency(arr, correction=correction, + lambda_=lambda_) + + phi2 = chi2_stat.statistic / arr.sum() + n_rows, n_cols = arr.shape + if method == "cramer": + value = phi2 / min(n_cols - 1, n_rows - 1) + elif method == "tschuprow": + value = phi2 / math.sqrt((n_rows - 1) * (n_cols - 1)) + elif method == 'pearson': + value = phi2 / (1 + phi2) + else: + raise ValueError("Invalid argument value: 'method' argument must " + "be 'cramer', 'tschuprow', or 'pearson'") + + return math.sqrt(value) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/distributions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9c37aa98c9545b2616c8d32e8f676d8d49289e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/distributions.py @@ -0,0 +1,24 @@ +# +# Author: Travis Oliphant 2002-2011 with contributions from +# SciPy Developers 2004-2011 +# +# NOTE: To look at history using `git blame`, use `git blame -M -C -C` +# instead of `git blame -Lxxx,+x`. +# +from ._distn_infrastructure import (rv_discrete, rv_continuous, rv_frozen) # noqa: F401 + +from . import _continuous_distns +from . import _discrete_distns + +from ._continuous_distns import * # noqa: F403 +from ._levy_stable import levy_stable +from ._discrete_distns import * # noqa: F403 +from ._entropy import entropy + +# For backwards compatibility e.g. pymc expects distributions.__all__. +__all__ = ['rv_discrete', 'rv_continuous', 'rv_histogram', 'entropy'] # noqa: F405 + +# Add only the distribution names, not the *_gen names. +__all__ += _continuous_distns._distn_names +__all__ += ['levy_stable'] +__all__ += _discrete_distns._distn_names diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/kde.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/kde.py new file mode 100644 index 0000000000000000000000000000000000000000..4401da5a30f4452ab394232d3928493d0e3b77ec --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/kde.py @@ -0,0 +1,18 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.stats` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = ["gaussian_kde"] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="stats", module="kde", + private_modules=["_kde"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/morestats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/morestats.py new file mode 100644 index 0000000000000000000000000000000000000000..ee8e6f43b7aaf7cb9af0fc1b37fdcee3a63277a3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/morestats.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.stats` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'mvsdist', + 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', + 'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot', + 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene', + 'fligner', 'mood', 'wilcoxon', 'median_test', + 'circmean', 'circvar', 'circstd', 'anderson_ksamp', + 'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax', + 'yeojohnson_normplot', 'find_repeats', 'chi2_contingency', 'distributions', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="stats", module="morestats", + private_modules=["_morestats"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats.py new file mode 100644 index 0000000000000000000000000000000000000000..88016af71803dc5c4ebadba168f22cdcd8273dbb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats.py @@ -0,0 +1,140 @@ +""" +=================================================================== +Statistical functions for masked arrays (:mod:`scipy.stats.mstats`) +=================================================================== + +.. currentmodule:: scipy.stats.mstats + +This module contains a large number of statistical functions that can +be used with masked arrays. + +Most of these functions are similar to those in `scipy.stats` but might +have small differences in the API or in the algorithm used. Since this +is a relatively new package, some API changes are still possible. + +Summary statistics +================== + +.. autosummary:: + :toctree: generated/ + + describe + gmean + hmean + kurtosis + mode + mquantiles + hdmedian + hdquantiles + hdquantiles_sd + idealfourths + plotting_positions + meppf + moment + skew + tmean + tvar + tmin + tmax + tsem + variation + find_repeats + sem + trimmed_mean + trimmed_mean_ci + trimmed_std + trimmed_var + +Frequency statistics +==================== + +.. autosummary:: + :toctree: generated/ + + scoreatpercentile + +Correlation functions +===================== + +.. autosummary:: + :toctree: generated/ + + f_oneway + pearsonr + spearmanr + pointbiserialr + kendalltau + kendalltau_seasonal + linregress + siegelslopes + theilslopes + sen_seasonal_slopes + +Statistical tests +================= + +.. autosummary:: + :toctree: generated/ + + ttest_1samp + ttest_onesamp + ttest_ind + ttest_rel + chisquare + kstest + ks_2samp + ks_1samp + ks_twosamp + mannwhitneyu + rankdata + kruskal + kruskalwallis + friedmanchisquare + brunnermunzel + skewtest + kurtosistest + normaltest + +Transformations +=============== + +.. autosummary:: + :toctree: generated/ + + obrientransform + trim + trima + trimmed_stde + trimr + trimtail + trimboth + winsorize + zmap + zscore + +Other +===== + +.. autosummary:: + :toctree: generated/ + + argstoarray + count_tied_groups + msign + compare_medians_ms + median_cihs + mjci + mquantiles_cimj + rsh + +""" +from . import _mstats_basic +from . import _mstats_extras +from ._mstats_basic import * # noqa: F403 +from ._mstats_extras import * # noqa: F403 +# Functions that support masked array input in stats but need to be kept in the +# mstats namespace for backwards compatibility: +from scipy.stats import gmean, hmean, zmap, zscore, chisquare + +__all__ = _mstats_basic.__all__ + _mstats_extras.__all__ +__all__ += ['gmean', 'hmean', 'zmap', 'zscore', 'chisquare'] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..19cc67a6acdfa054ffa2b29b6e774dd7aafda263 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats_basic.py @@ -0,0 +1,42 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.stats` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'argstoarray', + 'count_tied_groups', + 'describe', + 'f_oneway', 'find_repeats','friedmanchisquare', + 'kendalltau','kendalltau_seasonal','kruskal','kruskalwallis', + 'ks_twosamp', 'ks_2samp', 'kurtosis', 'kurtosistest', + 'ks_1samp', 'kstest', + 'linregress', + 'mannwhitneyu', 'meppf','mode','moment','mquantiles','msign', + 'normaltest', + 'obrientransform', + 'pearsonr','plotting_positions','pointbiserialr', + 'rankdata', + 'scoreatpercentile','sem', + 'sen_seasonal_slopes','skew','skewtest','spearmanr', + 'siegelslopes', 'theilslopes', + 'tmax','tmean','tmin','trim','trimboth', + 'trimtail','trima','trimr','trimmed_mean','trimmed_std', + 'trimmed_stde','trimmed_var','tsem','ttest_1samp','ttest_onesamp', + 'ttest_ind','ttest_rel','tvar', + 'variation', + 'winsorize', + 'brunnermunzel', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="stats", module="mstats_basic", + private_modules=["_mstats_basic"], all=__all__, + attribute=name, correct_module="mstats") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats_extras.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats_extras.py new file mode 100644 index 0000000000000000000000000000000000000000..fec695329cf2c2d58a4918cc99e209c0650c3ea6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mstats_extras.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.stats` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'compare_medians_ms', + 'hdquantiles', 'hdmedian', 'hdquantiles_sd', + 'idealfourths', + 'median_cihs','mjci','mquantiles_cimj', + 'rsh', + 'trimmed_mean_ci', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="stats", module="mstats_extras", + private_modules=["_mstats_extras"], all=__all__, + attribute=name, correct_module="mstats") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mvn.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mvn.py new file mode 100644 index 0000000000000000000000000000000000000000..65da9e20f6a4e6d24c1cb206c59821730fb6ab83 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/mvn.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.stats` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="stats", module="mvn", + private_modules=["_mvn"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/qmc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/qmc.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a08343cf4c759938b31c29e32aaa644bf6e0fd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/qmc.py @@ -0,0 +1,236 @@ +r""" +==================================================== +Quasi-Monte Carlo submodule (:mod:`scipy.stats.qmc`) +==================================================== + +.. currentmodule:: scipy.stats.qmc + +This module provides Quasi-Monte Carlo generators and associated helper +functions. + + +Quasi-Monte Carlo +================= + +Engines +------- + +.. autosummary:: + :toctree: generated/ + + QMCEngine + Sobol + Halton + LatinHypercube + PoissonDisk + MultinomialQMC + MultivariateNormalQMC + +Helpers +------- + +.. autosummary:: + :toctree: generated/ + + discrepancy + geometric_discrepancy + update_discrepancy + scale + + +Introduction to Quasi-Monte Carlo +================================= + +Quasi-Monte Carlo (QMC) methods [1]_, [2]_, [3]_ provide an +:math:`n \times d` array of numbers in :math:`[0,1]`. They can be used in +place of :math:`n` points from the :math:`U[0,1]^{d}` distribution. Compared to +random points, QMC points are designed to have fewer gaps and clumps. This is +quantified by discrepancy measures [4]_. From the Koksma-Hlawka +inequality [5]_ we know that low discrepancy reduces a bound on +integration error. Averaging a function :math:`f` over :math:`n` QMC points +can achieve an integration error close to :math:`O(n^{-1})` for well +behaved functions [2]_. + +Most QMC constructions are designed for special values of :math:`n` +such as powers of 2 or large primes. Changing the sample +size by even one can degrade their performance, even their +rate of convergence [6]_. For instance :math:`n=100` points may give less +accuracy than :math:`n=64` if the method was designed for :math:`n=2^m`. + +Some QMC constructions are extensible in :math:`n`: we can find +another special sample size :math:`n' > n` and often an infinite +sequence of increasing special sample sizes. Some QMC +constructions are extensible in :math:`d`: we can increase the dimension, +possibly to some upper bound, and typically without requiring +special values of :math:`d`. Some QMC methods are extensible in +both :math:`n` and :math:`d`. + +QMC points are deterministic. That makes it hard to estimate the accuracy of +integrals estimated by averages over QMC points. Randomized QMC (RQMC) [7]_ +points are constructed so that each point is individually :math:`U[0,1]^{d}` +while collectively the :math:`n` points retain their low discrepancy. +One can make :math:`R` independent replications of RQMC points to +see how stable a computation is. From :math:`R` independent values, +a t-test (or bootstrap t-test [8]_) then gives approximate confidence +intervals on the mean value. Some RQMC methods produce a +root mean squared error that is actually :math:`o(1/n)` and smaller than +the rate seen in unrandomized QMC. An intuitive explanation is +that the error is a sum of many small ones and random errors +cancel in a way that deterministic ones do not. RQMC also +has advantages on integrands that are singular or, for other +reasons, fail to be Riemann integrable. + +(R)QMC cannot beat Bahkvalov's curse of dimension (see [9]_). For +any random or deterministic method, there are worst case functions +that will give it poor performance in high dimensions. A worst +case function for QMC might be 0 at all n points but very +large elsewhere. Worst case analyses get very pessimistic +in high dimensions. (R)QMC can bring a great improvement over +MC when the functions on which it is used are not worst case. +For instance (R)QMC can be especially effective on integrands +that are well approximated by sums of functions of +some small number of their input variables at a time [10]_, [11]_. +That property is often a surprising finding about those functions. + +Also, to see an improvement over IID MC, (R)QMC requires a bit of smoothness of +the integrand, roughly the mixed first order derivative in each direction, +:math:`\partial^d f/\partial x_1 \cdots \partial x_d`, must be integral. +For instance, a function that is 1 inside the hypersphere and 0 outside of it +has infinite variation in the sense of Hardy and Krause for any dimension +:math:`d = 2`. + +Scrambled nets are a kind of RQMC that have some valuable robustness +properties [12]_. If the integrand is square integrable, they give variance +:math:`var_{SNET} = o(1/n)`. There is a finite upper bound on +:math:`var_{SNET} / var_{MC}` that holds simultaneously for every square +integrable integrand. Scrambled nets satisfy a strong law of large numbers +for :math:`f` in :math:`L^p` when :math:`p>1`. In some +special cases there is a central limit theorem [13]_. For smooth enough +integrands they can achieve RMSE nearly :math:`O(n^{-3})`. See [12]_ +for references about these properties. + +The main kinds of QMC methods are lattice rules [14]_ and digital +nets and sequences [2]_, [15]_. The theories meet up in polynomial +lattice rules [16]_ which can produce digital nets. Lattice rules +require some form of search for good constructions. For digital +nets there are widely used default constructions. + +The most widely used QMC methods are Sobol' sequences [17]_. +These are digital nets. They are extensible in both :math:`n` and :math:`d`. +They can be scrambled. The special sample sizes are powers +of 2. Another popular method are Halton sequences [18]_. +The constructions resemble those of digital nets. The earlier +dimensions have much better equidistribution properties than +later ones. There are essentially no special sample sizes. +They are not thought to be as accurate as Sobol' sequences. +They can be scrambled. The nets of Faure [19]_ are also widely +used. All dimensions are equally good, but the special sample +sizes grow rapidly with dimension :math:`d`. They can be scrambled. +The nets of Niederreiter and Xing [20]_ have the best asymptotic +properties but have not shown good empirical performance [21]_. + +Higher order digital nets are formed by a digit interleaving process +in the digits of the constructed points. They can achieve higher +levels of asymptotic accuracy given higher smoothness conditions on :math:`f` +and they can be scrambled [22]_. There is little or no empirical work +showing the improved rate to be attained. + +Using QMC is like using the entire period of a small random +number generator. The constructions are similar and so +therefore are the computational costs [23]_. + +(R)QMC is sometimes improved by passing the points through +a baker's transformation (tent function) prior to using them. +That function has the form :math:`1-2|x-1/2|`. As :math:`x` goes from 0 to +1, this function goes from 0 to 1 and then back. It is very +useful to produce a periodic function for lattice rules [14]_, +and sometimes it improves the convergence rate [24]_. + +It is not straightforward to apply QMC methods to Markov +chain Monte Carlo (MCMC). We can think of MCMC as using +:math:`n=1` point in :math:`[0,1]^{d}` for very large :math:`d`, with +ergodic results corresponding to :math:`d \to \infty`. One proposal is +in [25]_ and under strong conditions an improved rate of convergence +has been shown [26]_. + +Returning to Sobol' points: there are many versions depending +on what are called direction numbers. Those are the result of +searches and are tabulated. A very widely used set of direction +numbers come from [27]_. It is extensible in dimension up to +:math:`d=21201`. + +References +---------- +.. [1] Owen, Art B. "Monte Carlo Book: the Quasi-Monte Carlo parts." 2019. +.. [2] Niederreiter, Harald. "Random number generation and quasi-Monte Carlo + methods." Society for Industrial and Applied Mathematics, 1992. +.. [3] Dick, Josef, Frances Y. Kuo, and Ian H. Sloan. "High-dimensional + integration: the quasi-Monte Carlo way." Acta Numerica no. 22: 133, 2013. +.. [4] Aho, A. V., C. Aistleitner, T. Anderson, K. Appel, V. Arnol'd, N. + Aronszajn, D. Asotsky et al. "W. Chen et al.(eds.), "A Panorama of + Discrepancy Theory", Sringer International Publishing, + Switzerland: 679, 2014. +.. [5] Hickernell, Fred J. "Koksma-Hlawka Inequality." Wiley StatsRef: + Statistics Reference Online, 2014. +.. [6] Owen, Art B. "On dropping the first Sobol' point." :arxiv:`2008.08051`, + 2020. +.. [7] L'Ecuyer, Pierre, and Christiane Lemieux. "Recent advances in randomized + quasi-Monte Carlo methods." In Modeling uncertainty, pp. 419-474. Springer, + New York, NY, 2002. +.. [8] DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence + intervals." Statistical science: 189-212, 1996. +.. [9] Dimov, Ivan T. "Monte Carlo methods for applied scientists." World + Scientific, 2008. +.. [10] Caflisch, Russel E., William J. Morokoff, and Art B. Owen. "Valuation + of mortgage backed securities using Brownian bridges to reduce effective + dimension." Journal of Computational Finance: no. 1 27-46, 1997. +.. [11] Sloan, Ian H., and Henryk Wozniakowski. "When are quasi-Monte Carlo + algorithms efficient for high dimensional integrals?." Journal of Complexity + 14, no. 1 (1998): 1-33. +.. [12] Owen, Art B., and Daniel Rudolf, "A strong law of large numbers for + scrambled net integration." SIAM Review, to appear. +.. [13] Loh, Wei-Liem. "On the asymptotic distribution of scrambled net + quadrature." The Annals of Statistics 31, no. 4: 1282-1324, 2003. +.. [14] Sloan, Ian H. and S. Joe. "Lattice methods for multiple integration." + Oxford University Press, 1994. +.. [15] Dick, Josef, and Friedrich Pillichshammer. "Digital nets and sequences: + discrepancy theory and quasi-Monte Carlo integration." Cambridge University + Press, 2010. +.. [16] Dick, Josef, F. Kuo, Friedrich Pillichshammer, and I. Sloan. + "Construction algorithms for polynomial lattice rules for multivariate + integration." Mathematics of computation 74, no. 252: 1895-1921, 2005. +.. [17] Sobol', Il'ya Meerovich. "On the distribution of points in a cube and + the approximate evaluation of integrals." Zhurnal Vychislitel'noi Matematiki + i Matematicheskoi Fiziki 7, no. 4: 784-802, 1967. +.. [18] Halton, John H. "On the efficiency of certain quasi-random sequences of + points in evaluating multi-dimensional integrals." Numerische Mathematik 2, + no. 1: 84-90, 1960. +.. [19] Faure, Henri. "Discrepance de suites associees a un systeme de + numeration (en dimension s)." Acta arithmetica 41, no. 4: 337-351, 1982. +.. [20] Niederreiter, Harold, and Chaoping Xing. "Low-discrepancy sequences and + global function fields with many rational places." Finite Fields and their + applications 2, no. 3: 241-273, 1996. +.. [21] Hong, Hee Sun, and Fred J. Hickernell. "Algorithm 823: Implementing + scrambled digital sequences." ACM Transactions on Mathematical Software + (TOMS) 29, no. 2: 95-109, 2003. +.. [22] Dick, Josef. "Higher order scrambled digital nets achieve the optimal + rate of the root mean square error for smooth integrands." The Annals of + Statistics 39, no. 3: 1372-1398, 2011. +.. [23] Niederreiter, Harald. "Multidimensional numerical integration using + pseudorandom numbers." In Stochastic Programming 84 Part I, pp. 17-38. + Springer, Berlin, Heidelberg, 1986. +.. [24] Hickernell, Fred J. "Obtaining O (N-2+e) Convergence for Lattice + Quadrature Rules." In Monte Carlo and Quasi-Monte Carlo Methods 2000, + pp. 274-289. Springer, Berlin, Heidelberg, 2002. +.. [25] Owen, Art B., and Seth D. Tribble. "A quasi-Monte Carlo Metropolis + algorithm." Proceedings of the National Academy of Sciences 102, + no. 25: 8844-8849, 2005. +.. [26] Chen, Su. "Consistency and convergence rate of Markov chain quasi Monte + Carlo with examples." PhD diss., Stanford University, 2011. +.. [27] Joe, Stephen, and Frances Y. Kuo. "Constructing Sobol sequences with + better two-dimensional projections." SIAM Journal on Scientific Computing + 30, no. 5: 2635-2654, 2008. + +""" +from ._qmc import * # noqa: F403 +from ._qmc import __all__ # noqa: F401 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/sampling.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..12174d9dfb3cb93fa33811ed4b5d233817512e36 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/sampling.py @@ -0,0 +1,73 @@ +""" +====================================================== +Random Number Generators (:mod:`scipy.stats.sampling`) +====================================================== + +.. currentmodule:: scipy.stats.sampling + +This module contains a collection of random number generators to sample +from univariate continuous and discrete distributions. It uses the +implementation of a C library called "UNU.RAN". The only exception is +RatioUniforms, which is a pure Python implementation of the +Ratio-of-Uniforms method. + +Generators Wrapped +================== + +For continuous distributions +---------------------------- + +.. autosummary:: + :toctree: generated/ + + NumericalInverseHermite + NumericalInversePolynomial + TransformedDensityRejection + SimpleRatioUniforms + RatioUniforms + +For discrete distributions +-------------------------- + +.. autosummary:: + :toctree: generated/ + + DiscreteAliasUrn + DiscreteGuideTable + +Warnings / Errors used in :mod:`scipy.stats.sampling` +----------------------------------------------------- + +.. autosummary:: + :toctree: generated/ + + UNURANError + + +Generators for pre-defined distributions +======================================== + +To easily apply the above methods for some of the continuous distributions +in :mod:`scipy.stats`, the following functionality can be used: + +.. autosummary:: + :toctree: generated/ + + FastGeneratorInversion + +""" +from ._sampling import FastGeneratorInversion, RatioUniforms # noqa: F401 +from ._unuran.unuran_wrapper import ( # noqa: F401 + TransformedDensityRejection, + DiscreteAliasUrn, + DiscreteGuideTable, + NumericalInversePolynomial, + NumericalInverseHermite, + SimpleRatioUniforms, + UNURANError +) + +__all__ = ["NumericalInverseHermite", "NumericalInversePolynomial", + "TransformedDensityRejection", "SimpleRatioUniforms", + "RatioUniforms", "DiscreteAliasUrn", "DiscreteGuideTable", + "UNURANError", "FastGeneratorInversion"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/stats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d278e209ce8d487235ee281620af8520d76d87 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/stats.py @@ -0,0 +1,41 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.stats` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar', + 'tmin', 'tmax', 'tstd', 'tsem', 'moment', + 'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest', + 'normaltest', 'jarque_bera', + 'scoreatpercentile', 'percentileofscore', + 'cumfreq', 'relfreq', 'obrientransform', + 'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd', + 'median_abs_deviation', + 'sigmaclip', 'trimboth', 'trim1', 'trim_mean', + 'f_oneway', + 'pearsonr', 'fisher_exact', + 'spearmanr', 'pointbiserialr', + 'kendalltau', 'weightedtau', 'multiscale_graphcorr', + 'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp', + 'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel', + 'kstest', 'ks_1samp', 'ks_2samp', + 'chisquare', 'power_divergence', + 'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare', + 'rankdata', + 'combine_pvalues', 'wasserstein_distance', 'energy_distance', + 'brunnermunzel', 'alexandergovern', 'distributions', + 'mstats_basic', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="stats", module="stats", + private_modules=["_stats_py", "_mgc"], all=__all__, + attribute=name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/common_tests.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/common_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e5619318bce180357be0c0cd7a93b83edf8523 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/common_tests.py @@ -0,0 +1,354 @@ +import pickle + +import numpy as np +import numpy.testing as npt +from numpy.testing import assert_allclose, assert_equal +from pytest import raises as assert_raises + +import numpy.ma.testutils as ma_npt + +from scipy._lib._util import ( + getfullargspec_no_self as _getfullargspec, np_long +) +from scipy._lib._array_api_no_0d import xp_assert_equal +from scipy import stats + + +def check_named_results(res, attributes, ma=False, xp=None): + for i, attr in enumerate(attributes): + if ma: + ma_npt.assert_equal(res[i], getattr(res, attr)) + elif xp is not None: + xp_assert_equal(res[i], getattr(res, attr)) + else: + npt.assert_equal(res[i], getattr(res, attr)) + + +def check_normalization(distfn, args, distname): + norm_moment = distfn.moment(0, *args) + npt.assert_allclose(norm_moment, 1.0) + + if distname == "rv_histogram_instance": + atol, rtol = 1e-5, 0 + else: + atol, rtol = 1e-7, 1e-7 + + normalization_expect = distfn.expect(lambda x: 1, args=args) + npt.assert_allclose(normalization_expect, 1.0, atol=atol, rtol=rtol, + err_msg=distname, verbose=True) + + _a, _b = distfn.support(*args) + normalization_cdf = distfn.cdf(_b, *args) + npt.assert_allclose(normalization_cdf, 1.0) + + +def check_moment(distfn, arg, m, v, msg): + m1 = distfn.moment(1, *arg) + m2 = distfn.moment(2, *arg) + if not np.isinf(m): + npt.assert_almost_equal(m1, m, decimal=10, + err_msg=msg + ' - 1st moment') + else: # or np.isnan(m1), + npt.assert_(np.isinf(m1), + msg + f' - 1st moment -infinite, m1={str(m1)}') + + if not np.isinf(v): + npt.assert_almost_equal(m2 - m1 * m1, v, decimal=10, + err_msg=msg + ' - 2ndt moment') + else: # or np.isnan(m2), + npt.assert_(np.isinf(m2), msg + f' - 2nd moment -infinite, {m2=}') + + +def check_mean_expect(distfn, arg, m, msg): + if np.isfinite(m): + m1 = distfn.expect(lambda x: x, arg) + npt.assert_almost_equal(m1, m, decimal=5, + err_msg=msg + ' - 1st moment (expect)') + + +def check_var_expect(distfn, arg, m, v, msg): + dist_looser_tolerances = {"rv_histogram_instance" , "ksone"} + kwargs = {'rtol': 5e-6} if msg in dist_looser_tolerances else {} + if np.isfinite(v): + m2 = distfn.expect(lambda x: x*x, arg) + npt.assert_allclose(m2, v + m*m, **kwargs) + + +def check_skew_expect(distfn, arg, m, v, s, msg): + if np.isfinite(s): + m3e = distfn.expect(lambda x: np.power(x-m, 3), arg) + npt.assert_almost_equal(m3e, s * np.power(v, 1.5), + decimal=5, err_msg=msg + ' - skew') + else: + npt.assert_(np.isnan(s)) + + +def check_kurt_expect(distfn, arg, m, v, k, msg): + if np.isfinite(k): + m4e = distfn.expect(lambda x: np.power(x-m, 4), arg) + npt.assert_allclose(m4e, (k + 3.) * np.power(v, 2), + atol=1e-5, rtol=1e-5, + err_msg=msg + ' - kurtosis') + elif not np.isposinf(k): + npt.assert_(np.isnan(k)) + + +def check_munp_expect(dist, args, msg): + # If _munp is overridden, test a higher moment. (Before gh-18634, some + # distributions had issues with moments 5 and higher.) + if dist._munp.__func__ != stats.rv_continuous._munp: + res = dist.moment(5, *args) # shouldn't raise an error + ref = dist.expect(lambda x: x ** 5, args, lb=-np.inf, ub=np.inf) + if not np.isfinite(res): # could be valid; automated test can't know + return + # loose tolerance, mostly to see whether _munp returns *something* + assert_allclose(res, ref, atol=1e-10, rtol=1e-4, + err_msg=msg + ' - higher moment / _munp') + + +def check_entropy(distfn, arg, msg): + ent = distfn.entropy(*arg) + npt.assert_(not np.isnan(ent), msg + 'test Entropy is nan') + + +def check_private_entropy(distfn, args, superclass): + # compare a generic _entropy with the distribution-specific implementation + npt.assert_allclose(distfn._entropy(*args), + superclass._entropy(distfn, *args)) + + +def check_entropy_vect_scale(distfn, arg): + # check 2-d + sc = np.asarray([[1, 2], [3, 4]]) + v_ent = distfn.entropy(*arg, scale=sc) + s_ent = [distfn.entropy(*arg, scale=s) for s in sc.ravel()] + s_ent = np.asarray(s_ent).reshape(v_ent.shape) + assert_allclose(v_ent, s_ent, atol=1e-14) + + # check invalid value, check cast + sc = [1, 2, -3] + v_ent = distfn.entropy(*arg, scale=sc) + s_ent = [distfn.entropy(*arg, scale=s) for s in sc] + s_ent = np.asarray(s_ent).reshape(v_ent.shape) + assert_allclose(v_ent, s_ent, atol=1e-14) + + +def check_edge_support(distfn, args): + # Make sure that x=self.a and self.b are handled correctly. + x = distfn.support(*args) + if isinstance(distfn, stats.rv_discrete): + x = x[0]-1, x[1] + + npt.assert_equal(distfn.cdf(x, *args), [0.0, 1.0]) + npt.assert_equal(distfn.sf(x, *args), [1.0, 0.0]) + + if distfn.name not in ('skellam', 'dlaplace'): + # with a = -inf, log(0) generates warnings + npt.assert_equal(distfn.logcdf(x, *args), [-np.inf, 0.0]) + npt.assert_equal(distfn.logsf(x, *args), [0.0, -np.inf]) + + npt.assert_equal(distfn.ppf([0.0, 1.0], *args), x) + npt.assert_equal(distfn.isf([0.0, 1.0], *args), x[::-1]) + + # out-of-bounds for isf & ppf + npt.assert_(np.isnan(distfn.isf([-1, 2], *args)).all()) + npt.assert_(np.isnan(distfn.ppf([-1, 2], *args)).all()) + + +def check_named_args(distfn, x, shape_args, defaults, meths): + ## Check calling w/ named arguments. + + # check consistency of shapes, numargs and _parse signature + signature = _getfullargspec(distfn._parse_args) + npt.assert_(signature.varargs is None) + npt.assert_(signature.varkw is None) + npt.assert_(not signature.kwonlyargs) + npt.assert_(list(signature.defaults) == list(defaults)) + + shape_argnames = signature.args[:-len(defaults)] # a, b, loc=0, scale=1 + if distfn.shapes: + shapes_ = distfn.shapes.replace(',', ' ').split() + else: + shapes_ = '' + npt.assert_(len(shapes_) == distfn.numargs) + npt.assert_(len(shapes_) == len(shape_argnames)) + + # check calling w/ named arguments + shape_args = list(shape_args) + + vals = [meth(x, *shape_args) for meth in meths] + npt.assert_(np.all(np.isfinite(vals))) + + names, a, k = shape_argnames[:], shape_args[:], {} + while names: + k.update({names.pop(): a.pop()}) + v = [meth(x, *a, **k) for meth in meths] + npt.assert_array_equal(vals, v) + if 'n' not in k.keys(): + # `n` is first parameter of moment(), so can't be used as named arg + npt.assert_equal(distfn.moment(1, *a, **k), + distfn.moment(1, *shape_args)) + + # unknown arguments should not go through: + k.update({'kaboom': 42}) + assert_raises(TypeError, distfn.cdf, x, **k) + + +def check_random_state_property(distfn, args): + # check the random_state attribute of a distribution *instance* + + # This test fiddles with distfn.random_state. This breaks other tests, + # hence need to save it and then restore. + rndm = distfn.random_state + + # baseline: this relies on the global state + np.random.seed(1234) + distfn.random_state = None + r0 = distfn.rvs(*args, size=8) + + # use an explicit instance-level random_state + distfn.random_state = 1234 + r1 = distfn.rvs(*args, size=8) + npt.assert_equal(r0, r1) + + distfn.random_state = np.random.RandomState(1234) + r2 = distfn.rvs(*args, size=8) + npt.assert_equal(r0, r2) + + # check that np.random.Generator can be used (numpy >= 1.17) + if hasattr(np.random, 'default_rng'): + # obtain a np.random.Generator object + rng = np.random.default_rng(1234) + distfn.rvs(*args, size=1, random_state=rng) + + # can override the instance-level random_state for an individual .rvs call + distfn.random_state = 2 + orig_state = distfn.random_state.get_state() + + r3 = distfn.rvs(*args, size=8, random_state=np.random.RandomState(1234)) + npt.assert_equal(r0, r3) + + # ... and that does not alter the instance-level random_state! + npt.assert_equal(distfn.random_state.get_state(), orig_state) + + # finally, restore the random_state + distfn.random_state = rndm + + +def check_meth_dtype(distfn, arg, meths): + q0 = [0.25, 0.5, 0.75] + x0 = distfn.ppf(q0, *arg) + x_cast = [x0.astype(tp) for tp in (np_long, np.float16, np.float32, + np.float64)] + + for x in x_cast: + # casting may have clipped the values, exclude those + distfn._argcheck(*arg) + x = x[(distfn.a < x) & (x < distfn.b)] + for meth in meths: + val = meth(x, *arg) + npt.assert_(val.dtype == np.float64) + + +def check_ppf_dtype(distfn, arg): + q0 = np.asarray([0.25, 0.5, 0.75]) + q_cast = [q0.astype(tp) for tp in (np.float16, np.float32, np.float64)] + for q in q_cast: + for meth in [distfn.ppf, distfn.isf]: + val = meth(q, *arg) + npt.assert_(val.dtype == np.float64) + + +def check_cmplx_deriv(distfn, arg): + # Distributions allow complex arguments. + def deriv(f, x, *arg): + x = np.asarray(x) + h = 1e-10 + return (f(x + h*1j, *arg)/h).imag + + x0 = distfn.ppf([0.25, 0.51, 0.75], *arg) + x_cast = [x0.astype(tp) for tp in (np_long, np.float16, np.float32, + np.float64)] + + for x in x_cast: + # casting may have clipped the values, exclude those + distfn._argcheck(*arg) + x = x[(distfn.a < x) & (x < distfn.b)] + + pdf, cdf, sf = distfn.pdf(x, *arg), distfn.cdf(x, *arg), distfn.sf(x, *arg) + assert_allclose(deriv(distfn.cdf, x, *arg), pdf, rtol=1e-5) + assert_allclose(deriv(distfn.logcdf, x, *arg), pdf/cdf, rtol=1e-5) + + assert_allclose(deriv(distfn.sf, x, *arg), -pdf, rtol=1e-5) + assert_allclose(deriv(distfn.logsf, x, *arg), -pdf/sf, rtol=1e-5) + + assert_allclose(deriv(distfn.logpdf, x, *arg), + deriv(distfn.pdf, x, *arg) / distfn.pdf(x, *arg), + rtol=1e-5) + + +def check_pickling(distfn, args): + # check that a distribution instance pickles and unpickles + # pay special attention to the random_state property + + # save the random_state (restore later) + rndm = distfn.random_state + + # check unfrozen + distfn.random_state = 1234 + distfn.rvs(*args, size=8) + s = pickle.dumps(distfn) + r0 = distfn.rvs(*args, size=8) + + unpickled = pickle.loads(s) + r1 = unpickled.rvs(*args, size=8) + npt.assert_equal(r0, r1) + + # also smoke test some methods + medians = [distfn.ppf(0.5, *args), unpickled.ppf(0.5, *args)] + npt.assert_equal(medians[0], medians[1]) + npt.assert_equal(distfn.cdf(medians[0], *args), + unpickled.cdf(medians[1], *args)) + + # check frozen pickling/unpickling with rvs + frozen_dist = distfn(*args) + pkl = pickle.dumps(frozen_dist) + unpickled = pickle.loads(pkl) + + r0 = frozen_dist.rvs(size=8) + r1 = unpickled.rvs(size=8) + npt.assert_equal(r0, r1) + + # check pickling/unpickling of .fit method + if hasattr(distfn, "fit"): + fit_function = distfn.fit + pickled_fit_function = pickle.dumps(fit_function) + unpickled_fit_function = pickle.loads(pickled_fit_function) + assert fit_function.__name__ == unpickled_fit_function.__name__ == "fit" + + # restore the random_state + distfn.random_state = rndm + + +def check_freezing(distfn, args): + # regression test for gh-11089: freezing a distribution fails + # if loc and/or scale are specified + if isinstance(distfn, stats.rv_continuous): + locscale = {'loc': 1, 'scale': 2} + else: + locscale = {'loc': 1} + + rv = distfn(*args, **locscale) + assert rv.a == distfn(*args).a + assert rv.b == distfn(*args).b + + +def check_rvs_broadcast(distfunc, distname, allargs, shape, shape_only, otype): + np.random.seed(123) + sample = distfunc.rvs(*allargs) + assert_equal(sample.shape, shape, f"{distname}: rvs failed to broadcast") + if not shape_only: + rvs = np.vectorize(lambda *allargs: distfunc.rvs(*allargs), otypes=otype) + np.random.seed(123) + expected = rvs(*allargs) + assert_allclose(sample, expected, rtol=1e-13) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/_mvt.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/_mvt.py new file mode 100644 index 0000000000000000000000000000000000000000..c346d0daded4b6e734718742cc8950b84ed333f7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/_mvt.py @@ -0,0 +1,171 @@ +import math +import numpy as np +from scipy import special +from scipy.stats._qmc import primes_from_2_to + + +def _primes(n): + # Defined to facilitate comparison between translation and source + # In Matlab, primes(10.5) -> first four primes, primes(11.5) -> first five + return primes_from_2_to(math.ceil(n)) + + +def _gaminv(a, b): + # Defined to facilitate comparison between translation and source + # Matlab's `gaminv` is like `special.gammaincinv` but args are reversed + return special.gammaincinv(b, a) + + +def _qsimvtv(m, nu, sigma, a, b, rng): + """Estimates the multivariate t CDF using randomized QMC + + Parameters + ---------- + m : int + The number of points + nu : float + Degrees of freedom + sigma : ndarray + A 2D positive semidefinite covariance matrix + a : ndarray + Lower integration limits + b : ndarray + Upper integration limits. + rng : Generator + Pseudorandom number generator + + Returns + ------- + p : float + The estimated CDF. + e : float + An absolute error estimate. + + """ + # _qsimvtv is a Python translation of the Matlab function qsimvtv, + # semicolons and all. + # + # This function uses an algorithm given in the paper + # "Comparison of Methods for the Numerical Computation of + # Multivariate t Probabilities", in + # J. of Computational and Graphical Stat., 11(2002), pp. 950-971, by + # Alan Genz and Frank Bretz + # + # The primary references for the numerical integration are + # "On a Number-Theoretical Integration Method" + # H. Niederreiter, Aequationes Mathematicae, 8(1972), pp. 304-11. + # and + # "Randomization of Number Theoretic Methods for Multiple Integration" + # R. Cranley & T.N.L. Patterson, SIAM J Numer Anal, 13(1976), pp. 904-14. + # + # Alan Genz is the author of this function and following Matlab functions. + # Alan Genz, WSU Math, PO Box 643113, Pullman, WA 99164-3113 + # Email : alangenz@wsu.edu + # + # Copyright (C) 2013, Alan Genz, All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided the following conditions are met: + # 1. Redistributions of source code must retain the above copyright + # notice, this list of conditions and the following disclaimer. + # 2. Redistributions in binary form must reproduce the above copyright + # notice, this list of conditions and the following disclaimer in + # the documentation and/or other materials provided with the + # distribution. + # 3. The contributor name(s) may not be used to endorse or promote + # products derived from this software without specific prior + # written permission. + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF USE + # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + # Initialization + sn = max(1, math.sqrt(nu)); ch, az, bz = _chlrps(sigma, a/sn, b/sn) + n = len(sigma); N = 10; P = math.ceil(m/N); on = np.ones(P); p = 0; e = 0 + ps = np.sqrt(_primes(5*n*math.log(n+4)/4)); q = ps[:, np.newaxis] # Richtmyer gens. + + # Randomization loop for ns samples + c = None; dc = None + for S in range(N): + vp = on.copy(); s = np.zeros((n, P)) + for i in range(n): + x = np.abs(2*np.mod(q[i]*np.arange(1, P+1) + rng.random(), 1)-1) # periodizing transform + if i == 0: + r = on + if nu > 0: + r = np.sqrt(2*_gaminv(x, nu/2)) + else: + y = _Phinv(c + x*dc) + s[i:] += ch[i:, i-1:i] * y + si = s[i, :]; c = on.copy(); ai = az[i]*r - si; d = on.copy(); bi = bz[i]*r - si + c[ai <= -9] = 0; tl = abs(ai) < 9; c[tl] = _Phi(ai[tl]) + d[bi <= -9] = 0; tl = abs(bi) < 9; d[tl] = _Phi(bi[tl]) + dc = d - c; vp = vp * dc + d = (np.mean(vp) - p)/(S + 1); p = p + d; e = (S - 1)*e/(S + 1) + d**2 + e = math.sqrt(e) # error estimate is 3 times std error with N samples. + return p, e + + +# Standard statistical normal distribution functions +def _Phi(z): + return special.ndtr(z) + + +def _Phinv(p): + return special.ndtri(p) + + +def _chlrps(R, a, b): + """ + Computes permuted and scaled lower Cholesky factor c for R which may be + singular, also permuting and scaling integration limit vectors a and b. + """ + ep = 1e-10 # singularity tolerance + eps = np.finfo(R.dtype).eps + + n = len(R); c = R.copy(); ap = a.copy(); bp = b.copy(); d = np.sqrt(np.maximum(np.diag(c), 0)) + for i in range(n): + if d[i] > 0: + c[:, i] /= d[i]; c[i, :] /= d[i] + ap[i] /= d[i]; bp[i] /= d[i] + y = np.zeros((n, 1)); sqtp = math.sqrt(2*math.pi) + + for k in range(n): + im = k; ckk = 0; dem = 1; s = 0 + for i in range(k, n): + if c[i, i] > eps: + cii = math.sqrt(max(c[i, i], 0)) + if i > 0: s = c[i, :k] @ y[:k] + ai = (ap[i]-s)/cii; bi = (bp[i]-s)/cii; de = _Phi(bi)-_Phi(ai) + if de <= dem: + ckk = cii; dem = de; am = ai; bm = bi; im = i + if im > k: + ap[[im, k]] = ap[[k, im]]; bp[[im, k]] = bp[[k, im]]; c[im, im] = c[k, k] + t = c[im, :k].copy(); c[im, :k] = c[k, :k]; c[k, :k] = t + t = c[im+1:, im].copy(); c[im+1:, im] = c[im+1:, k]; c[im+1:, k] = t + t = c[k+1:im, k].copy(); c[k+1:im, k] = c[im, k+1:im].T; c[im, k+1:im] = t.T + if ckk > ep*(k+1): + c[k, k] = ckk; c[k, k+1:] = 0 + for i in range(k+1, n): + c[i, k] = c[i, k]/ckk; c[i, k+1:i+1] = c[i, k+1:i+1] - c[i, k]*c[k+1:i+1, k].T + if abs(dem) > ep: + y[k] = (np.exp(-am**2/2) - np.exp(-bm**2/2)) / (sqtp*dem) + else: + y[k] = (am + bm) / 2 + if am < -10: + y[k] = bm + elif bm > 10: + y[k] = am + c[k, :k+1] /= ckk; ap[k] /= ckk; bp[k] /= ckk + else: + c[k:, k] = 0; y[k] = (ap[k] + bp[k])/2 + pass + return c, ap, bp diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/fisher_exact_results_from_r.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/fisher_exact_results_from_r.py new file mode 100644 index 0000000000000000000000000000000000000000..b7dd8936018eae2f74cc6f5966235a86fa821793 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/fisher_exact_results_from_r.py @@ -0,0 +1,607 @@ +# DO NOT EDIT THIS FILE! +# This file was generated by the R script +# generate_fisher_exact_results_from_r.R +# The script was run with R version 3.6.2 (2019-12-12) at 2020-11-09 06:16:09 + + +from collections import namedtuple +import numpy as np + + +Inf = np.inf + +Parameters = namedtuple('Parameters', + ['table', 'confidence_level', 'alternative']) +RResults = namedtuple('RResults', + ['pvalue', 'conditional_odds_ratio', + 'conditional_odds_ratio_ci']) +data = [ + (Parameters(table=[[100, 2], [1000, 5]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.1300759363430016, + conditional_odds_ratio=0.25055839934223, + conditional_odds_ratio_ci=(0.04035202926536294, + 2.662846672960251))), + (Parameters(table=[[2, 7], [8, 2]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.02301413756522116, + conditional_odds_ratio=0.0858623513573622, + conditional_odds_ratio_ci=(0.004668988338943325, + 0.895792956493601))), + (Parameters(table=[[5, 1], [10, 10]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.1973244147157191, + conditional_odds_ratio=4.725646047336587, + conditional_odds_ratio_ci=(0.4153910882532168, + 259.2593661129417))), + (Parameters(table=[[5, 15], [20, 20]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.09580440012477633, + conditional_odds_ratio=0.3394396617440851, + conditional_odds_ratio_ci=(0.08056337526385809, + 1.22704788545557))), + (Parameters(table=[[5, 16], [16, 25]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.2697004098849359, + conditional_odds_ratio=0.4937791394540491, + conditional_odds_ratio_ci=(0.1176691231650079, + 1.787463657995973))), + (Parameters(table=[[10, 5], [10, 1]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.1973244147157192, + conditional_odds_ratio=0.2116112781158479, + conditional_odds_ratio_ci=(0.003857141267422399, + 2.407369893767229))), + (Parameters(table=[[10, 5], [10, 0]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.06126482213438735, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 1.451643573543705))), + (Parameters(table=[[5, 0], [1, 4]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.04761904761904762, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(1.024822256141754, + Inf))), + (Parameters(table=[[0, 5], [1, 4]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 39.00054996869288))), + (Parameters(table=[[5, 1], [0, 4]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.04761904761904761, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(1.024822256141754, + Inf))), + (Parameters(table=[[0, 1], [3, 2]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 39.00054996869287))), + (Parameters(table=[[200, 7], [8, 300]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=2.005657880389071e-122, + conditional_odds_ratio=977.7866978606228, + conditional_odds_ratio_ci=(349.2595113327733, + 3630.382605689872))), + (Parameters(table=[[28, 21], [6, 1957]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=5.728437460831947e-44, + conditional_odds_ratio=425.2403028434684, + conditional_odds_ratio_ci=(152.4166024390096, + 1425.700792178893))), + (Parameters(table=[[190, 800], [200, 900]], + confidence_level=0.95, + alternative='two.sided'), + RResults(pvalue=0.574111858126088, + conditional_odds_ratio=1.068697577856801, + conditional_odds_ratio_ci=(0.8520462587912048, + 1.340148950273938))), + (Parameters(table=[[100, 2], [1000, 5]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.1300759363430016, + conditional_odds_ratio=0.25055839934223, + conditional_odds_ratio_ci=(0.02502345007115455, + 6.304424772117853))), + (Parameters(table=[[2, 7], [8, 2]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.02301413756522116, + conditional_odds_ratio=0.0858623513573622, + conditional_odds_ratio_ci=(0.001923034001462487, + 1.53670836950172))), + (Parameters(table=[[5, 1], [10, 10]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.1973244147157191, + conditional_odds_ratio=4.725646047336587, + conditional_odds_ratio_ci=(0.2397970951413721, + 1291.342011095509))), + (Parameters(table=[[5, 15], [20, 20]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.09580440012477633, + conditional_odds_ratio=0.3394396617440851, + conditional_odds_ratio_ci=(0.05127576113762925, + 1.717176678806983))), + (Parameters(table=[[5, 16], [16, 25]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.2697004098849359, + conditional_odds_ratio=0.4937791394540491, + conditional_odds_ratio_ci=(0.07498546954483619, + 2.506969905199901))), + (Parameters(table=[[10, 5], [10, 1]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.1973244147157192, + conditional_odds_ratio=0.2116112781158479, + conditional_odds_ratio_ci=(0.0007743881879531337, + 4.170192301163831))), + (Parameters(table=[[10, 5], [10, 0]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.06126482213438735, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 2.642491011905582))), + (Parameters(table=[[5, 0], [1, 4]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.04761904761904762, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0.496935393325443, + Inf))), + (Parameters(table=[[0, 5], [1, 4]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 198.019801980198))), + (Parameters(table=[[5, 1], [0, 4]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.04761904761904761, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0.496935393325443, + Inf))), + (Parameters(table=[[0, 1], [3, 2]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 198.019801980198))), + (Parameters(table=[[200, 7], [8, 300]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=2.005657880389071e-122, + conditional_odds_ratio=977.7866978606228, + conditional_odds_ratio_ci=(270.0334165523604, + 5461.333333326708))), + (Parameters(table=[[28, 21], [6, 1957]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=5.728437460831947e-44, + conditional_odds_ratio=425.2403028434684, + conditional_odds_ratio_ci=(116.7944750275836, + 1931.995993191814))), + (Parameters(table=[[190, 800], [200, 900]], + confidence_level=0.99, + alternative='two.sided'), + RResults(pvalue=0.574111858126088, + conditional_odds_ratio=1.068697577856801, + conditional_odds_ratio_ci=(0.7949398282935892, + 1.436229679394333))), + (Parameters(table=[[100, 2], [1000, 5]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.1300759363430016, + conditional_odds_ratio=0.25055839934223, + conditional_odds_ratio_ci=(0, + 1.797867027270803))), + (Parameters(table=[[2, 7], [8, 2]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.0185217259520665, + conditional_odds_ratio=0.0858623513573622, + conditional_odds_ratio_ci=(0, + 0.6785254803404526))), + (Parameters(table=[[5, 1], [10, 10]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.9782608695652173, + conditional_odds_ratio=4.725646047336587, + conditional_odds_ratio_ci=(0, + 127.8497388102893))), + (Parameters(table=[[5, 15], [20, 20]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.05625775074399956, + conditional_odds_ratio=0.3394396617440851, + conditional_odds_ratio_ci=(0, + 1.032332939718425))), + (Parameters(table=[[5, 16], [16, 25]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.1808979350599346, + conditional_odds_ratio=0.4937791394540491, + conditional_odds_ratio_ci=(0, + 1.502407513296985))), + (Parameters(table=[[10, 5], [10, 1]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.1652173913043479, + conditional_odds_ratio=0.2116112781158479, + conditional_odds_ratio_ci=(0, + 1.820421051562392))), + (Parameters(table=[[10, 5], [10, 0]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.0565217391304348, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 1.06224603077045))), + (Parameters(table=[[5, 0], [1, 4]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[0, 5], [1, 4]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.5, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 19.00192394479939))), + (Parameters(table=[[5, 1], [0, 4]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[0, 1], [3, 2]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.4999999999999999, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 19.00192394479939))), + (Parameters(table=[[200, 7], [8, 300]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=977.7866978606228, + conditional_odds_ratio_ci=(0, + 3045.460216525746))), + (Parameters(table=[[28, 21], [6, 1957]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=425.2403028434684, + conditional_odds_ratio_ci=(0, + 1186.440170942579))), + (Parameters(table=[[190, 800], [200, 900]], + confidence_level=0.95, + alternative='less'), + RResults(pvalue=0.7416227010368963, + conditional_odds_ratio=1.068697577856801, + conditional_odds_ratio_ci=(0, + 1.293551891610822))), + (Parameters(table=[[100, 2], [1000, 5]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.1300759363430016, + conditional_odds_ratio=0.25055839934223, + conditional_odds_ratio_ci=(0, + 4.375946050832565))), + (Parameters(table=[[2, 7], [8, 2]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.0185217259520665, + conditional_odds_ratio=0.0858623513573622, + conditional_odds_ratio_ci=(0, + 1.235282118191202))), + (Parameters(table=[[5, 1], [10, 10]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.9782608695652173, + conditional_odds_ratio=4.725646047336587, + conditional_odds_ratio_ci=(0, + 657.2063583945989))), + (Parameters(table=[[5, 15], [20, 20]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.05625775074399956, + conditional_odds_ratio=0.3394396617440851, + conditional_odds_ratio_ci=(0, + 1.498867660683128))), + (Parameters(table=[[5, 16], [16, 25]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.1808979350599346, + conditional_odds_ratio=0.4937791394540491, + conditional_odds_ratio_ci=(0, + 2.186159386716762))), + (Parameters(table=[[10, 5], [10, 1]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.1652173913043479, + conditional_odds_ratio=0.2116112781158479, + conditional_odds_ratio_ci=(0, + 3.335351451901569))), + (Parameters(table=[[10, 5], [10, 0]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.0565217391304348, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 2.075407697450433))), + (Parameters(table=[[5, 0], [1, 4]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[0, 5], [1, 4]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.5, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 99.00009507969122))), + (Parameters(table=[[5, 1], [0, 4]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[0, 1], [3, 2]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.4999999999999999, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + 99.00009507969123))), + (Parameters(table=[[200, 7], [8, 300]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=977.7866978606228, + conditional_odds_ratio_ci=(0, + 4503.078257659934))), + (Parameters(table=[[28, 21], [6, 1957]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=1, + conditional_odds_ratio=425.2403028434684, + conditional_odds_ratio_ci=(0, + 1811.766127544222))), + (Parameters(table=[[190, 800], [200, 900]], + confidence_level=0.99, + alternative='less'), + RResults(pvalue=0.7416227010368963, + conditional_odds_ratio=1.068697577856801, + conditional_odds_ratio_ci=(0, + 1.396522811516685))), + (Parameters(table=[[100, 2], [1000, 5]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.979790445314723, + conditional_odds_ratio=0.25055839934223, + conditional_odds_ratio_ci=(0.05119649909830196, + Inf))), + (Parameters(table=[[2, 7], [8, 2]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.9990149169715733, + conditional_odds_ratio=0.0858623513573622, + conditional_odds_ratio_ci=(0.007163749169069961, + Inf))), + (Parameters(table=[[5, 1], [10, 10]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.1652173913043478, + conditional_odds_ratio=4.725646047336587, + conditional_odds_ratio_ci=(0.5493234651081089, + Inf))), + (Parameters(table=[[5, 15], [20, 20]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.9849086665340765, + conditional_odds_ratio=0.3394396617440851, + conditional_odds_ratio_ci=(0.1003538933958604, + Inf))), + (Parameters(table=[[5, 16], [16, 25]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.9330176609214881, + conditional_odds_ratio=0.4937791394540491, + conditional_odds_ratio_ci=(0.146507416280863, + Inf))), + (Parameters(table=[[10, 5], [10, 1]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.9782608695652174, + conditional_odds_ratio=0.2116112781158479, + conditional_odds_ratio_ci=(0.007821681994077808, + Inf))), + (Parameters(table=[[10, 5], [10, 0]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[5, 0], [1, 4]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.02380952380952382, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(1.487678929918272, + Inf))), + (Parameters(table=[[0, 5], [1, 4]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[5, 1], [0, 4]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.0238095238095238, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(1.487678929918272, + Inf))), + (Parameters(table=[[0, 1], [3, 2]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[200, 7], [8, 300]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=2.005657880388915e-122, + conditional_odds_ratio=977.7866978606228, + conditional_odds_ratio_ci=(397.784359748113, + Inf))), + (Parameters(table=[[28, 21], [6, 1957]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=5.728437460831983e-44, + conditional_odds_ratio=425.2403028434684, + conditional_odds_ratio_ci=(174.7148056880929, + Inf))), + (Parameters(table=[[190, 800], [200, 900]], + confidence_level=0.95, + alternative='greater'), + RResults(pvalue=0.2959825901308897, + conditional_odds_ratio=1.068697577856801, + conditional_odds_ratio_ci=(0.8828406663967776, + Inf))), + (Parameters(table=[[100, 2], [1000, 5]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.979790445314723, + conditional_odds_ratio=0.25055839934223, + conditional_odds_ratio_ci=(0.03045407081240429, + Inf))), + (Parameters(table=[[2, 7], [8, 2]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.9990149169715733, + conditional_odds_ratio=0.0858623513573622, + conditional_odds_ratio_ci=(0.002768053063547901, + Inf))), + (Parameters(table=[[5, 1], [10, 10]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.1652173913043478, + conditional_odds_ratio=4.725646047336587, + conditional_odds_ratio_ci=(0.2998184792279909, + Inf))), + (Parameters(table=[[5, 15], [20, 20]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.9849086665340765, + conditional_odds_ratio=0.3394396617440851, + conditional_odds_ratio_ci=(0.06180414342643172, + Inf))), + (Parameters(table=[[5, 16], [16, 25]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.9330176609214881, + conditional_odds_ratio=0.4937791394540491, + conditional_odds_ratio_ci=(0.09037094010066403, + Inf))), + (Parameters(table=[[10, 5], [10, 1]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.9782608695652174, + conditional_odds_ratio=0.2116112781158479, + conditional_odds_ratio_ci=(0.001521592095430679, + Inf))), + (Parameters(table=[[10, 5], [10, 0]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[5, 0], [1, 4]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.02380952380952382, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0.6661157890359722, + Inf))), + (Parameters(table=[[0, 5], [1, 4]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[5, 1], [0, 4]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.0238095238095238, + conditional_odds_ratio=Inf, + conditional_odds_ratio_ci=(0.6661157890359725, + Inf))), + (Parameters(table=[[0, 1], [3, 2]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=1, + conditional_odds_ratio=0, + conditional_odds_ratio_ci=(0, + Inf))), + (Parameters(table=[[200, 7], [8, 300]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=2.005657880388915e-122, + conditional_odds_ratio=977.7866978606228, + conditional_odds_ratio_ci=(297.9619252357688, + Inf))), + (Parameters(table=[[28, 21], [6, 1957]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=5.728437460831983e-44, + conditional_odds_ratio=425.2403028434684, + conditional_odds_ratio_ci=(130.3213490295859, + Inf))), + (Parameters(table=[[190, 800], [200, 900]], + confidence_level=0.99, + alternative='greater'), + RResults(pvalue=0.2959825901308897, + conditional_odds_ratio=1.068697577856801, + conditional_odds_ratio_ci=(0.8176272148267533, + Inf))), +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/AtmWtAg.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/AtmWtAg.dat new file mode 100644 index 0000000000000000000000000000000000000000..30537565fe8c47f74da0e63a39f4b46600f7768f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/AtmWtAg.dat @@ -0,0 +1,108 @@ +NIST/ITL StRD +Dataset Name: AtmWtAg (AtmWtAg.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 108) + + +Procedure: Analysis of Variance + + +Reference: Powell, L.J., Murphy, T.J. and Gramlich, J.W. (1982). + "The Absolute Isotopic Abundance & Atomic Weight + of a Reference Sample of Silver". + NBS Journal of Research, 87, pp. 9-19. + + +Data: 1 Factor + 2 Treatments + 24 Replicates/Cell + 48 Observations + 7 Constant Leading Digits + Average Level of Difficulty + Observed Data + + +Model: 3 Parameters (mu, tau_1, tau_2) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + + +Between Instrument 1 3.63834187500000E-09 3.63834187500000E-09 1.59467335677930E+01 +Within Instrument 46 1.04951729166667E-08 2.28155932971014E-10 + + Certified R-Squared 2.57426544538321E-01 + + Certified Residual + Standard Deviation 1.51048314446410E-05 + + + + + + + + + + + +Data: Instrument AgWt + 1 107.8681568 + 1 107.8681465 + 1 107.8681572 + 1 107.8681785 + 1 107.8681446 + 1 107.8681903 + 1 107.8681526 + 1 107.8681494 + 1 107.8681616 + 1 107.8681587 + 1 107.8681519 + 1 107.8681486 + 1 107.8681419 + 1 107.8681569 + 1 107.8681508 + 1 107.8681672 + 1 107.8681385 + 1 107.8681518 + 1 107.8681662 + 1 107.8681424 + 1 107.8681360 + 1 107.8681333 + 1 107.8681610 + 1 107.8681477 + 2 107.8681079 + 2 107.8681344 + 2 107.8681513 + 2 107.8681197 + 2 107.8681604 + 2 107.8681385 + 2 107.8681642 + 2 107.8681365 + 2 107.8681151 + 2 107.8681082 + 2 107.8681517 + 2 107.8681448 + 2 107.8681198 + 2 107.8681482 + 2 107.8681334 + 2 107.8681609 + 2 107.8681101 + 2 107.8681512 + 2 107.8681469 + 2 107.8681360 + 2 107.8681254 + 2 107.8681261 + 2 107.8681450 + 2 107.8681368 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SiRstv.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SiRstv.dat new file mode 100644 index 0000000000000000000000000000000000000000..18ea8971fd7a4d67800dafe98ac5ea5acef53025 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SiRstv.dat @@ -0,0 +1,85 @@ +NIST/ITL StRD +Dataset Name: SiRstv (SiRstv.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 85) + + +Procedure: Analysis of Variance + + +Reference: Ehrstein, James and Croarkin, M. Carroll. + Unpublished NIST dataset. + + +Data: 1 Factor + 5 Treatments + 5 Replicates/Cell + 25 Observations + 3 Constant Leading Digits + Lower Level of Difficulty + Observed Data + + +Model: 6 Parameters (mu,tau_1, ... , tau_5) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Instrument 4 5.11462616000000E-02 1.27865654000000E-02 1.18046237440255E+00 +Within Instrument 20 2.16636560000000E-01 1.08318280000000E-02 + + Certified R-Squared 1.90999039051129E-01 + + Certified Residual + Standard Deviation 1.04076068334656E-01 + + + + + + + + + + + + +Data: Instrument Resistance + 1 196.3052 + 1 196.1240 + 1 196.1890 + 1 196.2569 + 1 196.3403 + 2 196.3042 + 2 196.3825 + 2 196.1669 + 2 196.3257 + 2 196.0422 + 3 196.1303 + 3 196.2005 + 3 196.2889 + 3 196.0343 + 3 196.1811 + 4 196.2795 + 4 196.1748 + 4 196.1494 + 4 196.1485 + 4 195.9885 + 5 196.2119 + 5 196.1051 + 5 196.1850 + 5 196.0052 + 5 196.2090 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs01.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs01.dat new file mode 100644 index 0000000000000000000000000000000000000000..945b24bf35422152a5faba73ed054ab78fda1bdf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs01.dat @@ -0,0 +1,249 @@ +NIST/ITL StRD +Dataset Name: SmLs01 (SmLs01.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 249) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 21 Replicates/Cell + 189 Observations + 1 Constant Leading Digit + Lower Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.68000000000000E+00 2.10000000000000E-01 2.10000000000000E+01 +Within Treatment 180 1.80000000000000E+00 1.00000000000000E-02 + + Certified R-Squared 4.82758620689655E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1.4 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 2 1.3 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 3 1.5 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 4 1.3 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 5 1.5 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 6 1.3 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 7 1.5 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 8 1.3 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 9 1.5 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs02.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs02.dat new file mode 100644 index 0000000000000000000000000000000000000000..ee76633a660a48225064bbb86a25f6a2f36c6d9a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs02.dat @@ -0,0 +1,1869 @@ +NIST/ITL StRD +Dataset Name: SmLs02 (SmLs02.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 1869) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 201 Replicates/Cell + 1809 Observations + 1 Constant Leading Digit + Lower Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.60800000000000E+01 2.01000000000000E+00 2.01000000000000E+02 +Within Treatment 1800 1.80000000000000E+01 1.00000000000000E-02 + + Certified R-Squared 4.71830985915493E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1.4 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 2 1.3 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 3 1.5 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 4 1.3 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 5 1.5 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 6 1.3 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 7 1.5 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 8 1.3 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 9 1.5 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs03.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs03.dat new file mode 100644 index 0000000000000000000000000000000000000000..55dfa2313ffb152709c58b47c0058567b710d903 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs03.dat @@ -0,0 +1,18069 @@ +NIST/ITL StRD +Dataset Name: SmLs03 (SmLs03.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 18069) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 2001 Replicates/Cell + 18009 Observations + 1 Constant Leading Digit + Lower Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.60080000000000E+02 2.00100000000000E+01 2.00100000000000E+03 +Within Treatment 18000 1.80000000000000E+02 1.00000000000000E-02 + + Certified R-Squared 4.70712773465067E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1.4 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 1 1.3 + 1 1.5 + 2 1.3 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 2 1.2 + 2 1.4 + 3 1.5 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 3 1.4 + 3 1.6 + 4 1.3 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 4 1.2 + 4 1.4 + 5 1.5 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 5 1.4 + 5 1.6 + 6 1.3 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 6 1.2 + 6 1.4 + 7 1.5 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 7 1.4 + 7 1.6 + 8 1.3 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 8 1.2 + 8 1.4 + 9 1.5 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 + 9 1.4 + 9 1.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs04.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs04.dat new file mode 100644 index 0000000000000000000000000000000000000000..6a2a9fc935a56989b166de9b23f3df3bc4f64879 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs04.dat @@ -0,0 +1,249 @@ +NIST/ITL StRD +Dataset Name: SmLs04 (SmLs04.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 249) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 21 Replicates/Cell + 189 Observations + 7 Constant Leading Digits + Average Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.68000000000000E+00 2.10000000000000E-01 2.10000000000000E+01 +Within Treatment 180 1.80000000000000E+00 1.00000000000000E-02 + + Certified R-Squared 4.82758620689655E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1000000.4 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 2 1000000.3 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 3 1000000.5 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 4 1000000.3 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 5 1000000.5 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 6 1000000.3 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 7 1000000.5 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 8 1000000.3 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 9 1000000.5 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs05.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs05.dat new file mode 100644 index 0000000000000000000000000000000000000000..fe11c40b5f51aefc81d4d1501a74e627f2b2d992 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs05.dat @@ -0,0 +1,1869 @@ +NIST/ITL StRD +Dataset Name: SmLs05 (SmLs05.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 1869) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 201 Replicates/Cell + 1809 Observations + 7 Constant Leading Digits + Average Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.60800000000000E+01 2.01000000000000E+00 2.01000000000000E+02 +Within Treatment 1800 1.80000000000000E+01 1.00000000000000E-02 + + Certified R-Squared 4.71830985915493E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1000000.4 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 2 1000000.3 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 3 1000000.5 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 4 1000000.3 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 5 1000000.5 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 6 1000000.3 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 7 1000000.5 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 8 1000000.3 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 9 1000000.5 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs06.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs06.dat new file mode 100644 index 0000000000000000000000000000000000000000..602e4fbdaa26bbb8d95ce78d1f48dbbfa883e7e9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs06.dat @@ -0,0 +1,18069 @@ +NIST/ITL StRD +Dataset Name: SmLs06 (SmLs06.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 18069) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 2001 Replicates/Cell + 18009 Observations + 7 Constant Leading Digits + Average Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.60080000000000E+02 2.00100000000000E+01 2.00100000000000E+03 +Within Treatment 18000 1.80000000000000E+02 1.00000000000000E-02 + + Certified R-Squared 4.70712773465067E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1000000.4 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 1 1000000.3 + 1 1000000.5 + 2 1000000.3 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 2 1000000.2 + 2 1000000.4 + 3 1000000.5 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 3 1000000.4 + 3 1000000.6 + 4 1000000.3 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 4 1000000.2 + 4 1000000.4 + 5 1000000.5 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 5 1000000.4 + 5 1000000.6 + 6 1000000.3 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 6 1000000.2 + 6 1000000.4 + 7 1000000.5 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 7 1000000.4 + 7 1000000.6 + 8 1000000.3 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 8 1000000.2 + 8 1000000.4 + 9 1000000.5 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 + 9 1000000.4 + 9 1000000.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs07.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs07.dat new file mode 100644 index 0000000000000000000000000000000000000000..deeac955e65ffaf55838568baa54951efaf2662b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs07.dat @@ -0,0 +1,249 @@ +NIST/ITL StRD +Dataset Name: SmLs07 (SmLs07.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 249) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 21 Replicates/Cell + 189 Observations + 13 Constant Leading Digits + Higher Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.68000000000000E+00 2.10000000000000E-01 2.10000000000000E+01 +Within Treatment 180 1.80000000000000E+00 1.00000000000000E-02 + + Certified R-Squared 4.82758620689655E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1000000000000.4 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 2 1000000000000.3 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 3 1000000000000.5 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 4 1000000000000.3 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 5 1000000000000.5 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 6 1000000000000.3 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 7 1000000000000.5 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 8 1000000000000.3 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 9 1000000000000.5 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs08.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs08.dat new file mode 100644 index 0000000000000000000000000000000000000000..c5ee643fb8c6ef849ab8e34352bc60f15c715a45 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs08.dat @@ -0,0 +1,1869 @@ +NIST/ITL StRD +Dataset Name: SmLs08 (SmLs08.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 1869) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 201 Replicates/Cell + 1809 Observations + 13 Constant Leading Digits + Higher Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.60800000000000E+01 2.01000000000000E+00 2.01000000000000E+02 +Within Treatment 1800 1.80000000000000E+01 1.00000000000000E-02 + + Certified R-Squared 4.71830985915493E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1000000000000.4 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 2 1000000000000.3 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 3 1000000000000.5 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 4 1000000000000.3 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 5 1000000000000.5 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 6 1000000000000.3 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 7 1000000000000.5 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 8 1000000000000.3 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 9 1000000000000.5 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs09.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs09.dat new file mode 100644 index 0000000000000000000000000000000000000000..887905e355a2a13801f1b004187631f2301f7eef --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs09.dat @@ -0,0 +1,18069 @@ +NIST/ITL StRD +Dataset Name: SmLs09 (SmLs09.dat) + + +File Format: ASCII + Certified Values (lines 41 to 47) + Data (lines 61 to 18069) + + +Procedure: Analysis of Variance + + +Reference: Simon, Stephen D. and Lesage, James P. (1989). + "Assessing the Accuracy of ANOVA Calculations in + Statistical Software". + Computational Statistics & Data Analysis, 8, pp. 325-332. + + +Data: 1 Factor + 9 Treatments + 2001 Replicates/Cell + 18009 Observations + 13 Constant Leading Digits + Higher Level of Difficulty + Generated Data + + +Model: 10 Parameters (mu,tau_1, ... , tau_9) + y_{ij} = mu + tau_i + epsilon_{ij} + + + + + + +Certified Values: + +Source of Sums of Mean +Variation df Squares Squares F Statistic + +Between Treatment 8 1.60080000000000E+02 2.00100000000000E+01 2.00100000000000E+03 +Within Treatment 18000 1.80000000000000E+02 1.00000000000000E-02 + + Certified R-Squared 4.70712773465067E-01 + + Certified Residual + Standard Deviation 1.00000000000000E-01 + + + + + + + + + + + + +Data: Treatment Response + 1 1000000000000.4 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 1 1000000000000.3 + 1 1000000000000.5 + 2 1000000000000.3 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 2 1000000000000.2 + 2 1000000000000.4 + 3 1000000000000.5 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 3 1000000000000.4 + 3 1000000000000.6 + 4 1000000000000.3 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 4 1000000000000.2 + 4 1000000000000.4 + 5 1000000000000.5 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 5 1000000000000.4 + 5 1000000000000.6 + 6 1000000000000.3 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 6 1000000000000.2 + 6 1000000000000.4 + 7 1000000000000.5 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 7 1000000000000.4 + 7 1000000000000.6 + 8 1000000000000.3 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 8 1000000000000.2 + 8 1000000000000.4 + 9 1000000000000.5 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 + 9 1000000000000.4 + 9 1000000000000.6 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_linregress/Norris.dat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_linregress/Norris.dat new file mode 100644 index 0000000000000000000000000000000000000000..4bf8ed911cae75824b27e5f5d5e444e17fa8eae8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_linregress/Norris.dat @@ -0,0 +1,97 @@ +NIST/ITL StRD +Dataset Name: Norris (Norris.dat) + +File Format: ASCII + Certified Values (lines 31 to 46) + Data (lines 61 to 96) + +Procedure: Linear Least Squares Regression + +Reference: Norris, J., NIST. + Calibration of Ozone Monitors. + +Data: 1 Response Variable (y) + 1 Predictor Variable (x) + 36 Observations + Lower Level of Difficulty + Observed Data + +Model: Linear Class + 2 Parameters (B0,B1) + + y = B0 + B1*x + e + + + + Certified Regression Statistics + + Standard Deviation + Parameter Estimate of Estimate + + B0 -0.262323073774029 0.232818234301152 + B1 1.00211681802045 0.429796848199937E-03 + + Residual + Standard Deviation 0.884796396144373 + + R-Squared 0.999993745883712 + + + Certified Analysis of Variance Table + +Source of Degrees of Sums of Mean +Variation Freedom Squares Squares F Statistic + +Regression 1 4255954.13232369 4255954.13232369 5436385.54079785 +Residual 34 26.6173985294224 0.782864662630069 + + + + + + + + + + + + + +Data: y x + 0.1 0.2 + 338.8 337.4 + 118.1 118.2 + 888.0 884.6 + 9.2 10.1 + 228.1 226.5 + 668.5 666.3 + 998.5 996.3 + 449.1 448.6 + 778.9 777.0 + 559.2 558.2 + 0.3 0.4 + 0.1 0.6 + 778.1 775.5 + 668.8 666.9 + 339.3 338.0 + 448.9 447.5 + 10.8 11.6 + 557.7 556.0 + 228.3 228.1 + 998.0 995.8 + 888.8 887.6 + 119.6 120.2 + 0.3 0.3 + 0.6 0.3 + 557.6 556.8 + 339.3 339.1 + 888.0 887.2 + 998.5 999.0 + 778.9 779.0 + 10.2 11.1 + 117.6 118.3 + 228.9 229.2 + 668.4 669.1 + 449.2 448.9 + 0.2 0.5 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/studentized_range_mpmath_ref.json b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/studentized_range_mpmath_ref.json new file mode 100644 index 0000000000000000000000000000000000000000..bb971286cf85b28738a80bacececfb90c2566782 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/studentized_range_mpmath_ref.json @@ -0,0 +1,1499 @@ +{ + "COMMENT": "!!!!!! THIS FILE WAS AUTOGENERATED BY RUNNING `python studentized_range_mpmath_ref.py` !!!!!!", + "moment_data": [ + { + "src_case": { + "m": 0, + "k": 3, + "v": 10, + "expected_atol": 1e-09, + "expected_rtol": 1e-09 + }, + "mp_result": 1.0 + }, + { + "src_case": { + "m": 1, + "k": 3, + "v": 10, + "expected_atol": 1e-09, + "expected_rtol": 1e-09 + }, + "mp_result": 1.8342745127927962 + }, + { + "src_case": { + "m": 2, + "k": 3, + "v": 10, + "expected_atol": 1e-09, + "expected_rtol": 1e-09 + }, + "mp_result": 4.567483357831711 + }, + { + "src_case": { + "m": 3, + "k": 3, + "v": 10, + "expected_atol": 1e-09, + "expected_rtol": 1e-09 + }, + "mp_result": 14.412156886227011 + }, + { + "src_case": { + "m": 4, + "k": 3, + "v": 10, + "expected_atol": 1e-09, + "expected_rtol": 1e-09 + }, + "mp_result": 56.012250366720444 + } + ], + "cdf_data": [ + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0027502772229359594 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.8544145010066327e-12 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0027520560662338336 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.39089126131273e-13 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.002752437649536182 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.0862189999210748e-12 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.002752755744313648 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0027527430186246545 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.002752666667812431 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.505275157135514e-24 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 3.8546698113384126e-25 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.7362668562706085e-11 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 5.571947730052616e-26 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.032619249089036e-27 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.539763646681808e-22 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.618313512511099e-12 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 4.919231733354114e-28 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.159348906295542e-13 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.22331624289542043 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.2395624637676257 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.23510918942128056 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.23786536230099864 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.000651656693149116 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.2401356460422021 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.003971273224673166 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0008732969319364606 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.24023154593376422 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.001300816146573152 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.5682573722040226e-07 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0005841098057517027 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.2267674885784e-05 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0005731712496327297 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.746798012658064e-06 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 5.807700350854172e-07 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.147637957472628e-08 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 8.306675539750552e-08 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.8711786295203324 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9818862781476212 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9566506502400175 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9849546621386962 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9731488893573804 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.8450530667988544 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.6164875232404174 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9845292772767739 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.8079691517949077 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.7573606942645745 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.8587525248147736 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.8611036193280976 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.46523135355387657 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.6318042819232383 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.5574947140294286 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.5970517763141937 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.6493671527818267 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.6466699776044968 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9881335633712994 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999999861266821 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.999908236635449 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999978467928313 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999999996690216 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999999993640496 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9570401457077894 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999997977351971 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9991738325963548 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999730883609333 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999999905199205 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999999950566264 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9312318042339768 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999991743904675 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9977643922032399 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999054426012515 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999999602948055 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.9999999792458618 + } + ], + "pdf_data": [ + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.05487847613526332 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.564099684606509e-10 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.05494947290360002 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 8.442593793786411e-11 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.054964710604860405 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.764441961563576e-11 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.05497690690332341 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.05497385731702228 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 4.758021225803992e-22 + }, + { + "src_case": { + "q": 0.1, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.054977415200879516 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.8004731453548083e-19 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.5564176176604816e-09 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.342768070688728e-24 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.454372265306114e-10 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 3.9138464398429654e-25 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 5.266341131767418e-23 + }, + { + "src_case": { + "q": 0.1, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 8.234556126446594e-11 + }, + { + "src_case": { + "q": 0.1, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.32929780487562e-26 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.36083736990527154 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.4137959132282269 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.4080239698771056 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.398772020275752 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.4160873922094346 + }, + { + "src_case": { + "q": 1, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.4157583991350054 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.005210720148451848 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.02575314059867804 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.009782573637596617 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.006818708302379005 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0047089182958790715 + }, + { + "src_case": { + "q": 1, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.004627085294166373 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0010886280311369462 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.630674470916427e-06 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 4.121713278199428e-05 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 9.319506007252685e-06 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.5585754418789747e-06 + }, + { + "src_case": { + "q": 1, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.4190335899441991e-06 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.07185383302009114 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.050268901219386576 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.03321056847176124 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.04044172384981084 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.030571365659999617 + }, + { + "src_case": { + "q": 4, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.030120779149073032 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.17501664247670937 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.22374394725370736 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.23246597521020534 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.23239043677504484 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.23057775622748988 + }, + { + "src_case": { + "q": 4, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.23012666145240815 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.2073676639537027 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.3245990542431859 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0033733228559870584 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 7.728665739003835e-05 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.38244500549096866 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.45434978340834464 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.43334135870667473 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.159522630228393e-09 + }, + { + "src_case": { + "q": 4, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.45807877248528855 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 3.5303467191175695e-08 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 3.121281850105421e-06 + }, + { + "src_case": { + "q": 10, + "k": 3, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.1901591191700855e-09 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0006784051704217357 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.011845582636101885 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 3.844183552674918e-05 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 3.215093171597309e-08 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 5.125792577534542e-07 + }, + { + "src_case": { + "q": 10, + "k": 10, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.7759015355532446e-08 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 10, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.0017957646258393628 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 3, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.018534407764819284 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 20, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 0.00013316083413164858 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 50, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 2.082489228991225e-06 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 100, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 1.3444226792257012e-07 + }, + { + "src_case": { + "q": 10, + "k": 20, + "v": 120, + "expected_atol": 1e-11, + "expected_rtol": 1e-11 + }, + "mp_result": 7.446912854228521e-08 + } + ] +} \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_axis_nan_policy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_axis_nan_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..162e62b813927f03a86e685af7c4a0829575f62d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_axis_nan_policy.py @@ -0,0 +1,1350 @@ +# Many scipy.stats functions support `axis` and `nan_policy` parameters. +# When the two are combined, it can be tricky to get all the behavior just +# right. This file contains a suite of common tests for scipy.stats functions +# that support `axis` and `nan_policy` and additional tests for some associated +# functions in stats._util. + +from itertools import product, combinations_with_replacement, permutations +import os +import re +import pickle +import pytest +import warnings + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +from scipy import stats +from scipy.stats import norm # type: ignore[attr-defined] +from scipy.stats._axis_nan_policy import (_masked_arrays_2_sentinel_arrays, + SmallSampleWarning, + too_small_nd_omit, too_small_nd_not_omit, + too_small_1d_omit, too_small_1d_not_omit) +from scipy._lib._util import AxisError +from scipy.conftest import skip_xp_invalid_arg + + +SCIPY_XSLOW = int(os.environ.get('SCIPY_XSLOW', '0')) + + +def unpack_ttest_result(res): + low, high = res.confidence_interval() + return (res.statistic, res.pvalue, res.df, res._standard_error, + res._estimate, low, high) + + +def _get_ttest_ci(ttest): + # get a function that returns the CI bounds of provided `ttest` + def ttest_ci(*args, **kwargs): + res = ttest(*args, **kwargs) + return res.confidence_interval() + return ttest_ci + + +def xp_mean_1samp(*args, **kwargs): + kwargs.pop('_no_deco', None) + return stats._stats_py._xp_mean(*args, **kwargs) + + +def xp_mean_2samp(*args, **kwargs): + kwargs.pop('_no_deco', None) + weights = args[1] + return stats._stats_py._xp_mean(args[0], *args[2:], weights=weights, **kwargs) + + +def xp_var(*args, **kwargs): + kwargs.pop('_no_deco', None) + return stats._stats_py._xp_var(*args, **kwargs) + + +def combine_pvalues_weighted(*args, **kwargs): + return stats.combine_pvalues(args[0], *args[2:], weights=args[1], + method='stouffer', **kwargs) + + +axis_nan_policy_cases = [ + # function, args, kwds, number of samples, number of outputs, + # ... paired, unpacker function + # args, kwds typically aren't needed; just showing that they work + (stats.kruskal, tuple(), dict(), 3, 2, False, None), # 4 samples is slow + (stats.ranksums, ('less',), dict(), 2, 2, False, None), + (stats.mannwhitneyu, tuple(), {'method': 'asymptotic'}, 2, 2, False, None), + (stats.wilcoxon, ('pratt',), {'mode': 'auto'}, 2, 2, True, + lambda res: (res.statistic, res.pvalue)), + (stats.wilcoxon, tuple(), dict(), 1, 2, True, + lambda res: (res.statistic, res.pvalue)), + (stats.wilcoxon, tuple(), {'method': 'asymptotic'}, 1, 3, True, + lambda res: (res.statistic, res.pvalue, res.zstatistic)), + (stats.gmean, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.hmean, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.pmean, (1.42,), dict(), 1, 1, False, lambda x: (x,)), + (stats.sem, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.iqr, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.kurtosis, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.skew, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.kstat, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.kstatvar, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.moment, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.moment, tuple(), dict(order=[1, 2]), 1, 2, False, None), + (stats.jarque_bera, tuple(), dict(), 1, 2, False, None), + (stats.ttest_1samp, (np.array([0]),), dict(), 1, 7, False, + unpack_ttest_result), + (stats.ttest_rel, tuple(), dict(), 2, 7, True, unpack_ttest_result), + (stats.ttest_ind, tuple(), dict(), 2, 7, False, unpack_ttest_result), + (_get_ttest_ci(stats.ttest_1samp), (0,), dict(), 1, 2, False, None), + (_get_ttest_ci(stats.ttest_rel), tuple(), dict(), 2, 2, True, None), + (_get_ttest_ci(stats.ttest_ind), tuple(), dict(), 2, 2, False, None), + (stats.mode, tuple(), dict(), 1, 2, True, lambda x: (x.mode, x.count)), + (stats.differential_entropy, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.variation, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.friedmanchisquare, tuple(), dict(), 3, 2, True, None), + (stats.brunnermunzel, tuple(), dict(distribution='normal'), 2, 2, False, None), + (stats.mood, tuple(), {}, 2, 2, False, None), + (stats.shapiro, tuple(), {}, 1, 2, False, None), + (stats.ks_1samp, (norm().cdf,), dict(), 1, 4, False, + lambda res: (*res, res.statistic_location, res.statistic_sign)), + (stats.ks_2samp, tuple(), dict(), 2, 4, False, + lambda res: (*res, res.statistic_location, res.statistic_sign)), + (stats.kstest, (norm().cdf,), dict(), 1, 4, False, + lambda res: (*res, res.statistic_location, res.statistic_sign)), + (stats.kstest, tuple(), dict(), 2, 4, False, + lambda res: (*res, res.statistic_location, res.statistic_sign)), + (stats.levene, tuple(), {}, 2, 2, False, None), + (stats.fligner, tuple(), {'center': 'trimmed', 'proportiontocut': 0.01}, + 2, 2, False, None), + (stats.ansari, tuple(), {}, 2, 2, False, None), + (stats.entropy, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.entropy, tuple(), dict(), 2, 1, True, lambda x: (x,)), + (stats.skewtest, tuple(), dict(), 1, 2, False, None), + (stats.kurtosistest, tuple(), dict(), 1, 2, False, None), + (stats.normaltest, tuple(), dict(), 1, 2, False, None), + (stats.cramervonmises, ("norm",), dict(), 1, 2, False, + lambda res: (res.statistic, res.pvalue)), + (stats.cramervonmises_2samp, tuple(), dict(), 2, 2, False, + lambda res: (res.statistic, res.pvalue)), + (stats.epps_singleton_2samp, tuple(), dict(), 2, 2, False, None), + (stats.bartlett, tuple(), {}, 2, 2, False, None), + (stats.tmean, tuple(), {}, 1, 1, False, lambda x: (x,)), + (stats.tvar, tuple(), {}, 1, 1, False, lambda x: (x,)), + (stats.tmin, tuple(), {}, 1, 1, False, lambda x: (x,)), + (stats.tmax, tuple(), {}, 1, 1, False, lambda x: (x,)), + (stats.tstd, tuple(), {}, 1, 1, False, lambda x: (x,)), + (stats.tsem, tuple(), {}, 1, 1, False, lambda x: (x,)), + (stats.circmean, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.circvar, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.circstd, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.f_oneway, tuple(), {}, 2, 2, False, None), + (stats.alexandergovern, tuple(), {}, 2, 2, False, + lambda res: (res.statistic, res.pvalue)), + (stats.combine_pvalues, tuple(), {}, 1, 2, False, None), + (stats.lmoment, tuple(), dict(), 1, 4, False, lambda x: tuple(x)), + (combine_pvalues_weighted, tuple(), {}, 2, 2, True, None), + (xp_mean_1samp, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (xp_mean_2samp, tuple(), dict(), 2, 1, True, lambda x: (x,)), + (xp_var, tuple(), dict(), 1, 1, False, lambda x: (x,)), + (stats.chatterjeexi, tuple(), dict(), 2, 2, True, + lambda res: (res.statistic, res.pvalue)), +] + +# If the message is one of those expected, put nans in +# appropriate places of `statistics` and `pvalues` +too_small_messages = {"Degrees of freedom <= 0 for slice", + "x and y should have at least 5 elements", + "Data must be at least length 3", + "The sample must contain at least two", + "x and y must contain at least two", + "division by zero", + "Mean of empty slice", + "Data passed to ks_2samp must not be empty", + "Not enough test observations", + "Not enough other observations", + "Not enough observations.", + "At least one observation is required", + "zero-size array to reduction operation maximum", + "`x` and `y` must be of nonzero size.", + "The exact distribution of the Wilcoxon test", + "Data input must not be empty", + "Window length (0) must be positive and less", + "Window length (1) must be positive and less", + "Window length (2) must be positive and less", + "`skewtest` requires at least", + "`kurtosistest` requires at least", + "attempt to get argmax of an empty sequence", + "No array values within given limits", + "Input sample size must be greater than one.", + "At least one slice along `axis` has zero length", + "One or more sample arguments is too small", + "invalid value encountered", + "divide by zero encountered", +} + +# If the message is one of these, results of the function may be inaccurate, +# but NaNs are not to be placed +inaccuracy_messages = {"Precision loss occurred in moment calculation", + "Sample size too small for normal approximation."} + +# For some functions, nan_policy='propagate' should not just return NaNs +override_propagate_funcs = {stats.mode} + +# For some functions, empty arrays produce non-NaN results +empty_special_case_funcs = {stats.entropy} + +# Some functions don't follow the usual "too small" warning rules +too_small_special_case_funcs = {stats.entropy} + +def _mixed_data_generator(n_samples, n_repetitions, axis, rng, + paired=False): + # generate random samples to check the response of hypothesis tests to + # samples with different (but broadcastable) shapes and various + # nan patterns (e.g. all nans, some nans, no nans) along axis-slices + + data = [] + for i in range(n_samples): + n_patterns = 6 # number of distinct nan patterns + n_obs = 20 if paired else 20 + i # observations per axis-slice + x = np.ones((n_repetitions, n_patterns, n_obs)) * np.nan + + for j in range(n_repetitions): + samples = x[j, :, :] + + # case 0: axis-slice with all nans (0 reals) + # cases 1-3: axis-slice with 1-3 reals (the rest nans) + # case 4: axis-slice with mostly (all but two) reals + # case 5: axis slice with all reals + for k, n_reals in enumerate([0, 1, 2, 3, n_obs-2, n_obs]): + # for cases 1-3, need paired nansw to be in the same place + indices = rng.permutation(n_obs)[:n_reals] + samples[k, indices] = rng.random(size=n_reals) + + # permute the axis-slices just to show that order doesn't matter + samples[:] = rng.permutation(samples, axis=0) + + # For multi-sample tests, we want to test broadcasting and check + # that nan policy works correctly for each nan pattern for each input. + # This takes care of both simultaneously. + new_shape = [n_repetitions] + [1]*n_samples + [n_obs] + new_shape[1 + i] = 6 + x = x.reshape(new_shape) + + x = np.moveaxis(x, -1, axis) + data.append(x) + return data + + +def _homogeneous_data_generator(n_samples, n_repetitions, axis, rng, + paired=False, all_nans=True): + # generate random samples to check the response of hypothesis tests to + # samples with different (but broadcastable) shapes and homogeneous + # data (all nans or all finite) + data = [] + for i in range(n_samples): + n_obs = 20 if paired else 20 + i # observations per axis-slice + shape = [n_repetitions] + [1]*n_samples + [n_obs] + shape[1 + i] = 2 + x = np.ones(shape) * np.nan if all_nans else rng.random(shape) + x = np.moveaxis(x, -1, axis) + data.append(x) + return data + + +def nan_policy_1d(hypotest, data1d, unpacker, *args, n_outputs=2, + nan_policy='raise', paired=False, _no_deco=True, **kwds): + # Reference implementation for how `nan_policy` should work for 1d samples + + if nan_policy == 'raise': + for sample in data1d: + if np.any(np.isnan(sample)): + raise ValueError("The input contains nan values") + + elif (nan_policy == 'propagate' + and hypotest not in override_propagate_funcs): + # For all hypothesis tests tested, returning nans is the right thing. + # But many hypothesis tests don't propagate correctly (e.g. they treat + # np.nan the same as np.inf, which doesn't make sense when ranks are + # involved) so override that behavior here. + for sample in data1d: + if np.any(np.isnan(sample)): + return np.full(n_outputs, np.nan) + + elif nan_policy == 'omit': + # manually omit nans (or pairs in which at least one element is nan) + if not paired: + data1d = [sample[~np.isnan(sample)] for sample in data1d] + else: + nan_mask = np.isnan(data1d[0]) + for sample in data1d[1:]: + nan_mask = np.logical_or(nan_mask, np.isnan(sample)) + data1d = [sample[~nan_mask] for sample in data1d] + + return unpacker(hypotest(*data1d, *args, _no_deco=_no_deco, **kwds)) + + +# These three warnings are intentional +# For `wilcoxon` when the sample size < 50 +@pytest.mark.filterwarnings('ignore:Sample size too small for normal:UserWarning') +# `kurtosistest` and `normaltest` when sample size < 20 +@pytest.mark.filterwarnings('ignore:`kurtosistest` p-value may be:UserWarning') +# `foneway` +@pytest.mark.filterwarnings('ignore:all input arrays have length 1.:RuntimeWarning') + +# The rest of these may or may not be desirable. They need further investigation +# to determine whether the function's decorator should define `too_small. +# `bartlett`, `tvar`, `tstd`, `tsem` +@pytest.mark.filterwarnings('ignore:Degrees of freedom <= 0 for slice:RuntimeWarning') +# kstat, kstatvar, ttest_1samp, ttest_rel, ttest_ind, ttest_ci, brunnermunzel +# mood, levene, fligner, bartlett +@pytest.mark.filterwarnings('ignore:Invalid value encountered in:RuntimeWarning') +# kstatvar, ttest_1samp, ttest_rel, ttest_ci, brunnermunzel, levene, bartlett +@pytest.mark.filterwarnings('ignore:divide by zero encountered:RuntimeWarning') + +@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs", + "paired", "unpacker"), axis_nan_policy_cases) +@pytest.mark.parametrize(("nan_policy"), ("propagate", "omit", "raise")) +@pytest.mark.parametrize(("axis"), (1,)) +@pytest.mark.parametrize(("data_generator"), ("mixed",)) +def test_axis_nan_policy_fast(hypotest, args, kwds, n_samples, n_outputs, + paired, unpacker, nan_policy, axis, + data_generator): + if hypotest in {stats.cramervonmises_2samp, stats.kruskal} and not SCIPY_XSLOW: + pytest.skip("Too slow.") + _axis_nan_policy_test(hypotest, args, kwds, n_samples, n_outputs, paired, + unpacker, nan_policy, axis, data_generator) + + +if SCIPY_XSLOW: + # Takes O(1 min) to run, and even skipping with the `xslow` decorator takes + # about 3 sec because this is >3,000 tests. So ensure pytest doesn't see + # them at all unless `SCIPY_XSLOW` is defined. + + # These three warnings are intentional + # For `wilcoxon` when the sample size < 50 + @pytest.mark.filterwarnings('ignore:Sample size too small for normal:UserWarning') + # `kurtosistest` and `normaltest` when sample size < 20 + @pytest.mark.filterwarnings('ignore:`kurtosistest` p-value may be:UserWarning') + # `foneway` + @pytest.mark.filterwarnings('ignore:all input arrays have length 1.:RuntimeWarning') + + # The rest of these may or may not be desirable. They need further investigation + # to determine whether the function's decorator should define `too_small. + # `bartlett`, `tvar`, `tstd`, `tsem` + @pytest.mark.filterwarnings('ignore:Degrees of freedom <= 0 for:RuntimeWarning') + # kstat, kstatvar, ttest_1samp, ttest_rel, ttest_ind, ttest_ci, brunnermunzel + # mood, levene, fligner, bartlett + @pytest.mark.filterwarnings('ignore:Invalid value encountered in:RuntimeWarning') + # kstatvar, ttest_1samp, ttest_rel, ttest_ci, brunnermunzel, levene, bartlett + @pytest.mark.filterwarnings('ignore:divide by zero encountered:RuntimeWarning') + + @pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs", + "paired", "unpacker"), axis_nan_policy_cases) + @pytest.mark.parametrize(("nan_policy"), ("propagate", "omit", "raise")) + @pytest.mark.parametrize(("axis"), range(-3, 3)) + @pytest.mark.parametrize(("data_generator"), + ("all_nans", "all_finite", "mixed")) + def test_axis_nan_policy_full(hypotest, args, kwds, n_samples, n_outputs, + paired, unpacker, nan_policy, axis, + data_generator): + _axis_nan_policy_test(hypotest, args, kwds, n_samples, n_outputs, paired, + unpacker, nan_policy, axis, data_generator) + + +def _axis_nan_policy_test(hypotest, args, kwds, n_samples, n_outputs, paired, + unpacker, nan_policy, axis, data_generator): + # Tests the 1D and vectorized behavior of hypothesis tests against a + # reference implementation (nan_policy_1d with np.ndenumerate) + + # Some hypothesis tests return a non-iterable that needs an `unpacker` to + # extract the statistic and p-value. For those that don't: + if not unpacker: + def unpacker(res): + return res + + rng = np.random.default_rng(0) + + # Generate multi-dimensional test data with all important combinations + # of patterns of nans along `axis` + n_repetitions = 3 # number of repetitions of each pattern + data_gen_kwds = {'n_samples': n_samples, 'n_repetitions': n_repetitions, + 'axis': axis, 'rng': rng, 'paired': paired} + if data_generator == 'mixed': + inherent_size = 6 # number of distinct types of patterns + data = _mixed_data_generator(**data_gen_kwds) + elif data_generator == 'all_nans': + inherent_size = 2 # hard-coded in _homogeneous_data_generator + data_gen_kwds['all_nans'] = True + data = _homogeneous_data_generator(**data_gen_kwds) + elif data_generator == 'all_finite': + inherent_size = 2 # hard-coded in _homogeneous_data_generator + data_gen_kwds['all_nans'] = False + data = _homogeneous_data_generator(**data_gen_kwds) + + output_shape = [n_repetitions] + [inherent_size]*n_samples + + # To generate reference behavior to compare against, loop over the axis- + # slices in data. Make indexing easier by moving `axis` to the end and + # broadcasting all samples to the same shape. + data_b = [np.moveaxis(sample, axis, -1) for sample in data] + data_b = [np.broadcast_to(sample, output_shape + [sample.shape[-1]]) + for sample in data_b] + res_1d = np.zeros(output_shape + [n_outputs]) + + for i, _ in np.ndenumerate(np.zeros(output_shape)): + data1d = [sample[i] for sample in data_b] + contains_nan = any([np.isnan(sample).any() for sample in data1d]) + + # Take care of `nan_policy='raise'`. + # Afterward, the 1D part of the test is over + message = "The input contains nan values" + if nan_policy == 'raise' and contains_nan: + with pytest.raises(ValueError, match=message): + nan_policy_1d(hypotest, data1d, unpacker, *args, + n_outputs=n_outputs, + nan_policy=nan_policy, + paired=paired, _no_deco=True, **kwds) + + with pytest.raises(ValueError, match=message): + hypotest(*data1d, *args, nan_policy=nan_policy, **kwds) + + continue + + # Take care of `nan_policy='propagate'` and `nan_policy='omit'` + + # Get results of simple reference implementation + try: + res_1da = nan_policy_1d(hypotest, data1d, unpacker, *args, + n_outputs=n_outputs, + nan_policy=nan_policy, + paired=paired, _no_deco=True, **kwds) + except (ValueError, RuntimeWarning, ZeroDivisionError) as ea: + ea_str = str(ea) + if any([str(ea_str).startswith(msg) for msg in too_small_messages]): + res_1da = np.full(n_outputs, np.nan) + else: + raise + + # Get results of public function with 1D slices + # Should warn for all slices + if (nan_policy == 'omit' and data_generator == "all_nans" + and hypotest not in too_small_special_case_funcs): + with pytest.warns(SmallSampleWarning, match=too_small_1d_omit): + res = hypotest(*data1d, *args, nan_policy=nan_policy, **kwds) + # warning depends on slice + elif (nan_policy == 'omit' and data_generator == "mixed" + and hypotest not in too_small_special_case_funcs): + with np.testing.suppress_warnings() as sup: + sup.filter(SmallSampleWarning, too_small_1d_omit) + res = hypotest(*data1d, *args, nan_policy=nan_policy, **kwds) + # shouldn't complain if there are no NaNs + else: + res = hypotest(*data1d, *args, nan_policy=nan_policy, **kwds) + res_1db = unpacker(res) + + assert_allclose(res_1db, res_1da, rtol=1e-15) + res_1d[i] = res_1db + + res_1d = np.moveaxis(res_1d, -1, 0) + + # Perform a vectorized call to the hypothesis test. + + # If `nan_policy == 'raise'`, check that it raises the appropriate error. + # Test is done, so return + if nan_policy == 'raise' and not data_generator == "all_finite": + message = 'The input contains nan values' + with pytest.raises(ValueError, match=message): + hypotest(*data, axis=axis, nan_policy=nan_policy, *args, **kwds) + return + + # If `nan_policy == 'omit', we might be left with a small sample. + # Check for the appropriate warning. + if (nan_policy == 'omit' and data_generator in {"all_nans", "mixed"} + and hypotest not in too_small_special_case_funcs): + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + res = hypotest(*data, axis=axis, nan_policy=nan_policy, *args, **kwds) + else: # otherwise, there should be no warning + res = hypotest(*data, axis=axis, nan_policy=nan_policy, *args, **kwds) + + # Compare against the output against looping over 1D slices + res_nd = unpacker(res) + + assert_allclose(res_nd, res_1d, rtol=1e-14) + + +@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs", + "paired", "unpacker"), axis_nan_policy_cases) +@pytest.mark.parametrize(("nan_policy"), ("propagate", "omit", "raise")) +@pytest.mark.parametrize(("data_generator"), + ("all_nans", "all_finite", "mixed", "empty")) +def test_axis_nan_policy_axis_is_None(hypotest, args, kwds, n_samples, + n_outputs, paired, unpacker, nan_policy, + data_generator): + # check for correct behavior when `axis=None` + if not unpacker: + def unpacker(res): + return res + + rng = np.random.default_rng(0) + + if data_generator == "empty": + data = [rng.random((2, 0)) for i in range(n_samples)] + else: + data = [rng.random((2, 20)) for i in range(n_samples)] + + if data_generator == "mixed": + masks = [rng.random((2, 20)) > 0.9 for i in range(n_samples)] + for sample, mask in zip(data, masks): + sample[mask] = np.nan + elif data_generator == "all_nans": + data = [sample * np.nan for sample in data] + + data_raveled = [sample.ravel() for sample in data] + + if nan_policy == 'raise' and data_generator not in {"all_finite", "empty"}: + message = 'The input contains nan values' + + # check for correct behavior whether or not data is 1d to begin with + with pytest.raises(ValueError, match=message): + hypotest(*data, axis=None, nan_policy=nan_policy, + *args, **kwds) + with pytest.raises(ValueError, match=message): + hypotest(*data_raveled, axis=None, nan_policy=nan_policy, + *args, **kwds) + + return + + # behavior of reference implementation with 1d input, public function with 1d + # input, and public function with Nd input and `axis=None` should be consistent. + # This means: + # - If the reference version raises an error or emits a warning, it's because + # the sample is too small, so check that the public function emits an + # appropriate "too small" warning + # - Any results returned by the three versions should be the same. + with warnings.catch_warnings(): # treat warnings as errors + warnings.simplefilter("error") + + ea_str, eb_str, ec_str = None, None, None + try: + res1da = nan_policy_1d(hypotest, data_raveled, unpacker, *args, + n_outputs=n_outputs, nan_policy=nan_policy, + paired=paired, _no_deco=True, **kwds) + except (RuntimeWarning, ValueError, ZeroDivisionError) as ea: + res1da = None + ea_str = str(ea) + + try: + res1db = hypotest(*data_raveled, *args, nan_policy=nan_policy, **kwds) + except SmallSampleWarning as eb: + eb_str = str(eb) + + try: + res1dc = hypotest(*data, *args, axis=None, nan_policy=nan_policy, **kwds) + except SmallSampleWarning as ec: + ec_str = str(ec) + + if ea_str or eb_str or ec_str: # *if* there is some sort of error or warning + # If the reference implemented generated an error or warning, make sure the + # message was one of the expected "too small" messages. Note that some + # functions don't complain at all without the decorator; that's OK, too. + ok_msg = any([str(ea_str).startswith(msg) for msg in too_small_messages]) + assert (ea_str is None) or ok_msg + + # make sure the wrapped function emits the *intended* warning + desired_warnings = {too_small_1d_omit, too_small_1d_not_omit} + assert str(eb_str) in desired_warnings + assert str(ec_str) in desired_warnings + + with warnings.catch_warnings(): # ignore warnings to get return value + warnings.simplefilter("ignore") + res1db = hypotest(*data_raveled, *args, nan_policy=nan_policy, **kwds) + res1dc = hypotest(*data, *args, axis=None, nan_policy=nan_policy, **kwds) + + # Make sure any results returned by reference/public function are identical + # and all attributes are *NumPy* scalars + res1db, res1dc = unpacker(res1db), unpacker(res1dc) + assert_equal(res1dc, res1db) + all_results = list(res1db) + list(res1dc) + + if res1da is not None: + assert_allclose(res1db, res1da, rtol=1e-15) + all_results += list(res1da) + + for item in all_results: + assert np.issubdtype(item.dtype, np.number) + assert np.isscalar(item) + + +# Test keepdims for: +# - Axis negative, positive, None, and tuple +# - 1D with no NaNs +# - 1D with NaN propagation +# - Zero-sized output +# We're working on making `stats` quieter, but that's not what this test +# is about. For now, we expect all sorts of warnings here due to small samples. +@pytest.mark.filterwarnings('ignore::UserWarning') +@pytest.mark.filterwarnings('ignore::RuntimeWarning') +@pytest.mark.parametrize("nan_policy", ("omit", "propagate")) +@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs", + "paired", "unpacker"), axis_nan_policy_cases) +@pytest.mark.parametrize( + ("sample_shape", "axis_cases"), + (((2, 3, 3, 4), (None, 0, -1, (0, 2), (1, -1), (3, 1, 2, 0))), + ((10, ), (0, -1)), + ((20, 0), (0, 1))) +) +def test_keepdims(hypotest, args, kwds, n_samples, n_outputs, paired, unpacker, + sample_shape, axis_cases, nan_policy): + small_sample_raises = {stats.skewtest, stats.kurtosistest, stats.normaltest, + stats.differential_entropy} + if sample_shape == (2, 3, 3, 4) and hypotest in small_sample_raises: + pytest.skip("Sample too small; test raises error.") + # test if keepdims parameter works correctly + if not unpacker: + def unpacker(res): + return res + rng = np.random.default_rng(0) + data = [rng.random(sample_shape) for _ in range(n_samples)] + nan_data = [sample.copy() for sample in data] + nan_mask = [rng.random(sample_shape) < 0.2 for _ in range(n_samples)] + for sample, mask in zip(nan_data, nan_mask): + sample[mask] = np.nan + for axis in axis_cases: + expected_shape = list(sample_shape) + if axis is None: + expected_shape = np.ones(len(sample_shape)) + else: + if isinstance(axis, int): + expected_shape[axis] = 1 + else: + for ax in axis: + expected_shape[ax] = 1 + expected_shape = tuple(expected_shape) + res = unpacker(hypotest(*data, *args, axis=axis, keepdims=True, + **kwds)) + res_base = unpacker(hypotest(*data, *args, axis=axis, keepdims=False, + **kwds)) + nan_res = unpacker(hypotest(*nan_data, *args, axis=axis, + keepdims=True, nan_policy=nan_policy, + **kwds)) + nan_res_base = unpacker(hypotest(*nan_data, *args, axis=axis, + keepdims=False, + nan_policy=nan_policy, **kwds)) + for r, r_base, rn, rn_base in zip(res, res_base, nan_res, + nan_res_base): + assert r.shape == expected_shape + r = np.squeeze(r, axis=axis) + assert_allclose(r, r_base, atol=1e-16) + assert rn.shape == expected_shape + rn = np.squeeze(rn, axis=axis) + # ideally assert_equal, but `combine_pvalues` failed on 32-bit build + assert_allclose(rn, rn_base, atol=1e-16) + + +@pytest.mark.parametrize(("fun", "nsamp"), + [(stats.kstat, 1), + (stats.kstatvar, 1)]) +def test_hypotest_back_compat_no_axis(fun, nsamp): + m, n = 8, 9 + + rng = np.random.default_rng(0) + x = rng.random((nsamp, m, n)) + res = fun(*x) + res2 = fun(*x, _no_deco=True) + res3 = fun([xi.ravel() for xi in x]) + assert_equal(res, res2) + assert_equal(res, res3) + + +@pytest.mark.parametrize(("axis"), (0, 1, 2)) +def test_axis_nan_policy_decorated_positional_axis(axis): + # Test for correct behavior of function decorated with + # _axis_nan_policy_decorator whether `axis` is provided as positional or + # keyword argument + + shape = (8, 9, 10) + rng = np.random.default_rng(0) + x = rng.random(shape) + y = rng.random(shape) + res1 = stats.mannwhitneyu(x, y, True, 'two-sided', axis) + res2 = stats.mannwhitneyu(x, y, True, 'two-sided', axis=axis) + assert_equal(res1, res2) + + message = "mannwhitneyu() got multiple values for argument 'axis'" + with pytest.raises(TypeError, match=re.escape(message)): + stats.mannwhitneyu(x, y, True, 'two-sided', axis, axis=axis) + + +def test_axis_nan_policy_decorated_positional_args(): + # Test for correct behavior of function decorated with + # _axis_nan_policy_decorator when function accepts *args + + shape = (3, 8, 9, 10) + rng = np.random.default_rng(0) + x = rng.random(shape) + x[0, 0, 0, 0] = np.nan + stats.kruskal(*x) + + message = "kruskal() got an unexpected keyword argument 'samples'" + with pytest.raises(TypeError, match=re.escape(message)): + stats.kruskal(samples=x) + + with pytest.raises(TypeError, match=re.escape(message)): + stats.kruskal(*x, samples=x) + + +def test_axis_nan_policy_decorated_keyword_samples(): + # Test for correct behavior of function decorated with + # _axis_nan_policy_decorator whether samples are provided as positional or + # keyword arguments + + shape = (2, 8, 9, 10) + rng = np.random.default_rng(0) + x = rng.random(shape) + x[0, 0, 0, 0] = np.nan + res1 = stats.mannwhitneyu(*x) + res2 = stats.mannwhitneyu(x=x[0], y=x[1]) + assert_equal(res1, res2) + + message = "mannwhitneyu() got multiple values for argument" + with pytest.raises(TypeError, match=re.escape(message)): + stats.mannwhitneyu(*x, x=x[0], y=x[1]) + + +@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs", + "paired", "unpacker"), axis_nan_policy_cases) +def test_axis_nan_policy_decorated_pickled(hypotest, args, kwds, n_samples, + n_outputs, paired, unpacker): + if "ttest_ci" in hypotest.__name__: + pytest.skip("Can't pickle functions defined within functions.") + + rng = np.random.default_rng(0) + + # Some hypothesis tests return a non-iterable that needs an `unpacker` to + # extract the statistic and p-value. For those that don't: + if not unpacker: + def unpacker(res): + return res + + data = rng.uniform(size=(n_samples, 2, 30)) + pickled_hypotest = pickle.dumps(hypotest) + unpickled_hypotest = pickle.loads(pickled_hypotest) + res1 = unpacker(hypotest(*data, *args, axis=-1, **kwds)) + res2 = unpacker(unpickled_hypotest(*data, *args, axis=-1, **kwds)) + assert_allclose(res1, res2, rtol=1e-12) + + +def test_check_empty_inputs(): + # Test that _check_empty_inputs is doing its job, at least for single- + # sample inputs. (Multi-sample functionality is tested below.) + # If the input sample is not empty, it should return None. + # If the input sample is empty, it should return an array of NaNs or an + # empty array of appropriate shape. np.mean is used as a reference for the + # output because, like the statistics calculated by these functions, + # it works along and "consumes" `axis` but preserves the other axes. + for i in range(5): + for combo in combinations_with_replacement([0, 1, 2], i): + for axis in range(len(combo)): + samples = (np.zeros(combo),) + output = stats._axis_nan_policy._check_empty_inputs(samples, + axis) + if output is not None: + with np.testing.suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Mean of empty slice.") + sup.filter(RuntimeWarning, "invalid value encountered") + reference = samples[0].mean(axis=axis) + np.testing.assert_equal(output, reference) + + +def _check_arrays_broadcastable(arrays, axis): + # https://numpy.org/doc/stable/user/basics.broadcasting.html + # "When operating on two arrays, NumPy compares their shapes element-wise. + # It starts with the trailing (i.e. rightmost) dimensions and works its + # way left. + # Two dimensions are compatible when + # 1. they are equal, or + # 2. one of them is 1 + # ... + # Arrays do not need to have the same number of dimensions." + # (Clarification: if the arrays are compatible according to the criteria + # above and an array runs out of dimensions, it is still compatible.) + # Below, we follow the rules above except ignoring `axis` + + n_dims = max([arr.ndim for arr in arrays]) + if axis is not None: + # convert to negative axis + axis = (-n_dims + axis) if axis >= 0 else axis + + for dim in range(1, n_dims+1): # we'll index from -1 to -n_dims, inclusive + if -dim == axis: + continue # ignore lengths along `axis` + + dim_lengths = set() + for arr in arrays: + if dim <= arr.ndim and arr.shape[-dim] != 1: + dim_lengths.add(arr.shape[-dim]) + + if len(dim_lengths) > 1: + return False + return True + + +@pytest.mark.slow +@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs", + "paired", "unpacker"), axis_nan_policy_cases) +def test_empty(hypotest, args, kwds, n_samples, n_outputs, paired, unpacker): + # test for correct output shape when at least one input is empty + if hypotest in {stats.kruskal, stats.friedmanchisquare} and not SCIPY_XSLOW: + pytest.skip("Too slow.") + + if hypotest in override_propagate_funcs: + reason = "Doesn't follow the usual pattern. Tested separately." + pytest.skip(reason=reason) + + if unpacker is None: + unpacker = lambda res: (res[0], res[1]) # noqa: E731 + + def small_data_generator(n_samples, n_dims): + + def small_sample_generator(n_dims): + # return all possible "small" arrays in up to n_dim dimensions + for i in n_dims: + # "small" means with size along dimension either 0 or 1 + for combo in combinations_with_replacement([0, 1, 2], i): + yield np.zeros(combo) + + # yield all possible combinations of small samples + gens = [small_sample_generator(n_dims) for i in range(n_samples)] + yield from product(*gens) + + n_dims = [1, 2, 3] + for samples in small_data_generator(n_samples, n_dims): + + # this test is only for arrays of zero size + if not any(sample.size == 0 for sample in samples): + continue + + max_axis = max(sample.ndim for sample in samples) + + # need to test for all valid values of `axis` parameter, too + for axis in range(-max_axis, max_axis): + + try: + # After broadcasting, all arrays are the same shape, so + # the shape of the output should be the same as a single- + # sample statistic. Use np.mean as a reference. + concat = stats._stats_py._broadcast_concatenate(samples, axis, + paired=paired) + with np.testing.suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Mean of empty slice.") + sup.filter(RuntimeWarning, "invalid value encountered") + expected = np.mean(concat, axis=axis) * np.nan + + if hypotest in empty_special_case_funcs: + empty_val = hypotest(*([[]]*len(samples)), *args, **kwds) + expected = np.asarray(expected) + mask = np.isnan(expected) + expected[mask] = empty_val + expected = expected[()] + + if expected.size and hypotest not in too_small_special_case_funcs: + message = (too_small_1d_not_omit if max_axis == 1 + else too_small_nd_not_omit) + with pytest.warns(SmallSampleWarning, match=message): + res = hypotest(*samples, *args, axis=axis, **kwds) + else: + with np.testing.suppress_warnings() as sup: + # f_oneway special case + sup.filter(SmallSampleWarning, "all input arrays have length 1") + res = hypotest(*samples, *args, axis=axis, **kwds) + res = unpacker(res) + + for i in range(n_outputs): + assert_equal(res[i], expected) + + except ValueError: + # confirm that the arrays truly are not broadcastable + assert not _check_arrays_broadcastable(samples, + None if paired else axis) + + # confirm that _both_ `_broadcast_concatenate` and `hypotest` + # produce this information. + message = "Array shapes are incompatible for broadcasting." + with pytest.raises(ValueError, match=message): + stats._stats_py._broadcast_concatenate(samples, axis, paired) + with pytest.raises(ValueError, match=message): + hypotest(*samples, *args, axis=axis, **kwds) + + +def paired_non_broadcastable_cases(): + rng = np.random.default_rng(91359824598245) + for case in axis_nan_policy_cases: + hypotest, args, kwds, n_samples, n_outputs, paired, unpacker = case + if n_samples == 1: # broadcasting only needed with >1 sample + continue + yield case + (rng,) + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs", + "paired", "unpacker", "rng"), + paired_non_broadcastable_cases()) +def test_non_broadcastable(hypotest, args, kwds, n_samples, n_outputs, paired, + unpacker, rng, axis): + # test for correct error message when shapes are not broadcastable + + get_samples = True + while get_samples: + samples = [rng.random(size=rng.integers(2, 100, size=2)) + for i in range(n_samples)] + # if samples are broadcastable, try again + get_samples = _check_arrays_broadcastable(samples, axis=axis) + + message = "Array shapes are incompatible for broadcasting." + with pytest.raises(ValueError, match=message): + hypotest(*samples, *args, **kwds) + + if not paired: # there's another test for paired-sample statistics + return + + # Previously, paired sample statistics did not raise an error + # message when the shapes were broadcastable except along `axis` + # https://github.com/scipy/scipy/pull/19578#pullrequestreview-1766857165 + shape = rng.integers(2, 10, size=2) + most_samples = [rng.random(size=shape) for i in range(n_samples-1)] + shape = list(shape) + shape[axis] += 1 + other_sample = rng.random(size=shape) + with pytest.raises(ValueError, match=message): + hypotest(other_sample, *most_samples, *args, **kwds) + + +def test_masked_array_2_sentinel_array(): + # prepare arrays + np.random.seed(0) + A = np.random.rand(10, 11, 12) + B = np.random.rand(12) + mask = A < 0.5 + A = np.ma.masked_array(A, mask) + + # set arbitrary elements to special values + # (these values might have been considered for use as sentinel values) + max_float = np.finfo(np.float64).max + max_float2 = np.nextafter(max_float, -np.inf) + max_float3 = np.nextafter(max_float2, -np.inf) + A[3, 4, 1] = np.nan + A[4, 5, 2] = np.inf + A[5, 6, 3] = max_float + B[8] = np.nan + B[7] = np.inf + B[6] = max_float2 + + # convert masked A to array with sentinel value, don't modify B + out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([A, B]) + A_out, B_out = out_arrays + + # check that good sentinel value was chosen (according to intended logic) + assert (sentinel != max_float) and (sentinel != max_float2) + assert sentinel == max_float3 + + # check that output arrays are as intended + A_reference = A.data + A_reference[A.mask] = sentinel + np.testing.assert_array_equal(A_out, A_reference) + assert B_out is B + + +@skip_xp_invalid_arg +def test_masked_dtype(): + # When _masked_arrays_2_sentinel_arrays was first added, it always + # upcast the arrays to np.float64. After gh16662, check expected promotion + # and that the expected sentinel is found. + + # these are important because the max of the promoted dtype is the first + # candidate to be the sentinel value + max16 = np.iinfo(np.int16).max + max128c = np.finfo(np.complex128).max + + # a is a regular array, b has masked elements, and c has no masked elements + a = np.array([1, 2, max16], dtype=np.int16) + b = np.ma.array([1, 2, 1], dtype=np.int8, mask=[0, 1, 0]) + c = np.ma.array([1, 2, 1], dtype=np.complex128, mask=[0, 0, 0]) + + # check integer masked -> sentinel conversion + out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([a, b]) + a_out, b_out = out_arrays + assert sentinel == max16-1 # not max16 because max16 was in the data + assert b_out.dtype == np.int16 # check expected promotion + assert_allclose(b_out, [b[0], sentinel, b[-1]]) # check sentinel placement + assert a_out is a # not a masked array, so left untouched + assert not isinstance(b_out, np.ma.MaskedArray) # b became regular array + + # similarly with complex + out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([b, c]) + b_out, c_out = out_arrays + assert sentinel == max128c # max128c was not in the data + assert b_out.dtype == np.complex128 # b got promoted + assert_allclose(b_out, [b[0], sentinel, b[-1]]) # check sentinel placement + assert not isinstance(b_out, np.ma.MaskedArray) # b became regular array + assert not isinstance(c_out, np.ma.MaskedArray) # c became regular array + + # Also, check edge case when a sentinel value cannot be found in the data + min8, max8 = np.iinfo(np.int8).min, np.iinfo(np.int8).max + a = np.arange(min8, max8+1, dtype=np.int8) # use all possible values + mask1 = np.zeros_like(a, dtype=bool) + mask0 = np.zeros_like(a, dtype=bool) + + # a masked value can be used as the sentinel + mask1[1] = True + a1 = np.ma.array(a, mask=mask1) + out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([a1]) + assert sentinel == min8+1 + + # unless it's the smallest possible; skipped for simiplicity (see code) + mask0[0] = True + a0 = np.ma.array(a, mask=mask0) + message = "This function replaces masked elements with sentinel..." + with pytest.raises(ValueError, match=message): + _masked_arrays_2_sentinel_arrays([a0]) + + # test that dtype is preserved in functions + a = np.ma.array([1, 2, 3], mask=[0, 1, 0], dtype=np.float32) + assert stats.gmean(a).dtype == np.float32 + + +def test_masked_stat_1d(): + # basic test of _axis_nan_policy_factory with 1D masked sample + males = [19, 22, 16, 29, 24] + females = [20, 11, 17, 12] + res = stats.mannwhitneyu(males, females) + + # same result when extra nan is omitted + females2 = [20, 11, 17, np.nan, 12] + res2 = stats.mannwhitneyu(males, females2, nan_policy='omit') + np.testing.assert_array_equal(res2, res) + + # same result when extra element is masked + females3 = [20, 11, 17, 1000, 12] + mask3 = [False, False, False, True, False] + females3 = np.ma.masked_array(females3, mask=mask3) + res3 = stats.mannwhitneyu(males, females3) + np.testing.assert_array_equal(res3, res) + + # same result when extra nan is omitted and additional element is masked + females4 = [20, 11, 17, np.nan, 1000, 12] + mask4 = [False, False, False, False, True, False] + females4 = np.ma.masked_array(females4, mask=mask4) + res4 = stats.mannwhitneyu(males, females4, nan_policy='omit') + np.testing.assert_array_equal(res4, res) + + # same result when extra elements, including nan, are masked + females5 = [20, 11, 17, np.nan, 1000, 12] + mask5 = [False, False, False, True, True, False] + females5 = np.ma.masked_array(females5, mask=mask5) + res5 = stats.mannwhitneyu(males, females5, nan_policy='propagate') + res6 = stats.mannwhitneyu(males, females5, nan_policy='raise') + np.testing.assert_array_equal(res5, res) + np.testing.assert_array_equal(res6, res) + + +@pytest.mark.filterwarnings('ignore:After omitting NaNs...') +@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...') +@skip_xp_invalid_arg +@pytest.mark.parametrize(("axis"), range(-3, 3)) +def test_masked_stat_3d(axis): + # basic test of _axis_nan_policy_factory with 3D masked sample + np.random.seed(0) + a = np.random.rand(3, 4, 5) + b = np.random.rand(4, 5) + c = np.random.rand(4, 1) + + mask_a = a < 0.1 + mask_c = [False, False, False, True] + a_masked = np.ma.masked_array(a, mask=mask_a) + c_masked = np.ma.masked_array(c, mask=mask_c) + + a_nans = a.copy() + a_nans[mask_a] = np.nan + c_nans = c.copy() + c_nans[mask_c] = np.nan + + res = stats.kruskal(a_nans, b, c_nans, nan_policy='omit', axis=axis) + res2 = stats.kruskal(a_masked, b, c_masked, axis=axis) + np.testing.assert_array_equal(res, res2) + + +@pytest.mark.filterwarnings('ignore:After omitting NaNs...') +@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...') +@skip_xp_invalid_arg +def test_mixed_mask_nan_1(): + # targeted test of _axis_nan_policy_factory with 2D masked sample: + # omitting samples with masks and nan_policy='omit' are equivalent + # also checks paired-sample sentinel value removal + m, n = 3, 20 + axis = -1 + + np.random.seed(0) + a = np.random.rand(m, n) + b = np.random.rand(m, n) + mask_a1 = np.random.rand(m, n) < 0.2 + mask_a2 = np.random.rand(m, n) < 0.1 + mask_b1 = np.random.rand(m, n) < 0.15 + mask_b2 = np.random.rand(m, n) < 0.15 + mask_a1[2, :] = True + + a_nans = a.copy() + b_nans = b.copy() + a_nans[mask_a1 | mask_a2] = np.nan + b_nans[mask_b1 | mask_b2] = np.nan + + a_masked1 = np.ma.masked_array(a, mask=mask_a1) + b_masked1 = np.ma.masked_array(b, mask=mask_b1) + a_masked1[mask_a2] = np.nan + b_masked1[mask_b2] = np.nan + + a_masked2 = np.ma.masked_array(a, mask=mask_a2) + b_masked2 = np.ma.masked_array(b, mask=mask_b2) + a_masked2[mask_a1] = np.nan + b_masked2[mask_b1] = np.nan + + a_masked3 = np.ma.masked_array(a, mask=(mask_a1 | mask_a2)) + b_masked3 = np.ma.masked_array(b, mask=(mask_b1 | mask_b2)) + + res = stats.wilcoxon(a_nans, b_nans, nan_policy='omit', axis=axis) + res1 = stats.wilcoxon(a_masked1, b_masked1, nan_policy='omit', axis=axis) + res2 = stats.wilcoxon(a_masked2, b_masked2, nan_policy='omit', axis=axis) + res3 = stats.wilcoxon(a_masked3, b_masked3, nan_policy='raise', axis=axis) + res4 = stats.wilcoxon(a_masked3, b_masked3, + nan_policy='propagate', axis=axis) + + np.testing.assert_array_equal(res1, res) + np.testing.assert_array_equal(res2, res) + np.testing.assert_array_equal(res3, res) + np.testing.assert_array_equal(res4, res) + + +@pytest.mark.filterwarnings('ignore:After omitting NaNs...') +@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...') +@skip_xp_invalid_arg +def test_mixed_mask_nan_2(): + # targeted test of _axis_nan_policy_factory with 2D masked sample: + # check for expected interaction between masks and nans + + # Cases here are + # [mixed nan/mask, all nans, all masked, + # unmasked nan, masked nan, unmasked non-nan] + a = [[1, np.nan, 2], [np.nan, np.nan, np.nan], [1, 2, 3], + [1, np.nan, 3], [1, np.nan, 3], [1, 2, 3]] + mask = [[1, 0, 1], [0, 0, 0], [1, 1, 1], + [0, 0, 0], [0, 1, 0], [0, 0, 0]] + a_masked = np.ma.masked_array(a, mask=mask) + b = [[4, 5, 6]] + ref1 = stats.ranksums([1, 3], [4, 5, 6]) + ref2 = stats.ranksums([1, 2, 3], [4, 5, 6]) + + # nan_policy = 'omit' + # all elements are removed from first three rows + # middle element is removed from fourth and fifth rows + # no elements removed from last row + res = stats.ranksums(a_masked, b, nan_policy='omit', axis=-1) + stat_ref = [np.nan, np.nan, np.nan, + ref1.statistic, ref1.statistic, ref2.statistic] + p_ref = [np.nan, np.nan, np.nan, + ref1.pvalue, ref1.pvalue, ref2.pvalue] + np.testing.assert_array_equal(res.statistic, stat_ref) + np.testing.assert_array_equal(res.pvalue, p_ref) + + # nan_policy = 'propagate' + # nans propagate in first, second, and fourth row + # all elements are removed by mask from third row + # middle element is removed from fifth row + # no elements removed from last row + res = stats.ranksums(a_masked, b, nan_policy='propagate', axis=-1) + stat_ref = [np.nan, np.nan, np.nan, + np.nan, ref1.statistic, ref2.statistic] + p_ref = [np.nan, np.nan, np.nan, + np.nan, ref1.pvalue, ref2.pvalue] + np.testing.assert_array_equal(res.statistic, stat_ref) + np.testing.assert_array_equal(res.pvalue, p_ref) + + +def test_axis_None_vs_tuple(): + # `axis` `None` should be equivalent to tuple with all axes + shape = (3, 8, 9, 10) + rng = np.random.default_rng(0) + x = rng.random(shape) + res = stats.kruskal(*x, axis=None) + res2 = stats.kruskal(*x, axis=(0, 1, 2)) + np.testing.assert_array_equal(res, res2) + + +def test_axis_None_vs_tuple_with_broadcasting(): + # `axis` `None` should be equivalent to tuple with all axes, + # which should be equivalent to raveling the arrays before passing them + rng = np.random.default_rng(0) + x = rng.random((5, 1)) + y = rng.random((1, 5)) + x2, y2 = np.broadcast_arrays(x, y) + + res0 = stats.mannwhitneyu(x.ravel(), y.ravel()) + res1 = stats.mannwhitneyu(x, y, axis=None) + res2 = stats.mannwhitneyu(x, y, axis=(0, 1)) + res3 = stats.mannwhitneyu(x2.ravel(), y2.ravel()) + + assert res1 == res0 + assert res2 == res0 + assert res3 != res0 + + +@pytest.mark.parametrize(("axis"), + list(permutations(range(-3, 3), 2)) + [(-4, 1)]) +def test_other_axis_tuples(axis): + # Check that _axis_nan_policy_factory treats all `axis` tuples as expected + rng = np.random.default_rng(0) + shape_x = (4, 5, 6) + shape_y = (1, 6) + x = rng.random(shape_x) + y = rng.random(shape_y) + axis_original = axis + + # convert axis elements to positive + axis = tuple([(i if i >= 0 else 3 + i) for i in axis]) + axis = sorted(axis) + + if len(set(axis)) != len(axis): + message = "`axis` must contain only distinct elements" + with pytest.raises(AxisError, match=re.escape(message)): + stats.mannwhitneyu(x, y, axis=axis_original) + return + + if axis[0] < 0 or axis[-1] > 2: + message = "`axis` is out of bounds for array of dimension 3" + with pytest.raises(AxisError, match=re.escape(message)): + stats.mannwhitneyu(x, y, axis=axis_original) + return + + res = stats.mannwhitneyu(x, y, axis=axis_original) + + # reference behavior + not_axis = {0, 1, 2} - set(axis) # which axis is not part of `axis` + not_axis = next(iter(not_axis)) # take it out of the set + + x2 = x + shape_y_broadcasted = [1, 1, 6] + shape_y_broadcasted[not_axis] = shape_x[not_axis] + y2 = np.broadcast_to(y, shape_y_broadcasted) + + m = x2.shape[not_axis] + x2 = np.moveaxis(x2, axis, (1, 2)) + y2 = np.moveaxis(y2, axis, (1, 2)) + x2 = np.reshape(x2, (m, -1)) + y2 = np.reshape(y2, (m, -1)) + res2 = stats.mannwhitneyu(x2, y2, axis=1) + + np.testing.assert_array_equal(res, res2) + + +@pytest.mark.filterwarnings('ignore:After omitting NaNs...') +@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...') +@skip_xp_invalid_arg +@pytest.mark.parametrize( + ("weighted_fun_name, unpacker"), + [ + ("gmean", lambda x: x), + ("hmean", lambda x: x), + ("pmean", lambda x: x), + ("combine_pvalues", lambda x: (x.pvalue, x.statistic)), + ], +) +def test_mean_mixed_mask_nan_weights(weighted_fun_name, unpacker): + # targeted test of _axis_nan_policy_factory with 2D masked sample: + # omitting samples with masks and nan_policy='omit' are equivalent + # also checks paired-sample sentinel value removal + + if weighted_fun_name == 'pmean': + def weighted_fun(a, **kwargs): + return stats.pmean(a, p=0.42, **kwargs) + else: + weighted_fun = getattr(stats, weighted_fun_name) + + def func(*args, **kwargs): + return unpacker(weighted_fun(*args, **kwargs)) + + m, n = 3, 20 + axis = -1 + + rng = np.random.default_rng(6541968121) + a = rng.uniform(size=(m, n)) + b = rng.uniform(size=(m, n)) + mask_a1 = rng.uniform(size=(m, n)) < 0.2 + mask_a2 = rng.uniform(size=(m, n)) < 0.1 + mask_b1 = rng.uniform(size=(m, n)) < 0.15 + mask_b2 = rng.uniform(size=(m, n)) < 0.15 + mask_a1[2, :] = True + + a_nans = a.copy() + b_nans = b.copy() + a_nans[mask_a1 | mask_a2] = np.nan + b_nans[mask_b1 | mask_b2] = np.nan + + a_masked1 = np.ma.masked_array(a, mask=mask_a1) + b_masked1 = np.ma.masked_array(b, mask=mask_b1) + a_masked1[mask_a2] = np.nan + b_masked1[mask_b2] = np.nan + + a_masked2 = np.ma.masked_array(a, mask=mask_a2) + b_masked2 = np.ma.masked_array(b, mask=mask_b2) + a_masked2[mask_a1] = np.nan + b_masked2[mask_b1] = np.nan + + a_masked3 = np.ma.masked_array(a, mask=(mask_a1 | mask_a2)) + b_masked3 = np.ma.masked_array(b, mask=(mask_b1 | mask_b2)) + + with np.testing.suppress_warnings() as sup: + message = 'invalid value encountered' + sup.filter(RuntimeWarning, message) + res = func(a_nans, weights=b_nans, nan_policy="omit", axis=axis) + res1 = func(a_masked1, weights=b_masked1, nan_policy="omit", axis=axis) + res2 = func(a_masked2, weights=b_masked2, nan_policy="omit", axis=axis) + res3 = func(a_masked3, weights=b_masked3, nan_policy="raise", axis=axis) + res4 = func(a_masked3, weights=b_masked3, nan_policy="propagate", axis=axis) + + np.testing.assert_array_equal(res1, res) + np.testing.assert_array_equal(res2, res) + np.testing.assert_array_equal(res3, res) + np.testing.assert_array_equal(res4, res) + + +def test_raise_invalid_args_g17713(): + # other cases are handled in: + # test_axis_nan_policy_decorated_positional_axis - multiple values for arg + # test_axis_nan_policy_decorated_positional_args - unexpected kwd arg + message = "got an unexpected keyword argument" + with pytest.raises(TypeError, match=message): + stats.gmean([1, 2, 3], invalid_arg=True) + + message = " got multiple values for argument" + with pytest.raises(TypeError, match=message): + stats.gmean([1, 2, 3], a=True) + + message = "missing 1 required positional argument" + with pytest.raises(TypeError, match=message): + stats.gmean() + + message = "takes from 1 to 4 positional arguments but 5 were given" + with pytest.raises(TypeError, match=message): + stats.gmean([1, 2, 3], 0, float, [1, 1, 1], 10) + + +@pytest.mark.parametrize('dtype', [np.int16, np.float32, np.complex128]) +def test_array_like_input(dtype): + # Check that `_axis_nan_policy`-decorated functions work with custom + # containers that are coercible to numeric arrays + + class ArrLike: + def __init__(self, x, dtype): + self._x = x + self._dtype = dtype + + def __array__(self, dtype=None, copy=None): + return np.asarray(x, dtype=self._dtype) + + x = [1]*2 + [3, 4, 5] + res = stats.mode(ArrLike(x, dtype=dtype)) + assert res.mode == 1 + assert res.count == 2 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_binned_statistic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_binned_statistic.py new file mode 100644 index 0000000000000000000000000000000000000000..932df07f2e489c137b378841fd749272ae0bcc89 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_binned_statistic.py @@ -0,0 +1,568 @@ +import numpy as np +from numpy.testing import assert_allclose +import pytest +from pytest import raises as assert_raises +from scipy.stats import (binned_statistic, binned_statistic_2d, + binned_statistic_dd) +from scipy._lib._util import check_random_state + +from .common_tests import check_named_results + + +class TestBinnedStatistic: + + @classmethod + def setup_class(cls): + rng = check_random_state(9865) + cls.x = rng.uniform(size=100) + cls.y = rng.uniform(size=100) + cls.v = rng.uniform(size=100) + cls.X = rng.uniform(size=(100, 3)) + cls.w = rng.uniform(size=100) + cls.u = rng.uniform(size=100) + 1e6 + + def test_1d_count(self): + x = self.x + v = self.v + + count1, edges1, bc = binned_statistic(x, v, 'count', bins=10) + count2, edges2 = np.histogram(x, bins=10) + + assert_allclose(count1, count2) + assert_allclose(edges1, edges2) + + def test_gh5927(self): + # smoke test for gh5927 - binned_statistic was using `is` for string + # comparison + x = self.x + v = self.v + statistics = ['mean', 'median', 'count', 'sum'] + for statistic in statistics: + binned_statistic(x, v, statistic, bins=10) + + def test_big_number_std(self): + # tests for numerical stability of std calculation + # see issue gh-10126 for more + x = self.x + u = self.u + stat1, edges1, bc = binned_statistic(x, u, 'std', bins=10) + stat2, edges2, bc = binned_statistic(x, u, np.std, bins=10) + + assert_allclose(stat1, stat2) + + def test_empty_bins_std(self): + # tests that std returns gives nan for empty bins + x = self.x + u = self.u + print(binned_statistic(x, u, 'count', bins=1000)) + stat1, edges1, bc = binned_statistic(x, u, 'std', bins=1000) + stat2, edges2, bc = binned_statistic(x, u, np.std, bins=1000) + + assert_allclose(stat1, stat2) + + def test_non_finite_inputs_and_int_bins(self): + # if either `values` or `sample` contain np.inf or np.nan throw + # see issue gh-9010 for more + x = self.x + u = self.u + orig = u[0] + u[0] = np.inf + assert_raises(ValueError, binned_statistic, u, x, 'std', bins=10) + # need to test for non-python specific ints, e.g. np.int8, np.int64 + assert_raises(ValueError, binned_statistic, u, x, 'std', + bins=np.int64(10)) + u[0] = np.nan + assert_raises(ValueError, binned_statistic, u, x, 'count', bins=10) + # replace original value, u belongs the class + u[0] = orig + + def test_1d_result_attributes(self): + x = self.x + v = self.v + + res = binned_statistic(x, v, 'count', bins=10) + attributes = ('statistic', 'bin_edges', 'binnumber') + check_named_results(res, attributes) + + def test_1d_sum(self): + x = self.x + v = self.v + + sum1, edges1, bc = binned_statistic(x, v, 'sum', bins=10) + sum2, edges2 = np.histogram(x, bins=10, weights=v) + + assert_allclose(sum1, sum2) + assert_allclose(edges1, edges2) + + def test_1d_mean(self): + x = self.x + v = self.v + + stat1, edges1, bc = binned_statistic(x, v, 'mean', bins=10) + stat2, edges2, bc = binned_statistic(x, v, np.mean, bins=10) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_1d_std(self): + x = self.x + v = self.v + + stat1, edges1, bc = binned_statistic(x, v, 'std', bins=10) + stat2, edges2, bc = binned_statistic(x, v, np.std, bins=10) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_1d_min(self): + x = self.x + v = self.v + + stat1, edges1, bc = binned_statistic(x, v, 'min', bins=10) + stat2, edges2, bc = binned_statistic(x, v, np.min, bins=10) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_1d_max(self): + x = self.x + v = self.v + + stat1, edges1, bc = binned_statistic(x, v, 'max', bins=10) + stat2, edges2, bc = binned_statistic(x, v, np.max, bins=10) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_1d_median(self): + x = self.x + v = self.v + + stat1, edges1, bc = binned_statistic(x, v, 'median', bins=10) + stat2, edges2, bc = binned_statistic(x, v, np.median, bins=10) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_1d_bincode(self): + x = self.x[:20] + v = self.v[:20] + + count1, edges1, bc = binned_statistic(x, v, 'count', bins=3) + bc2 = np.array([3, 2, 1, 3, 2, 3, 3, 3, 3, 1, 1, 3, 3, 1, 2, 3, 1, + 1, 2, 1]) + + bcount = [(bc == i).sum() for i in np.unique(bc)] + + assert_allclose(bc, bc2) + assert_allclose(bcount, count1) + + def test_1d_range_keyword(self): + # Regression test for gh-3063, range can be (min, max) or [(min, max)] + np.random.seed(9865) + x = np.arange(30) + data = np.random.random(30) + + mean, bins, _ = binned_statistic(x[:15], data[:15]) + mean_range, bins_range, _ = binned_statistic(x, data, range=[(0, 14)]) + mean_range2, bins_range2, _ = binned_statistic(x, data, range=(0, 14)) + + assert_allclose(mean, mean_range) + assert_allclose(bins, bins_range) + assert_allclose(mean, mean_range2) + assert_allclose(bins, bins_range2) + + def test_1d_multi_values(self): + x = self.x + v = self.v + w = self.w + + stat1v, edges1v, bc1v = binned_statistic(x, v, 'mean', bins=10) + stat1w, edges1w, bc1w = binned_statistic(x, w, 'mean', bins=10) + stat2, edges2, bc2 = binned_statistic(x, [v, w], 'mean', bins=10) + + assert_allclose(stat2[0], stat1v) + assert_allclose(stat2[1], stat1w) + assert_allclose(edges1v, edges2) + assert_allclose(bc1v, bc2) + + def test_2d_count(self): + x = self.x + y = self.y + v = self.v + + count1, binx1, biny1, bc = binned_statistic_2d( + x, y, v, 'count', bins=5) + count2, binx2, biny2 = np.histogram2d(x, y, bins=5) + + assert_allclose(count1, count2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_result_attributes(self): + x = self.x + y = self.y + v = self.v + + res = binned_statistic_2d(x, y, v, 'count', bins=5) + attributes = ('statistic', 'x_edge', 'y_edge', 'binnumber') + check_named_results(res, attributes) + + def test_2d_sum(self): + x = self.x + y = self.y + v = self.v + + sum1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'sum', bins=5) + sum2, binx2, biny2 = np.histogram2d(x, y, bins=5, weights=v) + + assert_allclose(sum1, sum2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_mean(self): + x = self.x + y = self.y + v = self.v + + stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'mean', bins=5) + stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.mean, bins=5) + + assert_allclose(stat1, stat2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_mean_unicode(self): + x = self.x + y = self.y + v = self.v + stat1, binx1, biny1, bc = binned_statistic_2d( + x, y, v, 'mean', bins=5) + stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.mean, bins=5) + assert_allclose(stat1, stat2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_std(self): + x = self.x + y = self.y + v = self.v + + stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'std', bins=5) + stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.std, bins=5) + + assert_allclose(stat1, stat2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_min(self): + x = self.x + y = self.y + v = self.v + + stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'min', bins=5) + stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.min, bins=5) + + assert_allclose(stat1, stat2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_max(self): + x = self.x + y = self.y + v = self.v + + stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'max', bins=5) + stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.max, bins=5) + + assert_allclose(stat1, stat2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_median(self): + x = self.x + y = self.y + v = self.v + + stat1, binx1, biny1, bc = binned_statistic_2d( + x, y, v, 'median', bins=5) + stat2, binx2, biny2, bc = binned_statistic_2d( + x, y, v, np.median, bins=5) + + assert_allclose(stat1, stat2) + assert_allclose(binx1, binx2) + assert_allclose(biny1, biny2) + + def test_2d_bincode(self): + x = self.x[:20] + y = self.y[:20] + v = self.v[:20] + + count1, binx1, biny1, bc = binned_statistic_2d( + x, y, v, 'count', bins=3) + bc2 = np.array([17, 11, 6, 16, 11, 17, 18, 17, 17, 7, 6, 18, 16, + 6, 11, 16, 6, 6, 11, 8]) + + bcount = [(bc == i).sum() for i in np.unique(bc)] + + assert_allclose(bc, bc2) + count1adj = count1[count1.nonzero()] + assert_allclose(bcount, count1adj) + + def test_2d_multi_values(self): + x = self.x + y = self.y + v = self.v + w = self.w + + stat1v, binx1v, biny1v, bc1v = binned_statistic_2d( + x, y, v, 'mean', bins=8) + stat1w, binx1w, biny1w, bc1w = binned_statistic_2d( + x, y, w, 'mean', bins=8) + stat2, binx2, biny2, bc2 = binned_statistic_2d( + x, y, [v, w], 'mean', bins=8) + + assert_allclose(stat2[0], stat1v) + assert_allclose(stat2[1], stat1w) + assert_allclose(binx1v, binx2) + assert_allclose(biny1w, biny2) + assert_allclose(bc1v, bc2) + + def test_2d_binnumbers_unraveled(self): + x = self.x + y = self.y + v = self.v + + stat, edgesx, bcx = binned_statistic(x, v, 'mean', bins=20) + stat, edgesy, bcy = binned_statistic(y, v, 'mean', bins=10) + + stat2, edgesx2, edgesy2, bc2 = binned_statistic_2d( + x, y, v, 'mean', bins=(20, 10), expand_binnumbers=True) + + bcx3 = np.searchsorted(edgesx, x, side='right') + bcy3 = np.searchsorted(edgesy, y, side='right') + + # `numpy.searchsorted` is non-inclusive on right-edge, compensate + bcx3[x == x.max()] -= 1 + bcy3[y == y.max()] -= 1 + + assert_allclose(bcx, bc2[0]) + assert_allclose(bcy, bc2[1]) + assert_allclose(bcx3, bc2[0]) + assert_allclose(bcy3, bc2[1]) + + def test_dd_count(self): + X = self.X + v = self.v + + count1, edges1, bc = binned_statistic_dd(X, v, 'count', bins=3) + count2, edges2 = np.histogramdd(X, bins=3) + + assert_allclose(count1, count2) + assert_allclose(edges1, edges2) + + def test_dd_result_attributes(self): + X = self.X + v = self.v + + res = binned_statistic_dd(X, v, 'count', bins=3) + attributes = ('statistic', 'bin_edges', 'binnumber') + check_named_results(res, attributes) + + def test_dd_sum(self): + X = self.X + v = self.v + + sum1, edges1, bc = binned_statistic_dd(X, v, 'sum', bins=3) + sum2, edges2 = np.histogramdd(X, bins=3, weights=v) + sum3, edges3, bc = binned_statistic_dd(X, v, np.sum, bins=3) + + assert_allclose(sum1, sum2) + assert_allclose(edges1, edges2) + assert_allclose(sum1, sum3) + assert_allclose(edges1, edges3) + + def test_dd_mean(self): + X = self.X + v = self.v + + stat1, edges1, bc = binned_statistic_dd(X, v, 'mean', bins=3) + stat2, edges2, bc = binned_statistic_dd(X, v, np.mean, bins=3) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_dd_std(self): + X = self.X + v = self.v + + stat1, edges1, bc = binned_statistic_dd(X, v, 'std', bins=3) + stat2, edges2, bc = binned_statistic_dd(X, v, np.std, bins=3) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_dd_min(self): + X = self.X + v = self.v + + stat1, edges1, bc = binned_statistic_dd(X, v, 'min', bins=3) + stat2, edges2, bc = binned_statistic_dd(X, v, np.min, bins=3) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_dd_max(self): + X = self.X + v = self.v + + stat1, edges1, bc = binned_statistic_dd(X, v, 'max', bins=3) + stat2, edges2, bc = binned_statistic_dd(X, v, np.max, bins=3) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_dd_median(self): + X = self.X + v = self.v + + stat1, edges1, bc = binned_statistic_dd(X, v, 'median', bins=3) + stat2, edges2, bc = binned_statistic_dd(X, v, np.median, bins=3) + + assert_allclose(stat1, stat2) + assert_allclose(edges1, edges2) + + def test_dd_bincode(self): + X = self.X[:20] + v = self.v[:20] + + count1, edges1, bc = binned_statistic_dd(X, v, 'count', bins=3) + bc2 = np.array([63, 33, 86, 83, 88, 67, 57, 33, 42, 41, 82, 83, 92, + 32, 36, 91, 43, 87, 81, 81]) + + bcount = [(bc == i).sum() for i in np.unique(bc)] + + assert_allclose(bc, bc2) + count1adj = count1[count1.nonzero()] + assert_allclose(bcount, count1adj) + + def test_dd_multi_values(self): + X = self.X + v = self.v + w = self.w + + for stat in ["count", "sum", "mean", "std", "min", "max", "median", + np.std]: + stat1v, edges1v, bc1v = binned_statistic_dd(X, v, stat, bins=8) + stat1w, edges1w, bc1w = binned_statistic_dd(X, w, stat, bins=8) + stat2, edges2, bc2 = binned_statistic_dd(X, [v, w], stat, bins=8) + assert_allclose(stat2[0], stat1v) + assert_allclose(stat2[1], stat1w) + assert_allclose(edges1v, edges2) + assert_allclose(edges1w, edges2) + assert_allclose(bc1v, bc2) + + def test_dd_binnumbers_unraveled(self): + X = self.X + v = self.v + + stat, edgesx, bcx = binned_statistic(X[:, 0], v, 'mean', bins=15) + stat, edgesy, bcy = binned_statistic(X[:, 1], v, 'mean', bins=20) + stat, edgesz, bcz = binned_statistic(X[:, 2], v, 'mean', bins=10) + + stat2, edges2, bc2 = binned_statistic_dd( + X, v, 'mean', bins=(15, 20, 10), expand_binnumbers=True) + + assert_allclose(bcx, bc2[0]) + assert_allclose(bcy, bc2[1]) + assert_allclose(bcz, bc2[2]) + + def test_dd_binned_statistic_result(self): + # NOTE: tests the reuse of bin_edges from previous call + x = np.random.random((10000, 3)) + v = np.random.random(10000) + bins = np.linspace(0, 1, 10) + bins = (bins, bins, bins) + + result = binned_statistic_dd(x, v, 'mean', bins=bins) + stat = result.statistic + + result = binned_statistic_dd(x, v, 'mean', + binned_statistic_result=result) + stat2 = result.statistic + + assert_allclose(stat, stat2) + + def test_dd_zero_dedges(self): + x = np.random.random((10000, 3)) + v = np.random.random(10000) + bins = np.linspace(0, 1, 10) + bins = np.append(bins, 1) + bins = (bins, bins, bins) + with assert_raises(ValueError, match='difference is numerically 0'): + binned_statistic_dd(x, v, 'mean', bins=bins) + + def test_dd_range_errors(self): + # Test that descriptive exceptions are raised as appropriate for bad + # values of the `range` argument. (See gh-12996) + with assert_raises(ValueError, + match='In range, start must be <= stop'): + binned_statistic_dd([self.y], self.v, + range=[[1, 0]]) + with assert_raises( + ValueError, + match='In dimension 1 of range, start must be <= stop'): + binned_statistic_dd([self.x, self.y], self.v, + range=[[1, 0], [0, 1]]) + with assert_raises( + ValueError, + match='In dimension 2 of range, start must be <= stop'): + binned_statistic_dd([self.x, self.y], self.v, + range=[[0, 1], [1, 0]]) + with assert_raises( + ValueError, + match='range given for 1 dimensions; 2 required'): + binned_statistic_dd([self.x, self.y], self.v, + range=[[0, 1]]) + + def test_binned_statistic_float32(self): + X = np.array([0, 0.42358226], dtype=np.float32) + stat, _, _ = binned_statistic(X, None, 'count', bins=5) + assert_allclose(stat, np.array([1, 0, 0, 0, 1], dtype=np.float64)) + + def test_gh14332(self): + # Test the wrong output when the `sample` is close to bin edge + x = [] + size = 20 + for i in range(size): + x += [1-0.1**i] + + bins = np.linspace(0,1,11) + sum1, edges1, bc = binned_statistic_dd(x, np.ones(len(x)), + bins=[bins], statistic='sum') + sum2, edges2 = np.histogram(x, bins=bins) + + assert_allclose(sum1, sum2) + assert_allclose(edges1[0], edges2) + + @pytest.mark.parametrize("dtype", [np.float64, np.complex128]) + @pytest.mark.parametrize("statistic", [np.mean, np.median, np.sum, np.std, + np.min, np.max, 'count', + lambda x: (x**2).sum(), + lambda x: (x**2).sum() * 1j]) + def test_dd_all(self, dtype, statistic): + def ref_statistic(x): + return len(x) if statistic == 'count' else statistic(x) + + rng = np.random.default_rng(3704743126639371) + n = 10 + x = rng.random(size=n) + i = x >= 0.5 + v = rng.random(size=n) + if dtype is np.complex128: + v = v + rng.random(size=n)*1j + + stat, _, _ = binned_statistic_dd(x, v, statistic, bins=2) + ref = np.array([ref_statistic(v[~i]), ref_statistic(v[i])]) + assert_allclose(stat, ref) + assert stat.dtype == np.result_type(ref.dtype, np.float64) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_censored_data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_censored_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ae71dcfaccf899645051287f8944131ec48a1eee --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_censored_data.py @@ -0,0 +1,152 @@ +# Tests for the CensoredData class. + +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_array_equal +from scipy.stats import CensoredData + + +class TestCensoredData: + + def test_basic(self): + uncensored = [1] + left = [0] + right = [2, 5] + interval = [[2, 3]] + data = CensoredData(uncensored, left=left, right=right, + interval=interval) + assert_equal(data._uncensored, uncensored) + assert_equal(data._left, left) + assert_equal(data._right, right) + assert_equal(data._interval, interval) + + udata = data._uncensor() + assert_equal(udata, np.concatenate((uncensored, left, right, + np.mean(interval, axis=1)))) + + def test_right_censored(self): + x = np.array([0, 3, 2.5]) + is_censored = np.array([0, 1, 0], dtype=bool) + data = CensoredData.right_censored(x, is_censored) + assert_equal(data._uncensored, x[~is_censored]) + assert_equal(data._right, x[is_censored]) + assert_equal(data._left, []) + assert_equal(data._interval, np.empty((0, 2))) + + def test_left_censored(self): + x = np.array([0, 3, 2.5]) + is_censored = np.array([0, 1, 0], dtype=bool) + data = CensoredData.left_censored(x, is_censored) + assert_equal(data._uncensored, x[~is_censored]) + assert_equal(data._left, x[is_censored]) + assert_equal(data._right, []) + assert_equal(data._interval, np.empty((0, 2))) + + def test_interval_censored_basic(self): + a = [0.5, 2.0, 3.0, 5.5] + b = [1.0, 2.5, 3.5, 7.0] + data = CensoredData.interval_censored(low=a, high=b) + assert_array_equal(data._interval, np.array(list(zip(a, b)))) + assert data._uncensored.shape == (0,) + assert data._left.shape == (0,) + assert data._right.shape == (0,) + + def test_interval_censored_mixed(self): + # This is actually a mix of uncensored, left-censored, right-censored + # and interval-censored data. Check that when the `interval_censored` + # class method is used, the data is correctly separated into the + # appropriate arrays. + a = [0.5, -np.inf, -13.0, 2.0, 1.0, 10.0, -1.0] + b = [0.5, 2500.0, np.inf, 3.0, 1.0, 11.0, np.inf] + data = CensoredData.interval_censored(low=a, high=b) + assert_array_equal(data._interval, [[2.0, 3.0], [10.0, 11.0]]) + assert_array_equal(data._uncensored, [0.5, 1.0]) + assert_array_equal(data._left, [2500.0]) + assert_array_equal(data._right, [-13.0, -1.0]) + + def test_interval_to_other_types(self): + # The interval parameter can represent uncensored and + # left- or right-censored data. Test the conversion of such + # an example to the canonical form in which the different + # types have been split into the separate arrays. + interval = np.array([[0, 1], # interval-censored + [2, 2], # not censored + [3, 3], # not censored + [9, np.inf], # right-censored + [8, np.inf], # right-censored + [-np.inf, 0], # left-censored + [1, 2]]) # interval-censored + data = CensoredData(interval=interval) + assert_equal(data._uncensored, [2, 3]) + assert_equal(data._left, [0]) + assert_equal(data._right, [9, 8]) + assert_equal(data._interval, [[0, 1], [1, 2]]) + + def test_empty_arrays(self): + data = CensoredData(uncensored=[], left=[], right=[], interval=[]) + assert data._uncensored.shape == (0,) + assert data._left.shape == (0,) + assert data._right.shape == (0,) + assert data._interval.shape == (0, 2) + assert len(data) == 0 + + def test_invalid_constructor_args(self): + with pytest.raises(ValueError, match='must be a one-dimensional'): + CensoredData(uncensored=[[1, 2, 3]]) + with pytest.raises(ValueError, match='must be a one-dimensional'): + CensoredData(left=[[1, 2, 3]]) + with pytest.raises(ValueError, match='must be a one-dimensional'): + CensoredData(right=[[1, 2, 3]]) + with pytest.raises(ValueError, match='must be a two-dimensional'): + CensoredData(interval=[[1, 2, 3]]) + + with pytest.raises(ValueError, match='must not contain nan'): + CensoredData(uncensored=[1, np.nan, 2]) + with pytest.raises(ValueError, match='must not contain nan'): + CensoredData(left=[1, np.nan, 2]) + with pytest.raises(ValueError, match='must not contain nan'): + CensoredData(right=[1, np.nan, 2]) + with pytest.raises(ValueError, match='must not contain nan'): + CensoredData(interval=[[1, np.nan], [2, 3]]) + + with pytest.raises(ValueError, + match='both values must not be infinite'): + CensoredData(interval=[[1, 3], [2, 9], [np.inf, np.inf]]) + + with pytest.raises(ValueError, + match='left value must not exceed the right'): + CensoredData(interval=[[1, 0], [2, 2]]) + + @pytest.mark.parametrize('func', [CensoredData.left_censored, + CensoredData.right_censored]) + def test_invalid_left_right_censored_args(self, func): + with pytest.raises(ValueError, + match='`x` must be one-dimensional'): + func([[1, 2, 3]], [0, 1, 1]) + with pytest.raises(ValueError, + match='`censored` must be one-dimensional'): + func([1, 2, 3], [[0, 1, 1]]) + with pytest.raises(ValueError, match='`x` must not contain'): + func([1, 2, np.nan], [0, 1, 1]) + with pytest.raises(ValueError, match='must have the same length'): + func([1, 2, 3], [0, 0, 1, 1]) + + def test_invalid_censored_args(self): + with pytest.raises(ValueError, + match='`low` must be a one-dimensional'): + CensoredData.interval_censored(low=[[3]], high=[4, 5]) + with pytest.raises(ValueError, + match='`high` must be a one-dimensional'): + CensoredData.interval_censored(low=[3], high=[[4, 5]]) + with pytest.raises(ValueError, match='`low` must not contain'): + CensoredData.interval_censored([1, 2, np.nan], [0, 1, 1]) + with pytest.raises(ValueError, match='must have the same length'): + CensoredData.interval_censored([1, 2, 3], [0, 0, 1, 1]) + + def test_count_censored(self): + x = [1, 2, 3] + # data1 has no censored data. + data1 = CensoredData(x) + assert data1.num_censored() == 0 + data2 = CensoredData(uncensored=[2.5], left=[10], interval=[[0, 1]]) + assert data2.num_censored() == 2 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_contingency.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_contingency.py new file mode 100644 index 0000000000000000000000000000000000000000..aa83e05d7da6b3d21d5515a332344c2347f0d7eb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_contingency.py @@ -0,0 +1,294 @@ +import numpy as np +from numpy.testing import (assert_equal, assert_array_equal, + assert_array_almost_equal, assert_approx_equal, + assert_allclose) +import pytest +from pytest import raises as assert_raises +from scipy import stats +from scipy.special import xlogy +from scipy.stats.contingency import (margins, expected_freq, + chi2_contingency, association) + + +def test_margins(): + a = np.array([1]) + m = margins(a) + assert_equal(len(m), 1) + m0 = m[0] + assert_array_equal(m0, np.array([1])) + + a = np.array([[1]]) + m0, m1 = margins(a) + expected0 = np.array([[1]]) + expected1 = np.array([[1]]) + assert_array_equal(m0, expected0) + assert_array_equal(m1, expected1) + + a = np.arange(12).reshape(2, 6) + m0, m1 = margins(a) + expected0 = np.array([[15], [51]]) + expected1 = np.array([[6, 8, 10, 12, 14, 16]]) + assert_array_equal(m0, expected0) + assert_array_equal(m1, expected1) + + a = np.arange(24).reshape(2, 3, 4) + m0, m1, m2 = margins(a) + expected0 = np.array([[[66]], [[210]]]) + expected1 = np.array([[[60], [92], [124]]]) + expected2 = np.array([[[60, 66, 72, 78]]]) + assert_array_equal(m0, expected0) + assert_array_equal(m1, expected1) + assert_array_equal(m2, expected2) + + +def test_expected_freq(): + assert_array_equal(expected_freq([1]), np.array([1.0])) + + observed = np.array([[[2, 0], [0, 2]], [[0, 2], [2, 0]], [[1, 1], [1, 1]]]) + e = expected_freq(observed) + assert_array_equal(e, np.ones_like(observed)) + + observed = np.array([[10, 10, 20], [20, 20, 20]]) + e = expected_freq(observed) + correct = np.array([[12., 12., 16.], [18., 18., 24.]]) + assert_array_almost_equal(e, correct) + + +class TestChi2Contingency: + def test_chi2_contingency_trivial(self): + # Some very simple tests for chi2_contingency. + + # A trivial case + obs = np.array([[1, 2], [1, 2]]) + chi2, p, dof, expected = chi2_contingency(obs, correction=False) + assert_equal(chi2, 0.0) + assert_equal(p, 1.0) + assert_equal(dof, 1) + assert_array_equal(obs, expected) + + # A *really* trivial case: 1-D data. + obs = np.array([1, 2, 3]) + chi2, p, dof, expected = chi2_contingency(obs, correction=False) + assert_equal(chi2, 0.0) + assert_equal(p, 1.0) + assert_equal(dof, 0) + assert_array_equal(obs, expected) + + def test_chi2_contingency_R(self): + # Some test cases that were computed independently, using R. + + # Rcode = \ + # """ + # # Data vector. + # data <- c( + # 12, 34, 23, 4, 47, 11, + # 35, 31, 11, 34, 10, 18, + # 12, 32, 9, 18, 13, 19, + # 12, 12, 14, 9, 33, 25 + # ) + # + # # Create factor tags:r=rows, c=columns, t=tiers + # r <- factor(gl(4, 2*3, 2*3*4, labels=c("r1", "r2", "r3", "r4"))) + # c <- factor(gl(3, 1, 2*3*4, labels=c("c1", "c2", "c3"))) + # t <- factor(gl(2, 3, 2*3*4, labels=c("t1", "t2"))) + # + # # 3-way Chi squared test of independence + # s = summary(xtabs(data~r+c+t)) + # print(s) + # """ + # Routput = \ + # """ + # Call: xtabs(formula = data ~ r + c + t) + # Number of cases in table: 478 + # Number of factors: 3 + # Test for independence of all factors: + # Chisq = 102.17, df = 17, p-value = 3.514e-14 + # """ + obs = np.array( + [[[12, 34, 23], + [35, 31, 11], + [12, 32, 9], + [12, 12, 14]], + [[4, 47, 11], + [34, 10, 18], + [18, 13, 19], + [9, 33, 25]]]) + chi2, p, dof, expected = chi2_contingency(obs) + assert_approx_equal(chi2, 102.17, significant=5) + assert_approx_equal(p, 3.514e-14, significant=4) + assert_equal(dof, 17) + + # Rcode = \ + # """ + # # Data vector. + # data <- c( + # # + # 12, 17, + # 11, 16, + # # + # 11, 12, + # 15, 16, + # # + # 23, 15, + # 30, 22, + # # + # 14, 17, + # 15, 16 + # ) + # + # # Create factor tags:r=rows, c=columns, d=depths(?), t=tiers + # r <- factor(gl(2, 2, 2*2*2*2, labels=c("r1", "r2"))) + # c <- factor(gl(2, 1, 2*2*2*2, labels=c("c1", "c2"))) + # d <- factor(gl(2, 4, 2*2*2*2, labels=c("d1", "d2"))) + # t <- factor(gl(2, 8, 2*2*2*2, labels=c("t1", "t2"))) + # + # # 4-way Chi squared test of independence + # s = summary(xtabs(data~r+c+d+t)) + # print(s) + # """ + # Routput = \ + # """ + # Call: xtabs(formula = data ~ r + c + d + t) + # Number of cases in table: 262 + # Number of factors: 4 + # Test for independence of all factors: + # Chisq = 8.758, df = 11, p-value = 0.6442 + # """ + obs = np.array( + [[[[12, 17], + [11, 16]], + [[11, 12], + [15, 16]]], + [[[23, 15], + [30, 22]], + [[14, 17], + [15, 16]]]]) + chi2, p, dof, expected = chi2_contingency(obs) + assert_approx_equal(chi2, 8.758, significant=4) + assert_approx_equal(p, 0.6442, significant=4) + assert_equal(dof, 11) + + def test_chi2_contingency_g(self): + c = np.array([[15, 60], [15, 90]]) + g, p, dof, e = chi2_contingency(c, lambda_='log-likelihood', + correction=False) + assert_allclose(g, 2*xlogy(c, c/e).sum()) + + g, p, dof, e = chi2_contingency(c, lambda_='log-likelihood', + correction=True) + c_corr = c + np.array([[-0.5, 0.5], [0.5, -0.5]]) + assert_allclose(g, 2*xlogy(c_corr, c_corr/e).sum()) + + c = np.array([[10, 12, 10], [12, 10, 10]]) + g, p, dof, e = chi2_contingency(c, lambda_='log-likelihood') + assert_allclose(g, 2*xlogy(c, c/e).sum()) + + def test_chi2_contingency_bad_args(self): + # Test that "bad" inputs raise a ValueError. + + # Negative value in the array of observed frequencies. + obs = np.array([[-1, 10], [1, 2]]) + assert_raises(ValueError, chi2_contingency, obs) + + # The zeros in this will result in zeros in the array + # of expected frequencies. + obs = np.array([[0, 1], [0, 1]]) + assert_raises(ValueError, chi2_contingency, obs) + + # A degenerate case: `observed` has size 0. + obs = np.empty((0, 8)) + assert_raises(ValueError, chi2_contingency, obs) + + def test_chi2_contingency_yates_gh13875(self): + # Magnitude of Yates' continuity correction should not exceed difference + # between expected and observed value of the statistic; see gh-13875 + observed = np.array([[1573, 3], [4, 0]]) + p = chi2_contingency(observed)[1] + assert_allclose(p, 1, rtol=1e-12) + + @pytest.mark.parametrize("correction", [False, True]) + def test_result(self, correction): + obs = np.array([[1, 2], [1, 2]]) + res = chi2_contingency(obs, correction=correction) + assert_equal((res.statistic, res.pvalue, res.dof, res.expected_freq), res) + + @pytest.mark.slow + def test_exact_permutation(self): + table = np.arange(4).reshape(2, 2) + ref_statistic = chi2_contingency(table, correction=False).statistic + ref_pvalue = stats.fisher_exact(table).pvalue + method = stats.PermutationMethod(n_resamples=50000) + res = chi2_contingency(table, correction=False, method=method) + assert_equal(res.statistic, ref_statistic) + assert_allclose(res.pvalue, ref_pvalue, rtol=1e-15) + + @pytest.mark.slow + @pytest.mark.parametrize('method', (stats.PermutationMethod, + stats.MonteCarloMethod)) + def test_resampling_randomized(self, method): + rng = np.random.default_rng(2592340925) + # need to have big sum for asymptotic approximation to be good + rows = [300, 1000, 800] + cols = [200, 400, 800, 700] + table = stats.random_table(rows, cols, seed=rng).rvs() + res = chi2_contingency(table, correction=False, method=method(rng=rng)) + ref = chi2_contingency(table, correction=False) + assert_equal(res.statistic, ref.statistic) + assert_allclose(res.pvalue, ref.pvalue, atol=5e-3) + assert_equal(res.dof, np.nan) + assert_equal(res.expected_freq, ref.expected_freq) + + def test_resampling_invalid_args(self): + table = np.arange(8).reshape(2, 2, 2) + + method = stats.PermutationMethod() + message = "Use of `method` is only compatible with two-way tables." + with pytest.raises(ValueError, match=message): + chi2_contingency(table, correction=False, method=method) + + table = np.arange(4).reshape(2, 2) + + method = stats.PermutationMethod() + message = "`correction=True` is not compatible with..." + with pytest.raises(ValueError, match=message): + chi2_contingency(table, method=method) + + method = stats.MonteCarloMethod() + message = "`lambda_=2` is not compatible with..." + with pytest.raises(ValueError, match=message): + chi2_contingency(table, correction=False, lambda_=2, method=method) + + method = 'herring' + message = "`method='herring'` not recognized; if provided, `method`..." + with pytest.raises(ValueError, match=message): + chi2_contingency(table, correction=False, method=method) + + method = stats.MonteCarloMethod(rvs=stats.norm.rvs) + message = "If the `method` argument of `chi2_contingency` is..." + with pytest.raises(ValueError, match=message): + chi2_contingency(table, correction=False, method=method) + + +def test_bad_association_args(): + # Invalid Test Statistic + assert_raises(ValueError, association, [[1, 2], [3, 4]], "X") + # Invalid array shape + assert_raises(ValueError, association, [[[1, 2]], [[3, 4]]], "cramer") + # chi2_contingency exception + assert_raises(ValueError, association, [[-1, 10], [1, 2]], 'cramer') + # Invalid Array Item Data Type + assert_raises(ValueError, association, + np.array([[1, 2], ["dd", 4]], dtype=object), 'cramer') + + +@pytest.mark.parametrize('stat, expected', + [('cramer', 0.09222412010290792), + ('tschuprow', 0.0775509319944633), + ('pearson', 0.12932925727138758)]) +def test_assoc(stat, expected): + # 2d Array + obs1 = np.array([[12, 13, 14, 15, 16], + [17, 16, 18, 19, 11], + [9, 15, 14, 12, 11]]) + a = association(observed=obs1, method=stat) + assert_allclose(a, expected) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf1b45e8d48ab2733a0d434b1174604dd239059 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous.py @@ -0,0 +1,1879 @@ +import os +import pickle +from copy import deepcopy + +import numpy as np +from numpy import inf +import pytest +from numpy.testing import assert_allclose, assert_equal +from hypothesis import strategies, given, reproduce_failure, settings # noqa: F401 +import hypothesis.extra.numpy as npst + +from scipy import stats +from scipy.stats._fit import _kolmogorov_smirnov +from scipy.stats._ksstats import kolmogn +from scipy.stats import qmc +from scipy.stats._distr_params import distcont +from scipy.stats._distribution_infrastructure import ( + _Domain, _RealDomain, _Parameter, _Parameterization, _RealParameter, + ContinuousDistribution, ShiftedScaledDistribution, _fiinfo, + _generate_domain_support, Mixture) +from scipy.stats._new_distributions import StandardNormal, _LogUniform, _Gamma +from scipy.stats import Normal, Uniform + + +class Test_RealDomain: + rng = np.random.default_rng(349849812549824) + + def test_iv(self): + domain = _RealDomain(endpoints=('a', 'b')) + message = "The endpoints of the distribution are defined..." + with pytest.raises(TypeError, match=message): + domain.get_numerical_endpoints(dict) + + + @pytest.mark.parametrize('x', [rng.uniform(10, 10, size=(2, 3, 4)), + -np.inf, np.pi]) + def test_contains_simple(self, x): + # Test `contains` when endpoints are defined by constants + a, b = -np.inf, np.pi + domain = _RealDomain(endpoints=(a, b), inclusive=(False, True)) + assert_equal(domain.contains(x), (a < x) & (x <= b)) + + @pytest.mark.slow + @given(shapes=npst.mutually_broadcastable_shapes(num_shapes=3, min_side=0), + inclusive_a=strategies.booleans(), + inclusive_b=strategies.booleans(), + data=strategies.data()) + def test_contains(self, shapes, inclusive_a, inclusive_b, data): + # Test `contains` when endpoints are defined by parameters + input_shapes, result_shape = shapes + shape_a, shape_b, shape_x = input_shapes + + # Without defining min and max values, I spent forever trying to set + # up a valid test without overflows or similar just drawing arrays. + a_elements = dict(allow_nan=False, allow_infinity=False, + min_value=-1e3, max_value=1) + b_elements = dict(allow_nan=False, allow_infinity=False, + min_value=2, max_value=1e3) + a = data.draw(npst.arrays(npst.floating_dtypes(), + shape_a, elements=a_elements)) + b = data.draw(npst.arrays(npst.floating_dtypes(), + shape_b, elements=b_elements)) + # ensure some points are to the left, some to the right, and some + # are exactly on the boundary + d = b - a + x = np.concatenate([np.linspace(a-d, a, 10), + np.linspace(a, b, 10), + np.linspace(b, b+d, 10)]) + # Domain is defined by two parameters, 'a' and 'b' + domain = _RealDomain(endpoints=('a', 'b'), + inclusive=(inclusive_a, inclusive_b)) + domain.define_parameters(_RealParameter('a', domain=_RealDomain()), + _RealParameter('b', domain=_RealDomain())) + # Check that domain and string evaluation give the same result + res = domain.contains(x, dict(a=a, b=b)) + + # Apparently, `np.float16([2]) < np.float32(2.0009766)` is False + # but `np.float16([2]) < np.float32([2.0009766])` is True + # dtype = np.result_type(a.dtype, b.dtype, x.dtype) + # a, b, x = a.astype(dtype), b.astype(dtype), x.astype(dtype) + # unclear whether we should be careful about this, since it will be + # fixed with NEP50. Just do what makes the test pass. + left_comparison = '<=' if inclusive_a else '<' + right_comparison = '<=' if inclusive_b else '<' + ref = eval(f'(a {left_comparison} x) & (x {right_comparison} b)') + assert_equal(res, ref) + + @pytest.mark.parametrize('case', [ + (-np.inf, np.pi, False, True, r"(-\infty, \pi]"), + ('a', 5, True, False, "[a, 5)") + ]) + def test_str(self, case): + domain = _RealDomain(endpoints=case[:2], inclusive=case[2:4]) + assert str(domain) == case[4] + + @pytest.mark.slow + @given(a=strategies.one_of( + strategies.decimals(allow_nan=False), + strategies.characters(whitelist_categories="L"), # type: ignore[arg-type] + strategies.sampled_from(list(_Domain.symbols))), + b=strategies.one_of( + strategies.decimals(allow_nan=False), + strategies.characters(whitelist_categories="L"), # type: ignore[arg-type] + strategies.sampled_from(list(_Domain.symbols))), + inclusive_a=strategies.booleans(), + inclusive_b=strategies.booleans(), + ) + def test_str2(self, a, b, inclusive_a, inclusive_b): + # I wrote this independently from the implementation of __str__, but + # I imagine it looks pretty similar to __str__. + a = _Domain.symbols.get(a, a) + b = _Domain.symbols.get(b, b) + left_bracket = '[' if inclusive_a else '(' + right_bracket = ']' if inclusive_b else ')' + domain = _RealDomain(endpoints=(a, b), + inclusive=(inclusive_a, inclusive_b)) + ref = f"{left_bracket}{a}, {b}{right_bracket}" + assert str(domain) == ref + + def test_symbols_gh22137(self): + # `symbols` was accidentally shared between instances originally + # Check that this is no longer the case + domain1 = _RealDomain(endpoints=(0, 1)) + domain2 = _RealDomain(endpoints=(0, 1)) + assert domain1.symbols is not domain2.symbols + + +def draw_distribution_from_family(family, data, rng, proportions, min_side=0): + # If the distribution has parameters, choose a parameterization and + # draw broadcastable shapes for the parameter arrays. + n_parameterizations = family._num_parameterizations() + if n_parameterizations > 0: + i = data.draw(strategies.integers(0, max_value=n_parameterizations-1)) + n_parameters = family._num_parameters(i) + shapes, result_shape = data.draw( + npst.mutually_broadcastable_shapes(num_shapes=n_parameters, + min_side=min_side)) + dist = family._draw(shapes, rng=rng, proportions=proportions, + i_parameterization=i) + else: + dist = family._draw(rng=rng) + result_shape = tuple() + + # Draw a broadcastable shape for the arguments, and draw values for the + # arguments. + x_shape = data.draw(npst.broadcastable_shapes(result_shape, + min_side=min_side)) + x = dist._variable.draw(x_shape, parameter_values=dist._parameters, + proportions=proportions, rng=rng, region='typical') + x_result_shape = np.broadcast_shapes(x_shape, result_shape) + y_shape = data.draw(npst.broadcastable_shapes(x_result_shape, + min_side=min_side)) + y = dist._variable.draw(y_shape, parameter_values=dist._parameters, + proportions=proportions, rng=rng, region='typical') + xy_result_shape = np.broadcast_shapes(y_shape, x_result_shape) + p_domain = _RealDomain((0, 1), (True, True)) + p_var = _RealParameter('p', domain=p_domain) + p = p_var.draw(x_shape, proportions=proportions, rng=rng) + with np.errstate(divide='ignore', invalid='ignore'): + logp = np.log(p) + + return dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape + + +families = [ + StandardNormal, + Normal, + Uniform, + _LogUniform +] + + +class TestDistributions: + @pytest.mark.fail_slow(60) # need to break up check_moment_funcs + @settings(max_examples=20) + @pytest.mark.parametrize('family', families) + @given(data=strategies.data(), seed=strategies.integers(min_value=0)) + def test_support_moments_sample(self, family, data, seed): + rng = np.random.default_rng(seed) + + # relative proportions of valid, endpoint, out of bounds, and NaN params + proportions = (0.7, 0.1, 0.1, 0.1) + tmp = draw_distribution_from_family(family, data, rng, proportions) + dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape = tmp + sample_shape = data.draw(npst.array_shapes(min_dims=0, min_side=0, + max_side=20)) + + with np.errstate(invalid='ignore', divide='ignore'): + check_support(dist) + check_moment_funcs(dist, result_shape) # this needs to get split up + check_sample_shape_NaNs(dist, 'sample', sample_shape, result_shape, rng) + qrng = qmc.Halton(d=1, seed=rng) + check_sample_shape_NaNs(dist, 'sample', sample_shape, result_shape, qrng) + + @pytest.mark.fail_slow(10) + @pytest.mark.parametrize('family', families) + @pytest.mark.parametrize('func, methods, arg', + [('entropy', {'log/exp', 'quadrature'}, None), + ('logentropy', {'log/exp', 'quadrature'}, None), + ('median', {'icdf'}, None), + ('mode', {'optimization'}, None), + ('mean', {'cache'}, None), + ('variance', {'cache'}, None), + ('skewness', {'cache'}, None), + ('kurtosis', {'cache'}, None), + ('pdf', {'log/exp'}, 'x'), + ('logpdf', {'log/exp'}, 'x'), + ('logcdf', {'log/exp', 'complement', 'quadrature'}, 'x'), + ('cdf', {'log/exp', 'complement', 'quadrature'}, 'x'), + ('logccdf', {'log/exp', 'complement', 'quadrature'}, 'x'), + ('ccdf', {'log/exp', 'complement', 'quadrature'}, 'x'), + ('ilogccdf', {'complement', 'inversion'}, 'logp'), + ('iccdf', {'complement', 'inversion'}, 'p'), + ]) + @settings(max_examples=20) + @given(data=strategies.data(), seed=strategies.integers(min_value=0)) + def test_funcs(self, family, data, seed, func, methods, arg): + if family == Uniform and func == 'mode': + pytest.skip("Mode is not unique; `method`s disagree.") + + rng = np.random.default_rng(seed) + + # relative proportions of valid, endpoint, out of bounds, and NaN params + proportions = (0.7, 0.1, 0.1, 0.1) + tmp = draw_distribution_from_family(family, data, rng, proportions) + dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape = tmp + + args = {'x': x, 'p': p, 'logp': p} + with np.errstate(invalid='ignore', divide='ignore', over='ignore'): + if arg is None: + check_dist_func(dist, func, None, result_shape, methods) + elif arg in args: + check_dist_func(dist, func, args[arg], x_result_shape, methods) + + if func == 'variance': + assert_allclose(dist.standard_deviation()**2, dist.variance()) + + # invalid and divide are to be expected; maybe look into over + with np.errstate(invalid='ignore', divide='ignore', over='ignore'): + if not isinstance(dist, ShiftedScaledDistribution): + if func == 'cdf': + methods = {'quadrature'} + check_cdf2(dist, False, x, y, xy_result_shape, methods) + check_cdf2(dist, True, x, y, xy_result_shape, methods) + elif func == 'ccdf': + methods = {'addition'} + check_ccdf2(dist, False, x, y, xy_result_shape, methods) + check_ccdf2(dist, True, x, y, xy_result_shape, methods) + + def test_plot(self): + try: + import matplotlib.pyplot as plt + except ImportError: + return + + X = Uniform(a=0., b=1.) + ax = X.plot() + assert ax == plt.gca() + + @pytest.mark.parametrize('method_name', ['cdf', 'ccdf']) + def test_complement_safe(self, method_name): + X = stats.Normal() + X.tol = 1e-12 + p = np.asarray([1e-4, 1e-3]) + func = getattr(X, method_name) + ifunc = getattr(X, 'i'+method_name) + x = ifunc(p, method='formula') + p1 = func(x, method='complement_safe') + p2 = func(x, method='complement') + assert_equal(p1[1], p2[1]) + assert p1[0] != p2[0] + assert_allclose(p1[0], p[0], rtol=X.tol) + + @pytest.mark.parametrize('method_name', ['cdf', 'ccdf']) + def test_icomplement_safe(self, method_name): + X = stats.Normal() + X.tol = 1e-12 + p = np.asarray([1e-4, 1e-3]) + func = getattr(X, method_name) + ifunc = getattr(X, 'i'+method_name) + x1 = ifunc(p, method='complement_safe') + x2 = ifunc(p, method='complement') + assert_equal(x1[1], x2[1]) + assert x1[0] != x2[0] + assert_allclose(func(x1[0]), p[0], rtol=X.tol) + + def test_subtraction_safe(self): + X = stats.Normal() + X.tol = 1e-12 + + # Regular subtraction is fine in either tail (and of course, across tails) + x = [-11, -10, 10, 11] + y = [-10, -11, 11, 10] + p0 = X.cdf(x, y, method='quadrature') + p1 = X.cdf(x, y, method='subtraction_safe') + p2 = X.cdf(x, y, method='subtraction') + assert_equal(p2, p1) + assert_allclose(p1, p0, rtol=X.tol) + + # Safe subtraction is needed in special cases + x = np.asarray([-1e-20, -1e-21, 1e-20, 1e-21, -1e-20]) + y = np.asarray([-1e-21, -1e-20, 1e-21, 1e-20, 1e-20]) + p0 = X.pdf(0)*(y-x) + p1 = X.cdf(x, y, method='subtraction_safe') + p2 = X.cdf(x, y, method='subtraction') + assert_equal(p2, 0) + assert_allclose(p1, p0, rtol=X.tol) + + def test_logentropy_safe(self): + # simulate an `entropy` calculation over/underflowing with extreme parameters + class _Normal(stats.Normal): + def _entropy_formula(self, **params): + out = np.asarray(super()._entropy_formula(**params)) + out[0] = 0 + out[-1] = np.inf + return out + + X = _Normal(sigma=[1, 2, 3]) + with np.errstate(divide='ignore'): + res1 = X.logentropy(method='logexp_safe') + res2 = X.logentropy(method='logexp') + ref = X.logentropy(method='quadrature') + i_fl = [0, -1] # first and last + assert np.isinf(res2[i_fl]).all() + assert res1[1] == res2[1] + # quadrature happens to be perfectly accurate on some platforms + # assert res1[1] != ref[1] + assert_equal(res1[i_fl], ref[i_fl]) + + def test_logcdf2_safe(self): + # test what happens when 2-arg `cdf` underflows + X = stats.Normal(sigma=[1, 2, 3]) + x = [-301, 1, 300] + y = [-300, 2, 301] + with np.errstate(divide='ignore'): + res1 = X.logcdf(x, y, method='logexp_safe') + res2 = X.logcdf(x, y, method='logexp') + ref = X.logcdf(x, y, method='quadrature') + i_fl = [0, -1] # first and last + assert np.isinf(res2[i_fl]).all() + assert res1[1] == res2[1] + # quadrature happens to be perfectly accurate on some platforms + # assert res1[1] != ref[1] + assert_equal(res1[i_fl], ref[i_fl]) + + @pytest.mark.parametrize('method_name', ['logcdf', 'logccdf']) + def test_logexp_safe(self, method_name): + # test what happens when `cdf`/`ccdf` underflows + X = stats.Normal(sigma=2) + x = [-301, 1] if method_name == 'logcdf' else [301, 1] + func = getattr(X, method_name) + with np.errstate(divide='ignore'): + res1 = func(x, method='logexp_safe') + res2 = func(x, method='logexp') + ref = func(x, method='quadrature') + assert res1[0] == ref[0] + assert res1[0] != res2[0] + assert res1[1] == res2[1] + assert res1[1] != ref[1] + +def check_sample_shape_NaNs(dist, fname, sample_shape, result_shape, rng): + full_shape = sample_shape + result_shape + if fname == 'sample': + sample_method = dist.sample + + methods = {'inverse_transform'} + if dist._overrides(f'_{fname}_formula') and not isinstance(rng, qmc.QMCEngine): + methods.add('formula') + + for method in methods: + res = sample_method(sample_shape, method=method, rng=rng) + valid_parameters = np.broadcast_to(get_valid_parameters(dist), + res.shape) + assert_equal(res.shape, full_shape) + np.testing.assert_equal(res.dtype, dist._dtype) + + if full_shape == (): + # NumPy random makes a distinction between a 0d array and a scalar. + # In stats, we consistently turn 0d arrays into scalars, so + # maintain that behavior here. (With Array API arrays, this will + # change.) + assert np.isscalar(res) + assert np.all(np.isfinite(res[valid_parameters])) + assert_equal(res[~valid_parameters], np.nan) + + sample1 = sample_method(sample_shape, method=method, rng=42) + sample2 = sample_method(sample_shape, method=method, rng=42) + assert not np.any(np.equal(res, sample1)) + assert_equal(sample1, sample2) + + +def check_support(dist): + a, b = dist.support() + check_nans_and_edges(dist, 'support', None, a) + check_nans_and_edges(dist, 'support', None, b) + assert a.shape == dist._shape + assert b.shape == dist._shape + assert a.dtype == dist._dtype + assert b.dtype == dist._dtype + + +def check_dist_func(dist, fname, arg, result_shape, methods): + # Check that all computation methods of all distribution functions agree + # with one another, effectively testing the correctness of the generic + # computation methods and confirming the consistency of specific + # distributions with their pdf/logpdf. + + args = tuple() if arg is None else (arg,) + methods = methods.copy() + + if "cache" in methods: + # If "cache" is specified before the value has been evaluated, it + # raises an error. After the value is evaluated, it will succeed. + with pytest.raises(NotImplementedError): + getattr(dist, fname)(*args, method="cache") + + ref = getattr(dist, fname)(*args) + check_nans_and_edges(dist, fname, arg, ref) + + # Remove this after fixing `draw` + tol_override = {'atol': 1e-15} + # Mean can be 0, which makes logmean -inf. + if fname in {'logmean', 'mean', 'logskewness', 'skewness'}: + tol_override = {'atol': 1e-15} + elif fname in {'mode'}: + # can only expect about half of machine precision for optimization + # because math + tol_override = {'atol': 1e-6} + elif fname in {'logcdf'}: # gh-22276 + tol_override = {'rtol': 2e-7} + + if dist._overrides(f'_{fname}_formula'): + methods.add('formula') + + np.testing.assert_equal(ref.shape, result_shape) + # Until we convert to array API, let's do the familiar thing: + # 0d things are scalars, not arrays + if result_shape == tuple(): + assert np.isscalar(ref) + + for method in methods: + res = getattr(dist, fname)(*args, method=method) + if 'log' in fname: + np.testing.assert_allclose(np.exp(res), np.exp(ref), + **tol_override) + else: + np.testing.assert_allclose(res, ref, **tol_override) + + # for now, make sure dtypes are consistent; later, we can check whether + # they are correct. + np.testing.assert_equal(res.dtype, ref.dtype) + np.testing.assert_equal(res.shape, result_shape) + if result_shape == tuple(): + assert np.isscalar(res) + +def check_cdf2(dist, log, x, y, result_shape, methods): + # Specialized test for 2-arg cdf since the interface is a bit different + # from the other methods. Here, we'll use 1-arg cdf as a reference, and + # since we have already checked 1-arg cdf in `check_nans_and_edges`, this + # checks the equivalent of both `check_dist_func` and + # `check_nans_and_edges`. + methods = methods.copy() + + if log: + if dist._overrides('_logcdf2_formula'): + methods.add('formula') + if dist._overrides('_logcdf_formula') or dist._overrides('_logccdf_formula'): + methods.add('subtraction') + if (dist._overrides('_cdf_formula') + or dist._overrides('_ccdf_formula')): + methods.add('log/exp') + else: + if dist._overrides('_cdf2_formula'): + methods.add('formula') + if dist._overrides('_cdf_formula') or dist._overrides('_ccdf_formula'): + methods.add('subtraction') + if (dist._overrides('_logcdf_formula') + or dist._overrides('_logccdf_formula')): + methods.add('log/exp') + + ref = dist.cdf(y) - dist.cdf(x) + np.testing.assert_equal(ref.shape, result_shape) + + if result_shape == tuple(): + assert np.isscalar(ref) + + for method in methods: + res = (np.exp(dist.logcdf(x, y, method=method)) if log + else dist.cdf(x, y, method=method)) + np.testing.assert_allclose(res, ref, atol=1e-14) + if log: + np.testing.assert_equal(res.dtype, (ref + 0j).dtype) + else: + np.testing.assert_equal(res.dtype, ref.dtype) + np.testing.assert_equal(res.shape, result_shape) + if result_shape == tuple(): + assert np.isscalar(res) + + +def check_ccdf2(dist, log, x, y, result_shape, methods): + # Specialized test for 2-arg ccdf since the interface is a bit different + # from the other methods. Could be combined with check_cdf2 above, but + # writing it separately is simpler. + methods = methods.copy() + + if dist._overrides(f'_{"log" if log else ""}ccdf2_formula'): + methods.add('formula') + + ref = dist.cdf(x) + dist.ccdf(y) + np.testing.assert_equal(ref.shape, result_shape) + + if result_shape == tuple(): + assert np.isscalar(ref) + + for method in methods: + res = (np.exp(dist.logccdf(x, y, method=method)) if log + else dist.ccdf(x, y, method=method)) + np.testing.assert_allclose(res, ref, atol=1e-14) + np.testing.assert_equal(res.dtype, ref.dtype) + np.testing.assert_equal(res.shape, result_shape) + if result_shape == tuple(): + assert np.isscalar(res) + + +def check_nans_and_edges(dist, fname, arg, res): + + valid_parameters = get_valid_parameters(dist) + if fname in {'icdf', 'iccdf'}: + arg_domain = _RealDomain(endpoints=(0, 1), inclusive=(True, True)) + elif fname in {'ilogcdf', 'ilogccdf'}: + arg_domain = _RealDomain(endpoints=(-inf, 0), inclusive=(True, True)) + else: + arg_domain = dist._variable.domain + + classified_args = classify_arg(dist, arg, arg_domain) + valid_parameters, *classified_args = np.broadcast_arrays(valid_parameters, + *classified_args) + valid_arg, endpoint_arg, outside_arg, nan_arg = classified_args + all_valid = valid_arg & valid_parameters + + # Check NaN pattern and edge cases + assert_equal(res[~valid_parameters], np.nan) + assert_equal(res[nan_arg], np.nan) + + a, b = dist.support() + a = np.broadcast_to(a, res.shape) + b = np.broadcast_to(b, res.shape) + + outside_arg_minus = (outside_arg == -1) & valid_parameters + outside_arg_plus = (outside_arg == 1) & valid_parameters + endpoint_arg_minus = (endpoint_arg == -1) & valid_parameters + endpoint_arg_plus = (endpoint_arg == 1) & valid_parameters + # Writing this independently of how the are set in the distribution + # infrastructure. That is very compact; this is very verbose. + if fname in {'logpdf'}: + assert_equal(res[outside_arg_minus], -np.inf) + assert_equal(res[outside_arg_plus], -np.inf) + assert_equal(res[endpoint_arg_minus & ~valid_arg], -np.inf) + assert_equal(res[endpoint_arg_plus & ~valid_arg], -np.inf) + elif fname in {'pdf'}: + assert_equal(res[outside_arg_minus], 0) + assert_equal(res[outside_arg_plus], 0) + assert_equal(res[endpoint_arg_minus & ~valid_arg], 0) + assert_equal(res[endpoint_arg_plus & ~valid_arg], 0) + elif fname in {'logcdf'}: + assert_equal(res[outside_arg_minus], -inf) + assert_equal(res[outside_arg_plus], 0) + assert_equal(res[endpoint_arg_minus], -inf) + assert_equal(res[endpoint_arg_plus], 0) + elif fname in {'cdf'}: + assert_equal(res[outside_arg_minus], 0) + assert_equal(res[outside_arg_plus], 1) + assert_equal(res[endpoint_arg_minus], 0) + assert_equal(res[endpoint_arg_plus], 1) + elif fname in {'logccdf'}: + assert_equal(res[outside_arg_minus], 0) + assert_equal(res[outside_arg_plus], -inf) + assert_equal(res[endpoint_arg_minus], 0) + assert_equal(res[endpoint_arg_plus], -inf) + elif fname in {'ccdf'}: + assert_equal(res[outside_arg_minus], 1) + assert_equal(res[outside_arg_plus], 0) + assert_equal(res[endpoint_arg_minus], 1) + assert_equal(res[endpoint_arg_plus], 0) + elif fname in {'ilogcdf', 'icdf'}: + assert_equal(res[outside_arg == -1], np.nan) + assert_equal(res[outside_arg == 1], np.nan) + assert_equal(res[endpoint_arg == -1], a[endpoint_arg == -1]) + assert_equal(res[endpoint_arg == 1], b[endpoint_arg == 1]) + elif fname in {'ilogccdf', 'iccdf'}: + assert_equal(res[outside_arg == -1], np.nan) + assert_equal(res[outside_arg == 1], np.nan) + assert_equal(res[endpoint_arg == -1], b[endpoint_arg == -1]) + assert_equal(res[endpoint_arg == 1], a[endpoint_arg == 1]) + + if fname not in {'logmean', 'mean', 'logskewness', 'skewness', 'support'}: + assert np.isfinite(res[all_valid & (endpoint_arg == 0)]).all() + + +def check_moment_funcs(dist, result_shape): + # Check that all computation methods of all distribution functions agree + # with one another, effectively testing the correctness of the generic + # computation methods and confirming the consistency of specific + # distributions with their pdf/logpdf. + + atol = 1e-9 # make this tighter (e.g. 1e-13) after fixing `draw` + + def check(order, kind, method=None, ref=None, success=True): + if success: + res = dist.moment(order, kind, method=method) + assert_allclose(res, ref, atol=atol*10**order) + assert res.shape == ref.shape + else: + with pytest.raises(NotImplementedError): + dist.moment(order, kind, method=method) + + def has_formula(order, kind): + formula_name = f'_moment_{kind}_formula' + overrides = dist._overrides(formula_name) + if not overrides: + return False + formula = getattr(dist, formula_name) + orders = getattr(formula, 'orders', set(range(6))) + return order in orders + + + dist.reset_cache() + + ### Check Raw Moments ### + for i in range(6): + check(i, 'raw', 'cache', success=False) # not cached yet + ref = dist.moment(i, 'raw', method='quadrature') + check_nans_and_edges(dist, 'moment', None, ref) + assert ref.shape == result_shape + check(i, 'raw','cache', ref, success=True) # cached now + check(i, 'raw', 'formula', ref, success=has_formula(i, 'raw')) + check(i, 'raw', 'general', ref, success=(i == 0)) + if dist.__class__ == stats.Normal: + check(i, 'raw', 'quadrature_icdf', ref, success=True) + + + # Clearing caches to better check their behavior + dist.reset_cache() + + # If we have central or standard moment formulas, or if there are + # values in their cache, we can use method='transform' + dist.moment(0, 'central') # build up the cache + dist.moment(1, 'central') + for i in range(2, 6): + ref = dist.moment(i, 'raw', method='quadrature') + check(i, 'raw', 'transform', ref, + success=has_formula(i, 'central') or has_formula(i, 'standardized')) + dist.moment(i, 'central') # build up the cache + check(i, 'raw', 'transform', ref) + + dist.reset_cache() + + ### Check Central Moments ### + + for i in range(6): + check(i, 'central', 'cache', success=False) + ref = dist.moment(i, 'central', method='quadrature') + assert ref.shape == result_shape + check(i, 'central', 'cache', ref, success=True) + check(i, 'central', 'formula', ref, success=has_formula(i, 'central')) + check(i, 'central', 'general', ref, success=i <= 1) + if dist.__class__ == stats.Normal: + check(i, 'central', 'quadrature_icdf', ref, success=True) + if not (dist.__class__ == stats.Uniform and i == 5): + # Quadrature is not super accurate for 5th central moment when the + # support is really big. Skip this one failing test. We need to come + # up with a better system of skipping individual failures w/ hypothesis. + check(i, 'central', 'transform', ref, + success=has_formula(i, 'raw') or (i <= 1)) + if not has_formula(i, 'raw'): + dist.moment(i, 'raw') + check(i, 'central', 'transform', ref) + + dist.reset_cache() + + # If we have standard moment formulas, or if there are + # values in their cache, we can use method='normalize' + dist.moment(0, 'standardized') # build up the cache + dist.moment(1, 'standardized') + dist.moment(2, 'standardized') + for i in range(3, 6): + ref = dist.moment(i, 'central', method='quadrature') + check(i, 'central', 'normalize', ref, + success=has_formula(i, 'standardized')) + dist.moment(i, 'standardized') # build up the cache + check(i, 'central', 'normalize', ref) + + ### Check Standardized Moments ### + + var = dist.moment(2, 'central', method='quadrature') + dist.reset_cache() + + for i in range(6): + check(i, 'standardized', 'cache', success=False) + ref = dist.moment(i, 'central', method='quadrature') / var ** (i / 2) + assert ref.shape == result_shape + check(i, 'standardized', 'formula', ref, + success=has_formula(i, 'standardized')) + check(i, 'standardized', 'general', ref, success=i <= 2) + check(i, 'standardized', 'normalize', ref) + + if isinstance(dist, ShiftedScaledDistribution): + # logmoment is not fully fleshed out; no need to test + # ShiftedScaledDistribution here + return + + # logmoment is not very accuate, and it's not public, so skip for now + # ### Check Against _logmoment ### + # logmean = dist._logmoment(1, logcenter=-np.inf) + # for i in range(6): + # ref = np.exp(dist._logmoment(i, logcenter=-np.inf)) + # assert_allclose(dist.moment(i, 'raw'), ref, atol=atol*10**i) + # + # ref = np.exp(dist._logmoment(i, logcenter=logmean)) + # assert_allclose(dist.moment(i, 'central'), ref, atol=atol*10**i) + # + # ref = np.exp(dist._logmoment(i, logcenter=logmean, standardized=True)) + # assert_allclose(dist.moment(i, 'standardized'), ref, atol=atol*10**i) + + +@pytest.mark.parametrize('family', (Normal,)) +@pytest.mark.parametrize('x_shape', [tuple(), (2, 3)]) +@pytest.mark.parametrize('dist_shape', [tuple(), (4, 1)]) +@pytest.mark.parametrize('fname', ['sample']) +@pytest.mark.parametrize('rng_type', [np.random.Generator, qmc.Halton, qmc.Sobol]) +def test_sample_against_cdf(family, dist_shape, x_shape, fname, rng_type): + rng = np.random.default_rng(842582438235635) + num_parameters = family._num_parameters() + + if dist_shape and num_parameters == 0: + pytest.skip("Distribution can't have a shape without parameters.") + + dist = family._draw(dist_shape, rng) + + n = 1024 + sample_size = (n,) + x_shape + sample_array_shape = sample_size + dist_shape + + if fname == 'sample': + sample_method = dist.sample + + if rng_type != np.random.Generator: + rng = rng_type(d=1, seed=rng) + x = sample_method(sample_size, rng=rng) + assert x.shape == sample_array_shape + + # probably should give `axis` argument to ks_1samp, review that separately + statistic = _kolmogorov_smirnov(dist, x, axis=0) + pvalue = kolmogn(x.shape[0], statistic, cdf=False) + p_threshold = 0.01 + num_pvalues = pvalue.size + num_small_pvalues = np.sum(pvalue < p_threshold) + assert num_small_pvalues < p_threshold * num_pvalues + + +def get_valid_parameters(dist): + # Given a distribution, return a logical array that is true where all + # distribution parameters are within their respective domains. The code + # here is probably quite similar to that used to form the `_invalid` + # attribute of the distribution, but this was written about a week later + # without referring to that code, so it is a somewhat independent check. + + # Get all parameter values and `_Parameter` objects + parameter_values = dist._parameters + parameters = {} + for parameterization in dist._parameterizations: + parameters.update(parameterization.parameters) + + all_valid = np.ones(dist._shape, dtype=bool) + for name, value in parameter_values.items(): + if name not in parameters: # cached value not part of parameterization + continue + parameter = parameters[name] + + # Check that the numerical endpoints and inclusivity attribute + # agree with the `contains` method about which parameter values are + # within the domain. + a, b = parameter.domain.get_numerical_endpoints( + parameter_values=parameter_values) + a_included, b_included = parameter.domain.inclusive + valid = (a <= value) if a_included else a < value + valid &= (value <= b) if b_included else value < b + assert_equal(valid, parameter.domain.contains( + value, parameter_values=parameter_values)) + + # Form `all_valid` mask that is True where *all* parameters are valid + all_valid &= valid + + # Check that the `all_valid` mask formed here is the complement of the + # `dist._invalid` mask stored by the infrastructure + assert_equal(~all_valid, dist._invalid) + + return all_valid + +def classify_arg(dist, arg, arg_domain): + if arg is None: + valid_args = np.ones(dist._shape, dtype=bool) + endpoint_args = np.zeros(dist._shape, dtype=bool) + outside_args = np.zeros(dist._shape, dtype=bool) + nan_args = np.zeros(dist._shape, dtype=bool) + return valid_args, endpoint_args, outside_args, nan_args + + a, b = arg_domain.get_numerical_endpoints( + parameter_values=dist._parameters) + + a, b, arg = np.broadcast_arrays(a, b, arg) + a_included, b_included = arg_domain.inclusive + + inside = (a <= arg) if a_included else a < arg + inside &= (arg <= b) if b_included else arg < b + # TODO: add `supported` method and check here + on = np.zeros(a.shape, dtype=int) + on[a == arg] = -1 + on[b == arg] = 1 + outside = np.zeros(a.shape, dtype=int) + outside[(arg < a) if a_included else arg <= a] = -1 + outside[(b < arg) if b_included else b <= arg] = 1 + nan = np.isnan(arg) + + return inside, on, outside, nan + + +def test_input_validation(): + class Test(ContinuousDistribution): + _variable = _RealParameter('x', domain=_RealDomain()) + + message = ("The `Test` distribution family does not accept parameters, " + "but parameters `{'a'}` were provided.") + with pytest.raises(ValueError, match=message): + Test(a=1, ) + + message = "Attribute `tol` of `Test` must be a positive float, if specified." + with pytest.raises(ValueError, match=message): + Test(tol=np.asarray([])) + with pytest.raises(ValueError, match=message): + Test(tol=[1, 2, 3]) + with pytest.raises(ValueError, match=message): + Test(tol=np.nan) + with pytest.raises(ValueError, match=message): + Test(tol=-1) + + message = ("Argument `order` of `Test.moment` must be a " + "finite, positive integer.") + with pytest.raises(ValueError, match=message): + Test().moment(-1) + with pytest.raises(ValueError, match=message): + Test().moment(np.inf) + + message = "Argument `kind` of `Test.moment` must be one of..." + with pytest.raises(ValueError, match=message): + Test().moment(2, kind='coconut') + + class Test2(ContinuousDistribution): + _p1 = _RealParameter('c', domain=_RealDomain()) + _p2 = _RealParameter('d', domain=_RealDomain()) + _parameterizations = [_Parameterization(_p1, _p2)] + _variable = _RealParameter('x', domain=_RealDomain()) + + message = ("The provided parameters `{a}` do not match a supported " + "parameterization of the `Test2` distribution family.") + with pytest.raises(ValueError, match=message): + Test2(a=1) + + message = ("The `Test2` distribution family requires parameters, but none " + "were provided.") + with pytest.raises(ValueError, match=message): + Test2() + + message = ("The parameters `{c, d}` provided to the `Test2` " + "distribution family cannot be broadcast to the same shape.") + with pytest.raises(ValueError, match=message): + Test2(c=[1, 2], d=[1, 2, 3]) + + message = ("The argument provided to `Test2.pdf` cannot be be broadcast to " + "the same shape as the distribution parameters.") + with pytest.raises(ValueError, match=message): + dist = Test2(c=[1, 2, 3], d=[1, 2, 3]) + dist.pdf([1, 2]) + + message = "Parameter `c` must be of real dtype." + with pytest.raises(TypeError, match=message): + Test2(c=[1, object()], d=[1, 2]) + + message = "Parameter `convention` of `Test2.kurtosis` must be one of..." + with pytest.raises(ValueError, match=message): + dist = Test2(c=[1, 2, 3], d=[1, 2, 3]) + dist.kurtosis(convention='coconut') + + +def test_rng_deepcopy_pickle(): + # test behavior of `rng` attribute and copy behavior + kwargs = dict(a=[-1, 2], b=10) + dist1 = Uniform(**kwargs) + dist2 = deepcopy(dist1) + dist3 = pickle.loads(pickle.dumps(dist1)) + + res1, res2, res3 = dist1.sample(), dist2.sample(), dist3.sample() + assert np.all(res2 != res1) + assert np.all(res3 != res1) + + res1, res2, res3 = dist1.sample(rng=42), dist2.sample(rng=42), dist3.sample(rng=42) + assert np.all(res2 == res1) + assert np.all(res3 == res1) + + +class TestAttributes: + def test_cache_policy(self): + dist = StandardNormal(cache_policy="no_cache") + # make error message more appropriate + message = "`StandardNormal` does not provide an accurate implementation of the " + with pytest.raises(NotImplementedError, match=message): + dist.mean(method='cache') + mean = dist.mean() + with pytest.raises(NotImplementedError, match=message): + dist.mean(method='cache') + + # add to enum + dist.cache_policy = None + with pytest.raises(NotImplementedError, match=message): + dist.mean(method='cache') + mean = dist.mean() # method is 'formula' by default + cached_mean = dist.mean(method='cache') + assert_equal(cached_mean, mean) + + # cache is overridden by latest evaluation + quadrature_mean = dist.mean(method='quadrature') + cached_mean = dist.mean(method='cache') + assert_equal(cached_mean, quadrature_mean) + assert not np.all(mean == quadrature_mean) + + # We can turn the cache off, and it won't change, but the old cache is + # still available + dist.cache_policy = "no_cache" + mean = dist.mean(method='formula') + cached_mean = dist.mean(method='cache') + assert_equal(cached_mean, quadrature_mean) + assert not np.all(mean == quadrature_mean) + + dist.reset_cache() + with pytest.raises(NotImplementedError, match=message): + dist.mean(method='cache') + + message = "Attribute `cache_policy` of `StandardNormal`..." + with pytest.raises(ValueError, match=message): + dist.cache_policy = "invalid" + + def test_tol(self): + x = 3. + X = stats.Normal() + + message = "Attribute `tol` of `StandardNormal` must..." + with pytest.raises(ValueError, match=message): + X.tol = -1. + with pytest.raises(ValueError, match=message): + X.tol = (0.1,) + with pytest.raises(ValueError, match=message): + X.tol = np.nan + + X1 = stats.Normal(tol=1e-1) + X2 = stats.Normal(tol=1e-12) + ref = X.cdf(x) + res1 = X1.cdf(x, method='quadrature') + res2 = X2.cdf(x, method='quadrature') + assert_allclose(res1, ref, rtol=X1.tol) + assert_allclose(res2, ref, rtol=X2.tol) + assert abs(res1 - ref) > abs(res2 - ref) + + p = 0.99 + X1.tol, X2.tol = X2.tol, X1.tol + ref = X.icdf(p) + res1 = X1.icdf(p, method='inversion') + res2 = X2.icdf(p, method='inversion') + assert_allclose(res1, ref, rtol=X1.tol) + assert_allclose(res2, ref, rtol=X2.tol) + assert abs(res2 - ref) > abs(res1 - ref) + + def test_iv_policy(self): + X = Uniform(a=0, b=1) + assert X.pdf(2) == 0 + + X.validation_policy = 'skip_all' + assert X.pdf(np.asarray(2.)) == 1 + + # Tests _set_invalid_nan + a, b = np.asarray(1.), np.asarray(0.) # invalid parameters + X = Uniform(a=a, b=b, validation_policy='skip_all') + assert X.pdf(np.asarray(2.)) == -1 + + # Tests _set_invalid_nan_property + class MyUniform(Uniform): + def _entropy_formula(self, *args, **kwargs): + return 'incorrect' + + def _moment_raw_formula(self, order, **params): + return 'incorrect' + + X = MyUniform(a=a, b=b, validation_policy='skip_all') + assert X.entropy() == 'incorrect' + + # Tests _validate_order_kind + assert X.moment(kind='raw', order=-1) == 'incorrect' + + # Test input validation + message = "Attribute `validation_policy` of `MyUniform`..." + with pytest.raises(ValueError, match=message): + X.validation_policy = "invalid" + + def test_shapes(self): + X = stats.Normal(mu=1, sigma=2) + Y = stats.Normal(mu=[2], sigma=3) + + # Check that attributes are available as expected + assert X.mu == 1 + assert X.sigma == 2 + assert Y.mu[0] == 2 + assert Y.sigma[0] == 3 + + # Trying to set an attribute raises + # message depends on Python version + with pytest.raises(AttributeError): + X.mu = 2 + + # Trying to mutate an attribute really mutates a copy + Y.mu[0] = 10 + assert Y.mu[0] == 2 + + +class TestMakeDistribution: + @pytest.mark.parametrize('i, distdata', enumerate(distcont)) + def test_make_distribution(self, i, distdata): + distname = distdata[0] + + slow = {'argus', 'exponpow', 'exponweib', 'genexpon', 'gompertz', 'halfgennorm', + 'johnsonsb', 'kappa4', 'ksone', 'kstwo', 'kstwobign', 'powerlognorm', + 'powernorm', 'recipinvgauss', 'studentized_range', 'vonmises_line'} + if not int(os.environ.get('SCIPY_XSLOW', '0')) and distname in slow: + pytest.skip('Skipping as XSLOW') + + if distname in { # skip these distributions + 'levy_stable', # private methods seem to require >= 1d args + 'vonmises', # circular distribution; shouldn't work + }: + return + + # skip single test, mostly due to slight disagreement + custom_tolerances = {'ksone': 1e-5, 'kstwo': 1e-5} # discontinuous PDF + skip_entropy = {'kstwobign', 'pearson3'} # tolerance issue + skip_skewness = {'exponpow', 'ksone'} # tolerance issue + skip_kurtosis = {'chi', 'exponpow', 'invgamma', # tolerance issue + 'johnsonsb', 'ksone', 'kstwo'} # tolerance issue + skip_logccdf = {'arcsine', 'skewcauchy', 'trapezoid', 'triang'} # tolerance + skip_raw = {2: {'alpha', 'foldcauchy', 'halfcauchy', 'levy', 'levy_l'}, + 3: {'pareto'}, # stats.pareto is just wrong + 4: {'invgamma'}} # tolerance issue + skip_standardized = {'exponpow', 'ksone'} # tolerances + + dist = getattr(stats, distname) + params = dict(zip(dist.shapes.split(', '), distdata[1])) if dist.shapes else {} + rng = np.random.default_rng(7548723590230982) + CustomDistribution = stats.make_distribution(dist) + X = CustomDistribution(**params) + Y = dist(**params) + x = X.sample(shape=10, rng=rng) + p = X.cdf(x) + rtol = custom_tolerances.get(distname, 1e-7) + atol = 1e-12 + + with np.errstate(divide='ignore', invalid='ignore'): + m, v, s, k = Y.stats('mvsk') + assert_allclose(X.support(), Y.support()) + if distname not in skip_entropy: + assert_allclose(X.entropy(), Y.entropy(), rtol=rtol) + assert_allclose(X.median(), Y.median(), rtol=rtol) + assert_allclose(X.mean(), m, rtol=rtol, atol=atol) + assert_allclose(X.variance(), v, rtol=rtol, atol=atol) + if distname not in skip_skewness: + assert_allclose(X.skewness(), s, rtol=rtol, atol=atol) + if distname not in skip_kurtosis: + assert_allclose(X.kurtosis(convention='excess'), k, + rtol=rtol, atol=atol) + assert_allclose(X.logpdf(x), Y.logpdf(x), rtol=rtol) + assert_allclose(X.pdf(x), Y.pdf(x), rtol=rtol) + assert_allclose(X.logcdf(x), Y.logcdf(x), rtol=rtol) + assert_allclose(X.cdf(x), Y.cdf(x), rtol=rtol) + if distname not in skip_logccdf: + assert_allclose(X.logccdf(x), Y.logsf(x), rtol=rtol) + assert_allclose(X.ccdf(x), Y.sf(x), rtol=rtol) + assert_allclose(X.icdf(p), Y.ppf(p), rtol=rtol) + assert_allclose(X.iccdf(p), Y.isf(p), rtol=rtol) + for order in range(5): + if distname not in skip_raw.get(order, {}): + assert_allclose(X.moment(order, kind='raw'), + Y.moment(order), rtol=rtol, atol=atol) + for order in range(3, 4): + if distname not in skip_standardized: + assert_allclose(X.moment(order, kind='standardized'), + Y.stats('mvsk'[order-1]), rtol=rtol, atol=atol) + seed = 845298245687345 + assert_allclose(X.sample(shape=10, rng=seed), + Y.rvs(size=10, random_state=np.random.default_rng(seed)), + rtol=rtol) + + def test_input_validation(self): + message = '`levy_stable` is not supported.' + with pytest.raises(NotImplementedError, match=message): + stats.make_distribution(stats.levy_stable) + + message = '`vonmises` is not supported.' + with pytest.raises(NotImplementedError, match=message): + stats.make_distribution(stats.vonmises) + + message = "The argument must be an instance of `rv_continuous`." + with pytest.raises(ValueError, match=message): + stats.make_distribution(object()) + + def test_repr_str_docs(self): + from scipy.stats._distribution_infrastructure import _distribution_names + for dist in _distribution_names.keys(): + assert hasattr(stats, dist) + + dist = stats.make_distribution(stats.gamma) + assert str(dist(a=2)) == "Gamma(a=2.0)" + if np.__version__ >= "2": + assert repr(dist(a=2)) == "Gamma(a=np.float64(2.0))" + assert 'Gamma' in dist.__doc__ + + dist = stats.make_distribution(stats.halfgennorm) + assert str(dist(beta=2)) == "HalfGeneralizedNormal(beta=2.0)" + if np.__version__ >= "2": + assert repr(dist(beta=2)) == "HalfGeneralizedNormal(beta=np.float64(2.0))" + assert 'HalfGeneralizedNormal' in dist.__doc__ + + +class TestTransforms: + + # putting this at the top to hopefully avoid merge conflicts + def test_truncate(self): + rng = np.random.default_rng(81345982345826) + lb = rng.random((3, 1)) + ub = rng.random((3, 1)) + lb, ub = np.minimum(lb, ub), np.maximum(lb, ub) + + Y = stats.truncate(Normal(), lb=lb, ub=ub) + Y0 = stats.truncnorm(lb, ub) + + y = Y0.rvs((3, 10), random_state=rng) + p = Y0.cdf(y) + + assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j)) + assert_allclose(Y.entropy(), Y0.entropy()) + assert_allclose(Y.median(), Y0.ppf(0.5)) + assert_allclose(Y.mean(), Y0.mean()) + assert_allclose(Y.variance(), Y0.var()) + assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var())) + assert_allclose(Y.skewness(), Y0.stats('s')) + assert_allclose(Y.kurtosis(), Y0.stats('k') + 3) + assert_allclose(Y.support(), Y0.support()) + assert_allclose(Y.pdf(y), Y0.pdf(y)) + assert_allclose(Y.cdf(y), Y0.cdf(y)) + assert_allclose(Y.ccdf(y), Y0.sf(y)) + assert_allclose(Y.icdf(p), Y0.ppf(p)) + assert_allclose(Y.iccdf(p), Y0.isf(p)) + assert_allclose(Y.logpdf(y), Y0.logpdf(y)) + assert_allclose(Y.logcdf(y), Y0.logcdf(y)) + assert_allclose(Y.logccdf(y), Y0.logsf(y)) + assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p)) + assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p)) + sample = Y.sample(10) + assert np.all((sample > lb) & (sample < ub)) + + @pytest.mark.fail_slow(10) + @given(data=strategies.data(), seed=strategies.integers(min_value=0)) + def test_loc_scale(self, data, seed): + # Need tests with negative scale + rng = np.random.default_rng(seed) + + class TransformedNormal(ShiftedScaledDistribution): + def __init__(self, *args, **kwargs): + super().__init__(StandardNormal(), *args, **kwargs) + + tmp = draw_distribution_from_family( + TransformedNormal, data, rng, proportions=(1, 0, 0, 0), min_side=1) + dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape = tmp + + loc = dist.loc + scale = dist.scale + dist0 = StandardNormal() + dist_ref = stats.norm(loc=loc, scale=scale) + + x0 = (x - loc) / scale + y0 = (y - loc) / scale + + a, b = dist.support() + a0, b0 = dist0.support() + assert_allclose(a, a0 + loc) + assert_allclose(b, b0 + loc) + + with np.errstate(invalid='ignore', divide='ignore'): + assert_allclose(np.exp(dist.logentropy()), dist.entropy()) + assert_allclose(dist.entropy(), dist_ref.entropy()) + assert_allclose(dist.median(), dist0.median() + loc) + assert_allclose(dist.mode(), dist0.mode() + loc) + assert_allclose(dist.mean(), dist0.mean() + loc) + assert_allclose(dist.variance(), dist0.variance() * scale**2) + assert_allclose(dist.standard_deviation(), dist.variance()**0.5) + assert_allclose(dist.skewness(), dist0.skewness() * np.sign(scale)) + assert_allclose(dist.kurtosis(), dist0.kurtosis()) + assert_allclose(dist.logpdf(x), dist0.logpdf(x0) - np.log(scale)) + assert_allclose(dist.pdf(x), dist0.pdf(x0) / scale) + assert_allclose(dist.logcdf(x), dist0.logcdf(x0)) + assert_allclose(dist.cdf(x), dist0.cdf(x0)) + assert_allclose(dist.logccdf(x), dist0.logccdf(x0)) + assert_allclose(dist.ccdf(x), dist0.ccdf(x0)) + assert_allclose(dist.logcdf(x, y), dist0.logcdf(x0, y0)) + assert_allclose(dist.cdf(x, y), dist0.cdf(x0, y0)) + assert_allclose(dist.logccdf(x, y), dist0.logccdf(x0, y0)) + assert_allclose(dist.ccdf(x, y), dist0.ccdf(x0, y0)) + assert_allclose(dist.ilogcdf(logp), dist0.ilogcdf(logp)*scale + loc) + assert_allclose(dist.icdf(p), dist0.icdf(p)*scale + loc) + assert_allclose(dist.ilogccdf(logp), dist0.ilogccdf(logp)*scale + loc) + assert_allclose(dist.iccdf(p), dist0.iccdf(p)*scale + loc) + for i in range(1, 5): + assert_allclose(dist.moment(i, 'raw'), dist_ref.moment(i)) + assert_allclose(dist.moment(i, 'central'), + dist0.moment(i, 'central') * scale**i) + assert_allclose(dist.moment(i, 'standardized'), + dist0.moment(i, 'standardized') * np.sign(scale)**i) + + # Transform back to the original distribution using all arithmetic + # operations; check that it behaves as expected. + dist = (dist - 2*loc) + loc + dist = dist/scale**2 * scale + z = np.zeros(dist._shape) # compact broadcasting + + a, b = dist.support() + a0, b0 = dist0.support() + assert_allclose(a, a0 + z) + assert_allclose(b, b0 + z) + + with np.errstate(invalid='ignore', divide='ignore'): + assert_allclose(dist.logentropy(), dist0.logentropy() + z) + assert_allclose(dist.entropy(), dist0.entropy() + z) + assert_allclose(dist.median(), dist0.median() + z) + assert_allclose(dist.mode(), dist0.mode() + z) + assert_allclose(dist.mean(), dist0.mean() + z) + assert_allclose(dist.variance(), dist0.variance() + z) + assert_allclose(dist.standard_deviation(), dist0.standard_deviation() + z) + assert_allclose(dist.skewness(), dist0.skewness() + z) + assert_allclose(dist.kurtosis(), dist0.kurtosis() + z) + assert_allclose(dist.logpdf(x), dist0.logpdf(x)+z) + assert_allclose(dist.pdf(x), dist0.pdf(x) + z) + assert_allclose(dist.logcdf(x), dist0.logcdf(x) + z) + assert_allclose(dist.cdf(x), dist0.cdf(x) + z) + assert_allclose(dist.logccdf(x), dist0.logccdf(x) + z) + assert_allclose(dist.ccdf(x), dist0.ccdf(x) + z) + assert_allclose(dist.ilogcdf(logp), dist0.ilogcdf(logp) + z) + assert_allclose(dist.icdf(p), dist0.icdf(p) + z) + assert_allclose(dist.ilogccdf(logp), dist0.ilogccdf(logp) + z) + assert_allclose(dist.iccdf(p), dist0.iccdf(p) + z) + for i in range(1, 5): + assert_allclose(dist.moment(i, 'raw'), dist0.moment(i, 'raw')) + assert_allclose(dist.moment(i, 'central'), dist0.moment(i, 'central')) + assert_allclose(dist.moment(i, 'standardized'), + dist0.moment(i, 'standardized')) + + # These are tough to compare because of the way the shape works + # rng = np.random.default_rng(seed) + # rng0 = np.random.default_rng(seed) + # assert_allclose(dist.sample(x_result_shape, rng=rng), + # dist0.sample(x_result_shape, rng=rng0) * scale + loc) + # Should also try to test fit, plot? + + @pytest.mark.fail_slow(5) + @pytest.mark.parametrize('exp_pow', ['exp', 'pow']) + def test_exp_pow(self, exp_pow): + rng = np.random.default_rng(81345982345826) + mu = rng.random((3, 1)) + sigma = rng.random((3, 1)) + + X = Normal()*sigma + mu + if exp_pow == 'exp': + Y = stats.exp(X) + else: + Y = np.e ** X + Y0 = stats.lognorm(sigma, scale=np.exp(mu)) + + y = Y0.rvs((3, 10), random_state=rng) + p = Y0.cdf(y) + + assert_allclose(Y.logentropy(), np.log(Y0.entropy())) + assert_allclose(Y.entropy(), Y0.entropy()) + assert_allclose(Y.median(), Y0.ppf(0.5)) + assert_allclose(Y.mean(), Y0.mean()) + assert_allclose(Y.variance(), Y0.var()) + assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var())) + assert_allclose(Y.skewness(), Y0.stats('s')) + assert_allclose(Y.kurtosis(), Y0.stats('k') + 3) + assert_allclose(Y.support(), Y0.support()) + assert_allclose(Y.pdf(y), Y0.pdf(y)) + assert_allclose(Y.cdf(y), Y0.cdf(y)) + assert_allclose(Y.ccdf(y), Y0.sf(y)) + assert_allclose(Y.icdf(p), Y0.ppf(p)) + assert_allclose(Y.iccdf(p), Y0.isf(p)) + assert_allclose(Y.logpdf(y), Y0.logpdf(y)) + assert_allclose(Y.logcdf(y), Y0.logcdf(y)) + assert_allclose(Y.logccdf(y), Y0.logsf(y)) + assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p)) + assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p)) + seed = 3984593485 + assert_allclose(Y.sample(rng=seed), np.exp(X.sample(rng=seed))) + + + @pytest.mark.fail_slow(10) + @pytest.mark.parametrize('scale', [1, 2, -1]) + @pytest.mark.xfail_on_32bit("`scale=-1` fails on 32-bit; needs investigation") + def test_reciprocal(self, scale): + rng = np.random.default_rng(81345982345826) + a = rng.random((3, 1)) + + # Separate sign from scale. It's easy to scale the resulting + # RV with negative scale; we want to test the ability to divide + # by a RV with negative support + sign, scale = np.sign(scale), abs(scale) + + # Reference distribution + InvGamma = stats.make_distribution(stats.invgamma) + Y0 = sign * scale * InvGamma(a=a) + + # Test distribution + X = _Gamma(a=a) if sign > 0 else -_Gamma(a=a) + Y = scale / X + + y = Y0.sample(shape=(3, 10), rng=rng) + p = Y0.cdf(y) + logp = np.log(p) + + assert_allclose(Y.logentropy(), np.log(Y0.entropy())) + assert_allclose(Y.entropy(), Y0.entropy()) + assert_allclose(Y.median(), Y0.median()) + # moments are not finite + assert_allclose(Y.support(), Y0.support()) + assert_allclose(Y.pdf(y), Y0.pdf(y)) + assert_allclose(Y.cdf(y), Y0.cdf(y)) + assert_allclose(Y.ccdf(y), Y0.ccdf(y)) + assert_allclose(Y.icdf(p), Y0.icdf(p)) + assert_allclose(Y.iccdf(p), Y0.iccdf(p)) + assert_allclose(Y.logpdf(y), Y0.logpdf(y)) + assert_allclose(Y.logcdf(y), Y0.logcdf(y)) + assert_allclose(Y.logccdf(y), Y0.logccdf(y)) + with np.errstate(divide='ignore', invalid='ignore'): + assert_allclose(Y.ilogcdf(logp), Y0.ilogcdf(logp)) + assert_allclose(Y.ilogccdf(logp), Y0.ilogccdf(logp)) + seed = 3984593485 + assert_allclose(Y.sample(rng=seed), scale/(X.sample(rng=seed))) + + @pytest.mark.fail_slow(5) + def test_log(self): + rng = np.random.default_rng(81345982345826) + a = rng.random((3, 1)) + + X = _Gamma(a=a) + Y0 = stats.loggamma(a) + Y = stats.log(X) + y = Y0.rvs((3, 10), random_state=rng) + p = Y0.cdf(y) + + assert_allclose(Y.logentropy(), np.log(Y0.entropy())) + assert_allclose(Y.entropy(), Y0.entropy()) + assert_allclose(Y.median(), Y0.ppf(0.5)) + assert_allclose(Y.mean(), Y0.mean()) + assert_allclose(Y.variance(), Y0.var()) + assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var())) + assert_allclose(Y.skewness(), Y0.stats('s')) + assert_allclose(Y.kurtosis(), Y0.stats('k') + 3) + assert_allclose(Y.support(), Y0.support()) + assert_allclose(Y.pdf(y), Y0.pdf(y)) + assert_allclose(Y.cdf(y), Y0.cdf(y)) + assert_allclose(Y.ccdf(y), Y0.sf(y)) + assert_allclose(Y.icdf(p), Y0.ppf(p)) + assert_allclose(Y.iccdf(p), Y0.isf(p)) + assert_allclose(Y.logpdf(y), Y0.logpdf(y)) + assert_allclose(Y.logcdf(y), Y0.logcdf(y)) + assert_allclose(Y.logccdf(y), Y0.logsf(y)) + with np.errstate(invalid='ignore'): + assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p)) + assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p)) + seed = 3984593485 + assert_allclose(Y.sample(rng=seed), np.log(X.sample(rng=seed))) + + def test_monotonic_transforms(self): + # Some tests of monotonic transforms that are better to be grouped or + # don't fit well above + + X = Uniform(a=1, b=2) + X_str = "Uniform(a=1.0, b=2.0)" + + assert str(stats.log(X)) == f"log({X_str})" + assert str(1 / X) == f"1/({X_str})" + assert str(stats.exp(X)) == f"exp({X_str})" + + X = Uniform(a=-1, b=2) + message = "Division by a random variable is only implemented when the..." + with pytest.raises(NotImplementedError, match=message): + 1 / X + message = "The logarithm of a random variable is only implemented when the..." + with pytest.raises(NotImplementedError, match=message): + stats.log(X) + message = "Raising an argument to the power of a random variable is only..." + with pytest.raises(NotImplementedError, match=message): + (-2) ** X + with pytest.raises(NotImplementedError, match=message): + 1 ** X + with pytest.raises(NotImplementedError, match=message): + [0.5, 1.5] ** X + + message = "Raising a random variable to the power of an argument is only" + with pytest.raises(NotImplementedError, match=message): + X ** (-2) + with pytest.raises(NotImplementedError, match=message): + X ** 0 + with pytest.raises(NotImplementedError, match=message): + X ** [0.5, 1.5] + + def test_arithmetic_operators(self): + rng = np.random.default_rng(2348923495832349834) + + a, b, loc, scale = 0.294, 1.34, 0.57, 1.16 + + x = rng.uniform(-3, 3, 100) + Y = _LogUniform(a=a, b=b) + + X = scale*Y + loc + assert_allclose(X.cdf(x), Y.cdf((x - loc) / scale)) + X = loc + Y*scale + assert_allclose(X.cdf(x), Y.cdf((x - loc) / scale)) + + X = Y/scale - loc + assert_allclose(X.cdf(x), Y.cdf((x + loc) * scale)) + X = loc -_LogUniform(a=a, b=b)/scale + assert_allclose(X.cdf(x), Y.ccdf((-x + loc)*scale)) + + def test_abs(self): + rng = np.random.default_rng(81345982345826) + loc = rng.random((3, 1)) + + Y = stats.abs(Normal() + loc) + Y0 = stats.foldnorm(loc) + + y = Y0.rvs((3, 10), random_state=rng) + p = Y0.cdf(y) + + assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j)) + assert_allclose(Y.entropy(), Y0.entropy()) + assert_allclose(Y.median(), Y0.ppf(0.5)) + assert_allclose(Y.mean(), Y0.mean()) + assert_allclose(Y.variance(), Y0.var()) + assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var())) + assert_allclose(Y.skewness(), Y0.stats('s')) + assert_allclose(Y.kurtosis(), Y0.stats('k') + 3) + assert_allclose(Y.support(), Y0.support()) + assert_allclose(Y.pdf(y), Y0.pdf(y)) + assert_allclose(Y.cdf(y), Y0.cdf(y)) + assert_allclose(Y.ccdf(y), Y0.sf(y)) + assert_allclose(Y.icdf(p), Y0.ppf(p)) + assert_allclose(Y.iccdf(p), Y0.isf(p)) + assert_allclose(Y.logpdf(y), Y0.logpdf(y)) + assert_allclose(Y.logcdf(y), Y0.logcdf(y)) + assert_allclose(Y.logccdf(y), Y0.logsf(y)) + assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p)) + assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p)) + sample = Y.sample(10) + assert np.all(sample > 0) + + def test_abs_finite_support(self): + # The original implementation of `FoldedDistribution` might evaluate + # the private distribution methods outside the support. Check that this + # is resolved. + Weibull = stats.make_distribution(stats.weibull_min) + X = Weibull(c=2) + Y = abs(-X) + assert_equal(X.logpdf(1), Y.logpdf(1)) + assert_equal(X.pdf(1), Y.pdf(1)) + assert_equal(X.logcdf(1), Y.logcdf(1)) + assert_equal(X.cdf(1), Y.cdf(1)) + assert_equal(X.logccdf(1), Y.logccdf(1)) + assert_equal(X.ccdf(1), Y.ccdf(1)) + + def test_pow(self): + rng = np.random.default_rng(81345982345826) + + Y = Normal()**2 + Y0 = stats.chi2(df=1) + + y = Y0.rvs(10, random_state=rng) + p = Y0.cdf(y) + + assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j), rtol=1e-6) + assert_allclose(Y.entropy(), Y0.entropy(), rtol=1e-6) + assert_allclose(Y.median(), Y0.median()) + assert_allclose(Y.mean(), Y0.mean()) + assert_allclose(Y.variance(), Y0.var()) + assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var())) + assert_allclose(Y.skewness(), Y0.stats('s')) + assert_allclose(Y.kurtosis(), Y0.stats('k') + 3) + assert_allclose(Y.support(), Y0.support()) + assert_allclose(Y.pdf(y), Y0.pdf(y)) + assert_allclose(Y.cdf(y), Y0.cdf(y)) + assert_allclose(Y.ccdf(y), Y0.sf(y)) + assert_allclose(Y.icdf(p), Y0.ppf(p)) + assert_allclose(Y.iccdf(p), Y0.isf(p)) + assert_allclose(Y.logpdf(y), Y0.logpdf(y)) + assert_allclose(Y.logcdf(y), Y0.logcdf(y)) + assert_allclose(Y.logccdf(y), Y0.logsf(y)) + assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p)) + assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p)) + sample = Y.sample(10) + assert np.all(sample > 0) + +class TestOrderStatistic: + @pytest.mark.fail_slow(20) # Moments require integration + def test_order_statistic(self): + rng = np.random.default_rng(7546349802439582) + X = Uniform(a=0, b=1) + n = 5 + r = np.asarray([[1], [3], [5]]) + Y = stats.order_statistic(X, n=n, r=r) + Y0 = stats.beta(r, n + 1 - r) + + y = Y0.rvs((3, 10), random_state=rng) + p = Y0.cdf(y) + + # log methods need some attention before merge + assert_allclose(np.exp(Y.logentropy()), Y0.entropy()) + assert_allclose(Y.entropy(), Y0.entropy()) + assert_allclose(Y.mean(), Y0.mean()) + assert_allclose(Y.variance(), Y0.var()) + assert_allclose(Y.skewness(), Y0.stats('s'), atol=1e-15) + assert_allclose(Y.kurtosis(), Y0.stats('k') + 3, atol=1e-15) + assert_allclose(Y.median(), Y0.ppf(0.5)) + assert_allclose(Y.support(), Y0.support()) + assert_allclose(Y.pdf(y), Y0.pdf(y)) + assert_allclose(Y.cdf(y, method='formula'), Y.cdf(y, method='quadrature')) + assert_allclose(Y.ccdf(y, method='formula'), Y.ccdf(y, method='quadrature')) + assert_allclose(Y.icdf(p, method='formula'), Y.icdf(p, method='inversion')) + assert_allclose(Y.iccdf(p, method='formula'), Y.iccdf(p, method='inversion')) + assert_allclose(Y.logpdf(y), Y0.logpdf(y)) + assert_allclose(Y.logcdf(y), Y0.logcdf(y)) + assert_allclose(Y.logccdf(y), Y0.logsf(y)) + with np.errstate(invalid='ignore', divide='ignore'): + assert_allclose(Y.ilogcdf(np.log(p),), Y0.ppf(p)) + assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p)) + + message = "`r` and `n` must contain only positive integers." + with pytest.raises(ValueError, match=message): + stats.order_statistic(X, n=n, r=-1) + with pytest.raises(ValueError, match=message): + stats.order_statistic(X, n=-1, r=r) + with pytest.raises(ValueError, match=message): + stats.order_statistic(X, n=n, r=1.5) + with pytest.raises(ValueError, match=message): + stats.order_statistic(X, n=1.5, r=r) + + def test_support_gh22037(self): + # During review of gh-22037, it was noted that the `support` of + # an `OrderStatisticDistribution` returned incorrect results; + # this was resolved by overriding `_support`. + Uniform = stats.make_distribution(stats.uniform) + X = Uniform() + Y = X*5 + 2 + Z = stats.order_statistic(Y, r=3, n=5) + assert_allclose(Z.support(), Y.support()) + + def test_composition_gh22037(self): + # During review of gh-22037, it was noted that an error was + # raised when creating an `OrderStatisticDistribution` from + # a `TruncatedDistribution`. This was resolved by overriding + # `_update_parameters`. + Normal = stats.make_distribution(stats.norm) + TruncatedNormal = stats.make_distribution(stats.truncnorm) + a, b = [-2, -1], 1 + r, n = 3, [[4], [5]] + x = [[[-0.3]], [[0.1]]] + X1 = Normal() + Y1 = stats.truncate(X1, a, b) + Z1 = stats.order_statistic(Y1, r=r, n=n) + X2 = TruncatedNormal(a=a, b=b) + Z2 = stats.order_statistic(X2, r=r, n=n) + np.testing.assert_allclose(Z1.cdf(x), Z2.cdf(x)) + + +class TestFullCoverage: + # Adds tests just to get to 100% test coverage; this way it's more obvious + # if new lines are untested. + def test_Domain(self): + with pytest.raises(NotImplementedError): + _Domain.contains(None, 1.) + with pytest.raises(NotImplementedError): + _Domain.get_numerical_endpoints(None, 1.) + with pytest.raises(NotImplementedError): + _Domain.__str__(None) + + def test_Parameter(self): + with pytest.raises(NotImplementedError): + _Parameter.validate(None, 1.) + + @pytest.mark.parametrize(("dtype_in", "dtype_out"), + [(np.float16, np.float16), + (np.int16, np.float64)]) + def test_RealParameter_uncommon_dtypes(self, dtype_in, dtype_out): + domain = _RealDomain((-1, 1)) + parameter = _RealParameter('x', domain=domain) + + x = np.asarray([0.5, 2.5], dtype=dtype_in) + arr, dtype, valid = parameter.validate(x, parameter_values={}) + assert_equal(arr, x) + assert dtype == dtype_out + assert_equal(valid, [True, False]) + + def test_ContinuousDistribution_set_invalid_nan(self): + # Exercise code paths when formula returns wrong shape and dtype + # We could consider making this raise an error to force authors + # to return the right shape and dytpe, but this would need to be + # configurable. + class TestDist(ContinuousDistribution): + _variable = _RealParameter('x', domain=_RealDomain(endpoints=(0., 1.))) + def _logpdf_formula(self, x, *args, **kwargs): + return 0 + + X = TestDist() + dtype = np.float32 + X._dtype = dtype + x = np.asarray([0.5], dtype=dtype) + assert X.logpdf(x).dtype == dtype + + def test_fiinfo(self): + assert _fiinfo(np.float64(1.)).max == np.finfo(np.float64).max + assert _fiinfo(np.int64(1)).max == np.iinfo(np.int64).max + + def test_generate_domain_support(self): + msg = _generate_domain_support(StandardNormal) + assert "accepts no distribution parameters" in msg + + msg = _generate_domain_support(Normal) + assert "accepts one parameterization" in msg + + msg = _generate_domain_support(_LogUniform) + assert "accepts two parameterizations" in msg + + def test_ContinuousDistribution__repr__(self): + X = Uniform(a=0, b=1) + if np.__version__ < "2": + assert repr(X) == "Uniform(a=0.0, b=1.0)" + else: + assert repr(X) == "Uniform(a=np.float64(0.0), b=np.float64(1.0))" + if np.__version__ < "2": + assert repr(X*3 + 2) == "3.0*Uniform(a=0.0, b=1.0) + 2.0" + else: + assert repr(X*3 + 2) == ( + "np.float64(3.0)*Uniform(a=np.float64(0.0), b=np.float64(1.0))" + " + np.float64(2.0)" + ) + + X = Uniform(a=np.zeros(4), b=1) + assert repr(X) == "Uniform(a=array([0., 0., 0., 0.]), b=1)" + + X = Uniform(a=np.zeros(4, dtype=np.float32), b=np.ones(4, dtype=np.float32)) + assert repr(X) == ( + "Uniform(a=array([0., 0., 0., 0.], dtype=float32)," + " b=array([1., 1., 1., 1.], dtype=float32))" + ) + + +class TestReprs: + U = Uniform(a=0, b=1) + V = Uniform(a=np.float32(0.0), b=np.float32(1.0)) + X = Normal(mu=-1, sigma=1) + Y = Normal(mu=1, sigma=1) + Z = Normal(mu=np.zeros(1000), sigma=1) + + @pytest.mark.parametrize( + "dist", + [ + U, + U - np.array([1.0, 2.0]), + pytest.param( + V, + marks=pytest.mark.skipif( + np.__version__ < "2", + reason="numpy 1.x didn't have dtype in repr", + ) + ), + pytest.param( + np.ones(2, dtype=np.float32)*V + np.zeros(2, dtype=np.float64), + marks=pytest.mark.skipif( + np.__version__ < "2", + reason="numpy 1.x didn't have dtype in repr", + ) + ), + 3*U + 2, + U**4, + (3*U + 2)**4, + (3*U + 2)**3, + 2**U, + 2**(3*U + 1), + 1 / (1 + U), + stats.order_statistic(U, r=3, n=5), + stats.truncate(U, 0.2, 0.8), + stats.Mixture([X, Y], weights=[0.3, 0.7]), + abs(U), + stats.exp(U), + stats.log(1 + U), + np.array([1.0, 2.0])*U + np.array([2.0, 3.0]), + ] + ) + def test_executable(self, dist): + # Test that reprs actually evaluate to proper distribution + # provided relevant imports are made. + from numpy import array # noqa: F401 + from numpy import float32 # noqa: F401 + from scipy.stats import abs, exp, log, order_statistic, truncate # noqa: F401 + from scipy.stats import Mixture, Normal # noqa: F401 + from scipy.stats._new_distributions import Uniform # noqa: F401 + new_dist = eval(repr(dist)) + # A basic check that the distributions are the same + sample1 = dist.sample(shape=10, rng=1234) + sample2 = new_dist.sample(shape=10, rng=1234) + assert_equal(sample1, sample2) + assert sample1.dtype is sample2.dtype + + @pytest.mark.parametrize( + "dist", + [ + Z, + np.full(1000, 2.0) * X + 1.0, + 2.0 * X + np.full(1000, 1.0), + np.full(1000, 2.0) * X + 1.0, + stats.truncate(Z, -1, 1), + stats.truncate(Z, -np.ones(1000), np.ones(1000)), + stats.order_statistic(X, r=np.arange(1, 1000), n=1000), + Z**2, + 1.0 / (1 + stats.exp(Z)), + 2**Z, + ] + ) + def test_not_too_long(self, dist): + # Tests that array summarization is working to ensure reprs aren't too long. + # None of the reprs above will be executable. + assert len(repr(dist)) < 250 + + +class MixedDist(ContinuousDistribution): + _variable = _RealParameter('x', domain=_RealDomain(endpoints=(-np.inf, np.inf))) + def _pdf_formula(self, x, *args, **kwargs): + return (0.4 * 1/(1.1 * np.sqrt(2*np.pi)) * np.exp(-0.5*((x+0.25)/1.1)**2) + + 0.6 * 1/(0.9 * np.sqrt(2*np.pi)) * np.exp(-0.5*((x-0.5)/0.9)**2)) + + +class TestMixture: + def test_input_validation(self): + message = "`components` must contain at least one random variable." + with pytest.raises(ValueError, match=message): + Mixture([]) + + message = "Each element of `components` must be an instance..." + with pytest.raises(ValueError, match=message): + Mixture((1, 2, 3)) + + message = "All elements of `components` must have scalar shapes." + with pytest.raises(ValueError, match=message): + Mixture([Normal(mu=[1, 2]), Normal()]) + + message = "`components` and `weights` must have the same length." + with pytest.raises(ValueError, match=message): + Mixture([Normal()], weights=[0.5, 0.5]) + + message = "`weights` must have floating point dtype." + with pytest.raises(ValueError, match=message): + Mixture([Normal()], weights=[1]) + + message = "`weights` must have floating point dtype." + with pytest.raises(ValueError, match=message): + Mixture([Normal()], weights=[1]) + + message = "`weights` must sum to 1.0." + with pytest.raises(ValueError, match=message): + Mixture([Normal(), Normal()], weights=[0.5, 1.0]) + + message = "All `weights` must be non-negative." + with pytest.raises(ValueError, match=message): + Mixture([Normal(), Normal()], weights=[1.5, -0.5]) + + @pytest.mark.parametrize('shape', [(), (10,)]) + def test_basic(self, shape): + rng = np.random.default_rng(582348972387243524) + X = Mixture((Normal(mu=-0.25, sigma=1.1), Normal(mu=0.5, sigma=0.9)), + weights=(0.4, 0.6)) + Y = MixedDist() + x = rng.random(shape) + + def assert_allclose(res, ref, **kwargs): + if shape == (): + assert np.isscalar(res) + np.testing.assert_allclose(res, ref, **kwargs) + + assert_allclose(X.logentropy(), Y.logentropy()) + assert_allclose(X.entropy(), Y.entropy()) + assert_allclose(X.mode(), Y.mode()) + assert_allclose(X.median(), Y.median()) + assert_allclose(X.mean(), Y.mean()) + assert_allclose(X.variance(), Y.variance()) + assert_allclose(X.standard_deviation(), Y.standard_deviation()) + assert_allclose(X.skewness(), Y.skewness()) + assert_allclose(X.kurtosis(), Y.kurtosis()) + assert_allclose(X.logpdf(x), Y.logpdf(x)) + assert_allclose(X.pdf(x), Y.pdf(x)) + assert_allclose(X.logcdf(x), Y.logcdf(x)) + assert_allclose(X.cdf(x), Y.cdf(x)) + assert_allclose(X.logccdf(x), Y.logccdf(x)) + assert_allclose(X.ccdf(x), Y.ccdf(x)) + assert_allclose(X.ilogcdf(x), Y.ilogcdf(x)) + assert_allclose(X.icdf(x), Y.icdf(x)) + assert_allclose(X.ilogccdf(x), Y.ilogccdf(x)) + assert_allclose(X.iccdf(x), Y.iccdf(x)) + for kind in ['raw', 'central', 'standardized']: + for order in range(5): + assert_allclose(X.moment(order, kind=kind), + Y.moment(order, kind=kind), + atol=1e-15) + + # weak test of `sample` + shape = (10, 20, 5) + y = X.sample(shape, rng=rng) + assert y.shape == shape + assert stats.ks_1samp(y.ravel(), X.cdf).pvalue > 0.05 + + def test_default_weights(self): + a = 1.1 + Gamma = stats.make_distribution(stats.gamma) + X = Gamma(a=a) + Y = stats.Mixture((X, -X)) + x = np.linspace(-4, 4, 300) + assert_allclose(Y.pdf(x), stats.dgamma(a=a).pdf(x)) + + def test_properties(self): + components = [Normal(mu=-0.25, sigma=1.1), Normal(mu=0.5, sigma=0.9)] + weights = (0.4, 0.6) + X = Mixture(components, weights=weights) + + # Replacing properties doesn't work + # Different version of Python have different messages + with pytest.raises(AttributeError): + X.components = 10 + with pytest.raises(AttributeError): + X.weights = 10 + + # Mutation doesn't work + X.components[0] = components[1] + assert X.components[0] == components[0] + X.weights[0] = weights[1] + assert X.weights[0] == weights[0] + + def test_inverse(self): + # Originally, inverse relied on the mean to start the bracket search. + # This didn't work for distributions with non-finite mean. Check that + # this is resolved. + rng = np.random.default_rng(24358934657854237863456) + Cauchy = stats.make_distribution(stats.cauchy) + X0 = Cauchy() + X = stats.Mixture([X0, X0]) + p = rng.random(size=10) + np.testing.assert_allclose(X.icdf(p), X0.icdf(p)) + np.testing.assert_allclose(X.iccdf(p), X0.iccdf(p)) + np.testing.assert_allclose(X.ilogcdf(p), X0.ilogcdf(p)) + np.testing.assert_allclose(X.ilogccdf(p), X0.ilogccdf(p)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3fc6007b1f53e96ea4e8c3d6ad37c065850804 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_basic.py @@ -0,0 +1,1047 @@ +import sys +import numpy as np +import numpy.testing as npt +import pytest +from pytest import raises as assert_raises +from scipy.integrate import IntegrationWarning +import itertools + +from scipy import stats +from .common_tests import (check_normalization, check_moment, + check_mean_expect, + check_var_expect, check_skew_expect, + check_kurt_expect, check_entropy, + check_private_entropy, check_entropy_vect_scale, + check_edge_support, check_named_args, + check_random_state_property, + check_meth_dtype, check_ppf_dtype, + check_cmplx_deriv, + check_pickling, check_rvs_broadcast, + check_freezing, check_munp_expect,) +from scipy.stats._distr_params import distcont +from scipy.stats._distn_infrastructure import rv_continuous_frozen + +""" +Test all continuous distributions. + +Parameters were chosen for those distributions that pass the +Kolmogorov-Smirnov test. This provides safe parameters for each +distributions so that we can perform further testing of class methods. + +These tests currently check only/mostly for serious errors and exceptions, +not for numerically exact results. +""" + +# Note that you need to add new distributions you want tested +# to _distr_params + +DECIMAL = 5 # specify the precision of the tests # increased from 0 to 5 +_IS_32BIT = (sys.maxsize < 2**32) + +# Sets of tests to skip. +# Entries sorted by speed (very slow to slow). +# xslow took > 1s; slow took > 0.5s + +xslow_test_cont_basic = {'studentized_range', 'kstwo', 'ksone', 'vonmises', 'kappa4', + 'recipinvgauss', 'vonmises_line', 'gausshyper', + 'rel_breitwigner', 'norminvgauss'} +slow_test_cont_basic = {'crystalball', 'powerlognorm', 'pearson3'} + +# test_moments is already marked slow +xslow_test_moments = {'studentized_range', 'ksone', 'vonmises', 'vonmises_line', + 'recipinvgauss', 'kstwo', 'kappa4'} + +slow_fit_mle = {'exponweib', 'genexpon', 'genhyperbolic', 'johnsonsb', + 'kappa4', 'powerlognorm', 'tukeylambda'} +xslow_fit_mle = {'gausshyper', 'ncf', 'ncx2', 'recipinvgauss', 'vonmises_line'} +xfail_fit_mle = {'ksone', 'kstwo', 'trapezoid', 'truncpareto', 'irwinhall'} +skip_fit_mle = {'levy_stable', 'studentized_range'} # far too slow (>10min) +slow_fit_mm = {'chi2', 'expon', 'lognorm', 'loguniform', 'powerlaw', 'reciprocal'} +xslow_fit_mm = {'argus', 'beta', 'exponpow', 'gausshyper', 'gengamma', + 'genhalflogistic', 'geninvgauss', 'gompertz', 'halfgennorm', + 'johnsonsb', 'kstwobign', 'ncx2', 'norminvgauss', 'truncnorm', + 'truncweibull_min', 'wrapcauchy'} +xfail_fit_mm = {'alpha', 'betaprime', 'bradford', 'burr', 'burr12', 'cauchy', + 'crystalball', 'dpareto_lognorm', 'exponweib', 'f', 'fisk', + 'foldcauchy', 'genextreme', 'genpareto', 'halfcauchy', 'invgamma', + 'irwinhall', 'jf_skew_t', 'johnsonsu', 'kappa3', 'kappa4', 'landau', + 'levy', 'levy_l', 'loglaplace', 'lomax', 'mielke', 'ncf', 'nct', + 'pareto', 'powerlognorm', 'powernorm', 'rel_breitwigner', + 'skewcauchy', 't', 'trapezoid', 'truncexpon', 'truncpareto', + 'tukeylambda', 'vonmises', 'vonmises_line'} +skip_fit_mm = {'genexpon', 'genhyperbolic', 'ksone', 'kstwo', 'levy_stable', + 'recipinvgauss', 'studentized_range'} # far too slow (>10min) + +# These distributions fail the complex derivative test below. +# Here 'fail' mean produce wrong results and/or raise exceptions, depending +# on the implementation details of corresponding special functions. +# cf https://github.com/scipy/scipy/pull/4979 for a discussion. +fails_cmplx = {'argus', 'beta', 'betaprime', 'cauchy', 'chi', 'chi2', 'cosine', + 'dgamma', 'dpareto_lognorm', 'dweibull', 'erlang', 'f', 'foldcauchy', + 'gamma', 'gausshyper', 'gengamma', 'genhyperbolic', + 'geninvgauss', 'gennorm', 'genpareto', + 'halfcauchy', 'halfgennorm', 'invgamma', 'irwinhall', 'jf_skew_t', + 'ksone', 'kstwo', 'kstwobign', 'landau', 'levy_l', 'loggamma', + 'logistic', 'loguniform', 'maxwell', 'nakagami', + 'ncf', 'nct', 'ncx2', 'norminvgauss', 'pearson3', + 'powerlaw', 'rdist', 'reciprocal', 'rice', + 'skewnorm', 't', 'truncweibull_min', + 'tukeylambda', 'vonmises', 'vonmises_line', + 'rv_histogram_instance', 'truncnorm', 'studentized_range', + 'johnsonsb', 'halflogistic', 'rel_breitwigner'} + +# Slow test_method_with_lists +slow_with_lists = {'studentized_range'} + + +# rv_histogram instances, with uniform and non-uniform bins; +# stored as (dist, arg) tuples for cases_test_cont_basic +# and cases_test_moments. +histogram_test_instances = [] +case1 = {'a': [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, + 6, 6, 6, 7, 7, 7, 8, 8, 9], 'bins': 8} # equal width bins +case2 = {'a': [1, 1], 'bins': [0, 1, 10]} # unequal width bins +for case, density in itertools.product([case1, case2], [True, False]): + _hist = np.histogram(**case, density=density) + _rv_hist = stats.rv_histogram(_hist, density=density) + histogram_test_instances.append((_rv_hist, tuple())) + + +def cases_test_cont_basic(): + for distname, arg in distcont[:] + histogram_test_instances: + if distname == 'levy_stable': # fails; tested separately + continue + if distname in slow_test_cont_basic: + yield pytest.param(distname, arg, marks=pytest.mark.slow) + elif distname in xslow_test_cont_basic: + yield pytest.param(distname, arg, marks=pytest.mark.xslow) + else: + yield distname, arg + + +@pytest.mark.parametrize('distname,arg', cases_test_cont_basic()) +@pytest.mark.parametrize('sn', [500]) +def test_cont_basic(distname, arg, sn): + try: + distfn = getattr(stats, distname) + except TypeError: + distfn = distname + distname = 'rv_histogram_instance' + + rng = np.random.RandomState(765456) + rvs = distfn.rvs(size=sn, *arg, random_state=rng) + m, v = distfn.stats(*arg) + + if distname not in {'laplace_asymmetric'}: + check_sample_meanvar_(m, v, rvs) + check_cdf_ppf(distfn, arg, distname) + check_sf_isf(distfn, arg, distname) + check_cdf_sf(distfn, arg, distname) + check_ppf_isf(distfn, arg, distname) + check_pdf(distfn, arg, distname) + check_pdf_logpdf(distfn, arg, distname) + check_pdf_logpdf_at_endpoints(distfn, arg, distname) + check_cdf_logcdf(distfn, arg, distname) + check_sf_logsf(distfn, arg, distname) + check_ppf_broadcast(distfn, arg, distname) + + alpha = 0.01 + if distname == 'rv_histogram_instance': + check_distribution_rvs(distfn.cdf, arg, alpha, rvs) + elif distname != 'geninvgauss': + # skip kstest for geninvgauss since cdf is too slow; see test for + # rv generation in TestGenInvGauss in test_distributions.py + check_distribution_rvs(distname, arg, alpha, rvs) + + locscale_defaults = (0, 1) + meths = [distfn.pdf, distfn.logpdf, distfn.cdf, distfn.logcdf, + distfn.logsf] + # make sure arguments are within support + spec_x = {'weibull_max': -0.5, 'levy_l': -0.5, + 'pareto': 1.5, 'truncpareto': 3.2, 'tukeylambda': 0.3, + 'rv_histogram_instance': 5.0} + x = spec_x.get(distname, 0.5) + if distname == 'invweibull': + arg = (1,) + elif distname == 'ksone': + arg = (3,) + + check_named_args(distfn, x, arg, locscale_defaults, meths) + check_random_state_property(distfn, arg) + + if distname in ['rel_breitwigner'] and _IS_32BIT: + # gh18414 + pytest.skip("fails on Linux 32-bit") + else: + check_pickling(distfn, arg) + check_freezing(distfn, arg) + + # Entropy + if distname not in ['kstwobign', 'kstwo', 'ncf']: + check_entropy(distfn, arg, distname) + + if distfn.numargs == 0: + check_vecentropy(distfn, arg) + + if (distfn.__class__._entropy != stats.rv_continuous._entropy + and distname != 'vonmises'): + check_private_entropy(distfn, arg, stats.rv_continuous) + + with npt.suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error") + sup.filter(IntegrationWarning, "Extremely bad integrand") + sup.filter(RuntimeWarning, "invalid value") + check_entropy_vect_scale(distfn, arg) + + check_retrieving_support(distfn, arg) + check_edge_support(distfn, arg) + + check_meth_dtype(distfn, arg, meths) + check_ppf_dtype(distfn, arg) + + if distname not in fails_cmplx: + check_cmplx_deriv(distfn, arg) + + if distname != 'truncnorm': + check_ppf_private(distfn, arg, distname) + + +def cases_test_cont_basic_fit(): + slow = pytest.mark.slow + xslow = pytest.mark.xslow + fail = pytest.mark.skip(reason="Test fails and may be slow.") + skip = pytest.mark.skip(reason="Test too slow to run to completion (>10m).") + + for distname, arg in distcont[:] + histogram_test_instances: + for method in ["MLE", "MM"]: + for fix_args in [True, False]: + if method == 'MLE' and distname in slow_fit_mle: + yield pytest.param(distname, arg, method, fix_args, marks=slow) + continue + if method == 'MLE' and distname in xslow_fit_mle: + yield pytest.param(distname, arg, method, fix_args, marks=xslow) + continue + if method == 'MLE' and distname in xfail_fit_mle: + yield pytest.param(distname, arg, method, fix_args, marks=fail) + continue + if method == 'MLE' and distname in skip_fit_mle: + yield pytest.param(distname, arg, method, fix_args, marks=skip) + continue + if method == 'MM' and distname in slow_fit_mm: + yield pytest.param(distname, arg, method, fix_args, marks=slow) + continue + if method == 'MM' and distname in xslow_fit_mm: + yield pytest.param(distname, arg, method, fix_args, marks=xslow) + continue + if method == 'MM' and distname in xfail_fit_mm: + yield pytest.param(distname, arg, method, fix_args, marks=fail) + continue + if method == 'MM' and distname in skip_fit_mm: + yield pytest.param(distname, arg, method, fix_args, marks=skip) + continue + + yield distname, arg, method, fix_args + + +def test_cont_basic_fit_cases(): + # Distribution names should not be in multiple MLE or MM sets + assert (len(xslow_fit_mle.union(xfail_fit_mle).union(skip_fit_mle)) == + len(xslow_fit_mle) + len(xfail_fit_mle) + len(skip_fit_mle)) + assert (len(xslow_fit_mm.union(xfail_fit_mm).union(skip_fit_mm)) == + len(xslow_fit_mm) + len(xfail_fit_mm) + len(skip_fit_mm)) + + +@pytest.mark.parametrize('distname, arg, method, fix_args', + cases_test_cont_basic_fit()) +@pytest.mark.parametrize('n_fit_samples', [200]) +def test_cont_basic_fit(distname, arg, n_fit_samples, method, fix_args): + try: + distfn = getattr(stats, distname) + except TypeError: + distfn = distname + + rng = np.random.RandomState(765456) + rvs = distfn.rvs(size=n_fit_samples, *arg, random_state=rng) + if fix_args: + check_fit_args_fix(distfn, arg, rvs, method) + else: + check_fit_args(distfn, arg, rvs, method) + +@pytest.mark.parametrize('distname,arg', cases_test_cont_basic()) +def test_rvs_scalar(distname, arg): + # rvs should return a scalar when given scalar arguments (gh-12428) + try: + distfn = getattr(stats, distname) + except TypeError: + distfn = distname + distname = 'rv_histogram_instance' + + assert np.isscalar(distfn.rvs(*arg)) + assert np.isscalar(distfn.rvs(*arg, size=())) + assert np.isscalar(distfn.rvs(*arg, size=None)) + + +def test_levy_stable_random_state_property(): + # levy_stable only implements rvs(), so it is skipped in the + # main loop in test_cont_basic(). Here we apply just the test + # check_random_state_property to levy_stable. + check_random_state_property(stats.levy_stable, (0.5, 0.1)) + + +def cases_test_moments(): + fail_normalization = set() + fail_higher = {'ncf'} + fail_moment = {'johnsonsu'} # generic `munp` is inaccurate for johnsonsu + + for distname, arg in distcont[:] + histogram_test_instances: + if distname == 'levy_stable': + continue + + if distname in xslow_test_moments: + yield pytest.param(distname, arg, True, True, True, True, + marks=pytest.mark.xslow(reason="too slow")) + continue + + cond1 = distname not in fail_normalization + cond2 = distname not in fail_higher + cond3 = distname not in fail_moment + + marks = list() + # Currently unused, `marks` can be used to add a timeout to a test of + # a specific distribution. For example, this shows how a timeout could + # be added for the 'skewnorm' distribution: + # + # marks = list() + # if distname == 'skewnorm': + # marks.append(pytest.mark.timeout(300)) + + yield pytest.param(distname, arg, cond1, cond2, cond3, + False, marks=marks) + + if not cond1 or not cond2 or not cond3: + # Run the distributions that have issues twice, once skipping the + # not_ok parts, once with the not_ok parts but marked as knownfail + yield pytest.param(distname, arg, True, True, True, True, + marks=[pytest.mark.xfail] + marks) + + +@pytest.mark.slow +@pytest.mark.parametrize('distname,arg,normalization_ok,higher_ok,moment_ok,' + 'is_xfailing', + cases_test_moments()) +def test_moments(distname, arg, normalization_ok, higher_ok, moment_ok, + is_xfailing): + try: + distfn = getattr(stats, distname) + except TypeError: + distfn = distname + distname = 'rv_histogram_instance' + + with npt.suppress_warnings() as sup: + sup.filter(IntegrationWarning, + "The integral is probably divergent, or slowly convergent.") + sup.filter(IntegrationWarning, + "The maximum number of subdivisions.") + sup.filter(IntegrationWarning, + "The algorithm does not converge.") + + if is_xfailing: + sup.filter(IntegrationWarning) + + m, v, s, k = distfn.stats(*arg, moments='mvsk') + + with np.errstate(all="ignore"): + if normalization_ok: + check_normalization(distfn, arg, distname) + + if higher_ok: + check_mean_expect(distfn, arg, m, distname) + check_skew_expect(distfn, arg, m, v, s, distname) + check_var_expect(distfn, arg, m, v, distname) + check_kurt_expect(distfn, arg, m, v, k, distname) + check_munp_expect(distfn, arg, distname) + + check_loc_scale(distfn, arg, m, v, distname) + + if moment_ok: + check_moment(distfn, arg, m, v, distname) + + +@pytest.mark.parametrize('dist,shape_args', distcont) +def test_rvs_broadcast(dist, shape_args): + if dist in ['gausshyper', 'studentized_range']: + pytest.skip("too slow") + + if dist in ['rel_breitwigner'] and _IS_32BIT: + # gh18414 + pytest.skip("fails on Linux 32-bit") + + # If shape_only is True, it means the _rvs method of the + # distribution uses more than one random number to generate a random + # variate. That means the result of using rvs with broadcasting or + # with a nontrivial size will not necessarily be the same as using the + # numpy.vectorize'd version of rvs(), so we can only compare the shapes + # of the results, not the values. + # Whether or not a distribution is in the following list is an + # implementation detail of the distribution, not a requirement. If + # the implementation the rvs() method of a distribution changes, this + # test might also have to be changed. + shape_only = dist in ['argus', 'betaprime', 'dgamma', 'dpareto_lognorm', 'dweibull', + 'exponnorm', 'genhyperbolic', 'geninvgauss', 'landau', + 'levy_stable', 'nct', 'norminvgauss', 'rice', + 'skewnorm', 'semicircular', 'gennorm', 'loggamma'] + + distfunc = getattr(stats, dist) + loc = np.zeros(2) + scale = np.ones((3, 1)) + nargs = distfunc.numargs + allargs = [] + bshape = [3, 2] + # Generate shape parameter arguments... + for k in range(nargs): + shp = (k + 4,) + (1,)*(k + 2) + allargs.append(shape_args[k]*np.ones(shp)) + bshape.insert(0, k + 4) + allargs.extend([loc, scale]) + # bshape holds the expected shape when loc, scale, and the shape + # parameters are all broadcast together. + + check_rvs_broadcast(distfunc, dist, allargs, bshape, shape_only, 'd') + + +# Expected values of the SF, CDF, PDF were computed using +# mpmath with mpmath.mp.dps = 50 and output at 20: +# +# def ks(x, n): +# x = mpmath.mpf(x) +# logp = -mpmath.power(6.0*n*x+1.0, 2)/18.0/n +# sf, cdf = mpmath.exp(logp), -mpmath.expm1(logp) +# pdf = (6.0*n*x+1.0) * 2 * sf/3 +# print(mpmath.nstr(sf, 20), mpmath.nstr(cdf, 20), mpmath.nstr(pdf, 20)) +# +# Tests use 1/n < x < 1-1/n and n > 1e6 to use the asymptotic computation. +# Larger x has a smaller sf. +@pytest.mark.parametrize('x,n,sf,cdf,pdf,rtol', + [(2.0e-5, 1000000000, + 0.44932297307934442379, 0.55067702692065557621, + 35946.137394996276407, 5e-15), + (2.0e-9, 1000000000, + 0.99999999061111115519, 9.3888888448132728224e-9, + 8.6666665852962971765, 5e-14), + (5.0e-4, 1000000000, + 7.1222019433090374624e-218, 1.0, + 1.4244408634752704094e-211, 5e-14)]) +def test_gh17775_regression(x, n, sf, cdf, pdf, rtol): + # Regression test for gh-17775. In scipy 1.9.3 and earlier, + # these test would fail. + # + # KS one asymptotic sf ~ e^(-(6nx+1)^2 / 18n) + # Given a large 32-bit integer n, 6n will overflow in the c implementation. + # Example of broken behaviour: + # ksone.sf(2.0e-5, 1000000000) == 0.9374359693473666 + ks = stats.ksone + vals = np.array([ks.sf(x, n), ks.cdf(x, n), ks.pdf(x, n)]) + expected = np.array([sf, cdf, pdf]) + npt.assert_allclose(vals, expected, rtol=rtol) + # The sf+cdf must sum to 1.0. + npt.assert_equal(vals[0] + vals[1], 1.0) + # Check inverting the (potentially very small) sf (uses a lower tolerance) + npt.assert_allclose([ks.isf(sf, n)], [x], rtol=1e-8) + + +def test_rvs_gh2069_regression(): + # Regression tests for gh-2069. In scipy 0.17 and earlier, + # these tests would fail. + # + # A typical example of the broken behavior: + # >>> norm.rvs(loc=np.zeros(5), scale=np.ones(5)) + # array([-2.49613705, -2.49613705, -2.49613705, -2.49613705, -2.49613705]) + rng = np.random.RandomState(123) + vals = stats.norm.rvs(loc=np.zeros(5), scale=1, random_state=rng) + d = np.diff(vals) + npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!") + vals = stats.norm.rvs(loc=0, scale=np.ones(5), random_state=rng) + d = np.diff(vals) + npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!") + vals = stats.norm.rvs(loc=np.zeros(5), scale=np.ones(5), random_state=rng) + d = np.diff(vals) + npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!") + vals = stats.norm.rvs(loc=np.array([[0], [0]]), scale=np.ones(5), + random_state=rng) + d = np.diff(vals.ravel()) + npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!") + + assert_raises(ValueError, stats.norm.rvs, [[0, 0], [0, 0]], + [[1, 1], [1, 1]], 1) + assert_raises(ValueError, stats.gamma.rvs, [2, 3, 4, 5], 0, 1, (2, 2)) + assert_raises(ValueError, stats.gamma.rvs, [1, 1, 1, 1], [0, 0, 0, 0], + [[1], [2]], (4,)) + + +def test_nomodify_gh9900_regression(): + # Regression test for gh-9990 + # Prior to gh-9990, calls to stats.truncnorm._cdf() use what ever was + # set inside the stats.truncnorm instance during stats.truncnorm.cdf(). + # This could cause issues with multi-threaded code. + # Since then, the calls to cdf() are not permitted to modify the global + # stats.truncnorm instance. + tn = stats.truncnorm + # Use the right-half truncated normal + # Check that the cdf and _cdf return the same result. + npt.assert_almost_equal(tn.cdf(1, 0, np.inf), + 0.6826894921370859) + npt.assert_almost_equal(tn._cdf([1], [0], [np.inf]), + 0.6826894921370859) + + # Now use the left-half truncated normal + npt.assert_almost_equal(tn.cdf(-1, -np.inf, 0), + 0.31731050786291415) + npt.assert_almost_equal(tn._cdf([-1], [-np.inf], [0]), + 0.31731050786291415) + + # Check that the right-half truncated normal _cdf hasn't changed + npt.assert_almost_equal(tn._cdf([1], [0], [np.inf]), + 0.6826894921370859) # Not 1.6826894921370859 + npt.assert_almost_equal(tn.cdf(1, 0, np.inf), + 0.6826894921370859) + + # Check that the left-half truncated normal _cdf hasn't changed + npt.assert_almost_equal(tn._cdf([-1], [-np.inf], [0]), + 0.31731050786291415) # Not -0.6826894921370859 + npt.assert_almost_equal(tn.cdf(1, -np.inf, 0), + 1) # Not 1.6826894921370859 + npt.assert_almost_equal(tn.cdf(-1, -np.inf, 0), + 0.31731050786291415) # Not -0.6826894921370859 + + +def test_broadcast_gh9990_regression(): + # Regression test for gh-9990 + # The x-value 7 only lies within the support of 4 of the supplied + # distributions. Prior to 9990, one array passed to + # stats.reciprocal._cdf would have 4 elements, but an array + # previously stored by stats.reciprocal_argcheck() would have 6, leading + # to a broadcast error. + a = np.array([1, 2, 3, 4, 5, 6]) + b = np.array([8, 16, 1, 32, 1, 48]) + ans = [stats.reciprocal.cdf(7, _a, _b) for _a, _b in zip(a,b)] + npt.assert_array_almost_equal(stats.reciprocal.cdf(7, a, b), ans) + + ans = [stats.reciprocal.cdf(1, _a, _b) for _a, _b in zip(a,b)] + npt.assert_array_almost_equal(stats.reciprocal.cdf(1, a, b), ans) + + ans = [stats.reciprocal.cdf(_a, _a, _b) for _a, _b in zip(a,b)] + npt.assert_array_almost_equal(stats.reciprocal.cdf(a, a, b), ans) + + ans = [stats.reciprocal.cdf(_b, _a, _b) for _a, _b in zip(a,b)] + npt.assert_array_almost_equal(stats.reciprocal.cdf(b, a, b), ans) + + +def test_broadcast_gh7933_regression(): + # Check broadcast works + stats.truncnorm.logpdf( + np.array([3.0, 2.0, 1.0]), + a=(1.5 - np.array([6.0, 5.0, 4.0])) / 3.0, + b=np.inf, + loc=np.array([6.0, 5.0, 4.0]), + scale=3.0 + ) + + +def test_gh2002_regression(): + # Add a check that broadcast works in situations where only some + # x-values are compatible with some of the shape arguments. + x = np.r_[-2:2:101j] + a = np.r_[-np.ones(50), np.ones(51)] + expected = [stats.truncnorm.pdf(_x, _a, np.inf) for _x, _a in zip(x, a)] + ans = stats.truncnorm.pdf(x, a, np.inf) + npt.assert_array_almost_equal(ans, expected) + + +def test_gh1320_regression(): + # Check that the first example from gh-1320 now works. + c = 2.62 + stats.genextreme.ppf(0.5, np.array([[c], [c + 0.5]])) + # The other examples in gh-1320 appear to have stopped working + # some time ago. + # ans = stats.genextreme.moment(2, np.array([c, c + 0.5])) + # expected = np.array([25.50105963, 115.11191437]) + # stats.genextreme.moment(5, np.array([[c], [c + 0.5]])) + # stats.genextreme.moment(5, np.array([c, c + 0.5])) + + +def test_method_of_moments(): + # example from https://en.wikipedia.org/wiki/Method_of_moments_(statistics) + np.random.seed(1234) + x = [0, 0, 0, 0, 1] + a = 1/5 - 2*np.sqrt(3)/5 + b = 1/5 + 2*np.sqrt(3)/5 + # force use of method of moments (uniform.fit is overridden) + loc, scale = super(type(stats.uniform), stats.uniform).fit(x, method="MM") + npt.assert_almost_equal(loc, a, decimal=4) + npt.assert_almost_equal(loc+scale, b, decimal=4) + + +def check_sample_meanvar_(popmean, popvar, sample): + if np.isfinite(popmean): + check_sample_mean(sample, popmean) + if np.isfinite(popvar): + check_sample_var(sample, popvar) + + +def check_sample_mean(sample, popmean): + # Checks for unlikely difference between sample mean and population mean + prob = stats.ttest_1samp(sample, popmean).pvalue + assert prob > 0.01 + + +def check_sample_var(sample, popvar): + # check that population mean lies within the CI bootstrapped from the + # sample. This used to be a chi-squared test for variance, but there were + # too many false positives + res = stats.bootstrap( + (sample,), + lambda x, axis: x.var(ddof=1, axis=axis), + confidence_level=0.995, + ) + conf = res.confidence_interval + low, high = conf.low, conf.high + assert low <= popvar <= high + + +def check_cdf_ppf(distfn, arg, msg): + values = [0.001, 0.5, 0.999] + npt.assert_almost_equal(distfn.cdf(distfn.ppf(values, *arg), *arg), + values, decimal=DECIMAL, err_msg=msg + + ' - cdf-ppf roundtrip') + + +def check_sf_isf(distfn, arg, msg): + npt.assert_almost_equal(distfn.sf(distfn.isf([0.1, 0.5, 0.9], *arg), *arg), + [0.1, 0.5, 0.9], decimal=DECIMAL, err_msg=msg + + ' - sf-isf roundtrip') + + +def check_cdf_sf(distfn, arg, msg): + npt.assert_almost_equal(distfn.cdf([0.1, 0.9], *arg), + 1.0 - distfn.sf([0.1, 0.9], *arg), + decimal=DECIMAL, err_msg=msg + + ' - cdf-sf relationship') + + +def check_ppf_isf(distfn, arg, msg): + p = np.array([0.1, 0.9]) + npt.assert_almost_equal(distfn.isf(p, *arg), distfn.ppf(1-p, *arg), + decimal=DECIMAL, err_msg=msg + + ' - ppf-isf relationship') + + +def check_pdf(distfn, arg, msg): + # compares pdf at median with numerical derivative of cdf + median = distfn.ppf(0.5, *arg) + eps = 1e-6 + pdfv = distfn.pdf(median, *arg) + if (pdfv < 1e-4) or (pdfv > 1e4): + # avoid checking a case where pdf is close to zero or + # huge (singularity) + median = median + 0.1 + pdfv = distfn.pdf(median, *arg) + cdfdiff = (distfn.cdf(median + eps, *arg) - + distfn.cdf(median - eps, *arg))/eps/2.0 + # replace with better diff and better test (more points), + # actually, this works pretty well + msg += ' - cdf-pdf relationship' + npt.assert_almost_equal(pdfv, cdfdiff, decimal=DECIMAL, err_msg=msg) + + +def check_pdf_logpdf(distfn, args, msg): + # compares pdf at several points with the log of the pdf + points = np.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]) + vals = distfn.ppf(points, *args) + vals = vals[np.isfinite(vals)] + pdf = distfn.pdf(vals, *args) + logpdf = distfn.logpdf(vals, *args) + pdf = pdf[(pdf != 0) & np.isfinite(pdf)] + logpdf = logpdf[np.isfinite(logpdf)] + msg += " - logpdf-log(pdf) relationship" + npt.assert_almost_equal(np.log(pdf), logpdf, decimal=7, err_msg=msg) + + +def check_pdf_logpdf_at_endpoints(distfn, args, msg): + # compares pdf with the log of the pdf at the (finite) end points + points = np.array([0, 1]) + vals = distfn.ppf(points, *args) + vals = vals[np.isfinite(vals)] + pdf = distfn.pdf(vals, *args) + logpdf = distfn.logpdf(vals, *args) + pdf = pdf[(pdf != 0) & np.isfinite(pdf)] + logpdf = logpdf[np.isfinite(logpdf)] + msg += " - logpdf-log(pdf) relationship" + npt.assert_almost_equal(np.log(pdf), logpdf, decimal=7, err_msg=msg) + + +def check_sf_logsf(distfn, args, msg): + # compares sf at several points with the log of the sf + points = np.array([0.0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0]) + vals = distfn.ppf(points, *args) + vals = vals[np.isfinite(vals)] + sf = distfn.sf(vals, *args) + logsf = distfn.logsf(vals, *args) + sf = sf[sf != 0] + logsf = logsf[np.isfinite(logsf)] + msg += " - logsf-log(sf) relationship" + npt.assert_almost_equal(np.log(sf), logsf, decimal=7, err_msg=msg) + + +def check_cdf_logcdf(distfn, args, msg): + # compares cdf at several points with the log of the cdf + points = np.array([0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0]) + vals = distfn.ppf(points, *args) + vals = vals[np.isfinite(vals)] + cdf = distfn.cdf(vals, *args) + logcdf = distfn.logcdf(vals, *args) + cdf = cdf[cdf != 0] + logcdf = logcdf[np.isfinite(logcdf)] + msg += " - logcdf-log(cdf) relationship" + npt.assert_almost_equal(np.log(cdf), logcdf, decimal=7, err_msg=msg) + + +def check_ppf_broadcast(distfn, arg, msg): + # compares ppf for multiple argsets. + num_repeats = 5 + args = [] * num_repeats + if arg: + args = [np.array([_] * num_repeats) for _ in arg] + + median = distfn.ppf(0.5, *arg) + medians = distfn.ppf(0.5, *args) + msg += " - ppf multiple" + npt.assert_almost_equal(medians, [median] * num_repeats, decimal=7, err_msg=msg) + + +def check_distribution_rvs(dist, args, alpha, rvs): + # dist is either a cdf function or name of a distribution in scipy.stats. + # args are the args for scipy.stats.dist(*args) + # alpha is a significance level, ~0.01 + # rvs is array_like of random variables + # test from scipy.stats.tests + # this version reuses existing random variables + D, pval = stats.kstest(rvs, dist, args=args, N=1000) + if (pval < alpha): + # The rvs passed in failed the K-S test, which _could_ happen + # but is unlikely if alpha is small enough. + # Repeat the test with a new sample of rvs. + # Generate 1000 rvs, perform a K-S test that the new sample of rvs + # are distributed according to the distribution. + D, pval = stats.kstest(dist, dist, args=args, N=1000) + npt.assert_(pval > alpha, "D = " + str(D) + "; pval = " + str(pval) + + "; alpha = " + str(alpha) + "\nargs = " + str(args)) + + +def check_vecentropy(distfn, args): + npt.assert_equal(distfn.vecentropy(*args), distfn._entropy(*args)) + + +def check_loc_scale(distfn, arg, m, v, msg): + # Make `loc` and `scale` arrays to catch bugs like gh-13580 where + # `loc` and `scale` arrays improperly broadcast with shapes. + loc, scale = np.array([10.0, 20.0]), np.array([10.0, 20.0]) + mt, vt = distfn.stats(*arg, loc=loc, scale=scale) + npt.assert_allclose(m*scale + loc, mt) + npt.assert_allclose(v*scale*scale, vt) + + +def check_ppf_private(distfn, arg, msg): + # fails by design for truncnorm self.nb not defined + ppfs = distfn._ppf(np.array([0.1, 0.5, 0.9]), *arg) + npt.assert_(not np.any(np.isnan(ppfs)), msg + 'ppf private is nan') + + +def check_retrieving_support(distfn, args): + loc, scale = 1, 2 + supp = distfn.support(*args) + supp_loc_scale = distfn.support(*args, loc=loc, scale=scale) + npt.assert_almost_equal(np.array(supp)*scale + loc, + np.array(supp_loc_scale)) + + +def check_fit_args(distfn, arg, rvs, method): + with np.errstate(all='ignore'), npt.suppress_warnings() as sup: + sup.filter(category=RuntimeWarning, + message="The shape parameter of the erlang") + sup.filter(category=RuntimeWarning, + message="floating point number truncated") + vals = distfn.fit(rvs, method=method) + vals2 = distfn.fit(rvs, optimizer='powell', method=method) + # Only check the length of the return; accuracy tested in test_fit.py + npt.assert_(len(vals) == 2+len(arg)) + npt.assert_(len(vals2) == 2+len(arg)) + + +def check_fit_args_fix(distfn, arg, rvs, method): + with np.errstate(all='ignore'), npt.suppress_warnings() as sup: + sup.filter(category=RuntimeWarning, + message="The shape parameter of the erlang") + + vals = distfn.fit(rvs, floc=0, method=method) + vals2 = distfn.fit(rvs, fscale=1, method=method) + npt.assert_(len(vals) == 2+len(arg)) + npt.assert_(vals[-2] == 0) + npt.assert_(vals2[-1] == 1) + npt.assert_(len(vals2) == 2+len(arg)) + if len(arg) > 0: + vals3 = distfn.fit(rvs, f0=arg[0], method=method) + npt.assert_(len(vals3) == 2+len(arg)) + npt.assert_(vals3[0] == arg[0]) + if len(arg) > 1: + vals4 = distfn.fit(rvs, f1=arg[1], method=method) + npt.assert_(len(vals4) == 2+len(arg)) + npt.assert_(vals4[1] == arg[1]) + if len(arg) > 2: + vals5 = distfn.fit(rvs, f2=arg[2], method=method) + npt.assert_(len(vals5) == 2+len(arg)) + npt.assert_(vals5[2] == arg[2]) + + +def cases_test_methods_with_lists(): + for distname, arg in distcont: + if distname in slow_with_lists: + yield pytest.param(distname, arg, marks=pytest.mark.slow) + else: + yield distname, arg + + +@pytest.mark.parametrize('method', ['pdf', 'logpdf', 'cdf', 'logcdf', + 'sf', 'logsf', 'ppf', 'isf']) +@pytest.mark.parametrize('distname, args', cases_test_methods_with_lists()) +def test_methods_with_lists(method, distname, args): + # Test that the continuous distributions can accept Python lists + # as arguments. + dist = getattr(stats, distname) + f = getattr(dist, method) + if distname == 'invweibull' and method.startswith('log'): + x = [1.5, 2] + else: + x = [0.1, 0.2] + + shape2 = [[a]*2 for a in args] + loc = [0, 0.1] + scale = [1, 1.01] + result = f(x, *shape2, loc=loc, scale=scale) + npt.assert_allclose(result, + [f(*v) for v in zip(x, *shape2, loc, scale)], + rtol=1e-14, atol=5e-14) + + +def test_burr_fisk_moment_gh13234_regression(): + vals0 = stats.burr.moment(1, 5, 4) + assert isinstance(vals0, float) + + vals1 = stats.fisk.moment(1, 8) + assert isinstance(vals1, float) + + +def test_moments_with_array_gh12192_regression(): + # array loc and scalar scale + vals0 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]), scale=1) + expected0 = np.array([1., 2., 3.]) + npt.assert_equal(vals0, expected0) + + # array loc and invalid scalar scale + vals1 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]), scale=-1) + expected1 = np.array([np.nan, np.nan, np.nan]) + npt.assert_equal(vals1, expected1) + + # array loc and array scale with invalid entries + vals2 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]), + scale=[-3, 1, 0]) + expected2 = np.array([np.nan, 2., np.nan]) + npt.assert_equal(vals2, expected2) + + # (loc == 0) & (scale < 0) + vals3 = stats.norm.moment(order=2, loc=0, scale=-4) + expected3 = np.nan + npt.assert_equal(vals3, expected3) + assert isinstance(vals3, expected3.__class__) + + # array loc with 0 entries and scale with invalid entries + vals4 = stats.norm.moment(order=2, loc=[1, 0, 2], scale=[3, -4, -5]) + expected4 = np.array([10., np.nan, np.nan]) + npt.assert_equal(vals4, expected4) + + # all(loc == 0) & (array scale with invalid entries) + vals5 = stats.norm.moment(order=2, loc=[0, 0, 0], scale=[5., -2, 100.]) + expected5 = np.array([25., np.nan, 10000.]) + npt.assert_equal(vals5, expected5) + + # all( (loc == 0) & (scale < 0) ) + vals6 = stats.norm.moment(order=2, loc=[0, 0, 0], scale=[-5., -2, -100.]) + expected6 = np.array([np.nan, np.nan, np.nan]) + npt.assert_equal(vals6, expected6) + + # scalar args, loc, and scale + vals7 = stats.chi.moment(order=2, df=1, loc=0, scale=0) + expected7 = np.nan + npt.assert_equal(vals7, expected7) + assert isinstance(vals7, expected7.__class__) + + # array args, scalar loc, and scalar scale + vals8 = stats.chi.moment(order=2, df=[1, 2, 3], loc=0, scale=0) + expected8 = np.array([np.nan, np.nan, np.nan]) + npt.assert_equal(vals8, expected8) + + # array args, array loc, and array scale + vals9 = stats.chi.moment(order=2, df=[1, 2, 3], loc=[1., 0., 2.], + scale=[1., -3., 0.]) + expected9 = np.array([3.59576912, np.nan, np.nan]) + npt.assert_allclose(vals9, expected9, rtol=1e-8) + + # (n > 4), all(loc != 0), and all(scale != 0) + vals10 = stats.norm.moment(5, [1., 2.], [1., 2.]) + expected10 = np.array([26., 832.]) + npt.assert_allclose(vals10, expected10, rtol=1e-13) + + # test broadcasting and more + a = [-1.1, 0, 1, 2.2, np.pi] + b = [-1.1, 0, 1, 2.2, np.pi] + loc = [-1.1, 0, np.sqrt(2)] + scale = [-2.1, 0, 1, 2.2, np.pi] + + a = np.array(a).reshape((-1, 1, 1, 1)) + b = np.array(b).reshape((-1, 1, 1)) + loc = np.array(loc).reshape((-1, 1)) + scale = np.array(scale) + + vals11 = stats.beta.moment(order=2, a=a, b=b, loc=loc, scale=scale) + + a, b, loc, scale = np.broadcast_arrays(a, b, loc, scale) + + for i in np.ndenumerate(a): + with np.errstate(invalid='ignore', divide='ignore'): + i = i[0] # just get the index + # check against same function with scalar input + expected = stats.beta.moment(order=2, a=a[i], b=b[i], + loc=loc[i], scale=scale[i]) + np.testing.assert_equal(vals11[i], expected) + + +def test_broadcasting_in_moments_gh12192_regression(): + vals0 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]), scale=[[1]]) + expected0 = np.array([[1., 2., 3.]]) + npt.assert_equal(vals0, expected0) + assert vals0.shape == expected0.shape + + vals1 = stats.norm.moment(order=1, loc=np.array([[1], [2], [3]]), + scale=[1, 2, 3]) + expected1 = np.array([[1., 1., 1.], [2., 2., 2.], [3., 3., 3.]]) + npt.assert_equal(vals1, expected1) + assert vals1.shape == expected1.shape + + vals2 = stats.chi.moment(order=1, df=[1., 2., 3.], loc=0., scale=1.) + expected2 = np.array([0.79788456, 1.25331414, 1.59576912]) + npt.assert_allclose(vals2, expected2, rtol=1e-8) + assert vals2.shape == expected2.shape + + vals3 = stats.chi.moment(order=1, df=[[1.], [2.], [3.]], loc=[0., 1., 2.], + scale=[-1., 0., 3.]) + expected3 = np.array([[np.nan, np.nan, 4.39365368], + [np.nan, np.nan, 5.75994241], + [np.nan, np.nan, 6.78730736]]) + npt.assert_allclose(vals3, expected3, rtol=1e-8) + assert vals3.shape == expected3.shape + + +@pytest.mark.slow +def test_kappa3_array_gh13582(): + # https://github.com/scipy/scipy/pull/15140#issuecomment-994958241 + shapes = [0.5, 1.5, 2.5, 3.5, 4.5] + moments = 'mvsk' + res = np.array([[stats.kappa3.stats(shape, moments=moment) + for shape in shapes] for moment in moments]) + res2 = np.array(stats.kappa3.stats(shapes, moments=moments)) + npt.assert_allclose(res, res2) + + +@pytest.mark.xslow +def test_kappa4_array_gh13582(): + h = np.array([-0.5, 2.5, 3.5, 4.5, -3]) + k = np.array([-0.5, 1, -1.5, 0, 3.5]) + moments = 'mvsk' + res = np.array([[stats.kappa4.stats(h[i], k[i], moments=moment) + for i in range(5)] for moment in moments]) + res2 = np.array(stats.kappa4.stats(h, k, moments=moments)) + npt.assert_allclose(res, res2) + + # https://github.com/scipy/scipy/pull/15250#discussion_r775112913 + h = np.array([-1, -1/4, -1/4, 1, -1, 0]) + k = np.array([1, 1, 1/2, -1/3, -1, 0]) + res = np.array([[stats.kappa4.stats(h[i], k[i], moments=moment) + for i in range(6)] for moment in moments]) + res2 = np.array(stats.kappa4.stats(h, k, moments=moments)) + npt.assert_allclose(res, res2) + + # https://github.com/scipy/scipy/pull/15250#discussion_r775115021 + h = np.array([-1, -0.5, 1]) + k = np.array([-1, -0.5, 0, 1])[:, None] + res2 = np.array(stats.kappa4.stats(h, k, moments=moments)) + assert res2.shape == (4, 4, 3) + + +def test_frozen_attributes(): + # gh-14827 reported that all frozen distributions had both pmf and pdf + # attributes; continuous should have pdf and discrete should have pmf. + message = "'rv_continuous_frozen' object has no attribute" + with pytest.raises(AttributeError, match=message): + stats.norm().pmf + with pytest.raises(AttributeError, match=message): + stats.norm().logpmf + stats.norm.pmf = "herring" + frozen_norm = stats.norm() + assert isinstance(frozen_norm, rv_continuous_frozen) + delattr(stats.norm, 'pmf') + + +def test_skewnorm_pdf_gh16038(): + rng = np.random.default_rng(0) + x, a = -np.inf, 0 + npt.assert_equal(stats.skewnorm.pdf(x, a), stats.norm.pdf(x)) + x, a = rng.random(size=(3, 3)), rng.random(size=(3, 3)) + mask = rng.random(size=(3, 3)) < 0.5 + a[mask] = 0 + x_norm = x[mask] + res = stats.skewnorm.pdf(x, a) + npt.assert_equal(res[mask], stats.norm.pdf(x_norm)) + npt.assert_equal(res[~mask], stats.skewnorm.pdf(x[~mask], a[~mask])) + + +# for scalar input, these functions should return scalar output +scalar_out = [['rvs', []], ['pdf', [0]], ['logpdf', [0]], ['cdf', [0]], + ['logcdf', [0]], ['sf', [0]], ['logsf', [0]], ['ppf', [0]], + ['isf', [0]], ['moment', [1]], ['entropy', []], ['expect', []], + ['median', []], ['mean', []], ['std', []], ['var', []]] +scalars_out = [['interval', [0.95]], ['support', []], ['stats', ['mv']]] + + +@pytest.mark.parametrize('case', scalar_out + scalars_out) +def test_scalar_for_scalar(case): + # Some rv_continuous functions returned 0d array instead of NumPy scalar + # Guard against regression + method_name, args = case + method = getattr(stats.norm(), method_name) + res = method(*args) + if case in scalar_out: + assert isinstance(res, np.number) + else: + assert isinstance(res[0], np.number) + assert isinstance(res[1], np.number) + + +def test_scalar_for_scalar2(): + # test methods that are not attributes of frozen distributions + res = stats.norm.fit([1, 2, 3]) + assert isinstance(res[0], np.number) + assert isinstance(res[1], np.number) + res = stats.norm.fit_loc_scale([1, 2, 3]) + assert isinstance(res[0], np.number) + assert isinstance(res[1], np.number) + res = stats.norm.nnlf((0, 1), [1, 2, 3]) + assert isinstance(res, np.number) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_fit_censored.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_fit_censored.py new file mode 100644 index 0000000000000000000000000000000000000000..4508b49712e5bc8975bf2f9b2681ccc6504b0ae0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_fit_censored.py @@ -0,0 +1,683 @@ +# Tests for fitting specific distributions to censored data. + +import numpy as np +from numpy.testing import assert_allclose + +from scipy.optimize import fmin +from scipy.stats import (CensoredData, beta, cauchy, chi2, expon, gamma, + gumbel_l, gumbel_r, invgauss, invweibull, laplace, + logistic, lognorm, nct, ncx2, norm, weibull_max, + weibull_min) + + +# In some tests, we'll use this optimizer for improved accuracy. +def optimizer(func, x0, args=(), disp=0): + return fmin(func, x0, args=args, disp=disp, xtol=1e-12, ftol=1e-12) + + +def test_beta(): + """ + Test fitting beta shape parameters to interval-censored data. + + Calculation in R: + + > library(fitdistrplus) + > data <- data.frame(left=c(0.10, 0.50, 0.75, 0.80), + + right=c(0.20, 0.55, 0.90, 0.95)) + > result = fitdistcens(data, 'beta', control=list(reltol=1e-14)) + + > result + Fitting of the distribution ' beta ' on censored data by maximum likelihood + Parameters: + estimate + shape1 1.419941 + shape2 1.027066 + > result$sd + shape1 shape2 + 0.9914177 0.6866565 + """ + data = CensoredData(interval=[[0.10, 0.20], + [0.50, 0.55], + [0.75, 0.90], + [0.80, 0.95]]) + + # For this test, fit only the shape parameters; loc and scale are fixed. + a, b, loc, scale = beta.fit(data, floc=0, fscale=1, optimizer=optimizer) + + assert_allclose(a, 1.419941, rtol=5e-6) + assert_allclose(b, 1.027066, rtol=5e-6) + assert loc == 0 + assert scale == 1 + + +def test_cauchy_right_censored(): + """ + Test fitting the Cauchy distribution to right-censored data. + + Calculation in R, with two values not censored [1, 10] and + one right-censored value [30]. + + > library(fitdistrplus) + > data <- data.frame(left=c(1, 10, 30), right=c(1, 10, NA)) + > result = fitdistcens(data, 'cauchy', control=list(reltol=1e-14)) + > result + Fitting of the distribution ' cauchy ' on censored data by maximum + likelihood + Parameters: + estimate + location 7.100001 + scale 7.455866 + """ + data = CensoredData(uncensored=[1, 10], right=[30]) + loc, scale = cauchy.fit(data, optimizer=optimizer) + assert_allclose(loc, 7.10001, rtol=5e-6) + assert_allclose(scale, 7.455866, rtol=5e-6) + + +def test_cauchy_mixed(): + """ + Test fitting the Cauchy distribution to data with mixed censoring. + + Calculation in R, with: + * two values not censored [1, 10], + * one left-censored [1], + * one right-censored [30], and + * one interval-censored [[4, 8]]. + + > library(fitdistrplus) + > data <- data.frame(left=c(NA, 1, 4, 10, 30), right=c(1, 1, 8, 10, NA)) + > result = fitdistcens(data, 'cauchy', control=list(reltol=1e-14)) + > result + Fitting of the distribution ' cauchy ' on censored data by maximum + likelihood + Parameters: + estimate + location 4.605150 + scale 5.900852 + """ + data = CensoredData(uncensored=[1, 10], left=[1], right=[30], + interval=[[4, 8]]) + loc, scale = cauchy.fit(data, optimizer=optimizer) + assert_allclose(loc, 4.605150, rtol=5e-6) + assert_allclose(scale, 5.900852, rtol=5e-6) + + +def test_chi2_mixed(): + """ + Test fitting just the shape parameter (df) of chi2 to mixed data. + + Calculation in R, with: + * two values not censored [1, 10], + * one left-censored [1], + * one right-censored [30], and + * one interval-censored [[4, 8]]. + + > library(fitdistrplus) + > data <- data.frame(left=c(NA, 1, 4, 10, 30), right=c(1, 1, 8, 10, NA)) + > result = fitdistcens(data, 'chisq', control=list(reltol=1e-14)) + > result + Fitting of the distribution ' chisq ' on censored data by maximum + likelihood + Parameters: + estimate + df 5.060329 + """ + data = CensoredData(uncensored=[1, 10], left=[1], right=[30], + interval=[[4, 8]]) + df, loc, scale = chi2.fit(data, floc=0, fscale=1, optimizer=optimizer) + assert_allclose(df, 5.060329, rtol=5e-6) + assert loc == 0 + assert scale == 1 + + +def test_expon_right_censored(): + """ + For the exponential distribution with loc=0, the exact solution for + fitting n uncensored points x[0]...x[n-1] and m right-censored points + x[n]..x[n+m-1] is + + scale = sum(x)/n + + That is, divide the sum of all the values (not censored and + right-censored) by the number of uncensored values. (See, for example, + https://en.wikipedia.org/wiki/Censoring_(statistics)#Likelihood.) + + The second derivative of the log-likelihood function is + + n/scale**2 - 2*sum(x)/scale**3 + + from which the estimate of the standard error can be computed. + + ----- + + Calculation in R, for reference only. The R results are not + used in the test. + + > library(fitdistrplus) + > dexps <- function(x, scale) { + + return(dexp(x, 1/scale)) + + } + > pexps <- function(q, scale) { + + return(pexp(q, 1/scale)) + + } + > left <- c(1, 2.5, 3, 6, 7.5, 10, 12, 12, 14.5, 15, + + 16, 16, 20, 20, 21, 22) + > right <- c(1, 2.5, 3, 6, 7.5, 10, 12, 12, 14.5, 15, + + NA, NA, NA, NA, NA, NA) + > result = fitdistcens(data, 'exps', start=list(scale=mean(data$left)), + + control=list(reltol=1e-14)) + > result + Fitting of the distribution ' exps ' on censored data by maximum likelihood + Parameters: + estimate + scale 19.85 + > result$sd + scale + 6.277119 + """ + # This data has 10 uncensored values and 6 right-censored values. + obs = [1, 2.5, 3, 6, 7.5, 10, 12, 12, 14.5, 15, 16, 16, 20, 20, 21, 22] + cens = [False]*10 + [True]*6 + data = CensoredData.right_censored(obs, cens) + + loc, scale = expon.fit(data, floc=0, optimizer=optimizer) + + assert loc == 0 + # Use the analytical solution to compute the expected value. This + # is the sum of the observed values divided by the number of uncensored + # values. + n = len(data) - data.num_censored() + total = data._uncensored.sum() + data._right.sum() + expected = total / n + assert_allclose(scale, expected, 1e-8) + + +def test_gamma_right_censored(): + """ + Fit gamma shape and scale to data with one right-censored value. + + Calculation in R: + + > library(fitdistrplus) + > data <- data.frame(left=c(2.5, 2.9, 3.8, 9.1, 9.3, 12.0, 23.0, 25.0), + + right=c(2.5, 2.9, 3.8, 9.1, 9.3, 12.0, 23.0, NA)) + > result = fitdistcens(data, 'gamma', start=list(shape=1, scale=10), + + control=list(reltol=1e-13)) + > result + Fitting of the distribution ' gamma ' on censored data by maximum + likelihood + Parameters: + estimate + shape 1.447623 + scale 8.360197 + > result$sd + shape scale + 0.7053086 5.1016531 + """ + # The last value is right-censored. + x = CensoredData.right_censored([2.5, 2.9, 3.8, 9.1, 9.3, 12.0, 23.0, + 25.0], + [0]*7 + [1]) + + a, loc, scale = gamma.fit(x, floc=0, optimizer=optimizer) + + assert_allclose(a, 1.447623, rtol=5e-6) + assert loc == 0 + assert_allclose(scale, 8.360197, rtol=5e-6) + + +def test_gumbel(): + """ + Fit gumbel_l and gumbel_r to censored data. + + This R calculation should match gumbel_r. + + > library(evd) + > library(fitdistrplus) + > data = data.frame(left=c(0, 2, 3, 9, 10, 10), + + right=c(1, 2, 3, 9, NA, NA)) + > result = fitdistcens(data, 'gumbel', + + control=list(reltol=1e-14), + + start=list(loc=4, scale=5)) + > result + Fitting of the distribution ' gumbel ' on censored data by maximum + likelihood + Parameters: + estimate + loc 4.487853 + scale 4.843640 + """ + # First value is interval-censored. Last two are right-censored. + uncensored = np.array([2, 3, 9]) + right = np.array([10, 10]) + interval = np.array([[0, 1]]) + data = CensoredData(uncensored, right=right, interval=interval) + loc, scale = gumbel_r.fit(data, optimizer=optimizer) + assert_allclose(loc, 4.487853, rtol=5e-6) + assert_allclose(scale, 4.843640, rtol=5e-6) + + # Negate the data and reverse the intervals, and test with gumbel_l. + data2 = CensoredData(-uncensored, left=-right, + interval=-interval[:, ::-1]) + # Fitting gumbel_l to data2 should give the same result as above, but + # with loc negated. + loc2, scale2 = gumbel_l.fit(data2, optimizer=optimizer) + assert_allclose(loc2, -4.487853, rtol=5e-6) + assert_allclose(scale2, 4.843640, rtol=5e-6) + + +def test_invgauss(): + """ + Fit just the shape parameter of invgauss to data with one value + left-censored and one value right-censored. + + Calculation in R; using a fixed dispersion parameter amounts to fixing + the scale to be 1. + + > library(statmod) + > library(fitdistrplus) + > left <- c(NA, 0.4813096, 0.5571880, 0.5132463, 0.3801414, 0.5904386, + + 0.4822340, 0.3478597, 3, 0.7191797, 1.5810902, 0.4442299) + > right <- c(0.15, 0.4813096, 0.5571880, 0.5132463, 0.3801414, 0.5904386, + + 0.4822340, 0.3478597, NA, 0.7191797, 1.5810902, 0.4442299) + > data <- data.frame(left=left, right=right) + > result = fitdistcens(data, 'invgauss', control=list(reltol=1e-12), + + fix.arg=list(dispersion=1), start=list(mean=3)) + > result + Fitting of the distribution ' invgauss ' on censored data by maximum + likelihood + Parameters: + estimate + mean 0.853469 + Fixed parameters: + value + dispersion 1 + > result$sd + mean + 0.247636 + + Here's the R calculation with the dispersion as a free parameter to + be fit. + + > result = fitdistcens(data, 'invgauss', control=list(reltol=1e-12), + + start=list(mean=3, dispersion=1)) + > result + Fitting of the distribution ' invgauss ' on censored data by maximum + likelihood + Parameters: + estimate + mean 0.8699819 + dispersion 1.2261362 + + The parametrization of the inverse Gaussian distribution in the + `statmod` package is not the same as in SciPy (see + https://arxiv.org/abs/1603.06687 + for details). The translation from R to SciPy is + + scale = 1/dispersion + mu = mean * dispersion + + > 1/result$estimate['dispersion'] # 1/dispersion + dispersion + 0.8155701 + > result$estimate['mean'] * result$estimate['dispersion'] + mean + 1.066716 + + Those last two values are the SciPy scale and shape parameters. + """ + # One point is left-censored, and one is right-censored. + x = [0.4813096, 0.5571880, 0.5132463, 0.3801414, + 0.5904386, 0.4822340, 0.3478597, 0.7191797, + 1.5810902, 0.4442299] + data = CensoredData(uncensored=x, left=[0.15], right=[3]) + + # Fit only the shape parameter. + mu, loc, scale = invgauss.fit(data, floc=0, fscale=1, optimizer=optimizer) + + assert_allclose(mu, 0.853469, rtol=5e-5) + assert loc == 0 + assert scale == 1 + + # Fit the shape and scale. + mu, loc, scale = invgauss.fit(data, floc=0, optimizer=optimizer) + + assert_allclose(mu, 1.066716, rtol=5e-5) + assert loc == 0 + assert_allclose(scale, 0.8155701, rtol=5e-5) + + +def test_invweibull(): + """ + Fit invweibull to censored data. + + Here is the calculation in R. The 'frechet' distribution from the evd + package matches SciPy's invweibull distribution. The `loc` parameter + is fixed at 0. + + > library(evd) + > library(fitdistrplus) + > data = data.frame(left=c(0, 2, 3, 9, 10, 10), + + right=c(1, 2, 3, 9, NA, NA)) + > result = fitdistcens(data, 'frechet', + + control=list(reltol=1e-14), + + start=list(loc=4, scale=5)) + > result + Fitting of the distribution ' frechet ' on censored data by maximum + likelihood + Parameters: + estimate + scale 2.7902200 + shape 0.6379845 + Fixed parameters: + value + loc 0 + """ + # In the R data, the first value is interval-censored, and the last + # two are right-censored. The rest are not censored. + data = CensoredData(uncensored=[2, 3, 9], right=[10, 10], + interval=[[0, 1]]) + c, loc, scale = invweibull.fit(data, floc=0, optimizer=optimizer) + assert_allclose(c, 0.6379845, rtol=5e-6) + assert loc == 0 + assert_allclose(scale, 2.7902200, rtol=5e-6) + + +def test_laplace(): + """ + Fir the Laplace distribution to left- and right-censored data. + + Calculation in R: + + > library(fitdistrplus) + > dlaplace <- function(x, location=0, scale=1) { + + return(0.5*exp(-abs((x - location)/scale))/scale) + + } + > plaplace <- function(q, location=0, scale=1) { + + z <- (q - location)/scale + + s <- sign(z) + + f <- -s*0.5*exp(-abs(z)) + (s+1)/2 + + return(f) + + } + > left <- c(NA, -41.564, 50.0, 15.7384, 50.0, 10.0452, -2.0684, + + -19.5399, 50.0, 9.0005, 27.1227, 4.3113, -3.7372, + + 25.3111, 14.7987, 34.0887, 50.0, 42.8496, 18.5862, + + 32.8921, 9.0448, -27.4591, NA, 19.5083, -9.7199) + > right <- c(-50.0, -41.564, NA, 15.7384, NA, 10.0452, -2.0684, + + -19.5399, NA, 9.0005, 27.1227, 4.3113, -3.7372, + + 25.3111, 14.7987, 34.0887, NA, 42.8496, 18.5862, + + 32.8921, 9.0448, -27.4591, -50.0, 19.5083, -9.7199) + > data <- data.frame(left=left, right=right) + > result <- fitdistcens(data, 'laplace', start=list(location=10, scale=10), + + control=list(reltol=1e-13)) + > result + Fitting of the distribution ' laplace ' on censored data by maximum + likelihood + Parameters: + estimate + location 14.79870 + scale 30.93601 + > result$sd + location scale + 0.1758864 7.0972125 + """ + # The value -50 is left-censored, and the value 50 is right-censored. + obs = np.array([-50.0, -41.564, 50.0, 15.7384, 50.0, 10.0452, -2.0684, + -19.5399, 50.0, 9.0005, 27.1227, 4.3113, -3.7372, + 25.3111, 14.7987, 34.0887, 50.0, 42.8496, 18.5862, + 32.8921, 9.0448, -27.4591, -50.0, 19.5083, -9.7199]) + x = obs[(obs != -50.0) & (obs != 50)] + left = obs[obs == -50.0] + right = obs[obs == 50.0] + data = CensoredData(uncensored=x, left=left, right=right) + loc, scale = laplace.fit(data, loc=10, scale=10, optimizer=optimizer) + assert_allclose(loc, 14.79870, rtol=5e-6) + assert_allclose(scale, 30.93601, rtol=5e-6) + + +def test_logistic(): + """ + Fit the logistic distribution to left-censored data. + + Calculation in R: + > library(fitdistrplus) + > left = c(13.5401, 37.4235, 11.906 , 13.998 , NA , 0.4023, NA , + + 10.9044, 21.0629, 9.6985, NA , 12.9016, 39.164 , 34.6396, + + NA , 20.3665, 16.5889, 18.0952, 45.3818, 35.3306, 8.4949, + + 3.4041, NA , 7.2828, 37.1265, 6.5969, 17.6868, 17.4977, + + 16.3391, 36.0541) + > right = c(13.5401, 37.4235, 11.906 , 13.998 , 0. , 0.4023, 0. , + + 10.9044, 21.0629, 9.6985, 0. , 12.9016, 39.164 , 34.6396, + + 0. , 20.3665, 16.5889, 18.0952, 45.3818, 35.3306, 8.4949, + + 3.4041, 0. , 7.2828, 37.1265, 6.5969, 17.6868, 17.4977, + + 16.3391, 36.0541) + > data = data.frame(left=left, right=right) + > result = fitdistcens(data, 'logis', control=list(reltol=1e-14)) + > result + Fitting of the distribution ' logis ' on censored data by maximum + likelihood + Parameters: + estimate + location 14.633459 + scale 9.232736 + > result$sd + location scale + 2.931505 1.546879 + """ + # Values that are zero are left-censored; the true values are less than 0. + x = np.array([13.5401, 37.4235, 11.906, 13.998, 0.0, 0.4023, 0.0, 10.9044, + 21.0629, 9.6985, 0.0, 12.9016, 39.164, 34.6396, 0.0, 20.3665, + 16.5889, 18.0952, 45.3818, 35.3306, 8.4949, 3.4041, 0.0, + 7.2828, 37.1265, 6.5969, 17.6868, 17.4977, 16.3391, + 36.0541]) + data = CensoredData.left_censored(x, censored=(x == 0)) + loc, scale = logistic.fit(data, optimizer=optimizer) + assert_allclose(loc, 14.633459, rtol=5e-7) + assert_allclose(scale, 9.232736, rtol=5e-6) + + +def test_lognorm(): + """ + Ref: https://math.montana.edu/jobo/st528/documents/relc.pdf + + The data is the locomotive control time to failure example that starts + on page 8. That's the 8th page in the PDF; the page number shown in + the text is 270). + The document includes SAS output for the data. + """ + # These are the uncensored measurements. There are also 59 right-censored + # measurements where the lower bound is 135. + miles_to_fail = [22.5, 37.5, 46.0, 48.5, 51.5, 53.0, 54.5, 57.5, 66.5, + 68.0, 69.5, 76.5, 77.0, 78.5, 80.0, 81.5, 82.0, 83.0, + 84.0, 91.5, 93.5, 102.5, 107.0, 108.5, 112.5, 113.5, + 116.0, 117.0, 118.5, 119.0, 120.0, 122.5, 123.0, 127.5, + 131.0, 132.5, 134.0] + + data = CensoredData.right_censored(miles_to_fail + [135]*59, + [0]*len(miles_to_fail) + [1]*59) + sigma, loc, scale = lognorm.fit(data, floc=0) + + assert loc == 0 + # Convert the lognorm parameters to the mu and sigma of the underlying + # normal distribution. + mu = np.log(scale) + # The expected results are from the 17th page of the PDF document + # (labeled page 279), in the SAS output on the right side of the page. + assert_allclose(mu, 5.1169, rtol=5e-4) + assert_allclose(sigma, 0.7055, rtol=5e-3) + + +def test_nct(): + """ + Test fitting the noncentral t distribution to censored data. + + Calculation in R: + + > library(fitdistrplus) + > data <- data.frame(left=c(1, 2, 3, 5, 8, 10, 25, 25), + + right=c(1, 2, 3, 5, 8, 10, NA, NA)) + > result = fitdistcens(data, 't', control=list(reltol=1e-14), + + start=list(df=1, ncp=2)) + > result + Fitting of the distribution ' t ' on censored data by maximum likelihood + Parameters: + estimate + df 0.5432336 + ncp 2.8893565 + + """ + data = CensoredData.right_censored([1, 2, 3, 5, 8, 10, 25, 25], + [0, 0, 0, 0, 0, 0, 1, 1]) + # Fit just the shape parameter df and nc; loc and scale are fixed. + with np.errstate(over='ignore'): # remove context when gh-14901 is closed + df, nc, loc, scale = nct.fit(data, floc=0, fscale=1, + optimizer=optimizer) + assert_allclose(df, 0.5432336, rtol=5e-6) + assert_allclose(nc, 2.8893565, rtol=5e-6) + assert loc == 0 + assert scale == 1 + + +def test_ncx2(): + """ + Test fitting the shape parameters (df, ncp) of ncx2 to mixed data. + + Calculation in R, with + * 5 not censored values [2.7, 0.2, 6.5, 0.4, 0.1], + * 1 interval-censored value [[0.6, 1.0]], and + * 2 right-censored values [8, 8]. + + > library(fitdistrplus) + > data <- data.frame(left=c(2.7, 0.2, 6.5, 0.4, 0.1, 0.6, 8, 8), + + right=c(2.7, 0.2, 6.5, 0.4, 0.1, 1.0, NA, NA)) + > result = fitdistcens(data, 'chisq', control=list(reltol=1e-14), + + start=list(df=1, ncp=2)) + > result + Fitting of the distribution ' chisq ' on censored data by maximum + likelihood + Parameters: + estimate + df 1.052871 + ncp 2.362934 + """ + data = CensoredData(uncensored=[2.7, 0.2, 6.5, 0.4, 0.1], right=[8, 8], + interval=[[0.6, 1.0]]) + with np.errstate(over='ignore'): # remove context when gh-14901 is closed + df, ncp, loc, scale = ncx2.fit(data, floc=0, fscale=1, + optimizer=optimizer) + assert_allclose(df, 1.052871, rtol=5e-6) + assert_allclose(ncp, 2.362934, rtol=5e-6) + assert loc == 0 + assert scale == 1 + + +def test_norm(): + """ + Test fitting the normal distribution to interval-censored data. + + Calculation in R: + + > library(fitdistrplus) + > data <- data.frame(left=c(0.10, 0.50, 0.75, 0.80), + + right=c(0.20, 0.55, 0.90, 0.95)) + > result = fitdistcens(data, 'norm', control=list(reltol=1e-14)) + + > result + Fitting of the distribution ' norm ' on censored data by maximum likelihood + Parameters: + estimate + mean 0.5919990 + sd 0.2868042 + > result$sd + mean sd + 0.1444432 0.1029451 + """ + data = CensoredData(interval=[[0.10, 0.20], + [0.50, 0.55], + [0.75, 0.90], + [0.80, 0.95]]) + + loc, scale = norm.fit(data, optimizer=optimizer) + + assert_allclose(loc, 0.5919990, rtol=5e-6) + assert_allclose(scale, 0.2868042, rtol=5e-6) + + +def test_weibull_censored1(): + # Ref: http://www.ams.sunysb.edu/~zhu/ams588/Lecture_3_likelihood.pdf + + # Survival times; '*' indicates right-censored. + s = "3,5,6*,8,10*,11*,15,20*,22,23,27*,29,32,35,40,26,28,33*,21,24*" + + times, cens = zip(*[(float(t[0]), len(t) == 2) + for t in [w.split('*') for w in s.split(',')]]) + data = CensoredData.right_censored(times, cens) + + c, loc, scale = weibull_min.fit(data, floc=0) + + # Expected values are from the reference. + assert_allclose(c, 2.149, rtol=1e-3) + assert loc == 0 + assert_allclose(scale, 28.99, rtol=1e-3) + + # Flip the sign of the data, and make the censored values + # left-censored. We should get the same parameters when we fit + # weibull_max to the flipped data. + data2 = CensoredData.left_censored(-np.array(times), cens) + + c2, loc2, scale2 = weibull_max.fit(data2, floc=0) + + assert_allclose(c2, 2.149, rtol=1e-3) + assert loc2 == 0 + assert_allclose(scale2, 28.99, rtol=1e-3) + + +def test_weibull_min_sas1(): + # Data and SAS results from + # https://support.sas.com/documentation/cdl/en/qcug/63922/HTML/default/ + # viewer.htm#qcug_reliability_sect004.htm + + text = """ + 450 0 460 1 1150 0 1150 0 1560 1 + 1600 0 1660 1 1850 1 1850 1 1850 1 + 1850 1 1850 1 2030 1 2030 1 2030 1 + 2070 0 2070 0 2080 0 2200 1 3000 1 + 3000 1 3000 1 3000 1 3100 0 3200 1 + 3450 0 3750 1 3750 1 4150 1 4150 1 + 4150 1 4150 1 4300 1 4300 1 4300 1 + 4300 1 4600 0 4850 1 4850 1 4850 1 + 4850 1 5000 1 5000 1 5000 1 6100 1 + 6100 0 6100 1 6100 1 6300 1 6450 1 + 6450 1 6700 1 7450 1 7800 1 7800 1 + 8100 1 8100 1 8200 1 8500 1 8500 1 + 8500 1 8750 1 8750 0 8750 1 9400 1 + 9900 1 10100 1 10100 1 10100 1 11500 1 + """ + + life, cens = np.array([int(w) for w in text.split()]).reshape(-1, 2).T + life = life/1000.0 + + data = CensoredData.right_censored(life, cens) + + c, loc, scale = weibull_min.fit(data, floc=0, optimizer=optimizer) + assert_allclose(c, 1.0584, rtol=1e-4) + assert_allclose(scale, 26.2968, rtol=1e-5) + assert loc == 0 + + +def test_weibull_min_sas2(): + # http://support.sas.com/documentation/cdl/en/ormpug/67517/HTML/default/ + # viewer.htm#ormpug_nlpsolver_examples06.htm + + # The last two values are right-censored. + days = np.array([143, 164, 188, 188, 190, 192, 206, 209, 213, 216, 220, + 227, 230, 234, 246, 265, 304, 216, 244]) + + data = CensoredData.right_censored(days, [0]*(len(days) - 2) + [1]*2) + + c, loc, scale = weibull_min.fit(data, 1, loc=100, scale=100, + optimizer=optimizer) + + assert_allclose(c, 2.7112, rtol=5e-4) + assert_allclose(loc, 122.03, rtol=5e-4) + assert_allclose(scale, 108.37, rtol=5e-4) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_correlation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1af276de847c2a834c25fa0d3d352097112a13 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_correlation.py @@ -0,0 +1,80 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose + +from scipy import stats +from scipy.stats._axis_nan_policy import SmallSampleWarning + + +class TestChatterjeeXi: + @pytest.mark.parametrize('case', [ + dict(y_cont=True, statistic=-0.303030303030303, pvalue=0.9351329808526656), + dict(y_cont=False, statistic=0.07407407407407396, pvalue=0.3709859367123997)]) + def test_against_R_XICOR(self, case): + # Test against R package XICOR, e.g. + # library(XICOR) + # options(digits=16) + # x = c(0.11027287231363914, 0.8154770102474279, 0.7073943466920335, + # 0.6651317324378386, 0.6905752850115503, 0.06115250587536558, + # 0.5209906494474178, 0.3155763519785274, 0.18405731803625924, + # 0.8613557911541495) + # y = c(0.8402081904493103, 0.5946972833914318, 0.23481606164114155, + # 0.49754786197715384, 0.9146460831206026, 0.5848057749217579, + # 0.7620801065573549, 0.31410063302647495, 0.7935620302236199, + # 0.5423085761365468) + # xicor(x, y, ties=FALSE, pvalue=TRUE) + + rng = np.random.default_rng(25982435982346983) + x = rng.random(size=10) + + y = (rng.random(size=10) if case['y_cont'] + else rng.integers(0, 5, size=10)) + res = stats.chatterjeexi(x, y, y_continuous=case['y_cont']) + + assert_allclose(res.statistic, case['statistic']) + assert_allclose(res.pvalue, case['pvalue']) + + @pytest.mark.parametrize('y_continuous', (False, True)) + def test_permutation_asymptotic(self, y_continuous): + # XICOR doesn't seem to perform the permutation test as advertised, so + # compare the result of a permutation test against an asymptotic test. + rng = np.random.default_rng(2524579827426) + n = np.floor(rng.uniform(100, 150)).astype(int) + shape = (2, n) + x = rng.random(size=shape) + y = (rng.random(size=shape) if y_continuous + else rng.integers(0, 10, size=shape)) + method = stats.PermutationMethod(rng=rng) + res = stats.chatterjeexi(x, y, method=method, + y_continuous=y_continuous, axis=-1) + ref = stats.chatterjeexi(x, y, y_continuous=y_continuous, axis=-1) + np.testing.assert_allclose(res.statistic, ref.statistic, rtol=1e-15) + np.testing.assert_allclose(res.pvalue, ref.pvalue, rtol=2e-2) + + def test_input_validation(self): + rng = np.random.default_rng(25932435798274926) + x, y = rng.random(size=(2, 10)) + + message = 'Array shapes are incompatible for broadcasting.' + with pytest.raises(ValueError, match=message): + stats.chatterjeexi(x, y[:-1]) + + message = '...axis 10 is out of bounds for array...' + with pytest.raises(ValueError, match=message): + stats.chatterjeexi(x, y, axis=10) + + message = '`y_continuous` must be boolean.' + with pytest.raises(ValueError, match=message): + stats.chatterjeexi(x, y, y_continuous='a herring') + + message = "`method` must be 'asymptotic' or" + with pytest.raises(ValueError, match=message): + stats.chatterjeexi(x, y, method='ekki ekii') + + def test_special_cases(self): + message = 'One or more sample arguments is too small...' + with pytest.warns(SmallSampleWarning, match=message): + res = stats.chatterjeexi([1], [2]) + + assert np.isnan(res.statistic) + assert np.isnan(res.pvalue) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_crosstab.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_crosstab.py new file mode 100644 index 0000000000000000000000000000000000000000..239b3d3f6fa46e53ee90743a6eb6e10174a8c99c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_crosstab.py @@ -0,0 +1,115 @@ +import pytest +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +from scipy.stats.contingency import crosstab + + +@pytest.mark.parametrize('sparse', [False, True]) +def test_crosstab_basic(sparse): + a = [0, 0, 9, 9, 0, 0, 9] + b = [2, 1, 3, 1, 2, 3, 3] + expected_avals = [0, 9] + expected_bvals = [1, 2, 3] + expected_count = np.array([[1, 2, 1], + [1, 0, 2]]) + (avals, bvals), count = crosstab(a, b, sparse=sparse) + assert_array_equal(avals, expected_avals) + assert_array_equal(bvals, expected_bvals) + if sparse: + assert_array_equal(count.toarray(), expected_count) + else: + assert_array_equal(count, expected_count) + + +def test_crosstab_basic_1d(): + # Verify that a single input sequence works as expected. + x = [1, 2, 3, 1, 2, 3, 3] + expected_xvals = [1, 2, 3] + expected_count = np.array([2, 2, 3]) + (xvals,), count = crosstab(x) + assert_array_equal(xvals, expected_xvals) + assert_array_equal(count, expected_count) + + +def test_crosstab_basic_3d(): + # Verify the function for three input sequences. + a = 'a' + b = 'b' + x = [0, 0, 9, 9, 0, 0, 9, 9] + y = [a, a, a, a, b, b, b, a] + z = [1, 2, 3, 1, 2, 3, 3, 1] + expected_xvals = [0, 9] + expected_yvals = [a, b] + expected_zvals = [1, 2, 3] + expected_count = np.array([[[1, 1, 0], + [0, 1, 1]], + [[2, 0, 1], + [0, 0, 1]]]) + (xvals, yvals, zvals), count = crosstab(x, y, z) + assert_array_equal(xvals, expected_xvals) + assert_array_equal(yvals, expected_yvals) + assert_array_equal(zvals, expected_zvals) + assert_array_equal(count, expected_count) + + +@pytest.mark.parametrize('sparse', [False, True]) +def test_crosstab_levels(sparse): + a = [0, 0, 9, 9, 0, 0, 9] + b = [1, 2, 3, 1, 2, 3, 3] + expected_avals = [0, 9] + expected_bvals = [0, 1, 2, 3] + expected_count = np.array([[0, 1, 2, 1], + [0, 1, 0, 2]]) + (avals, bvals), count = crosstab(a, b, levels=[None, [0, 1, 2, 3]], + sparse=sparse) + assert_array_equal(avals, expected_avals) + assert_array_equal(bvals, expected_bvals) + if sparse: + assert_array_equal(count.toarray(), expected_count) + else: + assert_array_equal(count, expected_count) + + +@pytest.mark.parametrize('sparse', [False, True]) +def test_crosstab_extra_levels(sparse): + # The pair of values (-1, 3) will be ignored, because we explicitly + # request the counted `a` values to be [0, 9]. + a = [0, 0, 9, 9, 0, 0, 9, -1] + b = [1, 2, 3, 1, 2, 3, 3, 3] + expected_avals = [0, 9] + expected_bvals = [0, 1, 2, 3] + expected_count = np.array([[0, 1, 2, 1], + [0, 1, 0, 2]]) + (avals, bvals), count = crosstab(a, b, levels=[[0, 9], [0, 1, 2, 3]], + sparse=sparse) + assert_array_equal(avals, expected_avals) + assert_array_equal(bvals, expected_bvals) + if sparse: + assert_array_equal(count.toarray(), expected_count) + else: + assert_array_equal(count, expected_count) + + +def test_validation_at_least_one(): + with pytest.raises(TypeError, match='At least one'): + crosstab() + + +def test_validation_same_lengths(): + with pytest.raises(ValueError, match='must have the same length'): + crosstab([1, 2], [1, 2, 3, 4]) + + +def test_validation_sparse_only_two_args(): + with pytest.raises(ValueError, match='only two input sequences'): + crosstab([0, 1, 1], [8, 8, 9], [1, 3, 3], sparse=True) + + +def test_validation_len_levels_matches_args(): + with pytest.raises(ValueError, match='number of input sequences'): + crosstab([0, 1, 1], [8, 8, 9], levels=([0, 1, 2, 3],)) + + +def test_result(): + res = crosstab([0, 1], [1, 2]) + assert_equal((res.elements, res.count), res) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..8f468cf7397af0197f46d7813674feae533d63e3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_basic.py @@ -0,0 +1,574 @@ +import numpy.testing as npt +from numpy.testing import assert_allclose + +import numpy as np +import pytest + +from scipy import stats +from .common_tests import (check_normalization, check_moment, + check_mean_expect, + check_var_expect, check_skew_expect, + check_kurt_expect, check_entropy, + check_private_entropy, check_edge_support, + check_named_args, check_random_state_property, + check_pickling, check_rvs_broadcast, + check_freezing,) +from scipy.stats._distr_params import distdiscrete, invdistdiscrete +from scipy.stats._distn_infrastructure import rv_discrete_frozen + +vals = ([1, 2, 3, 4], [0.1, 0.2, 0.3, 0.4]) +distdiscrete += [[stats.rv_discrete(values=vals), ()]] + +# For these distributions, test_discrete_basic only runs with test mode full +distslow = {'zipfian', 'nhypergeom'} + +# Override number of ULPs adjustment for `check_cdf_ppf` +roundtrip_cdf_ppf_exceptions = {'nbinom': 30} + +def cases_test_discrete_basic(): + seen = set() + for distname, arg in distdiscrete: + if distname in distslow: + yield pytest.param(distname, arg, distname, marks=pytest.mark.slow) + else: + yield distname, arg, distname not in seen + seen.add(distname) + + +@pytest.mark.parametrize('distname,arg,first_case', cases_test_discrete_basic()) +def test_discrete_basic(distname, arg, first_case): + try: + distfn = getattr(stats, distname) + except TypeError: + distfn = distname + distname = 'sample distribution' + np.random.seed(9765456) + rvs = distfn.rvs(size=2000, *arg) + supp = np.unique(rvs) + m, v = distfn.stats(*arg) + check_cdf_ppf(distfn, arg, supp, distname + ' cdf_ppf') + + check_pmf_cdf(distfn, arg, distname) + check_oth(distfn, arg, supp, distname + ' oth') + check_edge_support(distfn, arg) + + alpha = 0.01 + check_discrete_chisquare(distfn, arg, rvs, alpha, + distname + ' chisquare') + + if first_case: + locscale_defaults = (0,) + meths = [distfn.pmf, distfn.logpmf, distfn.cdf, distfn.logcdf, + distfn.logsf] + # make sure arguments are within support + # for some distributions, this needs to be overridden + spec_k = {'randint': 11, 'hypergeom': 4, 'bernoulli': 0, + 'nchypergeom_wallenius': 6} + k = spec_k.get(distname, 1) + check_named_args(distfn, k, arg, locscale_defaults, meths) + if distname != 'sample distribution': + check_scale_docstring(distfn) + check_random_state_property(distfn, arg) + if distname not in {'poisson_binom'}: # can't be pickled + check_pickling(distfn, arg) + check_freezing(distfn, arg) + + # Entropy + check_entropy(distfn, arg, distname) + if distfn.__class__._entropy != stats.rv_discrete._entropy: + check_private_entropy(distfn, arg, stats.rv_discrete) + + +@pytest.mark.parametrize('distname,arg', distdiscrete) +def test_moments(distname, arg): + try: + distfn = getattr(stats, distname) + except TypeError: + distfn = distname + distname = 'sample distribution' + m, v, s, k = distfn.stats(*arg, moments='mvsk') + check_normalization(distfn, arg, distname) + + # compare `stats` and `moment` methods + check_moment(distfn, arg, m, v, distname) + check_mean_expect(distfn, arg, m, distname) + check_var_expect(distfn, arg, m, v, distname) + check_skew_expect(distfn, arg, m, v, s, distname) + with np.testing.suppress_warnings() as sup: + if distname in ['zipf', 'betanbinom']: + sup.filter(RuntimeWarning) + check_kurt_expect(distfn, arg, m, v, k, distname) + + # frozen distr moments + check_moment_frozen(distfn, arg, m, 1) + check_moment_frozen(distfn, arg, v+m*m, 2) + + +@pytest.mark.parametrize('dist,shape_args', distdiscrete) +def test_rvs_broadcast(dist, shape_args): + # If shape_only is True, it means the _rvs method of the + # distribution uses more than one random number to generate a random + # variate. That means the result of using rvs with broadcasting or + # with a nontrivial size will not necessarily be the same as using the + # numpy.vectorize'd version of rvs(), so we can only compare the shapes + # of the results, not the values. + # Whether or not a distribution is in the following list is an + # implementation detail of the distribution, not a requirement. If + # the implementation the rvs() method of a distribution changes, this + # test might also have to be changed. + shape_only = dist in ['betabinom', 'betanbinom', 'skellam', 'yulesimon', + 'dlaplace', 'nchypergeom_fisher', + 'nchypergeom_wallenius', 'poisson_binom'] + try: + distfunc = getattr(stats, dist) + except TypeError: + distfunc = dist + dist = f'rv_discrete(values=({dist.xk!r}, {dist.pk!r}))' + loc = np.zeros(2) + nargs = distfunc.numargs + allargs = [] + bshape = [] + + if dist == 'poisson_binom': + # normal rules apply except the last axis of `p` is ignored + p = np.full((3, 1, 10), 0.5) + allargs = (p, loc) + bshape = (3, 2) + check_rvs_broadcast(distfunc, dist, allargs, + bshape, shape_only, [np.dtype(int)]) + return + + # Generate shape parameter arguments... + for k in range(nargs): + shp = (k + 3,) + (1,)*(k + 1) + param_val = shape_args[k] + allargs.append(np.full(shp, param_val)) + bshape.insert(0, shp[0]) + allargs.append(loc) + bshape.append(loc.size) + # bshape holds the expected shape when loc, scale, and the shape + # parameters are all broadcast together. + check_rvs_broadcast( + distfunc, dist, allargs, bshape, shape_only, [np.dtype(int)] + ) + + +@pytest.mark.parametrize('dist,args', distdiscrete) +def test_ppf_with_loc(dist, args): + try: + distfn = getattr(stats, dist) + except TypeError: + distfn = dist + #check with a negative, no and positive relocation. + np.random.seed(1942349) + re_locs = [np.random.randint(-10, -1), 0, np.random.randint(1, 10)] + _a, _b = distfn.support(*args) + for loc in re_locs: + npt.assert_array_equal( + [_a-1+loc, _b+loc], + [distfn.ppf(0.0, *args, loc=loc), distfn.ppf(1.0, *args, loc=loc)] + ) + + +@pytest.mark.parametrize('dist, args', distdiscrete) +def test_isf_with_loc(dist, args): + try: + distfn = getattr(stats, dist) + except TypeError: + distfn = dist + # check with a negative, no and positive relocation. + np.random.seed(1942349) + re_locs = [np.random.randint(-10, -1), 0, np.random.randint(1, 10)] + _a, _b = distfn.support(*args) + for loc in re_locs: + expected = _b + loc, _a - 1 + loc + res = distfn.isf(0., *args, loc=loc), distfn.isf(1., *args, loc=loc) + npt.assert_array_equal(expected, res) + # test broadcasting behaviour + re_locs = [np.random.randint(-10, -1, size=(5, 3)), + np.zeros((5, 3)), + np.random.randint(1, 10, size=(5, 3))] + _a, _b = distfn.support(*args) + for loc in re_locs: + expected = _b + loc, _a - 1 + loc + res = distfn.isf(0., *args, loc=loc), distfn.isf(1., *args, loc=loc) + npt.assert_array_equal(expected, res) + + +def check_cdf_ppf(distfn, arg, supp, msg): + # supp is assumed to be an array of integers in the support of distfn + # (but not necessarily all the integers in the support). + # This test assumes that the PMF of any value in the support of the + # distribution is greater than 1e-8. + + # cdf is a step function, and ppf(q) = min{k : cdf(k) >= q, k integer} + cdf_supp = distfn.cdf(supp, *arg) + # In very rare cases, the finite precision calculation of ppf(cdf(supp)) + # can produce an array in which an element is off by one. We nudge the + # CDF values down by a few ULPs help to avoid this. + n_ulps = roundtrip_cdf_ppf_exceptions.get(distfn.name, 15) + cdf_supp0 = cdf_supp - n_ulps*np.spacing(cdf_supp) + npt.assert_array_equal(distfn.ppf(cdf_supp0, *arg), + supp, msg + '-roundtrip') + # Repeat the same calculation, but with the CDF values decreased by 1e-8. + npt.assert_array_equal(distfn.ppf(distfn.cdf(supp, *arg) - 1e-8, *arg), + supp, msg + '-roundtrip') + + if not hasattr(distfn, 'xk'): + _a, _b = distfn.support(*arg) + supp1 = supp[supp < _b] + npt.assert_array_equal(distfn.ppf(distfn.cdf(supp1, *arg) + 1e-8, *arg), + supp1 + distfn.inc, msg + ' ppf-cdf-next') + + +def check_pmf_cdf(distfn, arg, distname): + if hasattr(distfn, 'xk'): + index = distfn.xk + else: + startind = int(distfn.ppf(0.01, *arg) - 1) + index = list(range(startind, startind + 10)) + cdfs = distfn.cdf(index, *arg) + pmfs_cum = distfn.pmf(index, *arg).cumsum() + + atol, rtol = 1e-10, 1e-10 + if distname == 'skellam': # ncx2 accuracy + atol, rtol = 1e-5, 1e-5 + npt.assert_allclose(cdfs - cdfs[0], pmfs_cum - pmfs_cum[0], + atol=atol, rtol=rtol) + + # also check that pmf at non-integral k is zero + k = np.asarray(index) + k_shifted = k[:-1] + np.diff(k)/2 + npt.assert_equal(distfn.pmf(k_shifted, *arg), 0) + + # better check frozen distributions, and also when loc != 0 + loc = 0.5 + dist = distfn(loc=loc, *arg) + npt.assert_allclose(dist.pmf(k[1:] + loc), np.diff(dist.cdf(k + loc))) + npt.assert_equal(dist.pmf(k_shifted + loc), 0) + + +def check_moment_frozen(distfn, arg, m, k): + npt.assert_allclose(distfn(*arg).moment(k), m, + atol=1e-10, rtol=1e-10) + + +def check_oth(distfn, arg, supp, msg): + # checking other methods of distfn + npt.assert_allclose(distfn.sf(supp, *arg), 1. - distfn.cdf(supp, *arg), + atol=1e-10, rtol=1e-10) + + q = np.linspace(0.01, 0.99, 20) + npt.assert_allclose(distfn.isf(q, *arg), distfn.ppf(1. - q, *arg), + atol=1e-10, rtol=1e-10) + + median_sf = distfn.isf(0.5, *arg) + npt.assert_(distfn.sf(median_sf - 1, *arg) > 0.5) + npt.assert_(distfn.cdf(median_sf + 1, *arg) > 0.5) + + +def check_discrete_chisquare(distfn, arg, rvs, alpha, msg): + """Perform chisquare test for random sample of a discrete distribution + + Parameters + ---------- + distname : string + name of distribution function + arg : sequence + parameters of distribution + alpha : float + significance level, threshold for p-value + + Returns + ------- + result : bool + 0 if test passes, 1 if test fails + + """ + wsupp = 0.05 + + # construct intervals with minimum mass `wsupp`. + # intervals are left-half-open as in a cdf difference + _a, _b = distfn.support(*arg) + lo = int(max(_a, -1000)) + high = int(min(_b, 1000)) + 1 + distsupport = range(lo, high) + last = 0 + distsupp = [lo] + distmass = [] + for ii in distsupport: + current = distfn.cdf(ii, *arg) + if current - last >= wsupp - 1e-14: + distsupp.append(ii) + distmass.append(current - last) + last = current + if current > (1 - wsupp): + break + if distsupp[-1] < _b: + distsupp.append(_b) + distmass.append(1 - last) + distsupp = np.array(distsupp) + distmass = np.array(distmass) + + # convert intervals to right-half-open as required by histogram + histsupp = distsupp + 1e-8 + histsupp[0] = _a + + # find sample frequencies and perform chisquare test + freq, hsupp = np.histogram(rvs, histsupp) + chis, pval = stats.chisquare(np.array(freq), len(rvs)*distmass) + + npt.assert_( + pval > alpha, + f'chisquare - test for {msg} at arg = {str(arg)} with pval = {str(pval)}' + ) + + +def check_scale_docstring(distfn): + if distfn.__doc__ is not None: + # Docstrings can be stripped if interpreter is run with -OO + npt.assert_('scale' not in distfn.__doc__) + + +@pytest.mark.parametrize('method', ['pmf', 'logpmf', 'cdf', 'logcdf', + 'sf', 'logsf', 'ppf', 'isf']) +@pytest.mark.parametrize('distname, args', distdiscrete) +def test_methods_with_lists(method, distname, args): + # Test that the discrete distributions can accept Python lists + # as arguments. + try: + dist = getattr(stats, distname) + except TypeError: + return + dist_method = getattr(dist, method) + if method in ['ppf', 'isf']: + z = [0.1, 0.2] + else: + z = [0, 1] + p2 = [[p]*2 for p in args] + loc = [0, 1] + result = dist_method(z, *p2, loc=loc) + npt.assert_allclose(result, + [dist_method(*v) for v in zip(z, *p2, loc)], + rtol=1e-15, atol=1e-15) + + +@pytest.mark.parametrize('distname, args', invdistdiscrete) +def test_cdf_gh13280_regression(distname, args): + # Test for nan output when shape parameters are invalid + dist = getattr(stats, distname) + x = np.arange(-2, 15) + vals = dist.cdf(x, *args) + expected = np.nan + npt.assert_equal(vals, expected) + + +def cases_test_discrete_integer_shapes(): + # distributions parameters that are only allowed to be integral when + # fitting, but are allowed to be real as input to PDF, etc. + integrality_exceptions = {'nbinom': {'n'}, 'betanbinom': {'n'}} + + seen = set() + for distname, shapes in distdiscrete: + if distname in seen: + continue + seen.add(distname) + + try: + dist = getattr(stats, distname) + except TypeError: + continue + + shape_info = dist._shape_info() + + for i, shape in enumerate(shape_info): + if (shape.name in integrality_exceptions.get(distname, set()) or + not shape.integrality): + continue + + yield distname, shape.name, shapes + + +@pytest.mark.parametrize('distname, shapename, shapes', + cases_test_discrete_integer_shapes()) +def test_integer_shapes(distname, shapename, shapes): + dist = getattr(stats, distname) + shape_info = dist._shape_info() + shape_names = [shape.name for shape in shape_info] + i = shape_names.index(shapename) # this element of params must be integral + + shapes_copy = list(shapes) + + valid_shape = shapes[i] + invalid_shape = valid_shape - 0.5 # arbitrary non-integral value + new_valid_shape = valid_shape - 1 + shapes_copy[i] = [[valid_shape], [invalid_shape], [new_valid_shape]] + + a, b = dist.support(*shapes) + x = np.round(np.linspace(a, b, 5)) + + pmf = dist.pmf(x, *shapes_copy) + assert not np.any(np.isnan(pmf[0, :])) + assert np.all(np.isnan(pmf[1, :])) + assert not np.any(np.isnan(pmf[2, :])) + + +def test_frozen_attributes(): + # gh-14827 reported that all frozen distributions had both pmf and pdf + # attributes; continuous should have pdf and discrete should have pmf. + message = "'rv_discrete_frozen' object has no attribute" + with pytest.raises(AttributeError, match=message): + stats.binom(10, 0.5).pdf + with pytest.raises(AttributeError, match=message): + stats.binom(10, 0.5).logpdf + stats.binom.pdf = "herring" + frozen_binom = stats.binom(10, 0.5) + assert isinstance(frozen_binom, rv_discrete_frozen) + delattr(stats.binom, 'pdf') + + +@pytest.mark.parametrize('distname, shapes', distdiscrete) +def test_interval(distname, shapes): + # gh-11026 reported that `interval` returns incorrect values when + # `confidence=1`. The values were not incorrect, but it was not intuitive + # that the left end of the interval should extend beyond the support of the + # distribution. Confirm that this is the behavior for all distributions. + if isinstance(distname, str): + dist = getattr(stats, distname) + else: + dist = distname + a, b = dist.support(*shapes) + npt.assert_equal(dist.ppf([0, 1], *shapes), (a-1, b)) + npt.assert_equal(dist.isf([1, 0], *shapes), (a-1, b)) + npt.assert_equal(dist.interval(1, *shapes), (a-1, b)) + + +@pytest.mark.xfail_on_32bit("Sensible to machine precision") +def test_rv_sample(): + # Thoroughly test rv_sample and check that gh-3758 is resolved + + # Generate a random discrete distribution + rng = np.random.default_rng(98430143469) + xk = np.sort(rng.random(10) * 10) + pk = rng.random(10) + pk /= np.sum(pk) + dist = stats.rv_discrete(values=(xk, pk)) + + # Generate points to the left and right of xk + xk_left = (np.array([0] + xk[:-1].tolist()) + xk)/2 + xk_right = (np.array(xk[1:].tolist() + [xk[-1]+1]) + xk)/2 + + # Generate points to the left and right of cdf + cdf2 = np.cumsum(pk) + cdf2_left = (np.array([0] + cdf2[:-1].tolist()) + cdf2)/2 + cdf2_right = (np.array(cdf2[1:].tolist() + [1]) + cdf2)/2 + + # support - leftmost and rightmost xk + a, b = dist.support() + assert_allclose(a, xk[0]) + assert_allclose(b, xk[-1]) + + # pmf - supported only on the xk + assert_allclose(dist.pmf(xk), pk) + assert_allclose(dist.pmf(xk_right), 0) + assert_allclose(dist.pmf(xk_left), 0) + + # logpmf is log of the pmf; log(0) = -np.inf + with np.errstate(divide='ignore'): + assert_allclose(dist.logpmf(xk), np.log(pk)) + assert_allclose(dist.logpmf(xk_right), -np.inf) + assert_allclose(dist.logpmf(xk_left), -np.inf) + + # cdf - the cumulative sum of the pmf + assert_allclose(dist.cdf(xk), cdf2) + assert_allclose(dist.cdf(xk_right), cdf2) + assert_allclose(dist.cdf(xk_left), [0]+cdf2[:-1].tolist()) + + with np.errstate(divide='ignore'): + assert_allclose(dist.logcdf(xk), np.log(dist.cdf(xk)), + atol=1e-15) + assert_allclose(dist.logcdf(xk_right), np.log(dist.cdf(xk_right)), + atol=1e-15) + assert_allclose(dist.logcdf(xk_left), np.log(dist.cdf(xk_left)), + atol=1e-15) + + # sf is 1-cdf + assert_allclose(dist.sf(xk), 1-dist.cdf(xk)) + assert_allclose(dist.sf(xk_right), 1-dist.cdf(xk_right)) + assert_allclose(dist.sf(xk_left), 1-dist.cdf(xk_left)) + + with np.errstate(divide='ignore'): + assert_allclose(dist.logsf(xk), np.log(dist.sf(xk)), + atol=1e-15) + assert_allclose(dist.logsf(xk_right), np.log(dist.sf(xk_right)), + atol=1e-15) + assert_allclose(dist.logsf(xk_left), np.log(dist.sf(xk_left)), + atol=1e-15) + + # ppf + assert_allclose(dist.ppf(cdf2), xk) + assert_allclose(dist.ppf(cdf2_left), xk) + assert_allclose(dist.ppf(cdf2_right)[:-1], xk[1:]) + assert_allclose(dist.ppf(0), a - 1) + assert_allclose(dist.ppf(1), b) + + # isf + sf2 = dist.sf(xk) + assert_allclose(dist.isf(sf2), xk) + assert_allclose(dist.isf(1-cdf2_left), dist.ppf(cdf2_left)) + assert_allclose(dist.isf(1-cdf2_right), dist.ppf(cdf2_right)) + assert_allclose(dist.isf(0), b) + assert_allclose(dist.isf(1), a - 1) + + # interval is (ppf(alpha/2), isf(alpha/2)) + ps = np.linspace(0.01, 0.99, 10) + int2 = dist.ppf(ps/2), dist.isf(ps/2) + assert_allclose(dist.interval(1-ps), int2) + assert_allclose(dist.interval(0), dist.median()) + assert_allclose(dist.interval(1), (a-1, b)) + + # median is simply ppf(0.5) + med2 = dist.ppf(0.5) + assert_allclose(dist.median(), med2) + + # all four stats (mean, var, skew, and kurtosis) from the definitions + mean2 = np.sum(xk*pk) + var2 = np.sum((xk - mean2)**2 * pk) + skew2 = np.sum((xk - mean2)**3 * pk) / var2**(3/2) + kurt2 = np.sum((xk - mean2)**4 * pk) / var2**2 - 3 + assert_allclose(dist.mean(), mean2) + assert_allclose(dist.std(), np.sqrt(var2)) + assert_allclose(dist.var(), var2) + assert_allclose(dist.stats(moments='mvsk'), (mean2, var2, skew2, kurt2)) + + # noncentral moment against definition + mom3 = np.sum((xk**3) * pk) + assert_allclose(dist.moment(3), mom3) + + # expect - check against moments + assert_allclose(dist.expect(lambda x: 1), 1) + assert_allclose(dist.expect(), mean2) + assert_allclose(dist.expect(lambda x: x**3), mom3) + + # entropy is the negative of the expected value of log(p) + with np.errstate(divide='ignore'): + assert_allclose(-dist.expect(lambda x: dist.logpmf(x)), dist.entropy()) + + # RVS is just ppf of uniform random variates + rng = np.random.default_rng(98430143469) + rvs = dist.rvs(size=100, random_state=rng) + rng = np.random.default_rng(98430143469) + rvs0 = dist.ppf(rng.random(size=100)) + assert_allclose(rvs, rvs0) + +def test__pmf_float_input(): + # gh-21272 + # test that `rvs()` can be computed when `_pmf` requires float input + + class rv_exponential(stats.rv_discrete): + def _pmf(self, i): + return (2/3)*3**(1 - i) + + rv = rv_exponential(a=0.0, b=float('inf')) + rvs = rv.rvs(random_state=42) # should not crash due to integer input to `_pmf` + assert_allclose(rvs, 0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_distns.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_distns.py new file mode 100644 index 0000000000000000000000000000000000000000..c9b2a40a0acccb78bf2ab2f9a0dab707eb5fea71 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_distns.py @@ -0,0 +1,700 @@ +import pytest +import itertools + +from scipy import stats +from scipy.stats import (betabinom, betanbinom, hypergeom, nhypergeom, + bernoulli, boltzmann, skellam, zipf, zipfian, binom, + nbinom, nchypergeom_fisher, nchypergeom_wallenius, + randint, poisson_binom) + +import numpy as np +from numpy.testing import ( + assert_almost_equal, assert_equal, assert_allclose, suppress_warnings +) +from scipy.special import binom as special_binom +from scipy.optimize import root_scalar +from scipy.integrate import quad + + +# The expected values were computed with Wolfram Alpha, using +# the expression CDF[HypergeometricDistribution[N, n, M], k]. +@pytest.mark.parametrize('k, M, n, N, expected, rtol', + [(3, 10, 4, 5, + 0.9761904761904762, 1e-15), + (107, 10000, 3000, 215, + 0.9999999997226765, 1e-15), + (10, 10000, 3000, 215, + 2.681682217692179e-21, 5e-11)]) +def test_hypergeom_cdf(k, M, n, N, expected, rtol): + p = hypergeom.cdf(k, M, n, N) + assert_allclose(p, expected, rtol=rtol) + + +# The expected values were computed with Wolfram Alpha, using +# the expression SurvivalFunction[HypergeometricDistribution[N, n, M], k]. +@pytest.mark.parametrize('k, M, n, N, expected, rtol', + [(25, 10000, 3000, 215, + 0.9999999999052958, 1e-15), + (125, 10000, 3000, 215, + 1.4416781705752128e-18, 5e-11)]) +def test_hypergeom_sf(k, M, n, N, expected, rtol): + p = hypergeom.sf(k, M, n, N) + assert_allclose(p, expected, rtol=rtol) + + +def test_hypergeom_logpmf(): + # symmetries test + # f(k,N,K,n) = f(n-k,N,N-K,n) = f(K-k,N,K,N-n) = f(k,N,n,K) + k = 5 + N = 50 + K = 10 + n = 5 + logpmf1 = hypergeom.logpmf(k, N, K, n) + logpmf2 = hypergeom.logpmf(n - k, N, N - K, n) + logpmf3 = hypergeom.logpmf(K - k, N, K, N - n) + logpmf4 = hypergeom.logpmf(k, N, n, K) + assert_almost_equal(logpmf1, logpmf2, decimal=12) + assert_almost_equal(logpmf1, logpmf3, decimal=12) + assert_almost_equal(logpmf1, logpmf4, decimal=12) + + # test related distribution + # Bernoulli distribution if n = 1 + k = 1 + N = 10 + K = 7 + n = 1 + hypergeom_logpmf = hypergeom.logpmf(k, N, K, n) + bernoulli_logpmf = bernoulli.logpmf(k, K/N) + assert_almost_equal(hypergeom_logpmf, bernoulli_logpmf, decimal=12) + + +def test_nhypergeom_pmf(): + # test with hypergeom + M, n, r = 45, 13, 8 + k = 6 + NHG = nhypergeom.pmf(k, M, n, r) + HG = hypergeom.pmf(k, M, n, k+r-1) * (M - n - (r-1)) / (M - (k+r-1)) + assert_allclose(HG, NHG, rtol=1e-10) + + +def test_nhypergeom_pmfcdf(): + # test pmf and cdf with arbitrary values. + M = 8 + n = 3 + r = 4 + support = np.arange(n+1) + pmf = nhypergeom.pmf(support, M, n, r) + cdf = nhypergeom.cdf(support, M, n, r) + assert_allclose(pmf, [1/14, 3/14, 5/14, 5/14], rtol=1e-13) + assert_allclose(cdf, [1/14, 4/14, 9/14, 1.0], rtol=1e-13) + + +def test_nhypergeom_r0(): + # test with `r = 0`. + M = 10 + n = 3 + r = 0 + pmf = nhypergeom.pmf([[0, 1, 2, 0], [1, 2, 0, 3]], M, n, r) + assert_allclose(pmf, [[1, 0, 0, 1], [0, 0, 1, 0]], rtol=1e-13) + + +def test_nhypergeom_rvs_shape(): + # Check that when given a size with more dimensions than the + # dimensions of the broadcast parameters, rvs returns an array + # with the correct shape. + x = nhypergeom.rvs(22, [7, 8, 9], [[12], [13]], size=(5, 1, 2, 3)) + assert x.shape == (5, 1, 2, 3) + + +def test_nhypergeom_accuracy(): + # Check that nhypergeom.rvs post-gh-13431 gives the same values as + # inverse transform sampling + np.random.seed(0) + x = nhypergeom.rvs(22, 7, 11, size=100) + np.random.seed(0) + p = np.random.uniform(size=100) + y = nhypergeom.ppf(p, 22, 7, 11) + assert_equal(x, y) + + +def test_boltzmann_upper_bound(): + k = np.arange(-3, 5) + + N = 1 + p = boltzmann.pmf(k, 0.123, N) + expected = k == 0 + assert_equal(p, expected) + + lam = np.log(2) + N = 3 + p = boltzmann.pmf(k, lam, N) + expected = [0, 0, 0, 4/7, 2/7, 1/7, 0, 0] + assert_allclose(p, expected, rtol=1e-13) + + c = boltzmann.cdf(k, lam, N) + expected = [0, 0, 0, 4/7, 6/7, 1, 1, 1] + assert_allclose(c, expected, rtol=1e-13) + + +def test_betabinom_a_and_b_unity(): + # test limiting case that betabinom(n, 1, 1) is a discrete uniform + # distribution from 0 to n + n = 20 + k = np.arange(n + 1) + p = betabinom(n, 1, 1).pmf(k) + expected = np.repeat(1 / (n + 1), n + 1) + assert_almost_equal(p, expected) + + +@pytest.mark.parametrize('dtypes', itertools.product(*[(int, float)]*3)) +def test_betabinom_stats_a_and_b_integers_gh18026(dtypes): + # gh-18026 reported that `betabinom` kurtosis calculation fails when some + # parameters are integers. Check that this is resolved. + n_type, a_type, b_type = dtypes + n, a, b = n_type(10), a_type(2), b_type(3) + assert_allclose(betabinom.stats(n, a, b, moments='k'), -0.6904761904761907) + + +def test_betabinom_bernoulli(): + # test limiting case that betabinom(1, a, b) = bernoulli(a / (a + b)) + a = 2.3 + b = 0.63 + k = np.arange(2) + p = betabinom(1, a, b).pmf(k) + expected = bernoulli(a / (a + b)).pmf(k) + assert_almost_equal(p, expected) + + +def test_issue_10317(): + alpha, n, p = 0.9, 10, 1 + assert_equal(nbinom.interval(confidence=alpha, n=n, p=p), (0, 0)) + + +def test_issue_11134(): + alpha, n, p = 0.95, 10, 0 + assert_equal(binom.interval(confidence=alpha, n=n, p=p), (0, 0)) + + +def test_issue_7406(): + np.random.seed(0) + assert_equal(binom.ppf(np.random.rand(10), 0, 0.5), 0) + + # Also check that endpoints (q=0, q=1) are correct + assert_equal(binom.ppf(0, 0, 0.5), -1) + assert_equal(binom.ppf(1, 0, 0.5), 0) + + +def test_issue_5122(): + p = 0 + n = np.random.randint(100, size=10) + + x = 0 + ppf = binom.ppf(x, n, p) + assert_equal(ppf, -1) + + x = np.linspace(0.01, 0.99, 10) + ppf = binom.ppf(x, n, p) + assert_equal(ppf, 0) + + x = 1 + ppf = binom.ppf(x, n, p) + assert_equal(ppf, n) + + +def test_issue_1603(): + assert_equal(binom(1000, np.logspace(-3, -100)).ppf(0.01), 0) + + +def test_issue_5503(): + p = 0.5 + x = np.logspace(3, 14, 12) + assert_allclose(binom.cdf(x, 2*x, p), 0.5, atol=1e-2) + + +@pytest.mark.parametrize('x, n, p, cdf_desired', [ + (300, 1000, 3/10, 0.51559351981411995636), + (3000, 10000, 3/10, 0.50493298381929698016), + (30000, 100000, 3/10, 0.50156000591726422864), + (300000, 1000000, 3/10, 0.50049331906666960038), + (3000000, 10000000, 3/10, 0.50015600124585261196), + (30000000, 100000000, 3/10, 0.50004933192735230102), + (30010000, 100000000, 3/10, 0.98545384016570790717), + (29990000, 100000000, 3/10, 0.01455017177985268670), + (29950000, 100000000, 3/10, 5.02250963487432024943e-28), +]) +def test_issue_5503pt2(x, n, p, cdf_desired): + assert_allclose(binom.cdf(x, n, p), cdf_desired) + + +def test_issue_5503pt3(): + # From Wolfram Alpha: CDF[BinomialDistribution[1e12, 1e-12], 2] + assert_allclose(binom.cdf(2, 10**12, 10**-12), 0.91969860292869777384) + + +def test_issue_6682(): + # Reference value from R: + # options(digits=16) + # print(pnbinom(250, 50, 32/63, lower.tail=FALSE)) + assert_allclose(nbinom.sf(250, 50, 32./63.), 1.460458510976452e-35) + + +def test_issue_19747(): + # test that negative k does not raise an error in nbinom.logcdf + result = nbinom.logcdf([5, -1, 1], 5, 0.5) + reference = [-0.47313352, -np.inf, -2.21297293] + assert_allclose(result, reference) + + +def test_boost_divide_by_zero_issue_15101(): + n = 1000 + p = 0.01 + k = 996 + assert_allclose(binom.pmf(k, n, p), 0.0) + + +def test_skellam_gh11474(): + # test issue reported in gh-11474 caused by `cdfchn` + mu = [1, 10, 100, 1000, 5000, 5050, 5100, 5250, 6000] + cdf = skellam.cdf(0, mu, mu) + # generated in R + # library(skellam) + # options(digits = 16) + # mu = c(1, 10, 100, 1000, 5000, 5050, 5100, 5250, 6000) + # pskellam(0, mu, mu, TRUE) + cdf_expected = [0.6542541612768356, 0.5448901559424127, 0.5141135799745580, + 0.5044605891382528, 0.5019947363350450, 0.5019848365953181, + 0.5019750827993392, 0.5019466621805060, 0.5018209330219539] + assert_allclose(cdf, cdf_expected) + + +class TestZipfian: + def test_zipfian_asymptotic(self): + # test limiting case that zipfian(a, n) -> zipf(a) as n-> oo + a = 6.5 + N = 10000000 + k = np.arange(1, 21) + assert_allclose(zipfian.pmf(k, a, N), zipf.pmf(k, a)) + assert_allclose(zipfian.cdf(k, a, N), zipf.cdf(k, a)) + assert_allclose(zipfian.sf(k, a, N), zipf.sf(k, a)) + assert_allclose(zipfian.stats(a, N, moments='msvk'), + zipf.stats(a, moments='msvk')) + + def test_zipfian_continuity(self): + # test that zipfian(0.999999, n) ~ zipfian(1.000001, n) + # (a = 1 switches between methods of calculating harmonic sum) + alt1, agt1 = 0.99999999, 1.00000001 + N = 30 + k = np.arange(1, N + 1) + assert_allclose(zipfian.pmf(k, alt1, N), zipfian.pmf(k, agt1, N), + rtol=5e-7) + assert_allclose(zipfian.cdf(k, alt1, N), zipfian.cdf(k, agt1, N), + rtol=5e-7) + assert_allclose(zipfian.sf(k, alt1, N), zipfian.sf(k, agt1, N), + rtol=5e-7) + assert_allclose(zipfian.stats(alt1, N, moments='msvk'), + zipfian.stats(agt1, N, moments='msvk'), rtol=5e-7) + + def test_zipfian_R(self): + # test against R VGAM package + # library(VGAM) + # k <- c(13, 16, 1, 4, 4, 8, 10, 19, 5, 7) + # a <- c(1.56712977, 3.72656295, 5.77665117, 9.12168729, 5.79977172, + # 4.92784796, 9.36078764, 4.3739616 , 7.48171872, 4.6824154) + # n <- c(70, 80, 48, 65, 83, 89, 50, 30, 20, 20) + # pmf <- dzipf(k, N = n, shape = a) + # cdf <- pzipf(k, N = n, shape = a) + # print(pmf) + # print(cdf) + np.random.seed(0) + k = np.random.randint(1, 20, size=10) + a = np.random.rand(10)*10 + 1 + n = np.random.randint(1, 100, size=10) + pmf = [8.076972e-03, 2.950214e-05, 9.799333e-01, 3.216601e-06, + 3.158895e-04, 3.412497e-05, 4.350472e-10, 2.405773e-06, + 5.860662e-06, 1.053948e-04] + cdf = [0.8964133, 0.9998666, 0.9799333, 0.9999995, 0.9998584, + 0.9999458, 1.0000000, 0.9999920, 0.9999977, 0.9998498] + # skip the first point; zipUC is not accurate for low a, n + assert_allclose(zipfian.pmf(k, a, n)[1:], pmf[1:], rtol=1e-6) + assert_allclose(zipfian.cdf(k, a, n)[1:], cdf[1:], rtol=5e-5) + + np.random.seed(0) + naive_tests = np.vstack((np.logspace(-2, 1, 10), + np.random.randint(2, 40, 10))).T + + @pytest.mark.parametrize("a, n", naive_tests) + def test_zipfian_naive(self, a, n): + # test against bare-bones implementation + + @np.vectorize + def Hns(n, s): + """Naive implementation of harmonic sum""" + return (1/np.arange(1, n+1)**s).sum() + + @np.vectorize + def pzip(k, a, n): + """Naive implementation of zipfian pmf""" + if k < 1 or k > n: + return 0. + else: + return 1 / k**a / Hns(n, a) + + k = np.arange(n+1) + pmf = pzip(k, a, n) + cdf = np.cumsum(pmf) + mean = np.average(k, weights=pmf) + var = np.average((k - mean)**2, weights=pmf) + std = var**0.5 + skew = np.average(((k-mean)/std)**3, weights=pmf) + kurtosis = np.average(((k-mean)/std)**4, weights=pmf) - 3 + assert_allclose(zipfian.pmf(k, a, n), pmf) + assert_allclose(zipfian.cdf(k, a, n), cdf) + assert_allclose(zipfian.stats(a, n, moments="mvsk"), + [mean, var, skew, kurtosis]) + + def test_pmf_integer_k(self): + k = np.arange(0, 1000) + k_int32 = k.astype(np.int32) + dist = zipfian(111, 22) + pmf = dist.pmf(k) + pmf_k_int32 = dist.pmf(k_int32) + assert_equal(pmf, pmf_k_int32) + + +class TestNCH: + np.random.seed(2) # seeds 0 and 1 had some xl = xu; randint failed + shape = (2, 4, 3) + max_m = 100 + m1 = np.random.randint(1, max_m, size=shape) # red balls + m2 = np.random.randint(1, max_m, size=shape) # white balls + N = m1 + m2 # total balls + n = randint.rvs(0, N, size=N.shape) # number of draws + xl = np.maximum(0, n-m2) # lower bound of support + xu = np.minimum(n, m1) # upper bound of support + x = randint.rvs(xl, xu, size=xl.shape) + odds = np.random.rand(*x.shape)*2 + + # test output is more readable when function names (strings) are passed + @pytest.mark.parametrize('dist_name', + ['nchypergeom_fisher', 'nchypergeom_wallenius']) + def test_nch_hypergeom(self, dist_name): + # Both noncentral hypergeometric distributions reduce to the + # hypergeometric distribution when odds = 1 + dists = {'nchypergeom_fisher': nchypergeom_fisher, + 'nchypergeom_wallenius': nchypergeom_wallenius} + dist = dists[dist_name] + x, N, m1, n = self.x, self.N, self.m1, self.n + assert_allclose(dist.pmf(x, N, m1, n, odds=1), + hypergeom.pmf(x, N, m1, n)) + + def test_nchypergeom_fisher_naive(self): + # test against a very simple implementation + x, N, m1, n, odds = self.x, self.N, self.m1, self.n, self.odds + + @np.vectorize + def pmf_mean_var(x, N, m1, n, w): + # simple implementation of nchypergeom_fisher pmf + m2 = N - m1 + xl = np.maximum(0, n-m2) + xu = np.minimum(n, m1) + + def f(x): + t1 = special_binom(m1, x) + t2 = special_binom(m2, n - x) + return t1 * t2 * w**x + + def P(k): + return sum(f(y)*y**k for y in range(xl, xu + 1)) + + P0 = P(0) + P1 = P(1) + P2 = P(2) + pmf = f(x) / P0 + mean = P1 / P0 + var = P2 / P0 - (P1 / P0)**2 + return pmf, mean, var + + pmf, mean, var = pmf_mean_var(x, N, m1, n, odds) + assert_allclose(nchypergeom_fisher.pmf(x, N, m1, n, odds), pmf) + assert_allclose(nchypergeom_fisher.stats(N, m1, n, odds, moments='m'), + mean) + assert_allclose(nchypergeom_fisher.stats(N, m1, n, odds, moments='v'), + var) + + def test_nchypergeom_wallenius_naive(self): + # test against a very simple implementation + + np.random.seed(2) + shape = (2, 4, 3) + max_m = 100 + m1 = np.random.randint(1, max_m, size=shape) + m2 = np.random.randint(1, max_m, size=shape) + N = m1 + m2 + n = randint.rvs(0, N, size=N.shape) + xl = np.maximum(0, n-m2) + xu = np.minimum(n, m1) + x = randint.rvs(xl, xu, size=xl.shape) + w = np.random.rand(*x.shape)*2 + + def support(N, m1, n, w): + m2 = N - m1 + xl = np.maximum(0, n-m2) + xu = np.minimum(n, m1) + return xl, xu + + @np.vectorize + def mean(N, m1, n, w): + m2 = N - m1 + xl, xu = support(N, m1, n, w) + + def fun(u): + return u/m1 + (1 - (n-u)/m2)**w - 1 + + return root_scalar(fun, bracket=(xl, xu)).root + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, + message="invalid value encountered in mean") + assert_allclose(nchypergeom_wallenius.mean(N, m1, n, w), + mean(N, m1, n, w), rtol=2e-2) + + @np.vectorize + def variance(N, m1, n, w): + m2 = N - m1 + u = mean(N, m1, n, w) + a = u * (m1 - u) + b = (n-u)*(u + m2 - n) + return N*a*b / ((N-1) * (m1*b + m2*a)) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, + message="invalid value encountered in mean") + assert_allclose( + nchypergeom_wallenius.stats(N, m1, n, w, moments='v'), + variance(N, m1, n, w), + rtol=5e-2 + ) + + @np.vectorize + def pmf(x, N, m1, n, w): + m2 = N - m1 + xl, xu = support(N, m1, n, w) + + def integrand(t): + D = w*(m1 - x) + (m2 - (n-x)) + res = (1-t**(w/D))**x * (1-t**(1/D))**(n-x) + return res + + def f(x): + t1 = special_binom(m1, x) + t2 = special_binom(m2, n - x) + the_integral = quad(integrand, 0, 1, + epsrel=1e-16, epsabs=1e-16) + return t1 * t2 * the_integral[0] + + return f(x) + + pmf0 = pmf(x, N, m1, n, w) + pmf1 = nchypergeom_wallenius.pmf(x, N, m1, n, w) + + atol, rtol = 1e-6, 1e-6 + i = np.abs(pmf1 - pmf0) < atol + rtol*np.abs(pmf0) + assert i.sum() > np.prod(shape) / 2 # works at least half the time + + # for those that fail, discredit the naive implementation + for N, m1, n, w in zip(N[~i], m1[~i], n[~i], w[~i]): + # get the support + m2 = N - m1 + xl, xu = support(N, m1, n, w) + x = np.arange(xl, xu + 1) + + # calculate sum of pmf over the support + # the naive implementation is very wrong in these cases + assert pmf(x, N, m1, n, w).sum() < .5 + assert_allclose(nchypergeom_wallenius.pmf(x, N, m1, n, w).sum(), 1) + + def test_wallenius_against_mpmath(self): + # precompute data with mpmath since naive implementation above + # is not reliable. See source code in gh-13330. + M = 50 + n = 30 + N = 20 + odds = 2.25 + # Expected results, computed with mpmath. + sup = np.arange(21) + pmf = np.array([3.699003068656875e-20, + 5.89398584245431e-17, + 2.1594437742911123e-14, + 3.221458044649955e-12, + 2.4658279241205077e-10, + 1.0965862603981212e-08, + 3.057890479665704e-07, + 5.622818831643761e-06, + 7.056482841531681e-05, + 0.000618899425358671, + 0.003854172932571669, + 0.01720592676256026, + 0.05528844897093792, + 0.12772363313574242, + 0.21065898367825722, + 0.24465958845359234, + 0.1955114898110033, + 0.10355390084949237, + 0.03414490375225675, + 0.006231989845775931, + 0.0004715577304677075]) + mean = 14.808018384813426 + var = 2.6085975877923717 + + # nchypergeom_wallenius.pmf returns 0 for pmf(0) and pmf(1), and pmf(2) + # has only three digits of accuracy (~ 2.1511e-14). + assert_allclose(nchypergeom_wallenius.pmf(sup, M, n, N, odds), pmf, + rtol=1e-13, atol=1e-13) + assert_allclose(nchypergeom_wallenius.mean(M, n, N, odds), + mean, rtol=1e-13) + assert_allclose(nchypergeom_wallenius.var(M, n, N, odds), + var, rtol=1e-11) + + @pytest.mark.parametrize('dist_name', + ['nchypergeom_fisher', 'nchypergeom_wallenius']) + def test_rvs_shape(self, dist_name): + # Check that when given a size with more dimensions than the + # dimensions of the broadcast parameters, rvs returns an array + # with the correct shape. + dists = {'nchypergeom_fisher': nchypergeom_fisher, + 'nchypergeom_wallenius': nchypergeom_wallenius} + dist = dists[dist_name] + x = dist.rvs(50, 30, [[10], [20]], [0.5, 1.0, 2.0], size=(5, 1, 2, 3)) + assert x.shape == (5, 1, 2, 3) + + +@pytest.mark.parametrize("mu, q, expected", + [[10, 120, -1.240089881791596e-38], + [1500, 0, -86.61466680572661]]) +def test_nbinom_11465(mu, q, expected): + # test nbinom.logcdf at extreme tails + size = 20 + n, p = size, size/(size+mu) + # In R: + # options(digits=16) + # pnbinom(mu=10, size=20, q=120, log.p=TRUE) + assert_allclose(nbinom.logcdf(q, n, p), expected) + + +def test_gh_17146(): + # Check that discrete distributions return PMF of zero at non-integral x. + # See gh-17146. + x = np.linspace(0, 1, 11) + p = 0.8 + pmf = bernoulli(p).pmf(x) + i = (x % 1 == 0) + assert_allclose(pmf[-1], p) + assert_allclose(pmf[0], 1-p) + assert_equal(pmf[~i], 0) + + +class TestBetaNBinom: + @pytest.mark.parametrize('x, n, a, b, ref', + [[5, 5e6, 5, 20, 1.1520944824139114e-107], + [100, 50, 5, 20, 0.002855762954310226], + [10000, 1000, 5, 20, 1.9648515726019154e-05]]) + def test_betanbinom_pmf(self, x, n, a, b, ref): + # test that PMF stays accurate in the distribution tails + # reference values computed with mpmath + # from mpmath import mp + # mp.dps = 500 + # def betanbinom_pmf(k, n, a, b): + # k = mp.mpf(k) + # a = mp.mpf(a) + # b = mp.mpf(b) + # n = mp.mpf(n) + # return float(mp.binomial(n + k - mp.one, k) + # * mp.beta(a + n, b + k) / mp.beta(a, b)) + assert_allclose(betanbinom.pmf(x, n, a, b), ref, rtol=1e-10) + + + @pytest.mark.parametrize('n, a, b, ref', + [[10000, 5000, 50, 0.12841520515722202], + [10, 9, 9, 7.9224400871459695], + [100, 1000, 10, 1.5849602176622748]]) + def test_betanbinom_kurtosis(self, n, a, b, ref): + # reference values were computed via mpmath + # from mpmath import mp + # def kurtosis_betanegbinom(n, a, b): + # n = mp.mpf(n) + # a = mp.mpf(a) + # b = mp.mpf(b) + # four = mp.mpf(4.) + # mean = n * b / (a - mp.one) + # var = (n * b * (n + a - 1.) * (a + b - 1.) + # / ((a - 2.) * (a - 1.)**2.)) + # def f(k): + # return (mp.binomial(n + k - mp.one, k) + # * mp.beta(a + n, b + k) / mp.beta(a, b) + # * (k - mean)**four) + # fourth_moment = mp.nsum(f, [0, mp.inf]) + # return float(fourth_moment/var**2 - 3.) + assert_allclose(betanbinom.stats(n, a, b, moments="k"), + ref, rtol=3e-15) + + +class TestZipf: + def test_gh20692(self): + # test that int32 data for k generates same output as double + k = np.arange(0, 1000) + k_int32 = k.astype(np.int32) + dist = zipf(9) + pmf = dist.pmf(k) + pmf_k_int32 = dist.pmf(k_int32) + assert_equal(pmf, pmf_k_int32) + + +def test_gh20048(): + # gh-20048 reported an infinite loop in _drv2_ppfsingle + # check that the one identified is resolved + class test_dist_gen(stats.rv_discrete): + def _cdf(self, k): + return min(k / 100, 0.99) + + test_dist = test_dist_gen(b=np.inf) + + message = "Arguments that bracket..." + with pytest.raises(RuntimeError, match=message): + test_dist.ppf(0.999) + + +class TestPoissonBinomial: + def test_pmf(self): + # Test pmf against R `poisbinom` to confirm that this is indeed the Poisson + # binomial distribution. Consistency of other methods and all other behavior + # should be covered by generic tests. (If not, please add a generic test.) + # Like many other distributions, no special attempt is made to be more + # accurate than the usual formulas provide, so we use default tolerances. + # + # library(poisbinom) + # options(digits=16) + # k = c(0, 1, 2, 3, 4) + # p = c(0.9480654803913988, 0.052428488100509374, + # 0.25863527358887417, 0.057764076043633206) + # dpoisbinom(k, p) + rng = np.random.default_rng(259823598254) + n = rng.integers(10) # 4 + k = np.arange(n + 1) + p = rng.random(n) # [0.9480654803913988, 0.052428488100509374, + # 0.25863527358887417, 0.057764076043633206] + res = poisson_binom.pmf(k, p) + ref = [0.0343763443678060318, 0.6435428452689714307, 0.2936345519235536994, + 0.0277036647503902354, 0.0007425936892786034] + assert_allclose(res, ref) + + +class TestRandInt: + def test_gh19759(self): + # test zero PMF values within the support reported by gh-19759 + a = -354 + max_range = abs(a) + all_b_1 = [a + 2 ** 31 + i for i in range(max_range)] + res = randint.pmf(325, a, all_b_1) + assert (res > 0).all() + ref = 1 / (np.asarray(all_b_1, dtype=np.float64) - a) + assert_allclose(res, ref) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_distributions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..d874eb57e1f56fb61a31e12c2204832ff7209c3e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_distributions.py @@ -0,0 +1,10380 @@ +""" +Test functions for stats module +""" +import warnings +import re +import sys +import pickle +from pathlib import Path +import os +import json +import platform + +from numpy.testing import (assert_equal, assert_array_equal, + assert_almost_equal, assert_array_almost_equal, + assert_allclose, assert_, assert_warns, + assert_array_less, suppress_warnings, + assert_array_max_ulp, IS_PYPY) +import pytest +from pytest import raises as assert_raises + +import numpy as np +from numpy import typecodes, array +from numpy.lib.recfunctions import rec_append_fields +from scipy import special +from scipy._lib._util import check_random_state +from scipy.integrate import (IntegrationWarning, quad, trapezoid, + cumulative_trapezoid) +import scipy.stats as stats +from scipy.stats._distn_infrastructure import argsreduce +from scipy.stats._constants import _XMAX +import scipy.stats.distributions + +from scipy.special import xlogy, polygamma, entr +from scipy.stats._distr_params import distcont, invdistcont +from .test_discrete_basic import distdiscrete, invdistdiscrete +from scipy.stats._continuous_distns import FitDataError, _argus_phi +from scipy.optimize import root, fmin, differential_evolution +from itertools import product + +# python -OO strips docstrings +DOCSTRINGS_STRIPPED = sys.flags.optimize > 1 + +# Failing on macOS 11, Intel CPUs. See gh-14901 +MACOS_INTEL = (sys.platform == 'darwin') and (platform.machine() == 'x86_64') + + +# distributions to skip while testing the fix for the support method +# introduced in gh-13294. These distributions are skipped as they +# always return a non-nan support for every parametrization. +skip_test_support_gh13294_regression = ['tukeylambda', 'pearson3'] + + +def _assert_hasattr(a, b, msg=None): + if msg is None: + msg = f'{a} does not have attribute {b}' + assert_(hasattr(a, b), msg=msg) + + +def test_api_regression(): + # https://github.com/scipy/scipy/issues/3802 + _assert_hasattr(scipy.stats.distributions, 'f_gen') + + +def test_distributions_submodule(): + actual = set(scipy.stats.distributions.__all__) + continuous = [dist[0] for dist in distcont] # continuous dist names + discrete = [dist[0] for dist in distdiscrete] # discrete dist names + other = ['rv_discrete', 'rv_continuous', 'rv_histogram', + 'entropy', 'trapz'] + expected = continuous + discrete + other + + # need to remove, e.g., + # + expected = set(filter(lambda s: not str(s).startswith('<'), expected)) + + assert actual == expected + + +class TestVonMises: + @pytest.mark.parametrize('k', [0.1, 1, 101]) + @pytest.mark.parametrize('x', [0, 1, np.pi, 10, 100]) + def test_vonmises_periodic(self, k, x): + def check_vonmises_pdf_periodic(k, L, s, x): + vm = stats.vonmises(k, loc=L, scale=s) + assert_almost_equal(vm.pdf(x), vm.pdf(x % (2 * np.pi * s))) + + def check_vonmises_cdf_periodic(k, L, s, x): + vm = stats.vonmises(k, loc=L, scale=s) + assert_almost_equal(vm.cdf(x) % 1, + vm.cdf(x % (2 * np.pi * s)) % 1) + + check_vonmises_pdf_periodic(k, 0, 1, x) + check_vonmises_pdf_periodic(k, 1, 1, x) + check_vonmises_pdf_periodic(k, 0, 10, x) + + check_vonmises_cdf_periodic(k, 0, 1, x) + check_vonmises_cdf_periodic(k, 1, 1, x) + check_vonmises_cdf_periodic(k, 0, 10, x) + + def test_vonmises_line_support(self): + assert_equal(stats.vonmises_line.a, -np.pi) + assert_equal(stats.vonmises_line.b, np.pi) + + def test_vonmises_numerical(self): + vm = stats.vonmises(800) + assert_almost_equal(vm.cdf(0), 0.5) + + # Expected values of the vonmises PDF were computed using + # mpmath with 50 digits of precision: + # + # def vmpdf_mp(x, kappa): + # x = mpmath.mpf(x) + # kappa = mpmath.mpf(kappa) + # num = mpmath.exp(kappa*mpmath.cos(x)) + # den = 2 * mpmath.pi * mpmath.besseli(0, kappa) + # return num/den + + @pytest.mark.parametrize('x, kappa, expected_pdf', + [(0.1, 0.01, 0.16074242744907072), + (0.1, 25.0, 1.7515464099118245), + (0.1, 800, 0.2073272544458798), + (2.0, 0.01, 0.15849003875385817), + (2.0, 25.0, 8.356882934278192e-16), + (2.0, 800, 0.0)]) + def test_vonmises_pdf(self, x, kappa, expected_pdf): + pdf = stats.vonmises.pdf(x, kappa) + assert_allclose(pdf, expected_pdf, rtol=1e-15) + + # Expected values of the vonmises entropy were computed using + # mpmath with 50 digits of precision: + # + # def vonmises_entropy(kappa): + # kappa = mpmath.mpf(kappa) + # return (-kappa * mpmath.besseli(1, kappa) / + # mpmath.besseli(0, kappa) + mpmath.log(2 * mpmath.pi * + # mpmath.besseli(0, kappa))) + # >>> float(vonmises_entropy(kappa)) + + @pytest.mark.parametrize('kappa, expected_entropy', + [(1, 1.6274014590199897), + (5, 0.6756431570114528), + (100, -0.8811275441649473), + (1000, -2.03468891852547), + (2000, -2.3813876496587847)]) + def test_vonmises_entropy(self, kappa, expected_entropy): + entropy = stats.vonmises.entropy(kappa) + assert_allclose(entropy, expected_entropy, rtol=1e-13) + + def test_vonmises_rvs_gh4598(self): + # check that random variates wrap around as discussed in gh-4598 + seed = 30899520 + rng1 = np.random.default_rng(seed) + rng2 = np.random.default_rng(seed) + rng3 = np.random.default_rng(seed) + rvs1 = stats.vonmises(1, loc=0, scale=1).rvs(random_state=rng1) + rvs2 = stats.vonmises(1, loc=2*np.pi, scale=1).rvs(random_state=rng2) + rvs3 = stats.vonmises(1, loc=0, + scale=(2*np.pi/abs(rvs1)+1)).rvs(random_state=rng3) + assert_allclose(rvs1, rvs2, atol=1e-15) + assert_allclose(rvs1, rvs3, atol=1e-15) + + # Expected values of the vonmises LOGPDF were computed + # using wolfram alpha: + # kappa * cos(x) - log(2*pi*I0(kappa)) + @pytest.mark.parametrize('x, kappa, expected_logpdf', + [(0.1, 0.01, -1.8279520246003170), + (0.1, 25.0, 0.5604990605420549), + (0.1, 800, -1.5734567947337514), + (2.0, 0.01, -1.8420635346185686), + (2.0, 25.0, -34.7182759850871489), + (2.0, 800, -1130.4942582548682739)]) + def test_vonmises_logpdf(self, x, kappa, expected_logpdf): + logpdf = stats.vonmises.logpdf(x, kappa) + assert_allclose(logpdf, expected_logpdf, rtol=1e-15) + + def test_vonmises_expect(self): + """ + Test that the vonmises expectation values are + computed correctly. This test checks that the + numeric integration estimates the correct normalization + (1) and mean angle (loc). These expectations are + independent of the chosen 2pi interval. + """ + rng = np.random.default_rng(6762668991392531563) + + loc, kappa, lb = rng.random(3) * 10 + res = stats.vonmises(loc=loc, kappa=kappa).expect(lambda x: 1) + assert_allclose(res, 1) + assert np.issubdtype(res.dtype, np.floating) + + bounds = lb, lb + 2 * np.pi + res = stats.vonmises(loc=loc, kappa=kappa).expect(lambda x: 1, *bounds) + assert_allclose(res, 1) + assert np.issubdtype(res.dtype, np.floating) + + bounds = lb, lb + 2 * np.pi + res = stats.vonmises(loc=loc, kappa=kappa).expect(lambda x: np.exp(1j*x), + *bounds, complex_func=1) + assert_allclose(np.angle(res), loc % (2*np.pi)) + assert np.issubdtype(res.dtype, np.complexfloating) + + @pytest.mark.xslow + @pytest.mark.parametrize("rvs_loc", [0, 2]) + @pytest.mark.parametrize("rvs_shape", [1, 100, 1e8]) + @pytest.mark.parametrize('fix_loc', [True, False]) + @pytest.mark.parametrize('fix_shape', [True, False]) + def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_shape, + fix_loc, fix_shape): + if fix_shape and fix_loc: + pytest.skip("Nothing to fit.") + + rng = np.random.default_rng(6762668991392531563) + data = stats.vonmises.rvs(rvs_shape, size=1000, loc=rvs_loc, + random_state=rng) + + kwds = {'fscale': 1} + if fix_loc: + kwds['floc'] = rvs_loc + if fix_shape: + kwds['f0'] = rvs_shape + + _assert_less_or_close_loglike(stats.vonmises, data, + stats.vonmises.nnlf, **kwds) + + @pytest.mark.slow + def test_vonmises_fit_bad_floc(self): + data = [-0.92923506, -0.32498224, 0.13054989, -0.97252014, 2.79658071, + -0.89110948, 1.22520295, 1.44398065, 2.49163859, 1.50315096, + 3.05437696, -2.73126329, -3.06272048, 1.64647173, 1.94509247, + -1.14328023, 0.8499056, 2.36714682, -1.6823179, -0.88359996] + data = np.asarray(data) + loc = -0.5 * np.pi + kappa_fit, loc_fit, scale_fit = stats.vonmises.fit(data, floc=loc) + assert kappa_fit == np.finfo(float).tiny + _assert_less_or_close_loglike(stats.vonmises, data, + stats.vonmises.nnlf, fscale=1, floc=loc) + + @pytest.mark.parametrize('sign', [-1, 1]) + def test_vonmises_fit_unwrapped_data(self, sign): + rng = np.random.default_rng(6762668991392531563) + data = stats.vonmises(loc=sign*0.5*np.pi, kappa=10).rvs(100000, + random_state=rng) + shifted_data = data + 4*np.pi + kappa_fit, loc_fit, scale_fit = stats.vonmises.fit(data) + kappa_fit_shifted, loc_fit_shifted, _ = stats.vonmises.fit(shifted_data) + assert_allclose(loc_fit, loc_fit_shifted) + assert_allclose(kappa_fit, kappa_fit_shifted) + assert scale_fit == 1 + assert -np.pi < loc_fit < np.pi + + def test_vonmises_kappa_0_gh18166(self): + # Check that kappa = 0 is supported. + dist = stats.vonmises(0) + assert_allclose(dist.pdf(0), 1 / (2 * np.pi), rtol=1e-15) + assert_allclose(dist.cdf(np.pi/2), 0.75, rtol=1e-15) + assert_allclose(dist.sf(-np.pi/2), 0.75, rtol=1e-15) + assert_allclose(dist.ppf(0.9), np.pi*0.8, rtol=1e-15) + assert_allclose(dist.mean(), 0, atol=1e-15) + assert_allclose(dist.expect(), 0, atol=1e-15) + assert np.all(np.abs(dist.rvs(size=10, random_state=1234)) <= np.pi) + + def test_vonmises_fit_equal_data(self): + # When all data are equal, expect kappa = 1e16. + kappa, loc, scale = stats.vonmises.fit([0]) + assert kappa == 1e16 and loc == 0 and scale == 1 + + def test_vonmises_fit_bounds(self): + # For certain input data, the root bracket is violated numerically. + # Test that this situation is handled. The input data below are + # crafted to trigger the bound violation for the current choice of + # bounds and the specific way the bounds and the objective function + # are computed. + + # Test that no exception is raised when the lower bound is violated. + scipy.stats.vonmises.fit([0, 3.7e-08], floc=0) + + # Test that no exception is raised when the upper bound is violated. + scipy.stats.vonmises.fit([np.pi/2*(1-4.86e-9)], floc=0) + + +def _assert_less_or_close_loglike(dist, data, func=None, maybe_identical=False, + **kwds): + """ + This utility function checks that the negative log-likelihood function + (or `func`) of the result computed using dist.fit() is less than or equal + to the result computed using the generic fit method. Because of + normal numerical imprecision, the "equality" check is made using + `np.allclose` with a relative tolerance of 1e-15. + """ + if func is None: + func = dist.nnlf + + mle_analytical = dist.fit(data, **kwds) + numerical_opt = super(type(dist), dist).fit(data, **kwds) + + # Sanity check that the analytical MLE is actually executed. + # Due to floating point arithmetic, the generic MLE is unlikely + # to produce the exact same result as the analytical MLE. + if not maybe_identical: + assert np.any(mle_analytical != numerical_opt) + + ll_mle_analytical = func(mle_analytical, data) + ll_numerical_opt = func(numerical_opt, data) + assert (ll_mle_analytical <= ll_numerical_opt or + np.allclose(ll_mle_analytical, ll_numerical_opt, rtol=1e-15)) + + # Ideally we'd check that shapes are correctly fixed, too, but that is + # complicated by the many ways of fixing them (e.g. f0, fix_a, fa). + if 'floc' in kwds: + assert mle_analytical[-2] == kwds['floc'] + if 'fscale' in kwds: + assert mle_analytical[-1] == kwds['fscale'] + + +def assert_fit_warnings(dist): + param = ['floc', 'fscale'] + if dist.shapes: + nshapes = len(dist.shapes.split(",")) + param += ['f0', 'f1', 'f2'][:nshapes] + all_fixed = dict(zip(param, np.arange(len(param)))) + data = [1, 2, 3] + with pytest.raises(RuntimeError, + match="All parameters fixed. There is nothing " + "to optimize."): + dist.fit(data, **all_fixed) + with pytest.raises(ValueError, + match="The data contains non-finite values"): + dist.fit([np.nan]) + with pytest.raises(ValueError, + match="The data contains non-finite values"): + dist.fit([np.inf]) + with pytest.raises(TypeError, match="Unknown keyword arguments:"): + dist.fit(data, extra_keyword=2) + with pytest.raises(TypeError, match="Too many positional arguments."): + dist.fit(data, *[1]*(len(param) - 1)) + + +@pytest.mark.parametrize('dist', + ['alpha', 'betaprime', + 'fatiguelife', 'invgamma', 'invgauss', 'invweibull', + 'johnsonsb', 'levy', 'levy_l', 'lognorm', 'gibrat', + 'powerlognorm', 'rayleigh', 'wald']) +def test_support(dist): + """gh-6235""" + dct = dict(distcont) + args = dct[dist] + + dist = getattr(stats, dist) + + assert_almost_equal(dist.pdf(dist.a, *args), 0) + assert_equal(dist.logpdf(dist.a, *args), -np.inf) + assert_almost_equal(dist.pdf(dist.b, *args), 0) + assert_equal(dist.logpdf(dist.b, *args), -np.inf) + + +class TestRandInt: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.randint.rvs(5, 30, size=100) + assert_(np.all(vals < 30) & np.all(vals >= 5)) + assert_(len(vals) == 100) + vals = stats.randint.rvs(5, 30, size=(2, 50)) + assert_(np.shape(vals) == (2, 50)) + assert_(vals.dtype.char in typecodes['AllInteger']) + val = stats.randint.rvs(15, 46) + assert_((val >= 15) & (val < 46)) + assert_(isinstance(val, np.ScalarType), msg=repr(type(val))) + val = stats.randint(15, 46).rvs(3) + assert_(val.dtype.char in typecodes['AllInteger']) + + def test_pdf(self): + k = np.r_[0:36] + out = np.where((k >= 5) & (k < 30), 1.0/(30-5), 0) + vals = stats.randint.pmf(k, 5, 30) + assert_array_almost_equal(vals, out) + + def test_cdf(self): + x = np.linspace(0, 36, 100) + k = np.floor(x) + out = np.select([k >= 30, k >= 5], [1.0, (k-5.0+1)/(30-5.0)], 0) + vals = stats.randint.cdf(x, 5, 30) + assert_array_almost_equal(vals, out, decimal=12) + + +class TestBinom: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.binom.rvs(10, 0.75, size=(2, 50)) + assert_(np.all(vals >= 0) & np.all(vals <= 10)) + assert_(np.shape(vals) == (2, 50)) + assert_(vals.dtype.char in typecodes['AllInteger']) + val = stats.binom.rvs(10, 0.75) + assert_(isinstance(val, int)) + val = stats.binom(10, 0.75).rvs(3) + assert_(isinstance(val, np.ndarray)) + assert_(val.dtype.char in typecodes['AllInteger']) + + def test_pmf(self): + # regression test for Ticket #1842 + vals1 = stats.binom.pmf(100, 100, 1) + vals2 = stats.binom.pmf(0, 100, 0) + assert_allclose(vals1, 1.0, rtol=1e-15, atol=0) + assert_allclose(vals2, 1.0, rtol=1e-15, atol=0) + + def test_entropy(self): + # Basic entropy tests. + b = stats.binom(2, 0.5) + expected_p = np.array([0.25, 0.5, 0.25]) + expected_h = -sum(xlogy(expected_p, expected_p)) + h = b.entropy() + assert_allclose(h, expected_h) + + b = stats.binom(2, 0.0) + h = b.entropy() + assert_equal(h, 0.0) + + b = stats.binom(2, 1.0) + h = b.entropy() + assert_equal(h, 0.0) + + def test_warns_p0(self): + # no spurious warnings are generated for p=0; gh-3817 + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + assert_equal(stats.binom(n=2, p=0).mean(), 0) + assert_equal(stats.binom(n=2, p=0).std(), 0) + + def test_ppf_p1(self): + # Check that gh-17388 is resolved: PPF == n when p = 1 + n = 4 + assert stats.binom.ppf(q=0.3, n=n, p=1.0) == n + + def test_pmf_poisson(self): + # Check that gh-17146 is resolved: binom -> poisson + n = 1541096362225563.0 + p = 1.0477878413173978e-18 + x = np.arange(3) + res = stats.binom.pmf(x, n=n, p=p) + ref = stats.poisson.pmf(x, n * p) + assert_allclose(res, ref, atol=1e-16) + + def test_pmf_cdf(self): + # Check that gh-17809 is resolved: binom.pmf(0) ~ binom.cdf(0) + n = 25.0 * 10 ** 21 + p = 1.0 * 10 ** -21 + r = 0 + res = stats.binom.pmf(r, n, p) + ref = stats.binom.cdf(r, n, p) + assert_allclose(res, ref, atol=1e-16) + + def test_pmf_gh15101(self): + # Check that gh-15101 is resolved (no divide warnings when p~1, n~oo) + res = stats.binom.pmf(3, 2000, 0.999) + assert_allclose(res, 0, atol=1e-16) + + +class TestArcsine: + + def test_endpoints(self): + # Regression test for gh-13697. The following calculation + # should not generate a warning. + p = stats.arcsine.pdf([0, 1]) + assert_equal(p, [np.inf, np.inf]) + + +class TestBernoulli: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.bernoulli.rvs(0.75, size=(2, 50)) + assert_(np.all(vals >= 0) & np.all(vals <= 1)) + assert_(np.shape(vals) == (2, 50)) + assert_(vals.dtype.char in typecodes['AllInteger']) + val = stats.bernoulli.rvs(0.75) + assert_(isinstance(val, int)) + val = stats.bernoulli(0.75).rvs(3) + assert_(isinstance(val, np.ndarray)) + assert_(val.dtype.char in typecodes['AllInteger']) + + def test_entropy(self): + # Simple tests of entropy. + b = stats.bernoulli(0.25) + expected_h = -0.25*np.log(0.25) - 0.75*np.log(0.75) + h = b.entropy() + assert_allclose(h, expected_h) + + b = stats.bernoulli(0.0) + h = b.entropy() + assert_equal(h, 0.0) + + b = stats.bernoulli(1.0) + h = b.entropy() + assert_equal(h, 0.0) + + +class TestBradford: + # gh-6216 + def test_cdf_ppf(self): + c = 0.1 + x = np.logspace(-20, -4) + q = stats.bradford.cdf(x, c) + xx = stats.bradford.ppf(q, c) + assert_allclose(x, xx) + + +class TestCauchy: + + def test_pdf_no_overflow_warning(self): + # The argument is large enough that x**2 will overflow to + # infinity and 1/(1 + x**2) will be 0. This should not + # trigger a warning. + p = stats.cauchy.pdf(1e200) + assert p == 0.0 + + # Reference values were computed with mpmath. + @pytest.mark.parametrize( + 'x, ref', + [(0.0, -1.1447298858494002), + (5e-324, -1.1447298858494002), + (1e-34, -1.1447298858494002), + (2.2e-16, -1.1447298858494002), + (2e-8, -1.1447298858494006), + (5e-4, -1.144730135849369), + (0.1, -1.1546802167025683), + (1.5, -2.3233848821910463), + (2e18, -85.42408759475494), + (1e200, -922.1787670834676), + (_XMAX, -1420.7101556726175)]) + def test_logpdf(self, x, ref): + logp = stats.cauchy.logpdf([x, -x]) + assert_allclose(logp, [ref, ref], rtol=1e-15) + + # Reference values were computed with mpmath. + @pytest.mark.parametrize( + 'x, ref', + [(-5e15, 6.366197723675814e-17), + (-5, 0.06283295818900118), + (-1, 0.25), + (0, 0.5), + (1, 0.75), + (5, 0.9371670418109989), + (5e15, 0.9999999999999999)] + ) + @pytest.mark.parametrize( + 'method, sgn', + [(stats.cauchy.cdf, 1), + (stats.cauchy.sf, -1)] + ) + def test_cdf_sf(self, x, ref, method, sgn): + p = method(sgn*x) + assert_allclose(p, ref, rtol=1e-15) + + # Reference values were computed with mpmath. + @pytest.mark.parametrize('x, ref', + [(4e250, -7.957747154594767e-252), + (1e25, -3.1830988618379063e-26), + (10.0, -0.03223967552667532), + (0.0, -0.6931471805599453), + (-10.0, -3.4506339556469654), + (-7e45, -106.70696921963678), + (-3e225, -520.3249880981778)]) + def test_logcdf_logsf(self, x, ref): + logcdf = stats.cauchy.logcdf(x) + assert_allclose(logcdf, ref, rtol=5e-15) + logsf = stats.cauchy.logsf(-x) + assert_allclose(logsf, ref, rtol=5e-15) + + # Reference values were computed with mpmath. + @pytest.mark.parametrize( + 'p, ref', + [(1e-20, -3.1830988618379067e+19), + (1e-9, -318309886.1837906), + (0.25, -1.0), + (0.50, 0.0), + (0.75, 1.0), + (0.999999, 318309.88617359026), + (0.999999999999, 318316927901.77966)] + ) + @pytest.mark.parametrize( + 'method, sgn', + [(stats.cauchy.ppf, 1), + (stats.cauchy.isf, -1)]) + def test_ppf_isf(self, p, ref, method, sgn): + x = sgn*method(p) + assert_allclose(x, ref, rtol=1e-15) + + +class TestChi: + + # "Exact" value of chi.sf(10, 4), as computed by Wolfram Alpha with + # 1 - CDF[ChiDistribution[4], 10] + CHI_SF_10_4 = 9.83662422461598e-21 + # "Exact" value of chi.mean(df=1000) as computed by Wolfram Alpha with + # Mean[ChiDistribution[1000]] + CHI_MEAN_1000 = 31.614871896980 + + def test_sf(self): + s = stats.chi.sf(10, 4) + assert_allclose(s, self.CHI_SF_10_4, rtol=1e-15) + + def test_isf(self): + x = stats.chi.isf(self.CHI_SF_10_4, 4) + assert_allclose(x, 10, rtol=1e-15) + + def test_logcdf(self): + x = 10.0 + df = 15 + logcdf = stats.chi.logcdf(x, df) + # Reference value computed with mpath. + assert_allclose(logcdf, -1.304704343625153e-14, rtol=5e-15) + + def test_logsf(self): + x = 0.01 + df = 15 + logsf = stats.chi.logsf(x, df) + # Reference value computed with mpath. + assert_allclose(logsf, -3.936060782678026e-37, rtol=5e-15) + + # reference value for 1e14 was computed via mpmath + # from mpmath import mp + # mp.dps = 500 + # df = mp.mpf(1e14) + # float(mp.rf(mp.mpf(0.5) * df, mp.mpf(0.5)) * mp.sqrt(2.)) + + @pytest.mark.parametrize('df, ref', + [(1e3, CHI_MEAN_1000), + (1e14, 9999999.999999976)]) + def test_mean(self, df, ref): + assert_allclose(stats.chi.mean(df), ref, rtol=1e-12) + + # Entropy references values were computed with the following mpmath code + # from mpmath import mp + # mp.dps = 50 + # def chi_entropy_mpmath(df): + # df = mp.mpf(df) + # half_df = 0.5 * df + # entropy = mp.log(mp.gamma(half_df)) + 0.5 * \ + # (df - mp.log(2) - (df - mp.one) * mp.digamma(half_df)) + # return float(entropy) + + @pytest.mark.parametrize('df, ref', + [(1e-4, -9989.7316027504), + (1, 0.7257913526447274), + (1e3, 1.0721981095025448), + (1e10, 1.0723649429080335), + (1e100, 1.0723649429247002)]) + def test_entropy(self, df, ref): + assert_allclose(stats.chi(df).entropy(), ref, rtol=1e-15) + + +class TestCrystalBall: + + def test_pdf(self): + """ + All values are calculated using the independent implementation of the + ROOT framework (see https://root.cern.ch/). + Corresponding ROOT code is given in the comments. + """ + X = np.linspace(-5.0, 5.0, 21)[:-1] + + # for (double x = -5.0; x < 5.0; x += 0.5) { + # cout << setprecision(16) + # << ROOT::Math::crystalball_pdf(x, 1.0, 2.0, 1.0) + # << ", "; + # } + calculated = stats.crystalball.pdf(X, beta=1.0, m=2.0) + expected = np.array([0.02028666423671257, 0.02414280702550917, + 0.02921279650086611, 0.03606518086526679, + 0.04564499453260328, 0.05961795204258388, + 0.08114665694685029, 0.1168511860034644, + 0.1825799781304131, 0.2656523006609301, + 0.3010234935475763, 0.2656523006609301, + 0.1825799781304131, 0.09772801991305094, + 0.0407390997601359, 0.01322604925508607, + 0.003344068947749631, 0.0006584862184997063, + 0.0001009821322058648, 1.206059579124873e-05]) + assert_allclose(expected, calculated, rtol=1e-14) + + # for (double x = -5.0; x < 5.0; x += 0.5) { + # cout << setprecision(16) + # << ROOT::Math::crystalball_pdf(x, 2.0, 3.0, 1.0) + # << ", "; + # } + calculated = stats.crystalball.pdf(X, beta=2.0, m=3.0) + expected = np.array([0.00196480373120913, 0.0027975428126005, + 0.004175923965164595, 0.006631212592830816, + 0.01145873536041165, 0.022380342500804, + 0.05304970074264653, 0.1272596164638828, + 0.237752264003024, 0.3459275029304401, + 0.3919872148188981, 0.3459275029304401, + 0.237752264003024, 0.1272596164638828, + 0.05304970074264653, 0.01722271623872227, + 0.004354584612458383, 0.0008574685508575863, + 0.000131497061187334, 1.570508433595375e-05]) + assert_allclose(expected, calculated, rtol=1e-14) + + # for (double x = -5.0; x < 5.0; x += 0.5) { + # cout << setprecision(16) + # << ROOT::Math::crystalball_pdf(x, 2.0, 3.0, 2.0, 0.5) + # << ", "; + # } + calculated = stats.crystalball.pdf(X, beta=2.0, m=3.0, loc=0.5, scale=2.0) + expected = np.array([0.007859214924836521, 0.011190171250402, + 0.01670369586065838, 0.02652485037132326, + 0.04238659020399594, 0.06362980823194138, + 0.08973241216601403, 0.118876132001512, + 0.1479437366093383, 0.17296375146522, + 0.1899635180461471, 0.1959936074094491, + 0.1899635180461471, 0.17296375146522, + 0.1479437366093383, 0.118876132001512, + 0.08973241216601403, 0.06362980823194138, + 0.04238659020399594, 0.02652485037132326]) + assert_allclose(expected, calculated, rtol=1e-14) + + def test_cdf(self): + """ + All values are calculated using the independent implementation of the + ROOT framework (see https://root.cern.ch/). + Corresponding ROOT code is given in the comments. + """ + X = np.linspace(-5.0, 5.0, 21)[:-1] + + # for (double x = -5.0; x < 5.0; x += 0.5) { + # cout << setprecision(16) + # << ROOT::Math::crystalball_cdf(x, 1.0, 2.0, 1.0) + # << ", "; + # } + calculated = stats.crystalball.cdf(X, beta=1.0, m=2.0) + expected = np.array([0.1217199854202754, 0.1327854386403005, + 0.1460639825043305, 0.1622933138937006, + 0.1825799781304132, 0.2086628321490436, + 0.2434399708405509, 0.292127965008661, + 0.3651599562608263, 0.4782542338198316, + 0.6227229998727213, 0.7671917659256111, + 0.8802860434846165, 0.9495903590367718, + 0.9828337969321823, 0.9953144721881936, + 0.9989814290402977, 0.9998244687978383, + 0.9999761023377818, 0.9999974362721522]) + assert_allclose(expected, calculated, rtol=1e-13) + + # for (double x = -5.0; x < 5.0; x += 0.5) { + # cout << setprecision(16) + # << ROOT::Math::crystalball_cdf(x, 2.0, 3.0, 1.0) + # << ", "; + # } + calculated = stats.crystalball.cdf(X, beta=2.0, m=3.0) + expected = np.array([0.004420808395220632, 0.005595085625200946, + 0.007307866939038177, 0.009946818889246312, + 0.01432341920051472, 0.02238034250080412, + 0.03978727555698502, 0.08307626432678494, + 0.1733230597116304, 0.3205923321191123, + 0.508716882020547, 0.6968414319219818, + 0.8441107043294638, 0.934357499714309, + 0.9776464884841091, 0.9938985925142876, + 0.9986736357721329, 0.9997714265214375, + 0.9999688809071239, 0.9999966615611068]) + assert_allclose(expected, calculated, rtol=1e-13) + + # for (double x = -5.0; x < 5.0; x += 0.5) { + # cout << setprecision(16) + # << ROOT::Math::crystalball_cdf(x, 2.0, 3.0, 2.0, 0.5); + # << ", "; + # } + calculated = stats.crystalball.cdf(X, beta=2.0, m=3.0, loc=0.5, scale=2.0) + expected = np.array([0.0176832335808822, 0.02238034250080412, + 0.02923146775615237, 0.03978727555698502, + 0.05679453901646225, 0.08307626432678494, + 0.1212416644828466, 0.1733230597116304, + 0.2401101486313661, 0.3205923321191123, + 0.4117313791289429, 0.508716882020547, + 0.6057023849121512, 0.6968414319219818, + 0.7773236154097279, 0.8441107043294638, + 0.8961920995582476, 0.934357499714309, + 0.9606392250246318, 0.9776464884841091]) + assert_allclose(expected, calculated, rtol=1e-13) + + # Reference value computed with ROOT, e.g. + # cout << setprecision(16) + # << ROOT::Math::crystalball_cdf_c(12.0, 1.0, 2.0, 1.0) + # << endl; + @pytest.mark.parametrize( + 'x, beta, m, rootref', + [(12.0, 1.0, 2.0, 1.340451684048897e-33), + (9.0, 4.0, 1.25, 1.12843537145273e-19), + (20, 0.1, 1.001, 6.929038716892384e-93), + (-4.5, 2.0, 3.0, 0.9944049143747991), + (-30.0, 0.5, 5.0, 0.9976994814571858), + (-1e50, 1.5, 1.1, 0.9999951099570382)] + ) + def test_sf(self, x, beta, m, rootref): + sf = stats.crystalball.sf(x, beta=beta, m=m) + assert_allclose(sf, rootref, rtol=1e-13) + + def test_moments(self): + """ + All values are calculated using the pdf formula and the integrate function + of Mathematica + """ + # The Last two (alpha, n) pairs test the special case n == alpha**2 + beta = np.array([2.0, 1.0, 3.0, 2.0, 3.0]) + m = np.array([3.0, 3.0, 2.0, 4.0, 9.0]) + + # The distribution should be correctly normalised + expected_0th_moment = np.array([1.0, 1.0, 1.0, 1.0, 1.0]) + calculated_0th_moment = stats.crystalball._munp(0, beta, m) + assert_allclose(expected_0th_moment, calculated_0th_moment, rtol=0.001) + + # calculated using wolframalpha.com + # e.g. for beta = 2 and m = 3 we calculate the norm like this: + # integrate exp(-x^2/2) from -2 to infinity + + # integrate (3/2)^3*exp(-2^2/2)*(3/2-2-x)^(-3) from -infinity to -2 + norm = np.array([2.5511, 3.01873, 2.51065, 2.53983, 2.507410455]) + + a = np.array([-0.21992, -3.03265, np.inf, -0.135335, -0.003174]) + expected_1th_moment = a / norm + calculated_1th_moment = stats.crystalball._munp(1, beta, m) + assert_allclose(expected_1th_moment, calculated_1th_moment, rtol=0.001) + + a = np.array([np.inf, np.inf, np.inf, 3.2616, 2.519908]) + expected_2th_moment = a / norm + calculated_2th_moment = stats.crystalball._munp(2, beta, m) + assert_allclose(expected_2th_moment, calculated_2th_moment, rtol=0.001) + + a = np.array([np.inf, np.inf, np.inf, np.inf, -0.0577668]) + expected_3th_moment = a / norm + calculated_3th_moment = stats.crystalball._munp(3, beta, m) + assert_allclose(expected_3th_moment, calculated_3th_moment, rtol=0.001) + + a = np.array([np.inf, np.inf, np.inf, np.inf, 7.78468]) + expected_4th_moment = a / norm + calculated_4th_moment = stats.crystalball._munp(4, beta, m) + assert_allclose(expected_4th_moment, calculated_4th_moment, rtol=0.001) + + a = np.array([np.inf, np.inf, np.inf, np.inf, -1.31086]) + expected_5th_moment = a / norm + calculated_5th_moment = stats.crystalball._munp(5, beta, m) + assert_allclose(expected_5th_moment, calculated_5th_moment, rtol=0.001) + + def test_entropy(self): + # regression test for gh-13602 + cb = stats.crystalball(2, 3) + res1 = cb.entropy() + # -20000 and 30 are negative and positive infinity, respectively + lo, hi, N = -20000, 30, 200000 + x = np.linspace(lo, hi, N) + res2 = trapezoid(entr(cb.pdf(x)), x) + assert_allclose(res1, res2, rtol=1e-7) + + +class TestNBinom: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.nbinom.rvs(10, 0.75, size=(2, 50)) + assert_(np.all(vals >= 0)) + assert_(np.shape(vals) == (2, 50)) + assert_(vals.dtype.char in typecodes['AllInteger']) + val = stats.nbinom.rvs(10, 0.75) + assert_(isinstance(val, int)) + val = stats.nbinom(10, 0.75).rvs(3) + assert_(isinstance(val, np.ndarray)) + assert_(val.dtype.char in typecodes['AllInteger']) + + def test_pmf(self): + # regression test for ticket 1779 + assert_allclose(np.exp(stats.nbinom.logpmf(700, 721, 0.52)), + stats.nbinom.pmf(700, 721, 0.52)) + # logpmf(0,1,1) shouldn't return nan (regression test for gh-4029) + val = scipy.stats.nbinom.logpmf(0, 1, 1) + assert_equal(val, 0) + + def test_logcdf_gh16159(self): + # check that gh16159 is resolved. + vals = stats.nbinom.logcdf([0, 5, 0, 5], n=4.8, p=0.45) + ref = np.log(stats.nbinom.cdf([0, 5, 0, 5], n=4.8, p=0.45)) + assert_allclose(vals, ref) + + +class TestGenInvGauss: + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.slow + def test_rvs_with_mode_shift(self): + # ratio_unif w/ mode shift + gig = stats.geninvgauss(2.3, 1.5) + _, p = stats.kstest(gig.rvs(size=1500, random_state=1234), gig.cdf) + assert_equal(p > 0.05, True) + + @pytest.mark.slow + def test_rvs_without_mode_shift(self): + # ratio_unif w/o mode shift + gig = stats.geninvgauss(0.9, 0.75) + _, p = stats.kstest(gig.rvs(size=1500, random_state=1234), gig.cdf) + assert_equal(p > 0.05, True) + + @pytest.mark.slow + def test_rvs_new_method(self): + # new algorithm of Hoermann / Leydold + gig = stats.geninvgauss(0.1, 0.2) + _, p = stats.kstest(gig.rvs(size=1500, random_state=1234), gig.cdf) + assert_equal(p > 0.05, True) + + @pytest.mark.slow + def test_rvs_p_zero(self): + def my_ks_check(p, b): + gig = stats.geninvgauss(p, b) + rvs = gig.rvs(size=1500, random_state=1234) + return stats.kstest(rvs, gig.cdf)[1] > 0.05 + # boundary cases when p = 0 + assert_equal(my_ks_check(0, 0.2), True) # new algo + assert_equal(my_ks_check(0, 0.9), True) # ratio_unif w/o shift + assert_equal(my_ks_check(0, 1.5), True) # ratio_unif with shift + + def test_rvs_negative_p(self): + # if p negative, return inverse + assert_equal( + stats.geninvgauss(-1.5, 2).rvs(size=10, random_state=1234), + 1 / stats.geninvgauss(1.5, 2).rvs(size=10, random_state=1234)) + + def test_invgauss(self): + # test that invgauss is special case + ig = stats.geninvgauss.rvs(size=1500, p=-0.5, b=1, random_state=1234) + assert_equal(stats.kstest(ig, 'invgauss', args=[1])[1] > 0.15, True) + # test pdf and cdf + mu, x = 100, np.linspace(0.01, 1, 10) + pdf_ig = stats.geninvgauss.pdf(x, p=-0.5, b=1 / mu, scale=mu) + assert_allclose(pdf_ig, stats.invgauss(mu).pdf(x)) + cdf_ig = stats.geninvgauss.cdf(x, p=-0.5, b=1 / mu, scale=mu) + assert_allclose(cdf_ig, stats.invgauss(mu).cdf(x)) + + def test_pdf_R(self): + # test against R package GIGrvg + # x <- seq(0.01, 5, length.out = 10) + # GIGrvg::dgig(x, 0.5, 1, 1) + vals_R = np.array([2.081176820e-21, 4.488660034e-01, 3.747774338e-01, + 2.693297528e-01, 1.905637275e-01, 1.351476913e-01, + 9.636538981e-02, 6.909040154e-02, 4.978006801e-02, + 3.602084467e-02]) + x = np.linspace(0.01, 5, 10) + assert_allclose(vals_R, stats.geninvgauss.pdf(x, 0.5, 1)) + + def test_pdf_zero(self): + # pdf at 0 is 0, needs special treatment to avoid 1/x in pdf + assert_equal(stats.geninvgauss.pdf(0, 0.5, 0.5), 0) + # if x is large and p is moderate, make sure that pdf does not + # overflow because of x**(p-1); exp(-b*x) forces pdf to zero + assert_equal(stats.geninvgauss.pdf(2e6, 50, 2), 0) + + +class TestGenHyperbolic: + def setup_method(self): + np.random.seed(1234) + + def test_pdf_r(self): + # test against R package GeneralizedHyperbolic + # x <- seq(-10, 10, length.out = 10) + # GeneralizedHyperbolic::dghyp( + # x = x, lambda = 2, alpha = 2, beta = 1, delta = 1.5, mu = 0.5 + # ) + vals_R = np.array([ + 2.94895678275316e-13, 1.75746848647696e-10, 9.48149804073045e-08, + 4.17862521692026e-05, 0.0103947630463822, 0.240864958986839, + 0.162833527161649, 0.0374609592899472, 0.00634894847327781, + 0.000941920705790324 + ]) + + lmbda, alpha, beta = 2, 2, 1 + mu, delta = 0.5, 1.5 + args = (lmbda, alpha*delta, beta*delta) + + gh = stats.genhyperbolic(*args, loc=mu, scale=delta) + x = np.linspace(-10, 10, 10) + + assert_allclose(gh.pdf(x), vals_R, atol=0, rtol=1e-13) + + def test_cdf_r(self): + # test against R package GeneralizedHyperbolic + # q <- seq(-10, 10, length.out = 10) + # GeneralizedHyperbolic::pghyp( + # q = q, lambda = 2, alpha = 2, beta = 1, delta = 1.5, mu = 0.5 + # ) + vals_R = np.array([ + 1.01881590921421e-13, 6.13697274983578e-11, 3.37504977637992e-08, + 1.55258698166181e-05, 0.00447005453832497, 0.228935323956347, + 0.755759458895243, 0.953061062884484, 0.992598013917513, + 0.998942646586662 + ]) + + lmbda, alpha, beta = 2, 2, 1 + mu, delta = 0.5, 1.5 + args = (lmbda, alpha*delta, beta*delta) + + gh = stats.genhyperbolic(*args, loc=mu, scale=delta) + x = np.linspace(-10, 10, 10) + + assert_allclose(gh.cdf(x), vals_R, atol=0, rtol=1e-6) + + # The reference values were computed by implementing the PDF with mpmath + # and integrating it with mp.quad. The values were computed with + # mp.dps=250, and then again with mp.dps=400 to ensure the full 64 bit + # precision was computed. + @pytest.mark.parametrize( + 'x, p, a, b, loc, scale, ref', + [(-15, 2, 3, 1.5, 0.5, 1.5, 4.770036428808252e-20), + (-15, 10, 1.5, 0.25, 1, 5, 0.03282964575089294), + (-15, 10, 1.5, 1.375, 0, 1, 3.3711159600215594e-23), + (-15, 0.125, 1.5, 1.49995, 0, 1, 4.729401428898605e-23), + (-1, 0.125, 1.5, 1.49995, 0, 1, 0.0003565725914786859), + (5, -0.125, 1.5, 1.49995, 0, 1, 0.2600651974023352), + (5, -0.125, 1000, 999, 0, 1, 5.923270556517253e-28), + (20, -0.125, 1000, 999, 0, 1, 0.23452293711665634), + (40, -0.125, 1000, 999, 0, 1, 0.9999648749561968), + (60, -0.125, 1000, 999, 0, 1, 0.9999999999975475)] + ) + def test_cdf_mpmath(self, x, p, a, b, loc, scale, ref): + cdf = stats.genhyperbolic.cdf(x, p, a, b, loc=loc, scale=scale) + assert_allclose(cdf, ref, rtol=5e-12) + + # The reference values were computed by implementing the PDF with mpmath + # and integrating it with mp.quad. The values were computed with + # mp.dps=250, and then again with mp.dps=400 to ensure the full 64 bit + # precision was computed. + @pytest.mark.parametrize( + 'x, p, a, b, loc, scale, ref', + [(0, 1e-6, 12, -1, 0, 1, 0.38520358671350524), + (-1, 3, 2.5, 2.375, 1, 3, 0.9999901774267577), + (-20, 3, 2.5, 2.375, 1, 3, 1.0), + (25, 2, 3, 1.5, 0.5, 1.5, 8.593419916523976e-10), + (300, 10, 1.5, 0.25, 1, 5, 6.137415609872158e-24), + (60, -0.125, 1000, 999, 0, 1, 2.4524915075944173e-12), + (75, -0.125, 1000, 999, 0, 1, 2.9435194886214633e-18)] + ) + def test_sf_mpmath(self, x, p, a, b, loc, scale, ref): + sf = stats.genhyperbolic.sf(x, p, a, b, loc=loc, scale=scale) + assert_allclose(sf, ref, rtol=5e-12) + + def test_moments_r(self): + # test against R package GeneralizedHyperbolic + # sapply(1:4, + # function(x) GeneralizedHyperbolic::ghypMom( + # order = x, lambda = 2, alpha = 2, + # beta = 1, delta = 1.5, mu = 0.5, + # momType = 'raw') + # ) + + vals_R = [2.36848366948115, 8.4739346779246, + 37.8870502710066, 205.76608511485] + + lmbda, alpha, beta = 2, 2, 1 + mu, delta = 0.5, 1.5 + args = (lmbda, alpha*delta, beta*delta) + + vals_us = [ + stats.genhyperbolic(*args, loc=mu, scale=delta).moment(i) + for i in range(1, 5) + ] + + assert_allclose(vals_us, vals_R, atol=0, rtol=1e-13) + + def test_rvs(self): + # Kolmogorov-Smirnov test to ensure alignment + # of analytical and empirical cdfs + + lmbda, alpha, beta = 2, 2, 1 + mu, delta = 0.5, 1.5 + args = (lmbda, alpha*delta, beta*delta) + + gh = stats.genhyperbolic(*args, loc=mu, scale=delta) + _, p = stats.kstest(gh.rvs(size=1500, random_state=1234), gh.cdf) + + assert_equal(p > 0.05, True) + + def test_pdf_t(self): + # Test Against T-Student with 1 - 30 df + df = np.linspace(1, 30, 10) + + # in principle alpha should be zero in practice for big lmbdas + # alpha cannot be too small else pdf does not integrate + alpha, beta = np.float_power(df, 2)*np.finfo(np.float32).eps, 0 + mu, delta = 0, np.sqrt(df) + args = (-df/2, alpha, beta) + + gh = stats.genhyperbolic(*args, loc=mu, scale=delta) + x = np.linspace(gh.ppf(0.01), gh.ppf(0.99), 50)[:, np.newaxis] + + assert_allclose( + gh.pdf(x), stats.t.pdf(x, df), + atol=0, rtol=1e-6 + ) + + def test_pdf_cauchy(self): + # Test Against Cauchy distribution + + # in principle alpha should be zero in practice for big lmbdas + # alpha cannot be too small else pdf does not integrate + lmbda, alpha, beta = -0.5, np.finfo(np.float32).eps, 0 + mu, delta = 0, 1 + args = (lmbda, alpha, beta) + + gh = stats.genhyperbolic(*args, loc=mu, scale=delta) + x = np.linspace(gh.ppf(0.01), gh.ppf(0.99), 50)[:, np.newaxis] + + assert_allclose( + gh.pdf(x), stats.cauchy.pdf(x), + atol=0, rtol=1e-6 + ) + + def test_pdf_laplace(self): + # Test Against Laplace with location param [-10, 10] + loc = np.linspace(-10, 10, 10) + + # in principle delta should be zero in practice for big loc delta + # cannot be too small else pdf does not integrate + delta = np.finfo(np.float32).eps + + lmbda, alpha, beta = 1, 1, 0 + args = (lmbda, alpha*delta, beta*delta) + + # ppf does not integrate for scale < 5e-4 + # therefore using simple linspace to define the support + gh = stats.genhyperbolic(*args, loc=loc, scale=delta) + x = np.linspace(-20, 20, 50)[:, np.newaxis] + + assert_allclose( + gh.pdf(x), stats.laplace.pdf(x, loc=loc, scale=1), + atol=0, rtol=1e-11 + ) + + def test_pdf_norminvgauss(self): + # Test Against NIG with varying alpha/beta/delta/mu + + alpha, beta, delta, mu = ( + np.linspace(1, 20, 10), + np.linspace(0, 19, 10)*np.float_power(-1, range(10)), + np.linspace(1, 1, 10), + np.linspace(-100, 100, 10) + ) + + lmbda = - 0.5 + args = (lmbda, alpha * delta, beta * delta) + + gh = stats.genhyperbolic(*args, loc=mu, scale=delta) + x = np.linspace(gh.ppf(0.01), gh.ppf(0.99), 50)[:, np.newaxis] + + assert_allclose( + gh.pdf(x), stats.norminvgauss.pdf( + x, a=alpha, b=beta, loc=mu, scale=delta), + atol=0, rtol=1e-13 + ) + + +class TestHypSecant: + + # Reference values were computed with the mpmath expression + # float((2/mp.pi)*mp.atan(mp.exp(-x))) + # and mp.dps = 50. + @pytest.mark.parametrize('x, reference', + [(30, 5.957247804324683e-14), + (50, 1.2278802891647964e-22)]) + def test_sf(self, x, reference): + sf = stats.hypsecant.sf(x) + assert_allclose(sf, reference, rtol=5e-15) + + # Reference values were computed with the mpmath expression + # float(-mp.log(mp.tan((mp.pi/2)*p))) + # and mp.dps = 50. + @pytest.mark.parametrize('p, reference', + [(1e-6, 13.363927852673998), + (1e-12, 27.179438410639094)]) + def test_isf(self, p, reference): + x = stats.hypsecant.isf(p) + assert_allclose(x, reference, rtol=5e-15) + + def test_logcdf_logsf(self): + x = 50.0 + # Reference value was computed with mpmath. + ref = -1.2278802891647964e-22 + logcdf = stats.hypsecant.logcdf(x) + assert_allclose(logcdf, ref, rtol=5e-15) + logsf = stats.hypsecant.logsf(-x) + assert_allclose(logsf, ref, rtol=5e-15) + + +class TestNormInvGauss: + def setup_method(self): + np.random.seed(1234) + + def test_cdf_R(self): + # test pdf and cdf vals against R + # require("GeneralizedHyperbolic") + # x_test <- c(-7, -5, 0, 8, 15) + # r_cdf <- GeneralizedHyperbolic::pnig(x_test, mu = 0, a = 1, b = 0.5) + # r_pdf <- GeneralizedHyperbolic::dnig(x_test, mu = 0, a = 1, b = 0.5) + r_cdf = np.array([8.034920282e-07, 2.512671945e-05, 3.186661051e-01, + 9.988650664e-01, 9.999848769e-01]) + x_test = np.array([-7, -5, 0, 8, 15]) + vals_cdf = stats.norminvgauss.cdf(x_test, a=1, b=0.5) + assert_allclose(vals_cdf, r_cdf, atol=1e-9) + + def test_pdf_R(self): + # values from R as defined in test_cdf_R + r_pdf = np.array([1.359600783e-06, 4.413878805e-05, 4.555014266e-01, + 7.450485342e-04, 8.917889931e-06]) + x_test = np.array([-7, -5, 0, 8, 15]) + vals_pdf = stats.norminvgauss.pdf(x_test, a=1, b=0.5) + assert_allclose(vals_pdf, r_pdf, atol=1e-9) + + @pytest.mark.parametrize('x, a, b, sf, rtol', + [(-1, 1, 0, 0.8759652211005315, 1e-13), + (25, 1, 0, 1.1318690184042579e-13, 1e-4), + (1, 5, -1.5, 0.002066711134653577, 1e-12), + (10, 5, -1.5, 2.308435233930669e-29, 1e-9)]) + def test_sf_isf_mpmath(self, x, a, b, sf, rtol): + # Reference data generated with `reference_distributions.NormInvGauss`, + # e.g. `NormInvGauss(alpha=1, beta=0).sf(-1)` with mp.dps = 50 + s = stats.norminvgauss.sf(x, a, b) + assert_allclose(s, sf, rtol=rtol) + i = stats.norminvgauss.isf(sf, a, b) + assert_allclose(i, x, rtol=rtol) + + def test_sf_isf_mpmath_vectorized(self): + x = [-1, 25] + a = [1, 1] + b = 0 + sf = [0.8759652211005315, 1.1318690184042579e-13] # see previous test + s = stats.norminvgauss.sf(x, a, b) + assert_allclose(s, sf, rtol=1e-13, atol=1e-16) + i = stats.norminvgauss.isf(sf, a, b) + # Not perfect, but better than it was. See gh-13338. + assert_allclose(i, x, rtol=1e-6) + + def test_gh8718(self): + # Add test that gh-13338 resolved gh-8718 + dst = stats.norminvgauss(1, 0) + x = np.arange(0, 20, 2) + sf = dst.sf(x) + isf = dst.isf(sf) + assert_allclose(isf, x) + + def test_stats(self): + a, b = 1, 0.5 + gamma = np.sqrt(a**2 - b**2) + v_stats = (b / gamma, a**2 / gamma**3, 3.0 * b / (a * np.sqrt(gamma)), + 3.0 * (1 + 4 * b**2 / a**2) / gamma) + assert_equal(v_stats, stats.norminvgauss.stats(a, b, moments='mvsk')) + + def test_ppf(self): + a, b = 1, 0.5 + x_test = np.array([0.001, 0.5, 0.999]) + vals = stats.norminvgauss.ppf(x_test, a, b) + assert_allclose(x_test, stats.norminvgauss.cdf(vals, a, b)) + + +class TestGeom: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.geom.rvs(0.75, size=(2, 50)) + assert_(np.all(vals >= 0)) + assert_(np.shape(vals) == (2, 50)) + assert_(vals.dtype.char in typecodes['AllInteger']) + val = stats.geom.rvs(0.75) + assert_(isinstance(val, int)) + val = stats.geom(0.75).rvs(3) + assert_(isinstance(val, np.ndarray)) + assert_(val.dtype.char in typecodes['AllInteger']) + + def test_rvs_9313(self): + # previously, RVS were converted to `np.int32` on some platforms, + # causing overflow for moderately large integer output (gh-9313). + # Check that this is resolved to the extent possible w/ `np.int64`. + rng = np.random.default_rng(649496242618848) + rvs = stats.geom.rvs(np.exp(-35), size=5, random_state=rng) + assert rvs.dtype == np.int64 + assert np.all(rvs > np.iinfo(np.int32).max) + + def test_pmf(self): + vals = stats.geom.pmf([1, 2, 3], 0.5) + assert_array_almost_equal(vals, [0.5, 0.25, 0.125]) + + def test_logpmf(self): + # regression test for ticket 1793 + vals1 = np.log(stats.geom.pmf([1, 2, 3], 0.5)) + vals2 = stats.geom.logpmf([1, 2, 3], 0.5) + assert_allclose(vals1, vals2, rtol=1e-15, atol=0) + + # regression test for gh-4028 + val = stats.geom.logpmf(1, 1) + assert_equal(val, 0.0) + + def test_cdf_sf(self): + vals = stats.geom.cdf([1, 2, 3], 0.5) + vals_sf = stats.geom.sf([1, 2, 3], 0.5) + expected = array([0.5, 0.75, 0.875]) + assert_array_almost_equal(vals, expected) + assert_array_almost_equal(vals_sf, 1-expected) + + def test_logcdf_logsf(self): + vals = stats.geom.logcdf([1, 2, 3], 0.5) + vals_sf = stats.geom.logsf([1, 2, 3], 0.5) + expected = array([0.5, 0.75, 0.875]) + assert_array_almost_equal(vals, np.log(expected)) + assert_array_almost_equal(vals_sf, np.log1p(-expected)) + + def test_ppf(self): + vals = stats.geom.ppf([0.5, 0.75, 0.875], 0.5) + expected = array([1.0, 2.0, 3.0]) + assert_array_almost_equal(vals, expected) + + def test_ppf_underflow(self): + # this should not underflow + assert_allclose(stats.geom.ppf(1e-20, 1e-20), 1.0, atol=1e-14) + + def test_entropy_gh18226(self): + # gh-18226 reported that `geom.entropy` produced a warning and + # inaccurate output for small p. Check that this is resolved. + h = stats.geom(0.0146).entropy() + assert_allclose(h, 5.219397961962308, rtol=1e-15) + + def test_rvs_gh18372(self): + # gh-18372 reported that `geom.rvs` could produce negative numbers, + # with `RandomState` PRNG, but the support is positive integers. + # Check that this is resolved. + random_state = np.random.RandomState(294582935) + assert (stats.geom.rvs(1e-30, size=10, random_state=random_state) > 0).all() + +class TestPlanck: + def setup_method(self): + np.random.seed(1234) + + def test_sf(self): + vals = stats.planck.sf([1, 2, 3], 5.) + expected = array([4.5399929762484854e-05, + 3.0590232050182579e-07, + 2.0611536224385579e-09]) + assert_array_almost_equal(vals, expected) + + def test_logsf(self): + vals = stats.planck.logsf([1000., 2000., 3000.], 1000.) + expected = array([-1001000., -2001000., -3001000.]) + assert_array_almost_equal(vals, expected) + + +class TestGennorm: + def test_laplace(self): + # test against Laplace (special case for beta=1) + points = [1, 2, 3] + pdf1 = stats.gennorm.pdf(points, 1) + pdf2 = stats.laplace.pdf(points) + assert_almost_equal(pdf1, pdf2) + + def test_norm(self): + # test against normal (special case for beta=2) + points = [1, 2, 3] + pdf1 = stats.gennorm.pdf(points, 2) + pdf2 = stats.norm.pdf(points, scale=2**-.5) + assert_almost_equal(pdf1, pdf2) + + def test_rvs(self): + np.random.seed(0) + # 0 < beta < 1 + dist = stats.gennorm(0.5) + rvs = dist.rvs(size=1000) + assert stats.kstest(rvs, dist.cdf).pvalue > 0.1 + # beta = 1 + dist = stats.gennorm(1) + rvs = dist.rvs(size=1000) + rvs_laplace = stats.laplace.rvs(size=1000) + assert stats.ks_2samp(rvs, rvs_laplace).pvalue > 0.1 + # beta = 2 + dist = stats.gennorm(2) + rvs = dist.rvs(size=1000) + rvs_norm = stats.norm.rvs(scale=1/2**0.5, size=1000) + assert stats.ks_2samp(rvs, rvs_norm).pvalue > 0.1 + + def test_rvs_broadcasting(self): + np.random.seed(0) + dist = stats.gennorm([[0.5, 1.], [2., 5.]]) + rvs = dist.rvs(size=[1000, 2, 2]) + assert stats.kstest(rvs[:, 0, 0], stats.gennorm(0.5).cdf)[1] > 0.1 + assert stats.kstest(rvs[:, 0, 1], stats.gennorm(1.0).cdf)[1] > 0.1 + assert stats.kstest(rvs[:, 1, 0], stats.gennorm(2.0).cdf)[1] > 0.1 + assert stats.kstest(rvs[:, 1, 1], stats.gennorm(5.0).cdf)[1] > 0.1 + + +class TestGibrat: + + # sfx is sf(x). The values were computed with mpmath: + # + # from mpmath import mp + # mp.dps = 100 + # def gibrat_sf(x): + # return 1 - mp.ncdf(mp.log(x)) + # + # E.g. + # + # >>> float(gibrat_sf(1.5)) + # 0.3425678305148459 + # + @pytest.mark.parametrize('x, sfx', [(1.5, 0.3425678305148459), + (5000, 8.173334352522493e-18)]) + def test_sf_isf(self, x, sfx): + assert_allclose(stats.gibrat.sf(x), sfx, rtol=2e-14) + assert_allclose(stats.gibrat.isf(sfx), x, rtol=2e-14) + + +class TestGompertz: + + def test_gompertz_accuracy(self): + # Regression test for gh-4031 + p = stats.gompertz.ppf(stats.gompertz.cdf(1e-100, 1), 1) + assert_allclose(p, 1e-100) + + # sfx is sf(x). The values were computed with mpmath: + # + # from mpmath import mp + # mp.dps = 100 + # def gompertz_sf(x, c): + # return mp.exp(-c*mp.expm1(x)) + # + # E.g. + # + # >>> float(gompertz_sf(1, 2.5)) + # 0.013626967146253437 + # + @pytest.mark.parametrize('x, c, sfx', [(1, 2.5, 0.013626967146253437), + (3, 2.5, 1.8973243273704087e-21), + (0.05, 5, 0.7738668242570479), + (2.25, 5, 3.707795833465481e-19)]) + def test_sf_isf(self, x, c, sfx): + assert_allclose(stats.gompertz.sf(x, c), sfx, rtol=1e-14) + assert_allclose(stats.gompertz.isf(sfx, c), x, rtol=1e-14) + + def test_logcdf(self): + x = 8.0 + c = 0.1 + # Reference value computed with mpmath. + ref = -3.820049516821143e-130 + logcdf = stats.gompertz.logcdf(x, c) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + x = 3e-80 + c = 12 + # Reference value computed with mpmath. + ref = -3.6e-79 + logsf = stats.gompertz.logsf(x, c) + assert_allclose(logsf, ref, rtol=5e-15) + + # reference values were computed with mpmath + # from mpmath import mp + # mp.dps = 100 + # def gompertz_entropy(c): + # c = mp.mpf(c) + # return float(mp.one - mp.log(c) - mp.exp(c)*mp.e1(c)) + + @pytest.mark.parametrize('c, ref', [(1e-4, 1.5762523017634573), + (1, 0.4036526376768059), + (1000, -5.908754280976161), + (1e10, -22.025850930040455)]) + def test_entropy(self, c, ref): + assert_allclose(stats.gompertz.entropy(c), ref, rtol=1e-14) + + +class TestFoldNorm: + + # reference values were computed with mpmath with 50 digits of precision + # from mpmath import mp + # mp.dps = 50 + # mp.mpf(0.5) * (mp.erf((x - c)/mp.sqrt(2)) + mp.erf((x + c)/mp.sqrt(2))) + + @pytest.mark.parametrize('x, c, ref', [(1e-4, 1e-8, 7.978845594730578e-05), + (1e-4, 1e-4, 7.97884555483635e-05)]) + def test_cdf(self, x, c, ref): + assert_allclose(stats.foldnorm.cdf(x, c), ref, rtol=1e-15) + + +class TestHalfNorm: + + # sfx is sf(x). The values were computed with mpmath: + # + # from mpmath import mp + # mp.dps = 100 + # def halfnorm_sf(x): + # return 2*(1 - mp.ncdf(x)) + # + # E.g. + # + # >>> float(halfnorm_sf(1)) + # 0.3173105078629141 + # + @pytest.mark.parametrize('x, sfx', [(1, 0.3173105078629141), + (10, 1.523970604832105e-23)]) + def test_sf_isf(self, x, sfx): + assert_allclose(stats.halfnorm.sf(x), sfx, rtol=1e-14) + assert_allclose(stats.halfnorm.isf(sfx), x, rtol=1e-14) + + # reference values were computed via mpmath + # from mpmath import mp + # mp.dps = 100 + # def halfnorm_cdf_mpmath(x): + # x = mp.mpf(x) + # return float(mp.erf(x/mp.sqrt(2.))) + + @pytest.mark.parametrize('x, ref', [(1e-40, 7.978845608028653e-41), + (1e-18, 7.978845608028654e-19), + (8, 0.9999999999999988)]) + def test_cdf(self, x, ref): + assert_allclose(stats.halfnorm.cdf(x), ref, rtol=1e-15) + + @pytest.mark.parametrize("rvs_loc", [1e-5, 1e10]) + @pytest.mark.parametrize("rvs_scale", [1e-2, 100, 1e8]) + @pytest.mark.parametrize('fix_loc', [True, False]) + @pytest.mark.parametrize('fix_scale', [True, False]) + def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale, + fix_loc, fix_scale): + + rng = np.random.default_rng(6762668991392531563) + data = stats.halfnorm.rvs(loc=rvs_loc, scale=rvs_scale, size=1000, + random_state=rng) + + if fix_loc and fix_scale: + error_msg = ("All parameters fixed. There is nothing to " + "optimize.") + with pytest.raises(RuntimeError, match=error_msg): + stats.halflogistic.fit(data, floc=rvs_loc, fscale=rvs_scale) + return + + kwds = {} + if fix_loc: + kwds['floc'] = rvs_loc + if fix_scale: + kwds['fscale'] = rvs_scale + + # Numerical result may equal analytical result if the initial guess + # computed from moment condition is already optimal. + _assert_less_or_close_loglike(stats.halfnorm, data, **kwds, + maybe_identical=True) + + def test_fit_error(self): + # `floc` bigger than the minimal data point + with pytest.raises(FitDataError): + stats.halfnorm.fit([1, 2, 3], floc=2) + + +class TestHalfCauchy: + + @pytest.mark.parametrize("rvs_loc", [1e-5, 1e10]) + @pytest.mark.parametrize("rvs_scale", [1e-2, 1e8]) + @pytest.mark.parametrize('fix_loc', [True, False]) + @pytest.mark.parametrize('fix_scale', [True, False]) + def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale, + fix_loc, fix_scale): + + rng = np.random.default_rng(6762668991392531563) + data = stats.halfnorm.rvs(loc=rvs_loc, scale=rvs_scale, size=1000, + random_state=rng) + + if fix_loc and fix_scale: + error_msg = ("All parameters fixed. There is nothing to " + "optimize.") + with pytest.raises(RuntimeError, match=error_msg): + stats.halfcauchy.fit(data, floc=rvs_loc, fscale=rvs_scale) + return + + kwds = {} + if fix_loc: + kwds['floc'] = rvs_loc + if fix_scale: + kwds['fscale'] = rvs_scale + + _assert_less_or_close_loglike(stats.halfcauchy, data, **kwds) + + def test_fit_error(self): + # `floc` bigger than the minimal data point + with pytest.raises(FitDataError): + stats.halfcauchy.fit([1, 2, 3], floc=2) + + +class TestHalfLogistic: + # survival function reference values were computed with mpmath + # from mpmath import mp + # mp.dps = 50 + # def sf_mpmath(x): + # x = mp.mpf(x) + # return float(mp.mpf(2.)/(mp.exp(x) + mp.one)) + + @pytest.mark.parametrize('x, ref', [(100, 7.440151952041672e-44), + (200, 2.767793053473475e-87)]) + def test_sf(self, x, ref): + assert_allclose(stats.halflogistic.sf(x), ref, rtol=1e-15) + + # inverse survival function reference values were computed with mpmath + # from mpmath import mp + # mp.dps = 200 + # def isf_mpmath(x): + # halfx = mp.mpf(x)/2 + # return float(-mp.log(halfx/(mp.one - halfx))) + + @pytest.mark.parametrize('q, ref', [(7.440151952041672e-44, 100), + (2.767793053473475e-87, 200), + (1-1e-9, 1.999999943436137e-09), + (1-1e-15, 1.9984014443252818e-15)]) + def test_isf(self, q, ref): + assert_allclose(stats.halflogistic.isf(q), ref, rtol=1e-15) + + def test_logcdf(self): + x = 30.0 + # Reference value computed with mpmath. + ref = -1.871524593768035e-13 + logcdf = stats.halflogistic.logcdf(x) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + x = 2e-14 + # Reference value computed with mpmath. + ref = -1.000000000000005e-14 + logsf = stats.halflogistic.logsf(x) + assert_allclose(logsf, ref, rtol=5e-15) + + @pytest.mark.parametrize("rvs_loc", [1e-5, 1e10]) + @pytest.mark.parametrize("rvs_scale", [1e-2, 100, 1e8]) + @pytest.mark.parametrize('fix_loc', [True, False]) + @pytest.mark.parametrize('fix_scale', [True, False]) + def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale, + fix_loc, fix_scale): + + rng = np.random.default_rng(6762668991392531563) + data = stats.halflogistic.rvs(loc=rvs_loc, scale=rvs_scale, size=1000, + random_state=rng) + + kwds = {} + if fix_loc and fix_scale: + error_msg = ("All parameters fixed. There is nothing to " + "optimize.") + with pytest.raises(RuntimeError, match=error_msg): + stats.halflogistic.fit(data, floc=rvs_loc, fscale=rvs_scale) + return + + if fix_loc: + kwds['floc'] = rvs_loc + if fix_scale: + kwds['fscale'] = rvs_scale + + # Numerical result may equal analytical result if the initial guess + # computed from moment condition is already optimal. + _assert_less_or_close_loglike(stats.halflogistic, data, **kwds, + maybe_identical=True) + + def test_fit_bad_floc(self): + msg = r" Maximum likelihood estimation with 'halflogistic' requires" + with assert_raises(FitDataError, match=msg): + stats.halflogistic.fit([0, 2, 4], floc=1) + + +class TestHalfgennorm: + def test_expon(self): + # test against exponential (special case for beta=1) + points = [1, 2, 3] + pdf1 = stats.halfgennorm.pdf(points, 1) + pdf2 = stats.expon.pdf(points) + assert_almost_equal(pdf1, pdf2) + + def test_halfnorm(self): + # test against half normal (special case for beta=2) + points = [1, 2, 3] + pdf1 = stats.halfgennorm.pdf(points, 2) + pdf2 = stats.halfnorm.pdf(points, scale=2**-.5) + assert_almost_equal(pdf1, pdf2) + + def test_gennorm(self): + # test against generalized normal + points = [1, 2, 3] + pdf1 = stats.halfgennorm.pdf(points, .497324) + pdf2 = stats.gennorm.pdf(points, .497324) + assert_almost_equal(pdf1, 2*pdf2) + + +class TestLaplaceasymmetric: + def test_laplace(self): + # test against Laplace (special case for kappa=1) + points = np.array([1, 2, 3]) + pdf1 = stats.laplace_asymmetric.pdf(points, 1) + pdf2 = stats.laplace.pdf(points) + assert_allclose(pdf1, pdf2) + + def test_asymmetric_laplace_pdf(self): + # test asymmetric Laplace + points = np.array([1, 2, 3]) + kappa = 2 + kapinv = 1/kappa + pdf1 = stats.laplace_asymmetric.pdf(points, kappa) + pdf2 = stats.laplace_asymmetric.pdf(points*(kappa**2), kapinv) + assert_allclose(pdf1, pdf2) + + def test_asymmetric_laplace_log_10_16(self): + # test asymmetric Laplace + points = np.array([-np.log(16), np.log(10)]) + kappa = 2 + pdf1 = stats.laplace_asymmetric.pdf(points, kappa) + cdf1 = stats.laplace_asymmetric.cdf(points, kappa) + sf1 = stats.laplace_asymmetric.sf(points, kappa) + pdf2 = np.array([1/10, 1/250]) + cdf2 = np.array([1/5, 1 - 1/500]) + sf2 = np.array([4/5, 1/500]) + ppf1 = stats.laplace_asymmetric.ppf(cdf2, kappa) + ppf2 = points + isf1 = stats.laplace_asymmetric.isf(sf2, kappa) + isf2 = points + assert_allclose(np.concatenate((pdf1, cdf1, sf1, ppf1, isf1)), + np.concatenate((pdf2, cdf2, sf2, ppf2, isf2))) + + +class TestTruncnorm: + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.parametrize("a, b, ref", + [(0, 100, 0.7257913526447274), + (0.6, 0.7, -2.3027610681852573), + (1e-06, 2e-06, -13.815510557964274)]) + def test_entropy(self, a, b, ref): + # All reference values were calculated with mpmath: + # import numpy as np + # from mpmath import mp + # mp.dps = 50 + # def entropy_trun(a, b): + # a, b = mp.mpf(a), mp.mpf(b) + # Z = mp.ncdf(b) - mp.ncdf(a) + # + # def pdf(x): + # return mp.npdf(x) / Z + # + # res = -mp.quad(lambda t: pdf(t) * mp.log(pdf(t)), [a, b]) + # return np.float64(res) + assert_allclose(stats.truncnorm.entropy(a, b), ref, rtol=1e-10) + + @pytest.mark.parametrize("a, b, ref", + [(1e-11, 10000000000.0, 0.725791352640738), + (1e-100, 1e+100, 0.7257913526447274), + (-1e-100, 1e+100, 0.7257913526447274), + (-1e+100, 1e+100, 1.4189385332046727)]) + def test_extreme_entropy(self, a, b, ref): + # The reference values were calculated with mpmath + # import numpy as np + # from mpmath import mp + # mp.dps = 50 + # def trunc_norm_entropy(a, b): + # a, b = mp.mpf(a), mp.mpf(b) + # Z = mp.ncdf(b) - mp.ncdf(a) + # A = mp.log(mp.sqrt(2 * mp.pi * mp.e) * Z) + # B = (a * mp.npdf(a) - b * mp.npdf(b)) / (2 * Z) + # return np.float64(A + B) + assert_allclose(stats.truncnorm.entropy(a, b), ref, rtol=1e-14) + + def test_ppf_ticket1131(self): + vals = stats.truncnorm.ppf([-0.5, 0, 1e-4, 0.5, 1-1e-4, 1, 2], -1., 1., + loc=[3]*7, scale=2) + expected = np.array([np.nan, 1, 1.00056419, 3, 4.99943581, 5, np.nan]) + assert_array_almost_equal(vals, expected) + + def test_isf_ticket1131(self): + vals = stats.truncnorm.isf([-0.5, 0, 1e-4, 0.5, 1-1e-4, 1, 2], -1., 1., + loc=[3]*7, scale=2) + expected = np.array([np.nan, 5, 4.99943581, 3, 1.00056419, 1, np.nan]) + assert_array_almost_equal(vals, expected) + + def test_gh_2477_small_values(self): + # Check a case that worked in the original issue. + low, high = -11, -10 + x = stats.truncnorm.rvs(low, high, 0, 1, size=10) + assert_(low < x.min() < x.max() < high) + # Check a case that failed in the original issue. + low, high = 10, 11 + x = stats.truncnorm.rvs(low, high, 0, 1, size=10) + assert_(low < x.min() < x.max() < high) + + def test_gh_2477_large_values(self): + # Check a case that used to fail because of extreme tailness. + low, high = 100, 101 + x = stats.truncnorm.rvs(low, high, 0, 1, size=10) + assert_(low <= x.min() <= x.max() <= high), str([low, high, x]) + + # Check some additional extreme tails + low, high = 1000, 1001 + x = stats.truncnorm.rvs(low, high, 0, 1, size=10) + assert_(low < x.min() < x.max() < high) + + low, high = 10000, 10001 + x = stats.truncnorm.rvs(low, high, 0, 1, size=10) + assert_(low < x.min() < x.max() < high) + + low, high = -10001, -10000 + x = stats.truncnorm.rvs(low, high, 0, 1, size=10) + assert_(low < x.min() < x.max() < high) + + def test_gh_9403_nontail_values(self): + for low, high in [[3, 4], [-4, -3]]: + xvals = np.array([-np.inf, low, high, np.inf]) + xmid = (high+low)/2.0 + cdfs = stats.truncnorm.cdf(xvals, low, high) + sfs = stats.truncnorm.sf(xvals, low, high) + pdfs = stats.truncnorm.pdf(xvals, low, high) + expected_cdfs = np.array([0, 0, 1, 1]) + expected_sfs = np.array([1.0, 1.0, 0.0, 0.0]) + expected_pdfs = np.array([0, 3.3619772, 0.1015229, 0]) + if low < 0: + expected_pdfs = np.array([0, 0.1015229, 3.3619772, 0]) + assert_almost_equal(cdfs, expected_cdfs) + assert_almost_equal(sfs, expected_sfs) + assert_almost_equal(pdfs, expected_pdfs) + assert_almost_equal(np.log(expected_pdfs[1]/expected_pdfs[2]), + low + 0.5) + pvals = np.array([0, 0.5, 1.0]) + ppfs = stats.truncnorm.ppf(pvals, low, high) + expected_ppfs = np.array([low, np.sign(low)*3.1984741, high]) + assert_almost_equal(ppfs, expected_ppfs) + + if low < 0: + assert_almost_equal(stats.truncnorm.sf(xmid, low, high), + 0.8475544278436675) + assert_almost_equal(stats.truncnorm.cdf(xmid, low, high), + 0.1524455721563326) + else: + assert_almost_equal(stats.truncnorm.cdf(xmid, low, high), + 0.8475544278436675) + assert_almost_equal(stats.truncnorm.sf(xmid, low, high), + 0.1524455721563326) + pdf = stats.truncnorm.pdf(xmid, low, high) + assert_almost_equal(np.log(pdf/expected_pdfs[2]), (xmid+0.25)/2) + + def test_gh_9403_medium_tail_values(self): + for low, high in [[39, 40], [-40, -39]]: + xvals = np.array([-np.inf, low, high, np.inf]) + xmid = (high+low)/2.0 + cdfs = stats.truncnorm.cdf(xvals, low, high) + sfs = stats.truncnorm.sf(xvals, low, high) + pdfs = stats.truncnorm.pdf(xvals, low, high) + expected_cdfs = np.array([0, 0, 1, 1]) + expected_sfs = np.array([1.0, 1.0, 0.0, 0.0]) + expected_pdfs = np.array([0, 3.90256074e+01, 2.73349092e-16, 0]) + if low < 0: + expected_pdfs = np.array([0, 2.73349092e-16, + 3.90256074e+01, 0]) + assert_almost_equal(cdfs, expected_cdfs) + assert_almost_equal(sfs, expected_sfs) + assert_almost_equal(pdfs, expected_pdfs) + assert_almost_equal(np.log(expected_pdfs[1]/expected_pdfs[2]), + low + 0.5) + pvals = np.array([0, 0.5, 1.0]) + ppfs = stats.truncnorm.ppf(pvals, low, high) + expected_ppfs = np.array([low, np.sign(low)*39.01775731, high]) + assert_almost_equal(ppfs, expected_ppfs) + cdfs = stats.truncnorm.cdf(ppfs, low, high) + assert_almost_equal(cdfs, pvals) + + if low < 0: + assert_almost_equal(stats.truncnorm.sf(xmid, low, high), + 0.9999999970389126) + assert_almost_equal(stats.truncnorm.cdf(xmid, low, high), + 2.961048103554866e-09) + else: + assert_almost_equal(stats.truncnorm.cdf(xmid, low, high), + 0.9999999970389126) + assert_almost_equal(stats.truncnorm.sf(xmid, low, high), + 2.961048103554866e-09) + pdf = stats.truncnorm.pdf(xmid, low, high) + assert_almost_equal(np.log(pdf/expected_pdfs[2]), (xmid+0.25)/2) + + xvals = np.linspace(low, high, 11) + xvals2 = -xvals[::-1] + assert_almost_equal(stats.truncnorm.cdf(xvals, low, high), + stats.truncnorm.sf(xvals2, -high, -low)[::-1]) + assert_almost_equal(stats.truncnorm.sf(xvals, low, high), + stats.truncnorm.cdf(xvals2, -high, -low)[::-1]) + assert_almost_equal(stats.truncnorm.pdf(xvals, low, high), + stats.truncnorm.pdf(xvals2, -high, -low)[::-1]) + + def test_cdf_tail_15110_14753(self): + # Check accuracy issues reported in gh-14753 and gh-155110 + # Ground truth values calculated using Wolfram Alpha, e.g. + # (CDF[NormalDistribution[0,1],83/10]-CDF[NormalDistribution[0,1],8])/ + # (1 - CDF[NormalDistribution[0,1],8]) + assert_allclose(stats.truncnorm(13., 15.).cdf(14.), + 0.9999987259565643) + assert_allclose(stats.truncnorm(8, np.inf).cdf(8.3), + 0.9163220907327540) + + # Test data for the truncnorm stats() method. + # The data in each row is: + # a, b, mean, variance, skewness, excess kurtosis. Generated using + # https://gist.github.com/WarrenWeckesser/636b537ee889679227d53543d333a720 + _truncnorm_stats_data = [ + [-30, 30, + 0.0, 1.0, 0.0, 0.0], + [-10, 10, + 0.0, 1.0, 0.0, -1.4927521335810455e-19], + [-3, 3, + 0.0, 0.9733369246625415, 0.0, -0.17111443639774404], + [-2, 2, + 0.0, 0.7737413035499232, 0.0, -0.6344632828703505], + [0, np.inf, + 0.7978845608028654, + 0.3633802276324187, + 0.995271746431156, + 0.8691773036059741], + [-np.inf, 0, + -0.7978845608028654, + 0.3633802276324187, + -0.995271746431156, + 0.8691773036059741], + [-1, 3, + 0.282786110727154, + 0.6161417353578293, + 0.5393018494027877, + -0.20582065135274694], + [-3, 1, + -0.282786110727154, + 0.6161417353578293, + -0.5393018494027877, + -0.20582065135274694], + [-10, -9, + -9.108456288012409, + 0.011448805821636248, + -1.8985607290949496, + 5.0733461105025075], + ] + _truncnorm_stats_data = np.array(_truncnorm_stats_data) + + @pytest.mark.parametrize("case", _truncnorm_stats_data) + def test_moments(self, case): + a, b, m0, v0, s0, k0 = case + m, v, s, k = stats.truncnorm.stats(a, b, moments='mvsk') + assert_allclose([m, v, s, k], [m0, v0, s0, k0], atol=1e-17) + + def test_9902_moments(self): + m, v = stats.truncnorm.stats(0, np.inf, moments='mv') + assert_almost_equal(m, 0.79788456) + assert_almost_equal(v, 0.36338023) + + def test_gh_1489_trac_962_rvs(self): + # Check the original example. + low, high = 10, 15 + x = stats.truncnorm.rvs(low, high, 0, 1, size=10) + assert_(low < x.min() < x.max() < high) + + def test_gh_11299_rvs(self): + # Arose from investigating gh-11299 + # Test multiple shape parameters simultaneously. + low = [-10, 10, -np.inf, -5, -np.inf, -np.inf, -45, -45, 40, -10, 40] + high = [-5, 11, 5, np.inf, 40, -40, 40, -40, 45, np.inf, np.inf] + x = stats.truncnorm.rvs(low, high, size=(5, len(low))) + assert np.shape(x) == (5, len(low)) + assert_(np.all(low <= x.min(axis=0))) + assert_(np.all(x.max(axis=0) <= high)) + + def test_rvs_Generator(self): + # check that rvs can use a Generator + if hasattr(np.random, "default_rng"): + stats.truncnorm.rvs(-10, -5, size=5, + random_state=np.random.default_rng()) + + def test_logcdf_gh17064(self): + # regression test for gh-17064 - avoid roundoff error for logcdfs ~0 + a = np.array([-np.inf, -np.inf, -8, -np.inf, 10]) + b = np.array([np.inf, np.inf, 8, 10, np.inf]) + x = np.array([10, 7.5, 7.5, 9, 20]) + expected = [-7.619853024160525e-24, -3.190891672910947e-14, + -3.128682067168231e-14, -1.1285122074235991e-19, + -3.61374964828753e-66] + assert_allclose(stats.truncnorm(a, b).logcdf(x), expected) + assert_allclose(stats.truncnorm(-b, -a).logsf(-x), expected) + + def test_moments_gh18634(self): + # gh-18634 reported that moments 5 and higher didn't work; check that + # this is resolved + res = stats.truncnorm(-2, 3).moment(5) + # From Mathematica: + # Moment[TruncatedDistribution[{-2, 3}, NormalDistribution[]], 5] + ref = 1.645309620208361 + assert_allclose(res, ref) + + +class TestGenLogistic: + + # Expected values computed with mpmath with 50 digits of precision. + @pytest.mark.parametrize('x, expected', [(-1000, -1499.5945348918917), + (-125, -187.09453489189184), + (0, -1.3274028432916989), + (100, -99.59453489189184), + (1000, -999.5945348918918)]) + def test_logpdf(self, x, expected): + c = 1.5 + logp = stats.genlogistic.logpdf(x, c) + assert_allclose(logp, expected, rtol=1e-13) + + # Expected values computed with mpmath with 50 digits of precision + # from mpmath import mp + # mp.dps = 50 + # def entropy_mp(c): + # c = mp.mpf(c) + # return float(-mp.log(c)+mp.one+mp.digamma(c + mp.one) + mp.euler) + + @pytest.mark.parametrize('c, ref', [(1e-100, 231.25850929940458), + (1e-4, 10.21050485336338), + (1e8, 1.577215669901533), + (1e100, 1.5772156649015328)]) + def test_entropy(self, c, ref): + assert_allclose(stats.genlogistic.entropy(c), ref, rtol=5e-15) + + # Expected values computed with mpmath with 50 digits of precision + # from mpmath import mp + # mp.dps = 1000 + # + # def genlogistic_cdf_mp(x, c): + # x = mp.mpf(x) + # c = mp.mpf(c) + # return (mp.one + mp.exp(-x)) ** (-c) + # + # def genlogistic_sf_mp(x, c): + # return mp.one - genlogistic_cdf_mp(x, c) + # + # x, c, ref = 100, 0.02, -7.440151952041672e-466 + # print(float(mp.log(genlogistic_cdf_mp(x, c)))) + # ppf/isf reference values generated by passing in `ref` (`q` is produced) + + @pytest.mark.parametrize('x, c, ref', [(200, 10, 1.3838965267367375e-86), + (500, 20, 1.424915281348257e-216)]) + def test_sf(self, x, c, ref): + assert_allclose(stats.genlogistic.sf(x, c), ref, rtol=1e-14) + + @pytest.mark.parametrize('q, c, ref', [(0.01, 200, 9.898441467379765), + (0.001, 2, 7.600152115573173)]) + def test_isf(self, q, c, ref): + assert_allclose(stats.genlogistic.isf(q, c), ref, rtol=5e-16) + + @pytest.mark.parametrize('q, c, ref', [(0.5, 200, 5.6630969187064615), + (0.99, 20, 7.595630231412436)]) + def test_ppf(self, q, c, ref): + assert_allclose(stats.genlogistic.ppf(q, c), ref, rtol=5e-16) + + @pytest.mark.parametrize('x, c, ref', [(100, 0.02, -7.440151952041672e-46), + (50, 20, -3.857499695927835e-21)]) + def test_logcdf(self, x, c, ref): + assert_allclose(stats.genlogistic.logcdf(x, c), ref, rtol=1e-15) + + +class TestHypergeom: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.hypergeom.rvs(20, 10, 3, size=(2, 50)) + assert np.all(vals >= 0) & np.all(vals <= 3) + assert np.shape(vals) == (2, 50) + assert vals.dtype.char in typecodes['AllInteger'] + val = stats.hypergeom.rvs(20, 3, 10) + assert isinstance(val, int) + val = stats.hypergeom(20, 3, 10).rvs(3) + assert isinstance(val, np.ndarray) + assert val.dtype.char in typecodes['AllInteger'] + + def test_precision(self): + # comparison number from mpmath + M = 2500 + n = 50 + N = 500 + tot = M + good = n + hgpmf = stats.hypergeom.pmf(2, tot, good, N) + assert_almost_equal(hgpmf, 0.0010114963068932233, 11) + + def test_args(self): + # test correct output for corner cases of arguments + # see gh-2325 + assert_almost_equal(stats.hypergeom.pmf(0, 2, 1, 0), 1.0, 11) + assert_almost_equal(stats.hypergeom.pmf(1, 2, 1, 0), 0.0, 11) + + assert_almost_equal(stats.hypergeom.pmf(0, 2, 0, 2), 1.0, 11) + assert_almost_equal(stats.hypergeom.pmf(1, 2, 1, 0), 0.0, 11) + + def test_cdf_above_one(self): + # for some values of parameters, hypergeom cdf was >1, see gh-2238 + assert_(0 <= stats.hypergeom.cdf(30, 13397950, 4363, 12390) <= 1.0) + + def test_precision2(self): + # Test hypergeom precision for large numbers. See #1218. + # Results compared with those from R. + oranges = 9.9e4 + pears = 1.1e5 + fruits_eaten = np.array([3, 3.8, 3.9, 4, 4.1, 4.2, 5]) * 1e4 + quantile = 2e4 + res = [stats.hypergeom.sf(quantile, oranges + pears, oranges, eaten) + for eaten in fruits_eaten] + expected = np.array([0, 1.904153e-114, 2.752693e-66, 4.931217e-32, + 8.265601e-11, 0.1237904, 1]) + assert_allclose(res, expected, atol=0, rtol=5e-7) + + # Test with array_like first argument + quantiles = [1.9e4, 2e4, 2.1e4, 2.15e4] + res2 = stats.hypergeom.sf(quantiles, oranges + pears, oranges, 4.2e4) + expected2 = [1, 0.1237904, 6.511452e-34, 3.277667e-69] + assert_allclose(res2, expected2, atol=0, rtol=5e-7) + + def test_entropy(self): + # Simple tests of entropy. + hg = stats.hypergeom(4, 1, 1) + h = hg.entropy() + expected_p = np.array([0.75, 0.25]) + expected_h = -np.sum(xlogy(expected_p, expected_p)) + assert_allclose(h, expected_h) + + hg = stats.hypergeom(1, 1, 1) + h = hg.entropy() + assert_equal(h, 0.0) + + def test_logsf(self): + # Test logsf for very large numbers. See issue #4982 + # Results compare with those from R (v3.2.0): + # phyper(k, n, M-n, N, lower.tail=FALSE, log.p=TRUE) + # -2239.771 + + k = 1e4 + M = 1e7 + n = 1e6 + N = 5e4 + + result = stats.hypergeom.logsf(k, M, n, N) + expected = -2239.771 # From R + assert_almost_equal(result, expected, decimal=3) + + k = 1 + M = 1600 + n = 600 + N = 300 + + result = stats.hypergeom.logsf(k, M, n, N) + expected = -2.566567e-68 # From R + assert_almost_equal(result, expected, decimal=15) + + def test_logcdf(self): + # Test logcdf for very large numbers. See issue #8692 + # Results compare with those from R (v3.3.2): + # phyper(k, n, M-n, N, lower.tail=TRUE, log.p=TRUE) + # -5273.335 + + k = 1 + M = 1e7 + n = 1e6 + N = 5e4 + + result = stats.hypergeom.logcdf(k, M, n, N) + expected = -5273.335 # From R + assert_almost_equal(result, expected, decimal=3) + + # Same example as in issue #8692 + k = 40 + M = 1600 + n = 50 + N = 300 + + result = stats.hypergeom.logcdf(k, M, n, N) + expected = -7.565148879229e-23 # From R + assert_almost_equal(result, expected, decimal=15) + + k = 125 + M = 1600 + n = 250 + N = 500 + + result = stats.hypergeom.logcdf(k, M, n, N) + expected = -4.242688e-12 # From R + assert_almost_equal(result, expected, decimal=15) + + # test broadcasting robustness based on reviewer + # concerns in PR 9603; using an array version of + # the example from issue #8692 + k = np.array([40, 40, 40]) + M = 1600 + n = 50 + N = 300 + + result = stats.hypergeom.logcdf(k, M, n, N) + expected = np.full(3, -7.565148879229e-23) # filled from R result + assert_almost_equal(result, expected, decimal=15) + + def test_mean_gh18511(self): + # gh-18511 reported that the `mean` was incorrect for large arguments; + # check that this is resolved + M = 390_000 + n = 370_000 + N = 12_000 + + hm = stats.hypergeom.mean(M, n, N) + rm = n / M * N + assert_allclose(hm, rm) + + @pytest.mark.xslow + def test_sf_gh18506(self): + # gh-18506 reported that `sf` was incorrect for large population; + # check that this is resolved + n = 10 + N = 10**5 + i = np.arange(5, 15) + population_size = 10.**i + p = stats.hypergeom.sf(n - 1, population_size, N, n) + assert np.all(p > 0) + assert np.all(np.diff(p) < 0) + + +class TestLoggamma: + + # Expected cdf values were computed with mpmath. For given x and c, + # x = mpmath.mpf(x) + # c = mpmath.mpf(c) + # cdf = mpmath.gammainc(c, 0, mpmath.exp(x), + # regularized=True) + @pytest.mark.parametrize('x, c, cdf', + [(1, 2, 0.7546378854206702), + (-1, 14, 6.768116452566383e-18), + (-745.1, 0.001, 0.4749605142005238), + (-800, 0.001, 0.44958802911019136), + (-725, 0.1, 3.4301205868273265e-32), + (-740, 0.75, 1.0074360436599631e-241)]) + def test_cdf_ppf(self, x, c, cdf): + p = stats.loggamma.cdf(x, c) + assert_allclose(p, cdf, rtol=1e-13) + y = stats.loggamma.ppf(cdf, c) + assert_allclose(y, x, rtol=1e-13) + + # Expected sf values were computed with mpmath. For given x and c, + # x = mpmath.mpf(x) + # c = mpmath.mpf(c) + # sf = mpmath.gammainc(c, mpmath.exp(x), mpmath.inf, + # regularized=True) + @pytest.mark.parametrize('x, c, sf', + [(4, 1.5, 1.6341528919488565e-23), + (6, 100, 8.23836829202024e-74), + (-800, 0.001, 0.5504119708898086), + (-743, 0.0025, 0.8437131370024089)]) + def test_sf_isf(self, x, c, sf): + s = stats.loggamma.sf(x, c) + assert_allclose(s, sf, rtol=1e-13) + y = stats.loggamma.isf(sf, c) + assert_allclose(y, x, rtol=1e-13) + + def test_logpdf(self): + # Test logpdf with x=-500, c=2. ln(gamma(2)) = 0, and + # exp(-500) ~= 7e-218, which is far smaller than the ULP + # of c*x=-1000, so logpdf(-500, 2) = c*x - exp(x) - ln(gamma(2)) + # should give -1000.0. + lp = stats.loggamma.logpdf(-500, 2) + assert_allclose(lp, -1000.0, rtol=1e-14) + + def test_logcdf(self): + x = 4.0 + c = 4.5 + logcdf = stats.loggamma.logcdf(x, c) + # Reference value computed with mpmath. + ref = -2.1429747073164531e-19 + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + x = -25.0 + c = 3.5 + logsf = stats.loggamma.logsf(x, c) + # Reference value computed with mpmath. + ref = -8.58200139319556e-40 + assert_allclose(logsf, ref, rtol=5e-15) + + def test_stats(self): + # The following precomputed values are from the table in section 2.2 + # of "A Statistical Study of Log-Gamma Distribution", by Ping Shing + # Chan (thesis, McMaster University, 1993). + table = np.array([ + # c, mean, var, skew, exc. kurt. + 0.5, -1.9635, 4.9348, -1.5351, 4.0000, + 1.0, -0.5772, 1.6449, -1.1395, 2.4000, + 12.0, 2.4427, 0.0869, -0.2946, 0.1735, + ]).reshape(-1, 5) + for c, mean, var, skew, kurt in table: + computed = stats.loggamma.stats(c, moments='msvk') + assert_array_almost_equal(computed, [mean, var, skew, kurt], + decimal=4) + + @pytest.mark.parametrize('c', [0.1, 0.001]) + def test_rvs(self, c): + # Regression test for gh-11094. + x = stats.loggamma.rvs(c, size=100000) + # Before gh-11094 was fixed, the case with c=0.001 would + # generate many -inf values. + assert np.isfinite(x).all() + # Crude statistical test. About half the values should be + # less than the median and half greater than the median. + med = stats.loggamma.median(c) + btest = stats.binomtest(np.count_nonzero(x < med), len(x)) + ci = btest.proportion_ci(confidence_level=0.999) + assert ci.low < 0.5 < ci.high + + @pytest.mark.parametrize("c, ref", + [(1e-8, 19.420680753952364), + (1, 1.5772156649015328), + (1e4, -3.186214986116763), + (1e10, -10.093986931748889), + (1e100, -113.71031611649761)]) + def test_entropy(self, c, ref): + + # Reference values were calculated with mpmath + # from mpmath import mp + # mp.dps = 500 + # def loggamma_entropy_mpmath(c): + # c = mp.mpf(c) + # return float(mp.log(mp.gamma(c)) + c * (mp.one - mp.digamma(c))) + + assert_allclose(stats.loggamma.entropy(c), ref, rtol=1e-14) + + +class TestJohnsonsu: + # reference values were computed via mpmath + # from mpmath import mp + # mp.dps = 50 + # def johnsonsu_sf(x, a, b): + # x = mp.mpf(x) + # a = mp.mpf(a) + # b = mp.mpf(b) + # return float(mp.ncdf(-(a + b * mp.log(x + mp.sqrt(x*x + 1))))) + # Order is x, a, b, sf, isf tol + # (Can't expect full precision when the ISF input is very nearly 1) + cases = [(-500, 1, 1, 0.9999999982660072, 1e-8), + (2000, 1, 1, 7.426351000595343e-21, 5e-14), + (100000, 1, 1, 4.046923979269977e-40, 5e-14)] + + @pytest.mark.parametrize("case", cases) + def test_sf_isf(self, case): + x, a, b, sf, tol = case + assert_allclose(stats.johnsonsu.sf(x, a, b), sf, rtol=5e-14) + assert_allclose(stats.johnsonsu.isf(sf, a, b), x, rtol=tol) + + +class TestJohnsonb: + # reference values were computed via mpmath + # from mpmath import mp + # mp.dps = 50 + # def johnsonb_sf(x, a, b): + # x = mp.mpf(x) + # a = mp.mpf(a) + # b = mp.mpf(b) + # return float(mp.ncdf(-(a + b * mp.log(x/(mp.one - x))))) + # Order is x, a, b, sf, isf atol + # (Can't expect full precision when the ISF input is very nearly 1) + cases = [(1e-4, 1, 1, 0.9999999999999999, 1e-7), + (0.9999, 1, 1, 8.921114313932308e-25, 5e-14), + (0.999999, 1, 1, 5.815197487181902e-50, 5e-14)] + + @pytest.mark.parametrize("case", cases) + def test_sf_isf(self, case): + x, a, b, sf, tol = case + assert_allclose(stats.johnsonsb.sf(x, a, b), sf, rtol=5e-14) + assert_allclose(stats.johnsonsb.isf(sf, a, b), x, atol=tol) + + +class TestLogistic: + # gh-6226 + def test_cdf_ppf(self): + x = np.linspace(-20, 20) + y = stats.logistic.cdf(x) + xx = stats.logistic.ppf(y) + assert_allclose(x, xx) + + def test_sf_isf(self): + x = np.linspace(-20, 20) + y = stats.logistic.sf(x) + xx = stats.logistic.isf(y) + assert_allclose(x, xx) + + def test_extreme_values(self): + # p is chosen so that 1 - (1 - p) == p in double precision + p = 9.992007221626409e-16 + desired = 34.53957599234088 + assert_allclose(stats.logistic.ppf(1 - p), desired) + assert_allclose(stats.logistic.isf(p), desired) + + def test_logpdf_basic(self): + logp = stats.logistic.logpdf([-15, 0, 10]) + # Expected values computed with mpmath with 50 digits of precision. + expected = [-15.000000611804547, + -1.3862943611198906, + -10.000090797798434] + assert_allclose(logp, expected, rtol=1e-13) + + def test_logpdf_extreme_values(self): + logp = stats.logistic.logpdf([800, -800]) + # For such large arguments, logpdf(x) = -abs(x) when computed + # with 64 bit floating point. + assert_equal(logp, [-800, -800]) + + @pytest.mark.parametrize("loc_rvs,scale_rvs", [(0.4484955, 0.10216821), + (0.62918191, 0.74367064)]) + def test_fit(self, loc_rvs, scale_rvs): + data = stats.logistic.rvs(size=100, loc=loc_rvs, scale=scale_rvs) + + # test that result of fit method is the same as optimization + def func(input, data): + a, b = input + n = len(data) + x1 = np.sum(np.exp((data - a) / b) / + (1 + np.exp((data - a) / b))) - n / 2 + x2 = np.sum(((data - a) / b) * + ((np.exp((data - a) / b) - 1) / + (np.exp((data - a) / b) + 1))) - n + return x1, x2 + + expected_solution = root(func, stats.logistic._fitstart(data), args=( + data,)).x + fit_method = stats.logistic.fit(data) + + # other than computational variances, the fit method and the solution + # to this system of equations are equal + assert_allclose(fit_method, expected_solution, atol=1e-30) + + def test_fit_comp_optimizer(self): + data = stats.logistic.rvs(size=100, loc=0.5, scale=2) + _assert_less_or_close_loglike(stats.logistic, data) + _assert_less_or_close_loglike(stats.logistic, data, floc=1) + _assert_less_or_close_loglike(stats.logistic, data, fscale=1) + + @pytest.mark.parametrize('testlogcdf', [True, False]) + def test_logcdfsf_tails(self, testlogcdf): + # Test either logcdf or logsf. By symmetry, we can use the same + # expected values for both by switching the sign of x for logsf. + x = np.array([-10000, -800, 17, 50, 500]) + if testlogcdf: + y = stats.logistic.logcdf(x) + else: + y = stats.logistic.logsf(-x) + # The expected values were computed with mpmath. + expected = [-10000.0, -800.0, -4.139937633089748e-08, + -1.9287498479639178e-22, -7.124576406741286e-218] + assert_allclose(y, expected, rtol=2e-15) + + def test_fit_gh_18176(self): + # logistic.fit returned `scale < 0` for this data. Check that this has + # been fixed. + data = np.array([-459, 37, 43, 45, 45, 48, 54, 55, 58] + + [59] * 3 + [61] * 9) + # If scale were negative, NLLF would be infinite, so this would fail + _assert_less_or_close_loglike(stats.logistic, data) + + +class TestLogser: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.logser.rvs(0.75, size=(2, 50)) + assert np.all(vals >= 1) + assert np.shape(vals) == (2, 50) + assert vals.dtype.char in typecodes['AllInteger'] + val = stats.logser.rvs(0.75) + assert isinstance(val, int) + val = stats.logser(0.75).rvs(3) + assert isinstance(val, np.ndarray) + assert val.dtype.char in typecodes['AllInteger'] + + def test_pmf_small_p(self): + m = stats.logser.pmf(4, 1e-20) + # The expected value was computed using mpmath: + # >>> import mpmath + # >>> mpmath.mp.dps = 64 + # >>> k = 4 + # >>> p = mpmath.mpf('1e-20') + # >>> float(-(p**k)/k/mpmath.log(1-p)) + # 2.5e-61 + # It is also clear from noticing that for very small p, + # log(1-p) is approximately -p, and the formula becomes + # p**(k-1) / k + assert_allclose(m, 2.5e-61) + + def test_mean_small_p(self): + m = stats.logser.mean(1e-8) + # The expected mean was computed using mpmath: + # >>> import mpmath + # >>> mpmath.dps = 60 + # >>> p = mpmath.mpf('1e-8') + # >>> float(-p / ((1 - p)*mpmath.log(1 - p))) + # 1.000000005 + assert_allclose(m, 1.000000005) + + +class TestGumbel_r_l: + @pytest.fixture(scope='function') + def rng(self): + return np.random.default_rng(1234) + + @pytest.mark.parametrize("dist", [stats.gumbel_r, stats.gumbel_l]) + @pytest.mark.parametrize("loc_rvs", [-1, 0, 1]) + @pytest.mark.parametrize("scale_rvs", [.1, 1, 5]) + @pytest.mark.parametrize('fix_loc, fix_scale', + ([True, False], [False, True])) + def test_fit_comp_optimizer(self, dist, loc_rvs, scale_rvs, + fix_loc, fix_scale, rng): + data = dist.rvs(size=100, loc=loc_rvs, scale=scale_rvs, + random_state=rng) + + kwds = dict() + # the fixed location and scales are arbitrarily modified to not be + # close to the true value. + if fix_loc: + kwds['floc'] = loc_rvs * 2 + if fix_scale: + kwds['fscale'] = scale_rvs * 2 + + # test that the gumbel_* fit method is better than super method + _assert_less_or_close_loglike(dist, data, **kwds) + + @pytest.mark.parametrize("dist, sgn", [(stats.gumbel_r, 1), + (stats.gumbel_l, -1)]) + def test_fit(self, dist, sgn): + z = sgn*np.array([3, 3, 3, 3, 3, 3, 3, 3.00000001]) + loc, scale = dist.fit(z) + # The expected values were computed with mpmath with 60 digits + # of precision. + assert_allclose(loc, sgn*3.0000000001667906) + assert_allclose(scale, 1.2495222465145514e-09, rtol=1e-6) + + +class TestPareto: + def test_stats(self): + # Check the stats() method with some simple values. Also check + # that the calculations do not trigger RuntimeWarnings. + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + + m, v, s, k = stats.pareto.stats(0.5, moments='mvsk') + assert_equal(m, np.inf) + assert_equal(v, np.inf) + assert_equal(s, np.nan) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(1.0, moments='mvsk') + assert_equal(m, np.inf) + assert_equal(v, np.inf) + assert_equal(s, np.nan) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(1.5, moments='mvsk') + assert_equal(m, 3.0) + assert_equal(v, np.inf) + assert_equal(s, np.nan) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(2.0, moments='mvsk') + assert_equal(m, 2.0) + assert_equal(v, np.inf) + assert_equal(s, np.nan) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(2.5, moments='mvsk') + assert_allclose(m, 2.5 / 1.5) + assert_allclose(v, 2.5 / (1.5*1.5*0.5)) + assert_equal(s, np.nan) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(3.0, moments='mvsk') + assert_allclose(m, 1.5) + assert_allclose(v, 0.75) + assert_equal(s, np.nan) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(3.5, moments='mvsk') + assert_allclose(m, 3.5 / 2.5) + assert_allclose(v, 3.5 / (2.5*2.5*1.5)) + assert_allclose(s, (2*4.5/0.5)*np.sqrt(1.5/3.5)) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(4.0, moments='mvsk') + assert_allclose(m, 4.0 / 3.0) + assert_allclose(v, 4.0 / 18.0) + assert_allclose(s, 2*(1+4.0)/(4.0-3) * np.sqrt((4.0-2)/4.0)) + assert_equal(k, np.nan) + + m, v, s, k = stats.pareto.stats(4.5, moments='mvsk') + assert_allclose(m, 4.5 / 3.5) + assert_allclose(v, 4.5 / (3.5*3.5*2.5)) + assert_allclose(s, (2*5.5/1.5) * np.sqrt(2.5/4.5)) + assert_allclose(k, 6*(4.5**3 + 4.5**2 - 6*4.5 - 2)/(4.5*1.5*0.5)) + + def test_sf(self): + x = 1e9 + b = 2 + scale = 1.5 + p = stats.pareto.sf(x, b, loc=0, scale=scale) + expected = (scale/x)**b # 2.25e-18 + assert_allclose(p, expected) + + @pytest.fixture(scope='function') + def rng(self): + return np.random.default_rng(1234) + + @pytest.mark.filterwarnings("ignore:invalid value encountered in " + "double_scalars") + @pytest.mark.parametrize("rvs_shape", [1, 2]) + @pytest.mark.parametrize("rvs_loc", [0, 2]) + @pytest.mark.parametrize("rvs_scale", [1, 5]) + def test_fit(self, rvs_shape, rvs_loc, rvs_scale, rng): + data = stats.pareto.rvs(size=100, b=rvs_shape, scale=rvs_scale, + loc=rvs_loc, random_state=rng) + + # shape can still be fixed with multiple names + shape_mle_analytical1 = stats.pareto.fit(data, floc=0, f0=1.04)[0] + shape_mle_analytical2 = stats.pareto.fit(data, floc=0, fix_b=1.04)[0] + shape_mle_analytical3 = stats.pareto.fit(data, floc=0, fb=1.04)[0] + assert (shape_mle_analytical1 == shape_mle_analytical2 == + shape_mle_analytical3 == 1.04) + + # data can be shifted with changes to `loc` + data = stats.pareto.rvs(size=100, b=rvs_shape, scale=rvs_scale, + loc=(rvs_loc + 2), random_state=rng) + shape_mle_a, loc_mle_a, scale_mle_a = stats.pareto.fit(data, floc=2) + assert_equal(scale_mle_a + 2, data.min()) + + data_shift = data - 2 + ndata = data_shift.shape[0] + assert_equal(shape_mle_a, + ndata / np.sum(np.log(data_shift/data_shift.min()))) + assert_equal(loc_mle_a, 2) + + @pytest.mark.parametrize("rvs_shape", [.1, 2]) + @pytest.mark.parametrize("rvs_loc", [0, 2]) + @pytest.mark.parametrize("rvs_scale", [1, 5]) + @pytest.mark.parametrize('fix_shape, fix_loc, fix_scale', + [p for p in product([True, False], repeat=3) + if False in p]) + @np.errstate(invalid="ignore") + def test_fit_MLE_comp_optimizer(self, rvs_shape, rvs_loc, rvs_scale, + fix_shape, fix_loc, fix_scale, rng): + data = stats.pareto.rvs(size=100, b=rvs_shape, scale=rvs_scale, + loc=rvs_loc, random_state=rng) + + kwds = {} + if fix_shape: + kwds['f0'] = rvs_shape + if fix_loc: + kwds['floc'] = rvs_loc + if fix_scale: + kwds['fscale'] = rvs_scale + + _assert_less_or_close_loglike(stats.pareto, data, **kwds) + + @np.errstate(invalid="ignore") + def test_fit_known_bad_seed(self): + # Tests a known seed and set of parameters that would produce a result + # would violate the support of Pareto if the fit method did not check + # the constraint `fscale + floc < min(data)`. + shape, location, scale = 1, 0, 1 + data = stats.pareto.rvs(shape, location, scale, size=100, + random_state=np.random.default_rng(2535619)) + _assert_less_or_close_loglike(stats.pareto, data) + + def test_fit_warnings(self): + assert_fit_warnings(stats.pareto) + # `floc` that causes invalid negative data + assert_raises(FitDataError, stats.pareto.fit, [1, 2, 3], floc=2) + # `floc` and `fscale` combination causes invalid data + assert_raises(FitDataError, stats.pareto.fit, [5, 2, 3], floc=1, + fscale=3) + + def test_negative_data(self, rng): + data = stats.pareto.rvs(loc=-130, b=1, size=100, random_state=rng) + assert_array_less(data, 0) + # The purpose of this test is to make sure that no runtime warnings are + # raised for all negative data, not the output of the fit method. Other + # methods test the output but have to silence warnings from the super + # method. + _ = stats.pareto.fit(data) + + +class TestGenpareto: + def test_ab(self): + # c >= 0: a, b = [0, inf] + for c in [1., 0.]: + c = np.asarray(c) + a, b = stats.genpareto._get_support(c) + assert_equal(a, 0.) + assert_(np.isposinf(b)) + + # c < 0: a=0, b=1/|c| + c = np.asarray(-2.) + a, b = stats.genpareto._get_support(c) + assert_allclose([a, b], [0., 0.5]) + + def test_c0(self): + # with c=0, genpareto reduces to the exponential distribution + # rv = stats.genpareto(c=0.) + rv = stats.genpareto(c=0.) + x = np.linspace(0, 10., 30) + assert_allclose(rv.pdf(x), stats.expon.pdf(x)) + assert_allclose(rv.cdf(x), stats.expon.cdf(x)) + assert_allclose(rv.sf(x), stats.expon.sf(x)) + + q = np.linspace(0., 1., 10) + assert_allclose(rv.ppf(q), stats.expon.ppf(q)) + + def test_cm1(self): + # with c=-1, genpareto reduces to the uniform distr on [0, 1] + rv = stats.genpareto(c=-1.) + x = np.linspace(0, 10., 30) + assert_allclose(rv.pdf(x), stats.uniform.pdf(x)) + assert_allclose(rv.cdf(x), stats.uniform.cdf(x)) + assert_allclose(rv.sf(x), stats.uniform.sf(x)) + + q = np.linspace(0., 1., 10) + assert_allclose(rv.ppf(q), stats.uniform.ppf(q)) + + # logpdf(1., c=-1) should be zero + assert_allclose(rv.logpdf(1), 0) + + def test_x_inf(self): + # make sure x=inf is handled gracefully + rv = stats.genpareto(c=0.1) + assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.]) + assert_(np.isneginf(rv.logpdf(np.inf))) + + rv = stats.genpareto(c=0.) + assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.]) + assert_(np.isneginf(rv.logpdf(np.inf))) + + rv = stats.genpareto(c=-1.) + assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.]) + assert_(np.isneginf(rv.logpdf(np.inf))) + + def test_c_continuity(self): + # pdf is continuous at c=0, -1 + x = np.linspace(0, 10, 30) + for c in [0, -1]: + pdf0 = stats.genpareto.pdf(x, c) + for dc in [1e-14, -1e-14]: + pdfc = stats.genpareto.pdf(x, c + dc) + assert_allclose(pdf0, pdfc, atol=1e-12) + + cdf0 = stats.genpareto.cdf(x, c) + for dc in [1e-14, 1e-14]: + cdfc = stats.genpareto.cdf(x, c + dc) + assert_allclose(cdf0, cdfc, atol=1e-12) + + def test_c_continuity_ppf(self): + q = np.r_[np.logspace(1e-12, 0.01, base=0.1), + np.linspace(0.01, 1, 30, endpoint=False), + 1. - np.logspace(1e-12, 0.01, base=0.1)] + for c in [0., -1.]: + ppf0 = stats.genpareto.ppf(q, c) + for dc in [1e-14, -1e-14]: + ppfc = stats.genpareto.ppf(q, c + dc) + assert_allclose(ppf0, ppfc, atol=1e-12) + + def test_c_continuity_isf(self): + q = np.r_[np.logspace(1e-12, 0.01, base=0.1), + np.linspace(0.01, 1, 30, endpoint=False), + 1. - np.logspace(1e-12, 0.01, base=0.1)] + for c in [0., -1.]: + isf0 = stats.genpareto.isf(q, c) + for dc in [1e-14, -1e-14]: + isfc = stats.genpareto.isf(q, c + dc) + assert_allclose(isf0, isfc, atol=1e-12) + + def test_cdf_ppf_roundtrip(self): + # this should pass with machine precision. hat tip @pbrod + q = np.r_[np.logspace(1e-12, 0.01, base=0.1), + np.linspace(0.01, 1, 30, endpoint=False), + 1. - np.logspace(1e-12, 0.01, base=0.1)] + for c in [1e-8, -1e-18, 1e-15, -1e-15]: + assert_allclose(stats.genpareto.cdf(stats.genpareto.ppf(q, c), c), + q, atol=1e-15) + + def test_logsf(self): + logp = stats.genpareto.logsf(1e10, .01, 0, 1) + assert_allclose(logp, -1842.0680753952365) + + # Values in 'expected_stats' are + # [mean, variance, skewness, excess kurtosis]. + @pytest.mark.parametrize( + 'c, expected_stats', + [(0, [1, 1, 2, 6]), + (1/4, [4/3, 32/9, 10/np.sqrt(2), np.nan]), + (1/9, [9/8, (81/64)*(9/7), (10/9)*np.sqrt(7), 754/45]), + (-1, [1/2, 1/12, 0, -6/5])]) + def test_stats(self, c, expected_stats): + result = stats.genpareto.stats(c, moments='mvsk') + assert_allclose(result, expected_stats, rtol=1e-13, atol=1e-15) + + def test_var(self): + # Regression test for gh-11168. + v = stats.genpareto.var(1e-8) + assert_allclose(v, 1.000000040000001, rtol=1e-13) + + +class TestPearson3: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.pearson3.rvs(0.1, size=(2, 50)) + assert np.shape(vals) == (2, 50) + assert vals.dtype.char in typecodes['AllFloat'] + val = stats.pearson3.rvs(0.5) + assert isinstance(val, float) + val = stats.pearson3(0.5).rvs(3) + assert isinstance(val, np.ndarray) + assert val.dtype.char in typecodes['AllFloat'] + assert len(val) == 3 + + def test_pdf(self): + vals = stats.pearson3.pdf(2, [0.0, 0.1, 0.2]) + assert_allclose(vals, np.array([0.05399097, 0.05555481, 0.05670246]), + atol=1e-6) + vals = stats.pearson3.pdf(-3, 0.1) + assert_allclose(vals, np.array([0.00313791]), atol=1e-6) + vals = stats.pearson3.pdf([-3, -2, -1, 0, 1], 0.1) + assert_allclose(vals, np.array([0.00313791, 0.05192304, 0.25028092, + 0.39885918, 0.23413173]), atol=1e-6) + + def test_cdf(self): + vals = stats.pearson3.cdf(2, [0.0, 0.1, 0.2]) + assert_allclose(vals, np.array([0.97724987, 0.97462004, 0.97213626]), + atol=1e-6) + vals = stats.pearson3.cdf(-3, 0.1) + assert_allclose(vals, [0.00082256], atol=1e-6) + vals = stats.pearson3.cdf([-3, -2, -1, 0, 1], 0.1) + assert_allclose(vals, [8.22563821e-04, 1.99860448e-02, 1.58550710e-01, + 5.06649130e-01, 8.41442111e-01], atol=1e-6) + + def test_negative_cdf_bug_11186(self): + # incorrect CDFs for negative skews in gh-11186; fixed in gh-12640 + # Also check vectorization w/ negative, zero, and positive skews + skews = [-3, -1, 0, 0.5] + x_eval = 0.5 + neg_inf = -30 # avoid RuntimeWarning caused by np.log(0) + cdfs = stats.pearson3.cdf(x_eval, skews) + int_pdfs = [quad(stats.pearson3(skew).pdf, neg_inf, x_eval)[0] + for skew in skews] + assert_allclose(cdfs, int_pdfs) + + def test_return_array_bug_11746(self): + # pearson3.moment was returning size 0 or 1 array instead of float + # The first moment is equal to the loc, which defaults to zero + moment = stats.pearson3.moment(1, 2) + assert_equal(moment, 0) + assert isinstance(moment, np.number) + + moment = stats.pearson3.moment(1, 0.000001) + assert_equal(moment, 0) + assert isinstance(moment, np.number) + + def test_ppf_bug_17050(self): + # incorrect PPF for negative skews were reported in gh-17050 + # Check that this is fixed (even in the array case) + skews = [-3, -1, 0, 0.5] + x_eval = 0.5 + res = stats.pearson3.ppf(stats.pearson3.cdf(x_eval, skews), skews) + assert_allclose(res, x_eval) + + # Negation of the skew flips the distribution about the origin, so + # the following should hold + skew = np.array([[-0.5], [1.5]]) + x = np.linspace(-2, 2) + assert_allclose(stats.pearson3.pdf(x, skew), + stats.pearson3.pdf(-x, -skew)) + assert_allclose(stats.pearson3.cdf(x, skew), + stats.pearson3.sf(-x, -skew)) + assert_allclose(stats.pearson3.ppf(x, skew), + -stats.pearson3.isf(x, -skew)) + + def test_sf(self): + # reference values were computed via the reference distribution, e.g. + # mp.dps = 50; Pearson3(skew=skew).sf(x). Check positive, negative, + # and zero skew due to branching. + skew = [0.1, 0.5, 1.0, -0.1] + x = [5.0, 10.0, 50.0, 8.0] + ref = [1.64721926440872e-06, 8.271911573556123e-11, + 1.3149506021756343e-40, 2.763057937820296e-21] + assert_allclose(stats.pearson3.sf(x, skew), ref, rtol=2e-14) + assert_allclose(stats.pearson3.sf(x, 0), stats.norm.sf(x), rtol=2e-14) + + +class TestKappa4: + def test_cdf_genpareto(self): + # h = 1 and k != 0 is generalized Pareto + x = [0.0, 0.1, 0.2, 0.5] + h = 1.0 + for k in [-1.9, -1.0, -0.5, -0.2, -0.1, 0.1, 0.2, 0.5, 1.0, + 1.9]: + vals = stats.kappa4.cdf(x, h, k) + # shape parameter is opposite what is expected + vals_comp = stats.genpareto.cdf(x, -k) + assert_allclose(vals, vals_comp) + + def test_cdf_genextreme(self): + # h = 0 and k != 0 is generalized extreme value + x = np.linspace(-5, 5, 10) + h = 0.0 + k = np.linspace(-3, 3, 10) + vals = stats.kappa4.cdf(x, h, k) + vals_comp = stats.genextreme.cdf(x, k) + assert_allclose(vals, vals_comp) + + def test_cdf_expon(self): + # h = 1 and k = 0 is exponential + x = np.linspace(0, 10, 10) + h = 1.0 + k = 0.0 + vals = stats.kappa4.cdf(x, h, k) + vals_comp = stats.expon.cdf(x) + assert_allclose(vals, vals_comp) + + def test_cdf_gumbel_r(self): + # h = 0 and k = 0 is gumbel_r + x = np.linspace(-5, 5, 10) + h = 0.0 + k = 0.0 + vals = stats.kappa4.cdf(x, h, k) + vals_comp = stats.gumbel_r.cdf(x) + assert_allclose(vals, vals_comp) + + def test_cdf_logistic(self): + # h = -1 and k = 0 is logistic + x = np.linspace(-5, 5, 10) + h = -1.0 + k = 0.0 + vals = stats.kappa4.cdf(x, h, k) + vals_comp = stats.logistic.cdf(x) + assert_allclose(vals, vals_comp) + + def test_cdf_uniform(self): + # h = 1 and k = 1 is uniform + x = np.linspace(-5, 5, 10) + h = 1.0 + k = 1.0 + vals = stats.kappa4.cdf(x, h, k) + vals_comp = stats.uniform.cdf(x) + assert_allclose(vals, vals_comp) + + def test_integers_ctor(self): + # regression test for gh-7416: _argcheck fails for integer h and k + # in numpy 1.12 + stats.kappa4(1, 2) + + +class TestPoisson: + def setup_method(self): + np.random.seed(1234) + + def test_pmf_basic(self): + # Basic case + ln2 = np.log(2) + vals = stats.poisson.pmf([0, 1, 2], ln2) + expected = [0.5, ln2/2, ln2**2/4] + assert_allclose(vals, expected) + + def test_mu0(self): + # Edge case: mu=0 + vals = stats.poisson.pmf([0, 1, 2], 0) + expected = [1, 0, 0] + assert_array_equal(vals, expected) + + interval = stats.poisson.interval(0.95, 0) + assert_equal(interval, (0, 0)) + + def test_rvs(self): + vals = stats.poisson.rvs(0.5, size=(2, 50)) + assert np.all(vals >= 0) + assert np.shape(vals) == (2, 50) + assert vals.dtype.char in typecodes['AllInteger'] + val = stats.poisson.rvs(0.5) + assert isinstance(val, int) + val = stats.poisson(0.5).rvs(3) + assert isinstance(val, np.ndarray) + assert val.dtype.char in typecodes['AllInteger'] + + def test_stats(self): + mu = 16.0 + result = stats.poisson.stats(mu, moments='mvsk') + assert_allclose(result, [mu, mu, np.sqrt(1.0/mu), 1.0/mu]) + + mu = np.array([0.0, 1.0, 2.0]) + result = stats.poisson.stats(mu, moments='mvsk') + expected = (mu, mu, [np.inf, 1, 1/np.sqrt(2)], [np.inf, 1, 0.5]) + assert_allclose(result, expected) + + +class TestKSTwo: + def setup_method(self): + np.random.seed(1234) + + def test_cdf(self): + for n in [1, 2, 3, 10, 100, 1000]: + # Test x-values: + # 0, 1/2n, where the cdf should be 0 + # 1/n, where the cdf should be n!/n^n + # 0.5, where the cdf should match ksone.cdf + # 1-1/n, where cdf = 1-2/n^n + # 1, where cdf == 1 + # (E.g. Exact values given by Eqn 1 in Simard / L'Ecuyer) + x = np.array([0, 0.5/n, 1/n, 0.5, 1-1.0/n, 1]) + v1 = (1.0/n)**n + lg = scipy.special.gammaln(n+1) + elg = (np.exp(lg) if v1 != 0 else 0) + expected = np.array([0, 0, v1 * elg, + 1 - 2*stats.ksone.sf(0.5, n), + max(1 - 2*v1, 0.0), + 1.0]) + vals_cdf = stats.kstwo.cdf(x, n) + assert_allclose(vals_cdf, expected) + + def test_sf(self): + x = np.linspace(0, 1, 11) + for n in [1, 2, 3, 10, 100, 1000]: + # Same x values as in test_cdf, and use sf = 1 - cdf + x = np.array([0, 0.5/n, 1/n, 0.5, 1-1.0/n, 1]) + v1 = (1.0/n)**n + lg = scipy.special.gammaln(n+1) + elg = (np.exp(lg) if v1 != 0 else 0) + expected = np.array([1.0, 1.0, + 1 - v1 * elg, + 2*stats.ksone.sf(0.5, n), + min(2*v1, 1.0), 0]) + vals_sf = stats.kstwo.sf(x, n) + assert_allclose(vals_sf, expected) + + def test_cdf_sqrtn(self): + # For fixed a, cdf(a/sqrt(n), n) -> kstwobign(a) as n->infinity + # cdf(a/sqrt(n), n) is an increasing function of n (and a) + # Check that the function is indeed increasing (allowing for some + # small floating point and algorithm differences.) + x = np.linspace(0, 2, 11)[1:] + ns = [50, 100, 200, 400, 1000, 2000] + for _x in x: + xn = _x / np.sqrt(ns) + probs = stats.kstwo.cdf(xn, ns) + diffs = np.diff(probs) + assert_array_less(diffs, 1e-8) + + def test_cdf_sf(self): + x = np.linspace(0, 1, 11) + for n in [1, 2, 3, 10, 100, 1000]: + vals_cdf = stats.kstwo.cdf(x, n) + vals_sf = stats.kstwo.sf(x, n) + assert_array_almost_equal(vals_cdf, 1 - vals_sf) + + def test_cdf_sf_sqrtn(self): + x = np.linspace(0, 1, 11) + for n in [1, 2, 3, 10, 100, 1000]: + xn = x / np.sqrt(n) + vals_cdf = stats.kstwo.cdf(xn, n) + vals_sf = stats.kstwo.sf(xn, n) + assert_array_almost_equal(vals_cdf, 1 - vals_sf) + + def test_ppf_of_cdf(self): + x = np.linspace(0, 1, 11) + for n in [1, 2, 3, 10, 100, 1000]: + xn = x[x > 0.5/n] + vals_cdf = stats.kstwo.cdf(xn, n) + # CDFs close to 1 are better dealt with using the SF + cond = (0 < vals_cdf) & (vals_cdf < 0.99) + vals = stats.kstwo.ppf(vals_cdf, n) + assert_allclose(vals[cond], xn[cond], rtol=1e-4) + + def test_isf_of_sf(self): + x = np.linspace(0, 1, 11) + for n in [1, 2, 3, 10, 100, 1000]: + xn = x[x > 0.5/n] + vals_isf = stats.kstwo.isf(xn, n) + cond = (0 < vals_isf) & (vals_isf < 1.0) + vals = stats.kstwo.sf(vals_isf, n) + assert_allclose(vals[cond], xn[cond], rtol=1e-4) + + def test_ppf_of_cdf_sqrtn(self): + x = np.linspace(0, 1, 11) + for n in [1, 2, 3, 10, 100, 1000]: + xn = (x / np.sqrt(n))[x > 0.5/n] + vals_cdf = stats.kstwo.cdf(xn, n) + cond = (0 < vals_cdf) & (vals_cdf < 1.0) + vals = stats.kstwo.ppf(vals_cdf, n) + assert_allclose(vals[cond], xn[cond]) + + def test_isf_of_sf_sqrtn(self): + x = np.linspace(0, 1, 11) + for n in [1, 2, 3, 10, 100, 1000]: + xn = (x / np.sqrt(n))[x > 0.5/n] + vals_sf = stats.kstwo.sf(xn, n) + # SFs close to 1 are better dealt with using the CDF + cond = (0 < vals_sf) & (vals_sf < 0.95) + vals = stats.kstwo.isf(vals_sf, n) + assert_allclose(vals[cond], xn[cond]) + + def test_ppf(self): + probs = np.linspace(0, 1, 11)[1:] + for n in [1, 2, 3, 10, 100, 1000]: + xn = stats.kstwo.ppf(probs, n) + vals_cdf = stats.kstwo.cdf(xn, n) + assert_allclose(vals_cdf, probs) + + def test_simard_lecuyer_table1(self): + # Compute the cdf for values near the mean of the distribution. + # The mean u ~ log(2)*sqrt(pi/(2n)) + # Compute for x in [u/4, u/3, u/2, u, 2u, 3u] + # This is the computation of Table 1 of Simard, R., L'Ecuyer, P. (2011) + # "Computing the Two-Sided Kolmogorov-Smirnov Distribution". + # Except that the values below are not from the published table, but + # were generated using an independent SageMath implementation of + # Durbin's algorithm (with the exponentiation and scaling of + # Marsaglia/Tsang/Wang's version) using 500 bit arithmetic. + # Some of the values in the published table have relative + # errors greater than 1e-4. + ns = [10, 50, 100, 200, 500, 1000] + ratios = np.array([1.0/4, 1.0/3, 1.0/2, 1, 2, 3]) + expected = np.array([ + [1.92155292e-08, 5.72933228e-05, 2.15233226e-02, 6.31566589e-01, + 9.97685592e-01, 9.99999942e-01], + [2.28096224e-09, 1.99142563e-05, 1.42617934e-02, 5.95345542e-01, + 9.96177701e-01, 9.99998662e-01], + [1.00201886e-09, 1.32673079e-05, 1.24608594e-02, 5.86163220e-01, + 9.95866877e-01, 9.99998240e-01], + [4.93313022e-10, 9.52658029e-06, 1.12123138e-02, 5.79486872e-01, + 9.95661824e-01, 9.99997964e-01], + [2.37049293e-10, 6.85002458e-06, 1.01309221e-02, 5.73427224e-01, + 9.95491207e-01, 9.99997750e-01], + [1.56990874e-10, 5.71738276e-06, 9.59725430e-03, 5.70322692e-01, + 9.95409545e-01, 9.99997657e-01] + ]) + for idx, n in enumerate(ns): + x = ratios * np.log(2) * np.sqrt(np.pi/2/n) + vals_cdf = stats.kstwo.cdf(x, n) + assert_allclose(vals_cdf, expected[idx], rtol=1e-5) + + +class TestZipf: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.zipf.rvs(1.5, size=(2, 50)) + assert np.all(vals >= 1) + assert np.shape(vals) == (2, 50) + assert vals.dtype.char in typecodes['AllInteger'] + val = stats.zipf.rvs(1.5) + assert isinstance(val, int) + val = stats.zipf(1.5).rvs(3) + assert isinstance(val, np.ndarray) + assert val.dtype.char in typecodes['AllInteger'] + + def test_moments(self): + # n-th moment is finite iff a > n + 1 + m, v = stats.zipf.stats(a=2.8) + assert_(np.isfinite(m)) + assert_equal(v, np.inf) + + s, k = stats.zipf.stats(a=4.8, moments='sk') + assert_(not np.isfinite([s, k]).all()) + + +class TestDLaplace: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + vals = stats.dlaplace.rvs(1.5, size=(2, 50)) + assert np.shape(vals) == (2, 50) + assert vals.dtype.char in typecodes['AllInteger'] + val = stats.dlaplace.rvs(1.5) + assert isinstance(val, int) + val = stats.dlaplace(1.5).rvs(3) + assert isinstance(val, np.ndarray) + assert val.dtype.char in typecodes['AllInteger'] + assert stats.dlaplace.rvs(0.8) is not None + + def test_stats(self): + # compare the explicit formulas w/ direct summation using pmf + a = 1. + dl = stats.dlaplace(a) + m, v, s, k = dl.stats('mvsk') + + N = 37 + xx = np.arange(-N, N+1) + pp = dl.pmf(xx) + m2, m4 = np.sum(pp*xx**2), np.sum(pp*xx**4) + assert_equal((m, s), (0, 0)) + assert_allclose((v, k), (m2, m4/m2**2 - 3.), atol=1e-14, rtol=1e-8) + + def test_stats2(self): + a = np.log(2.) + dl = stats.dlaplace(a) + m, v, s, k = dl.stats('mvsk') + assert_equal((m, s), (0., 0.)) + assert_allclose((v, k), (4., 3.25)) + + +class TestInvgauss: + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.parametrize("rvs_mu,rvs_loc,rvs_scale", + [(2, 0, 1), (4.635, 4.362, 6.303)]) + def test_fit(self, rvs_mu, rvs_loc, rvs_scale): + data = stats.invgauss.rvs(size=100, mu=rvs_mu, + loc=rvs_loc, scale=rvs_scale) + # Analytical MLEs are calculated with formula when `floc` is fixed + mu, loc, scale = stats.invgauss.fit(data, floc=rvs_loc) + + data = data - rvs_loc + mu_temp = np.mean(data) + scale_mle = len(data) / (np.sum(data**(-1) - mu_temp**(-1))) + mu_mle = mu_temp/scale_mle + + # `mu` and `scale` match analytical formula + assert_allclose(mu_mle, mu, atol=1e-15, rtol=1e-15) + assert_allclose(scale_mle, scale, atol=1e-15, rtol=1e-15) + assert_equal(loc, rvs_loc) + data = stats.invgauss.rvs(size=100, mu=rvs_mu, + loc=rvs_loc, scale=rvs_scale) + # fixed parameters are returned + mu, loc, scale = stats.invgauss.fit(data, floc=rvs_loc - 1, + fscale=rvs_scale + 1) + assert_equal(rvs_scale + 1, scale) + assert_equal(rvs_loc - 1, loc) + + # shape can still be fixed with multiple names + shape_mle1 = stats.invgauss.fit(data, fmu=1.04)[0] + shape_mle2 = stats.invgauss.fit(data, fix_mu=1.04)[0] + shape_mle3 = stats.invgauss.fit(data, f0=1.04)[0] + assert shape_mle1 == shape_mle2 == shape_mle3 == 1.04 + + @pytest.mark.parametrize("rvs_mu,rvs_loc,rvs_scale", + [(2, 0, 1), (6.311, 3.225, 4.520)]) + def test_fit_MLE_comp_optimizer(self, rvs_mu, rvs_loc, rvs_scale): + rng = np.random.RandomState(1234) + data = stats.invgauss.rvs(size=100, mu=rvs_mu, + loc=rvs_loc, scale=rvs_scale, random_state=rng) + + super_fit = super(type(stats.invgauss), stats.invgauss).fit + # fitting without `floc` uses superclass fit method + super_fitted = super_fit(data) + invgauss_fit = stats.invgauss.fit(data) + assert_equal(super_fitted, invgauss_fit) + + # fitting with `fmu` is uses superclass fit method + super_fitted = super_fit(data, floc=0, fmu=2) + invgauss_fit = stats.invgauss.fit(data, floc=0, fmu=2) + assert_equal(super_fitted, invgauss_fit) + + # fixed `floc` uses analytical formula and provides better fit than + # super method + _assert_less_or_close_loglike(stats.invgauss, data, floc=rvs_loc) + + # fixed `floc` not resulting in invalid data < 0 uses analytical + # formulas and provides a better fit than the super method + assert np.all((data - (rvs_loc - 1)) > 0) + _assert_less_or_close_loglike(stats.invgauss, data, floc=rvs_loc - 1) + + # fixed `floc` to an arbitrary number, 0, still provides a better fit + # than the super method + _assert_less_or_close_loglike(stats.invgauss, data, floc=0) + + # fixed `fscale` to an arbitrary number still provides a better fit + # than the super method + _assert_less_or_close_loglike(stats.invgauss, data, floc=rvs_loc, + fscale=np.random.rand(1)[0]) + + def test_fit_raise_errors(self): + assert_fit_warnings(stats.invgauss) + # FitDataError is raised when negative invalid data + with pytest.raises(FitDataError): + stats.invgauss.fit([1, 2, 3], floc=2) + + def test_cdf_sf(self): + # Regression tests for gh-13614. + # Ground truth from R's statmod library (pinvgauss), e.g. + # library(statmod) + # options(digits=15) + # mu = c(4.17022005e-04, 7.20324493e-03, 1.14374817e-06, + # 3.02332573e-03, 1.46755891e-03) + # print(pinvgauss(5, mu, 1)) + + # make sure a finite value is returned when mu is very small. see + # GH-13614 + mu = [4.17022005e-04, 7.20324493e-03, 1.14374817e-06, + 3.02332573e-03, 1.46755891e-03] + expected = [1, 1, 1, 1, 1] + actual = stats.invgauss.cdf(0.4, mu=mu) + assert_equal(expected, actual) + + # test if the function can distinguish small left/right tail + # probabilities from zero. + cdf_actual = stats.invgauss.cdf(0.001, mu=1.05) + assert_allclose(cdf_actual, 4.65246506892667e-219) + sf_actual = stats.invgauss.sf(110, mu=1.05) + assert_allclose(sf_actual, 4.12851625944048e-25) + + # test if x does not cause numerical issues when mu is very small + # and x is close to mu in value. + + # slightly smaller than mu + actual = stats.invgauss.cdf(0.00009, 0.0001) + assert_allclose(actual, 2.9458022894924e-26) + + # slightly bigger than mu + actual = stats.invgauss.cdf(0.000102, 0.0001) + assert_allclose(actual, 0.976445540507925) + + def test_logcdf_logsf(self): + # Regression tests for improvements made in gh-13616. + # Ground truth from R's statmod library (pinvgauss), e.g. + # library(statmod) + # options(digits=15) + # print(pinvgauss(0.001, 1.05, 1, log.p=TRUE, lower.tail=FALSE)) + + # test if logcdf and logsf can compute values too small to + # be represented on the unlogged scale. See: gh-13616 + logcdf = stats.invgauss.logcdf(0.0001, mu=1.05) + assert_allclose(logcdf, -5003.87872590367) + logcdf = stats.invgauss.logcdf(110, 1.05) + assert_allclose(logcdf, -4.12851625944087e-25) + logsf = stats.invgauss.logsf(0.001, mu=1.05) + assert_allclose(logsf, -4.65246506892676e-219) + logsf = stats.invgauss.logsf(110, 1.05) + assert_allclose(logsf, -56.1467092416426) + + # from mpmath import mp + # mp.dps = 100 + # mu = mp.mpf(1e-2) + # ref = (1/2 * mp.log(2 * mp.pi * mp.e * mu**3) + # - 3/2* mp.exp(2/mu) * mp.e1(2/mu)) + @pytest.mark.parametrize("mu, ref", [(2e-8, -25.172361826883957), + (1e-3, -8.943444010642972), + (1e-2, -5.4962796152622335), + (1e8, 3.3244822568873476), + (1e100, 3.32448280139689)]) + def test_entropy(self, mu, ref): + assert_allclose(stats.invgauss.entropy(mu), ref, rtol=5e-14) + + +class TestLandau: + @pytest.mark.parametrize('name', ['pdf', 'cdf', 'sf', 'ppf', 'isf']) + def test_landau_levy_agreement(self, name): + # Test PDF to confirm that this is the Landau distribution + # Test other methods with tighter tolerance than generic tests + # Levy entropy is slow and inaccurate, and RVS is tested generically + if name in {'ppf', 'isf'}: + x = np.linspace(0.1, 0.9, 5), + else: + x = np.linspace(-2, 5, 10), + + landau_method = getattr(stats.landau, name) + levy_method = getattr(stats.levy_stable, name) + res = landau_method(*x) + ref = levy_method(*x, 1, 1) + assert_allclose(res, ref, rtol=1e-14) + + def test_moments(self): + # I would test these against Levy above, but Levy says variance is infinite. + assert_equal(stats.landau.stats(moments='mvsk'), (np.nan,)*4) + assert_equal(stats.landau.moment(5), np.nan) + + +class TestLaplace: + @pytest.mark.parametrize("rvs_loc", [-5, 0, 1, 2]) + @pytest.mark.parametrize("rvs_scale", [1, 2, 3, 10]) + def test_fit(self, rvs_loc, rvs_scale): + # tests that various inputs follow expected behavior + # for a variety of `loc` and `scale`. + rng = np.random.RandomState(1234) + data = stats.laplace.rvs(size=100, loc=rvs_loc, scale=rvs_scale, + random_state=rng) + + # MLE estimates are given by + loc_mle = np.median(data) + scale_mle = np.sum(np.abs(data - loc_mle)) / len(data) + + # standard outputs should match analytical MLE formulas + loc, scale = stats.laplace.fit(data) + assert_allclose(loc, loc_mle, atol=1e-15, rtol=1e-15) + assert_allclose(scale, scale_mle, atol=1e-15, rtol=1e-15) + + # fixed parameter should use analytical formula for other + loc, scale = stats.laplace.fit(data, floc=loc_mle) + assert_allclose(scale, scale_mle, atol=1e-15, rtol=1e-15) + loc, scale = stats.laplace.fit(data, fscale=scale_mle) + assert_allclose(loc, loc_mle) + + # test with non-mle fixed parameter + # create scale with non-median loc + loc = rvs_loc * 2 + scale_mle = np.sum(np.abs(data - loc)) / len(data) + + # fixed loc to non median, scale should match + # scale calculation with modified loc + loc, scale = stats.laplace.fit(data, floc=loc) + assert_equal(scale_mle, scale) + + # fixed scale created with non median loc, + # loc output should still be the data median. + loc, scale = stats.laplace.fit(data, fscale=scale_mle) + assert_equal(loc_mle, loc) + + # error raised when both `floc` and `fscale` are fixed + assert_raises(RuntimeError, stats.laplace.fit, data, floc=loc_mle, + fscale=scale_mle) + + # error is raised with non-finite values + assert_raises(ValueError, stats.laplace.fit, [np.nan]) + assert_raises(ValueError, stats.laplace.fit, [np.inf]) + + @pytest.mark.parametrize("rvs_loc,rvs_scale", [(-5, 10), + (10, 5), + (0.5, 0.2)]) + def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale): + rng = np.random.RandomState(1234) + data = stats.laplace.rvs(size=1000, loc=rvs_loc, scale=rvs_scale, + random_state=rng) + + # the log-likelihood function for laplace is given by + def ll(loc, scale, data): + return -1 * (- (len(data)) * np.log(2*scale) - + (1/scale)*np.sum(np.abs(data - loc))) + + # test that the objective function result of the analytical MLEs is + # less than or equal to that of the numerically optimized estimate + loc, scale = stats.laplace.fit(data) + loc_opt, scale_opt = super(type(stats.laplace), + stats.laplace).fit(data) + ll_mle = ll(loc, scale, data) + ll_opt = ll(loc_opt, scale_opt, data) + assert ll_mle < ll_opt or np.allclose(ll_mle, ll_opt, + atol=1e-15, rtol=1e-15) + + def test_fit_simple_non_random_data(self): + data = np.array([1.0, 1.0, 3.0, 5.0, 8.0, 14.0]) + # with `floc` fixed to 6, scale should be 4. + loc, scale = stats.laplace.fit(data, floc=6) + assert_allclose(scale, 4, atol=1e-15, rtol=1e-15) + # with `fscale` fixed to 6, loc should be 4. + loc, scale = stats.laplace.fit(data, fscale=6) + assert_allclose(loc, 4, atol=1e-15, rtol=1e-15) + + def test_sf_cdf_extremes(self): + # These calculations should not generate warnings. + x = 1000 + p0 = stats.laplace.cdf(-x) + # The exact value is smaller than can be represented with + # 64 bit floating point, so the expected result is 0. + assert p0 == 0.0 + # The closest 64 bit floating point representation of the + # exact value is 1.0. + p1 = stats.laplace.cdf(x) + assert p1 == 1.0 + + p0 = stats.laplace.sf(x) + # The exact value is smaller than can be represented with + # 64 bit floating point, so the expected result is 0. + assert p0 == 0.0 + # The closest 64 bit floating point representation of the + # exact value is 1.0. + p1 = stats.laplace.sf(-x) + assert p1 == 1.0 + + def test_sf(self): + x = 200 + p = stats.laplace.sf(x) + assert_allclose(p, np.exp(-x)/2, rtol=1e-13) + + def test_isf(self): + p = 1e-25 + x = stats.laplace.isf(p) + assert_allclose(x, -np.log(2*p), rtol=1e-13) + + def test_logcdf_logsf(self): + x = 40 + # Reference value computed with mpmath. + ref = -2.1241771276457944e-18 + logcdf = stats.laplace.logcdf(x) + assert_allclose(logcdf, ref) + logsf = stats.laplace.logsf(-x) + assert_allclose(logsf, ref, rtol=5e-15) + + +class TestLogLaplace: + + def test_sf(self): + # reference values were computed via the reference distribution, e.g. + # mp.dps = 100; LogLaplace(c=c).sf(x). + c = np.array([2.0, 3.0, 5.0]) + x = np.array([1e-5, 1e10, 1e15]) + ref = [0.99999999995, 5e-31, 5e-76] + assert_allclose(stats.loglaplace.sf(x, c), ref, rtol=1e-15) + + def test_isf(self): + # reference values were computed via the reference distribution, e.g. + # mp.dps = 100; LogLaplace(c=c).isf(q). + c = 3.25 + q = [0.8, 0.1, 1e-10, 1e-20, 1e-40] + ref = [0.7543222539245642, 1.6408455124660906, 964.4916294395846, + 1151387.578354072, 1640845512466.0906] + assert_allclose(stats.loglaplace.isf(q, c), ref, rtol=1e-14) + + @pytest.mark.parametrize('r', [1, 2, 3, 4]) + def test_moments_stats(self, r): + mom = 'mvsk'[r - 1] + c = np.arange(0.5, r + 0.5, 0.5) + + # r-th non-central moment is infinite if |r| >= c. + assert_allclose(stats.loglaplace.moment(r, c), np.inf) + + # r-th non-central moment is non-finite (inf or nan) if r >= c. + assert not np.any(np.isfinite(stats.loglaplace.stats(c, moments=mom))) + + @pytest.mark.parametrize("c", [0.5, 1.0, 2.0]) + @pytest.mark.parametrize("loc, scale", [(-1.2, 3.45)]) + @pytest.mark.parametrize("fix_c", [True, False]) + @pytest.mark.parametrize("fix_scale", [True, False]) + def test_fit_analytic_mle(self, c, loc, scale, fix_c, fix_scale): + # Test that the analytical MLE produces no worse result than the + # generic (numerical) MLE. + + rng = np.random.default_rng(6762668991392531563) + data = stats.loglaplace.rvs(c, loc=loc, scale=scale, size=100, + random_state=rng) + + kwds = {'floc': loc} + if fix_c: + kwds['fc'] = c + if fix_scale: + kwds['fscale'] = scale + nfree = 3 - len(kwds) + + if nfree == 0: + error_msg = "All parameters fixed. There is nothing to optimize." + with pytest.raises((RuntimeError, ValueError), match=error_msg): + stats.loglaplace.fit(data, **kwds) + return + + _assert_less_or_close_loglike(stats.loglaplace, data, **kwds) + + +class TestPowerlaw: + + # In the following data, `sf` was computed with mpmath. + @pytest.mark.parametrize('x, a, sf', + [(0.25, 2.0, 0.9375), + (0.99609375, 1/256, 1.528855235208108e-05)]) + def test_sf(self, x, a, sf): + assert_allclose(stats.powerlaw.sf(x, a), sf, rtol=1e-15) + + @pytest.fixture(scope='function') + def rng(self): + return np.random.default_rng(1234) + + @pytest.mark.parametrize("rvs_shape", [.1, .5, .75, 1, 2]) + @pytest.mark.parametrize("rvs_loc", [-1, 0, 1]) + @pytest.mark.parametrize("rvs_scale", [.1, 1, 5]) + @pytest.mark.parametrize('fix_shape, fix_loc, fix_scale', + [p for p in product([True, False], repeat=3) + if False in p]) + def test_fit_MLE_comp_optimizer(self, rvs_shape, rvs_loc, rvs_scale, + fix_shape, fix_loc, fix_scale, rng): + data = stats.powerlaw.rvs(size=250, a=rvs_shape, loc=rvs_loc, + scale=rvs_scale, random_state=rng) + + kwds = dict() + if fix_shape: + kwds['f0'] = rvs_shape + if fix_loc: + kwds['floc'] = np.nextafter(data.min(), -np.inf) + if fix_scale: + kwds['fscale'] = rvs_scale + + # Numerical result may equal analytical result if some code path + # of the analytical routine makes use of numerical optimization. + _assert_less_or_close_loglike(stats.powerlaw, data, **kwds, + maybe_identical=True) + + def test_problem_case(self): + # An observed problem with the test method indicated that some fixed + # scale values could cause bad results, this is now corrected. + a = 2.50002862645130604506 + location = 0.0 + scale = 35.249023299873095 + + data = stats.powerlaw.rvs(a=a, loc=location, scale=scale, size=100, + random_state=np.random.default_rng(5)) + + kwds = {'fscale': np.ptp(data) * 2} + + _assert_less_or_close_loglike(stats.powerlaw, data, **kwds) + + def test_fit_warnings(self): + assert_fit_warnings(stats.powerlaw) + # test for error when `fscale + floc <= np.max(data)` is not satisfied + msg = r" Maximum likelihood estimation with 'powerlaw' requires" + with assert_raises(FitDataError, match=msg): + stats.powerlaw.fit([1, 2, 4], floc=0, fscale=3) + + # test for error when `data - floc >= 0` is not satisfied + msg = r" Maximum likelihood estimation with 'powerlaw' requires" + with assert_raises(FitDataError, match=msg): + stats.powerlaw.fit([1, 2, 4], floc=2) + + # test for fixed location not less than `min(data)`. + msg = r" Maximum likelihood estimation with 'powerlaw' requires" + with assert_raises(FitDataError, match=msg): + stats.powerlaw.fit([1, 2, 4], floc=1) + + # test for when fixed scale is less than or equal to range of data + msg = r"Negative or zero `fscale` is outside" + with assert_raises(ValueError, match=msg): + stats.powerlaw.fit([1, 2, 4], fscale=-3) + + # test for when fixed scale is less than or equal to range of data + msg = r"`fscale` must be greater than the range of data." + with assert_raises(ValueError, match=msg): + stats.powerlaw.fit([1, 2, 4], fscale=3) + + def test_minimum_data_zero_gh17801(self): + # gh-17801 reported an overflow error when the minimum value of the + # data is zero. Check that this problem is resolved. + data = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6] + dist = stats.powerlaw + with np.errstate(over='ignore'): + _assert_less_or_close_loglike(dist, data) + + +class TestPowerLogNorm: + + # reference values were computed via mpmath + # from mpmath import mp + # mp.dps = 80 + # def powerlognorm_sf_mp(x, c, s): + # x = mp.mpf(x) + # c = mp.mpf(c) + # s = mp.mpf(s) + # return mp.ncdf(-mp.log(x) / s)**c + # + # def powerlognormal_cdf_mp(x, c, s): + # return mp.one - powerlognorm_sf_mp(x, c, s) + # + # x, c, s = 100, 20, 1 + # print(float(powerlognorm_sf_mp(x, c, s))) + + @pytest.mark.parametrize("x, c, s, ref", + [(100, 20, 1, 1.9057100820561928e-114), + (1e-3, 20, 1, 0.9999999999507617), + (1e-3, 0.02, 1, 0.9999999999999508), + (1e22, 0.02, 1, 6.50744044621611e-12)]) + def test_sf(self, x, c, s, ref): + assert_allclose(stats.powerlognorm.sf(x, c, s), ref, rtol=1e-13) + + # reference values were computed via mpmath using the survival + # function above (passing in `ref` and getting `q`). + @pytest.mark.parametrize("q, c, s, ref", + [(0.9999999587870905, 0.02, 1, 0.01), + (6.690376686108851e-233, 20, 1, 1000)]) + def test_isf(self, q, c, s, ref): + assert_allclose(stats.powerlognorm.isf(q, c, s), ref, rtol=5e-11) + + @pytest.mark.parametrize("x, c, s, ref", + [(1e25, 0.02, 1, 0.9999999999999963), + (1e-6, 0.02, 1, 2.054921078040843e-45), + (1e-6, 200, 1, 2.0549210780408428e-41), + (0.3, 200, 1, 0.9999999999713368)]) + def test_cdf(self, x, c, s, ref): + assert_allclose(stats.powerlognorm.cdf(x, c, s), ref, rtol=3e-14) + + # reference values were computed via mpmath + # from mpmath import mp + # mp.dps = 50 + # def powerlognorm_pdf_mpmath(x, c, s): + # x = mp.mpf(x) + # c = mp.mpf(c) + # s = mp.mpf(s) + # res = (c/(x * s) * mp.npdf(mp.log(x)/s) * + # mp.ncdf(-mp.log(x)/s)**(c - mp.one)) + # return float(res) + + @pytest.mark.parametrize("x, c, s, ref", + [(1e22, 0.02, 1, 6.5954987852335016e-34), + (1e20, 1e-3, 1, 1.588073750563988e-22), + (1e40, 1e-3, 1, 1.3179391812506349e-43)]) + def test_pdf(self, x, c, s, ref): + assert_allclose(stats.powerlognorm.pdf(x, c, s), ref, rtol=3e-12) + + +class TestPowerNorm: + + # survival function references were computed with mpmath via + # from mpmath import mp + # x = mp.mpf(x) + # c = mp.mpf(x) + # float(mp.ncdf(-x)**c) + + @pytest.mark.parametrize("x, c, ref", + [(9, 1, 1.1285884059538405e-19), + (20, 2, 7.582445786569958e-178), + (100, 0.02, 3.330957891903866e-44), + (200, 0.01, 1.3004759092324774e-87)]) + def test_sf(self, x, c, ref): + assert_allclose(stats.powernorm.sf(x, c), ref, rtol=1e-13) + + # inverse survival function references were computed with mpmath via + # from mpmath import mp + # def isf_mp(q, c): + # q = mp.mpf(q) + # c = mp.mpf(c) + # arg = q**(mp.one / c) + # return float(-mp.sqrt(2) * mp.erfinv(mp.mpf(2.) * arg - mp.one)) + + @pytest.mark.parametrize("q, c, ref", + [(1e-5, 20, -0.15690800666514138), + (0.99999, 100, -5.19933666203545), + (0.9999, 0.02, -2.576676052143387), + (5e-2, 0.02, 17.089518110222244), + (1e-18, 2, 5.9978070150076865), + (1e-50, 5, 6.361340902404057)]) + def test_isf(self, q, c, ref): + assert_allclose(stats.powernorm.isf(q, c), ref, rtol=5e-12) + + # CDF reference values were computed with mpmath via + # from mpmath import mp + # def cdf_mp(x, c): + # x = mp.mpf(x) + # c = mp.mpf(c) + # return float(mp.one - mp.ncdf(-x)**c) + + @pytest.mark.parametrize("x, c, ref", + [(-12, 9, 1.598833900869911e-32), + (2, 9, 0.9999999999999983), + (-20, 9, 2.4782617067456103e-88), + (-5, 0.02, 5.733032242841443e-09), + (-20, 0.02, 5.507248237212467e-91)]) + def test_cdf(self, x, c, ref): + assert_allclose(stats.powernorm.cdf(x, c), ref, rtol=5e-14) + + +class TestInvGamma: + def test_invgamma_inf_gh_1866(self): + # invgamma's moments are only finite for a>n + # specific numbers checked w/ boost 1.54 + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + mvsk = stats.invgamma.stats(a=19.31, moments='mvsk') + expected = [0.05461496450, 0.0001723162534, 1.020362676, + 2.055616582] + assert_allclose(mvsk, expected) + + a = [1.1, 3.1, 5.6] + mvsk = stats.invgamma.stats(a=a, moments='mvsk') + expected = ([10., 0.476190476, 0.2173913043], # mmm + [np.inf, 0.2061430632, 0.01312749422], # vvv + [np.nan, 41.95235392, 2.919025532], # sss + [np.nan, np.nan, 24.51923076]) # kkk + for x, y in zip(mvsk, expected): + assert_almost_equal(x, y) + + def test_cdf_ppf(self): + # gh-6245 + x = np.logspace(-2.6, 0) + y = stats.invgamma.cdf(x, 1) + xx = stats.invgamma.ppf(y, 1) + assert_allclose(x, xx) + + def test_sf_isf(self): + # gh-6245 + if sys.maxsize > 2**32: + x = np.logspace(2, 100) + else: + # Invgamme roundtrip on 32-bit systems has relative accuracy + # ~1e-15 until x=1e+15, and becomes inf above x=1e+18 + x = np.logspace(2, 18) + + y = stats.invgamma.sf(x, 1) + xx = stats.invgamma.isf(y, 1) + assert_allclose(x, xx, rtol=1.0) + + def test_logcdf(self): + x = 1e7 + a = 2.25 + # Reference value computed with mpmath. + ref = -6.97567687425534e-17 + logcdf = stats.invgamma.logcdf(x, a) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + x = 0.01 + a = 3.5 + # Reference value computed with mpmath. + ref = -1.147781224014262e-39 + logsf = stats.invgamma.logsf(x, a) + assert_allclose(logsf, ref, rtol=5e-15) + + @pytest.mark.parametrize("a, ref", + [(100000000.0, -26.21208257605721), + (1e+100, -343.9688254159022)]) + def test_large_entropy(self, a, ref): + # The reference values were calculated with mpmath: + # from mpmath import mp + # mp.dps = 500 + + # def invgamma_entropy(a): + # a = mp.mpf(a) + # h = a + mp.loggamma(a) - (mp.one + a) * mp.digamma(a) + # return float(h) + assert_allclose(stats.invgamma.entropy(a), ref, rtol=1e-15) + + +class TestF: + def test_endpoints(self): + # Compute the pdf at the left endpoint dst.a. + data = [[stats.f, (2, 1), 1.0]] + for _f, _args, _correct in data: + ans = _f.pdf(_f.a, *_args) + + ans = [_f.pdf(_f.a, *_args) for _f, _args, _ in data] + correct = [_correct_ for _f, _args, _correct_ in data] + assert_array_almost_equal(ans, correct) + + def test_f_moments(self): + # n-th moment of F distributions is only finite for n < dfd / 2 + m, v, s, k = stats.f.stats(11, 6.5, moments='mvsk') + assert_(np.isfinite(m)) + assert_(np.isfinite(v)) + assert_(np.isfinite(s)) + assert_(not np.isfinite(k)) + + def test_moments_warnings(self): + # no warnings should be generated for dfd = 2, 4, 6, 8 (div by zero) + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + stats.f.stats(dfn=[11]*4, dfd=[2, 4, 6, 8], moments='mvsk') + + def test_stats_broadcast(self): + dfn = np.array([[3], [11]]) + dfd = np.array([11, 12]) + m, v, s, k = stats.f.stats(dfn=dfn, dfd=dfd, moments='mvsk') + m2 = [dfd / (dfd - 2)]*2 + assert_allclose(m, m2) + v2 = 2 * dfd**2 * (dfn + dfd - 2) / dfn / (dfd - 2)**2 / (dfd - 4) + assert_allclose(v, v2) + s2 = ((2*dfn + dfd - 2) * np.sqrt(8*(dfd - 4)) / + ((dfd - 6) * np.sqrt(dfn*(dfn + dfd - 2)))) + assert_allclose(s, s2) + k2num = 12 * (dfn * (5*dfd - 22) * (dfn + dfd - 2) + + (dfd - 4) * (dfd - 2)**2) + k2den = dfn * (dfd - 6) * (dfd - 8) * (dfn + dfd - 2) + k2 = k2num / k2den + assert_allclose(k, k2) + + +class TestStudentT: + def test_rvgeneric_std(self): + # Regression test for #1191 + assert_array_almost_equal(stats.t.std([5, 6]), [1.29099445, 1.22474487]) + + def test_moments_t(self): + # regression test for #8786 + assert_equal(stats.t.stats(df=1, moments='mvsk'), + (np.inf, np.nan, np.nan, np.nan)) + assert_equal(stats.t.stats(df=1.01, moments='mvsk'), + (0.0, np.inf, np.nan, np.nan)) + assert_equal(stats.t.stats(df=2, moments='mvsk'), + (0.0, np.inf, np.nan, np.nan)) + assert_equal(stats.t.stats(df=2.01, moments='mvsk'), + (0.0, 2.01/(2.01-2.0), np.nan, np.inf)) + assert_equal(stats.t.stats(df=3, moments='sk'), (np.nan, np.inf)) + assert_equal(stats.t.stats(df=3.01, moments='sk'), (0.0, np.inf)) + assert_equal(stats.t.stats(df=4, moments='sk'), (0.0, np.inf)) + assert_equal(stats.t.stats(df=4.01, moments='sk'), (0.0, 6.0/(4.01 - 4.0))) + + def test_t_entropy(self): + df = [1, 2, 25, 100] + # Expected values were computed with mpmath. + expected = [2.5310242469692907, 1.9602792291600821, + 1.459327578078393, 1.4289633653182439] + assert_allclose(stats.t.entropy(df), expected, rtol=1e-13) + + @pytest.mark.parametrize("v, ref", + [(100, 1.4289633653182439), + (1e+100, 1.4189385332046727)]) + def test_t_extreme_entropy(self, v, ref): + # Reference values were calculated with mpmath: + # from mpmath import mp + # mp.dps = 500 + # + # def t_entropy(v): + # v = mp.mpf(v) + # C = (v + mp.one) / 2 + # A = C * (mp.digamma(C) - mp.digamma(v / 2)) + # B = 0.5 * mp.log(v) + mp.log(mp.beta(v / 2, mp.one / 2)) + # h = A + B + # return float(h) + assert_allclose(stats.t.entropy(v), ref, rtol=1e-14) + + @pytest.mark.parametrize("methname", ["pdf", "logpdf", "cdf", + "ppf", "sf", "isf"]) + @pytest.mark.parametrize("df_infmask", [[0, 0], [1, 1], [0, 1], + [[0, 1, 0], [1, 1, 1]], + [[1, 0], [0, 1]], + [[0], [1]]]) + def test_t_inf_df(self, methname, df_infmask): + np.random.seed(0) + df_infmask = np.asarray(df_infmask, dtype=bool) + df = np.random.uniform(0, 10, size=df_infmask.shape) + x = np.random.randn(*df_infmask.shape) + df[df_infmask] = np.inf + t_dist = stats.t(df=df, loc=3, scale=1) + t_dist_ref = stats.t(df=df[~df_infmask], loc=3, scale=1) + norm_dist = stats.norm(loc=3, scale=1) + t_meth = getattr(t_dist, methname) + t_meth_ref = getattr(t_dist_ref, methname) + norm_meth = getattr(norm_dist, methname) + res = t_meth(x) + assert_equal(res[df_infmask], norm_meth(x[df_infmask])) + assert_equal(res[~df_infmask], t_meth_ref(x[~df_infmask])) + + @pytest.mark.parametrize("df_infmask", [[0, 0], [1, 1], [0, 1], + [[0, 1, 0], [1, 1, 1]], + [[1, 0], [0, 1]], + [[0], [1]]]) + def test_t_inf_df_stats_entropy(self, df_infmask): + np.random.seed(0) + df_infmask = np.asarray(df_infmask, dtype=bool) + df = np.random.uniform(0, 10, size=df_infmask.shape) + df[df_infmask] = np.inf + res = stats.t.stats(df=df, loc=3, scale=1, moments='mvsk') + res_ex_inf = stats.norm.stats(loc=3, scale=1, moments='mvsk') + res_ex_noinf = stats.t.stats(df=df[~df_infmask], loc=3, scale=1, + moments='mvsk') + for i in range(4): + assert_equal(res[i][df_infmask], res_ex_inf[i]) + assert_equal(res[i][~df_infmask], res_ex_noinf[i]) + + res = stats.t.entropy(df=df, loc=3, scale=1) + res_ex_inf = stats.norm.entropy(loc=3, scale=1) + res_ex_noinf = stats.t.entropy(df=df[~df_infmask], loc=3, scale=1) + assert_equal(res[df_infmask], res_ex_inf) + assert_equal(res[~df_infmask], res_ex_noinf) + + def test_logpdf_pdf(self): + # reference values were computed via the reference distribution, e.g. + # mp.dps = 500; StudentT(df=df).logpdf(x), StudentT(df=df).pdf(x) + x = [1, 1e3, 10, 1] + df = [1e100, 1e50, 1e20, 1] + logpdf_ref = [-1.4189385332046727, -500000.9189385332, + -50.918938533204674, -1.8378770664093456] + pdf_ref = [0.24197072451914334, 0, + 7.69459862670642e-23, 0.15915494309189535] + assert_allclose(stats.t.logpdf(x, df), logpdf_ref, rtol=1e-14) + assert_allclose(stats.t.pdf(x, df), pdf_ref, rtol=1e-14) + + # Reference values were computed with mpmath, and double-checked with + # Wolfram Alpha. + @pytest.mark.parametrize('x, df, ref', + [(-75.0, 15, -46.76036184546812), + (0, 15, -0.6931471805599453), + (75.0, 15, -4.9230344937641665e-21)]) + def test_logcdf_logsf(self, x, df, ref): + logcdf = stats.t.logcdf(x, df) + assert_allclose(logcdf, ref, rtol=5e-15) + # The reference value is logcdf(x, df) == logsf(-x, df). + logsf = stats.t.logsf(-x, df) + assert_allclose(logsf, ref, rtol=5e-15) + + +class TestRvDiscrete: + def setup_method(self): + np.random.seed(1234) + + def test_rvs(self): + states = [-1, 0, 1, 2, 3, 4] + probability = [0.0, 0.3, 0.4, 0.0, 0.3, 0.0] + samples = 1000 + r = stats.rv_discrete(name='sample', values=(states, probability)) + x = r.rvs(size=samples) + assert isinstance(x, np.ndarray) + + for s, p in zip(states, probability): + assert abs(sum(x == s)/float(samples) - p) < 0.05 + + x = r.rvs() + assert np.issubdtype(type(x), np.integer) + + def test_entropy(self): + # Basic tests of entropy. + pvals = np.array([0.25, 0.45, 0.3]) + p = stats.rv_discrete(values=([0, 1, 2], pvals)) + expected_h = -sum(xlogy(pvals, pvals)) + h = p.entropy() + assert_allclose(h, expected_h) + + p = stats.rv_discrete(values=([0, 1, 2], [1.0, 0, 0])) + h = p.entropy() + assert_equal(h, 0.0) + + def test_pmf(self): + xk = [1, 2, 4] + pk = [0.5, 0.3, 0.2] + rv = stats.rv_discrete(values=(xk, pk)) + + x = [[1., 4.], + [3., 2]] + assert_allclose(rv.pmf(x), + [[0.5, 0.2], + [0., 0.3]], atol=1e-14) + + def test_cdf(self): + xk = [1, 2, 4] + pk = [0.5, 0.3, 0.2] + rv = stats.rv_discrete(values=(xk, pk)) + + x_values = [-2, 1., 1.1, 1.5, 2.0, 3.0, 4, 5] + expected = [0, 0.5, 0.5, 0.5, 0.8, 0.8, 1, 1] + assert_allclose(rv.cdf(x_values), expected, atol=1e-14) + + # also check scalar arguments + assert_allclose([rv.cdf(xx) for xx in x_values], + expected, atol=1e-14) + + def test_ppf(self): + xk = [1, 2, 4] + pk = [0.5, 0.3, 0.2] + rv = stats.rv_discrete(values=(xk, pk)) + + q_values = [0.1, 0.5, 0.6, 0.8, 0.9, 1.] + expected = [1, 1, 2, 2, 4, 4] + assert_allclose(rv.ppf(q_values), expected, atol=1e-14) + + # also check scalar arguments + assert_allclose([rv.ppf(q) for q in q_values], + expected, atol=1e-14) + + def test_cdf_ppf_next(self): + # copied and special cased from test_discrete_basic + vals = ([1, 2, 4, 7, 8], [0.1, 0.2, 0.3, 0.3, 0.1]) + rv = stats.rv_discrete(values=vals) + + assert_array_equal(rv.ppf(rv.cdf(rv.xk[:-1]) + 1e-8), + rv.xk[1:]) + + def test_multidimension(self): + xk = np.arange(12).reshape((3, 4)) + pk = np.array([[0.1, 0.1, 0.15, 0.05], + [0.1, 0.1, 0.05, 0.05], + [0.1, 0.1, 0.05, 0.05]]) + rv = stats.rv_discrete(values=(xk, pk)) + + assert_allclose(rv.expect(), np.sum(rv.xk * rv.pk), atol=1e-14) + + def test_bad_input(self): + xk = [1, 2, 3] + pk = [0.5, 0.5] + assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk))) + + pk = [1, 2, 3] + assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk))) + + xk = [1, 2, 3] + pk = [0.5, 1.2, -0.7] + assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk))) + + xk = [1, 2, 3, 4, 5] + pk = [0.3, 0.3, 0.3, 0.3, -0.2] + assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk))) + + xk = [1, 1] + pk = [0.5, 0.5] + assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk))) + + def test_shape_rv_sample(self): + # tests added for gh-9565 + + # mismatch of 2d inputs + xk, pk = np.arange(4).reshape((2, 2)), np.full((2, 3), 1/6) + assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk))) + + # same number of elements, but shapes not compatible + xk, pk = np.arange(6).reshape((3, 2)), np.full((2, 3), 1/6) + assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk))) + + # same shapes => no error + xk, pk = np.arange(6).reshape((3, 2)), np.full((3, 2), 1/6) + assert_equal(stats.rv_discrete(values=(xk, pk)).pmf(0), 1/6) + + def test_expect1(self): + xk = [1, 2, 4, 6, 7, 11] + pk = [0.1, 0.2, 0.2, 0.2, 0.2, 0.1] + rv = stats.rv_discrete(values=(xk, pk)) + + assert_allclose(rv.expect(), np.sum(rv.xk * rv.pk), atol=1e-14) + + def test_expect2(self): + # rv_sample should override _expect. Bug report from + # https://stackoverflow.com/questions/63199792 + y = [200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, + 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0, + 1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, + 2700.0, 2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, + 3500.0, 3600.0, 3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, + 4300.0, 4400.0, 4500.0, 4600.0, 4700.0, 4800.0] + + py = [0.0004, 0.0, 0.0033, 0.006500000000000001, 0.0, 0.0, + 0.004399999999999999, 0.6862, 0.0, 0.0, 0.0, + 0.00019999999999997797, 0.0006000000000000449, + 0.024499999999999966, 0.006400000000000072, + 0.0043999999999999595, 0.019499999999999962, + 0.03770000000000007, 0.01759999999999995, 0.015199999999999991, + 0.018100000000000005, 0.04500000000000004, 0.0025999999999999357, + 0.0, 0.0041000000000001036, 0.005999999999999894, + 0.0042000000000000925, 0.0050000000000000044, + 0.0041999999999999815, 0.0004999999999999449, + 0.009199999999999986, 0.008200000000000096, + 0.0, 0.0, 0.0046999999999999265, 0.0019000000000000128, + 0.0006000000000000449, 0.02510000000000001, 0.0, + 0.007199999999999984, 0.0, 0.012699999999999934, 0.0, 0.0, + 0.008199999999999985, 0.005600000000000049, 0.0] + + rv = stats.rv_discrete(values=(y, py)) + + # check the mean + assert_allclose(rv.expect(), rv.mean(), atol=1e-14) + assert_allclose(rv.expect(), + sum(v * w for v, w in zip(y, py)), atol=1e-14) + + # also check the second moment + assert_allclose(rv.expect(lambda x: x**2), + sum(v**2 * w for v, w in zip(y, py)), atol=1e-14) + + +class TestSkewCauchy: + def test_cauchy(self): + x = np.linspace(-5, 5, 100) + assert_array_almost_equal(stats.skewcauchy.pdf(x, a=0), + stats.cauchy.pdf(x)) + assert_array_almost_equal(stats.skewcauchy.cdf(x, a=0), + stats.cauchy.cdf(x)) + assert_array_almost_equal(stats.skewcauchy.ppf(x, a=0), + stats.cauchy.ppf(x)) + + def test_skewcauchy_R(self): + # options(digits=16) + # library(sgt) + # # lmbda, x contain the values generated for a, x below + # lmbda <- c(0.0976270078546495, 0.430378732744839, 0.2055267521432877, + # 0.0897663659937937, -0.15269040132219, 0.2917882261333122, + # -0.12482557747462, 0.7835460015641595, 0.9273255210020589, + # -0.2331169623484446) + # x <- c(2.917250380826646, 0.2889491975290444, 0.6804456109393229, + # 4.25596638292661, -4.289639418021131, -4.1287070029845925, + # -4.797816025596743, 3.32619845547938, 2.7815675094985046, + # 3.700121482468191) + # pdf = dsgt(x, mu=0, lambda=lambda, sigma=1, q=1/2, mean.cent=FALSE, + # var.adj = sqrt(2)) + # cdf = psgt(x, mu=0, lambda=lambda, sigma=1, q=1/2, mean.cent=FALSE, + # var.adj = sqrt(2)) + # qsgt(cdf, mu=0, lambda=lambda, sigma=1, q=1/2, mean.cent=FALSE, + # var.adj = sqrt(2)) + + np.random.seed(0) + a = np.random.rand(10) * 2 - 1 + x = np.random.rand(10) * 10 - 5 + pdf = [0.039473975217333909, 0.305829714049903223, 0.24140158118994162, + 0.019585772402693054, 0.021436553695989482, 0.00909817103867518, + 0.01658423410016873, 0.071083288030394126, 0.103250045941454524, + 0.013110230778426242] + cdf = [0.87426677718213752, 0.37556468910780882, 0.59442096496538066, + 0.91304659850890202, 0.09631964100300605, 0.03829624330921733, + 0.08245240578402535, 0.72057062945510386, 0.62826415852515449, + 0.95011308463898292] + assert_allclose(stats.skewcauchy.pdf(x, a), pdf) + assert_allclose(stats.skewcauchy.cdf(x, a), cdf) + assert_allclose(stats.skewcauchy.ppf(cdf, a), x) + + +class TestJFSkewT: + def test_compare_t(self): + # Verify that jf_skew_t with a=b recovers the t distribution with 2a + # degrees of freedom + a = b = 5 + df = a * 2 + x = [-1.0, 0.0, 1.0, 2.0] + q = [0.0, 0.1, 0.25, 0.75, 0.90, 1.0] + + jf = stats.jf_skew_t(a, b) + t = stats.t(df) + + assert_allclose(jf.pdf(x), t.pdf(x)) + assert_allclose(jf.cdf(x), t.cdf(x)) + assert_allclose(jf.ppf(q), t.ppf(q)) + assert_allclose(jf.stats('mvsk'), t.stats('mvsk')) + + @pytest.fixture + def gamlss_pdf_data(self): + """Sample data points computed using the `ST5` distribution from the + GAMLSS package in R. The pdf has been calculated for (a,b)=(2,3), + (a,b)=(8,4), and (a,b)=(12,13) for x in `np.linspace(-10, 10, 41)`. + + N.B. the `ST5` distribution in R uses an alternative parameterization + in terms of nu and tau, where: + - nu = (a - b) / (a * b * (a + b)) ** 0.5 + - tau = 2 / (a + b) + """ + data = np.load( + Path(__file__).parent / "data/jf_skew_t_gamlss_pdf_data.npy" + ) + return np.rec.fromarrays(data, names="x,pdf,a,b") + + @pytest.mark.parametrize("a,b", [(2, 3), (8, 4), (12, 13)]) + def test_compare_with_gamlss_r(self, gamlss_pdf_data, a, b): + """Compare the pdf with a table of reference values. The table of + reference values was produced using R, where the Jones and Faddy skew + t distribution is available in the GAMLSS package as `ST5`. + """ + data = gamlss_pdf_data[ + (gamlss_pdf_data["a"] == a) & (gamlss_pdf_data["b"] == b) + ] + x, pdf = data["x"], data["pdf"] + assert_allclose(pdf, stats.jf_skew_t(a, b).pdf(x), rtol=1e-12) + + +# Test data for TestSkewNorm.test_noncentral_moments() +# The expected noncentral moments were computed by Wolfram Alpha. +# In Wolfram Alpha, enter +# SkewNormalDistribution[0, 1, a] moment +# with `a` replaced by the desired shape parameter. In the results, there +# should be a table of the first four moments. Click on "More" to get more +# moments. The expected moments start with the first moment (order = 1). +_skewnorm_noncentral_moments = [ + (2, [2*np.sqrt(2/(5*np.pi)), + 1, + 22/5*np.sqrt(2/(5*np.pi)), + 3, + 446/25*np.sqrt(2/(5*np.pi)), + 15, + 2682/25*np.sqrt(2/(5*np.pi)), + 105, + 107322/125*np.sqrt(2/(5*np.pi))]), + (0.1, [np.sqrt(2/(101*np.pi)), + 1, + 302/101*np.sqrt(2/(101*np.pi)), + 3, + (152008*np.sqrt(2/(101*np.pi)))/10201, + 15, + (107116848*np.sqrt(2/(101*np.pi)))/1030301, + 105, + (97050413184*np.sqrt(2/(101*np.pi)))/104060401]), + (-3, [-3/np.sqrt(5*np.pi), + 1, + -63/(10*np.sqrt(5*np.pi)), + 3, + -2529/(100*np.sqrt(5*np.pi)), + 15, + -30357/(200*np.sqrt(5*np.pi)), + 105, + -2428623/(2000*np.sqrt(5*np.pi)), + 945, + -242862867/(20000*np.sqrt(5*np.pi)), + 10395, + -29143550277/(200000*np.sqrt(5*np.pi)), + 135135]), +] + + +class TestSkewNorm: + def setup_method(self): + self.rng = check_random_state(1234) + + def test_normal(self): + # When the skewness is 0 the distribution is normal + x = np.linspace(-5, 5, 100) + assert_array_almost_equal(stats.skewnorm.pdf(x, a=0), + stats.norm.pdf(x)) + + def test_rvs(self): + shape = (3, 4, 5) + x = stats.skewnorm.rvs(a=0.75, size=shape, random_state=self.rng) + assert_equal(shape, x.shape) + + x = stats.skewnorm.rvs(a=-3, size=shape, random_state=self.rng) + assert_equal(shape, x.shape) + + def test_moments(self): + X = stats.skewnorm.rvs(a=4, size=int(1e6), loc=5, scale=2, + random_state=self.rng) + expected = [np.mean(X), np.var(X), stats.skew(X), stats.kurtosis(X)] + computed = stats.skewnorm.stats(a=4, loc=5, scale=2, moments='mvsk') + assert_array_almost_equal(computed, expected, decimal=2) + + X = stats.skewnorm.rvs(a=-4, size=int(1e6), loc=5, scale=2, + random_state=self.rng) + expected = [np.mean(X), np.var(X), stats.skew(X), stats.kurtosis(X)] + computed = stats.skewnorm.stats(a=-4, loc=5, scale=2, moments='mvsk') + assert_array_almost_equal(computed, expected, decimal=2) + + def test_pdf_large_x(self): + # Triples are [x, a, logpdf(x, a)]. These values were computed + # using Log[PDF[SkewNormalDistribution[0, 1, a], x]] in Wolfram Alpha. + logpdfvals = [ + [40, -1, -1604.834233366398515598970], + [40, -1/2, -1004.142946723741991369168], + [40, 0, -800.9189385332046727417803], + [40, 1/2, -800.2257913526447274323631], + [-40, -1/2, -800.2257913526447274323631], + [-2, 1e7, -2.000000000000199559727173e14], + [2, -1e7, -2.000000000000199559727173e14], + ] + for x, a, logpdfval in logpdfvals: + logp = stats.skewnorm.logpdf(x, a) + assert_allclose(logp, logpdfval, rtol=1e-8) + + def test_cdf_large_x(self): + # Regression test for gh-7746. + # The x values are large enough that the closest 64 bit floating + # point representation of the exact CDF is 1.0. + p = stats.skewnorm.cdf([10, 20, 30], -1) + assert_allclose(p, np.ones(3), rtol=1e-14) + p = stats.skewnorm.cdf(25, 2.5) + assert_allclose(p, 1.0, rtol=1e-14) + + def test_cdf_sf_small_values(self): + # Triples are [x, a, cdf(x, a)]. These values were computed + # using CDF[SkewNormalDistribution[0, 1, a], x] in Wolfram Alpha. + cdfvals = [ + [-8, 1, 3.870035046664392611e-31], + [-4, 2, 8.1298399188811398e-21], + [-2, 5, 1.55326826787106273e-26], + [-9, -1, 2.257176811907681295e-19], + [-10, -4, 1.523970604832105213e-23], + ] + for x, a, cdfval in cdfvals: + p = stats.skewnorm.cdf(x, a) + assert_allclose(p, cdfval, rtol=1e-8) + # For the skew normal distribution, sf(-x, -a) = cdf(x, a). + p = stats.skewnorm.sf(-x, -a) + assert_allclose(p, cdfval, rtol=1e-8) + + @pytest.mark.parametrize('a, moments', _skewnorm_noncentral_moments) + def test_noncentral_moments(self, a, moments): + for order, expected in enumerate(moments, start=1): + mom = stats.skewnorm.moment(order, a) + assert_allclose(mom, expected, rtol=1e-14) + + def test_fit(self): + rng = np.random.default_rng(4609813989115202851) + + a, loc, scale = -2, 3.5, 0.5 # arbitrary, valid parameters + dist = stats.skewnorm(a, loc, scale) + rvs = dist.rvs(size=100, random_state=rng) + + # test that MLE still honors guesses and fixed parameters + a2, loc2, scale2 = stats.skewnorm.fit(rvs, -1.5, floc=3) + a3, loc3, scale3 = stats.skewnorm.fit(rvs, -1.6, floc=3) + assert loc2 == loc3 == 3 # fixed parameter is respected + assert a2 != a3 # different guess -> (slightly) different outcome + # quality of fit is tested elsewhere + + # test that MoM honors fixed parameters, accepts (but ignores) guesses + a4, loc4, scale4 = stats.skewnorm.fit(rvs, 3, fscale=3, method='mm') + assert scale4 == 3 + # because scale was fixed, only the mean and skewness will be matched + dist4 = stats.skewnorm(a4, loc4, scale4) + res = dist4.stats(moments='ms') + ref = np.mean(rvs), stats.skew(rvs) + assert_allclose(res, ref) + + # Test behavior when skew of data is beyond maximum of skewnorm + rvs2 = stats.pareto.rvs(1, size=100, random_state=rng) + + # MLE still works + res = stats.skewnorm.fit(rvs2) + assert np.all(np.isfinite(res)) + + # MoM fits variance and skewness + a5, loc5, scale5 = stats.skewnorm.fit(rvs2, method='mm') + assert np.isinf(a5) + # distribution infrastructure doesn't allow infinite shape parameters + # into _stats; it just bypasses it and produces NaNs. Calculate + # moments manually. + m, v = np.mean(rvs2), np.var(rvs2) + assert_allclose(m, loc5 + scale5 * np.sqrt(2/np.pi)) + assert_allclose(v, scale5**2 * (1 - 2 / np.pi)) + + # test that MLE and MoM behave as expected under sign changes + a6p, loc6p, scale6p = stats.skewnorm.fit(rvs, method='mle') + a6m, loc6m, scale6m = stats.skewnorm.fit(-rvs, method='mle') + assert_allclose([a6m, loc6m, scale6m], [-a6p, -loc6p, scale6p]) + a7p, loc7p, scale7p = stats.skewnorm.fit(rvs, method='mm') + a7m, loc7m, scale7m = stats.skewnorm.fit(-rvs, method='mm') + assert_allclose([a7m, loc7m, scale7m], [-a7p, -loc7p, scale7p]) + + def test_fit_gh19332(self): + # When the skewness of the data was high, `skewnorm.fit` fell back on + # generic `fit` behavior with a bad guess of the skewness parameter. + # Test that this is improved; `skewnorm.fit` is now better at finding + # the global optimum when the sample is highly skewed. See gh-19332. + x = np.array([-5, -1, 1 / 100_000] + 12 * [1] + [5]) + + params = stats.skewnorm.fit(x) + res = stats.skewnorm.nnlf(params, x) + + # Compare overridden fit against generic fit. + # res should be about 32.01, and generic fit is worse at 32.64. + # In case the generic fit improves, remove this assertion (see gh-19333). + params_super = stats.skewnorm.fit(x, superfit=True) + ref = stats.skewnorm.nnlf(params_super, x) + assert res < ref - 0.5 + + # Compare overridden fit against stats.fit + rng = np.random.default_rng(9842356982345693637) + bounds = {'a': (-5, 5), 'loc': (-10, 10), 'scale': (1e-16, 10)} + + def optimizer(fun, bounds): + return differential_evolution(fun, bounds, rng=rng) + + fit_result = stats.fit(stats.skewnorm, x, bounds, optimizer=optimizer) + np.testing.assert_allclose(params, fit_result.params, rtol=1e-4) + + def test_ppf(self): + # gh-20124 reported that Boost's ppf was wrong for high skewness + # Reference value was calculated using + # N[InverseCDF[SkewNormalDistribution[0, 1, 500], 1/100], 14] in Wolfram Alpha. + assert_allclose(stats.skewnorm.ppf(0.01, 500), 0.012533469508013, rtol=1e-13) + + +class TestExpon: + def test_zero(self): + assert_equal(stats.expon.pdf(0), 1) + + def test_tail(self): # Regression test for ticket 807 + assert_equal(stats.expon.cdf(1e-18), 1e-18) + assert_equal(stats.expon.isf(stats.expon.sf(40)), 40) + + def test_nan_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan]) + assert_raises(ValueError, stats.expon.fit, x) + + def test_inf_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf]) + assert_raises(ValueError, stats.expon.fit, x) + + +class TestNorm: + def test_nan_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan]) + assert_raises(ValueError, stats.norm.fit, x) + + def test_inf_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf]) + assert_raises(ValueError, stats.norm.fit, x) + + def test_bad_keyword_arg(self): + x = [1, 2, 3] + assert_raises(TypeError, stats.norm.fit, x, plate="shrimp") + + @pytest.mark.parametrize('loc', [0, 1]) + def test_delta_cdf(self, loc): + # The expected value is computed with mpmath: + # >>> import mpmath + # >>> mpmath.mp.dps = 60 + # >>> float(mpmath.ncdf(12) - mpmath.ncdf(11)) + # 1.910641809677555e-28 + expected = 1.910641809677555e-28 + delta = stats.norm._delta_cdf(11+loc, 12+loc, loc=loc) + assert_allclose(delta, expected, rtol=1e-13) + delta = stats.norm._delta_cdf(-(12+loc), -(11+loc), loc=-loc) + assert_allclose(delta, expected, rtol=1e-13) + + +class TestUniform: + """gh-10300""" + def test_nan_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan]) + assert_raises(ValueError, stats.uniform.fit, x) + + def test_inf_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf]) + assert_raises(ValueError, stats.uniform.fit, x) + + +class TestExponNorm: + def test_moments(self): + # Some moment test cases based on non-loc/scaled formula + def get_moms(lam, sig, mu): + # See wikipedia for these formulae + # where it is listed as an exponentially modified gaussian + opK2 = 1.0 + 1 / (lam*sig)**2 + exp_skew = 2 / (lam * sig)**3 * opK2**(-1.5) + exp_kurt = 6.0 * (1 + (lam * sig)**2)**(-2) + return [mu + 1/lam, sig*sig + 1.0/(lam*lam), exp_skew, exp_kurt] + + mu, sig, lam = 0, 1, 1 + K = 1.0 / (lam * sig) + sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk') + assert_almost_equal(sts, get_moms(lam, sig, mu)) + mu, sig, lam = -3, 2, 0.1 + K = 1.0 / (lam * sig) + sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk') + assert_almost_equal(sts, get_moms(lam, sig, mu)) + mu, sig, lam = 0, 3, 1 + K = 1.0 / (lam * sig) + sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk') + assert_almost_equal(sts, get_moms(lam, sig, mu)) + mu, sig, lam = -5, 11, 3.5 + K = 1.0 / (lam * sig) + sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk') + assert_almost_equal(sts, get_moms(lam, sig, mu)) + + def test_nan_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan]) + assert_raises(ValueError, stats.exponnorm.fit, x, floc=0, fscale=1) + + def test_inf_raises_error(self): + # see gh-issue 10300 + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf]) + assert_raises(ValueError, stats.exponnorm.fit, x, floc=0, fscale=1) + + def test_extremes_x(self): + # Test for extreme values against overflows + assert_almost_equal(stats.exponnorm.pdf(-900, 1), 0.0) + assert_almost_equal(stats.exponnorm.pdf(+900, 1), 0.0) + assert_almost_equal(stats.exponnorm.pdf(-900, 0.01), 0.0) + assert_almost_equal(stats.exponnorm.pdf(+900, 0.01), 0.0) + + # Expected values for the PDF were computed with mpmath, with + # the following function, and with mpmath.mp.dps = 50. + # + # def exponnorm_stdpdf(x, K): + # x = mpmath.mpf(x) + # K = mpmath.mpf(K) + # t1 = mpmath.exp(1/(2*K**2) - x/K) + # erfcarg = -(x - 1/K)/mpmath.sqrt(2) + # t2 = mpmath.erfc(erfcarg) + # return t1 * t2 / (2*K) + # + @pytest.mark.parametrize('x, K, expected', + [(20, 0.01, 6.90010764753618e-88), + (1, 0.01, 0.24438994313247364), + (-1, 0.01, 0.23955149623472075), + (-20, 0.01, 4.6004708690125477e-88), + (10, 1, 7.48518298877006e-05), + (10, 10000, 9.990005048283775e-05)]) + def test_std_pdf(self, x, K, expected): + assert_allclose(stats.exponnorm.pdf(x, K), expected, rtol=5e-12) + + # Expected values for the CDF were computed with mpmath using + # the following function and with mpmath.mp.dps = 60: + # + # def mp_exponnorm_cdf(x, K, loc=0, scale=1): + # x = mpmath.mpf(x) + # K = mpmath.mpf(K) + # loc = mpmath.mpf(loc) + # scale = mpmath.mpf(scale) + # z = (x - loc)/scale + # return (mpmath.ncdf(z) + # - mpmath.exp((1/(2*K) - z)/K)*mpmath.ncdf(z - 1/K)) + # + @pytest.mark.parametrize('x, K, scale, expected', + [[0, 0.01, 1, 0.4960109760186432], + [-5, 0.005, 1, 2.7939945412195734e-07], + [-1e4, 0.01, 100, 0.0], + [-1e4, 0.01, 1000, 6.920401854427357e-24], + [5, 0.001, 1, 0.9999997118542392]]) + def test_cdf_small_K(self, x, K, scale, expected): + p = stats.exponnorm.cdf(x, K, scale=scale) + if expected == 0.0: + assert p == 0.0 + else: + assert_allclose(p, expected, rtol=1e-13) + + # Expected values for the SF were computed with mpmath using + # the following function and with mpmath.mp.dps = 60: + # + # def mp_exponnorm_sf(x, K, loc=0, scale=1): + # x = mpmath.mpf(x) + # K = mpmath.mpf(K) + # loc = mpmath.mpf(loc) + # scale = mpmath.mpf(scale) + # z = (x - loc)/scale + # return (mpmath.ncdf(-z) + # + mpmath.exp((1/(2*K) - z)/K)*mpmath.ncdf(z - 1/K)) + # + @pytest.mark.parametrize('x, K, scale, expected', + [[10, 0.01, 1, 8.474702916146657e-24], + [2, 0.005, 1, 0.02302280664231312], + [5, 0.005, 0.5, 8.024820681931086e-24], + [10, 0.005, 0.5, 3.0603340062892486e-89], + [20, 0.005, 0.5, 0.0], + [-3, 0.001, 1, 0.9986545205566117]]) + def test_sf_small_K(self, x, K, scale, expected): + p = stats.exponnorm.sf(x, K, scale=scale) + if expected == 0.0: + assert p == 0.0 + else: + assert_allclose(p, expected, rtol=5e-13) + + +class TestGenExpon: + def test_pdf_unity_area(self): + from scipy.integrate import simpson + # PDF should integrate to one + p = stats.genexpon.pdf(np.arange(0, 10, 0.01), 0.5, 0.5, 2.0) + assert_almost_equal(simpson(p, dx=0.01), 1, 1) + + def test_cdf_bounds(self): + # CDF should always be positive + cdf = stats.genexpon.cdf(np.arange(0, 10, 0.01), 0.5, 0.5, 2.0) + assert np.all((0 <= cdf) & (cdf <= 1)) + + # The values of p in the following data were computed with mpmath. + # E.g. the script + # from mpmath import mp + # mp.dps = 80 + # x = mp.mpf('15.0') + # a = mp.mpf('1.0') + # b = mp.mpf('2.0') + # c = mp.mpf('1.5') + # print(float(mp.exp((-a-b)*x + (b/c)*-mp.expm1(-c*x)))) + # prints + # 1.0859444834514553e-19 + @pytest.mark.parametrize('x, p, a, b, c', + [(15, 1.0859444834514553e-19, 1, 2, 1.5), + (0.25, 0.7609068232534623, 0.5, 2, 3), + (0.25, 0.09026661397565876, 9.5, 2, 0.5), + (0.01, 0.9753038265071597, 2.5, 0.25, 0.5), + (3.25, 0.0001962824553094492, 2.5, 0.25, 0.5), + (0.125, 0.9508674287164001, 0.25, 5, 0.5)]) + def test_sf_isf(self, x, p, a, b, c): + sf = stats.genexpon.sf(x, a, b, c) + assert_allclose(sf, p, rtol=2e-14) + isf = stats.genexpon.isf(p, a, b, c) + assert_allclose(isf, x, rtol=2e-14) + + # The values of p in the following data were computed with mpmath. + @pytest.mark.parametrize('x, p, a, b, c', + [(0.25, 0.2390931767465377, 0.5, 2, 3), + (0.25, 0.9097333860243412, 9.5, 2, 0.5), + (0.01, 0.0246961734928403, 2.5, 0.25, 0.5), + (3.25, 0.9998037175446906, 2.5, 0.25, 0.5), + (0.125, 0.04913257128359998, 0.25, 5, 0.5)]) + def test_cdf_ppf(self, x, p, a, b, c): + cdf = stats.genexpon.cdf(x, a, b, c) + assert_allclose(cdf, p, rtol=2e-14) + ppf = stats.genexpon.ppf(p, a, b, c) + assert_allclose(ppf, x, rtol=2e-14) + + +class TestTruncexpon: + + def test_sf_isf(self): + # reference values were computed via the reference distribution, e.g. + # mp.dps = 50; TruncExpon(b=b).sf(x) + b = [20, 100] + x = [19.999999, 99.999999] + ref = [2.0611546593828472e-15, 3.7200778266671455e-50] + assert_allclose(stats.truncexpon.sf(x, b), ref, rtol=1.5e-10) + assert_allclose(stats.truncexpon.isf(ref, b), x, rtol=1e-12) + + +class TestExponpow: + def test_tail(self): + assert_almost_equal(stats.exponpow.cdf(1e-10, 2.), 1e-20) + assert_almost_equal(stats.exponpow.isf(stats.exponpow.sf(5, .8), .8), + 5) + + +class TestSkellam: + def test_pmf(self): + # comparison to R + k = np.arange(-10, 15) + mu1, mu2 = 10, 5 + skpmfR = np.array( + [4.2254582961926893e-005, 1.1404838449648488e-004, + 2.8979625801752660e-004, 6.9177078182101231e-004, + 1.5480716105844708e-003, 3.2412274963433889e-003, + 6.3373707175123292e-003, 1.1552351566696643e-002, + 1.9606152375042644e-002, 3.0947164083410337e-002, + 4.5401737566767360e-002, 6.1894328166820688e-002, + 7.8424609500170578e-002, 9.2418812533573133e-002, + 1.0139793148019728e-001, 1.0371927988298846e-001, + 9.9076583077406091e-002, 8.8546660073089561e-002, + 7.4187842052486810e-002, 5.8392772862200251e-002, + 4.3268692953013159e-002, 3.0248159818374226e-002, + 1.9991434305603021e-002, 1.2516877303301180e-002, + 7.4389876226229707e-003]) + + assert_almost_equal(stats.skellam.pmf(k, mu1, mu2), skpmfR, decimal=15) + + def test_cdf(self): + # comparison to R, only 5 decimals + k = np.arange(-10, 15) + mu1, mu2 = 10, 5 + skcdfR = np.array( + [6.4061475386192104e-005, 1.7810985988267694e-004, + 4.6790611790020336e-004, 1.1596768997212152e-003, + 2.7077485103056847e-003, 5.9489760066490718e-003, + 1.2286346724161398e-002, 2.3838698290858034e-002, + 4.3444850665900668e-002, 7.4392014749310995e-002, + 1.1979375231607835e-001, 1.8168808048289900e-001, + 2.6011268998306952e-001, 3.5253150251664261e-001, + 4.5392943399683988e-001, 5.5764871387982828e-001, + 6.5672529695723436e-001, 7.4527195703032389e-001, + 8.1945979908281064e-001, 8.7785257194501087e-001, + 9.2112126489802404e-001, 9.5136942471639818e-001, + 9.7136085902200120e-001, 9.8387773632530240e-001, + 9.9131672394792536e-001]) + + assert_almost_equal(stats.skellam.cdf(k, mu1, mu2), skcdfR, decimal=5) + + def test_extreme_mu2(self): + # check that crash reported by gh-17916 large mu2 is resolved + x, mu1, mu2 = 0, 1, 4820232647677555.0 + assert_allclose(stats.skellam.pmf(x, mu1, mu2), 0, atol=1e-16) + assert_allclose(stats.skellam.cdf(x, mu1, mu2), 1, atol=1e-16) + + +class TestLognorm: + def test_pdf(self): + # Regression test for Ticket #1471: avoid nan with 0/0 situation + # Also make sure there are no warnings at x=0, cf gh-5202 + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + pdf = stats.lognorm.pdf([0, 0.5, 1], 1) + assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) + + def test_logcdf(self): + # Regression test for gh-5940: sf et al would underflow too early + x2, mu, sigma = 201.68, 195, 0.149 + assert_allclose(stats.lognorm.sf(x2-mu, s=sigma), + stats.norm.sf(np.log(x2-mu)/sigma)) + assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma), + stats.norm.logsf(np.log(x2-mu)/sigma)) + + @pytest.fixture(scope='function') + def rng(self): + return np.random.default_rng(1234) + + @pytest.mark.parametrize("rvs_shape", [.1, 2]) + @pytest.mark.parametrize("rvs_loc", [-2, 0, 2]) + @pytest.mark.parametrize("rvs_scale", [.2, 1, 5]) + @pytest.mark.parametrize('fix_shape, fix_loc, fix_scale', + [e for e in product((False, True), repeat=3) + if False in e]) + @np.errstate(invalid="ignore") + def test_fit_MLE_comp_optimizer(self, rvs_shape, rvs_loc, rvs_scale, + fix_shape, fix_loc, fix_scale, rng): + data = stats.lognorm.rvs(size=100, s=rvs_shape, scale=rvs_scale, + loc=rvs_loc, random_state=rng) + + kwds = {} + if fix_shape: + kwds['f0'] = rvs_shape + if fix_loc: + kwds['floc'] = rvs_loc + if fix_scale: + kwds['fscale'] = rvs_scale + + # Numerical result may equal analytical result if some code path + # of the analytical routine makes use of numerical optimization. + _assert_less_or_close_loglike(stats.lognorm, data, **kwds, + maybe_identical=True) + + def test_isf(self): + # reference values were computed via the reference distribution, e.g. + # mp.dps = 100; + # LogNormal(s=s).isf(q=0.1, guess=0) + # LogNormal(s=s).isf(q=2e-10, guess=100) + s = 0.954 + q = [0.1, 2e-10, 5e-20, 6e-40] + ref = [3.3960065375794937, 390.07632793595974, 5830.5020828128445, + 287872.84087457904] + assert_allclose(stats.lognorm.isf(q, s), ref, rtol=1e-14) + + +class TestBeta: + def test_logpdf(self): + # Regression test for Ticket #1326: avoid nan with 0*log(0) situation + logpdf = stats.beta.logpdf(0, 1, 0.5) + assert_almost_equal(logpdf, -0.69314718056) + logpdf = stats.beta.logpdf(0, 0.5, 1) + assert_almost_equal(logpdf, np.inf) + + def test_logpdf_ticket_1866(self): + alpha, beta = 267, 1472 + x = np.array([0.2, 0.5, 0.6]) + b = stats.beta(alpha, beta) + assert_allclose(b.logpdf(x).sum(), -1201.699061824062) + assert_allclose(b.pdf(x), np.exp(b.logpdf(x))) + + def test_fit_bad_keyword_args(self): + x = [0.1, 0.5, 0.6] + assert_raises(TypeError, stats.beta.fit, x, floc=0, fscale=1, + plate="shrimp") + + def test_fit_duplicated_fixed_parameter(self): + # At most one of 'f0', 'fa' or 'fix_a' can be given to the fit method. + # More than one raises a ValueError. + x = [0.1, 0.5, 0.6] + assert_raises(ValueError, stats.beta.fit, x, fa=0.5, fix_a=0.5) + + @pytest.mark.skipif(MACOS_INTEL, reason="Overflow, see gh-14901") + def test_issue_12635(self): + # Confirm that Boost's beta distribution resolves gh-12635. + # Check against R: + # options(digits=16) + # p = 0.9999999999997369 + # a = 75.0 + # b = 66334470.0 + # print(qbeta(p, a, b)) + p, a, b = 0.9999999999997369, 75.0, 66334470.0 + assert_allclose(stats.beta.ppf(p, a, b), 2.343620802982393e-06) + + @pytest.mark.skipif(MACOS_INTEL, reason="Overflow, see gh-14901") + def test_issue_12794(self): + # Confirm that Boost's beta distribution resolves gh-12794. + # Check against R. + # options(digits=16) + # p = 1e-11 + # count_list = c(10,100,1000) + # print(qbeta(1-p, count_list + 1, 100000 - count_list)) + inv_R = np.array([0.0004944464889611935, + 0.0018360586912635726, + 0.0122663919942518351]) + count_list = np.array([10, 100, 1000]) + p = 1e-11 + inv = stats.beta.isf(p, count_list + 1, 100000 - count_list) + assert_allclose(inv, inv_R) + res = stats.beta.sf(inv, count_list + 1, 100000 - count_list) + assert_allclose(res, p) + + @pytest.mark.skipif(MACOS_INTEL, reason="Overflow, see gh-14901") + def test_issue_12796(self): + # Confirm that Boost's beta distribution succeeds in the case + # of gh-12796 + alpha_2 = 5e-6 + count_ = np.arange(1, 20) + nobs = 100000 + q, a, b = 1 - alpha_2, count_ + 1, nobs - count_ + inv = stats.beta.ppf(q, a, b) + res = stats.beta.cdf(inv, a, b) + assert_allclose(res, 1 - alpha_2) + + def test_endpoints(self): + # Confirm that boost's beta distribution returns inf at x=1 + # when b<1 + a, b = 1, 0.5 + assert_equal(stats.beta.pdf(1, a, b), np.inf) + + # Confirm that boost's beta distribution returns inf at x=0 + # when a<1 + a, b = 0.2, 3 + assert_equal(stats.beta.pdf(0, a, b), np.inf) + + # Confirm that boost's beta distribution returns 5 at x=0 + # when a=1, b=5 + a, b = 1, 5 + assert_equal(stats.beta.pdf(0, a, b), 5) + assert_equal(stats.beta.pdf(1e-310, a, b), 5) + + # Confirm that boost's beta distribution returns 5 at x=1 + # when a=5, b=1 + a, b = 5, 1 + assert_equal(stats.beta.pdf(1, a, b), 5) + assert_equal(stats.beta.pdf(1-1e-310, a, b), 5) + + @pytest.mark.xfail(IS_PYPY, reason="Does not convert boost warning") + def test_boost_eval_issue_14606(self): + q, a, b = 0.995, 1.0e11, 1.0e13 + with pytest.warns(RuntimeWarning): + stats.beta.ppf(q, a, b) + + @pytest.mark.parametrize('method', [stats.beta.ppf, stats.beta.isf]) + @pytest.mark.parametrize('a, b', [(1e-310, 12.5), (12.5, 1e-310)]) + def test_beta_ppf_with_subnormal_a_b(self, method, a, b): + # Regression test for gh-17444: beta.ppf(p, a, b) and beta.isf(p, a, b) + # would result in a segmentation fault if either a or b was subnormal. + p = 0.9 + # Depending on the version of Boost that we have vendored and + # our setting of the Boost double promotion policy, the call + # `stats.beta.ppf(p, a, b)` might raise an OverflowError or + # return a value. We'll accept either behavior (and not care about + # the value), because our goal here is to verify that the call does + # not trigger a segmentation fault. + try: + method(p, a, b) + except OverflowError: + # The OverflowError exception occurs with Boost 1.80 or earlier + # when Boost's double promotion policy is false; see + # https://github.com/boostorg/math/issues/882 + # and + # https://github.com/boostorg/math/pull/883 + # Once we have vendored the fixed version of Boost, we can drop + # this try-except wrapper and just call the function. + pass + + # Reference values computed with mpmath. + @pytest.mark.parametrize('x, a, b, ref', + [(0.999, 1.5, 2.5, -6.439838145196121e-08), + (2e-9, 3.25, 2.5, -63.13030939685114)]) + def test_logcdf(self, x, a, b, ref): + logcdf = stats.beta.logcdf(x, a, b) + assert_allclose(logcdf, ref, rtol=5e-15) + + # Reference values computed with mpmath. + @pytest.mark.parametrize('x, a, b, ref', + [(2e-9, 1.5, 2.5, -3.0368535131140806e-13), + (0.998, 3.25, 2.5, -13.309796070871489)]) + def test_logsf(self, x, a, b, ref): + logsf = stats.beta.logsf(x, a, b) + assert_allclose(logsf, ref, 5e-15) + + # entropy accuracy was confirmed using the following mpmath function + # from mpmath import mp + # mp.dps = 50 + # def beta_entropy_mpmath(a, b): + # a = mp.mpf(a) + # b = mp.mpf(b) + # entropy = mp.log(mp.beta(a, b)) - (a - 1) * mp.digamma(a) -\ + # (b - 1) * mp.digamma(b) + (a + b -2) * mp.digamma(a + b) + # return float(entropy) + + @pytest.mark.parametrize('a, b, ref', + [(0.5, 0.5, -0.24156447527049044), + (0.001, 1, -992.0922447210179), + (1, 10000, -8.210440371976183), + (100000, 100000, -5.377247470132859)]) + def test_entropy(self, a, b, ref): + assert_allclose(stats.beta(a, b).entropy(), ref) + + @pytest.mark.parametrize( + "a, b, ref, tol", + [ + (1, 10, -1.4025850929940458, 1e-14), + (10, 20, -1.0567887388936708, 1e-13), + (4e6, 4e6+20, -7.221686009678741, 1e-9), + (5e6, 5e6+10, -7.333257022834638, 1e-8), + (1e10, 1e10+20, -11.133707703130474, 1e-11), + (1e50, 1e50+20, -57.185409562486385, 1e-15), + (2, 1e10, -21.448635265288925, 1e-11), + (2, 1e20, -44.47448619497938, 1e-14), + (2, 1e50, -113.55203898480075, 1e-14), + (5, 1e10, -20.87226777401971, 1e-10), + (5, 1e20, -43.89811870326017, 1e-14), + (5, 1e50, -112.97567149308153, 1e-14), + (10, 1e10, -20.489796752909477, 1e-9), + (10, 1e20, -43.51564768139993, 1e-14), + (10, 1e50, -112.59320047122131, 1e-14), + (1e20, 2, -44.47448619497938, 1e-14), + (1e20, 5, -43.89811870326017, 1e-14), + (1e50, 10, -112.59320047122131, 1e-14), + ] + ) + def test_extreme_entropy(self, a, b, ref, tol): + # Reference values were calculated with mpmath: + # from mpmath import mp + # mp.dps = 500 + # + # def beta_entropy_mpmath(a, b): + # a = mp.mpf(a) + # b = mp.mpf(b) + # entropy = ( + # mp.log(mp.beta(a, b)) - (a - 1) * mp.digamma(a) + # - (b - 1) * mp.digamma(b) + (a + b - 2) * mp.digamma(a + b) + # ) + # return float(entropy) + assert_allclose(stats.beta(a, b).entropy(), ref, rtol=tol) + + +class TestBetaPrime: + # the test values are used in test_cdf_gh_17631 / test_ppf_gh_17631 + # They are computed with mpmath. Example: + # from mpmath import mp + # mp.dps = 50 + # a, b = mp.mpf(0.05), mp.mpf(0.1) + # x = mp.mpf(1e22) + # float(mp.betainc(a, b, 0.0, x/(1+x), regularized=True)) + # note: we use the values computed by the cdf to test whether + # ppf(cdf(x)) == x (up to a small tolerance) + # since the ppf can be very sensitive to small variations of the input, + # it can be required to generate the test case for the ppf separately, + # see self.test_ppf + cdf_vals = [ + (1e22, 100.0, 0.05, 0.8973027435427167), + (1e10, 100.0, 0.05, 0.5911548582766262), + (1e8, 0.05, 0.1, 0.9467768090820048), + (1e8, 100.0, 0.05, 0.4852944858726726), + (1e-10, 0.05, 0.1, 0.21238845427095), + (1e-10, 1.5, 1.5, 1.697652726007973e-15), + (1e-10, 0.05, 100.0, 0.40884514172337383), + (1e-22, 0.05, 0.1, 0.053349567649287326), + (1e-22, 1.5, 1.5, 1.6976527263135503e-33), + (1e-22, 0.05, 100.0, 0.10269725645728331), + (1e-100, 0.05, 0.1, 6.7163126421919795e-06), + (1e-100, 1.5, 1.5, 1.6976527263135503e-150), + (1e-100, 0.05, 100.0, 1.2928818587561651e-05), + ] + + def test_logpdf(self): + alpha, beta = 267, 1472 + x = np.array([0.2, 0.5, 0.6]) + b = stats.betaprime(alpha, beta) + assert_(np.isfinite(b.logpdf(x)).all()) + assert_allclose(b.pdf(x), np.exp(b.logpdf(x))) + + def test_cdf(self): + # regression test for gh-4030: Implementation of + # scipy.stats.betaprime.cdf() + x = stats.betaprime.cdf(0, 0.2, 0.3) + assert_equal(x, 0.0) + + alpha, beta = 267, 1472 + x = np.array([0.2, 0.5, 0.6]) + cdfs = stats.betaprime.cdf(x, alpha, beta) + assert_(np.isfinite(cdfs).all()) + + # check the new cdf implementation vs generic one: + gen_cdf = stats.rv_continuous._cdf_single + cdfs_g = [gen_cdf(stats.betaprime, val, alpha, beta) for val in x] + assert_allclose(cdfs, cdfs_g, atol=0, rtol=2e-12) + + # The expected values for test_ppf() were computed with mpmath, e.g. + # + # from mpmath import mp + # mp.dps = 125 + # p = 0.01 + # a, b = 1.25, 2.5 + # x = mp.findroot(lambda t: mp.betainc(a, b, x1=0, x2=t/(1+t), + # regularized=True) - p, + # x0=(0.01, 0.011), method='secant') + # print(float(x)) + # + # prints + # + # 0.01080162700956614 + # + @pytest.mark.parametrize( + 'p, a, b, expected', + [(0.010, 1.25, 2.5, 0.01080162700956614), + (1e-12, 1.25, 2.5, 1.0610141996279122e-10), + (1e-18, 1.25, 2.5, 1.6815941817974941e-15), + (1e-17, 0.25, 7.0, 1.0179194531881782e-69), + (0.375, 0.25, 7.0, 0.002036820346115211), + (0.9978811466052919, 0.05, 0.1, 1.0000000000001218e22),] + ) + def test_ppf(self, p, a, b, expected): + x = stats.betaprime.ppf(p, a, b) + assert_allclose(x, expected, rtol=1e-14) + + @pytest.mark.parametrize('x, a, b, p', cdf_vals) + def test_ppf_gh_17631(self, x, a, b, p): + assert_allclose(stats.betaprime.ppf(p, a, b), x, rtol=2e-14) + + def test__ppf(self): + # Verify that _ppf supports scalar arrays. + a = np.array(1.0) + b = np.array(1.0) + p = np.array(0.5) + assert_allclose(stats.betaprime._ppf(p, a, b), 1.0, rtol=5e-16) + + @pytest.mark.parametrize( + 'x, a, b, expected', + cdf_vals + [ + (1e10, 1.5, 1.5, 0.9999999999999983), + (1e10, 0.05, 0.1, 0.9664184367890859), + (1e22, 0.05, 0.1, 0.9978811466052919), + ]) + def test_cdf_gh_17631(self, x, a, b, expected): + assert_allclose(stats.betaprime.cdf(x, a, b), expected, rtol=1e-14) + + @pytest.mark.parametrize( + 'x, a, b, expected', + [(1e50, 0.05, 0.1, 0.9999966641709545), + (1e50, 100.0, 0.05, 0.995925162631006)]) + def test_cdf_extreme_tails(self, x, a, b, expected): + # for even more extreme values, we only get a few correct digits + # results are still < 1 + y = stats.betaprime.cdf(x, a, b) + assert y < 1.0 + assert_allclose(y, expected, rtol=2e-5) + + def test_sf(self): + # reference values were computed via the reference distribution, + # e.g. + # mp.dps = 50 + # a, b = 5, 3 + # x = 1e10 + # BetaPrime(a=a, b=b).sf(x); returns 3.4999999979e-29 + a = [5, 4, 2, 0.05, 0.05, 0.05, 0.05, 100.0, 100.0, 0.05, 0.05, + 0.05, 1.5, 1.5] + b = [3, 2, 1, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05, 100.0, 100.0, + 100.0, 1.5, 1.5] + x = [1e10, 1e20, 1e30, 1e22, 1e-10, 1e-22, 1e-100, 1e22, 1e10, + 1e-10, 1e-22, 1e-100, 1e10, 1e-10] + ref = [3.4999999979e-29, 9.999999999994357e-40, 1.9999999999999998e-30, + 0.0021188533947081017, 0.78761154572905, 0.9466504323507127, + 0.9999932836873578, 0.10269725645728331, 0.40884514172337383, + 0.5911548582766262, 0.8973027435427167, 0.9999870711814124, + 1.6976527260079727e-15, 0.9999999999999983] + sf_values = stats.betaprime.sf(x, a, b) + assert_allclose(sf_values, ref, rtol=1e-12) + + def test_logcdf(self): + x = 800 + a = 0.5 + b = 5.0 + ref = -7.467307556554531e-16 + logcdf = stats.betaprime.logcdf(x, a, b) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + x = 1e-8 + a = 4.5 + b = 0.5 + ref = -2.5868992866500915e-37 + logsf = stats.betaprime.logsf(x, a, b) + assert_allclose(logsf, ref, rtol=5e-15) + + + def test_fit_stats_gh18274(self): + # gh-18274 reported spurious warning emitted when fitting `betaprime` + # to data. Some of these were emitted by stats, too. Check that the + # warnings are no longer emitted. + stats.betaprime.fit([0.1, 0.25, 0.3, 1.2, 1.6], floc=0, fscale=1) + stats.betaprime(a=1, b=1).stats('mvsk') + + def test_moment_gh18634(self): + # Testing for gh-18634 revealed that `betaprime` raised a + # NotImplementedError for higher moments. Check that this is + # resolved. Parameters are arbitrary but lie on either side of the + # moment order (5) to test both branches of `_lazywhere`. Reference + # values produced with Mathematica, e.g. + # `Moment[BetaPrimeDistribution[2,7],5]` + ref = [np.inf, 0.867096912929055] + res = stats.betaprime(2, [4.2, 7.1]).moment(5) + assert_allclose(res, ref) + + +class TestGamma: + def test_pdf(self): + # a few test cases to compare with R + pdf = stats.gamma.pdf(90, 394, scale=1./5) + assert_almost_equal(pdf, 0.002312341) + + pdf = stats.gamma.pdf(3, 10, scale=1./5) + assert_almost_equal(pdf, 0.1620358) + + def test_logpdf(self): + # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0) + # situation + logpdf = stats.gamma.logpdf(0, 1) + assert_almost_equal(logpdf, 0) + + def test_fit_bad_keyword_args(self): + x = [0.1, 0.5, 0.6] + assert_raises(TypeError, stats.gamma.fit, x, floc=0, plate="shrimp") + + def test_isf(self): + # Test cases for when the probability is very small. See gh-13664. + # The expected values can be checked with mpmath. With mpmath, + # the survival function sf(x, k) can be computed as + # + # mpmath.gammainc(k, x, mpmath.inf, regularized=True) + # + # Here we have: + # + # >>> mpmath.mp.dps = 60 + # >>> float(mpmath.gammainc(1, 39.14394658089878, mpmath.inf, + # ... regularized=True)) + # 9.99999999999999e-18 + # >>> float(mpmath.gammainc(100, 330.6557590436547, mpmath.inf, + # regularized=True)) + # 1.000000000000028e-50 + # + assert np.isclose(stats.gamma.isf(1e-17, 1), + 39.14394658089878, atol=1e-14) + assert np.isclose(stats.gamma.isf(1e-50, 100), + 330.6557590436547, atol=1e-13) + + def test_logcdf(self): + x = 80 + a = 7 + ref = -7.096510270453943e-27 + logcdf = stats.gamma.logcdf(x, a) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + x = 0.001 + a = 3.0 + ref = -1.6654171666664883e-10 + logsf = stats.gamma.logsf(x, a) + assert_allclose(logsf, ref, rtol=5e-15) + + @pytest.mark.parametrize('scale', [1.0, 5.0]) + def test_delta_cdf(self, scale): + # Expected value computed with mpmath: + # + # >>> import mpmath + # >>> mpmath.mp.dps = 150 + # >>> cdf1 = mpmath.gammainc(3, 0, 245, regularized=True) + # >>> cdf2 = mpmath.gammainc(3, 0, 250, regularized=True) + # >>> float(cdf2 - cdf1) + # 1.1902609356171962e-102 + # + delta = stats.gamma._delta_cdf(scale*245, scale*250, 3, scale=scale) + assert_allclose(delta, 1.1902609356171962e-102, rtol=1e-13) + + @pytest.mark.parametrize('a, ref, rtol', + [(1e-4, -9990.366610819761, 1e-15), + (2, 1.5772156649015328, 1e-15), + (100, 3.7181819485047463, 1e-13), + (1e4, 6.024075385026086, 1e-15), + (1e18, 22.142204370151084, 1e-15), + (1e100, 116.54819318290696, 1e-15)]) + def test_entropy(self, a, ref, rtol): + # expected value computed with mpmath: + # from mpmath import mp + # mp.dps = 500 + # def gamma_entropy_reference(x): + # x = mp.mpf(x) + # return float(mp.digamma(x) * (mp.one - x) + x + mp.loggamma(x)) + + assert_allclose(stats.gamma.entropy(a), ref, rtol=rtol) + + @pytest.mark.parametrize("a", [1e-2, 1, 1e2]) + @pytest.mark.parametrize("loc", [1e-2, 0, 1e2]) + @pytest.mark.parametrize('scale', [1e-2, 1, 1e2]) + @pytest.mark.parametrize('fix_a', [True, False]) + @pytest.mark.parametrize('fix_loc', [True, False]) + @pytest.mark.parametrize('fix_scale', [True, False]) + def test_fit_mm(self, a, loc, scale, fix_a, fix_loc, fix_scale): + rng = np.random.default_rng(6762668991392531563) + data = stats.gamma.rvs(a, loc=loc, scale=scale, size=100, + random_state=rng) + + kwds = {} + if fix_a: + kwds['fa'] = a + if fix_loc: + kwds['floc'] = loc + if fix_scale: + kwds['fscale'] = scale + nfree = 3 - len(kwds) + + if nfree == 0: + error_msg = "All parameters fixed. There is nothing to optimize." + with pytest.raises(ValueError, match=error_msg): + stats.gamma.fit(data, method='mm', **kwds) + return + + theta = stats.gamma.fit(data, method='mm', **kwds) + dist = stats.gamma(*theta) + if nfree >= 1: + assert_allclose(dist.mean(), np.mean(data)) + if nfree >= 2: + assert_allclose(dist.moment(2), np.mean(data**2)) + if nfree >= 3: + assert_allclose(dist.moment(3), np.mean(data**3)) + + +def test_pdf_overflow_gh19616(): + # Confirm that gh19616 (intermediate over/underflows in PDF) is resolved + # Reference value from R GeneralizedHyperbolic library + # library(GeneralizedHyperbolic) + # options(digits=16) + # jitter = 1e-3 + # dnig(1, a=2**0.5 / jitter**2, b=1 / jitter**2) + jitter = 1e-3 + Z = stats.norminvgauss(2**0.5 / jitter**2, 1 / jitter**2, loc=0, scale=1) + assert_allclose(Z.pdf(1.0), 282.0948446666433) + + +class TestDgamma: + def test_pdf(self): + rng = np.random.default_rng(3791303244302340058) + size = 10 # number of points to check + x = rng.normal(scale=10, size=size) + a = rng.uniform(high=10, size=size) + res = stats.dgamma.pdf(x, a) + ref = stats.gamma.pdf(np.abs(x), a) / 2 + assert_allclose(res, ref) + + dist = stats.dgamma(a) + # There was an intermittent failure with assert_equal on Linux - 32 bit + assert_allclose(dist.pdf(x), res, rtol=5e-16) + + # mpmath was used to compute the expected values. + # For x < 0, cdf(x, a) is mp.gammainc(a, -x, mp.inf, regularized=True)/2 + # For x > 0, cdf(x, a) is (1 + mp.gammainc(a, 0, x, regularized=True))/2 + # E.g. + # from mpmath import mp + # mp.dps = 50 + # print(float(mp.gammainc(1, 20, mp.inf, regularized=True)/2)) + # prints + # 1.030576811219279e-09 + @pytest.mark.parametrize('x, a, expected', + [(-20, 1, 1.030576811219279e-09), + (-40, 1, 2.1241771276457944e-18), + (-50, 5, 2.7248509914602648e-17), + (-25, 0.125, 5.333071920958156e-14), + (5, 1, 0.9966310265004573)]) + def test_cdf_ppf_sf_isf_tail(self, x, a, expected): + cdf = stats.dgamma.cdf(x, a) + assert_allclose(cdf, expected, rtol=5e-15) + ppf = stats.dgamma.ppf(expected, a) + assert_allclose(ppf, x, rtol=5e-15) + sf = stats.dgamma.sf(-x, a) + assert_allclose(sf, expected, rtol=5e-15) + isf = stats.dgamma.isf(expected, a) + assert_allclose(isf, -x, rtol=5e-15) + + @pytest.mark.parametrize("a, ref", + [(1.5, 2.0541199559354117), + (1.3, 1.9357296377121247), + (1.1, 1.7856502333412134)]) + def test_entropy(self, a, ref): + # The reference values were calculated with mpmath: + # def entropy_dgamma(a): + # def pdf(x): + # A = mp.one / (mp.mpf(2.) * mp.gamma(a)) + # B = mp.fabs(x) ** (a - mp.one) + # C = mp.exp(-mp.fabs(x)) + # h = A * B * C + # return h + # + # return -mp.quad(lambda t: pdf(t) * mp.log(pdf(t)), + # [-mp.inf, mp.inf]) + assert_allclose(stats.dgamma.entropy(a), ref, rtol=1e-14) + + @pytest.mark.parametrize("a, ref", + [(1e-100, -1e+100), + (1e-10, -9999999975.858217), + (1e-5, -99987.37111657023), + (1e4, 6.717222565586032), + (1000000000000000.0, 19.38147391121996), + (1e+100, 117.2413403634669)]) + def test_entropy_entreme_values(self, a, ref): + # The reference values were calculated with mpmath: + # from mpmath import mp + # mp.dps = 500 + # def second_dgamma(a): + # a = mp.mpf(a) + # x_1 = a + mp.log(2) + mp.loggamma(a) + # x_2 = (mp.one - a) * mp.digamma(a) + # h = x_1 + x_2 + # return h + assert_allclose(stats.dgamma.entropy(a), ref, rtol=1e-10) + + def test_entropy_array_input(self): + x = np.array([1, 5, 1e20, 1e-5]) + y = stats.dgamma.entropy(x) + for i in range(len(y)): + assert y[i] == stats.dgamma.entropy(x[i]) + + +class TestChi2: + + # regression tests after precision improvements, ticket:1041, not verified + def test_precision(self): + assert_almost_equal(stats.chi2.pdf(1000, 1000), 8.919133934753128e-003, + decimal=14) + assert_almost_equal(stats.chi2.pdf(100, 100), 0.028162503162596778, + decimal=14) + + # Reference values computed with mpmath. + @pytest.mark.parametrize( + 'x, df, ref', + [(750.0, 3, -3.0172957781136564e-162), + (120.0, 15, -1.8924849646375648e-18), + (15.0, 13, -0.36723446372517876)] + ) + def test_logcdf(self, x, df, ref): + logcdf = stats.chi2.logcdf(x, df) + assert_allclose(logcdf, ref, rtol=5e-15) + + # Reference values computed with mpmath. + @pytest.mark.parametrize( + 'x, df, ref', + [(1e-4, 15, -3.936060782678026e-37), + (1.5, 40, -6.384797888313517e-22), + (3.0, 10, -0.018750635779926784)] + ) + def test_logsf(self, x, df, ref): + logsf = stats.chi2.logsf(x, df) + assert_allclose(logsf, ref, rtol=5e-15) + + def test_ppf(self): + # Expected values computed with mpmath. + df = 4.8 + x = stats.chi2.ppf(2e-47, df) + assert_allclose(x, 1.098472479575179840604902808e-19, rtol=1e-10) + x = stats.chi2.ppf(0.5, df) + assert_allclose(x, 4.15231407598589358660093156, rtol=1e-10) + + df = 13 + x = stats.chi2.ppf(2e-77, df) + assert_allclose(x, 1.0106330688195199050507943e-11, rtol=1e-10) + x = stats.chi2.ppf(0.1, df) + assert_allclose(x, 7.041504580095461859307179763, rtol=1e-10) + + # Entropy references values were computed with the following mpmath code + # from mpmath import mp + # mp.dps = 50 + # def chisq_entropy_mpmath(df): + # df = mp.mpf(df) + # half_df = 0.5 * df + # entropy = (half_df + mp.log(2) + mp.log(mp.gamma(half_df)) + + # (mp.one - half_df) * mp.digamma(half_df)) + # return float(entropy) + + @pytest.mark.parametrize('df, ref', + [(1e-4, -19988.980448690163), + (1, 0.7837571104739337), + (100, 4.061397128938114), + (251, 4.525577254045129), + (1e15, 19.034900320939986)]) + def test_entropy(self, df, ref): + assert_allclose(stats.chi2(df).entropy(), ref, rtol=1e-13) + + def test_regression_ticket_1326(self): + # adjust to avoid nan with 0*log(0) + assert_almost_equal(stats.chi2.pdf(0.0, 2), 0.5, 14) + + +class TestGumbelL: + # gh-6228 + def test_cdf_ppf(self): + x = np.linspace(-100, -4) + y = stats.gumbel_l.cdf(x) + xx = stats.gumbel_l.ppf(y) + assert_allclose(x, xx) + + def test_logcdf_logsf(self): + x = np.linspace(-100, -4) + y = stats.gumbel_l.logcdf(x) + z = stats.gumbel_l.logsf(x) + u = np.exp(y) + v = -special.expm1(z) + assert_allclose(u, v) + + def test_sf_isf(self): + x = np.linspace(-20, 5) + y = stats.gumbel_l.sf(x) + xx = stats.gumbel_l.isf(y) + assert_allclose(x, xx) + + @pytest.mark.parametrize('loc', [-1, 1]) + def test_fit_fixed_param(self, loc): + # ensure fixed location is correctly reflected from `gumbel_r.fit` + # See comments at end of gh-12737. + data = stats.gumbel_l.rvs(size=100, loc=loc) + fitted_loc, _ = stats.gumbel_l.fit(data, floc=loc) + assert_equal(fitted_loc, loc) + + +class TestGumbelR: + + def test_sf(self): + # Expected value computed with mpmath: + # >>> import mpmath + # >>> mpmath.mp.dps = 40 + # >>> float(mpmath.mp.one - mpmath.exp(-mpmath.exp(-50))) + # 1.9287498479639178e-22 + assert_allclose(stats.gumbel_r.sf(50), 1.9287498479639178e-22, + rtol=1e-14) + + def test_isf(self): + # Expected value computed with mpmath: + # >>> import mpmath + # >>> mpmath.mp.dps = 40 + # >>> float(-mpmath.log(-mpmath.log(mpmath.mp.one - 1e-17))) + # 39.14394658089878 + assert_allclose(stats.gumbel_r.isf(1e-17), 39.14394658089878, + rtol=1e-14) + + +class TestLevyStable: + @pytest.fixture(autouse=True) + def reset_levy_stable_params(self): + """Setup default parameters for levy_stable generator""" + stats.levy_stable.parameterization = "S1" + stats.levy_stable.cdf_default_method = "piecewise" + stats.levy_stable.pdf_default_method = "piecewise" + stats.levy_stable.quad_eps = stats._levy_stable._QUAD_EPS + + @pytest.fixture + def nolan_pdf_sample_data(self): + """Sample data points for pdf computed with Nolan's stablec + + See - http://fs2.american.edu/jpnolan/www/stable/stable.html + + There's a known limitation of Nolan's executable for alpha < 0.2. + + The data table loaded below is generated from Nolan's stablec + with the following parameter space: + + alpha = 0.1, 0.2, ..., 2.0 + beta = -1.0, -0.9, ..., 1.0 + p = 0.01, 0.05, 0.1, 0.25, 0.35, 0.5, + and the equivalent for the right tail + + Typically inputs for stablec: + + stablec.exe << + 1 # pdf + 1 # Nolan S equivalent to S0 in scipy + .25,2,.25 # alpha + -1,-1,0 # beta + -10,10,1 # x + 1,0 # gamma, delta + 2 # output file + """ + data = np.load( + Path(__file__).parent / + 'data/levy_stable/stable-Z1-pdf-sample-data.npy' + ) + data = np.rec.fromarrays(data.T, names='x,p,alpha,beta,pct') + return data + + @pytest.fixture + def nolan_cdf_sample_data(self): + """Sample data points for cdf computed with Nolan's stablec + + See - http://fs2.american.edu/jpnolan/www/stable/stable.html + + There's a known limitation of Nolan's executable for alpha < 0.2. + + The data table loaded below is generated from Nolan's stablec + with the following parameter space: + + alpha = 0.1, 0.2, ..., 2.0 + beta = -1.0, -0.9, ..., 1.0 + p = 0.01, 0.05, 0.1, 0.25, 0.35, 0.5, + + and the equivalent for the right tail + + Ideally, Nolan's output for CDF values should match the percentile + from where they have been sampled from. Even more so as we extract + percentile x positions from stablec too. However, we note at places + Nolan's stablec will produce absolute errors in order of 1e-5. We + compare against his calculations here. In future, once we less + reliant on Nolan's paper we might switch to comparing directly at + percentiles (those x values being produced from some alternative + means). + + Typically inputs for stablec: + + stablec.exe << + 2 # cdf + 1 # Nolan S equivalent to S0 in scipy + .25,2,.25 # alpha + -1,-1,0 # beta + -10,10,1 # x + 1,0 # gamma, delta + 2 # output file + """ + data = np.load( + Path(__file__).parent / + 'data/levy_stable/stable-Z1-cdf-sample-data.npy' + ) + data = np.rec.fromarrays(data.T, names='x,p,alpha,beta,pct') + return data + + @pytest.fixture + def nolan_loc_scale_sample_data(self): + """Sample data where loc, scale are different from 0, 1 + + Data extracted in similar way to pdf/cdf above using + Nolan's stablec but set to an arbitrary location scale of + (2, 3) for various important parameters alpha, beta and for + parameterisations S0 and S1. + """ + data = np.load( + Path(__file__).parent / + 'data/levy_stable/stable-loc-scale-sample-data.npy' + ) + return data + + @pytest.mark.slow + @pytest.mark.parametrize( + "sample_size", [ + pytest.param(50), pytest.param(1500, marks=pytest.mark.slow) + ] + ) + @pytest.mark.parametrize("parameterization", ["S0", "S1"]) + @pytest.mark.parametrize( + "alpha,beta", [(1.0, 0), (1.0, -0.5), (1.5, 0), (1.9, 0.5)] + ) + @pytest.mark.parametrize("gamma,delta", [(1, 0), (3, 2)]) + def test_rvs( + self, + parameterization, + alpha, + beta, + gamma, + delta, + sample_size, + ): + stats.levy_stable.parameterization = parameterization + ls = stats.levy_stable( + alpha=alpha, beta=beta, scale=gamma, loc=delta + ) + _, p = stats.kstest( + ls.rvs(size=sample_size, random_state=1234), ls.cdf + ) + assert p > 0.05 + + @pytest.mark.xslow + @pytest.mark.parametrize('beta', [0.5, 1]) + def test_rvs_alpha1(self, beta): + """Additional test cases for rvs for alpha equal to 1.""" + np.random.seed(987654321) + alpha = 1.0 + loc = 0.5 + scale = 1.5 + x = stats.levy_stable.rvs(alpha, beta, loc=loc, scale=scale, + size=5000) + stat, p = stats.kstest(x, 'levy_stable', + args=(alpha, beta, loc, scale)) + assert p > 0.01 + + def test_fit(self): + # construct data to have percentiles that match + # example in McCulloch 1986. + x = [ + -.05413, -.05413, 0., 0., 0., 0., .00533, .00533, .00533, .00533, + .00533, .03354, .03354, .03354, .03354, .03354, .05309, .05309, + .05309, .05309, .05309 + ] + alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(x) + assert_allclose(alpha1, 1.48, rtol=0, atol=0.01) + assert_almost_equal(beta1, -.22, 2) + assert_almost_equal(scale1, 0.01717, 4) + assert_almost_equal( + loc1, 0.00233, 2 + ) # to 2 dps due to rounding error in McCulloch86 + + # cover alpha=2 scenario + x2 = x + [.05309, .05309, .05309, .05309, .05309] + alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(x2) + assert_equal(alpha2, 2) + assert_equal(beta2, -1) + assert_almost_equal(scale2, .02503, 4) + assert_almost_equal(loc2, .03354, 4) + + @pytest.mark.xfail(reason="Unknown problem with fitstart.") + @pytest.mark.parametrize( + "alpha,beta,delta,gamma", + [ + (1.5, 0.4, 2, 3), + (1.0, 0.4, 2, 3), + ] + ) + @pytest.mark.parametrize( + "parametrization", ["S0", "S1"] + ) + def test_fit_rvs(self, alpha, beta, delta, gamma, parametrization): + """Test that fit agrees with rvs for each parametrization.""" + stats.levy_stable.parametrization = parametrization + data = stats.levy_stable.rvs( + alpha, beta, loc=delta, scale=gamma, size=10000, random_state=1234 + ) + fit = stats.levy_stable._fitstart(data) + alpha_obs, beta_obs, delta_obs, gamma_obs = fit + assert_allclose( + [alpha, beta, delta, gamma], + [alpha_obs, beta_obs, delta_obs, gamma_obs], + rtol=0.01, + ) + + def test_fit_beta_flip(self): + # Confirm that sign of beta affects loc, not alpha or scale. + x = np.array([1, 1, 3, 3, 10, 10, 10, 30, 30, 100, 100]) + alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(x) + alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(-x) + assert_equal(beta1, 1) + assert loc1 != 0 + assert_almost_equal(alpha2, alpha1) + assert_almost_equal(beta2, -beta1) + assert_almost_equal(loc2, -loc1) + assert_almost_equal(scale2, scale1) + + def test_fit_delta_shift(self): + # Confirm that loc slides up and down if data shifts. + SHIFT = 1 + x = np.array([1, 1, 3, 3, 10, 10, 10, 30, 30, 100, 100]) + alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(-x) + alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(-x + SHIFT) + assert_almost_equal(alpha2, alpha1) + assert_almost_equal(beta2, beta1) + assert_almost_equal(loc2, loc1 + SHIFT) + assert_almost_equal(scale2, scale1) + + def test_fit_loc_extrap(self): + # Confirm that loc goes out of sample for alpha close to 1. + x = [1, 1, 3, 3, 10, 10, 10, 30, 30, 140, 140] + alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(x) + assert alpha1 < 1, f"Expected alpha < 1, got {alpha1}" + assert loc1 < min(x), f"Expected loc < {min(x)}, got {loc1}" + + x2 = [1, 1, 3, 3, 10, 10, 10, 30, 30, 130, 130] + alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(x2) + assert alpha2 > 1, f"Expected alpha > 1, got {alpha2}" + assert loc2 > max(x2), f"Expected loc > {max(x2)}, got {loc2}" + + @pytest.mark.slow + @pytest.mark.parametrize( + "pct_range,alpha_range,beta_range", [ + pytest.param( + [.01, .5, .99], + [.1, 1, 2], + [-1, 0, .8], + ), + pytest.param( + [.01, .05, .5, .95, .99], + [.1, .5, 1, 1.5, 2], + [-.9, -.5, 0, .3, .6, 1], + marks=pytest.mark.slow + ), + pytest.param( + [.01, .05, .1, .25, .35, .5, .65, .75, .9, .95, .99], + np.linspace(0.1, 2, 20), + np.linspace(-1, 1, 21), + marks=pytest.mark.xslow, + ), + ] + ) + def test_pdf_nolan_samples( + self, nolan_pdf_sample_data, pct_range, alpha_range, beta_range + ): + """Test pdf values against Nolan's stablec.exe output""" + data = nolan_pdf_sample_data + + # some tests break on linux 32 bit + uname = platform.uname() + is_linux_32 = uname.system == 'Linux' and uname.machine == 'i686' + platform_desc = "/".join( + [uname.system, uname.machine, uname.processor]) + + # fmt: off + # There are a number of cases which fail on some but not all platforms. + # These are excluded by the filters below. TODO: Rewrite tests so that + # the now filtered out test cases are still run but marked in pytest as + # expected to fail. + tests = [ + [ + 'dni', 1e-7, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + ~( + ( + (r['beta'] == 0) & + (r['pct'] == 0.5) + ) | + ( + (r['beta'] >= 0.9) & + (r['alpha'] >= 1.6) & + (r['pct'] == 0.5) + ) | + ( + (r['alpha'] <= 0.4) & + np.isin(r['pct'], [.01, .99]) + ) | + ( + (r['alpha'] <= 0.3) & + np.isin(r['pct'], [.05, .95]) + ) | + ( + (r['alpha'] <= 0.2) & + np.isin(r['pct'], [.1, .9]) + ) | + ( + (r['alpha'] == 0.1) & + np.isin(r['pct'], [.25, .75]) & + np.isin(np.abs(r['beta']), [.5, .6, .7]) + ) | + ( + (r['alpha'] == 0.1) & + np.isin(r['pct'], [.5]) & + np.isin(np.abs(r['beta']), [.1]) + ) | + ( + (r['alpha'] == 0.1) & + np.isin(r['pct'], [.35, .65]) & + np.isin(np.abs(r['beta']), [-.4, -.3, .3, .4, .5]) + ) | + ( + (r['alpha'] == 0.2) & + (r['beta'] == 0.5) & + (r['pct'] == 0.25) + ) | + ( + (r['alpha'] == 0.2) & + (r['beta'] == -0.3) & + (r['pct'] == 0.65) + ) | + ( + (r['alpha'] == 0.2) & + (r['beta'] == 0.3) & + (r['pct'] == 0.35) + ) | + ( + (r['alpha'] == 1.) & + np.isin(r['pct'], [.5]) & + np.isin(np.abs(r['beta']), [.1, .2, .3, .4]) + ) | + ( + (r['alpha'] == 1.) & + np.isin(r['pct'], [.35, .65]) & + np.isin(np.abs(r['beta']), [.8, .9, 1.]) + ) | + ( + (r['alpha'] == 1.) & + np.isin(r['pct'], [.01, .99]) & + np.isin(np.abs(r['beta']), [-.1, .1]) + ) | + # various points ok but too sparse to list + (r['alpha'] >= 1.1) + ) + ) + ], + # piecewise generally good accuracy + [ + 'piecewise', 1e-11, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + (r['alpha'] > 0.2) & + (r['alpha'] != 1.) + ) + ], + # for alpha = 1. for linux 32 bit optimize.bisect + # has some issues for .01 and .99 percentile + [ + 'piecewise', 1e-11, lambda r: ( + (r['alpha'] == 1.) & + (not is_linux_32) & + np.isin(r['pct'], pct_range) & + (1. in alpha_range) & + np.isin(r['beta'], beta_range) + ) + ], + # for small alpha very slightly reduced accuracy + [ + 'piecewise', 2.5e-10, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + (r['alpha'] <= 0.2) + ) + ], + # fft accuracy reduces as alpha decreases + [ + 'fft-simpson', 1e-5, lambda r: ( + (r['alpha'] >= 1.9) & + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) + ), + ], + [ + 'fft-simpson', 1e-6, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + (r['alpha'] > 1) & + (r['alpha'] < 1.9) + ) + ], + # fft relative errors for alpha < 1, will raise if enabled + # ['fft-simpson', 1e-4, lambda r: r['alpha'] == 0.9], + # ['fft-simpson', 1e-3, lambda r: r['alpha'] == 0.8], + # ['fft-simpson', 1e-2, lambda r: r['alpha'] == 0.7], + # ['fft-simpson', 1e-1, lambda r: r['alpha'] == 0.6], + ] + # fmt: on + for ix, (default_method, rtol, + filter_func) in enumerate(tests): + stats.levy_stable.pdf_default_method = default_method + subdata = data[filter_func(data) + ] if filter_func is not None else data + with suppress_warnings() as sup: + # occurs in FFT methods only + sup.record( + RuntimeWarning, + "Density calculations experimental for FFT method.*" + ) + p = stats.levy_stable.pdf( + subdata['x'], + subdata['alpha'], + subdata['beta'], + scale=1, + loc=0 + ) + with np.errstate(over="ignore"): + subdata2 = rec_append_fields( + subdata, + ['calc', 'abserr', 'relerr'], + [ + p, + np.abs(p - subdata['p']), + np.abs(p - subdata['p']) / np.abs(subdata['p']) + ] + ) + failures = subdata2[ + (subdata2['relerr'] >= rtol) | + np.isnan(p) + ] + message = ( + f"pdf test {ix} failed with method '{default_method}' " + f"[platform: {platform_desc}]\n{failures.dtype.names}\n{failures}" + ) + assert_allclose( + p, + subdata['p'], + rtol, + err_msg=message, + verbose=False + ) + + @pytest.mark.parametrize( + "pct_range,alpha_range,beta_range", [ + pytest.param( + [.01, .5, .99], + [.1, 1, 2], + [-1, 0, .8], + ), + pytest.param( + [.01, .05, .5, .95, .99], + [.1, .5, 1, 1.5, 2], + [-.9, -.5, 0, .3, .6, 1], + marks=pytest.mark.slow + ), + pytest.param( + [.01, .05, .1, .25, .35, .5, .65, .75, .9, .95, .99], + np.linspace(0.1, 2, 20), + np.linspace(-1, 1, 21), + marks=pytest.mark.xslow, + ), + ] + ) + def test_cdf_nolan_samples( + self, nolan_cdf_sample_data, pct_range, alpha_range, beta_range + ): + """ Test cdf values against Nolan's stablec.exe output.""" + data = nolan_cdf_sample_data + tests = [ + # piecewise generally good accuracy + [ + 'piecewise', 2e-12, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + ~( + ( + (r['alpha'] == 1.) & + np.isin(r['beta'], [-0.3, -0.2, -0.1]) & + (r['pct'] == 0.01) + ) | + ( + (r['alpha'] == 1.) & + np.isin(r['beta'], [0.1, 0.2, 0.3]) & + (r['pct'] == 0.99) + ) + ) + ) + ], + # for some points with alpha=1, Nolan's STABLE clearly + # loses accuracy + [ + 'piecewise', 5e-2, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + ( + (r['alpha'] == 1.) & + np.isin(r['beta'], [-0.3, -0.2, -0.1]) & + (r['pct'] == 0.01) + ) | + ( + (r['alpha'] == 1.) & + np.isin(r['beta'], [0.1, 0.2, 0.3]) & + (r['pct'] == 0.99) + ) + ) + ], + # fft accuracy poor, very poor alpha < 1 + [ + 'fft-simpson', 1e-5, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + (r['alpha'] > 1.7) + ) + ], + [ + 'fft-simpson', 1e-4, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + (r['alpha'] > 1.5) & + (r['alpha'] <= 1.7) + ) + ], + [ + 'fft-simpson', 1e-3, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + (r['alpha'] > 1.3) & + (r['alpha'] <= 1.5) + ) + ], + [ + 'fft-simpson', 1e-2, lambda r: ( + np.isin(r['pct'], pct_range) & + np.isin(r['alpha'], alpha_range) & + np.isin(r['beta'], beta_range) & + (r['alpha'] > 1.0) & + (r['alpha'] <= 1.3) + ) + ], + ] + for ix, (default_method, rtol, + filter_func) in enumerate(tests): + stats.levy_stable.cdf_default_method = default_method + subdata = data[filter_func(data) + ] if filter_func is not None else data + with suppress_warnings() as sup: + sup.record( + RuntimeWarning, + 'Cumulative density calculations experimental for FFT' + + ' method. Use piecewise method instead.*' + ) + p = stats.levy_stable.cdf( + subdata['x'], + subdata['alpha'], + subdata['beta'], + scale=1, + loc=0 + ) + with np.errstate(over="ignore"): + subdata2 = rec_append_fields( + subdata, + ['calc', 'abserr', 'relerr'], + [ + p, + np.abs(p - subdata['p']), + np.abs(p - subdata['p']) / np.abs(subdata['p']) + ] + ) + failures = subdata2[ + (subdata2['relerr'] >= rtol) | + np.isnan(p) + ] + message = (f"cdf test {ix} failed with method '{default_method}'\n" + f"{failures.dtype.names}\n{failures}") + assert_allclose( + p, + subdata['p'], + rtol, + err_msg=message, + verbose=False + ) + + @pytest.mark.parametrize("param", [0, 1]) + @pytest.mark.parametrize("case", ["pdf", "cdf"]) + def test_location_scale( + self, nolan_loc_scale_sample_data, param, case + ): + """Tests for pdf and cdf where loc, scale are different from 0, 1 + """ + + uname = platform.uname() + is_linux_32 = uname.system == 'Linux' and "32bit" in platform.architecture()[0] + # Test seems to be unstable (see gh-17839 for a bug report on Debian + # i386), so skip it. + if is_linux_32 and case == 'pdf': + pytest.skip("Test unstable on some platforms; see gh-17839, 17859") + + data = nolan_loc_scale_sample_data + # We only test against piecewise as location/scale transforms + # are same for other methods. + stats.levy_stable.cdf_default_method = "piecewise" + stats.levy_stable.pdf_default_method = "piecewise" + + subdata = data[data["param"] == param] + stats.levy_stable.parameterization = f"S{param}" + + assert case in ["pdf", "cdf"] + function = ( + stats.levy_stable.pdf if case == "pdf" else stats.levy_stable.cdf + ) + + v1 = function( + subdata['x'], subdata['alpha'], subdata['beta'], scale=2, loc=3 + ) + assert_allclose(v1, subdata[case], 1e-5) + + @pytest.mark.parametrize( + "method,decimal_places", + [ + ['dni', 4], + ['piecewise', 4], + ] + ) + def test_pdf_alpha_equals_one_beta_non_zero(self, method, decimal_places): + """ sample points extracted from Tables and Graphs of Stable + Probability Density Functions - Donald R Holt - 1973 - p 187. + """ + xs = np.array( + [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4] + ) + density = np.array( + [ + .3183, .3096, .2925, .2622, .1591, .1587, .1599, .1635, .0637, + .0729, .0812, .0955, .0318, .0390, .0458, .0586, .0187, .0236, + .0285, .0384 + ] + ) + betas = np.array( + [ + 0, .25, .5, 1, 0, .25, .5, 1, 0, .25, .5, 1, 0, .25, .5, 1, 0, + .25, .5, 1 + ] + ) + with np.errstate(all='ignore'), suppress_warnings() as sup: + sup.filter( + category=RuntimeWarning, + message="Density calculation unstable.*" + ) + stats.levy_stable.pdf_default_method = method + # stats.levy_stable.fft_grid_spacing = 0.0001 + pdf = stats.levy_stable.pdf(xs, 1, betas, scale=1, loc=0) + assert_almost_equal( + pdf, density, decimal_places, method + ) + + @pytest.mark.parametrize( + "params,expected", + [ + [(1.48, -.22, 0, 1), (0, np.inf, np.nan, np.nan)], + [(2, .9, 10, 1.5), (10, 4.5, 0, 0)] + ] + ) + def test_stats(self, params, expected): + observed = stats.levy_stable.stats( + params[0], params[1], loc=params[2], scale=params[3], + moments='mvsk' + ) + assert_almost_equal(observed, expected) + + @pytest.mark.parametrize('alpha', [0.25, 0.5, 0.75]) + @pytest.mark.parametrize( + 'function,beta,points,expected', + [ + ( + stats.levy_stable.cdf, + 1.0, + np.linspace(-25, 0, 10), + 0.0, + ), + ( + stats.levy_stable.pdf, + 1.0, + np.linspace(-25, 0, 10), + 0.0, + ), + ( + stats.levy_stable.cdf, + -1.0, + np.linspace(0, 25, 10), + 1.0, + ), + ( + stats.levy_stable.pdf, + -1.0, + np.linspace(0, 25, 10), + 0.0, + ) + ] + ) + def test_distribution_outside_support( + self, alpha, function, beta, points, expected + ): + """Ensure the pdf/cdf routines do not return nan outside support. + + This distribution's support becomes truncated in a few special cases: + support is [mu, infty) if alpha < 1 and beta = 1 + support is (-infty, mu] if alpha < 1 and beta = -1 + Otherwise, the support is all reals. Here, mu is zero by default. + """ + assert 0 < alpha < 1 + assert_almost_equal( + function(points, alpha=alpha, beta=beta), + np.full(len(points), expected) + ) + + @pytest.mark.parametrize( + 'x,alpha,beta,expected', + # Reference values from Matlab + # format long + # alphas = [1.7720732804618808, 1.9217001522410235, 1.5654806051633634, + # 1.7420803447784388, 1.5748002527689913]; + # betas = [0.5059373136902996, -0.8779442746685926, -0.4016220341911392, + # -0.38180029468259247, -0.25200194914153684]; + # x0s = [0, 1e-4, -1e-4]; + # for x0 = x0s + # disp("x0 = " + x0) + # for ii = 1:5 + # alpha = alphas(ii); + # beta = betas(ii); + # pd = makedist('Stable','alpha',alpha,'beta',beta,'gam',1,'delta',0); + # % we need to adjust x. It is the same as x = 0 In scipy. + # x = x0 - beta * tan(pi * alpha / 2); + # disp(pd.pdf(x)) + # end + # end + [ + (0, 1.7720732804618808, 0.5059373136902996, 0.278932636798268), + (0, 1.9217001522410235, -0.8779442746685926, 0.281054757202316), + (0, 1.5654806051633634, -0.4016220341911392, 0.271282133194204), + (0, 1.7420803447784388, -0.38180029468259247, 0.280202199244247), + (0, 1.5748002527689913, -0.25200194914153684, 0.280136576218665), + ] + ) + def test_x_equal_zeta( + self, x, alpha, beta, expected + ): + """Test pdf for x equal to zeta. + + With S1 parametrization: x0 = x + zeta if alpha != 1 So, for x = 0, x0 + will be close to zeta. + + When case "x equal zeta" is not handled properly and quad_eps is not + low enough: - pdf may be less than 0 - logpdf is nan + + The points from the parametrize block are found randomly so that PDF is + less than 0. + + Reference values taken from MATLAB + https://www.mathworks.com/help/stats/stable-distribution.html + """ + stats.levy_stable.quad_eps = 1.2e-11 + + assert_almost_equal( + stats.levy_stable.pdf(x, alpha=alpha, beta=beta), + expected, + ) + + @pytest.mark.xfail + @pytest.mark.parametrize( + # See comment for test_x_equal_zeta for script for reference values + 'x,alpha,beta,expected', + [ + (1e-4, 1.7720732804618808, 0.5059373136902996, 0.278929165340670), + (1e-4, 1.9217001522410235, -0.8779442746685926, 0.281056564327953), + (1e-4, 1.5654806051633634, -0.4016220341911392, 0.271252432161167), + (1e-4, 1.7420803447784388, -0.38180029468259247, 0.280205311264134), + (1e-4, 1.5748002527689913, -0.25200194914153684, 0.280140965235426), + (-1e-4, 1.7720732804618808, 0.5059373136902996, 0.278936106741754), + (-1e-4, 1.9217001522410235, -0.8779442746685926, 0.281052948629429), + (-1e-4, 1.5654806051633634, -0.4016220341911392, 0.271275394392385), + (-1e-4, 1.7420803447784388, -0.38180029468259247, 0.280199085645099), + (-1e-4, 1.5748002527689913, -0.25200194914153684, 0.280132185432842), + ] + ) + def test_x_near_zeta( + self, x, alpha, beta, expected + ): + """Test pdf for x near zeta. + + With S1 parametrization: x0 = x + zeta if alpha != 1 So, for x = 0, x0 + will be close to zeta. + + When case "x near zeta" is not handled properly and quad_eps is not + low enough: - pdf may be less than 0 - logpdf is nan + + The points from the parametrize block are found randomly so that PDF is + less than 0. + + Reference values taken from MATLAB + https://www.mathworks.com/help/stats/stable-distribution.html + """ + stats.levy_stable.quad_eps = 1.2e-11 + + assert_almost_equal( + stats.levy_stable.pdf(x, alpha=alpha, beta=beta), + expected, + ) + + def test_frozen_parameterization_gh20821(self): + # gh-20821 reported that frozen distributions ignore the parameterization. + # Check that this is resolved and that the frozen distribution's + # parameterization can be changed independently of stats.levy_stable + rng = np.random.default_rng + shapes = dict(alpha=1.9, beta=0.1, loc=0.0, scale=1.0) + unfrozen = stats.levy_stable + frozen = stats.levy_stable(**shapes) + + unfrozen.parameterization = "S0" + frozen.parameterization = "S1" + unfrozen_a = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498)) + frozen_a = frozen.rvs(size=10, random_state=rng(329823498)) + assert not np.any(frozen_a == unfrozen_a) + + unfrozen.parameterization = "S1" + frozen.parameterization = "S0" + unfrozen_b = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498)) + frozen_b = frozen.rvs(size=10, random_state=rng(329823498)) + assert_equal(frozen_b, unfrozen_a) + assert_equal(unfrozen_b, frozen_a) + + def test_frozen_parameterization_gh20821b(self): + # Check that the parameterization of the frozen distribution is that of + # the unfrozen distribution at the time of freezing + rng = np.random.default_rng + shapes = dict(alpha=1.9, beta=0.1, loc=0.0, scale=1.0) + unfrozen = stats.levy_stable + + unfrozen.parameterization = "S0" + frozen = stats.levy_stable(**shapes) + unfrozen_a = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498)) + frozen_a = frozen.rvs(size=10, random_state=rng(329823498)) + assert_equal(frozen_a, unfrozen_a) + + unfrozen.parameterization = "S1" + frozen = stats.levy_stable(**shapes) + unfrozen_b = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498)) + frozen_b = frozen.rvs(size=10, random_state=rng(329823498)) + assert_equal(frozen_b, unfrozen_b) + + +class TestArrayArgument: # test for ticket:992 + def setup_method(self): + np.random.seed(1234) + + def test_noexception(self): + rvs = stats.norm.rvs(loc=(np.arange(5)), scale=np.ones(5), + size=(10, 5)) + assert_equal(rvs.shape, (10, 5)) + + +class TestDocstring: + def test_docstrings(self): + # See ticket #761 + if stats.rayleigh.__doc__ is not None: + assert_("rayleigh" in stats.rayleigh.__doc__.lower()) + if stats.bernoulli.__doc__ is not None: + assert_("bernoulli" in stats.bernoulli.__doc__.lower()) + + def test_no_name_arg(self): + # If name is not given, construction shouldn't fail. See #1508. + stats.rv_continuous() + stats.rv_discrete() + + +def test_args_reduce(): + a = array([1, 3, 2, 1, 2, 3, 3]) + b, c = argsreduce(a > 1, a, 2) + + assert_array_equal(b, [3, 2, 2, 3, 3]) + assert_array_equal(c, [2]) + + b, c = argsreduce(2 > 1, a, 2) + assert_array_equal(b, a) + assert_array_equal(c, [2] * np.size(a)) + + b, c = argsreduce(a > 0, a, 2) + assert_array_equal(b, a) + assert_array_equal(c, [2] * np.size(a)) + + +class TestFitMethod: + # fitting assumes continuous parameters + skip = ['ncf', 'ksone', 'kstwo', 'irwinhall'] + + def setup_method(self): + np.random.seed(1234) + + # skip these b/c deprecated, or only loc and scale arguments + fitSkipNonFinite = ['expon', 'norm', 'uniform', 'irwinhall'] + + @pytest.mark.parametrize('dist,args', distcont) + def test_fit_w_non_finite_data_values(self, dist, args): + """gh-10300""" + if dist in self.fitSkipNonFinite: + pytest.skip(f"{dist} fit known to fail or deprecated") + x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan]) + y = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf]) + distfunc = getattr(stats, dist) + assert_raises(ValueError, distfunc.fit, x, fscale=1) + assert_raises(ValueError, distfunc.fit, y, fscale=1) + + def test_fix_fit_2args_lognorm(self): + # Regression test for #1551. + np.random.seed(12345) + with np.errstate(all='ignore'): + x = stats.lognorm.rvs(0.25, 0., 20.0, size=20) + expected_shape = np.sqrt(((np.log(x) - np.log(20))**2).mean()) + assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)), + [expected_shape, 0, 20], atol=1e-8) + + def test_fix_fit_norm(self): + x = np.arange(1, 6) + + loc, scale = stats.norm.fit(x) + assert_almost_equal(loc, 3) + assert_almost_equal(scale, np.sqrt(2)) + + loc, scale = stats.norm.fit(x, floc=2) + assert_equal(loc, 2) + assert_equal(scale, np.sqrt(3)) + + loc, scale = stats.norm.fit(x, fscale=2) + assert_almost_equal(loc, 3) + assert_equal(scale, 2) + + def test_fix_fit_gamma(self): + x = np.arange(1, 6) + meanlog = np.log(x).mean() + + # A basic test of gamma.fit with floc=0. + floc = 0 + a, loc, scale = stats.gamma.fit(x, floc=floc) + s = np.log(x.mean()) - meanlog + assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5) + assert_equal(loc, floc) + assert_almost_equal(scale, x.mean()/a, decimal=8) + + # Regression tests for gh-2514. + # The problem was that if `floc=0` was given, any other fixed + # parameters were ignored. + f0 = 1 + floc = 0 + a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc) + assert_equal(a, f0) + assert_equal(loc, floc) + assert_almost_equal(scale, x.mean()/a, decimal=8) + + f0 = 2 + floc = 0 + a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc) + assert_equal(a, f0) + assert_equal(loc, floc) + assert_almost_equal(scale, x.mean()/a, decimal=8) + + # loc and scale fixed. + floc = 0 + fscale = 2 + a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale) + assert_equal(loc, floc) + assert_equal(scale, fscale) + c = meanlog - np.log(fscale) + assert_almost_equal(special.digamma(a), c) + + def test_fix_fit_beta(self): + # Test beta.fit when both floc and fscale are given. + + def mlefunc(a, b, x): + # Zeros of this function are critical points of + # the maximum likelihood function. + n = len(x) + s1 = np.log(x).sum() + s2 = np.log(1-x).sum() + psiab = special.psi(a + b) + func = [s1 - n * (-psiab + special.psi(a)), + s2 - n * (-psiab + special.psi(b))] + return func + + # Basic test with floc and fscale given. + x = np.array([0.125, 0.25, 0.5]) + a, b, loc, scale = stats.beta.fit(x, floc=0, fscale=1) + assert_equal(loc, 0) + assert_equal(scale, 1) + assert_allclose(mlefunc(a, b, x), [0, 0], atol=1e-6) + + # Basic test with f0, floc and fscale given. + # This is also a regression test for gh-2514. + x = np.array([0.125, 0.25, 0.5]) + a, b, loc, scale = stats.beta.fit(x, f0=2, floc=0, fscale=1) + assert_equal(a, 2) + assert_equal(loc, 0) + assert_equal(scale, 1) + da, db = mlefunc(a, b, x) + assert_allclose(db, 0, atol=1e-5) + + # Same floc and fscale values as above, but reverse the data + # and fix b (f1). + x2 = 1 - x + a2, b2, loc2, scale2 = stats.beta.fit(x2, f1=2, floc=0, fscale=1) + assert_equal(b2, 2) + assert_equal(loc2, 0) + assert_equal(scale2, 1) + da, db = mlefunc(a2, b2, x2) + assert_allclose(da, 0, atol=1e-5) + # a2 of this test should equal b from above. + assert_almost_equal(a2, b) + + # Check for detection of data out of bounds when floc and fscale + # are given. + assert_raises(ValueError, stats.beta.fit, x, floc=0.5, fscale=1) + y = np.array([0, .5, 1]) + assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1) + assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f0=2) + assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f1=2) + + # Check that attempting to fix all the parameters raises a ValueError. + assert_raises(ValueError, stats.beta.fit, y, f0=0, f1=1, + floc=2, fscale=3) + + def test_expon_fit(self): + x = np.array([2, 2, 4, 4, 4, 4, 4, 8]) + + loc, scale = stats.expon.fit(x) + assert_equal(loc, 2) # x.min() + assert_equal(scale, 2) # x.mean() - x.min() + + loc, scale = stats.expon.fit(x, fscale=3) + assert_equal(loc, 2) # x.min() + assert_equal(scale, 3) # fscale + + loc, scale = stats.expon.fit(x, floc=0) + assert_equal(loc, 0) # floc + assert_equal(scale, 4) # x.mean() - loc + + def test_lognorm_fit(self): + x = np.array([1.5, 3, 10, 15, 23, 59]) + lnxm1 = np.log(x - 1) + + shape, loc, scale = stats.lognorm.fit(x, floc=1) + assert_allclose(shape, lnxm1.std(), rtol=1e-12) + assert_equal(loc, 1) + assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12) + + shape, loc, scale = stats.lognorm.fit(x, floc=1, fscale=6) + assert_allclose(shape, np.sqrt(((lnxm1 - np.log(6))**2).mean()), + rtol=1e-12) + assert_equal(loc, 1) + assert_equal(scale, 6) + + shape, loc, scale = stats.lognorm.fit(x, floc=1, fix_s=0.75) + assert_equal(shape, 0.75) + assert_equal(loc, 1) + assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12) + + def test_uniform_fit(self): + x = np.array([1.0, 1.1, 1.2, 9.0]) + + loc, scale = stats.uniform.fit(x) + assert_equal(loc, x.min()) + assert_equal(scale, np.ptp(x)) + + loc, scale = stats.uniform.fit(x, floc=0) + assert_equal(loc, 0) + assert_equal(scale, x.max()) + + loc, scale = stats.uniform.fit(x, fscale=10) + assert_equal(loc, 0) + assert_equal(scale, 10) + + assert_raises(ValueError, stats.uniform.fit, x, floc=2.0) + assert_raises(ValueError, stats.uniform.fit, x, fscale=5.0) + + @pytest.mark.xslow + @pytest.mark.parametrize("method", ["MLE", "MM"]) + def test_fshapes(self, method): + # take a beta distribution, with shapes='a, b', and make sure that + # fa is equivalent to f0, and fb is equivalent to f1 + a, b = 3., 4. + x = stats.beta.rvs(a, b, size=100, random_state=1234) + res_1 = stats.beta.fit(x, f0=3., method=method) + res_2 = stats.beta.fit(x, fa=3., method=method) + assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12) + + res_2 = stats.beta.fit(x, fix_a=3., method=method) + assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12) + + res_3 = stats.beta.fit(x, f1=4., method=method) + res_4 = stats.beta.fit(x, fb=4., method=method) + assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12) + + res_4 = stats.beta.fit(x, fix_b=4., method=method) + assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12) + + # cannot specify both positional and named args at the same time + assert_raises(ValueError, stats.beta.fit, x, fa=1, f0=2, method=method) + + # check that attempting to fix all parameters raises a ValueError + assert_raises(ValueError, stats.beta.fit, x, fa=0, f1=1, + floc=2, fscale=3, method=method) + + # check that specifying floc, fscale and fshapes works for + # beta and gamma which override the generic fit method + res_5 = stats.beta.fit(x, fa=3., floc=0, fscale=1, method=method) + aa, bb, ll, ss = res_5 + assert_equal([aa, ll, ss], [3., 0, 1]) + + # gamma distribution + a = 3. + data = stats.gamma.rvs(a, size=100) + aa, ll, ss = stats.gamma.fit(data, fa=a, method=method) + assert_equal(aa, a) + + @pytest.mark.parametrize("method", ["MLE", "MM"]) + def test_extra_params(self, method): + # unknown parameters should raise rather than be silently ignored + dist = stats.exponnorm + data = dist.rvs(K=2, size=100) + dct = dict(enikibeniki=-101) + assert_raises(TypeError, dist.fit, data, **dct, method=method) + + +class TestFrozen: + def setup_method(self): + np.random.seed(1234) + + # Test that a frozen distribution gives the same results as the original + # object. + # + # Only tested for the normal distribution (with loc and scale specified) + # and for the gamma distribution (with a shape parameter specified). + def test_norm(self): + dist = stats.norm + frozen = stats.norm(loc=10.0, scale=3.0) + + result_f = frozen.pdf(20.0) + result = dist.pdf(20.0, loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.cdf(20.0) + result = dist.cdf(20.0, loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.ppf(0.25) + result = dist.ppf(0.25, loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.isf(0.25) + result = dist.isf(0.25, loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.sf(10.0) + result = dist.sf(10.0, loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.median() + result = dist.median(loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.mean() + result = dist.mean(loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.var() + result = dist.var(loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.std() + result = dist.std(loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.entropy() + result = dist.entropy(loc=10.0, scale=3.0) + assert_equal(result_f, result) + + result_f = frozen.moment(2) + result = dist.moment(2, loc=10.0, scale=3.0) + assert_equal(result_f, result) + + assert_equal(frozen.a, dist.a) + assert_equal(frozen.b, dist.b) + + def test_gamma(self): + a = 2.0 + dist = stats.gamma + frozen = stats.gamma(a) + + result_f = frozen.pdf(20.0) + result = dist.pdf(20.0, a) + assert_equal(result_f, result) + + result_f = frozen.cdf(20.0) + result = dist.cdf(20.0, a) + assert_equal(result_f, result) + + result_f = frozen.ppf(0.25) + result = dist.ppf(0.25, a) + assert_equal(result_f, result) + + result_f = frozen.isf(0.25) + result = dist.isf(0.25, a) + assert_equal(result_f, result) + + result_f = frozen.sf(10.0) + result = dist.sf(10.0, a) + assert_equal(result_f, result) + + result_f = frozen.median() + result = dist.median(a) + assert_equal(result_f, result) + + result_f = frozen.mean() + result = dist.mean(a) + assert_equal(result_f, result) + + result_f = frozen.var() + result = dist.var(a) + assert_equal(result_f, result) + + result_f = frozen.std() + result = dist.std(a) + assert_equal(result_f, result) + + result_f = frozen.entropy() + result = dist.entropy(a) + assert_equal(result_f, result) + + result_f = frozen.moment(2) + result = dist.moment(2, a) + assert_equal(result_f, result) + + assert_equal(frozen.a, frozen.dist.a) + assert_equal(frozen.b, frozen.dist.b) + + def test_regression_ticket_1293(self): + # Create a frozen distribution. + frozen = stats.lognorm(1) + # Call one of its methods that does not take any keyword arguments. + m1 = frozen.moment(2) + # Now call a method that takes a keyword argument. + frozen.stats(moments='mvsk') + # Call moment(2) again. + # After calling stats(), the following was raising an exception. + # So this test passes if the following does not raise an exception. + m2 = frozen.moment(2) + # The following should also be true, of course. But it is not + # the focus of this test. + assert_equal(m1, m2) + + def test_ab(self): + # test that the support of a frozen distribution + # (i) remains frozen even if it changes for the original one + # (ii) is actually correct if the shape parameters are such that + # the values of [a, b] are not the default [0, inf] + # take a genpareto as an example where the support + # depends on the value of the shape parameter: + # for c > 0: a, b = 0, inf + # for c < 0: a, b = 0, -1/c + + c = -0.1 + rv = stats.genpareto(c=c) + a, b = rv.dist._get_support(c) + assert_equal([a, b], [0., 10.]) + + c = 0.1 + stats.genpareto.pdf(0, c=c) + assert_equal(rv.dist._get_support(c), [0, np.inf]) + + c = -0.1 + rv = stats.genpareto(c=c) + a, b = rv.dist._get_support(c) + assert_equal([a, b], [0., 10.]) + + c = 0.1 + stats.genpareto.pdf(0, c) # this should NOT change genpareto.b + assert_equal((rv.dist.a, rv.dist.b), stats.genpareto._get_support(c)) + + rv1 = stats.genpareto(c=0.1) + assert_(rv1.dist is not rv.dist) + + # c >= 0: a, b = [0, inf] + for c in [1., 0.]: + c = np.asarray(c) + rv = stats.genpareto(c=c) + a, b = rv.a, rv.b + assert_equal(a, 0.) + assert_(np.isposinf(b)) + + # c < 0: a=0, b=1/|c| + c = np.asarray(-2.) + a, b = stats.genpareto._get_support(c) + assert_allclose([a, b], [0., 0.5]) + + def test_rv_frozen_in_namespace(self): + # Regression test for gh-3522 + assert_(hasattr(stats.distributions, 'rv_frozen')) + + def test_random_state(self): + # only check that the random_state attribute exists, + frozen = stats.norm() + assert_(hasattr(frozen, 'random_state')) + + # ... that it can be set, + frozen.random_state = 42 + assert_equal(frozen.random_state.get_state(), + np.random.RandomState(42).get_state()) + + # ... and that .rvs method accepts it as an argument + rndm = np.random.RandomState(1234) + frozen.rvs(size=8, random_state=rndm) + + def test_pickling(self): + # test that a frozen instance pickles and unpickles + # (this method is a clone of common_tests.check_pickling) + beta = stats.beta(2.3098496451481823, 0.62687954300963677) + poiss = stats.poisson(3.) + sample = stats.rv_discrete(values=([0, 1, 2, 3], + [0.1, 0.2, 0.3, 0.4])) + + for distfn in [beta, poiss, sample]: + distfn.random_state = 1234 + distfn.rvs(size=8) + s = pickle.dumps(distfn) + r0 = distfn.rvs(size=8) + + unpickled = pickle.loads(s) + r1 = unpickled.rvs(size=8) + assert_equal(r0, r1) + + # also smoke test some methods + medians = [distfn.ppf(0.5), unpickled.ppf(0.5)] + assert_equal(medians[0], medians[1]) + assert_equal(distfn.cdf(medians[0]), + unpickled.cdf(medians[1])) + + def test_expect(self): + # smoke test the expect method of the frozen distribution + # only take a gamma w/loc and scale and poisson with loc specified + def func(x): + return x + + gm = stats.gamma(a=2, loc=3, scale=4) + with np.errstate(invalid="ignore", divide="ignore"): + gm_val = gm.expect(func, lb=1, ub=2, conditional=True) + gamma_val = stats.gamma.expect(func, args=(2,), loc=3, scale=4, + lb=1, ub=2, conditional=True) + assert_allclose(gm_val, gamma_val) + + p = stats.poisson(3, loc=4) + p_val = p.expect(func) + poisson_val = stats.poisson.expect(func, args=(3,), loc=4) + assert_allclose(p_val, poisson_val) + + +class TestExpect: + # Test for expect method. + # + # Uses normal distribution and beta distribution for finite bounds, and + # hypergeom for discrete distribution with finite support + def test_norm(self): + v = stats.norm.expect(lambda x: (x-5)*(x-5), loc=5, scale=2) + assert_almost_equal(v, 4, decimal=14) + + m = stats.norm.expect(lambda x: (x), loc=5, scale=2) + assert_almost_equal(m, 5, decimal=14) + + lb = stats.norm.ppf(0.05, loc=5, scale=2) + ub = stats.norm.ppf(0.95, loc=5, scale=2) + prob90 = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub) + assert_almost_equal(prob90, 0.9, decimal=14) + + prob90c = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub, + conditional=True) + assert_almost_equal(prob90c, 1., decimal=14) + + def test_beta(self): + # case with finite support interval + v = stats.beta.expect(lambda x: (x-19/3.)*(x-19/3.), args=(10, 5), + loc=5, scale=2) + assert_almost_equal(v, 1./18., decimal=13) + + m = stats.beta.expect(lambda x: x, args=(10, 5), loc=5., scale=2.) + assert_almost_equal(m, 19/3., decimal=13) + + ub = stats.beta.ppf(0.95, 10, 10, loc=5, scale=2) + lb = stats.beta.ppf(0.05, 10, 10, loc=5, scale=2) + prob90 = stats.beta.expect(lambda x: 1., args=(10, 10), loc=5., + scale=2., lb=lb, ub=ub, conditional=False) + assert_almost_equal(prob90, 0.9, decimal=13) + + prob90c = stats.beta.expect(lambda x: 1, args=(10, 10), loc=5, + scale=2, lb=lb, ub=ub, conditional=True) + assert_almost_equal(prob90c, 1., decimal=13) + + def test_hypergeom(self): + # test case with finite bounds + + # without specifying bounds + m_true, v_true = stats.hypergeom.stats(20, 10, 8, loc=5.) + m = stats.hypergeom.expect(lambda x: x, args=(20, 10, 8), loc=5.) + assert_almost_equal(m, m_true, decimal=13) + + v = stats.hypergeom.expect(lambda x: (x-9.)**2, args=(20, 10, 8), + loc=5.) + assert_almost_equal(v, v_true, decimal=14) + + # with bounds, bounds equal to shifted support + v_bounds = stats.hypergeom.expect(lambda x: (x-9.)**2, + args=(20, 10, 8), + loc=5., lb=5, ub=13) + assert_almost_equal(v_bounds, v_true, decimal=14) + + # drop boundary points + prob_true = 1-stats.hypergeom.pmf([5, 13], 20, 10, 8, loc=5).sum() + prob_bounds = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), + loc=5., lb=6, ub=12) + assert_almost_equal(prob_bounds, prob_true, decimal=13) + + # conditional + prob_bc = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), loc=5., + lb=6, ub=12, conditional=True) + assert_almost_equal(prob_bc, 1, decimal=14) + + # check simple integral + prob_b = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), + lb=0, ub=8) + assert_almost_equal(prob_b, 1, decimal=13) + + def test_poisson(self): + # poisson, use lower bound only + prob_bounds = stats.poisson.expect(lambda x: 1, args=(2,), lb=3, + conditional=False) + prob_b_true = 1-stats.poisson.cdf(2, 2) + assert_almost_equal(prob_bounds, prob_b_true, decimal=14) + + prob_lb = stats.poisson.expect(lambda x: 1, args=(2,), lb=2, + conditional=True) + assert_almost_equal(prob_lb, 1, decimal=14) + + def test_genhalflogistic(self): + # genhalflogistic, changes upper bound of support in _argcheck + # regression test for gh-2622 + halflog = stats.genhalflogistic + # check consistency when calling expect twice with the same input + res1 = halflog.expect(args=(1.5,)) + halflog.expect(args=(0.5,)) + res2 = halflog.expect(args=(1.5,)) + assert_almost_equal(res1, res2, decimal=14) + + def test_rice_overflow(self): + # rice.pdf(999, 0.74) was inf since special.i0 silently overflows + # check that using i0e fixes it + assert_(np.isfinite(stats.rice.pdf(999, 0.74))) + + assert_(np.isfinite(stats.rice.expect(lambda x: 1, args=(0.74,)))) + assert_(np.isfinite(stats.rice.expect(lambda x: 2, args=(0.74,)))) + assert_(np.isfinite(stats.rice.expect(lambda x: 3, args=(0.74,)))) + + def test_logser(self): + # test a discrete distribution with infinite support and loc + p, loc = 0.3, 3 + res_0 = stats.logser.expect(lambda k: k, args=(p,)) + # check against the correct answer (sum of a geom series) + assert_allclose(res_0, + p / (p - 1.) / np.log(1. - p), atol=1e-15) + + # now check it with `loc` + res_l = stats.logser.expect(lambda k: k, args=(p,), loc=loc) + assert_allclose(res_l, res_0 + loc, atol=1e-15) + + def test_skellam(self): + # Use a discrete distribution w/ bi-infinite support. Compute two first + # moments and compare to known values (cf skellam.stats) + p1, p2 = 18, 22 + m1 = stats.skellam.expect(lambda x: x, args=(p1, p2)) + m2 = stats.skellam.expect(lambda x: x**2, args=(p1, p2)) + assert_allclose(m1, p1 - p2, atol=1e-12) + assert_allclose(m2 - m1**2, p1 + p2, atol=1e-12) + + def test_randint(self): + # Use a discrete distribution w/ parameter-dependent support, which + # is larger than the default chunksize + lo, hi = 0, 113 + res = stats.randint.expect(lambda x: x, (lo, hi)) + assert_allclose(res, + sum(_ for _ in range(lo, hi)) / (hi - lo), atol=1e-15) + + def test_zipf(self): + # Test that there is no infinite loop even if the sum diverges + assert_warns(RuntimeWarning, stats.zipf.expect, + lambda x: x**2, (2,)) + + def test_discrete_kwds(self): + # check that discrete expect accepts keywords to control the summation + n0 = stats.poisson.expect(lambda x: 1, args=(2,)) + n1 = stats.poisson.expect(lambda x: 1, args=(2,), + maxcount=1001, chunksize=32, tolerance=1e-8) + assert_almost_equal(n0, n1, decimal=14) + + def test_moment(self): + # test the .moment() method: compute a higher moment and compare to + # a known value + def poiss_moment5(mu): + return mu**5 + 10*mu**4 + 25*mu**3 + 15*mu**2 + mu + + for mu in [5, 7]: + m5 = stats.poisson.moment(5, mu) + assert_allclose(m5, poiss_moment5(mu), rtol=1e-10) + + def test_challenging_cases_gh8928(self): + # Several cases where `expect` failed to produce a correct result were + # reported in gh-8928. Check that these cases have been resolved. + assert_allclose(stats.norm.expect(loc=36, scale=1.0), 36) + assert_allclose(stats.norm.expect(loc=40, scale=1.0), 40) + assert_allclose(stats.norm.expect(loc=10, scale=0.1), 10) + assert_allclose(stats.gamma.expect(args=(148,)), 148) + assert_allclose(stats.logistic.expect(loc=85), 85) + + def test_lb_ub_gh15855(self): + # Make sure changes to `expect` made in gh15855 treat lb/ub correctly + dist = stats.uniform + ref = dist.mean(loc=10, scale=5) # 12.5 + # moment over whole distribution + assert_allclose(dist.expect(loc=10, scale=5), ref) + # moment over whole distribution, lb and ub outside of support + assert_allclose(dist.expect(loc=10, scale=5, lb=9, ub=16), ref) + # moment over 60% of distribution, [lb, ub] centered within support + assert_allclose(dist.expect(loc=10, scale=5, lb=11, ub=14), ref*0.6) + # moment over truncated distribution, essentially + assert_allclose(dist.expect(loc=10, scale=5, lb=11, ub=14, + conditional=True), ref) + # moment over 40% of distribution, [lb, ub] not centered within support + assert_allclose(dist.expect(loc=10, scale=5, lb=11, ub=13), 12*0.4) + # moment with lb > ub + assert_allclose(dist.expect(loc=10, scale=5, lb=13, ub=11), -12*0.4) + # moment with lb > ub, conditional + assert_allclose(dist.expect(loc=10, scale=5, lb=13, ub=11, + conditional=True), 12) + + +class TestNct: + def test_nc_parameter(self): + # Parameter values c<=0 were not enabled (gh-2402). + # For negative values c and for c=0 results of rv.cdf(0) below were nan + rv = stats.nct(5, 0) + assert_equal(rv.cdf(0), 0.5) + rv = stats.nct(5, -1) + assert_almost_equal(rv.cdf(0), 0.841344746069, decimal=10) + + def test_broadcasting(self): + res = stats.nct.pdf(5, np.arange(4, 7)[:, None], + np.linspace(0.1, 1, 4)) + expected = array([[0.00321886, 0.00557466, 0.00918418, 0.01442997], + [0.00217142, 0.00395366, 0.00683888, 0.01126276], + [0.00153078, 0.00291093, 0.00525206, 0.00900815]]) + assert_allclose(res, expected, rtol=1e-5) + + def test_variance_gh_issue_2401(self): + # Computation of the variance of a non-central t-distribution resulted + # in a TypeError: ufunc 'isinf' not supported for the input types, + # and the inputs could not be safely coerced to any supported types + # according to the casting rule 'safe' + rv = stats.nct(4, 0) + assert_equal(rv.var(), 2.0) + + def test_nct_inf_moments(self): + # n-th moment of nct only exists for df > n + m, v, s, k = stats.nct.stats(df=0.9, nc=0.3, moments='mvsk') + assert_equal([m, v, s, k], [np.nan, np.nan, np.nan, np.nan]) + + m, v, s, k = stats.nct.stats(df=1.9, nc=0.3, moments='mvsk') + assert_(np.isfinite(m)) + assert_equal([v, s, k], [np.nan, np.nan, np.nan]) + + m, v, s, k = stats.nct.stats(df=3.1, nc=0.3, moments='mvsk') + assert_(np.isfinite([m, v, s]).all()) + assert_equal(k, np.nan) + + def test_nct_stats_large_df_values(self): + # previously gamma function was used which lost precision at df=345 + # cf. https://github.com/scipy/scipy/issues/12919 for details + nct_mean_df_1000 = stats.nct.mean(1000, 2) + nct_stats_df_1000 = stats.nct.stats(1000, 2) + # These expected values were computed with mpmath. They were also + # verified with the Wolfram Alpha expressions: + # Mean[NoncentralStudentTDistribution[1000, 2]] + # Var[NoncentralStudentTDistribution[1000, 2]] + expected_stats_df_1000 = [2.0015015641422464, 1.0040115288163005] + assert_allclose(nct_mean_df_1000, expected_stats_df_1000[0], + rtol=1e-10) + assert_allclose(nct_stats_df_1000, expected_stats_df_1000, + rtol=1e-10) + # and a bigger df value + nct_mean = stats.nct.mean(100000, 2) + nct_stats = stats.nct.stats(100000, 2) + # These expected values were computed with mpmath. + expected_stats = [2.0000150001562518, 1.0000400011500288] + assert_allclose(nct_mean, expected_stats[0], rtol=1e-10) + assert_allclose(nct_stats, expected_stats, rtol=1e-9) + + def test_cdf_large_nc(self): + # gh-17916 reported a crash with large `nc` values + assert_allclose(stats.nct.cdf(2, 2, float(2**16)), 0) + + # PDF reference values were computed with mpmath + # with 100 digits of precision + + # def nct_pdf(x, df, nc): + # x = mp.mpf(x) + # n = mp.mpf(df) + # nc = mp.mpf(nc) + + # x2 = x*x + # ncx2 = nc*nc*x2 + # fac1 = n + x2 + # trm1 = (n/2.*mp.log(n) + mp.loggamma(n + mp.one) + # - (n * mp.log(2.) + nc*nc/2 + (n/2)*mp.log(fac1) + # + mp.loggamma(n/2))) + # Px = mp.exp(trm1) + # valF = ncx2 / (2*fac1) + # trm1 = (mp.sqrt(2)*nc*x*mp.hyp1f1(n/2+1, 1.5, valF) + # / (fac1*mp.gamma((n+1)/2))) + # trm2 = (mp.hyp1f1((n+1)/2, 0.5, valF) + # / (mp.sqrt(fac1)*mp.gamma(n/2 + mp.one))) + # Px *= trm1+trm2 + # return float(Px) + + @pytest.mark.parametrize("x, df, nc, expected", [ + (10000, 10, 16, 3.394646922945872e-30), + (-10, 8, 16, 4.282769500264159e-70) + ]) + def test_pdf_large_nc(self, x, df, nc, expected): + # gh-#20693 reported zero values for large `nc` values + assert_allclose(stats.nct.pdf(x, df, nc), expected, rtol=1e-12) + + +class TestRecipInvGauss: + + def test_pdf_endpoint(self): + p = stats.recipinvgauss.pdf(0, 0.6) + assert p == 0.0 + + def test_logpdf_endpoint(self): + logp = stats.recipinvgauss.logpdf(0, 0.6) + assert logp == -np.inf + + def test_cdf_small_x(self): + # The expected value was computer with mpmath: + # + # import mpmath + # + # mpmath.mp.dps = 100 + # + # def recipinvgauss_cdf_mp(x, mu): + # x = mpmath.mpf(x) + # mu = mpmath.mpf(mu) + # trm1 = 1/mu - x + # trm2 = 1/mu + x + # isqx = 1/mpmath.sqrt(x) + # return (mpmath.ncdf(-isqx*trm1) + # - mpmath.exp(2/mu)*mpmath.ncdf(-isqx*trm2)) + # + p = stats.recipinvgauss.cdf(0.05, 0.5) + expected = 6.590396159501331e-20 + assert_allclose(p, expected, rtol=1e-14) + + def test_sf_large_x(self): + # The expected value was computed with mpmath; see test_cdf_small. + p = stats.recipinvgauss.sf(80, 0.5) + expected = 2.699819200556787e-18 + assert_allclose(p, expected, 5e-15) + + +class TestRice: + def test_rice_zero_b(self): + # rice distribution should work with b=0, cf gh-2164 + x = [0.2, 1., 5.] + assert_(np.isfinite(stats.rice.pdf(x, b=0.)).all()) + assert_(np.isfinite(stats.rice.logpdf(x, b=0.)).all()) + assert_(np.isfinite(stats.rice.cdf(x, b=0.)).all()) + assert_(np.isfinite(stats.rice.logcdf(x, b=0.)).all()) + + q = [0.1, 0.1, 0.5, 0.9] + assert_(np.isfinite(stats.rice.ppf(q, b=0.)).all()) + + mvsk = stats.rice.stats(0, moments='mvsk') + assert_(np.isfinite(mvsk).all()) + + # furthermore, pdf is continuous as b\to 0 + # rice.pdf(x, b\to 0) = x exp(-x^2/2) + O(b^2) + # see e.g. Abramovich & Stegun 9.6.7 & 9.6.10 + b = 1e-8 + assert_allclose(stats.rice.pdf(x, 0), stats.rice.pdf(x, b), + atol=b, rtol=0) + + def test_rice_rvs(self): + rvs = stats.rice.rvs + assert_equal(rvs(b=3.).size, 1) + assert_equal(rvs(b=3., size=(3, 5)).shape, (3, 5)) + + def test_rice_gh9836(self): + # test that gh-9836 is resolved; previously jumped to 1 at the end + + cdf = stats.rice.cdf(np.arange(10, 160, 10), np.arange(10, 160, 10)) + # Generated in R + # library(VGAM) + # options(digits=16) + # x = seq(10, 150, 10) + # print(price(x, sigma=1, vee=x)) + cdf_exp = [0.4800278103504522, 0.4900233218590353, 0.4933500379379548, + 0.4950128317658719, 0.4960103776798502, 0.4966753655438764, + 0.4971503395812474, 0.4975065620443196, 0.4977836197921638, + 0.4980052636649550, 0.4981866072661382, 0.4983377260666599, + 0.4984655952615694, 0.4985751970541413, 0.4986701850071265] + assert_allclose(cdf, cdf_exp) + + probabilities = np.arange(0.1, 1, 0.1) + ppf = stats.rice.ppf(probabilities, 500/4, scale=4) + # Generated in R + # library(VGAM) + # options(digits=16) + # p = seq(0.1, .9, by = .1) + # print(qrice(p, vee = 500, sigma = 4)) + ppf_exp = [494.8898762347361, 496.6495690858350, 497.9184315188069, + 499.0026277378915, 500.0159999146250, 501.0293721352668, + 502.1135684981884, 503.3824312270405, 505.1421247157822] + assert_allclose(ppf, ppf_exp) + + ppf = scipy.stats.rice.ppf(0.5, np.arange(10, 150, 10)) + # Generated in R + # library(VGAM) + # options(digits=16) + # b <- seq(10, 140, 10) + # print(qrice(0.5, vee = b, sigma = 1)) + ppf_exp = [10.04995862522287, 20.02499480078302, 30.01666512465732, + 40.01249934924363, 50.00999966676032, 60.00833314046875, + 70.00714273568241, 80.00624991862573, 90.00555549840364, + 100.00499995833597, 110.00454542324384, 120.00416664255323, + 130.00384613488120, 140.00357141338748] + assert_allclose(ppf, ppf_exp) + + +class TestErlang: + def setup_method(self): + np.random.seed(1234) + + def test_erlang_runtimewarning(self): + # erlang should generate a RuntimeWarning if a non-integer + # shape parameter is used. + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + + # The non-integer shape parameter 1.3 should trigger a + # RuntimeWarning + assert_raises(RuntimeWarning, + stats.erlang.rvs, 1.3, loc=0, scale=1, size=4) + + # Calling the fit method with `f0` set to an integer should + # *not* trigger a RuntimeWarning. It should return the same + # values as gamma.fit(...). + data = [0.5, 1.0, 2.0, 4.0] + result_erlang = stats.erlang.fit(data, f0=1) + result_gamma = stats.gamma.fit(data, f0=1) + assert_allclose(result_erlang, result_gamma, rtol=1e-3) + + def test_gh_pr_10949_argcheck(self): + assert_equal(stats.erlang.pdf(0.5, a=[1, -1]), + stats.gamma.pdf(0.5, a=[1, -1])) + + +class TestRayleigh: + def setup_method(self): + np.random.seed(987654321) + + # gh-6227 + def test_logpdf(self): + y = stats.rayleigh.logpdf(50) + assert_allclose(y, -1246.0879769945718) + + def test_logsf(self): + y = stats.rayleigh.logsf(50) + assert_allclose(y, -1250) + + @pytest.mark.parametrize("rvs_loc,rvs_scale", [(0.85373171, 0.86932204), + (0.20558821, 0.61621008)]) + def test_fit(self, rvs_loc, rvs_scale): + data = stats.rayleigh.rvs(size=250, loc=rvs_loc, scale=rvs_scale) + + def scale_mle(data, floc): + return (np.sum((data - floc) ** 2) / (2 * len(data))) ** .5 + + # when `floc` is provided, `scale` is found with an analytical formula + scale_expect = scale_mle(data, rvs_loc) + loc, scale = stats.rayleigh.fit(data, floc=rvs_loc) + assert_equal(loc, rvs_loc) + assert_equal(scale, scale_expect) + + # when `fscale` is fixed, superclass fit is used to determine `loc`. + loc, scale = stats.rayleigh.fit(data, fscale=.6) + assert_equal(scale, .6) + + # with both parameters free, one dimensional optimization is done + # over a new function that takes into account the dependent relation + # of `scale` to `loc`. + loc, scale = stats.rayleigh.fit(data) + # test that `scale` is defined by its relation to `loc` + assert_equal(scale, scale_mle(data, loc)) + + @pytest.mark.parametrize("rvs_loc,rvs_scale", [[0.74, 0.01], + [0.08464463, 0.12069025]]) + def test_fit_comparison_super_method(self, rvs_loc, rvs_scale): + # test that the objective function result of the analytical MLEs is + # less than or equal to that of the numerically optimized estimate + data = stats.rayleigh.rvs(size=250, loc=rvs_loc, scale=rvs_scale) + _assert_less_or_close_loglike(stats.rayleigh, data) + + def test_fit_warnings(self): + assert_fit_warnings(stats.rayleigh) + + def test_fit_gh17088(self): + # `rayleigh.fit` could return a location that was inconsistent with + # the data. See gh-17088. + rng = np.random.default_rng(456) + loc, scale, size = 50, 600, 500 + rvs = stats.rayleigh.rvs(loc, scale, size=size, random_state=rng) + loc_fit, _ = stats.rayleigh.fit(rvs) + assert loc_fit < np.min(rvs) + loc_fit, scale_fit = stats.rayleigh.fit(rvs, fscale=scale) + assert loc_fit < np.min(rvs) + assert scale_fit == scale + + +class TestExponWeib: + + def test_pdf_logpdf(self): + # Regression test for gh-3508. + x = 0.1 + a = 1.0 + c = 100.0 + p = stats.exponweib.pdf(x, a, c) + logp = stats.exponweib.logpdf(x, a, c) + # Expected values were computed with mpmath. + assert_allclose([p, logp], + [1.0000000000000054e-97, -223.35075402042244]) + + def test_a_is_1(self): + # For issue gh-3508. + # Check that when a=1, the pdf and logpdf methods of exponweib are the + # same as those of weibull_min. + x = np.logspace(-4, -1, 4) + a = 1 + c = 100 + + p = stats.exponweib.pdf(x, a, c) + expected = stats.weibull_min.pdf(x, c) + assert_allclose(p, expected) + + logp = stats.exponweib.logpdf(x, a, c) + expected = stats.weibull_min.logpdf(x, c) + assert_allclose(logp, expected) + + def test_a_is_1_c_is_1(self): + # When a = 1 and c = 1, the distribution is exponential. + x = np.logspace(-8, 1, 10) + a = 1 + c = 1 + + p = stats.exponweib.pdf(x, a, c) + expected = stats.expon.pdf(x) + assert_allclose(p, expected) + + logp = stats.exponweib.logpdf(x, a, c) + expected = stats.expon.logpdf(x) + assert_allclose(logp, expected) + + # Reference values were computed with mpmath, e.g: + # + # from mpmath import mp + # + # def mp_sf(x, a, c): + # x = mp.mpf(x) + # a = mp.mpf(a) + # c = mp.mpf(c) + # return -mp.powm1(-mp.expm1(-x**c)), a) + # + # mp.dps = 100 + # print(float(mp_sf(1, 2.5, 0.75))) + # + # prints + # + # 0.6823127476985246 + # + @pytest.mark.parametrize( + 'x, a, c, ref', + [(1, 2.5, 0.75, 0.6823127476985246), + (50, 2.5, 0.75, 1.7056666054719663e-08), + (125, 2.5, 0.75, 1.4534393150714602e-16), + (250, 2.5, 0.75, 1.2391389689773512e-27), + (250, 0.03125, 0.75, 1.548923711221689e-29), + (3, 0.03125, 3.0, 5.873527551689983e-14), + (2e80, 10.0, 0.02, 2.9449084156902135e-17)] + ) + def test_sf(self, x, a, c, ref): + sf = stats.exponweib.sf(x, a, c) + assert_allclose(sf, ref, rtol=1e-14) + + # Reference values were computed with mpmath, e.g. + # + # from mpmath import mp + # + # def mp_isf(p, a, c): + # p = mp.mpf(p) + # a = mp.mpf(a) + # c = mp.mpf(c) + # return (-mp.log(-mp.expm1(mp.log1p(-p)/a)))**(1/c) + # + # mp.dps = 100 + # print(float(mp_isf(0.25, 2.5, 0.75))) + # + # prints + # + # 2.8946008178158924 + # + @pytest.mark.parametrize( + 'p, a, c, ref', + [(0.25, 2.5, 0.75, 2.8946008178158924), + (3e-16, 2.5, 0.75, 121.77966713102938), + (1e-12, 1, 2, 5.256521769756932), + (2e-13, 0.03125, 3, 2.953915059484589), + (5e-14, 10.0, 0.02, 7.57094886384687e+75)] + ) + def test_isf(self, p, a, c, ref): + isf = stats.exponweib.isf(p, a, c) + assert_allclose(isf, ref, rtol=5e-14) + + # Reference values computed with mpmath. + @pytest.mark.parametrize('x, a, c, ref', + [(2, 3, 8, -1.9848783170128456e-111), + (1000, 0.5, 0.75, -2.946296827524972e-78)]) + def test_logcdf(self, x, a, c, ref): + logcdf = stats.exponweib.logcdf(x, a, c) + assert_allclose(logcdf, ref, rtol=5e-15) + + # Reference values computed with mpmath. + @pytest.mark.parametrize('x, a, c, ref', + [(1e-65, 1.5, 1.25, -1.333521432163324e-122), + (2e-10, 2, 10, -1.0485760000000007e-194)]) + def test_logsf(self, x, a, c, ref): + logsf = stats.exponweib.logsf(x, a, c) + assert_allclose(logsf, ref, rtol=5e-15) + + +class TestFatigueLife: + + def test_sf_tail(self): + # Expected value computed with mpmath: + # import mpmath + # mpmath.mp.dps = 80 + # x = mpmath.mpf(800.0) + # c = mpmath.mpf(2.5) + # s = float(1 - mpmath.ncdf(1/c * (mpmath.sqrt(x) + # - 1/mpmath.sqrt(x)))) + # print(s) + # Output: + # 6.593376447038406e-30 + s = stats.fatiguelife.sf(800.0, 2.5) + assert_allclose(s, 6.593376447038406e-30, rtol=1e-13) + + def test_isf_tail(self): + # See test_sf_tail for the mpmath code. + p = 6.593376447038406e-30 + q = stats.fatiguelife.isf(p, 2.5) + assert_allclose(q, 800.0, rtol=1e-13) + + +class TestWeibull: + + def test_logpdf(self): + # gh-6217 + y = stats.weibull_min.logpdf(0, 1) + assert_equal(y, 0) + + def test_with_maxima_distrib(self): + # Tests for weibull_min and weibull_max. + # The expected values were computed using the symbolic algebra + # program 'maxima' with the package 'distrib', which has + # 'pdf_weibull' and 'cdf_weibull'. The mapping between the + # scipy and maxima functions is as follows: + # ----------------------------------------------------------------- + # scipy maxima + # --------------------------------- ------------------------------ + # weibull_min.pdf(x, a, scale=b) pdf_weibull(x, a, b) + # weibull_min.logpdf(x, a, scale=b) log(pdf_weibull(x, a, b)) + # weibull_min.cdf(x, a, scale=b) cdf_weibull(x, a, b) + # weibull_min.logcdf(x, a, scale=b) log(cdf_weibull(x, a, b)) + # weibull_min.sf(x, a, scale=b) 1 - cdf_weibull(x, a, b) + # weibull_min.logsf(x, a, scale=b) log(1 - cdf_weibull(x, a, b)) + # + # weibull_max.pdf(x, a, scale=b) pdf_weibull(-x, a, b) + # weibull_max.logpdf(x, a, scale=b) log(pdf_weibull(-x, a, b)) + # weibull_max.cdf(x, a, scale=b) 1 - cdf_weibull(-x, a, b) + # weibull_max.logcdf(x, a, scale=b) log(1 - cdf_weibull(-x, a, b)) + # weibull_max.sf(x, a, scale=b) cdf_weibull(-x, a, b) + # weibull_max.logsf(x, a, scale=b) log(cdf_weibull(-x, a, b)) + # ----------------------------------------------------------------- + x = 1.5 + a = 2.0 + b = 3.0 + + # weibull_min + + p = stats.weibull_min.pdf(x, a, scale=b) + assert_allclose(p, np.exp(-0.25)/3) + + lp = stats.weibull_min.logpdf(x, a, scale=b) + assert_allclose(lp, -0.25 - np.log(3)) + + c = stats.weibull_min.cdf(x, a, scale=b) + assert_allclose(c, -special.expm1(-0.25)) + + lc = stats.weibull_min.logcdf(x, a, scale=b) + assert_allclose(lc, np.log(-special.expm1(-0.25))) + + s = stats.weibull_min.sf(x, a, scale=b) + assert_allclose(s, np.exp(-0.25)) + + ls = stats.weibull_min.logsf(x, a, scale=b) + assert_allclose(ls, -0.25) + + # Also test using a large value x, for which computing the survival + # function using the CDF would result in 0. + s = stats.weibull_min.sf(30, 2, scale=3) + assert_allclose(s, np.exp(-100)) + + ls = stats.weibull_min.logsf(30, 2, scale=3) + assert_allclose(ls, -100) + + # weibull_max + x = -1.5 + + p = stats.weibull_max.pdf(x, a, scale=b) + assert_allclose(p, np.exp(-0.25)/3) + + lp = stats.weibull_max.logpdf(x, a, scale=b) + assert_allclose(lp, -0.25 - np.log(3)) + + c = stats.weibull_max.cdf(x, a, scale=b) + assert_allclose(c, np.exp(-0.25)) + + lc = stats.weibull_max.logcdf(x, a, scale=b) + assert_allclose(lc, -0.25) + + s = stats.weibull_max.sf(x, a, scale=b) + assert_allclose(s, -special.expm1(-0.25)) + + ls = stats.weibull_max.logsf(x, a, scale=b) + assert_allclose(ls, np.log(-special.expm1(-0.25))) + + # Also test using a value of x close to 0, for which computing the + # survival function using the CDF would result in 0. + s = stats.weibull_max.sf(-1e-9, 2, scale=3) + assert_allclose(s, -special.expm1(-1/9000000000000000000)) + + ls = stats.weibull_max.logsf(-1e-9, 2, scale=3) + assert_allclose(ls, np.log(-special.expm1(-1/9000000000000000000))) + + @pytest.mark.parametrize('scale', [1.0, 0.1]) + def test_delta_cdf(self, scale): + # Expected value computed with mpmath: + # + # def weibull_min_sf(x, k, scale): + # x = mpmath.mpf(x) + # k = mpmath.mpf(k) + # scale =mpmath.mpf(scale) + # return mpmath.exp(-(x/scale)**k) + # + # >>> import mpmath + # >>> mpmath.mp.dps = 60 + # >>> sf1 = weibull_min_sf(7.5, 3, 1) + # >>> sf2 = weibull_min_sf(8.0, 3, 1) + # >>> float(sf1 - sf2) + # 6.053624060118734e-184 + # + delta = stats.weibull_min._delta_cdf(scale*7.5, scale*8, 3, + scale=scale) + assert_allclose(delta, 6.053624060118734e-184) + + def test_fit_min(self): + rng = np.random.default_rng(5985959307161735394) + + c, loc, scale = 2, 3.5, 0.5 # arbitrary, valid parameters + dist = stats.weibull_min(c, loc, scale) + rvs = dist.rvs(size=100, random_state=rng) + + # test that MLE still honors guesses and fixed parameters + c2, loc2, scale2 = stats.weibull_min.fit(rvs, 1.5, floc=3) + c3, loc3, scale3 = stats.weibull_min.fit(rvs, 1.6, floc=3) + assert loc2 == loc3 == 3 # fixed parameter is respected + assert c2 != c3 # different guess -> (slightly) different outcome + # quality of fit is tested elsewhere + + # test that MoM honors fixed parameters, accepts (but ignores) guesses + c4, loc4, scale4 = stats.weibull_min.fit(rvs, 3, fscale=3, method='mm') + assert scale4 == 3 + # because scale was fixed, only the mean and skewness will be matched + dist4 = stats.weibull_min(c4, loc4, scale4) + res = dist4.stats(moments='ms') + ref = np.mean(rvs), stats.skew(rvs) + assert_allclose(res, ref) + + # reference values were computed via mpmath + # from mpmath import mp + # def weibull_sf_mpmath(x, c): + # x = mp.mpf(x) + # c = mp.mpf(c) + # return float(mp.exp(-x**c)) + + @pytest.mark.parametrize('x, c, ref', [(50, 1, 1.9287498479639178e-22), + (1000, 0.8, + 8.131269637872743e-110)]) + def test_sf_isf(self, x, c, ref): + assert_allclose(stats.weibull_min.sf(x, c), ref, rtol=5e-14) + assert_allclose(stats.weibull_min.isf(ref, c), x, rtol=5e-14) + + +class TestDweibull: + def test_entropy(self): + # Test that dweibull entropy follows that of weibull_min. + # (Generic tests check that the dweibull entropy is consistent + # with its PDF. As for accuracy, dweibull entropy should be just + # as accurate as weibull_min entropy. Checks of accuracy against + # a reference need only be applied to the fundamental distribution - + # weibull_min.) + rng = np.random.default_rng(8486259129157041777) + c = 10**rng.normal(scale=100, size=10) + res = stats.dweibull.entropy(c) + ref = stats.weibull_min.entropy(c) - np.log(0.5) + assert_allclose(res, ref, rtol=1e-15) + + def test_sf(self): + # test that for positive values the dweibull survival function is half + # the weibull_min survival function + rng = np.random.default_rng(8486259129157041777) + c = 10**rng.normal(scale=1, size=10) + x = 10 * rng.uniform() + res = stats.dweibull.sf(x, c) + ref = 0.5 * stats.weibull_min.sf(x, c) + assert_allclose(res, ref, rtol=1e-15) + + +class TestTruncWeibull: + + def test_pdf_bounds(self): + # test bounds + y = stats.truncweibull_min.pdf([0.1, 2.0], 2.0, 0.11, 1.99) + assert_equal(y, [0.0, 0.0]) + + def test_logpdf(self): + y = stats.truncweibull_min.logpdf(2.0, 1.0, 2.0, np.inf) + assert_equal(y, 0.0) + + # hand calculation + y = stats.truncweibull_min.logpdf(2.0, 1.0, 2.0, 4.0) + assert_allclose(y, 0.14541345786885884) + + def test_ppf_bounds(self): + # test bounds + y = stats.truncweibull_min.ppf([0.0, 1.0], 2.0, 0.1, 2.0) + assert_equal(y, [0.1, 2.0]) + + def test_cdf_to_ppf(self): + q = [0., 0.1, .25, 0.50, 0.75, 0.90, 1.] + x = stats.truncweibull_min.ppf(q, 2., 0., 3.) + q_out = stats.truncweibull_min.cdf(x, 2., 0., 3.) + assert_allclose(q, q_out) + + def test_sf_to_isf(self): + q = [0., 0.1, .25, 0.50, 0.75, 0.90, 1.] + x = stats.truncweibull_min.isf(q, 2., 0., 3.) + q_out = stats.truncweibull_min.sf(x, 2., 0., 3.) + assert_allclose(q, q_out) + + def test_munp(self): + c = 2. + a = 1. + b = 3. + + def xnpdf(x, n): + return x**n*stats.truncweibull_min.pdf(x, c, a, b) + + m0 = stats.truncweibull_min.moment(0, c, a, b) + assert_equal(m0, 1.) + + m1 = stats.truncweibull_min.moment(1, c, a, b) + m1_expected, _ = quad(lambda x: xnpdf(x, 1), a, b) + assert_allclose(m1, m1_expected) + + m2 = stats.truncweibull_min.moment(2, c, a, b) + m2_expected, _ = quad(lambda x: xnpdf(x, 2), a, b) + assert_allclose(m2, m2_expected) + + m3 = stats.truncweibull_min.moment(3, c, a, b) + m3_expected, _ = quad(lambda x: xnpdf(x, 3), a, b) + assert_allclose(m3, m3_expected) + + m4 = stats.truncweibull_min.moment(4, c, a, b) + m4_expected, _ = quad(lambda x: xnpdf(x, 4), a, b) + assert_allclose(m4, m4_expected) + + def test_reference_values(self): + a = 1. + b = 3. + c = 2. + x_med = np.sqrt(1 - np.log(0.5 + np.exp(-(8. + np.log(2.))))) + + cdf = stats.truncweibull_min.cdf(x_med, c, a, b) + assert_allclose(cdf, 0.5) + + lc = stats.truncweibull_min.logcdf(x_med, c, a, b) + assert_allclose(lc, -np.log(2.)) + + ppf = stats.truncweibull_min.ppf(0.5, c, a, b) + assert_allclose(ppf, x_med) + + sf = stats.truncweibull_min.sf(x_med, c, a, b) + assert_allclose(sf, 0.5) + + ls = stats.truncweibull_min.logsf(x_med, c, a, b) + assert_allclose(ls, -np.log(2.)) + + isf = stats.truncweibull_min.isf(0.5, c, a, b) + assert_allclose(isf, x_med) + + def test_compare_weibull_min(self): + # Verify that the truncweibull_min distribution gives the same results + # as the original weibull_min + x = 1.5 + c = 2.0 + a = 0.0 + b = np.inf + scale = 3.0 + + p = stats.weibull_min.pdf(x, c, scale=scale) + p_trunc = stats.truncweibull_min.pdf(x, c, a, b, scale=scale) + assert_allclose(p, p_trunc) + + lp = stats.weibull_min.logpdf(x, c, scale=scale) + lp_trunc = stats.truncweibull_min.logpdf(x, c, a, b, scale=scale) + assert_allclose(lp, lp_trunc) + + cdf = stats.weibull_min.cdf(x, c, scale=scale) + cdf_trunc = stats.truncweibull_min.cdf(x, c, a, b, scale=scale) + assert_allclose(cdf, cdf_trunc) + + lc = stats.weibull_min.logcdf(x, c, scale=scale) + lc_trunc = stats.truncweibull_min.logcdf(x, c, a, b, scale=scale) + assert_allclose(lc, lc_trunc) + + s = stats.weibull_min.sf(x, c, scale=scale) + s_trunc = stats.truncweibull_min.sf(x, c, a, b, scale=scale) + assert_allclose(s, s_trunc) + + ls = stats.weibull_min.logsf(x, c, scale=scale) + ls_trunc = stats.truncweibull_min.logsf(x, c, a, b, scale=scale) + assert_allclose(ls, ls_trunc) + + # # Also test using a large value x, for which computing the survival + # # function using the CDF would result in 0. + s = stats.truncweibull_min.sf(30, 2, a, b, scale=3) + assert_allclose(s, np.exp(-100)) + + ls = stats.truncweibull_min.logsf(30, 2, a, b, scale=3) + assert_allclose(ls, -100) + + def test_compare_weibull_min2(self): + # Verify that the truncweibull_min distribution PDF and CDF results + # are the same as those calculated from truncating weibull_min + c, a, b = 2.5, 0.25, 1.25 + x = np.linspace(a, b, 100) + + pdf1 = stats.truncweibull_min.pdf(x, c, a, b) + cdf1 = stats.truncweibull_min.cdf(x, c, a, b) + + norm = stats.weibull_min.cdf(b, c) - stats.weibull_min.cdf(a, c) + pdf2 = stats.weibull_min.pdf(x, c) / norm + cdf2 = (stats.weibull_min.cdf(x, c) - stats.weibull_min.cdf(a, c))/norm + + np.testing.assert_allclose(pdf1, pdf2) + np.testing.assert_allclose(cdf1, cdf2) + + +class TestRdist: + def test_rdist_cdf_gh1285(self): + # check workaround in rdist._cdf for issue gh-1285. + distfn = stats.rdist + values = [0.001, 0.5, 0.999] + assert_almost_equal(distfn.cdf(distfn.ppf(values, 541.0), 541.0), + values, decimal=5) + + def test_rdist_beta(self): + # rdist is a special case of stats.beta + x = np.linspace(-0.99, 0.99, 10) + c = 2.7 + assert_almost_equal(0.5*stats.beta(c/2, c/2).pdf((x + 1)/2), + stats.rdist(c).pdf(x)) + + # reference values were computed via mpmath + # from mpmath import mp + # mp.dps = 200 + # def rdist_sf_mpmath(x, c): + # x = mp.mpf(x) + # c = mp.mpf(c) + # return float(mp.betainc(c/2, c/2, (x+1)/2, mp.one, regularized=True)) + @pytest.mark.parametrize( + "x, c, ref", + [ + (0.0001, 541, 0.49907251345565845), + (0.1, 241, 0.06000788166249205), + (0.5, 441, 1.0655898106047832e-29), + (0.8, 341, 6.025478373732215e-78), + ] + ) + def test_rdist_sf(self, x, c, ref): + assert_allclose(stats.rdist.sf(x, c), ref, rtol=5e-14) + + +class TestTrapezoid: + def test_reduces_to_triang(self): + modes = [0, 0.3, 0.5, 1] + for mode in modes: + x = [0, mode, 1] + assert_almost_equal(stats.trapezoid.pdf(x, mode, mode), + stats.triang.pdf(x, mode)) + assert_almost_equal(stats.trapezoid.cdf(x, mode, mode), + stats.triang.cdf(x, mode)) + + def test_reduces_to_uniform(self): + x = np.linspace(0, 1, 10) + assert_almost_equal(stats.trapezoid.pdf(x, 0, 1), stats.uniform.pdf(x)) + assert_almost_equal(stats.trapezoid.cdf(x, 0, 1), stats.uniform.cdf(x)) + + def test_cases(self): + # edge cases + assert_almost_equal(stats.trapezoid.pdf(0, 0, 0), 2) + assert_almost_equal(stats.trapezoid.pdf(1, 1, 1), 2) + assert_almost_equal(stats.trapezoid.pdf(0.5, 0, 0.8), + 1.11111111111111111) + assert_almost_equal(stats.trapezoid.pdf(0.5, 0.2, 1.0), + 1.11111111111111111) + + # straightforward case + assert_almost_equal(stats.trapezoid.pdf(0.1, 0.2, 0.8), 0.625) + assert_almost_equal(stats.trapezoid.pdf(0.5, 0.2, 0.8), 1.25) + assert_almost_equal(stats.trapezoid.pdf(0.9, 0.2, 0.8), 0.625) + + assert_almost_equal(stats.trapezoid.cdf(0.1, 0.2, 0.8), 0.03125) + assert_almost_equal(stats.trapezoid.cdf(0.2, 0.2, 0.8), 0.125) + assert_almost_equal(stats.trapezoid.cdf(0.5, 0.2, 0.8), 0.5) + assert_almost_equal(stats.trapezoid.cdf(0.9, 0.2, 0.8), 0.96875) + assert_almost_equal(stats.trapezoid.cdf(1.0, 0.2, 0.8), 1.0) + + def test_moments_and_entropy(self): + # issue #11795: improve precision of trapezoid stats + # Apply formulas from Wikipedia for the following parameters: + a, b, c, d = -3, -1, 2, 3 # => 1/3, 5/6, -3, 6 + p1, p2, loc, scale = (b-a) / (d-a), (c-a) / (d-a), a, d-a + h = 2 / (d+c-b-a) + + def moment(n): + return (h * ((d**(n+2) - c**(n+2)) / (d-c) + - (b**(n+2) - a**(n+2)) / (b-a)) / + (n+1) / (n+2)) + + mean = moment(1) + var = moment(2) - mean**2 + entropy = 0.5 * (d-c+b-a) / (d+c-b-a) + np.log(0.5 * (d+c-b-a)) + assert_almost_equal(stats.trapezoid.mean(p1, p2, loc, scale), + mean, decimal=13) + assert_almost_equal(stats.trapezoid.var(p1, p2, loc, scale), + var, decimal=13) + assert_almost_equal(stats.trapezoid.entropy(p1, p2, loc, scale), + entropy, decimal=13) + + # Check boundary cases where scipy d=0 or d=1. + assert_almost_equal(stats.trapezoid.mean(0, 0, -3, 6), -1, decimal=13) + assert_almost_equal(stats.trapezoid.mean(0, 1, -3, 6), 0, decimal=13) + assert_almost_equal(stats.trapezoid.var(0, 1, -3, 6), 3, decimal=13) + + def test_trapezoid_vect(self): + # test that array-valued shapes and arguments are handled + c = np.array([0.1, 0.2, 0.3]) + d = np.array([0.5, 0.6])[:, None] + x = np.array([0.15, 0.25, 0.9]) + v = stats.trapezoid.pdf(x, c, d) + + cc, dd, xx = np.broadcast_arrays(c, d, x) + + res = np.empty(xx.size, dtype=xx.dtype) + ind = np.arange(xx.size) + for i, x1, c1, d1 in zip(ind, xx.ravel(), cc.ravel(), dd.ravel()): + res[i] = stats.trapezoid.pdf(x1, c1, d1) + + assert_allclose(v, res.reshape(v.shape), atol=1e-15) + + # Check that the stats() method supports vector arguments. + v = np.asarray(stats.trapezoid.stats(c, d, moments="mvsk")) + cc, dd = np.broadcast_arrays(c, d) + res = np.empty((cc.size, 4)) # 4 stats returned per value + ind = np.arange(cc.size) + for i, c1, d1 in zip(ind, cc.ravel(), dd.ravel()): + res[i] = stats.trapezoid.stats(c1, d1, moments="mvsk") + + assert_allclose(v, res.T.reshape(v.shape), atol=1e-15) + + def test_trapz(self): + # Basic test for alias + x = np.linspace(0, 1, 10) + with pytest.deprecated_call(match="`trapz.pdf` is deprecated"): + result = stats.trapz.pdf(x, 0, 1) + assert_almost_equal(result, stats.uniform.pdf(x)) + + @pytest.mark.parametrize('method', ['pdf', 'logpdf', 'cdf', 'logcdf', + 'sf', 'logsf', 'ppf', 'isf']) + def test_trapz_deprecation(self, method): + c, d = 0.2, 0.8 + expected = getattr(stats.trapezoid, method)(1, c, d) + with pytest.deprecated_call( + match=f"`trapz.{method}` is deprecated", + ): + result = getattr(stats.trapz, method)(1, c, d) + assert result == expected + + +class TestTriang: + def test_edge_cases(self): + with np.errstate(all='raise'): + assert_equal(stats.triang.pdf(0, 0), 2.) + assert_equal(stats.triang.pdf(0.5, 0), 1.) + assert_equal(stats.triang.pdf(1, 0), 0.) + + assert_equal(stats.triang.pdf(0, 1), 0) + assert_equal(stats.triang.pdf(0.5, 1), 1.) + assert_equal(stats.triang.pdf(1, 1), 2) + + assert_equal(stats.triang.cdf(0., 0.), 0.) + assert_equal(stats.triang.cdf(0.5, 0.), 0.75) + assert_equal(stats.triang.cdf(1.0, 0.), 1.0) + + assert_equal(stats.triang.cdf(0., 1.), 0.) + assert_equal(stats.triang.cdf(0.5, 1.), 0.25) + assert_equal(stats.triang.cdf(1., 1.), 1) + + +class TestMaxwell: + + # reference values were computed with wolfram alpha + # erfc(x/sqrt(2)) + sqrt(2/pi) * x * e^(-x^2/2) + + @pytest.mark.parametrize("x, ref", + [(20, 2.2138865931011177e-86), + (0.01, 0.999999734046458435)]) + def test_sf(self, x, ref): + assert_allclose(stats.maxwell.sf(x), ref, rtol=1e-14) + + # reference values were computed with wolfram alpha + # sqrt(2) * sqrt(Q^(-1)(3/2, q)) + + @pytest.mark.parametrize("q, ref", + [(0.001, 4.033142223656157022), + (0.9999847412109375, 0.0385743284050381), + (2**-55, 8.95564974719481)]) + def test_isf(self, q, ref): + assert_allclose(stats.maxwell.isf(q), ref, rtol=1e-15) + + def test_logcdf(self): + # Reference value computed with mpmath. + ref = -1.8729310110194814e-17 + logcdf = stats.maxwell.logcdf(9) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + # Reference value computed with mpmath. + ref = -2.6596152026762177e-25 + logsf = stats.maxwell.logsf(1e-8) + assert_allclose(logsf, ref, rtol=5e-15) + + +class TestMielke: + def test_moments(self): + k, s = 4.642, 0.597 + # n-th moment exists only if n < s + assert_equal(stats.mielke(k, s).moment(1), np.inf) + assert_equal(stats.mielke(k, 1.0).moment(1), np.inf) + assert_(np.isfinite(stats.mielke(k, 1.01).moment(1))) + + def test_burr_equivalence(self): + x = np.linspace(0.01, 100, 50) + k, s = 2.45, 5.32 + assert_allclose(stats.burr.pdf(x, s, k/s), stats.mielke.pdf(x, k, s)) + + +class TestBurr: + def test_endpoints_7491(self): + # gh-7491 + # Compute the pdf at the left endpoint dst.a. + data = [ + [stats.fisk, (1,), 1], + [stats.burr, (0.5, 2), 1], + [stats.burr, (1, 1), 1], + [stats.burr, (2, 0.5), 1], + [stats.burr12, (1, 0.5), 0.5], + [stats.burr12, (1, 1), 1.0], + [stats.burr12, (1, 2), 2.0]] + + ans = [_f.pdf(_f.a, *_args) for _f, _args, _ in data] + correct = [_correct_ for _f, _args, _correct_ in data] + assert_array_almost_equal(ans, correct) + + ans = [_f.logpdf(_f.a, *_args) for _f, _args, _ in data] + correct = [np.log(_correct_) for _f, _args, _correct_ in data] + assert_array_almost_equal(ans, correct) + + def test_burr_stats_9544(self): + # gh-9544. Test from gh-9978 + c, d = 5.0, 3 + mean, variance = stats.burr(c, d).stats() + # mean = sc.beta(3 + 1/5, 1. - 1/5) * 3 = 1.4110263... + # var = sc.beta(3 + 2 / 5, 1. - 2 / 5) * 3 - + # (sc.beta(3 + 1 / 5, 1. - 1 / 5) * 3) ** 2 + mean_hc, variance_hc = 1.4110263183925857, 0.22879948026191643 + assert_allclose(mean, mean_hc) + assert_allclose(variance, variance_hc) + + def test_burr_nan_mean_var_9544(self): + # gh-9544. Test from gh-9978 + c, d = 0.5, 3 + mean, variance = stats.burr(c, d).stats() + assert_(np.isnan(mean)) + assert_(np.isnan(variance)) + c, d = 1.5, 3 + mean, variance = stats.burr(c, d).stats() + assert_(np.isfinite(mean)) + assert_(np.isnan(variance)) + + c, d = 0.5, 3 + e1, e2, e3, e4 = stats.burr._munp(np.array([1, 2, 3, 4]), c, d) + assert_(np.isnan(e1)) + assert_(np.isnan(e2)) + assert_(np.isnan(e3)) + assert_(np.isnan(e4)) + c, d = 1.5, 3 + e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d) + assert_(np.isfinite(e1)) + assert_(np.isnan(e2)) + assert_(np.isnan(e3)) + assert_(np.isnan(e4)) + c, d = 2.5, 3 + e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d) + assert_(np.isfinite(e1)) + assert_(np.isfinite(e2)) + assert_(np.isnan(e3)) + assert_(np.isnan(e4)) + c, d = 3.5, 3 + e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d) + assert_(np.isfinite(e1)) + assert_(np.isfinite(e2)) + assert_(np.isfinite(e3)) + assert_(np.isnan(e4)) + c, d = 4.5, 3 + e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d) + assert_(np.isfinite(e1)) + assert_(np.isfinite(e2)) + assert_(np.isfinite(e3)) + assert_(np.isfinite(e4)) + + def test_burr_isf(self): + # reference values were computed via the reference distribution, e.g. + # mp.dps = 100 + # Burr(c=5, d=3).isf([0.1, 1e-10, 1e-20, 1e-40]) + c, d = 5.0, 3.0 + q = [0.1, 1e-10, 1e-20, 1e-40] + ref = [1.9469686558286508, 124.57309395989076, 12457.309396155173, + 124573093.96155174] + assert_allclose(stats.burr.isf(q, c, d), ref, rtol=1e-14) + + +class TestBurr12: + + @pytest.mark.parametrize('scale, expected', + [(1.0, 2.3283064359965952e-170), + (3.5, 5.987114417447875e-153)]) + def test_delta_cdf(self, scale, expected): + # Expected value computed with mpmath: + # + # def burr12sf(x, c, d, scale): + # x = mpmath.mpf(x) + # c = mpmath.mpf(c) + # d = mpmath.mpf(d) + # scale = mpmath.mpf(scale) + # return (mpmath.mp.one + (x/scale)**c)**(-d) + # + # >>> import mpmath + # >>> mpmath.mp.dps = 60 + # >>> float(burr12sf(2e5, 4, 8, 1) - burr12sf(4e5, 4, 8, 1)) + # 2.3283064359965952e-170 + # >>> float(burr12sf(2e5, 4, 8, 3.5) - burr12sf(4e5, 4, 8, 3.5)) + # 5.987114417447875e-153 + # + delta = stats.burr12._delta_cdf(2e5, 4e5, 4, 8, scale=scale) + assert_allclose(delta, expected, rtol=1e-13) + + def test_moments_edge(self): + # gh-18838 reported that burr12 moments could be invalid; see above. + # Check that this is resolved in an edge case where c*d == n, and + # compare the results against those produced by Mathematica, e.g. + # `SinghMaddalaDistribution[2, 2, 1]` at Wolfram Alpha. + c, d = 2, 2 + mean = np.pi/4 + var = 1 - np.pi**2/16 + skew = np.pi**3/(32*var**1.5) + kurtosis = np.nan + ref = [mean, var, skew, kurtosis] + res = stats.burr12(c, d).stats('mvsk') + assert_allclose(res, ref, rtol=1e-14) + + # Reference values were computed with mpmath using mp.dps = 80 + # and then cast to float. + @pytest.mark.parametrize( + 'p, c, d, ref', + [(1e-12, 20, 0.5, 15.848931924611135), + (1e-19, 20, 0.5, 79.43282347242815), + (1e-12, 0.25, 35, 2.0888618213462466), + (1e-80, 0.25, 35, 1360930951.7972188)] + ) + def test_isf_near_zero(self, p, c, d, ref): + x = stats.burr12.isf(p, c, d) + assert_allclose(x, ref, rtol=1e-14) + + +class TestStudentizedRange: + # For alpha = .05, .01, and .001, and for each value of + # v = [1, 3, 10, 20, 120, inf], a Q was picked from each table for + # k = [2, 8, 14, 20]. + + # these arrays are written with `k` as column, and `v` as rows. + # Q values are taken from table 3: + # https://www.jstor.org/stable/2237810 + q05 = [17.97, 45.40, 54.33, 59.56, + 4.501, 8.853, 10.35, 11.24, + 3.151, 5.305, 6.028, 6.467, + 2.950, 4.768, 5.357, 5.714, + 2.800, 4.363, 4.842, 5.126, + 2.772, 4.286, 4.743, 5.012] + q01 = [90.03, 227.2, 271.8, 298.0, + 8.261, 15.64, 18.22, 19.77, + 4.482, 6.875, 7.712, 8.226, + 4.024, 5.839, 6.450, 6.823, + 3.702, 5.118, 5.562, 5.827, + 3.643, 4.987, 5.400, 5.645] + q001 = [900.3, 2272, 2718, 2980, + 18.28, 34.12, 39.69, 43.05, + 6.487, 9.352, 10.39, 11.03, + 5.444, 7.313, 7.966, 8.370, + 4.772, 6.039, 6.448, 6.695, + 4.654, 5.823, 6.191, 6.411] + qs = np.concatenate((q05, q01, q001)) + ps = [.95, .99, .999] + vs = [1, 3, 10, 20, 120, np.inf] + ks = [2, 8, 14, 20] + + data = list(zip(product(ps, vs, ks), qs)) + + # A small selection of large-v cases generated with R's `ptukey` + # Each case is in the format (q, k, v, r_result) + r_data = [ + (0.1, 3, 9001, 0.002752818526842), + (1, 10, 1000, 0.000526142388912), + (1, 3, np.inf, 0.240712641229283), + (4, 3, np.inf, 0.987012338626815), + (1, 10, np.inf, 0.000519869467083), + ] + + @pytest.mark.slow + def test_cdf_against_tables(self): + for pvk, q in self.data: + p_expected, v, k = pvk + res_p = stats.studentized_range.cdf(q, k, v) + assert_allclose(res_p, p_expected, rtol=1e-4) + + @pytest.mark.xslow + def test_ppf_against_tables(self): + for pvk, q_expected in self.data: + p, v, k = pvk + res_q = stats.studentized_range.ppf(p, k, v) + assert_allclose(res_q, q_expected, rtol=5e-4) + + path_prefix = os.path.dirname(__file__) + relative_path = "data/studentized_range_mpmath_ref.json" + with open(os.path.join(path_prefix, relative_path)) as file: + pregenerated_data = json.load(file) + + @pytest.mark.parametrize("case_result", pregenerated_data["cdf_data"]) + def test_cdf_against_mp(self, case_result): + src_case = case_result["src_case"] + mp_result = case_result["mp_result"] + qkv = src_case["q"], src_case["k"], src_case["v"] + res = stats.studentized_range.cdf(*qkv) + + assert_allclose(res, mp_result, + atol=src_case["expected_atol"], + rtol=src_case["expected_rtol"]) + + @pytest.mark.parametrize("case_result", pregenerated_data["pdf_data"]) + def test_pdf_against_mp(self, case_result): + src_case = case_result["src_case"] + mp_result = case_result["mp_result"] + qkv = src_case["q"], src_case["k"], src_case["v"] + res = stats.studentized_range.pdf(*qkv) + + assert_allclose(res, mp_result, + atol=src_case["expected_atol"], + rtol=src_case["expected_rtol"]) + + @pytest.mark.xslow + @pytest.mark.xfail_on_32bit("intermittent RuntimeWarning: invalid value.") + @pytest.mark.parametrize("case_result", pregenerated_data["moment_data"]) + def test_moment_against_mp(self, case_result): + src_case = case_result["src_case"] + mp_result = case_result["mp_result"] + mkv = src_case["m"], src_case["k"], src_case["v"] + + # Silence invalid value encountered warnings. Actual problems will be + # caught by the result comparison. + with np.errstate(invalid='ignore'): + res = stats.studentized_range.moment(*mkv) + + assert_allclose(res, mp_result, + atol=src_case["expected_atol"], + rtol=src_case["expected_rtol"]) + + @pytest.mark.slow + def test_pdf_integration(self): + k, v = 3, 10 + # Test whether PDF integration is 1 like it should be. + res = quad(stats.studentized_range.pdf, 0, np.inf, args=(k, v)) + assert_allclose(res[0], 1) + + @pytest.mark.xslow + def test_pdf_against_cdf(self): + k, v = 3, 10 + + # Test whether the integrated PDF matches the CDF using cumulative + # integration. Use a small step size to reduce error due to the + # summation. This is slow, but tests the results well. + x = np.arange(0, 10, step=0.01) + + y_cdf = stats.studentized_range.cdf(x, k, v)[1:] + y_pdf_raw = stats.studentized_range.pdf(x, k, v) + y_pdf_cumulative = cumulative_trapezoid(y_pdf_raw, x) + + # Because of error caused by the summation, use a relatively large rtol + assert_allclose(y_pdf_cumulative, y_cdf, rtol=1e-4) + + @pytest.mark.parametrize("r_case_result", r_data) + def test_cdf_against_r(self, r_case_result): + # Test large `v` values using R + q, k, v, r_res = r_case_result + with np.errstate(invalid='ignore'): + res = stats.studentized_range.cdf(q, k, v) + assert_allclose(res, r_res) + + @pytest.mark.xslow + @pytest.mark.xfail_on_32bit("intermittent RuntimeWarning: invalid value.") + def test_moment_vectorization(self): + # Test moment broadcasting. Calls `_munp` directly because + # `rv_continuous.moment` is broken at time of writing. See gh-12192 + + # Silence invalid value encountered warnings. Actual problems will be + # caught by the result comparison. + with np.errstate(invalid='ignore'): + m = stats.studentized_range._munp([1, 2], [4, 5], [10, 11]) + + assert_allclose(m.shape, (2,)) + + with pytest.raises(ValueError, match="...could not be broadcast..."): + stats.studentized_range._munp(1, [4, 5], [10, 11, 12]) + + @pytest.mark.xslow + def test_fitstart_valid(self): + with suppress_warnings() as sup, np.errstate(invalid="ignore"): + # the integration warning message may differ + sup.filter(IntegrationWarning) + k, df, _, _ = stats.studentized_range._fitstart([1, 2, 3]) + assert_(stats.studentized_range._argcheck(k, df)) + + def test_infinite_df(self): + # Check that the CDF and PDF infinite and normal integrators + # roughly match for a high df case + res = stats.studentized_range.pdf(3, 10, np.inf) + res_finite = stats.studentized_range.pdf(3, 10, 99999) + assert_allclose(res, res_finite, atol=1e-4, rtol=1e-4) + + res = stats.studentized_range.cdf(3, 10, np.inf) + res_finite = stats.studentized_range.cdf(3, 10, 99999) + assert_allclose(res, res_finite, atol=1e-4, rtol=1e-4) + + def test_df_cutoff(self): + # Test that the CDF and PDF properly switch integrators at df=100,000. + # The infinite integrator should be different enough that it fails + # an allclose assertion. Also sanity check that using the same + # integrator does pass the allclose with a 1-df difference, which + # should be tiny. + + res = stats.studentized_range.pdf(3, 10, 100000) + res_finite = stats.studentized_range.pdf(3, 10, 99999) + res_sanity = stats.studentized_range.pdf(3, 10, 99998) + assert_raises(AssertionError, assert_allclose, res, res_finite, + atol=1e-6, rtol=1e-6) + assert_allclose(res_finite, res_sanity, atol=1e-6, rtol=1e-6) + + res = stats.studentized_range.cdf(3, 10, 100000) + res_finite = stats.studentized_range.cdf(3, 10, 99999) + res_sanity = stats.studentized_range.cdf(3, 10, 99998) + assert_raises(AssertionError, assert_allclose, res, res_finite, + atol=1e-6, rtol=1e-6) + assert_allclose(res_finite, res_sanity, atol=1e-6, rtol=1e-6) + + def test_clipping(self): + # The result of this computation was -9.9253938401489e-14 on some + # systems. The correct result is very nearly zero, but should not be + # negative. + q, k, v = 34.6413996195345746, 3, 339 + p = stats.studentized_range.sf(q, k, v) + assert_allclose(p, 0, atol=1e-10) + assert p >= 0 + + +class TestTukeyLambda: + + @pytest.mark.parametrize( + 'lam', + [0.0, -1.0, -2.0, np.array([[-1.0], [0.0], [-2.0]])] + ) + def test_pdf_nonpositive_lambda(self, lam): + # Make sure that Tukey-Lambda distribution correctly handles + # non-positive lambdas. + # This is a crude test--it just checks that all the PDF values + # are finite and greater than 0. + x = np.linspace(-5.0, 5.0, 101) + p = stats.tukeylambda.pdf(x, lam) + assert np.isfinite(p).all() + assert (p > 0.0).all() + + def test_pdf_mixed_lambda(self): + # Another crude test of the behavior of the PDF method. + x = np.linspace(-5.0, 5.0, 101) + lam = np.array([[-1.0], [0.0], [2.0]]) + p = stats.tukeylambda.pdf(x, lam) + assert np.isfinite(p).all() + # For p[0] and p[1], where lam <= 0, the support is (-inf, inf), + # so the PDF should be nonzero everywhere (assuming we aren't so + # far in the tails that we get underflow). + assert (p[:2] > 0.0).all() + # For p[2], where lam=2.0, the support is [-0.5, 0.5], so in pdf(x), + # some values should be positive and some should be 0. + assert (p[2] > 0.0).any() + assert (p[2] == 0.0).any() + + def test_support(self): + lam = np.array([-1.75, -0.5, 0.0, 0.25, 0.5, 2.0]) + a, b = stats.tukeylambda.support(lam) + expected_b = np.array([np.inf, np.inf, np.inf, 4, 2, 0.5]) + assert_equal(b, expected_b) + assert_equal(a, -expected_b) + + def test_pdf_support_boundary(self): + # Verify that tukeylambda.pdf() doesn't generate a + # warning when evaluated at the bounds of the support. + # For lam=0.5, the support is (-2, 2). + p = stats.tukeylambda.pdf([-2.0, 2.0], 0.5) + assert_equal(p, [0.0, 0.0]) + + def test_tukeylambda_stats_ticket_1545(self): + # Some test for the variance and kurtosis of the Tukey Lambda distr. + # See test_tukeylamdba_stats.py for more tests. + + mv = stats.tukeylambda.stats(0, moments='mvsk') + # Known exact values: + expected = [0, np.pi**2/3, 0, 1.2] + assert_almost_equal(mv, expected, decimal=10) + + mv = stats.tukeylambda.stats(3.13, moments='mvsk') + # 'expected' computed with mpmath. + expected = [0, 0.0269220858861465102, 0, -0.898062386219224104] + assert_almost_equal(mv, expected, decimal=10) + + mv = stats.tukeylambda.stats(0.14, moments='mvsk') + # 'expected' computed with mpmath. + expected = [0, 2.11029702221450250, 0, -0.02708377353223019456] + assert_almost_equal(mv, expected, decimal=10) + + +class TestLevy: + + def test_levy_cdf_ppf(self): + # Test levy.cdf, including small arguments. + x = np.array([1000, 1.0, 0.5, 0.1, 0.01, 0.001]) + + # Expected values were calculated separately with mpmath. + # E.g. + # >>> mpmath.mp.dps = 100 + # >>> x = mpmath.mp.mpf('0.01') + # >>> cdf = mpmath.erfc(mpmath.sqrt(1/(2*x))) + expected = np.array([0.9747728793699604, + 0.3173105078629141, + 0.1572992070502851, + 0.0015654022580025495, + 1.523970604832105e-23, + 1.795832784800726e-219]) + + y = stats.levy.cdf(x) + assert_allclose(y, expected, rtol=1e-10) + + # ppf(expected) should get us back to x. + xx = stats.levy.ppf(expected) + assert_allclose(xx, x, rtol=1e-13) + + def test_levy_sf(self): + # Large values, far into the tail of the distribution. + x = np.array([1e15, 1e25, 1e35, 1e50]) + # Expected values were calculated with mpmath. + expected = np.array([2.5231325220201597e-08, + 2.52313252202016e-13, + 2.52313252202016e-18, + 7.978845608028653e-26]) + y = stats.levy.sf(x) + assert_allclose(y, expected, rtol=1e-14) + + # The expected values for levy.isf(p) were calculated with mpmath. + # For loc=0 and scale=1, the inverse SF can be computed with + # + # import mpmath + # + # def levy_invsf(p): + # return 1/(2*mpmath.erfinv(p)**2) + # + # For example, with mpmath.mp.dps set to 60, float(levy_invsf(1e-20)) + # returns 6.366197723675814e+39. + # + @pytest.mark.parametrize('p, expected_isf', + [(1e-20, 6.366197723675814e+39), + (1e-8, 6366197723675813.0), + (0.375, 4.185810119346273), + (0.875, 0.42489442055310134), + (0.999, 0.09235685880262713), + (0.9999999962747097, 0.028766845244146945)]) + def test_levy_isf(self, p, expected_isf): + x = stats.levy.isf(p) + assert_allclose(x, expected_isf, atol=5e-15) + + def test_levy_logcdf(self): + x = 1e50 + ref = -7.978845608028653e-26 + logcdf = stats.levy.logcdf(x) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_levy_logsf(self): + x = 5e-3 + ref = -2.0884875837625492e-45 + logsf = stats.levy.logsf(x) + assert_allclose(logsf, ref, rtol=5e-15) + + +def test_540_567(): + # test for nan returned in tickets 540, 567 + assert_almost_equal(stats.norm.cdf(-1.7624320982), 0.03899815971089126, + decimal=10, err_msg='test_540_567') + assert_almost_equal(stats.norm.cdf(-1.7624320983), 0.038998159702449846, + decimal=10, err_msg='test_540_567') + assert_almost_equal(stats.norm.cdf(1.38629436112, loc=0.950273420309, + scale=0.204423758009), + 0.98353464004309321, + decimal=10, err_msg='test_540_567') + + +@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped") +def test_regression_ticket_1421(): + assert_('pdf(x, mu, loc=0, scale=1)' not in stats.poisson.__doc__) + assert_('pmf(x,' in stats.poisson.__doc__) + + +def test_nan_arguments_gh_issue_1362(): + with np.errstate(invalid='ignore'): + assert_(np.isnan(stats.t.logcdf(1, np.nan))) + assert_(np.isnan(stats.t.cdf(1, np.nan))) + assert_(np.isnan(stats.t.logsf(1, np.nan))) + assert_(np.isnan(stats.t.sf(1, np.nan))) + assert_(np.isnan(stats.t.pdf(1, np.nan))) + assert_(np.isnan(stats.t.logpdf(1, np.nan))) + assert_(np.isnan(stats.t.ppf(1, np.nan))) + assert_(np.isnan(stats.t.isf(1, np.nan))) + + assert_(np.isnan(stats.bernoulli.logcdf(np.nan, 0.5))) + assert_(np.isnan(stats.bernoulli.cdf(np.nan, 0.5))) + assert_(np.isnan(stats.bernoulli.logsf(np.nan, 0.5))) + assert_(np.isnan(stats.bernoulli.sf(np.nan, 0.5))) + assert_(np.isnan(stats.bernoulli.pmf(np.nan, 0.5))) + assert_(np.isnan(stats.bernoulli.logpmf(np.nan, 0.5))) + assert_(np.isnan(stats.bernoulli.ppf(np.nan, 0.5))) + assert_(np.isnan(stats.bernoulli.isf(np.nan, 0.5))) + + +def test_frozen_fit_ticket_1536(): + np.random.seed(5678) + true = np.array([0.25, 0., 0.5]) + x = stats.lognorm.rvs(true[0], true[1], true[2], size=100) + + with np.errstate(divide='ignore'): + params = np.array(stats.lognorm.fit(x, floc=0.)) + + assert_almost_equal(params, true, decimal=2) + + params = np.array(stats.lognorm.fit(x, fscale=0.5, loc=0)) + assert_almost_equal(params, true, decimal=2) + + params = np.array(stats.lognorm.fit(x, f0=0.25, loc=0)) + assert_almost_equal(params, true, decimal=2) + + params = np.array(stats.lognorm.fit(x, f0=0.25, floc=0)) + assert_almost_equal(params, true, decimal=2) + + np.random.seed(5678) + loc = 1 + floc = 0.9 + x = stats.norm.rvs(loc, 2., size=100) + params = np.array(stats.norm.fit(x, floc=floc)) + expected = np.array([floc, np.sqrt(((x-floc)**2).mean())]) + assert_almost_equal(params, expected, decimal=4) + + +def test_regression_ticket_1530(): + # Check the starting value works for Cauchy distribution fit. + np.random.seed(654321) + rvs = stats.cauchy.rvs(size=100) + params = stats.cauchy.fit(rvs) + expected = (0.045, 1.142) + assert_almost_equal(params, expected, decimal=1) + + +def test_gh_pr_4806(): + # Check starting values for Cauchy distribution fit. + np.random.seed(1234) + x = np.random.randn(42) + for offset in 10000.0, 1222333444.0: + loc, scale = stats.cauchy.fit(x + offset) + assert_allclose(loc, offset, atol=1.0) + assert_allclose(scale, 0.6, atol=1.0) + + +def test_poisson_logpmf_ticket_1436(): + assert_(np.isfinite(stats.poisson.logpmf(1500, 200))) + + +def test_powerlaw_stats(): + """Test the powerlaw stats function. + + This unit test is also a regression test for ticket 1548. + + The exact values are: + mean: + mu = a / (a + 1) + variance: + sigma**2 = a / ((a + 2) * (a + 1) ** 2) + skewness: + One formula (see https://en.wikipedia.org/wiki/Skewness) is + gamma_1 = (E[X**3] - 3*mu*E[X**2] + 2*mu**3) / sigma**3 + A short calculation shows that E[X**k] is a / (a + k), so gamma_1 + can be implemented as + n = a/(a+3) - 3*(a/(a+1))*a/(a+2) + 2*(a/(a+1))**3 + d = sqrt(a/((a+2)*(a+1)**2)) ** 3 + gamma_1 = n/d + Either by simplifying, or by a direct calculation of mu_3 / sigma**3, + one gets the more concise formula: + gamma_1 = -2.0 * ((a - 1) / (a + 3)) * sqrt((a + 2) / a) + kurtosis: (See https://en.wikipedia.org/wiki/Kurtosis) + The excess kurtosis is + gamma_2 = mu_4 / sigma**4 - 3 + A bit of calculus and algebra (sympy helps) shows that + mu_4 = 3*a*(3*a**2 - a + 2) / ((a+1)**4 * (a+2) * (a+3) * (a+4)) + so + gamma_2 = 3*(3*a**2 - a + 2) * (a+2) / (a*(a+3)*(a+4)) - 3 + which can be rearranged to + gamma_2 = 6 * (a**3 - a**2 - 6*a + 2) / (a*(a+3)*(a+4)) + """ + cases = [(1.0, (0.5, 1./12, 0.0, -1.2)), + (2.0, (2./3, 2./36, -0.56568542494924734, -0.6))] + for a, exact_mvsk in cases: + mvsk = stats.powerlaw.stats(a, moments="mvsk") + assert_array_almost_equal(mvsk, exact_mvsk) + + +def test_powerlaw_edge(): + # Regression test for gh-3986. + p = stats.powerlaw.logpdf(0, 1) + assert_equal(p, 0.0) + + +def test_exponpow_edge(): + # Regression test for gh-3982. + p = stats.exponpow.logpdf(0, 1) + assert_equal(p, 0.0) + + # Check pdf and logpdf at x = 0 for other values of b. + p = stats.exponpow.pdf(0, [0.25, 1.0, 1.5]) + assert_equal(p, [np.inf, 1.0, 0.0]) + p = stats.exponpow.logpdf(0, [0.25, 1.0, 1.5]) + assert_equal(p, [np.inf, 0.0, -np.inf]) + + +def test_gengamma_edge(): + # Regression test for gh-3985. + p = stats.gengamma.pdf(0, 1, 1) + assert_equal(p, 1.0) + + +@pytest.mark.parametrize("a, c, ref, tol", + [(1500000.0, 1, 8.529426144018633, 1e-15), + (1e+30, 1, 35.95771492811536, 1e-15), + (1e+100, 1, 116.54819318290696, 1e-15), + (3e3, 1, 5.422011196659015, 1e-13), + (3e6, -1e100, -236.29663213396054, 1e-15), + (3e60, 1e-100, 1.3925371786831085e+102, 1e-15)]) +def test_gengamma_extreme_entropy(a, c, ref, tol): + # The reference values were calculated with mpmath: + # from mpmath import mp + # mp.dps = 500 + # + # def gen_entropy(a, c): + # a, c = mp.mpf(a), mp.mpf(c) + # val = mp.digamma(a) + # h = (a * (mp.one - val) + val/c + mp.loggamma(a) - mp.log(abs(c))) + # return float(h) + assert_allclose(stats.gengamma.entropy(a, c), ref, rtol=tol) + + +def test_gengamma_endpoint_with_neg_c(): + p = stats.gengamma.pdf(0, 1, -1) + assert p == 0.0 + logp = stats.gengamma.logpdf(0, 1, -1) + assert logp == -np.inf + + +def test_gengamma_munp(): + # Regression tests for gh-4724. + p = stats.gengamma._munp(-2, 200, 1.) + assert_almost_equal(p, 1./199/198) + + p = stats.gengamma._munp(-2, 10, 1.) + assert_almost_equal(p, 1./9/8) + + +def test_ksone_fit_freeze(): + # Regression test for ticket #1638. + d = np.array( + [-0.18879233, 0.15734249, 0.18695107, 0.27908787, -0.248649, + -0.2171497, 0.12233512, 0.15126419, 0.03119282, 0.4365294, + 0.08930393, -0.23509903, 0.28231224, -0.09974875, -0.25196048, + 0.11102028, 0.1427649, 0.10176452, 0.18754054, 0.25826724, + 0.05988819, 0.0531668, 0.21906056, 0.32106729, 0.2117662, + 0.10886442, 0.09375789, 0.24583286, -0.22968366, -0.07842391, + -0.31195432, -0.21271196, 0.1114243, -0.13293002, 0.01331725, + -0.04330977, -0.09485776, -0.28434547, 0.22245721, -0.18518199, + -0.10943985, -0.35243174, 0.06897665, -0.03553363, -0.0701746, + -0.06037974, 0.37670779, -0.21684405]) + + with np.errstate(invalid='ignore'): + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, + "The maximum number of subdivisions .50. has been " + "achieved.") + sup.filter(RuntimeWarning, + "floating point number truncated to an integer") + stats.ksone.fit(d) + + +def test_norm_logcdf(): + # Test precision of the logcdf of the normal distribution. + # This precision was enhanced in ticket 1614. + x = -np.asarray(list(range(0, 120, 4))) + # Values from R + expected = [-0.69314718, -10.36010149, -35.01343716, -75.41067300, + -131.69539607, -203.91715537, -292.09872100, -396.25241451, + -516.38564863, -652.50322759, -804.60844201, -972.70364403, + -1156.79057310, -1356.87055173, -1572.94460885, -1805.01356068, + -2053.07806561, -2317.13866238, -2597.19579746, -2893.24984493, + -3205.30112136, -3533.34989701, -3877.39640444, -4237.44084522, + -4613.48339520, -5005.52420869, -5413.56342187, -5837.60115548, + -6277.63751711, -6733.67260303] + + assert_allclose(stats.norm().logcdf(x), expected, atol=1e-8) + + # also test the complex-valued code path + assert_allclose(stats.norm().logcdf(x + 1e-14j).real, expected, atol=1e-8) + + # test the accuracy: d(logcdf)/dx = pdf / cdf \equiv exp(logpdf - logcdf) + deriv = (stats.norm.logcdf(x + 1e-10j)/1e-10).imag + deriv_expected = np.exp(stats.norm.logpdf(x) - stats.norm.logcdf(x)) + assert_allclose(deriv, deriv_expected, atol=1e-10) + + +def test_levy_l_sf(): + # Test levy_l.sf for small arguments. + x = np.array([-0.016, -0.01, -0.005, -0.0015]) + # Expected values were calculated with mpmath. + expected = np.array([2.6644463892359302e-15, + 1.523970604832107e-23, + 2.0884875837625492e-45, + 5.302850374626878e-147]) + y = stats.levy_l.sf(x) + assert_allclose(y, expected, rtol=1e-13) + + +def test_levy_l_isf(): + # Test roundtrip sf(isf(p)), including a small input value. + p = np.array([3.0e-15, 0.25, 0.99]) + x = stats.levy_l.isf(p) + q = stats.levy_l.sf(x) + assert_allclose(q, p, rtol=5e-14) + + +def test_hypergeom_interval_1802(): + # these two had endless loops + assert_equal(stats.hypergeom.interval(.95, 187601, 43192, 757), + (152.0, 197.0)) + assert_equal(stats.hypergeom.interval(.945, 187601, 43192, 757), + (152.0, 197.0)) + # this was working also before + assert_equal(stats.hypergeom.interval(.94, 187601, 43192, 757), + (153.0, 196.0)) + + # degenerate case .a == .b + assert_equal(stats.hypergeom.ppf(0.02, 100, 100, 8), 8) + assert_equal(stats.hypergeom.ppf(1, 100, 100, 8), 8) + + +def test_distribution_too_many_args(): + np.random.seed(1234) + + # Check that a TypeError is raised when too many args are given to a method + # Regression test for ticket 1815. + x = np.linspace(0.1, 0.7, num=5) + assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0) + assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0) + assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5) + assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5) + assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5) + assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5) + assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5) + assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5) + assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5) + assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5) + + # These should not give errors + stats.gamma.pdf(x, 2, 3) # loc=3 + stats.gamma.pdf(x, 2, 3, 4) # loc=3, scale=4 + stats.gamma.stats(2., 3) + stats.gamma.stats(2., 3, 4) + stats.gamma.stats(2., 3, 4, 'mv') + stats.gamma.rvs(2., 3, 4, 5) + stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.) + + # Also for a discrete distribution + stats.geom.pmf(x, 2, loc=3) # no error, loc=3 + assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4) + assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4) + + # And for distributions with 0, 2 and 3 args respectively + assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0) + assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0) + assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1) + assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0) + assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5) + stats.ncf.pdf(x, 3, 4, 5, 6, 1.0) # 3 args, plus loc/scale + + +def test_ncx2_tails_ticket_955(): + # Trac #955 -- check that the cdf computed by special functions + # matches the integrated pdf + a = stats.ncx2.cdf(np.arange(20, 25, 0.2), 2, 1.07458615e+02) + b = stats.ncx2._cdfvec(np.arange(20, 25, 0.2), 2, 1.07458615e+02) + assert_allclose(a, b, rtol=1e-3, atol=0) + + +def test_ncx2_tails_pdf(): + # ncx2.pdf does not return nans in extreme tails(example from gh-1577) + # NB: this is to check that nan_to_num is not needed in ncx2.pdf + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + assert_equal(stats.ncx2.pdf(1, np.arange(340, 350), 2), 0) + logval = stats.ncx2.logpdf(1, np.arange(340, 350), 2) + + assert_(np.isneginf(logval).all()) + + # Verify logpdf has extended precision when pdf underflows to 0 + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + assert_equal(stats.ncx2.pdf(10000, 3, 12), 0) + assert_allclose(stats.ncx2.logpdf(10000, 3, 12), -4662.444377524883) + + +@pytest.mark.parametrize('method, expected', [ + ('cdf', np.array([2.497951336e-09, 3.437288941e-10])), + ('pdf', np.array([1.238579980e-07, 1.710041145e-08])), + ('logpdf', np.array([-15.90413011, -17.88416331])), + ('ppf', np.array([4.865182052, 7.017182271])) +]) +def test_ncx2_zero_nc(method, expected): + # gh-5441 + # ncx2 with nc=0 is identical to chi2 + # Comparison to R (v3.5.1) + # > options(digits=10) + # > pchisq(0.1, df=10, ncp=c(0,4)) + # > dchisq(0.1, df=10, ncp=c(0,4)) + # > dchisq(0.1, df=10, ncp=c(0,4), log=TRUE) + # > qchisq(0.1, df=10, ncp=c(0,4)) + + result = getattr(stats.ncx2, method)(0.1, nc=[0, 4], df=10) + assert_allclose(result, expected, atol=1e-15) + + +def test_ncx2_zero_nc_rvs(): + # gh-5441 + # ncx2 with nc=0 is identical to chi2 + result = stats.ncx2.rvs(df=10, nc=0, random_state=1) + expected = stats.chi2.rvs(df=10, random_state=1) + assert_allclose(result, expected, atol=1e-15) + + +def test_ncx2_gh12731(): + # test that gh-12731 is resolved; previously these were all 0.5 + nc = 10**np.arange(5, 10) + assert_equal(stats.ncx2.cdf(1e4, df=1, nc=nc), 0) + + +def test_ncx2_gh8665(): + # test that gh-8665 is resolved; previously this tended to nonzero value + x = np.array([4.99515382e+00, 1.07617327e+01, 2.31854502e+01, + 4.99515382e+01, 1.07617327e+02, 2.31854502e+02, + 4.99515382e+02, 1.07617327e+03, 2.31854502e+03, + 4.99515382e+03, 1.07617327e+04, 2.31854502e+04, + 4.99515382e+04]) + nu, lam = 20, 499.51538166556196 + + sf = stats.ncx2.sf(x, df=nu, nc=lam) + # computed in R. Couldn't find a survival function implementation + # options(digits=16) + # x <- c(4.99515382e+00, 1.07617327e+01, 2.31854502e+01, 4.99515382e+01, + # 1.07617327e+02, 2.31854502e+02, 4.99515382e+02, 1.07617327e+03, + # 2.31854502e+03, 4.99515382e+03, 1.07617327e+04, 2.31854502e+04, + # 4.99515382e+04) + # nu <- 20 + # lam <- 499.51538166556196 + # 1 - pchisq(x, df = nu, ncp = lam) + sf_expected = [1.0000000000000000, 1.0000000000000000, 1.0000000000000000, + 1.0000000000000000, 1.0000000000000000, 0.9999999999999888, + 0.6646525582135460, 0.0000000000000000, 0.0000000000000000, + 0.0000000000000000, 0.0000000000000000, 0.0000000000000000, + 0.0000000000000000] + assert_allclose(sf, sf_expected, atol=1e-12) + + +def test_ncx2_gh11777(): + # regression test for gh-11777: + # At high values of degrees of freedom df, ensure the pdf of ncx2 does + # not get clipped to zero when the non-centrality parameter is + # sufficiently less than df + df = 6700 + nc = 5300 + x = np.linspace(stats.ncx2.ppf(0.001, df, nc), + stats.ncx2.ppf(0.999, df, nc), num=10000) + ncx2_pdf = stats.ncx2.pdf(x, df, nc) + gauss_approx = stats.norm.pdf(x, df + nc, np.sqrt(2 * df + 4 * nc)) + # use huge tolerance as we're only looking for obvious discrepancy + assert_allclose(ncx2_pdf, gauss_approx, atol=1e-4) + + +# Expected values for foldnorm.sf were computed with mpmath: +# +# from mpmath import mp +# mp.dps = 60 +# def foldcauchy_sf(x, c): +# x = mp.mpf(x) +# c = mp.mpf(c) +# return mp.one - (mp.atan(x - c) + mp.atan(x + c))/mp.pi +# +# E.g. +# +# >>> float(foldcauchy_sf(2, 1)) +# 0.35241638234956674 +# +@pytest.mark.parametrize('x, c, expected', + [(2, 1, 0.35241638234956674), + (2, 2, 0.5779791303773694), + (1e13, 1, 6.366197723675813e-14), + (2e16, 1, 3.183098861837907e-17), + (1e13, 2e11, 6.368745221764519e-14), + (0.125, 200, 0.999998010612169)]) +def test_foldcauchy_sf(x, c, expected): + sf = stats.foldcauchy.sf(x, c) + assert_allclose(sf, expected, 2e-15) + + +# The same mpmath code shown in the comments above test_foldcauchy_sf() +# is used to create these expected values. +@pytest.mark.parametrize('x, expected', + [(2, 0.2951672353008665), + (1e13, 6.366197723675813e-14), + (2e16, 3.183098861837907e-17), + (5e80, 1.2732395447351629e-81)]) +def test_halfcauchy_sf(x, expected): + sf = stats.halfcauchy.sf(x) + assert_allclose(sf, expected, 2e-15) + + +# Expected value computed with mpmath: +# expected = mp.cot(mp.pi*p/2) +@pytest.mark.parametrize('p, expected', + [(0.9999995, 7.853981633329977e-07), + (0.975, 0.039290107007669675), + (0.5, 1.0), + (0.01, 63.65674116287158), + (1e-14, 63661977236758.13), + (5e-80, 1.2732395447351627e+79)]) +def test_halfcauchy_isf(p, expected): + x = stats.halfcauchy.isf(p) + assert_allclose(x, expected) + + +def test_foldnorm_zero(): + # Parameter value c=0 was not enabled, see gh-2399. + rv = stats.foldnorm(0, scale=1) + assert_equal(rv.cdf(0), 0) # rv.cdf(0) previously resulted in: nan + + +# Expected values for foldnorm.sf were computed with mpmath: +# +# from mpmath import mp +# mp.dps = 60 +# def foldnorm_sf(x, c): +# x = mp.mpf(x) +# c = mp.mpf(c) +# return mp.ncdf(-x+c) + mp.ncdf(-x-c) +# +# E.g. +# +# >>> float(foldnorm_sf(2, 1)) +# 0.16000515196308715 +# +@pytest.mark.parametrize('x, c, expected', + [(2, 1, 0.16000515196308715), + (20, 1, 8.527223952630977e-81), + (10, 15, 0.9999997133484281), + (25, 15, 7.619853024160525e-24)]) +def test_foldnorm_sf(x, c, expected): + sf = stats.foldnorm.sf(x, c) + assert_allclose(sf, expected, 1e-14) + + +def test_stats_shapes_argcheck(): + # stats method was failing for vector shapes if some of the values + # were outside of the allowed range, see gh-2678 + mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5) # 0 is not a legal `a` + mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5) + mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2) + assert_equal(mv2_augmented, mv3) + + # -1 is not a legal shape parameter + mv3 = stats.lognorm.stats([2, 2.4, -1]) + mv2 = stats.lognorm.stats([2, 2.4]) + mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2) + assert_equal(mv2_augmented, mv3) + + # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix. + # stats method with multiple shape parameters is not properly vectorized + # anyway, so some distributions may or may not fail. + + +# Test subclassing distributions w/ explicit shapes + +class _distr_gen(stats.rv_continuous): + def _pdf(self, x, a): + return 42 + + +class _distr2_gen(stats.rv_continuous): + def _cdf(self, x, a): + return 42 * a + x + + +class _distr3_gen(stats.rv_continuous): + def _pdf(self, x, a, b): + return a + b + + def _cdf(self, x, a): + # Different # of shape params from _pdf, to be able to check that + # inspection catches the inconsistency. + return 42 * a + x + + +class _distr6_gen(stats.rv_continuous): + # Two shape parameters (both _pdf and _cdf defined, consistent shapes.) + def _pdf(self, x, a, b): + return a*x + b + + def _cdf(self, x, a, b): + return 42 * a + x + + +class TestSubclassingExplicitShapes: + # Construct a distribution w/ explicit shapes parameter and test it. + + def test_correct_shapes(self): + dummy_distr = _distr_gen(name='dummy', shapes='a') + assert_equal(dummy_distr.pdf(1, a=1), 42) + + def test_wrong_shapes_1(self): + dummy_distr = _distr_gen(name='dummy', shapes='A') + assert_raises(TypeError, dummy_distr.pdf, 1, **dict(a=1)) + + def test_wrong_shapes_2(self): + dummy_distr = _distr_gen(name='dummy', shapes='a, b, c') + dct = dict(a=1, b=2, c=3) + assert_raises(TypeError, dummy_distr.pdf, 1, **dct) + + def test_shapes_string(self): + # shapes must be a string + dct = dict(name='dummy', shapes=42) + assert_raises(TypeError, _distr_gen, **dct) + + def test_shapes_identifiers_1(self): + # shapes must be a comma-separated list of valid python identifiers + dct = dict(name='dummy', shapes='(!)') + assert_raises(SyntaxError, _distr_gen, **dct) + + def test_shapes_identifiers_2(self): + dct = dict(name='dummy', shapes='4chan') + assert_raises(SyntaxError, _distr_gen, **dct) + + def test_shapes_identifiers_3(self): + dct = dict(name='dummy', shapes='m(fti)') + assert_raises(SyntaxError, _distr_gen, **dct) + + def test_shapes_identifiers_nodefaults(self): + dct = dict(name='dummy', shapes='a=2') + assert_raises(SyntaxError, _distr_gen, **dct) + + def test_shapes_args(self): + dct = dict(name='dummy', shapes='*args') + assert_raises(SyntaxError, _distr_gen, **dct) + + def test_shapes_kwargs(self): + dct = dict(name='dummy', shapes='**kwargs') + assert_raises(SyntaxError, _distr_gen, **dct) + + def test_shapes_keywords(self): + # python keywords cannot be used for shape parameters + dct = dict(name='dummy', shapes='a, b, c, lambda') + assert_raises(SyntaxError, _distr_gen, **dct) + + def test_shapes_signature(self): + # test explicit shapes which agree w/ the signature of _pdf + class _dist_gen(stats.rv_continuous): + def _pdf(self, x, a): + return stats.norm._pdf(x) * a + + dist = _dist_gen(shapes='a') + assert_equal(dist.pdf(0.5, a=2), stats.norm.pdf(0.5)*2) + + def test_shapes_signature_inconsistent(self): + # test explicit shapes which do not agree w/ the signature of _pdf + class _dist_gen(stats.rv_continuous): + def _pdf(self, x, a): + return stats.norm._pdf(x) * a + + dist = _dist_gen(shapes='a, b') + assert_raises(TypeError, dist.pdf, 0.5, **dict(a=1, b=2)) + + def test_star_args(self): + # test _pdf with only starargs + # NB: **kwargs of pdf will never reach _pdf + class _dist_gen(stats.rv_continuous): + def _pdf(self, x, *args): + extra_kwarg = args[0] + return stats.norm._pdf(x) * extra_kwarg + + dist = _dist_gen(shapes='extra_kwarg') + assert_equal(dist.pdf(0.5, extra_kwarg=33), stats.norm.pdf(0.5)*33) + assert_equal(dist.pdf(0.5, 33), stats.norm.pdf(0.5)*33) + assert_raises(TypeError, dist.pdf, 0.5, **dict(xxx=33)) + + def test_star_args_2(self): + # test _pdf with named & starargs + # NB: **kwargs of pdf will never reach _pdf + class _dist_gen(stats.rv_continuous): + def _pdf(self, x, offset, *args): + extra_kwarg = args[0] + return stats.norm._pdf(x) * extra_kwarg + offset + + dist = _dist_gen(shapes='offset, extra_kwarg') + assert_equal(dist.pdf(0.5, offset=111, extra_kwarg=33), + stats.norm.pdf(0.5)*33 + 111) + assert_equal(dist.pdf(0.5, 111, 33), + stats.norm.pdf(0.5)*33 + 111) + + def test_extra_kwarg(self): + # **kwargs to _pdf are ignored. + # this is a limitation of the framework (_pdf(x, *goodargs)) + class _distr_gen(stats.rv_continuous): + def _pdf(self, x, *args, **kwargs): + # _pdf should handle *args, **kwargs itself. Here "handling" + # is ignoring *args and looking for ``extra_kwarg`` and using + # that. + extra_kwarg = kwargs.pop('extra_kwarg', 1) + return stats.norm._pdf(x) * extra_kwarg + + dist = _distr_gen(shapes='extra_kwarg') + assert_equal(dist.pdf(1, extra_kwarg=3), stats.norm.pdf(1)) + + def test_shapes_empty_string(self): + # shapes='' is equivalent to shapes=None + class _dist_gen(stats.rv_continuous): + def _pdf(self, x): + return stats.norm.pdf(x) + + dist = _dist_gen(shapes='') + assert_equal(dist.pdf(0.5), stats.norm.pdf(0.5)) + + +class TestSubclassingNoShapes: + # Construct a distribution w/o explicit shapes parameter and test it. + + def test_only__pdf(self): + dummy_distr = _distr_gen(name='dummy') + assert_equal(dummy_distr.pdf(1, a=1), 42) + + def test_only__cdf(self): + # _pdf is determined from _cdf by taking numerical derivative + dummy_distr = _distr2_gen(name='dummy') + assert_almost_equal(dummy_distr.pdf(1, a=1), 1) + + @pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped") + def test_signature_inspection(self): + # check that _pdf signature inspection works correctly, and is used in + # the class docstring + dummy_distr = _distr_gen(name='dummy') + assert_equal(dummy_distr.numargs, 1) + assert_equal(dummy_distr.shapes, 'a') + res = re.findall(r'logpdf\(x, a, loc=0, scale=1\)', + dummy_distr.__doc__) + assert_(len(res) == 1) + + @pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped") + def test_signature_inspection_2args(self): + # same for 2 shape params and both _pdf and _cdf defined + dummy_distr = _distr6_gen(name='dummy') + assert_equal(dummy_distr.numargs, 2) + assert_equal(dummy_distr.shapes, 'a, b') + res = re.findall(r'logpdf\(x, a, b, loc=0, scale=1\)', + dummy_distr.__doc__) + assert_(len(res) == 1) + + def test_signature_inspection_2args_incorrect_shapes(self): + # both _pdf and _cdf defined, but shapes are inconsistent: raises + assert_raises(TypeError, _distr3_gen, name='dummy') + + def test_defaults_raise(self): + # default arguments should raise + class _dist_gen(stats.rv_continuous): + def _pdf(self, x, a=42): + return 42 + assert_raises(TypeError, _dist_gen, **dict(name='dummy')) + + def test_starargs_raise(self): + # without explicit shapes, *args are not allowed + class _dist_gen(stats.rv_continuous): + def _pdf(self, x, a, *args): + return 42 + assert_raises(TypeError, _dist_gen, **dict(name='dummy')) + + def test_kwargs_raise(self): + # without explicit shapes, **kwargs are not allowed + class _dist_gen(stats.rv_continuous): + def _pdf(self, x, a, **kwargs): + return 42 + assert_raises(TypeError, _dist_gen, **dict(name='dummy')) + + +@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped") +def test_docstrings(): + badones = [r',\s*,', r'\(\s*,', r'^\s*:'] + for distname in stats.__all__: + dist = getattr(stats, distname) + if isinstance(dist, (stats.rv_discrete | stats.rv_continuous)): + for regex in badones: + assert_(re.search(regex, dist.__doc__) is None) + + +def test_infinite_input(): + assert_almost_equal(stats.skellam.sf(np.inf, 10, 11), 0) + assert_almost_equal(stats.ncx2._cdf(np.inf, 8, 0.1), 1) + + +def test_lomax_accuracy(): + # regression test for gh-4033 + p = stats.lomax.ppf(stats.lomax.cdf(1e-100, 1), 1) + assert_allclose(p, 1e-100) + + +def test_truncexpon_accuracy(): + # regression test for gh-4035 + p = stats.truncexpon.ppf(stats.truncexpon.cdf(1e-100, 1), 1) + assert_allclose(p, 1e-100) + + +def test_rayleigh_accuracy(): + # regression test for gh-4034 + p = stats.rayleigh.isf(stats.rayleigh.sf(9, 1), 1) + assert_almost_equal(p, 9.0, decimal=15) + + +def test_genextreme_give_no_warnings(): + """regression test for gh-6219""" + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + stats.genextreme.cdf(.5, 0) + stats.genextreme.pdf(.5, 0) + stats.genextreme.ppf(.5, 0) + stats.genextreme.logpdf(-np.inf, 0.0) + number_of_warnings_thrown = len(w) + assert_equal(number_of_warnings_thrown, 0) + + +def test_moments_gh22400(): + # Regression test for gh-22400 + # Check for correct results at c=0 with no warnings. While we're at it, + # check that NaN and sufficiently negative input produce NaNs, and output + # with `c=1` also agrees with reference values. + res = np.asarray(stats.genextreme.stats([0.0, np.nan, 1, -1.5], moments='mvsk')) + + # Reference values for c=0 (Wikipedia) + mean = np.euler_gamma + var = np.pi**2 / 6 + skew = 12 * np.sqrt(6) * special.zeta(3) / np.pi**3 + kurt = 12 / 5 + ref_0 = [mean, var, skew, kurt] + ref_1 = ref_3 = [np.nan]*4 + ref_2 = [0, 1, -2, 6] # Wolfram Alpha, MaxStableDistribution[0, 1, -1] + + assert_allclose(res[:, 0], ref_0, rtol=1e-14) + assert_equal(res[:, 1], ref_1) + assert_allclose(res[:, 2], ref_2, rtol=1e-14) + assert_equal(res[:, 3], ref_3) + + +def test_genextreme_entropy(): + # regression test for gh-5181 + euler_gamma = 0.5772156649015329 + + h = stats.genextreme.entropy(-1.0) + assert_allclose(h, 2*euler_gamma + 1, rtol=1e-14) + + h = stats.genextreme.entropy(0) + assert_allclose(h, euler_gamma + 1, rtol=1e-14) + + h = stats.genextreme.entropy(1.0) + assert_equal(h, 1) + + h = stats.genextreme.entropy(-2.0, scale=10) + assert_allclose(h, euler_gamma*3 + np.log(10) + 1, rtol=1e-14) + + h = stats.genextreme.entropy(10) + assert_allclose(h, -9*euler_gamma + 1, rtol=1e-14) + + h = stats.genextreme.entropy(-10) + assert_allclose(h, 11*euler_gamma + 1, rtol=1e-14) + + +def test_genextreme_sf_isf(): + # Expected values were computed using mpmath: + # + # import mpmath + # + # def mp_genextreme_sf(x, xi, mu=0, sigma=1): + # # Formula from wikipedia, which has a sign convention for xi that + # # is the opposite of scipy's shape parameter. + # if xi != 0: + # t = mpmath.power(1 + ((x - mu)/sigma)*xi, -1/xi) + # else: + # t = mpmath.exp(-(x - mu)/sigma) + # return 1 - mpmath.exp(-t) + # + # >>> mpmath.mp.dps = 1000 + # >>> s = mp_genextreme_sf(mpmath.mp.mpf("1e8"), mpmath.mp.mpf("0.125")) + # >>> float(s) + # 1.6777205262585625e-57 + # >>> s = mp_genextreme_sf(mpmath.mp.mpf("7.98"), mpmath.mp.mpf("-0.125")) + # >>> float(s) + # 1.52587890625e-21 + # >>> s = mp_genextreme_sf(mpmath.mp.mpf("7.98"), mpmath.mp.mpf("0")) + # >>> float(s) + # 0.00034218086528426593 + + x = 1e8 + s = stats.genextreme.sf(x, -0.125) + assert_allclose(s, 1.6777205262585625e-57) + x2 = stats.genextreme.isf(s, -0.125) + assert_allclose(x2, x) + + x = 7.98 + s = stats.genextreme.sf(x, 0.125) + assert_allclose(s, 1.52587890625e-21) + x2 = stats.genextreme.isf(s, 0.125) + assert_allclose(x2, x) + + x = 7.98 + s = stats.genextreme.sf(x, 0) + assert_allclose(s, 0.00034218086528426593) + x2 = stats.genextreme.isf(s, 0) + assert_allclose(x2, x) + + +def test_burr12_ppf_small_arg(): + prob = 1e-16 + quantile = stats.burr12.ppf(prob, 2, 3) + # The expected quantile was computed using mpmath: + # >>> import mpmath + # >>> mpmath.mp.dps = 100 + # >>> prob = mpmath.mpf('1e-16') + # >>> c = mpmath.mpf(2) + # >>> d = mpmath.mpf(3) + # >>> float(((1-prob)**(-1/d) - 1)**(1/c)) + # 5.7735026918962575e-09 + assert_allclose(quantile, 5.7735026918962575e-09) + + +def test_invweibull_fit(): + """ + Test fitting invweibull to data. + + Here is a the same calculation in R: + + > library(evd) + > library(fitdistrplus) + > x = c(1, 1.25, 2, 2.5, 2.8, 3, 3.8, 4, 5, 8, 10, 12, 64, 99) + > result = fitdist(x, 'frechet', control=list(reltol=1e-13), + + fix.arg=list(loc=0), start=list(shape=2, scale=3)) + > result + Fitting of the distribution ' frechet ' by maximum likelihood + Parameters: + estimate Std. Error + shape 1.048482 0.2261815 + scale 3.099456 0.8292887 + Fixed parameters: + value + loc 0 + + """ + + def optimizer(func, x0, args=(), disp=0): + return fmin(func, x0, args=args, disp=disp, xtol=1e-12, ftol=1e-12) + + x = np.array([1, 1.25, 2, 2.5, 2.8, 3, 3.8, 4, 5, 8, 10, 12, 64, 99]) + c, loc, scale = stats.invweibull.fit(x, floc=0, optimizer=optimizer) + assert_allclose(c, 1.048482, rtol=5e-6) + assert loc == 0 + assert_allclose(scale, 3.099456, rtol=5e-6) + + +# Expected values were computed with mpmath. +@pytest.mark.parametrize('x, c, expected', + [(3, 1.5, 0.175064510070713299327), + (2000, 1.5, 1.11802773877318715787e-5), + (2000, 9.25, 2.92060308832269637092e-31), + (1e15, 1.5, 3.16227766016837933199884e-23)]) +def test_invweibull_sf(x, c, expected): + computed = stats.invweibull.sf(x, c) + assert_allclose(computed, expected, rtol=1e-15) + + +# Expected values were computed with mpmath. +@pytest.mark.parametrize('p, c, expected', + [(0.5, 2.5, 1.15789669836468183976), + (3e-18, 5, 3195.77171838060906447)]) +def test_invweibull_isf(p, c, expected): + computed = stats.invweibull.isf(p, c) + assert_allclose(computed, expected, rtol=1e-15) + + +@pytest.mark.parametrize( + 'df1,df2,x', + [(2, 2, [-0.5, 0.2, 1.0, 2.3]), + (4, 11, [-0.5, 0.2, 1.0, 2.3]), + (7, 17, [1, 2, 3, 4, 5])] +) +def test_ncf_edge_case(df1, df2, x): + # Test for edge case described in gh-11660. + # Non-central Fisher distribution when nc = 0 + # should be the same as Fisher distribution. + nc = 0 + expected_cdf = stats.f.cdf(x, df1, df2) + calculated_cdf = stats.ncf.cdf(x, df1, df2, nc) + assert_allclose(expected_cdf, calculated_cdf, rtol=1e-14) + + # when ncf_gen._skip_pdf will be used instead of generic pdf, + # this additional test will be useful. + expected_pdf = stats.f.pdf(x, df1, df2) + calculated_pdf = stats.ncf.pdf(x, df1, df2, nc) + assert_allclose(expected_pdf, calculated_pdf, rtol=1e-6) + + +def test_ncf_variance(): + # Regression test for gh-10658 (incorrect variance formula for ncf). + # The correct value of ncf.var(2, 6, 4), 42.75, can be verified with, for + # example, Wolfram Alpha with the expression + # Variance[NoncentralFRatioDistribution[2, 6, 4]] + # or with the implementation of the noncentral F distribution in the C++ + # library Boost. + v = stats.ncf.var(2, 6, 4) + assert_allclose(v, 42.75, rtol=1e-14) + + +def test_ncf_cdf_spotcheck(): + # Regression test for gh-15582 testing against values from R/MATLAB + # Generate check_val from R or MATLAB as follows: + # R: pf(20, df1 = 6, df2 = 33, ncp = 30.4) = 0.998921 + # MATLAB: ncfcdf(20, 6, 33, 30.4) = 0.998921 + scipy_val = stats.ncf.cdf(20, 6, 33, 30.4) + check_val = 0.998921 + assert_allclose(check_val, np.round(scipy_val, decimals=6)) + + +def test_ncf_ppf_issue_17026(): + # Regression test for gh-17026 + x = np.linspace(0, 1, 600) + x[0] = 1e-16 + par = (0.1, 2, 5, 0, 1) + q = stats.ncf.ppf(x, *par) + q0 = [stats.ncf.ppf(xi, *par) for xi in x] + assert_allclose(q, q0) + + +class TestHistogram: + def setup_method(self): + np.random.seed(1234) + + # We have 8 bins + # [1,2), [2,3), [3,4), [4,5), [5,6), [6,7), [7,8), [8,9) + # But actually np.histogram will put the last 9 also in the [8,9) bin! + # Therefore there is a slight difference below for the last bin, from + # what you might have expected. + histogram = np.histogram([1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, + 6, 6, 6, 6, 7, 7, 7, 8, 8, 9], bins=8) + self.template = stats.rv_histogram(histogram) + + data = stats.norm.rvs(loc=1.0, scale=2.5, size=10000, random_state=123) + norm_histogram = np.histogram(data, bins=50) + self.norm_template = stats.rv_histogram(norm_histogram) + + def test_pdf(self): + values = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, + 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]) + pdf_values = np.asarray([0.0/25.0, 0.0/25.0, 1.0/25.0, 1.0/25.0, + 2.0/25.0, 2.0/25.0, 3.0/25.0, 3.0/25.0, + 4.0/25.0, 4.0/25.0, 5.0/25.0, 5.0/25.0, + 4.0/25.0, 4.0/25.0, 3.0/25.0, 3.0/25.0, + 3.0/25.0, 3.0/25.0, 0.0/25.0, 0.0/25.0]) + assert_allclose(self.template.pdf(values), pdf_values) + + # Test explicitly the corner cases: + # As stated above the pdf in the bin [8,9) is greater than + # one would naively expect because np.histogram putted the 9 + # into the [8,9) bin. + assert_almost_equal(self.template.pdf(8.0), 3.0/25.0) + assert_almost_equal(self.template.pdf(8.5), 3.0/25.0) + # 9 is outside our defined bins [8,9) hence the pdf is already 0 + # for a continuous distribution this is fine, because a single value + # does not have a finite probability! + assert_almost_equal(self.template.pdf(9.0), 0.0/25.0) + assert_almost_equal(self.template.pdf(10.0), 0.0/25.0) + + x = np.linspace(-2, 2, 10) + assert_allclose(self.norm_template.pdf(x), + stats.norm.pdf(x, loc=1.0, scale=2.5), rtol=0.1) + + def test_cdf_ppf(self): + values = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, + 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]) + cdf_values = np.asarray([0.0/25.0, 0.0/25.0, 0.0/25.0, 0.5/25.0, + 1.0/25.0, 2.0/25.0, 3.0/25.0, 4.5/25.0, + 6.0/25.0, 8.0/25.0, 10.0/25.0, 12.5/25.0, + 15.0/25.0, 17.0/25.0, 19.0/25.0, 20.5/25.0, + 22.0/25.0, 23.5/25.0, 25.0/25.0, 25.0/25.0]) + assert_allclose(self.template.cdf(values), cdf_values) + # First three and last two values in cdf_value are not unique + assert_allclose(self.template.ppf(cdf_values[2:-1]), values[2:-1]) + + # Test of cdf and ppf are inverse functions + x = np.linspace(1.0, 9.0, 100) + assert_allclose(self.template.ppf(self.template.cdf(x)), x) + x = np.linspace(0.0, 1.0, 100) + assert_allclose(self.template.cdf(self.template.ppf(x)), x) + + x = np.linspace(-2, 2, 10) + assert_allclose(self.norm_template.cdf(x), + stats.norm.cdf(x, loc=1.0, scale=2.5), rtol=0.1) + + def test_rvs(self): + N = 10000 + sample = self.template.rvs(size=N, random_state=123) + assert_equal(np.sum(sample < 1.0), 0.0) + assert_allclose(np.sum(sample <= 2.0), 1.0/25.0 * N, rtol=0.2) + assert_allclose(np.sum(sample <= 2.5), 2.0/25.0 * N, rtol=0.2) + assert_allclose(np.sum(sample <= 3.0), 3.0/25.0 * N, rtol=0.1) + assert_allclose(np.sum(sample <= 3.5), 4.5/25.0 * N, rtol=0.1) + assert_allclose(np.sum(sample <= 4.0), 6.0/25.0 * N, rtol=0.1) + assert_allclose(np.sum(sample <= 4.5), 8.0/25.0 * N, rtol=0.1) + assert_allclose(np.sum(sample <= 5.0), 10.0/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 5.5), 12.5/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 6.0), 15.0/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 6.5), 17.0/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 7.0), 19.0/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 7.5), 20.5/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 8.0), 22.0/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 8.5), 23.5/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 9.0), 25.0/25.0 * N, rtol=0.05) + assert_allclose(np.sum(sample <= 9.0), 25.0/25.0 * N, rtol=0.05) + assert_equal(np.sum(sample > 9.0), 0.0) + + def test_munp(self): + for n in range(4): + assert_allclose(self.norm_template._munp(n), + stats.norm(1.0, 2.5).moment(n), rtol=0.05) + + def test_entropy(self): + assert_allclose(self.norm_template.entropy(), + stats.norm.entropy(loc=1.0, scale=2.5), rtol=0.05) + + +def test_histogram_non_uniform(): + # Tests rv_histogram works even for non-uniform bin widths + counts, bins = ([1, 1], [0, 1, 1001]) + + dist = stats.rv_histogram((counts, bins), density=False) + np.testing.assert_allclose(dist.pdf([0.5, 200]), [0.5, 0.0005]) + assert dist.median() == 1 + + dist = stats.rv_histogram((counts, bins), density=True) + np.testing.assert_allclose(dist.pdf([0.5, 200]), 1/1001) + assert dist.median() == 1001/2 + + # Omitting density produces a warning for non-uniform bins... + message = "Bin widths are not constant. Assuming..." + with pytest.warns(RuntimeWarning, match=message): + dist = stats.rv_histogram((counts, bins)) + assert dist.median() == 1001/2 # default is like `density=True` + + # ... but not for uniform bins + dist = stats.rv_histogram((counts, [0, 1, 2])) + assert dist.median() == 1 + + +class TestLogUniform: + def test_alias(self): + # This test makes sure that "reciprocal" and "loguniform" are + # aliases of the same distribution and that both are log-uniform + rng = np.random.default_rng(98643218961) + rv = stats.loguniform(10 ** -3, 10 ** 0) + rvs = rv.rvs(size=10000, random_state=rng) + + rng = np.random.default_rng(98643218961) + rv2 = stats.reciprocal(10 ** -3, 10 ** 0) + rvs2 = rv2.rvs(size=10000, random_state=rng) + + assert_allclose(rvs2, rvs) + + vals, _ = np.histogram(np.log10(rvs), bins=10) + assert 900 <= vals.min() <= vals.max() <= 1100 + assert np.abs(np.median(vals) - 1000) <= 10 + + @pytest.mark.parametrize("method", ['mle', 'mm']) + def test_fit_override(self, method): + # loguniform is overparameterized, so check that fit override enforces + # scale=1 unless fscale is provided by the user + rng = np.random.default_rng(98643218961) + rvs = stats.loguniform.rvs(0.1, 1, size=1000, random_state=rng) + + a, b, loc, scale = stats.loguniform.fit(rvs, method=method) + assert scale == 1 + + a, b, loc, scale = stats.loguniform.fit(rvs, fscale=2, method=method) + assert scale == 2 + + def test_overflow(self): + # original formulation had overflow issues; check that this is resolved + # Extensive accuracy tests elsewhere, no need to test all methods + rng = np.random.default_rng(7136519550773909093) + a, b = 1e-200, 1e200 + dist = stats.loguniform(a, b) + + # test roundtrip error + cdf = rng.uniform(0, 1, size=1000) + assert_allclose(dist.cdf(dist.ppf(cdf)), cdf) + rvs = dist.rvs(size=1000) + assert_allclose(dist.ppf(dist.cdf(rvs)), rvs) + + # test a property of the pdf (and that there is no overflow) + x = 10.**np.arange(-200, 200) + pdf = dist.pdf(x) # no overflow + assert_allclose(pdf[:-1]/pdf[1:], 10) + + # check munp against wikipedia reference + mean = (b - a)/(np.log(b) - np.log(a)) + assert_allclose(dist.mean(), mean) + + +class TestArgus: + def test_argus_rvs_large_chi(self): + # test that the algorithm can handle large values of chi + x = stats.argus.rvs(50, size=500, random_state=325) + assert_almost_equal(stats.argus(50).mean(), x.mean(), decimal=4) + + @pytest.mark.parametrize('chi, random_state', [ + [0.1, 325], # chi <= 0.5: rejection method case 1 + [1.3, 155], # 0.5 < chi <= 1.8: rejection method case 2 + [3.5, 135] # chi > 1.8: transform conditional Gamma distribution + ]) + def test_rvs(self, chi, random_state): + x = stats.argus.rvs(chi, size=500, random_state=random_state) + _, p = stats.kstest(x, "argus", (chi, )) + assert_(p > 0.05) + + @pytest.mark.parametrize('chi', [1e-9, 1e-6]) + def test_rvs_small_chi(self, chi): + # test for gh-11699 => rejection method case 1 can even handle chi=0 + # the CDF of the distribution for chi=0 is 1 - (1 - x**2)**(3/2) + # test rvs against distribution of limit chi=0 + r = stats.argus.rvs(chi, size=500, random_state=890981) + _, p = stats.kstest(r, lambda x: 1 - (1 - x**2)**(3/2)) + assert_(p > 0.05) + + # Expected values were computed with mpmath. + @pytest.mark.parametrize('chi, expected_mean', + [(1, 0.6187026683551835), + (10, 0.984805536783744), + (40, 0.9990617659702923), + (60, 0.9995831885165300), + (99, 0.9998469348663028)]) + def test_mean(self, chi, expected_mean): + m = stats.argus.mean(chi, scale=1) + assert_allclose(m, expected_mean, rtol=1e-13) + + # Expected values were computed with mpmath. + @pytest.mark.parametrize('chi, expected_var, rtol', + [(1, 0.05215651254197807, 1e-13), + (10, 0.00015805472008165595, 1e-11), + (40, 5.877763210262901e-07, 1e-8), + (60, 1.1590179389611416e-07, 1e-8), + (99, 1.5623277006064666e-08, 1e-8)]) + def test_var(self, chi, expected_var, rtol): + v = stats.argus.var(chi, scale=1) + assert_allclose(v, expected_var, rtol=rtol) + + # Expected values were computed with mpmath (code: see gh-13370). + @pytest.mark.parametrize('chi, expected, rtol', + [(0.9, 0.07646314974436118, 1e-14), + (0.5, 0.015429797891863365, 1e-14), + (0.1, 0.0001325825293278049, 1e-14), + (0.01, 1.3297677078224565e-07, 1e-15), + (1e-3, 1.3298072023958999e-10, 1e-14), + (1e-4, 1.3298075973486862e-13, 1e-14), + (1e-6, 1.32980760133771e-19, 1e-14), + (1e-9, 1.329807601338109e-28, 1e-15)]) + def test_argus_phi_small_chi(self, chi, expected, rtol): + assert_allclose(_argus_phi(chi), expected, rtol=rtol) + + # Expected values were computed with mpmath (code: see gh-13370). + @pytest.mark.parametrize( + 'chi, expected', + [(0.5, (0.28414073302940573, 1.2742227939992954, 1.2381254688255896)), + (0.2, (0.296172952995264, 1.2951290588110516, 1.1865767100877576)), + (0.1, (0.29791447523536274, 1.29806307956989, 1.1793168289857412)), + (0.01, (0.2984904104866452, 1.2990283628160553, 1.1769268414080531)), + (1e-3, (0.298496172925224, 1.2990380082487925, 1.176902956021053)), + (1e-4, (0.29849623054991836, 1.2990381047023793, 1.1769027171686324)), + (1e-6, (0.2984962311319278, 1.2990381056765605, 1.1769027147562232)), + (1e-9, (0.298496231131986, 1.299038105676658, 1.1769027147559818))]) + def test_pdf_small_chi(self, chi, expected): + x = np.array([0.1, 0.5, 0.9]) + assert_allclose(stats.argus.pdf(x, chi), expected, rtol=1e-13) + + # Expected values were computed with mpmath (code: see gh-13370). + @pytest.mark.parametrize( + 'chi, expected', + [(0.5, (0.9857660526895221, 0.6616565930168475, 0.08796070398429937)), + (0.2, (0.9851555052359501, 0.6514666238985464, 0.08362690023746594)), + (0.1, (0.9850670974995661, 0.6500061310508574, 0.08302050640683846)), + (0.01, (0.9850378582451867, 0.6495239242251358, 0.08282109244852445)), + (1e-3, (0.9850375656906663, 0.6495191015522573, 0.08281910005231098)), + (1e-4, (0.9850375627651049, 0.6495190533254682, 0.08281908012852317)), + (1e-6, (0.9850375627355568, 0.6495190528383777, 0.08281907992729293)), + (1e-9, (0.9850375627355538, 0.649519052838329, 0.0828190799272728))]) + def test_sf_small_chi(self, chi, expected): + x = np.array([0.1, 0.5, 0.9]) + assert_allclose(stats.argus.sf(x, chi), expected, rtol=1e-14) + + # Expected values were computed with mpmath. + @pytest.mark.parametrize( + 'x, chi, expected', + [(0.9999999, 0.25, 9.113252974162428e-11), + (0.9999999, 3.0, 6.616650419714568e-10), + (0.999999999, 2.5, 4.130195911418939e-13), + (0.999999999, 10.0, 2.3788319094393724e-11)]) + def test_sf_near_1(self, x, chi, expected): + sf = stats.argus.sf(x, chi) + assert_allclose(sf, expected, rtol=5e-15) + + # Expected values were computed with mpmath (code: see gh-13370). + @pytest.mark.parametrize( + 'chi, expected', + [(0.5, (0.0142339473104779, 0.3383434069831524, 0.9120392960157007)), + (0.2, (0.014844494764049919, 0.34853337610145363, 0.916373099762534)), + (0.1, (0.014932902500433911, 0.34999386894914264, 0.9169794935931616)), + (0.01, (0.014962141754813293, 0.35047607577486417, 0.9171789075514756)), + (1e-3, (0.01496243430933372, 0.35048089844774266, 0.917180899947689)), + (1e-4, (0.014962437234895118, 0.3504809466745317, 0.9171809198714769)), + (1e-6, (0.01496243726444329, 0.3504809471616223, 0.9171809200727071)), + (1e-9, (0.014962437264446245, 0.350480947161671, 0.9171809200727272))]) + def test_cdf_small_chi(self, chi, expected): + x = np.array([0.1, 0.5, 0.9]) + assert_allclose(stats.argus.cdf(x, chi), expected, rtol=1e-12) + + # Expected values were computed with mpmath (code: see gh-13370). + @pytest.mark.parametrize( + 'chi, expected, rtol', + [(0.5, (0.5964284712757741, 0.052890651988588604), 1e-12), + (0.101, (0.5893490968089076, 0.053017469847275685), 1e-11), + (0.1, (0.5893431757009437, 0.05301755449499372), 1e-13), + (0.01, (0.5890515677940915, 0.05302167905837031), 1e-13), + (1e-3, (0.5890486520005177, 0.053021719862088104), 1e-13), + (1e-4, (0.5890486228426105, 0.0530217202700811), 1e-13), + (1e-6, (0.5890486225481156, 0.05302172027420182), 1e-13), + (1e-9, (0.5890486225480862, 0.05302172027420224), 1e-13)]) + def test_stats_small_chi(self, chi, expected, rtol): + val = stats.argus.stats(chi, moments='mv') + assert_allclose(val, expected, rtol=rtol) + + +class TestNakagami: + + def test_logpdf(self): + # Test nakagami logpdf for an input where the PDF is smaller + # than can be represented with 64 bit floating point. + # The expected value of logpdf was computed with mpmath: + # + # def logpdf(x, nu): + # x = mpmath.mpf(x) + # nu = mpmath.mpf(nu) + # return (mpmath.log(2) + nu*mpmath.log(nu) - + # mpmath.loggamma(nu) + (2*nu - 1)*mpmath.log(x) - + # nu*x**2) + # + nu = 2.5 + x = 25 + logp = stats.nakagami.logpdf(x, nu) + assert_allclose(logp, -1546.9253055607549) + + def test_sf_isf(self): + # Test nakagami sf and isf when the survival function + # value is very small. + # The expected value of the survival function was computed + # with mpmath: + # + # def sf(x, nu): + # x = mpmath.mpf(x) + # nu = mpmath.mpf(nu) + # return mpmath.gammainc(nu, nu*x*x, regularized=True) + # + nu = 2.5 + x0 = 5.0 + sf = stats.nakagami.sf(x0, nu) + assert_allclose(sf, 2.736273158588307e-25, rtol=1e-13) + # Check round trip back to x0. + x1 = stats.nakagami.isf(sf, nu) + assert_allclose(x1, x0, rtol=1e-13) + + def test_logcdf(self): + x = 8 + nu = 0.5 + # Reference value computed with mpmath. + ref = -1.2441921148543576e-15 + logcdf = stats.nakagami.logcdf(x, nu) + assert_allclose(logcdf, ref, rtol=5e-15) + + def test_logsf(self): + x = 0.05 + nu = 12 + # Reference value computed with mpmath. + ref = -1.0791764722337046e-27 + logsf = stats.nakagami.logsf(x, nu) + assert_allclose(logsf, ref, rtol=5e-15) + + @pytest.mark.parametrize("m, ref", + [(5, -0.097341814372152), + (0.5, 0.7257913526447274), + (10, -0.43426184310934907)]) + def test_entropy(self, m, ref): + # from sympy import * + # from mpmath import mp + # import numpy as np + # v, x = symbols('v, x', real=True, positive=True) + # pdf = 2 * v ** v / gamma(v) * x ** (2 * v - 1) * exp(-v * x ** 2) + # h = simplify(simplify(integrate(-pdf * log(pdf), (x, 0, oo)))) + # entropy = lambdify(v, h, 'mpmath') + # mp.dps = 200 + # nu = 5 + # ref = np.float64(entropy(mp.mpf(nu))) + # print(ref) + assert_allclose(stats.nakagami.entropy(m), ref, rtol=1.1e-14) + + @pytest.mark.parametrize("m, ref", + [(1e-100, -5.0e+99), (1e-10, -4999999965.442979), + (9.999e6, -7.333206478668433), (1.001e7, -7.3337562313259825), + (1e10, -10.787134112333835), (1e100, -114.40346329705756)]) + def test_extreme_nu(self, m, ref): + assert_allclose(stats.nakagami.entropy(m), ref) + + def test_entropy_overflow(self): + assert np.isfinite(stats.nakagami._entropy(1e100)) + assert np.isfinite(stats.nakagami._entropy(1e-100)) + + @pytest.mark.parametrize("nu, ref", + [(1e10, 0.9999999999875), + (1e3, 0.9998750078173821), + (1e-10, 1.772453850659802e-05)]) + def test_mean(self, nu, ref): + # reference values were computed with mpmath + # from mpmath import mp + # mp.dps = 500 + # nu = mp.mpf(1e10) + # float(mp.rf(nu, mp.mpf(0.5))/mp.sqrt(nu)) + assert_allclose(stats.nakagami.mean(nu), ref, rtol=1e-12) + + @pytest.mark.xfail(reason="Fit of nakagami not reliable, see gh-10908.") + @pytest.mark.parametrize('nu', [1.6, 2.5, 3.9]) + @pytest.mark.parametrize('loc', [25.0, 10, 35]) + @pytest.mark.parametrize('scale', [13, 5, 20]) + def test_fit(self, nu, loc, scale): + # Regression test for gh-13396 (21/27 cases failed previously) + # The first tuple of the parameters' values is discussed in gh-10908 + N = 100 + samples = stats.nakagami.rvs(size=N, nu=nu, loc=loc, + scale=scale, random_state=1337) + nu_est, loc_est, scale_est = stats.nakagami.fit(samples) + assert_allclose(nu_est, nu, rtol=0.2) + assert_allclose(loc_est, loc, rtol=0.2) + assert_allclose(scale_est, scale, rtol=0.2) + + def dlogl_dnu(nu, loc, scale): + return ((-2*nu + 1) * np.sum(1/(samples - loc)) + + 2*nu/scale**2 * np.sum(samples - loc)) + + def dlogl_dloc(nu, loc, scale): + return (N * (1 + np.log(nu) - polygamma(0, nu)) + + 2 * np.sum(np.log((samples - loc) / scale)) + - np.sum(((samples - loc) / scale)**2)) + + def dlogl_dscale(nu, loc, scale): + return (- 2 * N * nu / scale + + 2 * nu / scale ** 3 * np.sum((samples - loc) ** 2)) + + assert_allclose(dlogl_dnu(nu_est, loc_est, scale_est), 0, atol=1e-3) + assert_allclose(dlogl_dloc(nu_est, loc_est, scale_est), 0, atol=1e-3) + assert_allclose(dlogl_dscale(nu_est, loc_est, scale_est), 0, atol=1e-3) + + @pytest.mark.parametrize('loc', [25.0, 10, 35]) + @pytest.mark.parametrize('scale', [13, 5, 20]) + def test_fit_nu(self, loc, scale): + # For nu = 0.5, we have analytical values for + # the MLE of the loc and the scale + nu = 0.5 + n = 100 + samples = stats.nakagami.rvs(size=n, nu=nu, loc=loc, + scale=scale, random_state=1337) + nu_est, loc_est, scale_est = stats.nakagami.fit(samples, f0=nu) + + # Analytical values + loc_theo = np.min(samples) + scale_theo = np.sqrt(np.mean((samples - loc_est) ** 2)) + + assert_allclose(nu_est, nu, rtol=1e-7) + assert_allclose(loc_est, loc_theo, rtol=1e-7) + assert_allclose(scale_est, scale_theo, rtol=1e-7) + + +class TestWrapCauchy: + + def test_cdf_shape_broadcasting(self): + # Regression test for gh-13791. + # Check that wrapcauchy.cdf broadcasts the shape parameter + # correctly. + c = np.array([[0.03, 0.25], [0.5, 0.75]]) + x = np.array([[1.0], [4.0]]) + p = stats.wrapcauchy.cdf(x, c) + assert p.shape == (2, 2) + scalar_values = [stats.wrapcauchy.cdf(x1, c1) + for (x1, c1) in np.nditer((x, c))] + assert_allclose(p.ravel(), scalar_values, rtol=1e-13) + + def test_cdf_center(self): + p = stats.wrapcauchy.cdf(np.pi, 0.03) + assert_allclose(p, 0.5, rtol=1e-14) + + def test_cdf(self): + x1 = 1.0 # less than pi + x2 = 4.0 # greater than pi + c = 0.75 + p = stats.wrapcauchy.cdf([x1, x2], c) + cr = (1 + c)/(1 - c) + assert_allclose(p[0], np.arctan(cr*np.tan(x1/2))/np.pi) + assert_allclose(p[1], 1 - np.arctan(cr*np.tan(np.pi - x2/2))/np.pi) + + +def test_rvs_no_size_error(): + # _rvs methods must have parameter `size`; see gh-11394 + class rvs_no_size_gen(stats.rv_continuous): + def _rvs(self): + return 1 + + rvs_no_size = rvs_no_size_gen(name='rvs_no_size') + + with assert_raises(TypeError, match=r"_rvs\(\) got (an|\d) unexpected"): + rvs_no_size.rvs() + + +@pytest.mark.parametrize('distname, args', invdistdiscrete + invdistcont) +def test_support_gh13294_regression(distname, args): + if distname in skip_test_support_gh13294_regression: + pytest.skip(f"skipping test for the support method for " + f"distribution {distname}.") + dist = getattr(stats, distname) + # test support method with invalid arguments + if isinstance(dist, stats.rv_continuous): + # test with valid scale + if len(args) != 0: + a0, b0 = dist.support(*args) + assert_equal(a0, np.nan) + assert_equal(b0, np.nan) + # test with invalid scale + # For some distributions, that take no parameters, + # the case of only invalid scale occurs and hence, + # it is implicitly tested in this test case. + loc1, scale1 = 0, -1 + a1, b1 = dist.support(*args, loc1, scale1) + assert_equal(a1, np.nan) + assert_equal(b1, np.nan) + else: + a, b = dist.support(*args) + assert_equal(a, np.nan) + assert_equal(b, np.nan) + + +def test_support_broadcasting_gh13294_regression(): + a0, b0 = stats.norm.support([0, 0, 0, 1], [1, 1, 1, -1]) + ex_a0 = np.array([-np.inf, -np.inf, -np.inf, np.nan]) + ex_b0 = np.array([np.inf, np.inf, np.inf, np.nan]) + assert_equal(a0, ex_a0) + assert_equal(b0, ex_b0) + assert a0.shape == ex_a0.shape + assert b0.shape == ex_b0.shape + + a1, b1 = stats.norm.support([], []) + ex_a1, ex_b1 = np.array([]), np.array([]) + assert_equal(a1, ex_a1) + assert_equal(b1, ex_b1) + assert a1.shape == ex_a1.shape + assert b1.shape == ex_b1.shape + + a2, b2 = stats.norm.support([0, 0, 0, 1], [-1]) + ex_a2 = np.array(4*[np.nan]) + ex_b2 = np.array(4*[np.nan]) + assert_equal(a2, ex_a2) + assert_equal(b2, ex_b2) + assert a2.shape == ex_a2.shape + assert b2.shape == ex_b2.shape + + +def test_stats_broadcasting_gh14953_regression(): + # test case in gh14953 + loc = [0., 0.] + scale = [[1.], [2.], [3.]] + assert_equal(stats.norm.var(loc, scale), [[1., 1.], [4., 4.], [9., 9.]]) + # test some edge cases + loc = np.empty((0, )) + scale = np.empty((1, 0)) + assert stats.norm.var(loc, scale).shape == (1, 0) + + +# Check a few values of the cosine distribution's cdf, sf, ppf and +# isf methods. Expected values were computed with mpmath. + +@pytest.mark.parametrize('x, expected', + [(-3.14159, 4.956444476505336e-19), + (3.14, 0.9999999998928399)]) +def test_cosine_cdf_sf(x, expected): + assert_allclose(stats.cosine.cdf(x), expected) + assert_allclose(stats.cosine.sf(-x), expected) + + +@pytest.mark.parametrize('p, expected', + [(1e-6, -3.1080612413765905), + (1e-17, -3.141585429601399), + (0.975, 2.1447547020964923)]) +def test_cosine_ppf_isf(p, expected): + assert_allclose(stats.cosine.ppf(p), expected) + assert_allclose(stats.cosine.isf(p), -expected) + + +def test_cosine_logpdf_endpoints(): + logp = stats.cosine.logpdf([-np.pi, np.pi]) + # reference value calculated using mpmath assuming `np.cos(-1)` is four + # floating point numbers too high. See gh-18382. + assert_array_less(logp, -37.18838327496655) + + +def test_distr_params_lists(): + # distribution objects are extra distributions added in + # test_discrete_basic. All other distributions are strings (names) + # and so we only choose those to compare whether both lists match. + discrete_distnames = {name for name, _ in distdiscrete + if isinstance(name, str)} + invdiscrete_distnames = {name for name, _ in invdistdiscrete} + assert discrete_distnames == invdiscrete_distnames + + cont_distnames = {name for name, _ in distcont} + invcont_distnames = {name for name, _ in invdistcont} + assert cont_distnames == invcont_distnames + + +def test_moment_order_4(): + # gh-13655 reported that if a distribution has a `_stats` method that + # accepts the `moments` parameter, then if the distribution's `moment` + # method is called with `order=4`, the faster/more accurate`_stats` gets + # called, but the results aren't used, and the generic `_munp` method is + # called to calculate the moment anyway. This tests that the issue has + # been fixed. + # stats.skewnorm._stats accepts the `moments` keyword + stats.skewnorm._stats(a=0, moments='k') # no failure = has `moments` + # When `moment` is called, `_stats` is used, so the moment is very accurate + # (exactly equal to Pearson's kurtosis of the normal distribution, 3) + assert stats.skewnorm.moment(order=4, a=0) == 3.0 + # At the time of gh-13655, skewnorm._munp() used the generic method + # to compute its result, which was inefficient and not very accurate. + # At that time, the following assertion would fail. skewnorm._munp() + # has since been made more accurate and efficient, so now this test + # is expected to pass. + assert stats.skewnorm._munp(4, 0) == 3.0 + + +class TestRelativisticBW: + @pytest.fixture + def ROOT_pdf_sample_data(self): + """Sample data points for pdf computed with CERN's ROOT + + See - https://root.cern/ + + Uses ROOT.TMath.BreitWignerRelativistic, available in ROOT + versions 6.27+ + + pdf calculated for Z0 Boson, W Boson, and Higgs Boson for + x in `np.linspace(0, 200, 401)`. + """ + data = np.load( + Path(__file__).parent / + 'data/rel_breitwigner_pdf_sample_data_ROOT.npy' + ) + data = np.rec.fromarrays(data.T, names='x,pdf,rho,gamma') + return data + + @pytest.mark.parametrize( + "rho,gamma,rtol", [ + (36.545206797050334, 2.4952, 5e-14), # Z0 Boson + (38.55107913669065, 2.085, 1e-14), # W Boson + (96292.3076923077, 0.0013, 5e-13), # Higgs Boson + ] + ) + def test_pdf_against_ROOT(self, ROOT_pdf_sample_data, rho, gamma, rtol): + data = ROOT_pdf_sample_data[ + (ROOT_pdf_sample_data['rho'] == rho) + & (ROOT_pdf_sample_data['gamma'] == gamma) + ] + x, pdf = data['x'], data['pdf'] + assert_allclose( + pdf, stats.rel_breitwigner.pdf(x, rho, scale=gamma), rtol=rtol + ) + + @pytest.mark.parametrize("rho, Gamma, rtol", [ + (36.545206797050334, 2.4952, 5e-13), # Z0 Boson + (38.55107913669065, 2.085, 5e-13), # W Boson + (96292.3076923077, 0.0013, 5e-10), # Higgs Boson + ] + ) + def test_pdf_against_simple_implementation(self, rho, Gamma, rtol): + # reference implementation straight from formulas on Wikipedia [1] + def pdf(E, M, Gamma): + gamma = np.sqrt(M**2 * (M**2 + Gamma**2)) + k = (2 * np.sqrt(2) * M * Gamma * gamma + / (np.pi * np.sqrt(M**2 + gamma))) + return k / ((E**2 - M**2)**2 + M**2*Gamma**2) + # get reasonable values at which to evaluate the CDF + p = np.linspace(0.05, 0.95, 10) + x = stats.rel_breitwigner.ppf(p, rho, scale=Gamma) + res = stats.rel_breitwigner.pdf(x, rho, scale=Gamma) + ref = pdf(x, rho*Gamma, Gamma) + assert_allclose(res, ref, rtol=rtol) + + @pytest.mark.xslow + @pytest.mark.parametrize( + "rho,gamma", [ + pytest.param( + 36.545206797050334, 2.4952, marks=pytest.mark.slow + ), # Z0 Boson + pytest.param( + 38.55107913669065, 2.085, marks=pytest.mark.xslow + ), # W Boson + pytest.param( + 96292.3076923077, 0.0013, marks=pytest.mark.xslow + ), # Higgs Boson + ] + ) + def test_fit_floc(self, rho, gamma): + """Tests fit for cases where floc is set. + + `rel_breitwigner` has special handling for these cases. + """ + seed = 6936804688480013683 + rng = np.random.default_rng(seed) + data = stats.rel_breitwigner.rvs( + rho, scale=gamma, size=1000, random_state=rng + ) + fit = stats.rel_breitwigner.fit(data, floc=0) + assert_allclose((fit[0], fit[2]), (rho, gamma), rtol=2e-1) + assert fit[1] == 0 + # Check again with fscale set. + fit = stats.rel_breitwigner.fit(data, floc=0, fscale=gamma) + assert_allclose(fit[0], rho, rtol=1e-2) + assert (fit[1], fit[2]) == (0, gamma) + + +class TestJohnsonSU: + @pytest.mark.parametrize("case", [ # a, b, loc, scale, m1, m2, g1, g2 + (-0.01, 1.1, 0.02, 0.0001, 0.02000137427557091, + 2.1112742956578063e-08, 0.05989781342460999, 20.36324408592951-3), + (2.554395574161155, 2.2482281679651965, 0, 1, -1.54215386737391, + 0.7629882028469993, -1.256656139406788, 6.303058419339775-3)]) + def test_moment_gh18071(self, case): + # gh-18071 reported an IntegrationWarning emitted by johnsonsu.stats + # Check that the warning is no longer emitted and that the values + # are accurate compared against results from Mathematica. + # Reference values from Mathematica, e.g. + # Mean[JohnsonDistribution["SU",-0.01, 1.1, 0.02, 0.0001]] + res = stats.johnsonsu.stats(*case[:4], moments='mvsk') + assert_allclose(res, case[4:], rtol=1e-14) + + +class TestTruncPareto: + def test_pdf(self): + # PDF is that of the truncated pareto distribution + b, c = 1.8, 5.3 + x = np.linspace(1.8, 5.3) + res = stats.truncpareto(b, c).pdf(x) + ref = stats.pareto(b).pdf(x) / stats.pareto(b).cdf(c) + assert_allclose(res, ref) + + @pytest.mark.parametrize('fix_loc', [True, False]) + @pytest.mark.parametrize('fix_scale', [True, False]) + @pytest.mark.parametrize('fix_b', [True, False]) + @pytest.mark.parametrize('fix_c', [True, False]) + def test_fit(self, fix_loc, fix_scale, fix_b, fix_c): + + rng = np.random.default_rng(6747363148258237171) + b, c, loc, scale = 1.8, 5.3, 1, 2.5 + dist = stats.truncpareto(b, c, loc=loc, scale=scale) + data = dist.rvs(size=500, random_state=rng) + + kwds = {} + if fix_loc: + kwds['floc'] = loc + if fix_scale: + kwds['fscale'] = scale + if fix_b: + kwds['f0'] = b + if fix_c: + kwds['f1'] = c + + if fix_loc and fix_scale and fix_b and fix_c: + message = "All parameters fixed. There is nothing to optimize." + with pytest.raises(RuntimeError, match=message): + stats.truncpareto.fit(data, **kwds) + else: + _assert_less_or_close_loglike(stats.truncpareto, data, **kwds) + + +class TestKappa3: + def test_sf(self): + # During development of gh-18822, we found that the override of + # kappa3.sf could experience overflow where the version in main did + # not. Check that this does not happen in final implementation. + sf0 = 1 - stats.kappa3.cdf(0.5, 1e5) + sf1 = stats.kappa3.sf(0.5, 1e5) + assert_allclose(sf1, sf0) + + +class TestIrwinHall: + unif = stats.uniform(0, 1) + ih1 = stats.irwinhall(1) + ih10 = stats.irwinhall(10) + + def test_stats_ih10(self): + # from Wolfram Alpha "mean variance skew kurtosis UniformSumDistribution[10]" + # W|A uses Pearson's definition of kurtosis so subtract 3 + # should be exact integer division converted to fp64, without any further ops + assert_array_max_ulp(self.ih10.stats('mvsk'), (5, 10/12, 0, -3/25)) + + def test_moments_ih10(self): + # from Wolfram Alpha "values moments UniformSumDistribution[10]" + # algo should use integer division converted to fp64, without any further ops + # so these should be precise to the ulpm if not exact + vals = [5, 155 / 6, 275 / 2, 752, 12650 / 3, + 677465 / 28, 567325 / 4, + 15266213 / 18, 10333565 / 2] + moments = [self.ih10.moment(n+1) for n in range(len(vals))] + assert_array_max_ulp(moments, vals) + # also from Wolfram Alpha "50th moment UniformSumDistribution[10]" + m50 = self.ih10.moment(50) + m50_exact = 17453002755350010529309685557285098151740985685/4862 + assert_array_max_ulp(m50, m50_exact) + + def test_pdf_ih1_unif(self): + # IH(1) PDF is by definition U(0,1) + # we should be too, but differences in floating point eval order happen + # it's unclear if we can get down to the single ulp for doubles unless + # quads are used we're within 6-10 ulps otherwise (across sf/cdf/pdf) + # which is pretty good + + pts = np.linspace(0, 1, 100) + pdf_unif = self.unif.pdf(pts) + pdf_ih1 = self.ih1.pdf(pts) + assert_array_max_ulp(pdf_ih1, pdf_unif, maxulp=10) + + def test_pdf_ih2_triangle(self): + # IH(2) PDF is a triangle + ih2 = stats.irwinhall(2) + npts = 101 + pts = np.linspace(0, 2, npts) + expected = np.linspace(0, 2, npts) + expected[(npts + 1) // 2:] = 2 - expected[(npts + 1) // 2:] + pdf_ih2 = ih2.pdf(pts) + assert_array_max_ulp(pdf_ih2, expected, maxulp=10) + + def test_cdf_ih1_unif(self): + # CDF of IH(1) should be identical to uniform + pts = np.linspace(0, 1, 100) + cdf_unif = self.unif.cdf(pts) + cdf_ih1 = self.ih1.cdf(pts) + + assert_array_max_ulp(cdf_ih1, cdf_unif, maxulp=10) + + def test_cdf(self): + # CDF of IH is symmetric so CDF should be 0.5 at n/2 + n = np.arange(1, 10) + ih = stats.irwinhall(n) + ih_cdf = ih.cdf(n / 2) + exact = np.repeat(1/2, len(n)) + # should be identically 1/2 but fp order of eval differences happen + assert_array_max_ulp(ih_cdf, exact, maxulp=10) + + def test_cdf_ih10_exact(self): + # from Wolfram Alpha "values CDF[UniformSumDistribution[10], x] x=0 to x=10" + # symmetric about n/2, i.e., cdf[n-x] = 1-cdf[x] = sf[x] + vals = [0, 1 / 3628800, 169 / 604800, 24427 / 1814400, + 252023 / 1814400, 1 / 2, 1562377 / 1814400, + 1789973 / 1814400, 604631 / 604800, + 3628799 / 3628800, 1] + + # essentially a test of bspline evaluation + # this and the other ones are mostly to detect regressions + assert_array_max_ulp(self.ih10.cdf(np.arange(11)), vals, maxulp=10) + + assert_array_max_ulp(self.ih10.cdf(1/10), 1/36288000000000000, maxulp=10) + ref = 36287999999999999/36288000000000000 + assert_array_max_ulp(self.ih10.cdf(99/10), ref, maxulp=10) + + def test_pdf_ih10_exact(self): + # from Wolfram Alpha "values PDF[UniformSumDistribution[10], x] x=0 to x=10" + # symmetric about n/2 = 5 + vals = [0, 1 / 362880, 251 / 181440, 913 / 22680, 44117 / 181440] + vals += [15619 / 36288] + vals[::-1] + assert_array_max_ulp(self.ih10.pdf(np.arange(11)), vals, maxulp=10) + + def test_sf_ih10_exact(self): + assert_allclose(self.ih10.sf(np.arange(11)), 1 - self.ih10.cdf(np.arange(11))) + # from Wolfram Alpha "SurvivalFunction[UniformSumDistribution[10],x] at x=1/10" + # and symmetry about n/2 = 5 + # W|A returns 1 for CDF @ x=9.9 + ref = 36287999999999999/36288000000000000 + assert_array_max_ulp(self.ih10.sf(1/10), ref, maxulp=10) + + +class TestDParetoLognorm: + def test_against_R(self): + # Test against R implementation in `distributionsrd` + # library(distributionsrd) + # options(digits=16) + # x = 1.1 + # b = 2 + # a = 1.5 + # m = 3 + # s = 1.2 + # ddoubleparetolognormal(x, b, a, m, s) + # pdoubleparetolognormal(x, b, a, m, s) + x, m, s, a, b = 1.1, 3, 1.2, 1.5, 2 + dist = stats.dpareto_lognorm(m, s, a, b) + np.testing.assert_allclose(dist.pdf(x), 0.02490187219085912) + np.testing.assert_allclose(dist.cdf(x), 0.01664024173822796) + + +# Cases are (distribution name, log10 of smallest probability mass to test, +# log10 of the complement of the largest probability mass to test, atol, +# rtol). None uses default values. +@pytest.mark.parametrize("case", [("kappa3", None, None, None, None), + ("loglaplace", None, None, None, None), + ("lognorm", None, None, None, None), + ("lomax", None, None, None, None), + ("pareto", None, None, None, None),]) +def test_sf_isf_overrides(case): + # Test that SF is the inverse of ISF. Supplements + # `test_continuous_basic.check_sf_isf` for distributions with overridden + # `sf` and `isf` methods. + distname, lp1, lp2, atol, rtol = case + + lpm = np.log10(0.5) # log10 of the probability mass at the median + lp1 = lp1 or -290 + lp2 = lp2 or -14 + atol = atol or 0 + rtol = rtol or 1e-12 + dist = getattr(stats, distname) + params = dict(distcont)[distname] + dist_frozen = dist(*params) + + # Test (very deep) right tail to median. We can benchmark with random + # (loguniform) points, but strictly logspaced points are fine for tests. + ref = np.logspace(lp1, lpm) + res = dist_frozen.sf(dist_frozen.isf(ref)) + assert_allclose(res, ref, atol=atol, rtol=rtol) + + # test median to left tail + ref = 1 - np.logspace(lp2, lpm, 20) + res = dist_frozen.sf(dist_frozen.isf(ref)) + assert_allclose(res, ref, atol=atol, rtol=rtol) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_entropy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..4002b2c52703b0828d2f24bfa6d988b872576d4b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_entropy.py @@ -0,0 +1,330 @@ +import math +import pytest +from pytest import raises as assert_raises + +import numpy as np + +from scipy import stats +from scipy.stats import norm, expon # type: ignore[attr-defined] +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import array_namespace, is_array_api_strict, is_jax +from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal, + xp_assert_less) + +class TestEntropy: + @array_api_compatible + def test_entropy_positive(self, xp): + # See ticket #497 + pk = xp.asarray([0.5, 0.2, 0.3]) + qk = xp.asarray([0.1, 0.25, 0.65]) + eself = stats.entropy(pk, pk) + edouble = stats.entropy(pk, qk) + xp_assert_equal(eself, xp.asarray(0.)) + xp_assert_less(-edouble, xp.asarray(0.)) + + @array_api_compatible + def test_entropy_base(self, xp): + pk = xp.ones(16) + S = stats.entropy(pk, base=2.) + xp_assert_less(xp.abs(S - 4.), xp.asarray(1.e-5)) + + qk = xp.ones(16) + qk = xp.where(xp.arange(16) < 8, xp.asarray(2.), qk) + S = stats.entropy(pk, qk) + S2 = stats.entropy(pk, qk, base=2.) + xp_assert_less(xp.abs(S/S2 - math.log(2.)), xp.asarray(1.e-5)) + + @array_api_compatible + def test_entropy_zero(self, xp): + # Test for PR-479 + x = xp.asarray([0., 1., 2.]) + xp_assert_close(stats.entropy(x), + xp.asarray(0.63651416829481278)) + + @array_api_compatible + def test_entropy_2d(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]]) + xp_assert_close(stats.entropy(pk, qk), + xp.asarray([0.1933259, 0.18609809])) + + @array_api_compatible + def test_entropy_2d_zero(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + qk = xp.asarray([[0.0, 0.1], [0.3, 0.6], [0.5, 0.3]]) + xp_assert_close(stats.entropy(pk, qk), + xp.asarray([xp.inf, 0.18609809])) + + pk = xp.asarray([[0.0, 0.2], [0.6, 0.3], [0.3, 0.5]]) + xp_assert_close(stats.entropy(pk, qk), + xp.asarray([0.17403988, 0.18609809])) + + @array_api_compatible + def test_entropy_base_2d_nondefault_axis(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + xp_assert_close(stats.entropy(pk, axis=1), + xp.asarray([0.63651417, 0.63651417, 0.66156324])) + + @array_api_compatible + def test_entropy_2d_nondefault_axis(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]]) + xp_assert_close(stats.entropy(pk, qk, axis=1), + xp.asarray([0.23104906, 0.23104906, 0.12770641])) + + @array_api_compatible + def test_entropy_raises_value_error(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + qk = xp.asarray([[0.1, 0.2], [0.6, 0.3]]) + message = "Array shapes are incompatible for broadcasting." + with pytest.raises(ValueError, match=message): + stats.entropy(pk, qk) + + @array_api_compatible + def test_base_entropy_with_axis_0_is_equal_to_default(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + xp_assert_close(stats.entropy(pk, axis=0), + stats.entropy(pk)) + + @array_api_compatible + def test_entropy_with_axis_0_is_equal_to_default(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]]) + xp_assert_close(stats.entropy(pk, qk, axis=0), + stats.entropy(pk, qk)) + + @array_api_compatible + def test_base_entropy_transposed(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + xp_assert_close(stats.entropy(pk.T), + stats.entropy(pk, axis=1)) + + @array_api_compatible + def test_entropy_transposed(self, xp): + pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]) + qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]]) + xp_assert_close(stats.entropy(pk.T, qk.T), + stats.entropy(pk, qk, axis=1)) + + @array_api_compatible + def test_entropy_broadcasting(self, xp): + rng = np.random.default_rng(74187315492831452) + x = xp.asarray(rng.random(3)) + y = xp.asarray(rng.random((2, 1))) + res = stats.entropy(x, y, axis=-1) + xp_assert_equal(res[0], stats.entropy(x, y[0, ...])) + xp_assert_equal(res[1], stats.entropy(x, y[1, ...])) + + @array_api_compatible + def test_entropy_shape_mismatch(self, xp): + x = xp.ones((10, 1, 12)) + y = xp.ones((11, 2)) + message = "Array shapes are incompatible for broadcasting." + with pytest.raises(ValueError, match=message): + stats.entropy(x, y) + + @array_api_compatible + def test_input_validation(self, xp): + x = xp.ones(10) + message = "`base` must be a positive number." + with pytest.raises(ValueError, match=message): + stats.entropy(x, base=-2) + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +class TestDifferentialEntropy: + """ + Vasicek results are compared with the R package vsgoftest. + + # library(vsgoftest) + # + # samp <- c() + # entropy.estimate(x = samp, window = ) + + """ + + def test_differential_entropy_vasicek(self, xp): + + random_state = np.random.RandomState(0) + values = random_state.standard_normal(100) + values = xp.asarray(values.tolist()) + + entropy = stats.differential_entropy(values, method='vasicek') + xp_assert_close(entropy, xp.asarray(1.342551187000946)) + + entropy = stats.differential_entropy(values, window_length=1, + method='vasicek') + xp_assert_close(entropy, xp.asarray(1.122044177725947)) + + entropy = stats.differential_entropy(values, window_length=8, + method='vasicek') + xp_assert_close(entropy, xp.asarray(1.349401487550325)) + + def test_differential_entropy_vasicek_2d_nondefault_axis(self, xp): + random_state = np.random.RandomState(0) + values = random_state.standard_normal((3, 100)) + values = xp.asarray(values.tolist()) + + entropy = stats.differential_entropy(values, axis=1, method='vasicek') + ref = xp.asarray([1.342551187000946, 1.341825903922332, 1.293774601883585]) + xp_assert_close(entropy, ref) + + entropy = stats.differential_entropy(values, axis=1, window_length=1, + method='vasicek') + ref = xp.asarray([1.122044177725947, 1.10294413850758, 1.129615790292772]) + xp_assert_close(entropy, ref) + + entropy = stats.differential_entropy(values, axis=1, window_length=8, + method='vasicek') + ref = xp.asarray([1.349401487550325, 1.338514126301301, 1.292331889365405]) + xp_assert_close(entropy, ref) + + + def test_differential_entropy_raises_value_error(self, xp): + random_state = np.random.RandomState(0) + values = random_state.standard_normal((3, 100)) + values = xp.asarray(values.tolist()) + + error_str = ( + r"Window length \({window_length}\) must be positive and less " + r"than half the sample size \({sample_size}\)." + ) + + sample_size = values.shape[1] + + for window_length in {-1, 0, sample_size//2, sample_size}: + + formatted_error_str = error_str.format( + window_length=window_length, + sample_size=sample_size, + ) + + with assert_raises(ValueError, match=formatted_error_str): + stats.differential_entropy( + values, + window_length=window_length, + axis=1, + ) + + @pytest.mark.skip_xp_backends('jax.numpy', + reason="JAX doesn't support item assignment") + def test_base_differential_entropy_with_axis_0_is_equal_to_default(self, xp): + random_state = np.random.RandomState(0) + values = random_state.standard_normal((100, 3)) + values = xp.asarray(values.tolist()) + + entropy = stats.differential_entropy(values, axis=0) + default_entropy = stats.differential_entropy(values) + xp_assert_close(entropy, default_entropy) + + @pytest.mark.skip_xp_backends('jax.numpy', + reason="JAX doesn't support item assignment") + def test_base_differential_entropy_transposed(self, xp): + random_state = np.random.RandomState(0) + values = random_state.standard_normal((3, 100)) + values = xp.asarray(values.tolist()) + + xp_assert_close( + stats.differential_entropy(values.T), + stats.differential_entropy(values, axis=1), + ) + + def test_input_validation(self, xp): + x = np.random.rand(10) + x = xp.asarray(x.tolist()) + + message = "`base` must be a positive number or `None`." + with pytest.raises(ValueError, match=message): + stats.differential_entropy(x, base=-2) + + message = "`method` must be one of..." + with pytest.raises(ValueError, match=message): + stats.differential_entropy(x, method='ekki-ekki') + + @pytest.mark.parametrize('method', ['vasicek', 'van es', + 'ebrahimi', 'correa']) + def test_consistency(self, method, xp): + if is_jax(xp) and method == 'ebrahimi': + pytest.xfail("Needs array assignment.") + elif is_array_api_strict(xp) and method == 'correa': + pytest.xfail("Needs fancy indexing.") + # test that method is a consistent estimator + n = 10000 if method == 'correa' else 1000000 + rvs = stats.norm.rvs(size=n, random_state=0) + rvs = xp.asarray(rvs.tolist()) + expected = xp.asarray(float(stats.norm.entropy())) + res = stats.differential_entropy(rvs, method=method) + xp_assert_close(res, expected, rtol=0.005) + + # values from differential_entropy reference [6], table 1, n=50, m=7 + norm_rmse_std_cases = { # method: (RMSE, STD) + 'vasicek': (0.198, 0.109), + 'van es': (0.212, 0.110), + 'correa': (0.135, 0.112), + 'ebrahimi': (0.128, 0.109) + } + + # values from differential_entropy reference [6], table 2, n=50, m=7 + expon_rmse_std_cases = { # method: (RMSE, STD) + 'vasicek': (0.194, 0.148), + 'van es': (0.179, 0.149), + 'correa': (0.155, 0.152), + 'ebrahimi': (0.151, 0.148) + } + + rmse_std_cases = {norm: norm_rmse_std_cases, + expon: expon_rmse_std_cases} + + @pytest.mark.parametrize('method', ['vasicek', 'van es', 'ebrahimi', 'correa']) + @pytest.mark.parametrize('dist', [norm, expon]) + def test_rmse_std(self, method, dist, xp): + # test that RMSE and standard deviation of estimators matches values + # given in differential_entropy reference [6]. Incidentally, also + # tests vectorization. + if is_jax(xp) and method == 'ebrahimi': + pytest.xfail("Needs array assignment.") + elif is_array_api_strict(xp) and method == 'correa': + pytest.xfail("Needs fancy indexing.") + + reps, n, m = 10000, 50, 7 + expected = self.rmse_std_cases[dist][method] + rmse_expected, std_expected = xp.asarray(expected[0]), xp.asarray(expected[1]) + rvs = dist.rvs(size=(reps, n), random_state=0) + rvs = xp.asarray(rvs.tolist()) + true_entropy = xp.asarray(float(dist.entropy())) + res = stats.differential_entropy(rvs, window_length=m, + method=method, axis=-1) + xp_assert_close(xp.sqrt(xp.mean((res - true_entropy)**2)), + rmse_expected, atol=0.005) + xp_test = array_namespace(res) + xp_assert_close(xp_test.std(res, correction=0), std_expected, atol=0.002) + + @pytest.mark.parametrize('n, method', [(8, 'van es'), + (12, 'ebrahimi'), + (1001, 'vasicek')]) + def test_method_auto(self, n, method, xp): + if is_jax(xp) and method == 'ebrahimi': + pytest.xfail("Needs array assignment.") + rvs = stats.norm.rvs(size=(n,), random_state=0) + rvs = xp.asarray(rvs.tolist()) + res1 = stats.differential_entropy(rvs) + res2 = stats.differential_entropy(rvs, method=method) + xp_assert_equal(res1, res2) + + @pytest.mark.skip_xp_backends('jax.numpy', + reason="JAX doesn't support item assignment") + @pytest.mark.parametrize('method', ["vasicek", "van es", "correa", "ebrahimi"]) + @pytest.mark.parametrize('dtype', [None, 'float32', 'float64']) + def test_dtypes_gh21192(self, xp, method, dtype): + # gh-21192 noted a change in the output of method='ebrahimi' + # with integer input. Check that the output is consistent regardless + # of input dtype. + if is_array_api_strict(xp) and method == 'correa': + pytest.xfail("Needs fancy indexing.") + x = [1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11] + dtype_in = getattr(xp, str(dtype), None) + dtype_out = getattr(xp, str(dtype), xp.asarray(1.).dtype) + res = stats.differential_entropy(xp.asarray(x, dtype=dtype_in), method=method) + ref = stats.differential_entropy(xp.asarray(x, dtype=xp.float64), method=method) + xp_assert_close(res, xp.asarray(ref, dtype=dtype_out)[()]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fast_gen_inversion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fast_gen_inversion.py new file mode 100644 index 0000000000000000000000000000000000000000..63052f748befc7b30cdf6609490092b1d1d062e0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fast_gen_inversion.py @@ -0,0 +1,433 @@ +import pytest +import warnings +import numpy as np +from numpy.testing import (assert_array_equal, assert_allclose, + suppress_warnings) +from copy import deepcopy +from scipy.stats.sampling import FastGeneratorInversion +from scipy import stats + + +def test_bad_args(): + # loc and scale must be scalar + with pytest.raises(ValueError, match="loc must be scalar"): + FastGeneratorInversion(stats.norm(loc=(1.2, 1.3))) + with pytest.raises(ValueError, match="scale must be scalar"): + FastGeneratorInversion(stats.norm(scale=[1.5, 5.7])) + + with pytest.raises(ValueError, match="'test' cannot be used to seed"): + FastGeneratorInversion(stats.norm(), random_state="test") + + msg = "Each of the 1 shape parameters must be a scalar" + with pytest.raises(ValueError, match=msg): + FastGeneratorInversion(stats.gamma([1.3, 2.5])) + + with pytest.raises(ValueError, match="`dist` must be a frozen"): + FastGeneratorInversion("xy") + + with pytest.raises(ValueError, match="Distribution 'truncnorm' is not"): + FastGeneratorInversion(stats.truncnorm(1.3, 4.5)) + + +def test_random_state(): + # fixed seed + gen = FastGeneratorInversion(stats.norm(), random_state=68734509) + x1 = gen.rvs(size=10) + gen.random_state = 68734509 + x2 = gen.rvs(size=10) + assert_array_equal(x1, x2) + + # Generator + urng = np.random.default_rng(20375857) + gen = FastGeneratorInversion(stats.norm(), random_state=urng) + x1 = gen.rvs(size=10) + gen.random_state = np.random.default_rng(20375857) + x2 = gen.rvs(size=10) + assert_array_equal(x1, x2) + + # RandomState + urng = np.random.RandomState(2364) + gen = FastGeneratorInversion(stats.norm(), random_state=urng) + x1 = gen.rvs(size=10) + gen.random_state = np.random.RandomState(2364) + x2 = gen.rvs(size=10) + assert_array_equal(x1, x2) + + # if evaluate_error is called, it must not interfere with the random_state + # used by rvs + gen = FastGeneratorInversion(stats.norm(), random_state=68734509) + x1 = gen.rvs(size=10) + _ = gen.evaluate_error(size=5) # this will generate 5 uniform rvs + x2 = gen.rvs(size=10) + gen.random_state = 68734509 + x3 = gen.rvs(size=20) + assert_array_equal(x2, x3[10:]) + + +dists_with_params = [ + ("alpha", (3.5,)), + ("anglit", ()), + ("argus", (3.5,)), + ("argus", (5.1,)), + ("beta", (1.5, 0.9)), + ("cosine", ()), + ("betaprime", (2.5, 3.3)), + ("bradford", (1.2,)), + ("burr", (1.3, 2.4)), + ("burr12", (0.7, 1.2)), + ("cauchy", ()), + ("chi2", (3.5,)), + ("chi", (4.5,)), + ("crystalball", (0.7, 1.2)), + ("expon", ()), + ("gamma", (1.5,)), + ("gennorm", (2.7,)), + ("gumbel_l", ()), + ("gumbel_r", ()), + ("hypsecant", ()), + ("invgauss", (3.1,)), + ("invweibull", (1.5,)), + ("laplace", ()), + ("logistic", ()), + ("maxwell", ()), + ("moyal", ()), + ("norm", ()), + ("pareto", (1.3,)), + ("powerlaw", (7.6,)), + ("rayleigh", ()), + ("semicircular", ()), + ("t", (5.7,)), + ("wald", ()), + ("weibull_max", (2.4,)), + ("weibull_min", (1.2,)), +] + + +@pytest.mark.parametrize(("distname, args"), dists_with_params) +def test_rvs_and_ppf(distname, args): + # check sample against rvs generated by rv_continuous + urng = np.random.default_rng(9807324628097097) + rng1 = getattr(stats, distname)(*args) + rvs1 = rng1.rvs(size=500, random_state=urng) + rng2 = FastGeneratorInversion(rng1, random_state=urng) + rvs2 = rng2.rvs(size=500) + assert stats.cramervonmises_2samp(rvs1, rvs2).pvalue > 0.01 + + # check ppf + q = [0.001, 0.1, 0.5, 0.9, 0.999] + assert_allclose(rng1.ppf(q), rng2.ppf(q), atol=1e-10) + + +@pytest.mark.parametrize(("distname, args"), dists_with_params) +def test_u_error(distname, args): + # check sample against rvs generated by rv_continuous + dist = getattr(stats, distname)(*args) + with suppress_warnings() as sup: + # filter the warnings thrown by UNU.RAN + sup.filter(RuntimeWarning) + rng = FastGeneratorInversion(dist) + u_error, x_error = rng.evaluate_error( + size=10_000, random_state=9807324628097097, x_error=False + ) + assert u_error <= 1e-10 + + +@pytest.mark.xslow +@pytest.mark.xfail(reason="geninvgauss CDF is not accurate") +def test_geninvgauss_uerror(): + dist = stats.geninvgauss(3.2, 1.5) + rng = FastGeneratorInversion(dist) + err = rng.evaluate_error(size=10_000, random_state=67982) + assert err[0] < 1e-10 + + +# TODO: add more distributions +@pytest.mark.fail_slow(5) +@pytest.mark.parametrize(("distname, args"), [("beta", (0.11, 0.11))]) +def test_error_extreme_params(distname, args): + # take extreme parameters where u-error might not be below the tolerance + # due to limitations of floating point arithmetic + with suppress_warnings() as sup: + # filter the warnings thrown by UNU.RAN for such extreme parameters + sup.filter(RuntimeWarning) + dist = getattr(stats, distname)(*args) + rng = FastGeneratorInversion(dist) + u_error, x_error = rng.evaluate_error( + size=10_000, random_state=980732462809709732623, x_error=True + ) + if u_error >= 2.5 * 1e-10: + assert x_error < 1e-9 + + +def test_evaluate_error_inputs(): + gen = FastGeneratorInversion(stats.norm()) + with pytest.raises(ValueError, match="size must be an integer"): + gen.evaluate_error(size=3.5) + with pytest.raises(ValueError, match="size must be an integer"): + gen.evaluate_error(size=(3, 3)) + + +def test_rvs_ppf_loc_scale(): + loc, scale = 3.5, 2.3 + dist = stats.norm(loc=loc, scale=scale) + rng = FastGeneratorInversion(dist, random_state=1234) + r = rng.rvs(size=1000) + r_rescaled = (r - loc) / scale + assert stats.cramervonmises(r_rescaled, "norm").pvalue > 0.01 + q = [0.001, 0.1, 0.5, 0.9, 0.999] + assert_allclose(rng._ppf(q), rng.ppf(q), atol=1e-10) + + +def test_domain(): + # only a basic check that the domain argument is passed to the + # UNU.RAN generators + rng = FastGeneratorInversion(stats.norm(), domain=(-1, 1)) + r = rng.rvs(size=100) + assert -1 <= r.min() < r.max() <= 1 + + # if loc and scale are used, new domain is loc + scale*domain + loc, scale = 3.5, 1.3 + dist = stats.norm(loc=loc, scale=scale) + rng = FastGeneratorInversion(dist, domain=(-1.5, 2)) + r = rng.rvs(size=100) + lb, ub = loc - scale * 1.5, loc + scale * 2 + assert lb <= r.min() < r.max() <= ub + + +@pytest.mark.parametrize(("distname, args, expected"), + [("beta", (3.5, 2.5), (0, 1)), + ("norm", (), (-np.inf, np.inf))]) +def test_support(distname, args, expected): + # test that the support is updated if truncation and loc/scale are applied + # use beta distribution since it is a transformed betaprime distribution, + # so it is important that the correct support is considered + # (i.e., the support of beta is (0,1), while betaprime is (0, inf)) + dist = getattr(stats, distname)(*args) + rng = FastGeneratorInversion(dist) + assert_array_equal(rng.support(), expected) + rng.loc = 1 + rng.scale = 2 + assert_array_equal(rng.support(), 1 + 2*np.array(expected)) + + +@pytest.mark.parametrize(("distname, args"), + [("beta", (3.5, 2.5)), ("norm", ())]) +def test_support_truncation(distname, args): + # similar test for truncation + dist = getattr(stats, distname)(*args) + rng = FastGeneratorInversion(dist, domain=(0.5, 0.7)) + assert_array_equal(rng.support(), (0.5, 0.7)) + rng.loc = 1 + rng.scale = 2 + assert_array_equal(rng.support(), (1 + 2 * 0.5, 1 + 2 * 0.7)) + + +def test_domain_shift_truncation(): + # center of norm is zero, it should be shifted to the left endpoint of + # domain. if this was not the case, PINV in UNURAN would raise a warning + # as the center is not inside the domain + with warnings.catch_warnings(): + warnings.simplefilter("error") + rng = FastGeneratorInversion(stats.norm(), domain=(1, 2)) + r = rng.rvs(size=100) + assert 1 <= r.min() < r.max() <= 2 + + +def test_non_rvs_methods_with_domain(): + # as a first step, compare truncated normal against stats.truncnorm + rng = FastGeneratorInversion(stats.norm(), domain=(2.3, 3.2)) + trunc_norm = stats.truncnorm(2.3, 3.2) + # take values that are inside and outside the domain + x = (2.0, 2.4, 3.0, 3.4) + p = (0.01, 0.5, 0.99) + assert_allclose(rng._cdf(x), trunc_norm.cdf(x)) + assert_allclose(rng._ppf(p), trunc_norm.ppf(p)) + loc, scale = 2, 3 + rng.loc = 2 + rng.scale = 3 + trunc_norm = stats.truncnorm(2.3, 3.2, loc=loc, scale=scale) + x = np.array(x) * scale + loc + assert_allclose(rng._cdf(x), trunc_norm.cdf(x)) + assert_allclose(rng._ppf(p), trunc_norm.ppf(p)) + + # do another sanity check with beta distribution + # in that case, it is important to use the correct domain since beta + # is a transformation of betaprime which has a different support + rng = FastGeneratorInversion(stats.beta(2.5, 3.5), domain=(0.3, 0.7)) + rng.loc = 2 + rng.scale = 2.5 + # the support is 2.75, , 3.75 (2 + 2.5 * 0.3, 2 + 2.5 * 0.7) + assert_array_equal(rng.support(), (2.75, 3.75)) + x = np.array([2.74, 2.76, 3.74, 3.76]) + # the cdf needs to be zero outside of the domain + y_cdf = rng._cdf(x) + assert_array_equal((y_cdf[0], y_cdf[3]), (0, 1)) + assert np.min(y_cdf[1:3]) > 0 + # ppf needs to map 0 and 1 to the boundaries + assert_allclose(rng._ppf(y_cdf), (2.75, 2.76, 3.74, 3.75)) + + +def test_non_rvs_methods_without_domain(): + norm_dist = stats.norm() + rng = FastGeneratorInversion(norm_dist) + x = np.linspace(-3, 3, num=10) + p = (0.01, 0.5, 0.99) + assert_allclose(rng._cdf(x), norm_dist.cdf(x)) + assert_allclose(rng._ppf(p), norm_dist.ppf(p)) + loc, scale = 0.5, 1.3 + rng.loc = loc + rng.scale = scale + norm_dist = stats.norm(loc=loc, scale=scale) + assert_allclose(rng._cdf(x), norm_dist.cdf(x)) + assert_allclose(rng._ppf(p), norm_dist.ppf(p)) + +@pytest.mark.parametrize(("domain, x"), + [(None, 0.5), + ((0, 1), 0.5), + ((0, 1), 1.5)]) +def test_scalar_inputs(domain, x): + """ pdf, cdf etc should map scalar values to scalars. check with and + w/o domain since domain impacts pdf, cdf etc + Take x inside and outside of domain """ + rng = FastGeneratorInversion(stats.norm(), domain=domain) + assert np.isscalar(rng._cdf(x)) + assert np.isscalar(rng._ppf(0.5)) + + +def test_domain_argus_large_chi(): + # for large chi, the Gamma distribution is used and the domain has to be + # transformed. this is a test to ensure that the transformation works + chi, lb, ub = 5.5, 0.25, 0.75 + rng = FastGeneratorInversion(stats.argus(chi), domain=(lb, ub)) + rng.random_state = 4574 + r = rng.rvs(size=500) + assert lb <= r.min() < r.max() <= ub + # perform goodness of fit test with conditional cdf + cdf = stats.argus(chi).cdf + prob = cdf(ub) - cdf(lb) + assert stats.cramervonmises(r, lambda x: cdf(x) / prob).pvalue > 0.05 + + +def test_setting_loc_scale(): + rng = FastGeneratorInversion(stats.norm(), random_state=765765864) + r1 = rng.rvs(size=1000) + rng.loc = 3.0 + rng.scale = 2.5 + r2 = rng.rvs(1000) + # rescaled r2 should be again standard normal + assert stats.cramervonmises_2samp(r1, (r2 - 3) / 2.5).pvalue > 0.05 + # reset values to default loc=0, scale=1 + rng.loc = 0 + rng.scale = 1 + r2 = rng.rvs(1000) + assert stats.cramervonmises_2samp(r1, r2).pvalue > 0.05 + + +def test_ignore_shape_range(): + msg = "No generator is defined for the shape parameters" + with pytest.raises(ValueError, match=msg): + rng = FastGeneratorInversion(stats.t(0.03)) + rng = FastGeneratorInversion(stats.t(0.03), ignore_shape_range=True) + # we can ignore the recommended range of shape parameters + # but u-error can be expected to be too large in that case + u_err, _ = rng.evaluate_error(size=1000, random_state=234) + assert u_err >= 1e-6 + +@pytest.mark.xfail_on_32bit( + "NumericalInversePolynomial.qrvs fails for Win 32-bit" +) +class TestQRVS: + def test_input_validation(self): + gen = FastGeneratorInversion(stats.norm()) + + match = "`qmc_engine` must be an instance of..." + with pytest.raises(ValueError, match=match): + gen.qrvs(qmc_engine=0) + + match = "`d` must be consistent with dimension of `qmc_engine`." + with pytest.raises(ValueError, match=match): + gen.qrvs(d=3, qmc_engine=stats.qmc.Halton(2)) + + qrngs = [None, stats.qmc.Sobol(1, seed=0), stats.qmc.Halton(3, seed=0)] + # `size=None` should not add anything to the shape, `size=1` should + sizes = [ + (None, tuple()), + (1, (1,)), + (4, (4,)), + ((4,), (4,)), + ((2, 4), (2, 4)), + ] + # Neither `d=None` nor `d=1` should add anything to the shape + ds = [(None, tuple()), (1, tuple()), (3, (3,))] + + @pytest.mark.parametrize("qrng", qrngs) + @pytest.mark.parametrize("size_in, size_out", sizes) + @pytest.mark.parametrize("d_in, d_out", ds) + def test_QRVS_shape_consistency(self, qrng, size_in, size_out, + d_in, d_out): + gen = FastGeneratorInversion(stats.norm()) + + # If d and qrng.d are inconsistent, an error is raised + if d_in is not None and qrng is not None and qrng.d != d_in: + match = "`d` must be consistent with dimension of `qmc_engine`." + with pytest.raises(ValueError, match=match): + gen.qrvs(size_in, d=d_in, qmc_engine=qrng) + return + + # Sometimes d is really determined by qrng + if d_in is None and qrng is not None and qrng.d != 1: + d_out = (qrng.d,) + + shape_expected = size_out + d_out + + qrng2 = deepcopy(qrng) + qrvs = gen.qrvs(size=size_in, d=d_in, qmc_engine=qrng) + if size_in is not None: + assert qrvs.shape == shape_expected + + if qrng2 is not None: + uniform = qrng2.random(np.prod(size_in) or 1) + qrvs2 = stats.norm.ppf(uniform).reshape(shape_expected) + assert_allclose(qrvs, qrvs2, atol=1e-12) + + def test_QRVS_size_tuple(self): + # QMCEngine samples are always of shape (n, d). When `size` is a tuple, + # we set `n = prod(size)` in the call to qmc_engine.random, transform + # the sample, and reshape it to the final dimensions. When we reshape, + # we need to be careful, because the _columns_ of the sample returned + # by a QMCEngine are "independent"-ish, but the elements within the + # columns are not. We need to make sure that this doesn't get mixed up + # by reshaping: qrvs[..., i] should remain "independent"-ish of + # qrvs[..., i+1], but the elements within qrvs[..., i] should be + # transformed from the same low-discrepancy sequence. + + gen = FastGeneratorInversion(stats.norm()) + + size = (3, 4) + d = 5 + qrng = stats.qmc.Halton(d, seed=0) + qrng2 = stats.qmc.Halton(d, seed=0) + + uniform = qrng2.random(np.prod(size)) + + qrvs = gen.qrvs(size=size, d=d, qmc_engine=qrng) + qrvs2 = stats.norm.ppf(uniform) + + for i in range(d): + sample = qrvs[..., i] + sample2 = qrvs2[:, i].reshape(size) + assert_allclose(sample, sample2, atol=1e-12) + + +def test_burr_overflow(): + # this case leads to an overflow error if math.exp is used + # in the definition of the burr pdf instead of np.exp + # a direct implementation of the PDF as x**(-c-1) / (1+x**(-c))**(d+1) + # also leads to an overflow error in the setup + args = (1.89128135, 0.30195177) + with suppress_warnings() as sup: + # filter potential overflow warning + sup.filter(RuntimeWarning) + gen = FastGeneratorInversion(stats.burr(*args)) + u_error, _ = gen.evaluate_error(random_state=4326) + assert u_error <= 1e-10 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..320c31cf30394b6edd05026b40c57622555656fc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fit.py @@ -0,0 +1,1089 @@ +import os +import numpy as np +import numpy.testing as npt +from numpy.testing import assert_allclose, assert_equal +import pytest +from scipy import stats +from scipy.optimize import differential_evolution + +from .test_continuous_basic import distcont +from scipy.stats._distn_infrastructure import FitError +from scipy.stats._distr_params import distdiscrete +from scipy.stats import goodness_of_fit + + +# this is not a proper statistical test for convergence, but only +# verifies that the estimate and true values don't differ by too much + +fit_sizes = [1000, 5000, 10000] # sample sizes to try + +thresh_percent = 0.25 # percent of true parameters for fail cut-off +thresh_min = 0.75 # minimum difference estimate - true to fail test + +mle_failing_fits = [ + 'dpareto_lognorm', + 'gausshyper', + 'genexpon', + 'gengamma', + 'irwinhall', + 'kappa4', + 'ksone', + 'kstwo', + 'ncf', + 'ncx2', + 'truncexpon', + 'tukeylambda', + 'vonmises', + 'levy_stable', + 'trapezoid', + 'truncweibull_min', + 'studentized_range', +] + +# these pass but are XSLOW (>1s) +mle_Xslow_fits = ['betaprime', 'crystalball', 'exponweib', 'f', 'geninvgauss', + 'jf_skew_t', 'recipinvgauss', 'rel_breitwigner', 'vonmises_line'] + +# The MLE fit method of these distributions doesn't perform well when all +# parameters are fit, so test them with the location fixed at 0. +mle_use_floc0 = [ + 'burr', + 'chi', + 'chi2', + 'mielke', + 'pearson3', + 'genhalflogistic', + 'rdist', + 'pareto', + 'powerlaw', # distfn.nnlf(est2, rvs) > distfn.nnlf(est1, rvs) otherwise + 'powerlognorm', + 'wrapcauchy', + 'rel_breitwigner', +] + +mm_failing_fits = ['alpha', 'betaprime', 'burr', 'burr12', 'cauchy', 'chi', + 'chi2', 'crystalball', 'dgamma', 'dpareto_lognorm', 'dweibull', + 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'genextreme', + 'gengamma', 'genhyperbolic', 'gennorm', 'genpareto', + 'halfcauchy', 'invgamma', 'invweibull', 'irwinhall', 'jf_skew_t', + 'johnsonsu', 'kappa3', 'ksone', 'kstwo', 'landau', 'levy', 'levy_l', + 'levy_stable', 'loglaplace', 'lomax', 'mielke', 'nakagami', + 'ncf', 'nct', 'ncx2', 'pareto', 'powerlognorm', 'powernorm', + 'rel_breitwigner', 'skewcauchy', 't', 'trapezoid', 'triang', + 'truncpareto', 'truncweibull_min', 'tukeylambda', + 'studentized_range'] + +# not sure if these fail, but they caused my patience to fail +mm_XXslow_fits = ['argus', 'exponpow', 'exponweib', 'gausshyper', 'genexpon', + 'genhalflogistic', 'halfgennorm', 'gompertz', 'johnsonsb', + 'kappa4', 'kstwobign', 'recipinvgauss', + 'truncexpon', 'vonmises', 'vonmises_line'] + +# these pass but are XSLOW (>1s) +mm_Xslow_fits = ['wrapcauchy'] + +failing_fits = {"MM": mm_failing_fits + mm_XXslow_fits, "MLE": mle_failing_fits} +xslow_fits = {"MM": mm_Xslow_fits, "MLE": mle_Xslow_fits} +fail_interval_censored = {"truncpareto"} + +# Don't run the fit test on these: +skip_fit = [ + 'erlang', # Subclass of gamma, generates a warning. + 'genhyperbolic', 'norminvgauss', # too slow +] + + +def cases_test_cont_fit(): + # this tests the closeness of the estimated parameters to the true + # parameters with fit method of continuous distributions + # Note: is slow, some distributions don't converge with sample + # size <= 10000 + for distname, arg in distcont: + if distname not in skip_fit: + yield distname, arg + + +@pytest.mark.slow +@pytest.mark.parametrize('distname,arg', cases_test_cont_fit()) +@pytest.mark.parametrize('method', ["MLE", "MM"]) +def test_cont_fit(distname, arg, method): + run_xfail = int(os.getenv('SCIPY_XFAIL', default=False)) + run_xslow = int(os.getenv('SCIPY_XSLOW', default=False)) + + if distname in failing_fits[method] and not run_xfail: + # The generic `fit` method can't be expected to work perfectly for all + # distributions, data, and guesses. Some failures are expected. + msg = "Failure expected; set environment variable SCIPY_XFAIL=1 to run." + pytest.xfail(msg) + + if distname in xslow_fits[method] and not run_xslow: + msg = "Very slow; set environment variable SCIPY_XSLOW=1 to run." + pytest.skip(msg) + + distfn = getattr(stats, distname) + + truearg = np.hstack([arg, [0.0, 1.0]]) + diffthreshold = np.max(np.vstack([truearg*thresh_percent, + np.full(distfn.numargs+2, thresh_min)]), + 0) + + for fit_size in fit_sizes: + # Note that if a fit succeeds, the other fit_sizes are skipped + np.random.seed(1234) + + with np.errstate(all='ignore'): + rvs = distfn.rvs(size=fit_size, *arg) + if method == 'MLE' and distfn.name in mle_use_floc0: + kwds = {'floc': 0} + else: + kwds = {} + # start with default values + est = distfn.fit(rvs, method=method, **kwds) + if method == 'MLE': + # Trivial test of the use of CensoredData. The fit() method + # will check that data contains no actual censored data, and + # do a regular uncensored fit. + data1 = stats.CensoredData(rvs) + est1 = distfn.fit(data1, **kwds) + msg = ('Different results fitting uncensored data wrapped as' + f' CensoredData: {distfn.name}: est={est} est1={est1}') + assert_allclose(est1, est, rtol=1e-10, err_msg=msg) + if method == 'MLE' and distname not in fail_interval_censored: + # Convert the first `nic` values in rvs to interval-censored + # values. The interval is small, so est2 should be close to + # est. + nic = 15 + interval = np.column_stack((rvs, rvs)) + interval[:nic, 0] *= 0.99 + interval[:nic, 1] *= 1.01 + interval.sort(axis=1) + data2 = stats.CensoredData(interval=interval) + est2 = distfn.fit(data2, **kwds) + msg = ('Different results fitting interval-censored' + f' data: {distfn.name}: est={est} est2={est2}') + assert_allclose(est2, est, rtol=0.05, err_msg=msg) + + diff = est - truearg + + # threshold for location + diffthreshold[-2] = np.max([np.abs(rvs.mean())*thresh_percent, + thresh_min]) + + if np.any(np.isnan(est)): + raise AssertionError('nan returned in fit') + else: + if np.all(np.abs(diff) <= diffthreshold): + break + else: + txt = f'parameter: {str(truearg)}\n' + txt += f'estimated: {str(est)}\n' + txt += f'diff : {str(diff)}\n' + raise AssertionError(f'fit not very good in {distfn.name}\n' + txt) + + +def _check_loc_scale_mle_fit(name, data, desired, atol=None): + d = getattr(stats, name) + actual = d.fit(data)[-2:] + assert_allclose(actual, desired, atol=atol, + err_msg=f'poor mle fit of (loc, scale) in {name}') + + +def test_non_default_loc_scale_mle_fit(): + data = np.array([1.01, 1.78, 1.78, 1.78, 1.88, 1.88, 1.88, 2.00]) + _check_loc_scale_mle_fit('uniform', data, [1.01, 0.99], 1e-3) + _check_loc_scale_mle_fit('expon', data, [1.01, 0.73875], 1e-3) + + +def test_expon_fit(): + """gh-6167""" + data = [0, 0, 0, 0, 2, 2, 2, 2] + phat = stats.expon.fit(data, floc=0) + assert_allclose(phat, [0, 1.0], atol=1e-3) + + +def test_fit_error(): + data = np.concatenate([np.zeros(29), np.ones(21)]) + message = "Optimization converged to parameters that are..." + with pytest.raises(FitError, match=message), \ + pytest.warns(RuntimeWarning): + stats.beta.fit(data) + + +@pytest.mark.parametrize("dist, params", + [(stats.norm, (0.5, 2.5)), # type: ignore[attr-defined] + (stats.binom, (10, 0.3, 2))]) # type: ignore[attr-defined] +def test_nnlf_and_related_methods(dist, params): + rng = np.random.default_rng(983459824) + + if hasattr(dist, 'pdf'): + logpxf = dist.logpdf + else: + logpxf = dist.logpmf + + x = dist.rvs(*params, size=100, random_state=rng) + ref = -logpxf(x, *params).sum() + res1 = dist.nnlf(params, x) + res2 = dist._penalized_nnlf(params, x) + assert_allclose(res1, ref) + assert_allclose(res2, ref) + + +def cases_test_fit_mle(): + # These fail default test or hang + skip_basic_fit = {'argus', 'irwinhall', 'foldnorm', 'truncpareto', + 'truncweibull_min', 'ksone', 'levy_stable', + 'studentized_range', 'kstwo', + 'beta', 'nakagami', 'truncnorm', # don't meet tolerance + 'poisson_binom'} # vector-valued shape parameter + + # Please keep this list in alphabetical order... + slow_basic_fit = {'alpha', 'arcsine', 'betaprime', 'binom', 'bradford', 'burr12', + 'chi', 'crystalball', 'dweibull', 'erlang', 'exponnorm', + 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'gamma', + 'genexpon', 'genextreme', 'gennorm', 'genpareto', + 'gompertz', 'halfgennorm', 'invgamma', 'invgauss', 'invweibull', + 'jf_skew_t', 'johnsonsb', 'johnsonsu', 'kappa3', + 'kstwobign', 'loglaplace', 'lognorm', 'lomax', 'mielke', + 'nbinom', 'norminvgauss', + 'pareto', 'pearson3', 'powerlaw', 'powernorm', + 'randint', 'rdist', 'recipinvgauss', 'rice', 'skewnorm', + 't', 'uniform', 'weibull_max', 'weibull_min', 'wrapcauchy'} + + # Please keep this list in alphabetical order... + xslow_basic_fit = {'betabinom', 'betanbinom', 'burr', 'dpareto_lognorm', + 'exponweib', 'gausshyper', 'gengamma', 'genhalflogistic', + 'genhyperbolic', 'geninvgauss', + 'hypergeom', 'kappa4', 'loguniform', + 'ncf', 'nchypergeom_fisher', 'nchypergeom_wallenius', + 'nct', 'ncx2', 'nhypergeom', + 'powerlognorm', 'reciprocal', 'rel_breitwigner', + 'skellam', 'trapezoid', 'triang', + 'tukeylambda', 'vonmises', 'zipfian'} + + for dist in dict(distdiscrete + distcont): + if dist in skip_basic_fit or not isinstance(dist, str): + reason = "tested separately" + yield pytest.param(dist, marks=pytest.mark.skip(reason=reason)) + elif dist in slow_basic_fit: + reason = "too slow (>= 0.25s)" + yield pytest.param(dist, marks=pytest.mark.slow(reason=reason)) + elif dist in xslow_basic_fit: + reason = "too slow (>= 1.0s)" + yield pytest.param(dist, marks=pytest.mark.xslow(reason=reason)) + else: + yield dist + + +def cases_test_fit_mse(): + # the first four are so slow that I'm not sure whether they would pass + skip_basic_fit = {'levy_stable', 'studentized_range', 'ksone', 'skewnorm', + 'irwinhall', # hangs + 'norminvgauss', # super slow (~1 hr) but passes + 'kstwo', # very slow (~25 min) but passes + 'geninvgauss', # quite slow (~4 minutes) but passes + 'gausshyper', 'genhyperbolic', # integration warnings + 'tukeylambda', # close, but doesn't meet tolerance + 'vonmises', # can have negative CDF; doesn't play nice + 'arcsine', 'argus', 'powerlaw', 'rdist', # don't meet tolerance + 'poisson_binom', # vector-valued shape parameter + } + + # Please keep this list in alphabetical order... + slow_basic_fit = {'alpha', 'anglit', 'betabinom', 'bradford', + 'chi', 'chi2', 'crystalball', 'dweibull', + 'erlang', 'exponnorm', 'exponpow', 'exponweib', + 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', + 'gamma', 'genexpon', 'genextreme', 'genhalflogistic', + 'genlogistic', 'genpareto', 'gompertz', + 'hypergeom', 'invweibull', + 'johnsonsu', 'kappa3', 'kstwobign', + 'laplace_asymmetric', 'loggamma', 'loglaplace', + 'lognorm', 'lomax', + 'maxwell', 'nhypergeom', + 'pareto', 'powernorm', 'randint', 'recipinvgauss', + 'semicircular', + 't', 'triang', 'truncexpon', 'truncpareto', + 'uniform', + 'wald', 'weibull_max', 'weibull_min', 'wrapcauchy'} + + # Please keep this list in alphabetical order... + xslow_basic_fit = {'argus', 'beta', 'betaprime', 'burr', 'burr12', + 'dgamma', 'dpareto_lognorm', 'f', 'gengamma', 'gennorm', + 'halfgennorm', 'invgamma', 'invgauss', 'jf_skew_t', + 'johnsonsb', 'kappa4', 'loguniform', 'mielke', + 'nakagami', 'ncf', 'nchypergeom_fisher', + 'nchypergeom_wallenius', 'nct', 'ncx2', + 'pearson3', 'powerlognorm', + 'reciprocal', 'rel_breitwigner', 'rice', + 'trapezoid', 'truncnorm', 'truncweibull_min', + 'vonmises_line', 'zipfian'} + + warns_basic_fit = {'skellam'} # can remove mark after gh-14901 is resolved + + for dist in dict(distdiscrete + distcont): + if dist in skip_basic_fit or not isinstance(dist, str): + reason = "Fails. Oh well." + yield pytest.param(dist, marks=pytest.mark.skip(reason=reason)) + elif dist in slow_basic_fit: + reason = "too slow (>= 0.25s)" + yield pytest.param(dist, marks=pytest.mark.slow(reason=reason)) + elif dist in xslow_basic_fit: + reason = "too slow (>= 1.0s)" + yield pytest.param(dist, marks=pytest.mark.xslow(reason=reason)) + elif dist in warns_basic_fit: + mark = pytest.mark.filterwarnings('ignore::RuntimeWarning') + yield pytest.param(dist, marks=mark) + else: + yield dist + + +def cases_test_fitstart(): + for distname, shapes in dict(distcont).items(): + if (not isinstance(distname, str) or + distname in {'studentized_range', 'recipinvgauss'}): # slow + continue + yield distname, shapes + + +@pytest.mark.parametrize('distname, shapes', cases_test_fitstart()) +def test_fitstart(distname, shapes): + dist = getattr(stats, distname) + rng = np.random.default_rng(216342614) + data = rng.random(10) + + with np.errstate(invalid='ignore', divide='ignore'): # irrelevant to test + guess = dist._fitstart(data) + + assert dist._argcheck(*guess[:-2]) + + +def assert_nlff_less_or_close(dist, data, params1, params0, rtol=1e-7, atol=0, + nlff_name='nnlf'): + nlff = getattr(dist, nlff_name) + nlff1 = nlff(params1, data) + nlff0 = nlff(params0, data) + if not (nlff1 < nlff0): + np.testing.assert_allclose(nlff1, nlff0, rtol=rtol, atol=atol) + + +class TestFit: + dist = stats.binom # type: ignore[attr-defined] + seed = 654634816187 + rng = np.random.default_rng(seed) + data = stats.binom.rvs(5, 0.5, size=100, random_state=rng) # type: ignore[attr-defined] # noqa: E501 + shape_bounds_a = [(1, 10), (0, 1)] + shape_bounds_d = {'n': (1, 10), 'p': (0, 1)} + atol = 5e-2 + rtol = 1e-2 + tols = {'atol': atol, 'rtol': rtol} + + def opt(self, *args, rng=1, **kwds): + return differential_evolution(*args, rng=rng, **kwds) + + def test_dist_iv(self): + message = "`dist` must be an instance of..." + with pytest.raises(ValueError, match=message): + stats.fit(10, self.data, self.shape_bounds_a) + + def test_data_iv(self): + message = "`data` must be exactly one-dimensional." + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, [[1, 2, 3]], self.shape_bounds_a) + + message = "All elements of `data` must be finite numbers." + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, [1, 2, 3, np.nan], self.shape_bounds_a) + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, [1, 2, 3, np.inf], self.shape_bounds_a) + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, ['1', '2', '3'], self.shape_bounds_a) + + def test_bounds_iv(self): + message = "Bounds provided for the following unrecognized..." + shape_bounds = {'n': (1, 10), 'p': (0, 1), '1': (0, 10)} + with pytest.warns(RuntimeWarning, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + message = "Each element of a `bounds` sequence must be a tuple..." + shape_bounds = [(1, 10, 3), (0, 1)] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + message = "Each element of `bounds` must be a tuple specifying..." + shape_bounds = [(1, 10, 3), (0, 1, 0.5)] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + shape_bounds = [1, 0] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + message = "A `bounds` sequence must contain at least 2 elements..." + shape_bounds = [(1, 10)] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + message = "A `bounds` sequence may not contain more than 3 elements..." + bounds = [(1, 10), (1, 10), (1, 10), (1, 10)] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, bounds) + + message = "There are no values for `p` on the interval..." + shape_bounds = {'n': (1, 10), 'p': (1, 0)} + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + message = "There are no values for `n` on the interval..." + shape_bounds = [(10, 1), (0, 1)] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + message = "There are no integer values for `n` on the interval..." + shape_bounds = [(1.4, 1.6), (0, 1)] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + message = "The intersection of user-provided bounds for `n`" + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data) + shape_bounds = [(-np.inf, np.inf), (0, 1)] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, shape_bounds) + + def test_guess_iv(self): + message = "Guesses provided for the following unrecognized..." + guess = {'n': 1, 'p': 0.5, '1': 255} + with pytest.warns(RuntimeWarning, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + message = "Each element of `guess` must be a scalar..." + guess = {'n': 1, 'p': 'hi'} + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + guess = [1, 'f'] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + guess = [[1, 2]] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + message = "A `guess` sequence must contain at least 2..." + guess = [1] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + message = "A `guess` sequence may not contain more than 3..." + guess = [1, 2, 3, 4] + with pytest.raises(ValueError, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + message = "Guess for parameter `n` rounded.*|Guess for parameter `p` clipped.*" + guess = {'n': 4.5, 'p': -0.5} + with pytest.warns(RuntimeWarning, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + message = "Guess for parameter `loc` rounded..." + guess = [5, 0.5, 0.5] + with pytest.warns(RuntimeWarning, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + message = "Guess for parameter `p` clipped..." + guess = {'n': 5, 'p': -0.5} + with pytest.warns(RuntimeWarning, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + message = "Guess for parameter `loc` clipped..." + guess = [5, 0.5, 1] + with pytest.warns(RuntimeWarning, match=message): + stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess) + + def basic_fit_test(self, dist_name, method, rng=1): + + N = 5000 + dist_data = dict(distcont + distdiscrete) + rng = np.random.default_rng(self.seed) + dist = getattr(stats, dist_name) + shapes = np.array(dist_data[dist_name]) + bounds = np.empty((len(shapes) + 2, 2), dtype=np.float64) + bounds[:-2, 0] = shapes/10.**np.sign(shapes) + bounds[:-2, 1] = shapes*10.**np.sign(shapes) + bounds[-2] = (0, 10) + bounds[-1] = (1e-16, 10) + loc = rng.uniform(*bounds[-2]) + scale = rng.uniform(*bounds[-1]) + ref = list(dist_data[dist_name]) + [loc, scale] + + if getattr(dist, 'pmf', False): + ref = ref[:-1] + ref[-1] = np.floor(loc) + data = dist.rvs(*ref, size=N, random_state=rng) + bounds = bounds[:-1] + if getattr(dist, 'pdf', False): + data = dist.rvs(*ref, size=N, random_state=rng) + + with npt.suppress_warnings() as sup: + sup.filter(RuntimeWarning, "overflow encountered") + res = stats.fit(dist, data, bounds, method=method, + optimizer=self.opt) + + nlff_names = {'mle': 'nnlf', 'mse': '_penalized_nlpsf'} + nlff_name = nlff_names[method] + assert_nlff_less_or_close(dist, data, res.params, ref, **self.tols, + nlff_name=nlff_name) + + @pytest.mark.parametrize("dist_name", cases_test_fit_mle()) + def test_basic_fit_mle(self, dist_name): + self.basic_fit_test(dist_name, "mle", rng=5) + + @pytest.mark.parametrize("dist_name", cases_test_fit_mse()) + def test_basic_fit_mse(self, dist_name): + self.basic_fit_test(dist_name, "mse", rng=2) + + @pytest.mark.slow + def test_arcsine(self): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.arcsine + shapes = (1., 2.) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = {'loc': (0.1, 10), 'scale': (0.1, 10)} + res = stats.fit(dist, data, shape_bounds, method='mse', optimizer=self.opt) + assert_nlff_less_or_close(dist, data, res.params, shapes, + nlff_name='_penalized_nlpsf', **self.tols) + + @pytest.mark.parametrize("method", ('mle', 'mse')) + def test_argus(self, method): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.argus + shapes = (1., 2., 3.) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = {'chi': (0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)} + res = stats.fit(dist, data, shape_bounds, optimizer=self.opt, method=method) + nlff_name = {'mle': 'nnlf', 'mse': '_penalized_nlpsf'}[method] + assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols, + nlff_name=nlff_name) + + @pytest.mark.xslow + def test_beta(self): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.beta + shapes = (2.3098496451481823, 0.62687954300963677, 1., 2.) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = {'a': (0.1, 10), 'b':(0.1, 10), + 'loc': (0.1, 10), 'scale': (0.1, 10)} + res = stats.fit(dist, data, shape_bounds, method='mle', optimizer=self.opt) + assert_nlff_less_or_close(dist, data, res.params, shapes, + nlff_name='nnlf', **self.tols) + + def test_foldnorm(self): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.foldnorm + shapes = (1.952125337355587, 2., 3.) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = {'c': (0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)} + res = stats.fit(dist, data, shape_bounds, optimizer=self.opt) + + assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols) + + def test_nakagami(self): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.nakagami + shapes = (4.9673794866666237, 1., 2.) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = {'nu':(0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)} + res = stats.fit(dist, data, shape_bounds, method='mle', optimizer=self.opt) + assert_nlff_less_or_close(dist, data, res.params, shapes, + nlff_name='nnlf', **self.tols) + + @pytest.mark.slow + def test_powerlaw(self): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.powerlaw + shapes = (1.6591133289905851, 1., 2.) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = {'a': (0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)} + res = stats.fit(dist, data, shape_bounds, method='mse', optimizer=self.opt) + assert_nlff_less_or_close(dist, data, res.params, shapes, + nlff_name='_penalized_nlpsf', **self.tols) + + def test_truncpareto(self): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.truncpareto + shapes = (1.8, 5.3, 2.3, 4.1) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = [(0.1, 10)]*4 + res = stats.fit(dist, data, shape_bounds, optimizer=self.opt) + + assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols) + + @pytest.mark.slow + def test_truncweibull_min(self): + # Can't guarantee that all distributions will fit all data with + # arbitrary bounds. This distribution just happens to fail above. + # Try something slightly different. + N = 1000 + rng = np.random.default_rng(self.seed) + dist = stats.truncweibull_min + shapes = (2.5, 0.25, 1.75, 2., 3.) + data = dist.rvs(*shapes, size=N, random_state=rng) + shape_bounds = [(0.1, 10)]*5 + res = stats.fit(dist, data, shape_bounds, optimizer=self.opt) + + assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols) + + def test_missing_shape_bounds(self): + # some distributions have a small domain w.r.t. a parameter, e.g. + # $p \in [0, 1]$ for binomial distribution + # User does not need to provide these because the intersection of the + # user's bounds (none) and the distribution's domain is finite + N = 1000 + rng = np.random.default_rng(self.seed) + + dist = stats.binom + n, p, loc = 10, 0.65, 0 + data = dist.rvs(n, p, loc=loc, size=N, random_state=rng) + shape_bounds = {'n': np.array([0, 20])} # check arrays are OK, too + res = stats.fit(dist, data, shape_bounds, optimizer=self.opt) + assert_allclose(res.params, (n, p, loc), **self.tols) + + dist = stats.bernoulli + p, loc = 0.314159, 0 + data = dist.rvs(p, loc=loc, size=N, random_state=rng) + res = stats.fit(dist, data, optimizer=self.opt) + assert_allclose(res.params, (p, loc), **self.tols) + + def test_fit_only_loc_scale(self): + # fit only loc + N = 5000 + rng = np.random.default_rng(self.seed) + + dist = stats.norm + loc, scale = 1.5, 1 + data = dist.rvs(loc=loc, size=N, random_state=rng) + loc_bounds = (0, 5) + bounds = {'loc': loc_bounds} + res = stats.fit(dist, data, bounds, optimizer=self.opt) + assert_allclose(res.params, (loc, scale), **self.tols) + + # fit only scale + loc, scale = 0, 2.5 + data = dist.rvs(scale=scale, size=N, random_state=rng) + scale_bounds = (0.01, 5) + bounds = {'scale': scale_bounds} + res = stats.fit(dist, data, bounds, optimizer=self.opt) + assert_allclose(res.params, (loc, scale), **self.tols) + + # fit only loc and scale + dist = stats.norm + loc, scale = 1.5, 2.5 + data = dist.rvs(loc=loc, scale=scale, size=N, random_state=rng) + bounds = {'loc': loc_bounds, 'scale': scale_bounds} + res = stats.fit(dist, data, bounds, optimizer=self.opt) + assert_allclose(res.params, (loc, scale), **self.tols) + + def test_everything_fixed(self): + N = 5000 + rng = np.random.default_rng(self.seed) + + dist = stats.norm + loc, scale = 1.5, 2.5 + data = dist.rvs(loc=loc, scale=scale, size=N, random_state=rng) + + # loc, scale fixed to 0, 1 by default + res = stats.fit(dist, data) + assert_allclose(res.params, (0, 1), **self.tols) + + # loc, scale explicitly fixed + bounds = {'loc': (loc, loc), 'scale': (scale, scale)} + res = stats.fit(dist, data, bounds) + assert_allclose(res.params, (loc, scale), **self.tols) + + # `n` gets fixed during polishing + dist = stats.binom + n, p, loc = 10, 0.65, 0 + data = dist.rvs(n, p, loc=loc, size=N, random_state=rng) + shape_bounds = {'n': (0, 20), 'p': (0.65, 0.65)} + res = stats.fit(dist, data, shape_bounds, optimizer=self.opt) + assert_allclose(res.params, (n, p, loc), **self.tols) + + def test_failure(self): + N = 5000 + rng = np.random.default_rng(self.seed) + + dist = stats.nbinom + shapes = (5, 0.5) + data = dist.rvs(*shapes, size=N, random_state=rng) + + assert data.min() == 0 + # With lower bounds on location at 0.5, likelihood is zero + bounds = [(0, 30), (0, 1), (0.5, 10)] + res = stats.fit(dist, data, bounds) + message = "Optimization converged to parameter values that are" + assert res.message.startswith(message) + assert res.success is False + + @pytest.mark.xslow + def test_guess(self): + # Test that guess helps DE find the desired solution + N = 2000 + # With some seeds, `fit` doesn't need a guess + rng = np.random.default_rng(196390444561) + dist = stats.nhypergeom + params = (20, 7, 12, 0) + bounds = [(2, 200), (0.7, 70), (1.2, 120), (0, 10)] + + data = dist.rvs(*params, size=N, random_state=rng) + + res = stats.fit(dist, data, bounds, optimizer=self.opt) + assert not np.allclose(res.params, params, **self.tols) + + res = stats.fit(dist, data, bounds, guess=params, optimizer=self.opt) + assert_allclose(res.params, params, **self.tols) + + def test_mse_accuracy_1(self): + # Test maximum spacing estimation against example from Wikipedia + # https://en.wikipedia.org/wiki/Maximum_spacing_estimation#Examples + data = [2, 4] + dist = stats.expon + bounds = {'loc': (0, 0), 'scale': (1e-8, 10)} + res_mle = stats.fit(dist, data, bounds=bounds, method='mle') + assert_allclose(res_mle.params.scale, 3, atol=1e-3) + res_mse = stats.fit(dist, data, bounds=bounds, method='mse') + assert_allclose(res_mse.params.scale, 3.915, atol=1e-3) + + def test_mse_accuracy_2(self): + # Test maximum spacing estimation against example from Wikipedia + # https://en.wikipedia.org/wiki/Maximum_spacing_estimation#Examples + rng = np.random.default_rng(9843212616816518964) + + dist = stats.uniform + n = 10 + data = dist(3, 6).rvs(size=n, random_state=rng) + bounds = {'loc': (0, 10), 'scale': (1e-8, 10)} + res = stats.fit(dist, data, bounds=bounds, method='mse') + # (loc=3.608118420015416, scale=5.509323262055043) + + x = np.sort(data) + a = (n*x[0] - x[-1])/(n - 1) + b = (n*x[-1] - x[0])/(n - 1) + ref = a, b-a # (3.6081133632151503, 5.509328130317254) + assert_allclose(res.params, ref, rtol=1e-4) + + +# Data from Matlab: https://www.mathworks.com/help/stats/lillietest.html +examgrades = [65, 61, 81, 88, 69, 89, 55, 84, 86, 84, 71, 81, 84, 81, 78, 67, + 96, 66, 73, 75, 59, 71, 69, 63, 79, 76, 63, 85, 87, 88, 80, 71, + 65, 84, 71, 75, 81, 79, 64, 65, 84, 77, 70, 75, 84, 75, 73, 92, + 90, 79, 80, 71, 73, 71, 58, 79, 73, 64, 77, 82, 81, 59, 54, 82, + 57, 79, 79, 73, 74, 82, 63, 64, 73, 69, 87, 68, 81, 73, 83, 73, + 80, 73, 73, 71, 66, 78, 64, 74, 68, 67, 75, 75, 80, 85, 74, 76, + 80, 77, 93, 70, 86, 80, 81, 83, 68, 60, 85, 64, 74, 82, 81, 77, + 66, 85, 75, 81, 69, 60, 83, 72] + + +class TestGoodnessOfFit: + + def test_gof_iv(self): + dist = stats.norm + x = [1, 2, 3] + + message = r"`dist` must be a \(non-frozen\) instance of..." + with pytest.raises(TypeError, match=message): + goodness_of_fit(stats.norm(), x) + + message = "`data` must be a one-dimensional array of numbers." + with pytest.raises(ValueError, match=message): + goodness_of_fit(dist, [[1, 2, 3]]) + + message = "`statistic` must be one of..." + with pytest.raises(ValueError, match=message): + goodness_of_fit(dist, x, statistic='mm') + + message = "`n_mc_samples` must be an integer." + with pytest.raises(TypeError, match=message): + goodness_of_fit(dist, x, n_mc_samples=1000.5) + + message = "SeedSequence expects int or sequence" + with pytest.raises(TypeError, match=message): + goodness_of_fit(dist, x, rng='herring') + + def test_against_ks(self): + rng = np.random.default_rng(8517426291317196949) + x = examgrades + known_params = {'loc': np.mean(x), 'scale': np.std(x, ddof=1)} + res = goodness_of_fit(stats.norm, x, known_params=known_params, + statistic='ks', rng=rng) + ref = stats.kstest(x, stats.norm(**known_params).cdf, method='exact') + assert_allclose(res.statistic, ref.statistic) # ~0.0848 + assert_allclose(res.pvalue, ref.pvalue, atol=5e-3) # ~0.335 + + def test_against_lilliefors(self): + rng = np.random.default_rng(2291803665717442724) + x = examgrades + # preserve use of old random_state during SPEC 7 transition + res = goodness_of_fit(stats.norm, x, statistic='ks', random_state=rng) + known_params = {'loc': np.mean(x), 'scale': np.std(x, ddof=1)} + ref = stats.kstest(x, stats.norm(**known_params).cdf, method='exact') + assert_allclose(res.statistic, ref.statistic) # ~0.0848 + assert_allclose(res.pvalue, 0.0348, atol=5e-3) + + def test_against_cvm(self): + rng = np.random.default_rng(8674330857509546614) + x = examgrades + known_params = {'loc': np.mean(x), 'scale': np.std(x, ddof=1)} + res = goodness_of_fit(stats.norm, x, known_params=known_params, + statistic='cvm', rng=rng) + ref = stats.cramervonmises(x, stats.norm(**known_params).cdf) + assert_allclose(res.statistic, ref.statistic) # ~0.090 + assert_allclose(res.pvalue, ref.pvalue, atol=5e-3) # ~0.636 + + def test_against_anderson_case_0(self): + # "Case 0" is where loc and scale are known [1] + rng = np.random.default_rng(7384539336846690410) + x = np.arange(1, 101) + # loc that produced critical value of statistic found w/ root_scalar + known_params = {'loc': 45.01575354024957, 'scale': 30} + res = goodness_of_fit(stats.norm, x, known_params=known_params, + statistic='ad', rng=rng) + assert_allclose(res.statistic, 2.492) # See [1] Table 1A 1.0 + assert_allclose(res.pvalue, 0.05, atol=5e-3) + + def test_against_anderson_case_1(self): + # "Case 1" is where scale is known and loc is fit [1] + rng = np.random.default_rng(5040212485680146248) + x = np.arange(1, 101) + # scale that produced critical value of statistic found w/ root_scalar + known_params = {'scale': 29.957112639101933} + res = goodness_of_fit(stats.norm, x, known_params=known_params, + statistic='ad', rng=rng) + assert_allclose(res.statistic, 0.908) # See [1] Table 1B 1.1 + assert_allclose(res.pvalue, 0.1, atol=5e-3) + + def test_against_anderson_case_2(self): + # "Case 2" is where loc is known and scale is fit [1] + rng = np.random.default_rng(726693985720914083) + x = np.arange(1, 101) + # loc that produced critical value of statistic found w/ root_scalar + known_params = {'loc': 44.5680212261933} + res = goodness_of_fit(stats.norm, x, known_params=known_params, + statistic='ad', rng=rng) + assert_allclose(res.statistic, 2.904) # See [1] Table 1B 1.2 + assert_allclose(res.pvalue, 0.025, atol=5e-3) + + def test_against_anderson_case_3(self): + # "Case 3" is where both loc and scale are fit [1] + rng = np.random.default_rng(6763691329830218206) + # c that produced critical value of statistic found w/ root_scalar + x = stats.skewnorm.rvs(1.4477847789132101, loc=1, scale=2, size=100, + random_state=rng) + res = goodness_of_fit(stats.norm, x, statistic='ad', rng=rng) + assert_allclose(res.statistic, 0.559) # See [1] Table 1B 1.2 + assert_allclose(res.pvalue, 0.15, atol=5e-3) + + @pytest.mark.xslow + def test_against_anderson_gumbel_r(self): + rng = np.random.default_rng(7302761058217743) + # c that produced critical value of statistic found w/ root_scalar + x = stats.genextreme(0.051896837188595134, loc=0.5, + scale=1.5).rvs(size=1000, random_state=rng) + res = goodness_of_fit(stats.gumbel_r, x, statistic='ad', + rng=rng) + ref = stats.anderson(x, dist='gumbel_r') + assert_allclose(res.statistic, ref.critical_values[0]) + assert_allclose(res.pvalue, ref.significance_level[0]/100, atol=5e-3) + + def test_against_filliben_norm(self): + # Test against `stats.fit` ref. [7] Section 8 "Example" + rng = np.random.default_rng(8024266430745011915) + y = [6, 1, -4, 8, -2, 5, 0] + known_params = {'loc': 0, 'scale': 1} + res = stats.goodness_of_fit(stats.norm, y, known_params=known_params, + statistic="filliben", rng=rng) + # Slight discrepancy presumably due to roundoff in Filliben's + # calculation. Using exact order statistic medians instead of + # Filliben's approximation doesn't account for it. + assert_allclose(res.statistic, 0.98538, atol=1e-4) + assert 0.75 < res.pvalue < 0.9 + + # Using R's ppcc library: + # library(ppcc) + # options(digits=16) + # x < - c(6, 1, -4, 8, -2, 5, 0) + # set.seed(100) + # ppccTest(x, "qnorm", ppos="Filliben") + # Discrepancy with + assert_allclose(res.statistic, 0.98540957187084, rtol=2e-5) + assert_allclose(res.pvalue, 0.8875, rtol=2e-3) + + def test_filliben_property(self): + # Filliben's statistic should be independent of data location and scale + rng = np.random.default_rng(8535677809395478813) + x = rng.normal(loc=10, scale=0.5, size=100) + res = stats.goodness_of_fit(stats.norm, x, + statistic="filliben", rng=rng) + known_params = {'loc': 0, 'scale': 1} + ref = stats.goodness_of_fit(stats.norm, x, known_params=known_params, + statistic="filliben", rng=rng) + assert_allclose(res.statistic, ref.statistic, rtol=1e-15) + + @pytest.mark.parametrize('case', [(25, [.928, .937, .950, .958, .966]), + (50, [.959, .965, .972, .977, .981]), + (95, [.977, .979, .983, .986, .989])]) + def test_against_filliben_norm_table(self, case): + # Test against `stats.fit` ref. [7] Table 1 + rng = np.random.default_rng(504569995557928957) + n, ref = case + x = rng.random(n) + known_params = {'loc': 0, 'scale': 1} + res = stats.goodness_of_fit(stats.norm, x, known_params=known_params, + statistic="filliben", rng=rng) + percentiles = np.array([0.005, 0.01, 0.025, 0.05, 0.1]) + res = stats.scoreatpercentile(res.null_distribution, percentiles*100) + assert_allclose(res, ref, atol=2e-3) + + @pytest.mark.xslow + @pytest.mark.parametrize('case', [(5, 0.95772790260469, 0.4755), + (6, 0.95398832257958, 0.3848), + (7, 0.9432692889277, 0.2328)]) + def test_against_ppcc(self, case): + # Test against R ppcc, e.g. + # library(ppcc) + # options(digits=16) + # x < - c(0.52325412, 1.06907699, -0.36084066, 0.15305959, 0.99093194) + # set.seed(100) + # ppccTest(x, "qrayleigh", ppos="Filliben") + n, ref_statistic, ref_pvalue = case + rng = np.random.default_rng(7777775561439803116) + x = rng.normal(size=n) + res = stats.goodness_of_fit(stats.rayleigh, x, statistic="filliben", + rng=rng) + assert_allclose(res.statistic, ref_statistic, rtol=1e-4) + assert_allclose(res.pvalue, ref_pvalue, atol=1.5e-2) + + def test_params_effects(self): + # Ensure that `guessed_params`, `fit_params`, and `known_params` have + # the intended effects. + rng = np.random.default_rng(9121950977643805391) + x = stats.skewnorm.rvs(-5.044559778383153, loc=1, scale=2, size=50, + random_state=rng) + + # Show that `guessed_params` don't fit to the guess, + # but `fit_params` and `known_params` respect the provided fit + guessed_params = {'c': 13.4} + fit_params = {'scale': 13.73} + known_params = {'loc': -13.85} + rng = np.random.default_rng(9121950977643805391) + res1 = goodness_of_fit(stats.weibull_min, x, n_mc_samples=2, + guessed_params=guessed_params, + fit_params=fit_params, + known_params=known_params, rng=rng) + assert not np.allclose(res1.fit_result.params.c, 13.4) + assert_equal(res1.fit_result.params.scale, 13.73) + assert_equal(res1.fit_result.params.loc, -13.85) + + # Show that changing the guess changes the parameter that gets fit, + # and it changes the null distribution + guessed_params = {'c': 2} + rng = np.random.default_rng(9121950977643805391) + res2 = goodness_of_fit(stats.weibull_min, x, n_mc_samples=2, + guessed_params=guessed_params, + fit_params=fit_params, + known_params=known_params, rng=rng) + assert not np.allclose(res2.fit_result.params.c, + res1.fit_result.params.c, rtol=1e-8) + assert not np.allclose(res2.null_distribution, + res1.null_distribution, rtol=1e-8) + assert_equal(res2.fit_result.params.scale, 13.73) + assert_equal(res2.fit_result.params.loc, -13.85) + + # If we set all parameters as fit_params and known_params, + # they're all fixed to those values, but the null distribution + # varies. + fit_params = {'c': 13.4, 'scale': 13.73} + rng = np.random.default_rng(9121950977643805391) + res3 = goodness_of_fit(stats.weibull_min, x, n_mc_samples=2, + guessed_params=guessed_params, + fit_params=fit_params, + known_params=known_params, rng=rng) + assert_equal(res3.fit_result.params.c, 13.4) + assert_equal(res3.fit_result.params.scale, 13.73) + assert_equal(res3.fit_result.params.loc, -13.85) + assert not np.allclose(res3.null_distribution, res1.null_distribution) + + def test_custom_statistic(self): + # Test support for custom statistic function. + + # References: + # [1] Pyke, R. (1965). "Spacings". Journal of the Royal Statistical + # Society: Series B (Methodological), 27(3): 395-436. + # [2] Burrows, P. M. (1979). "Selected Percentage Points of + # Greenwood's Statistics". Journal of the Royal Statistical + # Society. Series A (General), 142(2): 256-258. + + # Use the Greenwood statistic for illustration; see [1, p.402]. + def greenwood(dist, data, *, axis): + x = np.sort(data, axis=axis) + y = dist.cdf(x) + d = np.diff(y, axis=axis, prepend=0, append=1) + return np.sum(d ** 2, axis=axis) + + # Run the Monte Carlo test with sample size = 5 on a fully specified + # null distribution, and compare the simulated quantiles to the exact + # ones given in [2, Table 1, column (n = 5)]. + rng = np.random.default_rng(9121950977643805391) + data = stats.expon.rvs(size=5, random_state=rng) + result = goodness_of_fit(stats.expon, data, + known_params={'loc': 0, 'scale': 1}, + statistic=greenwood, rng=rng) + p = [.01, .05, .1, .2, .3, .4, .5, .6, .7, .8, .9, .95, .99] + exact_quantiles = [ + .183863, .199403, .210088, .226040, .239947, .253677, .268422, + .285293, .306002, .334447, .382972, .432049, .547468] + simulated_quantiles = np.quantile(result.null_distribution, p) + assert_allclose(simulated_quantiles, exact_quantiles, atol=0.005) + +class TestFitResult: + def test_plot_iv(self): + rng = np.random.default_rng(1769658657308472721) + data = stats.norm.rvs(0, 1, size=100, random_state=rng) + + def optimizer(*args, **kwargs): + return differential_evolution(*args, **kwargs, rng=rng) + + bounds = [(0, 30), (0, 1)] + res = stats.fit(stats.norm, data, bounds, optimizer=optimizer) + try: + import matplotlib # noqa: F401 + message = r"`plot_type` must be one of \{'..." + with pytest.raises(ValueError, match=message): + res.plot(plot_type='llama') + except (ModuleNotFoundError, ImportError): + message = r"matplotlib must be installed to use method `plot`." + with pytest.raises(ModuleNotFoundError, match=message): + res.plot(plot_type='llama') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_hypotests.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_hypotests.py new file mode 100644 index 0000000000000000000000000000000000000000..e996f9567248383d96beba09243ad1a1fd977652 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_hypotests.py @@ -0,0 +1,1862 @@ +from itertools import product + +import numpy as np +import random +import functools +import pytest +from numpy.testing import (assert_, assert_equal, assert_allclose, + assert_almost_equal) # avoid new uses +from pytest import raises as assert_raises + +import scipy.stats as stats +from scipy.stats import distributions +from scipy.stats._hypotests import (epps_singleton_2samp, cramervonmises, + _cdf_cvm, cramervonmises_2samp, + _pval_cvm_2samp_exact, barnard_exact, + boschloo_exact) +from scipy.stats._mannwhitneyu import mannwhitneyu, _mwu_state, _MWU +from .common_tests import check_named_results +from scipy._lib._testutils import _TestPythranFunc +from scipy.stats._axis_nan_policy import SmallSampleWarning, too_small_1d_not_omit + + +class TestEppsSingleton: + def test_statistic_1(self): + # first example in Goerg & Kaiser, also in original paper of + # Epps & Singleton. Note: values do not match exactly, the + # value of the interquartile range varies depending on how + # quantiles are computed + x = np.array([-0.35, 2.55, 1.73, 0.73, 0.35, + 2.69, 0.46, -0.94, -0.37, 12.07]) + y = np.array([-1.15, -0.15, 2.48, 3.25, 3.71, + 4.29, 5.00, 7.74, 8.38, 8.60]) + w, p = epps_singleton_2samp(x, y) + assert_almost_equal(w, 15.14, decimal=1) + assert_almost_equal(p, 0.00442, decimal=3) + + def test_statistic_2(self): + # second example in Goerg & Kaiser, again not a perfect match + x = np.array((0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 10, + 10, 10, 10)) + y = np.array((10, 4, 0, 5, 10, 10, 0, 5, 6, 7, 10, 3, 1, 7, 0, 8, 1, + 5, 8, 10)) + w, p = epps_singleton_2samp(x, y) + assert_allclose(w, 8.900, atol=0.001) + assert_almost_equal(p, 0.06364, decimal=3) + + def test_epps_singleton_array_like(self): + np.random.seed(1234) + x, y = np.arange(30), np.arange(28) + + w1, p1 = epps_singleton_2samp(list(x), list(y)) + w2, p2 = epps_singleton_2samp(tuple(x), tuple(y)) + w3, p3 = epps_singleton_2samp(x, y) + + assert_(w1 == w2 == w3) + assert_(p1 == p2 == p3) + + def test_epps_singleton_size(self): + # warns if sample contains fewer than 5 elements + x, y = (1, 2, 3, 4), np.arange(10) + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = epps_singleton_2samp(x, y) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_epps_singleton_nonfinite(self): + # raise error if there are non-finite values + x, y = (1, 2, 3, 4, 5, np.inf), np.arange(10) + assert_raises(ValueError, epps_singleton_2samp, x, y) + + def test_names(self): + x, y = np.arange(20), np.arange(30) + res = epps_singleton_2samp(x, y) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes) + + +class TestCvm: + # the expected values of the cdfs are taken from Table 1 in + # Csorgo / Faraway: The Exact and Asymptotic Distribution of + # Cramér-von Mises Statistics, 1996. + def test_cdf_4(self): + assert_allclose( + _cdf_cvm([0.02983, 0.04111, 0.12331, 0.94251], 4), + [0.01, 0.05, 0.5, 0.999], + atol=1e-4) + + def test_cdf_10(self): + assert_allclose( + _cdf_cvm([0.02657, 0.03830, 0.12068, 0.56643], 10), + [0.01, 0.05, 0.5, 0.975], + atol=1e-4) + + def test_cdf_1000(self): + assert_allclose( + _cdf_cvm([0.02481, 0.03658, 0.11889, 1.16120], 1000), + [0.01, 0.05, 0.5, 0.999], + atol=1e-4) + + def test_cdf_inf(self): + assert_allclose( + _cdf_cvm([0.02480, 0.03656, 0.11888, 1.16204]), + [0.01, 0.05, 0.5, 0.999], + atol=1e-4) + + def test_cdf_support(self): + # cdf has support on [1/(12*n), n/3] + assert_equal(_cdf_cvm([1/(12*533), 533/3], 533), [0, 1]) + assert_equal(_cdf_cvm([1/(12*(27 + 1)), (27 + 1)/3], 27), [0, 1]) + + def test_cdf_large_n(self): + # test that asymptotic cdf and cdf for large samples are close + assert_allclose( + _cdf_cvm([0.02480, 0.03656, 0.11888, 1.16204, 100], 10000), + _cdf_cvm([0.02480, 0.03656, 0.11888, 1.16204, 100]), + atol=1e-4) + + def test_large_x(self): + # for large values of x and n, the series used to compute the cdf + # converges slowly. + # this leads to bug in R package goftest and MAPLE code that is + # the basis of the implementation in scipy + # note: cdf = 1 for x >= 1000/3 and n = 1000 + assert_(0.99999 < _cdf_cvm(333.3, 1000) < 1.0) + assert_(0.99999 < _cdf_cvm(333.3) < 1.0) + + def test_low_p(self): + # _cdf_cvm can return values larger than 1. In that case, we just + # return a p-value of zero. + n = 12 + res = cramervonmises(np.ones(n)*0.8, 'norm') + assert_(_cdf_cvm(res.statistic, n) > 1.0) + assert_equal(res.pvalue, 0) + + @pytest.mark.parametrize('x', [(), [1.5]]) + def test_invalid_input(self, x): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = cramervonmises(x, "norm") + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_values_R(self): + # compared against R package goftest, version 1.1.1 + # goftest::cvm.test(c(-1.7, 2, 0, 1.3, 4, 0.1, 0.6), "pnorm") + res = cramervonmises([-1.7, 2, 0, 1.3, 4, 0.1, 0.6], "norm") + assert_allclose(res.statistic, 0.288156, atol=1e-6) + assert_allclose(res.pvalue, 0.1453465, atol=1e-6) + + # goftest::cvm.test(c(-1.7, 2, 0, 1.3, 4, 0.1, 0.6), + # "pnorm", mean = 3, sd = 1.5) + res = cramervonmises([-1.7, 2, 0, 1.3, 4, 0.1, 0.6], "norm", (3, 1.5)) + assert_allclose(res.statistic, 0.9426685, atol=1e-6) + assert_allclose(res.pvalue, 0.002026417, atol=1e-6) + + # goftest::cvm.test(c(1, 2, 5, 1.4, 0.14, 11, 13, 0.9, 7.5), "pexp") + res = cramervonmises([1, 2, 5, 1.4, 0.14, 11, 13, 0.9, 7.5], "expon") + assert_allclose(res.statistic, 0.8421854, atol=1e-6) + assert_allclose(res.pvalue, 0.004433406, atol=1e-6) + + def test_callable_cdf(self): + x, args = np.arange(5), (1.4, 0.7) + r1 = cramervonmises(x, distributions.expon.cdf) + r2 = cramervonmises(x, "expon") + assert_equal((r1.statistic, r1.pvalue), (r2.statistic, r2.pvalue)) + + r1 = cramervonmises(x, distributions.beta.cdf, args) + r2 = cramervonmises(x, "beta", args) + assert_equal((r1.statistic, r1.pvalue), (r2.statistic, r2.pvalue)) + + +class TestMannWhitneyU: + + # All magic numbers are from R wilcox.test unless otherwise specified + # https://rdrr.io/r/stats/wilcox.test.html + + # --- Test Input Validation --- + + @pytest.mark.parametrize('kwargs_update', [{'x': []}, {'y': []}, + {'x': [], 'y': []}]) + def test_empty(self, kwargs_update): + x = np.array([1, 2]) # generic, valid inputs + y = np.array([3, 4]) + kwargs = dict(x=x, y=y) + kwargs.update(kwargs_update) + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = mannwhitneyu(**kwargs) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_input_validation(self): + x = np.array([1, 2]) # generic, valid inputs + y = np.array([3, 4]) + with assert_raises(ValueError, match="`use_continuity` must be one"): + mannwhitneyu(x, y, use_continuity='ekki') + with assert_raises(ValueError, match="`alternative` must be one of"): + mannwhitneyu(x, y, alternative='ekki') + with assert_raises(ValueError, match="`axis` must be an integer"): + mannwhitneyu(x, y, axis=1.5) + with assert_raises(ValueError, match="`method` must be one of"): + mannwhitneyu(x, y, method='ekki') + + def test_auto(self): + # Test that default method ('auto') chooses intended method + + np.random.seed(1) + n = 8 # threshold to switch from exact to asymptotic + + # both inputs are smaller than threshold; should use exact + x = np.random.rand(n-1) + y = np.random.rand(n-1) + auto = mannwhitneyu(x, y) + asymptotic = mannwhitneyu(x, y, method='asymptotic') + exact = mannwhitneyu(x, y, method='exact') + assert auto.pvalue == exact.pvalue + assert auto.pvalue != asymptotic.pvalue + + # one input is smaller than threshold; should use exact + x = np.random.rand(n-1) + y = np.random.rand(n+1) + auto = mannwhitneyu(x, y) + asymptotic = mannwhitneyu(x, y, method='asymptotic') + exact = mannwhitneyu(x, y, method='exact') + assert auto.pvalue == exact.pvalue + assert auto.pvalue != asymptotic.pvalue + + # other input is smaller than threshold; should use exact + auto = mannwhitneyu(y, x) + asymptotic = mannwhitneyu(x, y, method='asymptotic') + exact = mannwhitneyu(x, y, method='exact') + assert auto.pvalue == exact.pvalue + assert auto.pvalue != asymptotic.pvalue + + # both inputs are larger than threshold; should use asymptotic + x = np.random.rand(n+1) + y = np.random.rand(n+1) + auto = mannwhitneyu(x, y) + asymptotic = mannwhitneyu(x, y, method='asymptotic') + exact = mannwhitneyu(x, y, method='exact') + assert auto.pvalue != exact.pvalue + assert auto.pvalue == asymptotic.pvalue + + # both inputs are smaller than threshold, but there is a tie + # should use asymptotic + x = np.random.rand(n-1) + y = np.random.rand(n-1) + y[3] = x[3] + auto = mannwhitneyu(x, y) + asymptotic = mannwhitneyu(x, y, method='asymptotic') + exact = mannwhitneyu(x, y, method='exact') + assert auto.pvalue != exact.pvalue + assert auto.pvalue == asymptotic.pvalue + + # --- Test Basic Functionality --- + + x = [210.052110, 110.190630, 307.918612] + y = [436.08811482466416, 416.37397329768191, 179.96975939463582, + 197.8118754228619, 34.038757281225756, 138.54220550921517, + 128.7769351470246, 265.92721427951852, 275.6617533155341, + 592.34083395416258, 448.73177590617018, 300.61495185038905, + 187.97508449019588] + + # This test was written for mann_whitney_u in gh-4933. + # Originally, the p-values for alternatives were swapped; + # this has been corrected and the tests have been refactored for + # compactness, but otherwise the tests are unchanged. + # R code for comparison, e.g.: + # options(digits = 16) + # x = c(210.052110, 110.190630, 307.918612) + # y = c(436.08811482466416, 416.37397329768191, 179.96975939463582, + # 197.8118754228619, 34.038757281225756, 138.54220550921517, + # 128.7769351470246, 265.92721427951852, 275.6617533155341, + # 592.34083395416258, 448.73177590617018, 300.61495185038905, + # 187.97508449019588) + # wilcox.test(x, y, alternative="g", exact=TRUE) + cases_basic = [[{"alternative": 'two-sided', "method": "asymptotic"}, + (16, 0.6865041817876)], + [{"alternative": 'less', "method": "asymptotic"}, + (16, 0.3432520908938)], + [{"alternative": 'greater', "method": "asymptotic"}, + (16, 0.7047591913255)], + [{"alternative": 'two-sided', "method": "exact"}, + (16, 0.7035714285714)], + [{"alternative": 'less', "method": "exact"}, + (16, 0.3517857142857)], + [{"alternative": 'greater', "method": "exact"}, + (16, 0.6946428571429)]] + + @pytest.mark.parametrize(("kwds", "expected"), cases_basic) + def test_basic(self, kwds, expected): + res = mannwhitneyu(self.x, self.y, **kwds) + assert_allclose(res, expected) + + cases_continuity = [[{"alternative": 'two-sided', "use_continuity": True}, + (23, 0.6865041817876)], + [{"alternative": 'less', "use_continuity": True}, + (23, 0.7047591913255)], + [{"alternative": 'greater', "use_continuity": True}, + (23, 0.3432520908938)], + [{"alternative": 'two-sided', "use_continuity": False}, + (23, 0.6377328900502)], + [{"alternative": 'less', "use_continuity": False}, + (23, 0.6811335549749)], + [{"alternative": 'greater', "use_continuity": False}, + (23, 0.3188664450251)]] + + @pytest.mark.parametrize(("kwds", "expected"), cases_continuity) + def test_continuity(self, kwds, expected): + # When x and y are interchanged, less and greater p-values should + # swap (compare to above). This wouldn't happen if the continuity + # correction were applied in the wrong direction. Note that less and + # greater p-values do not sum to 1 when continuity correction is on, + # which is what we'd expect. Also check that results match R when + # continuity correction is turned off. + # Note that method='asymptotic' -> exact=FALSE + # and use_continuity=False -> correct=FALSE, e.g.: + # wilcox.test(x, y, alternative="t", exact=FALSE, correct=FALSE) + res = mannwhitneyu(self.y, self.x, method='asymptotic', **kwds) + assert_allclose(res, expected) + + def test_tie_correct(self): + # Test tie correction against R's wilcox.test + # options(digits = 16) + # x = c(1, 2, 3, 4) + # y = c(1, 2, 3, 4, 5) + # wilcox.test(x, y, exact=FALSE) + x = [1, 2, 3, 4] + y0 = np.array([1, 2, 3, 4, 5]) + dy = np.array([0, 1, 0, 1, 0])*0.01 + dy2 = np.array([0, 0, 1, 0, 0])*0.01 + y = [y0-0.01, y0-dy, y0-dy2, y0, y0+dy2, y0+dy, y0+0.01] + res = mannwhitneyu(x, y, axis=-1, method="asymptotic") + U_expected = [10, 9, 8.5, 8, 7.5, 7, 6] + p_expected = [1, 0.9017048037317, 0.804080657472, 0.7086240584439, + 0.6197963884941, 0.5368784563079, 0.3912672792826] + assert_equal(res.statistic, U_expected) + assert_allclose(res.pvalue, p_expected) + + # --- Test Exact Distribution of U --- + + # These are tabulated values of the CDF of the exact distribution of + # the test statistic from pg 52 of reference [1] (Mann-Whitney Original) + pn3 = {1: [0.25, 0.5, 0.75], 2: [0.1, 0.2, 0.4, 0.6], + 3: [0.05, .1, 0.2, 0.35, 0.5, 0.65]} + pn4 = {1: [0.2, 0.4, 0.6], 2: [0.067, 0.133, 0.267, 0.4, 0.6], + 3: [0.028, 0.057, 0.114, 0.2, .314, 0.429, 0.571], + 4: [0.014, 0.029, 0.057, 0.1, 0.171, 0.243, 0.343, 0.443, 0.557]} + pm5 = {1: [0.167, 0.333, 0.5, 0.667], + 2: [0.047, 0.095, 0.19, 0.286, 0.429, 0.571], + 3: [0.018, 0.036, 0.071, 0.125, 0.196, 0.286, 0.393, 0.5, 0.607], + 4: [0.008, 0.016, 0.032, 0.056, 0.095, 0.143, + 0.206, 0.278, 0.365, 0.452, 0.548], + 5: [0.004, 0.008, 0.016, 0.028, 0.048, 0.075, 0.111, + 0.155, 0.21, 0.274, 0.345, .421, 0.5, 0.579]} + pm6 = {1: [0.143, 0.286, 0.428, 0.571], + 2: [0.036, 0.071, 0.143, 0.214, 0.321, 0.429, 0.571], + 3: [0.012, 0.024, 0.048, 0.083, 0.131, + 0.19, 0.274, 0.357, 0.452, 0.548], + 4: [0.005, 0.01, 0.019, 0.033, 0.057, 0.086, 0.129, + 0.176, 0.238, 0.305, 0.381, 0.457, 0.543], # the last element + # of the previous list, 0.543, has been modified from 0.545; + # I assume it was a typo + 5: [0.002, 0.004, 0.009, 0.015, 0.026, 0.041, 0.063, 0.089, + 0.123, 0.165, 0.214, 0.268, 0.331, 0.396, 0.465, 0.535], + 6: [0.001, 0.002, 0.004, 0.008, 0.013, 0.021, 0.032, 0.047, + 0.066, 0.09, 0.12, 0.155, 0.197, 0.242, 0.294, 0.350, + 0.409, 0.469, 0.531]} + + def test_exact_distribution(self): + # I considered parametrize. I decided against it. + setattr(_mwu_state, 's', _MWU(0, 0)) + + p_tables = {3: self.pn3, 4: self.pn4, 5: self.pm5, 6: self.pm6} + for n, table in p_tables.items(): + for m, p in table.items(): + # check p-value against table + u = np.arange(0, len(p)) + _mwu_state.s.set_shapes(m, n) + assert_allclose(_mwu_state.s.cdf(k=u), p, atol=1e-3) + + # check identity CDF + SF - PMF = 1 + # ( In this implementation, SF(U) includes PMF(U) ) + u2 = np.arange(0, m*n+1) + assert_allclose(_mwu_state.s.cdf(k=u2) + + _mwu_state.s.sf(k=u2) + - _mwu_state.s.pmf(k=u2), 1) + + # check symmetry about mean of U, i.e. pmf(U) = pmf(m*n-U) + pmf = _mwu_state.s.pmf(k=u2) + assert_allclose(pmf, pmf[::-1]) + + # check symmetry w.r.t. interchange of m, n + _mwu_state.s.set_shapes(n, m) + pmf2 = _mwu_state.s.pmf(k=u2) + assert_allclose(pmf, pmf2) + + def test_asymptotic_behavior(self): + np.random.seed(0) + + # for small samples, the asymptotic test is not very accurate + x = np.random.rand(5) + y = np.random.rand(5) + res1 = mannwhitneyu(x, y, method="exact") + res2 = mannwhitneyu(x, y, method="asymptotic") + assert res1.statistic == res2.statistic + assert np.abs(res1.pvalue - res2.pvalue) > 1e-2 + + # for large samples, they agree reasonably well + x = np.random.rand(40) + y = np.random.rand(40) + res1 = mannwhitneyu(x, y, method="exact") + res2 = mannwhitneyu(x, y, method="asymptotic") + assert res1.statistic == res2.statistic + assert np.abs(res1.pvalue - res2.pvalue) < 1e-3 + + # --- Test Corner Cases --- + + def test_exact_U_equals_mean(self): + # Test U == m*n/2 with exact method + # Without special treatment, two-sided p-value > 1 because both + # one-sided p-values are > 0.5 + res_l = mannwhitneyu([1, 2, 3], [1.5, 2.5], alternative="less", + method="exact") + res_g = mannwhitneyu([1, 2, 3], [1.5, 2.5], alternative="greater", + method="exact") + assert_equal(res_l.pvalue, res_g.pvalue) + assert res_l.pvalue > 0.5 + + res = mannwhitneyu([1, 2, 3], [1.5, 2.5], alternative="two-sided", + method="exact") + assert_equal(res, (3, 1)) + # U == m*n/2 for asymptotic case tested in test_gh_2118 + # The reason it's tricky for the asymptotic test has to do with + # continuity correction. + + cases_scalar = [[{"alternative": 'two-sided', "method": "asymptotic"}, + (0, 1)], + [{"alternative": 'less', "method": "asymptotic"}, + (0, 0.5)], + [{"alternative": 'greater', "method": "asymptotic"}, + (0, 0.977249868052)], + [{"alternative": 'two-sided', "method": "exact"}, (0, 1)], + [{"alternative": 'less', "method": "exact"}, (0, 0.5)], + [{"alternative": 'greater', "method": "exact"}, (0, 1)]] + + @pytest.mark.parametrize(("kwds", "result"), cases_scalar) + def test_scalar_data(self, kwds, result): + # just making sure scalars work + assert_allclose(mannwhitneyu(1, 2, **kwds), result) + + def test_equal_scalar_data(self): + # when two scalars are equal, there is an -0.5/0 in the asymptotic + # approximation. R gives pvalue=1.0 for alternatives 'less' and + # 'greater' but NA for 'two-sided'. I don't see why, so I don't + # see a need for a special case to match that behavior. + assert_equal(mannwhitneyu(1, 1, method="exact"), (0.5, 1)) + assert_equal(mannwhitneyu(1, 1, method="asymptotic"), (0.5, 1)) + + # without continuity correction, this becomes 0/0, which really + # is undefined + assert_equal(mannwhitneyu(1, 1, method="asymptotic", + use_continuity=False), (0.5, np.nan)) + + # --- Test Enhancements / Bug Reports --- + + @pytest.mark.parametrize("method", ["asymptotic", "exact"]) + def test_gh_12837_11113(self, method): + # Test that behavior for broadcastable nd arrays is appropriate: + # output shape is correct and all values are equal to when the test + # is performed on one pair of samples at a time. + # Tests that gh-12837 and gh-11113 (requests for n-d input) + # are resolved + np.random.seed(0) + + # arrays are broadcastable except for axis = -3 + axis = -3 + m, n = 7, 10 # sample sizes + x = np.random.rand(m, 3, 8) + y = np.random.rand(6, n, 1, 8) + 0.1 + res = mannwhitneyu(x, y, method=method, axis=axis) + + shape = (6, 3, 8) # appropriate shape of outputs, given inputs + assert res.pvalue.shape == shape + assert res.statistic.shape == shape + + # move axis of test to end for simplicity + x, y = np.moveaxis(x, axis, -1), np.moveaxis(y, axis, -1) + + x = x[None, ...] # give x a zeroth dimension + assert x.ndim == y.ndim + + x = np.broadcast_to(x, shape + (m,)) + y = np.broadcast_to(y, shape + (n,)) + assert x.shape[:-1] == shape + assert y.shape[:-1] == shape + + # loop over pairs of samples + statistics = np.zeros(shape) + pvalues = np.zeros(shape) + for indices in product(*[range(i) for i in shape]): + xi = x[indices] + yi = y[indices] + temp = mannwhitneyu(xi, yi, method=method) + statistics[indices] = temp.statistic + pvalues[indices] = temp.pvalue + + np.testing.assert_equal(res.pvalue, pvalues) + np.testing.assert_equal(res.statistic, statistics) + + def test_gh_11355(self): + # Test for correct behavior with NaN/Inf in input + x = [1, 2, 3, 4] + y = [3, 6, 7, 8, 9, 3, 2, 1, 4, 4, 5] + res1 = mannwhitneyu(x, y) + + # Inf is not a problem. This is a rank test, and it's the largest value + y[4] = np.inf + res2 = mannwhitneyu(x, y) + + assert_equal(res1.statistic, res2.statistic) + assert_equal(res1.pvalue, res2.pvalue) + + # NaNs should propagate by default. + y[4] = np.nan + res3 = mannwhitneyu(x, y) + assert_equal(res3.statistic, np.nan) + assert_equal(res3.pvalue, np.nan) + + cases_11355 = [([1, 2, 3, 4], + [3, 6, 7, 8, np.inf, 3, 2, 1, 4, 4, 5], + 10, 0.1297704873477), + ([1, 2, 3, 4], + [3, 6, 7, 8, np.inf, np.inf, 2, 1, 4, 4, 5], + 8.5, 0.08735617507695), + ([1, 2, np.inf, 4], + [3, 6, 7, 8, np.inf, 3, 2, 1, 4, 4, 5], + 17.5, 0.5988856695752), + ([1, 2, np.inf, 4], + [3, 6, 7, 8, np.inf, np.inf, 2, 1, 4, 4, 5], + 16, 0.4687165824462), + ([1, np.inf, np.inf, 4], + [3, 6, 7, 8, np.inf, np.inf, 2, 1, 4, 4, 5], + 24.5, 0.7912517950119)] + + @pytest.mark.parametrize(("x", "y", "statistic", "pvalue"), cases_11355) + def test_gh_11355b(self, x, y, statistic, pvalue): + # Test for correct behavior with NaN/Inf in input + res = mannwhitneyu(x, y, method='asymptotic') + assert_allclose(res.statistic, statistic, atol=1e-12) + assert_allclose(res.pvalue, pvalue, atol=1e-12) + + cases_9184 = [[True, "less", "asymptotic", 0.900775348204], + [True, "greater", "asymptotic", 0.1223118025635], + [True, "two-sided", "asymptotic", 0.244623605127], + [False, "less", "asymptotic", 0.8896643190401], + [False, "greater", "asymptotic", 0.1103356809599], + [False, "two-sided", "asymptotic", 0.2206713619198], + [True, "less", "exact", 0.8967698967699], + [True, "greater", "exact", 0.1272061272061], + [True, "two-sided", "exact", 0.2544122544123]] + + @pytest.mark.parametrize(("use_continuity", "alternative", + "method", "pvalue_exp"), cases_9184) + def test_gh_9184(self, use_continuity, alternative, method, pvalue_exp): + # gh-9184 might be considered a doc-only bug. Please see the + # documentation to confirm that mannwhitneyu correctly notes + # that the output statistic is that of the first sample (x). In any + # case, check the case provided there against output from R. + # R code: + # options(digits=16) + # x <- c(0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64, 0.73, 1.46) + # y <- c(1.15, 0.88, 0.90, 0.74, 1.21) + # wilcox.test(x, y, alternative = "less", exact = FALSE) + # wilcox.test(x, y, alternative = "greater", exact = FALSE) + # wilcox.test(x, y, alternative = "two.sided", exact = FALSE) + # wilcox.test(x, y, alternative = "less", exact = FALSE, + # correct=FALSE) + # wilcox.test(x, y, alternative = "greater", exact = FALSE, + # correct=FALSE) + # wilcox.test(x, y, alternative = "two.sided", exact = FALSE, + # correct=FALSE) + # wilcox.test(x, y, alternative = "less", exact = TRUE) + # wilcox.test(x, y, alternative = "greater", exact = TRUE) + # wilcox.test(x, y, alternative = "two.sided", exact = TRUE) + statistic_exp = 35 + x = (0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64, 0.73, 1.46) + y = (1.15, 0.88, 0.90, 0.74, 1.21) + res = mannwhitneyu(x, y, use_continuity=use_continuity, + alternative=alternative, method=method) + assert_equal(res.statistic, statistic_exp) + assert_allclose(res.pvalue, pvalue_exp) + + def test_gh_4067(self): + # Test for correct behavior with all NaN input - default is propagate + a = np.array([np.nan, np.nan, np.nan, np.nan, np.nan]) + b = np.array([np.nan, np.nan, np.nan, np.nan, np.nan]) + res = mannwhitneyu(a, b) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + # All cases checked against R wilcox.test, e.g. + # options(digits=16) + # x = c(1, 2, 3) + # y = c(1.5, 2.5) + # wilcox.test(x, y, exact=FALSE, alternative='less') + + cases_2118 = [[[1, 2, 3], [1.5, 2.5], "greater", (3, 0.6135850036578)], + [[1, 2, 3], [1.5, 2.5], "less", (3, 0.6135850036578)], + [[1, 2, 3], [1.5, 2.5], "two-sided", (3, 1.0)], + [[1, 2, 3], [2], "greater", (1.5, 0.681324055883)], + [[1, 2, 3], [2], "less", (1.5, 0.681324055883)], + [[1, 2, 3], [2], "two-sided", (1.5, 1)], + [[1, 2], [1, 2], "greater", (2, 0.667497228949)], + [[1, 2], [1, 2], "less", (2, 0.667497228949)], + [[1, 2], [1, 2], "two-sided", (2, 1)]] + + @pytest.mark.parametrize(["x", "y", "alternative", "expected"], cases_2118) + def test_gh_2118(self, x, y, alternative, expected): + # test cases in which U == m*n/2 when method is asymptotic + # applying continuity correction could result in p-value > 1 + res = mannwhitneyu(x, y, use_continuity=True, alternative=alternative, + method="asymptotic") + assert_allclose(res, expected, rtol=1e-12) + + def test_gh19692_smaller_table(self): + # In gh-19692, we noted that the shape of the cache used in calculating + # p-values was dependent on the order of the inputs because the sample + # sizes n1 and n2 changed. This was indicative of unnecessary cache + # growth and redundant calculation. Check that this is resolved. + rng = np.random.default_rng(7600451795963068007) + m, n = 5, 11 + x = rng.random(size=m) + y = rng.random(size=n) + + setattr(_mwu_state, 's', _MWU(0, 0)) + _mwu_state.s.reset() # reset cache + + res = stats.mannwhitneyu(x, y, method='exact') + shape = _mwu_state.s.configurations.shape + assert shape[-1] == min(res.statistic, m*n - res.statistic) + 1 + stats.mannwhitneyu(y, x, method='exact') + assert shape == _mwu_state.s.configurations.shape # same with reversed sizes + + # Also, we weren't exploiting the symmetry of the null distribution + # to its full potential. Ensure that the null distribution is not + # evaluated explicitly for `k > m*n/2`. + _mwu_state.s.reset() # reset cache + stats.mannwhitneyu(x, 0*y, method='exact', alternative='greater') + shape = _mwu_state.s.configurations.shape + assert shape[-1] == 1 # k is smallest possible + stats.mannwhitneyu(0*x, y, method='exact', alternative='greater') + assert shape == _mwu_state.s.configurations.shape + + @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided']) + def test_permutation_method(self, alternative): + rng = np.random.default_rng(7600451795963068007) + x = rng.random(size=(2, 5)) + y = rng.random(size=(2, 6)) + res = stats.mannwhitneyu(x, y, method=stats.PermutationMethod(), + alternative=alternative, axis=1) + res2 = stats.mannwhitneyu(x, y, method='exact', + alternative=alternative, axis=1) + assert_allclose(res.statistic, res2.statistic, rtol=1e-15) + assert_allclose(res.pvalue, res2.pvalue, rtol=1e-15) + + +class TestSomersD(_TestPythranFunc): + def setup_method(self): + self.dtypes = self.ALL_INTEGER + self.ALL_FLOAT + self.arguments = {0: (np.arange(10), + self.ALL_INTEGER + self.ALL_FLOAT), + 1: (np.arange(10), + self.ALL_INTEGER + self.ALL_FLOAT)} + input_array = [self.arguments[idx][0] for idx in self.arguments] + # In this case, self.partialfunc can simply be stats.somersd, + # since `alternative` is an optional argument. If it is required, + # we can use functools.partial to freeze the value, because + # we only mainly test various array inputs, not str, etc. + self.partialfunc = functools.partial(stats.somersd, + alternative='two-sided') + self.expected = self.partialfunc(*input_array) + + def pythranfunc(self, *args): + res = self.partialfunc(*args) + assert_allclose(res.statistic, self.expected.statistic, atol=1e-15) + assert_allclose(res.pvalue, self.expected.pvalue, atol=1e-15) + + def test_pythranfunc_keywords(self): + # Not specifying the optional keyword args + table = [[27, 25, 14, 7, 0], [7, 14, 18, 35, 12], [1, 3, 2, 7, 17]] + res1 = stats.somersd(table) + # Specifying the optional keyword args with default value + optional_args = self.get_optional_args(stats.somersd) + res2 = stats.somersd(table, **optional_args) + # Check if the results are the same in two cases + assert_allclose(res1.statistic, res2.statistic, atol=1e-15) + assert_allclose(res1.pvalue, res2.pvalue, atol=1e-15) + + def test_like_kendalltau(self): + # All tests correspond with one in test_stats.py `test_kendalltau` + + # case without ties, con-dis equal zero + x = [5, 2, 1, 3, 6, 4, 7, 8] + y = [5, 2, 6, 3, 1, 8, 7, 4] + # Cross-check with result from SAS FREQ: + expected = (0.000000000000000, 1.000000000000000) + res = stats.somersd(x, y) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # case without ties, con-dis equal zero + x = [0, 5, 2, 1, 3, 6, 4, 7, 8] + y = [5, 2, 0, 6, 3, 1, 8, 7, 4] + # Cross-check with result from SAS FREQ: + expected = (0.000000000000000, 1.000000000000000) + res = stats.somersd(x, y) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # case without ties, con-dis close to zero + x = [5, 2, 1, 3, 6, 4, 7] + y = [5, 2, 6, 3, 1, 7, 4] + # Cross-check with result from SAS FREQ: + expected = (-0.142857142857140, 0.630326953157670) + res = stats.somersd(x, y) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # simple case without ties + x = np.arange(10) + y = np.arange(10) + # Cross-check with result from SAS FREQ: + # SAS p value is not provided. + expected = (1.000000000000000, 0) + res = stats.somersd(x, y) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # swap a couple values and a couple more + x = np.arange(10) + y = np.array([0, 2, 1, 3, 4, 6, 5, 7, 8, 9]) + # Cross-check with result from SAS FREQ: + expected = (0.911111111111110, 0.000000000000000) + res = stats.somersd(x, y) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # same in opposite direction + x = np.arange(10) + y = np.arange(10)[::-1] + # Cross-check with result from SAS FREQ: + # SAS p value is not provided. + expected = (-1.000000000000000, 0) + res = stats.somersd(x, y) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # swap a couple values and a couple more + x = np.arange(10) + y = np.array([9, 7, 8, 6, 5, 3, 4, 2, 1, 0]) + # Cross-check with result from SAS FREQ: + expected = (-0.9111111111111111, 0.000000000000000) + res = stats.somersd(x, y) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # with some ties + x1 = [12, 2, 1, 12, 2] + x2 = [1, 4, 7, 1, 0] + # Cross-check with result from SAS FREQ: + expected = (-0.500000000000000, 0.304901788178780) + res = stats.somersd(x1, x2) + assert_allclose(res.statistic, expected[0], atol=1e-15) + assert_allclose(res.pvalue, expected[1], atol=1e-15) + + # with only ties in one or both inputs + # SAS will not produce an output for these: + # NOTE: No statistics are computed for x * y because x has fewer + # than 2 nonmissing levels. + # WARNING: No OUTPUT data set is produced for this table because a + # row or column variable has fewer than 2 nonmissing levels and no + # statistics are computed. + + res = stats.somersd([2, 2, 2], [2, 2, 2]) + assert_allclose(res.statistic, np.nan) + assert_allclose(res.pvalue, np.nan) + + res = stats.somersd([2, 0, 2], [2, 2, 2]) + assert_allclose(res.statistic, np.nan) + assert_allclose(res.pvalue, np.nan) + + res = stats.somersd([2, 2, 2], [2, 0, 2]) + assert_allclose(res.statistic, np.nan) + assert_allclose(res.pvalue, np.nan) + + res = stats.somersd([0], [0]) + assert_allclose(res.statistic, np.nan) + assert_allclose(res.pvalue, np.nan) + + # empty arrays provided as input + res = stats.somersd([], []) + assert_allclose(res.statistic, np.nan) + assert_allclose(res.pvalue, np.nan) + + # test unequal length inputs + x = np.arange(10.) + y = np.arange(20.) + assert_raises(ValueError, stats.somersd, x, y) + + def test_asymmetry(self): + # test that somersd is asymmetric w.r.t. input order and that + # convention is as described: first input is row variable & independent + # data is from Wikipedia: + # https://en.wikipedia.org/wiki/Somers%27_D + # but currently that example contradicts itself - it says X is + # independent yet take D_XY + + x = [1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 1, 2, + 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3] + y = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + # Cross-check with result from SAS FREQ: + d_cr = 0.272727272727270 + d_rc = 0.342857142857140 + p = 0.092891940883700 # same p-value for either direction + res = stats.somersd(x, y) + assert_allclose(res.statistic, d_cr, atol=1e-15) + assert_allclose(res.pvalue, p, atol=1e-4) + assert_equal(res.table.shape, (3, 2)) + res = stats.somersd(y, x) + assert_allclose(res.statistic, d_rc, atol=1e-15) + assert_allclose(res.pvalue, p, atol=1e-15) + assert_equal(res.table.shape, (2, 3)) + + def test_somers_original(self): + # test against Somers' original paper [1] + + # Table 5A + # Somers' convention was column IV + table = np.array([[8, 2], [6, 5], [3, 4], [1, 3], [2, 3]]) + # Our convention (and that of SAS FREQ) is row IV + table = table.T + dyx = 129/340 + assert_allclose(stats.somersd(table).statistic, dyx) + + # table 7A - d_yx = 1 + table = np.array([[25, 0], [85, 0], [0, 30]]) + dxy, dyx = 3300/5425, 3300/3300 + assert_allclose(stats.somersd(table).statistic, dxy) + assert_allclose(stats.somersd(table.T).statistic, dyx) + + # table 7B - d_yx < 0 + table = np.array([[25, 0], [0, 30], [85, 0]]) + dyx = -1800/3300 + assert_allclose(stats.somersd(table.T).statistic, dyx) + + def test_contingency_table_with_zero_rows_cols(self): + # test that zero rows/cols in contingency table don't affect result + + N = 100 + shape = 4, 6 + size = np.prod(shape) + + np.random.seed(0) + s = stats.multinomial.rvs(N, p=np.ones(size)/size).reshape(shape) + res = stats.somersd(s) + + s2 = np.insert(s, 2, np.zeros(shape[1]), axis=0) + res2 = stats.somersd(s2) + + s3 = np.insert(s, 2, np.zeros(shape[0]), axis=1) + res3 = stats.somersd(s3) + + s4 = np.insert(s2, 2, np.zeros(shape[0]+1), axis=1) + res4 = stats.somersd(s4) + + # Cross-check with result from SAS FREQ: + assert_allclose(res.statistic, -0.116981132075470, atol=1e-15) + assert_allclose(res.statistic, res2.statistic) + assert_allclose(res.statistic, res3.statistic) + assert_allclose(res.statistic, res4.statistic) + + assert_allclose(res.pvalue, 0.156376448188150, atol=1e-15) + assert_allclose(res.pvalue, res2.pvalue) + assert_allclose(res.pvalue, res3.pvalue) + assert_allclose(res.pvalue, res4.pvalue) + + def test_invalid_contingency_tables(self): + N = 100 + shape = 4, 6 + size = np.prod(shape) + + np.random.seed(0) + # start with a valid contingency table + s = stats.multinomial.rvs(N, p=np.ones(size)/size).reshape(shape) + + s5 = s - 2 + message = "All elements of the contingency table must be non-negative" + with assert_raises(ValueError, match=message): + stats.somersd(s5) + + s6 = s + 0.01 + message = "All elements of the contingency table must be integer" + with assert_raises(ValueError, match=message): + stats.somersd(s6) + + message = ("At least two elements of the contingency " + "table must be nonzero.") + with assert_raises(ValueError, match=message): + stats.somersd([[]]) + + with assert_raises(ValueError, match=message): + stats.somersd([[1]]) + + s7 = np.zeros((3, 3)) + with assert_raises(ValueError, match=message): + stats.somersd(s7) + + s7[0, 1] = 1 + with assert_raises(ValueError, match=message): + stats.somersd(s7) + + def test_only_ranks_matter(self): + # only ranks of input data should matter + x = [1, 2, 3] + x2 = [-1, 2.1, np.inf] + y = [3, 2, 1] + y2 = [0, -0.5, -np.inf] + res = stats.somersd(x, y) + res2 = stats.somersd(x2, y2) + assert_equal(res.statistic, res2.statistic) + assert_equal(res.pvalue, res2.pvalue) + + def test_contingency_table_return(self): + # check that contingency table is returned + x = np.arange(10) + y = np.arange(10) + res = stats.somersd(x, y) + assert_equal(res.table, np.eye(10)) + + def test_somersd_alternative(self): + # Test alternative parameter, asymptotic method (due to tie) + + # Based on scipy.stats.test_stats.TestCorrSpearman2::test_alternative + x1 = [1, 2, 3, 4, 5] + x2 = [5, 6, 7, 8, 7] + + # strong positive correlation + expected = stats.somersd(x1, x2, alternative="two-sided") + assert expected.statistic > 0 + + # rank correlation > 0 -> large "less" p-value + res = stats.somersd(x1, x2, alternative="less") + assert_equal(res.statistic, expected.statistic) + assert_allclose(res.pvalue, 1 - (expected.pvalue / 2)) + + # rank correlation > 0 -> small "greater" p-value + res = stats.somersd(x1, x2, alternative="greater") + assert_equal(res.statistic, expected.statistic) + assert_allclose(res.pvalue, expected.pvalue / 2) + + # reverse the direction of rank correlation + x2.reverse() + + # strong negative correlation + expected = stats.somersd(x1, x2, alternative="two-sided") + assert expected.statistic < 0 + + # rank correlation < 0 -> large "greater" p-value + res = stats.somersd(x1, x2, alternative="greater") + assert_equal(res.statistic, expected.statistic) + assert_allclose(res.pvalue, 1 - (expected.pvalue / 2)) + + # rank correlation < 0 -> small "less" p-value + res = stats.somersd(x1, x2, alternative="less") + assert_equal(res.statistic, expected.statistic) + assert_allclose(res.pvalue, expected.pvalue / 2) + + with pytest.raises(ValueError, match="`alternative` must be..."): + stats.somersd(x1, x2, alternative="ekki-ekki") + + @pytest.mark.parametrize("positive_correlation", (False, True)) + def test_somersd_perfect_correlation(self, positive_correlation): + # Before the addition of `alternative`, perfect correlation was + # treated as a special case. Now it is treated like any other case, but + # make sure there are no divide by zero warnings or associated errors + + x1 = np.arange(10) + x2 = x1 if positive_correlation else np.flip(x1) + expected_statistic = 1 if positive_correlation else -1 + + # perfect correlation -> small "two-sided" p-value (0) + res = stats.somersd(x1, x2, alternative="two-sided") + assert res.statistic == expected_statistic + assert res.pvalue == 0 + + # rank correlation > 0 -> large "less" p-value (1) + res = stats.somersd(x1, x2, alternative="less") + assert res.statistic == expected_statistic + assert res.pvalue == (1 if positive_correlation else 0) + + # rank correlation > 0 -> small "greater" p-value (0) + res = stats.somersd(x1, x2, alternative="greater") + assert res.statistic == expected_statistic + assert res.pvalue == (0 if positive_correlation else 1) + + def test_somersd_large_inputs_gh18132(self): + # Test that large inputs where potential overflows could occur give + # the expected output. This is tested in the case of binary inputs. + # See gh-18126. + + # generate lists of random classes 1-2 (binary) + classes = [1, 2] + n_samples = 10 ** 6 + random.seed(6272161) + x = random.choices(classes, k=n_samples) + y = random.choices(classes, k=n_samples) + + # get value to compare with: sklearn output + # from sklearn import metrics + # val_auc_sklearn = metrics.roc_auc_score(x, y) + # # convert to the Gini coefficient (Gini = (AUC*2)-1) + # val_sklearn = 2 * val_auc_sklearn - 1 + val_sklearn = -0.001528138777036947 + + # calculate the Somers' D statistic, which should be equal to the + # result of val_sklearn until approximately machine precision + val_scipy = stats.somersd(x, y).statistic + assert_allclose(val_sklearn, val_scipy, atol=1e-15) + + +class TestBarnardExact: + """Some tests to show that barnard_exact() works correctly.""" + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[43, 40], [10, 39]], (3.555406779643, 0.000362832367)), + ([[100, 2], [1000, 5]], (-1.776382925679, 0.135126970878)), + ([[2, 7], [8, 2]], (-2.518474945157, 0.019210815430)), + ([[5, 1], [10, 10]], (1.449486150679, 0.156277546306)), + ([[5, 15], [20, 20]], (-1.851640199545, 0.066363501421)), + ([[5, 16], [20, 25]], (-1.609639949352, 0.116984852192)), + ([[10, 5], [10, 1]], (-1.449486150679, 0.177536588915)), + ([[5, 0], [1, 4]], (2.581988897472, 0.013671875000)), + ([[0, 1], [3, 2]], (-1.095445115010, 0.509667991877)), + ([[0, 2], [6, 4]], (-1.549193338483, 0.197019618792)), + ([[2, 7], [8, 2]], (-2.518474945157, 0.019210815430)), + ], + ) + def test_precise(self, input_sample, expected): + """The expected values have been generated by R, using a resolution + for the nuisance parameter of 1e-6 : + ```R + library(Barnard) + options(digits=10) + barnard.test(43, 40, 10, 39, dp=1e-6, pooled=TRUE) + ``` + """ + res = barnard_exact(input_sample) + statistic, pvalue = res.statistic, res.pvalue + assert_allclose([statistic, pvalue], expected) + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[43, 40], [10, 39]], (3.920362887717, 0.000289470662)), + ([[100, 2], [1000, 5]], (-1.139432816087, 0.950272080594)), + ([[2, 7], [8, 2]], (-3.079373904042, 0.020172119141)), + ([[5, 1], [10, 10]], (1.622375939458, 0.150599922226)), + ([[5, 15], [20, 20]], (-1.974771239528, 0.063038448651)), + ([[5, 16], [20, 25]], (-1.722122973346, 0.133329494287)), + ([[10, 5], [10, 1]], (-1.765469659009, 0.250566655215)), + ([[5, 0], [1, 4]], (5.477225575052, 0.007812500000)), + ([[0, 1], [3, 2]], (-1.224744871392, 0.509667991877)), + ([[0, 2], [6, 4]], (-1.732050807569, 0.197019618792)), + ([[2, 7], [8, 2]], (-3.079373904042, 0.020172119141)), + ], + ) + def test_pooled_param(self, input_sample, expected): + """The expected values have been generated by R, using a resolution + for the nuisance parameter of 1e-6 : + ```R + library(Barnard) + options(digits=10) + barnard.test(43, 40, 10, 39, dp=1e-6, pooled=FALSE) + ``` + """ + res = barnard_exact(input_sample, pooled=False) + statistic, pvalue = res.statistic, res.pvalue + assert_allclose([statistic, pvalue], expected) + + def test_raises(self): + # test we raise an error for wrong input number of nuisances. + error_msg = ( + "Number of points `n` must be strictly positive, found 0" + ) + with assert_raises(ValueError, match=error_msg): + barnard_exact([[1, 2], [3, 4]], n=0) + + # test we raise an error for wrong shape of input. + error_msg = "The input `table` must be of shape \\(2, 2\\)." + with assert_raises(ValueError, match=error_msg): + barnard_exact(np.arange(6).reshape(2, 3)) + + # Test all values must be positives + error_msg = "All values in `table` must be nonnegative." + with assert_raises(ValueError, match=error_msg): + barnard_exact([[-1, 2], [3, 4]]) + + # Test value error on wrong alternative param + error_msg = ( + "`alternative` should be one of {'two-sided', 'less', 'greater'}," + " found .*" + ) + with assert_raises(ValueError, match=error_msg): + barnard_exact([[1, 2], [3, 4]], "not-correct") + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[0, 0], [4, 3]], (1.0, 0)), + ], + ) + def test_edge_cases(self, input_sample, expected): + res = barnard_exact(input_sample) + statistic, pvalue = res.statistic, res.pvalue + assert_equal(pvalue, expected[0]) + assert_equal(statistic, expected[1]) + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[0, 5], [0, 10]], (1.0, np.nan)), + ([[5, 0], [10, 0]], (1.0, np.nan)), + ], + ) + def test_row_or_col_zero(self, input_sample, expected): + res = barnard_exact(input_sample) + statistic, pvalue = res.statistic, res.pvalue + assert_equal(pvalue, expected[0]) + assert_equal(statistic, expected[1]) + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[2, 7], [8, 2]], (-2.518474945157, 0.009886140845)), + ([[7, 200], [300, 8]], (-21.320036698460, 0.0)), + ([[21, 28], [1957, 6]], (-30.489638143953, 0.0)), + ], + ) + @pytest.mark.parametrize("alternative", ["greater", "less"]) + def test_less_greater(self, input_sample, expected, alternative): + """ + "The expected values have been generated by R, using a resolution + for the nuisance parameter of 1e-6 : + ```R + library(Barnard) + options(digits=10) + a = barnard.test(2, 7, 8, 2, dp=1e-6, pooled=TRUE) + a$p.value[1] + ``` + In this test, we are using the "one-sided" return value `a$p.value[1]` + to test our pvalue. + """ + expected_stat, less_pvalue_expect = expected + + if alternative == "greater": + input_sample = np.array(input_sample)[:, ::-1] + expected_stat = -expected_stat + + res = barnard_exact(input_sample, alternative=alternative) + statistic, pvalue = res.statistic, res.pvalue + assert_allclose( + [statistic, pvalue], [expected_stat, less_pvalue_expect], atol=1e-7 + ) + + +class TestBoschlooExact: + """Some tests to show that boschloo_exact() works correctly.""" + + ATOL = 1e-7 + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[2, 7], [8, 2]], (0.01852173, 0.009886142)), + ([[5, 1], [10, 10]], (0.9782609, 0.9450994)), + ([[5, 16], [20, 25]], (0.08913823, 0.05827348)), + ([[10, 5], [10, 1]], (0.1652174, 0.08565611)), + ([[5, 0], [1, 4]], (1, 1)), + ([[0, 1], [3, 2]], (0.5, 0.34375)), + ([[2, 7], [8, 2]], (0.01852173, 0.009886142)), + ([[7, 12], [8, 3]], (0.06406797, 0.03410916)), + ([[10, 24], [25, 37]], (0.2009359, 0.1512882)), + ], + ) + def test_less(self, input_sample, expected): + """The expected values have been generated by R, using a resolution + for the nuisance parameter of 1e-8 : + ```R + library(Exact) + options(digits=10) + data <- matrix(c(43, 10, 40, 39), 2, 2, byrow=TRUE) + a = exact.test(data, method="Boschloo", alternative="less", + tsmethod="central", np.interval=TRUE, beta=1e-8) + ``` + """ + res = boschloo_exact(input_sample, alternative="less") + statistic, pvalue = res.statistic, res.pvalue + assert_allclose([statistic, pvalue], expected, atol=self.ATOL) + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[43, 40], [10, 39]], (0.0002875544, 0.0001615562)), + ([[2, 7], [8, 2]], (0.9990149, 0.9918327)), + ([[5, 1], [10, 10]], (0.1652174, 0.09008534)), + ([[5, 15], [20, 20]], (0.9849087, 0.9706997)), + ([[5, 16], [20, 25]], (0.972349, 0.9524124)), + ([[5, 0], [1, 4]], (0.02380952, 0.006865367)), + ([[0, 1], [3, 2]], (1, 1)), + ([[0, 2], [6, 4]], (1, 1)), + ([[2, 7], [8, 2]], (0.9990149, 0.9918327)), + ([[7, 12], [8, 3]], (0.9895302, 0.9771215)), + ([[10, 24], [25, 37]], (0.9012936, 0.8633275)), + ], + ) + def test_greater(self, input_sample, expected): + """The expected values have been generated by R, using a resolution + for the nuisance parameter of 1e-8 : + ```R + library(Exact) + options(digits=10) + data <- matrix(c(43, 10, 40, 39), 2, 2, byrow=TRUE) + a = exact.test(data, method="Boschloo", alternative="greater", + tsmethod="central", np.interval=TRUE, beta=1e-8) + ``` + """ + res = boschloo_exact(input_sample, alternative="greater") + statistic, pvalue = res.statistic, res.pvalue + assert_allclose([statistic, pvalue], expected, atol=self.ATOL) + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[43, 40], [10, 39]], (0.0002875544, 0.0003231115)), + ([[2, 7], [8, 2]], (0.01852173, 0.01977228)), + ([[5, 1], [10, 10]], (0.1652174, 0.1801707)), + ([[5, 16], [20, 25]], (0.08913823, 0.116547)), + ([[5, 0], [1, 4]], (0.02380952, 0.01373073)), + ([[0, 1], [3, 2]], (0.5, 0.6875)), + ([[2, 7], [8, 2]], (0.01852173, 0.01977228)), + ([[7, 12], [8, 3]], (0.06406797, 0.06821831)), + ], + ) + def test_two_sided(self, input_sample, expected): + """The expected values have been generated by R, using a resolution + for the nuisance parameter of 1e-8 : + ```R + library(Exact) + options(digits=10) + data <- matrix(c(43, 10, 40, 39), 2, 2, byrow=TRUE) + a = exact.test(data, method="Boschloo", alternative="two.sided", + tsmethod="central", np.interval=TRUE, beta=1e-8) + ``` + """ + res = boschloo_exact(input_sample, alternative="two-sided", n=64) + # Need n = 64 for python 32-bit + statistic, pvalue = res.statistic, res.pvalue + assert_allclose([statistic, pvalue], expected, atol=self.ATOL) + + def test_raises(self): + # test we raise an error for wrong input number of nuisances. + error_msg = ( + "Number of points `n` must be strictly positive, found 0" + ) + with assert_raises(ValueError, match=error_msg): + boschloo_exact([[1, 2], [3, 4]], n=0) + + # test we raise an error for wrong shape of input. + error_msg = "The input `table` must be of shape \\(2, 2\\)." + with assert_raises(ValueError, match=error_msg): + boschloo_exact(np.arange(6).reshape(2, 3)) + + # Test all values must be positives + error_msg = "All values in `table` must be nonnegative." + with assert_raises(ValueError, match=error_msg): + boschloo_exact([[-1, 2], [3, 4]]) + + # Test value error on wrong alternative param + error_msg = ( + r"`alternative` should be one of \('two-sided', 'less', " + r"'greater'\), found .*" + ) + with assert_raises(ValueError, match=error_msg): + boschloo_exact([[1, 2], [3, 4]], "not-correct") + + @pytest.mark.parametrize( + "input_sample,expected", + [ + ([[0, 5], [0, 10]], (np.nan, np.nan)), + ([[5, 0], [10, 0]], (np.nan, np.nan)), + ], + ) + def test_row_or_col_zero(self, input_sample, expected): + res = boschloo_exact(input_sample) + statistic, pvalue = res.statistic, res.pvalue + assert_equal(pvalue, expected[0]) + assert_equal(statistic, expected[1]) + + def test_two_sided_gt_1(self): + # Check that returned p-value does not exceed 1 even when twice + # the minimum of the one-sided p-values does. See gh-15345. + tbl = [[1, 1], [13, 12]] + pl = boschloo_exact(tbl, alternative='less').pvalue + pg = boschloo_exact(tbl, alternative='greater').pvalue + assert 2*min(pl, pg) > 1 + pt = boschloo_exact(tbl, alternative='two-sided').pvalue + assert pt == 1.0 + + @pytest.mark.parametrize("alternative", ("less", "greater")) + def test_against_fisher_exact(self, alternative): + # Check that the statistic of `boschloo_exact` is the same as the + # p-value of `fisher_exact` (for one-sided tests). See gh-15345. + tbl = [[2, 7], [8, 2]] + boschloo_stat = boschloo_exact(tbl, alternative=alternative).statistic + fisher_p = stats.fisher_exact(tbl, alternative=alternative)[1] + assert_allclose(boschloo_stat, fisher_p) + + +class TestCvm_2samp: + @pytest.mark.parametrize('args', [([], np.arange(5)), + (np.arange(5), [1])]) + def test_too_small_input(self, args): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = cramervonmises_2samp(*args) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_invalid_input(self): + y = np.arange(5) + msg = 'method must be either auto, exact or asymptotic' + with pytest.raises(ValueError, match=msg): + cramervonmises_2samp(y, y, 'xyz') + + def test_list_input(self): + x = [2, 3, 4, 7, 6] + y = [0.2, 0.7, 12, 18] + r1 = cramervonmises_2samp(x, y) + r2 = cramervonmises_2samp(np.array(x), np.array(y)) + assert_equal((r1.statistic, r1.pvalue), (r2.statistic, r2.pvalue)) + + def test_example_conover(self): + # Example 2 in Section 6.2 of W.J. Conover: Practical Nonparametric + # Statistics, 1971. + x = [7.6, 8.4, 8.6, 8.7, 9.3, 9.9, 10.1, 10.6, 11.2] + y = [5.2, 5.7, 5.9, 6.5, 6.8, 8.2, 9.1, 9.8, 10.8, 11.3, 11.5, 12.3, + 12.5, 13.4, 14.6] + r = cramervonmises_2samp(x, y) + assert_allclose(r.statistic, 0.262, atol=1e-3) + assert_allclose(r.pvalue, 0.18, atol=1e-2) + + @pytest.mark.parametrize('statistic, m, n, pval', + [(710, 5, 6, 48./462), + (1897, 7, 7, 117./1716), + (576, 4, 6, 2./210), + (1764, 6, 7, 2./1716)]) + def test_exact_pvalue(self, statistic, m, n, pval): + # the exact values are taken from Anderson: On the distribution of the + # two-sample Cramer-von-Mises criterion, 1962. + # The values are taken from Table 2, 3, 4 and 5 + assert_equal(_pval_cvm_2samp_exact(statistic, m, n), pval) + + @pytest.mark.xslow + def test_large_sample(self): + # for large samples, the statistic U gets very large + # do a sanity check that p-value is not 0, 1 or nan + np.random.seed(4367) + x = distributions.norm.rvs(size=1000000) + y = distributions.norm.rvs(size=900000) + r = cramervonmises_2samp(x, y) + assert_(0 < r.pvalue < 1) + r = cramervonmises_2samp(x, y+0.1) + assert_(0 < r.pvalue < 1) + + def test_exact_vs_asymptotic(self): + np.random.seed(0) + x = np.random.rand(7) + y = np.random.rand(8) + r1 = cramervonmises_2samp(x, y, method='exact') + r2 = cramervonmises_2samp(x, y, method='asymptotic') + assert_equal(r1.statistic, r2.statistic) + assert_allclose(r1.pvalue, r2.pvalue, atol=1e-2) + + def test_method_auto(self): + x = np.arange(20) + y = [0.5, 4.7, 13.1] + r1 = cramervonmises_2samp(x, y, method='exact') + r2 = cramervonmises_2samp(x, y, method='auto') + assert_equal(r1.pvalue, r2.pvalue) + # switch to asymptotic if one sample has more than 20 observations + x = np.arange(21) + r1 = cramervonmises_2samp(x, y, method='asymptotic') + r2 = cramervonmises_2samp(x, y, method='auto') + assert_equal(r1.pvalue, r2.pvalue) + + def test_same_input(self): + # make sure trivial edge case can be handled + # note that _cdf_cvm_inf(0) = nan. implementation avoids nan by + # returning pvalue=1 for very small values of the statistic + x = np.arange(15) + res = cramervonmises_2samp(x, x) + assert_equal((res.statistic, res.pvalue), (0.0, 1.0)) + # check exact p-value + res = cramervonmises_2samp(x[:4], x[:4]) + assert_equal((res.statistic, res.pvalue), (0.0, 1.0)) + + +class TestTukeyHSD: + + data_same_size = ([24.5, 23.5, 26.4, 27.1, 29.9], + [28.4, 34.2, 29.5, 32.2, 30.1], + [26.1, 28.3, 24.3, 26.2, 27.8]) + data_diff_size = ([24.5, 23.5, 26.28, 26.4, 27.1, 29.9, 30.1, 30.1], + [28.4, 34.2, 29.5, 32.2, 30.1], + [26.1, 28.3, 24.3, 26.2, 27.8]) + extreme_size = ([24.5, 23.5, 26.4], + [28.4, 34.2, 29.5, 32.2, 30.1, 28.4, 34.2, 29.5, 32.2, + 30.1], + [26.1, 28.3, 24.3, 26.2, 27.8]) + + sas_same_size = """ + Comparison LowerCL Difference UpperCL Significance + 2 - 3 0.6908830568 4.34 7.989116943 1 + 2 - 1 0.9508830568 4.6 8.249116943 1 + 3 - 2 -7.989116943 -4.34 -0.6908830568 1 + 3 - 1 -3.389116943 0.26 3.909116943 0 + 1 - 2 -8.249116943 -4.6 -0.9508830568 1 + 1 - 3 -3.909116943 -0.26 3.389116943 0 + """ + + sas_diff_size = """ + Comparison LowerCL Difference UpperCL Significance + 2 - 1 0.2679292645 3.645 7.022070736 1 + 2 - 3 0.5934764007 4.34 8.086523599 1 + 1 - 2 -7.022070736 -3.645 -0.2679292645 1 + 1 - 3 -2.682070736 0.695 4.072070736 0 + 3 - 2 -8.086523599 -4.34 -0.5934764007 1 + 3 - 1 -4.072070736 -0.695 2.682070736 0 + """ + + sas_extreme = """ + Comparison LowerCL Difference UpperCL Significance + 2 - 3 1.561605075 4.34 7.118394925 1 + 2 - 1 2.740784879 6.08 9.419215121 1 + 3 - 2 -7.118394925 -4.34 -1.561605075 1 + 3 - 1 -1.964526566 1.74 5.444526566 0 + 1 - 2 -9.419215121 -6.08 -2.740784879 1 + 1 - 3 -5.444526566 -1.74 1.964526566 0 + """ + + @pytest.mark.parametrize("data,res_expect_str,atol", + ((data_same_size, sas_same_size, 1e-4), + (data_diff_size, sas_diff_size, 1e-4), + (extreme_size, sas_extreme, 1e-10), + ), + ids=["equal size sample", + "unequal sample size", + "extreme sample size differences"]) + def test_compare_sas(self, data, res_expect_str, atol): + ''' + SAS code used to generate results for each sample: + DATA ACHE; + INPUT BRAND RELIEF; + CARDS; + 1 24.5 + ... + 3 27.8 + ; + ods graphics on; ODS RTF;ODS LISTING CLOSE; + PROC ANOVA DATA=ACHE; + CLASS BRAND; + MODEL RELIEF=BRAND; + MEANS BRAND/TUKEY CLDIFF; + TITLE 'COMPARE RELIEF ACROSS MEDICINES - ANOVA EXAMPLE'; + ods output CLDiffs =tc; + proc print data=tc; + format LowerCL 17.16 UpperCL 17.16 Difference 17.16; + title "Output with many digits"; + RUN; + QUIT; + ODS RTF close; + ODS LISTING; + ''' + res_expect = np.asarray(res_expect_str.replace(" - ", " ").split()[5:], + dtype=float).reshape((6, 6)) + res_tukey = stats.tukey_hsd(*data) + conf = res_tukey.confidence_interval() + # loop over the comparisons + for i, j, l, s, h, sig in res_expect: + i, j = int(i) - 1, int(j) - 1 + assert_allclose(conf.low[i, j], l, atol=atol) + assert_allclose(res_tukey.statistic[i, j], s, atol=atol) + assert_allclose(conf.high[i, j], h, atol=atol) + assert_allclose((res_tukey.pvalue[i, j] <= .05), sig == 1) + + matlab_sm_siz = """ + 1 2 -8.2491590248597 -4.6 -0.9508409751403 0.0144483269098 + 1 3 -3.9091590248597 -0.26 3.3891590248597 0.9803107240900 + 2 3 0.6908409751403 4.34 7.9891590248597 0.0203311368795 + """ + + matlab_diff_sz = """ + 1 2 -7.02207069748501 -3.645 -0.26792930251500 0.03371498443080 + 1 3 -2.68207069748500 0.695 4.07207069748500 0.85572267328807 + 2 3 0.59347644287720 4.34 8.08652355712281 0.02259047020620 + """ + + @pytest.mark.parametrize("data,res_expect_str,atol", + ((data_same_size, matlab_sm_siz, 1e-12), + (data_diff_size, matlab_diff_sz, 1e-7)), + ids=["equal size sample", + "unequal size sample"]) + def test_compare_matlab(self, data, res_expect_str, atol): + """ + vals = [24.5, 23.5, 26.4, 27.1, 29.9, 28.4, 34.2, 29.5, 32.2, 30.1, + 26.1, 28.3, 24.3, 26.2, 27.8] + names = {'zero', 'zero', 'zero', 'zero', 'zero', 'one', 'one', 'one', + 'one', 'one', 'two', 'two', 'two', 'two', 'two'} + [p,t,stats] = anova1(vals,names,"off"); + [c,m,h,nms] = multcompare(stats, "CType","hsd"); + """ + res_expect = np.asarray(res_expect_str.split(), + dtype=float).reshape((3, 6)) + res_tukey = stats.tukey_hsd(*data) + conf = res_tukey.confidence_interval() + # loop over the comparisons + for i, j, l, s, h, p in res_expect: + i, j = int(i) - 1, int(j) - 1 + assert_allclose(conf.low[i, j], l, atol=atol) + assert_allclose(res_tukey.statistic[i, j], s, atol=atol) + assert_allclose(conf.high[i, j], h, atol=atol) + assert_allclose(res_tukey.pvalue[i, j], p, atol=atol) + + def test_compare_r(self): + """ + Testing against results and p-values from R: + from: https://www.rdocumentation.org/packages/stats/versions/3.6.2/ + topics/TukeyHSD + > require(graphics) + > summary(fm1 <- aov(breaks ~ tension, data = warpbreaks)) + > TukeyHSD(fm1, "tension", ordered = TRUE) + > plot(TukeyHSD(fm1, "tension")) + Tukey multiple comparisons of means + 95% family-wise confidence level + factor levels have been ordered + Fit: aov(formula = breaks ~ tension, data = warpbreaks) + $tension + """ + str_res = """ + diff lwr upr p adj + 2 - 3 4.722222 -4.8376022 14.28205 0.4630831 + 1 - 3 14.722222 5.1623978 24.28205 0.0014315 + 1 - 2 10.000000 0.4401756 19.55982 0.0384598 + """ + res_expect = np.asarray(str_res.replace(" - ", " ").split()[5:], + dtype=float).reshape((3, 6)) + data = ([26, 30, 54, 25, 70, 52, 51, 26, 67, + 27, 14, 29, 19, 29, 31, 41, 20, 44], + [18, 21, 29, 17, 12, 18, 35, 30, 36, + 42, 26, 19, 16, 39, 28, 21, 39, 29], + [36, 21, 24, 18, 10, 43, 28, 15, 26, + 20, 21, 24, 17, 13, 15, 15, 16, 28]) + + res_tukey = stats.tukey_hsd(*data) + conf = res_tukey.confidence_interval() + # loop over the comparisons + for i, j, s, l, h, p in res_expect: + i, j = int(i) - 1, int(j) - 1 + # atols are set to the number of digits present in the r result. + assert_allclose(conf.low[i, j], l, atol=1e-7) + assert_allclose(res_tukey.statistic[i, j], s, atol=1e-6) + assert_allclose(conf.high[i, j], h, atol=1e-5) + assert_allclose(res_tukey.pvalue[i, j], p, atol=1e-7) + + def test_engineering_stat_handbook(self): + ''' + Example sourced from: + https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm + ''' + group1 = [6.9, 5.4, 5.8, 4.6, 4.0] + group2 = [8.3, 6.8, 7.8, 9.2, 6.5] + group3 = [8.0, 10.5, 8.1, 6.9, 9.3] + group4 = [5.8, 3.8, 6.1, 5.6, 6.2] + res = stats.tukey_hsd(group1, group2, group3, group4) + conf = res.confidence_interval() + lower = np.asarray([ + [0, 0, 0, -2.25], + [.29, 0, -2.93, .13], + [1.13, 0, 0, .97], + [0, 0, 0, 0]]) + upper = np.asarray([ + [0, 0, 0, 1.93], + [4.47, 0, 1.25, 4.31], + [5.31, 0, 0, 5.15], + [0, 0, 0, 0]]) + + for (i, j) in [(1, 0), (2, 0), (0, 3), (1, 2), (2, 3)]: + assert_allclose(conf.low[i, j], lower[i, j], atol=1e-2) + assert_allclose(conf.high[i, j], upper[i, j], atol=1e-2) + + def test_rand_symm(self): + # test some expected identities of the results + np.random.seed(1234) + data = np.random.rand(3, 100) + res = stats.tukey_hsd(*data) + conf = res.confidence_interval() + # the confidence intervals should be negated symmetric of each other + assert_equal(conf.low, -conf.high.T) + # the `high` and `low` center diagonals should be the same since the + # mean difference in a self comparison is 0. + assert_equal(np.diagonal(conf.high), conf.high[0, 0]) + assert_equal(np.diagonal(conf.low), conf.low[0, 0]) + # statistic array should be antisymmetric with zeros on the diagonal + assert_equal(res.statistic, -res.statistic.T) + assert_equal(np.diagonal(res.statistic), 0) + # p-values should be symmetric and 1 when compared to itself + assert_equal(res.pvalue, res.pvalue.T) + assert_equal(np.diagonal(res.pvalue), 1) + + def test_no_inf(self): + with assert_raises(ValueError, match="...must be finite."): + stats.tukey_hsd([1, 2, 3], [2, np.inf], [6, 7, 3]) + + def test_is_1d(self): + with assert_raises(ValueError, match="...must be one-dimensional"): + stats.tukey_hsd([[1, 2], [2, 3]], [2, 5], [5, 23, 6]) + + def test_no_empty(self): + with assert_raises(ValueError, match="...must be greater than one"): + stats.tukey_hsd([], [2, 5], [4, 5, 6]) + + @pytest.mark.parametrize("nargs", (0, 1)) + def test_not_enough_treatments(self, nargs): + with assert_raises(ValueError, match="...more than 1 treatment."): + stats.tukey_hsd(*([[23, 7, 3]] * nargs)) + + @pytest.mark.parametrize("cl", [-.5, 0, 1, 2]) + def test_conf_level_invalid(self, cl): + with assert_raises(ValueError, match="must be between 0 and 1"): + r = stats.tukey_hsd([23, 7, 3], [3, 4], [9, 4]) + r.confidence_interval(cl) + + def test_2_args_ttest(self): + # that with 2 treatments the `pvalue` is equal to that of `ttest_ind` + res_tukey = stats.tukey_hsd(*self.data_diff_size[:2]) + res_ttest = stats.ttest_ind(*self.data_diff_size[:2]) + assert_allclose(res_ttest.pvalue, res_tukey.pvalue[0, 1]) + assert_allclose(res_ttest.pvalue, res_tukey.pvalue[1, 0]) + + +class TestPoissonMeansTest: + @pytest.mark.parametrize("c1, n1, c2, n2, p_expect", ( + # example from [1], 6. Illustrative examples: Example 1 + [0, 100, 3, 100, 0.0884], + [2, 100, 6, 100, 0.1749] + )) + def test_paper_examples(self, c1, n1, c2, n2, p_expect): + res = stats.poisson_means_test(c1, n1, c2, n2) + assert_allclose(res.pvalue, p_expect, atol=1e-4) + + @pytest.mark.parametrize("c1, n1, c2, n2, p_expect, alt, d", ( + # These test cases are produced by the wrapped fortran code from the + # original authors. Using a slightly modified version of this fortran, + # found here, https://github.com/nolanbconaway/poisson-etest, + # additional tests were created. + [20, 10, 20, 10, 0.9999997568929630, 'two-sided', 0], + [10, 10, 10, 10, 0.9999998403241203, 'two-sided', 0], + [50, 15, 1, 1, 0.09920321053409643, 'two-sided', .05], + [3, 100, 20, 300, 0.12202725450896404, 'two-sided', 0], + [3, 12, 4, 20, 0.40416087318539173, 'greater', 0], + [4, 20, 3, 100, 0.008053640402974236, 'greater', 0], + # publishing paper does not include a `less` alternative, + # so it was calculated with switched argument order and + # alternative="greater" + [4, 20, 3, 10, 0.3083216325432898, 'less', 0], + [1, 1, 50, 15, 0.09322998607245102, 'less', 0] + )) + def test_fortran_authors(self, c1, n1, c2, n2, p_expect, alt, d): + res = stats.poisson_means_test(c1, n1, c2, n2, alternative=alt, diff=d) + assert_allclose(res.pvalue, p_expect, atol=2e-6, rtol=1e-16) + + def test_different_results(self): + # The implementation in Fortran is known to break down at higher + # counts and observations, so we expect different results. By + # inspection we can infer the p-value to be near one. + count1, count2 = 10000, 10000 + nobs1, nobs2 = 10000, 10000 + res = stats.poisson_means_test(count1, nobs1, count2, nobs2) + assert_allclose(res.pvalue, 1) + + def test_less_than_zero_lambda_hat2(self): + # demonstrates behavior that fixes a known fault from original Fortran. + # p-value should clearly be near one. + count1, count2 = 0, 0 + nobs1, nobs2 = 1, 1 + res = stats.poisson_means_test(count1, nobs1, count2, nobs2) + assert_allclose(res.pvalue, 1) + + def test_input_validation(self): + count1, count2 = 0, 0 + nobs1, nobs2 = 1, 1 + + # test non-integral events + message = '`k1` and `k2` must be integers.' + with assert_raises(TypeError, match=message): + stats.poisson_means_test(.7, nobs1, count2, nobs2) + with assert_raises(TypeError, match=message): + stats.poisson_means_test(count1, nobs1, .7, nobs2) + + # test negative events + message = '`k1` and `k2` must be greater than or equal to 0.' + with assert_raises(ValueError, match=message): + stats.poisson_means_test(-1, nobs1, count2, nobs2) + with assert_raises(ValueError, match=message): + stats.poisson_means_test(count1, nobs1, -1, nobs2) + + # test negative sample size + message = '`n1` and `n2` must be greater than 0.' + with assert_raises(ValueError, match=message): + stats.poisson_means_test(count1, -1, count2, nobs2) + with assert_raises(ValueError, match=message): + stats.poisson_means_test(count1, nobs1, count2, -1) + + # test negative difference + message = 'diff must be greater than or equal to 0.' + with assert_raises(ValueError, match=message): + stats.poisson_means_test(count1, nobs1, count2, nobs2, diff=-1) + + # test invalid alternative + message = 'Alternative must be one of ...' + with assert_raises(ValueError, match=message): + stats.poisson_means_test(1, 2, 1, 2, alternative='error') + + +class TestBWSTest: + + def test_bws_input_validation(self): + rng = np.random.default_rng(4571775098104213308) + + x, y = rng.random(size=(2, 7)) + + message = '`x` and `y` must be exactly one-dimensional.' + with pytest.raises(ValueError, match=message): + stats.bws_test([x, x], [y, y]) + + message = '`x` and `y` must not contain NaNs.' + with pytest.raises(ValueError, match=message): + stats.bws_test([np.nan], y) + + message = '`x` and `y` must be of nonzero size.' + with pytest.raises(ValueError, match=message): + stats.bws_test(x, []) + + message = 'alternative` must be one of...' + with pytest.raises(ValueError, match=message): + stats.bws_test(x, y, alternative='ekki-ekki') + + message = 'method` must be an instance of...' + with pytest.raises(ValueError, match=message): + stats.bws_test(x, y, method=42) + + + def test_against_published_reference(self): + # Test against Example 2 in bws_test Reference [1], pg 9 + # https://link.springer.com/content/pdf/10.1007/BF02762032.pdf + x = [1, 2, 3, 4, 6, 7, 8] + y = [5, 9, 10, 11, 12, 13, 14] + res = stats.bws_test(x, y, alternative='two-sided') + assert_allclose(res.statistic, 5.132, atol=1e-3) + assert_equal(res.pvalue, 10/3432) + + + @pytest.mark.parametrize(('alternative', 'statistic', 'pvalue'), + [('two-sided', 1.7510204081633, 0.1264422777777), + ('less', -1.7510204081633, 0.05754662004662), + ('greater', -1.7510204081633, 0.9424533799534)]) + def test_against_R(self, alternative, statistic, pvalue): + # Test against R library BWStest function bws_test + # library(BWStest) + # options(digits=16) + # x = c(...) + # y = c(...) + # bws_test(x, y, alternative='two.sided') + rng = np.random.default_rng(4571775098104213308) + x, y = rng.random(size=(2, 7)) + res = stats.bws_test(x, y, alternative=alternative) + assert_allclose(res.statistic, statistic, rtol=1e-13) + assert_allclose(res.pvalue, pvalue, atol=1e-2, rtol=1e-1) + + @pytest.mark.parametrize(('alternative', 'statistic', 'pvalue'), + [('two-sided', 1.142629265891, 0.2903950180801), + ('less', 0.99629665877411, 0.8545660222131), + ('greater', 0.99629665877411, 0.1454339777869)]) + def test_against_R_imbalanced(self, alternative, statistic, pvalue): + # Test against R library BWStest function bws_test + # library(BWStest) + # options(digits=16) + # x = c(...) + # y = c(...) + # bws_test(x, y, alternative='two.sided') + rng = np.random.default_rng(5429015622386364034) + x = rng.random(size=9) + y = rng.random(size=8) + res = stats.bws_test(x, y, alternative=alternative) + assert_allclose(res.statistic, statistic, rtol=1e-13) + assert_allclose(res.pvalue, pvalue, atol=1e-2, rtol=1e-1) + + def test_method(self): + # Test that `method` parameter has the desired effect + rng = np.random.default_rng(1520514347193347862) + x, y = rng.random(size=(2, 10)) + + rng = np.random.default_rng(1520514347193347862) + method = stats.PermutationMethod(n_resamples=10, rng=rng) + res1 = stats.bws_test(x, y, method=method) + + assert len(res1.null_distribution) == 10 + + rng = np.random.default_rng(1520514347193347862) + method = stats.PermutationMethod(n_resamples=10, rng=rng) + res2 = stats.bws_test(x, y, method=method) + + assert_allclose(res1.null_distribution, res2.null_distribution) + + rng = np.random.default_rng(5205143471933478621) + method = stats.PermutationMethod(n_resamples=10, rng=rng) + res3 = stats.bws_test(x, y, method=method) + + assert not np.allclose(res3.null_distribution, res1.null_distribution) + + def test_directions(self): + # Sanity check of the sign of the one-sided statistic + rng = np.random.default_rng(1520514347193347862) + x = rng.random(size=5) + y = x - 1 + + res = stats.bws_test(x, y, alternative='greater') + assert res.statistic > 0 + assert_equal(res.pvalue, 1 / len(res.null_distribution)) + + res = stats.bws_test(x, y, alternative='less') + assert res.statistic > 0 + assert_equal(res.pvalue, 1) + + res = stats.bws_test(y, x, alternative='less') + assert res.statistic < 0 + assert_equal(res.pvalue, 1 / len(res.null_distribution)) + + res = stats.bws_test(y, x, alternative='greater') + assert res.statistic < 0 + assert_equal(res.pvalue, 1) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_kdeoth.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_kdeoth.py new file mode 100644 index 0000000000000000000000000000000000000000..01aae391dcee1e43e9a51a72e9d6b642b7a24da8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_kdeoth.py @@ -0,0 +1,608 @@ +from scipy import stats, linalg, integrate +import numpy as np +from numpy.testing import (assert_almost_equal, assert_, assert_equal, + assert_array_almost_equal, + assert_array_almost_equal_nulp, assert_allclose) +import pytest +from pytest import raises as assert_raises + + +def test_kde_1d(): + #some basic tests comparing to normal distribution + np.random.seed(8765678) + n_basesample = 500 + xn = np.random.randn(n_basesample) + xnmean = xn.mean() + xnstd = xn.std(ddof=1) + + # get kde for original sample + gkde = stats.gaussian_kde(xn) + + # evaluate the density function for the kde for some points + xs = np.linspace(-7,7,501) + kdepdf = gkde.evaluate(xs) + normpdf = stats.norm.pdf(xs, loc=xnmean, scale=xnstd) + intervall = xs[1] - xs[0] + + assert_(np.sum((kdepdf - normpdf)**2)*intervall < 0.01) + prob1 = gkde.integrate_box_1d(xnmean, np.inf) + prob2 = gkde.integrate_box_1d(-np.inf, xnmean) + assert_almost_equal(prob1, 0.5, decimal=1) + assert_almost_equal(prob2, 0.5, decimal=1) + assert_almost_equal(gkde.integrate_box(xnmean, np.inf), prob1, decimal=13) + assert_almost_equal(gkde.integrate_box(-np.inf, xnmean), prob2, decimal=13) + + assert_almost_equal(gkde.integrate_kde(gkde), + (kdepdf**2).sum()*intervall, decimal=2) + assert_almost_equal(gkde.integrate_gaussian(xnmean, xnstd**2), + (kdepdf*normpdf).sum()*intervall, decimal=2) + + +def test_kde_1d_weighted(): + #some basic tests comparing to normal distribution + np.random.seed(8765678) + n_basesample = 500 + xn = np.random.randn(n_basesample) + wn = np.random.rand(n_basesample) + xnmean = np.average(xn, weights=wn) + xnstd = np.sqrt(np.average((xn-xnmean)**2, weights=wn)) + + # get kde for original sample + gkde = stats.gaussian_kde(xn, weights=wn) + + # evaluate the density function for the kde for some points + xs = np.linspace(-7,7,501) + kdepdf = gkde.evaluate(xs) + normpdf = stats.norm.pdf(xs, loc=xnmean, scale=xnstd) + intervall = xs[1] - xs[0] + + assert_(np.sum((kdepdf - normpdf)**2)*intervall < 0.01) + prob1 = gkde.integrate_box_1d(xnmean, np.inf) + prob2 = gkde.integrate_box_1d(-np.inf, xnmean) + assert_almost_equal(prob1, 0.5, decimal=1) + assert_almost_equal(prob2, 0.5, decimal=1) + assert_almost_equal(gkde.integrate_box(xnmean, np.inf), prob1, decimal=13) + assert_almost_equal(gkde.integrate_box(-np.inf, xnmean), prob2, decimal=13) + + assert_almost_equal(gkde.integrate_kde(gkde), + (kdepdf**2).sum()*intervall, decimal=2) + assert_almost_equal(gkde.integrate_gaussian(xnmean, xnstd**2), + (kdepdf*normpdf).sum()*intervall, decimal=2) + + +@pytest.mark.xslow +def test_kde_2d(): + #some basic tests comparing to normal distribution + np.random.seed(8765678) + n_basesample = 500 + + mean = np.array([1.0, 3.0]) + covariance = np.array([[1.0, 2.0], [2.0, 6.0]]) + + # Need transpose (shape (2, 500)) for kde + xn = np.random.multivariate_normal(mean, covariance, size=n_basesample).T + + # get kde for original sample + gkde = stats.gaussian_kde(xn) + + # evaluate the density function for the kde for some points + x, y = np.mgrid[-7:7:500j, -7:7:500j] + grid_coords = np.vstack([x.ravel(), y.ravel()]) + kdepdf = gkde.evaluate(grid_coords) + kdepdf = kdepdf.reshape(500, 500) + + normpdf = stats.multivariate_normal.pdf(np.dstack([x, y]), + mean=mean, cov=covariance) + intervall = y.ravel()[1] - y.ravel()[0] + + assert_(np.sum((kdepdf - normpdf)**2) * (intervall**2) < 0.01) + + small = -1e100 + large = 1e100 + prob1 = gkde.integrate_box([small, mean[1]], [large, large]) + prob2 = gkde.integrate_box([small, small], [large, mean[1]]) + + assert_almost_equal(prob1, 0.5, decimal=1) + assert_almost_equal(prob2, 0.5, decimal=1) + assert_almost_equal(gkde.integrate_kde(gkde), + (kdepdf**2).sum()*(intervall**2), decimal=2) + assert_almost_equal(gkde.integrate_gaussian(mean, covariance), + (kdepdf*normpdf).sum()*(intervall**2), decimal=2) + + +@pytest.mark.xslow +def test_kde_2d_weighted(): + #some basic tests comparing to normal distribution + np.random.seed(8765678) + n_basesample = 500 + + mean = np.array([1.0, 3.0]) + covariance = np.array([[1.0, 2.0], [2.0, 6.0]]) + + # Need transpose (shape (2, 500)) for kde + xn = np.random.multivariate_normal(mean, covariance, size=n_basesample).T + wn = np.random.rand(n_basesample) + + # get kde for original sample + gkde = stats.gaussian_kde(xn, weights=wn) + + # evaluate the density function for the kde for some points + x, y = np.mgrid[-7:7:500j, -7:7:500j] + grid_coords = np.vstack([x.ravel(), y.ravel()]) + kdepdf = gkde.evaluate(grid_coords) + kdepdf = kdepdf.reshape(500, 500) + + normpdf = stats.multivariate_normal.pdf(np.dstack([x, y]), + mean=mean, cov=covariance) + intervall = y.ravel()[1] - y.ravel()[0] + + assert_(np.sum((kdepdf - normpdf)**2) * (intervall**2) < 0.01) + + small = -1e100 + large = 1e100 + prob1 = gkde.integrate_box([small, mean[1]], [large, large]) + prob2 = gkde.integrate_box([small, small], [large, mean[1]]) + + assert_almost_equal(prob1, 0.5, decimal=1) + assert_almost_equal(prob2, 0.5, decimal=1) + assert_almost_equal(gkde.integrate_kde(gkde), + (kdepdf**2).sum()*(intervall**2), decimal=2) + assert_almost_equal(gkde.integrate_gaussian(mean, covariance), + (kdepdf*normpdf).sum()*(intervall**2), decimal=2) + + +def test_kde_bandwidth_method(): + def scotts_factor(kde_obj): + """Same as default, just check that it works.""" + return np.power(kde_obj.n, -1./(kde_obj.d+4)) + + np.random.seed(8765678) + n_basesample = 50 + xn = np.random.randn(n_basesample) + + # Default + gkde = stats.gaussian_kde(xn) + # Supply a callable + gkde2 = stats.gaussian_kde(xn, bw_method=scotts_factor) + # Supply a scalar + gkde3 = stats.gaussian_kde(xn, bw_method=gkde.factor) + + xs = np.linspace(-7,7,51) + kdepdf = gkde.evaluate(xs) + kdepdf2 = gkde2.evaluate(xs) + assert_almost_equal(kdepdf, kdepdf2) + kdepdf3 = gkde3.evaluate(xs) + assert_almost_equal(kdepdf, kdepdf3) + + assert_raises(ValueError, stats.gaussian_kde, xn, bw_method='wrongstring') + + +def test_kde_bandwidth_method_weighted(): + def scotts_factor(kde_obj): + """Same as default, just check that it works.""" + return np.power(kde_obj.neff, -1./(kde_obj.d+4)) + + np.random.seed(8765678) + n_basesample = 50 + xn = np.random.randn(n_basesample) + + # Default + gkde = stats.gaussian_kde(xn) + # Supply a callable + gkde2 = stats.gaussian_kde(xn, bw_method=scotts_factor) + # Supply a scalar + gkde3 = stats.gaussian_kde(xn, bw_method=gkde.factor) + + xs = np.linspace(-7,7,51) + kdepdf = gkde.evaluate(xs) + kdepdf2 = gkde2.evaluate(xs) + assert_almost_equal(kdepdf, kdepdf2) + kdepdf3 = gkde3.evaluate(xs) + assert_almost_equal(kdepdf, kdepdf3) + + assert_raises(ValueError, stats.gaussian_kde, xn, bw_method='wrongstring') + + +# Subclasses that should stay working (extracted from various sources). +# Unfortunately the earlier design of gaussian_kde made it necessary for users +# to create these kinds of subclasses, or call _compute_covariance() directly. + +class _kde_subclass1(stats.gaussian_kde): + def __init__(self, dataset): + self.dataset = np.atleast_2d(dataset) + self.d, self.n = self.dataset.shape + self.covariance_factor = self.scotts_factor + self._compute_covariance() + + +class _kde_subclass2(stats.gaussian_kde): + def __init__(self, dataset): + self.covariance_factor = self.scotts_factor + super().__init__(dataset) + + +class _kde_subclass4(stats.gaussian_kde): + def covariance_factor(self): + return 0.5 * self.silverman_factor() + + +def test_gaussian_kde_subclassing(): + x1 = np.array([-7, -5, 1, 4, 5], dtype=float) + xs = np.linspace(-10, 10, num=50) + + # gaussian_kde itself + kde = stats.gaussian_kde(x1) + ys = kde(xs) + + # subclass 1 + kde1 = _kde_subclass1(x1) + y1 = kde1(xs) + assert_array_almost_equal_nulp(ys, y1, nulp=10) + + # subclass 2 + kde2 = _kde_subclass2(x1) + y2 = kde2(xs) + assert_array_almost_equal_nulp(ys, y2, nulp=10) + + # subclass 3 was removed because we have no obligation to maintain support + # for user invocation of private methods + + # subclass 4 + kde4 = _kde_subclass4(x1) + y4 = kde4(x1) + y_expected = [0.06292987, 0.06346938, 0.05860291, 0.08657652, 0.07904017] + + assert_array_almost_equal(y_expected, y4, decimal=6) + + # Not a subclass, but check for use of _compute_covariance() + kde5 = kde + kde5.covariance_factor = lambda: kde.factor + kde5._compute_covariance() + y5 = kde5(xs) + assert_array_almost_equal_nulp(ys, y5, nulp=10) + + +def test_gaussian_kde_covariance_caching(): + x1 = np.array([-7, -5, 1, 4, 5], dtype=float) + xs = np.linspace(-10, 10, num=5) + # These expected values are from scipy 0.10, before some changes to + # gaussian_kde. They were not compared with any external reference. + y_expected = [0.02463386, 0.04689208, 0.05395444, 0.05337754, 0.01664475] + + # Set the bandwidth, then reset it to the default. + kde = stats.gaussian_kde(x1) + kde.set_bandwidth(bw_method=0.5) + kde.set_bandwidth(bw_method='scott') + y2 = kde(xs) + + assert_array_almost_equal(y_expected, y2, decimal=7) + + +def test_gaussian_kde_monkeypatch(): + """Ugly, but people may rely on this. See scipy pull request 123, + specifically the linked ML thread "Width of the Gaussian in stats.kde". + If it is necessary to break this later on, that is to be discussed on ML. + """ + x1 = np.array([-7, -5, 1, 4, 5], dtype=float) + xs = np.linspace(-10, 10, num=50) + + # The old monkeypatched version to get at Silverman's Rule. + kde = stats.gaussian_kde(x1) + kde.covariance_factor = kde.silverman_factor + kde._compute_covariance() + y1 = kde(xs) + + # The new saner version. + kde2 = stats.gaussian_kde(x1, bw_method='silverman') + y2 = kde2(xs) + + assert_array_almost_equal_nulp(y1, y2, nulp=10) + + +def test_kde_integer_input(): + """Regression test for #1181.""" + x1 = np.arange(5) + kde = stats.gaussian_kde(x1) + y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869, 0.13480721] + assert_array_almost_equal(kde(x1), y_expected, decimal=6) + + +_ftypes = ['float32', 'float64', 'float96', 'float128', 'int32', 'int64'] + + +@pytest.mark.parametrize("bw_type", _ftypes + ["scott", "silverman"]) +@pytest.mark.parametrize("dtype", _ftypes) +def test_kde_output_dtype(dtype, bw_type): + # Check whether the datatypes are available + dtype = getattr(np, dtype, None) + + if bw_type in ["scott", "silverman"]: + bw = bw_type + else: + bw_type = getattr(np, bw_type, None) + bw = bw_type(3) if bw_type else None + + if any(dt is None for dt in [dtype, bw]): + pytest.skip() + + weights = np.arange(5, dtype=dtype) + dataset = np.arange(5, dtype=dtype) + k = stats.gaussian_kde(dataset, bw_method=bw, weights=weights) + points = np.arange(5, dtype=dtype) + result = k(points) + # weights are always cast to float64 + assert result.dtype == np.result_type(dataset, points, np.float64(weights), + k.factor) + + +def test_pdf_logpdf_validation(): + rng = np.random.default_rng(64202298293133848336925499069837723291) + xn = rng.standard_normal((2, 10)) + gkde = stats.gaussian_kde(xn) + xs = rng.standard_normal((3, 10)) + + msg = "points have dimension 3, dataset has dimension 2" + with pytest.raises(ValueError, match=msg): + gkde.logpdf(xs) + + +def test_pdf_logpdf(): + np.random.seed(1) + n_basesample = 50 + xn = np.random.randn(n_basesample) + + # Default + gkde = stats.gaussian_kde(xn) + + xs = np.linspace(-15, 12, 25) + pdf = gkde.evaluate(xs) + pdf2 = gkde.pdf(xs) + assert_almost_equal(pdf, pdf2, decimal=12) + + logpdf = np.log(pdf) + logpdf2 = gkde.logpdf(xs) + assert_almost_equal(logpdf, logpdf2, decimal=12) + + # There are more points than data + gkde = stats.gaussian_kde(xs) + pdf = np.log(gkde.evaluate(xn)) + pdf2 = gkde.logpdf(xn) + assert_almost_equal(pdf, pdf2, decimal=12) + + +def test_pdf_logpdf_weighted(): + np.random.seed(1) + n_basesample = 50 + xn = np.random.randn(n_basesample) + wn = np.random.rand(n_basesample) + + # Default + gkde = stats.gaussian_kde(xn, weights=wn) + + xs = np.linspace(-15, 12, 25) + pdf = gkde.evaluate(xs) + pdf2 = gkde.pdf(xs) + assert_almost_equal(pdf, pdf2, decimal=12) + + logpdf = np.log(pdf) + logpdf2 = gkde.logpdf(xs) + assert_almost_equal(logpdf, logpdf2, decimal=12) + + # There are more points than data + gkde = stats.gaussian_kde(xs, weights=np.random.rand(len(xs))) + pdf = np.log(gkde.evaluate(xn)) + pdf2 = gkde.logpdf(xn) + assert_almost_equal(pdf, pdf2, decimal=12) + + +def test_marginal_1_axis(): + rng = np.random.default_rng(6111799263660870475) + n_data = 50 + n_dim = 10 + dataset = rng.normal(size=(n_dim, n_data)) + points = rng.normal(size=(n_dim, 3)) + + dimensions = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # dimensions to keep + + kde = stats.gaussian_kde(dataset) + marginal = kde.marginal(dimensions) + pdf = marginal.pdf(points[dimensions]) + + def marginal_pdf_single(point): + def f(x): + x = np.concatenate(([x], point[dimensions])) + return kde.pdf(x)[0] + return integrate.quad(f, -np.inf, np.inf)[0] + + def marginal_pdf(points): + return np.apply_along_axis(marginal_pdf_single, axis=0, arr=points) + + ref = marginal_pdf(points) + + assert_allclose(pdf, ref, rtol=1e-6) + + +@pytest.mark.xslow +def test_marginal_2_axis(): + rng = np.random.default_rng(6111799263660870475) + n_data = 30 + n_dim = 4 + dataset = rng.normal(size=(n_dim, n_data)) + points = rng.normal(size=(n_dim, 3)) + + dimensions = np.array([1, 3]) # dimensions to keep + + kde = stats.gaussian_kde(dataset) + marginal = kde.marginal(dimensions) + pdf = marginal.pdf(points[dimensions]) + + def marginal_pdf(points): + def marginal_pdf_single(point): + def f(y, x): + w, z = point[dimensions] + x = np.array([x, w, y, z]) + return kde.pdf(x)[0] + return integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)[0] + + return np.apply_along_axis(marginal_pdf_single, axis=0, arr=points) + + ref = marginal_pdf(points) + + assert_allclose(pdf, ref, rtol=1e-6) + + +def test_marginal_iv(): + # test input validation + rng = np.random.default_rng(6111799263660870475) + n_data = 30 + n_dim = 4 + dataset = rng.normal(size=(n_dim, n_data)) + points = rng.normal(size=(n_dim, 3)) + + kde = stats.gaussian_kde(dataset) + + # check that positive and negative indices are equivalent + dimensions1 = [-1, 1] + marginal1 = kde.marginal(dimensions1) + pdf1 = marginal1.pdf(points[dimensions1]) + + dimensions2 = [3, -3] + marginal2 = kde.marginal(dimensions2) + pdf2 = marginal2.pdf(points[dimensions2]) + + assert_equal(pdf1, pdf2) + + # IV for non-integer dimensions + message = "Elements of `dimensions` must be integers..." + with pytest.raises(ValueError, match=message): + kde.marginal([1, 2.5]) + + # IV for uniqueness + message = "All elements of `dimensions` must be unique." + with pytest.raises(ValueError, match=message): + kde.marginal([1, 2, 2]) + + # IV for non-integer dimensions + message = (r"Dimensions \[-5 6\] are invalid for a distribution in 4...") + with pytest.raises(ValueError, match=message): + kde.marginal([1, -5, 6]) + + +@pytest.mark.xslow +def test_logpdf_overflow(): + # regression test for gh-12988; testing against linalg instability for + # very high dimensionality kde + np.random.seed(1) + n_dimensions = 2500 + n_samples = 5000 + xn = np.array([np.random.randn(n_samples) + (n) for n in range( + 0, n_dimensions)]) + + # Default + gkde = stats.gaussian_kde(xn) + + logpdf = gkde.logpdf(np.arange(0, n_dimensions)) + np.testing.assert_equal(np.isneginf(logpdf[0]), False) + np.testing.assert_equal(np.isnan(logpdf[0]), False) + + +def test_weights_intact(): + # regression test for gh-9709: weights are not modified + np.random.seed(12345) + vals = np.random.lognormal(size=100) + weights = np.random.choice([1.0, 10.0, 100], size=vals.size) + orig_weights = weights.copy() + + stats.gaussian_kde(np.log10(vals), weights=weights) + assert_allclose(weights, orig_weights, atol=1e-14, rtol=1e-14) + + +def test_weights_integer(): + # integer weights are OK, cf gh-9709 (comment) + np.random.seed(12345) + values = [0.2, 13.5, 21.0, 75.0, 99.0] + weights = [1, 2, 4, 8, 16] # a list of integers + pdf_i = stats.gaussian_kde(values, weights=weights) + pdf_f = stats.gaussian_kde(values, weights=np.float64(weights)) + + xn = [0.3, 11, 88] + assert_allclose(pdf_i.evaluate(xn), + pdf_f.evaluate(xn), atol=1e-14, rtol=1e-14) + + +def test_seed(): + # Test the seed option of the resample method + def test_seed_sub(gkde_trail): + n_sample = 200 + # The results should be different without using seed + samp1 = gkde_trail.resample(n_sample) + samp2 = gkde_trail.resample(n_sample) + assert_raises( + AssertionError, assert_allclose, samp1, samp2, atol=1e-13 + ) + # Use integer seed + seed = 831 + samp1 = gkde_trail.resample(n_sample, seed=seed) + samp2 = gkde_trail.resample(n_sample, seed=seed) + assert_allclose(samp1, samp2, atol=1e-13) + # Use RandomState + rstate1 = np.random.RandomState(seed=138) + samp1 = gkde_trail.resample(n_sample, seed=rstate1) + rstate2 = np.random.RandomState(seed=138) + samp2 = gkde_trail.resample(n_sample, seed=rstate2) + assert_allclose(samp1, samp2, atol=1e-13) + + # check that np.random.Generator can be used (numpy >= 1.17) + if hasattr(np.random, 'default_rng'): + # obtain a np.random.Generator object + rng = np.random.default_rng(1234) + gkde_trail.resample(n_sample, seed=rng) + + np.random.seed(8765678) + n_basesample = 500 + wn = np.random.rand(n_basesample) + # Test 1D case + xn_1d = np.random.randn(n_basesample) + + gkde_1d = stats.gaussian_kde(xn_1d) + test_seed_sub(gkde_1d) + gkde_1d_weighted = stats.gaussian_kde(xn_1d, weights=wn) + test_seed_sub(gkde_1d_weighted) + + # Test 2D case + mean = np.array([1.0, 3.0]) + covariance = np.array([[1.0, 2.0], [2.0, 6.0]]) + xn_2d = np.random.multivariate_normal(mean, covariance, size=n_basesample).T + + gkde_2d = stats.gaussian_kde(xn_2d) + test_seed_sub(gkde_2d) + gkde_2d_weighted = stats.gaussian_kde(xn_2d, weights=wn) + test_seed_sub(gkde_2d_weighted) + + +def test_singular_data_covariance_gh10205(): + # When the data lie in a lower-dimensional subspace and this causes + # and exception, check that the error message is informative. + rng = np.random.default_rng(2321583144339784787) + mu = np.array([1, 10, 20]) + sigma = np.array([[4, 10, 0], [10, 25, 0], [0, 0, 100]]) + data = rng.multivariate_normal(mu, sigma, 1000) + try: # doesn't raise any error on some platforms, and that's OK + stats.gaussian_kde(data.T) + except linalg.LinAlgError: + msg = "The data appears to lie in a lower-dimensional subspace..." + with assert_raises(linalg.LinAlgError, match=msg): + stats.gaussian_kde(data.T) + + +def test_fewer_points_than_dimensions_gh17436(): + # When the number of points is fewer than the number of dimensions, the + # the covariance matrix would be singular, and the exception tested in + # test_singular_data_covariance_gh10205 would occur. However, sometimes + # this occurs when the user passes in the transpose of what `gaussian_kde` + # expects. This can result in a huge covariance matrix, so bail early. + rng = np.random.default_rng(2046127537594925772) + rvs = rng.multivariate_normal(np.zeros(3), np.eye(3), size=5) + message = "Number of dimensions is greater than number of samples..." + with pytest.raises(ValueError, match=message): + stats.gaussian_kde(rvs) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mgc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mgc.py new file mode 100644 index 0000000000000000000000000000000000000000..320f0b1edf98123555d26c5b501bd90b31847f2c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mgc.py @@ -0,0 +1,217 @@ +import pytest +from pytest import raises as assert_raises, warns as assert_warns + +import numpy as np +from numpy.testing import assert_approx_equal, assert_allclose, assert_equal + +from scipy.spatial.distance import cdist +from scipy import stats + +class TestMGCErrorWarnings: + """ Tests errors and warnings derived from MGC. + """ + def test_error_notndarray(self): + # raises error if x or y is not a ndarray + x = np.arange(20) + y = [5] * 20 + assert_raises(ValueError, stats.multiscale_graphcorr, x, y) + assert_raises(ValueError, stats.multiscale_graphcorr, y, x) + + def test_error_shape(self): + # raises error if number of samples different (n) + x = np.arange(100).reshape(25, 4) + y = x.reshape(10, 10) + assert_raises(ValueError, stats.multiscale_graphcorr, x, y) + + def test_error_lowsamples(self): + # raises error if samples are low (< 3) + x = np.arange(3) + y = np.arange(3) + assert_raises(ValueError, stats.multiscale_graphcorr, x, y) + + def test_error_nans(self): + # raises error if inputs contain NaNs + x = np.arange(20, dtype=float) + x[0] = np.nan + assert_raises(ValueError, stats.multiscale_graphcorr, x, x) + + y = np.arange(20) + assert_raises(ValueError, stats.multiscale_graphcorr, x, y) + + def test_error_wrongdisttype(self): + # raises error if metric is not a function + x = np.arange(20) + compute_distance = 0 + assert_raises(ValueError, stats.multiscale_graphcorr, x, x, + compute_distance=compute_distance) + + @pytest.mark.parametrize("reps", [ + -1, # reps is negative + '1', # reps is not integer + ]) + def test_error_reps(self, reps): + # raises error if reps is negative + x = np.arange(20) + assert_raises(ValueError, stats.multiscale_graphcorr, x, x, reps=reps) + + def test_warns_reps(self): + # raises warning when reps is less than 1000 + x = np.arange(20) + reps = 100 + assert_warns(RuntimeWarning, stats.multiscale_graphcorr, x, x, reps=reps) + + def test_error_infty(self): + # raises error if input contains infinities + x = np.arange(20) + y = np.ones(20) * np.inf + assert_raises(ValueError, stats.multiscale_graphcorr, x, y) + + +class TestMGCStat: + """ Test validity of MGC test statistic + """ + def _simulations(self, samps=100, dims=1, sim_type=""): + # linear simulation + if sim_type == "linear": + x = np.random.uniform(-1, 1, size=(samps, 1)) + y = x + 0.3 * np.random.random_sample(size=(x.size, 1)) + + # spiral simulation + elif sim_type == "nonlinear": + unif = np.array(np.random.uniform(0, 5, size=(samps, 1))) + x = unif * np.cos(np.pi * unif) + y = (unif * np.sin(np.pi * unif) + + 0.4*np.random.random_sample(size=(x.size, 1))) + + # independence (tests type I simulation) + elif sim_type == "independence": + u = np.random.normal(0, 1, size=(samps, 1)) + v = np.random.normal(0, 1, size=(samps, 1)) + u_2 = np.random.binomial(1, p=0.5, size=(samps, 1)) + v_2 = np.random.binomial(1, p=0.5, size=(samps, 1)) + x = u/3 + 2*u_2 - 1 + y = v/3 + 2*v_2 - 1 + + # raises error if not approved sim_type + else: + raise ValueError("sim_type must be linear, nonlinear, or " + "independence") + + # add dimensions of noise for higher dimensions + if dims > 1: + dims_noise = np.random.normal(0, 1, size=(samps, dims-1)) + x = np.concatenate((x, dims_noise), axis=1) + + return x, y + + @pytest.mark.xslow + @pytest.mark.parametrize("sim_type, obs_stat, obs_pvalue", [ + ("linear", 0.97, 1/1000), # test linear simulation + ("nonlinear", 0.163, 1/1000), # test spiral simulation + ("independence", -0.0094, 0.78) # test independence simulation + ]) + def test_oned(self, sim_type, obs_stat, obs_pvalue): + np.random.seed(12345678) + + # generate x and y + x, y = self._simulations(samps=100, dims=1, sim_type=sim_type) + + # test stat and pvalue + stat, pvalue, _ = stats.multiscale_graphcorr(x, y) + assert_approx_equal(stat, obs_stat, significant=1) + assert_approx_equal(pvalue, obs_pvalue, significant=1) + + @pytest.mark.xslow + @pytest.mark.parametrize("sim_type, obs_stat, obs_pvalue", [ + ("linear", 0.184, 1/1000), # test linear simulation + ("nonlinear", 0.0190, 0.117), # test spiral simulation + ]) + def test_fived(self, sim_type, obs_stat, obs_pvalue): + np.random.seed(12345678) + + # generate x and y + x, y = self._simulations(samps=100, dims=5, sim_type=sim_type) + + # test stat and pvalue + stat, pvalue, _ = stats.multiscale_graphcorr(x, y) + assert_approx_equal(stat, obs_stat, significant=1) + assert_approx_equal(pvalue, obs_pvalue, significant=1) + + @pytest.mark.xslow + def test_twosamp(self): + np.random.seed(12345678) + + # generate x and y + x = np.random.binomial(100, 0.5, size=(100, 5)) + y = np.random.normal(0, 1, size=(80, 5)) + + # test stat and pvalue + stat, pvalue, _ = stats.multiscale_graphcorr(x, y) + assert_approx_equal(stat, 1.0, significant=1) + assert_approx_equal(pvalue, 0.001, significant=1) + + # generate x and y + y = np.random.normal(0, 1, size=(100, 5)) + + # test stat and pvalue + stat, pvalue, _ = stats.multiscale_graphcorr(x, y, is_twosamp=True) + assert_approx_equal(stat, 1.0, significant=1) + assert_approx_equal(pvalue, 0.001, significant=1) + + @pytest.mark.xslow + def test_workers(self): + np.random.seed(12345678) + + # generate x and y + x, y = self._simulations(samps=100, dims=1, sim_type="linear") + + # test stat and pvalue + stat, pvalue, _ = stats.multiscale_graphcorr(x, y, workers=2) + assert_approx_equal(stat, 0.97, significant=1) + assert_approx_equal(pvalue, 0.001, significant=1) + + @pytest.mark.xslow + def test_random_state(self): + # generate x and y + x, y = self._simulations(samps=100, dims=1, sim_type="linear") + + # test stat and pvalue + stat, pvalue, _ = stats.multiscale_graphcorr(x, y, random_state=1) + assert_approx_equal(stat, 0.97, significant=1) + assert_approx_equal(pvalue, 0.001, significant=1) + + @pytest.mark.xslow + def test_dist_perm(self): + np.random.seed(12345678) + # generate x and y + x, y = self._simulations(samps=100, dims=1, sim_type="nonlinear") + distx = cdist(x, x, metric="euclidean") + disty = cdist(y, y, metric="euclidean") + + stat_dist, pvalue_dist, _ = stats.multiscale_graphcorr(distx, disty, + compute_distance=None, + random_state=1) + assert_approx_equal(stat_dist, 0.163, significant=1) + assert_approx_equal(pvalue_dist, 0.001, significant=1) + + @pytest.mark.fail_slow(20) # all other tests are XSLOW; we need at least one to run + @pytest.mark.slow + def test_pvalue_literature(self): + np.random.seed(12345678) + + # generate x and y + x, y = self._simulations(samps=100, dims=1, sim_type="linear") + + # test stat and pvalue + _, pvalue, _ = stats.multiscale_graphcorr(x, y, random_state=1) + assert_allclose(pvalue, 1/1001) + + @pytest.mark.xslow + def test_alias(self): + np.random.seed(12345678) + + # generate x and y + x, y = self._simulations(samps=100, dims=1, sim_type="linear") + + res = stats.multiscale_graphcorr(x, y, random_state=1) + assert_equal(res.stat, res.statistic) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_morestats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_morestats.py new file mode 100644 index 0000000000000000000000000000000000000000..e596ea8aa3786a87e08d88f740f0a5995ad42026 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_morestats.py @@ -0,0 +1,3227 @@ +# Author: Travis Oliphant, 2002 +# +# Further enhancements and tests added by numerous SciPy developers. +# +import math +import warnings +import sys +from functools import partial + +import numpy as np +from numpy.random import RandomState +from numpy.testing import (assert_array_equal, assert_almost_equal, + assert_array_less, assert_array_almost_equal, + assert_, assert_allclose, assert_equal, + suppress_warnings) +import pytest +from pytest import raises as assert_raises +import re +from scipy import optimize, stats, special +from scipy.stats._morestats import _abw_state, _get_As_weibull, _Avals_weibull +from .common_tests import check_named_results +from .._hypotests import _get_wilcoxon_distr, _get_wilcoxon_distr2 +from scipy.stats._binomtest import _binary_search_for_binom_tst +from scipy.stats._distr_params import distcont +from scipy.stats._axis_nan_policy import (SmallSampleWarning, too_small_nd_omit, + too_small_1d_omit, too_small_1d_not_omit) + +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import array_namespace, is_numpy +from scipy._lib._array_api_no_0d import ( + xp_assert_close, + xp_assert_equal, + xp_assert_less, +) + + +skip_xp_backends = pytest.mark.skip_xp_backends + +distcont = dict(distcont) # type: ignore + +# Matplotlib is not a scipy dependency but is optionally used in probplot, so +# check if it's available +try: + import matplotlib + matplotlib.rcParams['backend'] = 'Agg' + import matplotlib.pyplot as plt + have_matplotlib = True +except Exception: + have_matplotlib = False + + +# test data gear.dat from NIST for Levene and Bartlett test +# https://www.itl.nist.gov/div898/handbook/eda/section3/eda3581.htm +g1 = [1.006, 0.996, 0.998, 1.000, 0.992, 0.993, 1.002, 0.999, 0.994, 1.000] +g2 = [0.998, 1.006, 1.000, 1.002, 0.997, 0.998, 0.996, 1.000, 1.006, 0.988] +g3 = [0.991, 0.987, 0.997, 0.999, 0.995, 0.994, 1.000, 0.999, 0.996, 0.996] +g4 = [1.005, 1.002, 0.994, 1.000, 0.995, 0.994, 0.998, 0.996, 1.002, 0.996] +g5 = [0.998, 0.998, 0.982, 0.990, 1.002, 0.984, 0.996, 0.993, 0.980, 0.996] +g6 = [1.009, 1.013, 1.009, 0.997, 0.988, 1.002, 0.995, 0.998, 0.981, 0.996] +g7 = [0.990, 1.004, 0.996, 1.001, 0.998, 1.000, 1.018, 1.010, 0.996, 1.002] +g8 = [0.998, 1.000, 1.006, 1.000, 1.002, 0.996, 0.998, 0.996, 1.002, 1.006] +g9 = [1.002, 0.998, 0.996, 0.995, 0.996, 1.004, 1.004, 0.998, 0.999, 0.991] +g10 = [0.991, 0.995, 0.984, 0.994, 0.997, 0.997, 0.991, 0.998, 1.004, 0.997] + + +# The loggamma RVS stream is changing due to gh-13349; this version +# preserves the old stream so that tests don't change. +def _old_loggamma_rvs(*args, **kwargs): + return np.log(stats.gamma.rvs(*args, **kwargs)) + + +class TestBayes_mvs: + def test_basic(self): + # Expected values in this test simply taken from the function. For + # some checks regarding correctness of implementation, see review in + # gh-674 + data = [6, 9, 12, 7, 8, 8, 13] + mean, var, std = stats.bayes_mvs(data) + assert_almost_equal(mean.statistic, 9.0) + assert_allclose(mean.minmax, (7.103650222492964, 10.896349777507034), + rtol=1e-6) + + assert_almost_equal(var.statistic, 10.0) + assert_allclose(var.minmax, (3.1767242068607087, 24.45910381334018), + rtol=1e-09) + + assert_almost_equal(std.statistic, 2.9724954732045084, decimal=14) + assert_allclose(std.minmax, (1.7823367265645145, 4.9456146050146312), + rtol=1e-14) + + def test_empty_input(self): + assert_raises(ValueError, stats.bayes_mvs, []) + + def test_result_attributes(self): + x = np.arange(15) + attributes = ('statistic', 'minmax') + res = stats.bayes_mvs(x) + + for i in res: + check_named_results(i, attributes) + + +class TestMvsdist: + def test_basic(self): + data = [6, 9, 12, 7, 8, 8, 13] + mean, var, std = stats.mvsdist(data) + assert_almost_equal(mean.mean(), 9.0) + assert_allclose(mean.interval(0.9), (7.103650222492964, + 10.896349777507034), rtol=1e-14) + + assert_almost_equal(var.mean(), 10.0) + assert_allclose(var.interval(0.9), (3.1767242068607087, + 24.45910381334018), rtol=1e-09) + + assert_almost_equal(std.mean(), 2.9724954732045084, decimal=14) + assert_allclose(std.interval(0.9), (1.7823367265645145, + 4.9456146050146312), rtol=1e-14) + + def test_empty_input(self): + assert_raises(ValueError, stats.mvsdist, []) + + def test_bad_arg(self): + # Raise ValueError if fewer than two data points are given. + data = [1] + assert_raises(ValueError, stats.mvsdist, data) + + def test_warns(self): + # regression test for gh-5270 + # make sure there are no spurious divide-by-zero warnings + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + [x.mean() for x in stats.mvsdist([1, 2, 3])] + [x.mean() for x in stats.mvsdist([1, 2, 3, 4, 5])] + + +class TestShapiro: + def test_basic(self): + x1 = [0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46, + 4.43, 0.21, 4.75, 0.71, 1.52, 3.24, + 0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66] + w, pw = stats.shapiro(x1) + shapiro_test = stats.shapiro(x1) + assert_almost_equal(w, 0.90047299861907959, decimal=6) + assert_almost_equal(shapiro_test.statistic, 0.90047299861907959, decimal=6) + assert_almost_equal(pw, 0.042089745402336121, decimal=6) + assert_almost_equal(shapiro_test.pvalue, 0.042089745402336121, decimal=6) + + x2 = [1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11, + 3.48, 1.10, 0.88, -0.51, 1.46, 0.52, 6.20, 1.69, + 0.08, 3.67, 2.81, 3.49] + w, pw = stats.shapiro(x2) + shapiro_test = stats.shapiro(x2) + assert_almost_equal(w, 0.9590270, decimal=6) + assert_almost_equal(shapiro_test.statistic, 0.9590270, decimal=6) + assert_almost_equal(pw, 0.52460, decimal=3) + assert_almost_equal(shapiro_test.pvalue, 0.52460, decimal=3) + + # Verified against R + x3 = stats.norm.rvs(loc=5, scale=3, size=100, random_state=12345678) + w, pw = stats.shapiro(x3) + shapiro_test = stats.shapiro(x3) + assert_almost_equal(w, 0.9772805571556091, decimal=6) + assert_almost_equal(shapiro_test.statistic, 0.9772805571556091, decimal=6) + assert_almost_equal(pw, 0.08144091814756393, decimal=3) + assert_almost_equal(shapiro_test.pvalue, 0.08144091814756393, decimal=3) + + # Extracted from original paper + x4 = [0.139, 0.157, 0.175, 0.256, 0.344, 0.413, 0.503, 0.577, 0.614, + 0.655, 0.954, 1.392, 1.557, 1.648, 1.690, 1.994, 2.174, 2.206, + 3.245, 3.510, 3.571, 4.354, 4.980, 6.084, 8.351] + W_expected = 0.83467 + p_expected = 0.000914 + w, pw = stats.shapiro(x4) + shapiro_test = stats.shapiro(x4) + assert_almost_equal(w, W_expected, decimal=4) + assert_almost_equal(shapiro_test.statistic, W_expected, decimal=4) + assert_almost_equal(pw, p_expected, decimal=5) + assert_almost_equal(shapiro_test.pvalue, p_expected, decimal=5) + + def test_2d(self): + x1 = [[0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46, + 4.43, 0.21, 4.75], [0.71, 1.52, 3.24, + 0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66]] + w, pw = stats.shapiro(x1) + shapiro_test = stats.shapiro(x1) + assert_almost_equal(w, 0.90047299861907959, decimal=6) + assert_almost_equal(shapiro_test.statistic, 0.90047299861907959, decimal=6) + assert_almost_equal(pw, 0.042089745402336121, decimal=6) + assert_almost_equal(shapiro_test.pvalue, 0.042089745402336121, decimal=6) + + x2 = [[1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11, + 3.48, 1.10], [0.88, -0.51, 1.46, 0.52, 6.20, 1.69, + 0.08, 3.67, 2.81, 3.49]] + w, pw = stats.shapiro(x2) + shapiro_test = stats.shapiro(x2) + assert_almost_equal(w, 0.9590270, decimal=6) + assert_almost_equal(shapiro_test.statistic, 0.9590270, decimal=6) + assert_almost_equal(pw, 0.52460, decimal=3) + assert_almost_equal(shapiro_test.pvalue, 0.52460, decimal=3) + + @pytest.mark.parametrize('x', ([], [1], [1, 2])) + def test_not_enough_values(self, x): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.shapiro(x) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_nan_input(self): + x = np.arange(10.) + x[9] = np.nan + + w, pw = stats.shapiro(x) + shapiro_test = stats.shapiro(x) + assert_equal(w, np.nan) + assert_equal(shapiro_test.statistic, np.nan) + # Originally, shapiro returned a p-value of 1 in this case, + # but there is no way to produce a numerical p-value if the + # statistic is not a number. NaN is more appropriate. + assert_almost_equal(pw, np.nan) + assert_almost_equal(shapiro_test.pvalue, np.nan) + + def test_gh14462(self): + # shapiro is theoretically location-invariant, but when the magnitude + # of the values is much greater than the variance, there can be + # numerical issues. Fixed by subtracting median from the data. + # See gh-14462. + + trans_val, maxlog = stats.boxcox([122500, 474400, 110400]) + res = stats.shapiro(trans_val) + + # Reference from R: + # options(digits=16) + # x = c(0.00000000e+00, 3.39996924e-08, -6.35166875e-09) + # shapiro.test(x) + ref = (0.86468431705371, 0.2805581751566) + + assert_allclose(res, ref, rtol=1e-5) + + def test_length_3_gh18322(self): + # gh-18322 reported that the p-value could be negative for input of + # length 3. Check that this is resolved. + res = stats.shapiro([0.6931471805599453, 0.0, 0.0]) + assert res.pvalue >= 0 + + # R `shapiro.test` doesn't produce an accurate p-value in the case + # above. Check that the formula used in `stats.shapiro` is not wrong. + # options(digits=16) + # x = c(-0.7746653110021126, -0.4344432067942129, 1.8157053280290931) + # shapiro.test(x) + x = [-0.7746653110021126, -0.4344432067942129, 1.8157053280290931] + res = stats.shapiro(x) + assert_allclose(res.statistic, 0.84658770645509) + assert_allclose(res.pvalue, 0.2313666489882, rtol=1e-6) + + +class TestAnderson: + def test_normal(self): + rs = RandomState(1234567890) + x1 = rs.standard_exponential(size=50) + x2 = rs.standard_normal(size=50) + A, crit, sig = stats.anderson(x1) + assert_array_less(crit[:-1], A) + A, crit, sig = stats.anderson(x2) + assert_array_less(A, crit[-2:]) + + v = np.ones(10) + v[0] = 0 + A, crit, sig = stats.anderson(v) + # The expected statistic 3.208057 was computed independently of scipy. + # For example, in R: + # > library(nortest) + # > v <- rep(1, 10) + # > v[1] <- 0 + # > result <- ad.test(v) + # > result$statistic + # A + # 3.208057 + assert_allclose(A, 3.208057) + + def test_expon(self): + rs = RandomState(1234567890) + x1 = rs.standard_exponential(size=50) + x2 = rs.standard_normal(size=50) + A, crit, sig = stats.anderson(x1, 'expon') + assert_array_less(A, crit[-2:]) + with np.errstate(all='ignore'): + A, crit, sig = stats.anderson(x2, 'expon') + assert_(A > crit[-1]) + + def test_gumbel(self): + # Regression test for gh-6306. Before that issue was fixed, + # this case would return a2=inf. + v = np.ones(100) + v[0] = 0.0 + a2, crit, sig = stats.anderson(v, 'gumbel') + # A brief reimplementation of the calculation of the statistic. + n = len(v) + xbar, s = stats.gumbel_l.fit(v) + logcdf = stats.gumbel_l.logcdf(v, xbar, s) + logsf = stats.gumbel_l.logsf(v, xbar, s) + i = np.arange(1, n+1) + expected_a2 = -n - np.mean((2*i - 1) * (logcdf + logsf[::-1])) + + assert_allclose(a2, expected_a2) + + def test_bad_arg(self): + assert_raises(ValueError, stats.anderson, [1], dist='plate_of_shrimp') + + def test_result_attributes(self): + rs = RandomState(1234567890) + x = rs.standard_exponential(size=50) + res = stats.anderson(x) + attributes = ('statistic', 'critical_values', 'significance_level') + check_named_results(res, attributes) + + def test_gumbel_l(self): + # gh-2592, gh-6337 + # Adds support to 'gumbel_r' and 'gumbel_l' as valid inputs for dist. + rs = RandomState(1234567890) + x = rs.gumbel(size=100) + A1, crit1, sig1 = stats.anderson(x, 'gumbel') + A2, crit2, sig2 = stats.anderson(x, 'gumbel_l') + + assert_allclose(A2, A1) + + def test_gumbel_r(self): + # gh-2592, gh-6337 + # Adds support to 'gumbel_r' and 'gumbel_l' as valid inputs for dist. + rs = RandomState(1234567890) + x1 = rs.gumbel(size=100) + x2 = np.ones(100) + # A constant array is a degenerate case and breaks gumbel_r.fit, so + # change one value in x2. + x2[0] = 0.996 + A1, crit1, sig1 = stats.anderson(x1, 'gumbel_r') + A2, crit2, sig2 = stats.anderson(x2, 'gumbel_r') + + assert_array_less(A1, crit1[-2:]) + assert_(A2 > crit2[-1]) + + def test_weibull_min_case_A(self): + # data and reference values from `anderson` reference [7] + x = np.array([225, 171, 198, 189, 189, 135, 162, 135, 117, 162]) + res = stats.anderson(x, 'weibull_min') + m, loc, scale = res.fit_result.params + assert_allclose((m, loc, scale), (2.38, 99.02, 78.23), rtol=2e-3) + assert_allclose(res.statistic, 0.260, rtol=1e-3) + assert res.statistic < res.critical_values[0] + + c = 1 / m # ~0.42 + assert_allclose(c, 1/2.38, rtol=2e-3) + # interpolate between rows for c=0.4 and c=0.45, indices -3 and -2 + As40 = _Avals_weibull[-3] + As45 = _Avals_weibull[-2] + As_ref = As40 + (c - 0.4)/(0.45 - 0.4) * (As45 - As40) + # atol=1e-3 because results are rounded up to the next third decimal + assert np.all(res.critical_values > As_ref) + assert_allclose(res.critical_values, As_ref, atol=1e-3) + + def test_weibull_min_case_B(self): + # From `anderson` reference [7] + x = np.array([74, 57, 48, 29, 502, 12, 70, 21, + 29, 386, 59, 27, 153, 26, 326]) + message = "Maximum likelihood estimation has converged to " + with pytest.raises(ValueError, match=message): + stats.anderson(x, 'weibull_min') + + def test_weibull_warning_error(self): + # Check for warning message when there are too few observations + # This is also an example in which an error occurs during fitting + x = -np.array([225, 75, 57, 168, 107, 12, 61, 43, 29]) + wmessage = "Critical values of the test statistic are given for the..." + emessage = "An error occurred while fitting the Weibull distribution..." + wcontext = pytest.warns(UserWarning, match=wmessage) + econtext = pytest.raises(ValueError, match=emessage) + with wcontext, econtext: + stats.anderson(x, 'weibull_min') + + @pytest.mark.parametrize('distname', + ['norm', 'expon', 'gumbel_l', 'extreme1', + 'gumbel', 'gumbel_r', 'logistic', 'weibull_min']) + def test_anderson_fit_params(self, distname): + # check that anderson now returns a FitResult + rng = np.random.default_rng(330691555377792039) + real_distname = ('gumbel_l' if distname in {'extreme1', 'gumbel'} + else distname) + dist = getattr(stats, real_distname) + params = distcont[real_distname] + x = dist.rvs(*params, size=1000, random_state=rng) + res = stats.anderson(x, distname) + assert res.fit_result.success + + def test_anderson_weibull_As(self): + m = 1 # "when mi < 2, so that c > 0.5, the last line...should be used" + assert_equal(_get_As_weibull(1/m), _Avals_weibull[-1]) + m = np.inf + assert_equal(_get_As_weibull(1/m), _Avals_weibull[0]) + + +class TestAndersonKSamp: + def test_example1a(self): + # Example data from Scholz & Stephens (1987), originally + # published in Lehmann (1995, Nonparametrics, Statistical + # Methods Based on Ranks, p. 309) + # Pass a mixture of lists and arrays + t1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0] + t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8]) + t3 = np.array([34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0]) + t4 = np.array([34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]) + + Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4), midrank=False) + + assert_almost_equal(Tk, 4.449, 3) + assert_array_almost_equal([0.4985, 1.3237, 1.9158, 2.4930, 3.2459], + tm[0:5], 4) + assert_allclose(p, 0.0021, atol=0.00025) + + def test_example1b(self): + # Example data from Scholz & Stephens (1987), originally + # published in Lehmann (1995, Nonparametrics, Statistical + # Methods Based on Ranks, p. 309) + # Pass arrays + t1 = np.array([38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0]) + t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8]) + t3 = np.array([34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0]) + t4 = np.array([34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8]) + Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4), midrank=True) + + assert_almost_equal(Tk, 4.480, 3) + assert_array_almost_equal([0.4985, 1.3237, 1.9158, 2.4930, 3.2459], + tm[0:5], 4) + assert_allclose(p, 0.0020, atol=0.00025) + + @pytest.mark.xslow + def test_example2a(self): + # Example data taken from an earlier technical report of + # Scholz and Stephens + # Pass lists instead of arrays + t1 = [194, 15, 41, 29, 33, 181] + t2 = [413, 14, 58, 37, 100, 65, 9, 169, 447, 184, 36, 201, 118] + t3 = [34, 31, 18, 18, 67, 57, 62, 7, 22, 34] + t4 = [90, 10, 60, 186, 61, 49, 14, 24, 56, 20, 79, 84, 44, 59, 29, + 118, 25, 156, 310, 76, 26, 44, 23, 62] + t5 = [130, 208, 70, 101, 208] + t6 = [74, 57, 48, 29, 502, 12, 70, 21, 29, 386, 59, 27] + t7 = [55, 320, 56, 104, 220, 239, 47, 246, 176, 182, 33] + t8 = [23, 261, 87, 7, 120, 14, 62, 47, 225, 71, 246, 21, 42, 20, 5, + 12, 120, 11, 3, 14, 71, 11, 14, 11, 16, 90, 1, 16, 52, 95] + t9 = [97, 51, 11, 4, 141, 18, 142, 68, 77, 80, 1, 16, 106, 206, 82, + 54, 31, 216, 46, 111, 39, 63, 18, 191, 18, 163, 24] + t10 = [50, 44, 102, 72, 22, 39, 3, 15, 197, 188, 79, 88, 46, 5, 5, 36, + 22, 139, 210, 97, 30, 23, 13, 14] + t11 = [359, 9, 12, 270, 603, 3, 104, 2, 438] + t12 = [50, 254, 5, 283, 35, 12] + t13 = [487, 18, 100, 7, 98, 5, 85, 91, 43, 230, 3, 130] + t14 = [102, 209, 14, 57, 54, 32, 67, 59, 134, 152, 27, 14, 230, 66, + 61, 34] + + samples = (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14) + Tk, tm, p = stats.anderson_ksamp(samples, midrank=False) + assert_almost_equal(Tk, 3.288, 3) + assert_array_almost_equal([0.5990, 1.3269, 1.8052, 2.2486, 2.8009], + tm[0:5], 4) + assert_allclose(p, 0.0041, atol=0.00025) + + rng = np.random.default_rng(6989860141921615054) + method = stats.PermutationMethod(n_resamples=9999, rng=rng) + res = stats.anderson_ksamp(samples, midrank=False, method=method) + assert_array_equal(res.statistic, Tk) + assert_array_equal(res.critical_values, tm) + assert_allclose(res.pvalue, p, atol=6e-4) + + def test_example2b(self): + # Example data taken from an earlier technical report of + # Scholz and Stephens + t1 = [194, 15, 41, 29, 33, 181] + t2 = [413, 14, 58, 37, 100, 65, 9, 169, 447, 184, 36, 201, 118] + t3 = [34, 31, 18, 18, 67, 57, 62, 7, 22, 34] + t4 = [90, 10, 60, 186, 61, 49, 14, 24, 56, 20, 79, 84, 44, 59, 29, + 118, 25, 156, 310, 76, 26, 44, 23, 62] + t5 = [130, 208, 70, 101, 208] + t6 = [74, 57, 48, 29, 502, 12, 70, 21, 29, 386, 59, 27] + t7 = [55, 320, 56, 104, 220, 239, 47, 246, 176, 182, 33] + t8 = [23, 261, 87, 7, 120, 14, 62, 47, 225, 71, 246, 21, 42, 20, 5, + 12, 120, 11, 3, 14, 71, 11, 14, 11, 16, 90, 1, 16, 52, 95] + t9 = [97, 51, 11, 4, 141, 18, 142, 68, 77, 80, 1, 16, 106, 206, 82, + 54, 31, 216, 46, 111, 39, 63, 18, 191, 18, 163, 24] + t10 = [50, 44, 102, 72, 22, 39, 3, 15, 197, 188, 79, 88, 46, 5, 5, 36, + 22, 139, 210, 97, 30, 23, 13, 14] + t11 = [359, 9, 12, 270, 603, 3, 104, 2, 438] + t12 = [50, 254, 5, 283, 35, 12] + t13 = [487, 18, 100, 7, 98, 5, 85, 91, 43, 230, 3, 130] + t14 = [102, 209, 14, 57, 54, 32, 67, 59, 134, 152, 27, 14, 230, 66, + 61, 34] + + Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4, t5, t6, t7, t8, + t9, t10, t11, t12, t13, t14), + midrank=True) + + assert_almost_equal(Tk, 3.294, 3) + assert_array_almost_equal([0.5990, 1.3269, 1.8052, 2.2486, 2.8009], + tm[0:5], 4) + assert_allclose(p, 0.0041, atol=0.00025) + + def test_R_kSamples(self): + # test values generates with R package kSamples + # package version 1.2-6 (2017-06-14) + # r1 = 1:100 + # continuous case (no ties) --> version 1 + # res <- kSamples::ad.test(r1, r1 + 40.5) + # res$ad[1, "T.AD"] # 41.105 + # res$ad[1, " asympt. P-value"] # 5.8399e-18 + # + # discrete case (ties allowed) --> version 2 (here: midrank=True) + # res$ad[2, "T.AD"] # 41.235 + # + # res <- kSamples::ad.test(r1, r1 + .5) + # res$ad[1, "T.AD"] # -1.2824 + # res$ad[1, " asympt. P-value"] # 1 + # res$ad[2, "T.AD"] # -1.2944 + # + # res <- kSamples::ad.test(r1, r1 + 7.5) + # res$ad[1, "T.AD"] # 1.4923 + # res$ad[1, " asympt. P-value"] # 0.077501 + # + # res <- kSamples::ad.test(r1, r1 + 6) + # res$ad[2, "T.AD"] # 0.63892 + # res$ad[2, " asympt. P-value"] # 0.17981 + # + # res <- kSamples::ad.test(r1, r1 + 11.5) + # res$ad[1, "T.AD"] # 4.5042 + # res$ad[1, " asympt. P-value"] # 0.00545 + # + # res <- kSamples::ad.test(r1, r1 + 13.5) + # res$ad[1, "T.AD"] # 6.2982 + # res$ad[1, " asympt. P-value"] # 0.00118 + + x1 = np.linspace(1, 100, 100) + # test case: different distributions;p-value floored at 0.001 + # test case for issue #5493 / #8536 + with suppress_warnings() as sup: + sup.filter(UserWarning, message='p-value floored') + s, _, p = stats.anderson_ksamp([x1, x1 + 40.5], midrank=False) + assert_almost_equal(s, 41.105, 3) + assert_equal(p, 0.001) + + with suppress_warnings() as sup: + sup.filter(UserWarning, message='p-value floored') + s, _, p = stats.anderson_ksamp([x1, x1 + 40.5]) + assert_almost_equal(s, 41.235, 3) + assert_equal(p, 0.001) + + # test case: similar distributions --> p-value capped at 0.25 + with suppress_warnings() as sup: + sup.filter(UserWarning, message='p-value capped') + s, _, p = stats.anderson_ksamp([x1, x1 + .5], midrank=False) + assert_almost_equal(s, -1.2824, 4) + assert_equal(p, 0.25) + + with suppress_warnings() as sup: + sup.filter(UserWarning, message='p-value capped') + s, _, p = stats.anderson_ksamp([x1, x1 + .5]) + assert_almost_equal(s, -1.2944, 4) + assert_equal(p, 0.25) + + # test case: check interpolated p-value in [0.01, 0.25] (no ties) + s, _, p = stats.anderson_ksamp([x1, x1 + 7.5], midrank=False) + assert_almost_equal(s, 1.4923, 4) + assert_allclose(p, 0.0775, atol=0.005, rtol=0) + + # test case: check interpolated p-value in [0.01, 0.25] (w/ ties) + s, _, p = stats.anderson_ksamp([x1, x1 + 6]) + assert_almost_equal(s, 0.6389, 4) + assert_allclose(p, 0.1798, atol=0.005, rtol=0) + + # test extended critical values for p=0.001 and p=0.005 + s, _, p = stats.anderson_ksamp([x1, x1 + 11.5], midrank=False) + assert_almost_equal(s, 4.5042, 4) + assert_allclose(p, 0.00545, atol=0.0005, rtol=0) + + s, _, p = stats.anderson_ksamp([x1, x1 + 13.5], midrank=False) + assert_almost_equal(s, 6.2982, 4) + assert_allclose(p, 0.00118, atol=0.0001, rtol=0) + + def test_not_enough_samples(self): + assert_raises(ValueError, stats.anderson_ksamp, np.ones(5)) + + def test_no_distinct_observations(self): + assert_raises(ValueError, stats.anderson_ksamp, + (np.ones(5), np.ones(5))) + + def test_empty_sample(self): + assert_raises(ValueError, stats.anderson_ksamp, (np.ones(5), [])) + + def test_result_attributes(self): + # Pass a mixture of lists and arrays + t1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0] + t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8]) + res = stats.anderson_ksamp((t1, t2), midrank=False) + + attributes = ('statistic', 'critical_values', 'significance_level') + check_named_results(res, attributes) + + assert_equal(res.significance_level, res.pvalue) + + +class TestAnsari: + + def test_small(self): + x = [1, 2, 3, 3, 4] + y = [3, 2, 6, 1, 6, 1, 4, 1] + with suppress_warnings() as sup: + sup.filter(UserWarning, "Ties preclude use of exact statistic.") + W, pval = stats.ansari(x, y) + assert_almost_equal(W, 23.5, 11) + assert_almost_equal(pval, 0.13499256881897437, 11) + + def test_approx(self): + ramsay = np.array((111, 107, 100, 99, 102, 106, 109, 108, 104, 99, + 101, 96, 97, 102, 107, 113, 116, 113, 110, 98)) + parekh = np.array((107, 108, 106, 98, 105, 103, 110, 105, 104, + 100, 96, 108, 103, 104, 114, 114, 113, 108, + 106, 99)) + + with suppress_warnings() as sup: + sup.filter(UserWarning, "Ties preclude use of exact statistic.") + W, pval = stats.ansari(ramsay, parekh) + + assert_almost_equal(W, 185.5, 11) + assert_almost_equal(pval, 0.18145819972867083, 11) + + def test_exact(self): + W, pval = stats.ansari([1, 2, 3, 4], [15, 5, 20, 8, 10, 12]) + assert_almost_equal(W, 10.0, 11) + assert_almost_equal(pval, 0.533333333333333333, 7) + + @pytest.mark.parametrize('args', [([], [1]), ([1], [])]) + def test_bad_arg(self, args): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.ansari(*args) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_result_attributes(self): + x = [1, 2, 3, 3, 4] + y = [3, 2, 6, 1, 6, 1, 4, 1] + with suppress_warnings() as sup: + sup.filter(UserWarning, "Ties preclude use of exact statistic.") + res = stats.ansari(x, y) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes) + + def test_bad_alternative(self): + # invalid value for alternative must raise a ValueError + x1 = [1, 2, 3, 4] + x2 = [5, 6, 7, 8] + match = "'alternative' must be 'two-sided'" + with assert_raises(ValueError, match=match): + stats.ansari(x1, x2, alternative='foo') + + def test_alternative_exact(self): + x1 = [-5, 1, 5, 10, 15, 20, 25] # high scale, loc=10 + x2 = [7.5, 8.5, 9.5, 10.5, 11.5, 12.5] # low scale, loc=10 + # ratio of scales is greater than 1. So, the + # p-value must be high when `alternative='less'` + # and low when `alternative='greater'`. + statistic, pval = stats.ansari(x1, x2) + pval_l = stats.ansari(x1, x2, alternative='less').pvalue + pval_g = stats.ansari(x1, x2, alternative='greater').pvalue + assert pval_l > 0.95 + assert pval_g < 0.05 # level of significance. + # also check if the p-values sum up to 1 plus the probability + # mass under the calculated statistic. + prob = _abw_state.a.pmf(statistic, len(x1), len(x2)) + assert_allclose(pval_g + pval_l, 1 + prob, atol=1e-12) + # also check if one of the one-sided p-value equals half the + # two-sided p-value and the other one-sided p-value is its + # compliment. + assert_allclose(pval_g, pval/2, atol=1e-12) + assert_allclose(pval_l, 1+prob-pval/2, atol=1e-12) + # sanity check. The result should flip if + # we exchange x and y. + pval_l_reverse = stats.ansari(x2, x1, alternative='less').pvalue + pval_g_reverse = stats.ansari(x2, x1, alternative='greater').pvalue + assert pval_l_reverse < 0.05 + assert pval_g_reverse > 0.95 + + @pytest.mark.parametrize( + 'x, y, alternative, expected', + # the tests are designed in such a way that the + # if else statement in ansari test for exact + # mode is covered. + [([1, 2, 3, 4], [5, 6, 7, 8], 'less', 0.6285714285714), + ([1, 2, 3, 4], [5, 6, 7, 8], 'greater', 0.6285714285714), + ([1, 2, 3], [4, 5, 6, 7, 8], 'less', 0.8928571428571), + ([1, 2, 3], [4, 5, 6, 7, 8], 'greater', 0.2857142857143), + ([1, 2, 3, 4, 5], [6, 7, 8], 'less', 0.2857142857143), + ([1, 2, 3, 4, 5], [6, 7, 8], 'greater', 0.8928571428571)] + ) + def test_alternative_exact_with_R(self, x, y, alternative, expected): + # testing with R on arbitrary data + # Sample R code used for the third test case above: + # ```R + # > options(digits=16) + # > x <- c(1,2,3) + # > y <- c(4,5,6,7,8) + # > ansari.test(x, y, alternative='less', exact=TRUE) + # + # Ansari-Bradley test + # + # data: x and y + # AB = 6, p-value = 0.8928571428571 + # alternative hypothesis: true ratio of scales is less than 1 + # + # ``` + pval = stats.ansari(x, y, alternative=alternative).pvalue + assert_allclose(pval, expected, atol=1e-12) + + def test_alternative_approx(self): + # intuitive tests for approximation + x1 = stats.norm.rvs(0, 5, size=100, random_state=123) + x2 = stats.norm.rvs(0, 2, size=100, random_state=123) + # for m > 55 or n > 55, the test should automatically + # switch to approximation. + pval_l = stats.ansari(x1, x2, alternative='less').pvalue + pval_g = stats.ansari(x1, x2, alternative='greater').pvalue + assert_allclose(pval_l, 1.0, atol=1e-12) + assert_allclose(pval_g, 0.0, atol=1e-12) + # also check if one of the one-sided p-value equals half the + # two-sided p-value and the other one-sided p-value is its + # compliment. + x1 = stats.norm.rvs(0, 2, size=60, random_state=123) + x2 = stats.norm.rvs(0, 1.5, size=60, random_state=123) + pval = stats.ansari(x1, x2).pvalue + pval_l = stats.ansari(x1, x2, alternative='less').pvalue + pval_g = stats.ansari(x1, x2, alternative='greater').pvalue + assert_allclose(pval_g, pval/2, atol=1e-12) + assert_allclose(pval_l, 1-pval/2, atol=1e-12) + + +@array_api_compatible +class TestBartlett: + def test_data(self, xp): + # https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm + args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] + args = [xp.asarray(arg) for arg in args] + T, pval = stats.bartlett(*args) + xp_assert_close(T, xp.asarray(20.78587342806484)) + xp_assert_close(pval, xp.asarray(0.0136358632781)) + + def test_too_few_args(self, xp): + message = "Must enter at least two input sample vectors." + with pytest.raises(ValueError, match=message): + stats.bartlett(xp.asarray([1.])) + + def test_result_attributes(self, xp): + args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] + args = [xp.asarray(arg) for arg in args] + res = stats.bartlett(*args) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, xp=xp) + + @pytest.mark.skip_xp_backends( + "jax.numpy", cpu_only=True, + reason='`var` incorrect when `correction > n` (google/jax#21330)') + @pytest.mark.usefixtures("skip_xp_backends") + def test_empty_arg(self, xp): + args = (g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, []) + args = [xp.asarray(arg) for arg in args] + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.bartlett(*args) + else: + with np.testing.suppress_warnings() as sup: + # torch/array_api_strict + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(UserWarning, r"var\(\): degrees of freedom is <= 0.") + sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice") + res = stats.bartlett(*args) + NaN = xp.asarray(xp.nan) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + + def test_negative_pvalue_gh21152(self, xp): + a = xp.asarray([10.1, 10.2, 10.3, 10.4], dtype=xp.float32) + b = xp.asarray([10.15, 10.25, 10.35, 10.45], dtype=xp.float32) + c = xp.asarray([10.05, 10.15, 10.25, 10.35], dtype=xp.float32) + res = stats.bartlett(a, b, c) + assert xp.all(res.statistic >= 0) + + +class TestLevene: + + def test_data(self): + # https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm + args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] + W, pval = stats.levene(*args) + assert_almost_equal(W, 1.7059176930008939, 7) + assert_almost_equal(pval, 0.0990829755522, 7) + + def test_trimmed1(self): + # Test that center='trimmed' gives the same result as center='mean' + # when proportiontocut=0. + W1, pval1 = stats.levene(g1, g2, g3, center='mean') + W2, pval2 = stats.levene(g1, g2, g3, center='trimmed', + proportiontocut=0.0) + assert_almost_equal(W1, W2) + assert_almost_equal(pval1, pval2) + + def test_trimmed2(self): + x = [1.2, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100.0] + y = [0.0, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 200.0] + np.random.seed(1234) + x2 = np.random.permutation(x) + + # Use center='trimmed' + W0, pval0 = stats.levene(x, y, center='trimmed', + proportiontocut=0.125) + W1, pval1 = stats.levene(x2, y, center='trimmed', + proportiontocut=0.125) + # Trim the data here, and use center='mean' + W2, pval2 = stats.levene(x[1:-1], y[1:-1], center='mean') + # Result should be the same. + assert_almost_equal(W0, W2) + assert_almost_equal(W1, W2) + assert_almost_equal(pval1, pval2) + + def test_equal_mean_median(self): + x = np.linspace(-1, 1, 21) + np.random.seed(1234) + x2 = np.random.permutation(x) + y = x**3 + W1, pval1 = stats.levene(x, y, center='mean') + W2, pval2 = stats.levene(x2, y, center='median') + assert_almost_equal(W1, W2) + assert_almost_equal(pval1, pval2) + + def test_bad_keyword(self): + x = np.linspace(-1, 1, 21) + assert_raises(TypeError, stats.levene, x, x, portiontocut=0.1) + + def test_bad_center_value(self): + x = np.linspace(-1, 1, 21) + assert_raises(ValueError, stats.levene, x, x, center='trim') + + def test_too_few_args(self): + assert_raises(ValueError, stats.levene, [1]) + + def test_result_attributes(self): + args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] + res = stats.levene(*args) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes) + + # temporary fix for issue #9252: only accept 1d input + def test_1d_input(self): + x = np.array([[1, 2], [3, 4]]) + assert_raises(ValueError, stats.levene, g1, x) + + +class TestBinomTest: + """Tests for stats.binomtest.""" + + # Expected results here are from R binom.test, e.g. + # options(digits=16) + # binom.test(484, 967, p=0.48) + # + def test_two_sided_pvalues1(self): + # `tol` could be stricter on most architectures, but the value + # here is limited by accuracy of `binom.cdf` for large inputs on + # Linux_Python_37_32bit_full and aarch64 + rtol = 1e-10 # aarch64 observed rtol: 1.5e-11 + res = stats.binomtest(10079999, 21000000, 0.48) + assert_allclose(res.pvalue, 1.0, rtol=rtol) + res = stats.binomtest(10079990, 21000000, 0.48) + assert_allclose(res.pvalue, 0.9966892187965, rtol=rtol) + res = stats.binomtest(10080009, 21000000, 0.48) + assert_allclose(res.pvalue, 0.9970377203856, rtol=rtol) + res = stats.binomtest(10080017, 21000000, 0.48) + assert_allclose(res.pvalue, 0.9940754817328, rtol=1e-9) + + def test_two_sided_pvalues2(self): + rtol = 1e-10 # no aarch64 failure with 1e-15, preemptive bump + res = stats.binomtest(9, n=21, p=0.48) + assert_allclose(res.pvalue, 0.6689672431939, rtol=rtol) + res = stats.binomtest(4, 21, 0.48) + assert_allclose(res.pvalue, 0.008139563452106, rtol=rtol) + res = stats.binomtest(11, 21, 0.48) + assert_allclose(res.pvalue, 0.8278629664608, rtol=rtol) + res = stats.binomtest(7, 21, 0.48) + assert_allclose(res.pvalue, 0.1966772901718, rtol=rtol) + res = stats.binomtest(3, 10, .5) + assert_allclose(res.pvalue, 0.34375, rtol=rtol) + res = stats.binomtest(2, 2, .4) + assert_allclose(res.pvalue, 0.16, rtol=rtol) + res = stats.binomtest(2, 4, .3) + assert_allclose(res.pvalue, 0.5884, rtol=rtol) + + def test_edge_cases(self): + rtol = 1e-10 # aarch64 observed rtol: 1.33e-15 + res = stats.binomtest(484, 967, 0.5) + assert_allclose(res.pvalue, 1, rtol=rtol) + res = stats.binomtest(3, 47, 3/47) + assert_allclose(res.pvalue, 1, rtol=rtol) + res = stats.binomtest(13, 46, 13/46) + assert_allclose(res.pvalue, 1, rtol=rtol) + res = stats.binomtest(15, 44, 15/44) + assert_allclose(res.pvalue, 1, rtol=rtol) + res = stats.binomtest(7, 13, 0.5) + assert_allclose(res.pvalue, 1, rtol=rtol) + res = stats.binomtest(6, 11, 0.5) + assert_allclose(res.pvalue, 1, rtol=rtol) + + def test_binary_srch_for_binom_tst(self): + # Test that old behavior of binomtest is maintained + # by the new binary search method in cases where d + # exactly equals the input on one side. + n = 10 + p = 0.5 + k = 3 + # First test for the case where k > mode of PMF + i = np.arange(np.ceil(p * n), n+1) + d = stats.binom.pmf(k, n, p) + # Old way of calculating y, probably consistent with R. + y1 = np.sum(stats.binom.pmf(i, n, p) <= d, axis=0) + # New way with binary search. + ix = _binary_search_for_binom_tst(lambda x1: + -stats.binom.pmf(x1, n, p), + -d, np.ceil(p * n), n) + y2 = n - ix + int(d == stats.binom.pmf(ix, n, p)) + assert_allclose(y1, y2, rtol=1e-9) + # Now test for the other side. + k = 7 + i = np.arange(np.floor(p * n) + 1) + d = stats.binom.pmf(k, n, p) + # Old way of calculating y. + y1 = np.sum(stats.binom.pmf(i, n, p) <= d, axis=0) + # New way with binary search. + ix = _binary_search_for_binom_tst(lambda x1: + stats.binom.pmf(x1, n, p), + d, 0, np.floor(p * n)) + y2 = ix + 1 + assert_allclose(y1, y2, rtol=1e-9) + + # Expected results here are from R 3.6.2 binom.test + @pytest.mark.parametrize('alternative, pval, ci_low, ci_high', + [('less', 0.148831050443, + 0.0, 0.2772002496709138), + ('greater', 0.9004695898947, + 0.1366613252458672, 1.0), + ('two-sided', 0.2983720970096, + 0.1266555521019559, 0.2918426890886281)]) + def test_confidence_intervals1(self, alternative, pval, ci_low, ci_high): + res = stats.binomtest(20, n=100, p=0.25, alternative=alternative) + assert_allclose(res.pvalue, pval, rtol=1e-12) + assert_equal(res.statistic, 0.2) + ci = res.proportion_ci(confidence_level=0.95) + assert_allclose((ci.low, ci.high), (ci_low, ci_high), rtol=1e-12) + + # Expected results here are from R 3.6.2 binom.test. + @pytest.mark.parametrize('alternative, pval, ci_low, ci_high', + [('less', + 0.005656361, 0.0, 0.1872093), + ('greater', + 0.9987146, 0.008860761, 1.0), + ('two-sided', + 0.01191714, 0.006872485, 0.202706269)]) + def test_confidence_intervals2(self, alternative, pval, ci_low, ci_high): + res = stats.binomtest(3, n=50, p=0.2, alternative=alternative) + assert_allclose(res.pvalue, pval, rtol=1e-6) + assert_equal(res.statistic, 0.06) + ci = res.proportion_ci(confidence_level=0.99) + assert_allclose((ci.low, ci.high), (ci_low, ci_high), rtol=1e-6) + + # Expected results here are from R 3.6.2 binom.test. + @pytest.mark.parametrize('alternative, pval, ci_high', + [('less', 0.05631351, 0.2588656), + ('greater', 1.0, 1.0), + ('two-sided', 0.07604122, 0.3084971)]) + def test_confidence_interval_exact_k0(self, alternative, pval, ci_high): + # Test with k=0, n = 10. + res = stats.binomtest(0, 10, p=0.25, alternative=alternative) + assert_allclose(res.pvalue, pval, rtol=1e-6) + ci = res.proportion_ci(confidence_level=0.95) + assert_equal(ci.low, 0.0) + assert_allclose(ci.high, ci_high, rtol=1e-6) + + # Expected results here are from R 3.6.2 binom.test. + @pytest.mark.parametrize('alternative, pval, ci_low', + [('less', 1.0, 0.0), + ('greater', 9.536743e-07, 0.7411344), + ('two-sided', 9.536743e-07, 0.6915029)]) + def test_confidence_interval_exact_k_is_n(self, alternative, pval, ci_low): + # Test with k = n = 10. + res = stats.binomtest(10, 10, p=0.25, alternative=alternative) + assert_allclose(res.pvalue, pval, rtol=1e-6) + ci = res.proportion_ci(confidence_level=0.95) + assert_equal(ci.high, 1.0) + assert_allclose(ci.low, ci_low, rtol=1e-6) + + # Expected results are from the prop.test function in R 3.6.2. + @pytest.mark.parametrize( + 'k, alternative, corr, conf, ci_low, ci_high', + [[3, 'two-sided', True, 0.95, 0.08094782, 0.64632928], + [3, 'two-sided', True, 0.99, 0.0586329, 0.7169416], + [3, 'two-sided', False, 0.95, 0.1077913, 0.6032219], + [3, 'two-sided', False, 0.99, 0.07956632, 0.6799753], + [3, 'less', True, 0.95, 0.0, 0.6043476], + [3, 'less', True, 0.99, 0.0, 0.6901811], + [3, 'less', False, 0.95, 0.0, 0.5583002], + [3, 'less', False, 0.99, 0.0, 0.6507187], + [3, 'greater', True, 0.95, 0.09644904, 1.0], + [3, 'greater', True, 0.99, 0.06659141, 1.0], + [3, 'greater', False, 0.95, 0.1268766, 1.0], + [3, 'greater', False, 0.99, 0.08974147, 1.0], + + [0, 'two-sided', True, 0.95, 0.0, 0.3445372], + [0, 'two-sided', False, 0.95, 0.0, 0.2775328], + [0, 'less', True, 0.95, 0.0, 0.2847374], + [0, 'less', False, 0.95, 0.0, 0.212942], + [0, 'greater', True, 0.95, 0.0, 1.0], + [0, 'greater', False, 0.95, 0.0, 1.0], + + [10, 'two-sided', True, 0.95, 0.6554628, 1.0], + [10, 'two-sided', False, 0.95, 0.7224672, 1.0], + [10, 'less', True, 0.95, 0.0, 1.0], + [10, 'less', False, 0.95, 0.0, 1.0], + [10, 'greater', True, 0.95, 0.7152626, 1.0], + [10, 'greater', False, 0.95, 0.787058, 1.0]] + ) + def test_ci_wilson_method(self, k, alternative, corr, conf, + ci_low, ci_high): + res = stats.binomtest(k, n=10, p=0.1, alternative=alternative) + if corr: + method = 'wilsoncc' + else: + method = 'wilson' + ci = res.proportion_ci(confidence_level=conf, method=method) + assert_allclose((ci.low, ci.high), (ci_low, ci_high), rtol=1e-6) + + def test_estimate_equals_hypothesized_prop(self): + # Test the special case where the estimated proportion equals + # the hypothesized proportion. When alternative is 'two-sided', + # the p-value is 1. + res = stats.binomtest(4, 16, 0.25) + assert_equal(res.statistic, 0.25) + assert_equal(res.pvalue, 1.0) + + @pytest.mark.parametrize('k, n', [(0, 0), (-1, 2)]) + def test_invalid_k_n(self, k, n): + with pytest.raises(ValueError, + match="must be an integer not less than"): + stats.binomtest(k, n) + + def test_invalid_k_too_big(self): + with pytest.raises(ValueError, + match=r"k \(11\) must not be greater than n \(10\)."): + stats.binomtest(11, 10, 0.25) + + def test_invalid_k_wrong_type(self): + with pytest.raises(TypeError, + match="k must be an integer."): + stats.binomtest([10, 11], 21, 0.25) + + def test_invalid_p_range(self): + message = r'p \(-0.5\) must be in range...' + with pytest.raises(ValueError, match=message): + stats.binomtest(50, 150, p=-0.5) + message = r'p \(1.5\) must be in range...' + with pytest.raises(ValueError, match=message): + stats.binomtest(50, 150, p=1.5) + + def test_invalid_confidence_level(self): + res = stats.binomtest(3, n=10, p=0.1) + message = r"confidence_level \(-1\) must be in the interval" + with pytest.raises(ValueError, match=message): + res.proportion_ci(confidence_level=-1) + + def test_invalid_ci_method(self): + res = stats.binomtest(3, n=10, p=0.1) + with pytest.raises(ValueError, match=r"method \('plate of shrimp'\) must be"): + res.proportion_ci(method="plate of shrimp") + + def test_invalid_alternative(self): + with pytest.raises(ValueError, match=r"alternative \('ekki'\) not..."): + stats.binomtest(3, n=10, p=0.1, alternative='ekki') + + def test_alias(self): + res = stats.binomtest(3, n=10, p=0.1) + assert_equal(res.proportion_estimate, res.statistic) + + @pytest.mark.skipif(sys.maxsize <= 2**32, reason="32-bit does not overflow") + def test_boost_overflow_raises(self): + # Boost.Math error policy should raise exceptions in Python + with pytest.raises(OverflowError, match='Error in function...'): + stats.binomtest(5, 6, p=sys.float_info.min) + + +class TestFligner: + + def test_data(self): + # numbers from R: fligner.test in package stats + x1 = np.arange(5) + assert_array_almost_equal(stats.fligner(x1, x1**2), + (3.2282229927203536, 0.072379187848207877), + 11) + + def test_trimmed1(self): + # Perturb input to break ties in the transformed data + # See https://github.com/scipy/scipy/pull/8042 for more details + rs = np.random.RandomState(123) + + def _perturb(g): + return (np.asarray(g) + 1e-10 * rs.randn(len(g))).tolist() + + g1_ = _perturb(g1) + g2_ = _perturb(g2) + g3_ = _perturb(g3) + # Test that center='trimmed' gives the same result as center='mean' + # when proportiontocut=0. + Xsq1, pval1 = stats.fligner(g1_, g2_, g3_, center='mean') + Xsq2, pval2 = stats.fligner(g1_, g2_, g3_, center='trimmed', + proportiontocut=0.0) + assert_almost_equal(Xsq1, Xsq2) + assert_almost_equal(pval1, pval2) + + def test_trimmed2(self): + x = [1.2, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100.0] + y = [0.0, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 200.0] + # Use center='trimmed' + Xsq1, pval1 = stats.fligner(x, y, center='trimmed', + proportiontocut=0.125) + # Trim the data here, and use center='mean' + Xsq2, pval2 = stats.fligner(x[1:-1], y[1:-1], center='mean') + # Result should be the same. + assert_almost_equal(Xsq1, Xsq2) + assert_almost_equal(pval1, pval2) + + # The following test looks reasonable at first, but fligner() uses the + # function stats.rankdata(), and in one of the cases in this test, + # there are ties, while in the other (because of normal rounding + # errors) there are not. This difference leads to differences in the + # third significant digit of W. + # + #def test_equal_mean_median(self): + # x = np.linspace(-1,1,21) + # y = x**3 + # W1, pval1 = stats.fligner(x, y, center='mean') + # W2, pval2 = stats.fligner(x, y, center='median') + # assert_almost_equal(W1, W2) + # assert_almost_equal(pval1, pval2) + + def test_bad_keyword(self): + x = np.linspace(-1, 1, 21) + assert_raises(TypeError, stats.fligner, x, x, portiontocut=0.1) + + def test_bad_center_value(self): + x = np.linspace(-1, 1, 21) + assert_raises(ValueError, stats.fligner, x, x, center='trim') + + def test_bad_num_args(self): + # Too few args raises ValueError. + assert_raises(ValueError, stats.fligner, [1]) + + def test_empty_arg(self): + x = np.arange(5) + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.fligner(x, x**2, []) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + +def mood_cases_with_ties(): + # Generate random `x` and `y` arrays with ties both between and within the + # samples. Expected results are (statistic, pvalue) from SAS. + expected_results = [(-1.76658511464992, .0386488678399305), + (-.694031428192304, .2438312498647250), + (-1.15093525352151, .1248794365836150)] + seeds = [23453254, 1298352315, 987234597] + for si, seed in enumerate(seeds): + rng = np.random.default_rng(seed) + xy = rng.random(100) + # Generate random indices to make ties + tie_ind = rng.integers(low=0, high=99, size=5) + # Generate a random number of ties for each index. + num_ties_per_ind = rng.integers(low=1, high=5, size=5) + # At each `tie_ind`, mark the next `n` indices equal to that value. + for i, n in zip(tie_ind, num_ties_per_ind): + for j in range(i + 1, i + n): + xy[j] = xy[i] + # scramble order of xy before splitting into `x, y` + rng.shuffle(xy) + x, y = np.split(xy, 2) + yield x, y, 'less', *expected_results[si] + + +class TestMood: + @pytest.mark.parametrize("x,y,alternative,stat_expect,p_expect", + mood_cases_with_ties()) + def test_against_SAS(self, x, y, alternative, stat_expect, p_expect): + """ + Example code used to generate SAS output: + DATA myData; + INPUT X Y; + CARDS; + 1 0 + 1 1 + 1 2 + 1 3 + 1 4 + 2 0 + 2 1 + 2 4 + 2 9 + 2 16 + ods graphics on; + proc npar1way mood data=myData ; + class X; + ods output MoodTest=mt; + proc contents data=mt; + proc print data=mt; + format Prob1 17.16 Prob2 17.16 Statistic 17.16 Z 17.16 ; + title "Mood Two-Sample Test"; + proc print data=myData; + title "Data for above results"; + run; + """ + statistic, pvalue = stats.mood(x, y, alternative=alternative) + assert_allclose(stat_expect, statistic, atol=1e-16) + assert_allclose(p_expect, pvalue, atol=1e-16) + + @pytest.mark.parametrize("alternative, expected", + [('two-sided', (1.019938533549930, + .3077576129778760)), + ('less', (1.019938533549930, + 1 - .1538788064889380)), + ('greater', (1.019938533549930, + .1538788064889380))]) + def test_against_SAS_2(self, alternative, expected): + # Code to run in SAS in above function + x = [111, 107, 100, 99, 102, 106, 109, 108, 104, 99, + 101, 96, 97, 102, 107, 113, 116, 113, 110, 98] + y = [107, 108, 106, 98, 105, 103, 110, 105, 104, 100, + 96, 108, 103, 104, 114, 114, 113, 108, 106, 99] + res = stats.mood(x, y, alternative=alternative) + assert_allclose(res, expected) + + def test_mood_order_of_args(self): + # z should change sign when the order of arguments changes, pvalue + # should not change + np.random.seed(1234) + x1 = np.random.randn(10, 1) + x2 = np.random.randn(15, 1) + z1, p1 = stats.mood(x1, x2) + z2, p2 = stats.mood(x2, x1) + assert_array_almost_equal([z1, p1], [-z2, p2]) + + def test_mood_with_axis_none(self): + # Test with axis = None, compare with results from R + x1 = [-0.626453810742332, 0.183643324222082, -0.835628612410047, + 1.59528080213779, 0.329507771815361, -0.820468384118015, + 0.487429052428485, 0.738324705129217, 0.575781351653492, + -0.305388387156356, 1.51178116845085, 0.389843236411431, + -0.621240580541804, -2.2146998871775, 1.12493091814311, + -0.0449336090152309, -0.0161902630989461, 0.943836210685299, + 0.821221195098089, 0.593901321217509] + + x2 = [-0.896914546624981, 0.184849184646742, 1.58784533120882, + -1.13037567424629, -0.0802517565509893, 0.132420284381094, + 0.707954729271733, -0.23969802417184, 1.98447393665293, + -0.138787012119665, 0.417650750792556, 0.981752777463662, + -0.392695355503813, -1.03966897694891, 1.78222896030858, + -2.31106908460517, 0.878604580921265, 0.035806718015226, + 1.01282869212708, 0.432265154539617, 2.09081920524915, + -1.19992581964387, 1.58963820029007, 1.95465164222325, + 0.00493777682814261, -2.45170638784613, 0.477237302613617, + -0.596558168631403, 0.792203270299649, 0.289636710177348] + + x1 = np.array(x1) + x2 = np.array(x2) + x1.shape = (10, 2) + x2.shape = (15, 2) + assert_array_almost_equal(stats.mood(x1, x2, axis=None), + [-1.31716607555, 0.18778296257]) + + def test_mood_2d(self): + # Test if the results of mood test in 2-D case are consistent with the + # R result for the same inputs. Numbers from R mood.test(). + ny = 5 + np.random.seed(1234) + x1 = np.random.randn(10, ny) + x2 = np.random.randn(15, ny) + z_vectest, pval_vectest = stats.mood(x1, x2) + + for j in range(ny): + assert_array_almost_equal([z_vectest[j], pval_vectest[j]], + stats.mood(x1[:, j], x2[:, j])) + + # inverse order of dimensions + x1 = x1.transpose() + x2 = x2.transpose() + z_vectest, pval_vectest = stats.mood(x1, x2, axis=1) + + for i in range(ny): + # check axis handling is self consistent + assert_array_almost_equal([z_vectest[i], pval_vectest[i]], + stats.mood(x1[i, :], x2[i, :])) + + def test_mood_3d(self): + shape = (10, 5, 6) + np.random.seed(1234) + x1 = np.random.randn(*shape) + x2 = np.random.randn(*shape) + + for axis in range(3): + z_vectest, pval_vectest = stats.mood(x1, x2, axis=axis) + # Tests that result for 3-D arrays is equal to that for the + # same calculation on a set of 1-D arrays taken from the + # 3-D array + axes_idx = ([1, 2], [0, 2], [0, 1]) # the two axes != axis + for i in range(shape[axes_idx[axis][0]]): + for j in range(shape[axes_idx[axis][1]]): + if axis == 0: + slice1 = x1[:, i, j] + slice2 = x2[:, i, j] + elif axis == 1: + slice1 = x1[i, :, j] + slice2 = x2[i, :, j] + else: + slice1 = x1[i, j, :] + slice2 = x2[i, j, :] + + assert_array_almost_equal([z_vectest[i, j], + pval_vectest[i, j]], + stats.mood(slice1, slice2)) + + def test_mood_bad_arg(self): + # Warns when the sum of the lengths of the args is less than 3 + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.mood([1], []) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_mood_alternative(self): + + np.random.seed(0) + x = stats.norm.rvs(scale=0.75, size=100) + y = stats.norm.rvs(scale=1.25, size=100) + + stat1, p1 = stats.mood(x, y, alternative='two-sided') + stat2, p2 = stats.mood(x, y, alternative='less') + stat3, p3 = stats.mood(x, y, alternative='greater') + + assert stat1 == stat2 == stat3 + assert_allclose(p1, 0, atol=1e-7) + assert_allclose(p2, p1/2) + assert_allclose(p3, 1 - p1/2) + + with pytest.raises(ValueError, match="`alternative` must be..."): + stats.mood(x, y, alternative='ekki-ekki') + + @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater']) + def test_result(self, alternative): + rng = np.random.default_rng(265827767938813079281100964083953437622) + x1 = rng.standard_normal((10, 1)) + x2 = rng.standard_normal((15, 1)) + + res = stats.mood(x1, x2, alternative=alternative) + assert_equal((res.statistic, res.pvalue), res) + + +class TestProbplot: + + def test_basic(self): + x = stats.norm.rvs(size=20, random_state=12345) + osm, osr = stats.probplot(x, fit=False) + osm_expected = [-1.8241636, -1.38768012, -1.11829229, -0.91222575, + -0.73908135, -0.5857176, -0.44506467, -0.31273668, + -0.18568928, -0.06158146, 0.06158146, 0.18568928, + 0.31273668, 0.44506467, 0.5857176, 0.73908135, + 0.91222575, 1.11829229, 1.38768012, 1.8241636] + assert_allclose(osr, np.sort(x)) + assert_allclose(osm, osm_expected) + + res, res_fit = stats.probplot(x, fit=True) + res_fit_expected = [1.05361841, 0.31297795, 0.98741609] + assert_allclose(res_fit, res_fit_expected) + + def test_sparams_keyword(self): + x = stats.norm.rvs(size=100, random_state=123456) + # Check that None, () and 0 (loc=0, for normal distribution) all work + # and give the same results + osm1, osr1 = stats.probplot(x, sparams=None, fit=False) + osm2, osr2 = stats.probplot(x, sparams=0, fit=False) + osm3, osr3 = stats.probplot(x, sparams=(), fit=False) + assert_allclose(osm1, osm2) + assert_allclose(osm1, osm3) + assert_allclose(osr1, osr2) + assert_allclose(osr1, osr3) + # Check giving (loc, scale) params for normal distribution + osm, osr = stats.probplot(x, sparams=(), fit=False) + + def test_dist_keyword(self): + x = stats.norm.rvs(size=20, random_state=12345) + osm1, osr1 = stats.probplot(x, fit=False, dist='t', sparams=(3,)) + osm2, osr2 = stats.probplot(x, fit=False, dist=stats.t, sparams=(3,)) + assert_allclose(osm1, osm2) + assert_allclose(osr1, osr2) + + assert_raises(ValueError, stats.probplot, x, dist='wrong-dist-name') + assert_raises(AttributeError, stats.probplot, x, dist=[]) + + class custom_dist: + """Some class that looks just enough like a distribution.""" + def ppf(self, q): + return stats.norm.ppf(q, loc=2) + + osm1, osr1 = stats.probplot(x, sparams=(2,), fit=False) + osm2, osr2 = stats.probplot(x, dist=custom_dist(), fit=False) + assert_allclose(osm1, osm2) + assert_allclose(osr1, osr2) + + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_plot_kwarg(self): + fig = plt.figure() + fig.add_subplot(111) + x = stats.t.rvs(3, size=100, random_state=7654321) + res1, fitres1 = stats.probplot(x, plot=plt) + plt.close() + res2, fitres2 = stats.probplot(x, plot=None) + res3 = stats.probplot(x, fit=False, plot=plt) + plt.close() + res4 = stats.probplot(x, fit=False, plot=None) + # Check that results are consistent between combinations of `fit` and + # `plot` keywords. + assert_(len(res1) == len(res2) == len(res3) == len(res4) == 2) + assert_allclose(res1, res2) + assert_allclose(res1, res3) + assert_allclose(res1, res4) + assert_allclose(fitres1, fitres2) + + # Check that a Matplotlib Axes object is accepted + fig = plt.figure() + ax = fig.add_subplot(111) + stats.probplot(x, fit=False, plot=ax) + plt.close() + + def test_probplot_bad_args(self): + # Raise ValueError when given an invalid distribution. + assert_raises(ValueError, stats.probplot, [1], dist="plate_of_shrimp") + + def test_empty(self): + assert_equal(stats.probplot([], fit=False), + (np.array([]), np.array([]))) + assert_equal(stats.probplot([], fit=True), + ((np.array([]), np.array([])), + (np.nan, np.nan, 0.0))) + + def test_array_of_size_one(self): + with np.errstate(invalid='ignore'): + assert_equal(stats.probplot([1], fit=True), + ((np.array([0.]), np.array([1])), + (np.nan, np.nan, 0.0))) + + +class TestWilcoxon: + def test_wilcoxon_bad_arg(self): + # Raise ValueError when two args of different lengths are given or + # zero_method is unknown. + assert_raises(ValueError, stats.wilcoxon, [1, 2], [1, 2], "dummy") + assert_raises(ValueError, stats.wilcoxon, [1, 2], [1, 2], + alternative="dummy") + assert_raises(ValueError, stats.wilcoxon, [1]*10, method="xyz") + + def test_zero_diff(self): + x = np.arange(20) + # pratt and wilcox do not work if x - y == 0 and method == "asymptotic" + # => warning may be emitted and p-value is nan + with np.errstate(invalid="ignore"): + w, p = stats.wilcoxon(x, x, "wilcox", method="asymptotic") + assert_equal((w, p), (0.0, np.nan)) + w, p = stats.wilcoxon(x, x, "pratt", method="asymptotic") + assert_equal((w, p), (0.0, np.nan)) + # ranksum is n*(n+1)/2, split in half if zero_method == "zsplit" + assert_equal(stats.wilcoxon(x, x, "zsplit", method="asymptotic"), + (20*21/4, 1.0)) + + def test_pratt(self): + # regression test for gh-6805: p-value matches value from R package + # coin (wilcoxsign_test) reported in the issue + x = [1, 2, 3, 4] + y = [1, 2, 3, 5] + res = stats.wilcoxon(x, y, zero_method="pratt", method="asymptotic", + correction=False) + assert_allclose(res, (0.0, 0.31731050786291415)) + + def test_wilcoxon_arg_type(self): + # Should be able to accept list as arguments. + # Address issue 6070. + arr = [1, 2, 3, 0, -1, 3, 1, 2, 1, 1, 2] + + _ = stats.wilcoxon(arr, zero_method="pratt", method="asymptotic") + _ = stats.wilcoxon(arr, zero_method="zsplit", method="asymptotic") + _ = stats.wilcoxon(arr, zero_method="wilcox", method="asymptotic") + + def test_accuracy_wilcoxon(self): + freq = [1, 4, 16, 15, 8, 4, 5, 1, 2] + nums = range(-4, 5) + x = np.concatenate([[u] * v for u, v in zip(nums, freq)]) + y = np.zeros(x.size) + + T, p = stats.wilcoxon(x, y, "pratt", method="asymptotic", + correction=False) + assert_allclose(T, 423) + assert_allclose(p, 0.0031724568006762576) + + T, p = stats.wilcoxon(x, y, "zsplit", method="asymptotic", + correction=False) + assert_allclose(T, 441) + assert_allclose(p, 0.0032145343172473055) + + T, p = stats.wilcoxon(x, y, "wilcox", method="asymptotic", + correction=False) + assert_allclose(T, 327) + assert_allclose(p, 0.00641346115861) + + # Test the 'correction' option, using values computed in R with: + # > wilcox.test(x, y, paired=TRUE, exact=FALSE, correct={FALSE,TRUE}) + x = np.array([120, 114, 181, 188, 180, 146, 121, 191, 132, 113, 127, 112]) + y = np.array([133, 143, 119, 189, 112, 199, 198, 113, 115, 121, 142, 187]) + T, p = stats.wilcoxon(x, y, correction=False, method="asymptotic") + assert_equal(T, 34) + assert_allclose(p, 0.6948866, rtol=1e-6) + T, p = stats.wilcoxon(x, y, correction=True, method="asymptotic") + assert_equal(T, 34) + assert_allclose(p, 0.7240817, rtol=1e-6) + + def test_approx_mode(self): + # Check that `mode` is still an alias of keyword `method`, + # and `"approx"` is still an alias of argument `"asymptotic"` + x = np.array([3, 5, 23, 7, 243, 58, 98, 2, 8, -3, 9, 11]) + y = np.array([2, -2, 1, 23, 0, 5, 12, 18, 99, 12, 17, 27]) + res1 = stats.wilcoxon(x, y, "wilcox", method="approx") + res2 = stats.wilcoxon(x, y, "wilcox", method="asymptotic") + res3 = stats.wilcoxon(x, y, "wilcox", mode="approx") + res4 = stats.wilcoxon(x, y, "wilcox", mode="asymptotic") + assert res1 == res2 == res3 == res4 + + def test_wilcoxon_result_attributes(self): + x = np.array([120, 114, 181, 188, 180, 146, 121, 191, 132, 113, 127, 112]) + y = np.array([133, 143, 119, 189, 112, 199, 198, 113, 115, 121, 142, 187]) + res = stats.wilcoxon(x, y, correction=False, method="asymptotic") + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes) + + def test_wilcoxon_has_zstatistic(self): + rng = np.random.default_rng(89426135444) + x, y = rng.random(15), rng.random(15) + + res = stats.wilcoxon(x, y, method="asymptotic") + ref = stats.norm.ppf(res.pvalue/2) + assert_allclose(res.zstatistic, ref) + + res = stats.wilcoxon(x, y, method="exact") + assert not hasattr(res, 'zstatistic') + + res = stats.wilcoxon(x, y) + assert not hasattr(res, 'zstatistic') + + def test_wilcoxon_tie(self): + # Regression test for gh-2391. + # Corresponding R code is: + # > result = wilcox.test(rep(0.1, 10), exact=FALSE, correct=FALSE) + # > result$p.value + # [1] 0.001565402 + # > result = wilcox.test(rep(0.1, 10), exact=FALSE, correct=TRUE) + # > result$p.value + # [1] 0.001904195 + stat, p = stats.wilcoxon([0.1] * 10, method="asymptotic", + correction=False) + expected_p = 0.001565402 + assert_equal(stat, 0) + assert_allclose(p, expected_p, rtol=1e-6) + + stat, p = stats.wilcoxon([0.1] * 10, correction=True, + method="asymptotic") + expected_p = 0.001904195 + assert_equal(stat, 0) + assert_allclose(p, expected_p, rtol=1e-6) + + def test_onesided(self): + # tested against "R version 3.4.1 (2017-06-30)" + # x <- c(125, 115, 130, 140, 140, 115, 140, 125, 140, 135) + # y <- c(110, 122, 125, 120, 140, 124, 123, 137, 135, 145) + # cfg <- list(x = x, y = y, paired = TRUE, exact = FALSE) + # do.call(wilcox.test, c(cfg, list(alternative = "less", correct = FALSE))) + # do.call(wilcox.test, c(cfg, list(alternative = "less", correct = TRUE))) + # do.call(wilcox.test, c(cfg, list(alternative = "greater", correct = FALSE))) + # do.call(wilcox.test, c(cfg, list(alternative = "greater", correct = TRUE))) + x = [125, 115, 130, 140, 140, 115, 140, 125, 140, 135] + y = [110, 122, 125, 120, 140, 124, 123, 137, 135, 145] + + w, p = stats.wilcoxon(x, y, alternative="less", method="asymptotic", + correction=False) + assert_equal(w, 27) + assert_almost_equal(p, 0.7031847, decimal=6) + + w, p = stats.wilcoxon(x, y, alternative="less", correction=True, + method="asymptotic") + assert_equal(w, 27) + assert_almost_equal(p, 0.7233656, decimal=6) + + w, p = stats.wilcoxon(x, y, alternative="greater", + method="asymptotic", correction=False) + assert_equal(w, 27) + assert_almost_equal(p, 0.2968153, decimal=6) + + w, p = stats.wilcoxon(x, y, alternative="greater", + correction=True, method="asymptotic") + assert_equal(w, 27) + assert_almost_equal(p, 0.3176447, decimal=6) + + def test_exact_basic(self): + for n in range(1, 51): + pmf1 = _get_wilcoxon_distr(n) + pmf2 = _get_wilcoxon_distr2(n) + assert_equal(n*(n+1)/2 + 1, len(pmf1)) + assert_equal(sum(pmf1), 1) + assert_array_almost_equal(pmf1, pmf2) + + def test_exact_pval(self): + # expected values computed with "R version 3.4.1 (2017-06-30)" + x = np.array([1.81, 0.82, 1.56, -0.48, 0.81, 1.28, -1.04, 0.23, + -0.75, 0.14]) + y = np.array([0.71, 0.65, -0.2, 0.85, -1.1, -0.45, -0.84, -0.24, + -0.68, -0.76]) + _, p = stats.wilcoxon(x, y, alternative="two-sided", method="exact") + assert_almost_equal(p, 0.1054688, decimal=6) + _, p = stats.wilcoxon(x, y, alternative="less", method="exact") + assert_almost_equal(p, 0.9580078, decimal=6) + _, p = stats.wilcoxon(x, y, alternative="greater", method="exact") + assert_almost_equal(p, 0.05273438, decimal=6) + + x = np.arange(0, 20) + 0.5 + y = np.arange(20, 0, -1) + _, p = stats.wilcoxon(x, y, alternative="two-sided", method="exact") + assert_almost_equal(p, 0.8694878, decimal=6) + _, p = stats.wilcoxon(x, y, alternative="less", method="exact") + assert_almost_equal(p, 0.4347439, decimal=6) + _, p = stats.wilcoxon(x, y, alternative="greater", method="exact") + assert_almost_equal(p, 0.5795889, decimal=6) + + # These inputs were chosen to give a W statistic that is either the + # center of the distribution (when the length of the support is odd), or + # the value to the left of the center (when the length of the support is + # even). Also, the numbers are chosen so that the W statistic is the + # sum of the positive values. + + @pytest.mark.parametrize('x', [[-1, -2, 3], + [-1, 2, -3, -4, 5], + [-1, -2, 3, -4, -5, -6, 7, 8]]) + def test_exact_p_1(self, x): + w, p = stats.wilcoxon(x) + x = np.array(x) + wtrue = x[x > 0].sum() + assert_equal(w, wtrue) + assert_equal(p, 1) + + def test_auto(self): + # auto default to exact if there are no ties and n <= 50 + x = np.arange(0, 50) + 0.5 + y = np.arange(50, 0, -1) + assert_equal(stats.wilcoxon(x, y), + stats.wilcoxon(x, y, method="exact")) + + # n <= 50: if there are zeros in d = x-y, use PermutationMethod + pm = stats.PermutationMethod() + d = np.arange(-2, 5) + w, p = stats.wilcoxon(d) + # rerunning the test gives the same results since n_resamples + # is large enough to get deterministic results if n <= 13 + # so we do not need to use a seed. to avoid longer runtimes of the + # test, use n=7 only. For n=13, see test_auto_permutation_edge_case + assert_equal((w, p), stats.wilcoxon(d, method=pm)) + + # for larger vectors (n > 13) with ties/zeros, use asymptotic test + d = np.arange(-5, 9) # zero + w, p = stats.wilcoxon(d) + assert_equal((w, p), stats.wilcoxon(d, method="asymptotic")) + + d[d == 0] = 1 # tie + w, p = stats.wilcoxon(d) + assert_equal((w, p), stats.wilcoxon(d, method="asymptotic")) + + # use approximation for samples > 50 + d = np.arange(1, 52) + assert_equal(stats.wilcoxon(d), stats.wilcoxon(d, method="asymptotic")) + + @pytest.mark.xslow + def test_auto_permutation_edge_case(self): + # Check that `PermutationMethod()` is used and results are deterministic when + # `method='auto'`, there are zeros or ties in `d = x-y`, and `len(d) <= 13`. + d = np.arange(-5, 8) # zero + res = stats.wilcoxon(d) + ref = (27.5, 0.3955078125) # stats.wilcoxon(d, method=PermutationMethod()) + assert_equal(res, ref) + + d[d == 0] = 1 # tie + res = stats.wilcoxon(d) + ref = (32, 0.3779296875) # stats.wilcoxon(d, method=PermutationMethod()) + assert_equal(res, ref) + + @pytest.mark.parametrize('size', [3, 5, 10]) + def test_permutation_method(self, size): + rng = np.random.default_rng(92348034828501345) + x = rng.random(size=size) + res = stats.wilcoxon(x, method=stats.PermutationMethod()) + ref = stats.wilcoxon(x, method='exact') + assert_equal(res.statistic, ref.statistic) + assert_equal(res.pvalue, ref.pvalue) + + x = rng.random(size=size*10) + rng = np.random.default_rng(59234803482850134) + pm = stats.PermutationMethod(n_resamples=99, rng=rng) + ref = stats.wilcoxon(x, method=pm) + # preserve use of old random_state during SPEC 7 transition + rng = np.random.default_rng(59234803482850134) + pm = stats.PermutationMethod(n_resamples=99, random_state=rng) + res = stats.wilcoxon(x, method=pm) + + assert_equal(np.round(res.pvalue, 2), res.pvalue) # n_resamples used + assert_equal(res.pvalue, ref.pvalue) # rng/random_state used + + def test_method_auto_nan_propagate_ND_length_gt_50_gh20591(self): + # When method!='asymptotic', nan_policy='propagate', and a slice of + # a >1 dimensional array input contained NaN, the result object of + # `wilcoxon` could (under yet other conditions) return `zstatistic` + # for some slices but not others. This resulted in an error because + # `apply_along_axis` would have to create a ragged array. + # Check that this is resolved. + rng = np.random.default_rng(235889269872456) + A = rng.normal(size=(51, 2)) # length along slice > exact threshold + A[5, 1] = np.nan + res = stats.wilcoxon(A) + ref = stats.wilcoxon(A, method='asymptotic') + assert_allclose(res, ref) + assert hasattr(ref, 'zstatistic') + assert not hasattr(res, 'zstatistic') + + @pytest.mark.parametrize('method', ['exact', 'asymptotic']) + def test_symmetry_gh19872_gh20752(self, method): + # Check that one-sided exact tests obey required symmetry. Bug reported + # in gh-19872 and again in gh-20752; example from gh-19872 is more concise: + var1 = [62, 66, 61, 68, 74, 62, 68, 62, 55, 59] + var2 = [71, 71, 69, 61, 75, 71, 77, 72, 62, 65] + ref = stats.wilcoxon(var1, var2, alternative='less', method=method) + res = stats.wilcoxon(var2, var1, alternative='greater', method=method) + max_statistic = len(var1) * (len(var1) + 1) / 2 + assert int(res.statistic) != res.statistic + assert_allclose(max_statistic - res.statistic, ref.statistic, rtol=1e-15) + assert_allclose(res.pvalue, ref.pvalue, rtol=1e-15) + + @pytest.mark.parametrize("method", ('exact', stats.PermutationMethod())) + def test_all_zeros_exact(self, method): + # previously, this raised a RuntimeWarning when calculating Z, even + # when the Z value was not needed. Confirm that this no longer + # occurs when `method` is 'exact' or a `PermutationMethod`. + res = stats.wilcoxon(np.zeros(5), method=method) + assert_allclose(res, [0, 1]) + + +# data for k-statistics tests from +# https://cran.r-project.org/web/packages/kStatistics/kStatistics.pdf +# see nKS "Examples" +x_kstat = [16.34, 10.76, 11.84, 13.55, 15.85, 18.20, 7.51, 10.22, 12.52, 14.68, + 16.08, 19.43, 8.12, 11.20, 12.95, 14.77, 16.83, 19.80, 8.55, 11.58, + 12.10, 15.02, 16.83, 16.98, 19.92, 9.47, 11.68, 13.41, 15.35, 19.11] + + +@array_api_compatible +class TestKstat: + def test_moments_normal_distribution(self, xp): + np.random.seed(32149) + data = xp.asarray(np.random.randn(12345), dtype=xp.float64) + moments = xp.asarray([stats.kstat(data, n) for n in [1, 2, 3, 4]]) + + expected = xp.asarray([0.011315, 1.017931, 0.05811052, 0.0754134], + dtype=data.dtype) + xp_assert_close(moments, expected, rtol=1e-4) + + # test equivalence with `stats.moment` + m1 = stats.moment(data, order=1) + m2 = stats.moment(data, order=2) + m3 = stats.moment(data, order=3) + xp_assert_close(xp.asarray((m1, m2, m3)), expected[:-1], atol=0.02, rtol=1e-2) + + def test_empty_input(self, xp): + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.kstat(xp.asarray([])) + else: + with np.errstate(invalid='ignore'): # for array_api_strict + res = stats.kstat(xp.asarray([])) + xp_assert_equal(res, xp.asarray(xp.nan)) + + def test_nan_input(self, xp): + data = xp.arange(10.) + data = xp.where(data == 6, xp.asarray(xp.nan), data) + + xp_assert_equal(stats.kstat(data), xp.asarray(xp.nan)) + + @pytest.mark.parametrize('n', [0, 4.001]) + def test_kstat_bad_arg(self, n, xp): + # Raise ValueError if n > 4 or n < 1. + data = xp.arange(10) + message = 'k-statistics only supported for 1<=n<=4' + with pytest.raises(ValueError, match=message): + stats.kstat(data, n=n) + + @pytest.mark.parametrize('case', [(1, 14.02166666666667), + (2, 12.65006954022974), + (3, -1.447059503280798), + (4, -141.6682291883626)]) + def test_against_R(self, case, xp): + # Test against reference values computed with R kStatistics, e.g. + # options(digits=16) + # library(kStatistics) + # data <-c (16.34, 10.76, 11.84, 13.55, 15.85, 18.20, 7.51, 10.22, + # 12.52, 14.68, 16.08, 19.43, 8.12, 11.20, 12.95, 14.77, + # 16.83, 19.80, 8.55, 11.58, 12.10, 15.02, 16.83, 16.98, + # 19.92, 9.47, 11.68, 13.41, 15.35, 19.11) + # nKS(4, data) + n, ref = case + res = stats.kstat(xp.asarray(x_kstat), n) + xp_assert_close(res, xp.asarray(ref)) + + +@array_api_compatible +class TestKstatVar: + def test_empty_input(self, xp): + x = xp.asarray([]) + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.kstatvar(x) + else: + with np.errstate(invalid='ignore'): # for array_api_strict + res = stats.kstatvar(x) + xp_assert_equal(res, xp.asarray(xp.nan)) + + def test_nan_input(self, xp): + data = xp.arange(10.) + data = xp.where(data == 6, xp.asarray(xp.nan), data) + + xp_assert_equal(stats.kstat(data), xp.asarray(xp.nan)) + + @skip_xp_backends(np_only=True, + reason='input validation of `n` does not depend on backend') + @pytest.mark.usefixtures("skip_xp_backends") + def test_bad_arg(self): + # Raise ValueError is n is not 1 or 2. + data = [1] + n = 10 + message = 'Only n=1 or n=2 supported.' + with pytest.raises(ValueError, match=message): + stats.kstatvar(data, n=n) + + def test_against_R_mathworld(self, xp): + # Test against reference values computed using formulas exactly as + # they appear at https://mathworld.wolfram.com/k-Statistic.html + # This is *really* similar to how they appear in the implementation, + # but that could change, and this should not. + n = len(x_kstat) + k2 = 12.65006954022974 # see source code in TestKstat + k4 = -141.6682291883626 + + res = stats.kstatvar(xp.asarray(x_kstat), 1) + ref = k2 / n + xp_assert_close(res, xp.asarray(ref)) + + res = stats.kstatvar(xp.asarray(x_kstat), 2) + # *unbiased estimator* for var(k2) + ref = (2*k2**2*n + (n-1)*k4) / (n * (n+1)) + xp_assert_close(res, xp.asarray(ref)) + + +class TestPpccPlot: + def setup_method(self): + self.x = _old_loggamma_rvs(5, size=500, random_state=7654321) + 5 + + def test_basic(self): + N = 5 + svals, ppcc = stats.ppcc_plot(self.x, -10, 10, N=N) + ppcc_expected = [0.21139644, 0.21384059, 0.98766719, 0.97980182, + 0.93519298] + assert_allclose(svals, np.linspace(-10, 10, num=N)) + assert_allclose(ppcc, ppcc_expected) + + def test_dist(self): + # Test that we can specify distributions both by name and as objects. + svals1, ppcc1 = stats.ppcc_plot(self.x, -10, 10, dist='tukeylambda') + svals2, ppcc2 = stats.ppcc_plot(self.x, -10, 10, + dist=stats.tukeylambda) + assert_allclose(svals1, svals2, rtol=1e-20) + assert_allclose(ppcc1, ppcc2, rtol=1e-20) + # Test that 'tukeylambda' is the default dist + svals3, ppcc3 = stats.ppcc_plot(self.x, -10, 10) + assert_allclose(svals1, svals3, rtol=1e-20) + assert_allclose(ppcc1, ppcc3, rtol=1e-20) + + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_plot_kwarg(self): + # Check with the matplotlib.pyplot module + fig = plt.figure() + ax = fig.add_subplot(111) + stats.ppcc_plot(self.x, -20, 20, plot=plt) + fig.delaxes(ax) + + # Check that a Matplotlib Axes object is accepted + ax = fig.add_subplot(111) + stats.ppcc_plot(self.x, -20, 20, plot=ax) + plt.close() + + def test_invalid_inputs(self): + # `b` has to be larger than `a` + assert_raises(ValueError, stats.ppcc_plot, self.x, 1, 0) + + # Raise ValueError when given an invalid distribution. + assert_raises(ValueError, stats.ppcc_plot, [1, 2, 3], 0, 1, + dist="plate_of_shrimp") + + def test_empty(self): + # For consistency with probplot return for one empty array, + # ppcc contains all zeros and svals is the same as for normal array + # input. + svals, ppcc = stats.ppcc_plot([], 0, 1) + assert_allclose(svals, np.linspace(0, 1, num=80)) + assert_allclose(ppcc, np.zeros(80, dtype=float)) + + +class TestPpccMax: + def test_ppcc_max_bad_arg(self): + # Raise ValueError when given an invalid distribution. + data = [1] + assert_raises(ValueError, stats.ppcc_max, data, dist="plate_of_shrimp") + + def test_ppcc_max_basic(self): + x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000, + random_state=1234567) + 1e4 + assert_almost_equal(stats.ppcc_max(x), -0.71215366521264145, decimal=7) + + def test_dist(self): + x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000, + random_state=1234567) + 1e4 + + # Test that we can specify distributions both by name and as objects. + max1 = stats.ppcc_max(x, dist='tukeylambda') + max2 = stats.ppcc_max(x, dist=stats.tukeylambda) + assert_almost_equal(max1, -0.71215366521264145, decimal=5) + assert_almost_equal(max2, -0.71215366521264145, decimal=5) + + # Test that 'tukeylambda' is the default dist + max3 = stats.ppcc_max(x) + assert_almost_equal(max3, -0.71215366521264145, decimal=5) + + def test_brack(self): + x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000, + random_state=1234567) + 1e4 + assert_raises(ValueError, stats.ppcc_max, x, brack=(0.0, 1.0, 0.5)) + + assert_almost_equal(stats.ppcc_max(x, brack=(0, 1)), + -0.71215366521264145, decimal=7) + + assert_almost_equal(stats.ppcc_max(x, brack=(-2, 2)), + -0.71215366521264145, decimal=7) + + +@skip_xp_backends('jax.numpy', reason="JAX arrays do not support item assignment") +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +class TestBoxcox_llf: + + @pytest.mark.parametrize("dtype", ["float32", "float64"]) + def test_basic(self, dtype, xp): + dt = getattr(xp, dtype) + x = stats.norm.rvs(size=10000, loc=10, random_state=54321) + lmbda = 1 + llf = stats.boxcox_llf(lmbda, xp.asarray(x, dtype=dt)) + llf_expected = -x.size / 2. * np.log(np.sum(x.std()**2)) + xp_assert_close(llf, xp.asarray(llf_expected, dtype=dt)) + + @skip_xp_backends(np_only=True, + reason='array-likes only accepted for NumPy backend.') + def test_array_like(self, xp): + x = stats.norm.rvs(size=100, loc=10, random_state=54321) + lmbda = 1 + llf = stats.boxcox_llf(lmbda, x) + llf2 = stats.boxcox_llf(lmbda, list(x)) + xp_assert_close(llf, llf2, rtol=1e-12) + + def test_2d_input(self, xp): + # Note: boxcox_llf() was already working with 2-D input (sort of), so + # keep it like that. boxcox() doesn't work with 2-D input though, due + # to brent() returning a scalar. + x = stats.norm.rvs(size=100, loc=10, random_state=54321) + lmbda = 1 + llf = stats.boxcox_llf(lmbda, x) + llf2 = stats.boxcox_llf(lmbda, np.vstack([x, x]).T) + xp_assert_close(xp.asarray([llf, llf]), xp.asarray(llf2), rtol=1e-12) + + def test_empty(self, xp): + assert xp.isnan(xp.asarray(stats.boxcox_llf(1, xp.asarray([])))) + + def test_gh_6873(self, xp): + # Regression test for gh-6873. + # This example was taken from gh-7534, a duplicate of gh-6873. + data = xp.asarray([198.0, 233.0, 233.0, 392.0]) + llf = stats.boxcox_llf(-8, data) + # The expected value was computed with mpmath. + xp_assert_close(llf, xp.asarray(-17.93934208579061)) + + def test_instability_gh20021(self, xp): + data = xp.asarray([2003, 1950, 1997, 2000, 2009]) + llf = stats.boxcox_llf(1e-8, data) + # The expected value was computed with mpsci, set mpmath.mp.dps=100 + # expect float64 output for integer input + xp_assert_close(llf, xp.asarray(-15.32401272869016598, dtype=xp.float64)) + + +# This is the data from GitHub user Qukaiyi, given as an example +# of a data set that caused boxcox to fail. +_boxcox_data = [ + 15957, 112079, 1039553, 711775, 173111, 307382, 183155, 53366, 760875, + 207500, 160045, 473714, 40194, 440319, 133261, 265444, 155590, 36660, + 904939, 55108, 138391, 339146, 458053, 63324, 1377727, 1342632, 41575, + 68685, 172755, 63323, 368161, 199695, 538214, 167760, 388610, 398855, + 1001873, 364591, 1320518, 194060, 194324, 2318551, 196114, 64225, 272000, + 198668, 123585, 86420, 1925556, 695798, 88664, 46199, 759135, 28051, + 345094, 1977752, 51778, 82746, 638126, 2560910, 45830, 140576, 1603787, + 57371, 548730, 5343629, 2298913, 998813, 2156812, 423966, 68350, 145237, + 131935, 1600305, 342359, 111398, 1409144, 281007, 60314, 242004, 113418, + 246211, 61940, 95858, 957805, 40909, 307955, 174159, 124278, 241193, + 872614, 304180, 146719, 64361, 87478, 509360, 167169, 933479, 620561, + 483333, 97416, 143518, 286905, 597837, 2556043, 89065, 69944, 196858, + 88883, 49379, 916265, 1527392, 626954, 54415, 89013, 2883386, 106096, + 402697, 45578, 349852, 140379, 34648, 757343, 1305442, 2054757, 121232, + 606048, 101492, 51426, 1820833, 83412, 136349, 1379924, 505977, 1303486, + 95853, 146451, 285422, 2205423, 259020, 45864, 684547, 182014, 784334, + 174793, 563068, 170745, 1195531, 63337, 71833, 199978, 2330904, 227335, + 898280, 75294, 2011361, 116771, 157489, 807147, 1321443, 1148635, 2456524, + 81839, 1228251, 97488, 1051892, 75397, 3009923, 2732230, 90923, 39735, + 132433, 225033, 337555, 1204092, 686588, 1062402, 40362, 1361829, 1497217, + 150074, 551459, 2019128, 39581, 45349, 1117187, 87845, 1877288, 164448, + 10338362, 24942, 64737, 769946, 2469124, 2366997, 259124, 2667585, 29175, + 56250, 74450, 96697, 5920978, 838375, 225914, 119494, 206004, 430907, + 244083, 219495, 322239, 407426, 618748, 2087536, 2242124, 4736149, 124624, + 406305, 240921, 2675273, 4425340, 821457, 578467, 28040, 348943, 48795, + 145531, 52110, 1645730, 1768364, 348363, 85042, 2673847, 81935, 169075, + 367733, 135474, 383327, 1207018, 93481, 5934183, 352190, 636533, 145870, + 55659, 146215, 73191, 248681, 376907, 1606620, 169381, 81164, 246390, + 236093, 885778, 335969, 49266, 381430, 307437, 350077, 34346, 49340, + 84715, 527120, 40163, 46898, 4609439, 617038, 2239574, 159905, 118337, + 120357, 430778, 3799158, 3516745, 54198, 2970796, 729239, 97848, 6317375, + 887345, 58198, 88111, 867595, 210136, 1572103, 1420760, 574046, 845988, + 509743, 397927, 1119016, 189955, 3883644, 291051, 126467, 1239907, 2556229, + 411058, 657444, 2025234, 1211368, 93151, 577594, 4842264, 1531713, 305084, + 479251, 20591, 1466166, 137417, 897756, 594767, 3606337, 32844, 82426, + 1294831, 57174, 290167, 322066, 813146, 5671804, 4425684, 895607, 450598, + 1048958, 232844, 56871, 46113, 70366, 701618, 97739, 157113, 865047, + 194810, 1501615, 1765727, 38125, 2733376, 40642, 437590, 127337, 106310, + 4167579, 665303, 809250, 1210317, 45750, 1853687, 348954, 156786, 90793, + 1885504, 281501, 3902273, 359546, 797540, 623508, 3672775, 55330, 648221, + 266831, 90030, 7118372, 735521, 1009925, 283901, 806005, 2434897, 94321, + 309571, 4213597, 2213280, 120339, 64403, 8155209, 1686948, 4327743, + 1868312, 135670, 3189615, 1569446, 706058, 58056, 2438625, 520619, 105201, + 141961, 179990, 1351440, 3148662, 2804457, 2760144, 70775, 33807, 1926518, + 2362142, 186761, 240941, 97860, 1040429, 1431035, 78892, 484039, 57845, + 724126, 3166209, 175913, 159211, 1182095, 86734, 1921472, 513546, 326016, + 1891609 +] + + +class TestBoxcox: + + def test_fixed_lmbda(self): + x = _old_loggamma_rvs(5, size=50, random_state=12345) + 5 + xt = stats.boxcox(x, lmbda=1) + assert_allclose(xt, x - 1) + xt = stats.boxcox(x, lmbda=-1) + assert_allclose(xt, 1 - 1/x) + + xt = stats.boxcox(x, lmbda=0) + assert_allclose(xt, np.log(x)) + + # Also test that array_like input works + xt = stats.boxcox(list(x), lmbda=0) + assert_allclose(xt, np.log(x)) + + # test that constant input is accepted; see gh-12225 + xt = stats.boxcox(np.ones(10), 2) + assert_equal(xt, np.zeros(10)) + + def test_lmbda_None(self): + # Start from normal rv's, do inverse transform to check that + # optimization function gets close to the right answer. + lmbda = 2.5 + x = stats.norm.rvs(loc=10, size=50000, random_state=1245) + x_inv = (x * lmbda + 1)**(-lmbda) + xt, maxlog = stats.boxcox(x_inv) + + assert_almost_equal(maxlog, -1 / lmbda, decimal=2) + + def test_alpha(self): + rng = np.random.RandomState(1234) + x = _old_loggamma_rvs(5, size=50, random_state=rng) + 5 + + # Some regular values for alpha, on a small sample size + _, _, interval = stats.boxcox(x, alpha=0.75) + assert_allclose(interval, [4.004485780226041, 5.138756355035744]) + _, _, interval = stats.boxcox(x, alpha=0.05) + assert_allclose(interval, [1.2138178554857557, 8.209033272375663]) + + # Try some extreme values, see we don't hit the N=500 limit + x = _old_loggamma_rvs(7, size=500, random_state=rng) + 15 + _, _, interval = stats.boxcox(x, alpha=0.001) + assert_allclose(interval, [0.3988867, 11.40553131]) + _, _, interval = stats.boxcox(x, alpha=0.999) + assert_allclose(interval, [5.83316246, 5.83735292]) + + def test_boxcox_bad_arg(self): + # Raise ValueError if any data value is negative. + x = np.array([-1, 2]) + assert_raises(ValueError, stats.boxcox, x) + # Raise ValueError if data is constant. + assert_raises(ValueError, stats.boxcox, np.array([1])) + # Raise ValueError if data is not 1-dimensional. + assert_raises(ValueError, stats.boxcox, np.array([[1], [2]])) + + def test_empty(self): + assert_(stats.boxcox([]).shape == (0,)) + + def test_gh_6873(self): + # Regression test for gh-6873. + y, lam = stats.boxcox(_boxcox_data) + # The expected value of lam was computed with the function + # powerTransform in the R library 'car'. I trust that value + # to only about five significant digits. + assert_allclose(lam, -0.051654, rtol=1e-5) + + @pytest.mark.parametrize("bounds", [(-1, 1), (1.1, 2), (-2, -1.1)]) + def test_bounded_optimizer_within_bounds(self, bounds): + # Define custom optimizer with bounds. + def optimizer(fun): + return optimize.minimize_scalar(fun, bounds=bounds, + method="bounded") + + _, lmbda = stats.boxcox(_boxcox_data, lmbda=None, optimizer=optimizer) + assert bounds[0] < lmbda < bounds[1] + + def test_bounded_optimizer_against_unbounded_optimizer(self): + # Test whether setting bounds on optimizer excludes solution from + # unbounded optimizer. + + # Get unbounded solution. + _, lmbda = stats.boxcox(_boxcox_data, lmbda=None) + + # Set tolerance and bounds around solution. + bounds = (lmbda + 0.1, lmbda + 1) + options = {'xatol': 1e-12} + + def optimizer(fun): + return optimize.minimize_scalar(fun, bounds=bounds, + method="bounded", options=options) + + # Check bounded solution. Lower bound should be active. + _, lmbda_bounded = stats.boxcox(_boxcox_data, lmbda=None, + optimizer=optimizer) + assert lmbda_bounded != lmbda + assert_allclose(lmbda_bounded, bounds[0]) + + @pytest.mark.parametrize("optimizer", ["str", (1, 2), 0.1]) + def test_bad_optimizer_type_raises_error(self, optimizer): + # Check if error is raised if string, tuple or float is passed + with pytest.raises(ValueError, match="`optimizer` must be a callable"): + stats.boxcox(_boxcox_data, lmbda=None, optimizer=optimizer) + + def test_bad_optimizer_value_raises_error(self): + # Check if error is raised if `optimizer` function does not return + # `OptimizeResult` object + + # Define test function that always returns 1 + def optimizer(fun): + return 1 + + message = "return an object containing the optimal `lmbda`" + with pytest.raises(ValueError, match=message): + stats.boxcox(_boxcox_data, lmbda=None, optimizer=optimizer) + + @pytest.mark.parametrize( + "bad_x", [np.array([1, -42, 12345.6]), np.array([np.nan, 42, 1])] + ) + def test_negative_x_value_raises_error(self, bad_x): + """Test boxcox_normmax raises ValueError if x contains non-positive values.""" + message = "only positive, finite, real numbers" + with pytest.raises(ValueError, match=message): + stats.boxcox_normmax(bad_x) + + @pytest.mark.parametrize('x', [ + # Attempt to trigger overflow in power expressions. + np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0, + 2009.0, 1980.0, 1999.0, 2007.0, 1991.0]), + # Attempt to trigger overflow with a large optimal lambda. + np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0]), + # Attempt to trigger overflow with large data. + np.array([2003.0e200, 1950.0e200, 1997.0e200, 2000.0e200, 2009.0e200]) + ]) + def test_overflow(self, x): + with pytest.warns(UserWarning, match="The optimal lambda is"): + xt_bc, lam_bc = stats.boxcox(x) + assert np.all(np.isfinite(xt_bc)) + + +class TestBoxcoxNormmax: + def setup_method(self): + self.x = _old_loggamma_rvs(5, size=50, random_state=12345) + 5 + + def test_pearsonr(self): + maxlog = stats.boxcox_normmax(self.x) + assert_allclose(maxlog, 1.804465, rtol=1e-6) + + def test_mle(self): + maxlog = stats.boxcox_normmax(self.x, method='mle') + assert_allclose(maxlog, 1.758101, rtol=1e-6) + + # Check that boxcox() uses 'mle' + _, maxlog_boxcox = stats.boxcox(self.x) + assert_allclose(maxlog_boxcox, maxlog) + + def test_all(self): + maxlog_all = stats.boxcox_normmax(self.x, method='all') + assert_allclose(maxlog_all, [1.804465, 1.758101], rtol=1e-6) + + @pytest.mark.parametrize("method", ["mle", "pearsonr", "all"]) + @pytest.mark.parametrize("bounds", [(-1, 1), (1.1, 2), (-2, -1.1)]) + def test_bounded_optimizer_within_bounds(self, method, bounds): + + def optimizer(fun): + return optimize.minimize_scalar(fun, bounds=bounds, + method="bounded") + + maxlog = stats.boxcox_normmax(self.x, method=method, + optimizer=optimizer) + assert np.all(bounds[0] < maxlog) + assert np.all(maxlog < bounds[1]) + + @pytest.mark.slow + def test_user_defined_optimizer(self): + # tests an optimizer that is not based on scipy.optimize.minimize + lmbda = stats.boxcox_normmax(self.x) + lmbda_rounded = np.round(lmbda, 5) + lmbda_range = np.linspace(lmbda_rounded-0.01, lmbda_rounded+0.01, 1001) + + class MyResult: + pass + + def optimizer(fun): + # brute force minimum over the range + objs = [] + for lmbda in lmbda_range: + objs.append(fun(lmbda)) + res = MyResult() + res.x = lmbda_range[np.argmin(objs)] + return res + + lmbda2 = stats.boxcox_normmax(self.x, optimizer=optimizer) + assert lmbda2 != lmbda # not identical + assert_allclose(lmbda2, lmbda, 1e-5) # but as close as it should be + + def test_user_defined_optimizer_and_brack_raises_error(self): + optimizer = optimize.minimize_scalar + + # Using default `brack=None` with user-defined `optimizer` works as + # expected. + stats.boxcox_normmax(self.x, brack=None, optimizer=optimizer) + + # Using user-defined `brack` with user-defined `optimizer` is expected + # to throw an error. Instead, users should specify + # optimizer-specific parameters in the optimizer function itself. + with pytest.raises(ValueError, match="`brack` must be None if " + "`optimizer` is given"): + + stats.boxcox_normmax(self.x, brack=(-2.0, 2.0), + optimizer=optimizer) + + @pytest.mark.parametrize( + 'x', ([2003.0, 1950.0, 1997.0, 2000.0, 2009.0], + [0.50000471, 0.50004979, 0.50005902, 0.50009312, 0.50001632])) + def test_overflow(self, x): + message = "The optimal lambda is..." + with pytest.warns(UserWarning, match=message): + lmbda = stats.boxcox_normmax(x, method='mle') + assert np.isfinite(special.boxcox(x, lmbda)).all() + # 10000 is safety factor used in boxcox_normmax + ymax = np.finfo(np.float64).max / 10000 + x_treme = np.max(x) if lmbda > 0 else np.min(x) + y_extreme = special.boxcox(x_treme, lmbda) + assert_allclose(y_extreme, ymax * np.sign(lmbda)) + + def test_negative_ymax(self): + with pytest.raises(ValueError, match="`ymax` must be strictly positive"): + stats.boxcox_normmax(self.x, ymax=-1) + + @pytest.mark.parametrize("x", [ + # positive overflow in float64 + np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0], + dtype=np.float64), + # negative overflow in float64 + np.array([0.50000471, 0.50004979, 0.50005902, 0.50009312, 0.50001632], + dtype=np.float64), + # positive overflow in float32 + np.array([200.3, 195.0, 199.7, 200.0, 200.9], + dtype=np.float32), + # negative overflow in float32 + np.array([2e-30, 1e-30, 1e-30, 1e-30, 1e-30, 1e-30], + dtype=np.float32), + ]) + @pytest.mark.parametrize("ymax", [1e10, 1e30, None]) + # TODO: add method "pearsonr" after fix overflow issue + @pytest.mark.parametrize("method", ["mle"]) + def test_user_defined_ymax_input_float64_32(self, x, ymax, method): + # Test the maximum of the transformed data close to ymax + with pytest.warns(UserWarning, match="The optimal lambda is"): + kwarg = {'ymax': ymax} if ymax is not None else {} + lmb = stats.boxcox_normmax(x, method=method, **kwarg) + x_treme = [np.min(x), np.max(x)] + ymax_res = max(abs(stats.boxcox(x_treme, lmb))) + if ymax is None: + # 10000 is safety factor used in boxcox_normmax + ymax = np.finfo(x.dtype).max / 10000 + assert_allclose(ymax, ymax_res, rtol=1e-5) + + @pytest.mark.parametrize("x", [ + # positive overflow in float32 but not float64 + [200.3, 195.0, 199.7, 200.0, 200.9], + # negative overflow in float32 but not float64 + [2e-30, 1e-30, 1e-30, 1e-30, 1e-30, 1e-30], + ]) + # TODO: add method "pearsonr" after fix overflow issue + @pytest.mark.parametrize("method", ["mle"]) + def test_user_defined_ymax_inf(self, x, method): + x_32 = np.asarray(x, dtype=np.float32) + x_64 = np.asarray(x, dtype=np.float64) + + # assert overflow with float32 but not float64 + with pytest.warns(UserWarning, match="The optimal lambda is"): + stats.boxcox_normmax(x_32, method=method) + stats.boxcox_normmax(x_64, method=method) + + # compute the true optimal lambda then compare them + lmb_32 = stats.boxcox_normmax(x_32, ymax=np.inf, method=method) + lmb_64 = stats.boxcox_normmax(x_64, ymax=np.inf, method=method) + assert_allclose(lmb_32, lmb_64, rtol=1e-2) + + +class TestBoxcoxNormplot: + def setup_method(self): + self.x = _old_loggamma_rvs(5, size=500, random_state=7654321) + 5 + + def test_basic(self): + N = 5 + lmbdas, ppcc = stats.boxcox_normplot(self.x, -10, 10, N=N) + ppcc_expected = [0.57783375, 0.83610988, 0.97524311, 0.99756057, + 0.95843297] + assert_allclose(lmbdas, np.linspace(-10, 10, num=N)) + assert_allclose(ppcc, ppcc_expected) + + @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib") + def test_plot_kwarg(self): + # Check with the matplotlib.pyplot module + fig = plt.figure() + ax = fig.add_subplot(111) + stats.boxcox_normplot(self.x, -20, 20, plot=plt) + fig.delaxes(ax) + + # Check that a Matplotlib Axes object is accepted + ax = fig.add_subplot(111) + stats.boxcox_normplot(self.x, -20, 20, plot=ax) + plt.close() + + def test_invalid_inputs(self): + # `lb` has to be larger than `la` + assert_raises(ValueError, stats.boxcox_normplot, self.x, 1, 0) + # `x` can not contain negative values + assert_raises(ValueError, stats.boxcox_normplot, [-1, 1], 0, 1) + + def test_empty(self): + assert_(stats.boxcox_normplot([], 0, 1).size == 0) + + +class TestYeojohnson_llf: + + def test_array_like(self): + x = stats.norm.rvs(size=100, loc=0, random_state=54321) + lmbda = 1 + llf = stats.yeojohnson_llf(lmbda, x) + llf2 = stats.yeojohnson_llf(lmbda, list(x)) + assert_allclose(llf, llf2, rtol=1e-12) + + def test_2d_input(self): + x = stats.norm.rvs(size=100, loc=10, random_state=54321) + lmbda = 1 + llf = stats.yeojohnson_llf(lmbda, x) + llf2 = stats.yeojohnson_llf(lmbda, np.vstack([x, x]).T) + assert_allclose([llf, llf], llf2, rtol=1e-12) + + def test_empty(self): + assert_(np.isnan(stats.yeojohnson_llf(1, []))) + + +class TestYeojohnson: + + def test_fixed_lmbda(self): + rng = np.random.RandomState(12345) + + # Test positive input + x = _old_loggamma_rvs(5, size=50, random_state=rng) + 5 + assert np.all(x > 0) + xt = stats.yeojohnson(x, lmbda=1) + assert_allclose(xt, x) + xt = stats.yeojohnson(x, lmbda=-1) + assert_allclose(xt, 1 - 1 / (x + 1)) + xt = stats.yeojohnson(x, lmbda=0) + assert_allclose(xt, np.log(x + 1)) + xt = stats.yeojohnson(x, lmbda=1) + assert_allclose(xt, x) + + # Test negative input + x = _old_loggamma_rvs(5, size=50, random_state=rng) - 5 + assert np.all(x < 0) + xt = stats.yeojohnson(x, lmbda=2) + assert_allclose(xt, -np.log(-x + 1)) + xt = stats.yeojohnson(x, lmbda=1) + assert_allclose(xt, x) + xt = stats.yeojohnson(x, lmbda=3) + assert_allclose(xt, 1 / (-x + 1) - 1) + + # test both positive and negative input + x = _old_loggamma_rvs(5, size=50, random_state=rng) - 2 + assert not np.all(x < 0) + assert not np.all(x >= 0) + pos = x >= 0 + xt = stats.yeojohnson(x, lmbda=1) + assert_allclose(xt[pos], x[pos]) + xt = stats.yeojohnson(x, lmbda=-1) + assert_allclose(xt[pos], 1 - 1 / (x[pos] + 1)) + xt = stats.yeojohnson(x, lmbda=0) + assert_allclose(xt[pos], np.log(x[pos] + 1)) + xt = stats.yeojohnson(x, lmbda=1) + assert_allclose(xt[pos], x[pos]) + + neg = ~pos + xt = stats.yeojohnson(x, lmbda=2) + assert_allclose(xt[neg], -np.log(-x[neg] + 1)) + xt = stats.yeojohnson(x, lmbda=1) + assert_allclose(xt[neg], x[neg]) + xt = stats.yeojohnson(x, lmbda=3) + assert_allclose(xt[neg], 1 / (-x[neg] + 1) - 1) + + @pytest.mark.parametrize('lmbda', [0, .1, .5, 2]) + def test_lmbda_None(self, lmbda): + # Start from normal rv's, do inverse transform to check that + # optimization function gets close to the right answer. + + def _inverse_transform(x, lmbda): + x_inv = np.zeros(x.shape, dtype=x.dtype) + pos = x >= 0 + + # when x >= 0 + if abs(lmbda) < np.spacing(1.): + x_inv[pos] = np.exp(x[pos]) - 1 + else: # lmbda != 0 + x_inv[pos] = np.power(x[pos] * lmbda + 1, 1 / lmbda) - 1 + + # when x < 0 + if abs(lmbda - 2) > np.spacing(1.): + x_inv[~pos] = 1 - np.power(-(2 - lmbda) * x[~pos] + 1, + 1 / (2 - lmbda)) + else: # lmbda == 2 + x_inv[~pos] = 1 - np.exp(-x[~pos]) + + return x_inv + + n_samples = 20000 + np.random.seed(1234567) + x = np.random.normal(loc=0, scale=1, size=(n_samples)) + + x_inv = _inverse_transform(x, lmbda) + xt, maxlog = stats.yeojohnson(x_inv) + + assert_allclose(maxlog, lmbda, atol=1e-2) + + assert_almost_equal(0, np.linalg.norm(x - xt) / n_samples, decimal=2) + assert_almost_equal(0, xt.mean(), decimal=1) + assert_almost_equal(1, xt.std(), decimal=1) + + def test_empty(self): + assert_(stats.yeojohnson([]).shape == (0,)) + + def test_array_like(self): + x = stats.norm.rvs(size=100, loc=0, random_state=54321) + xt1, _ = stats.yeojohnson(x) + xt2, _ = stats.yeojohnson(list(x)) + assert_allclose(xt1, xt2, rtol=1e-12) + + @pytest.mark.parametrize('dtype', [np.complex64, np.complex128]) + def test_input_dtype_complex(self, dtype): + x = np.arange(6, dtype=dtype) + err_msg = ('Yeo-Johnson transformation is not defined for complex ' + 'numbers.') + with pytest.raises(ValueError, match=err_msg): + stats.yeojohnson(x) + + @pytest.mark.parametrize('dtype', [np.int8, np.uint8, np.int16, np.int32]) + def test_input_dtype_integer(self, dtype): + x_int = np.arange(8, dtype=dtype) + x_float = np.arange(8, dtype=np.float64) + xt_int, lmbda_int = stats.yeojohnson(x_int) + xt_float, lmbda_float = stats.yeojohnson(x_float) + assert_allclose(xt_int, xt_float, rtol=1e-7) + assert_allclose(lmbda_int, lmbda_float, rtol=1e-7) + + def test_input_high_variance(self): + # non-regression test for gh-10821 + x = np.array([3251637.22, 620695.44, 11642969.00, 2223468.22, + 85307500.00, 16494389.89, 917215.88, 11642969.00, + 2145773.87, 4962000.00, 620695.44, 651234.50, + 1907876.71, 4053297.88, 3251637.22, 3259103.08, + 9547969.00, 20631286.23, 12807072.08, 2383819.84, + 90114500.00, 17209575.46, 12852969.00, 2414609.99, + 2170368.23]) + xt_yeo, lam_yeo = stats.yeojohnson(x) + xt_box, lam_box = stats.boxcox(x + 1) + assert_allclose(xt_yeo, xt_box, rtol=1e-6) + assert_allclose(lam_yeo, lam_box, rtol=1e-6) + + @pytest.mark.parametrize('x', [ + np.array([1.0, float("nan"), 2.0]), + np.array([1.0, float("inf"), 2.0]), + np.array([1.0, -float("inf"), 2.0]), + np.array([-1.0, float("nan"), float("inf"), -float("inf"), 1.0]) + ]) + def test_nonfinite_input(self, x): + with pytest.raises(ValueError, match='Yeo-Johnson input must be finite'): + xt_yeo, lam_yeo = stats.yeojohnson(x) + + @pytest.mark.parametrize('x', [ + # Attempt to trigger overflow in power expressions. + np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0, + 2009.0, 1980.0, 1999.0, 2007.0, 1991.0]), + # Attempt to trigger overflow with a large optimal lambda. + np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0]), + # Attempt to trigger overflow with large data. + np.array([2003.0e200, 1950.0e200, 1997.0e200, 2000.0e200, 2009.0e200]) + ]) + def test_overflow(self, x): + # non-regression test for gh-18389 + + def optimizer(fun, lam_yeo): + out = optimize.fminbound(fun, -lam_yeo, lam_yeo, xtol=1.48e-08) + result = optimize.OptimizeResult() + result.x = out + return result + + with np.errstate(all="raise"): + xt_yeo, lam_yeo = stats.yeojohnson(x) + xt_box, lam_box = stats.boxcox( + x + 1, optimizer=partial(optimizer, lam_yeo=lam_yeo)) + assert np.isfinite(np.var(xt_yeo)) + assert np.isfinite(np.var(xt_box)) + assert_allclose(lam_yeo, lam_box, rtol=1e-6) + assert_allclose(xt_yeo, xt_box, rtol=1e-4) + + @pytest.mark.parametrize('x', [ + np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0, + 2009.0, 1980.0, 1999.0, 2007.0, 1991.0]), + np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0]) + ]) + @pytest.mark.parametrize('scale', [1, 1e-12, 1e-32, 1e-150, 1e32, 1e200]) + @pytest.mark.parametrize('sign', [1, -1]) + def test_overflow_underflow_signed_data(self, x, scale, sign): + # non-regression test for gh-18389 + with np.errstate(all="raise"): + xt_yeo, lam_yeo = stats.yeojohnson(sign * x * scale) + assert np.all(np.sign(sign * x) == np.sign(xt_yeo)) + assert np.isfinite(lam_yeo) + assert np.isfinite(np.var(xt_yeo)) + + @pytest.mark.parametrize('x', [ + np.array([0, 1, 2, 3]), + np.array([0, -1, 2, -3]), + np.array([0, 0, 0]) + ]) + @pytest.mark.parametrize('sign', [1, -1]) + @pytest.mark.parametrize('brack', [None, (-2, 2)]) + def test_integer_signed_data(self, x, sign, brack): + with np.errstate(all="raise"): + x_int = sign * x + x_float = x_int.astype(np.float64) + lam_yeo_int = stats.yeojohnson_normmax(x_int, brack=brack) + xt_yeo_int = stats.yeojohnson(x_int, lmbda=lam_yeo_int) + lam_yeo_float = stats.yeojohnson_normmax(x_float, brack=brack) + xt_yeo_float = stats.yeojohnson(x_float, lmbda=lam_yeo_float) + assert np.all(np.sign(x_int) == np.sign(xt_yeo_int)) + assert np.isfinite(lam_yeo_int) + assert np.isfinite(np.var(xt_yeo_int)) + assert lam_yeo_int == lam_yeo_float + assert np.all(xt_yeo_int == xt_yeo_float) + + +class TestYeojohnsonNormmax: + def setup_method(self): + self.x = _old_loggamma_rvs(5, size=50, random_state=12345) + 5 + + def test_mle(self): + maxlog = stats.yeojohnson_normmax(self.x) + assert_allclose(maxlog, 1.876393, rtol=1e-6) + + def test_darwin_example(self): + # test from original paper "A new family of power transformations to + # improve normality or symmetry" by Yeo and Johnson. + x = [6.1, -8.4, 1.0, 2.0, 0.7, 2.9, 3.5, 5.1, 1.8, 3.6, 7.0, 3.0, 9.3, + 7.5, -6.0] + lmbda = stats.yeojohnson_normmax(x) + assert np.allclose(lmbda, 1.305, atol=1e-3) + + +@array_api_compatible +class TestCircFuncs: + # In gh-5747, the R package `circular` was used to calculate reference + # values for the circular variance, e.g.: + # library(circular) + # options(digits=16) + # x = c(0, 2*pi/3, 5*pi/3) + # var.circular(x) + @pytest.mark.parametrize("test_func,expected", + [(stats.circmean, 0.167690146), + (stats.circvar, 0.006455174000787767), + (stats.circstd, 6.520702116)]) + def test_circfuncs(self, test_func, expected, xp): + x = xp.asarray([355., 5., 2., 359., 10., 350.]) + xp_assert_close(test_func(x, high=360), xp.asarray(expected)) + + def test_circfuncs_small(self, xp): + # Default tolerances won't work here because the reference values + # are approximations. Ensure all array types work in float64 to + # avoid needing separate float32 and float64 tolerances. + x = xp.asarray([20, 21, 22, 18, 19, 20.5, 19.2], dtype=xp.float64) + M1 = xp.mean(x) + M2 = stats.circmean(x, high=360) + xp_assert_close(M2, M1, rtol=1e-5) + + # plain torch var/std ddof=1, so we need array_api_compat torch + xp_test = array_namespace(x) + V1 = xp_test.var(x*xp.pi/180, correction=0) + # for small variations, circvar is approximately half the + # linear variance + V1 = V1 / 2. + V2 = stats.circvar(x, high=360) + xp_assert_close(V2, V1, rtol=1e-4) + + S1 = xp_test.std(x, correction=0) + S2 = stats.circstd(x, high=360) + xp_assert_close(S2, S1, rtol=1e-4) + + @pytest.mark.parametrize("test_func, numpy_func", + [(stats.circmean, np.mean), + (stats.circvar, np.var), + (stats.circstd, np.std)]) + def test_circfuncs_close(self, test_func, numpy_func, xp): + # circfuncs should handle very similar inputs (gh-12740) + x = np.asarray([0.12675364631578953] * 10 + [0.12675365920187928] * 100) + circstat = test_func(xp.asarray(x)) + normal = xp.asarray(numpy_func(x)) + xp_assert_close(circstat, normal, atol=2e-8) + + @pytest.mark.parametrize('circfunc', [stats.circmean, + stats.circvar, + stats.circstd]) + def test_circmean_axis(self, xp, circfunc): + x = xp.asarray([[355, 5, 2, 359, 10, 350], + [351, 7, 4, 352, 9, 349], + [357, 9, 8, 358, 4, 356.]]) + res = circfunc(x, high=360) + ref = circfunc(xp.reshape(x, (-1,)), high=360) + xp_assert_close(res, xp.asarray(ref)) + + res = circfunc(x, high=360, axis=1) + ref = [circfunc(x[i, :], high=360) for i in range(x.shape[0])] + xp_assert_close(res, xp.asarray(ref)) + + res = circfunc(x, high=360, axis=0) + ref = [circfunc(x[:, i], high=360) for i in range(x.shape[1])] + xp_assert_close(res, xp.asarray(ref)) + + @pytest.mark.parametrize("test_func,expected", + [(stats.circmean, 0.167690146), + (stats.circvar, 0.006455174270186603), + (stats.circstd, 6.520702116)]) + def test_circfuncs_array_like(self, test_func, expected, xp): + x = xp.asarray([355, 5, 2, 359, 10, 350.]) + xp_assert_close(test_func(x, high=360), xp.asarray(expected)) + + @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar, + stats.circstd]) + def test_empty(self, test_func, xp): + dtype = xp.float64 + x = xp.asarray([], dtype=dtype) + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = test_func(x) + else: + with np.testing.suppress_warnings() as sup: + # for array_api_strict + sup.filter(RuntimeWarning, "Mean of empty slice") + sup.filter(RuntimeWarning, "invalid value encountered") + res = test_func(x) + xp_assert_equal(res, xp.asarray(xp.nan, dtype=dtype)) + + @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar, + stats.circstd]) + def test_nan_propagate(self, test_func, xp): + x = xp.asarray([355, 5, 2, 359, 10, 350, np.nan]) + xp_assert_equal(test_func(x, high=360), xp.asarray(xp.nan)) + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.parametrize("test_func,expected", + [(stats.circmean, + {None: np.nan, 0: 355.66582264, 1: 0.28725053}), + (stats.circvar, + {None: np.nan, + 0: 0.002570671054089924, + 1: 0.005545914017677123}), + (stats.circstd, + {None: np.nan, 0: 4.11093193, 1: 6.04265394})]) + def test_nan_propagate_array(self, test_func, expected, xp): + x = xp.asarray([[355, 5, 2, 359, 10, 350, 1], + [351, 7, 4, 352, 9, 349, np.nan], + [1, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]]) + for axis in expected.keys(): + out = test_func(x, high=360, axis=axis) + if axis is None: + xp_assert_equal(out, xp.asarray(xp.nan)) + else: + xp_assert_close(out[0], xp.asarray(expected[axis])) + xp_assert_equal(out[1:], xp.full_like(out[1:], xp.nan)) + + def test_circmean_scalar(self, xp): + x = xp.asarray(1.)[()] + M1 = x + M2 = stats.circmean(x) + xp_assert_close(M2, M1, rtol=1e-5) + + def test_circmean_range(self, xp): + # regression test for gh-6420: circmean(..., high, low) must be + # between `high` and `low` + m = stats.circmean(xp.arange(0, 2, 0.1), xp.pi, -xp.pi) + xp_assert_less(m, xp.asarray(xp.pi)) + xp_assert_less(-m, xp.asarray(xp.pi)) + + def test_circfuncs_uint8(self, xp): + # regression test for gh-7255: overflow when working with + # numpy uint8 data type + x = xp.asarray([150, 10], dtype=xp.uint8) + xp_assert_close(stats.circmean(x, high=180), xp.asarray(170.0)) + xp_assert_close(stats.circvar(x, high=180), xp.asarray(0.2339555554617)) + xp_assert_close(stats.circstd(x, high=180), xp.asarray(20.91551378)) + + def test_circstd_zero(self, xp): + # circstd() of a single number should return positive zero. + y = stats.circstd(xp.asarray([0])) + assert math.copysign(1.0, y) == 1.0 + + def test_circmean_accuracy_tiny_input(self, xp): + # For tiny x such that sin(x) == x and cos(x) == 1.0 numerically, + # circmean(x) should return x because atan2(sin(x), cos(x)) == x. + # This test verifies this. + # + # The purpose of this test is not to show that circmean() is + # accurate in the last digit for certain input, because this is + # neither guaranteed not particularly useful. Rather, it is a + # "white-box" sanity check that no undue loss of precision is + # introduced by conversion between (high - low) and (2 * pi). + + x = xp.linspace(1e-9, 1e-8, 100) + assert xp.all(xp.sin(x) == x) and xp.all(xp.cos(x) == 1.0) + + m = (x * (2 * xp.pi) / (2 * xp.pi)) != x + assert xp.any(m) + x = x[m] + + y = stats.circmean(x[:, None], axis=1) + assert xp.all(y == x) + + def test_circmean_accuracy_huge_input(self, xp): + # White-box test that circmean() does not introduce undue loss of + # numerical accuracy by eagerly rotating the input. This is detected + # by supplying a huge input x such that (x - low) == x numerically. + x = xp.asarray(1e17, dtype=xp.float64) + y = math.atan2(xp.sin(x), xp.cos(x)) # -2.6584887370946806 + expected = xp.asarray(y, dtype=xp.float64) + actual = stats.circmean(x, high=xp.pi, low=-xp.pi) + xp_assert_close(actual, expected, rtol=1e-15, atol=0.0) + + +class TestCircFuncsNanPolicy: + # `nan_policy` is implemented by the `_axis_nan_policy` decorator, which is + # not yet array-API compatible. When it is array-API compatible, the generic + # tests run on every function will be much stronger than these, so these + # will not be necessary. So I don't see a need to make these array-API compatible; + # when the time comes, they can just be removed. + @pytest.mark.parametrize("test_func,expected", + [(stats.circmean, + {None: 359.4178026893944, + 0: np.array([353.0, 6.0, 3.0, 355.5, 9.5, + 349.5]), + 1: np.array([0.16769015, 358.66510252])}), + (stats.circvar, + {None: 0.008396678483192477, + 0: np.array([1.9997969, 0.4999873, 0.4999873, + 6.1230956, 0.1249992, 0.1249992] + )*(np.pi/180)**2, + 1: np.array([0.006455174270186603, + 0.01016767581393285])}), + (stats.circstd, + {None: 7.440570778057074, + 0: np.array([2.00020313, 1.00002539, 1.00002539, + 3.50108929, 0.50000317, + 0.50000317]), + 1: np.array([6.52070212, 8.19138093])})]) + def test_nan_omit_array(self, test_func, expected): + x = np.array([[355, 5, 2, 359, 10, 350, np.nan], + [351, 7, 4, 352, 9, 349, np.nan], + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]]) + for axis in expected.keys(): + if axis is None: + out = test_func(x, high=360, nan_policy='omit', axis=axis) + assert_allclose(out, expected[axis], rtol=1e-7) + else: + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + out = test_func(x, high=360, nan_policy='omit', axis=axis) + assert_allclose(out[:-1], expected[axis], rtol=1e-7) + assert_(np.isnan(out[-1])) + + @pytest.mark.parametrize("test_func,expected", + [(stats.circmean, 0.167690146), + (stats.circvar, 0.006455174270186603), + (stats.circstd, 6.520702116)]) + def test_nan_omit(self, test_func, expected): + x = [355, 5, 2, 359, 10, 350, np.nan] + assert_allclose(test_func(x, high=360, nan_policy='omit'), + expected, rtol=1e-7) + + @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar, + stats.circstd]) + def test_nan_omit_all(self, test_func): + x = [np.nan, np.nan, np.nan, np.nan, np.nan] + with pytest.warns(SmallSampleWarning, match=too_small_1d_omit): + assert_(np.isnan(test_func(x, nan_policy='omit'))) + + @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar, + stats.circstd]) + def test_nan_omit_all_axis(self, test_func): + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + x = np.array([[np.nan, np.nan, np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan, np.nan, np.nan]]) + out = test_func(x, nan_policy='omit', axis=1) + assert_(np.isnan(out).all()) + assert_(len(out) == 2) + + @pytest.mark.parametrize("x", + [[355, 5, 2, 359, 10, 350, np.nan], + np.array([[355, 5, 2, 359, 10, 350, np.nan], + [351, 7, 4, 352, np.nan, 9, 349]])]) + @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar, + stats.circstd]) + def test_nan_raise(self, test_func, x): + assert_raises(ValueError, test_func, x, high=360, nan_policy='raise') + + @pytest.mark.parametrize("x", + [[355, 5, 2, 359, 10, 350, np.nan], + np.array([[355, 5, 2, 359, 10, 350, np.nan], + [351, 7, 4, 352, np.nan, 9, 349]])]) + @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar, + stats.circstd]) + def test_bad_nan_policy(self, test_func, x): + assert_raises(ValueError, test_func, x, high=360, nan_policy='foobar') + + +class TestMedianTest: + + def test_bad_n_samples(self): + # median_test requires at least two samples. + assert_raises(ValueError, stats.median_test, [1, 2, 3]) + + def test_empty_sample(self): + # Each sample must contain at least one value. + assert_raises(ValueError, stats.median_test, [], [1, 2, 3]) + + def test_empty_when_ties_ignored(self): + # The grand median is 1, and all values in the first argument are + # equal to the grand median. With ties="ignore", those values are + # ignored, which results in the first sample being (in effect) empty. + # This should raise a ValueError. + assert_raises(ValueError, stats.median_test, + [1, 1, 1, 1], [2, 0, 1], [2, 0], ties="ignore") + + def test_empty_contingency_row(self): + # The grand median is 1, and with the default ties="below", all the + # values in the samples are counted as being below the grand median. + # This would result a row of zeros in the contingency table, which is + # an error. + assert_raises(ValueError, stats.median_test, [1, 1, 1], [1, 1, 1]) + + # With ties="above", all the values are counted as above the + # grand median. + assert_raises(ValueError, stats.median_test, [1, 1, 1], [1, 1, 1], + ties="above") + + def test_bad_ties(self): + assert_raises(ValueError, stats.median_test, [1, 2, 3], [4, 5], + ties="foo") + + def test_bad_nan_policy(self): + assert_raises(ValueError, stats.median_test, [1, 2, 3], [4, 5], + nan_policy='foobar') + + def test_bad_keyword(self): + assert_raises(TypeError, stats.median_test, [1, 2, 3], [4, 5], + foo="foo") + + def test_simple(self): + x = [1, 2, 3] + y = [1, 2, 3] + stat, p, med, tbl = stats.median_test(x, y) + + # The median is floating point, but this equality test should be safe. + assert_equal(med, 2.0) + + assert_array_equal(tbl, [[1, 1], [2, 2]]) + + # The expected values of the contingency table equal the contingency + # table, so the statistic should be 0 and the p-value should be 1. + assert_equal(stat, 0) + assert_equal(p, 1) + + def test_ties_options(self): + # Test the contingency table calculation. + x = [1, 2, 3, 4] + y = [5, 6] + z = [7, 8, 9] + # grand median is 5. + + # Default 'ties' option is "below". + stat, p, m, tbl = stats.median_test(x, y, z) + assert_equal(m, 5) + assert_equal(tbl, [[0, 1, 3], [4, 1, 0]]) + + stat, p, m, tbl = stats.median_test(x, y, z, ties="ignore") + assert_equal(m, 5) + assert_equal(tbl, [[0, 1, 3], [4, 0, 0]]) + + stat, p, m, tbl = stats.median_test(x, y, z, ties="above") + assert_equal(m, 5) + assert_equal(tbl, [[0, 2, 3], [4, 0, 0]]) + + def test_nan_policy_options(self): + x = [1, 2, np.nan] + y = [4, 5, 6] + mt1 = stats.median_test(x, y, nan_policy='propagate') + s, p, m, t = stats.median_test(x, y, nan_policy='omit') + + assert_equal(mt1, (np.nan, np.nan, np.nan, None)) + assert_allclose(s, 0.31250000000000006) + assert_allclose(p, 0.57615012203057869) + assert_equal(m, 4.0) + assert_equal(t, np.array([[0, 2], [2, 1]])) + assert_raises(ValueError, stats.median_test, x, y, nan_policy='raise') + + def test_basic(self): + # median_test calls chi2_contingency to compute the test statistic + # and p-value. Make sure it hasn't screwed up the call... + + x = [1, 2, 3, 4, 5] + y = [2, 4, 6, 8] + + stat, p, m, tbl = stats.median_test(x, y) + assert_equal(m, 4) + assert_equal(tbl, [[1, 2], [4, 2]]) + + exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl) + assert_allclose(stat, exp_stat) + assert_allclose(p, exp_p) + + stat, p, m, tbl = stats.median_test(x, y, lambda_=0) + assert_equal(m, 4) + assert_equal(tbl, [[1, 2], [4, 2]]) + + exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl, lambda_=0) + assert_allclose(stat, exp_stat) + assert_allclose(p, exp_p) + + stat, p, m, tbl = stats.median_test(x, y, correction=False) + assert_equal(m, 4) + assert_equal(tbl, [[1, 2], [4, 2]]) + + exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl, correction=False) + assert_allclose(stat, exp_stat) + assert_allclose(p, exp_p) + + @pytest.mark.parametrize("correction", [False, True]) + def test_result(self, correction): + x = [1, 2, 3] + y = [1, 2, 3] + + res = stats.median_test(x, y, correction=correction) + assert_equal((res.statistic, res.pvalue, res.median, res.table), res) + +@array_api_compatible +class TestDirectionalStats: + # Reference implementations are not available + def test_directional_stats_correctness(self, xp): + # Data from Fisher: Dispersion on a sphere, 1953 and + # Mardia and Jupp, Directional Statistics. + decl = -np.deg2rad(np.array([343.2, 62., 36.9, 27., 359., + 5.7, 50.4, 357.6, 44.])) + incl = -np.deg2rad(np.array([66.1, 68.7, 70.1, 82.1, 79.5, + 73., 69.3, 58.8, 51.4])) + data = np.stack((np.cos(incl) * np.cos(decl), + np.cos(incl) * np.sin(decl), + np.sin(incl)), + axis=1) + + decl = xp.asarray(decl.tolist()) + incl = xp.asarray(incl.tolist()) + data = xp.asarray(data.tolist()) + + dirstats = stats.directional_stats(data) + directional_mean = dirstats.mean_direction + + reference_mean = xp.asarray([0.2984, -0.1346, -0.9449]) + xp_assert_close(directional_mean, reference_mean, atol=1e-4) + + @pytest.mark.parametrize('angles, ref', [ + ([-np.pi/2, np.pi/2], 1.), + ([0, 2 * np.pi], 0.) + ]) + def test_directional_stats_2d_special_cases(self, angles, ref, xp): + angles = xp.asarray(angles) + ref = xp.asarray(ref) + data = xp.stack([xp.cos(angles), xp.sin(angles)], axis=1) + res = 1 - stats.directional_stats(data).mean_resultant_length + xp_assert_close(res, ref) + + def test_directional_stats_2d(self, xp): + # Test that for circular data directional_stats + # yields the same result as circmean/circvar + rng = np.random.default_rng(0xec9a6899d5a2830e0d1af479dbe1fd0c) + testdata = xp.asarray(2 * xp.pi * rng.random((1000, ))) + testdata_vector = xp.stack((xp.cos(testdata), + xp.sin(testdata)), + axis=1) + dirstats = stats.directional_stats(testdata_vector) + directional_mean = dirstats.mean_direction + xp_test = array_namespace(directional_mean) # np needs atan2 + directional_mean_angle = xp_test.atan2(directional_mean[1], + directional_mean[0]) + directional_mean_angle = directional_mean_angle % (2 * xp.pi) + circmean = stats.circmean(testdata) + xp_assert_close(directional_mean_angle, circmean) + + directional_var = 1. - dirstats.mean_resultant_length + circular_var = stats.circvar(testdata) + xp_assert_close(directional_var, circular_var) + + def test_directional_mean_higher_dim(self, xp): + # test that directional_stats works for higher dimensions + # here a 4D array is reduced over axis = 2 + data = xp.asarray([[0.8660254, 0.5, 0.], + [0.8660254, -0.5, 0.]]) + full_array = xp.asarray(xp.tile(data, (2, 2, 2, 1))) + expected = xp.asarray([[[1., 0., 0.], + [1., 0., 0.]], + [[1., 0., 0.], + [1., 0., 0.]]]) + dirstats = stats.directional_stats(full_array, axis=2) + xp_assert_close(dirstats.mean_direction, expected) + + @skip_xp_backends(np_only=True, reason='checking array-like input') + def test_directional_stats_list_ndarray_input(self, xp): + # test that list and numpy array inputs yield same results + data = [[0.8660254, 0.5, 0.], [0.8660254, -0.5, 0]] + data_array = xp.asarray(data, dtype=xp.float64) + ref = stats.directional_stats(data) + res = stats.directional_stats(data_array) + xp_assert_close(res.mean_direction, + xp.asarray(ref.mean_direction)) + xp_assert_close(res.mean_resultant_length, + xp.asarray(res.mean_resultant_length)) + + def test_directional_stats_1d_error(self, xp): + # test that one-dimensional data raises ValueError + data = xp.ones((5, )) + message = (r"samples must at least be two-dimensional. " + r"Instead samples has shape: (5,)") + with pytest.raises(ValueError, match=re.escape(message)): + stats.directional_stats(data) + + @pytest.mark.parametrize("dtype", ["float32", "float64"]) + def test_directional_stats_normalize(self, dtype, xp): + # test that directional stats calculations yield same results + # for unnormalized input with normalize=True and normalized + # input with normalize=False + data = np.array([[0.8660254, 0.5, 0.], + [1.7320508, -1., 0.]], dtype=dtype) + res = stats.directional_stats(xp.asarray(data), normalize=True) + normalized_data = data / np.linalg.norm(data, axis=-1, + keepdims=True) + ref = stats.directional_stats(normalized_data, normalize=False) + xp_assert_close(res.mean_direction, + xp.asarray(ref.mean_direction)) + xp_assert_close(res.mean_resultant_length, + xp.asarray(ref.mean_resultant_length)) + + +class TestFDRControl: + def test_input_validation(self): + message = "`ps` must include only numbers between 0 and 1" + with pytest.raises(ValueError, match=message): + stats.false_discovery_control([-1, 0.5, 0.7]) + with pytest.raises(ValueError, match=message): + stats.false_discovery_control([0.5, 0.7, 2]) + with pytest.raises(ValueError, match=message): + stats.false_discovery_control([0.5, 0.7, np.nan]) + + message = "Unrecognized `method` 'YAK'" + with pytest.raises(ValueError, match=message): + stats.false_discovery_control([0.5, 0.7, 0.9], method='YAK') + + message = "`axis` must be an integer or `None`" + with pytest.raises(ValueError, match=message): + stats.false_discovery_control([0.5, 0.7, 0.9], axis=1.5) + with pytest.raises(ValueError, match=message): + stats.false_discovery_control([0.5, 0.7, 0.9], axis=(1, 2)) + + def test_against_TileStats(self): + # See reference [3] of false_discovery_control + ps = [0.005, 0.009, 0.019, 0.022, 0.051, 0.101, 0.361, 0.387] + res = stats.false_discovery_control(ps) + ref = [0.036, 0.036, 0.044, 0.044, 0.082, 0.135, 0.387, 0.387] + assert_allclose(res, ref, atol=1e-3) + + @pytest.mark.parametrize("case", + [([0.24617028, 0.01140030, 0.05652047, 0.06841983, + 0.07989886, 0.01841490, 0.17540784, 0.06841983, + 0.06841983, 0.25464082], 'bh'), + ([0.72102493, 0.03339112, 0.16554665, 0.20039952, + 0.23402122, 0.05393666, 0.51376399, 0.20039952, + 0.20039952, 0.74583488], 'by')]) + def test_against_R(self, case): + # Test against p.adjust, e.g. + # p = c(0.22155325, 0.00114003,..., 0.0364813 , 0.25464082) + # p.adjust(p, "BY") + ref, method = case + rng = np.random.default_rng(6134137338861652935) + ps = stats.loguniform.rvs(1e-3, 0.5, size=10, random_state=rng) + ps[3] = ps[7] # force a tie + res = stats.false_discovery_control(ps, method=method) + assert_allclose(res, ref, atol=1e-6) + + def test_axis_None(self): + rng = np.random.default_rng(6134137338861652935) + ps = stats.loguniform.rvs(1e-3, 0.5, size=(3, 4, 5), random_state=rng) + res = stats.false_discovery_control(ps, axis=None) + ref = stats.false_discovery_control(ps.ravel()) + assert_equal(res, ref) + + @pytest.mark.parametrize("axis", [0, 1, -1]) + def test_axis(self, axis): + rng = np.random.default_rng(6134137338861652935) + ps = stats.loguniform.rvs(1e-3, 0.5, size=(3, 4, 5), random_state=rng) + res = stats.false_discovery_control(ps, axis=axis) + ref = np.apply_along_axis(stats.false_discovery_control, axis, ps) + assert_equal(res, ref) + + def test_edge_cases(self): + assert_array_equal(stats.false_discovery_control([0.25]), [0.25]) + assert_array_equal(stats.false_discovery_control(0.25), 0.25) + assert_array_equal(stats.false_discovery_control([]), []) + + +@array_api_compatible +class TestCommonAxis: + # More thorough testing of `axis` in `test_axis_nan_policy`, + # but those tests aren't run with array API yet. This class + # is in `test_morestats` instead of `test_axis_nan_policy` + # because there is no reason to run `test_axis_nan_policy` + # with the array API CI job right now. + + @pytest.mark.parametrize('case', [(stats.sem, {}), + (stats.kstat, {'n': 4}), + (stats.kstat, {'n': 2}), + (stats.variation, {})]) + def test_axis(self, case, xp): + fun, kwargs = case + rng = np.random.default_rng(24598245982345) + x = xp.asarray(rng.random((6, 7))) + + res = fun(x, **kwargs, axis=0) + ref = xp.asarray([fun(x[:, i], **kwargs) for i in range(x.shape[1])]) + xp_assert_close(res, ref) + + res = fun(x, **kwargs, axis=1) + ref = xp.asarray([fun(x[i, :], **kwargs) for i in range(x.shape[0])]) + xp_assert_close(res, ref) + + res = fun(x, **kwargs, axis=None) + ref = fun(xp.reshape(x, (-1,)), **kwargs) + xp_assert_close(res, ref) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_basic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..789065f088240287882e744509539dc65b4b836f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_basic.py @@ -0,0 +1,2071 @@ +""" +Tests for the stats.mstats module (support for masked arrays) +""" +import warnings +import platform + +import numpy as np +from numpy import nan +import numpy.ma as ma +from numpy.ma import masked, nomask + +import scipy.stats.mstats as mstats +from scipy import stats +from .common_tests import check_named_results +import pytest +from pytest import raises as assert_raises +from numpy.ma.testutils import (assert_equal, assert_almost_equal, + assert_array_almost_equal, + assert_array_almost_equal_nulp, assert_, + assert_allclose, assert_array_equal) +from numpy.testing import suppress_warnings +from scipy.stats import _mstats_basic, _stats_py +from scipy.conftest import skip_xp_invalid_arg +from scipy.stats._axis_nan_policy import SmallSampleWarning, too_small_1d_not_omit + +class TestMquantiles: + def test_mquantiles_limit_keyword(self): + # Regression test for Trac ticket #867 + data = np.array([[6., 7., 1.], + [47., 15., 2.], + [49., 36., 3.], + [15., 39., 4.], + [42., 40., -999.], + [41., 41., -999.], + [7., -999., -999.], + [39., -999., -999.], + [43., -999., -999.], + [40., -999., -999.], + [36., -999., -999.]]) + desired = [[19.2, 14.6, 1.45], + [40.0, 37.5, 2.5], + [42.8, 40.05, 3.55]] + quants = mstats.mquantiles(data, axis=0, limit=(0, 50)) + assert_almost_equal(quants, desired) + + +def check_equal_gmean(array_like, desired, axis=None, dtype=None, rtol=1e-7): + # Note this doesn't test when axis is not specified + x = mstats.gmean(array_like, axis=axis, dtype=dtype) + assert_allclose(x, desired, rtol=rtol) + assert_equal(x.dtype, dtype) + + +def check_equal_hmean(array_like, desired, axis=None, dtype=None, rtol=1e-7): + x = stats.hmean(array_like, axis=axis, dtype=dtype) + assert_allclose(x, desired, rtol=rtol) + assert_equal(x.dtype, dtype) + + +@skip_xp_invalid_arg +class TestGeoMean: + def test_1d(self): + a = [1, 2, 3, 4] + desired = np.power(1*2*3*4, 1./4.) + check_equal_gmean(a, desired, rtol=1e-14) + + def test_1d_ma(self): + # Test a 1d masked array + a = ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) + desired = 45.2872868812 + check_equal_gmean(a, desired) + + a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1]) + desired = np.power(1*2*3, 1./3.) + check_equal_gmean(a, desired, rtol=1e-14) + + def test_1d_ma_value(self): + # Test a 1d masked array with a masked value + a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], + mask=[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) + desired = 41.4716627439 + check_equal_gmean(a, desired) + + def test_1d_ma0(self): + # Test a 1d masked array with zero element + a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 0]) + desired = 0 + check_equal_gmean(a, desired) + + def test_1d_ma_inf(self): + # Test a 1d masked array with negative element + a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, -1]) + desired = np.nan + with np.errstate(invalid='ignore'): + check_equal_gmean(a, desired) + + @pytest.mark.skipif(not hasattr(np, 'float96'), + reason='cannot find float96 so skipping') + def test_1d_float96(self): + a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1]) + desired_dt = np.power(1*2*3, 1./3.).astype(np.float96) + check_equal_gmean(a, desired_dt, dtype=np.float96, rtol=1e-14) + + def test_2d_ma(self): + a = ma.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], + mask=[[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]]) + desired = np.array([1, 2, 3, 4]) + check_equal_gmean(a, desired, axis=0, rtol=1e-14) + + desired = ma.array([np.power(1*2*3*4, 1./4.), + np.power(2*3, 1./2.), + np.power(1*4, 1./2.)]) + check_equal_gmean(a, desired, axis=-1, rtol=1e-14) + + # Test a 2d masked array + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = 52.8885199 + check_equal_gmean(np.ma.array(a), desired) + + +@skip_xp_invalid_arg +class TestHarMean: + def test_1d(self): + a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1]) + desired = 3. / (1./1 + 1./2 + 1./3) + check_equal_hmean(a, desired, rtol=1e-14) + + a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) + desired = 34.1417152147 + check_equal_hmean(a, desired) + + a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], + mask=[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) + desired = 31.8137186141 + check_equal_hmean(a, desired) + + @pytest.mark.skipif(not hasattr(np, 'float96'), + reason='cannot find float96 so skipping') + def test_1d_float96(self): + a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1]) + desired_dt = np.asarray(3. / (1./1 + 1./2 + 1./3), dtype=np.float96) + check_equal_hmean(a, desired_dt, dtype=np.float96) + + def test_2d(self): + a = ma.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], + mask=[[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]]) + desired = ma.array([1, 2, 3, 4]) + check_equal_hmean(a, desired, axis=0, rtol=1e-14) + + desired = [4./(1/1.+1/2.+1/3.+1/4.), 2./(1/2.+1/3.), 2./(1/1.+1/4.)] + check_equal_hmean(a, desired, axis=-1, rtol=1e-14) + + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = 38.6696271841 + check_equal_hmean(np.ma.array(a), desired) + + +class TestRanking: + def test_ranking(self): + x = ma.array([0,1,1,1,2,3,4,5,5,6,]) + assert_almost_equal(mstats.rankdata(x), + [1,3,3,3,5,6,7,8.5,8.5,10]) + x[[3,4]] = masked + assert_almost_equal(mstats.rankdata(x), + [1,2.5,2.5,0,0,4,5,6.5,6.5,8]) + assert_almost_equal(mstats.rankdata(x, use_missing=True), + [1,2.5,2.5,4.5,4.5,4,5,6.5,6.5,8]) + x = ma.array([0,1,5,1,2,4,3,5,1,6,]) + assert_almost_equal(mstats.rankdata(x), + [1,3,8.5,3,5,7,6,8.5,3,10]) + x = ma.array([[0,1,1,1,2], [3,4,5,5,6,]]) + assert_almost_equal(mstats.rankdata(x), + [[1,3,3,3,5], [6,7,8.5,8.5,10]]) + assert_almost_equal(mstats.rankdata(x, axis=1), + [[1,3,3,3,5], [1,2,3.5,3.5,5]]) + assert_almost_equal(mstats.rankdata(x,axis=0), + [[1,1,1,1,1], [2,2,2,2,2,]]) + + +class TestCorr: + def test_pearsonr(self): + # Tests some computations of Pearson's r + x = ma.arange(10) + with warnings.catch_warnings(): + # The tests in this context are edge cases, with perfect + # correlation or anticorrelation, or totally masked data. + # None of these should trigger a RuntimeWarning. + warnings.simplefilter("error", RuntimeWarning) + + assert_almost_equal(mstats.pearsonr(x, x)[0], 1.0) + assert_almost_equal(mstats.pearsonr(x, x[::-1])[0], -1.0) + + x = ma.array(x, mask=True) + pr = mstats.pearsonr(x, x) + assert_(pr[0] is masked) + assert_(pr[1] is masked) + + x1 = ma.array([-1.0, 0.0, 1.0]) + y1 = ma.array([0, 0, 3]) + r, p = mstats.pearsonr(x1, y1) + assert_almost_equal(r, np.sqrt(3)/2) + assert_almost_equal(p, 1.0/3) + + # (x2, y2) have the same unmasked data as (x1, y1). + mask = [False, False, False, True] + x2 = ma.array([-1.0, 0.0, 1.0, 99.0], mask=mask) + y2 = ma.array([0, 0, 3, -1], mask=mask) + r, p = mstats.pearsonr(x2, y2) + assert_almost_equal(r, np.sqrt(3)/2) + assert_almost_equal(p, 1.0/3) + + def test_pearsonr_misaligned_mask(self): + mx = np.ma.masked_array([1, 2, 3, 4, 5, 6], mask=[0, 1, 0, 0, 0, 0]) + my = np.ma.masked_array([9, 8, 7, 6, 5, 9], mask=[0, 0, 1, 0, 0, 0]) + x = np.array([1, 4, 5, 6]) + y = np.array([9, 6, 5, 9]) + mr, mp = mstats.pearsonr(mx, my) + r, p = stats.pearsonr(x, y) + assert_equal(mr, r) + assert_equal(mp, p) + + def test_spearmanr(self): + # Tests some computations of Spearman's rho + (x, y) = ([5.05,6.75,3.21,2.66], [1.65,2.64,2.64,6.95]) + assert_almost_equal(mstats.spearmanr(x,y)[0], -0.6324555) + (x, y) = ([5.05,6.75,3.21,2.66,np.nan],[1.65,2.64,2.64,6.95,np.nan]) + (x, y) = (ma.fix_invalid(x), ma.fix_invalid(y)) + assert_almost_equal(mstats.spearmanr(x,y)[0], -0.6324555) + + x = [2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1, + 1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7] + y = [22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6, + 0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4] + assert_almost_equal(mstats.spearmanr(x,y)[0], 0.6887299) + x = [2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1, + 1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7, np.nan] + y = [22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6, + 0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4, np.nan] + (x, y) = (ma.fix_invalid(x), ma.fix_invalid(y)) + assert_almost_equal(mstats.spearmanr(x,y)[0], 0.6887299) + # Next test is to make sure calculation uses sufficient precision. + # The denominator's value is ~n^3 and used to be represented as an + # int. 2000**3 > 2**32 so these arrays would cause overflow on + # some machines. + x = list(range(2000)) + y = list(range(2000)) + y[0], y[9] = y[9], y[0] + y[10], y[434] = y[434], y[10] + y[435], y[1509] = y[1509], y[435] + # rho = 1 - 6 * (2 * (9^2 + 424^2 + 1074^2))/(2000 * (2000^2 - 1)) + # = 1 - (1 / 500) + # = 0.998 + assert_almost_equal(mstats.spearmanr(x,y)[0], 0.998) + + # test for namedtuple attributes + res = mstats.spearmanr(x, y) + attributes = ('correlation', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_spearmanr_alternative(self): + # check against R + # options(digits=16) + # cor.test(c(2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1, + # 1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7), + # c(22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6, + # 0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4), + # alternative='two.sided', method='spearman') + x = [2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1, + 1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7] + y = [22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6, + 0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4] + + r_exp = 0.6887298747763864 # from cor.test + + r, p = mstats.spearmanr(x, y) + assert_allclose(r, r_exp) + assert_allclose(p, 0.004519192910756) + + r, p = mstats.spearmanr(x, y, alternative='greater') + assert_allclose(r, r_exp) + assert_allclose(p, 0.002259596455378) + + r, p = mstats.spearmanr(x, y, alternative='less') + assert_allclose(r, r_exp) + assert_allclose(p, 0.9977404035446) + + # intuitive test (with obvious positive correlation) + n = 100 + x = np.linspace(0, 5, n) + y = 0.1*x + np.random.rand(n) # y is positively correlated w/ x + + stat1, p1 = mstats.spearmanr(x, y) + + stat2, p2 = mstats.spearmanr(x, y, alternative="greater") + assert_allclose(p2, p1 / 2) # positive correlation -> small p + + stat3, p3 = mstats.spearmanr(x, y, alternative="less") + assert_allclose(p3, 1 - p1 / 2) # positive correlation -> large p + + assert stat1 == stat2 == stat3 + + with pytest.raises(ValueError, match="alternative must be 'less'..."): + mstats.spearmanr(x, y, alternative="ekki-ekki") + + @pytest.mark.skipif(platform.machine() == 'ppc64le', + reason="fails/crashes on ppc64le") + def test_kendalltau(self): + # check case with maximum disorder and p=1 + x = ma.array(np.array([9, 2, 5, 6])) + y = ma.array(np.array([4, 7, 9, 11])) + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = [0.0, 1.0] + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected) + + # simple case without ties + x = ma.array(np.arange(10)) + y = ma.array(np.arange(10)) + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = [1.0, 5.511463844797e-07] + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected) + + # check exception in case of invalid method keyword + assert_raises(ValueError, mstats.kendalltau, x, y, method='banana') + + # swap a couple of values + b = y[1] + y[1] = y[2] + y[2] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = [0.9555555555555556, 5.511463844797e-06] + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected) + + # swap a couple more + b = y[5] + y[5] = y[6] + y[6] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = [0.9111111111111111, 2.976190476190e-05] + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected) + + # same in opposite direction + x = ma.array(np.arange(10)) + y = ma.array(np.arange(10)[::-1]) + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = [-1.0, 5.511463844797e-07] + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected) + + # swap a couple of values + b = y[1] + y[1] = y[2] + y[2] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = [-0.9555555555555556, 5.511463844797e-06] + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected) + + # swap a couple more + b = y[5] + y[5] = y[6] + y[6] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = [-0.9111111111111111, 2.976190476190e-05] + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected) + + # Tests some computations of Kendall's tau + x = ma.fix_invalid([5.05, 6.75, 3.21, 2.66, np.nan]) + y = ma.fix_invalid([1.65, 26.5, -5.93, 7.96, np.nan]) + z = ma.fix_invalid([1.65, 2.64, 2.64, 6.95, np.nan]) + assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), + [+0.3333333, 0.75]) + assert_almost_equal(np.asarray(mstats.kendalltau(x, y, method='asymptotic')), + [+0.3333333, 0.4969059]) + assert_almost_equal(np.asarray(mstats.kendalltau(x, z)), + [-0.5477226, 0.2785987]) + # + x = ma.fix_invalid([0, 0, 0, 0, 20, 20, 0, 60, 0, 20, + 10, 10, 0, 40, 0, 20, 0, 0, 0, 0, 0, np.nan]) + y = ma.fix_invalid([0, 80, 80, 80, 10, 33, 60, 0, 67, 27, + 25, 80, 80, 80, 80, 80, 80, 0, 10, 45, np.nan, 0]) + result = mstats.kendalltau(x, y) + assert_almost_equal(np.asarray(result), [-0.1585188, 0.4128009]) + + # test for namedtuple attributes + attributes = ('correlation', 'pvalue') + check_named_results(result, attributes, ma=True) + + @pytest.mark.skipif(platform.machine() == 'ppc64le', + reason="fails/crashes on ppc64le") + @pytest.mark.slow + def test_kendalltau_large(self): + # make sure internal variable use correct precision with + # larger arrays + x = np.arange(2000, dtype=float) + x = ma.masked_greater(x, 1995) + y = np.arange(2000, dtype=float) + y = np.concatenate((y[1000:], y[:1000])) + assert_(np.isfinite(mstats.kendalltau(x, y)[1])) + + def test_kendalltau_seasonal(self): + # Tests the seasonal Kendall tau. + x = [[nan, nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1], + [4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3], + [3, 2, 5, 6, 18, 4, 9, 1, 1, nan, 1, 1, nan], + [nan, 6, 11, 4, 17, nan, 6, 1, 1, 2, 5, 1, 1]] + x = ma.fix_invalid(x).T + output = mstats.kendalltau_seasonal(x) + assert_almost_equal(output['global p-value (indep)'], 0.008, 3) + assert_almost_equal(output['seasonal p-value'].round(2), + [0.18,0.53,0.20,0.04]) + + @pytest.mark.parametrize("method", ("exact", "asymptotic")) + @pytest.mark.parametrize("alternative", ("two-sided", "greater", "less")) + def test_kendalltau_mstats_vs_stats(self, method, alternative): + # Test that mstats.kendalltau and stats.kendalltau with + # nan_policy='omit' matches behavior of stats.kendalltau + # Accuracy of the alternatives is tested in stats/tests/test_stats.py + + np.random.seed(0) + n = 50 + x = np.random.rand(n) + y = np.random.rand(n) + mask = np.random.rand(n) > 0.5 + + x_masked = ma.array(x, mask=mask) + y_masked = ma.array(y, mask=mask) + res_masked = mstats.kendalltau( + x_masked, y_masked, method=method, alternative=alternative) + + x_compressed = x_masked.compressed() + y_compressed = y_masked.compressed() + res_compressed = stats.kendalltau( + x_compressed, y_compressed, method=method, alternative=alternative) + + x[mask] = np.nan + y[mask] = np.nan + res_nan = stats.kendalltau( + x, y, method=method, nan_policy='omit', alternative=alternative) + + assert_allclose(res_masked, res_compressed) + assert_allclose(res_nan, res_compressed) + + def test_kendall_p_exact_medium(self): + # Test for the exact method with medium samples (some n >= 171) + # expected values generated using SymPy + expectations = {(100, 2393): 0.62822615287956040664, + (101, 2436): 0.60439525773513602669, + (170, 0): 2.755801935583541e-307, + (171, 0): 0.0, + (171, 1): 2.755801935583541e-307, + (172, 1): 0.0, + (200, 9797): 0.74753983745929675209, + (201, 9656): 0.40959218958120363618} + for nc, expected in expectations.items(): + res = _mstats_basic._kendall_p_exact(nc[0], nc[1]) + assert_almost_equal(res, expected) + + @pytest.mark.xslow + def test_kendall_p_exact_large(self): + # Test for the exact method with large samples (n >= 171) + # expected values generated using SymPy + expectations = {(400, 38965): 0.48444283672113314099, + (401, 39516): 0.66363159823474837662, + (800, 156772): 0.42265448483120932055, + (801, 157849): 0.53437553412194416236, + (1600, 637472): 0.84200727400323538419, + (1601, 630304): 0.34465255088058593946} + + for nc, expected in expectations.items(): + res = _mstats_basic._kendall_p_exact(nc[0], nc[1]) + assert_almost_equal(res, expected) + + @skip_xp_invalid_arg + # mstats.pointbiserialr returns a NumPy float for the statistic, but converts + # it to a masked array with no masked elements before calling `special.betainc`, + # which won't accept masked arrays when `SCIPY_ARRAY_API=1`. + def test_pointbiserial(self): + x = [1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, + 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1] + y = [14.8, 13.8, 12.4, 10.1, 7.1, 6.1, 5.8, 4.6, 4.3, 3.5, 3.3, 3.2, + 3.0, 2.8, 2.8, 2.5, 2.4, 2.3, 2.1, 1.7, 1.7, 1.5, 1.3, 1.3, 1.2, + 1.2, 1.1, 0.8, 0.7, 0.6, 0.5, 0.2, 0.2, 0.1, np.nan] + assert_almost_equal(mstats.pointbiserialr(x, y)[0], 0.36149, 5) + + # test for namedtuple attributes + res = mstats.pointbiserialr(x, y) + attributes = ('correlation', 'pvalue') + check_named_results(res, attributes, ma=True) + + +@skip_xp_invalid_arg +class TestTrimming: + + def test_trim(self): + a = ma.arange(10) + assert_equal(mstats.trim(a), [0,1,2,3,4,5,6,7,8,9]) + a = ma.arange(10) + assert_equal(mstats.trim(a,(2,8)), [None,None,2,3,4,5,6,7,8,None]) + a = ma.arange(10) + assert_equal(mstats.trim(a,limits=(2,8),inclusive=(False,False)), + [None,None,None,3,4,5,6,7,None,None]) + a = ma.arange(10) + assert_equal(mstats.trim(a,limits=(0.1,0.2),relative=True), + [None,1,2,3,4,5,6,7,None,None]) + + a = ma.arange(12) + a[[0,-1]] = a[5] = masked + assert_equal(mstats.trim(a, (2,8)), + [None, None, 2, 3, 4, None, 6, 7, 8, None, None, None]) + + x = ma.arange(100).reshape(10, 10) + expected = [1]*10 + [0]*70 + [1]*20 + trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=None) + assert_equal(trimx._mask.ravel(), expected) + trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=0) + assert_equal(trimx._mask.ravel(), expected) + trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=-1) + assert_equal(trimx._mask.T.ravel(), expected) + + # same as above, but with an extra masked row inserted + x = ma.arange(110).reshape(11, 10) + x[1] = masked + expected = [1]*20 + [0]*70 + [1]*20 + trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=None) + assert_equal(trimx._mask.ravel(), expected) + trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=0) + assert_equal(trimx._mask.ravel(), expected) + trimx = mstats.trim(x.T, (0.1,0.2), relative=True, axis=-1) + assert_equal(trimx.T._mask.ravel(), expected) + + def test_trim_old(self): + x = ma.arange(100) + assert_equal(mstats.trimboth(x).count(), 60) + assert_equal(mstats.trimtail(x,tail='r').count(), 80) + x[50:70] = masked + trimx = mstats.trimboth(x) + assert_equal(trimx.count(), 48) + assert_equal(trimx._mask, [1]*16 + [0]*34 + [1]*20 + [0]*14 + [1]*16) + x._mask = nomask + x.shape = (10,10) + assert_equal(mstats.trimboth(x).count(), 60) + assert_equal(mstats.trimtail(x).count(), 80) + + def test_trimr(self): + x = ma.arange(10) + result = mstats.trimr(x, limits=(0.15, 0.14), inclusive=(False, False)) + expected = ma.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + mask=[1, 1, 0, 0, 0, 0, 0, 0, 0, 1]) + assert_equal(result, expected) + assert_equal(result.mask, expected.mask) + + def test_trimmedmean(self): + data = ma.array([77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(mstats.trimmed_mean(data,0.1), 343, 0) + assert_almost_equal(mstats.trimmed_mean(data,(0.1,0.1)), 343, 0) + assert_almost_equal(mstats.trimmed_mean(data,(0.2,0.2)), 283, 0) + + def test_trimmedvar(self): + # Basic test. Additional tests of all arguments, edge cases, + # input validation, and proper treatment of masked arrays are needed. + rng = np.random.default_rng(3262323289434724460) + data_orig = rng.random(size=20) + data = np.sort(data_orig) + data = ma.array(data, mask=[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]) + assert_allclose(mstats.trimmed_var(data_orig, 0.1), data.var()) + + def test_trimmedstd(self): + # Basic test. Additional tests of all arguments, edge cases, + # input validation, and proper treatment of masked arrays are needed. + rng = np.random.default_rng(7121029245207162780) + data_orig = rng.random(size=20) + data = np.sort(data_orig) + data = ma.array(data, mask=[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]) + assert_allclose(mstats.trimmed_std(data_orig, 0.1), data.std()) + + def test_trimmed_stde(self): + data = ma.array([77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(mstats.trimmed_stde(data,(0.2,0.2)), 56.13193, 5) + assert_almost_equal(mstats.trimmed_stde(data,0.2), 56.13193, 5) + + def test_winsorization(self): + data = ma.array([77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(mstats.winsorize(data,(0.2,0.2)).var(ddof=1), + 21551.4, 1) + assert_almost_equal( + mstats.winsorize(data, (0.2,0.2),(False,False)).var(ddof=1), + 11887.3, 1) + data[5] = masked + winsorized = mstats.winsorize(data) + assert_equal(winsorized.mask, data.mask) + + def test_winsorization_nan(self): + data = ma.array([np.nan, np.nan, 0, 1, 2]) + assert_raises(ValueError, mstats.winsorize, data, (0.05, 0.05), + nan_policy='raise') + # Testing propagate (default behavior) + assert_equal(mstats.winsorize(data, (0.4, 0.4)), + ma.array([2, 2, 2, 2, 2])) + assert_equal(mstats.winsorize(data, (0.8, 0.8)), + ma.array([np.nan, np.nan, np.nan, np.nan, np.nan])) + assert_equal(mstats.winsorize(data, (0.4, 0.4), nan_policy='omit'), + ma.array([np.nan, np.nan, 2, 2, 2])) + assert_equal(mstats.winsorize(data, (0.8, 0.8), nan_policy='omit'), + ma.array([np.nan, np.nan, 2, 2, 2])) + + +@skip_xp_invalid_arg +class TestMoments: + # Comparison numbers are found using R v.1.5.1 + # note that length(testcase) = 4 + # testmathworks comes from documentation for the + # Statistics Toolbox for Matlab and can be found at both + # https://www.mathworks.com/help/stats/kurtosis.html + # https://www.mathworks.com/help/stats/skewness.html + # Note that both test cases came from here. + testcase = [1,2,3,4] + testmathworks = ma.fix_invalid([1.165, 0.6268, 0.0751, 0.3516, -0.6965, + np.nan]) + testcase_2d = ma.array( + np.array([[0.05245846, 0.50344235, 0.86589117, 0.36936353, 0.46961149], + [0.11574073, 0.31299969, 0.45925772, 0.72618805, 0.75194407], + [0.67696689, 0.91878127, 0.09769044, 0.04645137, 0.37615733], + [0.05903624, 0.29908861, 0.34088298, 0.66216337, 0.83160998], + [0.64619526, 0.94894632, 0.27855892, 0.0706151, 0.39962917]]), + mask=np.array([[True, False, False, True, False], + [True, True, True, False, True], + [False, False, False, False, False], + [True, True, True, True, True], + [False, False, True, False, False]], dtype=bool)) + + def _assert_equal(self, actual, expect, *, shape=None, dtype=None): + expect = np.asarray(expect) + if shape is not None: + expect = np.broadcast_to(expect, shape) + assert_array_equal(actual, expect) + if dtype is None: + dtype = expect.dtype + assert actual.dtype == dtype + + def test_moment(self): + y = mstats.moment(self.testcase,1) + assert_almost_equal(y,0.0,10) + y = mstats.moment(self.testcase,2) + assert_almost_equal(y,1.25) + y = mstats.moment(self.testcase,3) + assert_almost_equal(y,0.0) + y = mstats.moment(self.testcase,4) + assert_almost_equal(y,2.5625) + + # check array_like input for moment + y = mstats.moment(self.testcase, [1, 2, 3, 4]) + assert_allclose(y, [0, 1.25, 0, 2.5625]) + + # check moment input consists only of integers + y = mstats.moment(self.testcase, 0.0) + assert_allclose(y, 1.0) + assert_raises(ValueError, mstats.moment, self.testcase, 1.2) + y = mstats.moment(self.testcase, [1.0, 2, 3, 4.0]) + assert_allclose(y, [0, 1.25, 0, 2.5625]) + + # test empty input + y = mstats.moment([]) + self._assert_equal(y, np.nan, dtype=np.float64) + y = mstats.moment(np.array([], dtype=np.float32)) + self._assert_equal(y, np.nan, dtype=np.float32) + y = mstats.moment(np.zeros((1, 0)), axis=0) + self._assert_equal(y, [], shape=(0,), dtype=np.float64) + y = mstats.moment([[]], axis=1) + self._assert_equal(y, np.nan, shape=(1,), dtype=np.float64) + y = mstats.moment([[]], moment=[0, 1], axis=0) + self._assert_equal(y, [], shape=(2, 0)) + + x = np.arange(10.) + x[9] = np.nan + assert_equal(mstats.moment(x, 2), ma.masked) # NaN value is ignored + + def test_variation(self): + y = mstats.variation(self.testcase) + assert_almost_equal(y,0.44721359549996, 10) + + def test_variation_ddof(self): + # test variation with delta degrees of freedom + # regression test for gh-13341 + a = np.array([1, 2, 3, 4, 5]) + y = mstats.variation(a, ddof=1) + assert_almost_equal(y, 0.5270462766947299) + + def test_skewness(self): + y = mstats.skew(self.testmathworks) + assert_almost_equal(y,-0.29322304336607,10) + y = mstats.skew(self.testmathworks,bias=0) + assert_almost_equal(y,-0.437111105023940,10) + y = mstats.skew(self.testcase) + assert_almost_equal(y,0.0,10) + + # test that skew works on multidimensional masked arrays + correct_2d = ma.array( + np.array([0.6882870394455785, 0, 0.2665647526856708, + 0, -0.05211472114254485]), + mask=np.array([False, False, False, True, False], dtype=bool) + ) + assert_allclose(mstats.skew(self.testcase_2d, 1), correct_2d) + for i, row in enumerate(self.testcase_2d): + assert_almost_equal(mstats.skew(row), correct_2d[i]) + + correct_2d_bias_corrected = ma.array( + np.array([1.685952043212545, 0.0, 0.3973712716070531, 0, + -0.09026534484117164]), + mask=np.array([False, False, False, True, False], dtype=bool) + ) + assert_allclose(mstats.skew(self.testcase_2d, 1, bias=False), + correct_2d_bias_corrected) + for i, row in enumerate(self.testcase_2d): + assert_almost_equal(mstats.skew(row, bias=False), + correct_2d_bias_corrected[i]) + + # Check consistency between stats and mstats implementations + assert_allclose(mstats.skew(self.testcase_2d[2, :]), + stats.skew(self.testcase_2d[2, :])) + + def test_kurtosis(self): + # Set flags for axis = 0 and fisher=0 (Pearson's definition of kurtosis + # for compatibility with Matlab) + y = mstats.kurtosis(self.testmathworks, 0, fisher=0, bias=1) + assert_almost_equal(y, 2.1658856802973, 10) + # Note that MATLAB has confusing docs for the following case + # kurtosis(x,0) gives an unbiased estimate of Pearson's skewness + # kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3) + # The MATLAB docs imply that both should give Fisher's + y = mstats.kurtosis(self.testmathworks, fisher=0, bias=0) + assert_almost_equal(y, 3.663542721189047, 10) + y = mstats.kurtosis(self.testcase, 0, 0) + assert_almost_equal(y, 1.64) + + # test that kurtosis works on multidimensional masked arrays + correct_2d = ma.array(np.array([-1.5, -3., -1.47247052385, 0., + -1.26979517952]), + mask=np.array([False, False, False, True, + False], dtype=bool)) + assert_array_almost_equal(mstats.kurtosis(self.testcase_2d, 1), + correct_2d) + for i, row in enumerate(self.testcase_2d): + assert_almost_equal(mstats.kurtosis(row), correct_2d[i]) + + correct_2d_bias_corrected = ma.array( + np.array([-1.5, -3., -1.88988209538, 0., -0.5234638463918877]), + mask=np.array([False, False, False, True, False], dtype=bool)) + assert_array_almost_equal(mstats.kurtosis(self.testcase_2d, 1, + bias=False), + correct_2d_bias_corrected) + for i, row in enumerate(self.testcase_2d): + assert_almost_equal(mstats.kurtosis(row, bias=False), + correct_2d_bias_corrected[i]) + + # Check consistency between stats and mstats implementations + assert_array_almost_equal_nulp(mstats.kurtosis(self.testcase_2d[2, :]), + stats.kurtosis(self.testcase_2d[2, :]), + nulp=4) + + +class TestMode: + def test_mode(self): + a1 = [0,0,0,1,1,1,2,3,3,3,3,4,5,6,7] + a2 = np.reshape(a1, (3,5)) + a3 = np.array([1,2,3,4,5,6]) + a4 = np.reshape(a3, (3,2)) + ma1 = ma.masked_where(ma.array(a1) > 2, a1) + ma2 = ma.masked_where(a2 > 2, a2) + ma3 = ma.masked_where(a3 < 2, a3) + ma4 = ma.masked_where(ma.array(a4) < 2, a4) + assert_equal(mstats.mode(a1, axis=None), (3,4)) + assert_equal(mstats.mode(a1, axis=0), (3,4)) + assert_equal(mstats.mode(ma1, axis=None), (0,3)) + assert_equal(mstats.mode(a2, axis=None), (3,4)) + assert_equal(mstats.mode(ma2, axis=None), (0,3)) + assert_equal(mstats.mode(a3, axis=None), (1,1)) + assert_equal(mstats.mode(ma3, axis=None), (2,1)) + assert_equal(mstats.mode(a2, axis=0), ([[0,0,0,1,1]], [[1,1,1,1,1]])) + assert_equal(mstats.mode(ma2, axis=0), ([[0,0,0,1,1]], [[1,1,1,1,1]])) + assert_equal(mstats.mode(a2, axis=-1), ([[0],[3],[3]], [[3],[3],[1]])) + assert_equal(mstats.mode(ma2, axis=-1), ([[0],[1],[0]], [[3],[1],[0]])) + assert_equal(mstats.mode(ma4, axis=0), ([[3,2]], [[1,1]])) + assert_equal(mstats.mode(ma4, axis=-1), ([[2],[3],[5]], [[1],[1],[1]])) + + a1_res = mstats.mode(a1, axis=None) + + # test for namedtuple attributes + attributes = ('mode', 'count') + check_named_results(a1_res, attributes, ma=True) + + def test_mode_modifies_input(self): + # regression test for gh-6428: mode(..., axis=None) may not modify + # the input array + im = np.zeros((100, 100)) + im[:50, :] += 1 + im[:, :50] += 1 + cp = im.copy() + mstats.mode(im, None) + assert_equal(im, cp) + + +class TestPercentile: + def setup_method(self): + self.a1 = [3, 4, 5, 10, -3, -5, 6] + self.a2 = [3, -6, -2, 8, 7, 4, 2, 1] + self.a3 = [3., 4, 5, 10, -3, -5, -6, 7.0] + + def test_percentile(self): + x = np.arange(8) * 0.5 + assert_equal(mstats.scoreatpercentile(x, 0), 0.) + assert_equal(mstats.scoreatpercentile(x, 100), 3.5) + assert_equal(mstats.scoreatpercentile(x, 50), 1.75) + + def test_2D(self): + x = ma.array([[1, 1, 1], + [1, 1, 1], + [4, 4, 3], + [1, 1, 1], + [1, 1, 1]]) + assert_equal(mstats.scoreatpercentile(x, 50), [1, 1, 1]) + + +@skip_xp_invalid_arg +class TestVariability: + """ Comparison numbers are found using R v.1.5.1 + note that length(testcase) = 4 + """ + testcase = ma.fix_invalid([1,2,3,4,np.nan]) + + def test_sem(self): + # This is not in R, so used: sqrt(var(testcase)*3/4) / sqrt(3) + y = mstats.sem(self.testcase) + assert_almost_equal(y, 0.6454972244) + n = self.testcase.count() + assert_allclose(mstats.sem(self.testcase, ddof=0) * np.sqrt(n/(n-2)), + mstats.sem(self.testcase, ddof=2)) + + def test_zmap(self): + # This is not in R, so tested by using: + # (testcase[i]-mean(testcase,axis=0)) / sqrt(var(testcase)*3/4) + y = mstats.zmap(self.testcase, self.testcase) + desired_unmaskedvals = ([-1.3416407864999, -0.44721359549996, + 0.44721359549996, 1.3416407864999]) + assert_array_almost_equal(desired_unmaskedvals, + y.data[y.mask == False], decimal=12) # noqa: E712 + + def test_zscore(self): + # This is not in R, so tested by using: + # (testcase[i]-mean(testcase,axis=0)) / sqrt(var(testcase)*3/4) + y = mstats.zscore(self.testcase) + desired = ma.fix_invalid([-1.3416407864999, -0.44721359549996, + 0.44721359549996, 1.3416407864999, np.nan]) + assert_almost_equal(desired, y, decimal=12) + + +@skip_xp_invalid_arg +class TestMisc: + + def test_obrientransform(self): + args = [[5]*5+[6]*11+[7]*9+[8]*3+[9]*2+[10]*2, + [6]+[7]*2+[8]*4+[9]*9+[10]*16] + result = [5*[3.1828]+11*[0.5591]+9*[0.0344]+3*[1.6086]+2*[5.2817]+2*[11.0538], + [10.4352]+2*[4.8599]+4*[1.3836]+9*[0.0061]+16*[0.7277]] + assert_almost_equal(np.round(mstats.obrientransform(*args).T, 4), + result, 4) + + def test_ks_2samp(self): + x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1], + [4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3], + [3, 2, 5, 6, 18, 4, 9, 1, 1, nan, 1, 1, nan], + [nan, 6, 11, 4, 17, nan, 6, 1, 1, 2, 5, 1, 1]] + x = ma.fix_invalid(x).T + (winter, spring, summer, fall) = x.T + + assert_almost_equal(np.round(mstats.ks_2samp(winter, spring), 4), + (0.1818, 0.9628)) + assert_almost_equal(np.round(mstats.ks_2samp(winter, spring, 'g'), 4), + (0.1469, 0.6886)) + assert_almost_equal(np.round(mstats.ks_2samp(winter, spring, 'l'), 4), + (0.1818, 0.6011)) + + def test_friedmanchisq(self): + # No missing values + args = ([9.0,9.5,5.0,7.5,9.5,7.5,8.0,7.0,8.5,6.0], + [7.0,6.5,7.0,7.5,5.0,8.0,6.0,6.5,7.0,7.0], + [6.0,8.0,4.0,6.0,7.0,6.5,6.0,4.0,6.5,3.0]) + result = mstats.friedmanchisquare(*args) + assert_almost_equal(result[0], 10.4737, 4) + assert_almost_equal(result[1], 0.005317, 6) + # Missing values + x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1], + [4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3], + [3, 2, 5, 6, 18, 4, 9, 1, 1,nan, 1, 1,nan], + [nan, 6, 11, 4, 17,nan, 6, 1, 1, 2, 5, 1, 1]] + x = ma.fix_invalid(x) + result = mstats.friedmanchisquare(*x) + assert_almost_equal(result[0], 2.0156, 4) + assert_almost_equal(result[1], 0.5692, 4) + + # test for namedtuple attributes + attributes = ('statistic', 'pvalue') + check_named_results(result, attributes, ma=True) + + +def test_regress_simple(): + # Regress a line with sinusoidal noise. Test for #1273. + x = np.linspace(0, 100, 100) + y = 0.2 * np.linspace(0, 100, 100) + 10 + y += np.sin(np.linspace(0, 20, 100)) + + result = mstats.linregress(x, y) + + # Result is of a correct class and with correct fields + lr = _stats_py.LinregressResult + assert_(isinstance(result, lr)) + attributes = ('slope', 'intercept', 'rvalue', 'pvalue', 'stderr') + check_named_results(result, attributes, ma=True) + assert 'intercept_stderr' in dir(result) + + # Slope and intercept are estimated correctly + assert_almost_equal(result.slope, 0.19644990055858422) + assert_almost_equal(result.intercept, 10.211269918932341) + assert_almost_equal(result.stderr, 0.002395781449783862) + assert_almost_equal(result.intercept_stderr, 0.13866936078570702) + + +def test_linregress_identical_x(): + x = np.zeros(10) + y = np.random.random(10) + msg = "Cannot calculate a linear regression if all x values are identical" + with assert_raises(ValueError, match=msg): + mstats.linregress(x, y) + + +class TestTheilslopes: + def test_theilslopes(self): + # Test for basic slope and intercept. + slope, intercept, lower, upper = mstats.theilslopes([0, 1, 1]) + assert_almost_equal(slope, 0.5) + assert_almost_equal(intercept, 0.5) + + slope, intercept, lower, upper = mstats.theilslopes([0, 1, 1], + method='joint') + assert_almost_equal(slope, 0.5) + assert_almost_equal(intercept, 0.0) + + # Test for correct masking. + y = np.ma.array([0, 1, 100, 1], mask=[False, False, True, False]) + slope, intercept, lower, upper = mstats.theilslopes(y) + assert_almost_equal(slope, 1./3) + assert_almost_equal(intercept, 2./3) + + slope, intercept, lower, upper = mstats.theilslopes(y, + method='joint') + assert_almost_equal(slope, 1./3) + assert_almost_equal(intercept, 0.0) + + # Test of confidence intervals from example in Sen (1968). + x = [1, 2, 3, 4, 10, 12, 18] + y = [9, 15, 19, 20, 45, 55, 78] + slope, intercept, lower, upper = mstats.theilslopes(y, x, 0.07) + assert_almost_equal(slope, 4) + assert_almost_equal(intercept, 4.0) + assert_almost_equal(upper, 4.38, decimal=2) + assert_almost_equal(lower, 3.71, decimal=2) + + slope, intercept, lower, upper = mstats.theilslopes(y, x, 0.07, + method='joint') + assert_almost_equal(slope, 4) + assert_almost_equal(intercept, 6.0) + assert_almost_equal(upper, 4.38, decimal=2) + assert_almost_equal(lower, 3.71, decimal=2) + + + def test_theilslopes_warnings(self): + # Test `theilslopes` with degenerate input; see gh-15943 + msg = "All `x` coordinates.*|Mean of empty slice.|invalid value encountered.*" + with pytest.warns(RuntimeWarning, match=msg): + res = mstats.theilslopes([0, 1], [0, 0]) + assert np.all(np.isnan(res)) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered...") + res = mstats.theilslopes([0, 0, 0], [0, 1, 0]) + assert_allclose(res, (0, 0, np.nan, np.nan)) + + + def test_theilslopes_namedtuple_consistency(self): + """ + Simple test to ensure tuple backwards-compatibility of the returned + TheilslopesResult object + """ + y = [1, 2, 4] + x = [4, 6, 8] + slope, intercept, low_slope, high_slope = mstats.theilslopes(y, x) + result = mstats.theilslopes(y, x) + + # note all four returned values are distinct here + assert_equal(slope, result.slope) + assert_equal(intercept, result.intercept) + assert_equal(low_slope, result.low_slope) + assert_equal(high_slope, result.high_slope) + + def test_gh19678_uint8(self): + # `theilslopes` returned unexpected results when `y` was an unsigned type. + # Check that this is resolved. + rng = np.random.default_rng(2549824598234528) + y = rng.integers(0, 255, size=10, dtype=np.uint8) + res = stats.theilslopes(y, y) + np.testing.assert_allclose(res.slope, 1) + + +def test_siegelslopes(): + # method should be exact for straight line + y = 2 * np.arange(10) + 0.5 + assert_equal(mstats.siegelslopes(y), (2.0, 0.5)) + assert_equal(mstats.siegelslopes(y, method='separate'), (2.0, 0.5)) + + x = 2 * np.arange(10) + y = 5 * x - 3.0 + assert_equal(mstats.siegelslopes(y, x), (5.0, -3.0)) + assert_equal(mstats.siegelslopes(y, x, method='separate'), (5.0, -3.0)) + + # method is robust to outliers: brekdown point of 50% + y[:4] = 1000 + assert_equal(mstats.siegelslopes(y, x), (5.0, -3.0)) + + # if there are no outliers, results should be comparable to linregress + x = np.arange(10) + y = -2.3 + 0.3*x + stats.norm.rvs(size=10, random_state=231) + slope_ols, intercept_ols, _, _, _ = stats.linregress(x, y) + + slope, intercept = mstats.siegelslopes(y, x) + assert_allclose(slope, slope_ols, rtol=0.1) + assert_allclose(intercept, intercept_ols, rtol=0.1) + + slope, intercept = mstats.siegelslopes(y, x, method='separate') + assert_allclose(slope, slope_ols, rtol=0.1) + assert_allclose(intercept, intercept_ols, rtol=0.1) + + +def test_siegelslopes_namedtuple_consistency(): + """ + Simple test to ensure tuple backwards-compatibility of the returned + SiegelslopesResult object. + """ + y = [1, 2, 4] + x = [4, 6, 8] + slope, intercept = mstats.siegelslopes(y, x) + result = mstats.siegelslopes(y, x) + + # note both returned values are distinct here + assert_equal(slope, result.slope) + assert_equal(intercept, result.intercept) + + +def test_sen_seasonal_slopes(): + rng = np.random.default_rng(5765986256978575148) + x = rng.random(size=(100, 4)) + intra_slope, inter_slope = mstats.sen_seasonal_slopes(x) + + # reference implementation from the `sen_seasonal_slopes` documentation + def dijk(yi): + n = len(yi) + x = np.arange(n) + dy = yi - yi[:, np.newaxis] + dx = x - x[:, np.newaxis] + mask = np.triu(np.ones((n, n), dtype=bool), k=1) + return dy[mask]/dx[mask] + + for i in range(4): + assert_allclose(np.median(dijk(x[:, i])), intra_slope[i]) + + all_slopes = np.concatenate([dijk(x[:, i]) for i in range(x.shape[1])]) + assert_allclose(np.median(all_slopes), inter_slope) + + +def test_plotting_positions(): + # Regression test for #1256 + pos = mstats.plotting_positions(np.arange(3), 0, 0) + assert_array_almost_equal(pos.data, np.array([0.25, 0.5, 0.75])) + + +@skip_xp_invalid_arg +class TestNormalitytests: + + def test_vs_nonmasked(self): + x = np.array((-2, -1, 0, 1, 2, 3)*4)**2 + assert_array_almost_equal(mstats.normaltest(x), + stats.normaltest(x)) + assert_array_almost_equal(mstats.skewtest(x), + stats.skewtest(x)) + assert_array_almost_equal(mstats.kurtosistest(x), + stats.kurtosistest(x)) + + funcs = [stats.normaltest, stats.skewtest, stats.kurtosistest] + mfuncs = [mstats.normaltest, mstats.skewtest, mstats.kurtosistest] + x = [1, 2, 3, 4] + for func, mfunc in zip(funcs, mfuncs): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = func(x) + assert np.isnan(res.statistic) + assert np.isnan(res.pvalue) + assert_raises(ValueError, mfunc, x) + + def test_axis_None(self): + # Test axis=None (equal to axis=0 for 1-D input) + x = np.array((-2,-1,0,1,2,3)*4)**2 + assert_allclose(mstats.normaltest(x, axis=None), mstats.normaltest(x)) + assert_allclose(mstats.skewtest(x, axis=None), mstats.skewtest(x)) + assert_allclose(mstats.kurtosistest(x, axis=None), + mstats.kurtosistest(x)) + + def test_maskedarray_input(self): + # Add some masked values, test result doesn't change + x = np.array((-2, -1, 0, 1, 2, 3)*4)**2 + xm = np.ma.array(np.r_[np.inf, x, 10], + mask=np.r_[True, [False] * x.size, True]) + assert_allclose(mstats.normaltest(xm), stats.normaltest(x)) + assert_allclose(mstats.skewtest(xm), stats.skewtest(x)) + assert_allclose(mstats.kurtosistest(xm), stats.kurtosistest(x)) + + def test_nd_input(self): + x = np.array((-2, -1, 0, 1, 2, 3)*4)**2 + x_2d = np.vstack([x] * 2).T + for func in [mstats.normaltest, mstats.skewtest, mstats.kurtosistest]: + res_1d = func(x) + res_2d = func(x_2d) + assert_allclose(res_2d[0], [res_1d[0]] * 2) + assert_allclose(res_2d[1], [res_1d[1]] * 2) + + def test_normaltest_result_attributes(self): + x = np.array((-2, -1, 0, 1, 2, 3)*4)**2 + res = mstats.normaltest(x) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_kurtosistest_result_attributes(self): + x = np.array((-2, -1, 0, 1, 2, 3)*4)**2 + res = mstats.kurtosistest(x) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_regression_9033(self): + # x clearly non-normal but power of negative denom needs + # to be handled correctly to reject normality + counts = [128, 0, 58, 7, 0, 41, 16, 0, 0, 167] + x = np.hstack([np.full(c, i) for i, c in enumerate(counts)]) + assert_equal(mstats.kurtosistest(x)[1] < 0.01, True) + + @pytest.mark.parametrize("test", ["skewtest", "kurtosistest"]) + @pytest.mark.parametrize("alternative", ["less", "greater"]) + def test_alternative(self, test, alternative): + x = stats.norm.rvs(loc=10, scale=2.5, size=30, random_state=123) + + stats_test = getattr(stats, test) + mstats_test = getattr(mstats, test) + + z_ex, p_ex = stats_test(x, alternative=alternative) + z, p = mstats_test(x, alternative=alternative) + assert_allclose(z, z_ex, atol=1e-12) + assert_allclose(p, p_ex, atol=1e-12) + + # test with masked arrays + x[1:5] = np.nan + x = np.ma.masked_array(x, mask=np.isnan(x)) + z_ex, p_ex = stats_test(x.compressed(), alternative=alternative) + z, p = mstats_test(x, alternative=alternative) + assert_allclose(z, z_ex, atol=1e-12) + assert_allclose(p, p_ex, atol=1e-12) + + def test_bad_alternative(self): + x = stats.norm.rvs(size=20, random_state=123) + msg = r"`alternative` must be..." + + with pytest.raises(ValueError, match=msg): + mstats.skewtest(x, alternative='error') + + with pytest.raises(ValueError, match=msg): + mstats.kurtosistest(x, alternative='error') + + +class TestFOneway: + def test_result_attributes(self): + a = np.array([655, 788], dtype=np.uint16) + b = np.array([789, 772], dtype=np.uint16) + res = mstats.f_oneway(a, b) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + +class TestMannwhitneyu: + # data from gh-1428 + x = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 2., 1., 1., 2., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 3., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1.]) + + y = np.array([1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., 1., 1., 1., + 2., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., 1., 1., 3., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., + 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., + 2., 1., 1., 2., 1., 1., 2., 1., 2., 1., 1., 1., 1., 2., + 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 2., 1., 1., 1., 1., 1., 2., 2., 2., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 2., 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 2., 1., 1., + 1., 1., 1., 1.]) + + def test_result_attributes(self): + res = mstats.mannwhitneyu(self.x, self.y) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_against_stats(self): + # gh-4641 reported that stats.mannwhitneyu returned half the p-value + # of mstats.mannwhitneyu. Default alternative of stats.mannwhitneyu + # is now two-sided, so they match. + res1 = mstats.mannwhitneyu(self.x, self.y) + res2 = stats.mannwhitneyu(self.x, self.y) + assert res1.statistic == res2.statistic + assert_allclose(res1.pvalue, res2.pvalue) + + +class TestKruskal: + def test_result_attributes(self): + x = [1, 3, 5, 7, 9] + y = [2, 4, 6, 8, 10] + + res = mstats.kruskal(x, y) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + +# TODO: for all ttest functions, add tests with masked array inputs +class TestTtest_rel: + def test_vs_nonmasked(self): + np.random.seed(1234567) + outcome = np.random.randn(20, 4) + [0, 0, 1, 2] + + # 1-D inputs + res1 = stats.ttest_rel(outcome[:, 0], outcome[:, 1]) + res2 = mstats.ttest_rel(outcome[:, 0], outcome[:, 1]) + assert_allclose(res1, res2) + + # 2-D inputs + res1 = stats.ttest_rel(outcome[:, 0], outcome[:, 1], axis=None) + res2 = mstats.ttest_rel(outcome[:, 0], outcome[:, 1], axis=None) + assert_allclose(res1, res2) + res1 = stats.ttest_rel(outcome[:, :2], outcome[:, 2:], axis=0) + res2 = mstats.ttest_rel(outcome[:, :2], outcome[:, 2:], axis=0) + assert_allclose(res1, res2) + + # Check default is axis=0 + res3 = mstats.ttest_rel(outcome[:, :2], outcome[:, 2:]) + assert_allclose(res2, res3) + + def test_fully_masked(self): + np.random.seed(1234567) + outcome = ma.masked_array(np.random.randn(3, 2), + mask=[[1, 1, 1], [0, 0, 0]]) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in absolute") + for pair in [(outcome[:, 0], outcome[:, 1]), + ([np.nan, np.nan], [1.0, 2.0])]: + t, p = mstats.ttest_rel(*pair) + assert_array_equal(t, (np.nan, np.nan)) + assert_array_equal(p, (np.nan, np.nan)) + + def test_result_attributes(self): + np.random.seed(1234567) + outcome = np.random.randn(20, 4) + [0, 0, 1, 2] + + res = mstats.ttest_rel(outcome[:, 0], outcome[:, 1]) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_invalid_input_size(self): + assert_raises(ValueError, mstats.ttest_rel, + np.arange(10), np.arange(11)) + x = np.arange(24) + assert_raises(ValueError, mstats.ttest_rel, + x.reshape(2, 3, 4), x.reshape(2, 4, 3), axis=1) + assert_raises(ValueError, mstats.ttest_rel, + x.reshape(2, 3, 4), x.reshape(2, 4, 3), axis=2) + + def test_empty(self): + res1 = mstats.ttest_rel([], []) + assert_(np.all(np.isnan(res1))) + + def test_zero_division(self): + t, p = mstats.ttest_ind([0, 0, 0], [1, 1, 1]) + assert_equal((np.abs(t), p), (np.inf, 0)) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in absolute") + t, p = mstats.ttest_ind([0, 0, 0], [0, 0, 0]) + assert_array_equal(t, np.array([np.nan, np.nan])) + assert_array_equal(p, np.array([np.nan, np.nan])) + + def test_bad_alternative(self): + msg = r"alternative must be 'less', 'greater' or 'two-sided'" + with pytest.raises(ValueError, match=msg): + mstats.ttest_ind([1, 2, 3], [4, 5, 6], alternative='foo') + + @pytest.mark.parametrize("alternative", ["less", "greater"]) + def test_alternative(self, alternative): + x = stats.norm.rvs(loc=10, scale=5, size=25, random_state=42) + y = stats.norm.rvs(loc=8, scale=2, size=25, random_state=42) + + t_ex, p_ex = stats.ttest_rel(x, y, alternative=alternative) + t, p = mstats.ttest_rel(x, y, alternative=alternative) + assert_allclose(t, t_ex, rtol=1e-14) + assert_allclose(p, p_ex, rtol=1e-14) + + # test with masked arrays + x[1:10] = np.nan + y[1:10] = np.nan + x = np.ma.masked_array(x, mask=np.isnan(x)) + y = np.ma.masked_array(y, mask=np.isnan(y)) + t, p = mstats.ttest_rel(x, y, alternative=alternative) + t_ex, p_ex = stats.ttest_rel(x.compressed(), y.compressed(), + alternative=alternative) + assert_allclose(t, t_ex, rtol=1e-14) + assert_allclose(p, p_ex, rtol=1e-14) + + +class TestTtest_ind: + def test_vs_nonmasked(self): + np.random.seed(1234567) + outcome = np.random.randn(20, 4) + [0, 0, 1, 2] + + # 1-D inputs + res1 = stats.ttest_ind(outcome[:, 0], outcome[:, 1]) + res2 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1]) + assert_allclose(res1, res2) + + # 2-D inputs + res1 = stats.ttest_ind(outcome[:, 0], outcome[:, 1], axis=None) + res2 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1], axis=None) + assert_allclose(res1, res2) + res1 = stats.ttest_ind(outcome[:, :2], outcome[:, 2:], axis=0) + res2 = mstats.ttest_ind(outcome[:, :2], outcome[:, 2:], axis=0) + assert_allclose(res1, res2) + + # Check default is axis=0 + res3 = mstats.ttest_ind(outcome[:, :2], outcome[:, 2:]) + assert_allclose(res2, res3) + + # Check equal_var + res4 = stats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=True) + res5 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=True) + assert_allclose(res4, res5) + res4 = stats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=False) + res5 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=False) + assert_allclose(res4, res5) + + def test_fully_masked(self): + np.random.seed(1234567) + outcome = ma.masked_array(np.random.randn(3, 2), mask=[[1, 1, 1], [0, 0, 0]]) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in absolute") + for pair in [(outcome[:, 0], outcome[:, 1]), + ([np.nan, np.nan], [1.0, 2.0])]: + t, p = mstats.ttest_ind(*pair) + assert_array_equal(t, (np.nan, np.nan)) + assert_array_equal(p, (np.nan, np.nan)) + + def test_result_attributes(self): + np.random.seed(1234567) + outcome = np.random.randn(20, 4) + [0, 0, 1, 2] + + res = mstats.ttest_ind(outcome[:, 0], outcome[:, 1]) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_empty(self): + res1 = mstats.ttest_ind([], []) + assert_(np.all(np.isnan(res1))) + + def test_zero_division(self): + t, p = mstats.ttest_ind([0, 0, 0], [1, 1, 1]) + assert_equal((np.abs(t), p), (np.inf, 0)) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in absolute") + t, p = mstats.ttest_ind([0, 0, 0], [0, 0, 0]) + assert_array_equal(t, (np.nan, np.nan)) + assert_array_equal(p, (np.nan, np.nan)) + + t, p = mstats.ttest_ind([0, 0, 0], [1, 1, 1], equal_var=False) + assert_equal((np.abs(t), p), (np.inf, 0)) + assert_array_equal(mstats.ttest_ind([0, 0, 0], [0, 0, 0], + equal_var=False), (np.nan, np.nan)) + + def test_bad_alternative(self): + msg = r"alternative must be 'less', 'greater' or 'two-sided'" + with pytest.raises(ValueError, match=msg): + mstats.ttest_ind([1, 2, 3], [4, 5, 6], alternative='foo') + + @pytest.mark.parametrize("alternative", ["less", "greater"]) + def test_alternative(self, alternative): + x = stats.norm.rvs(loc=10, scale=2, size=100, random_state=123) + y = stats.norm.rvs(loc=8, scale=2, size=100, random_state=123) + + t_ex, p_ex = stats.ttest_ind(x, y, alternative=alternative) + t, p = mstats.ttest_ind(x, y, alternative=alternative) + assert_allclose(t, t_ex, rtol=1e-14) + assert_allclose(p, p_ex, rtol=1e-14) + + # test with masked arrays + x[1:10] = np.nan + y[80:90] = np.nan + x = np.ma.masked_array(x, mask=np.isnan(x)) + y = np.ma.masked_array(y, mask=np.isnan(y)) + t_ex, p_ex = stats.ttest_ind(x.compressed(), y.compressed(), + alternative=alternative) + t, p = mstats.ttest_ind(x, y, alternative=alternative) + assert_allclose(t, t_ex, rtol=1e-14) + assert_allclose(p, p_ex, rtol=1e-14) + + +class TestTtest_1samp: + def test_vs_nonmasked(self): + np.random.seed(1234567) + outcome = np.random.randn(20, 4) + [0, 0, 1, 2] + + # 1-D inputs + res1 = stats.ttest_1samp(outcome[:, 0], 1) + res2 = mstats.ttest_1samp(outcome[:, 0], 1) + assert_allclose(res1, res2) + + def test_fully_masked(self): + np.random.seed(1234567) + outcome = ma.masked_array(np.random.randn(3), mask=[1, 1, 1]) + expected = (np.nan, np.nan) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in absolute") + for pair in [((np.nan, np.nan), 0.0), (outcome, 0.0)]: + t, p = mstats.ttest_1samp(*pair) + assert_array_equal(p, expected) + assert_array_equal(t, expected) + + def test_result_attributes(self): + np.random.seed(1234567) + outcome = np.random.randn(20, 4) + [0, 0, 1, 2] + + res = mstats.ttest_1samp(outcome[:, 0], 1) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_empty(self): + res1 = mstats.ttest_1samp([], 1) + assert_(np.all(np.isnan(res1))) + + def test_zero_division(self): + t, p = mstats.ttest_1samp([0, 0, 0], 1) + assert_equal((np.abs(t), p), (np.inf, 0)) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in absolute") + t, p = mstats.ttest_1samp([0, 0, 0], 0) + assert_(np.isnan(t)) + assert_array_equal(p, (np.nan, np.nan)) + + def test_bad_alternative(self): + msg = r"alternative must be 'less', 'greater' or 'two-sided'" + with pytest.raises(ValueError, match=msg): + mstats.ttest_1samp([1, 2, 3], 4, alternative='foo') + + @pytest.mark.parametrize("alternative", ["less", "greater"]) + def test_alternative(self, alternative): + x = stats.norm.rvs(loc=10, scale=2, size=100, random_state=123) + + t_ex, p_ex = stats.ttest_1samp(x, 9, alternative=alternative) + t, p = mstats.ttest_1samp(x, 9, alternative=alternative) + assert_allclose(t, t_ex, rtol=1e-14) + assert_allclose(p, p_ex, rtol=1e-14) + + # test with masked arrays + x[1:10] = np.nan + x = np.ma.masked_array(x, mask=np.isnan(x)) + t_ex, p_ex = stats.ttest_1samp(x.compressed(), 9, + alternative=alternative) + t, p = mstats.ttest_1samp(x, 9, alternative=alternative) + assert_allclose(t, t_ex, rtol=1e-14) + assert_allclose(p, p_ex, rtol=1e-14) + + +class TestDescribe: + """ + Tests for mstats.describe. + + Note that there are also tests for `mstats.describe` in the + class TestCompareWithStats. + """ + def test_basic_with_axis(self): + # This is a basic test that is also a regression test for gh-7303. + a = np.ma.masked_array([[0, 1, 2, 3, 4, 9], + [5, 5, 0, 9, 3, 3]], + mask=[[0, 0, 0, 0, 0, 1], + [0, 0, 1, 1, 0, 0]]) + result = mstats.describe(a, axis=1) + assert_equal(result.nobs, [5, 4]) + amin, amax = result.minmax + assert_equal(amin, [0, 3]) + assert_equal(amax, [4, 5]) + assert_equal(result.mean, [2.0, 4.0]) + assert_equal(result.variance, [2.0, 1.0]) + assert_equal(result.skewness, [0.0, 0.0]) + assert_allclose(result.kurtosis, [-1.3, -2.0]) + + +@skip_xp_invalid_arg +class TestCompareWithStats: + """ + Class to compare mstats results with stats results. + + It is in general assumed that scipy.stats is at a more mature stage than + stats.mstats. If a routine in mstats results in similar results like in + scipy.stats, this is considered also as a proper validation of scipy.mstats + routine. + + Different sample sizes are used for testing, as some problems between stats + and mstats are dependent on sample size. + + Author: Alexander Loew + + NOTE that some tests fail. This might be caused by + a) actual differences or bugs between stats and mstats + b) numerical inaccuracies + c) different definitions of routine interfaces + + These failures need to be checked. Current workaround is to have disabled these + tests, but issuing reports on scipy-dev + + """ + def get_n(self): + """ Returns list of sample sizes to be used for comparison. """ + return [1000, 100, 10, 5] + + def generate_xy_sample(self, n): + # This routine generates numpy arrays and corresponding masked arrays + # with the same data, but additional masked values + np.random.seed(1234567) + x = np.random.randn(n) + y = x + np.random.randn(n) + xm = np.full(len(x) + 5, 1e16) + ym = np.full(len(y) + 5, 1e16) + xm[0:len(x)] = x + ym[0:len(y)] = y + mask = xm > 9e15 + xm = np.ma.array(xm, mask=mask) + ym = np.ma.array(ym, mask=mask) + return x, y, xm, ym + + def generate_xy_sample2D(self, n, nx): + x = np.full((n, nx), np.nan) + y = np.full((n, nx), np.nan) + xm = np.full((n+5, nx), np.nan) + ym = np.full((n+5, nx), np.nan) + + for i in range(nx): + x[:, i], y[:, i], dx, dy = self.generate_xy_sample(n) + + xm[0:n, :] = x[0:n] + ym[0:n, :] = y[0:n] + xm = np.ma.array(xm, mask=np.isnan(xm)) + ym = np.ma.array(ym, mask=np.isnan(ym)) + return x, y, xm, ym + + def test_linregress(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + result1 = stats.linregress(x, y) + result2 = stats.mstats.linregress(xm, ym) + assert_allclose(np.asarray(result1), np.asarray(result2)) + + def test_pearsonr(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r, p = stats.pearsonr(x, y) + rm, pm = stats.mstats.pearsonr(xm, ym) + + assert_almost_equal(r, rm, decimal=14) + assert_almost_equal(p, pm, decimal=14) + + def test_spearmanr(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r, p = stats.spearmanr(x, y) + rm, pm = stats.mstats.spearmanr(xm, ym) + assert_almost_equal(r, rm, 14) + assert_almost_equal(p, pm, 14) + + def test_spearmanr_backcompat_useties(self): + # A regression test to ensure we don't break backwards compat + # more than we have to (see gh-9204). + x = np.arange(6) + assert_raises(ValueError, mstats.spearmanr, x, x, False) + + def test_gmean(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.gmean(abs(x)) + rm = stats.mstats.gmean(abs(xm)) + assert_allclose(r, rm, rtol=1e-13) + + r = stats.gmean(abs(y)) + rm = stats.mstats.gmean(abs(ym)) + assert_allclose(r, rm, rtol=1e-13) + + def test_hmean(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + + r = stats.hmean(abs(x)) + rm = stats.mstats.hmean(abs(xm)) + assert_almost_equal(r, rm, 10) + + r = stats.hmean(abs(y)) + rm = stats.mstats.hmean(abs(ym)) + assert_almost_equal(r, rm, 10) + + def test_skew(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + + r = stats.skew(x) + rm = stats.mstats.skew(xm) + assert_almost_equal(r, rm, 10) + + r = stats.skew(y) + rm = stats.mstats.skew(ym) + assert_almost_equal(r, rm, 10) + + def test_moment(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + + r = stats.moment(x) + rm = stats.mstats.moment(xm) + assert_almost_equal(r, rm, 10) + + r = stats.moment(y) + rm = stats.mstats.moment(ym) + assert_almost_equal(r, rm, 10) + + def test_zscore(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + + # reference solution + zx = (x - x.mean()) / x.std() + zy = (y - y.mean()) / y.std() + + # validate stats + assert_allclose(stats.zscore(x), zx, rtol=1e-10) + assert_allclose(stats.zscore(y), zy, rtol=1e-10) + + # compare stats and mstats + assert_allclose(stats.zscore(x), stats.mstats.zscore(xm[0:len(x)]), + rtol=1e-10) + assert_allclose(stats.zscore(y), stats.mstats.zscore(ym[0:len(y)]), + rtol=1e-10) + + def test_kurtosis(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.kurtosis(x) + rm = stats.mstats.kurtosis(xm) + assert_almost_equal(r, rm, 10) + + r = stats.kurtosis(y) + rm = stats.mstats.kurtosis(ym) + assert_almost_equal(r, rm, 10) + + def test_sem(self): + # example from stats.sem doc + a = np.arange(20).reshape(5, 4) + am = np.ma.array(a) + r = stats.sem(a, ddof=1) + rm = stats.mstats.sem(am, ddof=1) + + assert_allclose(r, 2.82842712, atol=1e-5) + assert_allclose(rm, 2.82842712, atol=1e-5) + + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + assert_almost_equal(stats.mstats.sem(xm, axis=None, ddof=0), + stats.sem(x, axis=None, ddof=0), decimal=13) + assert_almost_equal(stats.mstats.sem(ym, axis=None, ddof=0), + stats.sem(y, axis=None, ddof=0), decimal=13) + assert_almost_equal(stats.mstats.sem(xm, axis=None, ddof=1), + stats.sem(x, axis=None, ddof=1), decimal=13) + assert_almost_equal(stats.mstats.sem(ym, axis=None, ddof=1), + stats.sem(y, axis=None, ddof=1), decimal=13) + + def test_describe(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.describe(x, ddof=1) + rm = stats.mstats.describe(xm, ddof=1) + for ii in range(6): + assert_almost_equal(np.asarray(r[ii]), + np.asarray(rm[ii]), + decimal=12) + + def test_describe_result_attributes(self): + actual = mstats.describe(np.arange(5)) + attributes = ('nobs', 'minmax', 'mean', 'variance', 'skewness', + 'kurtosis') + check_named_results(actual, attributes, ma=True) + + def test_rankdata(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.rankdata(x) + rm = stats.mstats.rankdata(x) + assert_allclose(r, rm) + + def test_tmean(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + assert_almost_equal(stats.tmean(x),stats.mstats.tmean(xm), 14) + assert_almost_equal(stats.tmean(y),stats.mstats.tmean(ym), 14) + + def test_tmax(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + assert_almost_equal(stats.tmax(x,2.), + stats.mstats.tmax(xm,2.), 10) + assert_almost_equal(stats.tmax(y,2.), + stats.mstats.tmax(ym,2.), 10) + + assert_almost_equal(stats.tmax(x, upperlimit=3.), + stats.mstats.tmax(xm, upperlimit=3.), 10) + assert_almost_equal(stats.tmax(y, upperlimit=3.), + stats.mstats.tmax(ym, upperlimit=3.), 10) + + def test_tmin(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + assert_equal(stats.tmin(x), stats.mstats.tmin(xm)) + assert_equal(stats.tmin(y), stats.mstats.tmin(ym)) + + assert_almost_equal(stats.tmin(x, lowerlimit=-1.), + stats.mstats.tmin(xm, lowerlimit=-1.), 10) + assert_almost_equal(stats.tmin(y, lowerlimit=-1.), + stats.mstats.tmin(ym, lowerlimit=-1.), 10) + + def test_zmap(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + z = stats.zmap(x, y) + zm = stats.mstats.zmap(xm, ym) + assert_allclose(z, zm[0:len(z)], atol=1e-10) + + def test_variation(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + assert_almost_equal(stats.variation(x), stats.mstats.variation(xm), + decimal=12) + assert_almost_equal(stats.variation(y), stats.mstats.variation(ym), + decimal=12) + + def test_tvar(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + assert_almost_equal(stats.tvar(x), stats.mstats.tvar(xm), + decimal=12) + assert_almost_equal(stats.tvar(y), stats.mstats.tvar(ym), + decimal=12) + + def test_trimboth(self): + a = np.arange(20) + b = stats.trimboth(a, 0.1) + bm = stats.mstats.trimboth(a, 0.1) + assert_allclose(np.sort(b), bm.data[~bm.mask]) + + def test_tsem(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + assert_almost_equal(stats.tsem(x), stats.mstats.tsem(xm), + decimal=14) + assert_almost_equal(stats.tsem(y), stats.mstats.tsem(ym), + decimal=14) + assert_almost_equal(stats.tsem(x, limits=(-2., 2.)), + stats.mstats.tsem(xm, limits=(-2., 2.)), + decimal=14) + + def test_skewtest(self): + # this test is for 1D data + for n in self.get_n(): + if n > 8: + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.skewtest(x) + rm = stats.mstats.skewtest(xm) + assert_allclose(r, rm) + + def test_skewtest_result_attributes(self): + x = np.array((-2, -1, 0, 1, 2, 3)*4)**2 + res = mstats.skewtest(x) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, ma=True) + + def test_skewtest_2D_notmasked(self): + # a normal ndarray is passed to the masked function + x = np.random.random((20, 2)) * 20. + r = stats.skewtest(x) + rm = stats.mstats.skewtest(x) + assert_allclose(np.asarray(r), np.asarray(rm)) + + def test_skewtest_2D_WithMask(self): + nx = 2 + for n in self.get_n(): + if n > 8: + x, y, xm, ym = self.generate_xy_sample2D(n, nx) + r = stats.skewtest(x) + rm = stats.mstats.skewtest(xm) + + assert_allclose(r[0][0], rm[0][0], rtol=1e-14) + assert_allclose(r[0][1], rm[0][1], rtol=1e-14) + + def test_normaltest(self): + with np.errstate(over='raise'), suppress_warnings() as sup: + sup.filter(UserWarning, "`kurtosistest` p-value may be inaccurate") + sup.filter(UserWarning, "kurtosistest only valid for n>=20") + for n in self.get_n(): + if n > 8: + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.normaltest(x) + rm = stats.mstats.normaltest(xm) + assert_allclose(np.asarray(r), np.asarray(rm)) + + def test_find_repeats(self): + x = np.asarray([1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4]).astype('float') + tmp = np.asarray([1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]).astype('float') + mask = (tmp == 5.) + xm = np.ma.array(tmp, mask=mask) + x_orig, xm_orig = x.copy(), xm.copy() + + unique, unique_counts = np.unique(x, return_counts=True) + r = unique[unique_counts > 1], unique_counts[unique_counts > 1] + rm = stats.mstats.find_repeats(xm) + + assert_equal(r, rm) + assert_equal(x, x_orig) + assert_equal(xm, xm_orig) + + # This crazy behavior is expected by count_tied_groups, but is not + # in the docstring... + _, counts = stats.mstats.find_repeats([]) + assert_equal(counts, np.array(0, dtype=np.intp)) + + def test_kendalltau(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.kendalltau(x, y) + rm = stats.mstats.kendalltau(xm, ym) + assert_almost_equal(r[0], rm[0], decimal=10) + assert_almost_equal(r[1], rm[1], decimal=7) + + def test_obrientransform(self): + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + r = stats.obrientransform(x) + rm = stats.mstats.obrientransform(xm) + assert_almost_equal(r.T, rm[0:len(x)]) + + def test_ks_1samp(self): + """Checks that mstats.ks_1samp and stats.ks_1samp agree on masked arrays.""" + for mode in ['auto', 'exact', 'asymp']: + with suppress_warnings(): + for alternative in ['less', 'greater', 'two-sided']: + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + res1 = stats.ks_1samp(x, stats.norm.cdf, + alternative=alternative, mode=mode) + res2 = stats.mstats.ks_1samp(xm, stats.norm.cdf, + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res2)) + res3 = stats.ks_1samp(xm, stats.norm.cdf, + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res3)) + + def test_kstest_1samp(self): + """ + Checks that 1-sample mstats.kstest and stats.kstest agree on masked arrays. + """ + for mode in ['auto', 'exact', 'asymp']: + with suppress_warnings(): + for alternative in ['less', 'greater', 'two-sided']: + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + res1 = stats.kstest(x, 'norm', + alternative=alternative, mode=mode) + res2 = stats.mstats.kstest(xm, 'norm', + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res2)) + res3 = stats.kstest(xm, 'norm', + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res3)) + + def test_ks_2samp(self): + """Checks that mstats.ks_2samp and stats.ks_2samp agree on masked arrays. + gh-8431""" + for mode in ['auto', 'exact', 'asymp']: + with suppress_warnings() as sup: + if mode in ['auto', 'exact']: + message = "ks_2samp: Exact calculation unsuccessful." + sup.filter(RuntimeWarning, message) + for alternative in ['less', 'greater', 'two-sided']: + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + res1 = stats.ks_2samp(x, y, + alternative=alternative, mode=mode) + res2 = stats.mstats.ks_2samp(xm, ym, + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res2)) + res3 = stats.ks_2samp(xm, y, + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res3)) + + def test_kstest_2samp(self): + """ + Checks that 2-sample mstats.kstest and stats.kstest agree on masked arrays. + """ + for mode in ['auto', 'exact', 'asymp']: + with suppress_warnings() as sup: + if mode in ['auto', 'exact']: + message = "ks_2samp: Exact calculation unsuccessful." + sup.filter(RuntimeWarning, message) + for alternative in ['less', 'greater', 'two-sided']: + for n in self.get_n(): + x, y, xm, ym = self.generate_xy_sample(n) + res1 = stats.kstest(x, y, + alternative=alternative, mode=mode) + res2 = stats.mstats.kstest(xm, ym, + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res2)) + res3 = stats.kstest(xm, y, + alternative=alternative, mode=mode) + assert_equal(np.asarray(res1), np.asarray(res3)) + + +class TestBrunnerMunzel: + # Data from (Lumley, 1996) + X = np.ma.masked_invalid([1, 2, 1, 1, 1, np.nan, 1, 1, + 1, 1, 1, 2, 4, 1, 1, np.nan]) + Y = np.ma.masked_invalid([3, 3, 4, 3, np.nan, 1, 2, 3, 1, 1, 5, 4]) + significant = 14 + + def test_brunnermunzel_one_sided(self): + # Results are compared with R's lawstat package. + u1, p1 = mstats.brunnermunzel(self.X, self.Y, alternative='less') + u2, p2 = mstats.brunnermunzel(self.Y, self.X, alternative='greater') + u3, p3 = mstats.brunnermunzel(self.X, self.Y, alternative='greater') + u4, p4 = mstats.brunnermunzel(self.Y, self.X, alternative='less') + + assert_almost_equal(p1, p2, decimal=self.significant) + assert_almost_equal(p3, p4, decimal=self.significant) + assert_(p1 != p3) + assert_almost_equal(u1, 3.1374674823029505, + decimal=self.significant) + assert_almost_equal(u2, -3.1374674823029505, + decimal=self.significant) + assert_almost_equal(u3, 3.1374674823029505, + decimal=self.significant) + assert_almost_equal(u4, -3.1374674823029505, + decimal=self.significant) + assert_almost_equal(p1, 0.0028931043330757342, + decimal=self.significant) + assert_almost_equal(p3, 0.99710689566692423, + decimal=self.significant) + + def test_brunnermunzel_two_sided(self): + # Results are compared with R's lawstat package. + u1, p1 = mstats.brunnermunzel(self.X, self.Y, alternative='two-sided') + u2, p2 = mstats.brunnermunzel(self.Y, self.X, alternative='two-sided') + + assert_almost_equal(p1, p2, decimal=self.significant) + assert_almost_equal(u1, 3.1374674823029505, + decimal=self.significant) + assert_almost_equal(u2, -3.1374674823029505, + decimal=self.significant) + assert_almost_equal(p1, 0.0057862086661515377, + decimal=self.significant) + + def test_brunnermunzel_default(self): + # The default value for alternative is two-sided + u1, p1 = mstats.brunnermunzel(self.X, self.Y) + u2, p2 = mstats.brunnermunzel(self.Y, self.X) + + assert_almost_equal(p1, p2, decimal=self.significant) + assert_almost_equal(u1, 3.1374674823029505, + decimal=self.significant) + assert_almost_equal(u2, -3.1374674823029505, + decimal=self.significant) + assert_almost_equal(p1, 0.0057862086661515377, + decimal=self.significant) + + def test_brunnermunzel_alternative_error(self): + alternative = "error" + distribution = "t" + assert_(alternative not in ["two-sided", "greater", "less"]) + assert_raises(ValueError, + mstats.brunnermunzel, + self.X, + self.Y, + alternative, + distribution) + + def test_brunnermunzel_distribution_norm(self): + u1, p1 = mstats.brunnermunzel(self.X, self.Y, distribution="normal") + u2, p2 = mstats.brunnermunzel(self.Y, self.X, distribution="normal") + assert_almost_equal(p1, p2, decimal=self.significant) + assert_almost_equal(u1, 3.1374674823029505, + decimal=self.significant) + assert_almost_equal(u2, -3.1374674823029505, + decimal=self.significant) + assert_almost_equal(p1, 0.0017041417600383024, + decimal=self.significant) + + def test_brunnermunzel_distribution_error(self): + alternative = "two-sided" + distribution = "error" + assert_(alternative not in ["t", "normal"]) + assert_raises(ValueError, + mstats.brunnermunzel, + self.X, + self.Y, + alternative, + distribution) + + def test_brunnermunzel_empty_imput(self): + u1, p1 = mstats.brunnermunzel(self.X, []) + u2, p2 = mstats.brunnermunzel([], self.Y) + u3, p3 = mstats.brunnermunzel([], []) + + assert_(np.isnan(u1)) + assert_(np.isnan(p1)) + assert_(np.isnan(u2)) + assert_(np.isnan(p2)) + assert_(np.isnan(u3)) + assert_(np.isnan(p3)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_extras.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_extras.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9fd0d80a6e05652c5151f5dfece2c5979dbfe5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_extras.py @@ -0,0 +1,172 @@ +import numpy as np +import numpy.ma as ma +import scipy.stats.mstats as ms + +from numpy.testing import (assert_equal, assert_almost_equal, assert_, + assert_allclose) + + +def test_compare_medians_ms(): + x = np.arange(7) + y = x + 10 + assert_almost_equal(ms.compare_medians_ms(x, y), 0) + + y2 = np.linspace(0, 1, num=10) + assert_almost_equal(ms.compare_medians_ms(x, y2), 0.017116406778) + + +def test_hdmedian(): + # 1-D array + x = ma.arange(11) + assert_allclose(ms.hdmedian(x), 5, rtol=1e-14) + x.mask = ma.make_mask(x) + x.mask[:7] = False + assert_allclose(ms.hdmedian(x), 3, rtol=1e-14) + + # Check that `var` keyword returns a value. TODO: check whether returned + # value is actually correct. + assert_(ms.hdmedian(x, var=True).size == 2) + + # 2-D array + x2 = ma.arange(22).reshape((11, 2)) + assert_allclose(ms.hdmedian(x2, axis=0), [10, 11]) + x2.mask = ma.make_mask(x2) + x2.mask[:7, :] = False + assert_allclose(ms.hdmedian(x2, axis=0), [6, 7]) + + +def test_rsh(): + np.random.seed(132345) + x = np.random.randn(100) + res = ms.rsh(x) + # Just a sanity check that the code runs and output shape is correct. + # TODO: check that implementation is correct. + assert_(res.shape == x.shape) + + # Check points keyword + res = ms.rsh(x, points=[0, 1.]) + assert_(res.size == 2) + + +def test_mjci(): + # Tests the Marits-Jarrett estimator + data = ma.array([77, 87, 88,114,151,210,219,246,253,262, + 296,299,306,376,428,515,666,1310,2611]) + assert_almost_equal(ms.mjci(data),[55.76819,45.84028,198.87875],5) + + +def test_trimmed_mean_ci(): + # Tests the confidence intervals of the trimmed mean. + data = ma.array([545,555,558,572,575,576,578,580, + 594,605,635,651,653,661,666]) + assert_almost_equal(ms.trimmed_mean(data,0.2), 596.2, 1) + assert_equal(np.round(ms.trimmed_mean_ci(data,(0.2,0.2)),1), + [561.8, 630.6]) + + +def test_idealfourths(): + # Tests ideal-fourths + test = np.arange(100) + assert_almost_equal(np.asarray(ms.idealfourths(test)), + [24.416667,74.583333],6) + test_2D = test.repeat(3).reshape(-1,3) + assert_almost_equal(ms.idealfourths(test_2D, axis=0), + [[24.416667,24.416667,24.416667], + [74.583333,74.583333,74.583333]],6) + assert_almost_equal(ms.idealfourths(test_2D, axis=1), + test.repeat(2).reshape(-1,2)) + test = [0, 0] + _result = ms.idealfourths(test) + assert_(np.isnan(_result).all()) + + +class TestQuantiles: + data = [0.706560797,0.727229578,0.990399276,0.927065621,0.158953014, + 0.887764025,0.239407086,0.349638551,0.972791145,0.149789972, + 0.936947700,0.132359948,0.046041972,0.641675031,0.945530547, + 0.224218684,0.771450991,0.820257774,0.336458052,0.589113496, + 0.509736129,0.696838829,0.491323573,0.622767425,0.775189248, + 0.641461450,0.118455200,0.773029450,0.319280007,0.752229111, + 0.047841438,0.466295911,0.583850781,0.840581845,0.550086491, + 0.466470062,0.504765074,0.226855960,0.362641207,0.891620942, + 0.127898691,0.490094097,0.044882048,0.041441695,0.317976349, + 0.504135618,0.567353033,0.434617473,0.636243375,0.231803616, + 0.230154113,0.160011327,0.819464108,0.854706985,0.438809221, + 0.487427267,0.786907310,0.408367937,0.405534192,0.250444460, + 0.995309248,0.144389588,0.739947527,0.953543606,0.680051621, + 0.388382017,0.863530727,0.006514031,0.118007779,0.924024803, + 0.384236354,0.893687694,0.626534881,0.473051932,0.750134705, + 0.241843555,0.432947602,0.689538104,0.136934797,0.150206859, + 0.474335206,0.907775349,0.525869295,0.189184225,0.854284286, + 0.831089744,0.251637345,0.587038213,0.254475554,0.237781276, + 0.827928620,0.480283781,0.594514455,0.213641488,0.024194386, + 0.536668589,0.699497811,0.892804071,0.093835427,0.731107772] + + def test_hdquantiles(self): + data = self.data + assert_almost_equal(ms.hdquantiles(data,[0., 1.]), + [0.006514031, 0.995309248]) + hdq = ms.hdquantiles(data,[0.25, 0.5, 0.75]) + assert_almost_equal(hdq, [0.253210762, 0.512847491, 0.762232442,]) + + data = np.array(data).reshape(10,10) + hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0) + assert_almost_equal(hdq[:,0], ms.hdquantiles(data[:,0],[0.25,0.5,0.75])) + assert_almost_equal(hdq[:,-1], ms.hdquantiles(data[:,-1],[0.25,0.5,0.75])) + hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0,var=True) + assert_almost_equal(hdq[...,0], + ms.hdquantiles(data[:,0],[0.25,0.5,0.75],var=True)) + assert_almost_equal(hdq[...,-1], + ms.hdquantiles(data[:,-1],[0.25,0.5,0.75], var=True)) + + def test_hdquantiles_sd(self): + # Standard deviation is a jackknife estimator, so we can check if + # the efficient version (hdquantiles_sd) matches a rudimentary, + # but clear version here. + + hd_std_errs = ms.hdquantiles_sd(self.data) + + # jacknnife standard error, Introduction to the Bootstrap Eq. 11.5 + n = len(self.data) + jdata = np.broadcast_to(self.data, (n, n)) + jselector = np.logical_not(np.eye(n)) # leave out one sample each row + jdata = jdata[jselector].reshape(n, n-1) + jdist = ms.hdquantiles(jdata, axis=1) + jdist_mean = np.mean(jdist, axis=0) + jstd = ((n-1)/n * np.sum((jdist - jdist_mean)**2, axis=0))**.5 + + assert_almost_equal(hd_std_errs, jstd) + # Test actual values for good measure + assert_almost_equal(hd_std_errs, [0.0379258, 0.0380656, 0.0380013]) + + two_data_points = ms.hdquantiles_sd([1, 2]) + assert_almost_equal(two_data_points, [0.5, 0.5, 0.5]) + + def test_mquantiles_cimj(self): + # Only test that code runs, implementation not checked for correctness + ci_lower, ci_upper = ms.mquantiles_cimj(self.data) + assert_(ci_lower.size == ci_upper.size == 3) + + +def test_median_cihs(): + # Basic test against R library EnvStats function `eqnpar`, e.g. + # library(EnvStats) + # options(digits=8) + # x = c(0.88612955, 0.35242375, 0.66240904, 0.94617974, 0.10929913, + # 0.76699506, 0.88550655, 0.62763754, 0.76818588, 0.68506508, + # 0.88043148, 0.03911248, 0.93805564, 0.95326961, 0.25291112, + # 0.16128487, 0.49784577, 0.24588924, 0.6597, 0.92239679) + # eqnpar(x, p=0.5, + # ci.method = "interpolate", approx.conf.level = 0.95, ci = TRUE) + rng = np.random.default_rng(8824288259505800535) + x = rng.random(size=20) + assert_allclose(ms.median_cihs(x), (0.38663198, 0.88431272)) + + # SciPy's 90% CI upper limit doesn't match that of EnvStats eqnpar. SciPy + # doesn't look wrong, and it agrees with a different reference, + # `median_confint_hs` from `hoehleatsu/quantileCI`. + # In (e.g.) Colab with R runtime: + # devtools::install_github("hoehleatsu/quantileCI") + # library(quantileCI) + # median_confint_hs(x=x, conf.level=0.90, interpolate=TRUE) + assert_allclose(ms.median_cihs(x, 0.1), (0.48319773366, 0.88094268050)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multicomp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multicomp.py new file mode 100644 index 0000000000000000000000000000000000000000..2860b142c38a339f96c50af92bd452c6de95e84d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multicomp.py @@ -0,0 +1,405 @@ +import copy + +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from scipy import stats +from scipy.stats._multicomp import _pvalue_dunnett, DunnettResult + + +class TestDunnett: + # For the following tests, p-values were computed using Matlab, e.g. + # sample = [18. 15. 18. 16. 17. 15. 14. 14. 14. 15. 15.... + # 14. 15. 14. 22. 18. 21. 21. 10. 10. 11. 9.... + # 25. 26. 17.5 16. 15.5 14.5 22. 22. 24. 22.5 29.... + # 24.5 20. 18. 18.5 17.5 26.5 13. 16.5 13. 13. 13.... + # 28. 27. 34. 31. 29. 27. 24. 23. 38. 36. 25.... + # 38. 26. 22. 36. 27. 27. 32. 28. 31.... + # 24. 27. 33. 32. 28. 19. 37. 31. 36. 36.... + # 34. 38. 32. 38. 32.... + # 26. 24. 26. 25. 29. 29.5 16.5 36. 44.... + # 25. 27. 19.... + # 25. 20.... + # 28.]; + # j = [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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... + # 0 0 0 0... + # 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1... + # 2 2 2 2 2 2 2 2 2... + # 3 3 3... + # 4 4... + # 5]; + # [~, ~, stats] = anova1(sample, j, "off"); + # [results, ~, ~, gnames] = multcompare(stats, ... + # "CriticalValueType", "dunnett", ... + # "Approximate", false); + # tbl = array2table(results, "VariableNames", ... + # ["Group", "Control Group", "Lower Limit", ... + # "Difference", "Upper Limit", "P-value"]); + # tbl.("Group") = gnames(tbl.("Group")); + # tbl.("Control Group") = gnames(tbl.("Control Group")) + + # Matlab doesn't report the statistic, so the statistics were + # computed using R multcomp `glht`, e.g.: + # library(multcomp) + # options(digits=16) + # control < - c(18.0, 15.0, 18.0, 16.0, 17.0, 15.0, 14.0, 14.0, 14.0, + # 15.0, 15.0, 14.0, 15.0, 14.0, 22.0, 18.0, 21.0, 21.0, + # 10.0, 10.0, 11.0, 9.0, 25.0, 26.0, 17.5, 16.0, 15.5, + # 14.5, 22.0, 22.0, 24.0, 22.5, 29.0, 24.5, 20.0, 18.0, + # 18.5, 17.5, 26.5, 13.0, 16.5, 13.0, 13.0, 13.0, 28.0, + # 27.0, 34.0, 31.0, 29.0, 27.0, 24.0, 23.0, 38.0, 36.0, + # 25.0, 38.0, 26.0, 22.0, 36.0, 27.0, 27.0, 32.0, 28.0, + # 31.0) + # t < - c(24.0, 27.0, 33.0, 32.0, 28.0, 19.0, 37.0, 31.0, 36.0, 36.0, + # 34.0, 38.0, 32.0, 38.0, 32.0) + # w < - c(26.0, 24.0, 26.0, 25.0, 29.0, 29.5, 16.5, 36.0, 44.0) + # x < - c(25.0, 27.0, 19.0) + # y < - c(25.0, 20.0) + # z < - c(28.0) + # + # groups = factor(rep(c("control", "t", "w", "x", "y", "z"), + # times=c(length(control), length(t), length(w), + # length(x), length(y), length(z)))) + # df < - data.frame(response=c(control, t, w, x, y, z), + # group=groups) + # model < - aov(response + # ~group, data = df) + # test < - glht(model=model, + # linfct=mcp(group="Dunnett"), + # alternative="g") + # summary(test) + # confint(test) + # p-values agreed with those produced by Matlab to at least atol=1e-3 + + # From Matlab's documentation on multcompare + samples_1 = [ + [ + 24.0, 27.0, 33.0, 32.0, 28.0, 19.0, 37.0, 31.0, 36.0, 36.0, + 34.0, 38.0, 32.0, 38.0, 32.0 + ], + [26.0, 24.0, 26.0, 25.0, 29.0, 29.5, 16.5, 36.0, 44.0], + [25.0, 27.0, 19.0], + [25.0, 20.0], + [28.0] + ] + control_1 = [ + 18.0, 15.0, 18.0, 16.0, 17.0, 15.0, 14.0, 14.0, 14.0, 15.0, 15.0, + 14.0, 15.0, 14.0, 22.0, 18.0, 21.0, 21.0, 10.0, 10.0, 11.0, 9.0, + 25.0, 26.0, 17.5, 16.0, 15.5, 14.5, 22.0, 22.0, 24.0, 22.5, 29.0, + 24.5, 20.0, 18.0, 18.5, 17.5, 26.5, 13.0, 16.5, 13.0, 13.0, 13.0, + 28.0, 27.0, 34.0, 31.0, 29.0, 27.0, 24.0, 23.0, 38.0, 36.0, 25.0, + 38.0, 26.0, 22.0, 36.0, 27.0, 27.0, 32.0, 28.0, 31.0 + ] + pvalue_1 = [4.727e-06, 0.022346, 0.97912, 0.99953, 0.86579] # Matlab + # Statistic, alternative p-values, and CIs computed with R multcomp `glht` + p_1_twosided = [1e-4, 0.02237, 0.97913, 0.99953, 0.86583] + p_1_greater = [1e-4, 0.011217, 0.768500, 0.896991, 0.577211] + p_1_less = [1, 1, 0.99660, 0.98398, .99953] + statistic_1 = [5.27356, 2.91270, 0.60831, 0.27002, 0.96637] + ci_1_twosided = [[5.3633917835622, 0.7296142201217, -8.3879817106607, + -11.9090753452911, -11.7655021543469], + [15.9709832164378, 13.8936496687672, 13.4556900439941, + 14.6434503452911, 25.4998771543469]] + ci_1_greater = [5.9036402398526, 1.4000632918725, -7.2754756323636, + -10.5567456382391, -9.8675629499576] + ci_1_less = [15.4306165948619, 13.2230539537359, 12.3429406339544, + 13.2908248513211, 23.6015228251660] + pvalues_1 = dict(twosided=p_1_twosided, less=p_1_less, greater=p_1_greater) + cis_1 = dict(twosided=ci_1_twosided, less=ci_1_less, greater=ci_1_greater) + case_1 = dict(samples=samples_1, control=control_1, statistic=statistic_1, + pvalues=pvalues_1, cis=cis_1) + + # From Dunnett1955 comparing with R's DescTools: DunnettTest + samples_2 = [[9.76, 8.80, 7.68, 9.36], [12.80, 9.68, 12.16, 9.20, 10.55]] + control_2 = [7.40, 8.50, 7.20, 8.24, 9.84, 8.32] + pvalue_2 = [0.6201, 0.0058] + # Statistic, alternative p-values, and CIs computed with R multcomp `glht` + p_2_twosided = [0.6201020, 0.0058254] + p_2_greater = [0.3249776, 0.0029139] + p_2_less = [0.91676, 0.99984] + statistic_2 = [0.85703, 3.69375] + ci_2_twosided = [[-1.2564116462124, 0.8396273539789], + [2.5564116462124, 4.4163726460211]] + ci_2_greater = [-0.9588591188156, 1.1187563667543] + ci_2_less = [2.2588591188156, 4.1372436332457] + pvalues_2 = dict(twosided=p_2_twosided, less=p_2_less, greater=p_2_greater) + cis_2 = dict(twosided=ci_2_twosided, less=ci_2_less, greater=ci_2_greater) + case_2 = dict(samples=samples_2, control=control_2, statistic=statistic_2, + pvalues=pvalues_2, cis=cis_2) + + samples_3 = [[55, 64, 64], [55, 49, 52], [50, 44, 41]] + control_3 = [55, 47, 48] + pvalue_3 = [0.0364, 0.8966, 0.4091] + # Statistic, alternative p-values, and CIs computed with R multcomp `glht` + p_3_twosided = [0.036407, 0.896539, 0.409295] + p_3_greater = [0.018277, 0.521109, 0.981892] + p_3_less = [0.99944, 0.90054, 0.20974] + statistic_3 = [3.09073, 0.56195, -1.40488] + ci_3_twosided = [[0.7529028025053, -8.2470971974947, -15.2470971974947], + [21.2470971974947, 12.2470971974947, 5.2470971974947]] + ci_3_greater = [2.4023682323149, -6.5976317676851, -13.5976317676851] + ci_3_less = [19.5984402363662, 10.5984402363662, 3.5984402363662] + pvalues_3 = dict(twosided=p_3_twosided, less=p_3_less, greater=p_3_greater) + cis_3 = dict(twosided=ci_3_twosided, less=ci_3_less, greater=ci_3_greater) + case_3 = dict(samples=samples_3, control=control_3, statistic=statistic_3, + pvalues=pvalues_3, cis=cis_3) + + # From Thomson and Short, + # Mucociliary function in health, chronic obstructive airway disease, + # and asbestosis, Journal of Applied Physiology, 1969. Table 1 + # Comparing with R's DescTools: DunnettTest + samples_4 = [[3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]] + control_4 = [2.9, 3.0, 2.5, 2.6, 3.2] + pvalue_4 = [0.5832, 0.9982] + # Statistic, alternative p-values, and CIs computed with R multcomp `glht` + p_4_twosided = [0.58317, 0.99819] + p_4_greater = [0.30225, 0.69115] + p_4_less = [0.91929, 0.65212] + statistic_4 = [0.90875, -0.05007] + ci_4_twosided = [[-0.6898153448579, -1.0333456251632], + [1.4598153448579, 0.9933456251632]] + ci_4_greater = [-0.5186459268412, -0.8719655502147 ] + ci_4_less = [1.2886459268412, 0.8319655502147] + pvalues_4 = dict(twosided=p_4_twosided, less=p_4_less, greater=p_4_greater) + cis_4 = dict(twosided=ci_4_twosided, less=ci_4_less, greater=ci_4_greater) + case_4 = dict(samples=samples_4, control=control_4, statistic=statistic_4, + pvalues=pvalues_4, cis=cis_4) + + @pytest.mark.parametrize( + 'rho, n_groups, df, statistic, pvalue, alternative', + [ + # From Dunnett1955 + # Tables 1a and 1b pages 1117-1118 + (0.5, 1, 10, 1.81, 0.05, "greater"), # different than two-sided + (0.5, 3, 10, 2.34, 0.05, "greater"), + (0.5, 2, 30, 1.99, 0.05, "greater"), + (0.5, 5, 30, 2.33, 0.05, "greater"), + (0.5, 4, 12, 3.32, 0.01, "greater"), + (0.5, 7, 12, 3.56, 0.01, "greater"), + (0.5, 2, 60, 2.64, 0.01, "greater"), + (0.5, 4, 60, 2.87, 0.01, "greater"), + (0.5, 4, 60, [2.87, 2.21], [0.01, 0.05], "greater"), + # Tables 2a and 2b pages 1119-1120 + (0.5, 1, 10, 2.23, 0.05, "two-sided"), # two-sided + (0.5, 3, 10, 2.81, 0.05, "two-sided"), + (0.5, 2, 30, 2.32, 0.05, "two-sided"), + (0.5, 3, 20, 2.57, 0.05, "two-sided"), + (0.5, 4, 12, 3.76, 0.01, "two-sided"), + (0.5, 7, 12, 4.08, 0.01, "two-sided"), + (0.5, 2, 60, 2.90, 0.01, "two-sided"), + (0.5, 4, 60, 3.14, 0.01, "two-sided"), + (0.5, 4, 60, [3.14, 2.55], [0.01, 0.05], "two-sided"), + ], + ) + def test_critical_values( + self, rho, n_groups, df, statistic, pvalue, alternative + ): + rng = np.random.default_rng(165250594791731684851746311027739134893) + rho = np.full((n_groups, n_groups), rho) + np.fill_diagonal(rho, 1) + + statistic = np.array(statistic) + res = _pvalue_dunnett( + rho=rho, df=df, statistic=statistic, + alternative=alternative, + rng=rng + ) + assert_allclose(res, pvalue, atol=5e-3) + + @pytest.mark.parametrize( + 'samples, control, pvalue, statistic', + [ + (samples_1, control_1, pvalue_1, statistic_1), + (samples_2, control_2, pvalue_2, statistic_2), + (samples_3, control_3, pvalue_3, statistic_3), + (samples_4, control_4, pvalue_4, statistic_4), + ] + ) + def test_basic(self, samples, control, pvalue, statistic): + rng = np.random.default_rng(11681140010308601919115036826969764808) + + res = stats.dunnett(*samples, control=control, rng=rng) + + assert isinstance(res, DunnettResult) + assert_allclose(res.statistic, statistic, rtol=5e-5) + assert_allclose(res.pvalue, pvalue, rtol=1e-2, atol=1e-4) + + @pytest.mark.parametrize( + 'alternative', + ['two-sided', 'less', 'greater'] + ) + def test_ttest_ind(self, alternative): + # check that `dunnett` agrees with `ttest_ind` + # when there are only two groups + rng = np.random.default_rng(114184017807316971636137493526995620351) + + for _ in range(10): + sample = rng.integers(-100, 100, size=(10,)) + control = rng.integers(-100, 100, size=(10,)) + + # preserve use of old random_state during SPEC 7 transition + res = stats.dunnett( + sample, control=control, + alternative=alternative, random_state=rng + ) + ref = stats.ttest_ind( + sample, control, + alternative=alternative + ) + + assert_allclose(res.statistic, ref.statistic, rtol=1e-3, atol=1e-5) + assert_allclose(res.pvalue, ref.pvalue, rtol=1e-3, atol=1e-5) + + @pytest.mark.parametrize( + 'alternative, pvalue', + [ + ('less', [0, 1]), + ('greater', [1, 0]), + ('two-sided', [0, 0]), + ] + ) + def test_alternatives(self, alternative, pvalue): + rng = np.random.default_rng(114184017807316971636137493526995620351) + + # width of 20 and min diff between samples/control is 60 + # and maximal diff would be 100 + sample_less = rng.integers(0, 20, size=(10,)) + control = rng.integers(80, 100, size=(10,)) + sample_greater = rng.integers(160, 180, size=(10,)) + + res = stats.dunnett( + sample_less, sample_greater, control=control, + alternative=alternative, rng=rng + ) + assert_allclose(res.pvalue, pvalue, atol=1e-7) + + ci = res.confidence_interval() + # two-sided is comparable for high/low + if alternative == 'less': + assert np.isneginf(ci.low).all() + assert -100 < ci.high[0] < -60 + assert 60 < ci.high[1] < 100 + elif alternative == 'greater': + assert -100 < ci.low[0] < -60 + assert 60 < ci.low[1] < 100 + assert np.isposinf(ci.high).all() + elif alternative == 'two-sided': + assert -100 < ci.low[0] < -60 + assert 60 < ci.low[1] < 100 + assert -100 < ci.high[0] < -60 + assert 60 < ci.high[1] < 100 + + @pytest.mark.parametrize("case", [case_1, case_2, case_3, case_4]) + @pytest.mark.parametrize("alternative", ['less', 'greater', 'two-sided']) + def test_against_R_multicomp_glht(self, case, alternative): + rng = np.random.default_rng(189117774084579816190295271136455278291) + samples = case['samples'] + control = case['control'] + alternatives = {'less': 'less', 'greater': 'greater', + 'two-sided': 'twosided'} + p_ref = case['pvalues'][alternative.replace('-', '')] + + res = stats.dunnett(*samples, control=control, alternative=alternative, + rng=rng) + # atol can't be tighter because R reports some pvalues as "< 1e-4" + assert_allclose(res.pvalue, p_ref, rtol=5e-3, atol=1e-4) + + ci_ref = case['cis'][alternatives[alternative]] + if alternative == "greater": + ci_ref = [ci_ref, np.inf] + elif alternative == "less": + ci_ref = [-np.inf, ci_ref] + assert res._ci is None + assert res._ci_cl is None + ci = res.confidence_interval(confidence_level=0.95) + assert_allclose(ci.low, ci_ref[0], rtol=5e-3, atol=1e-5) + assert_allclose(ci.high, ci_ref[1], rtol=5e-3, atol=1e-5) + + # re-run to use the cached value "is" to check id as same object + assert res._ci is ci + assert res._ci_cl == 0.95 + ci_ = res.confidence_interval(confidence_level=0.95) + assert ci_ is ci + + @pytest.mark.parametrize('alternative', ["two-sided", "less", "greater"]) + def test_str(self, alternative): + rng = np.random.default_rng(189117774084579816190295271136455278291) + + res = stats.dunnett( + *self.samples_3, control=self.control_3, alternative=alternative, + rng=rng + ) + + # check some str output + res_str = str(res) + assert '(Sample 2 - Control)' in res_str + assert '95.0%' in res_str + + if alternative == 'less': + assert '-inf' in res_str + assert '19.' in res_str + elif alternative == 'greater': + assert 'inf' in res_str + assert '-13.' in res_str + else: + assert 'inf' not in res_str + assert '21.' in res_str + + def test_warnings(self): + rng = np.random.default_rng(189117774084579816190295271136455278291) + + res = stats.dunnett( + *self.samples_3, control=self.control_3, rng=rng + ) + msg = r"Computation of the confidence interval did not converge" + with pytest.warns(UserWarning, match=msg): + res._allowance(tol=1e-5) + + def test_raises(self): + samples, control = self.samples_3, self.control_3 + + # alternative + with pytest.raises(ValueError, match="alternative must be"): + stats.dunnett(*samples, control=control, alternative='bob') + + # 2D for a sample + samples_ = copy.deepcopy(samples) + samples_[0] = [samples_[0]] + with pytest.raises(ValueError, match="must be 1D arrays"): + stats.dunnett(*samples_, control=control) + + # 2D for control + control_ = copy.deepcopy(control) + control_ = [control_] + with pytest.raises(ValueError, match="must be 1D arrays"): + stats.dunnett(*samples, control=control_) + + # No obs in a sample + samples_ = copy.deepcopy(samples) + samples_[1] = [] + with pytest.raises(ValueError, match="at least 1 observation"): + stats.dunnett(*samples_, control=control) + + # No obs in control + control_ = [] + with pytest.raises(ValueError, match="at least 1 observation"): + stats.dunnett(*samples, control=control_) + + res = stats.dunnett(*samples, control=control) + with pytest.raises(ValueError, match="Confidence level must"): + res.confidence_interval(confidence_level=3) + + @pytest.mark.filterwarnings("ignore:Computation of the confidence") + @pytest.mark.parametrize('n_samples', [1, 2, 3]) + def test_shapes(self, n_samples): + rng = np.random.default_rng(689448934110805334) + samples = rng.normal(size=(n_samples, 10)) + control = rng.normal(size=10) + res = stats.dunnett(*samples, control=control, rng=rng) + assert res.statistic.shape == (n_samples,) + assert res.pvalue.shape == (n_samples,) + ci = res.confidence_interval() + assert ci.low.shape == (n_samples,) + assert ci.high.shape == (n_samples,) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multivariate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multivariate.py new file mode 100644 index 0000000000000000000000000000000000000000..d53a7925b4d6794f7f538647f0288810c163a8a0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multivariate.py @@ -0,0 +1,4030 @@ +""" +Test functions for multivariate normal distributions. + +""" +import pickle + +from numpy.testing import (assert_allclose, assert_almost_equal, + assert_array_almost_equal, assert_equal, + assert_array_less, assert_) +import pytest +from pytest import raises as assert_raises + +from .test_continuous_basic import check_distribution_rvs + +import numpy as np + +import scipy.linalg + +from scipy.stats._multivariate import (_PSD, + _lnB, + multivariate_normal_frozen) +from scipy.stats import (multivariate_normal, multivariate_hypergeom, + matrix_normal, special_ortho_group, ortho_group, + random_correlation, unitary_group, dirichlet, + beta, wishart, multinomial, invwishart, chi2, + invgamma, norm, uniform, ks_2samp, kstest, binom, + hypergeom, multivariate_t, cauchy, normaltest, + random_table, uniform_direction, vonmises_fisher, + dirichlet_multinomial, vonmises) + +from scipy.stats import _covariance, Covariance +from scipy import stats + +from scipy.integrate import tanhsinh +from scipy.integrate import romb, qmc_quad, dblquad, tplquad +from scipy.special import multigammaln + +from .common_tests import check_random_state_property +from .data._mvt import _qsimvtv + +from unittest.mock import patch + + +def assert_close(res, ref, *args, **kwargs): + res, ref = np.asarray(res), np.asarray(ref) + assert_allclose(res, ref, *args, **kwargs) + assert_equal(res.shape, ref.shape) + + +class TestCovariance: + + def test_input_validation(self): + + message = "The input `precision` must be a square, two-dimensional..." + with pytest.raises(ValueError, match=message): + _covariance.CovViaPrecision(np.ones(2)) + + message = "`precision.shape` must equal `covariance.shape`." + with pytest.raises(ValueError, match=message): + _covariance.CovViaPrecision(np.eye(3), covariance=np.eye(2)) + + message = "The input `diagonal` must be a one-dimensional array..." + with pytest.raises(ValueError, match=message): + _covariance.CovViaDiagonal("alpaca") + + message = "The input `cholesky` must be a square, two-dimensional..." + with pytest.raises(ValueError, match=message): + _covariance.CovViaCholesky(np.ones(2)) + + message = "The input `eigenvalues` must be a one-dimensional..." + with pytest.raises(ValueError, match=message): + _covariance.CovViaEigendecomposition(("alpaca", np.eye(2))) + + message = "The input `eigenvectors` must be a square..." + with pytest.raises(ValueError, match=message): + _covariance.CovViaEigendecomposition((np.ones(2), "alpaca")) + + message = "The shapes of `eigenvalues` and `eigenvectors` must be..." + with pytest.raises(ValueError, match=message): + _covariance.CovViaEigendecomposition(([1, 2, 3], np.eye(2))) + + _covariance_preprocessing = {"Diagonal": np.diag, + "Precision": np.linalg.inv, + "Cholesky": np.linalg.cholesky, + "Eigendecomposition": np.linalg.eigh, + "PSD": lambda x: + _PSD(x, allow_singular=True)} + _all_covariance_types = np.array(list(_covariance_preprocessing)) + _matrices = {"diagonal full rank": np.diag([1, 2, 3]), + "general full rank": [[5, 1, 3], [1, 6, 4], [3, 4, 7]], + "diagonal singular": np.diag([1, 0, 3]), + "general singular": [[5, -1, 0], [-1, 5, 0], [0, 0, 0]]} + _cov_types = {"diagonal full rank": _all_covariance_types, + "general full rank": _all_covariance_types[1:], + "diagonal singular": _all_covariance_types[[0, -2, -1]], + "general singular": _all_covariance_types[-2:]} + + @pytest.mark.parametrize("cov_type_name", _all_covariance_types[:-1]) + def test_factories(self, cov_type_name): + A = np.diag([1, 2, 3]) + x = [-4, 2, 5] + + cov_type = getattr(_covariance, f"CovVia{cov_type_name}") + preprocessing = self._covariance_preprocessing[cov_type_name] + factory = getattr(Covariance, f"from_{cov_type_name.lower()}") + + res = factory(preprocessing(A)) + ref = cov_type(preprocessing(A)) + assert type(res) is type(ref) + assert_allclose(res.whiten(x), ref.whiten(x)) + + @pytest.mark.parametrize("matrix_type", list(_matrices)) + @pytest.mark.parametrize("cov_type_name", _all_covariance_types) + def test_covariance(self, matrix_type, cov_type_name): + message = (f"CovVia{cov_type_name} does not support {matrix_type} " + "matrices") + if cov_type_name not in self._cov_types[matrix_type]: + pytest.skip(message) + + A = self._matrices[matrix_type] + cov_type = getattr(_covariance, f"CovVia{cov_type_name}") + preprocessing = self._covariance_preprocessing[cov_type_name] + + psd = _PSD(A, allow_singular=True) + + # test properties + cov_object = cov_type(preprocessing(A)) + assert_close(cov_object.log_pdet, psd.log_pdet) + assert_equal(cov_object.rank, psd.rank) + assert_equal(cov_object.shape, np.asarray(A).shape) + assert_close(cov_object.covariance, np.asarray(A)) + + # test whitening/coloring 1D x + rng = np.random.default_rng(5292808890472453840) + x = rng.random(size=3) + res = cov_object.whiten(x) + ref = x @ psd.U + # res != ref in general; but res @ res == ref @ ref + assert_close(res @ res, ref @ ref) + if hasattr(cov_object, "_colorize") and "singular" not in matrix_type: + # CovViaPSD does not have _colorize + assert_close(cov_object.colorize(res), x) + + # test whitening/coloring 3D x + x = rng.random(size=(2, 4, 3)) + res = cov_object.whiten(x) + ref = x @ psd.U + assert_close((res**2).sum(axis=-1), (ref**2).sum(axis=-1)) + if hasattr(cov_object, "_colorize") and "singular" not in matrix_type: + assert_close(cov_object.colorize(res), x) + + # gh-19197 reported that multivariate normal `rvs` produced incorrect + # results when a singular Covariance object was produce using + # `from_eigenvalues`. This was due to an issue in `colorize` with + # singular covariance matrices. Check this edge case, which is skipped + # in the previous tests. + if hasattr(cov_object, "_colorize"): + res = cov_object.colorize(np.eye(len(A))) + assert_close(res.T @ res, A) + + @pytest.mark.parametrize("size", [None, tuple(), 1, (2, 4, 3)]) + @pytest.mark.parametrize("matrix_type", list(_matrices)) + @pytest.mark.parametrize("cov_type_name", _all_covariance_types) + def test_mvn_with_covariance(self, size, matrix_type, cov_type_name): + message = (f"CovVia{cov_type_name} does not support {matrix_type} " + "matrices") + if cov_type_name not in self._cov_types[matrix_type]: + pytest.skip(message) + + A = self._matrices[matrix_type] + cov_type = getattr(_covariance, f"CovVia{cov_type_name}") + preprocessing = self._covariance_preprocessing[cov_type_name] + + mean = [0.1, 0.2, 0.3] + cov_object = cov_type(preprocessing(A)) + mvn = multivariate_normal + dist0 = multivariate_normal(mean, A, allow_singular=True) + dist1 = multivariate_normal(mean, cov_object, allow_singular=True) + + rng = np.random.default_rng(5292808890472453840) + x = rng.multivariate_normal(mean, A, size=size) + rng = np.random.default_rng(5292808890472453840) + x1 = mvn.rvs(mean, cov_object, size=size, random_state=rng) + rng = np.random.default_rng(5292808890472453840) + x2 = mvn(mean, cov_object, seed=rng).rvs(size=size) + if isinstance(cov_object, _covariance.CovViaPSD): + assert_close(x1, np.squeeze(x)) # for backward compatibility + assert_close(x2, np.squeeze(x)) + else: + assert_equal(x1.shape, x.shape) + assert_equal(x2.shape, x.shape) + assert_close(x2, x1) + + assert_close(mvn.pdf(x, mean, cov_object), dist0.pdf(x)) + assert_close(dist1.pdf(x), dist0.pdf(x)) + assert_close(mvn.logpdf(x, mean, cov_object), dist0.logpdf(x)) + assert_close(dist1.logpdf(x), dist0.logpdf(x)) + assert_close(mvn.entropy(mean, cov_object), dist0.entropy()) + assert_close(dist1.entropy(), dist0.entropy()) + + @pytest.mark.parametrize("size", [tuple(), (2, 4, 3)]) + @pytest.mark.parametrize("cov_type_name", _all_covariance_types) + def test_mvn_with_covariance_cdf(self, size, cov_type_name): + # This is split from the test above because it's slow to be running + # with all matrix types, and there's no need because _mvn.mvnun + # does the calculation. All Covariance needs to do is pass is + # provide the `covariance` attribute. + matrix_type = "diagonal full rank" + A = self._matrices[matrix_type] + cov_type = getattr(_covariance, f"CovVia{cov_type_name}") + preprocessing = self._covariance_preprocessing[cov_type_name] + + mean = [0.1, 0.2, 0.3] + cov_object = cov_type(preprocessing(A)) + mvn = multivariate_normal + dist0 = multivariate_normal(mean, A, allow_singular=True) + dist1 = multivariate_normal(mean, cov_object, allow_singular=True) + + rng = np.random.default_rng(5292808890472453840) + x = rng.multivariate_normal(mean, A, size=size) + + assert_close(mvn.cdf(x, mean, cov_object), dist0.cdf(x)) + assert_close(dist1.cdf(x), dist0.cdf(x)) + assert_close(mvn.logcdf(x, mean, cov_object), dist0.logcdf(x)) + assert_close(dist1.logcdf(x), dist0.logcdf(x)) + + def test_covariance_instantiation(self): + message = "The `Covariance` class cannot be instantiated directly." + with pytest.raises(NotImplementedError, match=message): + Covariance() + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") # matrix not PSD + def test_gh9942(self): + # Originally there was a mistake in the `multivariate_normal_frozen` + # `rvs` method that caused all covariance objects to be processed as + # a `_CovViaPSD`. Ensure that this is resolved. + A = np.diag([1, 2, -1e-8]) + n = A.shape[0] + mean = np.zeros(n) + + # Error if the matrix is processed as a `_CovViaPSD` + with pytest.raises(ValueError, match="The input matrix must be..."): + multivariate_normal(mean, A).rvs() + + # No error if it is provided as a `CovViaEigendecomposition` + seed = 3562050283508273023 + rng1 = np.random.default_rng(seed) + rng2 = np.random.default_rng(seed) + cov = Covariance.from_eigendecomposition(np.linalg.eigh(A)) + rv = multivariate_normal(mean, cov) + res = rv.rvs(random_state=rng1) + ref = multivariate_normal.rvs(mean, cov, random_state=rng2) + assert_equal(res, ref) + + def test_gh19197(self): + # gh-19197 reported that multivariate normal `rvs` produced incorrect + # results when a singular Covariance object was produce using + # `from_eigenvalues`. Check that this specific issue is resolved; + # a more general test is included in `test_covariance`. + mean = np.ones(2) + cov = Covariance.from_eigendecomposition((np.zeros(2), np.eye(2))) + dist = scipy.stats.multivariate_normal(mean=mean, cov=cov) + rvs = dist.rvs(size=None) + assert_equal(rvs, mean) + + cov = scipy.stats.Covariance.from_eigendecomposition( + (np.array([1., 0.]), np.array([[1., 0.], [0., 400.]]))) + dist = scipy.stats.multivariate_normal(mean=mean, cov=cov) + rvs = dist.rvs(size=None) + assert rvs[0] != mean[0] + assert rvs[1] == mean[1] + + +def _random_covariance(dim, evals, rng, singular=False): + # Generates random covariance matrix with dimensionality `dim` and + # eigenvalues `evals` using provided Generator `rng`. Randomly sets + # some evals to zero if `singular` is True. + A = rng.random((dim, dim)) + A = A @ A.T + _, v = np.linalg.eigh(A) + if singular: + zero_eigs = rng.normal(size=dim) > 0 + evals[zero_eigs] = 0 + cov = v @ np.diag(evals) @ v.T + return cov + + +def _sample_orthonormal_matrix(n): + M = np.random.randn(n, n) + u, s, v = scipy.linalg.svd(M) + return u + + +class TestMultivariateNormal: + def test_input_shape(self): + mu = np.arange(3) + cov = np.identity(2) + assert_raises(ValueError, multivariate_normal.pdf, (0, 1), mu, cov) + assert_raises(ValueError, multivariate_normal.pdf, (0, 1, 2), mu, cov) + assert_raises(ValueError, multivariate_normal.cdf, (0, 1), mu, cov) + assert_raises(ValueError, multivariate_normal.cdf, (0, 1, 2), mu, cov) + + def test_scalar_values(self): + np.random.seed(1234) + + # When evaluated on scalar data, the pdf should return a scalar + x, mean, cov = 1.5, 1.7, 2.5 + pdf = multivariate_normal.pdf(x, mean, cov) + assert_equal(pdf.ndim, 0) + + # When evaluated on a single vector, the pdf should return a scalar + x = np.random.randn(5) + mean = np.random.randn(5) + cov = np.abs(np.random.randn(5)) # Diagonal values for cov. matrix + pdf = multivariate_normal.pdf(x, mean, cov) + assert_equal(pdf.ndim, 0) + + # When evaluated on scalar data, the cdf should return a scalar + x, mean, cov = 1.5, 1.7, 2.5 + cdf = multivariate_normal.cdf(x, mean, cov) + assert_equal(cdf.ndim, 0) + + # When evaluated on a single vector, the cdf should return a scalar + x = np.random.randn(5) + mean = np.random.randn(5) + cov = np.abs(np.random.randn(5)) # Diagonal values for cov. matrix + cdf = multivariate_normal.cdf(x, mean, cov) + assert_equal(cdf.ndim, 0) + + def test_logpdf(self): + # Check that the log of the pdf is in fact the logpdf + np.random.seed(1234) + x = np.random.randn(5) + mean = np.random.randn(5) + cov = np.abs(np.random.randn(5)) + d1 = multivariate_normal.logpdf(x, mean, cov) + d2 = multivariate_normal.pdf(x, mean, cov) + assert_allclose(d1, np.log(d2)) + + def test_logpdf_default_values(self): + # Check that the log of the pdf is in fact the logpdf + # with default parameters Mean=None and cov = 1 + np.random.seed(1234) + x = np.random.randn(5) + d1 = multivariate_normal.logpdf(x) + d2 = multivariate_normal.pdf(x) + # check whether default values are being used + d3 = multivariate_normal.logpdf(x, None, 1) + d4 = multivariate_normal.pdf(x, None, 1) + assert_allclose(d1, np.log(d2)) + assert_allclose(d3, np.log(d4)) + + def test_logcdf(self): + # Check that the log of the cdf is in fact the logcdf + np.random.seed(1234) + x = np.random.randn(5) + mean = np.random.randn(5) + cov = np.abs(np.random.randn(5)) + d1 = multivariate_normal.logcdf(x, mean, cov) + d2 = multivariate_normal.cdf(x, mean, cov) + assert_allclose(d1, np.log(d2)) + + def test_logcdf_default_values(self): + # Check that the log of the cdf is in fact the logcdf + # with default parameters Mean=None and cov = 1 + np.random.seed(1234) + x = np.random.randn(5) + d1 = multivariate_normal.logcdf(x) + d2 = multivariate_normal.cdf(x) + # check whether default values are being used + d3 = multivariate_normal.logcdf(x, None, 1) + d4 = multivariate_normal.cdf(x, None, 1) + assert_allclose(d1, np.log(d2)) + assert_allclose(d3, np.log(d4)) + + def test_rank(self): + # Check that the rank is detected correctly. + np.random.seed(1234) + n = 4 + mean = np.random.randn(n) + for expected_rank in range(1, n + 1): + s = np.random.randn(n, expected_rank) + cov = np.dot(s, s.T) + distn = multivariate_normal(mean, cov, allow_singular=True) + assert_equal(distn.cov_object.rank, expected_rank) + + def test_degenerate_distributions(self): + + for n in range(1, 5): + z = np.random.randn(n) + for k in range(1, n): + # Sample a small covariance matrix. + s = np.random.randn(k, k) + cov_kk = np.dot(s, s.T) + + # Embed the small covariance matrix into a larger singular one. + cov_nn = np.zeros((n, n)) + cov_nn[:k, :k] = cov_kk + + # Embed part of the vector in the same way + x = np.zeros(n) + x[:k] = z[:k] + + # Define a rotation of the larger low rank matrix. + u = _sample_orthonormal_matrix(n) + cov_rr = np.dot(u, np.dot(cov_nn, u.T)) + y = np.dot(u, x) + + # Check some identities. + distn_kk = multivariate_normal(np.zeros(k), cov_kk, + allow_singular=True) + distn_nn = multivariate_normal(np.zeros(n), cov_nn, + allow_singular=True) + distn_rr = multivariate_normal(np.zeros(n), cov_rr, + allow_singular=True) + assert_equal(distn_kk.cov_object.rank, k) + assert_equal(distn_nn.cov_object.rank, k) + assert_equal(distn_rr.cov_object.rank, k) + pdf_kk = distn_kk.pdf(x[:k]) + pdf_nn = distn_nn.pdf(x) + pdf_rr = distn_rr.pdf(y) + assert_allclose(pdf_kk, pdf_nn) + assert_allclose(pdf_kk, pdf_rr) + logpdf_kk = distn_kk.logpdf(x[:k]) + logpdf_nn = distn_nn.logpdf(x) + logpdf_rr = distn_rr.logpdf(y) + assert_allclose(logpdf_kk, logpdf_nn) + assert_allclose(logpdf_kk, logpdf_rr) + + # Add an orthogonal component and find the density + y_orth = y + u[:, -1] + pdf_rr_orth = distn_rr.pdf(y_orth) + logpdf_rr_orth = distn_rr.logpdf(y_orth) + + # Ensure that this has zero probability + assert_equal(pdf_rr_orth, 0.0) + assert_equal(logpdf_rr_orth, -np.inf) + + def test_degenerate_array(self): + # Test that we can generate arrays of random variate from a degenerate + # multivariate normal, and that the pdf for these samples is non-zero + # (i.e. samples from the distribution lie on the subspace) + k = 10 + for n in range(2, 6): + for r in range(1, n): + mn = np.zeros(n) + u = _sample_orthonormal_matrix(n)[:, :r] + vr = np.dot(u, u.T) + X = multivariate_normal.rvs(mean=mn, cov=vr, size=k) + + pdf = multivariate_normal.pdf(X, mean=mn, cov=vr, + allow_singular=True) + assert_equal(pdf.size, k) + assert np.all(pdf > 0.0) + + logpdf = multivariate_normal.logpdf(X, mean=mn, cov=vr, + allow_singular=True) + assert_equal(logpdf.size, k) + assert np.all(logpdf > -np.inf) + + def test_large_pseudo_determinant(self): + # Check that large pseudo-determinants are handled appropriately. + + # Construct a singular diagonal covariance matrix + # whose pseudo determinant overflows double precision. + large_total_log = 1000.0 + npos = 100 + nzero = 2 + large_entry = np.exp(large_total_log / npos) + n = npos + nzero + cov = np.zeros((n, n), dtype=float) + np.fill_diagonal(cov, large_entry) + cov[-nzero:, -nzero:] = 0 + + # Check some determinants. + assert_equal(scipy.linalg.det(cov), 0) + assert_equal(scipy.linalg.det(cov[:npos, :npos]), np.inf) + assert_allclose(np.linalg.slogdet(cov[:npos, :npos]), + (1, large_total_log)) + + # Check the pseudo-determinant. + psd = _PSD(cov) + assert_allclose(psd.log_pdet, large_total_log) + + def test_broadcasting(self): + np.random.seed(1234) + n = 4 + + # Construct a random covariance matrix. + data = np.random.randn(n, n) + cov = np.dot(data, data.T) + mean = np.random.randn(n) + + # Construct an ndarray which can be interpreted as + # a 2x3 array whose elements are random data vectors. + X = np.random.randn(2, 3, n) + + # Check that multiple data points can be evaluated at once. + desired_pdf = multivariate_normal.pdf(X, mean, cov) + desired_cdf = multivariate_normal.cdf(X, mean, cov) + for i in range(2): + for j in range(3): + actual = multivariate_normal.pdf(X[i, j], mean, cov) + assert_allclose(actual, desired_pdf[i,j]) + # Repeat for cdf + actual = multivariate_normal.cdf(X[i, j], mean, cov) + assert_allclose(actual, desired_cdf[i,j], rtol=1e-3) + + def test_normal_1D(self): + # The probability density function for a 1D normal variable should + # agree with the standard normal distribution in scipy.stats.distributions + x = np.linspace(0, 2, 10) + mean, cov = 1.2, 0.9 + scale = cov**0.5 + d1 = norm.pdf(x, mean, scale) + d2 = multivariate_normal.pdf(x, mean, cov) + assert_allclose(d1, d2) + # The same should hold for the cumulative distribution function + d1 = norm.cdf(x, mean, scale) + d2 = multivariate_normal.cdf(x, mean, cov) + assert_allclose(d1, d2) + + def test_marginalization(self): + # Integrating out one of the variables of a 2D Gaussian should + # yield a 1D Gaussian + mean = np.array([2.5, 3.5]) + cov = np.array([[.5, 0.2], [0.2, .6]]) + n = 2 ** 8 + 1 # Number of samples + delta = 6 / (n - 1) # Grid spacing + + v = np.linspace(0, 6, n) + xv, yv = np.meshgrid(v, v) + pos = np.empty((n, n, 2)) + pos[:, :, 0] = xv + pos[:, :, 1] = yv + pdf = multivariate_normal.pdf(pos, mean, cov) + + # Marginalize over x and y axis + margin_x = romb(pdf, delta, axis=0) + margin_y = romb(pdf, delta, axis=1) + + # Compare with standard normal distribution + gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5) + gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5) + assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2) + assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2) + + def test_frozen(self): + # The frozen distribution should agree with the regular one + np.random.seed(1234) + x = np.random.randn(5) + mean = np.random.randn(5) + cov = np.abs(np.random.randn(5)) + norm_frozen = multivariate_normal(mean, cov) + assert_allclose(norm_frozen.pdf(x), multivariate_normal.pdf(x, mean, cov)) + assert_allclose(norm_frozen.logpdf(x), + multivariate_normal.logpdf(x, mean, cov)) + assert_allclose(norm_frozen.cdf(x), multivariate_normal.cdf(x, mean, cov)) + assert_allclose(norm_frozen.logcdf(x), + multivariate_normal.logcdf(x, mean, cov)) + + @pytest.mark.parametrize( + 'covariance', + [ + np.eye(2), + Covariance.from_diagonal([1, 1]), + ] + ) + def test_frozen_multivariate_normal_exposes_attributes(self, covariance): + mean = np.ones((2,)) + cov_should_be = np.eye(2) + norm_frozen = multivariate_normal(mean, covariance) + assert np.allclose(norm_frozen.mean, mean) + assert np.allclose(norm_frozen.cov, cov_should_be) + + def test_pseudodet_pinv(self): + # Make sure that pseudo-inverse and pseudo-det agree on cutoff + + # Assemble random covariance matrix with large and small eigenvalues + np.random.seed(1234) + n = 7 + x = np.random.randn(n, n) + cov = np.dot(x, x.T) + s, u = scipy.linalg.eigh(cov) + s = np.full(n, 0.5) + s[0] = 1.0 + s[-1] = 1e-7 + cov = np.dot(u, np.dot(np.diag(s), u.T)) + + # Set cond so that the lowest eigenvalue is below the cutoff + cond = 1e-5 + psd = _PSD(cov, cond=cond) + psd_pinv = _PSD(psd.pinv, cond=cond) + + # Check that the log pseudo-determinant agrees with the sum + # of the logs of all but the smallest eigenvalue + assert_allclose(psd.log_pdet, np.sum(np.log(s[:-1]))) + # Check that the pseudo-determinant of the pseudo-inverse + # agrees with 1 / pseudo-determinant + assert_allclose(-psd.log_pdet, psd_pinv.log_pdet) + + def test_exception_nonsquare_cov(self): + cov = [[1, 2, 3], [4, 5, 6]] + assert_raises(ValueError, _PSD, cov) + + def test_exception_nonfinite_cov(self): + cov_nan = [[1, 0], [0, np.nan]] + assert_raises(ValueError, _PSD, cov_nan) + cov_inf = [[1, 0], [0, np.inf]] + assert_raises(ValueError, _PSD, cov_inf) + + def test_exception_non_psd_cov(self): + cov = [[1, 0], [0, -1]] + assert_raises(ValueError, _PSD, cov) + + def test_exception_singular_cov(self): + np.random.seed(1234) + x = np.random.randn(5) + mean = np.random.randn(5) + cov = np.ones((5, 5)) + e = np.linalg.LinAlgError + assert_raises(e, multivariate_normal, mean, cov) + assert_raises(e, multivariate_normal.pdf, x, mean, cov) + assert_raises(e, multivariate_normal.logpdf, x, mean, cov) + assert_raises(e, multivariate_normal.cdf, x, mean, cov) + assert_raises(e, multivariate_normal.logcdf, x, mean, cov) + + # Message used to be "singular matrix", but this is more accurate. + # See gh-15508 + cov = [[1., 0.], [1., 1.]] + msg = "When `allow_singular is False`, the input matrix" + with pytest.raises(np.linalg.LinAlgError, match=msg): + multivariate_normal(cov=cov) + + def test_R_values(self): + # Compare the multivariate pdf with some values precomputed + # in R version 3.0.1 (2013-05-16) on Mac OS X 10.6. + + # The values below were generated by the following R-script: + # > library(mnormt) + # > x <- seq(0, 2, length=5) + # > y <- 3*x - 2 + # > z <- x + cos(y) + # > mu <- c(1, 3, 2) + # > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3) + # > r_pdf <- dmnorm(cbind(x,y,z), mu, Sigma) + r_pdf = np.array([0.0002214706, 0.0013819953, 0.0049138692, + 0.0103803050, 0.0140250800]) + + x = np.linspace(0, 2, 5) + y = 3 * x - 2 + z = x + np.cos(y) + r = np.array([x, y, z]).T + + mean = np.array([1, 3, 2], 'd') + cov = np.array([[1, 2, 0], [2, 5, .5], [0, .5, 3]], 'd') + + pdf = multivariate_normal.pdf(r, mean, cov) + assert_allclose(pdf, r_pdf, atol=1e-10) + + # Compare the multivariate cdf with some values precomputed + # in R version 3.3.2 (2016-10-31) on Debian GNU/Linux. + + # The values below were generated by the following R-script: + # > library(mnormt) + # > x <- seq(0, 2, length=5) + # > y <- 3*x - 2 + # > z <- x + cos(y) + # > mu <- c(1, 3, 2) + # > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3) + # > r_cdf <- pmnorm(cbind(x,y,z), mu, Sigma) + r_cdf = np.array([0.0017866215, 0.0267142892, 0.0857098761, + 0.1063242573, 0.2501068509]) + + cdf = multivariate_normal.cdf(r, mean, cov) + assert_allclose(cdf, r_cdf, atol=2e-5) + + # Also test bivariate cdf with some values precomputed + # in R version 3.3.2 (2016-10-31) on Debian GNU/Linux. + + # The values below were generated by the following R-script: + # > library(mnormt) + # > x <- seq(0, 2, length=5) + # > y <- 3*x - 2 + # > mu <- c(1, 3) + # > Sigma <- matrix(c(1,2,2,5), 2, 2) + # > r_cdf2 <- pmnorm(cbind(x,y), mu, Sigma) + r_cdf2 = np.array([0.01262147, 0.05838989, 0.18389571, + 0.40696599, 0.66470577]) + + r2 = np.array([x, y]).T + + mean2 = np.array([1, 3], 'd') + cov2 = np.array([[1, 2], [2, 5]], 'd') + + cdf2 = multivariate_normal.cdf(r2, mean2, cov2) + assert_allclose(cdf2, r_cdf2, atol=1e-5) + + def test_multivariate_normal_rvs_zero_covariance(self): + mean = np.zeros(2) + covariance = np.zeros((2, 2)) + model = multivariate_normal(mean, covariance, allow_singular=True) + sample = model.rvs() + assert_equal(sample, [0, 0]) + + def test_rvs_shape(self): + # Check that rvs parses the mean and covariance correctly, and returns + # an array of the right shape + N = 300 + d = 4 + sample = multivariate_normal.rvs(mean=np.zeros(d), cov=1, size=N) + assert_equal(sample.shape, (N, d)) + + sample = multivariate_normal.rvs(mean=None, + cov=np.array([[2, .1], [.1, 1]]), + size=N) + assert_equal(sample.shape, (N, 2)) + + u = multivariate_normal(mean=0, cov=1) + sample = u.rvs(N) + assert_equal(sample.shape, (N, )) + + def test_large_sample(self): + # Generate large sample and compare sample mean and sample covariance + # with mean and covariance matrix. + + np.random.seed(2846) + + n = 3 + mean = np.random.randn(n) + M = np.random.randn(n, n) + cov = np.dot(M, M.T) + size = 5000 + + sample = multivariate_normal.rvs(mean, cov, size) + + assert_allclose(np.cov(sample.T), cov, rtol=1e-1) + assert_allclose(sample.mean(0), mean, rtol=1e-1) + + def test_entropy(self): + np.random.seed(2846) + + n = 3 + mean = np.random.randn(n) + M = np.random.randn(n, n) + cov = np.dot(M, M.T) + + rv = multivariate_normal(mean, cov) + + # Check that frozen distribution agrees with entropy function + assert_almost_equal(rv.entropy(), multivariate_normal.entropy(mean, cov)) + # Compare entropy with manually computed expression involving + # the sum of the logs of the eigenvalues of the covariance matrix + eigs = np.linalg.eig(cov)[0] + desired = 1 / 2 * (n * (np.log(2 * np.pi) + 1) + np.sum(np.log(eigs))) + assert_almost_equal(desired, rv.entropy()) + + def test_lnB(self): + alpha = np.array([1, 1, 1]) + desired = .5 # e^lnB = 1/2 for [1, 1, 1] + + assert_almost_equal(np.exp(_lnB(alpha)), desired) + + def test_cdf_with_lower_limit_arrays(self): + # test CDF with lower limit in several dimensions + rng = np.random.default_rng(2408071309372769818) + mean = [0, 0] + cov = np.eye(2) + a = rng.random((4, 3, 2))*6 - 3 + b = rng.random((4, 3, 2))*6 - 3 + + cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a) + + cdf2a = multivariate_normal.cdf(b, mean, cov) + cdf2b = multivariate_normal.cdf(a, mean, cov) + ab1 = np.concatenate((a[..., 0:1], b[..., 1:2]), axis=-1) + ab2 = np.concatenate((a[..., 1:2], b[..., 0:1]), axis=-1) + cdf2ab1 = multivariate_normal.cdf(ab1, mean, cov) + cdf2ab2 = multivariate_normal.cdf(ab2, mean, cov) + cdf2 = cdf2a + cdf2b - cdf2ab1 - cdf2ab2 + + assert_allclose(cdf1, cdf2) + + def test_cdf_with_lower_limit_consistency(self): + # check that multivariate normal CDF functions are consistent + rng = np.random.default_rng(2408071309372769818) + mean = rng.random(3) + cov = rng.random((3, 3)) + cov = cov @ cov.T + a = rng.random((2, 3))*6 - 3 + b = rng.random((2, 3))*6 - 3 + + cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a) + cdf2 = multivariate_normal(mean, cov).cdf(b, lower_limit=a) + cdf3 = np.exp(multivariate_normal.logcdf(b, mean, cov, lower_limit=a)) + cdf4 = np.exp(multivariate_normal(mean, cov).logcdf(b, lower_limit=a)) + + assert_allclose(cdf2, cdf1, rtol=1e-4) + assert_allclose(cdf3, cdf1, rtol=1e-4) + assert_allclose(cdf4, cdf1, rtol=1e-4) + + def test_cdf_signs(self): + # check that sign of output is correct when np.any(lower > x) + mean = np.zeros(3) + cov = np.eye(3) + b = [[1, 1, 1], [0, 0, 0], [1, 0, 1], [0, 1, 0]] + a = [[0, 0, 0], [1, 1, 1], [0, 1, 0], [1, 0, 1]] + # when odd number of elements of b < a, output is negative + expected_signs = np.array([1, -1, -1, 1]) + cdf = multivariate_normal.cdf(b, mean, cov, lower_limit=a) + assert_allclose(cdf, cdf[0]*expected_signs) + + def test_mean_cov(self): + # test the interaction between a Covariance object and mean + P = np.diag(1 / np.array([1, 2, 3])) + cov_object = _covariance.CovViaPrecision(P) + + message = "`cov` represents a covariance matrix in 3 dimensions..." + with pytest.raises(ValueError, match=message): + multivariate_normal.entropy([0, 0], cov_object) + + with pytest.raises(ValueError, match=message): + multivariate_normal([0, 0], cov_object) + + x = [0.5, 0.5, 0.5] + ref = multivariate_normal.pdf(x, [0, 0, 0], cov_object) + assert_equal(multivariate_normal.pdf(x, cov=cov_object), ref) + + ref = multivariate_normal.pdf(x, [1, 1, 1], cov_object) + assert_equal(multivariate_normal.pdf(x, 1, cov=cov_object), ref) + + def test_fit_wrong_fit_data_shape(self): + data = [1, 3] + error_msg = "`x` must be two-dimensional." + with pytest.raises(ValueError, match=error_msg): + multivariate_normal.fit(data) + + @pytest.mark.parametrize('dim', (3, 5)) + def test_fit_correctness(self, dim): + rng = np.random.default_rng(4385269356937404) + x = rng.random((100, dim)) + mean_est, cov_est = multivariate_normal.fit(x) + mean_ref, cov_ref = np.mean(x, axis=0), np.cov(x.T, ddof=0) + assert_allclose(mean_est, mean_ref, atol=1e-15) + assert_allclose(cov_est, cov_ref, rtol=1e-15) + + def test_fit_both_parameters_fixed(self): + data = np.full((2, 1), 3) + mean_fixed = 1. + cov_fixed = np.atleast_2d(1.) + mean, cov = multivariate_normal.fit(data, fix_mean=mean_fixed, + fix_cov=cov_fixed) + assert_equal(mean, mean_fixed) + assert_equal(cov, cov_fixed) + + @pytest.mark.parametrize('fix_mean', [np.zeros((2, 2)), + np.zeros((3, ))]) + def test_fit_fix_mean_input_validation(self, fix_mean): + msg = ("`fix_mean` must be a one-dimensional array the same " + "length as the dimensionality of the vectors `x`.") + with pytest.raises(ValueError, match=msg): + multivariate_normal.fit(np.eye(2), fix_mean=fix_mean) + + @pytest.mark.parametrize('fix_cov', [np.zeros((2, )), + np.zeros((3, 2)), + np.zeros((4, 4))]) + def test_fit_fix_cov_input_validation_dimension(self, fix_cov): + msg = ("`fix_cov` must be a two-dimensional square array " + "of same side length as the dimensionality of the " + "vectors `x`.") + with pytest.raises(ValueError, match=msg): + multivariate_normal.fit(np.eye(3), fix_cov=fix_cov) + + def test_fit_fix_cov_not_positive_semidefinite(self): + error_msg = "`fix_cov` must be symmetric positive semidefinite." + with pytest.raises(ValueError, match=error_msg): + fix_cov = np.array([[1., 0.], [0., -1.]]) + multivariate_normal.fit(np.eye(2), fix_cov=fix_cov) + + def test_fit_fix_mean(self): + rng = np.random.default_rng(4385269356937404) + loc = rng.random(3) + A = rng.random((3, 3)) + cov = np.dot(A, A.T) + samples = multivariate_normal.rvs(mean=loc, cov=cov, size=100, + random_state=rng) + mean_free, cov_free = multivariate_normal.fit(samples) + logp_free = multivariate_normal.logpdf(samples, mean=mean_free, + cov=cov_free).sum() + mean_fix, cov_fix = multivariate_normal.fit(samples, fix_mean=loc) + assert_equal(mean_fix, loc) + logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix, + cov=cov_fix).sum() + # test that fixed parameters result in lower likelihood than free + # parameters + assert logp_fix < logp_free + # test that a small perturbation of the resulting parameters + # has lower likelihood than the estimated parameters + A = rng.random((3, 3)) + m = 1e-8 * np.dot(A, A.T) + cov_perturbed = cov_fix + m + logp_perturbed = (multivariate_normal.logpdf(samples, + mean=mean_fix, + cov=cov_perturbed) + ).sum() + assert logp_perturbed < logp_fix + + + def test_fit_fix_cov(self): + rng = np.random.default_rng(4385269356937404) + loc = rng.random(3) + A = rng.random((3, 3)) + cov = np.dot(A, A.T) + samples = multivariate_normal.rvs(mean=loc, cov=cov, + size=100, random_state=rng) + mean_free, cov_free = multivariate_normal.fit(samples) + logp_free = multivariate_normal.logpdf(samples, mean=mean_free, + cov=cov_free).sum() + mean_fix, cov_fix = multivariate_normal.fit(samples, fix_cov=cov) + assert_equal(mean_fix, np.mean(samples, axis=0)) + assert_equal(cov_fix, cov) + logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix, + cov=cov_fix).sum() + # test that fixed parameters result in lower likelihood than free + # parameters + assert logp_fix < logp_free + # test that a small perturbation of the resulting parameters + # has lower likelihood than the estimated parameters + mean_perturbed = mean_fix + 1e-8 * rng.random(3) + logp_perturbed = (multivariate_normal.logpdf(samples, + mean=mean_perturbed, + cov=cov_fix) + ).sum() + assert logp_perturbed < logp_fix + + +class TestMatrixNormal: + + def test_bad_input(self): + # Check that bad inputs raise errors + num_rows = 4 + num_cols = 3 + M = np.full((num_rows,num_cols), 0.3) + U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5) + V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3) + + # Incorrect dimensions + assert_raises(ValueError, matrix_normal, np.zeros((5,4,3))) + assert_raises(ValueError, matrix_normal, M, np.zeros(10), V) + assert_raises(ValueError, matrix_normal, M, U, np.zeros(10)) + assert_raises(ValueError, matrix_normal, M, U, U) + assert_raises(ValueError, matrix_normal, M, V, V) + assert_raises(ValueError, matrix_normal, M.T, U, V) + + e = np.linalg.LinAlgError + # Singular covariance for the rvs method of a non-frozen instance + assert_raises(e, matrix_normal.rvs, + M, U, np.ones((num_cols, num_cols))) + assert_raises(e, matrix_normal.rvs, + M, np.ones((num_rows, num_rows)), V) + # Singular covariance for a frozen instance + assert_raises(e, matrix_normal, M, U, np.ones((num_cols, num_cols))) + assert_raises(e, matrix_normal, M, np.ones((num_rows, num_rows)), V) + + def test_default_inputs(self): + # Check that default argument handling works + num_rows = 4 + num_cols = 3 + M = np.full((num_rows,num_cols), 0.3) + U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5) + V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3) + Z = np.zeros((num_rows, num_cols)) + Zr = np.zeros((num_rows, 1)) + Zc = np.zeros((1, num_cols)) + Ir = np.identity(num_rows) + Ic = np.identity(num_cols) + I1 = np.identity(1) + + assert_equal(matrix_normal.rvs(mean=M, rowcov=U, colcov=V).shape, + (num_rows, num_cols)) + assert_equal(matrix_normal.rvs(mean=M).shape, + (num_rows, num_cols)) + assert_equal(matrix_normal.rvs(rowcov=U).shape, + (num_rows, 1)) + assert_equal(matrix_normal.rvs(colcov=V).shape, + (1, num_cols)) + assert_equal(matrix_normal.rvs(mean=M, colcov=V).shape, + (num_rows, num_cols)) + assert_equal(matrix_normal.rvs(mean=M, rowcov=U).shape, + (num_rows, num_cols)) + assert_equal(matrix_normal.rvs(rowcov=U, colcov=V).shape, + (num_rows, num_cols)) + + assert_equal(matrix_normal(mean=M).rowcov, Ir) + assert_equal(matrix_normal(mean=M).colcov, Ic) + assert_equal(matrix_normal(rowcov=U).mean, Zr) + assert_equal(matrix_normal(rowcov=U).colcov, I1) + assert_equal(matrix_normal(colcov=V).mean, Zc) + assert_equal(matrix_normal(colcov=V).rowcov, I1) + assert_equal(matrix_normal(mean=M, rowcov=U).colcov, Ic) + assert_equal(matrix_normal(mean=M, colcov=V).rowcov, Ir) + assert_equal(matrix_normal(rowcov=U, colcov=V).mean, Z) + + def test_covariance_expansion(self): + # Check that covariance can be specified with scalar or vector + num_rows = 4 + num_cols = 3 + M = np.full((num_rows, num_cols), 0.3) + Uv = np.full(num_rows, 0.2) + Us = 0.2 + Vv = np.full(num_cols, 0.1) + Vs = 0.1 + + Ir = np.identity(num_rows) + Ic = np.identity(num_cols) + + assert_equal(matrix_normal(mean=M, rowcov=Uv, colcov=Vv).rowcov, + 0.2*Ir) + assert_equal(matrix_normal(mean=M, rowcov=Uv, colcov=Vv).colcov, + 0.1*Ic) + assert_equal(matrix_normal(mean=M, rowcov=Us, colcov=Vs).rowcov, + 0.2*Ir) + assert_equal(matrix_normal(mean=M, rowcov=Us, colcov=Vs).colcov, + 0.1*Ic) + + def test_frozen_matrix_normal(self): + for i in range(1,5): + for j in range(1,5): + M = np.full((i,j), 0.3) + U = 0.5 * np.identity(i) + np.full((i,i), 0.5) + V = 0.7 * np.identity(j) + np.full((j,j), 0.3) + + frozen = matrix_normal(mean=M, rowcov=U, colcov=V) + + rvs1 = frozen.rvs(random_state=1234) + rvs2 = matrix_normal.rvs(mean=M, rowcov=U, colcov=V, + random_state=1234) + assert_equal(rvs1, rvs2) + + X = frozen.rvs(random_state=1234) + + pdf1 = frozen.pdf(X) + pdf2 = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V) + assert_equal(pdf1, pdf2) + + logpdf1 = frozen.logpdf(X) + logpdf2 = matrix_normal.logpdf(X, mean=M, rowcov=U, colcov=V) + assert_equal(logpdf1, logpdf2) + + def test_matches_multivariate(self): + # Check that the pdfs match those obtained by vectorising and + # treating as a multivariate normal. + for i in range(1,5): + for j in range(1,5): + M = np.full((i,j), 0.3) + U = 0.5 * np.identity(i) + np.full((i,i), 0.5) + V = 0.7 * np.identity(j) + np.full((j,j), 0.3) + + frozen = matrix_normal(mean=M, rowcov=U, colcov=V) + X = frozen.rvs(random_state=1234) + pdf1 = frozen.pdf(X) + logpdf1 = frozen.logpdf(X) + entropy1 = frozen.entropy() + + vecX = X.T.flatten() + vecM = M.T.flatten() + cov = np.kron(V,U) + pdf2 = multivariate_normal.pdf(vecX, mean=vecM, cov=cov) + logpdf2 = multivariate_normal.logpdf(vecX, mean=vecM, cov=cov) + entropy2 = multivariate_normal.entropy(mean=vecM, cov=cov) + + assert_allclose(pdf1, pdf2, rtol=1E-10) + assert_allclose(logpdf1, logpdf2, rtol=1E-10) + assert_allclose(entropy1, entropy2) + + def test_array_input(self): + # Check array of inputs has the same output as the separate entries. + num_rows = 4 + num_cols = 3 + M = np.full((num_rows,num_cols), 0.3) + U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5) + V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3) + N = 10 + + frozen = matrix_normal(mean=M, rowcov=U, colcov=V) + X1 = frozen.rvs(size=N, random_state=1234) + X2 = frozen.rvs(size=N, random_state=4321) + X = np.concatenate((X1[np.newaxis,:,:,:],X2[np.newaxis,:,:,:]), axis=0) + assert_equal(X.shape, (2, N, num_rows, num_cols)) + + array_logpdf = frozen.logpdf(X) + assert_equal(array_logpdf.shape, (2, N)) + for i in range(2): + for j in range(N): + separate_logpdf = matrix_normal.logpdf(X[i,j], mean=M, + rowcov=U, colcov=V) + assert_allclose(separate_logpdf, array_logpdf[i,j], 1E-10) + + def test_moments(self): + # Check that the sample moments match the parameters + num_rows = 4 + num_cols = 3 + M = np.full((num_rows,num_cols), 0.3) + U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5) + V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3) + N = 1000 + + frozen = matrix_normal(mean=M, rowcov=U, colcov=V) + X = frozen.rvs(size=N, random_state=1234) + + sample_mean = np.mean(X,axis=0) + assert_allclose(sample_mean, M, atol=0.1) + + sample_colcov = np.cov(X.reshape(N*num_rows,num_cols).T) + assert_allclose(sample_colcov, V, atol=0.1) + + sample_rowcov = np.cov(np.swapaxes(X,1,2).reshape( + N*num_cols,num_rows).T) + assert_allclose(sample_rowcov, U, atol=0.1) + + def test_samples(self): + # Regression test to ensure that we always generate the same stream of + # random variates. + actual = matrix_normal.rvs( + mean=np.array([[1, 2], [3, 4]]), + rowcov=np.array([[4, -1], [-1, 2]]), + colcov=np.array([[5, 1], [1, 10]]), + random_state=np.random.default_rng(0), + size=2 + ) + expected = np.array( + [[[1.56228264238181, -1.24136424071189], + [2.46865788392114, 6.22964440489445]], + [[3.86405716144353, 10.73714311429529], + [2.59428444080606, 5.79987854490876]]] + ) + assert_allclose(actual, expected) + + +class TestDirichlet: + + def test_frozen_dirichlet(self): + np.random.seed(2846) + + n = np.random.randint(1, 32) + alpha = np.random.uniform(10e-10, 100, n) + + d = dirichlet(alpha) + + assert_equal(d.var(), dirichlet.var(alpha)) + assert_equal(d.mean(), dirichlet.mean(alpha)) + assert_equal(d.entropy(), dirichlet.entropy(alpha)) + num_tests = 10 + for i in range(num_tests): + x = np.random.uniform(10e-10, 100, n) + x /= np.sum(x) + assert_equal(d.pdf(x[:-1]), dirichlet.pdf(x[:-1], alpha)) + assert_equal(d.logpdf(x[:-1]), dirichlet.logpdf(x[:-1], alpha)) + + def test_numpy_rvs_shape_compatibility(self): + np.random.seed(2846) + alpha = np.array([1.0, 2.0, 3.0]) + x = np.random.dirichlet(alpha, size=7) + assert_equal(x.shape, (7, 3)) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + dirichlet.pdf(x.T, alpha) + dirichlet.pdf(x.T[:-1], alpha) + dirichlet.logpdf(x.T, alpha) + dirichlet.logpdf(x.T[:-1], alpha) + + def test_alpha_with_zeros(self): + np.random.seed(2846) + alpha = [1.0, 0.0, 3.0] + # don't pass invalid alpha to np.random.dirichlet + x = np.random.dirichlet(np.maximum(1e-9, alpha), size=7).T + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_alpha_with_negative_entries(self): + np.random.seed(2846) + alpha = [1.0, -2.0, 3.0] + # don't pass invalid alpha to np.random.dirichlet + x = np.random.dirichlet(np.maximum(1e-9, alpha), size=7).T + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_data_with_zeros(self): + alpha = np.array([1.0, 2.0, 3.0, 4.0]) + x = np.array([0.1, 0.0, 0.2, 0.7]) + dirichlet.pdf(x, alpha) + dirichlet.logpdf(x, alpha) + alpha = np.array([1.0, 1.0, 1.0, 1.0]) + assert_almost_equal(dirichlet.pdf(x, alpha), 6) + assert_almost_equal(dirichlet.logpdf(x, alpha), np.log(6)) + + def test_data_with_zeros_and_small_alpha(self): + alpha = np.array([1.0, 0.5, 3.0, 4.0]) + x = np.array([0.1, 0.0, 0.2, 0.7]) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_data_with_negative_entries(self): + alpha = np.array([1.0, 2.0, 3.0, 4.0]) + x = np.array([0.1, -0.1, 0.3, 0.7]) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_data_with_too_large_entries(self): + alpha = np.array([1.0, 2.0, 3.0, 4.0]) + x = np.array([0.1, 1.1, 0.3, 0.7]) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_data_too_deep_c(self): + alpha = np.array([1.0, 2.0, 3.0]) + x = np.full((2, 7, 7), 1 / 14) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_alpha_too_deep(self): + alpha = np.array([[1.0, 2.0], [3.0, 4.0]]) + x = np.full((2, 2, 7), 1 / 4) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_alpha_correct_depth(self): + alpha = np.array([1.0, 2.0, 3.0]) + x = np.full((3, 7), 1 / 3) + dirichlet.pdf(x, alpha) + dirichlet.logpdf(x, alpha) + + def test_non_simplex_data(self): + alpha = np.array([1.0, 2.0, 3.0]) + x = np.full((3, 7), 1 / 2) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_data_vector_too_short(self): + alpha = np.array([1.0, 2.0, 3.0, 4.0]) + x = np.full((2, 7), 1 / 2) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_data_vector_too_long(self): + alpha = np.array([1.0, 2.0, 3.0, 4.0]) + x = np.full((5, 7), 1 / 5) + assert_raises(ValueError, dirichlet.pdf, x, alpha) + assert_raises(ValueError, dirichlet.logpdf, x, alpha) + + def test_mean_var_cov(self): + # Reference values calculated by hand and confirmed with Mathematica, e.g. + # `Covariance[DirichletDistribution[{ 1, 0.8, 0.2, 10^-300}]]` + alpha = np.array([1., 0.8, 0.2]) + d = dirichlet(alpha) + + expected_mean = [0.5, 0.4, 0.1] + expected_var = [1. / 12., 0.08, 0.03] + expected_cov = [ + [ 1. / 12, -1. / 15, -1. / 60], + [-1. / 15, 2. / 25, -1. / 75], + [-1. / 60, -1. / 75, 3. / 100], + ] + + assert_array_almost_equal(d.mean(), expected_mean) + assert_array_almost_equal(d.var(), expected_var) + assert_array_almost_equal(d.cov(), expected_cov) + + def test_scalar_values(self): + alpha = np.array([0.2]) + d = dirichlet(alpha) + + # For alpha of length 1, mean and var should be scalar instead of array + assert_equal(d.mean().ndim, 0) + assert_equal(d.var().ndim, 0) + + assert_equal(d.pdf([1.]).ndim, 0) + assert_equal(d.logpdf([1.]).ndim, 0) + + def test_K_and_K_minus_1_calls_equal(self): + # Test that calls with K and K-1 entries yield the same results. + + np.random.seed(2846) + + n = np.random.randint(1, 32) + alpha = np.random.uniform(10e-10, 100, n) + + d = dirichlet(alpha) + num_tests = 10 + for i in range(num_tests): + x = np.random.uniform(10e-10, 100, n) + x /= np.sum(x) + assert_almost_equal(d.pdf(x[:-1]), d.pdf(x)) + + def test_multiple_entry_calls(self): + # Test that calls with multiple x vectors as matrix work + np.random.seed(2846) + + n = np.random.randint(1, 32) + alpha = np.random.uniform(10e-10, 100, n) + d = dirichlet(alpha) + + num_tests = 10 + num_multiple = 5 + xm = None + for i in range(num_tests): + for m in range(num_multiple): + x = np.random.uniform(10e-10, 100, n) + x /= np.sum(x) + if xm is not None: + xm = np.vstack((xm, x)) + else: + xm = x + rm = d.pdf(xm.T) + rs = None + for xs in xm: + r = d.pdf(xs) + if rs is not None: + rs = np.append(rs, r) + else: + rs = r + assert_array_almost_equal(rm, rs) + + def test_2D_dirichlet_is_beta(self): + np.random.seed(2846) + + alpha = np.random.uniform(10e-10, 100, 2) + d = dirichlet(alpha) + b = beta(alpha[0], alpha[1]) + + num_tests = 10 + for i in range(num_tests): + x = np.random.uniform(10e-10, 100, 2) + x /= np.sum(x) + assert_almost_equal(b.pdf(x), d.pdf([x])) + + assert_almost_equal(b.mean(), d.mean()[0]) + assert_almost_equal(b.var(), d.var()[0]) + + +def test_multivariate_normal_dimensions_mismatch(): + # Regression test for GH #3493. Check that setting up a PDF with a mean of + # length M and a covariance matrix of size (N, N), where M != N, raises a + # ValueError with an informative error message. + mu = np.array([0.0, 0.0]) + sigma = np.array([[1.0]]) + + assert_raises(ValueError, multivariate_normal, mu, sigma) + + # A simple check that the right error message was passed along. Checking + # that the entire message is there, word for word, would be somewhat + # fragile, so we just check for the leading part. + try: + multivariate_normal(mu, sigma) + except ValueError as e: + msg = "Dimension mismatch" + assert_equal(str(e)[:len(msg)], msg) + + +class TestWishart: + def test_scale_dimensions(self): + # Test that we can call the Wishart with various scale dimensions + + # Test case: dim=1, scale=1 + true_scale = np.array(1, ndmin=2) + scales = [ + 1, # scalar + [1], # iterable + np.array(1), # 0-dim + np.r_[1], # 1-dim + np.array(1, ndmin=2) # 2-dim + ] + for scale in scales: + w = wishart(1, scale) + assert_equal(w.scale, true_scale) + assert_equal(w.scale.shape, true_scale.shape) + + # Test case: dim=2, scale=[[1,0] + # [0,2] + true_scale = np.array([[1,0], + [0,2]]) + scales = [ + [1,2], # iterable + np.r_[1,2], # 1-dim + np.array([[1,0], # 2-dim + [0,2]]) + ] + for scale in scales: + w = wishart(2, scale) + assert_equal(w.scale, true_scale) + assert_equal(w.scale.shape, true_scale.shape) + + # We cannot call with a df < dim - 1 + assert_raises(ValueError, wishart, 1, np.eye(2)) + + # But we can call with dim - 1 < df < dim + wishart(1.1, np.eye(2)) # no error + # see gh-5562 + + # We cannot call with a 3-dimension array + scale = np.array(1, ndmin=3) + assert_raises(ValueError, wishart, 1, scale) + + def test_quantile_dimensions(self): + # Test that we can call the Wishart rvs with various quantile dimensions + + # If dim == 1, consider x.shape = [1,1,1] + X = [ + 1, # scalar + [1], # iterable + np.array(1), # 0-dim + np.r_[1], # 1-dim + np.array(1, ndmin=2), # 2-dim + np.array([1], ndmin=3) # 3-dim + ] + + w = wishart(1,1) + density = w.pdf(np.array(1, ndmin=3)) + for x in X: + assert_equal(w.pdf(x), density) + + # If dim == 1, consider x.shape = [1,1,*] + X = [ + [1,2,3], # iterable + np.r_[1,2,3], # 1-dim + np.array([1,2,3], ndmin=3) # 3-dim + ] + + w = wishart(1,1) + density = w.pdf(np.array([1,2,3], ndmin=3)) + for x in X: + assert_equal(w.pdf(x), density) + + # If dim == 2, consider x.shape = [2,2,1] + # where x[:,:,*] = np.eye(1)*2 + X = [ + 2, # scalar + [2,2], # iterable + np.array(2), # 0-dim + np.r_[2,2], # 1-dim + np.array([[2,0], + [0,2]]), # 2-dim + np.array([[2,0], + [0,2]])[:,:,np.newaxis] # 3-dim + ] + + w = wishart(2,np.eye(2)) + density = w.pdf(np.array([[2,0], + [0,2]])[:,:,np.newaxis]) + for x in X: + assert_equal(w.pdf(x), density) + + def test_frozen(self): + # Test that the frozen and non-frozen Wishart gives the same answers + + # Construct an arbitrary positive definite scale matrix + dim = 4 + scale = np.diag(np.arange(dim)+1) + scale[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2) + scale = np.dot(scale.T, scale) + + # Construct a collection of positive definite matrices to test the PDF + X = [] + for i in range(5): + x = np.diag(np.arange(dim)+(i+1)**2) + x[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2) + x = np.dot(x.T, x) + X.append(x) + X = np.array(X).T + + # Construct a 1D and 2D set of parameters + parameters = [ + (10, 1, np.linspace(0.1, 10, 5)), # 1D case + (10, scale, X) + ] + + for (df, scale, x) in parameters: + w = wishart(df, scale) + assert_equal(w.var(), wishart.var(df, scale)) + assert_equal(w.mean(), wishart.mean(df, scale)) + assert_equal(w.mode(), wishart.mode(df, scale)) + assert_equal(w.entropy(), wishart.entropy(df, scale)) + assert_equal(w.pdf(x), wishart.pdf(x, df, scale)) + + def test_wishart_2D_rvs(self): + dim = 3 + df = 10 + + # Construct a simple non-diagonal positive definite matrix + scale = np.eye(dim) + scale[0,1] = 0.5 + scale[1,0] = 0.5 + + # Construct frozen Wishart random variables + w = wishart(df, scale) + + # Get the generated random variables from a known seed + np.random.seed(248042) + w_rvs = wishart.rvs(df, scale) + np.random.seed(248042) + frozen_w_rvs = w.rvs() + + # Manually calculate what it should be, based on the Bartlett (1933) + # decomposition of a Wishart into D A A' D', where D is the Cholesky + # factorization of the scale matrix and A is the lower triangular matrix + # with the square root of chi^2 variates on the diagonal and N(0,1) + # variates in the lower triangle. + np.random.seed(248042) + covariances = np.random.normal(size=3) + variances = np.r_[ + np.random.chisquare(df), + np.random.chisquare(df-1), + np.random.chisquare(df-2), + ]**0.5 + + # Construct the lower-triangular A matrix + A = np.diag(variances) + A[np.tril_indices(dim, k=-1)] = covariances + + # Wishart random variate + D = np.linalg.cholesky(scale) + DA = D.dot(A) + manual_w_rvs = np.dot(DA, DA.T) + + # Test for equality + assert_allclose(w_rvs, manual_w_rvs) + assert_allclose(frozen_w_rvs, manual_w_rvs) + + def test_1D_is_chisquared(self): + # The 1-dimensional Wishart with an identity scale matrix is just a + # chi-squared distribution. + # Test variance, mean, entropy, pdf + # Kolgomorov-Smirnov test for rvs + np.random.seed(482974) + + sn = 500 + dim = 1 + scale = np.eye(dim) + + df_range = np.arange(1, 10, 2, dtype=float) + X = np.linspace(0.1,10,num=10) + for df in df_range: + w = wishart(df, scale) + c = chi2(df) + + # Statistics + assert_allclose(w.var(), c.var()) + assert_allclose(w.mean(), c.mean()) + assert_allclose(w.entropy(), c.entropy()) + + # PDF + assert_allclose(w.pdf(X), c.pdf(X)) + + # rvs + rvs = w.rvs(size=sn) + args = (df,) + alpha = 0.01 + check_distribution_rvs('chi2', args, alpha, rvs) + + def test_is_scaled_chisquared(self): + # The 2-dimensional Wishart with an arbitrary scale matrix can be + # transformed to a scaled chi-squared distribution. + # For :math:`S \sim W_p(V,n)` and :math:`\lambda \in \mathbb{R}^p` we have + # :math:`\lambda' S \lambda \sim \lambda' V \lambda \times \chi^2(n)` + np.random.seed(482974) + + sn = 500 + df = 10 + dim = 4 + # Construct an arbitrary positive definite matrix + scale = np.diag(np.arange(4)+1) + scale[np.tril_indices(4, k=-1)] = np.arange(6) + scale = np.dot(scale.T, scale) + # Use :math:`\lambda = [1, \dots, 1]'` + lamda = np.ones((dim,1)) + sigma_lamda = lamda.T.dot(scale).dot(lamda).squeeze() + w = wishart(df, sigma_lamda) + c = chi2(df, scale=sigma_lamda) + + # Statistics + assert_allclose(w.var(), c.var()) + assert_allclose(w.mean(), c.mean()) + assert_allclose(w.entropy(), c.entropy()) + + # PDF + X = np.linspace(0.1,10,num=10) + assert_allclose(w.pdf(X), c.pdf(X)) + + # rvs + rvs = w.rvs(size=sn) + args = (df,0,sigma_lamda) + alpha = 0.01 + check_distribution_rvs('chi2', args, alpha, rvs) + +class TestMultinomial: + def test_logpmf(self): + vals1 = multinomial.logpmf((3,4), 7, (0.3, 0.7)) + assert_allclose(vals1, -1.483270127243324, rtol=1e-8) + + vals2 = multinomial.logpmf([3, 4], 0, [.3, .7]) + assert vals2 == -np.inf + + vals3 = multinomial.logpmf([0, 0], 0, [.3, .7]) + assert vals3 == 0 + + vals4 = multinomial.logpmf([3, 4], 0, [-2, 3]) + assert_allclose(vals4, np.nan, rtol=1e-8) + + def test_reduces_binomial(self): + # test that the multinomial pmf reduces to the binomial pmf in the 2d + # case + val1 = multinomial.logpmf((3, 4), 7, (0.3, 0.7)) + val2 = binom.logpmf(3, 7, 0.3) + assert_allclose(val1, val2, rtol=1e-8) + + val1 = multinomial.pmf((6, 8), 14, (0.1, 0.9)) + val2 = binom.pmf(6, 14, 0.1) + assert_allclose(val1, val2, rtol=1e-8) + + def test_R(self): + # test against the values produced by this R code + # (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Multinom.html) + # X <- t(as.matrix(expand.grid(0:3, 0:3))); X <- X[, colSums(X) <= 3] + # X <- rbind(X, 3:3 - colSums(X)); dimnames(X) <- list(letters[1:3], NULL) + # X + # apply(X, 2, function(x) dmultinom(x, prob = c(1,2,5))) + + n, p = 3, [1./8, 2./8, 5./8] + r_vals = {(0, 0, 3): 0.244140625, (1, 0, 2): 0.146484375, + (2, 0, 1): 0.029296875, (3, 0, 0): 0.001953125, + (0, 1, 2): 0.292968750, (1, 1, 1): 0.117187500, + (2, 1, 0): 0.011718750, (0, 2, 1): 0.117187500, + (1, 2, 0): 0.023437500, (0, 3, 0): 0.015625000} + for x in r_vals: + assert_allclose(multinomial.pmf(x, n, p), r_vals[x], atol=1e-14) + + @pytest.mark.parametrize("n", [0, 3]) + def test_rvs_np(self, n): + # test that .rvs agrees w/numpy + sc_rvs = multinomial.rvs(n, [1/4.]*3, size=7, random_state=123) + rndm = np.random.RandomState(123) + np_rvs = rndm.multinomial(n, [1/4.]*3, size=7) + assert_equal(sc_rvs, np_rvs) + + def test_pmf(self): + vals0 = multinomial.pmf((5,), 5, (1,)) + assert_allclose(vals0, 1, rtol=1e-8) + + vals1 = multinomial.pmf((3,4), 7, (.3, .7)) + assert_allclose(vals1, .22689449999999994, rtol=1e-8) + + vals2 = multinomial.pmf([[[3,5],[0,8]], [[-1, 9], [1, 1]]], 8, + (.1, .9)) + assert_allclose(vals2, [[.03306744, .43046721], [0, 0]], rtol=1e-8) + + x = np.empty((0,2), dtype=np.float64) + vals3 = multinomial.pmf(x, 4, (.3, .7)) + assert_equal(vals3, np.empty([], dtype=np.float64)) + + vals4 = multinomial.pmf([1,2], 4, (.3, .7)) + assert_allclose(vals4, 0, rtol=1e-8) + + vals5 = multinomial.pmf([3, 3, 0], 6, [2/3.0, 1/3.0, 0]) + assert_allclose(vals5, 0.219478737997, rtol=1e-8) + + vals5 = multinomial.pmf([0, 0, 0], 0, [2/3.0, 1/3.0, 0]) + assert vals5 == 1 + + vals6 = multinomial.pmf([2, 1, 0], 0, [2/3.0, 1/3.0, 0]) + assert vals6 == 0 + + def test_pmf_broadcasting(self): + vals0 = multinomial.pmf([1, 2], 3, [[.1, .9], [.2, .8]]) + assert_allclose(vals0, [.243, .384], rtol=1e-8) + + vals1 = multinomial.pmf([1, 2], [3, 4], [.1, .9]) + assert_allclose(vals1, [.243, 0], rtol=1e-8) + + vals2 = multinomial.pmf([[[1, 2], [1, 1]]], 3, [.1, .9]) + assert_allclose(vals2, [[.243, 0]], rtol=1e-8) + + vals3 = multinomial.pmf([1, 2], [[[3], [4]]], [.1, .9]) + assert_allclose(vals3, [[[.243], [0]]], rtol=1e-8) + + vals4 = multinomial.pmf([[1, 2], [1,1]], [[[[3]]]], [.1, .9]) + assert_allclose(vals4, [[[[.243, 0]]]], rtol=1e-8) + + @pytest.mark.parametrize("n", [0, 5]) + def test_cov(self, n): + cov1 = multinomial.cov(n, (.2, .3, .5)) + cov2 = [[n*.2*.8, -n*.2*.3, -n*.2*.5], + [-n*.3*.2, n*.3*.7, -n*.3*.5], + [-n*.5*.2, -n*.5*.3, n*.5*.5]] + assert_allclose(cov1, cov2, rtol=1e-8) + + def test_cov_broadcasting(self): + cov1 = multinomial.cov(5, [[.1, .9], [.2, .8]]) + cov2 = [[[.45, -.45],[-.45, .45]], [[.8, -.8], [-.8, .8]]] + assert_allclose(cov1, cov2, rtol=1e-8) + + cov3 = multinomial.cov([4, 5], [.1, .9]) + cov4 = [[[.36, -.36], [-.36, .36]], [[.45, -.45], [-.45, .45]]] + assert_allclose(cov3, cov4, rtol=1e-8) + + cov5 = multinomial.cov([4, 5], [[.3, .7], [.4, .6]]) + cov6 = [[[4*.3*.7, -4*.3*.7], [-4*.3*.7, 4*.3*.7]], + [[5*.4*.6, -5*.4*.6], [-5*.4*.6, 5*.4*.6]]] + assert_allclose(cov5, cov6, rtol=1e-8) + + @pytest.mark.parametrize("n", [0, 2]) + def test_entropy(self, n): + # this is equivalent to a binomial distribution with n=2, so the + # entropy .77899774929 is easily computed "by hand" + ent0 = multinomial.entropy(n, [.2, .8]) + assert_allclose(ent0, binom.entropy(n, .2), rtol=1e-8) + + def test_entropy_broadcasting(self): + ent0 = multinomial.entropy([2, 3], [.2, .3]) + assert_allclose(ent0, [binom.entropy(2, .2), binom.entropy(3, .2)], + rtol=1e-8) + + ent1 = multinomial.entropy([7, 8], [[.3, .7], [.4, .6]]) + assert_allclose(ent1, [binom.entropy(7, .3), binom.entropy(8, .4)], + rtol=1e-8) + + ent2 = multinomial.entropy([[7], [8]], [[.3, .7], [.4, .6]]) + assert_allclose(ent2, + [[binom.entropy(7, .3), binom.entropy(7, .4)], + [binom.entropy(8, .3), binom.entropy(8, .4)]], + rtol=1e-8) + + @pytest.mark.parametrize("n", [0, 5]) + def test_mean(self, n): + mean1 = multinomial.mean(n, [.2, .8]) + assert_allclose(mean1, [n*.2, n*.8], rtol=1e-8) + + def test_mean_broadcasting(self): + mean1 = multinomial.mean([5, 6], [.2, .8]) + assert_allclose(mean1, [[5*.2, 5*.8], [6*.2, 6*.8]], rtol=1e-8) + + def test_frozen(self): + # The frozen distribution should agree with the regular one + np.random.seed(1234) + n = 12 + pvals = (.1, .2, .3, .4) + x = [[0,0,0,12],[0,0,1,11],[0,1,1,10],[1,1,1,9],[1,1,2,8]] + x = np.asarray(x, dtype=np.float64) + mn_frozen = multinomial(n, pvals) + assert_allclose(mn_frozen.pmf(x), multinomial.pmf(x, n, pvals)) + assert_allclose(mn_frozen.logpmf(x), multinomial.logpmf(x, n, pvals)) + assert_allclose(mn_frozen.entropy(), multinomial.entropy(n, pvals)) + + def test_gh_11860(self): + # gh-11860 reported cases in which the adjustments made by multinomial + # to the last element of `p` can cause `nan`s even when the input is + # essentially valid. Check that a pathological case returns a finite, + # nonzero result. (This would fail in main before the PR.) + n = 88 + rng = np.random.default_rng(8879715917488330089) + p = rng.random(n) + p[-1] = 1e-30 + p /= np.sum(p) + x = np.ones(n) + logpmf = multinomial.logpmf(x, n, p) + assert np.isfinite(logpmf) + +class TestInvwishart: + def test_frozen(self): + # Test that the frozen and non-frozen inverse Wishart gives the same + # answers + + # Construct an arbitrary positive definite scale matrix + dim = 4 + scale = np.diag(np.arange(dim)+1) + scale[np.tril_indices(dim, k=-1)] = np.arange(dim*(dim-1)/2) + scale = np.dot(scale.T, scale) + + # Construct a collection of positive definite matrices to test the PDF + X = [] + for i in range(5): + x = np.diag(np.arange(dim)+(i+1)**2) + x[np.tril_indices(dim, k=-1)] = np.arange(dim*(dim-1)/2) + x = np.dot(x.T, x) + X.append(x) + X = np.array(X).T + + # Construct a 1D and 2D set of parameters + parameters = [ + (10, 1, np.linspace(0.1, 10, 5)), # 1D case + (10, scale, X) + ] + + for (df, scale, x) in parameters: + iw = invwishart(df, scale) + assert_equal(iw.var(), invwishart.var(df, scale)) + assert_equal(iw.mean(), invwishart.mean(df, scale)) + assert_equal(iw.mode(), invwishart.mode(df, scale)) + assert_allclose(iw.pdf(x), invwishart.pdf(x, df, scale)) + + def test_1D_is_invgamma(self): + # The 1-dimensional inverse Wishart with an identity scale matrix is + # just an inverse gamma distribution. + # Test variance, mean, pdf, entropy + # Kolgomorov-Smirnov test for rvs + np.random.seed(482974) + + sn = 500 + dim = 1 + scale = np.eye(dim) + + df_range = np.arange(5, 20, 2, dtype=float) + X = np.linspace(0.1,10,num=10) + for df in df_range: + iw = invwishart(df, scale) + ig = invgamma(df/2, scale=1./2) + + # Statistics + assert_allclose(iw.var(), ig.var()) + assert_allclose(iw.mean(), ig.mean()) + + # PDF + assert_allclose(iw.pdf(X), ig.pdf(X)) + + # rvs + rvs = iw.rvs(size=sn) + args = (df/2, 0, 1./2) + alpha = 0.01 + check_distribution_rvs('invgamma', args, alpha, rvs) + + # entropy + assert_allclose(iw.entropy(), ig.entropy()) + + def test_invwishart_2D_rvs(self): + dim = 3 + df = 10 + + # Construct a simple non-diagonal positive definite matrix + scale = np.eye(dim) + scale[0,1] = 0.5 + scale[1,0] = 0.5 + + # Construct frozen inverse-Wishart random variables + iw = invwishart(df, scale) + + # Get the generated random variables from a known seed + np.random.seed(608072) + iw_rvs = invwishart.rvs(df, scale) + np.random.seed(608072) + frozen_iw_rvs = iw.rvs() + + # Manually calculate what it should be, based on the decomposition in + # https://arxiv.org/abs/2310.15884 of an invers-Wishart into L L', + # where L A = D, D is the Cholesky factorization of the scale matrix, + # and A is the lower triangular matrix with the square root of chi^2 + # variates on the diagonal and N(0,1) variates in the lower triangle. + # the diagonal chi^2 variates in this A are reversed compared to those + # in the Bartlett decomposition A for Wishart rvs. + np.random.seed(608072) + covariances = np.random.normal(size=3) + variances = np.r_[ + np.random.chisquare(df-2), + np.random.chisquare(df-1), + np.random.chisquare(df), + ]**0.5 + + # Construct the lower-triangular A matrix + A = np.diag(variances) + A[np.tril_indices(dim, k=-1)] = covariances + + # inverse-Wishart random variate + D = np.linalg.cholesky(scale) + L = np.linalg.solve(A.T, D.T).T + manual_iw_rvs = np.dot(L, L.T) + + # Test for equality + assert_allclose(iw_rvs, manual_iw_rvs) + assert_allclose(frozen_iw_rvs, manual_iw_rvs) + + def test_sample_mean(self): + """Test that sample mean consistent with known mean.""" + # Construct an arbitrary positive definite scale matrix + df = 10 + sample_size = 20_000 + for dim in [1, 5]: + scale = np.diag(np.arange(dim) + 1) + scale[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim - 1) / 2) + scale = np.dot(scale.T, scale) + + dist = invwishart(df, scale) + Xmean_exp = dist.mean() + Xvar_exp = dist.var() + Xmean_std = (Xvar_exp / sample_size)**0.5 # asymptotic SE of mean estimate + + X = dist.rvs(size=sample_size, random_state=1234) + Xmean_est = X.mean(axis=0) + + ntests = dim*(dim + 1)//2 + fail_rate = 0.01 / ntests # correct for multiple tests + max_diff = norm.ppf(1 - fail_rate / 2) + assert np.allclose( + (Xmean_est - Xmean_exp) / Xmean_std, + 0, + atol=max_diff, + ) + + def test_logpdf_4x4(self): + """Regression test for gh-8844.""" + X = np.array([[2, 1, 0, 0.5], + [1, 2, 0.5, 0.5], + [0, 0.5, 3, 1], + [0.5, 0.5, 1, 2]]) + Psi = np.array([[9, 7, 3, 1], + [7, 9, 5, 1], + [3, 5, 8, 2], + [1, 1, 2, 9]]) + nu = 6 + prob = invwishart.logpdf(X, nu, Psi) + # Explicit calculation from the formula on wikipedia. + p = X.shape[0] + sig, logdetX = np.linalg.slogdet(X) + sig, logdetPsi = np.linalg.slogdet(Psi) + M = np.linalg.solve(X, Psi) + expected = ((nu/2)*logdetPsi + - (nu*p/2)*np.log(2) + - multigammaln(nu/2, p) + - (nu + p + 1)/2*logdetX + - 0.5*M.trace()) + assert_allclose(prob, expected) + + +class TestSpecialOrthoGroup: + def test_reproducibility(self): + np.random.seed(514) + x = special_ortho_group.rvs(3) + expected = np.array([[-0.99394515, -0.04527879, 0.10011432], + [0.04821555, -0.99846897, 0.02711042], + [0.09873351, 0.03177334, 0.99460653]]) + assert_array_almost_equal(x, expected) + + random_state = np.random.RandomState(seed=514) + x = special_ortho_group.rvs(3, random_state=random_state) + assert_array_almost_equal(x, expected) + + def test_invalid_dim(self): + assert_raises(ValueError, special_ortho_group.rvs, None) + assert_raises(ValueError, special_ortho_group.rvs, (2, 2)) + assert_raises(ValueError, special_ortho_group.rvs, 1) + assert_raises(ValueError, special_ortho_group.rvs, 2.5) + + def test_frozen_matrix(self): + dim = 7 + frozen = special_ortho_group(dim) + + rvs1 = frozen.rvs(random_state=1234) + rvs2 = special_ortho_group.rvs(dim, random_state=1234) + + assert_equal(rvs1, rvs2) + + def test_det_and_ortho(self): + xs = [special_ortho_group.rvs(dim) + for dim in range(2,12) + for i in range(3)] + + # Test that determinants are always +1 + dets = [np.linalg.det(x) for x in xs] + assert_allclose(dets, [1.]*30, rtol=1e-13) + + # Test that these are orthogonal matrices + for x in xs: + assert_array_almost_equal(np.dot(x, x.T), + np.eye(x.shape[0])) + + def test_haar(self): + # Test that the distribution is constant under rotation + # Every column should have the same distribution + # Additionally, the distribution should be invariant under another rotation + + # Generate samples + dim = 5 + samples = 1000 # Not too many, or the test takes too long + ks_prob = .05 + np.random.seed(514) + xs = special_ortho_group.rvs(dim, size=samples) + + # Dot a few rows (0, 1, 2) with unit vectors (0, 2, 4, 3), + # effectively picking off entries in the matrices of xs. + # These projections should all have the same distribution, + # establishing rotational invariance. We use the two-sided + # KS test to confirm this. + # We could instead test that angles between random vectors + # are uniformly distributed, but the below is sufficient. + # It is not feasible to consider all pairs, so pick a few. + els = ((0,0), (0,2), (1,4), (2,3)) + #proj = {(er, ec): [x[er][ec] for x in xs] for er, ec in els} + proj = {(er, ec): sorted([x[er][ec] for x in xs]) for er, ec in els} + pairs = [(e0, e1) for e0 in els for e1 in els if e0 > e1] + ks_tests = [ks_2samp(proj[p0], proj[p1])[1] for (p0, p1) in pairs] + assert_array_less([ks_prob]*len(pairs), ks_tests) + + +class TestOrthoGroup: + def test_reproducibility(self): + seed = 514 + np.random.seed(seed) + x = ortho_group.rvs(3) + x2 = ortho_group.rvs(3, random_state=seed) + # Note this matrix has det -1, distinguishing O(N) from SO(N) + assert_almost_equal(np.linalg.det(x), -1) + expected = np.array([[0.381686, -0.090374, 0.919863], + [0.905794, -0.161537, -0.391718], + [-0.183993, -0.98272, -0.020204]]) + assert_array_almost_equal(x, expected) + assert_array_almost_equal(x2, expected) + + def test_invalid_dim(self): + assert_raises(ValueError, ortho_group.rvs, None) + assert_raises(ValueError, ortho_group.rvs, (2, 2)) + assert_raises(ValueError, ortho_group.rvs, 1) + assert_raises(ValueError, ortho_group.rvs, 2.5) + + def test_frozen_matrix(self): + dim = 7 + frozen = ortho_group(dim) + frozen_seed = ortho_group(dim, seed=1234) + + rvs1 = frozen.rvs(random_state=1234) + rvs2 = ortho_group.rvs(dim, random_state=1234) + rvs3 = frozen_seed.rvs(size=1) + + assert_equal(rvs1, rvs2) + assert_equal(rvs1, rvs3) + + def test_det_and_ortho(self): + xs = [[ortho_group.rvs(dim) + for i in range(10)] + for dim in range(2,12)] + + # Test that abs determinants are always +1 + dets = np.array([[np.linalg.det(x) for x in xx] for xx in xs]) + assert_allclose(np.fabs(dets), np.ones(dets.shape), rtol=1e-13) + + # Test that these are orthogonal matrices + for xx in xs: + for x in xx: + assert_array_almost_equal(np.dot(x, x.T), + np.eye(x.shape[0])) + + @pytest.mark.parametrize("dim", [2, 5, 10, 20]) + def test_det_distribution_gh18272(self, dim): + # Test that positive and negative determinants are equally likely. + rng = np.random.default_rng(6796248956179332344) + dist = ortho_group(dim=dim) + rvs = dist.rvs(size=5000, random_state=rng) + dets = scipy.linalg.det(rvs) + k = np.sum(dets > 0) + n = len(dets) + res = stats.binomtest(k, n) + low, high = res.proportion_ci(confidence_level=0.95) + assert low < 0.5 < high + + def test_haar(self): + # Test that the distribution is constant under rotation + # Every column should have the same distribution + # Additionally, the distribution should be invariant under another rotation + + # Generate samples + dim = 5 + samples = 1000 # Not too many, or the test takes too long + ks_prob = .05 + np.random.seed(518) # Note that the test is sensitive to seed too + xs = ortho_group.rvs(dim, size=samples) + + # Dot a few rows (0, 1, 2) with unit vectors (0, 2, 4, 3), + # effectively picking off entries in the matrices of xs. + # These projections should all have the same distribution, + # establishing rotational invariance. We use the two-sided + # KS test to confirm this. + # We could instead test that angles between random vectors + # are uniformly distributed, but the below is sufficient. + # It is not feasible to consider all pairs, so pick a few. + els = ((0,0), (0,2), (1,4), (2,3)) + #proj = {(er, ec): [x[er][ec] for x in xs] for er, ec in els} + proj = {(er, ec): sorted([x[er][ec] for x in xs]) for er, ec in els} + pairs = [(e0, e1) for e0 in els for e1 in els if e0 > e1] + ks_tests = [ks_2samp(proj[p0], proj[p1])[1] for (p0, p1) in pairs] + assert_array_less([ks_prob]*len(pairs), ks_tests) + + @pytest.mark.slow + def test_pairwise_distances(self): + # Test that the distribution of pairwise distances is close to correct. + np.random.seed(514) + + def random_ortho(dim): + u, _s, v = np.linalg.svd(np.random.normal(size=(dim, dim))) + return np.dot(u, v) + + for dim in range(2, 6): + def generate_test_statistics(rvs, N=1000, eps=1e-10): + stats = np.array([ + np.sum((rvs(dim=dim) - rvs(dim=dim))**2) + for _ in range(N) + ]) + # Add a bit of noise to account for numeric accuracy. + stats += np.random.uniform(-eps, eps, size=stats.shape) + return stats + + expected = generate_test_statistics(random_ortho) + actual = generate_test_statistics(scipy.stats.ortho_group.rvs) + + _D, p = scipy.stats.ks_2samp(expected, actual) + + assert_array_less(.05, p) + + +class TestRandomCorrelation: + def test_reproducibility(self): + np.random.seed(514) + eigs = (.5, .8, 1.2, 1.5) + x = random_correlation.rvs(eigs) + x2 = random_correlation.rvs(eigs, random_state=514) + expected = np.array([[1., -0.184851, 0.109017, -0.227494], + [-0.184851, 1., 0.231236, 0.326669], + [0.109017, 0.231236, 1., -0.178912], + [-0.227494, 0.326669, -0.178912, 1.]]) + assert_array_almost_equal(x, expected) + assert_array_almost_equal(x2, expected) + + def test_invalid_eigs(self): + assert_raises(ValueError, random_correlation.rvs, None) + assert_raises(ValueError, random_correlation.rvs, 'test') + assert_raises(ValueError, random_correlation.rvs, 2.5) + assert_raises(ValueError, random_correlation.rvs, [2.5]) + assert_raises(ValueError, random_correlation.rvs, [[1,2],[3,4]]) + assert_raises(ValueError, random_correlation.rvs, [2.5, -.5]) + assert_raises(ValueError, random_correlation.rvs, [1, 2, .1]) + + def test_frozen_matrix(self): + eigs = (.5, .8, 1.2, 1.5) + frozen = random_correlation(eigs) + frozen_seed = random_correlation(eigs, seed=514) + + rvs1 = random_correlation.rvs(eigs, random_state=514) + rvs2 = frozen.rvs(random_state=514) + rvs3 = frozen_seed.rvs() + + assert_equal(rvs1, rvs2) + assert_equal(rvs1, rvs3) + + def test_definition(self): + # Test the definition of a correlation matrix in several dimensions: + # + # 1. Det is product of eigenvalues (and positive by construction + # in examples) + # 2. 1's on diagonal + # 3. Matrix is symmetric + + def norm(i, e): + return i*e/sum(e) + + np.random.seed(123) + + eigs = [norm(i, np.random.uniform(size=i)) for i in range(2, 6)] + eigs.append([4,0,0,0]) + + ones = [[1.]*len(e) for e in eigs] + xs = [random_correlation.rvs(e) for e in eigs] + + # Test that determinants are products of eigenvalues + # These are positive by construction + # Could also test that the eigenvalues themselves are correct, + # but this seems sufficient. + dets = [np.fabs(np.linalg.det(x)) for x in xs] + dets_known = [np.prod(e) for e in eigs] + assert_allclose(dets, dets_known, rtol=1e-13, atol=1e-13) + + # Test for 1's on the diagonal + diags = [np.diag(x) for x in xs] + for a, b in zip(diags, ones): + assert_allclose(a, b, rtol=1e-13) + + # Correlation matrices are symmetric + for x in xs: + assert_allclose(x, x.T, rtol=1e-13) + + def test_to_corr(self): + # Check some corner cases in to_corr + + # ajj == 1 + m = np.array([[0.1, 0], [0, 1]], dtype=float) + m = random_correlation._to_corr(m) + assert_allclose(m, np.array([[1, 0], [0, 0.1]])) + + # Floating point overflow; fails to compute the correct + # rotation, but should still produce some valid rotation + # rather than infs/nans + with np.errstate(over='ignore'): + g = np.array([[0, 1], [-1, 0]]) + + m0 = np.array([[1e300, 0], [0, np.nextafter(1, 0)]], dtype=float) + m = random_correlation._to_corr(m0.copy()) + assert_allclose(m, g.T.dot(m0).dot(g)) + + m0 = np.array([[0.9, 1e300], [1e300, 1.1]], dtype=float) + m = random_correlation._to_corr(m0.copy()) + assert_allclose(m, g.T.dot(m0).dot(g)) + + # Zero discriminant; should set the first diag entry to 1 + m0 = np.array([[2, 1], [1, 2]], dtype=float) + m = random_correlation._to_corr(m0.copy()) + assert_allclose(m[0,0], 1) + + # Slightly negative discriminant; should be approx correct still + m0 = np.array([[2 + 1e-7, 1], [1, 2]], dtype=float) + m = random_correlation._to_corr(m0.copy()) + assert_allclose(m[0,0], 1) + + +class TestUniformDirection: + @pytest.mark.parametrize("dim", [1, 3]) + @pytest.mark.parametrize("size", [None, 1, 5, (5, 4)]) + def test_samples(self, dim, size): + # test that samples have correct shape and norm 1 + rng = np.random.default_rng(2777937887058094419) + uniform_direction_dist = uniform_direction(dim, seed=rng) + samples = uniform_direction_dist.rvs(size) + mean, cov = np.zeros(dim), np.eye(dim) + expected_shape = rng.multivariate_normal(mean, cov, size=size).shape + assert samples.shape == expected_shape + norms = np.linalg.norm(samples, axis=-1) + assert_allclose(norms, 1.) + + @pytest.mark.parametrize("dim", [None, 0, (2, 2), 2.5]) + def test_invalid_dim(self, dim): + message = ("Dimension of vector must be specified, " + "and must be an integer greater than 0.") + with pytest.raises(ValueError, match=message): + uniform_direction.rvs(dim) + + def test_frozen_distribution(self): + dim = 5 + frozen = uniform_direction(dim) + frozen_seed = uniform_direction(dim, seed=514) + + rvs1 = frozen.rvs(random_state=514) + rvs2 = uniform_direction.rvs(dim, random_state=514) + rvs3 = frozen_seed.rvs() + + assert_equal(rvs1, rvs2) + assert_equal(rvs1, rvs3) + + @pytest.mark.parametrize("dim", [2, 5, 8]) + def test_uniform(self, dim): + rng = np.random.default_rng(1036978481269651776) + spherical_dist = uniform_direction(dim, seed=rng) + # generate random, orthogonal vectors + v1, v2 = spherical_dist.rvs(size=2) + v2 -= v1 @ v2 * v1 + v2 /= np.linalg.norm(v2) + assert_allclose(v1 @ v2, 0, atol=1e-14) # orthogonal + # generate data and project onto orthogonal vectors + samples = spherical_dist.rvs(size=10000) + s1 = samples @ v1 + s2 = samples @ v2 + angles = np.arctan2(s1, s2) + # test that angles follow a uniform distribution + # normalize angles to range [0, 1] + angles += np.pi + angles /= 2*np.pi + # perform KS test + uniform_dist = uniform() + kstest_result = kstest(angles, uniform_dist.cdf) + assert kstest_result.pvalue > 0.05 + + +class TestUnitaryGroup: + def test_reproducibility(self): + np.random.seed(514) + x = unitary_group.rvs(3) + x2 = unitary_group.rvs(3, random_state=514) + + expected = np.array( + [[0.308771+0.360312j, 0.044021+0.622082j, 0.160327+0.600173j], + [0.732757+0.297107j, 0.076692-0.4614j, -0.394349+0.022613j], + [-0.148844+0.357037j, -0.284602-0.557949j, 0.607051+0.299257j]] + ) + + assert_array_almost_equal(x, expected) + assert_array_almost_equal(x2, expected) + + def test_invalid_dim(self): + assert_raises(ValueError, unitary_group.rvs, None) + assert_raises(ValueError, unitary_group.rvs, (2, 2)) + assert_raises(ValueError, unitary_group.rvs, 1) + assert_raises(ValueError, unitary_group.rvs, 2.5) + + def test_frozen_matrix(self): + dim = 7 + frozen = unitary_group(dim) + frozen_seed = unitary_group(dim, seed=514) + + rvs1 = frozen.rvs(random_state=514) + rvs2 = unitary_group.rvs(dim, random_state=514) + rvs3 = frozen_seed.rvs(size=1) + + assert_equal(rvs1, rvs2) + assert_equal(rvs1, rvs3) + + def test_unitarity(self): + xs = [unitary_group.rvs(dim) + for dim in range(2,12) + for i in range(3)] + + # Test that these are unitary matrices + for x in xs: + assert_allclose(np.dot(x, x.conj().T), np.eye(x.shape[0]), atol=1e-15) + + def test_haar(self): + # Test that the eigenvalues, which lie on the unit circle in + # the complex plane, are uncorrelated. + + # Generate samples + dim = 5 + samples = 1000 # Not too many, or the test takes too long + np.random.seed(514) # Note that the test is sensitive to seed too + xs = unitary_group.rvs(dim, size=samples) + + # The angles "x" of the eigenvalues should be uniformly distributed + # Overall this seems to be a necessary but weak test of the distribution. + eigs = np.vstack([scipy.linalg.eigvals(x) for x in xs]) + x = np.arctan2(eigs.imag, eigs.real) + res = kstest(x.ravel(), uniform(-np.pi, 2*np.pi).cdf) + assert_(res.pvalue > 0.05) + + +class TestMultivariateT: + + # These tests were created by running vpa(mvtpdf(...)) in MATLAB. The + # function takes no `mu` parameter. The tests were run as + # + # >> ans = vpa(mvtpdf(x - mu, shape, df)); + # + PDF_TESTS = [( + # x + [ + [1, 2], + [4, 1], + [2, 1], + [2, 4], + [1, 4], + [4, 1], + [3, 2], + [3, 3], + [4, 4], + [5, 1], + ], + # loc + [0, 0], + # shape + [ + [1, 0], + [0, 1] + ], + # df + 4, + # ans + [ + 0.013972450422333741737457302178882, + 0.0010998721906793330026219646100571, + 0.013972450422333741737457302178882, + 0.00073682844024025606101402363634634, + 0.0010998721906793330026219646100571, + 0.0010998721906793330026219646100571, + 0.0020732579600816823488240725481546, + 0.00095660371505271429414668515889275, + 0.00021831953784896498569831346792114, + 0.00037725616140301147447000396084604 + ] + + ), ( + # x + [ + [0.9718, 0.1298, 0.8134], + [0.4922, 0.5522, 0.7185], + [0.3010, 0.1491, 0.5008], + [0.5971, 0.2585, 0.8940], + [0.5434, 0.5287, 0.9507], + ], + # loc + [-1, 1, 50], + # shape + [ + [1.0000, 0.5000, 0.2500], + [0.5000, 1.0000, -0.1000], + [0.2500, -0.1000, 1.0000], + ], + # df + 8, + # ans + [ + 0.00000000000000069609279697467772867405511133763, + 0.00000000000000073700739052207366474839369535934, + 0.00000000000000069522909962669171512174435447027, + 0.00000000000000074212293557998314091880208889767, + 0.00000000000000077039675154022118593323030449058, + ] + )] + + @pytest.mark.parametrize("x, loc, shape, df, ans", PDF_TESTS) + def test_pdf_correctness(self, x, loc, shape, df, ans): + dist = multivariate_t(loc, shape, df, seed=0) + val = dist.pdf(x) + assert_array_almost_equal(val, ans) + + @pytest.mark.parametrize("x, loc, shape, df, ans", PDF_TESTS) + def test_logpdf_correct(self, x, loc, shape, df, ans): + dist = multivariate_t(loc, shape, df, seed=0) + val1 = dist.pdf(x) + val2 = dist.logpdf(x) + assert_array_almost_equal(np.log(val1), val2) + + # https://github.com/scipy/scipy/issues/10042#issuecomment-576795195 + def test_mvt_with_df_one_is_cauchy(self): + x = [9, 7, 4, 1, -3, 9, 0, -3, -1, 3] + val = multivariate_t.pdf(x, df=1) + ans = cauchy.pdf(x) + assert_array_almost_equal(val, ans) + + def test_mvt_with_high_df_is_approx_normal(self): + # `normaltest` returns the chi-squared statistic and the associated + # p-value. The null hypothesis is that `x` came from a normal + # distribution, so a low p-value represents rejecting the null, i.e. + # that it is unlikely that `x` came a normal distribution. + P_VAL_MIN = 0.1 + + dist = multivariate_t(0, 1, df=100000, seed=1) + samples = dist.rvs(size=100000) + _, p = normaltest(samples) + assert (p > P_VAL_MIN) + + dist = multivariate_t([-2, 3], [[10, -1], [-1, 10]], df=100000, + seed=42) + samples = dist.rvs(size=100000) + _, p = normaltest(samples) + assert ((p > P_VAL_MIN).all()) + + @patch('scipy.stats.multivariate_normal._logpdf') + def test_mvt_with_inf_df_calls_normal(self, mock): + dist = multivariate_t(0, 1, df=np.inf, seed=7) + assert isinstance(dist, multivariate_normal_frozen) + multivariate_t.pdf(0, df=np.inf) + assert mock.call_count == 1 + multivariate_t.logpdf(0, df=np.inf) + assert mock.call_count == 2 + + def test_shape_correctness(self): + # pdf and logpdf should return scalar when the + # number of samples in x is one. + dim = 4 + loc = np.zeros(dim) + shape = np.eye(dim) + df = 4.5 + x = np.zeros(dim) + res = multivariate_t(loc, shape, df).pdf(x) + assert np.isscalar(res) + res = multivariate_t(loc, shape, df).logpdf(x) + assert np.isscalar(res) + + # pdf() and logpdf() should return probabilities of shape + # (n_samples,) when x has n_samples. + n_samples = 7 + x = np.random.random((n_samples, dim)) + res = multivariate_t(loc, shape, df).pdf(x) + assert (res.shape == (n_samples,)) + res = multivariate_t(loc, shape, df).logpdf(x) + assert (res.shape == (n_samples,)) + + # rvs() should return scalar unless a size argument is applied. + res = multivariate_t(np.zeros(1), np.eye(1), 1).rvs() + assert np.isscalar(res) + + # rvs() should return vector of shape (size,) if size argument + # is applied. + size = 7 + res = multivariate_t(np.zeros(1), np.eye(1), 1).rvs(size=size) + assert (res.shape == (size,)) + + def test_default_arguments(self): + dist = multivariate_t() + assert_equal(dist.loc, [0]) + assert_equal(dist.shape, [[1]]) + assert (dist.df == 1) + + DEFAULT_ARGS_TESTS = [ + (None, None, None, 0, 1, 1), + (None, None, 7, 0, 1, 7), + (None, [[7, 0], [0, 7]], None, [0, 0], [[7, 0], [0, 7]], 1), + (None, [[7, 0], [0, 7]], 7, [0, 0], [[7, 0], [0, 7]], 7), + ([7, 7], None, None, [7, 7], [[1, 0], [0, 1]], 1), + ([7, 7], None, 7, [7, 7], [[1, 0], [0, 1]], 7), + ([7, 7], [[7, 0], [0, 7]], None, [7, 7], [[7, 0], [0, 7]], 1), + ([7, 7], [[7, 0], [0, 7]], 7, [7, 7], [[7, 0], [0, 7]], 7) + ] + + @pytest.mark.parametrize("loc, shape, df, loc_ans, shape_ans, df_ans", + DEFAULT_ARGS_TESTS) + def test_default_args(self, loc, shape, df, loc_ans, shape_ans, df_ans): + dist = multivariate_t(loc=loc, shape=shape, df=df) + assert_equal(dist.loc, loc_ans) + assert_equal(dist.shape, shape_ans) + assert (dist.df == df_ans) + + ARGS_SHAPES_TESTS = [ + (-1, 2, 3, [-1], [[2]], 3), + ([-1], [2], 3, [-1], [[2]], 3), + (np.array([-1]), np.array([2]), 3, [-1], [[2]], 3) + ] + + @pytest.mark.parametrize("loc, shape, df, loc_ans, shape_ans, df_ans", + ARGS_SHAPES_TESTS) + def test_scalar_list_and_ndarray_arguments(self, loc, shape, df, loc_ans, + shape_ans, df_ans): + dist = multivariate_t(loc, shape, df) + assert_equal(dist.loc, loc_ans) + assert_equal(dist.shape, shape_ans) + assert_equal(dist.df, df_ans) + + def test_argument_error_handling(self): + # `loc` should be a one-dimensional vector. + loc = [[1, 1]] + assert_raises(ValueError, + multivariate_t, + **dict(loc=loc)) + + # `shape` should be scalar or square matrix. + shape = [[1, 1], [2, 2], [3, 3]] + assert_raises(ValueError, + multivariate_t, + **dict(loc=loc, shape=shape)) + + # `df` should be greater than zero. + loc = np.zeros(2) + shape = np.eye(2) + df = -1 + assert_raises(ValueError, + multivariate_t, + **dict(loc=loc, shape=shape, df=df)) + df = 0 + assert_raises(ValueError, + multivariate_t, + **dict(loc=loc, shape=shape, df=df)) + + def test_reproducibility(self): + rng = np.random.RandomState(4) + loc = rng.uniform(size=3) + shape = np.eye(3) + dist1 = multivariate_t(loc, shape, df=3, seed=2) + dist2 = multivariate_t(loc, shape, df=3, seed=2) + samples1 = dist1.rvs(size=10) + samples2 = dist2.rvs(size=10) + assert_equal(samples1, samples2) + + def test_allow_singular(self): + # Make shape singular and verify error was raised. + args = dict(loc=[0,0], shape=[[0,0],[0,1]], df=1, allow_singular=False) + assert_raises(np.linalg.LinAlgError, multivariate_t, **args) + + @pytest.mark.parametrize("size", [(10, 3), (5, 6, 4, 3)]) + @pytest.mark.parametrize("dim", [2, 3, 4, 5]) + @pytest.mark.parametrize("df", [1., 2., np.inf]) + def test_rvs(self, size, dim, df): + dist = multivariate_t(np.zeros(dim), np.eye(dim), df) + rvs = dist.rvs(size=size) + assert rvs.shape == size + (dim, ) + + def test_cdf_signs(self): + # check that sign of output is correct when np.any(lower > x) + mean = np.zeros(3) + cov = np.eye(3) + df = 10 + b = [[1, 1, 1], [0, 0, 0], [1, 0, 1], [0, 1, 0]] + a = [[0, 0, 0], [1, 1, 1], [0, 1, 0], [1, 0, 1]] + # when odd number of elements of b < a, output is negative + expected_signs = np.array([1, -1, -1, 1]) + cdf = multivariate_normal.cdf(b, mean, cov, df, lower_limit=a) + assert_allclose(cdf, cdf[0]*expected_signs) + + @pytest.mark.parametrize('dim', [1, 2, 5]) + def test_cdf_against_multivariate_normal(self, dim): + # Check accuracy against MVN randomly-generated cases + self.cdf_against_mvn_test(dim) + + @pytest.mark.parametrize('dim', [3, 6, 9]) + def test_cdf_against_multivariate_normal_singular(self, dim): + # Check accuracy against MVN for randomly-generated singular cases + self.cdf_against_mvn_test(3, True) + + def cdf_against_mvn_test(self, dim, singular=False): + # Check for accuracy in the limit that df -> oo and MVT -> MVN + rng = np.random.default_rng(413722918996573) + n = 3 + + w = 10**rng.uniform(-2, 1, size=dim) + cov = _random_covariance(dim, w, rng, singular) + + mean = 10**rng.uniform(-1, 2, size=dim) * np.sign(rng.normal(size=dim)) + a = -10**rng.uniform(-1, 2, size=(n, dim)) + mean + b = 10**rng.uniform(-1, 2, size=(n, dim)) + mean + + res = stats.multivariate_t.cdf(b, mean, cov, df=10000, lower_limit=a, + allow_singular=True, random_state=rng) + ref = stats.multivariate_normal.cdf(b, mean, cov, allow_singular=True, + lower_limit=a) + assert_allclose(res, ref, atol=5e-4) + + def test_cdf_against_univariate_t(self): + rng = np.random.default_rng(413722918996573) + cov = 2 + mean = 0 + x = rng.normal(size=10, scale=np.sqrt(cov)) + df = 3 + + res = stats.multivariate_t.cdf(x, mean, cov, df, lower_limit=-np.inf, + random_state=rng) + ref = stats.t.cdf(x, df, mean, np.sqrt(cov)) + incorrect = stats.norm.cdf(x, mean, np.sqrt(cov)) + + assert_allclose(res, ref, atol=5e-4) # close to t + assert np.all(np.abs(res - incorrect) > 1e-3) # not close to normal + + @pytest.mark.parametrize("dim", [2, 3, 5, 10]) + @pytest.mark.parametrize("seed", [3363958638, 7891119608, 3887698049, + 5013150848, 1495033423, 6170824608]) + @pytest.mark.parametrize("singular", [False, True]) + def test_cdf_against_qsimvtv(self, dim, seed, singular): + if singular and seed != 3363958638: + pytest.skip('Agreement with qsimvtv is not great in singular case') + rng = np.random.default_rng(seed) + w = 10**rng.uniform(-2, 2, size=dim) + cov = _random_covariance(dim, w, rng, singular) + mean = rng.random(dim) + a = -rng.random(dim) + b = rng.random(dim) + df = rng.random() * 5 + + # no lower limit + res = stats.multivariate_t.cdf(b, mean, cov, df, random_state=rng, + allow_singular=True) + with np.errstate(invalid='ignore'): + ref = _qsimvtv(20000, df, cov, np.inf*a, b - mean, rng)[0] + assert_allclose(res, ref, atol=2e-4, rtol=1e-3) + + # with lower limit + res = stats.multivariate_t.cdf(b, mean, cov, df, lower_limit=a, + random_state=rng, allow_singular=True) + with np.errstate(invalid='ignore'): + ref = _qsimvtv(20000, df, cov, a - mean, b - mean, rng)[0] + assert_allclose(res, ref, atol=1e-4, rtol=1e-3) + + @pytest.mark.slow + def test_cdf_against_generic_integrators(self): + # Compare result against generic numerical integrators + dim = 3 + rng = np.random.default_rng(41372291899657) + w = 10 ** rng.uniform(-1, 1, size=dim) + cov = _random_covariance(dim, w, rng, singular=True) + mean = rng.random(dim) + a = -rng.random(dim) + b = rng.random(dim) + df = rng.random() * 5 + + res = stats.multivariate_t.cdf(b, mean, cov, df, random_state=rng, + lower_limit=a) + + def integrand(x): + return stats.multivariate_t.pdf(x.T, mean, cov, df) + + ref = qmc_quad(integrand, a, b, qrng=stats.qmc.Halton(d=dim, seed=rng)) + assert_allclose(res, ref.integral, rtol=1e-3) + + def integrand(*zyx): + return stats.multivariate_t.pdf(zyx[::-1], mean, cov, df) + + ref = tplquad(integrand, a[0], b[0], a[1], b[1], a[2], b[2]) + assert_allclose(res, ref[0], rtol=1e-3) + + def test_against_matlab(self): + # Test against matlab mvtcdf: + # C = [6.21786909 0.2333667 7.95506077; + # 0.2333667 29.67390923 16.53946426; + # 7.95506077 16.53946426 19.17725252] + # df = 1.9559939787727658 + # mvtcdf([0, 0, 0], C, df) % 0.2523 + rng = np.random.default_rng(2967390923) + cov = np.array([[ 6.21786909, 0.2333667 , 7.95506077], + [ 0.2333667 , 29.67390923, 16.53946426], + [ 7.95506077, 16.53946426, 19.17725252]]) + df = 1.9559939787727658 + dist = stats.multivariate_t(shape=cov, df=df) + res = dist.cdf([0, 0, 0], random_state=rng) + ref = 0.2523 + assert_allclose(res, ref, rtol=1e-3) + + def test_frozen(self): + seed = 4137229573 + rng = np.random.default_rng(seed) + loc = rng.uniform(size=3) + x = rng.uniform(size=3) + loc + shape = np.eye(3) + df = rng.random() + args = (loc, shape, df) + + rng_frozen = np.random.default_rng(seed) + rng_unfrozen = np.random.default_rng(seed) + dist = stats.multivariate_t(*args, seed=rng_frozen) + assert_equal(dist.cdf(x), + multivariate_t.cdf(x, *args, random_state=rng_unfrozen)) + + def test_vectorized(self): + dim = 4 + n = (2, 3) + rng = np.random.default_rng(413722918996573) + A = rng.random(size=(dim, dim)) + cov = A @ A.T + mean = rng.random(dim) + x = rng.random(n + (dim,)) + df = rng.random() * 5 + + res = stats.multivariate_t.cdf(x, mean, cov, df, random_state=rng) + + def _cdf_1d(x): + return _qsimvtv(10000, df, cov, -np.inf*x, x-mean, rng)[0] + + ref = np.apply_along_axis(_cdf_1d, -1, x) + assert_allclose(res, ref, atol=1e-4, rtol=1e-3) + + @pytest.mark.parametrize("dim", (3, 7)) + def test_against_analytical(self, dim): + rng = np.random.default_rng(413722918996573) + A = scipy.linalg.toeplitz(c=[1] + [0.5] * (dim - 1)) + res = stats.multivariate_t(shape=A).cdf([0] * dim, random_state=rng) + ref = 1 / (dim + 1) + assert_allclose(res, ref, rtol=5e-5) + + def test_entropy_inf_df(self): + cov = np.eye(3, 3) + df = np.inf + mvt_entropy = stats.multivariate_t.entropy(shape=cov, df=df) + mvn_entropy = stats.multivariate_normal.entropy(None, cov) + assert mvt_entropy == mvn_entropy + + @pytest.mark.parametrize("df", [1, 10, 100]) + def test_entropy_1d(self, df): + mvt_entropy = stats.multivariate_t.entropy(shape=1., df=df) + t_entropy = stats.t.entropy(df=df) + assert_allclose(mvt_entropy, t_entropy, rtol=1e-13) + + # entropy reference values were computed via numerical integration + # + # def integrand(x, y, mvt): + # vec = np.array([x, y]) + # return mvt.logpdf(vec) * mvt.pdf(vec) + + # def multivariate_t_entropy_quad_2d(df, cov): + # dim = cov.shape[0] + # loc = np.zeros((dim, )) + # mvt = stats.multivariate_t(loc, cov, df) + # limit = 100 + # return -integrate.dblquad(integrand, -limit, limit, -limit, limit, + # args=(mvt, ))[0] + + @pytest.mark.parametrize("df, cov, ref, tol", + [(10, np.eye(2, 2), 3.0378770664093313, 1e-14), + (100, np.array([[0.5, 1], [1, 10]]), + 3.55102424550609, 1e-8)]) + def test_entropy_vs_numerical_integration(self, df, cov, ref, tol): + loc = np.zeros((2, )) + mvt = stats.multivariate_t(loc, cov, df) + assert_allclose(mvt.entropy(), ref, rtol=tol) + + @pytest.mark.parametrize( + "df, dim, ref, tol", + [ + (10, 1, 1.5212624929756808, 1e-15), + (100, 1, 1.4289633653182439, 1e-13), + (500, 1, 1.420939531869349, 1e-14), + (1e20, 1, 1.4189385332046727, 1e-15), + (1e100, 1, 1.4189385332046727, 1e-15), + (10, 10, 15.069150450832911, 1e-15), + (1000, 10, 14.19936546446673, 1e-13), + (1e20, 10, 14.189385332046728, 1e-15), + (1e100, 10, 14.189385332046728, 1e-15), + (10, 100, 148.28902883192654, 1e-15), + (1000, 100, 141.99155538003762, 1e-14), + (1e20, 100, 141.8938533204673, 1e-15), + (1e100, 100, 141.8938533204673, 1e-15), + ] + ) + def test_extreme_entropy(self, df, dim, ref, tol): + # Reference values were calculated with mpmath: + # from mpmath import mp + # mp.dps = 500 + # + # def mul_t_mpmath_entropy(dim, df=1): + # dim = mp.mpf(dim) + # df = mp.mpf(df) + # halfsum = (dim + df)/2 + # half_df = df/2 + # + # return float( + # -mp.loggamma(halfsum) + mp.loggamma(half_df) + # + dim / 2 * mp.log(df * mp.pi) + # + halfsum * (mp.digamma(halfsum) - mp.digamma(half_df)) + # + 0.0 + # ) + mvt = stats.multivariate_t(shape=np.eye(dim), df=df) + assert_allclose(mvt.entropy(), ref, rtol=tol) + + def test_entropy_with_covariance(self): + # Generated using np.randn(5, 5) and then rounding + # to two decimal places + _A = np.array([ + [1.42, 0.09, -0.49, 0.17, 0.74], + [-1.13, -0.01, 0.71, 0.4, -0.56], + [1.07, 0.44, -0.28, -0.44, 0.29], + [-1.5, -0.94, -0.67, 0.73, -1.1], + [0.17, -0.08, 1.46, -0.32, 1.36] + ]) + # Set cov to be a symmetric positive semi-definite matrix + cov = _A @ _A.T + + # Test the asymptotic case. For large degrees of freedom + # the entropy approaches the multivariate normal entropy. + df = 1e20 + mul_t_entropy = stats.multivariate_t.entropy(shape=cov, df=df) + mul_norm_entropy = multivariate_normal(None, cov=cov).entropy() + assert_allclose(mul_t_entropy, mul_norm_entropy, rtol=1e-15) + + # Test the regular case. For a dim of 5 the threshold comes out + # to be approximately 766.45. So using slightly + # different dfs on each site of the threshold, the entropies + # are being compared. + df1 = 765 + df2 = 768 + _entropy1 = stats.multivariate_t.entropy(shape=cov, df=df1) + _entropy2 = stats.multivariate_t.entropy(shape=cov, df=df2) + assert_allclose(_entropy1, _entropy2, rtol=1e-5) + + +class TestMultivariateHypergeom: + @pytest.mark.parametrize( + "x, m, n, expected", + [ + # Ground truth value from R dmvhyper + ([3, 4], [5, 10], 7, -1.119814), + # test for `n=0` + ([3, 4], [5, 10], 0, -np.inf), + # test for `x < 0` + ([-3, 4], [5, 10], 7, -np.inf), + # test for `m < 0` (RuntimeWarning issue) + ([3, 4], [-5, 10], 7, np.nan), + # test for all `m < 0` and `x.sum() != n` + ([[1, 2], [3, 4]], [[-4, -6], [-5, -10]], + [3, 7], [np.nan, np.nan]), + # test for `x < 0` and `m < 0` (RuntimeWarning issue) + ([-3, 4], [-5, 10], 1, np.nan), + # test for `x > m` + ([1, 11], [10, 1], 12, np.nan), + # test for `m < 0` (RuntimeWarning issue) + ([1, 11], [10, -1], 12, np.nan), + # test for `n < 0` + ([3, 4], [5, 10], -7, np.nan), + # test for `x.sum() != n` + ([3, 3], [5, 10], 7, -np.inf) + ] + ) + def test_logpmf(self, x, m, n, expected): + vals = multivariate_hypergeom.logpmf(x, m, n) + assert_allclose(vals, expected, rtol=1e-6) + + def test_reduces_hypergeom(self): + # test that the multivariate_hypergeom pmf reduces to the + # hypergeom pmf in the 2d case. + val1 = multivariate_hypergeom.pmf(x=[3, 1], m=[10, 5], n=4) + val2 = hypergeom.pmf(k=3, M=15, n=4, N=10) + assert_allclose(val1, val2, rtol=1e-8) + + val1 = multivariate_hypergeom.pmf(x=[7, 3], m=[15, 10], n=10) + val2 = hypergeom.pmf(k=7, M=25, n=10, N=15) + assert_allclose(val1, val2, rtol=1e-8) + + def test_rvs(self): + # test if `rvs` is unbiased and large sample size converges + # to the true mean. + rv = multivariate_hypergeom(m=[3, 5], n=4) + rvs = rv.rvs(size=1000, random_state=123) + assert_allclose(rvs.mean(0), rv.mean(), rtol=1e-2) + + def test_rvs_broadcasting(self): + rv = multivariate_hypergeom(m=[[3, 5], [5, 10]], n=[4, 9]) + rvs = rv.rvs(size=(1000, 2), random_state=123) + assert_allclose(rvs.mean(0), rv.mean(), rtol=1e-2) + + @pytest.mark.parametrize('m, n', ( + ([0, 0, 20, 0, 0], 5), ([0, 0, 0, 0, 0], 0), + ([0, 0], 0), ([0], 0) + )) + def test_rvs_gh16171(self, m, n): + res = multivariate_hypergeom.rvs(m, n) + m = np.asarray(m) + res_ex = m.copy() + res_ex[m != 0] = n + assert_equal(res, res_ex) + + @pytest.mark.parametrize( + "x, m, n, expected", + [ + ([5], [5], 5, 1), + ([3, 4], [5, 10], 7, 0.3263403), + # Ground truth value from R dmvhyper + ([[[3, 5], [0, 8]], [[-1, 9], [1, 1]]], + [5, 10], [[8, 8], [8, 2]], + [[0.3916084, 0.006993007], [0, 0.4761905]]), + # test with empty arrays. + (np.array([], dtype=int), np.array([], dtype=int), 0, []), + ([1, 2], [4, 5], 5, 0), + # Ground truth value from R dmvhyper + ([3, 3, 0], [5, 6, 7], 6, 0.01077354) + ] + ) + def test_pmf(self, x, m, n, expected): + vals = multivariate_hypergeom.pmf(x, m, n) + assert_allclose(vals, expected, rtol=1e-7) + + @pytest.mark.parametrize( + "x, m, n, expected", + [ + ([3, 4], [[5, 10], [10, 15]], 7, [0.3263403, 0.3407531]), + ([[1], [2]], [[3], [4]], [1, 3], [1., 0.]), + ([[[1], [2]]], [[3], [4]], [1, 3], [[1., 0.]]), + ([[1], [2]], [[[[3]]]], [1, 3], [[[1., 0.]]]) + ] + ) + def test_pmf_broadcasting(self, x, m, n, expected): + vals = multivariate_hypergeom.pmf(x, m, n) + assert_allclose(vals, expected, rtol=1e-7) + + def test_cov(self): + cov1 = multivariate_hypergeom.cov(m=[3, 7, 10], n=12) + cov2 = [[0.64421053, -0.26526316, -0.37894737], + [-0.26526316, 1.14947368, -0.88421053], + [-0.37894737, -0.88421053, 1.26315789]] + assert_allclose(cov1, cov2, rtol=1e-8) + + def test_cov_broadcasting(self): + cov1 = multivariate_hypergeom.cov(m=[[7, 9], [10, 15]], n=[8, 12]) + cov2 = [[[1.05, -1.05], [-1.05, 1.05]], + [[1.56, -1.56], [-1.56, 1.56]]] + assert_allclose(cov1, cov2, rtol=1e-8) + + cov3 = multivariate_hypergeom.cov(m=[[4], [5]], n=[4, 5]) + cov4 = [[[0.]], [[0.]]] + assert_allclose(cov3, cov4, rtol=1e-8) + + cov5 = multivariate_hypergeom.cov(m=[7, 9], n=[8, 12]) + cov6 = [[[1.05, -1.05], [-1.05, 1.05]], + [[0.7875, -0.7875], [-0.7875, 0.7875]]] + assert_allclose(cov5, cov6, rtol=1e-8) + + def test_var(self): + # test with hypergeom + var0 = multivariate_hypergeom.var(m=[10, 5], n=4) + var1 = hypergeom.var(M=15, n=4, N=10) + assert_allclose(var0, var1, rtol=1e-8) + + def test_var_broadcasting(self): + var0 = multivariate_hypergeom.var(m=[10, 5], n=[4, 8]) + var1 = multivariate_hypergeom.var(m=[10, 5], n=4) + var2 = multivariate_hypergeom.var(m=[10, 5], n=8) + assert_allclose(var0[0], var1, rtol=1e-8) + assert_allclose(var0[1], var2, rtol=1e-8) + + var3 = multivariate_hypergeom.var(m=[[10, 5], [10, 14]], n=[4, 8]) + var4 = [[0.6984127, 0.6984127], [1.352657, 1.352657]] + assert_allclose(var3, var4, rtol=1e-8) + + var5 = multivariate_hypergeom.var(m=[[5], [10]], n=[5, 10]) + var6 = [[0.], [0.]] + assert_allclose(var5, var6, rtol=1e-8) + + def test_mean(self): + # test with hypergeom + mean0 = multivariate_hypergeom.mean(m=[10, 5], n=4) + mean1 = hypergeom.mean(M=15, n=4, N=10) + assert_allclose(mean0[0], mean1, rtol=1e-8) + + mean2 = multivariate_hypergeom.mean(m=[12, 8], n=10) + mean3 = [12.*10./20., 8.*10./20.] + assert_allclose(mean2, mean3, rtol=1e-8) + + def test_mean_broadcasting(self): + mean0 = multivariate_hypergeom.mean(m=[[3, 5], [10, 5]], n=[4, 8]) + mean1 = [[3.*4./8., 5.*4./8.], [10.*8./15., 5.*8./15.]] + assert_allclose(mean0, mean1, rtol=1e-8) + + def test_mean_edge_cases(self): + mean0 = multivariate_hypergeom.mean(m=[0, 0, 0], n=0) + assert_equal(mean0, [0., 0., 0.]) + + mean1 = multivariate_hypergeom.mean(m=[1, 0, 0], n=2) + assert_equal(mean1, [np.nan, np.nan, np.nan]) + + mean2 = multivariate_hypergeom.mean(m=[[1, 0, 0], [1, 0, 1]], n=2) + assert_allclose(mean2, [[np.nan, np.nan, np.nan], [1., 0., 1.]], + rtol=1e-17) + + mean3 = multivariate_hypergeom.mean(m=np.array([], dtype=int), n=0) + assert_equal(mean3, []) + assert_(mean3.shape == (0, )) + + def test_var_edge_cases(self): + var0 = multivariate_hypergeom.var(m=[0, 0, 0], n=0) + assert_allclose(var0, [0., 0., 0.], rtol=1e-16) + + var1 = multivariate_hypergeom.var(m=[1, 0, 0], n=2) + assert_equal(var1, [np.nan, np.nan, np.nan]) + + var2 = multivariate_hypergeom.var(m=[[1, 0, 0], [1, 0, 1]], n=2) + assert_allclose(var2, [[np.nan, np.nan, np.nan], [0., 0., 0.]], + rtol=1e-17) + + var3 = multivariate_hypergeom.var(m=np.array([], dtype=int), n=0) + assert_equal(var3, []) + assert_(var3.shape == (0, )) + + def test_cov_edge_cases(self): + cov0 = multivariate_hypergeom.cov(m=[1, 0, 0], n=1) + cov1 = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]] + assert_allclose(cov0, cov1, rtol=1e-17) + + cov3 = multivariate_hypergeom.cov(m=[0, 0, 0], n=0) + cov4 = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]] + assert_equal(cov3, cov4) + + cov5 = multivariate_hypergeom.cov(m=np.array([], dtype=int), n=0) + cov6 = np.array([], dtype=np.float64).reshape(0, 0) + assert_allclose(cov5, cov6, rtol=1e-17) + assert_(cov5.shape == (0, 0)) + + def test_frozen(self): + # The frozen distribution should agree with the regular one + np.random.seed(1234) + n = 12 + m = [7, 9, 11, 13] + x = [[0, 0, 0, 12], [0, 0, 1, 11], [0, 1, 1, 10], + [1, 1, 1, 9], [1, 1, 2, 8]] + x = np.asarray(x, dtype=int) + mhg_frozen = multivariate_hypergeom(m, n) + assert_allclose(mhg_frozen.pmf(x), + multivariate_hypergeom.pmf(x, m, n)) + assert_allclose(mhg_frozen.logpmf(x), + multivariate_hypergeom.logpmf(x, m, n)) + assert_allclose(mhg_frozen.var(), multivariate_hypergeom.var(m, n)) + assert_allclose(mhg_frozen.cov(), multivariate_hypergeom.cov(m, n)) + + def test_invalid_params(self): + assert_raises(ValueError, multivariate_hypergeom.pmf, 5, 10, 5) + assert_raises(ValueError, multivariate_hypergeom.pmf, 5, [10], 5) + assert_raises(ValueError, multivariate_hypergeom.pmf, [5, 4], [10], 5) + assert_raises(TypeError, multivariate_hypergeom.pmf, [5.5, 4.5], + [10, 15], 5) + assert_raises(TypeError, multivariate_hypergeom.pmf, [5, 4], + [10.5, 15.5], 5) + assert_raises(TypeError, multivariate_hypergeom.pmf, [5, 4], + [10, 15], 5.5) + + +class TestRandomTable: + def get_rng(self): + return np.random.default_rng(628174795866951638) + + def test_process_parameters(self): + message = "`row` must be one-dimensional" + with pytest.raises(ValueError, match=message): + random_table([[1, 2]], [1, 2]) + + message = "`col` must be one-dimensional" + with pytest.raises(ValueError, match=message): + random_table([1, 2], [[1, 2]]) + + message = "each element of `row` must be non-negative" + with pytest.raises(ValueError, match=message): + random_table([1, -1], [1, 2]) + + message = "each element of `col` must be non-negative" + with pytest.raises(ValueError, match=message): + random_table([1, 2], [1, -2]) + + message = "sums over `row` and `col` must be equal" + with pytest.raises(ValueError, match=message): + random_table([1, 2], [1, 0]) + + message = "each element of `row` must be an integer" + with pytest.raises(ValueError, match=message): + random_table([2.1, 2.1], [1, 1, 2]) + + message = "each element of `col` must be an integer" + with pytest.raises(ValueError, match=message): + random_table([1, 2], [1.1, 1.1, 1]) + + row = [1, 3] + col = [2, 1, 1] + r, c, n = random_table._process_parameters([1, 3], [2, 1, 1]) + assert_equal(row, r) + assert_equal(col, c) + assert n == np.sum(row) + + @pytest.mark.parametrize("scale,method", + ((1, "boyett"), (100, "patefield"))) + def test_process_rvs_method_on_None(self, scale, method): + row = np.array([1, 3]) * scale + col = np.array([2, 1, 1]) * scale + + ct = random_table + expected = ct.rvs(row, col, method=method, random_state=1) + got = ct.rvs(row, col, method=None, random_state=1) + + assert_equal(expected, got) + + def test_process_rvs_method_bad_argument(self): + row = [1, 3] + col = [2, 1, 1] + + # order of items in set is random, so cannot check that + message = "'foo' not recognized, must be one of" + with pytest.raises(ValueError, match=message): + random_table.rvs(row, col, method="foo") + + @pytest.mark.parametrize('frozen', (True, False)) + @pytest.mark.parametrize('log', (True, False)) + def test_pmf_logpmf(self, frozen, log): + # The pmf is tested through random sample generation + # with Boyett's algorithm, whose implementation is simple + # enough to verify manually for correctness. + rng = self.get_rng() + row = [2, 6] + col = [1, 3, 4] + rvs = random_table.rvs(row, col, size=1000, + method="boyett", random_state=rng) + + obj = random_table(row, col) if frozen else random_table + method = getattr(obj, "logpmf" if log else "pmf") + if not frozen: + original_method = method + + def method(x): + return original_method(x, row, col) + pmf = (lambda x: np.exp(method(x))) if log else method + + unique_rvs, counts = np.unique(rvs, axis=0, return_counts=True) + + # rough accuracy check + p = pmf(unique_rvs) + assert_allclose(p * len(rvs), counts, rtol=0.1) + + # accept any iterable + p2 = pmf(list(unique_rvs[0])) + assert_equal(p2, p[0]) + + # accept high-dimensional input and 2d input + rvs_nd = rvs.reshape((10, 100) + rvs.shape[1:]) + p = pmf(rvs_nd) + assert p.shape == (10, 100) + for i in range(p.shape[0]): + for j in range(p.shape[1]): + pij = p[i, j] + rvij = rvs_nd[i, j] + qij = pmf(rvij) + assert_equal(pij, qij) + + # probability is zero if column marginal does not match + x = [[0, 1, 1], [2, 1, 3]] + assert_equal(np.sum(x, axis=-1), row) + p = pmf(x) + assert p == 0 + + # probability is zero if row marginal does not match + x = [[0, 1, 2], [1, 2, 2]] + assert_equal(np.sum(x, axis=-2), col) + p = pmf(x) + assert p == 0 + + # response to invalid inputs + message = "`x` must be at least two-dimensional" + with pytest.raises(ValueError, match=message): + pmf([1]) + + message = "`x` must contain only integral values" + with pytest.raises(ValueError, match=message): + pmf([[1.1]]) + + message = "`x` must contain only integral values" + with pytest.raises(ValueError, match=message): + pmf([[np.nan]]) + + message = "`x` must contain only non-negative values" + with pytest.raises(ValueError, match=message): + pmf([[-1]]) + + message = "shape of `x` must agree with `row`" + with pytest.raises(ValueError, match=message): + pmf([[1, 2, 3]]) + + message = "shape of `x` must agree with `col`" + with pytest.raises(ValueError, match=message): + pmf([[1, 2], + [3, 4]]) + + @pytest.mark.parametrize("method", ("boyett", "patefield")) + def test_rvs_mean(self, method): + # test if `rvs` is unbiased and large sample size converges + # to the true mean. + rng = self.get_rng() + row = [2, 6] + col = [1, 3, 4] + rvs = random_table.rvs(row, col, size=1000, method=method, + random_state=rng) + mean = random_table.mean(row, col) + assert_equal(np.sum(mean), np.sum(row)) + assert_allclose(rvs.mean(0), mean, atol=0.05) + assert_equal(rvs.sum(axis=-1), np.broadcast_to(row, (1000, 2))) + assert_equal(rvs.sum(axis=-2), np.broadcast_to(col, (1000, 3))) + + def test_rvs_cov(self): + # test if `rvs` generated with patefield and boyett algorithms + # produce approximately the same covariance matrix + rng = self.get_rng() + row = [2, 6] + col = [1, 3, 4] + rvs1 = random_table.rvs(row, col, size=10000, method="boyett", + random_state=rng) + rvs2 = random_table.rvs(row, col, size=10000, method="patefield", + random_state=rng) + cov1 = np.var(rvs1, axis=0) + cov2 = np.var(rvs2, axis=0) + assert_allclose(cov1, cov2, atol=0.02) + + @pytest.mark.parametrize("method", ("boyett", "patefield")) + def test_rvs_size(self, method): + row = [2, 6] + col = [1, 3, 4] + + # test size `None` + rv = random_table.rvs(row, col, method=method, + random_state=self.get_rng()) + assert rv.shape == (2, 3) + + # test size 1 + rv2 = random_table.rvs(row, col, size=1, method=method, + random_state=self.get_rng()) + assert rv2.shape == (1, 2, 3) + assert_equal(rv, rv2[0]) + + # test size 0 + rv3 = random_table.rvs(row, col, size=0, method=method, + random_state=self.get_rng()) + assert rv3.shape == (0, 2, 3) + + # test other valid size + rv4 = random_table.rvs(row, col, size=20, method=method, + random_state=self.get_rng()) + assert rv4.shape == (20, 2, 3) + + rv5 = random_table.rvs(row, col, size=(4, 5), method=method, + random_state=self.get_rng()) + assert rv5.shape == (4, 5, 2, 3) + + assert_allclose(rv5.reshape(20, 2, 3), rv4, rtol=1e-15) + + # test invalid size + message = "`size` must be a non-negative integer or `None`" + with pytest.raises(ValueError, match=message): + random_table.rvs(row, col, size=-1, method=method, + random_state=self.get_rng()) + + with pytest.raises(ValueError, match=message): + random_table.rvs(row, col, size=np.nan, method=method, + random_state=self.get_rng()) + + @pytest.mark.parametrize("method", ("boyett", "patefield")) + def test_rvs_method(self, method): + # This test assumes that pmf is correct and checks that random samples + # follow this probability distribution. This seems like a circular + # argument, since pmf is checked in test_pmf_logpmf with random samples + # generated with the rvs method. This test is not redundant, because + # test_pmf_logpmf intentionally uses rvs generation with Boyett only, + # but here we test both Boyett and Patefield. + row = [2, 6] + col = [1, 3, 4] + + ct = random_table + rvs = ct.rvs(row, col, size=100000, method=method, + random_state=self.get_rng()) + + unique_rvs, counts = np.unique(rvs, axis=0, return_counts=True) + + # generated frequencies should match expected frequencies + p = ct.pmf(unique_rvs, row, col) + assert_allclose(p * len(rvs), counts, rtol=0.02) + + @pytest.mark.parametrize("method", ("boyett", "patefield")) + def test_rvs_with_zeros_in_col_row(self, method): + row = [0, 1, 0] + col = [1, 0, 0, 0] + d = random_table(row, col) + rv = d.rvs(1000, method=method, random_state=self.get_rng()) + expected = np.zeros((1000, len(row), len(col))) + expected[...] = [[0, 0, 0, 0], + [1, 0, 0, 0], + [0, 0, 0, 0]] + assert_equal(rv, expected) + + @pytest.mark.parametrize("method", (None, "boyett", "patefield")) + @pytest.mark.parametrize("col", ([], [0])) + @pytest.mark.parametrize("row", ([], [0])) + def test_rvs_with_edge_cases(self, method, row, col): + d = random_table(row, col) + rv = d.rvs(10, method=method, random_state=self.get_rng()) + expected = np.zeros((10, len(row), len(col))) + assert_equal(rv, expected) + + @pytest.mark.parametrize('v', (1, 2)) + def test_rvs_rcont(self, v): + # This test checks the internal low-level interface. + # It is implicitly also checked by the other test_rvs* calls. + import scipy.stats._rcont as _rcont + + row = np.array([1, 3], dtype=np.int64) + col = np.array([2, 1, 1], dtype=np.int64) + + rvs = getattr(_rcont, f"rvs_rcont{v}") + + ntot = np.sum(row) + result = rvs(row, col, ntot, 1, self.get_rng()) + + assert result.shape == (1, len(row), len(col)) + assert np.sum(result) == ntot + + def test_frozen(self): + row = [2, 6] + col = [1, 3, 4] + d = random_table(row, col, seed=self.get_rng()) + + sample = d.rvs() + + expected = random_table.mean(row, col) + assert_equal(expected, d.mean()) + + expected = random_table.pmf(sample, row, col) + assert_equal(expected, d.pmf(sample)) + + expected = random_table.logpmf(sample, row, col) + assert_equal(expected, d.logpmf(sample)) + + @pytest.mark.parametrize("method", ("boyett", "patefield")) + def test_rvs_frozen(self, method): + row = [2, 6] + col = [1, 3, 4] + d = random_table(row, col, seed=self.get_rng()) + + expected = random_table.rvs(row, col, size=10, method=method, + random_state=self.get_rng()) + got = d.rvs(size=10, method=method) + assert_equal(expected, got) + + +def check_pickling(distfn, args): + # check that a distribution instance pickles and unpickles + # pay special attention to the random_state property + + # save the random_state (restore later) + rndm = distfn.random_state + + distfn.random_state = 1234 + distfn.rvs(*args, size=8) + s = pickle.dumps(distfn) + r0 = distfn.rvs(*args, size=8) + + unpickled = pickle.loads(s) + r1 = unpickled.rvs(*args, size=8) + assert_equal(r0, r1) + + # restore the random_state + distfn.random_state = rndm + + +def test_random_state_property(): + scale = np.eye(3) + scale[0, 1] = 0.5 + scale[1, 0] = 0.5 + dists = [ + [multivariate_normal, ()], + [dirichlet, (np.array([1.]), )], + [wishart, (10, scale)], + [invwishart, (10, scale)], + [multinomial, (5, [0.5, 0.4, 0.1])], + [ortho_group, (2,)], + [special_ortho_group, (2,)] + ] + for distfn, args in dists: + check_random_state_property(distfn, args) + check_pickling(distfn, args) + + +class TestVonMises_Fisher: + @pytest.mark.parametrize("dim", [2, 3, 4, 6]) + @pytest.mark.parametrize("size", [None, 1, 5, (5, 4)]) + def test_samples(self, dim, size): + # test that samples have correct shape and norm 1 + rng = np.random.default_rng(2777937887058094419) + mu = np.full((dim, ), 1/np.sqrt(dim)) + vmf_dist = vonmises_fisher(mu, 1, seed=rng) + samples = vmf_dist.rvs(size) + mean, cov = np.zeros(dim), np.eye(dim) + expected_shape = rng.multivariate_normal(mean, cov, size=size).shape + assert samples.shape == expected_shape + norms = np.linalg.norm(samples, axis=-1) + assert_allclose(norms, 1.) + + @pytest.mark.parametrize("dim", [5, 8]) + @pytest.mark.parametrize("kappa", [1e15, 1e20, 1e30]) + def test_sampling_high_concentration(self, dim, kappa): + # test that no warnings are encountered for high values + rng = np.random.default_rng(2777937887058094419) + mu = np.full((dim, ), 1/np.sqrt(dim)) + vmf_dist = vonmises_fisher(mu, kappa, seed=rng) + vmf_dist.rvs(10) + + def test_two_dimensional_mu(self): + mu = np.ones((2, 2)) + msg = "'mu' must have one-dimensional shape." + with pytest.raises(ValueError, match=msg): + vonmises_fisher(mu, 1) + + def test_wrong_norm_mu(self): + mu = np.ones((2, )) + msg = "'mu' must be a unit vector of norm 1." + with pytest.raises(ValueError, match=msg): + vonmises_fisher(mu, 1) + + def test_one_entry_mu(self): + mu = np.ones((1, )) + msg = "'mu' must have at least two entries." + with pytest.raises(ValueError, match=msg): + vonmises_fisher(mu, 1) + + @pytest.mark.parametrize("kappa", [-1, (5, 3)]) + def test_kappa_validation(self, kappa): + msg = "'kappa' must be a positive scalar." + with pytest.raises(ValueError, match=msg): + vonmises_fisher([1, 0], kappa) + + @pytest.mark.parametrize("kappa", [0, 0.]) + def test_kappa_zero(self, kappa): + msg = ("For 'kappa=0' the von Mises-Fisher distribution " + "becomes the uniform distribution on the sphere " + "surface. Consider using 'scipy.stats.uniform_direction' " + "instead.") + with pytest.raises(ValueError, match=msg): + vonmises_fisher([1, 0], kappa) + + + @pytest.mark.parametrize("method", [vonmises_fisher.pdf, + vonmises_fisher.logpdf]) + def test_invalid_shapes_pdf_logpdf(self, method): + x = np.array([1., 0., 0]) + msg = ("The dimensionality of the last axis of 'x' must " + "match the dimensionality of the von Mises Fisher " + "distribution.") + with pytest.raises(ValueError, match=msg): + method(x, [1, 0], 1) + + @pytest.mark.parametrize("method", [vonmises_fisher.pdf, + vonmises_fisher.logpdf]) + def test_unnormalized_input(self, method): + x = np.array([0.5, 0.]) + msg = "'x' must be unit vectors of norm 1 along last dimension." + with pytest.raises(ValueError, match=msg): + method(x, [1, 0], 1) + + # Expected values of the vonmises-fisher logPDF were computed via mpmath + # from mpmath import mp + # import numpy as np + # mp.dps = 50 + # def logpdf_mpmath(x, mu, kappa): + # dim = mu.size + # halfdim = mp.mpf(0.5 * dim) + # kappa = mp.mpf(kappa) + # const = (kappa**(halfdim - mp.one)/((2*mp.pi)**halfdim * \ + # mp.besseli(halfdim -mp.one, kappa))) + # return float(const * mp.exp(kappa*mp.fdot(x, mu))) + + @pytest.mark.parametrize('x, mu, kappa, reference', + [(np.array([1., 0., 0.]), np.array([1., 0., 0.]), + 1e-4, 0.0795854295583605), + (np.array([1., 0., 0]), np.array([0., 0., 1.]), + 1e-4, 0.07957747141331854), + (np.array([1., 0., 0.]), np.array([1., 0., 0.]), + 100, 15.915494309189533), + (np.array([1., 0., 0]), np.array([0., 0., 1.]), + 100, 5.920684802611232e-43), + (np.array([1., 0., 0.]), + np.array([np.sqrt(0.98), np.sqrt(0.02), 0.]), + 2000, 5.930499050746588e-07), + (np.array([1., 0., 0]), np.array([1., 0., 0.]), + 2000, 318.3098861837907), + (np.array([1., 0., 0., 0., 0.]), + np.array([1., 0., 0., 0., 0.]), + 2000, 101371.86957712633), + (np.array([1., 0., 0., 0., 0.]), + np.array([np.sqrt(0.98), np.sqrt(0.02), 0., + 0, 0.]), + 2000, 0.00018886808182653578), + (np.array([1., 0., 0., 0., 0.]), + np.array([np.sqrt(0.8), np.sqrt(0.2), 0., + 0, 0.]), + 2000, 2.0255393314603194e-87)]) + def test_pdf_accuracy(self, x, mu, kappa, reference): + pdf = vonmises_fisher(mu, kappa).pdf(x) + assert_allclose(pdf, reference, rtol=1e-13) + + # Expected values of the vonmises-fisher logPDF were computed via mpmath + # from mpmath import mp + # import numpy as np + # mp.dps = 50 + # def logpdf_mpmath(x, mu, kappa): + # dim = mu.size + # halfdim = mp.mpf(0.5 * dim) + # kappa = mp.mpf(kappa) + # two = mp.mpf(2.) + # const = (kappa**(halfdim - mp.one)/((two*mp.pi)**halfdim * \ + # mp.besseli(halfdim - mp.one, kappa))) + # return float(mp.log(const * mp.exp(kappa*mp.fdot(x, mu)))) + + @pytest.mark.parametrize('x, mu, kappa, reference', + [(np.array([1., 0., 0.]), np.array([1., 0., 0.]), + 1e-4, -2.5309242486359573), + (np.array([1., 0., 0]), np.array([0., 0., 1.]), + 1e-4, -2.5310242486359575), + (np.array([1., 0., 0.]), np.array([1., 0., 0.]), + 100, 2.767293119578746), + (np.array([1., 0., 0]), np.array([0., 0., 1.]), + 100, -97.23270688042125), + (np.array([1., 0., 0.]), + np.array([np.sqrt(0.98), np.sqrt(0.02), 0.]), + 2000, -14.337987284534103), + (np.array([1., 0., 0]), np.array([1., 0., 0.]), + 2000, 5.763025393132737), + (np.array([1., 0., 0., 0., 0.]), + np.array([1., 0., 0., 0., 0.]), + 2000, 11.526550911307156), + (np.array([1., 0., 0., 0., 0.]), + np.array([np.sqrt(0.98), np.sqrt(0.02), 0., + 0, 0.]), + 2000, -8.574461766359684), + (np.array([1., 0., 0., 0., 0.]), + np.array([np.sqrt(0.8), np.sqrt(0.2), 0., + 0, 0.]), + 2000, -199.61906708886113)]) + def test_logpdf_accuracy(self, x, mu, kappa, reference): + logpdf = vonmises_fisher(mu, kappa).logpdf(x) + assert_allclose(logpdf, reference, rtol=1e-14) + + # Expected values of the vonmises-fisher entropy were computed via mpmath + # from mpmath import mp + # import numpy as np + # mp.dps = 50 + # def entropy_mpmath(dim, kappa): + # mu = np.full((dim, ), 1/np.sqrt(dim)) + # kappa = mp.mpf(kappa) + # halfdim = mp.mpf(0.5 * dim) + # logconstant = (mp.log(kappa**(halfdim - mp.one) + # /((2*mp.pi)**halfdim + # * mp.besseli(halfdim -mp.one, kappa))) + # return float(-logconstant - kappa * mp.besseli(halfdim, kappa)/ + # mp.besseli(halfdim -1, kappa)) + + @pytest.mark.parametrize('dim, kappa, reference', + [(3, 1e-4, 2.531024245302624), + (3, 100, -1.7672931195787458), + (5, 5000, -11.359032310024453), + (8, 1, 3.4189526482545527)]) + def test_entropy_accuracy(self, dim, kappa, reference): + mu = np.full((dim, ), 1/np.sqrt(dim)) + entropy = vonmises_fisher(mu, kappa).entropy() + assert_allclose(entropy, reference, rtol=2e-14) + + @pytest.mark.parametrize("method", [vonmises_fisher.pdf, + vonmises_fisher.logpdf]) + def test_broadcasting(self, method): + # test that pdf and logpdf values are correctly broadcasted + testshape = (2, 2) + rng = np.random.default_rng(2777937887058094419) + x = uniform_direction(3).rvs(testshape, random_state=rng) + mu = np.full((3, ), 1/np.sqrt(3)) + kappa = 5 + result_all = method(x, mu, kappa) + assert result_all.shape == testshape + for i in range(testshape[0]): + for j in range(testshape[1]): + current_val = method(x[i, j, :], mu, kappa) + assert_allclose(current_val, result_all[i, j], rtol=1e-15) + + def test_vs_vonmises_2d(self): + # test that in 2D, von Mises-Fisher yields the same results + # as the von Mises distribution + rng = np.random.default_rng(2777937887058094419) + mu = np.array([0, 1]) + mu_angle = np.arctan2(mu[1], mu[0]) + kappa = 20 + vmf = vonmises_fisher(mu, kappa) + vonmises_dist = vonmises(loc=mu_angle, kappa=kappa) + vectors = uniform_direction(2).rvs(10, random_state=rng) + angles = np.arctan2(vectors[:, 1], vectors[:, 0]) + assert_allclose(vonmises_dist.entropy(), vmf.entropy()) + assert_allclose(vonmises_dist.pdf(angles), vmf.pdf(vectors)) + assert_allclose(vonmises_dist.logpdf(angles), vmf.logpdf(vectors)) + + @pytest.mark.parametrize("dim", [2, 3, 6]) + @pytest.mark.parametrize("kappa, mu_tol, kappa_tol", + [(1, 5e-2, 5e-2), + (10, 1e-2, 1e-2), + (100, 5e-3, 2e-2), + (1000, 1e-3, 2e-2)]) + def test_fit_accuracy(self, dim, kappa, mu_tol, kappa_tol): + mu = np.full((dim, ), 1/np.sqrt(dim)) + vmf_dist = vonmises_fisher(mu, kappa) + rng = np.random.default_rng(2777937887058094419) + n_samples = 10000 + samples = vmf_dist.rvs(n_samples, random_state=rng) + mu_fit, kappa_fit = vonmises_fisher.fit(samples) + angular_error = np.arccos(mu.dot(mu_fit)) + assert_allclose(angular_error, 0., atol=mu_tol, rtol=0) + assert_allclose(kappa, kappa_fit, rtol=kappa_tol) + + def test_fit_error_one_dimensional_data(self): + x = np.zeros((3, )) + msg = "'x' must be two dimensional." + with pytest.raises(ValueError, match=msg): + vonmises_fisher.fit(x) + + def test_fit_error_unnormalized_data(self): + x = np.ones((3, 3)) + msg = "'x' must be unit vectors of norm 1 along last dimension." + with pytest.raises(ValueError, match=msg): + vonmises_fisher.fit(x) + + def test_frozen_distribution(self): + mu = np.array([0, 0, 1]) + kappa = 5 + frozen = vonmises_fisher(mu, kappa) + frozen_seed = vonmises_fisher(mu, kappa, seed=514) + + rvs1 = frozen.rvs(random_state=514) + rvs2 = vonmises_fisher.rvs(mu, kappa, random_state=514) + rvs3 = frozen_seed.rvs() + + assert_equal(rvs1, rvs2) + assert_equal(rvs1, rvs3) + + +class TestDirichletMultinomial: + @classmethod + def get_params(self, m): + rng = np.random.default_rng(28469824356873456) + alpha = rng.uniform(0, 100, size=2) + x = rng.integers(1, 20, size=(m, 2)) + n = x.sum(axis=-1) + return rng, m, alpha, n, x + + def test_frozen(self): + rng = np.random.default_rng(28469824356873456) + + alpha = rng.uniform(0, 100, 10) + x = rng.integers(0, 10, 10) + n = np.sum(x, axis=-1) + + d = dirichlet_multinomial(alpha, n) + assert_equal(d.logpmf(x), dirichlet_multinomial.logpmf(x, alpha, n)) + assert_equal(d.pmf(x), dirichlet_multinomial.pmf(x, alpha, n)) + assert_equal(d.mean(), dirichlet_multinomial.mean(alpha, n)) + assert_equal(d.var(), dirichlet_multinomial.var(alpha, n)) + assert_equal(d.cov(), dirichlet_multinomial.cov(alpha, n)) + + def test_pmf_logpmf_against_R(self): + # # Compare PMF against R's extraDistr ddirmnon + # # library(extraDistr) + # # options(digits=16) + # ddirmnom(c(1, 2, 3), 6, c(3, 4, 5)) + x = np.array([1, 2, 3]) + n = np.sum(x) + alpha = np.array([3, 4, 5]) + res = dirichlet_multinomial.pmf(x, alpha, n) + logres = dirichlet_multinomial.logpmf(x, alpha, n) + ref = 0.08484162895927638 + assert_allclose(res, ref) + assert_allclose(logres, np.log(ref)) + assert res.shape == logres.shape == () + + # library(extraDistr) + # options(digits=16) + # ddirmnom(c(4, 3, 2, 0, 2, 3, 5, 7, 4, 7), 37, + # c(45.01025314, 21.98739582, 15.14851365, 80.21588671, + # 52.84935481, 25.20905262, 53.85373737, 4.88568118, + # 89.06440654, 20.11359466)) + rng = np.random.default_rng(28469824356873456) + alpha = rng.uniform(0, 100, 10) + x = rng.integers(0, 10, 10) + n = np.sum(x, axis=-1) + res = dirichlet_multinomial(alpha, n).pmf(x) + logres = dirichlet_multinomial.logpmf(x, alpha, n) + ref = 3.65409306285992e-16 + assert_allclose(res, ref) + assert_allclose(logres, np.log(ref)) + + def test_pmf_logpmf_support(self): + # when the sum of the category counts does not equal the number of + # trials, the PMF is zero + rng, m, alpha, n, x = self.get_params(1) + n += 1 + assert_equal(dirichlet_multinomial(alpha, n).pmf(x), 0) + assert_equal(dirichlet_multinomial(alpha, n).logpmf(x), -np.inf) + + rng, m, alpha, n, x = self.get_params(10) + i = rng.random(size=10) > 0.5 + x[i] = np.round(x[i] * 2) # sum of these x does not equal n + assert_equal(dirichlet_multinomial(alpha, n).pmf(x)[i], 0) + assert_equal(dirichlet_multinomial(alpha, n).logpmf(x)[i], -np.inf) + assert np.all(dirichlet_multinomial(alpha, n).pmf(x)[~i] > 0) + assert np.all(dirichlet_multinomial(alpha, n).logpmf(x)[~i] > -np.inf) + + def test_dimensionality_one(self): + # if the dimensionality is one, there is only one possible outcome + n = 6 # number of trials + alpha = [10] # concentration parameters + x = np.asarray([n]) # counts + dist = dirichlet_multinomial(alpha, n) + + assert_equal(dist.pmf(x), 1) + assert_equal(dist.pmf(x+1), 0) + assert_equal(dist.logpmf(x), 0) + assert_equal(dist.logpmf(x+1), -np.inf) + assert_equal(dist.mean(), n) + assert_equal(dist.var(), 0) + assert_equal(dist.cov(), 0) + + @pytest.mark.parametrize('method_name', ['pmf', 'logpmf']) + def test_against_betabinom_pmf(self, method_name): + rng, m, alpha, n, x = self.get_params(100) + + method = getattr(dirichlet_multinomial(alpha, n), method_name) + ref_method = getattr(stats.betabinom(n, *alpha.T), method_name) + + res = method(x) + ref = ref_method(x.T[0]) + assert_allclose(res, ref) + + @pytest.mark.parametrize('method_name', ['mean', 'var']) + def test_against_betabinom_moments(self, method_name): + rng, m, alpha, n, x = self.get_params(100) + + method = getattr(dirichlet_multinomial(alpha, n), method_name) + ref_method = getattr(stats.betabinom(n, *alpha.T), method_name) + + res = method()[:, 0] + ref = ref_method() + assert_allclose(res, ref) + + def test_moments(self): + rng = np.random.default_rng(28469824356873456) + dim = 5 + n = rng.integers(1, 100) + alpha = rng.random(size=dim) * 10 + dist = dirichlet_multinomial(alpha, n) + + # Generate a random sample from the distribution using NumPy + m = 100000 + p = rng.dirichlet(alpha, size=m) + x = rng.multinomial(n, p, size=m) + + assert_allclose(dist.mean(), np.mean(x, axis=0), rtol=5e-3) + assert_allclose(dist.var(), np.var(x, axis=0), rtol=1e-2) + assert dist.mean().shape == dist.var().shape == (dim,) + + cov = dist.cov() + assert cov.shape == (dim, dim) + assert_allclose(cov, np.cov(x.T), rtol=2e-2) + assert_equal(np.diag(cov), dist.var()) + assert np.all(scipy.linalg.eigh(cov)[0] > 0) # positive definite + + def test_input_validation(self): + # valid inputs + x0 = np.array([1, 2, 3]) + n0 = np.sum(x0) + alpha0 = np.array([3, 4, 5]) + + text = "`x` must contain only non-negative integers." + with assert_raises(ValueError, match=text): + dirichlet_multinomial.logpmf([1, -1, 3], alpha0, n0) + with assert_raises(ValueError, match=text): + dirichlet_multinomial.logpmf([1, 2.1, 3], alpha0, n0) + + text = "`alpha` must contain only positive values." + with assert_raises(ValueError, match=text): + dirichlet_multinomial.logpmf(x0, [3, 0, 4], n0) + with assert_raises(ValueError, match=text): + dirichlet_multinomial.logpmf(x0, [3, -1, 4], n0) + + text = "`n` must be a positive integer." + with assert_raises(ValueError, match=text): + dirichlet_multinomial.logpmf(x0, alpha0, 49.1) + with assert_raises(ValueError, match=text): + dirichlet_multinomial.logpmf(x0, alpha0, 0) + + x = np.array([1, 2, 3, 4]) + alpha = np.array([3, 4, 5]) + text = "`x` and `alpha` must be broadcastable." + with assert_raises(ValueError, match=text): + dirichlet_multinomial.logpmf(x, alpha, x.sum()) + + @pytest.mark.parametrize('method', ['pmf', 'logpmf']) + def test_broadcasting_pmf(self, method): + alpha = np.array([[3, 4, 5], [4, 5, 6], [5, 5, 7], [8, 9, 10]]) + n = np.array([[6], [7], [8]]) + x = np.array([[1, 2, 3], [2, 2, 3]]).reshape((2, 1, 1, 3)) + method = getattr(dirichlet_multinomial, method) + res = method(x, alpha, n) + assert res.shape == (2, 3, 4) + for i in range(len(x)): + for j in range(len(n)): + for k in range(len(alpha)): + res_ijk = res[i, j, k] + ref = method(x[i].squeeze(), alpha[k].squeeze(), n[j].squeeze()) + assert_allclose(res_ijk, ref) + + @pytest.mark.parametrize('method_name', ['mean', 'var', 'cov']) + def test_broadcasting_moments(self, method_name): + alpha = np.array([[3, 4, 5], [4, 5, 6], [5, 5, 7], [8, 9, 10]]) + n = np.array([[6], [7], [8]]) + method = getattr(dirichlet_multinomial, method_name) + res = method(alpha, n) + assert res.shape == (3, 4, 3) if method_name != 'cov' else (3, 4, 3, 3) + for j in range(len(n)): + for k in range(len(alpha)): + res_ijk = res[j, k] + ref = method(alpha[k].squeeze(), n[j].squeeze()) + assert_allclose(res_ijk, ref) + + +class TestNormalInverseGamma: + + def test_marginal_x(self): + # According to [1], sqrt(a * lmbda / b) * (x - u) should follow a t-distribution + # with 2*a degrees of freedom. Test that this is true of the PDF and random + # variates. + rng = np.random.default_rng(8925849245) + mu, lmbda, a, b = rng.random(4) + + norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b) + t = stats.t(2*a, loc=mu, scale=1/np.sqrt(a * lmbda / b)) + + # Test PDF + x = np.linspace(-5, 5, 11) + res = tanhsinh(lambda s2, x: norm_inv_gamma.pdf(x, s2), 0, np.inf, args=(x,)) + ref = t.pdf(x) + assert_allclose(res.integral, ref) + + # Test RVS + res = norm_inv_gamma.rvs(size=10000, random_state=rng) + _, pvalue = stats.ks_1samp(res[0], t.cdf) + assert pvalue > 0.1 + + def test_marginal_s2(self): + # According to [1], s2 should follow an inverse gamma distribution with + # shapes a, b (where b is the scale in our parameterization). Test that + # this is true of the PDF and random variates. + rng = np.random.default_rng(8925849245) + mu, lmbda, a, b = rng.random(4) + + norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b) + inv_gamma = stats.invgamma(a, scale=b) + + # Test PDF + s2 = np.linspace(0.1, 10, 10) + res = tanhsinh(lambda x, s2: norm_inv_gamma.pdf(x, s2), + -np.inf, np.inf, args=(s2,)) + ref = inv_gamma.pdf(s2) + assert_allclose(res.integral, ref) + + # Test RVS + res = norm_inv_gamma.rvs(size=10000, random_state=rng) + _, pvalue = stats.ks_1samp(res[1], inv_gamma.cdf) + assert pvalue > 0.1 + + def test_pdf_logpdf(self): + # Check that PDF and log-PDF are consistent + rng = np.random.default_rng(8925849245) + mu, lmbda, a, b = rng.random((4, 20)) - 0.25 # make some invalid + x, s2 = rng.random(size=(2, 20)) - 0.25 + res = stats.normal_inverse_gamma(mu, lmbda, a, b).pdf(x, s2) + ref = stats.normal_inverse_gamma.logpdf(x, s2, mu, lmbda, a, b) + assert_allclose(res, np.exp(ref)) + + def test_invalid_and_special_cases(self): + # Test cases that are handled by input validation rather than the formulas + rng = np.random.default_rng(8925849245) + mu, lmbda, a, b = rng.random(4) + x, s2 = rng.random(2) + + res = stats.normal_inverse_gamma(np.nan, lmbda, a, b).pdf(x, s2) + assert_equal(res, np.nan) + + res = stats.normal_inverse_gamma(mu, -1, a, b).pdf(x, s2) + assert_equal(res, np.nan) + + res = stats.normal_inverse_gamma(mu, lmbda, 0, b).pdf(x, s2) + assert_equal(res, np.nan) + + res = stats.normal_inverse_gamma(mu, lmbda, a, -1).pdf(x, s2) + assert_equal(res, np.nan) + + res = stats.normal_inverse_gamma(mu, lmbda, a, b).pdf(x, -1) + assert_equal(res, 0) + + # PDF with out-of-support s2 is not zero if shape parameter is invalid + res = stats.normal_inverse_gamma(mu, [-1, np.nan], a, b).pdf(x, -1) + assert_equal(res, np.nan) + + res = stats.normal_inverse_gamma(mu, -1, a, b).mean() + assert_equal(res, (np.nan, np.nan)) + + res = stats.normal_inverse_gamma(mu, lmbda, -1, b).var() + assert_equal(res, (np.nan, np.nan)) + + with pytest.raises(ValueError, match="Domain error in arguments..."): + stats.normal_inverse_gamma(mu, lmbda, a, -1).rvs() + + def test_broadcasting(self): + # Test methods with broadcastable array parameters. Roughly speaking, the + # shapes should be the broadcasted shapes of all arguments, and the raveled + # outputs should be the same as the outputs with raveled inputs. + rng = np.random.default_rng(8925849245) + b = rng.random(2) + a = rng.random((3, 1)) + 2 # for defined moments + lmbda = rng.random((4, 1, 1)) + mu = rng.random((5, 1, 1, 1)) + s2 = rng.random((6, 1, 1, 1, 1)) + x = rng.random((7, 1, 1, 1, 1, 1)) + dist = stats.normal_inverse_gamma(mu, lmbda, a, b) + + # Test PDF and log-PDF + broadcasted = np.broadcast_arrays(x, s2, mu, lmbda, a, b) + broadcasted_raveled = [np.ravel(arr) for arr in broadcasted] + + res = dist.pdf(x, s2) + assert res.shape == broadcasted[0].shape + assert_allclose(res.ravel(), + stats.normal_inverse_gamma.pdf(*broadcasted_raveled)) + + res = dist.logpdf(x, s2) + assert res.shape == broadcasted[0].shape + assert_allclose(res.ravel(), + stats.normal_inverse_gamma.logpdf(*broadcasted_raveled)) + + # Test moments + broadcasted = np.broadcast_arrays(mu, lmbda, a, b) + broadcasted_raveled = [np.ravel(arr) for arr in broadcasted] + + res = dist.mean() + assert res[0].shape == broadcasted[0].shape + assert_allclose((res[0].ravel(), res[1].ravel()), + stats.normal_inverse_gamma.mean(*broadcasted_raveled)) + + res = dist.var() + assert res[0].shape == broadcasted[0].shape + assert_allclose((res[0].ravel(), res[1].ravel()), + stats.normal_inverse_gamma.var(*broadcasted_raveled)) + + # Test RVS + size = (6, 5, 4, 3, 2) + rng = np.random.default_rng(2348923985324) + res = dist.rvs(size=size, random_state=rng) + rng = np.random.default_rng(2348923985324) + shape = 6, 5*4*3*2 + ref = stats.normal_inverse_gamma.rvs(*broadcasted_raveled, size=shape, + random_state=rng) + assert_allclose((res[0].reshape(shape), res[1].reshape(shape)), ref) + + @pytest.mark.slow + @pytest.mark.fail_slow(10) + def test_moments(self): + # Test moments against quadrature + rng = np.random.default_rng(8925849245) + mu, lmbda, a, b = rng.random(4) + a += 2 # ensure defined + + dist = stats.normal_inverse_gamma(mu, lmbda, a, b) + res = dist.mean() + + ref = dblquad(lambda s2, x: dist.pdf(x, s2) * x, -np.inf, np.inf, 0, np.inf) + assert_allclose(res[0], ref[0], rtol=1e-6) + + ref = dblquad(lambda s2, x: dist.pdf(x, s2) * s2, -np.inf, np.inf, 0, np.inf) + assert_allclose(res[1], ref[0], rtol=1e-6) + + @pytest.mark.parametrize('dtype', [np.int32, np.float16, np.float32, np.float64]) + def test_dtype(self, dtype): + if np.__version__ < "2": + pytest.skip("Scalar dtypes only respected after NEP 50.") + rng = np.random.default_rng(8925849245) + x, s2, mu, lmbda, a, b = rng.uniform(3, 10, size=6).astype(dtype) + dtype_out = np.result_type(1.0, dtype) + dist = stats.normal_inverse_gamma(mu, lmbda, a, b) + assert dist.rvs()[0].dtype == dtype_out + assert dist.rvs()[1].dtype == dtype_out + assert dist.mean()[0].dtype == dtype_out + assert dist.mean()[1].dtype == dtype_out + assert dist.var()[0].dtype == dtype_out + assert dist.var()[1].dtype == dtype_out + assert dist.logpdf(x, s2).dtype == dtype_out + assert dist.pdf(x, s2).dtype == dtype_out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_odds_ratio.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_odds_ratio.py new file mode 100644 index 0000000000000000000000000000000000000000..14b5ca88d0fca9edb8c3c161c06e52054d594e62 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_odds_ratio.py @@ -0,0 +1,148 @@ +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose +from .._discrete_distns import nchypergeom_fisher, hypergeom +from scipy.stats._odds_ratio import odds_ratio +from .data.fisher_exact_results_from_r import data + + +class TestOddsRatio: + + @pytest.mark.parametrize('parameters, rresult', data) + def test_results_from_r(self, parameters, rresult): + alternative = parameters.alternative.replace('.', '-') + result = odds_ratio(parameters.table) + # The results computed by R are not very accurate. + if result.statistic < 400: + or_rtol = 5e-4 + ci_rtol = 2e-2 + else: + or_rtol = 5e-2 + ci_rtol = 1e-1 + assert_allclose(result.statistic, + rresult.conditional_odds_ratio, rtol=or_rtol) + ci = result.confidence_interval(parameters.confidence_level, + alternative) + assert_allclose((ci.low, ci.high), rresult.conditional_odds_ratio_ci, + rtol=ci_rtol) + + # Also do a self-check for the conditional odds ratio. + # With the computed conditional odds ratio as the noncentrality + # parameter of the noncentral hypergeometric distribution with + # parameters table.sum(), table[0].sum(), and table[:,0].sum() as + # total, ngood and nsample, respectively, the mean of the distribution + # should equal table[0, 0]. + cor = result.statistic + table = np.array(parameters.table) + total = table.sum() + ngood = table[0].sum() + nsample = table[:, 0].sum() + # nchypergeom_fisher does not allow the edge cases where the + # noncentrality parameter is 0 or inf, so handle those values + # separately here. + if cor == 0: + nchg_mean = hypergeom.support(total, ngood, nsample)[0] + elif cor == np.inf: + nchg_mean = hypergeom.support(total, ngood, nsample)[1] + else: + nchg_mean = nchypergeom_fisher.mean(total, ngood, nsample, cor) + assert_allclose(nchg_mean, table[0, 0], rtol=1e-13) + + # Check that the confidence interval is correct. + alpha = 1 - parameters.confidence_level + if alternative == 'two-sided': + if ci.low > 0: + sf = nchypergeom_fisher.sf(table[0, 0] - 1, + total, ngood, nsample, ci.low) + assert_allclose(sf, alpha/2, rtol=1e-11) + if np.isfinite(ci.high): + cdf = nchypergeom_fisher.cdf(table[0, 0], + total, ngood, nsample, ci.high) + assert_allclose(cdf, alpha/2, rtol=1e-11) + elif alternative == 'less': + if np.isfinite(ci.high): + cdf = nchypergeom_fisher.cdf(table[0, 0], + total, ngood, nsample, ci.high) + assert_allclose(cdf, alpha, rtol=1e-11) + else: + # alternative == 'greater' + if ci.low > 0: + sf = nchypergeom_fisher.sf(table[0, 0] - 1, + total, ngood, nsample, ci.low) + assert_allclose(sf, alpha, rtol=1e-11) + + @pytest.mark.parametrize('table', [ + [[0, 0], [5, 10]], + [[5, 10], [0, 0]], + [[0, 5], [0, 10]], + [[5, 0], [10, 0]], + ]) + def test_row_or_col_zero(self, table): + result = odds_ratio(table) + assert_equal(result.statistic, np.nan) + ci = result.confidence_interval() + assert_equal((ci.low, ci.high), (0, np.inf)) + + @pytest.mark.parametrize("case", + [[0.95, 'two-sided', 0.4879913, 2.635883], + [0.90, 'two-sided', 0.5588516, 2.301663]]) + def test_sample_odds_ratio_ci(self, case): + # Compare the sample odds ratio confidence interval to the R function + # oddsratio.wald from the epitools package, e.g. + # > library(epitools) + # > table = matrix(c(10, 20, 41, 93), nrow=2, ncol=2, byrow=TRUE) + # > result = oddsratio.wald(table) + # > result$measure + # odds ratio with 95% C.I. + # Predictor estimate lower upper + # Exposed1 1.000000 NA NA + # Exposed2 1.134146 0.4879913 2.635883 + + confidence_level, alternative, ref_low, ref_high = case + table = [[10, 20], [41, 93]] + result = odds_ratio(table, kind='sample') + assert_allclose(result.statistic, 1.134146, rtol=1e-6) + ci = result.confidence_interval(confidence_level, alternative) + assert_allclose([ci.low, ci.high], [ref_low, ref_high], rtol=1e-6) + + @pytest.mark.slow + @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided']) + def test_sample_odds_ratio_one_sided_ci(self, alternative): + # can't find a good reference for one-sided CI, so bump up the sample + # size and compare against the conditional odds ratio CI + table = [[1000, 2000], [4100, 9300]] + res = odds_ratio(table, kind='sample') + ref = odds_ratio(table, kind='conditional') + assert_allclose(res.statistic, ref.statistic, atol=1e-5) + assert_allclose(res.confidence_interval(alternative=alternative), + ref.confidence_interval(alternative=alternative), + atol=2e-3) + + @pytest.mark.parametrize('kind', ['sample', 'conditional']) + @pytest.mark.parametrize('bad_table', [123, "foo", [10, 11, 12]]) + def test_invalid_table_shape(self, kind, bad_table): + with pytest.raises(ValueError, match="Invalid shape"): + odds_ratio(bad_table, kind=kind) + + def test_invalid_table_type(self): + with pytest.raises(ValueError, match='must be an array of integers'): + odds_ratio([[1.0, 3.4], [5.0, 9.9]]) + + def test_negative_table_values(self): + with pytest.raises(ValueError, match='must be nonnegative'): + odds_ratio([[1, 2], [3, -4]]) + + def test_invalid_kind(self): + with pytest.raises(ValueError, match='`kind` must be'): + odds_ratio([[10, 20], [30, 14]], kind='magnetoreluctance') + + def test_invalid_alternative(self): + result = odds_ratio([[5, 10], [2, 32]]) + with pytest.raises(ValueError, match='`alternative` must be'): + result.confidence_interval(alternative='depleneration') + + @pytest.mark.parametrize('level', [-0.5, 1.5]) + def test_invalid_confidence_level(self, level): + result = odds_ratio([[5, 10], [2, 32]]) + with pytest.raises(ValueError, match='must be between 0 and 1'): + result.confidence_interval(confidence_level=level) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py new file mode 100644 index 0000000000000000000000000000000000000000..ba824e2d122b9abd970fee1e0fdaeeb9e52fbbeb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py @@ -0,0 +1,1489 @@ +import os +from collections import Counter +from itertools import combinations, product + +import pytest +import numpy as np +from numpy.testing import (assert_allclose, assert_equal, assert_array_equal, + assert_array_less) + +from scipy.spatial import distance +from scipy.stats import shapiro +from scipy.stats._sobol import _test_find_index +from scipy.stats import qmc +from scipy.stats._qmc import ( + van_der_corput, n_primes, primes_from_2_to, + update_discrepancy, QMCEngine, _l1_norm, + _perturb_discrepancy, _lloyd_centroidal_voronoi_tessellation +) + + +class TestUtils: + def test_scale(self): + # 1d scalar + space = [[0], [1], [0.5]] + out = [[-2], [6], [2]] + scaled_space = qmc.scale(space, l_bounds=-2, u_bounds=6) + + assert_allclose(scaled_space, out) + + # 2d space + space = [[0, 0], [1, 1], [0.5, 0.5]] + bounds = np.array([[-2, 0], [6, 5]]) + out = [[-2, 0], [6, 5], [2, 2.5]] + + scaled_space = qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1]) + + assert_allclose(scaled_space, out) + + scaled_back_space = qmc.scale(scaled_space, l_bounds=bounds[0], + u_bounds=bounds[1], reverse=True) + assert_allclose(scaled_back_space, space) + + # broadcast + space = [[0, 0, 0], [1, 1, 1], [0.5, 0.5, 0.5]] + l_bounds, u_bounds = 0, [6, 5, 3] + out = [[0, 0, 0], [6, 5, 3], [3, 2.5, 1.5]] + + scaled_space = qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds) + + assert_allclose(scaled_space, out) + + def test_scale_random(self): + rng = np.random.default_rng(317589836511269190194010915937762468165) + sample = rng.random((30, 10)) + a = -rng.random(10) * 10 + b = rng.random(10) * 10 + scaled = qmc.scale(sample, a, b, reverse=False) + unscaled = qmc.scale(scaled, a, b, reverse=True) + assert_allclose(unscaled, sample) + + def test_scale_errors(self): + with pytest.raises(ValueError, match=r"Sample is not a 2D array"): + space = [0, 1, 0.5] + qmc.scale(space, l_bounds=-2, u_bounds=6) + + with pytest.raises(ValueError, match=r"Bounds are not consistent"): + space = [[0, 0], [1, 1], [0.5, 0.5]] + bounds = np.array([[-2, 6], [6, 5]]) + qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1]) + + with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'" + r" must be broadcastable"): + space = [[0, 0], [1, 1], [0.5, 0.5]] + l_bounds, u_bounds = [-2, 0, 2], [6, 5] + qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds) + + with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'" + r" must be broadcastable"): + space = [[0, 0], [1, 1], [0.5, 0.5]] + bounds = np.array([[-2, 0, 2], [6, 5, 5]]) + qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1]) + + with pytest.raises(ValueError, match=r"Sample is not in unit " + r"hypercube"): + space = [[0, 0], [1, 1.5], [0.5, 0.5]] + bounds = np.array([[-2, 0], [6, 5]]) + qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1]) + + with pytest.raises(ValueError, match=r"Sample is out of bounds"): + out = [[-2, 0], [6, 5], [8, 2.5]] + bounds = np.array([[-2, 0], [6, 5]]) + qmc.scale(out, l_bounds=bounds[0], u_bounds=bounds[1], + reverse=True) + + def test_discrepancy(self): + space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]]) + space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0) + space_2 = np.array([[1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 6]]) + space_2 = (2.0 * space_2 - 1.0) / (2.0 * 6.0) + + # From Fang et al. Design and modeling for computer experiments, 2006 + assert_allclose(qmc.discrepancy(space_1), 0.0081, atol=1e-4) + assert_allclose(qmc.discrepancy(space_2), 0.0105, atol=1e-4) + + # From Zhou Y.-D. et al. Mixture discrepancy for quasi-random point + # sets. Journal of Complexity, 29 (3-4), pp. 283-301, 2013. + # Example 4 on Page 298 + sample = np.array([[2, 1, 1, 2, 2, 2], + [1, 2, 2, 2, 2, 2], + [2, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 2, 2], + [1, 2, 2, 2, 1, 1], + [2, 2, 2, 2, 1, 1], + [2, 2, 2, 1, 2, 2]]) + sample = (2.0 * sample - 1.0) / (2.0 * 2.0) + + assert_allclose(qmc.discrepancy(sample, method='MD'), 2.5000, + atol=1e-4) + assert_allclose(qmc.discrepancy(sample, method='WD'), 1.3680, + atol=1e-4) + assert_allclose(qmc.discrepancy(sample, method='CD'), 0.3172, + atol=1e-4) + + # From Tim P. et al. Minimizing the L2 and Linf star discrepancies + # of a single point in the unit hypercube. JCAM, 2005 + # Table 1 on Page 283 + for dim in [2, 4, 8, 16, 32, 64]: + ref = np.sqrt(3**(-dim)) + assert_allclose(qmc.discrepancy(np.array([[1]*dim]), + method='L2-star'), ref) + + def test_discrepancy_errors(self): + sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]]) + + with pytest.raises( + ValueError, match=r"Sample is not in unit hypercube" + ): + qmc.discrepancy(sample) + + with pytest.raises(ValueError, match=r"Sample is not a 2D array"): + qmc.discrepancy([1, 3]) + + sample = [[0, 0], [1, 1], [0.5, 0.5]] + with pytest.raises(ValueError, match=r"'toto' is not a valid ..."): + qmc.discrepancy(sample, method="toto") + + def test_discrepancy_parallel(self, monkeypatch): + sample = np.array([[2, 1, 1, 2, 2, 2], + [1, 2, 2, 2, 2, 2], + [2, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 2, 2], + [1, 2, 2, 2, 1, 1], + [2, 2, 2, 2, 1, 1], + [2, 2, 2, 1, 2, 2]]) + sample = (2.0 * sample - 1.0) / (2.0 * 2.0) + + assert_allclose(qmc.discrepancy(sample, method='MD', workers=8), + 2.5000, + atol=1e-4) + assert_allclose(qmc.discrepancy(sample, method='WD', workers=8), + 1.3680, + atol=1e-4) + assert_allclose(qmc.discrepancy(sample, method='CD', workers=8), + 0.3172, + atol=1e-4) + + # From Tim P. et al. Minimizing the L2 and Linf star discrepancies + # of a single point in the unit hypercube. JCAM, 2005 + # Table 1 on Page 283 + for dim in [2, 4, 8, 16, 32, 64]: + ref = np.sqrt(3 ** (-dim)) + assert_allclose(qmc.discrepancy(np.array([[1] * dim]), + method='L2-star', workers=-1), ref) + + monkeypatch.setattr(os, 'cpu_count', lambda: None) + with pytest.raises(NotImplementedError, match="Cannot determine the"): + qmc.discrepancy(sample, workers=-1) + + with pytest.raises(ValueError, match="Invalid number of workers..."): + qmc.discrepancy(sample, workers=-2) + + def test_geometric_discrepancy_errors(self): + sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]]) + + with pytest.raises(ValueError, match=r"Sample is not in unit hypercube"): + qmc.geometric_discrepancy(sample) + + with pytest.raises(ValueError, match=r"Sample is not a 2D array"): + qmc.geometric_discrepancy([1, 3]) + + sample = [[0, 0], [1, 1], [0.5, 0.5]] + with pytest.raises(ValueError, match=r"'toto' is not a valid ..."): + qmc.geometric_discrepancy(sample, method="toto") + + sample = np.array([[0, 0], [0, 0], [0, 1]]) + with pytest.warns(UserWarning, match="Sample contains duplicate points."): + qmc.geometric_discrepancy(sample) + + sample = np.array([[0.5, 0.5]]) + with pytest.raises(ValueError, match="Sample must contain at least two points"): + qmc.geometric_discrepancy(sample) + + def test_geometric_discrepancy(self): + sample = np.array([[0, 0], [1, 1]]) + assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2)) + assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2)) + + sample = np.array([[0, 0], [0, 1], [0.5, 1]]) + assert_allclose(qmc.geometric_discrepancy(sample), 0.5) + assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), 0.75) + + sample = np.array([[0, 0], [0.25, 0.25], [1, 1]]) + assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2) / 4) + assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2) / 2) + assert_allclose(qmc.geometric_discrepancy(sample, metric="chebyshev"), 0.25) + assert_allclose( + qmc.geometric_discrepancy(sample, method="mst", metric="chebyshev"), 0.5 + ) + + rng = np.random.default_rng(191468432622931918890291693003068437394) + sample = qmc.LatinHypercube(d=3, rng=rng).random(50) + assert_allclose(qmc.geometric_discrepancy(sample), 0.05106012076093356) + assert_allclose( + qmc.geometric_discrepancy(sample, method='mst'), 0.19704396643366182 + ) + + @pytest.mark.xfail( + reason="minimum_spanning_tree ignores zero distances (#18892)", + strict=True, + ) + def test_geometric_discrepancy_mst_with_zero_distances(self): + sample = np.array([[0, 0], [0, 0], [0, 1]]) + assert_allclose(qmc.geometric_discrepancy(sample, method='mst'), 0.5) + + def test_update_discrepancy(self): + # From Fang et al. Design and modeling for computer experiments, 2006 + space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]]) + space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0) + + disc_init = qmc.discrepancy(space_1[:-1], iterative=True) + disc_iter = update_discrepancy(space_1[-1], space_1[:-1], disc_init) + + assert_allclose(disc_iter, 0.0081, atol=1e-4) + + # n QMCEngine: + # preserve use of `seed` during SPEC 7 transition because + # some tests rely on behavior with integer `seed` (which is + # different from behavior with integer `rng`) + if self.can_scramble: + return self.qmce(scramble=scramble, seed=rng, **kwargs) + else: + if scramble: + pytest.skip() + else: + return self.qmce(seed=rng, **kwargs) + + def reference(self, scramble: bool) -> np.ndarray: + return self.scramble_nd if scramble else self.unscramble_nd + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + def test_0dim(self, scramble): + engine = self.engine(d=0, scramble=scramble) + sample = engine.random(4) + assert_array_equal(np.empty((4, 0)), sample) + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + def test_0sample(self, scramble): + engine = self.engine(d=2, scramble=scramble) + sample = engine.random(0) + assert_array_equal(np.empty((0, 2)), sample) + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + def test_1sample(self, scramble): + engine = self.engine(d=2, scramble=scramble) + sample = engine.random(1) + assert (1, 2) == sample.shape + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + def test_bounds(self, scramble): + engine = self.engine(d=100, scramble=scramble) + sample = engine.random(512) + assert np.all(sample >= 0) + assert np.all(sample <= 1) + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + def test_sample(self, scramble): + ref_sample = self.reference(scramble=scramble) + engine = self.engine(d=2, scramble=scramble) + sample = engine.random(n=len(ref_sample)) + + assert_allclose(sample, ref_sample, atol=1e-1) + assert engine.num_generated == len(ref_sample) + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + def test_continuing(self, scramble): + engine = self.engine(d=2, scramble=scramble) + ref_sample = engine.random(n=8) + + engine = self.engine(d=2, scramble=scramble) + + n_half = len(ref_sample) // 2 + + _ = engine.random(n=n_half) + sample = engine.random(n=n_half) + assert_allclose(sample, ref_sample[n_half:], atol=1e-1) + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + @pytest.mark.parametrize( + "rng", + ( + 170382760648021597650530316304495310428, + np.random.default_rng(170382760648021597650530316304495310428), + None, + ), + ) + def test_reset(self, scramble, rng): + engine = self.engine(d=2, scramble=scramble, rng=rng) + ref_sample = engine.random(n=8) + + engine.reset() + assert engine.num_generated == 0 + + sample = engine.random(n=8) + assert_allclose(sample, ref_sample) + + @pytest.mark.parametrize("scramble", scramble, ids=ids) + def test_fast_forward(self, scramble): + engine = self.engine(d=2, scramble=scramble) + ref_sample = engine.random(n=8) + + engine = self.engine(d=2, scramble=scramble) + + engine.fast_forward(4) + sample = engine.random(n=4) + + assert_allclose(sample, ref_sample[4:], atol=1e-1) + + # alternate fast forwarding with sampling + engine.reset() + even_draws = [] + for i in range(8): + if i % 2 == 0: + even_draws.append(engine.random()) + else: + engine.fast_forward(1) + assert_allclose( + ref_sample[[i for i in range(8) if i % 2 == 0]], + np.concatenate(even_draws), + atol=1e-5 + ) + + @pytest.mark.parametrize("scramble", [True]) + def test_distribution(self, scramble): + d = 50 + engine = self.engine(d=d, scramble=scramble) + sample = engine.random(1024) + assert_allclose( + np.mean(sample, axis=0), np.repeat(0.5, d), atol=1e-2 + ) + assert_allclose( + np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=1e-2 + ) + assert_allclose( + np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=1e-2 + ) + + def test_raises_optimizer(self): + message = r"'toto' is not a valid optimization method" + with pytest.raises(ValueError, match=message): + self.engine(d=1, scramble=False, optimization="toto") + + @pytest.mark.parametrize( + "optimization,metric", + [ + ("random-CD", qmc.discrepancy), + ("lloyd", lambda sample: -_l1_norm(sample))] + ) + def test_optimizers(self, optimization, metric): + engine = self.engine(d=2, scramble=False) + sample_ref = engine.random(n=64) + metric_ref = metric(sample_ref) + + optimal_ = self.engine(d=2, scramble=False, optimization=optimization) + sample_ = optimal_.random(n=64) + metric_ = metric(sample_) + + assert metric_ < metric_ref + + def test_consume_prng_state(self): + rng = np.random.default_rng(0xa29cabb11cfdf44ff6cac8bec254c2a0) + sample = [] + for i in range(3): + engine = self.engine(d=2, scramble=True, rng=rng) + sample.append(engine.random(4)) + + with pytest.raises(AssertionError, match="Arrays are not equal"): + assert_equal(sample[0], sample[1]) + with pytest.raises(AssertionError, match="Arrays are not equal"): + assert_equal(sample[0], sample[2]) + + +class TestHalton(QMCEngineTests): + qmce = qmc.Halton + can_scramble = True + # theoretical values known from Van der Corput + unscramble_nd = np.array([[0, 0], [1 / 2, 1 / 3], + [1 / 4, 2 / 3], [3 / 4, 1 / 9], + [1 / 8, 4 / 9], [5 / 8, 7 / 9], + [3 / 8, 2 / 9], [7 / 8, 5 / 9]]) + # theoretical values unknown: convergence properties checked + scramble_nd = np.array([[0.50246036, 0.93382481], + [0.00246036, 0.26715815], + [0.75246036, 0.60049148], + [0.25246036, 0.8227137 ], + [0.62746036, 0.15604704], + [0.12746036, 0.48938037], + [0.87746036, 0.71160259], + [0.37746036, 0.04493592]]) + + def test_workers(self): + ref_sample = self.reference(scramble=True) + engine = self.engine(d=2, scramble=True) + sample = engine.random(n=len(ref_sample), workers=8) + + assert_allclose(sample, ref_sample, atol=1e-3) + + # worker + integers + engine.reset() + ref_sample = engine.integers(10) + engine.reset() + sample = engine.integers(10, workers=8) + assert_equal(sample, ref_sample) + + +class TestLHS(QMCEngineTests): + qmce = qmc.LatinHypercube + can_scramble = True + + def test_continuing(self, *args): + pytest.skip("Not applicable: not a sequence.") + + def test_fast_forward(self, *args): + pytest.skip("Not applicable: not a sequence.") + + def test_sample(self, *args): + pytest.skip("Not applicable: the value of reference sample is" + " implementation dependent.") + + @pytest.mark.parametrize("strength", [1, 2]) + @pytest.mark.parametrize("scramble", [False, True]) + @pytest.mark.parametrize("optimization", [None, "random-CD"]) + def test_sample_stratified(self, optimization, scramble, strength): + rng = np.random.default_rng(37511836202578819870665127532742111260) + p = 5 + n = p**2 + d = 6 + + engine = qmc.LatinHypercube(d=d, scramble=scramble, + strength=strength, + optimization=optimization, + rng=rng) + sample = engine.random(n=n) + assert sample.shape == (n, d) + assert engine.num_generated == n + + # centering stratifies samples in the middle of equal segments: + # * inter-sample distance is constant in 1D sub-projections + # * after ordering, columns are equal + expected1d = (np.arange(n) + 0.5) / n + expected = np.broadcast_to(expected1d, (d, n)).T + assert np.any(sample != expected) + + sorted_sample = np.sort(sample, axis=0) + tol = 0.5 / n if scramble else 0 + + assert_allclose(sorted_sample, expected, atol=tol) + assert np.any(sample - expected > tol) + + if strength == 2 and optimization is None: + unique_elements = np.arange(p) + desired = set(product(unique_elements, unique_elements)) + + for i, j in combinations(range(engine.d), 2): + samples_2d = sample[:, [i, j]] + res = (samples_2d * p).astype(int) + res_set = {tuple(row) for row in res} + assert_equal(res_set, desired) + + def test_optimizer_1d(self): + # discrepancy measures are invariant under permuting factors and runs + engine = self.engine(d=1, scramble=False) + sample_ref = engine.random(n=64) + + optimal_ = self.engine(d=1, scramble=False, optimization="random-CD") + sample_ = optimal_.random(n=64) + + assert_array_equal(sample_ref, sample_) + + def test_raises(self): + message = r"not a valid strength" + with pytest.raises(ValueError, match=message): + qmc.LatinHypercube(1, strength=3) + + message = r"n is not the square of a prime number" + with pytest.raises(ValueError, match=message): + engine = qmc.LatinHypercube(d=2, strength=2) + engine.random(16) + + message = r"n is not the square of a prime number" + with pytest.raises(ValueError, match=message): + engine = qmc.LatinHypercube(d=2, strength=2) + engine.random(5) # because int(sqrt(5)) would result in 2 + + message = r"n is too small for d" + with pytest.raises(ValueError, match=message): + engine = qmc.LatinHypercube(d=5, strength=2) + engine.random(9) + + +class TestSobol(QMCEngineTests): + qmce = qmc.Sobol + can_scramble = True + # theoretical values from Joe Kuo2010 + unscramble_nd = np.array([[0., 0.], + [0.5, 0.5], + [0.75, 0.25], + [0.25, 0.75], + [0.375, 0.375], + [0.875, 0.875], + [0.625, 0.125], + [0.125, 0.625]]) + + # theoretical values unknown: convergence properties checked + scramble_nd = np.array([[0.25331921, 0.41371179], + [0.8654213, 0.9821167], + [0.70097554, 0.03664616], + [0.18027647, 0.60895735], + [0.10521339, 0.21897069], + [0.53019685, 0.66619033], + [0.91122276, 0.34580743], + [0.45337471, 0.78912079]]) + + def test_warning(self): + with pytest.warns(UserWarning, match=r"The balance properties of " + r"Sobol' points"): + engine = qmc.Sobol(1) + engine.random(10) + + def test_random_base2(self): + engine = qmc.Sobol(2, scramble=False) + sample = engine.random_base2(2) + assert_array_equal(self.unscramble_nd[:4], sample) + + # resampling still having N=2**n + sample = engine.random_base2(2) + assert_array_equal(self.unscramble_nd[4:8], sample) + + # resampling again but leading to N!=2**n + with pytest.raises(ValueError, match=r"The balance properties of " + r"Sobol' points"): + engine.random_base2(2) + + def test_raise(self): + with pytest.raises(ValueError, match=r"Maximum supported " + r"dimensionality"): + qmc.Sobol(qmc.Sobol.MAXDIM + 1) + + with pytest.raises(ValueError, match=r"Maximum supported " + r"'bits' is 64"): + qmc.Sobol(1, bits=65) + + def test_high_dim(self): + engine = qmc.Sobol(1111, scramble=False) + count1 = Counter(engine.random().flatten().tolist()) + count2 = Counter(engine.random().flatten().tolist()) + assert_equal(count1, Counter({0.0: 1111})) + assert_equal(count2, Counter({0.5: 1111})) + + @pytest.mark.parametrize("bits", [2, 3]) + def test_bits(self, bits): + engine = qmc.Sobol(2, scramble=False, bits=bits) + ns = 2**bits + sample = engine.random(ns) + assert_array_equal(self.unscramble_nd[:ns], sample) + + with pytest.raises(ValueError, match="increasing `bits`"): + engine.random() + + def test_64bits(self): + engine = qmc.Sobol(2, scramble=False, bits=64) + sample = engine.random(8) + assert_array_equal(self.unscramble_nd, sample) + + +class TestPoisson(QMCEngineTests): + qmce = qmc.PoissonDisk + can_scramble = False + + def test_bounds(self, *args): + pytest.skip("Too costly in memory.") + + def test_fast_forward(self, *args): + pytest.skip("Not applicable: recursive process.") + + def test_sample(self, *args): + pytest.skip("Not applicable: the value of reference sample is" + " implementation dependent.") + + def test_continuing(self, *args): + # can continue a sampling, but will not preserve the same order + # because candidates are lost, so we will not select the same center + radius = 0.05 + ns = 6 + engine = self.engine(d=2, radius=radius, scramble=False) + + sample_init = engine.random(n=ns) + assert len(sample_init) <= ns + assert l2_norm(sample_init) >= radius + + sample_continued = engine.random(n=ns) + assert len(sample_continued) <= ns + assert l2_norm(sample_continued) >= radius + + sample = np.concatenate([sample_init, sample_continued], axis=0) + assert len(sample) <= ns * 2 + assert l2_norm(sample) >= radius + + def test_mindist(self): + rng = np.random.default_rng(132074951149370773672162394161442690287) + ns = 50 + + low, high = 0.08, 0.2 + radii = (high - low) * rng.random(5) + low + + dimensions = [1, 3, 4] + hypersphere_methods = ["volume", "surface"] + + gen = product(dimensions, radii, hypersphere_methods) + + for d, radius, hypersphere in gen: + engine = self.qmce( + d=d, radius=radius, hypersphere=hypersphere, rng=rng + ) + sample = engine.random(ns) + + assert len(sample) <= ns + assert l2_norm(sample) >= radius + + def test_fill_space(self): + radius = 0.2 + engine = self.qmce(d=2, radius=radius) + + sample = engine.fill_space() + # circle packing problem is np complex + assert l2_norm(sample) >= radius + + @pytest.mark.parametrize("l_bounds", [[-1, -2, -1], [1, 2, 1]]) + def test_sample_inside_lower_bounds(self, l_bounds): + radius = 0.2 + u_bounds=[3, 3, 2] + engine = self.qmce( + d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds + ) + sample = engine.random(30) + + for point in sample: + assert_array_less(point, u_bounds) + assert_array_less(l_bounds, point) + + @pytest.mark.parametrize("u_bounds", [[-1, -2, -1], [1, 2, 1]]) + def test_sample_inside_upper_bounds(self, u_bounds): + radius = 0.2 + l_bounds=[-3, -3, -2] + engine = self.qmce( + d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds + ) + sample = engine.random(30) + + for point in sample: + assert_array_less(point, u_bounds) + assert_array_less(l_bounds, point) + + def test_inconsistent_bound_value(self): + radius = 0.2 + l_bounds=[3, 2, 1] + u_bounds=[-1, -2, -1] + with pytest.raises( + ValueError, + match="Bounds are not consistent 'l_bounds' < 'u_bounds'"): + self.qmce(d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds) + + @pytest.mark.parametrize("u_bounds", [[-1, -2, -1], [-1, -2]]) + @pytest.mark.parametrize("l_bounds", [[3, 2]]) + def test_inconsistent_bounds(self, u_bounds, l_bounds): + radius = 0.2 + with pytest.raises( + ValueError, + match="'l_bounds' and 'u_bounds' must be broadcastable and respect" + " the sample dimension"): + self.qmce( + d=3, radius=radius, + l_bounds=l_bounds, u_bounds=u_bounds + ) + + def test_raises(self): + message = r"'toto' is not a valid hypersphere sampling" + with pytest.raises(ValueError, match=message): + qmc.PoissonDisk(1, hypersphere="toto") + + +class TestMultinomialQMC: + def test_validations(self): + # negative Ps + p = np.array([0.12, 0.26, -0.05, 0.35, 0.22]) + with pytest.raises(ValueError, match=r"Elements of pvals must " + r"be non-negative."): + qmc.MultinomialQMC(p, n_trials=10) + + # sum of P too large + p = np.array([0.12, 0.26, 0.1, 0.35, 0.22]) + message = r"Elements of pvals must sum to 1." + with pytest.raises(ValueError, match=message): + qmc.MultinomialQMC(p, n_trials=10) + + p = np.array([0.12, 0.26, 0.05, 0.35, 0.22]) + + message = r"Dimension of `engine` must be 1." + with pytest.raises(ValueError, match=message): + qmc.MultinomialQMC(p, n_trials=10, engine=qmc.Sobol(d=2)) + + message = r"`engine` must be an instance of..." + with pytest.raises(ValueError, match=message): + qmc.MultinomialQMC(p, n_trials=10, engine=np.random.default_rng()) + + @pytest.mark.filterwarnings('ignore::UserWarning') + def test_MultinomialBasicDraw(self): + rng = np.random.default_rng(6955663962957011631562466584467607969) + p = np.array([0.12, 0.26, 0.05, 0.35, 0.22]) + n_trials = 100 + expected = np.atleast_2d(n_trials * p).astype(int) + # preserve use of legacy keyword during SPEC 7 transition + engine = qmc.MultinomialQMC(p, n_trials=n_trials, seed=rng) + assert_allclose(engine.random(1), expected, atol=1) + + def test_MultinomialDistribution(self): + rng = np.random.default_rng(77797854505813727292048130876699859000) + p = np.array([0.12, 0.26, 0.05, 0.35, 0.22]) + engine = qmc.MultinomialQMC(p, n_trials=8192, rng=rng) + draws = engine.random(1) + assert_allclose(draws / np.sum(draws), np.atleast_2d(p), atol=1e-4) + + def test_FindIndex(self): + p_cumulative = np.array([0.1, 0.4, 0.45, 0.6, 0.75, 0.9, 0.99, 1.0]) + size = len(p_cumulative) + assert_equal(_test_find_index(p_cumulative, size, 0.0), 0) + assert_equal(_test_find_index(p_cumulative, size, 0.4), 2) + assert_equal(_test_find_index(p_cumulative, size, 0.44999), 2) + assert_equal(_test_find_index(p_cumulative, size, 0.45001), 3) + assert_equal(_test_find_index(p_cumulative, size, 1.0), size - 1) + + @pytest.mark.filterwarnings('ignore::UserWarning') + def test_other_engine(self): + # same as test_MultinomialBasicDraw with different engine + rng = np.random.default_rng(283753519042773243071753037669078065412) + p = np.array([0.12, 0.26, 0.05, 0.35, 0.22]) + n_trials = 100 + expected = np.atleast_2d(n_trials * p).astype(int) + base_engine = qmc.Sobol(1, scramble=True, rng=rng) + engine = qmc.MultinomialQMC(p, n_trials=n_trials, engine=base_engine, + rng=rng) + assert_allclose(engine.random(1), expected, atol=1) + + +class TestNormalQMC: + def test_NormalQMC(self): + # d = 1 + engine = qmc.MultivariateNormalQMC(mean=np.zeros(1)) + samples = engine.random() + assert_equal(samples.shape, (1, 1)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 1)) + # d = 2 + engine = qmc.MultivariateNormalQMC(mean=np.zeros(2)) + samples = engine.random() + assert_equal(samples.shape, (1, 2)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 2)) + + def test_NormalQMCInvTransform(self): + # d = 1 + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(1), inv_transform=True) + samples = engine.random() + assert_equal(samples.shape, (1, 1)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 1)) + # d = 2 + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(2), inv_transform=True) + samples = engine.random() + assert_equal(samples.shape, (1, 2)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 2)) + + def test_NormalQMCSeeded(self): + # test even dimension + rng = np.random.default_rng(274600237797326520096085022671371676017) + # preserve use of legacy keyword during SPEC 7 transition + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(2), inv_transform=False, seed=rng) + samples = engine.random(n=2) + samples_expected = np.array([[-0.932001, -0.522923], + [-1.477655, 0.846851]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + # test odd dimension + rng = np.random.default_rng(274600237797326520096085022671371676017) + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(3), inv_transform=False, rng=rng) + samples = engine.random(n=2) + samples_expected = np.array([[-0.932001, -0.522923, 0.036578], + [-1.778011, 0.912428, -0.065421]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + # same test with another engine + rng = np.random.default_rng(274600237797326520096085022671371676017) + base_engine = qmc.Sobol(4, scramble=True, rng=rng) + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(3), inv_transform=False, + engine=base_engine, rng=rng + ) + samples = engine.random(n=2) + samples_expected = np.array([[-0.932001, -0.522923, 0.036578], + [-1.778011, 0.912428, -0.065421]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + def test_NormalQMCSeededInvTransform(self): + # test even dimension + rng = np.random.default_rng(288527772707286126646493545351112463929) + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(2), rng=rng, inv_transform=True) + samples = engine.random(n=2) + samples_expected = np.array([[-0.913237, -0.964026], + [0.255904, 0.003068]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + # test odd dimension + rng = np.random.default_rng(288527772707286126646493545351112463929) + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(3), rng=rng, inv_transform=True) + samples = engine.random(n=2) + samples_expected = np.array([[-0.913237, -0.964026, 0.355501], + [0.699261, 2.90213 , -0.6418]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + def test_other_engine(self): + for d in (0, 1, 2): + base_engine = qmc.Sobol(d=d, scramble=False) + engine = qmc.MultivariateNormalQMC(mean=np.zeros(d), + engine=base_engine, + inv_transform=True) + samples = engine.random() + assert_equal(samples.shape, (1, d)) + + def test_NormalQMCShapiro(self): + rng = np.random.default_rng(13242) + engine = qmc.MultivariateNormalQMC(mean=np.zeros(2), rng=rng) + samples = engine.random(n=256) + assert all(np.abs(samples.mean(axis=0)) < 1e-2) + assert all(np.abs(samples.std(axis=0) - 1) < 1e-2) + # perform Shapiro-Wilk test for normality + for i in (0, 1): + _, pval = shapiro(samples[:, i]) + assert pval > 0.9 + # make sure samples are uncorrelated + cov = np.cov(samples.transpose()) + assert np.abs(cov[0, 1]) < 1e-2 + + def test_NormalQMCShapiroInvTransform(self): + rng = np.random.default_rng(32344554) + engine = qmc.MultivariateNormalQMC( + mean=np.zeros(2), inv_transform=True, rng=rng) + samples = engine.random(n=256) + assert all(np.abs(samples.mean(axis=0)) < 1e-2) + assert all(np.abs(samples.std(axis=0) - 1) < 1e-2) + # perform Shapiro-Wilk test for normality + for i in (0, 1): + _, pval = shapiro(samples[:, i]) + assert pval > 0.9 + # make sure samples are uncorrelated + cov = np.cov(samples.transpose()) + assert np.abs(cov[0, 1]) < 1e-2 + + +class TestMultivariateNormalQMC: + + def test_validations(self): + + message = r"Dimension of `engine` must be consistent" + with pytest.raises(ValueError, match=message): + qmc.MultivariateNormalQMC([0], engine=qmc.Sobol(d=2)) + + message = r"Dimension of `engine` must be consistent" + with pytest.raises(ValueError, match=message): + qmc.MultivariateNormalQMC([0, 0, 0], engine=qmc.Sobol(d=4)) + + message = r"`engine` must be an instance of..." + with pytest.raises(ValueError, match=message): + qmc.MultivariateNormalQMC([0, 0], engine=np.random.default_rng()) + + message = r"Covariance matrix not PSD." + with pytest.raises(ValueError, match=message): + qmc.MultivariateNormalQMC([0, 0], [[1, 2], [2, 1]]) + + message = r"Covariance matrix is not symmetric." + with pytest.raises(ValueError, match=message): + qmc.MultivariateNormalQMC([0, 0], [[1, 0], [2, 1]]) + + message = r"Dimension mismatch between mean and covariance." + with pytest.raises(ValueError, match=message): + qmc.MultivariateNormalQMC([0], [[1, 0], [0, 1]]) + + def test_MultivariateNormalQMCNonPD(self): + # try with non-pd but psd cov; should work + engine = qmc.MultivariateNormalQMC( + [0, 0, 0], [[1, 0, 1], [0, 1, 1], [1, 1, 2]], + ) + assert engine._corr_matrix is not None + + def test_MultivariateNormalQMC(self): + # d = 1 scalar + engine = qmc.MultivariateNormalQMC(mean=0, cov=5) + samples = engine.random() + assert_equal(samples.shape, (1, 1)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 1)) + + # d = 2 list + engine = qmc.MultivariateNormalQMC(mean=[0, 1], cov=[[1, 0], [0, 1]]) + samples = engine.random() + assert_equal(samples.shape, (1, 2)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 2)) + + # d = 3 np.array + mean = np.array([0, 1, 2]) + cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + engine = qmc.MultivariateNormalQMC(mean, cov) + samples = engine.random() + assert_equal(samples.shape, (1, 3)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 3)) + + def test_MultivariateNormalQMCInvTransform(self): + # d = 1 scalar + engine = qmc.MultivariateNormalQMC(mean=0, cov=5, inv_transform=True) + samples = engine.random() + assert_equal(samples.shape, (1, 1)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 1)) + + # d = 2 list + engine = qmc.MultivariateNormalQMC( + mean=[0, 1], cov=[[1, 0], [0, 1]], inv_transform=True, + ) + samples = engine.random() + assert_equal(samples.shape, (1, 2)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 2)) + + # d = 3 np.array + mean = np.array([0, 1, 2]) + cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + engine = qmc.MultivariateNormalQMC(mean, cov, inv_transform=True) + samples = engine.random() + assert_equal(samples.shape, (1, 3)) + samples = engine.random(n=5) + assert_equal(samples.shape, (5, 3)) + + def test_MultivariateNormalQMCSeeded(self): + # test even dimension + rng = np.random.default_rng(180182791534511062935571481899241825000) + a = rng.standard_normal((2, 2)) + A = a @ a.transpose() + np.diag(rng.random(2)) + engine = qmc.MultivariateNormalQMC(np.array([0, 0]), A, + inv_transform=False, rng=rng) + samples = engine.random(n=2) + samples_expected = np.array([[-0.64419, -0.882413], + [0.837199, 2.045301]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + # test odd dimension + rng = np.random.default_rng(180182791534511062935571481899241825000) + a = rng.standard_normal((3, 3)) + A = a @ a.transpose() + np.diag(rng.random(3)) + engine = qmc.MultivariateNormalQMC(np.array([0, 0, 0]), A, + inv_transform=False, rng=rng) + samples = engine.random(n=2) + samples_expected = np.array([[-0.693853, -1.265338, -0.088024], + [1.620193, 2.679222, 0.457343]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + def test_MultivariateNormalQMCSeededInvTransform(self): + # test even dimension + rng = np.random.default_rng(224125808928297329711992996940871155974) + a = rng.standard_normal((2, 2)) + A = a @ a.transpose() + np.diag(rng.random(2)) + engine = qmc.MultivariateNormalQMC( + np.array([0, 0]), A, rng=rng, inv_transform=True + ) + samples = engine.random(n=2) + samples_expected = np.array([[0.682171, -3.114233], + [-0.098463, 0.668069]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + # test odd dimension + rng = np.random.default_rng(224125808928297329711992996940871155974) + a = rng.standard_normal((3, 3)) + A = a @ a.transpose() + np.diag(rng.random(3)) + engine = qmc.MultivariateNormalQMC( + np.array([0, 0, 0]), A, rng=rng, inv_transform=True + ) + samples = engine.random(n=2) + samples_expected = np.array([[0.988061, -1.644089, -0.877035], + [-1.771731, 1.096988, 2.024744]]) + assert_allclose(samples, samples_expected, atol=1e-4) + + def test_MultivariateNormalQMCShapiro(self): + # test the standard case + rng = np.random.default_rng(188960007281846377164494575845971640) + engine = qmc.MultivariateNormalQMC( + mean=[0, 0], cov=[[1, 0], [0, 1]], rng=rng + ) + samples = engine.random(n=256) + assert all(np.abs(samples.mean(axis=0)) < 1e-2) + assert all(np.abs(samples.std(axis=0) - 1) < 1e-2) + # perform Shapiro-Wilk test for normality + for i in (0, 1): + _, pval = shapiro(samples[:, i]) + assert pval > 0.9 + # make sure samples are uncorrelated + cov = np.cov(samples.transpose()) + assert np.abs(cov[0, 1]) < 1e-2 + + # test the correlated, non-zero mean case + engine = qmc.MultivariateNormalQMC( + mean=[1.0, 2.0], cov=[[1.5, 0.5], [0.5, 1.5]], rng=rng + ) + samples = engine.random(n=256) + assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2) + assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2) + # perform Shapiro-Wilk test for normality + for i in (0, 1): + _, pval = shapiro(samples[:, i]) + assert pval > 0.9 + # check covariance + cov = np.cov(samples.transpose()) + assert np.abs(cov[0, 1] - 0.5) < 1e-2 + + def test_MultivariateNormalQMCShapiroInvTransform(self): + # test the standard case + rng = np.random.default_rng(200089821034563288698994840831440331329) + engine = qmc.MultivariateNormalQMC( + mean=[0, 0], cov=[[1, 0], [0, 1]], rng=rng, inv_transform=True + ) + samples = engine.random(n=256) + assert all(np.abs(samples.mean(axis=0)) < 1e-2) + assert all(np.abs(samples.std(axis=0) - 1) < 1e-2) + # perform Shapiro-Wilk test for normality + for i in (0, 1): + _, pval = shapiro(samples[:, i]) + assert pval > 0.9 + # make sure samples are uncorrelated + cov = np.cov(samples.transpose()) + assert np.abs(cov[0, 1]) < 1e-2 + + # test the correlated, non-zero mean case + engine = qmc.MultivariateNormalQMC( + mean=[1.0, 2.0], + cov=[[1.5, 0.5], [0.5, 1.5]], + rng=rng, + inv_transform=True, + ) + samples = engine.random(n=256) + assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2) + assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2) + # perform Shapiro-Wilk test for normality + for i in (0, 1): + _, pval = shapiro(samples[:, i]) + assert pval > 0.9 + # check covariance + cov = np.cov(samples.transpose()) + assert np.abs(cov[0, 1] - 0.5) < 1e-2 + + def test_MultivariateNormalQMCDegenerate(self): + # X, Y iid standard Normal and Z = X + Y, random vector (X, Y, Z) + rng = np.random.default_rng(16320637417581448357869821654290448620) + engine = qmc.MultivariateNormalQMC( + mean=[0.0, 0.0, 0.0], + cov=[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 2.0]], + rng=rng, + ) + samples = engine.random(n=512) + assert all(np.abs(samples.mean(axis=0)) < 1e-2) + assert np.abs(np.std(samples[:, 0]) - 1) < 1e-2 + assert np.abs(np.std(samples[:, 1]) - 1) < 1e-2 + assert np.abs(np.std(samples[:, 2]) - np.sqrt(2)) < 1e-2 + for i in (0, 1, 2): + _, pval = shapiro(samples[:, i]) + assert pval > 0.8 + cov = np.cov(samples.transpose()) + assert np.abs(cov[0, 1]) < 1e-2 + assert np.abs(cov[0, 2] - 1) < 1e-2 + # check to see if X + Y = Z almost exactly + assert all(np.abs(samples[:, 0] + samples[:, 1] - samples[:, 2]) + < 1e-5) + + +class TestLloyd: + def test_lloyd(self): + # quite sensible seed as it can go up before going further down + rng = np.random.RandomState(1809831) + sample = rng.uniform(0, 1, size=(128, 2)) + base_l1 = _l1_norm(sample) + base_l2 = l2_norm(sample) + + for _ in range(4): + sample_lloyd = _lloyd_centroidal_voronoi_tessellation( + sample, maxiter=1, + ) + curr_l1 = _l1_norm(sample_lloyd) + curr_l2 = l2_norm(sample_lloyd) + + # higher is better for the distance measures + assert base_l1 < curr_l1 + assert base_l2 < curr_l2 + + base_l1 = curr_l1 + base_l2 = curr_l2 + + sample = sample_lloyd + + def test_lloyd_non_mutating(self): + """ + Verify that the input samples are not mutated in place and that they do + not share memory with the output. + """ + sample_orig = np.array([[0.1, 0.1], + [0.1, 0.2], + [0.2, 0.1], + [0.2, 0.2]]) + sample_copy = sample_orig.copy() + new_sample = _lloyd_centroidal_voronoi_tessellation( + sample=sample_orig + ) + assert_allclose(sample_orig, sample_copy) + assert not np.may_share_memory(sample_orig, new_sample) + + def test_lloyd_errors(self): + with pytest.raises(ValueError, match=r"`sample` is not a 2D array"): + sample = [0, 1, 0.5] + _lloyd_centroidal_voronoi_tessellation(sample) + + msg = r"`sample` dimension is not >= 2" + with pytest.raises(ValueError, match=msg): + sample = [[0], [0.4], [1]] + _lloyd_centroidal_voronoi_tessellation(sample) + + msg = r"`sample` is not in unit hypercube" + with pytest.raises(ValueError, match=msg): + sample = [[-1.1, 0], [0.1, 0.4], [1, 2]] + _lloyd_centroidal_voronoi_tessellation(sample) + + +# mindist +def l2_norm(sample): + return distance.pdist(sample).min() + + +@pytest.mark.parametrize('engine', [qmc.Halton, qmc.Sobol, + qmc.LatinHypercube, qmc.PoissonDisk]) +def test_deterministic(engine): + seed_number = 2359834584 + + rng = np.random.RandomState(seed_number) + res1 = engine(d=1, seed=rng).random(4) + rng = np.random.RandomState(seed_number) + res2 = engine(d=1, seed=rng).random(4) + assert_equal(res1, res2) + + rng = np.random.default_rng(seed_number) + res1 = engine(d=1, seed=rng).random(4) + res2 = engine(d=1, rng=seed_number).random(4) + assert_equal(res1, res2) + rng = np.random.default_rng(seed_number) + res3 = engine(d=1, rng=rng).random(4) + assert_equal(res2, res1) + assert_equal(res3, res1) + + message = "got multiple values for argument now known as `rng`" + with pytest.raises(TypeError, match=message): + engine(d=1, rng=seed_number, seed=seed_number) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_rank.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..08f6e13585dc61665ec6b6e733de87462e90002b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_rank.py @@ -0,0 +1,338 @@ +import numpy as np +from numpy.testing import assert_equal, assert_array_equal +import pytest + +from scipy.conftest import skip_xp_invalid_arg +from scipy.stats import rankdata, tiecorrect +from scipy._lib._util import np_long + + +class TestTieCorrect: + + def test_empty(self): + """An empty array requires no correction, should return 1.0.""" + ranks = np.array([], dtype=np.float64) + c = tiecorrect(ranks) + assert_equal(c, 1.0) + + def test_one(self): + """A single element requires no correction, should return 1.0.""" + ranks = np.array([1.0], dtype=np.float64) + c = tiecorrect(ranks) + assert_equal(c, 1.0) + + def test_no_correction(self): + """Arrays with no ties require no correction.""" + ranks = np.arange(2.0) + c = tiecorrect(ranks) + assert_equal(c, 1.0) + ranks = np.arange(3.0) + c = tiecorrect(ranks) + assert_equal(c, 1.0) + + def test_basic(self): + """Check a few basic examples of the tie correction factor.""" + # One tie of two elements + ranks = np.array([1.0, 2.5, 2.5]) + c = tiecorrect(ranks) + T = 2.0 + N = ranks.size + expected = 1.0 - (T**3 - T) / (N**3 - N) + assert_equal(c, expected) + + # One tie of two elements (same as above, but tie is not at the end) + ranks = np.array([1.5, 1.5, 3.0]) + c = tiecorrect(ranks) + T = 2.0 + N = ranks.size + expected = 1.0 - (T**3 - T) / (N**3 - N) + assert_equal(c, expected) + + # One tie of three elements + ranks = np.array([1.0, 3.0, 3.0, 3.0]) + c = tiecorrect(ranks) + T = 3.0 + N = ranks.size + expected = 1.0 - (T**3 - T) / (N**3 - N) + assert_equal(c, expected) + + # Two ties, lengths 2 and 3. + ranks = np.array([1.5, 1.5, 4.0, 4.0, 4.0]) + c = tiecorrect(ranks) + T1 = 2.0 + T2 = 3.0 + N = ranks.size + expected = 1.0 - ((T1**3 - T1) + (T2**3 - T2)) / (N**3 - N) + assert_equal(c, expected) + + def test_overflow(self): + ntie, k = 2000, 5 + a = np.repeat(np.arange(k), ntie) + n = a.size # ntie * k + out = tiecorrect(rankdata(a)) + assert_equal(out, 1.0 - k * (ntie**3 - ntie) / float(n**3 - n)) + + +class TestRankData: + + def test_empty(self): + """stats.rankdata([]) should return an empty array.""" + a = np.array([], dtype=int) + r = rankdata(a) + assert_array_equal(r, np.array([], dtype=np.float64)) + r = rankdata([]) + assert_array_equal(r, np.array([], dtype=np.float64)) + + @pytest.mark.parametrize("shape", [(0, 1, 2)]) + @pytest.mark.parametrize("axis", [None, *range(3)]) + def test_empty_multidim(self, shape, axis): + a = np.empty(shape, dtype=int) + r = rankdata(a, axis=axis) + expected_shape = (0,) if axis is None else shape + assert_equal(r.shape, expected_shape) + assert_equal(r.dtype, np.float64) + + def test_one(self): + """Check stats.rankdata with an array of length 1.""" + data = [100] + a = np.array(data, dtype=int) + r = rankdata(a) + assert_array_equal(r, np.array([1.0], dtype=np.float64)) + r = rankdata(data) + assert_array_equal(r, np.array([1.0], dtype=np.float64)) + + def test_basic(self): + """Basic tests of stats.rankdata.""" + data = [100, 10, 50] + expected = np.array([3.0, 1.0, 2.0], dtype=np.float64) + a = np.array(data, dtype=int) + r = rankdata(a) + assert_array_equal(r, expected) + r = rankdata(data) + assert_array_equal(r, expected) + + data = [40, 10, 30, 10, 50] + expected = np.array([4.0, 1.5, 3.0, 1.5, 5.0], dtype=np.float64) + a = np.array(data, dtype=int) + r = rankdata(a) + assert_array_equal(r, expected) + r = rankdata(data) + assert_array_equal(r, expected) + + data = [20, 20, 20, 10, 10, 10] + expected = np.array([5.0, 5.0, 5.0, 2.0, 2.0, 2.0], dtype=np.float64) + a = np.array(data, dtype=int) + r = rankdata(a) + assert_array_equal(r, expected) + r = rankdata(data) + assert_array_equal(r, expected) + # The docstring states explicitly that the argument is flattened. + a2d = a.reshape(2, 3) + r = rankdata(a2d) + assert_array_equal(r, expected) + + @skip_xp_invalid_arg + def test_rankdata_object_string(self): + + def min_rank(a): + return [1 + sum(i < j for i in a) for j in a] + + def max_rank(a): + return [sum(i <= j for i in a) for j in a] + + def ordinal_rank(a): + return min_rank([(x, i) for i, x in enumerate(a)]) + + def average_rank(a): + return [(i + j) / 2.0 for i, j in zip(min_rank(a), max_rank(a))] + + def dense_rank(a): + b = np.unique(a) + return [1 + sum(i < j for i in b) for j in a] + + rankf = dict(min=min_rank, max=max_rank, ordinal=ordinal_rank, + average=average_rank, dense=dense_rank) + + def check_ranks(a): + for method in 'min', 'max', 'dense', 'ordinal', 'average': + out = rankdata(a, method=method) + assert_array_equal(out, rankf[method](a)) + + val = ['foo', 'bar', 'qux', 'xyz', 'abc', 'efg', 'ace', 'qwe', 'qaz'] + check_ranks(np.random.choice(val, 200)) + check_ranks(np.random.choice(val, 200).astype('object')) + + val = np.array([0, 1, 2, 2.718, 3, 3.141], dtype='object') + check_ranks(np.random.choice(val, 200).astype('object')) + + def test_large_int(self): + data = np.array([2**60, 2**60+1], dtype=np.uint64) + r = rankdata(data) + assert_array_equal(r, [1.0, 2.0]) + + data = np.array([2**60, 2**60+1], dtype=np.int64) + r = rankdata(data) + assert_array_equal(r, [1.0, 2.0]) + + data = np.array([2**60, -2**60+1], dtype=np.int64) + r = rankdata(data) + assert_array_equal(r, [2.0, 1.0]) + + def test_big_tie(self): + for n in [10000, 100000, 1000000]: + data = np.ones(n, dtype=int) + r = rankdata(data) + expected_rank = 0.5 * (n + 1) + assert_array_equal(r, expected_rank * data, + "test failed with n=%d" % n) + + def test_axis(self): + data = [[0, 2, 1], + [4, 2, 2]] + expected0 = [[1., 1.5, 1.], + [2., 1.5, 2.]] + r0 = rankdata(data, axis=0) + assert_array_equal(r0, expected0) + expected1 = [[1., 3., 2.], + [3., 1.5, 1.5]] + r1 = rankdata(data, axis=1) + assert_array_equal(r1, expected1) + + methods = ["average", "min", "max", "dense", "ordinal"] + dtypes = [np.float64] + [np_long]*4 + + @pytest.mark.parametrize("axis", [0, 1]) + @pytest.mark.parametrize("method, dtype", zip(methods, dtypes)) + def test_size_0_axis(self, axis, method, dtype): + shape = (3, 0) + data = np.zeros(shape) + r = rankdata(data, method=method, axis=axis) + assert_equal(r.shape, shape) + assert_equal(r.dtype, dtype) + + @pytest.mark.parametrize('axis', range(3)) + @pytest.mark.parametrize('method', methods) + def test_nan_policy_omit_3d(self, axis, method): + shape = (20, 21, 22) + rng = np.random.RandomState(23983242) + + a = rng.random(size=shape) + i = rng.random(size=shape) < 0.4 + j = rng.random(size=shape) < 0.1 + k = rng.random(size=shape) < 0.1 + a[i] = np.nan + a[j] = -np.inf + a[k] - np.inf + + def rank_1d_omit(a, method): + out = np.zeros_like(a) + i = np.isnan(a) + a_compressed = a[~i] + res = rankdata(a_compressed, method) + out[~i] = res + out[i] = np.nan + return out + + def rank_omit(a, method, axis): + return np.apply_along_axis(lambda a: rank_1d_omit(a, method), + axis, a) + + res = rankdata(a, method, axis=axis, nan_policy='omit') + res0 = rank_omit(a, method, axis=axis) + + assert_array_equal(res, res0) + + def test_nan_policy_2d_axis_none(self): + # 2 2d-array test with axis=None + data = [[0, np.nan, 3], + [4, 2, np.nan], + [1, 2, 2]] + assert_array_equal(rankdata(data, axis=None, nan_policy='omit'), + [1., np.nan, 6., 7., 4., np.nan, 2., 4., 4.]) + assert_array_equal(rankdata(data, axis=None, nan_policy='propagate'), + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, + np.nan, np.nan, np.nan]) + + def test_nan_policy_raise(self): + # 1 1d-array test + data = [0, 2, 3, -2, np.nan, np.nan] + with pytest.raises(ValueError, match="The input contains nan"): + rankdata(data, nan_policy='raise') + + # 2 2d-array test + data = [[0, np.nan, 3], + [4, 2, np.nan], + [np.nan, 2, 2]] + + with pytest.raises(ValueError, match="The input contains nan"): + rankdata(data, axis=0, nan_policy="raise") + + with pytest.raises(ValueError, match="The input contains nan"): + rankdata(data, axis=1, nan_policy="raise") + + def test_nan_policy_propagate(self): + # 1 1d-array test + data = [0, 2, 3, -2, np.nan, np.nan] + assert_array_equal(rankdata(data, nan_policy='propagate'), + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]) + + # 2 2d-array test + data = [[0, np.nan, 3], + [4, 2, np.nan], + [1, 2, 2]] + assert_array_equal(rankdata(data, axis=0, nan_policy='propagate'), + [[1, np.nan, np.nan], + [3, np.nan, np.nan], + [2, np.nan, np.nan]]) + assert_array_equal(rankdata(data, axis=1, nan_policy='propagate'), + [[np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan], + [1, 2.5, 2.5]]) + + +_cases = ( + # values, method, expected + ([], 'average', []), + ([], 'min', []), + ([], 'max', []), + ([], 'dense', []), + ([], 'ordinal', []), + # + ([100], 'average', [1.0]), + ([100], 'min', [1.0]), + ([100], 'max', [1.0]), + ([100], 'dense', [1.0]), + ([100], 'ordinal', [1.0]), + # + ([100, 100, 100], 'average', [2.0, 2.0, 2.0]), + ([100, 100, 100], 'min', [1.0, 1.0, 1.0]), + ([100, 100, 100], 'max', [3.0, 3.0, 3.0]), + ([100, 100, 100], 'dense', [1.0, 1.0, 1.0]), + ([100, 100, 100], 'ordinal', [1.0, 2.0, 3.0]), + # + ([100, 300, 200], 'average', [1.0, 3.0, 2.0]), + ([100, 300, 200], 'min', [1.0, 3.0, 2.0]), + ([100, 300, 200], 'max', [1.0, 3.0, 2.0]), + ([100, 300, 200], 'dense', [1.0, 3.0, 2.0]), + ([100, 300, 200], 'ordinal', [1.0, 3.0, 2.0]), + # + ([100, 200, 300, 200], 'average', [1.0, 2.5, 4.0, 2.5]), + ([100, 200, 300, 200], 'min', [1.0, 2.0, 4.0, 2.0]), + ([100, 200, 300, 200], 'max', [1.0, 3.0, 4.0, 3.0]), + ([100, 200, 300, 200], 'dense', [1.0, 2.0, 3.0, 2.0]), + ([100, 200, 300, 200], 'ordinal', [1.0, 2.0, 4.0, 3.0]), + # + ([100, 200, 300, 200, 100], 'average', [1.5, 3.5, 5.0, 3.5, 1.5]), + ([100, 200, 300, 200, 100], 'min', [1.0, 3.0, 5.0, 3.0, 1.0]), + ([100, 200, 300, 200, 100], 'max', [2.0, 4.0, 5.0, 4.0, 2.0]), + ([100, 200, 300, 200, 100], 'dense', [1.0, 2.0, 3.0, 2.0, 1.0]), + ([100, 200, 300, 200, 100], 'ordinal', [1.0, 3.0, 5.0, 4.0, 2.0]), + # + ([10] * 30, 'ordinal', np.arange(1.0, 31.0)), +) + + +def test_cases(): + for values, method, expected in _cases: + r = rankdata(values, method=method) + assert_array_equal(r, expected) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_relative_risk.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_relative_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..b75e64d929f319465b1f1d62af4fb2096c2ab2ac --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_relative_risk.py @@ -0,0 +1,95 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose, assert_equal +from scipy.stats.contingency import relative_risk + + +# Test just the calculation of the relative risk, including edge +# cases that result in a relative risk of 0, inf or nan. +@pytest.mark.parametrize( + 'exposed_cases, exposed_total, control_cases, control_total, expected_rr', + [(1, 4, 3, 8, 0.25 / 0.375), + (0, 10, 5, 20, 0), + (0, 10, 0, 20, np.nan), + (5, 15, 0, 20, np.inf)] +) +def test_relative_risk(exposed_cases, exposed_total, + control_cases, control_total, expected_rr): + result = relative_risk(exposed_cases, exposed_total, + control_cases, control_total) + assert_allclose(result.relative_risk, expected_rr, rtol=1e-13) + + +def test_relative_risk_confidence_interval(): + result = relative_risk(exposed_cases=16, exposed_total=128, + control_cases=24, control_total=256) + rr = result.relative_risk + ci = result.confidence_interval(confidence_level=0.95) + # The corresponding calculation in R using the epitools package. + # + # > library(epitools) + # > c <- matrix(c(232, 112, 24, 16), nrow=2) + # > result <- riskratio(c) + # > result$measure + # risk ratio with 95% C.I. + # Predictor estimate lower upper + # Exposed1 1.000000 NA NA + # Exposed2 1.333333 0.7347317 2.419628 + # + # The last line is the result that we want. + assert_allclose(rr, 4/3) + assert_allclose((ci.low, ci.high), (0.7347317, 2.419628), rtol=5e-7) + + +def test_relative_risk_ci_conflevel0(): + result = relative_risk(exposed_cases=4, exposed_total=12, + control_cases=5, control_total=30) + rr = result.relative_risk + assert_allclose(rr, 2.0, rtol=1e-14) + ci = result.confidence_interval(0) + assert_allclose((ci.low, ci.high), (2.0, 2.0), rtol=1e-12) + + +def test_relative_risk_ci_conflevel1(): + result = relative_risk(exposed_cases=4, exposed_total=12, + control_cases=5, control_total=30) + ci = result.confidence_interval(1) + assert_equal((ci.low, ci.high), (0, np.inf)) + + +def test_relative_risk_ci_edge_cases_00(): + result = relative_risk(exposed_cases=0, exposed_total=12, + control_cases=0, control_total=30) + assert_equal(result.relative_risk, np.nan) + ci = result.confidence_interval() + assert_equal((ci.low, ci.high), (np.nan, np.nan)) + + +def test_relative_risk_ci_edge_cases_01(): + result = relative_risk(exposed_cases=0, exposed_total=12, + control_cases=1, control_total=30) + assert_equal(result.relative_risk, 0) + ci = result.confidence_interval() + assert_equal((ci.low, ci.high), (0.0, np.nan)) + + +def test_relative_risk_ci_edge_cases_10(): + result = relative_risk(exposed_cases=1, exposed_total=12, + control_cases=0, control_total=30) + assert_equal(result.relative_risk, np.inf) + ci = result.confidence_interval() + assert_equal((ci.low, ci.high), (np.nan, np.inf)) + + +@pytest.mark.parametrize('ec, et, cc, ct', [(0, 0, 10, 20), + (-1, 10, 1, 5), + (1, 10, 0, 0), + (1, 10, -1, 4)]) +def test_relative_risk_bad_value(ec, et, cc, ct): + with pytest.raises(ValueError, match="must be an integer not less than"): + relative_risk(ec, et, cc, ct) + + +def test_relative_risk_bad_type(): + with pytest.raises(TypeError, match="must be an integer"): + relative_risk(1, 10, 2.0, 40) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_resampling.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_resampling.py new file mode 100644 index 0000000000000000000000000000000000000000..22d5d4d32c7085e038a7f735a01ae9f07008a3ab --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_resampling.py @@ -0,0 +1,2009 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose, assert_equal, suppress_warnings + +from scipy.conftest import array_api_compatible +from scipy._lib._util import rng_integers +from scipy._lib._array_api import array_namespace, is_numpy +from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal +from scipy import stats, special +from scipy.optimize import root + +from scipy.stats import bootstrap, monte_carlo_test, permutation_test, power +import scipy.stats._resampling as _resampling + + +def test_bootstrap_iv(): + + message = "`data` must be a sequence of samples." + with pytest.raises(ValueError, match=message): + bootstrap(1, np.mean) + + message = "`data` must contain at least one sample." + with pytest.raises(ValueError, match=message): + bootstrap(tuple(), np.mean) + + message = "each sample in `data` must contain two or more observations..." + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3], [1]), np.mean) + + message = ("When `paired is True`, all samples must have the same length ") + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3], [1, 2, 3, 4]), np.mean, paired=True) + + message = "`vectorized` must be `True`, `False`, or `None`." + with pytest.raises(ValueError, match=message): + bootstrap(1, np.mean, vectorized='ekki') + + message = "`axis` must be an integer." + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, axis=1.5) + + message = "could not convert string to float" + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, confidence_level='ni') + + message = "`n_resamples` must be a non-negative integer." + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, n_resamples=-1000) + + message = "`n_resamples` must be a non-negative integer." + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, n_resamples=1000.5) + + message = "`batch` must be a positive integer or None." + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, batch=-1000) + + message = "`batch` must be a positive integer or None." + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, batch=1000.5) + + message = "`method` must be in" + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, method='ekki') + + message = "`bootstrap_result` must have attribute `bootstrap_distribution'" + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, bootstrap_result=10) + + message = "Either `bootstrap_result.bootstrap_distribution.size`" + with pytest.raises(ValueError, match=message): + bootstrap(([1, 2, 3],), np.mean, n_resamples=0) + + message = "SeedSequence expects int or sequence of ints" + with pytest.raises(TypeError, match=message): + bootstrap(([1, 2, 3],), np.mean, rng='herring') + + +@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa']) +@pytest.mark.parametrize("axis", [0, 1, 2]) +def test_bootstrap_batch(method, axis): + # for one-sample statistics, batch size shouldn't affect the result + np.random.seed(0) + + x = np.random.rand(10, 11, 12) + # SPEC-007 leave one call with random_state to ensure it still works + res1 = bootstrap((x,), np.mean, batch=None, method=method, + random_state=0, axis=axis, n_resamples=100) + np.random.seed(0) + res2 = bootstrap((x,), np.mean, batch=10, method=method, + axis=axis, n_resamples=100) + + assert_equal(res2.confidence_interval.low, res1.confidence_interval.low) + assert_equal(res2.confidence_interval.high, res1.confidence_interval.high) + assert_equal(res2.standard_error, res1.standard_error) + + +@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa']) +def test_bootstrap_paired(method): + # test that `paired` works as expected + np.random.seed(0) + n = 100 + x = np.random.rand(n) + y = np.random.rand(n) + + def my_statistic(x, y, axis=-1): + return ((x-y)**2).mean(axis=axis) + + def my_paired_statistic(i, axis=-1): + a = x[i] + b = y[i] + res = my_statistic(a, b) + return res + + i = np.arange(len(x)) + + res1 = bootstrap((i,), my_paired_statistic, rng=0) + res2 = bootstrap((x, y), my_statistic, paired=True, rng=0) + + assert_allclose(res1.confidence_interval, res2.confidence_interval) + assert_allclose(res1.standard_error, res2.standard_error) + + +@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa']) +@pytest.mark.parametrize("axis", [0, 1, 2]) +@pytest.mark.parametrize("paired", [True, False]) +def test_bootstrap_vectorized(method, axis, paired): + # test that paired is vectorized as expected: when samples are tiled, + # CI and standard_error of each axis-slice is the same as those of the + # original 1d sample + + np.random.seed(0) + + def my_statistic(x, y, z, axis=-1): + return x.mean(axis=axis) + y.mean(axis=axis) + z.mean(axis=axis) + + shape = 10, 11, 12 + n_samples = shape[axis] + + x = np.random.rand(n_samples) + y = np.random.rand(n_samples) + z = np.random.rand(n_samples) + res1 = bootstrap((x, y, z), my_statistic, paired=paired, method=method, + rng=0, axis=0, n_resamples=100) + assert (res1.bootstrap_distribution.shape + == res1.standard_error.shape + (100,)) + + reshape = [1, 1, 1] + reshape[axis] = n_samples + x = np.broadcast_to(x.reshape(reshape), shape) + y = np.broadcast_to(y.reshape(reshape), shape) + z = np.broadcast_to(z.reshape(reshape), shape) + res2 = bootstrap((x, y, z), my_statistic, paired=paired, method=method, + rng=0, axis=axis, n_resamples=100) + + assert_allclose(res2.confidence_interval.low, + res1.confidence_interval.low) + assert_allclose(res2.confidence_interval.high, + res1.confidence_interval.high) + assert_allclose(res2.standard_error, res1.standard_error) + + result_shape = list(shape) + result_shape.pop(axis) + + assert_equal(res2.confidence_interval.low.shape, result_shape) + assert_equal(res2.confidence_interval.high.shape, result_shape) + assert_equal(res2.standard_error.shape, result_shape) + + +@pytest.mark.slow +@pytest.mark.xfail_on_32bit("MemoryError with BCa observed in CI") +@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa']) +def test_bootstrap_against_theory(method): + # based on https://www.statology.org/confidence-intervals-python/ + rng = np.random.default_rng(2442101192988600726) + data = stats.norm.rvs(loc=5, scale=2, size=5000, random_state=rng) + alpha = 0.95 + dist = stats.t(df=len(data)-1, loc=np.mean(data), scale=stats.sem(data)) + expected_interval = dist.interval(confidence=alpha) + expected_se = dist.std() + + config = dict(data=(data,), statistic=np.mean, n_resamples=5000, + method=method, rng=rng) + res = bootstrap(**config, confidence_level=alpha) + assert_allclose(res.confidence_interval, expected_interval, rtol=5e-4) + assert_allclose(res.standard_error, expected_se, atol=3e-4) + + config.update(dict(n_resamples=0, bootstrap_result=res)) + res = bootstrap(**config, confidence_level=alpha, alternative='less') + assert_allclose(res.confidence_interval.high, dist.ppf(alpha), rtol=5e-4) + + config.update(dict(n_resamples=0, bootstrap_result=res)) + res = bootstrap(**config, confidence_level=alpha, alternative='greater') + assert_allclose(res.confidence_interval.low, dist.ppf(1-alpha), rtol=5e-4) + + +tests_R = {"basic": (23.77, 79.12), + "percentile": (28.86, 84.21), + "BCa": (32.31, 91.43)} + + +@pytest.mark.parametrize("method, expected", tests_R.items()) +def test_bootstrap_against_R(method, expected): + # Compare against R's "boot" library + # library(boot) + + # stat <- function (x, a) { + # mean(x[a]) + # } + + # x <- c(10, 12, 12.5, 12.5, 13.9, 15, 21, 22, + # 23, 34, 50, 81, 89, 121, 134, 213) + + # # Use a large value so we get a few significant digits for the CI. + # n = 1000000 + # bootresult = boot(x, stat, n) + # result <- boot.ci(bootresult) + # print(result) + x = np.array([10, 12, 12.5, 12.5, 13.9, 15, 21, 22, + 23, 34, 50, 81, 89, 121, 134, 213]) + res = bootstrap((x,), np.mean, n_resamples=1000000, method=method, + rng=0) + assert_allclose(res.confidence_interval, expected, rtol=0.005) + + +tests_against_itself_1samp = {"basic": 1780, + "percentile": 1784, + "BCa": 1784} + + +def test_multisample_BCa_against_R(): + # Because bootstrap is stochastic, it's tricky to test against reference + # behavior. Here, we show that SciPy's BCa CI matches R wboot's BCa CI + # much more closely than the other SciPy CIs do. + + # arbitrary skewed data + x = [0.75859206, 0.5910282, -0.4419409, -0.36654601, + 0.34955357, -1.38835871, 0.76735821] + y = [1.41186073, 0.49775975, 0.08275588, 0.24086388, + 0.03567057, 0.52024419, 0.31966611, 1.32067634] + + # a multi-sample statistic for which the BCa CI tends to be different + # from the other CIs + def statistic(x, y, axis): + s1 = stats.skew(x, axis=axis) + s2 = stats.skew(y, axis=axis) + return s1 - s2 + + # compute confidence intervals using each method + rng = np.random.default_rng(468865032284792692) + + res_basic = stats.bootstrap((x, y), statistic, method='basic', + batch=100, rng=rng) + res_percent = stats.bootstrap((x, y), statistic, method='percentile', + batch=100, rng=rng) + res_bca = stats.bootstrap((x, y), statistic, method='bca', + batch=100, rng=rng) + + # compute midpoints so we can compare just one number for each + mid_basic = np.mean(res_basic.confidence_interval) + mid_percent = np.mean(res_percent.confidence_interval) + mid_bca = np.mean(res_bca.confidence_interval) + + # reference for BCA CI computed using R wboot package: + # library(wBoot) + # library(moments) + + # x = c(0.75859206, 0.5910282, -0.4419409, -0.36654601, + # 0.34955357, -1.38835871, 0.76735821) + # y = c(1.41186073, 0.49775975, 0.08275588, 0.24086388, + # 0.03567057, 0.52024419, 0.31966611, 1.32067634) + + # twoskew <- function(x1, y1) {skewness(x1) - skewness(y1)} + # boot.two.bca(x, y, skewness, conf.level = 0.95, + # R = 9999, stacked = FALSE) + mid_wboot = -1.5519 + + # compute percent difference relative to wboot BCA method + diff_basic = (mid_basic - mid_wboot)/abs(mid_wboot) + diff_percent = (mid_percent - mid_wboot)/abs(mid_wboot) + diff_bca = (mid_bca - mid_wboot)/abs(mid_wboot) + + # SciPy's BCa CI midpoint is much closer than that of the other methods + assert diff_basic < -0.15 + assert diff_percent > 0.15 + assert abs(diff_bca) < 0.03 + + +def test_BCa_acceleration_against_reference(): + # Compare the (deterministic) acceleration parameter for a multi-sample + # problem against a reference value. The example is from [1], but Efron's + # value seems inaccurate. Straightforward code for computing the + # reference acceleration (0.011008228344026734) is available at: + # https://github.com/scipy/scipy/pull/16455#issuecomment-1193400981 + + y = np.array([10, 27, 31, 40, 46, 50, 52, 104, 146]) + z = np.array([16, 23, 38, 94, 99, 141, 197]) + + def statistic(z, y, axis=0): + return np.mean(z, axis=axis) - np.mean(y, axis=axis) + + data = [z, y] + res = stats.bootstrap(data, statistic) + + axis = -1 + alpha = 0.95 + theta_hat_b = res.bootstrap_distribution + batch = 100 + _, _, a_hat = _resampling._bca_interval(data, statistic, axis, alpha, + theta_hat_b, batch) + assert_allclose(a_hat, 0.011008228344026734) + + +@pytest.mark.slow +@pytest.mark.parametrize("method, expected", + tests_against_itself_1samp.items()) +def test_bootstrap_against_itself_1samp(method, expected): + # The expected values in this test were generated using bootstrap + # to check for unintended changes in behavior. The test also makes sure + # that bootstrap works with multi-sample statistics and that the + # `axis` argument works as expected / function is vectorized. + np.random.seed(0) + + n = 100 # size of sample + n_resamples = 999 # number of bootstrap resamples used to form each CI + confidence_level = 0.9 + + # The true mean is 5 + dist = stats.norm(loc=5, scale=1) + stat_true = dist.mean() + + # Do the same thing 2000 times. (The code is fully vectorized.) + n_replications = 2000 + data = dist.rvs(size=(n_replications, n)) + res = bootstrap((data,), + statistic=np.mean, + confidence_level=confidence_level, + n_resamples=n_resamples, + batch=50, + method=method, + axis=-1) + ci = res.confidence_interval + + # ci contains vectors of lower and upper confidence interval bounds + ci_contains_true = np.sum((ci[0] < stat_true) & (stat_true < ci[1])) + assert ci_contains_true == expected + + # ci_contains_true is not inconsistent with confidence_level + pvalue = stats.binomtest(ci_contains_true, n_replications, + confidence_level).pvalue + assert pvalue > 0.1 + + +tests_against_itself_2samp = {"basic": 892, + "percentile": 890} + + +@pytest.mark.slow +@pytest.mark.parametrize("method, expected", + tests_against_itself_2samp.items()) +def test_bootstrap_against_itself_2samp(method, expected): + # The expected values in this test were generated using bootstrap + # to check for unintended changes in behavior. The test also makes sure + # that bootstrap works with multi-sample statistics and that the + # `axis` argument works as expected / function is vectorized. + np.random.seed(0) + + n1 = 100 # size of sample 1 + n2 = 120 # size of sample 2 + n_resamples = 999 # number of bootstrap resamples used to form each CI + confidence_level = 0.9 + + # The statistic we're interested in is the difference in means + def my_stat(data1, data2, axis=-1): + mean1 = np.mean(data1, axis=axis) + mean2 = np.mean(data2, axis=axis) + return mean1 - mean2 + + # The true difference in the means is -0.1 + dist1 = stats.norm(loc=0, scale=1) + dist2 = stats.norm(loc=0.1, scale=1) + stat_true = dist1.mean() - dist2.mean() + + # Do the same thing 1000 times. (The code is fully vectorized.) + n_replications = 1000 + data1 = dist1.rvs(size=(n_replications, n1)) + data2 = dist2.rvs(size=(n_replications, n2)) + res = bootstrap((data1, data2), + statistic=my_stat, + confidence_level=confidence_level, + n_resamples=n_resamples, + batch=50, + method=method, + axis=-1) + ci = res.confidence_interval + + # ci contains vectors of lower and upper confidence interval bounds + ci_contains_true = np.sum((ci[0] < stat_true) & (stat_true < ci[1])) + assert ci_contains_true == expected + + # ci_contains_true is not inconsistent with confidence_level + pvalue = stats.binomtest(ci_contains_true, n_replications, + confidence_level).pvalue + assert pvalue > 0.1 + + +@pytest.mark.parametrize("method", ["basic", "percentile"]) +@pytest.mark.parametrize("axis", [0, 1]) +def test_bootstrap_vectorized_3samp(method, axis): + def statistic(*data, axis=0): + # an arbitrary, vectorized statistic + return sum(sample.mean(axis) for sample in data) + + def statistic_1d(*data): + # the same statistic, not vectorized + for sample in data: + assert sample.ndim == 1 + return statistic(*data, axis=0) + + np.random.seed(0) + x = np.random.rand(4, 5) + y = np.random.rand(4, 5) + z = np.random.rand(4, 5) + res1 = bootstrap((x, y, z), statistic, vectorized=True, + axis=axis, n_resamples=100, method=method, rng=0) + res2 = bootstrap((x, y, z), statistic_1d, vectorized=False, + axis=axis, n_resamples=100, method=method, rng=0) + assert_allclose(res1.confidence_interval, res2.confidence_interval) + assert_allclose(res1.standard_error, res2.standard_error) + + +@pytest.mark.xfail_on_32bit("Failure is not concerning; see gh-14107") +@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"]) +@pytest.mark.parametrize("axis", [0, 1]) +def test_bootstrap_vectorized_1samp(method, axis): + def statistic(x, axis=0): + # an arbitrary, vectorized statistic + return x.mean(axis=axis) + + def statistic_1d(x): + # the same statistic, not vectorized + assert x.ndim == 1 + return statistic(x, axis=0) + + np.random.seed(0) + x = np.random.rand(4, 5) + res1 = bootstrap((x,), statistic, vectorized=True, axis=axis, + n_resamples=100, batch=None, method=method, + rng=0) + res2 = bootstrap((x,), statistic_1d, vectorized=False, axis=axis, + n_resamples=100, batch=10, method=method, + rng=0) + assert_allclose(res1.confidence_interval, res2.confidence_interval) + assert_allclose(res1.standard_error, res2.standard_error) + + +@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"]) +def test_bootstrap_degenerate(method): + data = 35 * [10000.] + if method == "BCa": + with np.errstate(invalid='ignore'): + msg = "The BCa confidence interval cannot be calculated" + with pytest.warns(stats.DegenerateDataWarning, match=msg): + res = bootstrap([data, ], np.mean, method=method) + assert_equal(res.confidence_interval, (np.nan, np.nan)) + else: + res = bootstrap([data, ], np.mean, method=method) + assert_equal(res.confidence_interval, (10000., 10000.)) + assert_equal(res.standard_error, 0) + + +@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"]) +def test_bootstrap_gh15678(method): + # Check that gh-15678 is fixed: when statistic function returned a Python + # float, method="BCa" failed when trying to add a dimension to the float + rng = np.random.default_rng(354645618886684) + dist = stats.norm(loc=2, scale=4) + data = dist.rvs(size=100, random_state=rng) + data = (data,) + res = bootstrap(data, stats.skew, method=method, n_resamples=100, + rng=np.random.default_rng(9563)) + # this always worked because np.apply_along_axis returns NumPy data type + ref = bootstrap(data, stats.skew, method=method, n_resamples=100, + rng=np.random.default_rng(9563), vectorized=False) + assert_allclose(res.confidence_interval, ref.confidence_interval) + assert_allclose(res.standard_error, ref.standard_error) + assert isinstance(res.standard_error, np.float64) + + +def test_bootstrap_min(): + # Check that gh-15883 is fixed: percentileofscore should + # behave according to the 'mean' behavior and not trigger nan for BCa + rng = np.random.default_rng(1891289180021102) + dist = stats.norm(loc=2, scale=4) + data = dist.rvs(size=100, random_state=rng) + true_min = np.min(data) + data = (data,) + res = bootstrap(data, np.min, method="BCa", n_resamples=100, + rng=np.random.default_rng(3942)) + assert true_min == res.confidence_interval.low + res2 = bootstrap(-np.array(data), np.max, method="BCa", n_resamples=100, + rng=np.random.default_rng(3942)) + assert_allclose(-res.confidence_interval.low, + res2.confidence_interval.high) + assert_allclose(-res.confidence_interval.high, + res2.confidence_interval.low) + + +@pytest.mark.parametrize("additional_resamples", [0, 1000]) +def test_re_bootstrap(additional_resamples): + # Test behavior of parameter `bootstrap_result` + rng = np.random.default_rng(8958153316228384) + x = rng.random(size=100) + + n1 = 1000 + n2 = additional_resamples + n3 = n1 + additional_resamples + + rng = np.random.default_rng(296689032789913033) + res = stats.bootstrap((x,), np.mean, n_resamples=n1, rng=rng, + confidence_level=0.95, method='percentile') + res = stats.bootstrap((x,), np.mean, n_resamples=n2, rng=rng, + confidence_level=0.90, method='BCa', + bootstrap_result=res) + + rng = np.random.default_rng(296689032789913033) + ref = stats.bootstrap((x,), np.mean, n_resamples=n3, rng=rng, + confidence_level=0.90, method='BCa') + + assert_allclose(res.standard_error, ref.standard_error, rtol=1e-14) + assert_allclose(res.confidence_interval, ref.confidence_interval, + rtol=1e-14) + + +@pytest.mark.xfail_on_32bit("Sensible to machine precision") +@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa']) +def test_bootstrap_alternative(method): + rng = np.random.default_rng(5894822712842015040) + dist = stats.norm(loc=2, scale=4) + data = (dist.rvs(size=(100), random_state=rng),) + + config = dict(data=data, statistic=np.std, rng=rng, axis=-1) + t = stats.bootstrap(**config, confidence_level=0.9) + + config.update(dict(n_resamples=0, bootstrap_result=t)) + l = stats.bootstrap(**config, confidence_level=0.95, alternative='less') + g = stats.bootstrap(**config, confidence_level=0.95, alternative='greater') + + assert_allclose(l.confidence_interval.high, t.confidence_interval.high, + rtol=1e-14) + assert_allclose(g.confidence_interval.low, t.confidence_interval.low, + rtol=1e-14) + assert np.isneginf(l.confidence_interval.low) + assert np.isposinf(g.confidence_interval.high) + + with pytest.raises(ValueError, match='`alternative` must be one of'): + stats.bootstrap(**config, alternative='ekki-ekki') + + +def test_jackknife_resample(): + shape = 3, 4, 5, 6 + np.random.seed(0) + x = np.random.rand(*shape) + y = next(_resampling._jackknife_resample(x)) + + for i in range(shape[-1]): + # each resample is indexed along second to last axis + # (last axis is the one the statistic will be taken over / consumed) + slc = y[..., i, :] + expected = np.delete(x, i, axis=-1) + + assert np.array_equal(slc, expected) + + y2 = np.concatenate(list(_resampling._jackknife_resample(x, batch=2)), + axis=-2) + assert np.array_equal(y2, y) + + +@pytest.mark.parametrize("rng_name", ["RandomState", "default_rng"]) +def test_bootstrap_resample(rng_name): + rng = getattr(np.random, rng_name, None) + if rng is None: + pytest.skip(f"{rng_name} not available.") + rng1 = rng(0) + rng2 = rng(0) + + n_resamples = 10 + shape = 3, 4, 5, 6 + + np.random.seed(0) + x = np.random.rand(*shape) + y = _resampling._bootstrap_resample(x, n_resamples, rng=rng1) + + for i in range(n_resamples): + # each resample is indexed along second to last axis + # (last axis is the one the statistic will be taken over / consumed) + slc = y[..., i, :] + + js = rng_integers(rng2, 0, shape[-1], shape[-1]) + expected = x[..., js] + + assert np.array_equal(slc, expected) + + +@pytest.mark.parametrize("score", [0, 0.5, 1]) +@pytest.mark.parametrize("axis", [0, 1, 2]) +def test_percentile_of_score(score, axis): + shape = 10, 20, 30 + np.random.seed(0) + x = np.random.rand(*shape) + p = _resampling._percentile_of_score(x, score, axis=-1) + + def vectorized_pos(a, score, axis): + return np.apply_along_axis(stats.percentileofscore, axis, a, score) + + p2 = vectorized_pos(x, score, axis=-1)/100 + + assert_allclose(p, p2, 1e-15) + + +def test_percentile_along_axis(): + # the difference between _percentile_along_axis and np.percentile is that + # np.percentile gets _all_ the qs for each axis slice, whereas + # _percentile_along_axis gets the q corresponding with each axis slice + + shape = 10, 20 + np.random.seed(0) + x = np.random.rand(*shape) + q = np.random.rand(*shape[:-1]) * 100 + y = _resampling._percentile_along_axis(x, q) + + for i in range(shape[0]): + res = y[i] + expected = np.percentile(x[i], q[i], axis=-1) + assert_allclose(res, expected, 1e-15) + + +@pytest.mark.parametrize("axis", [0, 1, 2]) +def test_vectorize_statistic(axis): + # test that _vectorize_statistic vectorizes a statistic along `axis` + + def statistic(*data, axis): + # an arbitrary, vectorized statistic + return sum(sample.mean(axis) for sample in data) + + def statistic_1d(*data): + # the same statistic, not vectorized + for sample in data: + assert sample.ndim == 1 + return statistic(*data, axis=0) + + # vectorize the non-vectorized statistic + statistic2 = _resampling._vectorize_statistic(statistic_1d) + + np.random.seed(0) + x = np.random.rand(4, 5, 6) + y = np.random.rand(4, 1, 6) + z = np.random.rand(1, 5, 6) + + res1 = statistic(x, y, z, axis=axis) + res2 = statistic2(x, y, z, axis=axis) + assert_allclose(res1, res2) + + +@pytest.mark.slow +@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"]) +def test_vector_valued_statistic(method): + # Generate 95% confidence interval around MLE of normal distribution + # parameters. Repeat 100 times, each time on sample of size 100. + # Check that confidence interval contains true parameters ~95 times. + # Confidence intervals are estimated and stochastic; a test failure + # does not necessarily indicate that something is wrong. More important + # than values of `counts` below is that the shapes of the outputs are + # correct. + + rng = np.random.default_rng(2196847219) + params = 1, 0.5 + sample = stats.norm.rvs(*params, size=(100, 100), random_state=rng) + + def statistic(data, axis): + return np.asarray([np.mean(data, axis), + np.std(data, axis, ddof=1)]) + + res = bootstrap((sample,), statistic, method=method, axis=-1, + n_resamples=9999, batch=200) + + counts = np.sum((res.confidence_interval.low.T < params) + & (res.confidence_interval.high.T > params), + axis=0) + assert np.all(counts >= 90) + assert np.all(counts <= 100) + assert res.confidence_interval.low.shape == (2, 100) + assert res.confidence_interval.high.shape == (2, 100) + assert res.standard_error.shape == (2, 100) + assert res.bootstrap_distribution.shape == (2, 100, 9999) + + +@pytest.mark.slow +@pytest.mark.filterwarnings('ignore::RuntimeWarning') +def test_vector_valued_statistic_gh17715(): + # gh-17715 reported a mistake introduced in the extension of BCa to + # multi-sample statistics; a `len` should have been `.shape[-1]`. Check + # that this is resolved. + + rng = np.random.default_rng(141921000979291141) + + def concordance(x, y, axis): + xm = x.mean(axis) + ym = y.mean(axis) + cov = ((x - xm[..., None]) * (y - ym[..., None])).mean(axis) + return (2 * cov) / (x.var(axis) + y.var(axis) + (xm - ym) ** 2) + + def statistic(tp, tn, fp, fn, axis): + actual = tp + fp + expected = tp + fn + return np.nan_to_num(concordance(actual, expected, axis)) + + def statistic_extradim(*args, axis): + return statistic(*args, axis)[np.newaxis, ...] + + data = [[4, 0, 0, 2], # (tp, tn, fp, fn) + [2, 1, 2, 1], + [0, 6, 0, 0], + [0, 6, 3, 0], + [0, 8, 1, 0]] + data = np.array(data).T + + res = bootstrap(data, statistic_extradim, rng=rng, paired=True) + ref = bootstrap(data, statistic, rng=rng, paired=True) + assert_allclose(res.confidence_interval.low[0], + ref.confidence_interval.low, atol=1e-15) + assert_allclose(res.confidence_interval.high[0], + ref.confidence_interval.high, atol=1e-15) + + +def test_gh_20850(): + rng = np.random.default_rng(2085020850) + x = rng.random((10, 2)) + y = rng.random((11, 2)) + def statistic(x, y, axis): + return stats.ttest_ind(x, y, axis=axis).statistic + + # The shapes do *not* need to be the same along axis + stats.bootstrap((x, y), statistic) + stats.bootstrap((x.T, y.T), statistic, axis=1) + # But even when the shapes *are* the same along axis, the lengths + # along other dimensions have to be the same (or `bootstrap` warns). + message = "Ignoring the dimension specified by `axis`..." + with pytest.warns(FutureWarning, match=message): + stats.bootstrap((x, y[:10, 0]), statistic) # this won't work after 1.16 + with pytest.warns(FutureWarning, match=message): + stats.bootstrap((x, y[:10, 0:1]), statistic) # this will + with pytest.warns(FutureWarning, match=message): + stats.bootstrap((x.T, y.T[0:1, :10]), statistic, axis=1) # this will + + +# --- Test Monte Carlo Hypothesis Test --- # + +class TestMonteCarloHypothesisTest: + atol = 2.5e-2 # for comparing p-value + + def get_rvs(self, rvs_in, rs, dtype=None, xp=np): + return lambda *args, **kwds: xp.asarray(rvs_in(*args, random_state=rs, **kwds), + dtype=dtype) + + def get_statistic(self, xp): + def statistic(x, axis): + m = xp.mean(x, axis=axis) + v = xp.var(x, axis=axis, correction=1) + n = x.shape[axis] + return m / (v/n)**0.5 + # return stats.ttest_1samp(x, popmean=0., axis=axis).statistic) + return statistic + + @array_api_compatible + def test_input_validation(self, xp): + # test that the appropriate error messages are raised for invalid input + + data = xp.asarray([1., 2., 3.]) + def stat(x, axis=None): + return xp.mean(x, axis=axis) + + message = "Array shapes are incompatible for broadcasting." + temp = (xp.zeros((2, 5)), xp.zeros((3, 5))) + rvs = (stats.norm.rvs, stats.norm.rvs) + with pytest.raises(ValueError, match=message): + monte_carlo_test(temp, rvs, lambda x, y, axis: 1, axis=-1) + + message = "`axis` must be an integer." + with pytest.raises(ValueError, match=message): + monte_carlo_test(data, stats.norm.rvs, stat, axis=1.5) + + message = "`vectorized` must be `True`, `False`, or `None`." + with pytest.raises(ValueError, match=message): + monte_carlo_test(data, stats.norm.rvs, stat, vectorized=1.5) + + message = "`rvs` must be callable or sequence of callables." + with pytest.raises(TypeError, match=message): + monte_carlo_test(data, None, stat) + with pytest.raises(TypeError, match=message): + temp = xp.asarray([[1., 2.], [3., 4.]]) + monte_carlo_test(temp, [lambda x: x, None], stat) + + message = "If `rvs` is a sequence..." + with pytest.raises(ValueError, match=message): + temp = xp.asarray([[1., 2., 3.]]) + monte_carlo_test(temp, [lambda x: x, lambda x: x], stat) + + message = "`statistic` must be callable." + with pytest.raises(TypeError, match=message): + monte_carlo_test(data, stats.norm.rvs, None) + + message = "`n_resamples` must be a positive integer." + with pytest.raises(ValueError, match=message): + monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=-1000) + + message = "`n_resamples` must be a positive integer." + with pytest.raises(ValueError, match=message): + monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=1000.5) + + message = "`batch` must be a positive integer or None." + with pytest.raises(ValueError, match=message): + monte_carlo_test(data, stats.norm.rvs, stat, batch=-1000) + + message = "`batch` must be a positive integer or None." + with pytest.raises(ValueError, match=message): + monte_carlo_test(data, stats.norm.rvs, stat, batch=1000.5) + + message = "`alternative` must be in..." + with pytest.raises(ValueError, match=message): + monte_carlo_test(data, stats.norm.rvs, stat, alternative='ekki') + + # *If* this raises a value error, make sure it has the intended message + message = "Signature inspection of statistic" + def rvs(size): + return xp.asarray(stats.norm.rvs(size=size)) + try: + monte_carlo_test(data, rvs, xp.mean) + except ValueError as e: + assert str(e).startswith(message) + + @array_api_compatible + def test_input_validation_xp(self, xp): + def non_vectorized_statistic(x): + return xp.mean(x) + + message = "`statistic` must be vectorized..." + sample = xp.asarray([1., 2., 3.]) + if is_numpy(xp): + monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic) + return + + with pytest.raises(ValueError, match=message): + monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic) + with pytest.raises(ValueError, match=message): + monte_carlo_test(sample, stats.norm.rvs, xp.mean, vectorized=False) + + @pytest.mark.xslow + @array_api_compatible + def test_batch(self, xp): + # make sure that the `batch` parameter is respected by checking the + # maximum batch size provided in calls to `statistic` + rng = np.random.default_rng(23492340193) + x = xp.asarray(rng.standard_normal(size=10)) + + xp_test = array_namespace(x) # numpy.std doesn't have `correction` + def statistic(x, axis): + batch_size = 1 if x.ndim == 1 else x.shape[0] + statistic.batch_size = max(batch_size, statistic.batch_size) + statistic.counter += 1 + return self.get_statistic(xp_test)(x, axis=axis) + statistic.counter = 0 + statistic.batch_size = 0 + + kwds = {'sample': x, 'statistic': statistic, + 'n_resamples': 1000, 'vectorized': True} + + kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp) + res1 = monte_carlo_test(batch=1, **kwds) + assert_equal(statistic.counter, 1001) + assert_equal(statistic.batch_size, 1) + + kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp) + statistic.counter = 0 + res2 = monte_carlo_test(batch=50, **kwds) + assert_equal(statistic.counter, 21) + assert_equal(statistic.batch_size, 50) + + kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp) + statistic.counter = 0 + res3 = monte_carlo_test(**kwds) + assert_equal(statistic.counter, 2) + assert_equal(statistic.batch_size, 1000) + + xp_assert_equal(res1.pvalue, res3.pvalue) + xp_assert_equal(res2.pvalue, res3.pvalue) + + @array_api_compatible + @pytest.mark.parametrize('axis', range(-3, 3)) + def test_axis_dtype(self, axis, xp): + # test that Nd-array samples are handled correctly for valid values + # of the `axis` parameter; also make sure non-default dtype is maintained + rng = np.random.default_rng(2389234) + size = [2, 3, 4] + size[axis] = 100 + + # Determine non-default dtype + dtype_default = xp.asarray(1.).dtype + dtype_str = 'float32'if ("64" in str(dtype_default)) else 'float64' + dtype_np = getattr(np, dtype_str) + dtype = getattr(xp, dtype_str) + + # ttest_1samp is CPU array-API compatible, but it would be good to + # include CuPy in this test. We'll perform ttest_1samp with a + # NumPy array, but all the rest with be done with fully array-API + # compatible code. + x = rng.standard_normal(size=size, dtype=dtype_np) + expected = stats.ttest_1samp(x, popmean=0., axis=axis) + + x = xp.asarray(x, dtype=dtype) + xp_test = array_namespace(x) # numpy.std doesn't have `correction` + statistic = self.get_statistic(xp_test) + rvs = self.get_rvs(stats.norm.rvs, rng, dtype=dtype, xp=xp) + + res = monte_carlo_test(x, rvs, statistic, vectorized=True, + n_resamples=20000, axis=axis) + + ref_statistic = xp.asarray(expected.statistic, dtype=dtype) + ref_pvalue = xp.asarray(expected.pvalue, dtype=dtype) + xp_assert_close(res.statistic, ref_statistic) + xp_assert_close(res.pvalue, ref_pvalue, atol=self.atol) + + @array_api_compatible + @pytest.mark.parametrize('alternative', ("two-sided", "less", "greater")) + def test_alternative(self, alternative, xp): + # test that `alternative` is working as expected + rng = np.random.default_rng(65723433) + + x = rng.standard_normal(size=30) + ref = stats.ttest_1samp(x, 0., alternative=alternative) + + x = xp.asarray(x) + xp_test = array_namespace(x) # numpy.std doesn't have `correction` + statistic = self.get_statistic(xp_test) + rvs = self.get_rvs(stats.norm.rvs, rng, xp=xp) + + res = monte_carlo_test(x, rvs, statistic, alternative=alternative) + + xp_assert_close(res.statistic, xp.asarray(ref.statistic)) + xp_assert_close(res.pvalue, xp.asarray(ref.pvalue), atol=self.atol) + + + # Tests below involve statistics that are not yet array-API compatible. + # They can be converted when the statistics are converted. + @pytest.mark.slow + @pytest.mark.parametrize('alternative', ("less", "greater")) + @pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness + def test_against_ks_1samp(self, alternative, a): + # test that monte_carlo_test can reproduce pvalue of ks_1samp + rng = np.random.default_rng(65723433) + + x = stats.skewnorm.rvs(a=a, size=30, random_state=rng) + expected = stats.ks_1samp(x, stats.norm.cdf, alternative=alternative) + + def statistic1d(x): + return stats.ks_1samp(x, stats.norm.cdf, mode='asymp', + alternative=alternative).statistic + + norm_rvs = self.get_rvs(stats.norm.rvs, rng) + res = monte_carlo_test(x, norm_rvs, statistic1d, + n_resamples=1000, vectorized=False, + alternative=alternative) + + assert_allclose(res.statistic, expected.statistic) + if alternative == 'greater': + assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) + elif alternative == 'less': + assert_allclose(1-res.pvalue, expected.pvalue, atol=self.atol) + + @pytest.mark.parametrize('hypotest', (stats.skewtest, stats.kurtosistest)) + @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided")) + @pytest.mark.parametrize('a', np.linspace(-2, 2, 5)) # skewness + def test_against_normality_tests(self, hypotest, alternative, a): + # test that monte_carlo_test can reproduce pvalue of normality tests + rng = np.random.default_rng(85723405) + + x = stats.skewnorm.rvs(a=a, size=150, random_state=rng) + expected = hypotest(x, alternative=alternative) + + def statistic(x, axis): + return hypotest(x, axis=axis).statistic + + norm_rvs = self.get_rvs(stats.norm.rvs, rng) + res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True, + alternative=alternative) + + assert_allclose(res.statistic, expected.statistic) + assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) + + @pytest.mark.parametrize('a', np.arange(-2, 3)) # skewness parameter + def test_against_normaltest(self, a): + # test that monte_carlo_test can reproduce pvalue of normaltest + rng = np.random.default_rng(12340513) + + x = stats.skewnorm.rvs(a=a, size=150, random_state=rng) + expected = stats.normaltest(x) + + def statistic(x, axis): + return stats.normaltest(x, axis=axis).statistic + + norm_rvs = self.get_rvs(stats.norm.rvs, rng) + res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True, + alternative='greater') + + assert_allclose(res.statistic, expected.statistic) + assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) + + @pytest.mark.xslow + @pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness + def test_against_cramervonmises(self, a): + # test that monte_carlo_test can reproduce pvalue of cramervonmises + rng = np.random.default_rng(234874135) + + x = stats.skewnorm.rvs(a=a, size=30, random_state=rng) + expected = stats.cramervonmises(x, stats.norm.cdf) + + def statistic1d(x): + return stats.cramervonmises(x, stats.norm.cdf).statistic + + norm_rvs = self.get_rvs(stats.norm.rvs, rng) + res = monte_carlo_test(x, norm_rvs, statistic1d, + n_resamples=1000, vectorized=False, + alternative='greater') + + assert_allclose(res.statistic, expected.statistic) + assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) + + @pytest.mark.slow + @pytest.mark.parametrize('dist_name', ('norm', 'logistic')) + @pytest.mark.parametrize('i', range(5)) + def test_against_anderson(self, dist_name, i): + # test that monte_carlo_test can reproduce results of `anderson`. Note: + # `anderson` does not provide a p-value; it provides a list of + # significance levels and the associated critical value of the test + # statistic. `i` used to index this list. + + # find the skewness for which the sample statistic matches one of the + # critical values provided by `stats.anderson` + + def fun(a): + rng = np.random.default_rng(394295467) + x = stats.tukeylambda.rvs(a, size=100, random_state=rng) + expected = stats.anderson(x, dist_name) + return expected.statistic - expected.critical_values[i] + with suppress_warnings() as sup: + sup.filter(RuntimeWarning) + sol = root(fun, x0=0) + assert sol.success + + # get the significance level (p-value) associated with that critical + # value + a = sol.x[0] + rng = np.random.default_rng(394295467) + x = stats.tukeylambda.rvs(a, size=100, random_state=rng) + expected = stats.anderson(x, dist_name) + expected_stat = expected.statistic + expected_p = expected.significance_level[i]/100 + + # perform equivalent Monte Carlo test and compare results + def statistic1d(x): + return stats.anderson(x, dist_name).statistic + + dist_rvs = self.get_rvs(getattr(stats, dist_name).rvs, rng) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning) + res = monte_carlo_test(x, dist_rvs, + statistic1d, n_resamples=1000, + vectorized=False, alternative='greater') + + assert_allclose(res.statistic, expected_stat) + assert_allclose(res.pvalue, expected_p, atol=2*self.atol) + + def test_p_never_zero(self): + # Use biased estimate of p-value to ensure that p-value is never zero + # per monte_carlo_test reference [1] + rng = np.random.default_rng(2190176673029737545) + x = np.zeros(100) + res = monte_carlo_test(x, rng.random, np.mean, + vectorized=True, alternative='less') + assert res.pvalue == 0.0001 + + def test_against_ttest_ind(self): + # test that `monte_carlo_test` can reproduce results of `ttest_ind`. + rng = np.random.default_rng(219017667302737545) + data = rng.random(size=(2, 5)), rng.random(size=7) # broadcastable + rvs = rng.normal, rng.normal + def statistic(x, y, axis): + return stats.ttest_ind(x, y, axis=axis).statistic + + res = stats.monte_carlo_test(data, rvs, statistic, axis=-1) + ref = stats.ttest_ind(data[0], [data[1]], axis=-1) + assert_allclose(res.statistic, ref.statistic) + assert_allclose(res.pvalue, ref.pvalue, rtol=2e-2) + + def test_against_f_oneway(self): + # test that `monte_carlo_test` can reproduce results of `f_oneway`. + rng = np.random.default_rng(219017667302737545) + data = (rng.random(size=(2, 100)), rng.random(size=(2, 101)), + rng.random(size=(2, 102)), rng.random(size=(2, 103))) + rvs = rng.normal, rng.normal, rng.normal, rng.normal + + def statistic(*args, axis): + return stats.f_oneway(*args, axis=axis).statistic + + res = stats.monte_carlo_test(data, rvs, statistic, axis=-1, + alternative='greater') + ref = stats.f_oneway(*data, axis=-1) + + assert_allclose(res.statistic, ref.statistic) + assert_allclose(res.pvalue, ref.pvalue, atol=1e-2) + + @pytest.mark.fail_slow(2) + @pytest.mark.xfail_on_32bit("Statistic may not depend on sample order on 32-bit") + def test_finite_precision_statistic(self): + # Some statistics return numerically distinct values when the values + # should be equal in theory. Test that `monte_carlo_test` accounts + # for this in some way. + rng = np.random.default_rng(2549824598234528) + n_resamples = 9999 + def rvs(size): + return 1. * stats.bernoulli(p=0.333).rvs(size=size, random_state=rng) + + x = rvs(100) + res = stats.monte_carlo_test(x, rvs, np.var, alternative='less', + n_resamples=n_resamples) + # show that having a tolerance matters + c0 = np.sum(res.null_distribution <= res.statistic) + c1 = np.sum(res.null_distribution <= res.statistic*(1+1e-15)) + assert c0 != c1 + assert res.pvalue == (c1 + 1)/(n_resamples + 1) + + +class TestPower: + def test_input_validation(self): + # test that the appropriate error messages are raised for invalid input + rng = np.random.default_rng(8519895914314711673) + + test = stats.ttest_ind + rvs = (rng.normal, rng.normal) + n_observations = (10, 12) + + message = "`vectorized` must be `True`, `False`, or `None`." + with pytest.raises(ValueError, match=message): + power(test, rvs, n_observations, vectorized=1.5) + + message = "`rvs` must be callable or sequence of callables." + with pytest.raises(TypeError, match=message): + power(test, None, n_observations) + with pytest.raises(TypeError, match=message): + power(test, (rng.normal, 'ekki'), n_observations) + + message = "If `rvs` is a sequence..." + with pytest.raises(ValueError, match=message): + power(test, (rng.normal,), n_observations) + with pytest.raises(ValueError, match=message): + power(test, rvs, (10,)) + + message = "`significance` must contain floats between 0 and 1." + with pytest.raises(ValueError, match=message): + power(test, rvs, n_observations, significance=2) + with pytest.raises(ValueError, match=message): + power(test, rvs, n_observations, significance=np.linspace(-1, 1)) + + message = "`kwargs` must be a dictionary" + with pytest.raises(TypeError, match=message): + power(test, rvs, n_observations, kwargs=(1, 2, 3)) + + message = "shape mismatch: objects cannot be broadcast" + with pytest.raises(ValueError, match=message): + power(test, rvs, ([10, 11], [12, 13, 14])) + with pytest.raises(ValueError, match=message): + power(test, rvs, ([10, 11], [12, 13]), kwargs={'x': [1, 2, 3]}) + + message = "`test` must be callable" + with pytest.raises(TypeError, match=message): + power(None, rvs, n_observations) + + message = "`n_resamples` must be a positive integer" + with pytest.raises(ValueError, match=message): + power(test, rvs, n_observations, n_resamples=-10) + with pytest.raises(ValueError, match=message): + power(test, rvs, n_observations, n_resamples=10.5) + + message = "`batch` must be a positive integer" + with pytest.raises(ValueError, match=message): + power(test, rvs, n_observations, batch=-10) + with pytest.raises(ValueError, match=message): + power(test, rvs, n_observations, batch=10.5) + + @pytest.mark.slow + def test_batch(self): + # make sure that the `batch` parameter is respected by checking the + # maximum batch size provided in calls to `test` + rng = np.random.default_rng(23492340193) + + def test(x, axis): + batch_size = 1 if x.ndim == 1 else len(x) + test.batch_size = max(batch_size, test.batch_size) + test.counter += 1 + return stats.ttest_1samp(x, 0, axis=axis).pvalue + test.counter = 0 + test.batch_size = 0 + + kwds = dict(test=test, n_observations=10, n_resamples=1000) + + rng = np.random.default_rng(23492340193) + res1 = power(**kwds, rvs=rng.normal, batch=1) + assert_equal(test.counter, 1000) + assert_equal(test.batch_size, 1) + + rng = np.random.default_rng(23492340193) + test.counter = 0 + res2 = power(**kwds, rvs=rng.normal, batch=50) + assert_equal(test.counter, 20) + assert_equal(test.batch_size, 50) + + rng = np.random.default_rng(23492340193) + test.counter = 0 + res3 = power(**kwds, rvs=rng.normal, batch=1000) + assert_equal(test.counter, 1) + assert_equal(test.batch_size, 1000) + + assert_equal(res1.power, res3.power) + assert_equal(res2.power, res3.power) + + @pytest.mark.slow + def test_vectorization(self): + # Test that `power` is vectorized as expected + rng = np.random.default_rng(25495254834552) + + # Single vectorized call + popmeans = np.array([0, 0.2]) + def test(x, alternative, axis=-1): + # ensure that popmeans axis is zeroth and orthogonal to the rest + popmeans_expanded = np.expand_dims(popmeans, tuple(range(1, x.ndim + 1))) + return stats.ttest_1samp(x, popmeans_expanded, alternative=alternative, + axis=axis) + + # nx and kwargs broadcast against one another + nx = np.asarray([10, 15, 20, 50, 100])[:, np.newaxis] + kwargs = {'alternative': ['less', 'greater', 'two-sided']} + + # This dimension is added to the beginning + significance = np.asarray([0.01, 0.025, 0.05, 0.1]) + res = stats.power(test, rng.normal, nx, significance=significance, + kwargs=kwargs) + + # Looping over all combinations + ref = [] + for significance_i in significance: + for nx_i in nx: + for alternative_i in kwargs['alternative']: + for popmean_i in popmeans: + def test2(x, axis=-1): + return stats.ttest_1samp(x, popmean_i, axis=axis, + alternative=alternative_i) + + tmp = stats.power(test2, rng.normal, nx_i, + significance=significance_i) + ref.append(tmp.power) + ref = np.reshape(ref, res.power.shape) + + # Show that results are similar + assert_allclose(res.power, ref, rtol=2e-2, atol=1e-2) + + def test_ttest_ind_null(self): + # Check that the p-values of `ttest_ind` are uniformly distributed under + # the null hypothesis + rng = np.random.default_rng(254952548345528) + + test = stats.ttest_ind + n_observations = rng.integers(10, 100, size=(2, 10)) + rvs = rng.normal, rng.normal + significance = np.asarray([0.01, 0.05, 0.1]) + res = stats.power(test, rvs, n_observations, significance=significance) + significance = np.broadcast_to(significance[:, np.newaxis], res.power.shape) + assert_allclose(res.power, significance, atol=1e-2) + + def test_ttest_1samp_power(self): + # Check simulated ttest_1samp power against reference + rng = np.random.default_rng(254952548345528) + + # Reference values computed with statmodels + # import numpy as np + # from statsmodels.stats.power import tt_solve_power + # tt_solve_power = np.vectorize(tt_solve_power) + # tt_solve_power([0.1, 0.5, 0.9], [[10], [20]], [[[0.01]], [[0.05]]]) + ref = [[[0.0126515 , 0.10269751, 0.40415802], + [0.01657775, 0.29734608, 0.86228288]], + [[0.0592903 , 0.29317561, 0.71718121], + [0.07094116, 0.56450441, 0.96815163]]] + + kwargs = {'popmean': [0.1, 0.5, 0.9]} + n_observations = [[10], [20]] + significance = [0.01, 0.05] + res = stats.power(stats.ttest_1samp, rng.normal, n_observations, + significance=significance, kwargs=kwargs) + assert_allclose(res.power, ref, atol=1e-2) + + +class TestPermutationTest: + + rtol = 1e-14 + + def setup_method(self): + self.rng = np.random.default_rng(7170559330470561044) + + # -- Input validation -- # + + def test_permutation_test_iv(self): + + def stat(x, y, axis): + return stats.ttest_ind((x, y), axis).statistic + + message = "each sample in `data` must contain two or more ..." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1]), stat) + + message = "`data` must be a tuple containing at least two samples" + with pytest.raises(ValueError, match=message): + permutation_test((1,), stat) + with pytest.raises(TypeError, match=message): + permutation_test(1, stat) + + message = "`axis` must be an integer." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, axis=1.5) + + message = "`permutation_type` must be in..." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, + permutation_type="ekki") + + message = "`vectorized` must be `True`, `False`, or `None`." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, vectorized=1.5) + + message = "`n_resamples` must be a positive integer." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, n_resamples=-1000) + + message = "`n_resamples` must be a positive integer." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, n_resamples=1000.5) + + message = "`batch` must be a positive integer or None." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, batch=-1000) + + message = "`batch` must be a positive integer or None." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, batch=1000.5) + + message = "`alternative` must be in..." + with pytest.raises(ValueError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, alternative='ekki') + + message = "SeedSequence expects int or sequence of ints" + with pytest.raises(TypeError, match=message): + permutation_test(([1, 2, 3], [1, 2, 3]), stat, rng='herring') + + # -- Test Parameters -- # + # SPEC-007 leave one call with seed to check it still works + @pytest.mark.parametrize('random_state', [np.random.RandomState, + np.random.default_rng]) + @pytest.mark.parametrize('permutation_type', + ['pairings', 'samples', 'independent']) + def test_batch(self, permutation_type, random_state): + # make sure that the `batch` parameter is respected by checking the + # maximum batch size provided in calls to `statistic` + x = self.rng.random(10) + y = self.rng.random(10) + + def statistic(x, y, axis): + batch_size = 1 if x.ndim == 1 else len(x) + statistic.batch_size = max(batch_size, statistic.batch_size) + statistic.counter += 1 + return np.mean(x, axis=axis) - np.mean(y, axis=axis) + statistic.counter = 0 + statistic.batch_size = 0 + + kwds = {'n_resamples': 1000, 'permutation_type': permutation_type, + 'vectorized': True} + res1 = stats.permutation_test((x, y), statistic, batch=1, + random_state=random_state(0), **kwds) + assert_equal(statistic.counter, 1001) + assert_equal(statistic.batch_size, 1) + + statistic.counter = 0 + res2 = stats.permutation_test((x, y), statistic, batch=50, + random_state=random_state(0), **kwds) + assert_equal(statistic.counter, 21) + assert_equal(statistic.batch_size, 50) + + statistic.counter = 0 + res3 = stats.permutation_test((x, y), statistic, batch=1000, + random_state=random_state(0), **kwds) + assert_equal(statistic.counter, 2) + assert_equal(statistic.batch_size, 1000) + + assert_equal(res1.pvalue, res3.pvalue) + assert_equal(res2.pvalue, res3.pvalue) + + # SPEC-007 leave at least one call with seed to check it still works + @pytest.mark.parametrize('random_state', [np.random.RandomState, + np.random.default_rng]) + @pytest.mark.parametrize('permutation_type, exact_size', + [('pairings', special.factorial(3)**2), + ('samples', 2**3), + ('independent', special.binom(6, 3))]) + def test_permutations(self, permutation_type, exact_size, random_state): + # make sure that the `permutations` parameter is respected by checking + # the size of the null distribution + x = self.rng.random(3) + y = self.rng.random(3) + + def statistic(x, y, axis): + return np.mean(x, axis=axis) - np.mean(y, axis=axis) + + kwds = {'permutation_type': permutation_type, + 'vectorized': True} + res = stats.permutation_test((x, y), statistic, n_resamples=3, + random_state=random_state(0), **kwds) + assert_equal(res.null_distribution.size, 3) + + res = stats.permutation_test((x, y), statistic, **kwds) + assert_equal(res.null_distribution.size, exact_size) + + # -- Randomized Permutation Tests -- # + + # To get reasonable accuracy, these next three tests are somewhat slow. + # Originally, I had them passing for all combinations of permutation type, + # alternative, and RNG, but that takes too long for CI. Instead, split + # into three tests, each testing a particular combination of the three + # parameters. + + def test_randomized_test_against_exact_both(self): + # check that the randomized and exact tests agree to reasonable + # precision for permutation_type='both + + alternative, rng = 'less', 0 + + nx, ny, permutations = 8, 9, 24000 + assert special.binom(nx + ny, nx) > permutations + + x = stats.norm.rvs(size=nx) + y = stats.norm.rvs(size=ny) + data = x, y + + def statistic(x, y, axis): + return np.mean(x, axis=axis) - np.mean(y, axis=axis) + + kwds = {'vectorized': True, 'permutation_type': 'independent', + 'batch': 100, 'alternative': alternative, 'rng': rng} + res = permutation_test(data, statistic, n_resamples=permutations, + **kwds) + res2 = permutation_test(data, statistic, n_resamples=np.inf, **kwds) + + assert res.statistic == res2.statistic + assert_allclose(res.pvalue, res2.pvalue, atol=1e-2) + + @pytest.mark.slow() + def test_randomized_test_against_exact_samples(self): + # check that the randomized and exact tests agree to reasonable + # precision for permutation_type='samples' + + alternative, rng = 'greater', None + + nx, ny, permutations = 15, 15, 32000 + assert 2**nx > permutations + + x = stats.norm.rvs(size=nx) + y = stats.norm.rvs(size=ny) + data = x, y + + def statistic(x, y, axis): + return np.mean(x - y, axis=axis) + + kwds = {'vectorized': True, 'permutation_type': 'samples', + 'batch': 100, 'alternative': alternative, 'rng': rng} + res = permutation_test(data, statistic, n_resamples=permutations, + **kwds) + res2 = permutation_test(data, statistic, n_resamples=np.inf, **kwds) + + assert res.statistic == res2.statistic + assert_allclose(res.pvalue, res2.pvalue, atol=1e-2) + + def test_randomized_test_against_exact_pairings(self): + # check that the randomized and exact tests agree to reasonable + # precision for permutation_type='pairings' + + alternative, rng = 'two-sided', self.rng + + nx, ny, permutations = 8, 8, 40000 + assert special.factorial(nx) > permutations + + x = stats.norm.rvs(size=nx) + y = stats.norm.rvs(size=ny) + data = [x] + + def statistic1d(x): + return stats.pearsonr(x, y)[0] + + statistic = _resampling._vectorize_statistic(statistic1d) + + kwds = {'vectorized': True, 'permutation_type': 'samples', + 'batch': 100, 'alternative': alternative, 'rng': rng} + res = permutation_test(data, statistic, n_resamples=permutations, + **kwds) + res2 = permutation_test(data, statistic, n_resamples=np.inf, **kwds) + + assert res.statistic == res2.statistic + assert_allclose(res.pvalue, res2.pvalue, atol=1e-2) + + # -- Independent (Unpaired) Sample Tests -- # + + @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided")) + def test_against_ks_2samp(self, alternative): + + x = self.rng.normal(size=4, scale=1) + y = self.rng.normal(size=5, loc=3, scale=3) + + expected = stats.ks_2samp(x, y, alternative=alternative, mode='exact') + + def statistic1d(x, y): + return stats.ks_2samp(x, y, mode='asymp', + alternative=alternative).statistic + + # ks_2samp is always a one-tailed 'greater' test + # it's the statistic that changes (D+ vs D- vs max(D+, D-)) + res = permutation_test((x, y), statistic1d, n_resamples=np.inf, + alternative='greater', rng=self.rng) + + assert_allclose(res.statistic, expected.statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol) + + @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided")) + def test_against_ansari(self, alternative): + + x = self.rng.normal(size=4, scale=1) + y = self.rng.normal(size=5, scale=3) + + # ansari has a different convention for 'alternative' + alternative_correspondence = {"less": "greater", + "greater": "less", + "two-sided": "two-sided"} + alternative_scipy = alternative_correspondence[alternative] + expected = stats.ansari(x, y, alternative=alternative_scipy) + + def statistic1d(x, y): + return stats.ansari(x, y).statistic + + res = permutation_test((x, y), statistic1d, n_resamples=np.inf, + alternative=alternative, rng=self.rng) + + assert_allclose(res.statistic, expected.statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol) + + @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided")) + def test_against_mannwhitneyu(self, alternative): + + x = stats.uniform.rvs(size=(3, 5, 2), loc=0, random_state=self.rng) + y = stats.uniform.rvs(size=(3, 5, 2), loc=0.05, random_state=self.rng) + + expected = stats.mannwhitneyu(x, y, axis=1, alternative=alternative) + + def statistic(x, y, axis): + return stats.mannwhitneyu(x, y, axis=axis).statistic + + res = permutation_test((x, y), statistic, vectorized=True, + n_resamples=np.inf, alternative=alternative, + axis=1, rng=self.rng) + + assert_allclose(res.statistic, expected.statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol) + + def test_against_cvm(self): + + x = stats.norm.rvs(size=4, scale=1, random_state=self.rng) + y = stats.norm.rvs(size=5, loc=3, scale=3, random_state=self.rng) + + expected = stats.cramervonmises_2samp(x, y, method='exact') + + def statistic1d(x, y): + return stats.cramervonmises_2samp(x, y, + method='asymptotic').statistic + + # cramervonmises_2samp has only one alternative, greater + res = permutation_test((x, y), statistic1d, n_resamples=np.inf, + alternative='greater', rng=self.rng) + + assert_allclose(res.statistic, expected.statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol) + + @pytest.mark.xslow() + @pytest.mark.parametrize('axis', (-1, 2)) + def test_vectorized_nsamp_ptype_both(self, axis): + # Test that permutation_test with permutation_type='independent' works + # properly for a 3-sample statistic with nd array samples of different + # (but compatible) shapes and ndims. Show that exact permutation test + # and random permutation tests approximate SciPy's asymptotic pvalues + # and that exact and random permutation test results are even closer + # to one another (than they are to the asymptotic results). + + # Three samples, different (but compatible) shapes with different ndims + rng = np.random.default_rng(6709265303529651545) + x = rng.random(size=(3)) + y = rng.random(size=(1, 3, 2)) + z = rng.random(size=(2, 1, 4)) + data = (x, y, z) + + # Define the statistic (and pvalue for comparison) + def statistic1d(*data): + return stats.kruskal(*data).statistic + + def pvalue1d(*data): + return stats.kruskal(*data).pvalue + + statistic = _resampling._vectorize_statistic(statistic1d) + pvalue = _resampling._vectorize_statistic(pvalue1d) + + # Calculate the expected results + x2 = np.broadcast_to(x, (2, 3, 3)) # broadcast manually because + y2 = np.broadcast_to(y, (2, 3, 2)) # _vectorize_statistic doesn't + z2 = np.broadcast_to(z, (2, 3, 4)) + expected_statistic = statistic(x2, y2, z2, axis=axis) + expected_pvalue = pvalue(x2, y2, z2, axis=axis) + + # Calculate exact and randomized permutation results + kwds = {'vectorized': False, 'axis': axis, 'alternative': 'greater', + 'permutation_type': 'independent', 'rng': self.rng} + res = permutation_test(data, statistic1d, n_resamples=np.inf, **kwds) + res2 = permutation_test(data, statistic1d, n_resamples=1000, **kwds) + + # Check results + assert_allclose(res.statistic, expected_statistic, rtol=self.rtol) + assert_allclose(res.statistic, res2.statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected_pvalue, atol=6e-2) + assert_allclose(res.pvalue, res2.pvalue, atol=3e-2) + + # -- Paired-Sample Tests -- # + + @pytest.mark.slow + @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided")) + def test_against_wilcoxon(self, alternative): + + x = stats.uniform.rvs(size=(3, 6, 2), loc=0, random_state=self.rng) + y = stats.uniform.rvs(size=(3, 6, 2), loc=0.05, random_state=self.rng) + + # We'll check both 1- and 2-sample versions of the same test; + # we expect identical results to wilcoxon in all cases. + def statistic_1samp_1d(z): + # 'less' ensures we get the same of two statistics every time + return stats.wilcoxon(z, alternative='less').statistic + + def statistic_2samp_1d(x, y): + return stats.wilcoxon(x, y, alternative='less').statistic + + def test_1d(x, y): + return stats.wilcoxon(x, y, alternative=alternative) + + test = _resampling._vectorize_statistic(test_1d) + + expected = test(x, y, axis=1) + expected_stat = expected[0] + expected_p = expected[1] + + kwds = {'vectorized': False, 'axis': 1, 'alternative': alternative, + 'permutation_type': 'samples', 'rng': self.rng, + 'n_resamples': np.inf} + res1 = permutation_test((x-y,), statistic_1samp_1d, **kwds) + res2 = permutation_test((x, y), statistic_2samp_1d, **kwds) + + # `wilcoxon` returns a different statistic with 'two-sided' + assert_allclose(res1.statistic, res2.statistic, rtol=self.rtol) + if alternative != 'two-sided': + assert_allclose(res2.statistic, expected_stat, rtol=self.rtol) + + assert_allclose(res2.pvalue, expected_p, rtol=self.rtol) + assert_allclose(res1.pvalue, res2.pvalue, rtol=self.rtol) + + @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided")) + def test_against_binomtest(self, alternative): + + x = self.rng.integers(0, 2, size=10) + x[x == 0] = -1 + # More naturally, the test would flip elements between 0 and one. + # However, permutation_test will flip the _signs_ of the elements. + # So we have to work with +1/-1 instead of 1/0. + + def statistic(x, axis=0): + return np.sum(x > 0, axis=axis) + + k, n, p = statistic(x), 10, 0.5 + expected = stats.binomtest(k, n, p, alternative=alternative) + + res = stats.permutation_test((x,), statistic, vectorized=True, + permutation_type='samples', + n_resamples=np.inf, rng=self.rng, + alternative=alternative) + assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol) + + # -- Exact Association Tests -- # + + def test_against_kendalltau(self): + + x = self.rng.normal(size=6) + y = x + self.rng.normal(size=6) + + expected = stats.kendalltau(x, y, method='exact') + + def statistic1d(x): + return stats.kendalltau(x, y, method='asymptotic').statistic + + # kendalltau currently has only one alternative, two-sided + res = permutation_test((x,), statistic1d, permutation_type='pairings', + n_resamples=np.inf, rng=self.rng) + + assert_allclose(res.statistic, expected.statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol) + + @pytest.mark.parametrize('alternative', ('less', 'greater', 'two-sided')) + def test_against_fisher_exact(self, alternative): + + def statistic(x,): + return np.sum((x == 1) & (y == 1)) + + # x and y are binary random variables with some dependence + rng = np.random.default_rng(6235696159000529929) + x = (rng.random(7) > 0.6).astype(float) + y = (rng.random(7) + 0.25*x > 0.6).astype(float) + tab = stats.contingency.crosstab(x, y)[1] + + res = permutation_test((x,), statistic, permutation_type='pairings', + n_resamples=np.inf, alternative=alternative, + rng=rng) + res2 = stats.fisher_exact(tab, alternative=alternative) + + assert_allclose(res.pvalue, res2[1]) + + @pytest.mark.xslow() + @pytest.mark.parametrize('axis', (-2, 1)) + def test_vectorized_nsamp_ptype_samples(self, axis): + # Test that permutation_test with permutation_type='samples' works + # properly for a 3-sample statistic with nd array samples of different + # (but compatible) shapes and ndims. Show that exact permutation test + # reproduces SciPy's exact pvalue and that random permutation test + # approximates it. + + x = self.rng.random(size=(2, 4, 3)) + y = self.rng.random(size=(1, 4, 3)) + z = self.rng.random(size=(2, 4, 1)) + x = stats.rankdata(x, axis=axis) + y = stats.rankdata(y, axis=axis) + z = stats.rankdata(z, axis=axis) + y = y[0] # to check broadcast with different ndim + data = (x, y, z) + + def statistic1d(*data): + return stats.page_trend_test(data, ranked=True, + method='asymptotic').statistic + + def pvalue1d(*data): + return stats.page_trend_test(data, ranked=True, + method='exact').pvalue + + statistic = _resampling._vectorize_statistic(statistic1d) + pvalue = _resampling._vectorize_statistic(pvalue1d) + + expected_statistic = statistic(*np.broadcast_arrays(*data), axis=axis) + expected_pvalue = pvalue(*np.broadcast_arrays(*data), axis=axis) + + # Let's forgive this use of an integer seed, please. + kwds = {'vectorized': False, 'axis': axis, 'alternative': 'greater', + 'permutation_type': 'pairings', 'rng': 0} + res = permutation_test(data, statistic1d, n_resamples=np.inf, **kwds) + res2 = permutation_test(data, statistic1d, n_resamples=5000, **kwds) + + assert_allclose(res.statistic, expected_statistic, rtol=self.rtol) + assert_allclose(res.statistic, res2.statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected_pvalue, rtol=self.rtol) + assert_allclose(res.pvalue, res2.pvalue, atol=3e-2) + + # -- Test Against External References -- # + + tie_case_1 = {'x': [1, 2, 3, 4], 'y': [1.5, 2, 2.5], + 'expected_less': 0.2000000000, + 'expected_2sided': 0.4, # 2*expected_less + 'expected_Pr_gte_S_mean': 0.3428571429, # see note below + 'expected_statistic': 7.5, + 'expected_avg': 9.142857, 'expected_std': 1.40698} + tie_case_2 = {'x': [111, 107, 100, 99, 102, 106, 109, 108], + 'y': [107, 108, 106, 98, 105, 103, 110, 105, 104], + 'expected_less': 0.1555738379, + 'expected_2sided': 0.3111476758, + 'expected_Pr_gte_S_mean': 0.2969971205, # see note below + 'expected_statistic': 32.5, + 'expected_avg': 38.117647, 'expected_std': 5.172124} + + @pytest.mark.xslow() # only the second case is slow, really + @pytest.mark.parametrize('case', (tie_case_1, tie_case_2)) + def test_with_ties(self, case): + """ + Results above from SAS PROC NPAR1WAY, e.g. + + DATA myData; + INPUT X Y; + CARDS; + 1 1 + 1 2 + 1 3 + 1 4 + 2 1.5 + 2 2 + 2 2.5 + ods graphics on; + proc npar1way AB data=myData; + class X; + EXACT; + run; + ods graphics off; + + Note: SAS provides Pr >= |S-Mean|, which is different from our + definition of a two-sided p-value. + + """ + + x = case['x'] + y = case['y'] + + expected_statistic = case['expected_statistic'] + expected_less = case['expected_less'] + expected_2sided = case['expected_2sided'] + expected_Pr_gte_S_mean = case['expected_Pr_gte_S_mean'] + expected_avg = case['expected_avg'] + expected_std = case['expected_std'] + + def statistic1d(x, y): + return stats.ansari(x, y).statistic + + with np.testing.suppress_warnings() as sup: + sup.filter(UserWarning, "Ties preclude use of exact statistic") + res = permutation_test((x, y), statistic1d, n_resamples=np.inf, + alternative='less') + res2 = permutation_test((x, y), statistic1d, n_resamples=np.inf, + alternative='two-sided') + + assert_allclose(res.statistic, expected_statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected_less, atol=1e-10) + assert_allclose(res2.pvalue, expected_2sided, atol=1e-10) + assert_allclose(res2.null_distribution.mean(), expected_avg, rtol=1e-6) + assert_allclose(res2.null_distribution.std(), expected_std, rtol=1e-6) + + # SAS provides Pr >= |S-Mean|; might as well check against that, too + S = res.statistic + mean = res.null_distribution.mean() + n = len(res.null_distribution) + Pr_gte_S_mean = np.sum(np.abs(res.null_distribution-mean) + >= np.abs(S-mean))/n + assert_allclose(expected_Pr_gte_S_mean, Pr_gte_S_mean) + + @pytest.mark.slow + @pytest.mark.parametrize('alternative, expected_pvalue', + (('less', 0.9708333333333), + ('greater', 0.05138888888889), + ('two-sided', 0.1027777777778))) + def test_against_spearmanr_in_R(self, alternative, expected_pvalue): + """ + Results above from R cor.test, e.g. + + options(digits=16) + x <- c(1.76405235, 0.40015721, 0.97873798, + 2.2408932, 1.86755799, -0.97727788) + y <- c(2.71414076, 0.2488, 0.87551913, + 2.6514917, 2.01160156, 0.47699563) + cor.test(x, y, method = "spearm", alternative = "t") + """ + # data comes from + # np.random.seed(0) + # x = stats.norm.rvs(size=6) + # y = x + stats.norm.rvs(size=6) + x = [1.76405235, 0.40015721, 0.97873798, + 2.2408932, 1.86755799, -0.97727788] + y = [2.71414076, 0.2488, 0.87551913, + 2.6514917, 2.01160156, 0.47699563] + expected_statistic = 0.7714285714285715 + + def statistic1d(x): + return stats.spearmanr(x, y).statistic + + res = permutation_test((x,), statistic1d, permutation_type='pairings', + n_resamples=np.inf, alternative=alternative) + + assert_allclose(res.statistic, expected_statistic, rtol=self.rtol) + assert_allclose(res.pvalue, expected_pvalue, atol=1e-13) + + @pytest.mark.parametrize("batch", (-1, 0)) + def test_batch_generator_iv(self, batch): + with pytest.raises(ValueError, match="`batch` must be positive."): + list(_resampling._batch_generator([1, 2, 3], batch)) + + batch_generator_cases = [(range(0), 3, []), + (range(6), 3, [[0, 1, 2], [3, 4, 5]]), + (range(8), 3, [[0, 1, 2], [3, 4, 5], [6, 7]])] + + @pytest.mark.parametrize("iterable, batch, expected", + batch_generator_cases) + def test_batch_generator(self, iterable, batch, expected): + got = list(_resampling._batch_generator(iterable, batch)) + assert got == expected + + @pytest.mark.fail_slow(2) + def test_finite_precision_statistic(self): + # Some statistics return numerically distinct values when the values + # should be equal in theory. Test that `permutation_test` accounts + # for this in some way. + x = [1, 2, 4, 3] + y = [2, 4, 6, 8] + + def statistic(x, y): + return stats.pearsonr(x, y)[0] + + res = stats.permutation_test((x, y), statistic, vectorized=False, + permutation_type='pairings') + r, pvalue, null = res.statistic, res.pvalue, res.null_distribution + + correct_p = 2 * np.sum(null >= r - 1e-14) / len(null) + assert pvalue == correct_p == 1/3 + # Compare against other exact correlation tests using R corr.test + # options(digits=16) + # x = c(1, 2, 4, 3) + # y = c(2, 4, 6, 8) + # cor.test(x, y, alternative = "t", method = "spearman") # 0.333333333 + # cor.test(x, y, alternative = "t", method = "kendall") # 0.333333333 + + +def test_all_partitions_concatenated(): + # make sure that _all_paritions_concatenated produces the correct number + # of partitions of the data into samples of the given sizes and that + # all are unique + n = np.array([3, 2, 4], dtype=int) + nc = np.cumsum(n) + + all_partitions = set() + counter = 0 + for partition_concatenated in _resampling._all_partitions_concatenated(n): + counter += 1 + partitioning = np.split(partition_concatenated, nc[:-1]) + all_partitions.add(tuple([frozenset(i) for i in partitioning])) + + expected = np.prod([special.binom(sum(n[i:]), sum(n[i+1:])) + for i in range(len(n)-1)]) + + assert_equal(counter, expected) + assert_equal(len(all_partitions), expected) + + +@pytest.mark.parametrize('fun_name', + ['bootstrap', 'permutation_test', 'monte_carlo_test']) +def test_parameter_vectorized(fun_name): + # Check that parameter `vectorized` is working as desired for all + # resampling functions. Results don't matter; just don't fail asserts. + rng = np.random.default_rng(75245098234592) + sample = rng.random(size=10) + + def rvs(size): # needed by `monte_carlo_test` + return stats.norm.rvs(size=size, random_state=rng) + + fun_options = {'bootstrap': {'data': (sample,), 'rng': rng, + 'method': 'percentile'}, + 'permutation_test': {'data': (sample,), 'rng': rng, + 'permutation_type': 'samples'}, + 'monte_carlo_test': {'sample': sample, 'rvs': rvs}} + common_options = {'n_resamples': 100} + + fun = getattr(stats, fun_name) + options = fun_options[fun_name] + options.update(common_options) + + def statistic(x, axis): + assert x.ndim > 1 or np.array_equal(x, sample) + return np.mean(x, axis=axis) + fun(statistic=statistic, vectorized=None, **options) + fun(statistic=statistic, vectorized=True, **options) + + def statistic(x): + assert x.ndim == 1 + return np.mean(x) + fun(statistic=statistic, vectorized=None, **options) + fun(statistic=statistic, vectorized=False, **options) + + +class TestMonteCarloMethod: + def test_rvs_and_random_state(self): + message = "Use of `rvs` and `rng` are mutually exclusive." + rng = np.random.default_rng(34982345) + with pytest.raises(ValueError, match=message): + stats.MonteCarloMethod(rvs=rng.random, rng=rng) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sampling.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..978511e09ca34a525f6c39e04a5344bc1cd2f7f3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sampling.py @@ -0,0 +1,1445 @@ +import threading +import pickle +import pytest +from copy import deepcopy +import platform +import sys +import math +import numpy as np +from numpy.testing import assert_allclose, assert_equal, suppress_warnings +from scipy.stats.sampling import ( + TransformedDensityRejection, + DiscreteAliasUrn, + DiscreteGuideTable, + NumericalInversePolynomial, + NumericalInverseHermite, + RatioUniforms, + SimpleRatioUniforms, + UNURANError +) +from pytest import raises as assert_raises +from scipy import stats +from scipy import special +from scipy.stats import chisquare, cramervonmises +from scipy.stats._distr_params import distdiscrete, distcont +from scipy._lib._util import check_random_state + + +# common test data: this data can be shared between all the tests. + + +# Normal distribution shared between all the continuous methods +class StandardNormal: + def pdf(self, x): + # normalization constant needed for NumericalInverseHermite + return 1./np.sqrt(2.*np.pi) * np.exp(-0.5 * x*x) + + def dpdf(self, x): + return 1./np.sqrt(2.*np.pi) * -x * np.exp(-0.5 * x*x) + + def cdf(self, x): + return special.ndtr(x) + + +all_methods = [ + ("TransformedDensityRejection", {"dist": StandardNormal()}), + ("DiscreteAliasUrn", {"dist": [0.02, 0.18, 0.8]}), + ("DiscreteGuideTable", {"dist": [0.02, 0.18, 0.8]}), + ("NumericalInversePolynomial", {"dist": StandardNormal()}), + ("NumericalInverseHermite", {"dist": StandardNormal()}), + ("SimpleRatioUniforms", {"dist": StandardNormal(), "mode": 0}) +] + +if (sys.implementation.name == 'pypy' + and sys.implementation.version < (7, 3, 10)): + # changed in PyPy for v7.3.10 + floaterr = r"unsupported operand type for float\(\): 'list'" +else: + floaterr = r"must be real number, not list" +# Make sure an internal error occurs in UNU.RAN when invalid callbacks are +# passed. Moreover, different generators throw different error messages. +# So, in case of an `UNURANError`, we do not validate the error message. +bad_pdfs_common = [ + # Negative PDF + (lambda x: -x, UNURANError, r"..."), + # Returning wrong type + (lambda x: [], TypeError, floaterr), + # Undefined name inside the function + (lambda x: foo, NameError, r"name 'foo' is not defined"), # type: ignore[name-defined] # noqa: F821, E501 + # Infinite value returned => Overflow error. + (lambda x: np.inf, UNURANError, r"..."), + # NaN value => internal error in UNU.RAN + (lambda x: np.nan, UNURANError, r"..."), + # signature of PDF wrong + (lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given") +] + + +# same approach for dpdf +bad_dpdf_common = [ + # Infinite value returned. + (lambda x: np.inf, UNURANError, r"..."), + # NaN value => internal error in UNU.RAN + (lambda x: np.nan, UNURANError, r"..."), + # Returning wrong type + (lambda x: [], TypeError, floaterr), + # Undefined name inside the function + (lambda x: foo, NameError, r"name 'foo' is not defined"), # type: ignore[name-defined] # noqa: F821, E501 + # signature of dPDF wrong + (lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given") +] + + +# same approach for logpdf +bad_logpdfs_common = [ + # Returning wrong type + (lambda x: [], TypeError, floaterr), + # Undefined name inside the function + (lambda x: foo, NameError, r"name 'foo' is not defined"), # type: ignore[name-defined] # noqa: F821, E501 + # Infinite value returned => Overflow error. + (lambda x: np.inf, UNURANError, r"..."), + # NaN value => internal error in UNU.RAN + (lambda x: np.nan, UNURANError, r"..."), + # signature of logpdf wrong + (lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given") +] + + +bad_pv_common = [ + ([], r"must contain at least one element"), + ([[1.0, 0.0]], r"wrong number of dimensions \(expected 1, got 2\)"), + ([0.2, 0.4, np.nan, 0.8], r"must contain only finite / non-nan values"), + ([0.2, 0.4, np.inf, 0.8], r"must contain only finite / non-nan values"), + ([0.0, 0.0], r"must contain at least one non-zero value"), +] + + +# size of the domains is incorrect +bad_sized_domains = [ + # > 2 elements in the domain + ((1, 2, 3), ValueError, r"must be a length 2 tuple"), + # empty domain + ((), ValueError, r"must be a length 2 tuple") +] + +# domain values are incorrect +bad_domains = [ + ((2, 1), UNURANError, r"left >= right"), + ((1, 1), UNURANError, r"left >= right"), +] + +# infinite and nan values present in domain. +inf_nan_domains = [ + # left >= right + ((10, 10), UNURANError, r"left >= right"), + ((np.inf, np.inf), UNURANError, r"left >= right"), + ((-np.inf, -np.inf), UNURANError, r"left >= right"), + ((np.inf, -np.inf), UNURANError, r"left >= right"), + # Also include nans in some of the domains. + ((-np.inf, np.nan), ValueError, r"only non-nan values"), + ((np.nan, np.inf), ValueError, r"only non-nan values") +] + +# `nan` values present in domain. Some distributions don't support +# infinite tails, so don't mix the nan values with infinities. +nan_domains = [ + ((0, np.nan), ValueError, r"only non-nan values"), + ((np.nan, np.nan), ValueError, r"only non-nan values") +] + + +# all the methods should throw errors for nan, bad sized, and bad valued +# domains. +@pytest.mark.parametrize("domain, err, msg", + bad_domains + bad_sized_domains + + nan_domains) # type: ignore[operator] +@pytest.mark.parametrize("method, kwargs", all_methods) +def test_bad_domain(domain, err, msg, method, kwargs): + Method = getattr(stats.sampling, method) + with pytest.raises(err, match=msg): + Method(**kwargs, domain=domain) + + +@pytest.mark.parametrize("method, kwargs", all_methods) +def test_random_state(method, kwargs): + Method = getattr(stats.sampling, method) + + # simple seed that works for any version of NumPy + seed = 123 + rng1 = Method(**kwargs, random_state=seed) + rng2 = Method(**kwargs, random_state=seed) + assert_equal(rng1.rvs(100), rng2.rvs(100)) + + # global seed + np.random.seed(123) + rng1 = Method(**kwargs) + rvs1 = rng1.rvs(100) + np.random.seed(None) + rng2 = Method(**kwargs, random_state=123) + rvs2 = rng2.rvs(100) + assert_equal(rvs1, rvs2) + + # Generator seed for new NumPy + # when a RandomState is given, it should take the bitgen_t + # member of the class and create a Generator instance. + seed1 = np.random.RandomState(np.random.MT19937(123)) + seed2 = np.random.Generator(np.random.MT19937(123)) + rng1 = Method(**kwargs, random_state=seed1) + rng2 = Method(**kwargs, random_state=seed2) + assert_equal(rng1.rvs(100), rng2.rvs(100)) + + +def test_set_random_state(): + rng1 = TransformedDensityRejection(StandardNormal(), random_state=123) + rng2 = TransformedDensityRejection(StandardNormal()) + rng2.set_random_state(123) + assert_equal(rng1.rvs(100), rng2.rvs(100)) + rng = TransformedDensityRejection(StandardNormal(), random_state=123) + rvs1 = rng.rvs(100) + rng.set_random_state(123) + rvs2 = rng.rvs(100) + assert_equal(rvs1, rvs2) + + +def test_threading_behaviour(): + # Test if the API is thread-safe. + # This verifies if the lock mechanism and the use of `PyErr_Occurred` + # is correct. + errors = {"err1": None, "err2": None} + + class Distribution: + def __init__(self, pdf_msg): + self.pdf_msg = pdf_msg + + def pdf(self, x): + if 49.9 < x < 50.0: + raise ValueError(self.pdf_msg) + return x + + def dpdf(self, x): + return 1 + + def func1(): + dist = Distribution('foo') + rng = TransformedDensityRejection(dist, domain=(10, 100), + random_state=12) + try: + rng.rvs(100000) + except ValueError as e: + errors['err1'] = e.args[0] + + def func2(): + dist = Distribution('bar') + rng = TransformedDensityRejection(dist, domain=(10, 100), + random_state=2) + try: + rng.rvs(100000) + except ValueError as e: + errors['err2'] = e.args[0] + + t1 = threading.Thread(target=func1) + t2 = threading.Thread(target=func2) + + t1.start() + t2.start() + + t1.join() + t2.join() + + assert errors['err1'] == 'foo' + assert errors['err2'] == 'bar' + + +@pytest.mark.parametrize("method, kwargs", all_methods) +def test_pickle(method, kwargs): + Method = getattr(stats.sampling, method) + rng1 = Method(**kwargs, random_state=123) + obj = pickle.dumps(rng1) + rng2 = pickle.loads(obj) + assert_equal(rng1.rvs(100), rng2.rvs(100)) + + +@pytest.mark.parametrize("size", [None, 0, (0, ), 1, (10, 3), (2, 3, 4, 5), + (0, 0), (0, 1)]) +def test_rvs_size(size): + # As the `rvs` method is present in the base class and shared between + # all the classes, we can just test with one of the methods. + rng = TransformedDensityRejection(StandardNormal()) + if size is None: + assert np.isscalar(rng.rvs(size)) + else: + if np.isscalar(size): + size = (size, ) + assert rng.rvs(size).shape == size + + +def test_with_scipy_distribution(): + # test if the setup works with SciPy's rv_frozen distributions + dist = stats.norm() + urng = np.random.default_rng(0) + rng = NumericalInverseHermite(dist, random_state=urng) + u = np.linspace(0, 1, num=100) + check_cont_samples(rng, dist, dist.stats()) + assert_allclose(dist.ppf(u), rng.ppf(u)) + # test if it works with `loc` and `scale` + dist = stats.norm(loc=10., scale=5.) + rng = NumericalInverseHermite(dist, random_state=urng) + check_cont_samples(rng, dist, dist.stats()) + assert_allclose(dist.ppf(u), rng.ppf(u)) + # check for discrete distributions + dist = stats.binom(10, 0.2) + rng = DiscreteAliasUrn(dist, random_state=urng) + domain = dist.support() + pv = dist.pmf(np.arange(domain[0], domain[1]+1)) + check_discr_samples(rng, pv, dist.stats()) + + +def check_cont_samples(rng, dist, mv_ex, rtol=1e-7, atol=1e-1): + rvs = rng.rvs(100000) + mv = rvs.mean(), rvs.var() + # test the moments only if the variance is finite + if np.isfinite(mv_ex[1]): + assert_allclose(mv, mv_ex, rtol=rtol, atol=atol) + # Cramer Von Mises test for goodness-of-fit + rvs = rng.rvs(500) + dist.cdf = np.vectorize(dist.cdf) + pval = cramervonmises(rvs, dist.cdf).pvalue + assert pval > 0.1 + + +def check_discr_samples(rng, pv, mv_ex, rtol=1e-3, atol=1e-1): + rvs = rng.rvs(100000) + # test if the first few moments match + mv = rvs.mean(), rvs.var() + assert_allclose(mv, mv_ex, rtol=rtol, atol=atol) + # normalize + pv = pv / pv.sum() + # chi-squared test for goodness-of-fit + obs_freqs = np.zeros_like(pv) + _, freqs = np.unique(rvs, return_counts=True) + freqs = freqs / freqs.sum() + obs_freqs[:freqs.size] = freqs + pval = chisquare(obs_freqs, pv).pvalue + assert pval > 0.1 + + +def test_warning_center_not_in_domain(): + # UNURAN will warn if the center provided or the one computed w/o the + # domain is outside of the domain + msg = "102 : center moved into domain of distribution" + with pytest.warns(RuntimeWarning, match=msg): + NumericalInversePolynomial(StandardNormal(), center=0, domain=(3, 5)) + with pytest.warns(RuntimeWarning, match=msg): + NumericalInversePolynomial(StandardNormal(), domain=(3, 5)) + + +@pytest.mark.parametrize('method', ["SimpleRatioUniforms", + "NumericalInversePolynomial", + "TransformedDensityRejection"]) +def test_error_mode_not_in_domain(method): + # UNURAN raises an error if the mode is not in the domain + # the behavior is different compared to the case that center is not in the + # domain. mode is supposed to be the exact value, center can be an + # approximate value + Method = getattr(stats.sampling, method) + msg = "17 : mode not in domain" + with pytest.raises(UNURANError, match=msg): + Method(StandardNormal(), mode=0, domain=(3, 5)) + + +@pytest.mark.parametrize('method', ["NumericalInverseHermite", + "NumericalInversePolynomial"]) +class TestQRVS: + def test_input_validation(self, method): + match = "`qmc_engine` must be an instance of..." + with pytest.raises(ValueError, match=match): + Method = getattr(stats.sampling, method) + gen = Method(StandardNormal()) + gen.qrvs(qmc_engine=0) + + # issues with QMCEngines and old NumPy + Method = getattr(stats.sampling, method) + gen = Method(StandardNormal()) + + match = "`d` must be consistent with dimension of `qmc_engine`." + with pytest.raises(ValueError, match=match): + gen.qrvs(d=3, qmc_engine=stats.qmc.Halton(2)) + + qrngs = [None, stats.qmc.Sobol(1, seed=0), stats.qmc.Halton(3, seed=0)] + # `size=None` should not add anything to the shape, `size=1` should + sizes = [(None, tuple()), (1, (1,)), (4, (4,)), + ((4,), (4,)), ((2, 4), (2, 4))] # type: ignore + # Neither `d=None` nor `d=1` should add anything to the shape + ds = [(None, tuple()), (1, tuple()), (3, (3,))] + + @pytest.mark.parametrize('qrng', qrngs) + @pytest.mark.parametrize('size_in, size_out', sizes) + @pytest.mark.parametrize('d_in, d_out', ds) + def test_QRVS_shape_consistency(self, qrng, size_in, size_out, + d_in, d_out, method): + w32 = sys.platform == "win32" and platform.architecture()[0] == "32bit" + if w32 and method == "NumericalInversePolynomial": + pytest.xfail("NumericalInversePolynomial.qrvs fails for Win " + "32-bit") + + dist = StandardNormal() + Method = getattr(stats.sampling, method) + gen = Method(dist) + + # If d and qrng.d are inconsistent, an error is raised + if d_in is not None and qrng is not None and qrng.d != d_in: + match = "`d` must be consistent with dimension of `qmc_engine`." + with pytest.raises(ValueError, match=match): + gen.qrvs(size_in, d=d_in, qmc_engine=qrng) + return + + # Sometimes d is really determined by qrng + if d_in is None and qrng is not None and qrng.d != 1: + d_out = (qrng.d,) + + shape_expected = size_out + d_out + + qrng2 = deepcopy(qrng) + qrvs = gen.qrvs(size=size_in, d=d_in, qmc_engine=qrng) + if size_in is not None: + assert qrvs.shape == shape_expected + + if qrng2 is not None: + uniform = qrng2.random(np.prod(size_in) or 1) + qrvs2 = stats.norm.ppf(uniform).reshape(shape_expected) + assert_allclose(qrvs, qrvs2, atol=1e-12) + + def test_QRVS_size_tuple(self, method): + # QMCEngine samples are always of shape (n, d). When `size` is a tuple, + # we set `n = prod(size)` in the call to qmc_engine.random, transform + # the sample, and reshape it to the final dimensions. When we reshape, + # we need to be careful, because the _columns_ of the sample returned + # by a QMCEngine are "independent"-ish, but the elements within the + # columns are not. We need to make sure that this doesn't get mixed up + # by reshaping: qrvs[..., i] should remain "independent"-ish of + # qrvs[..., i+1], but the elements within qrvs[..., i] should be + # transformed from the same low-discrepancy sequence. + + dist = StandardNormal() + Method = getattr(stats.sampling, method) + gen = Method(dist) + + size = (3, 4) + d = 5 + qrng = stats.qmc.Halton(d, seed=0) + qrng2 = stats.qmc.Halton(d, seed=0) + + uniform = qrng2.random(np.prod(size)) + + qrvs = gen.qrvs(size=size, d=d, qmc_engine=qrng) + qrvs2 = stats.norm.ppf(uniform) + + for i in range(d): + sample = qrvs[..., i] + sample2 = qrvs2[:, i].reshape(size) + assert_allclose(sample, sample2, atol=1e-12) + + +class TestTransformedDensityRejection: + # Simple Custom Distribution + class dist0: + def pdf(self, x): + return 3/4 * (1-x*x) + + def dpdf(self, x): + return 3/4 * (-2*x) + + def cdf(self, x): + return 3/4 * (x - x**3/3 + 2/3) + + def support(self): + return -1, 1 + + # Standard Normal Distribution + class dist1: + def pdf(self, x): + return stats.norm._pdf(x / 0.1) + + def dpdf(self, x): + return -x / 0.01 * stats.norm._pdf(x / 0.1) + + def cdf(self, x): + return stats.norm._cdf(x / 0.1) + + # pdf with piecewise linear function as transformed density + # with T = -1/sqrt with shift. Taken from UNU.RAN test suite + # (from file t_tdr_ps.c) + class dist2: + def __init__(self, shift): + self.shift = shift + + def pdf(self, x): + x -= self.shift + y = 1. / (abs(x) + 1.) + return 0.5 * y * y + + def dpdf(self, x): + x -= self.shift + y = 1. / (abs(x) + 1.) + y = y * y * y + return y if (x < 0.) else -y + + def cdf(self, x): + x -= self.shift + if x <= 0.: + return 0.5 / (1. - x) + else: + return 1. - 0.5 / (1. + x) + + dists = [dist0(), dist1(), dist2(0.), dist2(10000.)] + + # exact mean and variance of the distributions in the list dists + mv0 = [0., 4./15.] + mv1 = [0., 0.01] + mv2 = [0., np.inf] + mv3 = [10000., np.inf] + mvs = [mv0, mv1, mv2, mv3] + + @pytest.mark.parametrize("dist, mv_ex", + zip(dists, mvs)) + def test_basic(self, dist, mv_ex): + with suppress_warnings() as sup: + # filter the warnings thrown by UNU.RAN + sup.filter(RuntimeWarning) + rng = TransformedDensityRejection(dist, random_state=42) + check_cont_samples(rng, dist, mv_ex) + + # PDF 0 everywhere => bad construction points + bad_pdfs = [(lambda x: 0, UNURANError, r"50 : bad construction points.")] + bad_pdfs += bad_pdfs_common # type: ignore[arg-type] + + @pytest.mark.parametrize("pdf, err, msg", bad_pdfs) + def test_bad_pdf(self, pdf, err, msg): + class dist: + pass + dist.pdf = pdf + dist.dpdf = lambda x: 1 # an arbitrary dPDF + with pytest.raises(err, match=msg): + TransformedDensityRejection(dist) + + @pytest.mark.parametrize("dpdf, err, msg", bad_dpdf_common) + def test_bad_dpdf(self, dpdf, err, msg): + class dist: + pass + dist.pdf = lambda x: x + dist.dpdf = dpdf + with pytest.raises(err, match=msg): + TransformedDensityRejection(dist, domain=(1, 10)) + + # test domains with inf + nan in them. need to write a custom test for + # this because not all methods support infinite tails. + @pytest.mark.parametrize("domain, err, msg", inf_nan_domains) + def test_inf_nan_domains(self, domain, err, msg): + with pytest.raises(err, match=msg): + TransformedDensityRejection(StandardNormal(), domain=domain) + + @pytest.mark.parametrize("construction_points", [-1, 0, 0.1]) + def test_bad_construction_points_scalar(self, construction_points): + with pytest.raises(ValueError, match=r"`construction_points` must be " + r"a positive integer."): + TransformedDensityRejection( + StandardNormal(), construction_points=construction_points + ) + + def test_bad_construction_points_array(self): + # empty array + construction_points = [] + with pytest.raises(ValueError, match=r"`construction_points` must " + r"either be a " + r"scalar or a non-empty array."): + TransformedDensityRejection( + StandardNormal(), construction_points=construction_points + ) + + # construction_points not monotonically increasing + construction_points = [1, 1, 1, 1, 1, 1] + with pytest.warns(RuntimeWarning, match=r"33 : starting points not " + r"strictly monotonically " + r"increasing"): + TransformedDensityRejection( + StandardNormal(), construction_points=construction_points + ) + + # construction_points containing nans + construction_points = [np.nan, np.nan, np.nan] + with pytest.raises(UNURANError, match=r"50 : bad construction " + r"points."): + TransformedDensityRejection( + StandardNormal(), construction_points=construction_points + ) + + # construction_points out of domain + construction_points = [-10, 10] + with pytest.warns(RuntimeWarning, match=r"50 : starting point out of " + r"domain"): + TransformedDensityRejection( + StandardNormal(), domain=(-3, 3), + construction_points=construction_points + ) + + @pytest.mark.parametrize("c", [-1., np.nan, np.inf, 0.1, 1.]) + def test_bad_c(self, c): + msg = r"`c` must either be -0.5 or 0." + with pytest.raises(ValueError, match=msg): + TransformedDensityRejection(StandardNormal(), c=-1.) + + u = [np.linspace(0, 1, num=1000), [], [[]], [np.nan], + [-np.inf, np.nan, np.inf], 0, + [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]] + + @pytest.mark.parametrize("u", u) + def test_ppf_hat(self, u): + # Increase the `max_squeeze_hat_ratio` so the ppf_hat is more + # accurate. + rng = TransformedDensityRejection(StandardNormal(), + max_squeeze_hat_ratio=0.9999) + # Older versions of NumPy throw RuntimeWarnings for comparisons + # with nan. + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in greater") + sup.filter(RuntimeWarning, "invalid value encountered in " + "greater_equal") + sup.filter(RuntimeWarning, "invalid value encountered in less") + sup.filter(RuntimeWarning, "invalid value encountered in " + "less_equal") + res = rng.ppf_hat(u) + expected = stats.norm.ppf(u) + assert_allclose(res, expected, rtol=1e-3, atol=1e-5) + assert res.shape == expected.shape + + def test_bad_dist(self): + # Empty distribution + class dist: + ... + + msg = r"`pdf` required but not found." + with pytest.raises(ValueError, match=msg): + TransformedDensityRejection(dist) + + # dPDF not present in dist + class dist: + pdf = lambda x: 1-x*x # noqa: E731 + + msg = r"`dpdf` required but not found." + with pytest.raises(ValueError, match=msg): + TransformedDensityRejection(dist) + + +class TestDiscreteAliasUrn: + # DAU fails on these probably because of large domains and small + # computation errors in PMF. Mean/SD match but chi-squared test fails. + basic_fail_dists = { + 'nchypergeom_fisher', # numerical errors on tails + 'nchypergeom_wallenius', # numerical errors on tails + 'randint' # fails on 32-bit ubuntu + } + + @pytest.mark.parametrize("distname, params", distdiscrete) + def test_basic(self, distname, params): + if distname in self.basic_fail_dists: + msg = ("DAU fails on these probably because of large domains " + "and small computation errors in PMF.") + pytest.skip(msg) + if not isinstance(distname, str): + dist = distname + else: + dist = getattr(stats, distname) + dist = dist(*params) + domain = dist.support() + if not np.isfinite(domain[1] - domain[0]): + # DAU only works with finite domain. So, skip the distributions + # with infinite tails. + pytest.skip("DAU only works with a finite domain.") + k = np.arange(domain[0], domain[1]+1) + pv = dist.pmf(k) + mv_ex = dist.stats('mv') + rng = DiscreteAliasUrn(dist, random_state=42) + check_discr_samples(rng, pv, mv_ex) + + # Can't use bad_pmf_common here as we evaluate PMF early on to avoid + # unhelpful errors from UNU.RAN. + bad_pmf = [ + # inf returned + (lambda x: np.inf, ValueError, + r"must contain only finite / non-nan values"), + # nan returned + (lambda x: np.nan, ValueError, + r"must contain only finite / non-nan values"), + # all zeros + (lambda x: 0.0, ValueError, + r"must contain at least one non-zero value"), + # Undefined name inside the function + (lambda x: foo, NameError, # type: ignore[name-defined] # noqa: F821 + r"name 'foo' is not defined"), + # Returning wrong type. + (lambda x: [], ValueError, + r"setting an array element with a sequence."), + # probabilities < 0 + (lambda x: -x, UNURANError, + r"50 : probability < 0"), + # signature of PMF wrong + (lambda: 1.0, TypeError, + r"takes 0 positional arguments but 1 was given") + ] + + @pytest.mark.parametrize("pmf, err, msg", bad_pmf) + def test_bad_pmf(self, pmf, err, msg): + class dist: + pass + dist.pmf = pmf + with pytest.raises(err, match=msg): + DiscreteAliasUrn(dist, domain=(1, 10)) + + @pytest.mark.parametrize("pv", [[0.18, 0.02, 0.8], + [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]]) + def test_sampling_with_pv(self, pv): + pv = np.asarray(pv, dtype=np.float64) + rng = DiscreteAliasUrn(pv, random_state=123) + rng.rvs(100_000) + pv = pv / pv.sum() + variates = np.arange(0, len(pv)) + # test if the first few moments match + m_expected = np.average(variates, weights=pv) + v_expected = np.average((variates - m_expected) ** 2, weights=pv) + mv_expected = m_expected, v_expected + check_discr_samples(rng, pv, mv_expected) + + @pytest.mark.parametrize("pv, msg", bad_pv_common) + def test_bad_pv(self, pv, msg): + with pytest.raises(ValueError, match=msg): + DiscreteAliasUrn(pv) + + # DAU doesn't support infinite tails. So, it should throw an error when + # inf is present in the domain. + inf_domain = [(-np.inf, np.inf), (np.inf, np.inf), (-np.inf, -np.inf), + (0, np.inf), (-np.inf, 0)] + + @pytest.mark.parametrize("domain", inf_domain) + def test_inf_domain(self, domain): + with pytest.raises(ValueError, match=r"must be finite"): + DiscreteAliasUrn(stats.binom(10, 0.2), domain=domain) + + def test_bad_urn_factor(self): + with pytest.warns(RuntimeWarning, match=r"relative urn size < 1."): + DiscreteAliasUrn([0.5, 0.5], urn_factor=-1) + + def test_bad_args(self): + msg = (r"`domain` must be provided when the " + r"probability vector is not available.") + + class dist: + def pmf(self, x): + return x + + with pytest.raises(ValueError, match=msg): + DiscreteAliasUrn(dist) + + def test_gh19359(self): + pv = special.softmax(np.ones((1533,))) + rng = DiscreteAliasUrn(pv, random_state=42) + # check the correctness + check_discr_samples(rng, pv, (1532 / 2, (1532**2 - 1) / 12), + rtol=5e-3) + + +class TestNumericalInversePolynomial: + # Simple Custom Distribution + class dist0: + def pdf(self, x): + return 3/4 * (1-x*x) + + def cdf(self, x): + return 3/4 * (x - x**3/3 + 2/3) + + def support(self): + return -1, 1 + + # Standard Normal Distribution + class dist1: + def pdf(self, x): + return stats.norm._pdf(x / 0.1) + + def cdf(self, x): + return stats.norm._cdf(x / 0.1) + + # Sin 2 distribution + # / 0.05 + 0.45*(1 +sin(2 Pi x)) if |x| <= 1 + # f(x) = < + # \ 0 otherwise + # Taken from UNU.RAN test suite (from file t_pinv.c) + class dist2: + def pdf(self, x): + return 0.05 + 0.45 * (1 + np.sin(2*np.pi*x)) + + def cdf(self, x): + return (0.05*(x + 1) + + 0.9*(1. + 2.*np.pi*(1 + x) - np.cos(2.*np.pi*x)) / + (4.*np.pi)) + + def support(self): + return -1, 1 + + # Sin 10 distribution + # / 0.05 + 0.45*(1 +sin(2 Pi x)) if |x| <= 5 + # f(x) = < + # \ 0 otherwise + # Taken from UNU.RAN test suite (from file t_pinv.c) + class dist3: + def pdf(self, x): + return 0.2 * (0.05 + 0.45 * (1 + np.sin(2*np.pi*x))) + + def cdf(self, x): + return x/10. + 0.5 + 0.09/(2*np.pi) * (np.cos(10*np.pi) - + np.cos(2*np.pi*x)) + + def support(self): + return -5, 5 + + dists = [dist0(), dist1(), dist2(), dist3()] + + # exact mean and variance of the distributions in the list dists + mv0 = [0., 4./15.] + mv1 = [0., 0.01] + mv2 = [-0.45/np.pi, 2/3*0.5 - 0.45**2/np.pi**2] + mv3 = [-0.45/np.pi, 0.2 * 250/3 * 0.5 - 0.45**2/np.pi**2] + mvs = [mv0, mv1, mv2, mv3] + + @pytest.mark.parametrize("dist, mv_ex", + zip(dists, mvs)) + def test_basic(self, dist, mv_ex): + rng = NumericalInversePolynomial(dist, random_state=42) + check_cont_samples(rng, dist, mv_ex) + + @pytest.mark.xslow + @pytest.mark.parametrize("distname, params", distcont) + def test_basic_all_scipy_dists(self, distname, params): + + very_slow_dists = ['anglit', 'gausshyper', 'kappa4', + 'ksone', 'kstwo', 'levy_l', + 'levy_stable', 'studentized_range', + 'trapezoid', 'triang', 'vonmises'] + # for these distributions, some assertions fail due to minor + # numerical differences. They can be avoided either by changing + # the seed or by increasing the u_resolution. + fail_dists = ['chi2', 'fatiguelife', 'gibrat', + 'halfgennorm', 'lognorm', 'ncf', + 'ncx2', 'pareto', 't'] + # for these distributions, skip the check for agreement between sample + # moments and true moments. We cannot expect them to pass due to the + # high variance of sample moments. + skip_sample_moment_check = ['rel_breitwigner'] + + if distname in very_slow_dists: + pytest.skip(f"PINV too slow for {distname}") + if distname in fail_dists: + pytest.skip(f"PINV fails for {distname}") + dist = (getattr(stats, distname) + if isinstance(distname, str) + else distname) + dist = dist(*params) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning) + rng = NumericalInversePolynomial(dist, random_state=42) + if distname in skip_sample_moment_check: + return + check_cont_samples(rng, dist, [dist.mean(), dist.var()]) + + @pytest.mark.parametrize("pdf, err, msg", bad_pdfs_common) + def test_bad_pdf(self, pdf, err, msg): + class dist: + pass + dist.pdf = pdf + with pytest.raises(err, match=msg): + NumericalInversePolynomial(dist, domain=[0, 5]) + + @pytest.mark.parametrize("logpdf, err, msg", bad_logpdfs_common) + def test_bad_logpdf(self, logpdf, err, msg): + class dist: + pass + dist.logpdf = logpdf + with pytest.raises(err, match=msg): + NumericalInversePolynomial(dist, domain=[0, 5]) + + # test domains with inf + nan in them. need to write a custom test for + # this because not all methods support infinite tails. + @pytest.mark.parametrize("domain, err, msg", inf_nan_domains) + def test_inf_nan_domains(self, domain, err, msg): + with pytest.raises(err, match=msg): + NumericalInversePolynomial(StandardNormal(), domain=domain) + + u = [ + # test if quantile 0 and 1 return -inf and inf respectively and check + # the correctness of the PPF for equidistant points between 0 and 1. + np.linspace(0, 1, num=10000), + # test the PPF method for empty arrays + [], [[]], + # test if nans and infs return nan result. + [np.nan], [-np.inf, np.nan, np.inf], + # test if a scalar is returned for a scalar input. + 0, + # test for arrays with nans, values greater than 1 and less than 0, + # and some valid values. + [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]] + ] + + @pytest.mark.parametrize("u", u) + def test_ppf(self, u): + dist = StandardNormal() + rng = NumericalInversePolynomial(dist, u_resolution=1e-14) + # Older versions of NumPy throw RuntimeWarnings for comparisons + # with nan. + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in greater") + sup.filter(RuntimeWarning, "invalid value encountered in " + "greater_equal") + sup.filter(RuntimeWarning, "invalid value encountered in less") + sup.filter(RuntimeWarning, "invalid value encountered in " + "less_equal") + res = rng.ppf(u) + expected = stats.norm.ppf(u) + assert_allclose(res, expected, rtol=1e-11, atol=1e-11) + assert res.shape == expected.shape + + x = [np.linspace(-10, 10, num=10000), [], [[]], [np.nan], + [-np.inf, np.nan, np.inf], 0, + [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-np.inf, 3, 4]]] + + @pytest.mark.parametrize("x", x) + def test_cdf(self, x): + dist = StandardNormal() + rng = NumericalInversePolynomial(dist, u_resolution=1e-14) + # Older versions of NumPy throw RuntimeWarnings for comparisons + # with nan. + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in greater") + sup.filter(RuntimeWarning, "invalid value encountered in " + "greater_equal") + sup.filter(RuntimeWarning, "invalid value encountered in less") + sup.filter(RuntimeWarning, "invalid value encountered in " + "less_equal") + res = rng.cdf(x) + expected = stats.norm.cdf(x) + assert_allclose(res, expected, rtol=1e-11, atol=1e-11) + assert res.shape == expected.shape + + @pytest.mark.slow + def test_u_error(self): + dist = StandardNormal() + rng = NumericalInversePolynomial(dist, u_resolution=1e-10) + max_error, mae = rng.u_error() + assert max_error < 1e-10 + assert mae <= max_error + rng = NumericalInversePolynomial(dist, u_resolution=1e-14) + max_error, mae = rng.u_error() + assert max_error < 1e-14 + assert mae <= max_error + + bad_orders = [1, 4.5, 20, np.inf, np.nan] + bad_u_resolution = [1e-20, 1e-1, np.inf, np.nan] + + @pytest.mark.parametrize("order", bad_orders) + def test_bad_orders(self, order): + dist = StandardNormal() + + msg = r"`order` must be an integer in the range \[3, 17\]." + with pytest.raises(ValueError, match=msg): + NumericalInversePolynomial(dist, order=order) + + @pytest.mark.parametrize("u_resolution", bad_u_resolution) + def test_bad_u_resolution(self, u_resolution): + msg = r"`u_resolution` must be between 1e-15 and 1e-5." + with pytest.raises(ValueError, match=msg): + NumericalInversePolynomial(StandardNormal(), + u_resolution=u_resolution) + + def test_bad_args(self): + + class BadDist: + def cdf(self, x): + return stats.norm._cdf(x) + + dist = BadDist() + msg = r"Either of the methods `pdf` or `logpdf` must be specified" + with pytest.raises(ValueError, match=msg): + rng = NumericalInversePolynomial(dist) + + dist = StandardNormal() + rng = NumericalInversePolynomial(dist) + msg = r"`sample_size` must be greater than or equal to 1000." + with pytest.raises(ValueError, match=msg): + rng.u_error(10) + + class Distribution: + def pdf(self, x): + return np.exp(-0.5 * x*x) + + dist = Distribution() + rng = NumericalInversePolynomial(dist) + msg = r"Exact CDF required but not found." + with pytest.raises(ValueError, match=msg): + rng.u_error() + + def test_logpdf_pdf_consistency(self): + # 1. check that PINV works with pdf and logpdf only + # 2. check that generated ppf is the same (up to a small tolerance) + + class MyDist: + pass + + # create generator from dist with only pdf + dist_pdf = MyDist() + dist_pdf.pdf = lambda x: math.exp(-x*x/2) + rng1 = NumericalInversePolynomial(dist_pdf) + + # create dist with only logpdf + dist_logpdf = MyDist() + dist_logpdf.logpdf = lambda x: -x*x/2 + rng2 = NumericalInversePolynomial(dist_logpdf) + + q = np.linspace(1e-5, 1-1e-5, num=100) + assert_allclose(rng1.ppf(q), rng2.ppf(q)) + + +class TestNumericalInverseHermite: + # / (1 +sin(2 Pi x))/2 if |x| <= 1 + # f(x) = < + # \ 0 otherwise + # Taken from UNU.RAN test suite (from file t_hinv.c) + class dist0: + def pdf(self, x): + return 0.5*(1. + np.sin(2.*np.pi*x)) + + def dpdf(self, x): + return np.pi*np.cos(2.*np.pi*x) + + def cdf(self, x): + return (1. + 2.*np.pi*(1 + x) - np.cos(2.*np.pi*x)) / (4.*np.pi) + + def support(self): + return -1, 1 + + # / Max(sin(2 Pi x)),0)Pi/2 if -1 < x <0.5 + # f(x) = < + # \ 0 otherwise + # Taken from UNU.RAN test suite (from file t_hinv.c) + class dist1: + def pdf(self, x): + if (x <= -0.5): + return np.sin((2. * np.pi) * x) * 0.5 * np.pi + if (x < 0.): + return 0. + if (x <= 0.5): + return np.sin((2. * np.pi) * x) * 0.5 * np.pi + + def dpdf(self, x): + if (x <= -0.5): + return np.cos((2. * np.pi) * x) * np.pi * np.pi + if (x < 0.): + return 0. + if (x <= 0.5): + return np.cos((2. * np.pi) * x) * np.pi * np.pi + + def cdf(self, x): + if (x <= -0.5): + return 0.25 * (1 - np.cos((2. * np.pi) * x)) + if (x < 0.): + return 0.5 + if (x <= 0.5): + return 0.75 - 0.25 * np.cos((2. * np.pi) * x) + + def support(self): + return -1, 0.5 + + dists = [dist0(), dist1()] + + # exact mean and variance of the distributions in the list dists + mv0 = [-1/(2*np.pi), 1/3 - 1/(4*np.pi*np.pi)] + mv1 = [-1/4, 3/8-1/(2*np.pi*np.pi) - 1/16] + mvs = [mv0, mv1] + + @pytest.mark.parametrize("dist, mv_ex", + zip(dists, mvs)) + @pytest.mark.parametrize("order", [3, 5]) + def test_basic(self, dist, mv_ex, order): + rng = NumericalInverseHermite(dist, order=order, random_state=42) + check_cont_samples(rng, dist, mv_ex) + + # test domains with inf + nan in them. need to write a custom test for + # this because not all methods support infinite tails. + @pytest.mark.parametrize("domain, err, msg", inf_nan_domains) + def test_inf_nan_domains(self, domain, err, msg): + with pytest.raises(err, match=msg): + NumericalInverseHermite(StandardNormal(), domain=domain) + + def basic_test_all_scipy_dists(self, distname, shapes): + slow_dists = {'ksone', 'kstwo', 'levy_stable', 'skewnorm'} + fail_dists = {'beta', 'gausshyper', 'geninvgauss', 'ncf', 'nct', + 'norminvgauss', 'genhyperbolic', 'studentized_range', + 'vonmises', 'kappa4', 'invgauss', 'wald'} + + if distname in slow_dists: + pytest.skip("Distribution is too slow") + if distname in fail_dists: + # specific reasons documented in gh-13319 + # https://github.com/scipy/scipy/pull/13319#discussion_r626188955 + pytest.xfail("Fails - usually due to inaccurate CDF/PDF") + + np.random.seed(0) + + dist = getattr(stats, distname)(*shapes) + fni = NumericalInverseHermite(dist) + + x = np.random.rand(10) + p_tol = np.max(np.abs(dist.ppf(x)-fni.ppf(x))/np.abs(dist.ppf(x))) + u_tol = np.max(np.abs(dist.cdf(fni.ppf(x)) - x)) + + assert p_tol < 1e-8 + assert u_tol < 1e-12 + + @pytest.mark.filterwarnings('ignore::RuntimeWarning') + @pytest.mark.xslow + @pytest.mark.parametrize(("distname", "shapes"), distcont) + def test_basic_all_scipy_dists(self, distname, shapes): + # if distname == "truncnorm": + # pytest.skip("Tested separately") + self.basic_test_all_scipy_dists(distname, shapes) + + @pytest.mark.fail_slow(5) + @pytest.mark.filterwarnings('ignore::RuntimeWarning') + def test_basic_truncnorm_gh17155(self): + self.basic_test_all_scipy_dists("truncnorm", (0.1, 2)) + + def test_input_validation(self): + match = r"`order` must be either 1, 3, or 5." + with pytest.raises(ValueError, match=match): + NumericalInverseHermite(StandardNormal(), order=2) + + match = "`cdf` required but not found" + with pytest.raises(ValueError, match=match): + NumericalInverseHermite("norm") + + match = "could not convert string to float" + with pytest.raises(ValueError, match=match): + NumericalInverseHermite(StandardNormal(), + u_resolution='ekki') + + rngs = [None, 0, np.random.RandomState(0)] + rngs.append(np.random.default_rng(0)) # type: ignore + sizes = [(None, tuple()), (8, (8,)), ((4, 5, 6), (4, 5, 6))] + + @pytest.mark.parametrize('rng', rngs) + @pytest.mark.parametrize('size_in, size_out', sizes) + def test_RVS(self, rng, size_in, size_out): + dist = StandardNormal() + fni = NumericalInverseHermite(dist) + + rng2 = deepcopy(rng) + rvs = fni.rvs(size=size_in, random_state=rng) + if size_in is not None: + assert rvs.shape == size_out + + if rng2 is not None: + rng2 = check_random_state(rng2) + uniform = rng2.uniform(size=size_in) + rvs2 = stats.norm.ppf(uniform) + assert_allclose(rvs, rvs2) + + def test_inaccurate_CDF(self): + # CDF function with inaccurate tail cannot be inverted; see gh-13319 + # https://github.com/scipy/scipy/pull/13319#discussion_r626188955 + shapes = (2.3098496451481823, 0.6268795430096368) + match = ("98 : one or more intervals very short; possibly due to " + "numerical problems with a pole or very flat tail") + + # fails with default tol + with pytest.warns(RuntimeWarning, match=match): + NumericalInverseHermite(stats.beta(*shapes)) + + # no error with coarser tol + NumericalInverseHermite(stats.beta(*shapes), u_resolution=1e-8) + + def test_custom_distribution(self): + dist1 = StandardNormal() + fni1 = NumericalInverseHermite(dist1) + + dist2 = stats.norm() + fni2 = NumericalInverseHermite(dist2) + + assert_allclose(fni1.rvs(random_state=0), fni2.rvs(random_state=0)) + + u = [ + # check the correctness of the PPF for equidistant points between + # 0.02 and 0.98. + np.linspace(0., 1., num=10000), + # test the PPF method for empty arrays + [], [[]], + # test if nans and infs return nan result. + [np.nan], [-np.inf, np.nan, np.inf], + # test if a scalar is returned for a scalar input. + 0, + # test for arrays with nans, values greater than 1 and less than 0, + # and some valid values. + [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]] + ] + + @pytest.mark.parametrize("u", u) + def test_ppf(self, u): + dist = StandardNormal() + rng = NumericalInverseHermite(dist, u_resolution=1e-12) + # Older versions of NumPy throw RuntimeWarnings for comparisons + # with nan. + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in greater") + sup.filter(RuntimeWarning, "invalid value encountered in " + "greater_equal") + sup.filter(RuntimeWarning, "invalid value encountered in less") + sup.filter(RuntimeWarning, "invalid value encountered in " + "less_equal") + res = rng.ppf(u) + expected = stats.norm.ppf(u) + assert_allclose(res, expected, rtol=1e-9, atol=3e-10) + assert res.shape == expected.shape + + @pytest.mark.slow + def test_u_error(self): + dist = StandardNormal() + rng = NumericalInverseHermite(dist, u_resolution=1e-10) + max_error, mae = rng.u_error() + assert max_error < 1e-10 + assert mae <= max_error + with suppress_warnings() as sup: + # ignore warning about u-resolution being too small. + sup.filter(RuntimeWarning) + rng = NumericalInverseHermite(dist, u_resolution=1e-14) + max_error, mae = rng.u_error() + assert max_error < 1e-14 + assert mae <= max_error + + +class TestDiscreteGuideTable: + basic_fail_dists = { + 'nchypergeom_fisher', # numerical errors on tails + 'nchypergeom_wallenius', # numerical errors on tails + 'randint' # fails on 32-bit ubuntu + } + + def test_guide_factor_gt3_raises_warning(self): + pv = [0.1, 0.3, 0.6] + urng = np.random.default_rng() + with pytest.warns(RuntimeWarning): + DiscreteGuideTable(pv, random_state=urng, guide_factor=7) + + def test_guide_factor_zero_raises_warning(self): + pv = [0.1, 0.3, 0.6] + urng = np.random.default_rng() + with pytest.warns(RuntimeWarning): + DiscreteGuideTable(pv, random_state=urng, guide_factor=0) + + def test_negative_guide_factor_raises_warning(self): + # This occurs from the UNU.RAN wrapper automatically. + # however it already gives a useful warning + # Here we just test that a warning is raised. + pv = [0.1, 0.3, 0.6] + urng = np.random.default_rng() + with pytest.warns(RuntimeWarning): + DiscreteGuideTable(pv, random_state=urng, guide_factor=-1) + + @pytest.mark.parametrize("distname, params", distdiscrete) + def test_basic(self, distname, params): + if distname in self.basic_fail_dists: + msg = ("DGT fails on these probably because of large domains " + "and small computation errors in PMF.") + pytest.skip(msg) + + if not isinstance(distname, str): + dist = distname + else: + dist = getattr(stats, distname) + + dist = dist(*params) + domain = dist.support() + + if not np.isfinite(domain[1] - domain[0]): + # DGT only works with finite domain. So, skip the distributions + # with infinite tails. + pytest.skip("DGT only works with a finite domain.") + + k = np.arange(domain[0], domain[1]+1) + pv = dist.pmf(k) + mv_ex = dist.stats('mv') + rng = DiscreteGuideTable(dist, random_state=42) + check_discr_samples(rng, pv, mv_ex) + + u = [ + # the correctness of the PPF for equidistant points between 0 and 1. + np.linspace(0, 1, num=10000), + # test the PPF method for empty arrays + [], [[]], + # test if nans and infs return nan result. + [np.nan], [-np.inf, np.nan, np.inf], + # test if a scalar is returned for a scalar input. + 0, + # test for arrays with nans, values greater than 1 and less than 0, + # and some valid values. + [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]] + ] + + @pytest.mark.parametrize('u', u) + def test_ppf(self, u): + n, p = 4, 0.1 + dist = stats.binom(n, p) + rng = DiscreteGuideTable(dist, random_state=42) + + # Older versions of NumPy throw RuntimeWarnings for comparisons + # with nan. + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in greater") + sup.filter(RuntimeWarning, "invalid value encountered in " + "greater_equal") + sup.filter(RuntimeWarning, "invalid value encountered in less") + sup.filter(RuntimeWarning, "invalid value encountered in " + "less_equal") + + res = rng.ppf(u) + expected = stats.binom.ppf(u, n, p) + assert_equal(res.shape, expected.shape) + assert_equal(res, expected) + + @pytest.mark.parametrize("pv, msg", bad_pv_common) + def test_bad_pv(self, pv, msg): + with pytest.raises(ValueError, match=msg): + DiscreteGuideTable(pv) + + # DGT doesn't support infinite tails. So, it should throw an error when + # inf is present in the domain. + inf_domain = [(-np.inf, np.inf), (np.inf, np.inf), (-np.inf, -np.inf), + (0, np.inf), (-np.inf, 0)] + + @pytest.mark.parametrize("domain", inf_domain) + def test_inf_domain(self, domain): + with pytest.raises(ValueError, match=r"must be finite"): + DiscreteGuideTable(stats.binom(10, 0.2), domain=domain) + + +class TestSimpleRatioUniforms: + # pdf with piecewise linear function as transformed density + # with T = -1/sqrt with shift. Taken from UNU.RAN test suite + # (from file t_srou.c) + class dist: + def __init__(self, shift): + self.shift = shift + self.mode = shift + + def pdf(self, x): + x -= self.shift + y = 1. / (abs(x) + 1.) + return 0.5 * y * y + + def cdf(self, x): + x -= self.shift + if x <= 0.: + return 0.5 / (1. - x) + else: + return 1. - 0.5 / (1. + x) + + dists = [dist(0.), dist(10000.)] + + # exact mean and variance of the distributions in the list dists + mv1 = [0., np.inf] + mv2 = [10000., np.inf] + mvs = [mv1, mv2] + + @pytest.mark.parametrize("dist, mv_ex", + zip(dists, mvs)) + def test_basic(self, dist, mv_ex): + rng = SimpleRatioUniforms(dist, mode=dist.mode, random_state=42) + check_cont_samples(rng, dist, mv_ex) + rng = SimpleRatioUniforms(dist, mode=dist.mode, + cdf_at_mode=dist.cdf(dist.mode), + random_state=42) + check_cont_samples(rng, dist, mv_ex) + + # test domains with inf + nan in them. need to write a custom test for + # this because not all methods support infinite tails. + @pytest.mark.parametrize("domain, err, msg", inf_nan_domains) + def test_inf_nan_domains(self, domain, err, msg): + with pytest.raises(err, match=msg): + SimpleRatioUniforms(StandardNormal(), domain=domain) + + def test_bad_args(self): + # pdf_area < 0 + with pytest.raises(ValueError, match=r"`pdf_area` must be > 0"): + SimpleRatioUniforms(StandardNormal(), mode=0, pdf_area=-1) + + +class TestRatioUniforms: + def test_rv_generation(self): + # use KS test to check distribution of rvs + # normal distribution + f = stats.norm.pdf + v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2) + u = np.sqrt(f(0)) + gen = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12345) + assert_equal(stats.kstest(gen.rvs(2500), 'norm')[1] > 0.25, True) + + # exponential distribution + gen = RatioUniforms(lambda x: np.exp(-x), umax=1, + vmin=0, vmax=2*np.exp(-1), random_state=12345) + assert_equal(stats.kstest(gen.rvs(1000), 'expon')[1] > 0.25, True) + + def test_shape(self): + # test shape of return value depending on size parameter + f = stats.norm.pdf + v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2) + u = np.sqrt(f(0)) + + gen1 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234) + gen2 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234) + gen3 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234) + r1, r2, r3 = gen1.rvs(3), gen2.rvs((3,)), gen3.rvs((3, 1)) + assert_equal(r1, r2) + assert_equal(r2, r3.flatten()) + assert_equal(r1.shape, (3,)) + assert_equal(r3.shape, (3, 1)) + + gen4 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12) + gen5 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12) + r4, r5 = gen4.rvs(size=(3, 3, 3)), gen5.rvs(size=27) + assert_equal(r4.flatten(), r5) + assert_equal(r4.shape, (3, 3, 3)) + + gen6 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234) + gen7 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234) + gen8 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234) + r6, r7, r8 = gen6.rvs(), gen7.rvs(1), gen8.rvs((1,)) + assert_equal(r6, r7) + assert_equal(r7, r8) + + def test_random_state(self): + f = stats.norm.pdf + v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2) + umax = np.sqrt(f(0)) + gen1 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=1234) + r1 = gen1.rvs(10) + np.random.seed(1234) + gen2 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v) + r2 = gen2.rvs(10) + assert_equal(r1, r2) + + def test_exceptions(self): + f = stats.norm.pdf + # need vmin < vmax + with assert_raises(ValueError, match="vmin must be smaller than vmax"): + RatioUniforms(pdf=f, umax=1, vmin=3, vmax=1) + with assert_raises(ValueError, match="vmin must be smaller than vmax"): + RatioUniforms(pdf=f, umax=1, vmin=1, vmax=1) + # need umax > 0 + with assert_raises(ValueError, match="umax must be positive"): + RatioUniforms(pdf=f, umax=-1, vmin=1, vmax=3) + with assert_raises(ValueError, match="umax must be positive"): + RatioUniforms(pdf=f, umax=0, vmin=1, vmax=3) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sensitivity_analysis.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sensitivity_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8d53040380808c03358b905878cc4a8b9b9679 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sensitivity_analysis.py @@ -0,0 +1,310 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_array_less +import pytest + +from scipy import stats +from scipy.stats import sobol_indices +from scipy.stats._resampling import BootstrapResult +from scipy.stats._sensitivity_analysis import ( + BootstrapSobolResult, f_ishigami, sample_AB, sample_A_B +) + + +@pytest.fixture(scope='session') +def ishigami_ref_indices(): + """Reference values for Ishigami from Saltelli2007. + + Chapter 4, exercise 5 pages 179-182. + """ + a = 7. + b = 0.1 + + var = 0.5 + a**2/8 + b*np.pi**4/5 + b**2*np.pi**8/18 + v1 = 0.5 + b*np.pi**4/5 + b**2*np.pi**8/50 + v2 = a**2/8 + v3 = 0 + v12 = 0 + # v13: mistake in the book, see other derivations e.g. in 10.1002/nme.4856 + v13 = b**2*np.pi**8*8/225 + v23 = 0 + + s_first = np.array([v1, v2, v3])/var + s_second = np.array([ + [0., 0., v13], + [v12, 0., v23], + [v13, v23, 0.] + ])/var + s_total = s_first + s_second.sum(axis=1) + + return s_first, s_total + + +def f_ishigami_vec(x): + """Output of shape (2, n).""" + res = f_ishigami(x) + return res, res + + +class TestSobolIndices: + + dists = [ + stats.uniform(loc=-np.pi, scale=2*np.pi) # type: ignore[attr-defined] + ] * 3 + + def test_sample_AB(self): + # (d, n) + A = np.array( + [[1, 4, 7, 10], + [2, 5, 8, 11], + [3, 6, 9, 12]] + ) + B = A + 100 + # (d, d, n) + ref = np.array( + [[[101, 104, 107, 110], + [2, 5, 8, 11], + [3, 6, 9, 12]], + [[1, 4, 7, 10], + [102, 105, 108, 111], + [3, 6, 9, 12]], + [[1, 4, 7, 10], + [2, 5, 8, 11], + [103, 106, 109, 112]]] + ) + AB = sample_AB(A=A, B=B) + assert_allclose(AB, ref) + + @pytest.mark.xslow + @pytest.mark.xfail_on_32bit("Can't create large array for test") + @pytest.mark.parametrize( + 'func', + [f_ishigami, pytest.param(f_ishigami_vec, marks=pytest.mark.slow)], + ids=['scalar', 'vector'] + ) + def test_ishigami(self, ishigami_ref_indices, func): + rng = np.random.default_rng(28631265345463262246170309650372465332) + res = sobol_indices( + func=func, n=4096, + dists=self.dists, + rng=rng + ) + + if func.__name__ == 'f_ishigami_vec': + ishigami_ref_indices = [ + [ishigami_ref_indices[0], ishigami_ref_indices[0]], + [ishigami_ref_indices[1], ishigami_ref_indices[1]] + ] + + assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2) + assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2) + + assert res._bootstrap_result is None + bootstrap_res = res.bootstrap(n_resamples=99) + assert isinstance(bootstrap_res, BootstrapSobolResult) + assert isinstance(res._bootstrap_result, BootstrapResult) + + assert res._bootstrap_result.confidence_interval.low.shape[0] == 2 + assert res._bootstrap_result.confidence_interval.low[1].shape \ + == res.first_order.shape + + assert bootstrap_res.first_order.confidence_interval.low.shape \ + == res.first_order.shape + assert bootstrap_res.total_order.confidence_interval.low.shape \ + == res.total_order.shape + + assert_array_less( + bootstrap_res.first_order.confidence_interval.low, res.first_order + ) + assert_array_less( + res.first_order, bootstrap_res.first_order.confidence_interval.high + ) + assert_array_less( + bootstrap_res.total_order.confidence_interval.low, res.total_order + ) + assert_array_less( + res.total_order, bootstrap_res.total_order.confidence_interval.high + ) + + # call again to use previous results and change a param + assert isinstance( + res.bootstrap(confidence_level=0.9, n_resamples=99), + BootstrapSobolResult + ) + assert isinstance(res._bootstrap_result, BootstrapResult) + + def test_func_dict(self, ishigami_ref_indices): + rng = np.random.default_rng(28631265345463262246170309650372465332) + n = 4096 + dists = [ + stats.uniform(loc=-np.pi, scale=2*np.pi), + stats.uniform(loc=-np.pi, scale=2*np.pi), + stats.uniform(loc=-np.pi, scale=2*np.pi) + ] + + A, B = sample_A_B(n=n, dists=dists, rng=rng) + AB = sample_AB(A=A, B=B) + + func = { + 'f_A': f_ishigami(A).reshape(1, -1), + 'f_B': f_ishigami(B).reshape(1, -1), + 'f_AB': f_ishigami(AB).reshape((3, 1, -1)) + } + + # preserve use of old random_state during SPEC 7 transition + res = sobol_indices( + func=func, n=n, + dists=dists, + rng=rng + ) + assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2) + + res = sobol_indices( + func=func, n=n, + rng=rng + ) + assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2) + # Ideally should be exactly equal but since f_ishigami + # uses floating point operations, so exact equality + # might not be possible (due to flakiness in computation). + # So, assert_allclose is used with default parameters + # Regression test for https://github.com/scipy/scipy/issues/21383 + assert_allclose(f_ishigami(A).reshape(1, -1), func['f_A']) + assert_allclose(f_ishigami(B).reshape(1, -1), func['f_B']) + assert_allclose(f_ishigami(AB).reshape((3, 1, -1)), func['f_AB']) + + def test_method(self, ishigami_ref_indices): + def jansen_sobol(f_A, f_B, f_AB): + """Jansen for S and Sobol' for St. + + From Saltelli2010, table 2 formulations (c) and (e).""" + var = np.var([f_A, f_B], axis=(0, -1)) + + s = (var - 0.5*np.mean((f_B - f_AB)**2, axis=-1)) / var + st = np.mean(f_A*(f_A - f_AB), axis=-1) / var + + return s.T, st.T + + rng = np.random.default_rng(28631265345463262246170309650372465332) + res = sobol_indices( + func=f_ishigami, n=4096, + dists=self.dists, + method=jansen_sobol, + rng=rng + ) + + assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2) + assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2) + + def jansen_sobol_typed( + f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray + ) -> tuple[np.ndarray, np.ndarray]: + return jansen_sobol(f_A, f_B, f_AB) + + _ = sobol_indices( + func=f_ishigami, n=8, + dists=self.dists, + method=jansen_sobol_typed, + rng=rng + ) + + def test_normalization(self, ishigami_ref_indices): + rng = np.random.default_rng(28631265345463262246170309650372465332) + res = sobol_indices( + func=lambda x: f_ishigami(x) + 1000, n=4096, + dists=self.dists, + rng=rng + ) + + assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2) + assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2) + + def test_constant_function(self, ishigami_ref_indices): + + def f_ishigami_vec_const(x): + """Output of shape (3, n).""" + res = f_ishigami(x) + return res, res * 0 + 10, res + + rng = np.random.default_rng(28631265345463262246170309650372465332) + res = sobol_indices( + func=f_ishigami_vec_const, n=4096, + dists=self.dists, + rng=rng + ) + + ishigami_vec_indices = [ + [ishigami_ref_indices[0], [0, 0, 0], ishigami_ref_indices[0]], + [ishigami_ref_indices[1], [0, 0, 0], ishigami_ref_indices[1]] + ] + + assert_allclose(res.first_order, ishigami_vec_indices[0], atol=1e-2) + assert_allclose(res.total_order, ishigami_vec_indices[1], atol=1e-2) + + @pytest.mark.xfail_on_32bit("Can't create large array for test") + def test_more_converged(self, ishigami_ref_indices): + rng = np.random.default_rng(28631265345463262246170309650372465332) + res = sobol_indices( + func=f_ishigami, n=2**19, # 524288 + dists=self.dists, + rng=rng + ) + + assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-4) + assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-4) + + def test_raises(self): + + message = r"Each distribution in `dists` must have method `ppf`" + with pytest.raises(ValueError, match=message): + sobol_indices(n=0, func=f_ishigami, dists="uniform") + + with pytest.raises(ValueError, match=message): + sobol_indices(n=0, func=f_ishigami, dists=[lambda x: x]) + + message = r"The balance properties of Sobol'" + with pytest.raises(ValueError, match=message): + sobol_indices(n=7, func=f_ishigami, dists=[stats.uniform()]) + + with pytest.raises(ValueError, match=message): + sobol_indices(n=4.1, func=f_ishigami, dists=[stats.uniform()]) + + message = r"'toto' is not a valid 'method'" + with pytest.raises(ValueError, match=message): + sobol_indices(n=0, func=f_ishigami, method='toto') + + message = r"must have the following signature" + with pytest.raises(ValueError, match=message): + sobol_indices(n=0, func=f_ishigami, method=lambda x: x) + + message = r"'dists' must be defined when 'func' is a callable" + with pytest.raises(ValueError, match=message): + sobol_indices(n=0, func=f_ishigami) + + def func_wrong_shape_output(x): + return x.reshape(-1, 1) + + message = r"'func' output should have a shape" + with pytest.raises(ValueError, match=message): + sobol_indices( + n=2, func=func_wrong_shape_output, dists=[stats.uniform()] + ) + + message = r"When 'func' is a dictionary" + with pytest.raises(ValueError, match=message): + sobol_indices( + n=2, func={'f_A': [], 'f_AB': []}, dists=[stats.uniform()] + ) + + with pytest.raises(ValueError, match=message): + # f_B malformed + sobol_indices( + n=2, + func={'f_A': [1, 2], 'f_B': [3], 'f_AB': [5, 6, 7, 8]}, + ) + + with pytest.raises(ValueError, match=message): + # f_AB malformed + sobol_indices( + n=2, + func={'f_A': [1, 2], 'f_B': [3, 4], 'f_AB': [5, 6, 7]}, + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..9416a69d30ce8f8b7ba628beb2b7a9194fd24101 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py @@ -0,0 +1,9847 @@ +""" Test functions for stats module + + WRITTEN BY LOUIS LUANGKESORN FOR THE STATS MODULE + BASED ON WILKINSON'S STATISTICS QUIZ + https://www.stanford.edu/~clint/bench/wilk.txt + + Additional tests by a host of SciPy developers. +""" +import os +import re +import warnings +from collections import namedtuple +from itertools import product +import hypothesis.extra.numpy as npst +import hypothesis +import contextlib + +from numpy.testing import (assert_, assert_equal, + assert_almost_equal, assert_array_almost_equal, + assert_array_equal, assert_approx_equal, + assert_allclose, suppress_warnings, + assert_array_less) +import pytest +from pytest import raises as assert_raises +import numpy.ma.testutils as mat +from numpy import array, arange, float32, power +import numpy as np + +import scipy.stats as stats +import scipy.stats.mstats as mstats +import scipy.stats._mstats_basic as mstats_basic +from scipy.stats._ksstats import kolmogn +from scipy.special._testutils import FuncData +from scipy.special import binom +from scipy import optimize +from .common_tests import check_named_results +from scipy.stats._axis_nan_policy import (_broadcast_concatenate, SmallSampleWarning, + too_small_nd_omit, too_small_nd_not_omit, + too_small_1d_omit, too_small_1d_not_omit) +from scipy.stats._stats_py import (_permutation_distribution_t, _chk_asarray, _moment, + LinregressResult, _xp_mean, _xp_var, _SimpleChi2) +from scipy._lib._util import AxisError +from scipy.conftest import array_api_compatible, skip_xp_invalid_arg +from scipy._lib._array_api import (array_namespace, xp_copy, is_numpy, + is_torch, xp_size, SCIPY_ARRAY_API) +from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal + +skip_xp_backends = pytest.mark.skip_xp_backends + + +""" Numbers in docstrings beginning with 'W' refer to the section numbers + and headings found in the STATISTICS QUIZ of Leland Wilkinson. These are + considered to be essential functionality. True testing and + evaluation of a statistics package requires use of the + NIST Statistical test data. See McCoullough(1999) Assessing The Reliability + of Statistical Software for a test methodology and its + implementation in testing SAS, SPSS, and S-Plus +""" + +# Datasets +# These data sets are from the nasty.dat sets used by Wilkinson +# For completeness, I should write the relevant tests and count them as failures +# Somewhat acceptable, since this is still beta software. It would count as a +# good target for 1.0 status +X = array([1,2,3,4,5,6,7,8,9], float) +ZERO = array([0,0,0,0,0,0,0,0,0], float) +BIG = array([99999991,99999992,99999993,99999994,99999995,99999996,99999997, + 99999998,99999999], float) +LITTLE = array([0.99999991,0.99999992,0.99999993,0.99999994,0.99999995,0.99999996, + 0.99999997,0.99999998,0.99999999], float) +HUGE = array([1e+12,2e+12,3e+12,4e+12,5e+12,6e+12,7e+12,8e+12,9e+12], float) +TINY = array([1e-12,2e-12,3e-12,4e-12,5e-12,6e-12,7e-12,8e-12,9e-12], float) +ROUND = array([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5], float) + + +@array_api_compatible +@skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.") +@skip_xp_backends('array_api_strict', + reason=("`array_api_strict.where` `fillvalue` doesn't " + "accept Python floats. See data-apis/array-api#807.") +) +@pytest.mark.usefixtures("skip_xp_backends") +class TestTrimmedStats: + # TODO: write these tests to handle missing values properly + dprec = np.finfo(np.float64).precision + + def test_tmean(self, xp): + x = xp.asarray(X.tolist()) # use default dtype of xp + + y = stats.tmean(x, (2, 8), (True, True)) + xp_assert_close(y, xp.asarray(5.0)) + + y1 = stats.tmean(x, limits=(2, 8), inclusive=(False, False)) + y2 = stats.tmean(x, limits=None) + xp_assert_close(y1, y2) + + x_2d = xp.reshape(xp.arange(63.), (9, 7)) + y = stats.tmean(x_2d, axis=None) + xp_assert_close(y, xp.mean(x_2d)) + + y = stats.tmean(x_2d, axis=0) + xp_assert_close(y, xp.mean(x_2d, axis=0)) + + y = stats.tmean(x_2d, axis=1) + xp_assert_close(y, xp.mean(x_2d, axis=1)) + + y = stats.tmean(x_2d, limits=(2, 61), axis=None) + xp_assert_close(y, xp.asarray(31.5)) + + y = stats.tmean(x_2d, limits=(2, 21), axis=0) + y_true = [14, 11.5, 9, 10, 11, 12, 13] + xp_assert_close(y, xp.asarray(y_true)) + + y = stats.tmean(x_2d, limits=(2, 21), inclusive=(True, False), axis=0) + y_true = [10.5, 11.5, 9, 10, 11, 12, 13] + xp_assert_close(y, xp.asarray(y_true)) + + x_2d_with_nan = xp_copy(x_2d) + x_2d_with_nan[-1, -3:] = xp.nan + y = stats.tmean(x_2d_with_nan, limits=(1, 13), axis=0) + y_true = [7, 4.5, 5.5, 6.5, xp.nan, xp.nan, xp.nan] + xp_assert_close(y, xp.asarray(y_true)) + + y = stats.tmean(x_2d, limits=(2, 21), axis=1) + y_true = [4, 10, 17, 21, xp.nan, xp.nan, xp.nan, xp.nan, xp.nan] + xp_assert_close(y, xp.asarray(y_true)) + + y = stats.tmean(x_2d, limits=(2, 21), + inclusive=(False, True), axis=1) + y_true = [4.5, 10, 17, 21, xp.nan, xp.nan, xp.nan, xp.nan, xp.nan] + xp_assert_close(y, xp.asarray(y_true)) + + @skip_xp_backends('cupy', + reason="cupy/cupy#8391") + def test_tvar(self, xp): + x = xp.asarray(X.tolist()) # use default dtype of xp + xp_test = array_namespace(x) # need array-api-compat var for `correction` + + y = stats.tvar(x, limits=(2, 8), inclusive=(True, True)) + xp_assert_close(y, xp.asarray(4.6666666666666661)) + + y = stats.tvar(x, limits=None) + xp_assert_close(y, xp_test.var(x, correction=1)) + + x_2d = xp.reshape(xp.arange(63.), (9, 7)) + y = stats.tvar(x_2d, axis=None) + xp_assert_close(y, xp_test.var(x_2d, correction=1)) + + y = stats.tvar(x_2d, axis=0) + xp_assert_close(y, xp.full((7,), 367.5)) + + y = stats.tvar(x_2d, axis=1) + xp_assert_close(y, xp.full((9,), 4.66666667)) + + # Limiting some values along one axis + y = stats.tvar(x_2d, limits=(1, 5), axis=1, inclusive=(True, True)) + xp_assert_close(y[0], xp.asarray(2.5)) + + # Limiting all values along one axis + y = stats.tvar(x_2d, limits=(0, 6), axis=1, inclusive=(True, True)) + xp_assert_close(y[0], xp.asarray(4.666666666666667)) + xp_assert_equal(y[1], xp.asarray(xp.nan)) + + def test_tstd(self, xp): + x = xp.asarray(X.tolist()) # use default dtype of xp + xp_test = array_namespace(x) # need array-api-compat std for `correction` + + y = stats.tstd(x, (2, 8), (True, True)) + xp_assert_close(y, xp.asarray(2.1602468994692865)) + + y = stats.tstd(x, limits=None) + xp_assert_close(y, xp_test.std(x, correction=1)) + + def test_tmin(self, xp): + x = xp.arange(10) + xp_assert_equal(stats.tmin(x), xp.asarray(0)) + xp_assert_equal(stats.tmin(x, lowerlimit=0), xp.asarray(0)) + xp_assert_equal(stats.tmin(x, lowerlimit=0, inclusive=False), xp.asarray(1)) + + x = xp.reshape(x, (5, 2)) + xp_assert_equal(stats.tmin(x, lowerlimit=0, inclusive=False), + xp.asarray([2, 1])) + xp_assert_equal(stats.tmin(x, axis=1), xp.asarray([0, 2, 4, 6, 8])) + xp_assert_equal(stats.tmin(x, axis=None), xp.asarray(0)) + + x = xp.arange(10.) + x[9] = xp.nan + xp_assert_equal(stats.tmin(x), xp.asarray(xp.nan)) + + # check that if a full slice is masked, the output returns a + # nan instead of a garbage value. + x = xp.arange(16).reshape(4, 4) + res = stats.tmin(x, lowerlimit=4, axis=1) + xp_assert_equal(res, xp.asarray([np.nan, 4, 8, 12])) + + @skip_xp_backends(np_only=True, + reason="Only NumPy arrays support scalar input/`nan_policy`.") + def test_tmin_scalar_and_nanpolicy(self, xp): + assert_equal(stats.tmin(4), 4) + + x = np.arange(10.) + x[9] = np.nan + with suppress_warnings() as sup: + sup.record(RuntimeWarning, "invalid value*") + assert_equal(stats.tmin(x, nan_policy='omit'), 0.) + msg = "The input contains nan values" + with assert_raises(ValueError, match=msg): + stats.tmin(x, nan_policy='raise') + msg = "nan_policy must be one of..." + with assert_raises(ValueError, match=msg): + stats.tmin(x, nan_policy='foobar') + + def test_tmax(self, xp): + x = xp.arange(10) + xp_assert_equal(stats.tmax(x), xp.asarray(9)) + xp_assert_equal(stats.tmax(x, upperlimit=9), xp.asarray(9)) + xp_assert_equal(stats.tmax(x, upperlimit=9, inclusive=False), xp.asarray(8)) + + x = xp.reshape(x, (5, 2)) + xp_assert_equal(stats.tmax(x, upperlimit=9, inclusive=False), + xp.asarray([8, 7])) + xp_assert_equal(stats.tmax(x, axis=1), xp.asarray([1, 3, 5, 7, 9])) + xp_assert_equal(stats.tmax(x, axis=None), xp.asarray(9)) + + x = xp.arange(10.) + x[9] = xp.nan + xp_assert_equal(stats.tmax(x), xp.asarray(xp.nan)) + + # check that if a full slice is masked, the output returns a + # nan instead of a garbage value. + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "All-NaN slice encountered") + x = xp.reshape(xp.arange(16), (4, 4)) + res = stats.tmax(x, upperlimit=11, axis=1) + xp_assert_equal(res, xp.asarray([3, 7, 11, np.nan])) + + @skip_xp_backends(np_only=True, + reason="Only NumPy arrays support scalar input/`nan_policy`.") + def test_tax_scalar_and_nanpolicy(self, xp): + assert_equal(stats.tmax(4), 4) + + x = np.arange(10.) + x[6] = np.nan + with suppress_warnings() as sup: + sup.record(RuntimeWarning, "invalid value*") + assert_equal(stats.tmax(x, nan_policy='omit'), 9.) + msg = "The input contains nan values" + with assert_raises(ValueError, match=msg): + stats.tmax(x, nan_policy='raise') + msg = "nan_policy must be one of..." + with assert_raises(ValueError, match=msg): + stats.tmax(x, nan_policy='foobar') + + def test_tsem(self, xp): + x = xp.asarray(X.tolist()) # use default dtype of xp + xp_test = array_namespace(x) # need array-api-compat std for `correction` + + y = stats.tsem(x, limits=(3, 8), inclusive=(False, True)) + y_ref = xp.asarray([4., 5., 6., 7., 8.]) + xp_assert_close(y, xp_test.std(y_ref, correction=1) / xp_size(y_ref)**0.5) + xp_assert_close(stats.tsem(x, limits=[-1, 10]), stats.tsem(x, limits=None)) + + +class TestPearsonrWilkinson: + """ W.II.D. Compute a correlation matrix on all the variables. + + All the correlations, except for ZERO and MISS, should be exactly 1. + ZERO and MISS should have undefined or missing correlations with the + other variables. The same should go for SPEARMAN correlations, if + your program has them. + """ + + def test_pXX(self): + y = stats.pearsonr(X,X) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pXBIG(self): + y = stats.pearsonr(X,BIG) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pXLITTLE(self): + y = stats.pearsonr(X,LITTLE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pXHUGE(self): + y = stats.pearsonr(X,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pXTINY(self): + y = stats.pearsonr(X,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pXROUND(self): + y = stats.pearsonr(X,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pBIGBIG(self): + y = stats.pearsonr(BIG,BIG) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pBIGLITTLE(self): + y = stats.pearsonr(BIG,LITTLE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pBIGHUGE(self): + y = stats.pearsonr(BIG,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pBIGTINY(self): + y = stats.pearsonr(BIG,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pBIGROUND(self): + y = stats.pearsonr(BIG,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pLITTLELITTLE(self): + y = stats.pearsonr(LITTLE,LITTLE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pLITTLEHUGE(self): + y = stats.pearsonr(LITTLE,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pLITTLETINY(self): + y = stats.pearsonr(LITTLE,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pLITTLEROUND(self): + y = stats.pearsonr(LITTLE,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pHUGEHUGE(self): + y = stats.pearsonr(HUGE,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pHUGETINY(self): + y = stats.pearsonr(HUGE,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pHUGEROUND(self): + y = stats.pearsonr(HUGE,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pTINYTINY(self): + y = stats.pearsonr(TINY,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pTINYROUND(self): + y = stats.pearsonr(TINY,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_pROUNDROUND(self): + y = stats.pearsonr(ROUND,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +@skip_xp_backends(cpu_only=True) +class TestPearsonr: + @skip_xp_backends(np_only=True) + def test_pearsonr_result_attributes(self): + res = stats.pearsonr(X, X) + attributes = ('correlation', 'pvalue') + check_named_results(res, attributes) + assert_equal(res.correlation, res.statistic) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + def test_r_almost_exactly_pos1(self, xp): + a = xp.arange(3.0) + r, prob = stats.pearsonr(a, a) + + xp_assert_close(r, xp.asarray(1.0), atol=1e-15) + # With n = len(a) = 3, the error in prob grows like the + # square root of the error in r. + xp_assert_close(prob, xp.asarray(0.0), atol=np.sqrt(2*np.spacing(1.0))) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + def test_r_almost_exactly_neg1(self, xp): + a = xp.arange(3.0) + r, prob = stats.pearsonr(a, -a) + + xp_assert_close(r, xp.asarray(-1.0), atol=1e-15) + # With n = len(a) = 3, the error in prob grows like the + # square root of the error in r. + xp_assert_close(prob, xp.asarray(0.0), atol=np.sqrt(2*np.spacing(1.0))) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + def test_basic(self, xp): + # A basic test, with a correlation coefficient + # that is not 1 or -1. + a = xp.asarray([-1, 0, 1]) + b = xp.asarray([0, 0, 3]) + r, prob = stats.pearsonr(a, b) + xp_assert_close(r, xp.asarray(3**0.5/2)) + xp_assert_close(prob, xp.asarray(1/3)) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment', + ) + def test_constant_input(self, xp): + # Zero variance input + # See https://github.com/scipy/scipy/issues/3728 + msg = "An input array is constant" + with pytest.warns(stats.ConstantInputWarning, match=msg): + x = xp.asarray([0.667, 0.667, 0.667]) + y = xp.asarray([0.123, 0.456, 0.789]) + r, p = stats.pearsonr(x, y) + xp_assert_close(r, xp.asarray(xp.nan)) + xp_assert_close(p, xp.asarray(xp.nan)) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment', + ) + @pytest.mark.parametrize('dtype', ['float32', 'float64']) + def test_near_constant_input(self, xp, dtype): + npdtype = getattr(np, dtype) + dtype = getattr(xp, dtype) + # Near constant input (but not constant): + x = xp.asarray([2, 2, 2 + np.spacing(2, dtype=npdtype)], dtype=dtype) + y = xp.asarray([3, 3, 3 + 6*np.spacing(3, dtype=npdtype)], dtype=dtype) + msg = "An input array is nearly constant; the computed" + with pytest.warns(stats.NearConstantInputWarning, match=msg): + # r and p are garbage, so don't bother checking them in this case. + # (The exact value of r would be 1.) + stats.pearsonr(x, y) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment', + ) + def test_very_small_input_values(self, xp): + # Very small values in an input. A naive implementation will + # suffer from underflow. + # See https://github.com/scipy/scipy/issues/9353 + x = xp.asarray([0.004434375, 0.004756007, 0.003911996, 0.0038005, 0.003409971], + dtype=xp.float64) + y = xp.asarray([2.48e-188, 7.41e-181, 4.09e-208, 2.08e-223, 2.66e-245], + dtype=xp.float64) + r, p = stats.pearsonr(x, y) + + # The expected values were computed using mpmath with 80 digits + # of precision. + xp_assert_close(r, xp.asarray(0.7272930540750450, dtype=xp.float64)) + xp_assert_close(p, xp.asarray(0.1637805429533202, dtype=xp.float64)) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment', + ) + def test_very_large_input_values(self, xp): + # Very large values in an input. A naive implementation will + # suffer from overflow. + # See https://github.com/scipy/scipy/issues/8980 + x = 1e90*xp.asarray([0, 0, 0, 1, 1, 1, 1], dtype=xp.float64) + y = 1e90*xp.arange(7, dtype=xp.float64) + + r, p = stats.pearsonr(x, y) + + # The expected values were computed using mpmath with 80 digits + # of precision. + xp_assert_close(r, xp.asarray(0.8660254037844386, dtype=xp.float64)) + xp_assert_close(p, xp.asarray(0.011724811003954638, dtype=xp.float64)) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + def test_extremely_large_input_values(self, xp): + # Extremely large values in x and y. These values would cause the + # product sigma_x * sigma_y to overflow if the two factors were + # computed independently. + x = xp.asarray([2.3e200, 4.5e200, 6.7e200, 8e200], dtype=xp.float64) + y = xp.asarray([1.2e199, 5.5e200, 3.3e201, 1.0e200], dtype=xp.float64) + r, p = stats.pearsonr(x, y) + + # The expected values were computed using mpmath with 80 digits + # of precision. + xp_assert_close(r, xp.asarray(0.351312332103289, dtype=xp.float64)) + xp_assert_close(p, xp.asarray(0.648687667896711, dtype=xp.float64)) + + @skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.") + def test_length_two_pos1(self, xp): + # Inputs with length 2. + # See https://github.com/scipy/scipy/issues/7730 + x = xp.asarray([1., 2.]) + y = xp.asarray([3., 5.]) + res = stats.pearsonr(x, y) + r, p = res + one = xp.asarray(1.) + xp_assert_equal(r, one) + xp_assert_equal(p, one) + low, high = res.confidence_interval() + xp_assert_equal(low, -one) + xp_assert_equal(high, one) + + @skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.") + def test_length_two_neg1(self, xp): + # Inputs with length 2. + # See https://github.com/scipy/scipy/issues/7730 + x = xp.asarray([2., 1.]) + y = xp.asarray([3., 5.]) + res = stats.pearsonr(x, y) + r, p = res + one = xp.asarray(1.) + xp_assert_equal(r, -one) + xp_assert_equal(p, one) + low, high = res.confidence_interval() + xp_assert_equal(low, -one) + xp_assert_equal(high, one) + + @skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.") + def test_length_two_constant_input(self, xp): + # Zero variance input + # See https://github.com/scipy/scipy/issues/3728 + # and https://github.com/scipy/scipy/issues/7730 + msg = "An input array is constant" + with pytest.warns(stats.ConstantInputWarning, match=msg): + x = xp.asarray([0.667, 0.667]) + y = xp.asarray([0.123, 0.456]) + r, p = stats.pearsonr(x, y) + xp_assert_close(r, xp.asarray(xp.nan)) + xp_assert_close(p, xp.asarray(xp.nan)) + + # Expected values computed with R 3.6.2 cor.test, e.g. + # options(digits=16) + # x <- c(1, 2, 3, 4) + # y <- c(0, 1, 0.5, 1) + # cor.test(x, y, method = "pearson", alternative = "g") + # correlation coefficient and p-value for alternative='two-sided' + # calculated with mpmath agree to 16 digits. + @pytest.mark.skip_xp_backends(np_only=True) + @pytest.mark.parametrize('alternative, pval, rlow, rhigh, sign', + [('two-sided', 0.325800137536, -0.814938968841, 0.99230697523, 1), + ('less', 0.8370999312316, -1, 0.985600937290653, 1), + ('greater', 0.1629000687684, -0.6785654158217636, 1, 1), + ('two-sided', 0.325800137536, -0.992306975236, 0.81493896884, -1), + ('less', 0.1629000687684, -1.0, 0.6785654158217636, -1), + ('greater', 0.8370999312316, -0.985600937290653, 1.0, -1)]) + def test_basic_example(self, alternative, pval, rlow, rhigh, sign): + x = [1, 2, 3, 4] + y = np.array([0, 1, 0.5, 1]) * sign + result = stats.pearsonr(x, y, alternative=alternative) + assert_allclose(result.statistic, 0.6741998624632421*sign, rtol=1e-12) + assert_allclose(result.pvalue, pval, rtol=1e-6) + ci = result.confidence_interval() + assert_allclose(ci, (rlow, rhigh), rtol=1e-6) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + def test_negative_correlation_pvalue_gh17795(self, xp): + x = xp.arange(10.) + y = -x + test_greater = stats.pearsonr(x, y, alternative='greater') + test_less = stats.pearsonr(x, y, alternative='less') + xp_assert_close(test_greater.pvalue, xp.asarray(1.)) + xp_assert_close(test_less.pvalue, xp.asarray(0.), atol=1e-20) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + def test_length3_r_exactly_negative_one(self, xp): + x = xp.asarray([1., 2., 3.]) + y = xp.asarray([5., -4., -13.]) + res = stats.pearsonr(x, y) + + # The expected r and p are exact. + r, p = res + one = xp.asarray(1.0) + xp_assert_close(r, -one) + xp_assert_close(p, 0*one, atol=1e-7) + low, high = res.confidence_interval() + xp_assert_equal(low, -one) + xp_assert_equal(high, one) + + @pytest.mark.skip_xp_backends(np_only=True) + def test_input_validation(self): + x = [1, 2, 3] + y = [4, 5] + message = '`x` and `y` must have the same length along `axis`.' + with pytest.raises(ValueError, match=message): + stats.pearsonr(x, y) + + x = [1] + y = [2] + message = '`x` and `y` must have length at least 2.' + with pytest.raises(ValueError, match=message): + stats.pearsonr(x, y) + + x = [-1j, -2j, -3.0j] + y = [-1j, -2j, -3.0j] + message = 'This function does not support complex data' + with pytest.raises(ValueError, match=message): + stats.pearsonr(x, y) + + message = "`method` must be an instance of..." + with pytest.raises(ValueError, match=message): + stats.pearsonr([1, 2], [3, 4], method="asymptotic") + + res = stats.pearsonr([1, 2], [3, 4]) + with pytest.raises(ValueError, match=message): + res.confidence_interval(method="exact") + + @pytest.mark.fail_slow(10) + @pytest.mark.skip_xp_backends(np_only=True) + @pytest.mark.xfail_on_32bit("Monte Carlo method needs > a few kB of memory") + @pytest.mark.parametrize('alternative', ('less', 'greater', 'two-sided')) + @pytest.mark.parametrize('method_name', + ('permutation', 'monte_carlo', 'monte_carlo2')) + def test_resampling_pvalue(self, method_name, alternative): + rng = np.random.default_rng(24623935790378923) + size = (2, 100) if method_name == 'permutation' else (2, 1000) + x = rng.normal(size=size) + y = rng.normal(size=size) + methods = {'permutation': stats.PermutationMethod(rng=rng), + 'monte_carlo': stats.MonteCarloMethod(rvs=(rng.normal,)*2), + 'monte_carlo2': stats.MonteCarloMethod(rng=1294)} + method = methods[method_name] + res = stats.pearsonr(x, y, alternative=alternative, method=method, axis=-1) + ref = stats.pearsonr(x, y, alternative=alternative, axis=-1) + assert_allclose(res.statistic, ref.statistic, rtol=1e-15) + assert_allclose(res.pvalue, ref.pvalue, rtol=1e-2, atol=1e-3) + + if method_name == 'monte_carlo2': + method = stats.MonteCarloMethod(rng=1294) + res2 = stats.pearsonr(x, y, alternative=alternative, method=method, axis=-1) + assert_equal(res2.statistic, res.statistic) + assert_equal(res2.pvalue, res.pvalue) + + @pytest.mark.skip_xp_backends(np_only=True) + @pytest.mark.parametrize('alternative', ('less', 'greater', 'two-sided')) + def test_bootstrap_ci(self, alternative): + rng = np.random.default_rng(2462935790378923) + x = rng.normal(size=(2, 100)) + y = rng.normal(size=(2, 100)) + res = stats.pearsonr(x, y, alternative=alternative, axis=-1) + + # preserve use of old random_state during SPEC 7 transition + rng = np.random.default_rng(724358723498249852) + method = stats.BootstrapMethod(random_state=rng) + res_ci = res.confidence_interval(method=method) + ref_ci = res.confidence_interval() + assert_allclose(res_ci, ref_ci, atol=1.5e-2) + + # `rng` is the new argument name` + rng = np.random.default_rng(724358723498249852) + method = stats.BootstrapMethod(rng=rng) + res_ci2 = res.confidence_interval(method=method) + assert_allclose(res_ci2, res_ci) + + @pytest.mark.skip_xp_backends(np_only=True) + @pytest.mark.parametrize('axis', [0, 1]) + def test_axis01(self, axis, xp): + rng = np.random.default_rng(38572345825) + shape = (9, 10) + x, y = rng.normal(size=(2,) + shape) + res = stats.pearsonr(x, y, axis=axis) + ci = res.confidence_interval() + if axis == 0: + x, y = x.T, y.T + for i in range(x.shape[0]): + res_i = stats.pearsonr(x[i], y[i]) + ci_i = res_i.confidence_interval() + assert_allclose(res.statistic[i], res_i.statistic) + assert_allclose(res.pvalue[i], res_i.pvalue) + assert_allclose(ci.low[i], ci_i.low) + assert_allclose(ci.high[i], ci_i.high) + + @pytest.mark.skip_xp_backends(np_only=True) + def test_axis_None(self, xp): + rng = np.random.default_rng(38572345825) + shape = (9, 10) + x, y = rng.normal(size=(2,) + shape) + res = stats.pearsonr(x, y, axis=None) + ci = res.confidence_interval() + ref = stats.pearsonr(x.ravel(), y.ravel()) + ci_ref = ref.confidence_interval() + assert_allclose(res.statistic, ref.statistic) + assert_allclose(res.pvalue, ref.pvalue) + assert_allclose(ci, ci_ref) + + def test_nd_input_validation(self, xp): + x = y = xp.ones((2, 5)) + message = '`axis` must be an integer.' + with pytest.raises(ValueError, match=message): + stats.pearsonr(x, y, axis=1.5) + + message = '`x` and `y` must have the same length along `axis`' + with pytest.raises(ValueError, match=message): + stats.pearsonr(x, xp.ones((2, 1)), axis=1) + + message = '`x` and `y` must have length at least 2.' + with pytest.raises(ValueError, match=message): + stats.pearsonr(xp.ones((2, 1)), xp.ones((2, 1)), axis=1) + + message = '`x` and `y` must be broadcastable.' + with pytest.raises(ValueError, match=message): + stats.pearsonr(x, xp.ones((3, 5)), axis=1) + + message = '`method` must be `None` if arguments are not NumPy arrays.' + if not is_numpy(xp): + x = xp.arange(10) + with pytest.raises(ValueError, match=message): + stats.pearsonr(x, x, method=stats.PermutationMethod()) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + def test_nd_special_cases(self, xp): + rng = np.random.default_rng(34989235492245) + x0 = xp.asarray(rng.random((3, 5))) + y0 = xp.asarray(rng.random((3, 5))) + + message = 'An input array is constant' + with pytest.warns(stats.ConstantInputWarning, match=message): + x = xp_copy(x0) + x[0, ...] = 1 + res = stats.pearsonr(x, y0, axis=1) + ci = res.confidence_interval() + nan = xp.asarray(xp.nan, dtype=xp.float64) + xp_assert_equal(res.statistic[0], nan) + xp_assert_equal(res.pvalue[0], nan) + xp_assert_equal(ci.low[0], nan) + xp_assert_equal(ci.high[0], nan) + assert not xp.any(xp.isnan(res.statistic[1:])) + assert not xp.any(xp.isnan(res.pvalue[1:])) + assert not xp.any(xp.isnan(ci.low[1:])) + assert not xp.any(xp.isnan(ci.high[1:])) + + message = 'An input array is nearly constant' + with pytest.warns(stats.NearConstantInputWarning, match=message): + x[0, 0] = 1 + 1e-15 + stats.pearsonr(x, y0, axis=1) + + # length 2 along axis + x = xp.asarray([[1, 2], [1, 2], [2, 1], [2, 1.]]) + y = xp.asarray([[1, 2], [2, 1], [1, 2], [2, 1.]]) + ones = xp.ones(4) + res = stats.pearsonr(x, y, axis=-1) + ci = res.confidence_interval() + xp_assert_close(res.statistic, xp.asarray([1, -1, -1, 1.])) + xp_assert_close(res.pvalue, ones) + xp_assert_close(ci.low, -ones) + xp_assert_close(ci.high, ones) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + @pytest.mark.parametrize('axis', [0, 1, None]) + @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided']) + def test_array_api(self, xp, axis, alternative): + x, y = rng.normal(size=(2, 10, 11)) + res = stats.pearsonr(xp.asarray(x), xp.asarray(y), + axis=axis, alternative=alternative) + ref = stats.pearsonr(x, y, axis=axis, alternative=alternative) + xp_assert_close(res.statistic, xp.asarray(ref.statistic)) + xp_assert_close(res.pvalue, xp.asarray(ref.pvalue)) + + res_ci = res.confidence_interval() + ref_ci = ref.confidence_interval() + xp_assert_close(res_ci.low, xp.asarray(ref_ci.low)) + xp_assert_close(res_ci.high, xp.asarray(ref_ci.high)) + + +class TestFisherExact: + """Some tests to show that fisher_exact() works correctly. + + Note that in SciPy 0.9.0 this was not working well for large numbers due to + inaccuracy of the hypergeom distribution (see #1218). Fixed now. + + Also note that R and SciPy have different argument formats for their + hypergeometric distribution functions. + + R: + > phyper(18999, 99000, 110000, 39000, lower.tail = FALSE) + [1] 1.701815e-09 + """ + + def test_basic(self): + fisher_exact = stats.fisher_exact + + res = fisher_exact([[14500, 20000], [30000, 40000]])[1] + assert_approx_equal(res, 0.01106, significant=4) + res = fisher_exact([[100, 2], [1000, 5]])[1] + assert_approx_equal(res, 0.1301, significant=4) + res = fisher_exact([[2, 7], [8, 2]])[1] + assert_approx_equal(res, 0.0230141, significant=6) + res = fisher_exact([[5, 1], [10, 10]])[1] + assert_approx_equal(res, 0.1973244, significant=6) + res = fisher_exact([[5, 15], [20, 20]])[1] + assert_approx_equal(res, 0.0958044, significant=6) + res = fisher_exact([[5, 16], [20, 25]])[1] + assert_approx_equal(res, 0.1725862, significant=6) + res = fisher_exact([[10, 5], [10, 1]])[1] + assert_approx_equal(res, 0.1973244, significant=6) + res = fisher_exact([[5, 0], [1, 4]])[1] + assert_approx_equal(res, 0.04761904, significant=6) + res = fisher_exact([[0, 1], [3, 2]])[1] + assert_approx_equal(res, 1.0) + res = fisher_exact([[0, 2], [6, 4]])[1] + assert_approx_equal(res, 0.4545454545) + res = fisher_exact([[2, 7], [8, 2]]) + assert_approx_equal(res[1], 0.0230141, significant=6) + assert_approx_equal(res[0], 4.0 / 56) + + def test_precise(self): + # results from R + # + # R defines oddsratio differently (see Notes section of fisher_exact + # docstring), so those will not match. We leave them in anyway, in + # case they will be useful later on. We test only the p-value. + tablist = [ + ([[100, 2], [1000, 5]], (2.505583993422285e-001, 1.300759363430016e-001)), + ([[2, 7], [8, 2]], (8.586235135736206e-002, 2.301413756522114e-002)), + ([[5, 1], [10, 10]], (4.725646047336584e+000, 1.973244147157190e-001)), + ([[5, 15], [20, 20]], (3.394396617440852e-001, 9.580440012477637e-002)), + ([[5, 16], [20, 25]], (3.960558326183334e-001, 1.725864953812994e-001)), + ([[10, 5], [10, 1]], (2.116112781158483e-001, 1.973244147157190e-001)), + ([[10, 5], [10, 0]], (0.000000000000000e+000, 6.126482213438734e-002)), + ([[5, 0], [1, 4]], (np.inf, 4.761904761904762e-002)), + ([[0, 5], [1, 4]], (0.000000000000000e+000, 1.000000000000000e+000)), + ([[5, 1], [0, 4]], (np.inf, 4.761904761904758e-002)), + ([[0, 1], [3, 2]], (0.000000000000000e+000, 1.000000000000000e+000)) + ] + for table, res_r in tablist: + res = stats.fisher_exact(np.asarray(table)) + np.testing.assert_almost_equal(res[1], res_r[1], decimal=11, + verbose=True) + + def test_gh4130(self): + # Previously, a fudge factor used to distinguish between theoretically + # and numerically different probability masses was 1e-4; it has been + # tightened to fix gh4130. Accuracy checked against R fisher.test. + # options(digits=16) + # table <- matrix(c(6, 108, 37, 200), nrow = 2) + # fisher.test(table, alternative = "t") + x = [[6, 37], [108, 200]] + res = stats.fisher_exact(x) + assert_allclose(res[1], 0.005092697748126) + + # case from https://github.com/brentp/fishers_exact_test/issues/27 + # That package has an (absolute?) fudge factor of 1e-6; too big + x = [[22, 0], [0, 102]] + res = stats.fisher_exact(x) + assert_allclose(res[1], 7.175066786244549e-25) + + # case from https://github.com/brentp/fishers_exact_test/issues/1 + x = [[94, 48], [3577, 16988]] + res = stats.fisher_exact(x) + assert_allclose(res[1], 2.069356340993818e-37) + + def test_gh9231(self): + # Previously, fisher_exact was extremely slow for this table + # As reported in gh-9231, the p-value should be very nearly zero + x = [[5829225, 5692693], [5760959, 5760959]] + res = stats.fisher_exact(x) + assert_allclose(res[1], 0, atol=1e-170) + + @pytest.mark.slow + def test_large_numbers(self): + # Test with some large numbers. Regression test for #1401 + pvals = [5.56e-11, 2.666e-11, 1.363e-11] # from R + for pval, num in zip(pvals, [75, 76, 77]): + res = stats.fisher_exact([[17704, 496], [1065, num]])[1] + assert_approx_equal(res, pval, significant=4) + + res = stats.fisher_exact([[18000, 80000], [20000, 90000]])[1] + assert_approx_equal(res, 0.2751, significant=4) + + def test_raises(self): + # test we raise an error for wrong number of dimensions. + message = "The input `table` must have two dimensions." + with pytest.raises(ValueError, match=message): + stats.fisher_exact(np.arange(6)) + + def test_row_or_col_zero(self): + tables = ([[0, 0], [5, 10]], + [[5, 10], [0, 0]], + [[0, 5], [0, 10]], + [[5, 0], [10, 0]]) + for table in tables: + oddsratio, pval = stats.fisher_exact(table) + assert_equal(pval, 1.0) + assert_equal(oddsratio, np.nan) + + def test_less_greater(self): + tables = ( + # Some tables to compare with R: + [[2, 7], [8, 2]], + [[200, 7], [8, 300]], + [[28, 21], [6, 1957]], + [[190, 800], [200, 900]], + # Some tables with simple exact values + # (includes regression test for ticket #1568): + [[0, 2], [3, 0]], + [[1, 1], [2, 1]], + [[2, 0], [1, 2]], + [[0, 1], [2, 3]], + [[1, 0], [1, 4]], + ) + pvals = ( + # from R: + [0.018521725952066501, 0.9990149169715733], + [1.0, 2.0056578803889148e-122], + [1.0, 5.7284374608319831e-44], + [0.7416227, 0.2959826], + # Exact: + [0.1, 1.0], + [0.7, 0.9], + [1.0, 0.3], + [2./3, 1.0], + [1.0, 1./3], + ) + for table, pval in zip(tables, pvals): + res = [] + res.append(stats.fisher_exact(table, alternative="less")[1]) + res.append(stats.fisher_exact(table, alternative="greater")[1]) + assert_allclose(res, pval, atol=0, rtol=1e-7) + + def test_gh3014(self): + # check if issue #3014 has been fixed. + # before, this would have risen a ValueError + odds, pvalue = stats.fisher_exact([[1, 2], [9, 84419233]]) + + @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater']) + def test_result(self, alternative): + table = np.array([[14500, 20000], [30000, 40000]]) + res = stats.fisher_exact(table, alternative=alternative) + assert_equal((res.statistic, res.pvalue), res) + + def test_input_validation_edge_cases_rxc(self): + rng = np.random.default_rng(2345783457834572345) + table = np.asarray([[2, 7], [8, 2]]) + + message = r"`alternative` must be the default \(None\) unless..." + with pytest.raises(ValueError, match=message): + method = stats.PermutationMethod(rng=rng) + stats.fisher_exact(table, method=method, alternative='less') + + message = "...not recognized; if provided, `method` must be an..." + with pytest.raises(ValueError, match=message): + method = stats.BootstrapMethod(rng=rng) + stats.fisher_exact(table, method=method) + + message = "If the `method` argument of `fisher_exact` is an..." + with pytest.raises(ValueError, match=message): + method = stats.MonteCarloMethod(rvs=stats.norm.rvs) + stats.fisher_exact(table, method=method) + + message = "`table` must have at least one row and one column." + with pytest.raises(ValueError, match=message): + stats.fisher_exact(np.zeros((0, 1))) + + # Specical case: when there is only one table with given marginals, the + # PMF of that case is 1.0, so the p-value is 1.0 + np.testing.assert_equal(stats.fisher_exact([[1, 2, 3]]), (1, 1)) + np.testing.assert_equal(stats.fisher_exact([[1], [2], [3]]), (1, 1)) + np.testing.assert_equal(stats.fisher_exact(np.zeros((2, 3))), (1, 1)) + + + + @pytest.mark.fail_slow(10) + @pytest.mark.slow() + def test_resampling_2x2(self): + rng = np.random.default_rng(2345783457834572345) + table = np.asarray([[2, 7], [8, 2]]) + ref = stats.fisher_exact(table) + ref_pvalue = ref.pvalue + ref_stat = stats.random_table(table.sum(axis=1), table.sum(axis=0)).pmf(table) + + method = stats.MonteCarloMethod(rng=rng) + res = stats.fisher_exact(table, method=method) + assert_allclose(res.pvalue, ref_pvalue, atol=0.0025) + assert_equal(res.statistic, ref_stat) + + method = stats.PermutationMethod(rng=rng) + res = stats.fisher_exact(table, method=method) + assert_allclose(res.pvalue, ref.pvalue, atol=0.0025) + assert_equal(res.statistic, ref_stat) + + @pytest.mark.fail_slow(10) + @pytest.mark.slow() + def test_resampling_rxc(self): + # Compare against R fisher.exact + # options(digits=16) + # MP6 < - rbind( + # c(1, 2, 2, 1, 1, 0, 1), + # c(2, 0, 0, 2, 3, 0, 0), + # c(0, 1, 1, 1, 2, 7, 3), + # c(1, 1, 2, 0, 0, 0, 1), + # c(0, 1, 1, 1, 1, 0, 0)) + # fisher.test(MP6) + + table = [[1, 2, 2, 1, 1, 0, 1], + [2, 0, 0, 2, 3, 0, 0], + [0, 1, 1, 1, 2, 7, 3], + [1, 1, 2, 0, 0, 0, 1], + [0, 1, 1, 1, 1, 0, 0]] + table = np.asarray(table) + + ref_pvalue = 0.03928964365533 + rng = np.random.default_rng(3928964365533) + + method = stats.PermutationMethod(rng=rng) + res = stats.fisher_exact(table, method=method) + assert_allclose(res.pvalue, ref_pvalue, atol=5e-4) + + method = stats.MonteCarloMethod(rng=rng, n_resamples=99999) + res = stats.fisher_exact(table, method=method) + assert_allclose(res.pvalue, ref_pvalue, atol=5e-4) + + @pytest.mark.xslow() + def test_resampling_exact_2x2(self): + # Test that exact permutation p-value matches result of `fisher_exact` + rng = np.random.default_rng(2345783457834572345) + method = stats.PermutationMethod(rng=rng) + + for a in range(1, 3): + for b in range(1, 3): + for c in range(1, 3): + for d in range(1, 4): + table = np.asarray([[a, b], [c, d]]) + ref = stats.fisher_exact(table) + res = stats.fisher_exact(table, method=method) + assert_allclose(res.pvalue, ref.pvalue, atol=1e-14) + + +class TestCorrSpearmanr: + """ W.II.D. Compute a correlation matrix on all the variables. + + All the correlations, except for ZERO and MISS, should be exactly 1. + ZERO and MISS should have undefined or missing correlations with the + other variables. The same should go for SPEARMAN correlations, if + your program has them. + """ + + def test_scalar(self): + y = stats.spearmanr(4., 2.) + assert_(np.isnan(y).all()) + + def test_uneven_lengths(self): + assert_raises(ValueError, stats.spearmanr, [1, 2, 1], [8, 9]) + assert_raises(ValueError, stats.spearmanr, [1, 2, 1], 8) + + def test_uneven_2d_shapes(self): + # Different number of columns should work - those just get concatenated. + np.random.seed(232324) + x = np.random.randn(4, 3) + y = np.random.randn(4, 2) + assert stats.spearmanr(x, y).statistic.shape == (5, 5) + assert stats.spearmanr(x.T, y.T, axis=1).pvalue.shape == (5, 5) + + assert_raises(ValueError, stats.spearmanr, x, y, axis=1) + assert_raises(ValueError, stats.spearmanr, x.T, y.T) + + def test_ndim_too_high(self): + np.random.seed(232324) + x = np.random.randn(4, 3, 2) + assert_raises(ValueError, stats.spearmanr, x) + assert_raises(ValueError, stats.spearmanr, x, x) + assert_raises(ValueError, stats.spearmanr, x, None, None) + # But should work with axis=None (raveling axes) for two input arrays + assert_allclose(stats.spearmanr(x, x, axis=None), + stats.spearmanr(x.flatten(), x.flatten(), axis=0)) + + def test_nan_policy(self): + x = np.arange(10.) + x[9] = np.nan + assert_array_equal(stats.spearmanr(x, x), (np.nan, np.nan)) + assert_array_equal(stats.spearmanr(x, x, nan_policy='omit'), + (1.0, 0.0)) + assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='raise') + assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='foobar') + + def test_nan_policy_bug_12458(self): + np.random.seed(5) + x = np.random.rand(5, 10) + k = 6 + x[:, k] = np.nan + y = np.delete(x, k, axis=1) + corx, px = stats.spearmanr(x, nan_policy='omit') + cory, py = stats.spearmanr(y) + corx = np.delete(np.delete(corx, k, axis=1), k, axis=0) + px = np.delete(np.delete(px, k, axis=1), k, axis=0) + assert_allclose(corx, cory, atol=1e-14) + assert_allclose(px, py, atol=1e-14) + + def test_nan_policy_bug_12411(self): + np.random.seed(5) + m = 5 + n = 10 + x = np.random.randn(m, n) + x[1, 0] = np.nan + x[3, -1] = np.nan + corr, pvalue = stats.spearmanr(x, axis=1, nan_policy="propagate") + res = [[stats.spearmanr(x[i, :], x[j, :]).statistic for i in range(m)] + for j in range(m)] + assert_allclose(corr, res) + + def test_sXX(self): + y = stats.spearmanr(X,X) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sXBIG(self): + y = stats.spearmanr(X,BIG) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sXLITTLE(self): + y = stats.spearmanr(X,LITTLE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sXHUGE(self): + y = stats.spearmanr(X,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sXTINY(self): + y = stats.spearmanr(X,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sXROUND(self): + y = stats.spearmanr(X,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sBIGBIG(self): + y = stats.spearmanr(BIG,BIG) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sBIGLITTLE(self): + y = stats.spearmanr(BIG,LITTLE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sBIGHUGE(self): + y = stats.spearmanr(BIG,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sBIGTINY(self): + y = stats.spearmanr(BIG,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sBIGROUND(self): + y = stats.spearmanr(BIG,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sLITTLELITTLE(self): + y = stats.spearmanr(LITTLE,LITTLE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sLITTLEHUGE(self): + y = stats.spearmanr(LITTLE,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sLITTLETINY(self): + y = stats.spearmanr(LITTLE,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sLITTLEROUND(self): + y = stats.spearmanr(LITTLE,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sHUGEHUGE(self): + y = stats.spearmanr(HUGE,HUGE) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sHUGETINY(self): + y = stats.spearmanr(HUGE,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sHUGEROUND(self): + y = stats.spearmanr(HUGE,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sTINYTINY(self): + y = stats.spearmanr(TINY,TINY) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sTINYROUND(self): + y = stats.spearmanr(TINY,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_sROUNDROUND(self): + y = stats.spearmanr(ROUND,ROUND) + r = y[0] + assert_approx_equal(r,1.0) + + def test_spearmanr_result_attributes(self): + res = stats.spearmanr(X, X) + attributes = ('correlation', 'pvalue') + check_named_results(res, attributes) + assert_equal(res.correlation, res.statistic) + + def test_1d_vs_2d(self): + x1 = [1, 2, 3, 4, 5, 6] + x2 = [1, 2, 3, 4, 6, 5] + res1 = stats.spearmanr(x1, x2) + res2 = stats.spearmanr(np.asarray([x1, x2]).T) + assert_allclose(res1, res2) + + def test_1d_vs_2d_nans(self): + # Now the same with NaNs present. Regression test for gh-9103. + for nan_policy in ['propagate', 'omit']: + x1 = [1, np.nan, 3, 4, 5, 6] + x2 = [1, 2, 3, 4, 6, np.nan] + res1 = stats.spearmanr(x1, x2, nan_policy=nan_policy) + res2 = stats.spearmanr(np.asarray([x1, x2]).T, nan_policy=nan_policy) + assert_allclose(res1, res2) + + def test_3cols(self): + x1 = np.arange(6) + x2 = -x1 + x3 = np.array([0, 1, 2, 3, 5, 4]) + x = np.asarray([x1, x2, x3]).T + actual = stats.spearmanr(x) + expected_corr = np.array([[1, -1, 0.94285714], + [-1, 1, -0.94285714], + [0.94285714, -0.94285714, 1]]) + expected_pvalue = np.zeros((3, 3), dtype=float) + expected_pvalue[2, 0:2] = 0.00480466472 + expected_pvalue[0:2, 2] = 0.00480466472 + + assert_allclose(actual.statistic, expected_corr) + assert_allclose(actual.pvalue, expected_pvalue) + + def test_gh_9103(self): + # Regression test for gh-9103. + x = np.array([[np.nan, 3.0, 4.0, 5.0, 5.1, 6.0, 9.2], + [5.0, np.nan, 4.1, 4.8, 4.9, 5.0, 4.1], + [0.5, 4.0, 7.1, 3.8, 8.0, 5.1, 7.6]]).T + corr = np.array([[np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan], + [np.nan, np.nan, 1.]]) + assert_allclose(stats.spearmanr(x, nan_policy='propagate').statistic, + corr) + + res = stats.spearmanr(x, nan_policy='omit').statistic + assert_allclose((res[0][1], res[0][2], res[1][2]), + (0.2051957, 0.4857143, -0.4707919), rtol=1e-6) + + def test_gh_8111(self): + # Regression test for gh-8111 (different result for float/int/bool). + n = 100 + np.random.seed(234568) + x = np.random.rand(n) + m = np.random.rand(n) > 0.7 + + # bool against float, no nans + a = (x > .5) + b = np.array(x) + res1 = stats.spearmanr(a, b, nan_policy='omit').statistic + + # bool against float with NaNs + b[m] = np.nan + res2 = stats.spearmanr(a, b, nan_policy='omit').statistic + + # int against float with NaNs + a = a.astype(np.int32) + res3 = stats.spearmanr(a, b, nan_policy='omit').statistic + + expected = [0.865895477, 0.866100381, 0.866100381] + assert_allclose([res1, res2, res3], expected) + + +class TestCorrSpearmanr2: + """Some further tests of the spearmanr function.""" + + def test_spearmanr_vs_r(self): + # Cross-check with R: + # cor.test(c(1,2,3,4,5),c(5,6,7,8,7),method="spearmanr") + x1 = [1, 2, 3, 4, 5] + x2 = [5, 6, 7, 8, 7] + expected = (0.82078268166812329, 0.088587005313543798) + res = stats.spearmanr(x1, x2) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + def test_empty_arrays(self): + assert_equal(stats.spearmanr([], []), (np.nan, np.nan)) + + def test_normal_draws(self): + np.random.seed(7546) + x = np.array([np.random.normal(loc=1, scale=1, size=500), + np.random.normal(loc=1, scale=1, size=500)]) + corr = [[1.0, 0.3], + [0.3, 1.0]] + x = np.dot(np.linalg.cholesky(corr), x) + expected = (0.28659685838743354, 6.579862219051161e-11) + res = stats.spearmanr(x[0], x[1]) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + def test_corr_1(self): + assert_approx_equal(stats.spearmanr([1, 1, 2], [1, 1, 2])[0], 1.0) + + def test_nan_policies(self): + x = np.arange(10.) + x[9] = np.nan + assert_array_equal(stats.spearmanr(x, x), (np.nan, np.nan)) + assert_allclose(stats.spearmanr(x, x, nan_policy='omit'), + (1.0, 0)) + assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='raise') + assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='foobar') + + def test_unequal_lengths(self): + x = np.arange(10.) + y = np.arange(20.) + assert_raises(ValueError, stats.spearmanr, x, y) + + def test_omit_paired_value(self): + x1 = [1, 2, 3, 4] + x2 = [8, 7, 6, np.nan] + res1 = stats.spearmanr(x1, x2, nan_policy='omit') + res2 = stats.spearmanr(x1[:3], x2[:3], nan_policy='omit') + assert_equal(res1, res2) + + def test_gh_issue_6061_windows_overflow(self): + x = list(range(2000)) + y = list(range(2000)) + y[0], y[9] = y[9], y[0] + y[10], y[434] = y[434], y[10] + y[435], y[1509] = y[1509], y[435] + # rho = 1 - 6 * (2 * (9^2 + 424^2 + 1074^2))/(2000 * (2000^2 - 1)) + # = 1 - (1 / 500) + # = 0.998 + x.append(np.nan) + y.append(3.0) + assert_almost_equal(stats.spearmanr(x, y, nan_policy='omit')[0], 0.998) + + def test_tie0(self): + # with only ties in one or both inputs + warn_msg = "An input array is constant" + with pytest.warns(stats.ConstantInputWarning, match=warn_msg): + r, p = stats.spearmanr([2, 2, 2], [2, 2, 2]) + assert_equal(r, np.nan) + assert_equal(p, np.nan) + r, p = stats.spearmanr([2, 0, 2], [2, 2, 2]) + assert_equal(r, np.nan) + assert_equal(p, np.nan) + r, p = stats.spearmanr([2, 2, 2], [2, 0, 2]) + assert_equal(r, np.nan) + assert_equal(p, np.nan) + + def test_tie1(self): + # Data + x = [1.0, 2.0, 3.0, 4.0] + y = [1.0, 2.0, 2.0, 3.0] + # Ranks of the data, with tie-handling. + xr = [1.0, 2.0, 3.0, 4.0] + yr = [1.0, 2.5, 2.5, 4.0] + # Result of spearmanr should be the same as applying + # pearsonr to the ranks. + sr = stats.spearmanr(x, y) + pr = stats.pearsonr(xr, yr) + assert_almost_equal(sr, pr) + + def test_tie2(self): + # Test tie-handling if inputs contain nan's + # Data without nan's + x1 = [1, 2, 2.5, 2] + y1 = [1, 3, 2.5, 4] + # Same data with nan's + x2 = [1, 2, 2.5, 2, np.nan] + y2 = [1, 3, 2.5, 4, np.nan] + + # Results for two data sets should be the same if nan's are ignored + sr1 = stats.spearmanr(x1, y1) + sr2 = stats.spearmanr(x2, y2, nan_policy='omit') + assert_almost_equal(sr1, sr2) + + def test_ties_axis_1(self): + z1 = np.array([[1, 1, 1, 1], [1, 2, 3, 4]]) + z2 = np.array([[1, 2, 3, 4], [1, 1, 1, 1]]) + z3 = np.array([[1, 1, 1, 1], [1, 1, 1, 1]]) + warn_msg = "An input array is constant" + with pytest.warns(stats.ConstantInputWarning, match=warn_msg): + r, p = stats.spearmanr(z1, axis=1) + assert_equal(r, np.nan) + assert_equal(p, np.nan) + r, p = stats.spearmanr(z2, axis=1) + assert_equal(r, np.nan) + assert_equal(p, np.nan) + r, p = stats.spearmanr(z3, axis=1) + assert_equal(r, np.nan) + assert_equal(p, np.nan) + + def test_gh_11111(self): + x = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + y = np.array([0, 0.009783728115345005, 0, 0, 0.0019759230121848587, + 0.0007535430349118562, 0.0002661781514710257, 0, 0, + 0.0007835762419683435]) + warn_msg = "An input array is constant" + with pytest.warns(stats.ConstantInputWarning, match=warn_msg): + r, p = stats.spearmanr(x, y) + assert_equal(r, np.nan) + assert_equal(p, np.nan) + + def test_index_error(self): + x = np.array([1.0, 7.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + y = np.array([0, 0.009783728115345005, 0, 0, 0.0019759230121848587, + 0.0007535430349118562, 0.0002661781514710257, 0, 0, + 0.0007835762419683435]) + assert_raises(ValueError, stats.spearmanr, x, y, axis=2) + + def test_alternative(self): + # Test alternative parameter + + # Simple test - Based on the above ``test_spearmanr_vs_r`` + x1 = [1, 2, 3, 4, 5] + x2 = [5, 6, 7, 8, 7] + + # strong positive correlation + expected = (0.82078268166812329, 0.088587005313543798) + + # correlation > 0 -> large "less" p-value + res = stats.spearmanr(x1, x2, alternative="less") + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], 1 - (expected[1] / 2)) + + # correlation > 0 -> small "less" p-value + res = stats.spearmanr(x1, x2, alternative="greater") + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1] / 2) + + with pytest.raises(ValueError, match="`alternative` must be 'less'..."): + stats.spearmanr(x1, x2, alternative="ekki-ekki") + + @pytest.mark.parametrize("alternative", ('two-sided', 'less', 'greater')) + def test_alternative_nan_policy(self, alternative): + # Test nan policies + x1 = [1, 2, 3, 4, 5] + x2 = [5, 6, 7, 8, 7] + x1nan = x1 + [np.nan] + x2nan = x2 + [np.nan] + + # test nan_policy="propagate" + assert_array_equal(stats.spearmanr(x1nan, x2nan), (np.nan, np.nan)) + + # test nan_policy="omit" + res_actual = stats.spearmanr(x1nan, x2nan, nan_policy='omit', + alternative=alternative) + res_expected = stats.spearmanr(x1, x2, alternative=alternative) + assert_allclose(res_actual, res_expected) + + # test nan_policy="raise" + message = 'The input contains nan values' + with pytest.raises(ValueError, match=message): + stats.spearmanr(x1nan, x2nan, nan_policy='raise', + alternative=alternative) + + # test invalid nan_policy + message = "nan_policy must be one of..." + with pytest.raises(ValueError, match=message): + stats.spearmanr(x1nan, x2nan, nan_policy='ekki-ekki', + alternative=alternative) + + +# W.II.E. Tabulate X against X, using BIG as a case weight. The values +# should appear on the diagonal and the total should be 899999955. +# If the table cannot hold these values, forget about working with +# census data. You can also tabulate HUGE against TINY. There is no +# reason a tabulation program should not be able to distinguish +# different values regardless of their magnitude. + +# I need to figure out how to do this one. + + +def test_kendalltau(): + # For the cases without ties, both variants should give the same + # result. + variants = ('b', 'c') + + # case without ties, con-dis equal zero + x = [5, 2, 1, 3, 6, 4, 7, 8] + y = [5, 2, 6, 3, 1, 8, 7, 4] + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (0.0, 1.0) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # case without ties, con-dis equal zero + x = [0, 5, 2, 1, 3, 6, 4, 7, 8] + y = [5, 2, 0, 6, 3, 1, 8, 7, 4] + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (0.0, 1.0) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # case without ties, con-dis close to zero + x = [5, 2, 1, 3, 6, 4, 7] + y = [5, 2, 6, 3, 1, 7, 4] + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (-0.14285714286, 0.77261904762) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # case without ties, con-dis close to zero + x = [2, 1, 3, 6, 4, 7, 8] + y = [2, 6, 3, 1, 8, 7, 4] + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (0.047619047619, 1.0) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # simple case without ties + x = np.arange(10) + y = np.arange(10) + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (1.0, 5.511463844797e-07) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # swap a couple of values + b = y[1] + y[1] = y[2] + y[2] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (0.9555555555555556, 5.511463844797e-06) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # swap a couple more + b = y[5] + y[5] = y[6] + y[6] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (0.9111111111111111, 2.976190476190e-05) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # same in opposite direction + x = np.arange(10) + y = np.arange(10)[::-1] + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (-1.0, 5.511463844797e-07) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # swap a couple of values + b = y[1] + y[1] = y[2] + y[2] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (-0.9555555555555556, 5.511463844797e-06) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # swap a couple more + b = y[5] + y[5] = y[6] + y[6] = b + # Cross-check with exact result from R: + # cor.test(x,y,method="kendall",exact=1) + expected = (-0.9111111111111111, 2.976190476190e-05) + for taux in variants: + res = stats.kendalltau(x, y, variant=taux) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # Check a case where variants are different + # Example values found from Kendall (1970). + # P-value is the same for the both variants + x = array([1, 2, 2, 4, 4, 6, 6, 8, 9, 9]) + y = array([1, 2, 4, 4, 4, 4, 8, 8, 8, 10]) + expected = 0.85895569 + assert_approx_equal(stats.kendalltau(x, y, variant='b')[0], expected) + expected = 0.825 + assert_approx_equal(stats.kendalltau(x, y, variant='c')[0], expected) + + # check exception in case of ties and method='exact' requested + y[2] = y[1] + assert_raises(ValueError, stats.kendalltau, x, y, method='exact') + + # check exception in case of invalid method keyword + assert_raises(ValueError, stats.kendalltau, x, y, method='banana') + + # check exception in case of invalid variant keyword + assert_raises(ValueError, stats.kendalltau, x, y, variant='rms') + + # tau-b with some ties + # Cross-check with R: + # cor.test(c(12,2,1,12,2),c(1,4,7,1,0),method="kendall",exact=FALSE) + x1 = [12, 2, 1, 12, 2] + x2 = [1, 4, 7, 1, 0] + expected = (-0.47140452079103173, 0.28274545993277478) + res = stats.kendalltau(x1, x2) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # test for namedtuple attribute results + attributes = ('correlation', 'pvalue') + for taux in variants: + res = stats.kendalltau(x1, x2, variant=taux) + check_named_results(res, attributes) + assert_equal(res.correlation, res.statistic) + + # with only ties in one or both inputs in tau-b or tau-c + for taux in variants: + assert_equal(stats.kendalltau([2, 2, 2], [2, 2, 2], variant=taux), + (np.nan, np.nan)) + assert_equal(stats.kendalltau([2, 0, 2], [2, 2, 2], variant=taux), + (np.nan, np.nan)) + assert_equal(stats.kendalltau([2, 2, 2], [2, 0, 2], variant=taux), + (np.nan, np.nan)) + + # empty arrays provided as input + assert_equal(stats.kendalltau([], []), (np.nan, np.nan)) + + # check with larger arrays + np.random.seed(7546) + x = np.array([np.random.normal(loc=1, scale=1, size=500), + np.random.normal(loc=1, scale=1, size=500)]) + corr = [[1.0, 0.3], + [0.3, 1.0]] + x = np.dot(np.linalg.cholesky(corr), x) + expected = (0.19291382765531062, 1.1337095377742629e-10) + res = stats.kendalltau(x[0], x[1]) + assert_approx_equal(res[0], expected[0]) + assert_approx_equal(res[1], expected[1]) + + # this should result in 1 for taub but not tau-c + assert_approx_equal(stats.kendalltau([1, 1, 2], [1, 1, 2], variant='b')[0], + 1.0) + assert_approx_equal(stats.kendalltau([1, 1, 2], [1, 1, 2], variant='c')[0], + 0.88888888) + + # test nan_policy + x = np.arange(10.) + x[9] = np.nan + assert_array_equal(stats.kendalltau(x, x), (np.nan, np.nan)) + assert_allclose(stats.kendalltau(x, x, nan_policy='omit'), + (1.0, 5.5114638e-6), rtol=1e-06) + assert_allclose(stats.kendalltau(x, x, nan_policy='omit', method='asymptotic'), + (1.0, 0.00017455009626808976), rtol=1e-06) + assert_raises(ValueError, stats.kendalltau, x, x, nan_policy='raise') + assert_raises(ValueError, stats.kendalltau, x, x, nan_policy='foobar') + + # test unequal length inputs + x = np.arange(10.) + y = np.arange(20.) + assert_raises(ValueError, stats.kendalltau, x, y) + + # test all ties + tau, p_value = stats.kendalltau([], []) + assert_equal(np.nan, tau) + assert_equal(np.nan, p_value) + tau, p_value = stats.kendalltau([0], [0]) + assert_equal(np.nan, tau) + assert_equal(np.nan, p_value) + + # Regression test for GitHub issue #6061 - Overflow on Windows + x = np.arange(2000, dtype=float) + x = np.ma.masked_greater(x, 1995) + y = np.arange(2000, dtype=float) + y = np.concatenate((y[1000:], y[:1000])) + assert_(np.isfinite(stats.kendalltau(x,y)[1])) + + +def test_kendalltau_vs_mstats_basic(): + np.random.seed(42) + for s in range(2,10): + a = [] + # Generate rankings with ties + for i in range(s): + a += [i]*i + b = list(a) + np.random.shuffle(a) + np.random.shuffle(b) + expected = mstats_basic.kendalltau(a, b) + actual = stats.kendalltau(a, b) + assert_approx_equal(actual[0], expected[0]) + assert_approx_equal(actual[1], expected[1]) + + +def test_kendalltau_nan_2nd_arg(): + # regression test for gh-6134: nans in the second arg were not handled + x = [1., 2., 3., 4.] + y = [np.nan, 2.4, 3.4, 3.4] + + r1 = stats.kendalltau(x, y, nan_policy='omit') + r2 = stats.kendalltau(x[1:], y[1:]) + assert_allclose(r1.statistic, r2.statistic, atol=1e-15) + + +def test_kendalltau_gh18139_overflow(): + # gh-18139 reported an overflow in `kendalltau` that appeared after + # SciPy 0.15.1. Check that this particular overflow does not occur. + # (Test would fail if warning were emitted.) + import random + random.seed(6272161) + classes = [1, 2, 3, 4, 5, 6, 7] + n_samples = 2 * 10 ** 5 + x = random.choices(classes, k=n_samples) + y = random.choices(classes, k=n_samples) + res = stats.kendalltau(x, y) + # Reference value from SciPy 0.15.1 + assert_allclose(res.statistic, 0.0011816493905730343) + # Reference p-value from `permutation_test` w/ n_resamples=9999 (default). + # Expected to be accurate to at least two digits. + assert_allclose(res.pvalue, 0.4894, atol=2e-3) + + +class TestKendallTauAlternative: + def test_kendalltau_alternative_asymptotic(self): + # Test alternative parameter, asymptotic method (due to tie) + + # Based on TestCorrSpearman2::test_alternative + x1 = [1, 2, 3, 4, 5] + x2 = [5, 6, 7, 8, 7] + + # strong positive correlation + expected = stats.kendalltau(x1, x2, alternative="two-sided") + assert expected[0] > 0 + + # rank correlation > 0 -> large "less" p-value + res = stats.kendalltau(x1, x2, alternative="less") + assert_equal(res[0], expected[0]) + assert_allclose(res[1], 1 - (expected[1] / 2)) + + # rank correlation > 0 -> small "greater" p-value + res = stats.kendalltau(x1, x2, alternative="greater") + assert_equal(res[0], expected[0]) + assert_allclose(res[1], expected[1] / 2) + + # reverse the direction of rank correlation + x2.reverse() + + # strong negative correlation + expected = stats.kendalltau(x1, x2, alternative="two-sided") + assert expected[0] < 0 + + # rank correlation < 0 -> large "greater" p-value + res = stats.kendalltau(x1, x2, alternative="greater") + assert_equal(res[0], expected[0]) + assert_allclose(res[1], 1 - (expected[1] / 2)) + + # rank correlation < 0 -> small "less" p-value + res = stats.kendalltau(x1, x2, alternative="less") + assert_equal(res[0], expected[0]) + assert_allclose(res[1], expected[1] / 2) + + with pytest.raises(ValueError, match="`alternative` must be 'less'..."): + stats.kendalltau(x1, x2, alternative="ekki-ekki") + + # There are a lot of special cases considered in the calculation of the + # exact p-value, so we test each separately. We also need to test + # separately when the observed statistic is in the left tail vs the right + # tail because the code leverages symmetry of the null distribution; to + # do that we use the same test case but negate one of the samples. + # Reference values computed using R cor.test, e.g. + # options(digits=16) + # x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1) + # y <- c( 2.6, 3.1, 2.5, 5.0, 3.6, 4.0, 5.2, 2.8, 3.8) + # cor.test(x, y, method = "kendall", alternative = "g") + + alternatives = ('less', 'two-sided', 'greater') + p_n1 = [np.nan, np.nan, np.nan] + p_n2 = [1, 1, 0.5] + p_c0 = [1, 0.3333333333333, 0.1666666666667] + p_c1 = [0.9583333333333, 0.3333333333333, 0.1666666666667] + p_no_correlation = [0.5916666666667, 1, 0.5916666666667] + p_no_correlationb = [0.5475694444444, 1, 0.5475694444444] + p_n_lt_171 = [0.9624118165785, 0.1194389329806, 0.0597194664903] + p_n_lt_171b = [0.246236925303, 0.4924738506059, 0.755634083327] + p_n_lt_171c = [0.9847475308925, 0.03071385306533, 0.01535692653267] + + def exact_test(self, x, y, alternative, rev, stat_expected, p_expected): + if rev: + y = -np.asarray(y) + stat_expected *= -1 + res = stats.kendalltau(x, y, method='exact', alternative=alternative) + res_expected = stat_expected, p_expected + assert_allclose(res, res_expected) + + case_R_n1 = (list(zip(alternatives, p_n1, [False]*3)) + + list(zip(alternatives, reversed(p_n1), [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_n1) + def test_against_R_n1(self, alternative, p_expected, rev): + x, y = [1], [2] + stat_expected = np.nan + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_R_n2 = (list(zip(alternatives, p_n2, [False]*3)) + + list(zip(alternatives, reversed(p_n2), [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_n2) + def test_against_R_n2(self, alternative, p_expected, rev): + x, y = [1, 2], [3, 4] + stat_expected = 0.9999999999999998 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_R_c0 = (list(zip(alternatives, p_c0, [False]*3)) + + list(zip(alternatives, reversed(p_c0), [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_c0) + def test_against_R_c0(self, alternative, p_expected, rev): + x, y = [1, 2, 3], [1, 2, 3] + stat_expected = 1 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_R_c1 = (list(zip(alternatives, p_c1, [False]*3)) + + list(zip(alternatives, reversed(p_c1), [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_c1) + def test_against_R_c1(self, alternative, p_expected, rev): + x, y = [1, 2, 3, 4], [1, 2, 4, 3] + stat_expected = 0.6666666666666667 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_R_no_corr = (list(zip(alternatives, p_no_correlation, [False]*3)) + + list(zip(alternatives, reversed(p_no_correlation), + [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_no_corr) + def test_against_R_no_correlation(self, alternative, p_expected, rev): + x, y = [1, 2, 3, 4, 5], [1, 5, 4, 2, 3] + stat_expected = 0 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_no_cor_b = (list(zip(alternatives, p_no_correlationb, [False]*3)) + + list(zip(alternatives, reversed(p_no_correlationb), + [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_no_cor_b) + def test_against_R_no_correlationb(self, alternative, p_expected, rev): + x, y = [1, 2, 3, 4, 5, 6, 7, 8], [8, 6, 1, 3, 2, 5, 4, 7] + stat_expected = 0 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_R_lt_171 = (list(zip(alternatives, p_n_lt_171, [False]*3)) + + list(zip(alternatives, reversed(p_n_lt_171), [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_lt_171) + def test_against_R_lt_171(self, alternative, p_expected, rev): + # Data from Hollander & Wolfe (1973), p. 187f. + # Used from https://rdrr.io/r/stats/cor.test.html + x = [44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1] + y = [2.6, 3.1, 2.5, 5.0, 3.6, 4.0, 5.2, 2.8, 3.8] + stat_expected = 0.4444444444444445 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_R_lt_171b = (list(zip(alternatives, p_n_lt_171b, [False]*3)) + + list(zip(alternatives, reversed(p_n_lt_171b), + [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_lt_171b) + def test_against_R_lt_171b(self, alternative, p_expected, rev): + np.random.seed(0) + x = np.random.rand(100) + y = np.random.rand(100) + stat_expected = -0.04686868686868687 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_R_lt_171c = (list(zip(alternatives, p_n_lt_171c, [False]*3)) + + list(zip(alternatives, reversed(p_n_lt_171c), + [True]*3))) + + @pytest.mark.parametrize("alternative, p_expected, rev", case_R_lt_171c) + def test_against_R_lt_171c(self, alternative, p_expected, rev): + np.random.seed(0) + x = np.random.rand(170) + y = np.random.rand(170) + stat_expected = 0.1115906717716673 + self.exact_test(x, y, alternative, rev, stat_expected, p_expected) + + case_gt_171 = (list(zip(alternatives, [False]*3)) + + list(zip(alternatives, [True]*3))) + + @pytest.mark.parametrize("alternative, rev", case_gt_171) + def test_gt_171(self, alternative, rev): + np.random.seed(0) + x = np.random.rand(400) + y = np.random.rand(400) + res0 = stats.kendalltau(x, y, method='exact', + alternative=alternative) + res1 = stats.kendalltau(x, y, method='asymptotic', + alternative=alternative) + assert_equal(res0[0], res1[0]) + assert_allclose(res0[1], res1[1], rtol=1e-3) + + @pytest.mark.parametrize("method", ('exact', 'asymptotic')) + @pytest.mark.parametrize("alternative", ('two-sided', 'less', 'greater')) + def test_nan_policy(self, method, alternative): + # Test nan policies + x1 = [1, 2, 3, 4, 5] + x2 = [5, 6, 7, 8, 9] + x1nan = x1 + [np.nan] + x2nan = x2 + [np.nan] + + # test nan_policy="propagate" + res_actual = stats.kendalltau(x1nan, x2nan, + method=method, alternative=alternative) + res_expected = (np.nan, np.nan) + assert_allclose(res_actual, res_expected) + + # test nan_policy="omit" + res_actual = stats.kendalltau(x1nan, x2nan, nan_policy='omit', + method=method, alternative=alternative) + res_expected = stats.kendalltau(x1, x2, method=method, + alternative=alternative) + assert_allclose(res_actual, res_expected) + + # test nan_policy="raise" + message = 'The input contains nan values' + with pytest.raises(ValueError, match=message): + stats.kendalltau(x1nan, x2nan, nan_policy='raise', + method=method, alternative=alternative) + + # test invalid nan_policy + message = "nan_policy must be one of..." + with pytest.raises(ValueError, match=message): + stats.kendalltau(x1nan, x2nan, nan_policy='ekki-ekki', + method=method, alternative=alternative) + + +def test_weightedtau(): + x = [12, 2, 1, 12, 2] + y = [1, 4, 7, 1, 0] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.56694968153682723) + assert_equal(np.nan, p_value) + tau, p_value = stats.weightedtau(x, y, additive=False) + assert_approx_equal(tau, -0.62205716951801038) + assert_equal(np.nan, p_value) + # This must be exactly Kendall's tau + tau, p_value = stats.weightedtau(x, y, weigher=lambda x: 1) + assert_approx_equal(tau, -0.47140452079103173) + assert_equal(np.nan, p_value) + + # test for namedtuple attribute results + res = stats.weightedtau(x, y) + attributes = ('correlation', 'pvalue') + check_named_results(res, attributes) + assert_equal(res.correlation, res.statistic) + + # Asymmetric, ranked version + tau, p_value = stats.weightedtau(x, y, rank=None) + assert_approx_equal(tau, -0.4157652301037516) + assert_equal(np.nan, p_value) + tau, p_value = stats.weightedtau(y, x, rank=None) + assert_approx_equal(tau, -0.7181341329699029) + assert_equal(np.nan, p_value) + tau, p_value = stats.weightedtau(x, y, rank=None, additive=False) + assert_approx_equal(tau, -0.40644850966246893) + assert_equal(np.nan, p_value) + tau, p_value = stats.weightedtau(y, x, rank=None, additive=False) + assert_approx_equal(tau, -0.83766582937355172) + assert_equal(np.nan, p_value) + tau, p_value = stats.weightedtau(x, y, rank=False) + assert_approx_equal(tau, -0.51604397940261848) + assert_equal(np.nan, p_value) + # This must be exactly Kendall's tau + tau, p_value = stats.weightedtau(x, y, rank=True, weigher=lambda x: 1) + assert_approx_equal(tau, -0.47140452079103173) + assert_equal(np.nan, p_value) + tau, p_value = stats.weightedtau(y, x, rank=True, weigher=lambda x: 1) + assert_approx_equal(tau, -0.47140452079103173) + assert_equal(np.nan, p_value) + # Test argument conversion + tau, p_value = stats.weightedtau(np.asarray(x, dtype=np.float64), y) + assert_approx_equal(tau, -0.56694968153682723) + tau, p_value = stats.weightedtau(np.asarray(x, dtype=np.int16), y) + assert_approx_equal(tau, -0.56694968153682723) + tau, p_value = stats.weightedtau(np.asarray(x, dtype=np.float64), + np.asarray(y, dtype=np.float64)) + assert_approx_equal(tau, -0.56694968153682723) + # All ties + tau, p_value = stats.weightedtau([], []) + assert_equal(np.nan, tau) + assert_equal(np.nan, p_value) + tau, p_value = stats.weightedtau([0], [0]) + assert_equal(np.nan, tau) + assert_equal(np.nan, p_value) + # Size mismatches + assert_raises(ValueError, stats.weightedtau, [0, 1], [0, 1, 2]) + assert_raises(ValueError, stats.weightedtau, [0, 1], [0, 1], [0]) + # NaNs + x = [12, 2, 1, 12, 2] + y = [1, 4, 7, 1, np.nan] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.56694968153682723) + x = [12, 2, np.nan, 12, 2] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.56694968153682723) + # NaNs when the dtype of x and y are all np.float64 + x = [12.0, 2.0, 1.0, 12.0, 2.0] + y = [1.0, 4.0, 7.0, 1.0, np.nan] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.56694968153682723) + x = [12.0, 2.0, np.nan, 12.0, 2.0] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.56694968153682723) + # NaNs when there are more than one NaN in x or y + x = [12.0, 2.0, 1.0, 12.0, 1.0] + y = [1.0, 4.0, 7.0, 1.0, 1.0] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.6615242347139803) + x = [12.0, 2.0, np.nan, 12.0, np.nan] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.6615242347139803) + y = [np.nan, 4.0, 7.0, np.nan, np.nan] + tau, p_value = stats.weightedtau(x, y) + assert_approx_equal(tau, -0.6615242347139803) + + +def test_segfault_issue_9710(): + # https://github.com/scipy/scipy/issues/9710 + # This test was created to check segfault + # In issue SEGFAULT only repros in optimized builds after calling the function twice + stats.weightedtau([1], [1.0]) + stats.weightedtau([1], [1.0]) + # The code below also caused SEGFAULT + stats.weightedtau([np.nan], [52]) + + +def test_kendall_tau_large(): + n = 172 + # Test omit policy + x = np.arange(n + 1).astype(float) + y = np.arange(n + 1).astype(float) + y[-1] = np.nan + _, pval = stats.kendalltau(x, y, method='exact', nan_policy='omit') + assert_equal(pval, 0.0) + + +def test_weightedtau_vs_quadratic(): + # Trivial quadratic implementation, all parameters mandatory + def wkq(x, y, rank, weigher, add): + tot = conc = disc = u = v = 0 + for (i, j) in product(range(len(x)), range(len(x))): + w = weigher(rank[i]) + weigher(rank[j]) if add \ + else weigher(rank[i]) * weigher(rank[j]) + tot += w + if x[i] == x[j]: + u += w + if y[i] == y[j]: + v += w + if x[i] < x[j] and y[i] < y[j] or x[i] > x[j] and y[i] > y[j]: + conc += w + elif x[i] < x[j] and y[i] > y[j] or x[i] > x[j] and y[i] < y[j]: + disc += w + return (conc - disc) / np.sqrt(tot - u) / np.sqrt(tot - v) + + def weigher(x): + return 1. / (x + 1) + + np.random.seed(42) + for s in range(3,10): + a = [] + # Generate rankings with ties + for i in range(s): + a += [i]*i + b = list(a) + np.random.shuffle(a) + np.random.shuffle(b) + # First pass: use element indices as ranks + rank = np.arange(len(a), dtype=np.intp) + for _ in range(2): + for add in [True, False]: + expected = wkq(a, b, rank, weigher, add) + actual = stats.weightedtau(a, b, rank, weigher, add).statistic + assert_approx_equal(expected, actual) + # Second pass: use a random rank + np.random.shuffle(rank) + + +class TestFindRepeats: + + def test_basic(self): + a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 5] + message = "`scipy.stats.find_repeats` is deprecated..." + with pytest.deprecated_call(match=message): + res, nums = stats.find_repeats(a) + assert_array_equal(res, [1, 2, 3, 4]) + assert_array_equal(nums, [3, 3, 2, 2]) + + def test_empty_result(self): + # Check that empty arrays are returned when there are no repeats. + for a in [[10, 20, 50, 30, 40], []]: + message = "`scipy.stats.find_repeats` is deprecated..." + with pytest.deprecated_call(match=message): + repeated, counts = stats.find_repeats(a) + assert_array_equal(repeated, []) + assert_array_equal(counts, []) + + +class TestRegression: + + def test_one_arg_deprecation(self): + x = np.arange(20).reshape((2, 10)) + message = "Inference of the two sets..." + with pytest.deprecated_call(match=message): + stats.linregress(x) + stats.linregress(x[0], x[1]) + + def test_linregressBIGX(self): + # W.II.F. Regress BIG on X. + result = stats.linregress(X, BIG) + assert_almost_equal(result.intercept, 99999990) + assert_almost_equal(result.rvalue, 1.0) + # The uncertainty ought to be almost zero + # since all points lie on a line + assert_almost_equal(result.stderr, 0.0) + assert_almost_equal(result.intercept_stderr, 0.0) + + def test_regressXX(self): + # W.IV.B. Regress X on X. + # The constant should be exactly 0 and the regression coefficient + # should be 1. This is a perfectly valid regression and the + # program should not complain. + result = stats.linregress(X, X) + assert_almost_equal(result.intercept, 0.0) + assert_almost_equal(result.rvalue, 1.0) + # The uncertainly on regression through two points ought to be 0 + assert_almost_equal(result.stderr, 0.0) + assert_almost_equal(result.intercept_stderr, 0.0) + + # W.IV.C. Regress X on BIG and LITTLE (two predictors). The program + # should tell you that this model is "singular" because BIG and + # LITTLE are linear combinations of each other. Cryptic error + # messages are unacceptable here. Singularity is the most + # fundamental regression error. + # + # Need to figure out how to handle multiple linear regression. + # This is not obvious + + def test_regressZEROX(self): + # W.IV.D. Regress ZERO on X. + # The program should inform you that ZERO has no variance or it should + # go ahead and compute the regression and report a correlation and + # total sum of squares of exactly 0. + result = stats.linregress(X, ZERO) + assert_almost_equal(result.intercept, 0.0) + assert_almost_equal(result.rvalue, 0.0) + + def test_regress_simple(self): + # Regress a line with sinusoidal noise. + x = np.linspace(0, 100, 100) + y = 0.2 * np.linspace(0, 100, 100) + 10 + y += np.sin(np.linspace(0, 20, 100)) + + result = stats.linregress(x, y) + lr = LinregressResult + assert_(isinstance(result, lr)) + assert_almost_equal(result.stderr, 2.3957814497838803e-3) + + def test_regress_alternative(self): + # test alternative parameter + x = np.linspace(0, 100, 100) + y = 0.2 * np.linspace(0, 100, 100) + 10 # slope is greater than zero + y += np.sin(np.linspace(0, 20, 100)) + + with pytest.raises(ValueError, match="`alternative` must be 'less'..."): + stats.linregress(x, y, alternative="ekki-ekki") + + res1 = stats.linregress(x, y, alternative="two-sided") + + # slope is greater than zero, so "less" p-value should be large + res2 = stats.linregress(x, y, alternative="less") + assert_allclose(res2.pvalue, 1 - (res1.pvalue / 2)) + + # slope is greater than zero, so "greater" p-value should be small + res3 = stats.linregress(x, y, alternative="greater") + assert_allclose(res3.pvalue, res1.pvalue / 2) + + assert res1.rvalue == res2.rvalue == res3.rvalue + + def test_regress_against_R(self): + # test against R `lm` + # options(digits=16) + # x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) + # y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) + # relation <- lm(y~x) + # print(summary(relation)) + + x = [151, 174, 138, 186, 128, 136, 179, 163, 152, 131] + y = [63, 81, 56, 91, 47, 57, 76, 72, 62, 48] + res = stats.linregress(x, y, alternative="two-sided") + # expected values from R's `lm` above + assert_allclose(res.slope, 0.6746104491292) + assert_allclose(res.intercept, -38.4550870760770) + assert_allclose(res.rvalue, np.sqrt(0.95478224775)) + assert_allclose(res.pvalue, 1.16440531074e-06) + assert_allclose(res.stderr, 0.0519051424731) + assert_allclose(res.intercept_stderr, 8.0490133029927) + + # TODO: remove this test once single-arg support is dropped; + # deprecation warning tested in `test_one_arg_deprecation` + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_regress_simple_onearg_rows(self): + # Regress a line w sinusoidal noise, + # with a single input of shape (2, N) + x = np.linspace(0, 100, 100) + y = 0.2 * np.linspace(0, 100, 100) + 10 + y += np.sin(np.linspace(0, 20, 100)) + rows = np.vstack((x, y)) + + result = stats.linregress(rows) + assert_almost_equal(result.stderr, 2.3957814497838803e-3) + assert_almost_equal(result.intercept_stderr, 1.3866936078570702e-1) + + # TODO: remove this test once single-arg support is dropped; + # deprecation warning tested in `test_one_arg_deprecation` + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_regress_simple_onearg_cols(self): + x = np.linspace(0, 100, 100) + y = 0.2 * np.linspace(0, 100, 100) + 10 + y += np.sin(np.linspace(0, 20, 100)) + columns = np.hstack((np.expand_dims(x, 1), np.expand_dims(y, 1))) + + result = stats.linregress(columns) + assert_almost_equal(result.stderr, 2.3957814497838803e-3) + assert_almost_equal(result.intercept_stderr, 1.3866936078570702e-1) + + # TODO: remove this test once single-arg support is dropped; + # deprecation warning tested in `test_one_arg_deprecation` + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_regress_shape_error(self): + # Check that a single input argument to linregress with wrong shape + # results in a ValueError. + assert_raises(ValueError, stats.linregress, np.ones((3, 3))) + + def test_linregress(self): + # compared with multivariate ols with pinv + x = np.arange(11) + y = np.arange(5, 16) + y[[(1), (-2)]] -= 1 + y[[(0), (-1)]] += 1 + + result = stats.linregress(x, y) + + # This test used to use 'assert_array_almost_equal' but its + # formulation got confusing since LinregressResult became + # _lib._bunch._make_tuple_bunch instead of namedtuple + # (for backwards compatibility, see PR #12983) + def assert_ae(x, y): + return assert_almost_equal(x, y, decimal=14) + assert_ae(result.slope, 1.0) + assert_ae(result.intercept, 5.0) + assert_ae(result.rvalue, 0.98229948625750) + assert_ae(result.pvalue, 7.45259691e-008) + assert_ae(result.stderr, 0.063564172616372733) + assert_ae(result.intercept_stderr, 0.37605071654517686) + + def test_regress_simple_negative_cor(self): + # If the slope of the regression is negative the factor R tend + # to -1 not 1. Sometimes rounding errors makes it < -1 + # leading to stderr being NaN. + a, n = 1e-71, 100000 + x = np.linspace(a, 2 * a, n) + y = np.linspace(2 * a, a, n) + result = stats.linregress(x, y) + + # Make sure propagated numerical errors + # did not bring rvalue below -1 (or were coerced) + assert_(result.rvalue >= -1) + assert_almost_equal(result.rvalue, -1) + + # slope and intercept stderror should stay numeric + assert_(not np.isnan(result.stderr)) + assert_(not np.isnan(result.intercept_stderr)) + + def test_linregress_result_attributes(self): + x = np.linspace(0, 100, 100) + y = 0.2 * np.linspace(0, 100, 100) + 10 + y += np.sin(np.linspace(0, 20, 100)) + result = stats.linregress(x, y) + + # Result is of a correct class + lr = LinregressResult + assert_(isinstance(result, lr)) + + # LinregressResult elements have correct names + attributes = ('slope', 'intercept', 'rvalue', 'pvalue', 'stderr') + check_named_results(result, attributes) + # Also check that the extra attribute (intercept_stderr) is present + assert 'intercept_stderr' in dir(result) + + def test_regress_two_inputs(self): + # Regress a simple line formed by two points. + x = np.arange(2) + y = np.arange(3, 5) + result = stats.linregress(x, y) + + # Non-horizontal line + assert_almost_equal(result.pvalue, 0.0) + + # Zero error through two points + assert_almost_equal(result.stderr, 0.0) + assert_almost_equal(result.intercept_stderr, 0.0) + + def test_regress_two_inputs_horizontal_line(self): + # Regress a horizontal line formed by two points. + x = np.arange(2) + y = np.ones(2) + result = stats.linregress(x, y) + + # Horizontal line + assert_almost_equal(result.pvalue, 1.0) + + # Zero error through two points + assert_almost_equal(result.stderr, 0.0) + assert_almost_equal(result.intercept_stderr, 0.0) + + def test_nist_norris(self): + # If this causes a lint failure in the future, please note the history of + # requests to allow extra whitespace in table formatting (e.g. gh-12367). + # Also see https://github.com/scipy/scipy/wiki/Why-do-we-not-use-an-auto%E2%80%90formatter%3F # noqa: E501 + x = [ 0.2, 337.4, 118.2, 884.6, 10.1, 226.5, + 666.3, 996.3, 448.6, 777.0, 558.2, 0.4, + 0.6, 775.5, 666.9, 338.0, 447.5, 11.6, + 556.0, 228.1, 995.8, 887.6, 120.2, 0.3, + 0.3, 556.8, 339.1, 887.2, 999.0, 779.0, + 11.1, 118.3, 229.2, 669.1, 448.9, 0.5] + + y = [ 0.1, 338.8, 118.1, 888.0, 9.2, 228.1, + 668.5, 998.5, 449.1, 778.9, 559.2, 0.3, + 0.1, 778.1, 668.8, 339.3, 448.9, 10.8, + 557.7, 228.3, 998.0, 888.8, 119.6, 0.3, + 0.6, 557.6, 339.3, 888.0, 998.5, 778.9, + 10.2, 117.6, 228.9, 668.4, 449.2, 0.2] + + result = stats.linregress(x, y) + + assert_almost_equal(result.slope, 1.00211681802045) + assert_almost_equal(result.intercept, -0.262323073774029) + assert_almost_equal(result.rvalue**2, 0.999993745883712) + assert_almost_equal(result.pvalue, 0.0) + assert_almost_equal(result.stderr, 0.00042979684820) + assert_almost_equal(result.intercept_stderr, 0.23281823430153) + + def test_compare_to_polyfit(self): + x = np.linspace(0, 100, 100) + y = 0.2 * np.linspace(0, 100, 100) + 10 + y += np.sin(np.linspace(0, 20, 100)) + result = stats.linregress(x, y) + poly = np.polyfit(x, y, 1) # Fit 1st degree polynomial + + # Make sure linear regression slope and intercept + # match with results from numpy polyfit + assert_almost_equal(result.slope, poly[0]) + assert_almost_equal(result.intercept, poly[1]) + + def test_empty_input(self): + assert_raises(ValueError, stats.linregress, [], []) + + def test_nan_input(self): + x = np.arange(10.) + x[9] = np.nan + + with np.errstate(invalid="ignore"): + result = stats.linregress(x, x) + + # Make sure the result still comes back as `LinregressResult` + lr = LinregressResult + assert_(isinstance(result, lr)) + assert_array_equal(result, (np.nan,)*5) + assert_equal(result.intercept_stderr, np.nan) + + def test_identical_x(self): + x = np.zeros(10) + y = np.random.random(10) + msg = "Cannot calculate a linear regression" + with assert_raises(ValueError, match=msg): + stats.linregress(x, y) + + +def test_theilslopes(): + # Basic slope test. + slope, intercept, lower, upper = stats.theilslopes([0,1,1]) + assert_almost_equal(slope, 0.5) + assert_almost_equal(intercept, 0.5) + + msg = ("method must be either 'joint' or 'separate'." + "'joint_separate' is invalid.") + with pytest.raises(ValueError, match=msg): + stats.theilslopes([0, 1, 1], method='joint_separate') + + slope, intercept, lower, upper = stats.theilslopes([0, 1, 1], + method='joint') + assert_almost_equal(slope, 0.5) + assert_almost_equal(intercept, 0.0) + + # Test of confidence intervals. + x = [1, 2, 3, 4, 10, 12, 18] + y = [9, 15, 19, 20, 45, 55, 78] + slope, intercept, lower, upper = stats.theilslopes(y, x, 0.07, + method='separate') + assert_almost_equal(slope, 4) + assert_almost_equal(intercept, 4.0) + assert_almost_equal(upper, 4.38, decimal=2) + assert_almost_equal(lower, 3.71, decimal=2) + + slope, intercept, lower, upper = stats.theilslopes(y, x, 0.07, + method='joint') + assert_almost_equal(slope, 4) + assert_almost_equal(intercept, 6.0) + assert_almost_equal(upper, 4.38, decimal=2) + assert_almost_equal(lower, 3.71, decimal=2) + + +def test_cumfreq(): + x = [1, 4, 2, 1, 3, 1] + cumfreqs, lowlim, binsize, extrapoints = stats.cumfreq(x, numbins=4) + assert_array_almost_equal(cumfreqs, np.array([3., 4., 5., 6.])) + cumfreqs, lowlim, binsize, extrapoints = stats.cumfreq( + x, numbins=4, defaultreallimits=(1.5, 5)) + assert_(extrapoints == 3) + + # test for namedtuple attribute results + attributes = ('cumcount', 'lowerlimit', 'binsize', 'extrapoints') + res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5)) + check_named_results(res, attributes) + + +def test_relfreq(): + a = np.array([1, 4, 2, 1, 3, 1]) + relfreqs, lowlim, binsize, extrapoints = stats.relfreq(a, numbins=4) + assert_array_almost_equal(relfreqs, + array([0.5, 0.16666667, 0.16666667, 0.16666667])) + + # test for namedtuple attribute results + attributes = ('frequency', 'lowerlimit', 'binsize', 'extrapoints') + res = stats.relfreq(a, numbins=4) + check_named_results(res, attributes) + + # check array_like input is accepted + relfreqs2, lowlim, binsize, extrapoints = stats.relfreq([1, 4, 2, 1, 3, 1], + numbins=4) + assert_array_almost_equal(relfreqs, relfreqs2) + + +class TestScoreatpercentile: + def setup_method(self): + self.a1 = [3, 4, 5, 10, -3, -5, 6] + self.a2 = [3, -6, -2, 8, 7, 4, 2, 1] + self.a3 = [3., 4, 5, 10, -3, -5, -6, 7.0] + + def test_basic(self): + x = arange(8) * 0.5 + assert_equal(stats.scoreatpercentile(x, 0), 0.) + assert_equal(stats.scoreatpercentile(x, 100), 3.5) + assert_equal(stats.scoreatpercentile(x, 50), 1.75) + + def test_fraction(self): + scoreatperc = stats.scoreatpercentile + + # Test defaults + assert_equal(scoreatperc(list(range(10)), 50), 4.5) + assert_equal(scoreatperc(list(range(10)), 50, (2,7)), 4.5) + assert_equal(scoreatperc(list(range(100)), 50, limit=(1, 8)), 4.5) + assert_equal(scoreatperc(np.array([1, 10,100]), 50, (10,100)), 55) + assert_equal(scoreatperc(np.array([1, 10,100]), 50, (1,10)), 5.5) + + # explicitly specify interpolation_method 'fraction' (the default) + assert_equal(scoreatperc(list(range(10)), 50, interpolation_method='fraction'), + 4.5) + assert_equal(scoreatperc(list(range(10)), 50, limit=(2, 7), + interpolation_method='fraction'), + 4.5) + assert_equal(scoreatperc(list(range(100)), 50, limit=(1, 8), + interpolation_method='fraction'), + 4.5) + assert_equal(scoreatperc(np.array([1, 10,100]), 50, (10, 100), + interpolation_method='fraction'), + 55) + assert_equal(scoreatperc(np.array([1, 10,100]), 50, (1,10), + interpolation_method='fraction'), + 5.5) + + def test_lower_higher(self): + scoreatperc = stats.scoreatpercentile + + # interpolation_method 'lower'/'higher' + assert_equal(scoreatperc(list(range(10)), 50, + interpolation_method='lower'), 4) + assert_equal(scoreatperc(list(range(10)), 50, + interpolation_method='higher'), 5) + assert_equal(scoreatperc(list(range(10)), 50, (2,7), + interpolation_method='lower'), 4) + assert_equal(scoreatperc(list(range(10)), 50, limit=(2,7), + interpolation_method='higher'), 5) + assert_equal(scoreatperc(list(range(100)), 50, (1,8), + interpolation_method='lower'), 4) + assert_equal(scoreatperc(list(range(100)), 50, (1,8), + interpolation_method='higher'), 5) + assert_equal(scoreatperc(np.array([1, 10, 100]), 50, (10, 100), + interpolation_method='lower'), 10) + assert_equal(scoreatperc(np.array([1, 10, 100]), 50, limit=(10, 100), + interpolation_method='higher'), 100) + assert_equal(scoreatperc(np.array([1, 10, 100]), 50, (1, 10), + interpolation_method='lower'), 1) + assert_equal(scoreatperc(np.array([1, 10, 100]), 50, limit=(1, 10), + interpolation_method='higher'), 10) + + def test_sequence_per(self): + x = arange(8) * 0.5 + expected = np.array([0, 3.5, 1.75]) + res = stats.scoreatpercentile(x, [0, 100, 50]) + assert_allclose(res, expected) + assert_(isinstance(res, np.ndarray)) + # Test with ndarray. Regression test for gh-2861 + assert_allclose(stats.scoreatpercentile(x, np.array([0, 100, 50])), + expected) + # Also test combination of 2-D array, axis not None and array-like per + res2 = stats.scoreatpercentile(np.arange(12).reshape((3,4)), + np.array([0, 1, 100, 100]), axis=1) + expected2 = array([[0, 4, 8], + [0.03, 4.03, 8.03], + [3, 7, 11], + [3, 7, 11]]) + assert_allclose(res2, expected2) + + def test_axis(self): + scoreatperc = stats.scoreatpercentile + x = arange(12).reshape(3, 4) + + assert_equal(scoreatperc(x, (25, 50, 100)), [2.75, 5.5, 11.0]) + + r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]] + assert_equal(scoreatperc(x, (25, 50, 100), axis=0), r0) + + r1 = [[0.75, 4.75, 8.75], [1.5, 5.5, 9.5], [3, 7, 11]] + assert_equal(scoreatperc(x, (25, 50, 100), axis=1), r1) + + x = array([[1, 1, 1], + [1, 1, 1], + [4, 4, 3], + [1, 1, 1], + [1, 1, 1]]) + score = stats.scoreatpercentile(x, 50) + assert_equal(score.shape, ()) + assert_equal(score, 1.0) + score = stats.scoreatpercentile(x, 50, axis=0) + assert_equal(score.shape, (3,)) + assert_equal(score, [1, 1, 1]) + + def test_exception(self): + assert_raises(ValueError, stats.scoreatpercentile, [1, 2], 56, + interpolation_method='foobar') + assert_raises(ValueError, stats.scoreatpercentile, [1], 101) + assert_raises(ValueError, stats.scoreatpercentile, [1], -1) + + def test_empty(self): + assert_equal(stats.scoreatpercentile([], 50), np.nan) + assert_equal(stats.scoreatpercentile(np.array([[], []]), 50), np.nan) + assert_equal(stats.scoreatpercentile([], [50, 99]), [np.nan, np.nan]) + + +class TestMode: + + def test_empty(self): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + vals, counts = stats.mode([]) + assert_equal(vals, np.array([])) + assert_equal(counts, np.array([])) + + def test_scalar(self): + vals, counts = stats.mode(4.) + assert_equal(vals, np.array([4.])) + assert_equal(counts, np.array([1])) + + def test_basic(self): + data1 = [3, 5, 1, 10, 23, 3, 2, 6, 8, 6, 10, 6] + vals = stats.mode(data1) + assert_equal(vals[0], 6) + assert_equal(vals[1], 3) + + def test_axes(self): + data1 = [10, 10, 30, 40] + data2 = [10, 10, 10, 10] + data3 = [20, 10, 20, 20] + data4 = [30, 30, 30, 30] + data5 = [40, 30, 30, 30] + arr = np.array([data1, data2, data3, data4, data5]) + + vals = stats.mode(arr, axis=None, keepdims=True) + assert_equal(vals[0], np.array([[30]])) + assert_equal(vals[1], np.array([[8]])) + + vals = stats.mode(arr, axis=0, keepdims=True) + assert_equal(vals[0], np.array([[10, 10, 30, 30]])) + assert_equal(vals[1], np.array([[2, 3, 3, 2]])) + + vals = stats.mode(arr, axis=1, keepdims=True) + assert_equal(vals[0], np.array([[10], [10], [20], [30], [30]])) + assert_equal(vals[1], np.array([[2], [4], [3], [4], [3]])) + + @pytest.mark.parametrize('axis', np.arange(-4, 0)) + def test_negative_axes_gh_15375(self, axis): + np.random.seed(984213899) + a = np.random.rand(10, 11, 12, 13) + res0 = stats.mode(a, axis=a.ndim+axis) + res1 = stats.mode(a, axis=axis) + np.testing.assert_array_equal(res0, res1) + + def test_mode_result_attributes(self): + data1 = [3, 5, 1, 10, 23, 3, 2, 6, 8, 6, 10, 6] + data2 = [] + actual = stats.mode(data1) + attributes = ('mode', 'count') + check_named_results(actual, attributes) + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + actual2 = stats.mode(data2) + check_named_results(actual2, attributes) + + def test_mode_nan(self): + data1 = [3, np.nan, 5, 1, 10, 23, 3, 2, 6, 8, 6, 10, 6] + actual = stats.mode(data1) + assert_equal(actual, (6, 3)) + + actual = stats.mode(data1, nan_policy='omit') + assert_equal(actual, (6, 3)) + assert_raises(ValueError, stats.mode, data1, nan_policy='raise') + assert_raises(ValueError, stats.mode, data1, nan_policy='foobar') + + @pytest.mark.parametrize("data", [ + [3, 5, 1, 1, 3], + [3, np.nan, 5, 1, 1, 3], + [3, 5, 1], + [3, np.nan, 5, 1], + ]) + @pytest.mark.parametrize('keepdims', [False, True]) + def test_smallest_equal(self, data, keepdims): + result = stats.mode(data, nan_policy='omit', keepdims=keepdims) + if keepdims: + assert_equal(result[0][0], 1) + else: + assert_equal(result[0], 1) + + @pytest.mark.parametrize('axis', np.arange(-3, 3)) + def test_mode_shape_gh_9955(self, axis, dtype=np.float64): + rng = np.random.default_rng(984213899) + a = rng.uniform(size=(3, 4, 5)).astype(dtype) + res = stats.mode(a, axis=axis, keepdims=False) + reference_shape = list(a.shape) + reference_shape.pop(axis) + np.testing.assert_array_equal(res.mode.shape, reference_shape) + np.testing.assert_array_equal(res.count.shape, reference_shape) + + def test_nan_policy_propagate_gh_9815(self): + # mode should treat np.nan as it would any other object when + # nan_policy='propagate' + a = [2, np.nan, 1, np.nan] + res = stats.mode(a) + assert np.isnan(res.mode) and res.count == 2 + + def test_keepdims(self): + # test empty arrays (handled by `np.mean`) + a = np.zeros((1, 2, 3, 0)) + + res = stats.mode(a, axis=1, keepdims=False) + assert res.mode.shape == res.count.shape == (1, 3, 0) + + res = stats.mode(a, axis=1, keepdims=True) + assert res.mode.shape == res.count.shape == (1, 1, 3, 0) + + # test nan_policy='propagate' + a = [[1, 3, 3, np.nan], [1, 1, np.nan, 1]] + + res = stats.mode(a, axis=1, keepdims=False) + assert_array_equal(res.mode, [3, 1]) + assert_array_equal(res.count, [2, 3]) + + res = stats.mode(a, axis=1, keepdims=True) + assert_array_equal(res.mode, [[3], [1]]) + assert_array_equal(res.count, [[2], [3]]) + + a = np.array(a) + res = stats.mode(a, axis=None, keepdims=False) + ref = stats.mode(a.ravel(), keepdims=False) + assert_array_equal(res, ref) + assert res.mode.shape == ref.mode.shape == () + + res = stats.mode(a, axis=None, keepdims=True) + ref = stats.mode(a.ravel(), keepdims=True) + assert_equal(res.mode.ravel(), ref.mode.ravel()) + assert res.mode.shape == (1, 1) + assert_equal(res.count.ravel(), ref.count.ravel()) + assert res.count.shape == (1, 1) + + # test nan_policy='omit' + a = [[1, np.nan, np.nan, np.nan, 1], + [np.nan, np.nan, np.nan, np.nan, 2], + [1, 2, np.nan, 5, 5]] + + res = stats.mode(a, axis=1, keepdims=False, nan_policy='omit') + assert_array_equal(res.mode, [1, 2, 5]) + assert_array_equal(res.count, [2, 1, 2]) + + res = stats.mode(a, axis=1, keepdims=True, nan_policy='omit') + assert_array_equal(res.mode, [[1], [2], [5]]) + assert_array_equal(res.count, [[2], [1], [2]]) + + a = np.array(a) + res = stats.mode(a, axis=None, keepdims=False, nan_policy='omit') + ref = stats.mode(a.ravel(), keepdims=False, nan_policy='omit') + assert_array_equal(res, ref) + assert res.mode.shape == ref.mode.shape == () + + res = stats.mode(a, axis=None, keepdims=True, nan_policy='omit') + ref = stats.mode(a.ravel(), keepdims=True, nan_policy='omit') + assert_equal(res.mode.ravel(), ref.mode.ravel()) + assert res.mode.shape == (1, 1) + assert_equal(res.count.ravel(), ref.count.ravel()) + assert res.count.shape == (1, 1) + + @pytest.mark.parametrize("nan_policy", ['propagate', 'omit']) + def test_gh16955(self, nan_policy): + # Check that bug reported in gh-16955 is resolved + shape = (4, 3) + data = np.ones(shape) + data[0, 0] = np.nan + res = stats.mode(a=data, axis=1, keepdims=False, nan_policy=nan_policy) + assert_array_equal(res.mode, [1, 1, 1, 1]) + assert_array_equal(res.count, [2, 3, 3, 3]) + + # Test with input from gh-16595. Support for non-numeric input + # was deprecated, so check for the appropriate error. + my_dtype = np.dtype([('asdf', np.uint8), ('qwer', np.float64, (3,))]) + test = np.zeros(10, dtype=my_dtype) + message = "Argument `a` is not....|An argument has dtype..." + with pytest.raises(TypeError, match=message): + stats.mode(test, nan_policy=nan_policy) + + def test_gh9955(self): + # The behavior of mode with empty slices (whether the input was empty + # or all elements were omitted) was inconsistent. Test that this is + # resolved: the mode of an empty slice is NaN and the count is zero. + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.mode([]) + ref = (np.nan, 0) + assert_equal(res, ref) + + with pytest.warns(SmallSampleWarning, match=too_small_1d_omit): + res = stats.mode([np.nan], nan_policy='omit') + assert_equal(res, ref) + + a = [[10., 20., 20.], [np.nan, np.nan, np.nan]] + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + res = stats.mode(a, axis=1, nan_policy='omit') + ref = ([20, np.nan], [2, 0]) + assert_equal(res, ref) + + res = stats.mode(a, axis=1, nan_policy='propagate') + ref = ([20, np.nan], [2, 3]) + assert_equal(res, ref) + + z = np.array([[], []]) + with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit): + res = stats.mode(z, axis=1) + ref = ([np.nan, np.nan], [0, 0]) + assert_equal(res, ref) + + @pytest.mark.filterwarnings('ignore::RuntimeWarning') # np.mean warns + @pytest.mark.parametrize('z', [np.empty((0, 1, 2)), np.empty((1, 1, 2))]) + def test_gh17214(self, z): + if z.size == 0: + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.mode(z, axis=None, keepdims=True) + else: + res = stats.mode(z, axis=None, keepdims=True) + ref = np.mean(z, axis=None, keepdims=True) + assert res[0].shape == res[1].shape == ref.shape == (1, 1, 1) + + def test_raise_non_numeric_gh18254(self): + message = ("...only boolean and numerical dtypes..." if SCIPY_ARRAY_API + else "Argument `a` is not recognized as numeric.") + + class ArrLike: + def __init__(self, x): + self._x = x + + def __array__(self, dtype=None, copy=None): + return self._x.astype(object) + + with pytest.raises(TypeError, match=message): + stats.mode(ArrLike(np.arange(3))) + with pytest.raises(TypeError, match=message): + stats.mode(np.arange(3, dtype=object)) + + +@array_api_compatible +class TestSEM: + + testcase = [1., 2., 3., 4.] + scalar_testcase = 4. + + def test_sem_scalar(self, xp): + # This is not in R, so used: + # sqrt(var(testcase)*3/4)/sqrt(3) + + # y = stats.sem(self.shoes[0]) + # assert_approx_equal(y,0.775177399) + scalar_testcase = xp.asarray(self.scalar_testcase)[()] + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + y = stats.sem(scalar_testcase) + else: + # Other array types can emit a variety of warnings. + with np.testing.suppress_warnings() as sup: + sup.filter(UserWarning) + sup.filter(RuntimeWarning) + y = stats.sem(scalar_testcase) + assert xp.isnan(y) + + def test_sem(self, xp): + testcase = xp.asarray(self.testcase) + y = stats.sem(testcase) + xp_assert_close(y, xp.asarray(0.6454972244)) + n = len(self.testcase) + xp_assert_close(stats.sem(testcase, ddof=0) * (n/(n-2))**0.5, + stats.sem(testcase, ddof=2)) + + x = xp.arange(10.) + x = xp.where(x == 9, xp.asarray(xp.nan), x) + xp_assert_equal(stats.sem(x), xp.asarray(xp.nan)) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_sem_nan_policy(self, xp): + x = np.arange(10.) + x[9] = np.nan + assert_equal(stats.sem(x, nan_policy='omit'), 0.9128709291752769) + assert_raises(ValueError, stats.sem, x, nan_policy='raise') + assert_raises(ValueError, stats.sem, x, nan_policy='foobar') + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +@skip_xp_backends('jax.numpy', reason="JAX can't do item assignment") +class TestZmapZscore: + + @pytest.mark.parametrize( + 'x, y', + [([1., 2., 3., 4.], [1., 2., 3., 4.]), + ([1., 2., 3.], [0., 1., 2., 3., 4.])] + ) + def test_zmap(self, x, y, xp): + # For these simple cases, calculate the expected result directly + # by using the formula for the z-score. + x, y = xp.asarray(x), xp.asarray(y) + xp_test = array_namespace(x, y) # std needs correction + expected = (x - xp.mean(y)) / xp_test.std(y, correction=0) + z = stats.zmap(x, y) + xp_assert_close(z, expected) + + def test_zmap_axis(self, xp): + # Test use of 'axis' keyword in zmap. + x = np.array([[0.0, 0.0, 1.0, 1.0], + [1.0, 1.0, 1.0, 2.0], + [2.0, 0.0, 2.0, 0.0]]) + + t1 = 1.0/(2.0/3)**0.5 + t2 = 3.**0.5/3 + t3 = 2.**0.5 + + z0 = stats.zmap(x, x, axis=0) + z1 = stats.zmap(x, x, axis=1) + + z0_expected = [[-t1, -t3/2, -t3/2, 0.0], + [0.0, t3, -t3/2, t1], + [t1, -t3/2, t3, -t1]] + z1_expected = [[-1.0, -1.0, 1.0, 1.0], + [-t2, -t2, -t2, 3.**0.5], + [1.0, -1.0, 1.0, -1.0]] + + xp_assert_close(z0, z0_expected) + xp_assert_close(z1, z1_expected) + + def test_zmap_ddof(self, xp): + # Test use of 'ddof' keyword in zmap. + x = xp.asarray([[0.0, 0.0, 1.0, 1.0], + [0.0, 1.0, 2.0, 3.0]]) + + z = stats.zmap(x, x, axis=1, ddof=1) + + z0_expected = xp.asarray([-0.5, -0.5, 0.5, 0.5])/(1.0/3**0.5) + z1_expected = xp.asarray([-1.5, -0.5, 0.5, 1.5])/(5./3)**0.5 + xp_assert_close(z[0, :], z0_expected) + xp_assert_close(z[1, :], z1_expected) + + @pytest.mark.parametrize('ddof', [0, 2]) + def test_zmap_nan_policy_omit(self, ddof, xp): + # nans in `scores` are propagated, regardless of `nan_policy`. + # `nan_policy` only affects how nans in `compare` are handled. + scores = xp.asarray([-3, -1, 2, np.nan]) + compare = xp.asarray([-8, -3, 2, 7, 12, np.nan]) + z = stats.zmap(scores, compare, ddof=ddof, nan_policy='omit') + ref = stats.zmap(scores, compare[~xp.isnan(compare)], ddof=ddof) + xp_assert_close(z, ref) + + @pytest.mark.parametrize('ddof', [0, 2]) + def test_zmap_nan_policy_omit_with_axis(self, ddof, xp): + scores = xp.reshape(xp.arange(-5.0, 9.0), (2, -1)) + compare = xp.reshape(xp.linspace(-8, 6, 24), (2, -1)) + compare[0, 4] = xp.nan + compare[0, 6] = xp.nan + compare[1, 1] = xp.nan + z = stats.zmap(scores, compare, nan_policy='omit', axis=1, ddof=ddof) + res0 = stats.zmap(scores[0, :], compare[0, :][~xp.isnan(compare[0, :])], + ddof=ddof) + res1 = stats.zmap(scores[1, :], compare[1, :][~xp.isnan(compare[1, :])], + ddof=ddof) + expected = xp.stack((res0, res1)) + xp_assert_close(z, expected) + + def test_zmap_nan_policy_raise(self, xp): + scores = xp.asarray([1, 2, 3]) + compare = xp.asarray([-8, -3, 2, 7, 12, xp.nan]) + with pytest.raises(ValueError, match='input contains nan'): + stats.zmap(scores, compare, nan_policy='raise') + + def test_zscore(self, xp): + # not in R, so tested by using: + # (testcase[i] - mean(testcase, axis=0)) / sqrt(var(testcase) * 3/4) + y = stats.zscore(xp.asarray([1, 2, 3, 4])) + desired = [-1.3416407864999, -0.44721359549996, + 0.44721359549996, 1.3416407864999] + xp_assert_close(y, xp.asarray(desired)) + + def test_zscore_axis(self, xp): + # Test use of 'axis' keyword in zscore. + x = xp.asarray([[0.0, 0.0, 1.0, 1.0], + [1.0, 1.0, 1.0, 2.0], + [2.0, 0.0, 2.0, 0.0]]) + + t1 = 1.0/(2.0/3)**0.5 + t2 = 3**0.5/3 + t3 = 2**0.5 + + z0 = stats.zscore(x, axis=0) + z1 = stats.zscore(x, axis=1) + + z0_expected = [[-t1, -t3/2, -t3/2, 0.0], + [0.0, t3, -t3/2, t1], + [t1, -t3/2, t3, -t1]] + z1_expected = [[-1.0, -1.0, 1.0, 1.0], + [-t2, -t2, -t2, 3**0.5], + [1.0, -1.0, 1.0, -1.0]] + + xp_assert_close(z0, xp.asarray(z0_expected)) + xp_assert_close(z1, xp.asarray(z1_expected)) + + def test_zscore_ddof(self, xp): + # Test use of 'ddof' keyword in zscore. + x = xp.asarray([[0.0, 0.0, 1.0, 1.0], + [0.0, 1.0, 2.0, 3.0]]) + + z = stats.zscore(x, axis=1, ddof=1) + + z0_expected = xp.asarray([-0.5, -0.5, 0.5, 0.5])/(1.0/3**0.5) + z1_expected = xp.asarray([-1.5, -0.5, 0.5, 1.5])/((5./3)**0.5) + xp_assert_close(z[0, :], z0_expected) + xp_assert_close(z[1, :], z1_expected) + + @skip_xp_backends('cupy', reason="cupy/cupy#8391") + def test_zscore_nan_propagate(self, xp): + x = xp.asarray([1, 2, np.nan, 4, 5]) + z = stats.zscore(x, nan_policy='propagate') + xp_assert_equal(z, xp.full(x.shape, xp.nan)) + + def test_zscore_nan_omit(self, xp): + x = xp.asarray([1, 2, xp.nan, 4, 5]) + + z = stats.zscore(x, nan_policy='omit') + + expected = xp.asarray([-1.2649110640673518, + -0.6324555320336759, + xp.nan, + 0.6324555320336759, + 1.2649110640673518 + ]) + xp_assert_close(z, expected) + + def test_zscore_nan_omit_with_ddof(self, xp): + x = xp.asarray([xp.nan, 1.0, 3.0, 5.0, 7.0, 9.0]) + xp_test = array_namespace(x) # numpy needs concat + z = stats.zscore(x, ddof=1, nan_policy='omit') + expected = xp_test.concat([xp.asarray([xp.nan]), stats.zscore(x[1:], ddof=1)]) + xp_assert_close(z, expected) + + def test_zscore_nan_raise(self, xp): + x = xp.asarray([1, 2, xp.nan, 4, 5]) + with pytest.raises(ValueError, match="The input contains nan..."): + stats.zscore(x, nan_policy='raise') + + @skip_xp_backends('cupy', reason="cupy/cupy#8391") + def test_zscore_constant_input_1d(self, xp): + x = xp.asarray([-0.087] * 3) + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + z = stats.zscore(x) + xp_assert_equal(z, xp.full(x.shape, xp.nan)) + + def test_zscore_constant_input_2d(self, xp): + x = xp.asarray([[10.0, 10.0, 10.0, 10.0], + [10.0, 11.0, 12.0, 13.0]]) + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + z0 = stats.zscore(x, axis=0) + xp_assert_close(z0, xp.asarray([[xp.nan, -1.0, -1.0, -1.0], + [xp.nan, 1.0, 1.0, 1.0]])) + + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + z1 = stats.zscore(x, axis=1) + xp_assert_equal(z1, xp.stack([xp.asarray([xp.nan, xp.nan, xp.nan, xp.nan]), + stats.zscore(x[1, :])])) + + z = stats.zscore(x, axis=None) + xp_assert_equal(z, xp.reshape(stats.zscore(xp.reshape(x, (-1,))), x.shape)) + + y = xp.ones((3, 6)) + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + z = stats.zscore(y, axis=None) + xp_assert_equal(z, xp.full(y.shape, xp.asarray(xp.nan))) + + def test_zscore_constant_input_2d_nan_policy_omit(self, xp): + x = xp.asarray([[10.0, 10.0, 10.0, 10.0], + [10.0, 11.0, 12.0, xp.nan], + [10.0, 12.0, xp.nan, 10.0]]) + s = (3/2)**0.5 + s2 = 2**0.5 + + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + z0 = stats.zscore(x, nan_policy='omit', axis=0) + xp_assert_close(z0, xp.asarray([[xp.nan, -s, -1.0, xp.nan], + [xp.nan, 0, 1.0, xp.nan], + [xp.nan, s, xp.nan, xp.nan]])) + + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + z1 = stats.zscore(x, nan_policy='omit', axis=1) + xp_assert_close(z1, xp.asarray([[xp.nan, xp.nan, xp.nan, xp.nan], + [-s, 0, s, xp.nan], + [-s2/2, s2, xp.nan, -s2/2]])) + + def test_zscore_2d_all_nan_row(self, xp): + # A row is all nan, and we use axis=1. + x = xp.asarray([[np.nan, np.nan, np.nan, np.nan], + [10.0, 10.0, 12.0, 12.0]]) + z = stats.zscore(x, nan_policy='omit', axis=1) + xp_assert_close(z, xp.asarray([[np.nan, np.nan, np.nan, np.nan], + [-1.0, -1.0, 1.0, 1.0]])) + + @skip_xp_backends('cupy', reason="cupy/cupy#8391") + def test_zscore_2d_all_nan(self, xp): + # The entire 2d array is nan, and we use axis=None. + y = xp.full((2, 3), xp.nan) + z = stats.zscore(y, nan_policy='omit', axis=None) + xp_assert_equal(z, y) + + @pytest.mark.parametrize('x', [np.array([]), np.zeros((3, 0, 5))]) + def test_zscore_empty_input(self, x, xp): + x = xp.asarray(x) + z = stats.zscore(x) + xp_assert_equal(z, x) + + def test_gzscore_normal_array(self, xp): + x = np.asarray([1, 2, 3, 4]) + z = stats.gzscore(xp.asarray(x)) + desired = np.log(x / stats.gmean(x)) / np.log(stats.gstd(x, ddof=0)) + xp_assert_close(z, xp.asarray(desired, dtype=xp.asarray(1.).dtype)) + + @skip_xp_invalid_arg + def test_gzscore_masked_array(self, xp): + x = np.array([1, 2, -1, 3, 4]) + mask = [0, 0, 1, 0, 0] + mx = np.ma.masked_array(x, mask=mask) + z = stats.gzscore(mx) + desired = ([-1.526072095151, -0.194700599824, np.inf, 0.584101799472, + 1.136670895503]) + desired = np.ma.masked_array(desired, mask=mask) + assert_allclose(z.compressed(), desired.compressed()) + assert_allclose(z.mask, desired.mask) + assert isinstance(z, np.ma.MaskedArray) + + @skip_xp_invalid_arg + def test_zscore_masked_element_0_gh19039(self, xp): + # zscore returned all NaNs when 0th element was masked. See gh-19039. + rng = np.random.default_rng(8675309) + x = rng.standard_normal(10) + mask = np.zeros_like(x) + y = np.ma.masked_array(x, mask) + y.mask[0] = True + + ref = stats.zscore(x[1:]) # compute reference from non-masked elements + assert not np.any(np.isnan(ref)) + res = stats.zscore(y) + assert_allclose(res[1:], ref) + res = stats.zscore(y, axis=None) + assert_allclose(res[1:], ref) + + y[1:] = y[1] # when non-masked elements are identical, result is nan + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + res = stats.zscore(y) + assert_equal(res[1:], np.nan) + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + res = stats.zscore(y, axis=None) + assert_equal(res[1:], np.nan) + + def test_degenerate_input(self, xp): + scores = xp.arange(3) + compare = xp.ones(3) + ref = xp.asarray([-xp.inf, xp.nan, xp.inf]) + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + res = stats.zmap(scores, compare) + xp_assert_equal(res, ref) + + @pytest.mark.skip_xp_backends('array_api_strict', reason='needs array-api#850') + def test_complex_gh22404(self, xp): + res = stats.zmap(xp.asarray([1, 2, 3, 4]), xp.asarray([1, 1j, -1, -1j])) + ref = xp.asarray([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j]) + xp_assert_close(res, ref) + + +class TestMedianAbsDeviation: + def setup_class(self): + self.dat_nan = np.array([2.20, 2.20, 2.4, 2.4, 2.5, 2.7, 2.8, 2.9, + 3.03, 3.03, 3.10, 3.37, 3.4, 3.4, 3.4, 3.5, + 3.6, 3.7, 3.7, 3.7, 3.7, 3.77, 5.28, np.nan]) + self.dat = np.array([2.20, 2.20, 2.4, 2.4, 2.5, 2.7, 2.8, 2.9, 3.03, + 3.03, 3.10, 3.37, 3.4, 3.4, 3.4, 3.5, 3.6, 3.7, + 3.7, 3.7, 3.7, 3.77, 5.28, 28.95]) + + def test_median_abs_deviation(self): + assert_almost_equal(stats.median_abs_deviation(self.dat, axis=None), + 0.355) + dat = self.dat.reshape(6, 4) + mad = stats.median_abs_deviation(dat, axis=0) + mad_expected = np.asarray([0.435, 0.5, 0.45, 0.4]) + assert_array_almost_equal(mad, mad_expected) + + def test_mad_nan_omit(self): + mad = stats.median_abs_deviation(self.dat_nan, nan_policy='omit') + assert_almost_equal(mad, 0.34) + + def test_axis_and_nan(self): + x = np.array([[1.0, 2.0, 3.0, 4.0, np.nan], + [1.0, 4.0, 5.0, 8.0, 9.0]]) + mad = stats.median_abs_deviation(x, axis=1) + assert_equal(mad, np.array([np.nan, 3.0])) + + def test_nan_policy_omit_with_inf(self): + z = np.array([1, 3, 4, 6, 99, np.nan, np.inf]) + mad = stats.median_abs_deviation(z, nan_policy='omit') + assert_equal(mad, 3.0) + + @pytest.mark.parametrize('axis', [0, 1, 2, None]) + def test_size_zero_with_axis(self, axis): + x = np.zeros((3, 0, 4)) + mad = stats.median_abs_deviation(x, axis=axis) + assert_equal(mad, np.full_like(x.sum(axis=axis), fill_value=np.nan)) + + @pytest.mark.parametrize('nan_policy, expected', + [('omit', np.array([np.nan, 1.5, 1.5])), + ('propagate', np.array([np.nan, np.nan, 1.5]))]) + def test_nan_policy_with_axis(self, nan_policy, expected): + x = np.array([[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + [1, 5, 3, 6, np.nan, np.nan], + [5, 6, 7, 9, 9, 10]]) + mad = stats.median_abs_deviation(x, nan_policy=nan_policy, axis=1) + assert_equal(mad, expected) + + @pytest.mark.parametrize('axis, expected', + [(1, [2.5, 2.0, 12.0]), (None, 4.5)]) + def test_center_mean_with_nan(self, axis, expected): + x = np.array([[1, 2, 4, 9, np.nan], + [0, 1, 1, 1, 12], + [-10, -10, -10, 20, 20]]) + mad = stats.median_abs_deviation(x, center=np.mean, nan_policy='omit', + axis=axis) + assert_allclose(mad, expected, rtol=1e-15, atol=1e-15) + + def test_center_not_callable(self): + with pytest.raises(TypeError, match='callable'): + stats.median_abs_deviation([1, 2, 3, 5], center=99) + + +def _check_warnings(warn_list, expected_type, expected_len): + """ + Checks that all of the warnings from a list returned by + `warnings.catch_all(record=True)` are of the required type and that the list + contains expected number of warnings. + """ + assert_equal(len(warn_list), expected_len, "number of warnings") + for warn_ in warn_list: + assert_(warn_.category is expected_type) + + +class TestIQR: + + def test_basic(self): + x = np.arange(8) * 0.5 + np.random.shuffle(x) + assert_equal(stats.iqr(x), 1.75) + + def test_api(self): + d = np.ones((5, 5)) + stats.iqr(d) + stats.iqr(d, None) + stats.iqr(d, 1) + stats.iqr(d, (0, 1)) + stats.iqr(d, None, (10, 90)) + stats.iqr(d, None, (30, 20), 1.0) + stats.iqr(d, None, (25, 75), 1.5, 'propagate') + stats.iqr(d, None, (50, 50), 'normal', 'raise', 'linear') + stats.iqr(d, None, (25, 75), -0.4, 'omit', 'lower', True) + + @pytest.mark.parametrize('x', [[], np.arange(0)]) + def test_empty(self, x): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + assert_equal(stats.iqr(x), np.nan) + + def test_constant(self): + # Constant array always gives 0 + x = np.ones((7, 4)) + assert_equal(stats.iqr(x), 0.0) + assert_array_equal(stats.iqr(x, axis=0), np.zeros(4)) + assert_array_equal(stats.iqr(x, axis=1), np.zeros(7)) + assert_equal(stats.iqr(x, interpolation='linear'), 0.0) + assert_equal(stats.iqr(x, interpolation='midpoint'), 0.0) + assert_equal(stats.iqr(x, interpolation='nearest'), 0.0) + assert_equal(stats.iqr(x, interpolation='lower'), 0.0) + assert_equal(stats.iqr(x, interpolation='higher'), 0.0) + + # 0 only along constant dimensions + # This also tests much of `axis` + y = np.ones((4, 5, 6)) * np.arange(6) + assert_array_equal(stats.iqr(y, axis=0), np.zeros((5, 6))) + assert_array_equal(stats.iqr(y, axis=1), np.zeros((4, 6))) + assert_array_equal(stats.iqr(y, axis=2), np.full((4, 5), 2.5)) + assert_array_equal(stats.iqr(y, axis=(0, 1)), np.zeros(6)) + assert_array_equal(stats.iqr(y, axis=(0, 2)), np.full(5, 3.)) + assert_array_equal(stats.iqr(y, axis=(1, 2)), np.full(4, 3.)) + + def test_scalarlike(self): + x = np.arange(1) + 7.0 + assert_equal(stats.iqr(x[0]), 0.0) + assert_equal(stats.iqr(x), 0.0) + assert_array_equal(stats.iqr(x, keepdims=True), [0.0]) + + def test_2D(self): + x = np.arange(15).reshape((3, 5)) + assert_equal(stats.iqr(x), 7.0) + assert_array_equal(stats.iqr(x, axis=0), np.full(5, 5.)) + assert_array_equal(stats.iqr(x, axis=1), np.full(3, 2.)) + assert_array_equal(stats.iqr(x, axis=(0, 1)), 7.0) + assert_array_equal(stats.iqr(x, axis=(1, 0)), 7.0) + + def test_axis(self): + # The `axis` keyword is also put through its paces in `test_keepdims`. + o = np.random.normal(size=(71, 23)) + x = np.dstack([o] * 10) # x.shape = (71, 23, 10) + q = stats.iqr(o) + + assert_equal(stats.iqr(x, axis=(0, 1)), q) + x = np.moveaxis(x, -1, 0) # x.shape = (10, 71, 23) + assert_equal(stats.iqr(x, axis=(2, 1)), q) + x = x.swapaxes(0, 1) # x.shape = (71, 10, 23) + assert_equal(stats.iqr(x, axis=(0, 2)), q) + x = x.swapaxes(0, 1) # x.shape = (10, 71, 23) + + assert_equal(stats.iqr(x, axis=(0, 1, 2)), + stats.iqr(x, axis=None)) + assert_equal(stats.iqr(x, axis=(0,)), + stats.iqr(x, axis=0)) + + d = np.arange(3 * 5 * 7 * 11) + # Older versions of numpy only shuffle along axis=0. + # Not sure about newer, don't care. + np.random.shuffle(d) + d = d.reshape((3, 5, 7, 11)) + assert_equal(stats.iqr(d, axis=(0, 1, 2))[0], + stats.iqr(d[:,:,:, 0].ravel())) + assert_equal(stats.iqr(d, axis=(0, 1, 3))[1], + stats.iqr(d[:,:, 1,:].ravel())) + assert_equal(stats.iqr(d, axis=(3, 1, -4))[2], + stats.iqr(d[:,:, 2,:].ravel())) + assert_equal(stats.iqr(d, axis=(3, 1, 2))[2], + stats.iqr(d[2,:,:,:].ravel())) + assert_equal(stats.iqr(d, axis=(3, 2))[2, 1], + stats.iqr(d[2, 1,:,:].ravel())) + assert_equal(stats.iqr(d, axis=(1, -2))[2, 1], + stats.iqr(d[2, :, :, 1].ravel())) + assert_equal(stats.iqr(d, axis=(1, 3))[2, 2], + stats.iqr(d[2, :, 2,:].ravel())) + + assert_raises(AxisError, stats.iqr, d, axis=4) + assert_raises(ValueError, stats.iqr, d, axis=(0, 0)) + + def test_rng(self): + x = np.arange(5) + assert_equal(stats.iqr(x), 2) + assert_equal(stats.iqr(x, rng=(25, 87.5)), 2.5) + assert_equal(stats.iqr(x, rng=(12.5, 75)), 2.5) + assert_almost_equal(stats.iqr(x, rng=(10, 50)), 1.6) # 3-1.4 + + assert_raises(ValueError, stats.iqr, x, rng=(0, 101)) + assert_raises(ValueError, stats.iqr, x, rng=(np.nan, 25)) + assert_raises(TypeError, stats.iqr, x, rng=(0, 50, 60)) + + def test_interpolation(self): + x = np.arange(5) + y = np.arange(4) + # Default + assert_equal(stats.iqr(x), 2) + assert_equal(stats.iqr(y), 1.5) + # Linear + assert_equal(stats.iqr(x, interpolation='linear'), 2) + assert_equal(stats.iqr(y, interpolation='linear'), 1.5) + # Higher + assert_equal(stats.iqr(x, interpolation='higher'), 2) + assert_equal(stats.iqr(x, rng=(25, 80), interpolation='higher'), 3) + assert_equal(stats.iqr(y, interpolation='higher'), 2) + # Lower (will generally, but not always be the same as higher) + assert_equal(stats.iqr(x, interpolation='lower'), 2) + assert_equal(stats.iqr(x, rng=(25, 80), interpolation='lower'), 2) + assert_equal(stats.iqr(y, interpolation='lower'), 2) + # Nearest + assert_equal(stats.iqr(x, interpolation='nearest'), 2) + assert_equal(stats.iqr(y, interpolation='nearest'), 1) + # Midpoint + assert_equal(stats.iqr(x, interpolation='midpoint'), 2) + assert_equal(stats.iqr(x, rng=(25, 80), interpolation='midpoint'), 2.5) + assert_equal(stats.iqr(y, interpolation='midpoint'), 2) + + # Check all method= values new in numpy 1.22.0 are accepted + for method in ('inverted_cdf', 'averaged_inverted_cdf', + 'closest_observation', 'interpolated_inverted_cdf', + 'hazen', 'weibull', 'median_unbiased', + 'normal_unbiased'): + stats.iqr(y, interpolation=method) + + assert_raises(ValueError, stats.iqr, x, interpolation='foobar') + + def test_keepdims(self): + # Also tests most of `axis` + x = np.ones((3, 5, 7, 11)) + assert_equal(stats.iqr(x, axis=None, keepdims=False).shape, ()) + assert_equal(stats.iqr(x, axis=2, keepdims=False).shape, (3, 5, 11)) + assert_equal(stats.iqr(x, axis=(0, 1), keepdims=False).shape, (7, 11)) + assert_equal(stats.iqr(x, axis=(0, 3), keepdims=False).shape, (5, 7)) + assert_equal(stats.iqr(x, axis=(1,), keepdims=False).shape, (3, 7, 11)) + assert_equal(stats.iqr(x, (0, 1, 2, 3), keepdims=False).shape, ()) + assert_equal(stats.iqr(x, axis=(0, 1, 3), keepdims=False).shape, (7,)) + + assert_equal(stats.iqr(x, axis=None, keepdims=True).shape, (1, 1, 1, 1)) + assert_equal(stats.iqr(x, axis=2, keepdims=True).shape, (3, 5, 1, 11)) + assert_equal(stats.iqr(x, axis=(0, 1), keepdims=True).shape, (1, 1, 7, 11)) + assert_equal(stats.iqr(x, axis=(0, 3), keepdims=True).shape, (1, 5, 7, 1)) + assert_equal(stats.iqr(x, axis=(1,), keepdims=True).shape, (3, 1, 7, 11)) + assert_equal(stats.iqr(x, (0, 1, 2, 3), keepdims=True).shape, (1, 1, 1, 1)) + assert_equal(stats.iqr(x, axis=(0, 1, 3), keepdims=True).shape, (1, 1, 7, 1)) + + def test_nanpolicy(self): + x = np.arange(15.0).reshape((3, 5)) + + # No NaNs + assert_equal(stats.iqr(x, nan_policy='propagate'), 7) + assert_equal(stats.iqr(x, nan_policy='omit'), 7) + assert_equal(stats.iqr(x, nan_policy='raise'), 7) + + # Yes NaNs + x[1, 2] = np.nan + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + assert_equal(stats.iqr(x, nan_policy='propagate'), + np.nan) + assert_equal(stats.iqr(x, axis=0, nan_policy='propagate'), + [5, 5, np.nan, 5, 5]) + assert_equal(stats.iqr(x, axis=1, nan_policy='propagate'), + [2, np.nan, 2]) + + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + assert_equal(stats.iqr(x, nan_policy='omit'), 7.5) + assert_equal(stats.iqr(x, axis=0, nan_policy='omit'), np.full(5, 5)) + assert_equal(stats.iqr(x, axis=1, nan_policy='omit'), [2, 2.5, 2]) + + assert_raises(ValueError, stats.iqr, x, nan_policy='raise') + assert_raises(ValueError, stats.iqr, x, axis=0, nan_policy='raise') + assert_raises(ValueError, stats.iqr, x, axis=1, nan_policy='raise') + + # Bad policy + assert_raises(ValueError, stats.iqr, x, nan_policy='barfood') + + def test_scale(self): + x = np.arange(15.0).reshape((3, 5)) + + # No NaNs + assert_equal(stats.iqr(x, scale=1.0), 7) + assert_almost_equal(stats.iqr(x, scale='normal'), 7 / 1.3489795) + assert_equal(stats.iqr(x, scale=2.0), 3.5) + + # Yes NaNs + x[1, 2] = np.nan + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + assert_equal(stats.iqr(x, scale=1.0, nan_policy='propagate'), np.nan) + assert_equal(stats.iqr(x, scale='normal', nan_policy='propagate'), np.nan) + assert_equal(stats.iqr(x, scale=2.0, nan_policy='propagate'), np.nan) + # axis=1 chosen to show behavior with both nans and without + assert_equal(stats.iqr(x, axis=1, scale=1.0, + nan_policy='propagate'), [2, np.nan, 2]) + assert_almost_equal(stats.iqr(x, axis=1, scale='normal', + nan_policy='propagate'), + np.array([2, np.nan, 2]) / 1.3489795) + assert_equal(stats.iqr(x, axis=1, scale=2.0, nan_policy='propagate'), + [1, np.nan, 1]) + # Since NumPy 1.17.0.dev, warnings are no longer emitted by + # np.percentile with nans, so we don't check the number of + # warnings here. See https://github.com/numpy/numpy/pull/12679. + + assert_equal(stats.iqr(x, scale=1.0, nan_policy='omit'), 7.5) + assert_almost_equal(stats.iqr(x, scale='normal', nan_policy='omit'), + 7.5 / 1.3489795) + assert_equal(stats.iqr(x, scale=2.0, nan_policy='omit'), 3.75) + + # Bad scale + assert_raises(ValueError, stats.iqr, x, scale='foobar') + + +class TestMoments: + """ + Comparison numbers are found using R v.1.5.1 + note that length(testcase) = 4 + testmathworks comes from documentation for the + Statistics Toolbox for Matlab and can be found at both + https://www.mathworks.com/help/stats/kurtosis.html + https://www.mathworks.com/help/stats/skewness.html + Note that both test cases came from here. + """ + testcase = [1., 2., 3., 4.] + scalar_testcase = 4. + np.random.seed(1234) + testcase_moment_accuracy = np.random.rand(42) + + def _assert_equal(self, actual, expect, *, shape=None, dtype=None): + expect = np.asarray(expect) + if shape is not None: + expect = np.broadcast_to(expect, shape) + assert_array_equal(actual, expect) + if dtype is None: + dtype = expect.dtype + assert actual.dtype == dtype + + @array_api_compatible + @pytest.mark.parametrize('size', [10, (10, 2)]) + @pytest.mark.parametrize('m, c', product((0, 1, 2, 3), (None, 0, 1))) + def test_moment_center_scalar_moment(self, size, m, c, xp): + rng = np.random.default_rng(6581432544381372042) + x = xp.asarray(rng.random(size=size)) + res = stats.moment(x, m, center=c) + c = xp.mean(x, axis=0) if c is None else c + ref = xp.sum((x - c)**m, axis=0)/x.shape[0] + xp_assert_close(res, ref, atol=1e-16) + + @array_api_compatible + @pytest.mark.parametrize('size', [10, (10, 2)]) + @pytest.mark.parametrize('c', (None, 0, 1)) + def test_moment_center_array_moment(self, size, c, xp): + rng = np.random.default_rng(1706828300224046506) + x = xp.asarray(rng.random(size=size)) + m = [0, 1, 2, 3] + res = stats.moment(x, m, center=c) + xp_test = array_namespace(x) # no `concat` in np < 2.0; no `newaxis` in torch + ref = xp_test.concat([stats.moment(x, i, center=c)[xp_test.newaxis, ...] + for i in m]) + xp_assert_equal(res, ref) + + @array_api_compatible + def test_moment(self, xp): + # mean((testcase-mean(testcase))**power,axis=0),axis=0))**power)) + testcase = xp.asarray(self.testcase) + + y = stats.moment(xp.asarray(self.scalar_testcase)) + xp_assert_close(y, xp.asarray(0.0)) + + y = stats.moment(testcase, 0) + xp_assert_close(y, xp.asarray(1.0)) + y = stats.moment(testcase, 1) + xp_assert_close(y, xp.asarray(0.0)) + y = stats.moment(testcase, 2) + xp_assert_close(y, xp.asarray(1.25)) + y = stats.moment(testcase, 3) + xp_assert_close(y, xp.asarray(0.0)) + y = stats.moment(testcase, 4) + xp_assert_close(y, xp.asarray(2.5625)) + + # check array_like input for moment + y = stats.moment(testcase, [1, 2, 3, 4]) + xp_assert_close(y, xp.asarray([0, 1.25, 0, 2.5625])) + + # check moment input consists only of integers + y = stats.moment(testcase, 0.0) + xp_assert_close(y, xp.asarray(1.0)) + message = 'All elements of `order` must be integral.' + with pytest.raises(ValueError, match=message): + stats.moment(testcase, 1.2) + y = stats.moment(testcase, [1.0, 2, 3, 4.0]) + xp_assert_close(y, xp.asarray([0, 1.25, 0, 2.5625])) + + def test_cases(): + y = stats.moment(xp.asarray([])) + xp_assert_equal(y, xp.asarray(xp.nan)) + y = stats.moment(xp.asarray([], dtype=xp.float32)) + xp_assert_equal(y, xp.asarray(xp.nan, dtype=xp.float32)) + y = stats.moment(xp.zeros((1, 0)), axis=0) + xp_assert_equal(y, xp.empty((0,))) + y = stats.moment(xp.asarray([[]]), axis=1) + xp_assert_equal(y, xp.asarray([xp.nan])) + y = stats.moment(xp.asarray([[]]), order=[0, 1], axis=0) + xp_assert_equal(y, xp.empty((2, 0))) + + # test empty input + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match="See documentation for..."): + test_cases() + else: + with np.testing.suppress_warnings() as sup: # needed by array_api_strict + sup.filter(RuntimeWarning, "Mean of empty slice.") + sup.filter(RuntimeWarning, "invalid value") + test_cases() + + def test_nan_policy(self): + x = np.arange(10.) + x[9] = np.nan + assert_equal(stats.moment(x, 2), np.nan) + assert_almost_equal(stats.moment(x, nan_policy='omit'), 0.0) + assert_raises(ValueError, stats.moment, x, nan_policy='raise') + assert_raises(ValueError, stats.moment, x, nan_policy='foobar') + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + @pytest.mark.parametrize('dtype', ['float32', 'float64', 'complex128']) + @pytest.mark.parametrize('expect, order', [(0, 1), (1, 0)]) + def test_constant_moments(self, dtype, expect, order, xp): + if dtype=='complex128' and is_torch(xp): + pytest.skip() + dtype = getattr(xp, dtype) + x = xp.asarray(np.random.rand(5), dtype=dtype) + y = stats.moment(x, order=order) + xp_assert_equal(y, xp.asarray(expect, dtype=dtype)) + + y = stats.moment(xp.broadcast_to(x, (6, 5)), axis=0, order=order) + xp_assert_equal(y, xp.full((5,), expect, dtype=dtype)) + + y = stats.moment(xp.broadcast_to(x, (1, 2, 3, 4, 5)), axis=2, + order=order) + xp_assert_equal(y, xp.full((1, 2, 4, 5), expect, dtype=dtype)) + + y = stats.moment(xp.broadcast_to(x, (1, 2, 3, 4, 5)), axis=None, + order=order) + xp_assert_equal(y, xp.full((), expect, dtype=dtype)) + + @skip_xp_backends('jax.numpy', + reason="JAX arrays do not support item assignment") + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_moment_propagate_nan(self, xp): + # Check that the shape of the result is the same for inputs + # with and without nans, cf gh-5817 + a = xp.reshape(xp.arange(8.), (2, -1)) + a[1, 0] = np.nan + mm = stats.moment(a, 2, axis=1) + xp_assert_close(mm, xp.asarray([1.25, np.nan]), atol=1e-15) + + @array_api_compatible + def test_moment_empty_order(self, xp): + # tests moment with empty `order` list + with pytest.raises(ValueError, match=r"`order` must be a scalar or a" + r" non-empty 1D array."): + stats.moment(xp.asarray([1, 2, 3, 4]), order=[]) + + @array_api_compatible + def test_rename_moment_order(self, xp): + # Parameter 'order' was formerly known as 'moment'. The old name + # has not been deprecated, so it must continue to work. + x = xp.arange(10) + res = stats.moment(x, moment=3) + ref = stats.moment(x, order=3) + xp_assert_equal(res, ref) + + def test_moment_accuracy(self): + # 'moment' must have a small enough error compared to the slower + # but very accurate numpy.power() implementation. + tc_no_mean = (self.testcase_moment_accuracy + - np.mean(self.testcase_moment_accuracy)) + assert_allclose(np.power(tc_no_mean, 42).mean(), + stats.moment(self.testcase_moment_accuracy, 42)) + + @array_api_compatible + @pytest.mark.parametrize('order', [0, 1, 2, 3]) + @pytest.mark.parametrize('axis', [-1, 0, 1]) + @pytest.mark.parametrize('center', [None, 0]) + def test_moment_array_api(self, xp, order, axis, center): + rng = np.random.default_rng(34823589259425) + x = rng.random(size=(5, 6, 7)) + res = stats.moment(xp.asarray(x), order, axis=axis, center=center) + ref = xp.asarray(_moment(x, order, axis, mean=center)) + xp_assert_close(res, ref) + + +class SkewKurtosisTest: + scalar_testcase = 4. + testcase = [1., 2., 3., 4.] + testmathworks = [1.165, 0.6268, 0.0751, 0.3516, -0.6965] + + +class TestSkew(SkewKurtosisTest): + @array_api_compatible + @pytest.mark.parametrize('stat_fun', [stats.skew, stats.kurtosis]) + def test_empty_1d(self, stat_fun, xp): + x = xp.asarray([]) + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stat_fun(x) + else: + with np.testing.suppress_warnings() as sup: + # array_api_strict produces these + sup.filter(RuntimeWarning, "Mean of empty slice") + sup.filter(RuntimeWarning, "invalid value encountered") + res = stat_fun(x) + xp_assert_equal(res, xp.asarray(xp.nan)) + + @skip_xp_backends('jax.numpy', + reason="JAX arrays do not support item assignment") + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_skewness(self, xp): + # Scalar test case + y = stats.skew(xp.asarray(self.scalar_testcase)) + xp_assert_close(y, xp.asarray(xp.nan)) + # sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0) / + # ((sqrt(var(testmathworks)*4/5))**3)/5 + y = stats.skew(xp.asarray(self.testmathworks)) + xp_assert_close(y, xp.asarray(-0.29322304336607), atol=1e-10) + y = stats.skew(xp.asarray(self.testmathworks), bias=0) + xp_assert_close(y, xp.asarray(-0.437111105023940), atol=1e-10) + y = stats.skew(xp.asarray(self.testcase)) + xp_assert_close(y, xp.asarray(0.0), atol=1e-10) + + def test_nan_policy(self): + # initially, nan_policy is ignored with alternative backends + x = np.arange(10.) + x[9] = np.nan + with np.errstate(invalid='ignore'): + assert_equal(stats.skew(x), np.nan) + assert_equal(stats.skew(x, nan_policy='omit'), 0.) + assert_raises(ValueError, stats.skew, x, nan_policy='raise') + assert_raises(ValueError, stats.skew, x, nan_policy='foobar') + + def test_skewness_scalar(self): + # `skew` must return a scalar for 1-dim input (only for NumPy arrays) + assert_equal(stats.skew(arange(10)), 0.0) + + @skip_xp_backends('jax.numpy', + reason="JAX arrays do not support item assignment") + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_skew_propagate_nan(self, xp): + # Check that the shape of the result is the same for inputs + # with and without nans, cf gh-5817 + a = xp.arange(8.) + a = xp.reshape(a, (2, -1)) + a[1, 0] = xp.nan + with np.errstate(invalid='ignore'): + s = stats.skew(a, axis=1) + xp_assert_equal(s, xp.asarray([0, xp.nan])) + + @array_api_compatible + def test_skew_constant_value(self, xp): + # Skewness of a constant input should be NaN (gh-16061) + with pytest.warns(RuntimeWarning, match="Precision loss occurred"): + a = xp.asarray([-0.27829495]*10) # xp.repeat not currently available + xp_assert_equal(stats.skew(a), xp.asarray(xp.nan)) + xp_assert_equal(stats.skew(a*2.**50), xp.asarray(xp.nan)) + xp_assert_equal(stats.skew(a/2.**50), xp.asarray(xp.nan)) + xp_assert_equal(stats.skew(a, bias=False), xp.asarray(xp.nan)) + + # # similarly, from gh-11086: + a = xp.asarray([14.3]*7) + xp_assert_equal(stats.skew(a), xp.asarray(xp.nan)) + a = 1. + xp.arange(-3., 4)*1e-16 + xp_assert_equal(stats.skew(a), xp.asarray(xp.nan)) + + @skip_xp_backends('jax.numpy', + reason="JAX arrays do not support item assignment") + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_precision_loss_gh15554(self, xp): + # gh-15554 was one of several issues that have reported problems with + # constant or near-constant input. We can't always fix these, but + # make sure there's a warning. + with pytest.warns(RuntimeWarning, match="Precision loss occurred"): + rng = np.random.default_rng(34095309370) + a = xp.asarray(rng.random(size=(100, 10))) + a[:, 0] = 1.01 + stats.skew(a) + + @skip_xp_backends('jax.numpy', + reason="JAX arrays do not support item assignment") + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + @pytest.mark.parametrize('axis', [-1, 0, 2, None]) + @pytest.mark.parametrize('bias', [False, True]) + def test_vectorization(self, xp, axis, bias): + # Behavior with array input is barely tested above. Compare + # against naive implementation. + rng = np.random.default_rng(1283413549926) + x = xp.asarray(rng.random((3, 4, 5))) + + def skewness(a, axis, bias): + # Simple implementation of skewness + if axis is None: + a = xp.reshape(a, (-1,)) + axis = 0 + xp_test = array_namespace(a) # plain torch ddof=1 by default + mean = xp_test.mean(a, axis=axis, keepdims=True) + mu3 = xp_test.mean((a - mean)**3, axis=axis) + std = xp_test.std(a, axis=axis) + res = mu3 / std ** 3 + if not bias: + n = a.shape[axis] + res *= ((n - 1.0) * n) ** 0.5 / (n - 2.0) + return res + + res = stats.skew(x, axis=axis, bias=bias) + ref = skewness(x, axis=axis, bias=bias) + xp_assert_close(res, ref) + + +class TestKurtosis(SkewKurtosisTest): + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_kurtosis(self, xp): + # Scalar test case + y = stats.kurtosis(xp.asarray(self.scalar_testcase)) + assert xp.isnan(y) + + # sum((testcase-mean(testcase,axis=0))**4,axis=0) + # / ((sqrt(var(testcase)*3/4))**4) + # / 4 + # + # sum((test2-mean(testmathworks,axis=0))**4,axis=0) + # / ((sqrt(var(testmathworks)*4/5))**4) + # / 5 + # + # Set flags for axis = 0 and + # fisher=0 (Pearson's defn of kurtosis for compatibility with Matlab) + y = stats.kurtosis(xp.asarray(self.testmathworks), 0, fisher=0, bias=1) + xp_assert_close(y, xp.asarray(2.1658856802973)) + + # Note that MATLAB has confusing docs for the following case + # kurtosis(x,0) gives an unbiased estimate of Pearson's skewness + # kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3) + # The MATLAB docs imply that both should give Fisher's + y = stats.kurtosis(xp.asarray(self.testmathworks), fisher=0, bias=0) + xp_assert_close(y, xp.asarray(3.663542721189047)) + y = stats.kurtosis(xp.asarray(self.testcase), 0, 0) + xp_assert_close(y, xp.asarray(1.64)) + + x = xp.arange(10.) + x = xp.where(x == 8, xp.asarray(xp.nan), x) + xp_assert_equal(stats.kurtosis(x), xp.asarray(xp.nan)) + + def test_kurtosis_nan_policy(self): + # nan_policy only for NumPy right now + x = np.arange(10.) + x[9] = np.nan + assert_almost_equal(stats.kurtosis(x, nan_policy='omit'), -1.230000) + assert_raises(ValueError, stats.kurtosis, x, nan_policy='raise') + assert_raises(ValueError, stats.kurtosis, x, nan_policy='foobar') + + def test_kurtosis_array_scalar(self): + # "array scalars" do not exist in other backends + assert_equal(type(stats.kurtosis([1, 2, 3])), np.float64) + + def test_kurtosis_propagate_nan(self): + # nan_policy only for NumPy right now + # Check that the shape of the result is the same for inputs + # with and without nans, cf gh-5817 + a = np.arange(8).reshape(2, -1).astype(float) + a[1, 0] = np.nan + k = stats.kurtosis(a, axis=1, nan_policy="propagate") + np.testing.assert_allclose(k, [-1.36, np.nan], atol=1e-15) + + @array_api_compatible + def test_kurtosis_constant_value(self, xp): + # Kurtosis of a constant input should be NaN (gh-16061) + a = xp.asarray([-0.27829495]*10) + with pytest.warns(RuntimeWarning, match="Precision loss occurred"): + assert xp.isnan(stats.kurtosis(a, fisher=False)) + assert xp.isnan(stats.kurtosis(a * float(2**50), fisher=False)) + assert xp.isnan(stats.kurtosis(a / float(2**50), fisher=False)) + assert xp.isnan(stats.kurtosis(a, fisher=False, bias=False)) + + @skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment') + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + @pytest.mark.parametrize('axis', [-1, 0, 2, None]) + @pytest.mark.parametrize('bias', [False, True]) + @pytest.mark.parametrize('fisher', [False, True]) + def test_vectorization(self, xp, axis, bias, fisher): + # Behavior with array input is not tested above. Compare + # against naive implementation. + rng = np.random.default_rng(1283413549926) + x = xp.asarray(rng.random((4, 5, 6))) + + def kurtosis(a, axis, bias, fisher): + # Simple implementation of kurtosis + if axis is None: + a = xp.reshape(a, (-1,)) + axis = 0 + xp_test = array_namespace(a) # plain torch ddof=1 by default + mean = xp_test.mean(a, axis=axis, keepdims=True) + mu4 = xp_test.mean((a - mean)**4, axis=axis) + mu2 = xp_test.var(a, axis=axis, correction=0) + if bias: + res = mu4 / mu2**2 - 3 + else: + n = a.shape[axis] + # https://en.wikipedia.org/wiki/Kurtosis#Standard_unbiased_estimator + res = (n-1) / ((n-2) * (n-3)) * ((n + 1) * mu4/mu2**2 - 3*(n-1)) + + # I know it looks strange to subtract then add 3, + # but it is simpler than the alternatives + return res if fisher else res + 3 + + res = stats.kurtosis(x, axis=axis, bias=bias, fisher=fisher) + ref = kurtosis(x, axis=axis, bias=bias, fisher=fisher) + xp_assert_close(res, ref) + + +@hypothesis.strategies.composite +def ttest_data_axis_strategy(draw): + # draw an array under shape and value constraints + elements = dict(allow_nan=False, allow_infinity=False) + shape = npst.array_shapes(min_dims=1, min_side=2) + # The test that uses this, `test_pvalue_ci`, uses `float64` to test + # extreme `alpha`. It could be adjusted to test a dtype-dependent + # range of `alpha` if this strategy is needed to generate other floats. + data = draw(npst.arrays(dtype=np.float64, elements=elements, shape=shape)) + + # determine axes over which nonzero variance can be computed accurately + ok_axes = [] + # Locally, I don't need catch_warnings or simplefilter, and I can just + # suppress RuntimeWarning. I include all that in hope of getting the same + # behavior on CI. + with warnings.catch_warnings(): + warnings.simplefilter("error") + for axis in range(len(data.shape)): + with contextlib.suppress(Exception): + var = stats.moment(data, order=2, axis=axis) + if np.all(var > 0) and np.all(np.isfinite(var)): + ok_axes.append(axis) + # if there are no valid axes, tell hypothesis to try a different example + hypothesis.assume(ok_axes) + + # draw one of the valid axes + axis = draw(hypothesis.strategies.sampled_from(ok_axes)) + + return data, axis + + +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +class TestStudentTest: + # Preserving original test cases. + # Recomputed statistics and p-values with R t.test, e.g. + # options(digits=16) + # t.test(c(-1., 0., 1.), mu=2) + X1 = [-1., 0., 1.] + X2 = [0., 1., 2.] + T1_0 = 0. + P1_0 = 1. + T1_1 = -1.7320508075689 + P1_1 = 0.2254033307585 + T1_2 = -3.4641016151378 + P1_2 = 0.07417990022745 + T2_0 = 1.7320508075689 + P2_0 = 0.2254033307585 + P1_1_l = P1_1 / 2 + P1_1_g = 1 - (P1_1 / 2) + + def test_onesample(self, xp): + with suppress_warnings() as sup, \ + np.errstate(invalid="ignore", divide="ignore"): + sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice") + a = xp.asarray(4.) if not is_numpy(xp) else 4. + t, p = stats.ttest_1samp(a, 3.) + xp_assert_equal(t, xp.asarray(xp.nan)) + xp_assert_equal(p, xp.asarray(xp.nan)) + + t, p = stats.ttest_1samp(xp.asarray(self.X1), 0.) + xp_assert_close(t, xp.asarray(self.T1_0)) + xp_assert_close(p, xp.asarray(self.P1_0)) + + res = stats.ttest_1samp(xp.asarray(self.X1), 0.) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, xp=xp) + + t, p = stats.ttest_1samp(xp.asarray(self.X2), 0.) + + xp_assert_close(t, xp.asarray(self.T2_0)) + xp_assert_close(p, xp.asarray(self.P2_0)) + + t, p = stats.ttest_1samp(xp.asarray(self.X1), 1.) + + xp_assert_close(t, xp.asarray(self.T1_1)) + xp_assert_close(p, xp.asarray(self.P1_1)) + + t, p = stats.ttest_1samp(xp.asarray(self.X1), 2.) + + xp_assert_close(t, xp.asarray(self.T1_2)) + xp_assert_close(p, xp.asarray(self.P1_2)) + + def test_onesample_nan_policy(self, xp): + # check nan policy + if not is_numpy(xp): + x = xp.asarray([1., 2., 3., xp.nan]) + message = "Use of `nan_policy` and `keepdims`..." + with pytest.raises(NotImplementedError, match=message): + stats.ttest_1samp(x, 1., nan_policy='omit') + return + + x = stats.norm.rvs(loc=5, scale=10, size=51, random_state=7654567) + x[50] = np.nan + with np.errstate(invalid="ignore"): + assert_array_equal(stats.ttest_1samp(x, 5.0), (np.nan, np.nan)) + + assert_array_almost_equal(stats.ttest_1samp(x, 5.0, nan_policy='omit'), + (-1.6412624074367159, 0.107147027334048005)) + assert_raises(ValueError, stats.ttest_1samp, x, 5.0, nan_policy='raise') + assert_raises(ValueError, stats.ttest_1samp, x, 5.0, + nan_policy='foobar') + + def test_1samp_alternative(self, xp): + message = "`alternative` must be 'less', 'greater', or 'two-sided'." + with pytest.raises(ValueError, match=message): + stats.ttest_1samp(xp.asarray(self.X1), 0., alternative="error") + + t, p = stats.ttest_1samp(xp.asarray(self.X1), 1., alternative="less") + xp_assert_close(p, xp.asarray(self.P1_1_l)) + xp_assert_close(t, xp.asarray(self.T1_1)) + + t, p = stats.ttest_1samp(xp.asarray(self.X1), 1., alternative="greater") + xp_assert_close(p, xp.asarray(self.P1_1_g)) + xp_assert_close(t, xp.asarray(self.T1_1)) + + @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater']) + def test_1samp_ci_1d(self, xp, alternative): + # test confidence interval method against reference values + rng = np.random.default_rng(8066178009154342972) + n = 10 + x = rng.normal(size=n, loc=1.5, scale=2) + popmean = rng.normal() # this shouldn't affect confidence interval + # Reference values generated with R t.test: + # options(digits=16) + # x = c(2.75532884, 0.93892217, 0.94835861, 1.49489446, -0.62396595, + # -1.88019867, -1.55684465, 4.88777104, 5.15310979, 4.34656348) + # t.test(x, conf.level=0.85, alternative='l') + dtype = xp.float32 if is_torch(xp) else xp.float64 # use default dtype + x = xp.asarray(x, dtype=dtype) + popmean = xp.asarray(popmean, dtype=dtype) + + ref = {'two-sided': [0.3594423211709136, 2.9333455028290860], + 'greater': [0.7470806207371626, np.inf], + 'less': [-np.inf, 2.545707203262837]} + res = stats.ttest_1samp(x, popmean=popmean, alternative=alternative) + ci = res.confidence_interval(confidence_level=0.85) + xp_assert_close(ci.low, xp.asarray(ref[alternative][0])) + xp_assert_close(ci.high, xp.asarray(ref[alternative][1])) + xp_assert_equal(res.df, xp.asarray(n-1)) + + def test_1samp_ci_iv(self, xp): + # test `confidence_interval` method input validation + res = stats.ttest_1samp(xp.arange(10.), 0.) + message = '`confidence_level` must be a number between 0 and 1.' + with pytest.raises(ValueError, match=message): + res.confidence_interval(confidence_level=10) + + @pytest.mark.xslow + @hypothesis.given(alpha=hypothesis.strategies.floats(1e-15, 1-1e-15), + data_axis=ttest_data_axis_strategy()) + @pytest.mark.parametrize('alternative', ['less', 'greater']) + def test_pvalue_ci(self, alpha, data_axis, alternative, xp): + # test relationship between one-sided p-values and confidence intervals + data, axis = data_axis + data = xp.asarray(data) + res = stats.ttest_1samp(data, 0., + alternative=alternative, axis=axis) + l, u = res.confidence_interval(confidence_level=alpha) + popmean = l if alternative == 'greater' else u + xp_test = array_namespace(l) # torch needs `expand_dims` + popmean = xp_test.expand_dims(popmean, axis=axis) + res = stats.ttest_1samp(data, popmean, alternative=alternative, axis=axis) + shape = list(data.shape) + shape.pop(axis) + # `float64` is used to correspond with extreme range of `alpha` + ref = xp.broadcast_to(xp.asarray(1-alpha, dtype=xp.float64), shape) + xp_assert_close(res.pvalue, ref) + + +class TestPercentileOfScore: + + def f(self, *args, **kwargs): + return stats.percentileofscore(*args, **kwargs) + + @pytest.mark.parametrize("kind, result", [("rank", 40), + ("mean", 35), + ("strict", 30), + ("weak", 40)]) + def test_unique(self, kind, result): + a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + assert_equal(self.f(a, 4, kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", 45), + ("mean", 40), + ("strict", 30), + ("weak", 50)]) + def test_multiple2(self, kind, result): + a = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9] + assert_equal(self.f(a, 4, kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", 50), + ("mean", 45), + ("strict", 30), + ("weak", 60)]) + def test_multiple3(self, kind, result): + a = [1, 2, 3, 4, 4, 4, 5, 6, 7, 8] + assert_equal(self.f(a, 4, kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", 30), + ("mean", 30), + ("strict", 30), + ("weak", 30)]) + def test_missing(self, kind, result): + a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11] + assert_equal(self.f(a, 4, kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", 40), + ("mean", 35), + ("strict", 30), + ("weak", 40)]) + def test_large_numbers(self, kind, result): + a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + assert_equal(self.f(a, 40, kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", 50), + ("mean", 45), + ("strict", 30), + ("weak", 60)]) + def test_large_numbers_multiple3(self, kind, result): + a = [10, 20, 30, 40, 40, 40, 50, 60, 70, 80] + assert_equal(self.f(a, 40, kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", 30), + ("mean", 30), + ("strict", 30), + ("weak", 30)]) + def test_large_numbers_missing(self, kind, result): + a = [10, 20, 30, 50, 60, 70, 80, 90, 100, 110] + assert_equal(self.f(a, 40, kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", [0, 10, 100, 100]), + ("mean", [0, 5, 95, 100]), + ("strict", [0, 0, 90, 100]), + ("weak", [0, 10, 100, 100])]) + def test_boundaries(self, kind, result): + a = [10, 20, 30, 50, 60, 70, 80, 90, 100, 110] + assert_equal(self.f(a, [0, 10, 110, 200], kind=kind), result) + + @pytest.mark.parametrize("kind, result", [("rank", [0, 10, 100]), + ("mean", [0, 5, 95]), + ("strict", [0, 0, 90]), + ("weak", [0, 10, 100])]) + def test_inf(self, kind, result): + a = [1, 2, 3, 4, 5, 6, 7, 8, 9, +np.inf] + assert_equal(self.f(a, [-np.inf, 1, +np.inf], kind=kind), result) + + cases = [("propagate", [], 1, np.nan), + ("propagate", [np.nan], 1, np.nan), + ("propagate", [np.nan], [0, 1, 2], [np.nan, np.nan, np.nan]), + ("propagate", [1, 2], [1, 2, np.nan], [50, 100, np.nan]), + ("omit", [1, 2, np.nan], [0, 1, 2], [0, 50, 100]), + ("omit", [1, 2], [0, 1, np.nan], [0, 50, np.nan]), + ("omit", [np.nan, np.nan], [0, 1, 2], [np.nan, np.nan, np.nan])] + + @pytest.mark.parametrize("policy, a, score, result", cases) + def test_nans_ok(self, policy, a, score, result): + assert_equal(self.f(a, score, nan_policy=policy), result) + + cases = [ + ("raise", [1, 2, 3, np.nan], [1, 2, 3], + "The input contains nan values"), + ("raise", [1, 2, 3], [1, 2, 3, np.nan], + "The input contains nan values"), + ] + + @pytest.mark.parametrize("policy, a, score, message", cases) + def test_nans_fail(self, policy, a, score, message): + with assert_raises(ValueError, match=message): + self.f(a, score, nan_policy=policy) + + @pytest.mark.parametrize("shape", [ + (6, ), + (2, 3), + (2, 1, 3), + (2, 1, 1, 3), + ]) + def test_nd(self, shape): + a = np.array([0, 1, 2, 3, 4, 5]) + scores = a.reshape(shape) + results = scores*10 + a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + assert_equal(self.f(a, scores, kind="rank"), results) + + +PowerDivCase = namedtuple('Case', # type: ignore[name-match] + ['f_obs', 'f_exp', 'ddof', 'axis', + 'chi2', # Pearson's + 'log', # G-test (log-likelihood) + 'mod_log', # Modified log-likelihood + 'cr', # Cressie-Read (lambda=2/3) + ]) + +# The details of the first two elements in power_div_1d_cases are used +# in a test in TestPowerDivergence. Check that code before making +# any changes here. +power_div_1d_cases = [ + # Use the default f_exp. + PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=None, ddof=0, axis=None, + chi2=4, + log=2*(4*np.log(4/8) + 12*np.log(12/8)), + mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)), + cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)), + # Give a non-uniform f_exp. + PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=[2, 16, 12, 2], ddof=0, axis=None, + chi2=24, + log=2*(4*np.log(4/2) + 8*np.log(8/16) + 8*np.log(8/2)), + mod_log=2*(2*np.log(2/4) + 16*np.log(16/8) + 2*np.log(2/8)), + cr=(4*((4/2)**(2/3) - 1) + 8*((8/16)**(2/3) - 1) + + 8*((8/2)**(2/3) - 1))/(5/9)), + # f_exp is a scalar. + PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=8, ddof=0, axis=None, + chi2=4, + log=2*(4*np.log(4/8) + 12*np.log(12/8)), + mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)), + cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)), + # f_exp equal to f_obs. + PowerDivCase(f_obs=[3, 5, 7, 9], f_exp=[3, 5, 7, 9], ddof=0, axis=0, + chi2=0, log=0, mod_log=0, cr=0), +] + + +power_div_empty_cases = [ + # Shape is (0,)--a data set with length 0. The computed + # test statistic should be 0. + PowerDivCase(f_obs=[], + f_exp=None, ddof=0, axis=0, + chi2=0, log=0, mod_log=0, cr=0), + # Shape is (0, 3). This is 3 data sets, but each data set has + # length 0, so the computed test statistic should be [0, 0, 0]. + PowerDivCase(f_obs=np.array([[],[],[]]).T, + f_exp=None, ddof=0, axis=0, + chi2=[0, 0, 0], + log=[0, 0, 0], + mod_log=[0, 0, 0], + cr=[0, 0, 0]), + # Shape is (3, 0). This represents an empty collection of + # data sets in which each data set has length 3. The test + # statistic should be an empty array. + PowerDivCase(f_obs=np.array([[],[],[]]), + f_exp=None, ddof=0, axis=0, + chi2=[], + log=[], + mod_log=[], + cr=[]), +] + + +@array_api_compatible +class TestPowerDivergence: + + def check_power_divergence(self, f_obs, f_exp, ddof, axis, lambda_, + expected_stat, xp): + dtype = xp.asarray(1.).dtype + + f_obs = xp.asarray(f_obs, dtype=dtype) + f_exp = xp.asarray(f_exp, dtype=dtype) if f_exp is not None else f_exp + + if axis is None: + num_obs = xp_size(f_obs) + else: + xp_test = array_namespace(f_obs) # torch needs broadcast_arrays + arrays = (xp_test.broadcast_arrays(f_obs, f_exp) if f_exp is not None + else (f_obs,)) + num_obs = arrays[0].shape[axis] + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Mean of empty slice") + stat, p = stats.power_divergence( + f_obs=f_obs, f_exp=f_exp, ddof=ddof, + axis=axis, lambda_=lambda_) + xp_assert_close(stat, xp.asarray(expected_stat, dtype=dtype)) + + if lambda_ == 1 or lambda_ == "pearson": + # Also test stats.chisquare. + stat, p = stats.chisquare(f_obs=f_obs, f_exp=f_exp, ddof=ddof, + axis=axis) + xp_assert_close(stat, xp.asarray(expected_stat, dtype=dtype)) + + ddof = np.asarray(ddof) + expected_p = stats.distributions.chi2.sf(expected_stat, + num_obs - 1 - ddof) + xp_assert_close(p, xp.asarray(expected_p, dtype=dtype)) + + @pytest.mark.parametrize('case', power_div_1d_cases) + @pytest.mark.parametrize('lambda_stat', + [(None, 'chi2'), ('pearson', 'chi2'), (1, 'chi2'), + ('log-likelihood', 'log'), ('mod-log-likelihood', 'mod_log'), + ('cressie-read', 'cr'), (2/3, 'cr')]) + def test_basic(self, case, lambda_stat, xp): + lambda_, attr = lambda_stat + expected_stat = getattr(case, attr) + self.check_power_divergence(case.f_obs, case.f_exp, case.ddof, case.axis, + lambda_, expected_stat, xp) + + def test_axis(self, xp): + case0 = power_div_1d_cases[0] + case1 = power_div_1d_cases[1] + f_obs = np.vstack((case0.f_obs, case1.f_obs)) + f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs), + case1.f_exp)) + # Check the four computational code paths in power_divergence + # using a 2D array with axis=1. + f_obs = xp.asarray(f_obs) + f_exp = xp.asarray(f_exp) if f_exp is not None else f_exp + self.check_power_divergence( + f_obs, f_exp, 0, 1, + "pearson", [case0.chi2, case1.chi2], xp=xp) + self.check_power_divergence( + f_obs, f_exp, 0, 1, + "log-likelihood", [case0.log, case1.log], xp=xp) + self.check_power_divergence( + f_obs, f_exp, 0, 1, + "mod-log-likelihood", [case0.mod_log, case1.mod_log], xp=xp) + self.check_power_divergence( + f_obs, f_exp, 0, 1, + "cressie-read", [case0.cr, case1.cr], xp=xp) + # Reshape case0.f_obs to shape (2,2), and use axis=None. + # The result should be the same. + f_obs_reshape = xp.reshape(xp.asarray(case0.f_obs), (2, 2)) + self.check_power_divergence( + f_obs_reshape, None, 0, None, + "pearson", case0.chi2, xp=xp) + + def test_ddof_broadcasting(self, xp): + # Test that ddof broadcasts correctly. + # ddof does not affect the test statistic. It is broadcast + # with the computed test statistic for the computation of + # the p value. + + case0 = power_div_1d_cases[0] + case1 = power_div_1d_cases[1] + # Create 4x2 arrays of observed and expected frequencies. + f_obs = np.vstack((case0.f_obs, case1.f_obs)).T + f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs), + case1.f_exp)).T + + expected_chi2 = [case0.chi2, case1.chi2] + + dtype = xp.asarray(1.).dtype + f_obs = xp.asarray(f_obs, dtype=dtype) + f_exp = xp.asarray(f_exp, dtype=dtype) + expected_chi2 = xp.asarray(expected_chi2, dtype=dtype) + + # ddof has shape (2, 1). This is broadcast with the computed + # statistic, so p will have shape (2,2). + ddof = xp.asarray([[0], [1]]) + + stat, p = stats.power_divergence(f_obs, f_exp, ddof=ddof) + xp_assert_close(stat, expected_chi2) + + # Compute the p values separately, passing in scalars for ddof. + stat0, p0 = stats.power_divergence(f_obs, f_exp, ddof=ddof[0, 0]) + stat1, p1 = stats.power_divergence(f_obs, f_exp, ddof=ddof[1, 0]) + + xp_test = array_namespace(f_obs) # needs `concat`, `newaxis` + expected_p = xp_test.concat((p0[xp_test.newaxis, :], + p1[xp_test.newaxis, :]), + axis=0) + xp_assert_close(p, expected_p) + + @pytest.mark.parametrize('case', power_div_empty_cases) + @pytest.mark.parametrize('lambda_stat', + [('pearson', 'chi2'), ('log-likelihood', 'log'), + ('mod-log-likelihood', 'mod_log'), + ('cressie-read', 'cr'), (2/3, 'cr')]) + def test_empty_cases(self, case, lambda_stat, xp): + lambda_, attr = lambda_stat + expected_stat = getattr(case, attr) + with warnings.catch_warnings(): + self.check_power_divergence( + case.f_obs, case.f_exp, case.ddof, case.axis, + lambda_, expected_stat, xp) + + def test_power_divergence_result_attributes(self, xp): + f_obs = power_div_1d_cases[0].f_obs + f_exp = power_div_1d_cases[0].f_exp + ddof = power_div_1d_cases[0].ddof + axis = power_div_1d_cases[0].axis + dtype = xp.asarray(1.).dtype + f_obs = xp.asarray(f_obs, dtype=dtype) + # f_exp is None + + res = stats.power_divergence(f_obs=f_obs, f_exp=f_exp, ddof=ddof, + axis=axis, lambda_="pearson") + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes, xp=xp) + + def test_power_divergence_gh_12282(self, xp): + # The sums of observed and expected frequencies must match + f_obs = xp.asarray([[10., 20.], [30., 20.]]) + f_exp = xp.asarray([[5., 15.], [35., 25.]]) + message = 'For each axis slice...' + with pytest.raises(ValueError, match=message): + stats.power_divergence(f_obs=f_obs, f_exp=xp.asarray([30., 60.])) + with pytest.raises(ValueError, match=message): + stats.power_divergence(f_obs=f_obs, f_exp=f_exp, axis=1) + stat, pval = stats.power_divergence(f_obs=f_obs, f_exp=f_exp) + xp_assert_close(stat, xp.asarray([5.71428571, 2.66666667])) + xp_assert_close(pval, xp.asarray([0.01682741, 0.10247043])) + + def test_power_divergence_against_cressie_read_data(self, xp): + # Test stats.power_divergence against tables 4 and 5 from + # Cressie and Read, "Multimonial Goodness-of-Fit Tests", + # J. R. Statist. Soc. B (1984), Vol 46, No. 3, pp. 440-464. + # This tests the calculation for several values of lambda. + + # Table 4 data recalculated for greater precision according to: + # Shelby J. Haberman, Analysis of Qualitative Data: Volume 1 + # Introductory Topics, Academic Press, New York, USA (1978). + obs = xp.asarray([15., 11., 14., 17., 5., 11., 10., 4., 8., + 10., 7., 9., 11., 3., 6., 1., 1., 4.]) + beta = -0.083769 # Haberman (1978), p. 15 + i = xp.arange(1., obs.shape[0] + 1.) + alpha = xp.log(xp.sum(obs) / xp.sum(xp.exp(beta*i))) + expected_counts = xp.exp(alpha + beta*i) + + # `table4` holds just the second and third columns from Table 4. + xp_test = array_namespace(obs) # NumPy needs concat, torch needs newaxis + table4 = xp_test.concat((obs[xp_test.newaxis, :], + expected_counts[xp_test.newaxis, :])).T + + table5 = xp.asarray([ + # lambda, statistic + -10.0, 72.2e3, + -5.0, 28.9e1, + -3.0, 65.6, + -2.0, 40.6, + -1.5, 34.0, + -1.0, 29.5, + -0.5, 26.5, + 0.0, 24.6, + 0.5, 23.4, + 0.67, 23.1, + 1.0, 22.7, + 1.5, 22.6, + 2.0, 22.9, + 3.0, 24.8, + 5.0, 35.5, + 10.0, 21.4e1, + ]) + table5 = xp.reshape(table5, (-1, 2)) + + for i in range(table5.shape[0]): + lambda_, expected_stat = table5[i, 0], table5[i, 1] + stat, p = stats.power_divergence(table4[:,0], table4[:,1], + lambda_=lambda_) + xp_assert_close(stat, expected_stat, rtol=5e-3) + + +@array_api_compatible +class TestChisquare: + def test_chisquare_12282a(self, xp): + # Currently `chisquare` is implemented via power_divergence + # in case that ever changes, perform a basic test like + # test_power_divergence_gh_12282 + with assert_raises(ValueError, match='For each axis slice...'): + f_obs = xp.asarray([10., 20.]) + f_exp = xp.asarray([30., 60.]) + stats.chisquare(f_obs=f_obs, f_exp=f_exp) + + def test_chisquare_12282b(self, xp): + # Check that users can now disable the sum check tested in + # test_chisquare_12282a. Also, confirm that statistic and p-value + # are as expected. + rng = np.random.default_rng(3843874358728234) + n = 10 + lam = rng.uniform(1000, 2000, size=n) + x = rng.poisson(lam) + lam = xp.asarray(lam) + x = xp.asarray(x, dtype=lam.dtype) + res = stats.chisquare(f_obs=x, f_exp=lam, ddof=-1, sum_check=False) + # Poisson is approximately normal with mean and variance lam + z = (x - lam) / xp.sqrt(lam) + statistic = xp.sum(z**2) + xp_assert_close(res.statistic, statistic) + # Sum of `n` squared standard normal variables follows chi2 with `n` DoF + X2 = _SimpleChi2(xp.asarray(n, dtype=statistic.dtype)) + xp_assert_close(res.pvalue, X2.sf(statistic)) + + @pytest.mark.parametrize("n, dtype", [(200, 'uint8'), (1000000, 'int32')]) + def test_chiquare_data_types_attributes(self, n, dtype, xp): + # Regression test for gh-10159 and gh-18368 + dtype = getattr(xp, dtype) + obs = xp.asarray([n, 0], dtype=dtype) + exp = xp.asarray([n // 2, n // 2], dtype=dtype) + res = stats.chisquare(obs, exp) + stat, p = res + xp_assert_close(stat, xp.asarray(n, dtype=xp.asarray(1.).dtype), rtol=1e-13) + # check that attributes are identical to unpacked outputs - see gh-18368 + xp_assert_equal(res.statistic, stat) + xp_assert_equal(res.pvalue, p) + + +@skip_xp_invalid_arg +class TestChisquareMA: + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_chisquare_masked_arrays(self): + # Test masked arrays. + obs = np.array([[8, 8, 16, 32, -1], [-1, -1, 3, 4, 5]]).T + mask = np.array([[0, 0, 0, 0, 1], [1, 1, 0, 0, 0]]).T + mobs = np.ma.masked_array(obs, mask) + expected_chisq = np.array([24.0, 0.5]) + expected_g = np.array([2*(2*8*np.log(0.5) + 32*np.log(2.0)), + 2*(3*np.log(0.75) + 5*np.log(1.25))]) + + chi2 = stats.distributions.chi2 + + chisq, p = stats.chisquare(mobs) + mat.assert_array_equal(chisq, expected_chisq) + mat.assert_array_almost_equal(p, chi2.sf(expected_chisq, + mobs.count(axis=0) - 1)) + + g, p = stats.power_divergence(mobs, lambda_='log-likelihood') + mat.assert_array_almost_equal(g, expected_g, decimal=15) + mat.assert_array_almost_equal(p, chi2.sf(expected_g, + mobs.count(axis=0) - 1)) + + chisq, p = stats.chisquare(mobs.T, axis=1) + mat.assert_array_equal(chisq, expected_chisq) + mat.assert_array_almost_equal(p, chi2.sf(expected_chisq, + mobs.T.count(axis=1) - 1)) + g, p = stats.power_divergence(mobs.T, axis=1, lambda_="log-likelihood") + mat.assert_array_almost_equal(g, expected_g, decimal=15) + mat.assert_array_almost_equal(p, chi2.sf(expected_g, + mobs.count(axis=0) - 1)) + + obs1 = np.ma.array([3, 5, 6, 99, 10], mask=[0, 0, 0, 1, 0]) + exp1 = np.ma.array([2, 4, 8, 10, 99], mask=[0, 0, 0, 0, 1]) + chi2, p = stats.chisquare(obs1, f_exp=exp1) + # Because of the mask at index 3 of obs1 and at index 4 of exp1, + # only the first three elements are included in the calculation + # of the statistic. + mat.assert_array_equal(chi2, 1/2 + 1/4 + 4/8) + + # When axis=None, the two values should have type np.float64. + chisq, p = stats.chisquare(np.ma.array([1,2,3]), axis=None) + assert_(isinstance(chisq, np.float64)) + assert_(isinstance(p, np.float64)) + assert_equal(chisq, 1.0) + assert_almost_equal(p, stats.distributions.chi2.sf(1.0, 2)) + + # Empty arrays: + # A data set with length 0 returns a masked scalar. + with np.errstate(invalid='ignore'): + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Mean of empty slice") + chisq, p = stats.chisquare(np.ma.array([])) + assert_(isinstance(chisq, np.ma.MaskedArray)) + assert_equal(chisq.shape, ()) + assert_(chisq.mask) + + empty3 = np.ma.array([[],[],[]]) + + # empty3 is a collection of 0 data sets (whose lengths would be 3, if + # there were any), so the return value is an array with length 0. + chisq, p = stats.chisquare(empty3) + assert_(isinstance(chisq, np.ma.MaskedArray)) + mat.assert_array_equal(chisq, []) + + # empty3.T is an array containing 3 data sets, each with length 0, + # so an array of size (3,) is returned, with all values masked. + with np.errstate(invalid='ignore'): + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Mean of empty slice") + chisq, p = stats.chisquare(empty3.T) + + assert_(isinstance(chisq, np.ma.MaskedArray)) + assert_equal(chisq.shape, (3,)) + assert_(np.all(chisq.mask)) + + def test_deprecation_warning(self): + a = np.asarray([1., 2., 3.]) + ma = np.ma.masked_array(a) + message = "`power_divergence` and `chisquare` support for masked..." + with pytest.warns(DeprecationWarning, match=message): + stats.chisquare(ma) + with pytest.warns(DeprecationWarning, match=message): + stats.chisquare(a, ma) + + +def test_friedmanchisquare(): + # see ticket:113 + # verified with matlab and R + # From Demsar "Statistical Comparisons of Classifiers over Multiple Data Sets" + # 2006, Xf=9.28 (no tie handling, tie corrected Xf >=9.28) + x1 = [array([0.763, 0.599, 0.954, 0.628, 0.882, 0.936, 0.661, 0.583, + 0.775, 1.0, 0.94, 0.619, 0.972, 0.957]), + array([0.768, 0.591, 0.971, 0.661, 0.888, 0.931, 0.668, 0.583, + 0.838, 1.0, 0.962, 0.666, 0.981, 0.978]), + array([0.771, 0.590, 0.968, 0.654, 0.886, 0.916, 0.609, 0.563, + 0.866, 1.0, 0.965, 0.614, 0.9751, 0.946]), + array([0.798, 0.569, 0.967, 0.657, 0.898, 0.931, 0.685, 0.625, + 0.875, 1.0, 0.962, 0.669, 0.975, 0.970])] + + # From "Bioestadistica para las ciencias de la salud" Xf=18.95 p<0.001: + x2 = [array([4,3,5,3,5,3,2,5,4,4,4,3]), + array([2,2,1,2,3,1,2,3,2,1,1,3]), + array([2,4,3,3,4,3,3,4,4,1,2,1]), + array([3,5,4,3,4,4,3,3,3,4,4,4])] + + # From Jerrorl H. Zar, "Biostatistical Analysis"(example 12.6), + # Xf=10.68, 0.005 < p < 0.01: + # Probability from this example is inexact + # using Chisquare approximation of Friedman Chisquare. + x3 = [array([7.0,9.9,8.5,5.1,10.3]), + array([5.3,5.7,4.7,3.5,7.7]), + array([4.9,7.6,5.5,2.8,8.4]), + array([8.8,8.9,8.1,3.3,9.1])] + + assert_array_almost_equal(stats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]), + (10.2283464566929, 0.0167215803284414)) + assert_array_almost_equal(stats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]), + (18.9428571428571, 0.000280938375189499)) + assert_array_almost_equal(stats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]), + (10.68, 0.0135882729582176)) + assert_raises(ValueError, stats.friedmanchisquare,x3[0],x3[1]) + + # test for namedtuple attribute results + attributes = ('statistic', 'pvalue') + res = stats.friedmanchisquare(*x1) + check_named_results(res, attributes) + + # test using mstats + assert_array_almost_equal(mstats.friedmanchisquare(x1[0], x1[1], + x1[2], x1[3]), + (10.2283464566929, 0.0167215803284414)) + # the following fails + # assert_array_almost_equal(mstats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]), + # (18.9428571428571, 0.000280938375189499)) + assert_array_almost_equal(mstats.friedmanchisquare(x3[0], x3[1], + x3[2], x3[3]), + (10.68, 0.0135882729582176)) + assert_raises(ValueError, mstats.friedmanchisquare,x3[0],x3[1]) + + +class TestKSTest: + """Tests kstest and ks_1samp agree with K-S various sizes, alternatives, modes.""" + + def _testOne(self, x, alternative, expected_statistic, expected_prob, + mode='auto', decimal=14): + result = stats.kstest(x, 'norm', alternative=alternative, mode=mode) + expected = np.array([expected_statistic, expected_prob]) + assert_array_almost_equal(np.array(result), expected, decimal=decimal) + + def _test_kstest_and_ks1samp(self, x, alternative, mode='auto', decimal=14): + result = stats.kstest(x, 'norm', alternative=alternative, mode=mode) + result_1samp = stats.ks_1samp(x, stats.norm.cdf, + alternative=alternative, mode=mode) + assert_array_almost_equal(np.array(result), result_1samp, decimal=decimal) + + def test_namedtuple_attributes(self): + x = np.linspace(-1, 1, 9) + # test for namedtuple attribute results + attributes = ('statistic', 'pvalue') + res = stats.kstest(x, 'norm') + check_named_results(res, attributes) + + def test_agree_with_ks_1samp(self): + x = np.linspace(-1, 1, 9) + self._test_kstest_and_ks1samp(x, 'two-sided') + + x = np.linspace(-15, 15, 9) + self._test_kstest_and_ks1samp(x, 'two-sided') + + x = [-1.23, 0.06, -0.60, 0.17, 0.66, -0.17, -0.08, 0.27, -0.98, -0.99] + self._test_kstest_and_ks1samp(x, 'two-sided') + self._test_kstest_and_ks1samp(x, 'greater', mode='exact') + self._test_kstest_and_ks1samp(x, 'less', mode='exact') + + def test_pm_inf_gh20386(self): + # Check that gh-20386 is resolved - `kstest` does not + # return NaNs when both -inf and inf are in sample. + vals = [-np.inf, 0, 1, np.inf] + res = stats.kstest(vals, stats.cauchy.cdf) + ref = stats.kstest(vals, stats.cauchy.cdf, _no_deco=True) + assert np.all(np.isfinite(res)) + assert_equal(res, ref) + assert not np.isnan(res.statistic) + assert not np.isnan(res.pvalue) + + # missing: no test that uses *args + + +class TestKSOneSample: + """ + Tests kstest and ks_samp 1-samples with K-S various sizes, alternatives, modes. + """ + + def _testOne(self, x, alternative, expected_statistic, expected_prob, + mode='auto', decimal=14): + result = stats.ks_1samp(x, stats.norm.cdf, alternative=alternative, mode=mode) + expected = np.array([expected_statistic, expected_prob]) + assert_array_almost_equal(np.array(result), expected, decimal=decimal) + + def test_namedtuple_attributes(self): + x = np.linspace(-1, 1, 9) + # test for namedtuple attribute results + attributes = ('statistic', 'pvalue') + res = stats.ks_1samp(x, stats.norm.cdf) + check_named_results(res, attributes) + + def test_agree_with_r(self): + # comparing with some values from R + x = np.linspace(-1, 1, 9) + self._testOne(x, 'two-sided', 0.15865525393145705, 0.95164069201518386) + + x = np.linspace(-15, 15, 9) + self._testOne(x, 'two-sided', 0.44435602715924361, 0.038850140086788665) + + x = [-1.23, 0.06, -0.60, 0.17, 0.66, -0.17, -0.08, 0.27, -0.98, -0.99] + self._testOne(x, 'two-sided', 0.293580126801961, 0.293408463684361) + self._testOne(x, 'greater', 0.293580126801961, 0.146988835042376, mode='exact') + self._testOne(x, 'less', 0.109348552425692, 0.732768892470675, mode='exact') + + def test_known_examples(self): + # the following tests rely on deterministically replicated rvs + x = stats.norm.rvs(loc=0.2, size=100, random_state=987654321) + self._testOne(x, 'two-sided', 0.12464329735846891, 0.089444888711820769, + mode='asymp') + self._testOne(x, 'less', 0.12464329735846891, 0.040989164077641749) + self._testOne(x, 'greater', 0.0072115233216310994, 0.98531158590396228) + + def test_ks1samp_allpaths(self): + # Check NaN input, output. + assert_(np.isnan(kolmogn(np.nan, 1, True))) + with assert_raises(ValueError, match='n is not integral: 1.5'): + kolmogn(1.5, 1, True) + assert_(np.isnan(kolmogn(-1, 1, True))) + + dataset = np.asarray([ + # Check x out of range + (101, 1, True, 1.0), + (101, 1.1, True, 1.0), + (101, 0, True, 0.0), + (101, -0.1, True, 0.0), + + (32, 1.0 / 64, True, 0.0), # Ruben-Gambino + (32, 1.0 / 64, False, 1.0), # Ruben-Gambino + + # Miller + (32, 0.5, True, 0.9999999363163307), + # Miller 2 * special.smirnov(32, 0.5) + (32, 0.5, False, 6.368366937916623e-08), + + # Check some other paths + (32, 1.0 / 8, True, 0.34624229979775223), + (32, 1.0 / 4, True, 0.9699508336558085), + (1600, 0.49, False, 0.0), + # 2 * special.smirnov(1600, 1/16.0) + (1600, 1 / 16.0, False, 7.0837876229702195e-06), + # _kolmogn_DMTW + (1600, 14 / 1600, False, 0.99962357317602), + # _kolmogn_PelzGood + (1600, 1 / 32, False, 0.08603386296651416), + ]) + FuncData(kolmogn, dataset, (0, 1, 2), 3).check(dtypes=[int, float, bool]) + + @pytest.mark.parametrize("ksfunc", [stats.kstest, stats.ks_1samp]) + @pytest.mark.parametrize("alternative, x6val, ref_location, ref_sign", + [('greater', 6, 6, +1), + ('less', 7, 7, -1), + ('two-sided', 6, 6, +1), + ('two-sided', 7, 7, -1)]) + def test_location_sign(self, ksfunc, alternative, + x6val, ref_location, ref_sign): + # Test that location and sign corresponding with statistic are as + # expected. (Test is designed to be easy to predict.) + x = np.arange(10) + 0.5 + x[6] = x6val + cdf = stats.uniform(scale=10).cdf + res = ksfunc(x, cdf, alternative=alternative) + assert_allclose(res.statistic, 0.1, rtol=1e-15) + assert res.statistic_location == ref_location + assert res.statistic_sign == ref_sign + + # missing: no test that uses *args + + +class TestKSTwoSamples: + """Tests 2-samples with K-S various sizes, alternatives, modes.""" + + def _testOne(self, x1, x2, alternative, expected_statistic, expected_prob, + mode='auto'): + result = stats.ks_2samp(x1, x2, alternative, mode=mode) + expected = np.array([expected_statistic, expected_prob]) + assert_array_almost_equal(np.array(result), expected) + + def testSmall(self): + self._testOne([0], [1], 'two-sided', 1.0/1, 1.0) + self._testOne([0], [1], 'greater', 1.0/1, 0.5) + self._testOne([0], [1], 'less', 0.0/1, 1.0) + self._testOne([1], [0], 'two-sided', 1.0/1, 1.0) + self._testOne([1], [0], 'greater', 0.0/1, 1.0) + self._testOne([1], [0], 'less', 1.0/1, 0.5) + + def testTwoVsThree(self): + data1 = np.array([1.0, 2.0]) + data1p = data1 + 0.01 + data1m = data1 - 0.01 + data2 = np.array([1.0, 2.0, 3.0]) + self._testOne(data1p, data2, 'two-sided', 1.0 / 3, 1.0) + self._testOne(data1p, data2, 'greater', 1.0 / 3, 0.7) + self._testOne(data1p, data2, 'less', 1.0 / 3, 0.7) + self._testOne(data1m, data2, 'two-sided', 2.0 / 3, 0.6) + self._testOne(data1m, data2, 'greater', 2.0 / 3, 0.3) + self._testOne(data1m, data2, 'less', 0, 1.0) + + def testTwoVsFour(self): + data1 = np.array([1.0, 2.0]) + data1p = data1 + 0.01 + data1m = data1 - 0.01 + data2 = np.array([1.0, 2.0, 3.0, 4.0]) + self._testOne(data1p, data2, 'two-sided', 2.0 / 4, 14.0/15) + self._testOne(data1p, data2, 'greater', 2.0 / 4, 8.0/15) + self._testOne(data1p, data2, 'less', 1.0 / 4, 12.0/15) + + self._testOne(data1m, data2, 'two-sided', 3.0 / 4, 6.0/15) + self._testOne(data1m, data2, 'greater', 3.0 / 4, 3.0/15) + self._testOne(data1m, data2, 'less', 0, 1.0) + + def test100_100(self): + x100 = np.linspace(1, 100, 100) + x100_2_p1 = x100 + 2 + 0.1 + x100_2_m1 = x100 + 2 - 0.1 + self._testOne(x100, x100_2_p1, 'two-sided', 3.0 / 100, 0.9999999999962055) + self._testOne(x100, x100_2_p1, 'greater', 3.0 / 100, 0.9143290114276248) + self._testOne(x100, x100_2_p1, 'less', 0, 1.0) + self._testOne(x100, x100_2_m1, 'two-sided', 2.0 / 100, 1.0) + self._testOne(x100, x100_2_m1, 'greater', 2.0 / 100, 0.960978450786184) + self._testOne(x100, x100_2_m1, 'less', 0, 1.0) + + def test100_110(self): + x100 = np.linspace(1, 100, 100) + x110 = np.linspace(1, 100, 110) + x110_20_p1 = x110 + 20 + 0.1 + x110_20_m1 = x110 + 20 - 0.1 + # 100, 110 + self._testOne(x100, x110_20_p1, 'two-sided', 232.0 / 1100, 0.015739183865607353) + self._testOne(x100, x110_20_p1, 'greater', 232.0 / 1100, 0.007869594319053203) + self._testOne(x100, x110_20_p1, 'less', 0, 1) + self._testOne(x100, x110_20_m1, 'two-sided', 229.0 / 1100, 0.017803803861026313) + self._testOne(x100, x110_20_m1, 'greater', 229.0 / 1100, 0.008901905958245056) + self._testOne(x100, x110_20_m1, 'less', 0.0, 1.0) + + def testRepeatedValues(self): + x2233 = np.array([2] * 3 + [3] * 4 + [5] * 5 + [6] * 4, dtype=int) + x3344 = x2233 + 1 + x2356 = np.array([2] * 3 + [3] * 4 + [5] * 10 + [6] * 4, dtype=int) + x3467 = np.array([3] * 10 + [4] * 2 + [6] * 10 + [7] * 4, dtype=int) + self._testOne(x2233, x3344, 'two-sided', 5.0/16, 0.4262934613454952) + self._testOne(x2233, x3344, 'greater', 5.0/16, 0.21465428276573786) + self._testOne(x2233, x3344, 'less', 0.0/16, 1.0) + self._testOne(x2356, x3467, 'two-sided', 190.0/21/26, 0.0919245790168125) + self._testOne(x2356, x3467, 'greater', 190.0/21/26, 0.0459633806858544) + self._testOne(x2356, x3467, 'less', 70.0/21/26, 0.6121593130022775) + + def testEqualSizes(self): + data2 = np.array([1.0, 2.0, 3.0]) + self._testOne(data2, data2+1, 'two-sided', 1.0/3, 1.0) + self._testOne(data2, data2+1, 'greater', 1.0/3, 0.75) + self._testOne(data2, data2+1, 'less', 0.0/3, 1.) + self._testOne(data2, data2+0.5, 'two-sided', 1.0/3, 1.0) + self._testOne(data2, data2+0.5, 'greater', 1.0/3, 0.75) + self._testOne(data2, data2+0.5, 'less', 0.0/3, 1.) + self._testOne(data2, data2-0.5, 'two-sided', 1.0/3, 1.0) + self._testOne(data2, data2-0.5, 'greater', 0.0/3, 1.0) + self._testOne(data2, data2-0.5, 'less', 1.0/3, 0.75) + + @pytest.mark.slow + def testMiddlingBoth(self): + # 500, 600 + n1, n2 = 500, 600 + delta = 1.0/n1/n2/2/2 + x = np.linspace(1, 200, n1) - delta + y = np.linspace(2, 200, n2) + self._testOne(x, y, 'two-sided', 2000.0 / n1 / n2, 1.0, + mode='auto') + self._testOne(x, y, 'two-sided', 2000.0 / n1 / n2, 1.0, + mode='asymp') + self._testOne(x, y, 'greater', 2000.0 / n1 / n2, 0.9697596024683929, + mode='asymp') + self._testOne(x, y, 'less', 500.0 / n1 / n2, 0.9968735843165021, + mode='asymp') + with suppress_warnings() as sup: + message = "ks_2samp: Exact calculation unsuccessful." + sup.filter(RuntimeWarning, message) + self._testOne(x, y, 'greater', 2000.0 / n1 / n2, 0.9697596024683929, + mode='exact') + self._testOne(x, y, 'less', 500.0 / n1 / n2, 0.9968735843165021, + mode='exact') + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + self._testOne(x, y, 'less', 500.0 / n1 / n2, 0.9968735843165021, + mode='exact') + _check_warnings(w, RuntimeWarning, 1) + + @pytest.mark.slow + def testMediumBoth(self): + # 1000, 1100 + n1, n2 = 1000, 1100 + delta = 1.0/n1/n2/2/2 + x = np.linspace(1, 200, n1) - delta + y = np.linspace(2, 200, n2) + self._testOne(x, y, 'two-sided', 6600.0 / n1 / n2, 1.0, + mode='asymp') + self._testOne(x, y, 'two-sided', 6600.0 / n1 / n2, 1.0, + mode='auto') + self._testOne(x, y, 'greater', 6600.0 / n1 / n2, 0.9573185808092622, + mode='asymp') + self._testOne(x, y, 'less', 1000.0 / n1 / n2, 0.9982410869433984, + mode='asymp') + + with suppress_warnings() as sup: + message = "ks_2samp: Exact calculation unsuccessful." + sup.filter(RuntimeWarning, message) + self._testOne(x, y, 'greater', 6600.0 / n1 / n2, 0.9573185808092622, + mode='exact') + self._testOne(x, y, 'less', 1000.0 / n1 / n2, 0.9982410869433984, + mode='exact') + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + self._testOne(x, y, 'less', 1000.0 / n1 / n2, 0.9982410869433984, + mode='exact') + _check_warnings(w, RuntimeWarning, 1) + + def testLarge(self): + # 10000, 110 + n1, n2 = 10000, 110 + lcm = n1*11.0 + delta = 1.0/n1/n2/2/2 + x = np.linspace(1, 200, n1) - delta + y = np.linspace(2, 100, n2) + self._testOne(x, y, 'two-sided', 55275.0 / lcm, 4.2188474935755949e-15) + self._testOne(x, y, 'greater', 561.0 / lcm, 0.99115454582047591) + self._testOne(x, y, 'less', 55275.0 / lcm, 3.1317328311518713e-26) + + def test_gh11184(self): + # 3000, 3001, exact two-sided + np.random.seed(123456) + x = np.random.normal(size=3000) + y = np.random.normal(size=3001) * 1.5 + self._testOne(x, y, 'two-sided', 0.11292880151060758, 2.7755575615628914e-15, + mode='asymp') + self._testOne(x, y, 'two-sided', 0.11292880151060758, 2.7755575615628914e-15, + mode='exact') + + @pytest.mark.xslow + def test_gh11184_bigger(self): + # 10000, 10001, exact two-sided + np.random.seed(123456) + x = np.random.normal(size=10000) + y = np.random.normal(size=10001) * 1.5 + self._testOne(x, y, 'two-sided', 0.10597913208679133, 3.3149311398483503e-49, + mode='asymp') + self._testOne(x, y, 'two-sided', 0.10597913208679133, 2.7755575615628914e-15, + mode='exact') + self._testOne(x, y, 'greater', 0.10597913208679133, 2.7947433906389253e-41, + mode='asymp') + self._testOne(x, y, 'less', 0.09658002199780022, 2.7947433906389253e-41, + mode='asymp') + + @pytest.mark.xslow + def test_gh12999(self): + np.random.seed(123456) + for x in range(1000, 12000, 1000): + vals1 = np.random.normal(size=(x)) + vals2 = np.random.normal(size=(x + 10), loc=0.5) + exact = stats.ks_2samp(vals1, vals2, mode='exact').pvalue + asymp = stats.ks_2samp(vals1, vals2, mode='asymp').pvalue + # these two p-values should be in line with each other + assert_array_less(exact, 3 * asymp) + assert_array_less(asymp, 3 * exact) + + @pytest.mark.slow + def testLargeBoth(self): + # 10000, 11000 + n1, n2 = 10000, 11000 + lcm = n1*11.0 + delta = 1.0/n1/n2/2/2 + x = np.linspace(1, 200, n1) - delta + y = np.linspace(2, 200, n2) + self._testOne(x, y, 'two-sided', 563.0 / lcm, 0.9990660108966576, + mode='asymp') + self._testOne(x, y, 'two-sided', 563.0 / lcm, 0.9990456491488628, + mode='exact') + self._testOne(x, y, 'two-sided', 563.0 / lcm, 0.9990660108966576, + mode='auto') + self._testOne(x, y, 'greater', 563.0 / lcm, 0.7561851877420673) + self._testOne(x, y, 'less', 10.0 / lcm, 0.9998239693191724) + with suppress_warnings() as sup: + message = "ks_2samp: Exact calculation unsuccessful." + sup.filter(RuntimeWarning, message) + self._testOne(x, y, 'greater', 563.0 / lcm, 0.7561851877420673, + mode='exact') + self._testOne(x, y, 'less', 10.0 / lcm, 0.9998239693191724, + mode='exact') + + def testNamedAttributes(self): + # test for namedtuple attribute results + attributes = ('statistic', 'pvalue') + res = stats.ks_2samp([1, 2], [3]) + check_named_results(res, attributes) + + @pytest.mark.slow + def test_some_code_paths(self): + # Check that some code paths are executed + from scipy.stats._stats_py import ( + _count_paths_outside_method, + _compute_outer_prob_inside_method + ) + + _compute_outer_prob_inside_method(1, 1, 1, 1) + _count_paths_outside_method(1000, 1, 1, 1001) + + with np.errstate(invalid='raise'): + assert_raises(FloatingPointError, _count_paths_outside_method, + 1100, 1099, 1, 1) + assert_raises(FloatingPointError, _count_paths_outside_method, + 2000, 1000, 1, 1) + + @pytest.mark.parametrize('case', (([], [1]), ([1], []), ([], []))) + def test_argument_checking(self, case): + # Check that an empty array warns + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.ks_2samp(*case) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + @pytest.mark.xslow + def test_gh12218(self): + """Ensure gh-12218 is fixed.""" + # gh-1228 triggered a TypeError calculating sqrt(n1*n2*(n1+n2)). + # n1, n2 both large integers, the product exceeded 2^64 + np.random.seed(12345678) + n1 = 2097152 # 2*^21 + rvs1 = stats.uniform.rvs(size=n1, loc=0., scale=1) + rvs2 = rvs1 + 1 # Exact value of rvs2 doesn't matter. + stats.ks_2samp(rvs1, rvs2, alternative='greater', mode='asymp') + stats.ks_2samp(rvs1, rvs2, alternative='less', mode='asymp') + stats.ks_2samp(rvs1, rvs2, alternative='two-sided', mode='asymp') + + def test_warnings_gh_14019(self): + # Check that RuntimeWarning is raised when method='auto' and exact + # p-value calculation fails. See gh-14019. + rng = np.random.RandomState(seed=23493549) + # random samples of the same size as in the issue + data1 = rng.random(size=881) + 0.5 + data2 = rng.random(size=369) + message = "ks_2samp: Exact calculation unsuccessful" + with pytest.warns(RuntimeWarning, match=message): + res = stats.ks_2samp(data1, data2, alternative='less') + assert_allclose(res.pvalue, 0, atol=1e-14) + + @pytest.mark.parametrize("ksfunc", [stats.kstest, stats.ks_2samp]) + @pytest.mark.parametrize("alternative, x6val, ref_location, ref_sign", + [('greater', 5.9, 5.9, +1), + ('less', 6.1, 6.0, -1), + ('two-sided', 5.9, 5.9, +1), + ('two-sided', 6.1, 6.0, -1)]) + def test_location_sign(self, ksfunc, alternative, + x6val, ref_location, ref_sign): + # Test that location and sign corresponding with statistic are as + # expected. (Test is designed to be easy to predict.) + x = np.arange(10, dtype=np.float64) + y = x.copy() + x[6] = x6val + res = stats.ks_2samp(x, y, alternative=alternative) + assert res.statistic == 0.1 + assert res.statistic_location == ref_location + assert res.statistic_sign == ref_sign + + +def test_ttest_rel(): + # regression test + tr,pr = 0.81248591389165692, 0.41846234511362157 + tpr = ([tr,-tr],[pr,pr]) + + rvs1 = np.linspace(1,100,100) + rvs2 = np.linspace(1.01,99.989,100) + rvs1_2D = np.array([np.linspace(1,100,100), np.linspace(1.01,99.989,100)]) + rvs2_2D = np.array([np.linspace(1.01,99.989,100), np.linspace(1,100,100)]) + + t,p = stats.ttest_rel(rvs1, rvs2, axis=0) + assert_array_almost_equal([t,p],(tr,pr)) + t,p = stats.ttest_rel(rvs1_2D.T, rvs2_2D.T, axis=0) + assert_array_almost_equal([t,p],tpr) + t,p = stats.ttest_rel(rvs1_2D, rvs2_2D, axis=1) + assert_array_almost_equal([t,p],tpr) + + # test scalars + with suppress_warnings() as sup, \ + np.errstate(invalid="ignore", divide="ignore"): + sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice") + t, p = stats.ttest_rel(4., 3.) + assert_(np.isnan(t)) + assert_(np.isnan(p)) + + # test for namedtuple attribute results + attributes = ('statistic', 'pvalue') + res = stats.ttest_rel(rvs1, rvs2, axis=0) + check_named_results(res, attributes) + + # test on 3 dimensions + rvs1_3D = np.dstack([rvs1_2D,rvs1_2D,rvs1_2D]) + rvs2_3D = np.dstack([rvs2_2D,rvs2_2D,rvs2_2D]) + t,p = stats.ttest_rel(rvs1_3D, rvs2_3D, axis=1) + assert_array_almost_equal(np.abs(t), tr) + assert_array_almost_equal(np.abs(p), pr) + assert_equal(t.shape, (2, 3)) + + t, p = stats.ttest_rel(np.moveaxis(rvs1_3D, 2, 0), + np.moveaxis(rvs2_3D, 2, 0), + axis=2) + assert_array_almost_equal(np.abs(t), tr) + assert_array_almost_equal(np.abs(p), pr) + assert_equal(t.shape, (3, 2)) + + # test alternative parameter + assert_raises(ValueError, stats.ttest_rel, rvs1, rvs2, alternative="error") + + t, p = stats.ttest_rel(rvs1, rvs2, axis=0, alternative="less") + assert_allclose(p, 1 - pr/2) + assert_allclose(t, tr) + + t, p = stats.ttest_rel(rvs1, rvs2, axis=0, alternative="greater") + assert_allclose(p, pr/2) + assert_allclose(t, tr) + + # check nan policy + rng = np.random.RandomState(12345678) + x = stats.norm.rvs(loc=5, scale=10, size=501, random_state=rng) + x[500] = np.nan + y = (stats.norm.rvs(loc=5, scale=10, size=501, random_state=rng) + + stats.norm.rvs(scale=0.2, size=501, random_state=rng)) + y[500] = np.nan + + with np.errstate(invalid="ignore"): + assert_array_equal(stats.ttest_rel(x, x), (np.nan, np.nan)) + + assert_array_almost_equal(stats.ttest_rel(x, y, nan_policy='omit'), + (0.25299925303978066, 0.8003729814201519)) + assert_raises(ValueError, stats.ttest_rel, x, y, nan_policy='raise') + assert_raises(ValueError, stats.ttest_rel, x, y, nan_policy='foobar') + + # test zero division problem + with pytest.warns(RuntimeWarning, match="Precision loss occurred"): + t, p = stats.ttest_rel([0, 0, 0], [1, 1, 1]) + assert_equal((np.abs(t), p), (np.inf, 0)) + with np.errstate(invalid="ignore"): + assert_equal(stats.ttest_rel([0, 0, 0], [0, 0, 0]), (np.nan, np.nan)) + + # check that nan in input array result in nan output + anan = np.array([[1, np.nan], [-1, 1]]) + assert_equal(stats.ttest_rel(anan, np.zeros((2, 2))), + ([0, np.nan], [1, np.nan])) + + # test incorrect input shape raise an error + x = np.arange(24) + assert_raises(ValueError, stats.ttest_rel, x.reshape((8, 3)), + x.reshape((2, 3, 4))) + + # Convert from two-sided p-values to one sided using T result data. + def convert(t, p, alt): + if (t < 0 and alt == "less") or (t > 0 and alt == "greater"): + return p / 2 + return 1 - (p / 2) + converter = np.vectorize(convert) + + rvs1_2D[:, 20:30] = np.nan + rvs2_2D[:, 15:25] = np.nan + + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + tr, pr = stats.ttest_rel(rvs1_2D, rvs2_2D, 0, nan_policy='omit') + + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + t, p = stats.ttest_rel(rvs1_2D, rvs2_2D, 0, + nan_policy='omit', alternative='less') + assert_allclose(t, tr, rtol=1e-14) + with np.errstate(invalid='ignore'): + assert_allclose(p, converter(tr, pr, 'less'), rtol=1e-14) + + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + t, p = stats.ttest_rel(rvs1_2D, rvs2_2D, 0, + nan_policy='omit', alternative='greater') + assert_allclose(t, tr, rtol=1e-14) + with np.errstate(invalid='ignore'): + assert_allclose(p, converter(tr, pr, 'greater'), rtol=1e-14) + + +def test_ttest_rel_nan_2nd_arg(): + # regression test for gh-6134: nans in the second arg were not handled + x = [np.nan, 2.0, 3.0, 4.0] + y = [1.0, 2.0, 1.0, 2.0] + + r1 = stats.ttest_rel(x, y, nan_policy='omit') + r2 = stats.ttest_rel(y, x, nan_policy='omit') + assert_allclose(r2.statistic, -r1.statistic, atol=1e-15) + assert_allclose(r2.pvalue, r1.pvalue, atol=1e-15) + + # NB: arguments are paired when NaNs are dropped + r3 = stats.ttest_rel(y[1:], x[1:]) + assert_allclose(r2, r3, atol=1e-15) + + # .. and this is consistent with R. R code: + # x = c(NA, 2.0, 3.0, 4.0) + # y = c(1.0, 2.0, 1.0, 2.0) + # t.test(x, y, paired=TRUE) + assert_allclose(r2, (-2, 0.1835), atol=1e-4) + + +def test_ttest_rel_empty_1d_returns_nan(): + # Two empty inputs should return a TtestResult containing nan + # for both values. + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + result = stats.ttest_rel([], []) + assert isinstance(result, stats._stats_py.TtestResult) + assert_equal(result, (np.nan, np.nan)) + + +@pytest.mark.parametrize('b, expected_shape', + [(np.empty((1, 5, 0)), (3, 5)), + (np.empty((1, 0, 0)), (3, 0))]) +def test_ttest_rel_axis_size_zero(b, expected_shape): + # In this test, the length of the axis dimension is zero. + # The results should be arrays containing nan with shape + # given by the broadcast nonaxis dimensions. + a = np.empty((3, 1, 0)) + with np.testing.suppress_warnings() as sup: + # first case should warn, second shouldn't? + sup.filter(SmallSampleWarning, too_small_nd_not_omit) + result = stats.ttest_rel(a, b, axis=-1) + assert isinstance(result, stats._stats_py.TtestResult) + expected_value = np.full(expected_shape, fill_value=np.nan) + assert_equal(result.statistic, expected_value) + assert_equal(result.pvalue, expected_value) + + +def test_ttest_rel_nonaxis_size_zero(): + # In this test, the length of the axis dimension is nonzero, + # but one of the nonaxis dimensions has length 0. Check that + # we still get the correctly broadcast shape, which is (5, 0) + # in this case. + a = np.empty((1, 8, 0)) + b = np.empty((5, 8, 1)) + result = stats.ttest_rel(a, b, axis=1) + assert isinstance(result, stats._stats_py.TtestResult) + assert_equal(result.statistic.shape, (5, 0)) + assert_equal(result.pvalue.shape, (5, 0)) + + +@pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater']) +def test_ttest_rel_ci_1d(alternative): + # test confidence interval method against reference values + rng = np.random.default_rng(3749065329432213059) + n = 10 + x = rng.normal(size=n, loc=1.5, scale=2) + y = rng.normal(size=n, loc=2, scale=2) + # Reference values generated with R t.test: + # options(digits=16) + # x = c(1.22825792, 1.63950485, 4.39025641, 0.68609437, 2.03813481, + # -1.20040109, 1.81997937, 1.86854636, 2.94694282, 3.94291373) + # y = c(3.49961496, 1.53192536, 5.53620083, 2.91687718, 0.04858043, + # 3.78505943, 3.3077496 , 2.30468892, 3.42168074, 0.56797592) + # t.test(x, y, paired=TRUE, conf.level=0.85, alternative='l') + + ref = {'two-sided': [-1.912194489914035, 0.400169725914035], + 'greater': [-1.563944820311475, np.inf], + 'less': [-np.inf, 0.05192005631147523]} + res = stats.ttest_rel(x, y, alternative=alternative) + ci = res.confidence_interval(confidence_level=0.85) + assert_allclose(ci, ref[alternative]) + assert_equal(res.df, n-1) + + +@pytest.mark.parametrize("test_fun, args", + [(stats.ttest_1samp, (np.arange(10), 0)), + (stats.ttest_rel, (np.arange(10), np.arange(10)))]) +def test_ttest_ci_iv(test_fun, args): + # test `confidence_interval` method input validation + res = test_fun(*args) + message = '`confidence_level` must be a number between 0 and 1.' + with pytest.raises(ValueError, match=message): + res.confidence_interval(confidence_level=10) + + +def _desc_stats(x1, x2, axis=0, *, xp=None): + xp = array_namespace(x1, x2) if xp is None else xp + + def _stats(x, axis=0): + x = xp.asarray(x) + mu = xp.mean(x, axis=axis) + std = xp.std(x, axis=axis, correction=1) + nobs = x.shape[axis] + return mu, std, nobs + + return _stats(x1, axis) + _stats(x2, axis) + + +@array_api_compatible +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +def test_ttest_ind(xp): + # regression test + tr = xp.asarray(1.0912746897927283) + pr = xp.asarray(0.27647818616351882) + tr_2D = xp.asarray([tr, -tr]) + pr_2D = xp.asarray([pr, pr]) + + rvs1 = xp.linspace(5, 105, 100) + rvs2 = xp.linspace(1, 100, 100) + rvs1_2D = xp.stack([rvs1, rvs2]) + rvs2_2D = xp.stack([rvs2, rvs1]) + + res = stats.ttest_ind(rvs1, rvs2, axis=0) + t, p = res # check that result object can be unpacked + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + res = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2)) + t, p = res # check that result object can be unpacked + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + res = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + res = stats.ttest_ind_from_stats(*_desc_stats(rvs1_2D.T, rvs2_2D.T)) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + res = stats.ttest_ind(rvs1_2D, rvs2_2D, axis=1) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + res = stats.ttest_ind_from_stats(*_desc_stats(rvs1_2D, rvs2_2D, axis=1)) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + # test on 3 dimensions removed because generic tests in + # test_axis_nan_policy are much stronger + + # test alternative parameter + message = "`alternative` must be 'less', 'greater', or 'two-sided'." + with pytest.raises(ValueError, match=message): + stats.ttest_ind(rvs1, rvs2, alternative = "error") + + args = _desc_stats(rvs1_2D.T, rvs2_2D.T) + with pytest.raises(ValueError, match=message): + stats.ttest_ind_from_stats(*args, alternative = "error") + + t, p = stats.ttest_ind(rvs1, rvs2, alternative="less") + xp_assert_close(p, 1 - (pr/2)) + xp_assert_close(t, tr) + + t, p = stats.ttest_ind(rvs1, rvs2, alternative="greater") + xp_assert_close(p, pr/2) + xp_assert_close(t, tr) + + # Check that ttest_ind_from_stats agrees with ttest_ind + res1 = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0, alternative="less") + args = _desc_stats(rvs1_2D.T, rvs2_2D.T) + res2 = stats.ttest_ind_from_stats(*args, alternative="less") + xp_assert_close(res1.statistic, res2.statistic) + xp_assert_close(res1.pvalue, res2.pvalue) + + res1 = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0, alternative="less") + args = _desc_stats(rvs1_2D.T, rvs2_2D.T) + res2 = stats.ttest_ind_from_stats(*args, alternative="less") + xp_assert_close(res1.statistic, res2.statistic) + xp_assert_close(res1.pvalue, res2.pvalue) + + # test NaNs + NaN = xp.asarray(xp.nan) + rvs1 = xp.where(xp.arange(rvs1.shape[0]) == 0, NaN, rvs1) + + res = stats.ttest_ind(rvs1, rvs2, axis=0) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + + res = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2)) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + + +def test_ttest_ind_nan_policy(): + rvs1 = np.linspace(5, 105, 100) + rvs2 = np.linspace(1, 100, 100) + rvs1_2D = np.array([rvs1, rvs2]) + rvs2_2D = np.array([rvs2, rvs1]) + rvs1_3D = np.dstack([rvs1_2D, rvs1_2D, rvs1_2D]) + rvs2_3D = np.dstack([rvs2_2D, rvs2_2D, rvs2_2D]) + + # check nan policy + rng = np.random.RandomState(12345678) + x = stats.norm.rvs(loc=5, scale=10, size=501, random_state=rng) + x[500] = np.nan + y = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng) + + with np.errstate(invalid="ignore"): + assert_array_equal(stats.ttest_ind(x, y), (np.nan, np.nan)) + + assert_array_almost_equal(stats.ttest_ind(x, y, nan_policy='omit'), + (0.24779670949091914, 0.80434267337517906)) + assert_raises(ValueError, stats.ttest_ind, x, y, nan_policy='raise') + assert_raises(ValueError, stats.ttest_ind, x, y, nan_policy='foobar') + + # test zero division problem + with pytest.warns(RuntimeWarning, match="Precision loss occurred"): + t, p = stats.ttest_ind([0, 0, 0], [1, 1, 1]) + assert_equal((np.abs(t), p), (np.inf, 0)) + + with np.errstate(invalid="ignore"): + assert_equal(stats.ttest_ind([0, 0, 0], [0, 0, 0]), (np.nan, np.nan)) + + # check that nan in input array result in nan output + anan = np.array([[1, np.nan], [-1, 1]]) + assert_equal(stats.ttest_ind(anan, np.zeros((2, 2))), + ([0, np.nan], [1, np.nan])) + + rvs1_3D[:, :, 10:15] = np.nan + rvs2_3D[:, :, 6:12] = np.nan + + # Convert from two-sided p-values to one sided using T result data. + def convert(t, p, alt): + if (t < 0 and alt == "less") or (t > 0 and alt == "greater"): + return p / 2 + return 1 - (p / 2) + converter = np.vectorize(convert) + + tr, pr = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=0, nan_policy='omit') + + t, p = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=0, nan_policy='omit', + alternative='less') + assert_allclose(t, tr, rtol=1e-14) + assert_allclose(p, converter(tr, pr, 'less'), rtol=1e-14) + + t, p = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=0, nan_policy='omit', + alternative='greater') + assert_allclose(t, tr, rtol=1e-14) + assert_allclose(p, converter(tr, pr, 'greater'), rtol=1e-14) + + +def test_ttest_ind_scalar(): + # test scalars + with suppress_warnings() as sup, np.errstate(invalid="ignore"): + sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice") + t, p = stats.ttest_ind(4., 3.) + assert np.isnan(t) + assert np.isnan(p) + + +@pytest.mark.filterwarnings("ignore:Arguments...:DeprecationWarning") +class Test_ttest_ind_permutations: + N = 20 + + # data for most tests + np.random.seed(0) + a = np.vstack((np.arange(3*N//4), np.random.random(3*N//4))) + b = np.vstack((np.arange(N//4) + 100, np.random.random(N//4))) + + # data for equal variance tests + a2 = np.arange(10) + b2 = np.arange(10) + 100 + + # data for exact test + a3 = [1, 2] + b3 = [3, 4] + + # data for bigger test + np.random.seed(0) + rvs1 = stats.norm.rvs(loc=5, scale=10, # type: ignore + size=500).reshape(100, 5).T + rvs2 = stats.norm.rvs(loc=8, scale=20, size=100) # type: ignore + + p_d = [1/1001, (676+1)/1001] # desired pvalues + p_d_gen = [1/1001, (672 + 1)/1001] # desired pvalues for Generator seed + p_d_big = [(993+1)/1001, (685+1)/1001, (840+1)/1001, + (955+1)/1001, (255+1)/1001] + + params = [ + (a, b, {"axis": 1}, p_d), # basic test + (a.T, b.T, {'axis': 0}, p_d), # along axis 0 + (a[0, :], b[0, :], {'axis': None}, p_d[0]), # 1d data + (a[0, :].tolist(), b[0, :].tolist(), {'axis': None}, p_d[0]), + # different seeds + (a, b, {'random_state': 0, "axis": 1}, p_d), + (a, b, {'random_state': np.random.RandomState(0), "axis": 1}, p_d), + (a2, b2, {'equal_var': True}, 1/1001), # equal variances + (rvs1, rvs2, {'axis': -1, 'random_state': 0}, p_d_big), # bigger test + (a3, b3, {}, 1/3), # exact test + (a, b, {'random_state': np.random.default_rng(0), "axis": 1}, p_d_gen), + ] + + @pytest.mark.parametrize("a,b,update,p_d", params) + def test_ttest_ind_permutations(self, a, b, update, p_d): + options_a = {'axis': None, 'equal_var': False} + options_p = {'axis': None, 'equal_var': False, + 'permutations': 1000, 'random_state': 0} + options_a.update(update) + options_p.update(update) + + stat_a, _ = stats.ttest_ind(a, b, **options_a) + stat_p, pvalue = stats.ttest_ind(a, b, **options_p) + assert_array_almost_equal(stat_a, stat_p, 5) + assert_array_almost_equal(pvalue, p_d) + + def test_ttest_ind_exact_alternative(self): + np.random.seed(0) + N = 3 + a = np.random.rand(2, N, 2) + b = np.random.rand(2, N, 2) + + options_p = {'axis': 1, 'permutations': 1000} + + options_p.update(alternative="greater") + res_g_ab = stats.ttest_ind(a, b, **options_p) + res_g_ba = stats.ttest_ind(b, a, **options_p) + + options_p.update(alternative="less") + res_l_ab = stats.ttest_ind(a, b, **options_p) + res_l_ba = stats.ttest_ind(b, a, **options_p) + + options_p.update(alternative="two-sided") + res_2_ab = stats.ttest_ind(a, b, **options_p) + res_2_ba = stats.ttest_ind(b, a, **options_p) + + # Alternative doesn't affect the statistic + assert_equal(res_g_ab.statistic, res_l_ab.statistic) + assert_equal(res_g_ab.statistic, res_2_ab.statistic) + + # Reversing order of inputs negates statistic + assert_equal(res_g_ab.statistic, -res_g_ba.statistic) + assert_equal(res_l_ab.statistic, -res_l_ba.statistic) + assert_equal(res_2_ab.statistic, -res_2_ba.statistic) + + # Reversing order of inputs does not affect p-value of 2-sided test + assert_equal(res_2_ab.pvalue, res_2_ba.pvalue) + + # In exact test, distribution is perfectly symmetric, so these + # identities are exactly satisfied. + assert_equal(res_g_ab.pvalue, res_l_ba.pvalue) + assert_equal(res_l_ab.pvalue, res_g_ba.pvalue) + mask = res_g_ab.pvalue <= 0.5 + assert_equal(res_g_ab.pvalue[mask] + res_l_ba.pvalue[mask], + res_2_ab.pvalue[mask]) + assert_equal(res_l_ab.pvalue[~mask] + res_g_ba.pvalue[~mask], + res_2_ab.pvalue[~mask]) + + def test_ttest_ind_exact_selection(self): + # test the various ways of activating the exact test + np.random.seed(0) + N = 3 + a = np.random.rand(N) + b = np.random.rand(N) + res0 = stats.ttest_ind(a, b) + res1 = stats.ttest_ind(a, b, permutations=1000) + res2 = stats.ttest_ind(a, b, permutations=0) + res3 = stats.ttest_ind(a, b, permutations=np.inf) + assert res1.pvalue != res0.pvalue + assert res2.pvalue == res0.pvalue + assert res3.pvalue == res1.pvalue + + def test_ttest_ind_exact_distribution(self): + # the exact distribution of the test statistic should have + # binom(na + nb, na) elements, all unique. This was not always true + # in gh-4824; fixed by gh-13661. + np.random.seed(0) + a = np.random.rand(3) + b = np.random.rand(4) + + data = np.concatenate((a, b)) + na, nb = len(a), len(b) + + permutations = 100000 + t_stat, _, _ = _permutation_distribution_t(data, permutations, na, + True) + + n_unique = len(set(t_stat)) + assert n_unique == binom(na + nb, na) + assert len(t_stat) == n_unique + + def test_ttest_ind_randperm_alternative(self): + np.random.seed(0) + N = 50 + a = np.random.rand(2, 3, N) + b = np.random.rand(3, N) + options_p = {'axis': -1, 'permutations': 1000, "random_state": 0} + + options_p.update(alternative="greater") + res_g_ab = stats.ttest_ind(a, b, **options_p) + res_g_ba = stats.ttest_ind(b, a, **options_p) + + options_p.update(alternative="less") + res_l_ab = stats.ttest_ind(a, b, **options_p) + res_l_ba = stats.ttest_ind(b, a, **options_p) + + # Alternative doesn't affect the statistic + assert_equal(res_g_ab.statistic, res_l_ab.statistic) + + # Reversing order of inputs negates statistic + assert_equal(res_g_ab.statistic, -res_g_ba.statistic) + assert_equal(res_l_ab.statistic, -res_l_ba.statistic) + + # For random permutations, the chance of ties between the observed + # test statistic and the population is small, so: + assert_equal(res_g_ab.pvalue + res_l_ab.pvalue, + 1 + 1/(options_p['permutations'] + 1)) + assert_equal(res_g_ba.pvalue + res_l_ba.pvalue, + 1 + 1/(options_p['permutations'] + 1)) + + @pytest.mark.slow() + def test_ttest_ind_randperm_alternative2(self): + np.random.seed(0) + N = 50 + a = np.random.rand(N, 4) + b = np.random.rand(N, 4) + options_p = {'permutations': 20000, "random_state": 0} + + options_p.update(alternative="greater") + res_g_ab = stats.ttest_ind(a, b, **options_p) + + options_p.update(alternative="less") + res_l_ab = stats.ttest_ind(a, b, **options_p) + + options_p.update(alternative="two-sided") + res_2_ab = stats.ttest_ind(a, b, **options_p) + + # For random permutations, the chance of ties between the observed + # test statistic and the population is small, so: + assert_equal(res_g_ab.pvalue + res_l_ab.pvalue, + 1 + 1/(options_p['permutations'] + 1)) + + # For for large sample sizes, the distribution should be approximately + # symmetric, so these identities should be approximately satisfied + mask = res_g_ab.pvalue <= 0.5 + assert_allclose(2 * res_g_ab.pvalue[mask], + res_2_ab.pvalue[mask], atol=2e-2) + assert_allclose(2 * (1-res_g_ab.pvalue[~mask]), + res_2_ab.pvalue[~mask], atol=2e-2) + assert_allclose(2 * res_l_ab.pvalue[~mask], + res_2_ab.pvalue[~mask], atol=2e-2) + assert_allclose(2 * (1-res_l_ab.pvalue[mask]), + res_2_ab.pvalue[mask], atol=2e-2) + + def test_ttest_ind_permutation_nanpolicy(self): + np.random.seed(0) + N = 50 + a = np.random.rand(N, 5) + b = np.random.rand(N, 5) + a[5, 1] = np.nan + b[8, 2] = np.nan + a[9, 3] = np.nan + b[9, 3] = np.nan + options_p = {'permutations': 1000, "random_state": 0} + + # Raise + options_p.update(nan_policy="raise") + with assert_raises(ValueError, match="The input contains nan values"): + res = stats.ttest_ind(a, b, **options_p) + + # Propagate + with suppress_warnings() as sup: + sup.record(RuntimeWarning, "invalid value*") + options_p.update(nan_policy="propagate") + res = stats.ttest_ind(a, b, **options_p) + + mask = np.isnan(a).any(axis=0) | np.isnan(b).any(axis=0) + res2 = stats.ttest_ind(a[:, ~mask], b[:, ~mask], **options_p) + + assert_equal(res.pvalue[mask], np.nan) + assert_equal(res.statistic[mask], np.nan) + + assert_allclose(res.pvalue[~mask], res2.pvalue) + assert_allclose(res.statistic[~mask], res2.statistic) + + # Propagate 1d + res = stats.ttest_ind(a.ravel(), b.ravel(), **options_p) + assert np.isnan(res.pvalue) # assert makes sure it's a scalar + assert np.isnan(res.statistic) + + def test_ttest_ind_permutation_check_inputs(self): + with assert_raises(ValueError, match="Permutations must be"): + stats.ttest_ind(self.a2, self.b2, permutations=-3) + with assert_raises(ValueError, match="Permutations must be"): + stats.ttest_ind(self.a2, self.b2, permutations=1.5) + with assert_raises(ValueError, match="'hello' cannot be used"): + stats.ttest_ind(self.a, self.b, permutations=1, + random_state='hello', axis=1) + + def test_ttest_ind_permutation_check_p_values(self): + # p-values should never be exactly zero + N = 10 + a = np.random.rand(N, 20) + b = np.random.rand(N, 20) + p_values = stats.ttest_ind(a, b, permutations=1).pvalue + print(0.0 not in p_values) + assert 0.0 not in p_values + + @pytest.mark.parametrize("alternative", ['less', 'greater', 'two-sided']) + @pytest.mark.parametrize("shape", [(12,), (2, 12)]) + def test_permutation_method(self, alternative, shape): + rng = np.random.default_rng(2348934579834565) + x = rng.random(size=shape) + y = rng.random(size=13) + + kwargs = dict(n_resamples=999) + + # Use ttest_ind with `method` + rng = np.random.default_rng(348934579834565) + method = stats.PermutationMethod(rng=rng, **kwargs) + res = stats.ttest_ind(x, y, axis=-1, alternative=alternative, method=method) + + # Use `permutation_test` directly + def statistic(x, y, axis): return stats.ttest_ind(x, y, axis=axis).statistic + rng = np.random.default_rng(348934579834565) + ref = stats.permutation_test((x, y), statistic, axis=-1, rng=rng, + alternative=alternative, **kwargs) + + assert_equal(res.statistic, ref.statistic) + assert_equal(res.pvalue, ref.pvalue) + + # Sanity check against theoretical t-test + ref = stats.ttest_ind(x, y, axis=-1, alternative=alternative) + assert_equal(res.statistic, ref.statistic) + assert_allclose(res.pvalue, ref.pvalue, rtol=3e-2) + + @pytest.mark.parametrize("alternative", ['less', 'greater', 'two-sided']) + @pytest.mark.parametrize("shape", [(12,), (2, 12)]) + def test_monte_carlo_method(self, alternative, shape): + rng = np.random.default_rng(2348934579834565) + x = rng.random(size=shape) + y = rng.random(size=13) + + kwargs = dict(n_resamples=999) + + # Use `monte_carlo` directly + def statistic(x, y, axis): return stats.ttest_ind(x, y, axis=axis).statistic + rng = np.random.default_rng(348934579834565) + rvs = [rng.standard_normal, rng.standard_normal] + ref = stats.monte_carlo_test((x, y), rvs=rvs, statistic=statistic, axis=-1, + alternative=alternative, **kwargs) + + # Use ttest_ind with `method` + rng = np.random.default_rng(348934579834565) + rvs = [rng.standard_normal, rng.standard_normal] + method = stats.MonteCarloMethod(rvs=rvs, **kwargs) + res = stats.ttest_ind(x, y, axis=-1, alternative=alternative, method=method) + assert_equal(res.statistic, ref.statistic) + assert_equal(res.pvalue, ref.pvalue) + + # Passing `rng` instead of `rvs` + method = stats.MonteCarloMethod(rng=348934579834565, **kwargs) + res = stats.ttest_ind(x, y, axis=-1, alternative=alternative, method=method) + assert_equal(res.statistic, ref.statistic) + assert_equal(res.pvalue, ref.pvalue) + + # Sanity check against theoretical t-test + ref = stats.ttest_ind(x, y, axis=-1, alternative=alternative) + assert_equal(res.statistic, ref.statistic) + assert_allclose(res.pvalue, ref.pvalue, rtol=6e-2) + + def test_resampling_input_validation(self): + message = "`method` must be an instance of `PermutationMethod`, an instance..." + with pytest.raises(ValueError, match=message): + stats.ttest_ind([1, 2, 3], [4, 5, 6], method='migratory') + + @array_api_compatible + @pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') + @pytest.mark.usefixtures("skip_xp_backends") + def test_permutation_not_implement_for_xp(self, xp): + a2, b2 = xp.asarray(self.a2), xp.asarray(self.b2) + + message = "Use of `permutations` is compatible only with NumPy arrays." + if is_numpy(xp): # no error + stats.ttest_ind(a2, b2, permutations=10) + else: # NotImplementedError + with pytest.raises(NotImplementedError, match=message): + stats.ttest_ind(a2, b2, permutations=10) + + message = "Use of resampling methods is compatible only with NumPy arrays." + rng = np.random.default_rng(7457345872572348) + method = stats.PermutationMethod(rng=rng) + if is_numpy(xp): # no error + stats.ttest_ind(a2, b2, method=method) + else: # NotImplementedError + with pytest.raises(NotImplementedError, match=message): + stats.ttest_ind(a2, b2, method=method) + + +@pytest.mark.filterwarnings("ignore:Arguments...:DeprecationWarning") +class Test_ttest_ind_common: + # for tests that are performed on variations of the t-test such as + # permutations and trimming + @pytest.mark.xslow() + @pytest.mark.parametrize("kwds", [{'permutations': 200, 'random_state': 0}, + {'trim': .2}, {}], + ids=["permutations", "trim", "basic"]) + @pytest.mark.parametrize('equal_var', [True, False], + ids=['equal_var', 'unequal_var']) + def test_ttest_many_dims(self, kwds, equal_var): + # Test that test works on many-dimensional arrays + np.random.seed(0) + a = np.random.rand(5, 4, 4, 7, 1, 6) + b = np.random.rand(4, 1, 8, 2, 6) + res = stats.ttest_ind(a, b, axis=-3, **kwds) + + # compare fully-vectorized t-test against t-test on smaller slice + i, j, k = 2, 3, 1 + a2 = a[i, :, j, :, 0, :] + b2 = b[:, 0, :, k, :] + res2 = stats.ttest_ind(a2, b2, axis=-2, **kwds) + assert_equal(res.statistic[i, :, j, k, :], + res2.statistic) + assert_equal(res.pvalue[i, :, j, k, :], + res2.pvalue) + + # compare against t-test on one axis-slice at a time + + # manually broadcast with tile; move axis to end to simplify + x = np.moveaxis(np.tile(a, (1, 1, 1, 1, 2, 1)), -3, -1) + y = np.moveaxis(np.tile(b, (5, 1, 4, 1, 1, 1)), -3, -1) + shape = x.shape[:-1] + statistics = np.zeros(shape) + pvalues = np.zeros(shape) + for indices in product(*(range(i) for i in shape)): + xi = x[indices] # use tuple to index single axis slice + yi = y[indices] + res3 = stats.ttest_ind(xi, yi, axis=-1, **kwds) + statistics[indices] = res3.statistic + pvalues[indices] = res3.pvalue + + assert_allclose(statistics, res.statistic) + assert_allclose(pvalues, res.pvalue) + + @pytest.mark.parametrize("kwds", [{'permutations': 200, 'random_state': 0}, + {'trim': .2}, {}], + ids=["trim", "permutations", "basic"]) + @pytest.mark.parametrize("axis", [-1, 0]) + def test_nans_on_axis(self, kwds, axis): + # confirm that with `nan_policy='propagate'`, NaN results are returned + # on the correct location + a = np.random.randint(10, size=(5, 3, 10)).astype('float') + b = np.random.randint(10, size=(5, 3, 10)).astype('float') + # set some indices in `a` and `b` to be `np.nan`. + a[0][2][3] = np.nan + b[2][0][6] = np.nan + + # arbitrarily use `np.sum` as a baseline for which indices should be + # NaNs + expected = np.isnan(np.sum(a + b, axis=axis)) + # multidimensional inputs to `t.sf(np.abs(t), df)` with NaNs on some + # indices throws an warning. See issue gh-13844 + with suppress_warnings() as sup, np.errstate(invalid="ignore"): + sup.filter(RuntimeWarning, + "invalid value encountered in less_equal") + sup.filter(RuntimeWarning, "Precision loss occurred") + res = stats.ttest_ind(a, b, axis=axis, **kwds) + p_nans = np.isnan(res.pvalue) + assert_array_equal(p_nans, expected) + statistic_nans = np.isnan(res.statistic) + assert_array_equal(statistic_nans, expected) + + +class Test_ttest_trim: + params = [ + [[1, 2, 3], [1.1, 2.9, 4.2], 0.53619490753126731, -0.6864951273557258, + .2], + [[56, 128.6, 12, 123.8, 64.34, 78, 763.3], [1.1, 2.9, 4.2], + 0.00998909252078421, 4.591598691181999, .2], + [[56, 128.6, 12, 123.8, 64.34, 78, 763.3], [1.1, 2.9, 4.2], + 0.10512380092302633, 2.832256715395378, .32], + [[2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9], + [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1], + 0.002878909511344, -4.2461168970325, .2], + [[-0.84504783, 0.13366078, 3.53601757, -0.62908581, 0.54119466, + -1.16511574, -0.08836614, 1.18495416, 2.48028757, -1.58925028, + -1.6706357, 0.3090472, -2.12258305, 0.3697304, -1.0415207, + -0.57783497, -0.90997008, 1.09850192, 0.41270579, -1.4927376], + [1.2725522, 1.1657899, 2.7509041, 1.2389013, -0.9490494, -1.0752459, + 1.1038576, 2.9912821, 3.5349111, 0.4171922, 1.0168959, -0.7625041, + -0.4300008, 3.0431921, 1.6035947, 0.5285634, -0.7649405, 1.5575896, + 1.3670797, 1.1726023], 0.005293305834235, -3.0983317739483, .2]] + + @pytest.mark.parametrize("a,b,pr,tr,trim", params) + def test_ttest_compare_r(self, a, b, pr, tr, trim): + ''' + Using PairedData's yuen.t.test method. Something to note is that there + are at least 3 R packages that come with a trimmed t-test method, and + comparisons were made between them. It was found that PairedData's + method's results match this method, SAS, and one of the other R + methods. A notable discrepancy was the DescTools implementation of the + function, which only sometimes agreed with SAS, WRS2, PairedData and + this implementation. For this reason, most comparisons in R are made + against PairedData's method. + + Rather than providing the input and output for all evaluations, here is + a representative example: + > library(PairedData) + > a <- c(1, 2, 3) + > b <- c(1.1, 2.9, 4.2) + > options(digits=16) + > yuen.t.test(a, b, tr=.2) + + Two-sample Yuen test, trim=0.2 + + data: x and y + t = -0.68649512735573, df = 3.4104431643464, p-value = 0.5361949075313 + alternative hypothesis: true difference in trimmed means is not equal + to 0 + 95 percent confidence interval: + -3.912777195645217 2.446110528978550 + sample estimates: + trimmed mean of x trimmed mean of y + 2.000000000000000 2.73333333333333 + ''' + statistic, pvalue = stats.ttest_ind(a, b, trim=trim, equal_var=False) + assert_allclose(statistic, tr, atol=1e-15) + assert_allclose(pvalue, pr, atol=1e-15) + + def test_compare_SAS(self): + # Source of the data used in this test: + # https://support.sas.com/resources/papers/proceedings14/1660-2014.pdf + a = [12, 14, 18, 25, 32, 44, 12, 14, 18, 25, 32, 44] + b = [17, 22, 14, 12, 30, 29, 19, 17, 22, 14, 12, 30, 29, 19] + # In this paper, a trimming percentage of 5% is used. However, + # in their implementation, the number of values trimmed is rounded to + # the nearest whole number. However, consistent with + # `scipy.stats.trimmed_mean`, this test truncates to the lower + # whole number. In this example, the paper notes that 1 value is + # trimmed off of each side. 9% replicates this amount of trimming. + statistic, pvalue = stats.ttest_ind(a, b, trim=.09, equal_var=False) + assert_allclose(pvalue, 0.514522, atol=1e-6) + assert_allclose(statistic, 0.669169, atol=1e-6) + + def test_equal_var(self): + ''' + The PairedData library only supports unequal variances. To compare + samples with equal variances, the multicon library is used. + > library(multicon) + > a <- c(2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9) + > b <- c(6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1) + > dv = c(a,b) + > iv = c(rep('a', length(a)), rep('b', length(b))) + > yuenContrast(dv~ iv, EQVAR = TRUE) + $Ms + N M wgt + a 11 2.442857142857143 1 + b 11 5.385714285714286 -1 + + $test + stat df crit p + results -4.246116897032513 12 2.178812829667228 0.00113508833897713 + ''' + a = [2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9] + b = [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1] + # `equal_var=True` is default + statistic, pvalue = stats.ttest_ind(a, b, trim=.2) + assert_allclose(pvalue, 0.00113508833897713, atol=1e-10) + assert_allclose(statistic, -4.246116897032513, atol=1e-10) + + @pytest.mark.parametrize('alt,pr,tr', + (('greater', 0.9985605452443, -4.2461168970325), + ('less', 0.001439454755672, -4.2461168970325),), + ) + def test_alternatives(self, alt, pr, tr): + ''' + > library(PairedData) + > a <- c(2.7,2.7,1.1,3.0,1.9,3.0,3.8,3.8,0.3,1.9,1.9) + > b <- c(6.5,5.4,8.1,3.5,0.5,3.8,6.8,4.9,9.5,6.2,4.1) + > options(digits=16) + > yuen.t.test(a, b, alternative = 'greater') + ''' + a = [2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9] + b = [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1] + + statistic, pvalue = stats.ttest_ind(a, b, trim=.2, equal_var=False, + alternative=alt) + assert_allclose(pvalue, pr, atol=1e-10) + assert_allclose(statistic, tr, atol=1e-10) + + def test_errors_unsupported(self): + # confirm that attempting to trim with permutations raises an error + match = "Use of `permutations` is incompatible with with use of `trim`." + with assert_raises(NotImplementedError, match=match): + message = "Arguments {'permutations'} are deprecated, whether..." + with pytest.warns(DeprecationWarning, match=message): + stats.ttest_ind([1, 2], [2, 3], trim=.2, permutations=2) + + with assert_raises(NotImplementedError, match=match): + message = "Arguments {.*'random_state'.*} are deprecated, whether..." + with pytest.warns(DeprecationWarning, match=message): + stats.ttest_ind([1, 2], [2, 3], trim=.2, permutations=2, + random_state=2) + + @array_api_compatible + @pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') + @pytest.mark.usefixtures("skip_xp_backends") + def test_permutation_not_implement_for_xp(self, xp): + message = "Use of `trim` is compatible only with NumPy arrays." + a, b = xp.arange(10), xp.arange(10)+1 + if is_numpy(xp): # no error + stats.ttest_ind(a, b, trim=0.1) + else: # NotImplementedError + with pytest.raises(NotImplementedError, match=message): + stats.ttest_ind(a, b, trim=0.1) + + @pytest.mark.parametrize("trim", [-.2, .5, 1]) + def test_trim_bounds_error(self, trim): + match = "Trimming percentage should be 0 <= `trim` < .5." + with assert_raises(ValueError, match=match): + stats.ttest_ind([1, 2], [2, 1], trim=trim) + + +@array_api_compatible +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +class Test_ttest_CI: + # indices in order [alternative={two-sided, less, greater}, + # equal_var={False, True}, trim={0, 0.2}] + # reference values in order `statistic, df, pvalue, low, high` + # equal_var=False reference values computed with R PairedData yuen.t.test: + # + # library(PairedData) + # options(digits=16) + # a < - c(0.88236329, 0.97318744, 0.4549262, 0.97893335, 0.0606677, + # 0.44013366, 0.55806018, 0.40151434, 0.14453315, 0.25860601, + # 0.20202162) + # b < - c(0.93455277, 0.42680603, 0.49751939, 0.14152846, 0.711435, + # 0.77669667, 0.20507578, 0.78702772, 0.94691855, 0.32464958, + # 0.3873582, 0.35187468, 0.21731811) + # yuen.t.test(a, b, tr=0, conf.level = 0.9, alternative = 'l') + # + # equal_var=True reference values computed with R multicon yuenContrast: + # + # library(multicon) + # options(digits=16) + # a < - c(0.88236329, 0.97318744, 0.4549262, 0.97893335, 0.0606677, + # 0.44013366, 0.55806018, 0.40151434, 0.14453315, 0.25860601, + # 0.20202162) + # b < - c(0.93455277, 0.42680603, 0.49751939, 0.14152846, 0.711435, + # 0.77669667, 0.20507578, 0.78702772, 0.94691855, 0.32464958, + # 0.3873582, 0.35187468, 0.21731811) + # dv = c(a, b) + # iv = c(rep('a', length(a)), rep('b', length(b))) + # yuenContrast(dv~iv, EQVAR = FALSE, alternative = 'unequal', tr = 0.2) + r = np.empty(shape=(3, 2, 2, 5)) + r[0, 0, 0] = [-0.2314607, 19.894435, 0.8193209, -0.247220294, 0.188729943] + r[1, 0, 0] = [-0.2314607, 19.894435, 0.40966045, -np.inf, 0.1382426469] + r[2, 0, 0] = [-0.2314607, 19.894435, 0.5903395, -0.1967329982, np.inf] + r[0, 0, 1] = [-0.2452886, 11.427896, 0.8105823, -0.34057446, 0.25847383] + r[1, 0, 1] = [-0.2452886, 11.427896, 0.40529115, -np.inf, 0.1865829074] + r[2, 0, 1] = [-0.2452886, 11.427896, 0.5947089, -0.268683541, np.inf] + # confidence interval not available for equal_var=True + r[0, 1, 0] = [-0.2345625322555006, 22, 0.8167175905643815, np.nan, np.nan] + r[1, 1, 0] = [-0.2345625322555006, 22, 0.4083587952821908, np.nan, np.nan] + r[2, 1, 0] = [-0.2345625322555006, 22, 0.5916412047178092, np.nan, np.nan] + r[0, 1, 1] = [-0.2505369406507428, 14, 0.8058115135702835, np.nan, np.nan] + r[1, 1, 1] = [-0.2505369406507428, 14, 0.4029057567851417, np.nan, np.nan] + r[2, 1, 1] = [-0.2505369406507428, 14, 0.5970942432148583, np.nan, np.nan] + @pytest.mark.parametrize('alternative', ['two-sided', 'less', 'greater']) + @pytest.mark.parametrize('equal_var', [False, True]) + @pytest.mark.parametrize('trim', [0, 0.2]) + def test_confidence_interval(self, alternative, equal_var, trim, xp): + if equal_var and trim: + pytest.xfail('Discrepancy in `main`; needs further investigation.') + + if trim and not is_numpy(xp): + pytest.skip('`trim` is only compatible with NumPy input') + + rng = np.random.default_rng(3810954496107292580) + x = xp.asarray(rng.random(11)) + y = xp.asarray(rng.random(13)) + + res = stats.ttest_ind(x, y, alternative=alternative, + equal_var=equal_var, trim=trim) + + alternatives = {'two-sided': 0, 'less': 1, 'greater': 2} + ref = self.r[alternatives[alternative], int(equal_var), int(np.ceil(trim))] + statistic, df, pvalue, low, high = ref + + rtol = 1e-7 # only 7 digits in reference + xp_assert_close(res.statistic, xp.asarray(statistic), rtol=rtol) + xp_assert_close(res.df, xp.asarray(df), rtol=rtol) + xp_assert_close(res.pvalue, xp.asarray(pvalue), rtol=rtol) + + if not equal_var: # CI not available when `equal_var is True` + ci = res.confidence_interval(0.9) + xp_assert_close(ci.low, xp.asarray(low), rtol=rtol) + xp_assert_close(ci.high, xp.asarray(high), rtol=rtol) + + +def test__broadcast_concatenate(): + # test that _broadcast_concatenate properly broadcasts arrays along all + # axes except `axis`, then concatenates along axis + np.random.seed(0) + a = np.random.rand(5, 4, 4, 3, 1, 6) + b = np.random.rand(4, 1, 8, 2, 6) + c = _broadcast_concatenate((a, b), axis=-3) + # broadcast manually as an independent check + a = np.tile(a, (1, 1, 1, 1, 2, 1)) + b = np.tile(b[None, ...], (5, 1, 4, 1, 1, 1)) + for index in product(*(range(i) for i in c.shape)): + i, j, k, l, m, n = index + if l < a.shape[-3]: + assert a[i, j, k, l, m, n] == c[i, j, k, l, m, n] + else: + assert b[i, j, k, l - a.shape[-3], m, n] == c[i, j, k, l, m, n] + + +@array_api_compatible +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +def test_ttest_ind_with_uneq_var(xp): + # check vs. R `t.test`, e.g. + # options(digits=20) + # a = c(1., 2., 3.) + # b = c(1.1, 2.9, 4.2) + # t.test(a, b, equal.var=FALSE) + + a = xp.asarray([1., 2., 3.]) + b = xp.asarray([1.1, 2.9, 4.2]) + pr = xp.asarray(0.53619490753126686) + tr = xp.asarray(-0.686495127355726265) + + t, p = stats.ttest_ind(a, b, equal_var=False) + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + t, p = stats.ttest_ind_from_stats(*_desc_stats(a, b), equal_var=False) + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + a = xp.asarray([1., 2., 3., 4.]) + pr = xp.asarray(0.84354139131608252) + tr = xp.asarray(-0.210866331595072315) + + t, p = stats.ttest_ind(a, b, equal_var=False) + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + t, p = stats.ttest_ind_from_stats(*_desc_stats(a, b), equal_var=False) + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + # regression test + tr = xp.asarray(1.0912746897927283) + tr_uneq_n = xp.asarray(0.66745638708050492) + pr = xp.asarray(0.27647831993021388) + pr_uneq_n = xp.asarray(0.50873585065616544) + tr_2D = xp.asarray([tr, -tr]) + pr_2D = xp.asarray([pr, pr]) + + rvs3 = xp.linspace(1, 100, 25) + rvs2 = xp.linspace(1, 100, 100) + rvs1 = xp.linspace(5, 105, 100) + rvs1_2D = xp.stack([rvs1, rvs2]) + rvs2_2D = xp.stack([rvs2, rvs1]) + + t, p = stats.ttest_ind(rvs1, rvs2, axis=0, equal_var=False) + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + t, p = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2), equal_var=False) + xp_assert_close(t, tr) + xp_assert_close(p, pr) + + t, p = stats.ttest_ind(rvs1, rvs3, axis=0, equal_var=False) + xp_assert_close(t, tr_uneq_n) + xp_assert_close(p, pr_uneq_n) + + t, p = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs3), equal_var=False) + xp_assert_close(t, tr_uneq_n) + xp_assert_close(p, pr_uneq_n) + + res = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0, equal_var=False) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + args = _desc_stats(rvs1_2D.T, rvs2_2D.T) + res = stats.ttest_ind_from_stats(*args, equal_var=False) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + res = stats.ttest_ind(rvs1_2D, rvs2_2D, axis=1, equal_var=False) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + args = _desc_stats(rvs1_2D, rvs2_2D, axis=1) + res = stats.ttest_ind_from_stats(*args, equal_var=False) + xp_assert_close(res.statistic, tr_2D) + xp_assert_close(res.pvalue, pr_2D) + + +@array_api_compatible +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +def test_ttest_ind_zero_division(xp): + # test zero division problem + x = xp.zeros(3) + y = xp.ones(3) + with pytest.warns(RuntimeWarning, match="Precision loss occurred"): + t, p = stats.ttest_ind(x, y, equal_var=False) + xp_assert_equal(t, xp.asarray(-xp.inf)) + xp_assert_equal(p, xp.asarray(0.)) + + with np.errstate(all='ignore'): + t, p = stats.ttest_ind(x, x, equal_var=False) + xp_assert_equal(t, xp.asarray(xp.nan)) + xp_assert_equal(p, xp.asarray(xp.nan)) + + # check that nan in input array result in nan output + anan = xp.asarray([[1, xp.nan], [-1, 1]]) + t, p = stats.ttest_ind(anan, xp.zeros((2, 2)), equal_var=False) + xp_assert_equal(t, xp.asarray([0., np.nan])) + xp_assert_equal(p, xp.asarray([1., np.nan])) + + +def test_ttest_ind_nan_2nd_arg(): + # regression test for gh-6134: nans in the second arg were not handled + x = [np.nan, 2.0, 3.0, 4.0] + y = [1.0, 2.0, 1.0, 2.0] + + r1 = stats.ttest_ind(x, y, nan_policy='omit') + r2 = stats.ttest_ind(y, x, nan_policy='omit') + assert_allclose(r2.statistic, -r1.statistic, atol=1e-15) + assert_allclose(r2.pvalue, r1.pvalue, atol=1e-15) + + # NB: arguments are not paired when NaNs are dropped + r3 = stats.ttest_ind(y, x[1:]) + assert_allclose(r2, r3, atol=1e-15) + + # .. and this is consistent with R. R code: + # x = c(NA, 2.0, 3.0, 4.0) + # y = c(1.0, 2.0, 1.0, 2.0) + # t.test(x, y, var.equal=TRUE) + assert_allclose(r2, (-2.5354627641855498, 0.052181400457057901), + atol=1e-15) + + +@array_api_compatible +def test_ttest_ind_empty_1d_returns_nan(xp): + # Two empty inputs should return a TtestResult containing nan + # for both values. + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.ttest_ind(xp.asarray([]), xp.asarray([])) + else: + res = stats.ttest_ind(xp.asarray([]), xp.asarray([])) + assert isinstance(res, stats._stats_py.TtestResult) + NaN = xp.asarray(xp.nan)[()] + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + + +@skip_xp_backends('cupy', reason='cupy/cupy#8391') +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +@pytest.mark.parametrize('b, expected_shape', + [(np.empty((1, 5, 0)), (3, 5)), + (np.empty((1, 0, 0)), (3, 0))]) +def test_ttest_ind_axis_size_zero(b, expected_shape, xp): + # In this test, the length of the axis dimension is zero. + # The results should be arrays containing nan with shape + # given by the broadcast nonaxis dimensions. + a = xp.empty((3, 1, 0)) + b = xp.asarray(b) + with np.testing.suppress_warnings() as sup: + # first case should warn, second shouldn't? + sup.filter(SmallSampleWarning, too_small_nd_not_omit) + res = stats.ttest_ind(a, b, axis=-1) + assert isinstance(res, stats._stats_py.TtestResult) + expected_value = xp.full(expected_shape, fill_value=xp.nan) + xp_assert_equal(res.statistic, expected_value) + xp_assert_equal(res.pvalue, expected_value) + + +@array_api_compatible +def test_ttest_ind_nonaxis_size_zero(xp): + # In this test, the length of the axis dimension is nonzero, + # but one of the nonaxis dimensions has length 0. Check that + # we still get the correctly broadcast shape, which is (5, 0) + # in this case. + a = xp.empty((1, 8, 0)) + b = xp.empty((5, 8, 1)) + res = stats.ttest_ind(a, b, axis=1) + assert isinstance(res, stats._stats_py.TtestResult) + assert res.statistic.shape ==(5, 0) + assert res.pvalue.shape == (5, 0) + + +@array_api_compatible +def test_ttest_ind_nonaxis_size_zero_different_lengths(xp): + # In this test, the length of the axis dimension is nonzero, + # and that size is different in the two inputs, + # and one of the nonaxis dimensions has length 0. Check that + # we still get the correctly broadcast shape, which is (5, 0) + # in this case. + a = xp.empty((1, 7, 0)) + b = xp.empty((5, 8, 1)) + res = stats.ttest_ind(a, b, axis=1) + assert isinstance(res, stats._stats_py.TtestResult) + assert res.statistic.shape ==(5, 0) + assert res.pvalue.shape == (5, 0) + + +@array_api_compatible +@pytest.mark.skip_xp_backends(np_only=True, + reason="Other backends don't like integers") +@pytest.mark.usefixtures("skip_xp_backends") +def test_gh5686(xp): + mean1, mean2 = xp.asarray([1, 2]), xp.asarray([3, 4]) + std1, std2 = xp.asarray([5, 3]), xp.asarray([4, 5]) + nobs1, nobs2 = xp.asarray([130, 140]), xp.asarray([100, 150]) + # This will raise a TypeError unless gh-5686 is fixed. + stats.ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2) + + +@array_api_compatible +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +def test_ttest_ind_from_stats_inputs_zero(xp): + # Regression test for gh-6409. + zero = xp.asarray(0.) + six = xp.asarray(6.) + NaN = xp.asarray(xp.nan) + res = stats.ttest_ind_from_stats(zero, zero, six, zero, zero, six, equal_var=False) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + + +@array_api_compatible +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +def test_ttest_uniform_pvalues(xp): + # test that p-values are uniformly distributed under the null hypothesis + rng = np.random.default_rng(246834602926842) + x = xp.asarray(rng.normal(size=(10000, 2))) + y = xp.asarray(rng.normal(size=(10000, 1))) + q = rng.uniform(size=100) + + res = stats.ttest_ind(x, y, equal_var=True, axis=-1) + pvalue = np.asarray(res.pvalue) + assert stats.ks_1samp(pvalue, stats.uniform().cdf).pvalue > 0.1 + assert_allclose(np.quantile(pvalue, q), q, atol=1e-2) + + res = stats.ttest_ind(y, x, equal_var=True, axis=-1) + pvalue = np.asarray(res.pvalue) + assert stats.ks_1samp(pvalue, stats.uniform().cdf).pvalue > 0.1 + assert_allclose(np.quantile(pvalue, q), q, atol=1e-2) + + # reference values from R: + # options(digits=16) + # t.test(c(2, 3, 5), c(1.5), var.equal=TRUE) + x, y = xp.asarray([2, 3, 5]), xp.asarray([1.5]) + + res = stats.ttest_ind(x, y, equal_var=True) + rtol = 1e-6 if is_torch(xp) else 1e-10 + xp_assert_close(res.statistic, xp.asarray(1.0394023007754), rtol=rtol) + xp_assert_close(res.pvalue, xp.asarray(0.407779907736), rtol=rtol) + + +def _convert_pvalue_alternative(t, p, alt, xp): + # test alternative parameter + # Convert from two-sided p-values to one sided using T result data. + less = xp.asarray(alt == "less") + greater = xp.asarray(alt == "greater") + i = ((t < 0) & less) | ((t > 0) & greater) + return xp.where(i, p/2, 1 - p/2) + + +@pytest.mark.slow +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +def test_ttest_1samp_new(xp): + n1, n2, n3 = (10, 15, 20) + rvn1 = stats.norm.rvs(loc=5, scale=10, size=(n1, n2, n3)) + rvn1 = xp.asarray(rvn1) + + # check multidimensional array and correct axis handling + # deterministic rvn1 and rvn2 would be better as in test_ttest_rel + popmean = xp.ones((1, n2, n3)) + t1, p1 = stats.ttest_1samp(rvn1, popmean, axis=0) + t2, p2 = stats.ttest_1samp(rvn1, 1., axis=0) + t3, p3 = stats.ttest_1samp(rvn1[:, 0, 0], 1.) + xp_assert_close(t1, t2, rtol=1e-14) + xp_assert_close(t1[0, 0], t3, rtol=1e-14) + assert_equal(t1.shape, (n2, n3)) + + popmean = xp.ones((n1, 1, n3)) + t1, p1 = stats.ttest_1samp(rvn1, popmean, axis=1) + t2, p2 = stats.ttest_1samp(rvn1, 1., axis=1) + t3, p3 = stats.ttest_1samp(rvn1[0, :, 0], 1.) + xp_assert_close(t1, t2, rtol=1e-14) + xp_assert_close(t1[0, 0], t3, rtol=1e-14) + assert_equal(t1.shape, (n1, n3)) + + popmean = xp.ones((n1, n2, 1)) + t1, p1 = stats.ttest_1samp(rvn1, popmean, axis=2) + t2, p2 = stats.ttest_1samp(rvn1, 1., axis=2) + t3, p3 = stats.ttest_1samp(rvn1[0, 0, :], 1.) + xp_assert_close(t1, t2, rtol=1e-14) + xp_assert_close(t1[0, 0], t3, rtol=1e-14) + assert_equal(t1.shape, (n1, n2)) + + # test zero division problem + t, p = stats.ttest_1samp(xp.asarray([0., 0., 0.]), 1.) + xp_assert_equal(xp.abs(t), xp.asarray(xp.inf)) + xp_assert_equal(p, xp.asarray(0.)) + + tr, pr = stats.ttest_1samp(rvn1[:, :, :], 1.) + + t, p = stats.ttest_1samp(rvn1[:, :, :], 1., alternative="greater") + pc = _convert_pvalue_alternative(tr, pr, "greater", xp) + xp_assert_close(p, pc) + xp_assert_close(t, tr) + + t, p = stats.ttest_1samp(rvn1[:, :, :], 1., alternative="less") + pc = _convert_pvalue_alternative(tr, pr, "less", xp) + xp_assert_close(p, pc) + xp_assert_close(t, tr) + + with np.errstate(all='ignore'): + res = stats.ttest_1samp(xp.asarray([0., 0., 0.]), 0.) + xp_assert_equal(res.statistic, xp.asarray(xp.nan)) + xp_assert_equal(res.pvalue, xp.asarray(xp.nan)) + + # check that nan in input array result in nan output + anan = xp.asarray([[1., np.nan], [-1., 1.]]) + res = stats.ttest_1samp(anan, 0.) + xp_assert_equal(res.statistic, xp.asarray([0., xp.nan])) + xp_assert_equal(res.pvalue, xp.asarray([1., xp.nan])) + + +@pytest.mark.skip_xp_backends(np_only=True, + reason="Only NumPy has nan_policy='omit' for now") +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +def test_ttest_1samp_new_omit(xp): + n1, n2, n3 = (5, 10, 15) + rvn1 = stats.norm.rvs(loc=5, scale=10, size=(n1, n2, n3)) + rvn1 = xp.asarray(rvn1) + + rvn1[0:2, 1:3, 4:8] = xp.nan + + tr, pr = stats.ttest_1samp(rvn1[:, :, :], 1., nan_policy='omit') + + t, p = stats.ttest_1samp(rvn1[:, :, :], 1., nan_policy='omit', + alternative="greater") + pc = _convert_pvalue_alternative(tr, pr, "greater", xp) + xp_assert_close(p, pc) + xp_assert_close(t, tr) + + t, p = stats.ttest_1samp(rvn1[:, :, :], 1., nan_policy='omit', + alternative="less") + pc = _convert_pvalue_alternative(tr, pr, "less", xp) + xp_assert_close(p, pc) + xp_assert_close(t, tr) + + +@pytest.mark.skip_xp_backends(cpu_only=True, + reason='Uses NumPy for pvalue, CI') +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +def test_ttest_1samp_popmean_array(xp): + # when popmean.shape[axis] != 1, raise an error + # if the user wants to test multiple null hypotheses simultaneously, + # use standard broadcasting rules + rng = np.random.default_rng(2913300596553337193) + x = rng.random(size=(1, 15, 20)) + x = xp.asarray(x) + + message = r"`popmean.shape\[axis\]` must equal 1." + popmean = xp.asarray(rng.random(size=(5, 2, 20))) + with pytest.raises(ValueError, match=message): + stats.ttest_1samp(x, popmean=popmean, axis=-2) + + popmean = xp.asarray(rng.random(size=(5, 1, 20))) + res = stats.ttest_1samp(x, popmean=popmean, axis=-2) + assert res.statistic.shape == (5, 20) + + xp_test = array_namespace(x) # torch needs expand_dims + l, u = res.confidence_interval() + l = xp_test.expand_dims(l, axis=-2) + u = xp_test.expand_dims(u, axis=-2) + + res = stats.ttest_1samp(x, popmean=l, axis=-2) + ref = xp.broadcast_to(xp.asarray(0.05, dtype=xp.float64), res.pvalue.shape) + xp_assert_close(res.pvalue, ref) + + res = stats.ttest_1samp(x, popmean=u, axis=-2) + xp_assert_close(res.pvalue, ref) + + +class TestDescribe: + @array_api_compatible + def test_describe_scalar(self, xp): + with suppress_warnings() as sup, \ + np.errstate(invalid="ignore", divide="ignore"): + sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice") + n, mm, m, v, sk, kurt = stats.describe(xp.asarray(4.)[()]) + assert n == 1 + xp_assert_equal(mm[0], xp.asarray(4.0)) + xp_assert_equal(mm[1], xp.asarray(4.0)) + xp_assert_equal(m, xp.asarray(4.0)) + xp_assert_equal(v ,xp.asarray(xp.nan)) + xp_assert_equal(sk, xp.asarray(xp.nan)) + xp_assert_equal(kurt, xp.asarray(xp.nan)) + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_describe_numbers(self, xp): + xp_test = array_namespace(xp.asarray(1.)) # numpy needs `concat` + x = xp_test.concat((xp.ones((3, 4)), xp.full((2, 4), 2.))) + nc = 5 + mmc = (xp.asarray([1., 1., 1., 1.]), xp.asarray([2., 2., 2., 2.])) + mc = xp.asarray([1.4, 1.4, 1.4, 1.4]) + vc = xp.asarray([0.3, 0.3, 0.3, 0.3]) + skc = xp.asarray([0.40824829046386357] * 4) + kurtc = xp.asarray([-1.833333333333333] * 4) + n, mm, m, v, sk, kurt = stats.describe(x) + assert n == nc + xp_assert_equal(mm[0], mmc[0]) + xp_assert_equal(mm[1], mmc[1]) + xp_assert_close(m, mc, rtol=4 * xp.finfo(m.dtype).eps) + xp_assert_close(v, vc, rtol=4 * xp.finfo(m.dtype).eps) + xp_assert_close(sk, skc) + xp_assert_close(kurt, kurtc) + + n, mm, m, v, sk, kurt = stats.describe(x.T, axis=1) + assert n == nc + xp_assert_equal(mm[0], mmc[0]) + xp_assert_equal(mm[1], mmc[1]) + xp_assert_close(m, mc, rtol=4 * xp.finfo(m.dtype).eps) + xp_assert_close(v, vc, rtol=4 * xp.finfo(m.dtype).eps) + xp_assert_close(sk, skc) + xp_assert_close(kurt, kurtc) + + def describe_nan_policy_omit_test(self): + x = np.arange(10.) + x[9] = np.nan + + nc, mmc = (9, (0.0, 8.0)) + mc = 4.0 + vc = 7.5 + skc = 0.0 + kurtc = -1.2300000000000002 + n, mm, m, v, sk, kurt = stats.describe(x, nan_policy='omit') + assert_equal(n, nc) + assert_equal(mm, mmc) + assert_equal(m, mc) + assert_equal(v, vc) + assert_array_almost_equal(sk, skc) + assert_array_almost_equal(kurt, kurtc, decimal=13) + + @array_api_compatible + def test_describe_nan_policy_other(self, xp): + x = xp.arange(10.) + x = xp.where(x==9, xp.asarray(xp.nan), x) + + message = 'The input contains nan values' + with pytest.raises(ValueError, match=message): + stats.describe(x, nan_policy='raise') + + n, mm, m, v, sk, kurt = stats.describe(x, nan_policy='propagate') + ref = xp.asarray(xp.nan)[()] + assert n == 10 + xp_assert_equal(mm[0], ref) + xp_assert_equal(mm[1], ref) + xp_assert_equal(m, ref) + xp_assert_equal(v, ref) + xp_assert_equal(sk, ref) + xp_assert_equal(kurt, ref) + + if is_numpy(xp): + self.describe_nan_policy_omit_test() + else: + message = "`nan_policy='omit' is incompatible with non-NumPy arrays." + with pytest.raises(ValueError, match=message): + stats.describe(x, nan_policy='omit') + + message = 'nan_policy must be one of...' + with pytest.raises(ValueError, match=message): + stats.describe(x, nan_policy='foobar') + + def test_describe_result_attributes(self): + # some result attributes are tuples, which aren't meant to be compared + # with `xp_assert_close` + actual = stats.describe(np.arange(5.)) + attributes = ('nobs', 'minmax', 'mean', 'variance', 'skewness', 'kurtosis') + check_named_results(actual, attributes) + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_describe_ddof(self, xp): + xp_test = array_namespace(xp.asarray(1.)) # numpy needs `concat` + x = xp_test.concat((xp.ones((3, 4)), xp.full((2, 4), 2.))) + nc = 5 + mmc = (xp.asarray([1., 1., 1., 1.]), xp.asarray([2., 2., 2., 2.])) + mc = xp.asarray([1.4, 1.4, 1.4, 1.4]) + vc = xp.asarray([0.24, 0.24, 0.24, 0.24]) + skc = xp.asarray([0.40824829046386357] * 4) + kurtc = xp.asarray([-1.833333333333333] * 4) + n, mm, m, v, sk, kurt = stats.describe(x, ddof=0) + assert n == nc + xp_assert_equal(mm[0], mmc[0]) + xp_assert_equal(mm[1], mmc[1]) + xp_assert_close(m, mc) + xp_assert_close(v, vc) + xp_assert_close(sk, skc) + xp_assert_close(kurt, kurtc) + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + @array_api_compatible + def test_describe_axis_none(self, xp): + xp_test = array_namespace(xp.asarray(1.)) # numpy needs `concat` + x = xp_test.concat((xp.ones((3, 4)), xp.full((2, 4), 2.))) + + # expected values + nc = 20 + mmc = (xp.asarray(1.0), xp.asarray(2.0)) + mc = xp.asarray(1.3999999999999999) + vc = xp.asarray(0.25263157894736848) + skc = xp.asarray(0.4082482904638634) + kurtc = xp.asarray(-1.8333333333333333) + + # actual values + n, mm, m, v, sk, kurt = stats.describe(x, axis=None) + + assert n == nc + xp_assert_equal(mm[0], mmc[0]) + xp_assert_equal(mm[1], mmc[1]) + xp_assert_close(m, mc) + xp_assert_close(v, vc) + xp_assert_close(sk, skc) + xp_assert_close(kurt, kurtc) + + @array_api_compatible + def test_describe_empty(self, xp): + message = "The input must not be empty." + with pytest.raises(ValueError, match=message): + stats.describe(xp.asarray([])) + + +@array_api_compatible +class NormalityTests: + def test_too_small(self, xp): + # 1D sample has too few observations -> warning/error + test_fun = getattr(stats, self.test_name) + x = xp.asarray(4.) + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = test_fun(x) + NaN = xp.asarray(xp.nan) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + else: + message = "...requires at least..." + with pytest.raises(ValueError, match=message): + test_fun(x) + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater']) + def test_against_R(self, alternative, xp): + # testa against R `dagoTest` from package `fBasics` + # library(fBasics) + # options(digits=16) + # x = c(-2, -1, 0, 1, 2, 3)**2 + # x = rep(x, times=4) + # test_result <- dagoTest(x) + # test_result@test$statistic + # test_result@test$p.value + test_name = self.test_name + test_fun = getattr(stats, test_name) + ref_statistic= xp.asarray(self.case_ref[0]) + ref_pvalue = xp.asarray(self.case_ref[1]) + + kwargs = {} + if alternative in {'less', 'greater'}: + if test_name in {'skewtest', 'kurtosistest'}: + ref_pvalue = ref_pvalue/2 if alternative == "less" else 1-ref_pvalue/2 + ref_pvalue = 1-ref_pvalue if test_name == 'skewtest' else ref_pvalue + kwargs['alternative'] = alternative + else: + pytest.skip('`alternative` not available for `normaltest`') + + x = xp.asarray((-2, -1, 0, 1, 2, 3.)*4)**2 + res = test_fun(x, **kwargs) + res_statistic, res_pvalue = res + xp_assert_close(res_statistic, ref_statistic) + xp_assert_close(res_pvalue, ref_pvalue) + check_named_results(res, ('statistic', 'pvalue'), xp=xp) + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + def test_nan(self, xp): + # nan in input -> nan output (default nan_policy='propagate') + test_fun = getattr(stats, self.test_name) + x = xp.arange(30.) + NaN = xp.asarray(xp.nan, dtype=x.dtype) + x = xp.where(x == 29, NaN, x) + with np.errstate(invalid="ignore"): + res = test_fun(x) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + +class TestSkewTest(NormalityTests): + test_name = 'skewtest' + case_ref = (1.98078826090875881, 0.04761502382843208) # statistic, pvalue + + def test_intuitive(self, xp): + # intuitive tests; see gh-13549. skewnorm with parameter 1 has skew > 0 + a1 = stats.skewnorm.rvs(a=1, size=10000, random_state=123) + a1_xp = xp.asarray(a1) + pval = stats.skewtest(a1_xp, alternative='greater').pvalue + xp_assert_close(pval, xp.asarray(0.0, dtype=a1_xp.dtype), atol=9e-6) + + def test_skewtest_too_few_observations(self, xp): + # Regression test for ticket #1492. + # skewtest requires at least 8 observations; 7 should raise a ValueError. + stats.skewtest(xp.arange(8.0)) + + x = xp.arange(7.0) + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.skewtest(x) + NaN = xp.asarray(xp.nan) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + else: + message = "`skewtest` requires at least 8 observations" + with pytest.raises(ValueError, match=message): + stats.skewtest(x) + + +class TestKurtosisTest(NormalityTests): + test_name = 'kurtosistest' + case_ref = (-0.01403734404759738, 0.98880018772590561) # statistic, pvalue + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + def test_intuitive(self, xp): + # intuitive tests; see gh-13549. excess kurtosis of laplace is 3 > 0 + a2 = stats.laplace.rvs(size=10000, random_state=123) + a2_xp = xp.asarray(a2) + pval = stats.kurtosistest(a2_xp, alternative='greater').pvalue + xp_assert_close(pval, xp.asarray(0.0, dtype=a2_xp.dtype), atol=1e-15) + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + def test_gh9033_regression(self, xp): + # regression test for issue gh-9033: x clearly non-normal but power of + # negative denom needs to be handled correctly to reject normality + counts = [128, 0, 58, 7, 0, 41, 16, 0, 0, 167] + x = np.hstack([np.full(c, i) for i, c in enumerate(counts)]) + x = xp.asarray(x, dtype=xp.float64) + assert stats.kurtosistest(x)[1] < 0.01 + + @skip_xp_backends('cupy', reason='cupy/cupy#8391') + @pytest.mark.usefixtures("skip_xp_backends") + def test_kurtosistest_too_few_observations(self, xp): + # kurtosistest requires at least 5 observations; 4 should raise a ValueError. + # At least 20 are needed to avoid warning + # Regression test for ticket #1425. + stats.kurtosistest(xp.arange(20.0)) + + message = "`kurtosistest` p-value may be inaccurate..." + with pytest.warns(UserWarning, match=message): + stats.kurtosistest(xp.arange(5.0)) + with pytest.warns(UserWarning, match=message): + stats.kurtosistest(xp.arange(19.0)) + + x = xp.arange(4.0) + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.skewtest(x) + NaN = xp.asarray(xp.nan) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + else: + message = "`kurtosistest` requires at least 5 observations" + with pytest.raises(ValueError, match=message): + stats.kurtosistest(x) + + +class TestNormalTest(NormalityTests): + test_name = 'normaltest' + case_ref = (3.92371918158185551, 0.14059672529747502) # statistic, pvalue + + +class TestRankSums: + + np.random.seed(0) + x, y = np.random.rand(2, 10) + + @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided']) + def test_ranksums_result_attributes(self, alternative): + # ranksums pval = mannwhitneyu pval w/out continuity or tie correction + res1 = stats.ranksums(self.x, self.y, + alternative=alternative).pvalue + res2 = stats.mannwhitneyu(self.x, self.y, use_continuity=False, + alternative=alternative).pvalue + assert_allclose(res1, res2) + + def test_ranksums_named_results(self): + res = stats.ranksums(self.x, self.y) + check_named_results(res, ('statistic', 'pvalue')) + + def test_input_validation(self): + with assert_raises(ValueError, match="`alternative` must be 'less'"): + stats.ranksums(self.x, self.y, alternative='foobar') + + +@array_api_compatible +class TestJarqueBera: + def test_jarque_bera_against_R(self, xp): + # library(tseries) + # options(digits=16) + # x < - rnorm(5) + # jarque.bera.test(x) + x = [-0.160104223201523288, 1.131262000934478040, -0.001235254523709458, + -0.776440091309490987, -2.072959999533182884] + x = xp.asarray(x) + ref = xp.asarray([0.17651605223752, 0.9155246169805]) + res = stats.jarque_bera(x) + xp_assert_close(res.statistic, ref[0]) + xp_assert_close(res.pvalue, ref[1]) + + @skip_xp_backends(np_only=True) + @pytest.mark.usefixtures("skip_xp_backends") + def test_jarque_bera_array_like(self): + # array-like only relevant for NumPy + np.random.seed(987654321) + x = np.random.normal(0, 1, 100000) + + jb_test1 = JB1, p1 = stats.jarque_bera(list(x)) + jb_test2 = JB2, p2 = stats.jarque_bera(tuple(x)) + jb_test3 = JB3, p3 = stats.jarque_bera(x.reshape(2, 50000)) + + assert JB1 == JB2 == JB3 == jb_test1.statistic == jb_test2.statistic == jb_test3.statistic # noqa: E501 + assert p1 == p2 == p3 == jb_test1.pvalue == jb_test2.pvalue == jb_test3.pvalue + + def test_jarque_bera_size(self, xp): + x = xp.asarray([]) + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.jarque_bera(x) + NaN = xp.asarray(xp.nan) + xp_assert_equal(res.statistic, NaN) + xp_assert_equal(res.pvalue, NaN) + else: + message = "At least one observation is required." + with pytest.raises(ValueError, match=message): + res = stats.jarque_bera(x) + + def test_axis(self, xp): + rng = np.random.RandomState(seed=122398129) + x = xp.asarray(rng.random(size=(2, 45))) + + res = stats.jarque_bera(x, axis=None) + ref = stats.jarque_bera(xp.reshape(x, (-1,))) + xp_assert_equal(res.statistic, ref.statistic) + xp_assert_equal(res.pvalue, ref.pvalue) + + res = stats.jarque_bera(x, axis=1) + s0, p0 = stats.jarque_bera(x[0, :]) + s1, p1 = stats.jarque_bera(x[1, :]) + xp_assert_close(res.statistic, xp.asarray([s0, s1])) + xp_assert_close(res.pvalue, xp.asarray([p0, p1])) + + resT = stats.jarque_bera(x.T, axis=0) + xp_assert_close(res.statistic, resT.statistic) + xp_assert_close(res.pvalue, resT.pvalue) + + +class TestMannWhitneyU: + X = [19.8958398126694, 19.5452691647182, 19.0577309166425, 21.716543054589, + 20.3269502208702, 20.0009273294025, 19.3440043632957, 20.4216806548105, + 19.0649894736528, 18.7808043120398, 19.3680942943298, 19.4848044069953, + 20.7514611265663, 19.0894948874598, 19.4975522356628, 18.9971170734274, + 20.3239606288208, 20.6921298083835, 19.0724259532507, 18.9825187935021, + 19.5144462609601, 19.8256857844223, 20.5174677102032, 21.1122407995892, + 17.9490854922535, 18.2847521114727, 20.1072217648826, 18.6439891962179, + 20.4970638083542, 19.5567594734914] + + Y = [19.2790668029091, 16.993808441865, 18.5416338448258, 17.2634018833575, + 19.1577183624616, 18.5119655377495, 18.6068455037221, 18.8358343362655, + 19.0366413269742, 18.1135025515417, 19.2201873866958, 17.8344909022841, + 18.2894380745856, 18.6661374133922, 19.9688601693252, 16.0672254617636, + 19.00596360572, 19.201561539032, 19.0487501090183, 19.0847908674356] + + significant = 14 + + def test_mannwhitneyu_one_sided(self): + u1, p1 = stats.mannwhitneyu(self.X, self.Y, alternative='less') + u2, p2 = stats.mannwhitneyu(self.Y, self.X, alternative='greater') + u3, p3 = stats.mannwhitneyu(self.X, self.Y, alternative='greater') + u4, p4 = stats.mannwhitneyu(self.Y, self.X, alternative='less') + + assert_equal(p1, p2) + assert_equal(p3, p4) + assert_(p1 != p3) + assert_equal(u1, 498) + assert_equal(u2, 102) + assert_equal(u3, 498) + assert_equal(u4, 102) + assert_approx_equal(p1, 0.999957683256589, significant=self.significant) + assert_approx_equal(p3, 4.5941632666275e-05, significant=self.significant) + + def test_mannwhitneyu_two_sided(self): + u1, p1 = stats.mannwhitneyu(self.X, self.Y, alternative='two-sided') + u2, p2 = stats.mannwhitneyu(self.Y, self.X, alternative='two-sided') + + assert_equal(p1, p2) + assert_equal(u1, 498) + assert_equal(u2, 102) + assert_approx_equal(p1, 9.188326533255e-05, + significant=self.significant) + + def test_mannwhitneyu_no_correct_one_sided(self): + u1, p1 = stats.mannwhitneyu(self.X, self.Y, False, + alternative='less') + u2, p2 = stats.mannwhitneyu(self.Y, self.X, False, + alternative='greater') + u3, p3 = stats.mannwhitneyu(self.X, self.Y, False, + alternative='greater') + u4, p4 = stats.mannwhitneyu(self.Y, self.X, False, + alternative='less') + + assert_equal(p1, p2) + assert_equal(p3, p4) + assert_(p1 != p3) + assert_equal(u1, 498) + assert_equal(u2, 102) + assert_equal(u3, 498) + assert_equal(u4, 102) + assert_approx_equal(p1, 0.999955905990004, significant=self.significant) + assert_approx_equal(p3, 4.40940099958089e-05, significant=self.significant) + + def test_mannwhitneyu_no_correct_two_sided(self): + u1, p1 = stats.mannwhitneyu(self.X, self.Y, False, + alternative='two-sided') + u2, p2 = stats.mannwhitneyu(self.Y, self.X, False, + alternative='two-sided') + + assert_equal(p1, p2) + assert_equal(u1, 498) + assert_equal(u2, 102) + assert_approx_equal(p1, 8.81880199916178e-05, + significant=self.significant) + + def test_mannwhitneyu_ones(self): + # test for gh-1428 + x = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 2., 1., 1., 2., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 3., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1.]) + + y = np.array([1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., 1., 1., 1., + 2., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., 1., 1., 3., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., + 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., + 2., 1., 1., 2., 1., 1., 2., 1., 2., 1., 1., 1., 1., 2., + 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 2., 1., 1., 1., 1., 1., 2., 2., 2., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 2., 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 2., 1., 1., + 1., 1., 1., 1.]) + + # checked against R wilcox.test + assert_allclose(stats.mannwhitneyu(x, y, alternative='less'), + (16980.5, 2.8214327656317373e-005)) + # p-value from R, e.g. wilcox.test(x, y, alternative="g") + assert_allclose(stats.mannwhitneyu(x, y, alternative='greater'), + (16980.5, 0.9999719954296)) + assert_allclose(stats.mannwhitneyu(x, y, alternative='two-sided'), + (16980.5, 5.642865531266e-05)) + + def test_mannwhitneyu_result_attributes(self): + # test for namedtuple attribute results + attributes = ('statistic', 'pvalue') + res = stats.mannwhitneyu(self.X, self.Y, alternative="less") + check_named_results(res, attributes) + + +def test_pointbiserial(): + # same as mstats test except for the nan + # Test data: https://web.archive.org/web/20060504220742/https://support.sas.com/ctx/samples/index.jsp?sid=490&tab=output + x = [1,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0, + 0,0,0,0,1] + y = [14.8,13.8,12.4,10.1,7.1,6.1,5.8,4.6,4.3,3.5,3.3,3.2,3.0, + 2.8,2.8,2.5,2.4,2.3,2.1,1.7,1.7,1.5,1.3,1.3,1.2,1.2,1.1, + 0.8,0.7,0.6,0.5,0.2,0.2,0.1] + assert_almost_equal(stats.pointbiserialr(x, y)[0], 0.36149, 5) + + # test for namedtuple attribute results + attributes = ('correlation', 'pvalue') + res = stats.pointbiserialr(x, y) + check_named_results(res, attributes) + assert_equal(res.correlation, res.statistic) + + +def test_obrientransform(): + # A couple tests calculated by hand. + x1 = np.array([0, 2, 4]) + t1 = stats.obrientransform(x1) + expected = [7, -2, 7] + assert_allclose(t1[0], expected) + + x2 = np.array([0, 3, 6, 9]) + t2 = stats.obrientransform(x2) + expected = np.array([30, 0, 0, 30]) + assert_allclose(t2[0], expected) + + # Test two arguments. + a, b = stats.obrientransform(x1, x2) + assert_equal(a, t1[0]) + assert_equal(b, t2[0]) + + # Test three arguments. + a, b, c = stats.obrientransform(x1, x2, x1) + assert_equal(a, t1[0]) + assert_equal(b, t2[0]) + assert_equal(c, t1[0]) + + # This is a regression test to check np.var replacement. + # The author of this test didn't separately verify the numbers. + x1 = np.arange(5) + result = np.array( + [[5.41666667, 1.04166667, -0.41666667, 1.04166667, 5.41666667], + [21.66666667, 4.16666667, -1.66666667, 4.16666667, 21.66666667]]) + assert_array_almost_equal(stats.obrientransform(x1, 2*x1), result, decimal=8) + + # Example from "O'Brien Test for Homogeneity of Variance" + # by Herve Abdi. + values = range(5, 11) + reps = np.array([5, 11, 9, 3, 2, 2]) + data = np.repeat(values, reps) + transformed_values = np.array([3.1828, 0.5591, 0.0344, + 1.6086, 5.2817, 11.0538]) + expected = np.repeat(transformed_values, reps) + result = stats.obrientransform(data) + assert_array_almost_equal(result[0], expected, decimal=4) + + +def check_equal_xmean(*args, xp, mean_fun, axis=None, dtype=None, + rtol=1e-7, weights=None): + # Note this doesn't test when axis is not specified + dtype = dtype or xp.float64 + if len(args) == 2: + array_like, desired = args + else: + array_like, p, desired = args + array_like = xp.asarray(array_like, dtype=dtype) + desired = xp.asarray(desired, dtype=dtype) + weights = xp.asarray(weights, dtype=dtype) if weights is not None else weights + args = (array_like,) if len(args) == 2 else (array_like, p) + x = mean_fun(*args, axis=axis, dtype=dtype, weights=weights) + xp_assert_close(x, desired, rtol=rtol) + + +def check_equal_gmean(*args, **kwargs): + return check_equal_xmean(*args, mean_fun=stats.gmean, **kwargs) + + +def check_equal_hmean(*args, **kwargs): + return check_equal_xmean(*args, mean_fun=stats.hmean, **kwargs) + + +def check_equal_pmean(*args, **kwargs): + return check_equal_xmean(*args, mean_fun=stats.pmean, **kwargs) + + +@array_api_compatible +class TestHMean: + def test_0(self, xp): + a = [1, 0, 2] + desired = 0 + check_equal_hmean(a, desired, xp=xp) + + def test_1d(self, xp): + # Test a 1d case + a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + desired = 34.1417152147 + check_equal_hmean(a, desired, xp=xp) + + a = [1, 2, 3, 4] + desired = 4. / (1. / 1 + 1. / 2 + 1. / 3 + 1. / 4) + check_equal_hmean(a, desired, xp=xp) + + def test_1d_with_zero(self, xp): + a = np.array([1, 0]) + desired = 0.0 + check_equal_hmean(a, desired, xp=xp, rtol=0.0) + + @skip_xp_backends('array_api_strict', + reason=("`array_api_strict.where` `fillvalue` doesn't " + "accept Python scalars. See data-apis/array-api#807.")) + @pytest.mark.usefixtures("skip_xp_backends") + def test_1d_with_negative_value(self, xp): + # Won't work for array_api_strict for now, but see data-apis/array-api#807 + a = np.array([1, 0, -1]) + message = "The harmonic mean is only defined..." + with pytest.warns(RuntimeWarning, match=message): + check_equal_hmean(a, xp.nan, xp=xp, rtol=0.0) + + # Note the next tests use axis=None as default, not axis=0 + def test_2d(self, xp): + # Test a 2d case + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = 38.6696271841 + check_equal_hmean(np.array(a), desired, xp=xp) + + def test_2d_axis0(self, xp): + # Test a 2d case with axis=0 + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = np.array([22.88135593, 39.13043478, 52.90076336, 65.45454545]) + check_equal_hmean(a, desired, axis=0, xp=xp) + + def test_2d_axis0_with_zero(self, xp): + a = [[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = np.array([22.88135593, 0.0, 52.90076336, 65.45454545]) + check_equal_hmean(a, desired, axis=0, xp=xp) + + def test_2d_axis1(self, xp): + # Test a 2d case with axis=1 + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = np.array([19.2, 63.03939962, 103.80078637]) + check_equal_hmean(a, desired, axis=1, xp=xp) + + def test_2d_axis1_with_zero(self, xp): + a = [[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = np.array([0.0, 63.03939962, 103.80078637]) + check_equal_hmean(a, desired, axis=1, xp=xp) + + @pytest.mark.skip_xp_backends( + np_only=True, + reason='array-likes only supported for NumPy backend', + ) + @pytest.mark.usefixtures("skip_xp_backends") + def test_weights_1d_list(self, xp): + # Desired result from: + # https://www.hackmath.net/en/math-problem/35871 + a = [2, 10, 6] + weights = [10, 5, 3] + desired = 3. + # all the other tests use `check_equal_hmean`, which now converts + # the input to an xp-array before calling `hmean`. This time, check + # that the function still accepts the lists of ints. + res = stats.hmean(a, weights=weights) + xp_assert_close(res, np.asarray(desired), rtol=1e-5) + + def test_weights_1d(self, xp): + # Desired result from: + # https://www.hackmath.net/en/math-problem/35871 + a = np.asarray([2, 10, 6]) + weights = np.asarray([10, 5, 3]) + desired = 3 + check_equal_hmean(a, desired, weights=weights, rtol=1e-5, xp=xp) + + def test_weights_2d_axis0(self, xp): + # Desired result from: + # https://www.hackmath.net/en/math-problem/35871 + a = np.array([[2, 5], [10, 5], [6, 5]]) + weights = np.array([[10, 1], [5, 1], [3, 1]]) + desired = np.array([3, 5]) + check_equal_hmean(a, desired, axis=0, weights=weights, rtol=1e-5, xp=xp) + + def test_weights_2d_axis1(self, xp): + # Desired result from: + # https://www.hackmath.net/en/math-problem/35871 + a = np.array([[2, 10, 6], [7, 7, 7]]) + weights = np.array([[10, 5, 3], [1, 1, 1]]) + desired = np.array([3, 7]) + check_equal_hmean(a, desired, axis=1, weights=weights, rtol=1e-5, xp=xp) + + @skip_xp_invalid_arg + def test_weights_masked_1d_array(self, xp): + # Desired result from: + # https://www.hackmath.net/en/math-problem/35871 + a = np.array([2, 10, 6, 42]) + weights = np.ma.array([10, 5, 3, 42], mask=[0, 0, 0, 1]) + desired = 3 + xp = np.ma # check_equal_hmean uses xp.asarray; this will preserve the mask + check_equal_hmean(a, desired, weights=weights, rtol=1e-5, + dtype=np.float64, xp=xp) + + +@array_api_compatible +class TestGMean: + def test_0(self, xp): + a = [1, 0, 2] + desired = 0 + check_equal_gmean(a, desired, xp=xp) + + def test_1d(self, xp): + # Test a 1d case + a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + desired = 45.2872868812 + check_equal_gmean(a, desired, xp=xp) + + a = [1, 2, 3, 4] + desired = power(1 * 2 * 3 * 4, 1. / 4.) + check_equal_gmean(a, desired, rtol=1e-14, xp=xp) + + a = array([1, 2, 3, 4], float32) + desired = power(1 * 2 * 3 * 4, 1. / 4.) + check_equal_gmean(a, desired, dtype=xp.float32, xp=xp) + + # Note the next tests use axis=None as default, not axis=0 + def test_2d(self, xp): + # Test a 2d case + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = 52.8885199 + check_equal_gmean(a, desired, xp=xp) + + def test_2d_axis0(self, xp): + # Test a 2d case with axis=0 + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = np.array([35.56893304, 49.32424149, 61.3579244, 72.68482371]) + check_equal_gmean(a, desired, axis=0, xp=xp) + + a = array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) + desired = array([1, 2, 3, 4]) + check_equal_gmean(a, desired, axis=0, rtol=1e-14, xp=xp) + + def test_2d_axis1(self, xp): + # Test a 2d case with axis=1 + a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] + desired = np.array([22.13363839, 64.02171746, 104.40086817]) + check_equal_gmean(a, desired, axis=1, xp=xp) + + a = array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) + v = power(1 * 2 * 3 * 4, 1. / 4.) + desired = array([v, v, v]) + check_equal_gmean(a, desired, axis=1, rtol=1e-14, xp=xp) + + def test_large_values(self, xp): + a = array([1e100, 1e200, 1e300]) + desired = 1e200 + check_equal_gmean(a, desired, rtol=1e-13, xp=xp) + + def test_1d_with_0(self, xp): + # Test a 1d case with zero element + a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 0] + desired = 0.0 # due to exp(-inf)=0 + with np.errstate(all='ignore'): + check_equal_gmean(a, desired, xp=xp) + + def test_1d_neg(self, xp): + # Test a 1d case with negative element + a = [10, 20, 30, 40, 50, 60, 70, 80, 90, -1] + desired = np.nan # due to log(-1) = nan + with np.errstate(invalid='ignore'): + check_equal_gmean(a, desired, xp=xp) + + @pytest.mark.skip_xp_backends( + np_only=True, + reason='array-likes only supported for NumPy backend', + ) + @pytest.mark.usefixtures("skip_xp_backends") + def test_weights_1d_list(self, xp): + # Desired result from: + # https://www.dummies.com/education/math/business-statistics/how-to-find-the-weighted-geometric-mean-of-a-data-set/ + a = [1, 2, 3, 4, 5] + weights = [2, 5, 6, 4, 3] + desired = 2.77748 + + # all the other tests use `check_equal_gmean`, which now converts + # the input to an xp-array before calling `gmean`. This time, check + # that the function still accepts the lists of ints. + res = stats.gmean(a, weights=weights) + xp_assert_close(res, np.asarray(desired), rtol=1e-5) + + def test_weights_1d(self, xp): + # Desired result from: + # https://www.dummies.com/education/math/business-statistics/how-to-find-the-weighted-geometric-mean-of-a-data-set/ + a = np.array([1, 2, 3, 4, 5]) + weights = np.array([2, 5, 6, 4, 3]) + desired = 2.77748 + check_equal_gmean(a, desired, weights=weights, rtol=1e-5, xp=xp) + + @skip_xp_invalid_arg + def test_weights_masked_1d_array(self, xp): + # Desired result from: + # https://www.dummies.com/education/math/business-statistics/how-to-find-the-weighted-geometric-mean-of-a-data-set/ + a = np.array([1, 2, 3, 4, 5, 6]) + weights = np.ma.array([2, 5, 6, 4, 3, 5], mask=[0, 0, 0, 0, 0, 1]) + desired = 2.77748 + xp = np.ma # check_equal_gmean uses xp.asarray; this will preserve the mask + check_equal_gmean(a, desired, weights=weights, rtol=1e-5, + dtype=np.float64, xp=xp) + + +@array_api_compatible +class TestPMean: + + def pmean_reference(a, p): + return (np.sum(a**p) / a.size)**(1/p) + + def wpmean_reference(a, p, weights): + return (np.sum(weights * a**p) / np.sum(weights))**(1/p) + + def test_bad_exponent(self, xp): + with pytest.raises(ValueError, match='Power mean only defined for'): + stats.pmean(xp.asarray([1, 2, 3]), xp.asarray([0])) + with pytest.raises(ValueError, match='Power mean only defined for'): + stats.pmean(xp.asarray([1, 2, 3]), xp.asarray([0])) + + def test_1d(self, xp): + a, p = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 3.5 + desired = TestPMean.pmean_reference(np.array(a), p) + check_equal_pmean(a, p, desired, xp=xp) + + a, p = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], -2.5 + desired = TestPMean.pmean_reference(np.array(a), p) + check_equal_pmean(a, p, desired, xp=xp) + + a, p = [1, 2, 3, 4], 2 + desired = np.sqrt((1**2 + 2**2 + 3**2 + 4**2) / 4) + check_equal_pmean(a, p, desired, xp=xp) + + def test_1d_with_zero(self, xp): + a, p = np.array([1, 0]), -1 + desired = 0.0 + check_equal_pmean(a, p, desired, rtol=0.0, xp=xp) + + @skip_xp_backends('array_api_strict', + reason=("`array_api_strict.where` `fillvalue` doesn't " + "accept Python scalars. See data-apis/array-api#807.")) + @pytest.mark.usefixtures("skip_xp_backends") + def test_1d_with_negative_value(self, xp): + a, p = np.array([1, 0, -1]), 1.23 + message = "The power mean is only defined..." + with pytest.warns(RuntimeWarning, match=message): + check_equal_pmean(a, p, xp.nan, xp=xp) + + @pytest.mark.parametrize( + ("a", "p"), + [([[10, 20], [50, 60], [90, 100]], -0.5), + (np.array([[10, 20], [50, 60], [90, 100]]), 0.5)] + ) + def test_2d_axisnone(self, a, p, xp): + desired = TestPMean.pmean_reference(np.array(a), p) + check_equal_pmean(a, p, desired, xp=xp) + + @pytest.mark.parametrize( + ("a", "p"), + [([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], -0.5), + ([[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], 0.5)] + ) + def test_2d_axis0(self, a, p, xp): + desired = [ + TestPMean.pmean_reference( + np.array([a[i][j] for i in range(len(a))]), p + ) + for j in range(len(a[0])) + ] + check_equal_pmean(a, p, desired, axis=0, xp=xp) + + @pytest.mark.parametrize( + ("a", "p"), + [([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], -0.5), + ([[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], 0.5)] + ) + def test_2d_axis1(self, a, p, xp): + desired = [TestPMean.pmean_reference(np.array(a_), p) for a_ in a] + check_equal_pmean(a, p, desired, axis=1, xp=xp) + + def test_weights_1d(self, xp): + a, p = [2, 10, 6], -1.23456789 + weights = [10, 5, 3] + desired = TestPMean.wpmean_reference(np.array(a), p, weights) + check_equal_pmean(a, p, desired, weights=weights, rtol=1e-5, xp=xp) + + @pytest.mark.skip_xp_backends( + np_only=True, + reason='array-likes only supported for NumPy backend', + ) + @pytest.mark.usefixtures("skip_xp_backends") + def test_weights_1d_list(self, xp): + a, p = [2, 10, 6], -1.23456789 + weights = [10, 5, 3] + desired = TestPMean.wpmean_reference(np.array(a), p, weights) + # all the other tests use `check_equal_pmean`, which now converts + # the input to an xp-array before calling `pmean`. This time, check + # that the function still accepts the lists of ints. + res = stats.pmean(a, p, weights=weights) + xp_assert_close(res, np.asarray(desired), rtol=1e-5) + + @skip_xp_invalid_arg + def test_weights_masked_1d_array(self, xp): + a, p = np.array([2, 10, 6, 42]), 1 + weights = np.ma.array([10, 5, 3, 42], mask=[0, 0, 0, 1]) + desired = np.average(a, weights=weights) + xp = np.ma # check_equal_pmean uses xp.asarray; this will preserve the mask + check_equal_pmean(a, p, desired, weights=weights, rtol=1e-5, + dtype=np.float64, xp=xp) + + @pytest.mark.parametrize( + ("axis", "fun_name", "p"), + [(None, "wpmean_reference", 9.87654321), + (0, "gmean", 0), + (1, "hmean", -1)] + ) + def test_weights_2d(self, axis, fun_name, p, xp): + if fun_name == 'wpmean_reference': + def fun(a, axis, weights): + return TestPMean.wpmean_reference(a, p, weights) + else: + fun = getattr(stats, fun_name) + a = np.array([[2, 5], [10, 5], [6, 5]]) + weights = np.array([[10, 1], [5, 1], [3, 1]]) + desired = fun(a, axis=axis, weights=weights) + check_equal_pmean(a, p, desired, axis=axis, weights=weights, rtol=1e-5, xp=xp) + + +class TestGSTD: + # must add 1 as `gstd` is only defined for positive values + array_1d = np.arange(2 * 3 * 4) + 1 + gstd_array_1d = 2.294407613602 + array_3d = array_1d.reshape(2, 3, 4) + + def test_1d_array(self): + gstd_actual = stats.gstd(self.array_1d) + assert_allclose(gstd_actual, self.gstd_array_1d) + + def test_1d_numeric_array_like_input(self): + gstd_actual = stats.gstd(tuple(self.array_1d)) + assert_allclose(gstd_actual, self.gstd_array_1d) + + def test_raises_value_error_non_numeric_input(self): + # this is raised by NumPy, but it's quite interpretable + with pytest.raises(TypeError, match="ufunc 'log' not supported"): + stats.gstd('You cannot take the logarithm of a string.') + + @pytest.mark.parametrize('bad_value', (0, -1, np.inf, np.nan)) + def test_returns_nan_invalid_value(self, bad_value): + x = np.append(self.array_1d, [bad_value]) + if np.isfinite(bad_value): + message = "The geometric standard deviation is only defined..." + with pytest.warns(RuntimeWarning, match=message): + res = stats.gstd(x) + else: + res = stats.gstd(x) + assert_equal(res, np.nan) + + def test_propagates_nan_values(self): + a = array([[1, 1, 1, 16], [np.nan, 1, 2, 3]]) + gstd_actual = stats.gstd(a, axis=1) + assert_allclose(gstd_actual, np.array([4, np.nan])) + + def test_ddof_equal_to_number_of_observations(self): + with pytest.warns(RuntimeWarning, match='Degrees of freedom <= 0'): + assert_equal(stats.gstd(self.array_1d, ddof=self.array_1d.size), np.inf) + + def test_3d_array(self): + gstd_actual = stats.gstd(self.array_3d, axis=None) + assert_allclose(gstd_actual, self.gstd_array_1d) + + def test_3d_array_axis_type_tuple(self): + gstd_actual = stats.gstd(self.array_3d, axis=(1,2)) + assert_allclose(gstd_actual, [2.12939215, 1.22120169]) + + def test_3d_array_axis_0(self): + gstd_actual = stats.gstd(self.array_3d, axis=0) + gstd_desired = np.array([ + [6.1330555493918, 3.958900210120, 3.1206598248344, 2.6651441426902], + [2.3758135028411, 2.174581428192, 2.0260062829505, 1.9115518327308], + [1.8205343606803, 1.746342404566, 1.6846557065742, 1.6325269194382] + ]) + assert_allclose(gstd_actual, gstd_desired) + + def test_3d_array_axis_1(self): + gstd_actual = stats.gstd(self.array_3d, axis=1) + gstd_desired = np.array([ + [3.118993630946, 2.275985934063, 1.933995977619, 1.742896469724], + [1.271693593916, 1.254158641801, 1.238774141609, 1.225164057869] + ]) + assert_allclose(gstd_actual, gstd_desired) + + def test_3d_array_axis_2(self): + gstd_actual = stats.gstd(self.array_3d, axis=2) + gstd_desired = np.array([ + [1.8242475707664, 1.2243686572447, 1.1318311657788], + [1.0934830582351, 1.0724479791887, 1.0591498540749] + ]) + assert_allclose(gstd_actual, gstd_desired) + + def test_masked_3d_array(self): + ma = np.ma.masked_where(self.array_3d > 16, self.array_3d) + message = "`gstd` support for masked array input was deprecated in..." + with pytest.warns(DeprecationWarning, match=message): + gstd_actual = stats.gstd(ma, axis=2) + gstd_desired = stats.gstd(self.array_3d, axis=2) + mask = [[0, 0, 0], [0, 1, 1]] + assert_allclose(gstd_actual, gstd_desired) + assert_equal(gstd_actual.mask, mask) + + +def test_binomtest(): + # precision tests compared to R for ticket:986 + pp = np.concatenate((np.linspace(0.1, 0.2, 5), + np.linspace(0.45, 0.65, 5), + np.linspace(0.85, 0.95, 5))) + n = 501 + x = 450 + results = [0.0, 0.0, 1.0159969301994141e-304, + 2.9752418572150531e-275, 7.7668382922535275e-250, + 2.3381250925167094e-099, 7.8284591587323951e-081, + 9.9155947819961383e-065, 2.8729390725176308e-050, + 1.7175066298388421e-037, 0.0021070691951093692, + 0.12044570587262322, 0.88154763174802508, 0.027120993063129286, + 2.6102587134694721e-006] + + for p, res in zip(pp, results): + assert_approx_equal(stats.binomtest(x, n, p).pvalue, res, + significant=12, err_msg=f'fail forp={p}') + assert_approx_equal(stats.binomtest(50, 100, 0.1).pvalue, + 5.8320387857343647e-024, + significant=12) + + +def test_binomtest2(): + # test added for issue #2384 + res2 = [ + [1.0, 1.0], + [0.5, 1.0, 0.5], + [0.25, 1.00, 1.00, 0.25], + [0.125, 0.625, 1.000, 0.625, 0.125], + [0.0625, 0.3750, 1.0000, 1.0000, 0.3750, 0.0625], + [0.03125, 0.21875, 0.68750, 1.00000, 0.68750, 0.21875, 0.03125], + [0.015625, 0.125000, 0.453125, 1.000000, 1.000000, 0.453125, 0.125000, + 0.015625], + [0.0078125, 0.0703125, 0.2890625, 0.7265625, 1.0000000, 0.7265625, + 0.2890625, 0.0703125, 0.0078125], + [0.00390625, 0.03906250, 0.17968750, 0.50781250, 1.00000000, + 1.00000000, 0.50781250, 0.17968750, 0.03906250, 0.00390625], + [0.001953125, 0.021484375, 0.109375000, 0.343750000, 0.753906250, + 1.000000000, 0.753906250, 0.343750000, 0.109375000, 0.021484375, + 0.001953125] + ] + for k in range(1, 11): + res1 = [stats.binomtest(v, k, 0.5).pvalue for v in range(k + 1)] + assert_almost_equal(res1, res2[k-1], decimal=10) + + +def test_binomtest3(): + # test added for issue #2384 + # test when x == n*p and neighbors + res3 = [stats.binomtest(v, v*k, 1./k).pvalue + for v in range(1, 11) for k in range(2, 11)] + assert_equal(res3, np.ones(len(res3), int)) + + # > bt=c() + # > for(i in as.single(1:10)) { + # + for(k in as.single(2:10)) { + # + bt = c(bt, binom.test(i-1, k*i,(1/k))$p.value); + # + print(c(i+1, k*i,(1/k))) + # + } + # + } + binom_testm1 = np.array([ + 0.5, 0.5555555555555556, 0.578125, 0.5904000000000003, + 0.5981224279835393, 0.603430543396034, 0.607304096221924, + 0.610255656871054, 0.612579511000001, 0.625, 0.670781893004115, + 0.68853759765625, 0.6980101120000006, 0.703906431368616, + 0.70793209416498, 0.7108561134173507, 0.713076544331419, + 0.714820192935702, 0.6875, 0.7268709038256367, 0.7418963909149174, + 0.74986110468096, 0.7548015520398076, 0.7581671424768577, + 0.760607984787832, 0.762459425024199, 0.7639120677676575, 0.7265625, + 0.761553963657302, 0.774800934828818, 0.7818005980538996, + 0.78613491480358, 0.789084353140195, 0.7912217659828884, + 0.79284214559524, 0.794112956558801, 0.75390625, 0.7856929451142176, + 0.7976688481430754, 0.8039848974727624, 0.807891868948366, + 0.8105487660137676, 0.812473307174702, 0.8139318233591120, + 0.815075399104785, 0.7744140625, 0.8037322594985427, + 0.814742863657656, 0.8205425178645808, 0.8241275984172285, + 0.8265645374416, 0.8283292196088257, 0.829666291102775, + 0.8307144686362666, 0.7905273437499996, 0.8178712053954738, + 0.828116983756619, 0.833508948940494, 0.8368403871552892, + 0.839104213210105, 0.840743186196171, 0.84198481438049, + 0.8429580531563676, 0.803619384765625, 0.829338573944648, + 0.8389591907548646, 0.84401876783902, 0.84714369697889, + 0.8492667010581667, 0.850803474598719, 0.851967542858308, + 0.8528799045949524, 0.8145294189453126, 0.838881732845347, + 0.847979024541911, 0.852760894015685, 0.8557134656773457, + 0.8577190131799202, 0.85917058278431, 0.860270010472127, + 0.861131648404582, 0.823802947998047, 0.846984756807511, + 0.855635653643743, 0.860180994825685, 0.86298688573253, + 0.864892525675245, 0.866271647085603, 0.867316125625004, + 0.8681346531755114 + ]) + + # > bt=c() + # > for(i in as.single(1:10)) { + # + for(k in as.single(2:10)) { + # + bt = c(bt, binom.test(i+1, k*i,(1/k))$p.value); + # + print(c(i+1, k*i,(1/k))) + # + } + # + } + + binom_testp1 = np.array([ + 0.5, 0.259259259259259, 0.26171875, 0.26272, 0.2632244513031551, + 0.2635138663069203, 0.2636951804161073, 0.2638162407564354, + 0.2639010709000002, 0.625, 0.4074074074074074, 0.42156982421875, + 0.4295746560000003, 0.43473045988554, 0.4383309503172684, + 0.4409884859402103, 0.4430309389962837, 0.444649849401104, 0.6875, + 0.4927602499618962, 0.5096031427383425, 0.5189636628480, + 0.5249280070771274, 0.5290623300865124, 0.5320974248125793, + 0.5344204730474308, 0.536255847400756, 0.7265625, 0.5496019313526808, + 0.5669248746708034, 0.576436455045805, 0.5824538812831795, + 0.5866053321547824, 0.589642781414643, 0.5919618019300193, + 0.593790427805202, 0.75390625, 0.590868349763505, 0.607983393277209, + 0.617303847446822, 0.623172512167948, 0.627208862156123, + 0.6301556891501057, 0.632401894928977, 0.6341708982290303, + 0.7744140625, 0.622562037497196, 0.639236102912278, 0.648263335014579, + 0.65392850011132, 0.657816519817211, 0.660650782947676, + 0.662808780346311, 0.6645068560246006, 0.7905273437499996, + 0.6478843304312477, 0.6640468318879372, 0.6727589686071775, + 0.6782129857784873, 0.681950188903695, 0.684671508668418, + 0.686741824999918, 0.688369886732168, 0.803619384765625, + 0.668716055304315, 0.684360013879534, 0.6927642396829181, + 0.6980155964704895, 0.701609591890657, 0.7042244320992127, + 0.7062125081341817, 0.707775152962577, 0.8145294189453126, + 0.686243374488305, 0.7013873696358975, 0.709501223328243, + 0.714563595144314, 0.718024953392931, 0.7205416252126137, + 0.722454130389843, 0.723956813292035, 0.823802947998047, + 0.701255953767043, 0.715928221686075, 0.723772209289768, + 0.7286603031173616, 0.7319999279787631, 0.7344267920995765, + 0.736270323773157, 0.737718376096348 + ]) + + res4_p1 = [stats.binomtest(v+1, v*k, 1./k).pvalue + for v in range(1, 11) for k in range(2, 11)] + res4_m1 = [stats.binomtest(v-1, v*k, 1./k).pvalue + for v in range(1, 11) for k in range(2, 11)] + + assert_almost_equal(res4_p1, binom_testp1, decimal=13) + assert_almost_equal(res4_m1, binom_testm1, decimal=13) + + +class TestTrim: + # test trim functions + def test_trim1(self): + a = np.arange(11) + assert_equal(np.sort(stats.trim1(a, 0.1)), np.arange(10)) + assert_equal(np.sort(stats.trim1(a, 0.2)), np.arange(9)) + assert_equal(np.sort(stats.trim1(a, 0.2, tail='left')), + np.arange(2, 11)) + assert_equal(np.sort(stats.trim1(a, 3/11., tail='left')), + np.arange(3, 11)) + assert_equal(stats.trim1(a, 1.0), []) + assert_equal(stats.trim1(a, 1.0, tail='left'), []) + + # empty input + assert_equal(stats.trim1([], 0.1), []) + assert_equal(stats.trim1([], 3/11., tail='left'), []) + assert_equal(stats.trim1([], 4/6.), []) + + # test axis + a = np.arange(24).reshape(6, 4) + ref = np.arange(4, 24).reshape(5, 4) # first row trimmed + + axis = 0 + trimmed = stats.trim1(a, 0.2, tail='left', axis=axis) + assert_equal(np.sort(trimmed, axis=axis), ref) + + axis = 1 + trimmed = stats.trim1(a.T, 0.2, tail='left', axis=axis) + assert_equal(np.sort(trimmed, axis=axis), ref.T) + + def test_trimboth(self): + a = np.arange(11) + assert_equal(np.sort(stats.trimboth(a, 3/11.)), np.arange(3, 8)) + assert_equal(np.sort(stats.trimboth(a, 0.2)), + np.array([2, 3, 4, 5, 6, 7, 8])) + assert_equal(np.sort(stats.trimboth(np.arange(24).reshape(6, 4), 0.2)), + np.arange(4, 20).reshape(4, 4)) + assert_equal(np.sort(stats.trimboth(np.arange(24).reshape(4, 6).T, + 2/6.)), + np.array([[2, 8, 14, 20], [3, 9, 15, 21]])) + assert_raises(ValueError, stats.trimboth, + np.arange(24).reshape(4, 6).T, 4/6.) + + # empty input + assert_equal(stats.trimboth([], 0.1), []) + assert_equal(stats.trimboth([], 3/11.), []) + assert_equal(stats.trimboth([], 4/6.), []) + + def test_trim_mean(self): + # don't use pre-sorted arrays + a = np.array([4, 8, 2, 0, 9, 5, 10, 1, 7, 3, 6]) + idx = np.array([3, 5, 0, 1, 2, 4]) + a2 = np.arange(24).reshape(6, 4)[idx, :] + a3 = np.arange(24).reshape(6, 4, order='F')[idx, :] + assert_equal(stats.trim_mean(a3, 2/6.), + np.array([2.5, 8.5, 14.5, 20.5])) + assert_equal(stats.trim_mean(a2, 2/6.), + np.array([10., 11., 12., 13.])) + idx4 = np.array([1, 0, 3, 2]) + a4 = np.arange(24).reshape(4, 6)[idx4, :] + assert_equal(stats.trim_mean(a4, 2/6.), + np.array([9., 10., 11., 12., 13., 14.])) + # shuffled arange(24) as array_like + a = [7, 11, 12, 21, 16, 6, 22, 1, 5, 0, 18, 10, 17, 9, 19, 15, 23, + 20, 2, 14, 4, 13, 8, 3] + assert_equal(stats.trim_mean(a, 2/6.), 11.5) + assert_equal(stats.trim_mean([5,4,3,1,2,0], 2/6.), 2.5) + + # check axis argument + np.random.seed(1234) + a = np.random.randint(20, size=(5, 6, 4, 7)) + for axis in [0, 1, 2, 3, -1]: + res1 = stats.trim_mean(a, 2/6., axis=axis) + res2 = stats.trim_mean(np.moveaxis(a, axis, 0), 2/6.) + assert_equal(res1, res2) + + res1 = stats.trim_mean(a, 2/6., axis=None) + res2 = stats.trim_mean(a.ravel(), 2/6.) + assert_equal(res1, res2) + + assert_raises(ValueError, stats.trim_mean, a, 0.6) + + # empty input + assert_equal(stats.trim_mean([], 0.0), np.nan) + assert_equal(stats.trim_mean([], 0.6), np.nan) + + +class TestSigmaClip: + def test_sigmaclip1(self): + a = np.concatenate((np.linspace(9.5, 10.5, 31), np.linspace(0, 20, 5))) + fact = 4 # default + c, low, upp = stats.sigmaclip(a) + assert_(c.min() > low) + assert_(c.max() < upp) + assert_equal(low, c.mean() - fact*c.std()) + assert_equal(upp, c.mean() + fact*c.std()) + assert_equal(c.size, a.size) + + def test_sigmaclip2(self): + a = np.concatenate((np.linspace(9.5, 10.5, 31), np.linspace(0, 20, 5))) + fact = 1.5 + c, low, upp = stats.sigmaclip(a, fact, fact) + assert_(c.min() > low) + assert_(c.max() < upp) + assert_equal(low, c.mean() - fact*c.std()) + assert_equal(upp, c.mean() + fact*c.std()) + assert_equal(c.size, 4) + assert_equal(a.size, 36) # check original array unchanged + + def test_sigmaclip3(self): + a = np.concatenate((np.linspace(9.5, 10.5, 11), + np.linspace(-100, -50, 3))) + fact = 1.8 + c, low, upp = stats.sigmaclip(a, fact, fact) + assert_(c.min() > low) + assert_(c.max() < upp) + assert_equal(low, c.mean() - fact*c.std()) + assert_equal(upp, c.mean() + fact*c.std()) + assert_equal(c, np.linspace(9.5, 10.5, 11)) + + def test_sigmaclip_result_attributes(self): + a = np.concatenate((np.linspace(9.5, 10.5, 11), + np.linspace(-100, -50, 3))) + fact = 1.8 + res = stats.sigmaclip(a, fact, fact) + attributes = ('clipped', 'lower', 'upper') + check_named_results(res, attributes) + + def test_std_zero(self): + # regression test #8632 + x = np.ones(10) + assert_equal(stats.sigmaclip(x)[0], x) + + +class TestAlexanderGovern: + def test_compare_dtypes(self): + args = [[13, 13, 13, 13, 13, 13, 13, 12, 12], + [14, 13, 12, 12, 12, 12, 12, 11, 11], + [14, 14, 13, 13, 13, 13, 13, 12, 12], + [15, 14, 13, 13, 13, 12, 12, 12, 11]] + args_int16 = [np.asarray(arg, dtype=np.int16) for arg in args] + args_int32 = [np.asarray(arg, dtype=np.int32) for arg in args] + args_uint8 = [np.asarray(arg, dtype=np.uint8) for arg in args] + args_float64 = [np.asarray(arg, dtype=np.float64) for arg in args] + + res_int16 = stats.alexandergovern(*args_int16) + res_int32 = stats.alexandergovern(*args_int32) + res_uint8 = stats.alexandergovern(*args_uint8) + res_float64 = stats.alexandergovern(*args_float64) + + assert (res_int16.pvalue == res_int32.pvalue == + res_uint8.pvalue == res_float64.pvalue) + assert (res_int16.statistic == res_int32.statistic == + res_uint8.statistic == res_float64.statistic) + + @pytest.mark.parametrize('case',[([1, 2], []), ([1, 2], 2), ([1, 2], [2])]) + def test_too_small_inputs(self, case): + # input array is of size zero or too small + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + res = stats.alexandergovern(*case) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_bad_inputs(self): + # inputs are not finite (infinity) + with np.errstate(invalid='ignore'): + res = stats.alexandergovern([1, 2], [np.inf, np.inf]) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + def test_compare_r(self): + ''' + Data generated in R with + > set.seed(1) + > library("onewaytests") + > library("tibble") + > y <- c(rnorm(40, sd=10), + + rnorm(30, sd=15), + + rnorm(20, sd=20)) + > x <- c(rep("one", times=40), + + rep("two", times=30), + + rep("eight", times=20)) + > x <- factor(x) + > ag.test(y ~ x, tibble(y,x)) + + Alexander-Govern Test (alpha = 0.05) + ------------------------------------------------------------- + data : y and x + + statistic : 1.359941 + parameter : 2 + p.value : 0.5066321 + + Result : Difference is not statistically significant. + ------------------------------------------------------------- + Example adapted from: + https://eval-serv2.metpsy.uni-jena.de/wiki-metheval-hp/index.php/R_FUN_Alexander-Govern + + ''' + one = [-6.264538107423324, 1.8364332422208225, -8.356286124100471, + 15.952808021377916, 3.295077718153605, -8.204683841180152, + 4.874290524284853, 7.383247051292173, 5.757813516534923, + -3.0538838715635603, 15.11781168450848, 3.898432364114311, + -6.2124058054180376, -22.146998871774997, 11.249309181431082, + -0.4493360901523085, -0.16190263098946087, 9.438362106852992, + 8.212211950980885, 5.939013212175088, 9.189773716082183, + 7.821363007310671, 0.745649833651906, -19.89351695863373, + 6.198257478947102, -0.5612873952900078, -1.557955067053293, + -14.707523838992744, -4.781500551086204, 4.179415601997024, + 13.58679551529044, -1.0278772734299553, 3.876716115593691, + -0.5380504058290512, -13.770595568286065, -4.149945632996798, + -3.942899537103493, -0.5931339671118566, 11.000253719838831, + 7.631757484575442] + + two = [-2.4678539438038034, -3.8004252020476135, 10.454450631071062, + 8.34994798010486, -10.331335418242798, -10.612427354431794, + 5.468729432052455, 11.527993867731237, -1.6851931822534207, + 13.216615896813222, 5.971588205506021, -9.180395898761569, + 5.116795371366372, -16.94044644121189, 21.495355525515556, + 29.7059984775879, -5.508322146997636, -15.662019394747961, + 8.545794411636193, -2.0258190582123654, 36.024266407571645, + -0.5886000409975387, 10.346090436761651, 0.4200323817099909, + -11.14909813323608, 2.8318844927151434, -27.074379433365568, + 21.98332292344329, 2.2988000731784655, 32.58917505543229] + + eight = [9.510190577993251, -14.198928618436291, 12.214527069781099, + -18.68195263288503, -25.07266800478204, 5.828924710349257, + -8.86583746436866, 0.02210703263248262, 1.4868264830332811, + -11.79041892376144, -11.37337465637004, -2.7035723024766414, + 23.56173993146409, -30.47133600859524, 11.878923752568431, + 6.659007424270365, 21.261996745527256, -6.083678472686013, + 7.400376198325763, 5.341975815444621] + + one, two, eight = np.asarray(one), np.asarray(two), np.asarray(eight) + soln = stats.alexandergovern(one, two, eight) + assert_allclose(soln.statistic, 1.3599405447999450836) + assert_allclose(soln.pvalue, 0.50663205309676440091) + + def test_compare_scholar(self): + ''' + Data taken from 'The Modification and Evaluation of the + Alexander-Govern Test in Terms of Power' by Kingsley Ochuko, T., + Abdullah, S., Binti Zain, Z., & Soaad Syed Yahaya, S. (2015). + ''' + young = [482.43, 484.36, 488.84, 495.15, 495.24, 502.69, 504.62, + 518.29, 519.1, 524.1, 524.12, 531.18, 548.42, 572.1, 584.68, + 609.09, 609.53, 666.63, 676.4] + middle = [335.59, 338.43, 353.54, 404.27, 437.5, 469.01, 485.85, + 487.3, 493.08, 494.31, 499.1, 886.41] + old = [519.01, 528.5, 530.23, 536.03, 538.56, 538.83, 557.24, 558.61, + 558.95, 565.43, 586.39, 594.69, 629.22, 645.69, 691.84] + young, middle, old = np.asarray(young), np.asarray(middle), np.asarray(old) + soln = stats.alexandergovern(young, middle, old) + assert_allclose(soln.statistic, 5.3237, atol=1e-3) + assert_allclose(soln.pvalue, 0.06982, atol=1e-4) + + # verify with ag.test in r + ''' + > library("onewaytests") + > library("tibble") + > young <- c(482.43, 484.36, 488.84, 495.15, 495.24, 502.69, 504.62, + + 518.29, 519.1, 524.1, 524.12, 531.18, 548.42, 572.1, + + 584.68, 609.09, 609.53, 666.63, 676.4) + > middle <- c(335.59, 338.43, 353.54, 404.27, 437.5, 469.01, 485.85, + + 487.3, 493.08, 494.31, 499.1, 886.41) + > old <- c(519.01, 528.5, 530.23, 536.03, 538.56, 538.83, 557.24, + + 558.61, 558.95, 565.43, 586.39, 594.69, 629.22, + + 645.69, 691.84) + > young_fct <- c(rep("young", times=19)) + > middle_fct <-c(rep("middle", times=12)) + > old_fct <- c(rep("old", times=15)) + > ag.test(a ~ b, tibble(a=c(young, middle, old), b=factor(c(young_fct, + + middle_fct, old_fct)))) + + Alexander-Govern Test (alpha = 0.05) + ------------------------------------------------------------- + data : a and b + + statistic : 5.324629 + parameter : 2 + p.value : 0.06978651 + + Result : Difference is not statistically significant. + ------------------------------------------------------------- + + ''' + assert_allclose(soln.statistic, 5.324629) + assert_allclose(soln.pvalue, 0.06978651) + + def test_compare_scholar3(self): + ''' + Data taken from 'Robustness And Comparative Power Of WelchAspin, + Alexander-Govern And Yuen Tests Under Non-Normality And Variance + Heteroscedasticity', by Ayed A. Almoied. 2017. Page 34-37. + https://digitalcommons.wayne.edu/cgi/viewcontent.cgi?article=2775&context=oa_dissertations + ''' + x1 = [-1.77559, -1.4113, -0.69457, -0.54148, -0.18808, -0.07152, + 0.04696, 0.051183, 0.148695, 0.168052, 0.422561, 0.458555, + 0.616123, 0.709968, 0.839956, 0.857226, 0.929159, 0.981442, + 0.999554, 1.642958] + x2 = [-1.47973, -1.2722, -0.91914, -0.80916, -0.75977, -0.72253, + -0.3601, -0.33273, -0.28859, -0.09637, -0.08969, -0.01824, + 0.260131, 0.289278, 0.518254, 0.683003, 0.877618, 1.172475, + 1.33964, 1.576766] + x1, x2 = np.asarray(x1), np.asarray(x2) + soln = stats.alexandergovern(x1, x2) + assert_allclose(soln.statistic, 0.713526, atol=1e-5) + assert_allclose(soln.pvalue, 0.398276, atol=1e-5) + + ''' + tested in ag.test in R: + > library("onewaytests") + > library("tibble") + > x1 <- c(-1.77559, -1.4113, -0.69457, -0.54148, -0.18808, -0.07152, + + 0.04696, 0.051183, 0.148695, 0.168052, 0.422561, 0.458555, + + 0.616123, 0.709968, 0.839956, 0.857226, 0.929159, 0.981442, + + 0.999554, 1.642958) + > x2 <- c(-1.47973, -1.2722, -0.91914, -0.80916, -0.75977, -0.72253, + + -0.3601, -0.33273, -0.28859, -0.09637, -0.08969, -0.01824, + + 0.260131, 0.289278, 0.518254, 0.683003, 0.877618, 1.172475, + + 1.33964, 1.576766) + > x1_fact <- c(rep("x1", times=20)) + > x2_fact <- c(rep("x2", times=20)) + > a <- c(x1, x2) + > b <- factor(c(x1_fact, x2_fact)) + > ag.test(a ~ b, tibble(a, b)) + Alexander-Govern Test (alpha = 0.05) + ------------------------------------------------------------- + data : a and b + + statistic : 0.7135182 + parameter : 1 + p.value : 0.3982783 + + Result : Difference is not statistically significant. + ------------------------------------------------------------- + ''' + assert_allclose(soln.statistic, 0.7135182) + assert_allclose(soln.pvalue, 0.3982783) + + def test_nan_policy_propagate(self): + args = np.asarray([1, 2, 3, 4]), np.asarray([1, np.nan]) + # default nan_policy is 'propagate' + res = stats.alexandergovern(*args) + assert_equal(res.pvalue, np.nan) + assert_equal(res.statistic, np.nan) + + def test_nan_policy_raise(self): + args = np.asarray([1, 2, 3, 4]), np.asarray([1, np.nan]) + with assert_raises(ValueError, match="The input contains nan values"): + stats.alexandergovern(*args, nan_policy='raise') + + def test_nan_policy_omit(self): + args_nan = np.asarray([1, 2, 3, np.nan, 4]), np.asarray([1, np.nan, 19, 25]) + args_no_nan = np.asarray([1, 2, 3, 4]), np.asarray([1, 19, 25]) + res_nan = stats.alexandergovern(*args_nan, nan_policy='omit') + res_no_nan = stats.alexandergovern(*args_no_nan) + assert_equal(res_nan.pvalue, res_no_nan.pvalue) + assert_equal(res_nan.statistic, res_no_nan.statistic) + + def test_constant_input(self): + # Zero variance input, consistent with `stats.pearsonr` + x1 = np.asarray([0.667, 0.667, 0.667]) + x2 = np.asarray([0.123, 0.456, 0.789]) + with pytest.warns(RuntimeWarning, match="Precision loss occurred..."): + res = stats.alexandergovern(x1, x2) + assert_equal(res.statistic, np.nan) + assert_equal(res.pvalue, np.nan) + + +class TestFOneWay: + + def test_trivial(self): + # A trivial test of stats.f_oneway, with F=0. + F, p = stats.f_oneway([0, 2], [0, 2]) + assert_equal(F, 0.0) + assert_equal(p, 1.0) + + def test_basic(self): + # Despite being a floating point calculation, this data should + # result in F being exactly 2.0. + F, p = stats.f_oneway([0, 2], [2, 4]) + assert_equal(F, 2.0) + assert_allclose(p, 1 - np.sqrt(0.5), rtol=1e-14) + + def test_known_exact(self): + # Another trivial dataset for which the exact F and p can be + # calculated. + F, p = stats.f_oneway([2], [2], [2, 3, 4]) + # The use of assert_equal might be too optimistic, but the calculation + # in this case is trivial enough that it is likely to go through with + # no loss of precision. + assert_equal(F, 3/5) + assert_equal(p, 5/8) + + def test_large_integer_array(self): + a = np.array([655, 788], dtype=np.uint16) + b = np.array([789, 772], dtype=np.uint16) + F, p = stats.f_oneway(a, b) + # The expected value was verified by computing it with mpmath with + # 40 digits of precision. + assert_allclose(F, 0.77450216931805540, rtol=1e-14) + + def test_result_attributes(self): + a = np.array([655, 788], dtype=np.uint16) + b = np.array([789, 772], dtype=np.uint16) + res = stats.f_oneway(a, b) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes) + + def test_nist(self): + # These are the nist ANOVA files. They can be found at: + # https://www.itl.nist.gov/div898/strd/anova/anova.html + filenames = ['SiRstv.dat', 'SmLs01.dat', 'SmLs02.dat', 'SmLs03.dat', + 'AtmWtAg.dat', 'SmLs04.dat', 'SmLs05.dat', 'SmLs06.dat', + 'SmLs07.dat', 'SmLs08.dat', 'SmLs09.dat'] + + for test_case in filenames: + rtol = 1e-7 + fname = os.path.abspath(os.path.join(os.path.dirname(__file__), + 'data/nist_anova', test_case)) + with open(fname) as f: + content = f.read().split('\n') + certified = [line.split() for line in content[40:48] + if line.strip()] + dataf = np.loadtxt(fname, skiprows=60) + y, x = dataf.T + y = y.astype(int) + caty = np.unique(y) + f = float(certified[0][-1]) + + xlist = [x[y == i] for i in caty] + res = stats.f_oneway(*xlist) + + # With the hard test cases we relax the tolerance a bit. + hard_tc = ('SmLs07.dat', 'SmLs08.dat', 'SmLs09.dat') + if test_case in hard_tc: + rtol = 1e-4 + + assert_allclose(res[0], f, rtol=rtol, + err_msg=f'Failing testcase: {test_case}') + + @pytest.mark.parametrize("a, b, expected", [ + (np.array([42, 42, 42]), np.array([7, 7, 7]), (np.inf, 0)), + (np.array([42, 42, 42]), np.array([42, 42, 42]), (np.nan, np.nan)) + ]) + def test_constant_input(self, a, b, expected): + # For more details, look on https://github.com/scipy/scipy/issues/11669 + msg = "Each of the input arrays is constant;" + with pytest.warns(stats.ConstantInputWarning, match=msg): + f, p = stats.f_oneway(a, b) + assert f, p == expected + + @pytest.mark.parametrize('axis', [-2, -1, 0, 1]) + def test_2d_inputs(self, axis): + a = np.array([[1, 4, 3, 3], + [2, 5, 3, 3], + [3, 6, 3, 3], + [2, 3, 3, 3], + [1, 4, 3, 3]]) + b = np.array([[3, 1, 5, 3], + [4, 6, 5, 3], + [4, 3, 5, 3], + [1, 5, 5, 3], + [5, 5, 5, 3], + [2, 3, 5, 3], + [8, 2, 5, 3], + [2, 2, 5, 3]]) + c = np.array([[4, 3, 4, 3], + [4, 2, 4, 3], + [5, 4, 4, 3], + [5, 4, 4, 3]]) + + if axis in [-1, 1]: + a = a.T + b = b.T + c = c.T + take_axis = 0 + else: + take_axis = 1 + + warn_msg = "Each of the input arrays is constant;" + with pytest.warns(stats.ConstantInputWarning, match=warn_msg): + f, p = stats.f_oneway(a, b, c, axis=axis) + + # Verify that the result computed with the 2d arrays matches + # the result of calling f_oneway individually on each slice. + for j in [0, 1]: + fj, pj = stats.f_oneway(np.take(a, j, take_axis), + np.take(b, j, take_axis), + np.take(c, j, take_axis)) + assert_allclose(f[j], fj, rtol=1e-14) + assert_allclose(p[j], pj, rtol=1e-14) + for j in [2, 3]: + with pytest.warns(stats.ConstantInputWarning, match=warn_msg): + fj, pj = stats.f_oneway(np.take(a, j, take_axis), + np.take(b, j, take_axis), + np.take(c, j, take_axis)) + assert_equal(f[j], fj) + assert_equal(p[j], pj) + + def test_3d_inputs(self): + # Some 3-d arrays. (There is nothing special about the values.) + a = 1/np.arange(1.0, 4*5*7 + 1).reshape(4, 5, 7) + b = 2/np.arange(1.0, 4*8*7 + 1).reshape(4, 8, 7) + c = np.cos(1/np.arange(1.0, 4*4*7 + 1).reshape(4, 4, 7)) + + f, p = stats.f_oneway(a, b, c, axis=1) + + assert f.shape == (4, 7) + assert p.shape == (4, 7) + + for i in range(a.shape[0]): + for j in range(a.shape[2]): + fij, pij = stats.f_oneway(a[i, :, j], b[i, :, j], c[i, :, j]) + assert_allclose(fij, f[i, j]) + assert_allclose(pij, p[i, j]) + + def test_length0_1d_error(self): + # Require at least one value in each group. + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + result = stats.f_oneway([1, 2, 3], [], [4, 5, 6, 7]) + assert_equal(result, (np.nan, np.nan)) + + def test_length0_2d_error(self): + with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit): + ncols = 3 + a = np.ones((4, ncols)) + b = np.ones((0, ncols)) + c = np.ones((5, ncols)) + f, p = stats.f_oneway(a, b, c) + nans = np.full((ncols,), fill_value=np.nan) + assert_equal(f, nans) + assert_equal(p, nans) + + def test_all_length_one(self): + with pytest.warns(SmallSampleWarning): + result = stats.f_oneway([10], [11], [12], [13]) + assert_equal(result, (np.nan, np.nan)) + + @pytest.mark.parametrize('args', [(), ([1, 2, 3],)]) + def test_too_few_inputs(self, args): + message = "At least two samples are required..." + with assert_raises(TypeError, match=message): + stats.f_oneway(*args) + + def test_axis_error(self): + a = np.ones((3, 4)) + b = np.ones((5, 4)) + with assert_raises(AxisError): + stats.f_oneway(a, b, axis=2) + + def test_bad_shapes(self): + a = np.ones((3, 4)) + b = np.ones((5, 4)) + with assert_raises(ValueError): + stats.f_oneway(a, b, axis=1) + + +class TestKruskal: + def test_simple(self): + x = [1] + y = [2] + h, p = stats.kruskal(x, y) + assert_equal(h, 1.0) + assert_approx_equal(p, stats.distributions.chi2.sf(h, 1)) + h, p = stats.kruskal(np.array(x), np.array(y)) + assert_equal(h, 1.0) + assert_approx_equal(p, stats.distributions.chi2.sf(h, 1)) + + def test_basic(self): + x = [1, 3, 5, 7, 9] + y = [2, 4, 6, 8, 10] + h, p = stats.kruskal(x, y) + assert_approx_equal(h, 3./11, significant=10) + assert_approx_equal(p, stats.distributions.chi2.sf(3./11, 1)) + h, p = stats.kruskal(np.array(x), np.array(y)) + assert_approx_equal(h, 3./11, significant=10) + assert_approx_equal(p, stats.distributions.chi2.sf(3./11, 1)) + + def test_simple_tie(self): + x = [1] + y = [1, 2] + h_uncorr = 1.5**2 + 2*2.25**2 - 12 + corr = 0.75 + expected = h_uncorr / corr # 0.5 + h, p = stats.kruskal(x, y) + # Since the expression is simple and the exact answer is 0.5, it + # should be safe to use assert_equal(). + assert_equal(h, expected) + + def test_another_tie(self): + x = [1, 1, 1, 2] + y = [2, 2, 2, 2] + h_uncorr = (12. / 8. / 9.) * 4 * (3**2 + 6**2) - 3 * 9 + corr = 1 - float(3**3 - 3 + 5**3 - 5) / (8**3 - 8) + expected = h_uncorr / corr + h, p = stats.kruskal(x, y) + assert_approx_equal(h, expected) + + def test_three_groups(self): + # A test of stats.kruskal with three groups, with ties. + x = [1, 1, 1] + y = [2, 2, 2] + z = [2, 2] + h_uncorr = (12. / 8. / 9.) * (3*2**2 + 3*6**2 + 2*6**2) - 3 * 9 # 5.0 + corr = 1 - float(3**3 - 3 + 5**3 - 5) / (8**3 - 8) + expected = h_uncorr / corr # 7.0 + h, p = stats.kruskal(x, y, z) + assert_approx_equal(h, expected) + assert_approx_equal(p, stats.distributions.chi2.sf(h, 2)) + + def test_empty(self): + # A test of stats.kruskal with three groups, with ties. + x = [1, 1, 1] + y = [2, 2, 2] + z = [] + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + assert_equal(stats.kruskal(x, y, z), (np.nan, np.nan)) + + def test_kruskal_result_attributes(self): + x = [1, 3, 5, 7, 9] + y = [2, 4, 6, 8, 10] + res = stats.kruskal(x, y) + attributes = ('statistic', 'pvalue') + check_named_results(res, attributes) + + def test_nan_policy(self): + x = np.arange(10.) + x[9] = np.nan + assert_equal(stats.kruskal(x, x), (np.nan, np.nan)) + assert_almost_equal(stats.kruskal(x, x, nan_policy='omit'), (0.0, 1.0)) + assert_raises(ValueError, stats.kruskal, x, x, nan_policy='raise') + assert_raises(ValueError, stats.kruskal, x, x, nan_policy='foobar') + + def test_large_no_samples(self): + # Test to see if large samples are handled correctly. + n = 50000 + x = np.random.randn(n) + y = np.random.randn(n) + 50 + h, p = stats.kruskal(x, y) + expected = 0 + assert_approx_equal(p, expected) + + def test_no_args_gh20661(self): + message = r"Need at least two groups in stats.kruskal\(\)" + with pytest.raises(ValueError, match=message): + stats.kruskal() + + +@skip_xp_backends(cpu_only=True, + exceptions=['cupy', 'jax.numpy'], + reason=('Delegation for `special.stdtr` only implemented ' + 'for CuPy and JAX.')) +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +class TestCombinePvalues: + # Reference values computed using the following R code: + # options(digits=16) + # library(metap) + # x = c(0.01, 0.2, 0.3) + # sumlog(x) # fisher + # sumz(x) # stouffer + # sumlog(1-x) # pearson (negative statistic and complement of p-value) + # minimump(x) # tippett + @pytest.mark.parametrize( + "method, expected_statistic, expected_pvalue", + [("fisher", 14.83716180549625 , 0.02156175132483465), + ("stouffer", 2.131790594240385, 0.01651203260896294), + ("pearson", -1.179737662212887, 1-0.9778736999143087), + ("tippett", 0.01, 0.02970100000000002), + # mudholkar_george: library(transite); p_combine(x, method="MG") + ("mudholkar_george", 6.828712071641684, 0.01654551838539527)]) + def test_reference_values(self, xp, method, expected_statistic, expected_pvalue): + x = [.01, .2, .3] + res = stats.combine_pvalues(xp.asarray(x), method=method) + xp_assert_close(res.statistic, xp.asarray(expected_statistic)) + xp_assert_close(res.pvalue, xp.asarray(expected_pvalue)) + + @pytest.mark.parametrize( + # Reference values computed using R `metap` `sumz`: + # options(digits=16) + # library(metap) + # x = c(0.01, 0.2, 0.3) + # sumz(x, weights=c(1., 1., 1.)) + # sumz(x, weights=c(1., 4., 9.)) + "weights, expected_statistic, expected_pvalue", + [([1., 1., 1.], 2.131790594240385, 0.01651203260896294), + ([1., 4., 9.], 1.051815015753598, 0.1464422142261314)]) + def test_weighted_stouffer(self, xp, weights, expected_statistic, expected_pvalue): + x = xp.asarray([.01, .2, .3]) + res = stats.combine_pvalues(x, method='stouffer', weights=xp.asarray(weights)) + xp_assert_close(res.statistic, xp.asarray(expected_statistic)) + xp_assert_close(res.pvalue, xp.asarray(expected_pvalue)) + + methods = ["fisher", "pearson", "tippett", "stouffer", "mudholkar_george"] + + @pytest.mark.parametrize("variant", ["single", "all", "random"]) + @pytest.mark.parametrize("method", methods) + def test_monotonicity(self, variant, method, xp): + xp_test = array_namespace(xp.asarray(1)) + # Test that result increases monotonically with respect to input. + m, n = 10, 7 + rng = np.random.default_rng(278448169958891062669391462690811630763) + + # `pvaluess` is an m × n array of p values. Each row corresponds to + # a set of p values to be combined with p values increasing + # monotonically down one column (single), simultaneously down each + # column (all), or independently down each column (random). + if variant == "single": + pvaluess = xp.broadcast_to(xp.asarray(rng.random(n)), (m, n)) + pvaluess = xp_test.concat([xp.reshape(xp.linspace(0.1, 0.9, m), (-1, 1)), + pvaluess[:, 1:]], axis=1) + elif variant == "all": + pvaluess = xp.broadcast_to(xp.linspace(0.1, 0.9, m), (n, m)).T + elif variant == "random": + pvaluess = xp_test.sort(xp.asarray(rng.uniform(0, 1, size=(m, n))), axis=0) + + combined_pvalues = xp.asarray([ + stats.combine_pvalues(pvaluess[i, :], method=method)[1] + for i in range(pvaluess.shape[0]) + ]) + assert xp.all(combined_pvalues[1:] - combined_pvalues[:-1] >= 0) + + @pytest.mark.parametrize("method", methods) + def test_result(self, method, xp): + res = stats.combine_pvalues(xp.asarray([.01, .2, .3]), method=method) + xp_assert_equal(res.statistic, res[0]) + xp_assert_equal(res.pvalue, res[1]) + + @pytest.mark.parametrize("method", methods) + # axis=None is currently broken for array API; will be handled when + # axis_nan_policy decorator is updated + @pytest.mark.parametrize("axis", [0, 1]) + def test_axis(self, method, axis, xp): + rng = np.random.default_rng(234892349810482) + x = xp.asarray(rng.random(size=(2, 10))) + x = x.T if (axis == 0) else x + res = stats.combine_pvalues(x, axis=axis, method=method) + + if axis is None: + x = xp.reshape(x, (-1,)) + ref = stats.combine_pvalues(x, method=method) + xp_assert_close(res.statistic, ref.statistic) + xp_assert_close(res.pvalue, ref.pvalue) + return + + x = x.T if (axis == 0) else x + x0, x1 = x[0, :], x[1, :] + ref0 = stats.combine_pvalues(x0, method=method) + ref1 = stats.combine_pvalues(x1, method=method) + + xp_assert_close(res.statistic[0], ref0.statistic) + xp_assert_close(res.statistic[1], ref1.statistic) + xp_assert_close(res.pvalue[0], ref0.pvalue) + xp_assert_close(res.pvalue[1], ref1.pvalue) + + +class TestCdfDistanceValidation: + """ + Test that _cdf_distance() (via wasserstein_distance()) raises ValueErrors + for bad inputs. + """ + + def test_distinct_value_and_weight_lengths(self): + # When the number of weights does not match the number of values, + # a ValueError should be raised. + assert_raises(ValueError, stats.wasserstein_distance, + [1], [2], [4], [3, 1]) + assert_raises(ValueError, stats.wasserstein_distance, [1], [2], [1, 0]) + + def test_zero_weight(self): + # When a distribution is given zero weight, a ValueError should be + # raised. + assert_raises(ValueError, stats.wasserstein_distance, + [0, 1], [2], [0, 0]) + assert_raises(ValueError, stats.wasserstein_distance, + [0, 1], [2], [3, 1], [0]) + + def test_negative_weights(self): + # A ValueError should be raised if there are any negative weights. + assert_raises(ValueError, stats.wasserstein_distance, + [0, 1], [2, 2], [1, 1], [3, -1]) + + def test_empty_distribution(self): + # A ValueError should be raised when trying to measure the distance + # between something and nothing. + assert_raises(ValueError, stats.wasserstein_distance, [], [2, 2]) + assert_raises(ValueError, stats.wasserstein_distance, [1], []) + + def test_inf_weight(self): + # An inf weight is not valid. + assert_raises(ValueError, stats.wasserstein_distance, + [1, 2, 1], [1, 1], [1, np.inf, 1], [1, 1]) + + +class TestWassersteinDistanceND: + """ Tests for wasserstein_distance_nd() output values. + """ + + def test_published_values(self): + # Compare against published values and manually computed results. + # The values and computed result are posted at James D. McCaffrey's blog, + # https://jamesmccaffrey.wordpress.com/2018/03/05/earth-mover-distance + # -wasserstein-metric-example-calculation/ + u = [(1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), + (4,2), (6,1), (6,1)] + v = [(2,1), (2,1), (3,2), (3,2), (3,2), (5,1), (5,1), (5,1), (5,1), (5,1), + (5,1), (5,1), (7,1)] + + res = stats.wasserstein_distance_nd(u, v) + # In original post, the author kept two decimal places for ease of calculation. + # This test uses the more precise value of distance to get the precise results. + # For comparison, please see the table and figure in the original blog post. + flow = np.array([2., 3., 5., 1., 1., 1.]) + dist = np.array([1.00, 5**0.5, 4.00, 2**0.5, 1.00, 1.00]) + ref = np.sum(flow * dist)/np.sum(flow) + assert_allclose(res, ref) + + @pytest.mark.parametrize('n_value', (4, 15, 35)) + @pytest.mark.parametrize('ndim', (3, 4, 7)) + @pytest.mark.parametrize('max_repeats', (5, 10)) + def test_same_distribution_nD(self, ndim, n_value, max_repeats): + # Any distribution moved to itself should have a Wasserstein distance + # of zero. + rng = np.random.default_rng(363836384995579937222333) + repeats = rng.integers(1, max_repeats, size=n_value, dtype=int) + + u_values = rng.random(size=(n_value, ndim)) + v_values = np.repeat(u_values, repeats, axis=0) + v_weights = rng.random(np.sum(repeats)) + range_repeat = np.repeat(np.arange(len(repeats)), repeats) + u_weights = np.bincount(range_repeat, weights=v_weights) + index = rng.permutation(len(v_weights)) + v_values, v_weights = v_values[index], v_weights[index] + + res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights) + assert_allclose(res, 0, atol=1e-15) + + @pytest.mark.parametrize('nu', (8, 9, 38)) + @pytest.mark.parametrize('nv', (8, 12, 17)) + @pytest.mark.parametrize('ndim', (3, 5, 23)) + def test_collapse_nD(self, nu, nv, ndim): + # test collapse for n dimensional values + # Collapsing a n-D distribution to a point distribution at zero + # is equivalent to taking the average of the norm of data. + rng = np.random.default_rng(38573488467338826109) + u_values = rng.random(size=(nu, ndim)) + v_values = np.zeros((nv, ndim)) + u_weights = rng.random(size=nu) + v_weights = rng.random(size=nv) + ref = np.average(np.linalg.norm(u_values, axis=1), weights=u_weights) + res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights) + assert_allclose(res, ref) + + @pytest.mark.parametrize('nu', (8, 16, 32)) + @pytest.mark.parametrize('nv', (8, 16, 32)) + @pytest.mark.parametrize('ndim', (1, 2, 6)) + def test_zero_weight_nD(self, nu, nv, ndim): + # Values with zero weight have no impact on the Wasserstein distance. + rng = np.random.default_rng(38573488467338826109) + u_values = rng.random(size=(nu, ndim)) + v_values = rng.random(size=(nv, ndim)) + u_weights = rng.random(size=nu) + v_weights = rng.random(size=nv) + ref = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights) + + add_row, nrows = rng.integers(0, nu, size=2) + add_value = rng.random(size=(nrows, ndim)) + u_values = np.insert(u_values, add_row, add_value, axis=0) + u_weights = np.insert(u_weights, add_row, np.zeros(nrows), axis=0) + res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights) + assert_allclose(res, ref) + + def test_inf_values(self): + # Inf values can lead to an inf distance or trigger a RuntimeWarning + # (and return NaN) if the distance is undefined. + uv, vv, uw = [[1, 1], [2, 1]], [[np.inf, -np.inf]], [1, 1] + distance = stats.wasserstein_distance_nd(uv, vv, uw) + assert_equal(distance, np.inf) + with np.errstate(invalid='ignore'): + uv, vv = [[np.inf, np.inf]], [[np.inf, -np.inf]] + distance = stats.wasserstein_distance_nd(uv, vv) + assert_equal(distance, np.nan) + + @pytest.mark.parametrize('nu', (10, 15, 20)) + @pytest.mark.parametrize('nv', (10, 15, 20)) + @pytest.mark.parametrize('ndim', (1, 3, 5)) + def test_multi_dim_nD(self, nu, nv, ndim): + # Adding dimension on distributions do not affect the result + rng = np.random.default_rng(2736495738494849509) + u_values = rng.random(size=(nu, ndim)) + v_values = rng.random(size=(nv, ndim)) + u_weights = rng.random(size=nu) + v_weights = rng.random(size=nv) + ref = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights) + + add_dim = rng.integers(0, ndim) + add_value = rng.random() + + u_values = np.insert(u_values, add_dim, add_value, axis=1) + v_values = np.insert(v_values, add_dim, add_value, axis=1) + res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights) + assert_allclose(res, ref) + + @pytest.mark.parametrize('nu', (7, 13, 19)) + @pytest.mark.parametrize('nv', (7, 13, 19)) + @pytest.mark.parametrize('ndim', (2, 4, 7)) + def test_orthogonal_nD(self, nu, nv, ndim): + # orthogonal transformations do not affect the result of the + # wasserstein_distance + rng = np.random.default_rng(34746837464536) + u_values = rng.random(size=(nu, ndim)) + v_values = rng.random(size=(nv, ndim)) + u_weights = rng.random(size=nu) + v_weights = rng.random(size=nv) + ref = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights) + + dist = stats.ortho_group(ndim) + transform = dist.rvs(random_state=rng) + shift = rng.random(size=ndim) + res = stats.wasserstein_distance_nd(u_values @ transform + shift, + v_values @ transform + shift, + u_weights, v_weights) + assert_allclose(res, ref) + + def test_error_code(self): + rng = np.random.default_rng(52473644737485644836320101) + with pytest.raises(ValueError, match='Invalid input values. The inputs'): + u_values = rng.random(size=(4, 10, 15)) + v_values = rng.random(size=(6, 2, 7)) + _ = stats.wasserstein_distance_nd(u_values, v_values) + with pytest.raises(ValueError, match='Invalid input values. Dimensions'): + u_values = rng.random(size=(15,)) + v_values = rng.random(size=(3, 15)) + _ = stats.wasserstein_distance_nd(u_values, v_values) + with pytest.raises(ValueError, + match='Invalid input values. If two-dimensional'): + u_values = rng.random(size=(2, 10)) + v_values = rng.random(size=(2, 2)) + _ = stats.wasserstein_distance_nd(u_values, v_values) + + @pytest.mark.parametrize('u_size', [1, 10, 50]) + @pytest.mark.parametrize('v_size', [1, 10, 50]) + def test_optimization_vs_analytical(self, u_size, v_size): + rng = np.random.default_rng(45634745675) + # Test when u_weights = None, v_weights = None + u_values = rng.random(size=(u_size, 1)) + v_values = rng.random(size=(v_size, 1)) + u_values_flat = u_values.ravel() + v_values_flat = v_values.ravel() + # These three calculations are done using different backends + # but they must be equal + d1 = stats.wasserstein_distance(u_values_flat, v_values_flat) + d2 = stats.wasserstein_distance_nd(u_values, v_values) + d3 = stats.wasserstein_distance_nd(u_values_flat, v_values_flat) + assert_allclose(d2, d1) + assert_allclose(d3, d1) + # Test with u_weights and v_weights specified. + u_weights = rng.random(size=u_size) + v_weights = rng.random(size=v_size) + d1 = stats.wasserstein_distance(u_values_flat, v_values_flat, + u_weights, v_weights) + d2 = stats.wasserstein_distance_nd(u_values, v_values, + u_weights, v_weights) + d3 = stats.wasserstein_distance_nd(u_values_flat, v_values_flat, + u_weights, v_weights) + assert_allclose(d2, d1) + assert_allclose(d3, d1) + + +class TestWassersteinDistance: + """ Tests for wasserstein_distance() output values. + """ + + def test_simple(self): + # For basic distributions, the value of the Wasserstein distance is + # straightforward. + assert_allclose( + stats.wasserstein_distance([0, 1], [0], [1, 1], [1]), + .5) + assert_allclose(stats.wasserstein_distance( + [0, 1], [0], [3, 1], [1]), + .25) + assert_allclose(stats.wasserstein_distance( + [0, 2], [0], [1, 1], [1]), + 1) + assert_allclose(stats.wasserstein_distance( + [0, 1, 2], [1, 2, 3]), + 1) + + def test_same_distribution(self): + # Any distribution moved to itself should have a Wasserstein distance + # of zero. + assert_equal(stats.wasserstein_distance([1, 2, 3], [2, 1, 3]), 0) + assert_equal( + stats.wasserstein_distance([1, 1, 1, 4], [4, 1], + [1, 1, 1, 1], [1, 3]), + 0) + + def test_shift(self): + # If the whole distribution is shifted by x, then the Wasserstein + # distance should be the norm of x. + assert_allclose(stats.wasserstein_distance([0], [1]), 1) + assert_allclose(stats.wasserstein_distance([-5], [5]), 10) + assert_allclose( + stats.wasserstein_distance([1, 2, 3, 4, 5], [11, 12, 13, 14, 15]), + 10) + assert_allclose( + stats.wasserstein_distance([4.5, 6.7, 2.1], [4.6, 7, 9.2], + [3, 1, 1], [1, 3, 1]), + 2.5) + + def test_combine_weights(self): + # Assigning a weight w to a value is equivalent to including that value + # w times in the value array with weight of 1. + assert_allclose( + stats.wasserstein_distance( + [0, 0, 1, 1, 1, 1, 5], [0, 3, 3, 3, 3, 4, 4], + [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]), + stats.wasserstein_distance([5, 0, 1], [0, 4, 3], + [1, 2, 4], [1, 2, 4])) + + def test_collapse(self): + # Collapsing a distribution to a point distribution at zero is + # equivalent to taking the average of the absolute values of the + # values. + u = np.arange(-10, 30, 0.3) + v = np.zeros_like(u) + assert_allclose( + stats.wasserstein_distance(u, v), + np.mean(np.abs(u))) + + u_weights = np.arange(len(u)) + v_weights = u_weights[::-1] + assert_allclose( + stats.wasserstein_distance(u, v, u_weights, v_weights), + np.average(np.abs(u), weights=u_weights)) + + def test_zero_weight(self): + # Values with zero weight have no impact on the Wasserstein distance. + assert_allclose( + stats.wasserstein_distance([1, 2, 100000], [1, 1], + [1, 1, 0], [1, 1]), + stats.wasserstein_distance([1, 2], [1, 1], [1, 1], [1, 1])) + + def test_inf_values(self): + # Inf values can lead to an inf distance or trigger a RuntimeWarning + # (and return NaN) if the distance is undefined. + assert_equal( + stats.wasserstein_distance([1, 2, np.inf], [1, 1]), + np.inf) + assert_equal( + stats.wasserstein_distance([1, 2, np.inf], [-np.inf, 1]), + np.inf) + assert_equal( + stats.wasserstein_distance([1, -np.inf, np.inf], [1, 1]), + np.inf) + with suppress_warnings() as sup: + sup.record(RuntimeWarning, "invalid value*") + assert_equal( + stats.wasserstein_distance([1, 2, np.inf], [np.inf, 1]), + np.nan) + + +class TestEnergyDistance: + """ Tests for energy_distance() output values. + """ + + def test_simple(self): + # For basic distributions, the value of the energy distance is + # straightforward. + assert_almost_equal( + stats.energy_distance([0, 1], [0], [1, 1], [1]), + np.sqrt(2) * .5) + assert_almost_equal(stats.energy_distance( + [0, 1], [0], [3, 1], [1]), + np.sqrt(2) * .25) + assert_almost_equal(stats.energy_distance( + [0, 2], [0], [1, 1], [1]), + 2 * .5) + assert_almost_equal( + stats.energy_distance([0, 1, 2], [1, 2, 3]), + np.sqrt(2) * (3*(1./3**2))**.5) + + def test_same_distribution(self): + # Any distribution moved to itself should have a energy distance of + # zero. + assert_equal(stats.energy_distance([1, 2, 3], [2, 1, 3]), 0) + assert_equal( + stats.energy_distance([1, 1, 1, 4], [4, 1], [1, 1, 1, 1], [1, 3]), + 0) + + def test_shift(self): + # If a single-point distribution is shifted by x, then the energy + # distance should be sqrt(2) * sqrt(x). + assert_almost_equal(stats.energy_distance([0], [1]), np.sqrt(2)) + assert_almost_equal( + stats.energy_distance([-5], [5]), + np.sqrt(2) * 10**.5) + + def test_combine_weights(self): + # Assigning a weight w to a value is equivalent to including that value + # w times in the value array with weight of 1. + assert_almost_equal( + stats.energy_distance([0, 0, 1, 1, 1, 1, 5], [0, 3, 3, 3, 3, 4, 4], + [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]), + stats.energy_distance([5, 0, 1], [0, 4, 3], [1, 2, 4], [1, 2, 4])) + + def test_zero_weight(self): + # Values with zero weight have no impact on the energy distance. + assert_almost_equal( + stats.energy_distance([1, 2, 100000], [1, 1], [1, 1, 0], [1, 1]), + stats.energy_distance([1, 2], [1, 1], [1, 1], [1, 1])) + + def test_inf_values(self): + # Inf values can lead to an inf distance or trigger a RuntimeWarning + # (and return NaN) if the distance is undefined. + assert_equal(stats.energy_distance([1, 2, np.inf], [1, 1]), np.inf) + assert_equal( + stats.energy_distance([1, 2, np.inf], [-np.inf, 1]), + np.inf) + assert_equal( + stats.energy_distance([1, -np.inf, np.inf], [1, 1]), + np.inf) + with suppress_warnings() as sup: + sup.record(RuntimeWarning, "invalid value*") + assert_equal( + stats.energy_distance([1, 2, np.inf], [np.inf, 1]), + np.nan) + + +class TestBrunnerMunzel: + # Data from (Lumley, 1996) + X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1] + Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4] + significant = 13 + + def test_brunnermunzel_one_sided(self): + # Results are compared with R's lawstat package. + u1, p1 = stats.brunnermunzel(self.X, self.Y, alternative='less') + u2, p2 = stats.brunnermunzel(self.Y, self.X, alternative='greater') + u3, p3 = stats.brunnermunzel(self.X, self.Y, alternative='greater') + u4, p4 = stats.brunnermunzel(self.Y, self.X, alternative='less') + + assert_approx_equal(p1, p2, significant=self.significant) + assert_approx_equal(p3, p4, significant=self.significant) + assert_(p1 != p3) + assert_approx_equal(u1, 3.1374674823029505, + significant=self.significant) + assert_approx_equal(u2, -3.1374674823029505, + significant=self.significant) + assert_approx_equal(u3, 3.1374674823029505, + significant=self.significant) + assert_approx_equal(u4, -3.1374674823029505, + significant=self.significant) + assert_approx_equal(p1, 0.0028931043330757342, + significant=self.significant) + assert_approx_equal(p3, 0.99710689566692423, + significant=self.significant) + + def test_brunnermunzel_two_sided(self): + # Results are compared with R's lawstat package. + u1, p1 = stats.brunnermunzel(self.X, self.Y, alternative='two-sided') + u2, p2 = stats.brunnermunzel(self.Y, self.X, alternative='two-sided') + + assert_approx_equal(p1, p2, significant=self.significant) + assert_approx_equal(u1, 3.1374674823029505, + significant=self.significant) + assert_approx_equal(u2, -3.1374674823029505, + significant=self.significant) + assert_approx_equal(p1, 0.0057862086661515377, + significant=self.significant) + + def test_brunnermunzel_default(self): + # The default value for alternative is two-sided + u1, p1 = stats.brunnermunzel(self.X, self.Y) + u2, p2 = stats.brunnermunzel(self.Y, self.X) + + assert_approx_equal(p1, p2, significant=self.significant) + assert_approx_equal(u1, 3.1374674823029505, + significant=self.significant) + assert_approx_equal(u2, -3.1374674823029505, + significant=self.significant) + assert_approx_equal(p1, 0.0057862086661515377, + significant=self.significant) + + def test_brunnermunzel_alternative_error(self): + alternative = "error" + distribution = "t" + nan_policy = "propagate" + assert_(alternative not in ["two-sided", "greater", "less"]) + assert_raises(ValueError, + stats.brunnermunzel, + self.X, + self.Y, + alternative, + distribution, + nan_policy) + + def test_brunnermunzel_distribution_norm(self): + u1, p1 = stats.brunnermunzel(self.X, self.Y, distribution="normal") + u2, p2 = stats.brunnermunzel(self.Y, self.X, distribution="normal") + assert_approx_equal(p1, p2, significant=self.significant) + assert_approx_equal(u1, 3.1374674823029505, + significant=self.significant) + assert_approx_equal(u2, -3.1374674823029505, + significant=self.significant) + assert_approx_equal(p1, 0.0017041417600383024, + significant=self.significant) + + def test_brunnermunzel_distribution_error(self): + alternative = "two-sided" + distribution = "error" + nan_policy = "propagate" + assert_(alternative not in ["t", "normal"]) + assert_raises(ValueError, + stats.brunnermunzel, + self.X, + self.Y, + alternative, + distribution, + nan_policy) + + @pytest.mark.parametrize("kwarg_update", [{'y': []}, {'x': []}, + {'x': [], 'y': []}]) + def test_brunnermunzel_empty_imput(self, kwarg_update): + kwargs = {'x': self.X, 'y': self.Y} + kwargs.update(kwarg_update) + with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): + statistic, pvalue = stats.brunnermunzel(**kwargs) + assert_equal(statistic, np.nan) + assert_equal(pvalue, np.nan) + + def test_brunnermunzel_nan_input_propagate(self): + X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, np.nan] + Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4] + u1, p1 = stats.brunnermunzel(X, Y, nan_policy="propagate") + u2, p2 = stats.brunnermunzel(Y, X, nan_policy="propagate") + + assert_equal(u1, np.nan) + assert_equal(p1, np.nan) + assert_equal(u2, np.nan) + assert_equal(p2, np.nan) + + def test_brunnermunzel_nan_input_raise(self): + X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, np.nan] + Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4] + alternative = "two-sided" + distribution = "t" + nan_policy = "raise" + + assert_raises(ValueError, + stats.brunnermunzel, + X, + Y, + alternative, + distribution, + nan_policy) + assert_raises(ValueError, + stats.brunnermunzel, + Y, + X, + alternative, + distribution, + nan_policy) + + def test_brunnermunzel_nan_input_omit(self): + X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, np.nan] + Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4] + u1, p1 = stats.brunnermunzel(X, Y, nan_policy="omit") + u2, p2 = stats.brunnermunzel(Y, X, nan_policy="omit") + + assert_approx_equal(p1, p2, significant=self.significant) + assert_approx_equal(u1, 3.1374674823029505, + significant=self.significant) + assert_approx_equal(u2, -3.1374674823029505, + significant=self.significant) + assert_approx_equal(p1, 0.0057862086661515377, + significant=self.significant) + + def test_brunnermunzel_return_nan(self): + """ tests that a warning is emitted when p is nan + p-value with t-distributions can be nan (0/0) (see gh-15843) + """ + x = [1, 2, 3] + y = [5, 6, 7, 8, 9] + + msg = "p-value cannot be estimated|divide by zero|invalid value encountered" + with pytest.warns(RuntimeWarning, match=msg): + stats.brunnermunzel(x, y, distribution="t") + + def test_brunnermunzel_normal_dist(self): + """ tests that a p is 0 for datasets that cause p->nan + when t-distribution is used (see gh-15843) + """ + x = [1, 2, 3] + y = [5, 6, 7, 8, 9] + + with pytest.warns(RuntimeWarning, match='divide by zero'): + _, p = stats.brunnermunzel(x, y, distribution="normal") + assert_equal(p, 0) + + +class TestQuantileTest: + r""" Test the non-parametric quantile test, + including the computation of confidence intervals + """ + + def test_quantile_test_iv(self): + x = [1, 2, 3] + + message = "`x` must be a one-dimensional array of numbers." + with pytest.raises(ValueError, match=message): + stats.quantile_test([x]) + + message = "`q` must be a scalar." + with pytest.raises(ValueError, match=message): + stats.quantile_test(x, q=[1, 2]) + + message = "`p` must be a float strictly between 0 and 1." + with pytest.raises(ValueError, match=message): + stats.quantile_test(x, p=[0.5, 0.75]) + with pytest.raises(ValueError, match=message): + stats.quantile_test(x, p=2) + with pytest.raises(ValueError, match=message): + stats.quantile_test(x, p=-0.5) + + message = "`alternative` must be one of..." + with pytest.raises(ValueError, match=message): + stats.quantile_test(x, alternative='one-sided') + + message = "`confidence_level` must be a number between 0 and 1." + with pytest.raises(ValueError, match=message): + stats.quantile_test(x).confidence_interval(1) + + @pytest.mark.parametrize( + 'p, alpha, lb, ub, alternative', + [[0.3, 0.95, 1.221402758160170, 1.476980793882643, 'two-sided'], + [0.5, 0.9, 1.506817785112854, 1.803988415397857, 'two-sided'], + [0.25, 0.95, -np.inf, 1.39096812846378, 'less'], + [0.8, 0.9, 2.117000016612675, np.inf, 'greater']] + ) + def test_R_ci_quantile(self, p, alpha, lb, ub, alternative): + # Test against R library `confintr` function `ci_quantile`, e.g. + # library(confintr) + # options(digits=16) + # x <- exp(seq(0, 1, by = 0.01)) + # ci_quantile(x, q = 0.3)$interval + # ci_quantile(x, q = 0.5, probs = c(0.05, 0.95))$interval + # ci_quantile(x, q = 0.25, probs = c(0, 0.95))$interval + # ci_quantile(x, q = 0.8, probs = c(0.1, 1))$interval + x = np.exp(np.arange(0, 1.01, 0.01)) + res = stats.quantile_test(x, p=p, alternative=alternative) + assert_allclose(res.confidence_interval(alpha), [lb, ub], rtol=1e-15) + + @pytest.mark.parametrize( + 'q, p, alternative, ref', + [[1.2, 0.3, 'two-sided', 0.01515567517648], + [1.8, 0.5, 'two-sided', 0.1109183496606]] + ) + def test_R_pvalue(self, q, p, alternative, ref): + # Test against R library `snpar` function `quant.test`, e.g. + # library(snpar) + # options(digits=16) + # x < - exp(seq(0, 1, by=0.01)) + # quant.test(x, q=1.2, p=0.3, exact=TRUE, alternative='t') + x = np.exp(np.arange(0, 1.01, 0.01)) + res = stats.quantile_test(x, q=q, p=p, alternative=alternative) + assert_allclose(res.pvalue, ref, rtol=1e-12) + + @pytest.mark.parametrize('case', ['continuous', 'discrete']) + @pytest.mark.parametrize('alternative', ['less', 'greater']) + @pytest.mark.parametrize('alpha', [0.9, 0.95]) + def test_pval_ci_match(self, case, alternative, alpha): + # Verify that the following statement holds: + + # The 95% confidence interval corresponding with alternative='less' + # has -inf as its lower bound, and the upper bound `xu` is the greatest + # element from the sample `x` such that: + # `stats.quantile_test(x, q=xu, p=p, alternative='less').pvalue`` + # will be greater than 5%. + + # And the corresponding statement for the alternative='greater' case. + + seed = int((7**len(case) + len(alternative))*alpha) + rng = np.random.default_rng(seed) + if case == 'continuous': + p, q = rng.random(size=2) + rvs = rng.random(size=100) + else: + rvs = rng.integers(1, 11, size=100) + p = rng.random() + q = rng.integers(1, 11) + + res = stats.quantile_test(rvs, q=q, p=p, alternative=alternative) + ci = res.confidence_interval(confidence_level=alpha) + + # select elements inside the confidence interval based on alternative + if alternative == 'less': + i_inside = rvs <= ci.high + else: + i_inside = rvs >= ci.low + + for x in rvs[i_inside]: + res = stats.quantile_test(rvs, q=x, p=p, alternative=alternative) + assert res.pvalue > 1 - alpha + + for x in rvs[~i_inside]: + res = stats.quantile_test(rvs, q=x, p=p, alternative=alternative) + assert res.pvalue < 1 - alpha + + def test_match_conover_examples(self): + # Test against the examples in [1] (Conover Practical Nonparametric + # Statistics Third Edition) pg 139 + + # Example 1 + # Data is [189, 233, 195, 160, 212, 176, 231, 185, 199, 213, 202, 193, + # 174, 166, 248] + # Two-sided test of whether the upper quartile (p=0.75) equals 193 + # (q=193). Conover shows that 7 of the observations are less than or + # equal to 193, and "for the binomial random variable Y, P(Y<=7) = + # 0.0173", so the two-sided p-value is twice that, 0.0346. + x = [189, 233, 195, 160, 212, 176, 231, 185, 199, 213, 202, 193, + 174, 166, 248] + pvalue_expected = 0.0346 + res = stats.quantile_test(x, q=193, p=0.75, alternative='two-sided') + assert_allclose(res.pvalue, pvalue_expected, rtol=1e-5) + + # Example 2 + # Conover doesn't give explicit data, just that 8 out of 112 + # observations are 60 or less. The test is whether the median time is + # equal to 60 against the alternative that the median is greater than + # 60. The p-value is calculated as P(Y<=8), where Y is again a binomial + # distributed random variable, now with p=0.5 and n=112. Conover uses a + # normal approximation, but we can easily calculate the CDF of the + # binomial distribution. + x = [59]*8 + [61]*(112-8) + pvalue_expected = stats.binom(p=0.5, n=112).pmf(k=8) + res = stats.quantile_test(x, q=60, p=0.5, alternative='greater') + assert_allclose(res.pvalue, pvalue_expected, atol=1e-10) + + +class TestPageTrendTest: + # expected statistic and p-values generated using R at + # https://rdrr.io/cran/cultevo/, e.g. + # library(cultevo) + # data = rbind(c(72, 47, 73, 35, 47, 96, 30, 59, 41, 36, 56, 49, 81, 43, + # 70, 47, 28, 28, 62, 20, 61, 20, 80, 24, 50), + # c(68, 52, 60, 34, 44, 20, 65, 88, 21, 81, 48, 31, 31, 67, + # 69, 94, 30, 24, 40, 87, 70, 43, 50, 96, 43), + # c(81, 13, 85, 35, 79, 12, 92, 86, 21, 64, 16, 64, 68, 17, + # 16, 89, 71, 43, 43, 36, 54, 13, 66, 51, 55)) + # result = page.test(data, verbose=FALSE) + # Most test cases generated to achieve common critical p-values so that + # results could be checked (to limited precision) against tables in + # scipy.stats.page_trend_test reference [1] + + np.random.seed(0) + data_3_25 = np.random.rand(3, 25) + data_10_26 = np.random.rand(10, 26) + + ts = [ + (12805, 0.3886487053947608, False, 'asymptotic', data_3_25), + (49140, 0.02888978556179862, False, 'asymptotic', data_10_26), + (12332, 0.7722477197436702, False, 'asymptotic', + [[72, 47, 73, 35, 47, 96, 30, 59, 41, 36, 56, 49, 81, + 43, 70, 47, 28, 28, 62, 20, 61, 20, 80, 24, 50], + [68, 52, 60, 34, 44, 20, 65, 88, 21, 81, 48, 31, 31, + 67, 69, 94, 30, 24, 40, 87, 70, 43, 50, 96, 43], + [81, 13, 85, 35, 79, 12, 92, 86, 21, 64, 16, 64, 68, + 17, 16, 89, 71, 43, 43, 36, 54, 13, 66, 51, 55]]), + (266, 4.121656378600823e-05, False, 'exact', + [[1.5, 4., 8.3, 5, 19, 11], + [5, 4, 3.5, 10, 20, 21], + [8.4, 3.2, 10, 12, 14, 15]]), + (332, 0.9566400920502488, True, 'exact', + [[4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], + [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], + [3, 4, 1, 2], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], + [1, 2, 3, 4], [1, 2, 3, 4]]), + (241, 0.9622210164861476, True, 'exact', + [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], + [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], + [3, 2, 1], [2, 1, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], + [1, 2, 3], [1, 2, 3], [1, 2, 3]]), + (197, 0.9619432897162209, True, 'exact', + [[6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1], [1, 3, 4, 5, 2, 6]]), + (423, 0.9590458306880073, True, 'exact', + [[5, 4, 3, 2, 1], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1], + [5, 4, 3, 2, 1], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1], + [4, 1, 3, 2, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], + [1, 2, 3, 4, 5]]), + (217, 0.9693058575034678, True, 'exact', + [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], + [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], + [2, 1, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], + [1, 2, 3]]), + (395, 0.991530289351305, True, 'exact', + [[7, 6, 5, 4, 3, 2, 1], [7, 6, 5, 4, 3, 2, 1], + [6, 5, 7, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 7]]), + (117, 0.9997817843373017, True, 'exact', + [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], + [3, 2, 1], [3, 2, 1], [3, 2, 1], [2, 1, 3], [1, 2, 3]]), + ] + + @pytest.mark.parametrize("L, p, ranked, method, data", ts) + def test_accuracy(self, L, p, ranked, method, data): + np.random.seed(42) + res = stats.page_trend_test(data, ranked=ranked, method=method) + assert_equal(L, res.statistic) + assert_allclose(p, res.pvalue) + assert_equal(method, res.method) + + ts2 = [ + (542, 0.9481266260876332, True, 'exact', + [[10, 9, 8, 7, 6, 5, 4, 3, 2, 1], + [1, 8, 4, 7, 6, 5, 9, 3, 2, 10]]), + (1322, 0.9993113928199309, True, 'exact', + [[10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], + [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [9, 2, 8, 7, 6, 5, 4, 3, 10, 1], + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]), + (2286, 0.9908688345484833, True, 'exact', + [[8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], + [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], + [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], + [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], + [8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6, 4, 7, 2, 8], + [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], + [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], + [1, 2, 3, 4, 5, 6, 7, 8]]), + ] + + # only the first of these appears slow because intermediate data are + # cached and used on the rest + @pytest.mark.parametrize("L, p, ranked, method, data", ts) + @pytest.mark.slow() + def test_accuracy2(self, L, p, ranked, method, data): + np.random.seed(42) + res = stats.page_trend_test(data, ranked=ranked, method=method) + assert_equal(L, res.statistic) + assert_allclose(p, res.pvalue) + assert_equal(method, res.method) + + def test_options(self): + np.random.seed(42) + m, n = 10, 20 + predicted_ranks = np.arange(1, n+1) + perm = np.random.permutation(np.arange(n)) + data = np.random.rand(m, n) + ranks = stats.rankdata(data, axis=1) + res1 = stats.page_trend_test(ranks) + res2 = stats.page_trend_test(ranks, ranked=True) + res3 = stats.page_trend_test(data, ranked=False) + res4 = stats.page_trend_test(ranks, predicted_ranks=predicted_ranks) + res5 = stats.page_trend_test(ranks[:, perm], + predicted_ranks=predicted_ranks[perm]) + assert_equal(res1.statistic, res2.statistic) + assert_equal(res1.statistic, res3.statistic) + assert_equal(res1.statistic, res4.statistic) + assert_equal(res1.statistic, res5.statistic) + + def test_Ames_assay(self): + # test from _page_trend_test.py [2] page 151; data on page 144 + np.random.seed(42) + + data = [[101, 117, 111], [91, 90, 107], [103, 133, 121], + [136, 140, 144], [190, 161, 201], [146, 120, 116]] + data = np.array(data).T + predicted_ranks = np.arange(1, 7) + + res = stats.page_trend_test(data, ranked=False, + predicted_ranks=predicted_ranks, + method="asymptotic") + assert_equal(res.statistic, 257) + assert_almost_equal(res.pvalue, 0.0035, decimal=4) + + res = stats.page_trend_test(data, ranked=False, + predicted_ranks=predicted_ranks, + method="exact") + assert_equal(res.statistic, 257) + assert_almost_equal(res.pvalue, 0.0023, decimal=4) + + def test_input_validation(self): + # test data not a 2d array + with assert_raises(ValueError, match="`data` must be a 2d array."): + stats.page_trend_test(None) + with assert_raises(ValueError, match="`data` must be a 2d array."): + stats.page_trend_test([]) + with assert_raises(ValueError, match="`data` must be a 2d array."): + stats.page_trend_test([1, 2]) + with assert_raises(ValueError, match="`data` must be a 2d array."): + stats.page_trend_test([[[1]]]) + + # test invalid dimensions + with assert_raises(ValueError, match="Page's L is only appropriate"): + stats.page_trend_test(np.random.rand(1, 3)) + with assert_raises(ValueError, match="Page's L is only appropriate"): + stats.page_trend_test(np.random.rand(2, 2)) + + # predicted ranks must include each integer [1, 2, 3] exactly once + message = "`predicted_ranks` must include each integer" + with assert_raises(ValueError, match=message): + stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]], + predicted_ranks=[0, 1, 2]) + with assert_raises(ValueError, match=message): + stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]], + predicted_ranks=[1.1, 2, 3]) + with assert_raises(ValueError, match=message): + stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]], + predicted_ranks=[1, 2, 3, 3]) + with assert_raises(ValueError, match=message): + stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]], + predicted_ranks="invalid") + + # test improperly ranked data + with assert_raises(ValueError, match="`data` is not properly ranked"): + stats.page_trend_test([[0, 2, 3], [1, 2, 3]], True) + with assert_raises(ValueError, match="`data` is not properly ranked"): + stats.page_trend_test([[1, 2, 3], [1, 2, 4]], True) + + # various + with assert_raises(ValueError, match="`data` contains NaNs"): + stats.page_trend_test([[1, 2, 3], [1, 2, np.nan]], + ranked=False) + with assert_raises(ValueError, match="`method` must be in"): + stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]], + method="ekki") + with assert_raises(TypeError, match="`ranked` must be boolean."): + stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]], + ranked="ekki") + + +rng = np.random.default_rng(902340982) +x = rng.random(10) +y = rng.random(10) + + +@pytest.mark.parametrize("fun, args", + [(stats.wilcoxon, (x,)), + (stats.ks_1samp, (x, stats.norm.cdf)), # type: ignore[attr-defined] # noqa: E501 + (stats.ks_2samp, (x, y)), + (stats.kstest, (x, y)), + ]) +def test_rename_mode_method(fun, args): + + res = fun(*args, method='exact') + res2 = fun(*args, mode='exact') + assert_equal(res, res2) + + err = rf"{fun.__name__}() got multiple values for argument" + with pytest.raises(TypeError, match=re.escape(err)): + fun(*args, method='exact', mode='exact') + + +class TestExpectile: + def test_same_as_mean(self): + rng = np.random.default_rng(42) + x = rng.random(size=20) + assert_allclose(stats.expectile(x, alpha=0.5), np.mean(x)) + + def test_minimum(self): + rng = np.random.default_rng(42) + x = rng.random(size=20) + assert_allclose(stats.expectile(x, alpha=0), np.amin(x)) + + def test_maximum(self): + rng = np.random.default_rng(42) + x = rng.random(size=20) + assert_allclose(stats.expectile(x, alpha=1), np.amax(x)) + + def test_weights(self): + # expectile should minimize `fun` defined below; see + # F. Sobotka and T. Kneib, "Geoadditive expectile regression", + # Computational Statistics and Data Analysis 56 (2012) 755-767 + # :doi:`10.1016/j.csda.2010.11.015` + rng = np.random.default_rng(1856392524598679138) + + def fun(u, a, alpha, weights): + w = np.full_like(a, fill_value=alpha) + w[a <= u] = 1 - alpha + return np.sum(w * weights * (a - u)**2) + + def expectile2(a, alpha, weights): + bracket = np.min(a), np.max(a) + return optimize.minimize_scalar(fun, bracket=bracket, + args=(a, alpha, weights)).x + + n = 10 + a = rng.random(n) + alpha = rng.random() + weights = rng.random(n) + + res = stats.expectile(a, alpha, weights=weights) + ref = expectile2(a, alpha, weights) + assert_allclose(res, ref) + + @pytest.mark.parametrize( + "alpha", [0.2, 0.5 - 1e-12, 0.5, 0.5 + 1e-12, 0.8] + ) + @pytest.mark.parametrize("n", [20, 2000]) + def test_expectile_properties(self, alpha, n): + """ + See Section 6 of + I. Steinwart, C. Pasin, R.C. Williamson & S. Zhang (2014). + "Elicitation and Identification of Properties". COLT. + http://proceedings.mlr.press/v35/steinwart14.html + + and + + Propositions 5, 6, 7 of + F. Bellini, B. Klar, and A. Müller and E. Rosazza Gianin (2013). + "Generalized Quantiles as Risk Measures" + http://doi.org/10.2139/ssrn.2225751 + """ + rng = np.random.default_rng(42) + x = rng.normal(size=n) + + # 0. definite / constancy + # Let T(X) denote the expectile of rv X ~ F. + # T(c) = c for constant c + for c in [-5, 0, 0.5]: + assert_allclose( + stats.expectile(np.full(shape=n, fill_value=c), alpha=alpha), + c + ) + + # 1. translation equivariance + # T(X + c) = T(X) + c + c = rng.exponential() + assert_allclose( + stats.expectile(x + c, alpha=alpha), + stats.expectile(x, alpha=alpha) + c, + ) + assert_allclose( + stats.expectile(x - c, alpha=alpha), + stats.expectile(x, alpha=alpha) - c, + ) + + # 2. positively homogeneity + # T(cX) = c * T(X) for c > 0 + assert_allclose( + stats.expectile(c * x, alpha=alpha), + c * stats.expectile(x, alpha=alpha), + ) + + # 3. subadditivity + # Note that subadditivity holds for alpha >= 0.5. + # T(X + Y) <= T(X) + T(Y) + # For alpha = 0.5, i.e. the mean, strict equality holds. + # For alpha < 0.5, one can use property 6. to show + # T(X + Y) >= T(X) + T(Y) + y = rng.logistic(size=n, loc=10) # different distribution than x + if alpha == 0.5: + def assert_op(a, b): + assert_allclose(a, b) + + elif alpha > 0.5: + def assert_op(a, b): + assert a < b + + else: + def assert_op(a, b): + assert a > b + + assert_op( + stats.expectile(np.r_[x + y], alpha=alpha), + stats.expectile(x, alpha=alpha) + + stats.expectile(y, alpha=alpha) + ) + + # 4. monotonicity + # This holds for first order stochastic dominance X: + # X >= Y whenever P(X <= x) < P(Y <= x) + # T(X) <= T(Y) whenever X <= Y + y = rng.normal(size=n, loc=5) + assert ( + stats.expectile(x, alpha=alpha) <= stats.expectile(y, alpha=alpha) + ) + + # 5. convexity for alpha > 0.5, concavity for alpha < 0.5 + # convexity is + # T((1 - c) X + c Y) <= (1 - c) T(X) + c T(Y) for 0 <= c <= 1 + y = rng.logistic(size=n, loc=10) + for c in [0.1, 0.5, 0.8]: + assert_op( + stats.expectile((1-c)*x + c*y, alpha=alpha), + (1-c) * stats.expectile(x, alpha=alpha) + + c * stats.expectile(y, alpha=alpha) + ) + + # 6. negative argument + # T_{alpha}(-X) = -T_{1-alpha}(X) + assert_allclose( + stats.expectile(-x, alpha=alpha), + -stats.expectile(x, alpha=1-alpha), + ) + + @pytest.mark.parametrize("n", [20, 2000]) + def test_monotonicity_in_alpha(self, n): + rng = np.random.default_rng(42) + x = rng.pareto(a=2, size=n) + e_list = [] + alpha_seq = np.logspace(-15, np.log10(0.5), 100) + # sorted list of unique alpha values in interval (0, 1) + for alpha in np.r_[0, alpha_seq, 1 - alpha_seq[:-1:-1], 1]: + e_list.append(stats.expectile(x, alpha=alpha)) + assert np.all(np.diff(e_list) > 0) + + +class TestLMoment: + # data from https://github.com/scipy/scipy/issues/19460 + data = [0.87, 0.87, 1.29, 1.5, 1.7, 0.66, 1.5, 0.5, 1., 1.25, 2.3, + 1.03, 2.85, 0.68, 1.74, 1.94, 0.63, 2.04, 1.2, 0.64, 2.05, 0.97, + 2.81, 1.02, 2.76, 0.86, 1.36, 1.29, 1.68, 0.72, 1.67, 1.15, 3.26, + 0.93, 0.83, 0.91, 0.92, 2.32, 1.12, 3.21, 1.23, 1.22, 1.29, 2.08, + 0.64, 2.83, 2.68, 1.77, 0.69, 1.69, 0.7, 1.83, 2.25, 1.23, 1.17, + 0.94, 1.22, 0.76, 0.69, 0.48, 1.04, 2.49, 1.38, 1.57, 1.79, 1.59, + 1.3, 1.54, 1.07, 1.03, 0.76, 2.35, 2.05, 2.02, 2.36, 1.59, 0.97, + 1.63, 1.66, 0.94, 1.45, 1.26, 1.25, 0.68, 2.96, 0.8, 1.16, 0.82, + 0.64, 0.87, 1.33, 1.28, 1.26, 1.19, 1.24, 1.12, 1.45, 1.03, 1.37, + 1.4, 1.35, 1.28, 1.04, 1.31, 0.87, 0.96, 2.55, 1.72, 1.05, 1.15, + 1.73, 1.03, 1.53, 2.41, 1.36, 2.08, 0.92, 0.73, 1.56, 1.94, 0.78] + + not_integers = [1.5, [1, 2, 3.5], np.nan, np.inf, 'a duck'] + + def test_dtype_iv(self): + message = '`sample` must be an array of real numbers.' + with pytest.raises(ValueError, match=message): + stats.lmoment(np.array(self.data, dtype=np.complex128)) + + @skip_xp_invalid_arg + def test_dtype_iv_non_numeric(self): + message = '`sample` must be an array of real numbers.' + with pytest.raises(ValueError, match=message): + stats.lmoment(np.array(self.data, dtype=object)) + + @pytest.mark.parametrize('order', not_integers + [0, -1, [], [[1, 2, 3]]]) + def test_order_iv(self, order): + message = '`order` must be a scalar or a non-empty...' + with pytest.raises(ValueError, match=message): + stats.lmoment(self.data, order=order) + + @pytest.mark.parametrize('axis', not_integers) + def test_axis_iv(self, axis): + message = '`axis` must be an integer, a tuple' + with pytest.raises(ValueError, match=message): + stats.lmoment(self.data, axis=axis) + + @pytest.mark.parametrize('sorted', not_integers) + def test_sorted_iv(self, sorted): + message = '`sorted` must be True or False.' + with pytest.raises(ValueError, match=message): + stats.lmoment(self.data, sorted=sorted) + + @pytest.mark.parametrize('standardize', not_integers) + def test_standardize_iv(self, standardize): + message = '`standardize` must be True or False.' + with pytest.raises(ValueError, match=message): + stats.lmoment(self.data, standardize=standardize) + + @pytest.mark.parametrize('order', [1, 4, [1, 2, 3, 4]]) + @pytest.mark.parametrize('standardize', [False, True]) + @pytest.mark.parametrize('sorted', [False, True]) + def test_lmoment(self, order, standardize, sorted): + # Reference values from R package `lmom` + # options(digits=16) + # library(lmom) + # data= c(0.87, 0.87,..., 1.94, 0.78) + # samlmu(data) + ref = np.asarray([1.4087603305785130, 0.3415936639118458, + 0.2189964482831403, 0.1328186463415905]) + + if not standardize: + ref[2:] *= ref[1] + + data = np.sort(self.data) if sorted else self.data + + res = stats.lmoment(data, order, standardize=standardize, sorted=sorted) + assert_allclose(res, ref[np.asarray(order)-1]) + + def test_dtype(self): + dtype = np.float32 + sample = np.asarray(self.data) + res = stats.lmoment(sample.astype(dtype)) + ref = stats.lmoment(sample) + assert res.dtype.type == dtype + assert_allclose(res, ref, rtol=1e-4) + + dtype = np.int64 + sample = np.asarray([1, 2, 3, 4, 5]) + res = stats.lmoment(sample.astype(dtype)) + ref = stats.lmoment(sample.astype(np.float64)) + assert res.dtype.type == np.float64 + assert_allclose(res, ref, rtol=1e-15) + + +@array_api_compatible +class TestXP_Mean: + @pytest.mark.parametrize('axis', [None, 1, -1, (-2, 2)]) + @pytest.mark.parametrize('weights', [None, True]) + @pytest.mark.parametrize('keepdims', [False, True]) + def test_xp_mean_basic(self, xp, axis, weights, keepdims): + rng = np.random.default_rng(90359458245906) + x = rng.random((3, 4, 5)) + x_xp = xp.asarray(x) + w = w_xp = None + + if weights: + w = rng.random((1, 5)) + w_xp = xp.asarray(w) + x, w = np.broadcast_arrays(x, w) + + res = _xp_mean(x_xp, weights=w_xp, axis=axis, keepdims=keepdims) + ref = np.average(x, weights=w, axis=axis, keepdims=keepdims) + + xp_assert_close(res, xp.asarray(ref)) + + def test_non_broadcastable(self, xp): + # non-broadcastable x and weights + x, w = xp.arange(10.), xp.zeros(5) + message = "Array shapes are incompatible for broadcasting." + with pytest.raises(ValueError, match=message): + _xp_mean(x, weights=w) + + def test_special_cases(self, xp): + # weights sum to zero + weights = xp.asarray([-1., 0., 1.]) + + res = _xp_mean(xp.asarray([1., 1., 1.]), weights=weights) + xp_assert_close(res, xp.asarray(xp.nan)) + + res = _xp_mean(xp.asarray([2., 1., 1.]), weights=weights) + xp_assert_close(res, xp.asarray(-np.inf)) + + res = _xp_mean(xp.asarray([1., 1., 2.]), weights=weights) + xp_assert_close(res, xp.asarray(np.inf)) + + def test_nan_policy(self, xp): + x = xp.arange(10.) + mask = (x == 3) + x = xp.where(mask, xp.asarray(xp.nan), x) + + # nan_policy='raise' raises an error + message = 'The input contains nan values' + with pytest.raises(ValueError, match=message): + _xp_mean(x, nan_policy='raise') + + # `nan_policy='propagate'` is the default, and the result is NaN + res1 = _xp_mean(x) + res2 = _xp_mean(x, nan_policy='propagate') + ref = xp.asarray(xp.nan) + xp_assert_equal(res1, ref) + xp_assert_equal(res2, ref) + + # `nan_policy='omit'` omits NaNs in `x` + res = _xp_mean(x, nan_policy='omit') + ref = xp.mean(x[~mask]) + xp_assert_close(res, ref) + + # `nan_policy='omit'` omits NaNs in `weights`, too + weights = xp.ones(10) + weights = xp.where(mask, xp.asarray(xp.nan), weights) + res = _xp_mean(xp.arange(10.), weights=weights, nan_policy='omit') + ref = xp.mean(x[~mask]) + xp_assert_close(res, ref) + + # Check for warning if omitting NaNs causes empty slice + message = 'After omitting NaNs...' + with pytest.warns(RuntimeWarning, match=message): + res = _xp_mean(x * np.nan, nan_policy='omit') + ref = xp.asarray(xp.nan) + xp_assert_equal(res, ref) + + def test_empty(self, xp): + message = 'One or more sample arguments is too small...' + with pytest.warns(SmallSampleWarning, match=message): + res = _xp_mean(xp.asarray([])) + ref = xp.asarray(xp.nan) + xp_assert_equal(res, ref) + + message = "All axis-slices of one or more sample arguments..." + with pytest.warns(SmallSampleWarning, match=message): + res = _xp_mean(xp.asarray([[]]), axis=1) + ref = xp.asarray([xp.nan]) + xp_assert_equal(res, ref) + + res = _xp_mean(xp.asarray([[]]), axis=0) + ref = xp.asarray([]) + xp_assert_equal(res, ref) + + def test_dtype(self, xp): + max = xp.finfo(xp.float32).max + x_np = np.asarray([max, max], dtype=np.float32) + x_xp = xp.asarray(x_np) + + # Overflow occurs for float32 input + with np.errstate(over='ignore'): + res = _xp_mean(x_xp) + ref = np.mean(x_np) + np.testing.assert_equal(ref, np.inf) + xp_assert_close(res, xp.asarray(ref)) + + # correct result is returned if `float64` is used + res = _xp_mean(x_xp, dtype=xp.float64) + ref = xp.asarray(np.mean(np.asarray(x_np, dtype=np.float64))) + xp_assert_close(res, ref) + + def test_integer(self, xp): + # integer inputs are converted to the appropriate float + x = xp.arange(10) + y = xp.arange(10.) + xp_assert_equal(_xp_mean(x), _xp_mean(y)) + xp_assert_equal(_xp_mean(y, weights=x), _xp_mean(y, weights=y)) + + def test_complex_gh22404(self, xp): + rng = np.random.default_rng(90359458245906) + x, y, wx, wy = rng.random((4, 20)) + res = _xp_mean(xp.asarray(x + y*1j), weights=xp.asarray(wx + wy*1j)) + ref = np.average(x + y*1j, weights=wx + wy*1j) + xp_assert_close(res, xp.asarray(ref)) + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +@skip_xp_backends('jax.numpy', reason='JAX arrays do not support item assignment') +class TestXP_Var: + @pytest.mark.parametrize('axis', [None, 1, -1, (-2, 2)]) + @pytest.mark.parametrize('keepdims', [False, True]) + @pytest.mark.parametrize('correction', [0, 1]) + @pytest.mark.parametrize('nan_policy', ['propagate', 'omit']) + def test_xp_var_basic(self, xp, axis, keepdims, correction, nan_policy): + rng = np.random.default_rng(90359458245906) + x = rng.random((3, 4, 5)) + var_ref = np.var + + if nan_policy == 'omit': + nan_mask = rng.random(size=x.shape) > 0.5 + x[nan_mask] = np.nan + var_ref = np.nanvar + + x_xp = xp.asarray(x) + + res = _xp_var(x_xp, axis=axis, keepdims=keepdims, correction=correction, + nan_policy=nan_policy) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice") + ref = var_ref(x, axis=axis, keepdims=keepdims, ddof=correction) + + xp_assert_close(res, xp.asarray(ref)) + + def test_special_cases(self, xp): + # correction too big + res = _xp_var(xp.asarray([1., 2.]), correction=3) + xp_assert_close(res, xp.asarray(xp.nan)) + + def test_nan_policy(self, xp): + x = xp.arange(10.) + mask = (x == 3) + x = xp.where(mask, xp.asarray(xp.nan), x) + + # nan_policy='raise' raises an error + message = 'The input contains nan values' + with pytest.raises(ValueError, match=message): + _xp_var(x, nan_policy='raise') + + # `nan_policy='propagate'` is the default, and the result is NaN + res1 = _xp_var(x) + res2 = _xp_var(x, nan_policy='propagate') + ref = xp.asarray(xp.nan) + xp_assert_equal(res1, ref) + xp_assert_equal(res2, ref) + + # `nan_policy='omit'` omits NaNs in `x` + res = _xp_var(x, nan_policy='omit') + xp_test = array_namespace(x) # torch has different default correction + ref = xp_test.var(x[~mask]) + xp_assert_close(res, ref) + + # Check for warning if omitting NaNs causes empty slice + message = 'After omitting NaNs...' + with pytest.warns(RuntimeWarning, match=message): + res = _xp_var(x * np.nan, nan_policy='omit') + ref = xp.asarray(xp.nan) + xp_assert_equal(res, ref) + + def test_empty(self, xp): + message = 'One or more sample arguments is too small...' + with pytest.warns(SmallSampleWarning, match=message): + res = _xp_var(xp.asarray([])) + ref = xp.asarray(xp.nan) + xp_assert_equal(res, ref) + + message = "All axis-slices of one or more sample arguments..." + with pytest.warns(SmallSampleWarning, match=message): + res = _xp_var(xp.asarray([[]]), axis=1) + ref = xp.asarray([xp.nan]) + xp_assert_equal(res, ref) + + res = _xp_var(xp.asarray([[]]), axis=0) + ref = xp.asarray([]) + xp_assert_equal(res, ref) + + def test_dtype(self, xp): + max = xp.finfo(xp.float32).max + x_np = np.asarray([max, max/2], dtype=np.float32) + x_xp = xp.asarray(x_np) + + # Overflow occurs for float32 input + with np.errstate(over='ignore'): + res = _xp_var(x_xp) + ref = np.var(x_np) + np.testing.assert_equal(ref, np.inf) + xp_assert_close(res, xp.asarray(ref)) + + # correct result is returned if `float64` is used + res = _xp_var(x_xp, dtype=xp.float64) + ref = xp.asarray(np.var(np.asarray(x_np, dtype=np.float64))) + xp_assert_close(res, ref) + + def test_integer(self, xp): + # integer inputs are converted to the appropriate float + x = xp.arange(10) + y = xp.arange(10.) + xp_assert_equal(_xp_var(x), _xp_var(y)) + + @pytest.mark.skip_xp_backends('array_api_strict', reason='needs array-api#850') + def test_complex_gh22404(self, xp): + rng = np.random.default_rng(90359458245906) + x, y = rng.random((2, 20)) + res = _xp_var(xp.asarray(x + y*1j)) + ref = np.var(x + y*1j) + xp_assert_close(res, xp.asarray(ref), check_dtype=False) + + +@array_api_compatible +def test_chk_asarray(xp): + rng = np.random.default_rng(2348923425434) + x0 = rng.random(size=(2, 3, 4)) + x = xp.asarray(x0) + + axis = 1 + x_out, axis_out = _chk_asarray(x, axis=axis, xp=xp) + xp_assert_equal(x_out, xp.asarray(x0)) + assert_equal(axis_out, axis) + + axis = None + x_out, axis_out = _chk_asarray(x, axis=axis, xp=xp) + xp_assert_equal(x_out, xp.asarray(x0.ravel())) + assert_equal(axis_out, 0) + + axis = 2 + x_out, axis_out = _chk_asarray(x[0, 0, 0], axis=axis, xp=xp) + xp_assert_equal(x_out, xp.asarray(np.atleast_1d(x0[0, 0, 0]))) + assert_equal(axis_out, axis) + + +@pytest.mark.skip_xp_backends('numpy', + reason='These parameters *are* compatible with NumPy') +@pytest.mark.usefixtures("skip_xp_backends") +@array_api_compatible +def test_axis_nan_policy_keepdims_nanpolicy(xp): + # this test does not need to be repeated for every function + # using the _axis_nan_policy decorator. The test is here + # rather than in `test_axis_nanpolicy.py` because there is + # no reason to run those tests on an array API CI job. + x = xp.asarray([1, 2, 3, 4]) + message = "Use of `nan_policy` and `keepdims`..." + with pytest.raises(NotImplementedError, match=message): + stats.skew(x, nan_policy='omit') + with pytest.raises(NotImplementedError, match=message): + stats.skew(x, keepdims=True) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_survival.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_survival.py new file mode 100644 index 0000000000000000000000000000000000000000..60a5fef27ae281c028ade8af523bdf1f62f8f664 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_survival.py @@ -0,0 +1,466 @@ +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose +from scipy import stats +from scipy.stats import _survival + + +def _kaplan_meier_reference(times, censored): + # This is a very straightforward implementation of the Kaplan-Meier + # estimator that does almost everything differently from the implementation + # in stats.ecdf. + + # Begin by sorting the raw data. Note that the order of death and loss + # at a given time matters: death happens first. See [2] page 461: + # "These conventions may be paraphrased by saying that deaths recorded as + # of an age t are treated as if they occurred slightly before t, and losses + # recorded as of an age t are treated as occurring slightly after t." + # We implement this by sorting the data first by time, then by `censored`, + # (which is 0 when there is a death and 1 when there is only a loss). + dtype = [('time', float), ('censored', int)] + data = np.array([(t, d) for t, d in zip(times, censored)], dtype=dtype) + data = np.sort(data, order=('time', 'censored')) + times = data['time'] + died = np.logical_not(data['censored']) + + m = times.size + n = np.arange(m, 0, -1) # number at risk + sf = np.cumprod((n - died) / n) + + # Find the indices of the *last* occurrence of unique times. The + # corresponding entries of `times` and `sf` are what we want. + _, indices = np.unique(times[::-1], return_index=True) + ref_times = times[-indices - 1] + ref_sf = sf[-indices - 1] + return ref_times, ref_sf + + +class TestSurvival: + + @staticmethod + def get_random_sample(rng, n_unique): + # generate random sample + unique_times = rng.random(n_unique) + # convert to `np.int32` to resolve `np.repeat` failure in 32-bit CI + repeats = rng.integers(1, 4, n_unique).astype(np.int32) + times = rng.permuted(np.repeat(unique_times, repeats)) + censored = rng.random(size=times.size) > rng.random() + sample = stats.CensoredData.right_censored(times, censored) + return sample, times, censored + + def test_input_validation(self): + message = '`sample` must be a one-dimensional sequence.' + with pytest.raises(ValueError, match=message): + stats.ecdf([[1]]) + with pytest.raises(ValueError, match=message): + stats.ecdf(1) + + message = '`sample` must not contain nan' + with pytest.raises(ValueError, match=message): + stats.ecdf([np.nan]) + + message = 'Currently, only uncensored and right-censored data...' + with pytest.raises(NotImplementedError, match=message): + stats.ecdf(stats.CensoredData.left_censored([1], censored=[True])) + + message = 'method` must be one of...' + res = stats.ecdf([1, 2, 3]) + with pytest.raises(ValueError, match=message): + res.cdf.confidence_interval(method='ekki-ekki') + with pytest.raises(ValueError, match=message): + res.sf.confidence_interval(method='shrubbery') + + message = 'confidence_level` must be a scalar between 0 and 1' + with pytest.raises(ValueError, match=message): + res.cdf.confidence_interval(-1) + with pytest.raises(ValueError, match=message): + res.sf.confidence_interval([0.5, 0.6]) + + message = 'The confidence interval is undefined at some observations.' + with pytest.warns(RuntimeWarning, match=message): + ci = res.cdf.confidence_interval() + + message = 'Confidence interval bounds do not implement...' + with pytest.raises(NotImplementedError, match=message): + ci.low.confidence_interval() + with pytest.raises(NotImplementedError, match=message): + ci.high.confidence_interval() + + def test_edge_cases(self): + res = stats.ecdf([]) + assert_equal(res.cdf.quantiles, []) + assert_equal(res.cdf.probabilities, []) + + res = stats.ecdf([1]) + assert_equal(res.cdf.quantiles, [1]) + assert_equal(res.cdf.probabilities, [1]) + + def test_unique(self): + # Example with unique observations; `stats.ecdf` ref. [1] page 80 + sample = [6.23, 5.58, 7.06, 6.42, 5.20] + res = stats.ecdf(sample) + ref_x = np.sort(np.unique(sample)) + ref_cdf = np.arange(1, 6) / 5 + ref_sf = 1 - ref_cdf + assert_equal(res.cdf.quantiles, ref_x) + assert_equal(res.cdf.probabilities, ref_cdf) + assert_equal(res.sf.quantiles, ref_x) + assert_equal(res.sf.probabilities, ref_sf) + + def test_nonunique(self): + # Example with non-unique observations; `stats.ecdf` ref. [1] page 82 + sample = [0, 2, 1, 2, 3, 4] + res = stats.ecdf(sample) + ref_x = np.sort(np.unique(sample)) + ref_cdf = np.array([1/6, 2/6, 4/6, 5/6, 1]) + ref_sf = 1 - ref_cdf + assert_equal(res.cdf.quantiles, ref_x) + assert_equal(res.cdf.probabilities, ref_cdf) + assert_equal(res.sf.quantiles, ref_x) + assert_equal(res.sf.probabilities, ref_sf) + + def test_evaluate_methods(self): + # Test CDF and SF `evaluate` methods + rng = np.random.default_rng(1162729143302572461) + sample, _, _ = self.get_random_sample(rng, 15) + res = stats.ecdf(sample) + x = res.cdf.quantiles + xr = x + np.diff(x, append=x[-1]+1)/2 # right shifted points + + assert_equal(res.cdf.evaluate(x), res.cdf.probabilities) + assert_equal(res.cdf.evaluate(xr), res.cdf.probabilities) + assert_equal(res.cdf.evaluate(x[0]-1), 0) # CDF starts at 0 + assert_equal(res.cdf.evaluate([-np.inf, np.inf]), [0, 1]) + + assert_equal(res.sf.evaluate(x), res.sf.probabilities) + assert_equal(res.sf.evaluate(xr), res.sf.probabilities) + assert_equal(res.sf.evaluate(x[0]-1), 1) # SF starts at 1 + assert_equal(res.sf.evaluate([-np.inf, np.inf]), [1, 0]) + + # ref. [1] page 91 + t1 = [37, 43, 47, 56, 60, 62, 71, 77, 80, 81] # times + d1 = [0, 0, 1, 1, 0, 0, 0, 1, 1, 1] # 1 means deaths (not censored) + r1 = [1, 1, 0.875, 0.75, 0.75, 0.75, 0.75, 0.5, 0.25, 0] # reference SF + + # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html + t2 = [8, 12, 26, 14, 21, 27, 8, 32, 20, 40] + d2 = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0] + r2 = [0.9, 0.788, 0.675, 0.675, 0.54, 0.405, 0.27, 0.27, 0.27] + t3 = [33, 28, 41, 48, 48, 25, 37, 48, 25, 43] + d3 = [1, 1, 1, 0, 0, 0, 0, 0, 0, 0] + r3 = [1, 0.875, 0.75, 0.75, 0.6, 0.6, 0.6] + + # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/bs704_survival4.html + t4 = [24, 3, 11, 19, 24, 13, 14, 2, 18, 17, + 24, 21, 12, 1, 10, 23, 6, 5, 9, 17] + d4 = [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1] + r4 = [0.95, 0.95, 0.897, 0.844, 0.844, 0.844, 0.844, 0.844, 0.844, + 0.844, 0.76, 0.676, 0.676, 0.676, 0.676, 0.507, 0.507] + + # https://www.real-statistics.com/survival-analysis/kaplan-meier-procedure/confidence-interval-for-the-survival-function/ + t5 = [3, 5, 8, 10, 5, 5, 8, 12, 15, 14, 2, 11, 10, 9, 12, 5, 8, 11] + d5 = [1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1] + r5 = [0.944, 0.889, 0.722, 0.542, 0.542, 0.542, 0.361, 0.181, 0.181, 0.181] + + @pytest.mark.parametrize("case", [(t1, d1, r1), (t2, d2, r2), (t3, d3, r3), + (t4, d4, r4), (t5, d5, r5)]) + def test_right_censored_against_examples(self, case): + # test `ecdf` against other implementations on example problems + times, died, ref = case + sample = stats.CensoredData.right_censored(times, np.logical_not(died)) + res = stats.ecdf(sample) + assert_allclose(res.sf.probabilities, ref, atol=1e-3) + assert_equal(res.sf.quantiles, np.sort(np.unique(times))) + + # test reference implementation against other implementations + res = _kaplan_meier_reference(times, np.logical_not(died)) + assert_equal(res[0], np.sort(np.unique(times))) + assert_allclose(res[1], ref, atol=1e-3) + + @pytest.mark.parametrize('seed', [182746786639392128, 737379171436494115, + 576033618403180168, 308115465002673650]) + def test_right_censored_against_reference_implementation(self, seed): + # test `ecdf` against reference implementation on random problems + rng = np.random.default_rng(seed) + n_unique = rng.integers(10, 100) + sample, times, censored = self.get_random_sample(rng, n_unique) + res = stats.ecdf(sample) + ref = _kaplan_meier_reference(times, censored) + assert_allclose(res.sf.quantiles, ref[0]) + assert_allclose(res.sf.probabilities, ref[1]) + + # If all observations are uncensored, the KM estimate should match + # the usual estimate for uncensored data + sample = stats.CensoredData(uncensored=times) + res = _survival._ecdf_right_censored(sample) # force Kaplan-Meier + ref = stats.ecdf(times) + assert_equal(res[0], ref.sf.quantiles) + assert_allclose(res[1], ref.cdf.probabilities, rtol=1e-14) + assert_allclose(res[2], ref.sf.probabilities, rtol=1e-14) + + def test_right_censored_ci(self): + # test "greenwood" confidence interval against example 4 (URL above). + times, died = self.t4, self.d4 + sample = stats.CensoredData.right_censored(times, np.logical_not(died)) + res = stats.ecdf(sample) + ref_allowance = [0.096, 0.096, 0.135, 0.162, 0.162, 0.162, 0.162, + 0.162, 0.162, 0.162, 0.214, 0.246, 0.246, 0.246, + 0.246, 0.341, 0.341] + + sf_ci = res.sf.confidence_interval() + cdf_ci = res.cdf.confidence_interval() + allowance = res.sf.probabilities - sf_ci.low.probabilities + + assert_allclose(allowance, ref_allowance, atol=1e-3) + assert_allclose(sf_ci.low.probabilities, + np.clip(res.sf.probabilities - allowance, 0, 1)) + assert_allclose(sf_ci.high.probabilities, + np.clip(res.sf.probabilities + allowance, 0, 1)) + assert_allclose(cdf_ci.low.probabilities, + np.clip(res.cdf.probabilities - allowance, 0, 1)) + assert_allclose(cdf_ci.high.probabilities, + np.clip(res.cdf.probabilities + allowance, 0, 1)) + + # test "log-log" confidence interval against Mathematica + # e = {24, 3, 11, 19, 24, 13, 14, 2, 18, 17, 24, 21, 12, 1, 10, 23, 6, 5, + # 9, 17} + # ci = {1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0} + # R = EventData[e, ci] + # S = SurvivalModelFit[R] + # S["PointwiseIntervals", ConfidenceLevel->0.95, + # ConfidenceTransform->"LogLog"] + + ref_low = [0.694743, 0.694743, 0.647529, 0.591142, 0.591142, 0.591142, + 0.591142, 0.591142, 0.591142, 0.591142, 0.464605, 0.370359, + 0.370359, 0.370359, 0.370359, 0.160489, 0.160489] + ref_high = [0.992802, 0.992802, 0.973299, 0.947073, 0.947073, 0.947073, + 0.947073, 0.947073, 0.947073, 0.947073, 0.906422, 0.856521, + 0.856521, 0.856521, 0.856521, 0.776724, 0.776724] + sf_ci = res.sf.confidence_interval(method='log-log') + assert_allclose(sf_ci.low.probabilities, ref_low, atol=1e-6) + assert_allclose(sf_ci.high.probabilities, ref_high, atol=1e-6) + + def test_right_censored_ci_example_5(self): + # test "exponential greenwood" confidence interval against example 5 + times, died = self.t5, self.d5 + sample = stats.CensoredData.right_censored(times, np.logical_not(died)) + res = stats.ecdf(sample) + lower = np.array([0.66639, 0.624174, 0.456179, 0.287822, 0.287822, + 0.287822, 0.128489, 0.030957, 0.030957, 0.030957]) + upper = np.array([0.991983, 0.970995, 0.87378, 0.739467, 0.739467, + 0.739467, 0.603133, 0.430365, 0.430365, 0.430365]) + + sf_ci = res.sf.confidence_interval(method='log-log') + cdf_ci = res.cdf.confidence_interval(method='log-log') + + assert_allclose(sf_ci.low.probabilities, lower, atol=1e-5) + assert_allclose(sf_ci.high.probabilities, upper, atol=1e-5) + assert_allclose(cdf_ci.low.probabilities, 1-upper, atol=1e-5) + assert_allclose(cdf_ci.high.probabilities, 1-lower, atol=1e-5) + + # Test against R's `survival` library `survfit` function, 90%CI + # library(survival) + # options(digits=16) + # time = c(3, 5, 8, 10, 5, 5, 8, 12, 15, 14, 2, 11, 10, 9, 12, 5, 8, 11) + # status = c(1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1) + # res = survfit(Surv(time, status) + # ~1, conf.type = "log-log", conf.int = 0.90) + # res$time; res$lower; res$upper + low = [0.74366748406861172, 0.68582332289196246, 0.50596835651480121, + 0.32913131413336727, 0.32913131413336727, 0.32913131413336727, + 0.15986912028781664, 0.04499539918147757, 0.04499539918147757, + 0.04499539918147757] + high = [0.9890291867238429, 0.9638835422144144, 0.8560366823086629, + 0.7130167643978450, 0.7130167643978450, 0.7130167643978450, + 0.5678602982997164, 0.3887616766886558, 0.3887616766886558, + 0.3887616766886558] + sf_ci = res.sf.confidence_interval(method='log-log', + confidence_level=0.9) + assert_allclose(sf_ci.low.probabilities, low) + assert_allclose(sf_ci.high.probabilities, high) + + # And with conf.type = "plain" + low = [0.8556383113628162, 0.7670478794850761, 0.5485720663578469, + 0.3441515412527123, 0.3441515412527123, 0.3441515412527123, + 0.1449184105424544, 0., 0., 0.] + high = [1., 1., 0.8958723780865975, 0.7391817920806210, + 0.7391817920806210, 0.7391817920806210, 0.5773038116797676, + 0.3642270254596720, 0.3642270254596720, 0.3642270254596720] + sf_ci = res.sf.confidence_interval(confidence_level=0.9) + assert_allclose(sf_ci.low.probabilities, low) + assert_allclose(sf_ci.high.probabilities, high) + + def test_right_censored_ci_nans(self): + # test `ecdf` confidence interval on a problem that results in NaNs + times, died = self.t1, self.d1 + sample = stats.CensoredData.right_censored(times, np.logical_not(died)) + res = stats.ecdf(sample) + + # Reference values generated with Matlab + # format long + # t = [37 43 47 56 60 62 71 77 80 81]; + # d = [0 0 1 1 0 0 0 1 1 1]; + # censored = ~d1; + # [f, x, flo, fup] = ecdf(t, 'Censoring', censored, 'Alpha', 0.05); + x = [37, 47, 56, 77, 80, 81] + flo = [np.nan, 0, 0, 0.052701464070711, 0.337611126231790, np.nan] + fup = [np.nan, 0.35417230377, 0.5500569798, 0.9472985359, 1.0, np.nan] + i = np.searchsorted(res.cdf.quantiles, x) + + message = "The confidence interval is undefined at some observations" + with pytest.warns(RuntimeWarning, match=message): + ci = res.cdf.confidence_interval() + + # Matlab gives NaN as the first element of the CIs. Mathematica agrees, + # but R's survfit does not. It makes some sense, but it's not what the + # formula gives, so skip that element. + assert_allclose(ci.low.probabilities[i][1:], flo[1:]) + assert_allclose(ci.high.probabilities[i][1:], fup[1:]) + + # [f, x, flo, fup] = ecdf(t, 'Censoring', censored, 'Function', + # 'survivor', 'Alpha', 0.05); + flo = [np.nan, 0.64582769623, 0.449943020228, 0.05270146407, 0, np.nan] + fup = [np.nan, 1.0, 1.0, 0.947298535929289, 0.662388873768210, np.nan] + i = np.searchsorted(res.cdf.quantiles, x) + + with pytest.warns(RuntimeWarning, match=message): + ci = res.sf.confidence_interval() + + assert_allclose(ci.low.probabilities[i][1:], flo[1:]) + assert_allclose(ci.high.probabilities[i][1:], fup[1:]) + + # With the same data, R's `survival` library `survfit` function + # doesn't produce the leading NaN + # library(survival) + # options(digits=16) + # time = c(37, 43, 47, 56, 60, 62, 71, 77, 80, 81) + # status = c(0, 0, 1, 1, 0, 0, 0, 1, 1, 1) + # res = survfit(Surv(time, status) + # ~1, conf.type = "plain", conf.int = 0.95) + # res$time + # res$lower + # res$upper + low = [1., 1., 0.64582769623233816, 0.44994302022779326, + 0.44994302022779326, 0.44994302022779326, 0.44994302022779326, + 0.05270146407071086, 0., np.nan] + high = [1., 1., 1., 1., 1., 1., 1., 0.9472985359292891, + 0.6623888737682101, np.nan] + assert_allclose(ci.low.probabilities, low) + assert_allclose(ci.high.probabilities, high) + + # It does with conf.type="log-log", as do we + with pytest.warns(RuntimeWarning, match=message): + ci = res.sf.confidence_interval(method='log-log') + low = [np.nan, np.nan, 0.38700001403202522, 0.31480711370551911, + 0.31480711370551911, 0.31480711370551911, 0.31480711370551911, + 0.08048821148507734, 0.01049958986680601, np.nan] + high = [np.nan, np.nan, 0.9813929658789660, 0.9308983170906275, + 0.9308983170906275, 0.9308983170906275, 0.9308983170906275, + 0.8263946341076415, 0.6558775085110887, np.nan] + assert_allclose(ci.low.probabilities, low) + assert_allclose(ci.high.probabilities, high) + + def test_right_censored_against_uncensored(self): + rng = np.random.default_rng(7463952748044886637) + sample = rng.integers(10, 100, size=1000) + censored = np.zeros_like(sample) + censored[np.argmax(sample)] = True + res = stats.ecdf(sample) + ref = stats.ecdf(stats.CensoredData.right_censored(sample, censored)) + assert_equal(res.sf.quantiles, ref.sf.quantiles) + assert_equal(res.sf._n, ref.sf._n) + assert_equal(res.sf._d[:-1], ref.sf._d[:-1]) # difference @ [-1] + assert_allclose(res.sf._sf[:-1], ref.sf._sf[:-1], rtol=1e-14) + + def test_plot_iv(self): + rng = np.random.default_rng(1769658657308472721) + n_unique = rng.integers(10, 100) + sample, _, _ = self.get_random_sample(rng, n_unique) + res = stats.ecdf(sample) + + try: + import matplotlib.pyplot as plt # noqa: F401 + res.sf.plot() # no other errors occur + except (ModuleNotFoundError, ImportError): + message = r"matplotlib must be installed to use method `plot`." + with pytest.raises(ModuleNotFoundError, match=message): + res.sf.plot() + + +class TestLogRank: + + @pytest.mark.parametrize( + "x, y, statistic, pvalue", + # Results validate with R + # library(survival) + # options(digits=16) + # + # futime_1 <- c(8, 12, 26, 14, 21, 27, 8, 32, 20, 40) + # fustat_1 <- c(1, 1, 1, 1, 1, 1, 0, 0, 0, 0) + # rx_1 <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + # + # futime_2 <- c(33, 28, 41, 48, 48, 25, 37, 48, 25, 43) + # fustat_2 <- c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0) + # rx_2 <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1) + # + # futime <- c(futime_1, futime_2) + # fustat <- c(fustat_1, fustat_2) + # rx <- c(rx_1, rx_2) + # + # survdiff(formula = Surv(futime, fustat) ~ rx) + # + # Also check against another library which handle alternatives + # library(nph) + # logrank.test(futime, fustat, rx, alternative = "two.sided") + # res["test"] + [( + # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html + # uncensored, censored + [[8, 12, 26, 14, 21, 27], [8, 32, 20, 40]], + [[33, 28, 41], [48, 48, 25, 37, 48, 25, 43]], + # chi2, ["two-sided", "less", "greater"] + 6.91598157449, + [0.008542873404, 0.9957285632979385, 0.004271436702061537] + ), + ( + # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html + [[19, 6, 5, 4], [20, 19, 17, 14]], + [[16, 21, 7], [21, 15, 18, 18, 5]], + 0.835004855038, + [0.3608293039, 0.8195853480676912, 0.1804146519323088] + ), + ( + # Bland, Altman, "The logrank test", BMJ, 2004 + # https://www.bmj.com/content/328/7447/1073.short + [[6, 13, 21, 30, 37, 38, 49, 50, 63, 79, 86, 98, 202, 219], + [31, 47, 80, 82, 82, 149]], + [[10, 10, 12, 13, 14, 15, 16, 17, 18, 20, 24, 24, 25, 28, 30, + 33, 35, 37, 40, 40, 46, 48, 76, 81, 82, 91, 112, 181], + [34, 40, 70]], + 7.49659416854, + [0.006181578637, 0.003090789318730882, 0.9969092106812691] + )] + ) + def test_log_rank(self, x, y, statistic, pvalue): + x = stats.CensoredData(uncensored=x[0], right=x[1]) + y = stats.CensoredData(uncensored=y[0], right=y[1]) + + for i, alternative in enumerate(["two-sided", "less", "greater"]): + res = stats.logrank(x=x, y=y, alternative=alternative) + + # we return z and use the normal distribution while other framework + # return z**2. The p-value are directly comparable, but we have to + # square the statistic + assert_allclose(res.statistic**2, statistic, atol=1e-10) + assert_allclose(res.pvalue, pvalue[i], atol=1e-10) + + def test_raises(self): + sample = stats.CensoredData([1, 2]) + + msg = r"`y` must be" + with pytest.raises(ValueError, match=msg): + stats.logrank(x=sample, y=[[1, 2]]) + + msg = r"`x` must be" + with pytest.raises(ValueError, match=msg): + stats.logrank(x=[[1, 2]], y=sample) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_tukeylambda_stats.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_tukeylambda_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..8041658599a6ed5b2cd70def1a92bffe0d851792 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_tukeylambda_stats.py @@ -0,0 +1,85 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_equal + +from scipy.stats._tukeylambda_stats import (tukeylambda_variance, + tukeylambda_kurtosis) + + +def test_tukeylambda_stats_known_exact(): + """Compare results with some known exact formulas.""" + # Some exact values of the Tukey Lambda variance and kurtosis: + # lambda var kurtosis + # 0 pi**2/3 6/5 (logistic distribution) + # 0.5 4 - pi (5/3 - pi/2)/(pi/4 - 1)**2 - 3 + # 1 1/3 -6/5 (uniform distribution on (-1,1)) + # 2 1/12 -6/5 (uniform distribution on (-1/2, 1/2)) + + # lambda = 0 + var = tukeylambda_variance(0) + assert_allclose(var, np.pi**2 / 3, atol=1e-12) + kurt = tukeylambda_kurtosis(0) + assert_allclose(kurt, 1.2, atol=1e-10) + + # lambda = 0.5 + var = tukeylambda_variance(0.5) + assert_allclose(var, 4 - np.pi, atol=1e-12) + kurt = tukeylambda_kurtosis(0.5) + desired = (5./3 - np.pi/2) / (np.pi/4 - 1)**2 - 3 + assert_allclose(kurt, desired, atol=1e-10) + + # lambda = 1 + var = tukeylambda_variance(1) + assert_allclose(var, 1.0 / 3, atol=1e-12) + kurt = tukeylambda_kurtosis(1) + assert_allclose(kurt, -1.2, atol=1e-10) + + # lambda = 2 + var = tukeylambda_variance(2) + assert_allclose(var, 1.0 / 12, atol=1e-12) + kurt = tukeylambda_kurtosis(2) + assert_allclose(kurt, -1.2, atol=1e-10) + + +def test_tukeylambda_stats_mpmath(): + """Compare results with some values that were computed using mpmath.""" + a10 = dict(atol=1e-10, rtol=0) + a12 = dict(atol=1e-12, rtol=0) + data = [ + # lambda variance kurtosis + [-0.1, 4.78050217874253547, 3.78559520346454510], + [-0.0649, 4.16428023599895777, 2.52019675947435718], + [-0.05, 3.93672267890775277, 2.13129793057777277], + [-0.001, 3.30128380390964882, 1.21452460083542988], + [0.001, 3.27850775649572176, 1.18560634779287585], + [0.03125, 2.95927803254615800, 0.804487555161819980], + [0.05, 2.78281053405464501, 0.611604043886644327], + [0.0649, 2.65282386754100551, 0.476834119532774540], + [1.2, 0.242153920578588346, -1.23428047169049726], + [10.0, 0.00095237579757703597, 2.37810697355144933], + [20.0, 0.00012195121951131043, 7.37654321002709531], + ] + + for lam, var_expected, kurt_expected in data: + var = tukeylambda_variance(lam) + assert_allclose(var, var_expected, **a12) + kurt = tukeylambda_kurtosis(lam) + assert_allclose(kurt, kurt_expected, **a10) + + # Test with vector arguments (most of the other tests are for single + # values). + lam, var_expected, kurt_expected = zip(*data) + var = tukeylambda_variance(lam) + assert_allclose(var, var_expected, **a12) + kurt = tukeylambda_kurtosis(lam) + assert_allclose(kurt, kurt_expected, **a10) + + +def test_tukeylambda_stats_invalid(): + """Test values of lambda outside the domains of the functions.""" + lam = [-1.0, -0.5] + var = tukeylambda_variance(lam) + assert_equal(var, np.array([np.nan, np.inf])) + + lam = [-1.0, -0.25] + kurt = tukeylambda_kurtosis(lam) + assert_equal(kurt, np.array([np.nan, np.inf])) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_variation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_variation.py new file mode 100644 index 0000000000000000000000000000000000000000..789f393e28c3961261f0f53ef26ec21335b28f71 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_variation.py @@ -0,0 +1,214 @@ +import math + +import numpy as np +import pytest +from numpy.testing import suppress_warnings + +from scipy.stats import variation +from scipy._lib._util import AxisError +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import is_numpy +from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close +from scipy.stats._axis_nan_policy import (too_small_nd_omit, too_small_nd_not_omit, + SmallSampleWarning) + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + + +class TestVariation: + """ + Test class for scipy.stats.variation + """ + + def test_ddof(self, xp): + x = xp.arange(9.0) + xp_assert_close(variation(x, ddof=1), xp.asarray(math.sqrt(60/8)/4)) + + @pytest.mark.parametrize('sgn', [1, -1]) + def test_sign(self, sgn, xp): + x = xp.asarray([1., 2., 3., 4., 5.]) + v = variation(sgn*x) + expected = xp.asarray(sgn*math.sqrt(2)/3) + xp_assert_close(v, expected, rtol=1e-10) + + def test_scalar(self, xp): + # A scalar is treated like a 1-d sequence with length 1. + xp_assert_equal(variation(4.0), 0.0) + + @pytest.mark.parametrize('nan_policy, expected', + [('propagate', np.nan), + ('omit', np.sqrt(20/3)/4)]) + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_variation_nan(self, nan_policy, expected, xp): + x = xp.arange(10.) + x[9] = xp.nan + xp_assert_close(variation(x, nan_policy=nan_policy), expected) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_nan_policy_raise(self, xp): + x = xp.asarray([1.0, 2.0, xp.nan, 3.0]) + with pytest.raises(ValueError, match='input contains nan'): + variation(x, nan_policy='raise') + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_bad_nan_policy(self, xp): + with pytest.raises(ValueError, match='must be one of'): + variation([1, 2, 3], nan_policy='foobar') + + @skip_xp_backends(np_only=True, + reason='`keepdims` only supports NumPy backend') + def test_keepdims(self, xp): + x = xp.reshape(xp.arange(10), (2, 5)) + y = variation(x, axis=1, keepdims=True) + expected = np.array([[np.sqrt(2)/2], + [np.sqrt(2)/7]]) + xp_assert_close(y, expected) + + @skip_xp_backends(np_only=True, + reason='`keepdims` only supports NumPy backend') + @pytest.mark.parametrize('axis, expected', + [(0, np.empty((1, 0))), + (1, np.full((5, 1), fill_value=np.nan))]) + def test_keepdims_size0(self, axis, expected, xp): + x = xp.zeros((5, 0)) + if axis == 1: + with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit): + y = variation(x, axis=axis, keepdims=True) + else: + y = variation(x, axis=axis, keepdims=True) + xp_assert_equal(y, expected) + + @skip_xp_backends(np_only=True, + reason='`keepdims` only supports NumPy backend') + @pytest.mark.parametrize('incr, expected_fill', [(0, np.inf), (1, np.nan)]) + def test_keepdims_and_ddof_eq_len_plus_incr(self, incr, expected_fill, xp): + x = xp.asarray([[1, 1, 2, 2], [1, 2, 3, 3]]) + y = variation(x, axis=1, ddof=x.shape[1] + incr, keepdims=True) + xp_assert_equal(y, xp.full((2, 1), fill_value=expected_fill)) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_propagate_nan(self, xp): + # Check that the shape of the result is the same for inputs + # with and without nans, cf gh-5817 + a = xp.reshape(xp.arange(8, dtype=float), (2, -1)) + a[1, 0] = xp.nan + v = variation(a, axis=1, nan_policy="propagate") + xp_assert_close(v, [math.sqrt(5/4)/1.5, xp.nan], atol=1e-15) + + @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend') + def test_axis_none(self, xp): + # Check that `variation` computes the result on the flattened + # input when axis is None. + y = variation([[0, 1], [2, 3]], axis=None) + xp_assert_close(y, math.sqrt(5/4)/1.5) + + def test_bad_axis(self, xp): + # Check that an invalid axis raises np.exceptions.AxisError. + x = xp.asarray([[1, 2, 3], [4, 5, 6]]) + with pytest.raises((AxisError, IndexError)): + variation(x, axis=10) + + def test_mean_zero(self, xp): + # Check that `variation` returns inf for a sequence that is not + # identically zero but whose mean is zero. + x = xp.asarray([10., -3., 1., -4., -4.]) + y = variation(x) + xp_assert_equal(y, xp.asarray(xp.inf)) + + x2 = xp.stack([x, -10.*x]) + y2 = variation(x2, axis=1) + xp_assert_equal(y2, xp.asarray([xp.inf, xp.inf])) + + @pytest.mark.parametrize('x', [[0.]*5, [1, 2, np.inf, 9]]) + def test_return_nan(self, x, xp): + x = xp.asarray(x) + # Test some cases where `variation` returns nan. + y = variation(x) + xp_assert_equal(y, xp.asarray(xp.nan, dtype=x.dtype)) + + @pytest.mark.parametrize('axis, expected', + [(0, []), (1, [np.nan]*3), (None, np.nan)]) + def test_2d_size_zero_with_axis(self, axis, expected, xp): + x = xp.empty((3, 0)) + with suppress_warnings() as sup: + # torch + sup.filter(UserWarning, "std*") + if axis != 0: + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match="See documentation..."): + y = variation(x, axis=axis) + else: + y = variation(x, axis=axis) + else: + y = variation(x, axis=axis) + xp_assert_equal(y, xp.asarray(expected)) + + def test_neg_inf(self, xp): + # Edge case that produces -inf: ddof equals the number of non-nan + # values, the values are not constant, and the mean is negative. + x1 = xp.asarray([-3., -5.]) + xp_assert_equal(variation(x1, ddof=2), xp.asarray(-xp.inf)) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_neg_inf_nan(self, xp): + x2 = xp.asarray([[xp.nan, 1, -10, xp.nan], + [-20, -3, xp.nan, xp.nan]]) + xp_assert_equal(variation(x2, axis=1, ddof=2, nan_policy='omit'), + [-xp.inf, -xp.inf]) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + @pytest.mark.parametrize("nan_policy", ['propagate', 'omit']) + def test_combined_edge_cases(self, nan_policy, xp): + x = xp.array([[0, 10, xp.nan, 1], + [0, -5, xp.nan, 2], + [0, -5, xp.nan, 3]]) + if nan_policy == 'omit': + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + y = variation(x, axis=0, nan_policy=nan_policy) + else: + y = variation(x, axis=0, nan_policy=nan_policy) + xp_assert_close(y, [xp.nan, xp.inf, xp.nan, math.sqrt(2/3)/2]) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + @pytest.mark.parametrize( + 'ddof, expected', + [(0, [np.sqrt(1/6), np.sqrt(5/8), np.inf, 0, np.nan, 0.0, np.nan]), + (1, [0.5, np.sqrt(5/6), np.inf, 0, np.nan, 0, np.nan]), + (2, [np.sqrt(0.5), np.sqrt(5/4), np.inf, np.nan, np.nan, 0, np.nan])] + ) + def test_more_nan_policy_omit_tests(self, ddof, expected, xp): + # The slightly strange formatting in the follow array is my attempt to + # maintain a clean tabular arrangement of the data while satisfying + # the demands of pycodestyle. Currently, E201 and E241 are not + # disabled by the `noqa` annotation. + nan = xp.nan + x = xp.asarray([[1.0, 2.0, nan, 3.0], + [0.0, 4.0, 3.0, 1.0], + [nan, -.5, 0.5, nan], + [nan, 9.0, 9.0, nan], + [nan, nan, nan, nan], + [3.0, 3.0, 3.0, 3.0], + [0.0, 0.0, 0.0, 0.0]]) + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + v = variation(x, axis=1, ddof=ddof, nan_policy='omit') + xp_assert_close(v, expected) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_variation_ddof(self, xp): + # test variation with delta degrees of freedom + # regression test for gh-13341 + a = xp.asarray([1., 2., 3., 4., 5.]) + nan_a = xp.asarray([1, 2, 3, xp.nan, 4, 5, xp.nan]) + y = variation(a, ddof=1) + nan_y = variation(nan_a, nan_policy="omit", ddof=1) + xp_assert_close(y, math.sqrt(5/2)/3) + assert y == nan_y diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c67ba49409169c49ac5d34f2be365def3c30369b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__init__.py @@ -0,0 +1,545 @@ +""" +SymPy is a Python library for symbolic mathematics. It aims to become a +full-featured computer algebra system (CAS) while keeping the code as simple +as possible in order to be comprehensible and easily extensible. SymPy is +written entirely in Python. It depends on mpmath, and other external libraries +may be optionally for things like plotting support. + +See the webpage for more information and documentation: + + https://sympy.org + +""" + + +# Keep this in sync with setup.py/pyproject.toml +import sys +if sys.version_info < (3, 9): + raise ImportError("Python version 3.9 or above is required for SymPy.") +del sys + + +try: + import mpmath +except ImportError: + raise ImportError("SymPy now depends on mpmath as an external library. " + "See https://docs.sympy.org/latest/install.html#mpmath for more information.") + +del mpmath + +from sympy.release import __version__ +from sympy.core.cache import lazy_function + +if 'dev' in __version__: + def enable_warnings(): + import warnings + warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*') + del warnings + enable_warnings() + del enable_warnings + + +def __sympy_debug(): + # helper function so we don't import os globally + import os + debug_str = os.getenv('SYMPY_DEBUG', 'False') + if debug_str in ('True', 'False'): + return eval(debug_str) + else: + raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % + debug_str) +# Fails py2 test if using type hinting +SYMPY_DEBUG = __sympy_debug() # type: bool + + +from .core import (sympify, SympifyError, cacheit, Basic, Atom, + preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol, + Wild, Dummy, symbols, var, Number, Float, Rational, Integer, + NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, + AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log, + trailing, Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality, + GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan, + vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass, + Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log, + expand_func, expand_trig, expand_complex, expand_multinomial, nfloat, + expand_power_base, expand_power_exp, arity, PrecisionExhausted, N, + evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate, + Catalan, EulerGamma, GoldenRatio, TribonacciConstant, bottom_up, use, + postorder_traversal, default_sort_key, ordered, num_digits) + +from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, + Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, + true, false, satisfiable) + +from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext, + assuming, Q, ask, register_handler, remove_handler, refine) + +from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr, + degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo, + pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, + subresultants, resultant, discriminant, cofactors, gcd_list, gcd, + lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose, + decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, + factor_list, factor, intervals, refine_root, count_roots, all_roots, + real_roots, nroots, ground_roots, nth_power_roots_poly, cancel, + reduced, groebner, is_zero_dimensional, GroebnerBasis, poly, + symmetrize, horner, interpolate, rational_interpolate, viete, together, + BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed, + OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed, + IsomorphismFailed, ExtraneousFactors, EvaluationFailed, + RefinementFailed, CoercionFailed, NotInvertible, NotReversible, + NotAlgebraic, DomainError, PolynomialError, UnificationFailed, + GeneratorsError, GeneratorsNeeded, ComputationFailed, + UnivariatePolynomialError, MultivariatePolynomialError, + PolificationFailed, OptionError, FlagError, minpoly, + minimal_polynomial, primitive_element, field_isomorphism, + to_number_field, isolate, round_two, prime_decomp, prime_valuation, + galois_group, itermonomials, Monomial, lex, grlex, + grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf, + ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing, + RationalField, RealField, ComplexField, PythonFiniteField, + GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational, + GMPYRationalField, AlgebraicField, PolynomialRing, FractionField, + ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, + QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW, + construct_domain, swinnerton_dyer_poly, cyclotomic_poly, + symmetric_poly, random_poly, interpolating_poly, jacobi_poly, + chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly, + legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list, + Options, ring, xring, vring, sring, field, xfield, vfield, sfield) + +from .series import (Order, O, limit, Limit, gruntz, series, approximants, + residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul, + fourier_series, fps, difference_delta, limit_seq) + +from .functions import (factorial, factorial2, rf, ff, binomial, + RisingFactorial, FallingFactorial, subfactorial, carmichael, + fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler, + catalan, genocchi, andre, partition, divisor_sigma, legendre_symbol, + jacobi_symbol, kronecker_symbol, mobius, primenu, primeomega, + totient, reduced_totient, primepi, sqrt, root, Min, Max, Id, + real_root, Rem, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift, + periodic_argument, unbranched_argument, principal_branch, transpose, + adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc, + asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log, + LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh, + acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold, + piecewise_exclusive, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, + Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, + lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, + multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, + LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside, + bspline_basis, bspline_basis_set, interpolating_spline, besselj, + bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1, + hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper, + meijerg, appellf1, legendre, assoc_legendre, hermite, hermite_prob, + chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre, + assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c, + Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus, + mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized) + +from .ntheory import (nextprime, prevprime, prime, primerange, + randprime, Sieve, sieve, primorial, cycle_length, composite, + compositepi, isprime, divisors, proper_divisors, factorint, + multiplicity, perfect_power, factor_cache, pollard_pm1, pollard_rho, primefactors, + divisor_count, proper_divisor_count, + factorrat, + mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, + is_deficient, is_amicable, is_carmichael, abundance, npartitions, is_primitive_root, + is_quad_residue, n_order, sqrt_mod, + quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue, + sqrt_mod_iter, discrete_log, quadratic_congruence, + binomial_coefficients, binomial_coefficients_list, + multinomial_coefficients, continued_fraction_periodic, + continued_fraction_iterator, continued_fraction_reduce, + continued_fraction_convergents, continued_fraction, egyptian_fraction) + +from .concrete import product, Product, summation, Sum + +from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, + inverse_mobius_transform, convolution, covering_product, + intersecting_product) + +from .simplify import (simplify, hypersimp, hypersimilar, logcombine, + separatevars, posify, besselsimp, kroneckersimp, signsimp, + nsimplify, FU, fu, sqrtdenest, cse, epath, EPath, hyperexpand, + collect, rcollect, radsimp, collect_const, fraction, numer, denom, + trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp, + ratsimp, ratsimpmodprime) + +from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet, + Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet, + Range, ComplexRegion, Complexes, Reals, Contains, ConditionSet, Ordinal, + OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet, + Integers, Rationals) + +from .solvers import (solve, solve_linear_system, solve_linear_system_LU, + solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick, + inv_quick, check_assumptions, failing_assumptions, diophantine, + rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol, + classify_ode, dsolve, homogeneous_order, solve_poly_system, factor_system, + solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul, + pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities, + reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality, + solve_rational_inequalities, solve_univariate_inequality, decompogen, + solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution) + +from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt, + casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy, + matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, + rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix, + DeferredVector, MatrixBase, Matrix, MutableMatrix, + MutableSparseMatrix, banded, ImmutableDenseMatrix, + ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice, + BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse, + MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose, + ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, + Adjoint, hadamard_product, HadamardProduct, HadamardPower, + Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix, + DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct, + PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1, + rot_ccw_axis2, rot_ccw_axis3, rot_givens) + +from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D, + Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle, + Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid, + convex_hull, idiff, intersection, closest_points, farthest_points, + GeometryError, Curve, Parabola) + +from .utilities import (flatten, group, take, subsets, variations, + numbered_symbols, cartes, capture, dict_merge, prefixes, postfixes, + sift, topological_sort, unflatten, has_dups, has_variety, reshape, + rotations, filldedent, lambdify, + threaded, xthreaded, public, memoize_property, timed) + +from .integrals import (integrate, Integral, line_integrate, mellin_transform, + inverse_mellin_transform, MellinTransform, InverseMellinTransform, + laplace_transform, laplace_correspondence, laplace_initial_conds, + inverse_laplace_transform, LaplaceTransform, + InverseLaplaceTransform, fourier_transform, inverse_fourier_transform, + FourierTransform, InverseFourierTransform, sine_transform, + inverse_sine_transform, SineTransform, InverseSineTransform, + cosine_transform, inverse_cosine_transform, CosineTransform, + InverseCosineTransform, hankel_transform, inverse_hankel_transform, + HankelTransform, InverseHankelTransform, singularityintegrate) + +from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure, + get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray, + MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, + tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, + permutedims, Array, DenseNDimArray, SparseNDimArray) + +from .parsing import parse_expr + +from .calculus import (euler_equations, singularities, is_increasing, + is_strictly_increasing, is_decreasing, is_strictly_decreasing, + is_monotonic, finite_diff_weights, apply_finite_diff, + differentiate_finite, periodicity, not_empty_in, AccumBounds, + is_convex, stationary_points, minimum, maximum) + +from .algebras import Quaternion + +from .printing import (pager_print, pretty, pretty_print, pprint, + pprint_use_unicode, pprint_try_use_unicode, latex, print_latex, + multiline_latex, mathml, print_mathml, python, print_python, pycode, + ccode, print_ccode, smtlib_code, glsl_code, print_glsl, cxxcode, fcode, + print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code, + mathematica_code, octave_code, rust_code, print_gtk, preview, srepr, + print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint, + maple_code, print_maple_code) + +test = lazy_function('sympy.testing.runtests_pytest', 'test') +doctest = lazy_function('sympy.testing.runtests', 'doctest') + +# This module causes conflicts with other modules: +# from .stats import * +# Adds about .04-.05 seconds of import time +# from combinatorics import * +# This module is slow to import: +#from physics import units +from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric +from .interactive import init_session, init_printing, interactive_traversal + +evalf._create_evalf_table() + +__all__ = [ + '__version__', + + # sympy.core + 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom', + 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr', + 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float', + 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm', + 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp', + 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'trailing', 'Mul', 'prod', + 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', + 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan', + 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative', + 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError', + 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig', + 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base', + 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple', + 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan', + 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', 'bottom_up', 'use', + 'postorder_traversal', 'default_sort_key', 'ordered', 'num_digits', + + # sympy.logic + 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor', + 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic', + 'bool_map', 'true', 'false', 'satisfiable', + + # sympy.assumptions + 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q', + 'ask', 'register_handler', 'remove_handler', 'refine', + + # sympy.polys + 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree', + 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo', + 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert', + 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list', + 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content', + 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff', + 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor', + 'intervals', 'refine_root', 'count_roots', 'all_roots', 'real_roots', + 'nroots', 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', + 'groebner', 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', + 'horner', 'interpolate', 'rational_interpolate', 'viete', 'together', + 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed', + 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed', + 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed', + 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible', + 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed', + 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed', + 'UnivariatePolynomialError', 'MultivariatePolynomialError', + 'PolificationFailed', 'OptionError', 'FlagError', 'minpoly', + 'minimal_polynomial', 'primitive_element', 'field_isomorphism', + 'to_number_field', 'isolate', 'round_two', 'prime_decomp', + 'prime_valuation', 'galois_group', 'itermonomials', 'Monomial', 'lex', 'grlex', + 'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf', + 'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField', + 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', + 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', + 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', + 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', + 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', + 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', + 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly', + 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly', + 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly', + 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list', + 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', + 'sfield', + + # sympy.series + 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants', + 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd', + 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq', + + # sympy.functions + 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial', + 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas', + 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan', + 'genocchi', 'andre', 'partition', 'divisor_sigma', 'legendre_symbol', 'jacobi_symbol', + 'kronecker_symbol', 'mobius', 'primenu', 'primeomega', 'totient', 'primepi', + 'reduced_totient', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', + 'Rem', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift', + 'periodic_argument', 'unbranched_argument', 'principal_branch', + 'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan', + 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc', + 'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh', + 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', + 'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise', + 'piecewise_fold', 'piecewise_exclusive', 'erf', 'erfc', 'erfi', 'erf2', + 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', + 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma', + 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma', + 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita', + 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside', + 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj', + 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn', + 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime', + 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre', + 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt', 'chebyshevu', + 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre', + 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm', + 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta', + 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc', + 'betainc_regularized', + + # sympy.ntheory + 'nextprime', 'prevprime', 'prime', 'primerange', 'randprime', + 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi', + 'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity', + 'perfect_power', 'pollard_pm1', 'factor_cache', 'pollard_rho', 'primefactors', + 'divisor_count', 'proper_divisor_count', + 'factorrat', + 'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime', + 'is_abundant', 'is_deficient', 'is_amicable', 'is_carmichael', 'abundance', + 'npartitions', + 'is_primitive_root', 'is_quad_residue', + 'n_order', 'sqrt_mod', 'quadratic_residues', + 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter', + 'discrete_log', 'quadratic_congruence', 'binomial_coefficients', + 'binomial_coefficients_list', 'multinomial_coefficients', + 'continued_fraction_periodic', 'continued_fraction_iterator', + 'continued_fraction_reduce', 'continued_fraction_convergents', + 'continued_fraction', 'egyptian_fraction', + + # sympy.concrete + 'product', 'Product', 'summation', 'Sum', + + # sympy.discrete + 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform', + 'inverse_mobius_transform', 'convolution', 'covering_product', + 'intersecting_product', + + # sympy.simplify + 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars', + 'posify', 'besselsimp', 'kroneckersimp', 'signsimp', + 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'epath', 'EPath', + 'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const', + 'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp', + 'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime', + + # sympy.sets + 'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet', + 'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference', + 'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet', + 'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Naturals', + 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes', + + # sympy.solvers + 'solve', 'solve_linear_system', 'solve_linear_system_LU', + 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol', + 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions', + 'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper', + 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order', + 'solve_poly_system', 'factor_system', 'solve_triangulated', 'pde_separate', + 'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde', + 'checkpdesol', 'ode_order', 'reduce_inequalities', + 'reduce_abs_inequality', 'reduce_abs_inequalities', + 'solve_poly_inequality', 'solve_rational_inequalities', + 'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve', + 'linear_eq_to_matrix', 'nonlinsolve', 'substitution', + + # sympy.matrices + 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag', + 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy', + 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1', + 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros', + 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix', + 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix', + 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice', + 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse', + 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace', + 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse', + 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct', + 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix', + 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct', + 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix', + 'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2', + 'rot_ccw_axis3', 'rot_givens', + + # sympy.geometry + 'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D', + 'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse', + 'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg', + 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection', + 'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola', + + # sympy.utilities + 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols', + 'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift', + 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape', + 'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded', + 'public', 'memoize_property', 'timed', + + # sympy.integrals + 'integrate', 'Integral', 'line_integrate', 'mellin_transform', + 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform', + 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform', + 'laplace_correspondence', 'laplace_initial_conds', + 'InverseLaplaceTransform', 'fourier_transform', + 'inverse_fourier_transform', 'FourierTransform', + 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform', + 'SineTransform', 'InverseSineTransform', 'cosine_transform', + 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform', + 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform', + 'InverseHankelTransform', 'singularityintegrate', + + # sympy.tensor + 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure', + 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', + 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', + 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', + 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray', + + # sympy.parsing + 'parse_expr', + + # sympy.calculus + 'euler_equations', 'singularities', 'is_increasing', + 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing', + 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff', + 'differentiate_finite', 'periodicity', 'not_empty_in', + 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum', + + # sympy.algebras + 'Quaternion', + + # sympy.printing + 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', + 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex', + 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode', + 'print_ccode', 'smtlib_code', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode', + 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode', + 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk', + 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr', + 'TableForm', 'dotprint', 'maple_code', 'print_maple_code', + + # sympy.plotting + 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric', + + # sympy.interactive + 'init_session', 'init_printing', 'interactive_traversal', + + # sympy.testing + 'test', 'doctest', +] + + +#===========================================================================# +# # +# XXX: The names below were importable before SymPy 1.6 using # +# # +# from sympy import * # +# # +# This happened implicitly because there was no __all__ defined in this # +# __init__.py file. Not every package is imported. The list matches what # +# would have been imported before. It is possible that these packages will # +# not be imported by a star-import from sympy in future. # +# # +#===========================================================================# + + +__all__.extend(( + 'algebras', + 'assumptions', + 'calculus', + 'concrete', + 'discrete', + 'external', + 'functions', + 'geometry', + 'interactive', + 'multipledispatch', + 'ntheory', + 'parsing', + 'plotting', + 'polys', + 'printing', + 'release', + 'strategies', + 'tensor', + 'utilities', +)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/abc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f7a4056e60b0d651becc0b9909bd0ab3c1723f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/abc.py @@ -0,0 +1,111 @@ +""" +This module exports all latin and greek letters as Symbols, so you can +conveniently do + + >>> from sympy.abc import x, y + +instead of the slightly more clunky-looking + + >>> from sympy import symbols + >>> x, y = symbols('x y') + +Caveats +======= + +1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``, +``E``, and ``Q`` are colliding with names defined in SymPy. If you import them +from both ``sympy.abc`` and ``sympy``, the second import will "win". +This is an issue only for * imports, which should only be used for short-lived +code such as interactive sessions and throwaway scripts that do not survive +until the next SymPy upgrade, where ``sympy`` may contain a different set of +names. + +2. This module does not define symbol names on demand, i.e. +``from sympy.abc import foo`` will be reported as an error because +``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``, +you still need to use ``Symbol('foo')`` or ``symbols('foo')``. +You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though +sticking with one and only one way to get the symbols does tend to make the code +more readable. + +The module also defines some special names to help detect which names clash +with the default SymPy namespace. + +``_clash1`` defines all the single letter variables that clash with +SymPy objects; ``_clash2`` defines the multi-letter clashing symbols; +and ``_clash`` is the union of both. These can be passed for ``locals`` +during sympification if one desires Symbols rather than the non-Symbol +objects for those names. + +Examples +======== + +>>> from sympy import S +>>> from sympy.abc import _clash1, _clash2, _clash +>>> S("Q & C", locals=_clash1) +C & Q +>>> S('pi(x)', locals=_clash2) +pi(x) +>>> S('pi(C, Q)', locals=_clash) +pi(C, Q) + +""" +from __future__ import annotations +from typing import Any + +import string + +from .core import Symbol, symbols +from .core.alphabets import greeks +from sympy.parsing.sympy_parser import null + +##### Symbol definitions ##### + +# Implementation note: The easiest way to avoid typos in the symbols() +# parameter is to copy it from the left-hand side of the assignment. + +a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j') +k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t') +u, v, w, x, y, z = symbols('u, v, w, x, y, z') + +A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J') +K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T') +U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z') + +alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta') +epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta') +iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu') +nu, xi, omicron, pi = symbols('nu, xi, omicron, pi') +rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon') +phi, chi, psi, omega = symbols('phi, chi, psi, omega') + + +##### Clashing-symbols diagnostics ##### + +# We want to know which names in SymPy collide with those in here. +# This is mostly for diagnosing SymPy's namespace during SymPy development. + +_latin = list(string.ascii_letters) +# QOSINE should not be imported as they clash; gamma, pi and zeta clash, too +_greek = list(greeks) # make a copy, so we can mutate it +# Note: We import lamda since lambda is a reserved keyword in Python +_greek.remove("lambda") +_greek.append("lamda") + +ns: dict[str, Any] = {} +exec('from sympy import *', ns) +_clash1: dict[str, Any] = {} +_clash2: dict[str, Any] = {} +while ns: + _k, _ = ns.popitem() + if _k in _greek: + _clash2[_k] = null + _greek.remove(_k) + elif _k in _latin: + _clash1[_k] = null + _latin.remove(_k) +_clash = {} +_clash.update(_clash1) +_clash.update(_clash2) + +del _latin, _greek, Symbol, _k, null diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..220c27a42975555f8fe7770fcef0dd18475c89e1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/__init__.py @@ -0,0 +1,43 @@ +from sympy.combinatorics.permutations import Permutation, Cycle +from sympy.combinatorics.prufer import Prufer +from sympy.combinatorics.generators import cyclic, alternating, symmetric, dihedral +from sympy.combinatorics.subsets import Subset +from sympy.combinatorics.partitions import (Partition, IntegerPartition, + RGS_rank, RGS_unrank, RGS_enum) +from sympy.combinatorics.polyhedron import (Polyhedron, tetrahedron, cube, + octahedron, dodecahedron, icosahedron) +from sympy.combinatorics.perm_groups import PermutationGroup, Coset, SymmetricPermutationGroup +from sympy.combinatorics.group_constructs import DirectProduct +from sympy.combinatorics.graycode import GrayCode +from sympy.combinatorics.named_groups import (SymmetricGroup, DihedralGroup, + CyclicGroup, AlternatingGroup, AbelianGroup, RubikGroup) +from sympy.combinatorics.pc_groups import PolycyclicGroup, Collector +from sympy.combinatorics.free_groups import free_group + +__all__ = [ + 'Permutation', 'Cycle', + + 'Prufer', + + 'cyclic', 'alternating', 'symmetric', 'dihedral', + + 'Subset', + + 'Partition', 'IntegerPartition', 'RGS_rank', 'RGS_unrank', 'RGS_enum', + + 'Polyhedron', 'tetrahedron', 'cube', 'octahedron', 'dodecahedron', + 'icosahedron', + + 'PermutationGroup', 'Coset', 'SymmetricPermutationGroup', + + 'DirectProduct', + + 'GrayCode', + + 'SymmetricGroup', 'DihedralGroup', 'CyclicGroup', 'AlternatingGroup', + 'AbelianGroup', 'RubikGroup', + + 'PolycyclicGroup', 'Collector', + + 'free_group', +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/coset_table.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/coset_table.py new file mode 100644 index 0000000000000000000000000000000000000000..0687aa34ec70e9062f65ff6413213848cf03e51b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/coset_table.py @@ -0,0 +1,1259 @@ +from sympy.combinatorics.free_groups import free_group +from sympy.printing.defaults import DefaultPrinting + +from itertools import chain, product +from bisect import bisect_left + + +############################################################################### +# COSET TABLE # +############################################################################### + +class CosetTable(DefaultPrinting): + # coset_table: Mathematically a coset table + # represented using a list of lists + # alpha: Mathematically a coset (precisely, a live coset) + # represented by an integer between i with 1 <= i <= n + # alpha in c + # x: Mathematically an element of "A" (set of generators and + # their inverses), represented using "FpGroupElement" + # fp_grp: Finitely Presented Group with < X|R > as presentation. + # H: subgroup of fp_grp. + # NOTE: We start with H as being only a list of words in generators + # of "fp_grp". Since `.subgroup` method has not been implemented. + + r""" + + Properties + ========== + + [1] `0 \in \Omega` and `\tau(1) = \epsilon` + [2] `\alpha^x = \beta \Leftrightarrow \beta^{x^{-1}} = \alpha` + [3] If `\alpha^x = \beta`, then `H \tau(\alpha)x = H \tau(\beta)` + [4] `\forall \alpha \in \Omega, 1^{\tau(\alpha)} = \alpha` + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + + .. [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson + Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. + "Implementation and Analysis of the Todd-Coxeter Algorithm" + + """ + # default limit for the number of cosets allowed in a + # coset enumeration. + coset_table_max_limit = 4096000 + # limit for the current instance + coset_table_limit = None + # maximum size of deduction stack above or equal to + # which it is emptied + max_stack_size = 100 + + def __init__(self, fp_grp, subgroup, max_cosets=None): + if not max_cosets: + max_cosets = CosetTable.coset_table_max_limit + self.fp_group = fp_grp + self.subgroup = subgroup + self.coset_table_limit = max_cosets + # "p" is setup independent of Omega and n + self.p = [0] + # a list of the form `[gen_1, gen_1^{-1}, ... , gen_k, gen_k^{-1}]` + self.A = list(chain.from_iterable((gen, gen**-1) \ + for gen in self.fp_group.generators)) + #P[alpha, x] Only defined when alpha^x is defined. + self.P = [[None]*len(self.A)] + # the mathematical coset table which is a list of lists + self.table = [[None]*len(self.A)] + self.A_dict = {x: self.A.index(x) for x in self.A} + self.A_dict_inv = {} + for x, index in self.A_dict.items(): + if index % 2 == 0: + self.A_dict_inv[x] = self.A_dict[x] + 1 + else: + self.A_dict_inv[x] = self.A_dict[x] - 1 + # used in the coset-table based method of coset enumeration. Each of + # the element is called a "deduction" which is the form (alpha, x) whenever + # a value is assigned to alpha^x during a definition or "deduction process" + self.deduction_stack = [] + # Attributes for modified methods. + H = self.subgroup + self._grp = free_group(', ' .join(["a_%d" % i for i in range(len(H))]))[0] + self.P = [[None]*len(self.A)] + self.p_p = {} + + @property + def omega(self): + """Set of live cosets. """ + return [coset for coset in range(len(self.p)) if self.p[coset] == coset] + + def copy(self): + """ + Return a shallow copy of Coset Table instance ``self``. + + """ + self_copy = self.__class__(self.fp_group, self.subgroup) + self_copy.table = [list(perm_rep) for perm_rep in self.table] + self_copy.p = list(self.p) + self_copy.deduction_stack = list(self.deduction_stack) + return self_copy + + def __str__(self): + return "Coset Table on %s with %s as subgroup generators" \ + % (self.fp_group, self.subgroup) + + __repr__ = __str__ + + @property + def n(self): + """The number `n` represents the length of the sublist containing the + live cosets. + + """ + if not self.table: + return 0 + return max(self.omega) + 1 + + # Pg. 152 [1] + def is_complete(self): + r""" + The coset table is called complete if it has no undefined entries + on the live cosets; that is, `\alpha^x` is defined for all + `\alpha \in \Omega` and `x \in A`. + + """ + return not any(None in self.table[coset] for coset in self.omega) + + # Pg. 153 [1] + def define(self, alpha, x, modified=False): + r""" + This routine is used in the relator-based strategy of Todd-Coxeter + algorithm if some `\alpha^x` is undefined. We check whether there is + space available for defining a new coset. If there is enough space + then we remedy this by adjoining a new coset `\beta` to `\Omega` + (i.e to set of live cosets) and put that equal to `\alpha^x`, then + make an assignment satisfying Property[1]. If there is not enough space + then we halt the Coset Table creation. The maximum amount of space that + can be used by Coset Table can be manipulated using the class variable + ``CosetTable.coset_table_max_limit``. + + See Also + ======== + + define_c + + """ + A = self.A + table = self.table + len_table = len(table) + if len_table >= self.coset_table_limit: + # abort the further generation of cosets + raise ValueError("the coset enumeration has defined more than " + "%s cosets. Try with a greater value max number of cosets " + % self.coset_table_limit) + table.append([None]*len(A)) + self.P.append([None]*len(self.A)) + # beta is the new coset generated + beta = len_table + self.p.append(beta) + table[alpha][self.A_dict[x]] = beta + table[beta][self.A_dict_inv[x]] = alpha + # P[alpha][x] = epsilon, P[beta][x**-1] = epsilon + if modified: + self.P[alpha][self.A_dict[x]] = self._grp.identity + self.P[beta][self.A_dict_inv[x]] = self._grp.identity + self.p_p[beta] = self._grp.identity + + def define_c(self, alpha, x): + r""" + A variation of ``define`` routine, described on Pg. 165 [1], used in + the coset table-based strategy of Todd-Coxeter algorithm. It differs + from ``define`` routine in that for each definition it also adds the + tuple `(\alpha, x)` to the deduction stack. + + See Also + ======== + + define + + """ + A = self.A + table = self.table + len_table = len(table) + if len_table >= self.coset_table_limit: + # abort the further generation of cosets + raise ValueError("the coset enumeration has defined more than " + "%s cosets. Try with a greater value max number of cosets " + % self.coset_table_limit) + table.append([None]*len(A)) + # beta is the new coset generated + beta = len_table + self.p.append(beta) + table[alpha][self.A_dict[x]] = beta + table[beta][self.A_dict_inv[x]] = alpha + # append to deduction stack + self.deduction_stack.append((alpha, x)) + + def scan_c(self, alpha, word): + """ + A variation of ``scan`` routine, described on pg. 165 of [1], which + puts at tuple, whenever a deduction occurs, to deduction stack. + + See Also + ======== + + scan, scan_check, scan_and_fill, scan_and_fill_c + + """ + # alpha is an integer representing a "coset" + # since scanning can be in two cases + # 1. for alpha=0 and w in Y (i.e generating set of H) + # 2. alpha in Omega (set of live cosets), w in R (relators) + A_dict = self.A_dict + A_dict_inv = self.A_dict_inv + table = self.table + f = alpha + i = 0 + r = len(word) + b = alpha + j = r - 1 + # list of union of generators and their inverses + while i <= j and table[f][A_dict[word[i]]] is not None: + f = table[f][A_dict[word[i]]] + i += 1 + if i > j: + if f != b: + self.coincidence_c(f, b) + return + while j >= i and table[b][A_dict_inv[word[j]]] is not None: + b = table[b][A_dict_inv[word[j]]] + j -= 1 + if j < i: + # we have an incorrect completed scan with coincidence f ~ b + # run the "coincidence" routine + self.coincidence_c(f, b) + elif j == i: + # deduction process + table[f][A_dict[word[i]]] = b + table[b][A_dict_inv[word[i]]] = f + self.deduction_stack.append((f, word[i])) + # otherwise scan is incomplete and yields no information + + # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets where + # coincidence occurs + def coincidence_c(self, alpha, beta): + """ + A variation of ``coincidence`` routine used in the coset-table based + method of coset enumeration. The only difference being on addition of + a new coset in coset table(i.e new coset introduction), then it is + appended to ``deduction_stack``. + + See Also + ======== + + coincidence + + """ + A_dict = self.A_dict + A_dict_inv = self.A_dict_inv + table = self.table + # behaves as a queue + q = [] + self.merge(alpha, beta, q) + while len(q) > 0: + gamma = q.pop(0) + for x in A_dict: + delta = table[gamma][A_dict[x]] + if delta is not None: + table[delta][A_dict_inv[x]] = None + # only line of difference from ``coincidence`` routine + self.deduction_stack.append((delta, x**-1)) + mu = self.rep(gamma) + nu = self.rep(delta) + if table[mu][A_dict[x]] is not None: + self.merge(nu, table[mu][A_dict[x]], q) + elif table[nu][A_dict_inv[x]] is not None: + self.merge(mu, table[nu][A_dict_inv[x]], q) + else: + table[mu][A_dict[x]] = nu + table[nu][A_dict_inv[x]] = mu + + def scan(self, alpha, word, y=None, fill=False, modified=False): + r""" + ``scan`` performs a scanning process on the input ``word``. + It first locates the largest prefix ``s`` of ``word`` for which + `\alpha^s` is defined (i.e is not ``None``), ``s`` may be empty. Let + ``word=sv``, let ``t`` be the longest suffix of ``v`` for which + `\alpha^{t^{-1}}` is defined, and let ``v=ut``. Then three + possibilities are there: + + 1. If ``t=v``, then we say that the scan completes, and if, in addition + `\alpha^s = \alpha^{t^{-1}}`, then we say that the scan completes + correctly. + + 2. It can also happen that scan does not complete, but `|u|=1`; that + is, the word ``u`` consists of a single generator `x \in A`. In that + case, if `\alpha^s = \beta` and `\alpha^{t^{-1}} = \gamma`, then we can + set `\beta^x = \gamma` and `\gamma^{x^{-1}} = \beta`. These assignments + are known as deductions and enable the scan to complete correctly. + + 3. See ``coicidence`` routine for explanation of third condition. + + Notes + ===== + + The code for the procedure of scanning `\alpha \in \Omega` + under `w \in A*` is defined on pg. 155 [1] + + See Also + ======== + + scan_c, scan_check, scan_and_fill, scan_and_fill_c + + Scan and Fill + ============= + + Performed when the default argument fill=True. + + Modified Scan + ============= + + Performed when the default argument modified=True + + """ + # alpha is an integer representing a "coset" + # since scanning can be in two cases + # 1. for alpha=0 and w in Y (i.e generating set of H) + # 2. alpha in Omega (set of live cosets), w in R (relators) + A_dict = self.A_dict + A_dict_inv = self.A_dict_inv + table = self.table + f = alpha + i = 0 + r = len(word) + b = alpha + j = r - 1 + b_p = y + if modified: + f_p = self._grp.identity + flag = 0 + while fill or flag == 0: + flag = 1 + while i <= j and table[f][A_dict[word[i]]] is not None: + if modified: + f_p = f_p*self.P[f][A_dict[word[i]]] + f = table[f][A_dict[word[i]]] + i += 1 + if i > j: + if f != b: + if modified: + self.modified_coincidence(f, b, f_p**-1*y) + else: + self.coincidence(f, b) + return + while j >= i and table[b][A_dict_inv[word[j]]] is not None: + if modified: + b_p = b_p*self.P[b][self.A_dict_inv[word[j]]] + b = table[b][A_dict_inv[word[j]]] + j -= 1 + if j < i: + # we have an incorrect completed scan with coincidence f ~ b + # run the "coincidence" routine + if modified: + self.modified_coincidence(f, b, f_p**-1*b_p) + else: + self.coincidence(f, b) + elif j == i: + # deduction process + table[f][A_dict[word[i]]] = b + table[b][A_dict_inv[word[i]]] = f + if modified: + self.P[f][self.A_dict[word[i]]] = f_p**-1*b_p + self.P[b][self.A_dict_inv[word[i]]] = b_p**-1*f_p + return + elif fill: + self.define(f, word[i], modified=modified) + # otherwise scan is incomplete and yields no information + + # used in the low-index subgroups algorithm + def scan_check(self, alpha, word): + r""" + Another version of ``scan`` routine, described on, it checks whether + `\alpha` scans correctly under `word`, it is a straightforward + modification of ``scan``. ``scan_check`` returns ``False`` (rather than + calling ``coincidence``) if the scan completes incorrectly; otherwise + it returns ``True``. + + See Also + ======== + + scan, scan_c, scan_and_fill, scan_and_fill_c + + """ + # alpha is an integer representing a "coset" + # since scanning can be in two cases + # 1. for alpha=0 and w in Y (i.e generating set of H) + # 2. alpha in Omega (set of live cosets), w in R (relators) + A_dict = self.A_dict + A_dict_inv = self.A_dict_inv + table = self.table + f = alpha + i = 0 + r = len(word) + b = alpha + j = r - 1 + while i <= j and table[f][A_dict[word[i]]] is not None: + f = table[f][A_dict[word[i]]] + i += 1 + if i > j: + return f == b + while j >= i and table[b][A_dict_inv[word[j]]] is not None: + b = table[b][A_dict_inv[word[j]]] + j -= 1 + if j < i: + # we have an incorrect completed scan with coincidence f ~ b + # return False, instead of calling coincidence routine + return False + elif j == i: + # deduction process + table[f][A_dict[word[i]]] = b + table[b][A_dict_inv[word[i]]] = f + return True + + def merge(self, k, lamda, q, w=None, modified=False): + """ + Merge two classes with representatives ``k`` and ``lamda``, described + on Pg. 157 [1] (for pseudocode), start by putting ``p[k] = lamda``. + It is more efficient to choose the new representative from the larger + of the two classes being merged, i.e larger among ``k`` and ``lamda``. + procedure ``merge`` performs the merging operation, adds the deleted + class representative to the queue ``q``. + + Parameters + ========== + + 'k', 'lamda' being the two class representatives to be merged. + + Notes + ===== + + Pg. 86-87 [1] contains a description of this method. + + See Also + ======== + + coincidence, rep + + """ + p = self.p + rep = self.rep + phi = rep(k, modified=modified) + psi = rep(lamda, modified=modified) + if phi != psi: + mu = min(phi, psi) + v = max(phi, psi) + p[v] = mu + if modified: + if v == phi: + self.p_p[phi] = self.p_p[k]**-1*w*self.p_p[lamda] + else: + self.p_p[psi] = self.p_p[lamda]**-1*w**-1*self.p_p[k] + q.append(v) + + def rep(self, k, modified=False): + r""" + Parameters + ========== + + `k \in [0 \ldots n-1]`, as for ``self`` only array ``p`` is used + + Returns + ======= + + Representative of the class containing ``k``. + + Returns the representative of `\sim` class containing ``k``, it also + makes some modification to array ``p`` of ``self`` to ease further + computations, described on Pg. 157 [1]. + + The information on classes under `\sim` is stored in array `p` of + ``self`` argument, which will always satisfy the property: + + `p[\alpha] \sim \alpha` and `p[\alpha]=\alpha \iff \alpha=rep(\alpha)` + `\forall \in [0 \ldots n-1]`. + + So, for `\alpha \in [0 \ldots n-1]`, we find `rep(self, \alpha)` by + continually replacing `\alpha` by `p[\alpha]` until it becomes + constant (i.e satisfies `p[\alpha] = \alpha`):w + + To increase the efficiency of later ``rep`` calculations, whenever we + find `rep(self, \alpha)=\beta`, we set + `p[\gamma] = \beta \forall \gamma \in p-chain` from `\alpha` to `\beta` + + Notes + ===== + + ``rep`` routine is also described on Pg. 85-87 [1] in Atkinson's + algorithm, this results from the fact that ``coincidence`` routine + introduces functionality similar to that introduced by the + ``minimal_block`` routine on Pg. 85-87 [1]. + + See Also + ======== + + coincidence, merge + + """ + p = self.p + lamda = k + rho = p[lamda] + if modified: + s = p[:] + while rho != lamda: + if modified: + s[rho] = lamda + lamda = rho + rho = p[lamda] + if modified: + rho = s[lamda] + while rho != k: + mu = rho + rho = s[mu] + p[rho] = lamda + self.p_p[rho] = self.p_p[rho]*self.p_p[mu] + else: + mu = k + rho = p[mu] + while rho != lamda: + p[mu] = lamda + mu = rho + rho = p[mu] + return lamda + + # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets + # where coincidence occurs + def coincidence(self, alpha, beta, w=None, modified=False): + r""" + The third situation described in ``scan`` routine is handled by this + routine, described on Pg. 156-161 [1]. + + The unfortunate situation when the scan completes but not correctly, + then ``coincidence`` routine is run. i.e when for some `i` with + `1 \le i \le r+1`, we have `w=st` with `s = x_1 x_2 \dots x_{i-1}`, + `t = x_i x_{i+1} \dots x_r`, and `\beta = \alpha^s` and + `\gamma = \alpha^{t-1}` are defined but unequal. This means that + `\beta` and `\gamma` represent the same coset of `H` in `G`. Described + on Pg. 156 [1]. ``rep`` + + See Also + ======== + + scan + + """ + A_dict = self.A_dict + A_dict_inv = self.A_dict_inv + table = self.table + # behaves as a queue + q = [] + if modified: + self.modified_merge(alpha, beta, w, q) + else: + self.merge(alpha, beta, q) + while len(q) > 0: + gamma = q.pop(0) + for x in A_dict: + delta = table[gamma][A_dict[x]] + if delta is not None: + table[delta][A_dict_inv[x]] = None + mu = self.rep(gamma, modified=modified) + nu = self.rep(delta, modified=modified) + if table[mu][A_dict[x]] is not None: + if modified: + v = self.p_p[delta]**-1*self.P[gamma][self.A_dict[x]]**-1 + v = v*self.p_p[gamma]*self.P[mu][self.A_dict[x]] + self.modified_merge(nu, table[mu][self.A_dict[x]], v, q) + else: + self.merge(nu, table[mu][A_dict[x]], q) + elif table[nu][A_dict_inv[x]] is not None: + if modified: + v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]] + v = v*self.p_p[delta]*self.P[mu][self.A_dict_inv[x]] + self.modified_merge(mu, table[nu][self.A_dict_inv[x]], v, q) + else: + self.merge(mu, table[nu][A_dict_inv[x]], q) + else: + table[mu][A_dict[x]] = nu + table[nu][A_dict_inv[x]] = mu + if modified: + v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]]*self.p_p[delta] + self.P[mu][self.A_dict[x]] = v + self.P[nu][self.A_dict_inv[x]] = v**-1 + + # method used in the HLT strategy + def scan_and_fill(self, alpha, word): + """ + A modified version of ``scan`` routine used in the relator-based + method of coset enumeration, described on pg. 162-163 [1], which + follows the idea that whenever the procedure is called and the scan + is incomplete then it makes new definitions to enable the scan to + complete; i.e it fills in the gaps in the scan of the relator or + subgroup generator. + + """ + self.scan(alpha, word, fill=True) + + def scan_and_fill_c(self, alpha, word): + """ + A modified version of ``scan`` routine, described on Pg. 165 second + para. [1], with modification similar to that of ``scan_anf_fill`` the + only difference being it calls the coincidence procedure used in the + coset-table based method i.e. the routine ``coincidence_c`` is used. + + See Also + ======== + + scan, scan_and_fill + + """ + A_dict = self.A_dict + A_dict_inv = self.A_dict_inv + table = self.table + r = len(word) + f = alpha + i = 0 + b = alpha + j = r - 1 + # loop until it has filled the alpha row in the table. + while True: + # do the forward scanning + while i <= j and table[f][A_dict[word[i]]] is not None: + f = table[f][A_dict[word[i]]] + i += 1 + if i > j: + if f != b: + self.coincidence_c(f, b) + return + # forward scan was incomplete, scan backwards + while j >= i and table[b][A_dict_inv[word[j]]] is not None: + b = table[b][A_dict_inv[word[j]]] + j -= 1 + if j < i: + self.coincidence_c(f, b) + elif j == i: + table[f][A_dict[word[i]]] = b + table[b][A_dict_inv[word[i]]] = f + self.deduction_stack.append((f, word[i])) + else: + self.define_c(f, word[i]) + + # method used in the HLT strategy + def look_ahead(self): + """ + When combined with the HLT method this is known as HLT+Lookahead + method of coset enumeration, described on pg. 164 [1]. Whenever + ``define`` aborts due to lack of space available this procedure is + executed. This routine helps in recovering space resulting from + "coincidence" of cosets. + + """ + R = self.fp_group.relators + p = self.p + # complete scan all relators under all cosets(obviously live) + # without making new definitions + for beta in self.omega: + for w in R: + self.scan(beta, w) + if p[beta] < beta: + break + + # Pg. 166 + def process_deductions(self, R_c_x, R_c_x_inv): + """ + Processes the deductions that have been pushed onto ``deduction_stack``, + described on Pg. 166 [1] and is used in coset-table based enumeration. + + See Also + ======== + + deduction_stack + + """ + p = self.p + table = self.table + while len(self.deduction_stack) > 0: + if len(self.deduction_stack) >= CosetTable.max_stack_size: + self.look_ahead() + del self.deduction_stack[:] + continue + else: + alpha, x = self.deduction_stack.pop() + if p[alpha] == alpha: + for w in R_c_x: + self.scan_c(alpha, w) + if p[alpha] < alpha: + break + beta = table[alpha][self.A_dict[x]] + if beta is not None and p[beta] == beta: + for w in R_c_x_inv: + self.scan_c(beta, w) + if p[beta] < beta: + break + + def process_deductions_check(self, R_c_x, R_c_x_inv): + """ + A variation of ``process_deductions``, this calls ``scan_check`` + wherever ``process_deductions`` calls ``scan``, described on Pg. [1]. + + See Also + ======== + + process_deductions + + """ + table = self.table + while len(self.deduction_stack) > 0: + alpha, x = self.deduction_stack.pop() + if not all(self.scan_check(alpha, w) for w in R_c_x): + return False + beta = table[alpha][self.A_dict[x]] + if beta is not None: + if not all(self.scan_check(beta, w) for w in R_c_x_inv): + return False + return True + + def switch(self, beta, gamma): + r"""Switch the elements `\beta, \gamma \in \Omega` of ``self``, used + by the ``standardize`` procedure, described on Pg. 167 [1]. + + See Also + ======== + + standardize + + """ + A = self.A + A_dict = self.A_dict + table = self.table + for x in A: + z = table[gamma][A_dict[x]] + table[gamma][A_dict[x]] = table[beta][A_dict[x]] + table[beta][A_dict[x]] = z + for alpha in range(len(self.p)): + if self.p[alpha] == alpha: + if table[alpha][A_dict[x]] == beta: + table[alpha][A_dict[x]] = gamma + elif table[alpha][A_dict[x]] == gamma: + table[alpha][A_dict[x]] = beta + + def standardize(self): + r""" + A coset table is standardized if when running through the cosets and + within each coset through the generator images (ignoring generator + inverses), the cosets appear in order of the integers + `0, 1, \dots, n`. "Standardize" reorders the elements of `\Omega` + such that, if we scan the coset table first by elements of `\Omega` + and then by elements of A, then the cosets occur in ascending order. + ``standardize()`` is used at the end of an enumeration to permute the + cosets so that they occur in some sort of standard order. + + Notes + ===== + + procedure is described on pg. 167-168 [1], it also makes use of the + ``switch`` routine to replace by smaller integer value. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r + >>> F, x, y = free_group("x, y") + + # Example 5.3 from [1] + >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) + >>> C = coset_enumeration_r(f, []) + >>> C.compress() + >>> C.table + [[1, 3, 1, 3], [2, 0, 2, 0], [3, 1, 3, 1], [0, 2, 0, 2]] + >>> C.standardize() + >>> C.table + [[1, 2, 1, 2], [3, 0, 3, 0], [0, 3, 0, 3], [2, 1, 2, 1]] + + """ + A = self.A + A_dict = self.A_dict + gamma = 1 + for alpha, x in product(range(self.n), A): + beta = self.table[alpha][A_dict[x]] + if beta >= gamma: + if beta > gamma: + self.switch(gamma, beta) + gamma += 1 + if gamma == self.n: + return + + # Compression of a Coset Table + def compress(self): + """Removes the non-live cosets from the coset table, described on + pg. 167 [1]. + + """ + gamma = -1 + A = self.A + A_dict = self.A_dict + A_dict_inv = self.A_dict_inv + table = self.table + chi = tuple([i for i in range(len(self.p)) if self.p[i] != i]) + for alpha in self.omega: + gamma += 1 + if gamma != alpha: + # replace alpha by gamma in coset table + for x in A: + beta = table[alpha][A_dict[x]] + table[gamma][A_dict[x]] = beta + # XXX: The line below uses == rather than = which means + # that it has no effect. It is not clear though if it is + # correct simply to delete the line or to change it to + # use =. Changing it causes some tests to fail. + # + # https://github.com/sympy/sympy/issues/27633 + table[beta][A_dict_inv[x]] == gamma # noqa: B015 + # all the cosets in the table are live cosets + self.p = list(range(gamma + 1)) + # delete the useless columns + del table[len(self.p):] + # re-define values + for row in table: + for j in range(len(self.A)): + row[j] -= bisect_left(chi, row[j]) + + def conjugates(self, R): + R_c = list(chain.from_iterable((rel.cyclic_conjugates(), \ + (rel**-1).cyclic_conjugates()) for rel in R)) + R_set = set() + for conjugate in R_c: + R_set = R_set.union(conjugate) + R_c_list = [] + for x in self.A: + r = {word for word in R_set if word[0] == x} + R_c_list.append(r) + R_set.difference_update(r) + return R_c_list + + def coset_representative(self, coset): + ''' + Compute the coset representative of a given coset. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) + >>> C = coset_enumeration_r(f, [x]) + >>> C.compress() + >>> C.table + [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] + >>> C.coset_representative(0) + + >>> C.coset_representative(1) + y + >>> C.coset_representative(2) + y**-1 + + ''' + for x in self.A: + gamma = self.table[coset][self.A_dict[x]] + if coset == 0: + return self.fp_group.identity + if gamma < coset: + return self.coset_representative(gamma)*x**-1 + + ############################## + # Modified Methods # + ############################## + + def modified_define(self, alpha, x): + r""" + Define a function p_p from from [1..n] to A* as + an additional component of the modified coset table. + + Parameters + ========== + + \alpha \in \Omega + x \in A* + + See Also + ======== + + define + + """ + self.define(alpha, x, modified=True) + + def modified_scan(self, alpha, w, y, fill=False): + r""" + Parameters + ========== + \alpha \in \Omega + w \in A* + y \in (YUY^-1) + fill -- `modified_scan_and_fill` when set to True. + + See Also + ======== + + scan + """ + self.scan(alpha, w, y=y, fill=fill, modified=True) + + def modified_scan_and_fill(self, alpha, w, y): + self.modified_scan(alpha, w, y, fill=True) + + def modified_merge(self, k, lamda, w, q): + r""" + Parameters + ========== + + 'k', 'lamda' -- the two class representatives to be merged. + q -- queue of length l of elements to be deleted from `\Omega` *. + w -- Word in (YUY^-1) + + See Also + ======== + + merge + """ + self.merge(k, lamda, q, w=w, modified=True) + + def modified_rep(self, k): + r""" + Parameters + ========== + + `k \in [0 \ldots n-1]` + + See Also + ======== + + rep + """ + self.rep(k, modified=True) + + def modified_coincidence(self, alpha, beta, w): + r""" + Parameters + ========== + + A coincident pair `\alpha, \beta \in \Omega, w \in Y \cup Y^{-1}` + + See Also + ======== + + coincidence + + """ + self.coincidence(alpha, beta, w=w, modified=True) + +############################################################################### +# COSET ENUMERATION # +############################################################################### + +# relator-based method +def coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, + incomplete=False, modified=False): + """ + This is easier of the two implemented methods of coset enumeration. + and is often called the HLT method, after Hazelgrove, Leech, Trotter + The idea is that we make use of ``scan_and_fill`` makes new definitions + whenever the scan is incomplete to enable the scan to complete; this way + we fill in the gaps in the scan of the relator or subgroup generator, + that's why the name relator-based method. + + An instance of `CosetTable` for `fp_grp` can be passed as the keyword + argument `draft` in which case the coset enumeration will start with + that instance and attempt to complete it. + + When `incomplete` is `True` and the function is unable to complete for + some reason, the partially complete table will be returned. + + # TODO: complete the docstring + + See Also + ======== + + scan_and_fill, + + Examples + ======== + + >>> from sympy.combinatorics.free_groups import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r + >>> F, x, y = free_group("x, y") + + # Example 5.1 from [1] + >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) + >>> C = coset_enumeration_r(f, [x]) + >>> for i in range(len(C.p)): + ... if C.p[i] == i: + ... print(C.table[i]) + [0, 0, 1, 2] + [1, 1, 2, 0] + [2, 2, 0, 1] + >>> C.p + [0, 1, 2, 1, 1] + + # Example from exercises Q2 [1] + >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) + >>> C = coset_enumeration_r(f, []) + >>> C.compress(); C.standardize() + >>> C.table + [[1, 2, 3, 4], + [5, 0, 6, 7], + [0, 5, 7, 6], + [7, 6, 5, 0], + [6, 7, 0, 5], + [2, 1, 4, 3], + [3, 4, 2, 1], + [4, 3, 1, 2]] + + # Example 5.2 + >>> f = FpGroup(F, [x**2, y**3, (x*y)**3]) + >>> Y = [x*y] + >>> C = coset_enumeration_r(f, Y) + >>> for i in range(len(C.p)): + ... if C.p[i] == i: + ... print(C.table[i]) + [1, 1, 2, 1] + [0, 0, 0, 2] + [3, 3, 1, 0] + [2, 2, 3, 3] + + # Example 5.3 + >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) + >>> Y = [] + >>> C = coset_enumeration_r(f, Y) + >>> for i in range(len(C.p)): + ... if C.p[i] == i: + ... print(C.table[i]) + [1, 3, 1, 3] + [2, 0, 2, 0] + [3, 1, 3, 1] + [0, 2, 0, 2] + + # Example 5.4 + >>> F, a, b, c, d, e = free_group("a, b, c, d, e") + >>> f = FpGroup(F, [a*b*c**-1, b*c*d**-1, c*d*e**-1, d*e*a**-1, e*a*b**-1]) + >>> Y = [a] + >>> C = coset_enumeration_r(f, Y) + >>> for i in range(len(C.p)): + ... if C.p[i] == i: + ... print(C.table[i]) + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + # example of "compress" method + >>> C.compress() + >>> C.table + [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] + + # Exercises Pg. 161, Q2. + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) + >>> Y = [] + >>> C = coset_enumeration_r(f, Y) + >>> C.compress() + >>> C.standardize() + >>> C.table + [[1, 2, 3, 4], + [5, 0, 6, 7], + [0, 5, 7, 6], + [7, 6, 5, 0], + [6, 7, 0, 5], + [2, 1, 4, 3], + [3, 4, 2, 1], + [4, 3, 1, 2]] + + # John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson + # Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490 + # from 1973chwd.pdf + # Table 1. Ex. 1 + >>> F, r, s, t = free_group("r, s, t") + >>> E1 = FpGroup(F, [t**-1*r*t*r**-2, r**-1*s*r*s**-2, s**-1*t*s*t**-2]) + >>> C = coset_enumeration_r(E1, [r]) + >>> for i in range(len(C.p)): + ... if C.p[i] == i: + ... print(C.table[i]) + [0, 0, 0, 0, 0, 0] + + Ex. 2 + >>> F, a, b = free_group("a, b") + >>> Cox = FpGroup(F, [a**6, b**6, (a*b)**2, (a**2*b**2)**2, (a**3*b**3)**5]) + >>> C = coset_enumeration_r(Cox, [a]) + >>> index = 0 + >>> for i in range(len(C.p)): + ... if C.p[i] == i: + ... index += 1 + >>> index + 500 + + # Ex. 3 + >>> F, a, b = free_group("a, b") + >>> B_2_4 = FpGroup(F, [a**4, b**4, (a*b)**4, (a**-1*b)**4, (a**2*b)**4, \ + (a*b**2)**4, (a**2*b**2)**4, (a**-1*b*a*b)**4, (a*b**-1*a*b)**4]) + >>> C = coset_enumeration_r(B_2_4, [a]) + >>> index = 0 + >>> for i in range(len(C.p)): + ... if C.p[i] == i: + ... index += 1 + >>> index + 1024 + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of computational group theory" + + """ + # 1. Initialize a coset table C for < X|R > + C = CosetTable(fp_grp, Y, max_cosets=max_cosets) + # Define coset table methods. + if modified: + _scan_and_fill = C.modified_scan_and_fill + _define = C.modified_define + else: + _scan_and_fill = C.scan_and_fill + _define = C.define + if draft: + C.table = draft.table[:] + C.p = draft.p[:] + R = fp_grp.relators + A_dict = C.A_dict + p = C.p + for i in range(len(Y)): + if modified: + _scan_and_fill(0, Y[i], C._grp.generators[i]) + else: + _scan_and_fill(0, Y[i]) + alpha = 0 + while alpha < C.n: + if p[alpha] == alpha: + try: + for w in R: + if modified: + _scan_and_fill(alpha, w, C._grp.identity) + else: + _scan_and_fill(alpha, w) + # if alpha was eliminated during the scan then break + if p[alpha] < alpha: + break + if p[alpha] == alpha: + for x in A_dict: + if C.table[alpha][A_dict[x]] is None: + _define(alpha, x) + except ValueError as e: + if incomplete: + return C + raise e + alpha += 1 + return C + +def modified_coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, + incomplete=False): + r""" + Introduce a new set of symbols y \in Y that correspond to the + generators of the subgroup. Store the elements of Y as a + word P[\alpha, x] and compute the coset table similar to that of + the regular coset enumeration methods. + + Examples + ======== + + >>> from sympy.combinatorics.free_groups import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup + >>> from sympy.combinatorics.coset_table import modified_coset_enumeration_r + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) + >>> C = modified_coset_enumeration_r(f, [x]) + >>> C.table + [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1], [None, 1, None, None], [1, 3, None, None]] + + See Also + ======== + + coset_enumertation_r + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E., + "Handbook of Computational Group Theory", + Section 5.3.2 + """ + return coset_enumeration_r(fp_grp, Y, max_cosets=max_cosets, draft=draft, + incomplete=incomplete, modified=True) + +# Pg. 166 +# coset-table based method +def coset_enumeration_c(fp_grp, Y, max_cosets=None, draft=None, + incomplete=False): + """ + >>> from sympy.combinatorics.free_groups import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) + >>> C = coset_enumeration_c(f, [x]) + >>> C.table + [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] + + """ + # Initialize a coset table C for < X|R > + X = fp_grp.generators + R = fp_grp.relators + C = CosetTable(fp_grp, Y, max_cosets=max_cosets) + if draft: + C.table = draft.table[:] + C.p = draft.p[:] + C.deduction_stack = draft.deduction_stack + for alpha, x in product(range(len(C.table)), X): + if C.table[alpha][C.A_dict[x]] is not None: + C.deduction_stack.append((alpha, x)) + A = C.A + # replace all the elements by cyclic reductions + R_cyc_red = [rel.identity_cyclic_reduction() for rel in R] + R_c = list(chain.from_iterable((rel.cyclic_conjugates(), (rel**-1).cyclic_conjugates()) \ + for rel in R_cyc_red)) + R_set = set() + for conjugate in R_c: + R_set = R_set.union(conjugate) + # a list of subsets of R_c whose words start with "x". + R_c_list = [] + for x in C.A: + r = {word for word in R_set if word[0] == x} + R_c_list.append(r) + R_set.difference_update(r) + for w in Y: + C.scan_and_fill_c(0, w) + for x in A: + C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) + alpha = 0 + while alpha < len(C.table): + if C.p[alpha] == alpha: + try: + for x in C.A: + if C.p[alpha] != alpha: + break + if C.table[alpha][C.A_dict[x]] is None: + C.define_c(alpha, x) + C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) + except ValueError as e: + if incomplete: + return C + raise e + alpha += 1 + return C diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..95530ccd44f025eca5f029c6ba60d3727cbcb29d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.py @@ -0,0 +1,1352 @@ +"""Finitely Presented Groups and its algorithms. """ + +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.combinatorics.free_groups import (FreeGroup, FreeGroupElement, + free_group) +from sympy.combinatorics.rewritingsystem import RewritingSystem +from sympy.combinatorics.coset_table import (CosetTable, + coset_enumeration_r, + coset_enumeration_c) +from sympy.combinatorics import PermutationGroup +from sympy.matrices.normalforms import invariant_factors +from sympy.matrices import Matrix +from sympy.polys.polytools import gcd +from sympy.printing.defaults import DefaultPrinting +from sympy.utilities import public +from sympy.utilities.magic import pollute + +from itertools import product + + +@public +def fp_group(fr_grp, relators=()): + _fp_group = FpGroup(fr_grp, relators) + return (_fp_group,) + tuple(_fp_group._generators) + +@public +def xfp_group(fr_grp, relators=()): + _fp_group = FpGroup(fr_grp, relators) + return (_fp_group, _fp_group._generators) + +# Does not work. Both symbols and pollute are undefined. Never tested. +@public +def vfp_group(fr_grpm, relators): + _fp_group = FpGroup(symbols, relators) + pollute([sym.name for sym in _fp_group.symbols], _fp_group.generators) + return _fp_group + + +def _parse_relators(rels): + """Parse the passed relators.""" + return rels + + +############################################################################### +# FINITELY PRESENTED GROUPS # +############################################################################### + + +class FpGroup(DefaultPrinting): + """ + The FpGroup would take a FreeGroup and a list/tuple of relators, the + relators would be specified in such a way that each of them be equal to the + identity of the provided free group. + + """ + is_group = True + is_FpGroup = True + is_PermutationGroup = False + + def __init__(self, fr_grp, relators): + relators = _parse_relators(relators) + self.free_group = fr_grp + self.relators = relators + self.generators = self._generators() + self.dtype = type("FpGroupElement", (FpGroupElement,), {"group": self}) + + # CosetTable instance on identity subgroup + self._coset_table = None + # returns whether coset table on identity subgroup + # has been standardized + self._is_standardized = False + + self._order = None + self._center = None + + self._rewriting_system = RewritingSystem(self) + self._perm_isomorphism = None + return + + def _generators(self): + return self.free_group.generators + + def make_confluent(self): + ''' + Try to make the group's rewriting system confluent + + ''' + self._rewriting_system.make_confluent() + return + + def reduce(self, word): + ''' + Return the reduced form of `word` in `self` according to the group's + rewriting system. If it's confluent, the reduced form is the unique normal + form of the word in the group. + + ''' + return self._rewriting_system.reduce(word) + + def equals(self, word1, word2): + ''' + Compare `word1` and `word2` for equality in the group + using the group's rewriting system. If the system is + confluent, the returned answer is necessarily correct. + (If it is not, `False` could be returned in some cases + where in fact `word1 == word2`) + + ''' + if self.reduce(word1*word2**-1) == self.identity: + return True + elif self._rewriting_system.is_confluent: + return False + return None + + @property + def identity(self): + return self.free_group.identity + + def __contains__(self, g): + return g in self.free_group + + def subgroup(self, gens, C=None, homomorphism=False): + ''' + Return the subgroup generated by `gens` using the + Reidemeister-Schreier algorithm + homomorphism -- When set to True, return a dictionary containing the images + of the presentation generators in the original group. + + Examples + ======== + + >>> from sympy.combinatorics.fp_groups import FpGroup + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) + >>> H = [x*y, x**-1*y**-1*x*y*x] + >>> K, T = f.subgroup(H, homomorphism=True) + >>> T(K.generators) + [x*y, x**-1*y**2*x**-1] + + ''' + + if not all(isinstance(g, FreeGroupElement) for g in gens): + raise ValueError("Generators must be `FreeGroupElement`s") + if not all(g.group == self.free_group for g in gens): + raise ValueError("Given generators are not members of the group") + if homomorphism: + g, rels, _gens = reidemeister_presentation(self, gens, C=C, homomorphism=True) + else: + g, rels = reidemeister_presentation(self, gens, C=C) + if g: + g = FpGroup(g[0].group, rels) + else: + g = FpGroup(free_group('')[0], []) + if homomorphism: + from sympy.combinatorics.homomorphisms import homomorphism + return g, homomorphism(g, self, g.generators, _gens, check=False) + return g + + def coset_enumeration(self, H, strategy="relator_based", max_cosets=None, + draft=None, incomplete=False): + """ + Return an instance of ``coset table``, when Todd-Coxeter algorithm is + run over the ``self`` with ``H`` as subgroup, using ``strategy`` + argument as strategy. The returned coset table is compressed but not + standardized. + + An instance of `CosetTable` for `fp_grp` can be passed as the keyword + argument `draft` in which case the coset enumeration will start with + that instance and attempt to complete it. + + When `incomplete` is `True` and the function is unable to complete for + some reason, the partially complete table will be returned. + + """ + if not max_cosets: + max_cosets = CosetTable.coset_table_max_limit + if strategy == 'relator_based': + C = coset_enumeration_r(self, H, max_cosets=max_cosets, + draft=draft, incomplete=incomplete) + else: + C = coset_enumeration_c(self, H, max_cosets=max_cosets, + draft=draft, incomplete=incomplete) + if C.is_complete(): + C.compress() + return C + + def standardize_coset_table(self): + """ + Standardized the coset table ``self`` and makes the internal variable + ``_is_standardized`` equal to ``True``. + + """ + self._coset_table.standardize() + self._is_standardized = True + + def coset_table(self, H, strategy="relator_based", max_cosets=None, + draft=None, incomplete=False): + """ + Return the mathematical coset table of ``self`` in ``H``. + + """ + if not H: + if self._coset_table is not None: + if not self._is_standardized: + self.standardize_coset_table() + else: + C = self.coset_enumeration([], strategy, max_cosets=max_cosets, + draft=draft, incomplete=incomplete) + self._coset_table = C + self.standardize_coset_table() + return self._coset_table.table + else: + C = self.coset_enumeration(H, strategy, max_cosets=max_cosets, + draft=draft, incomplete=incomplete) + C.standardize() + return C.table + + def order(self, strategy="relator_based"): + """ + Returns the order of the finitely presented group ``self``. It uses + the coset enumeration with identity group as subgroup, i.e ``H=[]``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x, y**2]) + >>> f.order(strategy="coset_table_based") + 2 + + """ + if self._order is not None: + return self._order + if self._coset_table is not None: + self._order = len(self._coset_table.table) + elif len(self.relators) == 0: + self._order = self.free_group.order() + elif len(self.generators) == 1: + self._order = abs(gcd([r.array_form[0][1] for r in self.relators])) + elif self._is_infinite(): + self._order = S.Infinity + else: + gens, C = self._finite_index_subgroup() + if C: + ind = len(C.table) + self._order = ind*self.subgroup(gens, C=C).order() + else: + self._order = self.index([]) + return self._order + + def _is_infinite(self): + ''' + Test if the group is infinite. Return `True` if the test succeeds + and `None` otherwise + + ''' + used_gens = set() + for r in self.relators: + used_gens.update(r.contains_generators()) + if not set(self.generators) <= used_gens: + return True + # Abelianisation test: check is the abelianisation is infinite + abelian_rels = [] + for rel in self.relators: + abelian_rels.append([rel.exponent_sum(g) for g in self.generators]) + m = Matrix(Matrix(abelian_rels)) + if 0 in invariant_factors(m): + return True + else: + return None + + + def _finite_index_subgroup(self, s=None): + ''' + Find the elements of `self` that generate a finite index subgroup + and, if found, return the list of elements and the coset table of `self` by + the subgroup, otherwise return `(None, None)` + + ''' + gen = self.most_frequent_generator() + rels = list(self.generators) + rels.extend(self.relators) + if not s: + if len(self.generators) == 2: + s = [gen] + [g for g in self.generators if g != gen] + else: + rand = self.free_group.identity + i = 0 + while ((rand in rels or rand**-1 in rels or rand.is_identity) + and i<10): + rand = self.random() + i += 1 + s = [gen, rand] + [g for g in self.generators if g != gen] + mid = (len(s)+1)//2 + half1 = s[:mid] + half2 = s[mid:] + draft1 = None + draft2 = None + m = 200 + C = None + while not C and (m/2 < CosetTable.coset_table_max_limit): + m = min(m, CosetTable.coset_table_max_limit) + draft1 = self.coset_enumeration(half1, max_cosets=m, + draft=draft1, incomplete=True) + if draft1.is_complete(): + C = draft1 + half = half1 + else: + draft2 = self.coset_enumeration(half2, max_cosets=m, + draft=draft2, incomplete=True) + if draft2.is_complete(): + C = draft2 + half = half2 + if not C: + m *= 2 + if not C: + return None, None + C.compress() + return half, C + + def most_frequent_generator(self): + gens = self.generators + rels = self.relators + freqs = [sum(r.generator_count(g) for r in rels) for g in gens] + return gens[freqs.index(max(freqs))] + + def random(self): + import random + r = self.free_group.identity + for i in range(random.randint(2,3)): + r = r*random.choice(self.generators)**random.choice([1,-1]) + return r + + def index(self, H, strategy="relator_based"): + """ + Return the index of subgroup ``H`` in group ``self``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**5, y**4, y*x*y**3*x**3]) + >>> f.index([x]) + 4 + + """ + # TODO: use |G:H| = |G|/|H| (currently H can't be made into a group) + # when we know |G| and |H| + + if H == []: + return self.order() + else: + C = self.coset_enumeration(H, strategy) + return len(C.table) + + def __str__(self): + if self.free_group.rank > 30: + str_form = "" % self.free_group.rank + else: + str_form = "" % str(self.generators) + return str_form + + __repr__ = __str__ + +#============================================================================== +# PERMUTATION GROUP METHODS +#============================================================================== + + def _to_perm_group(self): + ''' + Return an isomorphic permutation group and the isomorphism. + The implementation is dependent on coset enumeration so + will only terminate for finite groups. + + ''' + from sympy.combinatorics import Permutation + from sympy.combinatorics.homomorphisms import homomorphism + if self.order() is S.Infinity: + raise NotImplementedError("Permutation presentation of infinite " + "groups is not implemented") + if self._perm_isomorphism: + T = self._perm_isomorphism + P = T.image() + else: + C = self.coset_table([]) + gens = self.generators + images = [[C[i][2*gens.index(g)] for i in range(len(C))] for g in gens] + images = [Permutation(i) for i in images] + P = PermutationGroup(images) + T = homomorphism(self, P, gens, images, check=False) + self._perm_isomorphism = T + return P, T + + def _perm_group_list(self, method_name, *args): + ''' + Given the name of a `PermutationGroup` method (returning a subgroup + or a list of subgroups) and (optionally) additional arguments it takes, + return a list or a list of lists containing the generators of this (or + these) subgroups in terms of the generators of `self`. + + ''' + P, T = self._to_perm_group() + perm_result = getattr(P, method_name)(*args) + single = False + if isinstance(perm_result, PermutationGroup): + perm_result, single = [perm_result], True + result = [] + for group in perm_result: + gens = group.generators + result.append(T.invert(gens)) + return result[0] if single else result + + def derived_series(self): + ''' + Return the list of lists containing the generators + of the subgroups in the derived series of `self`. + + ''' + return self._perm_group_list('derived_series') + + def lower_central_series(self): + ''' + Return the list of lists containing the generators + of the subgroups in the lower central series of `self`. + + ''' + return self._perm_group_list('lower_central_series') + + def center(self): + ''' + Return the list of generators of the center of `self`. + + ''' + return self._perm_group_list('center') + + + def derived_subgroup(self): + ''' + Return the list of generators of the derived subgroup of `self`. + + ''' + return self._perm_group_list('derived_subgroup') + + + def centralizer(self, other): + ''' + Return the list of generators of the centralizer of `other` + (a list of elements of `self`) in `self`. + + ''' + T = self._to_perm_group()[1] + other = T(other) + return self._perm_group_list('centralizer', other) + + def normal_closure(self, other): + ''' + Return the list of generators of the normal closure of `other` + (a list of elements of `self`) in `self`. + + ''' + T = self._to_perm_group()[1] + other = T(other) + return self._perm_group_list('normal_closure', other) + + def _perm_property(self, attr): + ''' + Given an attribute of a `PermutationGroup`, return + its value for a permutation group isomorphic to `self`. + + ''' + P = self._to_perm_group()[0] + return getattr(P, attr) + + @property + def is_abelian(self): + ''' + Check if `self` is abelian. + + ''' + return self._perm_property("is_abelian") + + @property + def is_nilpotent(self): + ''' + Check if `self` is nilpotent. + + ''' + return self._perm_property("is_nilpotent") + + @property + def is_solvable(self): + ''' + Check if `self` is solvable. + + ''' + return self._perm_property("is_solvable") + + @property + def elements(self): + ''' + List the elements of `self`. + + ''' + P, T = self._to_perm_group() + return T.invert(P.elements) + + @property + def is_cyclic(self): + """ + Return ``True`` if group is Cyclic. + + """ + if len(self.generators) <= 1: + return True + try: + P, T = self._to_perm_group() + except NotImplementedError: + raise NotImplementedError("Check for infinite Cyclic group " + "is not implemented") + return P.is_cyclic + + def abelian_invariants(self): + """ + Return Abelian Invariants of a group. + """ + try: + P, T = self._to_perm_group() + except NotImplementedError: + raise NotImplementedError("abelian invariants is not implemented" + "for infinite group") + return P.abelian_invariants() + + def composition_series(self): + """ + Return subnormal series of maximum length for a group. + """ + try: + P, T = self._to_perm_group() + except NotImplementedError: + raise NotImplementedError("composition series is not implemented" + "for infinite group") + return P.composition_series() + + +class FpSubgroup(DefaultPrinting): + ''' + The class implementing a subgroup of an FpGroup or a FreeGroup + (only finite index subgroups are supported at this point). This + is to be used if one wishes to check if an element of the original + group belongs to the subgroup + + ''' + def __init__(self, G, gens, normal=False): + super().__init__() + self.parent = G + self.generators = list({g for g in gens if g != G.identity}) + self._min_words = None #for use in __contains__ + self.C = None + self.normal = normal + + def __contains__(self, g): + + if isinstance(self.parent, FreeGroup): + if self._min_words is None: + # make _min_words - a list of subwords such that + # g is in the subgroup if and only if it can be + # partitioned into these subwords. Infinite families of + # subwords are presented by tuples, e.g. (r, w) + # stands for the family of subwords r*w**n*r**-1 + + def _process(w): + # this is to be used before adding new words + # into _min_words; if the word w is not cyclically + # reduced, it will generate an infinite family of + # subwords so should be written as a tuple; + # if it is, w**-1 should be added to the list + # as well + p, r = w.cyclic_reduction(removed=True) + if not r.is_identity: + return [(r, p)] + else: + return [w, w**-1] + + # make the initial list + gens = [] + for w in self.generators: + if self.normal: + w = w.cyclic_reduction() + gens.extend(_process(w)) + + for w1 in gens: + for w2 in gens: + # if w1 and w2 are equal or are inverses, continue + if w1 == w2 or (not isinstance(w1, tuple) + and w1**-1 == w2): + continue + + # if the start of one word is the inverse of the + # end of the other, their multiple should be added + # to _min_words because of cancellation + if isinstance(w1, tuple): + # start, end + s1, s2 = w1[0][0], w1[0][0]**-1 + else: + s1, s2 = w1[0], w1[len(w1)-1] + + if isinstance(w2, tuple): + # start, end + r1, r2 = w2[0][0], w2[0][0]**-1 + else: + r1, r2 = w2[0], w2[len(w1)-1] + + # p1 and p2 are w1 and w2 or, in case when + # w1 or w2 is an infinite family, a representative + p1, p2 = w1, w2 + if isinstance(w1, tuple): + p1 = w1[0]*w1[1]*w1[0]**-1 + if isinstance(w2, tuple): + p2 = w2[0]*w2[1]*w2[0]**-1 + + # add the product of the words to the list is necessary + if r1**-1 == s2 and not (p1*p2).is_identity: + new = _process(p1*p2) + if new not in gens: + gens.extend(new) + + if r2**-1 == s1 and not (p2*p1).is_identity: + new = _process(p2*p1) + if new not in gens: + gens.extend(new) + + self._min_words = gens + + min_words = self._min_words + + def _is_subword(w): + # check if w is a word in _min_words or one of + # the infinite families in it + w, r = w.cyclic_reduction(removed=True) + if r.is_identity or self.normal: + return w in min_words + else: + t = [s[1] for s in min_words if isinstance(s, tuple) + and s[0] == r] + return [s for s in t if w.power_of(s)] != [] + + # store the solution of words for which the result of + # _word_break (below) is known + known = {} + + def _word_break(w): + # check if w can be written as a product of words + # in min_words + if len(w) == 0: + return True + i = 0 + while i < len(w): + i += 1 + prefix = w.subword(0, i) + if not _is_subword(prefix): + continue + rest = w.subword(i, len(w)) + if rest not in known: + known[rest] = _word_break(rest) + if known[rest]: + return True + return False + + if self.normal: + g = g.cyclic_reduction() + return _word_break(g) + else: + if self.C is None: + C = self.parent.coset_enumeration(self.generators) + self.C = C + i = 0 + C = self.C + for j in range(len(g)): + i = C.table[i][C.A_dict[g[j]]] + return i == 0 + + def order(self): + if not self.generators: + return S.One + if isinstance(self.parent, FreeGroup): + return S.Infinity + if self.C is None: + C = self.parent.coset_enumeration(self.generators) + self.C = C + # This is valid because `len(self.C.table)` (the index of the subgroup) + # will always be finite - otherwise coset enumeration doesn't terminate + return self.parent.order()/len(self.C.table) + + def to_FpGroup(self): + if isinstance(self.parent, FreeGroup): + gen_syms = [('x_%d'%i) for i in range(len(self.generators))] + return free_group(', '.join(gen_syms))[0] + return self.parent.subgroup(C=self.C) + + def __str__(self): + if len(self.generators) > 30: + str_form = "" % len(self.generators) + else: + str_form = "" % str(self.generators) + return str_form + + __repr__ = __str__ + + +############################################################################### +# LOW INDEX SUBGROUPS # +############################################################################### + +def low_index_subgroups(G, N, Y=()): + """ + Implements the Low Index Subgroups algorithm, i.e find all subgroups of + ``G`` upto a given index ``N``. This implements the method described in + [Sim94]. This procedure involves a backtrack search over incomplete Coset + Tables, rather than over forced coincidences. + + Parameters + ========== + + G: An FpGroup < X|R > + N: positive integer, representing the maximum index value for subgroups + Y: (an optional argument) specifying a list of subgroup generators, such + that each of the resulting subgroup contains the subgroup generated by Y. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, low_index_subgroups + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) + >>> L = low_index_subgroups(f, 4) + >>> for coset_table in L: + ... print(coset_table.table) + [[0, 0, 0, 0]] + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]] + [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]] + [[1, 1, 0, 0], [0, 0, 1, 1]] + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + Section 5.4 + + .. [2] Marston Conder and Peter Dobcsanyi + "Applications and Adaptions of the Low Index Subgroups Procedure" + + """ + C = CosetTable(G, []) + R = G.relators + # length chosen for the length of the short relators + len_short_rel = 5 + # elements of R2 only checked at the last step for complete + # coset tables + R2 = {rel for rel in R if len(rel) > len_short_rel} + # elements of R1 are used in inner parts of the process to prune + # branches of the search tree, + R1 = {rel.identity_cyclic_reduction() for rel in set(R) - R2} + R1_c_list = C.conjugates(R1) + S = [] + descendant_subgroups(S, C, R1_c_list, C.A[0], R2, N, Y) + return S + + +def descendant_subgroups(S, C, R1_c_list, x, R2, N, Y): + A_dict = C.A_dict + A_dict_inv = C.A_dict_inv + if C.is_complete(): + # if C is complete then it only needs to test + # whether the relators in R2 are satisfied + for w, alpha in product(R2, C.omega): + if not C.scan_check(alpha, w): + return + # relators in R2 are satisfied, append the table to list + S.append(C) + else: + # find the first undefined entry in Coset Table + for alpha, x in product(range(len(C.table)), C.A): + if C.table[alpha][A_dict[x]] is None: + # this is "x" in pseudo-code (using "y" makes it clear) + undefined_coset, undefined_gen = alpha, x + break + # for filling up the undefine entry we try all possible values + # of beta in Omega or beta = n where beta^(undefined_gen^-1) is undefined + reach = C.omega + [C.n] + for beta in reach: + if beta < N: + if beta == C.n or C.table[beta][A_dict_inv[undefined_gen]] is None: + try_descendant(S, C, R1_c_list, R2, N, undefined_coset, \ + undefined_gen, beta, Y) + + +def try_descendant(S, C, R1_c_list, R2, N, alpha, x, beta, Y): + r""" + Solves the problem of trying out each individual possibility + for `\alpha^x. + + """ + D = C.copy() + if beta == D.n and beta < N: + D.table.append([None]*len(D.A)) + D.p.append(beta) + D.table[alpha][D.A_dict[x]] = beta + D.table[beta][D.A_dict_inv[x]] = alpha + D.deduction_stack.append((alpha, x)) + if not D.process_deductions_check(R1_c_list[D.A_dict[x]], \ + R1_c_list[D.A_dict_inv[x]]): + return + for w in Y: + if not D.scan_check(0, w): + return + if first_in_class(D, Y): + descendant_subgroups(S, D, R1_c_list, x, R2, N, Y) + + +def first_in_class(C, Y=()): + """ + Checks whether the subgroup ``H=G1`` corresponding to the Coset Table + could possibly be the canonical representative of its conjugacy class. + + Parameters + ========== + + C: CosetTable + + Returns + ======= + + bool: True/False + + If this returns False, then no descendant of C can have that property, and + so we can abandon C. If it returns True, then we need to process further + the node of the search tree corresponding to C, and so we call + ``descendant_subgroups`` recursively on C. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, first_in_class + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) + >>> C = CosetTable(f, []) + >>> C.table = [[0, 0, None, None]] + >>> first_in_class(C) + True + >>> C.table = [[1, 1, 1, None], [0, 0, None, 1]]; C.p = [0, 1] + >>> first_in_class(C) + True + >>> C.table = [[1, 1, 2, 1], [0, 0, 0, None], [None, None, None, 0]] + >>> C.p = [0, 1, 2] + >>> first_in_class(C) + False + >>> C.table = [[1, 1, 1, 2], [0, 0, 2, 0], [2, None, 0, 1]] + >>> first_in_class(C) + False + + # TODO:: Sims points out in [Sim94] that performance can be improved by + # remembering some of the information computed by ``first_in_class``. If + # the ``continue alpha`` statement is executed at line 14, then the same thing + # will happen for that value of alpha in any descendant of the table C, and so + # the values the values of alpha for which this occurs could profitably be + # stored and passed through to the descendants of C. Of course this would + # make the code more complicated. + + # The code below is taken directly from the function on page 208 of [Sim94] + # nu[alpha] + + """ + n = C.n + # lamda is the largest numbered point in Omega_c_alpha which is currently defined + lamda = -1 + # for alpha in Omega_c, nu[alpha] is the point in Omega_c_alpha corresponding to alpha + nu = [None]*n + # for alpha in Omega_c_alpha, mu[alpha] is the point in Omega_c corresponding to alpha + mu = [None]*n + # mutually nu and mu are the mutually-inverse equivalence maps between + # Omega_c_alpha and Omega_c + next_alpha = False + # For each 0!=alpha in [0 .. nc-1], we start by constructing the equivalent + # standardized coset table C_alpha corresponding to H_alpha + for alpha in range(1, n): + # reset nu to "None" after previous value of alpha + for beta in range(lamda+1): + nu[mu[beta]] = None + # we only want to reject our current table in favour of a preceding + # table in the ordering in which 1 is replaced by alpha, if the subgroup + # G_alpha corresponding to this preceding table definitely contains the + # given subgroup + for w in Y: + # TODO: this should support input of a list of general words + # not just the words which are in "A" (i.e gen and gen^-1) + if C.table[alpha][C.A_dict[w]] != alpha: + # continue with alpha + next_alpha = True + break + if next_alpha: + next_alpha = False + continue + # try alpha as the new point 0 in Omega_C_alpha + mu[0] = alpha + nu[alpha] = 0 + # compare corresponding entries in C and C_alpha + lamda = 0 + for beta in range(n): + for x in C.A: + gamma = C.table[beta][C.A_dict[x]] + delta = C.table[mu[beta]][C.A_dict[x]] + # if either of the entries is undefined, + # we move with next alpha + if gamma is None or delta is None: + # continue with alpha + next_alpha = True + break + if nu[delta] is None: + # delta becomes the next point in Omega_C_alpha + lamda += 1 + nu[delta] = lamda + mu[lamda] = delta + if nu[delta] < gamma: + return False + if nu[delta] > gamma: + # continue with alpha + next_alpha = True + break + if next_alpha: + next_alpha = False + break + return True + +#======================================================================== +# Simplifying Presentation +#======================================================================== + +def simplify_presentation(*args, change_gens=False): + ''' + For an instance of `FpGroup`, return a simplified isomorphic copy of + the group (e.g. remove redundant generators or relators). Alternatively, + a list of generators and relators can be passed in which case the + simplified lists will be returned. + + By default, the generators of the group are unchanged. If you would + like to remove redundant generators, set the keyword argument + `change_gens = True`. + + ''' + if len(args) == 1: + if not isinstance(args[0], FpGroup): + raise TypeError("The argument must be an instance of FpGroup") + G = args[0] + gens, rels = simplify_presentation(G.generators, G.relators, + change_gens=change_gens) + if gens: + return FpGroup(gens[0].group, rels) + return FpGroup(FreeGroup([]), []) + elif len(args) == 2: + gens, rels = args[0][:], args[1][:] + if not gens: + return gens, rels + identity = gens[0].group.identity + else: + if len(args) == 0: + m = "Not enough arguments" + else: + m = "Too many arguments" + raise RuntimeError(m) + + prev_gens = [] + prev_rels = [] + while not set(prev_rels) == set(rels): + prev_rels = rels + while change_gens and not set(prev_gens) == set(gens): + prev_gens = gens + gens, rels = elimination_technique_1(gens, rels, identity) + rels = _simplify_relators(rels) + + if change_gens: + syms = [g.array_form[0][0] for g in gens] + F = free_group(syms)[0] + identity = F.identity + gens = F.generators + subs = dict(zip(syms, gens)) + for j, r in enumerate(rels): + a = r.array_form + rel = identity + for sym, p in a: + rel = rel*subs[sym]**p + rels[j] = rel + return gens, rels + +def _simplify_relators(rels): + """ + Simplifies a set of relators. All relators are checked to see if they are + of the form `gen^n`. If any such relators are found then all other relators + are processed for strings in the `gen` known order. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import _simplify_relators + >>> F, x, y = free_group("x, y") + >>> w1 = [x**2*y**4, x**3] + >>> _simplify_relators(w1) + [x**3, x**-1*y**4] + + >>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5] + >>> _simplify_relators(w2) + [x**-1*y**-2, x**-1*y*x**-1, x**3, y**5] + + >>> w3 = [x**6*y**4, x**4] + >>> _simplify_relators(w3) + [x**4, x**2*y**4] + + >>> w4 = [x**2, x**5, y**3] + >>> _simplify_relators(w4) + [x, y**3] + + """ + rels = rels[:] + + if not rels: + return [] + + identity = rels[0].group.identity + + # build dictionary with "gen: n" where gen^n is one of the relators + exps = {} + for i in range(len(rels)): + rel = rels[i] + if rel.number_syllables() == 1: + g = rel[0] + exp = abs(rel.array_form[0][1]) + if rel.array_form[0][1] < 0: + rels[i] = rels[i]**-1 + g = g**-1 + if g in exps: + exp = gcd(exp, exps[g].array_form[0][1]) + exps[g] = g**exp + + one_syllables_words = list(exps.values()) + # decrease some of the exponents in relators, making use of the single + # syllable relators + for i, rel in enumerate(rels): + if rel in one_syllables_words: + continue + rel = rel.eliminate_words(one_syllables_words, _all = True) + # if rels[i] contains g**n where abs(n) is greater than half of the power p + # of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0) + for g in rel.contains_generators(): + if g in exps: + exp = exps[g].array_form[0][1] + max_exp = (exp + 1)//2 + rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True) + rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True) + rels[i] = rel + + rels = [r.identity_cyclic_reduction() for r in rels] + + rels += one_syllables_words # include one_syllable_words in the list of relators + rels = list(set(rels)) # get unique values in rels + rels.sort() + + # remove entries in rels + try: + rels.remove(identity) + except ValueError: + pass + return rels + +# Pg 350, section 2.5.1 from [2] +def elimination_technique_1(gens, rels, identity): + rels = rels[:] + # the shorter relators are examined first so that generators selected for + # elimination will have shorter strings as equivalent + rels.sort() + gens = gens[:] + redundant_gens = {} + redundant_rels = [] + used_gens = set() + # examine each relator in relator list for any generator occurring exactly + # once + for rel in rels: + # don't look for a redundant generator in a relator which + # depends on previously found ones + contained_gens = rel.contains_generators() + if any(g in contained_gens for g in redundant_gens): + continue + contained_gens = list(contained_gens) + contained_gens.sort(reverse = True) + for gen in contained_gens: + if rel.generator_count(gen) == 1 and gen not in used_gens: + k = rel.exponent_sum(gen) + gen_index = rel.index(gen**k) + bk = rel.subword(gen_index + 1, len(rel)) + fw = rel.subword(0, gen_index) + chi = bk*fw + redundant_gens[gen] = chi**(-1*k) + used_gens.update(chi.contains_generators()) + redundant_rels.append(rel) + break + rels = [r for r in rels if r not in redundant_rels] + # eliminate the redundant generators from remaining relators + rels = [r.eliminate_words(redundant_gens, _all = True).identity_cyclic_reduction() for r in rels] + rels = list(set(rels)) + try: + rels.remove(identity) + except ValueError: + pass + gens = [g for g in gens if g not in redundant_gens] + return gens, rels + +############################################################################### +# SUBGROUP PRESENTATIONS # +############################################################################### + +# Pg 175 [1] +def define_schreier_generators(C, homomorphism=False): + ''' + Parameters + ========== + + C -- Coset table. + homomorphism -- When set to True, return a dictionary containing the images + of the presentation generators in the original group. + ''' + y = [] + gamma = 1 + f = C.fp_group + X = f.generators + if homomorphism: + # `_gens` stores the elements of the parent group to + # to which the schreier generators correspond to. + _gens = {} + # compute the schreier Traversal + tau = {} + tau[0] = f.identity + C.P = [[None]*len(C.A) for i in range(C.n)] + for alpha, x in product(C.omega, C.A): + beta = C.table[alpha][C.A_dict[x]] + if beta == gamma: + C.P[alpha][C.A_dict[x]] = "" + C.P[beta][C.A_dict_inv[x]] = "" + gamma += 1 + if homomorphism: + tau[beta] = tau[alpha]*x + elif x in X and C.P[alpha][C.A_dict[x]] is None: + y_alpha_x = '%s_%s' % (x, alpha) + y.append(y_alpha_x) + C.P[alpha][C.A_dict[x]] = y_alpha_x + if homomorphism: + _gens[y_alpha_x] = tau[alpha]*x*tau[beta]**-1 + grp_gens = list(free_group(', '.join(y))) + C._schreier_free_group = grp_gens.pop(0) + C._schreier_generators = grp_gens + if homomorphism: + C._schreier_gen_elem = _gens + # replace all elements of P by, free group elements + for i, j in product(range(len(C.P)), range(len(C.A))): + # if equals "", replace by identity element + if C.P[i][j] == "": + C.P[i][j] = C._schreier_free_group.identity + elif isinstance(C.P[i][j], str): + r = C._schreier_generators[y.index(C.P[i][j])] + C.P[i][j] = r + beta = C.table[i][j] + C.P[beta][j + 1] = r**-1 + +def reidemeister_relators(C): + R = C.fp_group.relators + rels = [rewrite(C, coset, word) for word in R for coset in range(C.n)] + order_1_gens = {i for i in rels if len(i) == 1} + + # remove all the order 1 generators from relators + rels = list(filter(lambda rel: rel not in order_1_gens, rels)) + + # replace order 1 generators by identity element in reidemeister relators + for i in range(len(rels)): + w = rels[i] + w = w.eliminate_words(order_1_gens, _all=True) + rels[i] = w + + C._schreier_generators = [i for i in C._schreier_generators + if not (i in order_1_gens or i**-1 in order_1_gens)] + + # Tietze transformation 1 i.e TT_1 + # remove cyclic conjugate elements from relators + i = 0 + while i < len(rels): + w = rels[i] + j = i + 1 + while j < len(rels): + if w.is_cyclic_conjugate(rels[j]): + del rels[j] + else: + j += 1 + i += 1 + + C._reidemeister_relators = rels + + +def rewrite(C, alpha, w): + """ + Parameters + ========== + + C: CosetTable + alpha: A live coset + w: A word in `A*` + + Returns + ======= + + rho(tau(alpha), w) + + Examples + ======== + + >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**2, y**3, (x*y)**6]) + >>> C = CosetTable(f, []) + >>> C.table = [[1, 1, 2, 3], [0, 0, 4, 5], [4, 4, 3, 0], [5, 5, 0, 2], [2, 2, 5, 1], [3, 3, 1, 4]] + >>> C.p = [0, 1, 2, 3, 4, 5] + >>> define_schreier_generators(C) + >>> rewrite(C, 0, (x*y)**6) + x_4*y_2*x_3*x_1*x_2*y_4*x_5 + + """ + v = C._schreier_free_group.identity + for i in range(len(w)): + x_i = w[i] + v = v*C.P[alpha][C.A_dict[x_i]] + alpha = C.table[alpha][C.A_dict[x_i]] + return v + +# Pg 350, section 2.5.2 from [2] +def elimination_technique_2(C): + """ + This technique eliminates one generator at a time. Heuristically this + seems superior in that we may select for elimination the generator with + shortest equivalent string at each stage. + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r, \ + reidemeister_relators, define_schreier_generators, elimination_technique_2 + >>> F, x, y = free_group("x, y") + >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]); H = [x*y, x**-1*y**-1*x*y*x] + >>> C = coset_enumeration_r(f, H) + >>> C.compress(); C.standardize() + >>> define_schreier_generators(C) + >>> reidemeister_relators(C) + >>> elimination_technique_2(C) + ([y_1, y_2], [y_2**-3, y_2*y_1*y_2*y_1*y_2*y_1, y_1**2]) + + """ + rels = C._reidemeister_relators + rels.sort(reverse=True) + gens = C._schreier_generators + for i in range(len(gens) - 1, -1, -1): + rel = rels[i] + for j in range(len(gens) - 1, -1, -1): + gen = gens[j] + if rel.generator_count(gen) == 1: + k = rel.exponent_sum(gen) + gen_index = rel.index(gen**k) + bk = rel.subword(gen_index + 1, len(rel)) + fw = rel.subword(0, gen_index) + rep_by = (bk*fw)**(-1*k) + del rels[i] + del gens[j] + rels = [rel.eliminate_word(gen, rep_by) for rel in rels] + break + C._reidemeister_relators = rels + C._schreier_generators = gens + return C._schreier_generators, C._reidemeister_relators + +def reidemeister_presentation(fp_grp, H, C=None, homomorphism=False): + """ + Parameters + ========== + + fp_group: A finitely presented group, an instance of FpGroup + H: A subgroup whose presentation is to be found, given as a list + of words in generators of `fp_grp` + homomorphism: When set to True, return a homomorphism from the subgroup + to the parent group + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> from sympy.combinatorics.fp_groups import FpGroup, reidemeister_presentation + >>> F, x, y = free_group("x, y") + + Example 5.6 Pg. 177 from [1] + >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) + >>> H = [x*y, x**-1*y**-1*x*y*x] + >>> reidemeister_presentation(f, H) + ((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1)) + + Example 5.8 Pg. 183 from [1] + >>> f = FpGroup(F, [x**3, y**3, (x*y)**3]) + >>> H = [x*y, x*y**-1] + >>> reidemeister_presentation(f, H) + ((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0)) + + Exercises Q2. Pg 187 from [1] + >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) + >>> H = [x] + >>> reidemeister_presentation(f, H) + ((x_0,), (x_0**4,)) + + Example 5.9 Pg. 183 from [1] + >>> f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2]) + >>> H = [x] + >>> reidemeister_presentation(f, H) + ((x_0,), (x_0**6,)) + + """ + if not C: + C = coset_enumeration_r(fp_grp, H) + C.compress(); C.standardize() + define_schreier_generators(C, homomorphism=homomorphism) + reidemeister_relators(C) + gens, rels = C._schreier_generators, C._reidemeister_relators + gens, rels = simplify_presentation(gens, rels, change_gens=True) + + C.schreier_generators = tuple(gens) + C.reidemeister_relators = tuple(rels) + + if homomorphism: + _gens = [C._schreier_gen_elem[str(gen)] for gen in gens] + return C.schreier_generators, C.reidemeister_relators, _gens + + return C.schreier_generators, C.reidemeister_relators + + +FpGroupElement = FreeGroupElement diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/free_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/free_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec85f4fac73fba95d4644a37ecb27140e45a4c5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/free_groups.py @@ -0,0 +1,1360 @@ +from __future__ import annotations + +from sympy.core import S +from sympy.core.expr import Expr +from sympy.core.symbol import Symbol, symbols as _symbols +from sympy.core.sympify import CantSympify +from sympy.printing.defaults import DefaultPrinting +from sympy.utilities import public +from sympy.utilities.iterables import flatten, is_sequence +from sympy.utilities.magic import pollute +from sympy.utilities.misc import as_int + + +@public +def free_group(symbols): + """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1))``. + + Parameters + ========== + + symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y, z = free_group("x, y, z") + >>> F + + >>> x**2*y**-1 + x**2*y**-1 + >>> type(_) + + + """ + _free_group = FreeGroup(symbols) + return (_free_group,) + tuple(_free_group.generators) + +@public +def xfree_group(symbols): + """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1)))``. + + Parameters + ========== + + symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) + + Examples + ======== + + >>> from sympy.combinatorics.free_groups import xfree_group + >>> F, (x, y, z) = xfree_group("x, y, z") + >>> F + + >>> y**2*x**-2*z**-1 + y**2*x**-2*z**-1 + >>> type(_) + + + """ + _free_group = FreeGroup(symbols) + return (_free_group, _free_group.generators) + +@public +def vfree_group(symbols): + """Construct a free group and inject ``f_0, f_1, ..., f_(n-1)`` as symbols + into the global namespace. + + Parameters + ========== + + symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) + + Examples + ======== + + >>> from sympy.combinatorics.free_groups import vfree_group + >>> vfree_group("x, y, z") + + >>> x**2*y**-2*z # noqa: F821 + x**2*y**-2*z + >>> type(_) + + + """ + _free_group = FreeGroup(symbols) + pollute([sym.name for sym in _free_group.symbols], _free_group.generators) + return _free_group + + +def _parse_symbols(symbols): + if not symbols: + return () + if isinstance(symbols, str): + return _symbols(symbols, seq=True) + elif isinstance(symbols, (Expr, FreeGroupElement)): + return (symbols,) + elif is_sequence(symbols): + if all(isinstance(s, str) for s in symbols): + return _symbols(symbols) + elif all(isinstance(s, Expr) for s in symbols): + return symbols + raise ValueError("The type of `symbols` must be one of the following: " + "a str, Symbol/Expr or a sequence of " + "one of these types") + + +############################################################################## +# FREE GROUP # +############################################################################## + +_free_group_cache: dict[int, FreeGroup] = {} + +class FreeGroup(DefaultPrinting): + """ + Free group with finite or infinite number of generators. Its input API + is that of a str, Symbol/Expr or a sequence of one of + these types (which may be empty) + + See Also + ======== + + sympy.polys.rings.PolyRing + + References + ========== + + .. [1] https://www.gap-system.org/Manuals/doc/ref/chap37.html + + .. [2] https://en.wikipedia.org/wiki/Free_group + + """ + is_associative = True + is_group = True + is_FreeGroup = True + is_PermutationGroup = False + relators: list[Expr] = [] + + def __new__(cls, symbols): + symbols = tuple(_parse_symbols(symbols)) + rank = len(symbols) + _hash = hash((cls.__name__, symbols, rank)) + obj = _free_group_cache.get(_hash) + + if obj is None: + obj = object.__new__(cls) + obj._hash = _hash + obj._rank = rank + # dtype method is used to create new instances of FreeGroupElement + obj.dtype = type("FreeGroupElement", (FreeGroupElement,), {"group": obj}) + obj.symbols = symbols + obj.generators = obj._generators() + obj._gens_set = set(obj.generators) + for symbol, generator in zip(obj.symbols, obj.generators): + if isinstance(symbol, Symbol): + name = symbol.name + if hasattr(obj, name): + setattr(obj, name, generator) + + _free_group_cache[_hash] = obj + + return obj + + def __getnewargs__(self): + """Return a tuple of arguments that must be passed to __new__ in order to support pickling this object.""" + return (self.symbols,) + + def __getstate__(self): + # Don't pickle any fields because they are regenerated within __new__ + return None + + def _generators(group): + """Returns the generators of the FreeGroup. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y, z = free_group("x, y, z") + >>> F.generators + (x, y, z) + + """ + gens = [] + for sym in group.symbols: + elm = ((sym, 1),) + gens.append(group.dtype(elm)) + return tuple(gens) + + def clone(self, symbols=None): + return self.__class__(symbols or self.symbols) + + def __contains__(self, i): + """Return True if ``i`` is contained in FreeGroup.""" + if not isinstance(i, FreeGroupElement): + return False + group = i.group + return self == group + + def __hash__(self): + return self._hash + + def __len__(self): + return self.rank + + def __str__(self): + if self.rank > 30: + str_form = "" % self.rank + else: + str_form = "" + return str_form + + __repr__ = __str__ + + def __getitem__(self, index): + symbols = self.symbols[index] + return self.clone(symbols=symbols) + + def __eq__(self, other): + """No ``FreeGroup`` is equal to any "other" ``FreeGroup``. + """ + return self is other + + def index(self, gen): + """Return the index of the generator `gen` from ``(f_0, ..., f_(n-1))``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> F.index(y) + 1 + >>> F.index(x) + 0 + + """ + if isinstance(gen, self.dtype): + return self.generators.index(gen) + else: + raise ValueError("expected a generator of Free Group %s, got %s" % (self, gen)) + + def order(self): + """Return the order of the free group. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> F.order() + oo + + >>> free_group("")[0].order() + 1 + + """ + if self.rank == 0: + return S.One + else: + return S.Infinity + + @property + def elements(self): + """ + Return the elements of the free group. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> (z,) = free_group("") + >>> z.elements + {} + + """ + if self.rank == 0: + # A set containing Identity element of `FreeGroup` self is returned + return {self.identity} + else: + raise ValueError("Group contains infinitely many elements" + ", hence cannot be represented") + + @property + def rank(self): + r""" + In group theory, the `rank` of a group `G`, denoted `G.rank`, + can refer to the smallest cardinality of a generating set + for G, that is + + \operatorname{rank}(G)=\min\{ |X|: X\subseteq G, \left\langle X\right\rangle =G\}. + + """ + return self._rank + + @property + def is_abelian(self): + """Returns if the group is Abelian. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> f.is_abelian + False + + """ + return self.rank in (0, 1) + + @property + def identity(self): + """Returns the identity element of free group.""" + return self.dtype() + + def contains(self, g): + """Tests if Free Group element ``g`` belong to self, ``G``. + + In mathematical terms any linear combination of generators + of a Free Group is contained in it. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> f.contains(x**3*y**2) + True + + """ + if not isinstance(g, FreeGroupElement): + return False + elif self != g.group: + return False + else: + return True + + def center(self): + """Returns the center of the free group `self`.""" + return {self.identity} + + +############################################################################ +# FreeGroupElement # +############################################################################ + + +class FreeGroupElement(CantSympify, DefaultPrinting, tuple): + """Used to create elements of FreeGroup. It cannot be used directly to + create a free group element. It is called by the `dtype` method of the + `FreeGroup` class. + + """ + __slots__ = () + is_assoc_word = True + + def new(self, init): + return self.__class__(init) + + _hash = None + + def __hash__(self): + _hash = self._hash + if _hash is None: + self._hash = _hash = hash((self.group, frozenset(tuple(self)))) + return _hash + + def copy(self): + return self.new(self) + + @property + def is_identity(self): + return not self.array_form + + @property + def array_form(self): + """ + SymPy provides two different internal kinds of representation + of associative words. The first one is called the `array_form` + which is a tuple containing `tuples` as its elements, where the + size of each tuple is two. At the first position the tuple + contains the `symbol-generator`, while at the second position + of tuple contains the exponent of that generator at the position. + Since elements (i.e. words) do not commute, the indexing of tuple + makes that property to stay. + + The structure in ``array_form`` of ``FreeGroupElement`` is of form: + + ``( ( symbol_of_gen, exponent ), ( , ), ... ( , ) )`` + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> (x*z).array_form + ((x, 1), (z, 1)) + >>> (x**2*z*y*x**2).array_form + ((x, 2), (z, 1), (y, 1), (x, 2)) + + See Also + ======== + + letter_repr + + """ + return tuple(self) + + @property + def letter_form(self): + """ + The letter representation of a ``FreeGroupElement`` is a tuple + of generator symbols, with each entry corresponding to a group + generator. Inverses of the generators are represented by + negative generator symbols. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b, c, d = free_group("a b c d") + >>> (a**3).letter_form + (a, a, a) + >>> (a**2*d**-2*a*b**-4).letter_form + (a, a, -d, -d, a, -b, -b, -b, -b) + >>> (a**-2*b**3*d).letter_form + (-a, -a, b, b, b, d) + + See Also + ======== + + array_form + + """ + return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j) + for i, j in self.array_form])) + + def __getitem__(self, i): + group = self.group + r = self.letter_form[i] + if r.is_Symbol: + return group.dtype(((r, 1),)) + else: + return group.dtype(((-r, -1),)) + + def index(self, gen): + if len(gen) != 1: + raise ValueError() + return (self.letter_form).index(gen.letter_form[0]) + + @property + def letter_form_elm(self): + """ + """ + group = self.group + r = self.letter_form + return [group.dtype(((elm,1),)) if elm.is_Symbol \ + else group.dtype(((-elm,-1),)) for elm in r] + + @property + def ext_rep(self): + """This is called the External Representation of ``FreeGroupElement`` + """ + return tuple(flatten(self.array_form)) + + def __contains__(self, gen): + return gen.array_form[0][0] in tuple([r[0] for r in self.array_form]) + + def __str__(self): + if self.is_identity: + return "" + + str_form = "" + array_form = self.array_form + for i in range(len(array_form)): + if i == len(array_form) - 1: + if array_form[i][1] == 1: + str_form += str(array_form[i][0]) + else: + str_form += str(array_form[i][0]) + \ + "**" + str(array_form[i][1]) + else: + if array_form[i][1] == 1: + str_form += str(array_form[i][0]) + "*" + else: + str_form += str(array_form[i][0]) + \ + "**" + str(array_form[i][1]) + "*" + return str_form + + __repr__ = __str__ + + def __pow__(self, n): + n = as_int(n) + result = self.group.identity + if n == 0: + return result + if n < 0: + n = -n + x = self.inverse() + else: + x = self + while True: + if n % 2: + result *= x + n >>= 1 + if not n: + break + x *= x + return result + + def __mul__(self, other): + """Returns the product of elements belonging to the same ``FreeGroup``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> x*y**2*y**-4 + x*y**-2 + >>> z*y**-2 + z*y**-2 + >>> x**2*y*y**-1*x**-2 + + + """ + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be multiplied") + if self.is_identity: + return other + if other.is_identity: + return self + r = list(self.array_form + other.array_form) + zero_mul_simp(r, len(self.array_form) - 1) + return group.dtype(tuple(r)) + + def __truediv__(self, other): + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be multiplied") + return self*(other.inverse()) + + def __rtruediv__(self, other): + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be multiplied") + return other*(self.inverse()) + + def __add__(self, other): + return NotImplemented + + def inverse(self): + """ + Returns the inverse of a ``FreeGroupElement`` element + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> x.inverse() + x**-1 + >>> (x*y).inverse() + y**-1*x**-1 + + """ + group = self.group + r = tuple([(i, -j) for i, j in self.array_form[::-1]]) + return group.dtype(r) + + def order(self): + """Find the order of a ``FreeGroupElement``. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y = free_group("x y") + >>> (x**2*y*y**-1*x**-2).order() + 1 + + """ + if self.is_identity: + return S.One + else: + return S.Infinity + + def commutator(self, other): + """ + Return the commutator of `self` and `x`: ``~x*~self*x*self`` + + """ + group = self.group + if not isinstance(other, group.dtype): + raise ValueError("commutator of only FreeGroupElement of the same " + "FreeGroup exists") + else: + return self.inverse()*other.inverse()*self*other + + def eliminate_words(self, words, _all=False, inverse=True): + ''' + Replace each subword from the dictionary `words` by words[subword]. + If words is a list, replace the words by the identity. + + ''' + again = True + new = self + if isinstance(words, dict): + while again: + again = False + for sub in words: + prev = new + new = new.eliminate_word(sub, words[sub], _all=_all, inverse=inverse) + if new != prev: + again = True + else: + while again: + again = False + for sub in words: + prev = new + new = new.eliminate_word(sub, _all=_all, inverse=inverse) + if new != prev: + again = True + return new + + def eliminate_word(self, gen, by=None, _all=False, inverse=True): + """ + For an associative word `self`, a subword `gen`, and an associative + word `by` (identity by default), return the associative word obtained by + replacing each occurrence of `gen` in `self` by `by`. If `_all = True`, + the occurrences of `gen` that may appear after the first substitution will + also be replaced and so on until no occurrences are found. This might not + always terminate (e.g. `(x).eliminate_word(x, x**2, _all=True)`). + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y = free_group("x y") + >>> w = x**5*y*x**2*y**-4*x + >>> w.eliminate_word( x, x**2 ) + x**10*y*x**4*y**-4*x**2 + >>> w.eliminate_word( x, y**-1 ) + y**-11 + >>> w.eliminate_word(x**5) + y*x**2*y**-4*x + >>> w.eliminate_word(x*y, y) + x**4*y*x**2*y**-4*x + + See Also + ======== + substituted_word + + """ + if by is None: + by = self.group.identity + if self.is_independent(gen) or gen == by: + return self + if gen == self: + return by + if gen**-1 == by: + _all = False + word = self + l = len(gen) + + try: + i = word.subword_index(gen) + k = 1 + except ValueError: + if not inverse: + return word + try: + i = word.subword_index(gen**-1) + k = -1 + except ValueError: + return word + + word = word.subword(0, i)*by**k*word.subword(i+l, len(word)).eliminate_word(gen, by) + + if _all: + return word.eliminate_word(gen, by, _all=True, inverse=inverse) + else: + return word + + def __len__(self): + """ + For an associative word `self`, returns the number of letters in it. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> len(w) + 13 + >>> len(a**17) + 17 + >>> len(w**0) + 0 + + """ + return sum(abs(j) for (i, j) in self) + + def __eq__(self, other): + """ + Two associative words are equal if they are words over the + same alphabet and if they are sequences of the same letters. + This is equivalent to saying that the external representations + of the words are equal. + There is no "universal" empty word, every alphabet has its own + empty word. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") + >>> f + + >>> g, swap0, swap1 = free_group("swap0 swap1") + >>> g + + + >>> swapnil0 == swapnil1 + False + >>> swapnil0*swapnil1 == swapnil1/swapnil1*swapnil0*swapnil1 + True + >>> swapnil0*swapnil1 == swapnil1*swapnil0 + False + >>> swapnil1**0 == swap0**0 + False + + """ + group = self.group + if not isinstance(other, group.dtype): + return False + return tuple.__eq__(self, other) + + def __lt__(self, other): + """ + The ordering of associative words is defined by length and + lexicography (this ordering is called short-lex ordering), that + is, shorter words are smaller than longer words, and words of the + same length are compared w.r.t. the lexicographical ordering induced + by the ordering of generators. Generators are sorted according + to the order in which they were created. If the generators are + invertible then each generator `g` is larger than its inverse `g^{-1}`, + and `g^{-1}` is larger than every generator that is smaller than `g`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> b < a + False + >>> a < a.inverse() + False + + """ + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be compared") + l = len(self) + m = len(other) + # implement lenlex order + if l < m: + return True + elif l > m: + return False + for i in range(l): + a = self[i].array_form[0] + b = other[i].array_form[0] + p = group.symbols.index(a[0]) + q = group.symbols.index(b[0]) + if p < q: + return True + elif p > q: + return False + elif a[1] < b[1]: + return True + elif a[1] > b[1]: + return False + return False + + def __le__(self, other): + return (self == other or self < other) + + def __gt__(self, other): + """ + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, x, y, z = free_group("x y z") + >>> y**2 > x**2 + True + >>> y*z > z*y + False + >>> x > x.inverse() + True + + """ + group = self.group + if not isinstance(other, group.dtype): + raise TypeError("only FreeGroup elements of same FreeGroup can " + "be compared") + return not self <= other + + def __ge__(self, other): + return not self < other + + def exponent_sum(self, gen): + """ + For an associative word `self` and a generator or inverse of generator + `gen`, ``exponent_sum`` returns the number of times `gen` appears in + `self` minus the number of times its inverse appears in `self`. If + neither `gen` nor its inverse occur in `self` then 0 is returned. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w = x**2*y**3 + >>> w.exponent_sum(x) + 2 + >>> w.exponent_sum(x**-1) + -2 + >>> w = x**2*y**4*x**-3 + >>> w.exponent_sum(x) + -1 + + See Also + ======== + + generator_count + + """ + if len(gen) != 1: + raise ValueError("gen must be a generator or inverse of a generator") + s = gen.array_form[0] + return s[1]*sum(i[1] for i in self.array_form if i[0] == s[0]) + + def generator_count(self, gen): + """ + For an associative word `self` and a generator `gen`, + ``generator_count`` returns the multiplicity of generator + `gen` in `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w = x**2*y**3 + >>> w.generator_count(x) + 2 + >>> w = x**2*y**4*x**-3 + >>> w.generator_count(x) + 5 + + See Also + ======== + + exponent_sum + + """ + if len(gen) != 1 or gen.array_form[0][1] < 0: + raise ValueError("gen must be a generator") + s = gen.array_form[0] + return s[1]*sum(abs(i[1]) for i in self.array_form if i[0] == s[0]) + + def subword(self, from_i, to_j, strict=True): + """ + For an associative word `self` and two positive integers `from_i` and + `to_j`, `subword` returns the subword of `self` that begins at position + `from_i` and ends at `to_j - 1`, indexing is done with origin 0. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.subword(2, 6) + a**3*b + + """ + group = self.group + if not strict: + from_i = max(from_i, 0) + to_j = min(len(self), to_j) + if from_i < 0 or to_j > len(self): + raise ValueError("`from_i`, `to_j` must be positive and no greater than " + "the length of associative word") + if to_j <= from_i: + return group.identity + else: + letter_form = self.letter_form[from_i: to_j] + array_form = letter_form_to_array_form(letter_form, group) + return group.dtype(array_form) + + def subword_index(self, word, start = 0): + ''' + Find the index of `word` in `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**2*b*a*b**3 + >>> w.subword_index(a*b*a*b) + 1 + + ''' + l = len(word) + self_lf = self.letter_form + word_lf = word.letter_form + index = None + for i in range(start,len(self_lf)-l+1): + if self_lf[i:i+l] == word_lf: + index = i + break + if index is not None: + return index + else: + raise ValueError("The given word is not a subword of self") + + def is_dependent(self, word): + """ + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**4*y**-3).is_dependent(x**4*y**-2) + True + >>> (x**2*y**-1).is_dependent(x*y) + False + >>> (x*y**2*x*y**2).is_dependent(x*y**2) + True + >>> (x**12).is_dependent(x**-4) + True + + See Also + ======== + + is_independent + + """ + try: + return self.subword_index(word) is not None + except ValueError: + pass + try: + return self.subword_index(word**-1) is not None + except ValueError: + return False + + def is_independent(self, word): + """ + + See Also + ======== + + is_dependent + + """ + return not self.is_dependent(word) + + def contains_generators(self): + """ + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y, z = free_group("x, y, z") + >>> (x**2*y**-1).contains_generators() + {x, y} + >>> (x**3*z).contains_generators() + {x, z} + + """ + group = self.group + gens = {group.dtype(((syllable[0], 1),)) for syllable in self.array_form} + return gens + + def cyclic_subword(self, from_i, to_j): + group = self.group + l = len(self) + letter_form = self.letter_form + period1 = int(from_i/l) + if from_i >= l: + from_i -= l*period1 + to_j -= l*period1 + diff = to_j - from_i + word = letter_form[from_i: to_j] + period2 = int(to_j/l) - 1 + word += letter_form*period2 + letter_form[:diff-l+from_i-l*period2] + word = letter_form_to_array_form(word, group) + return group.dtype(word) + + def cyclic_conjugates(self): + """Returns a words which are cyclic to the word `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w = x*y*x*y*x + >>> w.cyclic_conjugates() + {x*y*x**2*y, x**2*y*x*y, y*x*y*x**2, y*x**2*y*x, x*y*x*y*x} + >>> s = x*y*x**2*y*x + >>> s.cyclic_conjugates() + {x**2*y*x**2*y, y*x**2*y*x**2, x*y*x**2*y*x} + + References + ========== + + .. [1] https://planetmath.org/cyclicpermutation + + """ + return {self.cyclic_subword(i, i+len(self)) for i in range(len(self))} + + def is_cyclic_conjugate(self, w): + """ + Checks whether words ``self``, ``w`` are cyclic conjugates. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> w1 = x**2*y**5 + >>> w2 = x*y**5*x + >>> w1.is_cyclic_conjugate(w2) + True + >>> w3 = x**-1*y**5*x**-1 + >>> w3.is_cyclic_conjugate(w2) + False + + """ + l1 = len(self) + l2 = len(w) + if l1 != l2: + return False + w1 = self.identity_cyclic_reduction() + w2 = w.identity_cyclic_reduction() + letter1 = w1.letter_form + letter2 = w2.letter_form + str1 = ' '.join(map(str, letter1)) + str2 = ' '.join(map(str, letter2)) + if len(str1) != len(str2): + return False + + return str1 in str2 + ' ' + str2 + + def number_syllables(self): + """Returns the number of syllables of the associative word `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") + >>> (swapnil1**3*swapnil0*swapnil1**-1).number_syllables() + 3 + + """ + return len(self.array_form) + + def exponent_syllable(self, i): + """ + Returns the exponent of the `i`-th syllable of the associative word + `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.exponent_syllable( 2 ) + 2 + + """ + return self.array_form[i][1] + + def generator_syllable(self, i): + """ + Returns the symbol of the generator that is involved in the + i-th syllable of the associative word `self`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.generator_syllable( 3 ) + b + + """ + return self.array_form[i][0] + + def sub_syllables(self, from_i, to_j): + """ + `sub_syllables` returns the subword of the associative word `self` that + consists of syllables from positions `from_to` to `to_j`, where + `from_to` and `to_j` must be positive integers and indexing is done + with origin 0. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> f, a, b = free_group("a, b") + >>> w = a**5*b*a**2*b**-4*a + >>> w.sub_syllables(1, 2) + b + >>> w.sub_syllables(3, 3) + + + """ + if not isinstance(from_i, int) or not isinstance(to_j, int): + raise ValueError("both arguments should be integers") + group = self.group + if to_j <= from_i: + return group.identity + else: + r = tuple(self.array_form[from_i: to_j]) + return group.dtype(r) + + def substituted_word(self, from_i, to_j, by): + """ + Returns the associative word obtained by replacing the subword of + `self` that begins at position `from_i` and ends at position `to_j - 1` + by the associative word `by`. `from_i` and `to_j` must be positive + integers, indexing is done with origin 0. In other words, + `w.substituted_word(w, from_i, to_j, by)` is the product of the three + words: `w.subword(0, from_i)`, `by`, and + `w.subword(to_j len(w))`. + + See Also + ======== + + eliminate_word + + """ + lw = len(self) + if from_i >= to_j or from_i > lw or to_j > lw: + raise ValueError("values should be within bounds") + + # otherwise there are four possibilities + + # first if from=1 and to=lw then + if from_i == 0 and to_j == lw: + return by + elif from_i == 0: # second if from_i=1 (and to_j < lw) then + return by*self.subword(to_j, lw) + elif to_j == lw: # third if to_j=1 (and from_i > 1) then + return self.subword(0, from_i)*by + else: # finally + return self.subword(0, from_i)*by*self.subword(to_j, lw) + + def is_cyclically_reduced(self): + r"""Returns whether the word is cyclically reduced or not. + A word is cyclically reduced if by forming the cycle of the + word, the word is not reduced, i.e a word w = `a_1 ... a_n` + is called cyclically reduced if `a_1 \ne a_n^{-1}`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**2*y**-1*x**-1).is_cyclically_reduced() + False + >>> (y*x**2*y**2).is_cyclically_reduced() + True + + """ + if not self: + return True + return self[0] != self[-1]**-1 + + def identity_cyclic_reduction(self): + """Return a unique cyclically reduced version of the word. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**2*y**2*x**-1).identity_cyclic_reduction() + x*y**2 + >>> (x**-3*y**-1*x**5).identity_cyclic_reduction() + x**2*y**-1 + + References + ========== + + .. [1] https://planetmath.org/cyclicallyreduced + + """ + word = self.copy() + group = self.group + while not word.is_cyclically_reduced(): + exp1 = word.exponent_syllable(0) + exp2 = word.exponent_syllable(-1) + r = exp1 + exp2 + if r == 0: + rep = word.array_form[1: word.number_syllables() - 1] + else: + rep = ((word.generator_syllable(0), exp1 + exp2),) + \ + word.array_form[1: word.number_syllables() - 1] + word = group.dtype(rep) + return word + + def cyclic_reduction(self, removed=False): + """Return a cyclically reduced version of the word. Unlike + `identity_cyclic_reduction`, this will not cyclically permute + the reduced word - just remove the "unreduced" bits on either + side of it. Compare the examples with those of + `identity_cyclic_reduction`. + + When `removed` is `True`, return a tuple `(word, r)` where + self `r` is such that before the reduction the word was either + `r*word*r**-1`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> (x**2*y**2*x**-1).cyclic_reduction() + x*y**2 + >>> (x**-3*y**-1*x**5).cyclic_reduction() + y**-1*x**2 + >>> (x**-3*y**-1*x**5).cyclic_reduction(removed=True) + (y**-1*x**2, x**-3) + + """ + word = self.copy() + g = self.group.identity + while not word.is_cyclically_reduced(): + exp1 = abs(word.exponent_syllable(0)) + exp2 = abs(word.exponent_syllable(-1)) + exp = min(exp1, exp2) + start = word[0]**abs(exp) + end = word[-1]**abs(exp) + word = start**-1*word*end**-1 + g = g*start + if removed: + return word, g + return word + + def power_of(self, other): + ''' + Check if `self == other**n` for some integer n. + + Examples + ======== + + >>> from sympy.combinatorics import free_group + >>> F, x, y = free_group("x, y") + >>> ((x*y)**2).power_of(x*y) + True + >>> (x**-3*y**-2*x**3).power_of(x**-3*y*x**3) + True + + ''' + if self.is_identity: + return True + + l = len(other) + if l == 1: + # self has to be a power of one generator + gens = self.contains_generators() + s = other in gens or other**-1 in gens + return len(gens) == 1 and s + + # if self is not cyclically reduced and it is a power of other, + # other isn't cyclically reduced and the parts removed during + # their reduction must be equal + reduced, r1 = self.cyclic_reduction(removed=True) + if not r1.is_identity: + other, r2 = other.cyclic_reduction(removed=True) + if r1 == r2: + return reduced.power_of(other) + return False + + if len(self) < l or len(self) % l: + return False + + prefix = self.subword(0, l) + if prefix == other or prefix**-1 == other: + rest = self.subword(l, len(self)) + return rest.power_of(other) + return False + + +def letter_form_to_array_form(array_form, group): + """ + This method converts a list given with possible repetitions of elements in + it. It returns a new list such that repetitions of consecutive elements is + removed and replace with a tuple element of size two such that the first + index contains `value` and the second index contains the number of + consecutive repetitions of `value`. + + """ + a = list(array_form[:]) + new_array = [] + n = 1 + symbols = group.symbols + for i in range(len(a)): + if i == len(a) - 1: + if a[i] == a[i - 1]: + if (-a[i]) in symbols: + new_array.append((-a[i], -n)) + else: + new_array.append((a[i], n)) + else: + if (-a[i]) in symbols: + new_array.append((-a[i], -1)) + else: + new_array.append((a[i], 1)) + return new_array + elif a[i] == a[i + 1]: + n += 1 + else: + if (-a[i]) in symbols: + new_array.append((-a[i], -n)) + else: + new_array.append((a[i], n)) + n = 1 + + +def zero_mul_simp(l, index): + """Used to combine two reduced words.""" + while index >=0 and index < len(l) - 1 and l[index][0] == l[index + 1][0]: + exp = l[index][1] + l[index + 1][1] + base = l[index][0] + l[index] = (base, exp) + del l[index + 1] + if l[index][1] == 0: + del l[index] + index -= 1 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/galois.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/galois.py new file mode 100644 index 0000000000000000000000000000000000000000..f8ff89886283903e116bf40e1be6f6131386e802 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/galois.py @@ -0,0 +1,611 @@ +r""" +Construct transitive subgroups of symmetric groups, useful in Galois theory. + +Besides constructing instances of the :py:class:`~.PermutationGroup` class to +represent the transitive subgroups of $S_n$ for small $n$, this module provides +*names* for these groups. + +In some applications, it may be preferable to know the name of a group, +rather than receive an instance of the :py:class:`~.PermutationGroup` +class, and then have to do extra work to determine which group it is, by +checking various properties. + +Names are instances of ``Enum`` classes defined in this module. With a name in +hand, the name's ``get_perm_group`` method can then be used to retrieve a +:py:class:`~.PermutationGroup`. + +The names used for groups in this module are taken from [1]. + +References +========== + +.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*. + +""" + +from collections import defaultdict +from enum import Enum +import itertools + +from sympy.combinatorics.named_groups import ( + SymmetricGroup, AlternatingGroup, CyclicGroup, DihedralGroup, + set_symmetric_group_properties, set_alternating_group_properties, +) +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.combinatorics.permutations import Permutation + + +class S1TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S1. + """ + S1 = "S1" + + def get_perm_group(self): + return SymmetricGroup(1) + + +class S2TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S2. + """ + S2 = "S2" + + def get_perm_group(self): + return SymmetricGroup(2) + + +class S3TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S3. + """ + A3 = "A3" + S3 = "S3" + + def get_perm_group(self): + if self == S3TransitiveSubgroups.A3: + return AlternatingGroup(3) + elif self == S3TransitiveSubgroups.S3: + return SymmetricGroup(3) + + +class S4TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S4. + """ + C4 = "C4" + V = "V" + D4 = "D4" + A4 = "A4" + S4 = "S4" + + def get_perm_group(self): + if self == S4TransitiveSubgroups.C4: + return CyclicGroup(4) + elif self == S4TransitiveSubgroups.V: + return four_group() + elif self == S4TransitiveSubgroups.D4: + return DihedralGroup(4) + elif self == S4TransitiveSubgroups.A4: + return AlternatingGroup(4) + elif self == S4TransitiveSubgroups.S4: + return SymmetricGroup(4) + + +class S5TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S5. + """ + C5 = "C5" + D5 = "D5" + M20 = "M20" + A5 = "A5" + S5 = "S5" + + def get_perm_group(self): + if self == S5TransitiveSubgroups.C5: + return CyclicGroup(5) + elif self == S5TransitiveSubgroups.D5: + return DihedralGroup(5) + elif self == S5TransitiveSubgroups.M20: + return M20() + elif self == S5TransitiveSubgroups.A5: + return AlternatingGroup(5) + elif self == S5TransitiveSubgroups.S5: + return SymmetricGroup(5) + + +class S6TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S6. + """ + C6 = "C6" + S3 = "S3" + D6 = "D6" + A4 = "A4" + G18 = "G18" + A4xC2 = "A4 x C2" + S4m = "S4-" + S4p = "S4+" + G36m = "G36-" + G36p = "G36+" + S4xC2 = "S4 x C2" + PSL2F5 = "PSL2(F5)" + G72 = "G72" + PGL2F5 = "PGL2(F5)" + A6 = "A6" + S6 = "S6" + + def get_perm_group(self): + if self == S6TransitiveSubgroups.C6: + return CyclicGroup(6) + elif self == S6TransitiveSubgroups.S3: + return S3_in_S6() + elif self == S6TransitiveSubgroups.D6: + return DihedralGroup(6) + elif self == S6TransitiveSubgroups.A4: + return A4_in_S6() + elif self == S6TransitiveSubgroups.G18: + return G18() + elif self == S6TransitiveSubgroups.A4xC2: + return A4xC2() + elif self == S6TransitiveSubgroups.S4m: + return S4m() + elif self == S6TransitiveSubgroups.S4p: + return S4p() + elif self == S6TransitiveSubgroups.G36m: + return G36m() + elif self == S6TransitiveSubgroups.G36p: + return G36p() + elif self == S6TransitiveSubgroups.S4xC2: + return S4xC2() + elif self == S6TransitiveSubgroups.PSL2F5: + return PSL2F5() + elif self == S6TransitiveSubgroups.G72: + return G72() + elif self == S6TransitiveSubgroups.PGL2F5: + return PGL2F5() + elif self == S6TransitiveSubgroups.A6: + return AlternatingGroup(6) + elif self == S6TransitiveSubgroups.S6: + return SymmetricGroup(6) + + +def four_group(): + """ + Return a representation of the Klein four-group as a transitive subgroup + of S4. + """ + return PermutationGroup( + Permutation(0, 1)(2, 3), + Permutation(0, 2)(1, 3) + ) + + +def M20(): + """ + Return a representation of the metacyclic group M20, a transitive subgroup + of S5 that is one of the possible Galois groups for polys of degree 5. + + Notes + ===== + + See [1], Page 323. + + """ + G = PermutationGroup(Permutation(0, 1, 2, 3, 4), Permutation(1, 2, 4, 3)) + G._degree = 5 + G._order = 20 + G._is_transitive = True + G._is_sym = False + G._is_alt = False + G._is_cyclic = False + G._is_dihedral = False + return G + + +def S3_in_S6(): + """ + Return a representation of S3 as a transitive subgroup of S6. + + Notes + ===== + + The representation is found by viewing the group as the symmetries of a + triangular prism. + + """ + G = PermutationGroup(Permutation(0, 1, 2)(3, 4, 5), Permutation(0, 3)(2, 4)(1, 5)) + set_symmetric_group_properties(G, 3, 6) + return G + + +def A4_in_S6(): + """ + Return a representation of A4 as a transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup(Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4)) + set_alternating_group_properties(G, 4, 6) + return G + + +def S4m(): + """ + Return a representation of the S4- transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup(Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3)) + set_symmetric_group_properties(G, 4, 6) + return G + + +def S4p(): + """ + Return a representation of the S4+ transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup(Permutation(0, 2, 4, 1)(3, 5), Permutation(0, 3)(4, 5)) + set_symmetric_group_properties(G, 4, 6) + return G + + +def A4xC2(): + """ + Return a representation of the (A4 x C2) transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4), + Permutation(5)(2, 4)) + + +def S4xC2(): + """ + Return a representation of the (S4 x C2) transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3), + Permutation(1, 4)(3, 5)) + + +def G18(): + """ + Return a representation of the group G18, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with C2. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), Permutation(3, 4, 5), + Permutation(0, 4)(1, 5)(2, 3)) + + +def G36m(): + """ + Return a representation of the group G36-, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with C2^2. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), Permutation(3, 4, 5), + Permutation(1, 2)(3, 5), Permutation(0, 4)(1, 5)(2, 3)) + + +def G36p(): + """ + Return a representation of the group G36+, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with C4. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), Permutation(3, 4, 5), + Permutation(0, 5, 2, 3)(1, 4)) + + +def G72(): + """ + Return a representation of the group G72, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with D4. + + Notes + ===== + + See [1], Page 325. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), + Permutation(0, 4, 1, 3)(2, 5), Permutation(0, 3)(1, 4)(2, 5)) + + +def PSL2F5(): + r""" + Return a representation of the group $PSL_2(\mathbb{F}_5)$, as a transitive + subgroup of S6, isomorphic to $A_5$. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup( + Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 4, 3, 1, 5)) + set_alternating_group_properties(G, 5, 6) + return G + + +def PGL2F5(): + r""" + Return a representation of the group $PGL_2(\mathbb{F}_5)$, as a transitive + subgroup of S6, isomorphic to $S_5$. + + Notes + ===== + + See [1], Page 325. + + """ + G = PermutationGroup( + Permutation(0, 1, 2, 3, 4), Permutation(0, 5)(1, 2)(3, 4)) + set_symmetric_group_properties(G, 5, 6) + return G + + +def find_transitive_subgroups_of_S6(*targets, print_report=False): + r""" + Search for certain transitive subgroups of $S_6$. + + The symmetric group $S_6$ has 16 different transitive subgroups, up to + conjugacy. Some are more easily constructed than others. For example, the + dihedral group $D_6$ is immediately found, but it is not at all obvious how + to realize $S_4$ or $S_5$ *transitively* within $S_6$. + + In some cases there are well-known constructions that can be used. For + example, $S_5$ is isomorphic to $PGL_2(\mathbb{F}_5)$, which acts in a + natural way on the projective line $P^1(\mathbb{F}_5)$, a set of order 6. + + In absence of such special constructions however, we can simply search for + generators. For example, transitive instances of $A_4$ and $S_4$ can be + found within $S_6$ in this way. + + Once we are engaged in such searches, it may then be easier (if less + elegant) to find even those groups like $S_5$ that do have special + constructions, by mere search. + + This function locates generators for transitive instances in $S_6$ of the + following subgroups: + + * $A_4$ + * $S_4^-$ ($S_4$ not contained within $A_6$) + * $S_4^+$ ($S_4$ contained within $A_6$) + * $A_4 \times C_2$ + * $S_4 \times C_2$ + * $G_{18} = C_3^2 \rtimes C_2$ + * $G_{36}^- = C_3^2 \rtimes C_2^2$ + * $G_{36}^+ = C_3^2 \rtimes C_4$ + * $G_{72} = C_3^2 \rtimes D_4$ + * $A_5$ + * $S_5$ + + Note: Each of these groups also has a dedicated function in this module + that returns the group immediately, using generators that were found by + this search procedure. + + The search procedure serves as a record of how these generators were + found. Also, due to randomness in the generation of the elements of + permutation groups, it can be called again, in order to (probably) get + different generators for the same groups. + + Parameters + ========== + + targets : list of :py:class:`~.S6TransitiveSubgroups` values + The groups you want to find. + + print_report : bool (default False) + If True, print to stdout the generators found for each group. + + Returns + ======= + + dict + mapping each name in *targets* to the :py:class:`~.PermutationGroup` + that was found + + References + ========== + + .. [2] https://en.wikipedia.org/wiki/Projective_linear_group#Exceptional_isomorphisms + .. [3] https://en.wikipedia.org/wiki/Automorphisms_of_the_symmetric_and_alternating_groups#PGL%282,5%29 + + """ + def elts_by_order(G): + """Sort the elements of a group by their order. """ + elts = defaultdict(list) + for g in G.elements: + elts[g.order()].append(g) + return elts + + def order_profile(G, name=None): + """Determine how many elements a group has, of each order. """ + elts = elts_by_order(G) + profile = {o:len(e) for o, e in elts.items()} + if name: + print(f'{name}: ' + ' '.join(f'{len(profile[r])}@{r}' for r in sorted(profile.keys()))) + return profile + + S6 = SymmetricGroup(6) + A6 = AlternatingGroup(6) + S6_by_order = elts_by_order(S6) + + def search(existing_gens, needed_gen_orders, order, alt=None, profile=None, anti_profile=None): + """ + Find a transitive subgroup of S6. + + Parameters + ========== + + existing_gens : list of Permutation + Optionally empty list of generators that must be in the group. + + needed_gen_orders : list of positive int + Nonempty list of the orders of the additional generators that are + to be found. + + order: int + The order of the group being sought. + + alt: bool, None + If True, require the group to be contained in A6. + If False, require the group not to be contained in A6. + + profile : dict + If given, the group's order profile must equal this. + + anti_profile : dict + If given, the group's order profile must *not* equal this. + + """ + for gens in itertools.product(*[S6_by_order[n] for n in needed_gen_orders]): + if len(set(gens)) < len(gens): + continue + G = PermutationGroup(existing_gens + list(gens)) + if G.order() == order and G.is_transitive(): + if alt is not None and G.is_subgroup(A6) != alt: + continue + if profile and order_profile(G) != profile: + continue + if anti_profile and order_profile(G) == anti_profile: + continue + return G + + def match_known_group(G, alt=None): + needed = [g.order() for g in G.generators] + return search([], needed, G.order(), alt=alt, profile=order_profile(G)) + + found = {} + + def finish_up(name, G): + found[name] = G + if print_report: + print("=" * 40) + print(f"{name}:") + print(G.generators) + + if S6TransitiveSubgroups.A4 in targets or S6TransitiveSubgroups.A4xC2 in targets: + A4_in_S6 = match_known_group(AlternatingGroup(4)) + finish_up(S6TransitiveSubgroups.A4, A4_in_S6) + + if S6TransitiveSubgroups.S4m in targets or S6TransitiveSubgroups.S4xC2 in targets: + S4m_in_S6 = match_known_group(SymmetricGroup(4), alt=False) + finish_up(S6TransitiveSubgroups.S4m, S4m_in_S6) + + if S6TransitiveSubgroups.S4p in targets: + S4p_in_S6 = match_known_group(SymmetricGroup(4), alt=True) + finish_up(S6TransitiveSubgroups.S4p, S4p_in_S6) + + if S6TransitiveSubgroups.A4xC2 in targets: + A4xC2_in_S6 = search(A4_in_S6.generators, [2], 24, anti_profile=order_profile(SymmetricGroup(4))) + finish_up(S6TransitiveSubgroups.A4xC2, A4xC2_in_S6) + + if S6TransitiveSubgroups.S4xC2 in targets: + S4xC2_in_S6 = search(S4m_in_S6.generators, [2], 48) + finish_up(S6TransitiveSubgroups.S4xC2, S4xC2_in_S6) + + # For the normal factor N = C3^2 in any of the G_n subgroups, we take one + # obvious instance of C3^2 in S6: + N_gens = [Permutation(5)(0, 1, 2), Permutation(5)(3, 4, 5)] + + if S6TransitiveSubgroups.G18 in targets: + G18_in_S6 = search(N_gens, [2], 18) + finish_up(S6TransitiveSubgroups.G18, G18_in_S6) + + if S6TransitiveSubgroups.G36m in targets: + G36m_in_S6 = search(N_gens, [2, 2], 36, alt=False) + finish_up(S6TransitiveSubgroups.G36m, G36m_in_S6) + + if S6TransitiveSubgroups.G36p in targets: + G36p_in_S6 = search(N_gens, [4], 36, alt=True) + finish_up(S6TransitiveSubgroups.G36p, G36p_in_S6) + + if S6TransitiveSubgroups.G72 in targets: + G72_in_S6 = search(N_gens, [4, 2], 72) + finish_up(S6TransitiveSubgroups.G72, G72_in_S6) + + # The PSL2(F5) and PGL2(F5) subgroups are isomorphic to A5 and S5, resp. + + if S6TransitiveSubgroups.PSL2F5 in targets: + PSL2F5_in_S6 = match_known_group(AlternatingGroup(5)) + finish_up(S6TransitiveSubgroups.PSL2F5, PSL2F5_in_S6) + + if S6TransitiveSubgroups.PGL2F5 in targets: + PGL2F5_in_S6 = match_known_group(SymmetricGroup(5)) + finish_up(S6TransitiveSubgroups.PGL2F5, PGL2F5_in_S6) + + # There is little need to "search" for any of the groups C6, S3, D6, A6, + # or S6, since they all have obvious realizations within S6. However, we + # support them here just in case a random representation is desired. + + if S6TransitiveSubgroups.C6 in targets: + C6 = match_known_group(CyclicGroup(6)) + finish_up(S6TransitiveSubgroups.C6, C6) + + if S6TransitiveSubgroups.S3 in targets: + S3 = match_known_group(SymmetricGroup(3)) + finish_up(S6TransitiveSubgroups.S3, S3) + + if S6TransitiveSubgroups.D6 in targets: + D6 = match_known_group(DihedralGroup(6)) + finish_up(S6TransitiveSubgroups.D6, D6) + + if S6TransitiveSubgroups.A6 in targets: + A6 = match_known_group(A6) + finish_up(S6TransitiveSubgroups.A6, A6) + + if S6TransitiveSubgroups.S6 in targets: + S6 = match_known_group(S6) + finish_up(S6TransitiveSubgroups.S6, S6) + + return found diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/generators.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/generators.py new file mode 100644 index 0000000000000000000000000000000000000000..19e274a4c5b4bf0781855db6bc6bf499349fff31 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/generators.py @@ -0,0 +1,301 @@ +from sympy.combinatorics.permutations import Permutation +from sympy.core.symbol import symbols +from sympy.matrices import Matrix +from sympy.utilities.iterables import variations, rotate_left + + +def symmetric(n): + """ + Generates the symmetric group of order n, Sn. + + Examples + ======== + + >>> from sympy.combinatorics.generators import symmetric + >>> list(symmetric(3)) + [(2), (1 2), (2)(0 1), (0 1 2), (0 2 1), (0 2)] + """ + yield from (Permutation(perm) for perm in variations(range(n), n)) + + +def cyclic(n): + """ + Generates the cyclic group of order n, Cn. + + Examples + ======== + + >>> from sympy.combinatorics.generators import cyclic + >>> list(cyclic(5)) + [(4), (0 1 2 3 4), (0 2 4 1 3), + (0 3 1 4 2), (0 4 3 2 1)] + + See Also + ======== + + dihedral + """ + gen = list(range(n)) + for i in range(n): + yield Permutation(gen) + gen = rotate_left(gen, 1) + + +def alternating(n): + """ + Generates the alternating group of order n, An. + + Examples + ======== + + >>> from sympy.combinatorics.generators import alternating + >>> list(alternating(3)) + [(2), (0 1 2), (0 2 1)] + """ + for perm in variations(range(n), n): + p = Permutation(perm) + if p.is_even: + yield p + + +def dihedral(n): + """ + Generates the dihedral group of order 2n, Dn. + + The result is given as a subgroup of Sn, except for the special cases n=1 + (the group S2) and n=2 (the Klein 4-group) where that's not possible + and embeddings in S2 and S4 respectively are given. + + Examples + ======== + + >>> from sympy.combinatorics.generators import dihedral + >>> list(dihedral(3)) + [(2), (0 2), (0 1 2), (1 2), (0 2 1), (2)(0 1)] + + See Also + ======== + + cyclic + """ + if n == 1: + yield Permutation([0, 1]) + yield Permutation([1, 0]) + elif n == 2: + yield Permutation([0, 1, 2, 3]) + yield Permutation([1, 0, 3, 2]) + yield Permutation([2, 3, 0, 1]) + yield Permutation([3, 2, 1, 0]) + else: + gen = list(range(n)) + for i in range(n): + yield Permutation(gen) + yield Permutation(gen[::-1]) + gen = rotate_left(gen, 1) + + +def rubik_cube_generators(): + """Return the permutations of the 3x3 Rubik's cube, see + https://www.gap-system.org/Doc/Examples/rubik.html + """ + a = [ + [(1, 3, 8, 6), (2, 5, 7, 4), (9, 33, 25, 17), (10, 34, 26, 18), + (11, 35, 27, 19)], + [(9, 11, 16, 14), (10, 13, 15, 12), (1, 17, 41, 40), (4, 20, 44, 37), + (6, 22, 46, 35)], + [(17, 19, 24, 22), (18, 21, 23, 20), (6, 25, 43, 16), (7, 28, 42, 13), + (8, 30, 41, 11)], + [(25, 27, 32, 30), (26, 29, 31, 28), (3, 38, 43, 19), (5, 36, 45, 21), + (8, 33, 48, 24)], + [(33, 35, 40, 38), (34, 37, 39, 36), (3, 9, 46, 32), (2, 12, 47, 29), + (1, 14, 48, 27)], + [(41, 43, 48, 46), (42, 45, 47, 44), (14, 22, 30, 38), + (15, 23, 31, 39), (16, 24, 32, 40)] + ] + return [Permutation([[i - 1 for i in xi] for xi in x], size=48) for x in a] + + +def rubik(n): + """Return permutations for an nxn Rubik's cube. + + Permutations returned are for rotation of each of the slice + from the face up to the last face for each of the 3 sides (in this order): + front, right and bottom. Hence, the first n - 1 permutations are for the + slices from the front. + """ + + if n < 2: + raise ValueError('dimension of cube must be > 1') + + # 1-based reference to rows and columns in Matrix + def getr(f, i): + return faces[f].col(n - i) + + def getl(f, i): + return faces[f].col(i - 1) + + def getu(f, i): + return faces[f].row(i - 1) + + def getd(f, i): + return faces[f].row(n - i) + + def setr(f, i, s): + faces[f][:, n - i] = Matrix(n, 1, s) + + def setl(f, i, s): + faces[f][:, i - 1] = Matrix(n, 1, s) + + def setu(f, i, s): + faces[f][i - 1, :] = Matrix(1, n, s) + + def setd(f, i, s): + faces[f][n - i, :] = Matrix(1, n, s) + + # motion of a single face + def cw(F, r=1): + for _ in range(r): + face = faces[F] + rv = [] + for c in range(n): + for r in range(n - 1, -1, -1): + rv.append(face[r, c]) + faces[F] = Matrix(n, n, rv) + + def ccw(F): + cw(F, 3) + + # motion of plane i from the F side; + # fcw(0) moves the F face, fcw(1) moves the plane + # just behind the front face, etc... + def fcw(i, r=1): + for _ in range(r): + if i == 0: + cw(F) + i += 1 + temp = getr(L, i) + setr(L, i, list(getu(D, i))) + setu(D, i, list(reversed(getl(R, i)))) + setl(R, i, list(getd(U, i))) + setd(U, i, list(reversed(temp))) + i -= 1 + + def fccw(i): + fcw(i, 3) + + # motion of the entire cube from the F side + def FCW(r=1): + for _ in range(r): + cw(F) + ccw(B) + cw(U) + t = faces[U] + cw(L) + faces[U] = faces[L] + cw(D) + faces[L] = faces[D] + cw(R) + faces[D] = faces[R] + faces[R] = t + + def FCCW(): + FCW(3) + + # motion of the entire cube from the U side + def UCW(r=1): + for _ in range(r): + cw(U) + ccw(D) + t = faces[F] + faces[F] = faces[R] + faces[R] = faces[B] + faces[B] = faces[L] + faces[L] = t + + def UCCW(): + UCW(3) + + # defining the permutations for the cube + + U, F, R, B, L, D = names = symbols('U, F, R, B, L, D') + + # the faces are represented by nxn matrices + faces = {} + count = 0 + for fi in range(6): + f = [] + for a in range(n**2): + f.append(count) + count += 1 + faces[names[fi]] = Matrix(n, n, f) + + # this will either return the value of the current permutation + # (show != 1) or else append the permutation to the group, g + def perm(show=0): + # add perm to the list of perms + p = [] + for f in names: + p.extend(faces[f]) + if show: + return p + g.append(Permutation(p)) + + g = [] # container for the group's permutations + I = list(range(6*n**2)) # the identity permutation used for checking + + # define permutations corresponding to cw rotations of the planes + # up TO the last plane from that direction; by not including the + # last plane, the orientation of the cube is maintained. + + # F slices + for i in range(n - 1): + fcw(i) + perm() + fccw(i) # restore + assert perm(1) == I + + # R slices + # bring R to front + UCW() + for i in range(n - 1): + fcw(i) + # put it back in place + UCCW() + # record + perm() + # restore + # bring face to front + UCW() + fccw(i) + # restore + UCCW() + assert perm(1) == I + + # D slices + # bring up bottom + FCW() + UCCW() + FCCW() + for i in range(n - 1): + # turn strip + fcw(i) + # put bottom back on the bottom + FCW() + UCW() + FCCW() + # record + perm() + # restore + # bring up bottom + FCW() + UCCW() + FCCW() + # turn strip + fccw(i) + # put bottom back on the bottom + FCW() + UCW() + FCCW() + assert perm(1) == I + + return g diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/graycode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/graycode.py new file mode 100644 index 0000000000000000000000000000000000000000..930fd337862a70e920a985947d74375b27741293 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/graycode.py @@ -0,0 +1,430 @@ +from sympy.core import Basic, Integer + +import random + + +class GrayCode(Basic): + """ + A Gray code is essentially a Hamiltonian walk on + a n-dimensional cube with edge length of one. + The vertices of the cube are represented by vectors + whose values are binary. The Hamilton walk visits + each vertex exactly once. The Gray code for a 3d + cube is ['000','100','110','010','011','111','101', + '001']. + + A Gray code solves the problem of sequentially + generating all possible subsets of n objects in such + a way that each subset is obtained from the previous + one by either deleting or adding a single object. + In the above example, 1 indicates that the object is + present, and 0 indicates that its absent. + + Gray codes have applications in statistics as well when + we want to compute various statistics related to subsets + in an efficient manner. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> list(a.generate_gray()) + ['000', '001', '011', '010', '110', '111', '101', '100'] + >>> a = GrayCode(4) + >>> list(a.generate_gray()) + ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', \ + '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000'] + + References + ========== + + .. [1] Nijenhuis,A. and Wilf,H.S.(1978). + Combinatorial Algorithms. Academic Press. + .. [2] Knuth, D. (2011). The Art of Computer Programming, Vol 4 + Addison Wesley + + + """ + + _skip = False + _current = 0 + _rank = None + + def __new__(cls, n, *args, **kw_args): + """ + Default constructor. + + It takes a single argument ``n`` which gives the dimension of the Gray + code. The starting Gray code string (``start``) or the starting ``rank`` + may also be given; the default is to start at rank = 0 ('0...0'). + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> a + GrayCode(3) + >>> a.n + 3 + + >>> a = GrayCode(3, start='100') + >>> a.current + '100' + + >>> a = GrayCode(4, rank=4) + >>> a.current + '0110' + >>> a.rank + 4 + + """ + if n < 1 or int(n) != n: + raise ValueError( + 'Gray code dimension must be a positive integer, not %i' % n) + n = Integer(n) + args = (n,) + args + obj = Basic.__new__(cls, *args) + if 'start' in kw_args: + obj._current = kw_args["start"] + if len(obj._current) > n: + raise ValueError('Gray code start has length %i but ' + 'should not be greater than %i' % (len(obj._current), n)) + elif 'rank' in kw_args: + if int(kw_args["rank"]) != kw_args["rank"]: + raise ValueError('Gray code rank must be a positive integer, ' + 'not %i' % kw_args["rank"]) + obj._rank = int(kw_args["rank"]) % obj.selections + obj._current = obj.unrank(n, obj._rank) + return obj + + def next(self, delta=1): + """ + Returns the Gray code a distance ``delta`` (default = 1) from the + current value in canonical order. + + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3, start='110') + >>> a.next().current + '111' + >>> a.next(-1).current + '010' + """ + return GrayCode(self.n, rank=(self.rank + delta) % self.selections) + + @property + def selections(self): + """ + Returns the number of bit vectors in the Gray code. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> a.selections + 8 + """ + return 2**self.n + + @property + def n(self): + """ + Returns the dimension of the Gray code. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(5) + >>> a.n + 5 + """ + return self.args[0] + + def generate_gray(self, **hints): + """ + Generates the sequence of bit vectors of a Gray Code. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> list(a.generate_gray()) + ['000', '001', '011', '010', '110', '111', '101', '100'] + >>> list(a.generate_gray(start='011')) + ['011', '010', '110', '111', '101', '100'] + >>> list(a.generate_gray(rank=4)) + ['110', '111', '101', '100'] + + See Also + ======== + + skip + + References + ========== + + .. [1] Knuth, D. (2011). The Art of Computer Programming, + Vol 4, Addison Wesley + + """ + bits = self.n + start = None + if "start" in hints: + start = hints["start"] + elif "rank" in hints: + start = GrayCode.unrank(self.n, hints["rank"]) + if start is not None: + self._current = start + current = self.current + graycode_bin = gray_to_bin(current) + if len(graycode_bin) > self.n: + raise ValueError('Gray code start has length %i but should ' + 'not be greater than %i' % (len(graycode_bin), bits)) + self._current = int(current, 2) + graycode_int = int(''.join(graycode_bin), 2) + for i in range(graycode_int, 1 << bits): + if self._skip: + self._skip = False + else: + yield self.current + bbtc = (i ^ (i + 1)) + gbtc = (bbtc ^ (bbtc >> 1)) + self._current = (self._current ^ gbtc) + self._current = 0 + + def skip(self): + """ + Skips the bit generation. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> for i in a.generate_gray(): + ... if i == '010': + ... a.skip() + ... print(i) + ... + 000 + 001 + 011 + 010 + 111 + 101 + 100 + + See Also + ======== + + generate_gray + """ + self._skip = True + + @property + def rank(self): + """ + Ranks the Gray code. + + A ranking algorithm determines the position (or rank) + of a combinatorial object among all the objects w.r.t. + a given order. For example, the 4 bit binary reflected + Gray code (BRGC) '0101' has a rank of 6 as it appears in + the 6th position in the canonical ordering of the family + of 4 bit Gray codes. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> list(a.generate_gray()) + ['000', '001', '011', '010', '110', '111', '101', '100'] + >>> GrayCode(3, start='100').rank + 7 + >>> GrayCode(3, rank=7).current + '100' + + See Also + ======== + + unrank + + References + ========== + + .. [1] https://web.archive.org/web/20200224064753/http://statweb.stanford.edu/~susan/courses/s208/node12.html + + """ + if self._rank is None: + self._rank = int(gray_to_bin(self.current), 2) + return self._rank + + @property + def current(self): + """ + Returns the currently referenced Gray code as a bit string. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> GrayCode(3, start='100').current + '100' + """ + rv = self._current or '0' + if not isinstance(rv, str): + rv = bin(rv)[2:] + return rv.rjust(self.n, '0') + + @classmethod + def unrank(self, n, rank): + """ + Unranks an n-bit sized Gray code of rank k. This method exists + so that a derivative GrayCode class can define its own code of + a given rank. + + The string here is generated in reverse order to allow for tail-call + optimization. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> GrayCode(5, rank=3).current + '00010' + >>> GrayCode.unrank(5, 3) + '00010' + + See Also + ======== + + rank + """ + def _unrank(k, n): + if n == 1: + return str(k % 2) + m = 2**(n - 1) + if k < m: + return '0' + _unrank(k, n - 1) + return '1' + _unrank(m - (k % m) - 1, n - 1) + return _unrank(rank, n) + + +def random_bitstring(n): + """ + Generates a random bitlist of length n. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import random_bitstring + >>> random_bitstring(3) # doctest: +SKIP + 100 + """ + return ''.join([random.choice('01') for i in range(n)]) + + +def gray_to_bin(bin_list): + """ + Convert from Gray coding to binary coding. + + We assume big endian encoding. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import gray_to_bin + >>> gray_to_bin('100') + '111' + + See Also + ======== + + bin_to_gray + """ + b = [bin_list[0]] + for i in range(1, len(bin_list)): + b += str(int(b[i - 1] != bin_list[i])) + return ''.join(b) + + +def bin_to_gray(bin_list): + """ + Convert from binary coding to gray coding. + + We assume big endian encoding. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import bin_to_gray + >>> bin_to_gray('111') + '100' + + See Also + ======== + + gray_to_bin + """ + b = [bin_list[0]] + for i in range(1, len(bin_list)): + b += str(int(bin_list[i]) ^ int(bin_list[i - 1])) + return ''.join(b) + + +def get_subset_from_bitstring(super_set, bitstring): + """ + Gets the subset defined by the bitstring. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import get_subset_from_bitstring + >>> get_subset_from_bitstring(['a', 'b', 'c', 'd'], '0011') + ['c', 'd'] + >>> get_subset_from_bitstring(['c', 'a', 'c', 'c'], '1100') + ['c', 'a'] + + See Also + ======== + + graycode_subsets + """ + if len(super_set) != len(bitstring): + raise ValueError("The sizes of the lists are not equal") + return [super_set[i] for i, j in enumerate(bitstring) + if bitstring[i] == '1'] + + +def graycode_subsets(gray_code_set): + """ + Generates the subsets as enumerated by a Gray code. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import graycode_subsets + >>> list(graycode_subsets(['a', 'b', 'c'])) + [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], \ + ['a', 'c'], ['a']] + >>> list(graycode_subsets(['a', 'b', 'c', 'c'])) + [[], ['c'], ['c', 'c'], ['c'], ['b', 'c'], ['b', 'c', 'c'], \ + ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'c'], \ + ['a', 'b', 'c'], ['a', 'c'], ['a', 'c', 'c'], ['a', 'c'], ['a']] + + See Also + ======== + + get_subset_from_bitstring + """ + for bitstring in list(GrayCode(len(gray_code_set)).generate_gray()): + yield get_subset_from_bitstring(gray_code_set, bitstring) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c16ec254191646b26eee869763e2926e187da5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.py @@ -0,0 +1,61 @@ +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.combinatorics.permutations import Permutation +from sympy.utilities.iterables import uniq + +_af_new = Permutation._af_new + + +def DirectProduct(*groups): + """ + Returns the direct product of several groups as a permutation group. + + Explanation + =========== + + This is implemented much like the __mul__ procedure for taking the direct + product of two permutation groups, but the idea of shifting the + generators is realized in the case of an arbitrary number of groups. + A call to DirectProduct(G1, G2, ..., Gn) is generally expected to be faster + than a call to G1*G2*...*Gn (and thus the need for this algorithm). + + Examples + ======== + + >>> from sympy.combinatorics.group_constructs import DirectProduct + >>> from sympy.combinatorics.named_groups import CyclicGroup + >>> C = CyclicGroup(4) + >>> G = DirectProduct(C, C, C) + >>> G.order() + 64 + + See Also + ======== + + sympy.combinatorics.perm_groups.PermutationGroup.__mul__ + + """ + degrees = [] + gens_count = [] + total_degree = 0 + total_gens = 0 + for group in groups: + current_deg = group.degree + current_num_gens = len(group.generators) + degrees.append(current_deg) + total_degree += current_deg + gens_count.append(current_num_gens) + total_gens += current_num_gens + array_gens = [] + for i in range(total_gens): + array_gens.append(list(range(total_degree))) + current_gen = 0 + current_deg = 0 + for i in range(len(gens_count)): + for j in range(current_gen, current_gen + gens_count[i]): + gen = ((groups[i].generators)[j - current_gen]).array_form + array_gens[j][current_deg:current_deg + degrees[i]] = \ + [x + current_deg for x in gen] + current_gen += gens_count[i] + current_deg += degrees[i] + perm_gens = list(uniq([_af_new(list(a)) for a in array_gens])) + return PermutationGroup(perm_gens, dups=False) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..8099dfc2ed8a6943aa1261f9374ed84f0ad3c522 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.py @@ -0,0 +1,294 @@ +from itertools import chain, combinations + +from sympy.external.gmpy import gcd +from sympy.ntheory.factor_ import factorint +from sympy.utilities.misc import as_int + + +def _is_nilpotent_number(factors: dict) -> bool: + """ Check whether `n` is a nilpotent number. + Note that ``factors`` is a prime factorization of `n`. + + This is a low-level helper for ``is_nilpotent_number``, for internal use. + """ + for p in factors.keys(): + for q, e in factors.items(): + # We want to calculate + # any(pow(q, k, p) == 1 for k in range(1, e + 1)) + m = 1 + for _ in range(e): + m = m*q % p + if m == 1: + return False + return True + + +def is_nilpotent_number(n) -> bool: + """ + Check whether `n` is a nilpotent number. A number `n` is said to be + nilpotent if and only if every finite group of order `n` is nilpotent. + For more information see [1]_. + + Examples + ======== + + >>> from sympy.combinatorics.group_numbers import is_nilpotent_number + >>> from sympy import randprime + >>> is_nilpotent_number(21) + False + >>> is_nilpotent_number(randprime(1, 30)**12) + True + + References + ========== + + .. [1] Pakianathan, J., Shankar, K., Nilpotent Numbers, + The American Mathematical Monthly, 107(7), 631-634. + .. [2] https://oeis.org/A056867 + + """ + n = as_int(n) + if n <= 0: + raise ValueError("n must be a positive integer, not %i" % n) + return _is_nilpotent_number(factorint(n)) + + +def is_abelian_number(n) -> bool: + """ + Check whether `n` is an abelian number. A number `n` is said to be abelian + if and only if every finite group of order `n` is abelian. For more + information see [1]_. + + Examples + ======== + + >>> from sympy.combinatorics.group_numbers import is_abelian_number + >>> from sympy import randprime + >>> is_abelian_number(4) + True + >>> is_abelian_number(randprime(1, 2000)**2) + True + >>> is_abelian_number(60) + False + + References + ========== + + .. [1] Pakianathan, J., Shankar, K., Nilpotent Numbers, + The American Mathematical Monthly, 107(7), 631-634. + .. [2] https://oeis.org/A051532 + + """ + n = as_int(n) + if n <= 0: + raise ValueError("n must be a positive integer, not %i" % n) + factors = factorint(n) + return all(e < 3 for e in factors.values()) and _is_nilpotent_number(factors) + + +def is_cyclic_number(n) -> bool: + """ + Check whether `n` is a cyclic number. A number `n` is said to be cyclic + if and only if every finite group of order `n` is cyclic. For more + information see [1]_. + + Examples + ======== + + >>> from sympy.combinatorics.group_numbers import is_cyclic_number + >>> from sympy import randprime + >>> is_cyclic_number(15) + True + >>> is_cyclic_number(randprime(1, 2000)**2) + False + >>> is_cyclic_number(4) + False + + References + ========== + + .. [1] Pakianathan, J., Shankar, K., Nilpotent Numbers, + The American Mathematical Monthly, 107(7), 631-634. + .. [2] https://oeis.org/A003277 + + """ + n = as_int(n) + if n <= 0: + raise ValueError("n must be a positive integer, not %i" % n) + factors = factorint(n) + return all(e == 1 for e in factors.values()) and _is_nilpotent_number(factors) + + +def _holder_formula(prime_factors): + r""" Number of groups of order `n`. + where `n` is squarefree and its prime factors are ``prime_factors``. + i.e., ``n == math.prod(prime_factors)`` + + Explanation + =========== + + When `n` is squarefree, the number of groups of order `n` is expressed by + + .. math :: + \sum_{d \mid n} \prod_p \frac{p^{c(p, d)} - 1}{p - 1} + + where `n=de`, `p` is the prime factor of `e`, + and `c(p, d)` is the number of prime factors `q` of `d` such that `q \equiv 1 \pmod{p}` [2]_. + + The formula is elegant, but can be improved when implemented as an algorithm. + Since `n` is assumed to be squarefree, the divisor `d` of `n` can be identified with the power set of prime factors. + We let `N` be the set of prime factors of `n`. + `F = \{p \in N : \forall q \in N, q \not\equiv 1 \pmod{p} \}, M = N \setminus F`, we have the following. + + .. math :: + \sum_{d \in 2^{M}} \prod_{p \in M \setminus d} \frac{p^{c(p, F \cup d)} - 1}{p - 1} + + Practically, many prime factors are expected to be members of `F`, thus reducing computation time. + + Parameters + ========== + + prime_factors : set + The set of prime factors of ``n``. where `n` is squarefree. + + Returns + ======= + + int : Number of groups of order ``n`` + + Examples + ======== + + >>> from sympy.combinatorics.group_numbers import _holder_formula + >>> _holder_formula({2}) # n = 2 + 1 + >>> _holder_formula({2, 3}) # n = 2*3 = 6 + 2 + + See Also + ======== + + groups_count + + References + ========== + + .. [1] Otto Holder, Die Gruppen der Ordnungen p^3, pq^2, pqr, p^4, + Math. Ann. 43 pp. 301-412 (1893). + http://dx.doi.org/10.1007/BF01443651 + .. [2] John H. Conway, Heiko Dietrich and E.A. O'Brien, + Counting groups: gnus, moas and other exotica + The Mathematical Intelligencer 30, 6-15 (2008) + https://doi.org/10.1007/BF02985731 + + """ + F = {p for p in prime_factors if all(q % p != 1 for q in prime_factors)} + M = prime_factors - F + + s = 0 + powerset = chain.from_iterable(combinations(M, r) for r in range(len(M)+1)) + for ps in powerset: + ps = set(ps) + prod = 1 + for p in M - ps: + c = len([q for q in F | ps if q % p == 1]) + prod *= (p**c - 1) // (p - 1) + if not prod: + break + s += prod + return s + + +def groups_count(n): + r""" Number of groups of order `n`. + In [1]_, ``gnu(n)`` is given, so we follow this notation here as well. + + Parameters + ========== + + n : Integer + ``n`` is a positive integer + + Returns + ======= + + int : ``gnu(n)`` + + Raises + ====== + + ValueError + Number of groups of order ``n`` is unknown or not implemented. + For example, gnu(`2^{11}`) is not yet known. + On the other hand, gnu(99) is known to be 2, + but this has not yet been implemented in this function. + + Examples + ======== + + >>> from sympy.combinatorics.group_numbers import groups_count + >>> groups_count(3) # There is only one cyclic group of order 3 + 1 + >>> # There are two groups of order 10: the cyclic group and the dihedral group + >>> groups_count(10) + 2 + + See Also + ======== + + is_cyclic_number + `n` is cyclic iff gnu(n) = 1 + + References + ========== + + .. [1] John H. Conway, Heiko Dietrich and E.A. O'Brien, + Counting groups: gnus, moas and other exotica + The Mathematical Intelligencer 30, 6-15 (2008) + https://doi.org/10.1007/BF02985731 + .. [2] https://oeis.org/A000001 + + """ + n = as_int(n) + if n <= 0: + raise ValueError("n must be a positive integer, not %i" % n) + factors = factorint(n) + if len(factors) == 1: + (p, e) = list(factors.items())[0] + if p == 2: + A000679 = [1, 1, 2, 5, 14, 51, 267, 2328, 56092, 10494213, 49487367289] + if e < len(A000679): + return A000679[e] + if p == 3: + A090091 = [1, 1, 2, 5, 15, 67, 504, 9310, 1396077, 5937876645] + if e < len(A090091): + return A090091[e] + if e <= 2: # gnu(p) = 1, gnu(p**2) = 2 + return e + if e == 3: # gnu(p**3) = 5 + return 5 + if e == 4: # if p is an odd prime, gnu(p**4) = 15 + return 15 + if e == 5: # if p >= 5, gnu(p**5) is expressed by the following equation + return 61 + 2*p + 2*gcd(p-1, 3) + gcd(p-1, 4) + if e == 6: # if p >= 6, gnu(p**6) is expressed by the following equation + return 3*p**2 + 39*p + 344 +\ + 24*gcd(p-1, 3) + 11*gcd(p-1, 4) + 2*gcd(p-1, 5) + if e == 7: # if p >= 7, gnu(p**7) is expressed by the following equation + if p == 5: + return 34297 + return 3*p**5 + 12*p**4 + 44*p**3 + 170*p**2 + 707*p + 2455 +\ + (4*p**2 + 44*p + 291)*gcd(p-1, 3) + (p**2 + 19*p + 135)*gcd(p-1, 4) + \ + (3*p + 31)*gcd(p-1, 5) + 4*gcd(p-1, 7) + 5*gcd(p-1, 8) + gcd(p-1, 9) + if any(e > 1 for e in factors.values()): # n is not squarefree + # some known values for small n that have more than 1 factor and are not square free (https://oeis.org/A000001) + small = {12: 5, 18: 5, 20: 5, 24: 15, 28: 4, 36: 14, 40: 14, 44: 4, 45: 2, 48: 52, + 50: 5, 52: 5, 54: 15, 56: 13, 60: 13, 63: 4, 68: 5, 72: 50, 75: 3, 76: 4, + 80: 52, 84: 15, 88: 12, 90: 10, 92: 4} + if n in small: + return small[n] + raise ValueError("Number of groups of order n is unknown or not implemented") + if len(factors) == 2: # n is squarefree semiprime + p, q = sorted(factors.keys()) + return 2 if q % p == 1 else 1 + return _holder_formula(set(factors.keys())) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.py new file mode 100644 index 0000000000000000000000000000000000000000..256f56b3aa7c5404d332f42e37d4f1117ea81db7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.py @@ -0,0 +1,549 @@ +import itertools +from sympy.combinatorics.fp_groups import FpGroup, FpSubgroup, simplify_presentation +from sympy.combinatorics.free_groups import FreeGroup +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.core.intfunc import igcd +from sympy.functions.combinatorial.numbers import totient +from sympy.core.singleton import S + +class GroupHomomorphism: + ''' + A class representing group homomorphisms. Instantiate using `homomorphism()`. + + References + ========== + + .. [1] Holt, D., Eick, B. and O'Brien, E. (2005). Handbook of computational group theory. + + ''' + + def __init__(self, domain, codomain, images): + self.domain = domain + self.codomain = codomain + self.images = images + self._inverses = None + self._kernel = None + self._image = None + + def _invs(self): + ''' + Return a dictionary with `{gen: inverse}` where `gen` is a rewriting + generator of `codomain` (e.g. strong generator for permutation groups) + and `inverse` is an element of its preimage + + ''' + image = self.image() + inverses = {} + for k in list(self.images.keys()): + v = self.images[k] + if not (v in inverses + or v.is_identity): + inverses[v] = k + if isinstance(self.codomain, PermutationGroup): + gens = image.strong_gens + else: + gens = image.generators + for g in gens: + if g in inverses or g.is_identity: + continue + w = self.domain.identity + if isinstance(self.codomain, PermutationGroup): + parts = image._strong_gens_slp[g][::-1] + else: + parts = g + for s in parts: + if s in inverses: + w = w*inverses[s] + else: + w = w*inverses[s**-1]**-1 + inverses[g] = w + + return inverses + + def invert(self, g): + ''' + Return an element of the preimage of ``g`` or of each element + of ``g`` if ``g`` is a list. + + Explanation + =========== + + If the codomain is an FpGroup, the inverse for equal + elements might not always be the same unless the FpGroup's + rewriting system is confluent. However, making a system + confluent can be time-consuming. If it's important, try + `self.codomain.make_confluent()` first. + + ''' + from sympy.combinatorics import Permutation + from sympy.combinatorics.free_groups import FreeGroupElement + if isinstance(g, (Permutation, FreeGroupElement)): + if isinstance(self.codomain, FpGroup): + g = self.codomain.reduce(g) + if self._inverses is None: + self._inverses = self._invs() + image = self.image() + w = self.domain.identity + if isinstance(self.codomain, PermutationGroup): + gens = image.generator_product(g)[::-1] + else: + gens = g + # the following can't be "for s in gens:" + # because that would be equivalent to + # "for s in gens.array_form:" when g is + # a FreeGroupElement. On the other hand, + # when you call gens by index, the generator + # (or inverse) at position i is returned. + for i in range(len(gens)): + s = gens[i] + if s.is_identity: + continue + if s in self._inverses: + w = w*self._inverses[s] + else: + w = w*self._inverses[s**-1]**-1 + return w + elif isinstance(g, list): + return [self.invert(e) for e in g] + + def kernel(self): + ''' + Compute the kernel of `self`. + + ''' + if self._kernel is None: + self._kernel = self._compute_kernel() + return self._kernel + + def _compute_kernel(self): + G = self.domain + G_order = G.order() + if G_order is S.Infinity: + raise NotImplementedError( + "Kernel computation is not implemented for infinite groups") + gens = [] + if isinstance(G, PermutationGroup): + K = PermutationGroup(G.identity) + else: + K = FpSubgroup(G, gens, normal=True) + i = self.image().order() + while K.order()*i != G_order: + r = G.random() + k = r*self.invert(self(r))**-1 + if k not in K: + gens.append(k) + if isinstance(G, PermutationGroup): + K = PermutationGroup(gens) + else: + K = FpSubgroup(G, gens, normal=True) + return K + + def image(self): + ''' + Compute the image of `self`. + + ''' + if self._image is None: + values = list(set(self.images.values())) + if isinstance(self.codomain, PermutationGroup): + self._image = self.codomain.subgroup(values) + else: + self._image = FpSubgroup(self.codomain, values) + return self._image + + def _apply(self, elem): + ''' + Apply `self` to `elem`. + + ''' + if elem not in self.domain: + if isinstance(elem, (list, tuple)): + return [self._apply(e) for e in elem] + raise ValueError("The supplied element does not belong to the domain") + if elem.is_identity: + return self.codomain.identity + else: + images = self.images + value = self.codomain.identity + if isinstance(self.domain, PermutationGroup): + gens = self.domain.generator_product(elem, original=True) + for g in gens: + if g in self.images: + value = images[g]*value + else: + value = images[g**-1]**-1*value + else: + i = 0 + for _, p in elem.array_form: + if p < 0: + g = elem[i]**-1 + else: + g = elem[i] + value = value*images[g]**p + i += abs(p) + return value + + def __call__(self, elem): + return self._apply(elem) + + def is_injective(self): + ''' + Check if the homomorphism is injective + + ''' + return self.kernel().order() == 1 + + def is_surjective(self): + ''' + Check if the homomorphism is surjective + + ''' + im = self.image().order() + oth = self.codomain.order() + if im is S.Infinity and oth is S.Infinity: + return None + else: + return im == oth + + def is_isomorphism(self): + ''' + Check if `self` is an isomorphism. + + ''' + return self.is_injective() and self.is_surjective() + + def is_trivial(self): + ''' + Check is `self` is a trivial homomorphism, i.e. all elements + are mapped to the identity. + + ''' + return self.image().order() == 1 + + def compose(self, other): + ''' + Return the composition of `self` and `other`, i.e. + the homomorphism phi such that for all g in the domain + of `other`, phi(g) = self(other(g)) + + ''' + if not other.image().is_subgroup(self.domain): + raise ValueError("The image of `other` must be a subgroup of " + "the domain of `self`") + images = {g: self(other(g)) for g in other.images} + return GroupHomomorphism(other.domain, self.codomain, images) + + def restrict_to(self, H): + ''' + Return the restriction of the homomorphism to the subgroup `H` + of the domain. + + ''' + if not isinstance(H, PermutationGroup) or not H.is_subgroup(self.domain): + raise ValueError("Given H is not a subgroup of the domain") + domain = H + images = {g: self(g) for g in H.generators} + return GroupHomomorphism(domain, self.codomain, images) + + def invert_subgroup(self, H): + ''' + Return the subgroup of the domain that is the inverse image + of the subgroup ``H`` of the homomorphism image + + ''' + if not H.is_subgroup(self.image()): + raise ValueError("Given H is not a subgroup of the image") + gens = [] + P = PermutationGroup(self.image().identity) + for h in H.generators: + h_i = self.invert(h) + if h_i not in P: + gens.append(h_i) + P = PermutationGroup(gens) + for k in self.kernel().generators: + if k*h_i not in P: + gens.append(k*h_i) + P = PermutationGroup(gens) + return P + +def homomorphism(domain, codomain, gens, images=(), check=True): + ''' + Create (if possible) a group homomorphism from the group ``domain`` + to the group ``codomain`` defined by the images of the domain's + generators ``gens``. ``gens`` and ``images`` can be either lists or tuples + of equal sizes. If ``gens`` is a proper subset of the group's generators, + the unspecified generators will be mapped to the identity. If the + images are not specified, a trivial homomorphism will be created. + + If the given images of the generators do not define a homomorphism, + an exception is raised. + + If ``check`` is ``False``, do not check whether the given images actually + define a homomorphism. + + ''' + if not isinstance(domain, (PermutationGroup, FpGroup, FreeGroup)): + raise TypeError("The domain must be a group") + if not isinstance(codomain, (PermutationGroup, FpGroup, FreeGroup)): + raise TypeError("The codomain must be a group") + + generators = domain.generators + if not all(g in generators for g in gens): + raise ValueError("The supplied generators must be a subset of the domain's generators") + if not all(g in codomain for g in images): + raise ValueError("The images must be elements of the codomain") + + if images and len(images) != len(gens): + raise ValueError("The number of images must be equal to the number of generators") + + gens = list(gens) + images = list(images) + + images.extend([codomain.identity]*(len(generators)-len(images))) + gens.extend([g for g in generators if g not in gens]) + images = dict(zip(gens,images)) + + if check and not _check_homomorphism(domain, codomain, images): + raise ValueError("The given images do not define a homomorphism") + return GroupHomomorphism(domain, codomain, images) + +def _check_homomorphism(domain, codomain, images): + """ + Check that a given mapping of generators to images defines a homomorphism. + + Parameters + ========== + domain : PermutationGroup, FpGroup, FreeGroup + codomain : PermutationGroup, FpGroup, FreeGroup + images : dict + The set of keys must be equal to domain.generators. + The values must be elements of the codomain. + + """ + pres = domain if hasattr(domain, 'relators') else domain.presentation() + rels = pres.relators + gens = pres.generators + symbols = [g.ext_rep[0] for g in gens] + symbols_to_domain_generators = dict(zip(symbols, domain.generators)) + identity = codomain.identity + + def _image(r): + w = identity + for symbol, power in r.array_form: + g = symbols_to_domain_generators[symbol] + w *= images[g]**power + return w + + for r in rels: + if isinstance(codomain, FpGroup): + s = codomain.equals(_image(r), identity) + if s is None: + # only try to make the rewriting system + # confluent when it can't determine the + # truth of equality otherwise + success = codomain.make_confluent() + s = codomain.equals(_image(r), identity) + if s is None and not success: + raise RuntimeError("Can't determine if the images " + "define a homomorphism. Try increasing " + "the maximum number of rewriting rules " + "(group._rewriting_system.set_max(new_value); " + "the current value is stored in group._rewriting" + "_system.maxeqns)") + else: + s = _image(r).is_identity + if not s: + return False + return True + +def orbit_homomorphism(group, omega): + ''' + Return the homomorphism induced by the action of the permutation + group ``group`` on the set ``omega`` that is closed under the action. + + ''' + from sympy.combinatorics import Permutation + from sympy.combinatorics.named_groups import SymmetricGroup + codomain = SymmetricGroup(len(omega)) + identity = codomain.identity + omega = list(omega) + images = {g: identity*Permutation([omega.index(o^g) for o in omega]) for g in group.generators} + group._schreier_sims(base=omega) + H = GroupHomomorphism(group, codomain, images) + if len(group.basic_stabilizers) > len(omega): + H._kernel = group.basic_stabilizers[len(omega)] + else: + H._kernel = PermutationGroup([group.identity]) + return H + +def block_homomorphism(group, blocks): + ''' + Return the homomorphism induced by the action of the permutation + group ``group`` on the block system ``blocks``. The latter should be + of the same form as returned by the ``minimal_block`` method for + permutation groups, namely a list of length ``group.degree`` where + the i-th entry is a representative of the block i belongs to. + + ''' + from sympy.combinatorics import Permutation + from sympy.combinatorics.named_groups import SymmetricGroup + + n = len(blocks) + + # number the blocks; m is the total number, + # b is such that b[i] is the number of the block i belongs to, + # p is the list of length m such that p[i] is the representative + # of the i-th block + m = 0 + p = [] + b = [None]*n + for i in range(n): + if blocks[i] == i: + p.append(i) + b[i] = m + m += 1 + for i in range(n): + b[i] = b[blocks[i]] + + codomain = SymmetricGroup(m) + # the list corresponding to the identity permutation in codomain + identity = range(m) + images = {g: Permutation([b[p[i]^g] for i in identity]) for g in group.generators} + H = GroupHomomorphism(group, codomain, images) + return H + +def group_isomorphism(G, H, isomorphism=True): + ''' + Compute an isomorphism between 2 given groups. + + Parameters + ========== + + G : A finite ``FpGroup`` or a ``PermutationGroup``. + First group. + + H : A finite ``FpGroup`` or a ``PermutationGroup`` + Second group. + + isomorphism : bool + This is used to avoid the computation of homomorphism + when the user only wants to check if there exists + an isomorphism between the groups. + + Returns + ======= + + If isomorphism = False -- Returns a boolean. + If isomorphism = True -- Returns a boolean and an isomorphism between `G` and `H`. + + Examples + ======== + + >>> from sympy.combinatorics import free_group, Permutation + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> from sympy.combinatorics.fp_groups import FpGroup + >>> from sympy.combinatorics.homomorphisms import group_isomorphism + >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup + + >>> D = DihedralGroup(8) + >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) + >>> P = PermutationGroup(p) + >>> group_isomorphism(D, P) + (False, None) + + >>> F, a, b = free_group("a, b") + >>> G = FpGroup(F, [a**3, b**3, (a*b)**2]) + >>> H = AlternatingGroup(4) + >>> (check, T) = group_isomorphism(G, H) + >>> check + True + >>> T(b*a*b**-1*a**-1*b**-1) + (0 2 3) + + Notes + ===== + + Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups. + First, the generators of ``G`` are mapped to the elements of ``H`` and + we check if the mapping induces an isomorphism. + + ''' + if not isinstance(G, (PermutationGroup, FpGroup)): + raise TypeError("The group must be a PermutationGroup or an FpGroup") + if not isinstance(H, (PermutationGroup, FpGroup)): + raise TypeError("The group must be a PermutationGroup or an FpGroup") + + if isinstance(G, FpGroup) and isinstance(H, FpGroup): + G = simplify_presentation(G) + H = simplify_presentation(H) + # Two infinite FpGroups with the same generators are isomorphic + # when the relators are same but are ordered differently. + if G.generators == H.generators and (G.relators).sort() == (H.relators).sort(): + if not isomorphism: + return True + return (True, homomorphism(G, H, G.generators, H.generators)) + + # `_H` is the permutation group isomorphic to `H`. + _H = H + g_order = G.order() + h_order = H.order() + + if g_order is S.Infinity: + raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.") + + if isinstance(H, FpGroup): + if h_order is S.Infinity: + raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.") + _H, h_isomorphism = H._to_perm_group() + + if (g_order != h_order) or (G.is_abelian != H.is_abelian): + if not isomorphism: + return False + return (False, None) + + if not isomorphism: + # Two groups of the same cyclic numbered order + # are isomorphic to each other. + n = g_order + if (igcd(n, totient(n))) == 1: + return True + + # Match the generators of `G` with subsets of `_H` + gens = list(G.generators) + for subset in itertools.permutations(_H, len(gens)): + images = list(subset) + images.extend([_H.identity]*(len(G.generators)-len(images))) + _images = dict(zip(gens,images)) + if _check_homomorphism(G, _H, _images): + if isinstance(H, FpGroup): + images = h_isomorphism.invert(images) + T = homomorphism(G, H, G.generators, images, check=False) + if T.is_isomorphism(): + # It is a valid isomorphism + if not isomorphism: + return True + return (True, T) + + if not isomorphism: + return False + return (False, None) + +def is_isomorphic(G, H): + ''' + Check if the groups are isomorphic to each other + + Parameters + ========== + + G : A finite ``FpGroup`` or a ``PermutationGroup`` + First group. + + H : A finite ``FpGroup`` or a ``PermutationGroup`` + Second group. + + Returns + ======= + + boolean + ''' + return group_isomorphism(G, H, isomorphism=False) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/named_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/named_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..59f10c40ef716e3b644e00f936323e9f6936eb88 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/named_groups.py @@ -0,0 +1,332 @@ +from sympy.combinatorics.group_constructs import DirectProduct +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.combinatorics.permutations import Permutation + +_af_new = Permutation._af_new + + +def AbelianGroup(*cyclic_orders): + """ + Returns the direct product of cyclic groups with the given orders. + + Explanation + =========== + + According to the structure theorem for finite abelian groups ([1]), + every finite abelian group can be written as the direct product of + finitely many cyclic groups. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AbelianGroup + >>> AbelianGroup(3, 4) + PermutationGroup([ + (6)(0 1 2), + (3 4 5 6)]) + >>> _.is_group + True + + See Also + ======== + + DirectProduct + + References + ========== + + .. [1] https://groupprops.subwiki.org/wiki/Structure_theorem_for_finitely_generated_abelian_groups + + """ + groups = [] + degree = 0 + order = 1 + for size in cyclic_orders: + degree += size + order *= size + groups.append(CyclicGroup(size)) + G = DirectProduct(*groups) + G._is_abelian = True + G._degree = degree + G._order = order + + return G + + +def AlternatingGroup(n): + """ + Generates the alternating group on ``n`` elements as a permutation group. + + Explanation + =========== + + For ``n > 2``, the generators taken are ``(0 1 2), (0 1 2 ... n-1)`` for + ``n`` odd + and ``(0 1 2), (1 2 ... n-1)`` for ``n`` even (See [1], p.31, ex.6.9.). + After the group is generated, some of its basic properties are set. + The cases ``n = 1, 2`` are handled separately. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AlternatingGroup + >>> G = AlternatingGroup(4) + >>> G.is_group + True + >>> a = list(G.generate_dimino()) + >>> len(a) + 12 + >>> all(perm.is_even for perm in a) + True + + See Also + ======== + + SymmetricGroup, CyclicGroup, DihedralGroup + + References + ========== + + .. [1] Armstrong, M. "Groups and Symmetry" + + """ + # small cases are special + if n in (1, 2): + return PermutationGroup([Permutation([0])]) + + a = list(range(n)) + a[0], a[1], a[2] = a[1], a[2], a[0] + gen1 = a + if n % 2: + a = list(range(1, n)) + a.append(0) + gen2 = a + else: + a = list(range(2, n)) + a.append(1) + a.insert(0, 0) + gen2 = a + gens = [gen1, gen2] + if gen1 == gen2: + gens = gens[:1] + G = PermutationGroup([_af_new(a) for a in gens], dups=False) + + set_alternating_group_properties(G, n, n) + G._is_alt = True + return G + + +def set_alternating_group_properties(G, n, degree): + """Set known properties of an alternating group. """ + if n < 4: + G._is_abelian = True + G._is_nilpotent = True + else: + G._is_abelian = False + G._is_nilpotent = False + if n < 5: + G._is_solvable = True + else: + G._is_solvable = False + G._degree = degree + G._is_transitive = True + G._is_dihedral = False + + +def CyclicGroup(n): + """ + Generates the cyclic group of order ``n`` as a permutation group. + + Explanation + =========== + + The generator taken is the ``n``-cycle ``(0 1 2 ... n-1)`` + (in cycle notation). After the group is generated, some of its basic + properties are set. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import CyclicGroup + >>> G = CyclicGroup(6) + >>> G.is_group + True + >>> G.order() + 6 + >>> list(G.generate_schreier_sims(af=True)) + [[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 0], [2, 3, 4, 5, 0, 1], + [3, 4, 5, 0, 1, 2], [4, 5, 0, 1, 2, 3], [5, 0, 1, 2, 3, 4]] + + See Also + ======== + + SymmetricGroup, DihedralGroup, AlternatingGroup + + """ + a = list(range(1, n)) + a.append(0) + gen = _af_new(a) + G = PermutationGroup([gen]) + + G._is_abelian = True + G._is_nilpotent = True + G._is_solvable = True + G._degree = n + G._is_transitive = True + G._order = n + G._is_dihedral = (n == 2) + return G + + +def DihedralGroup(n): + r""" + Generates the dihedral group `D_n` as a permutation group. + + Explanation + =========== + + The dihedral group `D_n` is the group of symmetries of the regular + ``n``-gon. The generators taken are the ``n``-cycle ``a = (0 1 2 ... n-1)`` + (a rotation of the ``n``-gon) and ``b = (0 n-1)(1 n-2)...`` + (a reflection of the ``n``-gon) in cycle rotation. It is easy to see that + these satisfy ``a**n = b**2 = 1`` and ``bab = ~a`` so they indeed generate + `D_n` (See [1]). After the group is generated, some of its basic properties + are set. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> G = DihedralGroup(5) + >>> G.is_group + True + >>> a = list(G.generate_dimino()) + >>> [perm.cyclic_form for perm in a] + [[], [[0, 1, 2, 3, 4]], [[0, 2, 4, 1, 3]], + [[0, 3, 1, 4, 2]], [[0, 4, 3, 2, 1]], [[0, 4], [1, 3]], + [[1, 4], [2, 3]], [[0, 1], [2, 4]], [[0, 2], [3, 4]], + [[0, 3], [1, 2]]] + + See Also + ======== + + SymmetricGroup, CyclicGroup, AlternatingGroup + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Dihedral_group + + """ + # small cases are special + if n == 1: + return PermutationGroup([Permutation([1, 0])]) + if n == 2: + return PermutationGroup([Permutation([1, 0, 3, 2]), + Permutation([2, 3, 0, 1]), Permutation([3, 2, 1, 0])]) + + a = list(range(1, n)) + a.append(0) + gen1 = _af_new(a) + a = list(range(n)) + a.reverse() + gen2 = _af_new(a) + G = PermutationGroup([gen1, gen2]) + # if n is a power of 2, group is nilpotent + if n & (n-1) == 0: + G._is_nilpotent = True + else: + G._is_nilpotent = False + G._is_dihedral = True + G._is_abelian = False + G._is_solvable = True + G._degree = n + G._is_transitive = True + G._order = 2*n + return G + + +def SymmetricGroup(n): + """ + Generates the symmetric group on ``n`` elements as a permutation group. + + Explanation + =========== + + The generators taken are the ``n``-cycle + ``(0 1 2 ... n-1)`` and the transposition ``(0 1)`` (in cycle notation). + (See [1]). After the group is generated, some of its basic properties + are set. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> G = SymmetricGroup(4) + >>> G.is_group + True + >>> G.order() + 24 + >>> list(G.generate_schreier_sims(af=True)) + [[0, 1, 2, 3], [1, 2, 3, 0], [2, 3, 0, 1], [3, 1, 2, 0], [0, 2, 3, 1], + [1, 3, 0, 2], [2, 0, 1, 3], [3, 2, 0, 1], [0, 3, 1, 2], [1, 0, 2, 3], + [2, 1, 3, 0], [3, 0, 1, 2], [0, 1, 3, 2], [1, 2, 0, 3], [2, 3, 1, 0], + [3, 1, 0, 2], [0, 2, 1, 3], [1, 3, 2, 0], [2, 0, 3, 1], [3, 2, 1, 0], + [0, 3, 2, 1], [1, 0, 3, 2], [2, 1, 0, 3], [3, 0, 2, 1]] + + See Also + ======== + + CyclicGroup, DihedralGroup, AlternatingGroup + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Symmetric_group#Generators_and_relations + + """ + if n == 1: + G = PermutationGroup([Permutation([0])]) + elif n == 2: + G = PermutationGroup([Permutation([1, 0])]) + else: + a = list(range(1, n)) + a.append(0) + gen1 = _af_new(a) + a = list(range(n)) + a[0], a[1] = a[1], a[0] + gen2 = _af_new(a) + G = PermutationGroup([gen1, gen2]) + set_symmetric_group_properties(G, n, n) + G._is_sym = True + return G + + +def set_symmetric_group_properties(G, n, degree): + """Set known properties of a symmetric group. """ + if n < 3: + G._is_abelian = True + G._is_nilpotent = True + else: + G._is_abelian = False + G._is_nilpotent = False + if n < 5: + G._is_solvable = True + else: + G._is_solvable = False + G._degree = degree + G._is_transitive = True + G._is_dihedral = (n in [2, 3]) # cf Landau's func and Stirling's approx + + +def RubikGroup(n): + """Return a group of Rubik's cube generators + + >>> from sympy.combinatorics.named_groups import RubikGroup + >>> RubikGroup(2).is_group + True + """ + from sympy.combinatorics.generators import rubik + if n <= 1: + raise ValueError("Invalid cube. n has to be greater than 1") + return PermutationGroup(rubik(n)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/partitions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/partitions.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe646baabbb5bf2350cba859a265ac32bbfaf53 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/partitions.py @@ -0,0 +1,745 @@ +from sympy.core import Basic, Dict, sympify, Tuple +from sympy.core.numbers import Integer +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import _sympify +from sympy.functions.combinatorial.numbers import bell +from sympy.matrices import zeros +from sympy.sets.sets import FiniteSet, Union +from sympy.utilities.iterables import flatten, group +from sympy.utilities.misc import as_int + + +from collections import defaultdict + + +class Partition(FiniteSet): + """ + This class represents an abstract partition. + + A partition is a set of disjoint sets whose union equals a given set. + + See Also + ======== + + sympy.utilities.iterables.partitions, + sympy.utilities.iterables.multiset_partitions + """ + + _rank = None + _partition = None + + def __new__(cls, *partition): + """ + Generates a new partition object. + + This method also verifies if the arguments passed are + valid and raises a ValueError if they are not. + + Examples + ======== + + Creating Partition from Python lists: + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3]) + >>> a + Partition({3}, {1, 2}) + >>> a.partition + [[1, 2], [3]] + >>> len(a) + 2 + >>> a.members + (1, 2, 3) + + Creating Partition from Python sets: + + >>> Partition({1, 2, 3}, {4, 5}) + Partition({4, 5}, {1, 2, 3}) + + Creating Partition from SymPy finite sets: + + >>> from sympy import FiniteSet + >>> a = FiniteSet(1, 2, 3) + >>> b = FiniteSet(4, 5) + >>> Partition(a, b) + Partition({4, 5}, {1, 2, 3}) + """ + args = [] + dups = False + for arg in partition: + if isinstance(arg, list): + as_set = set(arg) + if len(as_set) < len(arg): + dups = True + break # error below + arg = as_set + args.append(_sympify(arg)) + + if not all(isinstance(part, FiniteSet) for part in args): + raise ValueError( + "Each argument to Partition should be " \ + "a list, set, or a FiniteSet") + + # sort so we have a canonical reference for RGS + U = Union(*args) + if dups or len(U) < sum(len(arg) for arg in args): + raise ValueError("Partition contained duplicate elements.") + + obj = FiniteSet.__new__(cls, *args) + obj.members = tuple(U) + obj.size = len(U) + return obj + + def sort_key(self, order=None): + """Return a canonical key that can be used for sorting. + + Ordering is based on the size and sorted elements of the partition + and ties are broken with the rank. + + Examples + ======== + + >>> from sympy import default_sort_key + >>> from sympy.combinatorics import Partition + >>> from sympy.abc import x + >>> a = Partition([1, 2]) + >>> b = Partition([3, 4]) + >>> c = Partition([1, x]) + >>> d = Partition(list(range(4))) + >>> l = [d, b, a + 1, a, c] + >>> l.sort(key=default_sort_key); l + [Partition({1, 2}), Partition({1}, {2}), Partition({1, x}), Partition({3, 4}), Partition({0, 1, 2, 3})] + """ + if order is None: + members = self.members + else: + members = tuple(sorted(self.members, + key=lambda w: default_sort_key(w, order))) + return tuple(map(default_sort_key, (self.size, members, self.rank))) + + @property + def partition(self): + """Return partition as a sorted list of lists. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> Partition([1], [2, 3]).partition + [[1], [2, 3]] + """ + if self._partition is None: + self._partition = sorted([sorted(p, key=default_sort_key) + for p in self.args]) + return self._partition + + def __add__(self, other): + """ + Return permutation whose rank is ``other`` greater than current rank, + (mod the maximum rank for the set). + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3]) + >>> a.rank + 1 + >>> (a + 1).rank + 2 + >>> (a + 100).rank + 1 + """ + other = as_int(other) + offset = self.rank + other + result = RGS_unrank((offset) % + RGS_enum(self.size), + self.size) + return Partition.from_rgs(result, self.members) + + def __sub__(self, other): + """ + Return permutation whose rank is ``other`` less than current rank, + (mod the maximum rank for the set). + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3]) + >>> a.rank + 1 + >>> (a - 1).rank + 0 + >>> (a - 100).rank + 1 + """ + return self.__add__(-other) + + def __le__(self, other): + """ + Checks if a partition is less than or equal to + the other based on rank. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3, 4, 5]) + >>> b = Partition([1], [2, 3], [4], [5]) + >>> a.rank, b.rank + (9, 34) + >>> a <= a + True + >>> a <= b + True + """ + return self.sort_key() <= sympify(other).sort_key() + + def __lt__(self, other): + """ + Checks if a partition is less than the other. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3, 4, 5]) + >>> b = Partition([1], [2, 3], [4], [5]) + >>> a.rank, b.rank + (9, 34) + >>> a < b + True + """ + return self.sort_key() < sympify(other).sort_key() + + @property + def rank(self): + """ + Gets the rank of a partition. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3], [4, 5]) + >>> a.rank + 13 + """ + if self._rank is not None: + return self._rank + self._rank = RGS_rank(self.RGS) + return self._rank + + @property + def RGS(self): + """ + Returns the "restricted growth string" of the partition. + + Explanation + =========== + + The RGS is returned as a list of indices, L, where L[i] indicates + the block in which element i appears. For example, in a partition + of 3 elements (a, b, c) into 2 blocks ([c], [a, b]) the RGS is + [1, 1, 0]: "a" is in block 1, "b" is in block 1 and "c" is in block 0. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3], [4, 5]) + >>> a.members + (1, 2, 3, 4, 5) + >>> a.RGS + (0, 0, 1, 2, 2) + >>> a + 1 + Partition({3}, {4}, {5}, {1, 2}) + >>> _.RGS + (0, 0, 1, 2, 3) + """ + rgs = {} + partition = self.partition + for i, part in enumerate(partition): + for j in part: + rgs[j] = i + return tuple([rgs[i] for i in sorted( + [i for p in partition for i in p], key=default_sort_key)]) + + @classmethod + def from_rgs(self, rgs, elements): + """ + Creates a set partition from a restricted growth string. + + Explanation + =========== + + The indices given in rgs are assumed to be the index + of the element as given in elements *as provided* (the + elements are not sorted by this routine). Block numbering + starts from 0. If any block was not referenced in ``rgs`` + an error will be raised. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> Partition.from_rgs([0, 1, 2, 0, 1], list('abcde')) + Partition({c}, {a, d}, {b, e}) + >>> Partition.from_rgs([0, 1, 2, 0, 1], list('cbead')) + Partition({e}, {a, c}, {b, d}) + >>> a = Partition([1, 4], [2], [3, 5]) + >>> Partition.from_rgs(a.RGS, a.members) + Partition({2}, {1, 4}, {3, 5}) + """ + if len(rgs) != len(elements): + raise ValueError('mismatch in rgs and element lengths') + max_elem = max(rgs) + 1 + partition = [[] for i in range(max_elem)] + j = 0 + for i in rgs: + partition[i].append(elements[j]) + j += 1 + if not all(p for p in partition): + raise ValueError('some blocks of the partition were empty.') + return Partition(*partition) + + +class IntegerPartition(Basic): + """ + This class represents an integer partition. + + Explanation + =========== + + In number theory and combinatorics, a partition of a positive integer, + ``n``, also called an integer partition, is a way of writing ``n`` as a + list of positive integers that sum to n. Two partitions that differ only + in the order of summands are considered to be the same partition; if order + matters then the partitions are referred to as compositions. For example, + 4 has five partitions: [4], [3, 1], [2, 2], [2, 1, 1], and [1, 1, 1, 1]; + the compositions [1, 2, 1] and [1, 1, 2] are the same as partition + [2, 1, 1]. + + See Also + ======== + + sympy.utilities.iterables.partitions, + sympy.utilities.iterables.multiset_partitions + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Partition_%28number_theory%29 + """ + + _dict = None + _keys = None + + def __new__(cls, partition, integer=None): + """ + Generates a new IntegerPartition object from a list or dictionary. + + Explanation + =========== + + The partition can be given as a list of positive integers or a + dictionary of (integer, multiplicity) items. If the partition is + preceded by an integer an error will be raised if the partition + does not sum to that given integer. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([5, 4, 3, 1, 1]) + >>> a + IntegerPartition(14, (5, 4, 3, 1, 1)) + >>> print(a) + [5, 4, 3, 1, 1] + >>> IntegerPartition({1:3, 2:1}) + IntegerPartition(5, (2, 1, 1, 1)) + + If the value that the partition should sum to is given first, a check + will be made to see n error will be raised if there is a discrepancy: + + >>> IntegerPartition(10, [5, 4, 3, 1]) + Traceback (most recent call last): + ... + ValueError: The partition is not valid + + """ + if integer is not None: + integer, partition = partition, integer + if isinstance(partition, (dict, Dict)): + _ = [] + for k, v in sorted(partition.items(), reverse=True): + if not v: + continue + k, v = as_int(k), as_int(v) + _.extend([k]*v) + partition = tuple(_) + else: + partition = tuple(sorted(map(as_int, partition), reverse=True)) + sum_ok = False + if integer is None: + integer = sum(partition) + sum_ok = True + else: + integer = as_int(integer) + + if not sum_ok and sum(partition) != integer: + raise ValueError("Partition did not add to %s" % integer) + if any(i < 1 for i in partition): + raise ValueError("All integer summands must be greater than one") + + obj = Basic.__new__(cls, Integer(integer), Tuple(*partition)) + obj.partition = list(partition) + obj.integer = integer + return obj + + def prev_lex(self): + """Return the previous partition of the integer, n, in lexical order, + wrapping around to [1, ..., 1] if the partition is [n]. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> p = IntegerPartition([4]) + >>> print(p.prev_lex()) + [3, 1] + >>> p.partition > p.prev_lex().partition + True + """ + d = defaultdict(int) + d.update(self.as_dict()) + keys = self._keys + if keys == [1]: + return IntegerPartition({self.integer: 1}) + if keys[-1] != 1: + d[keys[-1]] -= 1 + if keys[-1] == 2: + d[1] = 2 + else: + d[keys[-1] - 1] = d[1] = 1 + else: + d[keys[-2]] -= 1 + left = d[1] + keys[-2] + new = keys[-2] + d[1] = 0 + while left: + new -= 1 + if left - new >= 0: + d[new] += left//new + left -= d[new]*new + return IntegerPartition(self.integer, d) + + def next_lex(self): + """Return the next partition of the integer, n, in lexical order, + wrapping around to [n] if the partition is [1, ..., 1]. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> p = IntegerPartition([3, 1]) + >>> print(p.next_lex()) + [4] + >>> p.partition < p.next_lex().partition + True + """ + d = defaultdict(int) + d.update(self.as_dict()) + key = self._keys + a = key[-1] + if a == self.integer: + d.clear() + d[1] = self.integer + elif a == 1: + if d[a] > 1: + d[a + 1] += 1 + d[a] -= 2 + else: + b = key[-2] + d[b + 1] += 1 + d[1] = (d[b] - 1)*b + d[b] = 0 + else: + if d[a] > 1: + if len(key) == 1: + d.clear() + d[a + 1] = 1 + d[1] = self.integer - a - 1 + else: + a1 = a + 1 + d[a1] += 1 + d[1] = d[a]*a - a1 + d[a] = 0 + else: + b = key[-2] + b1 = b + 1 + d[b1] += 1 + need = d[b]*b + d[a]*a - b1 + d[a] = d[b] = 0 + d[1] = need + return IntegerPartition(self.integer, d) + + def as_dict(self): + """Return the partition as a dictionary whose keys are the + partition integers and the values are the multiplicity of that + integer. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> IntegerPartition([1]*3 + [2] + [3]*4).as_dict() + {1: 3, 2: 1, 3: 4} + """ + if self._dict is None: + groups = group(self.partition, multiple=False) + self._keys = [g[0] for g in groups] + self._dict = dict(groups) + return self._dict + + @property + def conjugate(self): + """ + Computes the conjugate partition of itself. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([6, 3, 3, 2, 1]) + >>> a.conjugate + [5, 4, 3, 1, 1, 1] + """ + j = 1 + temp_arr = list(self.partition) + [0] + k = temp_arr[0] + b = [0]*k + while k > 0: + while k > temp_arr[j]: + b[k - 1] = j + k -= 1 + j += 1 + return b + + def __lt__(self, other): + """Return True if self is less than other when the partition + is listed from smallest to biggest. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([3, 1]) + >>> a < a + False + >>> b = a.next_lex() + >>> a < b + True + >>> a == b + False + """ + return list(reversed(self.partition)) < list(reversed(other.partition)) + + def __le__(self, other): + """Return True if self is less than other when the partition + is listed from smallest to biggest. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([4]) + >>> a <= a + True + """ + return list(reversed(self.partition)) <= list(reversed(other.partition)) + + def as_ferrers(self, char='#'): + """ + Prints the ferrer diagram of a partition. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> print(IntegerPartition([1, 1, 5]).as_ferrers()) + ##### + # + # + """ + return "\n".join([char*i for i in self.partition]) + + def __str__(self): + return str(list(self.partition)) + + +def random_integer_partition(n, seed=None): + """ + Generates a random integer partition summing to ``n`` as a list + of reverse-sorted integers. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import random_integer_partition + + For the following, a seed is given so a known value can be shown; in + practice, the seed would not be given. + + >>> random_integer_partition(100, seed=[1, 1, 12, 1, 2, 1, 85, 1]) + [85, 12, 2, 1] + >>> random_integer_partition(10, seed=[1, 2, 3, 1, 5, 1]) + [5, 3, 1, 1] + >>> random_integer_partition(1) + [1] + """ + from sympy.core.random import _randint + + n = as_int(n) + if n < 1: + raise ValueError('n must be a positive integer') + + randint = _randint(seed) + + partition = [] + while (n > 0): + k = randint(1, n) + mult = randint(1, n//k) + partition.append((k, mult)) + n -= k*mult + partition.sort(reverse=True) + partition = flatten([[k]*m for k, m in partition]) + return partition + + +def RGS_generalized(m): + """ + Computes the m + 1 generalized unrestricted growth strings + and returns them as rows in matrix. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_generalized + >>> RGS_generalized(6) + Matrix([ + [ 1, 1, 1, 1, 1, 1, 1], + [ 1, 2, 3, 4, 5, 6, 0], + [ 2, 5, 10, 17, 26, 0, 0], + [ 5, 15, 37, 77, 0, 0, 0], + [ 15, 52, 151, 0, 0, 0, 0], + [ 52, 203, 0, 0, 0, 0, 0], + [203, 0, 0, 0, 0, 0, 0]]) + """ + d = zeros(m + 1) + for i in range(m + 1): + d[0, i] = 1 + + for i in range(1, m + 1): + for j in range(m): + if j <= m - i: + d[i, j] = j * d[i - 1, j] + d[i - 1, j + 1] + else: + d[i, j] = 0 + return d + + +def RGS_enum(m): + """ + RGS_enum computes the total number of restricted growth strings + possible for a superset of size m. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_enum + >>> from sympy.combinatorics import Partition + >>> RGS_enum(4) + 15 + >>> RGS_enum(5) + 52 + >>> RGS_enum(6) + 203 + + We can check that the enumeration is correct by actually generating + the partitions. Here, the 15 partitions of 4 items are generated: + + >>> a = Partition(list(range(4))) + >>> s = set() + >>> for i in range(20): + ... s.add(a) + ... a += 1 + ... + >>> assert len(s) == 15 + + """ + if (m < 1): + return 0 + elif (m == 1): + return 1 + else: + return bell(m) + + +def RGS_unrank(rank, m): + """ + Gives the unranked restricted growth string for a given + superset size. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_unrank + >>> RGS_unrank(14, 4) + [0, 1, 2, 3] + >>> RGS_unrank(0, 4) + [0, 0, 0, 0] + """ + if m < 1: + raise ValueError("The superset size must be >= 1") + if rank < 0 or RGS_enum(m) <= rank: + raise ValueError("Invalid arguments") + + L = [1] * (m + 1) + j = 1 + D = RGS_generalized(m) + for i in range(2, m + 1): + v = D[m - i, j] + cr = j*v + if cr <= rank: + L[i] = j + 1 + rank -= cr + j += 1 + else: + L[i] = int(rank / v + 1) + rank %= v + return [x - 1 for x in L[1:]] + + +def RGS_rank(rgs): + """ + Computes the rank of a restricted growth string. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_rank, RGS_unrank + >>> RGS_rank([0, 1, 2, 1, 3]) + 42 + >>> RGS_rank(RGS_unrank(4, 7)) + 4 + """ + rgs_size = len(rgs) + rank = 0 + D = RGS_generalized(rgs_size) + for i in range(1, rgs_size): + n = len(rgs[(i + 1):]) + m = max(rgs[0:i]) + rank += D[n, m + 1] * rgs[i] + return rank diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..abf7b82258d8bb61ba350509fcbb3110a035fc88 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.py @@ -0,0 +1,710 @@ +from sympy.ntheory.primetest import isprime +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.printing.defaults import DefaultPrinting +from sympy.combinatorics.free_groups import free_group + + +class PolycyclicGroup(DefaultPrinting): + + is_group = True + is_solvable = True + + def __init__(self, pc_sequence, pc_series, relative_order, collector=None): + """ + + Parameters + ========== + + pc_sequence : list + A sequence of elements whose classes generate the cyclic factor + groups of pc_series. + pc_series : list + A subnormal sequence of subgroups where each factor group is cyclic. + relative_order : list + The orders of factor groups of pc_series. + collector : Collector + By default, it is None. Collector class provides the + polycyclic presentation with various other functionalities. + + """ + self.pcgs = pc_sequence + self.pc_series = pc_series + self.relative_order = relative_order + self.collector = Collector(self.pcgs, pc_series, relative_order) if not collector else collector + + def is_prime_order(self): + return all(isprime(order) for order in self.relative_order) + + def length(self): + return len(self.pcgs) + + +class Collector(DefaultPrinting): + + """ + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + Section 8.1.3 + """ + + def __init__(self, pcgs, pc_series, relative_order, free_group_=None, pc_presentation=None): + """ + + Most of the parameters for the Collector class are the same as for PolycyclicGroup. + Others are described below. + + Parameters + ========== + + free_group_ : tuple + free_group_ provides the mapping of polycyclic generating + sequence with the free group elements. + pc_presentation : dict + Provides the presentation of polycyclic groups with the + help of power and conjugate relators. + + See Also + ======== + + PolycyclicGroup + + """ + self.pcgs = pcgs + self.pc_series = pc_series + self.relative_order = relative_order + self.free_group = free_group('x:{}'.format(len(pcgs)))[0] if not free_group_ else free_group_ + self.index = {s: i for i, s in enumerate(self.free_group.symbols)} + self.pc_presentation = self.pc_relators() + + def minimal_uncollected_subword(self, word): + r""" + Returns the minimal uncollected subwords. + + Explanation + =========== + + A word ``v`` defined on generators in ``X`` is a minimal + uncollected subword of the word ``w`` if ``v`` is a subword + of ``w`` and it has one of the following form + + * `v = {x_{i+1}}^{a_j}x_i` + + * `v = {x_{i+1}}^{a_j}{x_i}^{-1}` + + * `v = {x_i}^{a_j}` + + for `a_j` not in `\{1, \ldots, s-1\}`. Where, ``s`` is the power + exponent of the corresponding generator. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x1, x2 = free_group("x1, x2") + >>> word = x2**2*x1**7 + >>> collector.minimal_uncollected_subword(word) + ((x2, 2),) + + """ + # To handle the case word = + if not word: + return None + + array = word.array_form + re = self.relative_order + index = self.index + + for i in range(len(array)): + s1, e1 = array[i] + + if re[index[s1]] and (e1 < 0 or e1 > re[index[s1]]-1): + return ((s1, e1), ) + + for i in range(len(array)-1): + s1, e1 = array[i] + s2, e2 = array[i+1] + + if index[s1] > index[s2]: + e = 1 if e2 > 0 else -1 + return ((s1, e1), (s2, e)) + + return None + + def relations(self): + """ + Separates the given relators of pc presentation in power and + conjugate relations. + + Returns + ======= + + (power_rel, conj_rel) + Separates pc presentation into power and conjugate relations. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> power_rel, conj_rel = collector.relations() + >>> power_rel + {x0**2: (), x1**3: ()} + >>> conj_rel + {x0**-1*x1*x0: x1**2} + + See Also + ======== + + pc_relators + + """ + power_relators = {} + conjugate_relators = {} + for key, value in self.pc_presentation.items(): + if len(key.array_form) == 1: + power_relators[key] = value + else: + conjugate_relators[key] = value + return power_relators, conjugate_relators + + def subword_index(self, word, w): + """ + Returns the start and ending index of a given + subword in a word. + + Parameters + ========== + + word : FreeGroupElement + word defined on free group elements for a + polycyclic group. + w : FreeGroupElement + subword of a given word, whose starting and + ending index to be computed. + + Returns + ======= + + (i, j) + A tuple containing starting and ending index of ``w`` + in the given word. If not exists, (-1,-1) is returned. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x1, x2 = free_group("x1, x2") + >>> word = x2**2*x1**7 + >>> w = x2**2*x1 + >>> collector.subword_index(word, w) + (0, 3) + >>> w = x1**7 + >>> collector.subword_index(word, w) + (2, 9) + >>> w = x1**8 + >>> collector.subword_index(word, w) + (-1, -1) + + """ + low = -1 + high = -1 + for i in range(len(word)-len(w)+1): + if word.subword(i, i+len(w)) == w: + low = i + high = i+len(w) + break + return low, high + + def map_relation(self, w): + """ + Return a conjugate relation. + + Explanation + =========== + + Given a word formed by two free group elements, the + corresponding conjugate relation with those free + group elements is formed and mapped with the collected + word in the polycyclic presentation. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x0, x1 = free_group("x0, x1") + >>> w = x1*x0 + >>> collector.map_relation(w) + x1**2 + + See Also + ======== + + pc_presentation + + """ + array = w.array_form + s1 = array[0][0] + s2 = array[1][0] + key = ((s2, -1), (s1, 1), (s2, 1)) + key = self.free_group.dtype(key) + return self.pc_presentation[key] + + + def collected_word(self, word): + r""" + Return the collected form of a word. + + Explanation + =========== + + A word ``w`` is called collected, if `w = {x_{i_1}}^{a_1} * \ldots * + {x_{i_r}}^{a_r}` with `i_1 < i_2< \ldots < i_r` and `a_j` is in + `\{1, \ldots, {s_j}-1\}`. + + Otherwise w is uncollected. + + Parameters + ========== + + word : FreeGroupElement + An uncollected word. + + Returns + ======= + + word + A collected word of form `w = {x_{i_1}}^{a_1}, \ldots, + {x_{i_r}}^{a_r}` with `i_1, i_2, \ldots, i_r` and `a_j \in + \{1, \ldots, {s_j}-1\}`. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x0, x1, x2, x3 = free_group("x0, x1, x2, x3") + >>> word = x3*x2*x1*x0 + >>> collected_word = collector.collected_word(word) + >>> free_to_perm = {} + >>> free_group = collector.free_group + >>> for sym, gen in zip(free_group.symbols, collector.pcgs): + ... free_to_perm[sym] = gen + >>> G1 = PermutationGroup() + >>> for w in word: + ... sym = w[0] + ... perm = free_to_perm[sym] + ... G1 = PermutationGroup([perm] + G1.generators) + >>> G2 = PermutationGroup() + >>> for w in collected_word: + ... sym = w[0] + ... perm = free_to_perm[sym] + ... G2 = PermutationGroup([perm] + G2.generators) + + The two are not identical, but they are equivalent: + + >>> G1.equals(G2), G1 == G2 + (True, False) + + See Also + ======== + + minimal_uncollected_subword + + """ + free_group = self.free_group + while True: + w = self.minimal_uncollected_subword(word) + if not w: + break + + low, high = self.subword_index(word, free_group.dtype(w)) + if low == -1: + continue + + s1, e1 = w[0] + if len(w) == 1: + re = self.relative_order[self.index[s1]] + q = e1 // re + r = e1-q*re + + key = ((w[0][0], re), ) + key = free_group.dtype(key) + if self.pc_presentation[key]: + presentation = self.pc_presentation[key].array_form + sym, exp = presentation[0] + word_ = ((w[0][0], r), (sym, q*exp)) + word_ = free_group.dtype(word_) + else: + if r != 0: + word_ = ((w[0][0], r), ) + word_ = free_group.dtype(word_) + else: + word_ = None + word = word.eliminate_word(free_group.dtype(w), word_) + + if len(w) == 2 and w[1][1] > 0: + s2, e2 = w[1] + s2 = ((s2, 1), ) + s2 = free_group.dtype(s2) + word_ = self.map_relation(free_group.dtype(w)) + word_ = s2*word_**e1 + word_ = free_group.dtype(word_) + word = word.substituted_word(low, high, word_) + + elif len(w) == 2 and w[1][1] < 0: + s2, e2 = w[1] + s2 = ((s2, 1), ) + s2 = free_group.dtype(s2) + word_ = self.map_relation(free_group.dtype(w)) + word_ = s2**-1*word_**e1 + word_ = free_group.dtype(word_) + word = word.substituted_word(low, high, word_) + + return word + + + def pc_relators(self): + r""" + Return the polycyclic presentation. + + Explanation + =========== + + There are two types of relations used in polycyclic + presentation. + + * Power relations : Power relators are of the form `x_i^{re_i}`, + where `i \in \{0, \ldots, \mathrm{len(pcgs)}\}`, ``x`` represents polycyclic + generator and ``re`` is the corresponding relative order. + + * Conjugate relations : Conjugate relators are of the form `x_j^-1x_ix_j`, + where `j < i \in \{0, \ldots, \mathrm{len(pcgs)}\}`. + + Returns + ======= + + A dictionary with power and conjugate relations as key and + their collected form as corresponding values. + + Notes + ===== + + Identity Permutation is mapped with empty ``()``. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.permutations import Permutation + >>> S = SymmetricGroup(49).sylow_subgroup(7) + >>> der = S.derived_series() + >>> G = der[len(der)-2] + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> pcgs = PcGroup.pcgs + >>> len(pcgs) + 6 + >>> free_group = collector.free_group + >>> pc_resentation = collector.pc_presentation + >>> free_to_perm = {} + >>> for s, g in zip(free_group.symbols, pcgs): + ... free_to_perm[s] = g + + >>> for k, v in pc_resentation.items(): + ... k_array = k.array_form + ... if v != (): + ... v_array = v.array_form + ... lhs = Permutation() + ... for gen in k_array: + ... s = gen[0] + ... e = gen[1] + ... lhs = lhs*free_to_perm[s]**e + ... if v == (): + ... assert lhs.is_identity + ... continue + ... rhs = Permutation() + ... for gen in v_array: + ... s = gen[0] + ... e = gen[1] + ... rhs = rhs*free_to_perm[s]**e + ... assert lhs == rhs + + """ + free_group = self.free_group + rel_order = self.relative_order + pc_relators = {} + perm_to_free = {} + pcgs = self.pcgs + + for gen, s in zip(pcgs, free_group.generators): + perm_to_free[gen**-1] = s**-1 + perm_to_free[gen] = s + + pcgs = pcgs[::-1] + series = self.pc_series[::-1] + rel_order = rel_order[::-1] + collected_gens = [] + + for i, gen in enumerate(pcgs): + re = rel_order[i] + relation = perm_to_free[gen]**re + G = series[i] + + l = G.generator_product(gen**re, original = True) + l.reverse() + + word = free_group.identity + for g in l: + word = word*perm_to_free[g] + + word = self.collected_word(word) + pc_relators[relation] = word if word else () + self.pc_presentation = pc_relators + + collected_gens.append(gen) + if len(collected_gens) > 1: + conj = collected_gens[len(collected_gens)-1] + conjugator = perm_to_free[conj] + + for j in range(len(collected_gens)-1): + conjugated = perm_to_free[collected_gens[j]] + + relation = conjugator**-1*conjugated*conjugator + gens = conj**-1*collected_gens[j]*conj + + l = G.generator_product(gens, original = True) + l.reverse() + word = free_group.identity + for g in l: + word = word*perm_to_free[g] + + word = self.collected_word(word) + pc_relators[relation] = word if word else () + self.pc_presentation = pc_relators + + return pc_relators + + def exponent_vector(self, element): + r""" + Return the exponent vector of length equal to the + length of polycyclic generating sequence. + + Explanation + =========== + + For a given generator/element ``g`` of the polycyclic group, + it can be represented as `g = {x_1}^{e_1}, \ldots, {x_n}^{e_n}`, + where `x_i` represents polycyclic generators and ``n`` is + the number of generators in the free_group equal to the length + of pcgs. + + Parameters + ========== + + element : Permutation + Generator of a polycyclic group. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.permutations import Permutation + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> pcgs = PcGroup.pcgs + >>> collector.exponent_vector(G[0]) + [1, 0, 0, 0] + >>> exp = collector.exponent_vector(G[1]) + >>> g = Permutation() + >>> for i in range(len(exp)): + ... g = g*pcgs[i]**exp[i] if exp[i] else g + >>> assert g == G[1] + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + Section 8.1.1, Definition 8.4 + + """ + free_group = self.free_group + G = PermutationGroup() + for g in self.pcgs: + G = PermutationGroup([g] + G.generators) + gens = G.generator_product(element, original = True) + gens.reverse() + + perm_to_free = {} + for sym, g in zip(free_group.generators, self.pcgs): + perm_to_free[g**-1] = sym**-1 + perm_to_free[g] = sym + w = free_group.identity + for g in gens: + w = w*perm_to_free[g] + + word = self.collected_word(w) + + index = self.index + exp_vector = [0]*len(free_group) + word = word.array_form + for t in word: + exp_vector[index[t[0]]] = t[1] + return exp_vector + + def depth(self, element): + r""" + Return the depth of a given element. + + Explanation + =========== + + The depth of a given element ``g`` is defined by + `\mathrm{dep}[g] = i` if `e_1 = e_2 = \ldots = e_{i-1} = 0` + and `e_i != 0`, where ``e`` represents the exponent-vector. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> collector.depth(G[0]) + 2 + >>> collector.depth(G[1]) + 1 + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + Section 8.1.1, Definition 8.5 + + """ + exp_vector = self.exponent_vector(element) + return next((i+1 for i, x in enumerate(exp_vector) if x), len(self.pcgs)+1) + + def leading_exponent(self, element): + r""" + Return the leading non-zero exponent. + + Explanation + =========== + + The leading exponent for a given element `g` is defined + by `\mathrm{leading\_exponent}[g]` `= e_i`, if `\mathrm{depth}[g] = i`. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> collector.leading_exponent(G[1]) + 1 + + """ + exp_vector = self.exponent_vector(element) + depth = self.depth(element) + if depth != len(self.pcgs)+1: + return exp_vector[depth-1] + return None + + def _sift(self, z, g): + h = g + d = self.depth(h) + while d < len(self.pcgs) and z[d-1] != 1: + k = z[d-1] + e = self.leading_exponent(h)*(self.leading_exponent(k))**-1 + e = e % self.relative_order[d-1] + h = k**-e*h + d = self.depth(h) + return h + + def induced_pcgs(self, gens): + """ + + Parameters + ========== + + gens : list + A list of generators on which polycyclic subgroup + is to be defined. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> S = SymmetricGroup(8) + >>> G = S.sylow_subgroup(2) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> gens = [G[0], G[1]] + >>> ipcgs = collector.induced_pcgs(gens) + >>> [gen.order() for gen in ipcgs] + [2, 2, 2] + >>> G = S.sylow_subgroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> gens = [G[0], G[1]] + >>> ipcgs = collector.induced_pcgs(gens) + >>> [gen.order() for gen in ipcgs] + [3] + + """ + z = [1]*len(self.pcgs) + G = gens + while G: + g = G.pop(0) + h = self._sift(z, g) + d = self.depth(h) + if d < len(self.pcgs): + for gen in z: + if gen != 1: + G.append(h**-1*gen**-1*h*gen) + z[d-1] = h + z = [gen for gen in z if gen != 1] + return z + + def constructive_membership_test(self, ipcgs, g): + """ + Return the exponent vector for induced pcgs. + """ + e = [0]*len(ipcgs) + h = g + d = self.depth(h) + for i, gen in enumerate(ipcgs): + while self.depth(gen) == d: + f = self.leading_exponent(h)*self.leading_exponent(gen) + f = f % self.relative_order[d-1] + h = gen**(-f)*h + e[i] = f + d = self.depth(h) + if h == 1: + return e + return False diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/perm_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/perm_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..24359cb546246d63470de92b2fb2ab0804fc9886 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/perm_groups.py @@ -0,0 +1,5459 @@ +from math import factorial as _factorial, log, prod +from itertools import chain, product + + +from sympy.combinatorics import Permutation +from sympy.combinatorics.permutations import (_af_commutes_with, _af_invert, + _af_rmul, _af_rmuln, _af_pow, Cycle) +from sympy.combinatorics.util import (_check_cycles_alt_sym, + _distribute_gens_by_base, _orbits_transversals_from_bsgs, + _handle_precomputed_bsgs, _base_ordering, _strong_gens_from_distr, + _strip, _strip_af) +from sympy.core import Basic +from sympy.core.random import _randrange, randrange, choice +from sympy.core.symbol import Symbol +from sympy.core.sympify import _sympify +from sympy.functions.combinatorial.factorials import factorial +from sympy.ntheory import primefactors, sieve +from sympy.ntheory.factor_ import (factorint, multiplicity) +from sympy.ntheory.primetest import isprime +from sympy.utilities.iterables import has_variety, is_sequence, uniq + +rmul = Permutation.rmul_with_af +_af_new = Permutation._af_new + + +class PermutationGroup(Basic): + r"""The class defining a Permutation group. + + Explanation + =========== + + ``PermutationGroup([p1, p2, ..., pn])`` returns the permutation group + generated by the list of permutations. This group can be supplied + to Polyhedron if one desires to decorate the elements to which the + indices of the permutation refer. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> from sympy.combinatorics import Polyhedron + + The permutations corresponding to motion of the front, right and + bottom face of a $2 \times 2$ Rubik's cube are defined: + + >>> F = Permutation(2, 19, 21, 8)(3, 17, 20, 10)(4, 6, 7, 5) + >>> R = Permutation(1, 5, 21, 14)(3, 7, 23, 12)(8, 10, 11, 9) + >>> D = Permutation(6, 18, 14, 10)(7, 19, 15, 11)(20, 22, 23, 21) + + These are passed as permutations to PermutationGroup: + + >>> G = PermutationGroup(F, R, D) + >>> G.order() + 3674160 + + The group can be supplied to a Polyhedron in order to track the + objects being moved. An example involving the $2 \times 2$ Rubik's cube is + given there, but here is a simple demonstration: + + >>> a = Permutation(2, 1) + >>> b = Permutation(1, 0) + >>> G = PermutationGroup(a, b) + >>> P = Polyhedron(list('ABC'), pgroup=G) + >>> P.corners + (A, B, C) + >>> P.rotate(0) # apply permutation 0 + >>> P.corners + (A, C, B) + >>> P.reset() + >>> P.corners + (A, B, C) + + Or one can make a permutation as a product of selected permutations + and apply them to an iterable directly: + + >>> P10 = G.make_perm([0, 1]) + >>> P10('ABC') + ['C', 'A', 'B'] + + See Also + ======== + + sympy.combinatorics.polyhedron.Polyhedron, + sympy.combinatorics.permutations.Permutation + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + + .. [2] Seress, A. + "Permutation Group Algorithms" + + .. [3] https://en.wikipedia.org/wiki/Schreier_vector + + .. [4] https://en.wikipedia.org/wiki/Nielsen_transformation#Product_replacement_algorithm + + .. [5] Frank Celler, Charles R.Leedham-Green, Scott H.Murray, + Alice C.Niemeyer, and E.A.O'Brien. "Generating Random + Elements of a Finite Group" + + .. [6] https://en.wikipedia.org/wiki/Block_%28permutation_group_theory%29 + + .. [7] https://algorithmist.com/wiki/Union_find + + .. [8] https://en.wikipedia.org/wiki/Multiply_transitive_group#Multiply_transitive_groups + + .. [9] https://en.wikipedia.org/wiki/Center_%28group_theory%29 + + .. [10] https://en.wikipedia.org/wiki/Centralizer_and_normalizer + + .. [11] https://groupprops.subwiki.org/wiki/Derived_subgroup + + .. [12] https://en.wikipedia.org/wiki/Nilpotent_group + + .. [13] https://www.math.colostate.edu/~hulpke/CGT/cgtnotes.pdf + + .. [14] https://docs.gap-system.org/doc/ref/manual.pdf + + """ + is_group = True + + def __new__(cls, *args, dups=True, **kwargs): + """The default constructor. Accepts Cycle and Permutation forms. + Removes duplicates unless ``dups`` keyword is ``False``. + """ + if not args: + args = [Permutation()] + else: + args = list(args[0] if is_sequence(args[0]) else args) + if not args: + args = [Permutation()] + if any(isinstance(a, Cycle) for a in args): + args = [Permutation(a) for a in args] + if has_variety(a.size for a in args): + degree = kwargs.pop('degree', None) + if degree is None: + degree = max(a.size for a in args) + for i in range(len(args)): + if args[i].size != degree: + args[i] = Permutation(args[i], size=degree) + if dups: + args = list(uniq([_af_new(list(a)) for a in args])) + if len(args) > 1: + args = [g for g in args if not g.is_identity] + return Basic.__new__(cls, *args, **kwargs) + + def __init__(self, *args, **kwargs): + self._generators = list(self.args) + self._order = None + self._elements = [] + self._center = None + self._is_abelian = None + self._is_transitive = None + self._is_sym = None + self._is_alt = None + self._is_primitive = None + self._is_nilpotent = None + self._is_solvable = None + self._is_trivial = None + self._transitivity_degree = None + self._max_div = None + self._is_perfect = None + self._is_cyclic = None + self._is_dihedral = None + self._r = len(self._generators) + self._degree = self._generators[0].size + + # these attributes are assigned after running schreier_sims + self._base = [] + self._strong_gens = [] + self._strong_gens_slp = [] + self._basic_orbits = [] + self._transversals = [] + self._transversal_slp = [] + + # these attributes are assigned after running _random_pr_init + self._random_gens = [] + + # finite presentation of the group as an instance of `FpGroup` + self._fp_presentation = None + + def __getitem__(self, i): + return self._generators[i] + + def __contains__(self, i): + """Return ``True`` if *i* is contained in PermutationGroup. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> p = Permutation(1, 2, 3) + >>> Permutation(3) in PermutationGroup(p) + True + + """ + if not isinstance(i, Permutation): + raise TypeError("A PermutationGroup contains only Permutations as " + "elements, not elements of type %s" % type(i)) + return self.contains(i) + + def __len__(self): + return len(self._generators) + + def equals(self, other): + """Return ``True`` if PermutationGroup generated by elements in the + group are same i.e they represent the same PermutationGroup. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> p = Permutation(0, 1, 2, 3, 4, 5) + >>> G = PermutationGroup([p, p**2]) + >>> H = PermutationGroup([p**2, p]) + >>> G.generators == H.generators + False + >>> G.equals(H) + True + + """ + if not isinstance(other, PermutationGroup): + return False + + set_self_gens = set(self.generators) + set_other_gens = set(other.generators) + + # before reaching the general case there are also certain + # optimisation and obvious cases requiring less or no actual + # computation. + if set_self_gens == set_other_gens: + return True + + # in the most general case it will check that each generator of + # one group belongs to the other PermutationGroup and vice-versa + for gen1 in set_self_gens: + if not other.contains(gen1): + return False + for gen2 in set_other_gens: + if not self.contains(gen2): + return False + return True + + def __mul__(self, other): + """ + Return the direct product of two permutation groups as a permutation + group. + + Explanation + =========== + + This implementation realizes the direct product by shifting the index + set for the generators of the second group: so if we have ``G`` acting + on ``n1`` points and ``H`` acting on ``n2`` points, ``G*H`` acts on + ``n1 + n2`` points. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import CyclicGroup + >>> G = CyclicGroup(5) + >>> H = G*G + >>> H + PermutationGroup([ + (9)(0 1 2 3 4), + (5 6 7 8 9)]) + >>> H.order() + 25 + + """ + if isinstance(other, Permutation): + return Coset(other, self, dir='+') + gens1 = [perm._array_form for perm in self.generators] + gens2 = [perm._array_form for perm in other.generators] + n1 = self._degree + n2 = other._degree + start = list(range(n1)) + end = list(range(n1, n1 + n2)) + for i in range(len(gens2)): + gens2[i] = [x + n1 for x in gens2[i]] + gens2 = [start + gen for gen in gens2] + gens1 = [gen + end for gen in gens1] + together = gens1 + gens2 + gens = [_af_new(x) for x in together] + return PermutationGroup(gens) + + def _random_pr_init(self, r, n, _random_prec_n=None): + r"""Initialize random generators for the product replacement algorithm. + + Explanation + =========== + + The implementation uses a modification of the original product + replacement algorithm due to Leedham-Green, as described in [1], + pp. 69-71; also, see [2], pp. 27-29 for a detailed theoretical + analysis of the original product replacement algorithm, and [4]. + + The product replacement algorithm is used for producing random, + uniformly distributed elements of a group `G` with a set of generators + `S`. For the initialization ``_random_pr_init``, a list ``R`` of + `\max\{r, |S|\}` group generators is created as the attribute + ``G._random_gens``, repeating elements of `S` if necessary, and the + identity element of `G` is appended to ``R`` - we shall refer to this + last element as the accumulator. Then the function ``random_pr()`` + is called ``n`` times, randomizing the list ``R`` while preserving + the generation of `G` by ``R``. The function ``random_pr()`` itself + takes two random elements ``g, h`` among all elements of ``R`` but + the accumulator and replaces ``g`` with a randomly chosen element + from `\{gh, g(~h), hg, (~h)g\}`. Then the accumulator is multiplied + by whatever ``g`` was replaced by. The new value of the accumulator is + then returned by ``random_pr()``. + + The elements returned will eventually (for ``n`` large enough) become + uniformly distributed across `G` ([5]). For practical purposes however, + the values ``n = 50, r = 11`` are suggested in [1]. + + Notes + ===== + + THIS FUNCTION HAS SIDE EFFECTS: it changes the attribute + self._random_gens + + See Also + ======== + + random_pr + + """ + deg = self.degree + random_gens = [x._array_form for x in self.generators] + k = len(random_gens) + if k < r: + for i in range(k, r): + random_gens.append(random_gens[i - k]) + acc = list(range(deg)) + random_gens.append(acc) + self._random_gens = random_gens + + # handle randomized input for testing purposes + if _random_prec_n is None: + for i in range(n): + self.random_pr() + else: + for i in range(n): + self.random_pr(_random_prec=_random_prec_n[i]) + + def _union_find_merge(self, first, second, ranks, parents, not_rep): + """Merges two classes in a union-find data structure. + + Explanation + =========== + + Used in the implementation of Atkinson's algorithm as suggested in [1], + pp. 83-87. The class merging process uses union by rank as an + optimization. ([7]) + + Notes + ===== + + THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, + ``parents``, the list of class sizes, ``ranks``, and the list of + elements that are not representatives, ``not_rep``, are changed due to + class merging. + + See Also + ======== + + minimal_block, _union_find_rep + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of computational group theory" + + .. [7] https://algorithmist.com/wiki/Union_find + + """ + rep_first = self._union_find_rep(first, parents) + rep_second = self._union_find_rep(second, parents) + if rep_first != rep_second: + # union by rank + if ranks[rep_first] >= ranks[rep_second]: + new_1, new_2 = rep_first, rep_second + else: + new_1, new_2 = rep_second, rep_first + total_rank = ranks[new_1] + ranks[new_2] + if total_rank > self.max_div: + return -1 + parents[new_2] = new_1 + ranks[new_1] = total_rank + not_rep.append(new_2) + return 1 + return 0 + + def _union_find_rep(self, num, parents): + """Find representative of a class in a union-find data structure. + + Explanation + =========== + + Used in the implementation of Atkinson's algorithm as suggested in [1], + pp. 83-87. After the representative of the class to which ``num`` + belongs is found, path compression is performed as an optimization + ([7]). + + Notes + ===== + + THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, + ``parents``, is altered due to path compression. + + See Also + ======== + + minimal_block, _union_find_merge + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of computational group theory" + + .. [7] https://algorithmist.com/wiki/Union_find + + """ + rep, parent = num, parents[num] + while parent != rep: + rep = parent + parent = parents[rep] + # path compression + temp, parent = num, parents[num] + while parent != rep: + parents[temp] = rep + temp = parent + parent = parents[temp] + return rep + + @property + def base(self): + r"""Return a base from the Schreier-Sims algorithm. + + Explanation + =========== + + For a permutation group `G`, a base is a sequence of points + `B = (b_1, b_2, \dots, b_k)` such that no element of `G` apart + from the identity fixes all the points in `B`. The concepts of + a base and strong generating set and their applications are + discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. + + An alternative way to think of `B` is that it gives the + indices of the stabilizer cosets that contain more than the + identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> G = PermutationGroup([Permutation(0, 1, 3)(2, 4)]) + >>> G.base + [0, 2] + + See Also + ======== + + strong_gens, basic_transversals, basic_orbits, basic_stabilizers + + """ + if self._base == []: + self.schreier_sims() + return self._base + + def baseswap(self, base, strong_gens, pos, randomized=False, + transversals=None, basic_orbits=None, strong_gens_distr=None): + r"""Swap two consecutive base points in base and strong generating set. + + Explanation + =========== + + If a base for a group `G` is given by `(b_1, b_2, \dots, b_k)`, this + function returns a base `(b_1, b_2, \dots, b_{i+1}, b_i, \dots, b_k)`, + where `i` is given by ``pos``, and a strong generating set relative + to that base. The original base and strong generating set are not + modified. + + The randomized version (default) is of Las Vegas type. + + Parameters + ========== + + base, strong_gens + The base and strong generating set. + pos + The position at which swapping is performed. + randomized + A switch between randomized and deterministic version. + transversals + The transversals for the basic orbits, if known. + basic_orbits + The basic orbits, if known. + strong_gens_distr + The strong generators distributed by basic stabilizers, if known. + + Returns + ======= + + (base, strong_gens) + ``base`` is the new base, and ``strong_gens`` is a generating set + relative to it. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.testutil import _verify_bsgs + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> S = SymmetricGroup(4) + >>> S.schreier_sims() + >>> S.base + [0, 1, 2] + >>> base, gens = S.baseswap(S.base, S.strong_gens, 1, randomized=False) + >>> base, gens + ([0, 2, 1], + [(0 1 2 3), (3)(0 1), (1 3 2), + (2 3), (1 3)]) + + check that base, gens is a BSGS + + >>> S1 = PermutationGroup(gens) + >>> _verify_bsgs(S1, base, gens) + True + + See Also + ======== + + schreier_sims + + Notes + ===== + + The deterministic version of the algorithm is discussed in + [1], pp. 102-103; the randomized version is discussed in [1], p.103, and + [2], p.98. It is of Las Vegas type. + Notice that [1] contains a mistake in the pseudocode and + discussion of BASESWAP: on line 3 of the pseudocode, + `|\beta_{i+1}^{\left\langle T\right\rangle}|` should be replaced by + `|\beta_{i}^{\left\langle T\right\rangle}|`, and the same for the + discussion of the algorithm. + + """ + # construct the basic orbits, generators for the stabilizer chain + # and transversal elements from whatever was provided + transversals, basic_orbits, strong_gens_distr = \ + _handle_precomputed_bsgs(base, strong_gens, transversals, + basic_orbits, strong_gens_distr) + base_len = len(base) + degree = self.degree + # size of orbit of base[pos] under the stabilizer we seek to insert + # in the stabilizer chain at position pos + 1 + size = len(basic_orbits[pos])*len(basic_orbits[pos + 1]) \ + //len(_orbit(degree, strong_gens_distr[pos], base[pos + 1])) + # initialize the wanted stabilizer by a subgroup + if pos + 2 > base_len - 1: + T = [] + else: + T = strong_gens_distr[pos + 2][:] + # randomized version + if randomized is True: + stab_pos = PermutationGroup(strong_gens_distr[pos]) + schreier_vector = stab_pos.schreier_vector(base[pos + 1]) + # add random elements of the stabilizer until they generate it + while len(_orbit(degree, T, base[pos])) != size: + new = stab_pos.random_stab(base[pos + 1], + schreier_vector=schreier_vector) + T.append(new) + # deterministic version + else: + Gamma = set(basic_orbits[pos]) + Gamma.remove(base[pos]) + if base[pos + 1] in Gamma: + Gamma.remove(base[pos + 1]) + # add elements of the stabilizer until they generate it by + # ruling out member of the basic orbit of base[pos] along the way + while len(_orbit(degree, T, base[pos])) != size: + gamma = next(iter(Gamma)) + x = transversals[pos][gamma] + temp = x._array_form.index(base[pos + 1]) # (~x)(base[pos + 1]) + if temp not in basic_orbits[pos + 1]: + Gamma = Gamma - _orbit(degree, T, gamma) + else: + y = transversals[pos + 1][temp] + el = rmul(x, y) + if el(base[pos]) not in _orbit(degree, T, base[pos]): + T.append(el) + Gamma = Gamma - _orbit(degree, T, base[pos]) + # build the new base and strong generating set + strong_gens_new_distr = strong_gens_distr[:] + strong_gens_new_distr[pos + 1] = T + base_new = base[:] + base_new[pos], base_new[pos + 1] = base_new[pos + 1], base_new[pos] + strong_gens_new = _strong_gens_from_distr(strong_gens_new_distr) + for gen in T: + if gen not in strong_gens_new: + strong_gens_new.append(gen) + return base_new, strong_gens_new + + @property + def basic_orbits(self): + r""" + Return the basic orbits relative to a base and strong generating set. + + Explanation + =========== + + If `(b_1, b_2, \dots, b_k)` is a base for a group `G`, and + `G^{(i)} = G_{b_1, b_2, \dots, b_{i-1}}` is the ``i``-th basic stabilizer + (so that `G^{(1)} = G`), the ``i``-th basic orbit relative to this base + is the orbit of `b_i` under `G^{(i)}`. See [1], pp. 87-89 for more + information. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> S = SymmetricGroup(4) + >>> S.basic_orbits + [[0, 1, 2, 3], [1, 2, 3], [2, 3]] + + See Also + ======== + + base, strong_gens, basic_transversals, basic_stabilizers + + """ + if self._basic_orbits == []: + self.schreier_sims() + return self._basic_orbits + + @property + def basic_stabilizers(self): + r""" + Return a chain of stabilizers relative to a base and strong generating + set. + + Explanation + =========== + + The ``i``-th basic stabilizer `G^{(i)}` relative to a base + `(b_1, b_2, \dots, b_k)` is `G_{b_1, b_2, \dots, b_{i-1}}`. For more + information, see [1], pp. 87-89. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AlternatingGroup + >>> A = AlternatingGroup(4) + >>> A.schreier_sims() + >>> A.base + [0, 1] + >>> for g in A.basic_stabilizers: + ... print(g) + ... + PermutationGroup([ + (3)(0 1 2), + (1 2 3)]) + PermutationGroup([ + (1 2 3)]) + + See Also + ======== + + base, strong_gens, basic_orbits, basic_transversals + + """ + + if self._transversals == []: + self.schreier_sims() + strong_gens = self._strong_gens + base = self._base + if not base: # e.g. if self is trivial + return [] + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + basic_stabilizers = [] + for gens in strong_gens_distr: + basic_stabilizers.append(PermutationGroup(gens)) + return basic_stabilizers + + @property + def basic_transversals(self): + """ + Return basic transversals relative to a base and strong generating set. + + Explanation + =========== + + The basic transversals are transversals of the basic orbits. They + are provided as a list of dictionaries, each dictionary having + keys - the elements of one of the basic orbits, and values - the + corresponding transversal elements. See [1], pp. 87-89 for more + information. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AlternatingGroup + >>> A = AlternatingGroup(4) + >>> A.basic_transversals + [{0: (3), 1: (3)(0 1 2), 2: (3)(0 2 1), 3: (0 3 1)}, {1: (3), 2: (1 2 3), 3: (1 3 2)}] + + See Also + ======== + + strong_gens, base, basic_orbits, basic_stabilizers + + """ + + if self._transversals == []: + self.schreier_sims() + return self._transversals + + def composition_series(self): + r""" + Return the composition series for a group as a list + of permutation groups. + + Explanation + =========== + + The composition series for a group `G` is defined as a + subnormal series `G = H_0 > H_1 > H_2 \ldots` A composition + series is a subnormal series such that each factor group + `H(i+1) / H(i)` is simple. + A subnormal series is a composition series only if it is of + maximum length. + + The algorithm works as follows: + Starting with the derived series the idea is to fill + the gap between `G = der[i]` and `H = der[i+1]` for each + `i` independently. Since, all subgroups of the abelian group + `G/H` are normal so, first step is to take the generators + `g` of `G` and add them to generators of `H` one by one. + + The factor groups formed are not simple in general. Each + group is obtained from the previous one by adding one + generator `g`, if the previous group is denoted by `H` + then the next group `K` is generated by `g` and `H`. + The factor group `K/H` is cyclic and it's order is + `K.order()//G.order()`. The series is then extended between + `K` and `H` by groups generated by powers of `g` and `H`. + The series formed is then prepended to the already existing + series. + + Examples + ======== + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.named_groups import CyclicGroup + >>> S = SymmetricGroup(12) + >>> G = S.sylow_subgroup(2) + >>> C = G.composition_series() + >>> [H.order() for H in C] + [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] + >>> G = S.sylow_subgroup(3) + >>> C = G.composition_series() + >>> [H.order() for H in C] + [243, 81, 27, 9, 3, 1] + >>> G = CyclicGroup(12) + >>> C = G.composition_series() + >>> [H.order() for H in C] + [12, 6, 3, 1] + + """ + der = self.derived_series() + if not all(g.is_identity for g in der[-1].generators): + raise NotImplementedError('Group should be solvable') + series = [] + + for i in range(len(der)-1): + H = der[i+1] + up_seg = [] + for g in der[i].generators: + K = PermutationGroup([g] + H.generators) + order = K.order() // H.order() + down_seg = [] + for p, e in factorint(order).items(): + for _ in range(e): + down_seg.append(PermutationGroup([g] + H.generators)) + g = g**p + up_seg = down_seg + up_seg + H = K + up_seg[0] = der[i] + series.extend(up_seg) + series.append(der[-1]) + return series + + def coset_transversal(self, H): + """Return a transversal of the right cosets of self by its subgroup H + using the second method described in [1], Subsection 4.6.7 + + """ + + if not H.is_subgroup(self): + raise ValueError("The argument must be a subgroup") + + if H.order() == 1: + return self.elements + + self._schreier_sims(base=H.base) # make G.base an extension of H.base + + base = self.base + base_ordering = _base_ordering(base, self.degree) + identity = Permutation(self.degree - 1) + + transversals = self.basic_transversals[:] + # transversals is a list of dictionaries. Get rid of the keys + # so that it is a list of lists and sort each list in + # the increasing order of base[l]^x + for l, t in enumerate(transversals): + transversals[l] = sorted(t.values(), + key = lambda x: base_ordering[base[l]^x]) + + orbits = H.basic_orbits + h_stabs = H.basic_stabilizers + g_stabs = self.basic_stabilizers + + indices = [x.order()//y.order() for x, y in zip(g_stabs, h_stabs)] + + # T^(l) should be a right transversal of H^(l) in G^(l) for + # 1<=l<=len(base). While H^(l) is the trivial group, T^(l) + # contains all the elements of G^(l) so we might just as well + # start with l = len(h_stabs)-1 + if len(g_stabs) > len(h_stabs): + T = g_stabs[len(h_stabs)].elements + else: + T = [identity] + l = len(h_stabs)-1 + t_len = len(T) + while l > -1: + T_next = [] + for u in transversals[l]: + if u == identity: + continue + b = base_ordering[base[l]^u] + for t in T: + p = t*u + if all(base_ordering[h^p] >= b for h in orbits[l]): + T_next.append(p) + if t_len + len(T_next) == indices[l]: + break + if t_len + len(T_next) == indices[l]: + break + T += T_next + t_len += len(T_next) + l -= 1 + T.remove(identity) + T = [identity] + T + return T + + def _coset_representative(self, g, H): + """Return the representative of Hg from the transversal that + would be computed by ``self.coset_transversal(H)``. + + """ + if H.order() == 1: + return g + # The base of self must be an extension of H.base. + if not(self.base[:len(H.base)] == H.base): + self._schreier_sims(base=H.base) + orbits = H.basic_orbits[:] + h_transversals = [list(_.values()) for _ in H.basic_transversals] + transversals = [list(_.values()) for _ in self.basic_transversals] + base = self.base + base_ordering = _base_ordering(base, self.degree) + def step(l, x): + gamma = min(orbits[l], key = lambda y: base_ordering[y^x]) + i = [base[l]^h for h in h_transversals[l]].index(gamma) + x = h_transversals[l][i]*x + if l < len(orbits)-1: + for u in transversals[l]: + if base[l]^u == base[l]^x: + break + x = step(l+1, x*u**-1)*u + return x + return step(0, g) + + def coset_table(self, H): + """Return the standardised (right) coset table of self in H as + a list of lists. + """ + # Maybe this should be made to return an instance of CosetTable + # from fp_groups.py but the class would need to be changed first + # to be compatible with PermutationGroups + + if not H.is_subgroup(self): + raise ValueError("The argument must be a subgroup") + T = self.coset_transversal(H) + n = len(T) + + A = list(chain.from_iterable((gen, gen**-1) + for gen in self.generators)) + + table = [] + for i in range(n): + row = [self._coset_representative(T[i]*x, H) for x in A] + row = [T.index(r) for r in row] + table.append(row) + + # standardize (this is the same as the algorithm used in coset_table) + # If CosetTable is made compatible with PermutationGroups, this + # should be replaced by table.standardize() + A = range(len(A)) + gamma = 1 + for alpha, a in product(range(n), A): + beta = table[alpha][a] + if beta >= gamma: + if beta > gamma: + for x in A: + z = table[gamma][x] + table[gamma][x] = table[beta][x] + table[beta][x] = z + for i in range(n): + if table[i][x] == beta: + table[i][x] = gamma + elif table[i][x] == gamma: + table[i][x] = beta + gamma += 1 + if gamma >= n-1: + return table + + def center(self): + r""" + Return the center of a permutation group. + + Explanation + =========== + + The center for a group `G` is defined as + `Z(G) = \{z\in G | \forall g\in G, zg = gz \}`, + the set of elements of `G` that commute with all elements of `G`. + It is equal to the centralizer of `G` inside `G`, and is naturally a + subgroup of `G` ([9]). + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> D = DihedralGroup(4) + >>> G = D.center() + >>> G.order() + 2 + + See Also + ======== + + centralizer + + Notes + ===== + + This is a naive implementation that is a straightforward application + of ``.centralizer()`` + + """ + if not self._center: + self._center = self.centralizer(self) + return self._center + + def centralizer(self, other): + r""" + Return the centralizer of a group/set/element. + + Explanation + =========== + + The centralizer of a set of permutations ``S`` inside + a group ``G`` is the set of elements of ``G`` that commute with all + elements of ``S``:: + + `C_G(S) = \{ g \in G | gs = sg \forall s \in S\}` ([10]) + + Usually, ``S`` is a subset of ``G``, but if ``G`` is a proper subgroup of + the full symmetric group, we allow for ``S`` to have elements outside + ``G``. + + It is naturally a subgroup of ``G``; the centralizer of a permutation + group is equal to the centralizer of any set of generators for that + group, since any element commuting with the generators commutes with + any product of the generators. + + Parameters + ========== + + other + a permutation group/list of permutations/single permutation + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... CyclicGroup) + >>> S = SymmetricGroup(6) + >>> C = CyclicGroup(6) + >>> H = S.centralizer(C) + >>> H.is_subgroup(C) + True + + See Also + ======== + + subgroup_search + + Notes + ===== + + The implementation is an application of ``.subgroup_search()`` with + tests using a specific base for the group ``G``. + + """ + if hasattr(other, 'generators'): + if other.is_trivial or self.is_trivial: + return self + degree = self.degree + identity = _af_new(list(range(degree))) + orbits = other.orbits() + num_orbits = len(orbits) + orbits.sort(key=lambda x: -len(x)) + long_base = [] + orbit_reps = [None]*num_orbits + orbit_reps_indices = [None]*num_orbits + orbit_descr = [None]*degree + for i in range(num_orbits): + orbit = list(orbits[i]) + orbit_reps[i] = orbit[0] + orbit_reps_indices[i] = len(long_base) + for point in orbit: + orbit_descr[point] = i + long_base = long_base + orbit + base, strong_gens = self.schreier_sims_incremental(base=long_base) + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + i = 0 + for i in range(len(base)): + if strong_gens_distr[i] == [identity]: + break + base = base[:i] + base_len = i + for j in range(num_orbits): + if base[base_len - 1] in orbits[j]: + break + rel_orbits = orbits[: j + 1] + num_rel_orbits = len(rel_orbits) + transversals = [None]*num_rel_orbits + for j in range(num_rel_orbits): + rep = orbit_reps[j] + transversals[j] = dict( + other.orbit_transversal(rep, pairs=True)) + trivial_test = lambda x: True + tests = [None]*base_len + for l in range(base_len): + if base[l] in orbit_reps: + tests[l] = trivial_test + else: + def test(computed_words, l=l): + g = computed_words[l] + rep_orb_index = orbit_descr[base[l]] + rep = orbit_reps[rep_orb_index] + im = g._array_form[base[l]] + im_rep = g._array_form[rep] + tr_el = transversals[rep_orb_index][base[l]] + # using the definition of transversal, + # base[l]^g = rep^(tr_el*g); + # if g belongs to the centralizer, then + # base[l]^g = (rep^g)^tr_el + return im == tr_el._array_form[im_rep] + tests[l] = test + + def prop(g): + return [rmul(g, gen) for gen in other.generators] == \ + [rmul(gen, g) for gen in other.generators] + return self.subgroup_search(prop, base=base, + strong_gens=strong_gens, tests=tests) + elif hasattr(other, '__getitem__'): + gens = list(other) + return self.centralizer(PermutationGroup(gens)) + elif hasattr(other, 'array_form'): + return self.centralizer(PermutationGroup([other])) + + def commutator(self, G, H): + """ + Return the commutator of two subgroups. + + Explanation + =========== + + For a permutation group ``K`` and subgroups ``G``, ``H``, the + commutator of ``G`` and ``H`` is defined as the group generated + by all the commutators `[g, h] = hgh^{-1}g^{-1}` for ``g`` in ``G`` and + ``h`` in ``H``. It is naturally a subgroup of ``K`` ([1], p.27). + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... AlternatingGroup) + >>> S = SymmetricGroup(5) + >>> A = AlternatingGroup(5) + >>> G = S.commutator(S, A) + >>> G.is_subgroup(A) + True + + See Also + ======== + + derived_subgroup + + Notes + ===== + + The commutator of two subgroups `H, G` is equal to the normal closure + of the commutators of all the generators, i.e. `hgh^{-1}g^{-1}` for `h` + a generator of `H` and `g` a generator of `G` ([1], p.28) + + """ + ggens = G.generators + hgens = H.generators + commutators = [] + for ggen in ggens: + for hgen in hgens: + commutator = rmul(hgen, ggen, ~hgen, ~ggen) + if commutator not in commutators: + commutators.append(commutator) + res = self.normal_closure(commutators) + return res + + def coset_factor(self, g, factor_index=False): + """Return ``G``'s (self's) coset factorization of ``g`` + + Explanation + =========== + + If ``g`` is an element of ``G`` then it can be written as the product + of permutations drawn from the Schreier-Sims coset decomposition, + + The permutations returned in ``f`` are those for which + the product gives ``g``: ``g = f[n]*...f[1]*f[0]`` where ``n = len(B)`` + and ``B = G.base``. f[i] is one of the permutations in + ``self._basic_orbits[i]``. + + If factor_index==True, + returns a tuple ``[b[0],..,b[n]]``, where ``b[i]`` + belongs to ``self._basic_orbits[i]`` + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) + >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) + >>> G = PermutationGroup([a, b]) + + Define g: + + >>> g = Permutation(7)(1, 2, 4)(3, 6, 5) + + Confirm that it is an element of G: + + >>> G.contains(g) + True + + Thus, it can be written as a product of factors (up to + 3) drawn from u. See below that a factor from u1 and u2 + and the Identity permutation have been used: + + >>> f = G.coset_factor(g) + >>> f[2]*f[1]*f[0] == g + True + >>> f1 = G.coset_factor(g, True); f1 + [0, 4, 4] + >>> tr = G.basic_transversals + >>> f[0] == tr[0][f1[0]] + True + + If g is not an element of G then [] is returned: + + >>> c = Permutation(5, 6, 7) + >>> G.coset_factor(c) + [] + + See Also + ======== + + sympy.combinatorics.util._strip + + """ + if isinstance(g, (Cycle, Permutation)): + g = g.list() + if len(g) != self._degree: + # this could either adjust the size or return [] immediately + # but we don't choose between the two and just signal a possible + # error + raise ValueError('g should be the same size as permutations of G') + I = list(range(self._degree)) + basic_orbits = self.basic_orbits + transversals = self._transversals + factors = [] + base = self.base + h = g + for i in range(len(base)): + beta = h[base[i]] + if beta == base[i]: + factors.append(beta) + continue + if beta not in basic_orbits[i]: + return [] + u = transversals[i][beta]._array_form + h = _af_rmul(_af_invert(u), h) + factors.append(beta) + if h != I: + return [] + if factor_index: + return factors + tr = self.basic_transversals + factors = [tr[i][factors[i]] for i in range(len(base))] + return factors + + def generator_product(self, g, original=False): + r''' + Return a list of strong generators `[s1, \dots, sn]` + s.t `g = sn \times \dots \times s1`. If ``original=True``, make the + list contain only the original group generators + + ''' + product = [] + if g.is_identity: + return [] + if g in self.strong_gens: + if not original or g in self.generators: + return [g] + else: + slp = self._strong_gens_slp[g] + for s in slp: + product.extend(self.generator_product(s, original=True)) + return product + elif g**-1 in self.strong_gens: + g = g**-1 + if not original or g in self.generators: + return [g**-1] + else: + slp = self._strong_gens_slp[g] + for s in slp: + product.extend(self.generator_product(s, original=True)) + l = len(product) + product = [product[l-i-1]**-1 for i in range(l)] + return product + + f = self.coset_factor(g, True) + for i, j in enumerate(f): + slp = self._transversal_slp[i][j] + for s in slp: + if not original: + product.append(self.strong_gens[s]) + else: + s = self.strong_gens[s] + product.extend(self.generator_product(s, original=True)) + return product + + def coset_rank(self, g): + """rank using Schreier-Sims representation. + + Explanation + =========== + + The coset rank of ``g`` is the ordering number in which + it appears in the lexicographic listing according to the + coset decomposition + + The ordering is the same as in G.generate(method='coset'). + If ``g`` does not belong to the group it returns None. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) + >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) + >>> G = PermutationGroup([a, b]) + >>> c = Permutation(7)(2, 4)(3, 5) + >>> G.coset_rank(c) + 16 + >>> G.coset_unrank(16) + (7)(2 4)(3 5) + + See Also + ======== + + coset_factor + + """ + factors = self.coset_factor(g, True) + if not factors: + return None + rank = 0 + b = 1 + transversals = self._transversals + base = self._base + basic_orbits = self._basic_orbits + for i in range(len(base)): + k = factors[i] + j = basic_orbits[i].index(k) + rank += b*j + b = b*len(transversals[i]) + return rank + + def coset_unrank(self, rank, af=False): + """unrank using Schreier-Sims representation + + coset_unrank is the inverse operation of coset_rank + if 0 <= rank < order; otherwise it returns None. + + """ + if rank < 0 or rank >= self.order(): + return None + base = self.base + transversals = self.basic_transversals + basic_orbits = self.basic_orbits + m = len(base) + v = [0]*m + for i in range(m): + rank, c = divmod(rank, len(transversals[i])) + v[i] = basic_orbits[i][c] + a = [transversals[i][v[i]]._array_form for i in range(m)] + h = _af_rmuln(*a) + if af: + return h + else: + return _af_new(h) + + @property + def degree(self): + """Returns the size of the permutations in the group. + + Explanation + =========== + + The number of permutations comprising the group is given by + ``len(group)``; the number of permutations that can be generated + by the group is given by ``group.order()``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a]) + >>> G.degree + 3 + >>> len(G) + 1 + >>> G.order() + 2 + >>> list(G.generate()) + [(2), (2)(0 1)] + + See Also + ======== + + order + """ + return self._degree + + @property + def identity(self): + ''' + Return the identity element of the permutation group. + + ''' + return _af_new(list(range(self.degree))) + + @property + def elements(self): + """Returns all the elements of the permutation group as a list + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2)) + >>> p.elements + [(3), (3)(1 2), (1 3), (2 3), (1 2 3), (1 3 2)] + + """ + if not self._elements: + self._elements = list(self.generate()) + + return self._elements + + def derived_series(self): + r"""Return the derived series for the group. + + Explanation + =========== + + The derived series for a group `G` is defined as + `G = G_0 > G_1 > G_2 > \ldots` where `G_i = [G_{i-1}, G_{i-1}]`, + i.e. `G_i` is the derived subgroup of `G_{i-1}`, for + `i\in\mathbb{N}`. When we have `G_k = G_{k-1}` for some + `k\in\mathbb{N}`, the series terminates. + + Returns + ======= + + A list of permutation groups containing the members of the derived + series in the order `G = G_0, G_1, G_2, \ldots`. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... AlternatingGroup, DihedralGroup) + >>> A = AlternatingGroup(5) + >>> len(A.derived_series()) + 1 + >>> S = SymmetricGroup(4) + >>> len(S.derived_series()) + 4 + >>> S.derived_series()[1].is_subgroup(AlternatingGroup(4)) + True + >>> S.derived_series()[2].is_subgroup(DihedralGroup(2)) + True + + See Also + ======== + + derived_subgroup + + """ + res = [self] + current = self + nxt = self.derived_subgroup() + while not current.is_subgroup(nxt): + res.append(nxt) + current = nxt + nxt = nxt.derived_subgroup() + return res + + def derived_subgroup(self): + r"""Compute the derived subgroup. + + Explanation + =========== + + The derived subgroup, or commutator subgroup is the subgroup generated + by all commutators `[g, h] = hgh^{-1}g^{-1}` for `g, h\in G` ; it is + equal to the normal closure of the set of commutators of the generators + ([1], p.28, [11]). + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([1, 0, 2, 4, 3]) + >>> b = Permutation([0, 1, 3, 2, 4]) + >>> G = PermutationGroup([a, b]) + >>> C = G.derived_subgroup() + >>> list(C.generate(af=True)) + [[0, 1, 2, 3, 4], [0, 1, 3, 4, 2], [0, 1, 4, 2, 3]] + + See Also + ======== + + derived_series + + """ + r = self._r + gens = [p._array_form for p in self.generators] + set_commutators = set() + degree = self._degree + rng = list(range(degree)) + for i in range(r): + for j in range(r): + p1 = gens[i] + p2 = gens[j] + c = list(range(degree)) + for k in rng: + c[p2[p1[k]]] = p1[p2[k]] + ct = tuple(c) + if ct not in set_commutators: + set_commutators.add(ct) + cms = [_af_new(p) for p in set_commutators] + G2 = self.normal_closure(cms) + return G2 + + def generate(self, method="coset", af=False): + """Return iterator to generate the elements of the group. + + Explanation + =========== + + Iteration is done with one of these methods:: + + method='coset' using the Schreier-Sims coset representation + method='dimino' using the Dimino method + + If ``af = True`` it yields the array form of the permutations + + Examples + ======== + + >>> from sympy.combinatorics import PermutationGroup + >>> from sympy.combinatorics.polyhedron import tetrahedron + + The permutation group given in the tetrahedron object is also + true groups: + + >>> G = tetrahedron.pgroup + >>> G.is_group + True + + Also the group generated by the permutations in the tetrahedron + pgroup -- even the first two -- is a proper group: + + >>> H = PermutationGroup(G[0], G[1]) + >>> J = PermutationGroup(list(H.generate())); J + PermutationGroup([ + (0 1)(2 3), + (1 2 3), + (1 3 2), + (0 3 1), + (0 2 3), + (0 3)(1 2), + (0 1 3), + (3)(0 2 1), + (0 3 2), + (3)(0 1 2), + (0 2)(1 3)]) + >>> _.is_group + True + """ + if method == "coset": + return self.generate_schreier_sims(af) + elif method == "dimino": + return self.generate_dimino(af) + else: + raise NotImplementedError('No generation defined for %s' % method) + + def generate_dimino(self, af=False): + """Yield group elements using Dimino's algorithm. + + If ``af == True`` it yields the array form of the permutations. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1, 3]) + >>> b = Permutation([0, 2, 3, 1]) + >>> g = PermutationGroup([a, b]) + >>> list(g.generate_dimino(af=True)) + [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], + [0, 1, 3, 2], [0, 3, 2, 1], [0, 3, 1, 2]] + + References + ========== + + .. [1] The Implementation of Various Algorithms for Permutation Groups in + the Computer Algebra System: AXIOM, N.J. Doye, M.Sc. Thesis + + """ + idn = list(range(self.degree)) + order = 0 + element_list = [idn] + set_element_list = {tuple(idn)} + if af: + yield idn + else: + yield _af_new(idn) + gens = [p._array_form for p in self.generators] + + for i in range(len(gens)): + # D elements of the subgroup G_i generated by gens[:i] + D = element_list.copy() + N = [idn] + while N: + A = N + N = [] + for a in A: + for g in gens[:i + 1]: + ag = _af_rmul(a, g) + if tuple(ag) not in set_element_list: + # produce G_i*g + for d in D: + order += 1 + ap = _af_rmul(d, ag) + if af: + yield ap + else: + p = _af_new(ap) + yield p + element_list.append(ap) + set_element_list.add(tuple(ap)) + N.append(ap) + self._order = len(element_list) + + def generate_schreier_sims(self, af=False): + """Yield group elements using the Schreier-Sims representation + in coset_rank order + + If ``af = True`` it yields the array form of the permutations + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1, 3]) + >>> b = Permutation([0, 2, 3, 1]) + >>> g = PermutationGroup([a, b]) + >>> list(g.generate_schreier_sims(af=True)) + [[0, 1, 2, 3], [0, 2, 1, 3], [0, 3, 2, 1], + [0, 1, 3, 2], [0, 2, 3, 1], [0, 3, 1, 2]] + """ + + n = self._degree + u = self.basic_transversals + basic_orbits = self._basic_orbits + if len(u) == 0: + for x in self.generators: + if af: + yield x._array_form + else: + yield x + return + if len(u) == 1: + for i in basic_orbits[0]: + if af: + yield u[0][i]._array_form + else: + yield u[0][i] + return + + u = list(reversed(u)) + basic_orbits = basic_orbits[::-1] + # stg stack of group elements + stg = [list(range(n))] + posmax = [len(x) for x in u] + n1 = len(posmax) - 1 + pos = [0]*n1 + h = 0 + while 1: + # backtrack when finished iterating over coset + if pos[h] >= posmax[h]: + if h == 0: + return + pos[h] = 0 + h -= 1 + stg.pop() + continue + p = _af_rmul(u[h][basic_orbits[h][pos[h]]]._array_form, stg[-1]) + pos[h] += 1 + stg.append(p) + h += 1 + if h == n1: + if af: + for i in basic_orbits[-1]: + p = _af_rmul(u[-1][i]._array_form, stg[-1]) + yield p + else: + for i in basic_orbits[-1]: + p = _af_rmul(u[-1][i]._array_form, stg[-1]) + p1 = _af_new(p) + yield p1 + stg.pop() + h -= 1 + + @property + def generators(self): + """Returns the generators of the group. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1]) + >>> b = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a, b]) + >>> G.generators + [(1 2), (2)(0 1)] + + """ + return self._generators + + def contains(self, g, strict=True): + """Test if permutation ``g`` belong to self, ``G``. + + Explanation + =========== + + If ``g`` is an element of ``G`` it can be written as a product + of factors drawn from the cosets of ``G``'s stabilizers. To see + if ``g`` is one of the actual generators defining the group use + ``G.has(g)``. + + If ``strict`` is not ``True``, ``g`` will be resized, if necessary, + to match the size of permutations in ``self``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + + >>> a = Permutation(1, 2) + >>> b = Permutation(2, 3, 1) + >>> G = PermutationGroup(a, b, degree=5) + >>> G.contains(G[0]) # trivial check + True + >>> elem = Permutation([[2, 3]], size=5) + >>> G.contains(elem) + True + >>> G.contains(Permutation(4)(0, 1, 2, 3)) + False + + If strict is False, a permutation will be resized, if + necessary: + + >>> H = PermutationGroup(Permutation(5)) + >>> H.contains(Permutation(3)) + False + >>> H.contains(Permutation(3), strict=False) + True + + To test if a given permutation is present in the group: + + >>> elem in G.generators + False + >>> G.has(elem) + False + + See Also + ======== + + coset_factor, sympy.core.basic.Basic.has, __contains__ + + """ + if not isinstance(g, Permutation): + return False + if g.size != self.degree: + if strict: + return False + g = Permutation(g, size=self.degree) + if g in self.generators: + return True + return bool(self.coset_factor(g.array_form, True)) + + @property + def is_perfect(self): + """Return ``True`` if the group is perfect. + A group is perfect if it equals to its derived subgroup. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation(1,2,3)(4,5) + >>> b = Permutation(1,2,3,4,5) + >>> G = PermutationGroup([a, b]) + >>> G.is_perfect + False + + """ + if self._is_perfect is None: + self._is_perfect = self.equals(self.derived_subgroup()) + return self._is_perfect + + @property + def is_abelian(self): + """Test if the group is Abelian. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1]) + >>> b = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a, b]) + >>> G.is_abelian + False + >>> a = Permutation([0, 2, 1]) + >>> G = PermutationGroup([a]) + >>> G.is_abelian + True + + """ + if self._is_abelian is not None: + return self._is_abelian + + self._is_abelian = True + gens = [p._array_form for p in self.generators] + for x in gens: + for y in gens: + if y <= x: + continue + if not _af_commutes_with(x, y): + self._is_abelian = False + return False + return True + + def abelian_invariants(self): + """ + Returns the abelian invariants for the given group. + Let ``G`` be a nontrivial finite abelian group. Then G is isomorphic to + the direct product of finitely many nontrivial cyclic groups of + prime-power order. + + Explanation + =========== + + The prime-powers that occur as the orders of the factors are uniquely + determined by G. More precisely, the primes that occur in the orders of the + factors in any such decomposition of ``G`` are exactly the primes that divide + ``|G|`` and for any such prime ``p``, if the orders of the factors that are + p-groups in one such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, + then the orders of the factors that are p-groups in any such decomposition of ``G`` + are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``. + + The uniquely determined integers ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, taken + for all primes that divide ``|G|`` are called the invariants of the nontrivial + group ``G`` as suggested in ([14], p. 542). + + Notes + ===== + + We adopt the convention that the invariants of a trivial group are []. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1]) + >>> b = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a, b]) + >>> G.abelian_invariants() + [2] + >>> from sympy.combinatorics import CyclicGroup + >>> G = CyclicGroup(7) + >>> G.abelian_invariants() + [7] + + """ + if self.is_trivial: + return [] + gns = self.generators + inv = [] + G = self + H = G.derived_subgroup() + Hgens = H.generators + for p in primefactors(G.order()): + ranks = [] + while True: + pows = [] + for g in gns: + elm = g**p + if not H.contains(elm): + pows.append(elm) + K = PermutationGroup(Hgens + pows) if pows else H + r = G.order()//K.order() + G = K + gns = pows + if r == 1: + break + ranks.append(multiplicity(p, r)) + + if ranks: + pows = [1]*ranks[0] + for i in ranks: + for j in range(i): + pows[j] = pows[j]*p + inv.extend(pows) + inv.sort() + return inv + + def is_elementary(self, p): + """Return ``True`` if the group is elementary abelian. An elementary + abelian group is a finite abelian group, where every nontrivial + element has order `p`, where `p` is a prime. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1]) + >>> G = PermutationGroup([a]) + >>> G.is_elementary(2) + True + >>> a = Permutation([0, 2, 1, 3]) + >>> b = Permutation([3, 1, 2, 0]) + >>> G = PermutationGroup([a, b]) + >>> G.is_elementary(2) + True + >>> G.is_elementary(3) + False + + """ + return self.is_abelian and all(g.order() == p for g in self.generators) + + def _eval_is_alt_sym_naive(self, only_sym=False, only_alt=False): + """A naive test using the group order.""" + if only_sym and only_alt: + raise ValueError( + "Both {} and {} cannot be set to True" + .format(only_sym, only_alt)) + + n = self.degree + sym_order = _factorial(n) + order = self.order() + + if order == sym_order: + self._is_sym = True + self._is_alt = False + return not only_alt + + if 2*order == sym_order: + self._is_sym = False + self._is_alt = True + return not only_sym + + return False + + def _eval_is_alt_sym_monte_carlo(self, eps=0.05, perms=None): + """A test using monte-carlo algorithm. + + Parameters + ========== + + eps : float, optional + The criterion for the incorrect ``False`` return. + + perms : list[Permutation], optional + If explicitly given, it tests over the given candidates + for testing. + + If ``None``, it randomly computes ``N_eps`` and chooses + ``N_eps`` sample of the permutation from the group. + + See Also + ======== + + _check_cycles_alt_sym + """ + if perms is None: + n = self.degree + if n < 17: + c_n = 0.34 + else: + c_n = 0.57 + d_n = (c_n*log(2))/log(n) + N_eps = int(-log(eps)/d_n) + + perms = (self.random_pr() for i in range(N_eps)) + return self._eval_is_alt_sym_monte_carlo(perms=perms) + + for perm in perms: + if _check_cycles_alt_sym(perm): + return True + return False + + def is_alt_sym(self, eps=0.05, _random_prec=None): + r"""Monte Carlo test for the symmetric/alternating group for degrees + >= 8. + + Explanation + =========== + + More specifically, it is one-sided Monte Carlo with the + answer True (i.e., G is symmetric/alternating) guaranteed to be + correct, and the answer False being incorrect with probability eps. + + For degree < 8, the order of the group is checked so the test + is deterministic. + + Notes + ===== + + The algorithm itself uses some nontrivial results from group theory and + number theory: + 1) If a transitive group ``G`` of degree ``n`` contains an element + with a cycle of length ``n/2 < p < n-2`` for ``p`` a prime, ``G`` is the + symmetric or alternating group ([1], pp. 81-82) + 2) The proportion of elements in the symmetric/alternating group having + the property described in 1) is approximately `\log(2)/\log(n)` + ([1], p.82; [2], pp. 226-227). + The helper function ``_check_cycles_alt_sym`` is used to + go over the cycles in a permutation and look for ones satisfying 1). + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> D = DihedralGroup(10) + >>> D.is_alt_sym() + False + + See Also + ======== + + _check_cycles_alt_sym + + """ + if _random_prec is not None: + N_eps = _random_prec['N_eps'] + perms= (_random_prec[i] for i in range(N_eps)) + return self._eval_is_alt_sym_monte_carlo(perms=perms) + + if self._is_sym or self._is_alt: + return True + if self._is_sym is False and self._is_alt is False: + return False + + n = self.degree + if n < 8: + return self._eval_is_alt_sym_naive() + elif self.is_transitive(): + return self._eval_is_alt_sym_monte_carlo(eps=eps) + + self._is_sym, self._is_alt = False, False + return False + + @property + def is_nilpotent(self): + """Test if the group is nilpotent. + + Explanation + =========== + + A group `G` is nilpotent if it has a central series of finite length. + Alternatively, `G` is nilpotent if its lower central series terminates + with the trivial group. Every nilpotent group is also solvable + ([1], p.29, [12]). + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... CyclicGroup) + >>> C = CyclicGroup(6) + >>> C.is_nilpotent + True + >>> S = SymmetricGroup(5) + >>> S.is_nilpotent + False + + See Also + ======== + + lower_central_series, is_solvable + + """ + if self._is_nilpotent is None: + lcs = self.lower_central_series() + terminator = lcs[len(lcs) - 1] + gens = terminator.generators + degree = self.degree + identity = _af_new(list(range(degree))) + if all(g == identity for g in gens): + self._is_solvable = True + self._is_nilpotent = True + return True + else: + self._is_nilpotent = False + return False + else: + return self._is_nilpotent + + def is_normal(self, gr, strict=True): + """Test if ``G=self`` is a normal subgroup of ``gr``. + + Explanation + =========== + + G is normal in gr if + for each g2 in G, g1 in gr, ``g = g1*g2*g1**-1`` belongs to G + It is sufficient to check this for each g1 in gr.generators and + g2 in G.generators. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([1, 2, 0]) + >>> b = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a, b]) + >>> G1 = PermutationGroup([a, Permutation([2, 0, 1])]) + >>> G1.is_normal(G) + True + + """ + if not self.is_subgroup(gr, strict=strict): + return False + d_self = self.degree + d_gr = gr.degree + if self.is_trivial and (d_self == d_gr or not strict): + return True + if self._is_abelian: + return True + new_self = self.copy() + if not strict and d_self != d_gr: + if d_self < d_gr: + new_self = PermGroup(new_self.generators + [Permutation(d_gr - 1)]) + else: + gr = PermGroup(gr.generators + [Permutation(d_self - 1)]) + gens2 = [p._array_form for p in new_self.generators] + gens1 = [p._array_form for p in gr.generators] + for g1 in gens1: + for g2 in gens2: + p = _af_rmuln(g1, g2, _af_invert(g1)) + if not new_self.coset_factor(p, True): + return False + return True + + def is_primitive(self, randomized=True): + r"""Test if a group is primitive. + + Explanation + =========== + + A permutation group ``G`` acting on a set ``S`` is called primitive if + ``S`` contains no nontrivial block under the action of ``G`` + (a block is nontrivial if its cardinality is more than ``1``). + + Notes + ===== + + The algorithm is described in [1], p.83, and uses the function + minimal_block to search for blocks of the form `\{0, k\}` for ``k`` + ranging over representatives for the orbits of `G_0`, the stabilizer of + ``0``. This algorithm has complexity `O(n^2)` where ``n`` is the degree + of the group, and will perform badly if `G_0` is small. + + There are two implementations offered: one finds `G_0` + deterministically using the function ``stabilizer``, and the other + (default) produces random elements of `G_0` using ``random_stab``, + hoping that they generate a subgroup of `G_0` with not too many more + orbits than `G_0` (this is suggested in [1], p.83). Behavior is changed + by the ``randomized`` flag. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> D = DihedralGroup(10) + >>> D.is_primitive() + False + + See Also + ======== + + minimal_block, random_stab + + """ + if self._is_primitive is not None: + return self._is_primitive + + if self.is_transitive() is False: + return False + + if randomized: + random_stab_gens = [] + v = self.schreier_vector(0) + for _ in range(len(self)): + random_stab_gens.append(self.random_stab(0, v)) + stab = PermutationGroup(random_stab_gens) + else: + stab = self.stabilizer(0) + orbits = stab.orbits() + for orb in orbits: + x = orb.pop() + if x != 0 and any(e != 0 for e in self.minimal_block([0, x])): + self._is_primitive = False + return False + self._is_primitive = True + return True + + def minimal_blocks(self, randomized=True): + ''' + For a transitive group, return the list of all minimal + block systems. If a group is intransitive, return `False`. + + Examples + ======== + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> DihedralGroup(6).minimal_blocks() + [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]] + >>> G = PermutationGroup(Permutation(1,2,5)) + >>> G.minimal_blocks() + False + + See Also + ======== + + minimal_block, is_transitive, is_primitive + + ''' + def _number_blocks(blocks): + # number the blocks of a block system + # in order and return the number of + # blocks and the tuple with the + # reordering + n = len(blocks) + appeared = {} + m = 0 + b = [None]*n + for i in range(n): + if blocks[i] not in appeared: + appeared[blocks[i]] = m + b[i] = m + m += 1 + else: + b[i] = appeared[blocks[i]] + return tuple(b), m + + if not self.is_transitive(): + return False + blocks = [] + num_blocks = [] + rep_blocks = [] + if randomized: + random_stab_gens = [] + v = self.schreier_vector(0) + for i in range(len(self)): + random_stab_gens.append(self.random_stab(0, v)) + stab = PermutationGroup(random_stab_gens) + else: + stab = self.stabilizer(0) + orbits = stab.orbits() + for orb in orbits: + x = orb.pop() + if x != 0: + block = self.minimal_block([0, x]) + num_block, _ = _number_blocks(block) + # a representative block (containing 0) + rep = {j for j in range(self.degree) if num_block[j] == 0} + # check if the system is minimal with + # respect to the already discovere ones + minimal = True + blocks_remove_mask = [False] * len(blocks) + for i, r in enumerate(rep_blocks): + if len(r) > len(rep) and rep.issubset(r): + # i-th block system is not minimal + blocks_remove_mask[i] = True + elif len(r) < len(rep) and r.issubset(rep): + # the system being checked is not minimal + minimal = False + break + # remove non-minimal representative blocks + blocks = [b for i, b in enumerate(blocks) if not blocks_remove_mask[i]] + num_blocks = [n for i, n in enumerate(num_blocks) if not blocks_remove_mask[i]] + rep_blocks = [r for i, r in enumerate(rep_blocks) if not blocks_remove_mask[i]] + + if minimal and num_block not in num_blocks: + blocks.append(block) + num_blocks.append(num_block) + rep_blocks.append(rep) + return blocks + + @property + def is_solvable(self): + """Test if the group is solvable. + + ``G`` is solvable if its derived series terminates with the trivial + group ([1], p.29). + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> S = SymmetricGroup(3) + >>> S.is_solvable + True + + See Also + ======== + + is_nilpotent, derived_series + + """ + if self._is_solvable is None: + if self.order() % 2 != 0: + return True + ds = self.derived_series() + terminator = ds[len(ds) - 1] + gens = terminator.generators + degree = self.degree + identity = _af_new(list(range(degree))) + if all(g == identity for g in gens): + self._is_solvable = True + return True + else: + self._is_solvable = False + return False + else: + return self._is_solvable + + def is_subgroup(self, G, strict=True): + """Return ``True`` if all elements of ``self`` belong to ``G``. + + If ``strict`` is ``False`` then if ``self``'s degree is smaller + than ``G``'s, the elements will be resized to have the same degree. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> from sympy.combinatorics import SymmetricGroup, CyclicGroup + + Testing is strict by default: the degree of each group must be the + same: + + >>> p = Permutation(0, 1, 2, 3, 4, 5) + >>> G1 = PermutationGroup([Permutation(0, 1, 2), Permutation(0, 1)]) + >>> G2 = PermutationGroup([Permutation(0, 2), Permutation(0, 1, 2)]) + >>> G3 = PermutationGroup([p, p**2]) + >>> assert G1.order() == G2.order() == G3.order() == 6 + >>> G1.is_subgroup(G2) + True + >>> G1.is_subgroup(G3) + False + >>> G3.is_subgroup(PermutationGroup(G3[1])) + False + >>> G3.is_subgroup(PermutationGroup(G3[0])) + True + + To ignore the size, set ``strict`` to ``False``: + + >>> S3 = SymmetricGroup(3) + >>> S5 = SymmetricGroup(5) + >>> S3.is_subgroup(S5, strict=False) + True + >>> C7 = CyclicGroup(7) + >>> G = S5*C7 + >>> S5.is_subgroup(G, False) + True + >>> C7.is_subgroup(G, 0) + False + + """ + if isinstance(G, SymmetricPermutationGroup): + if self.degree != G.degree: + return False + return True + if not isinstance(G, PermutationGroup): + return False + if self == G or self.generators[0]==Permutation(): + return True + if G.order() % self.order() != 0: + return False + if self.degree == G.degree or \ + (self.degree < G.degree and not strict): + gens = self.generators + else: + return False + return all(G.contains(g, strict=strict) for g in gens) + + @property + def is_polycyclic(self): + """Return ``True`` if a group is polycyclic. A group is polycyclic if + it has a subnormal series with cyclic factors. For finite groups, + this is the same as if the group is solvable. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1, 3]) + >>> b = Permutation([2, 0, 1, 3]) + >>> G = PermutationGroup([a, b]) + >>> G.is_polycyclic + True + + """ + return self.is_solvable + + def is_transitive(self, strict=True): + """Test if the group is transitive. + + Explanation + =========== + + A group is transitive if it has a single orbit. + + If ``strict`` is ``False`` the group is transitive if it has + a single orbit of length different from 1. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1, 3]) + >>> b = Permutation([2, 0, 1, 3]) + >>> G1 = PermutationGroup([a, b]) + >>> G1.is_transitive() + False + >>> G1.is_transitive(strict=False) + True + >>> c = Permutation([2, 3, 0, 1]) + >>> G2 = PermutationGroup([a, c]) + >>> G2.is_transitive() + True + >>> d = Permutation([1, 0, 2, 3]) + >>> e = Permutation([0, 1, 3, 2]) + >>> G3 = PermutationGroup([d, e]) + >>> G3.is_transitive() or G3.is_transitive(strict=False) + False + + """ + if self._is_transitive: # strict or not, if True then True + return self._is_transitive + if strict: + if self._is_transitive is not None: # we only store strict=True + return self._is_transitive + + ans = len(self.orbit(0)) == self.degree + self._is_transitive = ans + return ans + + got_orb = False + for x in self.orbits(): + if len(x) > 1: + if got_orb: + return False + got_orb = True + return got_orb + + @property + def is_trivial(self): + """Test if the group is the trivial group. + + This is true if the group contains only the identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> G = PermutationGroup([Permutation([0, 1, 2])]) + >>> G.is_trivial + True + + """ + if self._is_trivial is None: + self._is_trivial = len(self) == 1 and self[0].is_Identity + return self._is_trivial + + def lower_central_series(self): + r"""Return the lower central series for the group. + + The lower central series for a group `G` is the series + `G = G_0 > G_1 > G_2 > \ldots` where + `G_k = [G, G_{k-1}]`, i.e. every term after the first is equal to the + commutator of `G` and the previous term in `G1` ([1], p.29). + + Returns + ======= + + A list of permutation groups in the order `G = G_0, G_1, G_2, \ldots` + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (AlternatingGroup, + ... DihedralGroup) + >>> A = AlternatingGroup(4) + >>> len(A.lower_central_series()) + 2 + >>> A.lower_central_series()[1].is_subgroup(DihedralGroup(2)) + True + + See Also + ======== + + commutator, derived_series + + """ + res = [self] + current = self + nxt = self.commutator(self, current) + while not current.is_subgroup(nxt): + res.append(nxt) + current = nxt + nxt = self.commutator(self, current) + return res + + @property + def max_div(self): + """Maximum proper divisor of the degree of a permutation group. + + Explanation + =========== + + Obviously, this is the degree divided by its minimal proper divisor + (larger than ``1``, if one exists). As it is guaranteed to be prime, + the ``sieve`` from ``sympy.ntheory`` is used. + This function is also used as an optimization tool for the functions + ``minimal_block`` and ``_union_find_merge``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> G = PermutationGroup([Permutation([0, 2, 1, 3])]) + >>> G.max_div + 2 + + See Also + ======== + + minimal_block, _union_find_merge + + """ + if self._max_div is not None: + return self._max_div + n = self.degree + if n == 1: + return 1 + for x in sieve: + if n % x == 0: + d = n//x + self._max_div = d + return d + + def minimal_block(self, points): + r"""For a transitive group, finds the block system generated by + ``points``. + + Explanation + =========== + + If a group ``G`` acts on a set ``S``, a nonempty subset ``B`` of ``S`` + is called a block under the action of ``G`` if for all ``g`` in ``G`` + we have ``gB = B`` (``g`` fixes ``B``) or ``gB`` and ``B`` have no + common points (``g`` moves ``B`` entirely). ([1], p.23; [6]). + + The distinct translates ``gB`` of a block ``B`` for ``g`` in ``G`` + partition the set ``S`` and this set of translates is known as a block + system. Moreover, we obviously have that all blocks in the partition + have the same size, hence the block size divides ``|S|`` ([1], p.23). + A ``G``-congruence is an equivalence relation ``~`` on the set ``S`` + such that ``a ~ b`` implies ``g(a) ~ g(b)`` for all ``g`` in ``G``. + For a transitive group, the equivalence classes of a ``G``-congruence + and the blocks of a block system are the same thing ([1], p.23). + + The algorithm below checks the group for transitivity, and then finds + the ``G``-congruence generated by the pairs ``(p_0, p_1), (p_0, p_2), + ..., (p_0,p_{k-1})`` which is the same as finding the maximal block + system (i.e., the one with minimum block size) such that + ``p_0, ..., p_{k-1}`` are in the same block ([1], p.83). + + It is an implementation of Atkinson's algorithm, as suggested in [1], + and manipulates an equivalence relation on the set ``S`` using a + union-find data structure. The running time is just above + `O(|points||S|)`. ([1], pp. 83-87; [7]). + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> D = DihedralGroup(10) + >>> D.minimal_block([0, 5]) + [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] + >>> D.minimal_block([0, 1]) + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + See Also + ======== + + _union_find_rep, _union_find_merge, is_transitive, is_primitive + + """ + if not self.is_transitive(): + return False + n = self.degree + gens = self.generators + # initialize the list of equivalence class representatives + parents = list(range(n)) + ranks = [1]*n + not_rep = [] + k = len(points) + # the block size must divide the degree of the group + if k > self.max_div: + return [0]*n + for i in range(k - 1): + parents[points[i + 1]] = points[0] + not_rep.append(points[i + 1]) + ranks[points[0]] = k + i = 0 + len_not_rep = k - 1 + while i < len_not_rep: + gamma = not_rep[i] + i += 1 + for gen in gens: + # find has side effects: performs path compression on the list + # of representatives + delta = self._union_find_rep(gamma, parents) + # union has side effects: performs union by rank on the list + # of representatives + temp = self._union_find_merge(gen(gamma), gen(delta), ranks, + parents, not_rep) + if temp == -1: + return [0]*n + len_not_rep += temp + for i in range(n): + # force path compression to get the final state of the equivalence + # relation + self._union_find_rep(i, parents) + + # rewrite result so that block representatives are minimal + new_reps = {} + return [new_reps.setdefault(r, i) for i, r in enumerate(parents)] + + def conjugacy_class(self, x): + r"""Return the conjugacy class of an element in the group. + + Explanation + =========== + + The conjugacy class of an element ``g`` in a group ``G`` is the set of + elements ``x`` in ``G`` that are conjugate with ``g``, i.e. for which + + ``g = xax^{-1}`` + + for some ``a`` in ``G``. + + Note that conjugacy is an equivalence relation, and therefore that + conjugacy classes are partitions of ``G``. For a list of all the + conjugacy classes of the group, use the conjugacy_classes() method. + + In a permutation group, each conjugacy class corresponds to a particular + `cycle structure': for example, in ``S_3``, the conjugacy classes are: + + * the identity class, ``{()}`` + * all transpositions, ``{(1 2), (1 3), (2 3)}`` + * all 3-cycles, ``{(1 2 3), (1 3 2)}`` + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, SymmetricGroup + >>> S3 = SymmetricGroup(3) + >>> S3.conjugacy_class(Permutation(0, 1, 2)) + {(0 1 2), (0 2 1)} + + Notes + ===== + + This procedure computes the conjugacy class directly by finding the + orbit of the element under conjugation in G. This algorithm is only + feasible for permutation groups of relatively small order, but is like + the orbit() function itself in that respect. + """ + # Ref: "Computing the conjugacy classes of finite groups"; Butler, G. + # Groups '93 Galway/St Andrews; edited by Campbell, C. M. + new_class = {x} + last_iteration = new_class + + while len(last_iteration) > 0: + this_iteration = set() + + for y in last_iteration: + for s in self.generators: + conjugated = s * y * (~s) + if conjugated not in new_class: + this_iteration.add(conjugated) + + new_class.update(last_iteration) + last_iteration = this_iteration + + return new_class + + + def conjugacy_classes(self): + r"""Return the conjugacy classes of the group. + + Explanation + =========== + + As described in the documentation for the .conjugacy_class() function, + conjugacy is an equivalence relation on a group G which partitions the + set of elements. This method returns a list of all these conjugacy + classes of G. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricGroup + >>> SymmetricGroup(3).conjugacy_classes() + [{(2)}, {(0 1 2), (0 2 1)}, {(0 2), (1 2), (2)(0 1)}] + + """ + identity = _af_new(list(range(self.degree))) + known_elements = {identity} + classes = [known_elements.copy()] + + for x in self.generate(): + if x not in known_elements: + new_class = self.conjugacy_class(x) + classes.append(new_class) + known_elements.update(new_class) + + return classes + + def normal_closure(self, other, k=10): + r"""Return the normal closure of a subgroup/set of permutations. + + Explanation + =========== + + If ``S`` is a subset of a group ``G``, the normal closure of ``A`` in ``G`` + is defined as the intersection of all normal subgroups of ``G`` that + contain ``A`` ([1], p.14). Alternatively, it is the group generated by + the conjugates ``x^{-1}yx`` for ``x`` a generator of ``G`` and ``y`` a + generator of the subgroup ``\left\langle S\right\rangle`` generated by + ``S`` (for some chosen generating set for ``\left\langle S\right\rangle``) + ([1], p.73). + + Parameters + ========== + + other + a subgroup/list of permutations/single permutation + k + an implementation-specific parameter that determines the number + of conjugates that are adjoined to ``other`` at once + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... CyclicGroup, AlternatingGroup) + >>> S = SymmetricGroup(5) + >>> C = CyclicGroup(5) + >>> G = S.normal_closure(C) + >>> G.order() + 60 + >>> G.is_subgroup(AlternatingGroup(5)) + True + + See Also + ======== + + commutator, derived_subgroup, random_pr + + Notes + ===== + + The algorithm is described in [1], pp. 73-74; it makes use of the + generation of random elements for permutation groups by the product + replacement algorithm. + + """ + if hasattr(other, 'generators'): + degree = self.degree + identity = _af_new(list(range(degree))) + + if all(g == identity for g in other.generators): + return other + Z = PermutationGroup(other.generators[:]) + base, strong_gens = Z.schreier_sims_incremental() + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + basic_orbits, basic_transversals = \ + _orbits_transversals_from_bsgs(base, strong_gens_distr) + + self._random_pr_init(r=10, n=20) + + _loop = True + while _loop: + Z._random_pr_init(r=10, n=10) + for _ in range(k): + g = self.random_pr() + h = Z.random_pr() + conj = h^g + res = _strip(conj, base, basic_orbits, basic_transversals) + if res[0] != identity or res[1] != len(base) + 1: + gens = Z.generators + gens.append(conj) + Z = PermutationGroup(gens) + strong_gens.append(conj) + temp_base, temp_strong_gens = \ + Z.schreier_sims_incremental(base, strong_gens) + base, strong_gens = temp_base, temp_strong_gens + strong_gens_distr = \ + _distribute_gens_by_base(base, strong_gens) + basic_orbits, basic_transversals = \ + _orbits_transversals_from_bsgs(base, + strong_gens_distr) + _loop = False + for g in self.generators: + for h in Z.generators: + conj = h^g + res = _strip(conj, base, basic_orbits, + basic_transversals) + if res[0] != identity or res[1] != len(base) + 1: + _loop = True + break + if _loop: + break + return Z + elif hasattr(other, '__getitem__'): + return self.normal_closure(PermutationGroup(other)) + elif hasattr(other, 'array_form'): + return self.normal_closure(PermutationGroup([other])) + + def orbit(self, alpha, action='tuples'): + r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. + + Explanation + =========== + + The time complexity of the algorithm used here is `O(|Orb|*r)` where + `|Orb|` is the size of the orbit and ``r`` is the number of generators of + the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. + Here alpha can be a single point, or a list of points. + + If alpha is a single point, the ordinary orbit is computed. + if alpha is a list of points, there are three available options: + + 'union' - computes the union of the orbits of the points in the list + 'tuples' - computes the orbit of the list interpreted as an ordered + tuple under the group action ( i.e., g((1,2,3)) = (g(1), g(2), g(3)) ) + 'sets' - computes the orbit of the list interpreted as a sets + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) + >>> G = PermutationGroup([a]) + >>> G.orbit(0) + {0, 1, 2} + >>> G.orbit([0, 4], 'union') + {0, 1, 2, 3, 4, 5, 6} + + See Also + ======== + + orbit_transversal + + """ + return _orbit(self.degree, self.generators, alpha, action) + + def orbit_rep(self, alpha, beta, schreier_vector=None): + """Return a group element which sends ``alpha`` to ``beta``. + + Explanation + =========== + + If ``beta`` is not in the orbit of ``alpha``, the function returns + ``False``. This implementation makes use of the schreier vector. + For a proof of correctness, see [1], p.80 + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AlternatingGroup + >>> G = AlternatingGroup(5) + >>> G.orbit_rep(0, 4) + (0 4 1 2 3) + + See Also + ======== + + schreier_vector + + """ + if schreier_vector is None: + schreier_vector = self.schreier_vector(alpha) + if schreier_vector[beta] is None: + return False + k = schreier_vector[beta] + gens = [x._array_form for x in self.generators] + a = [] + while k != -1: + a.append(gens[k]) + beta = gens[k].index(beta) # beta = (~gens[k])(beta) + k = schreier_vector[beta] + if a: + return _af_new(_af_rmuln(*a)) + else: + return _af_new(list(range(self._degree))) + + def orbit_transversal(self, alpha, pairs=False): + r"""Computes a transversal for the orbit of ``alpha`` as a set. + + Explanation + =========== + + For a permutation group `G`, a transversal for the orbit + `Orb = \{g(\alpha) | g \in G\}` is a set + `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. + Note that there may be more than one possible transversal. + If ``pairs`` is set to ``True``, it returns the list of pairs + `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> G = DihedralGroup(6) + >>> G.orbit_transversal(0) + [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] + + See Also + ======== + + orbit + + """ + return _orbit_transversal(self._degree, self.generators, alpha, pairs) + + def orbits(self, rep=False): + """Return the orbits of ``self``, ordered according to lowest element + in each orbit. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation(1, 5)(2, 3)(4, 0, 6) + >>> b = Permutation(1, 5)(3, 4)(2, 6, 0) + >>> G = PermutationGroup([a, b]) + >>> G.orbits() + [{0, 2, 3, 4, 6}, {1, 5}] + """ + return _orbits(self._degree, self._generators) + + def order(self): + """Return the order of the group: the number of permutations that + can be generated from elements of the group. + + The number of permutations comprising the group is given by + ``len(group)``; the length of each permutation in the group is + given by ``group.size``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + + >>> a = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a]) + >>> G.degree + 3 + >>> len(G) + 1 + >>> G.order() + 2 + >>> list(G.generate()) + [(2), (2)(0 1)] + + >>> a = Permutation([0, 2, 1]) + >>> b = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a, b]) + >>> G.order() + 6 + + See Also + ======== + + degree + + """ + if self._order is not None: + return self._order + if self._is_sym: + n = self._degree + self._order = factorial(n) + return self._order + if self._is_alt: + n = self._degree + self._order = factorial(n)/2 + return self._order + + m = prod([len(x) for x in self.basic_transversals]) + self._order = m + return m + + def index(self, H): + """ + Returns the index of a permutation group. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation(1,2,3) + >>> b =Permutation(3) + >>> G = PermutationGroup([a]) + >>> H = PermutationGroup([b]) + >>> G.index(H) + 3 + + """ + if H.is_subgroup(self): + return self.order()//H.order() + + @property + def is_symmetric(self): + """Return ``True`` if the group is symmetric. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricGroup + >>> g = SymmetricGroup(5) + >>> g.is_symmetric + True + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> g = PermutationGroup( + ... Permutation(0, 1, 2, 3, 4), + ... Permutation(2, 3)) + >>> g.is_symmetric + True + + Notes + ===== + + This uses a naive test involving the computation of the full + group order. + If you need more quicker taxonomy for large groups, you can use + :meth:`PermutationGroup.is_alt_sym`. + However, :meth:`PermutationGroup.is_alt_sym` may not be accurate + and is not able to distinguish between an alternating group and + a symmetric group. + + See Also + ======== + + is_alt_sym + """ + _is_sym = self._is_sym + if _is_sym is not None: + return _is_sym + + n = self.degree + if n >= 8: + if self.is_transitive(): + _is_alt_sym = self._eval_is_alt_sym_monte_carlo() + if _is_alt_sym: + if any(g.is_odd for g in self.generators): + self._is_sym, self._is_alt = True, False + return True + + self._is_sym, self._is_alt = False, True + return False + + return self._eval_is_alt_sym_naive(only_sym=True) + + self._is_sym, self._is_alt = False, False + return False + + return self._eval_is_alt_sym_naive(only_sym=True) + + + @property + def is_alternating(self): + """Return ``True`` if the group is alternating. + + Examples + ======== + + >>> from sympy.combinatorics import AlternatingGroup + >>> g = AlternatingGroup(5) + >>> g.is_alternating + True + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> g = PermutationGroup( + ... Permutation(0, 1, 2, 3, 4), + ... Permutation(2, 3, 4)) + >>> g.is_alternating + True + + Notes + ===== + + This uses a naive test involving the computation of the full + group order. + If you need more quicker taxonomy for large groups, you can use + :meth:`PermutationGroup.is_alt_sym`. + However, :meth:`PermutationGroup.is_alt_sym` may not be accurate + and is not able to distinguish between an alternating group and + a symmetric group. + + See Also + ======== + + is_alt_sym + """ + _is_alt = self._is_alt + if _is_alt is not None: + return _is_alt + + n = self.degree + if n >= 8: + if self.is_transitive(): + _is_alt_sym = self._eval_is_alt_sym_monte_carlo() + if _is_alt_sym: + if all(g.is_even for g in self.generators): + self._is_sym, self._is_alt = False, True + return True + + self._is_sym, self._is_alt = True, False + return False + + return self._eval_is_alt_sym_naive(only_alt=True) + + self._is_sym, self._is_alt = False, False + return False + + return self._eval_is_alt_sym_naive(only_alt=True) + + @classmethod + def _distinct_primes_lemma(cls, primes): + """Subroutine to test if there is only one cyclic group for the + order.""" + primes = sorted(primes) + l = len(primes) + for i in range(l): + for j in range(i+1, l): + if primes[j] % primes[i] == 1: + return None + return True + + @property + def is_cyclic(self): + r""" + Return ``True`` if the group is Cyclic. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AbelianGroup + >>> G = AbelianGroup(3, 4) + >>> G.is_cyclic + True + >>> G = AbelianGroup(4, 4) + >>> G.is_cyclic + False + + Notes + ===== + + If the order of a group $n$ can be factored into the distinct + primes $p_1, p_2, \dots , p_s$ and if + + .. math:: + \forall i, j \in \{1, 2, \dots, s \}: + p_i \not \equiv 1 \pmod {p_j} + + holds true, there is only one group of the order $n$ which + is a cyclic group [1]_. This is a generalization of the lemma + that the group of order $15, 35, \dots$ are cyclic. + + And also, these additional lemmas can be used to test if a + group is cyclic if the order of the group is already found. + + - If the group is abelian and the order of the group is + square-free, the group is cyclic. + - If the order of the group is less than $6$ and is not $4$, the + group is cyclic. + - If the order of the group is prime, the group is cyclic. + + References + ========== + + .. [1] 1978: John S. Rose: A Course on Group Theory, + Introduction to Finite Group Theory: 1.4 + """ + if self._is_cyclic is not None: + return self._is_cyclic + + if len(self.generators) == 1: + self._is_cyclic = True + self._is_abelian = True + return True + + if self._is_abelian is False: + self._is_cyclic = False + return False + + order = self.order() + + if order < 6: + self._is_abelian = True + if order != 4: + self._is_cyclic = True + return True + + factors = factorint(order) + if all(v == 1 for v in factors.values()): + if self._is_abelian: + self._is_cyclic = True + return True + + primes = list(factors.keys()) + if PermutationGroup._distinct_primes_lemma(primes) is True: + self._is_cyclic = True + self._is_abelian = True + return True + + if not self.is_abelian: + self._is_cyclic = False + return False + + self._is_cyclic = all( + any(g**(order//p) != self.identity for g in self.generators) + for p, e in factors.items() if e > 1 + ) + return self._is_cyclic + + @property + def is_dihedral(self): + r""" + Return ``True`` if the group is dihedral. + + Examples + ======== + + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy.combinatorics.named_groups import SymmetricGroup, CyclicGroup + >>> G = PermutationGroup(Permutation(1, 6)(2, 5)(3, 4), Permutation(0, 1, 2, 3, 4, 5, 6)) + >>> G.is_dihedral + True + >>> G = SymmetricGroup(3) + >>> G.is_dihedral + True + >>> G = CyclicGroup(6) + >>> G.is_dihedral + False + + References + ========== + + .. [Di1] https://math.stackexchange.com/questions/827230/given-a-cayley-table-is-there-an-algorithm-to-determine-if-it-is-a-dihedral-gro/827273#827273 + .. [Di2] https://kconrad.math.uconn.edu/blurbs/grouptheory/dihedral.pdf + .. [Di3] https://kconrad.math.uconn.edu/blurbs/grouptheory/dihedral2.pdf + .. [Di4] https://en.wikipedia.org/wiki/Dihedral_group + """ + if self._is_dihedral is not None: + return self._is_dihedral + + order = self.order() + + if order % 2 == 1: + self._is_dihedral = False + return False + if order == 2: + self._is_dihedral = True + return True + if order == 4: + # The dihedral group of order 4 is the Klein 4-group. + self._is_dihedral = not self.is_cyclic + return self._is_dihedral + if self.is_abelian: + # The only abelian dihedral groups are the ones of orders 2 and 4. + self._is_dihedral = False + return False + + # Now we know the group is of even order >= 6, and nonabelian. + n = order // 2 + + # Handle special cases where there are exactly two generators. + gens = self.generators + if len(gens) == 2: + x, y = gens + a, b = x.order(), y.order() + # Make a >= b + if a < b: + x, y, a, b = y, x, b, a + # Using Theorem 2.1 of [Di3]: + if a == 2 == b: + self._is_dihedral = True + return True + # Using Theorem 1.1 of [Di3]: + if a == n and b == 2 and y*x*y == ~x: + self._is_dihedral = True + return True + + # Proceed with algorithm of [Di1] + # Find elements of orders 2 and n + order_2, order_n = [], [] + for p in self.elements: + k = p.order() + if k == 2: + order_2.append(p) + elif k == n: + order_n.append(p) + + if len(order_2) != n + 1 - (n % 2): + self._is_dihedral = False + return False + + if not order_n: + self._is_dihedral = False + return False + + x = order_n[0] + # Want an element y of order 2 that is not a power of x + # (i.e. that is not the 180-deg rotation, when n is even). + y = order_2[0] + if n % 2 == 0 and y == x**(n//2): + y = order_2[1] + + self._is_dihedral = (y*x*y == ~x) + return self._is_dihedral + + def pointwise_stabilizer(self, points, incremental=True): + r"""Return the pointwise stabilizer for a set of points. + + Explanation + =========== + + For a permutation group `G` and a set of points + `\{p_1, p_2,\ldots, p_k\}`, the pointwise stabilizer of + `p_1, p_2, \ldots, p_k` is defined as + `G_{p_1,\ldots, p_k} = + \{g\in G | g(p_i) = p_i \forall i\in\{1, 2,\ldots,k\}\}` ([1],p20). + It is a subgroup of `G`. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> S = SymmetricGroup(7) + >>> Stab = S.pointwise_stabilizer([2, 3, 5]) + >>> Stab.is_subgroup(S.stabilizer(2).stabilizer(3).stabilizer(5)) + True + + See Also + ======== + + stabilizer, schreier_sims_incremental + + Notes + ===== + + When incremental == True, + rather than the obvious implementation using successive calls to + ``.stabilizer()``, this uses the incremental Schreier-Sims algorithm + to obtain a base with starting segment - the given points. + + """ + if incremental: + base, strong_gens = self.schreier_sims_incremental(base=points) + stab_gens = [] + degree = self.degree + for gen in strong_gens: + if [gen(point) for point in points] == points: + stab_gens.append(gen) + if not stab_gens: + stab_gens = _af_new(list(range(degree))) + return PermutationGroup(stab_gens) + else: + gens = self._generators + degree = self.degree + for x in points: + gens = _stabilizer(degree, gens, x) + return PermutationGroup(gens) + + def make_perm(self, n, seed=None): + """ + Multiply ``n`` randomly selected permutations from + pgroup together, starting with the identity + permutation. If ``n`` is a list of integers, those + integers will be used to select the permutations and they + will be applied in L to R order: make_perm((A, B, C)) will + give CBA(I) where I is the identity permutation. + + ``seed`` is used to set the seed for the random selection + of permutations from pgroup. If this is a list of integers, + the corresponding permutations from pgroup will be selected + in the order give. This is mainly used for testing purposes. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a, b = [Permutation([1, 0, 3, 2]), Permutation([1, 3, 0, 2])] + >>> G = PermutationGroup([a, b]) + >>> G.make_perm(1, [0]) + (0 1)(2 3) + >>> G.make_perm(3, [0, 1, 0]) + (0 2 3 1) + >>> G.make_perm([0, 1, 0]) + (0 2 3 1) + + See Also + ======== + + random + """ + if is_sequence(n): + if seed is not None: + raise ValueError('If n is a sequence, seed should be None') + n, seed = len(n), n + else: + try: + n = int(n) + except TypeError: + raise ValueError('n must be an integer or a sequence.') + randomrange = _randrange(seed) + + # start with the identity permutation + result = Permutation(list(range(self.degree))) + m = len(self) + for _ in range(n): + p = self[randomrange(m)] + result = rmul(result, p) + return result + + def random(self, af=False): + """Return a random group element + """ + rank = randrange(self.order()) + return self.coset_unrank(rank, af) + + def random_pr(self, gen_count=11, iterations=50, _random_prec=None): + """Return a random group element using product replacement. + + Explanation + =========== + + For the details of the product replacement algorithm, see + ``_random_pr_init`` In ``random_pr`` the actual 'product replacement' + is performed. Notice that if the attribute ``_random_gens`` + is empty, it needs to be initialized by ``_random_pr_init``. + + See Also + ======== + + _random_pr_init + + """ + if self._random_gens == []: + self._random_pr_init(gen_count, iterations) + random_gens = self._random_gens + r = len(random_gens) - 1 + + # handle randomized input for testing purposes + if _random_prec is None: + s = randrange(r) + t = randrange(r - 1) + if t == s: + t = r - 1 + x = choice([1, 2]) + e = choice([-1, 1]) + else: + s = _random_prec['s'] + t = _random_prec['t'] + if t == s: + t = r - 1 + x = _random_prec['x'] + e = _random_prec['e'] + + if x == 1: + random_gens[s] = _af_rmul(random_gens[s], _af_pow(random_gens[t], e)) + random_gens[r] = _af_rmul(random_gens[r], random_gens[s]) + else: + random_gens[s] = _af_rmul(_af_pow(random_gens[t], e), random_gens[s]) + random_gens[r] = _af_rmul(random_gens[s], random_gens[r]) + return _af_new(random_gens[r]) + + def random_stab(self, alpha, schreier_vector=None, _random_prec=None): + """Random element from the stabilizer of ``alpha``. + + The schreier vector for ``alpha`` is an optional argument used + for speeding up repeated calls. The algorithm is described in [1], p.81 + + See Also + ======== + + random_pr, orbit_rep + + """ + if schreier_vector is None: + schreier_vector = self.schreier_vector(alpha) + if _random_prec is None: + rand = self.random_pr() + else: + rand = _random_prec['rand'] + beta = rand(alpha) + h = self.orbit_rep(alpha, beta, schreier_vector) + return rmul(~h, rand) + + def schreier_sims(self): + """Schreier-Sims algorithm. + + Explanation + =========== + + It computes the generators of the chain of stabilizers + `G > G_{b_1} > .. > G_{b1,..,b_r} > 1` + in which `G_{b_1,..,b_i}` stabilizes `b_1,..,b_i`, + and the corresponding ``s`` cosets. + An element of the group can be written as the product + `h_1*..*h_s`. + + We use the incremental Schreier-Sims algorithm. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([0, 2, 1]) + >>> b = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a, b]) + >>> G.schreier_sims() + >>> G.basic_transversals + [{0: (2)(0 1), 1: (2), 2: (1 2)}, + {0: (2), 2: (0 2)}] + """ + if self._transversals: + return + self._schreier_sims() + return + + def _schreier_sims(self, base=None): + schreier = self.schreier_sims_incremental(base=base, slp_dict=True) + base, strong_gens = schreier[:2] + self._base = base + self._strong_gens = strong_gens + self._strong_gens_slp = schreier[2] + if not base: + self._transversals = [] + self._basic_orbits = [] + return + + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + basic_orbits, transversals, slps = _orbits_transversals_from_bsgs(base,\ + strong_gens_distr, slp=True) + + # rewrite the indices stored in slps in terms of strong_gens + for i, slp in enumerate(slps): + gens = strong_gens_distr[i] + for k in slp: + slp[k] = [strong_gens.index(gens[s]) for s in slp[k]] + + self._transversals = transversals + self._basic_orbits = [sorted(x) for x in basic_orbits] + self._transversal_slp = slps + + def schreier_sims_incremental(self, base=None, gens=None, slp_dict=False): + """Extend a sequence of points and generating set to a base and strong + generating set. + + Parameters + ========== + + base + The sequence of points to be extended to a base. Optional + parameter with default value ``[]``. + gens + The generating set to be extended to a strong generating set + relative to the base obtained. Optional parameter with default + value ``self.generators``. + + slp_dict + If `True`, return a dictionary `{g: gens}` for each strong + generator `g` where `gens` is a list of strong generators + coming before `g` in `strong_gens`, such that the product + of the elements of `gens` is equal to `g`. + + Returns + ======= + + (base, strong_gens) + ``base`` is the base obtained, and ``strong_gens`` is the strong + generating set relative to it. The original parameters ``base``, + ``gens`` remain unchanged. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AlternatingGroup + >>> from sympy.combinatorics.testutil import _verify_bsgs + >>> A = AlternatingGroup(7) + >>> base = [2, 3] + >>> seq = [2, 3] + >>> base, strong_gens = A.schreier_sims_incremental(base=seq) + >>> _verify_bsgs(A, base, strong_gens) + True + >>> base[:2] + [2, 3] + + Notes + ===== + + This version of the Schreier-Sims algorithm runs in polynomial time. + There are certain assumptions in the implementation - if the trivial + group is provided, ``base`` and ``gens`` are returned immediately, + as any sequence of points is a base for the trivial group. If the + identity is present in the generators ``gens``, it is removed as + it is a redundant generator. + The implementation is described in [1], pp. 90-93. + + See Also + ======== + + schreier_sims, schreier_sims_random + + """ + if base is None: + base = [] + if gens is None: + gens = self.generators[:] + degree = self.degree + id_af = list(range(degree)) + # handle the trivial group + if len(gens) == 1 and gens[0].is_Identity: + if slp_dict: + return base, gens, {gens[0]: [gens[0]]} + return base, gens + # prevent side effects + _base, _gens = base[:], gens[:] + # remove the identity as a generator + _gens = [x for x in _gens if not x.is_Identity] + # make sure no generator fixes all base points + for gen in _gens: + if all(x == gen._array_form[x] for x in _base): + for new in id_af: + if gen._array_form[new] != new: + break + else: + assert None # can this ever happen? + _base.append(new) + # distribute generators according to basic stabilizers + strong_gens_distr = _distribute_gens_by_base(_base, _gens) + strong_gens_slp = [] + # initialize the basic stabilizers, basic orbits and basic transversals + orbs = {} + transversals = {} + slps = {} + base_len = len(_base) + for i in range(base_len): + transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i], + _base[i], pairs=True, af=True, slp=True) + transversals[i] = dict(transversals[i]) + orbs[i] = list(transversals[i].keys()) + # main loop: amend the stabilizer chain until we have generators + # for all stabilizers + i = base_len - 1 + while i >= 0: + # this flag is used to continue with the main loop from inside + # a nested loop + continue_i = False + # test the generators for being a strong generating set + db = {} + for beta, u_beta in list(transversals[i].items()): + for j, gen in enumerate(strong_gens_distr[i]): + gb = gen._array_form[beta] + u1 = transversals[i][gb] + g1 = _af_rmul(gen._array_form, u_beta) + slp = [(i, g) for g in slps[i][beta]] + slp = [(i, j)] + slp + if g1 != u1: + # test if the schreier generator is in the i+1-th + # would-be basic stabilizer + y = True + try: + u1_inv = db[gb] + except KeyError: + u1_inv = db[gb] = _af_invert(u1) + schreier_gen = _af_rmul(u1_inv, g1) + u1_inv_slp = slps[i][gb][:] + u1_inv_slp.reverse() + u1_inv_slp = [(i, (g,)) for g in u1_inv_slp] + slp = u1_inv_slp + slp + h, j, slp = _strip_af(schreier_gen, _base, orbs, transversals, i, slp=slp, slps=slps) + if j <= base_len: + # new strong generator h at level j + y = False + elif h: + # h fixes all base points + y = False + moved = 0 + while h[moved] == moved: + moved += 1 + _base.append(moved) + base_len += 1 + strong_gens_distr.append([]) + if y is False: + # if a new strong generator is found, update the + # data structures and start over + h = _af_new(h) + strong_gens_slp.append((h, slp)) + for l in range(i + 1, j): + strong_gens_distr[l].append(h) + transversals[l], slps[l] =\ + _orbit_transversal(degree, strong_gens_distr[l], + _base[l], pairs=True, af=True, slp=True) + transversals[l] = dict(transversals[l]) + orbs[l] = list(transversals[l].keys()) + i = j - 1 + # continue main loop using the flag + continue_i = True + if continue_i is True: + break + if continue_i is True: + break + if continue_i is True: + continue + i -= 1 + + strong_gens = _gens[:] + + if slp_dict: + # create the list of the strong generators strong_gens and + # rewrite the indices of strong_gens_slp in terms of the + # elements of strong_gens + for k, slp in strong_gens_slp: + strong_gens.append(k) + for i in range(len(slp)): + s = slp[i] + if isinstance(s[1], tuple): + slp[i] = strong_gens_distr[s[0]][s[1][0]]**-1 + else: + slp[i] = strong_gens_distr[s[0]][s[1]] + strong_gens_slp = dict(strong_gens_slp) + # add the original generators + for g in _gens: + strong_gens_slp[g] = [g] + return (_base, strong_gens, strong_gens_slp) + + strong_gens.extend([k for k, _ in strong_gens_slp]) + return _base, strong_gens + + def schreier_sims_random(self, base=None, gens=None, consec_succ=10, + _random_prec=None): + r"""Randomized Schreier-Sims algorithm. + + Explanation + =========== + + The randomized Schreier-Sims algorithm takes the sequence ``base`` + and the generating set ``gens``, and extends ``base`` to a base, and + ``gens`` to a strong generating set relative to that base with + probability of a wrong answer at most `2^{-consec\_succ}`, + provided the random generators are sufficiently random. + + Parameters + ========== + + base + The sequence to be extended to a base. + gens + The generating set to be extended to a strong generating set. + consec_succ + The parameter defining the probability of a wrong answer. + _random_prec + An internal parameter used for testing purposes. + + Returns + ======= + + (base, strong_gens) + ``base`` is the base and ``strong_gens`` is the strong generating + set relative to it. + + Examples + ======== + + >>> from sympy.combinatorics.testutil import _verify_bsgs + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> S = SymmetricGroup(5) + >>> base, strong_gens = S.schreier_sims_random(consec_succ=5) + >>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP + True + + Notes + ===== + + The algorithm is described in detail in [1], pp. 97-98. It extends + the orbits ``orbs`` and the permutation groups ``stabs`` to + basic orbits and basic stabilizers for the base and strong generating + set produced in the end. + The idea of the extension process + is to "sift" random group elements through the stabilizer chain + and amend the stabilizers/orbits along the way when a sift + is not successful. + The helper function ``_strip`` is used to attempt + to decompose a random group element according to the current + state of the stabilizer chain and report whether the element was + fully decomposed (successful sift) or not (unsuccessful sift). In + the latter case, the level at which the sift failed is reported and + used to amend ``stabs``, ``base``, ``gens`` and ``orbs`` accordingly. + The halting condition is for ``consec_succ`` consecutive successful + sifts to pass. This makes sure that the current ``base`` and ``gens`` + form a BSGS with probability at least `1 - 1/\text{consec\_succ}`. + + See Also + ======== + + schreier_sims + + """ + if base is None: + base = [] + if gens is None: + gens = self.generators + base_len = len(base) + n = self.degree + # make sure no generator fixes all base points + for gen in gens: + if all(gen(x) == x for x in base): + new = 0 + while gen._array_form[new] == new: + new += 1 + base.append(new) + base_len += 1 + # distribute generators according to basic stabilizers + strong_gens_distr = _distribute_gens_by_base(base, gens) + # initialize the basic stabilizers, basic transversals and basic orbits + transversals = {} + orbs = {} + for i in range(base_len): + transversals[i] = dict(_orbit_transversal(n, strong_gens_distr[i], + base[i], pairs=True)) + orbs[i] = list(transversals[i].keys()) + # initialize the number of consecutive elements sifted + c = 0 + # start sifting random elements while the number of consecutive sifts + # is less than consec_succ + while c < consec_succ: + if _random_prec is None: + g = self.random_pr() + else: + g = _random_prec['g'].pop() + h, j = _strip(g, base, orbs, transversals) + y = True + # determine whether a new base point is needed + if j <= base_len: + y = False + elif not h.is_Identity: + y = False + moved = 0 + while h(moved) == moved: + moved += 1 + base.append(moved) + base_len += 1 + strong_gens_distr.append([]) + # if the element doesn't sift, amend the strong generators and + # associated stabilizers and orbits + if y is False: + for l in range(1, j): + strong_gens_distr[l].append(h) + transversals[l] = dict(_orbit_transversal(n, + strong_gens_distr[l], base[l], pairs=True)) + orbs[l] = list(transversals[l].keys()) + c = 0 + else: + c += 1 + # build the strong generating set + strong_gens = strong_gens_distr[0][:] + for gen in strong_gens_distr[1]: + if gen not in strong_gens: + strong_gens.append(gen) + return base, strong_gens + + def schreier_vector(self, alpha): + """Computes the schreier vector for ``alpha``. + + Explanation + =========== + + The Schreier vector efficiently stores information + about the orbit of ``alpha``. It can later be used to quickly obtain + elements of the group that send ``alpha`` to a particular element + in the orbit. Notice that the Schreier vector depends on the order + in which the group generators are listed. For a definition, see [3]. + Since list indices start from zero, we adopt the convention to use + "None" instead of 0 to signify that an element does not belong + to the orbit. + For the algorithm and its correctness, see [2], pp.78-80. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([2, 4, 6, 3, 1, 5, 0]) + >>> b = Permutation([0, 1, 3, 5, 4, 6, 2]) + >>> G = PermutationGroup([a, b]) + >>> G.schreier_vector(0) + [-1, None, 0, 1, None, 1, 0] + + See Also + ======== + + orbit + + """ + n = self.degree + v = [None]*n + v[alpha] = -1 + orb = [alpha] + used = [False]*n + used[alpha] = True + gens = self.generators + r = len(gens) + for b in orb: + for i in range(r): + temp = gens[i]._array_form[b] + if used[temp] is False: + orb.append(temp) + used[temp] = True + v[temp] = i + return v + + def stabilizer(self, alpha): + r"""Return the stabilizer subgroup of ``alpha``. + + Explanation + =========== + + The stabilizer of `\alpha` is the group `G_\alpha = + \{g \in G | g(\alpha) = \alpha\}`. + For a proof of correctness, see [1], p.79. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> G = DihedralGroup(6) + >>> G.stabilizer(5) + PermutationGroup([ + (5)(0 4)(1 3)]) + + See Also + ======== + + orbit + + """ + return PermGroup(_stabilizer(self._degree, self._generators, alpha)) + + @property + def strong_gens(self): + r"""Return a strong generating set from the Schreier-Sims algorithm. + + Explanation + =========== + + A generating set `S = \{g_1, g_2, \dots, g_t\}` for a permutation group + `G` is a strong generating set relative to the sequence of points + (referred to as a "base") `(b_1, b_2, \dots, b_k)` if, for + `1 \leq i \leq k` we have that the intersection of the pointwise + stabilizer `G^{(i+1)} := G_{b_1, b_2, \dots, b_i}` with `S` generates + the pointwise stabilizer `G^{(i+1)}`. The concepts of a base and + strong generating set and their applications are discussed in depth + in [1], pp. 87-89 and [2], pp. 55-57. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> D = DihedralGroup(4) + >>> D.strong_gens + [(0 1 2 3), (0 3)(1 2), (1 3)] + >>> D.base + [0, 1] + + See Also + ======== + + base, basic_transversals, basic_orbits, basic_stabilizers + + """ + if self._strong_gens == []: + self.schreier_sims() + return self._strong_gens + + def subgroup(self, gens): + """ + Return the subgroup generated by `gens` which is a list of + elements of the group + """ + + if not all(g in self for g in gens): + raise ValueError("The group does not contain the supplied generators") + + G = PermutationGroup(gens) + return G + + def subgroup_search(self, prop, base=None, strong_gens=None, tests=None, + init_subgroup=None): + """Find the subgroup of all elements satisfying the property ``prop``. + + Explanation + =========== + + This is done by a depth-first search with respect to base images that + uses several tests to prune the search tree. + + Parameters + ========== + + prop + The property to be used. Has to be callable on group elements + and always return ``True`` or ``False``. It is assumed that + all group elements satisfying ``prop`` indeed form a subgroup. + base + A base for the supergroup. + strong_gens + A strong generating set for the supergroup. + tests + A list of callables of length equal to the length of ``base``. + These are used to rule out group elements by partial base images, + so that ``tests[l](g)`` returns False if the element ``g`` is known + not to satisfy prop base on where g sends the first ``l + 1`` base + points. + init_subgroup + if a subgroup of the sought group is + known in advance, it can be passed to the function as this + parameter. + + Returns + ======= + + res + The subgroup of all elements satisfying ``prop``. The generating + set for this group is guaranteed to be a strong generating set + relative to the base ``base``. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... AlternatingGroup) + >>> from sympy.combinatorics.testutil import _verify_bsgs + >>> S = SymmetricGroup(7) + >>> prop_even = lambda x: x.is_even + >>> base, strong_gens = S.schreier_sims_incremental() + >>> G = S.subgroup_search(prop_even, base=base, strong_gens=strong_gens) + >>> G.is_subgroup(AlternatingGroup(7)) + True + >>> _verify_bsgs(G, base, G.generators) + True + + Notes + ===== + + This function is extremely lengthy and complicated and will require + some careful attention. The implementation is described in + [1], pp. 114-117, and the comments for the code here follow the lines + of the pseudocode in the book for clarity. + + The complexity is exponential in general, since the search process by + itself visits all members of the supergroup. However, there are a lot + of tests which are used to prune the search tree, and users can define + their own tests via the ``tests`` parameter, so in practice, and for + some computations, it's not terrible. + + A crucial part in the procedure is the frequent base change performed + (this is line 11 in the pseudocode) in order to obtain a new basic + stabilizer. The book mentiones that this can be done by using + ``.baseswap(...)``, however the current implementation uses a more + straightforward way to find the next basic stabilizer - calling the + function ``.stabilizer(...)`` on the previous basic stabilizer. + + """ + # initialize BSGS and basic group properties + def get_reps(orbits): + # get the minimal element in the base ordering + return [min(orbit, key = lambda x: base_ordering[x]) \ + for orbit in orbits] + + def update_nu(l): + temp_index = len(basic_orbits[l]) + 1 -\ + len(res_basic_orbits_init_base[l]) + # this corresponds to the element larger than all points + if temp_index >= len(sorted_orbits[l]): + nu[l] = base_ordering[degree] + else: + nu[l] = sorted_orbits[l][temp_index] + + if base is None: + base, strong_gens = self.schreier_sims_incremental() + base_len = len(base) + degree = self.degree + identity = _af_new(list(range(degree))) + base_ordering = _base_ordering(base, degree) + # add an element larger than all points + base_ordering.append(degree) + # add an element smaller than all points + base_ordering.append(-1) + # compute BSGS-related structures + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + basic_orbits, transversals = _orbits_transversals_from_bsgs(base, + strong_gens_distr) + # handle subgroup initialization and tests + if init_subgroup is None: + init_subgroup = PermutationGroup([identity]) + if tests is None: + trivial_test = lambda x: True + tests = [] + for i in range(base_len): + tests.append(trivial_test) + # line 1: more initializations. + res = init_subgroup + f = base_len - 1 + l = base_len - 1 + # line 2: set the base for K to the base for G + res_base = base[:] + # line 3: compute BSGS and related structures for K + res_base, res_strong_gens = res.schreier_sims_incremental( + base=res_base) + res_strong_gens_distr = _distribute_gens_by_base(res_base, + res_strong_gens) + res_generators = res.generators + res_basic_orbits_init_base = \ + [_orbit(degree, res_strong_gens_distr[i], res_base[i])\ + for i in range(base_len)] + # initialize orbit representatives + orbit_reps = [None]*base_len + # line 4: orbit representatives for f-th basic stabilizer of K + orbits = _orbits(degree, res_strong_gens_distr[f]) + orbit_reps[f] = get_reps(orbits) + # line 5: remove the base point from the representatives to avoid + # getting the identity element as a generator for K + orbit_reps[f].remove(base[f]) + # line 6: more initializations + c = [0]*base_len + u = [identity]*base_len + sorted_orbits = [None]*base_len + for i in range(base_len): + sorted_orbits[i] = basic_orbits[i][:] + sorted_orbits[i].sort(key=lambda point: base_ordering[point]) + # line 7: initializations + mu = [None]*base_len + nu = [None]*base_len + # this corresponds to the element smaller than all points + mu[l] = degree + 1 + update_nu(l) + # initialize computed words + computed_words = [identity]*base_len + # line 8: main loop + while True: + # apply all the tests + while l < base_len - 1 and \ + computed_words[l](base[l]) in orbit_reps[l] and \ + base_ordering[mu[l]] < \ + base_ordering[computed_words[l](base[l])] < \ + base_ordering[nu[l]] and \ + tests[l](computed_words): + # line 11: change the (partial) base of K + new_point = computed_words[l](base[l]) + res_base[l] = new_point + new_stab_gens = _stabilizer(degree, res_strong_gens_distr[l], + new_point) + res_strong_gens_distr[l + 1] = new_stab_gens + # line 12: calculate minimal orbit representatives for the + # l+1-th basic stabilizer + orbits = _orbits(degree, new_stab_gens) + orbit_reps[l + 1] = get_reps(orbits) + # line 13: amend sorted orbits + l += 1 + temp_orbit = [computed_words[l - 1](point) for point + in basic_orbits[l]] + temp_orbit.sort(key=lambda point: base_ordering[point]) + sorted_orbits[l] = temp_orbit + # lines 14 and 15: update variables used minimality tests + new_mu = degree + 1 + for i in range(l): + if base[l] in res_basic_orbits_init_base[i]: + candidate = computed_words[i](base[i]) + if base_ordering[candidate] > base_ordering[new_mu]: + new_mu = candidate + mu[l] = new_mu + update_nu(l) + # line 16: determine the new transversal element + c[l] = 0 + temp_point = sorted_orbits[l][c[l]] + gamma = computed_words[l - 1]._array_form.index(temp_point) + u[l] = transversals[l][gamma] + # update computed words + computed_words[l] = rmul(computed_words[l - 1], u[l]) + # lines 17 & 18: apply the tests to the group element found + g = computed_words[l] + temp_point = g(base[l]) + if l == base_len - 1 and \ + base_ordering[mu[l]] < \ + base_ordering[temp_point] < base_ordering[nu[l]] and \ + temp_point in orbit_reps[l] and \ + tests[l](computed_words) and \ + prop(g): + # line 19: reset the base of K + res_generators.append(g) + res_base = base[:] + # line 20: recalculate basic orbits (and transversals) + res_strong_gens.append(g) + res_strong_gens_distr = _distribute_gens_by_base(res_base, + res_strong_gens) + res_basic_orbits_init_base = \ + [_orbit(degree, res_strong_gens_distr[i], res_base[i]) \ + for i in range(base_len)] + # line 21: recalculate orbit representatives + # line 22: reset the search depth + orbit_reps[f] = get_reps(orbits) + l = f + # line 23: go up the tree until in the first branch not fully + # searched + while l >= 0 and c[l] == len(basic_orbits[l]) - 1: + l = l - 1 + # line 24: if the entire tree is traversed, return K + if l == -1: + return PermutationGroup(res_generators) + # lines 25-27: update orbit representatives + if l < f: + # line 26 + f = l + c[l] = 0 + # line 27 + temp_orbits = _orbits(degree, res_strong_gens_distr[f]) + orbit_reps[f] = get_reps(temp_orbits) + # line 28: update variables used for minimality testing + mu[l] = degree + 1 + temp_index = len(basic_orbits[l]) + 1 - \ + len(res_basic_orbits_init_base[l]) + if temp_index >= len(sorted_orbits[l]): + nu[l] = base_ordering[degree] + else: + nu[l] = sorted_orbits[l][temp_index] + # line 29: set the next element from the current branch and update + # accordingly + c[l] += 1 + if l == 0: + gamma = sorted_orbits[l][c[l]] + else: + gamma = computed_words[l - 1]._array_form.index(sorted_orbits[l][c[l]]) + + u[l] = transversals[l][gamma] + if l == 0: + computed_words[l] = u[l] + else: + computed_words[l] = rmul(computed_words[l - 1], u[l]) + + @property + def transitivity_degree(self): + r"""Compute the degree of transitivity of the group. + + Explanation + =========== + + A permutation group `G` acting on `\Omega = \{0, 1, \dots, n-1\}` is + ``k``-fold transitive, if, for any `k` points + `(a_1, a_2, \dots, a_k) \in \Omega` and any `k` points + `(b_1, b_2, \dots, b_k) \in \Omega` there exists `g \in G` such that + `g(a_1) = b_1, g(a_2) = b_2, \dots, g(a_k) = b_k` + The degree of transitivity of `G` is the maximum ``k`` such that + `G` is ``k``-fold transitive. ([8]) + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> a = Permutation([1, 2, 0]) + >>> b = Permutation([1, 0, 2]) + >>> G = PermutationGroup([a, b]) + >>> G.transitivity_degree + 3 + + See Also + ======== + + is_transitive, orbit + + """ + if self._transitivity_degree is None: + n = self.degree + G = self + # if G is k-transitive, a tuple (a_0,..,a_k) + # can be brought to (b_0,...,b_(k-1), b_k) + # where b_0,...,b_(k-1) are fixed points; + # consider the group G_k which stabilizes b_0,...,b_(k-1) + # if G_k is transitive on the subset excluding b_0,...,b_(k-1) + # then G is (k+1)-transitive + for i in range(n): + orb = G.orbit(i) + if len(orb) != n - i: + self._transitivity_degree = i + return i + G = G.stabilizer(i) + self._transitivity_degree = n + return n + else: + return self._transitivity_degree + + def _p_elements_group(self, p): + ''' + For an abelian p-group, return the subgroup consisting of + all elements of order p (and the identity) + + ''' + gens = self.generators[:] + gens = sorted(gens, key=lambda x: x.order(), reverse=True) + gens_p = [g**(g.order()/p) for g in gens] + gens_r = [] + for i in range(len(gens)): + x = gens[i] + x_order = x.order() + # x_p has order p + x_p = x**(x_order/p) + if i > 0: + P = PermutationGroup(gens_p[:i]) + else: + P = PermutationGroup(self.identity) + if x**(x_order/p) not in P: + gens_r.append(x**(x_order/p)) + else: + # replace x by an element of order (x.order()/p) + # so that gens still generates G + g = P.generator_product(x_p, original=True) + for s in g: + x = x*s**-1 + x_order = x_order/p + # insert x to gens so that the sorting is preserved + del gens[i] + del gens_p[i] + j = i - 1 + while j < len(gens) and gens[j].order() >= x_order: + j += 1 + gens = gens[:j] + [x] + gens[j:] + gens_p = gens_p[:j] + [x] + gens_p[j:] + return PermutationGroup(gens_r) + + def _sylow_alt_sym(self, p): + ''' + Return a p-Sylow subgroup of a symmetric or an + alternating group. + + Explanation + =========== + + The algorithm for this is hinted at in [1], Chapter 4, + Exercise 4. + + For Sym(n) with n = p^i, the idea is as follows. Partition + the interval [0..n-1] into p equal parts, each of length p^(i-1): + [0..p^(i-1)-1], [p^(i-1)..2*p^(i-1)-1]...[(p-1)*p^(i-1)..p^i-1]. + Find a p-Sylow subgroup of Sym(p^(i-1)) (treated as a subgroup + of ``self``) acting on each of the parts. Call the subgroups + P_1, P_2...P_p. The generators for the subgroups P_2...P_p + can be obtained from those of P_1 by applying a "shifting" + permutation to them, that is, a permutation mapping [0..p^(i-1)-1] + to the second part (the other parts are obtained by using the shift + multiple times). The union of this permutation and the generators + of P_1 is a p-Sylow subgroup of ``self``. + + For n not equal to a power of p, partition + [0..n-1] in accordance with how n would be written in base p. + E.g. for p=2 and n=11, 11 = 2^3 + 2^2 + 1 so the partition + is [[0..7], [8..9], {10}]. To generate a p-Sylow subgroup, + take the union of the generators for each of the parts. + For the above example, {(0 1), (0 2)(1 3), (0 4), (1 5)(2 7)} + from the first part, {(8 9)} from the second part and + nothing from the third. This gives 4 generators in total, and + the subgroup they generate is p-Sylow. + + Alternating groups are treated the same except when p=2. In this + case, (0 1)(s s+1) should be added for an appropriate s (the start + of a part) for each part in the partitions. + + See Also + ======== + + sylow_subgroup, is_alt_sym + + ''' + n = self.degree + gens = [] + identity = Permutation(n-1) + # the case of 2-sylow subgroups of alternating groups + # needs special treatment + alt = p == 2 and all(g.is_even for g in self.generators) + + # find the presentation of n in base p + coeffs = [] + m = n + while m > 0: + coeffs.append(m % p) + m = m // p + + power = len(coeffs)-1 + # for a symmetric group, gens[:i] is the generating + # set for a p-Sylow subgroup on [0..p**(i-1)-1]. For + # alternating groups, the same is given by gens[:2*(i-1)] + for i in range(1, power+1): + if i == 1 and alt: + # (0 1) shouldn't be added for alternating groups + continue + gen = Permutation([(j + p**(i-1)) % p**i for j in range(p**i)]) + gens.append(identity*gen) + if alt: + gen = Permutation(0, 1)*gen*Permutation(0, 1)*gen + gens.append(gen) + + # the first point in the current part (see the algorithm + # description in the docstring) + start = 0 + + while power > 0: + a = coeffs[power] + + # make the permutation shifting the start of the first + # part ([0..p^i-1] for some i) to the current one + for _ in range(a): + shift = Permutation() + if start > 0: + for i in range(p**power): + shift = shift(i, start + i) + + if alt: + gen = Permutation(0, 1)*shift*Permutation(0, 1)*shift + gens.append(gen) + j = 2*(power - 1) + else: + j = power + + for i, gen in enumerate(gens[:j]): + if alt and i % 2 == 1: + continue + # shift the generator to the start of the + # partition part + gen = shift*gen*shift + gens.append(gen) + + start += p**power + power = power-1 + + return gens + + def sylow_subgroup(self, p): + ''' + Return a p-Sylow subgroup of the group. + + The algorithm is described in [1], Chapter 4, Section 7 + + Examples + ======== + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.named_groups import AlternatingGroup + + >>> D = DihedralGroup(6) + >>> S = D.sylow_subgroup(2) + >>> S.order() + 4 + >>> G = SymmetricGroup(6) + >>> S = G.sylow_subgroup(5) + >>> S.order() + 5 + + >>> G1 = AlternatingGroup(3) + >>> G2 = AlternatingGroup(5) + >>> G3 = AlternatingGroup(9) + + >>> S1 = G1.sylow_subgroup(3) + >>> S2 = G2.sylow_subgroup(3) + >>> S3 = G3.sylow_subgroup(3) + + >>> len1 = len(S1.lower_central_series()) + >>> len2 = len(S2.lower_central_series()) + >>> len3 = len(S3.lower_central_series()) + + >>> len1 == len2 + True + >>> len1 < len3 + True + + ''' + from sympy.combinatorics.homomorphisms import ( + orbit_homomorphism, block_homomorphism) + + if not isprime(p): + raise ValueError("p must be a prime") + + def is_p_group(G): + # check if the order of G is a power of p + # and return the power + m = G.order() + n = 0 + while m % p == 0: + m = m/p + n += 1 + if m == 1: + return True, n + return False, n + + def _sylow_reduce(mu, nu): + # reduction based on two homomorphisms + # mu and nu with trivially intersecting + # kernels + Q = mu.image().sylow_subgroup(p) + Q = mu.invert_subgroup(Q) + nu = nu.restrict_to(Q) + R = nu.image().sylow_subgroup(p) + return nu.invert_subgroup(R) + + order = self.order() + if order % p != 0: + return PermutationGroup([self.identity]) + p_group, n = is_p_group(self) + if p_group: + return self + + if self.is_alt_sym(): + return PermutationGroup(self._sylow_alt_sym(p)) + + # if there is a non-trivial orbit with size not divisible + # by p, the sylow subgroup is contained in its stabilizer + # (by orbit-stabilizer theorem) + orbits = self.orbits() + non_p_orbits = [o for o in orbits if len(o) % p != 0 and len(o) != 1] + if non_p_orbits: + G = self.stabilizer(list(non_p_orbits[0]).pop()) + return G.sylow_subgroup(p) + + if not self.is_transitive(): + # apply _sylow_reduce to orbit actions + orbits = sorted(orbits, key=len) + omega1 = orbits.pop() + omega2 = orbits[0].union(*orbits) + mu = orbit_homomorphism(self, omega1) + nu = orbit_homomorphism(self, omega2) + return _sylow_reduce(mu, nu) + + blocks = self.minimal_blocks() + if len(blocks) > 1: + # apply _sylow_reduce to block system actions + mu = block_homomorphism(self, blocks[0]) + nu = block_homomorphism(self, blocks[1]) + return _sylow_reduce(mu, nu) + elif len(blocks) == 1: + block = list(blocks)[0] + if any(e != 0 for e in block): + # self is imprimitive + mu = block_homomorphism(self, block) + if not is_p_group(mu.image())[0]: + S = mu.image().sylow_subgroup(p) + return mu.invert_subgroup(S).sylow_subgroup(p) + + # find an element of order p + g = self.random() + g_order = g.order() + while g_order % p != 0 or g_order == 0: + g = self.random() + g_order = g.order() + g = g**(g_order // p) + if order % p**2 != 0: + return PermutationGroup(g) + + C = self.centralizer(g) + while C.order() % p**n != 0: + S = C.sylow_subgroup(p) + s_order = S.order() + Z = S.center() + P = Z._p_elements_group(p) + h = P.random() + C_h = self.centralizer(h) + while C_h.order() % p*s_order != 0: + h = P.random() + C_h = self.centralizer(h) + C = C_h + + return C.sylow_subgroup(p) + + def _block_verify(self, L, alpha): + delta = sorted(self.orbit(alpha)) + # p[i] will be the number of the block + # delta[i] belongs to + p = [-1]*len(delta) + blocks = [-1]*len(delta) + + B = [[]] # future list of blocks + u = [0]*len(delta) # u[i] in L s.t. alpha^u[i] = B[0][i] + + t = L.orbit_transversal(alpha, pairs=True) + for a, beta in t: + B[0].append(a) + i_a = delta.index(a) + p[i_a] = 0 + blocks[i_a] = alpha + u[i_a] = beta + + rho = 0 + m = 0 # number of blocks - 1 + + while rho <= m: + beta = B[rho][0] + for g in self.generators: + d = beta^g + i_d = delta.index(d) + sigma = p[i_d] + if sigma < 0: + # define a new block + m += 1 + sigma = m + u[i_d] = u[delta.index(beta)]*g + p[i_d] = sigma + rep = d + blocks[i_d] = rep + newb = [rep] + for gamma in B[rho][1:]: + i_gamma = delta.index(gamma) + d = gamma^g + i_d = delta.index(d) + if p[i_d] < 0: + u[i_d] = u[i_gamma]*g + p[i_d] = sigma + blocks[i_d] = rep + newb.append(d) + else: + # B[rho] is not a block + s = u[i_gamma]*g*u[i_d]**(-1) + return False, s + + B.append(newb) + else: + for h in B[rho][1:]: + if h^g not in B[sigma]: + # B[rho] is not a block + s = u[delta.index(beta)]*g*u[i_d]**(-1) + return False, s + rho += 1 + + return True, blocks + + def _verify(H, K, phi, z, alpha): + ''' + Return a list of relators ``rels`` in generators ``gens`_h` that + are mapped to ``H.generators`` by ``phi`` so that given a finite + presentation of ``K`` on a subset of ``gens_h`` + is a finite presentation of ``H``. + + Explanation + =========== + + ``H`` should be generated by the union of ``K.generators`` and ``z`` + (a single generator), and ``H.stabilizer(alpha) == K``; ``phi`` is a + canonical injection from a free group into a permutation group + containing ``H``. + + The algorithm is described in [1], Chapter 6. + + Examples + ======== + + >>> from sympy.combinatorics import free_group, Permutation, PermutationGroup + >>> from sympy.combinatorics.homomorphisms import homomorphism + >>> from sympy.combinatorics.fp_groups import FpGroup + + >>> H = PermutationGroup(Permutation(0, 2), Permutation (1, 5)) + >>> K = PermutationGroup(Permutation(5)(0, 2)) + >>> F = free_group("x_0 x_1")[0] + >>> gens = F.generators + >>> phi = homomorphism(F, H, F.generators, H.generators) + >>> rels_k = [gens[0]**2] # relators for presentation of K + >>> z= Permutation(1, 5) + >>> check, rels_h = H._verify(K, phi, z, 1) + >>> check + True + >>> rels = rels_k + rels_h + >>> G = FpGroup(F, rels) # presentation of H + >>> G.order() == H.order() + True + + See also + ======== + + strong_presentation, presentation, stabilizer + + ''' + + orbit = H.orbit(alpha) + beta = alpha^(z**-1) + + K_beta = K.stabilizer(beta) + + # orbit representatives of K_beta + gammas = [alpha, beta] + orbits = list({tuple(K_beta.orbit(o)) for o in orbit}) + orbit_reps = [orb[0] for orb in orbits] + for rep in orbit_reps: + if rep not in gammas: + gammas.append(rep) + + # orbit transversal of K + betas = [alpha, beta] + transversal = {alpha: phi.invert(H.identity), beta: phi.invert(z**-1)} + + for s, g in K.orbit_transversal(beta, pairs=True): + if s not in transversal: + transversal[s] = transversal[beta]*phi.invert(g) + + + union = K.orbit(alpha).union(K.orbit(beta)) + while (len(union) < len(orbit)): + for gamma in gammas: + if gamma in union: + r = gamma^z + if r not in union: + betas.append(r) + transversal[r] = transversal[gamma]*phi.invert(z) + for s, g in K.orbit_transversal(r, pairs=True): + if s not in transversal: + transversal[s] = transversal[r]*phi.invert(g) + union = union.union(K.orbit(r)) + break + + # compute relators + rels = [] + + for b in betas: + k_gens = K.stabilizer(b).generators + for y in k_gens: + new_rel = transversal[b] + gens = K.generator_product(y, original=True) + for g in gens[::-1]: + new_rel = new_rel*phi.invert(g) + new_rel = new_rel*transversal[b]**-1 + + perm = phi(new_rel) + try: + gens = K.generator_product(perm, original=True) + except ValueError: + return False, perm + for g in gens: + new_rel = new_rel*phi.invert(g)**-1 + if new_rel not in rels: + rels.append(new_rel) + + for gamma in gammas: + new_rel = transversal[gamma]*phi.invert(z)*transversal[gamma^z]**-1 + perm = phi(new_rel) + try: + gens = K.generator_product(perm, original=True) + except ValueError: + return False, perm + for g in gens: + new_rel = new_rel*phi.invert(g)**-1 + if new_rel not in rels: + rels.append(new_rel) + + return True, rels + + def strong_presentation(self): + ''' + Return a strong finite presentation of group. The generators + of the returned group are in the same order as the strong + generators of group. + + The algorithm is based on Sims' Verify algorithm described + in [1], Chapter 6. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> P = DihedralGroup(4) + >>> G = P.strong_presentation() + >>> P.order() == G.order() + True + + See Also + ======== + + presentation, _verify + + ''' + from sympy.combinatorics.fp_groups import (FpGroup, + simplify_presentation) + from sympy.combinatorics.free_groups import free_group + from sympy.combinatorics.homomorphisms import (block_homomorphism, + homomorphism, GroupHomomorphism) + + strong_gens = self.strong_gens[:] + stabs = self.basic_stabilizers[:] + base = self.base[:] + + # injection from a free group on len(strong_gens) + # generators into G + gen_syms = [('x_%d'%i) for i in range(len(strong_gens))] + F = free_group(', '.join(gen_syms))[0] + phi = homomorphism(F, self, F.generators, strong_gens) + + H = PermutationGroup(self.identity) + while stabs: + alpha = base.pop() + K = H + H = stabs.pop() + new_gens = [g for g in H.generators if g not in K] + + if K.order() == 1: + z = new_gens.pop() + rels = [F.generators[-1]**z.order()] + intermediate_gens = [z] + K = PermutationGroup(intermediate_gens) + + # add generators one at a time building up from K to H + while new_gens: + z = new_gens.pop() + intermediate_gens = [z] + intermediate_gens + K_s = PermutationGroup(intermediate_gens) + orbit = K_s.orbit(alpha) + orbit_k = K.orbit(alpha) + + # split into cases based on the orbit of K_s + if orbit_k == orbit: + if z in K: + rel = phi.invert(z) + perm = z + else: + t = K.orbit_rep(alpha, alpha^z) + rel = phi.invert(z)*phi.invert(t)**-1 + perm = z*t**-1 + for g in K.generator_product(perm, original=True): + rel = rel*phi.invert(g)**-1 + new_rels = [rel] + elif len(orbit_k) == 1: + # `success` is always true because `strong_gens` + # and `base` are already a verified BSGS. Later + # this could be changed to start with a randomly + # generated (potential) BSGS, and then new elements + # would have to be appended to it when `success` + # is false. + success, new_rels = K_s._verify(K, phi, z, alpha) + else: + # K.orbit(alpha) should be a block + # under the action of K_s on K_s.orbit(alpha) + check, block = K_s._block_verify(K, alpha) + if check: + # apply _verify to the action of K_s + # on the block system; for convenience, + # add the blocks as additional points + # that K_s should act on + t = block_homomorphism(K_s, block) + m = t.codomain.degree # number of blocks + d = K_s.degree + + # conjugating with p will shift + # permutations in t.image() to + # higher numbers, e.g. + # p*(0 1)*p = (m m+1) + p = Permutation() + for i in range(m): + p *= Permutation(i, i+d) + + t_img = t.images + # combine generators of K_s with their + # action on the block system + images = {g: g*p*t_img[g]*p for g in t_img} + for g in self.strong_gens[:-len(K_s.generators)]: + images[g] = g + K_s_act = PermutationGroup(list(images.values())) + f = GroupHomomorphism(self, K_s_act, images) + + K_act = PermutationGroup([f(g) for g in K.generators]) + success, new_rels = K_s_act._verify(K_act, f.compose(phi), f(z), d) + + for n in new_rels: + if n not in rels: + rels.append(n) + K = K_s + + group = FpGroup(F, rels) + return simplify_presentation(group) + + def presentation(self, eliminate_gens=True): + ''' + Return an `FpGroup` presentation of the group. + + The algorithm is described in [1], Chapter 6.1. + + ''' + from sympy.combinatorics.fp_groups import (FpGroup, + simplify_presentation) + from sympy.combinatorics.coset_table import CosetTable + from sympy.combinatorics.free_groups import free_group + from sympy.combinatorics.homomorphisms import homomorphism + + if self._fp_presentation: + return self._fp_presentation + + def _factor_group_by_rels(G, rels): + if isinstance(G, FpGroup): + rels.extend(G.relators) + return FpGroup(G.free_group, list(set(rels))) + return FpGroup(G, rels) + + gens = self.generators + len_g = len(gens) + + if len_g == 1: + order = gens[0].order() + # handle the trivial group + if order == 1: + return free_group([])[0] + F, x = free_group('x') + return FpGroup(F, [x**order]) + + if self.order() > 20: + half_gens = self.generators[0:(len_g+1)//2] + else: + half_gens = [] + H = PermutationGroup(half_gens) + H_p = H.presentation() + + len_h = len(H_p.generators) + + C = self.coset_table(H) + n = len(C) # subgroup index + + gen_syms = [('x_%d'%i) for i in range(len(gens))] + F = free_group(', '.join(gen_syms))[0] + + # mapping generators of H_p to those of F + images = [F.generators[i] for i in range(len_h)] + R = homomorphism(H_p, F, H_p.generators, images, check=False) + + # rewrite relators + rels = R(H_p.relators) + G_p = FpGroup(F, rels) + + # injective homomorphism from G_p into self + T = homomorphism(G_p, self, G_p.generators, gens) + + C_p = CosetTable(G_p, []) + + C_p.table = [[None]*(2*len_g) for i in range(n)] + + # initiate the coset transversal + transversal = [None]*n + transversal[0] = G_p.identity + + # fill in the coset table as much as possible + for i in range(2*len_h): + C_p.table[0][i] = 0 + + gamma = 1 + for alpha, x in product(range(n), range(2*len_g)): + beta = C[alpha][x] + if beta == gamma: + gen = G_p.generators[x//2]**((-1)**(x % 2)) + transversal[beta] = transversal[alpha]*gen + C_p.table[alpha][x] = beta + C_p.table[beta][x + (-1)**(x % 2)] = alpha + gamma += 1 + if gamma == n: + break + + C_p.p = list(range(n)) + beta = x = 0 + + while not C_p.is_complete(): + # find the first undefined entry + while C_p.table[beta][x] == C[beta][x]: + x = (x + 1) % (2*len_g) + if x == 0: + beta = (beta + 1) % n + + # define a new relator + gen = G_p.generators[x//2]**((-1)**(x % 2)) + new_rel = transversal[beta]*gen*transversal[C[beta][x]]**-1 + perm = T(new_rel) + nxt = G_p.identity + for s in H.generator_product(perm, original=True): + nxt = nxt*T.invert(s)**-1 + new_rel = new_rel*nxt + + # continue coset enumeration + G_p = _factor_group_by_rels(G_p, [new_rel]) + C_p.scan_and_fill(0, new_rel) + C_p = G_p.coset_enumeration([], strategy="coset_table", + draft=C_p, max_cosets=n, incomplete=True) + + self._fp_presentation = simplify_presentation(G_p) + return self._fp_presentation + + def polycyclic_group(self): + """ + Return the PolycyclicGroup instance with below parameters: + + Explanation + =========== + + * pc_sequence : Polycyclic sequence is formed by collecting all + the missing generators between the adjacent groups in the + derived series of given permutation group. + + * pc_series : Polycyclic series is formed by adding all the missing + generators of ``der[i+1]`` in ``der[i]``, where ``der`` represents + the derived series. + + * relative_order : A list, computed by the ratio of adjacent groups in + pc_series. + + """ + from sympy.combinatorics.pc_groups import PolycyclicGroup + if not self.is_polycyclic: + raise ValueError("The group must be solvable") + + der = self.derived_series() + pc_series = [] + pc_sequence = [] + relative_order = [] + pc_series.append(der[-1]) + der.reverse() + + for i in range(len(der)-1): + H = der[i] + for g in der[i+1].generators: + if g not in H: + H = PermutationGroup([g] + H.generators) + pc_series.insert(0, H) + pc_sequence.insert(0, g) + + G1 = pc_series[0].order() + G2 = pc_series[1].order() + relative_order.insert(0, G1 // G2) + + return PolycyclicGroup(pc_sequence, pc_series, relative_order, collector=None) + + +def _orbit(degree, generators, alpha, action='tuples'): + r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. + + Explanation + =========== + + The time complexity of the algorithm used here is `O(|Orb|*r)` where + `|Orb|` is the size of the orbit and ``r`` is the number of generators of + the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. + Here alpha can be a single point, or a list of points. + + If alpha is a single point, the ordinary orbit is computed. + if alpha is a list of points, there are three available options: + + 'union' - computes the union of the orbits of the points in the list + 'tuples' - computes the orbit of the list interpreted as an ordered + tuple under the group action ( i.e., g((1, 2, 3)) = (g(1), g(2), g(3)) ) + 'sets' - computes the orbit of the list interpreted as a sets + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> from sympy.combinatorics.perm_groups import _orbit + >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) + >>> G = PermutationGroup([a]) + >>> _orbit(G.degree, G.generators, 0) + {0, 1, 2} + >>> _orbit(G.degree, G.generators, [0, 4], 'union') + {0, 1, 2, 3, 4, 5, 6} + + See Also + ======== + + orbit, orbit_transversal + + """ + if not hasattr(alpha, '__getitem__'): + alpha = [alpha] + + gens = [x._array_form for x in generators] + if len(alpha) == 1 or action == 'union': + orb = alpha + used = [False]*degree + for el in alpha: + used[el] = True + for b in orb: + for gen in gens: + temp = gen[b] + if used[temp] == False: + orb.append(temp) + used[temp] = True + return set(orb) + elif action == 'tuples': + alpha = tuple(alpha) + orb = [alpha] + used = {alpha} + for b in orb: + for gen in gens: + temp = tuple([gen[x] for x in b]) + if temp not in used: + orb.append(temp) + used.add(temp) + return set(orb) + elif action == 'sets': + alpha = frozenset(alpha) + orb = [alpha] + used = {alpha} + for b in orb: + for gen in gens: + temp = frozenset([gen[x] for x in b]) + if temp not in used: + orb.append(temp) + used.add(temp) + return {tuple(x) for x in orb} + + +def _orbits(degree, generators): + """Compute the orbits of G. + + If ``rep=False`` it returns a list of sets else it returns a list of + representatives of the orbits + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy.combinatorics.perm_groups import _orbits + >>> a = Permutation([0, 2, 1]) + >>> b = Permutation([1, 0, 2]) + >>> _orbits(a.size, [a, b]) + [{0, 1, 2}] + """ + + orbs = [] + sorted_I = list(range(degree)) + I = set(sorted_I) + while I: + i = sorted_I[0] + orb = _orbit(degree, generators, i) + orbs.append(orb) + # remove all indices that are in this orbit + I -= orb + sorted_I = [i for i in sorted_I if i not in orb] + return orbs + + +def _orbit_transversal(degree, generators, alpha, pairs, af=False, slp=False): + r"""Computes a transversal for the orbit of ``alpha`` as a set. + + Explanation + =========== + + generators generators of the group ``G`` + + For a permutation group ``G``, a transversal for the orbit + `Orb = \{g(\alpha) | g \in G\}` is a set + `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. + Note that there may be more than one possible transversal. + If ``pairs`` is set to ``True``, it returns the list of pairs + `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 + + if ``af`` is ``True``, the transversal elements are given in + array form. + + If `slp` is `True`, a dictionary `{beta: slp_beta}` is returned + for `\beta \in Orb` where `slp_beta` is a list of indices of the + generators in `generators` s.t. if `slp_beta = [i_1 \dots i_n]` + `g_\beta = generators[i_n] \times \dots \times generators[i_1]`. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> from sympy.combinatorics.perm_groups import _orbit_transversal + >>> G = DihedralGroup(6) + >>> _orbit_transversal(G.degree, G.generators, 0, False) + [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] + """ + + tr = [(alpha, list(range(degree)))] + slp_dict = {alpha: []} + used = [False]*degree + used[alpha] = True + gens = [x._array_form for x in generators] + for x, px in tr: + px_slp = slp_dict[x] + for gen in gens: + temp = gen[x] + if used[temp] == False: + slp_dict[temp] = [gens.index(gen)] + px_slp + tr.append((temp, _af_rmul(gen, px))) + used[temp] = True + if pairs: + if not af: + tr = [(x, _af_new(y)) for x, y in tr] + if not slp: + return tr + return tr, slp_dict + + if af: + tr = [y for _, y in tr] + if not slp: + return tr + return tr, slp_dict + + tr = [_af_new(y) for _, y in tr] + if not slp: + return tr + return tr, slp_dict + + +def _stabilizer(degree, generators, alpha): + r"""Return the stabilizer subgroup of ``alpha``. + + Explanation + =========== + + The stabilizer of `\alpha` is the group `G_\alpha = + \{g \in G | g(\alpha) = \alpha\}`. + For a proof of correctness, see [1], p.79. + + degree : degree of G + generators : generators of G + + Examples + ======== + + >>> from sympy.combinatorics.perm_groups import _stabilizer + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> G = DihedralGroup(6) + >>> _stabilizer(G.degree, G.generators, 5) + [(5)(0 4)(1 3), (5)] + + See Also + ======== + + orbit + + """ + orb = [alpha] + table = {alpha: list(range(degree))} + table_inv = {alpha: list(range(degree))} + used = [False]*degree + used[alpha] = True + gens = [x._array_form for x in generators] + stab_gens = [] + for b in orb: + for gen in gens: + temp = gen[b] + if used[temp] is False: + gen_temp = _af_rmul(gen, table[b]) + orb.append(temp) + table[temp] = gen_temp + table_inv[temp] = _af_invert(gen_temp) + used[temp] = True + else: + schreier_gen = _af_rmuln(table_inv[temp], gen, table[b]) + if schreier_gen not in stab_gens: + stab_gens.append(schreier_gen) + return [_af_new(x) for x in stab_gens] + + +PermGroup = PermutationGroup + + +class SymmetricPermutationGroup(Basic): + """ + The class defining the lazy form of SymmetricGroup. + + deg : int + + """ + def __new__(cls, deg): + deg = _sympify(deg) + obj = Basic.__new__(cls, deg) + return obj + + def __init__(self, *args, **kwargs): + self._deg = self.args[0] + self._order = None + + def __contains__(self, i): + """Return ``True`` if *i* is contained in SymmetricPermutationGroup. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, SymmetricPermutationGroup + >>> G = SymmetricPermutationGroup(4) + >>> Permutation(1, 2, 3) in G + True + + """ + if not isinstance(i, Permutation): + raise TypeError("A SymmetricPermutationGroup contains only Permutations as " + "elements, not elements of type %s" % type(i)) + return i.size == self.degree + + def order(self): + """ + Return the order of the SymmetricPermutationGroup. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricPermutationGroup + >>> G = SymmetricPermutationGroup(4) + >>> G.order() + 24 + """ + if self._order is not None: + return self._order + n = self._deg + self._order = factorial(n) + return self._order + + @property + def degree(self): + """ + Return the degree of the SymmetricPermutationGroup. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricPermutationGroup + >>> G = SymmetricPermutationGroup(4) + >>> G.degree + 4 + + """ + return self._deg + + @property + def identity(self): + ''' + Return the identity element of the SymmetricPermutationGroup. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricPermutationGroup + >>> G = SymmetricPermutationGroup(4) + >>> G.identity() + (3) + + ''' + return _af_new(list(range(self._deg))) + + +class Coset(Basic): + """A left coset of a permutation group with respect to an element. + + Parameters + ========== + + g : Permutation + + H : PermutationGroup + + dir : "+" or "-", If not specified by default it will be "+" + here ``dir`` specified the type of coset "+" represent the + right coset and "-" represent the left coset. + + G : PermutationGroup, optional + The group which contains *H* as its subgroup and *g* as its + element. + + If not specified, it would automatically become a symmetric + group ``SymmetricPermutationGroup(g.size)`` and + ``SymmetricPermutationGroup(H.degree)`` if ``g.size`` and ``H.degree`` + are matching.``SymmetricPermutationGroup`` is a lazy form of SymmetricGroup + used for representation purpose. + + """ + + def __new__(cls, g, H, G=None, dir="+"): + g = _sympify(g) + if not isinstance(g, Permutation): + raise NotImplementedError + + H = _sympify(H) + if not isinstance(H, PermutationGroup): + raise NotImplementedError + + if G is not None: + G = _sympify(G) + if not isinstance(G, (PermutationGroup, SymmetricPermutationGroup)): + raise NotImplementedError + if not H.is_subgroup(G): + raise ValueError("{} must be a subgroup of {}.".format(H, G)) + if g not in G: + raise ValueError("{} must be an element of {}.".format(g, G)) + else: + g_size = g.size + h_degree = H.degree + if g_size != h_degree: + raise ValueError( + "The size of the permutation {} and the degree of " + "the permutation group {} should be matching " + .format(g, H)) + G = SymmetricPermutationGroup(g.size) + + if isinstance(dir, str): + dir = Symbol(dir) + elif not isinstance(dir, Symbol): + raise TypeError("dir must be of type basestring or " + "Symbol, not %s" % type(dir)) + if str(dir) not in ('+', '-'): + raise ValueError("dir must be one of '+' or '-' not %s" % dir) + obj = Basic.__new__(cls, g, H, G, dir) + return obj + + def __init__(self, *args, **kwargs): + self._dir = self.args[3] + + @property + def is_left_coset(self): + """ + Check if the coset is left coset that is ``gH``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset + >>> a = Permutation(1, 2) + >>> b = Permutation(0, 1) + >>> G = PermutationGroup([a, b]) + >>> cst = Coset(a, G, dir="-") + >>> cst.is_left_coset + True + + """ + return str(self._dir) == '-' + + @property + def is_right_coset(self): + """ + Check if the coset is right coset that is ``Hg``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset + >>> a = Permutation(1, 2) + >>> b = Permutation(0, 1) + >>> G = PermutationGroup([a, b]) + >>> cst = Coset(a, G, dir="+") + >>> cst.is_right_coset + True + + """ + return str(self._dir) == '+' + + def as_list(self): + """ + Return all the elements of coset in the form of list. + """ + g = self.args[0] + H = self.args[1] + cst = [] + if str(self._dir) == '+': + for h in H.elements: + cst.append(h*g) + else: + for h in H.elements: + cst.append(g*h) + return cst diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/permutations.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/permutations.py new file mode 100644 index 0000000000000000000000000000000000000000..3718467b69cbab2b9b0dd73e8fa160cceb0324bf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/permutations.py @@ -0,0 +1,3114 @@ +import random +from collections import defaultdict +from collections.abc import Iterable +from functools import reduce + +from sympy.core.parameters import global_parameters +from sympy.core.basic import Atom +from sympy.core.expr import Expr +from sympy.core.numbers import int_valued +from sympy.core.numbers import Integer +from sympy.core.sympify import _sympify +from sympy.matrices import zeros +from sympy.polys.polytools import lcm +from sympy.printing.repr import srepr +from sympy.utilities.iterables import (flatten, has_variety, minlex, + has_dups, runs, is_sequence) +from sympy.utilities.misc import as_int +from mpmath.libmp.libintmath import ifac +from sympy.multipledispatch import dispatch + +def _af_rmul(a, b): + """ + Return the product b*a; input and output are array forms. The ith value + is a[b[i]]. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_rmul, Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> _af_rmul(a, b) + [1, 2, 0] + >>> [a[b[i]] for i in range(3)] + [1, 2, 0] + + This handles the operands in reverse order compared to the ``*`` operator: + + >>> a = Permutation(a) + >>> b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + See Also + ======== + + rmul, _af_rmuln + """ + return [a[i] for i in b] + + +def _af_rmuln(*abc): + """ + Given [a, b, c, ...] return the product of ...*c*b*a using array forms. + The ith value is a[b[c[i]]]. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_rmul, Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> _af_rmul(a, b) + [1, 2, 0] + >>> [a[b[i]] for i in range(3)] + [1, 2, 0] + + This handles the operands in reverse order compared to the ``*`` operator: + + >>> a = Permutation(a); b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + See Also + ======== + + rmul, _af_rmul + """ + a = abc + m = len(a) + if m == 3: + p0, p1, p2 = a + return [p0[p1[i]] for i in p2] + if m == 4: + p0, p1, p2, p3 = a + return [p0[p1[p2[i]]] for i in p3] + if m == 5: + p0, p1, p2, p3, p4 = a + return [p0[p1[p2[p3[i]]]] for i in p4] + if m == 6: + p0, p1, p2, p3, p4, p5 = a + return [p0[p1[p2[p3[p4[i]]]]] for i in p5] + if m == 7: + p0, p1, p2, p3, p4, p5, p6 = a + return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6] + if m == 8: + p0, p1, p2, p3, p4, p5, p6, p7 = a + return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7] + if m == 1: + return a[0][:] + if m == 2: + a, b = a + return [a[i] for i in b] + if m == 0: + raise ValueError("String must not be empty") + p0 = _af_rmuln(*a[:m//2]) + p1 = _af_rmuln(*a[m//2:]) + return [p0[i] for i in p1] + + +def _af_parity(pi): + """ + Computes the parity of a permutation in array form. + + Explanation + =========== + + The parity of a permutation reflects the parity of the + number of inversions in the permutation, i.e., the + number of pairs of x and y such that x > y but p[x] < p[y]. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_parity + >>> _af_parity([0, 1, 2, 3]) + 0 + >>> _af_parity([3, 2, 0, 1]) + 1 + + See Also + ======== + + Permutation + """ + n = len(pi) + a = [0] * n + c = 0 + for j in range(n): + if a[j] == 0: + c += 1 + a[j] = 1 + i = j + while pi[i] != j: + i = pi[i] + a[i] = 1 + return (n - c) % 2 + + +def _af_invert(a): + """ + Finds the inverse, ~A, of a permutation, A, given in array form. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_invert, _af_rmul + >>> A = [1, 2, 0, 3] + >>> _af_invert(A) + [2, 0, 1, 3] + >>> _af_rmul(_, A) + [0, 1, 2, 3] + + See Also + ======== + + Permutation, __invert__ + """ + inv_form = [0] * len(a) + for i, ai in enumerate(a): + inv_form[ai] = i + return inv_form + + +def _af_pow(a, n): + """ + Routine for finding powers of a permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy.combinatorics.permutations import _af_pow + >>> p = Permutation([2, 0, 3, 1]) + >>> p.order() + 4 + >>> _af_pow(p._array_form, 4) + [0, 1, 2, 3] + """ + if n == 0: + return list(range(len(a))) + if n < 0: + return _af_pow(_af_invert(a), -n) + if n == 1: + return a[:] + elif n == 2: + b = [a[i] for i in a] + elif n == 3: + b = [a[a[i]] for i in a] + elif n == 4: + b = [a[a[a[i]]] for i in a] + else: + # use binary multiplication + b = list(range(len(a))) + while 1: + if n & 1: + b = [b[i] for i in a] + n -= 1 + if not n: + break + if n % 4 == 0: + a = [a[a[a[i]]] for i in a] + n = n // 4 + elif n % 2 == 0: + a = [a[i] for i in a] + n = n // 2 + return b + + +def _af_commutes_with(a, b): + """ + Checks if the two permutations with array forms + given by ``a`` and ``b`` commute. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_commutes_with + >>> _af_commutes_with([1, 2, 0], [0, 2, 1]) + False + + See Also + ======== + + Permutation, commutes_with + """ + return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1)) + + +class Cycle(dict): + """ + Wrapper around dict which provides the functionality of a disjoint cycle. + + Explanation + =========== + + A cycle shows the rule to use to move subsets of elements to obtain + a permutation. The Cycle class is more flexible than Permutation in + that 1) all elements need not be present in order to investigate how + multiple cycles act in sequence and 2) it can contain singletons: + + >>> from sympy.combinatorics.permutations import Perm, Cycle + + A Cycle will automatically parse a cycle given as a tuple on the rhs: + + >>> Cycle(1, 2)(2, 3) + (1 3 2) + + The identity cycle, Cycle(), can be used to start a product: + + >>> Cycle()(1, 2)(2, 3) + (1 3 2) + + The array form of a Cycle can be obtained by calling the list + method (or passing it to the list function) and all elements from + 0 will be shown: + + >>> a = Cycle(1, 2) + >>> a.list() + [0, 2, 1] + >>> list(a) + [0, 2, 1] + + If a larger (or smaller) range is desired use the list method and + provide the desired size -- but the Cycle cannot be truncated to + a size smaller than the largest element that is out of place: + + >>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3) + >>> b.list() + [0, 2, 1, 3, 4] + >>> b.list(b.size + 1) + [0, 2, 1, 3, 4, 5] + >>> b.list(-1) + [0, 2, 1] + + Singletons are not shown when printing with one exception: the largest + element is always shown -- as a singleton if necessary: + + >>> Cycle(1, 4, 10)(4, 5) + (1 5 4 10) + >>> Cycle(1, 2)(4)(5)(10) + (1 2)(10) + + The array form can be used to instantiate a Permutation so other + properties of the permutation can be investigated: + + >>> Perm(Cycle(1, 2)(3, 4).list()).transpositions() + [(1, 2), (3, 4)] + + Notes + ===== + + The underlying structure of the Cycle is a dictionary and although + the __iter__ method has been redefined to give the array form of the + cycle, the underlying dictionary items are still available with the + such methods as items(): + + >>> list(Cycle(1, 2).items()) + [(1, 2), (2, 1)] + + See Also + ======== + + Permutation + """ + def __missing__(self, arg): + """Enter arg into dictionary and return arg.""" + return as_int(arg) + + def __iter__(self): + yield from self.list() + + def __call__(self, *other): + """Return product of cycles processed from R to L. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2)(2, 3) + (1 3 2) + + An instance of a Cycle will automatically parse list-like + objects and Permutations that are on the right. It is more + flexible than the Permutation in that all elements need not + be present: + + >>> a = Cycle(1, 2) + >>> a(2, 3) + (1 3 2) + >>> a(2, 3)(4, 5) + (1 3 2)(4 5) + + """ + rv = Cycle(*other) + for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]): + rv[k] = v + return rv + + def list(self, size=None): + """Return the cycles as an explicit list starting from 0 up + to the greater of the largest value in the cycles and size. + + Truncation of trailing unmoved items will occur when size + is less than the maximum element in the cycle; if this is + desired, setting ``size=-1`` will guarantee such trimming. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> p = Cycle(2, 3)(4, 5) + >>> p.list() + [0, 1, 3, 2, 5, 4] + >>> p.list(10) + [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] + + Passing a length too small will trim trailing, unchanged elements + in the permutation: + + >>> Cycle(2, 4)(1, 2, 4).list(-1) + [0, 2, 1] + """ + if not self and size is None: + raise ValueError('must give size for empty Cycle') + if size is not None: + big = max([i for i in self.keys() if self[i] != i] + [0]) + size = max(size, big + 1) + else: + size = self.size + return [self[i] for i in range(size)] + + def __repr__(self): + """We want it to print as a Cycle, not as a dict. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2) + (1 2) + >>> print(_) + (1 2) + >>> list(Cycle(1, 2).items()) + [(1, 2), (2, 1)] + """ + if not self: + return 'Cycle()' + cycles = Permutation(self).cyclic_form + s = ''.join(str(tuple(c)) for c in cycles) + big = self.size - 1 + if not any(i == big for c in cycles for i in c): + s += '(%s)' % big + return 'Cycle%s' % s + + def __str__(self): + """We want it to be printed in a Cycle notation with no + comma in-between. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2) + (1 2) + >>> Cycle(1, 2, 4)(5, 6) + (1 2 4)(5 6) + """ + if not self: + return '()' + cycles = Permutation(self).cyclic_form + s = ''.join(str(tuple(c)) for c in cycles) + big = self.size - 1 + if not any(i == big for c in cycles for i in c): + s += '(%s)' % big + s = s.replace(',', '') + return s + + def __init__(self, *args): + """Load up a Cycle instance with the values for the cycle. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2, 6) + (1 2 6) + """ + + if not args: + return + if len(args) == 1: + if isinstance(args[0], Permutation): + for c in args[0].cyclic_form: + self.update(self(*c)) + return + elif isinstance(args[0], Cycle): + for k, v in args[0].items(): + self[k] = v + return + args = [as_int(a) for a in args] + if any(i < 0 for i in args): + raise ValueError('negative integers are not allowed in a cycle.') + if has_dups(args): + raise ValueError('All elements must be unique in a cycle.') + for i in range(-len(args), 0): + self[args[i]] = args[i + 1] + + @property + def size(self): + if not self: + return 0 + return max(self.keys()) + 1 + + def copy(self): + return Cycle(self) + + +class Permutation(Atom): + r""" + A permutation, alternatively known as an 'arrangement number' or 'ordering' + is an arrangement of the elements of an ordered list into a one-to-one + mapping with itself. The permutation of a given arrangement is given by + indicating the positions of the elements after re-arrangement [2]_. For + example, if one started with elements ``[x, y, a, b]`` (in that order) and + they were reordered as ``[x, y, b, a]`` then the permutation would be + ``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred + to as 0 and the permutation uses the indices of the elements in the + original ordering, not the elements ``(a, b, ...)`` themselves. + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + + Permutations Notation + ===================== + + Permutations are commonly represented in disjoint cycle or array forms. + + Array Notation and 2-line Form + ------------------------------------ + + In the 2-line form, the elements and their final positions are shown + as a matrix with 2 rows: + + [0 1 2 ... n-1] + [p(0) p(1) p(2) ... p(n-1)] + + Since the first line is always ``range(n)``, where n is the size of p, + it is sufficient to represent the permutation by the second line, + referred to as the "array form" of the permutation. This is entered + in brackets as the argument to the Permutation class: + + >>> p = Permutation([0, 2, 1]); p + Permutation([0, 2, 1]) + + Given i in range(p.size), the permutation maps i to i^p + + >>> [i^p for i in range(p.size)] + [0, 2, 1] + + The composite of two permutations p*q means first apply p, then q, so + i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules: + + >>> q = Permutation([2, 1, 0]) + >>> [i^p^q for i in range(3)] + [2, 0, 1] + >>> [i^(p*q) for i in range(3)] + [2, 0, 1] + + One can use also the notation p(i) = i^p, but then the composition + rule is (p*q)(i) = q(p(i)), not p(q(i)): + + >>> [(p*q)(i) for i in range(p.size)] + [2, 0, 1] + >>> [q(p(i)) for i in range(p.size)] + [2, 0, 1] + >>> [p(q(i)) for i in range(p.size)] + [1, 2, 0] + + Disjoint Cycle Notation + ----------------------- + + In disjoint cycle notation, only the elements that have shifted are + indicated. + + For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2). + This can be understood from the 2 line format of the given permutation. + In the 2-line form, + [0 1 2 3] + [1 3 2 0] + + The element in the 0th position is 1, so 0 -> 1. The element in the 1st + position is three, so 1 -> 3. And the element in the third position is again + 0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented + as 2 cycles: (0, 1, 3)(2). + In common notation, singular cycles are not explicitly written as they can be + inferred implicitly. + + Only the relative ordering of elements in a cycle matter: + + >>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2) + True + + The disjoint cycle notation is convenient when representing + permutations that have several cycles in them: + + >>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]]) + True + + It also provides some economy in entry when computing products of + permutations that are written in disjoint cycle notation: + + >>> Permutation(1, 2)(1, 3)(2, 3) + Permutation([0, 3, 2, 1]) + >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]]) + True + + Caution: when the cycles have common elements between them then the order + in which the permutations are applied matters. This module applies + the permutations from *left to right*. + + >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)]) + True + >>> Permutation(1, 2)(2, 3).list() + [0, 3, 1, 2] + + In the above case, (1,2) is computed before (2,3). + As 0 -> 0, 0 -> 0, element in position 0 is 0. + As 1 -> 2, 2 -> 3, element in position 1 is 3. + As 2 -> 1, 1 -> 1, element in position 2 is 1. + As 3 -> 3, 3 -> 2, element in position 3 is 2. + + If the first and second elements had been + swapped first, followed by the swapping of the second + and third, the result would have been [0, 2, 3, 1]. + If, you want to apply the cycles in the conventional + right to left order, call the function with arguments in reverse order + as demonstrated below: + + >>> Permutation([(1, 2), (2, 3)][::-1]).list() + [0, 2, 3, 1] + + Entering a singleton in a permutation is a way to indicate the size of the + permutation. The ``size`` keyword can also be used. + + Array-form entry: + + >>> Permutation([[1, 2], [9]]) + Permutation([0, 2, 1], size=10) + >>> Permutation([[1, 2]], size=10) + Permutation([0, 2, 1], size=10) + + Cyclic-form entry: + + >>> Permutation(1, 2, size=10) + Permutation([0, 2, 1], size=10) + >>> Permutation(9)(1, 2) + Permutation([0, 2, 1], size=10) + + Caution: no singleton containing an element larger than the largest + in any previous cycle can be entered. This is an important difference + in how Permutation and Cycle handle the ``__call__`` syntax. A singleton + argument at the start of a Permutation performs instantiation of the + Permutation and is permitted: + + >>> Permutation(5) + Permutation([], size=6) + + A singleton entered after instantiation is a call to the permutation + -- a function call -- and if the argument is out of range it will + trigger an error. For this reason, it is better to start the cycle + with the singleton: + + The following fails because there is no element 3: + + >>> Permutation(1, 2)(3) + Traceback (most recent call last): + ... + IndexError: list index out of range + + This is ok: only the call to an out of range singleton is prohibited; + otherwise the permutation autosizes: + + >>> Permutation(3)(1, 2) + Permutation([0, 2, 1, 3]) + >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2) + True + + + Equality testing + ---------------- + + The array forms must be the same in order for permutations to be equal: + + >>> Permutation([1, 0, 2, 3]) == Permutation([1, 0]) + False + + + Identity Permutation + -------------------- + + The identity permutation is a permutation in which no element is out of + place. It can be entered in a variety of ways. All the following create + an identity permutation of size 4: + + >>> I = Permutation([0, 1, 2, 3]) + >>> all(p == I for p in [ + ... Permutation(3), + ... Permutation(range(4)), + ... Permutation([], size=4), + ... Permutation(size=4)]) + True + + Watch out for entering the range *inside* a set of brackets (which is + cycle notation): + + >>> I == Permutation([range(4)]) + False + + + Permutation Printing + ==================== + + There are a few things to note about how Permutations are printed. + + .. deprecated:: 1.6 + + Configuring Permutation printing by setting + ``Permutation.print_cyclic`` is deprecated. Users should use the + ``perm_cyclic`` flag to the printers, as described below. + + 1) If you prefer one form (array or cycle) over another, you can set + ``init_printing`` with the ``perm_cyclic`` flag. + + >>> from sympy import init_printing + >>> p = Permutation(1, 2)(4, 5)(3, 4) + >>> p + Permutation([0, 2, 1, 4, 5, 3]) + + >>> init_printing(perm_cyclic=True, pretty_print=False) + >>> p + (1 2)(3 4 5) + + 2) Regardless of the setting, a list of elements in the array for cyclic + form can be obtained and either of those can be copied and supplied as + the argument to Permutation: + + >>> p.array_form + [0, 2, 1, 4, 5, 3] + >>> p.cyclic_form + [[1, 2], [3, 4, 5]] + >>> Permutation(_) == p + True + + 3) Printing is economical in that as little as possible is printed while + retaining all information about the size of the permutation: + + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation([1, 0, 2, 3]) + Permutation([1, 0, 2, 3]) + >>> Permutation([1, 0, 2, 3], size=20) + Permutation([1, 0], size=20) + >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20) + Permutation([1, 0, 2, 4, 3], size=20) + + >>> p = Permutation([1, 0, 2, 3]) + >>> init_printing(perm_cyclic=True, pretty_print=False) + >>> p + (3)(0 1) + >>> init_printing(perm_cyclic=False, pretty_print=False) + + The 2 was not printed but it is still there as can be seen with the + array_form and size methods: + + >>> p.array_form + [1, 0, 2, 3] + >>> p.size + 4 + + Short introduction to other methods + =================================== + + The permutation can act as a bijective function, telling what element is + located at a given position + + >>> q = Permutation([5, 2, 3, 4, 1, 0]) + >>> q.array_form[1] # the hard way + 2 + >>> q(1) # the easy way + 2 + >>> {i: q(i) for i in range(q.size)} # showing the bijection + {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0} + + The full cyclic form (including singletons) can be obtained: + + >>> p.full_cyclic_form + [[0, 1], [2], [3]] + + Any permutation can be factored into transpositions of pairs of elements: + + >>> Permutation([[1, 2], [3, 4, 5]]).transpositions() + [(1, 2), (3, 5), (3, 4)] + >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form + [[1, 2], [3, 4, 5]] + + The number of permutations on a set of n elements is given by n! and is + called the cardinality. + + >>> p.size + 4 + >>> p.cardinality + 24 + + A given permutation has a rank among all the possible permutations of the + same elements, but what that rank is depends on how the permutations are + enumerated. (There are a number of different methods of doing so.) The + lexicographic rank is given by the rank method and this rank is used to + increment a permutation with addition/subtraction: + + >>> p.rank() + 6 + >>> p + 1 + Permutation([1, 0, 3, 2]) + >>> p.next_lex() + Permutation([1, 0, 3, 2]) + >>> _.rank() + 7 + >>> p.unrank_lex(p.size, rank=7) + Permutation([1, 0, 3, 2]) + + The product of two permutations p and q is defined as their composition as + functions, (p*q)(i) = q(p(i)) [6]_. + + >>> p = Permutation([1, 0, 2, 3]) + >>> q = Permutation([2, 3, 1, 0]) + >>> list(q*p) + [2, 3, 0, 1] + >>> list(p*q) + [3, 2, 1, 0] + >>> [q(p(i)) for i in range(p.size)] + [3, 2, 1, 0] + + The permutation can be 'applied' to any list-like object, not only + Permutations: + + >>> p(['zero', 'one', 'four', 'two']) + ['one', 'zero', 'four', 'two'] + >>> p('zo42') + ['o', 'z', '4', '2'] + + If you have a list of arbitrary elements, the corresponding permutation + can be found with the from_sequence method: + + >>> Permutation.from_sequence('SymPy') + Permutation([1, 3, 2, 0, 4]) + + Checking if a Permutation is contained in a Group + ================================================= + + Generally if you have a group of permutations G on n symbols, and + you're checking if a permutation on less than n symbols is part + of that group, the check will fail. + + Here is an example for n=5 and we check if the cycle + (1,2,3) is in G: + + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=True, pretty_print=False) + >>> from sympy.combinatorics import Cycle, Permutation + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5)) + >>> p1 = Permutation(Cycle(2, 5, 3)) + >>> p2 = Permutation(Cycle(1, 2, 3)) + >>> a1 = Permutation(Cycle(1, 2, 3).list(6)) + >>> a2 = Permutation(Cycle(1, 2, 3)(5)) + >>> a3 = Permutation(Cycle(1, 2, 3),size=6) + >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p) + ((2 5 3), True) + ((1 2 3), False) + ((5)(1 2 3), True) + ((5)(1 2 3), True) + ((5)(1 2 3), True) + + The check for p2 above will fail. + + Checking if p1 is in G works because SymPy knows + G is a group on 5 symbols, and p1 is also on 5 symbols + (its largest element is 5). + + For ``a1``, the ``.list(6)`` call will extend the permutation to 5 + symbols, so the test will work as well. In the case of ``a2`` the + permutation is being extended to 5 symbols by using a singleton, + and in the case of ``a3`` it's extended through the constructor + argument ``size=6``. + + There is another way to do this, which is to tell the ``contains`` + method that the number of symbols the group is on does not need to + match perfectly the number of symbols for the permutation: + + >>> G.contains(p2,strict=False) + True + + This can be via the ``strict`` argument to the ``contains`` method, + and SymPy will try to extend the permutation on its own and then + perform the containment check. + + See Also + ======== + + Cycle + + References + ========== + + .. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics + Combinatorics and Graph Theory with Mathematica. Reading, MA: + Addison-Wesley, pp. 3-16, 1990. + + .. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial + Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011. + + .. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking + permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001), + 281-284. DOI=10.1016/S0020-0190(01)00141-7 + + .. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms' + CRC Press, 1999 + + .. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O. + Concrete Mathematics: A Foundation for Computer Science, 2nd ed. + Reading, MA: Addison-Wesley, 1994. + + .. [6] https://en.wikipedia.org/w/index.php?oldid=499948155#Product_and_inverse + + .. [7] https://en.wikipedia.org/wiki/Lehmer_code + + """ + + is_Permutation = True + + _array_form = None + _cyclic_form = None + _cycle_structure = None + _size = None + _rank = None + + def __new__(cls, *args, size=None, **kwargs): + """ + Constructor for the Permutation object from a list or a + list of lists in which all elements of the permutation may + appear only once. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + + Permutations entered in array-form are left unaltered: + + >>> Permutation([0, 2, 1]) + Permutation([0, 2, 1]) + + Permutations entered in cyclic form are converted to array form; + singletons need not be entered, but can be entered to indicate the + largest element: + + >>> Permutation([[4, 5, 6], [0, 1]]) + Permutation([1, 0, 2, 3, 5, 6, 4]) + >>> Permutation([[4, 5, 6], [0, 1], [19]]) + Permutation([1, 0, 2, 3, 5, 6, 4], size=20) + + All manipulation of permutations assumes that the smallest element + is 0 (in keeping with 0-based indexing in Python) so if the 0 is + missing when entering a permutation in array form, an error will be + raised: + + >>> Permutation([2, 1]) + Traceback (most recent call last): + ... + ValueError: Integers 0 through 2 must be present. + + If a permutation is entered in cyclic form, it can be entered without + singletons and the ``size`` specified so those values can be filled + in, otherwise the array form will only extend to the maximum value + in the cycles: + + >>> Permutation([[1, 4], [3, 5, 2]], size=10) + Permutation([0, 4, 3, 5, 1, 2], size=10) + >>> _.array_form + [0, 4, 3, 5, 1, 2, 6, 7, 8, 9] + """ + if size is not None: + size = int(size) + + #a) () + #b) (1) = identity + #c) (1, 2) = cycle + #d) ([1, 2, 3]) = array form + #e) ([[1, 2]]) = cyclic form + #f) (Cycle) = conversion to permutation + #g) (Permutation) = adjust size or return copy + ok = True + if not args: # a + return cls._af_new(list(range(size or 0))) + elif len(args) > 1: # c + return cls._af_new(Cycle(*args).list(size)) + if len(args) == 1: + a = args[0] + if isinstance(a, cls): # g + if size is None or size == a.size: + return a + return cls(a.array_form, size=size) + if isinstance(a, Cycle): # f + return cls._af_new(a.list(size)) + if not is_sequence(a): # b + if size is not None and a + 1 > size: + raise ValueError('size is too small when max is %s' % a) + return cls._af_new(list(range(a + 1))) + if has_variety(is_sequence(ai) for ai in a): + ok = False + else: + ok = False + if not ok: + raise ValueError("Permutation argument must be a list of ints, " + "a list of lists, Permutation or Cycle.") + + # safe to assume args are valid; this also makes a copy + # of the args + args = list(args[0]) + + is_cycle = args and is_sequence(args[0]) + if is_cycle: # e + args = [[int(i) for i in c] for c in args] + else: # d + args = [int(i) for i in args] + + # if there are n elements present, 0, 1, ..., n-1 should be present + # unless a cycle notation has been provided. A 0 will be added + # for convenience in case one wants to enter permutations where + # counting starts from 1. + + temp = flatten(args) + if has_dups(temp) and not is_cycle: + raise ValueError('there were repeated elements.') + temp = set(temp) + + if not is_cycle: + if temp != set(range(len(temp))): + raise ValueError('Integers 0 through %s must be present.' % + max(temp)) + if size is not None and temp and max(temp) + 1 > size: + raise ValueError('max element should not exceed %s' % (size - 1)) + + if is_cycle: + # it's not necessarily canonical so we won't store + # it -- use the array form instead + c = Cycle() + for ci in args: + c = c(*ci) + aform = c.list() + else: + aform = list(args) + if size and size > len(aform): + # don't allow for truncation of permutation which + # might split a cycle and lead to an invalid aform + # but do allow the permutation size to be increased + aform.extend(list(range(len(aform), size))) + + return cls._af_new(aform) + + @classmethod + def _af_new(cls, perm): + """A method to produce a Permutation object from a list; + the list is bound to the _array_form attribute, so it must + not be modified; this method is meant for internal use only; + the list ``a`` is supposed to be generated as a temporary value + in a method, so p = Perm._af_new(a) is the only object + to hold a reference to ``a``:: + + Examples + ======== + + >>> from sympy.combinatorics.permutations import Perm + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> a = [2, 1, 3, 0] + >>> p = Perm._af_new(a) + >>> p + Permutation([2, 1, 3, 0]) + + """ + p = super().__new__(cls) + p._array_form = perm + p._size = len(perm) + return p + + def copy(self): + return self.__class__(self.array_form) + + def __getnewargs__(self): + return (self.array_form,) + + def _hashable_content(self): + # the array_form (a list) is the Permutation arg, so we need to + # return a tuple, instead + return tuple(self.array_form) + + @property + def array_form(self): + """ + Return a copy of the attribute _array_form + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[2, 0], [3, 1]]) + >>> p.array_form + [2, 3, 0, 1] + >>> Permutation([[2, 0, 3, 1]]).array_form + [3, 2, 0, 1] + >>> Permutation([2, 0, 3, 1]).array_form + [2, 0, 3, 1] + >>> Permutation([[1, 2], [4, 5]]).array_form + [0, 2, 1, 3, 5, 4] + """ + return self._array_form[:] + + def list(self, size=None): + """Return the permutation as an explicit list, possibly + trimming unmoved elements if size is less than the maximum + element in the permutation; if this is desired, setting + ``size=-1`` will guarantee such trimming. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation(2, 3)(4, 5) + >>> p.list() + [0, 1, 3, 2, 5, 4] + >>> p.list(10) + [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] + + Passing a length too small will trim trailing, unchanged elements + in the permutation: + + >>> Permutation(2, 4)(1, 2, 4).list(-1) + [0, 2, 1] + >>> Permutation(3).list(-1) + [] + """ + if not self and size is None: + raise ValueError('must give size for empty Cycle') + rv = self.array_form + if size is not None: + if size > self.size: + rv.extend(list(range(self.size, size))) + else: + # find first value from rhs where rv[i] != i + i = self.size - 1 + while rv: + if rv[-1] != i: + break + rv.pop() + i -= 1 + return rv + + @property + def cyclic_form(self): + """ + This is used to convert to the cyclic notation + from the canonical notation. Singletons are omitted. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 3, 1, 2]) + >>> p.cyclic_form + [[1, 3, 2]] + >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form + [[0, 1], [3, 4]] + + See Also + ======== + + array_form, full_cyclic_form + """ + if self._cyclic_form is not None: + return list(self._cyclic_form) + array_form = self.array_form + unchecked = [True] * len(array_form) + cyclic_form = [] + for i in range(len(array_form)): + if unchecked[i]: + cycle = [] + cycle.append(i) + unchecked[i] = False + j = i + while unchecked[array_form[j]]: + j = array_form[j] + cycle.append(j) + unchecked[j] = False + if len(cycle) > 1: + cyclic_form.append(cycle) + assert cycle == list(minlex(cycle)) + cyclic_form.sort() + self._cyclic_form = cyclic_form.copy() + return cyclic_form + + @property + def full_cyclic_form(self): + """Return permutation in cyclic form including singletons. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 2, 1]).full_cyclic_form + [[0], [1, 2]] + """ + need = set(range(self.size)) - set(flatten(self.cyclic_form)) + rv = self.cyclic_form + [[i] for i in need] + rv.sort() + return rv + + @property + def size(self): + """ + Returns the number of elements in the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([[3, 2], [0, 1]]).size + 4 + + See Also + ======== + + cardinality, length, order, rank + """ + return self._size + + def support(self): + """Return the elements in permutation, P, for which P[i] != i. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[3, 2], [0, 1], [4]]) + >>> p.array_form + [1, 0, 3, 2, 4] + >>> p.support() + [0, 1, 2, 3] + """ + a = self.array_form + return [i for i, e in enumerate(a) if e != i] + + def __add__(self, other): + """Return permutation that is other higher in rank than self. + + The rank is the lexicographical rank, with the identity permutation + having rank of 0. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> I = Permutation([0, 1, 2, 3]) + >>> a = Permutation([2, 1, 3, 0]) + >>> I + a.rank() == a + True + + See Also + ======== + + __sub__, inversion_vector + + """ + rank = (self.rank() + other) % self.cardinality + rv = self.unrank_lex(self.size, rank) + rv._rank = rank + return rv + + def __sub__(self, other): + """Return the permutation that is other lower in rank than self. + + See Also + ======== + + __add__ + """ + return self.__add__(-other) + + @staticmethod + def rmul(*args): + """ + Return product of Permutations [a, b, c, ...] as the Permutation whose + ith value is a(b(c(i))). + + a, b, c, ... can be Permutation objects or tuples. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> a = Permutation(a); b = Permutation(b) + >>> list(Permutation.rmul(a, b)) + [1, 2, 0] + >>> [a(b(i)) for i in range(3)] + [1, 2, 0] + + This handles the operands in reverse order compared to the ``*`` operator: + + >>> a = Permutation(a); b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + Notes + ===== + + All items in the sequence will be parsed by Permutation as + necessary as long as the first item is a Permutation: + + >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b) + True + + The reverse order of arguments will raise a TypeError. + + """ + rv = args[0] + for i in range(1, len(args)): + rv = args[i]*rv + return rv + + @classmethod + def rmul_with_af(cls, *args): + """ + same as rmul, but the elements of args are Permutation objects + which have _array_form + """ + a = [x._array_form for x in args] + rv = cls._af_new(_af_rmuln(*a)) + return rv + + def mul_inv(self, other): + """ + other*~self, self and other have _array_form + """ + a = _af_invert(self._array_form) + b = other._array_form + return self._af_new(_af_rmul(a, b)) + + def __rmul__(self, other): + """This is needed to coerce other to Permutation in rmul.""" + cls = type(self) + return cls(other)*self + + def __mul__(self, other): + """ + Return the product a*b as a Permutation; the ith value is b(a(i)). + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_rmul, Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> a = Permutation(a); b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + This handles operands in reverse order compared to _af_rmul and rmul: + + >>> al = list(a); bl = list(b) + >>> _af_rmul(al, bl) + [1, 2, 0] + >>> [al[bl[i]] for i in range(3)] + [1, 2, 0] + + It is acceptable for the arrays to have different lengths; the shorter + one will be padded to match the longer one: + + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> b*Permutation([1, 0]) + Permutation([1, 2, 0]) + >>> Permutation([1, 0])*b + Permutation([2, 0, 1]) + + It is also acceptable to allow coercion to handle conversion of a + single list to the left of a Permutation: + + >>> [0, 1]*a # no change: 2-element identity + Permutation([1, 0, 2]) + >>> [[0, 1]]*a # exchange first two elements + Permutation([0, 1, 2]) + + You cannot use more than 1 cycle notation in a product of cycles + since coercion can only handle one argument to the left. To handle + multiple cycles it is convenient to use Cycle instead of Permutation: + + >>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP + >>> from sympy.combinatorics.permutations import Cycle + >>> Cycle(1, 2)(2, 3) + (1 3 2) + + """ + from sympy.combinatorics.perm_groups import PermutationGroup, Coset + if isinstance(other, PermutationGroup): + return Coset(self, other, dir='-') + a = self.array_form + # __rmul__ makes sure the other is a Permutation + b = other.array_form + if not b: + perm = a + else: + b.extend(list(range(len(b), len(a)))) + perm = [b[i] for i in a] + b[len(a):] + return self._af_new(perm) + + def commutes_with(self, other): + """ + Checks if the elements are commuting. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> a = Permutation([1, 4, 3, 0, 2, 5]) + >>> b = Permutation([0, 1, 2, 3, 4, 5]) + >>> a.commutes_with(b) + True + >>> b = Permutation([2, 3, 5, 4, 1, 0]) + >>> a.commutes_with(b) + False + """ + a = self.array_form + b = other.array_form + return _af_commutes_with(a, b) + + def __pow__(self, n): + """ + Routine for finding powers of a permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([2, 0, 3, 1]) + >>> p.order() + 4 + >>> p**4 + Permutation([0, 1, 2, 3]) + """ + if isinstance(n, Permutation): + raise NotImplementedError( + 'p**p is not defined; do you mean p^p (conjugate)?') + n = int(n) + return self._af_new(_af_pow(self.array_form, n)) + + def __rxor__(self, i): + """Return self(i) when ``i`` is an int. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation(1, 2, 9) + >>> 2^p == p(2) == 9 + True + """ + if int_valued(i): + return self(i) + else: + raise NotImplementedError( + "i^p = p(i) when i is an integer, not %s." % i) + + def __xor__(self, h): + """Return the conjugate permutation ``~h*self*h` `. + + Explanation + =========== + + If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and + ``b = ~h*a*h`` and both have the same cycle structure. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation(1, 2, 9) + >>> q = Permutation(6, 9, 8) + >>> p*q != q*p + True + + Calculate and check properties of the conjugate: + + >>> c = p^q + >>> c == ~q*p*q and p == q*c*~q + True + + The expression q^p^r is equivalent to q^(p*r): + + >>> r = Permutation(9)(4, 6, 8) + >>> q^p^r == q^(p*r) + True + + If the term to the left of the conjugate operator, i, is an integer + then this is interpreted as selecting the ith element from the + permutation to the right: + + >>> all(i^p == p(i) for i in range(p.size)) + True + + Note that the * operator as higher precedence than the ^ operator: + + >>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4) + True + + Notes + ===== + + In Python the precedence rule is p^q^r = (p^q)^r which differs + in general from p^(q^r) + + >>> q^p^r + (9)(1 4 8) + >>> q^(p^r) + (9)(1 8 6) + + For a given r and p, both of the following are conjugates of p: + ~r*p*r and r*p*~r. But these are not necessarily the same: + + >>> ~r*p*r == r*p*~r + True + + >>> p = Permutation(1, 2, 9)(5, 6) + >>> ~r*p*r == r*p*~r + False + + The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent + to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to + this method: + + >>> p^~r == r*p*~r + True + """ + + if self.size != h.size: + raise ValueError("The permutations must be of equal size.") + a = [None]*self.size + h = h._array_form + p = self._array_form + for i in range(self.size): + a[h[i]] = h[p[i]] + return self._af_new(a) + + def transpositions(self): + """ + Return the permutation decomposed into a list of transpositions. + + Explanation + =========== + + It is always possible to express a permutation as the product of + transpositions, see [1] + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]]) + >>> t = p.transpositions() + >>> t + [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)] + >>> print(''.join(str(c) for c in t)) + (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2) + >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties + + """ + a = self.cyclic_form + res = [] + for x in a: + nx = len(x) + if nx == 2: + res.append(tuple(x)) + elif nx > 2: + first = x[0] + res.extend((first, y) for y in x[nx - 1:0:-1]) + return res + + @classmethod + def from_sequence(self, i, key=None): + """Return the permutation needed to obtain ``i`` from the sorted + elements of ``i``. If custom sorting is desired, a key can be given. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + + >>> Permutation.from_sequence('SymPy') + (4)(0 1 3) + >>> _(sorted("SymPy")) + ['S', 'y', 'm', 'P', 'y'] + >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower()) + (4)(0 2)(1 3) + """ + ic = list(zip(i, list(range(len(i))))) + if key: + ic.sort(key=lambda x: key(x[0])) + else: + ic.sort() + return ~Permutation([i[1] for i in ic]) + + def __invert__(self): + """ + Return the inverse of the permutation. + + A permutation multiplied by its inverse is the identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([[2, 0], [3, 1]]) + >>> ~p + Permutation([2, 3, 0, 1]) + >>> _ == p**-1 + True + >>> p*~p == ~p*p == Permutation([0, 1, 2, 3]) + True + """ + return self._af_new(_af_invert(self._array_form)) + + def __iter__(self): + """Yield elements from array form. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> list(Permutation(range(3))) + [0, 1, 2] + """ + yield from self.array_form + + def __repr__(self): + return srepr(self) + + def __call__(self, *i): + """ + Allows applying a permutation instance as a bijective function. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[2, 0], [3, 1]]) + >>> p.array_form + [2, 3, 0, 1] + >>> [p(i) for i in range(4)] + [2, 3, 0, 1] + + If an array is given then the permutation selects the items + from the array (i.e. the permutation is applied to the array): + + >>> from sympy.abc import x + >>> p([x, 1, 0, x**2]) + [0, x**2, x, 1] + """ + # list indices can be Integer or int; leave this + # as it is (don't test or convert it) because this + # gets called a lot and should be fast + if len(i) == 1: + i = i[0] + if not isinstance(i, Iterable): + i = as_int(i) + if i < 0 or i > self.size: + raise TypeError( + "{} should be an integer between 0 and {}" + .format(i, self.size-1)) + return self._array_form[i] + # P([a, b, c]) + if len(i) != self.size: + raise TypeError( + "{} should have the length {}.".format(i, self.size)) + return [i[j] for j in self._array_form] + # P(1, 2, 3) + return self*Permutation(Cycle(*i), size=self.size) + + def atoms(self): + """ + Returns all the elements of a permutation + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 1, 2, 3, 4, 5]).atoms() + {0, 1, 2, 3, 4, 5} + >>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms() + {0, 1, 2, 3, 4, 5} + """ + return set(self.array_form) + + def apply(self, i): + r"""Apply the permutation to an expression. + + Parameters + ========== + + i : Expr + It should be an integer between $0$ and $n-1$ where $n$ + is the size of the permutation. + + If it is a symbol or a symbolic expression that can + have integer values, an ``AppliedPermutation`` object + will be returned which can represent an unevaluated + function. + + Notes + ===== + + Any permutation can be defined as a bijective function + $\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$ + where $n$ denotes the size of the permutation. + + The definition may even be extended for any set with distinctive + elements, such that the permutation can even be applied for + real numbers or such, however, it is not implemented for now for + computational reasons and the integrity with the group theory + module. + + This function is similar to the ``__call__`` magic, however, + ``__call__`` magic already has some other applications like + permuting an array or attaching new cycles, which would + not always be mathematically consistent. + + This also guarantees that the return type is a SymPy integer, + which guarantees the safety to use assumptions. + """ + i = _sympify(i) + if i.is_integer is False: + raise NotImplementedError("{} should be an integer.".format(i)) + + n = self.size + if (i < 0) == True or (i >= n) == True: + raise NotImplementedError( + "{} should be an integer between 0 and {}".format(i, n-1)) + + if i.is_Integer: + return Integer(self._array_form[i]) + return AppliedPermutation(self, i) + + def next_lex(self): + """ + Returns the next permutation in lexicographical order. + If self is the last permutation in lexicographical order + it returns None. + See [4] section 2.4. + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([2, 3, 1, 0]) + >>> p = Permutation([2, 3, 1, 0]); p.rank() + 17 + >>> p = p.next_lex(); p.rank() + 18 + + See Also + ======== + + rank, unrank_lex + """ + perm = self.array_form[:] + n = len(perm) + i = n - 2 + while perm[i + 1] < perm[i]: + i -= 1 + if i == -1: + return None + else: + j = n - 1 + while perm[j] < perm[i]: + j -= 1 + perm[j], perm[i] = perm[i], perm[j] + i += 1 + j = n - 1 + while i < j: + perm[j], perm[i] = perm[i], perm[j] + i += 1 + j -= 1 + return self._af_new(perm) + + @classmethod + def unrank_nonlex(self, n, r): + """ + This is a linear time unranking algorithm that does not + respect lexicographic order [3]. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation.unrank_nonlex(4, 5) + Permutation([2, 0, 3, 1]) + >>> Permutation.unrank_nonlex(4, -1) + Permutation([0, 1, 2, 3]) + + See Also + ======== + + next_nonlex, rank_nonlex + """ + def _unrank1(n, r, a): + if n > 0: + a[n - 1], a[r % n] = a[r % n], a[n - 1] + _unrank1(n - 1, r//n, a) + + id_perm = list(range(n)) + n = int(n) + r = r % ifac(n) + _unrank1(n, r, id_perm) + return self._af_new(id_perm) + + def rank_nonlex(self, inv_perm=None): + """ + This is a linear time ranking algorithm that does not + enforce lexicographic order [3]. + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.rank_nonlex() + 23 + + See Also + ======== + + next_nonlex, unrank_nonlex + """ + def _rank1(n, perm, inv_perm): + if n == 1: + return 0 + s = perm[n - 1] + t = inv_perm[n - 1] + perm[n - 1], perm[t] = perm[t], s + inv_perm[n - 1], inv_perm[s] = inv_perm[s], t + return s + n*_rank1(n - 1, perm, inv_perm) + + if inv_perm is None: + inv_perm = (~self).array_form + if not inv_perm: + return 0 + perm = self.array_form[:] + r = _rank1(len(perm), perm, inv_perm) + return r + + def next_nonlex(self): + """ + Returns the next permutation in nonlex order [3]. + If self is the last permutation in this order it returns None. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex() + 5 + >>> p = p.next_nonlex(); p + Permutation([3, 0, 1, 2]) + >>> p.rank_nonlex() + 6 + + See Also + ======== + + rank_nonlex, unrank_nonlex + """ + r = self.rank_nonlex() + if r == ifac(self.size) - 1: + return None + return self.unrank_nonlex(self.size, r + 1) + + def rank(self): + """ + Returns the lexicographic rank of the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.rank() + 0 + >>> p = Permutation([3, 2, 1, 0]) + >>> p.rank() + 23 + + See Also + ======== + + next_lex, unrank_lex, cardinality, length, order, size + """ + if self._rank is not None: + return self._rank + rank = 0 + rho = self.array_form[:] + n = self.size - 1 + size = n + 1 + psize = int(ifac(n)) + for j in range(size - 1): + rank += rho[j]*psize + for i in range(j + 1, size): + if rho[i] > rho[j]: + rho[i] -= 1 + psize //= n + n -= 1 + self._rank = rank + return rank + + @property + def cardinality(self): + """ + Returns the number of all possible permutations. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.cardinality + 24 + + See Also + ======== + + length, order, rank, size + """ + return int(ifac(self.size)) + + def parity(self): + """ + Computes the parity of a permutation. + + Explanation + =========== + + The parity of a permutation reflects the parity of the + number of inversions in the permutation, i.e., the + number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.parity() + 0 + >>> p = Permutation([3, 2, 0, 1]) + >>> p.parity() + 1 + + See Also + ======== + + _af_parity + """ + if self._cyclic_form is not None: + return (self.size - self.cycles) % 2 + + return _af_parity(self.array_form) + + @property + def is_even(self): + """ + Checks if a permutation is even. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.is_even + True + >>> p = Permutation([3, 2, 1, 0]) + >>> p.is_even + True + + See Also + ======== + + is_odd + """ + return not self.is_odd + + @property + def is_odd(self): + """ + Checks if a permutation is odd. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.is_odd + False + >>> p = Permutation([3, 2, 0, 1]) + >>> p.is_odd + True + + See Also + ======== + + is_even + """ + return bool(self.parity() % 2) + + @property + def is_Singleton(self): + """ + Checks to see if the permutation contains only one number and is + thus the only possible permutation of this set of numbers + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0]).is_Singleton + True + >>> Permutation([0, 1]).is_Singleton + False + + See Also + ======== + + is_Empty + """ + return self.size == 1 + + @property + def is_Empty(self): + """ + Checks to see if the permutation is a set with zero elements + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([]).is_Empty + True + >>> Permutation([0]).is_Empty + False + + See Also + ======== + + is_Singleton + """ + return self.size == 0 + + @property + def is_identity(self): + return self.is_Identity + + @property + def is_Identity(self): + """ + Returns True if the Permutation is an identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([]) + >>> p.is_Identity + True + >>> p = Permutation([[0], [1], [2]]) + >>> p.is_Identity + True + >>> p = Permutation([0, 1, 2]) + >>> p.is_Identity + True + >>> p = Permutation([0, 2, 1]) + >>> p.is_Identity + False + + See Also + ======== + + order + """ + af = self.array_form + return not af or all(i == af[i] for i in range(self.size)) + + def ascents(self): + """ + Returns the positions of ascents in a permutation, ie, the location + where p[i] < p[i+1] + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([4, 0, 1, 3, 2]) + >>> p.ascents() + [1, 2] + + See Also + ======== + + descents, inversions, min, max + """ + a = self.array_form + pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]] + return pos + + def descents(self): + """ + Returns the positions of descents in a permutation, ie, the location + where p[i] > p[i+1] + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([4, 0, 1, 3, 2]) + >>> p.descents() + [0, 3] + + See Also + ======== + + ascents, inversions, min, max + """ + a = self.array_form + pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]] + return pos + + def max(self) -> int: + """ + The maximum element moved by the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([1, 0, 2, 3, 4]) + >>> p.max() + 1 + + See Also + ======== + + min, descents, ascents, inversions + """ + a = self.array_form + if not a: + return 0 + return max(_a for i, _a in enumerate(a) if _a != i) + + def min(self) -> int: + """ + The minimum element moved by the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 4, 3, 2]) + >>> p.min() + 2 + + See Also + ======== + + max, descents, ascents, inversions + """ + a = self.array_form + if not a: + return 0 + return min(_a for i, _a in enumerate(a) if _a != i) + + def inversions(self): + """ + Computes the number of inversions of a permutation. + + Explanation + =========== + + An inversion is where i > j but p[i] < p[j]. + + For small length of p, it iterates over all i and j + values and calculates the number of inversions. + For large length of p, it uses a variation of merge + sort to calculate the number of inversions. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3, 4, 5]) + >>> p.inversions() + 0 + >>> Permutation([3, 2, 1, 0]).inversions() + 6 + + See Also + ======== + + descents, ascents, min, max + + References + ========== + + .. [1] https://www.cp.eng.chula.ac.th/~prabhas//teaching/algo/algo2008/count-inv.htm + + """ + inversions = 0 + a = self.array_form + n = len(a) + if n < 130: + for i in range(n - 1): + b = a[i] + for c in a[i + 1:]: + if b > c: + inversions += 1 + else: + k = 1 + right = 0 + arr = a[:] + temp = a[:] + while k < n: + i = 0 + while i + k < n: + right = i + k * 2 - 1 + if right >= n: + right = n - 1 + inversions += _merge(arr, temp, i, i + k, right) + i = i + k * 2 + k = k * 2 + return inversions + + def commutator(self, x): + """Return the commutator of ``self`` and ``x``: ``~x*~self*x*self`` + + If f and g are part of a group, G, then the commutator of f and g + is the group identity iff f and g commute, i.e. fg == gf. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([0, 2, 3, 1]) + >>> x = Permutation([2, 0, 3, 1]) + >>> c = p.commutator(x); c + Permutation([2, 1, 3, 0]) + >>> c == ~x*~p*x*p + True + + >>> I = Permutation(3) + >>> p = [I + i for i in range(6)] + >>> for i in range(len(p)): + ... for j in range(len(p)): + ... c = p[i].commutator(p[j]) + ... if p[i]*p[j] == p[j]*p[i]: + ... assert c == I + ... else: + ... assert c != I + ... + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Commutator + """ + + a = self.array_form + b = x.array_form + n = len(a) + if len(b) != n: + raise ValueError("The permutations must be of equal size.") + inva = [None]*n + for i in range(n): + inva[a[i]] = i + invb = [None]*n + for i in range(n): + invb[b[i]] = i + return self._af_new([a[b[inva[i]]] for i in invb]) + + def signature(self): + """ + Gives the signature of the permutation needed to place the + elements of the permutation in canonical order. + + The signature is calculated as (-1)^ + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2]) + >>> p.inversions() + 0 + >>> p.signature() + 1 + >>> q = Permutation([0,2,1]) + >>> q.inversions() + 1 + >>> q.signature() + -1 + + See Also + ======== + + inversions + """ + if self.is_even: + return 1 + return -1 + + def order(self): + """ + Computes the order of a permutation. + + When the permutation is raised to the power of its + order it equals the identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([3, 1, 5, 2, 4, 0]) + >>> p.order() + 4 + >>> (p**(p.order())) + Permutation([], size=6) + + See Also + ======== + + identity, cardinality, length, rank, size + """ + + return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1) + + def length(self): + """ + Returns the number of integers moved by a permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 3, 2, 1]).length() + 2 + >>> Permutation([[0, 1], [2, 3]]).length() + 4 + + See Also + ======== + + min, max, support, cardinality, order, rank, size + """ + + return len(self.support()) + + @property + def cycle_structure(self): + """Return the cycle structure of the permutation as a dictionary + indicating the multiplicity of each cycle length. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation(3).cycle_structure + {1: 4} + >>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure + {2: 2, 3: 1} + """ + if self._cycle_structure: + rv = self._cycle_structure + else: + rv = defaultdict(int) + singletons = self.size + for c in self.cyclic_form: + rv[len(c)] += 1 + singletons -= len(c) + if singletons: + rv[1] = singletons + self._cycle_structure = rv + return dict(rv) # make a copy + + @property + def cycles(self): + """ + Returns the number of cycles contained in the permutation + (including singletons). + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 1, 2]).cycles + 3 + >>> Permutation([0, 1, 2]).full_cyclic_form + [[0], [1], [2]] + >>> Permutation(0, 1)(2, 3).cycles + 2 + + See Also + ======== + sympy.functions.combinatorial.numbers.stirling + """ + return len(self.full_cyclic_form) + + def index(self): + """ + Returns the index of a permutation. + + The index of a permutation is the sum of all subscripts j such + that p[j] is greater than p[j+1]. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([3, 0, 2, 1, 4]) + >>> p.index() + 2 + """ + a = self.array_form + + return sum(j for j in range(len(a) - 1) if a[j] > a[j + 1]) + + def runs(self): + """ + Returns the runs of a permutation. + + An ascending sequence in a permutation is called a run [5]. + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8]) + >>> p.runs() + [[2, 5, 7], [3, 6], [0, 1, 4, 8]] + >>> q = Permutation([1,3,2,0]) + >>> q.runs() + [[1, 3], [2], [0]] + """ + return runs(self.array_form) + + def inversion_vector(self): + """Return the inversion vector of the permutation. + + The inversion vector consists of elements whose value + indicates the number of elements in the permutation + that are lesser than it and lie on its right hand side. + + The inversion vector is the same as the Lehmer encoding of a + permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2]) + >>> p.inversion_vector() + [4, 7, 0, 5, 0, 2, 1, 1] + >>> p = Permutation([3, 2, 1, 0]) + >>> p.inversion_vector() + [3, 2, 1] + + The inversion vector increases lexicographically with the rank + of the permutation, the -ith element cycling through 0..i. + + >>> p = Permutation(2) + >>> while p: + ... print('%s %s %s' % (p, p.inversion_vector(), p.rank())) + ... p = p.next_lex() + (2) [0, 0] 0 + (1 2) [0, 1] 1 + (2)(0 1) [1, 0] 2 + (0 1 2) [1, 1] 3 + (0 2 1) [2, 0] 4 + (0 2) [2, 1] 5 + + See Also + ======== + + from_inversion_vector + """ + self_array_form = self.array_form + n = len(self_array_form) + inversion_vector = [0] * (n - 1) + + for i in range(n - 1): + val = 0 + for j in range(i + 1, n): + if self_array_form[j] < self_array_form[i]: + val += 1 + inversion_vector[i] = val + return inversion_vector + + def rank_trotterjohnson(self): + """ + Returns the Trotter Johnson rank, which we get from the minimal + change algorithm. See [4] section 2.4. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.rank_trotterjohnson() + 0 + >>> p = Permutation([0, 2, 1, 3]) + >>> p.rank_trotterjohnson() + 7 + + See Also + ======== + + unrank_trotterjohnson, next_trotterjohnson + """ + if self.array_form == [] or self.is_Identity: + return 0 + if self.array_form == [1, 0]: + return 1 + perm = self.array_form + n = self.size + rank = 0 + for j in range(1, n): + k = 1 + i = 0 + while perm[i] != j: + if perm[i] < j: + k += 1 + i += 1 + j1 = j + 1 + if rank % 2 == 0: + rank = j1*rank + j1 - k + else: + rank = j1*rank + k - 1 + return rank + + @classmethod + def unrank_trotterjohnson(cls, size, rank): + """ + Trotter Johnson permutation unranking. See [4] section 2.4. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation.unrank_trotterjohnson(5, 10) + Permutation([0, 3, 1, 2, 4]) + + See Also + ======== + + rank_trotterjohnson, next_trotterjohnson + """ + perm = [0]*size + r2 = 0 + n = ifac(size) + pj = 1 + for j in range(2, size + 1): + pj *= j + r1 = (rank * pj) // n + k = r1 - j*r2 + if r2 % 2 == 0: + for i in range(j - 1, j - k - 1, -1): + perm[i] = perm[i - 1] + perm[j - k - 1] = j - 1 + else: + for i in range(j - 1, k, -1): + perm[i] = perm[i - 1] + perm[k] = j - 1 + r2 = r1 + return cls._af_new(perm) + + def next_trotterjohnson(self): + """ + Returns the next permutation in Trotter-Johnson order. + If self is the last permutation it returns None. + See [4] section 2.4. If it is desired to generate all such + permutations, they can be generated in order more quickly + with the ``generate_bell`` function. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([3, 0, 2, 1]) + >>> p.rank_trotterjohnson() + 4 + >>> p = p.next_trotterjohnson(); p + Permutation([0, 3, 2, 1]) + >>> p.rank_trotterjohnson() + 5 + + See Also + ======== + + rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell + """ + pi = self.array_form[:] + n = len(pi) + st = 0 + rho = pi[:] + done = False + m = n-1 + while m > 0 and not done: + d = rho.index(m) + for i in range(d, m): + rho[i] = rho[i + 1] + par = _af_parity(rho[:m]) + if par == 1: + if d == m: + m -= 1 + else: + pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d] + done = True + else: + if d == 0: + m -= 1 + st += 1 + else: + pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d] + done = True + if m == 0: + return None + return self._af_new(pi) + + def get_precedence_matrix(self): + """ + Gets the precedence matrix. This is used for computing the + distance between two permutations. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation.josephus(3, 6, 1) + >>> p + Permutation([2, 5, 3, 1, 4, 0]) + >>> p.get_precedence_matrix() + Matrix([ + [0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 1, 0], + [1, 1, 0, 1, 1, 1], + [1, 1, 0, 0, 1, 0], + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 1, 1, 0]]) + + See Also + ======== + + get_precedence_distance, get_adjacency_matrix, get_adjacency_distance + """ + m = zeros(self.size) + perm = self.array_form + for i in range(m.rows): + for j in range(i + 1, m.cols): + m[perm[i], perm[j]] = 1 + return m + + def get_precedence_distance(self, other): + """ + Computes the precedence distance between two permutations. + + Explanation + =========== + + Suppose p and p' represent n jobs. The precedence metric + counts the number of times a job j is preceded by job i + in both p and p'. This metric is commutative. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([2, 0, 4, 3, 1]) + >>> q = Permutation([3, 1, 2, 4, 0]) + >>> p.get_precedence_distance(q) + 7 + >>> q.get_precedence_distance(p) + 7 + + See Also + ======== + + get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance + """ + if self.size != other.size: + raise ValueError("The permutations must be of equal size.") + self_prec_mat = self.get_precedence_matrix() + other_prec_mat = other.get_precedence_matrix() + n_prec = 0 + for i in range(self.size): + for j in range(self.size): + if i == j: + continue + if self_prec_mat[i, j] * other_prec_mat[i, j] == 1: + n_prec += 1 + d = self.size * (self.size - 1)//2 - n_prec + return d + + def get_adjacency_matrix(self): + """ + Computes the adjacency matrix of a permutation. + + Explanation + =========== + + If job i is adjacent to job j in a permutation p + then we set m[i, j] = 1 where m is the adjacency + matrix of p. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation.josephus(3, 6, 1) + >>> p.get_adjacency_matrix() + Matrix([ + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 1], + [0, 1, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0]]) + >>> q = Permutation([0, 1, 2, 3]) + >>> q.get_adjacency_matrix() + Matrix([ + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + [0, 0, 0, 0]]) + + See Also + ======== + + get_precedence_matrix, get_precedence_distance, get_adjacency_distance + """ + m = zeros(self.size) + perm = self.array_form + for i in range(self.size - 1): + m[perm[i], perm[i + 1]] = 1 + return m + + def get_adjacency_distance(self, other): + """ + Computes the adjacency distance between two permutations. + + Explanation + =========== + + This metric counts the number of times a pair i,j of jobs is + adjacent in both p and p'. If n_adj is this quantity then + the adjacency distance is n - n_adj - 1 [1] + + [1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals + of Operational Research, 86, pp 473-490. (1999) + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 3, 1, 2, 4]) + >>> q = Permutation.josephus(4, 5, 2) + >>> p.get_adjacency_distance(q) + 3 + >>> r = Permutation([0, 2, 1, 4, 3]) + >>> p.get_adjacency_distance(r) + 4 + + See Also + ======== + + get_precedence_matrix, get_precedence_distance, get_adjacency_matrix + """ + if self.size != other.size: + raise ValueError("The permutations must be of the same size.") + self_adj_mat = self.get_adjacency_matrix() + other_adj_mat = other.get_adjacency_matrix() + n_adj = 0 + for i in range(self.size): + for j in range(self.size): + if i == j: + continue + if self_adj_mat[i, j] * other_adj_mat[i, j] == 1: + n_adj += 1 + d = self.size - n_adj - 1 + return d + + def get_positional_distance(self, other): + """ + Computes the positional distance between two permutations. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 3, 1, 2, 4]) + >>> q = Permutation.josephus(4, 5, 2) + >>> r = Permutation([3, 1, 4, 0, 2]) + >>> p.get_positional_distance(q) + 12 + >>> p.get_positional_distance(r) + 12 + + See Also + ======== + + get_precedence_distance, get_adjacency_distance + """ + a = self.array_form + b = other.array_form + if len(a) != len(b): + raise ValueError("The permutations must be of the same size.") + return sum(abs(a[i] - b[i]) for i in range(len(a))) + + @classmethod + def josephus(cls, m, n, s=1): + """Return as a permutation the shuffling of range(n) using the Josephus + scheme in which every m-th item is selected until all have been chosen. + The returned permutation has elements listed by the order in which they + were selected. + + The parameter ``s`` stops the selection process when there are ``s`` + items remaining and these are selected by continuing the selection, + counting by 1 rather than by ``m``. + + Consider selecting every 3rd item from 6 until only 2 remain:: + + choices chosen + ======== ====== + 012345 + 01 345 2 + 01 34 25 + 01 4 253 + 0 4 2531 + 0 25314 + 253140 + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation.josephus(3, 6, 2).array_form + [2, 5, 3, 1, 4, 0] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Flavius_Josephus + .. [2] https://en.wikipedia.org/wiki/Josephus_problem + .. [3] https://web.archive.org/web/20171008094331/http://www.wou.edu/~burtonl/josephus.html + + """ + from collections import deque + m -= 1 + Q = deque(list(range(n))) + perm = [] + while len(Q) > max(s, 1): + for dp in range(m): + Q.append(Q.popleft()) + perm.append(Q.popleft()) + perm.extend(list(Q)) + return cls(perm) + + @classmethod + def from_inversion_vector(cls, inversion): + """ + Calculates the permutation from the inversion vector. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0]) + Permutation([3, 2, 1, 0, 4, 5]) + + """ + size = len(inversion) + N = list(range(size + 1)) + perm = [] + try: + for k in range(size): + val = N[inversion[k]] + perm.append(val) + N.remove(val) + except IndexError: + raise ValueError("The inversion vector is not valid.") + perm.extend(N) + return cls._af_new(perm) + + @classmethod + def random(cls, n): + """ + Generates a random permutation of length ``n``. + + Uses the underlying Python pseudo-random number generator. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) + True + + """ + perm_array = list(range(n)) + random.shuffle(perm_array) + return cls._af_new(perm_array) + + @classmethod + def unrank_lex(cls, size, rank): + """ + Lexicographic permutation unranking. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> a = Permutation.unrank_lex(5, 10) + >>> a.rank() + 10 + >>> a + Permutation([0, 2, 4, 1, 3]) + + See Also + ======== + + rank, next_lex + """ + perm_array = [0] * size + psize = 1 + for i in range(size): + new_psize = psize*(i + 1) + d = (rank % new_psize) // psize + rank -= d*psize + perm_array[size - i - 1] = d + for j in range(size - i, size): + if perm_array[j] > d - 1: + perm_array[j] += 1 + psize = new_psize + return cls._af_new(perm_array) + + def resize(self, n): + """Resize the permutation to the new size ``n``. + + Parameters + ========== + + n : int + The new size of the permutation. + + Raises + ====== + + ValueError + If the permutation cannot be resized to the given size. + This may only happen when resized to a smaller size than + the original. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + + Increasing the size of a permutation: + + >>> p = Permutation(0, 1, 2) + >>> p = p.resize(5) + >>> p + (4)(0 1 2) + + Decreasing the size of the permutation: + + >>> p = p.resize(4) + >>> p + (3)(0 1 2) + + If resizing to the specific size breaks the cycles: + + >>> p.resize(2) + Traceback (most recent call last): + ... + ValueError: The permutation cannot be resized to 2 because the + cycle (0, 1, 2) may break. + """ + aform = self.array_form + l = len(aform) + if n > l: + aform += list(range(l, n)) + return Permutation._af_new(aform) + + elif n < l: + cyclic_form = self.full_cyclic_form + new_cyclic_form = [] + for cycle in cyclic_form: + cycle_min = min(cycle) + cycle_max = max(cycle) + if cycle_min <= n-1: + if cycle_max > n-1: + raise ValueError( + "The permutation cannot be resized to {} " + "because the cycle {} may break." + .format(n, tuple(cycle))) + + new_cyclic_form.append(cycle) + return Permutation(new_cyclic_form) + + return self + + # XXX Deprecated flag + print_cyclic = None + + +def _merge(arr, temp, left, mid, right): + """ + Merges two sorted arrays and calculates the inversion count. + + Helper function for calculating inversions. This method is + for internal use only. + """ + i = k = left + j = mid + inv_count = 0 + while i < mid and j <= right: + if arr[i] < arr[j]: + temp[k] = arr[i] + k += 1 + i += 1 + else: + temp[k] = arr[j] + k += 1 + j += 1 + inv_count += (mid -i) + while i < mid: + temp[k] = arr[i] + k += 1 + i += 1 + if j <= right: + k += right - j + 1 + j += right - j + 1 + arr[left:k + 1] = temp[left:k + 1] + else: + arr[left:right + 1] = temp[left:right + 1] + return inv_count + +Perm = Permutation +_af_new = Perm._af_new + + +class AppliedPermutation(Expr): + """A permutation applied to a symbolic variable. + + Parameters + ========== + + perm : Permutation + x : Expr + + Examples + ======== + + >>> from sympy import Symbol + >>> from sympy.combinatorics import Permutation + + Creating a symbolic permutation function application: + + >>> x = Symbol('x') + >>> p = Permutation(0, 1, 2) + >>> p.apply(x) + AppliedPermutation((0 1 2), x) + >>> _.subs(x, 1) + 2 + """ + def __new__(cls, perm, x, evaluate=None): + if evaluate is None: + evaluate = global_parameters.evaluate + + perm = _sympify(perm) + x = _sympify(x) + + if not isinstance(perm, Permutation): + raise ValueError("{} must be a Permutation instance." + .format(perm)) + + if evaluate: + if x.is_Integer: + return perm.apply(x) + + obj = super().__new__(cls, perm, x) + return obj + + +@dispatch(Permutation, Permutation) +def _eval_is_eq(lhs, rhs): + if lhs._size != rhs._size: + return None + return lhs._array_form == rhs._array_form diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/polyhedron.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/polyhedron.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc05d7d97c840649661f3290442499c841ca7c1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/polyhedron.py @@ -0,0 +1,1019 @@ +from sympy.combinatorics import Permutation as Perm +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.core import Basic, Tuple, default_sort_key +from sympy.sets import FiniteSet +from sympy.utilities.iterables import (minlex, unflatten, flatten) +from sympy.utilities.misc import as_int + +rmul = Perm.rmul + + +class Polyhedron(Basic): + """ + Represents the polyhedral symmetry group (PSG). + + Explanation + =========== + + The PSG is one of the symmetry groups of the Platonic solids. + There are three polyhedral groups: the tetrahedral group + of order 12, the octahedral group of order 24, and the + icosahedral group of order 60. + + All doctests have been given in the docstring of the + constructor of the object. + + References + ========== + + .. [1] https://mathworld.wolfram.com/PolyhedralGroup.html + + """ + _edges = None + + def __new__(cls, corners, faces=(), pgroup=()): + """ + The constructor of the Polyhedron group object. + + Explanation + =========== + + It takes up to three parameters: the corners, faces, and + allowed transformations. + + The corners/vertices are entered as a list of arbitrary + expressions that are used to identify each vertex. + + The faces are entered as a list of tuples of indices; a tuple + of indices identifies the vertices which define the face. They + should be entered in a cw or ccw order; they will be standardized + by reversal and rotation to be give the lowest lexical ordering. + If no faces are given then no edges will be computed. + + >>> from sympy.combinatorics.polyhedron import Polyhedron + >>> Polyhedron(list('abc'), [(1, 2, 0)]).faces + {(0, 1, 2)} + >>> Polyhedron(list('abc'), [(1, 0, 2)]).faces + {(0, 1, 2)} + + The allowed transformations are entered as allowable permutations + of the vertices for the polyhedron. Instance of Permutations + (as with faces) should refer to the supplied vertices by index. + These permutation are stored as a PermutationGroup. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy import init_printing + >>> from sympy.abc import w, x, y, z + >>> init_printing(pretty_print=False, perm_cyclic=False) + + Here we construct the Polyhedron object for a tetrahedron. + + >>> corners = [w, x, y, z] + >>> faces = [(0, 1, 2), (0, 2, 3), (0, 3, 1), (1, 2, 3)] + + Next, allowed transformations of the polyhedron must be given. This + is given as permutations of vertices. + + Although the vertices of a tetrahedron can be numbered in 24 (4!) + different ways, there are only 12 different orientations for a + physical tetrahedron. The following permutations, applied once or + twice, will generate all 12 of the orientations. (The identity + permutation, Permutation(range(4)), is not included since it does + not change the orientation of the vertices.) + + >>> pgroup = [Permutation([[0, 1, 2], [3]]), \ + Permutation([[0, 1, 3], [2]]), \ + Permutation([[0, 2, 3], [1]]), \ + Permutation([[1, 2, 3], [0]]), \ + Permutation([[0, 1], [2, 3]]), \ + Permutation([[0, 2], [1, 3]]), \ + Permutation([[0, 3], [1, 2]])] + + The Polyhedron is now constructed and demonstrated: + + >>> tetra = Polyhedron(corners, faces, pgroup) + >>> tetra.size + 4 + >>> tetra.edges + {(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)} + >>> tetra.corners + (w, x, y, z) + + It can be rotated with an arbitrary permutation of vertices, e.g. + the following permutation is not in the pgroup: + + >>> tetra.rotate(Permutation([0, 1, 3, 2])) + >>> tetra.corners + (w, x, z, y) + + An allowed permutation of the vertices can be constructed by + repeatedly applying permutations from the pgroup to the vertices. + Here is a demonstration that applying p and p**2 for every p in + pgroup generates all the orientations of a tetrahedron and no others: + + >>> all = ( (w, x, y, z), \ + (x, y, w, z), \ + (y, w, x, z), \ + (w, z, x, y), \ + (z, w, y, x), \ + (w, y, z, x), \ + (y, z, w, x), \ + (x, z, y, w), \ + (z, y, x, w), \ + (y, x, z, w), \ + (x, w, z, y), \ + (z, x, w, y) ) + + >>> got = [] + >>> for p in (pgroup + [p**2 for p in pgroup]): + ... h = Polyhedron(corners) + ... h.rotate(p) + ... got.append(h.corners) + ... + >>> set(got) == set(all) + True + + The make_perm method of a PermutationGroup will randomly pick + permutations, multiply them together, and return the permutation that + can be applied to the polyhedron to give the orientation produced + by those individual permutations. + + Here, 3 permutations are used: + + >>> tetra.pgroup.make_perm(3) # doctest: +SKIP + Permutation([0, 3, 1, 2]) + + To select the permutations that should be used, supply a list + of indices to the permutations in pgroup in the order they should + be applied: + + >>> use = [0, 0, 2] + >>> p002 = tetra.pgroup.make_perm(3, use) + >>> p002 + Permutation([1, 0, 3, 2]) + + + Apply them one at a time: + + >>> tetra.reset() + >>> for i in use: + ... tetra.rotate(pgroup[i]) + ... + >>> tetra.vertices + (x, w, z, y) + >>> sequentially = tetra.vertices + + Apply the composite permutation: + + >>> tetra.reset() + >>> tetra.rotate(p002) + >>> tetra.corners + (x, w, z, y) + >>> tetra.corners in all and tetra.corners == sequentially + True + + Notes + ===== + + Defining permutation groups + --------------------------- + + It is not necessary to enter any permutations, nor is necessary to + enter a complete set of transformations. In fact, for a polyhedron, + all configurations can be constructed from just two permutations. + For example, the orientations of a tetrahedron can be generated from + an axis passing through a vertex and face and another axis passing + through a different vertex or from an axis passing through the + midpoints of two edges opposite of each other. + + For simplicity of presentation, consider a square -- + not a cube -- with vertices 1, 2, 3, and 4: + + 1-----2 We could think of axes of rotation being: + | | 1) through the face + | | 2) from midpoint 1-2 to 3-4 or 1-3 to 2-4 + 3-----4 3) lines 1-4 or 2-3 + + + To determine how to write the permutations, imagine 4 cameras, + one at each corner, labeled A-D: + + A B A B + 1-----2 1-----3 vertex index: + | | | | 1 0 + | | | | 2 1 + 3-----4 2-----4 3 2 + C D C D 4 3 + + original after rotation + along 1-4 + + A diagonal and a face axis will be chosen for the "permutation group" + from which any orientation can be constructed. + + >>> pgroup = [] + + Imagine a clockwise rotation when viewing 1-4 from camera A. The new + orientation is (in camera-order): 1, 3, 2, 4 so the permutation is + given using the *indices* of the vertices as: + + >>> pgroup.append(Permutation((0, 2, 1, 3))) + + Now imagine rotating clockwise when looking down an axis entering the + center of the square as viewed. The new camera-order would be + 3, 1, 4, 2 so the permutation is (using indices): + + >>> pgroup.append(Permutation((2, 0, 3, 1))) + + The square can now be constructed: + ** use real-world labels for the vertices, entering them in + camera order + ** for the faces we use zero-based indices of the vertices + in *edge-order* as the face is traversed; neither the + direction nor the starting point matter -- the faces are + only used to define edges (if so desired). + + >>> square = Polyhedron((1, 2, 3, 4), [(0, 1, 3, 2)], pgroup) + + To rotate the square with a single permutation we can do: + + >>> square.rotate(square.pgroup[0]) + >>> square.corners + (1, 3, 2, 4) + + To use more than one permutation (or to use one permutation more + than once) it is more convenient to use the make_perm method: + + >>> p011 = square.pgroup.make_perm([0, 1, 1]) # diag flip + 2 rotations + >>> square.reset() # return to initial orientation + >>> square.rotate(p011) + >>> square.corners + (4, 2, 3, 1) + + Thinking outside the box + ------------------------ + + Although the Polyhedron object has a direct physical meaning, it + actually has broader application. In the most general sense it is + just a decorated PermutationGroup, allowing one to connect the + permutations to something physical. For example, a Rubik's cube is + not a proper polyhedron, but the Polyhedron class can be used to + represent it in a way that helps to visualize the Rubik's cube. + + >>> from sympy import flatten, unflatten, symbols + >>> from sympy.combinatorics import RubikGroup + >>> facelets = flatten([symbols(s+'1:5') for s in 'UFRBLD']) + >>> def show(): + ... pairs = unflatten(r2.corners, 2) + ... print(pairs[::2]) + ... print(pairs[1::2]) + ... + >>> r2 = Polyhedron(facelets, pgroup=RubikGroup(2)) + >>> show() + [(U1, U2), (F1, F2), (R1, R2), (B1, B2), (L1, L2), (D1, D2)] + [(U3, U4), (F3, F4), (R3, R4), (B3, B4), (L3, L4), (D3, D4)] + >>> r2.rotate(0) # cw rotation of F + >>> show() + [(U1, U2), (F3, F1), (U3, R2), (B1, B2), (L1, D1), (R3, R1)] + [(L4, L2), (F4, F2), (U4, R4), (B3, B4), (L3, D2), (D3, D4)] + + Predefined Polyhedra + ==================== + + For convenience, the vertices and faces are defined for the following + standard solids along with a permutation group for transformations. + When the polyhedron is oriented as indicated below, the vertices in + a given horizontal plane are numbered in ccw direction, starting from + the vertex that will give the lowest indices in a given face. (In the + net of the vertices, indices preceded by "-" indicate replication of + the lhs index in the net.) + + tetrahedron, tetrahedron_faces + ------------------------------ + + 4 vertices (vertex up) net: + + 0 0-0 + 1 2 3-1 + + 4 faces: + + (0, 1, 2) (0, 2, 3) (0, 3, 1) (1, 2, 3) + + cube, cube_faces + ---------------- + + 8 vertices (face up) net: + + 0 1 2 3-0 + 4 5 6 7-4 + + 6 faces: + + (0, 1, 2, 3) + (0, 1, 5, 4) (1, 2, 6, 5) (2, 3, 7, 6) (0, 3, 7, 4) + (4, 5, 6, 7) + + octahedron, octahedron_faces + ---------------------------- + + 6 vertices (vertex up) net: + + 0 0 0-0 + 1 2 3 4-1 + 5 5 5-5 + + 8 faces: + + (0, 1, 2) (0, 2, 3) (0, 3, 4) (0, 1, 4) + (1, 2, 5) (2, 3, 5) (3, 4, 5) (1, 4, 5) + + dodecahedron, dodecahedron_faces + -------------------------------- + + 20 vertices (vertex up) net: + + 0 1 2 3 4 -0 + 5 6 7 8 9 -5 + 14 10 11 12 13-14 + 15 16 17 18 19-15 + + 12 faces: + + (0, 1, 2, 3, 4) (0, 1, 6, 10, 5) (1, 2, 7, 11, 6) + (2, 3, 8, 12, 7) (3, 4, 9, 13, 8) (0, 4, 9, 14, 5) + (5, 10, 16, 15, 14) (6, 10, 16, 17, 11) (7, 11, 17, 18, 12) + (8, 12, 18, 19, 13) (9, 13, 19, 15, 14)(15, 16, 17, 18, 19) + + icosahedron, icosahedron_faces + ------------------------------ + + 12 vertices (face up) net: + + 0 0 0 0 -0 + 1 2 3 4 5 -1 + 6 7 8 9 10 -6 + 11 11 11 11 -11 + + 20 faces: + + (0, 1, 2) (0, 2, 3) (0, 3, 4) + (0, 4, 5) (0, 1, 5) (1, 2, 6) + (2, 3, 7) (3, 4, 8) (4, 5, 9) + (1, 5, 10) (2, 6, 7) (3, 7, 8) + (4, 8, 9) (5, 9, 10) (1, 6, 10) + (6, 7, 11) (7, 8, 11) (8, 9, 11) + (9, 10, 11) (6, 10, 11) + + >>> from sympy.combinatorics.polyhedron import cube + >>> cube.edges + {(0, 1), (0, 3), (0, 4), (1, 2), (1, 5), (2, 3), (2, 6), (3, 7), (4, 5), (4, 7), (5, 6), (6, 7)} + + If you want to use letters or other names for the corners you + can still use the pre-calculated faces: + + >>> corners = list('abcdefgh') + >>> Polyhedron(corners, cube.faces).corners + (a, b, c, d, e, f, g, h) + + References + ========== + + .. [1] www.ocf.berkeley.edu/~wwu/articles/platonicsolids.pdf + + """ + faces = [minlex(f, directed=False, key=default_sort_key) for f in faces] + corners, faces, pgroup = args = \ + [Tuple(*a) for a in (corners, faces, pgroup)] + obj = Basic.__new__(cls, *args) + obj._corners = tuple(corners) # in order given + obj._faces = FiniteSet(*faces) + if pgroup and pgroup[0].size != len(corners): + raise ValueError("Permutation size unequal to number of corners.") + # use the identity permutation if none are given + obj._pgroup = PermutationGroup( + pgroup or [Perm(range(len(corners)))] ) + return obj + + @property + def corners(self): + """ + Get the corners of the Polyhedron. + + The method ``vertices`` is an alias for ``corners``. + + Examples + ======== + + >>> from sympy.combinatorics import Polyhedron + >>> from sympy.abc import a, b, c, d + >>> p = Polyhedron(list('abcd')) + >>> p.corners == p.vertices == (a, b, c, d) + True + + See Also + ======== + + array_form, cyclic_form + """ + return self._corners + vertices = corners + + @property + def array_form(self): + """Return the indices of the corners. + + The indices are given relative to the original position of corners. + + Examples + ======== + + >>> from sympy.combinatorics.polyhedron import tetrahedron + >>> tetrahedron = tetrahedron.copy() + >>> tetrahedron.array_form + [0, 1, 2, 3] + + >>> tetrahedron.rotate(0) + >>> tetrahedron.array_form + [0, 2, 3, 1] + >>> tetrahedron.pgroup[0].array_form + [0, 2, 3, 1] + + See Also + ======== + + corners, cyclic_form + """ + corners = list(self.args[0]) + return [corners.index(c) for c in self.corners] + + @property + def cyclic_form(self): + """Return the indices of the corners in cyclic notation. + + The indices are given relative to the original position of corners. + + See Also + ======== + + corners, array_form + """ + return Perm._af_new(self.array_form).cyclic_form + + @property + def size(self): + """ + Get the number of corners of the Polyhedron. + """ + return len(self._corners) + + @property + def faces(self): + """ + Get the faces of the Polyhedron. + """ + return self._faces + + @property + def pgroup(self): + """ + Get the permutations of the Polyhedron. + """ + return self._pgroup + + @property + def edges(self): + """ + Given the faces of the polyhedra we can get the edges. + + Examples + ======== + + >>> from sympy.combinatorics import Polyhedron + >>> from sympy.abc import a, b, c + >>> corners = (a, b, c) + >>> faces = [(0, 1, 2)] + >>> Polyhedron(corners, faces).edges + {(0, 1), (0, 2), (1, 2)} + + """ + if self._edges is None: + output = set() + for face in self.faces: + for i in range(len(face)): + edge = tuple(sorted([face[i], face[i - 1]])) + output.add(edge) + self._edges = FiniteSet(*output) + return self._edges + + def rotate(self, perm): + """ + Apply a permutation to the polyhedron *in place*. The permutation + may be given as a Permutation instance or an integer indicating + which permutation from pgroup of the Polyhedron should be + applied. + + This is an operation that is analogous to rotation about + an axis by a fixed increment. + + Notes + ===== + + When a Permutation is applied, no check is done to see if that + is a valid permutation for the Polyhedron. For example, a cube + could be given a permutation which effectively swaps only 2 + vertices. A valid permutation (that rotates the object in a + physical way) will be obtained if one only uses + permutations from the ``pgroup`` of the Polyhedron. On the other + hand, allowing arbitrary rotations (applications of permutations) + gives a way to follow named elements rather than indices since + Polyhedron allows vertices to be named while Permutation works + only with indices. + + Examples + ======== + + >>> from sympy.combinatorics import Polyhedron, Permutation + >>> from sympy.combinatorics.polyhedron import cube + >>> cube = cube.copy() + >>> cube.corners + (0, 1, 2, 3, 4, 5, 6, 7) + >>> cube.rotate(0) + >>> cube.corners + (1, 2, 3, 0, 5, 6, 7, 4) + + A non-physical "rotation" that is not prohibited by this method: + + >>> cube.reset() + >>> cube.rotate(Permutation([[1, 2]], size=8)) + >>> cube.corners + (0, 2, 1, 3, 4, 5, 6, 7) + + Polyhedron can be used to follow elements of set that are + identified by letters instead of integers: + + >>> shadow = h5 = Polyhedron(list('abcde')) + >>> p = Permutation([3, 0, 1, 2, 4]) + >>> h5.rotate(p) + >>> h5.corners + (d, a, b, c, e) + >>> _ == shadow.corners + True + >>> copy = h5.copy() + >>> h5.rotate(p) + >>> h5.corners == copy.corners + False + """ + if not isinstance(perm, Perm): + perm = self.pgroup[perm] + # and we know it's valid + else: + if perm.size != self.size: + raise ValueError('Polyhedron and Permutation sizes differ.') + a = perm.array_form + corners = [self.corners[a[i]] for i in range(len(self.corners))] + self._corners = tuple(corners) + + def reset(self): + """Return corners to their original positions. + + Examples + ======== + + >>> from sympy.combinatorics.polyhedron import tetrahedron as T + >>> T = T.copy() + >>> T.corners + (0, 1, 2, 3) + >>> T.rotate(0) + >>> T.corners + (0, 2, 3, 1) + >>> T.reset() + >>> T.corners + (0, 1, 2, 3) + """ + self._corners = self.args[0] + + +def _pgroup_calcs(): + """Return the permutation groups for each of the polyhedra and the face + definitions: tetrahedron, cube, octahedron, dodecahedron, icosahedron, + tetrahedron_faces, cube_faces, octahedron_faces, dodecahedron_faces, + icosahedron_faces + + Explanation + =========== + + (This author did not find and did not know of a better way to do it though + there likely is such a way.) + + Although only 2 permutations are needed for a polyhedron in order to + generate all the possible orientations, a group of permutations is + provided instead. A set of permutations is called a "group" if:: + + a*b = c (for any pair of permutations in the group, a and b, their + product, c, is in the group) + + a*(b*c) = (a*b)*c (for any 3 permutations in the group associativity holds) + + there is an identity permutation, I, such that I*a = a*I for all elements + in the group + + a*b = I (the inverse of each permutation is also in the group) + + None of the polyhedron groups defined follow these definitions of a group. + Instead, they are selected to contain those permutations whose powers + alone will construct all orientations of the polyhedron, i.e. for + permutations ``a``, ``b``, etc... in the group, ``a, a**2, ..., a**o_a``, + ``b, b**2, ..., b**o_b``, etc... (where ``o_i`` is the order of + permutation ``i``) generate all permutations of the polyhedron instead of + mixed products like ``a*b``, ``a*b**2``, etc.... + + Note that for a polyhedron with n vertices, the valid permutations of the + vertices exclude those that do not maintain its faces. e.g. the + permutation BCDE of a square's four corners, ABCD, is a valid + permutation while CBDE is not (because this would twist the square). + + Examples + ======== + + The is_group checks for: closure, the presence of the Identity permutation, + and the presence of the inverse for each of the elements in the group. This + confirms that none of the polyhedra are true groups: + + >>> from sympy.combinatorics.polyhedron import ( + ... tetrahedron, cube, octahedron, dodecahedron, icosahedron) + ... + >>> polyhedra = (tetrahedron, cube, octahedron, dodecahedron, icosahedron) + >>> [h.pgroup.is_group for h in polyhedra] + ... + [True, True, True, True, True] + + Although tests in polyhedron's test suite check that powers of the + permutations in the groups generate all permutations of the vertices + of the polyhedron, here we also demonstrate the powers of the given + permutations create a complete group for the tetrahedron: + + >>> from sympy.combinatorics import Permutation, PermutationGroup + >>> for h in polyhedra[:1]: + ... G = h.pgroup + ... perms = set() + ... for g in G: + ... for e in range(g.order()): + ... p = tuple((g**e).array_form) + ... perms.add(p) + ... + ... perms = [Permutation(p) for p in perms] + ... assert PermutationGroup(perms).is_group + + In addition to doing the above, the tests in the suite confirm that the + faces are all present after the application of each permutation. + + References + ========== + + .. [1] https://dogschool.tripod.com/trianglegroup.html + + """ + def _pgroup_of_double(polyh, ordered_faces, pgroup): + n = len(ordered_faces[0]) + # the vertices of the double which sits inside a give polyhedron + # can be found by tracking the faces of the outer polyhedron. + # A map between face and the vertex of the double is made so that + # after rotation the position of the vertices can be located + fmap = dict(zip(ordered_faces, + range(len(ordered_faces)))) + flat_faces = flatten(ordered_faces) + new_pgroup = [] + for p in pgroup: + h = polyh.copy() + h.rotate(p) + c = h.corners + # reorder corners in the order they should appear when + # enumerating the faces + reorder = unflatten([c[j] for j in flat_faces], n) + # make them canonical + reorder = [tuple(map(as_int, + minlex(f, directed=False))) + for f in reorder] + # map face to vertex: the resulting list of vertices are the + # permutation that we seek for the double + new_pgroup.append(Perm([fmap[f] for f in reorder])) + return new_pgroup + + tetrahedron_faces = [ + (0, 1, 2), (0, 2, 3), (0, 3, 1), # upper 3 + (1, 2, 3), # bottom + ] + + # cw from top + # + _t_pgroup = [ + Perm([[1, 2, 3], [0]]), # cw from top + Perm([[0, 1, 2], [3]]), # cw from front face + Perm([[0, 3, 2], [1]]), # cw from back right face + Perm([[0, 3, 1], [2]]), # cw from back left face + Perm([[0, 1], [2, 3]]), # through front left edge + Perm([[0, 2], [1, 3]]), # through front right edge + Perm([[0, 3], [1, 2]]), # through back edge + ] + + tetrahedron = Polyhedron( + range(4), + tetrahedron_faces, + _t_pgroup) + + cube_faces = [ + (0, 1, 2, 3), # upper + (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (0, 3, 7, 4), # middle 4 + (4, 5, 6, 7), # lower + ] + + # U, D, F, B, L, R = up, down, front, back, left, right + _c_pgroup = [Perm(p) for p in + [ + [1, 2, 3, 0, 5, 6, 7, 4], # cw from top, U + [4, 0, 3, 7, 5, 1, 2, 6], # cw from F face + [4, 5, 1, 0, 7, 6, 2, 3], # cw from R face + + [1, 0, 4, 5, 2, 3, 7, 6], # cw through UF edge + [6, 2, 1, 5, 7, 3, 0, 4], # cw through UR edge + [6, 7, 3, 2, 5, 4, 0, 1], # cw through UB edge + [3, 7, 4, 0, 2, 6, 5, 1], # cw through UL edge + [4, 7, 6, 5, 0, 3, 2, 1], # cw through FL edge + [6, 5, 4, 7, 2, 1, 0, 3], # cw through FR edge + + [0, 3, 7, 4, 1, 2, 6, 5], # cw through UFL vertex + [5, 1, 0, 4, 6, 2, 3, 7], # cw through UFR vertex + [5, 6, 2, 1, 4, 7, 3, 0], # cw through UBR vertex + [7, 4, 0, 3, 6, 5, 1, 2], # cw through UBL + ]] + + cube = Polyhedron( + range(8), + cube_faces, + _c_pgroup) + + octahedron_faces = [ + (0, 1, 2), (0, 2, 3), (0, 3, 4), (0, 1, 4), # top 4 + (1, 2, 5), (2, 3, 5), (3, 4, 5), (1, 4, 5), # bottom 4 + ] + + octahedron = Polyhedron( + range(6), + octahedron_faces, + _pgroup_of_double(cube, cube_faces, _c_pgroup)) + + dodecahedron_faces = [ + (0, 1, 2, 3, 4), # top + (0, 1, 6, 10, 5), (1, 2, 7, 11, 6), (2, 3, 8, 12, 7), # upper 5 + (3, 4, 9, 13, 8), (0, 4, 9, 14, 5), + (5, 10, 16, 15, 14), (6, 10, 16, 17, 11), (7, 11, 17, 18, + 12), # lower 5 + (8, 12, 18, 19, 13), (9, 13, 19, 15, 14), + (15, 16, 17, 18, 19) # bottom + ] + + def _string_to_perm(s): + rv = [Perm(range(20))] + p = None + for si in s: + if si not in '01': + count = int(si) - 1 + else: + count = 1 + if si == '0': + p = _f0 + elif si == '1': + p = _f1 + rv.extend([p]*count) + return Perm.rmul(*rv) + + # top face cw + _f0 = Perm([ + 1, 2, 3, 4, 0, 6, 7, 8, 9, 5, 11, + 12, 13, 14, 10, 16, 17, 18, 19, 15]) + # front face cw + _f1 = Perm([ + 5, 0, 4, 9, 14, 10, 1, 3, 13, 15, + 6, 2, 8, 19, 16, 17, 11, 7, 12, 18]) + # the strings below, like 0104 are shorthand for F0*F1*F0**4 and are + # the remaining 4 face rotations, 15 edge permutations, and the + # 10 vertex rotations. + _dodeca_pgroup = [_f0, _f1] + [_string_to_perm(s) for s in ''' + 0104 140 014 0410 + 010 1403 03104 04103 102 + 120 1304 01303 021302 03130 + 0412041 041204103 04120410 041204104 041204102 + 10 01 1402 0140 04102 0412 1204 1302 0130 03120'''.strip().split()] + + dodecahedron = Polyhedron( + range(20), + dodecahedron_faces, + _dodeca_pgroup) + + icosahedron_faces = [ + (0, 1, 2), (0, 2, 3), (0, 3, 4), (0, 4, 5), (0, 1, 5), + (1, 6, 7), (1, 2, 7), (2, 7, 8), (2, 3, 8), (3, 8, 9), + (3, 4, 9), (4, 9, 10), (4, 5, 10), (5, 6, 10), (1, 5, 6), + (6, 7, 11), (7, 8, 11), (8, 9, 11), (9, 10, 11), (6, 10, 11)] + + icosahedron = Polyhedron( + range(12), + icosahedron_faces, + _pgroup_of_double( + dodecahedron, dodecahedron_faces, _dodeca_pgroup)) + + return (tetrahedron, cube, octahedron, dodecahedron, icosahedron, + tetrahedron_faces, cube_faces, octahedron_faces, + dodecahedron_faces, icosahedron_faces) + +# ----------------------------------------------------------------------- +# Standard Polyhedron groups +# +# These are generated using _pgroup_calcs() above. However to save +# import time we encode them explicitly here. +# ----------------------------------------------------------------------- + +tetrahedron = Polyhedron( + Tuple(0, 1, 2, 3), + Tuple( + Tuple(0, 1, 2), + Tuple(0, 2, 3), + Tuple(0, 1, 3), + Tuple(1, 2, 3)), + Tuple( + Perm(1, 2, 3), + Perm(3)(0, 1, 2), + Perm(0, 3, 2), + Perm(0, 3, 1), + Perm(0, 1)(2, 3), + Perm(0, 2)(1, 3), + Perm(0, 3)(1, 2) + )) + +cube = Polyhedron( + Tuple(0, 1, 2, 3, 4, 5, 6, 7), + Tuple( + Tuple(0, 1, 2, 3), + Tuple(0, 1, 5, 4), + Tuple(1, 2, 6, 5), + Tuple(2, 3, 7, 6), + Tuple(0, 3, 7, 4), + Tuple(4, 5, 6, 7)), + Tuple( + Perm(0, 1, 2, 3)(4, 5, 6, 7), + Perm(0, 4, 5, 1)(2, 3, 7, 6), + Perm(0, 4, 7, 3)(1, 5, 6, 2), + Perm(0, 1)(2, 4)(3, 5)(6, 7), + Perm(0, 6)(1, 2)(3, 5)(4, 7), + Perm(0, 6)(1, 7)(2, 3)(4, 5), + Perm(0, 3)(1, 7)(2, 4)(5, 6), + Perm(0, 4)(1, 7)(2, 6)(3, 5), + Perm(0, 6)(1, 5)(2, 4)(3, 7), + Perm(1, 3, 4)(2, 7, 5), + Perm(7)(0, 5, 2)(3, 4, 6), + Perm(0, 5, 7)(1, 6, 3), + Perm(0, 7, 2)(1, 4, 6))) + +octahedron = Polyhedron( + Tuple(0, 1, 2, 3, 4, 5), + Tuple( + Tuple(0, 1, 2), + Tuple(0, 2, 3), + Tuple(0, 3, 4), + Tuple(0, 1, 4), + Tuple(1, 2, 5), + Tuple(2, 3, 5), + Tuple(3, 4, 5), + Tuple(1, 4, 5)), + Tuple( + Perm(5)(1, 2, 3, 4), + Perm(0, 4, 5, 2), + Perm(0, 1, 5, 3), + Perm(0, 1)(2, 4)(3, 5), + Perm(0, 2)(1, 3)(4, 5), + Perm(0, 3)(1, 5)(2, 4), + Perm(0, 4)(1, 3)(2, 5), + Perm(0, 5)(1, 4)(2, 3), + Perm(0, 5)(1, 2)(3, 4), + Perm(0, 4, 1)(2, 3, 5), + Perm(0, 1, 2)(3, 4, 5), + Perm(0, 2, 3)(1, 5, 4), + Perm(0, 4, 3)(1, 5, 2))) + +dodecahedron = Polyhedron( + Tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), + Tuple( + Tuple(0, 1, 2, 3, 4), + Tuple(0, 1, 6, 10, 5), + Tuple(1, 2, 7, 11, 6), + Tuple(2, 3, 8, 12, 7), + Tuple(3, 4, 9, 13, 8), + Tuple(0, 4, 9, 14, 5), + Tuple(5, 10, 16, 15, 14), + Tuple(6, 10, 16, 17, 11), + Tuple(7, 11, 17, 18, 12), + Tuple(8, 12, 18, 19, 13), + Tuple(9, 13, 19, 15, 14), + Tuple(15, 16, 17, 18, 19)), + Tuple( + Perm(0, 1, 2, 3, 4)(5, 6, 7, 8, 9)(10, 11, 12, 13, 14)(15, 16, 17, 18, 19), + Perm(0, 5, 10, 6, 1)(2, 4, 14, 16, 11)(3, 9, 15, 17, 7)(8, 13, 19, 18, 12), + Perm(0, 10, 17, 12, 3)(1, 6, 11, 7, 2)(4, 5, 16, 18, 8)(9, 14, 15, 19, 13), + Perm(0, 6, 17, 19, 9)(1, 11, 18, 13, 4)(2, 7, 12, 8, 3)(5, 10, 16, 15, 14), + Perm(0, 2, 12, 19, 14)(1, 7, 18, 15, 5)(3, 8, 13, 9, 4)(6, 11, 17, 16, 10), + Perm(0, 4, 9, 14, 5)(1, 3, 13, 15, 10)(2, 8, 19, 16, 6)(7, 12, 18, 17, 11), + Perm(0, 1)(2, 5)(3, 10)(4, 6)(7, 14)(8, 16)(9, 11)(12, 15)(13, 17)(18, 19), + Perm(0, 7)(1, 2)(3, 6)(4, 11)(5, 12)(8, 10)(9, 17)(13, 16)(14, 18)(15, 19), + Perm(0, 12)(1, 8)(2, 3)(4, 7)(5, 18)(6, 13)(9, 11)(10, 19)(14, 17)(15, 16), + Perm(0, 8)(1, 13)(2, 9)(3, 4)(5, 12)(6, 19)(7, 14)(10, 18)(11, 15)(16, 17), + Perm(0, 4)(1, 9)(2, 14)(3, 5)(6, 13)(7, 15)(8, 10)(11, 19)(12, 16)(17, 18), + Perm(0, 5)(1, 14)(2, 15)(3, 16)(4, 10)(6, 9)(7, 19)(8, 17)(11, 13)(12, 18), + Perm(0, 11)(1, 6)(2, 10)(3, 16)(4, 17)(5, 7)(8, 15)(9, 18)(12, 14)(13, 19), + Perm(0, 18)(1, 12)(2, 7)(3, 11)(4, 17)(5, 19)(6, 8)(9, 16)(10, 13)(14, 15), + Perm(0, 18)(1, 19)(2, 13)(3, 8)(4, 12)(5, 17)(6, 15)(7, 9)(10, 16)(11, 14), + Perm(0, 13)(1, 19)(2, 15)(3, 14)(4, 9)(5, 8)(6, 18)(7, 16)(10, 12)(11, 17), + Perm(0, 16)(1, 15)(2, 19)(3, 18)(4, 17)(5, 10)(6, 14)(7, 13)(8, 12)(9, 11), + Perm(0, 18)(1, 17)(2, 16)(3, 15)(4, 19)(5, 12)(6, 11)(7, 10)(8, 14)(9, 13), + Perm(0, 15)(1, 19)(2, 18)(3, 17)(4, 16)(5, 14)(6, 13)(7, 12)(8, 11)(9, 10), + Perm(0, 17)(1, 16)(2, 15)(3, 19)(4, 18)(5, 11)(6, 10)(7, 14)(8, 13)(9, 12), + Perm(0, 19)(1, 18)(2, 17)(3, 16)(4, 15)(5, 13)(6, 12)(7, 11)(8, 10)(9, 14), + Perm(1, 4, 5)(2, 9, 10)(3, 14, 6)(7, 13, 16)(8, 15, 11)(12, 19, 17), + Perm(19)(0, 6, 2)(3, 5, 11)(4, 10, 7)(8, 14, 17)(9, 16, 12)(13, 15, 18), + Perm(0, 11, 8)(1, 7, 3)(4, 6, 12)(5, 17, 13)(9, 10, 18)(14, 16, 19), + Perm(0, 7, 13)(1, 12, 9)(2, 8, 4)(5, 11, 19)(6, 18, 14)(10, 17, 15), + Perm(0, 3, 9)(1, 8, 14)(2, 13, 5)(6, 12, 15)(7, 19, 10)(11, 18, 16), + Perm(0, 14, 10)(1, 9, 16)(2, 13, 17)(3, 19, 11)(4, 15, 6)(7, 8, 18), + Perm(0, 16, 7)(1, 10, 11)(2, 5, 17)(3, 14, 18)(4, 15, 12)(8, 9, 19), + Perm(0, 16, 13)(1, 17, 8)(2, 11, 12)(3, 6, 18)(4, 10, 19)(5, 15, 9), + Perm(0, 11, 15)(1, 17, 14)(2, 18, 9)(3, 12, 13)(4, 7, 19)(5, 6, 16), + Perm(0, 8, 15)(1, 12, 16)(2, 18, 10)(3, 19, 5)(4, 13, 14)(6, 7, 17))) + +icosahedron = Polyhedron( + Tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), + Tuple( + Tuple(0, 1, 2), + Tuple(0, 2, 3), + Tuple(0, 3, 4), + Tuple(0, 4, 5), + Tuple(0, 1, 5), + Tuple(1, 6, 7), + Tuple(1, 2, 7), + Tuple(2, 7, 8), + Tuple(2, 3, 8), + Tuple(3, 8, 9), + Tuple(3, 4, 9), + Tuple(4, 9, 10), + Tuple(4, 5, 10), + Tuple(5, 6, 10), + Tuple(1, 5, 6), + Tuple(6, 7, 11), + Tuple(7, 8, 11), + Tuple(8, 9, 11), + Tuple(9, 10, 11), + Tuple(6, 10, 11)), + Tuple( + Perm(11)(1, 2, 3, 4, 5)(6, 7, 8, 9, 10), + Perm(0, 5, 6, 7, 2)(3, 4, 10, 11, 8), + Perm(0, 1, 7, 8, 3)(4, 5, 6, 11, 9), + Perm(0, 2, 8, 9, 4)(1, 7, 11, 10, 5), + Perm(0, 3, 9, 10, 5)(1, 2, 8, 11, 6), + Perm(0, 4, 10, 6, 1)(2, 3, 9, 11, 7), + Perm(0, 1)(2, 5)(3, 6)(4, 7)(8, 10)(9, 11), + Perm(0, 2)(1, 3)(4, 7)(5, 8)(6, 9)(10, 11), + Perm(0, 3)(1, 9)(2, 4)(5, 8)(6, 11)(7, 10), + Perm(0, 4)(1, 9)(2, 10)(3, 5)(6, 8)(7, 11), + Perm(0, 5)(1, 4)(2, 10)(3, 6)(7, 9)(8, 11), + Perm(0, 6)(1, 5)(2, 10)(3, 11)(4, 7)(8, 9), + Perm(0, 7)(1, 2)(3, 6)(4, 11)(5, 8)(9, 10), + Perm(0, 8)(1, 9)(2, 3)(4, 7)(5, 11)(6, 10), + Perm(0, 9)(1, 11)(2, 10)(3, 4)(5, 8)(6, 7), + Perm(0, 10)(1, 9)(2, 11)(3, 6)(4, 5)(7, 8), + Perm(0, 11)(1, 6)(2, 10)(3, 9)(4, 8)(5, 7), + Perm(0, 11)(1, 8)(2, 7)(3, 6)(4, 10)(5, 9), + Perm(0, 11)(1, 10)(2, 9)(3, 8)(4, 7)(5, 6), + Perm(0, 11)(1, 7)(2, 6)(3, 10)(4, 9)(5, 8), + Perm(0, 11)(1, 9)(2, 8)(3, 7)(4, 6)(5, 10), + Perm(0, 5, 1)(2, 4, 6)(3, 10, 7)(8, 9, 11), + Perm(0, 1, 2)(3, 5, 7)(4, 6, 8)(9, 10, 11), + Perm(0, 2, 3)(1, 8, 4)(5, 7, 9)(6, 11, 10), + Perm(0, 3, 4)(1, 8, 10)(2, 9, 5)(6, 7, 11), + Perm(0, 4, 5)(1, 3, 10)(2, 9, 6)(7, 8, 11), + Perm(0, 10, 7)(1, 5, 6)(2, 4, 11)(3, 9, 8), + Perm(0, 6, 8)(1, 7, 2)(3, 5, 11)(4, 10, 9), + Perm(0, 7, 9)(1, 11, 4)(2, 8, 3)(5, 6, 10), + Perm(0, 8, 10)(1, 7, 6)(2, 11, 5)(3, 9, 4), + Perm(0, 9, 6)(1, 3, 11)(2, 8, 7)(4, 10, 5))) + +tetrahedron_faces = [tuple(arg) for arg in tetrahedron.faces] + +cube_faces = [tuple(arg) for arg in cube.faces] + +octahedron_faces = [tuple(arg) for arg in octahedron.faces] + +dodecahedron_faces = [tuple(arg) for arg in dodecahedron.faces] + +icosahedron_faces = [tuple(arg) for arg in icosahedron.faces] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/prufer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/prufer.py new file mode 100644 index 0000000000000000000000000000000000000000..e389df87cddc0152b2376e18b9f3df2e94d3d2fb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/prufer.py @@ -0,0 +1,435 @@ +from sympy.core import Basic +from sympy.core.containers import Tuple +from sympy.tensor.array import Array +from sympy.core.sympify import _sympify +from sympy.utilities.iterables import flatten, iterable +from sympy.utilities.misc import as_int + +from collections import defaultdict + + +class Prufer(Basic): + """ + The Prufer correspondence is an algorithm that describes the + bijection between labeled trees and the Prufer code. A Prufer + code of a labeled tree is unique up to isomorphism and has + a length of n - 2. + + Prufer sequences were first used by Heinz Prufer to give a + proof of Cayley's formula. + + References + ========== + + .. [1] https://mathworld.wolfram.com/LabeledTree.html + + """ + _prufer_repr = None + _tree_repr = None + _nodes = None + _rank = None + + @property + def prufer_repr(self): + """Returns Prufer sequence for the Prufer object. + + This sequence is found by removing the highest numbered vertex, + recording the node it was attached to, and continuing until only + two vertices remain. The Prufer sequence is the list of recorded nodes. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).prufer_repr + [3, 3, 3, 4] + >>> Prufer([1, 0, 0]).prufer_repr + [1, 0, 0] + + See Also + ======== + + to_prufer + + """ + if self._prufer_repr is None: + self._prufer_repr = self.to_prufer(self._tree_repr[:], self.nodes) + return self._prufer_repr + + @property + def tree_repr(self): + """Returns the tree representation of the Prufer object. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).tree_repr + [[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]] + >>> Prufer([1, 0, 0]).tree_repr + [[1, 2], [0, 1], [0, 3], [0, 4]] + + See Also + ======== + + to_tree + + """ + if self._tree_repr is None: + self._tree_repr = self.to_tree(self._prufer_repr[:]) + return self._tree_repr + + @property + def nodes(self): + """Returns the number of nodes in the tree. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).nodes + 6 + >>> Prufer([1, 0, 0]).nodes + 5 + + """ + return self._nodes + + @property + def rank(self): + """Returns the rank of the Prufer sequence. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> p = Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]) + >>> p.rank + 778 + >>> p.next(1).rank + 779 + >>> p.prev().rank + 777 + + See Also + ======== + + prufer_rank, next, prev, size + + """ + if self._rank is None: + self._rank = self.prufer_rank() + return self._rank + + @property + def size(self): + """Return the number of possible trees of this Prufer object. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> Prufer([0]*4).size == Prufer([6]*4).size == 1296 + True + + See Also + ======== + + prufer_rank, rank, next, prev + + """ + return self.prev(self.rank).prev().rank + 1 + + @staticmethod + def to_prufer(tree, n): + """Return the Prufer sequence for a tree given as a list of edges where + ``n`` is the number of nodes in the tree. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) + >>> a.prufer_repr + [0, 0] + >>> Prufer.to_prufer([[0, 1], [0, 2], [0, 3]], 4) + [0, 0] + + See Also + ======== + prufer_repr: returns Prufer sequence of a Prufer object. + + """ + d = defaultdict(int) + L = [] + for edge in tree: + # Increment the value of the corresponding + # node in the degree list as we encounter an + # edge involving it. + d[edge[0]] += 1 + d[edge[1]] += 1 + for i in range(n - 2): + # find the smallest leaf + for x in range(n): + if d[x] == 1: + break + # find the node it was connected to + y = None + for edge in tree: + if x == edge[0]: + y = edge[1] + elif x == edge[1]: + y = edge[0] + if y is not None: + break + # record and update + L.append(y) + for j in (x, y): + d[j] -= 1 + if not d[j]: + d.pop(j) + tree.remove(edge) + return L + + @staticmethod + def to_tree(prufer): + """Return the tree (as a list of edges) of the given Prufer sequence. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> a = Prufer([0, 2], 4) + >>> a.tree_repr + [[0, 1], [0, 2], [2, 3]] + >>> Prufer.to_tree([0, 2]) + [[0, 1], [0, 2], [2, 3]] + + References + ========== + + .. [1] https://hamberg.no/erlend/posts/2010-11-06-prufer-sequence-compact-tree-representation.html + + See Also + ======== + tree_repr: returns tree representation of a Prufer object. + + """ + tree = [] + last = [] + n = len(prufer) + 2 + d = defaultdict(lambda: 1) + for p in prufer: + d[p] += 1 + for i in prufer: + for j in range(n): + # find the smallest leaf (degree = 1) + if d[j] == 1: + break + # (i, j) is the new edge that we append to the tree + # and remove from the degree dictionary + d[i] -= 1 + d[j] -= 1 + tree.append(sorted([i, j])) + last = [i for i in range(n) if d[i] == 1] or [0, 1] + tree.append(last) + + return tree + + @staticmethod + def edges(*runs): + """Return a list of edges and the number of nodes from the given runs + that connect nodes in an integer-labelled tree. + + All node numbers will be shifted so that the minimum node is 0. It is + not a problem if edges are repeated in the runs; only unique edges are + returned. There is no assumption made about what the range of the node + labels should be, but all nodes from the smallest through the largest + must be present. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> Prufer.edges([1, 2, 3], [2, 4, 5]) # a T + ([[0, 1], [1, 2], [1, 3], [3, 4]], 5) + + Duplicate edges are removed: + + >>> Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) # a K + ([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7) + + """ + e = set() + nmin = runs[0][0] + for r in runs: + for i in range(len(r) - 1): + a, b = r[i: i + 2] + if b < a: + a, b = b, a + e.add((a, b)) + rv = [] + got = set() + nmin = nmax = None + for ei in e: + got.update(ei) + nmin = min(ei[0], nmin) if nmin is not None else ei[0] + nmax = max(ei[1], nmax) if nmax is not None else ei[1] + rv.append(list(ei)) + missing = set(range(nmin, nmax + 1)) - got + if missing: + missing = [i + nmin for i in missing] + if len(missing) == 1: + msg = 'Node %s is missing.' % missing.pop() + else: + msg = 'Nodes %s are missing.' % sorted(missing) + raise ValueError(msg) + if nmin != 0: + for i, ei in enumerate(rv): + rv[i] = [n - nmin for n in ei] + nmax -= nmin + return sorted(rv), nmax + 1 + + def prufer_rank(self): + """Computes the rank of a Prufer sequence. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) + >>> a.prufer_rank() + 0 + + See Also + ======== + + rank, next, prev, size + + """ + r = 0 + p = 1 + for i in range(self.nodes - 3, -1, -1): + r += p*self.prufer_repr[i] + p *= self.nodes + return r + + @classmethod + def unrank(self, rank, n): + """Finds the unranked Prufer sequence. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> Prufer.unrank(0, 4) + Prufer([0, 0]) + + """ + n, rank = as_int(n), as_int(rank) + L = defaultdict(int) + for i in range(n - 3, -1, -1): + L[i] = rank % n + rank = (rank - L[i])//n + return Prufer([L[i] for i in range(len(L))]) + + def __new__(cls, *args, **kw_args): + """The constructor for the Prufer object. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + + A Prufer object can be constructed from a list of edges: + + >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) + >>> a.prufer_repr + [0, 0] + + If the number of nodes is given, no checking of the nodes will + be performed; it will be assumed that nodes 0 through n - 1 are + present: + + >>> Prufer([[0, 1], [0, 2], [0, 3]], 4) + Prufer([[0, 1], [0, 2], [0, 3]], 4) + + A Prufer object can be constructed from a Prufer sequence: + + >>> b = Prufer([1, 3]) + >>> b.tree_repr + [[0, 1], [1, 3], [2, 3]] + + """ + arg0 = Array(args[0]) if args[0] else Tuple() + args = (arg0,) + tuple(_sympify(arg) for arg in args[1:]) + ret_obj = Basic.__new__(cls, *args, **kw_args) + args = [list(args[0])] + if args[0] and iterable(args[0][0]): + if not args[0][0]: + raise ValueError( + 'Prufer expects at least one edge in the tree.') + if len(args) > 1: + nnodes = args[1] + else: + nodes = set(flatten(args[0])) + nnodes = max(nodes) + 1 + if nnodes != len(nodes): + missing = set(range(nnodes)) - nodes + if len(missing) == 1: + msg = 'Node %s is missing.' % missing.pop() + else: + msg = 'Nodes %s are missing.' % sorted(missing) + raise ValueError(msg) + ret_obj._tree_repr = [list(i) for i in args[0]] + ret_obj._nodes = nnodes + else: + ret_obj._prufer_repr = args[0] + ret_obj._nodes = len(ret_obj._prufer_repr) + 2 + return ret_obj + + def next(self, delta=1): + """Generates the Prufer sequence that is delta beyond the current one. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) + >>> b = a.next(1) # == a.next() + >>> b.tree_repr + [[0, 2], [0, 1], [1, 3]] + >>> b.rank + 1 + + See Also + ======== + + prufer_rank, rank, prev, size + + """ + return Prufer.unrank(self.rank + delta, self.nodes) + + def prev(self, delta=1): + """Generates the Prufer sequence that is -delta before the current one. + + Examples + ======== + + >>> from sympy.combinatorics.prufer import Prufer + >>> a = Prufer([[0, 1], [1, 2], [2, 3], [1, 4]]) + >>> a.rank + 36 + >>> b = a.prev() + >>> b + Prufer([1, 2, 0]) + >>> b.rank + 35 + + See Also + ======== + + prufer_rank, rank, next, size + + """ + return Prufer.unrank(self.rank -delta, self.nodes) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e8dfe4c831db6490c987c85a57d0d1a939de61 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem.py @@ -0,0 +1,453 @@ +from collections import deque +from sympy.combinatorics.rewritingsystem_fsm import StateMachine + +class RewritingSystem: + ''' + A class implementing rewriting systems for `FpGroup`s. + + References + ========== + .. [1] Epstein, D., Holt, D. and Rees, S. (1991). + The use of Knuth-Bendix methods to solve the word problem in automatic groups. + Journal of Symbolic Computation, 12(4-5), pp.397-414. + + .. [2] GAP's Manual on its KBMAG package + https://www.gap-system.org/Manuals/pkg/kbmag-1.5.3/doc/manual.pdf + + ''' + def __init__(self, group): + self.group = group + self.alphabet = group.generators + self._is_confluent = None + + # these values are taken from [2] + self.maxeqns = 32767 # max rules + self.tidyint = 100 # rules before tidying + + # _max_exceeded is True if maxeqns is exceeded + # at any point + self._max_exceeded = False + + # Reduction automaton + self.reduction_automaton = None + self._new_rules = {} + + # dictionary of reductions + self.rules = {} + self.rules_cache = deque([], 50) + self._init_rules() + + + # All the transition symbols in the automaton + generators = list(self.alphabet) + generators += [gen**-1 for gen in generators] + # Create a finite state machine as an instance of the StateMachine object + self.reduction_automaton = StateMachine('Reduction automaton for '+ repr(self.group), generators) + self.construct_automaton() + + def set_max(self, n): + ''' + Set the maximum number of rules that can be defined + + ''' + if n > self.maxeqns: + self._max_exceeded = False + self.maxeqns = n + return + + @property + def is_confluent(self): + ''' + Return `True` if the system is confluent + + ''' + if self._is_confluent is None: + self._is_confluent = self._check_confluence() + return self._is_confluent + + def _init_rules(self): + identity = self.group.free_group.identity + for r in self.group.relators: + self.add_rule(r, identity) + self._remove_redundancies() + return + + def _add_rule(self, r1, r2): + ''' + Add the rule r1 -> r2 with no checking or further + deductions + + ''' + if len(self.rules) + 1 > self.maxeqns: + self._is_confluent = self._check_confluence() + self._max_exceeded = True + raise RuntimeError("Too many rules were defined.") + self.rules[r1] = r2 + # Add the newly added rule to the `new_rules` dictionary. + if self.reduction_automaton: + self._new_rules[r1] = r2 + + def add_rule(self, w1, w2, check=False): + new_keys = set() + + if w1 == w2: + return new_keys + + if w1 < w2: + w1, w2 = w2, w1 + + if (w1, w2) in self.rules_cache: + return new_keys + self.rules_cache.append((w1, w2)) + + s1, s2 = w1, w2 + + # The following is the equivalent of checking + # s1 for overlaps with the implicit reductions + # {g*g**-1 -> } and {g**-1*g -> } + # for any generator g without installing the + # redundant rules that would result from processing + # the overlaps. See [1], Section 3 for details. + + if len(s1) - len(s2) < 3: + if s1 not in self.rules: + new_keys.add(s1) + if not check: + self._add_rule(s1, s2) + if s2**-1 > s1**-1 and s2**-1 not in self.rules: + new_keys.add(s2**-1) + if not check: + self._add_rule(s2**-1, s1**-1) + + # overlaps on the right + while len(s1) - len(s2) > -1: + g = s1[len(s1)-1] + s1 = s1.subword(0, len(s1)-1) + s2 = s2*g**-1 + if len(s1) - len(s2) < 0: + if s2 not in self.rules: + if not check: + self._add_rule(s2, s1) + new_keys.add(s2) + elif len(s1) - len(s2) < 3: + new = self.add_rule(s1, s2, check) + new_keys.update(new) + + # overlaps on the left + while len(w1) - len(w2) > -1: + g = w1[0] + w1 = w1.subword(1, len(w1)) + w2 = g**-1*w2 + if len(w1) - len(w2) < 0: + if w2 not in self.rules: + if not check: + self._add_rule(w2, w1) + new_keys.add(w2) + elif len(w1) - len(w2) < 3: + new = self.add_rule(w1, w2, check) + new_keys.update(new) + + return new_keys + + def _remove_redundancies(self, changes=False): + ''' + Reduce left- and right-hand sides of reduction rules + and remove redundant equations (i.e. those for which + lhs == rhs). If `changes` is `True`, return a set + containing the removed keys and a set containing the + added keys + + ''' + removed = set() + added = set() + rules = self.rules.copy() + for r in rules: + v = self.reduce(r, exclude=r) + w = self.reduce(rules[r]) + if v != r: + del self.rules[r] + removed.add(r) + if v > w: + added.add(v) + self.rules[v] = w + elif v < w: + added.add(w) + self.rules[w] = v + else: + self.rules[v] = w + if changes: + return removed, added + return + + def make_confluent(self, check=False): + ''' + Try to make the system confluent using the Knuth-Bendix + completion algorithm + + ''' + if self._max_exceeded: + return self._is_confluent + lhs = list(self.rules.keys()) + + def _overlaps(r1, r2): + len1 = len(r1) + len2 = len(r2) + result = [] + for j in range(1, len1 + len2): + if (r1.subword(len1 - j, len1 + len2 - j, strict=False) + == r2.subword(j - len1, j, strict=False)): + a = r1.subword(0, len1-j, strict=False) + a = a*r2.subword(0, j-len1, strict=False) + b = r2.subword(j-len1, j, strict=False) + c = r2.subword(j, len2, strict=False) + c = c*r1.subword(len1 + len2 - j, len1, strict=False) + result.append(a*b*c) + return result + + def _process_overlap(w, r1, r2, check): + s = w.eliminate_word(r1, self.rules[r1]) + s = self.reduce(s) + t = w.eliminate_word(r2, self.rules[r2]) + t = self.reduce(t) + if s != t: + if check: + # system not confluent + return [0] + try: + new_keys = self.add_rule(t, s, check) + return new_keys + except RuntimeError: + return False + return + + added = 0 + i = 0 + while i < len(lhs): + r1 = lhs[i] + i += 1 + # j could be i+1 to not + # check each pair twice but lhs + # is extended in the loop and the new + # elements have to be checked with the + # preceding ones. there is probably a better way + # to handle this + j = 0 + while j < len(lhs): + r2 = lhs[j] + j += 1 + if r1 == r2: + continue + overlaps = _overlaps(r1, r2) + overlaps.extend(_overlaps(r1**-1, r2)) + if not overlaps: + continue + for w in overlaps: + new_keys = _process_overlap(w, r1, r2, check) + if new_keys: + if check: + return False + lhs.extend(new_keys) + added += len(new_keys) + elif new_keys == False: + # too many rules were added so the process + # couldn't complete + return self._is_confluent + + if added > self.tidyint and not check: + # tidy up + r, a = self._remove_redundancies(changes=True) + added = 0 + if r: + # reset i since some elements were removed + i = min(lhs.index(s) for s in r) + lhs = [l for l in lhs if l not in r] + lhs.extend(a) + if r1 in r: + # r1 was removed as redundant + break + + self._is_confluent = True + if not check: + self._remove_redundancies() + return True + + def _check_confluence(self): + return self.make_confluent(check=True) + + def reduce(self, word, exclude=None): + ''' + Apply reduction rules to `word` excluding the reduction rule + for the lhs equal to `exclude` + + ''' + rules = {r: self.rules[r] for r in self.rules if r != exclude} + # the following is essentially `eliminate_words()` code from the + # `FreeGroupElement` class, the only difference being the first + # "if" statement + again = True + new = word + while again: + again = False + for r in rules: + prev = new + if rules[r]**-1 > r**-1: + new = new.eliminate_word(r, rules[r], _all=True, inverse=False) + else: + new = new.eliminate_word(r, rules[r], _all=True) + if new != prev: + again = True + return new + + def _compute_inverse_rules(self, rules): + ''' + Compute the inverse rules for a given set of rules. + The inverse rules are used in the automaton for word reduction. + + Arguments: + rules (dictionary): Rules for which the inverse rules are to computed. + + Returns: + Dictionary of inverse_rules. + + ''' + inverse_rules = {} + for r in rules: + rule_key_inverse = r**-1 + rule_value_inverse = (rules[r])**-1 + if (rule_value_inverse < rule_key_inverse): + inverse_rules[rule_key_inverse] = rule_value_inverse + else: + inverse_rules[rule_value_inverse] = rule_key_inverse + return inverse_rules + + def construct_automaton(self): + ''' + Construct the automaton based on the set of reduction rules of the system. + + Automata Design: + The accept states of the automaton are the proper prefixes of the left hand side of the rules. + The complete left hand side of the rules are the dead states of the automaton. + + ''' + self._add_to_automaton(self.rules) + + def _add_to_automaton(self, rules): + ''' + Add new states and transitions to the automaton. + + Summary: + States corresponding to the new rules added to the system are computed and added to the automaton. + Transitions in the previously added states are also modified if necessary. + + Arguments: + rules (dictionary) -- Dictionary of the newly added rules. + + ''' + # Automaton variables + automaton_alphabet = [] + proper_prefixes = {} + + # compute the inverses of all the new rules added + all_rules = rules + inverse_rules = self._compute_inverse_rules(all_rules) + all_rules.update(inverse_rules) + + # Keep track of the accept_states. + accept_states = [] + + for rule in all_rules: + # The symbols present in the new rules are the symbols to be verified at each state. + # computes the automaton_alphabet, as the transitions solely depend upon the new states. + automaton_alphabet += rule.letter_form_elm + # Compute the proper prefixes for every rule. + proper_prefixes[rule] = [] + letter_word_array = list(rule.letter_form_elm) + len_letter_word_array = len(letter_word_array) + for i in range (1, len_letter_word_array): + letter_word_array[i] = letter_word_array[i-1]*letter_word_array[i] + # Add accept states. + elem = letter_word_array[i-1] + if elem not in self.reduction_automaton.states: + self.reduction_automaton.add_state(elem, state_type='a') + accept_states.append(elem) + proper_prefixes[rule] = letter_word_array + # Check for overlaps between dead and accept states. + if rule in accept_states: + self.reduction_automaton.states[rule].state_type = 'd' + self.reduction_automaton.states[rule].rh_rule = all_rules[rule] + accept_states.remove(rule) + # Add dead states + if rule not in self.reduction_automaton.states: + self.reduction_automaton.add_state(rule, state_type='d', rh_rule=all_rules[rule]) + + automaton_alphabet = set(automaton_alphabet) + + # Add new transitions for every state. + for state in self.reduction_automaton.states: + current_state_name = state + current_state_type = self.reduction_automaton.states[state].state_type + # Transitions will be modified only when suffixes of the current_state + # belongs to the proper_prefixes of the new rules. + # The rest are ignored if they cannot lead to a dead state after a finite number of transisitons. + if current_state_type == 's': + for letter in automaton_alphabet: + if letter in self.reduction_automaton.states: + self.reduction_automaton.states[state].add_transition(letter, letter) + else: + self.reduction_automaton.states[state].add_transition(letter, current_state_name) + elif current_state_type == 'a': + # Check if the transition to any new state in possible. + for letter in automaton_alphabet: + _next = current_state_name*letter + while len(_next) and _next not in self.reduction_automaton.states: + _next = _next.subword(1, len(_next)) + if not len(_next): + _next = 'start' + self.reduction_automaton.states[state].add_transition(letter, _next) + + # Add transitions for new states. All symbols used in the automaton are considered here. + # Ignore this if `reduction_automaton.automaton_alphabet` = `automaton_alphabet`. + if len(self.reduction_automaton.automaton_alphabet) != len(automaton_alphabet): + for state in accept_states: + current_state_name = state + for letter in self.reduction_automaton.automaton_alphabet: + _next = current_state_name*letter + while len(_next) and _next not in self.reduction_automaton.states: + _next = _next.subword(1, len(_next)) + if not len(_next): + _next = 'start' + self.reduction_automaton.states[state].add_transition(letter, _next) + + def reduce_using_automaton(self, word): + ''' + Reduce a word using an automaton. + + Summary: + All the symbols of the word are stored in an array and are given as the input to the automaton. + If the automaton reaches a dead state that subword is replaced and the automaton is run from the beginning. + The complete word has to be replaced when the word is read and the automaton reaches a dead state. + So, this process is repeated until the word is read completely and the automaton reaches the accept state. + + Arguments: + word (instance of FreeGroupElement) -- Word that needs to be reduced. + + ''' + # Modify the automaton if new rules are found. + if self._new_rules: + self._add_to_automaton(self._new_rules) + self._new_rules = {} + + flag = 1 + while flag: + flag = 0 + current_state = self.reduction_automaton.states['start'] + for i, s in enumerate(word.letter_form_elm): + next_state_name = current_state.transitions[s] + next_state = self.reduction_automaton.states[next_state_name] + if next_state.state_type == 'd': + subst = next_state.rh_rule + word = word.substituted_word(i - len(next_state_name) + 1, i+1, subst) + flag = 1 + break + current_state = next_state + return word diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem_fsm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem_fsm.py new file mode 100644 index 0000000000000000000000000000000000000000..21916530040ac321180692d1a0811da4ae36a056 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem_fsm.py @@ -0,0 +1,60 @@ +class State: + ''' + A representation of a state managed by a ``StateMachine``. + + Attributes: + name (instance of FreeGroupElement or string) -- State name which is also assigned to the Machine. + transisitons (OrderedDict) -- Represents all the transitions of the state object. + state_type (string) -- Denotes the type (accept/start/dead) of the state. + rh_rule (instance of FreeGroupElement) -- right hand rule for dead state. + state_machine (instance of StateMachine object) -- The finite state machine that the state belongs to. + ''' + + def __init__(self, name, state_machine, state_type=None, rh_rule=None): + self.name = name + self.transitions = {} + self.state_machine = state_machine + self.state_type = state_type[0] + self.rh_rule = rh_rule + + def add_transition(self, letter, state): + ''' + Add a transition from the current state to a new state. + + Keyword Arguments: + letter -- The alphabet element the current state reads to make the state transition. + state -- This will be an instance of the State object which represents a new state after in the transition after the alphabet is read. + + ''' + self.transitions[letter] = state + +class StateMachine: + ''' + Representation of a finite state machine the manages the states and the transitions of the automaton. + + Attributes: + states (dictionary) -- Collection of all registered `State` objects. + name (str) -- Name of the state machine. + ''' + + def __init__(self, name, automaton_alphabet): + self.name = name + self.automaton_alphabet = automaton_alphabet + self.states = {} # Contains all the states in the machine. + self.add_state('start', state_type='s') + + def add_state(self, state_name, state_type=None, rh_rule=None): + ''' + Instantiate a state object and stores it in the 'states' dictionary. + + Arguments: + state_name (instance of FreeGroupElement or string) -- name of the new states. + state_type (string) -- Denotes the type (accept/start/dead) of the state added. + rh_rule (instance of FreeGroupElement) -- right hand rule for dead state. + + ''' + new_state = State(state_name, self, state_type, rh_rule) + self.states[state_name] = new_state + + def __repr__(self): + return "%s" % (self.name) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/schur_number.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/schur_number.py new file mode 100644 index 0000000000000000000000000000000000000000..83aac98e543d4b54d4e6af17adca6e4f4de1b9ac --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/schur_number.py @@ -0,0 +1,160 @@ +""" +The Schur number S(k) is the largest integer n for which the interval [1,n] +can be partitioned into k sum-free sets.(https://mathworld.wolfram.com/SchurNumber.html) +""" +import math +from sympy.core import S +from sympy.core.basic import Basic +from sympy.core.function import Function +from sympy.core.numbers import Integer + + +class SchurNumber(Function): + r""" + This function creates a SchurNumber object + which is evaluated for `k \le 5` otherwise only + the lower bound information can be retrieved. + + Examples + ======== + + >>> from sympy.combinatorics.schur_number import SchurNumber + + Since S(3) = 13, hence the output is a number + >>> SchurNumber(3) + 13 + + We do not know the Schur number for values greater than 5, hence + only the object is returned + >>> SchurNumber(6) + SchurNumber(6) + + Now, the lower bound information can be retrieved using lower_bound() + method + >>> SchurNumber(6).lower_bound() + 536 + + """ + + @classmethod + def eval(cls, k): + if k.is_Number: + if k is S.Infinity: + return S.Infinity + if k.is_zero: + return S.Zero + if not k.is_integer or k.is_negative: + raise ValueError("k should be a positive integer") + first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44, 5: 160} + if k <= 5: + return Integer(first_known_schur_numbers[k]) + + def lower_bound(self): + f_ = self.args[0] + # Improved lower bounds known for S(6) and S(7) + if f_ == 6: + return Integer(536) + if f_ == 7: + return Integer(1680) + # For other cases, use general expression + if f_.is_Integer: + return 3*self.func(f_ - 1).lower_bound() - 1 + return (3**f_ - 1)/2 + + +def _schur_subsets_number(n): + + if n is S.Infinity: + raise ValueError("Input must be finite") + if n <= 0: + raise ValueError("n must be a non-zero positive integer.") + elif n <= 3: + min_k = 1 + else: + min_k = math.ceil(math.log(2*n + 1, 3)) + + return Integer(min_k) + + +def schur_partition(n): + """ + + This function returns the partition in the minimum number of sum-free subsets + according to the lower bound given by the Schur Number. + + Parameters + ========== + + n: a number + n is the upper limit of the range [1, n] for which we need to find and + return the minimum number of free subsets according to the lower bound + of schur number + + Returns + ======= + + List of lists + List of the minimum number of sum-free subsets + + Notes + ===== + + It is possible for some n to make the partition into less + subsets since the only known Schur numbers are: + S(1) = 1, S(2) = 4, S(3) = 13, S(4) = 44. + e.g for n = 44 the lower bound from the function above is 5 subsets but it has been proven + that can be done with 4 subsets. + + Examples + ======== + + For n = 1, 2, 3 the answer is the set itself + + >>> from sympy.combinatorics.schur_number import schur_partition + >>> schur_partition(2) + [[1, 2]] + + For n > 3, the answer is the minimum number of sum-free subsets: + + >>> schur_partition(5) + [[3, 2], [5], [1, 4]] + + >>> schur_partition(8) + [[3, 2], [6, 5, 8], [1, 4, 7]] + """ + + if isinstance(n, Basic) and not n.is_Number: + raise ValueError("Input value must be a number") + + number_of_subsets = _schur_subsets_number(n) + if n == 1: + sum_free_subsets = [[1]] + elif n == 2: + sum_free_subsets = [[1, 2]] + elif n == 3: + sum_free_subsets = [[1, 2, 3]] + else: + sum_free_subsets = [[1, 4], [2, 3]] + + while len(sum_free_subsets) < number_of_subsets: + sum_free_subsets = _generate_next_list(sum_free_subsets, n) + missed_elements = [3*k + 1 for k in range(len(sum_free_subsets), (n-1)//3 + 1)] + sum_free_subsets[-1] += missed_elements + + return sum_free_subsets + + +def _generate_next_list(current_list, n): + new_list = [] + + for item in current_list: + temp_1 = [number*3 for number in item if number*3 <= n] + temp_2 = [number*3 - 1 for number in item if number*3 - 1 <= n] + new_item = temp_1 + temp_2 + new_list.append(new_item) + + last_list = [3*k + 1 for k in range(len(current_list)+1) if 3*k + 1 <= n] + new_list.append(last_list) + current_list = new_list + + return current_list diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/subsets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/subsets.py new file mode 100644 index 0000000000000000000000000000000000000000..e540cb2395cb27e04c9d513831cb834a05ec2abd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/subsets.py @@ -0,0 +1,619 @@ +from itertools import combinations + +from sympy.combinatorics.graycode import GrayCode + + +class Subset(): + """ + Represents a basic subset object. + + Explanation + =========== + + We generate subsets using essentially two techniques, + binary enumeration and lexicographic enumeration. + The Subset class takes two arguments, the first one + describes the initial subset to consider and the second + describes the superset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.next_binary().subset + ['b'] + >>> a.prev_binary().subset + ['c'] + """ + + _rank_binary = None + _rank_lex = None + _rank_graycode = None + _subset = None + _superset = None + + def __new__(cls, subset, superset): + """ + Default constructor. + + It takes the ``subset`` and its ``superset`` as its parameters. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.subset + ['c', 'd'] + >>> a.superset + ['a', 'b', 'c', 'd'] + >>> a.size + 2 + """ + if len(subset) > len(superset): + raise ValueError('Invalid arguments have been provided. The ' + 'superset must be larger than the subset.') + for elem in subset: + if elem not in superset: + raise ValueError('The superset provided is invalid as it does ' + 'not contain the element {}'.format(elem)) + obj = object.__new__(cls) + obj._subset = subset + obj._superset = superset + return obj + + def __eq__(self, other): + """Return a boolean indicating whether a == b on the basis of + whether both objects are of the class Subset and if the values + of the subset and superset attributes are the same. + """ + if not isinstance(other, Subset): + return NotImplemented + return self.subset == other.subset and self.superset == other.superset + + def iterate_binary(self, k): + """ + This is a helper function. It iterates over the + binary subsets by ``k`` steps. This variable can be + both positive or negative. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.iterate_binary(-2).subset + ['d'] + >>> a = Subset(['a', 'b', 'c'], ['a', 'b', 'c', 'd']) + >>> a.iterate_binary(2).subset + [] + + See Also + ======== + + next_binary, prev_binary + """ + bin_list = Subset.bitlist_from_subset(self.subset, self.superset) + n = (int(''.join(bin_list), 2) + k) % 2**self.superset_size + bits = bin(n)[2:].rjust(self.superset_size, '0') + return Subset.subset_from_bitlist(self.superset, bits) + + def next_binary(self): + """ + Generates the next binary ordered subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.next_binary().subset + ['b'] + >>> a = Subset(['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.next_binary().subset + [] + + See Also + ======== + + prev_binary, iterate_binary + """ + return self.iterate_binary(1) + + def prev_binary(self): + """ + Generates the previous binary ordered subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset([], ['a', 'b', 'c', 'd']) + >>> a.prev_binary().subset + ['a', 'b', 'c', 'd'] + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.prev_binary().subset + ['c'] + + See Also + ======== + + next_binary, iterate_binary + """ + return self.iterate_binary(-1) + + def next_lexicographic(self): + """ + Generates the next lexicographically ordered subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.next_lexicographic().subset + ['d'] + >>> a = Subset(['d'], ['a', 'b', 'c', 'd']) + >>> a.next_lexicographic().subset + [] + + See Also + ======== + + prev_lexicographic + """ + i = self.superset_size - 1 + indices = Subset.subset_indices(self.subset, self.superset) + + if i in indices: + if i - 1 in indices: + indices.remove(i - 1) + else: + indices.remove(i) + i = i - 1 + while i >= 0 and i not in indices: + i = i - 1 + if i >= 0: + indices.remove(i) + indices.append(i+1) + else: + while i not in indices and i >= 0: + i = i - 1 + indices.append(i + 1) + + ret_set = [] + super_set = self.superset + for i in indices: + ret_set.append(super_set[i]) + return Subset(ret_set, super_set) + + def prev_lexicographic(self): + """ + Generates the previous lexicographically ordered subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset([], ['a', 'b', 'c', 'd']) + >>> a.prev_lexicographic().subset + ['d'] + >>> a = Subset(['c','d'], ['a', 'b', 'c', 'd']) + >>> a.prev_lexicographic().subset + ['c'] + + See Also + ======== + + next_lexicographic + """ + i = self.superset_size - 1 + indices = Subset.subset_indices(self.subset, self.superset) + + while i >= 0 and i not in indices: + i = i - 1 + + if i == 0 or i - 1 in indices: + indices.remove(i) + else: + if i >= 0: + indices.remove(i) + indices.append(i - 1) + indices.append(self.superset_size - 1) + + ret_set = [] + super_set = self.superset + for i in indices: + ret_set.append(super_set[i]) + return Subset(ret_set, super_set) + + def iterate_graycode(self, k): + """ + Helper function used for prev_gray and next_gray. + It performs ``k`` step overs to get the respective Gray codes. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) + >>> a.iterate_graycode(3).subset + [1, 4] + >>> a.iterate_graycode(-2).subset + [1, 2, 4] + + See Also + ======== + + next_gray, prev_gray + """ + unranked_code = GrayCode.unrank(self.superset_size, + (self.rank_gray + k) % self.cardinality) + return Subset.subset_from_bitlist(self.superset, + unranked_code) + + def next_gray(self): + """ + Generates the next Gray code ordered subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) + >>> a.next_gray().subset + [1, 3] + + See Also + ======== + + iterate_graycode, prev_gray + """ + return self.iterate_graycode(1) + + def prev_gray(self): + """ + Generates the previous Gray code ordered subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset([2, 3, 4], [1, 2, 3, 4, 5]) + >>> a.prev_gray().subset + [2, 3, 4, 5] + + See Also + ======== + + iterate_graycode, next_gray + """ + return self.iterate_graycode(-1) + + @property + def rank_binary(self): + """ + Computes the binary ordered rank. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset([], ['a','b','c','d']) + >>> a.rank_binary + 0 + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.rank_binary + 3 + + See Also + ======== + + iterate_binary, unrank_binary + """ + if self._rank_binary is None: + self._rank_binary = int("".join( + Subset.bitlist_from_subset(self.subset, + self.superset)), 2) + return self._rank_binary + + @property + def rank_lexicographic(self): + """ + Computes the lexicographic ranking of the subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.rank_lexicographic + 14 + >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) + >>> a.rank_lexicographic + 43 + """ + if self._rank_lex is None: + def _ranklex(self, subset_index, i, n): + if subset_index == [] or i > n: + return 0 + if i in subset_index: + subset_index.remove(i) + return 1 + _ranklex(self, subset_index, i + 1, n) + return 2**(n - i - 1) + _ranklex(self, subset_index, i + 1, n) + indices = Subset.subset_indices(self.subset, self.superset) + self._rank_lex = _ranklex(self, indices, 0, self.superset_size) + return self._rank_lex + + @property + def rank_gray(self): + """ + Computes the Gray code ranking of the subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c','d'], ['a','b','c','d']) + >>> a.rank_gray + 2 + >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) + >>> a.rank_gray + 27 + + See Also + ======== + + iterate_graycode, unrank_gray + """ + if self._rank_graycode is None: + bits = Subset.bitlist_from_subset(self.subset, self.superset) + self._rank_graycode = GrayCode(len(bits), start=bits).rank + return self._rank_graycode + + @property + def subset(self): + """ + Gets the subset represented by the current instance. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.subset + ['c', 'd'] + + See Also + ======== + + superset, size, superset_size, cardinality + """ + return self._subset + + @property + def size(self): + """ + Gets the size of the subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.size + 2 + + See Also + ======== + + subset, superset, superset_size, cardinality + """ + return len(self.subset) + + @property + def superset(self): + """ + Gets the superset of the subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.superset + ['a', 'b', 'c', 'd'] + + See Also + ======== + + subset, size, superset_size, cardinality + """ + return self._superset + + @property + def superset_size(self): + """ + Returns the size of the superset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.superset_size + 4 + + See Also + ======== + + subset, superset, size, cardinality + """ + return len(self.superset) + + @property + def cardinality(self): + """ + Returns the number of all possible subsets. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + >>> a.cardinality + 16 + + See Also + ======== + + subset, superset, size, superset_size + """ + return 2**(self.superset_size) + + @classmethod + def subset_from_bitlist(self, super_set, bitlist): + """ + Gets the subset defined by the bitlist. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> Subset.subset_from_bitlist(['a', 'b', 'c', 'd'], '0011').subset + ['c', 'd'] + + See Also + ======== + + bitlist_from_subset + """ + if len(super_set) != len(bitlist): + raise ValueError("The sizes of the lists are not equal") + ret_set = [] + for i in range(len(bitlist)): + if bitlist[i] == '1': + ret_set.append(super_set[i]) + return Subset(ret_set, super_set) + + @classmethod + def bitlist_from_subset(self, subset, superset): + """ + Gets the bitlist corresponding to a subset. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> Subset.bitlist_from_subset(['c', 'd'], ['a', 'b', 'c', 'd']) + '0011' + + See Also + ======== + + subset_from_bitlist + """ + bitlist = ['0'] * len(superset) + if isinstance(subset, Subset): + subset = subset.subset + for i in Subset.subset_indices(subset, superset): + bitlist[i] = '1' + return ''.join(bitlist) + + @classmethod + def unrank_binary(self, rank, superset): + """ + Gets the binary ordered subset of the specified rank. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> Subset.unrank_binary(4, ['a', 'b', 'c', 'd']).subset + ['b'] + + See Also + ======== + + iterate_binary, rank_binary + """ + bits = bin(rank)[2:].rjust(len(superset), '0') + return Subset.subset_from_bitlist(superset, bits) + + @classmethod + def unrank_gray(self, rank, superset): + """ + Gets the Gray code ordered subset of the specified rank. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> Subset.unrank_gray(4, ['a', 'b', 'c']).subset + ['a', 'b'] + >>> Subset.unrank_gray(0, ['a', 'b', 'c']).subset + [] + + See Also + ======== + + iterate_graycode, rank_gray + """ + graycode_bitlist = GrayCode.unrank(len(superset), rank) + return Subset.subset_from_bitlist(superset, graycode_bitlist) + + @classmethod + def subset_indices(self, subset, superset): + """Return indices of subset in superset in a list; the list is empty + if all elements of ``subset`` are not in ``superset``. + + Examples + ======== + + >>> from sympy.combinatorics import Subset + >>> superset = [1, 3, 2, 5, 4] + >>> Subset.subset_indices([3, 2, 1], superset) + [1, 2, 0] + >>> Subset.subset_indices([1, 6], superset) + [] + >>> Subset.subset_indices([], superset) + [] + + """ + a, b = superset, subset + sb = set(b) + d = {} + for i, ai in enumerate(a): + if ai in sb: + d[ai] = i + sb.remove(ai) + if not sb: + break + else: + return [] + return [d[bi] for bi in b] + + +def ksubsets(superset, k): + """ + Finds the subsets of size ``k`` in lexicographic order. + + This uses the itertools generator. + + Examples + ======== + + >>> from sympy.combinatorics.subsets import ksubsets + >>> list(ksubsets([1, 2, 3], 2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(ksubsets([1, 2, 3, 4, 5], 2)) + [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), \ + (2, 5), (3, 4), (3, 5), (4, 5)] + + See Also + ======== + + Subset + """ + return combinations(superset, k) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tensor_can.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tensor_can.py new file mode 100644 index 0000000000000000000000000000000000000000..d43e96ed27a21f988aaaa8fd16827987541f7373 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tensor_can.py @@ -0,0 +1,1189 @@ +from sympy.combinatorics.permutations import Permutation, _af_rmul, \ + _af_invert, _af_new +from sympy.combinatorics.perm_groups import PermutationGroup, _orbit, \ + _orbit_transversal +from sympy.combinatorics.util import _distribute_gens_by_base, \ + _orbits_transversals_from_bsgs + +""" + References for tensor canonicalization: + + [1] R. Portugal "Algorithmic simplification of tensor expressions", + J. Phys. A 32 (1999) 7779-7789 + + [2] R. Portugal, B.F. Svaiter "Group-theoretic Approach for Symbolic + Tensor Manipulation: I. Free Indices" + arXiv:math-ph/0107031v1 + + [3] L.R.U. Manssur, R. Portugal "Group-theoretic Approach for Symbolic + Tensor Manipulation: II. Dummy Indices" + arXiv:math-ph/0107032v1 + + [4] xperm.c part of XPerm written by J. M. Martin-Garcia + http://www.xact.es/index.html +""" + + +def dummy_sgs(dummies, sym, n): + """ + Return the strong generators for dummy indices. + + Parameters + ========== + + dummies : List of dummy indices. + `dummies[2k], dummies[2k+1]` are paired indices. + In base form, the dummy indices are always in + consecutive positions. + sym : symmetry under interchange of contracted dummies:: + * None no symmetry + * 0 commuting + * 1 anticommuting + + n : number of indices + + Examples + ======== + + >>> from sympy.combinatorics.tensor_can import dummy_sgs + >>> dummy_sgs(list(range(2, 8)), 0, 8) + [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9], + [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]] + """ + if len(dummies) > n: + raise ValueError("List too large") + res = [] + # exchange of contravariant and covariant indices + if sym is not None: + for j in dummies[::2]: + a = list(range(n + 2)) + if sym == 1: + a[n] = n + 1 + a[n + 1] = n + a[j], a[j + 1] = a[j + 1], a[j] + res.append(a) + # rename dummy indices + for j in dummies[:-3:2]: + a = list(range(n + 2)) + a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1] + res.append(a) + return res + + +def _min_dummies(dummies, sym, indices): + """ + Return list of minima of the orbits of indices in group of dummies. + See ``double_coset_can_rep`` for the description of ``dummies`` and ``sym``. + ``indices`` is the initial list of dummy indices. + + Examples + ======== + + >>> from sympy.combinatorics.tensor_can import _min_dummies + >>> _min_dummies([list(range(2, 8))], [0], list(range(10))) + [0, 1, 2, 2, 2, 2, 2, 2, 8, 9] + """ + num_types = len(sym) + m = [min(dx) if dx else None for dx in dummies] + res = indices[:] + for i in range(num_types): + for c, i in enumerate(indices): + for j in range(num_types): + if i in dummies[j]: + res[c] = m[j] + break + return res + + +def _trace_S(s, j, b, S_cosets): + """ + Return the representative h satisfying s[h[b]] == j + + If there is not such a representative return None + """ + for h in S_cosets[b]: + if s[h[b]] == j: + return h + return None + + +def _trace_D(gj, p_i, Dxtrav): + """ + Return the representative h satisfying h[gj] == p_i + + If there is not such a representative return None + """ + for h in Dxtrav: + if h[gj] == p_i: + return h + return None + + +def _dumx_remove(dumx, dumx_flat, p0): + """ + remove p0 from dumx + """ + res = [] + for dx in dumx: + if p0 not in dx: + res.append(dx) + continue + k = dx.index(p0) + if k % 2 == 0: + p0_paired = dx[k + 1] + else: + p0_paired = dx[k - 1] + dx.remove(p0) + dx.remove(p0_paired) + dumx_flat.remove(p0) + dumx_flat.remove(p0_paired) + res.append(dx) + + +def transversal2coset(size, base, transversal): + a = [] + j = 0 + for i in range(size): + if i in base: + a.append(sorted(transversal[j].values())) + j += 1 + else: + a.append([list(range(size))]) + j = len(a) - 1 + while a[j] == [list(range(size))]: + j -= 1 + return a[:j + 1] + + +def double_coset_can_rep(dummies, sym, b_S, sgens, S_transversals, g): + r""" + Butler-Portugal algorithm for tensor canonicalization with dummy indices. + + Parameters + ========== + + dummies + list of lists of dummy indices, + one list for each type of index; + the dummy indices are put in order contravariant, covariant + [d0, -d0, d1, -d1, ...]. + + sym + list of the symmetries of the index metric for each type. + + possible symmetries of the metrics + * 0 symmetric + * 1 antisymmetric + * None no symmetry + + b_S + base of a minimal slot symmetry BSGS. + + sgens + generators of the slot symmetry BSGS. + + S_transversals + transversals for the slot BSGS. + + g + permutation representing the tensor. + + Returns + ======= + + Return 0 if the tensor is zero, else return the array form of + the permutation representing the canonical form of the tensor. + + Notes + ===== + + A tensor with dummy indices can be represented in a number + of equivalent ways which typically grows exponentially with + the number of indices. To be able to establish if two tensors + with many indices are equal becomes computationally very slow + in absence of an efficient algorithm. + + The Butler-Portugal algorithm [3] is an efficient algorithm to + put tensors in canonical form, solving the above problem. + + Portugal observed that a tensor can be represented by a permutation, + and that the class of tensors equivalent to it under slot and dummy + symmetries is equivalent to the double coset `D*g*S` + (Note: in this documentation we use the conventions for multiplication + of permutations p, q with (p*q)(i) = p[q[i]] which is opposite + to the one used in the Permutation class) + + Using the algorithm by Butler to find a representative of the + double coset one can find a canonical form for the tensor. + + To see this correspondence, + let `g` be a permutation in array form; a tensor with indices `ind` + (the indices including both the contravariant and the covariant ones) + can be written as + + `t = T(ind[g[0]], \dots, ind[g[n-1]])`, + + where `n = len(ind)`; + `g` has size `n + 2`, the last two indices for the sign of the tensor + (trick introduced in [4]). + + A slot symmetry transformation `s` is a permutation acting on the slots + `t \rightarrow T(ind[(g*s)[0]], \dots, ind[(g*s)[n-1]])` + + A dummy symmetry transformation acts on `ind` + `t \rightarrow T(ind[(d*g)[0]], \dots, ind[(d*g)[n-1]])` + + Being interested only in the transformations of the tensor under + these symmetries, one can represent the tensor by `g`, which transforms + as + + `g -> d*g*s`, so it belongs to the coset `D*g*S`, or in other words + to the set of all permutations allowed by the slot and dummy symmetries. + + Let us explain the conventions by an example. + + Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries + `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` + + `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` + + and symmetric metric, find the tensor equivalent to it which + is the lowest under the ordering of indices: + lexicographic ordering `d1, d2, d3` and then contravariant + before covariant index; that is the canonical form of the tensor. + + The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}` + obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`. + + To convert this problem in the input for this function, + use the following ordering of the index names + (- for covariant for short) `d1, -d1, d2, -d2, d3, -d3` + + `T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]` + where the last two indices are for the sign + + `sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]` + + sgens[0] is the slot symmetry `-(0, 2)` + `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` + + sgens[1] is the slot symmetry `-(0, 4)` + `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` + + The dummy symmetry group D is generated by the strong base generators + `[(0, 1), (2, 3), (4, 5), (0, 2)(1, 3), (0, 4)(1, 5)]` + where the first three interchange covariant and contravariant + positions of the same index (d1 <-> -d1) and the last two interchange + the dummy indices themselves (d1 <-> d2). + + The dummy symmetry acts from the left + `d = [1, 0, 2, 3, 4, 5, 6, 7]` exchange `d1 \leftrightarrow -d1` + `T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}` + + `g=[4, 2, 0, 1, 3, 5, 6, 7] -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)` + which differs from `_af_rmul(g, d)`. + + The slot symmetry acts from the right + `s = [2, 1, 0, 3, 4, 5, 7, 6]` exchanges slots 0 and 2 and changes sign + `T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}` + + `g=[4,2,0,1,3,5,6,7] -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)` + + Example in which the tensor is zero, same slot symmetries as above: + `T^{d2}{}_{d1 d3}{}^{d1 d3}{}_{d2}` + + `= -T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,4)`; + + `= T_{d3 d1}{}^{d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,2)`; + + `= T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` symmetric metric; + + `= 0` since two of these lines have tensors differ only for the sign. + + The double coset D*g*S consists of permutations `h = d*g*s` corresponding + to equivalent tensors; if there are two `h` which are the same apart + from the sign, return zero; otherwise + choose as representative the tensor with indices + ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]` + that is ``rep = min(D*g*S) = min([d*g*s for d in D for s in S])`` + + The indices are fixed one by one; first choose the lowest index + for slot 0, then the lowest remaining index for slot 1, etc. + Doing this one obtains a chain of stabilizers + + `S \rightarrow S_{b0} \rightarrow S_{b0,b1} \rightarrow \dots` and + `D \rightarrow D_{p0} \rightarrow D_{p0,p1} \rightarrow \dots` + + where ``[b0, b1, ...] = range(b)`` is a base of the symmetric group; + the strong base `b_S` of S is an ordered sublist of it; + therefore it is sufficient to compute once the + strong base generators of S using the Schreier-Sims algorithm; + the stabilizers of the strong base generators are the + strong base generators of the stabilizer subgroup. + + ``dbase = [p0, p1, ...]`` is not in general in lexicographic order, + so that one must recompute the strong base generators each time; + however this is trivial, there is no need to use the Schreier-Sims + algorithm for D. + + The algorithm keeps a TAB of elements `(s_i, d_i, h_i)` + where `h_i = d_i \times g \times s_i` satisfying `h_i[j] = p_j` for `0 \le j < i` + starting from `s_0 = id, d_0 = id, h_0 = g`. + + The equations `h_0[0] = p_0, h_1[1] = p_1, \dots` are solved in this order, + choosing each time the lowest possible value of p_i + + For `j < i` + `d_i*g*s_i*S_{b_0, \dots, b_{i-1}}*b_j = D_{p_0, \dots, p_{i-1}}*p_j` + so that for dx in `D_{p_0,\dots,p_{i-1}}` and sx in + `S_{base[0], \dots, base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j` + + Search for dx, sx such that this equation holds for `j = i`; + it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j` + `sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})` + `dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})` + + `s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})` + `d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i` + `h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i` + + `h_n*b_j = p_j` for all j, so that `h_n` is the solution. + + Add the found `(s, d, h)` to TAB1. + + At the end of the iteration sort TAB1 with respect to the `h`; + if there are two consecutive `h` in TAB1 which differ only for the + sign, the tensor is zero, so return 0; + if there are two consecutive `h` which are equal, keep only one. + + Then stabilize the slot generators under `i` and the dummy generators + under `p_i`. + + Assign `TAB = TAB1` at the end of the iteration step. + + At the end `TAB` contains a unique `(s, d, h)`, since all the slots + of the tensor `h` have been fixed to have the minimum value according + to the symmetries. The algorithm returns `h`. + + It is important that the slot BSGS has lexicographic minimal base, + otherwise there is an `i` which does not belong to the slot base + for which `p_i` is fixed by the dummy symmetry only, while `i` + is not invariant from the slot stabilizer, so `p_i` is not in + general the minimal value. + + This algorithm differs slightly from the original algorithm [3]: + the canonical form is minimal lexicographically, and + the BSGS has minimal base under lexicographic order. + Equal tensors `h` are eliminated from TAB. + + + Examples + ======== + + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals + >>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]] + >>> base = [0, 2] + >>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7]) + >>> transversals = get_transversals(base, gens) + >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) + [0, 1, 2, 3, 4, 5, 7, 6] + + >>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7]) + >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) + 0 + """ + size = g.size + g = g.array_form + num_dummies = size - 2 + indices = list(range(num_dummies)) + all_metrics_with_sym = not any(_ is None for _ in sym) + num_types = len(sym) + dumx = dummies[:] + dumx_flat = [] + for dx in dumx: + dumx_flat.extend(dx) + b_S = b_S[:] + sgensx = [h._array_form for h in sgens] + if b_S: + S_transversals = transversal2coset(size, b_S, S_transversals) + # strong generating set for D + dsgsx = [] + for i in range(num_types): + dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) + idn = list(range(size)) + # TAB = list of entries (s, d, h) where h = _af_rmuln(d,g,s) + # for short, in the following d*g*s means _af_rmuln(d,g,s) + TAB = [(idn, idn, g)] + for i in range(size - 2): + b = i + testb = b in b_S and sgensx + if testb: + sgensx1 = [_af_new(_) for _ in sgensx] + deltab = _orbit(size, sgensx1, b) + else: + deltab = {b} + # p1 = min(IMAGES) = min(Union D_p*h*deltab for h in TAB) + if all_metrics_with_sym: + md = _min_dummies(dumx, sym, indices) + else: + md = [min(_orbit(size, [_af_new( + ddx) for ddx in dsgsx], ii)) for ii in range(size - 2)] + + p_i = min(min(md[h[x]] for x in deltab) for s, d, h in TAB) + dsgsx1 = [_af_new(_) for _ in dsgsx] + Dxtrav = _orbit_transversal(size, dsgsx1, p_i, False, af=True) \ + if dsgsx else None + if Dxtrav: + Dxtrav = [_af_invert(x) for x in Dxtrav] + # compute the orbit of p_i + for ii in range(num_types): + if p_i in dumx[ii]: + # the orbit is made by all the indices in dum[ii] + if sym[ii] is not None: + deltap = dumx[ii] + else: + # the orbit is made by all the even indices if p_i + # is even, by all the odd indices if p_i is odd + p_i_index = dumx[ii].index(p_i) % 2 + deltap = dumx[ii][p_i_index::2] + break + else: + deltap = [p_i] + TAB1 = [] + while TAB: + s, d, h = TAB.pop() + if min(md[h[x]] for x in deltab) != p_i: + continue + deltab1 = [x for x in deltab if md[h[x]] == p_i] + # NEXT = s*deltab1 intersection (d*g)**-1*deltap + dg = _af_rmul(d, g) + dginv = _af_invert(dg) + sdeltab = [s[x] for x in deltab1] + gdeltap = [dginv[x] for x in deltap] + NEXT = [x for x in sdeltab if x in gdeltap] + # d, s satisfy + # d*g*s*base[i-1] = p_{i-1}; using the stabilizers + # d*g*s*S_{base[0],...,base[i-1]}*base[i-1] = + # D_{p_0,...,p_{i-1}}*p_{i-1} + # so that to find d1, s1 satisfying d1*g*s1*b = p_i + # one can look for dx in D_{p_0,...,p_{i-1}} and + # sx in S_{base[0],...,base[i-1]} + # d1 = dx*d; s1 = s*sx + # d1*g*s1*b = dx*d*g*s*sx*b = p_i + for j in NEXT: + if testb: + # solve s1*b = j with s1 = s*sx for some element sx + # of the stabilizer of ..., base[i-1] + # sx*b = s**-1*j; sx = _trace_S(s, j,...) + # s1 = s*trace_S(s**-1*j,...) + s1 = _trace_S(s, j, b, S_transversals) + if not s1: + continue + else: + s1 = [s[ix] for ix in s1] + else: + s1 = s + # assert s1[b] == j # invariant + # solve d1*g*j = p_i with d1 = dx*d for some element dg + # of the stabilizer of ..., p_{i-1} + # dx**-1*p_i = d*g*j; dx**-1 = trace_D(d*g*j,...) + # d1 = trace_D(d*g*j,...)**-1*d + # to save an inversion in the inner loop; notice we did + # Dxtrav = [perm_af_invert(x) for x in Dxtrav] out of the loop + if Dxtrav: + d1 = _trace_D(dg[j], p_i, Dxtrav) + if not d1: + continue + else: + if p_i != dg[j]: + continue + d1 = idn + assert d1[dg[j]] == p_i # invariant + d1 = [d1[ix] for ix in d] + h1 = [d1[g[ix]] for ix in s1] + # assert h1[b] == p_i # invariant + TAB1.append((s1, d1, h1)) + + # if TAB contains equal permutations, keep only one of them; + # if TAB contains equal permutations up to the sign, return 0 + TAB1.sort(key=lambda x: x[-1]) + prev = [0] * size + while TAB1: + s, d, h = TAB1.pop() + if h[:-2] == prev[:-2]: + if h[-1] != prev[-1]: + return 0 + else: + TAB.append((s, d, h)) + prev = h + + # stabilize the SGS + sgensx = [h for h in sgensx if h[b] == b] + if b in b_S: + b_S.remove(b) + _dumx_remove(dumx, dumx_flat, p_i) + dsgsx = [] + for i in range(num_types): + dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) + return TAB[0][-1] + + +def canonical_free(base, gens, g, num_free): + """ + Canonicalization of a tensor with respect to free indices + choosing the minimum with respect to lexicographical ordering + in the free indices. + + Explanation + =========== + + ``base``, ``gens`` BSGS for slot permutation group + ``g`` permutation representing the tensor + ``num_free`` number of free indices + The indices must be ordered with first the free indices + + See explanation in double_coset_can_rep + The algorithm is a variation of the one given in [2]. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy.combinatorics.tensor_can import canonical_free + >>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]] + >>> gens = [Permutation(h) for h in gens] + >>> base = [0, 2] + >>> g = Permutation([2, 1, 0, 3, 4, 5]) + >>> canonical_free(base, gens, g, 4) + [0, 3, 1, 2, 5, 4] + + Consider the product of Riemann tensors + ``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}`` + The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]`` + The permutation corresponding to the tensor is + ``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]`` + + In particular ``a`` is position ``0``, ``b`` is in position ``9``. + Use the slot symmetries to get `T` is a form which is the minimal + in lexicographic order in the free indices ``a`` and ``b``, e.g. + ``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to + ``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]`` + + >>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens + >>> base, gens = riemann_bsgs + >>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0) + >>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9]) + >>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2) + [0, 3, 4, 6, 1, 2, 7, 5, 9, 8] + """ + g = g.array_form + size = len(g) + if not base: + return g[:] + + transversals = get_transversals(base, gens) + for x in sorted(g[:-2]): + if x not in base: + base.append(x) + h = g + for transv in transversals: + h_i = [size]*num_free + # find the element s in transversals[i] such that + # _af_rmul(h, s) has its free elements with the lowest position in h + s = None + for sk in transv.values(): + h1 = _af_rmul(h, sk) + hi = [h1.index(ix) for ix in range(num_free)] + if hi < h_i: + h_i = hi + s = sk + if s: + h = _af_rmul(h, s) + return h + + +def _get_map_slots(size, fixed_slots): + res = list(range(size)) + pos = 0 + for i in range(size): + if i in fixed_slots: + continue + res[i] = pos + pos += 1 + return res + + +def _lift_sgens(size, fixed_slots, free, s): + a = [] + j = k = 0 + fd = [y for _, y in sorted(zip(fixed_slots, free))] + num_free = len(free) + for i in range(size): + if i in fixed_slots: + a.append(fd[k]) + k += 1 + else: + a.append(s[j] + num_free) + j += 1 + return a + + +def canonicalize(g, dummies, msym, *v): + """ + canonicalize tensor formed by tensors + + Parameters + ========== + + g : permutation representing the tensor + + dummies : list representing the dummy indices + it can be a list of dummy indices of the same type + or a list of lists of dummy indices, one list for each + type of index; + the dummy indices must come after the free indices, + and put in order contravariant, covariant + [d0, -d0, d1,-d1,...] + + msym : symmetry of the metric(s) + it can be an integer or a list; + in the first case it is the symmetry of the dummy index metric; + in the second case it is the list of the symmetries of the + index metric for each type + + v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i` + + base_i, gens_i : BSGS for tensors of this type. + The BSGS should have minimal base under lexicographic ordering; + if not, an attempt is made do get the minimal BSGS; + in case of failure, + canonicalize_naive is used, which is much slower. + + n_i : number of tensors of type `i`. + + sym_i : symmetry under exchange of component tensors of type `i`. + + Both for msym and sym_i the cases are + * None no symmetry + * 0 commuting + * 1 anticommuting + + Returns + ======= + + 0 if the tensor is zero, else return the array form of + the permutation representing the canonical form of the tensor. + + Algorithm + ========= + + First one uses canonical_free to get the minimum tensor under + lexicographic order, using only the slot symmetries. + If the component tensors have not minimal BSGS, it is attempted + to find it; if the attempt fails canonicalize_naive + is used instead. + + Compute the residual slot symmetry keeping fixed the free indices + using tensor_gens(base, gens, list_free_indices, sym). + + Reduce the problem eliminating the free indices. + + Then use double_coset_can_rep and lift back the result reintroducing + the free indices. + + Examples + ======== + + one type of index with commuting metric; + + `A_{a b}` and `B_{a b}` antisymmetric and commuting + + `T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}` + + `ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices + + g = [1, 3, 0, 5, 4, 2, 6, 7] + + `T_c = 0` + + >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product + >>> from sympy.combinatorics import Permutation + >>> base2a, gens2a = get_symmetric_group_sgs(2, 1) + >>> t0 = (base2a, gens2a, 1, 0) + >>> t1 = (base2a, gens2a, 2, 0) + >>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7]) + >>> canonicalize(g, range(6), 0, t0, t1) + 0 + + same as above, but with `B_{a b}` anticommuting + + `T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}` + + can = [0,2,1,4,3,5,7,6] + + >>> t1 = (base2a, gens2a, 2, 1) + >>> canonicalize(g, range(6), 0, t0, t1) + [0, 2, 1, 4, 3, 5, 7, 6] + + two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order, + both with commuting metric + + `f^{a b c}` antisymmetric, commuting + + `A_{m a}` no symmetry, commuting + + `T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}` + + ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n] + + g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15] + + The canonical tensor is + `T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}` + + can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14] + + >>> base_f, gens_f = get_symmetric_group_sgs(3, 1) + >>> base1, gens1 = get_symmetric_group_sgs(1) + >>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1) + >>> t0 = (base_f, gens_f, 2, 0) + >>> t1 = (base_A, gens_A, 4, 0) + >>> dummies = [range(2, 10), range(10, 14)] + >>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15]) + >>> canonicalize(g, dummies, [0, 0], t0, t1) + [0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14] + """ + from sympy.combinatorics.testutil import canonicalize_naive + if not isinstance(msym, list): + if msym not in (0, 1, None): + raise ValueError('msym must be 0, 1 or None') + num_types = 1 + else: + num_types = len(msym) + if not all(msymx in (0, 1, None) for msymx in msym): + raise ValueError('msym entries must be 0, 1 or None') + if len(dummies) != num_types: + raise ValueError( + 'dummies and msym must have the same number of elements') + size = g.size + num_tensors = 0 + v1 = [] + for base_i, gens_i, n_i, sym_i in v: + # check that the BSGS is minimal; + # this property is used in double_coset_can_rep; + # if it is not minimal use canonicalize_naive + if not _is_minimal_bsgs(base_i, gens_i): + mbsgs = get_minimal_bsgs(base_i, gens_i) + if not mbsgs: + can = canonicalize_naive(g, dummies, msym, *v) + return can + base_i, gens_i = mbsgs + v1.append((base_i, gens_i, [[]] * n_i, sym_i)) + num_tensors += n_i + + if num_types == 1 and not isinstance(msym, list): + dummies = [dummies] + msym = [msym] + flat_dummies = [] + for dumx in dummies: + flat_dummies.extend(dumx) + + if flat_dummies and flat_dummies != list(range(flat_dummies[0], flat_dummies[-1] + 1)): + raise ValueError('dummies is not valid') + + # slot symmetry of the tensor + size1, sbase, sgens = gens_products(*v1) + if size != size1: + raise ValueError( + 'g has size %d, generators have size %d' % (size, size1)) + free = [i for i in range(size - 2) if i not in flat_dummies] + num_free = len(free) + + # g1 minimal tensor under slot symmetry + g1 = canonical_free(sbase, sgens, g, num_free) + if not flat_dummies: + return g1 + # save the sign of g1 + sign = 0 if g1[-1] == size - 1 else 1 + + # the free indices are kept fixed. + # Determine free_i, the list of slots of tensors which are fixed + # since they are occupied by free indices, which are fixed. + start = 0 + for i, (base_i, gens_i, n_i, sym_i) in enumerate(v): + free_i = [] + len_tens = gens_i[0].size - 2 + # for each component tensor get a list od fixed islots + for j in range(n_i): + # get the elements corresponding to the component tensor + h = g1[start:(start + len_tens)] + fr = [] + # get the positions of the fixed elements in h + for k in free: + if k in h: + fr.append(h.index(k)) + free_i.append(fr) + start += len_tens + v1[i] = (base_i, gens_i, free_i, sym_i) + # BSGS of the tensor with fixed free indices + # if tensor_gens fails in gens_product, use canonicalize_naive + size, sbase, sgens = gens_products(*v1) + + # reduce the permutations getting rid of the free indices + pos_free = [g1.index(x) for x in range(num_free)] + size_red = size - num_free + g1_red = [x - num_free for x in g1 if x in flat_dummies] + if sign: + g1_red.extend([size_red - 1, size_red - 2]) + else: + g1_red.extend([size_red - 2, size_red - 1]) + map_slots = _get_map_slots(size, pos_free) + sbase_red = [map_slots[i] for i in sbase if i not in pos_free] + sgens_red = [_af_new([map_slots[i] for i in y._array_form if i not in pos_free]) for y in sgens] + dummies_red = [[x - num_free for x in y] for y in dummies] + transv_red = get_transversals(sbase_red, sgens_red) + g1_red = _af_new(g1_red) + g2 = double_coset_can_rep( + dummies_red, msym, sbase_red, sgens_red, transv_red, g1_red) + if g2 == 0: + return 0 + # lift to the case with the free indices + g3 = _lift_sgens(size, pos_free, free, g2) + return g3 + + +def perm_af_direct_product(gens1, gens2, signed=True): + """ + Direct products of the generators gens1 and gens2. + + Examples + ======== + + >>> from sympy.combinatorics.tensor_can import perm_af_direct_product + >>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]] + >>> gens2 = [[1, 0]] + >>> perm_af_direct_product(gens1, gens2, False) + [[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]] + >>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]] + >>> gens2 = [[1, 0, 2, 3]] + >>> perm_af_direct_product(gens1, gens2, True) + [[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]] + """ + gens1 = [list(x) for x in gens1] + gens2 = [list(x) for x in gens2] + s = 2 if signed else 0 + n1 = len(gens1[0]) - s + n2 = len(gens2[0]) - s + start = list(range(n1)) + end = list(range(n1, n1 + n2)) + if signed: + gens1 = [gen[:-2] + end + [gen[-2] + n2, gen[-1] + n2] + for gen in gens1] + gens2 = [start + [x + n1 for x in gen] for gen in gens2] + else: + gens1 = [gen + end for gen in gens1] + gens2 = [start + [x + n1 for x in gen] for gen in gens2] + + res = gens1 + gens2 + + return res + + +def bsgs_direct_product(base1, gens1, base2, gens2, signed=True): + """ + Direct product of two BSGS. + + Parameters + ========== + + base1 : base of the first BSGS. + + gens1 : strong generating sequence of the first BSGS. + + base2, gens2 : similarly for the second BSGS. + + signed : flag for signed permutations. + + Examples + ======== + + >>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product) + >>> base1, gens1 = get_symmetric_group_sgs(1) + >>> base2, gens2 = get_symmetric_group_sgs(2) + >>> bsgs_direct_product(base1, gens1, base2, gens2) + ([1], [(4)(1 2)]) + """ + s = 2 if signed else 0 + n1 = gens1[0].size - s + base = list(base1) + base += [x + n1 for x in base2] + gens1 = [h._array_form for h in gens1] + gens2 = [h._array_form for h in gens2] + gens = perm_af_direct_product(gens1, gens2, signed) + size = len(gens[0]) + id_af = list(range(size)) + gens = [h for h in gens if h != id_af] + if not gens: + gens = [id_af] + return base, [_af_new(h) for h in gens] + + +def get_symmetric_group_sgs(n, antisym=False): + """ + Return base, gens of the minimal BSGS for (anti)symmetric tensor + + Parameters + ========== + + n : rank of the tensor + antisym : bool + ``antisym = False`` symmetric tensor + ``antisym = True`` antisymmetric tensor + + Examples + ======== + + >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs + >>> get_symmetric_group_sgs(3) + ([0, 1], [(4)(0 1), (4)(1 2)]) + """ + if n == 1: + return [], [_af_new(list(range(3)))] + gens = [Permutation(n - 1)(i, i + 1)._array_form for i in range(n - 1)] + if antisym == 0: + gens = [x + [n, n + 1] for x in gens] + else: + gens = [x + [n + 1, n] for x in gens] + base = list(range(n - 1)) + return base, [_af_new(h) for h in gens] + +riemann_bsgs = [0, 2], [Permutation(0, 1)(4, 5), Permutation(2, 3)(4, 5), + Permutation(5)(0, 2)(1, 3)] + + +def get_transversals(base, gens): + """ + Return transversals for the group with BSGS base, gens + """ + if not base: + return [] + stabs = _distribute_gens_by_base(base, gens) + orbits, transversals = _orbits_transversals_from_bsgs(base, stabs) + transversals = [{x: h._array_form for x, h in y.items()} for y in + transversals] + return transversals + + +def _is_minimal_bsgs(base, gens): + """ + Check if the BSGS has minimal base under lexigographic order. + + base, gens BSGS + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs + >>> _is_minimal_bsgs(*riemann_bsgs) + True + >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) + >>> _is_minimal_bsgs(*riemann_bsgs1) + False + """ + base1 = [] + sgs1 = gens[:] + size = gens[0].size + for i in range(size): + if not all(h._array_form[i] == i for h in sgs1): + base1.append(i) + sgs1 = [h for h in sgs1 if h._array_form[i] == i] + return base1 == base + + +def get_minimal_bsgs(base, gens): + """ + Compute a minimal GSGS + + base, gens BSGS + + If base, gens is a minimal BSGS return it; else return a minimal BSGS + if it fails in finding one, it returns None + + TODO: use baseswap in the case in which if it fails in finding a + minimal BSGS + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy.combinatorics.tensor_can import get_minimal_bsgs + >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) + >>> get_minimal_bsgs(*riemann_bsgs1) + ([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)]) + """ + G = PermutationGroup(gens) + base, gens = G.schreier_sims_incremental() + if not _is_minimal_bsgs(base, gens): + return None + return base, gens + + +def tensor_gens(base, gens, list_free_indices, sym=0): + """ + Returns size, res_base, res_gens BSGS for n tensors of the + same type. + + Explanation + =========== + + base, gens BSGS for tensors of this type + list_free_indices list of the slots occupied by fixed indices + for each of the tensors + + sym symmetry under commutation of two tensors + sym None no symmetry + sym 0 commuting + sym 1 anticommuting + + Examples + ======== + + >>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs + + two symmetric tensors with 3 indices without free indices + + >>> base, gens = get_symmetric_group_sgs(3) + >>> tensor_gens(base, gens, [[], []]) + (8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)]) + + two symmetric tensors with 3 indices with free indices in slot 1 and 0 + + >>> tensor_gens(base, gens, [[1], [0]]) + (8, [0, 4], [(7)(0 2), (7)(4 5)]) + + four symmetric tensors with 3 indices, two of which with free indices + + """ + def _get_bsgs(G, base, gens, free_indices): + """ + return the BSGS for G.pointwise_stabilizer(free_indices) + """ + if not free_indices: + return base[:], gens[:] + else: + H = G.pointwise_stabilizer(free_indices) + base, sgs = H.schreier_sims_incremental() + return base, sgs + + # if not base there is no slot symmetry for the component tensors + # if list_free_indices.count([]) < 2 there is no commutation symmetry + # so there is no resulting slot symmetry + if not base and list_free_indices.count([]) < 2: + n = len(list_free_indices) + size = gens[0].size + size = n * (size - 2) + 2 + return size, [], [_af_new(list(range(size)))] + + # if any(list_free_indices) one needs to compute the pointwise + # stabilizer, so G is needed + if any(list_free_indices): + G = PermutationGroup(gens) + else: + G = None + + # no_free list of lists of indices for component tensors without fixed + # indices + no_free = [] + size = gens[0].size + id_af = list(range(size)) + num_indices = size - 2 + if not list_free_indices[0]: + no_free.append(list(range(num_indices))) + res_base, res_gens = _get_bsgs(G, base, gens, list_free_indices[0]) + for i in range(1, len(list_free_indices)): + base1, gens1 = _get_bsgs(G, base, gens, list_free_indices[i]) + res_base, res_gens = bsgs_direct_product(res_base, res_gens, + base1, gens1, 1) + if not list_free_indices[i]: + no_free.append(list(range(size - 2, size - 2 + num_indices))) + size += num_indices + nr = size - 2 + res_gens = [h for h in res_gens if h._array_form != id_af] + # if sym there are no commuting tensors stop here + if sym is None or not no_free: + if not res_gens: + res_gens = [_af_new(id_af)] + return size, res_base, res_gens + + # if the component tensors have moinimal BSGS, so is their direct + # product P; the slot symmetry group is S = P*C, where C is the group + # to (anti)commute the component tensors with no free indices + # a stabilizer has the property S_i = P_i*C_i; + # the BSGS of P*C has SGS_P + SGS_C and the base is + # the ordered union of the bases of P and C. + # If P has minimal BSGS, so has S with this base. + base_comm = [] + for i in range(len(no_free) - 1): + ind1 = no_free[i] + ind2 = no_free[i + 1] + a = list(range(ind1[0])) + a.extend(ind2) + a.extend(ind1) + base_comm.append(ind1[0]) + a.extend(list(range(ind2[-1] + 1, nr))) + if sym == 0: + a.extend([nr, nr + 1]) + else: + a.extend([nr + 1, nr]) + res_gens.append(_af_new(a)) + res_base = list(res_base) + # each base is ordered; order the union of the two bases + for i in base_comm: + if i not in res_base: + res_base.append(i) + res_base.sort() + if not res_gens: + res_gens = [_af_new(id_af)] + + return size, res_base, res_gens + + +def gens_products(*v): + """ + Returns size, res_base, res_gens BSGS for n tensors of different types. + + Explanation + =========== + + v is a sequence of (base_i, gens_i, free_i, sym_i) + where + base_i, gens_i BSGS of tensor of type `i` + free_i list of the fixed slots for each of the tensors + of type `i`; if there are `n_i` tensors of type `i` + and none of them have fixed slots, `free = [[]]*n_i` + sym 0 (1) if the tensors of type `i` (anti)commute among themselves + + Examples + ======== + + >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products + >>> base, gens = get_symmetric_group_sgs(2) + >>> gens_products((base, gens, [[], []], 0)) + (6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)]) + >>> gens_products((base, gens, [[1], []], 0)) + (6, [2], [(5)(2 3)]) + """ + res_size, res_base, res_gens = tensor_gens(*v[0]) + for i in range(1, len(v)): + size, base, gens = tensor_gens(*v[i]) + res_base, res_gens = bsgs_direct_product(res_base, res_gens, base, + gens, 1) + res_size = res_gens[0].size + id_af = list(range(res_size)) + res_gens = [h for h in res_gens if h != id_af] + if not res_gens: + res_gens = [id_af] + return res_size, res_base, res_gens diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_coset_table.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_coset_table.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3f62880445c5deb526797ee0623fe3510bcbc3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_coset_table.py @@ -0,0 +1,825 @@ +from sympy.combinatorics.fp_groups import FpGroup +from sympy.combinatorics.coset_table import (CosetTable, + coset_enumeration_r, coset_enumeration_c) +from sympy.combinatorics.coset_table import modified_coset_enumeration_r +from sympy.combinatorics.free_groups import free_group + +from sympy.testing.pytest import slow + +""" +References +========== + +[1] Holt, D., Eick, B., O'Brien, E. +"Handbook of Computational Group Theory" + +[2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson +Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. +"Implementation and Analysis of the Todd-Coxeter Algorithm" + +""" + +def test_scan_1(): + # Example 5.1 from [1] + F, x, y = free_group("x, y") + f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) + c = CosetTable(f, [x]) + + c.scan_and_fill(0, x) + assert c.table == [[0, 0, None, None]] + assert c.p == [0] + assert c.n == 1 + assert c.omega == [0] + + c.scan_and_fill(0, x**3) + assert c.table == [[0, 0, None, None]] + assert c.p == [0] + assert c.n == 1 + assert c.omega == [0] + + c.scan_and_fill(0, y**3) + assert c.table == [[0, 0, 1, 2], [None, None, 2, 0], [None, None, 0, 1]] + assert c.p == [0, 1, 2] + assert c.n == 3 + assert c.omega == [0, 1, 2] + + c.scan_and_fill(0, x**-1*y**-1*x*y) + assert c.table == [[0, 0, 1, 2], [None, None, 2, 0], [2, 2, 0, 1]] + assert c.p == [0, 1, 2] + assert c.n == 3 + assert c.omega == [0, 1, 2] + + c.scan_and_fill(1, x**3) + assert c.table == [[0, 0, 1, 2], [3, 4, 2, 0], [2, 2, 0, 1], \ + [4, 1, None, None], [1, 3, None, None]] + assert c.p == [0, 1, 2, 3, 4] + assert c.n == 5 + assert c.omega == [0, 1, 2, 3, 4] + + c.scan_and_fill(1, y**3) + assert c.table == [[0, 0, 1, 2], [3, 4, 2, 0], [2, 2, 0, 1], \ + [4, 1, None, None], [1, 3, None, None]] + assert c.p == [0, 1, 2, 3, 4] + assert c.n == 5 + assert c.omega == [0, 1, 2, 3, 4] + + c.scan_and_fill(1, x**-1*y**-1*x*y) + assert c.table == [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1], \ + [None, 1, None, None], [1, 3, None, None]] + assert c.p == [0, 1, 2, 1, 1] + assert c.n == 3 + assert c.omega == [0, 1, 2] + + # Example 5.2 from [1] + f = FpGroup(F, [x**2, y**3, (x*y)**3]) + c = CosetTable(f, [x*y]) + + c.scan_and_fill(0, x*y) + assert c.table == [[1, None, None, 1], [None, 0, 0, None]] + assert c.p == [0, 1] + assert c.n == 2 + assert c.omega == [0, 1] + + c.scan_and_fill(0, x**2) + assert c.table == [[1, 1, None, 1], [0, 0, 0, None]] + assert c.p == [0, 1] + assert c.n == 2 + assert c.omega == [0, 1] + + c.scan_and_fill(0, y**3) + assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]] + assert c.p == [0, 1, 2] + assert c.n == 3 + assert c.omega == [0, 1, 2] + + c.scan_and_fill(0, (x*y)**3) + assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]] + assert c.p == [0, 1, 2] + assert c.n == 3 + assert c.omega == [0, 1, 2] + + c.scan_and_fill(1, x**2) + assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]] + assert c.p == [0, 1, 2] + assert c.n == 3 + assert c.omega == [0, 1, 2] + + c.scan_and_fill(1, y**3) + assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]] + assert c.p == [0, 1, 2] + assert c.n == 3 + assert c.omega == [0, 1, 2] + + c.scan_and_fill(1, (x*y)**3) + assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [3, 4, 1, 0], [None, 2, 4, None], [2, None, None, 3]] + assert c.p == [0, 1, 2, 3, 4] + assert c.n == 5 + assert c.omega == [0, 1, 2, 3, 4] + + c.scan_and_fill(2, x**2) + assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [3, 3, 1, 0], [2, 2, 3, 3], [2, None, None, 3]] + assert c.p == [0, 1, 2, 3, 3] + assert c.n == 4 + assert c.omega == [0, 1, 2, 3] + + +@slow +def test_coset_enumeration(): + # this test function contains the combined tests for the two strategies + # i.e. HLT and Felsch strategies. + + # Example 5.1 from [1] + F, x, y = free_group("x, y") + f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) + C_r = coset_enumeration_r(f, [x]) + C_r.compress(); C_r.standardize() + C_c = coset_enumeration_c(f, [x]) + C_c.compress(); C_c.standardize() + table1 = [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] + assert C_r.table == table1 + assert C_c.table == table1 + + # E1 from [2] Pg. 474 + F, r, s, t = free_group("r, s, t") + E1 = FpGroup(F, [t**-1*r*t*r**-2, r**-1*s*r*s**-2, s**-1*t*s*t**-2]) + C_r = coset_enumeration_r(E1, []) + C_r.compress() + C_c = coset_enumeration_c(E1, []) + C_c.compress() + table2 = [[0, 0, 0, 0, 0, 0]] + assert C_r.table == table2 + # test for issue #11449 + assert C_c.table == table2 + + # Cox group from [2] Pg. 474 + F, a, b = free_group("a, b") + Cox = FpGroup(F, [a**6, b**6, (a*b)**2, (a**2*b**2)**2, (a**3*b**3)**5]) + C_r = coset_enumeration_r(Cox, [a]) + C_r.compress(); C_r.standardize() + C_c = coset_enumeration_c(Cox, [a]) + C_c.compress(); C_c.standardize() + table3 = [[0, 0, 1, 2], + [2, 3, 4, 0], + [5, 1, 0, 6], + [1, 7, 8, 9], + [9, 10, 11, 1], + [12, 2, 9, 13], + [14, 9, 2, 11], + [3, 12, 15, 16], + [16, 17, 18, 3], + [6, 4, 3, 5], + [4, 19, 20, 21], + [21, 22, 6, 4], + [7, 5, 23, 24], + [25, 23, 5, 18], + [19, 6, 22, 26], + [24, 27, 28, 7], + [29, 8, 7, 30], + [8, 31, 32, 33], + [33, 34, 13, 8], + [10, 14, 35, 35], + [35, 36, 37, 10], + [30, 11, 10, 29], + [11, 38, 39, 14], + [13, 39, 38, 12], + [40, 15, 12, 41], + [42, 13, 34, 43], + [44, 35, 14, 45], + [15, 46, 47, 34], + [34, 48, 49, 15], + [50, 16, 21, 51], + [52, 21, 16, 49], + [17, 50, 53, 54], + [54, 55, 56, 17], + [41, 18, 17, 40], + [18, 28, 27, 25], + [26, 20, 19, 19], + [20, 57, 58, 59], + [59, 60, 51, 20], + [22, 52, 61, 23], + [23, 62, 63, 22], + [64, 24, 33, 65], + [48, 33, 24, 61], + [62, 25, 54, 66], + [67, 54, 25, 68], + [57, 26, 59, 69], + [70, 59, 26, 63], + [27, 64, 71, 72], + [72, 73, 68, 27], + [28, 41, 74, 75], + [75, 76, 30, 28], + [31, 29, 77, 78], + [79, 77, 29, 37], + [38, 30, 76, 80], + [78, 81, 82, 31], + [43, 32, 31, 42], + [32, 83, 84, 85], + [85, 86, 65, 32], + [36, 44, 87, 88], + [88, 89, 90, 36], + [45, 37, 36, 44], + [37, 82, 81, 79], + [80, 74, 41, 38], + [39, 42, 91, 92], + [92, 93, 45, 39], + [46, 40, 94, 95], + [96, 94, 40, 56], + [97, 91, 42, 82], + [83, 43, 98, 99], + [100, 98, 43, 47], + [101, 87, 44, 90], + [82, 45, 93, 97], + [95, 102, 103, 46], + [104, 47, 46, 105], + [47, 106, 107, 100], + [61, 108, 109, 48], + [105, 49, 48, 104], + [49, 110, 111, 52], + [51, 111, 110, 50], + [112, 53, 50, 113], + [114, 51, 60, 115], + [116, 61, 52, 117], + [53, 118, 119, 60], + [60, 70, 66, 53], + [55, 67, 120, 121], + [121, 122, 123, 55], + [113, 56, 55, 112], + [56, 103, 102, 96], + [69, 124, 125, 57], + [115, 58, 57, 114], + [58, 126, 127, 128], + [128, 128, 69, 58], + [66, 129, 130, 62], + [117, 63, 62, 116], + [63, 125, 124, 70], + [65, 109, 108, 64], + [131, 71, 64, 132], + [133, 65, 86, 134], + [135, 66, 70, 136], + [68, 130, 129, 67], + [137, 120, 67, 138], + [132, 68, 73, 131], + [139, 69, 128, 140], + [71, 141, 142, 86], + [86, 143, 144, 71], + [145, 72, 75, 146], + [147, 75, 72, 144], + [73, 145, 148, 120], + [120, 149, 150, 73], + [74, 151, 152, 94], + [94, 153, 146, 74], + [76, 147, 154, 77], + [77, 155, 156, 76], + [157, 78, 85, 158], + [143, 85, 78, 154], + [155, 79, 88, 159], + [160, 88, 79, 161], + [151, 80, 92, 162], + [163, 92, 80, 156], + [81, 157, 164, 165], + [165, 166, 161, 81], + [99, 107, 106, 83], + [134, 84, 83, 133], + [84, 167, 168, 169], + [169, 170, 158, 84], + [87, 171, 172, 93], + [93, 163, 159, 87], + [89, 160, 173, 174], + [174, 175, 176, 89], + [90, 90, 89, 101], + [91, 177, 178, 98], + [98, 179, 162, 91], + [180, 95, 100, 181], + [179, 100, 95, 152], + [153, 96, 121, 148], + [182, 121, 96, 183], + [177, 97, 165, 184], + [185, 165, 97, 172], + [186, 99, 169, 187], + [188, 169, 99, 178], + [171, 101, 174, 189], + [190, 174, 101, 176], + [102, 180, 191, 192], + [192, 193, 183, 102], + [103, 113, 194, 195], + [195, 196, 105, 103], + [106, 104, 197, 198], + [199, 197, 104, 109], + [110, 105, 196, 200], + [198, 201, 133, 106], + [107, 186, 202, 203], + [203, 204, 181, 107], + [108, 116, 205, 206], + [206, 207, 132, 108], + [109, 133, 201, 199], + [200, 194, 113, 110], + [111, 114, 208, 209], + [209, 210, 117, 111], + [118, 112, 211, 212], + [213, 211, 112, 123], + [214, 208, 114, 125], + [126, 115, 215, 216], + [217, 215, 115, 119], + [218, 205, 116, 130], + [125, 117, 210, 214], + [212, 219, 220, 118], + [136, 119, 118, 135], + [119, 221, 222, 217], + [122, 182, 223, 224], + [224, 225, 226, 122], + [138, 123, 122, 137], + [123, 220, 219, 213], + [124, 139, 227, 228], + [228, 229, 136, 124], + [216, 222, 221, 126], + [140, 127, 126, 139], + [127, 230, 231, 232], + [232, 233, 140, 127], + [129, 135, 234, 235], + [235, 236, 138, 129], + [130, 132, 207, 218], + [141, 131, 237, 238], + [239, 237, 131, 150], + [167, 134, 240, 241], + [242, 240, 134, 142], + [243, 234, 135, 220], + [221, 136, 229, 244], + [149, 137, 245, 246], + [247, 245, 137, 226], + [220, 138, 236, 243], + [244, 227, 139, 221], + [230, 140, 233, 248], + [238, 249, 250, 141], + [251, 142, 141, 252], + [142, 253, 254, 242], + [154, 255, 256, 143], + [252, 144, 143, 251], + [144, 257, 258, 147], + [146, 258, 257, 145], + [259, 148, 145, 260], + [261, 146, 153, 262], + [263, 154, 147, 264], + [148, 265, 266, 153], + [246, 267, 268, 149], + [260, 150, 149, 259], + [150, 250, 249, 239], + [162, 269, 270, 151], + [262, 152, 151, 261], + [152, 271, 272, 179], + [159, 273, 274, 155], + [264, 156, 155, 263], + [156, 270, 269, 163], + [158, 256, 255, 157], + [275, 164, 157, 276], + [277, 158, 170, 278], + [279, 159, 163, 280], + [161, 274, 273, 160], + [281, 173, 160, 282], + [276, 161, 166, 275], + [283, 162, 179, 284], + [164, 285, 286, 170], + [170, 188, 184, 164], + [166, 185, 189, 173], + [173, 287, 288, 166], + [241, 254, 253, 167], + [278, 168, 167, 277], + [168, 289, 290, 291], + [291, 292, 187, 168], + [189, 293, 294, 171], + [280, 172, 171, 279], + [172, 295, 296, 185], + [175, 190, 297, 297], + [297, 298, 299, 175], + [282, 176, 175, 281], + [176, 294, 293, 190], + [184, 296, 295, 177], + [284, 178, 177, 283], + [178, 300, 301, 188], + [181, 272, 271, 180], + [302, 191, 180, 303], + [304, 181, 204, 305], + [183, 266, 265, 182], + [306, 223, 182, 307], + [303, 183, 193, 302], + [308, 184, 188, 309], + [310, 189, 185, 311], + [187, 301, 300, 186], + [305, 202, 186, 304], + [312, 187, 292, 313], + [314, 297, 190, 315], + [191, 316, 317, 204], + [204, 318, 319, 191], + [320, 192, 195, 321], + [322, 195, 192, 319], + [193, 320, 323, 223], + [223, 324, 325, 193], + [194, 326, 327, 211], + [211, 328, 321, 194], + [196, 322, 329, 197], + [197, 330, 331, 196], + [332, 198, 203, 333], + [318, 203, 198, 329], + [330, 199, 206, 334], + [335, 206, 199, 336], + [326, 200, 209, 337], + [338, 209, 200, 331], + [201, 332, 339, 240], + [240, 340, 336, 201], + [202, 341, 342, 292], + [292, 343, 333, 202], + [205, 344, 345, 210], + [210, 338, 334, 205], + [207, 335, 346, 237], + [237, 347, 348, 207], + [208, 349, 350, 215], + [215, 351, 337, 208], + [352, 212, 217, 353], + [351, 217, 212, 327], + [328, 213, 224, 323], + [354, 224, 213, 355], + [349, 214, 228, 356], + [357, 228, 214, 345], + [358, 216, 232, 359], + [360, 232, 216, 350], + [344, 218, 235, 361], + [362, 235, 218, 348], + [219, 352, 363, 364], + [364, 365, 355, 219], + [222, 358, 366, 367], + [367, 368, 353, 222], + [225, 354, 369, 370], + [370, 371, 372, 225], + [307, 226, 225, 306], + [226, 268, 267, 247], + [227, 373, 374, 233], + [233, 360, 356, 227], + [229, 357, 361, 234], + [234, 375, 376, 229], + [248, 231, 230, 230], + [231, 377, 378, 379], + [379, 380, 359, 231], + [236, 362, 381, 245], + [245, 382, 383, 236], + [384, 238, 242, 385], + [340, 242, 238, 346], + [347, 239, 246, 381], + [386, 246, 239, 387], + [388, 241, 291, 389], + [343, 291, 241, 339], + [375, 243, 364, 390], + [391, 364, 243, 383], + [373, 244, 367, 392], + [393, 367, 244, 376], + [382, 247, 370, 394], + [395, 370, 247, 396], + [377, 248, 379, 397], + [398, 379, 248, 374], + [249, 384, 399, 400], + [400, 401, 387, 249], + [250, 260, 402, 403], + [403, 404, 252, 250], + [253, 251, 405, 406], + [407, 405, 251, 256], + [257, 252, 404, 408], + [406, 409, 277, 253], + [254, 388, 410, 411], + [411, 412, 385, 254], + [255, 263, 413, 414], + [414, 415, 276, 255], + [256, 277, 409, 407], + [408, 402, 260, 257], + [258, 261, 416, 417], + [417, 418, 264, 258], + [265, 259, 419, 420], + [421, 419, 259, 268], + [422, 416, 261, 270], + [271, 262, 423, 424], + [425, 423, 262, 266], + [426, 413, 263, 274], + [270, 264, 418, 422], + [420, 427, 307, 265], + [266, 303, 428, 425], + [267, 386, 429, 430], + [430, 431, 396, 267], + [268, 307, 427, 421], + [269, 283, 432, 433], + [433, 434, 280, 269], + [424, 428, 303, 271], + [272, 304, 435, 436], + [436, 437, 284, 272], + [273, 279, 438, 439], + [439, 440, 282, 273], + [274, 276, 415, 426], + [285, 275, 441, 442], + [443, 441, 275, 288], + [289, 278, 444, 445], + [446, 444, 278, 286], + [447, 438, 279, 294], + [295, 280, 434, 448], + [287, 281, 449, 450], + [451, 449, 281, 299], + [294, 282, 440, 447], + [448, 432, 283, 295], + [300, 284, 437, 452], + [442, 453, 454, 285], + [309, 286, 285, 308], + [286, 455, 456, 446], + [450, 457, 458, 287], + [311, 288, 287, 310], + [288, 454, 453, 443], + [445, 456, 455, 289], + [313, 290, 289, 312], + [290, 459, 460, 461], + [461, 462, 389, 290], + [293, 310, 463, 464], + [464, 465, 315, 293], + [296, 308, 466, 467], + [467, 468, 311, 296], + [298, 314, 469, 470], + [470, 471, 472, 298], + [315, 299, 298, 314], + [299, 458, 457, 451], + [452, 435, 304, 300], + [301, 312, 473, 474], + [474, 475, 309, 301], + [316, 302, 476, 477], + [478, 476, 302, 325], + [341, 305, 479, 480], + [481, 479, 305, 317], + [324, 306, 482, 483], + [484, 482, 306, 372], + [485, 466, 308, 454], + [455, 309, 475, 486], + [487, 463, 310, 458], + [454, 311, 468, 485], + [486, 473, 312, 455], + [459, 313, 488, 489], + [490, 488, 313, 342], + [491, 469, 314, 472], + [458, 315, 465, 487], + [477, 492, 485, 316], + [463, 317, 316, 468], + [317, 487, 493, 481], + [329, 447, 464, 318], + [468, 319, 318, 463], + [319, 467, 448, 322], + [321, 448, 467, 320], + [475, 323, 320, 466], + [432, 321, 328, 437], + [438, 329, 322, 434], + [323, 474, 452, 328], + [483, 494, 486, 324], + [466, 325, 324, 475], + [325, 485, 492, 478], + [337, 422, 433, 326], + [437, 327, 326, 432], + [327, 436, 424, 351], + [334, 426, 439, 330], + [434, 331, 330, 438], + [331, 433, 422, 338], + [333, 464, 447, 332], + [449, 339, 332, 440], + [465, 333, 343, 469], + [413, 334, 338, 418], + [336, 439, 426, 335], + [441, 346, 335, 415], + [440, 336, 340, 449], + [416, 337, 351, 423], + [339, 451, 470, 343], + [346, 443, 450, 340], + [480, 493, 487, 341], + [469, 342, 341, 465], + [342, 491, 495, 490], + [361, 407, 414, 344], + [418, 345, 344, 413], + [345, 417, 408, 357], + [381, 446, 442, 347], + [415, 348, 347, 441], + [348, 414, 407, 362], + [356, 408, 417, 349], + [423, 350, 349, 416], + [350, 425, 420, 360], + [353, 424, 436, 352], + [479, 363, 352, 435], + [428, 353, 368, 476], + [355, 452, 474, 354], + [488, 369, 354, 473], + [435, 355, 365, 479], + [402, 356, 360, 419], + [405, 361, 357, 404], + [359, 420, 425, 358], + [476, 366, 358, 428], + [427, 359, 380, 482], + [444, 381, 362, 409], + [363, 481, 477, 368], + [368, 393, 390, 363], + [365, 391, 394, 369], + [369, 490, 480, 365], + [366, 478, 483, 380], + [380, 398, 392, 366], + [371, 395, 496, 497], + [497, 498, 489, 371], + [473, 372, 371, 488], + [372, 486, 494, 484], + [392, 400, 403, 373], + [419, 374, 373, 402], + [374, 421, 430, 398], + [390, 411, 406, 375], + [404, 376, 375, 405], + [376, 403, 400, 393], + [397, 430, 421, 377], + [482, 378, 377, 427], + [378, 484, 497, 499], + [499, 499, 397, 378], + [394, 461, 445, 382], + [409, 383, 382, 444], + [383, 406, 411, 391], + [385, 450, 443, 384], + [492, 399, 384, 453], + [457, 385, 412, 493], + [387, 442, 446, 386], + [494, 429, 386, 456], + [453, 387, 401, 492], + [389, 470, 451, 388], + [493, 410, 388, 457], + [471, 389, 462, 495], + [412, 390, 393, 399], + [462, 394, 391, 410], + [401, 392, 398, 429], + [396, 445, 461, 395], + [498, 496, 395, 460], + [456, 396, 431, 494], + [431, 397, 499, 496], + [399, 477, 481, 412], + [429, 483, 478, 401], + [410, 480, 490, 462], + [496, 497, 484, 431], + [489, 495, 491, 459], + [495, 460, 459, 471], + [460, 489, 498, 498], + [472, 472, 471, 491]] + + assert C_r.table == table3 + assert C_c.table == table3 + + # Group denoted by B2,4 from [2] Pg. 474 + F, a, b = free_group("a, b") + B_2_4 = FpGroup(F, [a**4, b**4, (a*b)**4, (a**-1*b)**4, (a**2*b)**4, \ + (a*b**2)**4, (a**2*b**2)**4, (a**-1*b*a*b)**4, (a*b**-1*a*b)**4]) + C_r = coset_enumeration_r(B_2_4, [a]) + C_c = coset_enumeration_c(B_2_4, [a]) + index_r = 0 + for i in range(len(C_r.p)): + if C_r.p[i] == i: + index_r += 1 + assert index_r == 1024 + + index_c = 0 + for i in range(len(C_c.p)): + if C_c.p[i] == i: + index_c += 1 + assert index_c == 1024 + + # trivial Macdonald group G(2,2) from [2] Pg. 480 + M = FpGroup(F, [b**-1*a**-1*b*a*b**-1*a*b*a**-2, a**-1*b**-1*a*b*a**-1*b*a*b**-2]) + C_r = coset_enumeration_r(M, [a]) + C_r.compress(); C_r.standardize() + C_c = coset_enumeration_c(M, [a]) + C_c.compress(); C_c.standardize() + table4 = [[0, 0, 0, 0]] + assert C_r.table == table4 + assert C_c.table == table4 + + +def test_look_ahead(): + # Section 3.2 [Test Example] Example (d) from [2] + F, a, b, c = free_group("a, b, c") + f = FpGroup(F, [a**11, b**5, c**4, (a*c)**3, b**2*c**-1*b**-1*c, a**4*b**-1*a**-1*b]) + H = [c, b, c**2] + table0 = [[1, 2, 0, 0, 0, 0], + [3, 0, 4, 5, 6, 7], + [0, 8, 9, 10, 11, 12], + [5, 1, 10, 13, 14, 15], + [16, 5, 16, 1, 17, 18], + [4, 3, 1, 8, 19, 20], + [12, 21, 22, 23, 24, 1], + [25, 26, 27, 28, 1, 24], + [2, 10, 5, 16, 22, 28], + [10, 13, 13, 2, 29, 30]] + CosetTable.max_stack_size = 10 + C_c = coset_enumeration_c(f, H) + C_c.compress(); C_c.standardize() + assert C_c.table[: 10] == table0 + +def test_modified_methods(): + ''' + Tests for modified coset table methods. + Example 5.7 from [1] Holt, D., Eick, B., O'Brien + "Handbook of Computational Group Theory". + + ''' + F, x, y = free_group("x, y") + f = FpGroup(F, [x**3, y**5, (x*y)**2]) + H = [x*y, x**-1*y**-1*x*y*x] + C = CosetTable(f, H) + C.modified_define(0, x) + identity = C._grp.identity + a_0 = C._grp.generators[0] + a_1 = C._grp.generators[1] + + assert C.P == [[identity, None, None, None], + [None, identity, None, None]] + assert C.table == [[1, None, None, None], + [None, 0, None, None]] + + C.modified_define(1, x) + assert C.table == [[1, None, None, None], + [2, 0, None, None], + [None, 1, None, None]] + assert C.P == [[identity, None, None, None], + [identity, identity, None, None], + [None, identity, None, None]] + + C.modified_scan(0, x**3, C._grp.identity, fill=False) + assert C.P == [[identity, identity, None, None], + [identity, identity, None, None], + [identity, identity, None, None]] + assert C.table == [[1, 2, None, None], + [2, 0, None, None], + [0, 1, None, None]] + + C.modified_scan(0, x*y, C._grp.generators[0], fill=False) + assert C.P == [[identity, identity, None, a_0**-1], + [identity, identity, a_0, None], + [identity, identity, None, None]] + assert C.table == [[1, 2, None, 1], + [2, 0, 0, None], + [0, 1, None, None]] + + C.modified_define(2, y**-1) + assert C.table == [[1, 2, None, 1], + [2, 0, 0, None], + [0, 1, None, 3], + [None, None, 2, None]] + assert C.P == [[identity, identity, None, a_0**-1], + [identity, identity, a_0, None], + [identity, identity, None, identity], + [None, None, identity, None]] + + C.modified_scan(0, x**-1*y**-1*x*y*x, C._grp.generators[1]) + assert C.table == [[1, 2, None, 1], + [2, 0, 0, None], + [0, 1, None, 3], + [3, 3, 2, None]] + assert C.P == [[identity, identity, None, a_0**-1], + [identity, identity, a_0, None], + [identity, identity, None, identity], + [a_1, a_1**-1, identity, None]] + + C.modified_scan(2, (x*y)**2, C._grp.identity) + assert C.table == [[1, 2, 3, 1], + [2, 0, 0, None], + [0, 1, None, 3], + [3, 3, 2, 0]] + assert C.P == [[identity, identity, a_1**-1, a_0**-1], + [identity, identity, a_0, None], + [identity, identity, None, identity], + [a_1, a_1**-1, identity, a_1]] + + C.modified_define(2, y) + assert C.table == [[1, 2, 3, 1], + [2, 0, 0, None], + [0, 1, 4, 3], + [3, 3, 2, 0], + [None, None, None, 2]] + assert C.P == [[identity, identity, a_1**-1, a_0**-1], + [identity, identity, a_0, None], + [identity, identity, identity, identity], + [a_1, a_1**-1, identity, a_1], + [None, None, None, identity]] + + C.modified_scan(0, y**5, C._grp.identity) + assert C.table == [[1, 2, 3, 1], [2, 0, 0, 4], [0, 1, 4, 3], [3, 3, 2, 0], [None, None, 1, 2]] + assert C.P == [[identity, identity, a_1**-1, a_0**-1], + [identity, identity, a_0, a_0*a_1**-1], + [identity, identity, identity, identity], + [a_1, a_1**-1, identity, a_1], + [None, None, a_1*a_0**-1, identity]] + + C.modified_scan(1, (x*y)**2, C._grp.identity) + assert C.table == [[1, 2, 3, 1], + [2, 0, 0, 4], + [0, 1, 4, 3], + [3, 3, 2, 0], + [4, 4, 1, 2]] + assert C.P == [[identity, identity, a_1**-1, a_0**-1], + [identity, identity, a_0, a_0*a_1**-1], + [identity, identity, identity, identity], + [a_1, a_1**-1, identity, a_1], + [a_0*a_1**-1, a_1*a_0**-1, a_1*a_0**-1, identity]] + + # Modified coset enumeration test + f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) + C = coset_enumeration_r(f, [x]) + C_m = modified_coset_enumeration_r(f, [x]) + assert C_m.table == C.table diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_fp_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_fp_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..3f57bdf8eff92a3022d8e01cd74ce98575987929 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_fp_groups.py @@ -0,0 +1,257 @@ +from sympy.core.singleton import S +from sympy.combinatorics.fp_groups import (FpGroup, low_index_subgroups, + reidemeister_presentation, FpSubgroup, + simplify_presentation) +from sympy.combinatorics.free_groups import (free_group, FreeGroup) + +from sympy.testing.pytest import slow + +""" +References +========== + +[1] Holt, D., Eick, B., O'Brien, E. +"Handbook of Computational Group Theory" + +[2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson +Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. +"Implementation and Analysis of the Todd-Coxeter Algorithm" + +[3] PROC. SECOND INTERNAT. CONF. THEORY OF GROUPS, CANBERRA 1973, +pp. 347-356. "A Reidemeister-Schreier program" by George Havas. +http://staff.itee.uq.edu.au/havas/1973cdhw.pdf + +""" + +def test_low_index_subgroups(): + F, x, y = free_group("x, y") + + # Example 5.10 from [1] Pg. 194 + f = FpGroup(F, [x**2, y**3, (x*y)**4]) + L = low_index_subgroups(f, 4) + t1 = [[[0, 0, 0, 0]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]], + [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]], + [[1, 1, 0, 0], [0, 0, 1, 1]]] + for i in range(len(t1)): + assert L[i].table == t1[i] + + f = FpGroup(F, [x**2, y**3, (x*y)**7]) + L = low_index_subgroups(f, 15) + t2 = [[[0, 0, 0, 0]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [4, 4, 5, 3], [6, 6, 3, 4], [5, 5, 6, 6]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [5, 5, 3, 4], [4, 4, 6, 6]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], + [11, 11, 9, 6], [9, 9, 6, 8], [12, 12, 11, 7], [8, 8, 7, 10], + [10, 10, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], + [11, 11, 9, 6], [12, 12, 6, 8], [10, 10, 11, 7], [8, 8, 7, 10], + [9, 9, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], + [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], + [11, 11, 9, 6], [12, 12, 6, 8], [13, 13, 11, 7], [8, 8, 7, 10], + [9, 9, 12, 12], [10, 10, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6] + , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7], + [10, 10, 7, 8], [9, 9, 11, 12], [11, 11, 12, 10], [13, 13, 10, 11], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6] + , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7], + [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11], + [11, 11, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 4, 4] + , [7, 7, 6, 3], [8, 8, 3, 5], [5, 5, 8, 9], [6, 6, 9, 7], + [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11], + [11, 11, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [5, 5, 6, 3], [9, 9, 3, 5], [10, 10, 8, 4], [8, 8, 4, 7], + [6, 6, 10, 11], [7, 7, 11, 9], [12, 12, 9, 10], [11, 11, 13, 14], + [14, 14, 14, 12], [13, 13, 12, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7], + [5, 5, 10, 12], [7, 7, 12, 9], [8, 8, 11, 11], [13, 13, 9, 10], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7], + [5, 5, 12, 11], [7, 7, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7], + [5, 5, 9, 9], [6, 6, 11, 12], [8, 8, 12, 10], [13, 13, 10, 11], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7], + [5, 5, 12, 11], [6, 6, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9], + [12, 12, 13, 13]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] + , [9, 9, 6, 3], [10, 10, 3, 5], [11, 11, 8, 4], [12, 12, 4, 7], + [5, 5, 9, 9], [6, 6, 12, 13], [7, 7, 11, 11], [8, 8, 13, 10], + [13, 13, 10, 12]], + [[1, 1, 0, 0], [0, 0, 2, 3], [4, 4, 3, 1], [5, 5, 1, 2], [2, 2, 4, 4] + , [3, 3, 6, 7], [7, 7, 7, 5], [6, 6, 5, 6]]] + for i in range(len(t2)): + assert L[i].table == t2[i] + + f = FpGroup(F, [x**2, y**3, (x*y)**7]) + L = low_index_subgroups(f, 10, [x]) + t3 = [[[0, 0, 0, 0]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [4, 4, 5, 3], + [6, 6, 3, 4], [5, 5, 6, 6]], + [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3], + [5, 5, 3, 4], [4, 4, 6, 6]], + [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8], + [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]]] + for i in range(len(t3)): + assert L[i].table == t3[i] + + +def test_subgroup_presentations(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x**3, y**5, (x*y)**2]) + H = [x*y, x**-1*y**-1*x*y*x] + p1 = reidemeister_presentation(f, H) + assert str(p1) == "((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))" + + H = f.subgroup(H) + assert (H.generators, H.relators) == p1 + + f = FpGroup(F, [x**3, y**3, (x*y)**3]) + H = [x*y, x*y**-1] + p2 = reidemeister_presentation(f, H) + assert str(p2) == "((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))" + + f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) + H = [x] + p3 = reidemeister_presentation(f, H) + assert str(p3) == "((x_0,), (x_0**4,))" + + f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2]) + H = [x] + p4 = reidemeister_presentation(f, H) + assert str(p4) == "((x_0,), (x_0**6,))" + + # this presentation can be improved, the most simplified form + # of presentation is + # See [2] Pg 474 group PSL_2(11) + # This is the group PSL_2(11) + F, a, b, c = free_group("a, b, c") + f = FpGroup(F, [a**11, b**5, c**4, (b*c**2)**2, (a*b*c)**3, (a**4*c**2)**3, b**2*c**-1*b**-1*c, a**4*b**-1*a**-1*b]) + H = [a, b, c**2] + gens, rels = reidemeister_presentation(f, H) + assert str(gens) == "(b_1, c_3)" + assert len(rels) == 18 + + +@slow +def test_order(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + assert f.order() == 8 + + f = FpGroup(F, [x*y*x**-1*y**-1, y**2]) + assert f.order() is S.Infinity + + F, a, b, c = free_group("a, b, c") + f = FpGroup(F, [a**250, b**2, c*b*c**-1*b, c**4, c**-1*a**-1*c*a, a**-1*b**-1*a*b]) + assert f.order() == 2000 + + F, x = free_group("x") + f = FpGroup(F, []) + assert f.order() is S.Infinity + + f = FpGroup(free_group('')[0], []) + assert f.order() == 1 + +def test_fp_subgroup(): + def _test_subgroup(K, T, S): + _gens = T(K.generators) + assert all(elem in S for elem in _gens) + assert T.is_injective() + assert T.image().order() == S.order() + F, x, y = free_group("x, y") + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + S = FpSubgroup(f, [x*y]) + assert (x*y)**-3 in S + K, T = f.subgroup([x*y], homomorphism=True) + assert T(K.generators) == [y*x**-1] + _test_subgroup(K, T, S) + + S = FpSubgroup(f, [x**-1*y*x]) + assert x**-1*y**4*x in S + assert x**-1*y**4*x**2 not in S + K, T = f.subgroup([x**-1*y*x], homomorphism=True) + assert T(K.generators[0]**3) == y**3 + _test_subgroup(K, T, S) + + f = FpGroup(F, [x**3, y**5, (x*y)**2]) + H = [x*y, x**-1*y**-1*x*y*x] + K, T = f.subgroup(H, homomorphism=True) + S = FpSubgroup(f, H) + _test_subgroup(K, T, S) + +def test_permutation_methods(): + F, x, y = free_group("x, y") + # DihedralGroup(8) + G = FpGroup(F, [x**2, y**8, x*y*x**-1*y]) + T = G._to_perm_group()[1] + assert T.is_isomorphism() + assert G.center() == [y**4] + + # DiheadralGroup(4) + G = FpGroup(F, [x**2, y**4, x*y*x**-1*y]) + S = FpSubgroup(G, G.normal_closure([x])) + assert x in S + assert y**-1*x*y in S + + # Z_5xZ_4 + G = FpGroup(F, [x*y*x**-1*y**-1, y**5, x**4]) + assert G.is_abelian + assert G.is_solvable + + # AlternatingGroup(5) + G = FpGroup(F, [x**3, y**2, (x*y)**5]) + assert not G.is_solvable + + # AlternatingGroup(4) + G = FpGroup(F, [x**3, y**2, (x*y)**3]) + assert len(G.derived_series()) == 3 + S = FpSubgroup(G, G.derived_subgroup()) + assert S.order() == 4 + + +def test_simplify_presentation(): + # ref #16083 + G = simplify_presentation(FpGroup(FreeGroup([]), [])) + assert not G.generators + assert not G.relators + + # CyclicGroup(3) + # The second generator in is trivial due to relators {x^2, x^5} + F, x, y = free_group("x, y") + G = simplify_presentation(FpGroup(F, [x**2, x**5, y**3])) + assert x in G.relators + +def test_cyclic(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x]) + assert f.is_cyclic + f = FpGroup(F, [x*y, x*y**-1]) + assert f.is_cyclic + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + assert not f.is_cyclic + + +def test_abelian_invariants(): + F, x, y = free_group("x, y") + f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x]) + assert f.abelian_invariants() == [] + f = FpGroup(F, [x*y, x*y**-1]) + assert f.abelian_invariants() == [2] + f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) + assert f.abelian_invariants() == [2, 4] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_free_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_free_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..439be4b7c5e8bb5ff592c9b7f07773e82952b3d5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_free_groups.py @@ -0,0 +1,226 @@ +from sympy.combinatorics.free_groups import free_group, FreeGroup +from sympy.core import Symbol +from sympy.testing.pytest import raises +from sympy.core.numbers import oo + +F, x, y, z = free_group("x, y, z") + + +def test_FreeGroup__init__(): + x, y, z = map(Symbol, "xyz") + + assert len(FreeGroup("x, y, z").generators) == 3 + assert len(FreeGroup(x).generators) == 1 + assert len(FreeGroup(("x", "y", "z"))) == 3 + assert len(FreeGroup((x, y, z)).generators) == 3 + + +def test_FreeGroup__getnewargs__(): + x, y, z = map(Symbol, "xyz") + assert FreeGroup("x, y, z").__getnewargs__() == ((x, y, z),) + + +def test_free_group(): + G, a, b, c = free_group("a, b, c") + assert F.generators == (x, y, z) + assert x*z**2 in F + assert x in F + assert y*z**-1 in F + assert (y*z)**0 in F + assert a not in F + assert a**0 not in F + assert len(F) == 3 + assert str(F) == '' + assert not F == G + assert F.order() is oo + assert F.is_abelian == False + assert F.center() == {F.identity} + + (e,) = free_group("") + assert e.order() == 1 + assert e.generators == () + assert e.elements == {e.identity} + assert e.is_abelian == True + + +def test_FreeGroup__hash__(): + assert hash(F) + + +def test_FreeGroup__eq__(): + assert free_group("x, y, z")[0] == free_group("x, y, z")[0] + assert free_group("x, y, z")[0] is free_group("x, y, z")[0] + + assert free_group("x, y, z")[0] != free_group("a, x, y")[0] + assert free_group("x, y, z")[0] is not free_group("a, x, y")[0] + + assert free_group("x, y")[0] != free_group("x, y, z")[0] + assert free_group("x, y")[0] is not free_group("x, y, z")[0] + + assert free_group("x, y, z")[0] != free_group("x, y")[0] + assert free_group("x, y, z")[0] is not free_group("x, y")[0] + + +def test_FreeGroup__getitem__(): + assert F[0:] == FreeGroup("x, y, z") + assert F[1:] == FreeGroup("y, z") + assert F[2:] == FreeGroup("z") + + +def test_FreeGroupElm__hash__(): + assert hash(x*y*z) + + +def test_FreeGroupElm_copy(): + f = x*y*z**3 + g = f.copy() + h = x*y*z**7 + + assert f == g + assert f != h + + +def test_FreeGroupElm_inverse(): + assert x.inverse() == x**-1 + assert (x*y).inverse() == y**-1*x**-1 + assert (y*x*y**-1).inverse() == y*x**-1*y**-1 + assert (y**2*x**-1).inverse() == x*y**-2 + + +def test_FreeGroupElm_type_error(): + raises(TypeError, lambda: 2/x) + raises(TypeError, lambda: x**2 + y**2) + raises(TypeError, lambda: x/2) + + +def test_FreeGroupElm_methods(): + assert (x**0).order() == 1 + assert (y**2).order() is oo + assert (x**-1*y).commutator(x) == y**-1*x**-1*y*x + assert len(x**2*y**-1) == 3 + assert len(x**-1*y**3*z) == 5 + + +def test_FreeGroupElm_eliminate_word(): + w = x**5*y*x**2*y**-4*x + assert w.eliminate_word( x, x**2 ) == x**10*y*x**4*y**-4*x**2 + w3 = x**2*y**3*x**-1*y + assert w3.eliminate_word(x, x**2) == x**4*y**3*x**-2*y + assert w3.eliminate_word(x, y) == y**5 + assert w3.eliminate_word(x, y**4) == y**8 + assert w3.eliminate_word(y, x**-1) == x**-3 + assert w3.eliminate_word(x, y*z) == y*z*y*z*y**3*z**-1 + assert (y**-3).eliminate_word(y, x**-1*z**-1) == z*x*z*x*z*x + #assert w3.eliminate_word(x, y*x) == y*x*y*x**2*y*x*y*x*y*x*z**3 + #assert w3.eliminate_word(x, x*y) == x*y*x**2*y*x*y*x*y*x*y*z**3 + + +def test_FreeGroupElm_array_form(): + assert (x*z).array_form == ((Symbol('x'), 1), (Symbol('z'), 1)) + assert (x**2*z*y*x**-2).array_form == \ + ((Symbol('x'), 2), (Symbol('z'), 1), (Symbol('y'), 1), (Symbol('x'), -2)) + assert (x**-2*y**-1).array_form == ((Symbol('x'), -2), (Symbol('y'), -1)) + + +def test_FreeGroupElm_letter_form(): + assert (x**3).letter_form == (Symbol('x'), Symbol('x'), Symbol('x')) + assert (x**2*z**-2*x).letter_form == \ + (Symbol('x'), Symbol('x'), -Symbol('z'), -Symbol('z'), Symbol('x')) + + +def test_FreeGroupElm_ext_rep(): + assert (x**2*z**-2*x).ext_rep == \ + (Symbol('x'), 2, Symbol('z'), -2, Symbol('x'), 1) + assert (x**-2*y**-1).ext_rep == (Symbol('x'), -2, Symbol('y'), -1) + assert (x*z).ext_rep == (Symbol('x'), 1, Symbol('z'), 1) + + +def test_FreeGroupElm__mul__pow__(): + x1 = x.group.dtype(((Symbol('x'), 1),)) + assert x**2 == x1*x + + assert (x**2*y*x**-2)**4 == x**2*y**4*x**-2 + assert (x**2)**2 == x**4 + assert (x**-1)**-1 == x + assert (x**-1)**0 == F.identity + assert (y**2)**-2 == y**-4 + + assert x**2*x**-1 == x + assert x**2*y**2*y**-1 == x**2*y + assert x*x**-1 == F.identity + + assert x/x == F.identity + assert x/x**2 == x**-1 + assert (x**2*y)/(x**2*y**-1) == x**2*y**2*x**-2 + assert (x**2*y)/(y**-1*x**2) == x**2*y*x**-2*y + + assert x*(x**-1*y*z*y**-1) == y*z*y**-1 + assert x**2*(x**-2*y**-1*z**2*y) == y**-1*z**2*y + + a = F.identity + for n in range(10): + assert a == x**n + assert a**-1 == x**-n + a *= x + + +def test_FreeGroupElm__len__(): + assert len(x**5*y*x**2*y**-4*x) == 13 + assert len(x**17) == 17 + assert len(y**0) == 0 + + +def test_FreeGroupElm_comparison(): + assert not (x*y == y*x) + assert x**0 == y**0 + + assert x**2 < y**3 + assert not x**3 < y**2 + assert x*y < x**2*y + assert x**2*y**2 < y**4 + assert not y**4 < y**-4 + assert not y**4 < x**-4 + assert y**-2 < y**2 + + assert x**2 <= y**2 + assert x**2 <= x**2 + + assert not y*z > z*y + assert x > x**-1 + + assert not x**2 >= y**2 + + +def test_FreeGroupElm_syllables(): + w = x**5*y*x**2*y**-4*x + assert w.number_syllables() == 5 + assert w.exponent_syllable(2) == 2 + assert w.generator_syllable(3) == Symbol('y') + assert w.sub_syllables(1, 2) == y + assert w.sub_syllables(3, 3) == F.identity + + +def test_FreeGroup_exponents(): + w1 = x**2*y**3 + assert w1.exponent_sum(x) == 2 + assert w1.exponent_sum(x**-1) == -2 + assert w1.generator_count(x) == 2 + + w2 = x**2*y**4*x**-3 + assert w2.exponent_sum(x) == -1 + assert w2.generator_count(x) == 5 + + +def test_FreeGroup_generators(): + assert (x**2*y**4*z**-1).contains_generators() == {x, y, z} + assert (x**-1*y**3).contains_generators() == {x, y} + + +def test_FreeGroupElm_words(): + w = x**5*y*x**2*y**-4*x + assert w.subword(2, 6) == x**3*y + assert w.subword(3, 2) == F.identity + assert w.subword(6, 10) == x**2*y**-2 + + assert w.substituted_word(0, 7, y**-1) == y**-1*x*y**-4*x + assert w.substituted_word(0, 7, y**2*x) == y**2*x**2*y**-4*x diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_galois.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_galois.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2ac29a846db88444d275b72a85ce3debaeaf05 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_galois.py @@ -0,0 +1,82 @@ +"""Test groups defined by the galois module. """ + +from sympy.combinatorics.galois import ( + S4TransitiveSubgroups, S5TransitiveSubgroups, S6TransitiveSubgroups, + find_transitive_subgroups_of_S6, +) +from sympy.combinatorics.homomorphisms import is_isomorphic +from sympy.combinatorics.named_groups import ( + SymmetricGroup, AlternatingGroup, CyclicGroup, +) + + +def test_four_group(): + G = S4TransitiveSubgroups.V.get_perm_group() + A4 = AlternatingGroup(4) + assert G.is_subgroup(A4) + assert G.degree == 4 + assert G.is_transitive() + assert G.order() == 4 + assert not G.is_cyclic + + +def test_M20(): + G = S5TransitiveSubgroups.M20.get_perm_group() + S5 = SymmetricGroup(5) + A5 = AlternatingGroup(5) + assert G.is_subgroup(S5) + assert not G.is_subgroup(A5) + assert G.degree == 5 + assert G.is_transitive() + assert G.order() == 20 + + +# Setting this True means that for each of the transitive subgroups of S6, +# we run a test not only on the fixed representation, but also on one freshly +# generated by the search procedure. +INCLUDE_SEARCH_REPS = False +S6_randomized = {} +if INCLUDE_SEARCH_REPS: + S6_randomized = find_transitive_subgroups_of_S6(*list(S6TransitiveSubgroups)) + + +def get_versions_of_S6_subgroup(name): + vers = [name.get_perm_group()] + if INCLUDE_SEARCH_REPS: + vers.append(S6_randomized[name]) + return vers + + +def test_S6_transitive_subgroups(): + """ + Test enough characteristics to distinguish all 16 transitive subgroups. + """ + ts = S6TransitiveSubgroups + A6 = AlternatingGroup(6) + for name, alt, order, is_isom, not_isom in [ + (ts.C6, False, 6, CyclicGroup(6), None), + (ts.S3, False, 6, SymmetricGroup(3), None), + (ts.D6, False, 12, None, None), + (ts.A4, True, 12, None, None), + (ts.G18, False, 18, None, None), + (ts.A4xC2, False, 24, None, SymmetricGroup(4)), + (ts.S4m, False, 24, SymmetricGroup(4), None), + (ts.S4p, True, 24, None, None), + (ts.G36m, False, 36, None, None), + (ts.G36p, True, 36, None, None), + (ts.S4xC2, False, 48, None, None), + (ts.PSL2F5, True, 60, None, None), + (ts.G72, False, 72, None, None), + (ts.PGL2F5, False, 120, None, None), + (ts.A6, True, 360, None, None), + (ts.S6, False, 720, None, None), + ]: + for G in get_versions_of_S6_subgroup(name): + assert G.is_transitive() + assert G.degree == 6 + assert G.is_subgroup(A6) is alt + assert G.order() == order + if is_isom: + assert is_isomorphic(G, is_isom) + if not_isom: + assert not is_isomorphic(G, not_isom) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_generators.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_generators.py new file mode 100644 index 0000000000000000000000000000000000000000..795ef8f08f6ec212879f528c6a0c2f0bd73037f0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_generators.py @@ -0,0 +1,105 @@ +from sympy.combinatorics.generators import symmetric, cyclic, alternating, \ + dihedral, rubik +from sympy.combinatorics.permutations import Permutation +from sympy.testing.pytest import raises + +def test_generators(): + + assert list(cyclic(6)) == [ + Permutation([0, 1, 2, 3, 4, 5]), + Permutation([1, 2, 3, 4, 5, 0]), + Permutation([2, 3, 4, 5, 0, 1]), + Permutation([3, 4, 5, 0, 1, 2]), + Permutation([4, 5, 0, 1, 2, 3]), + Permutation([5, 0, 1, 2, 3, 4])] + + assert list(cyclic(10)) == [ + Permutation([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + Permutation([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), + Permutation([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]), + Permutation([3, 4, 5, 6, 7, 8, 9, 0, 1, 2]), + Permutation([4, 5, 6, 7, 8, 9, 0, 1, 2, 3]), + Permutation([5, 6, 7, 8, 9, 0, 1, 2, 3, 4]), + Permutation([6, 7, 8, 9, 0, 1, 2, 3, 4, 5]), + Permutation([7, 8, 9, 0, 1, 2, 3, 4, 5, 6]), + Permutation([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]), + Permutation([9, 0, 1, 2, 3, 4, 5, 6, 7, 8])] + + assert list(alternating(4)) == [ + Permutation([0, 1, 2, 3]), + Permutation([0, 2, 3, 1]), + Permutation([0, 3, 1, 2]), + Permutation([1, 0, 3, 2]), + Permutation([1, 2, 0, 3]), + Permutation([1, 3, 2, 0]), + Permutation([2, 0, 1, 3]), + Permutation([2, 1, 3, 0]), + Permutation([2, 3, 0, 1]), + Permutation([3, 0, 2, 1]), + Permutation([3, 1, 0, 2]), + Permutation([3, 2, 1, 0])] + + assert list(symmetric(3)) == [ + Permutation([0, 1, 2]), + Permutation([0, 2, 1]), + Permutation([1, 0, 2]), + Permutation([1, 2, 0]), + Permutation([2, 0, 1]), + Permutation([2, 1, 0])] + + assert list(symmetric(4)) == [ + Permutation([0, 1, 2, 3]), + Permutation([0, 1, 3, 2]), + Permutation([0, 2, 1, 3]), + Permutation([0, 2, 3, 1]), + Permutation([0, 3, 1, 2]), + Permutation([0, 3, 2, 1]), + Permutation([1, 0, 2, 3]), + Permutation([1, 0, 3, 2]), + Permutation([1, 2, 0, 3]), + Permutation([1, 2, 3, 0]), + Permutation([1, 3, 0, 2]), + Permutation([1, 3, 2, 0]), + Permutation([2, 0, 1, 3]), + Permutation([2, 0, 3, 1]), + Permutation([2, 1, 0, 3]), + Permutation([2, 1, 3, 0]), + Permutation([2, 3, 0, 1]), + Permutation([2, 3, 1, 0]), + Permutation([3, 0, 1, 2]), + Permutation([3, 0, 2, 1]), + Permutation([3, 1, 0, 2]), + Permutation([3, 1, 2, 0]), + Permutation([3, 2, 0, 1]), + Permutation([3, 2, 1, 0])] + + assert list(dihedral(1)) == [ + Permutation([0, 1]), Permutation([1, 0])] + + assert list(dihedral(2)) == [ + Permutation([0, 1, 2, 3]), + Permutation([1, 0, 3, 2]), + Permutation([2, 3, 0, 1]), + Permutation([3, 2, 1, 0])] + + assert list(dihedral(3)) == [ + Permutation([0, 1, 2]), + Permutation([2, 1, 0]), + Permutation([1, 2, 0]), + Permutation([0, 2, 1]), + Permutation([2, 0, 1]), + Permutation([1, 0, 2])] + + assert list(dihedral(5)) == [ + Permutation([0, 1, 2, 3, 4]), + Permutation([4, 3, 2, 1, 0]), + Permutation([1, 2, 3, 4, 0]), + Permutation([0, 4, 3, 2, 1]), + Permutation([2, 3, 4, 0, 1]), + Permutation([1, 0, 4, 3, 2]), + Permutation([3, 4, 0, 1, 2]), + Permutation([2, 1, 0, 4, 3]), + Permutation([4, 0, 1, 2, 3]), + Permutation([3, 2, 1, 0, 4])] + + raises(ValueError, lambda: rubik(1)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_graycode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_graycode.py new file mode 100644 index 0000000000000000000000000000000000000000..a754a3c401b07c9c12cb9bdeeefdfc94f6cb8b5c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_graycode.py @@ -0,0 +1,72 @@ +from sympy.combinatorics.graycode import (GrayCode, bin_to_gray, + random_bitstring, get_subset_from_bitstring, graycode_subsets, + gray_to_bin) +from sympy.testing.pytest import raises + +def test_graycode(): + g = GrayCode(2) + got = [] + for i in g.generate_gray(): + if i.startswith('0'): + g.skip() + got.append(i) + assert got == '00 11 10'.split() + a = GrayCode(6) + assert a.current == '0'*6 + assert a.rank == 0 + assert len(list(a.generate_gray())) == 64 + codes = ['011001', '011011', '011010', + '011110', '011111', '011101', '011100', '010100', '010101', '010111', + '010110', '010010', '010011', '010001', '010000', '110000', '110001', + '110011', '110010', '110110', '110111', '110101', '110100', '111100', + '111101', '111111', '111110', '111010', '111011', '111001', '111000', + '101000', '101001', '101011', '101010', '101110', '101111', '101101', + '101100', '100100', '100101', '100111', '100110', '100010', '100011', + '100001', '100000'] + assert list(a.generate_gray(start='011001')) == codes + assert list( + a.generate_gray(rank=GrayCode(6, start='011001').rank)) == codes + assert a.next().current == '000001' + assert a.next(2).current == '000011' + assert a.next(-1).current == '100000' + + a = GrayCode(5, start='10010') + assert a.rank == 28 + a = GrayCode(6, start='101000') + assert a.rank == 48 + + assert GrayCode(6, rank=4).current == '000110' + assert GrayCode(6, rank=4).rank == 4 + assert [GrayCode(4, start=s).rank for s in + GrayCode(4).generate_gray()] == [0, 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15] + a = GrayCode(15, rank=15) + assert a.current == '000000000001000' + + assert bin_to_gray('111') == '100' + + a = random_bitstring(5) + assert type(a) is str + assert len(a) == 5 + assert all(i in ['0', '1'] for i in a) + + assert get_subset_from_bitstring( + ['a', 'b', 'c', 'd'], '0011') == ['c', 'd'] + assert get_subset_from_bitstring('abcd', '1001') == ['a', 'd'] + assert list(graycode_subsets(['a', 'b', 'c'])) == \ + [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], + ['a', 'c'], ['a']] + + raises(ValueError, lambda: GrayCode(0)) + raises(ValueError, lambda: GrayCode(2.2)) + raises(ValueError, lambda: GrayCode(2, start=[1, 1, 0])) + raises(ValueError, lambda: GrayCode(2, rank=2.5)) + raises(ValueError, lambda: get_subset_from_bitstring(['c', 'a', 'c'], '1100')) + raises(ValueError, lambda: list(GrayCode(3).generate_gray(start="1111"))) + + +def test_live_issue_117(): + assert bin_to_gray('0100') == '0110' + assert bin_to_gray('0101') == '0111' + for bits in ('0100', '0101'): + assert gray_to_bin(bin_to_gray(bits)) == bits diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_constructs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_constructs.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f7d6394bbc2e285650ea95d36be8e2ed5ea69e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_constructs.py @@ -0,0 +1,15 @@ +from sympy.combinatorics.group_constructs import DirectProduct +from sympy.combinatorics.named_groups import CyclicGroup, DihedralGroup + + +def test_direct_product_n(): + C = CyclicGroup(4) + D = DihedralGroup(4) + G = DirectProduct(C, C, C) + assert G.order() == 64 + assert G.degree == 12 + assert len(G.orbits()) == 3 + assert G.is_abelian is True + H = DirectProduct(D, C) + assert H.order() == 32 + assert H.is_abelian is False diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_numbers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..743f1dcc8b642c19706687eeeddf6c9070b59166 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_numbers.py @@ -0,0 +1,110 @@ +from sympy.combinatorics.group_numbers import (is_nilpotent_number, + is_abelian_number, is_cyclic_number, _holder_formula, groups_count) +from sympy.ntheory.factor_ import factorint +from sympy.ntheory.generate import prime +from sympy.testing.pytest import raises +from sympy import randprime + + +def test_is_nilpotent_number(): + assert is_nilpotent_number(21) == False + assert is_nilpotent_number(randprime(1, 30)**12) == True + raises(ValueError, lambda: is_nilpotent_number(-5)) + + A056867 = [1, 2, 3, 4, 5, 7, 8, 9, 11, 13, 15, 16, 17, 19, + 23, 25, 27, 29, 31, 32, 33, 35, 37, 41, 43, 45, + 47, 49, 51, 53, 59, 61, 64, 65, 67, 69, 71, 73, + 77, 79, 81, 83, 85, 87, 89, 91, 95, 97, 99] + for n in range(1, 100): + assert is_nilpotent_number(n) == (n in A056867) + + +def test_is_abelian_number(): + assert is_abelian_number(4) == True + assert is_abelian_number(randprime(1, 2000)**2) == True + assert is_abelian_number(randprime(1000, 100000)) == True + assert is_abelian_number(60) == False + assert is_abelian_number(24) == False + raises(ValueError, lambda: is_abelian_number(-5)) + + A051532 = [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 23, 25, + 29, 31, 33, 35, 37, 41, 43, 45, 47, 49, 51, 53, + 59, 61, 65, 67, 69, 71, 73, 77, 79, 83, 85, 87, + 89, 91, 95, 97, 99] + for n in range(1, 100): + assert is_abelian_number(n) == (n in A051532) + + +A003277 = [1, 2, 3, 5, 7, 11, 13, 15, 17, 19, 23, 29, + 31, 33, 35, 37, 41, 43, 47, 51, 53, 59, 61, + 65, 67, 69, 71, 73, 77, 79, 83, 85, 87, 89, + 91, 95, 97] + + +def test_is_cyclic_number(): + assert is_cyclic_number(15) == True + assert is_cyclic_number(randprime(1, 2000)**2) == False + assert is_cyclic_number(randprime(1000, 100000)) == True + assert is_cyclic_number(4) == False + raises(ValueError, lambda: is_cyclic_number(-5)) + + for n in range(1, 100): + assert is_cyclic_number(n) == (n in A003277) + + +def test_holder_formula(): + # semiprime + assert _holder_formula({3, 5}) == 1 + assert _holder_formula({5, 11}) == 2 + # n in A003277 is always 1 + for n in A003277: + assert _holder_formula(set(factorint(n).keys())) == 1 + # otherwise + assert _holder_formula({2, 3, 5, 7}) == 12 + + +def test_groups_count(): + A000001 = [0, 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, + 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, + 5, 4, 1, 4, 1, 51, 1, 2, 1, 14, 1, 2, 2, + 14, 1, 6, 1, 4, 2, 2, 1, 52, 2, 5, 1, 5, + 1, 15, 2, 13, 2, 2, 1, 13, 1, 2, 4, 267, + 1, 4, 1, 5, 1, 4, 1, 50, 1, 2, 3, 4, 1, + 6, 1, 52, 15, 2, 1, 15, 1, 2, 1, 12, 1, + 10, 1, 4, 2] + for n in range(1, len(A000001)): + try: + assert groups_count(n) == A000001[n] + except ValueError: + pass + + A000679 = [1, 1, 2, 5, 14, 51, 267, 2328, 56092, 10494213, 49487367289] + for e in range(1, len(A000679)): + assert groups_count(2**e) == A000679[e] + + A090091 = [1, 1, 2, 5, 15, 67, 504, 9310, 1396077, 5937876645] + for e in range(1, len(A090091)): + assert groups_count(3**e) == A090091[e] + + A090130 = [1, 1, 2, 5, 15, 77, 684, 34297] + for e in range(1, len(A090130)): + assert groups_count(5**e) == A090130[e] + + A090140 = [1, 1, 2, 5, 15, 83, 860, 113147] + for e in range(1, len(A090140)): + assert groups_count(7**e) == A090140[e] + + A232105 = [51, 67, 77, 83, 87, 97, 101, 107, 111, 125, 131, + 145, 149, 155, 159, 173, 183, 193, 203, 207, 217] + for i in range(len(A232105)): + assert groups_count(prime(i+1)**5) == A232105[i] + + A232106 = [267, 504, 684, 860, 1192, 1476, 1944, 2264, 2876, + 4068, 4540, 6012, 7064, 7664, 8852, 10908, 13136] + for i in range(len(A232106)): + assert groups_count(prime(i+1)**6) == A232106[i] + + A232107 = [2328, 9310, 34297, 113147, 750735, 1600573, + 5546909, 9380741, 23316851, 71271069, 98488755] + for i in range(len(A232107)): + assert groups_count(prime(i+1)**7) == A232107[i] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_homomorphisms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_homomorphisms.py new file mode 100644 index 0000000000000000000000000000000000000000..0936bbddf46a16dccdfbaebda8d1c675c131f05a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_homomorphisms.py @@ -0,0 +1,114 @@ +from sympy.combinatorics import Permutation +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.combinatorics.homomorphisms import homomorphism, group_isomorphism, is_isomorphic +from sympy.combinatorics.free_groups import free_group +from sympy.combinatorics.fp_groups import FpGroup +from sympy.combinatorics.named_groups import AlternatingGroup, DihedralGroup, CyclicGroup +from sympy.testing.pytest import raises + +def test_homomorphism(): + # FpGroup -> PermutationGroup + F, a, b = free_group("a, b") + G = FpGroup(F, [a**3, b**3, (a*b)**2]) + + c = Permutation(3)(0, 1, 2) + d = Permutation(3)(1, 2, 3) + A = AlternatingGroup(4) + T = homomorphism(G, A, [a, b], [c, d]) + assert T(a*b**2*a**-1) == c*d**2*c**-1 + assert T.is_isomorphism() + assert T(T.invert(Permutation(3)(0, 2, 3))) == Permutation(3)(0, 2, 3) + + T = homomorphism(G, AlternatingGroup(4), G.generators) + assert T.is_trivial() + assert T.kernel().order() == G.order() + + E, e = free_group("e") + G = FpGroup(E, [e**8]) + P = PermutationGroup([Permutation(0, 1, 2, 3), Permutation(0, 2)]) + T = homomorphism(G, P, [e], [Permutation(0, 1, 2, 3)]) + assert T.image().order() == 4 + assert T(T.invert(Permutation(0, 2)(1, 3))) == Permutation(0, 2)(1, 3) + + T = homomorphism(E, AlternatingGroup(4), E.generators, [c]) + assert T.invert(c**2) == e**-1 #order(c) == 3 so c**2 == c**-1 + + # FreeGroup -> FreeGroup + T = homomorphism(F, E, [a], [e]) + assert T(a**-2*b**4*a**2).is_identity + + # FreeGroup -> FpGroup + G = FpGroup(F, [a*b*a**-1*b**-1]) + T = homomorphism(F, G, F.generators, G.generators) + assert T.invert(a**-1*b**-1*a**2) == a*b**-1 + + # PermutationGroup -> PermutationGroup + D = DihedralGroup(8) + p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) + P = PermutationGroup(p) + T = homomorphism(P, D, [p], [p]) + assert T.is_injective() + assert not T.is_isomorphism() + assert T.invert(p**3) == p**3 + + T2 = homomorphism(F, P, [F.generators[0]], P.generators) + T = T.compose(T2) + assert T.domain == F + assert T.codomain == D + assert T(a*b) == p + + D3 = DihedralGroup(3) + T = homomorphism(D3, D3, D3.generators, D3.generators) + assert T.is_isomorphism() + + +def test_isomorphisms(): + + F, a, b = free_group("a, b") + E, c, d = free_group("c, d") + # Infinite groups with differently ordered relators. + G = FpGroup(F, [a**2, b**3]) + H = FpGroup(F, [b**3, a**2]) + assert is_isomorphic(G, H) + + # Trivial Case + # FpGroup -> FpGroup + H = FpGroup(F, [a**3, b**3, (a*b)**2]) + F, c, d = free_group("c, d") + G = FpGroup(F, [c**3, d**3, (c*d)**2]) + check, T = group_isomorphism(G, H) + assert check + assert T(c**3*d**2) == a**3*b**2 + + # FpGroup -> PermutationGroup + # FpGroup is converted to the equivalent isomorphic group. + F, a, b = free_group("a, b") + G = FpGroup(F, [a**3, b**3, (a*b)**2]) + H = AlternatingGroup(4) + check, T = group_isomorphism(G, H) + assert check + assert T(b*a*b**-1*a**-1*b**-1) == Permutation(0, 2, 3) + assert T(b*a*b*a**-1*b**-1) == Permutation(0, 3, 2) + + # PermutationGroup -> PermutationGroup + D = DihedralGroup(8) + p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) + P = PermutationGroup(p) + assert not is_isomorphic(D, P) + + A = CyclicGroup(5) + B = CyclicGroup(7) + assert not is_isomorphic(A, B) + + # Two groups of the same prime order are isomorphic to each other. + G = FpGroup(F, [a, b**5]) + H = CyclicGroup(5) + assert G.order() == H.order() + assert is_isomorphic(G, H) + + +def test_check_homomorphism(): + a = Permutation(1,2,3,4) + b = Permutation(1,3) + G = PermutationGroup([a, b]) + raises(ValueError, lambda: homomorphism(G, G, [a], [a])) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_named_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_named_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..59bcb6ef3f020335de76d7a72152a0b58cbc6976 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_named_groups.py @@ -0,0 +1,70 @@ +from sympy.combinatorics.named_groups import (SymmetricGroup, CyclicGroup, + DihedralGroup, AlternatingGroup, + AbelianGroup, RubikGroup) +from sympy.testing.pytest import raises + + +def test_SymmetricGroup(): + G = SymmetricGroup(5) + elements = list(G.generate()) + assert (G.generators[0]).size == 5 + assert len(elements) == 120 + assert G.is_solvable is False + assert G.is_abelian is False + assert G.is_nilpotent is False + assert G.is_transitive() is True + H = SymmetricGroup(1) + assert H.order() == 1 + L = SymmetricGroup(2) + assert L.order() == 2 + + +def test_CyclicGroup(): + G = CyclicGroup(10) + elements = list(G.generate()) + assert len(elements) == 10 + assert (G.derived_subgroup()).order() == 1 + assert G.is_abelian is True + assert G.is_solvable is True + assert G.is_nilpotent is True + H = CyclicGroup(1) + assert H.order() == 1 + L = CyclicGroup(2) + assert L.order() == 2 + + +def test_DihedralGroup(): + G = DihedralGroup(6) + elements = list(G.generate()) + assert len(elements) == 12 + assert G.is_transitive() is True + assert G.is_abelian is False + assert G.is_solvable is True + assert G.is_nilpotent is False + H = DihedralGroup(1) + assert H.order() == 2 + L = DihedralGroup(2) + assert L.order() == 4 + assert L.is_abelian is True + assert L.is_nilpotent is True + + +def test_AlternatingGroup(): + G = AlternatingGroup(5) + elements = list(G.generate()) + assert len(elements) == 60 + assert [perm.is_even for perm in elements] == [True]*60 + H = AlternatingGroup(1) + assert H.order() == 1 + L = AlternatingGroup(2) + assert L.order() == 1 + + +def test_AbelianGroup(): + A = AbelianGroup(3, 3, 3) + assert A.order() == 27 + assert A.is_abelian is True + + +def test_RubikGroup(): + raises(ValueError, lambda: RubikGroup(1)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_partitions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_partitions.py new file mode 100644 index 0000000000000000000000000000000000000000..32e70e53a53aadbb17c8292bbef8f52d1144d6e0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_partitions.py @@ -0,0 +1,118 @@ +from sympy.core.sorting import ordered, default_sort_key +from sympy.combinatorics.partitions import (Partition, IntegerPartition, + RGS_enum, RGS_unrank, RGS_rank, + random_integer_partition) +from sympy.testing.pytest import raises +from sympy.utilities.iterables import partitions +from sympy.sets.sets import Set, FiniteSet + + +def test_partition_constructor(): + raises(ValueError, lambda: Partition([1, 1, 2])) + raises(ValueError, lambda: Partition([1, 2, 3], [2, 3, 4])) + raises(ValueError, lambda: Partition(1, 2, 3)) + raises(ValueError, lambda: Partition(*list(range(3)))) + + assert Partition([1, 2, 3], [4, 5]) == Partition([4, 5], [1, 2, 3]) + assert Partition({1, 2, 3}, {4, 5}) == Partition([1, 2, 3], [4, 5]) + + a = FiniteSet(1, 2, 3) + b = FiniteSet(4, 5) + assert Partition(a, b) == Partition([1, 2, 3], [4, 5]) + assert Partition({a, b}) == Partition(FiniteSet(a, b)) + assert Partition({a, b}) != Partition(a, b) + +def test_partition(): + from sympy.abc import x + + a = Partition([1, 2, 3], [4]) + b = Partition([1, 2], [3, 4]) + c = Partition([x]) + l = [a, b, c] + l.sort(key=default_sort_key) + assert l == [c, a, b] + l.sort(key=lambda w: default_sort_key(w, order='rev-lex')) + assert l == [c, a, b] + + assert (a == b) is False + assert a <= b + assert (a > b) is False + assert a != b + assert a < b + + assert (a + 2).partition == [[1, 2], [3, 4]] + assert (b - 1).partition == [[1, 2, 4], [3]] + + assert (a - 1).partition == [[1, 2, 3, 4]] + assert (a + 1).partition == [[1, 2, 4], [3]] + assert (b + 1).partition == [[1, 2], [3], [4]] + + assert a.rank == 1 + assert b.rank == 3 + + assert a.RGS == (0, 0, 0, 1) + assert b.RGS == (0, 0, 1, 1) + + +def test_integer_partition(): + # no zeros in partition + raises(ValueError, lambda: IntegerPartition(list(range(3)))) + # check fails since 1 + 2 != 100 + raises(ValueError, lambda: IntegerPartition(100, list(range(1, 3)))) + a = IntegerPartition(8, [1, 3, 4]) + b = a.next_lex() + c = IntegerPartition([1, 3, 4]) + d = IntegerPartition(8, {1: 3, 3: 1, 2: 1}) + assert a == c + assert a.integer == d.integer + assert a.conjugate == [3, 2, 2, 1] + assert (a == b) is False + assert a <= b + assert (a > b) is False + assert a != b + + for i in range(1, 11): + next = set() + prev = set() + a = IntegerPartition([i]) + ans = {IntegerPartition(p) for p in partitions(i)} + n = len(ans) + for j in range(n): + next.add(a) + a = a.next_lex() + IntegerPartition(i, a.partition) # check it by giving i + for j in range(n): + prev.add(a) + a = a.prev_lex() + IntegerPartition(i, a.partition) # check it by giving i + assert next == ans + assert prev == ans + + assert IntegerPartition([1, 2, 3]).as_ferrers() == '###\n##\n#' + assert IntegerPartition([1, 1, 3]).as_ferrers('o') == 'ooo\no\no' + assert str(IntegerPartition([1, 1, 3])) == '[3, 1, 1]' + assert IntegerPartition([1, 1, 3]).partition == [3, 1, 1] + + raises(ValueError, lambda: random_integer_partition(-1)) + assert random_integer_partition(1) == [1] + assert random_integer_partition(10, seed=[1, 3, 2, 1, 5, 1] + ) == [5, 2, 1, 1, 1] + + +def test_rgs(): + raises(ValueError, lambda: RGS_unrank(-1, 3)) + raises(ValueError, lambda: RGS_unrank(3, 0)) + raises(ValueError, lambda: RGS_unrank(10, 1)) + + raises(ValueError, lambda: Partition.from_rgs(list(range(3)), list(range(2)))) + raises(ValueError, lambda: Partition.from_rgs(list(range(1, 3)), list(range(2)))) + assert RGS_enum(-1) == 0 + assert RGS_enum(1) == 1 + assert RGS_unrank(7, 5) == [0, 0, 1, 0, 2] + assert RGS_unrank(23, 14) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2] + assert RGS_rank(RGS_unrank(40, 100)) == 40 + +def test_ordered_partition_9608(): + a = Partition([1, 2, 3], [4]) + b = Partition([1, 2], [3, 4]) + assert list(ordered([a,b], Set._infimum_key)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_pc_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_pc_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..b0c146279921e1e6499534fe9e33b993348d1503 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_pc_groups.py @@ -0,0 +1,87 @@ +from sympy.combinatorics.permutations import Permutation +from sympy.combinatorics.named_groups import SymmetricGroup, AlternatingGroup, DihedralGroup +from sympy.matrices import Matrix + +def test_pc_presentation(): + Groups = [SymmetricGroup(3), SymmetricGroup(4), SymmetricGroup(9).sylow_subgroup(3), + SymmetricGroup(9).sylow_subgroup(2), SymmetricGroup(8).sylow_subgroup(2), DihedralGroup(10)] + + S = SymmetricGroup(125).sylow_subgroup(5) + G = S.derived_series()[2] + Groups.append(G) + + G = SymmetricGroup(25).sylow_subgroup(5) + Groups.append(G) + + S = SymmetricGroup(11**2).sylow_subgroup(11) + G = S.derived_series()[2] + Groups.append(G) + + for G in Groups: + PcGroup = G.polycyclic_group() + collector = PcGroup.collector + pc_presentation = collector.pc_presentation + + pcgs = PcGroup.pcgs + free_group = collector.free_group + free_to_perm = {} + for s, g in zip(free_group.symbols, pcgs): + free_to_perm[s] = g + + for k, v in pc_presentation.items(): + k_array = k.array_form + if v != (): + v_array = v.array_form + + lhs = Permutation() + for gen in k_array: + s = gen[0] + e = gen[1] + lhs = lhs*free_to_perm[s]**e + + if v == (): + assert lhs.is_identity + continue + + rhs = Permutation() + for gen in v_array: + s = gen[0] + e = gen[1] + rhs = rhs*free_to_perm[s]**e + + assert lhs == rhs + + +def test_exponent_vector(): + + Groups = [SymmetricGroup(3), SymmetricGroup(4), SymmetricGroup(9).sylow_subgroup(3), + SymmetricGroup(9).sylow_subgroup(2), SymmetricGroup(8).sylow_subgroup(2)] + + for G in Groups: + PcGroup = G.polycyclic_group() + collector = PcGroup.collector + + pcgs = PcGroup.pcgs + # free_group = collector.free_group + + for gen in G.generators: + exp = collector.exponent_vector(gen) + g = Permutation() + for i in range(len(exp)): + g = g*pcgs[i]**exp[i] if exp[i] else g + assert g == gen + + +def test_induced_pcgs(): + G = [SymmetricGroup(9).sylow_subgroup(3), SymmetricGroup(20).sylow_subgroup(2), AlternatingGroup(4), + DihedralGroup(4), DihedralGroup(10), DihedralGroup(9), SymmetricGroup(3), SymmetricGroup(4)] + + for g in G: + PcGroup = g.polycyclic_group() + collector = PcGroup.collector + gens = list(g.generators) + ipcgs = collector.induced_pcgs(gens) + m = [] + for i in ipcgs: + m.append(collector.exponent_vector(i)) + assert Matrix(m).is_upper diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_perm_groups.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_perm_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..763b8fb0ae357500d68c29fe1c9e6b156e224949 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_perm_groups.py @@ -0,0 +1,1243 @@ +from sympy.core.containers import Tuple +from sympy.combinatorics.generators import rubik_cube_generators +from sympy.combinatorics.homomorphisms import is_isomorphic +from sympy.combinatorics.named_groups import SymmetricGroup, CyclicGroup,\ + DihedralGroup, AlternatingGroup, AbelianGroup, RubikGroup +from sympy.combinatorics.perm_groups import (PermutationGroup, + _orbit_transversal, Coset, SymmetricPermutationGroup) +from sympy.combinatorics.permutations import Permutation +from sympy.combinatorics.polyhedron import tetrahedron as Tetra, cube +from sympy.combinatorics.testutil import _verify_bsgs, _verify_centralizer,\ + _verify_normal_closure +from sympy.testing.pytest import skip, XFAIL, slow + +rmul = Permutation.rmul + + +def test_has(): + a = Permutation([1, 0]) + G = PermutationGroup([a]) + assert G.is_abelian + a = Permutation([2, 0, 1]) + b = Permutation([2, 1, 0]) + G = PermutationGroup([a, b]) + assert not G.is_abelian + + G = PermutationGroup([a]) + assert G.has(a) + assert not G.has(b) + + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([0, 2, 1, 3, 4]) + assert PermutationGroup(a, b).degree == \ + PermutationGroup(a, b).degree == 6 + + g = PermutationGroup(Permutation(0, 2, 1)) + assert Tuple(1, g).has(g) + + +def test_generate(): + a = Permutation([1, 0]) + g = list(PermutationGroup([a]).generate()) + assert g == [Permutation([0, 1]), Permutation([1, 0])] + assert len(list(PermutationGroup(Permutation((0, 1))).generate())) == 1 + g = PermutationGroup([a]).generate(method='dimino') + assert list(g) == [Permutation([0, 1]), Permutation([1, 0])] + a = Permutation([2, 0, 1]) + b = Permutation([2, 1, 0]) + G = PermutationGroup([a, b]) + g = G.generate() + v1 = [p.array_form for p in list(g)] + v1.sort() + assert v1 == [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, + 1], [2, 1, 0]] + v2 = list(G.generate(method='dimino', af=True)) + assert v1 == sorted(v2) + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([2, 1, 3, 4, 5, 0]) + g = PermutationGroup([a, b]).generate(af=True) + assert len(list(g)) == 360 + + +def test_order(): + a = Permutation([2, 0, 1, 3, 4, 5, 6, 7, 8, 9]) + b = Permutation([2, 1, 3, 4, 5, 6, 7, 8, 9, 0]) + g = PermutationGroup([a, b]) + assert g.order() == 1814400 + assert PermutationGroup().order() == 1 + + +def test_equality(): + p_1 = Permutation(0, 1, 3) + p_2 = Permutation(0, 2, 3) + p_3 = Permutation(0, 1, 2) + p_4 = Permutation(0, 1, 3) + g_1 = PermutationGroup(p_1, p_2) + g_2 = PermutationGroup(p_3, p_4) + g_3 = PermutationGroup(p_2, p_1) + g_4 = PermutationGroup(p_1, p_2) + + assert g_1 != g_2 + assert g_1.generators != g_2.generators + assert g_1.equals(g_2) + assert g_1 != g_3 + assert g_1.equals(g_3) + assert g_1 == g_4 + + +def test_stabilizer(): + S = SymmetricGroup(2) + H = S.stabilizer(0) + assert H.generators == [Permutation(1)] + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([2, 1, 3, 4, 5, 0]) + G = PermutationGroup([a, b]) + G0 = G.stabilizer(0) + assert G0.order() == 60 + + gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] + gens = [Permutation(p) for p in gens_cube] + G = PermutationGroup(gens) + G2 = G.stabilizer(2) + assert G2.order() == 6 + G2_1 = G2.stabilizer(1) + v = list(G2_1.generate(af=True)) + assert v == [[0, 1, 2, 3, 4, 5, 6, 7], [3, 1, 2, 0, 7, 5, 6, 4]] + + gens = ( + (1, 2, 0, 4, 5, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), + (0, 1, 2, 3, 4, 5, 19, 6, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 7, 17, 18), + (0, 1, 2, 3, 4, 5, 6, 7, 9, 18, 16, 11, 12, 13, 14, 15, 8, 17, 10, 19)) + gens = [Permutation(p) for p in gens] + G = PermutationGroup(gens) + G2 = G.stabilizer(2) + assert G2.order() == 181440 + S = SymmetricGroup(3) + assert [G.order() for G in S.basic_stabilizers] == [6, 2] + + +def test_center(): + # the center of the dihedral group D_n is of order 2 for even n + for i in (4, 6, 10): + D = DihedralGroup(i) + assert (D.center()).order() == 2 + # the center of the dihedral group D_n is of order 1 for odd n>2 + for i in (3, 5, 7): + D = DihedralGroup(i) + assert (D.center()).order() == 1 + # the center of an abelian group is the group itself + for i in (2, 3, 5): + for j in (1, 5, 7): + for k in (1, 1, 11): + G = AbelianGroup(i, j, k) + assert G.center().is_subgroup(G) + # the center of a nonabelian simple group is trivial + for i in(1, 5, 9): + A = AlternatingGroup(i) + assert (A.center()).order() == 1 + # brute-force verifications + D = DihedralGroup(5) + A = AlternatingGroup(3) + C = CyclicGroup(4) + G.is_subgroup(D*A*C) + assert _verify_centralizer(G, G) + + +def test_centralizer(): + # the centralizer of the trivial group is the entire group + S = SymmetricGroup(2) + assert S.centralizer(Permutation(list(range(2)))).is_subgroup(S) + A = AlternatingGroup(5) + assert A.centralizer(Permutation(list(range(5)))).is_subgroup(A) + # a centralizer in the trivial group is the trivial group itself + triv = PermutationGroup([Permutation([0, 1, 2, 3])]) + D = DihedralGroup(4) + assert triv.centralizer(D).is_subgroup(triv) + # brute-force verifications for centralizers of groups + for i in (4, 5, 6): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + C = CyclicGroup(i) + D = DihedralGroup(i) + for gp in (S, A, C, D): + for gp2 in (S, A, C, D): + if not gp2.is_subgroup(gp): + assert _verify_centralizer(gp, gp2) + # verify the centralizer for all elements of several groups + S = SymmetricGroup(5) + elements = list(S.generate_dimino()) + for element in elements: + assert _verify_centralizer(S, element) + A = AlternatingGroup(5) + elements = list(A.generate_dimino()) + for element in elements: + assert _verify_centralizer(A, element) + D = DihedralGroup(7) + elements = list(D.generate_dimino()) + for element in elements: + assert _verify_centralizer(D, element) + # verify centralizers of small groups within small groups + small = [] + for i in (1, 2, 3): + small.append(SymmetricGroup(i)) + small.append(AlternatingGroup(i)) + small.append(DihedralGroup(i)) + small.append(CyclicGroup(i)) + for gp in small: + for gp2 in small: + if gp.degree == gp2.degree: + assert _verify_centralizer(gp, gp2) + + +def test_coset_rank(): + gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] + gens = [Permutation(p) for p in gens_cube] + G = PermutationGroup(gens) + i = 0 + for h in G.generate(af=True): + rk = G.coset_rank(h) + assert rk == i + h1 = G.coset_unrank(rk, af=True) + assert h == h1 + i += 1 + assert G.coset_unrank(48) is None + assert G.coset_unrank(G.coset_rank(gens[0])) == gens[0] + + +def test_coset_factor(): + a = Permutation([0, 2, 1]) + G = PermutationGroup([a]) + c = Permutation([2, 1, 0]) + assert not G.coset_factor(c) + assert G.coset_rank(c) is None + + a = Permutation([2, 0, 1, 3, 4, 5]) + b = Permutation([2, 1, 3, 4, 5, 0]) + g = PermutationGroup([a, b]) + assert g.order() == 360 + d = Permutation([1, 0, 2, 3, 4, 5]) + assert not g.coset_factor(d.array_form) + assert not g.contains(d) + assert Permutation(2) in G + c = Permutation([1, 0, 2, 3, 5, 4]) + v = g.coset_factor(c, True) + tr = g.basic_transversals + p = Permutation.rmul(*[tr[i][v[i]] for i in range(len(g.base))]) + assert p == c + v = g.coset_factor(c) + p = Permutation.rmul(*v) + assert p == c + assert g.contains(c) + G = PermutationGroup([Permutation([2, 1, 0])]) + p = Permutation([1, 0, 2]) + assert G.coset_factor(p) == [] + + +def test_orbits(): + a = Permutation([2, 0, 1]) + b = Permutation([2, 1, 0]) + g = PermutationGroup([a, b]) + assert g.orbit(0) == {0, 1, 2} + assert g.orbits() == [{0, 1, 2}] + assert g.is_transitive() and g.is_transitive(strict=False) + assert g.orbit_transversal(0) == \ + [Permutation( + [0, 1, 2]), Permutation([2, 0, 1]), Permutation([1, 2, 0])] + assert g.orbit_transversal(0, True) == \ + [(0, Permutation([0, 1, 2])), (2, Permutation([2, 0, 1])), + (1, Permutation([1, 2, 0]))] + + G = DihedralGroup(6) + transversal, slps = _orbit_transversal(G.degree, G.generators, 0, True, slp=True) + for i, t in transversal: + slp = slps[i] + w = G.identity + for s in slp: + w = G.generators[s]*w + assert w == t + + a = Permutation(list(range(1, 100)) + [0]) + G = PermutationGroup([a]) + assert [min(o) for o in G.orbits()] == [0] + G = PermutationGroup(rubik_cube_generators()) + assert [min(o) for o in G.orbits()] == [0, 1] + assert not G.is_transitive() and not G.is_transitive(strict=False) + G = PermutationGroup([Permutation(0, 1, 3), Permutation(3)(0, 1)]) + assert not G.is_transitive() and G.is_transitive(strict=False) + assert PermutationGroup( + Permutation(3)).is_transitive(strict=False) is False + + +def test_is_normal(): + gens_s5 = [Permutation(p) for p in [[1, 2, 3, 4, 0], [2, 1, 4, 0, 3]]] + G1 = PermutationGroup(gens_s5) + assert G1.order() == 120 + gens_a5 = [Permutation(p) for p in [[1, 0, 3, 2, 4], [2, 1, 4, 3, 0]]] + G2 = PermutationGroup(gens_a5) + assert G2.order() == 60 + assert G2.is_normal(G1) + gens3 = [Permutation(p) for p in [[2, 1, 3, 0, 4], [1, 2, 0, 3, 4]]] + G3 = PermutationGroup(gens3) + assert not G3.is_normal(G1) + assert G3.order() == 12 + G4 = G1.normal_closure(G3.generators) + assert G4.order() == 60 + gens5 = [Permutation(p) for p in [[1, 2, 3, 0, 4], [1, 2, 0, 3, 4]]] + G5 = PermutationGroup(gens5) + assert G5.order() == 24 + G6 = G1.normal_closure(G5.generators) + assert G6.order() == 120 + assert G1.is_subgroup(G6) + assert not G1.is_subgroup(G4) + assert G2.is_subgroup(G4) + I5 = PermutationGroup(Permutation(4)) + assert I5.is_normal(G5) + assert I5.is_normal(G6, strict=False) + p1 = Permutation([1, 0, 2, 3, 4]) + p2 = Permutation([0, 1, 2, 4, 3]) + p3 = Permutation([3, 4, 2, 1, 0]) + id_ = Permutation([0, 1, 2, 3, 4]) + H = PermutationGroup([p1, p3]) + H_n1 = PermutationGroup([p1, p2]) + H_n2_1 = PermutationGroup(p1) + H_n2_2 = PermutationGroup(p2) + H_id = PermutationGroup(id_) + assert H_n1.is_normal(H) + assert H_n2_1.is_normal(H_n1) + assert H_n2_2.is_normal(H_n1) + assert H_id.is_normal(H_n2_1) + assert H_id.is_normal(H_n1) + assert H_id.is_normal(H) + assert not H_n2_1.is_normal(H) + assert not H_n2_2.is_normal(H) + + +def test_eq(): + a = [[1, 2, 0, 3, 4, 5], [1, 0, 2, 3, 4, 5], [2, 1, 0, 3, 4, 5], [ + 1, 2, 0, 3, 4, 5]] + a = [Permutation(p) for p in a + [[1, 2, 3, 4, 5, 0]]] + g = Permutation([1, 2, 3, 4, 5, 0]) + G1, G2, G3 = [PermutationGroup(x) for x in [a[:2], a[2:4], [g, g**2]]] + assert G1.order() == G2.order() == G3.order() == 6 + assert G1.is_subgroup(G2) + assert not G1.is_subgroup(G3) + G4 = PermutationGroup([Permutation([0, 1])]) + assert not G1.is_subgroup(G4) + assert G4.is_subgroup(G1, 0) + assert PermutationGroup(g, g).is_subgroup(PermutationGroup(g)) + assert SymmetricGroup(3).is_subgroup(SymmetricGroup(4), 0) + assert SymmetricGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) + assert not CyclicGroup(5).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) + assert CyclicGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) + + +def test_derived_subgroup(): + a = Permutation([1, 0, 2, 4, 3]) + b = Permutation([0, 1, 3, 2, 4]) + G = PermutationGroup([a, b]) + C = G.derived_subgroup() + assert C.order() == 3 + assert C.is_normal(G) + assert C.is_subgroup(G, 0) + assert not G.is_subgroup(C, 0) + gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] + gens = [Permutation(p) for p in gens_cube] + G = PermutationGroup(gens) + C = G.derived_subgroup() + assert C.order() == 12 + + +def test_is_solvable(): + a = Permutation([1, 2, 0]) + b = Permutation([1, 0, 2]) + G = PermutationGroup([a, b]) + assert G.is_solvable + G = PermutationGroup([a]) + assert G.is_solvable + a = Permutation([1, 2, 3, 4, 0]) + b = Permutation([1, 0, 2, 3, 4]) + G = PermutationGroup([a, b]) + assert not G.is_solvable + P = SymmetricGroup(10) + S = P.sylow_subgroup(3) + assert S.is_solvable + +def test_rubik1(): + gens = rubik_cube_generators() + gens1 = [gens[-1]] + [p**2 for p in gens[1:]] + G1 = PermutationGroup(gens1) + assert G1.order() == 19508428800 + gens2 = [p**2 for p in gens] + G2 = PermutationGroup(gens2) + assert G2.order() == 663552 + assert G2.is_subgroup(G1, 0) + C1 = G1.derived_subgroup() + assert C1.order() == 4877107200 + assert C1.is_subgroup(G1, 0) + assert not G2.is_subgroup(C1, 0) + + G = RubikGroup(2) + assert G.order() == 3674160 + + +@XFAIL +def test_rubik(): + skip('takes too much time') + G = PermutationGroup(rubik_cube_generators()) + assert G.order() == 43252003274489856000 + G1 = PermutationGroup(G[:3]) + assert G1.order() == 170659735142400 + assert not G1.is_normal(G) + G2 = G.normal_closure(G1.generators) + assert G2.is_subgroup(G) + + +def test_direct_product(): + C = CyclicGroup(4) + D = DihedralGroup(4) + G = C*C*C + assert G.order() == 64 + assert G.degree == 12 + assert len(G.orbits()) == 3 + assert G.is_abelian is True + H = D*C + assert H.order() == 32 + assert H.is_abelian is False + + +def test_orbit_rep(): + G = DihedralGroup(6) + assert G.orbit_rep(1, 3) in [Permutation([2, 3, 4, 5, 0, 1]), + Permutation([4, 3, 2, 1, 0, 5])] + H = CyclicGroup(4)*G + assert H.orbit_rep(1, 5) is False + + +def test_schreier_vector(): + G = CyclicGroup(50) + v = [0]*50 + v[23] = -1 + assert G.schreier_vector(23) == v + H = DihedralGroup(8) + assert H.schreier_vector(2) == [0, 1, -1, 0, 0, 1, 0, 0] + L = SymmetricGroup(4) + assert L.schreier_vector(1) == [1, -1, 0, 0] + + +def test_random_pr(): + D = DihedralGroup(6) + r = 11 + n = 3 + _random_prec_n = {} + _random_prec_n[0] = {'s': 7, 't': 3, 'x': 2, 'e': -1} + _random_prec_n[1] = {'s': 5, 't': 5, 'x': 1, 'e': -1} + _random_prec_n[2] = {'s': 3, 't': 4, 'x': 2, 'e': 1} + D._random_pr_init(r, n, _random_prec_n=_random_prec_n) + assert D._random_gens[11] == [0, 1, 2, 3, 4, 5] + _random_prec = {'s': 2, 't': 9, 'x': 1, 'e': -1} + assert D.random_pr(_random_prec=_random_prec) == \ + Permutation([0, 5, 4, 3, 2, 1]) + + +def test_is_alt_sym(): + G = DihedralGroup(10) + assert G.is_alt_sym() is False + assert G._eval_is_alt_sym_naive() is False + assert G._eval_is_alt_sym_naive(only_alt=True) is False + assert G._eval_is_alt_sym_naive(only_sym=True) is False + + S = SymmetricGroup(10) + assert S._eval_is_alt_sym_naive() is True + assert S._eval_is_alt_sym_naive(only_alt=True) is False + assert S._eval_is_alt_sym_naive(only_sym=True) is True + + N_eps = 10 + _random_prec = {'N_eps': N_eps, + 0: Permutation([[2], [1, 4], [0, 6, 7, 8, 9, 3, 5]]), + 1: Permutation([[1, 8, 7, 6, 3, 5, 2, 9], [0, 4]]), + 2: Permutation([[5, 8], [4, 7], [0, 1, 2, 3, 6, 9]]), + 3: Permutation([[3], [0, 8, 2, 7, 4, 1, 6, 9, 5]]), + 4: Permutation([[8], [4, 7, 9], [3, 6], [0, 5, 1, 2]]), + 5: Permutation([[6], [0, 2, 4, 5, 1, 8, 3, 9, 7]]), + 6: Permutation([[6, 9, 8], [4, 5], [1, 3, 7], [0, 2]]), + 7: Permutation([[4], [0, 2, 9, 1, 3, 8, 6, 5, 7]]), + 8: Permutation([[1, 5, 6, 3], [0, 2, 7, 8, 4, 9]]), + 9: Permutation([[8], [6, 7], [2, 3, 4, 5], [0, 1, 9]])} + assert S.is_alt_sym(_random_prec=_random_prec) is True + + A = AlternatingGroup(10) + assert A._eval_is_alt_sym_naive() is True + assert A._eval_is_alt_sym_naive(only_alt=True) is True + assert A._eval_is_alt_sym_naive(only_sym=True) is False + + _random_prec = {'N_eps': N_eps, + 0: Permutation([[1, 6, 4, 2, 7, 8, 5, 9, 3], [0]]), + 1: Permutation([[1], [0, 5, 8, 4, 9, 2, 3, 6, 7]]), + 2: Permutation([[1, 9, 8, 3, 2, 5], [0, 6, 7, 4]]), + 3: Permutation([[6, 8, 9], [4, 5], [1, 3, 7, 2], [0]]), + 4: Permutation([[8], [5], [4], [2, 6, 9, 3], [1], [0, 7]]), + 5: Permutation([[3, 6], [0, 8, 1, 7, 5, 9, 4, 2]]), + 6: Permutation([[5], [2, 9], [1, 8, 3], [0, 4, 7, 6]]), + 7: Permutation([[1, 8, 4, 7, 2, 3], [0, 6, 9, 5]]), + 8: Permutation([[5, 8, 7], [3], [1, 4, 2, 6], [0, 9]]), + 9: Permutation([[4, 9, 6], [3, 8], [1, 2], [0, 5, 7]])} + assert A.is_alt_sym(_random_prec=_random_prec) is False + + G = PermutationGroup( + Permutation(1, 3, size=8)(0, 2, 4, 6), + Permutation(5, 7, size=8)(0, 2, 4, 6)) + assert G.is_alt_sym() is False + + # Tests for monte-carlo c_n parameter setting, and which guarantees + # to give False. + G = DihedralGroup(10) + assert G._eval_is_alt_sym_monte_carlo() is False + G = DihedralGroup(20) + assert G._eval_is_alt_sym_monte_carlo() is False + + # A dry-running test to check if it looks up for the updated cache. + G = DihedralGroup(6) + G.is_alt_sym() + assert G.is_alt_sym() is False + + +def test_minimal_block(): + D = DihedralGroup(6) + block_system = D.minimal_block([0, 3]) + for i in range(3): + assert block_system[i] == block_system[i + 3] + S = SymmetricGroup(6) + assert S.minimal_block([0, 1]) == [0, 0, 0, 0, 0, 0] + + assert Tetra.pgroup.minimal_block([0, 1]) == [0, 0, 0, 0] + + P1 = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) + P2 = PermutationGroup(Permutation(0, 1, 2, 3, 4, 5), Permutation(1, 5)(2, 4)) + assert P1.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1] + assert P2.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1] + + +def test_minimal_blocks(): + P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) + assert P.minimal_blocks() == [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]] + + P = SymmetricGroup(5) + assert P.minimal_blocks() == [[0]*5] + + P = PermutationGroup(Permutation(0, 3)) + assert P.minimal_blocks() is False + + +def test_max_div(): + S = SymmetricGroup(10) + assert S.max_div == 5 + + +def test_is_primitive(): + S = SymmetricGroup(5) + assert S.is_primitive() is True + C = CyclicGroup(7) + assert C.is_primitive() is True + + a = Permutation(0, 1, 2, size=6) + b = Permutation(3, 4, 5, size=6) + G = PermutationGroup(a, b) + assert G.is_primitive() is False + + +def test_random_stab(): + S = SymmetricGroup(5) + _random_el = Permutation([1, 3, 2, 0, 4]) + _random_prec = {'rand': _random_el} + g = S.random_stab(2, _random_prec=_random_prec) + assert g == Permutation([1, 3, 2, 0, 4]) + h = S.random_stab(1) + assert h(1) == 1 + + +def test_transitivity_degree(): + perm = Permutation([1, 2, 0]) + C = PermutationGroup([perm]) + assert C.transitivity_degree == 1 + gen1 = Permutation([1, 2, 0, 3, 4]) + gen2 = Permutation([1, 2, 3, 4, 0]) + # alternating group of degree 5 + Alt = PermutationGroup([gen1, gen2]) + assert Alt.transitivity_degree == 3 + + +def test_schreier_sims_random(): + assert sorted(Tetra.pgroup.base) == [0, 1] + + S = SymmetricGroup(3) + base = [0, 1] + strong_gens = [Permutation([1, 2, 0]), Permutation([1, 0, 2]), + Permutation([0, 2, 1])] + assert S.schreier_sims_random(base, strong_gens, 5) == (base, strong_gens) + D = DihedralGroup(3) + _random_prec = {'g': [Permutation([2, 0, 1]), Permutation([1, 2, 0]), + Permutation([1, 0, 2])]} + base = [0, 1] + strong_gens = [Permutation([1, 2, 0]), Permutation([2, 1, 0]), + Permutation([0, 2, 1])] + assert D.schreier_sims_random([], D.generators, 2, + _random_prec=_random_prec) == (base, strong_gens) + + +def test_baseswap(): + S = SymmetricGroup(4) + S.schreier_sims() + base = S.base + strong_gens = S.strong_gens + assert base == [0, 1, 2] + deterministic = S.baseswap(base, strong_gens, 1, randomized=False) + randomized = S.baseswap(base, strong_gens, 1) + assert deterministic[0] == [0, 2, 1] + assert _verify_bsgs(S, deterministic[0], deterministic[1]) is True + assert randomized[0] == [0, 2, 1] + assert _verify_bsgs(S, randomized[0], randomized[1]) is True + + +def test_schreier_sims_incremental(): + identity = Permutation([0, 1, 2, 3, 4]) + TrivialGroup = PermutationGroup([identity]) + base, strong_gens = TrivialGroup.schreier_sims_incremental(base=[0, 1, 2]) + assert _verify_bsgs(TrivialGroup, base, strong_gens) is True + S = SymmetricGroup(5) + base, strong_gens = S.schreier_sims_incremental(base=[0, 1, 2]) + assert _verify_bsgs(S, base, strong_gens) is True + D = DihedralGroup(2) + base, strong_gens = D.schreier_sims_incremental(base=[1]) + assert _verify_bsgs(D, base, strong_gens) is True + A = AlternatingGroup(7) + gens = A.generators[:] + gen0 = gens[0] + gen1 = gens[1] + gen1 = rmul(gen1, ~gen0) + gen0 = rmul(gen0, gen1) + gen1 = rmul(gen0, gen1) + base, strong_gens = A.schreier_sims_incremental(base=[0, 1], gens=gens) + assert _verify_bsgs(A, base, strong_gens) is True + C = CyclicGroup(11) + gen = C.generators[0] + base, strong_gens = C.schreier_sims_incremental(gens=[gen**3]) + assert _verify_bsgs(C, base, strong_gens) is True + + +def _subgroup_search(i, j, k): + prop_true = lambda x: True + prop_fix_points = lambda x: [x(point) for point in points] == points + prop_comm_g = lambda x: rmul(x, g) == rmul(g, x) + prop_even = lambda x: x.is_even + for i in range(i, j, k): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + C = CyclicGroup(i) + Sym = S.subgroup_search(prop_true) + assert Sym.is_subgroup(S) + Alt = S.subgroup_search(prop_even) + assert Alt.is_subgroup(A) + Sym = S.subgroup_search(prop_true, init_subgroup=C) + assert Sym.is_subgroup(S) + points = [7] + assert S.stabilizer(7).is_subgroup(S.subgroup_search(prop_fix_points)) + points = [3, 4] + assert S.stabilizer(3).stabilizer(4).is_subgroup( + S.subgroup_search(prop_fix_points)) + points = [3, 5] + fix35 = A.subgroup_search(prop_fix_points) + points = [5] + fix5 = A.subgroup_search(prop_fix_points) + assert A.subgroup_search(prop_fix_points, init_subgroup=fix35 + ).is_subgroup(fix5) + base, strong_gens = A.schreier_sims_incremental() + g = A.generators[0] + comm_g = \ + A.subgroup_search(prop_comm_g, base=base, strong_gens=strong_gens) + assert _verify_bsgs(comm_g, base, comm_g.generators) is True + assert [prop_comm_g(gen) is True for gen in comm_g.generators] + + +def test_subgroup_search(): + _subgroup_search(10, 15, 2) + + +@XFAIL +def test_subgroup_search2(): + skip('takes too much time') + _subgroup_search(16, 17, 1) + + +def test_normal_closure(): + # the normal closure of the trivial group is trivial + S = SymmetricGroup(3) + identity = Permutation([0, 1, 2]) + closure = S.normal_closure(identity) + assert closure.is_trivial + # the normal closure of the entire group is the entire group + A = AlternatingGroup(4) + assert A.normal_closure(A).is_subgroup(A) + # brute-force verifications for subgroups + for i in (3, 4, 5): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + D = DihedralGroup(i) + C = CyclicGroup(i) + for gp in (A, D, C): + assert _verify_normal_closure(S, gp) + # brute-force verifications for all elements of a group + S = SymmetricGroup(5) + elements = list(S.generate_dimino()) + for element in elements: + assert _verify_normal_closure(S, element) + # small groups + small = [] + for i in (1, 2, 3): + small.append(SymmetricGroup(i)) + small.append(AlternatingGroup(i)) + small.append(DihedralGroup(i)) + small.append(CyclicGroup(i)) + for gp in small: + for gp2 in small: + if gp2.is_subgroup(gp, 0) and gp2.degree == gp.degree: + assert _verify_normal_closure(gp, gp2) + + +def test_derived_series(): + # the derived series of the trivial group consists only of the trivial group + triv = PermutationGroup([Permutation([0, 1, 2])]) + assert triv.derived_series()[0].is_subgroup(triv) + # the derived series for a simple group consists only of the group itself + for i in (5, 6, 7): + A = AlternatingGroup(i) + assert A.derived_series()[0].is_subgroup(A) + # the derived series for S_4 is S_4 > A_4 > K_4 > triv + S = SymmetricGroup(4) + series = S.derived_series() + assert series[1].is_subgroup(AlternatingGroup(4)) + assert series[2].is_subgroup(DihedralGroup(2)) + assert series[3].is_trivial + + +def test_lower_central_series(): + # the lower central series of the trivial group consists of the trivial + # group + triv = PermutationGroup([Permutation([0, 1, 2])]) + assert triv.lower_central_series()[0].is_subgroup(triv) + # the lower central series of a simple group consists of the group itself + for i in (5, 6, 7): + A = AlternatingGroup(i) + assert A.lower_central_series()[0].is_subgroup(A) + # GAP-verified example + S = SymmetricGroup(6) + series = S.lower_central_series() + assert len(series) == 2 + assert series[1].is_subgroup(AlternatingGroup(6)) + + +def test_commutator(): + # the commutator of the trivial group and the trivial group is trivial + S = SymmetricGroup(3) + triv = PermutationGroup([Permutation([0, 1, 2])]) + assert S.commutator(triv, triv).is_subgroup(triv) + # the commutator of the trivial group and any other group is again trivial + A = AlternatingGroup(3) + assert S.commutator(triv, A).is_subgroup(triv) + # the commutator is commutative + for i in (3, 4, 5): + S = SymmetricGroup(i) + A = AlternatingGroup(i) + D = DihedralGroup(i) + assert S.commutator(A, D).is_subgroup(S.commutator(D, A)) + # the commutator of an abelian group is trivial + S = SymmetricGroup(7) + A1 = AbelianGroup(2, 5) + A2 = AbelianGroup(3, 4) + triv = PermutationGroup([Permutation([0, 1, 2, 3, 4, 5, 6])]) + assert S.commutator(A1, A1).is_subgroup(triv) + assert S.commutator(A2, A2).is_subgroup(triv) + # examples calculated by hand + S = SymmetricGroup(3) + A = AlternatingGroup(3) + assert S.commutator(A, S).is_subgroup(A) + + +def test_is_nilpotent(): + # every abelian group is nilpotent + for i in (1, 2, 3): + C = CyclicGroup(i) + Ab = AbelianGroup(i, i + 2) + assert C.is_nilpotent + assert Ab.is_nilpotent + Ab = AbelianGroup(5, 7, 10) + assert Ab.is_nilpotent + # A_5 is not solvable and thus not nilpotent + assert AlternatingGroup(5).is_nilpotent is False + + +def test_is_trivial(): + for i in range(5): + triv = PermutationGroup([Permutation(list(range(i)))]) + assert triv.is_trivial + + +def test_pointwise_stabilizer(): + S = SymmetricGroup(2) + stab = S.pointwise_stabilizer([0]) + assert stab.generators == [Permutation(1)] + S = SymmetricGroup(5) + points = [] + stab = S + for point in (2, 0, 3, 4, 1): + stab = stab.stabilizer(point) + points.append(point) + assert S.pointwise_stabilizer(points).is_subgroup(stab) + + +def test_make_perm(): + assert cube.pgroup.make_perm(5, seed=list(range(5))) == \ + Permutation([4, 7, 6, 5, 0, 3, 2, 1]) + assert cube.pgroup.make_perm(7, seed=list(range(7))) == \ + Permutation([6, 7, 3, 2, 5, 4, 0, 1]) + + +def test_elements(): + from sympy.sets.sets import FiniteSet + + p = Permutation(2, 3) + assert set(PermutationGroup(p).elements) == {Permutation(3), Permutation(2, 3)} + assert FiniteSet(*PermutationGroup(p).elements) \ + == FiniteSet(Permutation(2, 3), Permutation(3)) + + +def test_is_group(): + assert PermutationGroup(Permutation(1,2), Permutation(2,4)).is_group is True + assert SymmetricGroup(4).is_group is True + + +def test_PermutationGroup(): + assert PermutationGroup() == PermutationGroup(Permutation()) + assert (PermutationGroup() == 0) is False + + +def test_coset_transvesal(): + G = AlternatingGroup(5) + H = PermutationGroup(Permutation(0,1,2),Permutation(1,2)(3,4)) + assert G.coset_transversal(H) == \ + [Permutation(4), Permutation(2, 3, 4), Permutation(2, 4, 3), + Permutation(1, 2, 4), Permutation(4)(1, 2, 3), Permutation(1, 3)(2, 4), + Permutation(0, 1, 2, 3, 4), Permutation(0, 1, 2, 4, 3), + Permutation(0, 1, 3, 2, 4), Permutation(0, 2, 4, 1, 3)] + + +def test_coset_table(): + G = PermutationGroup(Permutation(0,1,2,3), Permutation(0,1,2), + Permutation(0,4,2,7), Permutation(5,6), Permutation(0,7)) + H = PermutationGroup(Permutation(0,1,2,3), Permutation(0,7)) + assert G.coset_table(H) == \ + [[0, 0, 0, 0, 1, 2, 3, 3, 0, 0], [4, 5, 2, 5, 6, 0, 7, 7, 1, 1], + [5, 4, 5, 1, 0, 6, 8, 8, 6, 6], [3, 3, 3, 3, 7, 8, 0, 0, 3, 3], + [2, 1, 4, 4, 4, 4, 9, 9, 4, 4], [1, 2, 1, 2, 5, 5, 10, 10, 5, 5], + [6, 6, 6, 6, 2, 1, 11, 11, 2, 2], [9, 10, 8, 10, 11, 3, 1, 1, 7, 7], + [10, 9, 10, 7, 3, 11, 2, 2, 11, 11], [8, 7, 9, 9, 9, 9, 4, 4, 9, 9], + [7, 8, 7, 8, 10, 10, 5, 5, 10, 10], [11, 11, 11, 11, 8, 7, 6, 6, 8, 8]] + + +def test_subgroup(): + G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3)) + H = G.subgroup([Permutation(0,1,3)]) + assert H.is_subgroup(G) + + +def test_generator_product(): + G = SymmetricGroup(5) + p = Permutation(0, 2, 3)(1, 4) + gens = G.generator_product(p) + assert all(g in G.strong_gens for g in gens) + w = G.identity + for g in gens: + w = g*w + assert w == p + + +def test_sylow_subgroup(): + P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) + S = P.sylow_subgroup(2) + assert S.order() == 4 + + P = DihedralGroup(12) + S = P.sylow_subgroup(3) + assert S.order() == 3 + + P = PermutationGroup( + Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5), Permutation(0, 2)) + S = P.sylow_subgroup(3) + assert S.order() == 9 + S = P.sylow_subgroup(2) + assert S.order() == 8 + + P = SymmetricGroup(10) + S = P.sylow_subgroup(2) + assert S.order() == 256 + S = P.sylow_subgroup(3) + assert S.order() == 81 + S = P.sylow_subgroup(5) + assert S.order() == 25 + + # the length of the lower central series + # of a p-Sylow subgroup of Sym(n) grows with + # the highest exponent exp of p such + # that n >= p**exp + exp = 1 + length = 0 + for i in range(2, 9): + P = SymmetricGroup(i) + S = P.sylow_subgroup(2) + ls = S.lower_central_series() + if i // 2**exp > 0: + # length increases with exponent + assert len(ls) > length + length = len(ls) + exp += 1 + else: + assert len(ls) == length + + G = SymmetricGroup(100) + S = G.sylow_subgroup(3) + assert G.order() % S.order() == 0 + assert G.order()/S.order() % 3 > 0 + + G = AlternatingGroup(100) + S = G.sylow_subgroup(2) + assert G.order() % S.order() == 0 + assert G.order()/S.order() % 2 > 0 + + G = DihedralGroup(18) + S = G.sylow_subgroup(p=2) + assert S.order() == 4 + + G = DihedralGroup(50) + S = G.sylow_subgroup(p=2) + assert S.order() == 4 + + +@slow +def test_presentation(): + def _test(P): + G = P.presentation() + return G.order() == P.order() + + def _strong_test(P): + G = P.strong_presentation() + chk = len(G.generators) == len(P.strong_gens) + return chk and G.order() == P.order() + + P = PermutationGroup(Permutation(0,1,5,2)(3,7,4,6), Permutation(0,3,5,4)(1,6,2,7)) + assert _test(P) + + P = AlternatingGroup(5) + assert _test(P) + + P = SymmetricGroup(5) + assert _test(P) + + P = PermutationGroup( + [Permutation(0,3,1,2), Permutation(3)(0,1), Permutation(0,1)(2,3)]) + assert _strong_test(P) + + P = DihedralGroup(6) + assert _strong_test(P) + + a = Permutation(0,1)(2,3) + b = Permutation(0,2)(3,1) + c = Permutation(4,5) + P = PermutationGroup(c, a, b) + assert _strong_test(P) + + +def test_polycyclic(): + a = Permutation([0, 1, 2]) + b = Permutation([2, 1, 0]) + G = PermutationGroup([a, b]) + assert G.is_polycyclic is True + + a = Permutation([1, 2, 3, 4, 0]) + b = Permutation([1, 0, 2, 3, 4]) + G = PermutationGroup([a, b]) + assert G.is_polycyclic is False + + +def test_elementary(): + a = Permutation([1, 5, 2, 0, 3, 6, 4]) + G = PermutationGroup([a]) + assert G.is_elementary(7) is False + + a = Permutation(0, 1)(2, 3) + b = Permutation(0, 2)(3, 1) + G = PermutationGroup([a, b]) + assert G.is_elementary(2) is True + c = Permutation(4, 5, 6) + G = PermutationGroup([a, b, c]) + assert G.is_elementary(2) is False + + G = SymmetricGroup(4).sylow_subgroup(2) + assert G.is_elementary(2) is False + H = AlternatingGroup(4).sylow_subgroup(2) + assert H.is_elementary(2) is True + + +def test_perfect(): + G = AlternatingGroup(3) + assert G.is_perfect is False + G = AlternatingGroup(5) + assert G.is_perfect is True + + +def test_index(): + G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3)) + H = G.subgroup([Permutation(0,1,3)]) + assert G.index(H) == 4 + + +def test_cyclic(): + G = SymmetricGroup(2) + assert G.is_cyclic + G = AbelianGroup(3, 7) + assert G.is_cyclic + G = AbelianGroup(7, 7) + assert not G.is_cyclic + G = AlternatingGroup(3) + assert G.is_cyclic + G = AlternatingGroup(4) + assert not G.is_cyclic + + # Order less than 6 + G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 1)) + assert G.is_cyclic + G = PermutationGroup( + Permutation(0, 1, 2, 3), + Permutation(0, 2)(1, 3) + ) + assert G.is_cyclic + G = PermutationGroup( + Permutation(3), + Permutation(0, 1)(2, 3), + Permutation(0, 2)(1, 3), + Permutation(0, 3)(1, 2) + ) + assert G.is_cyclic is False + + # Order 15 + G = PermutationGroup( + Permutation(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), + Permutation(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13) + ) + assert G.is_cyclic + + # Distinct prime orders + assert PermutationGroup._distinct_primes_lemma([3, 5]) is True + assert PermutationGroup._distinct_primes_lemma([5, 7]) is True + assert PermutationGroup._distinct_primes_lemma([2, 3]) is None + assert PermutationGroup._distinct_primes_lemma([3, 5, 7]) is None + assert PermutationGroup._distinct_primes_lemma([5, 7, 13]) is True + + G = PermutationGroup( + Permutation(0, 1, 2, 3), + Permutation(0, 2)(1, 3)) + assert G.is_cyclic + assert G._is_abelian + + # Non-abelian and therefore not cyclic + G = PermutationGroup(*SymmetricGroup(3).generators) + assert G.is_cyclic is False + + # Abelian and cyclic + G = PermutationGroup( + Permutation(0, 1, 2, 3), + Permutation(4, 5, 6) + ) + assert G.is_cyclic + + # Abelian but not cyclic + G = PermutationGroup( + Permutation(0, 1), + Permutation(2, 3), + Permutation(4, 5, 6) + ) + assert G.is_cyclic is False + + +def test_dihedral(): + G = SymmetricGroup(2) + assert G.is_dihedral + G = SymmetricGroup(3) + assert G.is_dihedral + + G = AbelianGroup(2, 2) + assert G.is_dihedral + G = CyclicGroup(4) + assert not G.is_dihedral + + G = AbelianGroup(3, 5) + assert not G.is_dihedral + G = AbelianGroup(2) + assert G.is_dihedral + G = AbelianGroup(6) + assert not G.is_dihedral + + # D6, generated by two adjacent flips + G = PermutationGroup( + Permutation(1, 5)(2, 4), + Permutation(0, 1)(3, 4)(2, 5)) + assert G.is_dihedral + + # D7, generated by a flip and a rotation + G = PermutationGroup( + Permutation(1, 6)(2, 5)(3, 4), + Permutation(0, 1, 2, 3, 4, 5, 6)) + assert G.is_dihedral + + # S4, presented by three generators, fails due to having exactly 9 + # elements of order 2: + G = PermutationGroup( + Permutation(0, 1), Permutation(0, 2), + Permutation(0, 3)) + assert not G.is_dihedral + + # D7, given by three generators + G = PermutationGroup( + Permutation(1, 6)(2, 5)(3, 4), + Permutation(2, 0)(3, 6)(4, 5), + Permutation(0, 1, 2, 3, 4, 5, 6)) + assert G.is_dihedral + + +def test_abelian_invariants(): + G = AbelianGroup(2, 3, 4) + assert G.abelian_invariants() == [2, 3, 4] + G=PermutationGroup([Permutation(1, 2, 3, 4), Permutation(1, 2), Permutation(5, 6)]) + assert G.abelian_invariants() == [2, 2] + G = AlternatingGroup(7) + assert G.abelian_invariants() == [] + G = AlternatingGroup(4) + assert G.abelian_invariants() == [3] + G = DihedralGroup(4) + assert G.abelian_invariants() == [2, 2] + + G = PermutationGroup([Permutation(1, 2, 3, 4, 5, 6, 7)]) + assert G.abelian_invariants() == [7] + G = DihedralGroup(12) + S = G.sylow_subgroup(3) + assert S.abelian_invariants() == [3] + G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 3)) + assert G.abelian_invariants() == [3] + G = PermutationGroup([Permutation(0, 1), Permutation(0, 2, 4, 6)(1, 3, 5, 7)]) + assert G.abelian_invariants() == [2, 4] + G = SymmetricGroup(30) + S = G.sylow_subgroup(2) + assert S.abelian_invariants() == [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + S = G.sylow_subgroup(3) + assert S.abelian_invariants() == [3, 3, 3, 3] + S = G.sylow_subgroup(5) + assert S.abelian_invariants() == [5, 5, 5] + + +def test_composition_series(): + a = Permutation(1, 2, 3) + b = Permutation(1, 2) + G = PermutationGroup([a, b]) + comp_series = G.composition_series() + assert comp_series == G.derived_series() + # The first group in the composition series is always the group itself and + # the last group in the series is the trivial group. + S = SymmetricGroup(4) + assert S.composition_series()[0] == S + assert len(S.composition_series()) == 5 + A = AlternatingGroup(4) + assert A.composition_series()[0] == A + assert len(A.composition_series()) == 4 + + # the composition series for C_8 is C_8 > C_4 > C_2 > triv + G = CyclicGroup(8) + series = G.composition_series() + assert is_isomorphic(series[1], CyclicGroup(4)) + assert is_isomorphic(series[2], CyclicGroup(2)) + assert series[3].is_trivial + + +def test_is_symmetric(): + a = Permutation(0, 1, 2) + b = Permutation(0, 1, size=3) + assert PermutationGroup(a, b).is_symmetric is True + + a = Permutation(0, 2, 1) + b = Permutation(1, 2, size=3) + assert PermutationGroup(a, b).is_symmetric is True + + a = Permutation(0, 1, 2, 3) + b = Permutation(0, 3)(1, 2) + assert PermutationGroup(a, b).is_symmetric is False + +def test_conjugacy_class(): + S = SymmetricGroup(4) + x = Permutation(1, 2, 3) + C = {Permutation(0, 1, 2, size = 4), Permutation(0, 1, 3), + Permutation(0, 2, 1, size = 4), Permutation(0, 2, 3), + Permutation(0, 3, 1), Permutation(0, 3, 2), + Permutation(1, 2, 3), Permutation(1, 3, 2)} + assert S.conjugacy_class(x) == C + +def test_conjugacy_classes(): + S = SymmetricGroup(3) + expected = [{Permutation(size = 3)}, + {Permutation(0, 1, size = 3), Permutation(0, 2), Permutation(1, 2)}, + {Permutation(0, 1, 2), Permutation(0, 2, 1)}] + computed = S.conjugacy_classes() + + assert len(expected) == len(computed) + assert all(e in computed for e in expected) + +def test_coset_class(): + a = Permutation(1, 2) + b = Permutation(0, 1) + G = PermutationGroup([a, b]) + #Creating right coset + rht_coset = G*a + #Checking whether it is left coset or right coset + assert rht_coset.is_right_coset + assert not rht_coset.is_left_coset + #Creating list representation of coset + list_repr = rht_coset.as_list() + expected = [Permutation(0, 2), Permutation(0, 2, 1), Permutation(1, 2), + Permutation(2), Permutation(2)(0, 1), Permutation(0, 1, 2)] + for ele in list_repr: + assert ele in expected + #Creating left coset + left_coset = a*G + #Checking whether it is left coset or right coset + assert not left_coset.is_right_coset + assert left_coset.is_left_coset + #Creating list representation of Coset + list_repr = left_coset.as_list() + expected = [Permutation(2)(0, 1), Permutation(0, 1, 2), Permutation(1, 2), + Permutation(2), Permutation(0, 2), Permutation(0, 2, 1)] + for ele in list_repr: + assert ele in expected + + G = PermutationGroup(Permutation(1, 2, 3, 4), Permutation(2, 3, 4)) + H = PermutationGroup(Permutation(1, 2, 3, 4)) + g = Permutation(1, 3)(2, 4) + rht_coset = Coset(g, H, G, dir='+') + assert rht_coset.is_right_coset + list_repr = rht_coset.as_list() + expected = [Permutation(1, 2, 3, 4), Permutation(4), Permutation(1, 3)(2, 4), + Permutation(1, 4, 3, 2)] + for ele in list_repr: + assert ele in expected + +def test_symmetricpermutationgroup(): + a = SymmetricPermutationGroup(5) + assert a.degree == 5 + assert a.order() == 120 + assert a.identity() == Permutation(4) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_permutations.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_permutations.py new file mode 100644 index 0000000000000000000000000000000000000000..b52fcfec0e2fb3be872efaa814077760e121c748 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_permutations.py @@ -0,0 +1,564 @@ +from itertools import permutations +from copy import copy + +from sympy.core.expr import unchanged +from sympy.core.numbers import Integer +from sympy.core.relational import Eq +from sympy.core.symbol import Symbol +from sympy.core.singleton import S +from sympy.combinatorics.permutations import \ + Permutation, _af_parity, _af_rmul, _af_rmuln, AppliedPermutation, Cycle +from sympy.printing import sstr, srepr, pretty, latex +from sympy.testing.pytest import raises, warns_deprecated_sympy + + +rmul = Permutation.rmul +a = Symbol('a', integer=True) + + +def test_Permutation(): + # don't auto fill 0 + raises(ValueError, lambda: Permutation([1])) + p = Permutation([0, 1, 2, 3]) + # call as bijective + assert [p(i) for i in range(p.size)] == list(p) + # call as operator + assert p(list(range(p.size))) == list(p) + # call as function + assert list(p(1, 2)) == [0, 2, 1, 3] + raises(TypeError, lambda: p(-1)) + raises(TypeError, lambda: p(5)) + # conversion to list + assert list(p) == list(range(4)) + assert p.copy() == p + assert copy(p) == p + assert Permutation(size=4) == Permutation(3) + assert Permutation(Permutation(3), size=5) == Permutation(4) + # cycle form with size + assert Permutation([[1, 2]], size=4) == Permutation([[1, 2], [0], [3]]) + # random generation + assert Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) + + p = Permutation([2, 5, 1, 6, 3, 0, 4]) + q = Permutation([[1], [0, 3, 5, 6, 2, 4]]) + assert len({p, p}) == 1 + r = Permutation([1, 3, 2, 0, 4, 6, 5]) + ans = Permutation(_af_rmuln(*[w.array_form for w in (p, q, r)])).array_form + assert rmul(p, q, r).array_form == ans + # make sure no other permutation of p, q, r could have given + # that answer + for a, b, c in permutations((p, q, r)): + if (a, b, c) == (p, q, r): + continue + assert rmul(a, b, c).array_form != ans + + assert p.support() == list(range(7)) + assert q.support() == [0, 2, 3, 4, 5, 6] + assert Permutation(p.cyclic_form).array_form == p.array_form + assert p.cardinality == 5040 + assert q.cardinality == 5040 + assert q.cycles == 2 + assert rmul(q, p) == Permutation([4, 6, 1, 2, 5, 3, 0]) + assert rmul(p, q) == Permutation([6, 5, 3, 0, 2, 4, 1]) + assert _af_rmul(p.array_form, q.array_form) == \ + [6, 5, 3, 0, 2, 4, 1] + + assert rmul(Permutation([[1, 2, 3], [0, 4]]), + Permutation([[1, 2, 4], [0], [3]])).cyclic_form == \ + [[0, 4, 2], [1, 3]] + assert q.array_form == [3, 1, 4, 5, 0, 6, 2] + assert q.cyclic_form == [[0, 3, 5, 6, 2, 4]] + assert q.full_cyclic_form == [[0, 3, 5, 6, 2, 4], [1]] + assert p.cyclic_form == [[0, 2, 1, 5], [3, 6, 4]] + t = p.transpositions() + assert t == [(0, 5), (0, 1), (0, 2), (3, 4), (3, 6)] + assert Permutation.rmul(*[Permutation(Cycle(*ti)) for ti in (t)]) + assert Permutation([1, 0]).transpositions() == [(0, 1)] + + assert p**13 == p + assert q**0 == Permutation(list(range(q.size))) + assert q**-2 == ~q**2 + assert q**2 == Permutation([5, 1, 0, 6, 3, 2, 4]) + assert q**3 == q**2*q + assert q**4 == q**2*q**2 + + a = Permutation(1, 3) + b = Permutation(2, 0, 3) + I = Permutation(3) + assert ~a == a**-1 + assert a*~a == I + assert a*b**-1 == a*~b + + ans = Permutation(0, 5, 3, 1, 6)(2, 4) + assert (p + q.rank()).rank() == ans.rank() + assert (p + q.rank())._rank == ans.rank() + assert (q + p.rank()).rank() == ans.rank() + raises(TypeError, lambda: p + Permutation(list(range(10)))) + + assert (p - q.rank()).rank() == Permutation(0, 6, 3, 1, 2, 5, 4).rank() + assert p.rank() - q.rank() < 0 # for coverage: make sure mod is used + assert (q - p.rank()).rank() == Permutation(1, 4, 6, 2)(3, 5).rank() + + assert p*q == Permutation(_af_rmuln(*[list(w) for w in (q, p)])) + assert p*Permutation([]) == p + assert Permutation([])*p == p + assert p*Permutation([[0, 1]]) == Permutation([2, 5, 0, 6, 3, 1, 4]) + assert Permutation([[0, 1]])*p == Permutation([5, 2, 1, 6, 3, 0, 4]) + + pq = p ^ q + assert pq == Permutation([5, 6, 0, 4, 1, 2, 3]) + assert pq == rmul(q, p, ~q) + qp = q ^ p + assert qp == Permutation([4, 3, 6, 2, 1, 5, 0]) + assert qp == rmul(p, q, ~p) + raises(ValueError, lambda: p ^ Permutation([])) + + assert p.commutator(q) == Permutation(0, 1, 3, 4, 6, 5, 2) + assert q.commutator(p) == Permutation(0, 2, 5, 6, 4, 3, 1) + assert p.commutator(q) == ~q.commutator(p) + raises(ValueError, lambda: p.commutator(Permutation([]))) + + assert len(p.atoms()) == 7 + assert q.atoms() == {0, 1, 2, 3, 4, 5, 6} + + assert p.inversion_vector() == [2, 4, 1, 3, 1, 0] + assert q.inversion_vector() == [3, 1, 2, 2, 0, 1] + + assert Permutation.from_inversion_vector(p.inversion_vector()) == p + assert Permutation.from_inversion_vector(q.inversion_vector()).array_form\ + == q.array_form + raises(ValueError, lambda: Permutation.from_inversion_vector([0, 2])) + assert Permutation(list(range(500, -1, -1))).inversions() == 125250 + + s = Permutation([0, 4, 1, 3, 2]) + assert s.parity() == 0 + _ = s.cyclic_form # needed to create a value for _cyclic_form + assert len(s._cyclic_form) != s.size and s.parity() == 0 + assert not s.is_odd + assert s.is_even + assert Permutation([0, 1, 4, 3, 2]).parity() == 1 + assert _af_parity([0, 4, 1, 3, 2]) == 0 + assert _af_parity([0, 1, 4, 3, 2]) == 1 + + s = Permutation([0]) + + assert s.is_Singleton + assert Permutation([]).is_Empty + + r = Permutation([3, 2, 1, 0]) + assert (r**2).is_Identity + + assert rmul(~p, p).is_Identity + assert (~p)**13 == Permutation([5, 2, 0, 4, 6, 1, 3]) + assert p.max() == 6 + assert p.min() == 0 + + q = Permutation([[6], [5], [0, 1, 2, 3, 4]]) + + assert q.max() == 4 + assert q.min() == 0 + + p = Permutation([1, 5, 2, 0, 3, 6, 4]) + q = Permutation([[1, 2, 3, 5, 6], [0, 4]]) + + assert p.ascents() == [0, 3, 4] + assert q.ascents() == [1, 2, 4] + assert r.ascents() == [] + + assert p.descents() == [1, 2, 5] + assert q.descents() == [0, 3, 5] + assert Permutation(r.descents()).is_Identity + + assert p.inversions() == 7 + # test the merge-sort with a longer permutation + big = list(p) + list(range(p.max() + 1, p.max() + 130)) + assert Permutation(big).inversions() == 7 + assert p.signature() == -1 + assert q.inversions() == 11 + assert q.signature() == -1 + assert rmul(p, ~p).inversions() == 0 + assert rmul(p, ~p).signature() == 1 + + assert p.order() == 6 + assert q.order() == 10 + assert (p**(p.order())).is_Identity + + assert p.length() == 6 + assert q.length() == 7 + assert r.length() == 4 + + assert p.runs() == [[1, 5], [2], [0, 3, 6], [4]] + assert q.runs() == [[4], [2, 3, 5], [0, 6], [1]] + assert r.runs() == [[3], [2], [1], [0]] + + assert p.index() == 8 + assert q.index() == 8 + assert r.index() == 3 + + assert p.get_precedence_distance(q) == q.get_precedence_distance(p) + assert p.get_adjacency_distance(q) == p.get_adjacency_distance(q) + assert p.get_positional_distance(q) == p.get_positional_distance(q) + p = Permutation([0, 1, 2, 3]) + q = Permutation([3, 2, 1, 0]) + assert p.get_precedence_distance(q) == 6 + assert p.get_adjacency_distance(q) == 3 + assert p.get_positional_distance(q) == 8 + p = Permutation([0, 3, 1, 2, 4]) + q = Permutation.josephus(4, 5, 2) + assert p.get_adjacency_distance(q) == 3 + raises(ValueError, lambda: p.get_adjacency_distance(Permutation([]))) + raises(ValueError, lambda: p.get_positional_distance(Permutation([]))) + raises(ValueError, lambda: p.get_precedence_distance(Permutation([]))) + + a = [Permutation.unrank_nonlex(4, i) for i in range(5)] + iden = Permutation([0, 1, 2, 3]) + for i in range(5): + for j in range(i + 1, 5): + assert a[i].commutes_with(a[j]) == \ + (rmul(a[i], a[j]) == rmul(a[j], a[i])) + if a[i].commutes_with(a[j]): + assert a[i].commutator(a[j]) == iden + assert a[j].commutator(a[i]) == iden + + a = Permutation(3) + b = Permutation(0, 6, 3)(1, 2) + assert a.cycle_structure == {1: 4} + assert b.cycle_structure == {2: 1, 3: 1, 1: 2} + # issue 11130 + raises(ValueError, lambda: Permutation(3, size=3)) + raises(ValueError, lambda: Permutation([1, 2, 0, 3], size=3)) + + +def test_Permutation_subclassing(): + # Subclass that adds permutation application on iterables + class CustomPermutation(Permutation): + def __call__(self, *i): + try: + return super().__call__(*i) + except TypeError: + pass + + try: + perm_obj = i[0] + return [self._array_form[j] for j in perm_obj] + except TypeError: + raise TypeError('unrecognized argument') + + def __eq__(self, other): + if isinstance(other, Permutation): + return self._hashable_content() == other._hashable_content() + else: + return super().__eq__(other) + + def __hash__(self): + return super().__hash__() + + p = CustomPermutation([1, 2, 3, 0]) + q = Permutation([1, 2, 3, 0]) + + assert p == q + raises(TypeError, lambda: q([1, 2])) + assert [2, 3] == p([1, 2]) + + assert type(p * q) == CustomPermutation + assert type(q * p) == Permutation # True because q.__mul__(p) is called! + + # Run all tests for the Permutation class also on the subclass + def wrapped_test_Permutation(): + # Monkeypatch the class definition in the globals + globals()['__Perm'] = globals()['Permutation'] + globals()['Permutation'] = CustomPermutation + test_Permutation() + globals()['Permutation'] = globals()['__Perm'] # Restore + del globals()['__Perm'] + + wrapped_test_Permutation() + + +def test_josephus(): + assert Permutation.josephus(4, 6, 1) == Permutation([3, 1, 0, 2, 5, 4]) + assert Permutation.josephus(1, 5, 1).is_Identity + + +def test_ranking(): + assert Permutation.unrank_lex(5, 10).rank() == 10 + p = Permutation.unrank_lex(15, 225) + assert p.rank() == 225 + p1 = p.next_lex() + assert p1.rank() == 226 + assert Permutation.unrank_lex(15, 225).rank() == 225 + assert Permutation.unrank_lex(10, 0).is_Identity + p = Permutation.unrank_lex(4, 23) + assert p.rank() == 23 + assert p.array_form == [3, 2, 1, 0] + assert p.next_lex() is None + + p = Permutation([1, 5, 2, 0, 3, 6, 4]) + q = Permutation([[1, 2, 3, 5, 6], [0, 4]]) + a = [Permutation.unrank_trotterjohnson(4, i).array_form for i in range(5)] + assert a == [[0, 1, 2, 3], [0, 1, 3, 2], [0, 3, 1, 2], [3, 0, 1, + 2], [3, 0, 2, 1] ] + assert [Permutation(pa).rank_trotterjohnson() for pa in a] == list(range(5)) + assert Permutation([0, 1, 2, 3]).next_trotterjohnson() == \ + Permutation([0, 1, 3, 2]) + + assert q.rank_trotterjohnson() == 2283 + assert p.rank_trotterjohnson() == 3389 + assert Permutation([1, 0]).rank_trotterjohnson() == 1 + a = Permutation(list(range(3))) + b = a + l = [] + tj = [] + for i in range(6): + l.append(a) + tj.append(b) + a = a.next_lex() + b = b.next_trotterjohnson() + assert a == b is None + assert {tuple(a) for a in l} == {tuple(a) for a in tj} + + p = Permutation([2, 5, 1, 6, 3, 0, 4]) + q = Permutation([[6], [5], [0, 1, 2, 3, 4]]) + assert p.rank() == 1964 + assert q.rank() == 870 + assert Permutation([]).rank_nonlex() == 0 + prank = p.rank_nonlex() + assert prank == 1600 + assert Permutation.unrank_nonlex(7, 1600) == p + qrank = q.rank_nonlex() + assert qrank == 41 + assert Permutation.unrank_nonlex(7, 41) == Permutation(q.array_form) + + a = [Permutation.unrank_nonlex(4, i).array_form for i in range(24)] + assert a == [ + [1, 2, 3, 0], [3, 2, 0, 1], [1, 3, 0, 2], [1, 2, 0, 3], [2, 3, 1, 0], + [2, 0, 3, 1], [3, 0, 1, 2], [2, 0, 1, 3], [1, 3, 2, 0], [3, 0, 2, 1], + [1, 0, 3, 2], [1, 0, 2, 3], [2, 1, 3, 0], [2, 3, 0, 1], [3, 1, 0, 2], + [2, 1, 0, 3], [3, 2, 1, 0], [0, 2, 3, 1], [0, 3, 1, 2], [0, 2, 1, 3], + [3, 1, 2, 0], [0, 3, 2, 1], [0, 1, 3, 2], [0, 1, 2, 3]] + + N = 10 + p1 = Permutation(a[0]) + for i in range(1, N+1): + p1 = p1*Permutation(a[i]) + p2 = Permutation.rmul_with_af(*[Permutation(h) for h in a[N::-1]]) + assert p1 == p2 + + ok = [] + p = Permutation([1, 0]) + for i in range(3): + ok.append(p.array_form) + p = p.next_nonlex() + if p is None: + ok.append(None) + break + assert ok == [[1, 0], [0, 1], None] + assert Permutation([3, 2, 0, 1]).next_nonlex() == Permutation([1, 3, 0, 2]) + assert [Permutation(pa).rank_nonlex() for pa in a] == list(range(24)) + + +def test_mul(): + a, b = [0, 2, 1, 3], [0, 1, 3, 2] + assert _af_rmul(a, b) == [0, 2, 3, 1] + assert _af_rmuln(a, b, list(range(4))) == [0, 2, 3, 1] + assert rmul(Permutation(a), Permutation(b)).array_form == [0, 2, 3, 1] + + a = Permutation([0, 2, 1, 3]) + b = (0, 1, 3, 2) + c = (3, 1, 2, 0) + assert Permutation.rmul(a, b, c) == Permutation([1, 2, 3, 0]) + assert Permutation.rmul(a, c) == Permutation([3, 2, 1, 0]) + raises(TypeError, lambda: Permutation.rmul(b, c)) + + n = 6 + m = 8 + a = [Permutation.unrank_nonlex(n, i).array_form for i in range(m)] + h = list(range(n)) + for i in range(m): + h = _af_rmul(h, a[i]) + h2 = _af_rmuln(*a[:i + 1]) + assert h == h2 + + +def test_args(): + p = Permutation([(0, 3, 1, 2), (4, 5)]) + assert p._cyclic_form is None + assert Permutation(p) == p + assert p.cyclic_form == [[0, 3, 1, 2], [4, 5]] + assert p._array_form == [3, 2, 0, 1, 5, 4] + p = Permutation((0, 3, 1, 2)) + assert p._cyclic_form is None + assert p._array_form == [0, 3, 1, 2] + assert Permutation([0]) == Permutation((0, )) + assert Permutation([[0], [1]]) == Permutation(((0, ), (1, ))) == \ + Permutation(((0, ), [1])) + assert Permutation([[1, 2]]) == Permutation([0, 2, 1]) + assert Permutation([[1], [4, 2]]) == Permutation([0, 1, 4, 3, 2]) + assert Permutation([[1], [4, 2]], size=1) == Permutation([0, 1, 4, 3, 2]) + assert Permutation( + [[1], [4, 2]], size=6) == Permutation([0, 1, 4, 3, 2, 5]) + assert Permutation([[0, 1], [0, 2]]) == Permutation(0, 1, 2) + assert Permutation([], size=3) == Permutation([0, 1, 2]) + assert Permutation(3).list(5) == [0, 1, 2, 3, 4] + assert Permutation(3).list(-1) == [] + assert Permutation(5)(1, 2).list(-1) == [0, 2, 1] + assert Permutation(5)(1, 2).list() == [0, 2, 1, 3, 4, 5] + raises(ValueError, lambda: Permutation([1, 2], [0])) + # enclosing brackets needed + raises(ValueError, lambda: Permutation([[1, 2], 0])) + # enclosing brackets needed on 0 + raises(ValueError, lambda: Permutation([1, 1, 0])) + raises(ValueError, lambda: Permutation([4, 5], size=10)) # where are 0-3? + # but this is ok because cycles imply that only those listed moved + assert Permutation(4, 5) == Permutation([0, 1, 2, 3, 5, 4]) + + +def test_Cycle(): + assert str(Cycle()) == '()' + assert Cycle(Cycle(1,2)) == Cycle(1, 2) + assert Cycle(1,2).copy() == Cycle(1,2) + assert list(Cycle(1, 3, 2)) == [0, 3, 1, 2] + assert Cycle(1, 2)(2, 3) == Cycle(1, 3, 2) + assert Cycle(1, 2)(2, 3)(4, 5) == Cycle(1, 3, 2)(4, 5) + assert Permutation(Cycle(1, 2)(2, 1, 0, 3)).cyclic_form, Cycle(0, 2, 1) + raises(ValueError, lambda: Cycle().list()) + assert Cycle(1, 2).list() == [0, 2, 1] + assert Cycle(1, 2).list(4) == [0, 2, 1, 3] + assert Cycle(3).list(2) == [0, 1] + assert Cycle(3).list(6) == [0, 1, 2, 3, 4, 5] + assert Permutation(Cycle(1, 2), size=4) == \ + Permutation([0, 2, 1, 3]) + assert str(Cycle(1, 2)(4, 5)) == '(1 2)(4 5)' + assert str(Cycle(1, 2)) == '(1 2)' + assert Cycle(Permutation(list(range(3)))) == Cycle() + assert Cycle(1, 2).list() == [0, 2, 1] + assert Cycle(1, 2).list(4) == [0, 2, 1, 3] + assert Cycle().size == 0 + raises(ValueError, lambda: Cycle((1, 2))) + raises(ValueError, lambda: Cycle(1, 2, 1)) + raises(TypeError, lambda: Cycle(1, 2)*{}) + raises(ValueError, lambda: Cycle(4)[a]) + raises(ValueError, lambda: Cycle(2, -4, 3)) + + # check round-trip + p = Permutation([[1, 2], [4, 3]], size=5) + assert Permutation(Cycle(p)) == p + + +def test_from_sequence(): + assert Permutation.from_sequence('SymPy') == Permutation(4)(0, 1, 3) + assert Permutation.from_sequence('SymPy', key=lambda x: x.lower()) == \ + Permutation(4)(0, 2)(1, 3) + + +def test_resize(): + p = Permutation(0, 1, 2) + assert p.resize(5) == Permutation(0, 1, 2, size=5) + assert p.resize(4) == Permutation(0, 1, 2, size=4) + assert p.resize(3) == p + raises(ValueError, lambda: p.resize(2)) + + p = Permutation(0, 1, 2)(3, 4)(5, 6) + assert p.resize(3) == Permutation(0, 1, 2) + raises(ValueError, lambda: p.resize(4)) + + +def test_printing_cyclic(): + p1 = Permutation([0, 2, 1]) + assert repr(p1) == 'Permutation(1, 2)' + assert str(p1) == '(1 2)' + p2 = Permutation() + assert repr(p2) == 'Permutation()' + assert str(p2) == '()' + p3 = Permutation([1, 2, 0, 3]) + assert repr(p3) == 'Permutation(3)(0, 1, 2)' + + +def test_printing_non_cyclic(): + p1 = Permutation([0, 1, 2, 3, 4, 5]) + assert srepr(p1, perm_cyclic=False) == 'Permutation([], size=6)' + assert sstr(p1, perm_cyclic=False) == 'Permutation([], size=6)' + p2 = Permutation([0, 1, 2]) + assert srepr(p2, perm_cyclic=False) == 'Permutation([0, 1, 2])' + assert sstr(p2, perm_cyclic=False) == 'Permutation([0, 1, 2])' + + p3 = Permutation([0, 2, 1]) + assert srepr(p3, perm_cyclic=False) == 'Permutation([0, 2, 1])' + assert sstr(p3, perm_cyclic=False) == 'Permutation([0, 2, 1])' + p4 = Permutation([0, 1, 3, 2, 4, 5, 6, 7]) + assert srepr(p4, perm_cyclic=False) == 'Permutation([0, 1, 3, 2], size=8)' + + +def test_deprecated_print_cyclic(): + p = Permutation(0, 1, 2) + try: + Permutation.print_cyclic = True + with warns_deprecated_sympy(): + assert sstr(p) == '(0 1 2)' + with warns_deprecated_sympy(): + assert srepr(p) == 'Permutation(0, 1, 2)' + with warns_deprecated_sympy(): + assert pretty(p) == '(0 1 2)' + with warns_deprecated_sympy(): + assert latex(p) == r'\left( 0\; 1\; 2\right)' + + Permutation.print_cyclic = False + with warns_deprecated_sympy(): + assert sstr(p) == 'Permutation([1, 2, 0])' + with warns_deprecated_sympy(): + assert srepr(p) == 'Permutation([1, 2, 0])' + with warns_deprecated_sympy(): + assert pretty(p, use_unicode=False) == '/0 1 2\\\n\\1 2 0/' + with warns_deprecated_sympy(): + assert latex(p) == \ + r'\begin{pmatrix} 0 & 1 & 2 \\ 1 & 2 & 0 \end{pmatrix}' + finally: + Permutation.print_cyclic = None + + +def test_permutation_equality(): + a = Permutation(0, 1, 2) + b = Permutation(0, 1, 2) + assert Eq(a, b) is S.true + c = Permutation(0, 2, 1) + assert Eq(a, c) is S.false + + d = Permutation(0, 1, 2, size=4) + assert unchanged(Eq, a, d) + e = Permutation(0, 2, 1, size=4) + assert unchanged(Eq, a, e) + + i = Permutation() + assert unchanged(Eq, i, 0) + assert unchanged(Eq, 0, i) + + +def test_issue_17661(): + c1 = Cycle(1,2) + c2 = Cycle(1,2) + assert c1 == c2 + assert repr(c1) == 'Cycle(1, 2)' + assert c1 == c2 + + +def test_permutation_apply(): + x = Symbol('x') + p = Permutation(0, 1, 2) + assert p.apply(0) == 1 + assert isinstance(p.apply(0), Integer) + assert p.apply(x) == AppliedPermutation(p, x) + assert AppliedPermutation(p, x).subs(x, 0) == 1 + + x = Symbol('x', integer=False) + raises(NotImplementedError, lambda: p.apply(x)) + x = Symbol('x', negative=True) + raises(NotImplementedError, lambda: p.apply(x)) + + +def test_AppliedPermutation(): + x = Symbol('x') + p = Permutation(0, 1, 2) + raises(ValueError, lambda: AppliedPermutation((0, 1, 2), x)) + assert AppliedPermutation(p, 1, evaluate=True) == 2 + assert AppliedPermutation(p, 1, evaluate=False).__class__ == \ + AppliedPermutation diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_polyhedron.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_polyhedron.py new file mode 100644 index 0000000000000000000000000000000000000000..abf469bb560eef1f378eff4740a84b80b696035f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_polyhedron.py @@ -0,0 +1,105 @@ +from sympy.core.symbol import symbols +from sympy.sets.sets import FiniteSet +from sympy.combinatorics.polyhedron import (Polyhedron, + tetrahedron, cube as square, octahedron, dodecahedron, icosahedron, + cube_faces) +from sympy.combinatorics.permutations import Permutation +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.testing.pytest import raises + +rmul = Permutation.rmul + + +def test_polyhedron(): + raises(ValueError, lambda: Polyhedron(list('ab'), + pgroup=[Permutation([0])])) + pgroup = [Permutation([[0, 7, 2, 5], [6, 1, 4, 3]]), + Permutation([[0, 7, 1, 6], [5, 2, 4, 3]]), + Permutation([[3, 6, 0, 5], [4, 1, 7, 2]]), + Permutation([[7, 4, 5], [1, 3, 0], [2], [6]]), + Permutation([[1, 3, 2], [7, 6, 5], [4], [0]]), + Permutation([[4, 7, 6], [2, 0, 3], [1], [5]]), + Permutation([[1, 2, 0], [4, 5, 6], [3], [7]]), + Permutation([[4, 2], [0, 6], [3, 7], [1, 5]]), + Permutation([[3, 5], [7, 1], [2, 6], [0, 4]]), + Permutation([[2, 5], [1, 6], [0, 4], [3, 7]]), + Permutation([[4, 3], [7, 0], [5, 1], [6, 2]]), + Permutation([[4, 1], [0, 5], [6, 2], [7, 3]]), + Permutation([[7, 2], [3, 6], [0, 4], [1, 5]]), + Permutation([0, 1, 2, 3, 4, 5, 6, 7])] + corners = tuple(symbols('A:H')) + faces = cube_faces + cube = Polyhedron(corners, faces, pgroup) + + assert cube.edges == FiniteSet(*( + (0, 1), (6, 7), (1, 2), (5, 6), (0, 3), (2, 3), + (4, 7), (4, 5), (3, 7), (1, 5), (0, 4), (2, 6))) + + for i in range(3): # add 180 degree face rotations + cube.rotate(cube.pgroup[i]**2) + + assert cube.corners == corners + + for i in range(3, 7): # add 240 degree axial corner rotations + cube.rotate(cube.pgroup[i]**2) + + assert cube.corners == corners + cube.rotate(1) + raises(ValueError, lambda: cube.rotate(Permutation([0, 1]))) + assert cube.corners != corners + assert cube.array_form == [7, 6, 4, 5, 3, 2, 0, 1] + assert cube.cyclic_form == [[0, 7, 1, 6], [2, 4, 3, 5]] + cube.reset() + assert cube.corners == corners + + def check(h, size, rpt, target): + + assert len(h.faces) + len(h.vertices) - len(h.edges) == 2 + assert h.size == size + + got = set() + for p in h.pgroup: + # make sure it restores original + P = h.copy() + hit = P.corners + for i in range(rpt): + P.rotate(p) + if P.corners == hit: + break + else: + print('error in permutation', p.array_form) + for i in range(rpt): + P.rotate(p) + got.add(tuple(P.corners)) + c = P.corners + f = [[c[i] for i in f] for f in P.faces] + assert h.faces == Polyhedron(c, f).faces + assert len(got) == target + assert PermutationGroup([Permutation(g) for g in got]).is_group + + for h, size, rpt, target in zip( + (tetrahedron, square, octahedron, dodecahedron, icosahedron), + (4, 8, 6, 20, 12), + (3, 4, 4, 5, 5), + (12, 24, 24, 60, 60)): + check(h, size, rpt, target) + + +def test_pgroups(): + from sympy.combinatorics.polyhedron import (cube, tetrahedron_faces, + octahedron_faces, dodecahedron_faces, icosahedron_faces) + from sympy.combinatorics.polyhedron import _pgroup_calcs + (tetrahedron2, cube2, octahedron2, dodecahedron2, icosahedron2, + tetrahedron_faces2, cube_faces2, octahedron_faces2, + dodecahedron_faces2, icosahedron_faces2) = _pgroup_calcs() + + assert tetrahedron == tetrahedron2 + assert cube == cube2 + assert octahedron == octahedron2 + assert dodecahedron == dodecahedron2 + assert icosahedron == icosahedron2 + assert sorted(map(sorted, tetrahedron_faces)) == sorted(map(sorted, tetrahedron_faces2)) + assert sorted(cube_faces) == sorted(cube_faces2) + assert sorted(octahedron_faces) == sorted(octahedron_faces2) + assert sorted(dodecahedron_faces) == sorted(dodecahedron_faces2) + assert sorted(icosahedron_faces) == sorted(icosahedron_faces2) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_prufer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_prufer.py new file mode 100644 index 0000000000000000000000000000000000000000..b077c7cf3f023a4c36d7039505e6165ab29f275a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_prufer.py @@ -0,0 +1,74 @@ +from sympy.combinatorics.prufer import Prufer +from sympy.testing.pytest import raises + + +def test_prufer(): + # number of nodes is optional + assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]], 5).nodes == 5 + assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]]).nodes == 5 + + a = Prufer([[0, 1], [0, 2], [0, 3], [0, 4]]) + assert a.rank == 0 + assert a.nodes == 5 + assert a.prufer_repr == [0, 0, 0] + + a = Prufer([[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]]) + assert a.rank == 924 + assert a.nodes == 6 + assert a.tree_repr == [[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]] + assert a.prufer_repr == [4, 1, 4, 0] + + assert Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) == \ + ([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7) + assert Prufer([0]*4).size == Prufer([6]*4).size == 1296 + + # accept iterables but convert to list of lists + tree = [(0, 1), (1, 5), (0, 3), (0, 2), (2, 6), (4, 7), (2, 4)] + tree_lists = [list(t) for t in tree] + assert Prufer(tree).tree_repr == tree_lists + assert sorted(Prufer(set(tree)).tree_repr) == sorted(tree_lists) + + raises(ValueError, lambda: Prufer([[1, 2], [3, 4]])) # 0 is missing + raises(ValueError, lambda: Prufer([[2, 3], [3, 4]])) # 0, 1 are missing + assert Prufer(*Prufer.edges([1, 2], [3, 4])).prufer_repr == [1, 3] + raises(ValueError, lambda: Prufer.edges( + [1, 3], [3, 4])) # a broken tree but edges doesn't care + raises(ValueError, lambda: Prufer.edges([1, 2], [5, 6])) + raises(ValueError, lambda: Prufer([[]])) + + a = Prufer([[0, 1], [0, 2], [0, 3]]) + b = a.next() + assert b.tree_repr == [[0, 2], [0, 1], [1, 3]] + assert b.rank == 1 + + +def test_round_trip(): + def doit(t, b): + e, n = Prufer.edges(*t) + t = Prufer(e, n) + a = sorted(t.tree_repr) + b = [i - 1 for i in b] + assert t.prufer_repr == b + assert sorted(Prufer(b).tree_repr) == a + assert Prufer.unrank(t.rank, n).prufer_repr == b + + doit([[1, 2]], []) + doit([[2, 1, 3]], [1]) + doit([[1, 3, 2]], [3]) + doit([[1, 2, 3]], [2]) + doit([[2, 1, 4], [1, 3]], [1, 1]) + doit([[3, 2, 1, 4]], [2, 1]) + doit([[3, 2, 1], [2, 4]], [2, 2]) + doit([[1, 3, 2, 4]], [3, 2]) + doit([[1, 4, 2, 3]], [4, 2]) + doit([[3, 1, 4, 2]], [4, 1]) + doit([[4, 2, 1, 3]], [1, 2]) + doit([[1, 2, 4, 3]], [2, 4]) + doit([[1, 3, 4, 2]], [3, 4]) + doit([[2, 4, 1], [4, 3]], [4, 4]) + doit([[1, 2, 3, 4]], [2, 3]) + doit([[2, 3, 1], [3, 4]], [3, 3]) + doit([[1, 4, 3, 2]], [4, 3]) + doit([[2, 1, 4, 3]], [1, 4]) + doit([[2, 1, 3, 4]], [1, 3]) + doit([[6, 2, 1, 4], [1, 3, 5, 8], [3, 7]], [1, 2, 1, 3, 3, 5]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_rewriting.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_rewriting.py new file mode 100644 index 0000000000000000000000000000000000000000..97c562bd57a2cd6318fa1dcb13c6f6278c861cca --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_rewriting.py @@ -0,0 +1,49 @@ +from sympy.combinatorics.fp_groups import FpGroup +from sympy.combinatorics.free_groups import free_group +from sympy.testing.pytest import raises + + +def test_rewriting(): + F, a, b = free_group("a, b") + G = FpGroup(F, [a*b*a**-1*b**-1]) + a, b = G.generators + R = G._rewriting_system + assert R.is_confluent + + assert G.reduce(b**-1*a) == a*b**-1 + assert G.reduce(b**3*a**4*b**-2*a) == a**5*b + assert G.equals(b**2*a**-1*b, b**4*a**-1*b**-1) + + assert R.reduce_using_automaton(b*a*a**2*b**-1) == a**3 + assert R.reduce_using_automaton(b**3*a**4*b**-2*a) == a**5*b + assert R.reduce_using_automaton(b**-1*a) == a*b**-1 + + G = FpGroup(F, [a**3, b**3, (a*b)**2]) + R = G._rewriting_system + R.make_confluent() + # R._is_confluent should be set to True after + # a successful run of make_confluent + assert R.is_confluent + # but also the system should actually be confluent + assert R._check_confluence() + assert G.reduce(b*a**-1*b**-1*a**3*b**4*a**-1*b**-15) == a**-1*b**-1 + # check for automaton reduction + assert R.reduce_using_automaton(b*a**-1*b**-1*a**3*b**4*a**-1*b**-15) == a**-1*b**-1 + + G = FpGroup(F, [a**2, b**3, (a*b)**4]) + R = G._rewriting_system + assert G.reduce(a**2*b**-2*a**2*b) == b**-1 + assert R.reduce_using_automaton(a**2*b**-2*a**2*b) == b**-1 + assert G.reduce(a**3*b**-2*a**2*b) == a**-1*b**-1 + assert R.reduce_using_automaton(a**3*b**-2*a**2*b) == a**-1*b**-1 + # Check after adding a rule + R.add_rule(a**2, b) + assert R.reduce_using_automaton(a**2*b**-2*a**2*b) == b**-1 + assert R.reduce_using_automaton(a**4*b**-2*a**2*b**3) == b + + R.set_max(15) + raises(RuntimeError, lambda: R.add_rule(a**-3, b)) + R.set_max(20) + R.add_rule(a**-3, b) + + assert R.add_rule(a, a) == set() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_schur_number.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_schur_number.py new file mode 100644 index 0000000000000000000000000000000000000000..e6beb9b11fa993a99b71d89b8485050fc3575b8e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_schur_number.py @@ -0,0 +1,55 @@ +from sympy.core import S, Rational +from sympy.combinatorics.schur_number import schur_partition, SchurNumber +from sympy.core.random import _randint +from sympy.testing.pytest import raises +from sympy.core.symbol import symbols + + +def _sum_free_test(subset): + """ + Checks if subset is sum-free(There are no x,y,z in the subset such that + x + y = z) + """ + for i in subset: + for j in subset: + assert (i + j in subset) is False + + +def test_schur_partition(): + raises(ValueError, lambda: schur_partition(S.Infinity)) + raises(ValueError, lambda: schur_partition(-1)) + raises(ValueError, lambda: schur_partition(0)) + assert schur_partition(2) == [[1, 2]] + + random_number_generator = _randint(1000) + for _ in range(5): + n = random_number_generator(1, 1000) + result = schur_partition(n) + t = 0 + numbers = [] + for item in result: + _sum_free_test(item) + """ + Checks if the occurrence of all numbers is exactly one + """ + t += len(item) + for l in item: + assert (l in numbers) is False + numbers.append(l) + assert n == t + + x = symbols("x") + raises(ValueError, lambda: schur_partition(x)) + +def test_schur_number(): + first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44, 5: 160} + for k in first_known_schur_numbers: + assert SchurNumber(k) == first_known_schur_numbers[k] + + assert SchurNumber(S.Infinity) == S.Infinity + assert SchurNumber(0) == 0 + raises(ValueError, lambda: SchurNumber(0.5)) + + n = symbols("n") + assert SchurNumber(n).lower_bound() == 3**n/2 - Rational(1, 2) + assert SchurNumber(8).lower_bound() == 5039 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_subsets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_subsets.py new file mode 100644 index 0000000000000000000000000000000000000000..1d50076da1c685294c2d2561dcc2a6af629eaf83 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_subsets.py @@ -0,0 +1,63 @@ +from sympy.combinatorics.subsets import Subset, ksubsets +from sympy.testing.pytest import raises + + +def test_subset(): + a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) + assert a.next_binary() == Subset(['b'], ['a', 'b', 'c', 'd']) + assert a.prev_binary() == Subset(['c'], ['a', 'b', 'c', 'd']) + assert a.next_lexicographic() == Subset(['d'], ['a', 'b', 'c', 'd']) + assert a.prev_lexicographic() == Subset(['c'], ['a', 'b', 'c', 'd']) + assert a.next_gray() == Subset(['c'], ['a', 'b', 'c', 'd']) + assert a.prev_gray() == Subset(['d'], ['a', 'b', 'c', 'd']) + assert a.rank_binary == 3 + assert a.rank_lexicographic == 14 + assert a.rank_gray == 2 + assert a.cardinality == 16 + assert a.size == 2 + assert Subset.bitlist_from_subset(a, ['a', 'b', 'c', 'd']) == '0011' + + a = Subset([2, 5, 7], [1, 2, 3, 4, 5, 6, 7]) + assert a.next_binary() == Subset([2, 5, 6], [1, 2, 3, 4, 5, 6, 7]) + assert a.prev_binary() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7]) + assert a.next_lexicographic() == Subset([2, 6], [1, 2, 3, 4, 5, 6, 7]) + assert a.prev_lexicographic() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]) + assert a.next_gray() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]) + assert a.prev_gray() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7]) + assert a.rank_binary == 37 + assert a.rank_lexicographic == 93 + assert a.rank_gray == 57 + assert a.cardinality == 128 + + superset = ['a', 'b', 'c', 'd'] + assert Subset.unrank_binary(4, superset).rank_binary == 4 + assert Subset.unrank_gray(10, superset).rank_gray == 10 + + superset = [1, 2, 3, 4, 5, 6, 7, 8, 9] + assert Subset.unrank_binary(33, superset).rank_binary == 33 + assert Subset.unrank_gray(25, superset).rank_gray == 25 + + a = Subset([], ['a', 'b', 'c', 'd']) + i = 1 + while a.subset != Subset(['d'], ['a', 'b', 'c', 'd']).subset: + a = a.next_lexicographic() + i = i + 1 + assert i == 16 + + i = 1 + while a.subset != Subset([], ['a', 'b', 'c', 'd']).subset: + a = a.prev_lexicographic() + i = i + 1 + assert i == 16 + + raises(ValueError, lambda: Subset(['a', 'b'], ['a'])) + raises(ValueError, lambda: Subset(['a'], ['b', 'c'])) + raises(ValueError, lambda: Subset.subset_from_bitlist(['a', 'b'], '010')) + + assert Subset(['a'], ['a', 'b']) != Subset(['b'], ['a', 'b']) + assert Subset(['a'], ['a', 'b']) != Subset(['a'], ['a', 'c']) + +def test_ksubsets(): + assert list(ksubsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] + assert list(ksubsets([1, 2, 3, 4, 5], 2)) == [(1, 2), (1, 3), (1, 4), + (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_tensor_can.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_tensor_can.py new file mode 100644 index 0000000000000000000000000000000000000000..3922419f20b92536426bfaae4b7e94df5db671b5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_tensor_can.py @@ -0,0 +1,560 @@ +from sympy.combinatorics.permutations import Permutation, Perm +from sympy.combinatorics.tensor_can import (perm_af_direct_product, dummy_sgs, + riemann_bsgs, get_symmetric_group_sgs, canonicalize, bsgs_direct_product) +from sympy.combinatorics.testutil import canonicalize_naive, graph_certificate +from sympy.testing.pytest import skip, XFAIL + +def test_perm_af_direct_product(): + gens1 = [[1,0,2,3], [0,1,3,2]] + gens2 = [[1,0]] + assert perm_af_direct_product(gens1, gens2, 0) == [[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]] + gens1 = [[1,0,2,3,5,4], [0,1,3,2,4,5]] + gens2 = [[1,0,2,3]] + assert [[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]] + +def test_dummy_sgs(): + a = dummy_sgs([1,2], 0, 4) + assert a == [[0,2,1,3,4,5]] + a = dummy_sgs([2,3,4,5], 0, 8) + assert a == [x._array_form for x in [Perm(9)(2,3), Perm(9)(4,5), + Perm(9)(2,4)(3,5)]] + + a = dummy_sgs([2,3,4,5], 1, 8) + assert a == [x._array_form for x in [Perm(2,3)(8,9), Perm(4,5)(8,9), + Perm(9)(2,4)(3,5)]] + +def test_get_symmetric_group_sgs(): + assert get_symmetric_group_sgs(2) == ([0], [Permutation(3)(0,1)]) + assert get_symmetric_group_sgs(2, 1) == ([0], [Permutation(0,1)(2,3)]) + assert get_symmetric_group_sgs(3) == ([0,1], [Permutation(4)(0,1), Permutation(4)(1,2)]) + assert get_symmetric_group_sgs(3, 1) == ([0,1], [Permutation(0,1)(3,4), Permutation(1,2)(3,4)]) + assert get_symmetric_group_sgs(4) == ([0,1,2], [Permutation(5)(0,1), Permutation(5)(1,2), Permutation(5)(2,3)]) + assert get_symmetric_group_sgs(4, 1) == ([0,1,2], [Permutation(0,1)(4,5), Permutation(1,2)(4,5), Permutation(2,3)(4,5)]) + + +def test_canonicalize_no_slot_sym(): + # cases in which there is no slot symmetry after fixing the + # free indices; here and in the following if the symmetry of the + # metric is not specified, it is assumed to be symmetric. + # If it is not specified, tensors are commuting. + + # A_d0 * B^d0; g = [1,0, 2,3]; T_c = A^d0*B_d0; can = [0,1,2,3] + base1, gens1 = get_symmetric_group_sgs(1) + dummies = [0, 1] + g = Permutation([1,0,2,3]) + can = canonicalize(g, dummies, 0, (base1,gens1,1,0), (base1,gens1,1,0)) + assert can == [0,1,2,3] + # equivalently + can = canonicalize(g, dummies, 0, (base1, gens1, 2, None)) + assert can == [0,1,2,3] + + # with antisymmetric metric; T_c = -A^d0*B_d0; can = [0,1,3,2] + can = canonicalize(g, dummies, 1, (base1,gens1,1,0), (base1,gens1,1,0)) + assert can == [0,1,3,2] + + # A^a * B^b; ord = [a,b]; g = [0,1,2,3]; can = g + g = Permutation([0,1,2,3]) + dummies = [] + t0 = t1 = (base1, gens1, 1, 0) + can = canonicalize(g, dummies, 0, t0, t1) + assert can == [0,1,2,3] + # B^b * A^a + g = Permutation([1,0,2,3]) + can = canonicalize(g, dummies, 0, t0, t1) + assert can == [1,0,2,3] + + # A symmetric + # A^{b}_{d0}*A^{d0, a} order a,b,d0,-d0; T_c = A^{a d0}*A{b}_{d0} + # g = [1,3,2,0,4,5]; can = [0,2,1,3,4,5] + base2, gens2 = get_symmetric_group_sgs(2) + dummies = [2,3] + g = Permutation([1,3,2,0,4,5]) + can = canonicalize(g, dummies, 0, (base2, gens2, 2, 0)) + assert can == [0, 2, 1, 3, 4, 5] + # with antisymmetric metric + can = canonicalize(g, dummies, 1, (base2, gens2, 2, 0)) + assert can == [0, 2, 1, 3, 4, 5] + # A^{a}_{d0}*A^{d0, b} + g = Permutation([0,3,2,1,4,5]) + can = canonicalize(g, dummies, 1, (base2, gens2, 2, 0)) + assert can == [0, 2, 1, 3, 5, 4] + + # A, B symmetric + # A^b_d0*B^{d0,a}; g=[1,3,2,0,4,5] + # T_c = A^{b,d0}*B_{a,d0}; can = [1,2,0,3,4,5] + dummies = [2,3] + g = Permutation([1,3,2,0,4,5]) + can = canonicalize(g, dummies, 0, (base2,gens2,1,0), (base2,gens2,1,0)) + assert can == [1,2,0,3,4,5] + # same with antisymmetric metric + can = canonicalize(g, dummies, 1, (base2,gens2,1,0), (base2,gens2,1,0)) + assert can == [1,2,0,3,5,4] + + # A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5] + # T_c = A^{d0 d1}*B_d0*C_d1; can = [0,2,1,3,4,5] + base1, gens1 = get_symmetric_group_sgs(1) + base2, gens2 = get_symmetric_group_sgs(2) + g = Permutation([2,1,0,3,4,5]) + dummies = [0,1,2,3] + t0 = (base2, gens2, 1, 0) + t1 = t2 = (base1, gens1, 1, 0) + can = canonicalize(g, dummies, 0, t0, t1, t2) + assert can == [0, 2, 1, 3, 4, 5] + + # A without symmetry + # A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5] + # T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5] + g = Permutation([2,1,0,3,4,5]) + dummies = [0,1,2,3] + t0 = ([], [Permutation(list(range(4)))], 1, 0) + can = canonicalize(g, dummies, 0, t0, t1, t2) + assert can == [0,2,3,1,4,5] + # A, B without symmetry + # A^{d1}_{d0}*B_{d1}^{d0}; g = [2,1,3,0,4,5] + # T_c = A^{d0 d1}*B_{d0 d1}; can = [0,2,1,3,4,5] + t0 = t1 = ([], [Permutation(list(range(4)))], 1, 0) + dummies = [0,1,2,3] + g = Permutation([2,1,3,0,4,5]) + can = canonicalize(g, dummies, 0, t0, t1) + assert can == [0, 2, 1, 3, 4, 5] + # A_{d0}^{d1}*B_{d1}^{d0}; g = [1,2,3,0,4,5] + # T_c = A^{d0 d1}*B_{d1 d0}; can = [0,2,3,1,4,5] + g = Permutation([1,2,3,0,4,5]) + can = canonicalize(g, dummies, 0, t0, t1) + assert can == [0,2,3,1,4,5] + + # A, B, C without symmetry + # A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1] + # g=[4,2,0,3,5,1,6,7] + # T_c=A^{d0 d1}*B_{a d1}*C_{d0 b}; can = [2,4,0,5,3,1,6,7] + t0 = t1 = t2 = ([], [Permutation(list(range(4)))], 1, 0) + dummies = [2,3,4,5] + g = Permutation([4,2,0,3,5,1,6,7]) + can = canonicalize(g, dummies, 0, t0, t1, t2) + assert can == [2,4,0,5,3,1,6,7] + + # A symmetric, B and C without symmetry + # A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1] + # g=[4,2,0,3,5,1,6,7] + # T_c = A^{d0 d1}*B_{a d0}*C_{d1 b}; can = [2,4,0,3,5,1,6,7] + t0 = (base2,gens2,1,0) + t1 = t2 = ([], [Permutation(list(range(4)))], 1, 0) + dummies = [2,3,4,5] + g = Permutation([4,2,0,3,5,1,6,7]) + can = canonicalize(g, dummies, 0, t0, t1, t2) + assert can == [2,4,0,3,5,1,6,7] + + # A and C symmetric, B without symmetry + # A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1] + # g=[4,2,0,3,5,1,6,7] + # T_c = A^{d0 d1}*B_{a d0}*C_{b d1}; can = [2,4,0,3,1,5,6,7] + t0 = t2 = (base2,gens2,1,0) + t1 = ([], [Permutation(list(range(4)))], 1, 0) + dummies = [2,3,4,5] + g = Permutation([4,2,0,3,5,1,6,7]) + can = canonicalize(g, dummies, 0, t0, t1, t2) + assert can == [2,4,0,3,1,5,6,7] + + # A symmetric, B without symmetry, C antisymmetric + # A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1] + # g=[4,2,0,3,5,1,6,7] + # T_c = -A^{d0 d1}*B_{a d0}*C_{b d1}; can = [2,4,0,3,1,5,7,6] + t0 = (base2,gens2, 1, 0) + t1 = ([], [Permutation(list(range(4)))], 1, 0) + base2a, gens2a = get_symmetric_group_sgs(2, 1) + t2 = (base2a, gens2a, 1, 0) + dummies = [2,3,4,5] + g = Permutation([4,2,0,3,5,1,6,7]) + can = canonicalize(g, dummies, 0, t0, t1, t2) + assert can == [2,4,0,3,1,5,7,6] + + +def test_canonicalize_no_dummies(): + base1, gens1 = get_symmetric_group_sgs(1) + base2, gens2 = get_symmetric_group_sgs(2) + base2a, gens2a = get_symmetric_group_sgs(2, 1) + + # A commuting + # A^c A^b A^a; ord = [a,b,c]; g = [2,1,0,3,4] + # T_c = A^a A^b A^c; can = list(range(5)) + g = Permutation([2,1,0,3,4]) + can = canonicalize(g, [], 0, (base1, gens1, 3, 0)) + assert can == list(range(5)) + + # A anticommuting + # A^c A^b A^a; ord = [a,b,c]; g = [2,1,0,3,4] + # T_c = -A^a A^b A^c; can = [0,1,2,4,3] + g = Permutation([2,1,0,3,4]) + can = canonicalize(g, [], 0, (base1, gens1, 3, 1)) + assert can == [0,1,2,4,3] + + # A commuting and symmetric + # A^{b,d}*A^{c,a}; ord = [a,b,c,d]; g = [1,3,2,0,4,5] + # T_c = A^{a c}*A^{b d}; can = [0,2,1,3,4,5] + g = Permutation([1,3,2,0,4,5]) + can = canonicalize(g, [], 0, (base2, gens2, 2, 0)) + assert can == [0,2,1,3,4,5] + + # A anticommuting and symmetric + # A^{b,d}*A^{c,a}; ord = [a,b,c,d]; g = [1,3,2,0,4,5] + # T_c = -A^{a c}*A^{b d}; can = [0,2,1,3,5,4] + g = Permutation([1,3,2,0,4,5]) + can = canonicalize(g, [], 0, (base2, gens2, 2, 1)) + assert can == [0,2,1,3,5,4] + # A^{c,a}*A^{b,d} ; g = [2,0,1,3,4,5] + # T_c = A^{a c}*A^{b d}; can = [0,2,1,3,4,5] + g = Permutation([2,0,1,3,4,5]) + can = canonicalize(g, [], 0, (base2, gens2, 2, 1)) + assert can == [0,2,1,3,4,5] + +def test_no_metric_symmetry(): + # no metric symmetry + # A^d1_d0 * A^d0_d1; ord = [d0,-d0,d1,-d1]; g= [2,1,0,3,4,5] + # T_c = A^d0_d1 * A^d1_d0; can = [0,3,2,1,4,5] + g = Permutation([2,1,0,3,4,5]) + can = canonicalize(g, list(range(4)), None, [[], [Permutation(list(range(4)))], 2, 0]) + assert can == [0,3,2,1,4,5] + + # A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0 + # ord = [d0,-d0,d1,-d1,d2,-d2,d3,-d3] + # 0 1 2 3 4 5 6 7 + # g = [2,5,0,7,4,3,6,1,8,9] + # T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2 + # can = [0,3,2,1,4,7,6,5,8,9] + g = Permutation([2,5,0,7,4,3,6,1,8,9]) + #can = canonicalize(g, list(range(8)), 0, [[], [list(range(4))], 4, 0]) + #assert can == [0, 2, 3, 1, 4, 6, 7, 5, 8, 9] + can = canonicalize(g, list(range(8)), None, [[], [Permutation(list(range(4)))], 4, 0]) + assert can == [0, 3, 2, 1, 4, 7, 6, 5, 8, 9] + + # A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1 + # g = [0,5,2,7,6,1,4,3,8,9] + # T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0 + # can = [0,3,2,5,4,7,6,1,8,9] + g = Permutation([0,5,2,7,6,1,4,3,8,9]) + can = canonicalize(g, list(range(8)), None, [[], [Permutation(list(range(4)))], 4, 0]) + assert can == [0,3,2,5,4,7,6,1,8,9] + + g = Permutation([12,7,10,3,14,13,4,11,6,1,2,9,0,15,8,5,16,17]) + can = canonicalize(g, list(range(16)), None, [[], [Permutation(list(range(4)))], 8, 0]) + assert can == [0,3,2,5,4,7,6,1,8,11,10,13,12,15,14,9,16,17] + +def test_canonical_free(): + # t = A^{d0 a1}*A_d0^a0 + # ord = [a0,a1,d0,-d0]; g = [2,1,3,0,4,5]; dummies = [[2,3]] + # t_c = A_d0^a0*A^{d0 a1} + # can = [3,0, 2,1, 4,5] + g = Permutation([2,1,3,0,4,5]) + dummies = [[2,3]] + can = canonicalize(g, dummies, [None], ([], [Permutation(3)], 2, 0)) + assert can == [3,0, 2,1, 4,5] + +def test_canonicalize1(): + base1, gens1 = get_symmetric_group_sgs(1) + base1a, gens1a = get_symmetric_group_sgs(1, 1) + base2, gens2 = get_symmetric_group_sgs(2) + base3, gens3 = get_symmetric_group_sgs(3) + base2a, gens2a = get_symmetric_group_sgs(2, 1) + base3a, gens3a = get_symmetric_group_sgs(3, 1) + + # A_d0*A^d0; ord = [d0,-d0]; g = [1,0,2,3] + # T_c = A^d0*A_d0; can = [0,1,2,3] + g = Permutation([1,0,2,3]) + can = canonicalize(g, [0, 1], 0, (base1, gens1, 2, 0)) + assert can == list(range(4)) + + # A commuting + # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0; ord=[d0,-d0,d1,-d1,d2,-d2] + # g = [1,3,5,4,2,0,6,7] + # T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2; can = list(range(8)) + g = Permutation([1,3,5,4,2,0,6,7]) + can = canonicalize(g, list(range(6)), 0, (base1, gens1, 6, 0)) + assert can == list(range(8)) + + # A anticommuting + # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0; ord=[d0,-d0,d1,-d1,d2,-d2] + # g = [1,3,5,4,2,0,6,7] + # T_c 0; can = 0 + g = Permutation([1,3,5,4,2,0,6,7]) + can = canonicalize(g, list(range(6)), 0, (base1, gens1, 6, 1)) + assert can == 0 + can1 = canonicalize_naive(g, list(range(6)), 0, (base1, gens1, 6, 1)) + assert can1 == 0 + + # A commuting symmetric + # A^{d0 b}*A^a_d1*A^d1_d0; ord=[a,b,d0,-d0,d1,-d1] + # g = [2,1,0,5,4,3,6,7] + # T_c = A^{a d0}*A^{b d1}*A_{d0 d1}; can = [0,2,1,4,3,5,6,7] + g = Permutation([2,1,0,5,4,3,6,7]) + can = canonicalize(g, list(range(2,6)), 0, (base2, gens2, 3, 0)) + assert can == [0,2,1,4,3,5,6,7] + + # A, B commuting symmetric + # A^{d0 b}*A^d1_d0*B^a_d1; ord=[a,b,d0,-d0,d1,-d1] + # g = [2,1,4,3,0,5,6,7] + # T_c = A^{b d0}*A_d0^d1*B^a_d1; can = [1,2,3,4,0,5,6,7] + g = Permutation([2,1,4,3,0,5,6,7]) + can = canonicalize(g, list(range(2,6)), 0, (base2,gens2,2,0), (base2,gens2,1,0)) + assert can == [1,2,3,4,0,5,6,7] + + # A commuting symmetric + # A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1] + # g = [4,2,1,0,5,3,6,7] + # T_c = A^{a d0 d1}*A^{b}_{d0 d1}; can = [0,2,4,1,3,5,6,7] + g = Permutation([4,2,1,0,5,3,6,7]) + can = canonicalize(g, list(range(2,6)), 0, (base3, gens3, 2, 0)) + assert can == [0,2,4,1,3,5,6,7] + + + # A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0 + # ord = [a0,a1,a2,a3,d0,-d0,d1,-d1,d2,-d2,d3,-d3] + # 0 1 2 3 4 5 6 7 8 9 10 11 + # g = [10,4,8, 0,7,9, 6,11,1, 2,3,5, 12,13] + # T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3} + # can = [0,4,6, 1,5,8, 2,3,10, 7,9,11, 12,13] + g = Permutation([10,4,8, 0,7,9, 6,11,1, 2,3,5, 12,13]) + can = canonicalize(g, list(range(4,12)), 0, (base3, gens3, 4, 0)) + assert can == [0,4,6, 1,5,8, 2,3,10, 7,9,11, 12,13] + + # A commuting symmetric, B antisymmetric + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # ord = [d0,-d0,d1,-d1,d2,-d2,d3,-d3] + # g = [0,2,4,5,7,3,1,6,8,9] + # in this esxample and in the next three, + # renaming dummy indices and using symmetry of A, + # T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3 + # can = 0 + g = Permutation([0,2,4,5,7,3,1,6,8,9]) + can = canonicalize(g, list(range(8)), 0, (base3, gens3,2,0), (base2a,gens2a,1,0)) + assert can == 0 + # A anticommuting symmetric, B anticommuting + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3} + # can = [0,2,4, 1,3,6, 5,7, 8,9] + can = canonicalize(g, list(range(8)), 0, (base3, gens3,2,1), (base2a,gens2a,1,0)) + assert can == [0,2,4, 1,3,6, 5,7, 8,9] + # A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3} + # can = [0,2,4, 1,3,6, 5,7, 9,8] + can = canonicalize(g, list(range(8)), 1, (base3, gens3,2,1), (base2a,gens2a,1,0)) + assert can == [0,2,4, 1,3,6, 5,7, 9,8] + + # A anticommuting symmetric, B anticommuting anticommuting, + # no metric symmetry + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3 + # can = [0,2,4, 1,3,7, 5,6, 8,9] + can = canonicalize(g, list(range(8)), None, (base3, gens3,2,1), (base2a,gens2a,1,0)) + assert can == [0,2,4,1,3,7,5,6,8,9] + + # Gamma anticommuting + # Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha} + # ord = [alpha, rho, mu,-mu,nu,-nu] + # g = [3,5,1,4,2,0,6,7] + # T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu} + # can = [2,4,1,0,3,5,7,6]] + g = Permutation([3,5,1,4,2,0,6,7]) + t0 = (base2a, gens2a, 1, None) + t1 = (base1, gens1, 1, None) + t2 = (base3a, gens3a, 1, None) + can = canonicalize(g, list(range(2, 6)), 0, t0, t1, t2) + assert can == [2,4,1,0,3,5,7,6] + + # Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha} + # ord = [alpha, beta, gamma, -rho, mu,-mu,nu,-nu] + # 0 1 2 3 4 5 6 7 + # g = [5,7,2,1,3,6,4,0,8,9] + # T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu} # can = [4,6,1,2,3,0,5,7,8,9] + t0 = (base2a, gens2a, 2, None) + g = Permutation([5,7,2,1,3,6,4,0,8,9]) + can = canonicalize(g, list(range(4, 8)), 0, t0, t1, t2) + assert can == [4,6,1,2,3,0,5,7,8,9] + + # f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry + # f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b} + # ord = [mu,-mu,nu,-nu,a,-a,b,-b,c,-c,d,-d, e, -e] + # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 + # g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15] + # T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e} + # can = [4,6,8, 5,10,12, 0,7, 1,11, 2,9, 3,13, 15,14] + g = Permutation([8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15]) + base_f, gens_f = bsgs_direct_product(base1, gens1, base2a, gens2a) + base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1) + t0 = (base_f, gens_f, 2, 0) + t1 = (base_A, gens_A, 4, 0) + can = canonicalize(g, [list(range(4)), list(range(4, 14))], [0, 0], t0, t1) + assert can == [4,6,8, 5,10,12, 0,7, 1,11, 2,9, 3,13, 15,14] + + +def test_riemann_invariants(): + baser, gensr = riemann_bsgs + # R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1]; g = [0,2,3,1,4,5] + # T_c = -R^{d0 d1}_{d0 d1}; can = [0,2,1,3,5,4] + g = Permutation([0,2,3,1,4,5]) + can = canonicalize(g, list(range(2, 4)), 0, (baser, gensr, 1, 0)) + assert can == [0,2,1,3,5,4] + # use a non minimal BSGS + can = canonicalize(g, list(range(2, 4)), 0, ([2, 0], [Permutation([1,0,2,3,5,4]), Permutation([2,3,0,1,4,5])], 1, 0)) + assert can == [0,2,1,3,5,4] + + """ + The following tests in test_riemann_invariants and in + test_riemann_invariants1 have been checked using xperm.c from XPerm in + in [1] and with an older version contained in [2] + + [1] xperm.c part of xPerm written by J. M. Martin-Garcia + http://www.xact.es/index.html + [2] test_xperm.cc in cadabra by Kasper Peeters, http://cadabra.phi-sci.com/ + """ + # R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} * + # R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10} + # ord: contravariant d_k ->2*k, covariant d_k -> 2*k+1 + # T_c = R^{d0 d1 d2 d3} * R_{d0 d1}^{d4 d5} * R_{d2 d3}^{d6 d7} * + # R_{d4 d5}^{d8 d9} * R_{d6 d7}^{d10 d11} * R_{d8 d9 d10 d11} + g = Permutation([23,2,1,10,12,8,0,11,15,5,17,19,21,7,13,9,4,14,22,3,16,18,6,20,24,25]) + can = canonicalize(g, list(range(24)), 0, (baser, gensr, 6, 0)) + assert can == [0,2,4,6,1,3,8,10,5,7,12,14,9,11,16,18,13,15,20,22,17,19,21,23,24,25] + + # use a non minimal BSGS + can = canonicalize(g, list(range(24)), 0, ([2, 0], [Permutation([1,0,2,3,5,4]), Permutation([2,3,0,1,4,5])], 6, 0)) + assert can == [0,2,4,6,1,3,8,10,5,7,12,14,9,11,16,18,13,15,20,22,17,19,21,23,24,25] + + g = Permutation([0,2,5,7,4,6,9,11,8,10,13,15,12,14,17,19,16,18,21,23,20,22,25,27,24,26,29,31,28,30,33,35,32,34,37,39,36,38,1,3,40,41]) + can = canonicalize(g, list(range(40)), 0, (baser, gensr, 10, 0)) + assert can == [0,2,4,6,1,3,8,10,5,7,12,14,9,11,16,18,13,15,20,22,17,19,24,26,21,23,28,30,25,27,32,34,29,31,36,38,33,35,37,39,40,41] + + +@XFAIL +def test_riemann_invariants1(): + skip('takes too much time') + baser, gensr = riemann_bsgs + g = Permutation([17, 44, 11, 3, 0, 19, 23, 15, 38, 4, 25, 27, 43, 36, 22, 14, 8, 30, 41, 20, 2, 10, 12, 28, 18, 1, 29, 13, 37, 42, 33, 7, 9, 31, 24, 26, 39, 5, 34, 47, 32, 6, 21, 40, 35, 46, 45, 16, 48, 49]) + can = canonicalize(g, list(range(48)), 0, (baser, gensr, 12, 0)) + assert can == [0, 2, 4, 6, 1, 3, 8, 10, 5, 7, 12, 14, 9, 11, 16, 18, 13, 15, 20, 22, 17, 19, 24, 26, 21, 23, 28, 30, 25, 27, 32, 34, 29, 31, 36, 38, 33, 35, 40, 42, 37, 39, 44, 46, 41, 43, 45, 47, 48, 49] + + g = Permutation([0,2,4,6, 7,8,10,12, 14,16,18,20, 19,22,24,26, 5,21,28,30, 32,34,36,38, 40,42,44,46, 13,48,50,52, 15,49,54,56, 17,33,41,58, 9,23,60,62, 29,35,63,64, 3,45,66,68, 25,37,47,57, 11,31,69,70, 27,39,53,72, 1,59,73,74, 55,61,67,76, 43,65,75,78, 51,71,77,79, 80,81]) + can = canonicalize(g, list(range(80)), 0, (baser, gensr, 20, 0)) + assert can == [0,2,4,6, 1,8,10,12, 3,14,16,18, 5,20,22,24, 7,26,28,30, 9,15,32,34, 11,36,23,38, 13,40,42,44, 17,39,29,46, 19,48,43,50, 21,45,52,54, 25,56,33,58, 27,60,53,62, 31,51,64,66, 35,65,47,68, 37,70,49,72, 41,74,57,76, 55,67,59,78, 61,69,71,75, 63,79,73,77, 80,81] + + +def test_riemann_products(): + baser, gensr = riemann_bsgs + base1, gens1 = get_symmetric_group_sgs(1) + base2, gens2 = get_symmetric_group_sgs(2) + base2a, gens2a = get_symmetric_group_sgs(2, 1) + + # R^{a b d0}_d0 = 0 + g = Permutation([0,1,2,3,4,5]) + can = canonicalize(g, list(range(2,4)), 0, (baser, gensr, 1, 0)) + assert can == 0 + + # R^{d0 b a}_d0 ; ord = [a,b,d0,-d0}; g = [2,1,0,3,4,5] + # T_c = -R^{a d0 b}_d0; can = [0,2,1,3,5,4] + g = Permutation([2,1,0,3,4,5]) + can = canonicalize(g, list(range(2, 4)), 0, (baser, gensr, 1, 0)) + assert can == [0,2,1,3,5,4] + + # R^d1_d2^b_d0 * R^{d0 a}_d1^d2; ord=[a,b,d0,-d0,d1,-d1,d2,-d2] + # g = [4,7,1,3,2,0,5,6,8,9] + # T_c = -R^{a d0 d1 d2}* R^b_{d0 d1 d2} + # can = [0,2,4,6,1,3,5,7,9,8] + g = Permutation([4,7,1,3,2,0,5,6,8,9]) + can = canonicalize(g, list(range(2,8)), 0, (baser, gensr, 2, 0)) + assert can == [0,2,4,6,1,3,5,7,9,8] + can1 = canonicalize_naive(g, list(range(2,8)), 0, (baser, gensr, 2, 0)) + assert can == can1 + + # A symmetric commuting + # R^{d6 d5}_d2^d1 * R^{d4 d0 d2 d3} * A_{d6 d0} A_{d3 d1} * A_{d4 d5} + # g = [12,10,5,2, 8,0,4,6, 13,1, 7,3, 9,11,14,15] + # T_c = -R^{d0 d1 d2 d3} * R_d0^{d4 d5 d6} * A_{d1 d4}*A_{d2 d5}*A_{d3 d6} + + g = Permutation([12,10,5,2,8,0,4,6,13,1,7,3,9,11,14,15]) + can = canonicalize(g, list(range(14)), 0, ((baser,gensr,2,0)), (base2,gens2,3,0)) + assert can == [0, 2, 4, 6, 1, 8, 10, 12, 3, 9, 5, 11, 7, 13, 15, 14] + + # R^{d2 a0 a2 d0} * R^d1_d2^{a1 a3} * R^{a4 a5}_{d0 d1} + # ord = [a0,a1,a2,a3,a4,a5,d0,-d0,d1,-d1,d2,-d2] + # 0 1 2 3 4 5 6 7 8 9 10 11 + # can = [0, 6, 2, 8, 1, 3, 7, 10, 4, 5, 9, 11, 12, 13] + # T_c = R^{a0 d0 a2 d1}*R^{a1 a3}_d0^d2*R^{a4 a5}_{d1 d2} + g = Permutation([10,0,2,6,8,11,1,3,4,5,7,9,12,13]) + can = canonicalize(g, list(range(6,12)), 0, (baser, gensr, 3, 0)) + assert can == [0, 6, 2, 8, 1, 3, 7, 10, 4, 5, 9, 11, 12, 13] + #can1 = canonicalize_naive(g, list(range(6,12)), 0, (baser, gensr, 3, 0)) + #assert can == can1 + + # A^n_{i, j} antisymmetric in i,j + # A_m0^d0_a1 * A_m1^a0_d0; ord = [m0,m1,a0,a1,d0,-d0] + # g = [0,4,3,1,2,5,6,7] + # T_c = -A_{m a1}^d0 * A_m1^a0_d0 + # can = [0,3,4,1,2,5,7,6] + base, gens = bsgs_direct_product(base1, gens1, base2a, gens2a) + dummies = list(range(4, 6)) + g = Permutation([0,4,3,1,2,5,6,7]) + can = canonicalize(g, dummies, 0, (base, gens, 2, 0)) + assert can == [0, 3, 4, 1, 2, 5, 7, 6] + + + # A^n_{i, j} symmetric in i,j + # A^m0_a0^d2 * A^n0_d2^d1 * A^n1_d1^d0 * A_{m0 d0}^a1 + # ordering: first the free indices; then first n, then d + # ord=[n0,n1,a0,a1, m0,-m0,d0,-d0,d1,-d1,d2,-d2] + # 0 1 2 3 4 5 6 7 8 9 10 11] + # g = [4,2,10, 0,11,8, 1,9,6, 5,7,3, 12,13] + # if the dummy indices m_i and d_i were separated, + # one gets + # T_c = A^{n0 d0 d1} * A^n1_d0^d2 * A^m0^a0_d1 * A_m0^a1_d2 + # can = [0, 6, 8, 1, 7, 10, 4, 2, 9, 5, 3, 11, 12, 13] + # If they are not, so can is + # T_c = A^{n0 m0 d0} A^n1_m0^d1 A^{d2 a0}_d0 A_d2^a1_d1 + # can = [0, 4, 6, 1, 5, 8, 10, 2, 7, 11, 3, 9, 12, 13] + # case with single type of indices + + base, gens = bsgs_direct_product(base1, gens1, base2, gens2) + dummies = list(range(4, 12)) + g = Permutation([4,2,10, 0,11,8, 1,9,6, 5,7,3, 12,13]) + can = canonicalize(g, dummies, 0, (base, gens, 4, 0)) + assert can == [0, 4, 6, 1, 5, 8, 10, 2, 7, 11, 3, 9, 12, 13] + # case with separated indices + dummies = [list(range(4, 6)), list(range(6,12))] + sym = [0, 0] + can = canonicalize(g, dummies, sym, (base, gens, 4, 0)) + assert can == [0, 6, 8, 1, 7, 10, 4, 2, 9, 5, 3, 11, 12, 13] + # case with separated indices with the second type of index + # with antisymmetric metric: there is a sign change + sym = [0, 1] + can = canonicalize(g, dummies, sym, (base, gens, 4, 0)) + assert can == [0, 6, 8, 1, 7, 10, 4, 2, 9, 5, 3, 11, 13, 12] + +def test_graph_certificate(): + # test tensor invariants constructed from random regular graphs; + # checked graph isomorphism with networkx + import random + def randomize_graph(size, g): + p = list(range(size)) + random.shuffle(p) + g1a = {} + for k, v in g1.items(): + g1a[p[k]] = [p[i] for i in v] + return g1a + + g1 = {0: [2, 3, 7], 1: [4, 5, 7], 2: [0, 4, 6], 3: [0, 6, 7], 4: [1, 2, 5], 5: [1, 4, 6], 6: [2, 3, 5], 7: [0, 1, 3]} + g2 = {0: [2, 3, 7], 1: [2, 4, 5], 2: [0, 1, 5], 3: [0, 6, 7], 4: [1, 5, 6], 5: [1, 2, 4], 6: [3, 4, 7], 7: [0, 3, 6]} + + c1 = graph_certificate(g1) + c2 = graph_certificate(g2) + assert c1 != c2 + g1a = randomize_graph(8, g1) + c1a = graph_certificate(g1a) + assert c1 == c1a + + g1 = {0: [8, 1, 9, 7], 1: [0, 9, 3, 4], 2: [3, 4, 6, 7], 3: [1, 2, 5, 6], 4: [8, 1, 2, 5], 5: [9, 3, 4, 7], 6: [8, 2, 3, 7], 7: [0, 2, 5, 6], 8: [0, 9, 4, 6], 9: [8, 0, 5, 1]} + g2 = {0: [1, 2, 5, 6], 1: [0, 9, 5, 7], 2: [0, 4, 6, 7], 3: [8, 9, 6, 7], 4: [8, 2, 6, 7], 5: [0, 9, 8, 1], 6: [0, 2, 3, 4], 7: [1, 2, 3, 4], 8: [9, 3, 4, 5], 9: [8, 1, 3, 5]} + c1 = graph_certificate(g1) + c2 = graph_certificate(g2) + assert c1 != c2 + g1a = randomize_graph(10, g1) + c1a = graph_certificate(g1a) + assert c1 == c1a diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_testutil.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_testutil.py new file mode 100644 index 0000000000000000000000000000000000000000..736e7a4ff86967e41dca71cf12de6c387a82d26d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_testutil.py @@ -0,0 +1,55 @@ +from sympy.combinatorics.named_groups import SymmetricGroup, AlternatingGroup,\ + CyclicGroup +from sympy.combinatorics.testutil import _verify_bsgs, _cmp_perm_lists,\ + _naive_list_centralizer, _verify_centralizer,\ + _verify_normal_closure +from sympy.combinatorics.permutations import Permutation +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.core.random import shuffle + + +def test_cmp_perm_lists(): + S = SymmetricGroup(4) + els = list(S.generate_dimino()) + other = els.copy() + shuffle(other) + assert _cmp_perm_lists(els, other) is True + + +def test_naive_list_centralizer(): + # verified by GAP + S = SymmetricGroup(3) + A = AlternatingGroup(3) + assert _naive_list_centralizer(S, S) == [Permutation([0, 1, 2])] + assert PermutationGroup(_naive_list_centralizer(S, A)).is_subgroup(A) + + +def test_verify_bsgs(): + S = SymmetricGroup(5) + S.schreier_sims() + base = S.base + strong_gens = S.strong_gens + assert _verify_bsgs(S, base, strong_gens) is True + assert _verify_bsgs(S, base[:-1], strong_gens) is False + assert _verify_bsgs(S, base, S.generators) is False + + +def test_verify_centralizer(): + # verified by GAP + S = SymmetricGroup(3) + A = AlternatingGroup(3) + triv = PermutationGroup([Permutation([0, 1, 2])]) + assert _verify_centralizer(S, S, centr=triv) + assert _verify_centralizer(S, A, centr=A) + + +def test_verify_normal_closure(): + # verified by GAP + S = SymmetricGroup(3) + A = AlternatingGroup(3) + assert _verify_normal_closure(S, A, closure=A) + S = SymmetricGroup(5) + A = AlternatingGroup(5) + C = CyclicGroup(5) + assert _verify_normal_closure(S, A, closure=A) + assert _verify_normal_closure(S, C, closure=A) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_util.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..bca183e81f354e398aee9ae809fe79b20c7f2468 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/tests/test_util.py @@ -0,0 +1,120 @@ +from sympy.combinatorics.named_groups import SymmetricGroup, DihedralGroup,\ + AlternatingGroup +from sympy.combinatorics.permutations import Permutation +from sympy.combinatorics.util import _check_cycles_alt_sym, _strip,\ + _distribute_gens_by_base, _strong_gens_from_distr,\ + _orbits_transversals_from_bsgs, _handle_precomputed_bsgs, _base_ordering,\ + _remove_gens +from sympy.combinatorics.testutil import _verify_bsgs + + +def test_check_cycles_alt_sym(): + perm1 = Permutation([[0, 1, 2, 3, 4, 5, 6], [7], [8], [9]]) + perm2 = Permutation([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9]]) + perm3 = Permutation([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + assert _check_cycles_alt_sym(perm1) is True + assert _check_cycles_alt_sym(perm2) is False + assert _check_cycles_alt_sym(perm3) is False + + +def test_strip(): + D = DihedralGroup(5) + D.schreier_sims() + member = Permutation([4, 0, 1, 2, 3]) + not_member1 = Permutation([0, 1, 4, 3, 2]) + not_member2 = Permutation([3, 1, 4, 2, 0]) + identity = Permutation([0, 1, 2, 3, 4]) + res1 = _strip(member, D.base, D.basic_orbits, D.basic_transversals) + res2 = _strip(not_member1, D.base, D.basic_orbits, D.basic_transversals) + res3 = _strip(not_member2, D.base, D.basic_orbits, D.basic_transversals) + assert res1[0] == identity + assert res1[1] == len(D.base) + 1 + assert res2[0] == not_member1 + assert res2[1] == len(D.base) + 1 + assert res3[0] != identity + assert res3[1] == 2 + + +def test_distribute_gens_by_base(): + base = [0, 1, 2] + gens = [Permutation([0, 1, 2, 3]), Permutation([0, 1, 3, 2]), + Permutation([0, 2, 3, 1]), Permutation([3, 2, 1, 0])] + assert _distribute_gens_by_base(base, gens) == [gens, + [Permutation([0, 1, 2, 3]), + Permutation([0, 1, 3, 2]), + Permutation([0, 2, 3, 1])], + [Permutation([0, 1, 2, 3]), + Permutation([0, 1, 3, 2])]] + + +def test_strong_gens_from_distr(): + strong_gens_distr = [[Permutation([0, 2, 1]), Permutation([1, 2, 0]), + Permutation([1, 0, 2])], [Permutation([0, 2, 1])]] + assert _strong_gens_from_distr(strong_gens_distr) == \ + [Permutation([0, 2, 1]), + Permutation([1, 2, 0]), + Permutation([1, 0, 2])] + + +def test_orbits_transversals_from_bsgs(): + S = SymmetricGroup(4) + S.schreier_sims() + base = S.base + strong_gens = S.strong_gens + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + result = _orbits_transversals_from_bsgs(base, strong_gens_distr) + orbits = result[0] + transversals = result[1] + base_len = len(base) + for i in range(base_len): + for el in orbits[i]: + assert transversals[i][el](base[i]) == el + for j in range(i): + assert transversals[i][el](base[j]) == base[j] + order = 1 + for i in range(base_len): + order *= len(orbits[i]) + assert S.order() == order + + +def test_handle_precomputed_bsgs(): + A = AlternatingGroup(5) + A.schreier_sims() + base = A.base + strong_gens = A.strong_gens + result = _handle_precomputed_bsgs(base, strong_gens) + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + assert strong_gens_distr == result[2] + transversals = result[0] + orbits = result[1] + base_len = len(base) + for i in range(base_len): + for el in orbits[i]: + assert transversals[i][el](base[i]) == el + for j in range(i): + assert transversals[i][el](base[j]) == base[j] + order = 1 + for i in range(base_len): + order *= len(orbits[i]) + assert A.order() == order + + +def test_base_ordering(): + base = [2, 4, 5] + degree = 7 + assert _base_ordering(base, degree) == [3, 4, 0, 5, 1, 2, 6] + + +def test_remove_gens(): + S = SymmetricGroup(10) + base, strong_gens = S.schreier_sims_incremental() + new_gens = _remove_gens(base, strong_gens) + assert _verify_bsgs(S, base, new_gens) is True + A = AlternatingGroup(7) + base, strong_gens = A.schreier_sims_incremental() + new_gens = _remove_gens(base, strong_gens) + assert _verify_bsgs(A, base, new_gens) is True + D = DihedralGroup(2) + base, strong_gens = D.schreier_sims_incremental() + new_gens = _remove_gens(base, strong_gens) + assert _verify_bsgs(D, base, new_gens) is True diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/testutil.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/testutil.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe664ce9e7437b97feec90f2052eb2987c57a4e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/testutil.py @@ -0,0 +1,357 @@ +from sympy.combinatorics import Permutation +from sympy.combinatorics.util import _distribute_gens_by_base + +rmul = Permutation.rmul + + +def _cmp_perm_lists(first, second): + """ + Compare two lists of permutations as sets. + + Explanation + =========== + + This is used for testing purposes. Since the array form of a + permutation is currently a list, Permutation is not hashable + and cannot be put into a set. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy.combinatorics.testutil import _cmp_perm_lists + >>> a = Permutation([0, 2, 3, 4, 1]) + >>> b = Permutation([1, 2, 0, 4, 3]) + >>> c = Permutation([3, 4, 0, 1, 2]) + >>> ls1 = [a, b, c] + >>> ls2 = [b, c, a] + >>> _cmp_perm_lists(ls1, ls2) + True + + """ + return {tuple(a) for a in first} == \ + {tuple(a) for a in second} + + +def _naive_list_centralizer(self, other, af=False): + from sympy.combinatorics.perm_groups import PermutationGroup + """ + Return a list of elements for the centralizer of a subgroup/set/element. + + Explanation + =========== + + This is a brute force implementation that goes over all elements of the + group and checks for membership in the centralizer. It is used to + test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``. + + Examples + ======== + + >>> from sympy.combinatorics.testutil import _naive_list_centralizer + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> D = DihedralGroup(4) + >>> _naive_list_centralizer(D, D) + [Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])] + + See Also + ======== + + sympy.combinatorics.perm_groups.centralizer + + """ + from sympy.combinatorics.permutations import _af_commutes_with + if hasattr(other, 'generators'): + elements = list(self.generate_dimino(af=True)) + gens = [x._array_form for x in other.generators] + commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens) + centralizer_list = [] + if not af: + for element in elements: + if commutes_with_gens(element): + centralizer_list.append(Permutation._af_new(element)) + else: + for element in elements: + if commutes_with_gens(element): + centralizer_list.append(element) + return centralizer_list + elif hasattr(other, 'getitem'): + return _naive_list_centralizer(self, PermutationGroup(other), af) + elif hasattr(other, 'array_form'): + return _naive_list_centralizer(self, PermutationGroup([other]), af) + + +def _verify_bsgs(group, base, gens): + """ + Verify the correctness of a base and strong generating set. + + Explanation + =========== + + This is a naive implementation using the definition of a base and a strong + generating set relative to it. There are other procedures for + verifying a base and strong generating set, but this one will + serve for more robust testing. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AlternatingGroup + >>> from sympy.combinatorics.testutil import _verify_bsgs + >>> A = AlternatingGroup(4) + >>> A.schreier_sims() + >>> _verify_bsgs(A, A.base, A.strong_gens) + True + + See Also + ======== + + sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims + + """ + from sympy.combinatorics.perm_groups import PermutationGroup + strong_gens_distr = _distribute_gens_by_base(base, gens) + current_stabilizer = group + for i in range(len(base)): + candidate = PermutationGroup(strong_gens_distr[i]) + if current_stabilizer.order() != candidate.order(): + return False + current_stabilizer = current_stabilizer.stabilizer(base[i]) + if current_stabilizer.order() != 1: + return False + return True + + +def _verify_centralizer(group, arg, centr=None): + """ + Verify the centralizer of a group/set/element inside another group. + + This is used for testing ``.centralizer()`` from + ``sympy.combinatorics.perm_groups`` + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... AlternatingGroup) + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy.combinatorics.testutil import _verify_centralizer + >>> S = SymmetricGroup(5) + >>> A = AlternatingGroup(5) + >>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])]) + >>> _verify_centralizer(S, A, centr) + True + + See Also + ======== + + _naive_list_centralizer, + sympy.combinatorics.perm_groups.PermutationGroup.centralizer, + _cmp_perm_lists + + """ + if centr is None: + centr = group.centralizer(arg) + centr_list = list(centr.generate_dimino(af=True)) + centr_list_naive = _naive_list_centralizer(group, arg, af=True) + return _cmp_perm_lists(centr_list, centr_list_naive) + + +def _verify_normal_closure(group, arg, closure=None): + from sympy.combinatorics.perm_groups import PermutationGroup + """ + Verify the normal closure of a subgroup/subset/element in a group. + + This is used to test + sympy.combinatorics.perm_groups.PermutationGroup.normal_closure + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... AlternatingGroup) + >>> from sympy.combinatorics.testutil import _verify_normal_closure + >>> S = SymmetricGroup(3) + >>> A = AlternatingGroup(3) + >>> _verify_normal_closure(S, A, closure=A) + True + + See Also + ======== + + sympy.combinatorics.perm_groups.PermutationGroup.normal_closure + + """ + if closure is None: + closure = group.normal_closure(arg) + conjugates = set() + if hasattr(arg, 'generators'): + subgr_gens = arg.generators + elif hasattr(arg, '__getitem__'): + subgr_gens = arg + elif hasattr(arg, 'array_form'): + subgr_gens = [arg] + for el in group.generate_dimino(): + conjugates.update(gen ^ el for gen in subgr_gens) + naive_closure = PermutationGroup(list(conjugates)) + return closure.is_subgroup(naive_closure) + + +def canonicalize_naive(g, dummies, sym, *v): + """ + Canonicalize tensor formed by tensors of the different types. + + Explanation + =========== + + sym_i symmetry under exchange of two component tensors of type `i` + None no symmetry + 0 commuting + 1 anticommuting + + Parameters + ========== + + g : Permutation representing the tensor. + dummies : List of dummy indices. + msym : Symmetry of the metric. + v : A list of (base_i, gens_i, n_i, sym_i) for tensors of type `i`. + base_i, gens_i BSGS for tensors of this type + n_i number of tensors of type `i` + + Returns + ======= + + Returns 0 if the tensor is zero, else returns the array form of + the permutation representing the canonical form of the tensor. + + Examples + ======== + + >>> from sympy.combinatorics.testutil import canonicalize_naive + >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs + >>> from sympy.combinatorics import Permutation + >>> g = Permutation([1, 3, 2, 0, 4, 5]) + >>> base2, gens2 = get_symmetric_group_sgs(2) + >>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0)) + [0, 2, 1, 3, 4, 5] + """ + from sympy.combinatorics.perm_groups import PermutationGroup + from sympy.combinatorics.tensor_can import gens_products, dummy_sgs + from sympy.combinatorics.permutations import _af_rmul + v1 = [] + for i in range(len(v)): + base_i, gens_i, n_i, sym_i = v[i] + v1.append((base_i, gens_i, [[]]*n_i, sym_i)) + size, sbase, sgens = gens_products(*v1) + dgens = dummy_sgs(dummies, sym, size-2) + if isinstance(sym, int): + num_types = 1 + dummies = [dummies] + sym = [sym] + else: + num_types = len(sym) + dgens = [] + for i in range(num_types): + dgens.extend(dummy_sgs(dummies[i], sym[i], size - 2)) + S = PermutationGroup(sgens) + D = PermutationGroup([Permutation(x) for x in dgens]) + dlist = list(D.generate(af=True)) + g = g.array_form + st = set() + for s in S.generate(af=True): + h = _af_rmul(g, s) + for d in dlist: + q = tuple(_af_rmul(d, h)) + st.add(q) + a = list(st) + a.sort() + prev = (0,)*size + for h in a: + if h[:-2] == prev[:-2]: + if h[-1] != prev[-1]: + return 0 + prev = h + return list(a[0]) + + +def graph_certificate(gr): + """ + Return a certificate for the graph + + Parameters + ========== + + gr : adjacency list + + Explanation + =========== + + The graph is assumed to be unoriented and without + external lines. + + Associate to each vertex of the graph a symmetric tensor with + number of indices equal to the degree of the vertex; indices + are contracted when they correspond to the same line of the graph. + The canonical form of the tensor gives a certificate for the graph. + + This is not an efficient algorithm to get the certificate of a graph. + + Examples + ======== + + >>> from sympy.combinatorics.testutil import graph_certificate + >>> gr1 = {0:[1, 2, 3, 5], 1:[0, 2, 4], 2:[0, 1, 3, 4], 3:[0, 2, 4], 4:[1, 2, 3, 5], 5:[0, 4]} + >>> gr2 = {0:[1, 5], 1:[0, 2, 3, 4], 2:[1, 3, 5], 3:[1, 2, 4, 5], 4:[1, 3, 5], 5:[0, 2, 3, 4]} + >>> c1 = graph_certificate(gr1) + >>> c2 = graph_certificate(gr2) + >>> c1 + [0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21] + >>> c1 == c2 + True + """ + from sympy.combinatorics.permutations import _af_invert + from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize + items = list(gr.items()) + items.sort(key=lambda x: len(x[1]), reverse=True) + pvert = [x[0] for x in items] + pvert = _af_invert(pvert) + + # the indices of the tensor are twice the number of lines of the graph + num_indices = 0 + for v, neigh in items: + num_indices += len(neigh) + # associate to each vertex its indices; for each line + # between two vertices assign the + # even index to the vertex which comes first in items, + # the odd index to the other vertex + vertices = [[] for i in items] + i = 0 + for v, neigh in items: + for v2 in neigh: + if pvert[v] < pvert[v2]: + vertices[pvert[v]].append(i) + vertices[pvert[v2]].append(i+1) + i += 2 + g = [] + for v in vertices: + g.extend(v) + assert len(g) == num_indices + g += [num_indices, num_indices + 1] + size = num_indices + 2 + assert sorted(g) == list(range(size)) + g = Permutation(g) + vlen = [0]*(len(vertices[0])+1) + for neigh in vertices: + vlen[len(neigh)] += 1 + v = [] + for i in range(len(vlen)): + n = vlen[i] + if n: + base, gens = get_symmetric_group_sgs(i) + v.append((base, gens, n, 0)) + v.reverse() + dummies = list(range(num_indices)) + can = canonicalize(g, dummies, 0, *v) + return can diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/util.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/util.py new file mode 100644 index 0000000000000000000000000000000000000000..fc73b02f94f4aae6f1b98bb3f0c837fd5a1d1e6d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/combinatorics/util.py @@ -0,0 +1,532 @@ +from sympy.combinatorics.permutations import Permutation, _af_invert, _af_rmul +from sympy.ntheory import isprime + +rmul = Permutation.rmul +_af_new = Permutation._af_new + +############################################ +# +# Utilities for computational group theory +# +############################################ + + +def _base_ordering(base, degree): + r""" + Order `\{0, 1, \dots, n-1\}` so that base points come first and in order. + + Parameters + ========== + + base : the base + degree : the degree of the associated permutation group + + Returns + ======= + + A list ``base_ordering`` such that ``base_ordering[point]`` is the + number of ``point`` in the ordering. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricGroup + >>> from sympy.combinatorics.util import _base_ordering + >>> S = SymmetricGroup(4) + >>> S.schreier_sims() + >>> _base_ordering(S.base, S.degree) + [0, 1, 2, 3] + + Notes + ===== + + This is used in backtrack searches, when we define a relation `\ll` on + the underlying set for a permutation group of degree `n`, + `\{0, 1, \dots, n-1\}`, so that if `(b_1, b_2, \dots, b_k)` is a base we + have `b_i \ll b_j` whenever `i>> from sympy.combinatorics.util import _check_cycles_alt_sym + >>> from sympy.combinatorics import Permutation + >>> a = Permutation([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12]]) + >>> _check_cycles_alt_sym(a) + False + >>> b = Permutation([[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10]]) + >>> _check_cycles_alt_sym(b) + True + + See Also + ======== + + sympy.combinatorics.perm_groups.PermutationGroup.is_alt_sym + + """ + n = perm.size + af = perm.array_form + current_len = 0 + total_len = 0 + used = set() + for i in range(n//2): + if i not in used and i < n//2 - total_len: + current_len = 1 + used.add(i) + j = i + while af[j] != i: + current_len += 1 + j = af[j] + used.add(j) + total_len += current_len + if current_len > n//2 and current_len < n - 2 and isprime(current_len): + return True + return False + + +def _distribute_gens_by_base(base, gens): + r""" + Distribute the group elements ``gens`` by membership in basic stabilizers. + + Explanation + =========== + + Notice that for a base `(b_1, b_2, \dots, b_k)`, the basic stabilizers + are defined as `G^{(i)} = G_{b_1, \dots, b_{i-1}}` for + `i \in\{1, 2, \dots, k\}`. + + Parameters + ========== + + base : a sequence of points in `\{0, 1, \dots, n-1\}` + gens : a list of elements of a permutation group of degree `n`. + + Returns + ======= + list + List of length `k`, where `k` is the length of *base*. The `i`-th entry + contains those elements in *gens* which fix the first `i` elements of + *base* (so that the `0`-th entry is equal to *gens* itself). If no + element fixes the first `i` elements of *base*, the `i`-th element is + set to a list containing the identity element. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> from sympy.combinatorics.util import _distribute_gens_by_base + >>> D = DihedralGroup(3) + >>> D.schreier_sims() + >>> D.strong_gens + [(0 1 2), (0 2), (1 2)] + >>> D.base + [0, 1] + >>> _distribute_gens_by_base(D.base, D.strong_gens) + [[(0 1 2), (0 2), (1 2)], + [(1 2)]] + + See Also + ======== + + _strong_gens_from_distr, _orbits_transversals_from_bsgs, + _handle_precomputed_bsgs + + """ + base_len = len(base) + degree = gens[0].size + stabs = [[] for _ in range(base_len)] + max_stab_index = 0 + for gen in gens: + j = 0 + while j < base_len - 1 and gen._array_form[base[j]] == base[j]: + j += 1 + if j > max_stab_index: + max_stab_index = j + for k in range(j + 1): + stabs[k].append(gen) + for i in range(max_stab_index + 1, base_len): + stabs[i].append(_af_new(list(range(degree)))) + return stabs + + +def _handle_precomputed_bsgs(base, strong_gens, transversals=None, + basic_orbits=None, strong_gens_distr=None): + """ + Calculate BSGS-related structures from those present. + + Explanation + =========== + + The base and strong generating set must be provided; if any of the + transversals, basic orbits or distributed strong generators are not + provided, they will be calculated from the base and strong generating set. + + Parameters + ========== + + base : the base + strong_gens : the strong generators + transversals : basic transversals + basic_orbits : basic orbits + strong_gens_distr : strong generators distributed by membership in basic stabilizers + + Returns + ======= + + (transversals, basic_orbits, strong_gens_distr) + where *transversals* are the basic transversals, *basic_orbits* are the + basic orbits, and *strong_gens_distr* are the strong generators distributed + by membership in basic stabilizers. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> from sympy.combinatorics.util import _handle_precomputed_bsgs + >>> D = DihedralGroup(3) + >>> D.schreier_sims() + >>> _handle_precomputed_bsgs(D.base, D.strong_gens, + ... basic_orbits=D.basic_orbits) + ([{0: (2), 1: (0 1 2), 2: (0 2)}, {1: (2), 2: (1 2)}], [[0, 1, 2], [1, 2]], [[(0 1 2), (0 2), (1 2)], [(1 2)]]) + + See Also + ======== + + _orbits_transversals_from_bsgs, _distribute_gens_by_base + + """ + if strong_gens_distr is None: + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + if transversals is None: + if basic_orbits is None: + basic_orbits, transversals = \ + _orbits_transversals_from_bsgs(base, strong_gens_distr) + else: + transversals = \ + _orbits_transversals_from_bsgs(base, strong_gens_distr, + transversals_only=True) + else: + if basic_orbits is None: + base_len = len(base) + basic_orbits = [None]*base_len + for i in range(base_len): + basic_orbits[i] = list(transversals[i].keys()) + return transversals, basic_orbits, strong_gens_distr + + +def _orbits_transversals_from_bsgs(base, strong_gens_distr, + transversals_only=False, slp=False): + """ + Compute basic orbits and transversals from a base and strong generating set. + + Explanation + =========== + + The generators are provided as distributed across the basic stabilizers. + If the optional argument ``transversals_only`` is set to True, only the + transversals are returned. + + Parameters + ========== + + base : The base. + strong_gens_distr : Strong generators distributed by membership in basic stabilizers. + transversals_only : bool, default: False + A flag switching between returning only the + transversals and both orbits and transversals. + slp : bool, default: False + If ``True``, return a list of dictionaries containing the + generator presentations of the elements of the transversals, + i.e. the list of indices of generators from ``strong_gens_distr[i]`` + such that their product is the relevant transversal element. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricGroup + >>> from sympy.combinatorics.util import _distribute_gens_by_base + >>> S = SymmetricGroup(3) + >>> S.schreier_sims() + >>> strong_gens_distr = _distribute_gens_by_base(S.base, S.strong_gens) + >>> (S.base, strong_gens_distr) + ([0, 1], [[(0 1 2), (2)(0 1), (1 2)], [(1 2)]]) + + See Also + ======== + + _distribute_gens_by_base, _handle_precomputed_bsgs + + """ + from sympy.combinatorics.perm_groups import _orbit_transversal + base_len = len(base) + degree = strong_gens_distr[0][0].size + transversals = [None]*base_len + slps = [None]*base_len + if transversals_only is False: + basic_orbits = [None]*base_len + for i in range(base_len): + transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i], + base[i], pairs=True, slp=True) + transversals[i] = dict(transversals[i]) + if transversals_only is False: + basic_orbits[i] = list(transversals[i].keys()) + if transversals_only: + return transversals + else: + if not slp: + return basic_orbits, transversals + return basic_orbits, transversals, slps + + +def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None): + """ + Remove redundant generators from a strong generating set. + + Parameters + ========== + + base : a base + strong_gens : a strong generating set relative to *base* + basic_orbits : basic orbits + strong_gens_distr : strong generators distributed by membership in basic stabilizers + + Returns + ======= + + A strong generating set with respect to ``base`` which is a subset of + ``strong_gens``. + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricGroup + >>> from sympy.combinatorics.util import _remove_gens + >>> from sympy.combinatorics.testutil import _verify_bsgs + >>> S = SymmetricGroup(15) + >>> base, strong_gens = S.schreier_sims_incremental() + >>> new_gens = _remove_gens(base, strong_gens) + >>> len(new_gens) + 14 + >>> _verify_bsgs(S, base, new_gens) + True + + Notes + ===== + + This procedure is outlined in [1],p.95. + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of computational group theory" + + """ + from sympy.combinatorics.perm_groups import _orbit + base_len = len(base) + degree = strong_gens[0].size + if strong_gens_distr is None: + strong_gens_distr = _distribute_gens_by_base(base, strong_gens) + if basic_orbits is None: + basic_orbits = [] + for i in range(base_len): + basic_orbit = _orbit(degree, strong_gens_distr[i], base[i]) + basic_orbits.append(basic_orbit) + strong_gens_distr.append([]) + res = strong_gens[:] + for i in range(base_len - 1, -1, -1): + gens_copy = strong_gens_distr[i][:] + for gen in strong_gens_distr[i]: + if gen not in strong_gens_distr[i + 1]: + temp_gens = gens_copy[:] + temp_gens.remove(gen) + if temp_gens == []: + continue + temp_orbit = _orbit(degree, temp_gens, base[i]) + if temp_orbit == basic_orbits[i]: + gens_copy.remove(gen) + res.remove(gen) + return res + + +def _strip(g, base, orbits, transversals): + """ + Attempt to decompose a permutation using a (possibly partial) BSGS + structure. + + Explanation + =========== + + This is done by treating the sequence ``base`` as an actual base, and + the orbits ``orbits`` and transversals ``transversals`` as basic orbits and + transversals relative to it. + + This process is called "sifting". A sift is unsuccessful when a certain + orbit element is not found or when after the sift the decomposition + does not end with the identity element. + + The argument ``transversals`` is a list of dictionaries that provides + transversal elements for the orbits ``orbits``. + + Parameters + ========== + + g : permutation to be decomposed + base : sequence of points + orbits : list + A list in which the ``i``-th entry is an orbit of ``base[i]`` + under some subgroup of the pointwise stabilizer of ` + `base[0], base[1], ..., base[i - 1]``. The groups themselves are implicit + in this function since the only information we need is encoded in the orbits + and transversals + transversals : list + A list of orbit transversals associated with the orbits *orbits*. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation, SymmetricGroup + >>> from sympy.combinatorics.util import _strip + >>> S = SymmetricGroup(5) + >>> S.schreier_sims() + >>> g = Permutation([0, 2, 3, 1, 4]) + >>> _strip(g, S.base, S.basic_orbits, S.basic_transversals) + ((4), 5) + + Notes + ===== + + The algorithm is described in [1],pp.89-90. The reason for returning + both the current state of the element being decomposed and the level + at which the sifting ends is that they provide important information for + the randomized version of the Schreier-Sims algorithm. + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E."Handbook of computational group theory" + + See Also + ======== + + sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims + sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims_random + + """ + h = g._array_form + base_len = len(base) + for i in range(base_len): + beta = h[base[i]] + if beta == base[i]: + continue + if beta not in orbits[i]: + return _af_new(h), i + 1 + u = transversals[i][beta]._array_form + h = _af_rmul(_af_invert(u), h) + return _af_new(h), base_len + 1 + + +def _strip_af(h, base, orbits, transversals, j, slp=[], slps={}): + """ + optimized _strip, with h, transversals and result in array form + if the stripped elements is the identity, it returns False, base_len + 1 + + j h[base[i]] == base[i] for i <= j + + """ + base_len = len(base) + for i in range(j+1, base_len): + beta = h[base[i]] + if beta == base[i]: + continue + if beta not in orbits[i]: + if not slp: + return h, i + 1 + return h, i + 1, slp + u = transversals[i][beta] + if h == u: + if not slp: + return False, base_len + 1 + return False, base_len + 1, slp + h = _af_rmul(_af_invert(u), h) + if slp: + u_slp = slps[i][beta][:] + u_slp.reverse() + u_slp = [(i, (g,)) for g in u_slp] + slp = u_slp + slp + if not slp: + return h, base_len + 1 + return h, base_len + 1, slp + + +def _strong_gens_from_distr(strong_gens_distr): + """ + Retrieve strong generating set from generators of basic stabilizers. + + This is just the union of the generators of the first and second basic + stabilizers. + + Parameters + ========== + + strong_gens_distr : strong generators distributed by membership in basic stabilizers + + Examples + ======== + + >>> from sympy.combinatorics import SymmetricGroup + >>> from sympy.combinatorics.util import (_strong_gens_from_distr, + ... _distribute_gens_by_base) + >>> S = SymmetricGroup(3) + >>> S.schreier_sims() + >>> S.strong_gens + [(0 1 2), (2)(0 1), (1 2)] + >>> strong_gens_distr = _distribute_gens_by_base(S.base, S.strong_gens) + >>> _strong_gens_from_distr(strong_gens_distr) + [(0 1 2), (2)(0 1), (1 2)] + + See Also + ======== + + _distribute_gens_by_base + + """ + if len(strong_gens_distr) == 1: + return strong_gens_distr[0][:] + else: + result = strong_gens_distr[0] + for gen in strong_gens_distr[1]: + if gen not in result: + result.append(gen) + return result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/conftest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..788ec7ed8a38de422b76c4ac19057513670d2d38 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/conftest.py @@ -0,0 +1,96 @@ +import sys + +sys._running_pytest = True # type: ignore +from sympy.external.importtools import version_tuple + +import pytest +from sympy.core.cache import clear_cache, USE_CACHE +from sympy.external.gmpy import GROUND_TYPES +from sympy.utilities.misc import ARCH +import re + +try: + import hypothesis + + hypothesis.settings.register_profile("sympy_hypothesis_profile", deadline=None) + hypothesis.settings.load_profile("sympy_hypothesis_profile") +except ImportError: + raise ImportError( + "hypothesis is a required dependency to run the SymPy test suite. " + "Install it with 'pip install hypothesis' or 'conda install -c conda-forge hypothesis'" + ) + + +sp = re.compile(r"([0-9]+)/([1-9][0-9]*)") + + +def process_split(config, items): + split = config.getoption("--split") + if not split: + return + m = sp.match(split) + if not m: + raise ValueError( + "split must be a string of the form a/b " "where a and b are ints." + ) + i, t = map(int, m.groups()) + start, end = (i - 1) * len(items) // t, i * len(items) // t + + if i < t: + # remove elements from end of list first + del items[end:] + del items[:start] + + +def pytest_report_header(config): + s = "architecture: %s\n" % ARCH + s += "cache: %s\n" % USE_CACHE + version = "" + if GROUND_TYPES == "gmpy": + import gmpy2 + + version = gmpy2.version() + elif GROUND_TYPES == "flint": + try: + from flint import __version__ + except ImportError: + version = "unknown" + else: + version = f'(python-flint=={__version__})' + s += "ground types: %s %s\n" % (GROUND_TYPES, version) + return s + + +def pytest_terminal_summary(terminalreporter): + if terminalreporter.stats.get("error", None) or terminalreporter.stats.get( + "failed", None + ): + terminalreporter.write_sep(" ", "DO *NOT* COMMIT!", red=True, bold=True) + + +def pytest_addoption(parser): + parser.addoption("--split", action="store", default="", help="split tests") + + +def pytest_collection_modifyitems(config, items): + """pytest hook.""" + # handle splits + process_split(config, items) + + +@pytest.fixture(autouse=True, scope="module") +def file_clear_cache(): + clear_cache() + + +@pytest.fixture(autouse=True, scope="module") +def check_disabled(request): + if getattr(request.module, "disabled", False): + pytest.skip("test requirements not met.") + elif getattr(request.module, "ipython", False): + # need to check version and options for ipython tests + if ( + version_tuple(pytest.__version__) < version_tuple("2.6.3") + and pytest.config.getvalue("-s") != "no" + ): + pytest.skip("run py.test with -s or upgrade to newer version.") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/galgebra.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/galgebra.py new file mode 100644 index 0000000000000000000000000000000000000000..be812bfcbcece834c86d7b55eb846286acd0ac08 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/galgebra.py @@ -0,0 +1 @@ +raise ImportError("""As of SymPy 1.0 the galgebra module is maintained separately at https://github.com/pygae/galgebra""") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..37b558f3f03f149dae6af20254e9b88192f7f1ed --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/__init__.py @@ -0,0 +1,72 @@ +"""A module that handles matrices. + +Includes functions for fast creating matrices like zero, one/eye, random +matrix, etc. +""" +from .exceptions import ShapeError, NonSquareMatrixError +from .kind import MatrixKind +from .dense import ( + GramSchmidt, casoratian, diag, eye, hessian, jordan_cell, + list2numpy, matrix2numpy, matrix_multiply_elementwise, ones, + randMatrix, rot_axis1, rot_axis2, rot_axis3, rot_ccw_axis1, + rot_ccw_axis2, rot_ccw_axis3, rot_givens, + symarray, wronskian, zeros) +from .dense import MutableDenseMatrix +from .matrixbase import DeferredVector, MatrixBase + +MutableMatrix = MutableDenseMatrix +Matrix = MutableMatrix + +from .sparse import MutableSparseMatrix +from .sparsetools import banded +from .immutable import ImmutableDenseMatrix, ImmutableSparseMatrix + +ImmutableMatrix = ImmutableDenseMatrix +SparseMatrix = MutableSparseMatrix + +from .expressions import ( + MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, + Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, + Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint, + hadamard_product, HadamardProduct, HadamardPower, Determinant, det, + diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace, + DotProduct, kronecker_product, KroneckerProduct, + PermutationMatrix, MatrixPermute, MatrixSet, Permanent, per) + +from .utilities import dotprodsimp + +__all__ = [ + 'ShapeError', 'NonSquareMatrixError', 'MatrixKind', + + 'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell', + 'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones', + 'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray', + 'wronskian', 'zeros', 'rot_ccw_axis1', 'rot_ccw_axis2', 'rot_ccw_axis3', + 'rot_givens', + + 'MutableDenseMatrix', + + 'DeferredVector', 'MatrixBase', + + 'Matrix', 'MutableMatrix', + + 'MutableSparseMatrix', + + 'banded', + + 'ImmutableDenseMatrix', 'ImmutableSparseMatrix', + + 'ImmutableMatrix', 'SparseMatrix', + + 'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', + 'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', + 'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix', + 'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint', + 'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant', + 'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix', + 'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product', + 'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'MatrixSet', + 'Permanent', 'per', + + 'dotprodsimp', +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb845600533c4c6fef196fe5a45b98890f4ad78 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py @@ -0,0 +1,21 @@ +from sympy.core.numbers import Integer +from sympy.matrices.dense import (eye, zeros) + +i3 = Integer(3) +M = eye(100) + + +def timeit_Matrix__getitem_ii(): + M[3, 3] + + +def timeit_Matrix__getitem_II(): + M[i3, i3] + + +def timeit_Matrix__getslice(): + M[:, :] + + +def timeit_Matrix_zeronm(): + zeros(100, 100) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/common.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/common.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb54726fe1a0c36658d8bf63b974db5a3ce8bad --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/common.py @@ -0,0 +1,3258 @@ +""" +A module containing deprecated matrix mixin classes. + +The classes in this module are deprecated and will be removed in a future +release. They are kept here for backwards compatibility in case downstream +code was subclassing them. + +Importing anything else from this module is deprecated so anything here +should either not be used or should be imported from somewhere else. +""" +from __future__ import annotations +from collections import defaultdict +from collections.abc import Iterable +from inspect import isfunction +from functools import reduce + +from sympy.assumptions.refine import refine +from sympy.core import SympifyError, Add +from sympy.core.basic import Atom +from sympy.core.decorators import call_highest_priority +from sympy.core.logic import fuzzy_and, FuzzyBool +from sympy.core.numbers import Integer +from sympy.core.mod import Mod +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.complexes import Abs, re, im +from sympy.utilities.exceptions import sympy_deprecation_warning +from .utilities import _dotprodsimp, _simplify +from sympy.polys.polytools import Poly +from sympy.utilities.iterables import flatten, is_sequence +from sympy.utilities.misc import as_int, filldedent +from sympy.tensor.array import NDimArray + +from .utilities import _get_intermediate_simp_bool + + +# These exception types were previously defined in this module but were moved +# to exceptions.py. We reimport them here for backwards compatibility in case +# downstream code was importing them from here. +from .exceptions import ( # noqa: F401 + MatrixError, ShapeError, NonSquareMatrixError, NonInvertibleMatrixError, + NonPositiveDefiniteMatrixError +) + + +_DEPRECATED_MIXINS = ( + 'MatrixShaping', + 'MatrixSpecial', + 'MatrixProperties', + 'MatrixOperations', + 'MatrixArithmetic', + 'MatrixCommon', + 'MatrixDeterminant', + 'MatrixReductions', + 'MatrixSubspaces', + 'MatrixEigen', + 'MatrixCalculus', + 'MatrixDeprecated', +) + + +class _MatrixDeprecatedMeta(type): + + # + # Override the default __instancecheck__ implementation to ensure that + # e.g. isinstance(M, MatrixCommon) still works when M is one of the + # matrix classes. Matrix no longer inherits from MatrixCommon so + # isinstance(M, MatrixCommon) would now return False by default. + # + # There were lots of places in the codebase where this was being done + # so it seems likely that downstream code may be doing it too. All use + # of these mixins is deprecated though so we give a deprecation warning + # unconditionally if they are being used with isinstance. + # + # Any code seeing this deprecation warning should be changed to use + # isinstance(M, MatrixBase) instead which also works in previous versions + # of SymPy. + # + + def __instancecheck__(cls, instance): + + sympy_deprecation_warning( + f""" + Checking whether an object is an instance of {cls.__name__} is + deprecated. + + Use `isinstance(obj, Matrix)` instead of `isinstance(obj, {cls.__name__})`. + """, + deprecated_since_version="1.13", + active_deprecations_target="deprecated-matrix-mixins", + stacklevel=3, + ) + + from sympy.matrices.matrixbase import MatrixBase + from sympy.matrices.matrices import ( + MatrixDeterminant, + MatrixReductions, + MatrixSubspaces, + MatrixEigen, + MatrixCalculus, + MatrixDeprecated + ) + + all_mixins = ( + MatrixRequired, + MatrixShaping, + MatrixSpecial, + MatrixProperties, + MatrixOperations, + MatrixArithmetic, + MatrixCommon, + MatrixDeterminant, + MatrixReductions, + MatrixSubspaces, + MatrixEigen, + MatrixCalculus, + MatrixDeprecated + ) + + if cls in all_mixins and isinstance(instance, MatrixBase): + return True + else: + return super().__instancecheck__(instance) + + +class MatrixRequired(metaclass=_MatrixDeprecatedMeta): + """Deprecated mixin class for making matrix classes.""" + + rows: int + cols: int + _simplify = None + + def __init_subclass__(cls, **kwargs): + + # Warn if any downstream code is subclassing this class or any of the + # deprecated mixin classes that are all ultimately subclasses of this + # class. + # + # We don't want to warn about the deprecated mixins themselves being + # created, but only about them being used as mixins by downstream code. + # Otherwise just importing this module would trigger a warning. + # Ultimately the whole module should be deprecated and removed but for + # SymPy 1.13 it is premature to do that given that this module was the + # main way to import matrix exception types in all previous versions. + + if cls.__name__ not in _DEPRECATED_MIXINS: + sympy_deprecation_warning( + f""" + Inheriting from the Matrix mixin classes is deprecated. + + The class {cls.__name__} is subclassing a deprecated mixin. + """, + deprecated_since_version="1.13", + active_deprecations_target="deprecated-matrix-mixins", + stacklevel=3, + ) + + super().__init_subclass__(**kwargs) + + @classmethod + def _new(cls, *args, **kwargs): + """`_new` must, at minimum, be callable as + `_new(rows, cols, mat) where mat is a flat list of the + elements of the matrix.""" + raise NotImplementedError("Subclasses must implement this.") + + def __eq__(self, other): + raise NotImplementedError("Subclasses must implement this.") + + def __getitem__(self, key): + """Implementations of __getitem__ should accept ints, in which + case the matrix is indexed as a flat list, tuples (i,j) in which + case the (i,j) entry is returned, slices, or mixed tuples (a,b) + where a and b are any combination of slices and integers.""" + raise NotImplementedError("Subclasses must implement this.") + + def __len__(self): + """The total number of entries in the matrix.""" + raise NotImplementedError("Subclasses must implement this.") + + @property + def shape(self): + raise NotImplementedError("Subclasses must implement this.") + + +class MatrixShaping(MatrixRequired): + """Provides basic matrix shaping and extracting of submatrices""" + + def _eval_col_del(self, col): + def entry(i, j): + return self[i, j] if j < col else self[i, j + 1] + return self._new(self.rows, self.cols - 1, entry) + + def _eval_col_insert(self, pos, other): + + def entry(i, j): + if j < pos: + return self[i, j] + elif pos <= j < pos + other.cols: + return other[i, j - pos] + return self[i, j - other.cols] + + return self._new(self.rows, self.cols + other.cols, entry) + + def _eval_col_join(self, other): + rows = self.rows + + def entry(i, j): + if i < rows: + return self[i, j] + return other[i - rows, j] + + return classof(self, other)._new(self.rows + other.rows, self.cols, + entry) + + def _eval_extract(self, rowsList, colsList): + mat = list(self) + cols = self.cols + indices = (i * cols + j for i in rowsList for j in colsList) + return self._new(len(rowsList), len(colsList), + [mat[i] for i in indices]) + + def _eval_get_diag_blocks(self): + sub_blocks = [] + + def recurse_sub_blocks(M): + for i in range(1, M.shape[0] + 1): + if i == 1: + to_the_right = M[0, i:] + to_the_bottom = M[i:, 0] + else: + to_the_right = M[:i, i:] + to_the_bottom = M[i:, :i] + if any(to_the_right) or any(to_the_bottom): + continue + sub_blocks.append(M[:i, :i]) + if M.shape != M[:i, :i].shape: + recurse_sub_blocks(M[i:, i:]) + return + + recurse_sub_blocks(self) + return sub_blocks + + def _eval_row_del(self, row): + def entry(i, j): + return self[i, j] if i < row else self[i + 1, j] + return self._new(self.rows - 1, self.cols, entry) + + def _eval_row_insert(self, pos, other): + entries = list(self) + insert_pos = pos * self.cols + entries[insert_pos:insert_pos] = list(other) + return self._new(self.rows + other.rows, self.cols, entries) + + def _eval_row_join(self, other): + cols = self.cols + + def entry(i, j): + if j < cols: + return self[i, j] + return other[i, j - cols] + + return classof(self, other)._new(self.rows, self.cols + other.cols, + entry) + + def _eval_tolist(self): + return [list(self[i,:]) for i in range(self.rows)] + + def _eval_todok(self): + dok = {} + rows, cols = self.shape + for i in range(rows): + for j in range(cols): + val = self[i, j] + if val != self.zero: + dok[i, j] = val + return dok + + def _eval_vec(self): + rows = self.rows + + def entry(n, _): + # we want to read off the columns first + j = n // rows + i = n - j * rows + return self[i, j] + + return self._new(len(self), 1, entry) + + def _eval_vech(self, diagonal): + c = self.cols + v = [] + if diagonal: + for j in range(c): + for i in range(j, c): + v.append(self[i, j]) + else: + for j in range(c): + for i in range(j + 1, c): + v.append(self[i, j]) + return self._new(len(v), 1, v) + + def col_del(self, col): + """Delete the specified column.""" + if col < 0: + col += self.cols + if not 0 <= col < self.cols: + raise IndexError("Column {} is out of range.".format(col)) + return self._eval_col_del(col) + + def col_insert(self, pos, other): + """Insert one or more columns at the given column position. + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(3, 1) + >>> M.col_insert(1, V) + Matrix([ + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + + See Also + ======== + + col + row_insert + """ + # Allows you to build a matrix even if it is null matrix + if not self: + return type(self)(other) + + pos = as_int(pos) + + if pos < 0: + pos = self.cols + pos + if pos < 0: + pos = 0 + elif pos > self.cols: + pos = self.cols + + if self.rows != other.rows: + raise ShapeError( + "The matrices have incompatible number of rows ({} and {})" + .format(self.rows, other.rows)) + + return self._eval_col_insert(pos, other) + + def col_join(self, other): + """Concatenates two matrices along self's last and other's first row. + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(1, 3) + >>> M.col_join(V) + Matrix([ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [1, 1, 1]]) + + See Also + ======== + + col + row_join + """ + # A null matrix can always be stacked (see #10770) + if self.rows == 0 and self.cols != other.cols: + return self._new(0, other.cols, []).col_join(other) + + if self.cols != other.cols: + raise ShapeError( + "The matrices have incompatible number of columns ({} and {})" + .format(self.cols, other.cols)) + return self._eval_col_join(other) + + def col(self, j): + """Elementary column selector. + + Examples + ======== + + >>> from sympy import eye + >>> eye(2).col(0) + Matrix([ + [1], + [0]]) + + See Also + ======== + + row + col_del + col_join + col_insert + """ + return self[:, j] + + def extract(self, rowsList, colsList): + r"""Return a submatrix by specifying a list of rows and columns. + Negative indices can be given. All indices must be in the range + $-n \le i < n$ where $n$ is the number of rows or columns. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(4, 3, range(12)) + >>> m + Matrix([ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8], + [9, 10, 11]]) + >>> m.extract([0, 1, 3], [0, 1]) + Matrix([ + [0, 1], + [3, 4], + [9, 10]]) + + Rows or columns can be repeated: + + >>> m.extract([0, 0, 1], [-1]) + Matrix([ + [2], + [2], + [5]]) + + Every other row can be taken by using range to provide the indices: + + >>> m.extract(range(0, m.rows, 2), [-1]) + Matrix([ + [2], + [8]]) + + RowsList or colsList can also be a list of booleans, in which case + the rows or columns corresponding to the True values will be selected: + + >>> m.extract([0, 1, 2, 3], [True, False, True]) + Matrix([ + [0, 2], + [3, 5], + [6, 8], + [9, 11]]) + """ + + if not is_sequence(rowsList) or not is_sequence(colsList): + raise TypeError("rowsList and colsList must be iterable") + # ensure rowsList and colsList are lists of integers + if rowsList and all(isinstance(i, bool) for i in rowsList): + rowsList = [index for index, item in enumerate(rowsList) if item] + if colsList and all(isinstance(i, bool) for i in colsList): + colsList = [index for index, item in enumerate(colsList) if item] + + # ensure everything is in range + rowsList = [a2idx(k, self.rows) for k in rowsList] + colsList = [a2idx(k, self.cols) for k in colsList] + + return self._eval_extract(rowsList, colsList) + + def get_diag_blocks(self): + """Obtains the square sub-matrices on the main diagonal of a square matrix. + + Useful for inverting symbolic matrices or solving systems of + linear equations which may be decoupled by having a block diagonal + structure. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y, z + >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]]) + >>> a1, a2, a3 = A.get_diag_blocks() + >>> a1 + Matrix([ + [1, 3], + [y, z**2]]) + >>> a2 + Matrix([[x]]) + >>> a3 + Matrix([[0]]) + + """ + return self._eval_get_diag_blocks() + + @classmethod + def hstack(cls, *args): + """Return a matrix formed by joining args horizontally (i.e. + by repeated application of row_join). + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> Matrix.hstack(eye(2), 2*eye(2)) + Matrix([ + [1, 0, 2, 0], + [0, 1, 0, 2]]) + """ + if len(args) == 0: + return cls._new() + + kls = type(args[0]) + return reduce(kls.row_join, args) + + def reshape(self, rows, cols): + """Reshape the matrix. Total number of elements must remain the same. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 3, lambda i, j: 1) + >>> m + Matrix([ + [1, 1, 1], + [1, 1, 1]]) + >>> m.reshape(1, 6) + Matrix([[1, 1, 1, 1, 1, 1]]) + >>> m.reshape(3, 2) + Matrix([ + [1, 1], + [1, 1], + [1, 1]]) + + """ + if self.rows * self.cols != rows * cols: + raise ValueError("Invalid reshape parameters %d %d" % (rows, cols)) + return self._new(rows, cols, lambda i, j: self[i * cols + j]) + + def row_del(self, row): + """Delete the specified row.""" + if row < 0: + row += self.rows + if not 0 <= row < self.rows: + raise IndexError("Row {} is out of range.".format(row)) + + return self._eval_row_del(row) + + def row_insert(self, pos, other): + """Insert one or more rows at the given row position. + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(1, 3) + >>> M.row_insert(1, V) + Matrix([ + [0, 0, 0], + [1, 1, 1], + [0, 0, 0], + [0, 0, 0]]) + + See Also + ======== + + row + col_insert + """ + # Allows you to build a matrix even if it is null matrix + if not self: + return self._new(other) + + pos = as_int(pos) + + if pos < 0: + pos = self.rows + pos + if pos < 0: + pos = 0 + elif pos > self.rows: + pos = self.rows + + if self.cols != other.cols: + raise ShapeError( + "The matrices have incompatible number of columns ({} and {})" + .format(self.cols, other.cols)) + + return self._eval_row_insert(pos, other) + + def row_join(self, other): + """Concatenates two matrices along self's last and rhs's first column + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(3, 1) + >>> M.row_join(V) + Matrix([ + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1]]) + + See Also + ======== + + row + col_join + """ + # A null matrix can always be stacked (see #10770) + if self.cols == 0 and self.rows != other.rows: + return self._new(other.rows, 0, []).row_join(other) + + if self.rows != other.rows: + raise ShapeError( + "The matrices have incompatible number of rows ({} and {})" + .format(self.rows, other.rows)) + return self._eval_row_join(other) + + def diagonal(self, k=0): + """Returns the kth diagonal of self. The main diagonal + corresponds to `k=0`; diagonals above and below correspond to + `k > 0` and `k < 0`, respectively. The values of `self[i, j]` + for which `j - i = k`, are returned in order of increasing + `i + j`, starting with `i + j = |k|`. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(3, 3, lambda i, j: j - i); m + Matrix([ + [ 0, 1, 2], + [-1, 0, 1], + [-2, -1, 0]]) + >>> _.diagonal() + Matrix([[0, 0, 0]]) + >>> m.diagonal(1) + Matrix([[1, 1]]) + >>> m.diagonal(-2) + Matrix([[-2]]) + + Even though the diagonal is returned as a Matrix, the element + retrieval can be done with a single index: + + >>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1] + 2 + + See Also + ======== + + diag + """ + rv = [] + k = as_int(k) + r = 0 if k > 0 else -k + c = 0 if r else k + while True: + if r == self.rows or c == self.cols: + break + rv.append(self[r, c]) + r += 1 + c += 1 + if not rv: + raise ValueError(filldedent(''' + The %s diagonal is out of range [%s, %s]''' % ( + k, 1 - self.rows, self.cols - 1))) + return self._new(1, len(rv), rv) + + def row(self, i): + """Elementary row selector. + + Examples + ======== + + >>> from sympy import eye + >>> eye(2).row(0) + Matrix([[1, 0]]) + + See Also + ======== + + col + row_del + row_join + row_insert + """ + return self[i, :] + + @property + def shape(self): + """The shape (dimensions) of the matrix as the 2-tuple (rows, cols). + + Examples + ======== + + >>> from sympy import zeros + >>> M = zeros(2, 3) + >>> M.shape + (2, 3) + >>> M.rows + 2 + >>> M.cols + 3 + """ + return (self.rows, self.cols) + + def todok(self): + """Return the matrix as dictionary of keys. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix.eye(3) + >>> M.todok() + {(0, 0): 1, (1, 1): 1, (2, 2): 1} + """ + return self._eval_todok() + + def tolist(self): + """Return the Matrix as a nested Python list. + + Examples + ======== + + >>> from sympy import Matrix, ones + >>> m = Matrix(3, 3, range(9)) + >>> m + Matrix([ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> m.tolist() + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + >>> ones(3, 0).tolist() + [[], [], []] + + When there are no rows then it will not be possible to tell how + many columns were in the original matrix: + + >>> ones(0, 3).tolist() + [] + + """ + if not self.rows: + return [] + if not self.cols: + return [[] for i in range(self.rows)] + return self._eval_tolist() + + def todod(M): + """Returns matrix as dict of dicts containing non-zero elements of the Matrix + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[0, 1],[0, 3]]) + >>> A + Matrix([ + [0, 1], + [0, 3]]) + >>> A.todod() + {0: {1: 1}, 1: {1: 3}} + + + """ + rowsdict = {} + Mlol = M.tolist() + for i, Mi in enumerate(Mlol): + row = {j: Mij for j, Mij in enumerate(Mi) if Mij} + if row: + rowsdict[i] = row + return rowsdict + + def vec(self): + """Return the Matrix converted into a one column matrix by stacking columns + + Examples + ======== + + >>> from sympy import Matrix + >>> m=Matrix([[1, 3], [2, 4]]) + >>> m + Matrix([ + [1, 3], + [2, 4]]) + >>> m.vec() + Matrix([ + [1], + [2], + [3], + [4]]) + + See Also + ======== + + vech + """ + return self._eval_vec() + + def vech(self, diagonal=True, check_symmetry=True): + """Reshapes the matrix into a column vector by stacking the + elements in the lower triangle. + + Parameters + ========== + + diagonal : bool, optional + If ``True``, it includes the diagonal elements. + + check_symmetry : bool, optional + If ``True``, it checks whether the matrix is symmetric. + + Examples + ======== + + >>> from sympy import Matrix + >>> m=Matrix([[1, 2], [2, 3]]) + >>> m + Matrix([ + [1, 2], + [2, 3]]) + >>> m.vech() + Matrix([ + [1], + [2], + [3]]) + >>> m.vech(diagonal=False) + Matrix([[2]]) + + Notes + ===== + + This should work for symmetric matrices and ``vech`` can + represent symmetric matrices in vector form with less size than + ``vec``. + + See Also + ======== + + vec + """ + if not self.is_square: + raise NonSquareMatrixError + + if check_symmetry and not self.is_symmetric(): + raise ValueError("The matrix is not symmetric.") + + return self._eval_vech(diagonal) + + @classmethod + def vstack(cls, *args): + """Return a matrix formed by joining args vertically (i.e. + by repeated application of col_join). + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> Matrix.vstack(eye(2), 2*eye(2)) + Matrix([ + [1, 0], + [0, 1], + [2, 0], + [0, 2]]) + """ + if len(args) == 0: + return cls._new() + + kls = type(args[0]) + return reduce(kls.col_join, args) + + +class MatrixSpecial(MatrixRequired): + """Construction of special matrices""" + + @classmethod + def _eval_diag(cls, rows, cols, diag_dict): + """diag_dict is a defaultdict containing + all the entries of the diagonal matrix.""" + def entry(i, j): + return diag_dict[(i, j)] + return cls._new(rows, cols, entry) + + @classmethod + def _eval_eye(cls, rows, cols): + vals = [cls.zero]*(rows*cols) + vals[::cols+1] = [cls.one]*min(rows, cols) + return cls._new(rows, cols, vals, copy=False) + + @classmethod + def _eval_jordan_block(cls, size: int, eigenvalue, band='upper'): + if band == 'lower': + def entry(i, j): + if i == j: + return eigenvalue + elif j + 1 == i: + return cls.one + return cls.zero + else: + def entry(i, j): + if i == j: + return eigenvalue + elif i + 1 == j: + return cls.one + return cls.zero + return cls._new(size, size, entry) + + @classmethod + def _eval_ones(cls, rows, cols): + def entry(i, j): + return cls.one + return cls._new(rows, cols, entry) + + @classmethod + def _eval_zeros(cls, rows, cols): + return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False) + + @classmethod + def _eval_wilkinson(cls, n): + def entry(i, j): + return cls.one if i + 1 == j else cls.zero + + D = cls._new(2*n + 1, 2*n + 1, entry) + + wminus = cls.diag(list(range(-n, n + 1)), unpack=True) + D + D.T + wplus = abs(cls.diag(list(range(-n, n + 1)), unpack=True)) + D + D.T + + return wminus, wplus + + @classmethod + def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs): + """Returns a matrix with the specified diagonal. + If matrices are passed, a block-diagonal matrix + is created (i.e. the "direct sum" of the matrices). + + kwargs + ====== + + rows : rows of the resulting matrix; computed if + not given. + + cols : columns of the resulting matrix; computed if + not given. + + cls : class for the resulting matrix + + unpack : bool which, when True (default), unpacks a single + sequence rather than interpreting it as a Matrix. + + strict : bool which, when False (default), allows Matrices to + have variable-length rows. + + Examples + ======== + + >>> from sympy import Matrix + >>> Matrix.diag(1, 2, 3) + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + + The current default is to unpack a single sequence. If this is + not desired, set `unpack=False` and it will be interpreted as + a matrix. + + >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3) + True + + When more than one element is passed, each is interpreted as + something to put on the diagonal. Lists are converted to + matrices. Filling of the diagonal always continues from + the bottom right hand corner of the previous item: this + will create a block-diagonal matrix whether the matrices + are square or not. + + >>> col = [1, 2, 3] + >>> row = [[4, 5]] + >>> Matrix.diag(col, row) + Matrix([ + [1, 0, 0], + [2, 0, 0], + [3, 0, 0], + [0, 4, 5]]) + + When `unpack` is False, elements within a list need not all be + of the same length. Setting `strict` to True would raise a + ValueError for the following: + + >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False) + Matrix([ + [1, 2, 3], + [4, 5, 0], + [6, 0, 0]]) + + The type of the returned matrix can be set with the ``cls`` + keyword. + + >>> from sympy import ImmutableMatrix + >>> from sympy.utilities.misc import func_name + >>> func_name(Matrix.diag(1, cls=ImmutableMatrix)) + 'ImmutableDenseMatrix' + + A zero dimension matrix can be used to position the start of + the filling at the start of an arbitrary row or column: + + >>> from sympy import ones + >>> r2 = ones(0, 2) + >>> Matrix.diag(r2, 1, 2) + Matrix([ + [0, 0, 1, 0], + [0, 0, 0, 2]]) + + See Also + ======== + eye + diagonal + .dense.diag + .expressions.blockmatrix.BlockMatrix + .sparsetools.banded + """ + from sympy.matrices.matrixbase import MatrixBase + from sympy.matrices.dense import Matrix + from sympy.matrices import SparseMatrix + klass = kwargs.get('cls', kls) + if unpack and len(args) == 1 and is_sequence(args[0]) and \ + not isinstance(args[0], MatrixBase): + args = args[0] + + # fill a default dict with the diagonal entries + diag_entries = defaultdict(int) + rmax = cmax = 0 # keep track of the biggest index seen + for m in args: + if isinstance(m, list): + if strict: + # if malformed, Matrix will raise an error + _ = Matrix(m) + r, c = _.shape + m = _.tolist() + else: + r, c, smat = SparseMatrix._handle_creation_inputs(m) + for (i, j), _ in smat.items(): + diag_entries[(i + rmax, j + cmax)] = _ + m = [] # to skip process below + elif hasattr(m, 'shape'): # a Matrix + # convert to list of lists + r, c = m.shape + m = m.tolist() + else: # in this case, we're a single value + diag_entries[(rmax, cmax)] = m + rmax += 1 + cmax += 1 + continue + # process list of lists + for i, mi in enumerate(m): + for j, _ in enumerate(mi): + diag_entries[(i + rmax, j + cmax)] = _ + rmax += r + cmax += c + if rows is None: + rows, cols = cols, rows + if rows is None: + rows, cols = rmax, cmax + else: + cols = rows if cols is None else cols + if rows < rmax or cols < cmax: + raise ValueError(filldedent(''' + The constructed matrix is {} x {} but a size of {} x {} + was specified.'''.format(rmax, cmax, rows, cols))) + return klass._eval_diag(rows, cols, diag_entries) + + @classmethod + def eye(kls, rows, cols=None, **kwargs): + """Returns an identity matrix. + + Parameters + ========== + + rows : rows of the matrix + cols : cols of the matrix (if None, cols=rows) + + kwargs + ====== + cls : class of the returned matrix + """ + if cols is None: + cols = rows + if rows < 0 or cols < 0: + raise ValueError("Cannot create a {} x {} matrix. " + "Both dimensions must be positive".format(rows, cols)) + klass = kwargs.get('cls', kls) + rows, cols = as_int(rows), as_int(cols) + + return klass._eval_eye(rows, cols) + + @classmethod + def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): + """Returns a Jordan block + + Parameters + ========== + + size : Integer, optional + Specifies the shape of the Jordan block matrix. + + eigenvalue : Number or Symbol + Specifies the value for the main diagonal of the matrix. + + .. note:: + The keyword ``eigenval`` is also specified as an alias + of this keyword, but it is not recommended to use. + + We may deprecate the alias in later release. + + band : 'upper' or 'lower', optional + Specifies the position of the off-diagonal to put `1` s on. + + cls : Matrix, optional + Specifies the matrix class of the output form. + + If it is not specified, the class type where the method is + being executed on will be returned. + + Returns + ======= + + Matrix + A Jordan block matrix. + + Raises + ====== + + ValueError + If insufficient arguments are given for matrix size + specification, or no eigenvalue is given. + + Examples + ======== + + Creating a default Jordan block: + + >>> from sympy import Matrix + >>> from sympy.abc import x + >>> Matrix.jordan_block(4, x) + Matrix([ + [x, 1, 0, 0], + [0, x, 1, 0], + [0, 0, x, 1], + [0, 0, 0, x]]) + + Creating an alternative Jordan block matrix where `1` is on + lower off-diagonal: + + >>> Matrix.jordan_block(4, x, band='lower') + Matrix([ + [x, 0, 0, 0], + [1, x, 0, 0], + [0, 1, x, 0], + [0, 0, 1, x]]) + + Creating a Jordan block with keyword arguments + + >>> Matrix.jordan_block(size=4, eigenvalue=x) + Matrix([ + [x, 1, 0, 0], + [0, x, 1, 0], + [0, 0, x, 1], + [0, 0, 0, x]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Jordan_matrix + """ + klass = kwargs.pop('cls', kls) + + eigenval = kwargs.get('eigenval', None) + if eigenvalue is None and eigenval is None: + raise ValueError("Must supply an eigenvalue") + elif eigenvalue != eigenval and None not in (eigenval, eigenvalue): + raise ValueError( + "Inconsistent values are given: 'eigenval'={}, " + "'eigenvalue'={}".format(eigenval, eigenvalue)) + else: + if eigenval is not None: + eigenvalue = eigenval + + if size is None: + raise ValueError("Must supply a matrix size") + + size = as_int(size) + return klass._eval_jordan_block(size, eigenvalue, band) + + @classmethod + def ones(kls, rows, cols=None, **kwargs): + """Returns a matrix of ones. + + Parameters + ========== + + rows : rows of the matrix + cols : cols of the matrix (if None, cols=rows) + + kwargs + ====== + cls : class of the returned matrix + """ + if cols is None: + cols = rows + klass = kwargs.get('cls', kls) + rows, cols = as_int(rows), as_int(cols) + + return klass._eval_ones(rows, cols) + + @classmethod + def zeros(kls, rows, cols=None, **kwargs): + """Returns a matrix of zeros. + + Parameters + ========== + + rows : rows of the matrix + cols : cols of the matrix (if None, cols=rows) + + kwargs + ====== + cls : class of the returned matrix + """ + if cols is None: + cols = rows + if rows < 0 or cols < 0: + raise ValueError("Cannot create a {} x {} matrix. " + "Both dimensions must be positive".format(rows, cols)) + klass = kwargs.get('cls', kls) + rows, cols = as_int(rows), as_int(cols) + + return klass._eval_zeros(rows, cols) + + @classmethod + def companion(kls, poly): + """Returns a companion matrix of a polynomial. + + Examples + ======== + + >>> from sympy import Matrix, Poly, Symbol, symbols + >>> x = Symbol('x') + >>> c0, c1, c2, c3, c4 = symbols('c0:5') + >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) + >>> Matrix.companion(p) + Matrix([ + [0, 0, 0, 0, -c0], + [1, 0, 0, 0, -c1], + [0, 1, 0, 0, -c2], + [0, 0, 1, 0, -c3], + [0, 0, 0, 1, -c4]]) + """ + poly = kls._sympify(poly) + if not isinstance(poly, Poly): + raise ValueError("{} must be a Poly instance.".format(poly)) + if not poly.is_monic: + raise ValueError("{} must be a monic polynomial.".format(poly)) + if not poly.is_univariate: + raise ValueError( + "{} must be a univariate polynomial.".format(poly)) + + size = poly.degree() + if not size >= 1: + raise ValueError( + "{} must have degree not less than 1.".format(poly)) + + coeffs = poly.all_coeffs() + def entry(i, j): + if j == size - 1: + return -coeffs[-1 - i] + elif i == j + 1: + return kls.one + return kls.zero + return kls._new(size, size, entry) + + + @classmethod + def wilkinson(kls, n, **kwargs): + """Returns two square Wilkinson Matrix of size 2*n + 1 + $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n) + + Examples + ======== + + >>> from sympy import Matrix + >>> wminus, wplus = Matrix.wilkinson(3) + >>> wminus + Matrix([ + [-3, 1, 0, 0, 0, 0, 0], + [ 1, -2, 1, 0, 0, 0, 0], + [ 0, 1, -1, 1, 0, 0, 0], + [ 0, 0, 1, 0, 1, 0, 0], + [ 0, 0, 0, 1, 1, 1, 0], + [ 0, 0, 0, 0, 1, 2, 1], + [ 0, 0, 0, 0, 0, 1, 3]]) + >>> wplus + Matrix([ + [3, 1, 0, 0, 0, 0, 0], + [1, 2, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 1, 2, 1], + [0, 0, 0, 0, 0, 1, 3]]) + + References + ========== + + .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/ + .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp. + + """ + klass = kwargs.get('cls', kls) + n = as_int(n) + return klass._eval_wilkinson(n) + +class MatrixProperties(MatrixRequired): + """Provides basic properties of a matrix.""" + + def _eval_atoms(self, *types): + result = set() + for i in self: + result.update(i.atoms(*types)) + return result + + def _eval_free_symbols(self): + return set().union(*(i.free_symbols for i in self if i)) + + def _eval_has(self, *patterns): + return any(a.has(*patterns) for a in self) + + def _eval_is_anti_symmetric(self, simpfunc): + if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)): + return False + return True + + def _eval_is_diagonal(self): + for i in range(self.rows): + for j in range(self.cols): + if i != j and self[i, j]: + return False + return True + + # _eval_is_hermitian is called by some general SymPy + # routines and has a different *args signature. Make + # sure the names don't clash by adding `_matrix_` in name. + def _eval_is_matrix_hermitian(self, simpfunc): + mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate())) + return mat.is_zero_matrix + + def _eval_is_Identity(self) -> FuzzyBool: + def dirac(i, j): + if i == j: + return 1 + return 0 + + return all(self[i, j] == dirac(i, j) + for i in range(self.rows) + for j in range(self.cols)) + + def _eval_is_lower_hessenberg(self): + return all(self[i, j].is_zero + for i in range(self.rows) + for j in range(i + 2, self.cols)) + + def _eval_is_lower(self): + return all(self[i, j].is_zero + for i in range(self.rows) + for j in range(i + 1, self.cols)) + + def _eval_is_symbolic(self): + return self.has(Symbol) + + def _eval_is_symmetric(self, simpfunc): + mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i])) + return mat.is_zero_matrix + + def _eval_is_zero_matrix(self): + if any(i.is_zero == False for i in self): + return False + if any(i.is_zero is None for i in self): + return None + return True + + def _eval_is_upper_hessenberg(self): + return all(self[i, j].is_zero + for i in range(2, self.rows) + for j in range(min(self.cols, (i - 1)))) + + def _eval_values(self): + return [i for i in self if not i.is_zero] + + def _has_positive_diagonals(self): + diagonal_entries = (self[i, i] for i in range(self.rows)) + return fuzzy_and(x.is_positive for x in diagonal_entries) + + def _has_nonnegative_diagonals(self): + diagonal_entries = (self[i, i] for i in range(self.rows)) + return fuzzy_and(x.is_nonnegative for x in diagonal_entries) + + def atoms(self, *types): + """Returns the atoms that form the current object. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import Matrix + >>> Matrix([[x]]) + Matrix([[x]]) + >>> _.atoms() + {x} + >>> Matrix([[x, y], [y, x]]) + Matrix([ + [x, y], + [y, x]]) + >>> _.atoms() + {x, y} + """ + + types = tuple(t if isinstance(t, type) else type(t) for t in types) + if not types: + types = (Atom,) + return self._eval_atoms(*types) + + @property + def free_symbols(self): + """Returns the free symbols within the matrix. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import Matrix + >>> Matrix([[x], [1]]).free_symbols + {x} + """ + return self._eval_free_symbols() + + def has(self, *patterns): + """Test whether any subexpression matches any of the patterns. + + Examples + ======== + + >>> from sympy import Matrix, SparseMatrix, Float + >>> from sympy.abc import x, y + >>> A = Matrix(((1, x), (0.2, 3))) + >>> B = SparseMatrix(((1, x), (0.2, 3))) + >>> A.has(x) + True + >>> A.has(y) + False + >>> A.has(Float) + True + >>> B.has(x) + True + >>> B.has(y) + False + >>> B.has(Float) + True + """ + return self._eval_has(*patterns) + + def is_anti_symmetric(self, simplify=True): + """Check if matrix M is an antisymmetric matrix, + that is, M is a square matrix with all M[i, j] == -M[j, i]. + + When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is + simplified before testing to see if it is zero. By default, + the SymPy simplify function is used. To use a custom function + set simplify to a function that accepts a single argument which + returns a simplified expression. To skip simplification, set + simplify to False but note that although this will be faster, + it may induce false negatives. + + Examples + ======== + + >>> from sympy import Matrix, symbols + >>> m = Matrix(2, 2, [0, 1, -1, 0]) + >>> m + Matrix([ + [ 0, 1], + [-1, 0]]) + >>> m.is_anti_symmetric() + True + >>> x, y = symbols('x y') + >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0]) + >>> m + Matrix([ + [ 0, 0, x], + [-y, 0, 0]]) + >>> m.is_anti_symmetric() + False + + >>> from sympy.abc import x, y + >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, + ... -(x + 1)**2, 0, x*y, + ... -y, -x*y, 0]) + + Simplification of matrix elements is done by default so even + though two elements which should be equal and opposite would not + pass an equality test, the matrix is still reported as + anti-symmetric: + + >>> m[0, 1] == -m[1, 0] + False + >>> m.is_anti_symmetric() + True + + If ``simplify=False`` is used for the case when a Matrix is already + simplified, this will speed things up. Here, we see that without + simplification the matrix does not appear anti-symmetric: + + >>> print(m.is_anti_symmetric(simplify=False)) + None + + But if the matrix were already expanded, then it would appear + anti-symmetric and simplification in the is_anti_symmetric routine + is not needed: + + >>> m = m.expand() + >>> m.is_anti_symmetric(simplify=False) + True + """ + # accept custom simplification + simpfunc = simplify + if not isfunction(simplify): + simpfunc = _simplify if simplify else lambda x: x + + if not self.is_square: + return False + return self._eval_is_anti_symmetric(simpfunc) + + def is_diagonal(self): + """Check if matrix is diagonal, + that is matrix in which the entries outside the main diagonal are all zero. + + Examples + ======== + + >>> from sympy import Matrix, diag + >>> m = Matrix(2, 2, [1, 0, 0, 2]) + >>> m + Matrix([ + [1, 0], + [0, 2]]) + >>> m.is_diagonal() + True + + >>> m = Matrix(2, 2, [1, 1, 0, 2]) + >>> m + Matrix([ + [1, 1], + [0, 2]]) + >>> m.is_diagonal() + False + + >>> m = diag(1, 2, 3) + >>> m + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + >>> m.is_diagonal() + True + + See Also + ======== + + is_lower + is_upper + sympy.matrices.matrixbase.MatrixCommon.is_diagonalizable + diagonalize + """ + return self._eval_is_diagonal() + + @property + def is_weakly_diagonally_dominant(self): + r"""Tests if the matrix is row weakly diagonally dominant. + + Explanation + =========== + + A $n, n$ matrix $A$ is row weakly diagonally dominant if + + .. math:: + \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1} + \left|A_{i, j}\right| \quad {\text{for all }} + i \in \{ 0, ..., n-1 \} + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) + >>> A.is_weakly_diagonally_dominant + True + + >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) + >>> A.is_weakly_diagonally_dominant + False + + >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) + >>> A.is_weakly_diagonally_dominant + True + + Notes + ===== + + If you want to test whether a matrix is column diagonally + dominant, you can apply the test after transposing the matrix. + """ + if not self.is_square: + return False + + rows, cols = self.shape + + def test_row(i): + summation = self.zero + for j in range(cols): + if i != j: + summation += Abs(self[i, j]) + return (Abs(self[i, i]) - summation).is_nonnegative + + return fuzzy_and(test_row(i) for i in range(rows)) + + @property + def is_strongly_diagonally_dominant(self): + r"""Tests if the matrix is row strongly diagonally dominant. + + Explanation + =========== + + A $n, n$ matrix $A$ is row strongly diagonally dominant if + + .. math:: + \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1} + \left|A_{i, j}\right| \quad {\text{for all }} + i \in \{ 0, ..., n-1 \} + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) + >>> A.is_strongly_diagonally_dominant + False + + >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) + >>> A.is_strongly_diagonally_dominant + False + + >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) + >>> A.is_strongly_diagonally_dominant + True + + Notes + ===== + + If you want to test whether a matrix is column diagonally + dominant, you can apply the test after transposing the matrix. + """ + if not self.is_square: + return False + + rows, cols = self.shape + + def test_row(i): + summation = self.zero + for j in range(cols): + if i != j: + summation += Abs(self[i, j]) + return (Abs(self[i, i]) - summation).is_positive + + return fuzzy_and(test_row(i) for i in range(rows)) + + @property + def is_hermitian(self): + """Checks if the matrix is Hermitian. + + In a Hermitian matrix element i,j is the complex conjugate of + element j,i. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy import I + >>> from sympy.abc import x + >>> a = Matrix([[1, I], [-I, 1]]) + >>> a + Matrix([ + [ 1, I], + [-I, 1]]) + >>> a.is_hermitian + True + >>> a[0, 0] = 2*I + >>> a.is_hermitian + False + >>> a[0, 0] = x + >>> a.is_hermitian + >>> a[0, 1] = a[1, 0]*I + >>> a.is_hermitian + False + """ + if not self.is_square: + return False + + return self._eval_is_matrix_hermitian(_simplify) + + @property + def is_Identity(self) -> FuzzyBool: + if not self.is_square: + return False + return self._eval_is_Identity() + + @property + def is_lower_hessenberg(self): + r"""Checks if the matrix is in the lower-Hessenberg form. + + The lower hessenberg matrix has zero entries + above the first superdiagonal. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) + >>> a + Matrix([ + [1, 2, 0, 0], + [5, 2, 3, 0], + [3, 4, 3, 7], + [5, 6, 1, 1]]) + >>> a.is_lower_hessenberg + True + + See Also + ======== + + is_upper_hessenberg + is_lower + """ + return self._eval_is_lower_hessenberg() + + @property + def is_lower(self): + """Check if matrix is a lower triangular matrix. True can be returned + even if the matrix is not square. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, [1, 0, 0, 1]) + >>> m + Matrix([ + [1, 0], + [0, 1]]) + >>> m.is_lower + True + + >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5]) + >>> m + Matrix([ + [0, 0, 0], + [2, 0, 0], + [1, 4, 0], + [6, 6, 5]]) + >>> m.is_lower + True + + >>> from sympy.abc import x, y + >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y]) + >>> m + Matrix([ + [x**2 + y, x + y**2], + [ 0, x + y]]) + >>> m.is_lower + False + + See Also + ======== + + is_upper + is_diagonal + is_lower_hessenberg + """ + return self._eval_is_lower() + + @property + def is_square(self): + """Checks if a matrix is square. + + A matrix is square if the number of rows equals the number of columns. + The empty matrix is square by definition, since the number of rows and + the number of columns are both zero. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[1, 2, 3], [4, 5, 6]]) + >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> c = Matrix([]) + >>> a.is_square + False + >>> b.is_square + True + >>> c.is_square + True + """ + return self.rows == self.cols + + def is_symbolic(self): + """Checks if any elements contain Symbols. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.is_symbolic() + True + + """ + return self._eval_is_symbolic() + + def is_symmetric(self, simplify=True): + """Check if matrix is symmetric matrix, + that is square matrix and is equal to its transpose. + + By default, simplifications occur before testing symmetry. + They can be skipped using 'simplify=False'; while speeding things a bit, + this may however induce false negatives. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, [0, 1, 1, 2]) + >>> m + Matrix([ + [0, 1], + [1, 2]]) + >>> m.is_symmetric() + True + + >>> m = Matrix(2, 2, [0, 1, 2, 0]) + >>> m + Matrix([ + [0, 1], + [2, 0]]) + >>> m.is_symmetric() + False + + >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0]) + >>> m + Matrix([ + [0, 0, 0], + [0, 0, 0]]) + >>> m.is_symmetric() + False + + >>> from sympy.abc import x, y + >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) + >>> m + Matrix([ + [ 1, x**2 + 2*x + 1, y], + [(x + 1)**2, 2, 0], + [ y, 0, 3]]) + >>> m.is_symmetric() + True + + If the matrix is already simplified, you may speed-up is_symmetric() + test by using 'simplify=False'. + + >>> bool(m.is_symmetric(simplify=False)) + False + >>> m1 = m.expand() + >>> m1.is_symmetric(simplify=False) + True + """ + simpfunc = simplify + if not isfunction(simplify): + simpfunc = _simplify if simplify else lambda x: x + + if not self.is_square: + return False + + return self._eval_is_symmetric(simpfunc) + + @property + def is_upper_hessenberg(self): + """Checks if the matrix is the upper-Hessenberg form. + + The upper hessenberg matrix has zero entries + below the first subdiagonal. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) + >>> a + Matrix([ + [1, 4, 2, 3], + [3, 4, 1, 7], + [0, 2, 3, 4], + [0, 0, 1, 3]]) + >>> a.is_upper_hessenberg + True + + See Also + ======== + + is_lower_hessenberg + is_upper + """ + return self._eval_is_upper_hessenberg() + + @property + def is_upper(self): + """Check if matrix is an upper triangular matrix. True can be returned + even if the matrix is not square. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, [1, 0, 0, 1]) + >>> m + Matrix([ + [1, 0], + [0, 1]]) + >>> m.is_upper + True + + >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) + >>> m + Matrix([ + [5, 1, 9], + [0, 4, 6], + [0, 0, 5], + [0, 0, 0]]) + >>> m.is_upper + True + + >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) + >>> m + Matrix([ + [4, 2, 5], + [6, 1, 1]]) + >>> m.is_upper + False + + See Also + ======== + + is_lower + is_diagonal + is_upper_hessenberg + """ + return all(self[i, j].is_zero + for i in range(1, self.rows) + for j in range(min(i, self.cols))) + + @property + def is_zero_matrix(self): + """Checks if a matrix is a zero matrix. + + A matrix is zero if every element is zero. A matrix need not be square + to be considered zero. The empty matrix is zero by the principle of + vacuous truth. For a matrix that may or may not be zero (e.g. + contains a symbol), this will be None + + Examples + ======== + + >>> from sympy import Matrix, zeros + >>> from sympy.abc import x + >>> a = Matrix([[0, 0], [0, 0]]) + >>> b = zeros(3, 4) + >>> c = Matrix([[0, 1], [0, 0]]) + >>> d = Matrix([]) + >>> e = Matrix([[x, 0], [0, 0]]) + >>> a.is_zero_matrix + True + >>> b.is_zero_matrix + True + >>> c.is_zero_matrix + False + >>> d.is_zero_matrix + True + >>> e.is_zero_matrix + """ + return self._eval_is_zero_matrix() + + def values(self): + """Return non-zero values of self.""" + return self._eval_values() + + +class MatrixOperations(MatrixRequired): + """Provides basic matrix shape and elementwise + operations. Should not be instantiated directly.""" + + def _eval_adjoint(self): + return self.transpose().conjugate() + + def _eval_applyfunc(self, f): + out = self._new(self.rows, self.cols, [f(x) for x in self]) + return out + + def _eval_as_real_imag(self): # type: ignore + return (self.applyfunc(re), self.applyfunc(im)) + + def _eval_conjugate(self): + return self.applyfunc(lambda x: x.conjugate()) + + def _eval_permute_cols(self, perm): + # apply the permutation to a list + mapping = list(perm) + + def entry(i, j): + return self[i, mapping[j]] + + return self._new(self.rows, self.cols, entry) + + def _eval_permute_rows(self, perm): + # apply the permutation to a list + mapping = list(perm) + + def entry(i, j): + return self[mapping[i], j] + + return self._new(self.rows, self.cols, entry) + + def _eval_trace(self): + return sum(self[i, i] for i in range(self.rows)) + + def _eval_transpose(self): + return self._new(self.cols, self.rows, lambda i, j: self[j, i]) + + def adjoint(self): + """Conjugate transpose or Hermitian conjugation.""" + return self._eval_adjoint() + + def applyfunc(self, f): + """Apply a function to each element of the matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, lambda i, j: i*2+j) + >>> m + Matrix([ + [0, 1], + [2, 3]]) + >>> m.applyfunc(lambda i: 2*i) + Matrix([ + [0, 2], + [4, 6]]) + + """ + if not callable(f): + raise TypeError("`f` must be callable.") + + return self._eval_applyfunc(f) + + def as_real_imag(self, deep=True, **hints): + """Returns a tuple containing the (real, imaginary) part of matrix.""" + # XXX: Ignoring deep and hints... + return self._eval_as_real_imag() + + def conjugate(self): + """Return the by-element conjugation. + + Examples + ======== + + >>> from sympy import SparseMatrix, I + >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I))) + >>> a + Matrix([ + [1, 2 + I], + [3, 4], + [I, -I]]) + >>> a.C + Matrix([ + [ 1, 2 - I], + [ 3, 4], + [-I, I]]) + + See Also + ======== + + transpose: Matrix transposition + H: Hermite conjugation + sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation + """ + return self._eval_conjugate() + + def doit(self, **hints): + return self.applyfunc(lambda x: x.doit(**hints)) + + def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): + """Apply evalf() to each element of self.""" + options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, + 'quad':quad, 'verbose':verbose} + return self.applyfunc(lambda i: i.evalf(n, **options)) + + def expand(self, deep=True, modulus=None, power_base=True, power_exp=True, + mul=True, log=True, multinomial=True, basic=True, **hints): + """Apply core.function.expand to each entry of the matrix. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import Matrix + >>> Matrix(1, 1, [x*(x+1)]) + Matrix([[x*(x + 1)]]) + >>> _.expand() + Matrix([[x**2 + x]]) + + """ + return self.applyfunc(lambda x: x.expand( + deep, modulus, power_base, power_exp, mul, log, multinomial, basic, + **hints)) + + @property + def H(self): + """Return Hermite conjugate. + + Examples + ======== + + >>> from sympy import Matrix, I + >>> m = Matrix((0, 1 + I, 2, 3)) + >>> m + Matrix([ + [ 0], + [1 + I], + [ 2], + [ 3]]) + >>> m.H + Matrix([[0, 1 - I, 2, 3]]) + + See Also + ======== + + conjugate: By-element conjugation + sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation + """ + return self.T.C + + def permute(self, perm, orientation='rows', direction='forward'): + r"""Permute the rows or columns of a matrix by the given list of + swaps. + + Parameters + ========== + + perm : Permutation, list, or list of lists + A representation for the permutation. + + If it is ``Permutation``, it is used directly with some + resizing with respect to the matrix size. + + If it is specified as list of lists, + (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed + from applying the product of cycles. The direction how the + cyclic product is applied is described in below. + + If it is specified as a list, the list should represent + an array form of a permutation. (e.g., ``[1, 2, 0]``) which + would would form the swapping function + `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`. + + orientation : 'rows', 'cols' + A flag to control whether to permute the rows or the columns + + direction : 'forward', 'backward' + A flag to control whether to apply the permutations from + the start of the list first, or from the back of the list + first. + + For example, if the permutation specification is + ``[[0, 1], [0, 2]]``, + + If the flag is set to ``'forward'``, the cycle would be + formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`. + + If the flag is set to ``'backward'``, the cycle would be + formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`. + + If the argument ``perm`` is not in a form of list of lists, + this flag takes no effect. + + Examples + ======== + + >>> from sympy import eye + >>> M = eye(3) + >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward') + Matrix([ + [0, 0, 1], + [1, 0, 0], + [0, 1, 0]]) + + >>> from sympy import eye + >>> M = eye(3) + >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward') + Matrix([ + [0, 1, 0], + [0, 0, 1], + [1, 0, 0]]) + + Notes + ===== + + If a bijective function + `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the + permutation. + + If the matrix `A` is the matrix to permute, represented as + a horizontal or a vertical stack of vectors: + + .. math:: + A = + \begin{bmatrix} + a_0 \\ a_1 \\ \vdots \\ a_{n-1} + \end{bmatrix} = + \begin{bmatrix} + \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1} + \end{bmatrix} + + If the matrix `B` is the result, the permutation of matrix rows + is defined as: + + .. math:: + B := \begin{bmatrix} + a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)} + \end{bmatrix} + + And the permutation of matrix columns is defined as: + + .. math:: + B := \begin{bmatrix} + \alpha_{\sigma(0)} & \alpha_{\sigma(1)} & + \cdots & \alpha_{\sigma(n-1)} + \end{bmatrix} + """ + from sympy.combinatorics import Permutation + + # allow british variants and `columns` + if direction == 'forwards': + direction = 'forward' + if direction == 'backwards': + direction = 'backward' + if orientation == 'columns': + orientation = 'cols' + + if direction not in ('forward', 'backward'): + raise TypeError("direction='{}' is an invalid kwarg. " + "Try 'forward' or 'backward'".format(direction)) + if orientation not in ('rows', 'cols'): + raise TypeError("orientation='{}' is an invalid kwarg. " + "Try 'rows' or 'cols'".format(orientation)) + + if not isinstance(perm, (Permutation, Iterable)): + raise ValueError( + "{} must be a list, a list of lists, " + "or a SymPy permutation object.".format(perm)) + + # ensure all swaps are in range + max_index = self.rows if orientation == 'rows' else self.cols + if not all(0 <= t <= max_index for t in flatten(list(perm))): + raise IndexError("`swap` indices out of range.") + + if perm and not isinstance(perm, Permutation) and \ + isinstance(perm[0], Iterable): + if direction == 'forward': + perm = list(reversed(perm)) + perm = Permutation(perm, size=max_index+1) + else: + perm = Permutation(perm, size=max_index+1) + + if orientation == 'rows': + return self._eval_permute_rows(perm) + if orientation == 'cols': + return self._eval_permute_cols(perm) + + def permute_cols(self, swaps, direction='forward'): + """Alias for + ``self.permute(swaps, orientation='cols', direction=direction)`` + + See Also + ======== + + permute + """ + return self.permute(swaps, orientation='cols', direction=direction) + + def permute_rows(self, swaps, direction='forward'): + """Alias for + ``self.permute(swaps, orientation='rows', direction=direction)`` + + See Also + ======== + + permute + """ + return self.permute(swaps, orientation='rows', direction=direction) + + def refine(self, assumptions=True): + """Apply refine to each element of the matrix. + + Examples + ======== + + >>> from sympy import Symbol, Matrix, Abs, sqrt, Q + >>> x = Symbol('x') + >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]]) + Matrix([ + [ Abs(x)**2, sqrt(x**2)], + [sqrt(x**2), Abs(x)**2]]) + >>> _.refine(Q.real(x)) + Matrix([ + [ x**2, Abs(x)], + [Abs(x), x**2]]) + + """ + return self.applyfunc(lambda x: refine(x, assumptions)) + + def replace(self, F, G, map=False, simultaneous=True, exact=None): + """Replaces Function F in Matrix entries with Function G. + + Examples + ======== + + >>> from sympy import symbols, Function, Matrix + >>> F, G = symbols('F, G', cls=Function) + >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M + Matrix([ + [F(0), F(1)], + [F(1), F(2)]]) + >>> N = M.replace(F,G) + >>> N + Matrix([ + [G(0), G(1)], + [G(1), G(2)]]) + """ + return self.applyfunc( + lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact)) + + def rot90(self, k=1): + """Rotates Matrix by 90 degrees + + Parameters + ========== + + k : int + Specifies how many times the matrix is rotated by 90 degrees + (clockwise when positive, counter-clockwise when negative). + + Examples + ======== + + >>> from sympy import Matrix, symbols + >>> A = Matrix(2, 2, symbols('a:d')) + >>> A + Matrix([ + [a, b], + [c, d]]) + + Rotating the matrix clockwise one time: + + >>> A.rot90(1) + Matrix([ + [c, a], + [d, b]]) + + Rotating the matrix anticlockwise two times: + + >>> A.rot90(-2) + Matrix([ + [d, c], + [b, a]]) + """ + + mod = k%4 + if mod == 0: + return self + if mod == 1: + return self[::-1, ::].T + if mod == 2: + return self[::-1, ::-1] + if mod == 3: + return self[::, ::-1].T + + def simplify(self, **kwargs): + """Apply simplify to each element of the matrix. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import SparseMatrix, sin, cos + >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2]) + Matrix([[x*sin(y)**2 + x*cos(y)**2]]) + >>> _.simplify() + Matrix([[x]]) + """ + return self.applyfunc(lambda x: x.simplify(**kwargs)) + + def subs(self, *args, **kwargs): # should mirror core.basic.subs + """Return a new matrix with subs applied to each entry. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import SparseMatrix, Matrix + >>> SparseMatrix(1, 1, [x]) + Matrix([[x]]) + >>> _.subs(x, y) + Matrix([[y]]) + >>> Matrix(_).subs(y, x) + Matrix([[x]]) + """ + + if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]): + args = (list(args[0]),) + + return self.applyfunc(lambda x: x.subs(*args, **kwargs)) + + def trace(self): + """ + Returns the trace of a square matrix i.e. the sum of the + diagonal elements. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix(2, 2, [1, 2, 3, 4]) + >>> A.trace() + 5 + + """ + if self.rows != self.cols: + raise NonSquareMatrixError() + return self._eval_trace() + + def transpose(self): + """ + Returns the transpose of the matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix(2, 2, [1, 2, 3, 4]) + >>> A.transpose() + Matrix([ + [1, 3], + [2, 4]]) + + >>> from sympy import Matrix, I + >>> m=Matrix(((1, 2+I), (3, 4))) + >>> m + Matrix([ + [1, 2 + I], + [3, 4]]) + >>> m.transpose() + Matrix([ + [ 1, 3], + [2 + I, 4]]) + >>> m.T == m.transpose() + True + + See Also + ======== + + conjugate: By-element conjugation + + """ + return self._eval_transpose() + + @property + def T(self): + '''Matrix transposition''' + return self.transpose() + + @property + def C(self): + '''By-element conjugation''' + return self.conjugate() + + def n(self, *args, **kwargs): + """Apply evalf() to each element of self.""" + return self.evalf(*args, **kwargs) + + def xreplace(self, rule): # should mirror core.basic.xreplace + """Return a new matrix with xreplace applied to each entry. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import SparseMatrix, Matrix + >>> SparseMatrix(1, 1, [x]) + Matrix([[x]]) + >>> _.xreplace({x: y}) + Matrix([[y]]) + >>> Matrix(_).xreplace({y: x}) + Matrix([[x]]) + """ + return self.applyfunc(lambda x: x.xreplace(rule)) + + def _eval_simplify(self, **kwargs): + # XXX: We can't use self.simplify here as mutable subclasses will + # override simplify and have it return None + return MatrixOperations.simplify(self, **kwargs) + + def _eval_trigsimp(self, **opts): + from sympy.simplify.trigsimp import trigsimp + return self.applyfunc(lambda x: trigsimp(x, **opts)) + + def upper_triangular(self, k=0): + """Return the elements on and above the kth diagonal of a matrix. + If k is not specified then simply returns upper-triangular portion + of a matrix + + Examples + ======== + + >>> from sympy import ones + >>> A = ones(4) + >>> A.upper_triangular() + Matrix([ + [1, 1, 1, 1], + [0, 1, 1, 1], + [0, 0, 1, 1], + [0, 0, 0, 1]]) + + >>> A.upper_triangular(2) + Matrix([ + [0, 0, 1, 1], + [0, 0, 0, 1], + [0, 0, 0, 0], + [0, 0, 0, 0]]) + + >>> A.upper_triangular(-1) + Matrix([ + [1, 1, 1, 1], + [1, 1, 1, 1], + [0, 1, 1, 1], + [0, 0, 1, 1]]) + + """ + + def entry(i, j): + return self[i, j] if i + k <= j else self.zero + + return self._new(self.rows, self.cols, entry) + + + def lower_triangular(self, k=0): + """Return the elements on and below the kth diagonal of a matrix. + If k is not specified then simply returns lower-triangular portion + of a matrix + + Examples + ======== + + >>> from sympy import ones + >>> A = ones(4) + >>> A.lower_triangular() + Matrix([ + [1, 0, 0, 0], + [1, 1, 0, 0], + [1, 1, 1, 0], + [1, 1, 1, 1]]) + + >>> A.lower_triangular(-2) + Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 0, 0, 0], + [1, 1, 0, 0]]) + + >>> A.lower_triangular(1) + Matrix([ + [1, 1, 0, 0], + [1, 1, 1, 0], + [1, 1, 1, 1], + [1, 1, 1, 1]]) + + """ + + def entry(i, j): + return self[i, j] if i + k >= j else self.zero + + return self._new(self.rows, self.cols, entry) + + + +class MatrixArithmetic(MatrixRequired): + """Provides basic matrix arithmetic operations. + Should not be instantiated directly.""" + + _op_priority = 10.01 + + def _eval_Abs(self): + return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j])) + + def _eval_add(self, other): + return self._new(self.rows, self.cols, + lambda i, j: self[i, j] + other[i, j]) + + def _eval_matrix_mul(self, other): + def entry(i, j): + vec = [self[i,k]*other[k,j] for k in range(self.cols)] + try: + return Add(*vec) + except (TypeError, SympifyError): + # Some matrices don't work with `sum` or `Add` + # They don't work with `sum` because `sum` tries to add `0` + # Fall back to a safe way to multiply if the `Add` fails. + return reduce(lambda a, b: a + b, vec) + + return self._new(self.rows, other.cols, entry) + + def _eval_matrix_mul_elementwise(self, other): + return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j]) + + def _eval_matrix_rmul(self, other): + def entry(i, j): + return sum(other[i,k]*self[k,j] for k in range(other.cols)) + return self._new(other.rows, self.cols, entry) + + def _eval_pow_by_recursion(self, num): + if num == 1: + return self + + if num % 2 == 1: + a, b = self, self._eval_pow_by_recursion(num - 1) + else: + a = b = self._eval_pow_by_recursion(num // 2) + + return a.multiply(b) + + def _eval_pow_by_cayley(self, exp): + from sympy.discrete.recurrences import linrec_coeffs + row = self.shape[0] + p = self.charpoly() + + coeffs = (-p).all_coeffs()[1:] + coeffs = linrec_coeffs(coeffs, exp) + new_mat = self.eye(row) + ans = self.zeros(row) + + for i in range(row): + ans += coeffs[i]*new_mat + new_mat *= self + + return ans + + def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None): + if prevsimp is None: + prevsimp = [True]*len(self) + + if num == 1: + return self + + if num % 2 == 1: + a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1, + prevsimp=prevsimp) + else: + a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2, + prevsimp=prevsimp) + + m = a.multiply(b, dotprodsimp=False) + lenm = len(m) + elems = [None]*lenm + + for i in range(lenm): + if prevsimp[i]: + elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True) + else: + elems[i] = m[i] + + return m._new(m.rows, m.cols, elems) + + def _eval_scalar_mul(self, other): + return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other) + + def _eval_scalar_rmul(self, other): + return self._new(self.rows, self.cols, lambda i, j: other*self[i,j]) + + def _eval_Mod(self, other): + return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other)) + + # Python arithmetic functions + def __abs__(self): + """Returns a new matrix with entry-wise absolute values.""" + return self._eval_Abs() + + @call_highest_priority('__radd__') + def __add__(self, other): + """Return self + other, raising ShapeError if shapes do not match.""" + if isinstance(other, NDimArray): # Matrix and array addition is currently not implemented + return NotImplemented + other = _matrixify(other) + # matrix-like objects can have shapes. This is + # our first sanity check. + if hasattr(other, 'shape'): + if self.shape != other.shape: + raise ShapeError("Matrix size mismatch: %s + %s" % ( + self.shape, other.shape)) + + # honest SymPy matrices defer to their class's routine + if getattr(other, 'is_Matrix', False): + # call the highest-priority class's _eval_add + a, b = self, other + if a.__class__ != classof(a, b): + b, a = a, b + return a._eval_add(b) + # Matrix-like objects can be passed to CommonMatrix routines directly. + if getattr(other, 'is_MatrixLike', False): + return MatrixArithmetic._eval_add(self, other) + + raise TypeError('cannot add %s and %s' % (type(self), type(other))) + + @call_highest_priority('__rtruediv__') + def __truediv__(self, other): + return self * (self.one / other) + + @call_highest_priority('__rmatmul__') + def __matmul__(self, other): + other = _matrixify(other) + if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): + return NotImplemented + + return self.__mul__(other) + + def __mod__(self, other): + return self.applyfunc(lambda x: x % other) + + @call_highest_priority('__rmul__') + def __mul__(self, other): + """Return self*other where other is either a scalar or a matrix + of compatible dimensions. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) + >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]]) + True + >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> A*B + Matrix([ + [30, 36, 42], + [66, 81, 96]]) + >>> B*A + Traceback (most recent call last): + ... + ShapeError: Matrices size mismatch. + >>> + + See Also + ======== + + matrix_multiply_elementwise + """ + + return self.multiply(other) + + def multiply(self, other, dotprodsimp=None): + """Same as __mul__() but with optional simplification. + + Parameters + ========== + + dotprodsimp : bool, optional + Specifies whether intermediate term algebraic simplification is used + during matrix multiplications to control expression blowup and thus + speed up calculation. Default is off. + """ + + isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) + other = _matrixify(other) + # matrix-like objects can have shapes. This is + # our first sanity check. Double check other is not explicitly not a Matrix. + if (hasattr(other, 'shape') and len(other.shape) == 2 and + (getattr(other, 'is_Matrix', True) or + getattr(other, 'is_MatrixLike', True))): + if self.shape[1] != other.shape[0]: + raise ShapeError("Matrix size mismatch: %s * %s." % ( + self.shape, other.shape)) + + # honest SymPy matrices defer to their class's routine + if getattr(other, 'is_Matrix', False): + m = self._eval_matrix_mul(other) + if isimpbool: + return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) + return m + + # Matrix-like objects can be passed to CommonMatrix routines directly. + if getattr(other, 'is_MatrixLike', False): + return MatrixArithmetic._eval_matrix_mul(self, other) + + # if 'other' is not iterable then scalar multiplication. + if not isinstance(other, Iterable): + try: + return self._eval_scalar_mul(other) + except TypeError: + pass + + return NotImplemented + + def multiply_elementwise(self, other): + """Return the Hadamard product (elementwise product) of A and B + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) + >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) + >>> A.multiply_elementwise(B) + Matrix([ + [ 0, 10, 200], + [300, 40, 5]]) + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.cross + sympy.matrices.matrixbase.MatrixBase.dot + multiply + """ + if self.shape != other.shape: + raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape)) + + return self._eval_matrix_mul_elementwise(other) + + def __neg__(self): + return self._eval_scalar_mul(-1) + + @call_highest_priority('__rpow__') + def __pow__(self, exp): + """Return self**exp a scalar or symbol.""" + + return self.pow(exp) + + + def pow(self, exp, method=None): + r"""Return self**exp a scalar or symbol. + + Parameters + ========== + + method : multiply, mulsimp, jordan, cayley + If multiply then it returns exponentiation using recursion. + If jordan then Jordan form exponentiation will be used. + If cayley then the exponentiation is done using Cayley-Hamilton + theorem. + If mulsimp then the exponentiation is done using recursion + with dotprodsimp. This specifies whether intermediate term + algebraic simplification is used during naive matrix power to + control expression blowup and thus speed up calculation. + If None, then it heuristically decides which method to use. + + """ + + if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']: + raise TypeError('No such method') + if self.rows != self.cols: + raise NonSquareMatrixError() + a = self + jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None) + exp = sympify(exp) + + if exp.is_zero: + return a._new(a.rows, a.cols, lambda i, j: int(i == j)) + if exp == 1: + return a + + diagonal = getattr(a, 'is_diagonal', None) + if diagonal is not None and diagonal(): + return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0) + + if exp.is_Number and exp % 1 == 0: + if a.rows == 1: + return a._new([[a[0]**exp]]) + if exp < 0: + exp = -exp + a = a.inv() + # When certain conditions are met, + # Jordan block algorithm is faster than + # computation by recursion. + if method == 'jordan': + try: + return jordan_pow(exp) + except MatrixError: + if method == 'jordan': + raise + + elif method == 'cayley': + if not exp.is_Number or exp % 1 != 0: + raise ValueError("cayley method is only valid for integer powers") + return a._eval_pow_by_cayley(exp) + + elif method == "mulsimp": + if not exp.is_Number or exp % 1 != 0: + raise ValueError("mulsimp method is only valid for integer powers") + return a._eval_pow_by_recursion_dotprodsimp(exp) + + elif method == "multiply": + if not exp.is_Number or exp % 1 != 0: + raise ValueError("multiply method is only valid for integer powers") + return a._eval_pow_by_recursion(exp) + + elif method is None and exp.is_Number and exp % 1 == 0: + if exp.is_Float: + exp = Integer(exp) + # Decide heuristically which method to apply + if a.rows == 2 and exp > 100000: + return jordan_pow(exp) + elif _get_intermediate_simp_bool(True, None): + return a._eval_pow_by_recursion_dotprodsimp(exp) + elif exp > 10000: + return a._eval_pow_by_cayley(exp) + else: + return a._eval_pow_by_recursion(exp) + + if jordan_pow: + try: + return jordan_pow(exp) + except NonInvertibleMatrixError: + # Raised by jordan_pow on zero determinant matrix unless exp is + # definitely known to be a non-negative integer. + # Here we raise if n is definitely not a non-negative integer + # but otherwise we can leave this as an unevaluated MatPow. + if exp.is_integer is False or exp.is_nonnegative is False: + raise + + from sympy.matrices.expressions import MatPow + return MatPow(a, exp) + + @call_highest_priority('__add__') + def __radd__(self, other): + return self + other + + @call_highest_priority('__matmul__') + def __rmatmul__(self, other): + other = _matrixify(other) + if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): + return NotImplemented + + return self.__rmul__(other) + + @call_highest_priority('__mul__') + def __rmul__(self, other): + return self.rmultiply(other) + + def rmultiply(self, other, dotprodsimp=None): + """Same as __rmul__() but with optional simplification. + + Parameters + ========== + + dotprodsimp : bool, optional + Specifies whether intermediate term algebraic simplification is used + during matrix multiplications to control expression blowup and thus + speed up calculation. Default is off. + """ + isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) + other = _matrixify(other) + # matrix-like objects can have shapes. This is + # our first sanity check. Double check other is not explicitly not a Matrix. + if (hasattr(other, 'shape') and len(other.shape) == 2 and + (getattr(other, 'is_Matrix', True) or + getattr(other, 'is_MatrixLike', True))): + if self.shape[0] != other.shape[1]: + raise ShapeError("Matrix size mismatch.") + + # honest SymPy matrices defer to their class's routine + if getattr(other, 'is_Matrix', False): + m = self._eval_matrix_rmul(other) + if isimpbool: + return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) + return m + # Matrix-like objects can be passed to CommonMatrix routines directly. + if getattr(other, 'is_MatrixLike', False): + return MatrixArithmetic._eval_matrix_rmul(self, other) + + # if 'other' is not iterable then scalar multiplication. + if not isinstance(other, Iterable): + try: + return self._eval_scalar_rmul(other) + except TypeError: + pass + + return NotImplemented + + @call_highest_priority('__sub__') + def __rsub__(self, a): + return (-self) + a + + @call_highest_priority('__rsub__') + def __sub__(self, a): + return self + (-a) + + +class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties, + MatrixSpecial, MatrixShaping): + """All common matrix operations including basic arithmetic, shaping, + and special matrices like `zeros`, and `eye`.""" + _diff_wrt: bool = True + + +class _MinimalMatrix: + """Class providing the minimum functionality + for a matrix-like object and implementing every method + required for a `MatrixRequired`. This class does not have everything + needed to become a full-fledged SymPy object, but it will satisfy the + requirements of anything inheriting from `MatrixRequired`. If you wish + to make a specialized matrix type, make sure to implement these + methods and properties with the exception of `__init__` and `__repr__` + which are included for convenience.""" + + is_MatrixLike = True + _sympify = staticmethod(sympify) + _class_priority = 3 + zero = S.Zero + one = S.One + + is_Matrix = True + is_MatrixExpr = False + + @classmethod + def _new(cls, *args, **kwargs): + return cls(*args, **kwargs) + + def __init__(self, rows, cols=None, mat=None, copy=False): + if isfunction(mat): + # if we passed in a function, use that to populate the indices + mat = [mat(i, j) for i in range(rows) for j in range(cols)] + if cols is None and mat is None: + mat = rows + rows, cols = getattr(mat, 'shape', (rows, cols)) + try: + # if we passed in a list of lists, flatten it and set the size + if cols is None and mat is None: + mat = rows + cols = len(mat[0]) + rows = len(mat) + mat = [x for l in mat for x in l] + except (IndexError, TypeError): + pass + self.mat = tuple(self._sympify(x) for x in mat) + self.rows, self.cols = rows, cols + if self.rows is None or self.cols is None: + raise NotImplementedError("Cannot initialize matrix with given parameters") + + def __getitem__(self, key): + def _normalize_slices(row_slice, col_slice): + """Ensure that row_slice and col_slice do not have + `None` in their arguments. Any integers are converted + to slices of length 1""" + if not isinstance(row_slice, slice): + row_slice = slice(row_slice, row_slice + 1, None) + row_slice = slice(*row_slice.indices(self.rows)) + + if not isinstance(col_slice, slice): + col_slice = slice(col_slice, col_slice + 1, None) + col_slice = slice(*col_slice.indices(self.cols)) + + return (row_slice, col_slice) + + def _coord_to_index(i, j): + """Return the index in _mat corresponding + to the (i,j) position in the matrix. """ + return i * self.cols + j + + if isinstance(key, tuple): + i, j = key + if isinstance(i, slice) or isinstance(j, slice): + # if the coordinates are not slices, make them so + # and expand the slices so they don't contain `None` + i, j = _normalize_slices(i, j) + + rowsList, colsList = list(range(self.rows))[i], \ + list(range(self.cols))[j] + indices = (i * self.cols + j for i in rowsList for j in + colsList) + return self._new(len(rowsList), len(colsList), + [self.mat[i] for i in indices]) + + # if the key is a tuple of ints, change + # it to an array index + key = _coord_to_index(i, j) + return self.mat[key] + + def __eq__(self, other): + try: + classof(self, other) + except TypeError: + return False + return ( + self.shape == other.shape and list(self) == list(other)) + + def __len__(self): + return self.rows*self.cols + + def __repr__(self): + return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols, + self.mat) + + @property + def shape(self): + return (self.rows, self.cols) + + +class _CastableMatrix: # this is needed here ONLY FOR TESTS. + def as_mutable(self): + return self + + def as_immutable(self): + return self + + +class _MatrixWrapper: + """Wrapper class providing the minimum functionality for a matrix-like + object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix + math operations should work on matrix-like objects. This one is intended for + matrix-like objects which use the same indexing format as SymPy with respect + to returning matrix elements instead of rows for non-tuple indexes. + """ + + is_Matrix = False # needs to be here because of __getattr__ + is_MatrixLike = True + + def __init__(self, mat, shape): + self.mat = mat + self.shape = shape + self.rows, self.cols = shape + + def __getitem__(self, key): + if isinstance(key, tuple): + return sympify(self.mat.__getitem__(key)) + + return sympify(self.mat.__getitem__((key // self.rows, key % self.cols))) + + def __iter__(self): # supports numpy.matrix and numpy.array + mat = self.mat + cols = self.cols + + return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols)) + + +def _matrixify(mat): + """If `mat` is a Matrix or is matrix-like, + return a Matrix or MatrixWrapper object. Otherwise + `mat` is passed through without modification.""" + + if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False): + return mat + + if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)): + return mat + + shape = None + + if hasattr(mat, 'shape'): # numpy, scipy.sparse + if len(mat.shape) == 2: + shape = mat.shape + elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath + shape = (mat.rows, mat.cols) + + if shape: + return _MatrixWrapper(mat, shape) + + return mat + + +def a2idx(j, n=None): + """Return integer after making positive and validating against n.""" + if not isinstance(j, int): + jindex = getattr(j, '__index__', None) + if jindex is not None: + j = jindex() + else: + raise IndexError("Invalid index a[%r]" % (j,)) + if n is not None: + if j < 0: + j += n + if not (j >= 0 and j < n): + raise IndexError("Index out of range: a[%s]" % (j,)) + return int(j) + + +def classof(A, B): + """ + Get the type of the result when combining matrices of different types. + + Currently the strategy is that immutability is contagious. + + Examples + ======== + + >>> from sympy import Matrix, ImmutableMatrix + >>> from sympy.matrices.matrixbase import classof + >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix + >>> IM = ImmutableMatrix([[1, 2], [3, 4]]) + >>> classof(M, IM) + + """ + priority_A = getattr(A, '_class_priority', None) + priority_B = getattr(B, '_class_priority', None) + if None not in (priority_A, priority_B): + if A._class_priority > B._class_priority: + return A.__class__ + else: + return B.__class__ + + try: + import numpy + except ImportError: + pass + else: + if isinstance(A, numpy.ndarray): + return B.__class__ + if isinstance(B, numpy.ndarray): + return A.__class__ + + raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/decompositions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/decompositions.py new file mode 100644 index 0000000000000000000000000000000000000000..a8dd466d84c957b870396a050fd25ec21e7113a3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/decompositions.py @@ -0,0 +1,1621 @@ +import copy + +from sympy.core import S +from sympy.core.function import expand_mul +from sympy.functions.elementary.miscellaneous import Min, sqrt +from sympy.functions.elementary.complexes import sign + +from .exceptions import NonSquareMatrixError, NonPositiveDefiniteMatrixError +from .utilities import _get_intermediate_simp, _iszero +from .determinant import _find_reasonable_pivot_naive + + +def _rank_decomposition(M, iszerofunc=_iszero, simplify=False): + r"""Returns a pair of matrices (`C`, `F`) with matching rank + such that `A = C F`. + + Parameters + ========== + + iszerofunc : Function, optional + A function used for detecting whether an element can + act as a pivot. ``lambda x: x.is_zero`` is used by default. + + simplify : Bool or Function, optional + A function used to simplify elements when looking for a + pivot. By default SymPy's ``simplify`` is used. + + Returns + ======= + + (C, F) : Matrices + `C` and `F` are full-rank matrices with rank as same as `A`, + whose product gives `A`. + + See Notes for additional mathematical details. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([ + ... [1, 3, 1, 4], + ... [2, 7, 3, 9], + ... [1, 5, 3, 1], + ... [1, 2, 0, 8] + ... ]) + >>> C, F = A.rank_decomposition() + >>> C + Matrix([ + [1, 3, 4], + [2, 7, 9], + [1, 5, 1], + [1, 2, 8]]) + >>> F + Matrix([ + [1, 0, -2, 0], + [0, 1, 1, 0], + [0, 0, 0, 1]]) + >>> C * F == A + True + + Notes + ===== + + Obtaining `F`, an RREF of `A`, is equivalent to creating a + product + + .. math:: + E_n E_{n-1} ... E_1 A = F + + where `E_n, E_{n-1}, \dots, E_1` are the elimination matrices or + permutation matrices equivalent to each row-reduction step. + + The inverse of the same product of elimination matrices gives + `C`: + + .. math:: + C = \left(E_n E_{n-1} \dots E_1\right)^{-1} + + It is not necessary, however, to actually compute the inverse: + the columns of `C` are those from the original matrix with the + same column indices as the indices of the pivot columns of `F`. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Rank_factorization + + .. [2] Piziak, R.; Odell, P. L. (1 June 1999). + "Full Rank Factorization of Matrices". + Mathematics Magazine. 72 (3): 193. doi:10.2307/2690882 + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.rref + """ + + F, pivot_cols = M.rref(simplify=simplify, iszerofunc=iszerofunc, + pivots=True) + rank = len(pivot_cols) + + C = M.extract(range(M.rows), pivot_cols) + F = F[:rank, :] + + return C, F + + +def _liupc(M): + """Liu's algorithm, for pre-determination of the Elimination Tree of + the given matrix, used in row-based symbolic Cholesky factorization. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> S = SparseMatrix([ + ... [1, 0, 3, 2], + ... [0, 0, 1, 0], + ... [4, 0, 0, 5], + ... [0, 6, 7, 0]]) + >>> S.liupc() + ([[0], [], [0], [1, 2]], [4, 3, 4, 4]) + + References + ========== + + .. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees, + Jeroen Van Grondelle (1999) + https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582 + """ + # Algorithm 2.4, p 17 of reference + + # get the indices of the elements that are non-zero on or below diag + R = [[] for r in range(M.rows)] + + for r, c, _ in M.row_list(): + if c <= r: + R[r].append(c) + + inf = len(R) # nothing will be this large + parent = [inf]*M.rows + virtual = [inf]*M.rows + + for r in range(M.rows): + for c in R[r][:-1]: + while virtual[c] < r: + t = virtual[c] + virtual[c] = r + c = t + + if virtual[c] == inf: + parent[c] = virtual[c] = r + + return R, parent + +def _row_structure_symbolic_cholesky(M): + """Symbolic cholesky factorization, for pre-determination of the + non-zero structure of the Cholesky factororization. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> S = SparseMatrix([ + ... [1, 0, 3, 2], + ... [0, 0, 1, 0], + ... [4, 0, 0, 5], + ... [0, 6, 7, 0]]) + >>> S.row_structure_symbolic_cholesky() + [[0], [], [0], [1, 2]] + + References + ========== + + .. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees, + Jeroen Van Grondelle (1999) + https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582 + """ + + R, parent = M.liupc() + inf = len(R) # this acts as infinity + Lrow = copy.deepcopy(R) + + for k in range(M.rows): + for j in R[k]: + while j != inf and j != k: + Lrow[k].append(j) + j = parent[j] + + Lrow[k] = sorted(set(Lrow[k])) + + return Lrow + + +def _cholesky(M, hermitian=True): + """Returns the Cholesky-type decomposition L of a matrix A + such that L * L.H == A if hermitian flag is True, + or L * L.T == A if hermitian is False. + + A must be a Hermitian positive-definite matrix if hermitian is True, + or a symmetric matrix if it is False. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) + >>> A.cholesky() + Matrix([ + [ 5, 0, 0], + [ 3, 3, 0], + [-1, 1, 3]]) + >>> A.cholesky() * A.cholesky().T + Matrix([ + [25, 15, -5], + [15, 18, 0], + [-5, 0, 11]]) + + The matrix can have complex entries: + + >>> from sympy import I + >>> A = Matrix(((9, 3*I), (-3*I, 5))) + >>> A.cholesky() + Matrix([ + [ 3, 0], + [-I, 2]]) + >>> A.cholesky() * A.cholesky().H + Matrix([ + [ 9, 3*I], + [-3*I, 5]]) + + Non-hermitian Cholesky-type decomposition may be useful when the + matrix is not positive-definite. + + >>> A = Matrix([[1, 2], [2, 1]]) + >>> L = A.cholesky(hermitian=False) + >>> L + Matrix([ + [1, 0], + [2, sqrt(3)*I]]) + >>> L*L.T == A + True + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.LDLdecomposition + sympy.matrices.matrixbase.MatrixBase.LUdecomposition + QRdecomposition + """ + + from .dense import MutableDenseMatrix + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if hermitian and not M.is_hermitian: + raise ValueError("Matrix must be Hermitian.") + if not hermitian and not M.is_symmetric(): + raise ValueError("Matrix must be symmetric.") + + L = MutableDenseMatrix.zeros(M.rows, M.rows) + + if hermitian: + for i in range(M.rows): + for j in range(i): + L[i, j] = ((1 / L[j, j])*(M[i, j] - + sum(L[i, k]*L[j, k].conjugate() for k in range(j)))) + + Lii2 = (M[i, i] - + sum(L[i, k]*L[i, k].conjugate() for k in range(i))) + + if Lii2.is_positive is False: + raise NonPositiveDefiniteMatrixError( + "Matrix must be positive-definite") + + L[i, i] = sqrt(Lii2) + + else: + for i in range(M.rows): + for j in range(i): + L[i, j] = ((1 / L[j, j])*(M[i, j] - + sum(L[i, k]*L[j, k] for k in range(j)))) + + L[i, i] = sqrt(M[i, i] - + sum(L[i, k]**2 for k in range(i))) + + return M._new(L) + +def _cholesky_sparse(M, hermitian=True): + """ + Returns the Cholesky decomposition L of a matrix A + such that L * L.T = A + + A must be a square, symmetric, positive-definite + and non-singular matrix + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> A = SparseMatrix(((25,15,-5),(15,18,0),(-5,0,11))) + >>> A.cholesky() + Matrix([ + [ 5, 0, 0], + [ 3, 3, 0], + [-1, 1, 3]]) + >>> A.cholesky() * A.cholesky().T == A + True + + The matrix can have complex entries: + + >>> from sympy import I + >>> A = SparseMatrix(((9, 3*I), (-3*I, 5))) + >>> A.cholesky() + Matrix([ + [ 3, 0], + [-I, 2]]) + >>> A.cholesky() * A.cholesky().H + Matrix([ + [ 9, 3*I], + [-3*I, 5]]) + + Non-hermitian Cholesky-type decomposition may be useful when the + matrix is not positive-definite. + + >>> A = SparseMatrix([[1, 2], [2, 1]]) + >>> L = A.cholesky(hermitian=False) + >>> L + Matrix([ + [1, 0], + [2, sqrt(3)*I]]) + >>> L*L.T == A + True + + See Also + ======== + + sympy.matrices.sparse.SparseMatrix.LDLdecomposition + sympy.matrices.matrixbase.MatrixBase.LUdecomposition + QRdecomposition + """ + + from .dense import MutableDenseMatrix + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if hermitian and not M.is_hermitian: + raise ValueError("Matrix must be Hermitian.") + if not hermitian and not M.is_symmetric(): + raise ValueError("Matrix must be symmetric.") + + dps = _get_intermediate_simp(expand_mul, expand_mul) + Crowstruc = M.row_structure_symbolic_cholesky() + C = MutableDenseMatrix.zeros(M.rows) + + for i in range(len(Crowstruc)): + for j in Crowstruc[i]: + if i != j: + C[i, j] = M[i, j] + summ = 0 + + for p1 in Crowstruc[i]: + if p1 < j: + for p2 in Crowstruc[j]: + if p2 < j: + if p1 == p2: + if hermitian: + summ += C[i, p1]*C[j, p1].conjugate() + else: + summ += C[i, p1]*C[j, p1] + else: + break + else: + break + + C[i, j] = dps((C[i, j] - summ) / C[j, j]) + + else: # i == j + C[j, j] = M[j, j] + summ = 0 + + for k in Crowstruc[j]: + if k < j: + if hermitian: + summ += C[j, k]*C[j, k].conjugate() + else: + summ += C[j, k]**2 + else: + break + + Cjj2 = dps(C[j, j] - summ) + + if hermitian and Cjj2.is_positive is False: + raise NonPositiveDefiniteMatrixError( + "Matrix must be positive-definite") + + C[j, j] = sqrt(Cjj2) + + return M._new(C) + + +def _LDLdecomposition(M, hermitian=True): + """Returns the LDL Decomposition (L, D) of matrix A, + such that L * D * L.H == A if hermitian flag is True, or + L * D * L.T == A if hermitian is False. + This method eliminates the use of square root. + Further this ensures that all the diagonal entries of L are 1. + A must be a Hermitian positive-definite matrix if hermitian is True, + or a symmetric matrix otherwise. + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) + >>> L, D = A.LDLdecomposition() + >>> L + Matrix([ + [ 1, 0, 0], + [ 3/5, 1, 0], + [-1/5, 1/3, 1]]) + >>> D + Matrix([ + [25, 0, 0], + [ 0, 9, 0], + [ 0, 0, 9]]) + >>> L * D * L.T * A.inv() == eye(A.rows) + True + + The matrix can have complex entries: + + >>> from sympy import I + >>> A = Matrix(((9, 3*I), (-3*I, 5))) + >>> L, D = A.LDLdecomposition() + >>> L + Matrix([ + [ 1, 0], + [-I/3, 1]]) + >>> D + Matrix([ + [9, 0], + [0, 4]]) + >>> L*D*L.H == A + True + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.cholesky + sympy.matrices.matrixbase.MatrixBase.LUdecomposition + QRdecomposition + """ + + from .dense import MutableDenseMatrix + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if hermitian and not M.is_hermitian: + raise ValueError("Matrix must be Hermitian.") + if not hermitian and not M.is_symmetric(): + raise ValueError("Matrix must be symmetric.") + + D = MutableDenseMatrix.zeros(M.rows, M.rows) + L = MutableDenseMatrix.eye(M.rows) + + if hermitian: + for i in range(M.rows): + for j in range(i): + L[i, j] = (1 / D[j, j])*(M[i, j] - sum( + L[i, k]*L[j, k].conjugate()*D[k, k] for k in range(j))) + + D[i, i] = (M[i, i] - + sum(L[i, k]*L[i, k].conjugate()*D[k, k] for k in range(i))) + + if D[i, i].is_positive is False: + raise NonPositiveDefiniteMatrixError( + "Matrix must be positive-definite") + + else: + for i in range(M.rows): + for j in range(i): + L[i, j] = (1 / D[j, j])*(M[i, j] - sum( + L[i, k]*L[j, k]*D[k, k] for k in range(j))) + + D[i, i] = M[i, i] - sum(L[i, k]**2*D[k, k] for k in range(i)) + + return M._new(L), M._new(D) + +def _LDLdecomposition_sparse(M, hermitian=True): + """ + Returns the LDL Decomposition (matrices ``L`` and ``D``) of matrix + ``A``, such that ``L * D * L.T == A``. ``A`` must be a square, + symmetric, positive-definite and non-singular. + + This method eliminates the use of square root and ensures that all + the diagonal entries of L are 1. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) + >>> L, D = A.LDLdecomposition() + >>> L + Matrix([ + [ 1, 0, 0], + [ 3/5, 1, 0], + [-1/5, 1/3, 1]]) + >>> D + Matrix([ + [25, 0, 0], + [ 0, 9, 0], + [ 0, 0, 9]]) + >>> L * D * L.T == A + True + + """ + + from .dense import MutableDenseMatrix + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if hermitian and not M.is_hermitian: + raise ValueError("Matrix must be Hermitian.") + if not hermitian and not M.is_symmetric(): + raise ValueError("Matrix must be symmetric.") + + dps = _get_intermediate_simp(expand_mul, expand_mul) + Lrowstruc = M.row_structure_symbolic_cholesky() + L = MutableDenseMatrix.eye(M.rows) + D = MutableDenseMatrix.zeros(M.rows, M.cols) + + for i in range(len(Lrowstruc)): + for j in Lrowstruc[i]: + if i != j: + L[i, j] = M[i, j] + summ = 0 + + for p1 in Lrowstruc[i]: + if p1 < j: + for p2 in Lrowstruc[j]: + if p2 < j: + if p1 == p2: + if hermitian: + summ += L[i, p1]*L[j, p1].conjugate()*D[p1, p1] + else: + summ += L[i, p1]*L[j, p1]*D[p1, p1] + else: + break + else: + break + + L[i, j] = dps((L[i, j] - summ) / D[j, j]) + + else: # i == j + D[i, i] = M[i, i] + summ = 0 + + for k in Lrowstruc[i]: + if k < i: + if hermitian: + summ += L[i, k]*L[i, k].conjugate()*D[k, k] + else: + summ += L[i, k]**2*D[k, k] + else: + break + + D[i, i] = dps(D[i, i] - summ) + + if hermitian and D[i, i].is_positive is False: + raise NonPositiveDefiniteMatrixError( + "Matrix must be positive-definite") + + return M._new(L), M._new(D) + + +def _LUdecomposition(M, iszerofunc=_iszero, simpfunc=None, rankcheck=False): + """Returns (L, U, perm) where L is a lower triangular matrix with unit + diagonal, U is an upper triangular matrix, and perm is a list of row + swap index pairs. If A is the original matrix, then + ``A = (L*U).permuteBkwd(perm)``, and the row permutation matrix P such + that $P A = L U$ can be computed by ``P = eye(A.rows).permuteFwd(perm)``. + + See documentation for LUCombined for details about the keyword argument + rankcheck, iszerofunc, and simpfunc. + + Parameters + ========== + + rankcheck : bool, optional + Determines if this function should detect the rank + deficiency of the matrixis and should raise a + ``ValueError``. + + iszerofunc : function, optional + A function which determines if a given expression is zero. + + The function should be a callable that takes a single + SymPy expression and returns a 3-valued boolean value + ``True``, ``False``, or ``None``. + + It is internally used by the pivot searching algorithm. + See the notes section for a more information about the + pivot searching algorithm. + + simpfunc : function or None, optional + A function that simplifies the input. + + If this is specified as a function, this function should be + a callable that takes a single SymPy expression and returns + an another SymPy expression that is algebraically + equivalent. + + If ``None``, it indicates that the pivot search algorithm + should not attempt to simplify any candidate pivots. + + It is internally used by the pivot searching algorithm. + See the notes section for a more information about the + pivot searching algorithm. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[4, 3], [6, 3]]) + >>> L, U, _ = a.LUdecomposition() + >>> L + Matrix([ + [ 1, 0], + [3/2, 1]]) + >>> U + Matrix([ + [4, 3], + [0, -3/2]]) + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.cholesky + sympy.matrices.dense.DenseMatrix.LDLdecomposition + QRdecomposition + LUdecomposition_Simple + LUdecompositionFF + LUsolve + """ + + combined, p = M.LUdecomposition_Simple(iszerofunc=iszerofunc, + simpfunc=simpfunc, rankcheck=rankcheck) + + # L is lower triangular ``M.rows x M.rows`` + # U is upper triangular ``M.rows x M.cols`` + # L has unit diagonal. For each column in combined, the subcolumn + # below the diagonal of combined is shared by L. + # If L has more columns than combined, then the remaining subcolumns + # below the diagonal of L are zero. + # The upper triangular portion of L and combined are equal. + def entry_L(i, j): + if i < j: + # Super diagonal entry + return M.zero + elif i == j: + return M.one + elif j < combined.cols: + return combined[i, j] + + # Subdiagonal entry of L with no corresponding + # entry in combined + return M.zero + + def entry_U(i, j): + return M.zero if i > j else combined[i, j] + + L = M._new(combined.rows, combined.rows, entry_L) + U = M._new(combined.rows, combined.cols, entry_U) + + return L, U, p + +def _LUdecomposition_Simple(M, iszerofunc=_iszero, simpfunc=None, + rankcheck=False): + r"""Compute the PLU decomposition of the matrix. + + Parameters + ========== + + rankcheck : bool, optional + Determines if this function should detect the rank + deficiency of the matrixis and should raise a + ``ValueError``. + + iszerofunc : function, optional + A function which determines if a given expression is zero. + + The function should be a callable that takes a single + SymPy expression and returns a 3-valued boolean value + ``True``, ``False``, or ``None``. + + It is internally used by the pivot searching algorithm. + See the notes section for a more information about the + pivot searching algorithm. + + simpfunc : function or None, optional + A function that simplifies the input. + + If this is specified as a function, this function should be + a callable that takes a single SymPy expression and returns + an another SymPy expression that is algebraically + equivalent. + + If ``None``, it indicates that the pivot search algorithm + should not attempt to simplify any candidate pivots. + + It is internally used by the pivot searching algorithm. + See the notes section for a more information about the + pivot searching algorithm. + + Returns + ======= + + (lu, row_swaps) : (Matrix, list) + If the original matrix is a $m, n$ matrix: + + *lu* is a $m, n$ matrix, which contains result of the + decomposition in a compressed form. See the notes section + to see how the matrix is compressed. + + *row_swaps* is a $m$-element list where each element is a + pair of row exchange indices. + + ``A = (L*U).permute_backward(perm)``, and the row + permutation matrix $P$ from the formula $P A = L U$ can be + computed by ``P=eye(A.row).permute_forward(perm)``. + + Raises + ====== + + ValueError + Raised if ``rankcheck=True`` and the matrix is found to + be rank deficient during the computation. + + Notes + ===== + + About the PLU decomposition: + + PLU decomposition is a generalization of a LU decomposition + which can be extended for rank-deficient matrices. + + It can further be generalized for non-square matrices, and this + is the notation that SymPy is using. + + PLU decomposition is a decomposition of a $m, n$ matrix $A$ in + the form of $P A = L U$ where + + * $L$ is a $m, m$ lower triangular matrix with unit diagonal + entries. + * $U$ is a $m, n$ upper triangular matrix. + * $P$ is a $m, m$ permutation matrix. + + So, for a square matrix, the decomposition would look like: + + .. math:: + L = \begin{bmatrix} + 1 & 0 & 0 & \cdots & 0 \\ + L_{1, 0} & 1 & 0 & \cdots & 0 \\ + L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 + \end{bmatrix} + + .. math:: + U = \begin{bmatrix} + U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ + 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ + 0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + 0 & 0 & 0 & \cdots & U_{n-1, n-1} + \end{bmatrix} + + And for a matrix with more rows than the columns, + the decomposition would look like: + + .. math:: + L = \begin{bmatrix} + 1 & 0 & 0 & \cdots & 0 & 0 & \cdots & 0 \\ + L_{1, 0} & 1 & 0 & \cdots & 0 & 0 & \cdots & 0 \\ + L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 & 0 & \cdots & 0 \\ + \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \ddots + & \vdots \\ + L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 & 0 + & \cdots & 0 \\ + L_{n, 0} & L_{n, 1} & L_{n, 2} & \cdots & L_{n, n-1} & 1 + & \cdots & 0 \\ + \vdots & \vdots & \vdots & \ddots & \vdots & \vdots + & \ddots & \vdots \\ + L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & L_{m-1, n-1} + & 0 & \cdots & 1 \\ + \end{bmatrix} + + .. math:: + U = \begin{bmatrix} + U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ + 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ + 0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + 0 & 0 & 0 & \cdots & U_{n-1, n-1} \\ + 0 & 0 & 0 & \cdots & 0 \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + 0 & 0 & 0 & \cdots & 0 + \end{bmatrix} + + Finally, for a matrix with more columns than the rows, the + decomposition would look like: + + .. math:: + L = \begin{bmatrix} + 1 & 0 & 0 & \cdots & 0 \\ + L_{1, 0} & 1 & 0 & \cdots & 0 \\ + L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & 1 + \end{bmatrix} + + .. math:: + U = \begin{bmatrix} + U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1} + & \cdots & U_{0, n-1} \\ + 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1} + & \cdots & U_{1, n-1} \\ + 0 & 0 & U_{2, 2} & \cdots & U_{2, m-1} + & \cdots & U_{2, n-1} \\ + \vdots & \vdots & \vdots & \ddots & \vdots + & \cdots & \vdots \\ + 0 & 0 & 0 & \cdots & U_{m-1, m-1} + & \cdots & U_{m-1, n-1} \\ + \end{bmatrix} + + About the compressed LU storage: + + The results of the decomposition are often stored in compressed + forms rather than returning $L$ and $U$ matrices individually. + + It may be less intiuitive, but it is commonly used for a lot of + numeric libraries because of the efficiency. + + The storage matrix is defined as following for this specific + method: + + * The subdiagonal elements of $L$ are stored in the subdiagonal + portion of $LU$, that is $LU_{i, j} = L_{i, j}$ whenever + $i > j$. + * The elements on the diagonal of $L$ are all 1, and are not + explicitly stored. + * $U$ is stored in the upper triangular portion of $LU$, that is + $LU_{i, j} = U_{i, j}$ whenever $i <= j$. + * For a case of $m > n$, the right side of the $L$ matrix is + trivial to store. + * For a case of $m < n$, the below side of the $U$ matrix is + trivial to store. + + So, for a square matrix, the compressed output matrix would be: + + .. math:: + LU = \begin{bmatrix} + U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ + L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ + L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & U_{n-1, n-1} + \end{bmatrix} + + For a matrix with more rows than the columns, the compressed + output matrix would be: + + .. math:: + LU = \begin{bmatrix} + U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ + L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ + L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots + & U_{n-1, n-1} \\ + \vdots & \vdots & \vdots & \ddots & \vdots \\ + L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots + & L_{m-1, n-1} \\ + \end{bmatrix} + + For a matrix with more columns than the rows, the compressed + output matrix would be: + + .. math:: + LU = \begin{bmatrix} + U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1} + & \cdots & U_{0, n-1} \\ + L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1} + & \cdots & U_{1, n-1} \\ + L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, m-1} + & \cdots & U_{2, n-1} \\ + \vdots & \vdots & \vdots & \ddots & \vdots + & \cdots & \vdots \\ + L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & U_{m-1, m-1} + & \cdots & U_{m-1, n-1} \\ + \end{bmatrix} + + About the pivot searching algorithm: + + When a matrix contains symbolic entries, the pivot search algorithm + differs from the case where every entry can be categorized as zero or + nonzero. + The algorithm searches column by column through the submatrix whose + top left entry coincides with the pivot position. + If it exists, the pivot is the first entry in the current search + column that iszerofunc guarantees is nonzero. + If no such candidate exists, then each candidate pivot is simplified + if simpfunc is not None. + The search is repeated, with the difference that a candidate may be + the pivot if ``iszerofunc()`` cannot guarantee that it is nonzero. + In the second search the pivot is the first candidate that + iszerofunc can guarantee is nonzero. + If no such candidate exists, then the pivot is the first candidate + for which iszerofunc returns None. + If no such candidate exists, then the search is repeated in the next + column to the right. + The pivot search algorithm differs from the one in ``rref()``, which + relies on ``_find_reasonable_pivot()``. + Future versions of ``LUdecomposition_simple()`` may use + ``_find_reasonable_pivot()``. + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.LUdecomposition + LUdecompositionFF + LUsolve + """ + + if rankcheck: + # https://github.com/sympy/sympy/issues/9796 + pass + + if S.Zero in M.shape: + # Define LU decomposition of a matrix with no entries as a matrix + # of the same dimensions with all zero entries. + return M.zeros(M.rows, M.cols), [] + + dps = _get_intermediate_simp() + lu = M.as_mutable() + row_swaps = [] + + pivot_col = 0 + + for pivot_row in range(0, lu.rows - 1): + # Search for pivot. Prefer entry that iszeropivot determines + # is nonzero, over entry that iszeropivot cannot guarantee + # is zero. + # XXX ``_find_reasonable_pivot`` uses slow zero testing. Blocked by bug #10279 + # Future versions of LUdecomposition_simple can pass iszerofunc and simpfunc + # to _find_reasonable_pivot(). + # In pass 3 of _find_reasonable_pivot(), the predicate in ``if x.equals(S.Zero):`` + # calls sympy.simplify(), and not the simplification function passed in via + # the keyword argument simpfunc. + iszeropivot = True + + while pivot_col != M.cols and iszeropivot: + sub_col = (lu[r, pivot_col] for r in range(pivot_row, M.rows)) + + pivot_row_offset, pivot_value, is_assumed_non_zero, ind_simplified_pairs =\ + _find_reasonable_pivot_naive(sub_col, iszerofunc, simpfunc) + + iszeropivot = pivot_value is None + + if iszeropivot: + # All candidate pivots in this column are zero. + # Proceed to next column. + pivot_col += 1 + + if rankcheck and pivot_col != pivot_row: + # All entries including and below the pivot position are + # zero, which indicates that the rank of the matrix is + # strictly less than min(num rows, num cols) + # Mimic behavior of previous implementation, by throwing a + # ValueError. + raise ValueError("Rank of matrix is strictly less than" + " number of rows or columns." + " Pass keyword argument" + " rankcheck=False to compute" + " the LU decomposition of this matrix.") + + candidate_pivot_row = None if pivot_row_offset is None else pivot_row + pivot_row_offset + + if candidate_pivot_row is None and iszeropivot: + # If candidate_pivot_row is None and iszeropivot is True + # after pivot search has completed, then the submatrix + # below and to the right of (pivot_row, pivot_col) is + # all zeros, indicating that Gaussian elimination is + # complete. + return lu, row_swaps + + # Update entries simplified during pivot search. + for offset, val in ind_simplified_pairs: + lu[pivot_row + offset, pivot_col] = val + + if pivot_row != candidate_pivot_row: + # Row swap book keeping: + # Record which rows were swapped. + # Update stored portion of L factor by multiplying L on the + # left and right with the current permutation. + # Swap rows of U. + row_swaps.append([pivot_row, candidate_pivot_row]) + + # Update L. + lu[pivot_row, 0:pivot_row], lu[candidate_pivot_row, 0:pivot_row] = \ + lu[candidate_pivot_row, 0:pivot_row], lu[pivot_row, 0:pivot_row] + + # Swap pivot row of U with candidate pivot row. + lu[pivot_row, pivot_col:lu.cols], lu[candidate_pivot_row, pivot_col:lu.cols] = \ + lu[candidate_pivot_row, pivot_col:lu.cols], lu[pivot_row, pivot_col:lu.cols] + + # Introduce zeros below the pivot by adding a multiple of the + # pivot row to a row under it, and store the result in the + # row under it. + # Only entries in the target row whose index is greater than + # start_col may be nonzero. + start_col = pivot_col + 1 + + for row in range(pivot_row + 1, lu.rows): + # Store factors of L in the subcolumn below + # (pivot_row, pivot_row). + lu[row, pivot_row] = \ + dps(lu[row, pivot_col]/lu[pivot_row, pivot_col]) + + # Form the linear combination of the pivot row and the current + # row below the pivot row that zeros the entries below the pivot. + # Employing slicing instead of a loop here raises + # NotImplementedError: Cannot add Zero to MutableSparseMatrix + # in sympy/matrices/tests/test_sparse.py. + # c = pivot_row + 1 if pivot_row == pivot_col else pivot_col + for c in range(start_col, lu.cols): + lu[row, c] = dps(lu[row, c] - lu[row, pivot_row]*lu[pivot_row, c]) + + if pivot_row != pivot_col: + # matrix rank < min(num rows, num cols), + # so factors of L are not stored directly below the pivot. + # These entries are zero by construction, so don't bother + # computing them. + for row in range(pivot_row + 1, lu.rows): + lu[row, pivot_col] = M.zero + + pivot_col += 1 + + if pivot_col == lu.cols: + # All candidate pivots are zero implies that Gaussian + # elimination is complete. + return lu, row_swaps + + if rankcheck: + if iszerofunc( + lu[Min(lu.rows, lu.cols) - 1, Min(lu.rows, lu.cols) - 1]): + raise ValueError("Rank of matrix is strictly less than" + " number of rows or columns." + " Pass keyword argument" + " rankcheck=False to compute" + " the LU decomposition of this matrix.") + + return lu, row_swaps + +def _LUdecompositionFF(M): + """Compute a fraction-free LU decomposition. + + Returns 4 matrices P, L, D, U such that PA = L D**-1 U. + If the elements of the matrix belong to some integral domain I, then all + elements of L, D and U are guaranteed to belong to I. + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.LUdecomposition + LUdecomposition_Simple + LUsolve + + References + ========== + + .. [1] W. Zhou & D.J. Jeffrey, "Fraction-free matrix factors: new forms + for LU and QR factors". Frontiers in Computer Science in China, + Vol 2, no. 1, pp. 67-80, 2008. + """ + + from sympy.matrices import SparseMatrix + + zeros = SparseMatrix.zeros + eye = SparseMatrix.eye + n, m = M.rows, M.cols + U, L, P = M.as_mutable(), eye(n), eye(n) + DD = zeros(n, n) + oldpivot = 1 + + for k in range(n - 1): + if U[k, k] == 0: + for kpivot in range(k + 1, n): + if U[kpivot, k]: + break + else: + raise ValueError("Matrix is not full rank") + + U[k, k:], U[kpivot, k:] = U[kpivot, k:], U[k, k:] + L[k, :k], L[kpivot, :k] = L[kpivot, :k], L[k, :k] + P[k, :], P[kpivot, :] = P[kpivot, :], P[k, :] + + L [k, k] = Ukk = U[k, k] + DD[k, k] = oldpivot * Ukk + + for i in range(k + 1, n): + L[i, k] = Uik = U[i, k] + + for j in range(k + 1, m): + U[i, j] = (Ukk * U[i, j] - U[k, j] * Uik) / oldpivot + + U[i, k] = 0 + + oldpivot = Ukk + + DD[n - 1, n - 1] = oldpivot + + return P, L, DD, U + +def _singular_value_decomposition(A): + r"""Returns a Condensed Singular Value decomposition. + + Explanation + =========== + + A Singular Value decomposition is a decomposition in the form $A = U \Sigma V^H$ + where + + - $U, V$ are column orthogonal matrix. + - $\Sigma$ is a diagonal matrix, where the main diagonal contains singular + values of matrix A. + + A column orthogonal matrix satisfies + $\mathbb{I} = U^H U$ while a full orthogonal matrix satisfies + relation $\mathbb{I} = U U^H = U^H U$ where $\mathbb{I}$ is an identity + matrix with matching dimensions. + + For matrices which are not square or are rank-deficient, it is + sufficient to return a column orthogonal matrix because augmenting + them may introduce redundant computations. + In condensed Singular Value Decomposition we only return column orthogonal + matrices because of this reason + + If you want to augment the results to return a full orthogonal + decomposition, you should use the following procedures. + + - Augment the $U, V$ matrices with columns that are orthogonal to every + other columns and make it square. + - Augment the $\Sigma$ matrix with zero rows to make it have the same + shape as the original matrix. + + The procedure will be illustrated in the examples section. + + Examples + ======== + + we take a full rank matrix first: + + >>> from sympy import Matrix + >>> A = Matrix([[1, 2],[2,1]]) + >>> U, S, V = A.singular_value_decomposition() + >>> U + Matrix([ + [ sqrt(2)/2, sqrt(2)/2], + [-sqrt(2)/2, sqrt(2)/2]]) + >>> S + Matrix([ + [1, 0], + [0, 3]]) + >>> V + Matrix([ + [-sqrt(2)/2, sqrt(2)/2], + [ sqrt(2)/2, sqrt(2)/2]]) + + If a matrix if square and full rank both U, V + are orthogonal in both directions + + >>> U * U.H + Matrix([ + [1, 0], + [0, 1]]) + >>> U.H * U + Matrix([ + [1, 0], + [0, 1]]) + + >>> V * V.H + Matrix([ + [1, 0], + [0, 1]]) + >>> V.H * V + Matrix([ + [1, 0], + [0, 1]]) + >>> A == U * S * V.H + True + + >>> C = Matrix([ + ... [1, 0, 0, 0, 2], + ... [0, 0, 3, 0, 0], + ... [0, 0, 0, 0, 0], + ... [0, 2, 0, 0, 0], + ... ]) + >>> U, S, V = C.singular_value_decomposition() + + >>> V.H * V + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> V * V.H + Matrix([ + [1/5, 0, 0, 0, 2/5], + [ 0, 1, 0, 0, 0], + [ 0, 0, 1, 0, 0], + [ 0, 0, 0, 0, 0], + [2/5, 0, 0, 0, 4/5]]) + + If you want to augment the results to be a full orthogonal + decomposition, you should augment $V$ with an another orthogonal + column. + + You are able to append an arbitrary standard basis that are linearly + independent to every other columns and you can run the Gram-Schmidt + process to make them augmented as orthogonal basis. + + >>> V_aug = V.row_join(Matrix([[0,0,0,0,1], + ... [0,0,0,1,0]]).H) + >>> V_aug = V_aug.QRdecomposition()[0] + >>> V_aug + Matrix([ + [0, sqrt(5)/5, 0, -2*sqrt(5)/5, 0], + [1, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 1], + [0, 2*sqrt(5)/5, 0, sqrt(5)/5, 0]]) + >>> V_aug.H * V_aug + Matrix([ + [1, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 1]]) + >>> V_aug * V_aug.H + Matrix([ + [1, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 1]]) + + Similarly we augment U + + >>> U_aug = U.row_join(Matrix([0,0,1,0])) + >>> U_aug = U_aug.QRdecomposition()[0] + >>> U_aug + Matrix([ + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + [1, 0, 0, 0]]) + + >>> U_aug.H * U_aug + Matrix([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1]]) + >>> U_aug * U_aug.H + Matrix([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1]]) + + We add 2 zero columns and one row to S + + >>> S_aug = S.col_join(Matrix([[0,0,0]])) + >>> S_aug = S_aug.row_join(Matrix([[0,0,0,0], + ... [0,0,0,0]]).H) + >>> S_aug + Matrix([ + [2, 0, 0, 0, 0], + [0, sqrt(5), 0, 0, 0], + [0, 0, 3, 0, 0], + [0, 0, 0, 0, 0]]) + + + + >>> U_aug * S_aug * V_aug.H == C + True + + """ + + AH = A.H + m, n = A.shape + if m >= n: + V, S = (AH * A).diagonalize() + + ranked = [] + for i, x in enumerate(S.diagonal()): + if not x.is_zero: + ranked.append(i) + + V = V[:, ranked] + + Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked] + + S = S.diag(*Singular_vals) + V, _ = V.QRdecomposition() + U = A * V * S.inv() + else: + U, S = (A * AH).diagonalize() + + ranked = [] + for i, x in enumerate(S.diagonal()): + if not x.is_zero: + ranked.append(i) + + U = U[:, ranked] + Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked] + + S = S.diag(*Singular_vals) + U, _ = U.QRdecomposition() + V = AH * U * S.inv() + + return U, S, V + +def _QRdecomposition_optional(M, normalize=True): + def dot(u, v): + return u.dot(v, hermitian=True) + + dps = _get_intermediate_simp(expand_mul, expand_mul) + + A = M.as_mutable() + ranked = [] + + Q = A + R = A.zeros(A.cols) + + for j in range(A.cols): + for i in range(j): + if Q[:, i].is_zero_matrix: + continue + + R[i, j] = dot(Q[:, i], Q[:, j]) / dot(Q[:, i], Q[:, i]) + R[i, j] = dps(R[i, j]) + Q[:, j] -= Q[:, i] * R[i, j] + + Q[:, j] = dps(Q[:, j]) + if Q[:, j].is_zero_matrix is not True: + ranked.append(j) + R[j, j] = M.one + + Q = Q.extract(range(Q.rows), ranked) + R = R.extract(ranked, range(R.cols)) + + if normalize: + # Normalization + for i in range(Q.cols): + norm = Q[:, i].norm() + Q[:, i] /= norm + R[i, :] *= norm + + return M.__class__(Q), M.__class__(R) + + +def _QRdecomposition(M): + r"""Returns a QR decomposition. + + Explanation + =========== + + A QR decomposition is a decomposition in the form $A = Q R$ + where + + - $Q$ is a column orthogonal matrix. + - $R$ is a upper triangular (trapezoidal) matrix. + + A column orthogonal matrix satisfies + $\mathbb{I} = Q^H Q$ while a full orthogonal matrix satisfies + relation $\mathbb{I} = Q Q^H = Q^H Q$ where $I$ is an identity + matrix with matching dimensions. + + For matrices which are not square or are rank-deficient, it is + sufficient to return a column orthogonal matrix because augmenting + them may introduce redundant computations. + And an another advantage of this is that you can easily inspect the + matrix rank by counting the number of columns of $Q$. + + If you want to augment the results to return a full orthogonal + decomposition, you should use the following procedures. + + - Augment the $Q$ matrix with columns that are orthogonal to every + other columns and make it square. + - Augment the $R$ matrix with zero rows to make it have the same + shape as the original matrix. + + The procedure will be illustrated in the examples section. + + Examples + ======== + + A full rank matrix example: + + >>> from sympy import Matrix + >>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]]) + >>> Q, R = A.QRdecomposition() + >>> Q + Matrix([ + [ 6/7, -69/175, -58/175], + [ 3/7, 158/175, 6/175], + [-2/7, 6/35, -33/35]]) + >>> R + Matrix([ + [14, 21, -14], + [ 0, 175, -70], + [ 0, 0, 35]]) + + If the matrix is square and full rank, the $Q$ matrix becomes + orthogonal in both directions, and needs no augmentation. + + >>> Q * Q.H + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> Q.H * Q + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + >>> A == Q*R + True + + A rank deficient matrix example: + + >>> A = Matrix([[12, -51, 0], [6, 167, 0], [-4, 24, 0]]) + >>> Q, R = A.QRdecomposition() + >>> Q + Matrix([ + [ 6/7, -69/175], + [ 3/7, 158/175], + [-2/7, 6/35]]) + >>> R + Matrix([ + [14, 21, 0], + [ 0, 175, 0]]) + + QRdecomposition might return a matrix Q that is rectangular. + In this case the orthogonality condition might be satisfied as + $\mathbb{I} = Q.H*Q$ but not in the reversed product + $\mathbb{I} = Q * Q.H$. + + >>> Q.H * Q + Matrix([ + [1, 0], + [0, 1]]) + >>> Q * Q.H + Matrix([ + [27261/30625, 348/30625, -1914/6125], + [ 348/30625, 30589/30625, 198/6125], + [ -1914/6125, 198/6125, 136/1225]]) + + If you want to augment the results to be a full orthogonal + decomposition, you should augment $Q$ with an another orthogonal + column. + + You are able to append an identity matrix, + and you can run the Gram-Schmidt + process to make them augmented as orthogonal basis. + + >>> Q_aug = Q.row_join(Matrix.eye(3)) + >>> Q_aug = Q_aug.QRdecomposition()[0] + >>> Q_aug + Matrix([ + [ 6/7, -69/175, 58/175], + [ 3/7, 158/175, -6/175], + [-2/7, 6/35, 33/35]]) + >>> Q_aug.H * Q_aug + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> Q_aug * Q_aug.H + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + Augmenting the $R$ matrix with zero row is straightforward. + + >>> R_aug = R.col_join(Matrix([[0, 0, 0]])) + >>> R_aug + Matrix([ + [14, 21, 0], + [ 0, 175, 0], + [ 0, 0, 0]]) + >>> Q_aug * R_aug == A + True + + A zero matrix example: + + >>> from sympy import Matrix + >>> A = Matrix.zeros(3, 4) + >>> Q, R = A.QRdecomposition() + + They may return matrices with zero rows and columns. + + >>> Q + Matrix(3, 0, []) + >>> R + Matrix(0, 4, []) + >>> Q*R + Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]]) + + As the same augmentation rule described above, $Q$ can be augmented + with columns of an identity matrix and $R$ can be augmented with + rows of a zero matrix. + + >>> Q_aug = Q.row_join(Matrix.eye(3)) + >>> R_aug = R.col_join(Matrix.zeros(3, 4)) + >>> Q_aug * Q_aug.T + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> R_aug + Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]]) + >>> Q_aug * R_aug == A + True + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.cholesky + sympy.matrices.dense.DenseMatrix.LDLdecomposition + sympy.matrices.matrixbase.MatrixBase.LUdecomposition + QRsolve + """ + return _QRdecomposition_optional(M, normalize=True) + +def _upper_hessenberg_decomposition(A): + """Converts a matrix into Hessenberg matrix H. + + Returns 2 matrices H, P s.t. + $P H P^{T} = A$, where H is an upper hessenberg matrix + and P is an orthogonal matrix + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([ + ... [1,2,3], + ... [-3,5,6], + ... [4,-8,9], + ... ]) + >>> H, P = A.upper_hessenberg_decomposition() + >>> H + Matrix([ + [1, 6/5, 17/5], + [5, 213/25, -134/25], + [0, 216/25, 137/25]]) + >>> P + Matrix([ + [1, 0, 0], + [0, -3/5, 4/5], + [0, 4/5, 3/5]]) + >>> P * H * P.H == A + True + + + References + ========== + + .. [#] https://mathworld.wolfram.com/HessenbergDecomposition.html + """ + + M = A.as_mutable() + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + + n = M.cols + P = M.eye(n) + H = M + + for j in range(n - 2): + + u = H[j + 1:, j] + + if u[1:, :].is_zero_matrix: + continue + + if sign(u[0]) != 0: + u[0] = u[0] + sign(u[0]) * u.norm() + else: + u[0] = u[0] + u.norm() + + v = u / u.norm() + + H[j + 1:, :] = H[j + 1:, :] - 2 * v * (v.H * H[j + 1:, :]) + H[:, j + 1:] = H[:, j + 1:] - (H[:, j + 1:] * (2 * v)) * v.H + P[:, j + 1:] = P[:, j + 1:] - (P[:, j + 1:] * (2 * v)) * v.H + + return H, P diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/dense.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/dense.py new file mode 100644 index 0000000000000000000000000000000000000000..98bf9931df54f67abfd9c4dc810b46fdcf70288f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/dense.py @@ -0,0 +1,1094 @@ +from __future__ import annotations +import random + +from sympy.core.basic import Basic +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.utilities.decorator import doctest_depends_on +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import is_sequence + +from .exceptions import ShapeError +from .decompositions import _cholesky, _LDLdecomposition +from .matrixbase import MatrixBase +from .repmatrix import MutableRepMatrix, RepMatrix +from .solvers import _lower_triangular_solve, _upper_triangular_solve + + +__doctest_requires__ = {('symarray',): ['numpy']} + + +def _iszero(x): + """Returns True if x is zero.""" + return x.is_zero + + +class DenseMatrix(RepMatrix): + """Matrix implementation based on DomainMatrix as the internal representation""" + + # + # DenseMatrix is a superclass for both MutableDenseMatrix and + # ImmutableDenseMatrix. Methods shared by both classes but not for the + # Sparse classes should be implemented here. + # + + is_MatrixExpr: bool = False + + _op_priority = 10.01 + _class_priority = 4 + + @property + def _mat(self): + sympy_deprecation_warning( + """ + The private _mat attribute of Matrix is deprecated. Use the + .flat() method instead. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-private-matrix-attributes" + ) + + return self.flat() + + def _eval_inverse(self, **kwargs): + return self.inv(method=kwargs.get('method', 'GE'), + iszerofunc=kwargs.get('iszerofunc', _iszero), + try_block_diag=kwargs.get('try_block_diag', False)) + + def as_immutable(self): + """Returns an Immutable version of this Matrix + """ + from .immutable import ImmutableDenseMatrix as cls + return cls._fromrep(self._rep.copy()) + + def as_mutable(self): + """Returns a mutable version of this matrix + + Examples + ======== + + >>> from sympy import ImmutableMatrix + >>> X = ImmutableMatrix([[1, 2], [3, 4]]) + >>> Y = X.as_mutable() + >>> Y[1, 1] = 5 # Can set values in Y + >>> Y + Matrix([ + [1, 2], + [3, 5]]) + """ + return Matrix(self) + + def cholesky(self, hermitian=True): + return _cholesky(self, hermitian=hermitian) + + def LDLdecomposition(self, hermitian=True): + return _LDLdecomposition(self, hermitian=hermitian) + + def lower_triangular_solve(self, rhs): + return _lower_triangular_solve(self, rhs) + + def upper_triangular_solve(self, rhs): + return _upper_triangular_solve(self, rhs) + + cholesky.__doc__ = _cholesky.__doc__ + LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ + lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ + upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ + + +def _force_mutable(x): + """Return a matrix as a Matrix, otherwise return x.""" + if getattr(x, 'is_Matrix', False): + return x.as_mutable() + elif isinstance(x, Basic): + return x + elif hasattr(x, '__array__'): + a = x.__array__() + if len(a.shape) == 0: + return sympify(a) + return Matrix(x) + return x + + +class MutableDenseMatrix(DenseMatrix, MutableRepMatrix): + + def simplify(self, **kwargs): + """Applies simplify to the elements of a matrix in place. + + This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure)) + + See Also + ======== + + sympy.simplify.simplify.simplify + """ + from sympy.simplify.simplify import simplify as _simplify + for (i, j), element in self.todok().items(): + self[i, j] = _simplify(element, **kwargs) + + +MutableMatrix = Matrix = MutableDenseMatrix + +########### +# Numpy Utility Functions: +# list2numpy, matrix2numpy, symmarray +########### + + +def list2numpy(l, dtype=object): # pragma: no cover + """Converts Python list of SymPy expressions to a NumPy array. + + See Also + ======== + + matrix2numpy + """ + from numpy import empty + a = empty(len(l), dtype) + for i, s in enumerate(l): + a[i] = s + return a + + +def matrix2numpy(m, dtype=object): # pragma: no cover + """Converts SymPy's matrix to a NumPy array. + + See Also + ======== + + list2numpy + """ + from numpy import empty + a = empty(m.shape, dtype) + for i in range(m.rows): + for j in range(m.cols): + a[i, j] = m[i, j] + return a + + +########### +# Rotation matrices: +# rot_givens, rot_axis[123], rot_ccw_axis[123] +########### + + +def rot_givens(i, j, theta, dim=3): + r"""Returns a a Givens rotation matrix, a a rotation in the + plane spanned by two coordinates axes. + + Explanation + =========== + + The Givens rotation corresponds to a generalization of rotation + matrices to any number of dimensions, given by: + + .. math:: + G(i, j, \theta) = + \begin{bmatrix} + 1 & \cdots & 0 & \cdots & 0 & \cdots & 0 \\ + \vdots & \ddots & \vdots & & \vdots & & \vdots \\ + 0 & \cdots & c & \cdots & -s & \cdots & 0 \\ + \vdots & & \vdots & \ddots & \vdots & & \vdots \\ + 0 & \cdots & s & \cdots & c & \cdots & 0 \\ + \vdots & & \vdots & & \vdots & \ddots & \vdots \\ + 0 & \cdots & 0 & \cdots & 0 & \cdots & 1 + \end{bmatrix} + + Where $c = \cos(\theta)$ and $s = \sin(\theta)$ appear at the intersections + ``i``\th and ``j``\th rows and columns. + + For fixed ``i > j``\, the non-zero elements of a Givens matrix are + given by: + + - $g_{kk} = 1$ for $k \ne i,\,j$ + - $g_{kk} = c$ for $k = i,\,j$ + - $g_{ji} = -g_{ij} = -s$ + + Parameters + ========== + + i : int between ``0`` and ``dim - 1`` + Represents first axis + j : int between ``0`` and ``dim - 1`` + Represents second axis + dim : int bigger than 1 + Number of dimensions. Defaults to 3. + + Examples + ======== + + >>> from sympy import pi, rot_givens + + A counterclockwise rotation of pi/3 (60 degrees) around + the third axis (z-axis): + + >>> rot_givens(1, 0, pi/3) + Matrix([ + [ 1/2, -sqrt(3)/2, 0], + [sqrt(3)/2, 1/2, 0], + [ 0, 0, 1]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_givens(1, 0, pi/2) + Matrix([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1]]) + + This can be generalized to any number + of dimensions: + + >>> rot_givens(1, 0, pi/2, dim=4) + Matrix([ + [0, -1, 0, 0], + [1, 0, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Givens_rotation + + See Also + ======== + + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (clockwise around the x axis) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (clockwise around the z axis) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (counterclockwise around the y axis) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + if not isinstance(dim, int) or dim < 2: + raise ValueError('dim must be an integer biggen than one, ' + 'got {}.'.format(dim)) + + if i == j: + raise ValueError('i and j must be different, ' + 'got ({}, {})'.format(i, j)) + + for ij in [i, j]: + if not isinstance(ij, int) or ij < 0 or ij > dim - 1: + raise ValueError('i and j must be integers between 0 and ' + '{}, got i={} and j={}.'.format(dim-1, i, j)) + + theta = sympify(theta) + c = cos(theta) + s = sin(theta) + M = eye(dim) + M[i, i] = c + M[j, j] = c + M[i, j] = s + M[j, i] = -s + return M + + +def rot_axis3(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + clockwise rotation around the `z`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & \sin(\theta) & 0 \\ + -\sin(\theta) & \cos(\theta) & 0 \\ + 0 & 0 & 1 + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_axis3 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_axis3(theta) + Matrix([ + [ 1/2, sqrt(3)/2, 0], + [-sqrt(3)/2, 1/2, 0], + [ 0, 0, 1]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_axis3(pi/2) + Matrix([ + [ 0, 1, 0], + [-1, 0, 0], + [ 0, 0, 1]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (clockwise around the x axis) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + """ + return rot_givens(0, 1, theta, dim=3) + + +def rot_axis2(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + clockwise rotation around the `y`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & 0 & -\sin(\theta) \\ + 0 & 1 & 0 \\ + \sin(\theta) & 0 & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_axis2 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_axis2(theta) + Matrix([ + [ 1/2, 0, -sqrt(3)/2], + [ 0, 1, 0], + [sqrt(3)/2, 0, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_axis2(pi/2) + Matrix([ + [0, 0, -1], + [0, 1, 0], + [1, 0, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + return rot_givens(2, 0, theta, dim=3) + + +def rot_axis1(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + clockwise rotation around the `x`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + 1 & 0 & 0 \\ + 0 & \cos(\theta) & \sin(\theta) \\ + 0 & -\sin(\theta) & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_axis1 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_axis1(theta) + Matrix([ + [1, 0, 0], + [0, 1/2, sqrt(3)/2], + [0, -sqrt(3)/2, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_axis1(pi/2) + Matrix([ + [1, 0, 0], + [0, 0, 1], + [0, -1, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (clockwise around the z axis) + """ + return rot_givens(1, 2, theta, dim=3) + + +def rot_ccw_axis3(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + counterclockwise rotation around the `z`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & -\sin(\theta) & 0 \\ + \sin(\theta) & \cos(\theta) & 0 \\ + 0 & 0 & 1 + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_ccw_axis3 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_ccw_axis3(theta) + Matrix([ + [ 1/2, -sqrt(3)/2, 0], + [sqrt(3)/2, 1/2, 0], + [ 0, 0, 1]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_ccw_axis3(pi/2) + Matrix([ + [0, -1, 0], + [1, 0, 0], + [0, 0, 1]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (clockwise around the z axis) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (counterclockwise around the y axis) + """ + return rot_givens(1, 0, theta, dim=3) + + +def rot_ccw_axis2(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + counterclockwise rotation around the `y`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + \cos(\theta) & 0 & \sin(\theta) \\ + 0 & 1 & 0 \\ + -\sin(\theta) & 0 & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_ccw_axis2 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_ccw_axis2(theta) + Matrix([ + [ 1/2, 0, sqrt(3)/2], + [ 0, 1, 0], + [-sqrt(3)/2, 0, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_ccw_axis2(pi/2) + Matrix([ + [ 0, 0, 1], + [ 0, 1, 0], + [-1, 0, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (clockwise around the y axis) + rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (counterclockwise around the x axis) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + return rot_givens(0, 2, theta, dim=3) + + +def rot_ccw_axis1(theta): + r"""Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis. + + Explanation + =========== + + For a right-handed coordinate system, this corresponds to a + counterclockwise rotation around the `x`-axis, given by: + + .. math:: + + R = \begin{bmatrix} + 1 & 0 & 0 \\ + 0 & \cos(\theta) & -\sin(\theta) \\ + 0 & \sin(\theta) & \cos(\theta) + \end{bmatrix} + + Examples + ======== + + >>> from sympy import pi, rot_ccw_axis1 + + A rotation of pi/3 (60 degrees): + + >>> theta = pi/3 + >>> rot_ccw_axis1(theta) + Matrix([ + [1, 0, 0], + [0, 1/2, -sqrt(3)/2], + [0, sqrt(3)/2, 1/2]]) + + If we rotate by pi/2 (90 degrees): + + >>> rot_ccw_axis1(pi/2) + Matrix([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0]]) + + See Also + ======== + + rot_givens: Returns a Givens rotation matrix (generalized rotation for + any number of dimensions) + rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) + about the 1-axis (clockwise around the x axis) + rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) + about the 2-axis (counterclockwise around the y axis) + rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) + about the 3-axis (counterclockwise around the z axis) + """ + return rot_givens(2, 1, theta, dim=3) + + +@doctest_depends_on(modules=('numpy',)) +def symarray(prefix, shape, **kwargs): # pragma: no cover + r"""Create a numpy ndarray of symbols (as an object array). + + The created symbols are named ``prefix_i1_i2_``... You should thus provide a + non-empty prefix if you want your symbols to be unique for different output + arrays, as SymPy symbols with identical names are the same object. + + Parameters + ---------- + + prefix : string + A prefix prepended to the name of every symbol. + + shape : int or tuple + Shape of the created array. If an int, the array is one-dimensional; for + more than one dimension the shape must be a tuple. + + \*\*kwargs : dict + keyword arguments passed on to Symbol + + Examples + ======== + These doctests require numpy. + + >>> from sympy import symarray + >>> symarray('', 3) + [_0 _1 _2] + + If you want multiple symarrays to contain distinct symbols, you *must* + provide unique prefixes: + + >>> a = symarray('', 3) + >>> b = symarray('', 3) + >>> a[0] == b[0] + True + >>> a = symarray('a', 3) + >>> b = symarray('b', 3) + >>> a[0] == b[0] + False + + Creating symarrays with a prefix: + + >>> symarray('a', 3) + [a_0 a_1 a_2] + + For more than one dimension, the shape must be given as a tuple: + + >>> symarray('a', (2, 3)) + [[a_0_0 a_0_1 a_0_2] + [a_1_0 a_1_1 a_1_2]] + >>> symarray('a', (2, 3, 2)) + [[[a_0_0_0 a_0_0_1] + [a_0_1_0 a_0_1_1] + [a_0_2_0 a_0_2_1]] + + [[a_1_0_0 a_1_0_1] + [a_1_1_0 a_1_1_1] + [a_1_2_0 a_1_2_1]]] + + For setting assumptions of the underlying Symbols: + + >>> [s.is_real for s in symarray('a', 2, real=True)] + [True, True] + """ + from numpy import empty, ndindex + arr = empty(shape, dtype=object) + for index in ndindex(shape): + arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))), + **kwargs) + return arr + + +############### +# Functions +############### + +def casoratian(seqs, n, zero=True): + """Given linear difference operator L of order 'k' and homogeneous + equation Ly = 0 we want to compute kernel of L, which is a set + of 'k' sequences: a(n), b(n), ... z(n). + + Solutions of L are linearly independent iff their Casoratian, + denoted as C(a, b, ..., z), do not vanish for n = 0. + + Casoratian is defined by k x k determinant:: + + + a(n) b(n) . . . z(n) + + | a(n+1) b(n+1) . . . z(n+1) | + | . . . . | + | . . . . | + | . . . . | + + a(n+k-1) b(n+k-1) . . . z(n+k-1) + + + It proves very useful in rsolve_hyper() where it is applied + to a generating set of a recurrence to factor out linearly + dependent solutions and return a basis: + + >>> from sympy import Symbol, casoratian, factorial + >>> n = Symbol('n', integer=True) + + Exponential and factorial are linearly independent: + + >>> casoratian([2**n, factorial(n)], n) != 0 + True + + """ + + seqs = list(map(sympify, seqs)) + + if not zero: + f = lambda i, j: seqs[j].subs(n, n + i) + else: + f = lambda i, j: seqs[j].subs(n, i) + + k = len(seqs) + + return Matrix(k, k, f).det() + + +def eye(*args, **kwargs): + """Create square identity matrix n x n + + See Also + ======== + + diag + zeros + ones + """ + + return Matrix.eye(*args, **kwargs) + + +def diag(*values, strict=True, unpack=False, **kwargs): + """Returns a matrix with the provided values placed on the + diagonal. If non-square matrices are included, they will + produce a block-diagonal matrix. + + Examples + ======== + + This version of diag is a thin wrapper to Matrix.diag that differs + in that it treats all lists like matrices -- even when a single list + is given. If this is not desired, either put a `*` before the list or + set `unpack=True`. + + >>> from sympy import diag + + >>> diag([1, 2, 3], unpack=True) # = diag(1,2,3) or diag(*[1,2,3]) + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + + >>> diag([1, 2, 3]) # a column vector + Matrix([ + [1], + [2], + [3]]) + + See Also + ======== + .matrixbase.MatrixBase.eye + .matrixbase.MatrixBase.diagonal + .matrixbase.MatrixBase.diag + .expressions.blockmatrix.BlockMatrix + """ + return Matrix.diag(*values, strict=strict, unpack=unpack, **kwargs) + + +def GramSchmidt(vlist, orthonormal=False): + """Apply the Gram-Schmidt process to a set of vectors. + + Parameters + ========== + + vlist : List of Matrix + Vectors to be orthogonalized for. + + orthonormal : Bool, optional + If true, return an orthonormal basis. + + Returns + ======= + + vlist : List of Matrix + Orthogonalized vectors + + Notes + ===== + + This routine is mostly duplicate from ``Matrix.orthogonalize``, + except for some difference that this always raises error when + linearly dependent vectors are found, and the keyword ``normalize`` + has been named as ``orthonormal`` in this function. + + See Also + ======== + + .matrixbase.MatrixBase.orthogonalize + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process + """ + return MutableDenseMatrix.orthogonalize( + *vlist, normalize=orthonormal, rankcheck=True + ) + + +def hessian(f, varlist, constraints=()): + """Compute Hessian matrix for a function f wrt parameters in varlist + which may be given as a sequence or a row/column vector. A list of + constraints may optionally be given. + + Examples + ======== + + >>> from sympy import Function, hessian, pprint + >>> from sympy.abc import x, y + >>> f = Function('f')(x, y) + >>> g1 = Function('g')(x, y) + >>> g2 = x**2 + 3*y + >>> pprint(hessian(f, (x, y), [g1, g2])) + [ d d ] + [ 0 0 --(g(x, y)) --(g(x, y)) ] + [ dx dy ] + [ ] + [ 0 0 2*x 3 ] + [ ] + [ 2 2 ] + [d d d ] + [--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))] + [dx 2 dy dx ] + [ dx ] + [ ] + [ 2 2 ] + [d d d ] + [--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ] + [dy dy dx 2 ] + [ dy ] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Hessian_matrix + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.jacobian + wronskian + """ + # f is the expression representing a function f, return regular matrix + if isinstance(varlist, MatrixBase): + if 1 not in varlist.shape: + raise ShapeError("`varlist` must be a column or row vector.") + if varlist.cols == 1: + varlist = varlist.T + varlist = varlist.tolist()[0] + if is_sequence(varlist): + n = len(varlist) + if not n: + raise ShapeError("`len(varlist)` must not be zero.") + else: + raise ValueError("Improper variable list in hessian function") + if not getattr(f, 'diff'): + # check differentiability + raise ValueError("Function `f` (%s) is not differentiable" % f) + m = len(constraints) + N = m + n + out = zeros(N) + for k, g in enumerate(constraints): + if not getattr(g, 'diff'): + # check differentiability + raise ValueError("Function `f` (%s) is not differentiable" % f) + for i in range(n): + out[k, i + m] = g.diff(varlist[i]) + for i in range(n): + for j in range(i, n): + out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j]) + for i in range(N): + for j in range(i + 1, N): + out[j, i] = out[i, j] + return out + + +def jordan_cell(eigenval, n): + """ + Create a Jordan block: + + Examples + ======== + + >>> from sympy import jordan_cell + >>> from sympy.abc import x + >>> jordan_cell(x, 4) + Matrix([ + [x, 1, 0, 0], + [0, x, 1, 0], + [0, 0, x, 1], + [0, 0, 0, x]]) + """ + + return Matrix.jordan_block(size=n, eigenvalue=eigenval) + + +def matrix_multiply_elementwise(A, B): + """Return the Hadamard product (elementwise product) of A and B + + >>> from sympy import Matrix, matrix_multiply_elementwise + >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) + >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) + >>> matrix_multiply_elementwise(A, B) + Matrix([ + [ 0, 10, 200], + [300, 40, 5]]) + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.__mul__ + """ + return A.multiply_elementwise(B) + + +def ones(*args, **kwargs): + """Returns a matrix of ones with ``rows`` rows and ``cols`` columns; + if ``cols`` is omitted a square matrix will be returned. + + See Also + ======== + + zeros + eye + diag + """ + + if 'c' in kwargs: + kwargs['cols'] = kwargs.pop('c') + + return Matrix.ones(*args, **kwargs) + + +def randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False, + percent=100, prng=None): + """Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted + the matrix will be square. If ``symmetric`` is True the matrix must be + square. If ``percent`` is less than 100 then only approximately the given + percentage of elements will be non-zero. + + The pseudo-random number generator used to generate matrix is chosen in the + following way. + + * If ``prng`` is supplied, it will be used as random number generator. + It should be an instance of ``random.Random``, or at least have + ``randint`` and ``shuffle`` methods with same signatures. + * if ``prng`` is not supplied but ``seed`` is supplied, then new + ``random.Random`` with given ``seed`` will be created; + * otherwise, a new ``random.Random`` with default seed will be used. + + Examples + ======== + + >>> from sympy import randMatrix + >>> randMatrix(3) # doctest:+SKIP + [25, 45, 27] + [44, 54, 9] + [23, 96, 46] + >>> randMatrix(3, 2) # doctest:+SKIP + [87, 29] + [23, 37] + [90, 26] + >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP + [0, 2, 0] + [2, 0, 1] + [0, 0, 1] + >>> randMatrix(3, symmetric=True) # doctest:+SKIP + [85, 26, 29] + [26, 71, 43] + [29, 43, 57] + >>> A = randMatrix(3, seed=1) + >>> B = randMatrix(3, seed=2) + >>> A == B + False + >>> A == randMatrix(3, seed=1) + True + >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP + [77, 70, 0], + [70, 0, 0], + [ 0, 0, 88] + """ + # Note that ``Random()`` is equivalent to ``Random(None)`` + prng = prng or random.Random(seed) + + if c is None: + c = r + + if symmetric and r != c: + raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c)) + + ij = range(r * c) + if percent != 100: + ij = prng.sample(ij, int(len(ij)*percent // 100)) + + m = zeros(r, c) + + if not symmetric: + for ijk in ij: + i, j = divmod(ijk, c) + m[i, j] = prng.randint(min, max) + else: + for ijk in ij: + i, j = divmod(ijk, c) + if i <= j: + m[i, j] = m[j, i] = prng.randint(min, max) + + return m + + +def wronskian(functions, var, method='bareiss'): + """ + Compute Wronskian for [] of functions + + :: + + | f1 f2 ... fn | + | f1' f2' ... fn' | + | . . . . | + W(f1, ..., fn) = | . . . . | + | . . . . | + | (n) (n) (n) | + | D (f1) D (f2) ... D (fn) | + + see: https://en.wikipedia.org/wiki/Wronskian + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.jacobian + hessian + """ + + functions = [sympify(f) for f in functions] + n = len(functions) + if n == 0: + return S.One + W = Matrix(n, n, lambda i, j: functions[i].diff(var, j)) + return W.det(method) + + +def zeros(*args, **kwargs): + """Returns a matrix of zeros with ``rows`` rows and ``cols`` columns; + if ``cols`` is omitted a square matrix will be returned. + + See Also + ======== + + ones + eye + diag + """ + + if 'c' in kwargs: + kwargs['cols'] = kwargs.pop('c') + + return Matrix.zeros(*args, **kwargs) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/determinant.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/determinant.py new file mode 100644 index 0000000000000000000000000000000000000000..9206c0714999ebe0cde5c4300d9b3293939177df --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/determinant.py @@ -0,0 +1,1021 @@ +from types import FunctionType + +from sympy.core.cache import cacheit +from sympy.core.numbers import Float, Integer +from sympy.core.singleton import S +from sympy.core.symbol import uniquely_named_symbol +from sympy.core.mul import Mul +from sympy.polys import PurePoly, cancel +from sympy.functions.combinatorial.numbers import nC +from sympy.polys.matrices.domainmatrix import DomainMatrix +from sympy.polys.matrices.ddm import DDM + +from .exceptions import NonSquareMatrixError +from .utilities import ( + _get_intermediate_simp, _get_intermediate_simp_bool, + _iszero, _is_zero_after_expand_mul, _dotprodsimp, _simplify) + + +def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify): + """ Find the lowest index of an item in ``col`` that is + suitable for a pivot. If ``col`` consists only of + Floats, the pivot with the largest norm is returned. + Otherwise, the first element where ``iszerofunc`` returns + False is used. If ``iszerofunc`` does not return false, + items are simplified and retested until a suitable + pivot is found. + + Returns a 4-tuple + (pivot_offset, pivot_val, assumed_nonzero, newly_determined) + where pivot_offset is the index of the pivot, pivot_val is + the (possibly simplified) value of the pivot, assumed_nonzero + is True if an assumption that the pivot was non-zero + was made without being proved, and newly_determined are + elements that were simplified during the process of pivot + finding.""" + + newly_determined = [] + col = list(col) + # a column that contains a mix of floats and integers + # but at least one float is considered a numerical + # column, and so we do partial pivoting + if all(isinstance(x, (Float, Integer)) for x in col) and any( + isinstance(x, Float) for x in col): + col_abs = [abs(x) for x in col] + max_value = max(col_abs) + if iszerofunc(max_value): + # just because iszerofunc returned True, doesn't + # mean the value is numerically zero. Make sure + # to replace all entries with numerical zeros + if max_value != 0: + newly_determined = [(i, 0) for i, x in enumerate(col) if x != 0] + return (None, None, False, newly_determined) + index = col_abs.index(max_value) + return (index, col[index], False, newly_determined) + + # PASS 1 (iszerofunc directly) + possible_zeros = [] + for i, x in enumerate(col): + is_zero = iszerofunc(x) + # is someone wrote a custom iszerofunc, it may return + # BooleanFalse or BooleanTrue instead of True or False, + # so use == for comparison instead of `is` + if is_zero == False: + # we found something that is definitely not zero + return (i, x, False, newly_determined) + possible_zeros.append(is_zero) + + # by this point, we've found no certain non-zeros + if all(possible_zeros): + # if everything is definitely zero, we have + # no pivot + return (None, None, False, newly_determined) + + # PASS 2 (iszerofunc after simplify) + # we haven't found any for-sure non-zeros, so + # go through the elements iszerofunc couldn't + # make a determination about and opportunistically + # simplify to see if we find something + for i, x in enumerate(col): + if possible_zeros[i] is not None: + continue + simped = simpfunc(x) + is_zero = iszerofunc(simped) + if is_zero in (True, False): + newly_determined.append((i, simped)) + if is_zero == False: + return (i, simped, False, newly_determined) + possible_zeros[i] = is_zero + + # after simplifying, some things that were recognized + # as zeros might be zeros + if all(possible_zeros): + # if everything is definitely zero, we have + # no pivot + return (None, None, False, newly_determined) + + # PASS 3 (.equals(0)) + # some expressions fail to simplify to zero, but + # ``.equals(0)`` evaluates to True. As a last-ditch + # attempt, apply ``.equals`` to these expressions + for i, x in enumerate(col): + if possible_zeros[i] is not None: + continue + if x.equals(S.Zero): + # ``.iszero`` may return False with + # an implicit assumption (e.g., ``x.equals(0)`` + # when ``x`` is a symbol), so only treat it + # as proved when ``.equals(0)`` returns True + possible_zeros[i] = True + newly_determined.append((i, S.Zero)) + + if all(possible_zeros): + return (None, None, False, newly_determined) + + # at this point there is nothing that could definitely + # be a pivot. To maintain compatibility with existing + # behavior, we'll assume that an illdetermined thing is + # non-zero. We should probably raise a warning in this case + i = possible_zeros.index(None) + return (i, col[i], True, newly_determined) + + +def _find_reasonable_pivot_naive(col, iszerofunc=_iszero, simpfunc=None): + """ + Helper that computes the pivot value and location from a + sequence of contiguous matrix column elements. As a side effect + of the pivot search, this function may simplify some of the elements + of the input column. A list of these simplified entries and their + indices are also returned. + This function mimics the behavior of _find_reasonable_pivot(), + but does less work trying to determine if an indeterminate candidate + pivot simplifies to zero. This more naive approach can be much faster, + with the trade-off that it may erroneously return a pivot that is zero. + + ``col`` is a sequence of contiguous column entries to be searched for + a suitable pivot. + ``iszerofunc`` is a callable that returns a Boolean that indicates + if its input is zero, or None if no such determination can be made. + ``simpfunc`` is a callable that simplifies its input. It must return + its input if it does not simplify its input. Passing in + ``simpfunc=None`` indicates that the pivot search should not attempt + to simplify any candidate pivots. + + Returns a 4-tuple: + (pivot_offset, pivot_val, assumed_nonzero, newly_determined) + ``pivot_offset`` is the sequence index of the pivot. + ``pivot_val`` is the value of the pivot. + pivot_val and col[pivot_index] are equivalent, but will be different + when col[pivot_index] was simplified during the pivot search. + ``assumed_nonzero`` is a boolean indicating if the pivot cannot be + guaranteed to be zero. If assumed_nonzero is true, then the pivot + may or may not be non-zero. If assumed_nonzero is false, then + the pivot is non-zero. + ``newly_determined`` is a list of index-value pairs of pivot candidates + that were simplified during the pivot search. + """ + + # indeterminates holds the index-value pairs of each pivot candidate + # that is neither zero or non-zero, as determined by iszerofunc(). + # If iszerofunc() indicates that a candidate pivot is guaranteed + # non-zero, or that every candidate pivot is zero then the contents + # of indeterminates are unused. + # Otherwise, the only viable candidate pivots are symbolic. + # In this case, indeterminates will have at least one entry, + # and all but the first entry are ignored when simpfunc is None. + indeterminates = [] + for i, col_val in enumerate(col): + col_val_is_zero = iszerofunc(col_val) + if col_val_is_zero == False: + # This pivot candidate is non-zero. + return i, col_val, False, [] + elif col_val_is_zero is None: + # The candidate pivot's comparison with zero + # is indeterminate. + indeterminates.append((i, col_val)) + + if len(indeterminates) == 0: + # All candidate pivots are guaranteed to be zero, i.e. there is + # no pivot. + return None, None, False, [] + + if simpfunc is None: + # Caller did not pass in a simplification function that might + # determine if an indeterminate pivot candidate is guaranteed + # to be nonzero, so assume the first indeterminate candidate + # is non-zero. + return indeterminates[0][0], indeterminates[0][1], True, [] + + # newly_determined holds index-value pairs of candidate pivots + # that were simplified during the search for a non-zero pivot. + newly_determined = [] + for i, col_val in indeterminates: + tmp_col_val = simpfunc(col_val) + if id(col_val) != id(tmp_col_val): + # simpfunc() simplified this candidate pivot. + newly_determined.append((i, tmp_col_val)) + if iszerofunc(tmp_col_val) == False: + # Candidate pivot simplified to a guaranteed non-zero value. + return i, tmp_col_val, False, newly_determined + + return indeterminates[0][0], indeterminates[0][1], True, newly_determined + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _berkowitz_toeplitz_matrix(M): + """Return (A,T) where T the Toeplitz matrix used in the Berkowitz algorithm + corresponding to ``M`` and A is the first principal submatrix. + """ + + # the 0 x 0 case is trivial + if M.rows == 0 and M.cols == 0: + return M._new(1,1, [M.one]) + + # + # Partition M = [ a_11 R ] + # [ C A ] + # + + a, R = M[0,0], M[0, 1:] + C, A = M[1:, 0], M[1:,1:] + + # + # The Toeplitz matrix looks like + # + # [ 1 ] + # [ -a 1 ] + # [ -RC -a 1 ] + # [ -RAC -RC -a 1 ] + # [ -RA**2C -RAC -RC -a 1 ] + # etc. + + # Compute the diagonal entries. + # Because multiplying matrix times vector is so much + # more efficient than matrix times matrix, recursively + # compute -R * A**n * C. + diags = [C] + for i in range(M.rows - 2): + diags.append(A.multiply(diags[i], dotprodsimp=None)) + diags = [(-R).multiply(d, dotprodsimp=None)[0, 0] for d in diags] + diags = [M.one, -a] + diags + + def entry(i,j): + if j > i: + return M.zero + return diags[i - j] + + toeplitz = M._new(M.cols + 1, M.rows, entry) + return (A, toeplitz) + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _berkowitz_vector(M): + """ Run the Berkowitz algorithm and return a vector whose entries + are the coefficients of the characteristic polynomial of ``M``. + + Given N x N matrix, efficiently compute + coefficients of characteristic polynomials of ``M`` + without division in the ground domain. + + This method is particularly useful for computing determinant, + principal minors and characteristic polynomial when ``M`` + has complicated coefficients e.g. polynomials. Semi-direct + usage of this algorithm is also important in computing + efficiently sub-resultant PRS. + + Assuming that M is a square matrix of dimension N x N and + I is N x N identity matrix, then the Berkowitz vector is + an N x 1 vector whose entries are coefficients of the + polynomial + + charpoly(M) = det(t*I - M) + + As a consequence, all polynomials generated by Berkowitz + algorithm are monic. + + For more information on the implemented algorithm refer to: + + [1] S.J. Berkowitz, On computing the determinant in small + parallel time using a small number of processors, ACM, + Information Processing Letters 18, 1984, pp. 147-150 + + [2] M. Keber, Division-Free computation of sub-resultants + using Bezout matrices, Tech. Report MPI-I-2006-1-006, + Saarbrucken, 2006 + """ + + # handle the trivial cases + if M.rows == 0 and M.cols == 0: + return M._new(1, 1, [M.one]) + elif M.rows == 1 and M.cols == 1: + return M._new(2, 1, [M.one, -M[0,0]]) + + submat, toeplitz = _berkowitz_toeplitz_matrix(M) + + return toeplitz.multiply(_berkowitz_vector(submat), dotprodsimp=None) + + +def _adjugate(M, method="berkowitz"): + """Returns the adjugate, or classical adjoint, of + a matrix. That is, the transpose of the matrix of cofactors. + + https://en.wikipedia.org/wiki/Adjugate + + Parameters + ========== + + method : string, optional + Method to use to find the cofactors, can be "bareiss", "berkowitz", + "bird", "laplace" or "lu". + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> M.adjugate() + Matrix([ + [ 4, -2], + [-3, 1]]) + + See Also + ======== + + cofactor_matrix + sympy.matrices.matrixbase.MatrixBase.transpose + """ + + return M.cofactor_matrix(method=method).transpose() + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _charpoly(M, x='lambda', simplify=_simplify): + """Computes characteristic polynomial det(x*I - M) where I is + the identity matrix. + + A PurePoly is returned, so using different variables for ``x`` does + not affect the comparison or the polynomials: + + Parameters + ========== + + x : string, optional + Name for the "lambda" variable, defaults to "lambda". + + simplify : function, optional + Simplification function to use on the characteristic polynomial + calculated. Defaults to ``simplify``. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[1, 3], [2, 0]]) + >>> M.charpoly() + PurePoly(lambda**2 - lambda - 6, lambda, domain='ZZ') + >>> M.charpoly(x) == M.charpoly(y) + True + >>> M.charpoly(x) == M.charpoly(y) + True + + Specifying ``x`` is optional; a symbol named ``lambda`` is used by + default (which looks good when pretty-printed in unicode): + + >>> M.charpoly().as_expr() + lambda**2 - lambda - 6 + + And if ``x`` clashes with an existing symbol, underscores will + be prepended to the name to make it unique: + + >>> M = Matrix([[1, 2], [x, 0]]) + >>> M.charpoly(x).as_expr() + _x**2 - _x - 2*x + + Whether you pass a symbol or not, the generator can be obtained + with the gen attribute since it may not be the same as the symbol + that was passed: + + >>> M.charpoly(x).gen + _x + >>> M.charpoly(x).gen == x + False + + Notes + ===== + + The Samuelson-Berkowitz algorithm is used to compute + the characteristic polynomial efficiently and without any + division operations. Thus the characteristic polynomial over any + commutative ring without zero divisors can be computed. + + If the determinant det(x*I - M) can be found out easily as + in the case of an upper or a lower triangular matrix, then + instead of Samuelson-Berkowitz algorithm, eigenvalues are computed + and the characteristic polynomial with their help. + + See Also + ======== + + det + """ + + if not M.is_square: + raise NonSquareMatrixError() + + # Use DomainMatrix. We are already going to convert this to a Poly so there + # is no need to worry about expanding powers etc. Also since this algorithm + # does not require division or zero detection it is fine to use EX. + # + # M.to_DM() will fall back on EXRAW rather than EX. EXRAW is a lot faster + # for elementary arithmetic because it does not call cancel for each + # operation but it generates large unsimplified results that are slow in + # the subsequent call to simplify. Using EX instead is faster overall + # but at least in some cases EXRAW+simplify gives a simpler result so we + # preserve that existing behaviour of charpoly for now... + dM = M.to_DM() + + K = dM.domain + + cp = dM.charpoly() + + x = uniquely_named_symbol(x, [M], modify=lambda s: '_' + s) + + if K.is_EXRAW or simplify is not _simplify: + # XXX: Converting back to Expr is expensive. We only do it if the + # caller supplied a custom simplify function for backwards + # compatibility or otherwise if the domain was EX. For any other domain + # there should be no benefit in simplifying at this stage because Poly + # will put everything into canonical form anyway. + berk_vector = [K.to_sympy(c) for c in cp] + berk_vector = [simplify(a) for a in berk_vector] + p = PurePoly(berk_vector, x) + + else: + # Convert from the list of domain elements directly to Poly. + p = PurePoly(cp, x, domain=K) + + return p + + +def _cofactor(M, i, j, method="berkowitz"): + """Calculate the cofactor of an element. + + Parameters + ========== + + method : string, optional + Method to use to find the cofactors, can be "bareiss", "berkowitz", + "bird", "laplace" or "lu". + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> M.cofactor(0, 1) + -3 + + See Also + ======== + + cofactor_matrix + minor + minor_submatrix + """ + + if not M.is_square or M.rows < 1: + raise NonSquareMatrixError() + + return S.NegativeOne**((i + j) % 2) * M.minor(i, j, method) + + +def _cofactor_matrix(M, method="berkowitz"): + """Return a matrix containing the cofactor of each element. + + Parameters + ========== + + method : string, optional + Method to use to find the cofactors, can be "bareiss", "berkowitz", + "bird", "laplace" or "lu". + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> M.cofactor_matrix() + Matrix([ + [ 4, -3], + [-2, 1]]) + + See Also + ======== + + cofactor + minor + minor_submatrix + """ + + if not M.is_square: + raise NonSquareMatrixError() + + return M._new(M.rows, M.cols, + lambda i, j: M.cofactor(i, j, method)) + +def _per(M): + """Returns the permanent of a matrix. Unlike determinant, + permanent is defined for both square and non-square matrices. + + For an m x n matrix, with m less than or equal to n, + it is given as the sum over the permutations s of size + less than or equal to m on [1, 2, . . . n] of the product + from i = 1 to m of M[i, s[i]]. Taking the transpose will + not affect the value of the permanent. + + In the case of a square matrix, this is the same as the permutation + definition of the determinant, but it does not take the sign of the + permutation into account. Computing the permanent with this definition + is quite inefficient, so here the Ryser formula is used. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> M.per() + 450 + >>> M = Matrix([1, 5, 7]) + >>> M.per() + 13 + + References + ========== + + .. [1] Prof. Frank Ben's notes: https://math.berkeley.edu/~bernd/ban275.pdf + .. [2] Wikipedia article on Permanent: https://en.wikipedia.org/wiki/Permanent_%28mathematics%29 + .. [3] https://reference.wolfram.com/language/ref/Permanent.html + .. [4] Permanent of a rectangular matrix : https://arxiv.org/pdf/0904.3251.pdf + """ + import itertools + + m, n = M.shape + if m > n: + M = M.T + m, n = n, m + s = list(range(n)) + + subsets = [] + for i in range(1, m + 1): + subsets += list(map(list, itertools.combinations(s, i))) + + perm = 0 + for subset in subsets: + prod = 1 + sub_len = len(subset) + for i in range(m): + prod *= sum(M[i, j] for j in subset) + perm += prod * S.NegativeOne**sub_len * nC(n - sub_len, m - sub_len) + perm *= S.NegativeOne**m + return perm.simplify() + +def _det_DOM(M): + DOM = DomainMatrix.from_Matrix(M, field=True, extension=True) + K = DOM.domain + return K.to_sympy(DOM.det()) + +# This functions is a candidate for caching if it gets implemented for matrices. +def _det(M, method="bareiss", iszerofunc=None): + """Computes the determinant of a matrix if ``M`` is a concrete matrix object + otherwise return an expressions ``Determinant(M)`` if ``M`` is a + ``MatrixSymbol`` or other expression. + + Parameters + ========== + + method : string, optional + Specifies the algorithm used for computing the matrix determinant. + + If the matrix is at most 3x3, a hard-coded formula is used and the + specified method is ignored. Otherwise, it defaults to + ``'bareiss'``. + + Also, if the matrix is an upper or a lower triangular matrix, determinant + is computed by simple multiplication of diagonal elements, and the + specified method is ignored. + + If it is set to ``'domain-ge'``, then Gaussian elimination method will + be used via using DomainMatrix. + + If it is set to ``'bareiss'``, Bareiss' fraction-free algorithm will + be used. + + If it is set to ``'berkowitz'``, Berkowitz' algorithm will be used. + + If it is set to ``'bird'``, Bird's algorithm will be used [1]_. + + If it is set to ``'laplace'``, Laplace's algorithm will be used. + + Otherwise, if it is set to ``'lu'``, LU decomposition will be used. + + .. note:: + For backward compatibility, legacy keys like "bareis" and + "det_lu" can still be used to indicate the corresponding + methods. + And the keys are also case-insensitive for now. However, it is + suggested to use the precise keys for specifying the method. + + iszerofunc : FunctionType or None, optional + If it is set to ``None``, it will be defaulted to ``_iszero`` if the + method is set to ``'bareiss'``, and ``_is_zero_after_expand_mul`` if + the method is set to ``'lu'``. + + It can also accept any user-specified zero testing function, if it + is formatted as a function which accepts a single symbolic argument + and returns ``True`` if it is tested as zero and ``False`` if it + tested as non-zero, and also ``None`` if it is undecidable. + + Returns + ======= + + det : Basic + Result of determinant. + + Raises + ====== + + ValueError + If unrecognized keys are given for ``method`` or ``iszerofunc``. + + NonSquareMatrixError + If attempted to calculate determinant from a non-square matrix. + + Examples + ======== + + >>> from sympy import Matrix, eye, det + >>> I3 = eye(3) + >>> det(I3) + 1 + >>> M = Matrix([[1, 2], [3, 4]]) + >>> det(M) + -2 + >>> det(M) == M.det() + True + >>> M.det(method="domain-ge") + -2 + + References + ========== + + .. [1] Bird, R. S. (2011). A simple division-free algorithm for computing + determinants. Inf. Process. Lett., 111(21), 1072-1074. doi: + 10.1016/j.ipl.2011.08.006 + """ + + # sanitize `method` + method = method.lower() + + if method == "bareis": + method = "bareiss" + elif method == "det_lu": + method = "lu" + + if method not in ("bareiss", "berkowitz", "lu", "domain-ge", "bird", + "laplace"): + raise ValueError("Determinant method '%s' unrecognized" % method) + + if iszerofunc is None: + if method == "bareiss": + iszerofunc = _is_zero_after_expand_mul + elif method == "lu": + iszerofunc = _iszero + + elif not isinstance(iszerofunc, FunctionType): + raise ValueError("Zero testing method '%s' unrecognized" % iszerofunc) + + n = M.rows + + if n == M.cols: # square check is done in individual method functions + if n == 0: + return M.one + elif n == 1: + return M[0, 0] + elif n == 2: + m = M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0] + return _get_intermediate_simp(_dotprodsimp)(m) + elif n == 3: + m = (M[0, 0] * M[1, 1] * M[2, 2] + + M[0, 1] * M[1, 2] * M[2, 0] + + M[0, 2] * M[1, 0] * M[2, 1] + - M[0, 2] * M[1, 1] * M[2, 0] + - M[0, 0] * M[1, 2] * M[2, 1] + - M[0, 1] * M[1, 0] * M[2, 2]) + return _get_intermediate_simp(_dotprodsimp)(m) + + dets = [] + for b in M.strongly_connected_components(): + if method == "domain-ge": # uses DomainMatrix to evaluate determinant + det = _det_DOM(M[b, b]) + elif method == "bareiss": + det = M[b, b]._eval_det_bareiss(iszerofunc=iszerofunc) + elif method == "berkowitz": + det = M[b, b]._eval_det_berkowitz() + elif method == "lu": + det = M[b, b]._eval_det_lu(iszerofunc=iszerofunc) + elif method == "bird": + det = M[b, b]._eval_det_bird() + elif method == "laplace": + det = M[b, b]._eval_det_laplace() + dets.append(det) + return Mul(*dets) + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _det_bareiss(M, iszerofunc=_is_zero_after_expand_mul): + """Compute matrix determinant using Bareiss' fraction-free + algorithm which is an extension of the well known Gaussian + elimination method. This approach is best suited for dense + symbolic matrices and will result in a determinant with + minimal number of fractions. It means that less term + rewriting is needed on resulting formulae. + + Parameters + ========== + + iszerofunc : function, optional + The function to use to determine zeros when doing an LU decomposition. + Defaults to ``lambda x: x.is_zero``. + + TODO: Implement algorithm for sparse matrices (SFF), + http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps. + """ + + # Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's + # thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf + def bareiss(mat, cumm=1): + if mat.rows == 0: + return mat.one + elif mat.rows == 1: + return mat[0, 0] + + # find a pivot and extract the remaining matrix + # With the default iszerofunc, _find_reasonable_pivot slows down + # the computation by the factor of 2.5 in one test. + # Relevant issues: #10279 and #13877. + pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0], iszerofunc=iszerofunc) + if pivot_pos is None: + return mat.zero + + # if we have a valid pivot, we'll do a "row swap", so keep the + # sign of the det + sign = (-1) ** (pivot_pos % 2) + + # we want every row but the pivot row and every column + rows = [i for i in range(mat.rows) if i != pivot_pos] + cols = list(range(mat.cols)) + tmp_mat = mat.extract(rows, cols) + + def entry(i, j): + ret = (pivot_val*tmp_mat[i, j + 1] - mat[pivot_pos, j + 1]*tmp_mat[i, 0]) / cumm + if _get_intermediate_simp_bool(True): + return _dotprodsimp(ret) + elif not ret.is_Atom: + return cancel(ret) + return ret + + return sign*bareiss(M._new(mat.rows - 1, mat.cols - 1, entry), pivot_val) + + if not M.is_square: + raise NonSquareMatrixError() + + if M.rows == 0: + return M.one + # sympy/matrices/tests/test_matrices.py contains a test that + # suggests that the determinant of a 0 x 0 matrix is one, by + # convention. + + return bareiss(M) + + +def _det_berkowitz(M): + """ Use the Berkowitz algorithm to compute the determinant.""" + + if not M.is_square: + raise NonSquareMatrixError() + + if M.rows == 0: + return M.one + # sympy/matrices/tests/test_matrices.py contains a test that + # suggests that the determinant of a 0 x 0 matrix is one, by + # convention. + + berk_vector = _berkowitz_vector(M) + return (-1)**(len(berk_vector) - 1) * berk_vector[-1] + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _det_LU(M, iszerofunc=_iszero, simpfunc=None): + """ Computes the determinant of a matrix from its LU decomposition. + This function uses the LU decomposition computed by + LUDecomposition_Simple(). + + The keyword arguments iszerofunc and simpfunc are passed to + LUDecomposition_Simple(). + iszerofunc is a callable that returns a boolean indicating if its + input is zero, or None if it cannot make the determination. + simpfunc is a callable that simplifies its input. + The default is simpfunc=None, which indicate that the pivot search + algorithm should not attempt to simplify any candidate pivots. + If simpfunc fails to simplify its input, then it must return its input + instead of a copy. + + Parameters + ========== + + iszerofunc : function, optional + The function to use to determine zeros when doing an LU decomposition. + Defaults to ``lambda x: x.is_zero``. + + simpfunc : function, optional + The simplification function to use when looking for zeros for pivots. + """ + + if not M.is_square: + raise NonSquareMatrixError() + + if M.rows == 0: + return M.one + # sympy/matrices/tests/test_matrices.py contains a test that + # suggests that the determinant of a 0 x 0 matrix is one, by + # convention. + + lu, row_swaps = M.LUdecomposition_Simple(iszerofunc=iszerofunc, + simpfunc=simpfunc) + # P*A = L*U => det(A) = det(L)*det(U)/det(P) = det(P)*det(U). + # Lower triangular factor L encoded in lu has unit diagonal => det(L) = 1. + # P is a permutation matrix => det(P) in {-1, 1} => 1/det(P) = det(P). + # LUdecomposition_Simple() returns a list of row exchange index pairs, rather + # than a permutation matrix, but det(P) = (-1)**len(row_swaps). + + # Avoid forming the potentially time consuming product of U's diagonal entries + # if the product is zero. + # Bottom right entry of U is 0 => det(A) = 0. + # It may be impossible to determine if this entry of U is zero when it is symbolic. + if iszerofunc(lu[lu.rows-1, lu.rows-1]): + return M.zero + + # Compute det(P) + det = -M.one if len(row_swaps)%2 else M.one + + # Compute det(U) by calculating the product of U's diagonal entries. + # The upper triangular portion of lu is the upper triangular portion of the + # U factor in the LU decomposition. + for k in range(lu.rows): + det *= lu[k, k] + + # return det(P)*det(U) + return det + + +@cacheit +def __det_laplace(M): + """Compute the determinant of a matrix using Laplace expansion. + + This is a recursive function, and it should not be called directly. + Use _det_laplace() instead. The reason for splitting this function + into two is to allow caching of determinants of submatrices. While + one could also define this function inside _det_laplace(), that + would remove the advantage of using caching in Cramer Solve. + """ + n = M.shape[0] + if n == 1: + return M[0] + elif n == 2: + return M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0] + else: + return sum((-1) ** i * M[0, i] * + __det_laplace(M.minor_submatrix(0, i)) for i in range(n)) + + +def _det_laplace(M): + """Compute the determinant of a matrix using Laplace expansion. + + While Laplace expansion is not the most efficient method of computing + a determinant, it is a simple one, and it has the advantage of + being division free. To improve efficiency, this function uses + caching to avoid recomputing determinants of submatrices. + """ + if not M.is_square: + raise NonSquareMatrixError() + if M.shape[0] == 0: + return M.one + # sympy/matrices/tests/test_matrices.py contains a test that + # suggests that the determinant of a 0 x 0 matrix is one, by + # convention. + return __det_laplace(M.as_immutable()) + + +def _det_bird(M): + r"""Compute the determinant of a matrix using Bird's algorithm. + + Bird's algorithm is a simple division-free algorithm for computing, which + is of lower order than the Laplace's algorithm. It is described in [1]_. + + References + ========== + + .. [1] Bird, R. S. (2011). A simple division-free algorithm for computing + determinants. Inf. Process. Lett., 111(21), 1072-1074. doi: + 10.1016/j.ipl.2011.08.006 + """ + def mu(X): + n = X.shape[0] + zero = X.domain.zero + + total = zero + diag_sums = [zero] + for i in reversed(range(1, n)): + total -= X[i][i] + diag_sums.append(total) + diag_sums = diag_sums[::-1] + + elems = [[zero] * i + [diag_sums[i]] + X_i[i + 1:] for i, X_i in + enumerate(X)] + return DDM(elems, X.shape, X.domain) + + Mddm = M._rep.to_ddm() + n = M.shape[0] + if n == 0: + return M.one + # sympy/matrices/tests/test_matrices.py contains a test that + # suggests that the determinant of a 0 x 0 matrix is one, by + # convention. + Fn1 = Mddm + for _ in range(n - 1): + Fn1 = mu(Fn1).matmul(Mddm) + detA = Fn1[0][0] + if n % 2 == 0: + detA = -detA + + return Mddm.domain.to_sympy(detA) + + +def _minor(M, i, j, method="berkowitz"): + """Return the (i,j) minor of ``M``. That is, + return the determinant of the matrix obtained by deleting + the `i`th row and `j`th column from ``M``. + + Parameters + ========== + + i, j : int + The row and column to exclude to obtain the submatrix. + + method : string, optional + Method to use to find the determinant of the submatrix, can be + "bareiss", "berkowitz", "bird", "laplace" or "lu". + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> M.minor(1, 1) + -12 + + See Also + ======== + + minor_submatrix + cofactor + det + """ + + if not M.is_square: + raise NonSquareMatrixError() + + return M.minor_submatrix(i, j).det(method=method) + + +def _minor_submatrix(M, i, j): + """Return the submatrix obtained by removing the `i`th row + and `j`th column from ``M`` (works with Pythonic negative indices). + + Parameters + ========== + + i, j : int + The row and column to exclude to obtain the submatrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> M.minor_submatrix(1, 1) + Matrix([ + [1, 3], + [7, 9]]) + + See Also + ======== + + minor + cofactor + """ + + if i < 0: + i += M.rows + if j < 0: + j += M.cols + + if not 0 <= i < M.rows or not 0 <= j < M.cols: + raise ValueError("`i` and `j` must satisfy 0 <= i < ``M.rows`` " + "(%d)" % M.rows + "and 0 <= j < ``M.cols`` (%d)." % M.cols) + + rows = [a for a in range(M.rows) if a != i] + cols = [a for a in range(M.cols) if a != j] + + return M.extract(rows, cols) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/eigen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/eigen.py new file mode 100644 index 0000000000000000000000000000000000000000..87b2418efcece1c0b158ec56995bb011286feb3c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/eigen.py @@ -0,0 +1,1346 @@ +from types import FunctionType +from collections import Counter + +from mpmath import mp, workprec +from mpmath.libmp.libmpf import prec_to_dps + +from sympy.core.sorting import default_sort_key +from sympy.core.evalf import DEFAULT_MAXPREC, PrecisionExhausted +from sympy.core.logic import fuzzy_and, fuzzy_or +from sympy.core.numbers import Float +from sympy.core.sympify import _sympify +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.polys import roots, CRootOf, ZZ, QQ, EX +from sympy.polys.matrices import DomainMatrix +from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy +from sympy.polys.polytools import gcd + +from .exceptions import MatrixError, NonSquareMatrixError +from .determinant import _find_reasonable_pivot + +from .utilities import _iszero, _simplify + + +__doctest_requires__ = { + ('_is_indefinite', + '_is_negative_definite', + '_is_negative_semidefinite', + '_is_positive_definite', + '_is_positive_semidefinite'): ['matplotlib'], +} + + +def _eigenvals_eigenvects_mpmath(M): + norm2 = lambda v: mp.sqrt(sum(i**2 for i in v)) + + v1 = None + prec = max(x._prec for x in M.atoms(Float)) + eps = 2**-prec + + while prec < DEFAULT_MAXPREC: + with workprec(prec): + A = mp.matrix(M.evalf(n=prec_to_dps(prec))) + E, ER = mp.eig(A) + v2 = norm2([i for e in E for i in (mp.re(e), mp.im(e))]) + if v1 is not None and mp.fabs(v1 - v2) < eps: + return E, ER + v1 = v2 + prec *= 2 + + # we get here because the next step would have taken us + # past MAXPREC or because we never took a step; in case + # of the latter, we refuse to send back a solution since + # it would not have been verified; we also resist taking + # a small step to arrive exactly at MAXPREC since then + # the two calculations might be artificially close. + raise PrecisionExhausted + + +def _eigenvals_mpmath(M, multiple=False): + """Compute eigenvalues using mpmath""" + E, _ = _eigenvals_eigenvects_mpmath(M) + result = [_sympify(x) for x in E] + if multiple: + return result + return dict(Counter(result)) + + +def _eigenvects_mpmath(M): + E, ER = _eigenvals_eigenvects_mpmath(M) + result = [] + for i in range(M.rows): + eigenval = _sympify(E[i]) + eigenvect = _sympify(ER[:, i]) + result.append((eigenval, 1, [eigenvect])) + + return result + + +# This function is a candidate for caching if it gets implemented for matrices. +def _eigenvals( + M, error_when_incomplete=True, *, simplify=False, multiple=False, + rational=False, **flags): + r"""Compute eigenvalues of the matrix. + + Parameters + ========== + + error_when_incomplete : bool, optional + If it is set to ``True``, it will raise an error if not all + eigenvalues are computed. This is caused by ``roots`` not returning + a full list of eigenvalues. + + simplify : bool or function, optional + If it is set to ``True``, it attempts to return the most + simplified form of expressions returned by applying default + simplification method in every routine. + + If it is set to ``False``, it will skip simplification in this + particular routine to save computation resources. + + If a function is passed to, it will attempt to apply + the particular function as simplification method. + + rational : bool, optional + If it is set to ``True``, every floating point numbers would be + replaced with rationals before computation. It can solve some + issues of ``roots`` routine not working well with floats. + + multiple : bool, optional + If it is set to ``True``, the result will be in the form of a + list. + + If it is set to ``False``, the result will be in the form of a + dictionary. + + Returns + ======= + + eigs : list or dict + Eigenvalues of a matrix. The return format would be specified by + the key ``multiple``. + + Raises + ====== + + MatrixError + If not enough roots had got computed. + + NonSquareMatrixError + If attempted to compute eigenvalues from a non-square matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) + >>> M.eigenvals() + {-1: 1, 0: 1, 2: 1} + + See Also + ======== + + MatrixBase.charpoly + eigenvects + + Notes + ===== + + Eigenvalues of a matrix $A$ can be computed by solving a matrix + equation $\det(A - \lambda I) = 0$ + + It's not always possible to return radical solutions for + eigenvalues for matrices larger than $4, 4$ shape due to + Abel-Ruffini theorem. + + If there is no radical solution is found for the eigenvalue, + it may return eigenvalues in the form of + :class:`sympy.polys.rootoftools.ComplexRootOf`. + """ + if not M: + if multiple: + return [] + return {} + + if not M.is_square: + raise NonSquareMatrixError("{} must be a square matrix.".format(M)) + + if M._rep.domain not in (ZZ, QQ): + # Skip this check for ZZ/QQ because it can be slow + if all(x.is_number for x in M) and M.has(Float): + return _eigenvals_mpmath(M, multiple=multiple) + + if rational: + from sympy.simplify import nsimplify + M = M.applyfunc( + lambda x: nsimplify(x, rational=True) if x.has(Float) else x) + + if multiple: + return _eigenvals_list( + M, error_when_incomplete=error_when_incomplete, simplify=simplify, + **flags) + return _eigenvals_dict( + M, error_when_incomplete=error_when_incomplete, simplify=simplify, + **flags) + + +eigenvals_error_message = \ +"It is not always possible to express the eigenvalues of a matrix " + \ +"of size 5x5 or higher in radicals. " + \ +"We have CRootOf, but domains other than the rationals are not " + \ +"currently supported. " + \ +"If there are no symbols in the matrix, " + \ +"it should still be possible to compute numeric approximations " + \ +"of the eigenvalues using " + \ +"M.evalf().eigenvals() or M.charpoly().nroots()." + + +def _eigenvals_list( + M, error_when_incomplete=True, simplify=False, **flags): + iblocks = M.strongly_connected_components() + all_eigs = [] + is_dom = M._rep.domain in (ZZ, QQ) + for b in iblocks: + + # Fast path for a 1x1 block: + if is_dom and len(b) == 1: + index = b[0] + val = M[index, index] + all_eigs.append(val) + continue + + block = M[b, b] + + if isinstance(simplify, FunctionType): + charpoly = block.charpoly(simplify=simplify) + else: + charpoly = block.charpoly() + + eigs = roots(charpoly, multiple=True, **flags) + + if len(eigs) != block.rows: + try: + eigs = charpoly.all_roots(multiple=True) + except NotImplementedError: + if error_when_incomplete: + raise MatrixError(eigenvals_error_message) + else: + eigs = [] + + all_eigs += eigs + + if not simplify: + return all_eigs + if not isinstance(simplify, FunctionType): + simplify = _simplify + return [simplify(value) for value in all_eigs] + + +def _eigenvals_dict( + M, error_when_incomplete=True, simplify=False, **flags): + iblocks = M.strongly_connected_components() + all_eigs = {} + is_dom = M._rep.domain in (ZZ, QQ) + for b in iblocks: + + # Fast path for a 1x1 block: + if is_dom and len(b) == 1: + index = b[0] + val = M[index, index] + all_eigs[val] = all_eigs.get(val, 0) + 1 + continue + + block = M[b, b] + + if isinstance(simplify, FunctionType): + charpoly = block.charpoly(simplify=simplify) + else: + charpoly = block.charpoly() + + eigs = roots(charpoly, multiple=False, **flags) + + if sum(eigs.values()) != block.rows: + try: + eigs = dict(charpoly.all_roots(multiple=False)) + except NotImplementedError: + if error_when_incomplete: + raise MatrixError(eigenvals_error_message) + else: + eigs = {} + + for k, v in eigs.items(): + if k in all_eigs: + all_eigs[k] += v + else: + all_eigs[k] = v + + if not simplify: + return all_eigs + if not isinstance(simplify, FunctionType): + simplify = _simplify + return {simplify(key): value for key, value in all_eigs.items()} + + +def _eigenspace(M, eigenval, iszerofunc=_iszero, simplify=False): + """Get a basis for the eigenspace for a particular eigenvalue""" + m = M - M.eye(M.rows) * eigenval + ret = m.nullspace(iszerofunc=iszerofunc) + + # The nullspace for a real eigenvalue should be non-trivial. + # If we didn't find an eigenvector, try once more a little harder + if len(ret) == 0 and simplify: + ret = m.nullspace(iszerofunc=iszerofunc, simplify=True) + if len(ret) == 0: + raise NotImplementedError( + "Can't evaluate eigenvector for eigenvalue {}".format(eigenval)) + return ret + + +def _eigenvects_DOM(M, **kwargs): + DOM = DomainMatrix.from_Matrix(M, field=True, extension=True) + DOM = DOM.to_dense() + + if DOM.domain != EX: + rational, algebraic = dom_eigenvects(DOM) + eigenvects = dom_eigenvects_to_sympy( + rational, algebraic, M.__class__, **kwargs) + eigenvects = sorted(eigenvects, key=lambda x: default_sort_key(x[0])) + + return eigenvects + return None + + +def _eigenvects_sympy(M, iszerofunc, simplify=True, **flags): + eigenvals = M.eigenvals(rational=False, **flags) + + # Make sure that we have all roots in radical form + for x in eigenvals: + if x.has(CRootOf): + raise MatrixError( + "Eigenvector computation is not implemented if the matrix have " + "eigenvalues in CRootOf form") + + eigenvals = sorted(eigenvals.items(), key=default_sort_key) + ret = [] + for val, mult in eigenvals: + vects = _eigenspace(M, val, iszerofunc=iszerofunc, simplify=simplify) + ret.append((val, mult, vects)) + return ret + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _eigenvects(M, error_when_incomplete=True, iszerofunc=_iszero, *, chop=False, **flags): + """Compute eigenvectors of the matrix. + + Parameters + ========== + + error_when_incomplete : bool, optional + Raise an error when not all eigenvalues are computed. This is + caused by ``roots`` not returning a full list of eigenvalues. + + iszerofunc : function, optional + Specifies a zero testing function to be used in ``rref``. + + Default value is ``_iszero``, which uses SymPy's naive and fast + default assumption handler. + + It can also accept any user-specified zero testing function, if it + is formatted as a function which accepts a single symbolic argument + and returns ``True`` if it is tested as zero and ``False`` if it + is tested as non-zero, and ``None`` if it is undecidable. + + simplify : bool or function, optional + If ``True``, ``as_content_primitive()`` will be used to tidy up + normalization artifacts. + + It will also be used by the ``nullspace`` routine. + + chop : bool or positive number, optional + If the matrix contains any Floats, they will be changed to Rationals + for computation purposes, but the answers will be returned after + being evaluated with evalf. The ``chop`` flag is passed to ``evalf``. + When ``chop=True`` a default precision will be used; a number will + be interpreted as the desired level of precision. + + Returns + ======= + + ret : [(eigenval, multiplicity, eigenspace), ...] + A ragged list containing tuples of data obtained by ``eigenvals`` + and ``nullspace``. + + ``eigenspace`` is a list containing the ``eigenvector`` for each + eigenvalue. + + ``eigenvector`` is a vector in the form of a ``Matrix``. e.g. + a vector of length 3 is returned as ``Matrix([a_1, a_2, a_3])``. + + Raises + ====== + + NotImplementedError + If failed to compute nullspace. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) + >>> M.eigenvects() + [(-1, 1, [Matrix([ + [-1], + [ 1], + [ 0]])]), (0, 1, [Matrix([ + [ 0], + [-1], + [ 1]])]), (2, 1, [Matrix([ + [2/3], + [1/3], + [ 1]])])] + + See Also + ======== + + eigenvals + MatrixBase.nullspace + """ + simplify = flags.get('simplify', True) + primitive = flags.get('simplify', False) + flags.pop('simplify', None) # remove this if it's there + flags.pop('multiple', None) # remove this if it's there + + if not isinstance(simplify, FunctionType): + simpfunc = _simplify if simplify else lambda x: x + + has_floats = M.has(Float) + if has_floats: + if all(x.is_number for x in M): + return _eigenvects_mpmath(M) + from sympy.simplify import nsimplify + M = M.applyfunc(lambda x: nsimplify(x, rational=True)) + + ret = _eigenvects_DOM(M) + if ret is None: + ret = _eigenvects_sympy(M, iszerofunc, simplify=simplify, **flags) + + if primitive: + # if the primitive flag is set, get rid of any common + # integer denominators + def denom_clean(l): + return [(v / gcd(list(v))).applyfunc(simpfunc) for v in l] + + ret = [(val, mult, denom_clean(es)) for val, mult, es in ret] + + if has_floats: + # if we had floats to start with, turn the eigenvectors to floats + ret = [(val.evalf(chop=chop), mult, [v.evalf(chop=chop) for v in es]) + for val, mult, es in ret] + + return ret + + +def _is_diagonalizable_with_eigen(M, reals_only=False): + """See _is_diagonalizable. This function returns the bool along with the + eigenvectors to avoid calculating them again in functions like + ``diagonalize``.""" + + if not M.is_square: + return False, [] + + eigenvecs = M.eigenvects(simplify=True) + + for val, mult, basis in eigenvecs: + if reals_only and not val.is_real: # if we have a complex eigenvalue + return False, eigenvecs + + if mult != len(basis): # if the geometric multiplicity doesn't equal the algebraic + return False, eigenvecs + + return True, eigenvecs + +def _is_diagonalizable(M, reals_only=False, **kwargs): + """Returns ``True`` if a matrix is diagonalizable. + + Parameters + ========== + + reals_only : bool, optional + If ``True``, it tests whether the matrix can be diagonalized + to contain only real numbers on the diagonal. + + + If ``False``, it tests whether the matrix can be diagonalized + at all, even with numbers that may not be real. + + Examples + ======== + + Example of a diagonalizable matrix: + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2, 0], [0, 3, 0], [2, -4, 2]]) + >>> M.is_diagonalizable() + True + + Example of a non-diagonalizable matrix: + + >>> M = Matrix([[0, 1], [0, 0]]) + >>> M.is_diagonalizable() + False + + Example of a matrix that is diagonalized in terms of non-real entries: + + >>> M = Matrix([[0, 1], [-1, 0]]) + >>> M.is_diagonalizable(reals_only=False) + True + >>> M.is_diagonalizable(reals_only=True) + False + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.is_diagonal + diagonalize + """ + if not M.is_square: + return False + + if all(e.is_real for e in M) and M.is_symmetric(): + return True + + if all(e.is_complex for e in M) and M.is_hermitian: + return True + + return _is_diagonalizable_with_eigen(M, reals_only=reals_only)[0] + + +#G&VL, Matrix Computations, Algo 5.4.2 +def _householder_vector(x): + if not x.cols == 1: + raise ValueError("Input must be a column matrix") + v = x.copy() + v_plus = x.copy() + v_minus = x.copy() + q = x[0, 0] / abs(x[0, 0]) + norm_x = x.norm() + v_plus[0, 0] = x[0, 0] + q * norm_x + v_minus[0, 0] = x[0, 0] - q * norm_x + if x[1:, 0].norm() == 0: + bet = 0 + v[0, 0] = 1 + else: + if v_plus.norm() <= v_minus.norm(): + v = v_plus + else: + v = v_minus + v = v / v[0] + bet = 2 / (v.norm() ** 2) + return v, bet + + +def _bidiagonal_decmp_hholder(M): + m = M.rows + n = M.cols + A = M.as_mutable() + U, V = A.eye(m), A.eye(n) + for i in range(min(m, n)): + v, bet = _householder_vector(A[i:, i]) + hh_mat = A.eye(m - i) - bet * v * v.H + A[i:, i:] = hh_mat * A[i:, i:] + temp = A.eye(m) + temp[i:, i:] = hh_mat + U = U * temp + if i + 1 <= n - 2: + v, bet = _householder_vector(A[i, i+1:].T) + hh_mat = A.eye(n - i - 1) - bet * v * v.H + A[i:, i+1:] = A[i:, i+1:] * hh_mat + temp = A.eye(n) + temp[i+1:, i+1:] = hh_mat + V = temp * V + return U, A, V + + +def _eval_bidiag_hholder(M): + m = M.rows + n = M.cols + A = M.as_mutable() + for i in range(min(m, n)): + v, bet = _householder_vector(A[i:, i]) + hh_mat = A.eye(m-i) - bet * v * v.H + A[i:, i:] = hh_mat * A[i:, i:] + if i + 1 <= n - 2: + v, bet = _householder_vector(A[i, i+1:].T) + hh_mat = A.eye(n - i - 1) - bet * v * v.H + A[i:, i+1:] = A[i:, i+1:] * hh_mat + return A + + +def _bidiagonal_decomposition(M, upper=True): + """ + Returns $(U,B,V.H)$ for + + $$A = UBV^{H}$$ + + where $A$ is the input matrix, and $B$ is its Bidiagonalized form + + Note: Bidiagonal Computation can hang for symbolic matrices. + + Parameters + ========== + + upper : bool. Whether to do upper bidiagnalization or lower. + True for upper and False for lower. + + References + ========== + + .. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition + .. [2] Complex Matrix Bidiagonalization, https://github.com/vslobody/Householder-Bidiagonalization + + """ + + if not isinstance(upper, bool): + raise ValueError("upper must be a boolean") + + if upper: + return _bidiagonal_decmp_hholder(M) + + X = _bidiagonal_decmp_hholder(M.H) + return X[2].H, X[1].H, X[0].H + + +def _bidiagonalize(M, upper=True): + """ + Returns $B$, the Bidiagonalized form of the input matrix. + + Note: Bidiagonal Computation can hang for symbolic matrices. + + Parameters + ========== + + upper : bool. Whether to do upper bidiagnalization or lower. + True for upper and False for lower. + + References + ========== + + .. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition + .. [2] Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization + + """ + + if not isinstance(upper, bool): + raise ValueError("upper must be a boolean") + + if upper: + return _eval_bidiag_hholder(M) + return _eval_bidiag_hholder(M.H).H + + +def _diagonalize(M, reals_only=False, sort=False, normalize=False): + """ + Return (P, D), where D is diagonal and + + D = P^-1 * M * P + + where M is current matrix. + + Parameters + ========== + + reals_only : bool. Whether to throw an error if complex numbers are need + to diagonalize. (Default: False) + + sort : bool. Sort the eigenvalues along the diagonal. (Default: False) + + normalize : bool. If True, normalize the columns of P. (Default: False) + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) + >>> M + Matrix([ + [1, 2, 0], + [0, 3, 0], + [2, -4, 2]]) + >>> (P, D) = M.diagonalize() + >>> D + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + >>> P + Matrix([ + [-1, 0, -1], + [ 0, 0, -1], + [ 2, 1, 2]]) + >>> P.inv() * M * P + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.is_diagonal + is_diagonalizable + """ + + if not M.is_square: + raise NonSquareMatrixError() + + is_diagonalizable, eigenvecs = _is_diagonalizable_with_eigen(M, + reals_only=reals_only) + + if not is_diagonalizable: + raise MatrixError("Matrix is not diagonalizable") + + if sort: + eigenvecs = sorted(eigenvecs, key=default_sort_key) + + p_cols, diag = [], [] + + for val, mult, basis in eigenvecs: + diag += [val] * mult + p_cols += basis + + if normalize: + p_cols = [v / v.norm() for v in p_cols] + + return M.hstack(*p_cols), M.diag(*diag) + + +def _fuzzy_positive_definite(M): + positive_diagonals = M._has_positive_diagonals() + if positive_diagonals is False: + return False + + if positive_diagonals and M.is_strongly_diagonally_dominant: + return True + + return None + + +def _fuzzy_positive_semidefinite(M): + nonnegative_diagonals = M._has_nonnegative_diagonals() + if nonnegative_diagonals is False: + return False + + if nonnegative_diagonals and M.is_weakly_diagonally_dominant: + return True + + return None + + +def _is_positive_definite(M): + if not M.is_hermitian: + if not M.is_square: + return False + M = M + M.H + + fuzzy = _fuzzy_positive_definite(M) + if fuzzy is not None: + return fuzzy + + return _is_positive_definite_GE(M) + + +def _is_positive_semidefinite(M): + if not M.is_hermitian: + if not M.is_square: + return False + M = M + M.H + + fuzzy = _fuzzy_positive_semidefinite(M) + if fuzzy is not None: + return fuzzy + + return _is_positive_semidefinite_cholesky(M) + + +def _is_negative_definite(M): + return _is_positive_definite(-M) + + +def _is_negative_semidefinite(M): + return _is_positive_semidefinite(-M) + + +def _is_indefinite(M): + if M.is_hermitian: + eigen = M.eigenvals() + args1 = [x.is_positive for x in eigen.keys()] + any_positive = fuzzy_or(args1) + args2 = [x.is_negative for x in eigen.keys()] + any_negative = fuzzy_or(args2) + + return fuzzy_and([any_positive, any_negative]) + + elif M.is_square: + return (M + M.H).is_indefinite + + return False + + +def _is_positive_definite_GE(M): + """A division-free gaussian elimination method for testing + positive-definiteness.""" + M = M.as_mutable() + size = M.rows + + for i in range(size): + is_positive = M[i, i].is_positive + if is_positive is not True: + return is_positive + for j in range(i+1, size): + M[j, i+1:] = M[i, i] * M[j, i+1:] - M[j, i] * M[i, i+1:] + return True + + +def _is_positive_semidefinite_cholesky(M): + """Uses Cholesky factorization with complete pivoting + + References + ========== + + .. [1] http://eprints.ma.man.ac.uk/1199/1/covered/MIMS_ep2008_116.pdf + + .. [2] https://www.value-at-risk.net/cholesky-factorization/ + """ + M = M.as_mutable() + for k in range(M.rows): + diags = [M[i, i] for i in range(k, M.rows)] + pivot, pivot_val, nonzero, _ = _find_reasonable_pivot(diags) + + if nonzero: + return None + + if pivot is None: + for i in range(k+1, M.rows): + for j in range(k, M.cols): + iszero = M[i, j].is_zero + if iszero is None: + return None + elif iszero is False: + return False + return True + + if M[k, k].is_negative or pivot_val.is_negative: + return False + elif not (M[k, k].is_nonnegative and pivot_val.is_nonnegative): + return None + + if pivot > 0: + M.col_swap(k, k+pivot) + M.row_swap(k, k+pivot) + + M[k, k] = sqrt(M[k, k]) + M[k, k+1:] /= M[k, k] + M[k+1:, k+1:] -= M[k, k+1:].H * M[k, k+1:] + + return M[-1, -1].is_nonnegative + + +_doc_positive_definite = \ + r"""Finds out the definiteness of a matrix. + + Explanation + =========== + + A square real matrix $A$ is: + + - A positive definite matrix if $x^T A x > 0$ + for all non-zero real vectors $x$. + - A positive semidefinite matrix if $x^T A x \geq 0$ + for all non-zero real vectors $x$. + - A negative definite matrix if $x^T A x < 0$ + for all non-zero real vectors $x$. + - A negative semidefinite matrix if $x^T A x \leq 0$ + for all non-zero real vectors $x$. + - An indefinite matrix if there exists non-zero real vectors + $x, y$ with $x^T A x > 0 > y^T A y$. + + A square complex matrix $A$ is: + + - A positive definite matrix if $\text{re}(x^H A x) > 0$ + for all non-zero complex vectors $x$. + - A positive semidefinite matrix if $\text{re}(x^H A x) \geq 0$ + for all non-zero complex vectors $x$. + - A negative definite matrix if $\text{re}(x^H A x) < 0$ + for all non-zero complex vectors $x$. + - A negative semidefinite matrix if $\text{re}(x^H A x) \leq 0$ + for all non-zero complex vectors $x$. + - An indefinite matrix if there exists non-zero complex vectors + $x, y$ with $\text{re}(x^H A x) > 0 > \text{re}(y^H A y)$. + + A matrix need not be symmetric or hermitian to be positive definite. + + - A real non-symmetric matrix is positive definite if and only if + $\frac{A + A^T}{2}$ is positive definite. + - A complex non-hermitian matrix is positive definite if and only if + $\frac{A + A^H}{2}$ is positive definite. + + And this extension can apply for all the definitions above. + + However, for complex cases, you can restrict the definition of + $\text{re}(x^H A x) > 0$ to $x^H A x > 0$ and require the matrix + to be hermitian. + But we do not present this restriction for computation because you + can check ``M.is_hermitian`` independently with this and use + the same procedure. + + Examples + ======== + + An example of symmetric positive definite matrix: + + .. plot:: + :context: reset + :format: doctest + :include-source: True + + >>> from sympy import Matrix, symbols + >>> from sympy.plotting import plot3d + >>> a, b = symbols('a b') + >>> x = Matrix([a, b]) + + >>> A = Matrix([[1, 0], [0, 1]]) + >>> A.is_positive_definite + True + >>> A.is_positive_semidefinite + True + + >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) + + An example of symmetric positive semidefinite matrix: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> A = Matrix([[1, -1], [-1, 1]]) + >>> A.is_positive_definite + False + >>> A.is_positive_semidefinite + True + + >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) + + An example of symmetric negative definite matrix: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> A = Matrix([[-1, 0], [0, -1]]) + >>> A.is_negative_definite + True + >>> A.is_negative_semidefinite + True + >>> A.is_indefinite + False + + >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) + + An example of symmetric indefinite matrix: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> A = Matrix([[1, 2], [2, -1]]) + >>> A.is_indefinite + True + + >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) + + An example of non-symmetric positive definite matrix. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> A = Matrix([[1, 2], [-2, 1]]) + >>> A.is_positive_definite + True + >>> A.is_positive_semidefinite + True + + >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1)) + + Notes + ===== + + Although some people trivialize the definition of positive definite + matrices only for symmetric or hermitian matrices, this restriction + is not correct because it does not classify all instances of + positive definite matrices from the definition $x^T A x > 0$ or + $\text{re}(x^H A x) > 0$. + + For instance, ``Matrix([[1, 2], [-2, 1]])`` presented in + the example above is an example of real positive definite matrix + that is not symmetric. + + However, since the following formula holds true; + + .. math:: + \text{re}(x^H A x) > 0 \iff + \text{re}(x^H \frac{A + A^H}{2} x) > 0 + + We can classify all positive definite matrices that may or may not + be symmetric or hermitian by transforming the matrix to + $\frac{A + A^T}{2}$ or $\frac{A + A^H}{2}$ + (which is guaranteed to be always real symmetric or complex + hermitian) and we can defer most of the studies to symmetric or + hermitian positive definite matrices. + + But it is a different problem for the existence of Cholesky + decomposition. Because even though a non symmetric or a non + hermitian matrix can be positive definite, Cholesky or LDL + decomposition does not exist because the decompositions require the + matrix to be symmetric or hermitian. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Definiteness_of_a_matrix#Eigenvalues + + .. [2] https://mathworld.wolfram.com/PositiveDefiniteMatrix.html + + .. [3] Johnson, C. R. "Positive Definite Matrices." Amer. + Math. Monthly 77, 259-264 1970. + """ + +_is_positive_definite.__doc__ = _doc_positive_definite +_is_positive_semidefinite.__doc__ = _doc_positive_definite +_is_negative_definite.__doc__ = _doc_positive_definite +_is_negative_semidefinite.__doc__ = _doc_positive_definite +_is_indefinite.__doc__ = _doc_positive_definite + + +def _jordan_form(M, calc_transform=True, *, chop=False): + """Return $(P, J)$ where $J$ is a Jordan block + matrix and $P$ is a matrix such that $M = P J P^{-1}$ + + Parameters + ========== + + calc_transform : bool + If ``False``, then only $J$ is returned. + + chop : bool + All matrices are converted to exact types when computing + eigenvalues and eigenvectors. As a result, there may be + approximation errors. If ``chop==True``, these errors + will be truncated. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[ 6, 5, -2, -3], [-3, -1, 3, 3], [ 2, 1, -2, -3], [-1, 1, 5, 5]]) + >>> P, J = M.jordan_form() + >>> J + Matrix([ + [2, 1, 0, 0], + [0, 2, 0, 0], + [0, 0, 2, 1], + [0, 0, 0, 2]]) + + See Also + ======== + + jordan_block + """ + + if not M.is_square: + raise NonSquareMatrixError("Only square matrices have Jordan forms") + + mat = M + has_floats = M.has(Float) + + if has_floats: + try: + max_prec = max(term._prec for term in M.values() if isinstance(term, Float)) + except ValueError: + # if no term in the matrix is explicitly a Float calling max() + # will throw a error so setting max_prec to default value of 53 + max_prec = 53 + + # setting minimum max_dps to 15 to prevent loss of precision in + # matrix containing non evaluated expressions + max_dps = max(prec_to_dps(max_prec), 15) + + def restore_floats(*args): + """If ``has_floats`` is `True`, cast all ``args`` as + matrices of floats.""" + + if has_floats: + args = [m.evalf(n=max_dps, chop=chop) for m in args] + if len(args) == 1: + return args[0] + + return args + + # cache calculations for some speedup + mat_cache = {} + + def eig_mat(val, pow): + """Cache computations of ``(M - val*I)**pow`` for quick + retrieval""" + + if (val, pow) in mat_cache: + return mat_cache[(val, pow)] + + if (val, pow - 1) in mat_cache: + mat_cache[(val, pow)] = mat_cache[(val, pow - 1)].multiply( + mat_cache[(val, 1)], dotprodsimp=None) + else: + mat_cache[(val, pow)] = (mat - val*M.eye(M.rows)).pow(pow) + + return mat_cache[(val, pow)] + + # helper functions + def nullity_chain(val, algebraic_multiplicity): + """Calculate the sequence [0, nullity(E), nullity(E**2), ...] + until it is constant where ``E = M - val*I``""" + + # mat.rank() is faster than computing the null space, + # so use the rank-nullity theorem + cols = M.cols + ret = [0] + nullity = cols - eig_mat(val, 1).rank() + i = 2 + + while nullity != ret[-1]: + ret.append(nullity) + + if nullity == algebraic_multiplicity: + break + + nullity = cols - eig_mat(val, i).rank() + i += 1 + + # Due to issues like #7146 and #15872, SymPy sometimes + # gives the wrong rank. In this case, raise an error + # instead of returning an incorrect matrix + if nullity < ret[-1] or nullity > algebraic_multiplicity: + raise MatrixError( + "SymPy had encountered an inconsistent " + "result while computing Jordan block: " + "{}".format(M)) + + return ret + + def blocks_from_nullity_chain(d): + """Return a list of the size of each Jordan block. + If d_n is the nullity of E**n, then the number + of Jordan blocks of size n is + + 2*d_n - d_(n-1) - d_(n+1)""" + + # d[0] is always the number of columns, so skip past it + mid = [2*d[n] - d[n - 1] - d[n + 1] for n in range(1, len(d) - 1)] + # d is assumed to plateau with "d[ len(d) ] == d[-1]", so + # 2*d_n - d_(n-1) - d_(n+1) == d_n - d_(n-1) + end = [d[-1] - d[-2]] if len(d) > 1 else [d[0]] + + return mid + end + + def pick_vec(small_basis, big_basis): + """Picks a vector from big_basis that isn't in + the subspace spanned by small_basis""" + + if len(small_basis) == 0: + return big_basis[0] + + for v in big_basis: + _, pivots = M.hstack(*(small_basis + [v])).echelon_form( + with_pivots=True) + + if pivots[-1] == len(small_basis): + return v + + # roots doesn't like Floats, so replace them with Rationals + if has_floats: + from sympy.simplify import nsimplify + mat = mat.applyfunc(lambda x: nsimplify(x, rational=True)) + + # first calculate the jordan block structure + eigs = mat.eigenvals() + + # Make sure that we have all roots in radical form + for x in eigs: + if x.has(CRootOf): + raise MatrixError( + "Jordan normal form is not implemented if the matrix have " + "eigenvalues in CRootOf form") + + # most matrices have distinct eigenvalues + # and so are diagonalizable. In this case, don't + # do extra work! + if len(eigs.keys()) == mat.cols: + blocks = sorted(eigs.keys(), key=default_sort_key) + jordan_mat = mat.diag(*blocks) + + if not calc_transform: + return restore_floats(jordan_mat) + + jordan_basis = [eig_mat(eig, 1).nullspace()[0] + for eig in blocks] + basis_mat = mat.hstack(*jordan_basis) + + return restore_floats(basis_mat, jordan_mat) + + block_structure = [] + + for eig in sorted(eigs.keys(), key=default_sort_key): + algebraic_multiplicity = eigs[eig] + chain = nullity_chain(eig, algebraic_multiplicity) + block_sizes = blocks_from_nullity_chain(chain) + + # if block_sizes = = [a, b, c, ...], then the number of + # Jordan blocks of size 1 is a, of size 2 is b, etc. + # create an array that has (eig, block_size) with one + # entry for each block + size_nums = [(i+1, num) for i, num in enumerate(block_sizes)] + + # we expect larger Jordan blocks to come earlier + size_nums.reverse() + + block_structure.extend( + [(eig, size) for size, num in size_nums for _ in range(num)]) + + jordan_form_size = sum(size for eig, size in block_structure) + + if jordan_form_size != M.rows: + raise MatrixError( + "SymPy had encountered an inconsistent result while " + "computing Jordan block. : {}".format(M)) + + blocks = (mat.jordan_block(size=size, eigenvalue=eig) for eig, size in block_structure) + jordan_mat = mat.diag(*blocks) + + if not calc_transform: + return restore_floats(jordan_mat) + + # For each generalized eigenspace, calculate a basis. + # We start by looking for a vector in null( (A - eig*I)**n ) + # which isn't in null( (A - eig*I)**(n-1) ) where n is + # the size of the Jordan block + # + # Ideally we'd just loop through block_structure and + # compute each generalized eigenspace. However, this + # causes a lot of unneeded computation. Instead, we + # go through the eigenvalues separately, since we know + # their generalized eigenspaces must have bases that + # are linearly independent. + jordan_basis = [] + + for eig in sorted(eigs.keys(), key=default_sort_key): + eig_basis = [] + + for block_eig, size in block_structure: + if block_eig != eig: + continue + + null_big = (eig_mat(eig, size)).nullspace() + null_small = (eig_mat(eig, size - 1)).nullspace() + + # we want to pick something that is in the big basis + # and not the small, but also something that is independent + # of any other generalized eigenvectors from a different + # generalized eigenspace sharing the same eigenvalue. + vec = pick_vec(null_small + eig_basis, null_big) + new_vecs = [eig_mat(eig, i).multiply(vec, dotprodsimp=None) + for i in range(size)] + + eig_basis.extend(new_vecs) + jordan_basis.extend(reversed(new_vecs)) + + basis_mat = mat.hstack(*jordan_basis) + + return restore_floats(basis_mat, jordan_mat) + + +def _left_eigenvects(M, **flags): + """Returns left eigenvectors and eigenvalues. + + This function returns the list of triples (eigenval, multiplicity, + basis) for the left eigenvectors. Options are the same as for + eigenvects(), i.e. the ``**flags`` arguments gets passed directly to + eigenvects(). + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) + >>> M.eigenvects() + [(-1, 1, [Matrix([ + [-1], + [ 1], + [ 0]])]), (0, 1, [Matrix([ + [ 0], + [-1], + [ 1]])]), (2, 1, [Matrix([ + [2/3], + [1/3], + [ 1]])])] + >>> M.left_eigenvects() + [(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2, + 1, [Matrix([[1, 1, 1]])])] + + """ + + eigs = M.transpose().eigenvects(**flags) + + return [(val, mult, [l.transpose() for l in basis]) for val, mult, basis in eigs] + + +def _singular_values(M): + """Compute the singular values of a Matrix + + Examples + ======== + + >>> from sympy import Matrix, Symbol + >>> x = Symbol('x', real=True) + >>> M = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]]) + >>> M.singular_values() + [sqrt(x**2 + 1), 1, 0] + + See Also + ======== + + condition_number + """ + + if M.rows >= M.cols: + valmultpairs = M.H.multiply(M).eigenvals() + else: + valmultpairs = M.multiply(M.H).eigenvals() + + # Expands result from eigenvals into a simple list + vals = [] + + for k, v in valmultpairs.items(): + vals += [sqrt(k)] * v # dangerous! same k in several spots! + + # Pad with zeros if singular values are computed in reverse way, + # to give consistent format. + if len(vals) < M.cols: + vals += [M.zero] * (M.cols - len(vals)) + + # sort them in descending order + vals.sort(reverse=True, key=default_sort_key) + + return vals diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc7cfa0bdffd59ff2bc5a9cd85cf9b04ed1a63d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/exceptions.py @@ -0,0 +1,26 @@ +""" +Exceptions raised by the matrix module. +""" + + +class MatrixError(Exception): + pass + + +class ShapeError(ValueError, MatrixError): + """Wrong matrix shape""" + pass + + +class NonSquareMatrixError(ShapeError): + pass + + +class NonInvertibleMatrixError(ValueError, MatrixError): + """The matrix in not invertible (division by multidimensional zero error).""" + pass + + +class NonPositiveDefiniteMatrixError(ValueError, MatrixError): + """The matrix is not a positive-definite matrix.""" + pass diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4ab203ab74165d1003cdedd83945ea3fcf8f47 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py @@ -0,0 +1,62 @@ +""" A module which handles Matrix Expressions """ + +from .slice import MatrixSlice +from .blockmatrix import BlockMatrix, BlockDiagMatrix, block_collapse, blockcut +from .companion import CompanionMatrix +from .funcmatrix import FunctionMatrix +from .inverse import Inverse +from .matadd import MatAdd +from .matexpr import MatrixExpr, MatrixSymbol, matrix_symbols +from .matmul import MatMul +from .matpow import MatPow +from .trace import Trace, trace +from .determinant import Determinant, det, Permanent, per +from .transpose import Transpose +from .adjoint import Adjoint +from .hadamard import hadamard_product, HadamardProduct, hadamard_power, HadamardPower +from .diagonal import DiagonalMatrix, DiagonalOf, DiagMatrix, diagonalize_vector +from .dotproduct import DotProduct +from .kronecker import kronecker_product, KroneckerProduct, combine_kronecker +from .permutation import PermutationMatrix, MatrixPermute +from .sets import MatrixSet +from .special import ZeroMatrix, Identity, OneMatrix + +__all__ = [ + 'MatrixSlice', + + 'BlockMatrix', 'BlockDiagMatrix', 'block_collapse', 'blockcut', + 'FunctionMatrix', + + 'CompanionMatrix', + + 'Inverse', + + 'MatAdd', + + 'Identity', 'MatrixExpr', 'MatrixSymbol', 'ZeroMatrix', 'OneMatrix', + 'matrix_symbols', 'MatrixSet', + + 'MatMul', + + 'MatPow', + + 'Trace', 'trace', + + 'Determinant', 'det', + + 'Transpose', + + 'Adjoint', + + 'hadamard_product', 'HadamardProduct', 'hadamard_power', 'HadamardPower', + + 'DiagonalMatrix', 'DiagonalOf', 'DiagMatrix', 'diagonalize_vector', + + 'DotProduct', + + 'kronecker_product', 'KroneckerProduct', 'combine_kronecker', + + 'PermutationMatrix', 'MatrixPermute', + + 'Permanent', 'per' +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73e40cefe8c2f9b64bac479abbdf360b06aaec5e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/_shape.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/_shape.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3285144adaddd3b40ba8542d3bfe254b680f506b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/_shape.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/adjoint.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/adjoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fbeaeb5d7add98cdff60cea3dd95fd2bb191a0b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/adjoint.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/blockmatrix.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/blockmatrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16b7b6255be4908fcfb84d37a7f9503765bc862a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/blockmatrix.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/companion.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/companion.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..143c87e2f8dd623bd3b7fd0740b466ac3f4a90a7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/companion.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/determinant.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/determinant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e1ade2ffab8ccca9457e47136f881f2c0d51e3a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/determinant.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/funcmatrix.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/funcmatrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edfa33c95dc956b0ceaade55a616594e3297c748 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/funcmatrix.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/hadamard.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/hadamard.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47ff917f8b6b68f6251aedd5299eacad440f1543 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/hadamard.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/inverse.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/inverse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfccf00596ee5e3130bd64bd7c7c5869e19bfdd2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/inverse.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matadd.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matadd.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3263fba4e71568e7c0eb45745af47595ef1332aa Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matadd.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matexpr.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matexpr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccdd516a5b0a506144b7b5ba53e2e264f8f0aa0c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matexpr.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matmul.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matmul.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d641415ff2c9c2c2e9184fbbe82f1109b7161897 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matmul.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matpow.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matpow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0994826409a64a38c763d8fb83db95ee6654bca Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matpow.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/permutation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/permutation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..247c426af967491960962637250610a945c05db7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/permutation.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/sets.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/sets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b7dbe743d09ca52c6d22e32a803608921f8ff53 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/sets.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/slice.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/slice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd9a6c2384e1a673803ac44ba07a30cd62aecd67 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/slice.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/special.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/special.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4f83f49a20233a88bb38ee833b3d9a5c471450c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/special.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/trace.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/trace.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2489d67d8be6d0a102a4268a24891cb1e43025e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/trace.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/transpose.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/transpose.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a62af9b4dba11f7881021966127a479f05727e8f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/transpose.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..a95d481bf8e1edf4c62992044cd50563b335caac --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py @@ -0,0 +1,102 @@ +from sympy.core.relational import Eq +from sympy.core.expr import Expr +from sympy.core.numbers import Integer +from sympy.logic.boolalg import Boolean, And +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.exceptions import ShapeError +from typing import Union + + +def is_matadd_valid(*args: MatrixExpr) -> Boolean: + """Return the symbolic condition how ``MatAdd``, ``HadamardProduct`` + makes sense. + + Parameters + ========== + + args + The list of arguments of matrices to be tested for. + + Examples + ======== + + >>> from sympy import MatrixSymbol, symbols + >>> from sympy.matrices.expressions._shape import is_matadd_valid + + >>> m, n, p, q = symbols('m n p q') + >>> A = MatrixSymbol('A', m, n) + >>> B = MatrixSymbol('B', p, q) + >>> is_matadd_valid(A, B) + Eq(m, p) & Eq(n, q) + """ + rows, cols = zip(*(arg.shape for arg in args)) + return And( + *(Eq(i, j) for i, j in zip(rows[:-1], rows[1:])), + *(Eq(i, j) for i, j in zip(cols[:-1], cols[1:])), + ) + + +def is_matmul_valid(*args: Union[MatrixExpr, Expr]) -> Boolean: + """Return the symbolic condition how ``MatMul`` makes sense + + Parameters + ========== + + args + The list of arguments of matrices and scalar expressions to be tested + for. + + Examples + ======== + + >>> from sympy import MatrixSymbol, symbols + >>> from sympy.matrices.expressions._shape import is_matmul_valid + + >>> m, n, p, q = symbols('m n p q') + >>> A = MatrixSymbol('A', m, n) + >>> B = MatrixSymbol('B', p, q) + >>> is_matmul_valid(A, B) + Eq(n, p) + """ + rows, cols = zip(*(arg.shape for arg in args if isinstance(arg, MatrixExpr))) + return And(*(Eq(i, j) for i, j in zip(cols[:-1], rows[1:]))) + + +def is_square(arg: MatrixExpr, /) -> Boolean: + """Return the symbolic condition how the matrix is assumed to be square + + Parameters + ========== + + arg + The matrix to be tested for. + + Examples + ======== + + >>> from sympy import MatrixSymbol, symbols + >>> from sympy.matrices.expressions._shape import is_square + + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', m, n) + >>> is_square(A) + Eq(m, n) + """ + return Eq(arg.rows, arg.cols) + + +def validate_matadd_integer(*args: MatrixExpr) -> None: + """Validate matrix shape for addition only for integer values""" + rows, cols = zip(*(x.shape for x in args)) + if len(set(filter(lambda x: isinstance(x, (int, Integer)), rows))) > 1: + raise ShapeError(f"Matrices have mismatching shape: {rows}") + if len(set(filter(lambda x: isinstance(x, (int, Integer)), cols))) > 1: + raise ShapeError(f"Matrices have mismatching shape: {cols}") + + +def validate_matmul_integer(*args: MatrixExpr) -> None: + """Validate matrix shape for multiplication only for integer values""" + for A, B in zip(args[:-1], args[1:]): + i, j = A.cols, B.rows + if isinstance(i, (int, Integer)) and isinstance(j, (int, Integer)) and i != j: + raise ShapeError("Matrices are not aligned", i, j) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py new file mode 100644 index 0000000000000000000000000000000000000000..2039a7b2eb8eeacb02435979121c4133a11d8e02 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py @@ -0,0 +1,60 @@ +from sympy.core import Basic +from sympy.functions import adjoint, conjugate +from sympy.matrices.expressions.matexpr import MatrixExpr + + +class Adjoint(MatrixExpr): + """ + The Hermitian adjoint of a matrix expression. + + This is a symbolic object that simply stores its argument without + evaluating it. To actually compute the adjoint, use the ``adjoint()`` + function. + + Examples + ======== + + >>> from sympy import MatrixSymbol, Adjoint, adjoint + >>> A = MatrixSymbol('A', 3, 5) + >>> B = MatrixSymbol('B', 5, 3) + >>> Adjoint(A*B) + Adjoint(A*B) + >>> adjoint(A*B) + Adjoint(B)*Adjoint(A) + >>> adjoint(A*B) == Adjoint(A*B) + False + >>> adjoint(A*B) == Adjoint(A*B).doit() + True + """ + is_Adjoint = True + + def doit(self, **hints): + arg = self.arg + if hints.get('deep', True) and isinstance(arg, Basic): + return adjoint(arg.doit(**hints)) + else: + return adjoint(self.arg) + + @property + def arg(self): + return self.args[0] + + @property + def shape(self): + return self.arg.shape[::-1] + + def _entry(self, i, j, **kwargs): + return conjugate(self.arg._entry(j, i, **kwargs)) + + def _eval_adjoint(self): + return self.arg + + def _eval_transpose(self): + return self.arg.conjugate() + + def _eval_conjugate(self): + return self.arg.transpose() + + def _eval_trace(self): + from sympy.matrices.expressions.trace import Trace + return conjugate(Trace(self.arg)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..c0363658447a8dc37a152b30e45533bac582b10c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py @@ -0,0 +1,204 @@ +from sympy.core.expr import ExprBuilder +from sympy.core.function import (Function, FunctionClass, Lambda) +from sympy.core.symbol import Dummy +from sympy.core.sympify import sympify, _sympify +from sympy.matrices.expressions import MatrixExpr +from sympy.matrices.matrixbase import MatrixBase + + +class ElementwiseApplyFunction(MatrixExpr): + r""" + Apply function to a matrix elementwise without evaluating. + + Examples + ======== + + It can be created by calling ``.applyfunc()`` on a matrix + expression: + + >>> from sympy import MatrixSymbol + >>> from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction + >>> from sympy import exp + >>> X = MatrixSymbol("X", 3, 3) + >>> X.applyfunc(exp) + Lambda(_d, exp(_d)).(X) + + Otherwise using the class constructor: + + >>> from sympy import eye + >>> expr = ElementwiseApplyFunction(exp, eye(3)) + >>> expr + Lambda(_d, exp(_d)).(Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]])) + >>> expr.doit() + Matrix([ + [E, 1, 1], + [1, E, 1], + [1, 1, E]]) + + Notice the difference with the real mathematical functions: + + >>> exp(eye(3)) + Matrix([ + [E, 0, 0], + [0, E, 0], + [0, 0, E]]) + """ + + def __new__(cls, function, expr): + expr = _sympify(expr) + if not expr.is_Matrix: + raise ValueError("{} must be a matrix instance.".format(expr)) + + if expr.shape == (1, 1): + # Check if the function returns a matrix, in that case, just apply + # the function instead of creating an ElementwiseApplyFunc object: + ret = function(expr) + if isinstance(ret, MatrixExpr): + return ret + + if not isinstance(function, (FunctionClass, Lambda)): + d = Dummy('d') + function = Lambda(d, function(d)) + + function = sympify(function) + if not isinstance(function, (FunctionClass, Lambda)): + raise ValueError( + "{} should be compatible with SymPy function classes." + .format(function)) + + if 1 not in function.nargs: + raise ValueError( + '{} should be able to accept 1 arguments.'.format(function)) + + if not isinstance(function, Lambda): + d = Dummy('d') + function = Lambda(d, function(d)) + + obj = MatrixExpr.__new__(cls, function, expr) + return obj + + @property + def function(self): + return self.args[0] + + @property + def expr(self): + return self.args[1] + + @property + def shape(self): + return self.expr.shape + + def doit(self, **hints): + deep = hints.get("deep", True) + expr = self.expr + if deep: + expr = expr.doit(**hints) + function = self.function + if isinstance(function, Lambda) and function.is_identity: + # This is a Lambda containing the identity function. + return expr + if isinstance(expr, MatrixBase): + return expr.applyfunc(self.function) + elif isinstance(expr, ElementwiseApplyFunction): + return ElementwiseApplyFunction( + lambda x: self.function(expr.function(x)), + expr.expr + ).doit(**hints) + else: + return self + + def _entry(self, i, j, **kwargs): + return self.function(self.expr._entry(i, j, **kwargs)) + + def _get_function_fdiff(self): + d = Dummy("d") + function = self.function(d) + fdiff = function.diff(d) + if isinstance(fdiff, Function): + fdiff = type(fdiff) + else: + fdiff = Lambda(d, fdiff) + return fdiff + + def _eval_derivative(self, x): + from sympy.matrices.expressions.hadamard import hadamard_product + dexpr = self.expr.diff(x) + fdiff = self._get_function_fdiff() + return hadamard_product( + dexpr, + ElementwiseApplyFunction(fdiff, self.expr) + ) + + def _eval_derivative_matrix_lines(self, x): + from sympy.matrices.expressions.special import Identity + from sympy.tensor.array.expressions.array_expressions import ArrayContraction + from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal + from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct + + fdiff = self._get_function_fdiff() + lr = self.expr._eval_derivative_matrix_lines(x) + ewdiff = ElementwiseApplyFunction(fdiff, self.expr) + if 1 in x.shape: + # Vector: + iscolumn = self.shape[1] == 1 + for i in lr: + if iscolumn: + ptr1 = i.first_pointer + ptr2 = Identity(self.shape[1]) + else: + ptr1 = Identity(self.shape[0]) + ptr2 = i.second_pointer + + subexpr = ExprBuilder( + ArrayDiagonal, + [ + ExprBuilder( + ArrayTensorProduct, + [ + ewdiff, + ptr1, + ptr2, + ] + ), + (0, 2) if iscolumn else (1, 4) + ], + validator=ArrayDiagonal._validate + ) + i._lines = [subexpr] + i._first_pointer_parent = subexpr.args[0].args + i._first_pointer_index = 1 + i._second_pointer_parent = subexpr.args[0].args + i._second_pointer_index = 2 + else: + # Matrix case: + for i in lr: + ptr1 = i.first_pointer + ptr2 = i.second_pointer + newptr1 = Identity(ptr1.shape[1]) + newptr2 = Identity(ptr2.shape[1]) + subexpr = ExprBuilder( + ArrayContraction, + [ + ExprBuilder( + ArrayTensorProduct, + [ptr1, newptr1, ewdiff, ptr2, newptr2] + ), + (1, 2, 4), + (5, 7, 8), + ], + validator=ArrayContraction._validate + ) + i._first_pointer_parent = subexpr.args[0].args + i._first_pointer_index = 1 + i._second_pointer_parent = subexpr.args[0].args + i._second_pointer_index = 4 + i._lines = [subexpr] + return lr + + def _eval_transpose(self): + from sympy.matrices.expressions.transpose import Transpose + return self.func(self.function, Transpose(self.expr).doit()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..0125d6233ba7cf8c0b590fbb655d9c7c447e0bd4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py @@ -0,0 +1,975 @@ +from sympy.assumptions.ask import (Q, ask) +from sympy.core import Basic, Add, Mul, S +from sympy.core.sympify import _sympify +from sympy.functions.elementary.complexes import re, im +from sympy.strategies import typed, exhaust, condition, do_one, unpack +from sympy.strategies.traverse import bottom_up +from sympy.utilities.iterables import is_sequence, sift +from sympy.utilities.misc import filldedent + +from sympy.matrices import Matrix, ShapeError +from sympy.matrices.exceptions import NonInvertibleMatrixError +from sympy.matrices.expressions.determinant import det, Determinant +from sympy.matrices.expressions.inverse import Inverse +from sympy.matrices.expressions.matadd import MatAdd +from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement +from sympy.matrices.expressions.matmul import MatMul +from sympy.matrices.expressions.matpow import MatPow +from sympy.matrices.expressions.slice import MatrixSlice +from sympy.matrices.expressions.special import ZeroMatrix, Identity +from sympy.matrices.expressions.trace import trace +from sympy.matrices.expressions.transpose import Transpose, transpose + + +class BlockMatrix(MatrixExpr): + """A BlockMatrix is a Matrix comprised of other matrices. + + The submatrices are stored in a SymPy Matrix object but accessed as part of + a Matrix Expression + + >>> from sympy import (MatrixSymbol, BlockMatrix, symbols, + ... Identity, ZeroMatrix, block_collapse) + >>> n,m,l = symbols('n m l') + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> Z = MatrixSymbol('Z', n, m) + >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) + >>> print(B) + Matrix([ + [X, Z], + [0, Y]]) + + >>> C = BlockMatrix([[Identity(n), Z]]) + >>> print(C) + Matrix([[I, Z]]) + + >>> print(block_collapse(C*B)) + Matrix([[X, Z + Z*Y]]) + + Some matrices might be comprised of rows of blocks with + the matrices in each row having the same height and the + rows all having the same total number of columns but + not having the same number of columns for each matrix + in each row. In this case, the matrix is not a block + matrix and should be instantiated by Matrix. + + >>> from sympy import ones, Matrix + >>> dat = [ + ... [ones(3,2), ones(3,3)*2], + ... [ones(2,3)*3, ones(2,2)*4]] + ... + >>> BlockMatrix(dat) + Traceback (most recent call last): + ... + ValueError: + Although this matrix is comprised of blocks, the blocks do not fill + the matrix in a size-symmetric fashion. To create a full matrix from + these arguments, pass them directly to Matrix. + >>> Matrix(dat) + Matrix([ + [1, 1, 2, 2, 2], + [1, 1, 2, 2, 2], + [1, 1, 2, 2, 2], + [3, 3, 3, 4, 4], + [3, 3, 3, 4, 4]]) + + See Also + ======== + sympy.matrices.matrixbase.MatrixBase.irregular + """ + def __new__(cls, *args, **kwargs): + from sympy.matrices.immutable import ImmutableDenseMatrix + isMat = lambda i: getattr(i, 'is_Matrix', False) + if len(args) != 1 or \ + not is_sequence(args[0]) or \ + len({isMat(r) for r in args[0]}) != 1: + raise ValueError(filldedent(''' + expecting a sequence of 1 or more rows + containing Matrices.''')) + rows = args[0] if args else [] + if not isMat(rows): + if rows and isMat(rows[0]): + rows = [rows] # rows is not list of lists or [] + # regularity check + # same number of matrices in each row + blocky = ok = len({len(r) for r in rows}) == 1 + if ok: + # same number of rows for each matrix in a row + for r in rows: + ok = len({i.rows for i in r}) == 1 + if not ok: + break + blocky = ok + if ok: + # same number of cols for each matrix in each col + for c in range(len(rows[0])): + ok = len({rows[i][c].cols + for i in range(len(rows))}) == 1 + if not ok: + break + if not ok: + # same total cols in each row + ok = len({ + sum(i.cols for i in r) for r in rows}) == 1 + if blocky and ok: + raise ValueError(filldedent(''' + Although this matrix is comprised of blocks, + the blocks do not fill the matrix in a + size-symmetric fashion. To create a full matrix + from these arguments, pass them directly to + Matrix.''')) + raise ValueError(filldedent(''' + When there are not the same number of rows in each + row's matrices or there are not the same number of + total columns in each row, the matrix is not a + block matrix. If this matrix is known to consist of + blocks fully filling a 2-D space then see + Matrix.irregular.''')) + mat = ImmutableDenseMatrix(rows, evaluate=False) + obj = Basic.__new__(cls, mat) + return obj + + @property + def shape(self): + numrows = numcols = 0 + M = self.blocks + for i in range(M.shape[0]): + numrows += M[i, 0].shape[0] + for i in range(M.shape[1]): + numcols += M[0, i].shape[1] + return (numrows, numcols) + + @property + def blockshape(self): + return self.blocks.shape + + @property + def blocks(self): + return self.args[0] + + @property + def rowblocksizes(self): + return [self.blocks[i, 0].rows for i in range(self.blockshape[0])] + + @property + def colblocksizes(self): + return [self.blocks[0, i].cols for i in range(self.blockshape[1])] + + def structurally_equal(self, other): + return (isinstance(other, BlockMatrix) + and self.shape == other.shape + and self.blockshape == other.blockshape + and self.rowblocksizes == other.rowblocksizes + and self.colblocksizes == other.colblocksizes) + + def _blockmul(self, other): + if (isinstance(other, BlockMatrix) and + self.colblocksizes == other.rowblocksizes): + return BlockMatrix(self.blocks*other.blocks) + + return self * other + + def _blockadd(self, other): + if (isinstance(other, BlockMatrix) + and self.structurally_equal(other)): + return BlockMatrix(self.blocks + other.blocks) + + return self + other + + def _eval_transpose(self): + # Flip all the individual matrices + matrices = [transpose(matrix) for matrix in self.blocks] + # Make a copy + M = Matrix(self.blockshape[0], self.blockshape[1], matrices) + # Transpose the block structure + M = M.transpose() + return BlockMatrix(M) + + def _eval_adjoint(self): + return BlockMatrix( + Matrix(self.blockshape[0], self.blockshape[1], self.blocks).adjoint() + ) + + def _eval_trace(self): + if self.rowblocksizes == self.colblocksizes: + blocks = [self.blocks[i, i] for i in range(self.blockshape[0])] + return Add(*[trace(block) for block in blocks]) + + def _eval_determinant(self): + if self.blockshape == (1, 1): + return det(self.blocks[0, 0]) + if self.blockshape == (2, 2): + [[A, B], + [C, D]] = self.blocks.tolist() + if ask(Q.invertible(A)): + return det(A)*det(D - C*A.I*B) + elif ask(Q.invertible(D)): + return det(D)*det(A - B*D.I*C) + return Determinant(self) + + def _eval_as_real_imag(self): + real_matrices = [re(matrix) for matrix in self.blocks] + real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices) + + im_matrices = [im(matrix) for matrix in self.blocks] + im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices) + + return (BlockMatrix(real_matrices), BlockMatrix(im_matrices)) + + def _eval_derivative(self, x): + return BlockMatrix(self.blocks.diff(x)) + + def transpose(self): + """Return transpose of matrix. + + Examples + ======== + + >>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix + >>> from sympy.abc import m, n + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> Z = MatrixSymbol('Z', n, m) + >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) + >>> B.transpose() + Matrix([ + [X.T, 0], + [Z.T, Y.T]]) + >>> _.transpose() + Matrix([ + [X, Z], + [0, Y]]) + """ + return self._eval_transpose() + + def schur(self, mat = 'A', generalized = False): + """Return the Schur Complement of the 2x2 BlockMatrix + + Parameters + ========== + + mat : String, optional + The matrix with respect to which the + Schur Complement is calculated. 'A' is + used by default + + generalized : bool, optional + If True, returns the generalized Schur + Component which uses Moore-Penrose Inverse + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + + The default Schur Complement is evaluated with "A" + + >>> X.schur() + -C*A**(-1)*B + D + >>> X.schur('D') + A - B*D**(-1)*C + + Schur complement with non-invertible matrices is not + defined. Instead, the generalized Schur complement can + be calculated which uses the Moore-Penrose Inverse. To + achieve this, `generalized` must be set to `True` + + >>> X.schur('B', generalized=True) + C - D*(B.T*B)**(-1)*B.T*A + >>> X.schur('C', generalized=True) + -A*(C.T*C)**(-1)*C.T*D + B + + Returns + ======= + + M : Matrix + The Schur Complement Matrix + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If given matrix is non-invertible + + References + ========== + + .. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.pinv + """ + + if self.blockshape == (2, 2): + [[A, B], + [C, D]] = self.blocks.tolist() + d={'A' : A, 'B' : B, 'C' : C, 'D' : D} + try: + inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv() + if mat == 'A': + return D - C * inv * B + elif mat == 'B': + return C - D * inv * A + elif mat == 'C': + return B - A * inv * D + elif mat == 'D': + return A - B * inv * C + #For matrices where no sub-matrix is square + return self + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \ + to compute the generalized Schur Complement which uses Moore-Penrose Inverse') + else: + raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices') + + def LDUdecomposition(self): + """Returns the Block LDU decomposition of + a 2x2 Block Matrix + + Returns + ======= + + (L, D, U) : Matrices + L : Lower Diagonal Matrix + D : Diagonal Matrix + U : Upper Diagonal Matrix + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + >>> L, D, U = X.LDUdecomposition() + >>> block_collapse(L*D*U) + Matrix([ + [A, B], + [C, D]]) + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If the matrix "A" is non-invertible + + See Also + ======== + sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition + sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition + """ + if self.blockshape == (2,2): + [[A, B], + [C, D]] = self.blocks.tolist() + try: + AI = A.I + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\ + "A" is singular') + Ip = Identity(B.shape[0]) + Iq = Identity(B.shape[1]) + Z = ZeroMatrix(*B.shape) + L = BlockMatrix([[Ip, Z], [C*AI, Iq]]) + D = BlockDiagMatrix(A, self.schur()) + U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]]) + return L, D, U + else: + raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices") + + def UDLdecomposition(self): + """Returns the Block UDL decomposition of + a 2x2 Block Matrix + + Returns + ======= + + (U, D, L) : Matrices + U : Upper Diagonal Matrix + D : Diagonal Matrix + L : Lower Diagonal Matrix + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + >>> U, D, L = X.UDLdecomposition() + >>> block_collapse(U*D*L) + Matrix([ + [A, B], + [C, D]]) + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If the matrix "D" is non-invertible + + See Also + ======== + sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition + sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition + """ + if self.blockshape == (2,2): + [[A, B], + [C, D]] = self.blocks.tolist() + try: + DI = D.I + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\ + "D" is singular') + Ip = Identity(A.shape[0]) + Iq = Identity(B.shape[1]) + Z = ZeroMatrix(*B.shape) + U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]]) + D = BlockDiagMatrix(self.schur('D'), D) + L = BlockMatrix([[Ip, Z],[DI*C, Iq]]) + return U, D, L + else: + raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices") + + def LUdecomposition(self): + """Returns the Block LU decomposition of + a 2x2 Block Matrix + + Returns + ======= + + (L, U) : Matrices + L : Lower Diagonal Matrix + U : Upper Diagonal Matrix + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + >>> L, U = X.LUdecomposition() + >>> block_collapse(L*U) + Matrix([ + [A, B], + [C, D]]) + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If the matrix "A" is non-invertible + + See Also + ======== + sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition + sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition + """ + if self.blockshape == (2,2): + [[A, B], + [C, D]] = self.blocks.tolist() + try: + A = A**S.Half + AI = A.I + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\ + "A" is singular') + Z = ZeroMatrix(*B.shape) + Q = self.schur()**S.Half + L = BlockMatrix([[A, Z], [C*AI, Q]]) + U = BlockMatrix([[A, AI*B],[Z.T, Q]]) + return L, U + else: + raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices") + + def _entry(self, i, j, **kwargs): + # Find row entry + orig_i, orig_j = i, j + for row_block, numrows in enumerate(self.rowblocksizes): + cmp = i < numrows + if cmp == True: + break + elif cmp == False: + i -= numrows + elif row_block < self.blockshape[0] - 1: + # Can't tell which block and it's not the last one, return unevaluated + return MatrixElement(self, orig_i, orig_j) + for col_block, numcols in enumerate(self.colblocksizes): + cmp = j < numcols + if cmp == True: + break + elif cmp == False: + j -= numcols + elif col_block < self.blockshape[1] - 1: + return MatrixElement(self, orig_i, orig_j) + return self.blocks[row_block, col_block][i, j] + + @property + def is_Identity(self): + if self.blockshape[0] != self.blockshape[1]: + return False + for i in range(self.blockshape[0]): + for j in range(self.blockshape[1]): + if i==j and not self.blocks[i, j].is_Identity: + return False + if i!=j and not self.blocks[i, j].is_ZeroMatrix: + return False + return True + + @property + def is_structurally_symmetric(self): + return self.rowblocksizes == self.colblocksizes + + def equals(self, other): + if self == other: + return True + if (isinstance(other, BlockMatrix) and self.blocks == other.blocks): + return True + return super().equals(other) + + +class BlockDiagMatrix(BlockMatrix): + """A sparse matrix with block matrices along its diagonals + + Examples + ======== + + >>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols + >>> n, m, l = symbols('n m l') + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> BlockDiagMatrix(X, Y) + Matrix([ + [X, 0], + [0, Y]]) + + Notes + ===== + + If you want to get the individual diagonal blocks, use + :meth:`get_diag_blocks`. + + See Also + ======== + + sympy.matrices.dense.diag + """ + def __new__(cls, *mats): + return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats]) + + @property + def diag(self): + return self.args + + @property + def blocks(self): + from sympy.matrices.immutable import ImmutableDenseMatrix + mats = self.args + data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols) + for j in range(len(mats))] + for i in range(len(mats))] + return ImmutableDenseMatrix(data, evaluate=False) + + @property + def shape(self): + return (sum(block.rows for block in self.args), + sum(block.cols for block in self.args)) + + @property + def blockshape(self): + n = len(self.args) + return (n, n) + + @property + def rowblocksizes(self): + return [block.rows for block in self.args] + + @property + def colblocksizes(self): + return [block.cols for block in self.args] + + def _all_square_blocks(self): + """Returns true if all blocks are square""" + return all(mat.is_square for mat in self.args) + + def _eval_determinant(self): + if self._all_square_blocks(): + return Mul(*[det(mat) for mat in self.args]) + # At least one block is non-square. Since the entire matrix must be square we know there must + # be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient + return S.Zero + + def _eval_inverse(self, expand='ignored'): + if self._all_square_blocks(): + return BlockDiagMatrix(*[mat.inverse() for mat in self.args]) + # See comment in _eval_determinant() + raise NonInvertibleMatrixError('Matrix det == 0; not invertible.') + + def _eval_transpose(self): + return BlockDiagMatrix(*[mat.transpose() for mat in self.args]) + + def _blockmul(self, other): + if (isinstance(other, BlockDiagMatrix) and + self.colblocksizes == other.rowblocksizes): + return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)]) + else: + return BlockMatrix._blockmul(self, other) + + def _blockadd(self, other): + if (isinstance(other, BlockDiagMatrix) and + self.blockshape == other.blockshape and + self.rowblocksizes == other.rowblocksizes and + self.colblocksizes == other.colblocksizes): + return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)]) + else: + return BlockMatrix._blockadd(self, other) + + def get_diag_blocks(self): + """Return the list of diagonal blocks of the matrix. + + Examples + ======== + + >>> from sympy import BlockDiagMatrix, Matrix + + >>> A = Matrix([[1, 2], [3, 4]]) + >>> B = Matrix([[5, 6], [7, 8]]) + >>> M = BlockDiagMatrix(A, B) + + How to get diagonal blocks from the block diagonal matrix: + + >>> diag_blocks = M.get_diag_blocks() + >>> diag_blocks[0] + Matrix([ + [1, 2], + [3, 4]]) + >>> diag_blocks[1] + Matrix([ + [5, 6], + [7, 8]]) + """ + return self.args + + +def block_collapse(expr): + """Evaluates a block matrix expression + + >>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, ZeroMatrix, block_collapse + >>> n,m,l = symbols('n m l') + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> Z = MatrixSymbol('Z', n, m) + >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]]) + >>> print(B) + Matrix([ + [X, Z], + [0, Y]]) + + >>> C = BlockMatrix([[Identity(n), Z]]) + >>> print(C) + Matrix([[I, Z]]) + + >>> print(block_collapse(C*B)) + Matrix([[X, Z + Z*Y]]) + """ + from sympy.strategies.util import expr_fns + + hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix) + + conditioned_rl = condition( + hasbm, + typed( + {MatAdd: do_one(bc_matadd, bc_block_plus_ident), + MatMul: do_one(bc_matmul, bc_dist), + MatPow: bc_matmul, + Transpose: bc_transpose, + Inverse: bc_inverse, + BlockMatrix: do_one(bc_unpack, deblock)} + ) + ) + + rule = exhaust( + bottom_up( + exhaust(conditioned_rl), + fns=expr_fns + ) + ) + + result = rule(expr) + doit = getattr(result, 'doit', None) + if doit is not None: + return doit() + else: + return result + +def bc_unpack(expr): + if expr.blockshape == (1, 1): + return expr.blocks[0, 0] + return expr + +def bc_matadd(expr): + args = sift(expr.args, lambda M: isinstance(M, BlockMatrix)) + blocks = args[True] + if not blocks: + return expr + + nonblocks = args[False] + block = blocks[0] + for b in blocks[1:]: + block = block._blockadd(b) + if nonblocks: + return MatAdd(*nonblocks) + block + else: + return block + +def bc_block_plus_ident(expr): + idents = [arg for arg in expr.args if arg.is_Identity] + if not idents: + return expr + + blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)] + if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks) + and blocks[0].is_structurally_symmetric): + block_id = BlockDiagMatrix(*[Identity(k) + for k in blocks[0].rowblocksizes]) + rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)] + return MatAdd(block_id * len(idents), *blocks, *rest).doit() + + return expr + +def bc_dist(expr): + """ Turn a*[X, Y] into [a*X, a*Y] """ + factor, mat = expr.as_coeff_mmul() + if factor == 1: + return expr + + unpacked = unpack(mat) + + if isinstance(unpacked, BlockDiagMatrix): + B = unpacked.diag + new_B = [factor * mat for mat in B] + return BlockDiagMatrix(*new_B) + elif isinstance(unpacked, BlockMatrix): + B = unpacked.blocks + new_B = [ + [factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)] + return BlockMatrix(new_B) + return expr + + +def bc_matmul(expr): + if isinstance(expr, MatPow): + if expr.args[1].is_Integer and expr.args[1] > 0: + factor, matrices = 1, [expr.args[0]]*expr.args[1] + else: + return expr + else: + factor, matrices = expr.as_coeff_matrices() + + i = 0 + while (i+1 < len(matrices)): + A, B = matrices[i:i+2] + if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix): + matrices[i] = A._blockmul(B) + matrices.pop(i+1) + elif isinstance(A, BlockMatrix): + matrices[i] = A._blockmul(BlockMatrix([[B]])) + matrices.pop(i+1) + elif isinstance(B, BlockMatrix): + matrices[i] = BlockMatrix([[A]])._blockmul(B) + matrices.pop(i+1) + else: + i+=1 + return MatMul(factor, *matrices).doit() + +def bc_transpose(expr): + collapse = block_collapse(expr.arg) + return collapse._eval_transpose() + + +def bc_inverse(expr): + if isinstance(expr.arg, BlockDiagMatrix): + return expr.inverse() + + expr2 = blockinverse_1x1(expr) + if expr != expr2: + return expr2 + return blockinverse_2x2(Inverse(reblock_2x2(expr.arg))) + +def blockinverse_1x1(expr): + if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1): + mat = Matrix([[expr.arg.blocks[0].inverse()]]) + return BlockMatrix(mat) + return expr + + +def blockinverse_2x2(expr): + if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2): + # See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou + [[A, B], + [C, D]] = expr.arg.blocks.tolist() + + formula = _choose_2x2_inversion_formula(A, B, C, D) + if formula != None: + MI = expr.arg.schur(formula).I + if formula == 'A': + AI = A.I + return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]]) + if formula == 'B': + BI = B.I + return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]]) + if formula == 'C': + CI = C.I + return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]]) + if formula == 'D': + DI = D.I + return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]]) + + return expr + + +def _choose_2x2_inversion_formula(A, B, C, D): + """ + Assuming [[A, B], [C, D]] would form a valid square block matrix, find + which of the classical 2x2 block matrix inversion formulas would be + best suited. + + Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion + of the given argument or None if the matrix cannot be inverted using + any of those formulas. + """ + # Try to find a known invertible matrix. Note that the Schur complement + # is currently not being considered for this + A_inv = ask(Q.invertible(A)) + if A_inv == True: + return 'A' + B_inv = ask(Q.invertible(B)) + if B_inv == True: + return 'B' + C_inv = ask(Q.invertible(C)) + if C_inv == True: + return 'C' + D_inv = ask(Q.invertible(D)) + if D_inv == True: + return 'D' + # Otherwise try to find a matrix that isn't known to be non-invertible + if A_inv != False: + return 'A' + if B_inv != False: + return 'B' + if C_inv != False: + return 'C' + if D_inv != False: + return 'D' + return None + + +def deblock(B): + """ Flatten a BlockMatrix of BlockMatrices """ + if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix): + return B + wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]]) + bb = B.blocks.applyfunc(wrap) # everything is a block + + try: + MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), []) + for row in range(0, bb.shape[0]): + M = Matrix(bb[row, 0].blocks) + for col in range(1, bb.shape[1]): + M = M.row_join(bb[row, col].blocks) + MM = MM.col_join(M) + + return BlockMatrix(MM) + except ShapeError: + return B + + +def reblock_2x2(expr): + """ + Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If + possible in such a way that the matrix continues to be invertible using the + classical 2x2 block inversion formulas. + """ + if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape): + return expr + + BM = BlockMatrix # for brevity's sake + rowblocks, colblocks = expr.blockshape + blocks = expr.blocks + for i in range(1, rowblocks): + for j in range(1, colblocks): + # try to split rows at i and cols at j + A = bc_unpack(BM(blocks[:i, :j])) + B = bc_unpack(BM(blocks[:i, j:])) + C = bc_unpack(BM(blocks[i:, :j])) + D = bc_unpack(BM(blocks[i:, j:])) + + formula = _choose_2x2_inversion_formula(A, B, C, D) + if formula is not None: + return BlockMatrix([[A, B], [C, D]]) + + # else: nothing worked, just split upper left corner + return BM([[blocks[0, 0], BM(blocks[0, 1:])], + [BM(blocks[1:, 0]), BM(blocks[1:, 1:])]]) + + +def bounds(sizes): + """ Convert sequence of numbers into pairs of low-high pairs + + >>> from sympy.matrices.expressions.blockmatrix import bounds + >>> bounds((1, 10, 50)) + [(0, 1), (1, 11), (11, 61)] + """ + low = 0 + rv = [] + for size in sizes: + rv.append((low, low + size)) + low += size + return rv + +def blockcut(expr, rowsizes, colsizes): + """ Cut a matrix expression into Blocks + + >>> from sympy import ImmutableMatrix, blockcut + >>> M = ImmutableMatrix(4, 4, range(16)) + >>> B = blockcut(M, (1, 3), (1, 3)) + >>> type(B).__name__ + 'BlockMatrix' + >>> ImmutableMatrix(B.blocks[0, 1]) + Matrix([[1, 2, 3]]) + """ + + rowbounds = bounds(rowsizes) + colbounds = bounds(colsizes) + return BlockMatrix([[MatrixSlice(expr, rowbound, colbound) + for colbound in colbounds] + for rowbound in rowbounds]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py new file mode 100644 index 0000000000000000000000000000000000000000..6969c917f63806cb1f5417804e01ecc1350d1406 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py @@ -0,0 +1,56 @@ +from sympy.core.singleton import S +from sympy.core.sympify import _sympify +from sympy.polys.polytools import Poly + +from .matexpr import MatrixExpr + + +class CompanionMatrix(MatrixExpr): + """A symbolic companion matrix of a polynomial. + + Examples + ======== + + >>> from sympy import Poly, Symbol, symbols + >>> from sympy.matrices.expressions import CompanionMatrix + >>> x = Symbol('x') + >>> c0, c1, c2, c3, c4 = symbols('c0:5') + >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) + >>> CompanionMatrix(p) + CompanionMatrix(Poly(x**5 + c4*x**4 + c3*x**3 + c2*x**2 + c1*x + c0, + x, domain='ZZ[c0,c1,c2,c3,c4]')) + """ + def __new__(cls, poly): + poly = _sympify(poly) + if not isinstance(poly, Poly): + raise ValueError("{} must be a Poly instance.".format(poly)) + if not poly.is_monic: + raise ValueError("{} must be a monic polynomial.".format(poly)) + if not poly.is_univariate: + raise ValueError( + "{} must be a univariate polynomial.".format(poly)) + if not poly.degree() >= 1: + raise ValueError( + "{} must have degree not less than 1.".format(poly)) + + return super().__new__(cls, poly) + + + @property + def shape(self): + poly = self.args[0] + size = poly.degree() + return size, size + + + def _entry(self, i, j): + if j == self.cols - 1: + return -self.args[0].all_coeffs()[-1 - i] + elif i == j + 1: + return S.One + return S.Zero + + + def as_explicit(self): + from sympy.matrices.immutable import ImmutableDenseMatrix + return ImmutableDenseMatrix.companion(self.args[0]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py new file mode 100644 index 0000000000000000000000000000000000000000..b323b3f93a5a0404bf2205f39d25b931d173b6d9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py @@ -0,0 +1,148 @@ +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.singleton import S +from sympy.core.sympify import sympify +from sympy.matrices.exceptions import NonSquareMatrixError +from sympy.matrices.matrixbase import MatrixBase + + +class Determinant(Expr): + """Matrix Determinant + + Represents the determinant of a matrix expression. + + Examples + ======== + + >>> from sympy import MatrixSymbol, Determinant, eye + >>> A = MatrixSymbol('A', 3, 3) + >>> Determinant(A) + Determinant(A) + >>> Determinant(eye(3)).doit() + 1 + """ + is_commutative = True + + def __new__(cls, mat): + mat = sympify(mat) + if not mat.is_Matrix: + raise TypeError("Input to Determinant, %s, not a matrix" % str(mat)) + + if mat.is_square is False: + raise NonSquareMatrixError("Det of a non-square matrix") + + return Basic.__new__(cls, mat) + + @property + def arg(self): + return self.args[0] + + @property + def kind(self): + return self.arg.kind.element_kind + + def doit(self, **hints): + arg = self.arg + if hints.get('deep', True): + arg = arg.doit(**hints) + + result = arg._eval_determinant() + if result is not None: + return result + + return self + + +def det(matexpr): + """ Matrix Determinant + + Examples + ======== + + >>> from sympy import MatrixSymbol, det, eye + >>> A = MatrixSymbol('A', 3, 3) + >>> det(A) + Determinant(A) + >>> det(eye(3)) + 1 + """ + + return Determinant(matexpr).doit() + +class Permanent(Expr): + """Matrix Permanent + + Represents the permanent of a matrix expression. + + Examples + ======== + + >>> from sympy import MatrixSymbol, Permanent, ones + >>> A = MatrixSymbol('A', 3, 3) + >>> Permanent(A) + Permanent(A) + >>> Permanent(ones(3, 3)).doit() + 6 + """ + + def __new__(cls, mat): + mat = sympify(mat) + if not mat.is_Matrix: + raise TypeError("Input to Permanent, %s, not a matrix" % str(mat)) + + return Basic.__new__(cls, mat) + + @property + def arg(self): + return self.args[0] + + def doit(self, expand=False, **hints): + if isinstance(self.arg, MatrixBase): + return self.arg.per() + else: + return self + +def per(matexpr): + """ Matrix Permanent + + Examples + ======== + + >>> from sympy import MatrixSymbol, Matrix, per, ones + >>> A = MatrixSymbol('A', 3, 3) + >>> per(A) + Permanent(A) + >>> per(ones(5, 5)) + 120 + >>> M = Matrix([1, 2, 5]) + >>> per(M) + 8 + """ + + return Permanent(matexpr).doit() + +from sympy.assumptions.ask import ask, Q +from sympy.assumptions.refine import handlers_dict + + +def refine_Determinant(expr, assumptions): + """ + >>> from sympy import MatrixSymbol, Q, assuming, refine, det + >>> X = MatrixSymbol('X', 2, 2) + >>> det(X) + Determinant(X) + >>> with assuming(Q.orthogonal(X)): + ... print(refine(det(X))) + 1 + """ + if ask(Q.orthogonal(expr.arg), assumptions): + return S.One + elif ask(Q.singular(expr.arg), assumptions): + return S.Zero + elif ask(Q.unit_triangular(expr.arg), assumptions): + return S.One + + return expr + + +handlers_dict['Determinant'] = refine_Determinant diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py new file mode 100644 index 0000000000000000000000000000000000000000..ba8a0216588143e3e251dab84c25f038fad550a4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py @@ -0,0 +1,220 @@ +from sympy.core.sympify import _sympify + +from sympy.matrices.expressions import MatrixExpr +from sympy.core import S, Eq, Ge +from sympy.core.mul import Mul +from sympy.functions.special.tensor_functions import KroneckerDelta + + +class DiagonalMatrix(MatrixExpr): + """DiagonalMatrix(M) will create a matrix expression that + behaves as though all off-diagonal elements, + `M[i, j]` where `i != j`, are zero. + + Examples + ======== + + >>> from sympy import MatrixSymbol, DiagonalMatrix, Symbol + >>> n = Symbol('n', integer=True) + >>> m = Symbol('m', integer=True) + >>> D = DiagonalMatrix(MatrixSymbol('x', 2, 3)) + >>> D[1, 2] + 0 + >>> D[1, 1] + x[1, 1] + + The length of the diagonal -- the lesser of the two dimensions of `M` -- + is accessed through the `diagonal_length` property: + + >>> D.diagonal_length + 2 + >>> DiagonalMatrix(MatrixSymbol('x', n + 1, n)).diagonal_length + n + + When one of the dimensions is symbolic the other will be treated as + though it is smaller: + + >>> tall = DiagonalMatrix(MatrixSymbol('x', n, 3)) + >>> tall.diagonal_length + 3 + >>> tall[10, 1] + 0 + + When the size of the diagonal is not known, a value of None will + be returned: + + >>> DiagonalMatrix(MatrixSymbol('x', n, m)).diagonal_length is None + True + + """ + arg = property(lambda self: self.args[0]) + + shape = property(lambda self: self.arg.shape) # type:ignore + + @property + def diagonal_length(self): + r, c = self.shape + if r.is_Integer and c.is_Integer: + m = min(r, c) + elif r.is_Integer and not c.is_Integer: + m = r + elif c.is_Integer and not r.is_Integer: + m = c + elif r == c: + m = r + else: + try: + m = min(r, c) + except TypeError: + m = None + return m + + def _entry(self, i, j, **kwargs): + if self.diagonal_length is not None: + if Ge(i, self.diagonal_length) is S.true: + return S.Zero + elif Ge(j, self.diagonal_length) is S.true: + return S.Zero + eq = Eq(i, j) + if eq is S.true: + return self.arg[i, i] + elif eq is S.false: + return S.Zero + return self.arg[i, j]*KroneckerDelta(i, j) + + +class DiagonalOf(MatrixExpr): + """DiagonalOf(M) will create a matrix expression that + is equivalent to the diagonal of `M`, represented as + a single column matrix. + + Examples + ======== + + >>> from sympy import MatrixSymbol, DiagonalOf, Symbol + >>> n = Symbol('n', integer=True) + >>> m = Symbol('m', integer=True) + >>> x = MatrixSymbol('x', 2, 3) + >>> diag = DiagonalOf(x) + >>> diag.shape + (2, 1) + + The diagonal can be addressed like a matrix or vector and will + return the corresponding element of the original matrix: + + >>> diag[1, 0] == diag[1] == x[1, 1] + True + + The length of the diagonal -- the lesser of the two dimensions of `M` -- + is accessed through the `diagonal_length` property: + + >>> diag.diagonal_length + 2 + >>> DiagonalOf(MatrixSymbol('x', n + 1, n)).diagonal_length + n + + When only one of the dimensions is symbolic the other will be + treated as though it is smaller: + + >>> dtall = DiagonalOf(MatrixSymbol('x', n, 3)) + >>> dtall.diagonal_length + 3 + + When the size of the diagonal is not known, a value of None will + be returned: + + >>> DiagonalOf(MatrixSymbol('x', n, m)).diagonal_length is None + True + + """ + arg = property(lambda self: self.args[0]) + @property + def shape(self): + r, c = self.arg.shape + if r.is_Integer and c.is_Integer: + m = min(r, c) + elif r.is_Integer and not c.is_Integer: + m = r + elif c.is_Integer and not r.is_Integer: + m = c + elif r == c: + m = r + else: + try: + m = min(r, c) + except TypeError: + m = None + return m, S.One + + @property + def diagonal_length(self): + return self.shape[0] + + def _entry(self, i, j, **kwargs): + return self.arg._entry(i, i, **kwargs) + + +class DiagMatrix(MatrixExpr): + """ + Turn a vector into a diagonal matrix. + """ + def __new__(cls, vector): + vector = _sympify(vector) + obj = MatrixExpr.__new__(cls, vector) + shape = vector.shape + dim = shape[1] if shape[0] == 1 else shape[0] + if vector.shape[0] != 1: + obj._iscolumn = True + else: + obj._iscolumn = False + obj._shape = (dim, dim) + obj._vector = vector + return obj + + @property + def shape(self): + return self._shape + + def _entry(self, i, j, **kwargs): + if self._iscolumn: + result = self._vector._entry(i, 0, **kwargs) + else: + result = self._vector._entry(0, j, **kwargs) + if i != j: + result *= KroneckerDelta(i, j) + return result + + def _eval_transpose(self): + return self + + def as_explicit(self): + from sympy.matrices.dense import diag + return diag(*list(self._vector.as_explicit())) + + def doit(self, **hints): + from sympy.assumptions import ask, Q + from sympy.matrices.expressions.matmul import MatMul + from sympy.matrices.expressions.transpose import Transpose + from sympy.matrices.dense import eye + from sympy.matrices.matrixbase import MatrixBase + vector = self._vector + # This accounts for shape (1, 1) and identity matrices, among others: + if ask(Q.diagonal(vector)): + return vector + if isinstance(vector, MatrixBase): + ret = eye(max(vector.shape)) + for i in range(ret.shape[0]): + ret[i, i] = vector[i] + return type(vector)(ret) + if vector.is_MatMul: + matrices = [arg for arg in vector.args if arg.is_Matrix] + scalars = [arg for arg in vector.args if arg not in matrices] + if scalars: + return Mul.fromiter(scalars)*DiagMatrix(MatMul.fromiter(matrices).doit()).doit() + if isinstance(vector, Transpose): + vector = vector.arg + return DiagMatrix(vector) + + +def diagonalize_vector(vector): + return DiagMatrix(vector).doit() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py new file mode 100644 index 0000000000000000000000000000000000000000..3a413f8c79a221505f0c082d7f19f78597a2befc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py @@ -0,0 +1,55 @@ +from sympy.core import Basic, Expr +from sympy.core.sympify import _sympify +from sympy.matrices.expressions.transpose import transpose + + +class DotProduct(Expr): + """ + Dot product of vector matrices + + The input should be two 1 x n or n x 1 matrices. The output represents the + scalar dotproduct. + + This is similar to using MatrixElement and MatMul, except DotProduct does + not require that one vector to be a row vector and the other vector to be + a column vector. + + >>> from sympy import MatrixSymbol, DotProduct + >>> A = MatrixSymbol('A', 1, 3) + >>> B = MatrixSymbol('B', 1, 3) + >>> DotProduct(A, B) + DotProduct(A, B) + >>> DotProduct(A, B).doit() + A[0, 0]*B[0, 0] + A[0, 1]*B[0, 1] + A[0, 2]*B[0, 2] + """ + + def __new__(cls, arg1, arg2): + arg1, arg2 = _sympify((arg1, arg2)) + + if not arg1.is_Matrix: + raise TypeError("Argument 1 of DotProduct is not a matrix") + if not arg2.is_Matrix: + raise TypeError("Argument 2 of DotProduct is not a matrix") + if not (1 in arg1.shape): + raise TypeError("Argument 1 of DotProduct is not a vector") + if not (1 in arg2.shape): + raise TypeError("Argument 2 of DotProduct is not a vector") + + if set(arg1.shape) != set(arg2.shape): + raise TypeError("DotProduct arguments are not the same length") + + return Basic.__new__(cls, arg1, arg2) + + def doit(self, expand=False, **hints): + if self.args[0].shape == self.args[1].shape: + if self.args[0].shape[0] == 1: + mul = self.args[0]*transpose(self.args[1]) + else: + mul = transpose(self.args[0])*self.args[1] + else: + if self.args[0].shape[0] == 1: + mul = self.args[0]*self.args[1] + else: + mul = transpose(self.args[0])*transpose(self.args[1]) + + return mul[0] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py new file mode 100644 index 0000000000000000000000000000000000000000..aff2bb81ecff99d8e733f282ac2dd187d76ce895 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py @@ -0,0 +1,62 @@ +from sympy.matrices.expressions import MatrixExpr +from sympy.assumptions.ask import Q + +class Factorization(MatrixExpr): + arg = property(lambda self: self.args[0]) + shape = property(lambda self: self.arg.shape) # type: ignore + +class LofLU(Factorization): + @property + def predicates(self): + return (Q.lower_triangular,) +class UofLU(Factorization): + @property + def predicates(self): + return (Q.upper_triangular,) + +class LofCholesky(LofLU): pass +class UofCholesky(UofLU): pass + +class QofQR(Factorization): + @property + def predicates(self): + return (Q.orthogonal,) +class RofQR(Factorization): + @property + def predicates(self): + return (Q.upper_triangular,) + +class EigenVectors(Factorization): + @property + def predicates(self): + return (Q.orthogonal,) +class EigenValues(Factorization): + @property + def predicates(self): + return (Q.diagonal,) + +class UofSVD(Factorization): + @property + def predicates(self): + return (Q.orthogonal,) +class SofSVD(Factorization): + @property + def predicates(self): + return (Q.diagonal,) +class VofSVD(Factorization): + @property + def predicates(self): + return (Q.orthogonal,) + + +def lu(expr): + return LofLU(expr), UofLU(expr) + +def qr(expr): + return QofQR(expr), RofQR(expr) + +def eig(expr): + return EigenValues(expr), EigenVectors(expr) + +def svd(expr): + return UofSVD(expr), SofSVD(expr), VofSVD(expr) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa9222c2a9b218f42636267235d5dd44c25f8bb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py @@ -0,0 +1,91 @@ +from sympy.core.sympify import _sympify +from sympy.matrices.expressions import MatrixExpr +from sympy.core.numbers import I +from sympy.core.singleton import S +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt + + +class DFT(MatrixExpr): + r""" + Returns a discrete Fourier transform matrix. The matrix is scaled + with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. + + Parameters + ========== + + n : integer or Symbol + Size of the transform. + + Examples + ======== + + >>> from sympy.abc import n + >>> from sympy.matrices.expressions.fourier import DFT + >>> DFT(3) + DFT(3) + >>> DFT(3).as_explicit() + Matrix([ + [sqrt(3)/3, sqrt(3)/3, sqrt(3)/3], + [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(2*I*pi/3)/3], + [sqrt(3)/3, sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]]) + >>> DFT(n).shape + (n, n) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/DFT_matrix + + """ + + def __new__(cls, n): + n = _sympify(n) + cls._check_dim(n) + + obj = super().__new__(cls, n) + return obj + + n = property(lambda self: self.args[0]) # type: ignore + shape = property(lambda self: (self.n, self.n)) # type: ignore + + def _entry(self, i, j, **kwargs): + w = exp(-2*S.Pi*I/self.n) + return w**(i*j) / sqrt(self.n) + + def _eval_inverse(self): + return IDFT(self.n) + + +class IDFT(DFT): + r""" + Returns an inverse discrete Fourier transform matrix. The matrix is scaled + with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. + + Parameters + ========== + + n : integer or Symbol + Size of the transform + + Examples + ======== + + >>> from sympy.matrices.expressions.fourier import DFT, IDFT + >>> IDFT(3) + IDFT(3) + >>> IDFT(4)*DFT(4) + I + + See Also + ======== + + DFT + + """ + def _entry(self, i, j, **kwargs): + w = exp(-2*S.Pi*I/self.n) + return w**(-i*j) / sqrt(self.n) + + def _eval_inverse(self): + return DFT(self.n) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..91106edb489b73ac9dd6cb94adc508c0db75d3a5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py @@ -0,0 +1,118 @@ +from .matexpr import MatrixExpr +from sympy.core.function import FunctionClass, Lambda +from sympy.core.symbol import Dummy +from sympy.core.sympify import _sympify, sympify +from sympy.matrices import Matrix +from sympy.functions.elementary.complexes import re, im + + +class FunctionMatrix(MatrixExpr): + """Represents a matrix using a function (``Lambda``) which gives + outputs according to the coordinates of each matrix entries. + + Parameters + ========== + + rows : nonnegative integer. Can be symbolic. + + cols : nonnegative integer. Can be symbolic. + + lamda : Function, Lambda or str + If it is a SymPy ``Function`` or ``Lambda`` instance, + it should be able to accept two arguments which represents the + matrix coordinates. + + If it is a pure string containing Python ``lambda`` semantics, + it is interpreted by the SymPy parser and casted into a SymPy + ``Lambda`` instance. + + Examples + ======== + + Creating a ``FunctionMatrix`` from ``Lambda``: + + >>> from sympy import FunctionMatrix, symbols, Lambda, MatPow + >>> i, j, n, m = symbols('i,j,n,m') + >>> FunctionMatrix(n, m, Lambda((i, j), i + j)) + FunctionMatrix(n, m, Lambda((i, j), i + j)) + + Creating a ``FunctionMatrix`` from a SymPy function: + + >>> from sympy import KroneckerDelta + >>> X = FunctionMatrix(3, 3, KroneckerDelta) + >>> X.as_explicit() + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + Creating a ``FunctionMatrix`` from a SymPy undefined function: + + >>> from sympy import Function + >>> f = Function('f') + >>> X = FunctionMatrix(3, 3, f) + >>> X.as_explicit() + Matrix([ + [f(0, 0), f(0, 1), f(0, 2)], + [f(1, 0), f(1, 1), f(1, 2)], + [f(2, 0), f(2, 1), f(2, 2)]]) + + Creating a ``FunctionMatrix`` from Python ``lambda``: + + >>> FunctionMatrix(n, m, 'lambda i, j: i + j') + FunctionMatrix(n, m, Lambda((i, j), i + j)) + + Example of lazy evaluation of matrix product: + + >>> Y = FunctionMatrix(1000, 1000, Lambda((i, j), i + j)) + >>> isinstance(Y*Y, MatPow) # this is an expression object + True + >>> (Y**2)[10,10] # So this is evaluated lazily + 342923500 + + Notes + ===== + + This class provides an alternative way to represent an extremely + dense matrix with entries in some form of a sequence, in a most + sparse way. + """ + def __new__(cls, rows, cols, lamda): + rows, cols = _sympify(rows), _sympify(cols) + cls._check_dim(rows) + cls._check_dim(cols) + + lamda = sympify(lamda) + if not isinstance(lamda, (FunctionClass, Lambda)): + raise ValueError( + "{} should be compatible with SymPy function classes." + .format(lamda)) + + if 2 not in lamda.nargs: + raise ValueError( + '{} should be able to accept 2 arguments.'.format(lamda)) + + if not isinstance(lamda, Lambda): + i, j = Dummy('i'), Dummy('j') + lamda = Lambda((i, j), lamda(i, j)) + + return super().__new__(cls, rows, cols, lamda) + + @property + def shape(self): + return self.args[0:2] + + @property + def lamda(self): + return self.args[2] + + def _entry(self, i, j, **kwargs): + return self.lamda(i, j) + + def _eval_trace(self): + from sympy.matrices.expressions.trace import Trace + from sympy.concrete.summations import Sum + return Trace(self).rewrite(Sum).doit() + + def _eval_as_real_imag(self): + return (re(Matrix(self)), im(Matrix(self))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py new file mode 100644 index 0000000000000000000000000000000000000000..38c9033ebea3a7bfc569223978dc6ef3890206cf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py @@ -0,0 +1,464 @@ +from collections import Counter + +from sympy.core import Mul, sympify +from sympy.core.add import Add +from sympy.core.expr import ExprBuilder +from sympy.core.sorting import default_sort_key +from sympy.functions.elementary.exponential import log +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions._shape import validate_matadd_integer as validate +from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix +from sympy.strategies import ( + unpack, flatten, condition, exhaust, rm_id, sort +) +from sympy.utilities.exceptions import sympy_deprecation_warning + + +def hadamard_product(*matrices): + """ + Return the elementwise (aka Hadamard) product of matrices. + + Examples + ======== + + >>> from sympy import hadamard_product, MatrixSymbol + >>> A = MatrixSymbol('A', 2, 3) + >>> B = MatrixSymbol('B', 2, 3) + >>> hadamard_product(A) + A + >>> hadamard_product(A, B) + HadamardProduct(A, B) + >>> hadamard_product(A, B)[0, 1] + A[0, 1]*B[0, 1] + """ + if not matrices: + raise TypeError("Empty Hadamard product is undefined") + if len(matrices) == 1: + return matrices[0] + return HadamardProduct(*matrices).doit() + + +class HadamardProduct(MatrixExpr): + """ + Elementwise product of matrix expressions + + Examples + ======== + + Hadamard product for matrix symbols: + + >>> from sympy import hadamard_product, HadamardProduct, MatrixSymbol + >>> A = MatrixSymbol('A', 5, 5) + >>> B = MatrixSymbol('B', 5, 5) + >>> isinstance(hadamard_product(A, B), HadamardProduct) + True + + Notes + ===== + + This is a symbolic object that simply stores its argument without + evaluating it. To actually compute the product, use the function + ``hadamard_product()`` or ``HadamardProduct.doit`` + """ + is_HadamardProduct = True + + def __new__(cls, *args, evaluate=False, check=None): + args = list(map(sympify, args)) + if len(args) == 0: + # We currently don't have a way to support one-matrices of generic dimensions: + raise ValueError("HadamardProduct needs at least one argument") + + if not all(isinstance(arg, MatrixExpr) for arg in args): + raise TypeError("Mix of Matrix and Scalar symbols") + + if check is not None: + sympy_deprecation_warning( + "Passing check to HadamardProduct is deprecated and the check argument will be removed in a future version.", + deprecated_since_version="1.11", + active_deprecations_target='remove-check-argument-from-matrix-operations') + + if check is not False: + validate(*args) + + obj = super().__new__(cls, *args) + if evaluate: + obj = obj.doit(deep=False) + return obj + + @property + def shape(self): + return self.args[0].shape + + def _entry(self, i, j, **kwargs): + return Mul(*[arg._entry(i, j, **kwargs) for arg in self.args]) + + def _eval_transpose(self): + from sympy.matrices.expressions.transpose import transpose + return HadamardProduct(*list(map(transpose, self.args))) + + def doit(self, **hints): + expr = self.func(*(i.doit(**hints) for i in self.args)) + # Check for explicit matrices: + from sympy.matrices.matrixbase import MatrixBase + from sympy.matrices.immutable import ImmutableMatrix + + explicit = [i for i in expr.args if isinstance(i, MatrixBase)] + if explicit: + remainder = [i for i in expr.args if i not in explicit] + expl_mat = ImmutableMatrix([ + Mul.fromiter(i) for i in zip(*explicit) + ]).reshape(*self.shape) + expr = HadamardProduct(*([expl_mat] + remainder)) + + return canonicalize(expr) + + def _eval_derivative(self, x): + terms = [] + args = list(self.args) + for i in range(len(args)): + factors = args[:i] + [args[i].diff(x)] + args[i+1:] + terms.append(hadamard_product(*factors)) + return Add.fromiter(terms) + + def _eval_derivative_matrix_lines(self, x): + from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal + from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct + from sympy.matrices.expressions.matexpr import _make_matrix + + with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] + lines = [] + for ind in with_x_ind: + left_args = self.args[:ind] + right_args = self.args[ind+1:] + + d = self.args[ind]._eval_derivative_matrix_lines(x) + hadam = hadamard_product(*(right_args + left_args)) + diagonal = [(0, 2), (3, 4)] + diagonal = [e for j, e in enumerate(diagonal) if self.shape[j] != 1] + for i in d: + l1 = i._lines[i._first_line_index] + l2 = i._lines[i._second_line_index] + subexpr = ExprBuilder( + ArrayDiagonal, + [ + ExprBuilder( + ArrayTensorProduct, + [ + ExprBuilder(_make_matrix, [l1]), + hadam, + ExprBuilder(_make_matrix, [l2]), + ] + ), + *diagonal], + + ) + i._first_pointer_parent = subexpr.args[0].args[0].args + i._first_pointer_index = 0 + i._second_pointer_parent = subexpr.args[0].args[2].args + i._second_pointer_index = 0 + i._lines = [subexpr] + lines.append(i) + + return lines + + +# TODO Implement algorithm for rewriting Hadamard product as diagonal matrix +# if matmul identy matrix is multiplied. +def canonicalize(x): + """Canonicalize the Hadamard product ``x`` with mathematical properties. + + Examples + ======== + + >>> from sympy import MatrixSymbol, HadamardProduct + >>> from sympy import OneMatrix, ZeroMatrix + >>> from sympy.matrices.expressions.hadamard import canonicalize + >>> from sympy import init_printing + >>> init_printing(use_unicode=False) + + >>> A = MatrixSymbol('A', 2, 2) + >>> B = MatrixSymbol('B', 2, 2) + >>> C = MatrixSymbol('C', 2, 2) + + Hadamard product associativity: + + >>> X = HadamardProduct(A, HadamardProduct(B, C)) + >>> X + A.*(B.*C) + >>> canonicalize(X) + A.*B.*C + + Hadamard product commutativity: + + >>> X = HadamardProduct(A, B) + >>> Y = HadamardProduct(B, A) + >>> X + A.*B + >>> Y + B.*A + >>> canonicalize(X) + A.*B + >>> canonicalize(Y) + A.*B + + Hadamard product identity: + + >>> X = HadamardProduct(A, OneMatrix(2, 2)) + >>> X + A.*1 + >>> canonicalize(X) + A + + Absorbing element of Hadamard product: + + >>> X = HadamardProduct(A, ZeroMatrix(2, 2)) + >>> X + A.*0 + >>> canonicalize(X) + 0 + + Rewriting to Hadamard Power + + >>> X = HadamardProduct(A, A, A) + >>> X + A.*A.*A + >>> canonicalize(X) + .3 + A + + Notes + ===== + + As the Hadamard product is associative, nested products can be flattened. + + The Hadamard product is commutative so that factors can be sorted for + canonical form. + + A matrix of only ones is an identity for Hadamard product, + so every matrices of only ones can be removed. + + Any zero matrix will make the whole product a zero matrix. + + Duplicate elements can be collected and rewritten as HadamardPower + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Hadamard_product_(matrices) + """ + # Associativity + rule = condition( + lambda x: isinstance(x, HadamardProduct), + flatten + ) + fun = exhaust(rule) + x = fun(x) + + # Identity + fun = condition( + lambda x: isinstance(x, HadamardProduct), + rm_id(lambda x: isinstance(x, OneMatrix)) + ) + x = fun(x) + + # Absorbing by Zero Matrix + def absorb(x): + if any(isinstance(c, ZeroMatrix) for c in x.args): + return ZeroMatrix(*x.shape) + else: + return x + fun = condition( + lambda x: isinstance(x, HadamardProduct), + absorb + ) + x = fun(x) + + # Rewriting with HadamardPower + if isinstance(x, HadamardProduct): + tally = Counter(x.args) + + new_arg = [] + for base, exp in tally.items(): + if exp == 1: + new_arg.append(base) + else: + new_arg.append(HadamardPower(base, exp)) + + x = HadamardProduct(*new_arg) + + # Commutativity + fun = condition( + lambda x: isinstance(x, HadamardProduct), + sort(default_sort_key) + ) + x = fun(x) + + # Unpacking + x = unpack(x) + return x + + +def hadamard_power(base, exp): + base = sympify(base) + exp = sympify(exp) + if exp == 1: + return base + if not base.is_Matrix: + return base**exp + if exp.is_Matrix: + raise ValueError("cannot raise expression to a matrix") + return HadamardPower(base, exp) + + +class HadamardPower(MatrixExpr): + r""" + Elementwise power of matrix expressions + + Parameters + ========== + + base : scalar or matrix + + exp : scalar or matrix + + Notes + ===== + + There are four definitions for the hadamard power which can be used. + Let's consider `A, B` as `(m, n)` matrices, and `a, b` as scalars. + + Matrix raised to a scalar exponent: + + .. math:: + A^{\circ b} = \begin{bmatrix} + A_{0, 0}^b & A_{0, 1}^b & \cdots & A_{0, n-1}^b \\ + A_{1, 0}^b & A_{1, 1}^b & \cdots & A_{1, n-1}^b \\ + \vdots & \vdots & \ddots & \vdots \\ + A_{m-1, 0}^b & A_{m-1, 1}^b & \cdots & A_{m-1, n-1}^b + \end{bmatrix} + + Scalar raised to a matrix exponent: + + .. math:: + a^{\circ B} = \begin{bmatrix} + a^{B_{0, 0}} & a^{B_{0, 1}} & \cdots & a^{B_{0, n-1}} \\ + a^{B_{1, 0}} & a^{B_{1, 1}} & \cdots & a^{B_{1, n-1}} \\ + \vdots & \vdots & \ddots & \vdots \\ + a^{B_{m-1, 0}} & a^{B_{m-1, 1}} & \cdots & a^{B_{m-1, n-1}} + \end{bmatrix} + + Matrix raised to a matrix exponent: + + .. math:: + A^{\circ B} = \begin{bmatrix} + A_{0, 0}^{B_{0, 0}} & A_{0, 1}^{B_{0, 1}} & + \cdots & A_{0, n-1}^{B_{0, n-1}} \\ + A_{1, 0}^{B_{1, 0}} & A_{1, 1}^{B_{1, 1}} & + \cdots & A_{1, n-1}^{B_{1, n-1}} \\ + \vdots & \vdots & + \ddots & \vdots \\ + A_{m-1, 0}^{B_{m-1, 0}} & A_{m-1, 1}^{B_{m-1, 1}} & + \cdots & A_{m-1, n-1}^{B_{m-1, n-1}} + \end{bmatrix} + + Scalar raised to a scalar exponent: + + .. math:: + a^{\circ b} = a^b + """ + + def __new__(cls, base, exp): + base = sympify(base) + exp = sympify(exp) + + if base.is_scalar and exp.is_scalar: + return base ** exp + + if isinstance(base, MatrixExpr) and isinstance(exp, MatrixExpr): + validate(base, exp) + + obj = super().__new__(cls, base, exp) + return obj + + @property + def base(self): + return self._args[0] + + @property + def exp(self): + return self._args[1] + + @property + def shape(self): + if self.base.is_Matrix: + return self.base.shape + return self.exp.shape + + def _entry(self, i, j, **kwargs): + base = self.base + exp = self.exp + + if base.is_Matrix: + a = base._entry(i, j, **kwargs) + elif base.is_scalar: + a = base + else: + raise ValueError( + 'The base {} must be a scalar or a matrix.'.format(base)) + + if exp.is_Matrix: + b = exp._entry(i, j, **kwargs) + elif exp.is_scalar: + b = exp + else: + raise ValueError( + 'The exponent {} must be a scalar or a matrix.'.format(exp)) + + return a ** b + + def _eval_transpose(self): + from sympy.matrices.expressions.transpose import transpose + return HadamardPower(transpose(self.base), self.exp) + + def _eval_derivative(self, x): + dexp = self.exp.diff(x) + logbase = self.base.applyfunc(log) + dlbase = logbase.diff(x) + return hadamard_product( + dexp*logbase + self.exp*dlbase, + self + ) + + def _eval_derivative_matrix_lines(self, x): + from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct + from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal + from sympy.matrices.expressions.matexpr import _make_matrix + + lr = self.base._eval_derivative_matrix_lines(x) + for i in lr: + diagonal = [(1, 2), (3, 4)] + diagonal = [e for j, e in enumerate(diagonal) if self.base.shape[j] != 1] + l1 = i._lines[i._first_line_index] + l2 = i._lines[i._second_line_index] + subexpr = ExprBuilder( + ArrayDiagonal, + [ + ExprBuilder( + ArrayTensorProduct, + [ + ExprBuilder(_make_matrix, [l1]), + self.exp*hadamard_power(self.base, self.exp-1), + ExprBuilder(_make_matrix, [l2]), + ] + ), + *diagonal], + validator=ArrayDiagonal._validate + ) + i._first_pointer_parent = subexpr.args[0].args[0].args + i._first_pointer_index = 0 + i._first_line_index = 0 + i._second_pointer_parent = subexpr.args[0].args[2].args + i._second_pointer_index = 0 + i._second_line_index = 0 + i._lines = [subexpr] + return lr diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py new file mode 100644 index 0000000000000000000000000000000000000000..cfc3feccd7126a761f18f23599eed9413c86a9e5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py @@ -0,0 +1,112 @@ +from sympy.core.sympify import _sympify +from sympy.core import S, Basic + +from sympy.matrices.exceptions import NonSquareMatrixError +from sympy.matrices.expressions.matpow import MatPow + + +class Inverse(MatPow): + """ + The multiplicative inverse of a matrix expression + + This is a symbolic object that simply stores its argument without + evaluating it. To actually compute the inverse, use the ``.inverse()`` + method of matrices. + + Examples + ======== + + >>> from sympy import MatrixSymbol, Inverse + >>> A = MatrixSymbol('A', 3, 3) + >>> B = MatrixSymbol('B', 3, 3) + >>> Inverse(A) + A**(-1) + >>> A.inverse() == Inverse(A) + True + >>> (A*B).inverse() + B**(-1)*A**(-1) + >>> Inverse(A*B) + (A*B)**(-1) + + """ + is_Inverse = True + exp = S.NegativeOne + + def __new__(cls, mat, exp=S.NegativeOne): + # exp is there to make it consistent with + # inverse.func(*inverse.args) == inverse + mat = _sympify(mat) + exp = _sympify(exp) + if not mat.is_Matrix: + raise TypeError("mat should be a matrix") + if mat.is_square is False: + raise NonSquareMatrixError("Inverse of non-square matrix %s" % mat) + return Basic.__new__(cls, mat, exp) + + @property + def arg(self): + return self.args[0] + + @property + def shape(self): + return self.arg.shape + + def _eval_inverse(self): + return self.arg + + def _eval_transpose(self): + return Inverse(self.arg.transpose()) + + def _eval_adjoint(self): + return Inverse(self.arg.adjoint()) + + def _eval_conjugate(self): + return Inverse(self.arg.conjugate()) + + def _eval_determinant(self): + from sympy.matrices.expressions.determinant import det + return 1/det(self.arg) + + def doit(self, **hints): + if 'inv_expand' in hints and hints['inv_expand'] == False: + return self + + arg = self.arg + if hints.get('deep', True): + arg = arg.doit(**hints) + + return arg.inverse() + + def _eval_derivative_matrix_lines(self, x): + arg = self.args[0] + lines = arg._eval_derivative_matrix_lines(x) + for line in lines: + line.first_pointer *= -self.T + line.second_pointer *= self + return lines + + +from sympy.assumptions.ask import ask, Q +from sympy.assumptions.refine import handlers_dict + + +def refine_Inverse(expr, assumptions): + """ + >>> from sympy import MatrixSymbol, Q, assuming, refine + >>> X = MatrixSymbol('X', 2, 2) + >>> X.I + X**(-1) + >>> with assuming(Q.orthogonal(X)): + ... print(refine(X.I)) + X.T + """ + if ask(Q.orthogonal(expr), assumptions): + return expr.arg.T + elif ask(Q.unitary(expr), assumptions): + return expr.arg.conjugate() + elif ask(Q.singular(expr), assumptions): + raise ValueError("Inverse of singular matrix %s" % expr.arg) + + return expr + +handlers_dict['Inverse'] = refine_Inverse diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/kronecker.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/kronecker.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd175cb0d500af3e786e2d0dbf6b010947840b4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/kronecker.py @@ -0,0 +1,434 @@ +"""Implementation of the Kronecker product""" +from functools import reduce +from math import prod + +from sympy.core import Mul, sympify +from sympy.functions import adjoint +from sympy.matrices.exceptions import ShapeError +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.transpose import transpose +from sympy.matrices.expressions.special import Identity +from sympy.matrices.matrixbase import MatrixBase +from sympy.strategies import ( + canon, condition, distribute, do_one, exhaust, flatten, typed, unpack) +from sympy.strategies.traverse import bottom_up +from sympy.utilities import sift + +from .matadd import MatAdd +from .matmul import MatMul +from .matpow import MatPow + + +def kronecker_product(*matrices): + """ + The Kronecker product of two or more arguments. + + This computes the explicit Kronecker product for subclasses of + ``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic + ``KroneckerProduct`` object is returned. + + + Examples + ======== + + For ``MatrixSymbol`` arguments a ``KroneckerProduct`` object is returned. + Elements of this matrix can be obtained by indexing, or for MatrixSymbols + with known dimension the explicit matrix can be obtained with + ``.as_explicit()`` + + >>> from sympy import kronecker_product, MatrixSymbol + >>> A = MatrixSymbol('A', 2, 2) + >>> B = MatrixSymbol('B', 2, 2) + >>> kronecker_product(A) + A + >>> kronecker_product(A, B) + KroneckerProduct(A, B) + >>> kronecker_product(A, B)[0, 1] + A[0, 0]*B[0, 1] + >>> kronecker_product(A, B).as_explicit() + Matrix([ + [A[0, 0]*B[0, 0], A[0, 0]*B[0, 1], A[0, 1]*B[0, 0], A[0, 1]*B[0, 1]], + [A[0, 0]*B[1, 0], A[0, 0]*B[1, 1], A[0, 1]*B[1, 0], A[0, 1]*B[1, 1]], + [A[1, 0]*B[0, 0], A[1, 0]*B[0, 1], A[1, 1]*B[0, 0], A[1, 1]*B[0, 1]], + [A[1, 0]*B[1, 0], A[1, 0]*B[1, 1], A[1, 1]*B[1, 0], A[1, 1]*B[1, 1]]]) + + For explicit matrices the Kronecker product is returned as a Matrix + + >>> from sympy import Matrix, kronecker_product + >>> sigma_x = Matrix([ + ... [0, 1], + ... [1, 0]]) + ... + >>> Isigma_y = Matrix([ + ... [0, 1], + ... [-1, 0]]) + ... + >>> kronecker_product(sigma_x, Isigma_y) + Matrix([ + [ 0, 0, 0, 1], + [ 0, 0, -1, 0], + [ 0, 1, 0, 0], + [-1, 0, 0, 0]]) + + See Also + ======== + KroneckerProduct + + """ + if not matrices: + raise TypeError("Empty Kronecker product is undefined") + if len(matrices) == 1: + return matrices[0] + else: + return KroneckerProduct(*matrices).doit() + + +class KroneckerProduct(MatrixExpr): + """ + The Kronecker product of two or more arguments. + + The Kronecker product is a non-commutative product of matrices. + Given two matrices of dimension (m, n) and (s, t) it produces a matrix + of dimension (m s, n t). + + This is a symbolic object that simply stores its argument without + evaluating it. To actually compute the product, use the function + ``kronecker_product()`` or call the ``.doit()`` or ``.as_explicit()`` + methods. + + >>> from sympy import KroneckerProduct, MatrixSymbol + >>> A = MatrixSymbol('A', 5, 5) + >>> B = MatrixSymbol('B', 5, 5) + >>> isinstance(KroneckerProduct(A, B), KroneckerProduct) + True + """ + is_KroneckerProduct = True + + def __new__(cls, *args, check=True): + args = list(map(sympify, args)) + if all(a.is_Identity for a in args): + ret = Identity(prod(a.rows for a in args)) + if all(isinstance(a, MatrixBase) for a in args): + return ret.as_explicit() + else: + return ret + + if check: + validate(*args) + return super().__new__(cls, *args) + + @property + def shape(self): + rows, cols = self.args[0].shape + for mat in self.args[1:]: + rows *= mat.rows + cols *= mat.cols + return (rows, cols) + + def _entry(self, i, j, **kwargs): + result = 1 + for mat in reversed(self.args): + i, m = divmod(i, mat.rows) + j, n = divmod(j, mat.cols) + result *= mat[m, n] + return result + + def _eval_adjoint(self): + return KroneckerProduct(*list(map(adjoint, self.args))).doit() + + def _eval_conjugate(self): + return KroneckerProduct(*[a.conjugate() for a in self.args]).doit() + + def _eval_transpose(self): + return KroneckerProduct(*list(map(transpose, self.args))).doit() + + def _eval_trace(self): + from .trace import trace + return Mul(*[trace(a) for a in self.args]) + + def _eval_determinant(self): + from .determinant import det, Determinant + if not all(a.is_square for a in self.args): + return Determinant(self) + + m = self.rows + return Mul(*[det(a)**(m/a.rows) for a in self.args]) + + def _eval_inverse(self): + try: + return KroneckerProduct(*[a.inverse() for a in self.args]) + except ShapeError: + from sympy.matrices.expressions.inverse import Inverse + return Inverse(self) + + def structurally_equal(self, other): + '''Determine whether two matrices have the same Kronecker product structure + + Examples + ======== + + >>> from sympy import KroneckerProduct, MatrixSymbol, symbols + >>> m, n = symbols(r'm, n', integer=True) + >>> A = MatrixSymbol('A', m, m) + >>> B = MatrixSymbol('B', n, n) + >>> C = MatrixSymbol('C', m, m) + >>> D = MatrixSymbol('D', n, n) + >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(C, D)) + True + >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(D, C)) + False + >>> KroneckerProduct(A, B).structurally_equal(C) + False + ''' + # Inspired by BlockMatrix + return (isinstance(other, KroneckerProduct) + and self.shape == other.shape + and len(self.args) == len(other.args) + and all(a.shape == b.shape for (a, b) in zip(self.args, other.args))) + + def has_matching_shape(self, other): + '''Determine whether two matrices have the appropriate structure to bring matrix + multiplication inside the KroneckerProdut + + Examples + ======== + >>> from sympy import KroneckerProduct, MatrixSymbol, symbols + >>> m, n = symbols(r'm, n', integer=True) + >>> A = MatrixSymbol('A', m, n) + >>> B = MatrixSymbol('B', n, m) + >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(B, A)) + True + >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(A, B)) + False + >>> KroneckerProduct(A, B).has_matching_shape(A) + False + ''' + return (isinstance(other, KroneckerProduct) + and self.cols == other.rows + and len(self.args) == len(other.args) + and all(a.cols == b.rows for (a, b) in zip(self.args, other.args))) + + def _eval_expand_kroneckerproduct(self, **hints): + return flatten(canon(typed({KroneckerProduct: distribute(KroneckerProduct, MatAdd)}))(self)) + + def _kronecker_add(self, other): + if self.structurally_equal(other): + return self.__class__(*[a + b for (a, b) in zip(self.args, other.args)]) + else: + return self + other + + def _kronecker_mul(self, other): + if self.has_matching_shape(other): + return self.__class__(*[a*b for (a, b) in zip(self.args, other.args)]) + else: + return self * other + + def doit(self, **hints): + deep = hints.get('deep', True) + if deep: + args = [arg.doit(**hints) for arg in self.args] + else: + args = self.args + return canonicalize(KroneckerProduct(*args)) + + +def validate(*args): + if not all(arg.is_Matrix for arg in args): + raise TypeError("Mix of Matrix and Scalar symbols") + + +# rules + +def extract_commutative(kron): + c_part = [] + nc_part = [] + for arg in kron.args: + c, nc = arg.args_cnc() + c_part.extend(c) + nc_part.append(Mul._from_args(nc)) + + c_part = Mul(*c_part) + if c_part != 1: + return c_part*KroneckerProduct(*nc_part) + return kron + + +def matrix_kronecker_product(*matrices): + """Compute the Kronecker product of a sequence of SymPy Matrices. + + This is the standard Kronecker product of matrices [1]. + + Parameters + ========== + + matrices : tuple of MatrixBase instances + The matrices to take the Kronecker product of. + + Returns + ======= + + matrix : MatrixBase + The Kronecker product matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.matrices.expressions.kronecker import ( + ... matrix_kronecker_product) + + >>> m1 = Matrix([[1,2],[3,4]]) + >>> m2 = Matrix([[1,0],[0,1]]) + >>> matrix_kronecker_product(m1, m2) + Matrix([ + [1, 0, 2, 0], + [0, 1, 0, 2], + [3, 0, 4, 0], + [0, 3, 0, 4]]) + >>> matrix_kronecker_product(m2, m1) + Matrix([ + [1, 2, 0, 0], + [3, 4, 0, 0], + [0, 0, 1, 2], + [0, 0, 3, 4]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Kronecker_product + """ + # Make sure we have a sequence of Matrices + if not all(isinstance(m, MatrixBase) for m in matrices): + raise TypeError( + 'Sequence of Matrices expected, got: %s' % repr(matrices) + ) + + # Pull out the first element in the product. + matrix_expansion = matrices[-1] + # Do the kronecker product working from right to left. + for mat in reversed(matrices[:-1]): + rows = mat.rows + cols = mat.cols + # Go through each row appending kronecker product to. + # running matrix_expansion. + for i in range(rows): + start = matrix_expansion*mat[i*cols] + # Go through each column joining each item + for j in range(cols - 1): + start = start.row_join( + matrix_expansion*mat[i*cols + j + 1] + ) + # If this is the first element, make it the start of the + # new row. + if i == 0: + next = start + else: + next = next.col_join(start) + matrix_expansion = next + + MatrixClass = max(matrices, key=lambda M: M._class_priority).__class__ + if isinstance(matrix_expansion, MatrixClass): + return matrix_expansion + else: + return MatrixClass(matrix_expansion) + + +def explicit_kronecker_product(kron): + # Make sure we have a sequence of Matrices + if not all(isinstance(m, MatrixBase) for m in kron.args): + return kron + + return matrix_kronecker_product(*kron.args) + + +rules = (unpack, + explicit_kronecker_product, + flatten, + extract_commutative) + +canonicalize = exhaust(condition(lambda x: isinstance(x, KroneckerProduct), + do_one(*rules))) + + +def _kronecker_dims_key(expr): + if isinstance(expr, KroneckerProduct): + return tuple(a.shape for a in expr.args) + else: + return (0,) + + +def kronecker_mat_add(expr): + args = sift(expr.args, _kronecker_dims_key) + nonkrons = args.pop((0,), None) + if not args: + return expr + + krons = [reduce(lambda x, y: x._kronecker_add(y), group) + for group in args.values()] + + if not nonkrons: + return MatAdd(*krons) + else: + return MatAdd(*krons) + nonkrons + + +def kronecker_mat_mul(expr): + # modified from block matrix code + factor, matrices = expr.as_coeff_matrices() + + i = 0 + while i < len(matrices) - 1: + A, B = matrices[i:i+2] + if isinstance(A, KroneckerProduct) and isinstance(B, KroneckerProduct): + matrices[i] = A._kronecker_mul(B) + matrices.pop(i+1) + else: + i += 1 + + return factor*MatMul(*matrices) + + +def kronecker_mat_pow(expr): + if isinstance(expr.base, KroneckerProduct) and all(a.is_square for a in expr.base.args): + return KroneckerProduct(*[MatPow(a, expr.exp) for a in expr.base.args]) + else: + return expr + + +def combine_kronecker(expr): + """Combine KronekeckerProduct with expression. + + If possible write operations on KroneckerProducts of compatible shapes + as a single KroneckerProduct. + + Examples + ======== + + >>> from sympy.matrices.expressions import combine_kronecker + >>> from sympy import MatrixSymbol, KroneckerProduct, symbols + >>> m, n = symbols(r'm, n', integer=True) + >>> A = MatrixSymbol('A', m, n) + >>> B = MatrixSymbol('B', n, m) + >>> combine_kronecker(KroneckerProduct(A, B)*KroneckerProduct(B, A)) + KroneckerProduct(A*B, B*A) + >>> combine_kronecker(KroneckerProduct(A, B)+KroneckerProduct(B.T, A.T)) + KroneckerProduct(A + B.T, B + A.T) + >>> C = MatrixSymbol('C', n, n) + >>> D = MatrixSymbol('D', m, m) + >>> combine_kronecker(KroneckerProduct(C, D)**m) + KroneckerProduct(C**m, D**m) + """ + def haskron(expr): + return isinstance(expr, MatrixExpr) and expr.has(KroneckerProduct) + + rule = exhaust( + bottom_up(exhaust(condition(haskron, typed( + {MatAdd: kronecker_mat_add, + MatMul: kronecker_mat_mul, + MatPow: kronecker_mat_pow}))))) + result = rule(expr) + doit = getattr(result, 'doit', None) + if doit is not None: + return doit() + else: + return result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matadd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matadd.py new file mode 100644 index 0000000000000000000000000000000000000000..cfae1e5010e4077c7210c85c4315ed2404f245d7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matadd.py @@ -0,0 +1,155 @@ +from functools import reduce +import operator + +from sympy.core import Basic, sympify +from sympy.core.add import add, Add, _could_extract_minus_sign +from sympy.core.sorting import default_sort_key +from sympy.functions import adjoint +from sympy.matrices.matrixbase import MatrixBase +from sympy.matrices.expressions.transpose import transpose +from sympy.strategies import (rm_id, unpack, flatten, sort, condition, + exhaust, do_one, glom) +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.special import ZeroMatrix, GenericZeroMatrix +from sympy.matrices.expressions._shape import validate_matadd_integer as validate +from sympy.utilities.iterables import sift +from sympy.utilities.exceptions import sympy_deprecation_warning + +# XXX: MatAdd should perhaps not subclass directly from Add +class MatAdd(MatrixExpr, Add): + """A Sum of Matrix Expressions + + MatAdd inherits from and operates like SymPy Add + + Examples + ======== + + >>> from sympy import MatAdd, MatrixSymbol + >>> A = MatrixSymbol('A', 5, 5) + >>> B = MatrixSymbol('B', 5, 5) + >>> C = MatrixSymbol('C', 5, 5) + >>> MatAdd(A, B, C) + A + B + C + """ + is_MatAdd = True + + identity = GenericZeroMatrix() + + def __new__(cls, *args, evaluate=False, check=None, _sympify=True): + if not args: + return cls.identity + + # This must be removed aggressively in the constructor to avoid + # TypeErrors from GenericZeroMatrix().shape + args = list(filter(lambda i: cls.identity != i, args)) + if _sympify: + args = list(map(sympify, args)) + + if not all(isinstance(arg, MatrixExpr) for arg in args): + raise TypeError("Mix of Matrix and Scalar symbols") + + obj = Basic.__new__(cls, *args) + + if check is not None: + sympy_deprecation_warning( + "Passing check to MatAdd is deprecated and the check argument will be removed in a future version.", + deprecated_since_version="1.11", + active_deprecations_target='remove-check-argument-from-matrix-operations') + + if check is not False: + validate(*args) + + if evaluate: + obj = cls._evaluate(obj) + + return obj + + @classmethod + def _evaluate(cls, expr): + return canonicalize(expr) + + @property + def shape(self): + return self.args[0].shape + + def could_extract_minus_sign(self): + return _could_extract_minus_sign(self) + + def expand(self, **kwargs): + expanded = super(MatAdd, self).expand(**kwargs) + return self._evaluate(expanded) + + def _entry(self, i, j, **kwargs): + return Add(*[arg._entry(i, j, **kwargs) for arg in self.args]) + + def _eval_transpose(self): + return MatAdd(*[transpose(arg) for arg in self.args]).doit() + + def _eval_adjoint(self): + return MatAdd(*[adjoint(arg) for arg in self.args]).doit() + + def _eval_trace(self): + from .trace import trace + return Add(*[trace(arg) for arg in self.args]).doit() + + def doit(self, **hints): + deep = hints.get('deep', True) + if deep: + args = [arg.doit(**hints) for arg in self.args] + else: + args = self.args + return canonicalize(MatAdd(*args)) + + def _eval_derivative_matrix_lines(self, x): + add_lines = [arg._eval_derivative_matrix_lines(x) for arg in self.args] + return [j for i in add_lines for j in i] + +add.register_handlerclass((Add, MatAdd), MatAdd) + + +factor_of = lambda arg: arg.as_coeff_mmul()[0] +matrix_of = lambda arg: unpack(arg.as_coeff_mmul()[1]) +def combine(cnt, mat): + if cnt == 1: + return mat + else: + return cnt * mat + + +def merge_explicit(matadd): + """ Merge explicit MatrixBase arguments + + Examples + ======== + + >>> from sympy import MatrixSymbol, eye, Matrix, MatAdd, pprint + >>> from sympy.matrices.expressions.matadd import merge_explicit + >>> A = MatrixSymbol('A', 2, 2) + >>> B = eye(2) + >>> C = Matrix([[1, 2], [3, 4]]) + >>> X = MatAdd(A, B, C) + >>> pprint(X) + [1 0] [1 2] + A + [ ] + [ ] + [0 1] [3 4] + >>> pprint(merge_explicit(X)) + [2 2] + A + [ ] + [3 5] + """ + groups = sift(matadd.args, lambda arg: isinstance(arg, MatrixBase)) + if len(groups[True]) > 1: + return MatAdd(*(groups[False] + [reduce(operator.add, groups[True])])) + else: + return matadd + + +rules = (rm_id(lambda x: x == 0 or isinstance(x, ZeroMatrix)), + unpack, + flatten, + glom(matrix_of, factor_of, combine), + merge_explicit, + sort(default_sort_key)) + +canonicalize = exhaust(condition(lambda x: isinstance(x, MatAdd), + do_one(*rules))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py new file mode 100644 index 0000000000000000000000000000000000000000..a4e99296ccfcbdac5e09a86ecee020adf9831c73 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py @@ -0,0 +1,888 @@ +from __future__ import annotations +from functools import wraps + +from sympy.core import S, Integer, Basic, Mul, Add +from sympy.core.assumptions import check_assumptions +from sympy.core.decorators import call_highest_priority +from sympy.core.expr import Expr, ExprBuilder +from sympy.core.logic import FuzzyBool +from sympy.core.symbol import Str, Dummy, symbols, Symbol +from sympy.core.sympify import SympifyError, _sympify +from sympy.external.gmpy import SYMPY_INTS +from sympy.functions import conjugate, adjoint +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.matrices.exceptions import NonSquareMatrixError +from sympy.matrices.kind import MatrixKind +from sympy.matrices.matrixbase import MatrixBase +from sympy.multipledispatch import dispatch +from sympy.utilities.misc import filldedent + + +def _sympifyit(arg, retval=None): + # This version of _sympifyit sympifies MutableMatrix objects + def deco(func): + @wraps(func) + def __sympifyit_wrapper(a, b): + try: + b = _sympify(b) + return func(a, b) + except SympifyError: + return retval + + return __sympifyit_wrapper + + return deco + + +class MatrixExpr(Expr): + """Superclass for Matrix Expressions + + MatrixExprs represent abstract matrices, linear transformations represented + within a particular basis. + + Examples + ======== + + >>> from sympy import MatrixSymbol + >>> A = MatrixSymbol('A', 3, 3) + >>> y = MatrixSymbol('y', 3, 1) + >>> x = (A.T*A).I * A * y + + See Also + ======== + + MatrixSymbol, MatAdd, MatMul, Transpose, Inverse + """ + __slots__: tuple[str, ...] = () + + # Should not be considered iterable by the + # sympy.utilities.iterables.iterable function. Subclass that actually are + # iterable (i.e., explicit matrices) should set this to True. + _iterable = False + + _op_priority = 11.0 + + is_Matrix: bool = True + is_MatrixExpr: bool = True + is_Identity: FuzzyBool = None + is_Inverse = False + is_Transpose = False + is_ZeroMatrix = False + is_MatAdd = False + is_MatMul = False + + is_commutative = False + is_number = False + is_symbol = False + is_scalar = False + + kind: MatrixKind = MatrixKind() + + def __new__(cls, *args, **kwargs): + args = map(_sympify, args) + return Basic.__new__(cls, *args, **kwargs) + + # The following is adapted from the core Expr object + + @property + def shape(self) -> tuple[Expr, Expr]: + raise NotImplementedError + + @property + def _add_handler(self): + return MatAdd + + @property + def _mul_handler(self): + return MatMul + + def __neg__(self): + return MatMul(S.NegativeOne, self).doit() + + def __abs__(self): + raise NotImplementedError + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__radd__') + def __add__(self, other): + return MatAdd(self, other).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__add__') + def __radd__(self, other): + return MatAdd(other, self).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__rsub__') + def __sub__(self, other): + return MatAdd(self, -other).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__sub__') + def __rsub__(self, other): + return MatAdd(other, -self).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__rmul__') + def __mul__(self, other): + return MatMul(self, other).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__rmul__') + def __matmul__(self, other): + return MatMul(self, other).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__mul__') + def __rmul__(self, other): + return MatMul(other, self).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__mul__') + def __rmatmul__(self, other): + return MatMul(other, self).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__rpow__') + def __pow__(self, other): + return MatPow(self, other).doit() + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__pow__') + def __rpow__(self, other): + raise NotImplementedError("Matrix Power not defined") + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__rtruediv__') + def __truediv__(self, other): + return self * other**S.NegativeOne + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__truediv__') + def __rtruediv__(self, other): + raise NotImplementedError() + #return MatMul(other, Pow(self, S.NegativeOne)) + + @property + def rows(self): + return self.shape[0] + + @property + def cols(self): + return self.shape[1] + + @property + def is_square(self) -> bool | None: + rows, cols = self.shape + if isinstance(rows, Integer) and isinstance(cols, Integer): + return rows == cols + if rows == cols: + return True + return None + + def _eval_conjugate(self): + from sympy.matrices.expressions.adjoint import Adjoint + return Adjoint(Transpose(self)) + + def as_real_imag(self, deep=True, **hints): + return self._eval_as_real_imag() + + def _eval_as_real_imag(self): + real = S.Half * (self + self._eval_conjugate()) + im = (self - self._eval_conjugate())/(2*S.ImaginaryUnit) + return (real, im) + + def _eval_inverse(self): + return Inverse(self) + + def _eval_determinant(self): + return Determinant(self) + + def _eval_transpose(self): + return Transpose(self) + + def _eval_trace(self): + return None + + def _eval_power(self, exp): + """ + Override this in sub-classes to implement simplification of powers. The cases where the exponent + is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases. + """ + return MatPow(self, exp) + + def _eval_simplify(self, **kwargs): + if self.is_Atom: + return self + else: + from sympy.simplify import simplify + return self.func(*[simplify(x, **kwargs) for x in self.args]) + + def _eval_adjoint(self): + from sympy.matrices.expressions.adjoint import Adjoint + return Adjoint(self) + + def _eval_derivative_n_times(self, x, n): + return Basic._eval_derivative_n_times(self, x, n) + + def _eval_derivative(self, x): + # `x` is a scalar: + if self.has(x): + # See if there are other methods using it: + return super()._eval_derivative(x) + else: + return ZeroMatrix(*self.shape) + + @classmethod + def _check_dim(cls, dim): + """Helper function to check invalid matrix dimensions""" + ok = not dim.is_Float and check_assumptions( + dim, integer=True, nonnegative=True) + if ok is False: + raise ValueError( + "The dimension specification {} should be " + "a nonnegative integer.".format(dim)) + + + def _entry(self, i, j, **kwargs): + raise NotImplementedError( + "Indexing not implemented for %s" % self.__class__.__name__) + + def adjoint(self): + return adjoint(self) + + def as_coeff_Mul(self, rational=False): + """Efficiently extract the coefficient of a product.""" + return S.One, self + + def conjugate(self): + return conjugate(self) + + def transpose(self): + from sympy.matrices.expressions.transpose import transpose + return transpose(self) + + @property + def T(self): + '''Matrix transposition''' + return self.transpose() + + def inverse(self): + if self.is_square is False: + raise NonSquareMatrixError('Inverse of non-square matrix') + return self._eval_inverse() + + def inv(self): + return self.inverse() + + def det(self): + from sympy.matrices.expressions.determinant import det + return det(self) + + @property + def I(self): + return self.inverse() + + def valid_index(self, i, j): + def is_valid(idx): + return isinstance(idx, (int, Integer, Symbol, Expr)) + return (is_valid(i) and is_valid(j) and + (self.rows is None or + (i >= -self.rows) != False and (i < self.rows) != False) and + (j >= -self.cols) != False and (j < self.cols) != False) + + def __getitem__(self, key): + if not isinstance(key, tuple) and isinstance(key, slice): + from sympy.matrices.expressions.slice import MatrixSlice + return MatrixSlice(self, key, (0, None, 1)) + if isinstance(key, tuple) and len(key) == 2: + i, j = key + if isinstance(i, slice) or isinstance(j, slice): + from sympy.matrices.expressions.slice import MatrixSlice + return MatrixSlice(self, i, j) + i, j = _sympify(i), _sympify(j) + if self.valid_index(i, j) != False: + return self._entry(i, j) + else: + raise IndexError("Invalid indices (%s, %s)" % (i, j)) + elif isinstance(key, (SYMPY_INTS, Integer)): + # row-wise decomposition of matrix + rows, cols = self.shape + # allow single indexing if number of columns is known + if not isinstance(cols, Integer): + raise IndexError(filldedent(''' + Single indexing is only supported when the number + of columns is known.''')) + key = _sympify(key) + i = key // cols + j = key % cols + if self.valid_index(i, j) != False: + return self._entry(i, j) + else: + raise IndexError("Invalid index %s" % key) + elif isinstance(key, (Symbol, Expr)): + raise IndexError(filldedent(''' + Only integers may be used when addressing the matrix + with a single index.''')) + raise IndexError("Invalid index, wanted %s[i,j]" % self) + + def _is_shape_symbolic(self) -> bool: + return (not isinstance(self.rows, (SYMPY_INTS, Integer)) + or not isinstance(self.cols, (SYMPY_INTS, Integer))) + + def as_explicit(self): + """ + Returns a dense Matrix with elements represented explicitly + + Returns an object of type ImmutableDenseMatrix. + + Examples + ======== + + >>> from sympy import Identity + >>> I = Identity(3) + >>> I + I + >>> I.as_explicit() + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + See Also + ======== + as_mutable: returns mutable Matrix type + + """ + if self._is_shape_symbolic(): + raise ValueError( + 'Matrix with symbolic shape ' + 'cannot be represented explicitly.') + from sympy.matrices.immutable import ImmutableDenseMatrix + return ImmutableDenseMatrix([[self[i, j] + for j in range(self.cols)] + for i in range(self.rows)]) + + def as_mutable(self): + """ + Returns a dense, mutable matrix with elements represented explicitly + + Examples + ======== + + >>> from sympy import Identity + >>> I = Identity(3) + >>> I + I + >>> I.shape + (3, 3) + >>> I.as_mutable() + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + See Also + ======== + as_explicit: returns ImmutableDenseMatrix + """ + return self.as_explicit().as_mutable() + + def __array__(self, dtype=object, copy=None): + if copy is not None and not copy: + raise TypeError("Cannot implement copy=False when converting Matrix to ndarray") + from numpy import empty + a = empty(self.shape, dtype=object) + for i in range(self.rows): + for j in range(self.cols): + a[i, j] = self[i, j] + return a + + def equals(self, other): + """ + Test elementwise equality between matrices, potentially of different + types + + >>> from sympy import Identity, eye + >>> Identity(3).equals(eye(3)) + True + """ + return self.as_explicit().equals(other) + + def canonicalize(self): + return self + + def as_coeff_mmul(self): + return S.One, MatMul(self) + + @staticmethod + def from_index_summation(expr, first_index=None, last_index=None, dimensions=None): + r""" + Parse expression of matrices with explicitly summed indices into a + matrix expression without indices, if possible. + + This transformation expressed in mathematical notation: + + `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` + + Optional parameter ``first_index``: specify which free index to use as + the index starting the expression. + + Examples + ======== + + >>> from sympy import MatrixSymbol, MatrixExpr, Sum + >>> from sympy.abc import i, j, k, l, N + >>> A = MatrixSymbol("A", N, N) + >>> B = MatrixSymbol("B", N, N) + >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) + >>> MatrixExpr.from_index_summation(expr) + A*B + + Transposition is detected: + + >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) + >>> MatrixExpr.from_index_summation(expr) + A.T*B + + Detect the trace: + + >>> expr = Sum(A[i, i], (i, 0, N-1)) + >>> MatrixExpr.from_index_summation(expr) + Trace(A) + + More complicated expressions: + + >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) + >>> MatrixExpr.from_index_summation(expr) + A*B.T*A.T + """ + from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array + from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix + first_indices = [] + if first_index is not None: + first_indices.append(first_index) + if last_index is not None: + first_indices.append(last_index) + arr = convert_indexed_to_array(expr, first_indices=first_indices) + return convert_array_to_matrix(arr) + + def applyfunc(self, func): + from .applyfunc import ElementwiseApplyFunction + return ElementwiseApplyFunction(func, self) + + +@dispatch(MatrixExpr, Expr) +def _eval_is_eq(lhs, rhs): # noqa:F811 + return False + +@dispatch(MatrixExpr, MatrixExpr) # type: ignore +def _eval_is_eq(lhs, rhs): # noqa:F811 + if lhs.shape != rhs.shape: + return False + if (lhs - rhs).is_ZeroMatrix: + return True + +def get_postprocessor(cls): + def _postprocessor(expr): + # To avoid circular imports, we can't have MatMul/MatAdd on the top level + mat_class = {Mul: MatMul, Add: MatAdd}[cls] + nonmatrices = [] + matrices = [] + for term in expr.args: + if isinstance(term, MatrixExpr): + matrices.append(term) + else: + nonmatrices.append(term) + + if not matrices: + return cls._from_args(nonmatrices) + + if nonmatrices: + if cls == Mul: + for i in range(len(matrices)): + if not matrices[i].is_MatrixExpr: + # If one of the matrices explicit, absorb the scalar into it + # (doit will combine all explicit matrices into one, so it + # doesn't matter which) + matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices)) + nonmatrices = [] + break + + else: + # Maintain the ability to create Add(scalar, matrix) without + # raising an exception. That way different algorithms can + # replace matrix expressions with non-commutative symbols to + # manipulate them like non-commutative scalars. + return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) + + if mat_class == MatAdd: + return mat_class(*matrices).doit(deep=False) + return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False) + return _postprocessor + + +Basic._constructor_postprocessor_mapping[MatrixExpr] = { + "Mul": [get_postprocessor(Mul)], + "Add": [get_postprocessor(Add)], +} + + +def _matrix_derivative(expr, x, old_algorithm=False): + + if isinstance(expr, MatrixBase) or isinstance(x, MatrixBase): + # Do not use array expressions for explicit matrices: + old_algorithm = True + + if old_algorithm: + return _matrix_derivative_old_algorithm(expr, x) + + from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array + from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive + from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix + + array_expr = convert_matrix_to_array(expr) + diff_array_expr = array_derive(array_expr, x) + diff_matrix_expr = convert_array_to_matrix(diff_array_expr) + return diff_matrix_expr + + +def _matrix_derivative_old_algorithm(expr, x): + from sympy.tensor.array.array_derivatives import ArrayDerivative + lines = expr._eval_derivative_matrix_lines(x) + + parts = [i.build() for i in lines] + + from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix + + parts = [[convert_array_to_matrix(j) for j in i] for i in parts] + + def _get_shape(elem): + if isinstance(elem, MatrixExpr): + return elem.shape + return 1, 1 + + def get_rank(parts): + return sum(j not in (1, None) for i in parts for j in _get_shape(i)) + + ranks = [get_rank(i) for i in parts] + rank = ranks[0] + + def contract_one_dims(parts): + if len(parts) == 1: + return parts[0] + else: + p1, p2 = parts[:2] + if p2.is_Matrix: + p2 = p2.T + if p1 == Identity(1): + pbase = p2 + elif p2 == Identity(1): + pbase = p1 + else: + pbase = p1*p2 + if len(parts) == 2: + return pbase + else: # len(parts) > 2 + if pbase.is_Matrix: + raise ValueError("") + return pbase*Mul.fromiter(parts[2:]) + + if rank <= 2: + return Add.fromiter([contract_one_dims(i) for i in parts]) + + return ArrayDerivative(expr, x) + + +class MatrixElement(Expr): + parent = property(lambda self: self.args[0]) + i = property(lambda self: self.args[1]) + j = property(lambda self: self.args[2]) + _diff_wrt = True + is_symbol = True + is_commutative = True + + def __new__(cls, name, n, m): + n, m = map(_sympify, (n, m)) + if isinstance(name, str): + name = Symbol(name) + else: + if isinstance(name, MatrixBase): + if n.is_Integer and m.is_Integer: + return name[n, m] + name = _sympify(name) # change mutable into immutable + else: + name = _sympify(name) + if not isinstance(name.kind, MatrixKind): + raise TypeError("First argument of MatrixElement should be a matrix") + if not getattr(name, 'valid_index', lambda n, m: True)(n, m): + raise IndexError('indices out of range') + obj = Expr.__new__(cls, name, n, m) + return obj + + @property + def symbol(self): + return self.args[0] + + def doit(self, **hints): + deep = hints.get('deep', True) + if deep: + args = [arg.doit(**hints) for arg in self.args] + else: + args = self.args + return args[0][args[1], args[2]] + + @property + def indices(self): + return self.args[1:] + + def _eval_derivative(self, v): + + if not isinstance(v, MatrixElement): + return self.parent.diff(v)[self.i, self.j] + + M = self.args[0] + + m, n = self.parent.shape + + if M == v.args[0]: + return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \ + KroneckerDelta(self.args[2], v.args[2], (0, n-1)) + + if isinstance(M, Inverse): + from sympy.concrete.summations import Sum + i, j = self.args[1:] + i1, i2 = symbols("z1, z2", cls=Dummy) + Y = M.args[0] + r1, r2 = Y.shape + return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1)) + + if self.has(v.args[0]): + return None + + return S.Zero + + +class MatrixSymbol(MatrixExpr): + """Symbolic representation of a Matrix object + + Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and + can be included in Matrix Expressions + + Examples + ======== + + >>> from sympy import MatrixSymbol, Identity + >>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix + >>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix + >>> A.shape + (3, 4) + >>> 2*A*B + Identity(3) + I + 2*A*B + """ + is_commutative = False + is_symbol = True + _diff_wrt = True + + def __new__(cls, name, n, m): + n, m = _sympify(n), _sympify(m) + + cls._check_dim(m) + cls._check_dim(n) + + if isinstance(name, str): + name = Str(name) + obj = Basic.__new__(cls, name, n, m) + return obj + + @property + def shape(self): + return self.args[1], self.args[2] + + @property + def name(self): + return self.args[0].name + + def _entry(self, i, j, **kwargs): + return MatrixElement(self, i, j) + + @property + def free_symbols(self): + return {self} + + def _eval_simplify(self, **kwargs): + return self + + def _eval_derivative(self, x): + # x is a scalar: + return ZeroMatrix(self.shape[0], self.shape[1]) + + def _eval_derivative_matrix_lines(self, x): + if self != x: + first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero + second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero + return [_LeftRightArgs( + [first, second], + )] + else: + first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One + second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One + return [_LeftRightArgs( + [first, second], + )] + + +def matrix_symbols(expr): + return [sym for sym in expr.free_symbols if sym.is_Matrix] + + +class _LeftRightArgs: + r""" + Helper class to compute matrix derivatives. + + The logic: when an expression is derived by a matrix `X_{mn}`, two lines of + matrix multiplications are created: the one contracted to `m` (first line), + and the one contracted to `n` (second line). + + Transposition flips the side by which new matrices are connected to the + lines. + + The trace connects the end of the two lines. + """ + + def __init__(self, lines, higher=S.One): + self._lines = list(lines) + self._first_pointer_parent = self._lines + self._first_pointer_index = 0 + self._first_line_index = 0 + self._second_pointer_parent = self._lines + self._second_pointer_index = 1 + self._second_line_index = 1 + self.higher = higher + + @property + def first_pointer(self): + return self._first_pointer_parent[self._first_pointer_index] + + @first_pointer.setter + def first_pointer(self, value): + self._first_pointer_parent[self._first_pointer_index] = value + + @property + def second_pointer(self): + return self._second_pointer_parent[self._second_pointer_index] + + @second_pointer.setter + def second_pointer(self, value): + self._second_pointer_parent[self._second_pointer_index] = value + + def __repr__(self): + built = [self._build(i) for i in self._lines] + return "_LeftRightArgs(lines=%s, higher=%s)" % ( + built, + self.higher, + ) + + def transpose(self): + self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent + self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index + self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index + return self + + @staticmethod + def _build(expr): + if isinstance(expr, ExprBuilder): + return expr.build() + if isinstance(expr, list): + if len(expr) == 1: + return expr[0] + else: + return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]]) + else: + return expr + + def build(self): + data = [self._build(i) for i in self._lines] + if self.higher != 1: + data += [self._build(self.higher)] + data = list(data) + return data + + def matrix_form(self): + if self.first != 1 and self.higher != 1: + raise ValueError("higher dimensional array cannot be represented") + + def _get_shape(elem): + if isinstance(elem, MatrixExpr): + return elem.shape + return (None, None) + + if _get_shape(self.first)[1] != _get_shape(self.second)[1]: + # Remove one-dimensional identity matrices: + # (this is needed by `a.diff(a)` where `a` is a vector) + if _get_shape(self.second) == (1, 1): + return self.first*self.second[0, 0] + if _get_shape(self.first) == (1, 1): + return self.first[1, 1]*self.second.T + raise ValueError("incompatible shapes") + if self.first != 1: + return self.first*self.second.T + else: + return self.higher + + def rank(self): + """ + Number of dimensions different from trivial (warning: not related to + matrix rank). + """ + rank = 0 + if self.first != 1: + rank += sum(i != 1 for i in self.first.shape) + if self.second != 1: + rank += sum(i != 1 for i in self.second.shape) + if self.higher != 1: + rank += 2 + return rank + + def _multiply_pointer(self, pointer, other): + from ...tensor.array.expressions.array_expressions import ArrayTensorProduct + from ...tensor.array.expressions.array_expressions import ArrayContraction + + subexpr = ExprBuilder( + ArrayContraction, + [ + ExprBuilder( + ArrayTensorProduct, + [ + pointer, + other + ] + ), + (1, 2) + ], + validator=ArrayContraction._validate + ) + + return subexpr + + def append_first(self, other): + self.first_pointer *= other + + def append_second(self, other): + self.second_pointer *= other + + +def _make_matrix(x): + from sympy.matrices.immutable import ImmutableDenseMatrix + if isinstance(x, MatrixExpr): + return x + return ImmutableDenseMatrix([[x]]) + + +from .matmul import MatMul +from .matadd import MatAdd +from .matpow import MatPow +from .transpose import Transpose +from .inverse import Inverse +from .special import ZeroMatrix, Identity +from .determinant import Determinant diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..1c46f7ff5251d89793423f92ea02d7243601de3f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py @@ -0,0 +1,496 @@ +from sympy.assumptions.ask import ask, Q +from sympy.assumptions.refine import handlers_dict +from sympy.core import Basic, sympify, S +from sympy.core.mul import mul, Mul +from sympy.core.numbers import Number, Integer +from sympy.core.symbol import Dummy +from sympy.functions import adjoint +from sympy.strategies import (rm_id, unpack, typed, flatten, exhaust, + do_one, new) +from sympy.matrices.exceptions import NonInvertibleMatrixError +from sympy.matrices.matrixbase import MatrixBase +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.matrices.expressions._shape import validate_matmul_integer as validate + +from .inverse import Inverse +from .matexpr import MatrixExpr +from .matpow import MatPow +from .transpose import transpose +from .permutation import PermutationMatrix +from .special import ZeroMatrix, Identity, GenericIdentity, OneMatrix + + +# XXX: MatMul should perhaps not subclass directly from Mul +class MatMul(MatrixExpr, Mul): + """ + A product of matrix expressions + + Examples + ======== + + >>> from sympy import MatMul, MatrixSymbol + >>> A = MatrixSymbol('A', 5, 4) + >>> B = MatrixSymbol('B', 4, 3) + >>> C = MatrixSymbol('C', 3, 6) + >>> MatMul(A, B, C) + A*B*C + """ + is_MatMul = True + + identity = GenericIdentity() + + def __new__(cls, *args, evaluate=False, check=None, _sympify=True): + if not args: + return cls.identity + + # This must be removed aggressively in the constructor to avoid + # TypeErrors from GenericIdentity().shape + args = list(filter(lambda i: cls.identity != i, args)) + if _sympify: + args = list(map(sympify, args)) + obj = Basic.__new__(cls, *args) + factor, matrices = obj.as_coeff_matrices() + + if check is not None: + sympy_deprecation_warning( + "Passing check to MatMul is deprecated and the check argument will be removed in a future version.", + deprecated_since_version="1.11", + active_deprecations_target='remove-check-argument-from-matrix-operations') + + if check is not False: + validate(*matrices) + + if not matrices: + # Should it be + # + # return Basic.__neq__(cls, factor, GenericIdentity()) ? + return factor + + if evaluate: + return cls._evaluate(obj) + + return obj + + @classmethod + def _evaluate(cls, expr): + return canonicalize(expr) + + @property + def shape(self): + matrices = [arg for arg in self.args if arg.is_Matrix] + return (matrices[0].rows, matrices[-1].cols) + + def _entry(self, i, j, expand=True, **kwargs): + # Avoid cyclic imports + from sympy.concrete.summations import Sum + from sympy.matrices.immutable import ImmutableMatrix + + coeff, matrices = self.as_coeff_matrices() + + if len(matrices) == 1: # situation like 2*X, matmul is just X + return coeff * matrices[0][i, j] + + indices = [None]*(len(matrices) + 1) + ind_ranges = [None]*(len(matrices) - 1) + indices[0] = i + indices[-1] = j + + def f(): + counter = 1 + while True: + yield Dummy("i_%i" % counter) + counter += 1 + + dummy_generator = kwargs.get("dummy_generator", f()) + + for i in range(1, len(matrices)): + indices[i] = next(dummy_generator) + + for i, arg in enumerate(matrices[:-1]): + ind_ranges[i] = arg.shape[1] - 1 + matrices = [arg._entry(indices[i], indices[i+1], dummy_generator=dummy_generator) for i, arg in enumerate(matrices)] + expr_in_sum = Mul.fromiter(matrices) + if any(v.has(ImmutableMatrix) for v in matrices): + expand = True + result = coeff*Sum( + expr_in_sum, + *zip(indices[1:-1], [0]*len(ind_ranges), ind_ranges) + ) + + # Don't waste time in result.doit() if the sum bounds are symbolic + if not any(isinstance(v, (Integer, int)) for v in ind_ranges): + expand = False + return result.doit() if expand else result + + def as_coeff_matrices(self): + scalars = [x for x in self.args if not x.is_Matrix] + matrices = [x for x in self.args if x.is_Matrix] + coeff = Mul(*scalars) + if coeff.is_commutative is False: + raise NotImplementedError("noncommutative scalars in MatMul are not supported.") + + return coeff, matrices + + def as_coeff_mmul(self): + coeff, matrices = self.as_coeff_matrices() + return coeff, MatMul(*matrices) + + def expand(self, **kwargs): + expanded = super(MatMul, self).expand(**kwargs) + return self._evaluate(expanded) + + def _eval_transpose(self): + """Transposition of matrix multiplication. + + Notes + ===== + + The following rules are applied. + + Transposition for matrix multiplied with another matrix: + `\\left(A B\\right)^{T} = B^{T} A^{T}` + + Transposition for matrix multiplied with scalar: + `\\left(c A\\right)^{T} = c A^{T}` + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Transpose + """ + coeff, matrices = self.as_coeff_matrices() + return MatMul( + coeff, *[transpose(arg) for arg in matrices[::-1]]).doit() + + def _eval_adjoint(self): + return MatMul(*[adjoint(arg) for arg in self.args[::-1]]).doit() + + def _eval_trace(self): + factor, mmul = self.as_coeff_mmul() + if factor != 1: + from .trace import trace + return factor * trace(mmul.doit()) + + def _eval_determinant(self): + from sympy.matrices.expressions.determinant import Determinant + factor, matrices = self.as_coeff_matrices() + square_matrices = only_squares(*matrices) + return factor**self.rows * Mul(*list(map(Determinant, square_matrices))) + + def _eval_inverse(self): + if all(arg.is_square for arg in self.args if isinstance(arg, MatrixExpr)): + return MatMul(*( + arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1 + for arg in self.args[::-1] + ) + ).doit() + return Inverse(self) + + def doit(self, **hints): + deep = hints.get('deep', True) + if deep: + args = tuple(arg.doit(**hints) for arg in self.args) + else: + args = self.args + + # treat scalar*MatrixSymbol or scalar*MatPow separately + expr = canonicalize(MatMul(*args)) + return expr + + # Needed for partial compatibility with Mul + def args_cnc(self, cset=False, warn=True, **kwargs): + coeff_c = [x for x in self.args if x.is_commutative] + coeff_nc = [x for x in self.args if not x.is_commutative] + if cset: + clen = len(coeff_c) + coeff_c = set(coeff_c) + if clen and warn and len(coeff_c) != clen: + raise ValueError('repeated commutative arguments: %s' % + [ci for ci in coeff_c if list(self.args).count(ci) > 1]) + return [coeff_c, coeff_nc] + + def _eval_derivative_matrix_lines(self, x): + from .transpose import Transpose + with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] + lines = [] + for ind in with_x_ind: + left_args = self.args[:ind] + right_args = self.args[ind+1:] + + if right_args: + right_mat = MatMul.fromiter(right_args) + else: + right_mat = Identity(self.shape[1]) + if left_args: + left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)]) + else: + left_rev = Identity(self.shape[0]) + + d = self.args[ind]._eval_derivative_matrix_lines(x) + for i in d: + i.append_first(left_rev) + i.append_second(right_mat) + lines.append(i) + + return lines + +mul.register_handlerclass((Mul, MatMul), MatMul) + + +# Rules +def newmul(*args): + if args[0] == 1: + args = args[1:] + return new(MatMul, *args) + +def any_zeros(mul): + if any(arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix) + for arg in mul.args): + matrices = [arg for arg in mul.args if arg.is_Matrix] + return ZeroMatrix(matrices[0].rows, matrices[-1].cols) + return mul + +def merge_explicit(matmul): + """ Merge explicit MatrixBase arguments + + >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint + >>> from sympy.matrices.expressions.matmul import merge_explicit + >>> A = MatrixSymbol('A', 2, 2) + >>> B = Matrix([[1, 1], [1, 1]]) + >>> C = Matrix([[1, 2], [3, 4]]) + >>> X = MatMul(A, B, C) + >>> pprint(X) + [1 1] [1 2] + A*[ ]*[ ] + [1 1] [3 4] + >>> pprint(merge_explicit(X)) + [4 6] + A*[ ] + [4 6] + + >>> X = MatMul(B, A, C) + >>> pprint(X) + [1 1] [1 2] + [ ]*A*[ ] + [1 1] [3 4] + >>> pprint(merge_explicit(X)) + [1 1] [1 2] + [ ]*A*[ ] + [1 1] [3 4] + """ + if not any(isinstance(arg, MatrixBase) for arg in matmul.args): + return matmul + newargs = [] + last = matmul.args[0] + for arg in matmul.args[1:]: + if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)): + last = last * arg + else: + newargs.append(last) + last = arg + newargs.append(last) + + return MatMul(*newargs) + +def remove_ids(mul): + """ Remove Identities from a MatMul + + This is a modified version of sympy.strategies.rm_id. + This is necessary because MatMul may contain both MatrixExprs and Exprs + as args. + + See Also + ======== + + sympy.strategies.rm_id + """ + # Separate Exprs from MatrixExprs in args + factor, mmul = mul.as_coeff_mmul() + # Apply standard rm_id for MatMuls + result = rm_id(lambda x: x.is_Identity is True)(mmul) + if result != mmul: + return newmul(factor, *result.args) # Recombine and return + else: + return mul + +def factor_in_front(mul): + factor, matrices = mul.as_coeff_matrices() + if factor != 1: + return newmul(factor, *matrices) + return mul + +def combine_powers(mul): + r"""Combine consecutive powers with the same base into one, e.g. + $$A \times A^2 \Rightarrow A^3$$ + + This also cancels out the possible matrix inverses using the + knowledgebase of :class:`~.Inverse`, e.g., + $$ Y \times X \times X^{-1} \Rightarrow Y $$ + """ + factor, args = mul.as_coeff_matrices() + new_args = [args[0]] + + for i in range(1, len(args)): + A = new_args[-1] + B = args[i] + + if isinstance(B, Inverse) and isinstance(B.arg, MatMul): + Bargs = B.arg.args + l = len(Bargs) + if list(Bargs) == new_args[-l:]: + new_args = new_args[:-l] + [Identity(B.shape[0])] + continue + + if isinstance(A, Inverse) and isinstance(A.arg, MatMul): + Aargs = A.arg.args + l = len(Aargs) + if list(Aargs) == args[i:i+l]: + identity = Identity(A.shape[0]) + new_args[-1] = identity + for j in range(i, i+l): + args[j] = identity + continue + + if A.is_square == False or B.is_square == False: + new_args.append(B) + continue + + if isinstance(A, MatPow): + A_base, A_exp = A.args + else: + A_base, A_exp = A, S.One + + if isinstance(B, MatPow): + B_base, B_exp = B.args + else: + B_base, B_exp = B, S.One + + if A_base == B_base: + new_exp = A_exp + B_exp + new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) + continue + elif not isinstance(B_base, MatrixBase): + try: + B_base_inv = B_base.inverse() + except NonInvertibleMatrixError: + B_base_inv = None + if B_base_inv is not None and A_base == B_base_inv: + new_exp = A_exp - B_exp + new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) + continue + new_args.append(B) + + return newmul(factor, *new_args) + +def combine_permutations(mul): + """Refine products of permutation matrices as the products of cycles. + """ + args = mul.args + l = len(args) + if l < 2: + return mul + + result = [args[0]] + for i in range(1, l): + A = result[-1] + B = args[i] + if isinstance(A, PermutationMatrix) and \ + isinstance(B, PermutationMatrix): + cycle_1 = A.args[0] + cycle_2 = B.args[0] + result[-1] = PermutationMatrix(cycle_1 * cycle_2) + else: + result.append(B) + + return MatMul(*result) + +def combine_one_matrices(mul): + """ + Combine products of OneMatrix + + e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4) + """ + factor, args = mul.as_coeff_matrices() + new_args = [args[0]] + + for B in args[1:]: + A = new_args[-1] + if not isinstance(A, OneMatrix) or not isinstance(B, OneMatrix): + new_args.append(B) + continue + new_args.pop() + new_args.append(OneMatrix(A.shape[0], B.shape[1])) + factor *= A.shape[1] + + return newmul(factor, *new_args) + +def distribute_monom(mul): + """ + Simplify MatMul expressions but distributing + rational term to MatMul. + + e.g. 2*(A+B) -> 2*A + 2*B + """ + args = mul.args + if len(args) == 2: + from .matadd import MatAdd + if args[0].is_MatAdd and args[1].is_Rational: + return MatAdd(*[MatMul(mat, args[1]).doit() for mat in args[0].args]) + if args[1].is_MatAdd and args[0].is_Rational: + return MatAdd(*[MatMul(args[0], mat).doit() for mat in args[1].args]) + return mul + +rules = ( + distribute_monom, any_zeros, remove_ids, combine_one_matrices, combine_powers, unpack, rm_id(lambda x: x == 1), + merge_explicit, factor_in_front, flatten, combine_permutations) + +canonicalize = exhaust(typed({MatMul: do_one(*rules)})) + +def only_squares(*matrices): + """factor matrices only if they are square""" + if matrices[0].rows != matrices[-1].cols: + raise RuntimeError("Invalid matrices being multiplied") + out = [] + start = 0 + for i, M in enumerate(matrices): + if M.cols == matrices[start].rows: + out.append(MatMul(*matrices[start:i+1]).doit()) + start = i+1 + return out + + +def refine_MatMul(expr, assumptions): + """ + >>> from sympy import MatrixSymbol, Q, assuming, refine + >>> X = MatrixSymbol('X', 2, 2) + >>> expr = X * X.T + >>> print(expr) + X*X.T + >>> with assuming(Q.orthogonal(X)): + ... print(refine(expr)) + I + """ + newargs = [] + exprargs = [] + + for args in expr.args: + if args.is_Matrix: + exprargs.append(args) + else: + newargs.append(args) + + last = exprargs[0] + for arg in exprargs[1:]: + if arg == last.T and ask(Q.orthogonal(arg), assumptions): + last = Identity(arg.shape[0]) + elif arg == last.conjugate() and ask(Q.unitary(arg), assumptions): + last = Identity(arg.shape[0]) + else: + newargs.append(last) + last = arg + newargs.append(last) + + return MatMul(*newargs) + + +handlers_dict['MatMul'] = refine_MatMul diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py new file mode 100644 index 0000000000000000000000000000000000000000..b6472995e134e9e5ebfd28a901480665d1531275 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py @@ -0,0 +1,150 @@ +from .matexpr import MatrixExpr +from .special import Identity +from sympy.core import S +from sympy.core.expr import ExprBuilder +from sympy.core.cache import cacheit +from sympy.core.power import Pow +from sympy.core.sympify import _sympify +from sympy.matrices import MatrixBase +from sympy.matrices.exceptions import NonSquareMatrixError + + +class MatPow(MatrixExpr): + def __new__(cls, base, exp, evaluate=False, **options): + base = _sympify(base) + if not base.is_Matrix: + raise TypeError("MatPow base should be a matrix") + + if base.is_square is False: + raise NonSquareMatrixError("Power of non-square matrix %s" % base) + + exp = _sympify(exp) + obj = super().__new__(cls, base, exp) + + if evaluate: + obj = obj.doit(deep=False) + + return obj + + @property + def base(self): + return self.args[0] + + @property + def exp(self): + return self.args[1] + + @property + def shape(self): + return self.base.shape + + @cacheit + def _get_explicit_matrix(self): + return self.base.as_explicit()**self.exp + + def _entry(self, i, j, **kwargs): + from sympy.matrices.expressions import MatMul + A = self.doit() + if isinstance(A, MatPow): + # We still have a MatPow, make an explicit MatMul out of it. + if A.exp.is_Integer and A.exp.is_positive: + A = MatMul(*[A.base for k in range(A.exp)]) + elif not self._is_shape_symbolic(): + return A._get_explicit_matrix()[i, j] + else: + # Leave the expression unevaluated: + from sympy.matrices.expressions.matexpr import MatrixElement + return MatrixElement(self, i, j) + return A[i, j] + + def doit(self, **hints): + if hints.get('deep', True): + base, exp = (arg.doit(**hints) for arg in self.args) + else: + base, exp = self.args + + # combine all powers, e.g. (A ** 2) ** 3 -> A ** 6 + while isinstance(base, MatPow): + exp *= base.args[1] + base = base.args[0] + + if isinstance(base, MatrixBase): + # Delegate + return base ** exp + + # Handle simple cases so that _eval_power() in MatrixExpr sub-classes can ignore them + if exp == S.One: + return base + if exp == S.Zero: + return Identity(base.rows) + if exp == S.NegativeOne: + from sympy.matrices.expressions import Inverse + return Inverse(base).doit(**hints) + + eval_power = getattr(base, '_eval_power', None) + if eval_power is not None: + return eval_power(exp) + + return MatPow(base, exp) + + def _eval_transpose(self): + base, exp = self.args + return MatPow(base.transpose(), exp) + + def _eval_adjoint(self): + base, exp = self.args + return MatPow(base.adjoint(), exp) + + def _eval_conjugate(self): + base, exp = self.args + return MatPow(base.conjugate(), exp) + + def _eval_derivative(self, x): + return Pow._eval_derivative(self, x) + + def _eval_derivative_matrix_lines(self, x): + from sympy.tensor.array.expressions.array_expressions import ArrayContraction + from ...tensor.array.expressions.array_expressions import ArrayTensorProduct + from .matmul import MatMul + from .inverse import Inverse + exp = self.exp + if self.base.shape == (1, 1) and not exp.has(x): + lr = self.base._eval_derivative_matrix_lines(x) + for i in lr: + subexpr = ExprBuilder( + ArrayContraction, + [ + ExprBuilder( + ArrayTensorProduct, + [ + Identity(1), + i._lines[0], + exp*self.base**(exp-1), + i._lines[1], + Identity(1), + ] + ), + (0, 3, 4), (5, 7, 8) + ], + validator=ArrayContraction._validate + ) + i._first_pointer_parent = subexpr.args[0].args + i._first_pointer_index = 0 + i._second_pointer_parent = subexpr.args[0].args + i._second_pointer_index = 4 + i._lines = [subexpr] + return lr + if (exp > 0) == True: + newexpr = MatMul.fromiter([self.base for i in range(exp)]) + elif (exp == -1) == True: + return Inverse(self.base)._eval_derivative_matrix_lines(x) + elif (exp < 0) == True: + newexpr = MatMul.fromiter([Inverse(self.base) for i in range(-exp)]) + elif (exp == 0) == True: + return self.doit()._eval_derivative_matrix_lines(x) + else: + raise NotImplementedError("cannot evaluate %s derived by %s" % (self, x)) + return newexpr._eval_derivative_matrix_lines(x) + + def _eval_inverse(self): + return MatPow(self.base, -self.exp) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/permutation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/permutation.py new file mode 100644 index 0000000000000000000000000000000000000000..5634fa941a53d8890583fe61bb29bc34f4e6000d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/permutation.py @@ -0,0 +1,303 @@ +from sympy.core import S +from sympy.core.sympify import _sympify +from sympy.functions import KroneckerDelta + +from .matexpr import MatrixExpr +from .special import ZeroMatrix, Identity, OneMatrix + + +class PermutationMatrix(MatrixExpr): + """A Permutation Matrix + + Parameters + ========== + + perm : Permutation + The permutation the matrix uses. + + The size of the permutation determines the matrix size. + + See the documentation of + :class:`sympy.combinatorics.permutations.Permutation` for + the further information of how to create a permutation object. + + Examples + ======== + + >>> from sympy import Matrix, PermutationMatrix + >>> from sympy.combinatorics import Permutation + + Creating a permutation matrix: + + >>> p = Permutation(1, 2, 0) + >>> P = PermutationMatrix(p) + >>> P = P.as_explicit() + >>> P + Matrix([ + [0, 1, 0], + [0, 0, 1], + [1, 0, 0]]) + + Permuting a matrix row and column: + + >>> M = Matrix([0, 1, 2]) + >>> Matrix(P*M) + Matrix([ + [1], + [2], + [0]]) + + >>> Matrix(M.T*P) + Matrix([[2, 0, 1]]) + + See Also + ======== + + sympy.combinatorics.permutations.Permutation + """ + + def __new__(cls, perm): + from sympy.combinatorics.permutations import Permutation + + perm = _sympify(perm) + if not isinstance(perm, Permutation): + raise ValueError( + "{} must be a SymPy Permutation instance.".format(perm)) + + return super().__new__(cls, perm) + + @property + def shape(self): + size = self.args[0].size + return (size, size) + + @property + def is_Identity(self): + return self.args[0].is_Identity + + def doit(self, **hints): + if self.is_Identity: + return Identity(self.rows) + return self + + def _entry(self, i, j, **kwargs): + perm = self.args[0] + return KroneckerDelta(perm.apply(i), j) + + def _eval_power(self, exp): + return PermutationMatrix(self.args[0] ** exp).doit() + + def _eval_inverse(self): + return PermutationMatrix(self.args[0] ** -1) + + _eval_transpose = _eval_adjoint = _eval_inverse + + def _eval_determinant(self): + sign = self.args[0].signature() + if sign == 1: + return S.One + elif sign == -1: + return S.NegativeOne + raise NotImplementedError + + def _eval_rewrite_as_BlockDiagMatrix(self, *args, **kwargs): + from sympy.combinatorics.permutations import Permutation + from .blockmatrix import BlockDiagMatrix + + perm = self.args[0] + full_cyclic_form = perm.full_cyclic_form + + cycles_picks = [] + + # Stage 1. Decompose the cycles into the blockable form. + a, b, c = 0, 0, 0 + flag = False + for cycle in full_cyclic_form: + l = len(cycle) + m = max(cycle) + + if not flag: + if m + 1 > a + l: + flag = True + temp = [cycle] + b = m + c = l + else: + cycles_picks.append([cycle]) + a += l + + else: + if m > b: + if m + 1 == a + c + l: + temp.append(cycle) + cycles_picks.append(temp) + flag = False + a = m+1 + else: + b = m + temp.append(cycle) + c += l + else: + if b + 1 == a + c + l: + temp.append(cycle) + cycles_picks.append(temp) + flag = False + a = b+1 + else: + temp.append(cycle) + c += l + + # Stage 2. Normalize each decomposed cycles and build matrix. + p = 0 + args = [] + for pick in cycles_picks: + new_cycles = [] + l = 0 + for cycle in pick: + new_cycle = [i - p for i in cycle] + new_cycles.append(new_cycle) + l += len(cycle) + p += l + perm = Permutation(new_cycles) + mat = PermutationMatrix(perm) + args.append(mat) + + return BlockDiagMatrix(*args) + + +class MatrixPermute(MatrixExpr): + r"""Symbolic representation for permuting matrix rows or columns. + + Parameters + ========== + + perm : Permutation, PermutationMatrix + The permutation to use for permuting the matrix. + The permutation can be resized to the suitable one, + + axis : 0 or 1 + The axis to permute alongside. + If `0`, it will permute the matrix rows. + If `1`, it will permute the matrix columns. + + Notes + ===== + + This follows the same notation used in + :meth:`sympy.matrices.matrixbase.MatrixBase.permute`. + + Examples + ======== + + >>> from sympy import Matrix, MatrixPermute + >>> from sympy.combinatorics import Permutation + + Permuting the matrix rows: + + >>> p = Permutation(1, 2, 0) + >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> B = MatrixPermute(A, p, axis=0) + >>> B.as_explicit() + Matrix([ + [4, 5, 6], + [7, 8, 9], + [1, 2, 3]]) + + Permuting the matrix columns: + + >>> B = MatrixPermute(A, p, axis=1) + >>> B.as_explicit() + Matrix([ + [2, 3, 1], + [5, 6, 4], + [8, 9, 7]]) + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.permute + """ + def __new__(cls, mat, perm, axis=S.Zero): + from sympy.combinatorics.permutations import Permutation + + mat = _sympify(mat) + if not mat.is_Matrix: + raise ValueError( + "{} must be a SymPy matrix instance.".format(perm)) + + perm = _sympify(perm) + if isinstance(perm, PermutationMatrix): + perm = perm.args[0] + + if not isinstance(perm, Permutation): + raise ValueError( + "{} must be a SymPy Permutation or a PermutationMatrix " \ + "instance".format(perm)) + + axis = _sympify(axis) + if axis not in (0, 1): + raise ValueError("The axis must be 0 or 1.") + + mat_size = mat.shape[axis] + if mat_size != perm.size: + try: + perm = perm.resize(mat_size) + except ValueError: + raise ValueError( + "Size does not match between the permutation {} " + "and the matrix {} threaded over the axis {} " + "and cannot be converted." + .format(perm, mat, axis)) + + return super().__new__(cls, mat, perm, axis) + + def doit(self, deep=True, **hints): + mat, perm, axis = self.args + + if deep: + mat = mat.doit(deep=deep, **hints) + perm = perm.doit(deep=deep, **hints) + + if perm.is_Identity: + return mat + + if mat.is_Identity: + if axis is S.Zero: + return PermutationMatrix(perm) + elif axis is S.One: + return PermutationMatrix(perm**-1) + + if isinstance(mat, (ZeroMatrix, OneMatrix)): + return mat + + if isinstance(mat, MatrixPermute) and mat.args[2] == axis: + return MatrixPermute(mat.args[0], perm * mat.args[1], axis) + + return self + + @property + def shape(self): + return self.args[0].shape + + def _entry(self, i, j, **kwargs): + mat, perm, axis = self.args + + if axis == 0: + return mat[perm.apply(i), j] + elif axis == 1: + return mat[i, perm.apply(j)] + + def _eval_rewrite_as_MatMul(self, *args, **kwargs): + from .matmul import MatMul + + mat, perm, axis = self.args + + deep = kwargs.get("deep", True) + + if deep: + mat = mat.rewrite(MatMul) + + if axis == 0: + return MatMul(PermutationMatrix(perm), mat) + elif axis == 1: + return MatMul(mat, PermutationMatrix(perm**-1)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4930ea8f1b058977a8dd1abdc62f1f5e2195c1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py @@ -0,0 +1,68 @@ +from sympy.core.assumptions import check_assumptions +from sympy.core.logic import fuzzy_and +from sympy.core.sympify import _sympify +from sympy.matrices.kind import MatrixKind +from sympy.sets.sets import Set, SetKind +from sympy.core.kind import NumberKind +from .matexpr import MatrixExpr + + +class MatrixSet(Set): + """ + MatrixSet represents the set of matrices with ``shape = (n, m)`` over the + given set. + + Examples + ======== + + >>> from sympy.matrices import MatrixSet + >>> from sympy import S, I, Matrix + >>> M = MatrixSet(2, 2, set=S.Reals) + >>> X = Matrix([[1, 2], [3, 4]]) + >>> X in M + True + >>> X = Matrix([[1, 2], [I, 4]]) + >>> X in M + False + + """ + is_empty = False + + def __new__(cls, n, m, set): + n, m, set = _sympify(n), _sympify(m), _sympify(set) + cls._check_dim(n) + cls._check_dim(m) + if not isinstance(set, Set): + raise TypeError("{} should be an instance of Set.".format(set)) + return Set.__new__(cls, n, m, set) + + @property + def shape(self): + return self.args[:2] + + @property + def set(self): + return self.args[2] + + def _contains(self, other): + if not isinstance(other, MatrixExpr): + raise TypeError("{} should be an instance of MatrixExpr.".format(other)) + if other.shape != self.shape: + are_symbolic = any(_sympify(x).is_Symbol for x in other.shape + self.shape) + if are_symbolic: + return None + return False + return fuzzy_and(self.set.contains(x) for x in other) + + @classmethod + def _check_dim(cls, dim): + """Helper function to check invalid matrix dimensions""" + ok = not dim.is_Float and check_assumptions( + dim, integer=True, nonnegative=True) + if ok is False: + raise ValueError( + "The dimension specification {} should be " + "a nonnegative integer.".format(dim)) + + def _kind(self): + return SetKind(MatrixKind(NumberKind)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/slice.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/slice.py new file mode 100644 index 0000000000000000000000000000000000000000..1904b49f29c503fb4c0c909532f8342fb0f4b135 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/slice.py @@ -0,0 +1,114 @@ +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.core.basic import Basic +from sympy.core.containers import Tuple +from sympy.functions.elementary.integers import floor + +def normalize(i, parentsize): + if isinstance(i, slice): + i = (i.start, i.stop, i.step) + if not isinstance(i, (tuple, list, Tuple)): + if (i < 0) == True: + i += parentsize + i = (i, i+1, 1) + i = list(i) + if len(i) == 2: + i.append(1) + start, stop, step = i + start = start or 0 + if stop is None: + stop = parentsize + if (start < 0) == True: + start += parentsize + if (stop < 0) == True: + stop += parentsize + step = step or 1 + + if ((stop - start) * step < 1) == True: + raise IndexError() + + return (start, stop, step) + +class MatrixSlice(MatrixExpr): + """ A MatrixSlice of a Matrix Expression + + Examples + ======== + + >>> from sympy import MatrixSlice, ImmutableMatrix + >>> M = ImmutableMatrix(4, 4, range(16)) + >>> M + Matrix([ + [ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + + >>> B = MatrixSlice(M, (0, 2), (2, 4)) + >>> ImmutableMatrix(B) + Matrix([ + [2, 3], + [6, 7]]) + """ + parent = property(lambda self: self.args[0]) + rowslice = property(lambda self: self.args[1]) + colslice = property(lambda self: self.args[2]) + + def __new__(cls, parent, rowslice, colslice): + rowslice = normalize(rowslice, parent.shape[0]) + colslice = normalize(colslice, parent.shape[1]) + if not (len(rowslice) == len(colslice) == 3): + raise IndexError() + if ((0 > rowslice[0]) == True or + (parent.shape[0] < rowslice[1]) == True or + (0 > colslice[0]) == True or + (parent.shape[1] < colslice[1]) == True): + raise IndexError() + if isinstance(parent, MatrixSlice): + return mat_slice_of_slice(parent, rowslice, colslice) + return Basic.__new__(cls, parent, Tuple(*rowslice), Tuple(*colslice)) + + @property + def shape(self): + rows = self.rowslice[1] - self.rowslice[0] + rows = rows if self.rowslice[2] == 1 else floor(rows/self.rowslice[2]) + cols = self.colslice[1] - self.colslice[0] + cols = cols if self.colslice[2] == 1 else floor(cols/self.colslice[2]) + return rows, cols + + def _entry(self, i, j, **kwargs): + return self.parent._entry(i*self.rowslice[2] + self.rowslice[0], + j*self.colslice[2] + self.colslice[0], + **kwargs) + + @property + def on_diag(self): + return self.rowslice == self.colslice + + +def slice_of_slice(s, t): + start1, stop1, step1 = s + start2, stop2, step2 = t + + start = start1 + start2*step1 + step = step1 * step2 + stop = start1 + step1*stop2 + + if stop > stop1: + raise IndexError() + + return start, stop, step + + +def mat_slice_of_slice(parent, rowslice, colslice): + """ Collapse nested matrix slices + + >>> from sympy import MatrixSymbol + >>> X = MatrixSymbol('X', 10, 10) + >>> X[:, 1:5][5:8, :] + X[5:8, 1:5] + >>> X[1:9:2, 2:6][1:3, 2] + X[3:7:2, 4:5] + """ + row = slice_of_slice(parent.rowslice, rowslice) + col = slice_of_slice(parent.colslice, colslice) + return MatrixSlice(parent.parent, row, col) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/special.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/special.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e426f16ada0e4245b644867974b41b6f86b5cc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/special.py @@ -0,0 +1,299 @@ +from sympy.assumptions.ask import ask, Q +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.sympify import _sympify +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.matrices.exceptions import NonInvertibleMatrixError +from .matexpr import MatrixExpr + + +class ZeroMatrix(MatrixExpr): + """The Matrix Zero 0 - additive identity + + Examples + ======== + + >>> from sympy import MatrixSymbol, ZeroMatrix + >>> A = MatrixSymbol('A', 3, 5) + >>> Z = ZeroMatrix(3, 5) + >>> A + Z + A + >>> Z*A.T + 0 + """ + is_ZeroMatrix = True + + def __new__(cls, m, n): + m, n = _sympify(m), _sympify(n) + cls._check_dim(m) + cls._check_dim(n) + + return super().__new__(cls, m, n) + + @property + def shape(self): + return (self.args[0], self.args[1]) + + def _eval_power(self, exp): + # exp = -1, 0, 1 are already handled at this stage + if (exp < 0) == True: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible") + return self + + def _eval_transpose(self): + return ZeroMatrix(self.cols, self.rows) + + def _eval_adjoint(self): + return ZeroMatrix(self.cols, self.rows) + + def _eval_trace(self): + return S.Zero + + def _eval_determinant(self): + return S.Zero + + def _eval_inverse(self): + raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") + + def _eval_as_real_imag(self): + return (self, self) + + def _eval_conjugate(self): + return self + + def _entry(self, i, j, **kwargs): + return S.Zero + + +class GenericZeroMatrix(ZeroMatrix): + """ + A zero matrix without a specified shape + + This exists primarily so MatAdd() with no arguments can return something + meaningful. + """ + def __new__(cls): + # super(ZeroMatrix, cls) instead of super(GenericZeroMatrix, cls) + # because ZeroMatrix.__new__ doesn't have the same signature + return super(ZeroMatrix, cls).__new__(cls) + + @property + def rows(self): + raise TypeError("GenericZeroMatrix does not have a specified shape") + + @property + def cols(self): + raise TypeError("GenericZeroMatrix does not have a specified shape") + + @property + def shape(self): + raise TypeError("GenericZeroMatrix does not have a specified shape") + + # Avoid Matrix.__eq__ which might call .shape + def __eq__(self, other): + return isinstance(other, GenericZeroMatrix) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return super().__hash__() + + + +class Identity(MatrixExpr): + """The Matrix Identity I - multiplicative identity + + Examples + ======== + + >>> from sympy import Identity, MatrixSymbol + >>> A = MatrixSymbol('A', 3, 5) + >>> I = Identity(3) + >>> I*A + A + """ + + is_Identity = True + + def __new__(cls, n): + n = _sympify(n) + cls._check_dim(n) + + return super().__new__(cls, n) + + @property + def rows(self): + return self.args[0] + + @property + def cols(self): + return self.args[0] + + @property + def shape(self): + return (self.args[0], self.args[0]) + + @property + def is_square(self): + return True + + def _eval_transpose(self): + return self + + def _eval_trace(self): + return self.rows + + def _eval_inverse(self): + return self + + def _eval_as_real_imag(self): + return (self, ZeroMatrix(*self.shape)) + + def _eval_conjugate(self): + return self + + def _eval_adjoint(self): + return self + + def _entry(self, i, j, **kwargs): + eq = Eq(i, j) + if eq is S.true: + return S.One + elif eq is S.false: + return S.Zero + return KroneckerDelta(i, j, (0, self.cols-1)) + + def _eval_determinant(self): + return S.One + + def _eval_power(self, exp): + return self + + +class GenericIdentity(Identity): + """ + An identity matrix without a specified shape + + This exists primarily so MatMul() with no arguments can return something + meaningful. + """ + def __new__(cls): + # super(Identity, cls) instead of super(GenericIdentity, cls) because + # Identity.__new__ doesn't have the same signature + return super(Identity, cls).__new__(cls) + + @property + def rows(self): + raise TypeError("GenericIdentity does not have a specified shape") + + @property + def cols(self): + raise TypeError("GenericIdentity does not have a specified shape") + + @property + def shape(self): + raise TypeError("GenericIdentity does not have a specified shape") + + @property + def is_square(self): + return True + + # Avoid Matrix.__eq__ which might call .shape + def __eq__(self, other): + return isinstance(other, GenericIdentity) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return super().__hash__() + + +class OneMatrix(MatrixExpr): + """ + Matrix whose all entries are ones. + """ + def __new__(cls, m, n, evaluate=False): + m, n = _sympify(m), _sympify(n) + cls._check_dim(m) + cls._check_dim(n) + + if evaluate: + condition = Eq(m, 1) & Eq(n, 1) + if condition == True: + return Identity(1) + + obj = super().__new__(cls, m, n) + return obj + + @property + def shape(self): + return self._args + + @property + def is_Identity(self): + return self._is_1x1() == True + + def as_explicit(self): + from sympy.matrices.immutable import ImmutableDenseMatrix + return ImmutableDenseMatrix.ones(*self.shape) + + def doit(self, **hints): + args = self.args + if hints.get('deep', True): + args = [a.doit(**hints) for a in args] + return self.func(*args, evaluate=True) + + def _eval_power(self, exp): + # exp = -1, 0, 1 are already handled at this stage + if self._is_1x1() == True: + return Identity(1) + if (exp < 0) == True: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible") + if ask(Q.integer(exp)): + return self.shape[0] ** (exp - 1) * OneMatrix(*self.shape) + return super()._eval_power(exp) + + def _eval_transpose(self): + return OneMatrix(self.cols, self.rows) + + def _eval_adjoint(self): + return OneMatrix(self.cols, self.rows) + + def _eval_trace(self): + return S.One*self.rows + + def _is_1x1(self): + """Returns true if the matrix is known to be 1x1""" + shape = self.shape + return Eq(shape[0], 1) & Eq(shape[1], 1) + + def _eval_determinant(self): + condition = self._is_1x1() + if condition == True: + return S.One + elif condition == False: + return S.Zero + else: + from sympy.matrices.expressions.determinant import Determinant + return Determinant(self) + + def _eval_inverse(self): + condition = self._is_1x1() + if condition == True: + return Identity(1) + elif condition == False: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") + else: + from .inverse import Inverse + return Inverse(self) + + def _eval_as_real_imag(self): + return (self, ZeroMatrix(*self.shape)) + + def _eval_conjugate(self): + return self + + def _entry(self, i, j, **kwargs): + return S.One diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_companion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_companion.py new file mode 100644 index 0000000000000000000000000000000000000000..edc592c29098eddce0c6352806aa73d5d889e999 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_companion.py @@ -0,0 +1,48 @@ +from sympy.core.expr import unchanged +from sympy.core.symbol import Symbol, symbols +from sympy.matrices.immutable import ImmutableDenseMatrix +from sympy.matrices.expressions.companion import CompanionMatrix +from sympy.polys.polytools import Poly +from sympy.testing.pytest import raises + + +def test_creation(): + x = Symbol('x') + y = Symbol('y') + raises(ValueError, lambda: CompanionMatrix(1)) + raises(ValueError, lambda: CompanionMatrix(Poly([1], x))) + raises(ValueError, lambda: CompanionMatrix(Poly([2, 1], x))) + raises(ValueError, lambda: CompanionMatrix(Poly(x*y, [x, y]))) + assert unchanged(CompanionMatrix, Poly([1, 2, 3], x)) + + +def test_shape(): + c0, c1, c2 = symbols('c0:3') + x = Symbol('x') + assert CompanionMatrix(Poly([1, c0], x)).shape == (1, 1) + assert CompanionMatrix(Poly([1, c1, c0], x)).shape == (2, 2) + assert CompanionMatrix(Poly([1, c2, c1, c0], x)).shape == (3, 3) + + +def test_entry(): + c0, c1, c2 = symbols('c0:3') + x = Symbol('x') + A = CompanionMatrix(Poly([1, c2, c1, c0], x)) + assert A[0, 0] == 0 + assert A[1, 0] == 1 + assert A[1, 1] == 0 + assert A[2, 1] == 1 + assert A[0, 2] == -c0 + assert A[1, 2] == -c1 + assert A[2, 2] == -c2 + + +def test_as_explicit(): + c0, c1, c2 = symbols('c0:3') + x = Symbol('x') + assert CompanionMatrix(Poly([1, c0], x)).as_explicit() == \ + ImmutableDenseMatrix([-c0]) + assert CompanionMatrix(Poly([1, c1, c0], x)).as_explicit() == \ + ImmutableDenseMatrix([[0, -c0], [1, -c1]]) + assert CompanionMatrix(Poly([1, c2, c1, c0], x)).as_explicit() == \ + ImmutableDenseMatrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/trace.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/trace.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f9f94ea7486dc21b47c2e2e783a93280b180e0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/trace.py @@ -0,0 +1,167 @@ +from sympy.core.basic import Basic +from sympy.core.expr import Expr, ExprBuilder +from sympy.core.singleton import S +from sympy.core.sorting import default_sort_key +from sympy.core.symbol import uniquely_named_symbol +from sympy.core.sympify import sympify +from sympy.matrices.matrixbase import MatrixBase +from sympy.matrices.exceptions import NonSquareMatrixError + + +class Trace(Expr): + """Matrix Trace + + Represents the trace of a matrix expression. + + Examples + ======== + + >>> from sympy import MatrixSymbol, Trace, eye + >>> A = MatrixSymbol('A', 3, 3) + >>> Trace(A) + Trace(A) + >>> Trace(eye(3)) + Trace(Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]])) + >>> Trace(eye(3)).simplify() + 3 + """ + is_Trace = True + is_commutative = True + + def __new__(cls, mat): + mat = sympify(mat) + + if not mat.is_Matrix: + raise TypeError("input to Trace, %s, is not a matrix" % str(mat)) + + if mat.is_square is False: + raise NonSquareMatrixError("Trace of a non-square matrix") + + return Basic.__new__(cls, mat) + + def _eval_transpose(self): + return self + + def _eval_derivative(self, v): + from sympy.concrete.summations import Sum + from .matexpr import MatrixElement + if isinstance(v, MatrixElement): + return self.rewrite(Sum).diff(v) + expr = self.doit() + if isinstance(expr, Trace): + # Avoid looping infinitely: + raise NotImplementedError + return expr._eval_derivative(v) + + def _eval_derivative_matrix_lines(self, x): + from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction + r = self.args[0]._eval_derivative_matrix_lines(x) + for lr in r: + if lr.higher == 1: + lr.higher = ExprBuilder( + ArrayContraction, + [ + ExprBuilder( + ArrayTensorProduct, + [ + lr._lines[0], + lr._lines[1], + ] + ), + (1, 3), + ], + validator=ArrayContraction._validate + ) + else: + # This is not a matrix line: + lr.higher = ExprBuilder( + ArrayContraction, + [ + ExprBuilder( + ArrayTensorProduct, + [ + lr._lines[0], + lr._lines[1], + lr.higher, + ] + ), + (1, 3), (0, 2) + ] + ) + lr._lines = [S.One, S.One] + lr._first_pointer_parent = lr._lines + lr._second_pointer_parent = lr._lines + lr._first_pointer_index = 0 + lr._second_pointer_index = 1 + return r + + @property + def arg(self): + return self.args[0] + + def doit(self, **hints): + if hints.get('deep', True): + arg = self.arg.doit(**hints) + result = arg._eval_trace() + if result is not None: + return result + else: + return Trace(arg) + else: + # _eval_trace would go too deep here + if isinstance(self.arg, MatrixBase): + return trace(self.arg) + else: + return Trace(self.arg) + + def as_explicit(self): + return Trace(self.arg.as_explicit()).doit() + + def _normalize(self): + # Normalization of trace of matrix products. Use transposition and + # cyclic properties of traces to make sure the arguments of the matrix + # product are sorted and the first argument is not a transposition. + from sympy.matrices.expressions.matmul import MatMul + from sympy.matrices.expressions.transpose import Transpose + trace_arg = self.arg + if isinstance(trace_arg, MatMul): + + def get_arg_key(x): + a = trace_arg.args[x] + if isinstance(a, Transpose): + a = a.arg + return default_sort_key(a) + + indmin = min(range(len(trace_arg.args)), key=get_arg_key) + if isinstance(trace_arg.args[indmin], Transpose): + trace_arg = Transpose(trace_arg).doit() + indmin = min(range(len(trace_arg.args)), key=lambda x: default_sort_key(trace_arg.args[x])) + trace_arg = MatMul.fromiter(trace_arg.args[indmin:] + trace_arg.args[:indmin]) + return Trace(trace_arg) + return self + + def _eval_rewrite_as_Sum(self, expr, **kwargs): + from sympy.concrete.summations import Sum + i = uniquely_named_symbol('i', [expr]) + s = Sum(self.arg[i, i], (i, 0, self.arg.rows - 1)) + return s.doit() + + +def trace(expr): + """Trace of a Matrix. Sum of the diagonal elements. + + Examples + ======== + + >>> from sympy import trace, Symbol, MatrixSymbol, eye + >>> n = Symbol('n') + >>> X = MatrixSymbol('X', n, n) # A square matrix + >>> trace(2*X) + 2*Trace(X) + >>> trace(eye(3)) + 3 + """ + return Trace(expr).doit() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/transpose.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/transpose.py new file mode 100644 index 0000000000000000000000000000000000000000..b11f7fc21490aab219420610ca529d81d6995d40 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/expressions/transpose.py @@ -0,0 +1,103 @@ +from sympy.core.basic import Basic +from sympy.matrices.expressions.matexpr import MatrixExpr + + +class Transpose(MatrixExpr): + """ + The transpose of a matrix expression. + + This is a symbolic object that simply stores its argument without + evaluating it. To actually compute the transpose, use the ``transpose()`` + function, or the ``.T`` attribute of matrices. + + Examples + ======== + + >>> from sympy import MatrixSymbol, Transpose, transpose + >>> A = MatrixSymbol('A', 3, 5) + >>> B = MatrixSymbol('B', 5, 3) + >>> Transpose(A) + A.T + >>> A.T == transpose(A) == Transpose(A) + True + >>> Transpose(A*B) + (A*B).T + >>> transpose(A*B) + B.T*A.T + + """ + is_Transpose = True + + def doit(self, **hints): + arg = self.arg + if hints.get('deep', True) and isinstance(arg, Basic): + arg = arg.doit(**hints) + _eval_transpose = getattr(arg, '_eval_transpose', None) + if _eval_transpose is not None: + result = _eval_transpose() + return result if result is not None else Transpose(arg) + else: + return Transpose(arg) + + @property + def arg(self): + return self.args[0] + + @property + def shape(self): + return self.arg.shape[::-1] + + def _entry(self, i, j, expand=False, **kwargs): + return self.arg._entry(j, i, expand=expand, **kwargs) + + def _eval_adjoint(self): + return self.arg.conjugate() + + def _eval_conjugate(self): + return self.arg.adjoint() + + def _eval_transpose(self): + return self.arg + + def _eval_trace(self): + from .trace import Trace + return Trace(self.arg) # Trace(X.T) => Trace(X) + + def _eval_determinant(self): + from sympy.matrices.expressions.determinant import det + return det(self.arg) + + def _eval_derivative(self, x): + # x is a scalar: + return self.arg._eval_derivative(x) + + def _eval_derivative_matrix_lines(self, x): + lines = self.args[0]._eval_derivative_matrix_lines(x) + return [i.transpose() for i in lines] + + +def transpose(expr): + """Matrix transpose""" + return Transpose(expr).doit(deep=False) + + +from sympy.assumptions.ask import ask, Q +from sympy.assumptions.refine import handlers_dict + + +def refine_Transpose(expr, assumptions): + """ + >>> from sympy import MatrixSymbol, Q, assuming, refine + >>> X = MatrixSymbol('X', 2, 2) + >>> X.T + X.T + >>> with assuming(Q.symmetric(X)): + ... print(refine(X.T)) + X + """ + if ask(Q.symmetric(expr), assumptions): + return expr.arg + + return expr + +handlers_dict['Transpose'] = refine_Transpose diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/graph.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..4c6356db884cfcd3c759ada07ac559f43dbcbbcb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/graph.py @@ -0,0 +1,279 @@ +from sympy.utilities.iterables import \ + flatten, connected_components, strongly_connected_components +from .exceptions import NonSquareMatrixError + + +def _connected_components(M): + """Returns the list of connected vertices of the graph when + a square matrix is viewed as a weighted graph. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([ + ... [66, 0, 0, 68, 0, 0, 0, 0, 67], + ... [0, 55, 0, 0, 0, 0, 54, 53, 0], + ... [0, 0, 0, 0, 1, 2, 0, 0, 0], + ... [86, 0, 0, 88, 0, 0, 0, 0, 87], + ... [0, 0, 10, 0, 11, 12, 0, 0, 0], + ... [0, 0, 20, 0, 21, 22, 0, 0, 0], + ... [0, 45, 0, 0, 0, 0, 44, 43, 0], + ... [0, 35, 0, 0, 0, 0, 34, 33, 0], + ... [76, 0, 0, 78, 0, 0, 0, 0, 77]]) + >>> A.connected_components() + [[0, 3, 8], [1, 6, 7], [2, 4, 5]] + + Notes + ===== + + Even if any symbolic elements of the matrix can be indeterminate + to be zero mathematically, this only takes the account of the + structural aspect of the matrix, so they will considered to be + nonzero. + """ + if not M.is_square: + raise NonSquareMatrixError + + V = range(M.rows) + E = sorted(M.todok().keys()) + return connected_components((V, E)) + + +def _strongly_connected_components(M): + """Returns the list of strongly connected vertices of the graph when + a square matrix is viewed as a weighted graph. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([ + ... [44, 0, 0, 0, 43, 0, 45, 0, 0], + ... [0, 66, 62, 61, 0, 68, 0, 60, 67], + ... [0, 0, 22, 21, 0, 0, 0, 20, 0], + ... [0, 0, 12, 11, 0, 0, 0, 10, 0], + ... [34, 0, 0, 0, 33, 0, 35, 0, 0], + ... [0, 86, 82, 81, 0, 88, 0, 80, 87], + ... [54, 0, 0, 0, 53, 0, 55, 0, 0], + ... [0, 0, 2, 1, 0, 0, 0, 0, 0], + ... [0, 76, 72, 71, 0, 78, 0, 70, 77]]) + >>> A.strongly_connected_components() + [[0, 4, 6], [2, 3, 7], [1, 5, 8]] + """ + if not M.is_square: + raise NonSquareMatrixError + + # RepMatrix uses the more efficient DomainMatrix.scc() method + rep = getattr(M, '_rep', None) + if rep is not None: + return rep.scc() + + V = range(M.rows) + E = sorted(M.todok().keys()) + return strongly_connected_components((V, E)) + + +def _connected_components_decomposition(M): + """Decomposes a square matrix into block diagonal form only + using the permutations. + + Explanation + =========== + + The decomposition is in a form of $A = P^{-1} B P$ where $P$ is a + permutation matrix and $B$ is a block diagonal matrix. + + Returns + ======= + + P, B : PermutationMatrix, BlockDiagMatrix + *P* is a permutation matrix for the similarity transform + as in the explanation. And *B* is the block diagonal matrix of + the result of the permutation. + + If you would like to get the diagonal blocks from the + BlockDiagMatrix, see + :meth:`~sympy.matrices.expressions.blockmatrix.BlockDiagMatrix.get_diag_blocks`. + + Examples + ======== + + >>> from sympy import Matrix, pprint + >>> A = Matrix([ + ... [66, 0, 0, 68, 0, 0, 0, 0, 67], + ... [0, 55, 0, 0, 0, 0, 54, 53, 0], + ... [0, 0, 0, 0, 1, 2, 0, 0, 0], + ... [86, 0, 0, 88, 0, 0, 0, 0, 87], + ... [0, 0, 10, 0, 11, 12, 0, 0, 0], + ... [0, 0, 20, 0, 21, 22, 0, 0, 0], + ... [0, 45, 0, 0, 0, 0, 44, 43, 0], + ... [0, 35, 0, 0, 0, 0, 34, 33, 0], + ... [76, 0, 0, 78, 0, 0, 0, 0, 77]]) + + >>> P, B = A.connected_components_decomposition() + >>> pprint(P) + PermutationMatrix((1 3)(2 8 5 7 4 6)) + >>> pprint(B) + [[66 68 67] ] + [[ ] ] + [[86 88 87] 0 0 ] + [[ ] ] + [[76 78 77] ] + [ ] + [ [55 54 53] ] + [ [ ] ] + [ 0 [45 44 43] 0 ] + [ [ ] ] + [ [35 34 33] ] + [ ] + [ [0 1 2 ]] + [ [ ]] + [ 0 0 [10 11 12]] + [ [ ]] + [ [20 21 22]] + + >>> P = P.as_explicit() + >>> B = B.as_explicit() + >>> P.T*B*P == A + True + + Notes + ===== + + This problem corresponds to the finding of the connected components + of a graph, when a matrix is viewed as a weighted graph. + """ + from sympy.combinatorics.permutations import Permutation + from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix + from sympy.matrices.expressions.permutation import PermutationMatrix + + iblocks = M.connected_components() + + p = Permutation(flatten(iblocks)) + P = PermutationMatrix(p) + + blocks = [] + for b in iblocks: + blocks.append(M[b, b]) + B = BlockDiagMatrix(*blocks) + return P, B + + +def _strongly_connected_components_decomposition(M, lower=True): + """Decomposes a square matrix into block triangular form only + using the permutations. + + Explanation + =========== + + The decomposition is in a form of $A = P^{-1} B P$ where $P$ is a + permutation matrix and $B$ is a block diagonal matrix. + + Parameters + ========== + + lower : bool + Makes $B$ lower block triangular when ``True``. + Otherwise, makes $B$ upper block triangular. + + Returns + ======= + + P, B : PermutationMatrix, BlockMatrix + *P* is a permutation matrix for the similarity transform + as in the explanation. And *B* is the block triangular matrix of + the result of the permutation. + + Examples + ======== + + >>> from sympy import Matrix, pprint + >>> A = Matrix([ + ... [44, 0, 0, 0, 43, 0, 45, 0, 0], + ... [0, 66, 62, 61, 0, 68, 0, 60, 67], + ... [0, 0, 22, 21, 0, 0, 0, 20, 0], + ... [0, 0, 12, 11, 0, 0, 0, 10, 0], + ... [34, 0, 0, 0, 33, 0, 35, 0, 0], + ... [0, 86, 82, 81, 0, 88, 0, 80, 87], + ... [54, 0, 0, 0, 53, 0, 55, 0, 0], + ... [0, 0, 2, 1, 0, 0, 0, 0, 0], + ... [0, 76, 72, 71, 0, 78, 0, 70, 77]]) + + A lower block triangular decomposition: + + >>> P, B = A.strongly_connected_components_decomposition() + >>> pprint(P) + PermutationMatrix((8)(1 4 3 2 6)(5 7)) + >>> pprint(B) + [[44 43 45] [0 0 0] [0 0 0] ] + [[ ] [ ] [ ] ] + [[34 33 35] [0 0 0] [0 0 0] ] + [[ ] [ ] [ ] ] + [[54 53 55] [0 0 0] [0 0 0] ] + [ ] + [ [0 0 0] [22 21 20] [0 0 0] ] + [ [ ] [ ] [ ] ] + [ [0 0 0] [12 11 10] [0 0 0] ] + [ [ ] [ ] [ ] ] + [ [0 0 0] [2 1 0 ] [0 0 0] ] + [ ] + [ [0 0 0] [62 61 60] [66 68 67]] + [ [ ] [ ] [ ]] + [ [0 0 0] [82 81 80] [86 88 87]] + [ [ ] [ ] [ ]] + [ [0 0 0] [72 71 70] [76 78 77]] + + >>> P = P.as_explicit() + >>> B = B.as_explicit() + >>> P.T * B * P == A + True + + An upper block triangular decomposition: + + >>> P, B = A.strongly_connected_components_decomposition(lower=False) + >>> pprint(P) + PermutationMatrix((0 1 5 7 4 3 2 8 6)) + >>> pprint(B) + [[66 68 67] [62 61 60] [0 0 0] ] + [[ ] [ ] [ ] ] + [[86 88 87] [82 81 80] [0 0 0] ] + [[ ] [ ] [ ] ] + [[76 78 77] [72 71 70] [0 0 0] ] + [ ] + [ [0 0 0] [22 21 20] [0 0 0] ] + [ [ ] [ ] [ ] ] + [ [0 0 0] [12 11 10] [0 0 0] ] + [ [ ] [ ] [ ] ] + [ [0 0 0] [2 1 0 ] [0 0 0] ] + [ ] + [ [0 0 0] [0 0 0] [44 43 45]] + [ [ ] [ ] [ ]] + [ [0 0 0] [0 0 0] [34 33 35]] + [ [ ] [ ] [ ]] + [ [0 0 0] [0 0 0] [54 53 55]] + + >>> P = P.as_explicit() + >>> B = B.as_explicit() + >>> P.T * B * P == A + True + """ + from sympy.combinatorics.permutations import Permutation + from sympy.matrices.expressions.blockmatrix import BlockMatrix + from sympy.matrices.expressions.permutation import PermutationMatrix + + iblocks = M.strongly_connected_components() + if not lower: + iblocks = list(reversed(iblocks)) + + p = Permutation(flatten(iblocks)) + P = PermutationMatrix(p) + + rows = [] + for a in iblocks: + cols = [] + for b in iblocks: + cols.append(M[a, b]) + rows.append(cols) + B = BlockMatrix(rows) + return P, B diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/immutable.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/immutable.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec2174bf1c785e1a4698e1b55078d300e62dafe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/immutable.py @@ -0,0 +1,196 @@ +from mpmath.matrices.matrices import _matrix + +from sympy.core import Basic, Dict, Tuple +from sympy.core.numbers import Integer +from sympy.core.cache import cacheit +from sympy.core.sympify import _sympy_converter as sympify_converter, _sympify +from sympy.matrices.dense import DenseMatrix +from sympy.matrices.expressions import MatrixExpr +from sympy.matrices.matrixbase import MatrixBase +from sympy.matrices.repmatrix import RepMatrix +from sympy.matrices.sparse import SparseRepMatrix +from sympy.multipledispatch import dispatch + + +def sympify_matrix(arg): + return arg.as_immutable() + + +sympify_converter[MatrixBase] = sympify_matrix + + +def sympify_mpmath_matrix(arg): + mat = [_sympify(x) for x in arg] + return ImmutableDenseMatrix(arg.rows, arg.cols, mat) + + +sympify_converter[_matrix] = sympify_mpmath_matrix + + +class ImmutableRepMatrix(RepMatrix, MatrixExpr): # type: ignore + """Immutable matrix based on RepMatrix + + Uses DomainMAtrix as the internal representation. + """ + + # + # This is a subclass of RepMatrix that adds/overrides some methods to make + # the instances Basic and immutable. ImmutableRepMatrix is a superclass for + # both ImmutableDenseMatrix and ImmutableSparseMatrix. + # + + def __new__(cls, *args, **kwargs): + return cls._new(*args, **kwargs) + + __hash__ = MatrixExpr.__hash__ + + def copy(self): + return self + + @property + def cols(self): + return self._cols + + @property + def rows(self): + return self._rows + + @property + def shape(self): + return self._rows, self._cols + + def as_immutable(self): + return self + + def _entry(self, i, j, **kwargs): + return self[i, j] + + def __setitem__(self, *args): + raise TypeError("Cannot set values of {}".format(self.__class__)) + + def is_diagonalizable(self, reals_only=False, **kwargs): + return super().is_diagonalizable( + reals_only=reals_only, **kwargs) + + is_diagonalizable.__doc__ = SparseRepMatrix.is_diagonalizable.__doc__ + is_diagonalizable = cacheit(is_diagonalizable) + + def analytic_func(self, f, x): + return self.as_mutable().analytic_func(f, x).as_immutable() + + +class ImmutableDenseMatrix(DenseMatrix, ImmutableRepMatrix): # type: ignore + """Create an immutable version of a matrix. + + Examples + ======== + + >>> from sympy import eye, ImmutableMatrix + >>> ImmutableMatrix(eye(3)) + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> _[0, 0] = 42 + Traceback (most recent call last): + ... + TypeError: Cannot set values of ImmutableDenseMatrix + """ + + # MatrixExpr is set as NotIterable, but we want explicit matrices to be + # iterable + _iterable = True + _class_priority = 8 + _op_priority = 10.001 + + @classmethod + def _new(cls, *args, **kwargs): + if len(args) == 1 and isinstance(args[0], ImmutableDenseMatrix): + return args[0] + if kwargs.get('copy', True) is False: + if len(args) != 3: + raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]") + rows, cols, flat_list = args + else: + rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) + flat_list = list(flat_list) # create a shallow copy + + rep = cls._flat_list_to_DomainMatrix(rows, cols, flat_list) + + return cls._fromrep(rep) + + @classmethod + def _fromrep(cls, rep): + rows, cols = rep.shape + flat_list = rep.to_sympy().to_list_flat() + obj = Basic.__new__(cls, + Integer(rows), + Integer(cols), + Tuple(*flat_list, sympify=False)) + obj._rows = rows + obj._cols = cols + obj._rep = rep + return obj + + +# make sure ImmutableDenseMatrix is aliased as ImmutableMatrix +ImmutableMatrix = ImmutableDenseMatrix + + +class ImmutableSparseMatrix(SparseRepMatrix, ImmutableRepMatrix): # type:ignore + """Create an immutable version of a sparse matrix. + + Examples + ======== + + >>> from sympy import eye, ImmutableSparseMatrix + >>> ImmutableSparseMatrix(1, 1, {}) + Matrix([[0]]) + >>> ImmutableSparseMatrix(eye(3)) + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> _[0, 0] = 42 + Traceback (most recent call last): + ... + TypeError: Cannot set values of ImmutableSparseMatrix + >>> _.shape + (3, 3) + """ + is_Matrix = True + _class_priority = 9 + + @classmethod + def _new(cls, *args, **kwargs): + rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs) + + rep = cls._smat_to_DomainMatrix(rows, cols, smat) + + return cls._fromrep(rep) + + @classmethod + def _fromrep(cls, rep): + rows, cols = rep.shape + smat = rep.to_sympy().to_dok() + obj = Basic.__new__(cls, Integer(rows), Integer(cols), Dict(smat)) + obj._rows = rows + obj._cols = cols + obj._rep = rep + return obj + + +@dispatch(ImmutableDenseMatrix, ImmutableDenseMatrix) +def _eval_is_eq(lhs, rhs): # noqa:F811 + """Helper method for Equality with matrices.sympy. + + Relational automatically converts matrices to ImmutableDenseMatrix + instances, so this method only applies here. Returns True if the + matrices are definitively the same, False if they are definitively + different, and None if undetermined (e.g. if they contain Symbols). + Returning None triggers default handling of Equalities. + + """ + if lhs.shape != rhs.shape: + return False + return (lhs - rhs).is_zero_matrix diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/inverse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/inverse.py new file mode 100644 index 0000000000000000000000000000000000000000..61d9e12edf013d2f5555d61786343aa3840edfd3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/inverse.py @@ -0,0 +1,524 @@ +from sympy.polys.matrices.exceptions import DMNonInvertibleMatrixError +from sympy.polys.domains import EX + +from .exceptions import MatrixError, NonSquareMatrixError, NonInvertibleMatrixError +from .utilities import _iszero + + +def _pinv_full_rank(M): + """Subroutine for full row or column rank matrices. + + For full row rank matrices, inverse of ``A * A.H`` Exists. + For full column rank matrices, inverse of ``A.H * A`` Exists. + + This routine can apply for both cases by checking the shape + and have small decision. + """ + + if M.is_zero_matrix: + return M.H + + if M.rows >= M.cols: + return M.H.multiply(M).inv().multiply(M.H) + else: + return M.H.multiply(M.multiply(M.H).inv()) + +def _pinv_rank_decomposition(M): + """Subroutine for rank decomposition + + With rank decompositions, `A` can be decomposed into two full- + rank matrices, and each matrix can take pseudoinverse + individually. + """ + + if M.is_zero_matrix: + return M.H + + B, C = M.rank_decomposition() + + Bp = _pinv_full_rank(B) + Cp = _pinv_full_rank(C) + + return Cp.multiply(Bp) + +def _pinv_diagonalization(M): + """Subroutine using diagonalization + + This routine can sometimes fail if SymPy's eigenvalue + computation is not reliable. + """ + + if M.is_zero_matrix: + return M.H + + A = M + AH = M.H + + try: + if M.rows >= M.cols: + P, D = AH.multiply(A).diagonalize(normalize=True) + D_pinv = D.applyfunc(lambda x: 0 if _iszero(x) else 1 / x) + + return P.multiply(D_pinv).multiply(P.H).multiply(AH) + + else: + P, D = A.multiply(AH).diagonalize( + normalize=True) + D_pinv = D.applyfunc(lambda x: 0 if _iszero(x) else 1 / x) + + return AH.multiply(P).multiply(D_pinv).multiply(P.H) + + except MatrixError: + raise NotImplementedError( + 'pinv for rank-deficient matrices where ' + 'diagonalization of A.H*A fails is not supported yet.') + +def _pinv(M, method='RD'): + """Calculate the Moore-Penrose pseudoinverse of the matrix. + + The Moore-Penrose pseudoinverse exists and is unique for any matrix. + If the matrix is invertible, the pseudoinverse is the same as the + inverse. + + Parameters + ========== + + method : String, optional + Specifies the method for computing the pseudoinverse. + + If ``'RD'``, Rank-Decomposition will be used. + + If ``'ED'``, Diagonalization will be used. + + Examples + ======== + + Computing pseudoinverse by rank decomposition : + + >>> from sympy import Matrix + >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) + >>> A.pinv() + Matrix([ + [-17/18, 4/9], + [ -1/9, 1/9], + [ 13/18, -2/9]]) + + Computing pseudoinverse by diagonalization : + + >>> B = A.pinv(method='ED') + >>> B.simplify() + >>> B + Matrix([ + [-17/18, 4/9], + [ -1/9, 1/9], + [ 13/18, -2/9]]) + + See Also + ======== + + inv + pinv_solve + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse + + """ + + # Trivial case: pseudoinverse of all-zero matrix is its transpose. + if M.is_zero_matrix: + return M.H + + if method == 'RD': + return _pinv_rank_decomposition(M) + elif method == 'ED': + return _pinv_diagonalization(M) + else: + raise ValueError('invalid pinv method %s' % repr(method)) + + +def _verify_invertible(M, iszerofunc=_iszero): + """Initial check to see if a matrix is invertible. Raises or returns + determinant for use in _inv_ADJ.""" + + if not M.is_square: + raise NonSquareMatrixError("A Matrix must be square to invert.") + + d = M.det(method='berkowitz') + zero = d.equals(0) + + if zero is None: # if equals() can't decide, will rref be able to? + ok = M.rref(simplify=True)[0] + zero = any(iszerofunc(ok[j, j]) for j in range(ok.rows)) + + if zero: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") + + return d + +def _inv_ADJ(M, iszerofunc=_iszero): + """Calculates the inverse using the adjugate matrix and a determinant. + + See Also + ======== + + inv + inverse_GE + inverse_LU + inverse_CH + inverse_LDL + """ + + d = _verify_invertible(M, iszerofunc=iszerofunc) + + return M.adjugate() / d + +def _inv_GE(M, iszerofunc=_iszero): + """Calculates the inverse using Gaussian elimination. + + See Also + ======== + + inv + inverse_ADJ + inverse_LU + inverse_CH + inverse_LDL + """ + + from .dense import Matrix + + if not M.is_square: + raise NonSquareMatrixError("A Matrix must be square to invert.") + + big = Matrix.hstack(M.as_mutable(), Matrix.eye(M.rows)) + red = big.rref(iszerofunc=iszerofunc, simplify=True)[0] + + if any(iszerofunc(red[j, j]) for j in range(red.rows)): + raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") + + return M._new(red[:, big.rows:]) + +def _inv_LU(M, iszerofunc=_iszero): + """Calculates the inverse using LU decomposition. + + See Also + ======== + + inv + inverse_ADJ + inverse_GE + inverse_CH + inverse_LDL + """ + + if not M.is_square: + raise NonSquareMatrixError("A Matrix must be square to invert.") + if M.free_symbols: + _verify_invertible(M, iszerofunc=iszerofunc) + + return M.LUsolve(M.eye(M.rows), iszerofunc=_iszero) + +def _inv_CH(M, iszerofunc=_iszero): + """Calculates the inverse using cholesky decomposition. + + See Also + ======== + + inv + inverse_ADJ + inverse_GE + inverse_LU + inverse_LDL + """ + + _verify_invertible(M, iszerofunc=iszerofunc) + + return M.cholesky_solve(M.eye(M.rows)) + +def _inv_LDL(M, iszerofunc=_iszero): + """Calculates the inverse using LDL decomposition. + + See Also + ======== + + inv + inverse_ADJ + inverse_GE + inverse_LU + inverse_CH + """ + + _verify_invertible(M, iszerofunc=iszerofunc) + + return M.LDLsolve(M.eye(M.rows)) + +def _inv_QR(M, iszerofunc=_iszero): + """Calculates the inverse using QR decomposition. + + See Also + ======== + + inv + inverse_ADJ + inverse_GE + inverse_CH + inverse_LDL + """ + + _verify_invertible(M, iszerofunc=iszerofunc) + + return M.QRsolve(M.eye(M.rows)) + +def _try_DM(M, use_EX=False): + """Try to convert a matrix to a ``DomainMatrix``.""" + dM = M.to_DM() + K = dM.domain + + # Return DomainMatrix if a domain is found. Only use EX if use_EX=True. + if not use_EX and K.is_EXRAW: + return None + elif K.is_EXRAW: + return dM.convert_to(EX) + else: + return dM + + +def _use_exact_domain(dom): + """Check whether to convert to an exact domain.""" + # DomainMatrix can handle RR and CC with partial pivoting. Other inexact + # domains like RR[a,b,...] can only be handled by converting to an exact + # domain like QQ[a,b,...] + if dom.is_RR or dom.is_CC: + return False + else: + return not dom.is_Exact + + +def _inv_DM(dM, cancel=True): + """Calculates the inverse using ``DomainMatrix``. + + See Also + ======== + + inv + inverse_ADJ + inverse_GE + inverse_CH + inverse_LDL + sympy.polys.matrices.domainmatrix.DomainMatrix.inv + """ + m, n = dM.shape + dom = dM.domain + + if m != n: + raise NonSquareMatrixError("A Matrix must be square to invert.") + + # Convert RR[a,b,...] to QQ[a,b,...] + use_exact = _use_exact_domain(dom) + + if use_exact: + dom_exact = dom.get_exact() + dM = dM.convert_to(dom_exact) + + try: + dMi, den = dM.inv_den() + except DMNonInvertibleMatrixError: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") + + if use_exact: + dMi = dMi.convert_to(dom) + den = dom.convert_from(den, dom_exact) + + if cancel: + # Convert to field and cancel with the denominator. + if not dMi.domain.is_Field: + dMi = dMi.to_field() + Mi = (dMi / den).to_Matrix() + else: + # Convert to Matrix and divide without cancelling + Mi = dMi.to_Matrix() / dMi.domain.to_sympy(den) + + return Mi + +def _inv_block(M, iszerofunc=_iszero): + """Calculates the inverse using BLOCKWISE inversion. + + See Also + ======== + + inv + inverse_ADJ + inverse_GE + inverse_CH + inverse_LDL + """ + from sympy.matrices.expressions.blockmatrix import BlockMatrix + i = M.shape[0] + if i <= 20 : + return M.inv(method="LU", iszerofunc=_iszero) + A = M[:i // 2, :i //2] + B = M[:i // 2, i // 2:] + C = M[i // 2:, :i // 2] + D = M[i // 2:, i // 2:] + try: + D_inv = _inv_block(D) + except NonInvertibleMatrixError: + return M.inv(method="LU", iszerofunc=_iszero) + B_D_i = B*D_inv + BDC = B_D_i*C + A_n = A - BDC + try: + A_n = _inv_block(A_n) + except NonInvertibleMatrixError: + return M.inv(method="LU", iszerofunc=_iszero) + B_n = -A_n*B_D_i + dc = D_inv*C + C_n = -dc*A_n + D_n = D_inv + dc*-B_n + nn = BlockMatrix([[A_n, B_n], [C_n, D_n]]).as_explicit() + return nn + +def _inv(M, method=None, iszerofunc=_iszero, try_block_diag=False): + """ + Return the inverse of a matrix using the method indicated. The default + is DM if a suitable domain is found or otherwise GE for dense matrices + LDL for sparse matrices. + + Parameters + ========== + + method : ('DM', 'DMNC', 'GE', 'LU', 'ADJ', 'CH', 'LDL', 'QR') + + iszerofunc : function, optional + Zero-testing function to use. + + try_block_diag : bool, optional + If True then will try to form block diagonal matrices using the + method get_diag_blocks(), invert these individually, and then + reconstruct the full inverse matrix. + + Examples + ======== + + >>> from sympy import SparseMatrix, Matrix + >>> A = SparseMatrix([ + ... [ 2, -1, 0], + ... [-1, 2, -1], + ... [ 0, 0, 2]]) + >>> A.inv('CH') + Matrix([ + [2/3, 1/3, 1/6], + [1/3, 2/3, 1/3], + [ 0, 0, 1/2]]) + >>> A.inv(method='LDL') # use of 'method=' is optional + Matrix([ + [2/3, 1/3, 1/6], + [1/3, 2/3, 1/3], + [ 0, 0, 1/2]]) + >>> A * _ + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> A = Matrix(A) + >>> A.inv('CH') + Matrix([ + [2/3, 1/3, 1/6], + [1/3, 2/3, 1/3], + [ 0, 0, 1/2]]) + >>> A.inv('ADJ') == A.inv('GE') == A.inv('LU') == A.inv('CH') == A.inv('LDL') == A.inv('QR') + True + + Notes + ===== + + According to the ``method`` keyword, it calls the appropriate method: + + DM .... Use DomainMatrix ``inv_den`` method + DMNC .... Use DomainMatrix ``inv_den`` method without cancellation + GE .... inverse_GE(); default for dense matrices + LU .... inverse_LU() + ADJ ... inverse_ADJ() + CH ... inverse_CH() + LDL ... inverse_LDL(); default for sparse matrices + QR ... inverse_QR() + + Note, the GE and LU methods may require the matrix to be simplified + before it is inverted in order to properly detect zeros during + pivoting. In difficult cases a custom zero detection function can + be provided by setting the ``iszerofunc`` argument to a function that + should return True if its argument is zero. The ADJ routine computes + the determinant and uses that to detect singular matrices in addition + to testing for zeros on the diagonal. + + See Also + ======== + + inverse_ADJ + inverse_GE + inverse_LU + inverse_CH + inverse_LDL + + Raises + ====== + + ValueError + If the determinant of the matrix is zero. + """ + + from sympy.matrices import diag, SparseMatrix + + if not M.is_square: + raise NonSquareMatrixError("A Matrix must be square to invert.") + + if try_block_diag: + blocks = M.get_diag_blocks() + r = [] + + for block in blocks: + r.append(block.inv(method=method, iszerofunc=iszerofunc)) + + return diag(*r) + + # Default: Use DomainMatrix if the domain is not EX. + # If DM is requested explicitly then use it even if the domain is EX. + if method is None and iszerofunc is _iszero: + dM = _try_DM(M, use_EX=False) + if dM is not None: + method = 'DM' + elif method in ("DM", "DMNC"): + dM = _try_DM(M, use_EX=True) + + # A suitable domain was not found, fall back to GE for dense matrices + # and LDL for sparse matrices. + if method is None: + if isinstance(M, SparseMatrix): + method = 'LDL' + else: + method = 'GE' + + if method == "DM": + rv = _inv_DM(dM) + elif method == "DMNC": + rv = _inv_DM(dM, cancel=False) + elif method == "GE": + rv = M.inverse_GE(iszerofunc=iszerofunc) + elif method == "LU": + rv = M.inverse_LU(iszerofunc=iszerofunc) + elif method == "ADJ": + rv = M.inverse_ADJ(iszerofunc=iszerofunc) + elif method == "CH": + rv = M.inverse_CH(iszerofunc=iszerofunc) + elif method == "LDL": + rv = M.inverse_LDL(iszerofunc=iszerofunc) + elif method == "QR": + rv = M.inverse_QR(iszerofunc=iszerofunc) + elif method == "BLOCK": + rv = M.inverse_BLOCK(iszerofunc=iszerofunc) + else: + raise ValueError("Inversion method unrecognized") + + return M._new(rv) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/kind.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/kind.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f53ffe16f7cbde60213e49071a2a74e80e5c6c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/kind.py @@ -0,0 +1,97 @@ +# sympy.matrices.kind + +from sympy.core.kind import Kind, _NumberKind, NumberKind +from sympy.core.mul import Mul + + +class MatrixKind(Kind): + """ + Kind for all matrices in SymPy. + + Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``, + but any expression representing the matrix can have this. + + Parameters + ========== + + element_kind : Kind + Kind of the element. Default is + :class:`sympy.core.kind.NumberKind`, + which means that the matrix contains only numbers. + + Examples + ======== + + Any instance of matrix class has kind ``MatrixKind``: + + >>> from sympy import MatrixSymbol + >>> A = MatrixSymbol('A', 2, 2) + >>> A.kind + MatrixKind(NumberKind) + + An expression representing a matrix may not be an instance of + the Matrix class, but it will have kind ``MatrixKind``: + + >>> from sympy import MatrixExpr, Integral + >>> from sympy.abc import x + >>> intM = Integral(A, x) + >>> isinstance(intM, MatrixExpr) + False + >>> intM.kind + MatrixKind(NumberKind) + + Use ``isinstance()`` to check for ``MatrixKind`` without specifying the + element kind. Use ``is`` to check the kind including the element kind: + + >>> from sympy import Matrix + >>> from sympy.core import NumberKind + >>> from sympy.matrices import MatrixKind + >>> M = Matrix([1, 2]) + >>> isinstance(M.kind, MatrixKind) + True + >>> M.kind is MatrixKind(NumberKind) + True + + See Also + ======== + + sympy.core.kind.NumberKind + sympy.core.kind.UndefinedKind + sympy.core.containers.TupleKind + sympy.sets.sets.SetKind + + """ + def __new__(cls, element_kind=NumberKind): + obj = super().__new__(cls, element_kind) + obj.element_kind = element_kind + return obj + + def __repr__(self): + return "MatrixKind(%s)" % self.element_kind + + +@Mul._kind_dispatcher.register(_NumberKind, MatrixKind) +def num_mat_mul(k1, k2): + """ + Return MatrixKind. The element kind is selected by recursive dispatching. + Do not need to dispatch in reversed order because KindDispatcher + searches for this automatically. + """ + # Deal with Mul._kind_dispatcher's commutativity + # XXX: this function is called with either k1 or k2 as MatrixKind because + # the Mul kind dispatcher is commutative. Maybe it shouldn't be. Need to + # swap the args here because NumberKind does not have an element_kind + # attribute. + if not isinstance(k2, MatrixKind): + k1, k2 = k2, k1 + elemk = Mul._kind_dispatcher(k1, k2.element_kind) + return MatrixKind(elemk) + + +@Mul._kind_dispatcher.register(MatrixKind, MatrixKind) +def mat_mat_mul(k1, k2): + """ + Return MatrixKind. The element kind is selected by recursive dispatching. + """ + elemk = Mul._kind_dispatcher(k1.element_kind, k2.element_kind) + return MatrixKind(elemk) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/matrices.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..fed41a626cb395ac0529071317630d853e0d3a96 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/matrices.py @@ -0,0 +1,687 @@ +# +# A module consisting of deprecated matrix classes. New code should not be +# added here. +# +from sympy.core.basic import Basic +from sympy.core.symbol import Dummy + +from .common import MatrixCommon + +from .exceptions import NonSquareMatrixError + +from .utilities import _iszero, _is_zero_after_expand_mul, _simplify + +from .determinant import ( + _find_reasonable_pivot, _find_reasonable_pivot_naive, + _adjugate, _charpoly, _cofactor, _cofactor_matrix, _per, + _det, _det_bareiss, _det_berkowitz, _det_bird, _det_laplace, _det_LU, + _minor, _minor_submatrix) + +from .reductions import _is_echelon, _echelon_form, _rank, _rref +from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize + +from .eigen import ( + _eigenvals, _eigenvects, + _bidiagonalize, _bidiagonal_decomposition, + _is_diagonalizable, _diagonalize, + _is_positive_definite, _is_positive_semidefinite, + _is_negative_definite, _is_negative_semidefinite, _is_indefinite, + _jordan_form, _left_eigenvects, _singular_values) + + +# This class was previously defined in this module, but was moved to +# sympy.matrices.matrixbase. We import it here for backwards compatibility in +# case someone was importing it from here. +from .matrixbase import MatrixBase + + +__doctest_requires__ = { + ('MatrixEigen.is_indefinite', + 'MatrixEigen.is_negative_definite', + 'MatrixEigen.is_negative_semidefinite', + 'MatrixEigen.is_positive_definite', + 'MatrixEigen.is_positive_semidefinite'): ['matplotlib'], +} + + +class MatrixDeterminant(MatrixCommon): + """Provides basic matrix determinant operations. Should not be instantiated + directly. See ``determinant.py`` for their implementations.""" + + def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul): + return _det_bareiss(self, iszerofunc=iszerofunc) + + def _eval_det_berkowitz(self): + return _det_berkowitz(self) + + def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None): + return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc) + + def _eval_det_bird(self): + return _det_bird(self) + + def _eval_det_laplace(self): + return _det_laplace(self) + + def _eval_determinant(self): # for expressions.determinant.Determinant + return _det(self) + + def adjugate(self, method="berkowitz"): + return _adjugate(self, method=method) + + def charpoly(self, x='lambda', simplify=_simplify): + return _charpoly(self, x=x, simplify=simplify) + + def cofactor(self, i, j, method="berkowitz"): + return _cofactor(self, i, j, method=method) + + def cofactor_matrix(self, method="berkowitz"): + return _cofactor_matrix(self, method=method) + + def det(self, method="bareiss", iszerofunc=None): + return _det(self, method=method, iszerofunc=iszerofunc) + + def per(self): + return _per(self) + + def minor(self, i, j, method="berkowitz"): + return _minor(self, i, j, method=method) + + def minor_submatrix(self, i, j): + return _minor_submatrix(self, i, j) + + _find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__ + _find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__ + _eval_det_bareiss.__doc__ = _det_bareiss.__doc__ + _eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__ + _eval_det_bird.__doc__ = _det_bird.__doc__ + _eval_det_laplace.__doc__ = _det_laplace.__doc__ + _eval_det_lu.__doc__ = _det_LU.__doc__ + _eval_determinant.__doc__ = _det.__doc__ + adjugate.__doc__ = _adjugate.__doc__ + charpoly.__doc__ = _charpoly.__doc__ + cofactor.__doc__ = _cofactor.__doc__ + cofactor_matrix.__doc__ = _cofactor_matrix.__doc__ + det.__doc__ = _det.__doc__ + per.__doc__ = _per.__doc__ + minor.__doc__ = _minor.__doc__ + minor_submatrix.__doc__ = _minor_submatrix.__doc__ + + +class MatrixReductions(MatrixDeterminant): + """Provides basic matrix row/column operations. Should not be instantiated + directly. See ``reductions.py`` for some of their implementations.""" + + def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False): + return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify, + with_pivots=with_pivots) + + @property + def is_echelon(self): + return _is_echelon(self) + + def rank(self, iszerofunc=_iszero, simplify=False): + return _rank(self, iszerofunc=iszerofunc, simplify=simplify) + + def rref_rhs(self, rhs): + """Return reduced row-echelon form of matrix, matrix showing + rhs after reduction steps. ``rhs`` must have the same number + of rows as ``self``. + + Examples + ======== + + >>> from sympy import Matrix, symbols + >>> r1, r2 = symbols('r1 r2') + >>> Matrix([[1, 1], [2, 1]]).rref_rhs(Matrix([r1, r2])) + (Matrix([ + [1, 0], + [0, 1]]), Matrix([ + [ -r1 + r2], + [2*r1 - r2]])) + """ + r, _ = _rref(self.hstack(self, self.eye(self.rows), rhs)) + return r[:, :self.cols], r[:, -rhs.cols:] + + def rref(self, iszerofunc=_iszero, simplify=False, pivots=True, + normalize_last=True): + return _rref(self, iszerofunc=iszerofunc, simplify=simplify, + pivots=pivots, normalize_last=normalize_last) + + echelon_form.__doc__ = _echelon_form.__doc__ + is_echelon.__doc__ = _is_echelon.__doc__ + rank.__doc__ = _rank.__doc__ + rref.__doc__ = _rref.__doc__ + + def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"): + """Validate the arguments for a row/column operation. ``error_str`` + can be one of "row" or "col" depending on the arguments being parsed.""" + if op not in ["n->kn", "n<->m", "n->n+km"]: + raise ValueError("Unknown {} operation '{}'. Valid col operations " + "are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op)) + + # define self_col according to error_str + self_cols = self.cols if error_str == 'col' else self.rows + + # normalize and validate the arguments + if op == "n->kn": + col = col if col is not None else col1 + if col is None or k is None: + raise ValueError("For a {0} operation 'n->kn' you must provide the " + "kwargs `{0}` and `k`".format(error_str)) + if not 0 <= col < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col)) + + elif op == "n<->m": + # we need two cols to swap. It does not matter + # how they were specified, so gather them together and + # remove `None` + cols = {col, k, col1, col2}.difference([None]) + if len(cols) > 2: + # maybe the user left `k` by mistake? + cols = {col, col1, col2}.difference([None]) + if len(cols) != 2: + raise ValueError("For a {0} operation 'n<->m' you must provide the " + "kwargs `{0}1` and `{0}2`".format(error_str)) + col1, col2 = cols + if not 0 <= col1 < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col1)) + if not 0 <= col2 < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2)) + + elif op == "n->n+km": + col = col1 if col is None else col + col2 = col1 if col2 is None else col2 + if col is None or col2 is None or k is None: + raise ValueError("For a {0} operation 'n->n+km' you must provide the " + "kwargs `{0}`, `k`, and `{0}2`".format(error_str)) + if col == col2: + raise ValueError("For a {0} operation 'n->n+km' `{0}` and `{0}2` must " + "be different.".format(error_str)) + if not 0 <= col < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col)) + if not 0 <= col2 < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2)) + + else: + raise ValueError('invalid operation %s' % repr(op)) + + return op, col, k, col1, col2 + + def _eval_col_op_multiply_col_by_const(self, col, k): + def entry(i, j): + if j == col: + return k * self[i, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_col_op_swap(self, col1, col2): + def entry(i, j): + if j == col1: + return self[i, col2] + elif j == col2: + return self[i, col1] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_col_op_add_multiple_to_other_col(self, col, k, col2): + def entry(i, j): + if j == col: + return self[i, j] + k * self[i, col2] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_row_op_swap(self, row1, row2): + def entry(i, j): + if i == row1: + return self[row2, j] + elif i == row2: + return self[row1, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_row_op_multiply_row_by_const(self, row, k): + def entry(i, j): + if i == row: + return k * self[i, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_row_op_add_multiple_to_other_row(self, row, k, row2): + def entry(i, j): + if i == row: + return self[i, j] + k * self[row2, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def elementary_col_op(self, op="n->kn", col=None, k=None, col1=None, col2=None): + """Performs the elementary column operation `op`. + + `op` may be one of + + * ``"n->kn"`` (column n goes to k*n) + * ``"n<->m"`` (swap column n and column m) + * ``"n->n+km"`` (column n goes to column n + k*column m) + + Parameters + ========== + + op : string; the elementary row operation + col : the column to apply the column operation + k : the multiple to apply in the column operation + col1 : one column of a column swap + col2 : second column of a column swap or column "m" in the column operation + "n->n+km" + """ + + op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, "col") + + # now that we've validated, we're all good to dispatch + if op == "n->kn": + return self._eval_col_op_multiply_col_by_const(col, k) + if op == "n<->m": + return self._eval_col_op_swap(col1, col2) + if op == "n->n+km": + return self._eval_col_op_add_multiple_to_other_col(col, k, col2) + + def elementary_row_op(self, op="n->kn", row=None, k=None, row1=None, row2=None): + """Performs the elementary row operation `op`. + + `op` may be one of + + * ``"n->kn"`` (row n goes to k*n) + * ``"n<->m"`` (swap row n and row m) + * ``"n->n+km"`` (row n goes to row n + k*row m) + + Parameters + ========== + + op : string; the elementary row operation + row : the row to apply the row operation + k : the multiple to apply in the row operation + row1 : one row of a row swap + row2 : second row of a row swap or row "m" in the row operation + "n->n+km" + """ + + op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, "row") + + # now that we've validated, we're all good to dispatch + if op == "n->kn": + return self._eval_row_op_multiply_row_by_const(row, k) + if op == "n<->m": + return self._eval_row_op_swap(row1, row2) + if op == "n->n+km": + return self._eval_row_op_add_multiple_to_other_row(row, k, row2) + + +class MatrixSubspaces(MatrixReductions): + """Provides methods relating to the fundamental subspaces of a matrix. + Should not be instantiated directly. See ``subspaces.py`` for their + implementations.""" + + def columnspace(self, simplify=False): + return _columnspace(self, simplify=simplify) + + def nullspace(self, simplify=False, iszerofunc=_iszero): + return _nullspace(self, simplify=simplify, iszerofunc=iszerofunc) + + def rowspace(self, simplify=False): + return _rowspace(self, simplify=simplify) + + # This is a classmethod but is converted to such later in order to allow + # assignment of __doc__ since that does not work for already wrapped + # classmethods in Python 3.6. + def orthogonalize(cls, *vecs, **kwargs): + return _orthogonalize(cls, *vecs, **kwargs) + + columnspace.__doc__ = _columnspace.__doc__ + nullspace.__doc__ = _nullspace.__doc__ + rowspace.__doc__ = _rowspace.__doc__ + orthogonalize.__doc__ = _orthogonalize.__doc__ + + orthogonalize = classmethod(orthogonalize) # type:ignore + + +class MatrixEigen(MatrixSubspaces): + """Provides basic matrix eigenvalue/vector operations. + Should not be instantiated directly. See ``eigen.py`` for their + implementations.""" + + def eigenvals(self, error_when_incomplete=True, **flags): + return _eigenvals(self, error_when_incomplete=error_when_incomplete, **flags) + + def eigenvects(self, error_when_incomplete=True, iszerofunc=_iszero, **flags): + return _eigenvects(self, error_when_incomplete=error_when_incomplete, + iszerofunc=iszerofunc, **flags) + + def is_diagonalizable(self, reals_only=False, **kwargs): + return _is_diagonalizable(self, reals_only=reals_only, **kwargs) + + def diagonalize(self, reals_only=False, sort=False, normalize=False): + return _diagonalize(self, reals_only=reals_only, sort=sort, + normalize=normalize) + + def bidiagonalize(self, upper=True): + return _bidiagonalize(self, upper=upper) + + def bidiagonal_decomposition(self, upper=True): + return _bidiagonal_decomposition(self, upper=upper) + + @property + def is_positive_definite(self): + return _is_positive_definite(self) + + @property + def is_positive_semidefinite(self): + return _is_positive_semidefinite(self) + + @property + def is_negative_definite(self): + return _is_negative_definite(self) + + @property + def is_negative_semidefinite(self): + return _is_negative_semidefinite(self) + + @property + def is_indefinite(self): + return _is_indefinite(self) + + def jordan_form(self, calc_transform=True, **kwargs): + return _jordan_form(self, calc_transform=calc_transform, **kwargs) + + def left_eigenvects(self, **flags): + return _left_eigenvects(self, **flags) + + def singular_values(self): + return _singular_values(self) + + eigenvals.__doc__ = _eigenvals.__doc__ + eigenvects.__doc__ = _eigenvects.__doc__ + is_diagonalizable.__doc__ = _is_diagonalizable.__doc__ + diagonalize.__doc__ = _diagonalize.__doc__ + is_positive_definite.__doc__ = _is_positive_definite.__doc__ + is_positive_semidefinite.__doc__ = _is_positive_semidefinite.__doc__ + is_negative_definite.__doc__ = _is_negative_definite.__doc__ + is_negative_semidefinite.__doc__ = _is_negative_semidefinite.__doc__ + is_indefinite.__doc__ = _is_indefinite.__doc__ + jordan_form.__doc__ = _jordan_form.__doc__ + left_eigenvects.__doc__ = _left_eigenvects.__doc__ + singular_values.__doc__ = _singular_values.__doc__ + bidiagonalize.__doc__ = _bidiagonalize.__doc__ + bidiagonal_decomposition.__doc__ = _bidiagonal_decomposition.__doc__ + + +class MatrixCalculus(MatrixCommon): + """Provides calculus-related matrix operations.""" + + def diff(self, *args, evaluate=True, **kwargs): + """Calculate the derivative of each element in the matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.diff(x) + Matrix([ + [1, 0], + [0, 0]]) + + See Also + ======== + + integrate + limit + """ + # XXX this should be handled here rather than in Derivative + from sympy.tensor.array.array_derivatives import ArrayDerivative + deriv = ArrayDerivative(self, *args, evaluate=evaluate) + # XXX This can rather changed to always return immutable matrix + if not isinstance(self, Basic) and evaluate: + return deriv.as_mutable() + return deriv + + def _eval_derivative(self, arg): + return self.applyfunc(lambda x: x.diff(arg)) + + def integrate(self, *args, **kwargs): + """Integrate each element of the matrix. ``args`` will + be passed to the ``integrate`` function. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.integrate((x, )) + Matrix([ + [x**2/2, x*y], + [ x, 0]]) + >>> M.integrate((x, 0, 2)) + Matrix([ + [2, 2*y], + [2, 0]]) + + See Also + ======== + + limit + diff + """ + return self.applyfunc(lambda x: x.integrate(*args, **kwargs)) + + def jacobian(self, X): + """Calculates the Jacobian matrix (derivative of a vector-valued function). + + Parameters + ========== + + ``self`` : vector of expressions representing functions f_i(x_1, ..., x_n). + X : set of x_i's in order, it can be a list or a Matrix + + Both ``self`` and X can be a row or a column matrix in any order + (i.e., jacobian() should always work). + + Examples + ======== + + >>> from sympy import sin, cos, Matrix + >>> from sympy.abc import rho, phi + >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2]) + >>> Y = Matrix([rho, phi]) + >>> X.jacobian(Y) + Matrix([ + [cos(phi), -rho*sin(phi)], + [sin(phi), rho*cos(phi)], + [ 2*rho, 0]]) + >>> X = Matrix([rho*cos(phi), rho*sin(phi)]) + >>> X.jacobian(Y) + Matrix([ + [cos(phi), -rho*sin(phi)], + [sin(phi), rho*cos(phi)]]) + + See Also + ======== + + hessian + wronskian + """ + if not isinstance(X, MatrixBase): + X = self._new(X) + # Both X and ``self`` can be a row or a column matrix, so we need to make + # sure all valid combinations work, but everything else fails: + if self.shape[0] == 1: + m = self.shape[1] + elif self.shape[1] == 1: + m = self.shape[0] + else: + raise TypeError("``self`` must be a row or a column matrix") + if X.shape[0] == 1: + n = X.shape[1] + elif X.shape[1] == 1: + n = X.shape[0] + else: + raise TypeError("X must be a row or a column matrix") + + # m is the number of functions and n is the number of variables + # computing the Jacobian is now easy: + return self._new(m, n, lambda j, i: self[j].diff(X[i])) + + def limit(self, *args): + """Calculate the limit of each element in the matrix. + ``args`` will be passed to the ``limit`` function. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.limit(x, 2) + Matrix([ + [2, y], + [1, 0]]) + + See Also + ======== + + integrate + diff + """ + return self.applyfunc(lambda x: x.limit(*args)) + + +# https://github.com/sympy/sympy/pull/12854 +class MatrixDeprecated(MatrixCommon): + """A class to house deprecated matrix methods.""" + def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify): + return self.charpoly(x=x) + + def berkowitz_det(self): + """Computes determinant using Berkowitz method. + + See Also + ======== + + det + berkowitz + """ + return self.det(method='berkowitz') + + def berkowitz_eigenvals(self, **flags): + """Computes eigenvalues of a Matrix using Berkowitz method. + + See Also + ======== + + berkowitz + """ + return self.eigenvals(**flags) + + def berkowitz_minors(self): + """Computes principal minors using Berkowitz method. + + See Also + ======== + + berkowitz + """ + sign, minors = self.one, [] + + for poly in self.berkowitz(): + minors.append(sign * poly[-1]) + sign = -sign + + return tuple(minors) + + def berkowitz(self): + from sympy.matrices import zeros + berk = ((1,),) + if not self: + return berk + + if not self.is_square: + raise NonSquareMatrixError() + + A, N = self, self.rows + transforms = [0] * (N - 1) + + for n in range(N, 1, -1): + T, k = zeros(n + 1, n), n - 1 + + R, C = -A[k, :k], A[:k, k] + A, a = A[:k, :k], -A[k, k] + + items = [C] + + for i in range(0, n - 2): + items.append(A * items[i]) + + for i, B in enumerate(items): + items[i] = (R * B)[0, 0] + + items = [self.one, a] + items + + for i in range(n): + T[i:, i] = items[:n - i + 1] + + transforms[k - 1] = T + + polys = [self._new([self.one, -A[0, 0]])] + + for i, T in enumerate(transforms): + polys.append(T * polys[i]) + + return berk + tuple(map(tuple, polys)) + + def cofactorMatrix(self, method="berkowitz"): + return self.cofactor_matrix(method=method) + + def det_bareis(self): + return _det_bareiss(self) + + def det_LU_decomposition(self): + """Compute matrix determinant using LU decomposition. + + + Note that this method fails if the LU decomposition itself + fails. In particular, if the matrix has no inverse this method + will fail. + + TODO: Implement algorithm for sparse matrices (SFF), + https://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps + + See Also + ======== + + + det + det_bareiss + berkowitz_det + """ + return self.det(method='lu') + + def jordan_cell(self, eigenval, n): + return self.jordan_block(size=n, eigenvalue=eigenval) + + def jordan_cells(self, calc_transformation=True): + P, J = self.jordan_form() + return P, J.get_diag_blocks() + + def minorEntry(self, i, j, method="berkowitz"): + return self.minor(i, j, method=method) + + def minorMatrix(self, i, j): + return self.minor_submatrix(i, j) + + def permuteBkwd(self, perm): + """Permute the rows of the matrix with the given permutation in reverse.""" + return self.permute_rows(perm, direction='backward') + + def permuteFwd(self, perm): + """Permute the rows of the matrix with the given permutation.""" + return self.permute_rows(perm, direction='forward') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/matrixbase.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/matrixbase.py new file mode 100644 index 0000000000000000000000000000000000000000..49acc04043b30e003f7eed256f2e06e6a6556401 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/matrixbase.py @@ -0,0 +1,5428 @@ +from __future__ import annotations +from collections import defaultdict +from collections.abc import Iterable +from inspect import isfunction +from functools import reduce + +from sympy.assumptions.refine import refine +from sympy.core import SympifyError, Add +from sympy.core.basic import Atom, Basic +from sympy.core.kind import UndefinedKind +from sympy.core.numbers import Integer +from sympy.core.mod import Mod +from sympy.core.symbol import Symbol, Dummy +from sympy.core.sympify import sympify, _sympify +from sympy.core.function import diff +from sympy.polys import cancel +from sympy.functions.elementary.complexes import Abs, re, im +from sympy.printing import sstr +from sympy.functions.elementary.miscellaneous import Max, Min, sqrt +from sympy.functions.special.tensor_functions import KroneckerDelta, LeviCivita +from sympy.core.singleton import S +from sympy.printing.defaults import Printable +from sympy.printing.str import StrPrinter +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.combinatorial.factorials import binomial, factorial + +import mpmath as mp +from collections.abc import Callable +from sympy.utilities.iterables import reshape +from sympy.core.expr import Expr +from sympy.core.power import Pow +from sympy.core.symbol import uniquely_named_symbol + +from .utilities import _dotprodsimp, _simplify as _utilities_simplify +from sympy.polys.polytools import Poly +from sympy.utilities.iterables import flatten, is_sequence +from sympy.utilities.misc import as_int, filldedent +from sympy.core.decorators import call_highest_priority +from sympy.core.logic import fuzzy_and, FuzzyBool +from sympy.tensor.array import NDimArray +from sympy.utilities.iterables import NotIterable + +from .utilities import _get_intermediate_simp_bool + +from .kind import MatrixKind + +from .exceptions import ( + MatrixError, ShapeError, NonSquareMatrixError, NonInvertibleMatrixError, +) + +from .utilities import _iszero, _is_zero_after_expand_mul + +from .determinant import ( + _find_reasonable_pivot, _find_reasonable_pivot_naive, + _adjugate, _charpoly, _cofactor, _cofactor_matrix, _per, + _det, _det_bareiss, _det_berkowitz, _det_bird, _det_laplace, _det_LU, + _minor, _minor_submatrix) + +from .reductions import _is_echelon, _echelon_form, _rank, _rref + +from .solvers import ( + _diagonal_solve, _lower_triangular_solve, _upper_triangular_solve, + _cholesky_solve, _LDLsolve, _LUsolve, _QRsolve, _gauss_jordan_solve, + _pinv_solve, _cramer_solve, _solve, _solve_least_squares) + +from .inverse import ( + _pinv, _inv_ADJ, _inv_GE, _inv_LU, _inv_CH, _inv_LDL, _inv_QR, + _inv, _inv_block) + +from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize + +from .eigen import ( + _eigenvals, _eigenvects, + _bidiagonalize, _bidiagonal_decomposition, + _is_diagonalizable, _diagonalize, + _is_positive_definite, _is_positive_semidefinite, + _is_negative_definite, _is_negative_semidefinite, _is_indefinite, + _jordan_form, _left_eigenvects, _singular_values) + +from .decompositions import ( + _rank_decomposition, _cholesky, _LDLdecomposition, + _LUdecomposition, _LUdecomposition_Simple, _LUdecompositionFF, + _singular_value_decomposition, _QRdecomposition, _upper_hessenberg_decomposition) + +from .graph import ( + _connected_components, _connected_components_decomposition, + _strongly_connected_components, _strongly_connected_components_decomposition) + + +__doctest_requires__ = { + ('MatrixBase.is_indefinite', + 'MatrixBase.is_positive_definite', + 'MatrixBase.is_positive_semidefinite', + 'MatrixBase.is_negative_definite', + 'MatrixBase.is_negative_semidefinite'): ['matplotlib'], +} + + +class MatrixBase(Printable): + """All common matrix operations including basic arithmetic, shaping, + and special matrices like `zeros`, and `eye`.""" + + _op_priority = 10.01 + + # Added just for numpy compatibility + __array_priority__ = 11 + + is_Matrix = True + _class_priority = 3 + _sympify = staticmethod(sympify) + zero = S.Zero + one = S.One + + _diff_wrt: bool = True + rows: int + cols: int + _simplify = None + + @classmethod + def _new(cls, *args, **kwargs): + """`_new` must, at minimum, be callable as + `_new(rows, cols, mat) where mat is a flat list of the + elements of the matrix.""" + raise NotImplementedError("Subclasses must implement this.") + + def __eq__(self, other): + raise NotImplementedError("Subclasses must implement this.") + + def __getitem__(self, key): + """Implementations of __getitem__ should accept ints, in which + case the matrix is indexed as a flat list, tuples (i,j) in which + case the (i,j) entry is returned, slices, or mixed tuples (a,b) + where a and b are any combination of slices and integers.""" + raise NotImplementedError("Subclasses must implement this.") + + @property + def shape(self): + """The shape (dimensions) of the matrix as the 2-tuple (rows, cols). + + Examples + ======== + + >>> from sympy import zeros + >>> M = zeros(2, 3) + >>> M.shape + (2, 3) + >>> M.rows + 2 + >>> M.cols + 3 + """ + return (self.rows, self.cols) + + def _eval_col_del(self, col): + def entry(i, j): + return self[i, j] if j < col else self[i, j + 1] + return self._new(self.rows, self.cols - 1, entry) + + def _eval_col_insert(self, pos, other): + + def entry(i, j): + if j < pos: + return self[i, j] + elif pos <= j < pos + other.cols: + return other[i, j - pos] + return self[i, j - other.cols] + + return self._new(self.rows, self.cols + other.cols, entry) + + def _eval_col_join(self, other): + rows = self.rows + + def entry(i, j): + if i < rows: + return self[i, j] + return other[i - rows, j] + + return classof(self, other)._new(self.rows + other.rows, self.cols, + entry) + + def _eval_extract(self, rowsList, colsList): + mat = list(self) + cols = self.cols + indices = (i * cols + j for i in rowsList for j in colsList) + return self._new(len(rowsList), len(colsList), + [mat[i] for i in indices]) + + def _eval_get_diag_blocks(self): + sub_blocks = [] + + def recurse_sub_blocks(M): + for i in range(1, M.shape[0] + 1): + if i == 1: + to_the_right = M[0, i:] + to_the_bottom = M[i:, 0] + else: + to_the_right = M[:i, i:] + to_the_bottom = M[i:, :i] + if any(to_the_right) or any(to_the_bottom): + continue + sub_blocks.append(M[:i, :i]) + if M.shape != M[:i, :i].shape: + recurse_sub_blocks(M[i:, i:]) + return + + recurse_sub_blocks(self) + return sub_blocks + + def _eval_row_del(self, row): + def entry(i, j): + return self[i, j] if i < row else self[i + 1, j] + return self._new(self.rows - 1, self.cols, entry) + + def _eval_row_insert(self, pos, other): + entries = list(self) + insert_pos = pos * self.cols + entries[insert_pos:insert_pos] = list(other) + return self._new(self.rows + other.rows, self.cols, entries) + + def _eval_row_join(self, other): + cols = self.cols + + def entry(i, j): + if j < cols: + return self[i, j] + return other[i, j - cols] + + return classof(self, other)._new(self.rows, self.cols + other.cols, + entry) + + def _eval_tolist(self): + return [list(self[i,:]) for i in range(self.rows)] + + def _eval_todok(self): + dok = {} + rows, cols = self.shape + for i in range(rows): + for j in range(cols): + val = self[i, j] + if val != self.zero: + dok[i, j] = val + return dok + + @classmethod + def _eval_from_dok(cls, rows, cols, dok): + out_flat = [cls.zero] * (rows * cols) + for (i, j), val in dok.items(): + out_flat[i * cols + j] = val + return cls._new(rows, cols, out_flat) + + def _eval_vec(self): + rows = self.rows + + def entry(n, _): + # we want to read off the columns first + j = n // rows + i = n - j * rows + return self[i, j] + + return self._new(len(self), 1, entry) + + def _eval_vech(self, diagonal): + c = self.cols + v = [] + if diagonal: + for j in range(c): + for i in range(j, c): + v.append(self[i, j]) + else: + for j in range(c): + for i in range(j + 1, c): + v.append(self[i, j]) + return self._new(len(v), 1, v) + + def col_del(self, col): + """Delete the specified column.""" + if col < 0: + col += self.cols + if not 0 <= col < self.cols: + raise IndexError("Column {} is out of range.".format(col)) + return self._eval_col_del(col) + + def col_insert(self, pos, other): + """Insert one or more columns at the given column position. + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(3, 1) + >>> M.col_insert(1, V) + Matrix([ + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + + See Also + ======== + + col + row_insert + """ + # Allows you to build a matrix even if it is null matrix + if not self: + return type(self)(other) + + pos = as_int(pos) + + if pos < 0: + pos = self.cols + pos + if pos < 0: + pos = 0 + elif pos > self.cols: + pos = self.cols + + if self.rows != other.rows: + raise ShapeError( + "The matrices have incompatible number of rows ({} and {})" + .format(self.rows, other.rows)) + + return self._eval_col_insert(pos, other) + + def col_join(self, other): + """Concatenates two matrices along self's last and other's first row. + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(1, 3) + >>> M.col_join(V) + Matrix([ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [1, 1, 1]]) + + See Also + ======== + + col + row_join + """ + # A null matrix can always be stacked (see #10770) + if self.rows == 0 and self.cols != other.cols: + return self._new(0, other.cols, []).col_join(other) + + if self.cols != other.cols: + raise ShapeError( + "The matrices have incompatible number of columns ({} and {})" + .format(self.cols, other.cols)) + return self._eval_col_join(other) + + def col(self, j): + """Elementary column selector. + + Examples + ======== + + >>> from sympy import eye + >>> eye(2).col(0) + Matrix([ + [1], + [0]]) + + See Also + ======== + + row + col_del + col_join + col_insert + """ + return self[:, j] + + def extract(self, rowsList, colsList): + r"""Return a submatrix by specifying a list of rows and columns. + Negative indices can be given. All indices must be in the range + $-n \le i < n$ where $n$ is the number of rows or columns. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(4, 3, range(12)) + >>> m + Matrix([ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8], + [9, 10, 11]]) + >>> m.extract([0, 1, 3], [0, 1]) + Matrix([ + [0, 1], + [3, 4], + [9, 10]]) + + Rows or columns can be repeated: + + >>> m.extract([0, 0, 1], [-1]) + Matrix([ + [2], + [2], + [5]]) + + Every other row can be taken by using range to provide the indices: + + >>> m.extract(range(0, m.rows, 2), [-1]) + Matrix([ + [2], + [8]]) + + RowsList or colsList can also be a list of booleans, in which case + the rows or columns corresponding to the True values will be selected: + + >>> m.extract([0, 1, 2, 3], [True, False, True]) + Matrix([ + [0, 2], + [3, 5], + [6, 8], + [9, 11]]) + """ + + if not is_sequence(rowsList) or not is_sequence(colsList): + raise TypeError("rowsList and colsList must be iterable") + # ensure rowsList and colsList are lists of integers + if rowsList and all(isinstance(i, bool) for i in rowsList): + rowsList = [index for index, item in enumerate(rowsList) if item] + if colsList and all(isinstance(i, bool) for i in colsList): + colsList = [index for index, item in enumerate(colsList) if item] + + # ensure everything is in range + rowsList = [a2idx(k, self.rows) for k in rowsList] + colsList = [a2idx(k, self.cols) for k in colsList] + + return self._eval_extract(rowsList, colsList) + + def get_diag_blocks(self): + """Obtains the square sub-matrices on the main diagonal of a square matrix. + + Useful for inverting symbolic matrices or solving systems of + linear equations which may be decoupled by having a block diagonal + structure. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y, z + >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]]) + >>> a1, a2, a3 = A.get_diag_blocks() + >>> a1 + Matrix([ + [1, 3], + [y, z**2]]) + >>> a2 + Matrix([[x]]) + >>> a3 + Matrix([[0]]) + + """ + return self._eval_get_diag_blocks() + + @classmethod + def hstack(cls, *args): + """Return a matrix formed by joining args horizontally (i.e. + by repeated application of row_join). + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> Matrix.hstack(eye(2), 2*eye(2)) + Matrix([ + [1, 0, 2, 0], + [0, 1, 0, 2]]) + """ + if len(args) == 0: + return cls._new() + + kls = type(args[0]) + return reduce(kls.row_join, args) + + def reshape(self, rows, cols): + """Reshape the matrix. Total number of elements must remain the same. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 3, lambda i, j: 1) + >>> m + Matrix([ + [1, 1, 1], + [1, 1, 1]]) + >>> m.reshape(1, 6) + Matrix([[1, 1, 1, 1, 1, 1]]) + >>> m.reshape(3, 2) + Matrix([ + [1, 1], + [1, 1], + [1, 1]]) + + """ + if self.rows * self.cols != rows * cols: + raise ValueError("Invalid reshape parameters %d %d" % (rows, cols)) + dok = {divmod(i*self.cols + j, cols): + v for (i, j), v in self.todok().items()} + return self._eval_from_dok(rows, cols, dok) + + def row_del(self, row): + """Delete the specified row.""" + if row < 0: + row += self.rows + if not 0 <= row < self.rows: + raise IndexError("Row {} is out of range.".format(row)) + + return self._eval_row_del(row) + + def row_insert(self, pos, other): + """Insert one or more rows at the given row position. + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(1, 3) + >>> M.row_insert(1, V) + Matrix([ + [0, 0, 0], + [1, 1, 1], + [0, 0, 0], + [0, 0, 0]]) + + See Also + ======== + + row + col_insert + """ + # Allows you to build a matrix even if it is null matrix + if not self: + return self._new(other) + + pos = as_int(pos) + + if pos < 0: + pos = self.rows + pos + if pos < 0: + pos = 0 + elif pos > self.rows: + pos = self.rows + + if self.cols != other.cols: + raise ShapeError( + "The matrices have incompatible number of columns ({} and {})" + .format(self.cols, other.cols)) + + return self._eval_row_insert(pos, other) + + def row_join(self, other): + """Concatenates two matrices along self's last and rhs's first column + + Examples + ======== + + >>> from sympy import zeros, ones + >>> M = zeros(3) + >>> V = ones(3, 1) + >>> M.row_join(V) + Matrix([ + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1]]) + + See Also + ======== + + row + col_join + """ + # A null matrix can always be stacked (see #10770) + if self.cols == 0 and self.rows != other.rows: + return self._new(other.rows, 0, []).row_join(other) + + if self.rows != other.rows: + raise ShapeError( + "The matrices have incompatible number of rows ({} and {})" + .format(self.rows, other.rows)) + return self._eval_row_join(other) + + def diagonal(self, k=0): + """Returns the kth diagonal of self. The main diagonal + corresponds to `k=0`; diagonals above and below correspond to + `k > 0` and `k < 0`, respectively. The values of `self[i, j]` + for which `j - i = k`, are returned in order of increasing + `i + j`, starting with `i + j = |k|`. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(3, 3, lambda i, j: j - i); m + Matrix([ + [ 0, 1, 2], + [-1, 0, 1], + [-2, -1, 0]]) + >>> _.diagonal() + Matrix([[0, 0, 0]]) + >>> m.diagonal(1) + Matrix([[1, 1]]) + >>> m.diagonal(-2) + Matrix([[-2]]) + + Even though the diagonal is returned as a Matrix, the element + retrieval can be done with a single index: + + >>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1] + 2 + + See Also + ======== + + diag + """ + rv = [] + k = as_int(k) + r = 0 if k > 0 else -k + c = 0 if r else k + while True: + if r == self.rows or c == self.cols: + break + rv.append(self[r, c]) + r += 1 + c += 1 + if not rv: + raise ValueError(filldedent(''' + The %s diagonal is out of range [%s, %s]''' % ( + k, 1 - self.rows, self.cols - 1))) + return self._new(1, len(rv), rv) + + def row(self, i): + """Elementary row selector. + + Examples + ======== + + >>> from sympy import eye + >>> eye(2).row(0) + Matrix([[1, 0]]) + + See Also + ======== + + col + row_del + row_join + row_insert + """ + return self[i, :] + + def todok(self): + """Return the matrix as dictionary of keys. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix.eye(3) + >>> M.todok() + {(0, 0): 1, (1, 1): 1, (2, 2): 1} + """ + return self._eval_todok() + + @classmethod + def from_dok(cls, rows, cols, dok): + """Create a matrix from a dictionary of keys. + + Examples + ======== + + >>> from sympy import Matrix + >>> d = {(0, 0): 1, (1, 2): 3, (2, 1): 4} + >>> Matrix.from_dok(3, 3, d) + Matrix([ + [1, 0, 0], + [0, 0, 3], + [0, 4, 0]]) + """ + dok = {ij: cls._sympify(val) for ij, val in dok.items()} + return cls._eval_from_dok(rows, cols, dok) + + def tolist(self): + """Return the Matrix as a nested Python list. + + Examples + ======== + + >>> from sympy import Matrix, ones + >>> m = Matrix(3, 3, range(9)) + >>> m + Matrix([ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> m.tolist() + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + >>> ones(3, 0).tolist() + [[], [], []] + + When there are no rows then it will not be possible to tell how + many columns were in the original matrix: + + >>> ones(0, 3).tolist() + [] + + """ + if not self.rows: + return [] + if not self.cols: + return [[] for i in range(self.rows)] + return self._eval_tolist() + + def todod(M): + """Returns matrix as dict of dicts containing non-zero elements of the Matrix + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[0, 1],[0, 3]]) + >>> A + Matrix([ + [0, 1], + [0, 3]]) + >>> A.todod() + {0: {1: 1}, 1: {1: 3}} + + + """ + rowsdict = {} + Mlol = M.tolist() + for i, Mi in enumerate(Mlol): + row = {j: Mij for j, Mij in enumerate(Mi) if Mij} + if row: + rowsdict[i] = row + return rowsdict + + def vec(self): + """Return the Matrix converted into a one column matrix by stacking columns + + Examples + ======== + + >>> from sympy import Matrix + >>> m=Matrix([[1, 3], [2, 4]]) + >>> m + Matrix([ + [1, 3], + [2, 4]]) + >>> m.vec() + Matrix([ + [1], + [2], + [3], + [4]]) + + See Also + ======== + + vech + """ + return self._eval_vec() + + def vech(self, diagonal=True, check_symmetry=True): + """Reshapes the matrix into a column vector by stacking the + elements in the lower triangle. + + Parameters + ========== + + diagonal : bool, optional + If ``True``, it includes the diagonal elements. + + check_symmetry : bool, optional + If ``True``, it checks whether the matrix is symmetric. + + Examples + ======== + + >>> from sympy import Matrix + >>> m=Matrix([[1, 2], [2, 3]]) + >>> m + Matrix([ + [1, 2], + [2, 3]]) + >>> m.vech() + Matrix([ + [1], + [2], + [3]]) + >>> m.vech(diagonal=False) + Matrix([[2]]) + + Notes + ===== + + This should work for symmetric matrices and ``vech`` can + represent symmetric matrices in vector form with less size than + ``vec``. + + See Also + ======== + + vec + """ + if not self.is_square: + raise NonSquareMatrixError + + if check_symmetry and not self.is_symmetric(): + raise ValueError("The matrix is not symmetric.") + + return self._eval_vech(diagonal) + + @classmethod + def vstack(cls, *args): + """Return a matrix formed by joining args vertically (i.e. + by repeated application of col_join). + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> Matrix.vstack(eye(2), 2*eye(2)) + Matrix([ + [1, 0], + [0, 1], + [2, 0], + [0, 2]]) + """ + if len(args) == 0: + return cls._new() + + kls = type(args[0]) + return reduce(kls.col_join, args) + + @classmethod + def _eval_diag(cls, rows, cols, diag_dict): + """diag_dict is a defaultdict containing + all the entries of the diagonal matrix.""" + def entry(i, j): + return diag_dict[(i, j)] + return cls._new(rows, cols, entry) + + @classmethod + def _eval_eye(cls, rows, cols): + vals = [cls.zero]*(rows*cols) + vals[::cols+1] = [cls.one]*min(rows, cols) + return cls._new(rows, cols, vals, copy=False) + + @classmethod + def _eval_jordan_block(cls, size: int, eigenvalue, band='upper'): + if band == 'lower': + def entry(i, j): + if i == j: + return eigenvalue + elif j + 1 == i: + return cls.one + return cls.zero + else: + def entry(i, j): + if i == j: + return eigenvalue + elif i + 1 == j: + return cls.one + return cls.zero + return cls._new(size, size, entry) + + @classmethod + def _eval_ones(cls, rows, cols): + def entry(i, j): + return cls.one + return cls._new(rows, cols, entry) + + @classmethod + def _eval_zeros(cls, rows, cols): + return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False) + + @classmethod + def _eval_wilkinson(cls, n): + def entry(i, j): + return cls.one if i + 1 == j else cls.zero + + D = cls._new(2*n + 1, 2*n + 1, entry) + + wminus = cls.diag(list(range(-n, n + 1)), unpack=True) + D + D.T + wplus = abs(cls.diag(list(range(-n, n + 1)), unpack=True)) + D + D.T + + return wminus, wplus + + @classmethod + def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs): + """Returns a matrix with the specified diagonal. + If matrices are passed, a block-diagonal matrix + is created (i.e. the "direct sum" of the matrices). + + kwargs + ====== + + rows : rows of the resulting matrix; computed if + not given. + + cols : columns of the resulting matrix; computed if + not given. + + cls : class for the resulting matrix + + unpack : bool which, when True (default), unpacks a single + sequence rather than interpreting it as a Matrix. + + strict : bool which, when False (default), allows Matrices to + have variable-length rows. + + Examples + ======== + + >>> from sympy import Matrix + >>> Matrix.diag(1, 2, 3) + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + + The current default is to unpack a single sequence. If this is + not desired, set `unpack=False` and it will be interpreted as + a matrix. + + >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3) + True + + When more than one element is passed, each is interpreted as + something to put on the diagonal. Lists are converted to + matrices. Filling of the diagonal always continues from + the bottom right hand corner of the previous item: this + will create a block-diagonal matrix whether the matrices + are square or not. + + >>> col = [1, 2, 3] + >>> row = [[4, 5]] + >>> Matrix.diag(col, row) + Matrix([ + [1, 0, 0], + [2, 0, 0], + [3, 0, 0], + [0, 4, 5]]) + + When `unpack` is False, elements within a list need not all be + of the same length. Setting `strict` to True would raise a + ValueError for the following: + + >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False) + Matrix([ + [1, 2, 3], + [4, 5, 0], + [6, 0, 0]]) + + The type of the returned matrix can be set with the ``cls`` + keyword. + + >>> from sympy import ImmutableMatrix + >>> from sympy.utilities.misc import func_name + >>> func_name(Matrix.diag(1, cls=ImmutableMatrix)) + 'ImmutableDenseMatrix' + + A zero dimension matrix can be used to position the start of + the filling at the start of an arbitrary row or column: + + >>> from sympy import ones + >>> r2 = ones(0, 2) + >>> Matrix.diag(r2, 1, 2) + Matrix([ + [0, 0, 1, 0], + [0, 0, 0, 2]]) + + See Also + ======== + eye + diagonal + .dense.diag + .expressions.blockmatrix.BlockMatrix + .sparsetools.banded + """ + from sympy.matrices.matrixbase import MatrixBase + from sympy.matrices.dense import Matrix + from sympy.matrices import SparseMatrix + klass = kwargs.get('cls', kls) + if unpack and len(args) == 1 and is_sequence(args[0]) and \ + not isinstance(args[0], MatrixBase): + args = args[0] + + # fill a default dict with the diagonal entries + diag_entries = defaultdict(int) + rmax = cmax = 0 # keep track of the biggest index seen + for m in args: + if isinstance(m, list): + if strict: + # if malformed, Matrix will raise an error + _ = Matrix(m) + r, c = _.shape + m = _.tolist() + else: + r, c, smat = SparseMatrix._handle_creation_inputs(m) + for (i, j), _ in smat.items(): + diag_entries[(i + rmax, j + cmax)] = _ + m = [] # to skip process below + elif hasattr(m, 'shape'): # a Matrix + # convert to list of lists + r, c = m.shape + m = m.tolist() + else: # in this case, we're a single value + diag_entries[(rmax, cmax)] = m + rmax += 1 + cmax += 1 + continue + # process list of lists + for i, mi in enumerate(m): + for j, _ in enumerate(mi): + diag_entries[(i + rmax, j + cmax)] = _ + rmax += r + cmax += c + if rows is None: + rows, cols = cols, rows + if rows is None: + rows, cols = rmax, cmax + else: + cols = rows if cols is None else cols + if rows < rmax or cols < cmax: + raise ValueError(filldedent(''' + The constructed matrix is {} x {} but a size of {} x {} + was specified.'''.format(rmax, cmax, rows, cols))) + return klass._eval_diag(rows, cols, diag_entries) + + @classmethod + def eye(kls, rows, cols=None, **kwargs): + """Returns an identity matrix. + + Parameters + ========== + + rows : rows of the matrix + cols : cols of the matrix (if None, cols=rows) + + kwargs + ====== + cls : class of the returned matrix + """ + if cols is None: + cols = rows + if rows < 0 or cols < 0: + raise ValueError("Cannot create a {} x {} matrix. " + "Both dimensions must be positive".format(rows, cols)) + klass = kwargs.get('cls', kls) + rows, cols = as_int(rows), as_int(cols) + + return klass._eval_eye(rows, cols) + + @classmethod + def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): + """Returns a Jordan block + + Parameters + ========== + + size : Integer, optional + Specifies the shape of the Jordan block matrix. + + eigenvalue : Number or Symbol + Specifies the value for the main diagonal of the matrix. + + .. note:: + The keyword ``eigenval`` is also specified as an alias + of this keyword, but it is not recommended to use. + + We may deprecate the alias in later release. + + band : 'upper' or 'lower', optional + Specifies the position of the off-diagonal to put `1` s on. + + cls : Matrix, optional + Specifies the matrix class of the output form. + + If it is not specified, the class type where the method is + being executed on will be returned. + + Returns + ======= + + Matrix + A Jordan block matrix. + + Raises + ====== + + ValueError + If insufficient arguments are given for matrix size + specification, or no eigenvalue is given. + + Examples + ======== + + Creating a default Jordan block: + + >>> from sympy import Matrix + >>> from sympy.abc import x + >>> Matrix.jordan_block(4, x) + Matrix([ + [x, 1, 0, 0], + [0, x, 1, 0], + [0, 0, x, 1], + [0, 0, 0, x]]) + + Creating an alternative Jordan block matrix where `1` is on + lower off-diagonal: + + >>> Matrix.jordan_block(4, x, band='lower') + Matrix([ + [x, 0, 0, 0], + [1, x, 0, 0], + [0, 1, x, 0], + [0, 0, 1, x]]) + + Creating a Jordan block with keyword arguments + + >>> Matrix.jordan_block(size=4, eigenvalue=x) + Matrix([ + [x, 1, 0, 0], + [0, x, 1, 0], + [0, 0, x, 1], + [0, 0, 0, x]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Jordan_matrix + """ + klass = kwargs.pop('cls', kls) + + eigenval = kwargs.get('eigenval', None) + if eigenvalue is None and eigenval is None: + raise ValueError("Must supply an eigenvalue") + elif eigenvalue != eigenval and None not in (eigenval, eigenvalue): + raise ValueError( + "Inconsistent values are given: 'eigenval'={}, " + "'eigenvalue'={}".format(eigenval, eigenvalue)) + else: + if eigenval is not None: + eigenvalue = eigenval + + if size is None: + raise ValueError("Must supply a matrix size") + + size = as_int(size) + return klass._eval_jordan_block(size, eigenvalue, band) + + @classmethod + def ones(kls, rows, cols=None, **kwargs): + """Returns a matrix of ones. + + Parameters + ========== + + rows : rows of the matrix + cols : cols of the matrix (if None, cols=rows) + + kwargs + ====== + cls : class of the returned matrix + """ + if cols is None: + cols = rows + klass = kwargs.get('cls', kls) + rows, cols = as_int(rows), as_int(cols) + + return klass._eval_ones(rows, cols) + + @classmethod + def zeros(kls, rows, cols=None, **kwargs): + """Returns a matrix of zeros. + + Parameters + ========== + + rows : rows of the matrix + cols : cols of the matrix (if None, cols=rows) + + kwargs + ====== + cls : class of the returned matrix + """ + if cols is None: + cols = rows + if rows < 0 or cols < 0: + raise ValueError("Cannot create a {} x {} matrix. " + "Both dimensions must be positive".format(rows, cols)) + klass = kwargs.get('cls', kls) + rows, cols = as_int(rows), as_int(cols) + + return klass._eval_zeros(rows, cols) + + @classmethod + def companion(kls, poly): + """Returns a companion matrix of a polynomial. + + Examples + ======== + + >>> from sympy import Matrix, Poly, Symbol, symbols + >>> x = Symbol('x') + >>> c0, c1, c2, c3, c4 = symbols('c0:5') + >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) + >>> Matrix.companion(p) + Matrix([ + [0, 0, 0, 0, -c0], + [1, 0, 0, 0, -c1], + [0, 1, 0, 0, -c2], + [0, 0, 1, 0, -c3], + [0, 0, 0, 1, -c4]]) + """ + poly = kls._sympify(poly) + if not isinstance(poly, Poly): + raise ValueError("{} must be a Poly instance.".format(poly)) + if not poly.is_monic: + raise ValueError("{} must be a monic polynomial.".format(poly)) + if not poly.is_univariate: + raise ValueError( + "{} must be a univariate polynomial.".format(poly)) + + size = poly.degree() + if not size >= 1: + raise ValueError( + "{} must have degree not less than 1.".format(poly)) + + coeffs = poly.all_coeffs() + def entry(i, j): + if j == size - 1: + return -coeffs[-1 - i] + elif i == j + 1: + return kls.one + return kls.zero + return kls._new(size, size, entry) + + + @classmethod + def wilkinson(kls, n, **kwargs): + """Returns two square Wilkinson Matrix of size 2*n + 1 + $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n) + + Examples + ======== + + >>> from sympy import Matrix + >>> wminus, wplus = Matrix.wilkinson(3) + >>> wminus + Matrix([ + [-3, 1, 0, 0, 0, 0, 0], + [ 1, -2, 1, 0, 0, 0, 0], + [ 0, 1, -1, 1, 0, 0, 0], + [ 0, 0, 1, 0, 1, 0, 0], + [ 0, 0, 0, 1, 1, 1, 0], + [ 0, 0, 0, 0, 1, 2, 1], + [ 0, 0, 0, 0, 0, 1, 3]]) + >>> wplus + Matrix([ + [3, 1, 0, 0, 0, 0, 0], + [1, 2, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 1, 2, 1], + [0, 0, 0, 0, 0, 1, 3]]) + + References + ========== + + .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/ + .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp. + + """ + klass = kwargs.get('cls', kls) + n = as_int(n) + return klass._eval_wilkinson(n) + + # The RepMatrix subclass uses more efficient sparse implementations of + # _eval_iter_values and other things. + + def _eval_iter_values(self): + return (i for i in self if i is not S.Zero) + + def _eval_values(self): + return list(self.iter_values()) + + def _eval_iter_items(self): + for i in range(self.rows): + for j in range(self.cols): + if self[i, j]: + yield (i, j), self[i, j] + + def _eval_atoms(self, *types): + values = self.values() + if len(values) < self.rows * self.cols and isinstance(S.Zero, types): + s = {S.Zero} + else: + s = set() + return s.union(*[v.atoms(*types) for v in values]) + + def _eval_free_symbols(self): + return set().union(*(i.free_symbols for i in set(self.values()))) + + def _eval_has(self, *patterns): + return any(a.has(*patterns) for a in self.iter_values()) + + def _eval_is_symbolic(self): + return self.has(Symbol) + + # _eval_is_hermitian is called by some general SymPy + # routines and has a different *args signature. Make + # sure the names don't clash by adding `_matrix_` in name. + def _eval_is_matrix_hermitian(self, simpfunc): + herm = lambda i, j: simpfunc(self[i, j] - self[j, i].adjoint()).is_zero + return fuzzy_and(herm(i, j) for (i, j), v in self.iter_items()) + + def _eval_is_zero_matrix(self): + return fuzzy_and(v.is_zero for v in self.iter_values()) + + def _eval_is_Identity(self) -> FuzzyBool: + one = self.one + zero = self.zero + ident = lambda i, j, v: v is one if i == j else v is zero + return all(ident(i, j, v) for (i, j), v in self.iter_items()) + + def _eval_is_diagonal(self): + return fuzzy_and(v.is_zero for (i, j), v in self.iter_items() if i != j) + + def _eval_is_lower(self): + return all(v.is_zero for (i, j), v in self.iter_items() if i < j) + + def _eval_is_upper(self): + return all(v.is_zero for (i, j), v in self.iter_items() if i > j) + + def _eval_is_lower_hessenberg(self): + return all(v.is_zero for (i, j), v in self.iter_items() if i + 1 < j) + + def _eval_is_upper_hessenberg(self): + return all(v.is_zero for (i, j), v in self.iter_items() if i > j + 1) + + def _eval_is_symmetric(self, simpfunc): + sym = lambda i, j: simpfunc(self[i, j] - self[j, i]).is_zero + return fuzzy_and(sym(i, j) for (i, j), v in self.iter_items()) + + def _eval_is_anti_symmetric(self, simpfunc): + anti = lambda i, j: simpfunc(self[i, j] + self[j, i]).is_zero + return fuzzy_and(anti(i, j) for (i, j), v in self.iter_items()) + + def _has_positive_diagonals(self): + diagonal_entries = (self[i, i] for i in range(self.rows)) + return fuzzy_and(x.is_positive for x in diagonal_entries) + + def _has_nonnegative_diagonals(self): + diagonal_entries = (self[i, i] for i in range(self.rows)) + return fuzzy_and(x.is_nonnegative for x in diagonal_entries) + + def atoms(self, *types): + """Returns the atoms that form the current object. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import Matrix + >>> Matrix([[x]]) + Matrix([[x]]) + >>> _.atoms() + {x} + >>> Matrix([[x, y], [y, x]]) + Matrix([ + [x, y], + [y, x]]) + >>> _.atoms() + {x, y} + """ + + types = tuple(t if isinstance(t, type) else type(t) for t in types) + if not types: + types = (Atom,) + return self._eval_atoms(*types) + + @property + def free_symbols(self): + """Returns the free symbols within the matrix. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import Matrix + >>> Matrix([[x], [1]]).free_symbols + {x} + """ + return self._eval_free_symbols() + + def has(self, *patterns): + """Test whether any subexpression matches any of the patterns. + + Examples + ======== + + >>> from sympy import Matrix, SparseMatrix, Float + >>> from sympy.abc import x, y + >>> A = Matrix(((1, x), (0.2, 3))) + >>> B = SparseMatrix(((1, x), (0.2, 3))) + >>> A.has(x) + True + >>> A.has(y) + False + >>> A.has(Float) + True + >>> B.has(x) + True + >>> B.has(y) + False + >>> B.has(Float) + True + """ + return self._eval_has(*patterns) + + def is_anti_symmetric(self, simplify=True): + """Check if matrix M is an antisymmetric matrix, + that is, M is a square matrix with all M[i, j] == -M[j, i]. + + When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is + simplified before testing to see if it is zero. By default, + the SymPy simplify function is used. To use a custom function + set simplify to a function that accepts a single argument which + returns a simplified expression. To skip simplification, set + simplify to False but note that although this will be faster, + it may induce false negatives. + + Examples + ======== + + >>> from sympy import Matrix, symbols + >>> m = Matrix(2, 2, [0, 1, -1, 0]) + >>> m + Matrix([ + [ 0, 1], + [-1, 0]]) + >>> m.is_anti_symmetric() + True + >>> x, y = symbols('x y') + >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0]) + >>> m + Matrix([ + [ 0, 0, x], + [-y, 0, 0]]) + >>> m.is_anti_symmetric() + False + + >>> from sympy.abc import x, y + >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, + ... -(x + 1)**2, 0, x*y, + ... -y, -x*y, 0]) + + Simplification of matrix elements is done by default so even + though two elements which should be equal and opposite would not + pass an equality test, the matrix is still reported as + anti-symmetric: + + >>> m[0, 1] == -m[1, 0] + False + >>> m.is_anti_symmetric() + True + + If ``simplify=False`` is used for the case when a Matrix is already + simplified, this will speed things up. Here, we see that without + simplification the matrix does not appear anti-symmetric: + + >>> print(m.is_anti_symmetric(simplify=False)) + None + + But if the matrix were already expanded, then it would appear + anti-symmetric and simplification in the is_anti_symmetric routine + is not needed: + + >>> m = m.expand() + >>> m.is_anti_symmetric(simplify=False) + True + """ + # accept custom simplification + simpfunc = simplify + if not isfunction(simplify): + simpfunc = _utilities_simplify if simplify else lambda x: x + + if not self.is_square: + return False + return self._eval_is_anti_symmetric(simpfunc) + + def is_diagonal(self): + """Check if matrix is diagonal, + that is matrix in which the entries outside the main diagonal are all zero. + + Examples + ======== + + >>> from sympy import Matrix, diag + >>> m = Matrix(2, 2, [1, 0, 0, 2]) + >>> m + Matrix([ + [1, 0], + [0, 2]]) + >>> m.is_diagonal() + True + + >>> m = Matrix(2, 2, [1, 1, 0, 2]) + >>> m + Matrix([ + [1, 1], + [0, 2]]) + >>> m.is_diagonal() + False + + >>> m = diag(1, 2, 3) + >>> m + Matrix([ + [1, 0, 0], + [0, 2, 0], + [0, 0, 3]]) + >>> m.is_diagonal() + True + + See Also + ======== + + is_lower + is_upper + sympy.matrices.matrixbase.MatrixBase.is_diagonalizable + diagonalize + """ + return self._eval_is_diagonal() + + @property + def is_weakly_diagonally_dominant(self): + r"""Tests if the matrix is row weakly diagonally dominant. + + Explanation + =========== + + A $n, n$ matrix $A$ is row weakly diagonally dominant if + + .. math:: + \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1} + \left|A_{i, j}\right| \quad {\text{for all }} + i \in \{ 0, ..., n-1 \} + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) + >>> A.is_weakly_diagonally_dominant + True + + >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) + >>> A.is_weakly_diagonally_dominant + False + + >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) + >>> A.is_weakly_diagonally_dominant + True + + Notes + ===== + + If you want to test whether a matrix is column diagonally + dominant, you can apply the test after transposing the matrix. + """ + if not self.is_square: + return False + + rows, cols = self.shape + + def test_row(i): + summation = self.zero + for j in range(cols): + if i != j: + summation += Abs(self[i, j]) + return (Abs(self[i, i]) - summation).is_nonnegative + + return fuzzy_and(test_row(i) for i in range(rows)) + + @property + def is_strongly_diagonally_dominant(self): + r"""Tests if the matrix is row strongly diagonally dominant. + + Explanation + =========== + + A $n, n$ matrix $A$ is row strongly diagonally dominant if + + .. math:: + \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1} + \left|A_{i, j}\right| \quad {\text{for all }} + i \in \{ 0, ..., n-1 \} + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) + >>> A.is_strongly_diagonally_dominant + False + + >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) + >>> A.is_strongly_diagonally_dominant + False + + >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) + >>> A.is_strongly_diagonally_dominant + True + + Notes + ===== + + If you want to test whether a matrix is column diagonally + dominant, you can apply the test after transposing the matrix. + """ + if not self.is_square: + return False + + rows, cols = self.shape + + def test_row(i): + summation = self.zero + for j in range(cols): + if i != j: + summation += Abs(self[i, j]) + return (Abs(self[i, i]) - summation).is_positive + + return fuzzy_and(test_row(i) for i in range(rows)) + + @property + def is_hermitian(self): + """Checks if the matrix is Hermitian. + + In a Hermitian matrix element i,j is the complex conjugate of + element j,i. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy import I + >>> from sympy.abc import x + >>> a = Matrix([[1, I], [-I, 1]]) + >>> a + Matrix([ + [ 1, I], + [-I, 1]]) + >>> a.is_hermitian + True + >>> a[0, 0] = 2*I + >>> a.is_hermitian + False + >>> a[0, 0] = x + >>> a.is_hermitian + >>> a[0, 1] = a[1, 0]*I + >>> a.is_hermitian + False + """ + if not self.is_square: + return False + + return self._eval_is_matrix_hermitian(_utilities_simplify) + + @property + def is_Identity(self) -> FuzzyBool: + if not self.is_square: + return False + return self._eval_is_Identity() + + @property + def is_lower_hessenberg(self): + r"""Checks if the matrix is in the lower-Hessenberg form. + + The lower hessenberg matrix has zero entries + above the first superdiagonal. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) + >>> a + Matrix([ + [1, 2, 0, 0], + [5, 2, 3, 0], + [3, 4, 3, 7], + [5, 6, 1, 1]]) + >>> a.is_lower_hessenberg + True + + See Also + ======== + + is_upper_hessenberg + is_lower + """ + return self._eval_is_lower_hessenberg() + + @property + def is_lower(self): + """Check if matrix is a lower triangular matrix. True can be returned + even if the matrix is not square. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, [1, 0, 0, 1]) + >>> m + Matrix([ + [1, 0], + [0, 1]]) + >>> m.is_lower + True + + >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5]) + >>> m + Matrix([ + [0, 0, 0], + [2, 0, 0], + [1, 4, 0], + [6, 6, 5]]) + >>> m.is_lower + True + + >>> from sympy.abc import x, y + >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y]) + >>> m + Matrix([ + [x**2 + y, x + y**2], + [ 0, x + y]]) + >>> m.is_lower + False + + See Also + ======== + + is_upper + is_diagonal + is_lower_hessenberg + """ + return self._eval_is_lower() + + @property + def is_square(self): + """Checks if a matrix is square. + + A matrix is square if the number of rows equals the number of columns. + The empty matrix is square by definition, since the number of rows and + the number of columns are both zero. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[1, 2, 3], [4, 5, 6]]) + >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> c = Matrix([]) + >>> a.is_square + False + >>> b.is_square + True + >>> c.is_square + True + """ + return self.rows == self.cols + + def is_symbolic(self): + """Checks if any elements contain Symbols. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.is_symbolic() + True + + """ + return self._eval_is_symbolic() + + def is_symmetric(self, simplify=True): + """Check if matrix is symmetric matrix, + that is square matrix and is equal to its transpose. + + By default, simplifications occur before testing symmetry. + They can be skipped using 'simplify=False'; while speeding things a bit, + this may however induce false negatives. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, [0, 1, 1, 2]) + >>> m + Matrix([ + [0, 1], + [1, 2]]) + >>> m.is_symmetric() + True + + >>> m = Matrix(2, 2, [0, 1, 2, 0]) + >>> m + Matrix([ + [0, 1], + [2, 0]]) + >>> m.is_symmetric() + False + + >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0]) + >>> m + Matrix([ + [0, 0, 0], + [0, 0, 0]]) + >>> m.is_symmetric() + False + + >>> from sympy.abc import x, y + >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) + >>> m + Matrix([ + [ 1, x**2 + 2*x + 1, y], + [(x + 1)**2, 2, 0], + [ y, 0, 3]]) + >>> m.is_symmetric() + True + + If the matrix is already simplified, you may speed-up is_symmetric() + test by using 'simplify=False'. + + >>> bool(m.is_symmetric(simplify=False)) + False + >>> m1 = m.expand() + >>> m1.is_symmetric(simplify=False) + True + """ + simpfunc = simplify + if not isfunction(simplify): + simpfunc = _utilities_simplify if simplify else lambda x: x + + if not self.is_square: + return False + + return self._eval_is_symmetric(simpfunc) + + @property + def is_upper_hessenberg(self): + """Checks if the matrix is the upper-Hessenberg form. + + The upper hessenberg matrix has zero entries + below the first subdiagonal. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) + >>> a + Matrix([ + [1, 4, 2, 3], + [3, 4, 1, 7], + [0, 2, 3, 4], + [0, 0, 1, 3]]) + >>> a.is_upper_hessenberg + True + + See Also + ======== + + is_lower_hessenberg + is_upper + """ + return self._eval_is_upper_hessenberg() + + @property + def is_upper(self): + """Check if matrix is an upper triangular matrix. True can be returned + even if the matrix is not square. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, [1, 0, 0, 1]) + >>> m + Matrix([ + [1, 0], + [0, 1]]) + >>> m.is_upper + True + + >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) + >>> m + Matrix([ + [5, 1, 9], + [0, 4, 6], + [0, 0, 5], + [0, 0, 0]]) + >>> m.is_upper + True + + >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) + >>> m + Matrix([ + [4, 2, 5], + [6, 1, 1]]) + >>> m.is_upper + False + + See Also + ======== + + is_lower + is_diagonal + is_upper_hessenberg + """ + return self._eval_is_upper() + + @property + def is_zero_matrix(self): + """Checks if a matrix is a zero matrix. + + A matrix is zero if every element is zero. A matrix need not be square + to be considered zero. The empty matrix is zero by the principle of + vacuous truth. For a matrix that may or may not be zero (e.g. + contains a symbol), this will be None + + Examples + ======== + + >>> from sympy import Matrix, zeros + >>> from sympy.abc import x + >>> a = Matrix([[0, 0], [0, 0]]) + >>> b = zeros(3, 4) + >>> c = Matrix([[0, 1], [0, 0]]) + >>> d = Matrix([]) + >>> e = Matrix([[x, 0], [0, 0]]) + >>> a.is_zero_matrix + True + >>> b.is_zero_matrix + True + >>> c.is_zero_matrix + False + >>> d.is_zero_matrix + True + >>> e.is_zero_matrix + """ + return self._eval_is_zero_matrix() + + def values(self): + """Return non-zero values of self. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix([[0, 1], [2, 3]]) + >>> m.values() + [1, 2, 3] + + See Also + ======== + + iter_values + tolist + flat + """ + return self._eval_values() + + def iter_values(self): + """ + Iterate over non-zero values of self. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix([[0, 1], [2, 3]]) + >>> list(m.iter_values()) + [1, 2, 3] + + See Also + ======== + + values + """ + return self._eval_iter_values() + + def iter_items(self): + """Iterate over indices and values of nonzero items. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix([[0, 1], [2, 3]]) + >>> list(m.iter_items()) + [((0, 1), 1), ((1, 0), 2), ((1, 1), 3)] + + See Also + ======== + + iter_values + todok + """ + return self._eval_iter_items() + + def _eval_adjoint(self): + return self.transpose().applyfunc(lambda x: x.adjoint()) + + def _eval_applyfunc(self, f): + cols = self.cols + size = self.rows*self.cols + + dok = self.todok() + valmap = {v: f(v) for v in dok.values()} + + if len(dok) < size and ((fzero := f(S.Zero)) is not S.Zero): + out_flat = [fzero]*size + for (i, j), v in dok.items(): + out_flat[i*cols + j] = valmap[v] + out = self._new(self.rows, self.cols, out_flat) + else: + fdok = {ij: valmap[v] for ij, v in dok.items()} + out = self.from_dok(self.rows, self.cols, fdok) + + return out + + def _eval_as_real_imag(self): # type: ignore + return (self.applyfunc(re), self.applyfunc(im)) + + def _eval_conjugate(self): + return self.applyfunc(lambda x: x.conjugate()) + + def _eval_permute_cols(self, perm): + # apply the permutation to a list + mapping = list(perm) + + def entry(i, j): + return self[i, mapping[j]] + + return self._new(self.rows, self.cols, entry) + + def _eval_permute_rows(self, perm): + # apply the permutation to a list + mapping = list(perm) + + def entry(i, j): + return self[mapping[i], j] + + return self._new(self.rows, self.cols, entry) + + def _eval_trace(self): + return sum(self[i, i] for i in range(self.rows)) + + def _eval_transpose(self): + return self._new(self.cols, self.rows, lambda i, j: self[j, i]) + + def adjoint(self): + """Conjugate transpose or Hermitian conjugation.""" + return self._eval_adjoint() + + def applyfunc(self, f): + """Apply a function to each element of the matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix(2, 2, lambda i, j: i*2+j) + >>> m + Matrix([ + [0, 1], + [2, 3]]) + >>> m.applyfunc(lambda i: 2*i) + Matrix([ + [0, 2], + [4, 6]]) + + """ + if not callable(f): + raise TypeError("`f` must be callable.") + + return self._eval_applyfunc(f) + + def as_real_imag(self, deep=True, **hints): + """Returns a tuple containing the (real, imaginary) part of matrix.""" + # XXX: Ignoring deep and hints... + return self._eval_as_real_imag() + + def conjugate(self): + """Return the by-element conjugation. + + Examples + ======== + + >>> from sympy import SparseMatrix, I + >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I))) + >>> a + Matrix([ + [1, 2 + I], + [3, 4], + [I, -I]]) + >>> a.C + Matrix([ + [ 1, 2 - I], + [ 3, 4], + [-I, I]]) + + See Also + ======== + + transpose: Matrix transposition + H: Hermite conjugation + sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation + """ + return self._eval_conjugate() + + def doit(self, **hints): + return self.applyfunc(lambda x: x.doit(**hints)) + + def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): + """Apply evalf() to each element of self.""" + options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, + 'quad':quad, 'verbose':verbose} + return self.applyfunc(lambda i: i.evalf(n, **options)) + + def expand(self, deep=True, modulus=None, power_base=True, power_exp=True, + mul=True, log=True, multinomial=True, basic=True, **hints): + """Apply core.function.expand to each entry of the matrix. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import Matrix + >>> Matrix(1, 1, [x*(x+1)]) + Matrix([[x*(x + 1)]]) + >>> _.expand() + Matrix([[x**2 + x]]) + + """ + return self.applyfunc(lambda x: x.expand( + deep, modulus, power_base, power_exp, mul, log, multinomial, basic, + **hints)) + + @property + def H(self): + """Return Hermite conjugate. + + Examples + ======== + + >>> from sympy import Matrix, I + >>> m = Matrix((0, 1 + I, 2, 3)) + >>> m + Matrix([ + [ 0], + [1 + I], + [ 2], + [ 3]]) + >>> m.H + Matrix([[0, 1 - I, 2, 3]]) + + See Also + ======== + + conjugate: By-element conjugation + sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation + """ + return self.adjoint() + + def permute(self, perm, orientation='rows', direction='forward'): + r"""Permute the rows or columns of a matrix by the given list of + swaps. + + Parameters + ========== + + perm : Permutation, list, or list of lists + A representation for the permutation. + + If it is ``Permutation``, it is used directly with some + resizing with respect to the matrix size. + + If it is specified as list of lists, + (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed + from applying the product of cycles. The direction how the + cyclic product is applied is described in below. + + If it is specified as a list, the list should represent + an array form of a permutation. (e.g., ``[1, 2, 0]``) which + would would form the swapping function + `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`. + + orientation : 'rows', 'cols' + A flag to control whether to permute the rows or the columns + + direction : 'forward', 'backward' + A flag to control whether to apply the permutations from + the start of the list first, or from the back of the list + first. + + For example, if the permutation specification is + ``[[0, 1], [0, 2]]``, + + If the flag is set to ``'forward'``, the cycle would be + formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`. + + If the flag is set to ``'backward'``, the cycle would be + formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`. + + If the argument ``perm`` is not in a form of list of lists, + this flag takes no effect. + + Examples + ======== + + >>> from sympy import eye + >>> M = eye(3) + >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward') + Matrix([ + [0, 0, 1], + [1, 0, 0], + [0, 1, 0]]) + + >>> from sympy import eye + >>> M = eye(3) + >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward') + Matrix([ + [0, 1, 0], + [0, 0, 1], + [1, 0, 0]]) + + Notes + ===== + + If a bijective function + `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the + permutation. + + If the matrix `A` is the matrix to permute, represented as + a horizontal or a vertical stack of vectors: + + .. math:: + A = + \begin{bmatrix} + a_0 \\ a_1 \\ \vdots \\ a_{n-1} + \end{bmatrix} = + \begin{bmatrix} + \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1} + \end{bmatrix} + + If the matrix `B` is the result, the permutation of matrix rows + is defined as: + + .. math:: + B := \begin{bmatrix} + a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)} + \end{bmatrix} + + And the permutation of matrix columns is defined as: + + .. math:: + B := \begin{bmatrix} + \alpha_{\sigma(0)} & \alpha_{\sigma(1)} & + \cdots & \alpha_{\sigma(n-1)} + \end{bmatrix} + """ + from sympy.combinatorics import Permutation + + # allow british variants and `columns` + if direction == 'forwards': + direction = 'forward' + if direction == 'backwards': + direction = 'backward' + if orientation == 'columns': + orientation = 'cols' + + if direction not in ('forward', 'backward'): + raise TypeError("direction='{}' is an invalid kwarg. " + "Try 'forward' or 'backward'".format(direction)) + if orientation not in ('rows', 'cols'): + raise TypeError("orientation='{}' is an invalid kwarg. " + "Try 'rows' or 'cols'".format(orientation)) + + if not isinstance(perm, (Permutation, Iterable)): + raise ValueError( + "{} must be a list, a list of lists, " + "or a SymPy permutation object.".format(perm)) + + # ensure all swaps are in range + max_index = self.rows if orientation == 'rows' else self.cols + if not all(0 <= t <= max_index for t in flatten(list(perm))): + raise IndexError("`swap` indices out of range.") + + if perm and not isinstance(perm, Permutation) and \ + isinstance(perm[0], Iterable): + if direction == 'forward': + perm = list(reversed(perm)) + perm = Permutation(perm, size=max_index+1) + else: + perm = Permutation(perm, size=max_index+1) + + if orientation == 'rows': + return self._eval_permute_rows(perm) + if orientation == 'cols': + return self._eval_permute_cols(perm) + + def permute_cols(self, swaps, direction='forward'): + """Alias for + ``self.permute(swaps, orientation='cols', direction=direction)`` + + See Also + ======== + + permute + """ + return self.permute(swaps, orientation='cols', direction=direction) + + def permute_rows(self, swaps, direction='forward'): + """Alias for + ``self.permute(swaps, orientation='rows', direction=direction)`` + + See Also + ======== + + permute + """ + return self.permute(swaps, orientation='rows', direction=direction) + + def refine(self, assumptions=True): + """Apply refine to each element of the matrix. + + Examples + ======== + + >>> from sympy import Symbol, Matrix, Abs, sqrt, Q + >>> x = Symbol('x') + >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]]) + Matrix([ + [ Abs(x)**2, sqrt(x**2)], + [sqrt(x**2), Abs(x)**2]]) + >>> _.refine(Q.real(x)) + Matrix([ + [ x**2, Abs(x)], + [Abs(x), x**2]]) + + """ + return self.applyfunc(lambda x: refine(x, assumptions)) + + def replace(self, F, G, map=False, simultaneous=True, exact=None): + """Replaces Function F in Matrix entries with Function G. + + Examples + ======== + + >>> from sympy import symbols, Function, Matrix + >>> F, G = symbols('F, G', cls=Function) + >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M + Matrix([ + [F(0), F(1)], + [F(1), F(2)]]) + >>> N = M.replace(F,G) + >>> N + Matrix([ + [G(0), G(1)], + [G(1), G(2)]]) + """ + kwargs = {'map': map, 'simultaneous': simultaneous, 'exact': exact} + + if map: + + d = {} + def func(eij): + eij, dij = eij.replace(F, G, **kwargs) + d.update(dij) + return eij + + M = self.applyfunc(func) + return M, d + + else: + return self.applyfunc(lambda i: i.replace(F, G, **kwargs)) + + def rot90(self, k=1): + """Rotates Matrix by 90 degrees + + Parameters + ========== + + k : int + Specifies how many times the matrix is rotated by 90 degrees + (clockwise when positive, counter-clockwise when negative). + + Examples + ======== + + >>> from sympy import Matrix, symbols + >>> A = Matrix(2, 2, symbols('a:d')) + >>> A + Matrix([ + [a, b], + [c, d]]) + + Rotating the matrix clockwise one time: + + >>> A.rot90(1) + Matrix([ + [c, a], + [d, b]]) + + Rotating the matrix anticlockwise two times: + + >>> A.rot90(-2) + Matrix([ + [d, c], + [b, a]]) + """ + + mod = k%4 + if mod == 0: + return self + if mod == 1: + return self[::-1, ::].T + if mod == 2: + return self[::-1, ::-1] + if mod == 3: + return self[::, ::-1].T + + def simplify(self, **kwargs): + """Apply simplify to each element of the matrix. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import SparseMatrix, sin, cos + >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2]) + Matrix([[x*sin(y)**2 + x*cos(y)**2]]) + >>> _.simplify() + Matrix([[x]]) + """ + return self.applyfunc(lambda x: x.simplify(**kwargs)) + + def subs(self, *args, **kwargs): # should mirror core.basic.subs + """Return a new matrix with subs applied to each entry. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import SparseMatrix, Matrix + >>> SparseMatrix(1, 1, [x]) + Matrix([[x]]) + >>> _.subs(x, y) + Matrix([[y]]) + >>> Matrix(_).subs(y, x) + Matrix([[x]]) + """ + + if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]): + args = (list(args[0]),) + + return self.applyfunc(lambda x: x.subs(*args, **kwargs)) + + def trace(self): + """ + Returns the trace of a square matrix i.e. the sum of the + diagonal elements. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix(2, 2, [1, 2, 3, 4]) + >>> A.trace() + 5 + + """ + if self.rows != self.cols: + raise NonSquareMatrixError() + return self._eval_trace() + + def transpose(self): + """ + Returns the transpose of the matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix(2, 2, [1, 2, 3, 4]) + >>> A.transpose() + Matrix([ + [1, 3], + [2, 4]]) + + >>> from sympy import Matrix, I + >>> m=Matrix(((1, 2+I), (3, 4))) + >>> m + Matrix([ + [1, 2 + I], + [3, 4]]) + >>> m.transpose() + Matrix([ + [ 1, 3], + [2 + I, 4]]) + >>> m.T == m.transpose() + True + + See Also + ======== + + conjugate: By-element conjugation + + """ + return self._eval_transpose() + + @property + def T(self): + '''Matrix transposition''' + return self.transpose() + + @property + def C(self): + '''By-element conjugation''' + return self.conjugate() + + def n(self, *args, **kwargs): + """Apply evalf() to each element of self.""" + return self.evalf(*args, **kwargs) + + def xreplace(self, rule): # should mirror core.basic.xreplace + """Return a new matrix with xreplace applied to each entry. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import SparseMatrix, Matrix + >>> SparseMatrix(1, 1, [x]) + Matrix([[x]]) + >>> _.xreplace({x: y}) + Matrix([[y]]) + >>> Matrix(_).xreplace({y: x}) + Matrix([[x]]) + """ + return self.applyfunc(lambda x: x.xreplace(rule)) + + def _eval_simplify(self, **kwargs): + # XXX: We can't use self.simplify here as mutable subclasses will + # override simplify and have it return None + return self.applyfunc(lambda x: x.simplify(**kwargs)) + + def _eval_trigsimp(self, **opts): + from sympy.simplify.trigsimp import trigsimp + return self.applyfunc(lambda x: trigsimp(x, **opts)) + + def upper_triangular(self, k=0): + """Return the elements on and above the kth diagonal of a matrix. + If k is not specified then simply returns upper-triangular portion + of a matrix + + Examples + ======== + + >>> from sympy import ones + >>> A = ones(4) + >>> A.upper_triangular() + Matrix([ + [1, 1, 1, 1], + [0, 1, 1, 1], + [0, 0, 1, 1], + [0, 0, 0, 1]]) + + >>> A.upper_triangular(2) + Matrix([ + [0, 0, 1, 1], + [0, 0, 0, 1], + [0, 0, 0, 0], + [0, 0, 0, 0]]) + + >>> A.upper_triangular(-1) + Matrix([ + [1, 1, 1, 1], + [1, 1, 1, 1], + [0, 1, 1, 1], + [0, 0, 1, 1]]) + + """ + + def entry(i, j): + return self[i, j] if i + k <= j else self.zero + + return self._new(self.rows, self.cols, entry) + + def lower_triangular(self, k=0): + """Return the elements on and below the kth diagonal of a matrix. + If k is not specified then simply returns lower-triangular portion + of a matrix + + Examples + ======== + + >>> from sympy import ones + >>> A = ones(4) + >>> A.lower_triangular() + Matrix([ + [1, 0, 0, 0], + [1, 1, 0, 0], + [1, 1, 1, 0], + [1, 1, 1, 1]]) + + >>> A.lower_triangular(-2) + Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 0, 0, 0], + [1, 1, 0, 0]]) + + >>> A.lower_triangular(1) + Matrix([ + [1, 1, 0, 0], + [1, 1, 1, 0], + [1, 1, 1, 1], + [1, 1, 1, 1]]) + + """ + + def entry(i, j): + return self[i, j] if i + k >= j else self.zero + + return self._new(self.rows, self.cols, entry) + + def _eval_Abs(self): + return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j])) + + def _eval_add(self, other): + return self._new(self.rows, self.cols, + lambda i, j: self[i, j] + other[i, j]) + + def _eval_matrix_mul(self, other): + def entry(i, j): + vec = [self[i,k]*other[k,j] for k in range(self.cols)] + try: + return Add(*vec) + except (TypeError, SympifyError): + # Some matrices don't work with `sum` or `Add` + # They don't work with `sum` because `sum` tries to add `0` + # Fall back to a safe way to multiply if the `Add` fails. + return reduce(lambda a, b: a + b, vec) + + return self._new(self.rows, other.cols, entry) + + def _eval_matrix_mul_elementwise(self, other): + return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j]) + + def _eval_matrix_rmul(self, other): + def entry(i, j): + return sum(other[i,k]*self[k,j] for k in range(other.cols)) + return self._new(other.rows, self.cols, entry) + + def _eval_pow_by_recursion(self, num): + if num == 1: + return self + + if num % 2 == 1: + a, b = self, self._eval_pow_by_recursion(num - 1) + else: + a = b = self._eval_pow_by_recursion(num // 2) + + return a.multiply(b) + + def _eval_pow_by_cayley(self, exp): + from sympy.discrete.recurrences import linrec_coeffs + row = self.shape[0] + p = self.charpoly() + + coeffs = (-p).all_coeffs()[1:] + coeffs = linrec_coeffs(coeffs, exp) + new_mat = self.eye(row) + ans = self.zeros(row) + + for i in range(row): + ans += coeffs[i]*new_mat + new_mat *= self + + return ans + + def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None): + if prevsimp is None: + prevsimp = [True]*len(self) + + if num == 1: + return self + + if num % 2 == 1: + a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1, + prevsimp=prevsimp) + else: + a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2, + prevsimp=prevsimp) + + m = a.multiply(b, dotprodsimp=False) + lenm = len(m) + elems = [None]*lenm + + for i in range(lenm): + if prevsimp[i]: + elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True) + else: + elems[i] = m[i] + + return m._new(m.rows, m.cols, elems) + + def _eval_scalar_mul(self, other): + return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other) + + def _eval_scalar_rmul(self, other): + return self._new(self.rows, self.cols, lambda i, j: other*self[i,j]) + + def _eval_Mod(self, other): + return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other)) + + # Python arithmetic functions + def __abs__(self): + """Returns a new matrix with entry-wise absolute values.""" + return self._eval_Abs() + + @call_highest_priority('__radd__') + def __add__(self, other): + """Return self + other, raising ShapeError if shapes do not match.""" + + other, T = _coerce_operand(self, other) + + if T != "is_matrix": + return NotImplemented + + if self.shape != other.shape: + raise ShapeError(f"Matrix size mismatch: {self.shape} + {other.shape}.") + + # Unify matrix types + a, b = self, other + if a.__class__ != classof(a, b): + b, a = a, b + + return a._eval_add(b) + + @call_highest_priority('__rtruediv__') + def __truediv__(self, other): + return self * (self.one / other) + + @call_highest_priority('__rmatmul__') + def __matmul__(self, other): + self, other, T = _unify_with_other(self, other) + + if T != "is_matrix": + return NotImplemented + + return self.__mul__(other) + + def __mod__(self, other): + return self.applyfunc(lambda x: x % other) + + @call_highest_priority('__rmul__') + def __mul__(self, other): + """Return self*other where other is either a scalar or a matrix + of compatible dimensions. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) + >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]]) + True + >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> A*B + Matrix([ + [30, 36, 42], + [66, 81, 96]]) + >>> B*A + Traceback (most recent call last): + ... + ShapeError: Matrices size mismatch. + >>> + + See Also + ======== + + matrix_multiply_elementwise + """ + + return self.multiply(other) + + def multiply(self, other, dotprodsimp=None): + """Same as __mul__() but with optional simplification. + + Parameters + ========== + + dotprodsimp : bool, optional + Specifies whether intermediate term algebraic simplification is used + during matrix multiplications to control expression blowup and thus + speed up calculation. Default is off. + """ + + isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) + + self, other, T = _unify_with_other(self, other) + + if T == "possible_scalar": + try: + return self._eval_scalar_mul(other) + except TypeError: + return NotImplemented + + elif T == "is_matrix": + + if self.shape[1] != other.shape[0]: + raise ShapeError(f"Matrix size mismatch: {self.shape} * {other.shape}.") + + m = self._eval_matrix_mul(other) + + if isimpbool: + m = m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) + + return m + + else: + return NotImplemented + + def multiply_elementwise(self, other): + """Return the Hadamard product (elementwise product) of A and B + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) + >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) + >>> A.multiply_elementwise(B) + Matrix([ + [ 0, 10, 200], + [300, 40, 5]]) + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.cross + sympy.matrices.matrixbase.MatrixBase.dot + multiply + """ + if self.shape != other.shape: + raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape)) + + return self._eval_matrix_mul_elementwise(other) + + def __neg__(self): + return self._eval_scalar_mul(-1) + + @call_highest_priority('__rpow__') + def __pow__(self, exp): + """Return self**exp a scalar or symbol.""" + + return self.pow(exp) + + + def pow(self, exp, method=None): + r"""Return self**exp a scalar or symbol. + + Parameters + ========== + + method : multiply, mulsimp, jordan, cayley + If multiply then it returns exponentiation using recursion. + If jordan then Jordan form exponentiation will be used. + If cayley then the exponentiation is done using Cayley-Hamilton + theorem. + If mulsimp then the exponentiation is done using recursion + with dotprodsimp. This specifies whether intermediate term + algebraic simplification is used during naive matrix power to + control expression blowup and thus speed up calculation. + If None, then it heuristically decides which method to use. + + """ + + if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']: + raise TypeError('No such method') + if self.rows != self.cols: + raise NonSquareMatrixError() + a = self + jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None) + exp = sympify(exp) + + if exp.is_zero: + return a._new(a.rows, a.cols, lambda i, j: int(i == j)) + if exp == 1: + return a + + diagonal = getattr(a, 'is_diagonal', None) + if diagonal is not None and diagonal(): + return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0) + + if exp.is_Number and exp % 1 == 0: + if a.rows == 1: + return a._new([[a[0]**exp]]) + if exp < 0: + exp = -exp + a = a.inv() + # When certain conditions are met, + # Jordan block algorithm is faster than + # computation by recursion. + if method == 'jordan': + try: + return jordan_pow(exp) + except MatrixError: + if method == 'jordan': + raise + + elif method == 'cayley': + if not exp.is_Number or exp % 1 != 0: + raise ValueError("cayley method is only valid for integer powers") + return a._eval_pow_by_cayley(exp) + + elif method == "mulsimp": + if not exp.is_Number or exp % 1 != 0: + raise ValueError("mulsimp method is only valid for integer powers") + return a._eval_pow_by_recursion_dotprodsimp(exp) + + elif method == "multiply": + if not exp.is_Number or exp % 1 != 0: + raise ValueError("multiply method is only valid for integer powers") + return a._eval_pow_by_recursion(exp) + + elif method is None and exp.is_Number and exp % 1 == 0: + if exp.is_Float: + exp = Integer(exp) + # Decide heuristically which method to apply + if a.rows == 2 and exp > 100000: + return jordan_pow(exp) + elif _get_intermediate_simp_bool(True, None): + return a._eval_pow_by_recursion_dotprodsimp(exp) + elif exp > 10000: + return a._eval_pow_by_cayley(exp) + else: + return a._eval_pow_by_recursion(exp) + + if jordan_pow: + try: + return jordan_pow(exp) + except NonInvertibleMatrixError: + # Raised by jordan_pow on zero determinant matrix unless exp is + # definitely known to be a non-negative integer. + # Here we raise if n is definitely not a non-negative integer + # but otherwise we can leave this as an unevaluated MatPow. + if exp.is_integer is False or exp.is_nonnegative is False: + raise + + from sympy.matrices.expressions import MatPow + return MatPow(a, exp) + + @call_highest_priority('__add__') + def __radd__(self, other): + return self.__add__(other) + + @call_highest_priority('__matmul__') + def __rmatmul__(self, other): + self, other, T = _unify_with_other(self, other) + + if T != "is_matrix": + return NotImplemented + + return self.__rmul__(other) + + @call_highest_priority('__mul__') + def __rmul__(self, other): + return self.rmultiply(other) + + def rmultiply(self, other, dotprodsimp=None): + """Same as __rmul__() but with optional simplification. + + Parameters + ========== + + dotprodsimp : bool, optional + Specifies whether intermediate term algebraic simplification is used + during matrix multiplications to control expression blowup and thus + speed up calculation. Default is off. + """ + isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) + self, other, T = _unify_with_other(self, other) + + if T == "possible_scalar": + try: + return self._eval_scalar_rmul(other) + except TypeError: + return NotImplemented + + elif T == "is_matrix": + if self.shape[0] != other.shape[1]: + raise ShapeError("Matrix size mismatch.") + + m = self._eval_matrix_rmul(other) + + if isimpbool: + return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) + + return m + + else: + return NotImplemented + + @call_highest_priority('__sub__') + def __rsub__(self, a): + return (-self) + a + + @call_highest_priority('__rsub__') + def __sub__(self, a): + return self + (-a) + + def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul): + return _det_bareiss(self, iszerofunc=iszerofunc) + + def _eval_det_berkowitz(self): + return _det_berkowitz(self) + + def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None): + return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc) + + def _eval_det_bird(self): + return _det_bird(self) + + def _eval_det_laplace(self): + return _det_laplace(self) + + def _eval_determinant(self): # for expressions.determinant.Determinant + return _det(self) + + def adjugate(self, method="berkowitz"): + return _adjugate(self, method=method) + + def charpoly(self, x='lambda', simplify=_utilities_simplify): + return _charpoly(self, x=x, simplify=simplify) + + def cofactor(self, i, j, method="berkowitz"): + return _cofactor(self, i, j, method=method) + + def cofactor_matrix(self, method="berkowitz"): + return _cofactor_matrix(self, method=method) + + def det(self, method="bareiss", iszerofunc=None): + return _det(self, method=method, iszerofunc=iszerofunc) + + def per(self): + return _per(self) + + def minor(self, i, j, method="berkowitz"): + return _minor(self, i, j, method=method) + + def minor_submatrix(self, i, j): + return _minor_submatrix(self, i, j) + + _find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__ + _find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__ + _eval_det_bareiss.__doc__ = _det_bareiss.__doc__ + _eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__ + _eval_det_bird.__doc__ = _det_bird.__doc__ + _eval_det_laplace.__doc__ = _det_laplace.__doc__ + _eval_det_lu.__doc__ = _det_LU.__doc__ + _eval_determinant.__doc__ = _det.__doc__ + adjugate.__doc__ = _adjugate.__doc__ + charpoly.__doc__ = _charpoly.__doc__ + cofactor.__doc__ = _cofactor.__doc__ + cofactor_matrix.__doc__ = _cofactor_matrix.__doc__ + det.__doc__ = _det.__doc__ + per.__doc__ = _per.__doc__ + minor.__doc__ = _minor.__doc__ + minor_submatrix.__doc__ = _minor_submatrix.__doc__ + + def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False): + return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify, + with_pivots=with_pivots) + + @property + def is_echelon(self): + return _is_echelon(self) + + def rank(self, iszerofunc=_iszero, simplify=False): + return _rank(self, iszerofunc=iszerofunc, simplify=simplify) + + def rref_rhs(self, rhs): + """Return reduced row-echelon form of matrix, matrix showing + rhs after reduction steps. ``rhs`` must have the same number + of rows as ``self``. + + Examples + ======== + + >>> from sympy import Matrix, symbols + >>> r1, r2 = symbols('r1 r2') + >>> Matrix([[1, 1], [2, 1]]).rref_rhs(Matrix([r1, r2])) + (Matrix([ + [1, 0], + [0, 1]]), Matrix([ + [ -r1 + r2], + [2*r1 - r2]])) + """ + r, _ = _rref(self.hstack(self, self.eye(self.rows), rhs)) + return r[:, :self.cols], r[:, -rhs.cols:] + + def rref(self, iszerofunc=_iszero, simplify=False, pivots=True, + normalize_last=True): + return _rref(self, iszerofunc=iszerofunc, simplify=simplify, + pivots=pivots, normalize_last=normalize_last) + + echelon_form.__doc__ = _echelon_form.__doc__ + is_echelon.__doc__ = _is_echelon.__doc__ + rank.__doc__ = _rank.__doc__ + rref.__doc__ = _rref.__doc__ + + def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"): + """Validate the arguments for a row/column operation. ``error_str`` + can be one of "row" or "col" depending on the arguments being parsed.""" + if op not in ["n->kn", "n<->m", "n->n+km"]: + raise ValueError("Unknown {} operation '{}'. Valid col operations " + "are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op)) + + # define self_col according to error_str + self_cols = self.cols if error_str == 'col' else self.rows + + # normalize and validate the arguments + if op == "n->kn": + col = col if col is not None else col1 + if col is None or k is None: + raise ValueError("For a {0} operation 'n->kn' you must provide the " + "kwargs `{0}` and `k`".format(error_str)) + if not 0 <= col < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col)) + + elif op == "n<->m": + # we need two cols to swap. It does not matter + # how they were specified, so gather them together and + # remove `None` + cols = {col, k, col1, col2}.difference([None]) + if len(cols) > 2: + # maybe the user left `k` by mistake? + cols = {col, col1, col2}.difference([None]) + if len(cols) != 2: + raise ValueError("For a {0} operation 'n<->m' you must provide the " + "kwargs `{0}1` and `{0}2`".format(error_str)) + col1, col2 = cols + if not 0 <= col1 < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col1)) + if not 0 <= col2 < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2)) + + elif op == "n->n+km": + col = col1 if col is None else col + col2 = col1 if col2 is None else col2 + if col is None or col2 is None or k is None: + raise ValueError("For a {0} operation 'n->n+km' you must provide the " + "kwargs `{0}`, `k`, and `{0}2`".format(error_str)) + if col == col2: + raise ValueError("For a {0} operation 'n->n+km' `{0}` and `{0}2` must " + "be different.".format(error_str)) + if not 0 <= col < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col)) + if not 0 <= col2 < self_cols: + raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2)) + + else: + raise ValueError('invalid operation %s' % repr(op)) + + return op, col, k, col1, col2 + + def _eval_col_op_multiply_col_by_const(self, col, k): + def entry(i, j): + if j == col: + return k * self[i, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_col_op_swap(self, col1, col2): + def entry(i, j): + if j == col1: + return self[i, col2] + elif j == col2: + return self[i, col1] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_col_op_add_multiple_to_other_col(self, col, k, col2): + def entry(i, j): + if j == col: + return self[i, j] + k * self[i, col2] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_row_op_swap(self, row1, row2): + def entry(i, j): + if i == row1: + return self[row2, j] + elif i == row2: + return self[row1, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_row_op_multiply_row_by_const(self, row, k): + def entry(i, j): + if i == row: + return k * self[i, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def _eval_row_op_add_multiple_to_other_row(self, row, k, row2): + def entry(i, j): + if i == row: + return self[i, j] + k * self[row2, j] + return self[i, j] + return self._new(self.rows, self.cols, entry) + + def elementary_col_op(self, op="n->kn", col=None, k=None, col1=None, col2=None): + """Performs the elementary column operation `op`. + + `op` may be one of + + * ``"n->kn"`` (column n goes to k*n) + * ``"n<->m"`` (swap column n and column m) + * ``"n->n+km"`` (column n goes to column n + k*column m) + + Parameters + ========== + + op : string; the elementary row operation + col : the column to apply the column operation + k : the multiple to apply in the column operation + col1 : one column of a column swap + col2 : second column of a column swap or column "m" in the column operation + "n->n+km" + """ + + op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, "col") + + # now that we've validated, we're all good to dispatch + if op == "n->kn": + return self._eval_col_op_multiply_col_by_const(col, k) + if op == "n<->m": + return self._eval_col_op_swap(col1, col2) + if op == "n->n+km": + return self._eval_col_op_add_multiple_to_other_col(col, k, col2) + + def elementary_row_op(self, op="n->kn", row=None, k=None, row1=None, row2=None): + """Performs the elementary row operation `op`. + + `op` may be one of + + * ``"n->kn"`` (row n goes to k*n) + * ``"n<->m"`` (swap row n and row m) + * ``"n->n+km"`` (row n goes to row n + k*row m) + + Parameters + ========== + + op : string; the elementary row operation + row : the row to apply the row operation + k : the multiple to apply in the row operation + row1 : one row of a row swap + row2 : second row of a row swap or row "m" in the row operation + "n->n+km" + """ + + op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, "row") + + # now that we've validated, we're all good to dispatch + if op == "n->kn": + return self._eval_row_op_multiply_row_by_const(row, k) + if op == "n<->m": + return self._eval_row_op_swap(row1, row2) + if op == "n->n+km": + return self._eval_row_op_add_multiple_to_other_row(row, k, row2) + + def columnspace(self, simplify=False): + return _columnspace(self, simplify=simplify) + + def nullspace(self, simplify=False, iszerofunc=_iszero): + return _nullspace(self, simplify=simplify, iszerofunc=iszerofunc) + + def rowspace(self, simplify=False): + return _rowspace(self, simplify=simplify) + + # This is a classmethod but is converted to such later in order to allow + # assignment of __doc__ since that does not work for already wrapped + # classmethods in Python 3.6. + def orthogonalize(cls, *vecs, **kwargs): + return _orthogonalize(cls, *vecs, **kwargs) + + columnspace.__doc__ = _columnspace.__doc__ + nullspace.__doc__ = _nullspace.__doc__ + rowspace.__doc__ = _rowspace.__doc__ + orthogonalize.__doc__ = _orthogonalize.__doc__ + + orthogonalize = classmethod(orthogonalize) # type:ignore + + def eigenvals(self, error_when_incomplete=True, **flags): + return _eigenvals(self, error_when_incomplete=error_when_incomplete, **flags) + + def eigenvects(self, error_when_incomplete=True, iszerofunc=_iszero, **flags): + return _eigenvects(self, error_when_incomplete=error_when_incomplete, + iszerofunc=iszerofunc, **flags) + + def is_diagonalizable(self, reals_only=False, **kwargs): + return _is_diagonalizable(self, reals_only=reals_only, **kwargs) + + def diagonalize(self, reals_only=False, sort=False, normalize=False): + return _diagonalize(self, reals_only=reals_only, sort=sort, + normalize=normalize) + + def bidiagonalize(self, upper=True): + return _bidiagonalize(self, upper=upper) + + def bidiagonal_decomposition(self, upper=True): + return _bidiagonal_decomposition(self, upper=upper) + + @property + def is_positive_definite(self): + return _is_positive_definite(self) + + @property + def is_positive_semidefinite(self): + return _is_positive_semidefinite(self) + + @property + def is_negative_definite(self): + return _is_negative_definite(self) + + @property + def is_negative_semidefinite(self): + return _is_negative_semidefinite(self) + + @property + def is_indefinite(self): + return _is_indefinite(self) + + def jordan_form(self, calc_transform=True, **kwargs): + return _jordan_form(self, calc_transform=calc_transform, **kwargs) + + def left_eigenvects(self, **flags): + return _left_eigenvects(self, **flags) + + def singular_values(self): + return _singular_values(self) + + eigenvals.__doc__ = _eigenvals.__doc__ + eigenvects.__doc__ = _eigenvects.__doc__ + is_diagonalizable.__doc__ = _is_diagonalizable.__doc__ + diagonalize.__doc__ = _diagonalize.__doc__ + is_positive_definite.__doc__ = _is_positive_definite.__doc__ + is_positive_semidefinite.__doc__ = _is_positive_semidefinite.__doc__ + is_negative_definite.__doc__ = _is_negative_definite.__doc__ + is_negative_semidefinite.__doc__ = _is_negative_semidefinite.__doc__ + is_indefinite.__doc__ = _is_indefinite.__doc__ + jordan_form.__doc__ = _jordan_form.__doc__ + left_eigenvects.__doc__ = _left_eigenvects.__doc__ + singular_values.__doc__ = _singular_values.__doc__ + bidiagonalize.__doc__ = _bidiagonalize.__doc__ + bidiagonal_decomposition.__doc__ = _bidiagonal_decomposition.__doc__ + + def diff(self, *args, evaluate=True, **kwargs): + """Calculate the derivative of each element in the matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.diff(x) + Matrix([ + [1, 0], + [0, 0]]) + + See Also + ======== + + integrate + limit + """ + # XXX this should be handled here rather than in Derivative + from sympy.tensor.array.array_derivatives import ArrayDerivative + deriv = ArrayDerivative(self, *args, evaluate=evaluate) + # XXX This can rather changed to always return immutable matrix + if not isinstance(self, Basic) and evaluate: + return deriv.as_mutable() + return deriv + + def _eval_derivative(self, arg): + return self.applyfunc(lambda x: x.diff(arg)) + + def integrate(self, *args, **kwargs): + """Integrate each element of the matrix. ``args`` will + be passed to the ``integrate`` function. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.integrate((x, )) + Matrix([ + [x**2/2, x*y], + [ x, 0]]) + >>> M.integrate((x, 0, 2)) + Matrix([ + [2, 2*y], + [2, 0]]) + + See Also + ======== + + limit + diff + """ + return self.applyfunc(lambda x: x.integrate(*args, **kwargs)) + + def jacobian(self, X): + """Calculates the Jacobian matrix (derivative of a vector-valued function). + + Parameters + ========== + + ``self`` : vector of expressions representing functions f_i(x_1, ..., x_n). + X : set of x_i's in order, it can be a list or a Matrix + + Both ``self`` and X can be a row or a column matrix in any order + (i.e., jacobian() should always work). + + Examples + ======== + + >>> from sympy import sin, cos, Matrix + >>> from sympy.abc import rho, phi + >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2]) + >>> Y = Matrix([rho, phi]) + >>> X.jacobian(Y) + Matrix([ + [cos(phi), -rho*sin(phi)], + [sin(phi), rho*cos(phi)], + [ 2*rho, 0]]) + >>> X = Matrix([rho*cos(phi), rho*sin(phi)]) + >>> X.jacobian(Y) + Matrix([ + [cos(phi), -rho*sin(phi)], + [sin(phi), rho*cos(phi)]]) + + See Also + ======== + + hessian + wronskian + """ + from sympy.matrices.matrixbase import MatrixBase + if not isinstance(X, MatrixBase): + X = self._new(X) + # Both X and ``self`` can be a row or a column matrix, so we need to make + # sure all valid combinations work, but everything else fails: + if self.shape[0] == 1: + m = self.shape[1] + elif self.shape[1] == 1: + m = self.shape[0] + else: + raise TypeError("``self`` must be a row or a column matrix") + if X.shape[0] == 1: + n = X.shape[1] + elif X.shape[1] == 1: + n = X.shape[0] + else: + raise TypeError("X must be a row or a column matrix") + + # m is the number of functions and n is the number of variables + # computing the Jacobian is now easy: + return self._new(m, n, lambda j, i: self[j].diff(X[i])) + + def limit(self, *args): + """Calculate the limit of each element in the matrix. + ``args`` will be passed to the ``limit`` function. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x, y + >>> M = Matrix([[x, y], [1, 0]]) + >>> M.limit(x, 2) + Matrix([ + [2, y], + [1, 0]]) + + See Also + ======== + + integrate + diff + """ + return self.applyfunc(lambda x: x.limit(*args)) + + def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_utilities_simplify): + return self.charpoly(x=x) + + def berkowitz_det(self): + """Computes determinant using Berkowitz method. + + See Also + ======== + + det + """ + return self.det(method='berkowitz') + + def berkowitz_eigenvals(self, **flags): + """Computes eigenvalues of a Matrix using Berkowitz method.""" + return self.eigenvals(**flags) + + def berkowitz_minors(self): + """Computes principal minors using Berkowitz method.""" + sign, minors = self.one, [] + + for poly in self.berkowitz(): + minors.append(sign * poly[-1]) + sign = -sign + + return tuple(minors) + + def berkowitz(self): + from sympy.matrices import zeros + berk = ((1,),) + if not self: + return berk + + if not self.is_square: + raise NonSquareMatrixError() + + A, N = self, self.rows + transforms = [0] * (N - 1) + + for n in range(N, 1, -1): + T, k = zeros(n + 1, n), n - 1 + + R, C = -A[k, :k], A[:k, k] + A, a = A[:k, :k], -A[k, k] + + items = [C] + + for i in range(0, n - 2): + items.append(A * items[i]) + + for i, B in enumerate(items): + items[i] = (R * B)[0, 0] + + items = [self.one, a] + items + + for i in range(n): + T[i:, i] = items[:n - i + 1] + + transforms[k - 1] = T + + polys = [self._new([self.one, -A[0, 0]])] + + for i, T in enumerate(transforms): + polys.append(T * polys[i]) + + return berk + tuple(map(tuple, polys)) + + def cofactorMatrix(self, method="berkowitz"): + return self.cofactor_matrix(method=method) + + def det_bareis(self): + return _det_bareiss(self) + + def det_LU_decomposition(self): + """Compute matrix determinant using LU decomposition. + + + Note that this method fails if the LU decomposition itself + fails. In particular, if the matrix has no inverse this method + will fail. + + TODO: Implement algorithm for sparse matrices (SFF), + http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps. + + See Also + ======== + + + det + berkowitz_det + """ + return self.det(method='lu') + + def jordan_cell(self, eigenval, n): + return self.jordan_block(size=n, eigenvalue=eigenval) + + def jordan_cells(self, calc_transformation=True): + P, J = self.jordan_form() + return P, J.get_diag_blocks() + + def minorEntry(self, i, j, method="berkowitz"): + return self.minor(i, j, method=method) + + def minorMatrix(self, i, j): + return self.minor_submatrix(i, j) + + def permuteBkwd(self, perm): + """Permute the rows of the matrix with the given permutation in reverse.""" + return self.permute_rows(perm, direction='backward') + + def permuteFwd(self, perm): + """Permute the rows of the matrix with the given permutation.""" + return self.permute_rows(perm, direction='forward') + + @property + def kind(self) -> MatrixKind: + elem_kinds = {e.kind for e in self.flat()} + if len(elem_kinds) == 1: + elemkind, = elem_kinds + else: + elemkind = UndefinedKind + return MatrixKind(elemkind) + + def flat(self): + """ + Returns a flat list of all elements in the matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> m = Matrix([[0, 2], [3, 4]]) + >>> m.flat() + [0, 2, 3, 4] + + See Also + ======== + + tolist + values + """ + return [self[i, j] for i in range(self.rows) for j in range(self.cols)] + + def __array__(self, dtype=object, copy=None): + if copy is not None and not copy: + raise TypeError("Cannot implement copy=False when converting Matrix to ndarray") + from .dense import matrix2numpy + return matrix2numpy(self, dtype=dtype) + + def __len__(self): + """Return the number of elements of ``self``. + + Implemented mainly so bool(Matrix()) == False. + """ + return self.rows * self.cols + + def _matrix_pow_by_jordan_blocks(self, num): + from sympy.matrices import diag, MutableMatrix + + def jordan_cell_power(jc, n): + N = jc.shape[0] + l = jc[0,0] + if l.is_zero: + if N == 1 and n.is_nonnegative: + jc[0,0] = l**n + elif not (n.is_integer and n.is_nonnegative): + raise NonInvertibleMatrixError("Non-invertible matrix can only be raised to a nonnegative integer") + else: + for i in range(N): + jc[0,i] = KroneckerDelta(i, n) + else: + for i in range(N): + bn = binomial(n, i) + if isinstance(bn, binomial): + bn = bn._eval_expand_func() + jc[0,i] = l**(n-i)*bn + for i in range(N): + for j in range(1, N-i): + jc[j,i+j] = jc [j-1,i+j-1] + + P, J = self.jordan_form() + jordan_cells = J.get_diag_blocks() + # Make sure jordan_cells matrices are mutable: + jordan_cells = [MutableMatrix(j) for j in jordan_cells] + for j in jordan_cells: + jordan_cell_power(j, num) + return self._new(P.multiply(diag(*jordan_cells)) + .multiply(P.inv())) + + def __str__(self): + if S.Zero in self.shape: + return 'Matrix(%s, %s, [])' % (self.rows, self.cols) + return "Matrix(%s)" % str(self.tolist()) + + def _format_str(self, printer=None): + if not printer: + printer = StrPrinter() + # Handle zero dimensions: + if S.Zero in self.shape: + return 'Matrix(%s, %s, [])' % (self.rows, self.cols) + if self.rows == 1: + return "Matrix([%s])" % self.table(printer, rowsep=',\n') + return "Matrix([\n%s])" % self.table(printer, rowsep=',\n') + + @classmethod + def irregular(cls, ntop, *matrices, **kwargs): + """Return a matrix filled by the given matrices which + are listed in order of appearance from left to right, top to + bottom as they first appear in the matrix. They must fill the + matrix completely. + + Examples + ======== + + >>> from sympy import ones, Matrix + >>> Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3, + ... ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) + Matrix([ + [1, 2, 2, 2, 3, 3], + [1, 2, 2, 2, 3, 3], + [4, 2, 2, 2, 5, 5], + [6, 6, 7, 7, 5, 5]]) + """ + ntop = as_int(ntop) + # make sure we are working with explicit matrices + b = [i.as_explicit() if hasattr(i, 'as_explicit') else i + for i in matrices] + q = list(range(len(b))) + dat = [i.rows for i in b] + active = [q.pop(0) for _ in range(ntop)] + cols = sum(b[i].cols for i in active) + rows = [] + while any(dat): + r = [] + for a, j in enumerate(active): + r.extend(b[j][-dat[j], :]) + dat[j] -= 1 + if dat[j] == 0 and q: + active[a] = q.pop(0) + if len(r) != cols: + raise ValueError(filldedent(''' + Matrices provided do not appear to fill + the space completely.''')) + rows.append(r) + return cls._new(rows) + + @classmethod + def _handle_ndarray(cls, arg): + # NumPy array or matrix or some other object that implements + # __array__. So let's first use this method to get a + # numpy.array() and then make a Python list out of it. + arr = arg.__array__() + if len(arr.shape) == 2: + rows, cols = arr.shape[0], arr.shape[1] + flat_list = [cls._sympify(i) for i in arr.ravel()] + return rows, cols, flat_list + elif len(arr.shape) == 1: + flat_list = [cls._sympify(i) for i in arr] + return arr.shape[0], 1, flat_list + else: + raise NotImplementedError( + "SymPy supports just 1D and 2D matrices") + + @classmethod + def _handle_creation_inputs(cls, *args, **kwargs): + """Return the number of rows, cols and flat matrix elements. + + Examples + ======== + + >>> from sympy import Matrix, I + + Matrix can be constructed as follows: + + * from a nested list of iterables + + >>> Matrix( ((1, 2+I), (3, 4)) ) + Matrix([ + [1, 2 + I], + [3, 4]]) + + * from un-nested iterable (interpreted as a column) + + >>> Matrix( [1, 2] ) + Matrix([ + [1], + [2]]) + + * from un-nested iterable with dimensions + + >>> Matrix(1, 2, [1, 2] ) + Matrix([[1, 2]]) + + * from no arguments (a 0 x 0 matrix) + + >>> Matrix() + Matrix(0, 0, []) + + * from a rule + + >>> Matrix(2, 2, lambda i, j: i/(j + 1) ) + Matrix([ + [0, 0], + [1, 1/2]]) + + See Also + ======== + irregular - filling a matrix with irregular blocks + """ + from sympy.matrices import SparseMatrix + from sympy.matrices.expressions.matexpr import MatrixSymbol + from sympy.matrices.expressions.blockmatrix import BlockMatrix + + flat_list = None + + if len(args) == 1: + # Matrix(SparseMatrix(...)) + if isinstance(args[0], SparseMatrix): + return args[0].rows, args[0].cols, flatten(args[0].tolist()) + + # Matrix(Matrix(...)) + elif isinstance(args[0], MatrixBase): + return args[0].rows, args[0].cols, args[0].flat() + + # Matrix(MatrixSymbol('X', 2, 2)) + elif isinstance(args[0], Basic) and args[0].is_Matrix: + return args[0].rows, args[0].cols, args[0].as_explicit().flat() + + elif isinstance(args[0], mp.matrix): + M = args[0] + flat_list = [cls._sympify(x) for x in M] + return M.rows, M.cols, flat_list + + # Matrix(numpy.ones((2, 2))) + elif hasattr(args[0], "__array__"): + return cls._handle_ndarray(args[0]) + + # Matrix([1, 2, 3]) or Matrix([[1, 2], [3, 4]]) + elif is_sequence(args[0]) \ + and not isinstance(args[0], DeferredVector): + dat = list(args[0]) + ismat = lambda i: isinstance(i, MatrixBase) and ( + evaluate or isinstance(i, (BlockMatrix, MatrixSymbol))) + raw = lambda i: is_sequence(i) and not ismat(i) + evaluate = kwargs.get('evaluate', True) + + + if evaluate: + + def make_explicit(x): + """make Block and Symbol explicit""" + if isinstance(x, BlockMatrix): + return x.as_explicit() + elif isinstance(x, MatrixSymbol) and all(_.is_Integer for _ in x.shape): + return x.as_explicit() + else: + return x + + def make_explicit_row(row): + # Could be list or could be list of lists + if isinstance(row, (list, tuple)): + return [make_explicit(x) for x in row] + else: + return make_explicit(row) + + if isinstance(dat, (list, tuple)): + dat = [make_explicit_row(row) for row in dat] + + if len(dat) == 0: + rows = cols = 0 + flat_list = [] + elif all(raw(i) for i in dat) and len(dat[0]) == 0: + if not all(len(i) == 0 for i in dat): + raise ValueError('mismatched dimensions') + rows = len(dat) + cols = 0 + flat_list = [] + elif not any(raw(i) or ismat(i) for i in dat): + # a column as a list of values + flat_list = [cls._sympify(i) for i in dat] + rows = len(flat_list) + cols = 1 if rows else 0 + elif evaluate and all(ismat(i) for i in dat): + # a column as a list of matrices + ncol = {i.cols for i in dat if any(i.shape)} + if ncol: + if len(ncol) != 1: + raise ValueError('mismatched dimensions') + flat_list = [_ for i in dat for r in i.tolist() for _ in r] + cols = ncol.pop() + rows = len(flat_list)//cols + else: + rows = cols = 0 + flat_list = [] + elif evaluate and any(ismat(i) for i in dat): + ncol = set() + flat_list = [] + for i in dat: + if ismat(i): + flat_list.extend( + [k for j in i.tolist() for k in j]) + if any(i.shape): + ncol.add(i.cols) + elif raw(i): + if i: + ncol.add(len(i)) + flat_list.extend([cls._sympify(ij) for ij in i]) + else: + ncol.add(1) + flat_list.append(i) + if len(ncol) > 1: + raise ValueError('mismatched dimensions') + cols = ncol.pop() + rows = len(flat_list)//cols + else: + # list of lists; each sublist is a logical row + # which might consist of many rows if the values in + # the row are matrices + flat_list = [] + ncol = set() + rows = cols = 0 + for row in dat: + if not is_sequence(row) and \ + not getattr(row, 'is_Matrix', False): + raise ValueError('expecting list of lists') + + if hasattr(row, '__array__'): + if 0 in row.shape: + continue + + if evaluate and all(ismat(i) for i in row): + r, c, flatT = cls._handle_creation_inputs( + [i.T for i in row]) + T = reshape(flatT, [c]) + flat = \ + [T[i][j] for j in range(c) for i in range(r)] + r, c = c, r + else: + r = 1 + if getattr(row, 'is_Matrix', False): + c = 1 + flat = [row] + else: + c = len(row) + flat = [cls._sympify(i) for i in row] + ncol.add(c) + if len(ncol) > 1: + raise ValueError('mismatched dimensions') + flat_list.extend(flat) + rows += r + cols = ncol.pop() if ncol else 0 + + elif len(args) == 3: + rows = as_int(args[0]) + cols = as_int(args[1]) + + if rows < 0 or cols < 0: + raise ValueError("Cannot create a {} x {} matrix. " + "Both dimensions must be positive".format(rows, cols)) + + # Matrix(2, 2, lambda i, j: i+j) + if len(args) == 3 and isinstance(args[2], Callable): + op = args[2] + flat_list = [] + for i in range(rows): + flat_list.extend( + [cls._sympify(op(cls._sympify(i), cls._sympify(j))) + for j in range(cols)]) + + # Matrix(2, 2, [1, 2, 3, 4]) + elif len(args) == 3 and is_sequence(args[2]): + flat_list = args[2] + if len(flat_list) != rows * cols: + raise ValueError( + 'List length should be equal to rows*columns') + flat_list = [cls._sympify(i) for i in flat_list] + + + # Matrix() + elif len(args) == 0: + # Empty Matrix + rows = cols = 0 + flat_list = [] + + if flat_list is None: + raise TypeError(filldedent(''' + Data type not understood; expecting list of lists + or lists of values.''')) + + return rows, cols, flat_list + + def _setitem(self, key, value): + """Helper to set value at location given by key. + + Examples + ======== + + >>> from sympy import Matrix, I, zeros, ones + >>> m = Matrix(((1, 2+I), (3, 4))) + >>> m + Matrix([ + [1, 2 + I], + [3, 4]]) + >>> m[1, 0] = 9 + >>> m + Matrix([ + [1, 2 + I], + [9, 4]]) + >>> m[1, 0] = [[0, 1]] + + To replace row r you assign to position r*m where m + is the number of columns: + + >>> M = zeros(4) + >>> m = M.cols + >>> M[3*m] = ones(1, m)*2; M + Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 2, 2, 2]]) + + And to replace column c you can assign to position c: + + >>> M[2] = ones(m, 1)*4; M + Matrix([ + [0, 0, 4, 0], + [0, 0, 4, 0], + [0, 0, 4, 0], + [2, 2, 4, 2]]) + """ + from .dense import Matrix + + is_slice = isinstance(key, slice) + i, j = key = self.key2ij(key) + is_mat = isinstance(value, MatrixBase) + if isinstance(i, slice) or isinstance(j, slice): + if is_mat: + self.copyin_matrix(key, value) + return + if not isinstance(value, Expr) and is_sequence(value): + self.copyin_list(key, value) + return + raise ValueError('unexpected value: %s' % value) + else: + if (not is_mat and + not isinstance(value, Basic) and is_sequence(value)): + value = Matrix(value) + is_mat = True + if is_mat: + if is_slice: + key = (slice(*divmod(i, self.cols)), + slice(*divmod(j, self.cols))) + else: + key = (slice(i, i + value.rows), + slice(j, j + value.cols)) + self.copyin_matrix(key, value) + else: + return i, j, self._sympify(value) + return + + def add(self, b): + """Return self + b.""" + return self + b + + def condition_number(self): + """Returns the condition number of a matrix. + + This is the maximum singular value divided by the minimum singular value + + Examples + ======== + + >>> from sympy import Matrix, S + >>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]]) + >>> A.condition_number() + 100 + + See Also + ======== + + singular_values + """ + + if not self: + return self.zero + singularvalues = self.singular_values() + return Max(*singularvalues) / Min(*singularvalues) + + def copy(self): + """ + Returns the copy of a matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix(2, 2, [1, 2, 3, 4]) + >>> A.copy() + Matrix([ + [1, 2], + [3, 4]]) + + """ + return self._new(self.rows, self.cols, self.flat()) + + def cross(self, b): + r""" + Return the cross product of ``self`` and ``b`` relaxing the condition + of compatible dimensions: if each has 3 elements, a matrix of the + same type and shape as ``self`` will be returned. If ``b`` has the same + shape as ``self`` then common identities for the cross product (like + `a \times b = - b \times a`) will hold. + + Parameters + ========== + b : 3x1 or 1x3 Matrix + + See Also + ======== + + dot + hat + vee + multiply + multiply_elementwise + """ + from sympy.matrices.expressions.matexpr import MatrixExpr + + if not isinstance(b, (MatrixBase, MatrixExpr)): + raise TypeError( + "{} must be a Matrix, not {}.".format(b, type(b))) + + if not (self.rows * self.cols == b.rows * b.cols == 3): + raise ShapeError("Dimensions incorrect for cross product: %s x %s" % + ((self.rows, self.cols), (b.rows, b.cols))) + else: + return self._new(self.rows, self.cols, ( + (self[1] * b[2] - self[2] * b[1]), + (self[2] * b[0] - self[0] * b[2]), + (self[0] * b[1] - self[1] * b[0]))) + + def hat(self): + r""" + Return the skew-symmetric matrix representing the cross product, + so that ``self.hat() * b`` is equivalent to ``self.cross(b)``. + + Examples + ======== + + Calling ``hat`` creates a skew-symmetric 3x3 Matrix from a 3x1 Matrix: + + >>> from sympy import Matrix + >>> a = Matrix([1, 2, 3]) + >>> a.hat() + Matrix([ + [ 0, -3, 2], + [ 3, 0, -1], + [-2, 1, 0]]) + + Multiplying it with another 3x1 Matrix calculates the cross product: + + >>> b = Matrix([3, 2, 1]) + >>> a.hat() * b + Matrix([ + [-4], + [ 8], + [-4]]) + + Which is equivalent to calling the ``cross`` method: + + >>> a.cross(b) + Matrix([ + [-4], + [ 8], + [-4]]) + + See Also + ======== + + dot + cross + vee + multiply + multiply_elementwise + """ + + if self.shape != (3, 1): + raise ShapeError("Dimensions incorrect, expected (3, 1), got " + + str(self.shape)) + else: + x, y, z = self + return self._new(3, 3, ( + 0, -z, y, + z, 0, -x, + -y, x, 0)) + + def vee(self): + r""" + Return a 3x1 vector from a skew-symmetric matrix representing the cross product, + so that ``self * b`` is equivalent to ``self.vee().cross(b)``. + + Examples + ======== + + Calling ``vee`` creates a vector from a skew-symmetric Matrix: + + >>> from sympy import Matrix + >>> A = Matrix([[0, -3, 2], [3, 0, -1], [-2, 1, 0]]) + >>> a = A.vee() + >>> a + Matrix([ + [1], + [2], + [3]]) + + Calculating the matrix product of the original matrix with a vector + is equivalent to a cross product: + + >>> b = Matrix([3, 2, 1]) + >>> A * b + Matrix([ + [-4], + [ 8], + [-4]]) + + >>> a.cross(b) + Matrix([ + [-4], + [ 8], + [-4]]) + + ``vee`` can also be used to retrieve angular velocity expressions. + Defining a rotation matrix: + + >>> from sympy import rot_ccw_axis3, trigsimp + >>> from sympy.physics.mechanics import dynamicsymbols + >>> theta = dynamicsymbols('theta') + >>> R = rot_ccw_axis3(theta) + >>> R + Matrix([ + [cos(theta(t)), -sin(theta(t)), 0], + [sin(theta(t)), cos(theta(t)), 0], + [ 0, 0, 1]]) + + We can retrieve the angular velocity: + + >>> Omega = R.T * R.diff() + >>> Omega = trigsimp(Omega) + >>> Omega.vee() + Matrix([ + [ 0], + [ 0], + [Derivative(theta(t), t)]]) + + See Also + ======== + + dot + cross + hat + multiply + multiply_elementwise + """ + + if self.shape != (3, 3): + raise ShapeError("Dimensions incorrect, expected (3, 3), got " + + str(self.shape)) + elif not self.is_anti_symmetric(): + raise ValueError("Matrix is not skew-symmetric") + else: + return self._new(3, 1, ( + self[2, 1], + self[0, 2], + self[1, 0])) + + @property + def D(self): + """Return Dirac conjugate (if ``self.rows == 4``). + + Examples + ======== + + >>> from sympy import Matrix, I, eye + >>> m = Matrix((0, 1 + I, 2, 3)) + >>> m.D + Matrix([[0, 1 - I, -2, -3]]) + >>> m = (eye(4) + I*eye(4)) + >>> m[0, 3] = 2 + >>> m.D + Matrix([ + [1 - I, 0, 0, 0], + [ 0, 1 - I, 0, 0], + [ 0, 0, -1 + I, 0], + [ 2, 0, 0, -1 + I]]) + + If the matrix does not have 4 rows an AttributeError will be raised + because this property is only defined for matrices with 4 rows. + + >>> Matrix(eye(2)).D + Traceback (most recent call last): + ... + AttributeError: Matrix has no attribute D. + + See Also + ======== + + sympy.matrices.matrixbase.MatrixBase.conjugate: By-element conjugation + sympy.matrices.matrixbase.MatrixBase.H: Hermite conjugation + """ + from sympy.physics.matrices import mgamma + if self.rows != 4: + # In Python 3.2, properties can only return an AttributeError + # so we can't raise a ShapeError -- see commit which added the + # first line of this inline comment. Also, there is no need + # for a message since MatrixBase will raise the AttributeError + raise AttributeError + return self.H * mgamma(0) + + def dot(self, b, hermitian=None, conjugate_convention=None): + """Return the dot or inner product of two vectors of equal length. + Here ``self`` must be a ``Matrix`` of size 1 x n or n x 1, and ``b`` + must be either a matrix of size 1 x n, n x 1, or a list/tuple of length n. + A scalar is returned. + + By default, ``dot`` does not conjugate ``self`` or ``b``, even if there are + complex entries. Set ``hermitian=True`` (and optionally a ``conjugate_convention``) + to compute the hermitian inner product. + + Possible kwargs are ``hermitian`` and ``conjugate_convention``. + + If ``conjugate_convention`` is ``"left"``, ``"math"`` or ``"maths"``, + the conjugate of the first vector (``self``) is used. If ``"right"`` + or ``"physics"`` is specified, the conjugate of the second vector ``b`` is used. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> v = Matrix([1, 1, 1]) + >>> M.row(0).dot(v) + 6 + >>> M.col(0).dot(v) + 12 + >>> v = [3, 2, 1] + >>> M.row(0).dot(v) + 10 + + >>> from sympy import I + >>> q = Matrix([1*I, 1*I, 1*I]) + >>> q.dot(q, hermitian=False) + -3 + + >>> q.dot(q, hermitian=True) + 3 + + >>> q1 = Matrix([1, 1, 1*I]) + >>> q.dot(q1, hermitian=True, conjugate_convention="maths") + 1 - 2*I + >>> q.dot(q1, hermitian=True, conjugate_convention="physics") + 1 + 2*I + + + See Also + ======== + + cross + multiply + multiply_elementwise + """ + from .dense import Matrix + + if not isinstance(b, MatrixBase): + if is_sequence(b): + if len(b) != self.cols and len(b) != self.rows: + raise ShapeError( + "Dimensions incorrect for dot product: %s, %s" % ( + self.shape, len(b))) + return self.dot(Matrix(b)) + else: + raise TypeError( + "`b` must be an ordered iterable or Matrix, not %s." % + type(b)) + + if (1 not in self.shape) or (1 not in b.shape): + raise ShapeError + if len(self) != len(b): + raise ShapeError( + "Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape)) + + mat = self + n = len(mat) + if mat.shape != (1, n): + mat = mat.reshape(1, n) + if b.shape != (n, 1): + b = b.reshape(n, 1) + + # Now ``mat`` is a row vector and ``b`` is a column vector. + + # If it so happens that only conjugate_convention is passed + # then automatically set hermitian to True. If only hermitian + # is true but no conjugate_convention is not passed then + # automatically set it to ``"maths"`` + + if conjugate_convention is not None and hermitian is None: + hermitian = True + if hermitian and conjugate_convention is None: + conjugate_convention = "maths" + + if hermitian == True: + if conjugate_convention in ("maths", "left", "math"): + mat = mat.conjugate() + elif conjugate_convention in ("physics", "right"): + b = b.conjugate() + else: + raise ValueError("Unknown conjugate_convention was entered." + " conjugate_convention must be one of the" + " following: math, maths, left, physics or right.") + return (mat * b)[0] + + def dual(self): + """Returns the dual of a matrix. + + A dual of a matrix is: + + ``(1/2)*levicivita(i, j, k, l)*M(k, l)`` summed over indices `k` and `l` + + Since the levicivita method is anti_symmetric for any pairwise + exchange of indices, the dual of a symmetric matrix is the zero + matrix. Strictly speaking the dual defined here assumes that the + 'matrix' `M` is a contravariant anti_symmetric second rank tensor, + so that the dual is a covariant second rank tensor. + + """ + from sympy.matrices import zeros + + M, n = self[:, :], self.rows + work = zeros(n) + if self.is_symmetric(): + return work + + for i in range(1, n): + for j in range(1, n): + acum = 0 + for k in range(1, n): + acum += LeviCivita(i, j, 0, k) * M[0, k] + work[i, j] = acum + work[j, i] = -acum + + for l in range(1, n): + acum = 0 + for a in range(1, n): + for b in range(1, n): + acum += LeviCivita(0, l, a, b) * M[a, b] + acum /= 2 + work[0, l] = -acum + work[l, 0] = acum + + return work + + def _eval_matrix_exp_jblock(self): + """A helper function to compute an exponential of a Jordan block + matrix + + Examples + ======== + + >>> from sympy import Symbol, Matrix + >>> l = Symbol('lamda') + + A trivial example of 1*1 Jordan block: + + >>> m = Matrix.jordan_block(1, l) + >>> m._eval_matrix_exp_jblock() + Matrix([[exp(lamda)]]) + + An example of 3*3 Jordan block: + + >>> m = Matrix.jordan_block(3, l) + >>> m._eval_matrix_exp_jblock() + Matrix([ + [exp(lamda), exp(lamda), exp(lamda)/2], + [ 0, exp(lamda), exp(lamda)], + [ 0, 0, exp(lamda)]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Matrix_function#Jordan_decomposition + """ + size = self.rows + l = self[0, 0] + exp_l = exp(l) + + bands = {i: exp_l / factorial(i) for i in range(size)} + + from .sparsetools import banded + return self.__class__(banded(size, bands)) + + + def analytic_func(self, f, x): + """ + Computes f(A) where A is a Square Matrix + and f is an analytic function. + + Examples + ======== + + >>> from sympy import Symbol, Matrix, S, log + + >>> x = Symbol('x') + >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]]) + >>> f = log(x) + >>> m.analytic_func(f, x) + Matrix([ + [ 0, log(2)], + [log(2), 0]]) + + Parameters + ========== + + f : Expr + Analytic Function + x : Symbol + parameter of f + + """ + + f, x = _sympify(f), _sympify(x) + if not self.is_square: + raise NonSquareMatrixError + if not x.is_symbol: + raise ValueError("{} must be a symbol.".format(x)) + if x not in f.free_symbols: + raise ValueError( + "{} must be a parameter of {}.".format(x, f)) + if x in self.free_symbols: + raise ValueError( + "{} must not be a parameter of {}.".format(x, self)) + + eigen = self.eigenvals() + max_mul = max(eigen.values()) + derivative = {} + dd = f + for i in range(max_mul - 1): + dd = diff(dd, x) + derivative[i + 1] = dd + n = self.shape[0] + r = self.zeros(n) + f_val = self.zeros(n, 1) + row = 0 + + for i in eigen: + mul = eigen[i] + f_val[row] = f.subs(x, i) + if f_val[row].is_number and not f_val[row].is_complex: + raise ValueError( + "Cannot evaluate the function because the " + "function {} is not analytic at the given " + "eigenvalue {}".format(f, f_val[row])) + val = 1 + for a in range(n): + r[row, a] = val + val *= i + if mul > 1: + coe = [1 for ii in range(n)] + deri = 1 + while mul > 1: + row = row + 1 + mul -= 1 + d_i = derivative[deri].subs(x, i) + if d_i.is_number and not d_i.is_complex: + raise ValueError( + "Cannot evaluate the function because the " + "derivative {} is not analytic at the given " + "eigenvalue {}".format(derivative[deri], d_i)) + f_val[row] = d_i + for a in range(n): + if a - deri + 1 <= 0: + r[row, a] = 0 + coe[a] = 0 + continue + coe[a] = coe[a]*(a - deri + 1) + r[row, a] = coe[a]*pow(i, a - deri) + deri += 1 + row += 1 + c = r.solve(f_val) + ans = self.zeros(n) + pre = self.eye(n) + for i in range(n): + ans = ans + c[i]*pre + pre *= self + return ans + + + def exp(self): + """Return the exponential of a square matrix. + + Examples + ======== + + >>> from sympy import Symbol, Matrix + + >>> t = Symbol('t') + >>> m = Matrix([[0, 1], [-1, 0]]) * t + >>> m.exp() + Matrix([ + [ exp(I*t)/2 + exp(-I*t)/2, -I*exp(I*t)/2 + I*exp(-I*t)/2], + [I*exp(I*t)/2 - I*exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]]) + """ + if not self.is_square: + raise NonSquareMatrixError( + "Exponentiation is valid only for square matrices") + try: + P, J = self.jordan_form() + cells = J.get_diag_blocks() + except MatrixError: + raise NotImplementedError( + "Exponentiation is implemented only for matrices for which the Jordan normal form can be computed") + + blocks = [cell._eval_matrix_exp_jblock() for cell in cells] + from sympy.matrices import diag + eJ = diag(*blocks) + # n = self.rows + ret = P.multiply(eJ, dotprodsimp=None).multiply(P.inv(), dotprodsimp=None) + if all(value.is_real for value in self.values()): + return type(self)(re(ret)) + else: + return type(self)(ret) + + def _eval_matrix_log_jblock(self): + """Helper function to compute logarithm of a jordan block. + + Examples + ======== + + >>> from sympy import Symbol, Matrix + >>> l = Symbol('lamda') + + A trivial example of 1*1 Jordan block: + + >>> m = Matrix.jordan_block(1, l) + >>> m._eval_matrix_log_jblock() + Matrix([[log(lamda)]]) + + An example of 3*3 Jordan block: + + >>> m = Matrix.jordan_block(3, l) + >>> m._eval_matrix_log_jblock() + Matrix([ + [log(lamda), 1/lamda, -1/(2*lamda**2)], + [ 0, log(lamda), 1/lamda], + [ 0, 0, log(lamda)]]) + """ + size = self.rows + l = self[0, 0] + + if l.is_zero: + raise MatrixError( + 'Could not take logarithm or reciprocal for the given ' + 'eigenvalue {}'.format(l)) + + bands = {0: log(l)} + for i in range(1, size): + bands[i] = -((-l) ** -i) / i + + from .sparsetools import banded + return self.__class__(banded(size, bands)) + + def log(self, simplify=cancel): + """Return the logarithm of a square matrix. + + Parameters + ========== + + simplify : function, bool + The function to simplify the result with. + + Default is ``cancel``, which is effective to reduce the + expression growing for taking reciprocals and inverses for + symbolic matrices. + + Examples + ======== + + >>> from sympy import S, Matrix + + Examples for positive-definite matrices: + + >>> m = Matrix([[1, 1], [0, 1]]) + >>> m.log() + Matrix([ + [0, 1], + [0, 0]]) + + >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]]) + >>> m.log() + Matrix([ + [ 0, log(2)], + [log(2), 0]]) + + Examples for non positive-definite matrices: + + >>> m = Matrix([[S(3)/4, S(5)/4], [S(5)/4, S(3)/4]]) + >>> m.log() + Matrix([ + [ I*pi/2, log(2) - I*pi/2], + [log(2) - I*pi/2, I*pi/2]]) + + >>> m = Matrix( + ... [[0, 0, 0, 1], + ... [0, 0, 1, 0], + ... [0, 1, 0, 0], + ... [1, 0, 0, 0]]) + >>> m.log() + Matrix([ + [ I*pi/2, 0, 0, -I*pi/2], + [ 0, I*pi/2, -I*pi/2, 0], + [ 0, -I*pi/2, I*pi/2, 0], + [-I*pi/2, 0, 0, I*pi/2]]) + """ + if not self.is_square: + raise NonSquareMatrixError( + "Logarithm is valid only for square matrices") + + try: + if simplify: + P, J = simplify(self).jordan_form() + else: + P, J = self.jordan_form() + + cells = J.get_diag_blocks() + except MatrixError: + raise NotImplementedError( + "Logarithm is implemented only for matrices for which " + "the Jordan normal form can be computed") + + blocks = [ + cell._eval_matrix_log_jblock() + for cell in cells] + from sympy.matrices import diag + eJ = diag(*blocks) + + if simplify: + ret = simplify(P * eJ * simplify(P.inv())) + ret = self.__class__(ret) + else: + ret = P * eJ * P.inv() + + return ret + + def is_nilpotent(self): + """Checks if a matrix is nilpotent. + + A matrix B is nilpotent if for some integer k, B**k is + a zero matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) + >>> a.is_nilpotent() + True + + >>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]]) + >>> a.is_nilpotent() + False + """ + if not self: + return True + if not self.is_square: + raise NonSquareMatrixError( + "Nilpotency is valid only for square matrices") + x = uniquely_named_symbol('x', self, modify=lambda s: '_' + s) + p = self.charpoly(x) + if p.args[0] == x ** self.rows: + return True + return False + + def key2bounds(self, keys): + """Converts a key with potentially mixed types of keys (integer and slice) + into a tuple of ranges and raises an error if any index is out of ``self``'s + range. + + See Also + ======== + + key2ij + """ + islice, jslice = [isinstance(k, slice) for k in keys] + if islice: + if not self.rows: + rlo = rhi = 0 + else: + rlo, rhi = keys[0].indices(self.rows)[:2] + else: + rlo = a2idx(keys[0], self.rows) + rhi = rlo + 1 + if jslice: + if not self.cols: + clo = chi = 0 + else: + clo, chi = keys[1].indices(self.cols)[:2] + else: + clo = a2idx(keys[1], self.cols) + chi = clo + 1 + return rlo, rhi, clo, chi + + def key2ij(self, key): + """Converts key into canonical form, converting integers or indexable + items into valid integers for ``self``'s range or returning slices + unchanged. + + See Also + ======== + + key2bounds + """ + if is_sequence(key): + if not len(key) == 2: + raise TypeError('key must be a sequence of length 2') + return [a2idx(i, n) if not isinstance(i, slice) else i + for i, n in zip(key, self.shape)] + elif isinstance(key, slice): + return key.indices(len(self))[:2] + else: + return divmod(a2idx(key, len(self)), self.cols) + + def normalized(self, iszerofunc=_iszero): + """Return the normalized version of ``self``. + + Parameters + ========== + + iszerofunc : Function, optional + A function to determine whether ``self`` is a zero vector. + The default ``_iszero`` tests to see if each element is + exactly zero. + + Returns + ======= + + Matrix + Normalized vector form of ``self``. + It has the same length as a unit vector. However, a zero vector + will be returned for a vector with norm 0. + + Raises + ====== + + ShapeError + If the matrix is not in a vector form. + + See Also + ======== + + norm + """ + if self.rows != 1 and self.cols != 1: + raise ShapeError("A Matrix must be a vector to normalize.") + norm = self.norm() + if iszerofunc(norm): + out = self.zeros(self.rows, self.cols) + else: + out = self.applyfunc(lambda i: i / norm) + return out + + def norm(self, ord=None): + """Return the Norm of a Matrix or Vector. + + In the simplest case this is the geometric size of the vector + Other norms can be specified by the ord parameter + + + ===== ============================ ========================== + ord norm for matrices norm for vectors + ===== ============================ ========================== + None Frobenius norm 2-norm + 'fro' Frobenius norm - does not exist + inf maximum row sum max(abs(x)) + -inf -- min(abs(x)) + 1 maximum column sum as below + -1 -- as below + 2 2-norm (largest sing. value) as below + -2 smallest singular value as below + other - does not exist sum(abs(x)**ord)**(1./ord) + ===== ============================ ========================== + + Examples + ======== + + >>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo + >>> x = Symbol('x', real=True) + >>> v = Matrix([cos(x), sin(x)]) + >>> trigsimp( v.norm() ) + 1 + >>> v.norm(10) + (sin(x)**10 + cos(x)**10)**(1/10) + >>> A = Matrix([[1, 1], [1, 1]]) + >>> A.norm(1) # maximum sum of absolute values of A is 2 + 2 + >>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm) + 2 + >>> A.norm(-2) # Inverse spectral norm (smallest singular value) + 0 + >>> A.norm() # Frobenius Norm + 2 + >>> A.norm(oo) # Infinity Norm + 2 + >>> Matrix([1, -2]).norm(oo) + 2 + >>> Matrix([-1, 2]).norm(-oo) + 1 + + See Also + ======== + + normalized + """ + # Row or Column Vector Norms + vals = list(self.values()) or [0] + if S.One in self.shape: + if ord in (2, None): # Common case sqrt() + return sqrt(Add(*(abs(i) ** 2 for i in vals))) + + elif ord == 1: # sum(abs(x)) + return Add(*(abs(i) for i in vals)) + + elif ord is S.Infinity: # max(abs(x)) + return Max(*[abs(i) for i in vals]) + + elif ord is S.NegativeInfinity: # min(abs(x)) + return Min(*[abs(i) for i in vals]) + + # Otherwise generalize the 2-norm, Sum(x_i**ord)**(1/ord) + # Note that while useful this is not mathematically a norm + try: + return Pow(Add(*(abs(i) ** ord for i in vals)), S.One / ord) + except (NotImplementedError, TypeError): + raise ValueError("Expected order to be Number, Symbol, oo") + + # Matrix Norms + else: + if ord == 1: # Maximum column sum + m = self.applyfunc(abs) + return Max(*[sum(m.col(i)) for i in range(m.cols)]) + + elif ord == 2: # Spectral Norm + # Maximum singular value + return Max(*self.singular_values()) + + elif ord == -2: + # Minimum singular value + return Min(*self.singular_values()) + + elif ord is S.Infinity: # Infinity Norm - Maximum row sum + m = self.applyfunc(abs) + return Max(*[sum(m.row(i)) for i in range(m.rows)]) + + elif (ord is None or isinstance(ord, + str) and ord.lower() in + ['f', 'fro', 'frobenius', 'vector']): + # Reshape as vector and send back to norm function + return self.vec().norm(ord=2) + + else: + raise NotImplementedError("Matrix Norms under development") + + def print_nonzero(self, symb="X"): + """Shows location of non-zero entries for fast shape lookup. + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> m = Matrix(2, 3, lambda i, j: i*3+j) + >>> m + Matrix([ + [0, 1, 2], + [3, 4, 5]]) + >>> m.print_nonzero() + [ XX] + [XXX] + >>> m = eye(4) + >>> m.print_nonzero("x") + [x ] + [ x ] + [ x ] + [ x] + + """ + s = [] + for i in range(self.rows): + line = [] + for j in range(self.cols): + if self[i, j] == 0: + line.append(" ") + else: + line.append(str(symb)) + s.append("[%s]" % ''.join(line)) + print('\n'.join(s)) + + def project(self, v): + """Return the projection of ``self`` onto the line containing ``v``. + + Examples + ======== + + >>> from sympy import Matrix, S, sqrt + >>> V = Matrix([sqrt(3)/2, S.Half]) + >>> x = Matrix([[1, 0]]) + >>> V.project(x) + Matrix([[sqrt(3)/2, 0]]) + >>> V.project(-x) + Matrix([[sqrt(3)/2, 0]]) + """ + return v * (self.dot(v) / v.dot(v)) + + def table(self, printer, rowstart='[', rowend=']', rowsep='\n', + colsep=', ', align='right'): + r""" + String form of Matrix as a table. + + ``printer`` is the printer to use for on the elements (generally + something like StrPrinter()) + + ``rowstart`` is the string used to start each row (by default '['). + + ``rowend`` is the string used to end each row (by default ']'). + + ``rowsep`` is the string used to separate rows (by default a newline). + + ``colsep`` is the string used to separate columns (by default ', '). + + ``align`` defines how the elements are aligned. Must be one of 'left', + 'right', or 'center'. You can also use '<', '>', and '^' to mean the + same thing, respectively. + + This is used by the string printer for Matrix. + + Examples + ======== + + >>> from sympy import Matrix, StrPrinter + >>> M = Matrix([[1, 2], [-33, 4]]) + >>> printer = StrPrinter() + >>> M.table(printer) + '[ 1, 2]\n[-33, 4]' + >>> print(M.table(printer)) + [ 1, 2] + [-33, 4] + >>> print(M.table(printer, rowsep=',\n')) + [ 1, 2], + [-33, 4] + >>> print('[%s]' % M.table(printer, rowsep=',\n')) + [[ 1, 2], + [-33, 4]] + >>> print(M.table(printer, colsep=' ')) + [ 1 2] + [-33 4] + >>> print(M.table(printer, align='center')) + [ 1 , 2] + [-33, 4] + >>> print(M.table(printer, rowstart='{', rowend='}')) + { 1, 2} + {-33, 4} + """ + # Handle zero dimensions: + if S.Zero in self.shape: + return '[]' + # Build table of string representations of the elements + res = [] + # Track per-column max lengths for pretty alignment + maxlen = [0] * self.cols + for i in range(self.rows): + res.append([]) + for j in range(self.cols): + s = printer._print(self[i, j]) + res[-1].append(s) + maxlen[j] = max(len(s), maxlen[j]) + # Patch strings together + align = { + 'left': 'ljust', + 'right': 'rjust', + 'center': 'center', + '<': 'ljust', + '>': 'rjust', + '^': 'center', + }[align] + for i, row in enumerate(res): + for j, elem in enumerate(row): + row[j] = getattr(elem, align)(maxlen[j]) + res[i] = rowstart + colsep.join(row) + rowend + return rowsep.join(res) + + def rank_decomposition(self, iszerofunc=_iszero, simplify=False): + return _rank_decomposition(self, iszerofunc=iszerofunc, + simplify=simplify) + + def cholesky(self, hermitian=True): + raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') + + def LDLdecomposition(self, hermitian=True): + raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') + + def LUdecomposition(self, iszerofunc=_iszero, simpfunc=None, + rankcheck=False): + return _LUdecomposition(self, iszerofunc=iszerofunc, simpfunc=simpfunc, + rankcheck=rankcheck) + + def LUdecomposition_Simple(self, iszerofunc=_iszero, simpfunc=None, + rankcheck=False): + return _LUdecomposition_Simple(self, iszerofunc=iszerofunc, + simpfunc=simpfunc, rankcheck=rankcheck) + + def LUdecompositionFF(self): + return _LUdecompositionFF(self) + + def singular_value_decomposition(self): + return _singular_value_decomposition(self) + + def QRdecomposition(self): + return _QRdecomposition(self) + + def upper_hessenberg_decomposition(self): + return _upper_hessenberg_decomposition(self) + + def diagonal_solve(self, rhs): + return _diagonal_solve(self, rhs) + + def lower_triangular_solve(self, rhs): + raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') + + def upper_triangular_solve(self, rhs): + raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') + + def cholesky_solve(self, rhs): + return _cholesky_solve(self, rhs) + + def LDLsolve(self, rhs): + return _LDLsolve(self, rhs) + + def LUsolve(self, rhs, iszerofunc=_iszero): + return _LUsolve(self, rhs, iszerofunc=iszerofunc) + + def QRsolve(self, b): + return _QRsolve(self, b) + + def gauss_jordan_solve(self, B, freevar=False): + return _gauss_jordan_solve(self, B, freevar=freevar) + + def pinv_solve(self, B, arbitrary_matrix=None): + return _pinv_solve(self, B, arbitrary_matrix=arbitrary_matrix) + + def cramer_solve(self, rhs, det_method="laplace"): + return _cramer_solve(self, rhs, det_method=det_method) + + def solve(self, rhs, method='GJ'): + return _solve(self, rhs, method=method) + + def solve_least_squares(self, rhs, method='CH'): + return _solve_least_squares(self, rhs, method=method) + + def pinv(self, method='RD'): + return _pinv(self, method=method) + + def inverse_ADJ(self, iszerofunc=_iszero): + return _inv_ADJ(self, iszerofunc=iszerofunc) + + def inverse_BLOCK(self, iszerofunc=_iszero): + return _inv_block(self, iszerofunc=iszerofunc) + + def inverse_GE(self, iszerofunc=_iszero): + return _inv_GE(self, iszerofunc=iszerofunc) + + def inverse_LU(self, iszerofunc=_iszero): + return _inv_LU(self, iszerofunc=iszerofunc) + + def inverse_CH(self, iszerofunc=_iszero): + return _inv_CH(self, iszerofunc=iszerofunc) + + def inverse_LDL(self, iszerofunc=_iszero): + return _inv_LDL(self, iszerofunc=iszerofunc) + + def inverse_QR(self, iszerofunc=_iszero): + return _inv_QR(self, iszerofunc=iszerofunc) + + def inv(self, method=None, iszerofunc=_iszero, try_block_diag=False): + return _inv(self, method=method, iszerofunc=iszerofunc, + try_block_diag=try_block_diag) + + def connected_components(self): + return _connected_components(self) + + def connected_components_decomposition(self): + return _connected_components_decomposition(self) + + def strongly_connected_components(self): + return _strongly_connected_components(self) + + def strongly_connected_components_decomposition(self, lower=True): + return _strongly_connected_components_decomposition(self, lower=lower) + + _sage_ = Basic._sage_ + + rank_decomposition.__doc__ = _rank_decomposition.__doc__ + cholesky.__doc__ = _cholesky.__doc__ + LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ + LUdecomposition.__doc__ = _LUdecomposition.__doc__ + LUdecomposition_Simple.__doc__ = _LUdecomposition_Simple.__doc__ + LUdecompositionFF.__doc__ = _LUdecompositionFF.__doc__ + singular_value_decomposition.__doc__ = _singular_value_decomposition.__doc__ + QRdecomposition.__doc__ = _QRdecomposition.__doc__ + upper_hessenberg_decomposition.__doc__ = _upper_hessenberg_decomposition.__doc__ + + diagonal_solve.__doc__ = _diagonal_solve.__doc__ + lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ + upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ + cholesky_solve.__doc__ = _cholesky_solve.__doc__ + LDLsolve.__doc__ = _LDLsolve.__doc__ + LUsolve.__doc__ = _LUsolve.__doc__ + QRsolve.__doc__ = _QRsolve.__doc__ + gauss_jordan_solve.__doc__ = _gauss_jordan_solve.__doc__ + pinv_solve.__doc__ = _pinv_solve.__doc__ + cramer_solve.__doc__ = _cramer_solve.__doc__ + solve.__doc__ = _solve.__doc__ + solve_least_squares.__doc__ = _solve_least_squares.__doc__ + + pinv.__doc__ = _pinv.__doc__ + inverse_ADJ.__doc__ = _inv_ADJ.__doc__ + inverse_GE.__doc__ = _inv_GE.__doc__ + inverse_LU.__doc__ = _inv_LU.__doc__ + inverse_CH.__doc__ = _inv_CH.__doc__ + inverse_LDL.__doc__ = _inv_LDL.__doc__ + inverse_QR.__doc__ = _inv_QR.__doc__ + inverse_BLOCK.__doc__ = _inv_block.__doc__ + inv.__doc__ = _inv.__doc__ + + connected_components.__doc__ = _connected_components.__doc__ + connected_components_decomposition.__doc__ = \ + _connected_components_decomposition.__doc__ + strongly_connected_components.__doc__ = \ + _strongly_connected_components.__doc__ + strongly_connected_components_decomposition.__doc__ = \ + _strongly_connected_components_decomposition.__doc__ + + +def _convert_matrix(typ, mat): + """Convert mat to a Matrix of type typ.""" + from sympy.matrices.matrixbase import MatrixBase + if getattr(mat, "is_Matrix", False) and not isinstance(mat, MatrixBase): + # This is needed for interop between Matrix and the redundant matrix + # mixin types like _MinimalMatrix etc. If anyone should happen to be + # using those then this keeps them working. Really _MinimalMatrix etc + # should be deprecated and removed though. + return typ(*mat.shape, list(mat)) + else: + return typ(mat) + + +def _has_matrix_shape(other): + shape = getattr(other, 'shape', None) + if shape is None: + return False + return isinstance(shape, tuple) and len(shape) == 2 + + +def _has_rows_cols(other): + return hasattr(other, 'rows') and hasattr(other, 'cols') + + +def _coerce_operand(self, other): + """Convert other to a Matrix, or check for possible scalar.""" + + INVALID = None, 'invalid_type' + + # Disallow mixing Matrix and Array + if isinstance(other, NDimArray): + return INVALID + + is_Matrix = getattr(other, 'is_Matrix', None) + + # Return a Matrix as-is + if is_Matrix: + return other, 'is_matrix' + + # Try to convert numpy array, mpmath matrix etc. + if is_Matrix is None: + if _has_matrix_shape(other) or _has_rows_cols(other): + return _convert_matrix(type(self), other), 'is_matrix' + + # Could be a scalar but only if not iterable... + if not isinstance(other, Iterable): + return other, 'possible_scalar' + + return INVALID + + +def classof(A, B): + """ + Get the type of the result when combining matrices of different types. + + Currently the strategy is that immutability is contagious. + + Examples + ======== + + >>> from sympy import Matrix, ImmutableMatrix + >>> from sympy.matrices.matrixbase import classof + >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix + >>> IM = ImmutableMatrix([[1, 2], [3, 4]]) + >>> classof(M, IM) + + """ + priority_A = getattr(A, '_class_priority', None) + priority_B = getattr(B, '_class_priority', None) + if None not in (priority_A, priority_B): + if A._class_priority > B._class_priority: + return A.__class__ + else: + return B.__class__ + + try: + import numpy + except ImportError: + pass + else: + if isinstance(A, numpy.ndarray): + return B.__class__ + if isinstance(B, numpy.ndarray): + return A.__class__ + + raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__)) + + +def _unify_with_other(self, other): + """Unify self and other into a single matrix type, or check for scalar.""" + other, T = _coerce_operand(self, other) + + if T == "is_matrix": + typ = classof(self, other) + if typ != self.__class__: + self = _convert_matrix(typ, self) + if typ != other.__class__: + other = _convert_matrix(typ, other) + + return self, other, T + + +def a2idx(j, n=None): + """Return integer after making positive and validating against n.""" + if not isinstance(j, int): + jindex = getattr(j, '__index__', None) + if jindex is not None: + j = jindex() + else: + raise IndexError("Invalid index a[%r]" % (j,)) + if n is not None: + if j < 0: + j += n + if not (j >= 0 and j < n): + raise IndexError("Index out of range: a[%s]" % (j,)) + return int(j) + + +class DeferredVector(Symbol, NotIterable): # type: ignore + """A vector whose components are deferred (e.g. for use with lambdify). + + Examples + ======== + + >>> from sympy import DeferredVector, lambdify + >>> X = DeferredVector( 'X' ) + >>> X + X + >>> expr = (X[0] + 2, X[2] + 3) + >>> func = lambdify( X, expr) + >>> func( [1, 2, 3] ) + (3, 6) + """ + + def __getitem__(self, i): + if i == -0: + i = 0 + if i < 0: + raise IndexError('DeferredVector index out of range') + component_name = '%s[%d]' % (self.name, i) + return Symbol(component_name) + + def __str__(self): + return sstr(self) + + def __repr__(self): + return "DeferredVector('%s')" % self.name diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/normalforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/normalforms.py new file mode 100644 index 0000000000000000000000000000000000000000..61a7d26bbdb8c8a3e8e3044d39b2403b2e14b7d5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/normalforms.py @@ -0,0 +1,156 @@ +'''Functions returning normal forms of matrices''' + +from sympy.polys.domains.integerring import ZZ +from sympy.polys.polytools import Poly +from sympy.polys.matrices import DomainMatrix +from sympy.polys.matrices.normalforms import ( + smith_normal_form as _snf, + is_smith_normal_form as _is_snf, + smith_normal_decomp as _snd, + invariant_factors as _invf, + hermite_normal_form as _hnf, + ) + + +def _to_domain(m, domain=None): + """Convert Matrix to DomainMatrix""" + # XXX: deprecated support for RawMatrix: + ring = getattr(m, "ring", None) + m = m.applyfunc(lambda e: e.as_expr() if isinstance(e, Poly) else e) + + dM = DomainMatrix.from_Matrix(m) + + domain = domain or ring + if domain is not None: + dM = dM.convert_to(domain) + return dM + + +def smith_normal_form(m, domain=None): + ''' + Return the Smith Normal Form of a matrix `m` over the ring `domain`. + This will only work if the ring is a principal ideal domain. + + Examples + ======== + + >>> from sympy import Matrix, ZZ + >>> from sympy.matrices.normalforms import smith_normal_form + >>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]]) + >>> print(smith_normal_form(m, domain=ZZ)) + Matrix([[1, 0, 0], [0, 10, 0], [0, 0, 30]]) + + ''' + dM = _to_domain(m, domain) + return _snf(dM).to_Matrix() + + +def is_smith_normal_form(m, domain=None): + ''' + Checks that the matrix is in Smith Normal Form + ''' + dM = _to_domain(m, domain) + return _is_snf(dM) + + +def smith_normal_decomp(m, domain=None): + ''' + Return the Smith Normal Decomposition of a matrix `m` over the ring + `domain`. This will only work if the ring is a principal ideal domain. + + Examples + ======== + + >>> from sympy import Matrix, ZZ + >>> from sympy.matrices.normalforms import smith_normal_decomp + >>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]]) + >>> a, s, t = smith_normal_decomp(m, domain=ZZ) + >>> assert a == s * m * t + ''' + dM = _to_domain(m, domain) + a, s, t = _snd(dM) + return a.to_Matrix(), s.to_Matrix(), t.to_Matrix() + + +def invariant_factors(m, domain=None): + ''' + Return the tuple of abelian invariants for a matrix `m` + (as in the Smith-Normal form) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm + .. [2] https://web.archive.org/web/20200331143852/https://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf + + ''' + dM = _to_domain(m, domain) + factors = _invf(dM) + factors = tuple(dM.domain.to_sympy(f) for f in factors) + # XXX: deprecated. + if hasattr(m, "ring"): + if m.ring.is_PolynomialRing: + K = m.ring + to_poly = lambda f: Poly(f, K.symbols, domain=K.domain) + factors = tuple(to_poly(f) for f in factors) + return factors + + +def hermite_normal_form(A, *, D=None, check_rank=False): + r""" + Compute the Hermite Normal Form of a Matrix *A* of integers. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.matrices.normalforms import hermite_normal_form + >>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]]) + >>> print(hermite_normal_form(m)) + Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]]) + + Parameters + ========== + + A : $m \times n$ ``Matrix`` of integers. + + D : int, optional + Let $W$ be the HNF of *A*. If known in advance, a positive integer *D* + being any multiple of $\det(W)$ may be provided. In this case, if *A* + also has rank $m$, then we may use an alternative algorithm that works + mod *D* in order to prevent coefficient explosion. + + check_rank : boolean, optional (default=False) + The basic assumption is that, if you pass a value for *D*, then + you already believe that *A* has rank $m$, so we do not waste time + checking it for you. If you do want this to be checked (and the + ordinary, non-modulo *D* algorithm to be used if the check fails), then + set *check_rank* to ``True``. + + Returns + ======= + + ``Matrix`` + The HNF of matrix *A*. + + Raises + ====== + + DMDomainError + If the domain of the matrix is not :ref:`ZZ`. + + DMShapeError + If the mod *D* algorithm is used but the matrix has more rows than + columns. + + References + ========== + + .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* + (See Algorithms 2.4.5 and 2.4.8.) + + """ + # Accept any of Python int, SymPy Integer, and ZZ itself: + if D is not None and not ZZ.of_type(D): + D = ZZ(int(D)) + return _hnf(A._rep, D=D, check_rank=check_rank).to_Matrix() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/reductions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..aace8c0336358e1869a34d99f79390cc0c0163fe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/reductions.py @@ -0,0 +1,387 @@ +from types import FunctionType + +from sympy.polys.polyerrors import CoercionFailed +from sympy.polys.domains import ZZ, QQ + +from .utilities import _get_intermediate_simp, _iszero, _dotprodsimp, _simplify +from .determinant import _find_reasonable_pivot + + +def _row_reduce_list(mat, rows, cols, one, iszerofunc, simpfunc, + normalize_last=True, normalize=True, zero_above=True): + """Row reduce a flat list representation of a matrix and return a tuple + (rref_matrix, pivot_cols, swaps) where ``rref_matrix`` is a flat list, + ``pivot_cols`` are the pivot columns and ``swaps`` are any row swaps that + were used in the process of row reduction. + + Parameters + ========== + + mat : list + list of matrix elements, must be ``rows`` * ``cols`` in length + + rows, cols : integer + number of rows and columns in flat list representation + + one : SymPy object + represents the value one, from ``Matrix.one`` + + iszerofunc : determines if an entry can be used as a pivot + + simpfunc : used to simplify elements and test if they are + zero if ``iszerofunc`` returns `None` + + normalize_last : indicates where all row reduction should + happen in a fraction-free manner and then the rows are + normalized (so that the pivots are 1), or whether + rows should be normalized along the way (like the naive + row reduction algorithm) + + normalize : whether pivot rows should be normalized so that + the pivot value is 1 + + zero_above : whether entries above the pivot should be zeroed. + If ``zero_above=False``, an echelon matrix will be returned. + """ + + def get_col(i): + return mat[i::cols] + + def row_swap(i, j): + mat[i*cols:(i + 1)*cols], mat[j*cols:(j + 1)*cols] = \ + mat[j*cols:(j + 1)*cols], mat[i*cols:(i + 1)*cols] + + def cross_cancel(a, i, b, j): + """Does the row op row[i] = a*row[i] - b*row[j]""" + q = (j - i)*cols + for p in range(i*cols, (i + 1)*cols): + mat[p] = isimp(a*mat[p] - b*mat[p + q]) + + isimp = _get_intermediate_simp(_dotprodsimp) + piv_row, piv_col = 0, 0 + pivot_cols = [] + swaps = [] + + # use a fraction free method to zero above and below each pivot + while piv_col < cols and piv_row < rows: + pivot_offset, pivot_val, \ + assumed_nonzero, newly_determined = _find_reasonable_pivot( + get_col(piv_col)[piv_row:], iszerofunc, simpfunc) + + # _find_reasonable_pivot may have simplified some things + # in the process. Let's not let them go to waste + for (offset, val) in newly_determined: + offset += piv_row + mat[offset*cols + piv_col] = val + + if pivot_offset is None: + piv_col += 1 + continue + + pivot_cols.append(piv_col) + if pivot_offset != 0: + row_swap(piv_row, pivot_offset + piv_row) + swaps.append((piv_row, pivot_offset + piv_row)) + + # if we aren't normalizing last, we normalize + # before we zero the other rows + if normalize_last is False: + i, j = piv_row, piv_col + mat[i*cols + j] = one + for p in range(i*cols + j + 1, (i + 1)*cols): + mat[p] = isimp(mat[p] / pivot_val) + # after normalizing, the pivot value is 1 + pivot_val = one + + # zero above and below the pivot + for row in range(rows): + # don't zero our current row + if row == piv_row: + continue + # don't zero above the pivot unless we're told. + if zero_above is False and row < piv_row: + continue + # if we're already a zero, don't do anything + val = mat[row*cols + piv_col] + if iszerofunc(val): + continue + + cross_cancel(pivot_val, row, val, piv_row) + piv_row += 1 + + # normalize each row + if normalize_last is True and normalize is True: + for piv_i, piv_j in enumerate(pivot_cols): + pivot_val = mat[piv_i*cols + piv_j] + mat[piv_i*cols + piv_j] = one + for p in range(piv_i*cols + piv_j + 1, (piv_i + 1)*cols): + mat[p] = isimp(mat[p] / pivot_val) + + return mat, tuple(pivot_cols), tuple(swaps) + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _row_reduce(M, iszerofunc, simpfunc, normalize_last=True, + normalize=True, zero_above=True): + + mat, pivot_cols, swaps = _row_reduce_list(list(M), M.rows, M.cols, M.one, + iszerofunc, simpfunc, normalize_last=normalize_last, + normalize=normalize, zero_above=zero_above) + + return M._new(M.rows, M.cols, mat), pivot_cols, swaps + + +def _is_echelon(M, iszerofunc=_iszero): + """Returns `True` if the matrix is in echelon form. That is, all rows of + zeros are at the bottom, and below each leading non-zero in a row are + exclusively zeros.""" + + if M.rows <= 0 or M.cols <= 0: + return True + + zeros_below = all(iszerofunc(t) for t in M[1:, 0]) + + if iszerofunc(M[0, 0]): + return zeros_below and _is_echelon(M[:, 1:], iszerofunc) + + return zeros_below and _is_echelon(M[1:, 1:], iszerofunc) + + +def _echelon_form(M, iszerofunc=_iszero, simplify=False, with_pivots=False): + """Returns a matrix row-equivalent to ``M`` that is in echelon form. Note + that echelon form of a matrix is *not* unique, however, properties like the + row space and the null space are preserved. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> M.echelon_form() + Matrix([ + [1, 2], + [0, -2]]) + """ + + simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify + + mat, pivots, _ = _row_reduce(M, iszerofunc, simpfunc, + normalize_last=True, normalize=False, zero_above=False) + + if with_pivots: + return mat, pivots + + return mat + + +# This functions is a candidate for caching if it gets implemented for matrices. +def _rank(M, iszerofunc=_iszero, simplify=False): + """Returns the rank of a matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x + >>> m = Matrix([[1, 2], [x, 1 - 1/x]]) + >>> m.rank() + 2 + >>> n = Matrix(3, 3, range(1, 10)) + >>> n.rank() + 2 + """ + + def _permute_complexity_right(M, iszerofunc): + """Permute columns with complicated elements as + far right as they can go. Since the ``sympy`` row reduction + algorithms start on the left, having complexity right-shifted + speeds things up. + + Returns a tuple (mat, perm) where perm is a permutation + of the columns to perform to shift the complex columns right, and mat + is the permuted matrix.""" + + def complexity(i): + # the complexity of a column will be judged by how many + # element's zero-ness cannot be determined + return sum(1 if iszerofunc(e) is None else 0 for e in M[:, i]) + + complex = [(complexity(i), i) for i in range(M.cols)] + perm = [j for (i, j) in sorted(complex)] + + return (M.permute(perm, orientation='cols'), perm) + + simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify + + # for small matrices, we compute the rank explicitly + # if is_zero on elements doesn't answer the question + # for small matrices, we fall back to the full routine. + if M.rows <= 0 or M.cols <= 0: + return 0 + + if M.rows <= 1 or M.cols <= 1: + zeros = [iszerofunc(x) for x in M] + + if False in zeros: + return 1 + + if M.rows == 2 and M.cols == 2: + zeros = [iszerofunc(x) for x in M] + + if False not in zeros and None not in zeros: + return 0 + + d = M.det() + + if iszerofunc(d) and False in zeros: + return 1 + if iszerofunc(d) is False: + return 2 + + mat, _ = _permute_complexity_right(M, iszerofunc=iszerofunc) + _, pivots, _ = _row_reduce(mat, iszerofunc, simpfunc, normalize_last=True, + normalize=False, zero_above=False) + + return len(pivots) + + +def _to_DM_ZZ_QQ(M): + # We have to test for _rep here because there are tests that otherwise fail + # with e.g. "AttributeError: 'SubspaceOnlyMatrix' object has no attribute + # '_rep'." There is almost certainly no value in such tests. The + # presumption seems to be that someone could create a new class by + # inheriting some of the Matrix classes and not the full set that is used + # by the standard Matrix class but if anyone tried that it would fail in + # many ways. + if not hasattr(M, '_rep'): + return None + + rep = M._rep + K = rep.domain + + if K.is_ZZ: + return rep + elif K.is_QQ: + try: + return rep.convert_to(ZZ) + except CoercionFailed: + return rep + else: + if not all(e.is_Rational for e in M): + return None + try: + return rep.convert_to(ZZ) + except CoercionFailed: + return rep.convert_to(QQ) + + +def _rref_dm(dM): + """Compute the reduced row echelon form of a DomainMatrix.""" + K = dM.domain + + if K.is_ZZ: + dM_rref, den, pivots = dM.rref_den(keep_domain=False) + dM_rref = dM_rref.to_field() / den + elif K.is_QQ: + dM_rref, pivots = dM.rref() + else: + assert False # pragma: no cover + + M_rref = dM_rref.to_Matrix() + + return M_rref, pivots + + +def _rref(M, iszerofunc=_iszero, simplify=False, pivots=True, + normalize_last=True): + """Return reduced row-echelon form of matrix and indices + of pivot vars. + + Parameters + ========== + + iszerofunc : Function + A function used for detecting whether an element can + act as a pivot. ``lambda x: x.is_zero`` is used by default. + + simplify : Function + A function used to simplify elements when looking for a pivot. + By default SymPy's ``simplify`` is used. + + pivots : True or False + If ``True``, a tuple containing the row-reduced matrix and a tuple + of pivot columns is returned. If ``False`` just the row-reduced + matrix is returned. + + normalize_last : True or False + If ``True``, no pivots are normalized to `1` until after all + entries above and below each pivot are zeroed. This means the row + reduction algorithm is fraction free until the very last step. + If ``False``, the naive row reduction procedure is used where + each pivot is normalized to be `1` before row operations are + used to zero above and below the pivot. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x + >>> m = Matrix([[1, 2], [x, 1 - 1/x]]) + >>> m.rref() + (Matrix([ + [1, 0], + [0, 1]]), (0, 1)) + >>> rref_matrix, rref_pivots = m.rref() + >>> rref_matrix + Matrix([ + [1, 0], + [0, 1]]) + >>> rref_pivots + (0, 1) + + ``iszerofunc`` can correct rounding errors in matrices with float + values. In the following example, calling ``rref()`` leads to + floating point errors, incorrectly row reducing the matrix. + ``iszerofunc= lambda x: abs(x) < 1e-9`` sets sufficiently small numbers + to zero, avoiding this error. + + >>> m = Matrix([[0.9, -0.1, -0.2, 0], [-0.8, 0.9, -0.4, 0], [-0.1, -0.8, 0.6, 0]]) + >>> m.rref() + (Matrix([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0]]), (0, 1, 2)) + >>> m.rref(iszerofunc=lambda x:abs(x)<1e-9) + (Matrix([ + [1, 0, -0.301369863013699, 0], + [0, 1, -0.712328767123288, 0], + [0, 0, 0, 0]]), (0, 1)) + + Notes + ===== + + The default value of ``normalize_last=True`` can provide significant + speedup to row reduction, especially on matrices with symbols. However, + if you depend on the form row reduction algorithm leaves entries + of the matrix, set ``normalize_last=False`` + """ + # Try to use DomainMatrix for ZZ or QQ + dM = _to_DM_ZZ_QQ(M) + + if dM is not None: + # Use DomainMatrix for ZZ or QQ + mat, pivot_cols = _rref_dm(dM) + else: + # Use the generic Matrix routine. + if isinstance(simplify, FunctionType): + simpfunc = simplify + else: + simpfunc = _simplify + + mat, pivot_cols, _ = _row_reduce(M, iszerofunc, simpfunc, + normalize_last, normalize=True, zero_above=True) + + if pivots: + return mat, pivot_cols + else: + return mat diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/repmatrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/repmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..57f32fae34786f68f579fad7de38c9e3cf43e131 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/repmatrix.py @@ -0,0 +1,1034 @@ +from collections import defaultdict + +from operator import index as index_ + +from sympy.core.expr import Expr +from sympy.core.kind import Kind, NumberKind, UndefinedKind +from sympy.core.numbers import Integer, Rational +from sympy.core.sympify import _sympify, SympifyError +from sympy.core.singleton import S +from sympy.polys.domains import ZZ, QQ, GF, EXRAW +from sympy.polys.matrices import DomainMatrix +from sympy.polys.matrices.exceptions import DMNonInvertibleMatrixError +from sympy.polys.polyerrors import CoercionFailed, NotInvertible +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import is_sequence +from sympy.utilities.misc import filldedent, as_int + +from .exceptions import ShapeError, NonSquareMatrixError, NonInvertibleMatrixError +from .matrixbase import classof, MatrixBase +from .kind import MatrixKind + + +class RepMatrix(MatrixBase): + """Matrix implementation based on DomainMatrix as an internal representation. + + The RepMatrix class is a superclass for Matrix, ImmutableMatrix, + SparseMatrix and ImmutableSparseMatrix which are the main usable matrix + classes in SymPy. Most methods on this class are simply forwarded to + DomainMatrix. + """ + + # + # MatrixBase is the common superclass for all of the usable explicit matrix + # classes in SymPy. The idea is that MatrixBase is an abstract class though + # and that subclasses will implement the lower-level methods. + # + # RepMatrix is a subclass of MatrixBase that uses DomainMatrix as an + # internal representation and delegates lower-level methods to + # DomainMatrix. All of SymPy's standard explicit matrix classes subclass + # RepMatrix and so use DomainMatrix internally. + # + # A RepMatrix uses an internal DomainMatrix with the domain set to ZZ, QQ + # or EXRAW. The EXRAW domain is equivalent to the previous implementation + # of Matrix that used Expr for the elements. The ZZ and QQ domains are used + # when applicable just because they are compatible with the previous + # implementation but are much more efficient. Other domains such as QQ[x] + # are not used because they differ from Expr in some way (e.g. automatic + # expansion of powers and products). + # + + _rep: DomainMatrix + + def __eq__(self, other): + # Skip sympify for mutable matrices... + if not isinstance(other, RepMatrix): + try: + other = _sympify(other) + except SympifyError: + return NotImplemented + if not isinstance(other, RepMatrix): + return NotImplemented + + return self._rep.unify_eq(other._rep) + + def to_DM(self, domain=None, **kwargs): + """Convert to a :class:`~.DomainMatrix`. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> M.to_DM() + DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) + + The :meth:`DomainMatrix.to_Matrix` method can be used to convert back: + + >>> M.to_DM().to_Matrix() == M + True + + The domain can be given explicitly or otherwise it will be chosen by + :func:`construct_domain`. Any keyword arguments (besides ``domain``) + are passed to :func:`construct_domain`: + + >>> from sympy import QQ, symbols + >>> x = symbols('x') + >>> M = Matrix([[x, 1], [1, x]]) + >>> M + Matrix([ + [x, 1], + [1, x]]) + >>> M.to_DM().domain + ZZ[x] + >>> M.to_DM(field=True).domain + ZZ(x) + >>> M.to_DM(domain=QQ[x]).domain + QQ[x] + + See Also + ======== + + DomainMatrix + DomainMatrix.to_Matrix + DomainMatrix.convert_to + DomainMatrix.choose_domain + construct_domain + """ + if domain is not None: + if kwargs: + raise TypeError("Options cannot be used with domain parameter") + return self._rep.convert_to(domain) + + rep = self._rep + dom = rep.domain + + # If the internal DomainMatrix is already ZZ or QQ then we can maybe + # bypass calling construct_domain or performing any conversions. Some + # kwargs might affect this though e.g. field=True (not sure if there + # are others). + if not kwargs: + if dom.is_ZZ: + return rep.copy() + elif dom.is_QQ: + # All elements might be integers + try: + return rep.convert_to(ZZ) + except CoercionFailed: + pass + return rep.copy() + + # Let construct_domain choose a domain + rep_dom = rep.choose_domain(**kwargs) + + # XXX: There should be an option to construct_domain to choose EXRAW + # instead of EX. At least converting to EX does not initially trigger + # EX.simplify which is what we want here but should probably be + # considered a bug in EX. Perhaps also this could be handled in + # DomainMatrix.choose_domain rather than here... + if rep_dom.domain.is_EX: + rep_dom = rep_dom.convert_to(EXRAW) + + return rep_dom + + @classmethod + def _unify_element_sympy(cls, rep, element): + domain = rep.domain + element = _sympify(element) + + if domain != EXRAW: + # The domain can only be ZZ, QQ or EXRAW + if element.is_Integer: + new_domain = domain + elif element.is_Rational: + new_domain = QQ + else: + new_domain = EXRAW + + # XXX: This converts the domain for all elements in the matrix + # which can be slow. This happens e.g. if __setitem__ changes one + # element to something that does not fit in the domain + if new_domain != domain: + rep = rep.convert_to(new_domain) + domain = new_domain + + if domain != EXRAW: + element = new_domain.from_sympy(element) + + if domain == EXRAW and not isinstance(element, Expr): + sympy_deprecation_warning( + """ + non-Expr objects in a Matrix is deprecated. Matrix represents + a mathematical matrix. To represent a container of non-numeric + entities, Use a list of lists, TableForm, NumPy array, or some + other data structure instead. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-non-expr-in-matrix", + stacklevel=4, + ) + + return rep, element + + @classmethod + def _dod_to_DomainMatrix(cls, rows, cols, dod, types): + + if not all(issubclass(typ, Expr) for typ in types): + sympy_deprecation_warning( + """ + non-Expr objects in a Matrix is deprecated. Matrix represents + a mathematical matrix. To represent a container of non-numeric + entities, Use a list of lists, TableForm, NumPy array, or some + other data structure instead. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-non-expr-in-matrix", + stacklevel=6, + ) + + rep = DomainMatrix(dod, (rows, cols), EXRAW) + + if all(issubclass(typ, Rational) for typ in types): + if all(issubclass(typ, Integer) for typ in types): + rep = rep.convert_to(ZZ) + else: + rep = rep.convert_to(QQ) + + return rep + + @classmethod + def _flat_list_to_DomainMatrix(cls, rows, cols, flat_list): + + elements_dod = defaultdict(dict) + for n, element in enumerate(flat_list): + if element != 0: + i, j = divmod(n, cols) + elements_dod[i][j] = element + + types = set(map(type, flat_list)) + + rep = cls._dod_to_DomainMatrix(rows, cols, elements_dod, types) + return rep + + @classmethod + def _smat_to_DomainMatrix(cls, rows, cols, smat): + + elements_dod = defaultdict(dict) + for (i, j), element in smat.items(): + if element != 0: + elements_dod[i][j] = element + + types = set(map(type, smat.values())) + + rep = cls._dod_to_DomainMatrix(rows, cols, elements_dod, types) + return rep + + def flat(self): + return self._rep.to_sympy().to_list_flat() + + def _eval_tolist(self): + return self._rep.to_sympy().to_list() + + def _eval_todok(self): + return self._rep.to_sympy().to_dok() + + @classmethod + def _eval_from_dok(cls, rows, cols, dok): + return cls._fromrep(cls._smat_to_DomainMatrix(rows, cols, dok)) + + def _eval_values(self): + return list(self._eval_iter_values()) + + def _eval_iter_values(self): + rep = self._rep + K = rep.domain + values = rep.iter_values() + if not K.is_EXRAW: + values = map(K.to_sympy, values) + return values + + def _eval_iter_items(self): + rep = self._rep + K = rep.domain + to_sympy = K.to_sympy + items = rep.iter_items() + if not K.is_EXRAW: + items = ((i, to_sympy(v)) for i, v in items) + return items + + def copy(self): + return self._fromrep(self._rep.copy()) + + @property + def kind(self) -> MatrixKind: + domain = self._rep.domain + element_kind: Kind + if domain in (ZZ, QQ): + element_kind = NumberKind + elif domain == EXRAW: + kinds = {e.kind for e in self.values()} + if len(kinds) == 1: + [element_kind] = kinds + else: + element_kind = UndefinedKind + else: # pragma: no cover + raise RuntimeError("Domain should only be ZZ, QQ or EXRAW") + return MatrixKind(element_kind) + + def _eval_has(self, *patterns): + # if the matrix has any zeros, see if S.Zero + # has the pattern. If _smat is full length, + # the matrix has no zeros. + zhas = False + dok = self.todok() + if len(dok) != self.rows*self.cols: + zhas = S.Zero.has(*patterns) + return zhas or any(value.has(*patterns) for value in dok.values()) + + def _eval_is_Identity(self): + if not all(self[i, i] == 1 for i in range(self.rows)): + return False + return len(self.todok()) == self.rows + + def _eval_is_symmetric(self, simpfunc): + diff = (self - self.T).applyfunc(simpfunc) + return len(diff.values()) == 0 + + def _eval_transpose(self): + """Returns the transposed SparseMatrix of this SparseMatrix. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> a = SparseMatrix(((1, 2), (3, 4))) + >>> a + Matrix([ + [1, 2], + [3, 4]]) + >>> a.T + Matrix([ + [1, 3], + [2, 4]]) + """ + return self._fromrep(self._rep.transpose()) + + def _eval_col_join(self, other): + return self._fromrep(self._rep.vstack(other._rep)) + + def _eval_row_join(self, other): + return self._fromrep(self._rep.hstack(other._rep)) + + def _eval_extract(self, rowsList, colsList): + return self._fromrep(self._rep.extract(rowsList, colsList)) + + def __getitem__(self, key): + return _getitem_RepMatrix(self, key) + + @classmethod + def _eval_zeros(cls, rows, cols): + rep = DomainMatrix.zeros((rows, cols), ZZ) + return cls._fromrep(rep) + + @classmethod + def _eval_eye(cls, rows, cols): + rep = DomainMatrix.eye((rows, cols), ZZ) + return cls._fromrep(rep) + + def _eval_add(self, other): + return classof(self, other)._fromrep(self._rep + other._rep) + + def _eval_matrix_mul(self, other): + return classof(self, other)._fromrep(self._rep * other._rep) + + def _eval_matrix_mul_elementwise(self, other): + selfrep, otherrep = self._rep.unify(other._rep) + newrep = selfrep.mul_elementwise(otherrep) + return classof(self, other)._fromrep(newrep) + + def _eval_scalar_mul(self, other): + rep, other = self._unify_element_sympy(self._rep, other) + return self._fromrep(rep.scalarmul(other)) + + def _eval_scalar_rmul(self, other): + rep, other = self._unify_element_sympy(self._rep, other) + return self._fromrep(rep.rscalarmul(other)) + + def _eval_Abs(self): + return self._fromrep(self._rep.applyfunc(abs)) + + def _eval_conjugate(self): + rep = self._rep + domain = rep.domain + if domain in (ZZ, QQ): + return self.copy() + else: + return self._fromrep(rep.applyfunc(lambda e: e.conjugate())) + + def equals(self, other, failing_expression=False): + """Applies ``equals`` to corresponding elements of the matrices, + trying to prove that the elements are equivalent, returning True + if they are, False if any pair is not, and None (or the first + failing expression if failing_expression is True) if it cannot + be decided if the expressions are equivalent or not. This is, in + general, an expensive operation. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.abc import x + >>> A = Matrix([x*(x - 1), 0]) + >>> B = Matrix([x**2 - x, 0]) + >>> A == B + False + >>> A.simplify() == B.simplify() + True + >>> A.equals(B) + True + >>> A.equals(2) + False + + See Also + ======== + sympy.core.expr.Expr.equals + """ + if self.shape != getattr(other, 'shape', None): + return False + + rv = True + for i in range(self.rows): + for j in range(self.cols): + ans = self[i, j].equals(other[i, j], failing_expression) + if ans is False: + return False + elif ans is not True and rv is True: + rv = ans + return rv + + def inv_mod(M, m): + r""" + Returns the inverse of the integer matrix ``M`` modulo ``m``. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix(2, 2, [1, 2, 3, 4]) + >>> A.inv_mod(5) + Matrix([ + [3, 1], + [4, 2]]) + >>> A.inv_mod(3) + Matrix([ + [1, 1], + [0, 1]]) + + """ + + if not M.is_square: + raise NonSquareMatrixError() + + try: + m = as_int(m) + except ValueError: + raise TypeError("inv_mod: modulus m must be an integer") + + K = GF(m, symmetric=False) + + try: + dM = M.to_DM(K) + except CoercionFailed: + raise ValueError("inv_mod: matrix entries must be integers") + + if K.is_Field: + try: + dMi = dM.inv() + except DMNonInvertibleMatrixError as exc: + msg = f'Matrix is not invertible (mod {m})' + raise NonInvertibleMatrixError(msg) from exc + else: + dMadj, det = dM.adj_det() + try: + detinv = 1 / det + except NotInvertible: + msg = f'Matrix is not invertible (mod {m})' + raise NonInvertibleMatrixError(msg) + dMi = dMadj * detinv + + return dMi.to_Matrix() + + def lll(self, delta=0.75): + """LLL-reduced basis for the rowspace of a matrix of integers. + + Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm. + + The implementation is provided by :class:`~DomainMatrix`. See + :meth:`~DomainMatrix.lll` for more details. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 0, 0, 0, -20160], + ... [0, 1, 0, 0, 33768], + ... [0, 0, 1, 0, 39578], + ... [0, 0, 0, 1, 47757]]) + >>> M.lll() + Matrix([ + [ 10, -3, -2, 8, -4], + [ 3, -9, 8, 1, -11], + [ -3, 13, -9, -3, -9], + [-12, -7, -11, 9, -1]]) + + See Also + ======== + + lll_transform + sympy.polys.matrices.domainmatrix.DomainMatrix.lll + """ + delta = QQ.from_sympy(_sympify(delta)) + dM = self._rep.convert_to(ZZ) + basis = dM.lll(delta=delta) + return self._fromrep(basis) + + def lll_transform(self, delta=0.75): + """LLL-reduced basis and transformation matrix. + + Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm. + + The implementation is provided by :class:`~DomainMatrix`. See + :meth:`~DomainMatrix.lll_transform` for more details. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 0, 0, 0, -20160], + ... [0, 1, 0, 0, 33768], + ... [0, 0, 1, 0, 39578], + ... [0, 0, 0, 1, 47757]]) + >>> B, T = M.lll_transform() + >>> B + Matrix([ + [ 10, -3, -2, 8, -4], + [ 3, -9, 8, 1, -11], + [ -3, 13, -9, -3, -9], + [-12, -7, -11, 9, -1]]) + >>> T + Matrix([ + [ 10, -3, -2, 8], + [ 3, -9, 8, 1], + [ -3, 13, -9, -3], + [-12, -7, -11, 9]]) + + The transformation matrix maps the original basis to the LLL-reduced + basis: + + >>> T * M == B + True + + See Also + ======== + + lll + sympy.polys.matrices.domainmatrix.DomainMatrix.lll_transform + """ + delta = QQ.from_sympy(_sympify(delta)) + dM = self._rep.convert_to(ZZ) + basis, transform = dM.lll_transform(delta=delta) + B = self._fromrep(basis) + T = self._fromrep(transform) + return B, T + + +class MutableRepMatrix(RepMatrix): + """Mutable matrix based on DomainMatrix as the internal representation""" + + # + # MutableRepMatrix is a subclass of RepMatrix that adds/overrides methods + # to make the instances mutable. MutableRepMatrix is a superclass for both + # MutableDenseMatrix and MutableSparseMatrix. + # + + is_zero = False + + def __new__(cls, *args, **kwargs): + return cls._new(*args, **kwargs) + + @classmethod + def _new(cls, *args, copy=True, **kwargs): + if copy is False: + # The input was rows, cols, [list]. + # It should be used directly without creating a copy. + if len(args) != 3: + raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]") + rows, cols, flat_list = args + else: + rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) + flat_list = list(flat_list) # create a shallow copy + + rep = cls._flat_list_to_DomainMatrix(rows, cols, flat_list) + + return cls._fromrep(rep) + + @classmethod + def _fromrep(cls, rep): + obj = super().__new__(cls) + obj.rows, obj.cols = rep.shape + obj._rep = rep + return obj + + def copy(self): + return self._fromrep(self._rep.copy()) + + def as_mutable(self): + return self.copy() + + def __setitem__(self, key, value): + """ + + Examples + ======== + + >>> from sympy import Matrix, I, zeros, ones + >>> m = Matrix(((1, 2+I), (3, 4))) + >>> m + Matrix([ + [1, 2 + I], + [3, 4]]) + >>> m[1, 0] = 9 + >>> m + Matrix([ + [1, 2 + I], + [9, 4]]) + >>> m[1, 0] = [[0, 1]] + + To replace row r you assign to position r*m where m + is the number of columns: + + >>> M = zeros(4) + >>> m = M.cols + >>> M[3*m] = ones(1, m)*2; M + Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 2, 2, 2]]) + + And to replace column c you can assign to position c: + + >>> M[2] = ones(m, 1)*4; M + Matrix([ + [0, 0, 4, 0], + [0, 0, 4, 0], + [0, 0, 4, 0], + [2, 2, 4, 2]]) + """ + rv = self._setitem(key, value) + if rv is not None: + i, j, value = rv + self._rep, value = self._unify_element_sympy(self._rep, value) + self._rep.rep.setitem(i, j, value) + + def _eval_col_del(self, col): + self._rep = DomainMatrix.hstack(self._rep[:,:col], self._rep[:,col+1:]) + self.cols -= 1 + + def _eval_row_del(self, row): + self._rep = DomainMatrix.vstack(self._rep[:row,:], self._rep[row+1:, :]) + self.rows -= 1 + + def _eval_col_insert(self, col, other): + other = self._new(other) + return self.hstack(self[:,:col], other, self[:,col:]) + + def _eval_row_insert(self, row, other): + other = self._new(other) + return self.vstack(self[:row,:], other, self[row:,:]) + + def col_op(self, j, f): + """In-place operation on col j using two-arg functor whose args are + interpreted as (self[i, j], i). + + Examples + ======== + + >>> from sympy import eye + >>> M = eye(3) + >>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M + Matrix([ + [1, 2, 0], + [0, 1, 0], + [0, 0, 1]]) + + See Also + ======== + col + row_op + """ + for i in range(self.rows): + self[i, j] = f(self[i, j], i) + + def col_swap(self, i, j): + """Swap the two given columns of the matrix in-place. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 0], [1, 0]]) + >>> M + Matrix([ + [1, 0], + [1, 0]]) + >>> M.col_swap(0, 1) + >>> M + Matrix([ + [0, 1], + [0, 1]]) + + See Also + ======== + + col + row_swap + """ + for k in range(0, self.rows): + self[k, i], self[k, j] = self[k, j], self[k, i] + + def row_op(self, i, f): + """In-place operation on row ``i`` using two-arg functor whose args are + interpreted as ``(self[i, j], j)``. + + Examples + ======== + + >>> from sympy import eye + >>> M = eye(3) + >>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M + Matrix([ + [1, 0, 0], + [2, 1, 0], + [0, 0, 1]]) + + See Also + ======== + row + zip_row_op + col_op + + """ + for j in range(self.cols): + self[i, j] = f(self[i, j], j) + + #The next three methods give direct support for the most common row operations inplace. + def row_mult(self,i,factor): + """Multiply the given row by the given factor in-place. + + Examples + ======== + + >>> from sympy import eye + >>> M = eye(3) + >>> M.row_mult(1,7); M + Matrix([ + [1, 0, 0], + [0, 7, 0], + [0, 0, 1]]) + + """ + for j in range(self.cols): + self[i,j] *= factor + + def row_add(self,s,t,k): + """Add k times row s (source) to row t (target) in place. + + Examples + ======== + + >>> from sympy import eye + >>> M = eye(3) + >>> M.row_add(0, 2,3); M + Matrix([ + [1, 0, 0], + [0, 1, 0], + [3, 0, 1]]) + """ + + for j in range(self.cols): + self[t,j] += k*self[s,j] + + def row_swap(self, i, j): + """Swap the two given rows of the matrix in-place. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[0, 1], [1, 0]]) + >>> M + Matrix([ + [0, 1], + [1, 0]]) + >>> M.row_swap(0, 1) + >>> M + Matrix([ + [1, 0], + [0, 1]]) + + See Also + ======== + + row + col_swap + """ + for k in range(0, self.cols): + self[i, k], self[j, k] = self[j, k], self[i, k] + + def zip_row_op(self, i, k, f): + """In-place operation on row ``i`` using two-arg functor whose args are + interpreted as ``(self[i, j], self[k, j])``. + + Examples + ======== + + >>> from sympy import eye + >>> M = eye(3) + >>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M + Matrix([ + [1, 0, 0], + [2, 1, 0], + [0, 0, 1]]) + + See Also + ======== + row + row_op + col_op + + """ + for j in range(self.cols): + self[i, j] = f(self[i, j], self[k, j]) + + def copyin_list(self, key, value): + """Copy in elements from a list. + + Parameters + ========== + + key : slice + The section of this matrix to replace. + value : iterable + The iterable to copy values from. + + Examples + ======== + + >>> from sympy import eye + >>> I = eye(3) + >>> I[:2, 0] = [1, 2] # col + >>> I + Matrix([ + [1, 0, 0], + [2, 1, 0], + [0, 0, 1]]) + >>> I[1, :2] = [[3, 4]] + >>> I + Matrix([ + [1, 0, 0], + [3, 4, 0], + [0, 0, 1]]) + + See Also + ======== + + copyin_matrix + """ + if not is_sequence(value): + raise TypeError("`value` must be an ordered iterable, not %s." % type(value)) + return self.copyin_matrix(key, type(self)(value)) + + def copyin_matrix(self, key, value): + """Copy in values from a matrix into the given bounds. + + Parameters + ========== + + key : slice + The section of this matrix to replace. + value : Matrix + The matrix to copy values from. + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> M = Matrix([[0, 1], [2, 3], [4, 5]]) + >>> I = eye(3) + >>> I[:3, :2] = M + >>> I + Matrix([ + [0, 1, 0], + [2, 3, 0], + [4, 5, 1]]) + >>> I[0, 1] = M + >>> I + Matrix([ + [0, 0, 1], + [2, 2, 3], + [4, 4, 5]]) + + See Also + ======== + + copyin_list + """ + rlo, rhi, clo, chi = self.key2bounds(key) + shape = value.shape + dr, dc = rhi - rlo, chi - clo + if shape != (dr, dc): + raise ShapeError(filldedent("The Matrix `value` doesn't have the " + "same dimensions " + "as the in sub-Matrix given by `key`.")) + + for i in range(value.rows): + for j in range(value.cols): + self[i + rlo, j + clo] = value[i, j] + + def fill(self, value): + """Fill self with the given value. + + Notes + ===== + + Unless many values are going to be deleted (i.e. set to zero) + this will create a matrix that is slower than a dense matrix in + operations. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> M = SparseMatrix.zeros(3); M + Matrix([ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]) + >>> M.fill(1); M + Matrix([ + [1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + + See Also + ======== + + zeros + ones + """ + value = _sympify(value) + if not value: + self._rep = DomainMatrix.zeros(self.shape, EXRAW) + else: + elements_dod = {i: dict.fromkeys(range(self.cols), value) for i in range(self.rows)} + self._rep = DomainMatrix(elements_dod, self.shape, EXRAW) + + +def _getitem_RepMatrix(self, key): + """Return portion of self defined by key. If the key involves a slice + then a list will be returned (if key is a single slice) or a matrix + (if key was a tuple involving a slice). + + Examples + ======== + + >>> from sympy import Matrix, I + >>> m = Matrix([ + ... [1, 2 + I], + ... [3, 4 ]]) + + If the key is a tuple that does not involve a slice then that element + is returned: + + >>> m[1, 0] + 3 + + When a tuple key involves a slice, a matrix is returned. Here, the + first column is selected (all rows, column 0): + + >>> m[:, 0] + Matrix([ + [1], + [3]]) + + If the slice is not a tuple then it selects from the underlying + list of elements that are arranged in row order and a list is + returned if a slice is involved: + + >>> m[0] + 1 + >>> m[::2] + [1, 3] + """ + if isinstance(key, tuple): + i, j = key + try: + return self._rep.getitem_sympy(index_(i), index_(j)) + except (TypeError, IndexError): + if (isinstance(i, Expr) and not i.is_number) or (isinstance(j, Expr) and not j.is_number): + if ((j < 0) is True) or ((j >= self.shape[1]) is True) or\ + ((i < 0) is True) or ((i >= self.shape[0]) is True): + raise ValueError("index out of boundary") + from sympy.matrices.expressions.matexpr import MatrixElement + return MatrixElement(self, i, j) + + if isinstance(i, slice): + i = range(self.rows)[i] + elif is_sequence(i): + pass + else: + i = [i] + if isinstance(j, slice): + j = range(self.cols)[j] + elif is_sequence(j): + pass + else: + j = [j] + return self.extract(i, j) + + else: + # Index/slice like a flattened list + rows, cols = self.shape + + # Raise the appropriate exception: + if not rows * cols: + return [][key] + + rep = self._rep.rep + domain = rep.domain + is_slice = isinstance(key, slice) + + if is_slice: + values = [rep.getitem(*divmod(n, cols)) for n in range(rows * cols)[key]] + else: + values = [rep.getitem(*divmod(index_(key), cols))] + + if domain != EXRAW: + to_sympy = domain.to_sympy + values = [to_sympy(val) for val in values] + + if is_slice: + return values + else: + return values[0] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/solvers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..1fba990df80dcf46304ecb1412f5382f60948c51 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/solvers.py @@ -0,0 +1,942 @@ +from sympy.core.function import expand_mul +from sympy.core.symbol import Dummy, uniquely_named_symbol, symbols +from sympy.utilities.iterables import numbered_symbols + +from .exceptions import ShapeError, NonSquareMatrixError, NonInvertibleMatrixError +from .eigen import _fuzzy_positive_definite +from .utilities import _get_intermediate_simp, _iszero + + +def _diagonal_solve(M, rhs): + """Solves ``Ax = B`` efficiently, where A is a diagonal Matrix, + with non-zero diagonal entries. + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> A = eye(2)*2 + >>> B = Matrix([[1, 2], [3, 4]]) + >>> A.diagonal_solve(B) == B/2 + True + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.lower_triangular_solve + sympy.matrices.dense.DenseMatrix.upper_triangular_solve + gauss_jordan_solve + cholesky_solve + LDLsolve + LUsolve + QRsolve + pinv_solve + cramer_solve + """ + + if not M.is_diagonal(): + raise TypeError("Matrix should be diagonal") + if rhs.rows != M.rows: + raise TypeError("Size mismatch") + + return M._new( + rhs.rows, rhs.cols, lambda i, j: rhs[i, j] / M[i, i]) + + +def _lower_triangular_solve(M, rhs): + """Solves ``Ax = B``, where A is a lower triangular matrix. + + See Also + ======== + + upper_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LDLsolve + LUsolve + QRsolve + pinv_solve + cramer_solve + """ + + from .dense import MutableDenseMatrix + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if rhs.rows != M.rows: + raise ShapeError("Matrices size mismatch.") + if not M.is_lower: + raise ValueError("Matrix must be lower triangular.") + + dps = _get_intermediate_simp() + X = MutableDenseMatrix.zeros(M.rows, rhs.cols) + + for j in range(rhs.cols): + for i in range(M.rows): + if M[i, i] == 0: + raise TypeError("Matrix must be non-singular.") + + X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j] + for k in range(i))) / M[i, i]) + + return M._new(X) + +def _lower_triangular_solve_sparse(M, rhs): + """Solves ``Ax = B``, where A is a lower triangular matrix. + + See Also + ======== + + upper_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LDLsolve + LUsolve + QRsolve + pinv_solve + cramer_solve + """ + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if rhs.rows != M.rows: + raise ShapeError("Matrices size mismatch.") + if not M.is_lower: + raise ValueError("Matrix must be lower triangular.") + + dps = _get_intermediate_simp() + rows = [[] for i in range(M.rows)] + + for i, j, v in M.row_list(): + if i > j: + rows[i].append((j, v)) + + X = rhs.as_mutable() + + for j in range(rhs.cols): + for i in range(rhs.rows): + for u, v in rows[i]: + X[i, j] -= v*X[u, j] + + X[i, j] = dps(X[i, j] / M[i, i]) + + return M._new(X) + + +def _upper_triangular_solve(M, rhs): + """Solves ``Ax = B``, where A is an upper triangular matrix. + + See Also + ======== + + lower_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LDLsolve + LUsolve + QRsolve + pinv_solve + cramer_solve + """ + + from .dense import MutableDenseMatrix + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if rhs.rows != M.rows: + raise ShapeError("Matrix size mismatch.") + if not M.is_upper: + raise TypeError("Matrix is not upper triangular.") + + dps = _get_intermediate_simp() + X = MutableDenseMatrix.zeros(M.rows, rhs.cols) + + for j in range(rhs.cols): + for i in reversed(range(M.rows)): + if M[i, i] == 0: + raise ValueError("Matrix must be non-singular.") + + X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j] + for k in range(i + 1, M.rows))) / M[i, i]) + + return M._new(X) + +def _upper_triangular_solve_sparse(M, rhs): + """Solves ``Ax = B``, where A is an upper triangular matrix. + + See Also + ======== + + lower_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LDLsolve + LUsolve + QRsolve + pinv_solve + cramer_solve + """ + + if not M.is_square: + raise NonSquareMatrixError("Matrix must be square.") + if rhs.rows != M.rows: + raise ShapeError("Matrix size mismatch.") + if not M.is_upper: + raise TypeError("Matrix is not upper triangular.") + + dps = _get_intermediate_simp() + rows = [[] for i in range(M.rows)] + + for i, j, v in M.row_list(): + if i < j: + rows[i].append((j, v)) + + X = rhs.as_mutable() + + for j in range(rhs.cols): + for i in reversed(range(rhs.rows)): + for u, v in reversed(rows[i]): + X[i, j] -= v*X[u, j] + + X[i, j] = dps(X[i, j] / M[i, i]) + + return M._new(X) + + +def _cholesky_solve(M, rhs): + """Solves ``Ax = B`` using Cholesky decomposition, + for a general square non-singular matrix. + For a non-square matrix with rows > cols, + the least squares solution is returned. + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.lower_triangular_solve + sympy.matrices.dense.DenseMatrix.upper_triangular_solve + gauss_jordan_solve + diagonal_solve + LDLsolve + LUsolve + QRsolve + pinv_solve + cramer_solve + """ + + if M.rows < M.cols: + raise NotImplementedError( + 'Under-determined System. Try M.gauss_jordan_solve(rhs)') + + hermitian = True + reform = False + + if M.is_symmetric(): + hermitian = False + elif not M.is_hermitian: + reform = True + + if reform or _fuzzy_positive_definite(M) is False: + H = M.H + M = H.multiply(M) + rhs = H.multiply(rhs) + hermitian = not M.is_symmetric() + + L = M.cholesky(hermitian=hermitian) + Y = L.lower_triangular_solve(rhs) + + if hermitian: + return (L.H).upper_triangular_solve(Y) + else: + return (L.T).upper_triangular_solve(Y) + + +def _LDLsolve(M, rhs): + """Solves ``Ax = B`` using LDL decomposition, + for a general square and non-singular matrix. + + For a non-square matrix with rows > cols, + the least squares solution is returned. + + Examples + ======== + + >>> from sympy import Matrix, eye + >>> A = eye(2)*2 + >>> B = Matrix([[1, 2], [3, 4]]) + >>> A.LDLsolve(B) == B/2 + True + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.LDLdecomposition + sympy.matrices.dense.DenseMatrix.lower_triangular_solve + sympy.matrices.dense.DenseMatrix.upper_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LUsolve + QRsolve + pinv_solve + cramer_solve + """ + + if M.rows < M.cols: + raise NotImplementedError( + 'Under-determined System. Try M.gauss_jordan_solve(rhs)') + + hermitian = True + reform = False + + if M.is_symmetric(): + hermitian = False + elif not M.is_hermitian: + reform = True + + if reform or _fuzzy_positive_definite(M) is False: + H = M.H + M = H.multiply(M) + rhs = H.multiply(rhs) + hermitian = not M.is_symmetric() + + L, D = M.LDLdecomposition(hermitian=hermitian) + Y = L.lower_triangular_solve(rhs) + Z = D.diagonal_solve(Y) + + if hermitian: + return (L.H).upper_triangular_solve(Z) + else: + return (L.T).upper_triangular_solve(Z) + + +def _LUsolve(M, rhs, iszerofunc=_iszero): + """Solve the linear system ``Ax = rhs`` for ``x`` where ``A = M``. + + This is for symbolic matrices, for real or complex ones use + mpmath.lu_solve or mpmath.qr_solve. + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.lower_triangular_solve + sympy.matrices.dense.DenseMatrix.upper_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LDLsolve + QRsolve + pinv_solve + LUdecomposition + cramer_solve + """ + + if rhs.rows != M.rows: + raise ShapeError( + "``M`` and ``rhs`` must have the same number of rows.") + + m = M.rows + n = M.cols + + if m < n: + raise NotImplementedError("Underdetermined systems not supported.") + + try: + A, perm = M.LUdecomposition_Simple( + iszerofunc=iszerofunc, rankcheck=True) + except ValueError: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") + + dps = _get_intermediate_simp() + b = rhs.permute_rows(perm).as_mutable() + + # forward substitution, all diag entries are scaled to 1 + for i in range(m): + for j in range(min(i, n)): + scale = A[i, j] + b.zip_row_op(i, j, lambda x, y: dps(x - scale * y)) + + # consistency check for overdetermined systems + if m > n: + for i in range(n, m): + for j in range(b.cols): + if not iszerofunc(b[i, j]): + raise ValueError("The system is inconsistent.") + + b = b[0:n, :] # truncate zero rows if consistent + + # backward substitution + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + scale = A[i, j] + b.zip_row_op(i, j, lambda x, y: dps(x - scale * y)) + + scale = A[i, i] + b.row_op(i, lambda x, _: dps(scale**-1 * x)) + + return rhs.__class__(b) + + +def _QRsolve(M, b): + """Solve the linear system ``Ax = b``. + + ``M`` is the matrix ``A``, the method argument is the vector + ``b``. The method returns the solution vector ``x``. If ``b`` is a + matrix, the system is solved for each column of ``b`` and the + return value is a matrix of the same shape as ``b``. + + This method is slower (approximately by a factor of 2) but + more stable for floating-point arithmetic than the LUsolve method. + However, LUsolve usually uses an exact arithmetic, so you do not need + to use QRsolve. + + This is mainly for educational purposes and symbolic matrices, for real + (or complex) matrices use mpmath.qr_solve. + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.lower_triangular_solve + sympy.matrices.dense.DenseMatrix.upper_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LDLsolve + LUsolve + pinv_solve + QRdecomposition + cramer_solve + """ + + dps = _get_intermediate_simp(expand_mul, expand_mul) + Q, R = M.QRdecomposition() + y = Q.T * b + + # back substitution to solve R*x = y: + # We build up the result "backwards" in the vector 'x' and reverse it + # only in the end. + x = [] + n = R.rows + + for j in range(n - 1, -1, -1): + tmp = y[j, :] + + for k in range(j + 1, n): + tmp -= R[j, k] * x[n - 1 - k] + + tmp = dps(tmp) + + x.append(tmp / R[j, j]) + + return M.vstack(*x[::-1]) + + +def _gauss_jordan_solve(M, B, freevar=False): + """ + Solves ``Ax = B`` using Gauss Jordan elimination. + + There may be zero, one, or infinite solutions. If one solution + exists, it will be returned. If infinite solutions exist, it will + be returned parametrically. If no solutions exist, It will throw + ValueError. + + Parameters + ========== + + B : Matrix + The right hand side of the equation to be solved for. Must have + the same number of rows as matrix A. + + freevar : boolean, optional + Flag, when set to `True` will return the indices of the free + variables in the solutions (column Matrix), for a system that is + undetermined (e.g. A has more columns than rows), for which + infinite solutions are possible, in terms of arbitrary + values of free variables. Default `False`. + + Returns + ======= + + x : Matrix + The matrix that will satisfy ``Ax = B``. Will have as many rows as + matrix A has columns, and as many columns as matrix B. + + params : Matrix + If the system is underdetermined (e.g. A has more columns than + rows), infinite solutions are possible, in terms of arbitrary + parameters. These arbitrary parameters are returned as params + Matrix. + + free_var_index : List, optional + If the system is underdetermined (e.g. A has more columns than + rows), infinite solutions are possible, in terms of arbitrary + values of free variables. Then the indices of the free variables + in the solutions (column Matrix) are returned by free_var_index, + if the flag `freevar` is set to `True`. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]]) + >>> B = Matrix([7, 12, 4]) + >>> sol, params = A.gauss_jordan_solve(B) + >>> sol + Matrix([ + [-2*tau0 - 3*tau1 + 2], + [ tau0], + [ 2*tau1 + 5], + [ tau1]]) + >>> params + Matrix([ + [tau0], + [tau1]]) + >>> taus_zeroes = { tau:0 for tau in params } + >>> sol_unique = sol.xreplace(taus_zeroes) + >>> sol_unique + Matrix([ + [2], + [0], + [5], + [0]]) + + + >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) + >>> B = Matrix([3, 6, 9]) + >>> sol, params = A.gauss_jordan_solve(B) + >>> sol + Matrix([ + [-1], + [ 2], + [ 0]]) + >>> params + Matrix(0, 1, []) + + >>> A = Matrix([[2, -7], [-1, 4]]) + >>> B = Matrix([[-21, 3], [12, -2]]) + >>> sol, params = A.gauss_jordan_solve(B) + >>> sol + Matrix([ + [0, -2], + [3, -1]]) + >>> params + Matrix(0, 2, []) + + + >>> from sympy import Matrix + >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]]) + >>> B = Matrix([7, 12, 4]) + >>> sol, params, freevars = A.gauss_jordan_solve(B, freevar=True) + >>> sol + Matrix([ + [-2*tau0 - 3*tau1 + 2], + [ tau0], + [ 2*tau1 + 5], + [ tau1]]) + >>> params + Matrix([ + [tau0], + [tau1]]) + >>> freevars + [1, 3] + + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.lower_triangular_solve + sympy.matrices.dense.DenseMatrix.upper_triangular_solve + cholesky_solve + diagonal_solve + LDLsolve + LUsolve + QRsolve + pinv + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gaussian_elimination + + """ + + from sympy.matrices import Matrix, zeros + + cls = M.__class__ + aug = M.hstack(M.copy(), B.copy()) + B_cols = B.cols + row, col = aug[:, :-B_cols].shape + + # solve by reduced row echelon form + A, pivots = aug.rref(simplify=True) + A, v = A[:, :-B_cols], A[:, -B_cols:] + pivots = list(filter(lambda p: p < col, pivots)) + rank = len(pivots) + + # Get index of free symbols (free parameters) + # non-pivots columns are free variables + free_var_index = [c for c in range(A.cols) if c not in pivots] + + # Bring to block form + permutation = Matrix(pivots + free_var_index).T + + # check for existence of solutions + # rank of aug Matrix should be equal to rank of coefficient matrix + if not v[rank:, :].is_zero_matrix: + raise ValueError("Linear system has no solution") + + # Free parameters + # what are current unnumbered free symbol names? + name = uniquely_named_symbol('tau', [aug], + compare=lambda i: str(i).rstrip('1234567890'), + modify=lambda s: '_' + s).name + gen = numbered_symbols(name) + tau = Matrix([next(gen) for k in range((col - rank)*B_cols)]).reshape( + col - rank, B_cols) + + # Full parametric solution + V = A[:rank, free_var_index] + vt = v[:rank, :] + free_sol = tau.vstack(vt - V * tau, tau) + + # Undo permutation + sol = zeros(col, B_cols) + + for k in range(col): + sol[permutation[k], :] = free_sol[k,:] + + sol, tau = cls(sol), cls(tau) + + if freevar: + return sol, tau, free_var_index + else: + return sol, tau + + +def _pinv_solve(M, B, arbitrary_matrix=None): + """Solve ``Ax = B`` using the Moore-Penrose pseudoinverse. + + There may be zero, one, or infinite solutions. If one solution + exists, it will be returned. If infinite solutions exist, one will + be returned based on the value of arbitrary_matrix. If no solutions + exist, the least-squares solution is returned. + + Parameters + ========== + + B : Matrix + The right hand side of the equation to be solved for. Must have + the same number of rows as matrix A. + arbitrary_matrix : Matrix + If the system is underdetermined (e.g. A has more columns than + rows), infinite solutions are possible, in terms of an arbitrary + matrix. This parameter may be set to a specific matrix to use + for that purpose; if so, it must be the same shape as x, with as + many rows as matrix A has columns, and as many columns as matrix + B. If left as None, an appropriate matrix containing dummy + symbols in the form of ``wn_m`` will be used, with n and m being + row and column position of each symbol. + + Returns + ======= + + x : Matrix + The matrix that will satisfy ``Ax = B``. Will have as many rows as + matrix A has columns, and as many columns as matrix B. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) + >>> B = Matrix([7, 8]) + >>> A.pinv_solve(B) + Matrix([ + [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18], + [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9], + [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]]) + >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0])) + Matrix([ + [-55/18], + [ 1/9], + [ 59/18]]) + + See Also + ======== + + sympy.matrices.dense.DenseMatrix.lower_triangular_solve + sympy.matrices.dense.DenseMatrix.upper_triangular_solve + gauss_jordan_solve + cholesky_solve + diagonal_solve + LDLsolve + LUsolve + QRsolve + pinv + + Notes + ===== + + This may return either exact solutions or least squares solutions. + To determine which, check ``A * A.pinv() * B == B``. It will be + True if exact solutions exist, and False if only a least-squares + solution exists. Be aware that the left hand side of that equation + may need to be simplified to correctly compare to the right hand + side. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system + + """ + + from sympy.matrices import eye + + A = M + A_pinv = M.pinv() + + if arbitrary_matrix is None: + rows, cols = A.cols, B.cols + w = symbols('w:{}_:{}'.format(rows, cols), cls=Dummy) + arbitrary_matrix = M.__class__(cols, rows, w).T + + return A_pinv.multiply(B) + (eye(A.cols) - + A_pinv.multiply(A)).multiply(arbitrary_matrix) + + +def _cramer_solve(M, rhs, det_method="laplace"): + """Solves system of linear equations using Cramer's rule. + + This method is relatively inefficient compared to other methods. + However it only uses a single division, assuming a division-free determinant + method is provided. This is helpful to minimize the chance of divide-by-zero + cases in symbolic solutions to linear systems. + + Parameters + ========== + M : Matrix + The matrix representing the left hand side of the equation. + rhs : Matrix + The matrix representing the right hand side of the equation. + det_method : str or callable + The method to use to calculate the determinant of the matrix. + The default is ``'laplace'``. If a callable is passed, it should take a + single argument, the matrix, and return the determinant of the matrix. + + Returns + ======= + x : Matrix + The matrix that will satisfy ``Ax = B``. Will have as many rows as + matrix A has columns, and as many columns as matrix B. + + Examples + ======== + + >>> from sympy import Matrix + >>> A = Matrix([[0, -6, 1], [0, -6, -1], [-5, -2, 3]]) + >>> B = Matrix([[-30, -9], [-18, -27], [-26, 46]]) + >>> x = A.cramer_solve(B) + >>> x + Matrix([ + [ 0, -5], + [ 4, 3], + [-6, 9]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Cramer%27s_rule#Explicit_formulas_for_small_systems + + """ + from .dense import zeros + + def entry(i, j): + return rhs[i, sol] if j == col else M[i, j] + + if det_method == "bird": + from .determinant import _det_bird + det = _det_bird + elif det_method == "laplace": + from .determinant import _det_laplace + det = _det_laplace + elif isinstance(det_method, str): + det = lambda matrix: matrix.det(method=det_method) + else: + det = det_method + det_M = det(M) + x = zeros(*rhs.shape) + for sol in range(rhs.shape[1]): + for col in range(rhs.shape[0]): + x[col, sol] = det(M.__class__(*M.shape, entry)) / det_M + return M.__class__(x) + + +def _solve(M, rhs, method='GJ'): + """Solves linear equation where the unique solution exists. + + Parameters + ========== + + rhs : Matrix + Vector representing the right hand side of the linear equation. + + method : string, optional + If set to ``'GJ'`` or ``'GE'``, the Gauss-Jordan elimination will be + used, which is implemented in the routine ``gauss_jordan_solve``. + + If set to ``'LU'``, ``LUsolve`` routine will be used. + + If set to ``'QR'``, ``QRsolve`` routine will be used. + + If set to ``'PINV'``, ``pinv_solve`` routine will be used. + + If set to ``'CRAMER'``, ``cramer_solve`` routine will be used. + + It also supports the methods available for special linear systems + + For positive definite systems: + + If set to ``'CH'``, ``cholesky_solve`` routine will be used. + + If set to ``'LDL'``, ``LDLsolve`` routine will be used. + + To use a different method and to compute the solution via the + inverse, use a method defined in the .inv() docstring. + + Returns + ======= + + solutions : Matrix + Vector representing the solution. + + Raises + ====== + + ValueError + If there is not a unique solution then a ``ValueError`` will be + raised. + + If ``M`` is not square, a ``ValueError`` and a different routine + for solving the system will be suggested. + """ + + if method in ('GJ', 'GE'): + try: + soln, param = M.gauss_jordan_solve(rhs) + + if param: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible. " + "Try ``M.gauss_jordan_solve(rhs)`` to obtain a parametric solution.") + + except ValueError: + raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") + + return soln + + elif method == 'LU': + return M.LUsolve(rhs) + elif method == 'CH': + return M.cholesky_solve(rhs) + elif method == 'QR': + return M.QRsolve(rhs) + elif method == 'LDL': + return M.LDLsolve(rhs) + elif method == 'PINV': + return M.pinv_solve(rhs) + elif method == 'CRAMER': + return M.cramer_solve(rhs) + else: + return M.inv(method=method).multiply(rhs) + + +def _solve_least_squares(M, rhs, method='CH'): + """Return the least-square fit to the data. + + Parameters + ========== + + rhs : Matrix + Vector representing the right hand side of the linear equation. + + method : string or boolean, optional + If set to ``'CH'``, ``cholesky_solve`` routine will be used. + + If set to ``'LDL'``, ``LDLsolve`` routine will be used. + + If set to ``'QR'``, ``QRsolve`` routine will be used. + + If set to ``'PINV'``, ``pinv_solve`` routine will be used. + + Otherwise, the conjugate of ``M`` will be used to create a system + of equations that is passed to ``solve`` along with the hint + defined by ``method``. + + Returns + ======= + + solutions : Matrix + Vector representing the solution. + + Examples + ======== + + >>> from sympy import Matrix, ones + >>> A = Matrix([1, 2, 3]) + >>> B = Matrix([2, 3, 4]) + >>> S = Matrix(A.row_join(B)) + >>> S + Matrix([ + [1, 2], + [2, 3], + [3, 4]]) + + If each line of S represent coefficients of Ax + By + and x and y are [2, 3] then S*xy is: + + >>> r = S*Matrix([2, 3]); r + Matrix([ + [ 8], + [13], + [18]]) + + But let's add 1 to the middle value and then solve for the + least-squares value of xy: + + >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy + Matrix([ + [ 5/3], + [10/3]]) + + The error is given by S*xy - r: + + >>> S*xy - r + Matrix([ + [1/3], + [1/3], + [1/3]]) + >>> _.norm().n(2) + 0.58 + + If a different xy is used, the norm will be higher: + + >>> xy += ones(2, 1)/10 + >>> (S*xy - r).norm().n(2) + 1.5 + + """ + + if method == 'CH': + return M.cholesky_solve(rhs) + elif method == 'QR': + return M.QRsolve(rhs) + elif method == 'LDL': + return M.LDLsolve(rhs) + elif method == 'PINV': + return M.pinv_solve(rhs) + else: + t = M.H + return (t * M).solve(t * rhs, method=method) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/sparse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..95a7b3ca0ac29cf4409ec1eeecd059f9643e9bbc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/sparse.py @@ -0,0 +1,473 @@ +from collections.abc import Callable + +from sympy.core.containers import Dict +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import is_sequence +from sympy.utilities.misc import as_int + +from .matrixbase import MatrixBase +from .repmatrix import MutableRepMatrix, RepMatrix + +from .utilities import _iszero + +from .decompositions import ( + _liupc, _row_structure_symbolic_cholesky, _cholesky_sparse, + _LDLdecomposition_sparse) + +from .solvers import ( + _lower_triangular_solve_sparse, _upper_triangular_solve_sparse) + + +class SparseRepMatrix(RepMatrix): + """ + A sparse matrix (a matrix with a large number of zero elements). + + Examples + ======== + + >>> from sympy import SparseMatrix, ones + >>> SparseMatrix(2, 2, range(4)) + Matrix([ + [0, 1], + [2, 3]]) + >>> SparseMatrix(2, 2, {(1, 1): 2}) + Matrix([ + [0, 0], + [0, 2]]) + + A SparseMatrix can be instantiated from a ragged list of lists: + + >>> SparseMatrix([[1, 2, 3], [1, 2], [1]]) + Matrix([ + [1, 2, 3], + [1, 2, 0], + [1, 0, 0]]) + + For safety, one may include the expected size and then an error + will be raised if the indices of any element are out of range or + (for a flat list) if the total number of elements does not match + the expected shape: + + >>> SparseMatrix(2, 2, [1, 2]) + Traceback (most recent call last): + ... + ValueError: List length (2) != rows*columns (4) + + Here, an error is not raised because the list is not flat and no + element is out of range: + + >>> SparseMatrix(2, 2, [[1, 2]]) + Matrix([ + [1, 2], + [0, 0]]) + + But adding another element to the first (and only) row will cause + an error to be raised: + + >>> SparseMatrix(2, 2, [[1, 2, 3]]) + Traceback (most recent call last): + ... + ValueError: The location (0, 2) is out of designated range: (1, 1) + + To autosize the matrix, pass None for rows: + + >>> SparseMatrix(None, [[1, 2, 3]]) + Matrix([[1, 2, 3]]) + >>> SparseMatrix(None, {(1, 1): 1, (3, 3): 3}) + Matrix([ + [0, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 3]]) + + Values that are themselves a Matrix are automatically expanded: + + >>> SparseMatrix(4, 4, {(1, 1): ones(2)}) + Matrix([ + [0, 0, 0, 0], + [0, 1, 1, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]]) + + A ValueError is raised if the expanding matrix tries to overwrite + a different element already present: + + >>> SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2}) + Traceback (most recent call last): + ... + ValueError: collision at (1, 1) + + See Also + ======== + DenseMatrix + MutableSparseMatrix + ImmutableSparseMatrix + """ + + @classmethod + def _handle_creation_inputs(cls, *args, **kwargs): + if len(args) == 1 and isinstance(args[0], MatrixBase): + rows = args[0].rows + cols = args[0].cols + smat = args[0].todok() + return rows, cols, smat + + smat = {} + # autosizing + if len(args) == 2 and args[0] is None: + args = [None, None, args[1]] + + if len(args) == 3: + r, c = args[:2] + if r is c is None: + rows = cols = None + elif None in (r, c): + raise ValueError( + 'Pass rows=None and no cols for autosizing.') + else: + rows, cols = as_int(args[0]), as_int(args[1]) + + if isinstance(args[2], Callable): + op = args[2] + + if None in (rows, cols): + raise ValueError( + "{} and {} must be integers for this " + "specification.".format(rows, cols)) + + row_indices = [cls._sympify(i) for i in range(rows)] + col_indices = [cls._sympify(j) for j in range(cols)] + + for i in row_indices: + for j in col_indices: + value = cls._sympify(op(i, j)) + if value != cls.zero: + smat[i, j] = value + + return rows, cols, smat + + elif isinstance(args[2], (dict, Dict)): + def update(i, j, v): + # update smat and make sure there are no collisions + if v: + if (i, j) in smat and v != smat[i, j]: + raise ValueError( + "There is a collision at {} for {} and {}." + .format((i, j), v, smat[i, j]) + ) + smat[i, j] = v + + # manual copy, copy.deepcopy() doesn't work + for (r, c), v in args[2].items(): + if isinstance(v, MatrixBase): + for (i, j), vv in v.todok().items(): + update(r + i, c + j, vv) + elif isinstance(v, (list, tuple)): + _, _, smat = cls._handle_creation_inputs(v, **kwargs) + for i, j in smat: + update(r + i, c + j, smat[i, j]) + else: + v = cls._sympify(v) + update(r, c, cls._sympify(v)) + + elif is_sequence(args[2]): + flat = not any(is_sequence(i) for i in args[2]) + if not flat: + _, _, smat = \ + cls._handle_creation_inputs(args[2], **kwargs) + else: + flat_list = args[2] + if len(flat_list) != rows * cols: + raise ValueError( + "The length of the flat list ({}) does not " + "match the specified size ({} * {})." + .format(len(flat_list), rows, cols) + ) + + for i in range(rows): + for j in range(cols): + value = flat_list[i*cols + j] + value = cls._sympify(value) + if value != cls.zero: + smat[i, j] = value + + if rows is None: # autosizing + keys = smat.keys() + rows = max(r for r, _ in keys) + 1 if keys else 0 + cols = max(c for _, c in keys) + 1 if keys else 0 + + else: + for i, j in smat.keys(): + if i and i >= rows or j and j >= cols: + raise ValueError( + "The location {} is out of the designated range" + "[{}, {}]x[{}, {}]" + .format((i, j), 0, rows - 1, 0, cols - 1) + ) + + return rows, cols, smat + + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + # list of values or lists + v = args[0] + c = 0 + for i, row in enumerate(v): + if not isinstance(row, (list, tuple)): + row = [row] + for j, vv in enumerate(row): + if vv != cls.zero: + smat[i, j] = cls._sympify(vv) + c = max(c, len(row)) + rows = len(v) if c else 0 + cols = c + return rows, cols, smat + + else: + # handle full matrix forms with _handle_creation_inputs + rows, cols, mat = super()._handle_creation_inputs(*args) + for i in range(rows): + for j in range(cols): + value = mat[cols*i + j] + if value != cls.zero: + smat[i, j] = value + + return rows, cols, smat + + @property + def _smat(self): + + sympy_deprecation_warning( + """ + The private _smat attribute of SparseMatrix is deprecated. Use the + .todok() method instead. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-private-matrix-attributes" + ) + + return self.todok() + + def _eval_inverse(self, **kwargs): + return self.inv(method=kwargs.get('method', 'LDL'), + iszerofunc=kwargs.get('iszerofunc', _iszero), + try_block_diag=kwargs.get('try_block_diag', False)) + + def applyfunc(self, f): + """Apply a function to each element of the matrix. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> m = SparseMatrix(2, 2, lambda i, j: i*2+j) + >>> m + Matrix([ + [0, 1], + [2, 3]]) + >>> m.applyfunc(lambda i: 2*i) + Matrix([ + [0, 2], + [4, 6]]) + + """ + if not callable(f): + raise TypeError("`f` must be callable.") + + # XXX: This only applies the function to the nonzero elements of the + # matrix so is inconsistent with DenseMatrix.applyfunc e.g. + # zeros(2, 2).applyfunc(lambda x: x + 1) + dok = {} + for k, v in self.todok().items(): + fv = f(v) + if fv != 0: + dok[k] = fv + + return self._new(self.rows, self.cols, dok) + + def as_immutable(self): + """Returns an Immutable version of this Matrix.""" + from .immutable import ImmutableSparseMatrix + return ImmutableSparseMatrix(self) + + def as_mutable(self): + """Returns a mutable version of this matrix. + + Examples + ======== + + >>> from sympy import ImmutableMatrix + >>> X = ImmutableMatrix([[1, 2], [3, 4]]) + >>> Y = X.as_mutable() + >>> Y[1, 1] = 5 # Can set values in Y + >>> Y + Matrix([ + [1, 2], + [3, 5]]) + """ + return MutableSparseMatrix(self) + + def col_list(self): + """Returns a column-sorted list of non-zero elements of the matrix. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> a=SparseMatrix(((1, 2), (3, 4))) + >>> a + Matrix([ + [1, 2], + [3, 4]]) + >>> a.CL + [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)] + + See Also + ======== + + sympy.matrices.sparse.SparseMatrix.row_list + """ + return [tuple(k + (self[k],)) for k in sorted(self.todok().keys(), key=lambda k: list(reversed(k)))] + + def nnz(self): + """Returns the number of non-zero elements in Matrix.""" + return len(self.todok()) + + def row_list(self): + """Returns a row-sorted list of non-zero elements of the matrix. + + Examples + ======== + + >>> from sympy import SparseMatrix + >>> a = SparseMatrix(((1, 2), (3, 4))) + >>> a + Matrix([ + [1, 2], + [3, 4]]) + >>> a.RL + [(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)] + + See Also + ======== + + sympy.matrices.sparse.SparseMatrix.col_list + """ + return [tuple(k + (self[k],)) for k in + sorted(self.todok().keys(), key=list)] + + def scalar_multiply(self, scalar): + "Scalar element-wise multiplication" + return scalar * self + + def solve_least_squares(self, rhs, method='LDL'): + """Return the least-square fit to the data. + + By default the cholesky_solve routine is used (method='CH'); other + methods of matrix inversion can be used. To find out which are + available, see the docstring of the .inv() method. + + Examples + ======== + + >>> from sympy import SparseMatrix, Matrix, ones + >>> A = Matrix([1, 2, 3]) + >>> B = Matrix([2, 3, 4]) + >>> S = SparseMatrix(A.row_join(B)) + >>> S + Matrix([ + [1, 2], + [2, 3], + [3, 4]]) + + If each line of S represent coefficients of Ax + By + and x and y are [2, 3] then S*xy is: + + >>> r = S*Matrix([2, 3]); r + Matrix([ + [ 8], + [13], + [18]]) + + But let's add 1 to the middle value and then solve for the + least-squares value of xy: + + >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy + Matrix([ + [ 5/3], + [10/3]]) + + The error is given by S*xy - r: + + >>> S*xy - r + Matrix([ + [1/3], + [1/3], + [1/3]]) + >>> _.norm().n(2) + 0.58 + + If a different xy is used, the norm will be higher: + + >>> xy += ones(2, 1)/10 + >>> (S*xy - r).norm().n(2) + 1.5 + + """ + t = self.T + return (t*self).inv(method=method)*t*rhs + + def solve(self, rhs, method='LDL'): + """Return solution to self*soln = rhs using given inversion method. + + For a list of possible inversion methods, see the .inv() docstring. + """ + if not self.is_square: + if self.rows < self.cols: + raise ValueError('Under-determined system.') + elif self.rows > self.cols: + raise ValueError('For over-determined system, M, having ' + 'more rows than columns, try M.solve_least_squares(rhs).') + else: + return self.inv(method=method).multiply(rhs) + + RL = property(row_list, None, None, "Alternate faster representation") + CL = property(col_list, None, None, "Alternate faster representation") + + def liupc(self): + return _liupc(self) + + def row_structure_symbolic_cholesky(self): + return _row_structure_symbolic_cholesky(self) + + def cholesky(self, hermitian=True): + return _cholesky_sparse(self, hermitian=hermitian) + + def LDLdecomposition(self, hermitian=True): + return _LDLdecomposition_sparse(self, hermitian=hermitian) + + def lower_triangular_solve(self, rhs): + return _lower_triangular_solve_sparse(self, rhs) + + def upper_triangular_solve(self, rhs): + return _upper_triangular_solve_sparse(self, rhs) + + liupc.__doc__ = _liupc.__doc__ + row_structure_symbolic_cholesky.__doc__ = _row_structure_symbolic_cholesky.__doc__ + cholesky.__doc__ = _cholesky_sparse.__doc__ + LDLdecomposition.__doc__ = _LDLdecomposition_sparse.__doc__ + lower_triangular_solve.__doc__ = lower_triangular_solve.__doc__ + upper_triangular_solve.__doc__ = upper_triangular_solve.__doc__ + + +class MutableSparseMatrix(SparseRepMatrix, MutableRepMatrix): + + @classmethod + def _new(cls, *args, **kwargs): + rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs) + + rep = cls._smat_to_DomainMatrix(rows, cols, smat) + + return cls._fromrep(rep) + + +SparseMatrix = MutableSparseMatrix diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/sparsetools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/sparsetools.py new file mode 100644 index 0000000000000000000000000000000000000000..50048f6dc7e5cf160366963d16427987616ddce7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/sparsetools.py @@ -0,0 +1,300 @@ +from sympy.core.containers import Dict +from sympy.core.symbol import Dummy +from sympy.utilities.iterables import is_sequence +from sympy.utilities.misc import as_int, filldedent + +from .sparse import MutableSparseMatrix as SparseMatrix + + +def _doktocsr(dok): + """Converts a sparse matrix to Compressed Sparse Row (CSR) format. + + Parameters + ========== + + A : contains non-zero elements sorted by key (row, column) + JA : JA[i] is the column corresponding to A[i] + IA : IA[i] contains the index in A for the first non-zero element + of row[i]. Thus IA[i+1] - IA[i] gives number of non-zero + elements row[i]. The length of IA is always 1 more than the + number of rows in the matrix. + + Examples + ======== + + >>> from sympy.matrices.sparsetools import _doktocsr + >>> from sympy import SparseMatrix, diag + >>> m = SparseMatrix(diag(1, 2, 3)) + >>> m[2, 0] = -1 + >>> _doktocsr(m) + [[1, 2, -1, 3], [0, 1, 0, 2], [0, 1, 2, 4], [3, 3]] + + """ + row, JA, A = [list(i) for i in zip(*dok.row_list())] + IA = [0]*((row[0] if row else 0) + 1) + for i, r in enumerate(row): + IA.extend([i]*(r - row[i - 1])) # if i = 0 nothing is extended + IA.extend([len(A)]*(dok.rows - len(IA) + 1)) + shape = [dok.rows, dok.cols] + return [A, JA, IA, shape] + + +def _csrtodok(csr): + """Converts a CSR representation to DOK representation. + + Examples + ======== + + >>> from sympy.matrices.sparsetools import _csrtodok + >>> _csrtodok([[5, 8, 3, 6], [0, 1, 2, 1], [0, 0, 2, 3, 4], [4, 3]]) + Matrix([ + [0, 0, 0], + [5, 8, 0], + [0, 0, 3], + [0, 6, 0]]) + + """ + smat = {} + A, JA, IA, shape = csr + for i in range(len(IA) - 1): + indices = slice(IA[i], IA[i + 1]) + for l, m in zip(A[indices], JA[indices]): + smat[i, m] = l + return SparseMatrix(*shape, smat) + + +def banded(*args, **kwargs): + """Returns a SparseMatrix from the given dictionary describing + the diagonals of the matrix. The keys are positive for upper + diagonals and negative for those below the main diagonal. The + values may be: + + * expressions or single-argument functions, + + * lists or tuples of values, + + * matrices + + Unless dimensions are given, the size of the returned matrix will + be large enough to contain the largest non-zero value provided. + + kwargs + ====== + + rows : rows of the resulting matrix; computed if + not given. + + cols : columns of the resulting matrix; computed if + not given. + + Examples + ======== + + >>> from sympy import banded, ones, Matrix + >>> from sympy.abc import x + + If explicit values are given in tuples, + the matrix will autosize to contain all values, otherwise + a single value is filled onto the entire diagonal: + + >>> banded({1: (1, 2, 3), -1: (4, 5, 6), 0: x}) + Matrix([ + [x, 1, 0, 0], + [4, x, 2, 0], + [0, 5, x, 3], + [0, 0, 6, x]]) + + A function accepting a single argument can be used to fill the + diagonal as a function of diagonal index (which starts at 0). + The size (or shape) of the matrix must be given to obtain more + than a 1x1 matrix: + + >>> s = lambda d: (1 + d)**2 + >>> banded(5, {0: s, 2: s, -2: 2}) + Matrix([ + [1, 0, 1, 0, 0], + [0, 4, 0, 4, 0], + [2, 0, 9, 0, 9], + [0, 2, 0, 16, 0], + [0, 0, 2, 0, 25]]) + + The diagonal of matrices placed on a diagonal will coincide + with the indicated diagonal: + + >>> vert = Matrix([1, 2, 3]) + >>> banded({0: vert}, cols=3) + Matrix([ + [1, 0, 0], + [2, 1, 0], + [3, 2, 1], + [0, 3, 2], + [0, 0, 3]]) + + >>> banded(4, {0: ones(2)}) + Matrix([ + [1, 1, 0, 0], + [1, 1, 0, 0], + [0, 0, 1, 1], + [0, 0, 1, 1]]) + + Errors are raised if the designated size will not hold + all values an integral number of times. Here, the rows + are designated as odd (but an even number is required to + hold the off-diagonal 2x2 ones): + + >>> banded({0: 2, 1: ones(2)}, rows=5) + Traceback (most recent call last): + ... + ValueError: + sequence does not fit an integral number of times in the matrix + + And here, an even number of rows is given...but the square + matrix has an even number of columns, too. As we saw + in the previous example, an odd number is required: + + >>> banded(4, {0: 2, 1: ones(2)}) # trying to make 4x4 and cols must be odd + Traceback (most recent call last): + ... + ValueError: + sequence does not fit an integral number of times in the matrix + + A way around having to count rows is to enclosing matrix elements + in a tuple and indicate the desired number of them to the right: + + >>> banded({0: 2, 2: (ones(2),)*3}) + Matrix([ + [2, 0, 1, 1, 0, 0, 0, 0], + [0, 2, 1, 1, 0, 0, 0, 0], + [0, 0, 2, 0, 1, 1, 0, 0], + [0, 0, 0, 2, 1, 1, 0, 0], + [0, 0, 0, 0, 2, 0, 1, 1], + [0, 0, 0, 0, 0, 2, 1, 1]]) + + An error will be raised if more than one value + is written to a given entry. Here, the ones overlap + with the main diagonal if they are placed on the + first diagonal: + + >>> banded({0: (2,)*5, 1: (ones(2),)*3}) + Traceback (most recent call last): + ... + ValueError: collision at (1, 1) + + By placing a 0 at the bottom left of the 2x2 matrix of + ones, the collision is avoided: + + >>> u2 = Matrix([ + ... [1, 1], + ... [0, 1]]) + >>> banded({0: [2]*5, 1: [u2]*3}) + Matrix([ + [2, 1, 1, 0, 0, 0, 0], + [0, 2, 1, 0, 0, 0, 0], + [0, 0, 2, 1, 1, 0, 0], + [0, 0, 0, 2, 1, 0, 0], + [0, 0, 0, 0, 2, 1, 1], + [0, 0, 0, 0, 0, 0, 1]]) + """ + try: + if len(args) not in (1, 2, 3): + raise TypeError + if not isinstance(args[-1], (dict, Dict)): + raise TypeError + if len(args) == 1: + rows = kwargs.get('rows', None) + cols = kwargs.get('cols', None) + if rows is not None: + rows = as_int(rows) + if cols is not None: + cols = as_int(cols) + elif len(args) == 2: + rows = cols = as_int(args[0]) + else: + rows, cols = map(as_int, args[:2]) + # fails with ValueError if any keys are not ints + _ = all(as_int(k) for k in args[-1]) + except (ValueError, TypeError): + raise TypeError(filldedent( + '''unrecognized input to banded: + expecting [[row,] col,] {int: value}''')) + def rc(d): + # return row,col coord of diagonal start + r = -d if d < 0 else 0 + c = 0 if r else d + return r, c + smat = {} + undone = [] + tba = Dummy() + # first handle objects with size + for d, v in args[-1].items(): + r, c = rc(d) + # note: only list and tuple are recognized since this + # will allow other Basic objects like Tuple + # into the matrix if so desired + if isinstance(v, (list, tuple)): + extra = 0 + for i, vi in enumerate(v): + i += extra + if is_sequence(vi): + vi = SparseMatrix(vi) + smat[r + i, c + i] = vi + extra += min(vi.shape) - 1 + else: + smat[r + i, c + i] = vi + elif is_sequence(v): + v = SparseMatrix(v) + rv, cv = v.shape + if rows and cols: + nr, xr = divmod(rows - r, rv) + nc, xc = divmod(cols - c, cv) + x = xr or xc + do = min(nr, nc) + elif rows: + do, x = divmod(rows - r, rv) + elif cols: + do, x = divmod(cols - c, cv) + else: + do = 1 + x = 0 + if x: + raise ValueError(filldedent(''' + sequence does not fit an integral number of times + in the matrix''')) + j = min(v.shape) + for i in range(do): + smat[r, c] = v + r += j + c += j + elif v: + smat[r, c] = tba + undone.append((d, v)) + s = SparseMatrix(None, smat) # to expand matrices + smat = s.todok() + # check for dim errors here + if rows is not None and rows < s.rows: + raise ValueError('Designated rows %s < needed %s' % (rows, s.rows)) + if cols is not None and cols < s.cols: + raise ValueError('Designated cols %s < needed %s' % (cols, s.cols)) + if rows is cols is None: + rows = s.rows + cols = s.cols + elif rows is not None and cols is None: + cols = max(rows, s.cols) + elif cols is not None and rows is None: + rows = max(cols, s.rows) + def update(i, j, v): + # update smat and make sure there are + # no collisions + if v: + if (i, j) in smat and smat[i, j] not in (tba, v): + raise ValueError('collision at %s' % ((i, j),)) + smat[i, j] = v + if undone: + for d, vi in undone: + r, c = rc(d) + v = vi if callable(vi) else lambda _: vi + i = 0 + while r + i < rows and c + i < cols: + update(r + i, c + i, v(i)) + i += 1 + return SparseMatrix(rows, cols, smat) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/subspaces.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/subspaces.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab0b71b4289ebaeb6394059c6a7cd49d3a148a1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/subspaces.py @@ -0,0 +1,174 @@ +from .utilities import _iszero + + +def _columnspace(M, simplify=False): + """Returns a list of vectors (Matrix objects) that span columnspace of ``M`` + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) + >>> M + Matrix([ + [ 1, 3, 0], + [-2, -6, 0], + [ 3, 9, 6]]) + >>> M.columnspace() + [Matrix([ + [ 1], + [-2], + [ 3]]), Matrix([ + [0], + [0], + [6]])] + + See Also + ======== + + nullspace + rowspace + """ + + reduced, pivots = M.echelon_form(simplify=simplify, with_pivots=True) + + return [M.col(i) for i in pivots] + + +def _nullspace(M, simplify=False, iszerofunc=_iszero): + """Returns list of vectors (Matrix objects) that span nullspace of ``M`` + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) + >>> M + Matrix([ + [ 1, 3, 0], + [-2, -6, 0], + [ 3, 9, 6]]) + >>> M.nullspace() + [Matrix([ + [-3], + [ 1], + [ 0]])] + + See Also + ======== + + columnspace + rowspace + """ + + reduced, pivots = M.rref(iszerofunc=iszerofunc, simplify=simplify) + + free_vars = [i for i in range(M.cols) if i not in pivots] + basis = [] + + for free_var in free_vars: + # for each free variable, we will set it to 1 and all others + # to 0. Then, we will use back substitution to solve the system + vec = [M.zero] * M.cols + vec[free_var] = M.one + + for piv_row, piv_col in enumerate(pivots): + vec[piv_col] -= reduced[piv_row, free_var] + + basis.append(vec) + + return [M._new(M.cols, 1, b) for b in basis] + + +def _rowspace(M, simplify=False): + """Returns a list of vectors that span the row space of ``M``. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) + >>> M + Matrix([ + [ 1, 3, 0], + [-2, -6, 0], + [ 3, 9, 6]]) + >>> M.rowspace() + [Matrix([[1, 3, 0]]), Matrix([[0, 0, 6]])] + """ + + reduced, pivots = M.echelon_form(simplify=simplify, with_pivots=True) + + return [reduced.row(i) for i in range(len(pivots))] + + +def _orthogonalize(cls, *vecs, normalize=False, rankcheck=False): + """Apply the Gram-Schmidt orthogonalization procedure + to vectors supplied in ``vecs``. + + Parameters + ========== + + vecs + vectors to be made orthogonal + + normalize : bool + If ``True``, return an orthonormal basis. + + rankcheck : bool + If ``True``, the computation does not stop when encountering + linearly dependent vectors. + + If ``False``, it will raise ``ValueError`` when any zero + or linearly dependent vectors are found. + + Returns + ======= + + list + List of orthogonal (or orthonormal) basis vectors. + + Examples + ======== + + >>> from sympy import I, Matrix + >>> v = [Matrix([1, I]), Matrix([1, -I])] + >>> Matrix.orthogonalize(*v) + [Matrix([ + [1], + [I]]), Matrix([ + [ 1], + [-I]])] + + See Also + ======== + + MatrixBase.QRdecomposition + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process + """ + from .decompositions import _QRdecomposition_optional + + if not vecs: + return [] + + all_row_vecs = (vecs[0].rows == 1) + + vecs = [x.vec() for x in vecs] + M = cls.hstack(*vecs) + Q, R = _QRdecomposition_optional(M, normalize=normalize) + + if rankcheck and Q.cols < len(vecs): + raise ValueError("GramSchmidt: vector set not linearly independent") + + ret = [] + for i in range(Q.cols): + if all_row_vecs: + col = cls(Q[:, i].T) + else: + col = cls(Q[:, i]) + ret.append(col) + return ret diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/utilities.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/utilities.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a680b47e63615e210e561639a192ba47c642d3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/matrices/utilities.py @@ -0,0 +1,72 @@ +from contextlib import contextmanager +from threading import local + +from sympy.core.function import expand_mul + + +class DotProdSimpState(local): + def __init__(self): + self.state = None + +_dotprodsimp_state = DotProdSimpState() + +@contextmanager +def dotprodsimp(x): + old = _dotprodsimp_state.state + + try: + _dotprodsimp_state.state = x + yield + finally: + _dotprodsimp_state.state = old + + +def _dotprodsimp(expr, withsimp=False): + """Wrapper for simplify.dotprodsimp to avoid circular imports.""" + from sympy.simplify.simplify import dotprodsimp as dps + return dps(expr, withsimp=withsimp) + + +def _get_intermediate_simp(deffunc=lambda x: x, offfunc=lambda x: x, + onfunc=_dotprodsimp, dotprodsimp=None): + """Support function for controlling intermediate simplification. Returns a + simplification function according to the global setting of dotprodsimp + operation. + + ``deffunc`` - Function to be used by default. + ``offfunc`` - Function to be used if dotprodsimp has been turned off. + ``onfunc`` - Function to be used if dotprodsimp has been turned on. + ``dotprodsimp`` - True, False or None. Will be overridden by global + _dotprodsimp_state.state if that is not None. + """ + + if dotprodsimp is False or _dotprodsimp_state.state is False: + return offfunc + if dotprodsimp is True or _dotprodsimp_state.state is True: + return onfunc + + return deffunc # None, None + + +def _get_intermediate_simp_bool(default=False, dotprodsimp=None): + """Same as ``_get_intermediate_simp`` but returns bools instead of functions + by default.""" + + return _get_intermediate_simp(default, False, True, dotprodsimp) + + +def _iszero(x): + """Returns True if x is zero.""" + return getattr(x, 'is_zero', None) + + +def _is_zero_after_expand_mul(x): + """Tests by expand_mul only, suitable for polynomials and rational + functions.""" + return expand_mul(x) == 0 + + +def _simplify(expr): + """ Wrapper to avoid circular imports. """ + from sympy.simplify.simplify import simplify + return simplify(expr) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8055ed12d213de3ebc7a1f17100607fb1e3b89b8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__init__.py @@ -0,0 +1,130 @@ +"""Polynomial manipulation algorithms and algebraic objects. """ + +__all__ = [ + 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree', + 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo', + 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert', + 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list', + 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content', + 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff', + 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor', + 'intervals', 'refine_root', 'count_roots', 'all_roots', 'real_roots', + 'nroots', 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', + 'groebner', 'is_zero_dimensional', 'GroebnerBasis', 'poly', + + 'symmetrize', 'horner', 'interpolate', 'rational_interpolate', 'viete', + + 'together', + + 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed', + 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed', + 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed', + 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible', + 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed', + 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed', + 'UnivariatePolynomialError', 'MultivariatePolynomialError', + 'PolificationFailed', 'OptionError', 'FlagError', + + 'minpoly', 'minimal_polynomial', 'primitive_element', 'field_isomorphism', + 'to_number_field', 'isolate', 'round_two', 'prime_decomp', + 'prime_valuation', 'galois_group', + + 'itermonomials', 'Monomial', + + 'lex', 'grlex', 'grevlex', 'ilex', 'igrlex', 'igrevlex', + + 'CRootOf', 'rootof', 'RootOf', 'ComplexRootOf', 'RootSum', + + 'roots', + + 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField', + 'ComplexField', 'PythonFiniteField', 'GMPYFiniteField', + 'PythonIntegerRing', 'GMPYIntegerRing', 'PythonRational', + 'GMPYRationalField', 'AlgebraicField', 'PolynomialRing', 'FractionField', + 'ExpressionDomain', 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', + 'QQ_python', 'QQ_gmpy', 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', + 'CC', 'EX', 'EXRAW', + + 'construct_domain', + + 'swinnerton_dyer_poly', 'cyclotomic_poly', 'symmetric_poly', + 'random_poly', 'interpolating_poly', + + 'jacobi_poly', 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', + 'hermite_prob_poly', 'legendre_poly', 'laguerre_poly', + + 'bernoulli_poly', 'bernoulli_c_poly', 'genocchi_poly', 'euler_poly', + 'andre_poly', + + 'apart', 'apart_list', 'assemble_partfrac_list', + + 'Options', + + 'ring', 'xring', 'vring', 'sring', + + 'field', 'xfield', 'vfield', 'sfield' +] + +from .polytools import (Poly, PurePoly, poly_from_expr, + parallel_poly_from_expr, degree, total_degree, degree_list, LC, LM, + LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex, + invert, subresultants, resultant, discriminant, cofactors, gcd_list, + gcd, lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, + compose, decompose, sturm, gff_list, gff, sqf_norm, sqf_part, + sqf_list, sqf, factor_list, factor, intervals, refine_root, + count_roots, all_roots, real_roots, nroots, ground_roots, + nth_power_roots_poly, cancel, reduced, groebner, is_zero_dimensional, + GroebnerBasis, poly) + +from .polyfuncs import (symmetrize, horner, interpolate, + rational_interpolate, viete) + +from .rationaltools import together + +from .polyerrors import (BasePolynomialError, ExactQuotientFailed, + PolynomialDivisionFailed, OperationNotSupported, HeuristicGCDFailed, + HomomorphismFailed, IsomorphismFailed, ExtraneousFactors, + EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible, + NotReversible, NotAlgebraic, DomainError, PolynomialError, + UnificationFailed, GeneratorsError, GeneratorsNeeded, + ComputationFailed, UnivariatePolynomialError, + MultivariatePolynomialError, PolificationFailed, OptionError, + FlagError) + +from .numberfields import (minpoly, minimal_polynomial, primitive_element, + field_isomorphism, to_number_field, isolate, round_two, prime_decomp, + prime_valuation, galois_group) + +from .monomials import itermonomials, Monomial + +from .orderings import lex, grlex, grevlex, ilex, igrlex, igrevlex + +from .rootoftools import CRootOf, rootof, RootOf, ComplexRootOf, RootSum + +from .polyroots import roots + +from .domains import (Domain, FiniteField, IntegerRing, RationalField, + RealField, ComplexField, PythonFiniteField, GMPYFiniteField, + PythonIntegerRing, GMPYIntegerRing, PythonRational, GMPYRationalField, + AlgebraicField, PolynomialRing, FractionField, ExpressionDomain, + FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, QQ_gmpy, GF, FF, + ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW) + +from .constructor import construct_domain + +from .specialpolys import (swinnerton_dyer_poly, cyclotomic_poly, + symmetric_poly, random_poly, interpolating_poly) + +from .orthopolys import (jacobi_poly, chebyshevt_poly, chebyshevu_poly, + hermite_poly, hermite_prob_poly, legendre_poly, laguerre_poly) + +from .appellseqs import (bernoulli_poly, bernoulli_c_poly, genocchi_poly, + euler_poly, andre_poly) + +from .partfrac import apart, apart_list, assemble_partfrac_list + +from .polyoptions import Options + +from .rings import ring, xring, vring, sring + +from .fields import field, xfield, vfield, sfield diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e1763e7bf65a7061a956526b9a5f55a7ad1ae2a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/appellseqs.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/appellseqs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dcc89f31387b8bc5f4a35ef006cb842dcc0ae72 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/appellseqs.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/compatibility.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/compatibility.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a7d7dee5490dec5ffe10c4ecced933c6ef9c721 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/compatibility.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/constructor.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/constructor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df54d67d15c0ad24712894f26450e3942d3adae2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/constructor.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densearith.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densearith.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82ca1fc5a031a043838c8a78376b99da01a38c11 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densearith.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densebasic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densebasic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f71b7dcbbd207061212464a9ff2242b5a87bd060 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densebasic.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densetools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densetools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c1e7e5b6f3ed9757c4f005b5e1cf679c69d813b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/densetools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/domainmatrix.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/domainmatrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d27fc83cc2361a8417655b66ba1f84373284861 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/domainmatrix.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/euclidtools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/euclidtools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0b81a4fb87249e9302dcc9f40d3295217fd09b1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/euclidtools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/factortools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/factortools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e49c174fd996146dca5d43747f3892146aff28ca Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/factortools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/fglmtools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/fglmtools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..577abde063b0ea84a265bedfbc808194ec1f1a05 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/fglmtools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/fields.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/fields.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ac2bade8d0940585430f14f5e07a54d587de76 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/fields.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/galoistools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/galoistools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c7f789b07f27fe684ccf338f60bdda368c3d1c6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/galoistools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/groebnertools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/groebnertools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da6534bbd72a2fc6773fc579b67c760682350e56 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/groebnertools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/heuristicgcd.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/heuristicgcd.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fff52b0996857a47aeb343da16a3666a4a428662 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/heuristicgcd.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/monomials.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/monomials.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d94ce1a793c06b843aafc719650875d658c65bc4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/monomials.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/orderings.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/orderings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6868ce0af1e3acb41e8d869ad78927bc65570c3e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/orderings.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyclasses.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyclasses.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df0fa53426c123fab47bcfa51ee63943ce947a66 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyclasses.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyconfig.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyconfig.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0f55a67fca1d992aba466ed83798093355cdf6c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyconfig.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyerrors.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyerrors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e07cf4bb72dba444c969bdc8de8bab8aaf014c5c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyerrors.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyfuncs.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyfuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30640675a889ece99125f52d463cc52860dbfddd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyfuncs.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyoptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyoptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54a183169e993ce64e0b9b8ab9ed67a083b1ad04 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyoptions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyroots.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyroots.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a0051bada396d2577caa99d2b8fea07f28f3850 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyroots.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyutils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72a34cded22719b49218c8d616637f79e7c09cb3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/polyutils.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rationaltools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rationaltools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b84429c38abf59b6f4f450ea4f2806899a1688c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rationaltools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/ring_series.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/ring_series.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..657637ca6ce0745b868abb561bcd591bcd6e1f65 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/ring_series.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rings.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32eab4f17533648607dfa30032a37c0f467cc12c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rings.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rootisolation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rootisolation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cedc8e2c015e12cb7c66850ffca519e45fc6a48 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rootisolation.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rootoftools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rootoftools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2451e14244eaf8b2abc96556c27fc8231686c176 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/rootoftools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/specialpolys.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/specialpolys.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66c03790ed621e5eeda52e529419778118968687 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/specialpolys.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/sqfreetools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/sqfreetools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bcf73029eeefcc2752a55c92fe812b8b2f74a13 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/__pycache__/sqfreetools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43486eec86f7453ec470a22b8f8decaa316cbe70 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__init__.py @@ -0,0 +1,5 @@ +"""Module for algebraic geometry and commutative algebra.""" + +from .homomorphisms import homomorphism + +__all__ = ['homomorphism'] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..807091ded108eadbd09302b8c39736d28e1d2df5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/extensions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/extensions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1f81d7f25d7e20acafd40a99991f3d8e9d88ef4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/extensions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/homomorphisms.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/homomorphisms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9bdf9b92d804ef976a8f25e6c304c4f36d97c52 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/homomorphisms.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/ideals.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/ideals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ea9abefc1ef51953bfb46a2670ca11257484cf6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/ideals.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/modules.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/modules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2754a48a3d10925df70e72080a89f07a4e20f30 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/__pycache__/modules.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/extensions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..2668f792b5721db877f275e57ed54961b2e4df93 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/extensions.py @@ -0,0 +1,356 @@ +"""Finite extensions of ring domains.""" + +from sympy.polys.domains.domain import Domain +from sympy.polys.domains.domainelement import DomainElement +from sympy.polys.polyerrors import (CoercionFailed, NotInvertible, + GeneratorsError) +from sympy.polys.polytools import Poly +from sympy.printing.defaults import DefaultPrinting + + +class ExtensionElement(DomainElement, DefaultPrinting): + """ + Element of a finite extension. + + A class of univariate polynomials modulo the ``modulus`` + of the extension ``ext``. It is represented by the + unique polynomial ``rep`` of lowest degree. Both + ``rep`` and the representation ``mod`` of ``modulus`` + are of class DMP. + + """ + __slots__ = ('rep', 'ext') + + def __init__(self, rep, ext): + self.rep = rep + self.ext = ext + + def parent(f): + return f.ext + + def as_expr(f): + return f.ext.to_sympy(f) + + def __bool__(f): + return bool(f.rep) + + def __pos__(f): + return f + + def __neg__(f): + return ExtElem(-f.rep, f.ext) + + def _get_rep(f, g): + if isinstance(g, ExtElem): + if g.ext == f.ext: + return g.rep + else: + return None + else: + try: + g = f.ext.convert(g) + return g.rep + except CoercionFailed: + return None + + def __add__(f, g): + rep = f._get_rep(g) + if rep is not None: + return ExtElem(f.rep + rep, f.ext) + else: + return NotImplemented + + __radd__ = __add__ + + def __sub__(f, g): + rep = f._get_rep(g) + if rep is not None: + return ExtElem(f.rep - rep, f.ext) + else: + return NotImplemented + + def __rsub__(f, g): + rep = f._get_rep(g) + if rep is not None: + return ExtElem(rep - f.rep, f.ext) + else: + return NotImplemented + + def __mul__(f, g): + rep = f._get_rep(g) + if rep is not None: + return ExtElem((f.rep * rep) % f.ext.mod, f.ext) + else: + return NotImplemented + + __rmul__ = __mul__ + + def _divcheck(f): + """Raise if division is not implemented for this divisor""" + if not f: + raise NotInvertible('Zero divisor') + elif f.ext.is_Field: + return True + elif f.rep.is_ground and f.ext.domain.is_unit(f.rep.LC()): + return True + else: + # Some cases like (2*x + 2)/2 over ZZ will fail here. It is + # unclear how to implement division in general if the ground + # domain is not a field so for now it was decided to restrict the + # implementation to division by invertible constants. + msg = (f"Can not invert {f} in {f.ext}. " + "Only division by invertible constants is implemented.") + raise NotImplementedError(msg) + + def inverse(f): + """Multiplicative inverse. + + Raises + ====== + + NotInvertible + If the element is a zero divisor. + + """ + f._divcheck() + + if f.ext.is_Field: + invrep = f.rep.invert(f.ext.mod) + else: + R = f.ext.ring + invrep = R.exquo(R.one, f.rep) + + return ExtElem(invrep, f.ext) + + def __truediv__(f, g): + rep = f._get_rep(g) + if rep is None: + return NotImplemented + g = ExtElem(rep, f.ext) + + try: + ginv = g.inverse() + except NotInvertible: + raise ZeroDivisionError(f"{f} / {g}") + + return f * ginv + + __floordiv__ = __truediv__ + + def __rtruediv__(f, g): + try: + g = f.ext.convert(g) + except CoercionFailed: + return NotImplemented + return g / f + + __rfloordiv__ = __rtruediv__ + + def __mod__(f, g): + rep = f._get_rep(g) + if rep is None: + return NotImplemented + g = ExtElem(rep, f.ext) + + try: + g._divcheck() + except NotInvertible: + raise ZeroDivisionError(f"{f} % {g}") + + # Division where defined is always exact so there is no remainder + return f.ext.zero + + def __rmod__(f, g): + try: + g = f.ext.convert(g) + except CoercionFailed: + return NotImplemented + return g % f + + def __pow__(f, n): + if not isinstance(n, int): + raise TypeError("exponent of type 'int' expected") + if n < 0: + try: + f, n = f.inverse(), -n + except NotImplementedError: + raise ValueError("negative powers are not defined") + + b = f.rep + m = f.ext.mod + r = f.ext.one.rep + while n > 0: + if n % 2: + r = (r*b) % m + b = (b*b) % m + n //= 2 + + return ExtElem(r, f.ext) + + def __eq__(f, g): + if isinstance(g, ExtElem): + return f.rep == g.rep and f.ext == g.ext + else: + return NotImplemented + + def __ne__(f, g): + return not f == g + + def __hash__(f): + return hash((f.rep, f.ext)) + + def __str__(f): + from sympy.printing.str import sstr + return sstr(f.as_expr()) + + __repr__ = __str__ + + @property + def is_ground(f): + return f.rep.is_ground + + def to_ground(f): + [c] = f.rep.to_list() + return c + +ExtElem = ExtensionElement + + +class MonogenicFiniteExtension(Domain): + r""" + Finite extension generated by an integral element. + + The generator is defined by a monic univariate + polynomial derived from the argument ``mod``. + + A shorter alias is ``FiniteExtension``. + + Examples + ======== + + Quadratic integer ring $\mathbb{Z}[\sqrt2]$: + + >>> from sympy import Symbol, Poly + >>> from sympy.polys.agca.extensions import FiniteExtension + >>> x = Symbol('x') + >>> R = FiniteExtension(Poly(x**2 - 2)); R + ZZ[x]/(x**2 - 2) + >>> R.rank + 2 + >>> R(1 + x)*(3 - 2*x) + x - 1 + + Finite field $GF(5^3)$ defined by the primitive + polynomial $x^3 + x^2 + 2$ (over $\mathbb{Z}_5$). + + >>> F = FiniteExtension(Poly(x**3 + x**2 + 2, modulus=5)); F + GF(5)[x]/(x**3 + x**2 + 2) + >>> F.basis + (1, x, x**2) + >>> F(x + 3)/(x**2 + 2) + -2*x**2 + x + 2 + + Function field of an elliptic curve: + + >>> t = Symbol('t') + >>> FiniteExtension(Poly(t**2 - x**3 - x + 1, t, field=True)) + ZZ(x)[t]/(t**2 - x**3 - x + 1) + + """ + is_FiniteExtension = True + + dtype = ExtensionElement + + def __init__(self, mod): + if not (isinstance(mod, Poly) and mod.is_univariate): + raise TypeError("modulus must be a univariate Poly") + + # Using auto=True (default) potentially changes the ground domain to a + # field whereas auto=False raises if division is not exact. We'll let + # the caller decide whether or not they want to put the ground domain + # over a field. In most uses mod is already monic. + mod = mod.monic(auto=False) + + self.rank = mod.degree() + self.modulus = mod + self.mod = mod.rep # DMP representation + + self.domain = dom = mod.domain + self.ring = dom.old_poly_ring(*mod.gens) + + self.zero = self.convert(self.ring.zero) + self.one = self.convert(self.ring.one) + + gen = self.ring.gens[0] + self.symbol = self.ring.symbols[0] + self.generator = self.convert(gen) + self.basis = tuple(self.convert(gen**i) for i in range(self.rank)) + + # XXX: It might be necessary to check mod.is_irreducible here + self.is_Field = self.domain.is_Field + + def new(self, arg): + rep = self.ring.convert(arg) + return ExtElem(rep % self.mod, self) + + def __eq__(self, other): + if not isinstance(other, FiniteExtension): + return False + return self.modulus == other.modulus + + def __hash__(self): + return hash((self.__class__.__name__, self.modulus)) + + def __str__(self): + return "%s/(%s)" % (self.ring, self.modulus.as_expr()) + + __repr__ = __str__ + + @property + def has_CharacteristicZero(self): + return self.domain.has_CharacteristicZero + + def characteristic(self): + return self.domain.characteristic() + + def convert(self, f, base=None): + rep = self.ring.convert(f, base) + return ExtElem(rep % self.mod, self) + + def convert_from(self, f, base): + rep = self.ring.convert(f, base) + return ExtElem(rep % self.mod, self) + + def to_sympy(self, f): + return self.ring.to_sympy(f.rep) + + def from_sympy(self, f): + return self.convert(f) + + def set_domain(self, K): + mod = self.modulus.set_domain(K) + return self.__class__(mod) + + def drop(self, *symbols): + if self.symbol in symbols: + raise GeneratorsError('Can not drop generator from FiniteExtension') + K = self.domain.drop(*symbols) + return self.set_domain(K) + + def quo(self, f, g): + return self.exquo(f, g) + + def exquo(self, f, g): + rep = self.ring.exquo(f.rep, g.rep) + return ExtElem(rep % self.mod, self) + + def is_negative(self, a): + return False + + def is_unit(self, a): + if self.is_Field: + return bool(a) + elif a.is_ground: + return self.domain.is_unit(a.to_ground()) + +FiniteExtension = MonogenicFiniteExtension diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/homomorphisms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/homomorphisms.py new file mode 100644 index 0000000000000000000000000000000000000000..45e9549980a8848eee944000d321922576961a00 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/homomorphisms.py @@ -0,0 +1,691 @@ +""" +Computations with homomorphisms of modules and rings. + +This module implements classes for representing homomorphisms of rings and +their modules. Instead of instantiating the classes directly, you should use +the function ``homomorphism(from, to, matrix)`` to create homomorphism objects. +""" + + +from sympy.polys.agca.modules import (Module, FreeModule, QuotientModule, + SubModule, SubQuotientModule) +from sympy.polys.polyerrors import CoercionFailed + +# The main computational task for module homomorphisms is kernels. +# For this reason, the concrete classes are organised by domain module type. + + +class ModuleHomomorphism: + """ + Abstract base class for module homomoprhisms. Do not instantiate. + + Instead, use the ``homomorphism`` function: + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> homomorphism(F, F, [[1, 0], [0, 1]]) + Matrix([ + [1, 0], : QQ[x]**2 -> QQ[x]**2 + [0, 1]]) + + Attributes: + + - ring - the ring over which we are considering modules + - domain - the domain module + - codomain - the codomain module + - _ker - cached kernel + - _img - cached image + + Non-implemented methods: + + - _kernel + - _image + - _restrict_domain + - _restrict_codomain + - _quotient_domain + - _quotient_codomain + - _apply + - _mul_scalar + - _compose + - _add + """ + + def __init__(self, domain, codomain): + if not isinstance(domain, Module): + raise TypeError('Source must be a module, got %s' % domain) + if not isinstance(codomain, Module): + raise TypeError('Target must be a module, got %s' % codomain) + if domain.ring != codomain.ring: + raise ValueError('Source and codomain must be over same ring, ' + 'got %s != %s' % (domain, codomain)) + self.domain = domain + self.codomain = codomain + self.ring = domain.ring + self._ker = None + self._img = None + + def kernel(self): + r""" + Compute the kernel of ``self``. + + That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute + `ker(\phi) = \{x \in M | \phi(x) = 0\}`. This is a submodule of `M`. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> homomorphism(F, F, [[1, 0], [x, 0]]).kernel() + <[x, -1]> + """ + if self._ker is None: + self._ker = self._kernel() + return self._ker + + def image(self): + r""" + Compute the image of ``self``. + + That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute + `im(\phi) = \{\phi(x) | x \in M \}`. This is a submodule of `N`. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> homomorphism(F, F, [[1, 0], [x, 0]]).image() == F.submodule([1, 0]) + True + """ + if self._img is None: + self._img = self._image() + return self._img + + def _kernel(self): + """Compute the kernel of ``self``.""" + raise NotImplementedError + + def _image(self): + """Compute the image of ``self``.""" + raise NotImplementedError + + def _restrict_domain(self, sm): + """Implementation of domain restriction.""" + raise NotImplementedError + + def _restrict_codomain(self, sm): + """Implementation of codomain restriction.""" + raise NotImplementedError + + def _quotient_domain(self, sm): + """Implementation of domain quotient.""" + raise NotImplementedError + + def _quotient_codomain(self, sm): + """Implementation of codomain quotient.""" + raise NotImplementedError + + def restrict_domain(self, sm): + """ + Return ``self``, with the domain restricted to ``sm``. + + Here ``sm`` has to be a submodule of ``self.domain``. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h + Matrix([ + [1, x], : QQ[x]**2 -> QQ[x]**2 + [0, 0]]) + >>> h.restrict_domain(F.submodule([1, 0])) + Matrix([ + [1, x], : <[1, 0]> -> QQ[x]**2 + [0, 0]]) + + This is the same as just composing on the right with the submodule + inclusion: + + >>> h * F.submodule([1, 0]).inclusion_hom() + Matrix([ + [1, x], : <[1, 0]> -> QQ[x]**2 + [0, 0]]) + """ + if not self.domain.is_submodule(sm): + raise ValueError('sm must be a submodule of %s, got %s' + % (self.domain, sm)) + if sm == self.domain: + return self + return self._restrict_domain(sm) + + def restrict_codomain(self, sm): + """ + Return ``self``, with codomain restricted to to ``sm``. + + Here ``sm`` has to be a submodule of ``self.codomain`` containing the + image. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h + Matrix([ + [1, x], : QQ[x]**2 -> QQ[x]**2 + [0, 0]]) + >>> h.restrict_codomain(F.submodule([1, 0])) + Matrix([ + [1, x], : QQ[x]**2 -> <[1, 0]> + [0, 0]]) + """ + if not sm.is_submodule(self.image()): + raise ValueError('the image %s must contain sm, got %s' + % (self.image(), sm)) + if sm == self.codomain: + return self + return self._restrict_codomain(sm) + + def quotient_domain(self, sm): + """ + Return ``self`` with domain replaced by ``domain/sm``. + + Here ``sm`` must be a submodule of ``self.kernel()``. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h + Matrix([ + [1, x], : QQ[x]**2 -> QQ[x]**2 + [0, 0]]) + >>> h.quotient_domain(F.submodule([-x, 1])) + Matrix([ + [1, x], : QQ[x]**2/<[-x, 1]> -> QQ[x]**2 + [0, 0]]) + """ + if not self.kernel().is_submodule(sm): + raise ValueError('kernel %s must contain sm, got %s' % + (self.kernel(), sm)) + if sm.is_zero(): + return self + return self._quotient_domain(sm) + + def quotient_codomain(self, sm): + """ + Return ``self`` with codomain replaced by ``codomain/sm``. + + Here ``sm`` must be a submodule of ``self.codomain``. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h + Matrix([ + [1, x], : QQ[x]**2 -> QQ[x]**2 + [0, 0]]) + >>> h.quotient_codomain(F.submodule([1, 1])) + Matrix([ + [1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]> + [0, 0]]) + + This is the same as composing with the quotient map on the left: + + >>> (F/[(1, 1)]).quotient_hom() * h + Matrix([ + [1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]> + [0, 0]]) + """ + if not self.codomain.is_submodule(sm): + raise ValueError('sm must be a submodule of codomain %s, got %s' + % (self.codomain, sm)) + if sm.is_zero(): + return self + return self._quotient_codomain(sm) + + def _apply(self, elem): + """Apply ``self`` to ``elem``.""" + raise NotImplementedError + + def __call__(self, elem): + return self.codomain.convert(self._apply(self.domain.convert(elem))) + + def _compose(self, oth): + """ + Compose ``self`` with ``oth``, that is, return the homomorphism + obtained by first applying then ``self``, then ``oth``. + + (This method is private since in this syntax, it is non-obvious which + homomorphism is executed first.) + """ + raise NotImplementedError + + def _mul_scalar(self, c): + """Scalar multiplication. ``c`` is guaranteed in self.ring.""" + raise NotImplementedError + + def _add(self, oth): + """ + Homomorphism addition. + ``oth`` is guaranteed to be a homomorphism with same domain/codomain. + """ + raise NotImplementedError + + def _check_hom(self, oth): + """Helper to check that oth is a homomorphism with same domain/codomain.""" + if not isinstance(oth, ModuleHomomorphism): + return False + return oth.domain == self.domain and oth.codomain == self.codomain + + def __mul__(self, oth): + if isinstance(oth, ModuleHomomorphism) and self.domain == oth.codomain: + return oth._compose(self) + try: + return self._mul_scalar(self.ring.convert(oth)) + except CoercionFailed: + return NotImplemented + + # NOTE: _compose will never be called from rmul + __rmul__ = __mul__ + + def __truediv__(self, oth): + try: + return self._mul_scalar(1/self.ring.convert(oth)) + except CoercionFailed: + return NotImplemented + + def __add__(self, oth): + if self._check_hom(oth): + return self._add(oth) + return NotImplemented + + def __sub__(self, oth): + if self._check_hom(oth): + return self._add(oth._mul_scalar(self.ring.convert(-1))) + return NotImplemented + + def is_injective(self): + """ + Return True if ``self`` is injective. + + That is, check if the elements of the domain are mapped to the same + codomain element. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h.is_injective() + False + >>> h.quotient_domain(h.kernel()).is_injective() + True + """ + return self.kernel().is_zero() + + def is_surjective(self): + """ + Return True if ``self`` is surjective. + + That is, check if every element of the codomain has at least one + preimage. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h.is_surjective() + False + >>> h.restrict_codomain(h.image()).is_surjective() + True + """ + return self.image() == self.codomain + + def is_isomorphism(self): + """ + Return True if ``self`` is an isomorphism. + + That is, check if every element of the codomain has precisely one + preimage. Equivalently, ``self`` is both injective and surjective. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h = h.restrict_codomain(h.image()) + >>> h.is_isomorphism() + False + >>> h.quotient_domain(h.kernel()).is_isomorphism() + True + """ + return self.is_injective() and self.is_surjective() + + def is_zero(self): + """ + Return True if ``self`` is a zero morphism. + + That is, check if every element of the domain is mapped to zero + under self. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) + >>> h.is_zero() + False + >>> h.restrict_domain(F.submodule()).is_zero() + True + >>> h.quotient_codomain(h.image()).is_zero() + True + """ + return self.image().is_zero() + + def __eq__(self, oth): + try: + return (self - oth).is_zero() + except TypeError: + return False + + def __ne__(self, oth): + return not (self == oth) + + +class MatrixHomomorphism(ModuleHomomorphism): + r""" + Helper class for all homomoprhisms which are expressed via a matrix. + + That is, for such homomorphisms ``domain`` is contained in a module + generated by finitely many elements `e_1, \ldots, e_n`, so that the + homomorphism is determined uniquely by its action on the `e_i`. It + can thus be represented as a vector of elements of the codomain module, + or potentially a supermodule of the codomain module + (and hence conventionally as a matrix, if there is a similar interpretation + for elements of the codomain module). + + Note that this class does *not* assume that the `e_i` freely generate a + submodule, nor that ``domain`` is even all of this submodule. It exists + only to unify the interface. + + Do not instantiate. + + Attributes: + + - matrix - the list of images determining the homomorphism. + NOTE: the elements of matrix belong to either self.codomain or + self.codomain.container + + Still non-implemented methods: + + - kernel + - _apply + """ + + def __init__(self, domain, codomain, matrix): + ModuleHomomorphism.__init__(self, domain, codomain) + if len(matrix) != domain.rank: + raise ValueError('Need to provide %s elements, got %s' + % (domain.rank, len(matrix))) + + converter = self.codomain.convert + if isinstance(self.codomain, (SubModule, SubQuotientModule)): + converter = self.codomain.container.convert + self.matrix = tuple(converter(x) for x in matrix) + + def _sympy_matrix(self): + """Helper function which returns a SymPy matrix ``self.matrix``.""" + from sympy.matrices import Matrix + c = lambda x: x + if isinstance(self.codomain, (QuotientModule, SubQuotientModule)): + c = lambda x: x.data + return Matrix([[self.ring.to_sympy(y) for y in c(x)] for x in self.matrix]).T + + def __repr__(self): + lines = repr(self._sympy_matrix()).split('\n') + t = " : %s -> %s" % (self.domain, self.codomain) + s = ' '*len(t) + n = len(lines) + for i in range(n // 2): + lines[i] += s + lines[n // 2] += t + for i in range(n//2 + 1, n): + lines[i] += s + return '\n'.join(lines) + + def _restrict_domain(self, sm): + """Implementation of domain restriction.""" + return SubModuleHomomorphism(sm, self.codomain, self.matrix) + + def _restrict_codomain(self, sm): + """Implementation of codomain restriction.""" + return self.__class__(self.domain, sm, self.matrix) + + def _quotient_domain(self, sm): + """Implementation of domain quotient.""" + return self.__class__(self.domain/sm, self.codomain, self.matrix) + + def _quotient_codomain(self, sm): + """Implementation of codomain quotient.""" + Q = self.codomain/sm + converter = Q.convert + if isinstance(self.codomain, SubModule): + converter = Q.container.convert + return self.__class__(self.domain, self.codomain/sm, + [converter(x) for x in self.matrix]) + + def _add(self, oth): + return self.__class__(self.domain, self.codomain, + [x + y for x, y in zip(self.matrix, oth.matrix)]) + + def _mul_scalar(self, c): + return self.__class__(self.domain, self.codomain, [c*x for x in self.matrix]) + + def _compose(self, oth): + return self.__class__(self.domain, oth.codomain, [oth(x) for x in self.matrix]) + + +class FreeModuleHomomorphism(MatrixHomomorphism): + """ + Concrete class for homomorphisms with domain a free module or a quotient + thereof. + + Do not instantiate; the constructor does not check that your data is well + defined. Use the ``homomorphism`` function instead: + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> homomorphism(F, F, [[1, 0], [0, 1]]) + Matrix([ + [1, 0], : QQ[x]**2 -> QQ[x]**2 + [0, 1]]) + """ + + def _apply(self, elem): + if isinstance(self.domain, QuotientModule): + elem = elem.data + return sum(x * e for x, e in zip(elem, self.matrix)) + + def _image(self): + return self.codomain.submodule(*self.matrix) + + def _kernel(self): + # The domain is either a free module or a quotient thereof. + # It does not matter if it is a quotient, because that won't increase + # the kernel. + # Our generators {e_i} are sent to the matrix entries {b_i}. + # The kernel is essentially the syzygy module of these {b_i}. + syz = self.image().syzygy_module() + return self.domain.submodule(*syz.gens) + + +class SubModuleHomomorphism(MatrixHomomorphism): + """ + Concrete class for homomorphism with domain a submodule of a free module + or a quotient thereof. + + Do not instantiate; the constructor does not check that your data is well + defined. Use the ``homomorphism`` function instead: + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> M = QQ.old_poly_ring(x).free_module(2)*x + >>> homomorphism(M, M, [[1, 0], [0, 1]]) + Matrix([ + [1, 0], : <[x, 0], [0, x]> -> <[x, 0], [0, x]> + [0, 1]]) + """ + + def _apply(self, elem): + if isinstance(self.domain, SubQuotientModule): + elem = elem.data + return sum(x * e for x, e in zip(elem, self.matrix)) + + def _image(self): + return self.codomain.submodule(*[self(x) for x in self.domain.gens]) + + def _kernel(self): + syz = self.image().syzygy_module() + return self.domain.submodule( + *[sum(xi*gi for xi, gi in zip(s, self.domain.gens)) + for s in syz.gens]) + + +def homomorphism(domain, codomain, matrix): + r""" + Create a homomorphism object. + + This function tries to build a homomorphism from ``domain`` to ``codomain`` + via the matrix ``matrix``. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> from sympy.polys.agca import homomorphism + + >>> R = QQ.old_poly_ring(x) + >>> T = R.free_module(2) + + If ``domain`` is a free module generated by `e_1, \ldots, e_n`, then + ``matrix`` should be an n-element iterable `(b_1, \ldots, b_n)` where + the `b_i` are elements of ``codomain``. The constructed homomorphism is the + unique homomorphism sending `e_i` to `b_i`. + + >>> F = R.free_module(2) + >>> h = homomorphism(F, T, [[1, x], [x**2, 0]]) + >>> h + Matrix([ + [1, x**2], : QQ[x]**2 -> QQ[x]**2 + [x, 0]]) + >>> h([1, 0]) + [1, x] + >>> h([0, 1]) + [x**2, 0] + >>> h([1, 1]) + [x**2 + 1, x] + + If ``domain`` is a submodule of a free module, them ``matrix`` determines + a homomoprhism from the containing free module to ``codomain``, and the + homomorphism returned is obtained by restriction to ``domain``. + + >>> S = F.submodule([1, 0], [0, x]) + >>> homomorphism(S, T, [[1, x], [x**2, 0]]) + Matrix([ + [1, x**2], : <[1, 0], [0, x]> -> QQ[x]**2 + [x, 0]]) + + If ``domain`` is a (sub)quotient `N/K`, then ``matrix`` determines a + homomorphism from `N` to ``codomain``. If the kernel contains `K`, this + homomorphism descends to ``domain`` and is returned; otherwise an exception + is raised. + + >>> homomorphism(S/[(1, 0)], T, [0, [x**2, 0]]) + Matrix([ + [0, x**2], : <[1, 0] + <[1, 0]>, [0, x] + <[1, 0]>, [1, 0] + <[1, 0]>> -> QQ[x]**2 + [0, 0]]) + >>> homomorphism(S/[(0, x)], T, [0, [x**2, 0]]) + Traceback (most recent call last): + ... + ValueError: kernel <[1, 0], [0, 0]> must contain sm, got <[0,x]> + + """ + def freepres(module): + """ + Return a tuple ``(F, S, Q, c)`` where ``F`` is a free module, ``S`` is a + submodule of ``F``, and ``Q`` a submodule of ``S``, such that + ``module = S/Q``, and ``c`` is a conversion function. + """ + if isinstance(module, FreeModule): + return module, module, module.submodule(), lambda x: module.convert(x) + if isinstance(module, QuotientModule): + return (module.base, module.base, module.killed_module, + lambda x: module.convert(x).data) + if isinstance(module, SubQuotientModule): + return (module.base.container, module.base, module.killed_module, + lambda x: module.container.convert(x).data) + # an ordinary submodule + return (module.container, module, module.submodule(), + lambda x: module.container.convert(x)) + + SF, SS, SQ, _ = freepres(domain) + TF, TS, TQ, c = freepres(codomain) + # NOTE this is probably a bit inefficient (redundant checks) + return FreeModuleHomomorphism(SF, TF, [c(x) for x in matrix] + ).restrict_domain(SS).restrict_codomain(TS + ).quotient_codomain(TQ).quotient_domain(SQ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/ideals.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/ideals.py new file mode 100644 index 0000000000000000000000000000000000000000..1969554a1d674bc36ded1a3e312d587c66104086 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/ideals.py @@ -0,0 +1,395 @@ +"""Computations with ideals of polynomial rings.""" + +from sympy.polys.polyerrors import CoercionFailed +from sympy.polys.polyutils import IntegerPowerable + + +class Ideal(IntegerPowerable): + """ + Abstract base class for ideals. + + Do not instantiate - use explicit constructors in the ring class instead: + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> QQ.old_poly_ring(x).ideal(x+1) + + + Attributes + + - ring - the ring this ideal belongs to + + Non-implemented methods: + + - _contains_elem + - _contains_ideal + - _quotient + - _intersect + - _union + - _product + - is_whole_ring + - is_zero + - is_prime, is_maximal, is_primary, is_radical + - is_principal + - height, depth + - radical + + Methods that likely should be overridden in subclasses: + + - reduce_element + """ + + def _contains_elem(self, x): + """Implementation of element containment.""" + raise NotImplementedError + + def _contains_ideal(self, I): + """Implementation of ideal containment.""" + raise NotImplementedError + + def _quotient(self, J): + """Implementation of ideal quotient.""" + raise NotImplementedError + + def _intersect(self, J): + """Implementation of ideal intersection.""" + raise NotImplementedError + + def is_whole_ring(self): + """Return True if ``self`` is the whole ring.""" + raise NotImplementedError + + def is_zero(self): + """Return True if ``self`` is the zero ideal.""" + raise NotImplementedError + + def _equals(self, J): + """Implementation of ideal equality.""" + return self._contains_ideal(J) and J._contains_ideal(self) + + def is_prime(self): + """Return True if ``self`` is a prime ideal.""" + raise NotImplementedError + + def is_maximal(self): + """Return True if ``self`` is a maximal ideal.""" + raise NotImplementedError + + def is_radical(self): + """Return True if ``self`` is a radical ideal.""" + raise NotImplementedError + + def is_primary(self): + """Return True if ``self`` is a primary ideal.""" + raise NotImplementedError + + def is_principal(self): + """Return True if ``self`` is a principal ideal.""" + raise NotImplementedError + + def radical(self): + """Compute the radical of ``self``.""" + raise NotImplementedError + + def depth(self): + """Compute the depth of ``self``.""" + raise NotImplementedError + + def height(self): + """Compute the height of ``self``.""" + raise NotImplementedError + + # TODO more + + # non-implemented methods end here + + def __init__(self, ring): + self.ring = ring + + def _check_ideal(self, J): + """Helper to check ``J`` is an ideal of our ring.""" + if not isinstance(J, Ideal) or J.ring != self.ring: + raise ValueError( + 'J must be an ideal of %s, got %s' % (self.ring, J)) + + def contains(self, elem): + """ + Return True if ``elem`` is an element of this ideal. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).ideal(x+1, x-1).contains(3) + True + >>> QQ.old_poly_ring(x).ideal(x**2, x**3).contains(x) + False + """ + return self._contains_elem(self.ring.convert(elem)) + + def subset(self, other): + """ + Returns True if ``other`` is is a subset of ``self``. + + Here ``other`` may be an ideal. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> I = QQ.old_poly_ring(x).ideal(x+1) + >>> I.subset([x**2 - 1, x**2 + 2*x + 1]) + True + >>> I.subset([x**2 + 1, x + 1]) + False + >>> I.subset(QQ.old_poly_ring(x).ideal(x**2 - 1)) + True + """ + if isinstance(other, Ideal): + return self._contains_ideal(other) + return all(self._contains_elem(x) for x in other) + + def quotient(self, J, **opts): + r""" + Compute the ideal quotient of ``self`` by ``J``. + + That is, if ``self`` is the ideal `I`, compute the set + `I : J = \{x \in R | xJ \subset I \}`. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> R = QQ.old_poly_ring(x, y) + >>> R.ideal(x*y).quotient(R.ideal(x)) + + """ + self._check_ideal(J) + return self._quotient(J, **opts) + + def intersect(self, J): + """ + Compute the intersection of self with ideal J. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> R = QQ.old_poly_ring(x, y) + >>> R.ideal(x).intersect(R.ideal(y)) + + """ + self._check_ideal(J) + return self._intersect(J) + + def saturate(self, J): + r""" + Compute the ideal saturation of ``self`` by ``J``. + + That is, if ``self`` is the ideal `I`, compute the set + `I : J^\infty = \{x \in R | xJ^n \subset I \text{ for some } n\}`. + """ + raise NotImplementedError + # Note this can be implemented using repeated quotient + + def union(self, J): + """ + Compute the ideal generated by the union of ``self`` and ``J``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).ideal(x**2 - 1).union(QQ.old_poly_ring(x).ideal((x+1)**2)) == QQ.old_poly_ring(x).ideal(x+1) + True + """ + self._check_ideal(J) + return self._union(J) + + def product(self, J): + r""" + Compute the ideal product of ``self`` and ``J``. + + That is, compute the ideal generated by products `xy`, for `x` an element + of ``self`` and `y \in J`. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> QQ.old_poly_ring(x, y).ideal(x).product(QQ.old_poly_ring(x, y).ideal(y)) + + """ + self._check_ideal(J) + return self._product(J) + + def reduce_element(self, x): + """ + Reduce the element ``x`` of our ring modulo the ideal ``self``. + + Here "reduce" has no specific meaning: it could return a unique normal + form, simplify the expression a bit, or just do nothing. + """ + return x + + def __add__(self, e): + if not isinstance(e, Ideal): + R = self.ring.quotient_ring(self) + if isinstance(e, R.dtype): + return e + if isinstance(e, R.ring.dtype): + return R(e) + return R.convert(e) + self._check_ideal(e) + return self.union(e) + + __radd__ = __add__ + + def __mul__(self, e): + if not isinstance(e, Ideal): + try: + e = self.ring.ideal(e) + except CoercionFailed: + return NotImplemented + self._check_ideal(e) + return self.product(e) + + __rmul__ = __mul__ + + def _zeroth_power(self): + return self.ring.ideal(1) + + def _first_power(self): + # Raising to any power but 1 returns a new instance. So we mult by 1 + # here so that the first power is no exception. + return self * 1 + + def __eq__(self, e): + if not isinstance(e, Ideal) or e.ring != self.ring: + return False + return self._equals(e) + + def __ne__(self, e): + return not (self == e) + + +class ModuleImplementedIdeal(Ideal): + """ + Ideal implementation relying on the modules code. + + Attributes: + + - _module - the underlying module + """ + + def __init__(self, ring, module): + Ideal.__init__(self, ring) + self._module = module + + def _contains_elem(self, x): + return self._module.contains([x]) + + def _contains_ideal(self, J): + if not isinstance(J, ModuleImplementedIdeal): + raise NotImplementedError + return self._module.is_submodule(J._module) + + def _intersect(self, J): + if not isinstance(J, ModuleImplementedIdeal): + raise NotImplementedError + return self.__class__(self.ring, self._module.intersect(J._module)) + + def _quotient(self, J, **opts): + if not isinstance(J, ModuleImplementedIdeal): + raise NotImplementedError + return self._module.module_quotient(J._module, **opts) + + def _union(self, J): + if not isinstance(J, ModuleImplementedIdeal): + raise NotImplementedError + return self.__class__(self.ring, self._module.union(J._module)) + + @property + def gens(self): + """ + Return generators for ``self``. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x, y + >>> list(QQ.old_poly_ring(x, y).ideal(x, y, x**2 + y).gens) + [DMP_Python([[1], []], QQ), DMP_Python([[1, 0]], QQ), DMP_Python([[1], [], [1, 0]], QQ)] + """ + return (x[0] for x in self._module.gens) + + def is_zero(self): + """ + Return True if ``self`` is the zero ideal. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).ideal(x).is_zero() + False + >>> QQ.old_poly_ring(x).ideal().is_zero() + True + """ + return self._module.is_zero() + + def is_whole_ring(self): + """ + Return True if ``self`` is the whole ring, i.e. one generator is a unit. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ, ilex + >>> QQ.old_poly_ring(x).ideal(x).is_whole_ring() + False + >>> QQ.old_poly_ring(x).ideal(3).is_whole_ring() + True + >>> QQ.old_poly_ring(x, order=ilex).ideal(2 + x).is_whole_ring() + True + """ + return self._module.is_full_module() + + def __repr__(self): + from sympy.printing.str import sstr + gens = [self.ring.to_sympy(x) for [x] in self._module.gens] + return '<' + ','.join(sstr(g) for g in gens) + '>' + + # NOTE this is the only method using the fact that the module is a SubModule + def _product(self, J): + if not isinstance(J, ModuleImplementedIdeal): + raise NotImplementedError + return self.__class__(self.ring, self._module.submodule( + *[[x*y] for [x] in self._module.gens for [y] in J._module.gens])) + + def in_terms_of_generators(self, e): + """ + Express ``e`` in terms of the generators of ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> I = QQ.old_poly_ring(x).ideal(x**2 + 1, x) + >>> I.in_terms_of_generators(1) # doctest: +SKIP + [DMP_Python([1], QQ), DMP_Python([-1, 0], QQ)] + """ + return self._module.in_terms_of_generators([e]) + + def reduce_element(self, x, **options): + return self._module.reduce_element([x], **options)[0] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/modules.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2e2ed814f4143b4b49f8b1f10c2a07cb32d06a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/modules.py @@ -0,0 +1,1488 @@ +""" +Computations with modules over polynomial rings. + +This module implements various classes that encapsulate groebner basis +computations for modules. Most of them should not be instantiated by hand. +Instead, use the constructing routines on objects you already have. + +For example, to construct a free module over ``QQ[x, y]``, call +``QQ[x, y].free_module(rank)`` instead of the ``FreeModule`` constructor. +In fact ``FreeModule`` is an abstract base class that should not be +instantiated, the ``free_module`` method instead returns the implementing class +``FreeModulePolyRing``. + +In general, the abstract base classes implement most functionality in terms of +a few non-implemented methods. The concrete base classes supply only these +non-implemented methods. They may also supply new implementations of the +convenience methods, for example if there are faster algorithms available. +""" + + +from copy import copy +from functools import reduce + +from sympy.polys.agca.ideals import Ideal +from sympy.polys.domains.field import Field +from sympy.polys.orderings import ProductOrder, monomial_key +from sympy.polys.polyclasses import DMP +from sympy.polys.polyerrors import CoercionFailed +from sympy.core.basic import _aresame +from sympy.utilities.iterables import iterable + +# TODO +# - module saturation +# - module quotient/intersection for quotient rings +# - free resoltutions / syzygies +# - finding small/minimal generating sets +# - ... + +########################################################################## +## Abstract base classes ################################################# +########################################################################## + + +class Module: + """ + Abstract base class for modules. + + Do not instantiate - use ring explicit constructors instead: + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> QQ.old_poly_ring(x).free_module(2) + QQ[x]**2 + + Attributes: + + - dtype - type of elements + - ring - containing ring + + Non-implemented methods: + + - submodule + - quotient_module + - is_zero + - is_submodule + - multiply_ideal + + The method convert likely needs to be changed in subclasses. + """ + + def __init__(self, ring): + self.ring = ring + + def convert(self, elem, M=None): + """ + Convert ``elem`` into internal representation of this module. + + If ``M`` is not None, it should be a module containing it. + """ + if not isinstance(elem, self.dtype): + raise CoercionFailed + return elem + + def submodule(self, *gens): + """Generate a submodule.""" + raise NotImplementedError + + def quotient_module(self, other): + """Generate a quotient module.""" + raise NotImplementedError + + def __truediv__(self, e): + if not isinstance(e, Module): + e = self.submodule(*e) + return self.quotient_module(e) + + def contains(self, elem): + """Return True if ``elem`` is an element of this module.""" + try: + self.convert(elem) + return True + except CoercionFailed: + return False + + def __contains__(self, elem): + return self.contains(elem) + + def subset(self, other): + """ + Returns True if ``other`` is is a subset of ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> F.subset([(1, x), (x, 2)]) + True + >>> F.subset([(1/x, x), (x, 2)]) + False + """ + return all(self.contains(x) for x in other) + + def __eq__(self, other): + return self.is_submodule(other) and other.is_submodule(self) + + def __ne__(self, other): + return not (self == other) + + def is_zero(self): + """Returns True if ``self`` is a zero module.""" + raise NotImplementedError + + def is_submodule(self, other): + """Returns True if ``other`` is a submodule of ``self``.""" + raise NotImplementedError + + def multiply_ideal(self, other): + """ + Multiply ``self`` by the ideal ``other``. + """ + raise NotImplementedError + + def __mul__(self, e): + if not isinstance(e, Ideal): + try: + e = self.ring.ideal(e) + except (CoercionFailed, NotImplementedError): + return NotImplemented + return self.multiply_ideal(e) + + __rmul__ = __mul__ + + def identity_hom(self): + """Return the identity homomorphism on ``self``.""" + raise NotImplementedError + + +class ModuleElement: + """ + Base class for module element wrappers. + + Use this class to wrap primitive data types as module elements. It stores + a reference to the containing module, and implements all the arithmetic + operators. + + Attributes: + + - module - containing module + - data - internal data + + Methods that likely need change in subclasses: + + - add + - mul + - div + - eq + """ + + def __init__(self, module, data): + self.module = module + self.data = data + + def add(self, d1, d2): + """Add data ``d1`` and ``d2``.""" + return d1 + d2 + + def mul(self, m, d): + """Multiply module data ``m`` by coefficient d.""" + return m * d + + def div(self, m, d): + """Divide module data ``m`` by coefficient d.""" + return m / d + + def eq(self, d1, d2): + """Return true if d1 and d2 represent the same element.""" + return d1 == d2 + + def __add__(self, om): + if not isinstance(om, self.__class__) or om.module != self.module: + try: + om = self.module.convert(om) + except CoercionFailed: + return NotImplemented + return self.__class__(self.module, self.add(self.data, om.data)) + + __radd__ = __add__ + + def __neg__(self): + return self.__class__(self.module, self.mul(self.data, + self.module.ring.convert(-1))) + + def __sub__(self, om): + if not isinstance(om, self.__class__) or om.module != self.module: + try: + om = self.module.convert(om) + except CoercionFailed: + return NotImplemented + return self.__add__(-om) + + def __rsub__(self, om): + return (-self).__add__(om) + + def __mul__(self, o): + if not isinstance(o, self.module.ring.dtype): + try: + o = self.module.ring.convert(o) + except CoercionFailed: + return NotImplemented + return self.__class__(self.module, self.mul(self.data, o)) + + __rmul__ = __mul__ + + def __truediv__(self, o): + if not isinstance(o, self.module.ring.dtype): + try: + o = self.module.ring.convert(o) + except CoercionFailed: + return NotImplemented + return self.__class__(self.module, self.div(self.data, o)) + + def __eq__(self, om): + if not isinstance(om, self.__class__) or om.module != self.module: + try: + om = self.module.convert(om) + except CoercionFailed: + return False + return self.eq(self.data, om.data) + + def __ne__(self, om): + return not self == om + +########################################################################## +## Free Modules ########################################################## +########################################################################## + + +class FreeModuleElement(ModuleElement): + """Element of a free module. Data stored as a tuple.""" + + def add(self, d1, d2): + return tuple(x + y for x, y in zip(d1, d2)) + + def mul(self, d, p): + return tuple(x * p for x in d) + + def div(self, d, p): + return tuple(x / p for x in d) + + def __repr__(self): + from sympy.printing.str import sstr + data = self.data + if any(isinstance(x, DMP) for x in data): + data = [self.module.ring.to_sympy(x) for x in data] + return '[' + ', '.join(sstr(x) for x in data) + ']' + + def __iter__(self): + return self.data.__iter__() + + def __getitem__(self, idx): + return self.data[idx] + + +class FreeModule(Module): + """ + Abstract base class for free modules. + + Additional attributes: + + - rank - rank of the free module + + Non-implemented methods: + + - submodule + """ + + dtype = FreeModuleElement + + def __init__(self, ring, rank): + Module.__init__(self, ring) + self.rank = rank + + def __repr__(self): + return repr(self.ring) + "**" + repr(self.rank) + + def is_submodule(self, other): + """ + Returns True if ``other`` is a submodule of ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> M = F.submodule([2, x]) + >>> F.is_submodule(F) + True + >>> F.is_submodule(M) + True + >>> M.is_submodule(F) + False + """ + if isinstance(other, SubModule): + return other.container == self + if isinstance(other, FreeModule): + return other.ring == self.ring and other.rank == self.rank + return False + + def convert(self, elem, M=None): + """ + Convert ``elem`` into the internal representation. + + This method is called implicitly whenever computations involve elements + not in the internal representation. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> F.convert([1, 0]) + [1, 0] + """ + if isinstance(elem, FreeModuleElement): + if elem.module is self: + return elem + if elem.module.rank != self.rank: + raise CoercionFailed + return FreeModuleElement(self, + tuple(self.ring.convert(x, elem.module.ring) for x in elem.data)) + elif iterable(elem): + tpl = tuple(self.ring.convert(x) for x in elem) + if len(tpl) != self.rank: + raise CoercionFailed + return FreeModuleElement(self, tpl) + elif _aresame(elem, 0): + return FreeModuleElement(self, (self.ring.convert(0),)*self.rank) + else: + raise CoercionFailed + + def is_zero(self): + """ + Returns True if ``self`` is a zero module. + + (If, as this implementation assumes, the coefficient ring is not the + zero ring, then this is equivalent to the rank being zero.) + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(0).is_zero() + True + >>> QQ.old_poly_ring(x).free_module(1).is_zero() + False + """ + return self.rank == 0 + + def basis(self): + """ + Return a set of basis elements. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(3).basis() + ([1, 0, 0], [0, 1, 0], [0, 0, 1]) + """ + from sympy.matrices import eye + M = eye(self.rank) + return tuple(self.convert(M.row(i)) for i in range(self.rank)) + + def quotient_module(self, submodule): + """ + Return a quotient module. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> M = QQ.old_poly_ring(x).free_module(2) + >>> M.quotient_module(M.submodule([1, x], [x, 2])) + QQ[x]**2/<[1, x], [x, 2]> + + Or more conicisely, using the overloaded division operator: + + >>> QQ.old_poly_ring(x).free_module(2) / [[1, x], [x, 2]] + QQ[x]**2/<[1, x], [x, 2]> + """ + return QuotientModule(self.ring, self, submodule) + + def multiply_ideal(self, other): + """ + Multiply ``self`` by the ideal ``other``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> I = QQ.old_poly_ring(x).ideal(x) + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> F.multiply_ideal(I) + <[x, 0], [0, x]> + """ + return self.submodule(*self.basis()).multiply_ideal(other) + + def identity_hom(self): + """ + Return the identity homomorphism on ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(2).identity_hom() + Matrix([ + [1, 0], : QQ[x]**2 -> QQ[x]**2 + [0, 1]]) + """ + from sympy.polys.agca.homomorphisms import homomorphism + return homomorphism(self, self, self.basis()) + + +class FreeModulePolyRing(FreeModule): + """ + Free module over a generalized polynomial ring. + + Do not instantiate this, use the constructor method of the ring instead: + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(3) + >>> F + QQ[x]**3 + >>> F.contains([x, 1, 0]) + True + >>> F.contains([1/x, 0, 1]) + False + """ + + def __init__(self, ring, rank): + from sympy.polys.domains.old_polynomialring import PolynomialRingBase + FreeModule.__init__(self, ring, rank) + if not isinstance(ring, PolynomialRingBase): + raise NotImplementedError('This implementation only works over ' + + 'polynomial rings, got %s' % ring) + if not isinstance(ring.dom, Field): + raise NotImplementedError('Ground domain must be a field, ' + + 'got %s' % ring.dom) + + def submodule(self, *gens, **opts): + """ + Generate a submodule. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, x + y]) + >>> M + <[x, x + y]> + >>> M.contains([2*x, 2*x + 2*y]) + True + >>> M.contains([x, y]) + False + """ + return SubModulePolyRing(gens, self, **opts) + + +class FreeModuleQuotientRing(FreeModule): + """ + Free module over a quotient ring. + + Do not instantiate this, use the constructor method of the ring instead: + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(3) + >>> F + (QQ[x]/)**3 + + Attributes + + - quot - the quotient module `R^n / IR^n`, where `R/I` is our ring + """ + + def __init__(self, ring, rank): + from sympy.polys.domains.quotientring import QuotientRing + FreeModule.__init__(self, ring, rank) + if not isinstance(ring, QuotientRing): + raise NotImplementedError('This implementation only works over ' + + 'quotient rings, got %s' % ring) + F = self.ring.ring.free_module(self.rank) + self.quot = F / (self.ring.base_ideal*F) + + def __repr__(self): + return "(" + repr(self.ring) + ")" + "**" + repr(self.rank) + + def submodule(self, *gens, **opts): + """ + Generate a submodule. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y]) + >>> M + <[x + , x + y + ]> + >>> M.contains([y**2, x**2 + x*y]) + True + >>> M.contains([x, y]) + False + """ + return SubModuleQuotientRing(gens, self, **opts) + + def lift(self, elem): + """ + Lift the element ``elem`` of self to the module self.quot. + + Note that self.quot is the same set as self, just as an R-module + and not as an R/I-module, so this makes sense. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) + >>> e = F.convert([1, 0]) + >>> e + [1 + , 0 + ] + >>> L = F.quot + >>> l = F.lift(e) + >>> l + [1, 0] + <[x**2 + 1, 0], [0, x**2 + 1]> + >>> L.contains(l) + True + """ + return self.quot.convert([x.data for x in elem]) + + def unlift(self, elem): + """ + Push down an element of self.quot to self. + + This undoes ``lift``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) + >>> e = F.convert([1, 0]) + >>> l = F.lift(e) + >>> e == l + False + >>> e == F.unlift(l) + True + """ + return self.convert(elem.data) + +########################################################################## +## Submodules and subquotients ########################################### +########################################################################## + + +class SubModule(Module): + """ + Base class for submodules. + + Attributes: + + - container - containing module + - gens - generators (subset of containing module) + - rank - rank of containing module + + Non-implemented methods: + + - _contains + - _syzygies + - _in_terms_of_generators + - _intersect + - _module_quotient + + Methods that likely need change in subclasses: + + - reduce_element + """ + + def __init__(self, gens, container): + Module.__init__(self, container.ring) + self.gens = tuple(container.convert(x) for x in gens) + self.container = container + self.rank = container.rank + self.ring = container.ring + self.dtype = container.dtype + + def __repr__(self): + return "<" + ", ".join(repr(x) for x in self.gens) + ">" + + def _contains(self, other): + """Implementation of containment. + Other is guaranteed to be FreeModuleElement.""" + raise NotImplementedError + + def _syzygies(self): + """Implementation of syzygy computation wrt self generators.""" + raise NotImplementedError + + def _in_terms_of_generators(self, e): + """Implementation of expression in terms of generators.""" + raise NotImplementedError + + def convert(self, elem, M=None): + """ + Convert ``elem`` into the internal represantition. + + Mostly called implicitly. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, x]) + >>> M.convert([2, 2*x]) + [2, 2*x] + """ + if isinstance(elem, self.container.dtype) and elem.module is self: + return elem + r = copy(self.container.convert(elem, M)) + r.module = self + if not self._contains(r): + raise CoercionFailed + return r + + def _intersect(self, other): + """Implementation of intersection. + Other is guaranteed to be a submodule of same free module.""" + raise NotImplementedError + + def _module_quotient(self, other): + """Implementation of quotient. + Other is guaranteed to be a submodule of same free module.""" + raise NotImplementedError + + def intersect(self, other, **options): + """ + Returns the intersection of ``self`` with submodule ``other``. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x, y).free_module(2) + >>> F.submodule([x, x]).intersect(F.submodule([y, y])) + <[x*y, x*y]> + + Some implementation allow further options to be passed. Currently, to + only one implemented is ``relations=True``, in which case the function + will return a triple ``(res, rela, relb)``, where ``res`` is the + intersection module, and ``rela`` and ``relb`` are lists of coefficient + vectors, expressing the generators of ``res`` in terms of the + generators of ``self`` (``rela``) and ``other`` (``relb``). + + >>> F.submodule([x, x]).intersect(F.submodule([y, y]), relations=True) + (<[x*y, x*y]>, [(DMP_Python([[1, 0]], QQ),)], [(DMP_Python([[1], []], QQ),)]) + + The above result says: the intersection module is generated by the + single element `(-xy, -xy) = -y (x, x) = -x (y, y)`, where + `(x, x)` and `(y, y)` respectively are the unique generators of + the two modules being intersected. + """ + if not isinstance(other, SubModule): + raise TypeError('%s is not a SubModule' % other) + if other.container != self.container: + raise ValueError( + '%s is contained in a different free module' % other) + return self._intersect(other, **options) + + def module_quotient(self, other, **options): + r""" + Returns the module quotient of ``self`` by submodule ``other``. + + That is, if ``self`` is the module `M` and ``other`` is `N`, then + return the ideal `\{f \in R | fN \subset M\}`. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.abc import x, y + >>> F = QQ.old_poly_ring(x, y).free_module(2) + >>> S = F.submodule([x*y, x*y]) + >>> T = F.submodule([x, x]) + >>> S.module_quotient(T) + + + Some implementations allow further options to be passed. Currently, the + only one implemented is ``relations=True``, which may only be passed + if ``other`` is principal. In this case the function + will return a pair ``(res, rel)`` where ``res`` is the ideal, and + ``rel`` is a list of coefficient vectors, expressing the generators of + the ideal, multiplied by the generator of ``other`` in terms of + generators of ``self``. + + >>> S.module_quotient(T, relations=True) + (, [[DMP_Python([[1]], QQ)]]) + + This means that the quotient ideal is generated by the single element + `y`, and that `y (x, x) = 1 (xy, xy)`, `(x, x)` and `(xy, xy)` being + the generators of `T` and `S`, respectively. + """ + if not isinstance(other, SubModule): + raise TypeError('%s is not a SubModule' % other) + if other.container != self.container: + raise ValueError( + '%s is contained in a different free module' % other) + return self._module_quotient(other, **options) + + def union(self, other): + """ + Returns the module generated by the union of ``self`` and ``other``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(1) + >>> M = F.submodule([x**2 + x]) # + >>> N = F.submodule([x**2 - 1]) # <(x-1)(x+1)> + >>> M.union(N) == F.submodule([x+1]) + True + """ + if not isinstance(other, SubModule): + raise TypeError('%s is not a SubModule' % other) + if other.container != self.container: + raise ValueError( + '%s is contained in a different free module' % other) + return self.__class__(self.gens + other.gens, self.container) + + def is_zero(self): + """ + Return True if ``self`` is a zero module. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> F.submodule([x, 1]).is_zero() + False + >>> F.submodule([0, 0]).is_zero() + True + """ + return all(x == 0 for x in self.gens) + + def submodule(self, *gens): + """ + Generate a submodule. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> M = QQ.old_poly_ring(x).free_module(2).submodule([x, 1]) + >>> M.submodule([x**2, x]) + <[x**2, x]> + """ + if not self.subset(gens): + raise ValueError('%s not a subset of %s' % (gens, self)) + return self.__class__(gens, self.container) + + def is_full_module(self): + """ + Return True if ``self`` is the entire free module. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> F.submodule([x, 1]).is_full_module() + False + >>> F.submodule([1, 1], [1, 2]).is_full_module() + True + """ + return all(self.contains(x) for x in self.container.basis()) + + def is_submodule(self, other): + """ + Returns True if ``other`` is a submodule of ``self``. + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> M = F.submodule([2, x]) + >>> N = M.submodule([2*x, x**2]) + >>> M.is_submodule(M) + True + >>> M.is_submodule(N) + True + >>> N.is_submodule(M) + False + """ + if isinstance(other, SubModule): + return self.container == other.container and \ + all(self.contains(x) for x in other.gens) + if isinstance(other, (FreeModule, QuotientModule)): + return self.container == other and self.is_full_module() + return False + + def syzygy_module(self, **opts): + r""" + Compute the syzygy module of the generators of ``self``. + + Suppose `M` is generated by `f_1, \ldots, f_n` over the ring + `R`. Consider the homomorphism `\phi: R^n \to M`, given by + sending `(r_1, \ldots, r_n) \to r_1 f_1 + \cdots + r_n f_n`. + The syzygy module is defined to be the kernel of `\phi`. + + Examples + ======== + + The syzygy module is zero iff the generators generate freely a free + submodule: + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(2).submodule([1, 0], [1, 1]).syzygy_module().is_zero() + True + + A slightly more interesting example: + + >>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, 2*x], [y, 2*y]) + >>> S = QQ.old_poly_ring(x, y).free_module(2).submodule([y, -x]) + >>> M.syzygy_module() == S + True + """ + F = self.ring.free_module(len(self.gens)) + # NOTE we filter out zero syzygies. This is for convenience of the + # _syzygies function and not meant to replace any real "generating set + # reduction" algorithm + return F.submodule(*[x for x in self._syzygies() if F.convert(x) != 0], + **opts) + + def in_terms_of_generators(self, e): + """ + Express element ``e`` of ``self`` in terms of the generators. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> M = F.submodule([1, 0], [1, 1]) + >>> M.in_terms_of_generators([x, x**2]) # doctest: +SKIP + [DMP_Python([-1, 1, 0], QQ), DMP_Python([1, 0, 0], QQ)] + """ + try: + e = self.convert(e) + except CoercionFailed: + raise ValueError('%s is not an element of %s' % (e, self)) + return self._in_terms_of_generators(e) + + def reduce_element(self, x): + """ + Reduce the element ``x`` of our ring modulo the ideal ``self``. + + Here "reduce" has no specific meaning, it could return a unique normal + form, simplify the expression a bit, or just do nothing. + """ + return x + + def quotient_module(self, other, **opts): + """ + Return a quotient module. + + This is the same as taking a submodule of a quotient of the containing + module. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> S1 = F.submodule([x, 1]) + >>> S2 = F.submodule([x**2, x]) + >>> S1.quotient_module(S2) + <[x, 1] + <[x**2, x]>> + + Or more coincisely, using the overloaded division operator: + + >>> F.submodule([x, 1]) / [(x**2, x)] + <[x, 1] + <[x**2, x]>> + """ + if not self.is_submodule(other): + raise ValueError('%s not a submodule of %s' % (other, self)) + return SubQuotientModule(self.gens, + self.container.quotient_module(other), **opts) + + def __add__(self, oth): + return self.container.quotient_module(self).convert(oth) + + __radd__ = __add__ + + def multiply_ideal(self, I): + """ + Multiply ``self`` by the ideal ``I``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> I = QQ.old_poly_ring(x).ideal(x**2) + >>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, 1]) + >>> I*M + <[x**2, x**2]> + """ + return self.submodule(*[x*g for [x] in I._module.gens for g in self.gens]) + + def inclusion_hom(self): + """ + Return a homomorphism representing the inclusion map of ``self``. + + That is, the natural map from ``self`` to ``self.container``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).inclusion_hom() + Matrix([ + [1, 0], : <[x, x]> -> QQ[x]**2 + [0, 1]]) + """ + return self.container.identity_hom().restrict_domain(self) + + def identity_hom(self): + """ + Return the identity homomorphism on ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).identity_hom() + Matrix([ + [1, 0], : <[x, x]> -> <[x, x]> + [0, 1]]) + """ + return self.container.identity_hom().restrict_domain( + self).restrict_codomain(self) + + +class SubQuotientModule(SubModule): + """ + Submodule of a quotient module. + + Equivalently, quotient module of a submodule. + + Do not instantiate this, instead use the submodule or quotient_module + constructing methods: + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> S = F.submodule([1, 0], [1, x]) + >>> Q = F/[(1, 0)] + >>> S/[(1, 0)] == Q.submodule([5, x]) + True + + Attributes: + + - base - base module we are quotient of + - killed_module - submodule used to form the quotient + """ + def __init__(self, gens, container, **opts): + SubModule.__init__(self, gens, container) + self.killed_module = self.container.killed_module + # XXX it is important for some code below that the generators of base + # are in this particular order! + self.base = self.container.base.submodule( + *[x.data for x in self.gens], **opts).union(self.killed_module) + + def _contains(self, elem): + return self.base.contains(elem.data) + + def _syzygies(self): + # let N = self.killed_module be generated by e_1, ..., e_r + # let F = self.base be generated by f_1, ..., f_s and e_1, ..., e_r + # Then self = F/N. + # Let phi: R**s --> self be the evident surjection. + # Similarly psi: R**(s + r) --> F. + # We need to find generators for ker(phi). Let chi: R**s --> F be the + # evident lift of phi. For X in R**s, phi(X) = 0 iff chi(X) is + # contained in N, iff there exists Y in R**r such that + # psi(X, Y) = 0. + # Hence if alpha: R**(s + r) --> R**s is the projection map, then + # ker(phi) = alpha ker(psi). + return [X[:len(self.gens)] for X in self.base._syzygies()] + + def _in_terms_of_generators(self, e): + return self.base._in_terms_of_generators(e.data)[:len(self.gens)] + + def is_full_module(self): + """ + Return True if ``self`` is the entire free module. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> F.submodule([x, 1]).is_full_module() + False + >>> F.submodule([1, 1], [1, 2]).is_full_module() + True + """ + return self.base.is_full_module() + + def quotient_hom(self): + """ + Return the quotient homomorphism to self. + + That is, return the natural map from ``self.base`` to ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> M = (QQ.old_poly_ring(x).free_module(2) / [(1, x)]).submodule([1, 0]) + >>> M.quotient_hom() + Matrix([ + [1, 0], : <[1, 0], [1, x]> -> <[1, 0] + <[1, x]>, [1, x] + <[1, x]>> + [0, 1]]) + """ + return self.base.identity_hom().quotient_codomain(self.killed_module) + + +_subs0 = lambda x: x[0] +_subs1 = lambda x: x[1:] + + +class ModuleOrder(ProductOrder): + """A product monomial order with a zeroth term as module index.""" + + def __init__(self, o1, o2, TOP): + if TOP: + ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0)) + else: + ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1)) + + +class SubModulePolyRing(SubModule): + """ + Submodule of a free module over a generalized polynomial ring. + + Do not instantiate this, use the constructor method of FreeModule instead: + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x, y).free_module(2) + >>> F.submodule([x, y], [1, 0]) + <[x, y], [1, 0]> + + Attributes: + + - order - monomial order used + """ + + #self._gb - cached groebner basis + #self._gbe - cached groebner basis relations + + def __init__(self, gens, container, order="lex", TOP=True): + SubModule.__init__(self, gens, container) + if not isinstance(container, FreeModulePolyRing): + raise NotImplementedError('This implementation is for submodules of ' + + 'FreeModulePolyRing, got %s' % container) + self.order = ModuleOrder(monomial_key(order), self.ring.order, TOP) + self._gb = None + self._gbe = None + + def __eq__(self, other): + if isinstance(other, SubModulePolyRing) and self.order != other.order: + return False + return SubModule.__eq__(self, other) + + def _groebner(self, extended=False): + """Returns a standard basis in sdm form.""" + from sympy.polys.distributedmodules import sdm_groebner, sdm_nf_mora + if self._gbe is None and extended: + gb, gbe = sdm_groebner( + [self.ring._vector_to_sdm(x, self.order) for x in self.gens], + sdm_nf_mora, self.order, self.ring.dom, extended=True) + self._gb, self._gbe = tuple(gb), tuple(gbe) + if self._gb is None: + self._gb = tuple(sdm_groebner( + [self.ring._vector_to_sdm(x, self.order) for x in self.gens], + sdm_nf_mora, self.order, self.ring.dom)) + if extended: + return self._gb, self._gbe + else: + return self._gb + + def _groebner_vec(self, extended=False): + """Returns a standard basis in element form.""" + if not extended: + return [FreeModuleElement(self, + tuple(self.ring._sdm_to_vector(x, self.rank))) + for x in self._groebner()] + gb, gbe = self._groebner(extended=True) + return ([self.convert(self.ring._sdm_to_vector(x, self.rank)) + for x in gb], + [self.ring._sdm_to_vector(x, len(self.gens)) for x in gbe]) + + def _contains(self, x): + from sympy.polys.distributedmodules import sdm_zero, sdm_nf_mora + return sdm_nf_mora(self.ring._vector_to_sdm(x, self.order), + self._groebner(), self.order, self.ring.dom) == \ + sdm_zero() + + def _syzygies(self): + """Compute syzygies. See [SCA, algorithm 2.5.4].""" + # NOTE if self.gens is a standard basis, this can be done more + # efficiently using Schreyer's theorem + + # First bullet point + k = len(self.gens) + r = self.rank + zero = self.ring.convert(0) + one = self.ring.convert(1) + Rkr = self.ring.free_module(r + k) + newgens = [] + for j, f in enumerate(self.gens): + m = [0]*(r + k) + for i, v in enumerate(f): + m[i] = v + for i in range(k): + m[r + i] = one if j == i else zero + m = FreeModuleElement(Rkr, tuple(m)) + newgens.append(m) + # Note: we need *descending* order on module index, and TOP=False to + # get an elimination order + F = Rkr.submodule(*newgens, order='ilex', TOP=False) + + # Second bullet point: standard basis of F + G = F._groebner_vec() + + # Third bullet point: G0 = G intersect the new k components + G0 = [x[r:] for x in G if all(y == zero for y in x[:r])] + + # Fourth and fifth bullet points: we are done + return G0 + + def _in_terms_of_generators(self, e): + """Expression in terms of generators. See [SCA, 2.8.1].""" + # NOTE: if gens is a standard basis, this can be done more efficiently + M = self.ring.free_module(self.rank).submodule(*((e,) + self.gens)) + S = M.syzygy_module( + order="ilex", TOP=False) # We want decreasing order! + G = S._groebner_vec() + # This list cannot not be empty since e is an element + e = [x for x in G if self.ring.is_unit(x[0])][0] + return [-x/e[0] for x in e[1:]] + + def reduce_element(self, x, NF=None): + """ + Reduce the element ``x`` of our container modulo ``self``. + + This applies the normal form ``NF`` to ``x``. If ``NF`` is passed + as none, the default Mora normal form is used (which is not unique!). + """ + from sympy.polys.distributedmodules import sdm_nf_mora + if NF is None: + NF = sdm_nf_mora + return self.container.convert(self.ring._sdm_to_vector(NF( + self.ring._vector_to_sdm(x, self.order), self._groebner(), + self.order, self.ring.dom), + self.rank)) + + def _intersect(self, other, relations=False): + # See: [SCA, section 2.8.2] + fi = self.gens + hi = other.gens + r = self.rank + ci = [[0]*(2*r) for _ in range(r)] + for k in range(r): + ci[k][k] = 1 + ci[k][r + k] = 1 + di = [list(f) + [0]*r for f in fi] + ei = [[0]*r + list(h) for h in hi] + syz = self.ring.free_module(2*r).submodule(*(ci + di + ei))._syzygies() + nonzero = [x for x in syz if any(y != self.ring.zero for y in x[:r])] + res = self.container.submodule(*([-y for y in x[:r]] for x in nonzero)) + reln1 = [x[r:r + len(fi)] for x in nonzero] + reln2 = [x[r + len(fi):] for x in nonzero] + if relations: + return res, reln1, reln2 + return res + + def _module_quotient(self, other, relations=False): + # See: [SCA, section 2.8.4] + if relations and len(other.gens) != 1: + raise NotImplementedError + if len(other.gens) == 0: + return self.ring.ideal(1) + elif len(other.gens) == 1: + # We do some trickery. Let f be the (vector!) generating ``other`` + # and f1, .., fn be the (vectors) generating self. + # Consider the submodule of R^{r+1} generated by (f, 1) and + # {(fi, 0) | i}. Then the intersection with the last module + # component yields the quotient. + g1 = list(other.gens[0]) + [1] + gi = [list(x) + [0] for x in self.gens] + # NOTE: We *need* to use an elimination order + M = self.ring.free_module(self.rank + 1).submodule(*([g1] + gi), + order='ilex', TOP=False) + if not relations: + return self.ring.ideal(*[x[-1] for x in M._groebner_vec() if + all(y == self.ring.zero for y in x[:-1])]) + else: + G, R = M._groebner_vec(extended=True) + indices = [i for i, x in enumerate(G) if + all(y == self.ring.zero for y in x[:-1])] + return (self.ring.ideal(*[G[i][-1] for i in indices]), + [[-x for x in R[i][1:]] for i in indices]) + # For more generators, we use I : = intersection of + # {I : | i} + # TODO this can be done more efficiently + return reduce(lambda x, y: x.intersect(y), + (self._module_quotient(self.container.submodule(x)) for x in other.gens)) + + +class SubModuleQuotientRing(SubModule): + """ + Class for submodules of free modules over quotient rings. + + Do not instantiate this. Instead use the submodule methods. + + >>> from sympy.abc import x, y + >>> from sympy import QQ + >>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y]) + >>> M + <[x + , x + y + ]> + >>> M.contains([y**2, x**2 + x*y]) + True + >>> M.contains([x, y]) + False + + Attributes: + + - quot - the subquotient of `R^n/IR^n` generated by lifts of our generators + """ + + def __init__(self, gens, container): + SubModule.__init__(self, gens, container) + self.quot = self.container.quot.submodule( + *[self.container.lift(x) for x in self.gens]) + + def _contains(self, elem): + return self.quot._contains(self.container.lift(elem)) + + def _syzygies(self): + return [tuple(self.ring.convert(y, self.quot.ring) for y in x) + for x in self.quot._syzygies()] + + def _in_terms_of_generators(self, elem): + return [self.ring.convert(x, self.quot.ring) for x in + self.quot._in_terms_of_generators(self.container.lift(elem))] + +########################################################################## +## Quotient Modules ###################################################### +########################################################################## + + +class QuotientModuleElement(ModuleElement): + """Element of a quotient module.""" + + def eq(self, d1, d2): + """Equality comparison.""" + return self.module.killed_module.contains(d1 - d2) + + def __repr__(self): + return repr(self.data) + " + " + repr(self.module.killed_module) + + +class QuotientModule(Module): + """ + Class for quotient modules. + + Do not instantiate this directly. For subquotients, see the + SubQuotientModule class. + + Attributes: + + - base - the base module we are a quotient of + - killed_module - the submodule used to form the quotient + - rank of the base + """ + + dtype = QuotientModuleElement + + def __init__(self, ring, base, submodule): + Module.__init__(self, ring) + if not base.is_submodule(submodule): + raise ValueError('%s is not a submodule of %s' % (submodule, base)) + self.base = base + self.killed_module = submodule + self.rank = base.rank + + def __repr__(self): + return repr(self.base) + "/" + repr(self.killed_module) + + def is_zero(self): + """ + Return True if ``self`` is a zero module. + + This happens if and only if the base module is the same as the + submodule being killed. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) + >>> (F/[(1, 0)]).is_zero() + False + >>> (F/[(1, 0), (0, 1)]).is_zero() + True + """ + return self.base == self.killed_module + + def is_submodule(self, other): + """ + Return True if ``other`` is a submodule of ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)] + >>> S = Q.submodule([1, 0]) + >>> Q.is_submodule(S) + True + >>> S.is_submodule(Q) + False + """ + if isinstance(other, QuotientModule): + return self.killed_module == other.killed_module and \ + self.base.is_submodule(other.base) + if isinstance(other, SubQuotientModule): + return other.container == self + return False + + def submodule(self, *gens, **opts): + """ + Generate a submodule. + + This is the same as taking a quotient of a submodule of the base + module. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)] + >>> Q.submodule([x, 0]) + <[x, 0] + <[x, x]>> + """ + return SubQuotientModule(gens, self, **opts) + + def convert(self, elem, M=None): + """ + Convert ``elem`` into the internal representation. + + This method is called implicitly whenever computations involve elements + not in the internal representation. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> F = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] + >>> F.convert([1, 0]) + [1, 0] + <[1, 2], [1, x]> + """ + if isinstance(elem, QuotientModuleElement): + if elem.module is self: + return elem + if self.killed_module.is_submodule(elem.module.killed_module): + return QuotientModuleElement(self, self.base.convert(elem.data)) + raise CoercionFailed + return QuotientModuleElement(self, self.base.convert(elem)) + + def identity_hom(self): + """ + Return the identity homomorphism on ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] + >>> M.identity_hom() + Matrix([ + [1, 0], : QQ[x]**2/<[1, 2], [1, x]> -> QQ[x]**2/<[1, 2], [1, x]> + [0, 1]]) + """ + return self.base.identity_hom().quotient_codomain( + self.killed_module).quotient_domain(self.killed_module) + + def quotient_hom(self): + """ + Return the quotient homomorphism to ``self``. + + That is, return a homomorphism representing the natural map from + ``self.base`` to ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] + >>> M.quotient_hom() + Matrix([ + [1, 0], : QQ[x]**2 -> QQ[x]**2/<[1, 2], [1, x]> + [0, 1]]) + """ + return self.base.identity_hom().quotient_codomain( + self.killed_module) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_extensions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..4becf4fd800a7a34c16989adaaf97e312c18f01c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_extensions.py @@ -0,0 +1,196 @@ +from sympy.core.symbol import symbols +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.polys import QQ, ZZ +from sympy.polys.polytools import Poly +from sympy.polys.polyerrors import NotInvertible +from sympy.polys.agca.extensions import FiniteExtension +from sympy.polys.domainmatrix import DomainMatrix + +from sympy.testing.pytest import raises + +from sympy.abc import x, y, t + + +def test_FiniteExtension(): + # Gaussian integers + A = FiniteExtension(Poly(x**2 + 1, x)) + assert A.rank == 2 + assert str(A) == 'ZZ[x]/(x**2 + 1)' + i = A.generator + assert i.parent() is A + + assert i*i == A(-1) + raises(TypeError, lambda: i*()) + + assert A.basis == (A.one, i) + assert A(1) == A.one + assert i**2 == A(-1) + assert i**2 != -1 # no coercion + assert (2 + i)*(1 - i) == 3 - i + assert (1 + i)**8 == A(16) + assert A(1).inverse() == A(1) + raises(NotImplementedError, lambda: A(2).inverse()) + + # Finite field of order 27 + F = FiniteExtension(Poly(x**3 - x + 1, x, modulus=3)) + assert F.rank == 3 + a = F.generator # also generates the cyclic group F - {0} + assert F.basis == (F(1), a, a**2) + assert a**27 == a + assert a**26 == F(1) + assert a**13 == F(-1) + assert a**9 == a + 1 + assert a**3 == a - 1 + assert a**6 == a**2 + a + 1 + assert F(x**2 + x).inverse() == 1 - a + assert F(x + 2)**(-1) == F(x + 2).inverse() + assert a**19 * a**(-19) == F(1) + assert (a - 1) / (2*a**2 - 1) == a**2 + 1 + assert (a - 1) // (2*a**2 - 1) == a**2 + 1 + assert 2/(a**2 + 1) == a**2 - a + 1 + assert (a**2 + 1)/2 == -a**2 - 1 + raises(NotInvertible, lambda: F(0).inverse()) + + # Function field of an elliptic curve + K = FiniteExtension(Poly(t**2 - x**3 - x + 1, t, field=True)) + assert K.rank == 2 + assert str(K) == 'ZZ(x)[t]/(t**2 - x**3 - x + 1)' + y = K.generator + c = 1/(x**3 - x**2 + x - 1) + assert ((y + x)*(y - x)).inverse() == K(c) + assert (y + x)*(y - x)*c == K(1) # explicit inverse of y + x + + +def test_FiniteExtension_eq_hash(): + # Test eq and hash + p1 = Poly(x**2 - 2, x, domain=ZZ) + p2 = Poly(x**2 - 2, x, domain=QQ) + K1 = FiniteExtension(p1) + K2 = FiniteExtension(p2) + assert K1 == FiniteExtension(Poly(x**2 - 2)) + assert K2 != FiniteExtension(Poly(x**2 - 2)) + assert len({K1, K2, FiniteExtension(p1)}) == 2 + + +def test_FiniteExtension_mod(): + # Test mod + K = FiniteExtension(Poly(x**3 + 1, x, domain=QQ)) + xf = K(x) + assert (xf**2 - 1) % 1 == K.zero + assert 1 % (xf**2 - 1) == K.zero + assert (xf**2 - 1) / (xf - 1) == xf + 1 + assert (xf**2 - 1) // (xf - 1) == xf + 1 + assert (xf**2 - 1) % (xf - 1) == K.zero + raises(ZeroDivisionError, lambda: (xf**2 - 1) % 0) + raises(TypeError, lambda: xf % []) + raises(TypeError, lambda: [] % xf) + + # Test mod over ring + K = FiniteExtension(Poly(x**3 + 1, x, domain=ZZ)) + xf = K(x) + assert (xf**2 - 1) % 1 == K.zero + raises(NotImplementedError, lambda: (xf**2 - 1) % (xf - 1)) + + +def test_FiniteExtension_from_sympy(): + # Test to_sympy/from_sympy + K = FiniteExtension(Poly(x**3 + 1, x, domain=ZZ)) + xf = K(x) + assert K.from_sympy(x) == xf + assert K.to_sympy(xf) == x + + +def test_FiniteExtension_set_domain(): + KZ = FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')) + KQ = FiniteExtension(Poly(x**2 + 1, x, domain='QQ')) + assert KZ.set_domain(QQ) == KQ + + +def test_FiniteExtension_exquo(): + # Test exquo + K = FiniteExtension(Poly(x**4 + 1)) + xf = K(x) + assert K.exquo(xf**2 - 1, xf - 1) == xf + 1 + + +def test_FiniteExtension_convert(): + # Test from_MonogenicFiniteExtension + K1 = FiniteExtension(Poly(x**2 + 1)) + K2 = QQ[x] + x1, x2 = K1(x), K2(x) + assert K1.convert(x2) == x1 + assert K2.convert(x1) == x2 + + K = FiniteExtension(Poly(x**2 - 1, domain=QQ)) + assert K.convert_from(QQ(1, 2), QQ) == K.one/2 + + +def test_FiniteExtension_division_ring(): + # Test division in FiniteExtension over a ring + KQ = FiniteExtension(Poly(x**2 - 1, x, domain=QQ)) + KZ = FiniteExtension(Poly(x**2 - 1, x, domain=ZZ)) + KQt = FiniteExtension(Poly(x**2 - 1, x, domain=QQ[t])) + KQtf = FiniteExtension(Poly(x**2 - 1, x, domain=QQ.frac_field(t))) + assert KQ.is_Field is True + assert KZ.is_Field is False + assert KQt.is_Field is False + assert KQtf.is_Field is True + for K in KQ, KZ, KQt, KQtf: + xK = K.convert(x) + assert xK / K.one == xK + assert xK // K.one == xK + assert xK % K.one == K.zero + raises(ZeroDivisionError, lambda: xK / K.zero) + raises(ZeroDivisionError, lambda: xK // K.zero) + raises(ZeroDivisionError, lambda: xK % K.zero) + if K.is_Field: + assert xK / xK == K.one + assert xK // xK == K.one + assert xK % xK == K.zero + else: + raises(NotImplementedError, lambda: xK / xK) + raises(NotImplementedError, lambda: xK // xK) + raises(NotImplementedError, lambda: xK % xK) + + +def test_FiniteExtension_Poly(): + K = FiniteExtension(Poly(x**2 - 2)) + p = Poly(x, y, domain=K) + assert p.domain == K + assert p.as_expr() == x + assert (p**2).as_expr() == 2 + + K = FiniteExtension(Poly(x**2 - 2, x, domain=QQ)) + K2 = FiniteExtension(Poly(t**2 - 2, t, domain=K)) + assert str(K2) == 'QQ[x]/(x**2 - 2)[t]/(t**2 - 2)' + + eK = K2.convert(x + t) + assert K2.to_sympy(eK) == x + t + assert K2.to_sympy(eK ** 2) == 4 + 2*x*t + p = Poly(x + t, y, domain=K2) + assert p**2 == Poly(4 + 2*x*t, y, domain=K2) + + +def test_FiniteExtension_sincos_jacobian(): + # Use FiniteExtensino to compute the Jacobian of a matrix involving sin + # and cos of different symbols. + r, p, t = symbols('rho, phi, theta') + elements = [ + [sin(p)*cos(t), r*cos(p)*cos(t), -r*sin(p)*sin(t)], + [sin(p)*sin(t), r*cos(p)*sin(t), r*sin(p)*cos(t)], + [ cos(p), -r*sin(p), 0], + ] + + def make_extension(K): + K = FiniteExtension(Poly(sin(p)**2+cos(p)**2-1, sin(p), domain=K[cos(p)])) + K = FiniteExtension(Poly(sin(t)**2+cos(t)**2-1, sin(t), domain=K[cos(t)])) + return K + + Ksc1 = make_extension(ZZ[r]) + Ksc2 = make_extension(ZZ)[r] + + for K in [Ksc1, Ksc2]: + elements_K = [[K.convert(e) for e in row] for row in elements] + J = DomainMatrix(elements_K, (3, 3), K) + det = J.charpoly()[-1] * (-K.one)**3 + assert det == K.convert(r**2*sin(p)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_homomorphisms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_homomorphisms.py new file mode 100644 index 0000000000000000000000000000000000000000..2e63838e09ed9b9436a58a7d8041175e731bc4ef --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_homomorphisms.py @@ -0,0 +1,113 @@ +"""Tests for homomorphisms.""" + +from sympy.core.singleton import S +from sympy.polys.domains.rationalfield import QQ +from sympy.abc import x, y +from sympy.polys.agca import homomorphism +from sympy.testing.pytest import raises + + +def test_printing(): + R = QQ.old_poly_ring(x) + + assert str(homomorphism(R.free_module(1), R.free_module(1), [0])) == \ + 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1' + assert str(homomorphism(R.free_module(2), R.free_module(2), [0, 0])) == \ + 'Matrix([ \n[0, 0], : QQ[x]**2 -> QQ[x]**2\n[0, 0]]) ' + assert str(homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])) == \ + 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1/<[x]>' + assert str(R.free_module(0).identity_hom()) == 'Matrix(0, 0, []) : QQ[x]**0 -> QQ[x]**0' + +def test_operations(): + F = QQ.old_poly_ring(x).free_module(2) + G = QQ.old_poly_ring(x).free_module(3) + f = F.identity_hom() + g = homomorphism(F, F, [0, [1, x]]) + h = homomorphism(F, F, [[1, 0], 0]) + i = homomorphism(F, G, [[1, 0, 0], [0, 1, 0]]) + + assert f == f + assert f != g + assert f != i + assert (f != F.identity_hom()) is False + assert 2*f == f*2 == homomorphism(F, F, [[2, 0], [0, 2]]) + assert f/2 == homomorphism(F, F, [[S.Half, 0], [0, S.Half]]) + assert f + g == homomorphism(F, F, [[1, 0], [1, x + 1]]) + assert f - g == homomorphism(F, F, [[1, 0], [-1, 1 - x]]) + assert f*g == g == g*f + assert h*g == homomorphism(F, F, [0, [1, 0]]) + assert g*h == homomorphism(F, F, [0, 0]) + assert i*f == i + assert f([1, 2]) == [1, 2] + assert g([1, 2]) == [2, 2*x] + + assert i.restrict_domain(F.submodule([x, x]))([x, x]) == i([x, x]) + h1 = h.quotient_domain(F.submodule([0, 1])) + assert h1([1, 0]) == h([1, 0]) + assert h1.restrict_domain(h1.domain.submodule([x, 0]))([x, 0]) == h([x, 0]) + + raises(TypeError, lambda: f/g) + raises(TypeError, lambda: f + 1) + raises(TypeError, lambda: f + i) + raises(TypeError, lambda: f - 1) + raises(TypeError, lambda: f*i) + + +def test_creation(): + F = QQ.old_poly_ring(x).free_module(3) + G = QQ.old_poly_ring(x).free_module(2) + SM = F.submodule([1, 1, 1]) + Q = F / SM + SQ = Q.submodule([1, 0, 0]) + + matrix = [[1, 0], [0, 1], [-1, -1]] + h = homomorphism(F, G, matrix) + h2 = homomorphism(Q, G, matrix) + assert h.quotient_domain(SM) == h2 + raises(ValueError, lambda: h.quotient_domain(F.submodule([1, 0, 0]))) + assert h2.restrict_domain(SQ) == homomorphism(SQ, G, matrix) + raises(ValueError, lambda: h.restrict_domain(G)) + raises(ValueError, lambda: h.restrict_codomain(G.submodule([1, 0]))) + raises(ValueError, lambda: h.quotient_codomain(F)) + + im = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + for M in [F, SM, Q, SQ]: + assert M.identity_hom() == homomorphism(M, M, im) + assert SM.inclusion_hom() == homomorphism(SM, F, im) + assert SQ.inclusion_hom() == homomorphism(SQ, Q, im) + assert Q.quotient_hom() == homomorphism(F, Q, im) + assert SQ.quotient_hom() == homomorphism(SQ.base, SQ, im) + + class conv: + def convert(x, y=None): + return x + + class dummy: + container = conv() + + def submodule(*args): + return None + raises(TypeError, lambda: homomorphism(dummy(), G, matrix)) + raises(TypeError, lambda: homomorphism(F, dummy(), matrix)) + raises( + ValueError, lambda: homomorphism(QQ.old_poly_ring(x, y).free_module(3), G, matrix)) + raises(ValueError, lambda: homomorphism(F, G, [0, 0])) + + +def test_properties(): + R = QQ.old_poly_ring(x, y) + F = R.free_module(2) + h = homomorphism(F, F, [[x, 0], [y, 0]]) + assert h.kernel() == F.submodule([-y, x]) + assert h.image() == F.submodule([x, 0], [y, 0]) + assert not h.is_injective() + assert not h.is_surjective() + assert h.restrict_codomain(h.image()).is_surjective() + assert h.restrict_domain(F.submodule([1, 0])).is_injective() + assert h.quotient_domain( + h.kernel()).restrict_codomain(h.image()).is_isomorphism() + + R2 = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1] + F = R2.free_module(2) + h = homomorphism(F, F, [[x, 0], [y, y + 1]]) + assert h.is_isomorphism() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_ideals.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_ideals.py new file mode 100644 index 0000000000000000000000000000000000000000..b7fff0674b54a22e2a5acba5110d62d96a877074 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_ideals.py @@ -0,0 +1,131 @@ +"""Test ideals.py code.""" + +from sympy.polys import QQ, ilex +from sympy.abc import x, y, z +from sympy.testing.pytest import raises + + +def test_ideal_operations(): + R = QQ.old_poly_ring(x, y) + I = R.ideal(x) + J = R.ideal(y) + S = R.ideal(x*y) + T = R.ideal(x, y) + + assert not (I == J) + assert I == I + + assert I.union(J) == T + assert I + J == T + assert I + T == T + + assert not I.subset(T) + assert T.subset(I) + + assert I.product(J) == S + assert I*J == S + assert x*J == S + assert I*y == S + assert R.convert(x)*J == S + assert I*R.convert(y) == S + + assert not I.is_zero() + assert not J.is_whole_ring() + + assert R.ideal(x**2 + 1, x).is_whole_ring() + assert R.ideal() == R.ideal(0) + assert R.ideal().is_zero() + + assert T.contains(x*y) + assert T.subset([x, y]) + + assert T.in_terms_of_generators(x) == [R(1), R(0)] + + assert T**0 == R.ideal(1) + assert T**1 == T + assert T**2 == R.ideal(x**2, y**2, x*y) + assert I**5 == R.ideal(x**5) + + +def test_exceptions(): + I = QQ.old_poly_ring(x).ideal(x) + J = QQ.old_poly_ring(y).ideal(1) + raises(ValueError, lambda: I.union(x)) + raises(ValueError, lambda: I + J) + raises(ValueError, lambda: I * J) + raises(ValueError, lambda: I.union(J)) + assert (I == J) is False + assert I != J + + +def test_nontriv_global(): + R = QQ.old_poly_ring(x, y, z) + + def contains(I, f): + return R.ideal(*I).contains(f) + + assert contains([x, y], x) + assert contains([x, y], x + y) + assert not contains([x, y], 1) + assert not contains([x, y], z) + assert contains([x**2 + y, x**2 + x], x - y) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**3) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y**2) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4 + y**3 + 2*z*y*x) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y*z) + assert contains([x, 1 + x + y, 5 - 7*y], 1) + assert contains( + [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], + x**3) + assert not contains( + [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], + x**2 + y**2) + + # compare local order + assert not contains([x*(1 + x + y), y*(1 + z)], x) + assert not contains([x*(1 + x + y), y*(1 + z)], x + y) + + +def test_nontriv_local(): + R = QQ.old_poly_ring(x, y, z, order=ilex) + + def contains(I, f): + return R.ideal(*I).contains(f) + + assert contains([x, y], x) + assert contains([x, y], x + y) + assert not contains([x, y], 1) + assert not contains([x, y], z) + assert contains([x**2 + y, x**2 + x], x - y) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) + assert contains([x*(1 + x + y), y*(1 + z)], x) + assert contains([x*(1 + x + y), y*(1 + z)], x + y) + + +def test_intersection(): + R = QQ.old_poly_ring(x, y, z) + # SCA, example 1.8.11 + assert R.ideal(x, y).intersect(R.ideal(y**2, z)) == R.ideal(y**2, y*z, x*z) + + assert R.ideal(x, y).intersect(R.ideal()).is_zero() + + R = QQ.old_poly_ring(x, y, z, order="ilex") + assert R.ideal(x, y).intersect(R.ideal(y**2 + y**2*z, z + z*x**3*y)) == \ + R.ideal(y**2, y*z, x*z) + + +def test_quotient(): + # SCA, example 1.8.13 + R = QQ.old_poly_ring(x, y, z) + assert R.ideal(x, y).quotient(R.ideal(y**2, z)) == R.ideal(x, y) + + +def test_reduction(): + from sympy.polys.distributedmodules import sdm_nf_buchberger_reduced + R = QQ.old_poly_ring(x, y) + I = R.ideal(x**5, y) + e = R.convert(x**3 + y**2) + assert I.reduce_element(e) == e + assert I.reduce_element(e, NF=sdm_nf_buchberger_reduced) == R.convert(x**3) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_modules.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..29c2d4ce45f452f6f61420654be64a67d13b396b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/agca/tests/test_modules.py @@ -0,0 +1,408 @@ +"""Test modules.py code.""" + +from sympy.polys.agca.modules import FreeModule, ModuleOrder, FreeModulePolyRing +from sympy.polys import CoercionFailed, QQ, lex, grlex, ilex, ZZ +from sympy.abc import x, y, z +from sympy.testing.pytest import raises +from sympy.core.numbers import Rational + + +def test_FreeModuleElement(): + M = QQ.old_poly_ring(x).free_module(3) + e = M.convert([1, x, x**2]) + f = [QQ.old_poly_ring(x).convert(1), QQ.old_poly_ring(x).convert(x), QQ.old_poly_ring(x).convert(x**2)] + assert list(e) == f + assert f[0] == e[0] + assert f[1] == e[1] + assert f[2] == e[2] + raises(IndexError, lambda: e[3]) + + g = M.convert([x, 0, 0]) + assert e + g == M.convert([x + 1, x, x**2]) + assert f + g == M.convert([x + 1, x, x**2]) + assert -e == M.convert([-1, -x, -x**2]) + assert e - g == M.convert([1 - x, x, x**2]) + assert e != g + + assert M.convert([x, x, x]) / QQ.old_poly_ring(x).convert(x) == [1, 1, 1] + R = QQ.old_poly_ring(x, order="ilex") + assert R.free_module(1).convert([x]) / R.convert(x) == [1] + + +def test_FreeModule(): + M1 = FreeModule(QQ.old_poly_ring(x), 2) + assert M1 == FreeModule(QQ.old_poly_ring(x), 2) + assert M1 != FreeModule(QQ.old_poly_ring(y), 2) + assert M1 != FreeModule(QQ.old_poly_ring(x), 3) + M2 = FreeModule(QQ.old_poly_ring(x, order="ilex"), 2) + + assert [x, 1] in M1 + assert [x] not in M1 + assert [2, y] not in M1 + assert [1/(x + 1), 2] not in M1 + + e = M1.convert([x, x**2 + 1]) + X = QQ.old_poly_ring(x).convert(x) + assert e == [X, X**2 + 1] + assert e == [x, x**2 + 1] + assert 2*e == [2*x, 2*x**2 + 2] + assert e*2 == [2*x, 2*x**2 + 2] + assert e/2 == [x/2, (x**2 + 1)/2] + assert x*e == [x**2, x**3 + x] + assert e*x == [x**2, x**3 + x] + assert X*e == [x**2, x**3 + x] + assert e*X == [x**2, x**3 + x] + + assert [x, 1] in M2 + assert [x] not in M2 + assert [2, y] not in M2 + assert [1/(x + 1), 2] in M2 + + e = M2.convert([x, x**2 + 1]) + X = QQ.old_poly_ring(x, order="ilex").convert(x) + assert e == [X, X**2 + 1] + assert e == [x, x**2 + 1] + assert 2*e == [2*x, 2*x**2 + 2] + assert e*2 == [2*x, 2*x**2 + 2] + assert e/2 == [x/2, (x**2 + 1)/2] + assert x*e == [x**2, x**3 + x] + assert e*x == [x**2, x**3 + x] + assert e/(1 + x) == [x/(1 + x), (x**2 + 1)/(1 + x)] + assert X*e == [x**2, x**3 + x] + assert e*X == [x**2, x**3 + x] + + M3 = FreeModule(QQ.old_poly_ring(x, y), 2) + assert M3.convert(e) == M3.convert([x, x**2 + 1]) + + assert not M3.is_submodule(0) + assert not M3.is_zero() + + raises(NotImplementedError, lambda: ZZ.old_poly_ring(x).free_module(2)) + raises(NotImplementedError, lambda: FreeModulePolyRing(ZZ, 2)) + raises(CoercionFailed, lambda: M1.convert(QQ.old_poly_ring(x).free_module(3) + .convert([1, 2, 3]))) + raises(CoercionFailed, lambda: M3.convert(1)) + + +def test_ModuleOrder(): + o1 = ModuleOrder(lex, grlex, False) + o2 = ModuleOrder(ilex, lex, False) + + assert o1 == ModuleOrder(lex, grlex, False) + assert (o1 != ModuleOrder(lex, grlex, False)) is False + assert o1 != o2 + + assert o1((1, 2, 3)) == (1, (5, (2, 3))) + assert o2((1, 2, 3)) == (-1, (2, 3)) + + +def test_SubModulePolyRing_global(): + R = QQ.old_poly_ring(x, y) + F = R.free_module(3) + Fd = F.submodule([1, 0, 0], [1, 2, 0], [1, 2, 3]) + M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1]) + + assert F == Fd + assert Fd == F + assert F != M + assert M != F + assert Fd != M + assert M != Fd + assert Fd == F.submodule(*F.basis()) + + assert Fd.is_full_module() + assert not M.is_full_module() + assert not Fd.is_zero() + assert not M.is_zero() + assert Fd.submodule().is_zero() + + assert M.contains([x**2 + y**2 + x, 1 + y, 1]) + assert not M.contains([x**2 + y**2 + x, 1 + y, 2]) + assert M.contains([y**2, 1 - x*y, -x]) + + assert not F.submodule([1 + x, 0, 0]) == F.submodule([1, 0, 0]) + assert F.submodule([1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1])) == F + assert not M.is_submodule(0) + + m = F.convert([x**2 + y**2, 1, 0]) + n = M.convert(m) + assert m.module is F + assert n.module is M + + raises(ValueError, lambda: M.submodule([1, 0, 0])) + raises(TypeError, lambda: M.union(1)) + raises(ValueError, lambda: M.union(R.free_module(1).submodule([x]))) + + assert F.submodule([x, x, x]) != F.submodule([x, x, x], order="ilex") + + +def test_SubModulePolyRing_local(): + R = QQ.old_poly_ring(x, y, order=ilex) + F = R.free_module(3) + Fd = F.submodule([1 + x, 0, 0], [1 + y, 2 + 2*y, 0], [1, 2, 3]) + M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1]) + + assert F == Fd + assert Fd == F + assert F != M + assert M != F + assert Fd != M + assert M != Fd + assert Fd == F.submodule(*F.basis()) + + assert Fd.is_full_module() + assert not M.is_full_module() + assert not Fd.is_zero() + assert not M.is_zero() + assert Fd.submodule().is_zero() + + assert M.contains([x**2 + y**2 + x, 1 + y, 1]) + assert not M.contains([x**2 + y**2 + x, 1 + y, 2]) + assert M.contains([y**2, 1 - x*y, -x]) + + assert F.submodule([1 + x, 0, 0]) == F.submodule([1, 0, 0]) + assert F.submodule( + [1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1 + x*y])) == F + + raises(ValueError, lambda: M.submodule([1, 0, 0])) + + +def test_SubModulePolyRing_nontriv_global(): + R = QQ.old_poly_ring(x, y, z) + F = R.free_module(1) + + def contains(I, f): + return F.submodule(*[[g] for g in I]).contains([f]) + + assert contains([x, y], x) + assert contains([x, y], x + y) + assert not contains([x, y], 1) + assert not contains([x, y], z) + assert contains([x**2 + y, x**2 + x], x - y) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**3) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y**2) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4 + y**3 + 2*z*y*x) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y*z) + assert contains([x, 1 + x + y, 5 - 7*y], 1) + assert contains( + [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], + x**3) + assert not contains( + [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], + x**2 + y**2) + + # compare local order + assert not contains([x*(1 + x + y), y*(1 + z)], x) + assert not contains([x*(1 + x + y), y*(1 + z)], x + y) + + +def test_SubModulePolyRing_nontriv_local(): + R = QQ.old_poly_ring(x, y, z, order=ilex) + F = R.free_module(1) + + def contains(I, f): + return F.submodule(*[[g] for g in I]).contains([f]) + + assert contains([x, y], x) + assert contains([x, y], x + y) + assert not contains([x, y], 1) + assert not contains([x, y], z) + assert contains([x**2 + y, x**2 + x], x - y) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) + assert contains([x*(1 + x + y), y*(1 + z)], x) + assert contains([x*(1 + x + y), y*(1 + z)], x + y) + + +def test_syzygy(): + R = QQ.old_poly_ring(x, y, z) + M = R.free_module(1).submodule([x*y], [y*z], [x*z]) + S = R.free_module(3).submodule([0, x, -y], [z, -x, 0]) + assert M.syzygy_module() == S + + M2 = M / ([x*y*z],) + S2 = R.free_module(3).submodule([z, 0, 0], [0, x, 0], [0, 0, y]) + assert M2.syzygy_module() == S2 + + F = R.free_module(3) + assert F.submodule(*F.basis()).syzygy_module() == F.submodule() + + R2 = QQ.old_poly_ring(x, y, z) / [x*y*z] + M3 = R2.free_module(1).submodule([x*y], [y*z], [x*z]) + S3 = R2.free_module(3).submodule([z, 0, 0], [0, x, 0], [0, 0, y]) + assert M3.syzygy_module() == S3 + + +def test_in_terms_of_generators(): + R = QQ.old_poly_ring(x, order="ilex") + M = R.free_module(2).submodule([2*x, 0], [1, 2]) + assert M.in_terms_of_generators( + [x, x]) == [R.convert(Rational(1, 4)), R.convert(x/2)] + raises(ValueError, lambda: M.in_terms_of_generators([1, 0])) + + M = R.free_module(2) / ([x, 0], [1, 1]) + SM = M.submodule([1, x]) + assert SM.in_terms_of_generators([2, 0]) == [R.convert(-2/(x - 1))] + + R = QQ.old_poly_ring(x, y) / [x**2 - y**2] + M = R.free_module(2) + SM = M.submodule([x, 0], [0, y]) + assert SM.in_terms_of_generators( + [x**2, x**2]) == [R.convert(x), R.convert(y)] + + +def test_QuotientModuleElement(): + R = QQ.old_poly_ring(x) + F = R.free_module(3) + N = F.submodule([1, x, x**2]) + M = F/N + e = M.convert([x**2, 2, 0]) + + assert M.convert([x + 1, x**2 + x, x**3 + x**2]) == 0 + assert e == [x**2, 2, 0] + N == F.convert([x**2, 2, 0]) + N == \ + M.convert(F.convert([x**2, 2, 0])) + + assert M.convert([x**2 + 1, 2*x + 2, x**2]) == e + [0, x, 0] == \ + e + M.convert([0, x, 0]) == e + F.convert([0, x, 0]) + assert M.convert([x**2 + 1, 2, x**2]) == e - [0, x, 0] == \ + e - M.convert([0, x, 0]) == e - F.convert([0, x, 0]) + assert M.convert([0, 2, 0]) == M.convert([x**2, 4, 0]) - e == \ + [x**2, 4, 0] - e == F.convert([x**2, 4, 0]) - e + assert M.convert([x**3 + x**2, 2*x + 2, 0]) == (1 + x)*e == \ + R.convert(1 + x)*e == e*(1 + x) == e*R.convert(1 + x) + assert -e == [-x**2, -2, 0] + + f = [x, x, 0] + N + assert M.convert([1, 1, 0]) == f / x == f / R.convert(x) + + M2 = F/[(2, 2*x, 2*x**2), (0, 0, 1)] + G = R.free_module(2) + M3 = G/[[1, x]] + M4 = F.submodule([1, x, x**2], [1, 0, 0]) / N + raises(CoercionFailed, lambda: M.convert(G.convert([1, x]))) + raises(CoercionFailed, lambda: M.convert(M3.convert([1, x]))) + raises(CoercionFailed, lambda: M.convert(M2.convert([1, x, x]))) + assert M2.convert(M.convert([2, x, x**2])) == [2, x, 0] + assert M.convert(M4.convert([2, 0, 0])) == [2, 0, 0] + + +def test_QuotientModule(): + R = QQ.old_poly_ring(x) + F = R.free_module(3) + N = F.submodule([1, x, x**2]) + M = F/N + + assert M != F + assert M != N + assert M == F / [(1, x, x**2)] + assert not M.is_zero() + assert (F / F.basis()).is_zero() + + SQ = F.submodule([1, x, x**2], [2, 0, 0]) / N + assert SQ == M.submodule([2, x, x**2]) + assert SQ != M.submodule([2, 1, 0]) + assert SQ != M + assert M.is_submodule(SQ) + assert not SQ.is_full_module() + + raises(ValueError, lambda: N/F) + raises(ValueError, lambda: F.submodule([2, 0, 0]) / N) + raises(ValueError, lambda: R.free_module(2)/F) + raises(CoercionFailed, lambda: F.convert(M.convert([1, x, x**2]))) + + M1 = F / [[1, 1, 1]] + M2 = M1.submodule([1, 0, 0], [0, 1, 0]) + assert M1 == M2 + + +def test_ModulesQuotientRing(): + R = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1] + M1 = R.free_module(2) + assert M1 == R.free_module(2) + assert M1 != QQ.old_poly_ring(x).free_module(2) + assert M1 != R.free_module(3) + + assert [x, 1] in M1 + assert [x] not in M1 + assert [1/(R.convert(x) + 1), 2] in M1 + assert [1, 2/(1 + y)] in M1 + assert [1, 2/y] not in M1 + + assert M1.convert([x**2, y]) == [-1, y] + + F = R.free_module(3) + Fd = F.submodule([x**2, 0, 0], [1, 2, 0], [1, 2, 3]) + M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1]) + + assert F == Fd + assert Fd == F + assert F != M + assert M != F + assert Fd != M + assert M != Fd + assert Fd == F.submodule(*F.basis()) + + assert Fd.is_full_module() + assert not M.is_full_module() + assert not Fd.is_zero() + assert not M.is_zero() + assert Fd.submodule().is_zero() + + assert M.contains([x**2 + y**2 + x, -x**2 + y, 1]) + assert not M.contains([x**2 + y**2 + x, 1 + y, 2]) + assert M.contains([y**2, 1 - x*y, -x]) + + assert F.submodule([x, 0, 0]) == F.submodule([1, 0, 0]) + assert not F.submodule([y, 0, 0]) == F.submodule([1, 0, 0]) + assert F.submodule([1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1])) == F + assert not M.is_submodule(0) + + +def test_module_mul(): + R = QQ.old_poly_ring(x) + M = R.free_module(2) + S1 = M.submodule([x, 0], [0, x]) + S2 = M.submodule([x**2, 0], [0, x**2]) + I = R.ideal(x) + + assert I*M == M*I == S1 == x*M == M*x + assert I*S1 == S2 == x*S1 + + +def test_intersection(): + # SCA, example 2.8.5 + F = QQ.old_poly_ring(x, y).free_module(2) + M1 = F.submodule([x, y], [y, 1]) + M2 = F.submodule([0, y - 1], [x, 1], [y, x]) + I = F.submodule([x, y], [y**2 - y, y - 1], [x*y + y, x + 1]) + I1, rel1, rel2 = M1.intersect(M2, relations=True) + assert I1 == M2.intersect(M1) == I + for i, g in enumerate(I1.gens): + assert g == sum(c*x for c, x in zip(rel1[i], M1.gens)) \ + == sum(d*y for d, y in zip(rel2[i], M2.gens)) + + assert F.submodule([x, y]).intersect(F.submodule([y, x])).is_zero() + + +def test_quotient(): + # SCA, example 2.8.6 + R = QQ.old_poly_ring(x, y, z) + F = R.free_module(2) + assert F.submodule([x*y, x*z], [y*z, x*y]).module_quotient( + F.submodule([y, z], [z, y])) == QQ.old_poly_ring(x, y, z).ideal(x**2*y**2 - x*y*z**2) + assert F.submodule([x, y]).module_quotient(F.submodule()).is_whole_ring() + + M = F.submodule([x**2, x**2], [y**2, y**2]) + N = F.submodule([x + y, x + y]) + q, rel = M.module_quotient(N, relations=True) + assert q == R.ideal(y**2, x - y) + for i, g in enumerate(q.gens): + assert g*N.gens[0] == sum(c*x for c, x in zip(rel[i], M.gens)) + + +def test_groebner_extendend(): + M = QQ.old_poly_ring(x, y, z).free_module(3).submodule([x + 1, y, 1], [x*y, z, z**2]) + G, R = M._groebner_vec(extended=True) + for i, g in enumerate(G): + assert g == sum(c*gen for c, gen in zip(R[i], M.gens)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/appellseqs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/appellseqs.py new file mode 100644 index 0000000000000000000000000000000000000000..ac10fe3d1f1e60ccdf46cdae4eb5b8a969500a3e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/appellseqs.py @@ -0,0 +1,269 @@ +r""" +Efficient functions for generating Appell sequences. + +An Appell sequence is a zero-indexed sequence of polynomials `p_i(x)` +satisfying `p_{i+1}'(x)=(i+1)p_i(x)` for all `i`. This definition leads +to the following iterative algorithm: + +.. math :: p_0(x) = c_0,\ p_i(x) = i \int_0^x p_{i-1}(t)\,dt + c_i + +The constant coefficients `c_i` are usually determined from the +just-evaluated integral and `i`. + +Appell sequences satisfy the following identity from umbral calculus: + +.. math :: p_n(x+y) = \sum_{k=0}^n \binom{n}{k} p_k(x) y^{n-k} + +References +========== + +.. [1] https://en.wikipedia.org/wiki/Appell_sequence +.. [2] Peter Luschny, "An introduction to the Bernoulli function", + https://arxiv.org/abs/2009.06743 +""" +from sympy.polys.densearith import dup_mul_ground, dup_sub_ground, dup_quo_ground +from sympy.polys.densetools import dup_eval, dup_integrate +from sympy.polys.domains import ZZ, QQ +from sympy.polys.polytools import named_poly +from sympy.utilities import public + +def dup_bernoulli(n, K): + """Low-level implementation of Bernoulli polynomials.""" + if n < 1: + return [K.one] + p = [K.one, K(-1,2)] + for i in range(2, n+1): + p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K) + if i % 2 == 0: + p = dup_sub_ground(p, dup_eval(p, K(1,2), K) * K(1<<(i-1), (1<>> from sympy import summation + >>> from sympy.abc import x + >>> from sympy.polys import bernoulli_poly + >>> bernoulli_poly(5, x) + x**5 - 5*x**4/2 + 5*x**3/3 - x/6 + + >>> def psum(p, a, b): + ... return (bernoulli_poly(p+1,b+1) - bernoulli_poly(p+1,a)) / (p+1) + >>> psum(4, -6, 27) + 3144337 + >>> summation(x**4, (x, -6, 27)) + 3144337 + + >>> psum(1, 1, x).factor() + x*(x + 1)/2 + >>> psum(2, 1, x).factor() + x*(x + 1)*(2*x + 1)/6 + >>> psum(3, 1, x).factor() + x**2*(x + 1)**2/4 + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + + See Also + ======== + + sympy.functions.combinatorial.numbers.bernoulli + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Bernoulli_polynomials + """ + return named_poly(n, dup_bernoulli, QQ, "Bernoulli polynomial", (x,), polys) + +def dup_bernoulli_c(n, K): + """Low-level implementation of central Bernoulli polynomials.""" + p = [K.one] + for i in range(1, n+1): + p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K) + if i % 2 == 0: + p = dup_sub_ground(p, dup_eval(p, K.one, K) * K((1<<(i-1))-1, (1<>> from sympy import bernoulli, euler, genocchi + >>> from sympy.abc import x + >>> from sympy.polys import andre_poly + >>> andre_poly(9, x) + x**9 - 36*x**7 + 630*x**5 - 5124*x**3 + 12465*x + + >>> [andre_poly(n, 0) for n in range(11)] + [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521] + >>> [euler(n) for n in range(11)] + [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521] + >>> [andre_poly(n-1, 1) * n / (4**n - 2**n) for n in range(1, 11)] + [1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66] + >>> [bernoulli(n) for n in range(1, 11)] + [1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66] + >>> [-andre_poly(n-1, -1) * n / (-2)**(n-1) for n in range(1, 11)] + [-1, -1, 0, 1, 0, -3, 0, 17, 0, -155] + >>> [genocchi(n) for n in range(1, 11)] + [-1, -1, 0, 1, 0, -3, 0, 17, 0, -155] + + >>> [abs(andre_poly(n, n%2)) for n in range(11)] + [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521] + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + + See Also + ======== + + sympy.functions.combinatorial.numbers.andre + + References + ========== + + .. [1] Peter Luschny, "An introduction to the Bernoulli function", + https://arxiv.org/abs/2009.06743 + """ + return named_poly(n, dup_andre, ZZ, "Andre polynomial", (x,), polys) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_galoispolys.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_galoispolys.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2a0329a0cf96be2e8359a3741d8e2de13fa37a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_galoispolys.py @@ -0,0 +1,66 @@ +"""Benchmarks for polynomials over Galois fields. """ + + +from sympy.polys.galoistools import gf_from_dict, gf_factor_sqf +from sympy.polys.domains import ZZ +from sympy.core.numbers import pi +from sympy.ntheory.generate import nextprime + + +def gathen_poly(n, p, K): + return gf_from_dict({n: K.one, 1: K.one, 0: K.one}, p, K) + + +def shoup_poly(n, p, K): + f = [K.one] * (n + 1) + for i in range(1, n + 1): + f[i] = (f[i - 1]**2 + K.one) % p + return f + + +def genprime(n, K): + return K(nextprime(int((2**n * pi).evalf()))) + +p_10 = genprime(10, ZZ) +f_10 = gathen_poly(10, p_10, ZZ) + +p_20 = genprime(20, ZZ) +f_20 = gathen_poly(20, p_20, ZZ) + + +def timeit_gathen_poly_f10_zassenhaus(): + gf_factor_sqf(f_10, p_10, ZZ, method='zassenhaus') + + +def timeit_gathen_poly_f10_shoup(): + gf_factor_sqf(f_10, p_10, ZZ, method='shoup') + + +def timeit_gathen_poly_f20_zassenhaus(): + gf_factor_sqf(f_20, p_20, ZZ, method='zassenhaus') + + +def timeit_gathen_poly_f20_shoup(): + gf_factor_sqf(f_20, p_20, ZZ, method='shoup') + +P_08 = genprime(8, ZZ) +F_10 = shoup_poly(10, P_08, ZZ) + +P_18 = genprime(18, ZZ) +F_20 = shoup_poly(20, P_18, ZZ) + + +def timeit_shoup_poly_F10_zassenhaus(): + gf_factor_sqf(F_10, P_08, ZZ, method='zassenhaus') + + +def timeit_shoup_poly_F10_shoup(): + gf_factor_sqf(F_10, P_08, ZZ, method='shoup') + + +def timeit_shoup_poly_F20_zassenhaus(): + gf_factor_sqf(F_20, P_18, ZZ, method='zassenhaus') + + +def timeit_shoup_poly_F20_shoup(): + gf_factor_sqf(F_20, P_18, ZZ, method='shoup') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_groebnertools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_groebnertools.py new file mode 100644 index 0000000000000000000000000000000000000000..e709f4f6d2cb42c0980d2e49725e01a7a2aa2b87 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_groebnertools.py @@ -0,0 +1,25 @@ +"""Benchmark of the Groebner bases algorithms. """ + + +from sympy.polys.rings import ring +from sympy.polys.domains import QQ +from sympy.polys.groebnertools import groebner + +R, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 = ring("x1:13", QQ) + +V = R.gens +E = [(x1, x2), (x2, x3), (x1, x4), (x1, x6), (x1, x12), (x2, x5), (x2, x7), (x3, x8), + (x3, x10), (x4, x11), (x4, x9), (x5, x6), (x6, x7), (x7, x8), (x8, x9), (x9, x10), + (x10, x11), (x11, x12), (x5, x12), (x5, x9), (x6, x10), (x7, x11), (x8, x12)] + +F3 = [ x**3 - 1 for x in V ] +Fg = [ x**2 + x*y + y**2 for x, y in E ] + +F_1 = F3 + Fg +F_2 = F3 + Fg + [x3**2 + x3*x4 + x4**2] + +def time_vertex_color_12_vertices_23_edges(): + assert groebner(F_1, R) != [1] + +def time_vertex_color_12_vertices_24_edges(): + assert groebner(F_2, R) == [1] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_solvers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3ce5e246db2f5589e6a5dba9f18b7388c179c4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/benchmarks/bench_solvers.py @@ -0,0 +1,543 @@ +from sympy.polys.rings import ring +from sympy.polys.fields import field +from sympy.polys.domains import ZZ, QQ +from sympy.polys.solvers import solve_lin_sys + +# Expected times on 3.4 GHz i7: + +# In [1]: %timeit time_solve_lin_sys_189x49() +# 1 loops, best of 3: 864 ms per loop +# In [2]: %timeit time_solve_lin_sys_165x165() +# 1 loops, best of 3: 1.83 s per loop +# In [3]: %timeit time_solve_lin_sys_10x8() +# 1 loops, best of 3: 2.31 s per loop + +# Benchmark R_165: shows how fast are arithmetics in QQ. + +R_165, uk_0, uk_1, uk_2, uk_3, uk_4, uk_5, uk_6, uk_7, uk_8, uk_9, uk_10, uk_11, uk_12, uk_13, uk_14, uk_15, uk_16, uk_17, uk_18, uk_19, uk_20, uk_21, uk_22, uk_23, uk_24, uk_25, uk_26, uk_27, uk_28, uk_29, uk_30, uk_31, uk_32, uk_33, uk_34, uk_35, uk_36, uk_37, uk_38, uk_39, uk_40, uk_41, uk_42, uk_43, uk_44, uk_45, uk_46, uk_47, uk_48, uk_49, uk_50, uk_51, uk_52, uk_53, uk_54, uk_55, uk_56, uk_57, uk_58, uk_59, uk_60, uk_61, uk_62, uk_63, uk_64, uk_65, uk_66, uk_67, uk_68, uk_69, uk_70, uk_71, uk_72, uk_73, uk_74, uk_75, uk_76, uk_77, uk_78, uk_79, uk_80, uk_81, uk_82, uk_83, uk_84, uk_85, uk_86, uk_87, uk_88, uk_89, uk_90, uk_91, uk_92, uk_93, uk_94, uk_95, uk_96, uk_97, uk_98, uk_99, uk_100, uk_101, uk_102, uk_103, uk_104, uk_105, uk_106, uk_107, uk_108, uk_109, uk_110, uk_111, uk_112, uk_113, uk_114, uk_115, uk_116, uk_117, uk_118, uk_119, uk_120, uk_121, uk_122, uk_123, uk_124, uk_125, uk_126, uk_127, uk_128, uk_129, uk_130, uk_131, uk_132, uk_133, uk_134, uk_135, uk_136, uk_137, uk_138, uk_139, uk_140, uk_141, uk_142, uk_143, uk_144, uk_145, uk_146, uk_147, uk_148, uk_149, uk_150, uk_151, uk_152, uk_153, uk_154, uk_155, uk_156, uk_157, uk_158, uk_159, uk_160, uk_161, uk_162, uk_163, uk_164 = ring("uk_:165", QQ) + +def eqs_165x165(): + return [ + uk_0 + 50719*uk_1 + 2789545*uk_10 + 411400*uk_100 + 1683000*uk_101 + 166375*uk_103 + 680625*uk_104 + 2784375*uk_106 + 729*uk_109 + 456471*uk_11 + 4131*uk_110 + 11016*uk_111 + 4455*uk_112 + 18225*uk_113 + 23409*uk_115 + 62424*uk_116 + 25245*uk_117 + 103275*uk_118 + 2586669*uk_12 + 166464*uk_120 + 67320*uk_121 + 275400*uk_122 + 27225*uk_124 + 111375*uk_125 + 455625*uk_127 + 6897784*uk_13 + 132651*uk_130 + 353736*uk_131 + 143055*uk_132 + 585225*uk_133 + 943296*uk_135 + 381480*uk_136 + 1560600*uk_137 + 154275*uk_139 + 2789545*uk_14 + 631125*uk_140 + 2581875*uk_142 + 2515456*uk_145 + 1017280*uk_146 + 4161600*uk_147 + 411400*uk_149 + 11411775*uk_15 + 1683000*uk_150 + 6885000*uk_152 + 166375*uk_155 + 680625*uk_156 + 2784375*uk_158 + 11390625*uk_161 + 3025*uk_17 + 495*uk_18 + 2805*uk_19 + 55*uk_2 + 7480*uk_20 + 3025*uk_21 + 12375*uk_22 + 81*uk_24 + 459*uk_25 + 1224*uk_26 + 495*uk_27 + 2025*uk_28 + 9*uk_3 + 2601*uk_30 + 6936*uk_31 + 2805*uk_32 + 11475*uk_33 + 18496*uk_35 + 7480*uk_36 + 30600*uk_37 + 3025*uk_39 + 51*uk_4 + 12375*uk_40 + 50625*uk_42 + 130470415844959*uk_45 + 141482932855*uk_46 + 23151752649*uk_47 + 131193265011*uk_48 + 349848706696*uk_49 + 136*uk_5 + 141482932855*uk_50 + 578793816225*uk_51 + 153424975*uk_53 + 25105905*uk_54 + 142266795*uk_55 + 379378120*uk_56 + 153424975*uk_57 + 627647625*uk_58 + 55*uk_6 + 4108239*uk_60 + 23280021*uk_61 + 62080056*uk_62 + 25105905*uk_63 + 102705975*uk_64 + 131920119*uk_66 + 351786984*uk_67 + 142266795*uk_68 + 582000525*uk_69 + 225*uk_7 + 938098624*uk_71 + 379378120*uk_72 + 1552001400*uk_73 + 153424975*uk_75 + 627647625*uk_76 + 2567649375*uk_78 + 166375*uk_81 + 27225*uk_82 + 154275*uk_83 + 411400*uk_84 + 166375*uk_85 + 680625*uk_86 + 4455*uk_88 + 25245*uk_89 + 2572416961*uk_9 + 67320*uk_90 + 27225*uk_91 + 111375*uk_92 + 143055*uk_94 + 381480*uk_95 + 154275*uk_96 + 631125*uk_97 + 1017280*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 413820*uk_100 + 1633500*uk_101 + 65340*uk_102 + 178695*uk_103 + 705375*uk_104 + 28215*uk_105 + 2784375*uk_106 + 111375*uk_107 + 4455*uk_108 + 97336*uk_109 + 2333074*uk_11 + 19044*uk_110 + 279312*uk_111 + 120612*uk_112 + 476100*uk_113 + 19044*uk_114 + 3726*uk_115 + 54648*uk_116 + 23598*uk_117 + 93150*uk_118 + 3726*uk_119 + 456471*uk_12 + 801504*uk_120 + 346104*uk_121 + 1366200*uk_122 + 54648*uk_123 + 149454*uk_124 + 589950*uk_125 + 23598*uk_126 + 2328750*uk_127 + 93150*uk_128 + 3726*uk_129 + 6694908*uk_13 + 729*uk_130 + 10692*uk_131 + 4617*uk_132 + 18225*uk_133 + 729*uk_134 + 156816*uk_135 + 67716*uk_136 + 267300*uk_137 + 10692*uk_138 + 29241*uk_139 + 2890983*uk_14 + 115425*uk_140 + 4617*uk_141 + 455625*uk_142 + 18225*uk_143 + 729*uk_144 + 2299968*uk_145 + 993168*uk_146 + 3920400*uk_147 + 156816*uk_148 + 428868*uk_149 + 11411775*uk_15 + 1692900*uk_150 + 67716*uk_151 + 6682500*uk_152 + 267300*uk_153 + 10692*uk_154 + 185193*uk_155 + 731025*uk_156 + 29241*uk_157 + 2885625*uk_158 + 115425*uk_159 + 456471*uk_16 + 4617*uk_160 + 11390625*uk_161 + 455625*uk_162 + 18225*uk_163 + 729*uk_164 + 3025*uk_17 + 2530*uk_18 + 495*uk_19 + 55*uk_2 + 7260*uk_20 + 3135*uk_21 + 12375*uk_22 + 495*uk_23 + 2116*uk_24 + 414*uk_25 + 6072*uk_26 + 2622*uk_27 + 10350*uk_28 + 414*uk_29 + 46*uk_3 + 81*uk_30 + 1188*uk_31 + 513*uk_32 + 2025*uk_33 + 81*uk_34 + 17424*uk_35 + 7524*uk_36 + 29700*uk_37 + 1188*uk_38 + 3249*uk_39 + 9*uk_4 + 12825*uk_40 + 513*uk_41 + 50625*uk_42 + 2025*uk_43 + 81*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 118331180206*uk_47 + 23151752649*uk_48 + 339559038852*uk_49 + 132*uk_5 + 146627766777*uk_50 + 578793816225*uk_51 + 23151752649*uk_52 + 153424975*uk_53 + 128319070*uk_54 + 25105905*uk_55 + 368219940*uk_56 + 159004065*uk_57 + 627647625*uk_58 + 25105905*uk_59 + 57*uk_6 + 107321404*uk_60 + 20997666*uk_61 + 307965768*uk_62 + 132985218*uk_63 + 524941650*uk_64 + 20997666*uk_65 + 4108239*uk_66 + 60254172*uk_67 + 26018847*uk_68 + 102705975*uk_69 + 225*uk_7 + 4108239*uk_70 + 883727856*uk_71 + 381609756*uk_72 + 1506354300*uk_73 + 60254172*uk_74 + 164786031*uk_75 + 650471175*uk_76 + 26018847*uk_77 + 2567649375*uk_78 + 102705975*uk_79 + 9*uk_8 + 4108239*uk_80 + 166375*uk_81 + 139150*uk_82 + 27225*uk_83 + 399300*uk_84 + 172425*uk_85 + 680625*uk_86 + 27225*uk_87 + 116380*uk_88 + 22770*uk_89 + 2572416961*uk_9 + 333960*uk_90 + 144210*uk_91 + 569250*uk_92 + 22770*uk_93 + 4455*uk_94 + 65340*uk_95 + 28215*uk_96 + 111375*uk_97 + 4455*uk_98 + 958320*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 402380*uk_100 + 1534500*uk_101 + 313720*uk_102 + 191455*uk_103 + 730125*uk_104 + 149270*uk_105 + 2784375*uk_106 + 569250*uk_107 + 116380*uk_108 + 912673*uk_109 + 4919743*uk_11 + 432814*uk_110 + 1166716*uk_111 + 555131*uk_112 + 2117025*uk_113 + 432814*uk_114 + 205252*uk_115 + 553288*uk_116 + 263258*uk_117 + 1003950*uk_118 + 205252*uk_119 + 2333074*uk_12 + 1491472*uk_120 + 709652*uk_121 + 2706300*uk_122 + 553288*uk_123 + 337657*uk_124 + 1287675*uk_125 + 263258*uk_126 + 4910625*uk_127 + 1003950*uk_128 + 205252*uk_129 + 6289156*uk_13 + 97336*uk_130 + 262384*uk_131 + 124844*uk_132 + 476100*uk_133 + 97336*uk_134 + 707296*uk_135 + 336536*uk_136 + 1283400*uk_137 + 262384*uk_138 + 160126*uk_139 + 2992421*uk_14 + 610650*uk_140 + 124844*uk_141 + 2328750*uk_142 + 476100*uk_143 + 97336*uk_144 + 1906624*uk_145 + 907184*uk_146 + 3459600*uk_147 + 707296*uk_148 + 431644*uk_149 + 11411775*uk_15 + 1646100*uk_150 + 336536*uk_151 + 6277500*uk_152 + 1283400*uk_153 + 262384*uk_154 + 205379*uk_155 + 783225*uk_156 + 160126*uk_157 + 2986875*uk_158 + 610650*uk_159 + 2333074*uk_16 + 124844*uk_160 + 11390625*uk_161 + 2328750*uk_162 + 476100*uk_163 + 97336*uk_164 + 3025*uk_17 + 5335*uk_18 + 2530*uk_19 + 55*uk_2 + 6820*uk_20 + 3245*uk_21 + 12375*uk_22 + 2530*uk_23 + 9409*uk_24 + 4462*uk_25 + 12028*uk_26 + 5723*uk_27 + 21825*uk_28 + 4462*uk_29 + 97*uk_3 + 2116*uk_30 + 5704*uk_31 + 2714*uk_32 + 10350*uk_33 + 2116*uk_34 + 15376*uk_35 + 7316*uk_36 + 27900*uk_37 + 5704*uk_38 + 3481*uk_39 + 46*uk_4 + 13275*uk_40 + 2714*uk_41 + 50625*uk_42 + 10350*uk_43 + 2116*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 249524445217*uk_47 + 118331180206*uk_48 + 318979703164*uk_49 + 124*uk_5 + 151772600699*uk_50 + 578793816225*uk_51 + 118331180206*uk_52 + 153424975*uk_53 + 270585865*uk_54 + 128319070*uk_55 + 345903580*uk_56 + 164583155*uk_57 + 627647625*uk_58 + 128319070*uk_59 + 59*uk_6 + 477215071*uk_60 + 226308178*uk_61 + 610048132*uk_62 + 290264837*uk_63 + 1106942175*uk_64 + 226308178*uk_65 + 107321404*uk_66 + 289301176*uk_67 + 137651366*uk_68 + 524941650*uk_69 + 225*uk_7 + 107321404*uk_70 + 779855344*uk_71 + 371060204*uk_72 + 1415060100*uk_73 + 289301176*uk_74 + 176552839*uk_75 + 673294725*uk_76 + 137651366*uk_77 + 2567649375*uk_78 + 524941650*uk_79 + 46*uk_8 + 107321404*uk_80 + 166375*uk_81 + 293425*uk_82 + 139150*uk_83 + 375100*uk_84 + 178475*uk_85 + 680625*uk_86 + 139150*uk_87 + 517495*uk_88 + 245410*uk_89 + 2572416961*uk_9 + 661540*uk_90 + 314765*uk_91 + 1200375*uk_92 + 245410*uk_93 + 116380*uk_94 + 313720*uk_95 + 149270*uk_96 + 569250*uk_97 + 116380*uk_98 + 845680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 389180*uk_100 + 1435500*uk_101 + 618860*uk_102 + 204655*uk_103 + 754875*uk_104 + 325435*uk_105 + 2784375*uk_106 + 1200375*uk_107 + 517495*uk_108 + 3375000*uk_109 + 7607850*uk_11 + 2182500*uk_110 + 2610000*uk_111 + 1372500*uk_112 + 5062500*uk_113 + 2182500*uk_114 + 1411350*uk_115 + 1687800*uk_116 + 887550*uk_117 + 3273750*uk_118 + 1411350*uk_119 + 4919743*uk_12 + 2018400*uk_120 + 1061400*uk_121 + 3915000*uk_122 + 1687800*uk_123 + 558150*uk_124 + 2058750*uk_125 + 887550*uk_126 + 7593750*uk_127 + 3273750*uk_128 + 1411350*uk_129 + 5883404*uk_13 + 912673*uk_130 + 1091444*uk_131 + 573949*uk_132 + 2117025*uk_133 + 912673*uk_134 + 1305232*uk_135 + 686372*uk_136 + 2531700*uk_137 + 1091444*uk_138 + 360937*uk_139 + 3093859*uk_14 + 1331325*uk_140 + 573949*uk_141 + 4910625*uk_142 + 2117025*uk_143 + 912673*uk_144 + 1560896*uk_145 + 820816*uk_146 + 3027600*uk_147 + 1305232*uk_148 + 431636*uk_149 + 11411775*uk_15 + 1592100*uk_150 + 686372*uk_151 + 5872500*uk_152 + 2531700*uk_153 + 1091444*uk_154 + 226981*uk_155 + 837225*uk_156 + 360937*uk_157 + 3088125*uk_158 + 1331325*uk_159 + 4919743*uk_16 + 573949*uk_160 + 11390625*uk_161 + 4910625*uk_162 + 2117025*uk_163 + 912673*uk_164 + 3025*uk_17 + 8250*uk_18 + 5335*uk_19 + 55*uk_2 + 6380*uk_20 + 3355*uk_21 + 12375*uk_22 + 5335*uk_23 + 22500*uk_24 + 14550*uk_25 + 17400*uk_26 + 9150*uk_27 + 33750*uk_28 + 14550*uk_29 + 150*uk_3 + 9409*uk_30 + 11252*uk_31 + 5917*uk_32 + 21825*uk_33 + 9409*uk_34 + 13456*uk_35 + 7076*uk_36 + 26100*uk_37 + 11252*uk_38 + 3721*uk_39 + 97*uk_4 + 13725*uk_40 + 5917*uk_41 + 50625*uk_42 + 21825*uk_43 + 9409*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 385862544150*uk_47 + 249524445217*uk_48 + 298400367476*uk_49 + 116*uk_5 + 156917434621*uk_50 + 578793816225*uk_51 + 249524445217*uk_52 + 153424975*uk_53 + 418431750*uk_54 + 270585865*uk_55 + 323587220*uk_56 + 170162245*uk_57 + 627647625*uk_58 + 270585865*uk_59 + 61*uk_6 + 1141177500*uk_60 + 737961450*uk_61 + 882510600*uk_62 + 464078850*uk_63 + 1711766250*uk_64 + 737961450*uk_65 + 477215071*uk_66 + 570690188*uk_67 + 300104323*uk_68 + 1106942175*uk_69 + 225*uk_7 + 477215071*uk_70 + 682474864*uk_71 + 358887644*uk_72 + 1323765900*uk_73 + 570690188*uk_74 + 188725399*uk_75 + 696118275*uk_76 + 300104323*uk_77 + 2567649375*uk_78 + 1106942175*uk_79 + 97*uk_8 + 477215071*uk_80 + 166375*uk_81 + 453750*uk_82 + 293425*uk_83 + 350900*uk_84 + 184525*uk_85 + 680625*uk_86 + 293425*uk_87 + 1237500*uk_88 + 800250*uk_89 + 2572416961*uk_9 + 957000*uk_90 + 503250*uk_91 + 1856250*uk_92 + 800250*uk_93 + 517495*uk_94 + 618860*uk_95 + 325435*uk_96 + 1200375*uk_97 + 517495*uk_98 + 740080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 374220*uk_100 + 1336500*uk_101 + 891000*uk_102 + 218295*uk_103 + 779625*uk_104 + 519750*uk_105 + 2784375*uk_106 + 1856250*uk_107 + 1237500*uk_108 + 7189057*uk_109 + 9788767*uk_11 + 5587350*uk_110 + 4022892*uk_111 + 2346687*uk_112 + 8381025*uk_113 + 5587350*uk_114 + 4342500*uk_115 + 3126600*uk_116 + 1823850*uk_117 + 6513750*uk_118 + 4342500*uk_119 + 7607850*uk_12 + 2251152*uk_120 + 1313172*uk_121 + 4689900*uk_122 + 3126600*uk_123 + 766017*uk_124 + 2735775*uk_125 + 1823850*uk_126 + 9770625*uk_127 + 6513750*uk_128 + 4342500*uk_129 + 5477652*uk_13 + 3375000*uk_130 + 2430000*uk_131 + 1417500*uk_132 + 5062500*uk_133 + 3375000*uk_134 + 1749600*uk_135 + 1020600*uk_136 + 3645000*uk_137 + 2430000*uk_138 + 595350*uk_139 + 3195297*uk_14 + 2126250*uk_140 + 1417500*uk_141 + 7593750*uk_142 + 5062500*uk_143 + 3375000*uk_144 + 1259712*uk_145 + 734832*uk_146 + 2624400*uk_147 + 1749600*uk_148 + 428652*uk_149 + 11411775*uk_15 + 1530900*uk_150 + 1020600*uk_151 + 5467500*uk_152 + 3645000*uk_153 + 2430000*uk_154 + 250047*uk_155 + 893025*uk_156 + 595350*uk_157 + 3189375*uk_158 + 2126250*uk_159 + 7607850*uk_16 + 1417500*uk_160 + 11390625*uk_161 + 7593750*uk_162 + 5062500*uk_163 + 3375000*uk_164 + 3025*uk_17 + 10615*uk_18 + 8250*uk_19 + 55*uk_2 + 5940*uk_20 + 3465*uk_21 + 12375*uk_22 + 8250*uk_23 + 37249*uk_24 + 28950*uk_25 + 20844*uk_26 + 12159*uk_27 + 43425*uk_28 + 28950*uk_29 + 193*uk_3 + 22500*uk_30 + 16200*uk_31 + 9450*uk_32 + 33750*uk_33 + 22500*uk_34 + 11664*uk_35 + 6804*uk_36 + 24300*uk_37 + 16200*uk_38 + 3969*uk_39 + 150*uk_4 + 14175*uk_40 + 9450*uk_41 + 50625*uk_42 + 33750*uk_43 + 22500*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 496476473473*uk_47 + 385862544150*uk_48 + 277821031788*uk_49 + 108*uk_5 + 162062268543*uk_50 + 578793816225*uk_51 + 385862544150*uk_52 + 153424975*uk_53 + 538382185*uk_54 + 418431750*uk_55 + 301270860*uk_56 + 175741335*uk_57 + 627647625*uk_58 + 418431750*uk_59 + 63*uk_6 + 1889232031*uk_60 + 1468315050*uk_61 + 1057186836*uk_62 + 616692321*uk_63 + 2202472575*uk_64 + 1468315050*uk_65 + 1141177500*uk_66 + 821647800*uk_67 + 479294550*uk_68 + 1711766250*uk_69 + 225*uk_7 + 1141177500*uk_70 + 591586416*uk_71 + 345092076*uk_72 + 1232471700*uk_73 + 821647800*uk_74 + 201303711*uk_75 + 718941825*uk_76 + 479294550*uk_77 + 2567649375*uk_78 + 1711766250*uk_79 + 150*uk_8 + 1141177500*uk_80 + 166375*uk_81 + 583825*uk_82 + 453750*uk_83 + 326700*uk_84 + 190575*uk_85 + 680625*uk_86 + 453750*uk_87 + 2048695*uk_88 + 1592250*uk_89 + 2572416961*uk_9 + 1146420*uk_90 + 668745*uk_91 + 2388375*uk_92 + 1592250*uk_93 + 1237500*uk_94 + 891000*uk_95 + 519750*uk_96 + 1856250*uk_97 + 1237500*uk_98 + 641520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 357500*uk_100 + 1237500*uk_101 + 1061500*uk_102 + 232375*uk_103 + 804375*uk_104 + 689975*uk_105 + 2784375*uk_106 + 2388375*uk_107 + 2048695*uk_108 + 9800344*uk_109 + 10853866*uk_11 + 8838628*uk_110 + 4579600*uk_111 + 2976740*uk_112 + 10304100*uk_113 + 8838628*uk_114 + 7971286*uk_115 + 4130200*uk_116 + 2684630*uk_117 + 9292950*uk_118 + 7971286*uk_119 + 9788767*uk_12 + 2140000*uk_120 + 1391000*uk_121 + 4815000*uk_122 + 4130200*uk_123 + 904150*uk_124 + 3129750*uk_125 + 2684630*uk_126 + 10833750*uk_127 + 9292950*uk_128 + 7971286*uk_129 + 5071900*uk_13 + 7189057*uk_130 + 3724900*uk_131 + 2421185*uk_132 + 8381025*uk_133 + 7189057*uk_134 + 1930000*uk_135 + 1254500*uk_136 + 4342500*uk_137 + 3724900*uk_138 + 815425*uk_139 + 3296735*uk_14 + 2822625*uk_140 + 2421185*uk_141 + 9770625*uk_142 + 8381025*uk_143 + 7189057*uk_144 + 1000000*uk_145 + 650000*uk_146 + 2250000*uk_147 + 1930000*uk_148 + 422500*uk_149 + 11411775*uk_15 + 1462500*uk_150 + 1254500*uk_151 + 5062500*uk_152 + 4342500*uk_153 + 3724900*uk_154 + 274625*uk_155 + 950625*uk_156 + 815425*uk_157 + 3290625*uk_158 + 2822625*uk_159 + 9788767*uk_16 + 2421185*uk_160 + 11390625*uk_161 + 9770625*uk_162 + 8381025*uk_163 + 7189057*uk_164 + 3025*uk_17 + 11770*uk_18 + 10615*uk_19 + 55*uk_2 + 5500*uk_20 + 3575*uk_21 + 12375*uk_22 + 10615*uk_23 + 45796*uk_24 + 41302*uk_25 + 21400*uk_26 + 13910*uk_27 + 48150*uk_28 + 41302*uk_29 + 214*uk_3 + 37249*uk_30 + 19300*uk_31 + 12545*uk_32 + 43425*uk_33 + 37249*uk_34 + 10000*uk_35 + 6500*uk_36 + 22500*uk_37 + 19300*uk_38 + 4225*uk_39 + 193*uk_4 + 14625*uk_40 + 12545*uk_41 + 50625*uk_42 + 43425*uk_43 + 37249*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 550497229654*uk_47 + 496476473473*uk_48 + 257241696100*uk_49 + 100*uk_5 + 167207102465*uk_50 + 578793816225*uk_51 + 496476473473*uk_52 + 153424975*uk_53 + 596962630*uk_54 + 538382185*uk_55 + 278954500*uk_56 + 181320425*uk_57 + 627647625*uk_58 + 538382185*uk_59 + 65*uk_6 + 2322727324*uk_60 + 2094796138*uk_61 + 1085386600*uk_62 + 705501290*uk_63 + 2442119850*uk_64 + 2094796138*uk_65 + 1889232031*uk_66 + 978876700*uk_67 + 636269855*uk_68 + 2202472575*uk_69 + 225*uk_7 + 1889232031*uk_70 + 507190000*uk_71 + 329673500*uk_72 + 1141177500*uk_73 + 978876700*uk_74 + 214287775*uk_75 + 741765375*uk_76 + 636269855*uk_77 + 2567649375*uk_78 + 2202472575*uk_79 + 193*uk_8 + 1889232031*uk_80 + 166375*uk_81 + 647350*uk_82 + 583825*uk_83 + 302500*uk_84 + 196625*uk_85 + 680625*uk_86 + 583825*uk_87 + 2518780*uk_88 + 2271610*uk_89 + 2572416961*uk_9 + 1177000*uk_90 + 765050*uk_91 + 2648250*uk_92 + 2271610*uk_93 + 2048695*uk_94 + 1061500*uk_95 + 689975*uk_96 + 2388375*uk_97 + 2048695*uk_98 + 550000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 339020*uk_100 + 1138500*uk_101 + 1082840*uk_102 + 246895*uk_103 + 829125*uk_104 + 788590*uk_105 + 2784375*uk_106 + 2648250*uk_107 + 2518780*uk_108 + 8120601*uk_109 + 10194519*uk_11 + 8645814*uk_110 + 3716892*uk_111 + 2706867*uk_112 + 9090225*uk_113 + 8645814*uk_114 + 9204996*uk_115 + 3957288*uk_116 + 2881938*uk_117 + 9678150*uk_118 + 9204996*uk_119 + 10853866*uk_12 + 1701264*uk_120 + 1238964*uk_121 + 4160700*uk_122 + 3957288*uk_123 + 902289*uk_124 + 3030075*uk_125 + 2881938*uk_126 + 10175625*uk_127 + 9678150*uk_128 + 9204996*uk_129 + 4666148*uk_13 + 9800344*uk_130 + 4213232*uk_131 + 3068332*uk_132 + 10304100*uk_133 + 9800344*uk_134 + 1811296*uk_135 + 1319096*uk_136 + 4429800*uk_137 + 4213232*uk_138 + 960646*uk_139 + 3398173*uk_14 + 3226050*uk_140 + 3068332*uk_141 + 10833750*uk_142 + 10304100*uk_143 + 9800344*uk_144 + 778688*uk_145 + 567088*uk_146 + 1904400*uk_147 + 1811296*uk_148 + 412988*uk_149 + 11411775*uk_15 + 1386900*uk_150 + 1319096*uk_151 + 4657500*uk_152 + 4429800*uk_153 + 4213232*uk_154 + 300763*uk_155 + 1010025*uk_156 + 960646*uk_157 + 3391875*uk_158 + 3226050*uk_159 + 10853866*uk_16 + 3068332*uk_160 + 11390625*uk_161 + 10833750*uk_162 + 10304100*uk_163 + 9800344*uk_164 + 3025*uk_17 + 11055*uk_18 + 11770*uk_19 + 55*uk_2 + 5060*uk_20 + 3685*uk_21 + 12375*uk_22 + 11770*uk_23 + 40401*uk_24 + 43014*uk_25 + 18492*uk_26 + 13467*uk_27 + 45225*uk_28 + 43014*uk_29 + 201*uk_3 + 45796*uk_30 + 19688*uk_31 + 14338*uk_32 + 48150*uk_33 + 45796*uk_34 + 8464*uk_35 + 6164*uk_36 + 20700*uk_37 + 19688*uk_38 + 4489*uk_39 + 214*uk_4 + 15075*uk_40 + 14338*uk_41 + 50625*uk_42 + 48150*uk_43 + 45796*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 517055809161*uk_47 + 550497229654*uk_48 + 236662360412*uk_49 + 92*uk_5 + 172351936387*uk_50 + 578793816225*uk_51 + 550497229654*uk_52 + 153424975*uk_53 + 560698545*uk_54 + 596962630*uk_55 + 256638140*uk_56 + 186899515*uk_57 + 627647625*uk_58 + 596962630*uk_59 + 67*uk_6 + 2049098319*uk_60 + 2181627066*uk_61 + 937895748*uk_62 + 683032773*uk_63 + 2293766775*uk_64 + 2181627066*uk_65 + 2322727324*uk_66 + 998555672*uk_67 + 727209022*uk_68 + 2442119850*uk_69 + 225*uk_7 + 2322727324*uk_70 + 429285616*uk_71 + 312631916*uk_72 + 1049883300*uk_73 + 998555672*uk_74 + 227677591*uk_75 + 764588925*uk_76 + 727209022*uk_77 + 2567649375*uk_78 + 2442119850*uk_79 + 214*uk_8 + 2322727324*uk_80 + 166375*uk_81 + 608025*uk_82 + 647350*uk_83 + 278300*uk_84 + 202675*uk_85 + 680625*uk_86 + 647350*uk_87 + 2222055*uk_88 + 2365770*uk_89 + 2572416961*uk_9 + 1017060*uk_90 + 740685*uk_91 + 2487375*uk_92 + 2365770*uk_93 + 2518780*uk_94 + 1082840*uk_95 + 788590*uk_96 + 2648250*uk_97 + 2518780*uk_98 + 465520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 318780*uk_100 + 1039500*uk_101 + 928620*uk_102 + 261855*uk_103 + 853875*uk_104 + 762795*uk_105 + 2784375*uk_106 + 2487375*uk_107 + 2222055*uk_108 + 2863288*uk_109 + 7202098*uk_11 + 4052964*uk_110 + 1693776*uk_111 + 1391316*uk_112 + 4536900*uk_113 + 4052964*uk_114 + 5736942*uk_115 + 2397528*uk_116 + 1969398*uk_117 + 6421950*uk_118 + 5736942*uk_119 + 10194519*uk_12 + 1001952*uk_120 + 823032*uk_121 + 2683800*uk_122 + 2397528*uk_123 + 676062*uk_124 + 2204550*uk_125 + 1969398*uk_126 + 7188750*uk_127 + 6421950*uk_128 + 5736942*uk_129 + 4260396*uk_13 + 8120601*uk_130 + 3393684*uk_131 + 2787669*uk_132 + 9090225*uk_133 + 8120601*uk_134 + 1418256*uk_135 + 1164996*uk_136 + 3798900*uk_137 + 3393684*uk_138 + 956961*uk_139 + 3499611*uk_14 + 3120525*uk_140 + 2787669*uk_141 + 10175625*uk_142 + 9090225*uk_143 + 8120601*uk_144 + 592704*uk_145 + 486864*uk_146 + 1587600*uk_147 + 1418256*uk_148 + 399924*uk_149 + 11411775*uk_15 + 1304100*uk_150 + 1164996*uk_151 + 4252500*uk_152 + 3798900*uk_153 + 3393684*uk_154 + 328509*uk_155 + 1071225*uk_156 + 956961*uk_157 + 3493125*uk_158 + 3120525*uk_159 + 10194519*uk_16 + 2787669*uk_160 + 11390625*uk_161 + 10175625*uk_162 + 9090225*uk_163 + 8120601*uk_164 + 3025*uk_17 + 7810*uk_18 + 11055*uk_19 + 55*uk_2 + 4620*uk_20 + 3795*uk_21 + 12375*uk_22 + 11055*uk_23 + 20164*uk_24 + 28542*uk_25 + 11928*uk_26 + 9798*uk_27 + 31950*uk_28 + 28542*uk_29 + 142*uk_3 + 40401*uk_30 + 16884*uk_31 + 13869*uk_32 + 45225*uk_33 + 40401*uk_34 + 7056*uk_35 + 5796*uk_36 + 18900*uk_37 + 16884*uk_38 + 4761*uk_39 + 201*uk_4 + 15525*uk_40 + 13869*uk_41 + 50625*uk_42 + 45225*uk_43 + 40401*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 365283208462*uk_47 + 517055809161*uk_48 + 216083024724*uk_49 + 84*uk_5 + 177496770309*uk_50 + 578793816225*uk_51 + 517055809161*uk_52 + 153424975*uk_53 + 396115390*uk_54 + 560698545*uk_55 + 234321780*uk_56 + 192478605*uk_57 + 627647625*uk_58 + 560698545*uk_59 + 69*uk_6 + 1022697916*uk_60 + 1447621698*uk_61 + 604976232*uk_62 + 496944762*uk_63 + 1620472050*uk_64 + 1447621698*uk_65 + 2049098319*uk_66 + 856339596*uk_67 + 703421811*uk_68 + 2293766775*uk_69 + 225*uk_7 + 2049098319*uk_70 + 357873264*uk_71 + 293967324*uk_72 + 958589100*uk_73 + 856339596*uk_74 + 241473159*uk_75 + 787412475*uk_76 + 703421811*uk_77 + 2567649375*uk_78 + 2293766775*uk_79 + 201*uk_8 + 2049098319*uk_80 + 166375*uk_81 + 429550*uk_82 + 608025*uk_83 + 254100*uk_84 + 208725*uk_85 + 680625*uk_86 + 608025*uk_87 + 1109020*uk_88 + 1569810*uk_89 + 2572416961*uk_9 + 656040*uk_90 + 538890*uk_91 + 1757250*uk_92 + 1569810*uk_93 + 2222055*uk_94 + 928620*uk_95 + 762795*uk_96 + 2487375*uk_97 + 2222055*uk_98 + 388080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 296780*uk_100 + 940500*uk_101 + 593560*uk_102 + 277255*uk_103 + 878625*uk_104 + 554510*uk_105 + 2784375*uk_106 + 1757250*uk_107 + 1109020*uk_108 + 15625*uk_109 + 1267975*uk_11 + 88750*uk_110 + 47500*uk_111 + 44375*uk_112 + 140625*uk_113 + 88750*uk_114 + 504100*uk_115 + 269800*uk_116 + 252050*uk_117 + 798750*uk_118 + 504100*uk_119 + 7202098*uk_12 + 144400*uk_120 + 134900*uk_121 + 427500*uk_122 + 269800*uk_123 + 126025*uk_124 + 399375*uk_125 + 252050*uk_126 + 1265625*uk_127 + 798750*uk_128 + 504100*uk_129 + 3854644*uk_13 + 2863288*uk_130 + 1532464*uk_131 + 1431644*uk_132 + 4536900*uk_133 + 2863288*uk_134 + 820192*uk_135 + 766232*uk_136 + 2428200*uk_137 + 1532464*uk_138 + 715822*uk_139 + 3601049*uk_14 + 2268450*uk_140 + 1431644*uk_141 + 7188750*uk_142 + 4536900*uk_143 + 2863288*uk_144 + 438976*uk_145 + 410096*uk_146 + 1299600*uk_147 + 820192*uk_148 + 383116*uk_149 + 11411775*uk_15 + 1214100*uk_150 + 766232*uk_151 + 3847500*uk_152 + 2428200*uk_153 + 1532464*uk_154 + 357911*uk_155 + 1134225*uk_156 + 715822*uk_157 + 3594375*uk_158 + 2268450*uk_159 + 7202098*uk_16 + 1431644*uk_160 + 11390625*uk_161 + 7188750*uk_162 + 4536900*uk_163 + 2863288*uk_164 + 3025*uk_17 + 1375*uk_18 + 7810*uk_19 + 55*uk_2 + 4180*uk_20 + 3905*uk_21 + 12375*uk_22 + 7810*uk_23 + 625*uk_24 + 3550*uk_25 + 1900*uk_26 + 1775*uk_27 + 5625*uk_28 + 3550*uk_29 + 25*uk_3 + 20164*uk_30 + 10792*uk_31 + 10082*uk_32 + 31950*uk_33 + 20164*uk_34 + 5776*uk_35 + 5396*uk_36 + 17100*uk_37 + 10792*uk_38 + 5041*uk_39 + 142*uk_4 + 15975*uk_40 + 10082*uk_41 + 50625*uk_42 + 31950*uk_43 + 20164*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 64310424025*uk_47 + 365283208462*uk_48 + 195503689036*uk_49 + 76*uk_5 + 182641604231*uk_50 + 578793816225*uk_51 + 365283208462*uk_52 + 153424975*uk_53 + 69738625*uk_54 + 396115390*uk_55 + 212005420*uk_56 + 198057695*uk_57 + 627647625*uk_58 + 396115390*uk_59 + 71*uk_6 + 31699375*uk_60 + 180052450*uk_61 + 96366100*uk_62 + 90026225*uk_63 + 285294375*uk_64 + 180052450*uk_65 + 1022697916*uk_66 + 547359448*uk_67 + 511348958*uk_68 + 1620472050*uk_69 + 225*uk_7 + 1022697916*uk_70 + 292952944*uk_71 + 273679724*uk_72 + 867294900*uk_73 + 547359448*uk_74 + 255674479*uk_75 + 810236025*uk_76 + 511348958*uk_77 + 2567649375*uk_78 + 1620472050*uk_79 + 142*uk_8 + 1022697916*uk_80 + 166375*uk_81 + 75625*uk_82 + 429550*uk_83 + 229900*uk_84 + 214775*uk_85 + 680625*uk_86 + 429550*uk_87 + 34375*uk_88 + 195250*uk_89 + 2572416961*uk_9 + 104500*uk_90 + 97625*uk_91 + 309375*uk_92 + 195250*uk_93 + 1109020*uk_94 + 593560*uk_95 + 554510*uk_96 + 1757250*uk_97 + 1109020*uk_98 + 317680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 321200*uk_100 + 990000*uk_101 + 110000*uk_102 + 293095*uk_103 + 903375*uk_104 + 100375*uk_105 + 2784375*uk_106 + 309375*uk_107 + 34375*uk_108 + 185193*uk_109 + 2890983*uk_11 + 81225*uk_110 + 259920*uk_111 + 237177*uk_112 + 731025*uk_113 + 81225*uk_114 + 35625*uk_115 + 114000*uk_116 + 104025*uk_117 + 320625*uk_118 + 35625*uk_119 + 1267975*uk_12 + 364800*uk_120 + 332880*uk_121 + 1026000*uk_122 + 114000*uk_123 + 303753*uk_124 + 936225*uk_125 + 104025*uk_126 + 2885625*uk_127 + 320625*uk_128 + 35625*uk_129 + 4057520*uk_13 + 15625*uk_130 + 50000*uk_131 + 45625*uk_132 + 140625*uk_133 + 15625*uk_134 + 160000*uk_135 + 146000*uk_136 + 450000*uk_137 + 50000*uk_138 + 133225*uk_139 + 3702487*uk_14 + 410625*uk_140 + 45625*uk_141 + 1265625*uk_142 + 140625*uk_143 + 15625*uk_144 + 512000*uk_145 + 467200*uk_146 + 1440000*uk_147 + 160000*uk_148 + 426320*uk_149 + 11411775*uk_15 + 1314000*uk_150 + 146000*uk_151 + 4050000*uk_152 + 450000*uk_153 + 50000*uk_154 + 389017*uk_155 + 1199025*uk_156 + 133225*uk_157 + 3695625*uk_158 + 410625*uk_159 + 1267975*uk_16 + 45625*uk_160 + 11390625*uk_161 + 1265625*uk_162 + 140625*uk_163 + 15625*uk_164 + 3025*uk_17 + 3135*uk_18 + 1375*uk_19 + 55*uk_2 + 4400*uk_20 + 4015*uk_21 + 12375*uk_22 + 1375*uk_23 + 3249*uk_24 + 1425*uk_25 + 4560*uk_26 + 4161*uk_27 + 12825*uk_28 + 1425*uk_29 + 57*uk_3 + 625*uk_30 + 2000*uk_31 + 1825*uk_32 + 5625*uk_33 + 625*uk_34 + 6400*uk_35 + 5840*uk_36 + 18000*uk_37 + 2000*uk_38 + 5329*uk_39 + 25*uk_4 + 16425*uk_40 + 1825*uk_41 + 50625*uk_42 + 5625*uk_43 + 625*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 146627766777*uk_47 + 64310424025*uk_48 + 205793356880*uk_49 + 80*uk_5 + 187786438153*uk_50 + 578793816225*uk_51 + 64310424025*uk_52 + 153424975*uk_53 + 159004065*uk_54 + 69738625*uk_55 + 223163600*uk_56 + 203636785*uk_57 + 627647625*uk_58 + 69738625*uk_59 + 73*uk_6 + 164786031*uk_60 + 72274575*uk_61 + 231278640*uk_62 + 211041759*uk_63 + 650471175*uk_64 + 72274575*uk_65 + 31699375*uk_66 + 101438000*uk_67 + 92562175*uk_68 + 285294375*uk_69 + 225*uk_7 + 31699375*uk_70 + 324601600*uk_71 + 296198960*uk_72 + 912942000*uk_73 + 101438000*uk_74 + 270281551*uk_75 + 833059575*uk_76 + 92562175*uk_77 + 2567649375*uk_78 + 285294375*uk_79 + 25*uk_8 + 31699375*uk_80 + 166375*uk_81 + 172425*uk_82 + 75625*uk_83 + 242000*uk_84 + 220825*uk_85 + 680625*uk_86 + 75625*uk_87 + 178695*uk_88 + 78375*uk_89 + 2572416961*uk_9 + 250800*uk_90 + 228855*uk_91 + 705375*uk_92 + 78375*uk_93 + 34375*uk_94 + 110000*uk_95 + 100375*uk_96 + 309375*uk_97 + 34375*uk_98 + 352000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 297000*uk_100 + 891000*uk_101 + 225720*uk_102 + 309375*uk_103 + 928125*uk_104 + 235125*uk_105 + 2784375*uk_106 + 705375*uk_107 + 178695*uk_108 + 6859*uk_109 + 963661*uk_11 + 20577*uk_110 + 25992*uk_111 + 27075*uk_112 + 81225*uk_113 + 20577*uk_114 + 61731*uk_115 + 77976*uk_116 + 81225*uk_117 + 243675*uk_118 + 61731*uk_119 + 2890983*uk_12 + 98496*uk_120 + 102600*uk_121 + 307800*uk_122 + 77976*uk_123 + 106875*uk_124 + 320625*uk_125 + 81225*uk_126 + 961875*uk_127 + 243675*uk_128 + 61731*uk_129 + 3651768*uk_13 + 185193*uk_130 + 233928*uk_131 + 243675*uk_132 + 731025*uk_133 + 185193*uk_134 + 295488*uk_135 + 307800*uk_136 + 923400*uk_137 + 233928*uk_138 + 320625*uk_139 + 3803925*uk_14 + 961875*uk_140 + 243675*uk_141 + 2885625*uk_142 + 731025*uk_143 + 185193*uk_144 + 373248*uk_145 + 388800*uk_146 + 1166400*uk_147 + 295488*uk_148 + 405000*uk_149 + 11411775*uk_15 + 1215000*uk_150 + 307800*uk_151 + 3645000*uk_152 + 923400*uk_153 + 233928*uk_154 + 421875*uk_155 + 1265625*uk_156 + 320625*uk_157 + 3796875*uk_158 + 961875*uk_159 + 2890983*uk_16 + 243675*uk_160 + 11390625*uk_161 + 2885625*uk_162 + 731025*uk_163 + 185193*uk_164 + 3025*uk_17 + 1045*uk_18 + 3135*uk_19 + 55*uk_2 + 3960*uk_20 + 4125*uk_21 + 12375*uk_22 + 3135*uk_23 + 361*uk_24 + 1083*uk_25 + 1368*uk_26 + 1425*uk_27 + 4275*uk_28 + 1083*uk_29 + 19*uk_3 + 3249*uk_30 + 4104*uk_31 + 4275*uk_32 + 12825*uk_33 + 3249*uk_34 + 5184*uk_35 + 5400*uk_36 + 16200*uk_37 + 4104*uk_38 + 5625*uk_39 + 57*uk_4 + 16875*uk_40 + 4275*uk_41 + 50625*uk_42 + 12825*uk_43 + 3249*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 48875922259*uk_47 + 146627766777*uk_48 + 185214021192*uk_49 + 72*uk_5 + 192931272075*uk_50 + 578793816225*uk_51 + 146627766777*uk_52 + 153424975*uk_53 + 53001355*uk_54 + 159004065*uk_55 + 200847240*uk_56 + 209215875*uk_57 + 627647625*uk_58 + 159004065*uk_59 + 75*uk_6 + 18309559*uk_60 + 54928677*uk_61 + 69383592*uk_62 + 72274575*uk_63 + 216823725*uk_64 + 54928677*uk_65 + 164786031*uk_66 + 208150776*uk_67 + 216823725*uk_68 + 650471175*uk_69 + 225*uk_7 + 164786031*uk_70 + 262927296*uk_71 + 273882600*uk_72 + 821647800*uk_73 + 208150776*uk_74 + 285294375*uk_75 + 855883125*uk_76 + 216823725*uk_77 + 2567649375*uk_78 + 650471175*uk_79 + 57*uk_8 + 164786031*uk_80 + 166375*uk_81 + 57475*uk_82 + 172425*uk_83 + 217800*uk_84 + 226875*uk_85 + 680625*uk_86 + 172425*uk_87 + 19855*uk_88 + 59565*uk_89 + 2572416961*uk_9 + 75240*uk_90 + 78375*uk_91 + 235125*uk_92 + 59565*uk_93 + 178695*uk_94 + 225720*uk_95 + 235125*uk_96 + 705375*uk_97 + 178695*uk_98 + 285120*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 304920*uk_100 + 891000*uk_101 + 75240*uk_102 + 326095*uk_103 + 952875*uk_104 + 80465*uk_105 + 2784375*uk_106 + 235125*uk_107 + 19855*uk_108 + 148877*uk_109 + 2688107*uk_11 + 53371*uk_110 + 202248*uk_111 + 216293*uk_112 + 632025*uk_113 + 53371*uk_114 + 19133*uk_115 + 72504*uk_116 + 77539*uk_117 + 226575*uk_118 + 19133*uk_119 + 963661*uk_12 + 274752*uk_120 + 293832*uk_121 + 858600*uk_122 + 72504*uk_123 + 314237*uk_124 + 918225*uk_125 + 77539*uk_126 + 2683125*uk_127 + 226575*uk_128 + 19133*uk_129 + 3651768*uk_13 + 6859*uk_130 + 25992*uk_131 + 27797*uk_132 + 81225*uk_133 + 6859*uk_134 + 98496*uk_135 + 105336*uk_136 + 307800*uk_137 + 25992*uk_138 + 112651*uk_139 + 3905363*uk_14 + 329175*uk_140 + 27797*uk_141 + 961875*uk_142 + 81225*uk_143 + 6859*uk_144 + 373248*uk_145 + 399168*uk_146 + 1166400*uk_147 + 98496*uk_148 + 426888*uk_149 + 11411775*uk_15 + 1247400*uk_150 + 105336*uk_151 + 3645000*uk_152 + 307800*uk_153 + 25992*uk_154 + 456533*uk_155 + 1334025*uk_156 + 112651*uk_157 + 3898125*uk_158 + 329175*uk_159 + 963661*uk_16 + 27797*uk_160 + 11390625*uk_161 + 961875*uk_162 + 81225*uk_163 + 6859*uk_164 + 3025*uk_17 + 2915*uk_18 + 1045*uk_19 + 55*uk_2 + 3960*uk_20 + 4235*uk_21 + 12375*uk_22 + 1045*uk_23 + 2809*uk_24 + 1007*uk_25 + 3816*uk_26 + 4081*uk_27 + 11925*uk_28 + 1007*uk_29 + 53*uk_3 + 361*uk_30 + 1368*uk_31 + 1463*uk_32 + 4275*uk_33 + 361*uk_34 + 5184*uk_35 + 5544*uk_36 + 16200*uk_37 + 1368*uk_38 + 5929*uk_39 + 19*uk_4 + 17325*uk_40 + 1463*uk_41 + 50625*uk_42 + 4275*uk_43 + 361*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 136338098933*uk_47 + 48875922259*uk_48 + 185214021192*uk_49 + 72*uk_5 + 198076105997*uk_50 + 578793816225*uk_51 + 48875922259*uk_52 + 153424975*uk_53 + 147845885*uk_54 + 53001355*uk_55 + 200847240*uk_56 + 214794965*uk_57 + 627647625*uk_58 + 53001355*uk_59 + 77*uk_6 + 142469671*uk_60 + 51074033*uk_61 + 193543704*uk_62 + 206984239*uk_63 + 604824075*uk_64 + 51074033*uk_65 + 18309559*uk_66 + 69383592*uk_67 + 74201897*uk_68 + 216823725*uk_69 + 225*uk_7 + 18309559*uk_70 + 262927296*uk_71 + 281186136*uk_72 + 821647800*uk_73 + 69383592*uk_74 + 300712951*uk_75 + 878706675*uk_76 + 74201897*uk_77 + 2567649375*uk_78 + 216823725*uk_79 + 19*uk_8 + 18309559*uk_80 + 166375*uk_81 + 160325*uk_82 + 57475*uk_83 + 217800*uk_84 + 232925*uk_85 + 680625*uk_86 + 57475*uk_87 + 154495*uk_88 + 55385*uk_89 + 2572416961*uk_9 + 209880*uk_90 + 224455*uk_91 + 655875*uk_92 + 55385*uk_93 + 19855*uk_94 + 75240*uk_95 + 80465*uk_96 + 235125*uk_97 + 19855*uk_98 + 285120*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 278080*uk_100 + 792000*uk_101 + 186560*uk_102 + 343255*uk_103 + 977625*uk_104 + 230285*uk_105 + 2784375*uk_106 + 655875*uk_107 + 154495*uk_108 + uk_109 + 50719*uk_11 + 53*uk_110 + 64*uk_111 + 79*uk_112 + 225*uk_113 + 53*uk_114 + 2809*uk_115 + 3392*uk_116 + 4187*uk_117 + 11925*uk_118 + 2809*uk_119 + 2688107*uk_12 + 4096*uk_120 + 5056*uk_121 + 14400*uk_122 + 3392*uk_123 + 6241*uk_124 + 17775*uk_125 + 4187*uk_126 + 50625*uk_127 + 11925*uk_128 + 2809*uk_129 + 3246016*uk_13 + 148877*uk_130 + 179776*uk_131 + 221911*uk_132 + 632025*uk_133 + 148877*uk_134 + 217088*uk_135 + 267968*uk_136 + 763200*uk_137 + 179776*uk_138 + 330773*uk_139 + 4006801*uk_14 + 942075*uk_140 + 221911*uk_141 + 2683125*uk_142 + 632025*uk_143 + 148877*uk_144 + 262144*uk_145 + 323584*uk_146 + 921600*uk_147 + 217088*uk_148 + 399424*uk_149 + 11411775*uk_15 + 1137600*uk_150 + 267968*uk_151 + 3240000*uk_152 + 763200*uk_153 + 179776*uk_154 + 493039*uk_155 + 1404225*uk_156 + 330773*uk_157 + 3999375*uk_158 + 942075*uk_159 + 2688107*uk_16 + 221911*uk_160 + 11390625*uk_161 + 2683125*uk_162 + 632025*uk_163 + 148877*uk_164 + 3025*uk_17 + 55*uk_18 + 2915*uk_19 + 55*uk_2 + 3520*uk_20 + 4345*uk_21 + 12375*uk_22 + 2915*uk_23 + uk_24 + 53*uk_25 + 64*uk_26 + 79*uk_27 + 225*uk_28 + 53*uk_29 + uk_3 + 2809*uk_30 + 3392*uk_31 + 4187*uk_32 + 11925*uk_33 + 2809*uk_34 + 4096*uk_35 + 5056*uk_36 + 14400*uk_37 + 3392*uk_38 + 6241*uk_39 + 53*uk_4 + 17775*uk_40 + 4187*uk_41 + 50625*uk_42 + 11925*uk_43 + 2809*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 2572416961*uk_47 + 136338098933*uk_48 + 164634685504*uk_49 + 64*uk_5 + 203220939919*uk_50 + 578793816225*uk_51 + 136338098933*uk_52 + 153424975*uk_53 + 2789545*uk_54 + 147845885*uk_55 + 178530880*uk_56 + 220374055*uk_57 + 627647625*uk_58 + 147845885*uk_59 + 79*uk_6 + 50719*uk_60 + 2688107*uk_61 + 3246016*uk_62 + 4006801*uk_63 + 11411775*uk_64 + 2688107*uk_65 + 142469671*uk_66 + 172038848*uk_67 + 212360453*uk_68 + 604824075*uk_69 + 225*uk_7 + 142469671*uk_70 + 207745024*uk_71 + 256435264*uk_72 + 730353600*uk_73 + 172038848*uk_74 + 316537279*uk_75 + 901530225*uk_76 + 212360453*uk_77 + 2567649375*uk_78 + 604824075*uk_79 + 53*uk_8 + 142469671*uk_80 + 166375*uk_81 + 3025*uk_82 + 160325*uk_83 + 193600*uk_84 + 238975*uk_85 + 680625*uk_86 + 160325*uk_87 + 55*uk_88 + 2915*uk_89 + 2572416961*uk_9 + 3520*uk_90 + 4345*uk_91 + 12375*uk_92 + 2915*uk_93 + 154495*uk_94 + 186560*uk_95 + 230285*uk_96 + 655875*uk_97 + 154495*uk_98 + 225280*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 285120*uk_100 + 792000*uk_101 + 3520*uk_102 + 360855*uk_103 + 1002375*uk_104 + 4455*uk_105 + 2784375*uk_106 + 12375*uk_107 + 55*uk_108 + 2197*uk_109 + 659347*uk_11 + 169*uk_110 + 10816*uk_111 + 13689*uk_112 + 38025*uk_113 + 169*uk_114 + 13*uk_115 + 832*uk_116 + 1053*uk_117 + 2925*uk_118 + 13*uk_119 + 50719*uk_12 + 53248*uk_120 + 67392*uk_121 + 187200*uk_122 + 832*uk_123 + 85293*uk_124 + 236925*uk_125 + 1053*uk_126 + 658125*uk_127 + 2925*uk_128 + 13*uk_129 + 3246016*uk_13 + uk_130 + 64*uk_131 + 81*uk_132 + 225*uk_133 + uk_134 + 4096*uk_135 + 5184*uk_136 + 14400*uk_137 + 64*uk_138 + 6561*uk_139 + 4108239*uk_14 + 18225*uk_140 + 81*uk_141 + 50625*uk_142 + 225*uk_143 + uk_144 + 262144*uk_145 + 331776*uk_146 + 921600*uk_147 + 4096*uk_148 + 419904*uk_149 + 11411775*uk_15 + 1166400*uk_150 + 5184*uk_151 + 3240000*uk_152 + 14400*uk_153 + 64*uk_154 + 531441*uk_155 + 1476225*uk_156 + 6561*uk_157 + 4100625*uk_158 + 18225*uk_159 + 50719*uk_16 + 81*uk_160 + 11390625*uk_161 + 50625*uk_162 + 225*uk_163 + uk_164 + 3025*uk_17 + 715*uk_18 + 55*uk_19 + 55*uk_2 + 3520*uk_20 + 4455*uk_21 + 12375*uk_22 + 55*uk_23 + 169*uk_24 + 13*uk_25 + 832*uk_26 + 1053*uk_27 + 2925*uk_28 + 13*uk_29 + 13*uk_3 + uk_30 + 64*uk_31 + 81*uk_32 + 225*uk_33 + uk_34 + 4096*uk_35 + 5184*uk_36 + 14400*uk_37 + 64*uk_38 + 6561*uk_39 + uk_4 + 18225*uk_40 + 81*uk_41 + 50625*uk_42 + 225*uk_43 + uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 33441420493*uk_47 + 2572416961*uk_48 + 164634685504*uk_49 + 64*uk_5 + 208365773841*uk_50 + 578793816225*uk_51 + 2572416961*uk_52 + 153424975*uk_53 + 36264085*uk_54 + 2789545*uk_55 + 178530880*uk_56 + 225953145*uk_57 + 627647625*uk_58 + 2789545*uk_59 + 81*uk_6 + 8571511*uk_60 + 659347*uk_61 + 42198208*uk_62 + 53407107*uk_63 + 148353075*uk_64 + 659347*uk_65 + 50719*uk_66 + 3246016*uk_67 + 4108239*uk_68 + 11411775*uk_69 + 225*uk_7 + 50719*uk_70 + 207745024*uk_71 + 262927296*uk_72 + 730353600*uk_73 + 3246016*uk_74 + 332767359*uk_75 + 924353775*uk_76 + 4108239*uk_77 + 2567649375*uk_78 + 11411775*uk_79 + uk_8 + 50719*uk_80 + 166375*uk_81 + 39325*uk_82 + 3025*uk_83 + 193600*uk_84 + 245025*uk_85 + 680625*uk_86 + 3025*uk_87 + 9295*uk_88 + 715*uk_89 + 2572416961*uk_9 + 45760*uk_90 + 57915*uk_91 + 160875*uk_92 + 715*uk_93 + 55*uk_94 + 3520*uk_95 + 4455*uk_96 + 12375*uk_97 + 55*uk_98 + 225280*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 273900*uk_100 + 742500*uk_101 + 42900*uk_102 + 378895*uk_103 + 1027125*uk_104 + 59345*uk_105 + 2784375*uk_106 + 160875*uk_107 + 9295*uk_108 + 216*uk_109 + 304314*uk_11 + 468*uk_110 + 2160*uk_111 + 2988*uk_112 + 8100*uk_113 + 468*uk_114 + 1014*uk_115 + 4680*uk_116 + 6474*uk_117 + 17550*uk_118 + 1014*uk_119 + 659347*uk_12 + 21600*uk_120 + 29880*uk_121 + 81000*uk_122 + 4680*uk_123 + 41334*uk_124 + 112050*uk_125 + 6474*uk_126 + 303750*uk_127 + 17550*uk_128 + 1014*uk_129 + 3043140*uk_13 + 2197*uk_130 + 10140*uk_131 + 14027*uk_132 + 38025*uk_133 + 2197*uk_134 + 46800*uk_135 + 64740*uk_136 + 175500*uk_137 + 10140*uk_138 + 89557*uk_139 + 4209677*uk_14 + 242775*uk_140 + 14027*uk_141 + 658125*uk_142 + 38025*uk_143 + 2197*uk_144 + 216000*uk_145 + 298800*uk_146 + 810000*uk_147 + 46800*uk_148 + 413340*uk_149 + 11411775*uk_15 + 1120500*uk_150 + 64740*uk_151 + 3037500*uk_152 + 175500*uk_153 + 10140*uk_154 + 571787*uk_155 + 1550025*uk_156 + 89557*uk_157 + 4201875*uk_158 + 242775*uk_159 + 659347*uk_16 + 14027*uk_160 + 11390625*uk_161 + 658125*uk_162 + 38025*uk_163 + 2197*uk_164 + 3025*uk_17 + 330*uk_18 + 715*uk_19 + 55*uk_2 + 3300*uk_20 + 4565*uk_21 + 12375*uk_22 + 715*uk_23 + 36*uk_24 + 78*uk_25 + 360*uk_26 + 498*uk_27 + 1350*uk_28 + 78*uk_29 + 6*uk_3 + 169*uk_30 + 780*uk_31 + 1079*uk_32 + 2925*uk_33 + 169*uk_34 + 3600*uk_35 + 4980*uk_36 + 13500*uk_37 + 780*uk_38 + 6889*uk_39 + 13*uk_4 + 18675*uk_40 + 1079*uk_41 + 50625*uk_42 + 2925*uk_43 + 169*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 15434501766*uk_47 + 33441420493*uk_48 + 154345017660*uk_49 + 60*uk_5 + 213510607763*uk_50 + 578793816225*uk_51 + 33441420493*uk_52 + 153424975*uk_53 + 16737270*uk_54 + 36264085*uk_55 + 167372700*uk_56 + 231532235*uk_57 + 627647625*uk_58 + 36264085*uk_59 + 83*uk_6 + 1825884*uk_60 + 3956082*uk_61 + 18258840*uk_62 + 25258062*uk_63 + 68470650*uk_64 + 3956082*uk_65 + 8571511*uk_66 + 39560820*uk_67 + 54725801*uk_68 + 148353075*uk_69 + 225*uk_7 + 8571511*uk_70 + 182588400*uk_71 + 252580620*uk_72 + 684706500*uk_73 + 39560820*uk_74 + 349403191*uk_75 + 947177325*uk_76 + 54725801*uk_77 + 2567649375*uk_78 + 148353075*uk_79 + 13*uk_8 + 8571511*uk_80 + 166375*uk_81 + 18150*uk_82 + 39325*uk_83 + 181500*uk_84 + 251075*uk_85 + 680625*uk_86 + 39325*uk_87 + 1980*uk_88 + 4290*uk_89 + 2572416961*uk_9 + 19800*uk_90 + 27390*uk_91 + 74250*uk_92 + 4290*uk_93 + 9295*uk_94 + 42900*uk_95 + 59345*uk_96 + 160875*uk_97 + 9295*uk_98 + 198000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 280500*uk_100 + 742500*uk_101 + 19800*uk_102 + 397375*uk_103 + 1051875*uk_104 + 28050*uk_105 + 2784375*uk_106 + 74250*uk_107 + 1980*uk_108 + 205379*uk_109 + 2992421*uk_11 + 20886*uk_110 + 208860*uk_111 + 295885*uk_112 + 783225*uk_113 + 20886*uk_114 + 2124*uk_115 + 21240*uk_116 + 30090*uk_117 + 79650*uk_118 + 2124*uk_119 + 304314*uk_12 + 212400*uk_120 + 300900*uk_121 + 796500*uk_122 + 21240*uk_123 + 426275*uk_124 + 1128375*uk_125 + 30090*uk_126 + 2986875*uk_127 + 79650*uk_128 + 2124*uk_129 + 3043140*uk_13 + 216*uk_130 + 2160*uk_131 + 3060*uk_132 + 8100*uk_133 + 216*uk_134 + 21600*uk_135 + 30600*uk_136 + 81000*uk_137 + 2160*uk_138 + 43350*uk_139 + 4311115*uk_14 + 114750*uk_140 + 3060*uk_141 + 303750*uk_142 + 8100*uk_143 + 216*uk_144 + 216000*uk_145 + 306000*uk_146 + 810000*uk_147 + 21600*uk_148 + 433500*uk_149 + 11411775*uk_15 + 1147500*uk_150 + 30600*uk_151 + 3037500*uk_152 + 81000*uk_153 + 2160*uk_154 + 614125*uk_155 + 1625625*uk_156 + 43350*uk_157 + 4303125*uk_158 + 114750*uk_159 + 304314*uk_16 + 3060*uk_160 + 11390625*uk_161 + 303750*uk_162 + 8100*uk_163 + 216*uk_164 + 3025*uk_17 + 3245*uk_18 + 330*uk_19 + 55*uk_2 + 3300*uk_20 + 4675*uk_21 + 12375*uk_22 + 330*uk_23 + 3481*uk_24 + 354*uk_25 + 3540*uk_26 + 5015*uk_27 + 13275*uk_28 + 354*uk_29 + 59*uk_3 + 36*uk_30 + 360*uk_31 + 510*uk_32 + 1350*uk_33 + 36*uk_34 + 3600*uk_35 + 5100*uk_36 + 13500*uk_37 + 360*uk_38 + 7225*uk_39 + 6*uk_4 + 19125*uk_40 + 510*uk_41 + 50625*uk_42 + 1350*uk_43 + 36*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 151772600699*uk_47 + 15434501766*uk_48 + 154345017660*uk_49 + 60*uk_5 + 218655441685*uk_50 + 578793816225*uk_51 + 15434501766*uk_52 + 153424975*uk_53 + 164583155*uk_54 + 16737270*uk_55 + 167372700*uk_56 + 237111325*uk_57 + 627647625*uk_58 + 16737270*uk_59 + 85*uk_6 + 176552839*uk_60 + 17954526*uk_61 + 179545260*uk_62 + 254355785*uk_63 + 673294725*uk_64 + 17954526*uk_65 + 1825884*uk_66 + 18258840*uk_67 + 25866690*uk_68 + 68470650*uk_69 + 225*uk_7 + 1825884*uk_70 + 182588400*uk_71 + 258666900*uk_72 + 684706500*uk_73 + 18258840*uk_74 + 366444775*uk_75 + 970000875*uk_76 + 25866690*uk_77 + 2567649375*uk_78 + 68470650*uk_79 + 6*uk_8 + 1825884*uk_80 + 166375*uk_81 + 178475*uk_82 + 18150*uk_83 + 181500*uk_84 + 257125*uk_85 + 680625*uk_86 + 18150*uk_87 + 191455*uk_88 + 19470*uk_89 + 2572416961*uk_9 + 194700*uk_90 + 275825*uk_91 + 730125*uk_92 + 19470*uk_93 + 1980*uk_94 + 19800*uk_95 + 28050*uk_96 + 74250*uk_97 + 1980*uk_98 + 198000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 267960*uk_100 + 693000*uk_101 + 181720*uk_102 + 416295*uk_103 + 1076625*uk_104 + 282315*uk_105 + 2784375*uk_106 + 730125*uk_107 + 191455*uk_108 + 614125*uk_109 + 4311115*uk_11 + 426275*uk_110 + 404600*uk_111 + 628575*uk_112 + 1625625*uk_113 + 426275*uk_114 + 295885*uk_115 + 280840*uk_116 + 436305*uk_117 + 1128375*uk_118 + 295885*uk_119 + 2992421*uk_12 + 266560*uk_120 + 414120*uk_121 + 1071000*uk_122 + 280840*uk_123 + 643365*uk_124 + 1663875*uk_125 + 436305*uk_126 + 4303125*uk_127 + 1128375*uk_128 + 295885*uk_129 + 2840264*uk_13 + 205379*uk_130 + 194936*uk_131 + 302847*uk_132 + 783225*uk_133 + 205379*uk_134 + 185024*uk_135 + 287448*uk_136 + 743400*uk_137 + 194936*uk_138 + 446571*uk_139 + 4412553*uk_14 + 1154925*uk_140 + 302847*uk_141 + 2986875*uk_142 + 783225*uk_143 + 205379*uk_144 + 175616*uk_145 + 272832*uk_146 + 705600*uk_147 + 185024*uk_148 + 423864*uk_149 + 11411775*uk_15 + 1096200*uk_150 + 287448*uk_151 + 2835000*uk_152 + 743400*uk_153 + 194936*uk_154 + 658503*uk_155 + 1703025*uk_156 + 446571*uk_157 + 4404375*uk_158 + 1154925*uk_159 + 2992421*uk_16 + 302847*uk_160 + 11390625*uk_161 + 2986875*uk_162 + 783225*uk_163 + 205379*uk_164 + 3025*uk_17 + 4675*uk_18 + 3245*uk_19 + 55*uk_2 + 3080*uk_20 + 4785*uk_21 + 12375*uk_22 + 3245*uk_23 + 7225*uk_24 + 5015*uk_25 + 4760*uk_26 + 7395*uk_27 + 19125*uk_28 + 5015*uk_29 + 85*uk_3 + 3481*uk_30 + 3304*uk_31 + 5133*uk_32 + 13275*uk_33 + 3481*uk_34 + 3136*uk_35 + 4872*uk_36 + 12600*uk_37 + 3304*uk_38 + 7569*uk_39 + 59*uk_4 + 19575*uk_40 + 5133*uk_41 + 50625*uk_42 + 13275*uk_43 + 3481*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 218655441685*uk_47 + 151772600699*uk_48 + 144055349816*uk_49 + 56*uk_5 + 223800275607*uk_50 + 578793816225*uk_51 + 151772600699*uk_52 + 153424975*uk_53 + 237111325*uk_54 + 164583155*uk_55 + 156214520*uk_56 + 242690415*uk_57 + 627647625*uk_58 + 164583155*uk_59 + 87*uk_6 + 366444775*uk_60 + 254355785*uk_61 + 241422440*uk_62 + 375067005*uk_63 + 970000875*uk_64 + 254355785*uk_65 + 176552839*uk_66 + 167575576*uk_67 + 260340627*uk_68 + 673294725*uk_69 + 225*uk_7 + 176552839*uk_70 + 159054784*uk_71 + 247102968*uk_72 + 639059400*uk_73 + 167575576*uk_74 + 383892111*uk_75 + 992824425*uk_76 + 260340627*uk_77 + 2567649375*uk_78 + 673294725*uk_79 + 59*uk_8 + 176552839*uk_80 + 166375*uk_81 + 257125*uk_82 + 178475*uk_83 + 169400*uk_84 + 263175*uk_85 + 680625*uk_86 + 178475*uk_87 + 397375*uk_88 + 275825*uk_89 + 2572416961*uk_9 + 261800*uk_90 + 406725*uk_91 + 1051875*uk_92 + 275825*uk_93 + 191455*uk_94 + 181720*uk_95 + 282315*uk_96 + 730125*uk_97 + 191455*uk_98 + 172480*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 254540*uk_100 + 643500*uk_101 + 243100*uk_102 + 435655*uk_103 + 1101375*uk_104 + 416075*uk_105 + 2784375*uk_106 + 1051875*uk_107 + 397375*uk_108 + 474552*uk_109 + 3956082*uk_11 + 517140*uk_110 + 316368*uk_111 + 541476*uk_112 + 1368900*uk_113 + 517140*uk_114 + 563550*uk_115 + 344760*uk_116 + 590070*uk_117 + 1491750*uk_118 + 563550*uk_119 + 4311115*uk_12 + 210912*uk_120 + 360984*uk_121 + 912600*uk_122 + 344760*uk_123 + 617838*uk_124 + 1561950*uk_125 + 590070*uk_126 + 3948750*uk_127 + 1491750*uk_128 + 563550*uk_129 + 2637388*uk_13 + 614125*uk_130 + 375700*uk_131 + 643025*uk_132 + 1625625*uk_133 + 614125*uk_134 + 229840*uk_135 + 393380*uk_136 + 994500*uk_137 + 375700*uk_138 + 673285*uk_139 + 4513991*uk_14 + 1702125*uk_140 + 643025*uk_141 + 4303125*uk_142 + 1625625*uk_143 + 614125*uk_144 + 140608*uk_145 + 240656*uk_146 + 608400*uk_147 + 229840*uk_148 + 411892*uk_149 + 11411775*uk_15 + 1041300*uk_150 + 393380*uk_151 + 2632500*uk_152 + 994500*uk_153 + 375700*uk_154 + 704969*uk_155 + 1782225*uk_156 + 673285*uk_157 + 4505625*uk_158 + 1702125*uk_159 + 4311115*uk_16 + 643025*uk_160 + 11390625*uk_161 + 4303125*uk_162 + 1625625*uk_163 + 614125*uk_164 + 3025*uk_17 + 4290*uk_18 + 4675*uk_19 + 55*uk_2 + 2860*uk_20 + 4895*uk_21 + 12375*uk_22 + 4675*uk_23 + 6084*uk_24 + 6630*uk_25 + 4056*uk_26 + 6942*uk_27 + 17550*uk_28 + 6630*uk_29 + 78*uk_3 + 7225*uk_30 + 4420*uk_31 + 7565*uk_32 + 19125*uk_33 + 7225*uk_34 + 2704*uk_35 + 4628*uk_36 + 11700*uk_37 + 4420*uk_38 + 7921*uk_39 + 85*uk_4 + 20025*uk_40 + 7565*uk_41 + 50625*uk_42 + 19125*uk_43 + 7225*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 200648522958*uk_47 + 218655441685*uk_48 + 133765681972*uk_49 + 52*uk_5 + 228945109529*uk_50 + 578793816225*uk_51 + 218655441685*uk_52 + 153424975*uk_53 + 217584510*uk_54 + 237111325*uk_55 + 145056340*uk_56 + 248269505*uk_57 + 627647625*uk_58 + 237111325*uk_59 + 89*uk_6 + 308574396*uk_60 + 336266970*uk_61 + 205716264*uk_62 + 352091298*uk_63 + 890118450*uk_64 + 336266970*uk_65 + 366444775*uk_66 + 224177980*uk_67 + 383689235*uk_68 + 970000875*uk_69 + 225*uk_7 + 366444775*uk_70 + 137144176*uk_71 + 234727532*uk_72 + 593412300*uk_73 + 224177980*uk_74 + 401745199*uk_75 + 1015647975*uk_76 + 383689235*uk_77 + 2567649375*uk_78 + 970000875*uk_79 + 85*uk_8 + 366444775*uk_80 + 166375*uk_81 + 235950*uk_82 + 257125*uk_83 + 157300*uk_84 + 269225*uk_85 + 680625*uk_86 + 257125*uk_87 + 334620*uk_88 + 364650*uk_89 + 2572416961*uk_9 + 223080*uk_90 + 381810*uk_91 + 965250*uk_92 + 364650*uk_93 + 397375*uk_94 + 243100*uk_95 + 416075*uk_96 + 1051875*uk_97 + 397375*uk_98 + 148720*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 240240*uk_100 + 594000*uk_101 + 205920*uk_102 + 455455*uk_103 + 1126125*uk_104 + 390390*uk_105 + 2784375*uk_106 + 965250*uk_107 + 334620*uk_108 + 32768*uk_109 + 1623008*uk_11 + 79872*uk_110 + 49152*uk_111 + 93184*uk_112 + 230400*uk_113 + 79872*uk_114 + 194688*uk_115 + 119808*uk_116 + 227136*uk_117 + 561600*uk_118 + 194688*uk_119 + 3956082*uk_12 + 73728*uk_120 + 139776*uk_121 + 345600*uk_122 + 119808*uk_123 + 264992*uk_124 + 655200*uk_125 + 227136*uk_126 + 1620000*uk_127 + 561600*uk_128 + 194688*uk_129 + 2434512*uk_13 + 474552*uk_130 + 292032*uk_131 + 553644*uk_132 + 1368900*uk_133 + 474552*uk_134 + 179712*uk_135 + 340704*uk_136 + 842400*uk_137 + 292032*uk_138 + 645918*uk_139 + 4615429*uk_14 + 1597050*uk_140 + 553644*uk_141 + 3948750*uk_142 + 1368900*uk_143 + 474552*uk_144 + 110592*uk_145 + 209664*uk_146 + 518400*uk_147 + 179712*uk_148 + 397488*uk_149 + 11411775*uk_15 + 982800*uk_150 + 340704*uk_151 + 2430000*uk_152 + 842400*uk_153 + 292032*uk_154 + 753571*uk_155 + 1863225*uk_156 + 645918*uk_157 + 4606875*uk_158 + 1597050*uk_159 + 3956082*uk_16 + 553644*uk_160 + 11390625*uk_161 + 3948750*uk_162 + 1368900*uk_163 + 474552*uk_164 + 3025*uk_17 + 1760*uk_18 + 4290*uk_19 + 55*uk_2 + 2640*uk_20 + 5005*uk_21 + 12375*uk_22 + 4290*uk_23 + 1024*uk_24 + 2496*uk_25 + 1536*uk_26 + 2912*uk_27 + 7200*uk_28 + 2496*uk_29 + 32*uk_3 + 6084*uk_30 + 3744*uk_31 + 7098*uk_32 + 17550*uk_33 + 6084*uk_34 + 2304*uk_35 + 4368*uk_36 + 10800*uk_37 + 3744*uk_38 + 8281*uk_39 + 78*uk_4 + 20475*uk_40 + 7098*uk_41 + 50625*uk_42 + 17550*uk_43 + 6084*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 82317342752*uk_47 + 200648522958*uk_48 + 123476014128*uk_49 + 48*uk_5 + 234089943451*uk_50 + 578793816225*uk_51 + 200648522958*uk_52 + 153424975*uk_53 + 89265440*uk_54 + 217584510*uk_55 + 133898160*uk_56 + 253848595*uk_57 + 627647625*uk_58 + 217584510*uk_59 + 91*uk_6 + 51936256*uk_60 + 126594624*uk_61 + 77904384*uk_62 + 147693728*uk_63 + 365176800*uk_64 + 126594624*uk_65 + 308574396*uk_66 + 189891936*uk_67 + 360003462*uk_68 + 890118450*uk_69 + 225*uk_7 + 308574396*uk_70 + 116856576*uk_71 + 221540592*uk_72 + 547765200*uk_73 + 189891936*uk_74 + 420004039*uk_75 + 1038471525*uk_76 + 360003462*uk_77 + 2567649375*uk_78 + 890118450*uk_79 + 78*uk_8 + 308574396*uk_80 + 166375*uk_81 + 96800*uk_82 + 235950*uk_83 + 145200*uk_84 + 275275*uk_85 + 680625*uk_86 + 235950*uk_87 + 56320*uk_88 + 137280*uk_89 + 2572416961*uk_9 + 84480*uk_90 + 160160*uk_91 + 396000*uk_92 + 137280*uk_93 + 334620*uk_94 + 205920*uk_95 + 390390*uk_96 + 965250*uk_97 + 334620*uk_98 + 126720*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 245520*uk_100 + 594000*uk_101 + 84480*uk_102 + 475695*uk_103 + 1150875*uk_104 + 163680*uk_105 + 2784375*uk_106 + 396000*uk_107 + 56320*uk_108 + 39304*uk_109 + 1724446*uk_11 + 36992*uk_110 + 55488*uk_111 + 107508*uk_112 + 260100*uk_113 + 36992*uk_114 + 34816*uk_115 + 52224*uk_116 + 101184*uk_117 + 244800*uk_118 + 34816*uk_119 + 1623008*uk_12 + 78336*uk_120 + 151776*uk_121 + 367200*uk_122 + 52224*uk_123 + 294066*uk_124 + 711450*uk_125 + 101184*uk_126 + 1721250*uk_127 + 244800*uk_128 + 34816*uk_129 + 2434512*uk_13 + 32768*uk_130 + 49152*uk_131 + 95232*uk_132 + 230400*uk_133 + 32768*uk_134 + 73728*uk_135 + 142848*uk_136 + 345600*uk_137 + 49152*uk_138 + 276768*uk_139 + 4716867*uk_14 + 669600*uk_140 + 95232*uk_141 + 1620000*uk_142 + 230400*uk_143 + 32768*uk_144 + 110592*uk_145 + 214272*uk_146 + 518400*uk_147 + 73728*uk_148 + 415152*uk_149 + 11411775*uk_15 + 1004400*uk_150 + 142848*uk_151 + 2430000*uk_152 + 345600*uk_153 + 49152*uk_154 + 804357*uk_155 + 1946025*uk_156 + 276768*uk_157 + 4708125*uk_158 + 669600*uk_159 + 1623008*uk_16 + 95232*uk_160 + 11390625*uk_161 + 1620000*uk_162 + 230400*uk_163 + 32768*uk_164 + 3025*uk_17 + 1870*uk_18 + 1760*uk_19 + 55*uk_2 + 2640*uk_20 + 5115*uk_21 + 12375*uk_22 + 1760*uk_23 + 1156*uk_24 + 1088*uk_25 + 1632*uk_26 + 3162*uk_27 + 7650*uk_28 + 1088*uk_29 + 34*uk_3 + 1024*uk_30 + 1536*uk_31 + 2976*uk_32 + 7200*uk_33 + 1024*uk_34 + 2304*uk_35 + 4464*uk_36 + 10800*uk_37 + 1536*uk_38 + 8649*uk_39 + 32*uk_4 + 20925*uk_40 + 2976*uk_41 + 50625*uk_42 + 7200*uk_43 + 1024*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 87462176674*uk_47 + 82317342752*uk_48 + 123476014128*uk_49 + 48*uk_5 + 239234777373*uk_50 + 578793816225*uk_51 + 82317342752*uk_52 + 153424975*uk_53 + 94844530*uk_54 + 89265440*uk_55 + 133898160*uk_56 + 259427685*uk_57 + 627647625*uk_58 + 89265440*uk_59 + 93*uk_6 + 58631164*uk_60 + 55182272*uk_61 + 82773408*uk_62 + 160373478*uk_63 + 388000350*uk_64 + 55182272*uk_65 + 51936256*uk_66 + 77904384*uk_67 + 150939744*uk_68 + 365176800*uk_69 + 225*uk_7 + 51936256*uk_70 + 116856576*uk_71 + 226409616*uk_72 + 547765200*uk_73 + 77904384*uk_74 + 438668631*uk_75 + 1061295075*uk_76 + 150939744*uk_77 + 2567649375*uk_78 + 365176800*uk_79 + 32*uk_8 + 51936256*uk_80 + 166375*uk_81 + 102850*uk_82 + 96800*uk_83 + 145200*uk_84 + 281325*uk_85 + 680625*uk_86 + 96800*uk_87 + 63580*uk_88 + 59840*uk_89 + 2572416961*uk_9 + 89760*uk_90 + 173910*uk_91 + 420750*uk_92 + 59840*uk_93 + 56320*uk_94 + 84480*uk_95 + 163680*uk_96 + 396000*uk_97 + 56320*uk_98 + 126720*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 250800*uk_100 + 594000*uk_101 + 89760*uk_102 + 496375*uk_103 + 1175625*uk_104 + 177650*uk_105 + 2784375*uk_106 + 420750*uk_107 + 63580*uk_108 + 592704*uk_109 + 4260396*uk_11 + 239904*uk_110 + 338688*uk_111 + 670320*uk_112 + 1587600*uk_113 + 239904*uk_114 + 97104*uk_115 + 137088*uk_116 + 271320*uk_117 + 642600*uk_118 + 97104*uk_119 + 1724446*uk_12 + 193536*uk_120 + 383040*uk_121 + 907200*uk_122 + 137088*uk_123 + 758100*uk_124 + 1795500*uk_125 + 271320*uk_126 + 4252500*uk_127 + 642600*uk_128 + 97104*uk_129 + 2434512*uk_13 + 39304*uk_130 + 55488*uk_131 + 109820*uk_132 + 260100*uk_133 + 39304*uk_134 + 78336*uk_135 + 155040*uk_136 + 367200*uk_137 + 55488*uk_138 + 306850*uk_139 + 4818305*uk_14 + 726750*uk_140 + 109820*uk_141 + 1721250*uk_142 + 260100*uk_143 + 39304*uk_144 + 110592*uk_145 + 218880*uk_146 + 518400*uk_147 + 78336*uk_148 + 433200*uk_149 + 11411775*uk_15 + 1026000*uk_150 + 155040*uk_151 + 2430000*uk_152 + 367200*uk_153 + 55488*uk_154 + 857375*uk_155 + 2030625*uk_156 + 306850*uk_157 + 4809375*uk_158 + 726750*uk_159 + 1724446*uk_16 + 109820*uk_160 + 11390625*uk_161 + 1721250*uk_162 + 260100*uk_163 + 39304*uk_164 + 3025*uk_17 + 4620*uk_18 + 1870*uk_19 + 55*uk_2 + 2640*uk_20 + 5225*uk_21 + 12375*uk_22 + 1870*uk_23 + 7056*uk_24 + 2856*uk_25 + 4032*uk_26 + 7980*uk_27 + 18900*uk_28 + 2856*uk_29 + 84*uk_3 + 1156*uk_30 + 1632*uk_31 + 3230*uk_32 + 7650*uk_33 + 1156*uk_34 + 2304*uk_35 + 4560*uk_36 + 10800*uk_37 + 1632*uk_38 + 9025*uk_39 + 34*uk_4 + 21375*uk_40 + 3230*uk_41 + 50625*uk_42 + 7650*uk_43 + 1156*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 216083024724*uk_47 + 87462176674*uk_48 + 123476014128*uk_49 + 48*uk_5 + 244379611295*uk_50 + 578793816225*uk_51 + 87462176674*uk_52 + 153424975*uk_53 + 234321780*uk_54 + 94844530*uk_55 + 133898160*uk_56 + 265006775*uk_57 + 627647625*uk_58 + 94844530*uk_59 + 95*uk_6 + 357873264*uk_60 + 144853464*uk_61 + 204499008*uk_62 + 404737620*uk_63 + 958589100*uk_64 + 144853464*uk_65 + 58631164*uk_66 + 82773408*uk_67 + 163822370*uk_68 + 388000350*uk_69 + 225*uk_7 + 58631164*uk_70 + 116856576*uk_71 + 231278640*uk_72 + 547765200*uk_73 + 82773408*uk_74 + 457738975*uk_75 + 1084118625*uk_76 + 163822370*uk_77 + 2567649375*uk_78 + 388000350*uk_79 + 34*uk_8 + 58631164*uk_80 + 166375*uk_81 + 254100*uk_82 + 102850*uk_83 + 145200*uk_84 + 287375*uk_85 + 680625*uk_86 + 102850*uk_87 + 388080*uk_88 + 157080*uk_89 + 2572416961*uk_9 + 221760*uk_90 + 438900*uk_91 + 1039500*uk_92 + 157080*uk_93 + 63580*uk_94 + 89760*uk_95 + 177650*uk_96 + 420750*uk_97 + 63580*uk_98 + 126720*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 234740*uk_100 + 544500*uk_101 + 203280*uk_102 + 517495*uk_103 + 1200375*uk_104 + 448140*uk_105 + 2784375*uk_106 + 1039500*uk_107 + 388080*uk_108 + 614125*uk_109 + 4311115*uk_11 + 606900*uk_110 + 317900*uk_111 + 700825*uk_112 + 1625625*uk_113 + 606900*uk_114 + 599760*uk_115 + 314160*uk_116 + 692580*uk_117 + 1606500*uk_118 + 599760*uk_119 + 4260396*uk_12 + 164560*uk_120 + 362780*uk_121 + 841500*uk_122 + 314160*uk_123 + 799765*uk_124 + 1855125*uk_125 + 692580*uk_126 + 4303125*uk_127 + 1606500*uk_128 + 599760*uk_129 + 2231636*uk_13 + 592704*uk_130 + 310464*uk_131 + 684432*uk_132 + 1587600*uk_133 + 592704*uk_134 + 162624*uk_135 + 358512*uk_136 + 831600*uk_137 + 310464*uk_138 + 790356*uk_139 + 4919743*uk_14 + 1833300*uk_140 + 684432*uk_141 + 4252500*uk_142 + 1587600*uk_143 + 592704*uk_144 + 85184*uk_145 + 187792*uk_146 + 435600*uk_147 + 162624*uk_148 + 413996*uk_149 + 11411775*uk_15 + 960300*uk_150 + 358512*uk_151 + 2227500*uk_152 + 831600*uk_153 + 310464*uk_154 + 912673*uk_155 + 2117025*uk_156 + 790356*uk_157 + 4910625*uk_158 + 1833300*uk_159 + 4260396*uk_16 + 684432*uk_160 + 11390625*uk_161 + 4252500*uk_162 + 1587600*uk_163 + 592704*uk_164 + 3025*uk_17 + 4675*uk_18 + 4620*uk_19 + 55*uk_2 + 2420*uk_20 + 5335*uk_21 + 12375*uk_22 + 4620*uk_23 + 7225*uk_24 + 7140*uk_25 + 3740*uk_26 + 8245*uk_27 + 19125*uk_28 + 7140*uk_29 + 85*uk_3 + 7056*uk_30 + 3696*uk_31 + 8148*uk_32 + 18900*uk_33 + 7056*uk_34 + 1936*uk_35 + 4268*uk_36 + 9900*uk_37 + 3696*uk_38 + 9409*uk_39 + 84*uk_4 + 21825*uk_40 + 8148*uk_41 + 50625*uk_42 + 18900*uk_43 + 7056*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 218655441685*uk_47 + 216083024724*uk_48 + 113186346284*uk_49 + 44*uk_5 + 249524445217*uk_50 + 578793816225*uk_51 + 216083024724*uk_52 + 153424975*uk_53 + 237111325*uk_54 + 234321780*uk_55 + 122739980*uk_56 + 270585865*uk_57 + 627647625*uk_58 + 234321780*uk_59 + 97*uk_6 + 366444775*uk_60 + 362133660*uk_61 + 189689060*uk_62 + 418178155*uk_63 + 970000875*uk_64 + 362133660*uk_65 + 357873264*uk_66 + 187457424*uk_67 + 413258412*uk_68 + 958589100*uk_69 + 225*uk_7 + 357873264*uk_70 + 98191984*uk_71 + 216468692*uk_72 + 502118100*uk_73 + 187457424*uk_74 + 477215071*uk_75 + 1106942175*uk_76 + 413258412*uk_77 + 2567649375*uk_78 + 958589100*uk_79 + 84*uk_8 + 357873264*uk_80 + 166375*uk_81 + 257125*uk_82 + 254100*uk_83 + 133100*uk_84 + 293425*uk_85 + 680625*uk_86 + 254100*uk_87 + 397375*uk_88 + 392700*uk_89 + 2572416961*uk_9 + 205700*uk_90 + 453475*uk_91 + 1051875*uk_92 + 392700*uk_93 + 388080*uk_94 + 203280*uk_95 + 448140*uk_96 + 1039500*uk_97 + 388080*uk_98 + 106480*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 217800*uk_100 + 495000*uk_101 + 187000*uk_102 + 539055*uk_103 + 1225125*uk_104 + 462825*uk_105 + 2784375*uk_106 + 1051875*uk_107 + 397375*uk_108 + 29791*uk_109 + 1572289*uk_11 + 81685*uk_110 + 38440*uk_111 + 95139*uk_112 + 216225*uk_113 + 81685*uk_114 + 223975*uk_115 + 105400*uk_116 + 260865*uk_117 + 592875*uk_118 + 223975*uk_119 + 4311115*uk_12 + 49600*uk_120 + 122760*uk_121 + 279000*uk_122 + 105400*uk_123 + 303831*uk_124 + 690525*uk_125 + 260865*uk_126 + 1569375*uk_127 + 592875*uk_128 + 223975*uk_129 + 2028760*uk_13 + 614125*uk_130 + 289000*uk_131 + 715275*uk_132 + 1625625*uk_133 + 614125*uk_134 + 136000*uk_135 + 336600*uk_136 + 765000*uk_137 + 289000*uk_138 + 833085*uk_139 + 5021181*uk_14 + 1893375*uk_140 + 715275*uk_141 + 4303125*uk_142 + 1625625*uk_143 + 614125*uk_144 + 64000*uk_145 + 158400*uk_146 + 360000*uk_147 + 136000*uk_148 + 392040*uk_149 + 11411775*uk_15 + 891000*uk_150 + 336600*uk_151 + 2025000*uk_152 + 765000*uk_153 + 289000*uk_154 + 970299*uk_155 + 2205225*uk_156 + 833085*uk_157 + 5011875*uk_158 + 1893375*uk_159 + 4311115*uk_16 + 715275*uk_160 + 11390625*uk_161 + 4303125*uk_162 + 1625625*uk_163 + 614125*uk_164 + 3025*uk_17 + 1705*uk_18 + 4675*uk_19 + 55*uk_2 + 2200*uk_20 + 5445*uk_21 + 12375*uk_22 + 4675*uk_23 + 961*uk_24 + 2635*uk_25 + 1240*uk_26 + 3069*uk_27 + 6975*uk_28 + 2635*uk_29 + 31*uk_3 + 7225*uk_30 + 3400*uk_31 + 8415*uk_32 + 19125*uk_33 + 7225*uk_34 + 1600*uk_35 + 3960*uk_36 + 9000*uk_37 + 3400*uk_38 + 9801*uk_39 + 85*uk_4 + 22275*uk_40 + 8415*uk_41 + 50625*uk_42 + 19125*uk_43 + 7225*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 79744925791*uk_47 + 218655441685*uk_48 + 102896678440*uk_49 + 40*uk_5 + 254669279139*uk_50 + 578793816225*uk_51 + 218655441685*uk_52 + 153424975*uk_53 + 86475895*uk_54 + 237111325*uk_55 + 111581800*uk_56 + 276164955*uk_57 + 627647625*uk_58 + 237111325*uk_59 + 99*uk_6 + 48740959*uk_60 + 133644565*uk_61 + 62891560*uk_62 + 155656611*uk_63 + 353765025*uk_64 + 133644565*uk_65 + 366444775*uk_66 + 172444600*uk_67 + 426800385*uk_68 + 970000875*uk_69 + 225*uk_7 + 366444775*uk_70 + 81150400*uk_71 + 200847240*uk_72 + 456471000*uk_73 + 172444600*uk_74 + 497096919*uk_75 + 1129765725*uk_76 + 426800385*uk_77 + 2567649375*uk_78 + 970000875*uk_79 + 85*uk_8 + 366444775*uk_80 + 166375*uk_81 + 93775*uk_82 + 257125*uk_83 + 121000*uk_84 + 299475*uk_85 + 680625*uk_86 + 257125*uk_87 + 52855*uk_88 + 144925*uk_89 + 2572416961*uk_9 + 68200*uk_90 + 168795*uk_91 + 383625*uk_92 + 144925*uk_93 + 397375*uk_94 + 187000*uk_95 + 462825*uk_96 + 1051875*uk_97 + 397375*uk_98 + 88000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 222200*uk_100 + 495000*uk_101 + 68200*uk_102 + 561055*uk_103 + 1249875*uk_104 + 172205*uk_105 + 2784375*uk_106 + 383625*uk_107 + 52855*uk_108 + 4913*uk_109 + 862223*uk_11 + 8959*uk_110 + 11560*uk_111 + 29189*uk_112 + 65025*uk_113 + 8959*uk_114 + 16337*uk_115 + 21080*uk_116 + 53227*uk_117 + 118575*uk_118 + 16337*uk_119 + 1572289*uk_12 + 27200*uk_120 + 68680*uk_121 + 153000*uk_122 + 21080*uk_123 + 173417*uk_124 + 386325*uk_125 + 53227*uk_126 + 860625*uk_127 + 118575*uk_128 + 16337*uk_129 + 2028760*uk_13 + 29791*uk_130 + 38440*uk_131 + 97061*uk_132 + 216225*uk_133 + 29791*uk_134 + 49600*uk_135 + 125240*uk_136 + 279000*uk_137 + 38440*uk_138 + 316231*uk_139 + 5122619*uk_14 + 704475*uk_140 + 97061*uk_141 + 1569375*uk_142 + 216225*uk_143 + 29791*uk_144 + 64000*uk_145 + 161600*uk_146 + 360000*uk_147 + 49600*uk_148 + 408040*uk_149 + 11411775*uk_15 + 909000*uk_150 + 125240*uk_151 + 2025000*uk_152 + 279000*uk_153 + 38440*uk_154 + 1030301*uk_155 + 2295225*uk_156 + 316231*uk_157 + 5113125*uk_158 + 704475*uk_159 + 1572289*uk_16 + 97061*uk_160 + 11390625*uk_161 + 1569375*uk_162 + 216225*uk_163 + 29791*uk_164 + 3025*uk_17 + 935*uk_18 + 1705*uk_19 + 55*uk_2 + 2200*uk_20 + 5555*uk_21 + 12375*uk_22 + 1705*uk_23 + 289*uk_24 + 527*uk_25 + 680*uk_26 + 1717*uk_27 + 3825*uk_28 + 527*uk_29 + 17*uk_3 + 961*uk_30 + 1240*uk_31 + 3131*uk_32 + 6975*uk_33 + 961*uk_34 + 1600*uk_35 + 4040*uk_36 + 9000*uk_37 + 1240*uk_38 + 10201*uk_39 + 31*uk_4 + 22725*uk_40 + 3131*uk_41 + 50625*uk_42 + 6975*uk_43 + 961*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 43731088337*uk_47 + 79744925791*uk_48 + 102896678440*uk_49 + 40*uk_5 + 259814113061*uk_50 + 578793816225*uk_51 + 79744925791*uk_52 + 153424975*uk_53 + 47422265*uk_54 + 86475895*uk_55 + 111581800*uk_56 + 281744045*uk_57 + 627647625*uk_58 + 86475895*uk_59 + 101*uk_6 + 14657791*uk_60 + 26728913*uk_61 + 34488920*uk_62 + 87084523*uk_63 + 194000175*uk_64 + 26728913*uk_65 + 48740959*uk_66 + 62891560*uk_67 + 158801189*uk_68 + 353765025*uk_69 + 225*uk_7 + 48740959*uk_70 + 81150400*uk_71 + 204904760*uk_72 + 456471000*uk_73 + 62891560*uk_74 + 517384519*uk_75 + 1152589275*uk_76 + 158801189*uk_77 + 2567649375*uk_78 + 353765025*uk_79 + 31*uk_8 + 48740959*uk_80 + 166375*uk_81 + 51425*uk_82 + 93775*uk_83 + 121000*uk_84 + 305525*uk_85 + 680625*uk_86 + 93775*uk_87 + 15895*uk_88 + 28985*uk_89 + 2572416961*uk_9 + 37400*uk_90 + 94435*uk_91 + 210375*uk_92 + 28985*uk_93 + 52855*uk_94 + 68200*uk_95 + 172205*uk_96 + 383625*uk_97 + 52855*uk_98 + 88000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 226600*uk_100 + 495000*uk_101 + 37400*uk_102 + 583495*uk_103 + 1274625*uk_104 + 96305*uk_105 + 2784375*uk_106 + 210375*uk_107 + 15895*uk_108 + 79507*uk_109 + 2180917*uk_11 + 31433*uk_110 + 73960*uk_111 + 190447*uk_112 + 416025*uk_113 + 31433*uk_114 + 12427*uk_115 + 29240*uk_116 + 75293*uk_117 + 164475*uk_118 + 12427*uk_119 + 862223*uk_12 + 68800*uk_120 + 177160*uk_121 + 387000*uk_122 + 29240*uk_123 + 456187*uk_124 + 996525*uk_125 + 75293*uk_126 + 2176875*uk_127 + 164475*uk_128 + 12427*uk_129 + 2028760*uk_13 + 4913*uk_130 + 11560*uk_131 + 29767*uk_132 + 65025*uk_133 + 4913*uk_134 + 27200*uk_135 + 70040*uk_136 + 153000*uk_137 + 11560*uk_138 + 180353*uk_139 + 5224057*uk_14 + 393975*uk_140 + 29767*uk_141 + 860625*uk_142 + 65025*uk_143 + 4913*uk_144 + 64000*uk_145 + 164800*uk_146 + 360000*uk_147 + 27200*uk_148 + 424360*uk_149 + 11411775*uk_15 + 927000*uk_150 + 70040*uk_151 + 2025000*uk_152 + 153000*uk_153 + 11560*uk_154 + 1092727*uk_155 + 2387025*uk_156 + 180353*uk_157 + 5214375*uk_158 + 393975*uk_159 + 862223*uk_16 + 29767*uk_160 + 11390625*uk_161 + 860625*uk_162 + 65025*uk_163 + 4913*uk_164 + 3025*uk_17 + 2365*uk_18 + 935*uk_19 + 55*uk_2 + 2200*uk_20 + 5665*uk_21 + 12375*uk_22 + 935*uk_23 + 1849*uk_24 + 731*uk_25 + 1720*uk_26 + 4429*uk_27 + 9675*uk_28 + 731*uk_29 + 43*uk_3 + 289*uk_30 + 680*uk_31 + 1751*uk_32 + 3825*uk_33 + 289*uk_34 + 1600*uk_35 + 4120*uk_36 + 9000*uk_37 + 680*uk_38 + 10609*uk_39 + 17*uk_4 + 23175*uk_40 + 1751*uk_41 + 50625*uk_42 + 3825*uk_43 + 289*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 110613929323*uk_47 + 43731088337*uk_48 + 102896678440*uk_49 + 40*uk_5 + 264958946983*uk_50 + 578793816225*uk_51 + 43731088337*uk_52 + 153424975*uk_53 + 119950435*uk_54 + 47422265*uk_55 + 111581800*uk_56 + 287323135*uk_57 + 627647625*uk_58 + 47422265*uk_59 + 103*uk_6 + 93779431*uk_60 + 37075589*uk_61 + 87236680*uk_62 + 224634451*uk_63 + 490706325*uk_64 + 37075589*uk_65 + 14657791*uk_66 + 34488920*uk_67 + 88808969*uk_68 + 194000175*uk_69 + 225*uk_7 + 14657791*uk_70 + 81150400*uk_71 + 208962280*uk_72 + 456471000*uk_73 + 34488920*uk_74 + 538077871*uk_75 + 1175412825*uk_76 + 88808969*uk_77 + 2567649375*uk_78 + 194000175*uk_79 + 17*uk_8 + 14657791*uk_80 + 166375*uk_81 + 130075*uk_82 + 51425*uk_83 + 121000*uk_84 + 311575*uk_85 + 680625*uk_86 + 51425*uk_87 + 101695*uk_88 + 40205*uk_89 + 2572416961*uk_9 + 94600*uk_90 + 243595*uk_91 + 532125*uk_92 + 40205*uk_93 + 15895*uk_94 + 37400*uk_95 + 96305*uk_96 + 210375*uk_97 + 15895*uk_98 + 88000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 207900*uk_100 + 445500*uk_101 + 85140*uk_102 + 606375*uk_103 + 1299375*uk_104 + 248325*uk_105 + 2784375*uk_106 + 532125*uk_107 + 101695*uk_108 + 64*uk_109 + 202876*uk_11 + 688*uk_110 + 576*uk_111 + 1680*uk_112 + 3600*uk_113 + 688*uk_114 + 7396*uk_115 + 6192*uk_116 + 18060*uk_117 + 38700*uk_118 + 7396*uk_119 + 2180917*uk_12 + 5184*uk_120 + 15120*uk_121 + 32400*uk_122 + 6192*uk_123 + 44100*uk_124 + 94500*uk_125 + 18060*uk_126 + 202500*uk_127 + 38700*uk_128 + 7396*uk_129 + 1825884*uk_13 + 79507*uk_130 + 66564*uk_131 + 194145*uk_132 + 416025*uk_133 + 79507*uk_134 + 55728*uk_135 + 162540*uk_136 + 348300*uk_137 + 66564*uk_138 + 474075*uk_139 + 5325495*uk_14 + 1015875*uk_140 + 194145*uk_141 + 2176875*uk_142 + 416025*uk_143 + 79507*uk_144 + 46656*uk_145 + 136080*uk_146 + 291600*uk_147 + 55728*uk_148 + 396900*uk_149 + 11411775*uk_15 + 850500*uk_150 + 162540*uk_151 + 1822500*uk_152 + 348300*uk_153 + 66564*uk_154 + 1157625*uk_155 + 2480625*uk_156 + 474075*uk_157 + 5315625*uk_158 + 1015875*uk_159 + 2180917*uk_16 + 194145*uk_160 + 11390625*uk_161 + 2176875*uk_162 + 416025*uk_163 + 79507*uk_164 + 3025*uk_17 + 220*uk_18 + 2365*uk_19 + 55*uk_2 + 1980*uk_20 + 5775*uk_21 + 12375*uk_22 + 2365*uk_23 + 16*uk_24 + 172*uk_25 + 144*uk_26 + 420*uk_27 + 900*uk_28 + 172*uk_29 + 4*uk_3 + 1849*uk_30 + 1548*uk_31 + 4515*uk_32 + 9675*uk_33 + 1849*uk_34 + 1296*uk_35 + 3780*uk_36 + 8100*uk_37 + 1548*uk_38 + 11025*uk_39 + 43*uk_4 + 23625*uk_40 + 4515*uk_41 + 50625*uk_42 + 9675*uk_43 + 1849*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 10289667844*uk_47 + 110613929323*uk_48 + 92607010596*uk_49 + 36*uk_5 + 270103780905*uk_50 + 578793816225*uk_51 + 110613929323*uk_52 + 153424975*uk_53 + 11158180*uk_54 + 119950435*uk_55 + 100423620*uk_56 + 292902225*uk_57 + 627647625*uk_58 + 119950435*uk_59 + 105*uk_6 + 811504*uk_60 + 8723668*uk_61 + 7303536*uk_62 + 21301980*uk_63 + 45647100*uk_64 + 8723668*uk_65 + 93779431*uk_66 + 78513012*uk_67 + 228996285*uk_68 + 490706325*uk_69 + 225*uk_7 + 93779431*uk_70 + 65731824*uk_71 + 191717820*uk_72 + 410823900*uk_73 + 78513012*uk_74 + 559176975*uk_75 + 1198236375*uk_76 + 228996285*uk_77 + 2567649375*uk_78 + 490706325*uk_79 + 43*uk_8 + 93779431*uk_80 + 166375*uk_81 + 12100*uk_82 + 130075*uk_83 + 108900*uk_84 + 317625*uk_85 + 680625*uk_86 + 130075*uk_87 + 880*uk_88 + 9460*uk_89 + 2572416961*uk_9 + 7920*uk_90 + 23100*uk_91 + 49500*uk_92 + 9460*uk_93 + 101695*uk_94 + 85140*uk_95 + 248325*uk_96 + 532125*uk_97 + 101695*uk_98 + 71280*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 211860*uk_100 + 445500*uk_101 + 7920*uk_102 + 629695*uk_103 + 1324125*uk_104 + 23540*uk_105 + 2784375*uk_106 + 49500*uk_107 + 880*uk_108 + uk_109 + 50719*uk_11 + 4*uk_110 + 36*uk_111 + 107*uk_112 + 225*uk_113 + 4*uk_114 + 16*uk_115 + 144*uk_116 + 428*uk_117 + 900*uk_118 + 16*uk_119 + 202876*uk_12 + 1296*uk_120 + 3852*uk_121 + 8100*uk_122 + 144*uk_123 + 11449*uk_124 + 24075*uk_125 + 428*uk_126 + 50625*uk_127 + 900*uk_128 + 16*uk_129 + 1825884*uk_13 + 64*uk_130 + 576*uk_131 + 1712*uk_132 + 3600*uk_133 + 64*uk_134 + 5184*uk_135 + 15408*uk_136 + 32400*uk_137 + 576*uk_138 + 45796*uk_139 + 5426933*uk_14 + 96300*uk_140 + 1712*uk_141 + 202500*uk_142 + 3600*uk_143 + 64*uk_144 + 46656*uk_145 + 138672*uk_146 + 291600*uk_147 + 5184*uk_148 + 412164*uk_149 + 11411775*uk_15 + 866700*uk_150 + 15408*uk_151 + 1822500*uk_152 + 32400*uk_153 + 576*uk_154 + 1225043*uk_155 + 2576025*uk_156 + 45796*uk_157 + 5416875*uk_158 + 96300*uk_159 + 202876*uk_16 + 1712*uk_160 + 11390625*uk_161 + 202500*uk_162 + 3600*uk_163 + 64*uk_164 + 3025*uk_17 + 55*uk_18 + 220*uk_19 + 55*uk_2 + 1980*uk_20 + 5885*uk_21 + 12375*uk_22 + 220*uk_23 + uk_24 + 4*uk_25 + 36*uk_26 + 107*uk_27 + 225*uk_28 + 4*uk_29 + uk_3 + 16*uk_30 + 144*uk_31 + 428*uk_32 + 900*uk_33 + 16*uk_34 + 1296*uk_35 + 3852*uk_36 + 8100*uk_37 + 144*uk_38 + 11449*uk_39 + 4*uk_4 + 24075*uk_40 + 428*uk_41 + 50625*uk_42 + 900*uk_43 + 16*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 2572416961*uk_47 + 10289667844*uk_48 + 92607010596*uk_49 + 36*uk_5 + 275248614827*uk_50 + 578793816225*uk_51 + 10289667844*uk_52 + 153424975*uk_53 + 2789545*uk_54 + 11158180*uk_55 + 100423620*uk_56 + 298481315*uk_57 + 627647625*uk_58 + 11158180*uk_59 + 107*uk_6 + 50719*uk_60 + 202876*uk_61 + 1825884*uk_62 + 5426933*uk_63 + 11411775*uk_64 + 202876*uk_65 + 811504*uk_66 + 7303536*uk_67 + 21707732*uk_68 + 45647100*uk_69 + 225*uk_7 + 811504*uk_70 + 65731824*uk_71 + 195369588*uk_72 + 410823900*uk_73 + 7303536*uk_74 + 580681831*uk_75 + 1221059925*uk_76 + 21707732*uk_77 + 2567649375*uk_78 + 45647100*uk_79 + 4*uk_8 + 811504*uk_80 + 166375*uk_81 + 3025*uk_82 + 12100*uk_83 + 108900*uk_84 + 323675*uk_85 + 680625*uk_86 + 12100*uk_87 + 55*uk_88 + 220*uk_89 + 2572416961*uk_9 + 1980*uk_90 + 5885*uk_91 + 12375*uk_92 + 220*uk_93 + 880*uk_94 + 7920*uk_95 + 23540*uk_96 + 49500*uk_97 + 880*uk_98 + 71280*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 215820*uk_100 + 445500*uk_101 + 1980*uk_102 + 653455*uk_103 + 1348875*uk_104 + 5995*uk_105 + 2784375*uk_106 + 12375*uk_107 + 55*uk_108 + 39304*uk_109 + 1724446*uk_11 + 1156*uk_110 + 41616*uk_111 + 126004*uk_112 + 260100*uk_113 + 1156*uk_114 + 34*uk_115 + 1224*uk_116 + 3706*uk_117 + 7650*uk_118 + 34*uk_119 + 50719*uk_12 + 44064*uk_120 + 133416*uk_121 + 275400*uk_122 + 1224*uk_123 + 403954*uk_124 + 833850*uk_125 + 3706*uk_126 + 1721250*uk_127 + 7650*uk_128 + 34*uk_129 + 1825884*uk_13 + uk_130 + 36*uk_131 + 109*uk_132 + 225*uk_133 + uk_134 + 1296*uk_135 + 3924*uk_136 + 8100*uk_137 + 36*uk_138 + 11881*uk_139 + 5528371*uk_14 + 24525*uk_140 + 109*uk_141 + 50625*uk_142 + 225*uk_143 + uk_144 + 46656*uk_145 + 141264*uk_146 + 291600*uk_147 + 1296*uk_148 + 427716*uk_149 + 11411775*uk_15 + 882900*uk_150 + 3924*uk_151 + 1822500*uk_152 + 8100*uk_153 + 36*uk_154 + 1295029*uk_155 + 2673225*uk_156 + 11881*uk_157 + 5518125*uk_158 + 24525*uk_159 + 50719*uk_16 + 109*uk_160 + 11390625*uk_161 + 50625*uk_162 + 225*uk_163 + uk_164 + 3025*uk_17 + 1870*uk_18 + 55*uk_19 + 55*uk_2 + 1980*uk_20 + 5995*uk_21 + 12375*uk_22 + 55*uk_23 + 1156*uk_24 + 34*uk_25 + 1224*uk_26 + 3706*uk_27 + 7650*uk_28 + 34*uk_29 + 34*uk_3 + uk_30 + 36*uk_31 + 109*uk_32 + 225*uk_33 + uk_34 + 1296*uk_35 + 3924*uk_36 + 8100*uk_37 + 36*uk_38 + 11881*uk_39 + uk_4 + 24525*uk_40 + 109*uk_41 + 50625*uk_42 + 225*uk_43 + uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 87462176674*uk_47 + 2572416961*uk_48 + 92607010596*uk_49 + 36*uk_5 + 280393448749*uk_50 + 578793816225*uk_51 + 2572416961*uk_52 + 153424975*uk_53 + 94844530*uk_54 + 2789545*uk_55 + 100423620*uk_56 + 304060405*uk_57 + 627647625*uk_58 + 2789545*uk_59 + 109*uk_6 + 58631164*uk_60 + 1724446*uk_61 + 62080056*uk_62 + 187964614*uk_63 + 388000350*uk_64 + 1724446*uk_65 + 50719*uk_66 + 1825884*uk_67 + 5528371*uk_68 + 11411775*uk_69 + 225*uk_7 + 50719*uk_70 + 65731824*uk_71 + 199021356*uk_72 + 410823900*uk_73 + 1825884*uk_74 + 602592439*uk_75 + 1243883475*uk_76 + 5528371*uk_77 + 2567649375*uk_78 + 11411775*uk_79 + uk_8 + 50719*uk_80 + 166375*uk_81 + 102850*uk_82 + 3025*uk_83 + 108900*uk_84 + 329725*uk_85 + 680625*uk_86 + 3025*uk_87 + 63580*uk_88 + 1870*uk_89 + 2572416961*uk_9 + 67320*uk_90 + 203830*uk_91 + 420750*uk_92 + 1870*uk_93 + 55*uk_94 + 1980*uk_95 + 5995*uk_96 + 12375*uk_97 + 55*uk_98 + 71280*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 219780*uk_100 + 445500*uk_101 + 67320*uk_102 + 677655*uk_103 + 1373625*uk_104 + 207570*uk_105 + 2784375*uk_106 + 420750*uk_107 + 63580*uk_108 + 1092727*uk_109 + 5224057*uk_11 + 360706*uk_110 + 381924*uk_111 + 1177599*uk_112 + 2387025*uk_113 + 360706*uk_114 + 119068*uk_115 + 126072*uk_116 + 388722*uk_117 + 787950*uk_118 + 119068*uk_119 + 1724446*uk_12 + 133488*uk_120 + 411588*uk_121 + 834300*uk_122 + 126072*uk_123 + 1269063*uk_124 + 2572425*uk_125 + 388722*uk_126 + 5214375*uk_127 + 787950*uk_128 + 119068*uk_129 + 1825884*uk_13 + 39304*uk_130 + 41616*uk_131 + 128316*uk_132 + 260100*uk_133 + 39304*uk_134 + 44064*uk_135 + 135864*uk_136 + 275400*uk_137 + 41616*uk_138 + 418914*uk_139 + 5629809*uk_14 + 849150*uk_140 + 128316*uk_141 + 1721250*uk_142 + 260100*uk_143 + 39304*uk_144 + 46656*uk_145 + 143856*uk_146 + 291600*uk_147 + 44064*uk_148 + 443556*uk_149 + 11411775*uk_15 + 899100*uk_150 + 135864*uk_151 + 1822500*uk_152 + 275400*uk_153 + 41616*uk_154 + 1367631*uk_155 + 2772225*uk_156 + 418914*uk_157 + 5619375*uk_158 + 849150*uk_159 + 1724446*uk_16 + 128316*uk_160 + 11390625*uk_161 + 1721250*uk_162 + 260100*uk_163 + 39304*uk_164 + 3025*uk_17 + 5665*uk_18 + 1870*uk_19 + 55*uk_2 + 1980*uk_20 + 6105*uk_21 + 12375*uk_22 + 1870*uk_23 + 10609*uk_24 + 3502*uk_25 + 3708*uk_26 + 11433*uk_27 + 23175*uk_28 + 3502*uk_29 + 103*uk_3 + 1156*uk_30 + 1224*uk_31 + 3774*uk_32 + 7650*uk_33 + 1156*uk_34 + 1296*uk_35 + 3996*uk_36 + 8100*uk_37 + 1224*uk_38 + 12321*uk_39 + 34*uk_4 + 24975*uk_40 + 3774*uk_41 + 50625*uk_42 + 7650*uk_43 + 1156*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 264958946983*uk_47 + 87462176674*uk_48 + 92607010596*uk_49 + 36*uk_5 + 285538282671*uk_50 + 578793816225*uk_51 + 87462176674*uk_52 + 153424975*uk_53 + 287323135*uk_54 + 94844530*uk_55 + 100423620*uk_56 + 309639495*uk_57 + 627647625*uk_58 + 94844530*uk_59 + 111*uk_6 + 538077871*uk_60 + 177617938*uk_61 + 188066052*uk_62 + 579870327*uk_63 + 1175412825*uk_64 + 177617938*uk_65 + 58631164*uk_66 + 62080056*uk_67 + 191413506*uk_68 + 388000350*uk_69 + 225*uk_7 + 58631164*uk_70 + 65731824*uk_71 + 202673124*uk_72 + 410823900*uk_73 + 62080056*uk_74 + 624908799*uk_75 + 1266707025*uk_76 + 191413506*uk_77 + 2567649375*uk_78 + 388000350*uk_79 + 34*uk_8 + 58631164*uk_80 + 166375*uk_81 + 311575*uk_82 + 102850*uk_83 + 108900*uk_84 + 335775*uk_85 + 680625*uk_86 + 102850*uk_87 + 583495*uk_88 + 192610*uk_89 + 2572416961*uk_9 + 203940*uk_90 + 628815*uk_91 + 1274625*uk_92 + 192610*uk_93 + 63580*uk_94 + 67320*uk_95 + 207570*uk_96 + 420750*uk_97 + 63580*uk_98 + 71280*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 198880*uk_100 + 396000*uk_101 + 181280*uk_102 + 702295*uk_103 + 1398375*uk_104 + 640145*uk_105 + 2784375*uk_106 + 1274625*uk_107 + 583495*uk_108 + 857375*uk_109 + 4818305*uk_11 + 929575*uk_110 + 288800*uk_111 + 1019825*uk_112 + 2030625*uk_113 + 929575*uk_114 + 1007855*uk_115 + 313120*uk_116 + 1105705*uk_117 + 2201625*uk_118 + 1007855*uk_119 + 5224057*uk_12 + 97280*uk_120 + 343520*uk_121 + 684000*uk_122 + 313120*uk_123 + 1213055*uk_124 + 2415375*uk_125 + 1105705*uk_126 + 4809375*uk_127 + 2201625*uk_128 + 1007855*uk_129 + 1623008*uk_13 + 1092727*uk_130 + 339488*uk_131 + 1198817*uk_132 + 2387025*uk_133 + 1092727*uk_134 + 105472*uk_135 + 372448*uk_136 + 741600*uk_137 + 339488*uk_138 + 1315207*uk_139 + 5731247*uk_14 + 2618775*uk_140 + 1198817*uk_141 + 5214375*uk_142 + 2387025*uk_143 + 1092727*uk_144 + 32768*uk_145 + 115712*uk_146 + 230400*uk_147 + 105472*uk_148 + 408608*uk_149 + 11411775*uk_15 + 813600*uk_150 + 372448*uk_151 + 1620000*uk_152 + 741600*uk_153 + 339488*uk_154 + 1442897*uk_155 + 2873025*uk_156 + 1315207*uk_157 + 5720625*uk_158 + 2618775*uk_159 + 5224057*uk_16 + 1198817*uk_160 + 11390625*uk_161 + 5214375*uk_162 + 2387025*uk_163 + 1092727*uk_164 + 3025*uk_17 + 5225*uk_18 + 5665*uk_19 + 55*uk_2 + 1760*uk_20 + 6215*uk_21 + 12375*uk_22 + 5665*uk_23 + 9025*uk_24 + 9785*uk_25 + 3040*uk_26 + 10735*uk_27 + 21375*uk_28 + 9785*uk_29 + 95*uk_3 + 10609*uk_30 + 3296*uk_31 + 11639*uk_32 + 23175*uk_33 + 10609*uk_34 + 1024*uk_35 + 3616*uk_36 + 7200*uk_37 + 3296*uk_38 + 12769*uk_39 + 103*uk_4 + 25425*uk_40 + 11639*uk_41 + 50625*uk_42 + 23175*uk_43 + 10609*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 244379611295*uk_47 + 264958946983*uk_48 + 82317342752*uk_49 + 32*uk_5 + 290683116593*uk_50 + 578793816225*uk_51 + 264958946983*uk_52 + 153424975*uk_53 + 265006775*uk_54 + 287323135*uk_55 + 89265440*uk_56 + 315218585*uk_57 + 627647625*uk_58 + 287323135*uk_59 + 113*uk_6 + 457738975*uk_60 + 496285415*uk_61 + 154185760*uk_62 + 544468465*uk_63 + 1084118625*uk_64 + 496285415*uk_65 + 538077871*uk_66 + 167169824*uk_67 + 590318441*uk_68 + 1175412825*uk_69 + 225*uk_7 + 538077871*uk_70 + 51936256*uk_71 + 183399904*uk_72 + 365176800*uk_73 + 167169824*uk_74 + 647630911*uk_75 + 1289530575*uk_76 + 590318441*uk_77 + 2567649375*uk_78 + 1175412825*uk_79 + 103*uk_8 + 538077871*uk_80 + 166375*uk_81 + 287375*uk_82 + 311575*uk_83 + 96800*uk_84 + 341825*uk_85 + 680625*uk_86 + 311575*uk_87 + 496375*uk_88 + 538175*uk_89 + 2572416961*uk_9 + 167200*uk_90 + 590425*uk_91 + 1175625*uk_92 + 538175*uk_93 + 583495*uk_94 + 181280*uk_95 + 640145*uk_96 + 1274625*uk_97 + 583495*uk_98 + 56320*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 177100*uk_100 + 346500*uk_101 + 146300*uk_102 + 727375*uk_103 + 1423125*uk_104 + 600875*uk_105 + 2784375*uk_106 + 1175625*uk_107 + 496375*uk_108 + 64*uk_109 + 202876*uk_11 + 1520*uk_110 + 448*uk_111 + 1840*uk_112 + 3600*uk_113 + 1520*uk_114 + 36100*uk_115 + 10640*uk_116 + 43700*uk_117 + 85500*uk_118 + 36100*uk_119 + 4818305*uk_12 + 3136*uk_120 + 12880*uk_121 + 25200*uk_122 + 10640*uk_123 + 52900*uk_124 + 103500*uk_125 + 43700*uk_126 + 202500*uk_127 + 85500*uk_128 + 36100*uk_129 + 1420132*uk_13 + 857375*uk_130 + 252700*uk_131 + 1037875*uk_132 + 2030625*uk_133 + 857375*uk_134 + 74480*uk_135 + 305900*uk_136 + 598500*uk_137 + 252700*uk_138 + 1256375*uk_139 + 5832685*uk_14 + 2458125*uk_140 + 1037875*uk_141 + 4809375*uk_142 + 2030625*uk_143 + 857375*uk_144 + 21952*uk_145 + 90160*uk_146 + 176400*uk_147 + 74480*uk_148 + 370300*uk_149 + 11411775*uk_15 + 724500*uk_150 + 305900*uk_151 + 1417500*uk_152 + 598500*uk_153 + 252700*uk_154 + 1520875*uk_155 + 2975625*uk_156 + 1256375*uk_157 + 5821875*uk_158 + 2458125*uk_159 + 4818305*uk_16 + 1037875*uk_160 + 11390625*uk_161 + 4809375*uk_162 + 2030625*uk_163 + 857375*uk_164 + 3025*uk_17 + 220*uk_18 + 5225*uk_19 + 55*uk_2 + 1540*uk_20 + 6325*uk_21 + 12375*uk_22 + 5225*uk_23 + 16*uk_24 + 380*uk_25 + 112*uk_26 + 460*uk_27 + 900*uk_28 + 380*uk_29 + 4*uk_3 + 9025*uk_30 + 2660*uk_31 + 10925*uk_32 + 21375*uk_33 + 9025*uk_34 + 784*uk_35 + 3220*uk_36 + 6300*uk_37 + 2660*uk_38 + 13225*uk_39 + 95*uk_4 + 25875*uk_40 + 10925*uk_41 + 50625*uk_42 + 21375*uk_43 + 9025*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 10289667844*uk_47 + 244379611295*uk_48 + 72027674908*uk_49 + 28*uk_5 + 295827950515*uk_50 + 578793816225*uk_51 + 244379611295*uk_52 + 153424975*uk_53 + 11158180*uk_54 + 265006775*uk_55 + 78107260*uk_56 + 320797675*uk_57 + 627647625*uk_58 + 265006775*uk_59 + 115*uk_6 + 811504*uk_60 + 19273220*uk_61 + 5680528*uk_62 + 23330740*uk_63 + 45647100*uk_64 + 19273220*uk_65 + 457738975*uk_66 + 134912540*uk_67 + 554105075*uk_68 + 1084118625*uk_69 + 225*uk_7 + 457738975*uk_70 + 39763696*uk_71 + 163315180*uk_72 + 319529700*uk_73 + 134912540*uk_74 + 670758775*uk_75 + 1312354125*uk_76 + 554105075*uk_77 + 2567649375*uk_78 + 1084118625*uk_79 + 95*uk_8 + 457738975*uk_80 + 166375*uk_81 + 12100*uk_82 + 287375*uk_83 + 84700*uk_84 + 347875*uk_85 + 680625*uk_86 + 287375*uk_87 + 880*uk_88 + 20900*uk_89 + 2572416961*uk_9 + 6160*uk_90 + 25300*uk_91 + 49500*uk_92 + 20900*uk_93 + 496375*uk_94 + 146300*uk_95 + 600875*uk_96 + 1175625*uk_97 + 496375*uk_98 + 43120*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 205920*uk_100 + 396000*uk_101 + 7040*uk_102 + 752895*uk_103 + 1447875*uk_104 + 25740*uk_105 + 2784375*uk_106 + 49500*uk_107 + 880*uk_108 + 195112*uk_109 + 2941702*uk_11 + 13456*uk_110 + 107648*uk_111 + 393588*uk_112 + 756900*uk_113 + 13456*uk_114 + 928*uk_115 + 7424*uk_116 + 27144*uk_117 + 52200*uk_118 + 928*uk_119 + 202876*uk_12 + 59392*uk_120 + 217152*uk_121 + 417600*uk_122 + 7424*uk_123 + 793962*uk_124 + 1526850*uk_125 + 27144*uk_126 + 2936250*uk_127 + 52200*uk_128 + 928*uk_129 + 1623008*uk_13 + 64*uk_130 + 512*uk_131 + 1872*uk_132 + 3600*uk_133 + 64*uk_134 + 4096*uk_135 + 14976*uk_136 + 28800*uk_137 + 512*uk_138 + 54756*uk_139 + 5934123*uk_14 + 105300*uk_140 + 1872*uk_141 + 202500*uk_142 + 3600*uk_143 + 64*uk_144 + 32768*uk_145 + 119808*uk_146 + 230400*uk_147 + 4096*uk_148 + 438048*uk_149 + 11411775*uk_15 + 842400*uk_150 + 14976*uk_151 + 1620000*uk_152 + 28800*uk_153 + 512*uk_154 + 1601613*uk_155 + 3080025*uk_156 + 54756*uk_157 + 5923125*uk_158 + 105300*uk_159 + 202876*uk_16 + 1872*uk_160 + 11390625*uk_161 + 202500*uk_162 + 3600*uk_163 + 64*uk_164 + 3025*uk_17 + 3190*uk_18 + 220*uk_19 + 55*uk_2 + 1760*uk_20 + 6435*uk_21 + 12375*uk_22 + 220*uk_23 + 3364*uk_24 + 232*uk_25 + 1856*uk_26 + 6786*uk_27 + 13050*uk_28 + 232*uk_29 + 58*uk_3 + 16*uk_30 + 128*uk_31 + 468*uk_32 + 900*uk_33 + 16*uk_34 + 1024*uk_35 + 3744*uk_36 + 7200*uk_37 + 128*uk_38 + 13689*uk_39 + 4*uk_4 + 26325*uk_40 + 468*uk_41 + 50625*uk_42 + 900*uk_43 + 16*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 149200183738*uk_47 + 10289667844*uk_48 + 82317342752*uk_49 + 32*uk_5 + 300972784437*uk_50 + 578793816225*uk_51 + 10289667844*uk_52 + 153424975*uk_53 + 161793610*uk_54 + 11158180*uk_55 + 89265440*uk_56 + 326376765*uk_57 + 627647625*uk_58 + 11158180*uk_59 + 117*uk_6 + 170618716*uk_60 + 11766808*uk_61 + 94134464*uk_62 + 344179134*uk_63 + 661882950*uk_64 + 11766808*uk_65 + 811504*uk_66 + 6492032*uk_67 + 23736492*uk_68 + 45647100*uk_69 + 225*uk_7 + 811504*uk_70 + 51936256*uk_71 + 189891936*uk_72 + 365176800*uk_73 + 6492032*uk_74 + 694292391*uk_75 + 1335177675*uk_76 + 23736492*uk_77 + 2567649375*uk_78 + 45647100*uk_79 + 4*uk_8 + 811504*uk_80 + 166375*uk_81 + 175450*uk_82 + 12100*uk_83 + 96800*uk_84 + 353925*uk_85 + 680625*uk_86 + 12100*uk_87 + 185020*uk_88 + 12760*uk_89 + 2572416961*uk_9 + 102080*uk_90 + 373230*uk_91 + 717750*uk_92 + 12760*uk_93 + 880*uk_94 + 7040*uk_95 + 25740*uk_96 + 49500*uk_97 + 880*uk_98 + 56320*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 183260*uk_100 + 346500*uk_101 + 89320*uk_102 + 778855*uk_103 + 1472625*uk_104 + 379610*uk_105 + 2784375*uk_106 + 717750*uk_107 + 185020*uk_108 + 15625*uk_109 + 1267975*uk_11 + 36250*uk_110 + 17500*uk_111 + 74375*uk_112 + 140625*uk_113 + 36250*uk_114 + 84100*uk_115 + 40600*uk_116 + 172550*uk_117 + 326250*uk_118 + 84100*uk_119 + 2941702*uk_12 + 19600*uk_120 + 83300*uk_121 + 157500*uk_122 + 40600*uk_123 + 354025*uk_124 + 669375*uk_125 + 172550*uk_126 + 1265625*uk_127 + 326250*uk_128 + 84100*uk_129 + 1420132*uk_13 + 195112*uk_130 + 94192*uk_131 + 400316*uk_132 + 756900*uk_133 + 195112*uk_134 + 45472*uk_135 + 193256*uk_136 + 365400*uk_137 + 94192*uk_138 + 821338*uk_139 + 6035561*uk_14 + 1552950*uk_140 + 400316*uk_141 + 2936250*uk_142 + 756900*uk_143 + 195112*uk_144 + 21952*uk_145 + 93296*uk_146 + 176400*uk_147 + 45472*uk_148 + 396508*uk_149 + 11411775*uk_15 + 749700*uk_150 + 193256*uk_151 + 1417500*uk_152 + 365400*uk_153 + 94192*uk_154 + 1685159*uk_155 + 3186225*uk_156 + 821338*uk_157 + 6024375*uk_158 + 1552950*uk_159 + 2941702*uk_16 + 400316*uk_160 + 11390625*uk_161 + 2936250*uk_162 + 756900*uk_163 + 195112*uk_164 + 3025*uk_17 + 1375*uk_18 + 3190*uk_19 + 55*uk_2 + 1540*uk_20 + 6545*uk_21 + 12375*uk_22 + 3190*uk_23 + 625*uk_24 + 1450*uk_25 + 700*uk_26 + 2975*uk_27 + 5625*uk_28 + 1450*uk_29 + 25*uk_3 + 3364*uk_30 + 1624*uk_31 + 6902*uk_32 + 13050*uk_33 + 3364*uk_34 + 784*uk_35 + 3332*uk_36 + 6300*uk_37 + 1624*uk_38 + 14161*uk_39 + 58*uk_4 + 26775*uk_40 + 6902*uk_41 + 50625*uk_42 + 13050*uk_43 + 3364*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 64310424025*uk_47 + 149200183738*uk_48 + 72027674908*uk_49 + 28*uk_5 + 306117618359*uk_50 + 578793816225*uk_51 + 149200183738*uk_52 + 153424975*uk_53 + 69738625*uk_54 + 161793610*uk_55 + 78107260*uk_56 + 331955855*uk_57 + 627647625*uk_58 + 161793610*uk_59 + 119*uk_6 + 31699375*uk_60 + 73542550*uk_61 + 35503300*uk_62 + 150889025*uk_63 + 285294375*uk_64 + 73542550*uk_65 + 170618716*uk_66 + 82367656*uk_67 + 350062538*uk_68 + 661882950*uk_69 + 225*uk_7 + 170618716*uk_70 + 39763696*uk_71 + 168995708*uk_72 + 319529700*uk_73 + 82367656*uk_74 + 718231759*uk_75 + 1358001225*uk_76 + 350062538*uk_77 + 2567649375*uk_78 + 661882950*uk_79 + 58*uk_8 + 170618716*uk_80 + 166375*uk_81 + 75625*uk_82 + 175450*uk_83 + 84700*uk_84 + 359975*uk_85 + 680625*uk_86 + 175450*uk_87 + 34375*uk_88 + 79750*uk_89 + 2572416961*uk_9 + 38500*uk_90 + 163625*uk_91 + 309375*uk_92 + 79750*uk_93 + 185020*uk_94 + 89320*uk_95 + 379610*uk_96 + 717750*uk_97 + 185020*uk_98 + 43120*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 186340*uk_100 + 346500*uk_101 + 38500*uk_102 + 805255*uk_103 + 1497375*uk_104 + 166375*uk_105 + 2784375*uk_106 + 309375*uk_107 + 34375*uk_108 + 8000*uk_109 + 1014380*uk_11 + 10000*uk_110 + 11200*uk_111 + 48400*uk_112 + 90000*uk_113 + 10000*uk_114 + 12500*uk_115 + 14000*uk_116 + 60500*uk_117 + 112500*uk_118 + 12500*uk_119 + 1267975*uk_12 + 15680*uk_120 + 67760*uk_121 + 126000*uk_122 + 14000*uk_123 + 292820*uk_124 + 544500*uk_125 + 60500*uk_126 + 1012500*uk_127 + 112500*uk_128 + 12500*uk_129 + 1420132*uk_13 + 15625*uk_130 + 17500*uk_131 + 75625*uk_132 + 140625*uk_133 + 15625*uk_134 + 19600*uk_135 + 84700*uk_136 + 157500*uk_137 + 17500*uk_138 + 366025*uk_139 + 6136999*uk_14 + 680625*uk_140 + 75625*uk_141 + 1265625*uk_142 + 140625*uk_143 + 15625*uk_144 + 21952*uk_145 + 94864*uk_146 + 176400*uk_147 + 19600*uk_148 + 409948*uk_149 + 11411775*uk_15 + 762300*uk_150 + 84700*uk_151 + 1417500*uk_152 + 157500*uk_153 + 17500*uk_154 + 1771561*uk_155 + 3294225*uk_156 + 366025*uk_157 + 6125625*uk_158 + 680625*uk_159 + 1267975*uk_16 + 75625*uk_160 + 11390625*uk_161 + 1265625*uk_162 + 140625*uk_163 + 15625*uk_164 + 3025*uk_17 + 1100*uk_18 + 1375*uk_19 + 55*uk_2 + 1540*uk_20 + 6655*uk_21 + 12375*uk_22 + 1375*uk_23 + 400*uk_24 + 500*uk_25 + 560*uk_26 + 2420*uk_27 + 4500*uk_28 + 500*uk_29 + 20*uk_3 + 625*uk_30 + 700*uk_31 + 3025*uk_32 + 5625*uk_33 + 625*uk_34 + 784*uk_35 + 3388*uk_36 + 6300*uk_37 + 700*uk_38 + 14641*uk_39 + 25*uk_4 + 27225*uk_40 + 3025*uk_41 + 50625*uk_42 + 5625*uk_43 + 625*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 51448339220*uk_47 + 64310424025*uk_48 + 72027674908*uk_49 + 28*uk_5 + 311262452281*uk_50 + 578793816225*uk_51 + 64310424025*uk_52 + 153424975*uk_53 + 55790900*uk_54 + 69738625*uk_55 + 78107260*uk_56 + 337534945*uk_57 + 627647625*uk_58 + 69738625*uk_59 + 121*uk_6 + 20287600*uk_60 + 25359500*uk_61 + 28402640*uk_62 + 122739980*uk_63 + 228235500*uk_64 + 25359500*uk_65 + 31699375*uk_66 + 35503300*uk_67 + 153424975*uk_68 + 285294375*uk_69 + 225*uk_7 + 31699375*uk_70 + 39763696*uk_71 + 171835972*uk_72 + 319529700*uk_73 + 35503300*uk_74 + 742576879*uk_75 + 1380824775*uk_76 + 153424975*uk_77 + 2567649375*uk_78 + 285294375*uk_79 + 25*uk_8 + 31699375*uk_80 + 166375*uk_81 + 60500*uk_82 + 75625*uk_83 + 84700*uk_84 + 366025*uk_85 + 680625*uk_86 + 75625*uk_87 + 22000*uk_88 + 27500*uk_89 + 2572416961*uk_9 + 30800*uk_90 + 133100*uk_91 + 247500*uk_92 + 27500*uk_93 + 34375*uk_94 + 38500*uk_95 + 166375*uk_96 + 309375*uk_97 + 34375*uk_98 + 43120*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 189420*uk_100 + 346500*uk_101 + 30800*uk_102 + 832095*uk_103 + 1522125*uk_104 + 135300*uk_105 + 2784375*uk_106 + 247500*uk_107 + 22000*uk_108 + 79507*uk_109 + 2180917*uk_11 + 36980*uk_110 + 51772*uk_111 + 227427*uk_112 + 416025*uk_113 + 36980*uk_114 + 17200*uk_115 + 24080*uk_116 + 105780*uk_117 + 193500*uk_118 + 17200*uk_119 + 1014380*uk_12 + 33712*uk_120 + 148092*uk_121 + 270900*uk_122 + 24080*uk_123 + 650547*uk_124 + 1190025*uk_125 + 105780*uk_126 + 2176875*uk_127 + 193500*uk_128 + 17200*uk_129 + 1420132*uk_13 + 8000*uk_130 + 11200*uk_131 + 49200*uk_132 + 90000*uk_133 + 8000*uk_134 + 15680*uk_135 + 68880*uk_136 + 126000*uk_137 + 11200*uk_138 + 302580*uk_139 + 6238437*uk_14 + 553500*uk_140 + 49200*uk_141 + 1012500*uk_142 + 90000*uk_143 + 8000*uk_144 + 21952*uk_145 + 96432*uk_146 + 176400*uk_147 + 15680*uk_148 + 423612*uk_149 + 11411775*uk_15 + 774900*uk_150 + 68880*uk_151 + 1417500*uk_152 + 126000*uk_153 + 11200*uk_154 + 1860867*uk_155 + 3404025*uk_156 + 302580*uk_157 + 6226875*uk_158 + 553500*uk_159 + 1014380*uk_16 + 49200*uk_160 + 11390625*uk_161 + 1012500*uk_162 + 90000*uk_163 + 8000*uk_164 + 3025*uk_17 + 2365*uk_18 + 1100*uk_19 + 55*uk_2 + 1540*uk_20 + 6765*uk_21 + 12375*uk_22 + 1100*uk_23 + 1849*uk_24 + 860*uk_25 + 1204*uk_26 + 5289*uk_27 + 9675*uk_28 + 860*uk_29 + 43*uk_3 + 400*uk_30 + 560*uk_31 + 2460*uk_32 + 4500*uk_33 + 400*uk_34 + 784*uk_35 + 3444*uk_36 + 6300*uk_37 + 560*uk_38 + 15129*uk_39 + 20*uk_4 + 27675*uk_40 + 2460*uk_41 + 50625*uk_42 + 4500*uk_43 + 400*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 110613929323*uk_47 + 51448339220*uk_48 + 72027674908*uk_49 + 28*uk_5 + 316407286203*uk_50 + 578793816225*uk_51 + 51448339220*uk_52 + 153424975*uk_53 + 119950435*uk_54 + 55790900*uk_55 + 78107260*uk_56 + 343114035*uk_57 + 627647625*uk_58 + 55790900*uk_59 + 123*uk_6 + 93779431*uk_60 + 43618340*uk_61 + 61065676*uk_62 + 268252791*uk_63 + 490706325*uk_64 + 43618340*uk_65 + 20287600*uk_66 + 28402640*uk_67 + 124768740*uk_68 + 228235500*uk_69 + 225*uk_7 + 20287600*uk_70 + 39763696*uk_71 + 174676236*uk_72 + 319529700*uk_73 + 28402640*uk_74 + 767327751*uk_75 + 1403648325*uk_76 + 124768740*uk_77 + 2567649375*uk_78 + 228235500*uk_79 + 20*uk_8 + 20287600*uk_80 + 166375*uk_81 + 130075*uk_82 + 60500*uk_83 + 84700*uk_84 + 372075*uk_85 + 680625*uk_86 + 60500*uk_87 + 101695*uk_88 + 47300*uk_89 + 2572416961*uk_9 + 66220*uk_90 + 290895*uk_91 + 532125*uk_92 + 47300*uk_93 + 22000*uk_94 + 30800*uk_95 + 135300*uk_96 + 247500*uk_97 + 22000*uk_98 + 43120*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 192500*uk_100 + 346500*uk_101 + 66220*uk_102 + 859375*uk_103 + 1546875*uk_104 + 295625*uk_105 + 2784375*uk_106 + 532125*uk_107 + 101695*uk_108 + 830584*uk_109 + 4767586*uk_11 + 379948*uk_110 + 247408*uk_111 + 1104500*uk_112 + 1988100*uk_113 + 379948*uk_114 + 173806*uk_115 + 113176*uk_116 + 505250*uk_117 + 909450*uk_118 + 173806*uk_119 + 2180917*uk_12 + 73696*uk_120 + 329000*uk_121 + 592200*uk_122 + 113176*uk_123 + 1468750*uk_124 + 2643750*uk_125 + 505250*uk_126 + 4758750*uk_127 + 909450*uk_128 + 173806*uk_129 + 1420132*uk_13 + 79507*uk_130 + 51772*uk_131 + 231125*uk_132 + 416025*uk_133 + 79507*uk_134 + 33712*uk_135 + 150500*uk_136 + 270900*uk_137 + 51772*uk_138 + 671875*uk_139 + 6339875*uk_14 + 1209375*uk_140 + 231125*uk_141 + 2176875*uk_142 + 416025*uk_143 + 79507*uk_144 + 21952*uk_145 + 98000*uk_146 + 176400*uk_147 + 33712*uk_148 + 437500*uk_149 + 11411775*uk_15 + 787500*uk_150 + 150500*uk_151 + 1417500*uk_152 + 270900*uk_153 + 51772*uk_154 + 1953125*uk_155 + 3515625*uk_156 + 671875*uk_157 + 6328125*uk_158 + 1209375*uk_159 + 2180917*uk_16 + 231125*uk_160 + 11390625*uk_161 + 2176875*uk_162 + 416025*uk_163 + 79507*uk_164 + 3025*uk_17 + 5170*uk_18 + 2365*uk_19 + 55*uk_2 + 1540*uk_20 + 6875*uk_21 + 12375*uk_22 + 2365*uk_23 + 8836*uk_24 + 4042*uk_25 + 2632*uk_26 + 11750*uk_27 + 21150*uk_28 + 4042*uk_29 + 94*uk_3 + 1849*uk_30 + 1204*uk_31 + 5375*uk_32 + 9675*uk_33 + 1849*uk_34 + 784*uk_35 + 3500*uk_36 + 6300*uk_37 + 1204*uk_38 + 15625*uk_39 + 43*uk_4 + 28125*uk_40 + 5375*uk_41 + 50625*uk_42 + 9675*uk_43 + 1849*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 241807194334*uk_47 + 110613929323*uk_48 + 72027674908*uk_49 + 28*uk_5 + 321552120125*uk_50 + 578793816225*uk_51 + 110613929323*uk_52 + 153424975*uk_53 + 262217230*uk_54 + 119950435*uk_55 + 78107260*uk_56 + 348693125*uk_57 + 627647625*uk_58 + 119950435*uk_59 + 125*uk_6 + 448153084*uk_60 + 205006198*uk_61 + 133492408*uk_62 + 595948250*uk_63 + 1072706850*uk_64 + 205006198*uk_65 + 93779431*uk_66 + 61065676*uk_67 + 272614625*uk_68 + 490706325*uk_69 + 225*uk_7 + 93779431*uk_70 + 39763696*uk_71 + 177516500*uk_72 + 319529700*uk_73 + 61065676*uk_74 + 792484375*uk_75 + 1426471875*uk_76 + 272614625*uk_77 + 2567649375*uk_78 + 490706325*uk_79 + 43*uk_8 + 93779431*uk_80 + 166375*uk_81 + 284350*uk_82 + 130075*uk_83 + 84700*uk_84 + 378125*uk_85 + 680625*uk_86 + 130075*uk_87 + 485980*uk_88 + 222310*uk_89 + 2572416961*uk_9 + 144760*uk_90 + 646250*uk_91 + 1163250*uk_92 + 222310*uk_93 + 101695*uk_94 + 66220*uk_95 + 295625*uk_96 + 532125*uk_97 + 101695*uk_98 + 43120*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 167640*uk_100 + 297000*uk_101 + 124080*uk_102 + 887095*uk_103 + 1571625*uk_104 + 656590*uk_105 + 2784375*uk_106 + 1163250*uk_107 + 485980*uk_108 + 97336*uk_109 + 2333074*uk_11 + 198904*uk_110 + 50784*uk_111 + 268732*uk_112 + 476100*uk_113 + 198904*uk_114 + 406456*uk_115 + 103776*uk_116 + 549148*uk_117 + 972900*uk_118 + 406456*uk_119 + 4767586*uk_12 + 26496*uk_120 + 140208*uk_121 + 248400*uk_122 + 103776*uk_123 + 741934*uk_124 + 1314450*uk_125 + 549148*uk_126 + 2328750*uk_127 + 972900*uk_128 + 406456*uk_129 + 1217256*uk_13 + 830584*uk_130 + 212064*uk_131 + 1122172*uk_132 + 1988100*uk_133 + 830584*uk_134 + 54144*uk_135 + 286512*uk_136 + 507600*uk_137 + 212064*uk_138 + 1516126*uk_139 + 6441313*uk_14 + 2686050*uk_140 + 1122172*uk_141 + 4758750*uk_142 + 1988100*uk_143 + 830584*uk_144 + 13824*uk_145 + 73152*uk_146 + 129600*uk_147 + 54144*uk_148 + 387096*uk_149 + 11411775*uk_15 + 685800*uk_150 + 286512*uk_151 + 1215000*uk_152 + 507600*uk_153 + 212064*uk_154 + 2048383*uk_155 + 3629025*uk_156 + 1516126*uk_157 + 6429375*uk_158 + 2686050*uk_159 + 4767586*uk_16 + 1122172*uk_160 + 11390625*uk_161 + 4758750*uk_162 + 1988100*uk_163 + 830584*uk_164 + 3025*uk_17 + 2530*uk_18 + 5170*uk_19 + 55*uk_2 + 1320*uk_20 + 6985*uk_21 + 12375*uk_22 + 5170*uk_23 + 2116*uk_24 + 4324*uk_25 + 1104*uk_26 + 5842*uk_27 + 10350*uk_28 + 4324*uk_29 + 46*uk_3 + 8836*uk_30 + 2256*uk_31 + 11938*uk_32 + 21150*uk_33 + 8836*uk_34 + 576*uk_35 + 3048*uk_36 + 5400*uk_37 + 2256*uk_38 + 16129*uk_39 + 94*uk_4 + 28575*uk_40 + 11938*uk_41 + 50625*uk_42 + 21150*uk_43 + 8836*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 118331180206*uk_47 + 241807194334*uk_48 + 61738007064*uk_49 + 24*uk_5 + 326696954047*uk_50 + 578793816225*uk_51 + 241807194334*uk_52 + 153424975*uk_53 + 128319070*uk_54 + 262217230*uk_55 + 66949080*uk_56 + 354272215*uk_57 + 627647625*uk_58 + 262217230*uk_59 + 127*uk_6 + 107321404*uk_60 + 219308956*uk_61 + 55993776*uk_62 + 296300398*uk_63 + 524941650*uk_64 + 219308956*uk_65 + 448153084*uk_66 + 114422064*uk_67 + 605483422*uk_68 + 1072706850*uk_69 + 225*uk_7 + 448153084*uk_70 + 29214144*uk_71 + 154591512*uk_72 + 273882600*uk_73 + 114422064*uk_74 + 818046751*uk_75 + 1449295425*uk_76 + 605483422*uk_77 + 2567649375*uk_78 + 1072706850*uk_79 + 94*uk_8 + 448153084*uk_80 + 166375*uk_81 + 139150*uk_82 + 284350*uk_83 + 72600*uk_84 + 384175*uk_85 + 680625*uk_86 + 284350*uk_87 + 116380*uk_88 + 237820*uk_89 + 2572416961*uk_9 + 60720*uk_90 + 321310*uk_91 + 569250*uk_92 + 237820*uk_93 + 485980*uk_94 + 124080*uk_95 + 656590*uk_96 + 1163250*uk_97 + 485980*uk_98 + 31680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 170280*uk_100 + 297000*uk_101 + 60720*uk_102 + 915255*uk_103 + 1596375*uk_104 + 326370*uk_105 + 2784375*uk_106 + 569250*uk_107 + 116380*uk_108 + 10648*uk_109 + 1115818*uk_11 + 22264*uk_110 + 11616*uk_111 + 62436*uk_112 + 108900*uk_113 + 22264*uk_114 + 46552*uk_115 + 24288*uk_116 + 130548*uk_117 + 227700*uk_118 + 46552*uk_119 + 2333074*uk_12 + 12672*uk_120 + 68112*uk_121 + 118800*uk_122 + 24288*uk_123 + 366102*uk_124 + 638550*uk_125 + 130548*uk_126 + 1113750*uk_127 + 227700*uk_128 + 46552*uk_129 + 1217256*uk_13 + 97336*uk_130 + 50784*uk_131 + 272964*uk_132 + 476100*uk_133 + 97336*uk_134 + 26496*uk_135 + 142416*uk_136 + 248400*uk_137 + 50784*uk_138 + 765486*uk_139 + 6542751*uk_14 + 1335150*uk_140 + 272964*uk_141 + 2328750*uk_142 + 476100*uk_143 + 97336*uk_144 + 13824*uk_145 + 74304*uk_146 + 129600*uk_147 + 26496*uk_148 + 399384*uk_149 + 11411775*uk_15 + 696600*uk_150 + 142416*uk_151 + 1215000*uk_152 + 248400*uk_153 + 50784*uk_154 + 2146689*uk_155 + 3744225*uk_156 + 765486*uk_157 + 6530625*uk_158 + 1335150*uk_159 + 2333074*uk_16 + 272964*uk_160 + 11390625*uk_161 + 2328750*uk_162 + 476100*uk_163 + 97336*uk_164 + 3025*uk_17 + 1210*uk_18 + 2530*uk_19 + 55*uk_2 + 1320*uk_20 + 7095*uk_21 + 12375*uk_22 + 2530*uk_23 + 484*uk_24 + 1012*uk_25 + 528*uk_26 + 2838*uk_27 + 4950*uk_28 + 1012*uk_29 + 22*uk_3 + 2116*uk_30 + 1104*uk_31 + 5934*uk_32 + 10350*uk_33 + 2116*uk_34 + 576*uk_35 + 3096*uk_36 + 5400*uk_37 + 1104*uk_38 + 16641*uk_39 + 46*uk_4 + 29025*uk_40 + 5934*uk_41 + 50625*uk_42 + 10350*uk_43 + 2116*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 56593173142*uk_47 + 118331180206*uk_48 + 61738007064*uk_49 + 24*uk_5 + 331841787969*uk_50 + 578793816225*uk_51 + 118331180206*uk_52 + 153424975*uk_53 + 61369990*uk_54 + 128319070*uk_55 + 66949080*uk_56 + 359851305*uk_57 + 627647625*uk_58 + 128319070*uk_59 + 129*uk_6 + 24547996*uk_60 + 51327628*uk_61 + 26779632*uk_62 + 143940522*uk_63 + 251059050*uk_64 + 51327628*uk_65 + 107321404*uk_66 + 55993776*uk_67 + 300966546*uk_68 + 524941650*uk_69 + 225*uk_7 + 107321404*uk_70 + 29214144*uk_71 + 157026024*uk_72 + 273882600*uk_73 + 55993776*uk_74 + 844014879*uk_75 + 1472118975*uk_76 + 300966546*uk_77 + 2567649375*uk_78 + 524941650*uk_79 + 46*uk_8 + 107321404*uk_80 + 166375*uk_81 + 66550*uk_82 + 139150*uk_83 + 72600*uk_84 + 390225*uk_85 + 680625*uk_86 + 139150*uk_87 + 26620*uk_88 + 55660*uk_89 + 2572416961*uk_9 + 29040*uk_90 + 156090*uk_91 + 272250*uk_92 + 55660*uk_93 + 116380*uk_94 + 60720*uk_95 + 326370*uk_96 + 569250*uk_97 + 116380*uk_98 + 31680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 172920*uk_100 + 297000*uk_101 + 29040*uk_102 + 943855*uk_103 + 1621125*uk_104 + 158510*uk_105 + 2784375*uk_106 + 272250*uk_107 + 26620*uk_108 + 10648*uk_109 + 1115818*uk_11 + 10648*uk_110 + 11616*uk_111 + 63404*uk_112 + 108900*uk_113 + 10648*uk_114 + 10648*uk_115 + 11616*uk_116 + 63404*uk_117 + 108900*uk_118 + 10648*uk_119 + 1115818*uk_12 + 12672*uk_120 + 69168*uk_121 + 118800*uk_122 + 11616*uk_123 + 377542*uk_124 + 648450*uk_125 + 63404*uk_126 + 1113750*uk_127 + 108900*uk_128 + 10648*uk_129 + 1217256*uk_13 + 10648*uk_130 + 11616*uk_131 + 63404*uk_132 + 108900*uk_133 + 10648*uk_134 + 12672*uk_135 + 69168*uk_136 + 118800*uk_137 + 11616*uk_138 + 377542*uk_139 + 6644189*uk_14 + 648450*uk_140 + 63404*uk_141 + 1113750*uk_142 + 108900*uk_143 + 10648*uk_144 + 13824*uk_145 + 75456*uk_146 + 129600*uk_147 + 12672*uk_148 + 411864*uk_149 + 11411775*uk_15 + 707400*uk_150 + 69168*uk_151 + 1215000*uk_152 + 118800*uk_153 + 11616*uk_154 + 2248091*uk_155 + 3861225*uk_156 + 377542*uk_157 + 6631875*uk_158 + 648450*uk_159 + 1115818*uk_16 + 63404*uk_160 + 11390625*uk_161 + 1113750*uk_162 + 108900*uk_163 + 10648*uk_164 + 3025*uk_17 + 1210*uk_18 + 1210*uk_19 + 55*uk_2 + 1320*uk_20 + 7205*uk_21 + 12375*uk_22 + 1210*uk_23 + 484*uk_24 + 484*uk_25 + 528*uk_26 + 2882*uk_27 + 4950*uk_28 + 484*uk_29 + 22*uk_3 + 484*uk_30 + 528*uk_31 + 2882*uk_32 + 4950*uk_33 + 484*uk_34 + 576*uk_35 + 3144*uk_36 + 5400*uk_37 + 528*uk_38 + 17161*uk_39 + 22*uk_4 + 29475*uk_40 + 2882*uk_41 + 50625*uk_42 + 4950*uk_43 + 484*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 56593173142*uk_47 + 56593173142*uk_48 + 61738007064*uk_49 + 24*uk_5 + 336986621891*uk_50 + 578793816225*uk_51 + 56593173142*uk_52 + 153424975*uk_53 + 61369990*uk_54 + 61369990*uk_55 + 66949080*uk_56 + 365430395*uk_57 + 627647625*uk_58 + 61369990*uk_59 + 131*uk_6 + 24547996*uk_60 + 24547996*uk_61 + 26779632*uk_62 + 146172158*uk_63 + 251059050*uk_64 + 24547996*uk_65 + 24547996*uk_66 + 26779632*uk_67 + 146172158*uk_68 + 251059050*uk_69 + 225*uk_7 + 24547996*uk_70 + 29214144*uk_71 + 159460536*uk_72 + 273882600*uk_73 + 26779632*uk_74 + 870388759*uk_75 + 1494942525*uk_76 + 146172158*uk_77 + 2567649375*uk_78 + 251059050*uk_79 + 22*uk_8 + 24547996*uk_80 + 166375*uk_81 + 66550*uk_82 + 66550*uk_83 + 72600*uk_84 + 396275*uk_85 + 680625*uk_86 + 66550*uk_87 + 26620*uk_88 + 26620*uk_89 + 2572416961*uk_9 + 29040*uk_90 + 158510*uk_91 + 272250*uk_92 + 26620*uk_93 + 26620*uk_94 + 29040*uk_95 + 158510*uk_96 + 272250*uk_97 + 26620*uk_98 + 31680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 175560*uk_100 + 297000*uk_101 + 29040*uk_102 + 972895*uk_103 + 1645875*uk_104 + 160930*uk_105 + 2784375*uk_106 + 272250*uk_107 + 26620*uk_108 + 97336*uk_109 + 2333074*uk_11 + 46552*uk_110 + 50784*uk_111 + 281428*uk_112 + 476100*uk_113 + 46552*uk_114 + 22264*uk_115 + 24288*uk_116 + 134596*uk_117 + 227700*uk_118 + 22264*uk_119 + 1115818*uk_12 + 26496*uk_120 + 146832*uk_121 + 248400*uk_122 + 24288*uk_123 + 813694*uk_124 + 1376550*uk_125 + 134596*uk_126 + 2328750*uk_127 + 227700*uk_128 + 22264*uk_129 + 1217256*uk_13 + 10648*uk_130 + 11616*uk_131 + 64372*uk_132 + 108900*uk_133 + 10648*uk_134 + 12672*uk_135 + 70224*uk_136 + 118800*uk_137 + 11616*uk_138 + 389158*uk_139 + 6745627*uk_14 + 658350*uk_140 + 64372*uk_141 + 1113750*uk_142 + 108900*uk_143 + 10648*uk_144 + 13824*uk_145 + 76608*uk_146 + 129600*uk_147 + 12672*uk_148 + 424536*uk_149 + 11411775*uk_15 + 718200*uk_150 + 70224*uk_151 + 1215000*uk_152 + 118800*uk_153 + 11616*uk_154 + 2352637*uk_155 + 3980025*uk_156 + 389158*uk_157 + 6733125*uk_158 + 658350*uk_159 + 1115818*uk_16 + 64372*uk_160 + 11390625*uk_161 + 1113750*uk_162 + 108900*uk_163 + 10648*uk_164 + 3025*uk_17 + 2530*uk_18 + 1210*uk_19 + 55*uk_2 + 1320*uk_20 + 7315*uk_21 + 12375*uk_22 + 1210*uk_23 + 2116*uk_24 + 1012*uk_25 + 1104*uk_26 + 6118*uk_27 + 10350*uk_28 + 1012*uk_29 + 46*uk_3 + 484*uk_30 + 528*uk_31 + 2926*uk_32 + 4950*uk_33 + 484*uk_34 + 576*uk_35 + 3192*uk_36 + 5400*uk_37 + 528*uk_38 + 17689*uk_39 + 22*uk_4 + 29925*uk_40 + 2926*uk_41 + 50625*uk_42 + 4950*uk_43 + 484*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 118331180206*uk_47 + 56593173142*uk_48 + 61738007064*uk_49 + 24*uk_5 + 342131455813*uk_50 + 578793816225*uk_51 + 56593173142*uk_52 + 153424975*uk_53 + 128319070*uk_54 + 61369990*uk_55 + 66949080*uk_56 + 371009485*uk_57 + 627647625*uk_58 + 61369990*uk_59 + 133*uk_6 + 107321404*uk_60 + 51327628*uk_61 + 55993776*uk_62 + 310298842*uk_63 + 524941650*uk_64 + 51327628*uk_65 + 24547996*uk_66 + 26779632*uk_67 + 148403794*uk_68 + 251059050*uk_69 + 225*uk_7 + 24547996*uk_70 + 29214144*uk_71 + 161895048*uk_72 + 273882600*uk_73 + 26779632*uk_74 + 897168391*uk_75 + 1517766075*uk_76 + 148403794*uk_77 + 2567649375*uk_78 + 251059050*uk_79 + 22*uk_8 + 24547996*uk_80 + 166375*uk_81 + 139150*uk_82 + 66550*uk_83 + 72600*uk_84 + 402325*uk_85 + 680625*uk_86 + 66550*uk_87 + 116380*uk_88 + 55660*uk_89 + 2572416961*uk_9 + 60720*uk_90 + 336490*uk_91 + 569250*uk_92 + 55660*uk_93 + 26620*uk_94 + 29040*uk_95 + 160930*uk_96 + 272250*uk_97 + 26620*uk_98 + 31680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 178200*uk_100 + 297000*uk_101 + 60720*uk_102 + 1002375*uk_103 + 1670625*uk_104 + 341550*uk_105 + 2784375*uk_106 + 569250*uk_107 + 116380*uk_108 + 830584*uk_109 + 4767586*uk_11 + 406456*uk_110 + 212064*uk_111 + 1192860*uk_112 + 1988100*uk_113 + 406456*uk_114 + 198904*uk_115 + 103776*uk_116 + 583740*uk_117 + 972900*uk_118 + 198904*uk_119 + 2333074*uk_12 + 54144*uk_120 + 304560*uk_121 + 507600*uk_122 + 103776*uk_123 + 1713150*uk_124 + 2855250*uk_125 + 583740*uk_126 + 4758750*uk_127 + 972900*uk_128 + 198904*uk_129 + 1217256*uk_13 + 97336*uk_130 + 50784*uk_131 + 285660*uk_132 + 476100*uk_133 + 97336*uk_134 + 26496*uk_135 + 149040*uk_136 + 248400*uk_137 + 50784*uk_138 + 838350*uk_139 + 6847065*uk_14 + 1397250*uk_140 + 285660*uk_141 + 2328750*uk_142 + 476100*uk_143 + 97336*uk_144 + 13824*uk_145 + 77760*uk_146 + 129600*uk_147 + 26496*uk_148 + 437400*uk_149 + 11411775*uk_15 + 729000*uk_150 + 149040*uk_151 + 1215000*uk_152 + 248400*uk_153 + 50784*uk_154 + 2460375*uk_155 + 4100625*uk_156 + 838350*uk_157 + 6834375*uk_158 + 1397250*uk_159 + 2333074*uk_16 + 285660*uk_160 + 11390625*uk_161 + 2328750*uk_162 + 476100*uk_163 + 97336*uk_164 + 3025*uk_17 + 5170*uk_18 + 2530*uk_19 + 55*uk_2 + 1320*uk_20 + 7425*uk_21 + 12375*uk_22 + 2530*uk_23 + 8836*uk_24 + 4324*uk_25 + 2256*uk_26 + 12690*uk_27 + 21150*uk_28 + 4324*uk_29 + 94*uk_3 + 2116*uk_30 + 1104*uk_31 + 6210*uk_32 + 10350*uk_33 + 2116*uk_34 + 576*uk_35 + 3240*uk_36 + 5400*uk_37 + 1104*uk_38 + 18225*uk_39 + 46*uk_4 + 30375*uk_40 + 6210*uk_41 + 50625*uk_42 + 10350*uk_43 + 2116*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 241807194334*uk_47 + 118331180206*uk_48 + 61738007064*uk_49 + 24*uk_5 + 347276289735*uk_50 + 578793816225*uk_51 + 118331180206*uk_52 + 153424975*uk_53 + 262217230*uk_54 + 128319070*uk_55 + 66949080*uk_56 + 376588575*uk_57 + 627647625*uk_58 + 128319070*uk_59 + 135*uk_6 + 448153084*uk_60 + 219308956*uk_61 + 114422064*uk_62 + 643624110*uk_63 + 1072706850*uk_64 + 219308956*uk_65 + 107321404*uk_66 + 55993776*uk_67 + 314964990*uk_68 + 524941650*uk_69 + 225*uk_7 + 107321404*uk_70 + 29214144*uk_71 + 164329560*uk_72 + 273882600*uk_73 + 55993776*uk_74 + 924353775*uk_75 + 1540589625*uk_76 + 314964990*uk_77 + 2567649375*uk_78 + 524941650*uk_79 + 46*uk_8 + 107321404*uk_80 + 166375*uk_81 + 284350*uk_82 + 139150*uk_83 + 72600*uk_84 + 408375*uk_85 + 680625*uk_86 + 139150*uk_87 + 485980*uk_88 + 237820*uk_89 + 2572416961*uk_9 + 124080*uk_90 + 697950*uk_91 + 1163250*uk_92 + 237820*uk_93 + 116380*uk_94 + 60720*uk_95 + 341550*uk_96 + 569250*uk_97 + 116380*uk_98 + 31680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 150700*uk_100 + 247500*uk_101 + 103400*uk_102 + 1032295*uk_103 + 1695375*uk_104 + 708290*uk_105 + 2784375*uk_106 + 1163250*uk_107 + 485980*uk_108 + 24389*uk_109 + 1470851*uk_11 + 79054*uk_110 + 16820*uk_111 + 115217*uk_112 + 189225*uk_113 + 79054*uk_114 + 256244*uk_115 + 54520*uk_116 + 373462*uk_117 + 613350*uk_118 + 256244*uk_119 + 4767586*uk_12 + 11600*uk_120 + 79460*uk_121 + 130500*uk_122 + 54520*uk_123 + 544301*uk_124 + 893925*uk_125 + 373462*uk_126 + 1468125*uk_127 + 613350*uk_128 + 256244*uk_129 + 1014380*uk_13 + 830584*uk_130 + 176720*uk_131 + 1210532*uk_132 + 1988100*uk_133 + 830584*uk_134 + 37600*uk_135 + 257560*uk_136 + 423000*uk_137 + 176720*uk_138 + 1764286*uk_139 + 6948503*uk_14 + 2897550*uk_140 + 1210532*uk_141 + 4758750*uk_142 + 1988100*uk_143 + 830584*uk_144 + 8000*uk_145 + 54800*uk_146 + 90000*uk_147 + 37600*uk_148 + 375380*uk_149 + 11411775*uk_15 + 616500*uk_150 + 257560*uk_151 + 1012500*uk_152 + 423000*uk_153 + 176720*uk_154 + 2571353*uk_155 + 4223025*uk_156 + 1764286*uk_157 + 6935625*uk_158 + 2897550*uk_159 + 4767586*uk_16 + 1210532*uk_160 + 11390625*uk_161 + 4758750*uk_162 + 1988100*uk_163 + 830584*uk_164 + 3025*uk_17 + 1595*uk_18 + 5170*uk_19 + 55*uk_2 + 1100*uk_20 + 7535*uk_21 + 12375*uk_22 + 5170*uk_23 + 841*uk_24 + 2726*uk_25 + 580*uk_26 + 3973*uk_27 + 6525*uk_28 + 2726*uk_29 + 29*uk_3 + 8836*uk_30 + 1880*uk_31 + 12878*uk_32 + 21150*uk_33 + 8836*uk_34 + 400*uk_35 + 2740*uk_36 + 4500*uk_37 + 1880*uk_38 + 18769*uk_39 + 94*uk_4 + 30825*uk_40 + 12878*uk_41 + 50625*uk_42 + 21150*uk_43 + 8836*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 74600091869*uk_47 + 241807194334*uk_48 + 51448339220*uk_49 + 20*uk_5 + 352421123657*uk_50 + 578793816225*uk_51 + 241807194334*uk_52 + 153424975*uk_53 + 80896805*uk_54 + 262217230*uk_55 + 55790900*uk_56 + 382167665*uk_57 + 627647625*uk_58 + 262217230*uk_59 + 137*uk_6 + 42654679*uk_60 + 138259994*uk_61 + 29417020*uk_62 + 201506587*uk_63 + 330941475*uk_64 + 138259994*uk_65 + 448153084*uk_66 + 95351720*uk_67 + 653159282*uk_68 + 1072706850*uk_69 + 225*uk_7 + 448153084*uk_70 + 20287600*uk_71 + 138970060*uk_72 + 228235500*uk_73 + 95351720*uk_74 + 951944911*uk_75 + 1563413175*uk_76 + 653159282*uk_77 + 2567649375*uk_78 + 1072706850*uk_79 + 94*uk_8 + 448153084*uk_80 + 166375*uk_81 + 87725*uk_82 + 284350*uk_83 + 60500*uk_84 + 414425*uk_85 + 680625*uk_86 + 284350*uk_87 + 46255*uk_88 + 149930*uk_89 + 2572416961*uk_9 + 31900*uk_90 + 218515*uk_91 + 358875*uk_92 + 149930*uk_93 + 485980*uk_94 + 103400*uk_95 + 708290*uk_96 + 1163250*uk_97 + 485980*uk_98 + 22000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 183480*uk_100 + 297000*uk_101 + 38280*uk_102 + 1062655*uk_103 + 1720125*uk_104 + 221705*uk_105 + 2784375*uk_106 + 358875*uk_107 + 46255*uk_108 + 1860867*uk_109 + 6238437*uk_11 + 438741*uk_110 + 363096*uk_111 + 2102931*uk_112 + 3404025*uk_113 + 438741*uk_114 + 103443*uk_115 + 85608*uk_116 + 495813*uk_117 + 802575*uk_118 + 103443*uk_119 + 1470851*uk_12 + 70848*uk_120 + 410328*uk_121 + 664200*uk_122 + 85608*uk_123 + 2376483*uk_124 + 3846825*uk_125 + 495813*uk_126 + 6226875*uk_127 + 802575*uk_128 + 103443*uk_129 + 1217256*uk_13 + 24389*uk_130 + 20184*uk_131 + 116899*uk_132 + 189225*uk_133 + 24389*uk_134 + 16704*uk_135 + 96744*uk_136 + 156600*uk_137 + 20184*uk_138 + 560309*uk_139 + 7049941*uk_14 + 906975*uk_140 + 116899*uk_141 + 1468125*uk_142 + 189225*uk_143 + 24389*uk_144 + 13824*uk_145 + 80064*uk_146 + 129600*uk_147 + 16704*uk_148 + 463704*uk_149 + 11411775*uk_15 + 750600*uk_150 + 96744*uk_151 + 1215000*uk_152 + 156600*uk_153 + 20184*uk_154 + 2685619*uk_155 + 4347225*uk_156 + 560309*uk_157 + 7036875*uk_158 + 906975*uk_159 + 1470851*uk_16 + 116899*uk_160 + 11390625*uk_161 + 1468125*uk_162 + 189225*uk_163 + 24389*uk_164 + 3025*uk_17 + 6765*uk_18 + 1595*uk_19 + 55*uk_2 + 1320*uk_20 + 7645*uk_21 + 12375*uk_22 + 1595*uk_23 + 15129*uk_24 + 3567*uk_25 + 2952*uk_26 + 17097*uk_27 + 27675*uk_28 + 3567*uk_29 + 123*uk_3 + 841*uk_30 + 696*uk_31 + 4031*uk_32 + 6525*uk_33 + 841*uk_34 + 576*uk_35 + 3336*uk_36 + 5400*uk_37 + 696*uk_38 + 19321*uk_39 + 29*uk_4 + 31275*uk_40 + 4031*uk_41 + 50625*uk_42 + 6525*uk_43 + 841*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 316407286203*uk_47 + 74600091869*uk_48 + 61738007064*uk_49 + 24*uk_5 + 357565957579*uk_50 + 578793816225*uk_51 + 74600091869*uk_52 + 153424975*uk_53 + 343114035*uk_54 + 80896805*uk_55 + 66949080*uk_56 + 387746755*uk_57 + 627647625*uk_58 + 80896805*uk_59 + 139*uk_6 + 767327751*uk_60 + 180914673*uk_61 + 149722488*uk_62 + 867142743*uk_63 + 1403648325*uk_64 + 180914673*uk_65 + 42654679*uk_66 + 35300424*uk_67 + 204448289*uk_68 + 330941475*uk_69 + 225*uk_7 + 42654679*uk_70 + 29214144*uk_71 + 169198584*uk_72 + 273882600*uk_73 + 35300424*uk_74 + 979941799*uk_75 + 1586236725*uk_76 + 204448289*uk_77 + 2567649375*uk_78 + 330941475*uk_79 + 29*uk_8 + 42654679*uk_80 + 166375*uk_81 + 372075*uk_82 + 87725*uk_83 + 72600*uk_84 + 420475*uk_85 + 680625*uk_86 + 87725*uk_87 + 832095*uk_88 + 196185*uk_89 + 2572416961*uk_9 + 162360*uk_90 + 940335*uk_91 + 1522125*uk_92 + 196185*uk_93 + 46255*uk_94 + 38280*uk_95 + 221705*uk_96 + 358875*uk_97 + 46255*uk_98 + 31680*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 155100*uk_100 + 247500*uk_101 + 135300*uk_102 + 1093455*uk_103 + 1744875*uk_104 + 953865*uk_105 + 2784375*uk_106 + 1522125*uk_107 + 832095*uk_108 + 1000000*uk_109 + 5071900*uk_11 + 1230000*uk_110 + 200000*uk_111 + 1410000*uk_112 + 2250000*uk_113 + 1230000*uk_114 + 1512900*uk_115 + 246000*uk_116 + 1734300*uk_117 + 2767500*uk_118 + 1512900*uk_119 + 6238437*uk_12 + 40000*uk_120 + 282000*uk_121 + 450000*uk_122 + 246000*uk_123 + 1988100*uk_124 + 3172500*uk_125 + 1734300*uk_126 + 5062500*uk_127 + 2767500*uk_128 + 1512900*uk_129 + 1014380*uk_13 + 1860867*uk_130 + 302580*uk_131 + 2133189*uk_132 + 3404025*uk_133 + 1860867*uk_134 + 49200*uk_135 + 346860*uk_136 + 553500*uk_137 + 302580*uk_138 + 2445363*uk_139 + 7151379*uk_14 + 3902175*uk_140 + 2133189*uk_141 + 6226875*uk_142 + 3404025*uk_143 + 1860867*uk_144 + 8000*uk_145 + 56400*uk_146 + 90000*uk_147 + 49200*uk_148 + 397620*uk_149 + 11411775*uk_15 + 634500*uk_150 + 346860*uk_151 + 1012500*uk_152 + 553500*uk_153 + 302580*uk_154 + 2803221*uk_155 + 4473225*uk_156 + 2445363*uk_157 + 7138125*uk_158 + 3902175*uk_159 + 6238437*uk_16 + 2133189*uk_160 + 11390625*uk_161 + 6226875*uk_162 + 3404025*uk_163 + 1860867*uk_164 + 3025*uk_17 + 5500*uk_18 + 6765*uk_19 + 55*uk_2 + 1100*uk_20 + 7755*uk_21 + 12375*uk_22 + 6765*uk_23 + 10000*uk_24 + 12300*uk_25 + 2000*uk_26 + 14100*uk_27 + 22500*uk_28 + 12300*uk_29 + 100*uk_3 + 15129*uk_30 + 2460*uk_31 + 17343*uk_32 + 27675*uk_33 + 15129*uk_34 + 400*uk_35 + 2820*uk_36 + 4500*uk_37 + 2460*uk_38 + 19881*uk_39 + 123*uk_4 + 31725*uk_40 + 17343*uk_41 + 50625*uk_42 + 27675*uk_43 + 15129*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 257241696100*uk_47 + 316407286203*uk_48 + 51448339220*uk_49 + 20*uk_5 + 362710791501*uk_50 + 578793816225*uk_51 + 316407286203*uk_52 + 153424975*uk_53 + 278954500*uk_54 + 343114035*uk_55 + 55790900*uk_56 + 393325845*uk_57 + 627647625*uk_58 + 343114035*uk_59 + 141*uk_6 + 507190000*uk_60 + 623843700*uk_61 + 101438000*uk_62 + 715137900*uk_63 + 1141177500*uk_64 + 623843700*uk_65 + 767327751*uk_66 + 124768740*uk_67 + 879619617*uk_68 + 1403648325*uk_69 + 225*uk_7 + 767327751*uk_70 + 20287600*uk_71 + 143027580*uk_72 + 228235500*uk_73 + 124768740*uk_74 + 1008344439*uk_75 + 1609060275*uk_76 + 879619617*uk_77 + 2567649375*uk_78 + 1403648325*uk_79 + 123*uk_8 + 767327751*uk_80 + 166375*uk_81 + 302500*uk_82 + 372075*uk_83 + 60500*uk_84 + 426525*uk_85 + 680625*uk_86 + 372075*uk_87 + 550000*uk_88 + 676500*uk_89 + 2572416961*uk_9 + 110000*uk_90 + 775500*uk_91 + 1237500*uk_92 + 676500*uk_93 + 832095*uk_94 + 135300*uk_95 + 953865*uk_96 + 1522125*uk_97 + 832095*uk_98 + 22000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 157300*uk_100 + 247500*uk_101 + 110000*uk_102 + 1124695*uk_103 + 1769625*uk_104 + 786500*uk_105 + 2784375*uk_106 + 1237500*uk_107 + 550000*uk_108 + 912673*uk_109 + 4919743*uk_11 + 940900*uk_110 + 188180*uk_111 + 1345487*uk_112 + 2117025*uk_113 + 940900*uk_114 + 970000*uk_115 + 194000*uk_116 + 1387100*uk_117 + 2182500*uk_118 + 970000*uk_119 + 5071900*uk_12 + 38800*uk_120 + 277420*uk_121 + 436500*uk_122 + 194000*uk_123 + 1983553*uk_124 + 3120975*uk_125 + 1387100*uk_126 + 4910625*uk_127 + 2182500*uk_128 + 970000*uk_129 + 1014380*uk_13 + 1000000*uk_130 + 200000*uk_131 + 1430000*uk_132 + 2250000*uk_133 + 1000000*uk_134 + 40000*uk_135 + 286000*uk_136 + 450000*uk_137 + 200000*uk_138 + 2044900*uk_139 + 7252817*uk_14 + 3217500*uk_140 + 1430000*uk_141 + 5062500*uk_142 + 2250000*uk_143 + 1000000*uk_144 + 8000*uk_145 + 57200*uk_146 + 90000*uk_147 + 40000*uk_148 + 408980*uk_149 + 11411775*uk_15 + 643500*uk_150 + 286000*uk_151 + 1012500*uk_152 + 450000*uk_153 + 200000*uk_154 + 2924207*uk_155 + 4601025*uk_156 + 2044900*uk_157 + 7239375*uk_158 + 3217500*uk_159 + 5071900*uk_16 + 1430000*uk_160 + 11390625*uk_161 + 5062500*uk_162 + 2250000*uk_163 + 1000000*uk_164 + 3025*uk_17 + 5335*uk_18 + 5500*uk_19 + 55*uk_2 + 1100*uk_20 + 7865*uk_21 + 12375*uk_22 + 5500*uk_23 + 9409*uk_24 + 9700*uk_25 + 1940*uk_26 + 13871*uk_27 + 21825*uk_28 + 9700*uk_29 + 97*uk_3 + 10000*uk_30 + 2000*uk_31 + 14300*uk_32 + 22500*uk_33 + 10000*uk_34 + 400*uk_35 + 2860*uk_36 + 4500*uk_37 + 2000*uk_38 + 20449*uk_39 + 100*uk_4 + 32175*uk_40 + 14300*uk_41 + 50625*uk_42 + 22500*uk_43 + 10000*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 249524445217*uk_47 + 257241696100*uk_48 + 51448339220*uk_49 + 20*uk_5 + 367855625423*uk_50 + 578793816225*uk_51 + 257241696100*uk_52 + 153424975*uk_53 + 270585865*uk_54 + 278954500*uk_55 + 55790900*uk_56 + 398904935*uk_57 + 627647625*uk_58 + 278954500*uk_59 + 143*uk_6 + 477215071*uk_60 + 491974300*uk_61 + 98394860*uk_62 + 703523249*uk_63 + 1106942175*uk_64 + 491974300*uk_65 + 507190000*uk_66 + 101438000*uk_67 + 725281700*uk_68 + 1141177500*uk_69 + 225*uk_7 + 507190000*uk_70 + 20287600*uk_71 + 145056340*uk_72 + 228235500*uk_73 + 101438000*uk_74 + 1037152831*uk_75 + 1631883825*uk_76 + 725281700*uk_77 + 2567649375*uk_78 + 1141177500*uk_79 + 100*uk_8 + 507190000*uk_80 + 166375*uk_81 + 293425*uk_82 + 302500*uk_83 + 60500*uk_84 + 432575*uk_85 + 680625*uk_86 + 302500*uk_87 + 517495*uk_88 + 533500*uk_89 + 2572416961*uk_9 + 106700*uk_90 + 762905*uk_91 + 1200375*uk_92 + 533500*uk_93 + 550000*uk_94 + 110000*uk_95 + 786500*uk_96 + 1237500*uk_97 + 550000*uk_98 + 22000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 159500*uk_100 + 247500*uk_101 + 106700*uk_102 + 1156375*uk_103 + 1794375*uk_104 + 773575*uk_105 + 2784375*uk_106 + 1200375*uk_107 + 517495*uk_108 + 1481544*uk_109 + 5781966*uk_11 + 1260612*uk_110 + 259920*uk_111 + 1884420*uk_112 + 2924100*uk_113 + 1260612*uk_114 + 1072626*uk_115 + 221160*uk_116 + 1603410*uk_117 + 2488050*uk_118 + 1072626*uk_119 + 4919743*uk_12 + 45600*uk_120 + 330600*uk_121 + 513000*uk_122 + 221160*uk_123 + 2396850*uk_124 + 3719250*uk_125 + 1603410*uk_126 + 5771250*uk_127 + 2488050*uk_128 + 1072626*uk_129 + 1014380*uk_13 + 912673*uk_130 + 188180*uk_131 + 1364305*uk_132 + 2117025*uk_133 + 912673*uk_134 + 38800*uk_135 + 281300*uk_136 + 436500*uk_137 + 188180*uk_138 + 2039425*uk_139 + 7354255*uk_14 + 3164625*uk_140 + 1364305*uk_141 + 4910625*uk_142 + 2117025*uk_143 + 912673*uk_144 + 8000*uk_145 + 58000*uk_146 + 90000*uk_147 + 38800*uk_148 + 420500*uk_149 + 11411775*uk_15 + 652500*uk_150 + 281300*uk_151 + 1012500*uk_152 + 436500*uk_153 + 188180*uk_154 + 3048625*uk_155 + 4730625*uk_156 + 2039425*uk_157 + 7340625*uk_158 + 3164625*uk_159 + 4919743*uk_16 + 1364305*uk_160 + 11390625*uk_161 + 4910625*uk_162 + 2117025*uk_163 + 912673*uk_164 + 3025*uk_17 + 6270*uk_18 + 5335*uk_19 + 55*uk_2 + 1100*uk_20 + 7975*uk_21 + 12375*uk_22 + 5335*uk_23 + 12996*uk_24 + 11058*uk_25 + 2280*uk_26 + 16530*uk_27 + 25650*uk_28 + 11058*uk_29 + 114*uk_3 + 9409*uk_30 + 1940*uk_31 + 14065*uk_32 + 21825*uk_33 + 9409*uk_34 + 400*uk_35 + 2900*uk_36 + 4500*uk_37 + 1940*uk_38 + 21025*uk_39 + 97*uk_4 + 32625*uk_40 + 14065*uk_41 + 50625*uk_42 + 21825*uk_43 + 9409*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 293255533554*uk_47 + 249524445217*uk_48 + 51448339220*uk_49 + 20*uk_5 + 373000459345*uk_50 + 578793816225*uk_51 + 249524445217*uk_52 + 153424975*uk_53 + 318008130*uk_54 + 270585865*uk_55 + 55790900*uk_56 + 404484025*uk_57 + 627647625*uk_58 + 270585865*uk_59 + 145*uk_6 + 659144124*uk_60 + 560850702*uk_61 + 115639320*uk_62 + 838385070*uk_63 + 1300942350*uk_64 + 560850702*uk_65 + 477215071*uk_66 + 98394860*uk_67 + 713362735*uk_68 + 1106942175*uk_69 + 225*uk_7 + 477215071*uk_70 + 20287600*uk_71 + 147085100*uk_72 + 228235500*uk_73 + 98394860*uk_74 + 1066366975*uk_75 + 1654707375*uk_76 + 713362735*uk_77 + 2567649375*uk_78 + 1106942175*uk_79 + 97*uk_8 + 477215071*uk_80 + 166375*uk_81 + 344850*uk_82 + 293425*uk_83 + 60500*uk_84 + 438625*uk_85 + 680625*uk_86 + 293425*uk_87 + 714780*uk_88 + 608190*uk_89 + 2572416961*uk_9 + 125400*uk_90 + 909150*uk_91 + 1410750*uk_92 + 608190*uk_93 + 517495*uk_94 + 106700*uk_95 + 773575*uk_96 + 1200375*uk_97 + 517495*uk_98 + 22000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 129360*uk_100 + 198000*uk_101 + 100320*uk_102 + 1188495*uk_103 + 1819125*uk_104 + 921690*uk_105 + 2784375*uk_106 + 1410750*uk_107 + 714780*uk_108 + 64*uk_109 + 202876*uk_11 + 1824*uk_110 + 256*uk_111 + 2352*uk_112 + 3600*uk_113 + 1824*uk_114 + 51984*uk_115 + 7296*uk_116 + 67032*uk_117 + 102600*uk_118 + 51984*uk_119 + 5781966*uk_12 + 1024*uk_120 + 9408*uk_121 + 14400*uk_122 + 7296*uk_123 + 86436*uk_124 + 132300*uk_125 + 67032*uk_126 + 202500*uk_127 + 102600*uk_128 + 51984*uk_129 + 811504*uk_13 + 1481544*uk_130 + 207936*uk_131 + 1910412*uk_132 + 2924100*uk_133 + 1481544*uk_134 + 29184*uk_135 + 268128*uk_136 + 410400*uk_137 + 207936*uk_138 + 2463426*uk_139 + 7455693*uk_14 + 3770550*uk_140 + 1910412*uk_141 + 5771250*uk_142 + 2924100*uk_143 + 1481544*uk_144 + 4096*uk_145 + 37632*uk_146 + 57600*uk_147 + 29184*uk_148 + 345744*uk_149 + 11411775*uk_15 + 529200*uk_150 + 268128*uk_151 + 810000*uk_152 + 410400*uk_153 + 207936*uk_154 + 3176523*uk_155 + 4862025*uk_156 + 2463426*uk_157 + 7441875*uk_158 + 3770550*uk_159 + 5781966*uk_16 + 1910412*uk_160 + 11390625*uk_161 + 5771250*uk_162 + 2924100*uk_163 + 1481544*uk_164 + 3025*uk_17 + 220*uk_18 + 6270*uk_19 + 55*uk_2 + 880*uk_20 + 8085*uk_21 + 12375*uk_22 + 6270*uk_23 + 16*uk_24 + 456*uk_25 + 64*uk_26 + 588*uk_27 + 900*uk_28 + 456*uk_29 + 4*uk_3 + 12996*uk_30 + 1824*uk_31 + 16758*uk_32 + 25650*uk_33 + 12996*uk_34 + 256*uk_35 + 2352*uk_36 + 3600*uk_37 + 1824*uk_38 + 21609*uk_39 + 114*uk_4 + 33075*uk_40 + 16758*uk_41 + 50625*uk_42 + 25650*uk_43 + 12996*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 10289667844*uk_47 + 293255533554*uk_48 + 41158671376*uk_49 + 16*uk_5 + 378145293267*uk_50 + 578793816225*uk_51 + 293255533554*uk_52 + 153424975*uk_53 + 11158180*uk_54 + 318008130*uk_55 + 44632720*uk_56 + 410063115*uk_57 + 627647625*uk_58 + 318008130*uk_59 + 147*uk_6 + 811504*uk_60 + 23127864*uk_61 + 3246016*uk_62 + 29822772*uk_63 + 45647100*uk_64 + 23127864*uk_65 + 659144124*uk_66 + 92511456*uk_67 + 849949002*uk_68 + 1300942350*uk_69 + 225*uk_7 + 659144124*uk_70 + 12984064*uk_71 + 119291088*uk_72 + 182588400*uk_73 + 92511456*uk_74 + 1095986871*uk_75 + 1677530925*uk_76 + 849949002*uk_77 + 2567649375*uk_78 + 1300942350*uk_79 + 114*uk_8 + 659144124*uk_80 + 166375*uk_81 + 12100*uk_82 + 344850*uk_83 + 48400*uk_84 + 444675*uk_85 + 680625*uk_86 + 344850*uk_87 + 880*uk_88 + 25080*uk_89 + 2572416961*uk_9 + 3520*uk_90 + 32340*uk_91 + 49500*uk_92 + 25080*uk_93 + 714780*uk_94 + 100320*uk_95 + 921690*uk_96 + 1410750*uk_97 + 714780*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 163900*uk_100 + 247500*uk_101 + 4400*uk_102 + 1221055*uk_103 + 1843875*uk_104 + 32780*uk_105 + 2784375*uk_106 + 49500*uk_107 + 880*uk_108 + 205379*uk_109 + 2992421*uk_11 + 13924*uk_110 + 69620*uk_111 + 518669*uk_112 + 783225*uk_113 + 13924*uk_114 + 944*uk_115 + 4720*uk_116 + 35164*uk_117 + 53100*uk_118 + 944*uk_119 + 202876*uk_12 + 23600*uk_120 + 175820*uk_121 + 265500*uk_122 + 4720*uk_123 + 1309859*uk_124 + 1977975*uk_125 + 35164*uk_126 + 2986875*uk_127 + 53100*uk_128 + 944*uk_129 + 1014380*uk_13 + 64*uk_130 + 320*uk_131 + 2384*uk_132 + 3600*uk_133 + 64*uk_134 + 1600*uk_135 + 11920*uk_136 + 18000*uk_137 + 320*uk_138 + 88804*uk_139 + 7557131*uk_14 + 134100*uk_140 + 2384*uk_141 + 202500*uk_142 + 3600*uk_143 + 64*uk_144 + 8000*uk_145 + 59600*uk_146 + 90000*uk_147 + 1600*uk_148 + 444020*uk_149 + 11411775*uk_15 + 670500*uk_150 + 11920*uk_151 + 1012500*uk_152 + 18000*uk_153 + 320*uk_154 + 3307949*uk_155 + 4995225*uk_156 + 88804*uk_157 + 7543125*uk_158 + 134100*uk_159 + 202876*uk_16 + 2384*uk_160 + 11390625*uk_161 + 202500*uk_162 + 3600*uk_163 + 64*uk_164 + 3025*uk_17 + 3245*uk_18 + 220*uk_19 + 55*uk_2 + 1100*uk_20 + 8195*uk_21 + 12375*uk_22 + 220*uk_23 + 3481*uk_24 + 236*uk_25 + 1180*uk_26 + 8791*uk_27 + 13275*uk_28 + 236*uk_29 + 59*uk_3 + 16*uk_30 + 80*uk_31 + 596*uk_32 + 900*uk_33 + 16*uk_34 + 400*uk_35 + 2980*uk_36 + 4500*uk_37 + 80*uk_38 + 22201*uk_39 + 4*uk_4 + 33525*uk_40 + 596*uk_41 + 50625*uk_42 + 900*uk_43 + 16*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 151772600699*uk_47 + 10289667844*uk_48 + 51448339220*uk_49 + 20*uk_5 + 383290127189*uk_50 + 578793816225*uk_51 + 10289667844*uk_52 + 153424975*uk_53 + 164583155*uk_54 + 11158180*uk_55 + 55790900*uk_56 + 415642205*uk_57 + 627647625*uk_58 + 11158180*uk_59 + 149*uk_6 + 176552839*uk_60 + 11969684*uk_61 + 59848420*uk_62 + 445870729*uk_63 + 673294725*uk_64 + 11969684*uk_65 + 811504*uk_66 + 4057520*uk_67 + 30228524*uk_68 + 45647100*uk_69 + 225*uk_7 + 811504*uk_70 + 20287600*uk_71 + 151142620*uk_72 + 228235500*uk_73 + 4057520*uk_74 + 1126012519*uk_75 + 1700354475*uk_76 + 30228524*uk_77 + 2567649375*uk_78 + 45647100*uk_79 + 4*uk_8 + 811504*uk_80 + 166375*uk_81 + 178475*uk_82 + 12100*uk_83 + 60500*uk_84 + 450725*uk_85 + 680625*uk_86 + 12100*uk_87 + 191455*uk_88 + 12980*uk_89 + 2572416961*uk_9 + 64900*uk_90 + 483505*uk_91 + 730125*uk_92 + 12980*uk_93 + 880*uk_94 + 4400*uk_95 + 32780*uk_96 + 49500*uk_97 + 880*uk_98 + 22000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 166100*uk_100 + 247500*uk_101 + 64900*uk_102 + 1254055*uk_103 + 1868625*uk_104 + 489995*uk_105 + 2784375*uk_106 + 730125*uk_107 + 191455*uk_108 + 2406104*uk_109 + 6796346*uk_11 + 1059404*uk_110 + 359120*uk_111 + 2711356*uk_112 + 4040100*uk_113 + 1059404*uk_114 + 466454*uk_115 + 158120*uk_116 + 1193806*uk_117 + 1778850*uk_118 + 466454*uk_119 + 2992421*uk_12 + 53600*uk_120 + 404680*uk_121 + 603000*uk_122 + 158120*uk_123 + 3055334*uk_124 + 4552650*uk_125 + 1193806*uk_126 + 6783750*uk_127 + 1778850*uk_128 + 466454*uk_129 + 1014380*uk_13 + 205379*uk_130 + 69620*uk_131 + 525631*uk_132 + 783225*uk_133 + 205379*uk_134 + 23600*uk_135 + 178180*uk_136 + 265500*uk_137 + 69620*uk_138 + 1345259*uk_139 + 7658569*uk_14 + 2004525*uk_140 + 525631*uk_141 + 2986875*uk_142 + 783225*uk_143 + 205379*uk_144 + 8000*uk_145 + 60400*uk_146 + 90000*uk_147 + 23600*uk_148 + 456020*uk_149 + 11411775*uk_15 + 679500*uk_150 + 178180*uk_151 + 1012500*uk_152 + 265500*uk_153 + 69620*uk_154 + 3442951*uk_155 + 5130225*uk_156 + 1345259*uk_157 + 7644375*uk_158 + 2004525*uk_159 + 2992421*uk_16 + 525631*uk_160 + 11390625*uk_161 + 2986875*uk_162 + 783225*uk_163 + 205379*uk_164 + 3025*uk_17 + 7370*uk_18 + 3245*uk_19 + 55*uk_2 + 1100*uk_20 + 8305*uk_21 + 12375*uk_22 + 3245*uk_23 + 17956*uk_24 + 7906*uk_25 + 2680*uk_26 + 20234*uk_27 + 30150*uk_28 + 7906*uk_29 + 134*uk_3 + 3481*uk_30 + 1180*uk_31 + 8909*uk_32 + 13275*uk_33 + 3481*uk_34 + 400*uk_35 + 3020*uk_36 + 4500*uk_37 + 1180*uk_38 + 22801*uk_39 + 59*uk_4 + 33975*uk_40 + 8909*uk_41 + 50625*uk_42 + 13275*uk_43 + 3481*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 344703872774*uk_47 + 151772600699*uk_48 + 51448339220*uk_49 + 20*uk_5 + 388434961111*uk_50 + 578793816225*uk_51 + 151772600699*uk_52 + 153424975*uk_53 + 373799030*uk_54 + 164583155*uk_55 + 55790900*uk_56 + 421221295*uk_57 + 627647625*uk_58 + 164583155*uk_59 + 151*uk_6 + 910710364*uk_60 + 400984414*uk_61 + 135926920*uk_62 + 1026248246*uk_63 + 1529177850*uk_64 + 400984414*uk_65 + 176552839*uk_66 + 59848420*uk_67 + 451855571*uk_68 + 673294725*uk_69 + 225*uk_7 + 176552839*uk_70 + 20287600*uk_71 + 153171380*uk_72 + 228235500*uk_73 + 59848420*uk_74 + 1156443919*uk_75 + 1723178025*uk_76 + 451855571*uk_77 + 2567649375*uk_78 + 673294725*uk_79 + 59*uk_8 + 176552839*uk_80 + 166375*uk_81 + 405350*uk_82 + 178475*uk_83 + 60500*uk_84 + 456775*uk_85 + 680625*uk_86 + 178475*uk_87 + 987580*uk_88 + 434830*uk_89 + 2572416961*uk_9 + 147400*uk_90 + 1112870*uk_91 + 1658250*uk_92 + 434830*uk_93 + 191455*uk_94 + 64900*uk_95 + 489995*uk_96 + 730125*uk_97 + 191455*uk_98 + 22000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 134640*uk_100 + 198000*uk_101 + 117920*uk_102 + 1287495*uk_103 + 1893375*uk_104 + 1127610*uk_105 + 2784375*uk_106 + 1658250*uk_107 + 987580*uk_108 + 438976*uk_109 + 3854644*uk_11 + 773984*uk_110 + 92416*uk_111 + 883728*uk_112 + 1299600*uk_113 + 773984*uk_114 + 1364656*uk_115 + 162944*uk_116 + 1558152*uk_117 + 2291400*uk_118 + 1364656*uk_119 + 6796346*uk_12 + 19456*uk_120 + 186048*uk_121 + 273600*uk_122 + 162944*uk_123 + 1779084*uk_124 + 2616300*uk_125 + 1558152*uk_126 + 3847500*uk_127 + 2291400*uk_128 + 1364656*uk_129 + 811504*uk_13 + 2406104*uk_130 + 287296*uk_131 + 2747268*uk_132 + 4040100*uk_133 + 2406104*uk_134 + 34304*uk_135 + 328032*uk_136 + 482400*uk_137 + 287296*uk_138 + 3136806*uk_139 + 7760007*uk_14 + 4612950*uk_140 + 2747268*uk_141 + 6783750*uk_142 + 4040100*uk_143 + 2406104*uk_144 + 4096*uk_145 + 39168*uk_146 + 57600*uk_147 + 34304*uk_148 + 374544*uk_149 + 11411775*uk_15 + 550800*uk_150 + 328032*uk_151 + 810000*uk_152 + 482400*uk_153 + 287296*uk_154 + 3581577*uk_155 + 5267025*uk_156 + 3136806*uk_157 + 7745625*uk_158 + 4612950*uk_159 + 6796346*uk_16 + 2747268*uk_160 + 11390625*uk_161 + 6783750*uk_162 + 4040100*uk_163 + 2406104*uk_164 + 3025*uk_17 + 4180*uk_18 + 7370*uk_19 + 55*uk_2 + 880*uk_20 + 8415*uk_21 + 12375*uk_22 + 7370*uk_23 + 5776*uk_24 + 10184*uk_25 + 1216*uk_26 + 11628*uk_27 + 17100*uk_28 + 10184*uk_29 + 76*uk_3 + 17956*uk_30 + 2144*uk_31 + 20502*uk_32 + 30150*uk_33 + 17956*uk_34 + 256*uk_35 + 2448*uk_36 + 3600*uk_37 + 2144*uk_38 + 23409*uk_39 + 134*uk_4 + 34425*uk_40 + 20502*uk_41 + 50625*uk_42 + 30150*uk_43 + 17956*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 195503689036*uk_47 + 344703872774*uk_48 + 41158671376*uk_49 + 16*uk_5 + 393579795033*uk_50 + 578793816225*uk_51 + 344703872774*uk_52 + 153424975*uk_53 + 212005420*uk_54 + 373799030*uk_55 + 44632720*uk_56 + 426800385*uk_57 + 627647625*uk_58 + 373799030*uk_59 + 153*uk_6 + 292952944*uk_60 + 516522296*uk_61 + 61674304*uk_62 + 589760532*uk_63 + 867294900*uk_64 + 516522296*uk_65 + 910710364*uk_66 + 108741536*uk_67 + 1039840938*uk_68 + 1529177850*uk_69 + 225*uk_7 + 910710364*uk_70 + 12984064*uk_71 + 124160112*uk_72 + 182588400*uk_73 + 108741536*uk_74 + 1187281071*uk_75 + 1746001575*uk_76 + 1039840938*uk_77 + 2567649375*uk_78 + 1529177850*uk_79 + 134*uk_8 + 910710364*uk_80 + 166375*uk_81 + 229900*uk_82 + 405350*uk_83 + 48400*uk_84 + 462825*uk_85 + 680625*uk_86 + 405350*uk_87 + 317680*uk_88 + 560120*uk_89 + 2572416961*uk_9 + 66880*uk_90 + 639540*uk_91 + 940500*uk_92 + 560120*uk_93 + 987580*uk_94 + 117920*uk_95 + 1127610*uk_96 + 1658250*uk_97 + 987580*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 136400*uk_100 + 198000*uk_101 + 66880*uk_102 + 1321375*uk_103 + 1918125*uk_104 + 647900*uk_105 + 2784375*uk_106 + 940500*uk_107 + 317680*uk_108 + 39304*uk_109 + 1724446*uk_11 + 87856*uk_110 + 18496*uk_111 + 179180*uk_112 + 260100*uk_113 + 87856*uk_114 + 196384*uk_115 + 41344*uk_116 + 400520*uk_117 + 581400*uk_118 + 196384*uk_119 + 3854644*uk_12 + 8704*uk_120 + 84320*uk_121 + 122400*uk_122 + 41344*uk_123 + 816850*uk_124 + 1185750*uk_125 + 400520*uk_126 + 1721250*uk_127 + 581400*uk_128 + 196384*uk_129 + 811504*uk_13 + 438976*uk_130 + 92416*uk_131 + 895280*uk_132 + 1299600*uk_133 + 438976*uk_134 + 19456*uk_135 + 188480*uk_136 + 273600*uk_137 + 92416*uk_138 + 1825900*uk_139 + 7861445*uk_14 + 2650500*uk_140 + 895280*uk_141 + 3847500*uk_142 + 1299600*uk_143 + 438976*uk_144 + 4096*uk_145 + 39680*uk_146 + 57600*uk_147 + 19456*uk_148 + 384400*uk_149 + 11411775*uk_15 + 558000*uk_150 + 188480*uk_151 + 810000*uk_152 + 273600*uk_153 + 92416*uk_154 + 3723875*uk_155 + 5405625*uk_156 + 1825900*uk_157 + 7846875*uk_158 + 2650500*uk_159 + 3854644*uk_16 + 895280*uk_160 + 11390625*uk_161 + 3847500*uk_162 + 1299600*uk_163 + 438976*uk_164 + 3025*uk_17 + 1870*uk_18 + 4180*uk_19 + 55*uk_2 + 880*uk_20 + 8525*uk_21 + 12375*uk_22 + 4180*uk_23 + 1156*uk_24 + 2584*uk_25 + 544*uk_26 + 5270*uk_27 + 7650*uk_28 + 2584*uk_29 + 34*uk_3 + 5776*uk_30 + 1216*uk_31 + 11780*uk_32 + 17100*uk_33 + 5776*uk_34 + 256*uk_35 + 2480*uk_36 + 3600*uk_37 + 1216*uk_38 + 24025*uk_39 + 76*uk_4 + 34875*uk_40 + 11780*uk_41 + 50625*uk_42 + 17100*uk_43 + 5776*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 87462176674*uk_47 + 195503689036*uk_48 + 41158671376*uk_49 + 16*uk_5 + 398724628955*uk_50 + 578793816225*uk_51 + 195503689036*uk_52 + 153424975*uk_53 + 94844530*uk_54 + 212005420*uk_55 + 44632720*uk_56 + 432379475*uk_57 + 627647625*uk_58 + 212005420*uk_59 + 155*uk_6 + 58631164*uk_60 + 131057896*uk_61 + 27591136*uk_62 + 267289130*uk_63 + 388000350*uk_64 + 131057896*uk_65 + 292952944*uk_66 + 61674304*uk_67 + 597469820*uk_68 + 867294900*uk_69 + 225*uk_7 + 292952944*uk_70 + 12984064*uk_71 + 125783120*uk_72 + 182588400*uk_73 + 61674304*uk_74 + 1218523975*uk_75 + 1768825125*uk_76 + 597469820*uk_77 + 2567649375*uk_78 + 867294900*uk_79 + 76*uk_8 + 292952944*uk_80 + 166375*uk_81 + 102850*uk_82 + 229900*uk_83 + 48400*uk_84 + 468875*uk_85 + 680625*uk_86 + 229900*uk_87 + 63580*uk_88 + 142120*uk_89 + 2572416961*uk_9 + 29920*uk_90 + 289850*uk_91 + 420750*uk_92 + 142120*uk_93 + 317680*uk_94 + 66880*uk_95 + 647900*uk_96 + 940500*uk_97 + 317680*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 138160*uk_100 + 198000*uk_101 + 29920*uk_102 + 1355695*uk_103 + 1942875*uk_104 + 293590*uk_105 + 2784375*uk_106 + 420750*uk_107 + 63580*uk_108 + 512*uk_109 + 405752*uk_11 + 2176*uk_110 + 1024*uk_111 + 10048*uk_112 + 14400*uk_113 + 2176*uk_114 + 9248*uk_115 + 4352*uk_116 + 42704*uk_117 + 61200*uk_118 + 9248*uk_119 + 1724446*uk_12 + 2048*uk_120 + 20096*uk_121 + 28800*uk_122 + 4352*uk_123 + 197192*uk_124 + 282600*uk_125 + 42704*uk_126 + 405000*uk_127 + 61200*uk_128 + 9248*uk_129 + 811504*uk_13 + 39304*uk_130 + 18496*uk_131 + 181492*uk_132 + 260100*uk_133 + 39304*uk_134 + 8704*uk_135 + 85408*uk_136 + 122400*uk_137 + 18496*uk_138 + 838066*uk_139 + 7962883*uk_14 + 1201050*uk_140 + 181492*uk_141 + 1721250*uk_142 + 260100*uk_143 + 39304*uk_144 + 4096*uk_145 + 40192*uk_146 + 57600*uk_147 + 8704*uk_148 + 394384*uk_149 + 11411775*uk_15 + 565200*uk_150 + 85408*uk_151 + 810000*uk_152 + 122400*uk_153 + 18496*uk_154 + 3869893*uk_155 + 5546025*uk_156 + 838066*uk_157 + 7948125*uk_158 + 1201050*uk_159 + 1724446*uk_16 + 181492*uk_160 + 11390625*uk_161 + 1721250*uk_162 + 260100*uk_163 + 39304*uk_164 + 3025*uk_17 + 440*uk_18 + 1870*uk_19 + 55*uk_2 + 880*uk_20 + 8635*uk_21 + 12375*uk_22 + 1870*uk_23 + 64*uk_24 + 272*uk_25 + 128*uk_26 + 1256*uk_27 + 1800*uk_28 + 272*uk_29 + 8*uk_3 + 1156*uk_30 + 544*uk_31 + 5338*uk_32 + 7650*uk_33 + 1156*uk_34 + 256*uk_35 + 2512*uk_36 + 3600*uk_37 + 544*uk_38 + 24649*uk_39 + 34*uk_4 + 35325*uk_40 + 5338*uk_41 + 50625*uk_42 + 7650*uk_43 + 1156*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 20579335688*uk_47 + 87462176674*uk_48 + 41158671376*uk_49 + 16*uk_5 + 403869462877*uk_50 + 578793816225*uk_51 + 87462176674*uk_52 + 153424975*uk_53 + 22316360*uk_54 + 94844530*uk_55 + 44632720*uk_56 + 437958565*uk_57 + 627647625*uk_58 + 94844530*uk_59 + 157*uk_6 + 3246016*uk_60 + 13795568*uk_61 + 6492032*uk_62 + 63703064*uk_63 + 91294200*uk_64 + 13795568*uk_65 + 58631164*uk_66 + 27591136*uk_67 + 270738022*uk_68 + 388000350*uk_69 + 225*uk_7 + 58631164*uk_70 + 12984064*uk_71 + 127406128*uk_72 + 182588400*uk_73 + 27591136*uk_74 + 1250172631*uk_75 + 1791648675*uk_76 + 270738022*uk_77 + 2567649375*uk_78 + 388000350*uk_79 + 34*uk_8 + 58631164*uk_80 + 166375*uk_81 + 24200*uk_82 + 102850*uk_83 + 48400*uk_84 + 474925*uk_85 + 680625*uk_86 + 102850*uk_87 + 3520*uk_88 + 14960*uk_89 + 2572416961*uk_9 + 7040*uk_90 + 69080*uk_91 + 99000*uk_92 + 14960*uk_93 + 63580*uk_94 + 29920*uk_95 + 293590*uk_96 + 420750*uk_97 + 63580*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 174900*uk_100 + 247500*uk_101 + 8800*uk_102 + 1390455*uk_103 + 1967625*uk_104 + 69960*uk_105 + 2784375*uk_106 + 99000*uk_107 + 3520*uk_108 + 3869893*uk_109 + 7962883*uk_11 + 197192*uk_110 + 492980*uk_111 + 3919191*uk_112 + 5546025*uk_113 + 197192*uk_114 + 10048*uk_115 + 25120*uk_116 + 199704*uk_117 + 282600*uk_118 + 10048*uk_119 + 405752*uk_12 + 62800*uk_120 + 499260*uk_121 + 706500*uk_122 + 25120*uk_123 + 3969117*uk_124 + 5616675*uk_125 + 199704*uk_126 + 7948125*uk_127 + 282600*uk_128 + 10048*uk_129 + 1014380*uk_13 + 512*uk_130 + 1280*uk_131 + 10176*uk_132 + 14400*uk_133 + 512*uk_134 + 3200*uk_135 + 25440*uk_136 + 36000*uk_137 + 1280*uk_138 + 202248*uk_139 + 8064321*uk_14 + 286200*uk_140 + 10176*uk_141 + 405000*uk_142 + 14400*uk_143 + 512*uk_144 + 8000*uk_145 + 63600*uk_146 + 90000*uk_147 + 3200*uk_148 + 505620*uk_149 + 11411775*uk_15 + 715500*uk_150 + 25440*uk_151 + 1012500*uk_152 + 36000*uk_153 + 1280*uk_154 + 4019679*uk_155 + 5688225*uk_156 + 202248*uk_157 + 8049375*uk_158 + 286200*uk_159 + 405752*uk_16 + 10176*uk_160 + 11390625*uk_161 + 405000*uk_162 + 14400*uk_163 + 512*uk_164 + 3025*uk_17 + 8635*uk_18 + 440*uk_19 + 55*uk_2 + 1100*uk_20 + 8745*uk_21 + 12375*uk_22 + 440*uk_23 + 24649*uk_24 + 1256*uk_25 + 3140*uk_26 + 24963*uk_27 + 35325*uk_28 + 1256*uk_29 + 157*uk_3 + 64*uk_30 + 160*uk_31 + 1272*uk_32 + 1800*uk_33 + 64*uk_34 + 400*uk_35 + 3180*uk_36 + 4500*uk_37 + 160*uk_38 + 25281*uk_39 + 8*uk_4 + 35775*uk_40 + 1272*uk_41 + 50625*uk_42 + 1800*uk_43 + 64*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 403869462877*uk_47 + 20579335688*uk_48 + 51448339220*uk_49 + 20*uk_5 + 409014296799*uk_50 + 578793816225*uk_51 + 20579335688*uk_52 + 153424975*uk_53 + 437958565*uk_54 + 22316360*uk_55 + 55790900*uk_56 + 443537655*uk_57 + 627647625*uk_58 + 22316360*uk_59 + 159*uk_6 + 1250172631*uk_60 + 63703064*uk_61 + 159257660*uk_62 + 1266098397*uk_63 + 1791648675*uk_64 + 63703064*uk_65 + 3246016*uk_66 + 8115040*uk_67 + 64514568*uk_68 + 91294200*uk_69 + 225*uk_7 + 3246016*uk_70 + 20287600*uk_71 + 161286420*uk_72 + 228235500*uk_73 + 8115040*uk_74 + 1282227039*uk_75 + 1814472225*uk_76 + 64514568*uk_77 + 2567649375*uk_78 + 91294200*uk_79 + 8*uk_8 + 3246016*uk_80 + 166375*uk_81 + 474925*uk_82 + 24200*uk_83 + 60500*uk_84 + 480975*uk_85 + 680625*uk_86 + 24200*uk_87 + 1355695*uk_88 + 69080*uk_89 + 2572416961*uk_9 + 172700*uk_90 + 1372965*uk_91 + 1942875*uk_92 + 69080*uk_93 + 3520*uk_94 + 8800*uk_95 + 69960*uk_96 + 99000*uk_97 + 3520*uk_98 + 22000*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 106260*uk_100 + 148500*uk_101 + 103620*uk_102 + 1425655*uk_103 + 1992375*uk_104 + 1390235*uk_105 + 2784375*uk_106 + 1942875*uk_107 + 1355695*uk_108 + 64*uk_109 + 202876*uk_11 + 2512*uk_110 + 192*uk_111 + 2576*uk_112 + 3600*uk_113 + 2512*uk_114 + 98596*uk_115 + 7536*uk_116 + 101108*uk_117 + 141300*uk_118 + 98596*uk_119 + 7962883*uk_12 + 576*uk_120 + 7728*uk_121 + 10800*uk_122 + 7536*uk_123 + 103684*uk_124 + 144900*uk_125 + 101108*uk_126 + 202500*uk_127 + 141300*uk_128 + 98596*uk_129 + 608628*uk_13 + 3869893*uk_130 + 295788*uk_131 + 3968489*uk_132 + 5546025*uk_133 + 3869893*uk_134 + 22608*uk_135 + 303324*uk_136 + 423900*uk_137 + 295788*uk_138 + 4069597*uk_139 + 8165759*uk_14 + 5687325*uk_140 + 3968489*uk_141 + 7948125*uk_142 + 5546025*uk_143 + 3869893*uk_144 + 1728*uk_145 + 23184*uk_146 + 32400*uk_147 + 22608*uk_148 + 311052*uk_149 + 11411775*uk_15 + 434700*uk_150 + 303324*uk_151 + 607500*uk_152 + 423900*uk_153 + 295788*uk_154 + 4173281*uk_155 + 5832225*uk_156 + 4069597*uk_157 + 8150625*uk_158 + 5687325*uk_159 + 7962883*uk_16 + 3968489*uk_160 + 11390625*uk_161 + 7948125*uk_162 + 5546025*uk_163 + 3869893*uk_164 + 3025*uk_17 + 220*uk_18 + 8635*uk_19 + 55*uk_2 + 660*uk_20 + 8855*uk_21 + 12375*uk_22 + 8635*uk_23 + 16*uk_24 + 628*uk_25 + 48*uk_26 + 644*uk_27 + 900*uk_28 + 628*uk_29 + 4*uk_3 + 24649*uk_30 + 1884*uk_31 + 25277*uk_32 + 35325*uk_33 + 24649*uk_34 + 144*uk_35 + 1932*uk_36 + 2700*uk_37 + 1884*uk_38 + 25921*uk_39 + 157*uk_4 + 36225*uk_40 + 25277*uk_41 + 50625*uk_42 + 35325*uk_43 + 24649*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 10289667844*uk_47 + 403869462877*uk_48 + 30869003532*uk_49 + 12*uk_5 + 414159130721*uk_50 + 578793816225*uk_51 + 403869462877*uk_52 + 153424975*uk_53 + 11158180*uk_54 + 437958565*uk_55 + 33474540*uk_56 + 449116745*uk_57 + 627647625*uk_58 + 437958565*uk_59 + 161*uk_6 + 811504*uk_60 + 31851532*uk_61 + 2434512*uk_62 + 32663036*uk_63 + 45647100*uk_64 + 31851532*uk_65 + 1250172631*uk_66 + 95554596*uk_67 + 1282024163*uk_68 + 1791648675*uk_69 + 225*uk_7 + 1250172631*uk_70 + 7303536*uk_71 + 97989108*uk_72 + 136941300*uk_73 + 95554596*uk_74 + 1314687199*uk_75 + 1837295775*uk_76 + 1282024163*uk_77 + 2567649375*uk_78 + 1791648675*uk_79 + 157*uk_8 + 1250172631*uk_80 + 166375*uk_81 + 12100*uk_82 + 474925*uk_83 + 36300*uk_84 + 487025*uk_85 + 680625*uk_86 + 474925*uk_87 + 880*uk_88 + 34540*uk_89 + 2572416961*uk_9 + 2640*uk_90 + 35420*uk_91 + 49500*uk_92 + 34540*uk_93 + 1355695*uk_94 + 103620*uk_95 + 1390235*uk_96 + 1942875*uk_97 + 1355695*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 143440*uk_100 + 198000*uk_101 + 3520*uk_102 + 1461295*uk_103 + 2017125*uk_104 + 35860*uk_105 + 2784375*uk_106 + 49500*uk_107 + 880*uk_108 + 17576*uk_109 + 1318694*uk_11 + 2704*uk_110 + 10816*uk_111 + 110188*uk_112 + 152100*uk_113 + 2704*uk_114 + 416*uk_115 + 1664*uk_116 + 16952*uk_117 + 23400*uk_118 + 416*uk_119 + 202876*uk_12 + 6656*uk_120 + 67808*uk_121 + 93600*uk_122 + 1664*uk_123 + 690794*uk_124 + 953550*uk_125 + 16952*uk_126 + 1316250*uk_127 + 23400*uk_128 + 416*uk_129 + 811504*uk_13 + 64*uk_130 + 256*uk_131 + 2608*uk_132 + 3600*uk_133 + 64*uk_134 + 1024*uk_135 + 10432*uk_136 + 14400*uk_137 + 256*uk_138 + 106276*uk_139 + 8267197*uk_14 + 146700*uk_140 + 2608*uk_141 + 202500*uk_142 + 3600*uk_143 + 64*uk_144 + 4096*uk_145 + 41728*uk_146 + 57600*uk_147 + 1024*uk_148 + 425104*uk_149 + 11411775*uk_15 + 586800*uk_150 + 10432*uk_151 + 810000*uk_152 + 14400*uk_153 + 256*uk_154 + 4330747*uk_155 + 5978025*uk_156 + 106276*uk_157 + 8251875*uk_158 + 146700*uk_159 + 202876*uk_16 + 2608*uk_160 + 11390625*uk_161 + 202500*uk_162 + 3600*uk_163 + 64*uk_164 + 3025*uk_17 + 1430*uk_18 + 220*uk_19 + 55*uk_2 + 880*uk_20 + 8965*uk_21 + 12375*uk_22 + 220*uk_23 + 676*uk_24 + 104*uk_25 + 416*uk_26 + 4238*uk_27 + 5850*uk_28 + 104*uk_29 + 26*uk_3 + 16*uk_30 + 64*uk_31 + 652*uk_32 + 900*uk_33 + 16*uk_34 + 256*uk_35 + 2608*uk_36 + 3600*uk_37 + 64*uk_38 + 26569*uk_39 + 4*uk_4 + 36675*uk_40 + 652*uk_41 + 50625*uk_42 + 900*uk_43 + 16*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 66882840986*uk_47 + 10289667844*uk_48 + 41158671376*uk_49 + 16*uk_5 + 419303964643*uk_50 + 578793816225*uk_51 + 10289667844*uk_52 + 153424975*uk_53 + 72528170*uk_54 + 11158180*uk_55 + 44632720*uk_56 + 454695835*uk_57 + 627647625*uk_58 + 11158180*uk_59 + 163*uk_6 + 34286044*uk_60 + 5274776*uk_61 + 21099104*uk_62 + 214947122*uk_63 + 296706150*uk_64 + 5274776*uk_65 + 811504*uk_66 + 3246016*uk_67 + 33068788*uk_68 + 45647100*uk_69 + 225*uk_7 + 811504*uk_70 + 12984064*uk_71 + 132275152*uk_72 + 182588400*uk_73 + 3246016*uk_74 + 1347553111*uk_75 + 1860119325*uk_76 + 33068788*uk_77 + 2567649375*uk_78 + 45647100*uk_79 + 4*uk_8 + 811504*uk_80 + 166375*uk_81 + 78650*uk_82 + 12100*uk_83 + 48400*uk_84 + 493075*uk_85 + 680625*uk_86 + 12100*uk_87 + 37180*uk_88 + 5720*uk_89 + 2572416961*uk_9 + 22880*uk_90 + 233090*uk_91 + 321750*uk_92 + 5720*uk_93 + 880*uk_94 + 3520*uk_95 + 35860*uk_96 + 49500*uk_97 + 880*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 145200*uk_100 + 198000*uk_101 + 22880*uk_102 + 1497375*uk_103 + 2041875*uk_104 + 235950*uk_105 + 2784375*uk_106 + 321750*uk_107 + 37180*uk_108 + 262144*uk_109 + 3246016*uk_11 + 106496*uk_110 + 65536*uk_111 + 675840*uk_112 + 921600*uk_113 + 106496*uk_114 + 43264*uk_115 + 26624*uk_116 + 274560*uk_117 + 374400*uk_118 + 43264*uk_119 + 1318694*uk_12 + 16384*uk_120 + 168960*uk_121 + 230400*uk_122 + 26624*uk_123 + 1742400*uk_124 + 2376000*uk_125 + 274560*uk_126 + 3240000*uk_127 + 374400*uk_128 + 43264*uk_129 + 811504*uk_13 + 17576*uk_130 + 10816*uk_131 + 111540*uk_132 + 152100*uk_133 + 17576*uk_134 + 6656*uk_135 + 68640*uk_136 + 93600*uk_137 + 10816*uk_138 + 707850*uk_139 + 8368635*uk_14 + 965250*uk_140 + 111540*uk_141 + 1316250*uk_142 + 152100*uk_143 + 17576*uk_144 + 4096*uk_145 + 42240*uk_146 + 57600*uk_147 + 6656*uk_148 + 435600*uk_149 + 11411775*uk_15 + 594000*uk_150 + 68640*uk_151 + 810000*uk_152 + 93600*uk_153 + 10816*uk_154 + 4492125*uk_155 + 6125625*uk_156 + 707850*uk_157 + 8353125*uk_158 + 965250*uk_159 + 1318694*uk_16 + 111540*uk_160 + 11390625*uk_161 + 1316250*uk_162 + 152100*uk_163 + 17576*uk_164 + 3025*uk_17 + 3520*uk_18 + 1430*uk_19 + 55*uk_2 + 880*uk_20 + 9075*uk_21 + 12375*uk_22 + 1430*uk_23 + 4096*uk_24 + 1664*uk_25 + 1024*uk_26 + 10560*uk_27 + 14400*uk_28 + 1664*uk_29 + 64*uk_3 + 676*uk_30 + 416*uk_31 + 4290*uk_32 + 5850*uk_33 + 676*uk_34 + 256*uk_35 + 2640*uk_36 + 3600*uk_37 + 416*uk_38 + 27225*uk_39 + 26*uk_4 + 37125*uk_40 + 4290*uk_41 + 50625*uk_42 + 5850*uk_43 + 676*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 164634685504*uk_47 + 66882840986*uk_48 + 41158671376*uk_49 + 16*uk_5 + 424448798565*uk_50 + 578793816225*uk_51 + 66882840986*uk_52 + 153424975*uk_53 + 178530880*uk_54 + 72528170*uk_55 + 44632720*uk_56 + 460274925*uk_57 + 627647625*uk_58 + 72528170*uk_59 + 165*uk_6 + 207745024*uk_60 + 84396416*uk_61 + 51936256*uk_62 + 535592640*uk_63 + 730353600*uk_64 + 84396416*uk_65 + 34286044*uk_66 + 21099104*uk_67 + 217584510*uk_68 + 296706150*uk_69 + 225*uk_7 + 34286044*uk_70 + 12984064*uk_71 + 133898160*uk_72 + 182588400*uk_73 + 21099104*uk_74 + 1380824775*uk_75 + 1882942875*uk_76 + 217584510*uk_77 + 2567649375*uk_78 + 296706150*uk_79 + 26*uk_8 + 34286044*uk_80 + 166375*uk_81 + 193600*uk_82 + 78650*uk_83 + 48400*uk_84 + 499125*uk_85 + 680625*uk_86 + 78650*uk_87 + 225280*uk_88 + 91520*uk_89 + 2572416961*uk_9 + 56320*uk_90 + 580800*uk_91 + 792000*uk_92 + 91520*uk_93 + 37180*uk_94 + 22880*uk_95 + 235950*uk_96 + 321750*uk_97 + 37180*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 146960*uk_100 + 198000*uk_101 + 56320*uk_102 + 1533895*uk_103 + 2066625*uk_104 + 587840*uk_105 + 2784375*uk_106 + 792000*uk_107 + 225280*uk_108 + 1643032*uk_109 + 5984842*uk_11 + 891136*uk_110 + 222784*uk_111 + 2325308*uk_112 + 3132900*uk_113 + 891136*uk_114 + 483328*uk_115 + 120832*uk_116 + 1261184*uk_117 + 1699200*uk_118 + 483328*uk_119 + 3246016*uk_12 + 30208*uk_120 + 315296*uk_121 + 424800*uk_122 + 120832*uk_123 + 3290902*uk_124 + 4433850*uk_125 + 1261184*uk_126 + 5973750*uk_127 + 1699200*uk_128 + 483328*uk_129 + 811504*uk_13 + 262144*uk_130 + 65536*uk_131 + 684032*uk_132 + 921600*uk_133 + 262144*uk_134 + 16384*uk_135 + 171008*uk_136 + 230400*uk_137 + 65536*uk_138 + 1784896*uk_139 + 8470073*uk_14 + 2404800*uk_140 + 684032*uk_141 + 3240000*uk_142 + 921600*uk_143 + 262144*uk_144 + 4096*uk_145 + 42752*uk_146 + 57600*uk_147 + 16384*uk_148 + 446224*uk_149 + 11411775*uk_15 + 601200*uk_150 + 171008*uk_151 + 810000*uk_152 + 230400*uk_153 + 65536*uk_154 + 4657463*uk_155 + 6275025*uk_156 + 1784896*uk_157 + 8454375*uk_158 + 2404800*uk_159 + 3246016*uk_16 + 684032*uk_160 + 11390625*uk_161 + 3240000*uk_162 + 921600*uk_163 + 262144*uk_164 + 3025*uk_17 + 6490*uk_18 + 3520*uk_19 + 55*uk_2 + 880*uk_20 + 9185*uk_21 + 12375*uk_22 + 3520*uk_23 + 13924*uk_24 + 7552*uk_25 + 1888*uk_26 + 19706*uk_27 + 26550*uk_28 + 7552*uk_29 + 118*uk_3 + 4096*uk_30 + 1024*uk_31 + 10688*uk_32 + 14400*uk_33 + 4096*uk_34 + 256*uk_35 + 2672*uk_36 + 3600*uk_37 + 1024*uk_38 + 27889*uk_39 + 64*uk_4 + 37575*uk_40 + 10688*uk_41 + 50625*uk_42 + 14400*uk_43 + 4096*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 303545201398*uk_47 + 164634685504*uk_48 + 41158671376*uk_49 + 16*uk_5 + 429593632487*uk_50 + 578793816225*uk_51 + 164634685504*uk_52 + 153424975*uk_53 + 329166310*uk_54 + 178530880*uk_55 + 44632720*uk_56 + 465854015*uk_57 + 627647625*uk_58 + 178530880*uk_59 + 167*uk_6 + 706211356*uk_60 + 383029888*uk_61 + 95757472*uk_62 + 999468614*uk_63 + 1346589450*uk_64 + 383029888*uk_65 + 207745024*uk_66 + 51936256*uk_67 + 542084672*uk_68 + 730353600*uk_69 + 225*uk_7 + 207745024*uk_70 + 12984064*uk_71 + 135521168*uk_72 + 182588400*uk_73 + 51936256*uk_74 + 1414502191*uk_75 + 1905766425*uk_76 + 542084672*uk_77 + 2567649375*uk_78 + 730353600*uk_79 + 64*uk_8 + 207745024*uk_80 + 166375*uk_81 + 356950*uk_82 + 193600*uk_83 + 48400*uk_84 + 505175*uk_85 + 680625*uk_86 + 193600*uk_87 + 765820*uk_88 + 415360*uk_89 + 2572416961*uk_9 + 103840*uk_90 + 1083830*uk_91 + 1460250*uk_92 + 415360*uk_93 + 225280*uk_94 + 56320*uk_95 + 587840*uk_96 + 792000*uk_97 + 225280*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 111540*uk_100 + 148500*uk_101 + 77880*uk_102 + 1570855*uk_103 + 2091375*uk_104 + 1096810*uk_105 + 2784375*uk_106 + 1460250*uk_107 + 765820*uk_108 + 6859*uk_109 + 963661*uk_11 + 42598*uk_110 + 4332*uk_111 + 61009*uk_112 + 81225*uk_113 + 42598*uk_114 + 264556*uk_115 + 26904*uk_116 + 378898*uk_117 + 504450*uk_118 + 264556*uk_119 + 5984842*uk_12 + 2736*uk_120 + 38532*uk_121 + 51300*uk_122 + 26904*uk_123 + 542659*uk_124 + 722475*uk_125 + 378898*uk_126 + 961875*uk_127 + 504450*uk_128 + 264556*uk_129 + 608628*uk_13 + 1643032*uk_130 + 167088*uk_131 + 2353156*uk_132 + 3132900*uk_133 + 1643032*uk_134 + 16992*uk_135 + 239304*uk_136 + 318600*uk_137 + 167088*uk_138 + 3370198*uk_139 + 8571511*uk_14 + 4486950*uk_140 + 2353156*uk_141 + 5973750*uk_142 + 3132900*uk_143 + 1643032*uk_144 + 1728*uk_145 + 24336*uk_146 + 32400*uk_147 + 16992*uk_148 + 342732*uk_149 + 11411775*uk_15 + 456300*uk_150 + 239304*uk_151 + 607500*uk_152 + 318600*uk_153 + 167088*uk_154 + 4826809*uk_155 + 6426225*uk_156 + 3370198*uk_157 + 8555625*uk_158 + 4486950*uk_159 + 5984842*uk_16 + 2353156*uk_160 + 11390625*uk_161 + 5973750*uk_162 + 3132900*uk_163 + 1643032*uk_164 + 3025*uk_17 + 1045*uk_18 + 6490*uk_19 + 55*uk_2 + 660*uk_20 + 9295*uk_21 + 12375*uk_22 + 6490*uk_23 + 361*uk_24 + 2242*uk_25 + 228*uk_26 + 3211*uk_27 + 4275*uk_28 + 2242*uk_29 + 19*uk_3 + 13924*uk_30 + 1416*uk_31 + 19942*uk_32 + 26550*uk_33 + 13924*uk_34 + 144*uk_35 + 2028*uk_36 + 2700*uk_37 + 1416*uk_38 + 28561*uk_39 + 118*uk_4 + 38025*uk_40 + 19942*uk_41 + 50625*uk_42 + 26550*uk_43 + 13924*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 48875922259*uk_47 + 303545201398*uk_48 + 30869003532*uk_49 + 12*uk_5 + 434738466409*uk_50 + 578793816225*uk_51 + 303545201398*uk_52 + 153424975*uk_53 + 53001355*uk_54 + 329166310*uk_55 + 33474540*uk_56 + 471433105*uk_57 + 627647625*uk_58 + 329166310*uk_59 + 169*uk_6 + 18309559*uk_60 + 113711998*uk_61 + 11563932*uk_62 + 162858709*uk_63 + 216823725*uk_64 + 113711998*uk_65 + 706211356*uk_66 + 71818104*uk_67 + 1011438298*uk_68 + 1346589450*uk_69 + 225*uk_7 + 706211356*uk_70 + 7303536*uk_71 + 102858132*uk_72 + 136941300*uk_73 + 71818104*uk_74 + 1448585359*uk_75 + 1928589975*uk_76 + 1011438298*uk_77 + 2567649375*uk_78 + 1346589450*uk_79 + 118*uk_8 + 706211356*uk_80 + 166375*uk_81 + 57475*uk_82 + 356950*uk_83 + 36300*uk_84 + 511225*uk_85 + 680625*uk_86 + 356950*uk_87 + 19855*uk_88 + 123310*uk_89 + 2572416961*uk_9 + 12540*uk_90 + 176605*uk_91 + 235125*uk_92 + 123310*uk_93 + 765820*uk_94 + 77880*uk_95 + 1096810*uk_96 + 1460250*uk_97 + 765820*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 150480*uk_100 + 198000*uk_101 + 16720*uk_102 + 1608255*uk_103 + 2116125*uk_104 + 178695*uk_105 + 2784375*uk_106 + 235125*uk_107 + 19855*uk_108 + 1092727*uk_109 + 5224057*uk_11 + 201571*uk_110 + 169744*uk_111 + 1814139*uk_112 + 2387025*uk_113 + 201571*uk_114 + 37183*uk_115 + 31312*uk_116 + 334647*uk_117 + 440325*uk_118 + 37183*uk_119 + 963661*uk_12 + 26368*uk_120 + 281808*uk_121 + 370800*uk_122 + 31312*uk_123 + 3011823*uk_124 + 3962925*uk_125 + 334647*uk_126 + 5214375*uk_127 + 440325*uk_128 + 37183*uk_129 + 811504*uk_13 + 6859*uk_130 + 5776*uk_131 + 61731*uk_132 + 81225*uk_133 + 6859*uk_134 + 4864*uk_135 + 51984*uk_136 + 68400*uk_137 + 5776*uk_138 + 555579*uk_139 + 8672949*uk_14 + 731025*uk_140 + 61731*uk_141 + 961875*uk_142 + 81225*uk_143 + 6859*uk_144 + 4096*uk_145 + 43776*uk_146 + 57600*uk_147 + 4864*uk_148 + 467856*uk_149 + 11411775*uk_15 + 615600*uk_150 + 51984*uk_151 + 810000*uk_152 + 68400*uk_153 + 5776*uk_154 + 5000211*uk_155 + 6579225*uk_156 + 555579*uk_157 + 8656875*uk_158 + 731025*uk_159 + 963661*uk_16 + 61731*uk_160 + 11390625*uk_161 + 961875*uk_162 + 81225*uk_163 + 6859*uk_164 + 3025*uk_17 + 5665*uk_18 + 1045*uk_19 + 55*uk_2 + 880*uk_20 + 9405*uk_21 + 12375*uk_22 + 1045*uk_23 + 10609*uk_24 + 1957*uk_25 + 1648*uk_26 + 17613*uk_27 + 23175*uk_28 + 1957*uk_29 + 103*uk_3 + 361*uk_30 + 304*uk_31 + 3249*uk_32 + 4275*uk_33 + 361*uk_34 + 256*uk_35 + 2736*uk_36 + 3600*uk_37 + 304*uk_38 + 29241*uk_39 + 19*uk_4 + 38475*uk_40 + 3249*uk_41 + 50625*uk_42 + 4275*uk_43 + 361*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 264958946983*uk_47 + 48875922259*uk_48 + 41158671376*uk_49 + 16*uk_5 + 439883300331*uk_50 + 578793816225*uk_51 + 48875922259*uk_52 + 153424975*uk_53 + 287323135*uk_54 + 53001355*uk_55 + 44632720*uk_56 + 477012195*uk_57 + 627647625*uk_58 + 53001355*uk_59 + 171*uk_6 + 538077871*uk_60 + 99257083*uk_61 + 83584912*uk_62 + 893313747*uk_63 + 1175412825*uk_64 + 99257083*uk_65 + 18309559*uk_66 + 15418576*uk_67 + 164786031*uk_68 + 216823725*uk_69 + 225*uk_7 + 18309559*uk_70 + 12984064*uk_71 + 138767184*uk_72 + 182588400*uk_73 + 15418576*uk_74 + 1483074279*uk_75 + 1951413525*uk_76 + 164786031*uk_77 + 2567649375*uk_78 + 216823725*uk_79 + 19*uk_8 + 18309559*uk_80 + 166375*uk_81 + 311575*uk_82 + 57475*uk_83 + 48400*uk_84 + 517275*uk_85 + 680625*uk_86 + 57475*uk_87 + 583495*uk_88 + 107635*uk_89 + 2572416961*uk_9 + 90640*uk_90 + 968715*uk_91 + 1274625*uk_92 + 107635*uk_93 + 19855*uk_94 + 16720*uk_95 + 178695*uk_96 + 235125*uk_97 + 19855*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 114180*uk_100 + 148500*uk_101 + 67980*uk_102 + 1646095*uk_103 + 2140875*uk_104 + 980045*uk_105 + 2784375*uk_106 + 1274625*uk_107 + 583495*uk_108 + 27000*uk_109 + 1521570*uk_11 + 92700*uk_110 + 10800*uk_111 + 155700*uk_112 + 202500*uk_113 + 92700*uk_114 + 318270*uk_115 + 37080*uk_116 + 534570*uk_117 + 695250*uk_118 + 318270*uk_119 + 5224057*uk_12 + 4320*uk_120 + 62280*uk_121 + 81000*uk_122 + 37080*uk_123 + 897870*uk_124 + 1167750*uk_125 + 534570*uk_126 + 1518750*uk_127 + 695250*uk_128 + 318270*uk_129 + 608628*uk_13 + 1092727*uk_130 + 127308*uk_131 + 1835357*uk_132 + 2387025*uk_133 + 1092727*uk_134 + 14832*uk_135 + 213828*uk_136 + 278100*uk_137 + 127308*uk_138 + 3082687*uk_139 + 8774387*uk_14 + 4009275*uk_140 + 1835357*uk_141 + 5214375*uk_142 + 2387025*uk_143 + 1092727*uk_144 + 1728*uk_145 + 24912*uk_146 + 32400*uk_147 + 14832*uk_148 + 359148*uk_149 + 11411775*uk_15 + 467100*uk_150 + 213828*uk_151 + 607500*uk_152 + 278100*uk_153 + 127308*uk_154 + 5177717*uk_155 + 6734025*uk_156 + 3082687*uk_157 + 8758125*uk_158 + 4009275*uk_159 + 5224057*uk_16 + 1835357*uk_160 + 11390625*uk_161 + 5214375*uk_162 + 2387025*uk_163 + 1092727*uk_164 + 3025*uk_17 + 1650*uk_18 + 5665*uk_19 + 55*uk_2 + 660*uk_20 + 9515*uk_21 + 12375*uk_22 + 5665*uk_23 + 900*uk_24 + 3090*uk_25 + 360*uk_26 + 5190*uk_27 + 6750*uk_28 + 3090*uk_29 + 30*uk_3 + 10609*uk_30 + 1236*uk_31 + 17819*uk_32 + 23175*uk_33 + 10609*uk_34 + 144*uk_35 + 2076*uk_36 + 2700*uk_37 + 1236*uk_38 + 29929*uk_39 + 103*uk_4 + 38925*uk_40 + 17819*uk_41 + 50625*uk_42 + 23175*uk_43 + 10609*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 77172508830*uk_47 + 264958946983*uk_48 + 30869003532*uk_49 + 12*uk_5 + 445028134253*uk_50 + 578793816225*uk_51 + 264958946983*uk_52 + 153424975*uk_53 + 83686350*uk_54 + 287323135*uk_55 + 33474540*uk_56 + 482591285*uk_57 + 627647625*uk_58 + 287323135*uk_59 + 173*uk_6 + 45647100*uk_60 + 156721710*uk_61 + 18258840*uk_62 + 263231610*uk_63 + 342353250*uk_64 + 156721710*uk_65 + 538077871*uk_66 + 62688684*uk_67 + 903761861*uk_68 + 1175412825*uk_69 + 225*uk_7 + 538077871*uk_70 + 7303536*uk_71 + 105292644*uk_72 + 136941300*uk_73 + 62688684*uk_74 + 1517968951*uk_75 + 1974237075*uk_76 + 903761861*uk_77 + 2567649375*uk_78 + 1175412825*uk_79 + 103*uk_8 + 538077871*uk_80 + 166375*uk_81 + 90750*uk_82 + 311575*uk_83 + 36300*uk_84 + 523325*uk_85 + 680625*uk_86 + 311575*uk_87 + 49500*uk_88 + 169950*uk_89 + 2572416961*uk_9 + 19800*uk_90 + 285450*uk_91 + 371250*uk_92 + 169950*uk_93 + 583495*uk_94 + 67980*uk_95 + 980045*uk_96 + 1274625*uk_97 + 583495*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 154000*uk_100 + 198000*uk_101 + 26400*uk_102 + 1684375*uk_103 + 2165625*uk_104 + 288750*uk_105 + 2784375*uk_106 + 371250*uk_107 + 49500*uk_108 + 2985984*uk_109 + 7303536*uk_11 + 622080*uk_110 + 331776*uk_111 + 3628800*uk_112 + 4665600*uk_113 + 622080*uk_114 + 129600*uk_115 + 69120*uk_116 + 756000*uk_117 + 972000*uk_118 + 129600*uk_119 + 1521570*uk_12 + 36864*uk_120 + 403200*uk_121 + 518400*uk_122 + 69120*uk_123 + 4410000*uk_124 + 5670000*uk_125 + 756000*uk_126 + 7290000*uk_127 + 972000*uk_128 + 129600*uk_129 + 811504*uk_13 + 27000*uk_130 + 14400*uk_131 + 157500*uk_132 + 202500*uk_133 + 27000*uk_134 + 7680*uk_135 + 84000*uk_136 + 108000*uk_137 + 14400*uk_138 + 918750*uk_139 + 8875825*uk_14 + 1181250*uk_140 + 157500*uk_141 + 1518750*uk_142 + 202500*uk_143 + 27000*uk_144 + 4096*uk_145 + 44800*uk_146 + 57600*uk_147 + 7680*uk_148 + 490000*uk_149 + 11411775*uk_15 + 630000*uk_150 + 84000*uk_151 + 810000*uk_152 + 108000*uk_153 + 14400*uk_154 + 5359375*uk_155 + 6890625*uk_156 + 918750*uk_157 + 8859375*uk_158 + 1181250*uk_159 + 1521570*uk_16 + 157500*uk_160 + 11390625*uk_161 + 1518750*uk_162 + 202500*uk_163 + 27000*uk_164 + 3025*uk_17 + 7920*uk_18 + 1650*uk_19 + 55*uk_2 + 880*uk_20 + 9625*uk_21 + 12375*uk_22 + 1650*uk_23 + 20736*uk_24 + 4320*uk_25 + 2304*uk_26 + 25200*uk_27 + 32400*uk_28 + 4320*uk_29 + 144*uk_3 + 900*uk_30 + 480*uk_31 + 5250*uk_32 + 6750*uk_33 + 900*uk_34 + 256*uk_35 + 2800*uk_36 + 3600*uk_37 + 480*uk_38 + 30625*uk_39 + 30*uk_4 + 39375*uk_40 + 5250*uk_41 + 50625*uk_42 + 6750*uk_43 + 900*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 370428042384*uk_47 + 77172508830*uk_48 + 41158671376*uk_49 + 16*uk_5 + 450172968175*uk_50 + 578793816225*uk_51 + 77172508830*uk_52 + 153424975*uk_53 + 401694480*uk_54 + 83686350*uk_55 + 44632720*uk_56 + 488170375*uk_57 + 627647625*uk_58 + 83686350*uk_59 + 175*uk_6 + 1051709184*uk_60 + 219106080*uk_61 + 116856576*uk_62 + 1278118800*uk_63 + 1643295600*uk_64 + 219106080*uk_65 + 45647100*uk_66 + 24345120*uk_67 + 266274750*uk_68 + 342353250*uk_69 + 225*uk_7 + 45647100*uk_70 + 12984064*uk_71 + 142013200*uk_72 + 182588400*uk_73 + 24345120*uk_74 + 1553269375*uk_75 + 1997060625*uk_76 + 266274750*uk_77 + 2567649375*uk_78 + 342353250*uk_79 + 30*uk_8 + 45647100*uk_80 + 166375*uk_81 + 435600*uk_82 + 90750*uk_83 + 48400*uk_84 + 529375*uk_85 + 680625*uk_86 + 90750*uk_87 + 1140480*uk_88 + 237600*uk_89 + 2572416961*uk_9 + 126720*uk_90 + 1386000*uk_91 + 1782000*uk_92 + 237600*uk_93 + 49500*uk_94 + 26400*uk_95 + 288750*uk_96 + 371250*uk_97 + 49500*uk_98 + 14080*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 116820*uk_100 + 148500*uk_101 + 95040*uk_102 + 1723095*uk_103 + 2190375*uk_104 + 1401840*uk_105 + 2784375*uk_106 + 1782000*uk_107 + 1140480*uk_108 + 912673*uk_109 + 4919743*uk_11 + 1354896*uk_110 + 112908*uk_111 + 1665393*uk_112 + 2117025*uk_113 + 1354896*uk_114 + 2011392*uk_115 + 167616*uk_116 + 2472336*uk_117 + 3142800*uk_118 + 2011392*uk_119 + 7303536*uk_12 + 13968*uk_120 + 206028*uk_121 + 261900*uk_122 + 167616*uk_123 + 3038913*uk_124 + 3863025*uk_125 + 2472336*uk_126 + 4910625*uk_127 + 3142800*uk_128 + 2011392*uk_129 + 608628*uk_13 + 2985984*uk_130 + 248832*uk_131 + 3670272*uk_132 + 4665600*uk_133 + 2985984*uk_134 + 20736*uk_135 + 305856*uk_136 + 388800*uk_137 + 248832*uk_138 + 4511376*uk_139 + 8977263*uk_14 + 5734800*uk_140 + 3670272*uk_141 + 7290000*uk_142 + 4665600*uk_143 + 2985984*uk_144 + 1728*uk_145 + 25488*uk_146 + 32400*uk_147 + 20736*uk_148 + 375948*uk_149 + 11411775*uk_15 + 477900*uk_150 + 305856*uk_151 + 607500*uk_152 + 388800*uk_153 + 248832*uk_154 + 5545233*uk_155 + 7049025*uk_156 + 4511376*uk_157 + 8960625*uk_158 + 5734800*uk_159 + 7303536*uk_16 + 3670272*uk_160 + 11390625*uk_161 + 7290000*uk_162 + 4665600*uk_163 + 2985984*uk_164 + 3025*uk_17 + 5335*uk_18 + 7920*uk_19 + 55*uk_2 + 660*uk_20 + 9735*uk_21 + 12375*uk_22 + 7920*uk_23 + 9409*uk_24 + 13968*uk_25 + 1164*uk_26 + 17169*uk_27 + 21825*uk_28 + 13968*uk_29 + 97*uk_3 + 20736*uk_30 + 1728*uk_31 + 25488*uk_32 + 32400*uk_33 + 20736*uk_34 + 144*uk_35 + 2124*uk_36 + 2700*uk_37 + 1728*uk_38 + 31329*uk_39 + 144*uk_4 + 39825*uk_40 + 25488*uk_41 + 50625*uk_42 + 32400*uk_43 + 20736*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 249524445217*uk_47 + 370428042384*uk_48 + 30869003532*uk_49 + 12*uk_5 + 455317802097*uk_50 + 578793816225*uk_51 + 370428042384*uk_52 + 153424975*uk_53 + 270585865*uk_54 + 401694480*uk_55 + 33474540*uk_56 + 493749465*uk_57 + 627647625*uk_58 + 401694480*uk_59 + 177*uk_6 + 477215071*uk_60 + 708442992*uk_61 + 59036916*uk_62 + 870794511*uk_63 + 1106942175*uk_64 + 708442992*uk_65 + 1051709184*uk_66 + 87642432*uk_67 + 1292725872*uk_68 + 1643295600*uk_69 + 225*uk_7 + 1051709184*uk_70 + 7303536*uk_71 + 107727156*uk_72 + 136941300*uk_73 + 87642432*uk_74 + 1588975551*uk_75 + 2019884175*uk_76 + 1292725872*uk_77 + 2567649375*uk_78 + 1643295600*uk_79 + 144*uk_8 + 1051709184*uk_80 + 166375*uk_81 + 293425*uk_82 + 435600*uk_83 + 36300*uk_84 + 535425*uk_85 + 680625*uk_86 + 435600*uk_87 + 517495*uk_88 + 768240*uk_89 + 2572416961*uk_9 + 64020*uk_90 + 944295*uk_91 + 1200375*uk_92 + 768240*uk_93 + 1140480*uk_94 + 95040*uk_95 + 1401840*uk_96 + 1782000*uk_97 + 1140480*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 118140*uk_100 + 148500*uk_101 + 64020*uk_102 + 1762255*uk_103 + 2215125*uk_104 + 954965*uk_105 + 2784375*uk_106 + 1200375*uk_107 + 517495*uk_108 + 238328*uk_109 + 3144578*uk_11 + 372868*uk_110 + 46128*uk_111 + 688076*uk_112 + 864900*uk_113 + 372868*uk_114 + 583358*uk_115 + 72168*uk_116 + 1076506*uk_117 + 1353150*uk_118 + 583358*uk_119 + 4919743*uk_12 + 8928*uk_120 + 133176*uk_121 + 167400*uk_122 + 72168*uk_123 + 1986542*uk_124 + 2497050*uk_125 + 1076506*uk_126 + 3138750*uk_127 + 1353150*uk_128 + 583358*uk_129 + 608628*uk_13 + 912673*uk_130 + 112908*uk_131 + 1684211*uk_132 + 2117025*uk_133 + 912673*uk_134 + 13968*uk_135 + 208356*uk_136 + 261900*uk_137 + 112908*uk_138 + 3107977*uk_139 + 9078701*uk_14 + 3906675*uk_140 + 1684211*uk_141 + 4910625*uk_142 + 2117025*uk_143 + 912673*uk_144 + 1728*uk_145 + 25776*uk_146 + 32400*uk_147 + 13968*uk_148 + 384492*uk_149 + 11411775*uk_15 + 483300*uk_150 + 208356*uk_151 + 607500*uk_152 + 261900*uk_153 + 112908*uk_154 + 5735339*uk_155 + 7209225*uk_156 + 3107977*uk_157 + 9061875*uk_158 + 3906675*uk_159 + 4919743*uk_16 + 1684211*uk_160 + 11390625*uk_161 + 4910625*uk_162 + 2117025*uk_163 + 912673*uk_164 + 3025*uk_17 + 3410*uk_18 + 5335*uk_19 + 55*uk_2 + 660*uk_20 + 9845*uk_21 + 12375*uk_22 + 5335*uk_23 + 3844*uk_24 + 6014*uk_25 + 744*uk_26 + 11098*uk_27 + 13950*uk_28 + 6014*uk_29 + 62*uk_3 + 9409*uk_30 + 1164*uk_31 + 17363*uk_32 + 21825*uk_33 + 9409*uk_34 + 144*uk_35 + 2148*uk_36 + 2700*uk_37 + 1164*uk_38 + 32041*uk_39 + 97*uk_4 + 40275*uk_40 + 17363*uk_41 + 50625*uk_42 + 21825*uk_43 + 9409*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 159489851582*uk_47 + 249524445217*uk_48 + 30869003532*uk_49 + 12*uk_5 + 460462636019*uk_50 + 578793816225*uk_51 + 249524445217*uk_52 + 153424975*uk_53 + 172951790*uk_54 + 270585865*uk_55 + 33474540*uk_56 + 499328555*uk_57 + 627647625*uk_58 + 270585865*uk_59 + 179*uk_6 + 194963836*uk_60 + 305024066*uk_61 + 37734936*uk_62 + 562879462*uk_63 + 707530050*uk_64 + 305024066*uk_65 + 477215071*uk_66 + 59036916*uk_67 + 880633997*uk_68 + 1106942175*uk_69 + 225*uk_7 + 477215071*uk_70 + 7303536*uk_71 + 108944412*uk_72 + 136941300*uk_73 + 59036916*uk_74 + 1625087479*uk_75 + 2042707725*uk_76 + 880633997*uk_77 + 2567649375*uk_78 + 1106942175*uk_79 + 97*uk_8 + 477215071*uk_80 + 166375*uk_81 + 187550*uk_82 + 293425*uk_83 + 36300*uk_84 + 541475*uk_85 + 680625*uk_86 + 293425*uk_87 + 211420*uk_88 + 330770*uk_89 + 2572416961*uk_9 + 40920*uk_90 + 610390*uk_91 + 767250*uk_92 + 330770*uk_93 + 517495*uk_94 + 64020*uk_95 + 954965*uk_96 + 1200375*uk_97 + 517495*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 119460*uk_100 + 148500*uk_101 + 40920*uk_102 + 1801855*uk_103 + 2239875*uk_104 + 617210*uk_105 + 2784375*uk_106 + 767250*uk_107 + 211420*uk_108 + 59319*uk_109 + 1978041*uk_11 + 94302*uk_110 + 18252*uk_111 + 275301*uk_112 + 342225*uk_113 + 94302*uk_114 + 149916*uk_115 + 29016*uk_116 + 437658*uk_117 + 544050*uk_118 + 149916*uk_119 + 3144578*uk_12 + 5616*uk_120 + 84708*uk_121 + 105300*uk_122 + 29016*uk_123 + 1277679*uk_124 + 1588275*uk_125 + 437658*uk_126 + 1974375*uk_127 + 544050*uk_128 + 149916*uk_129 + 608628*uk_13 + 238328*uk_130 + 46128*uk_131 + 695764*uk_132 + 864900*uk_133 + 238328*uk_134 + 8928*uk_135 + 134664*uk_136 + 167400*uk_137 + 46128*uk_138 + 2031182*uk_139 + 9180139*uk_14 + 2524950*uk_140 + 695764*uk_141 + 3138750*uk_142 + 864900*uk_143 + 238328*uk_144 + 1728*uk_145 + 26064*uk_146 + 32400*uk_147 + 8928*uk_148 + 393132*uk_149 + 11411775*uk_15 + 488700*uk_150 + 134664*uk_151 + 607500*uk_152 + 167400*uk_153 + 46128*uk_154 + 5929741*uk_155 + 7371225*uk_156 + 2031182*uk_157 + 9163125*uk_158 + 2524950*uk_159 + 3144578*uk_16 + 695764*uk_160 + 11390625*uk_161 + 3138750*uk_162 + 864900*uk_163 + 238328*uk_164 + 3025*uk_17 + 2145*uk_18 + 3410*uk_19 + 55*uk_2 + 660*uk_20 + 9955*uk_21 + 12375*uk_22 + 3410*uk_23 + 1521*uk_24 + 2418*uk_25 + 468*uk_26 + 7059*uk_27 + 8775*uk_28 + 2418*uk_29 + 39*uk_3 + 3844*uk_30 + 744*uk_31 + 11222*uk_32 + 13950*uk_33 + 3844*uk_34 + 144*uk_35 + 2172*uk_36 + 2700*uk_37 + 744*uk_38 + 32761*uk_39 + 62*uk_4 + 40725*uk_40 + 11222*uk_41 + 50625*uk_42 + 13950*uk_43 + 3844*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 100324261479*uk_47 + 159489851582*uk_48 + 30869003532*uk_49 + 12*uk_5 + 465607469941*uk_50 + 578793816225*uk_51 + 159489851582*uk_52 + 153424975*uk_53 + 108792255*uk_54 + 172951790*uk_55 + 33474540*uk_56 + 504907645*uk_57 + 627647625*uk_58 + 172951790*uk_59 + 181*uk_6 + 77143599*uk_60 + 122638542*uk_61 + 23736492*uk_62 + 358025421*uk_63 + 445059225*uk_64 + 122638542*uk_65 + 194963836*uk_66 + 37734936*uk_67 + 569168618*uk_68 + 707530050*uk_69 + 225*uk_7 + 194963836*uk_70 + 7303536*uk_71 + 110161668*uk_72 + 136941300*uk_73 + 37734936*uk_74 + 1661605159*uk_75 + 2065531275*uk_76 + 569168618*uk_77 + 2567649375*uk_78 + 707530050*uk_79 + 62*uk_8 + 194963836*uk_80 + 166375*uk_81 + 117975*uk_82 + 187550*uk_83 + 36300*uk_84 + 547525*uk_85 + 680625*uk_86 + 187550*uk_87 + 83655*uk_88 + 132990*uk_89 + 2572416961*uk_9 + 25740*uk_90 + 388245*uk_91 + 482625*uk_92 + 132990*uk_93 + 211420*uk_94 + 40920*uk_95 + 617210*uk_96 + 767250*uk_97 + 211420*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 120780*uk_100 + 148500*uk_101 + 25740*uk_102 + 1841895*uk_103 + 2264625*uk_104 + 392535*uk_105 + 2784375*uk_106 + 482625*uk_107 + 83655*uk_108 + 21952*uk_109 + 1420132*uk_11 + 30576*uk_110 + 9408*uk_111 + 143472*uk_112 + 176400*uk_113 + 30576*uk_114 + 42588*uk_115 + 13104*uk_116 + 199836*uk_117 + 245700*uk_118 + 42588*uk_119 + 1978041*uk_12 + 4032*uk_120 + 61488*uk_121 + 75600*uk_122 + 13104*uk_123 + 937692*uk_124 + 1152900*uk_125 + 199836*uk_126 + 1417500*uk_127 + 245700*uk_128 + 42588*uk_129 + 608628*uk_13 + 59319*uk_130 + 18252*uk_131 + 278343*uk_132 + 342225*uk_133 + 59319*uk_134 + 5616*uk_135 + 85644*uk_136 + 105300*uk_137 + 18252*uk_138 + 1306071*uk_139 + 9281577*uk_14 + 1605825*uk_140 + 278343*uk_141 + 1974375*uk_142 + 342225*uk_143 + 59319*uk_144 + 1728*uk_145 + 26352*uk_146 + 32400*uk_147 + 5616*uk_148 + 401868*uk_149 + 11411775*uk_15 + 494100*uk_150 + 85644*uk_151 + 607500*uk_152 + 105300*uk_153 + 18252*uk_154 + 6128487*uk_155 + 7535025*uk_156 + 1306071*uk_157 + 9264375*uk_158 + 1605825*uk_159 + 1978041*uk_16 + 278343*uk_160 + 11390625*uk_161 + 1974375*uk_162 + 342225*uk_163 + 59319*uk_164 + 3025*uk_17 + 1540*uk_18 + 2145*uk_19 + 55*uk_2 + 660*uk_20 + 10065*uk_21 + 12375*uk_22 + 2145*uk_23 + 784*uk_24 + 1092*uk_25 + 336*uk_26 + 5124*uk_27 + 6300*uk_28 + 1092*uk_29 + 28*uk_3 + 1521*uk_30 + 468*uk_31 + 7137*uk_32 + 8775*uk_33 + 1521*uk_34 + 144*uk_35 + 2196*uk_36 + 2700*uk_37 + 468*uk_38 + 33489*uk_39 + 39*uk_4 + 41175*uk_40 + 7137*uk_41 + 50625*uk_42 + 8775*uk_43 + 1521*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 72027674908*uk_47 + 100324261479*uk_48 + 30869003532*uk_49 + 12*uk_5 + 470752303863*uk_50 + 578793816225*uk_51 + 100324261479*uk_52 + 153424975*uk_53 + 78107260*uk_54 + 108792255*uk_55 + 33474540*uk_56 + 510486735*uk_57 + 627647625*uk_58 + 108792255*uk_59 + 183*uk_6 + 39763696*uk_60 + 55385148*uk_61 + 17041584*uk_62 + 259884156*uk_63 + 319529700*uk_64 + 55385148*uk_65 + 77143599*uk_66 + 23736492*uk_67 + 361981503*uk_68 + 445059225*uk_69 + 225*uk_7 + 77143599*uk_70 + 7303536*uk_71 + 111378924*uk_72 + 136941300*uk_73 + 23736492*uk_74 + 1698528591*uk_75 + 2088354825*uk_76 + 361981503*uk_77 + 2567649375*uk_78 + 445059225*uk_79 + 39*uk_8 + 77143599*uk_80 + 166375*uk_81 + 84700*uk_82 + 117975*uk_83 + 36300*uk_84 + 553575*uk_85 + 680625*uk_86 + 117975*uk_87 + 43120*uk_88 + 60060*uk_89 + 2572416961*uk_9 + 18480*uk_90 + 281820*uk_91 + 346500*uk_92 + 60060*uk_93 + 83655*uk_94 + 25740*uk_95 + 392535*uk_96 + 482625*uk_97 + 83655*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 122100*uk_100 + 148500*uk_101 + 18480*uk_102 + 1882375*uk_103 + 2289375*uk_104 + 284900*uk_105 + 2784375*uk_106 + 346500*uk_107 + 43120*uk_108 + 24389*uk_109 + 1470851*uk_11 + 23548*uk_110 + 10092*uk_111 + 155585*uk_112 + 189225*uk_113 + 23548*uk_114 + 22736*uk_115 + 9744*uk_116 + 150220*uk_117 + 182700*uk_118 + 22736*uk_119 + 1420132*uk_12 + 4176*uk_120 + 64380*uk_121 + 78300*uk_122 + 9744*uk_123 + 992525*uk_124 + 1207125*uk_125 + 150220*uk_126 + 1468125*uk_127 + 182700*uk_128 + 22736*uk_129 + 608628*uk_13 + 21952*uk_130 + 9408*uk_131 + 145040*uk_132 + 176400*uk_133 + 21952*uk_134 + 4032*uk_135 + 62160*uk_136 + 75600*uk_137 + 9408*uk_138 + 958300*uk_139 + 9383015*uk_14 + 1165500*uk_140 + 145040*uk_141 + 1417500*uk_142 + 176400*uk_143 + 21952*uk_144 + 1728*uk_145 + 26640*uk_146 + 32400*uk_147 + 4032*uk_148 + 410700*uk_149 + 11411775*uk_15 + 499500*uk_150 + 62160*uk_151 + 607500*uk_152 + 75600*uk_153 + 9408*uk_154 + 6331625*uk_155 + 7700625*uk_156 + 958300*uk_157 + 9365625*uk_158 + 1165500*uk_159 + 1420132*uk_16 + 145040*uk_160 + 11390625*uk_161 + 1417500*uk_162 + 176400*uk_163 + 21952*uk_164 + 3025*uk_17 + 1595*uk_18 + 1540*uk_19 + 55*uk_2 + 660*uk_20 + 10175*uk_21 + 12375*uk_22 + 1540*uk_23 + 841*uk_24 + 812*uk_25 + 348*uk_26 + 5365*uk_27 + 6525*uk_28 + 812*uk_29 + 29*uk_3 + 784*uk_30 + 336*uk_31 + 5180*uk_32 + 6300*uk_33 + 784*uk_34 + 144*uk_35 + 2220*uk_36 + 2700*uk_37 + 336*uk_38 + 34225*uk_39 + 28*uk_4 + 41625*uk_40 + 5180*uk_41 + 50625*uk_42 + 6300*uk_43 + 784*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 74600091869*uk_47 + 72027674908*uk_48 + 30869003532*uk_49 + 12*uk_5 + 475897137785*uk_50 + 578793816225*uk_51 + 72027674908*uk_52 + 153424975*uk_53 + 80896805*uk_54 + 78107260*uk_55 + 33474540*uk_56 + 516065825*uk_57 + 627647625*uk_58 + 78107260*uk_59 + 185*uk_6 + 42654679*uk_60 + 41183828*uk_61 + 17650212*uk_62 + 272107435*uk_63 + 330941475*uk_64 + 41183828*uk_65 + 39763696*uk_66 + 17041584*uk_67 + 262724420*uk_68 + 319529700*uk_69 + 225*uk_7 + 39763696*uk_70 + 7303536*uk_71 + 112596180*uk_72 + 136941300*uk_73 + 17041584*uk_74 + 1735857775*uk_75 + 2111178375*uk_76 + 262724420*uk_77 + 2567649375*uk_78 + 319529700*uk_79 + 28*uk_8 + 39763696*uk_80 + 166375*uk_81 + 87725*uk_82 + 84700*uk_83 + 36300*uk_84 + 559625*uk_85 + 680625*uk_86 + 84700*uk_87 + 46255*uk_88 + 44660*uk_89 + 2572416961*uk_9 + 19140*uk_90 + 295075*uk_91 + 358875*uk_92 + 44660*uk_93 + 43120*uk_94 + 18480*uk_95 + 284900*uk_96 + 346500*uk_97 + 43120*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 123420*uk_100 + 148500*uk_101 + 19140*uk_102 + 1923295*uk_103 + 2314125*uk_104 + 298265*uk_105 + 2784375*uk_106 + 358875*uk_107 + 46255*uk_108 + 74088*uk_109 + 2130198*uk_11 + 51156*uk_110 + 21168*uk_111 + 329868*uk_112 + 396900*uk_113 + 51156*uk_114 + 35322*uk_115 + 14616*uk_116 + 227766*uk_117 + 274050*uk_118 + 35322*uk_119 + 1470851*uk_12 + 6048*uk_120 + 94248*uk_121 + 113400*uk_122 + 14616*uk_123 + 1468698*uk_124 + 1767150*uk_125 + 227766*uk_126 + 2126250*uk_127 + 274050*uk_128 + 35322*uk_129 + 608628*uk_13 + 24389*uk_130 + 10092*uk_131 + 157267*uk_132 + 189225*uk_133 + 24389*uk_134 + 4176*uk_135 + 65076*uk_136 + 78300*uk_137 + 10092*uk_138 + 1014101*uk_139 + 9484453*uk_14 + 1220175*uk_140 + 157267*uk_141 + 1468125*uk_142 + 189225*uk_143 + 24389*uk_144 + 1728*uk_145 + 26928*uk_146 + 32400*uk_147 + 4176*uk_148 + 419628*uk_149 + 11411775*uk_15 + 504900*uk_150 + 65076*uk_151 + 607500*uk_152 + 78300*uk_153 + 10092*uk_154 + 6539203*uk_155 + 7868025*uk_156 + 1014101*uk_157 + 9466875*uk_158 + 1220175*uk_159 + 1470851*uk_16 + 157267*uk_160 + 11390625*uk_161 + 1468125*uk_162 + 189225*uk_163 + 24389*uk_164 + 3025*uk_17 + 2310*uk_18 + 1595*uk_19 + 55*uk_2 + 660*uk_20 + 10285*uk_21 + 12375*uk_22 + 1595*uk_23 + 1764*uk_24 + 1218*uk_25 + 504*uk_26 + 7854*uk_27 + 9450*uk_28 + 1218*uk_29 + 42*uk_3 + 841*uk_30 + 348*uk_31 + 5423*uk_32 + 6525*uk_33 + 841*uk_34 + 144*uk_35 + 2244*uk_36 + 2700*uk_37 + 348*uk_38 + 34969*uk_39 + 29*uk_4 + 42075*uk_40 + 5423*uk_41 + 50625*uk_42 + 6525*uk_43 + 841*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 108041512362*uk_47 + 74600091869*uk_48 + 30869003532*uk_49 + 12*uk_5 + 481041971707*uk_50 + 578793816225*uk_51 + 74600091869*uk_52 + 153424975*uk_53 + 117160890*uk_54 + 80896805*uk_55 + 33474540*uk_56 + 521644915*uk_57 + 627647625*uk_58 + 80896805*uk_59 + 187*uk_6 + 89468316*uk_60 + 61775742*uk_61 + 25562376*uk_62 + 398347026*uk_63 + 479294550*uk_64 + 61775742*uk_65 + 42654679*uk_66 + 17650212*uk_67 + 275049137*uk_68 + 330941475*uk_69 + 225*uk_7 + 42654679*uk_70 + 7303536*uk_71 + 113813436*uk_72 + 136941300*uk_73 + 17650212*uk_74 + 1773592711*uk_75 + 2134001925*uk_76 + 275049137*uk_77 + 2567649375*uk_78 + 330941475*uk_79 + 29*uk_8 + 42654679*uk_80 + 166375*uk_81 + 127050*uk_82 + 87725*uk_83 + 36300*uk_84 + 565675*uk_85 + 680625*uk_86 + 87725*uk_87 + 97020*uk_88 + 66990*uk_89 + 2572416961*uk_9 + 27720*uk_90 + 431970*uk_91 + 519750*uk_92 + 66990*uk_93 + 46255*uk_94 + 19140*uk_95 + 298265*uk_96 + 358875*uk_97 + 46255*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 124740*uk_100 + 148500*uk_101 + 27720*uk_102 + 1964655*uk_103 + 2338875*uk_104 + 436590*uk_105 + 2784375*uk_106 + 519750*uk_107 + 97020*uk_108 + 300763*uk_109 + 3398173*uk_11 + 188538*uk_110 + 53868*uk_111 + 848421*uk_112 + 1010025*uk_113 + 188538*uk_114 + 118188*uk_115 + 33768*uk_116 + 531846*uk_117 + 633150*uk_118 + 118188*uk_119 + 2130198*uk_12 + 9648*uk_120 + 151956*uk_121 + 180900*uk_122 + 33768*uk_123 + 2393307*uk_124 + 2849175*uk_125 + 531846*uk_126 + 3391875*uk_127 + 633150*uk_128 + 118188*uk_129 + 608628*uk_13 + 74088*uk_130 + 21168*uk_131 + 333396*uk_132 + 396900*uk_133 + 74088*uk_134 + 6048*uk_135 + 95256*uk_136 + 113400*uk_137 + 21168*uk_138 + 1500282*uk_139 + 9585891*uk_14 + 1786050*uk_140 + 333396*uk_141 + 2126250*uk_142 + 396900*uk_143 + 74088*uk_144 + 1728*uk_145 + 27216*uk_146 + 32400*uk_147 + 6048*uk_148 + 428652*uk_149 + 11411775*uk_15 + 510300*uk_150 + 95256*uk_151 + 607500*uk_152 + 113400*uk_153 + 21168*uk_154 + 6751269*uk_155 + 8037225*uk_156 + 1500282*uk_157 + 9568125*uk_158 + 1786050*uk_159 + 2130198*uk_16 + 333396*uk_160 + 11390625*uk_161 + 2126250*uk_162 + 396900*uk_163 + 74088*uk_164 + 3025*uk_17 + 3685*uk_18 + 2310*uk_19 + 55*uk_2 + 660*uk_20 + 10395*uk_21 + 12375*uk_22 + 2310*uk_23 + 4489*uk_24 + 2814*uk_25 + 804*uk_26 + 12663*uk_27 + 15075*uk_28 + 2814*uk_29 + 67*uk_3 + 1764*uk_30 + 504*uk_31 + 7938*uk_32 + 9450*uk_33 + 1764*uk_34 + 144*uk_35 + 2268*uk_36 + 2700*uk_37 + 504*uk_38 + 35721*uk_39 + 42*uk_4 + 42525*uk_40 + 7938*uk_41 + 50625*uk_42 + 9450*uk_43 + 1764*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 172351936387*uk_47 + 108041512362*uk_48 + 30869003532*uk_49 + 12*uk_5 + 486186805629*uk_50 + 578793816225*uk_51 + 108041512362*uk_52 + 153424975*uk_53 + 186899515*uk_54 + 117160890*uk_55 + 33474540*uk_56 + 527224005*uk_57 + 627647625*uk_58 + 117160890*uk_59 + 189*uk_6 + 227677591*uk_60 + 142723266*uk_61 + 40778076*uk_62 + 642254697*uk_63 + 764588925*uk_64 + 142723266*uk_65 + 89468316*uk_66 + 25562376*uk_67 + 402607422*uk_68 + 479294550*uk_69 + 225*uk_7 + 89468316*uk_70 + 7303536*uk_71 + 115030692*uk_72 + 136941300*uk_73 + 25562376*uk_74 + 1811733399*uk_75 + 2156825475*uk_76 + 402607422*uk_77 + 2567649375*uk_78 + 479294550*uk_79 + 42*uk_8 + 89468316*uk_80 + 166375*uk_81 + 202675*uk_82 + 127050*uk_83 + 36300*uk_84 + 571725*uk_85 + 680625*uk_86 + 127050*uk_87 + 246895*uk_88 + 154770*uk_89 + 2572416961*uk_9 + 44220*uk_90 + 696465*uk_91 + 829125*uk_92 + 154770*uk_93 + 97020*uk_94 + 27720*uk_95 + 436590*uk_96 + 519750*uk_97 + 97020*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 126060*uk_100 + 148500*uk_101 + 44220*uk_102 + 2006455*uk_103 + 2363625*uk_104 + 703835*uk_105 + 2784375*uk_106 + 829125*uk_107 + 246895*uk_108 + 1124864*uk_109 + 5274776*uk_11 + 724672*uk_110 + 129792*uk_111 + 2065856*uk_112 + 2433600*uk_113 + 724672*uk_114 + 466856*uk_115 + 83616*uk_116 + 1330888*uk_117 + 1567800*uk_118 + 466856*uk_119 + 3398173*uk_12 + 14976*uk_120 + 238368*uk_121 + 280800*uk_122 + 83616*uk_123 + 3794024*uk_124 + 4469400*uk_125 + 1330888*uk_126 + 5265000*uk_127 + 1567800*uk_128 + 466856*uk_129 + 608628*uk_13 + 300763*uk_130 + 53868*uk_131 + 857399*uk_132 + 1010025*uk_133 + 300763*uk_134 + 9648*uk_135 + 153564*uk_136 + 180900*uk_137 + 53868*uk_138 + 2444227*uk_139 + 9687329*uk_14 + 2879325*uk_140 + 857399*uk_141 + 3391875*uk_142 + 1010025*uk_143 + 300763*uk_144 + 1728*uk_145 + 27504*uk_146 + 32400*uk_147 + 9648*uk_148 + 437772*uk_149 + 11411775*uk_15 + 515700*uk_150 + 153564*uk_151 + 607500*uk_152 + 180900*uk_153 + 53868*uk_154 + 6967871*uk_155 + 8208225*uk_156 + 2444227*uk_157 + 9669375*uk_158 + 2879325*uk_159 + 3398173*uk_16 + 857399*uk_160 + 11390625*uk_161 + 3391875*uk_162 + 1010025*uk_163 + 300763*uk_164 + 3025*uk_17 + 5720*uk_18 + 3685*uk_19 + 55*uk_2 + 660*uk_20 + 10505*uk_21 + 12375*uk_22 + 3685*uk_23 + 10816*uk_24 + 6968*uk_25 + 1248*uk_26 + 19864*uk_27 + 23400*uk_28 + 6968*uk_29 + 104*uk_3 + 4489*uk_30 + 804*uk_31 + 12797*uk_32 + 15075*uk_33 + 4489*uk_34 + 144*uk_35 + 2292*uk_36 + 2700*uk_37 + 804*uk_38 + 36481*uk_39 + 67*uk_4 + 42975*uk_40 + 12797*uk_41 + 50625*uk_42 + 15075*uk_43 + 4489*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 267531363944*uk_47 + 172351936387*uk_48 + 30869003532*uk_49 + 12*uk_5 + 491331639551*uk_50 + 578793816225*uk_51 + 172351936387*uk_52 + 153424975*uk_53 + 290112680*uk_54 + 186899515*uk_55 + 33474540*uk_56 + 532803095*uk_57 + 627647625*uk_58 + 186899515*uk_59 + 191*uk_6 + 548576704*uk_60 + 353409992*uk_61 + 63297312*uk_62 + 1007482216*uk_63 + 1186824600*uk_64 + 353409992*uk_65 + 227677591*uk_66 + 40778076*uk_67 + 649051043*uk_68 + 764588925*uk_69 + 225*uk_7 + 227677591*uk_70 + 7303536*uk_71 + 116247948*uk_72 + 136941300*uk_73 + 40778076*uk_74 + 1850279839*uk_75 + 2179649025*uk_76 + 649051043*uk_77 + 2567649375*uk_78 + 764588925*uk_79 + 67*uk_8 + 227677591*uk_80 + 166375*uk_81 + 314600*uk_82 + 202675*uk_83 + 36300*uk_84 + 577775*uk_85 + 680625*uk_86 + 202675*uk_87 + 594880*uk_88 + 383240*uk_89 + 2572416961*uk_9 + 68640*uk_90 + 1092520*uk_91 + 1287000*uk_92 + 383240*uk_93 + 246895*uk_94 + 44220*uk_95 + 703835*uk_96 + 829125*uk_97 + 246895*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 127380*uk_100 + 148500*uk_101 + 68640*uk_102 + 2048695*uk_103 + 2388375*uk_104 + 1103960*uk_105 + 2784375*uk_106 + 1287000*uk_107 + 594880*uk_108 + 3581577*uk_109 + 7760007*uk_11 + 2434536*uk_110 + 280908*uk_111 + 4517937*uk_112 + 5267025*uk_113 + 2434536*uk_114 + 1654848*uk_115 + 190944*uk_116 + 3071016*uk_117 + 3580200*uk_118 + 1654848*uk_119 + 5274776*uk_12 + 22032*uk_120 + 354348*uk_121 + 413100*uk_122 + 190944*uk_123 + 5699097*uk_124 + 6644025*uk_125 + 3071016*uk_126 + 7745625*uk_127 + 3580200*uk_128 + 1654848*uk_129 + 608628*uk_13 + 1124864*uk_130 + 129792*uk_131 + 2087488*uk_132 + 2433600*uk_133 + 1124864*uk_134 + 14976*uk_135 + 240864*uk_136 + 280800*uk_137 + 129792*uk_138 + 3873896*uk_139 + 9788767*uk_14 + 4516200*uk_140 + 2087488*uk_141 + 5265000*uk_142 + 2433600*uk_143 + 1124864*uk_144 + 1728*uk_145 + 27792*uk_146 + 32400*uk_147 + 14976*uk_148 + 446988*uk_149 + 11411775*uk_15 + 521100*uk_150 + 240864*uk_151 + 607500*uk_152 + 280800*uk_153 + 129792*uk_154 + 7189057*uk_155 + 8381025*uk_156 + 3873896*uk_157 + 9770625*uk_158 + 4516200*uk_159 + 5274776*uk_16 + 2087488*uk_160 + 11390625*uk_161 + 5265000*uk_162 + 2433600*uk_163 + 1124864*uk_164 + 3025*uk_17 + 8415*uk_18 + 5720*uk_19 + 55*uk_2 + 660*uk_20 + 10615*uk_21 + 12375*uk_22 + 5720*uk_23 + 23409*uk_24 + 15912*uk_25 + 1836*uk_26 + 29529*uk_27 + 34425*uk_28 + 15912*uk_29 + 153*uk_3 + 10816*uk_30 + 1248*uk_31 + 20072*uk_32 + 23400*uk_33 + 10816*uk_34 + 144*uk_35 + 2316*uk_36 + 2700*uk_37 + 1248*uk_38 + 37249*uk_39 + 104*uk_4 + 43425*uk_40 + 20072*uk_41 + 50625*uk_42 + 23400*uk_43 + 10816*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 393579795033*uk_47 + 267531363944*uk_48 + 30869003532*uk_49 + 12*uk_5 + 496476473473*uk_50 + 578793816225*uk_51 + 267531363944*uk_52 + 153424975*uk_53 + 426800385*uk_54 + 290112680*uk_55 + 33474540*uk_56 + 538382185*uk_57 + 627647625*uk_58 + 290112680*uk_59 + 193*uk_6 + 1187281071*uk_60 + 807040728*uk_61 + 93120084*uk_62 + 1497681351*uk_63 + 1746001575*uk_64 + 807040728*uk_65 + 548576704*uk_66 + 63297312*uk_67 + 1018031768*uk_68 + 1186824600*uk_69 + 225*uk_7 + 548576704*uk_70 + 7303536*uk_71 + 117465204*uk_72 + 136941300*uk_73 + 63297312*uk_74 + 1889232031*uk_75 + 2202472575*uk_76 + 1018031768*uk_77 + 2567649375*uk_78 + 1186824600*uk_79 + 104*uk_8 + 548576704*uk_80 + 166375*uk_81 + 462825*uk_82 + 314600*uk_83 + 36300*uk_84 + 583825*uk_85 + 680625*uk_86 + 314600*uk_87 + 1287495*uk_88 + 875160*uk_89 + 2572416961*uk_9 + 100980*uk_90 + 1624095*uk_91 + 1893375*uk_92 + 875160*uk_93 + 594880*uk_94 + 68640*uk_95 + 1103960*uk_96 + 1287000*uk_97 + 594880*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 85800*uk_100 + 99000*uk_101 + 67320*uk_102 + 2091375*uk_103 + 2413125*uk_104 + 1640925*uk_105 + 2784375*uk_106 + 1893375*uk_107 + 1287495*uk_108 + 6859*uk_109 + 963661*uk_11 + 55233*uk_110 + 2888*uk_111 + 70395*uk_112 + 81225*uk_113 + 55233*uk_114 + 444771*uk_115 + 23256*uk_116 + 566865*uk_117 + 654075*uk_118 + 444771*uk_119 + 7760007*uk_12 + 1216*uk_120 + 29640*uk_121 + 34200*uk_122 + 23256*uk_123 + 722475*uk_124 + 833625*uk_125 + 566865*uk_126 + 961875*uk_127 + 654075*uk_128 + 444771*uk_129 + 405752*uk_13 + 3581577*uk_130 + 187272*uk_131 + 4564755*uk_132 + 5267025*uk_133 + 3581577*uk_134 + 9792*uk_135 + 238680*uk_136 + 275400*uk_137 + 187272*uk_138 + 5817825*uk_139 + 9890205*uk_14 + 6712875*uk_140 + 4564755*uk_141 + 7745625*uk_142 + 5267025*uk_143 + 3581577*uk_144 + 512*uk_145 + 12480*uk_146 + 14400*uk_147 + 9792*uk_148 + 304200*uk_149 + 11411775*uk_15 + 351000*uk_150 + 238680*uk_151 + 405000*uk_152 + 275400*uk_153 + 187272*uk_154 + 7414875*uk_155 + 8555625*uk_156 + 5817825*uk_157 + 9871875*uk_158 + 6712875*uk_159 + 7760007*uk_16 + 4564755*uk_160 + 11390625*uk_161 + 7745625*uk_162 + 5267025*uk_163 + 3581577*uk_164 + 3025*uk_17 + 1045*uk_18 + 8415*uk_19 + 55*uk_2 + 440*uk_20 + 10725*uk_21 + 12375*uk_22 + 8415*uk_23 + 361*uk_24 + 2907*uk_25 + 152*uk_26 + 3705*uk_27 + 4275*uk_28 + 2907*uk_29 + 19*uk_3 + 23409*uk_30 + 1224*uk_31 + 29835*uk_32 + 34425*uk_33 + 23409*uk_34 + 64*uk_35 + 1560*uk_36 + 1800*uk_37 + 1224*uk_38 + 38025*uk_39 + 153*uk_4 + 43875*uk_40 + 29835*uk_41 + 50625*uk_42 + 34425*uk_43 + 23409*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 48875922259*uk_47 + 393579795033*uk_48 + 20579335688*uk_49 + 8*uk_5 + 501621307395*uk_50 + 578793816225*uk_51 + 393579795033*uk_52 + 153424975*uk_53 + 53001355*uk_54 + 426800385*uk_55 + 22316360*uk_56 + 543961275*uk_57 + 627647625*uk_58 + 426800385*uk_59 + 195*uk_6 + 18309559*uk_60 + 147440133*uk_61 + 7709288*uk_62 + 187913895*uk_63 + 216823725*uk_64 + 147440133*uk_65 + 1187281071*uk_66 + 62080056*uk_67 + 1513201365*uk_68 + 1746001575*uk_69 + 225*uk_7 + 1187281071*uk_70 + 3246016*uk_71 + 79121640*uk_72 + 91294200*uk_73 + 62080056*uk_74 + 1928589975*uk_75 + 2225296125*uk_76 + 1513201365*uk_77 + 2567649375*uk_78 + 1746001575*uk_79 + 153*uk_8 + 1187281071*uk_80 + 166375*uk_81 + 57475*uk_82 + 462825*uk_83 + 24200*uk_84 + 589875*uk_85 + 680625*uk_86 + 462825*uk_87 + 19855*uk_88 + 159885*uk_89 + 2572416961*uk_9 + 8360*uk_90 + 203775*uk_91 + 235125*uk_92 + 159885*uk_93 + 1287495*uk_94 + 67320*uk_95 + 1640925*uk_96 + 1893375*uk_97 + 1287495*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 130020*uk_100 + 148500*uk_101 + 12540*uk_102 + 2134495*uk_103 + 2437875*uk_104 + 205865*uk_105 + 2784375*uk_106 + 235125*uk_107 + 19855*uk_108 + 729000*uk_109 + 4564710*uk_11 + 153900*uk_110 + 97200*uk_111 + 1595700*uk_112 + 1822500*uk_113 + 153900*uk_114 + 32490*uk_115 + 20520*uk_116 + 336870*uk_117 + 384750*uk_118 + 32490*uk_119 + 963661*uk_12 + 12960*uk_120 + 212760*uk_121 + 243000*uk_122 + 20520*uk_123 + 3492810*uk_124 + 3989250*uk_125 + 336870*uk_126 + 4556250*uk_127 + 384750*uk_128 + 32490*uk_129 + 608628*uk_13 + 6859*uk_130 + 4332*uk_131 + 71117*uk_132 + 81225*uk_133 + 6859*uk_134 + 2736*uk_135 + 44916*uk_136 + 51300*uk_137 + 4332*uk_138 + 737371*uk_139 + 9991643*uk_14 + 842175*uk_140 + 71117*uk_141 + 961875*uk_142 + 81225*uk_143 + 6859*uk_144 + 1728*uk_145 + 28368*uk_146 + 32400*uk_147 + 2736*uk_148 + 465708*uk_149 + 11411775*uk_15 + 531900*uk_150 + 44916*uk_151 + 607500*uk_152 + 51300*uk_153 + 4332*uk_154 + 7645373*uk_155 + 8732025*uk_156 + 737371*uk_157 + 9973125*uk_158 + 842175*uk_159 + 963661*uk_16 + 71117*uk_160 + 11390625*uk_161 + 961875*uk_162 + 81225*uk_163 + 6859*uk_164 + 3025*uk_17 + 4950*uk_18 + 1045*uk_19 + 55*uk_2 + 660*uk_20 + 10835*uk_21 + 12375*uk_22 + 1045*uk_23 + 8100*uk_24 + 1710*uk_25 + 1080*uk_26 + 17730*uk_27 + 20250*uk_28 + 1710*uk_29 + 90*uk_3 + 361*uk_30 + 228*uk_31 + 3743*uk_32 + 4275*uk_33 + 361*uk_34 + 144*uk_35 + 2364*uk_36 + 2700*uk_37 + 228*uk_38 + 38809*uk_39 + 19*uk_4 + 44325*uk_40 + 3743*uk_41 + 50625*uk_42 + 4275*uk_43 + 361*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 231517526490*uk_47 + 48875922259*uk_48 + 30869003532*uk_49 + 12*uk_5 + 506766141317*uk_50 + 578793816225*uk_51 + 48875922259*uk_52 + 153424975*uk_53 + 251059050*uk_54 + 53001355*uk_55 + 33474540*uk_56 + 549540365*uk_57 + 627647625*uk_58 + 53001355*uk_59 + 197*uk_6 + 410823900*uk_60 + 86729490*uk_61 + 54776520*uk_62 + 899247870*uk_63 + 1027059750*uk_64 + 86729490*uk_65 + 18309559*uk_66 + 11563932*uk_67 + 189841217*uk_68 + 216823725*uk_69 + 225*uk_7 + 18309559*uk_70 + 7303536*uk_71 + 119899716*uk_72 + 136941300*uk_73 + 11563932*uk_74 + 1968353671*uk_75 + 2248119675*uk_76 + 189841217*uk_77 + 2567649375*uk_78 + 216823725*uk_79 + 19*uk_8 + 18309559*uk_80 + 166375*uk_81 + 272250*uk_82 + 57475*uk_83 + 36300*uk_84 + 595925*uk_85 + 680625*uk_86 + 57475*uk_87 + 445500*uk_88 + 94050*uk_89 + 2572416961*uk_9 + 59400*uk_90 + 975150*uk_91 + 1113750*uk_92 + 94050*uk_93 + 19855*uk_94 + 12540*uk_95 + 205865*uk_96 + 235125*uk_97 + 19855*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 131340*uk_100 + 148500*uk_101 + 59400*uk_102 + 2178055*uk_103 + 2462625*uk_104 + 985050*uk_105 + 2784375*uk_106 + 1113750*uk_107 + 445500*uk_108 + 5177717*uk_109 + 8774387*uk_11 + 2693610*uk_110 + 359148*uk_111 + 5955871*uk_112 + 6734025*uk_113 + 2693610*uk_114 + 1401300*uk_115 + 186840*uk_116 + 3098430*uk_117 + 3503250*uk_118 + 1401300*uk_119 + 4564710*uk_12 + 24912*uk_120 + 413124*uk_121 + 467100*uk_122 + 186840*uk_123 + 6850973*uk_124 + 7746075*uk_125 + 3098430*uk_126 + 8758125*uk_127 + 3503250*uk_128 + 1401300*uk_129 + 608628*uk_13 + 729000*uk_130 + 97200*uk_131 + 1611900*uk_132 + 1822500*uk_133 + 729000*uk_134 + 12960*uk_135 + 214920*uk_136 + 243000*uk_137 + 97200*uk_138 + 3564090*uk_139 + 10093081*uk_14 + 4029750*uk_140 + 1611900*uk_141 + 4556250*uk_142 + 1822500*uk_143 + 729000*uk_144 + 1728*uk_145 + 28656*uk_146 + 32400*uk_147 + 12960*uk_148 + 475212*uk_149 + 11411775*uk_15 + 537300*uk_150 + 214920*uk_151 + 607500*uk_152 + 243000*uk_153 + 97200*uk_154 + 7880599*uk_155 + 8910225*uk_156 + 3564090*uk_157 + 10074375*uk_158 + 4029750*uk_159 + 4564710*uk_16 + 1611900*uk_160 + 11390625*uk_161 + 4556250*uk_162 + 1822500*uk_163 + 729000*uk_164 + 3025*uk_17 + 9515*uk_18 + 4950*uk_19 + 55*uk_2 + 660*uk_20 + 10945*uk_21 + 12375*uk_22 + 4950*uk_23 + 29929*uk_24 + 15570*uk_25 + 2076*uk_26 + 34427*uk_27 + 38925*uk_28 + 15570*uk_29 + 173*uk_3 + 8100*uk_30 + 1080*uk_31 + 17910*uk_32 + 20250*uk_33 + 8100*uk_34 + 144*uk_35 + 2388*uk_36 + 2700*uk_37 + 1080*uk_38 + 39601*uk_39 + 90*uk_4 + 44775*uk_40 + 17910*uk_41 + 50625*uk_42 + 20250*uk_43 + 8100*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 445028134253*uk_47 + 231517526490*uk_48 + 30869003532*uk_49 + 12*uk_5 + 511910975239*uk_50 + 578793816225*uk_51 + 231517526490*uk_52 + 153424975*uk_53 + 482591285*uk_54 + 251059050*uk_55 + 33474540*uk_56 + 555119455*uk_57 + 627647625*uk_58 + 251059050*uk_59 + 199*uk_6 + 1517968951*uk_60 + 789694830*uk_61 + 105292644*uk_62 + 1746103013*uk_63 + 1974237075*uk_64 + 789694830*uk_65 + 410823900*uk_66 + 54776520*uk_67 + 908377290*uk_68 + 1027059750*uk_69 + 225*uk_7 + 410823900*uk_70 + 7303536*uk_71 + 121116972*uk_72 + 136941300*uk_73 + 54776520*uk_74 + 2008523119*uk_75 + 2270943225*uk_76 + 908377290*uk_77 + 2567649375*uk_78 + 1027059750*uk_79 + 90*uk_8 + 410823900*uk_80 + 166375*uk_81 + 523325*uk_82 + 272250*uk_83 + 36300*uk_84 + 601975*uk_85 + 680625*uk_86 + 272250*uk_87 + 1646095*uk_88 + 856350*uk_89 + 2572416961*uk_9 + 114180*uk_90 + 1893485*uk_91 + 2140875*uk_92 + 856350*uk_93 + 445500*uk_94 + 59400*uk_95 + 985050*uk_96 + 1113750*uk_97 + 445500*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 88440*uk_100 + 99000*uk_101 + 76120*uk_102 + 2222055*uk_103 + 2487375*uk_104 + 1912515*uk_105 + 2784375*uk_106 + 2140875*uk_107 + 1646095*uk_108 + 300763*uk_109 + 3398173*uk_11 + 776597*uk_110 + 35912*uk_111 + 902289*uk_112 + 1010025*uk_113 + 776597*uk_114 + 2005243*uk_115 + 92728*uk_116 + 2329791*uk_117 + 2607975*uk_118 + 2005243*uk_119 + 8774387*uk_12 + 4288*uk_120 + 107736*uk_121 + 120600*uk_122 + 92728*uk_123 + 2706867*uk_124 + 3030075*uk_125 + 2329791*uk_126 + 3391875*uk_127 + 2607975*uk_128 + 2005243*uk_129 + 405752*uk_13 + 5177717*uk_130 + 239432*uk_131 + 6015729*uk_132 + 6734025*uk_133 + 5177717*uk_134 + 11072*uk_135 + 278184*uk_136 + 311400*uk_137 + 239432*uk_138 + 6989373*uk_139 + 10194519*uk_14 + 7823925*uk_140 + 6015729*uk_141 + 8758125*uk_142 + 6734025*uk_143 + 5177717*uk_144 + 512*uk_145 + 12864*uk_146 + 14400*uk_147 + 11072*uk_148 + 323208*uk_149 + 11411775*uk_15 + 361800*uk_150 + 278184*uk_151 + 405000*uk_152 + 311400*uk_153 + 239432*uk_154 + 8120601*uk_155 + 9090225*uk_156 + 6989373*uk_157 + 10175625*uk_158 + 7823925*uk_159 + 8774387*uk_16 + 6015729*uk_160 + 11390625*uk_161 + 8758125*uk_162 + 6734025*uk_163 + 5177717*uk_164 + 3025*uk_17 + 3685*uk_18 + 9515*uk_19 + 55*uk_2 + 440*uk_20 + 11055*uk_21 + 12375*uk_22 + 9515*uk_23 + 4489*uk_24 + 11591*uk_25 + 536*uk_26 + 13467*uk_27 + 15075*uk_28 + 11591*uk_29 + 67*uk_3 + 29929*uk_30 + 1384*uk_31 + 34773*uk_32 + 38925*uk_33 + 29929*uk_34 + 64*uk_35 + 1608*uk_36 + 1800*uk_37 + 1384*uk_38 + 40401*uk_39 + 173*uk_4 + 45225*uk_40 + 34773*uk_41 + 50625*uk_42 + 38925*uk_43 + 29929*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 172351936387*uk_47 + 445028134253*uk_48 + 20579335688*uk_49 + 8*uk_5 + 517055809161*uk_50 + 578793816225*uk_51 + 445028134253*uk_52 + 153424975*uk_53 + 186899515*uk_54 + 482591285*uk_55 + 22316360*uk_56 + 560698545*uk_57 + 627647625*uk_58 + 482591285*uk_59 + 201*uk_6 + 227677591*uk_60 + 587883929*uk_61 + 27185384*uk_62 + 683032773*uk_63 + 764588925*uk_64 + 587883929*uk_65 + 1517968951*uk_66 + 70195096*uk_67 + 1763651787*uk_68 + 1974237075*uk_69 + 225*uk_7 + 1517968951*uk_70 + 3246016*uk_71 + 81556152*uk_72 + 91294200*uk_73 + 70195096*uk_74 + 2049098319*uk_75 + 2293766775*uk_76 + 1763651787*uk_77 + 2567649375*uk_78 + 1974237075*uk_79 + 173*uk_8 + 1517968951*uk_80 + 166375*uk_81 + 202675*uk_82 + 523325*uk_83 + 24200*uk_84 + 608025*uk_85 + 680625*uk_86 + 523325*uk_87 + 246895*uk_88 + 637505*uk_89 + 2572416961*uk_9 + 29480*uk_90 + 740685*uk_91 + 829125*uk_92 + 637505*uk_93 + 1646095*uk_94 + 76120*uk_95 + 1912515*uk_96 + 2140875*uk_97 + 1646095*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 133980*uk_100 + 148500*uk_101 + 44220*uk_102 + 2266495*uk_103 + 2512125*uk_104 + 748055*uk_105 + 2784375*uk_106 + 829125*uk_107 + 246895*uk_108 + 5088448*uk_109 + 8723668*uk_11 + 1982128*uk_110 + 355008*uk_111 + 6005552*uk_112 + 6656400*uk_113 + 1982128*uk_114 + 772108*uk_115 + 138288*uk_116 + 2339372*uk_117 + 2592900*uk_118 + 772108*uk_119 + 3398173*uk_12 + 24768*uk_120 + 418992*uk_121 + 464400*uk_122 + 138288*uk_123 + 7087948*uk_124 + 7856100*uk_125 + 2339372*uk_126 + 8707500*uk_127 + 2592900*uk_128 + 772108*uk_129 + 608628*uk_13 + 300763*uk_130 + 53868*uk_131 + 911267*uk_132 + 1010025*uk_133 + 300763*uk_134 + 9648*uk_135 + 163212*uk_136 + 180900*uk_137 + 53868*uk_138 + 2761003*uk_139 + 10295957*uk_14 + 3060225*uk_140 + 911267*uk_141 + 3391875*uk_142 + 1010025*uk_143 + 300763*uk_144 + 1728*uk_145 + 29232*uk_146 + 32400*uk_147 + 9648*uk_148 + 494508*uk_149 + 11411775*uk_15 + 548100*uk_150 + 163212*uk_151 + 607500*uk_152 + 180900*uk_153 + 53868*uk_154 + 8365427*uk_155 + 9272025*uk_156 + 2761003*uk_157 + 10276875*uk_158 + 3060225*uk_159 + 3398173*uk_16 + 911267*uk_160 + 11390625*uk_161 + 3391875*uk_162 + 1010025*uk_163 + 300763*uk_164 + 3025*uk_17 + 9460*uk_18 + 3685*uk_19 + 55*uk_2 + 660*uk_20 + 11165*uk_21 + 12375*uk_22 + 3685*uk_23 + 29584*uk_24 + 11524*uk_25 + 2064*uk_26 + 34916*uk_27 + 38700*uk_28 + 11524*uk_29 + 172*uk_3 + 4489*uk_30 + 804*uk_31 + 13601*uk_32 + 15075*uk_33 + 4489*uk_34 + 144*uk_35 + 2436*uk_36 + 2700*uk_37 + 804*uk_38 + 41209*uk_39 + 67*uk_4 + 45675*uk_40 + 13601*uk_41 + 50625*uk_42 + 15075*uk_43 + 4489*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 442455717292*uk_47 + 172351936387*uk_48 + 30869003532*uk_49 + 12*uk_5 + 522200643083*uk_50 + 578793816225*uk_51 + 172351936387*uk_52 + 153424975*uk_53 + 479801740*uk_54 + 186899515*uk_55 + 33474540*uk_56 + 566277635*uk_57 + 627647625*uk_58 + 186899515*uk_59 + 203*uk_6 + 1500470896*uk_60 + 584485756*uk_61 + 104684016*uk_62 + 1770904604*uk_63 + 1962825300*uk_64 + 584485756*uk_65 + 227677591*uk_66 + 40778076*uk_67 + 689829119*uk_68 + 764588925*uk_69 + 225*uk_7 + 227677591*uk_70 + 7303536*uk_71 + 123551484*uk_72 + 136941300*uk_73 + 40778076*uk_74 + 2090079271*uk_75 + 2316590325*uk_76 + 689829119*uk_77 + 2567649375*uk_78 + 764588925*uk_79 + 67*uk_8 + 227677591*uk_80 + 166375*uk_81 + 520300*uk_82 + 202675*uk_83 + 36300*uk_84 + 614075*uk_85 + 680625*uk_86 + 202675*uk_87 + 1627120*uk_88 + 633820*uk_89 + 2572416961*uk_9 + 113520*uk_90 + 1920380*uk_91 + 2128500*uk_92 + 633820*uk_93 + 246895*uk_94 + 44220*uk_95 + 748055*uk_96 + 829125*uk_97 + 246895*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 90200*uk_100 + 99000*uk_101 + 75680*uk_102 + 2311375*uk_103 + 2536875*uk_104 + 1939300*uk_105 + 2784375*uk_106 + 2128500*uk_107 + 1627120*uk_108 + 592704*uk_109 + 4260396*uk_11 + 1213632*uk_110 + 56448*uk_111 + 1446480*uk_112 + 1587600*uk_113 + 1213632*uk_114 + 2485056*uk_115 + 115584*uk_116 + 2961840*uk_117 + 3250800*uk_118 + 2485056*uk_119 + 8723668*uk_12 + 5376*uk_120 + 137760*uk_121 + 151200*uk_122 + 115584*uk_123 + 3530100*uk_124 + 3874500*uk_125 + 2961840*uk_126 + 4252500*uk_127 + 3250800*uk_128 + 2485056*uk_129 + 405752*uk_13 + 5088448*uk_130 + 236672*uk_131 + 6064720*uk_132 + 6656400*uk_133 + 5088448*uk_134 + 11008*uk_135 + 282080*uk_136 + 309600*uk_137 + 236672*uk_138 + 7228300*uk_139 + 10397395*uk_14 + 7933500*uk_140 + 6064720*uk_141 + 8707500*uk_142 + 6656400*uk_143 + 5088448*uk_144 + 512*uk_145 + 13120*uk_146 + 14400*uk_147 + 11008*uk_148 + 336200*uk_149 + 11411775*uk_15 + 369000*uk_150 + 282080*uk_151 + 405000*uk_152 + 309600*uk_153 + 236672*uk_154 + 8615125*uk_155 + 9455625*uk_156 + 7228300*uk_157 + 10378125*uk_158 + 7933500*uk_159 + 8723668*uk_16 + 6064720*uk_160 + 11390625*uk_161 + 8707500*uk_162 + 6656400*uk_163 + 5088448*uk_164 + 3025*uk_17 + 4620*uk_18 + 9460*uk_19 + 55*uk_2 + 440*uk_20 + 11275*uk_21 + 12375*uk_22 + 9460*uk_23 + 7056*uk_24 + 14448*uk_25 + 672*uk_26 + 17220*uk_27 + 18900*uk_28 + 14448*uk_29 + 84*uk_3 + 29584*uk_30 + 1376*uk_31 + 35260*uk_32 + 38700*uk_33 + 29584*uk_34 + 64*uk_35 + 1640*uk_36 + 1800*uk_37 + 1376*uk_38 + 42025*uk_39 + 172*uk_4 + 46125*uk_40 + 35260*uk_41 + 50625*uk_42 + 38700*uk_43 + 29584*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 216083024724*uk_47 + 442455717292*uk_48 + 20579335688*uk_49 + 8*uk_5 + 527345477005*uk_50 + 578793816225*uk_51 + 442455717292*uk_52 + 153424975*uk_53 + 234321780*uk_54 + 479801740*uk_55 + 22316360*uk_56 + 571856725*uk_57 + 627647625*uk_58 + 479801740*uk_59 + 205*uk_6 + 357873264*uk_60 + 732788112*uk_61 + 34083168*uk_62 + 873381180*uk_63 + 958589100*uk_64 + 732788112*uk_65 + 1500470896*uk_66 + 69789344*uk_67 + 1788351940*uk_68 + 1962825300*uk_69 + 225*uk_7 + 1500470896*uk_70 + 3246016*uk_71 + 83179160*uk_72 + 91294200*uk_73 + 69789344*uk_74 + 2131465975*uk_75 + 2339413875*uk_76 + 1788351940*uk_77 + 2567649375*uk_78 + 1962825300*uk_79 + 172*uk_8 + 1500470896*uk_80 + 166375*uk_81 + 254100*uk_82 + 520300*uk_83 + 24200*uk_84 + 620125*uk_85 + 680625*uk_86 + 520300*uk_87 + 388080*uk_88 + 794640*uk_89 + 2572416961*uk_9 + 36960*uk_90 + 947100*uk_91 + 1039500*uk_92 + 794640*uk_93 + 1627120*uk_94 + 75680*uk_95 + 1939300*uk_96 + 2128500*uk_97 + 1627120*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 91080*uk_100 + 99000*uk_101 + 36960*uk_102 + 2356695*uk_103 + 2561625*uk_104 + 956340*uk_105 + 2784375*uk_106 + 1039500*uk_107 + 388080*uk_108 + 64*uk_109 + 202876*uk_11 + 1344*uk_110 + 128*uk_111 + 3312*uk_112 + 3600*uk_113 + 1344*uk_114 + 28224*uk_115 + 2688*uk_116 + 69552*uk_117 + 75600*uk_118 + 28224*uk_119 + 4260396*uk_12 + 256*uk_120 + 6624*uk_121 + 7200*uk_122 + 2688*uk_123 + 171396*uk_124 + 186300*uk_125 + 69552*uk_126 + 202500*uk_127 + 75600*uk_128 + 28224*uk_129 + 405752*uk_13 + 592704*uk_130 + 56448*uk_131 + 1460592*uk_132 + 1587600*uk_133 + 592704*uk_134 + 5376*uk_135 + 139104*uk_136 + 151200*uk_137 + 56448*uk_138 + 3599316*uk_139 + 10498833*uk_14 + 3912300*uk_140 + 1460592*uk_141 + 4252500*uk_142 + 1587600*uk_143 + 592704*uk_144 + 512*uk_145 + 13248*uk_146 + 14400*uk_147 + 5376*uk_148 + 342792*uk_149 + 11411775*uk_15 + 372600*uk_150 + 139104*uk_151 + 405000*uk_152 + 151200*uk_153 + 56448*uk_154 + 8869743*uk_155 + 9641025*uk_156 + 3599316*uk_157 + 10479375*uk_158 + 3912300*uk_159 + 4260396*uk_16 + 1460592*uk_160 + 11390625*uk_161 + 4252500*uk_162 + 1587600*uk_163 + 592704*uk_164 + 3025*uk_17 + 220*uk_18 + 4620*uk_19 + 55*uk_2 + 440*uk_20 + 11385*uk_21 + 12375*uk_22 + 4620*uk_23 + 16*uk_24 + 336*uk_25 + 32*uk_26 + 828*uk_27 + 900*uk_28 + 336*uk_29 + 4*uk_3 + 7056*uk_30 + 672*uk_31 + 17388*uk_32 + 18900*uk_33 + 7056*uk_34 + 64*uk_35 + 1656*uk_36 + 1800*uk_37 + 672*uk_38 + 42849*uk_39 + 84*uk_4 + 46575*uk_40 + 17388*uk_41 + 50625*uk_42 + 18900*uk_43 + 7056*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 10289667844*uk_47 + 216083024724*uk_48 + 20579335688*uk_49 + 8*uk_5 + 532490310927*uk_50 + 578793816225*uk_51 + 216083024724*uk_52 + 153424975*uk_53 + 11158180*uk_54 + 234321780*uk_55 + 22316360*uk_56 + 577435815*uk_57 + 627647625*uk_58 + 234321780*uk_59 + 207*uk_6 + 811504*uk_60 + 17041584*uk_61 + 1623008*uk_62 + 41995332*uk_63 + 45647100*uk_64 + 17041584*uk_65 + 357873264*uk_66 + 34083168*uk_67 + 881901972*uk_68 + 958589100*uk_69 + 225*uk_7 + 357873264*uk_70 + 3246016*uk_71 + 83990664*uk_72 + 91294200*uk_73 + 34083168*uk_74 + 2173258431*uk_75 + 2362237425*uk_76 + 881901972*uk_77 + 2567649375*uk_78 + 958589100*uk_79 + 84*uk_8 + 357873264*uk_80 + 166375*uk_81 + 12100*uk_82 + 254100*uk_83 + 24200*uk_84 + 626175*uk_85 + 680625*uk_86 + 254100*uk_87 + 880*uk_88 + 18480*uk_89 + 2572416961*uk_9 + 1760*uk_90 + 45540*uk_91 + 49500*uk_92 + 18480*uk_93 + 388080*uk_94 + 36960*uk_95 + 956340*uk_96 + 1039500*uk_97 + 388080*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 137940*uk_100 + 148500*uk_101 + 2640*uk_102 + 2402455*uk_103 + 2586375*uk_104 + 45980*uk_105 + 2784375*uk_106 + 49500*uk_107 + 880*uk_108 + 2803221*uk_109 + 7151379*uk_11 + 79524*uk_110 + 238572*uk_111 + 4155129*uk_112 + 4473225*uk_113 + 79524*uk_114 + 2256*uk_115 + 6768*uk_116 + 117876*uk_117 + 126900*uk_118 + 2256*uk_119 + 202876*uk_12 + 20304*uk_120 + 353628*uk_121 + 380700*uk_122 + 6768*uk_123 + 6159021*uk_124 + 6630525*uk_125 + 117876*uk_126 + 7138125*uk_127 + 126900*uk_128 + 2256*uk_129 + 608628*uk_13 + 64*uk_130 + 192*uk_131 + 3344*uk_132 + 3600*uk_133 + 64*uk_134 + 576*uk_135 + 10032*uk_136 + 10800*uk_137 + 192*uk_138 + 174724*uk_139 + 10600271*uk_14 + 188100*uk_140 + 3344*uk_141 + 202500*uk_142 + 3600*uk_143 + 64*uk_144 + 1728*uk_145 + 30096*uk_146 + 32400*uk_147 + 576*uk_148 + 524172*uk_149 + 11411775*uk_15 + 564300*uk_150 + 10032*uk_151 + 607500*uk_152 + 10800*uk_153 + 192*uk_154 + 9129329*uk_155 + 9828225*uk_156 + 174724*uk_157 + 10580625*uk_158 + 188100*uk_159 + 202876*uk_16 + 3344*uk_160 + 11390625*uk_161 + 202500*uk_162 + 3600*uk_163 + 64*uk_164 + 3025*uk_17 + 7755*uk_18 + 220*uk_19 + 55*uk_2 + 660*uk_20 + 11495*uk_21 + 12375*uk_22 + 220*uk_23 + 19881*uk_24 + 564*uk_25 + 1692*uk_26 + 29469*uk_27 + 31725*uk_28 + 564*uk_29 + 141*uk_3 + 16*uk_30 + 48*uk_31 + 836*uk_32 + 900*uk_33 + 16*uk_34 + 144*uk_35 + 2508*uk_36 + 2700*uk_37 + 48*uk_38 + 43681*uk_39 + 4*uk_4 + 47025*uk_40 + 836*uk_41 + 50625*uk_42 + 900*uk_43 + 16*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 362710791501*uk_47 + 10289667844*uk_48 + 30869003532*uk_49 + 12*uk_5 + 537635144849*uk_50 + 578793816225*uk_51 + 10289667844*uk_52 + 153424975*uk_53 + 393325845*uk_54 + 11158180*uk_55 + 33474540*uk_56 + 583014905*uk_57 + 627647625*uk_58 + 11158180*uk_59 + 209*uk_6 + 1008344439*uk_60 + 28605516*uk_61 + 85816548*uk_62 + 1494638211*uk_63 + 1609060275*uk_64 + 28605516*uk_65 + 811504*uk_66 + 2434512*uk_67 + 42401084*uk_68 + 45647100*uk_69 + 225*uk_7 + 811504*uk_70 + 7303536*uk_71 + 127203252*uk_72 + 136941300*uk_73 + 2434512*uk_74 + 2215456639*uk_75 + 2385060975*uk_76 + 42401084*uk_77 + 2567649375*uk_78 + 45647100*uk_79 + 4*uk_8 + 811504*uk_80 + 166375*uk_81 + 426525*uk_82 + 12100*uk_83 + 36300*uk_84 + 632225*uk_85 + 680625*uk_86 + 12100*uk_87 + 1093455*uk_88 + 31020*uk_89 + 2572416961*uk_9 + 93060*uk_90 + 1620795*uk_91 + 1744875*uk_92 + 31020*uk_93 + 880*uk_94 + 2640*uk_95 + 45980*uk_96 + 49500*uk_97 + 880*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 92840*uk_100 + 99000*uk_101 + 62040*uk_102 + 2448655*uk_103 + 2611125*uk_104 + 1636305*uk_105 + 2784375*uk_106 + 1744875*uk_107 + 1093455*uk_108 + 493039*uk_109 + 4006801*uk_11 + 879981*uk_110 + 49928*uk_111 + 1316851*uk_112 + 1404225*uk_113 + 879981*uk_114 + 1570599*uk_115 + 89112*uk_116 + 2350329*uk_117 + 2506275*uk_118 + 1570599*uk_119 + 7151379*uk_12 + 5056*uk_120 + 133352*uk_121 + 142200*uk_122 + 89112*uk_123 + 3517159*uk_124 + 3750525*uk_125 + 2350329*uk_126 + 3999375*uk_127 + 2506275*uk_128 + 1570599*uk_129 + 405752*uk_13 + 2803221*uk_130 + 159048*uk_131 + 4194891*uk_132 + 4473225*uk_133 + 2803221*uk_134 + 9024*uk_135 + 238008*uk_136 + 253800*uk_137 + 159048*uk_138 + 6277461*uk_139 + 10701709*uk_14 + 6693975*uk_140 + 4194891*uk_141 + 7138125*uk_142 + 4473225*uk_143 + 2803221*uk_144 + 512*uk_145 + 13504*uk_146 + 14400*uk_147 + 9024*uk_148 + 356168*uk_149 + 11411775*uk_15 + 379800*uk_150 + 238008*uk_151 + 405000*uk_152 + 253800*uk_153 + 159048*uk_154 + 9393931*uk_155 + 10017225*uk_156 + 6277461*uk_157 + 10681875*uk_158 + 6693975*uk_159 + 7151379*uk_16 + 4194891*uk_160 + 11390625*uk_161 + 7138125*uk_162 + 4473225*uk_163 + 2803221*uk_164 + 3025*uk_17 + 4345*uk_18 + 7755*uk_19 + 55*uk_2 + 440*uk_20 + 11605*uk_21 + 12375*uk_22 + 7755*uk_23 + 6241*uk_24 + 11139*uk_25 + 632*uk_26 + 16669*uk_27 + 17775*uk_28 + 11139*uk_29 + 79*uk_3 + 19881*uk_30 + 1128*uk_31 + 29751*uk_32 + 31725*uk_33 + 19881*uk_34 + 64*uk_35 + 1688*uk_36 + 1800*uk_37 + 1128*uk_38 + 44521*uk_39 + 141*uk_4 + 47475*uk_40 + 29751*uk_41 + 50625*uk_42 + 31725*uk_43 + 19881*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 203220939919*uk_47 + 362710791501*uk_48 + 20579335688*uk_49 + 8*uk_5 + 542779978771*uk_50 + 578793816225*uk_51 + 362710791501*uk_52 + 153424975*uk_53 + 220374055*uk_54 + 393325845*uk_55 + 22316360*uk_56 + 588593995*uk_57 + 627647625*uk_58 + 393325845*uk_59 + 211*uk_6 + 316537279*uk_60 + 564958941*uk_61 + 32054408*uk_62 + 845435011*uk_63 + 901530225*uk_64 + 564958941*uk_65 + 1008344439*uk_66 + 57211032*uk_67 + 1508940969*uk_68 + 1609060275*uk_69 + 225*uk_7 + 1008344439*uk_70 + 3246016*uk_71 + 85613672*uk_72 + 91294200*uk_73 + 57211032*uk_74 + 2258060599*uk_75 + 2407884525*uk_76 + 1508940969*uk_77 + 2567649375*uk_78 + 1609060275*uk_79 + 141*uk_8 + 1008344439*uk_80 + 166375*uk_81 + 238975*uk_82 + 426525*uk_83 + 24200*uk_84 + 638275*uk_85 + 680625*uk_86 + 426525*uk_87 + 343255*uk_88 + 612645*uk_89 + 2572416961*uk_9 + 34760*uk_90 + 916795*uk_91 + 977625*uk_92 + 612645*uk_93 + 1093455*uk_94 + 62040*uk_95 + 1636305*uk_96 + 1744875*uk_97 + 1093455*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 93720*uk_100 + 99000*uk_101 + 34760*uk_102 + 2495295*uk_103 + 2635875*uk_104 + 925485*uk_105 + 2784375*uk_106 + 977625*uk_107 + 343255*uk_108 + 15625*uk_109 + 1267975*uk_11 + 49375*uk_110 + 5000*uk_111 + 133125*uk_112 + 140625*uk_113 + 49375*uk_114 + 156025*uk_115 + 15800*uk_116 + 420675*uk_117 + 444375*uk_118 + 156025*uk_119 + 4006801*uk_12 + 1600*uk_120 + 42600*uk_121 + 45000*uk_122 + 15800*uk_123 + 1134225*uk_124 + 1198125*uk_125 + 420675*uk_126 + 1265625*uk_127 + 444375*uk_128 + 156025*uk_129 + 405752*uk_13 + 493039*uk_130 + 49928*uk_131 + 1329333*uk_132 + 1404225*uk_133 + 493039*uk_134 + 5056*uk_135 + 134616*uk_136 + 142200*uk_137 + 49928*uk_138 + 3584151*uk_139 + 10803147*uk_14 + 3786075*uk_140 + 1329333*uk_141 + 3999375*uk_142 + 1404225*uk_143 + 493039*uk_144 + 512*uk_145 + 13632*uk_146 + 14400*uk_147 + 5056*uk_148 + 362952*uk_149 + 11411775*uk_15 + 383400*uk_150 + 134616*uk_151 + 405000*uk_152 + 142200*uk_153 + 49928*uk_154 + 9663597*uk_155 + 10208025*uk_156 + 3584151*uk_157 + 10783125*uk_158 + 3786075*uk_159 + 4006801*uk_16 + 1329333*uk_160 + 11390625*uk_161 + 3999375*uk_162 + 1404225*uk_163 + 493039*uk_164 + 3025*uk_17 + 1375*uk_18 + 4345*uk_19 + 55*uk_2 + 440*uk_20 + 11715*uk_21 + 12375*uk_22 + 4345*uk_23 + 625*uk_24 + 1975*uk_25 + 200*uk_26 + 5325*uk_27 + 5625*uk_28 + 1975*uk_29 + 25*uk_3 + 6241*uk_30 + 632*uk_31 + 16827*uk_32 + 17775*uk_33 + 6241*uk_34 + 64*uk_35 + 1704*uk_36 + 1800*uk_37 + 632*uk_38 + 45369*uk_39 + 79*uk_4 + 47925*uk_40 + 16827*uk_41 + 50625*uk_42 + 17775*uk_43 + 6241*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 64310424025*uk_47 + 203220939919*uk_48 + 20579335688*uk_49 + 8*uk_5 + 547924812693*uk_50 + 578793816225*uk_51 + 203220939919*uk_52 + 153424975*uk_53 + 69738625*uk_54 + 220374055*uk_55 + 22316360*uk_56 + 594173085*uk_57 + 627647625*uk_58 + 220374055*uk_59 + 213*uk_6 + 31699375*uk_60 + 100170025*uk_61 + 10143800*uk_62 + 270078675*uk_63 + 285294375*uk_64 + 100170025*uk_65 + 316537279*uk_66 + 32054408*uk_67 + 853448613*uk_68 + 901530225*uk_69 + 225*uk_7 + 316537279*uk_70 + 3246016*uk_71 + 86425176*uk_72 + 91294200*uk_73 + 32054408*uk_74 + 2301070311*uk_75 + 2430708075*uk_76 + 853448613*uk_77 + 2567649375*uk_78 + 901530225*uk_79 + 79*uk_8 + 316537279*uk_80 + 166375*uk_81 + 75625*uk_82 + 238975*uk_83 + 24200*uk_84 + 644325*uk_85 + 680625*uk_86 + 238975*uk_87 + 34375*uk_88 + 108625*uk_89 + 2572416961*uk_9 + 11000*uk_90 + 292875*uk_91 + 309375*uk_92 + 108625*uk_93 + 343255*uk_94 + 34760*uk_95 + 925485*uk_96 + 977625*uk_97 + 343255*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 141900*uk_100 + 148500*uk_101 + 16500*uk_102 + 2542375*uk_103 + 2660625*uk_104 + 295625*uk_105 + 2784375*uk_106 + 309375*uk_107 + 34375*uk_108 + 7301384*uk_109 + 9839486*uk_11 + 940900*uk_110 + 451632*uk_111 + 8091740*uk_112 + 8468100*uk_113 + 940900*uk_114 + 121250*uk_115 + 58200*uk_116 + 1042750*uk_117 + 1091250*uk_118 + 121250*uk_119 + 1267975*uk_12 + 27936*uk_120 + 500520*uk_121 + 523800*uk_122 + 58200*uk_123 + 8967650*uk_124 + 9384750*uk_125 + 1042750*uk_126 + 9821250*uk_127 + 1091250*uk_128 + 121250*uk_129 + 608628*uk_13 + 15625*uk_130 + 7500*uk_131 + 134375*uk_132 + 140625*uk_133 + 15625*uk_134 + 3600*uk_135 + 64500*uk_136 + 67500*uk_137 + 7500*uk_138 + 1155625*uk_139 + 10904585*uk_14 + 1209375*uk_140 + 134375*uk_141 + 1265625*uk_142 + 140625*uk_143 + 15625*uk_144 + 1728*uk_145 + 30960*uk_146 + 32400*uk_147 + 3600*uk_148 + 554700*uk_149 + 11411775*uk_15 + 580500*uk_150 + 64500*uk_151 + 607500*uk_152 + 67500*uk_153 + 7500*uk_154 + 9938375*uk_155 + 10400625*uk_156 + 1155625*uk_157 + 10884375*uk_158 + 1209375*uk_159 + 1267975*uk_16 + 134375*uk_160 + 11390625*uk_161 + 1265625*uk_162 + 140625*uk_163 + 15625*uk_164 + 3025*uk_17 + 10670*uk_18 + 1375*uk_19 + 55*uk_2 + 660*uk_20 + 11825*uk_21 + 12375*uk_22 + 1375*uk_23 + 37636*uk_24 + 4850*uk_25 + 2328*uk_26 + 41710*uk_27 + 43650*uk_28 + 4850*uk_29 + 194*uk_3 + 625*uk_30 + 300*uk_31 + 5375*uk_32 + 5625*uk_33 + 625*uk_34 + 144*uk_35 + 2580*uk_36 + 2700*uk_37 + 300*uk_38 + 46225*uk_39 + 25*uk_4 + 48375*uk_40 + 5375*uk_41 + 50625*uk_42 + 5625*uk_43 + 625*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 499048890434*uk_47 + 64310424025*uk_48 + 30869003532*uk_49 + 12*uk_5 + 553069646615*uk_50 + 578793816225*uk_51 + 64310424025*uk_52 + 153424975*uk_53 + 541171730*uk_54 + 69738625*uk_55 + 33474540*uk_56 + 599752175*uk_57 + 627647625*uk_58 + 69738625*uk_59 + 215*uk_6 + 1908860284*uk_60 + 245987150*uk_61 + 118073832*uk_62 + 2115489490*uk_63 + 2213884350*uk_64 + 245987150*uk_65 + 31699375*uk_66 + 15215700*uk_67 + 272614625*uk_68 + 285294375*uk_69 + 225*uk_7 + 31699375*uk_70 + 7303536*uk_71 + 130855020*uk_72 + 136941300*uk_73 + 15215700*uk_74 + 2344485775*uk_75 + 2453531625*uk_76 + 272614625*uk_77 + 2567649375*uk_78 + 285294375*uk_79 + 25*uk_8 + 31699375*uk_80 + 166375*uk_81 + 586850*uk_82 + 75625*uk_83 + 36300*uk_84 + 650375*uk_85 + 680625*uk_86 + 75625*uk_87 + 2069980*uk_88 + 266750*uk_89 + 2572416961*uk_9 + 128040*uk_90 + 2294050*uk_91 + 2400750*uk_92 + 266750*uk_93 + 34375*uk_94 + 16500*uk_95 + 295625*uk_96 + 309375*uk_97 + 34375*uk_98 + 7920*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 95480*uk_100 + 99000*uk_101 + 85360*uk_102 + 2589895*uk_103 + 2685375*uk_104 + 2315390*uk_105 + 2784375*uk_106 + 2400750*uk_107 + 2069980*uk_108 + 3944312*uk_109 + 8013602*uk_11 + 4843016*uk_110 + 199712*uk_111 + 5417188*uk_112 + 5616900*uk_113 + 4843016*uk_114 + 5946488*uk_115 + 245216*uk_116 + 6651484*uk_117 + 6896700*uk_118 + 5946488*uk_119 + 9839486*uk_12 + 10112*uk_120 + 274288*uk_121 + 284400*uk_122 + 245216*uk_123 + 7440062*uk_124 + 7714350*uk_125 + 6651484*uk_126 + 7998750*uk_127 + 6896700*uk_128 + 5946488*uk_129 + 405752*uk_13 + 7301384*uk_130 + 301088*uk_131 + 8167012*uk_132 + 8468100*uk_133 + 7301384*uk_134 + 12416*uk_135 + 336784*uk_136 + 349200*uk_137 + 301088*uk_138 + 9135266*uk_139 + 11006023*uk_14 + 9472050*uk_140 + 8167012*uk_141 + 9821250*uk_142 + 8468100*uk_143 + 7301384*uk_144 + 512*uk_145 + 13888*uk_146 + 14400*uk_147 + 12416*uk_148 + 376712*uk_149 + 11411775*uk_15 + 390600*uk_150 + 336784*uk_151 + 405000*uk_152 + 349200*uk_153 + 301088*uk_154 + 10218313*uk_155 + 10595025*uk_156 + 9135266*uk_157 + 10985625*uk_158 + 9472050*uk_159 + 9839486*uk_16 + 8167012*uk_160 + 11390625*uk_161 + 9821250*uk_162 + 8468100*uk_163 + 7301384*uk_164 + 3025*uk_17 + 8690*uk_18 + 10670*uk_19 + 55*uk_2 + 440*uk_20 + 11935*uk_21 + 12375*uk_22 + 10670*uk_23 + 24964*uk_24 + 30652*uk_25 + 1264*uk_26 + 34286*uk_27 + 35550*uk_28 + 30652*uk_29 + 158*uk_3 + 37636*uk_30 + 1552*uk_31 + 42098*uk_32 + 43650*uk_33 + 37636*uk_34 + 64*uk_35 + 1736*uk_36 + 1800*uk_37 + 1552*uk_38 + 47089*uk_39 + 194*uk_4 + 48825*uk_40 + 42098*uk_41 + 50625*uk_42 + 43650*uk_43 + 37636*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 406441879838*uk_47 + 499048890434*uk_48 + 20579335688*uk_49 + 8*uk_5 + 558214480537*uk_50 + 578793816225*uk_51 + 499048890434*uk_52 + 153424975*uk_53 + 440748110*uk_54 + 541171730*uk_55 + 22316360*uk_56 + 605331265*uk_57 + 627647625*uk_58 + 541171730*uk_59 + 217*uk_6 + 1266149116*uk_60 + 1554638788*uk_61 + 64108816*uk_62 + 1738951634*uk_63 + 1803060450*uk_64 + 1554638788*uk_65 + 1908860284*uk_66 + 78715888*uk_67 + 2135168462*uk_68 + 2213884350*uk_69 + 225*uk_7 + 1908860284*uk_70 + 3246016*uk_71 + 88048184*uk_72 + 91294200*uk_73 + 78715888*uk_74 + 2388306991*uk_75 + 2476355175*uk_76 + 2135168462*uk_77 + 2567649375*uk_78 + 2213884350*uk_79 + 194*uk_8 + 1908860284*uk_80 + 166375*uk_81 + 477950*uk_82 + 586850*uk_83 + 24200*uk_84 + 656425*uk_85 + 680625*uk_86 + 586850*uk_87 + 1373020*uk_88 + 1685860*uk_89 + 2572416961*uk_9 + 69520*uk_90 + 1885730*uk_91 + 1955250*uk_92 + 1685860*uk_93 + 2069980*uk_94 + 85360*uk_95 + 2315390*uk_96 + 2400750*uk_97 + 2069980*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 96360*uk_100 + 99000*uk_101 + 69520*uk_102 + 2637855*uk_103 + 2710125*uk_104 + 1903110*uk_105 + 2784375*uk_106 + 1955250*uk_107 + 1373020*uk_108 + 2197000*uk_109 + 6593470*uk_11 + 2670200*uk_110 + 135200*uk_111 + 3701100*uk_112 + 3802500*uk_113 + 2670200*uk_114 + 3245320*uk_115 + 164320*uk_116 + 4498260*uk_117 + 4621500*uk_118 + 3245320*uk_119 + 8013602*uk_12 + 8320*uk_120 + 227760*uk_121 + 234000*uk_122 + 164320*uk_123 + 6234930*uk_124 + 6405750*uk_125 + 4498260*uk_126 + 6581250*uk_127 + 4621500*uk_128 + 3245320*uk_129 + 405752*uk_13 + 3944312*uk_130 + 199712*uk_131 + 5467116*uk_132 + 5616900*uk_133 + 3944312*uk_134 + 10112*uk_135 + 276816*uk_136 + 284400*uk_137 + 199712*uk_138 + 7577838*uk_139 + 11107461*uk_14 + 7785450*uk_140 + 5467116*uk_141 + 7998750*uk_142 + 5616900*uk_143 + 3944312*uk_144 + 512*uk_145 + 14016*uk_146 + 14400*uk_147 + 10112*uk_148 + 383688*uk_149 + 11411775*uk_15 + 394200*uk_150 + 276816*uk_151 + 405000*uk_152 + 284400*uk_153 + 199712*uk_154 + 10503459*uk_155 + 10791225*uk_156 + 7577838*uk_157 + 11086875*uk_158 + 7785450*uk_159 + 8013602*uk_16 + 5467116*uk_160 + 11390625*uk_161 + 7998750*uk_162 + 5616900*uk_163 + 3944312*uk_164 + 3025*uk_17 + 7150*uk_18 + 8690*uk_19 + 55*uk_2 + 440*uk_20 + 12045*uk_21 + 12375*uk_22 + 8690*uk_23 + 16900*uk_24 + 20540*uk_25 + 1040*uk_26 + 28470*uk_27 + 29250*uk_28 + 20540*uk_29 + 130*uk_3 + 24964*uk_30 + 1264*uk_31 + 34602*uk_32 + 35550*uk_33 + 24964*uk_34 + 64*uk_35 + 1752*uk_36 + 1800*uk_37 + 1264*uk_38 + 47961*uk_39 + 158*uk_4 + 49275*uk_40 + 34602*uk_41 + 50625*uk_42 + 35550*uk_43 + 24964*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 334414204930*uk_47 + 406441879838*uk_48 + 20579335688*uk_49 + 8*uk_5 + 563359314459*uk_50 + 578793816225*uk_51 + 406441879838*uk_52 + 153424975*uk_53 + 362640850*uk_54 + 440748110*uk_55 + 22316360*uk_56 + 610910355*uk_57 + 627647625*uk_58 + 440748110*uk_59 + 219*uk_6 + 857151100*uk_60 + 1041768260*uk_61 + 52747760*uk_62 + 1443969930*uk_63 + 1483530750*uk_64 + 1041768260*uk_65 + 1266149116*uk_66 + 64108816*uk_67 + 1754978838*uk_68 + 1803060450*uk_69 + 225*uk_7 + 1266149116*uk_70 + 3246016*uk_71 + 88859688*uk_72 + 91294200*uk_73 + 64108816*uk_74 + 2432533959*uk_75 + 2499178725*uk_76 + 1754978838*uk_77 + 2567649375*uk_78 + 1803060450*uk_79 + 158*uk_8 + 1266149116*uk_80 + 166375*uk_81 + 393250*uk_82 + 477950*uk_83 + 24200*uk_84 + 662475*uk_85 + 680625*uk_86 + 477950*uk_87 + 929500*uk_88 + 1129700*uk_89 + 2572416961*uk_9 + 57200*uk_90 + 1565850*uk_91 + 1608750*uk_92 + 1129700*uk_93 + 1373020*uk_94 + 69520*uk_95 + 1903110*uk_96 + 1955250*uk_97 + 1373020*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 97240*uk_100 + 99000*uk_101 + 57200*uk_102 + 2686255*uk_103 + 2734875*uk_104 + 1580150*uk_105 + 2784375*uk_106 + 1608750*uk_107 + 929500*uk_108 + 1331000*uk_109 + 5579090*uk_11 + 1573000*uk_110 + 96800*uk_111 + 2674100*uk_112 + 2722500*uk_113 + 1573000*uk_114 + 1859000*uk_115 + 114400*uk_116 + 3160300*uk_117 + 3217500*uk_118 + 1859000*uk_119 + 6593470*uk_12 + 7040*uk_120 + 194480*uk_121 + 198000*uk_122 + 114400*uk_123 + 5372510*uk_124 + 5469750*uk_125 + 3160300*uk_126 + 5568750*uk_127 + 3217500*uk_128 + 1859000*uk_129 + 405752*uk_13 + 2197000*uk_130 + 135200*uk_131 + 3734900*uk_132 + 3802500*uk_133 + 2197000*uk_134 + 8320*uk_135 + 229840*uk_136 + 234000*uk_137 + 135200*uk_138 + 6349330*uk_139 + 11208899*uk_14 + 6464250*uk_140 + 3734900*uk_141 + 6581250*uk_142 + 3802500*uk_143 + 2197000*uk_144 + 512*uk_145 + 14144*uk_146 + 14400*uk_147 + 8320*uk_148 + 390728*uk_149 + 11411775*uk_15 + 397800*uk_150 + 229840*uk_151 + 405000*uk_152 + 234000*uk_153 + 135200*uk_154 + 10793861*uk_155 + 10989225*uk_156 + 6349330*uk_157 + 11188125*uk_158 + 6464250*uk_159 + 6593470*uk_16 + 3734900*uk_160 + 11390625*uk_161 + 6581250*uk_162 + 3802500*uk_163 + 2197000*uk_164 + 3025*uk_17 + 6050*uk_18 + 7150*uk_19 + 55*uk_2 + 440*uk_20 + 12155*uk_21 + 12375*uk_22 + 7150*uk_23 + 12100*uk_24 + 14300*uk_25 + 880*uk_26 + 24310*uk_27 + 24750*uk_28 + 14300*uk_29 + 110*uk_3 + 16900*uk_30 + 1040*uk_31 + 28730*uk_32 + 29250*uk_33 + 16900*uk_34 + 64*uk_35 + 1768*uk_36 + 1800*uk_37 + 1040*uk_38 + 48841*uk_39 + 130*uk_4 + 49725*uk_40 + 28730*uk_41 + 50625*uk_42 + 29250*uk_43 + 16900*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 282965865710*uk_47 + 334414204930*uk_48 + 20579335688*uk_49 + 8*uk_5 + 568504148381*uk_50 + 578793816225*uk_51 + 334414204930*uk_52 + 153424975*uk_53 + 306849950*uk_54 + 362640850*uk_55 + 22316360*uk_56 + 616489445*uk_57 + 627647625*uk_58 + 362640850*uk_59 + 221*uk_6 + 613699900*uk_60 + 725281700*uk_61 + 44632720*uk_62 + 1232978890*uk_63 + 1255295250*uk_64 + 725281700*uk_65 + 857151100*uk_66 + 52747760*uk_67 + 1457156870*uk_68 + 1483530750*uk_69 + 225*uk_7 + 857151100*uk_70 + 3246016*uk_71 + 89671192*uk_72 + 91294200*uk_73 + 52747760*uk_74 + 2477166679*uk_75 + 2522002275*uk_76 + 1457156870*uk_77 + 2567649375*uk_78 + 1483530750*uk_79 + 130*uk_8 + 857151100*uk_80 + 166375*uk_81 + 332750*uk_82 + 393250*uk_83 + 24200*uk_84 + 668525*uk_85 + 680625*uk_86 + 393250*uk_87 + 665500*uk_88 + 786500*uk_89 + 2572416961*uk_9 + 48400*uk_90 + 1337050*uk_91 + 1361250*uk_92 + 786500*uk_93 + 929500*uk_94 + 57200*uk_95 + 1580150*uk_96 + 1608750*uk_97 + 929500*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 98120*uk_100 + 99000*uk_101 + 48400*uk_102 + 2735095*uk_103 + 2759625*uk_104 + 1349150*uk_105 + 2784375*uk_106 + 1361250*uk_107 + 665500*uk_108 + 941192*uk_109 + 4970462*uk_11 + 1056440*uk_110 + 76832*uk_111 + 2141692*uk_112 + 2160900*uk_113 + 1056440*uk_114 + 1185800*uk_115 + 86240*uk_116 + 2403940*uk_117 + 2425500*uk_118 + 1185800*uk_119 + 5579090*uk_12 + 6272*uk_120 + 174832*uk_121 + 176400*uk_122 + 86240*uk_123 + 4873442*uk_124 + 4917150*uk_125 + 2403940*uk_126 + 4961250*uk_127 + 2425500*uk_128 + 1185800*uk_129 + 405752*uk_13 + 1331000*uk_130 + 96800*uk_131 + 2698300*uk_132 + 2722500*uk_133 + 1331000*uk_134 + 7040*uk_135 + 196240*uk_136 + 198000*uk_137 + 96800*uk_138 + 5470190*uk_139 + 11310337*uk_14 + 5519250*uk_140 + 2698300*uk_141 + 5568750*uk_142 + 2722500*uk_143 + 1331000*uk_144 + 512*uk_145 + 14272*uk_146 + 14400*uk_147 + 7040*uk_148 + 397832*uk_149 + 11411775*uk_15 + 401400*uk_150 + 196240*uk_151 + 405000*uk_152 + 198000*uk_153 + 96800*uk_154 + 11089567*uk_155 + 11189025*uk_156 + 5470190*uk_157 + 11289375*uk_158 + 5519250*uk_159 + 5579090*uk_16 + 2698300*uk_160 + 11390625*uk_161 + 5568750*uk_162 + 2722500*uk_163 + 1331000*uk_164 + 3025*uk_17 + 5390*uk_18 + 6050*uk_19 + 55*uk_2 + 440*uk_20 + 12265*uk_21 + 12375*uk_22 + 6050*uk_23 + 9604*uk_24 + 10780*uk_25 + 784*uk_26 + 21854*uk_27 + 22050*uk_28 + 10780*uk_29 + 98*uk_3 + 12100*uk_30 + 880*uk_31 + 24530*uk_32 + 24750*uk_33 + 12100*uk_34 + 64*uk_35 + 1784*uk_36 + 1800*uk_37 + 880*uk_38 + 49729*uk_39 + 110*uk_4 + 50175*uk_40 + 24530*uk_41 + 50625*uk_42 + 24750*uk_43 + 12100*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 252096862178*uk_47 + 282965865710*uk_48 + 20579335688*uk_49 + 8*uk_5 + 573648982303*uk_50 + 578793816225*uk_51 + 282965865710*uk_52 + 153424975*uk_53 + 273375410*uk_54 + 306849950*uk_55 + 22316360*uk_56 + 622068535*uk_57 + 627647625*uk_58 + 306849950*uk_59 + 223*uk_6 + 487105276*uk_60 + 546750820*uk_61 + 39763696*uk_62 + 1108413026*uk_63 + 1118353950*uk_64 + 546750820*uk_65 + 613699900*uk_66 + 44632720*uk_67 + 1244137070*uk_68 + 1255295250*uk_69 + 225*uk_7 + 613699900*uk_70 + 3246016*uk_71 + 90482696*uk_72 + 91294200*uk_73 + 44632720*uk_74 + 2522205151*uk_75 + 2544825825*uk_76 + 1244137070*uk_77 + 2567649375*uk_78 + 1255295250*uk_79 + 110*uk_8 + 613699900*uk_80 + 166375*uk_81 + 296450*uk_82 + 332750*uk_83 + 24200*uk_84 + 674575*uk_85 + 680625*uk_86 + 332750*uk_87 + 528220*uk_88 + 592900*uk_89 + 2572416961*uk_9 + 43120*uk_90 + 1201970*uk_91 + 1212750*uk_92 + 592900*uk_93 + 665500*uk_94 + 48400*uk_95 + 1349150*uk_96 + 1361250*uk_97 + 665500*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 99000*uk_100 + 99000*uk_101 + 43120*uk_102 + 2784375*uk_103 + 2784375*uk_104 + 1212750*uk_105 + 2784375*uk_106 + 1212750*uk_107 + 528220*uk_108 + 830584*uk_109 + 4767586*uk_11 + 865928*uk_110 + 70688*uk_111 + 1988100*uk_112 + 1988100*uk_113 + 865928*uk_114 + 902776*uk_115 + 73696*uk_116 + 2072700*uk_117 + 2072700*uk_118 + 902776*uk_119 + 4970462*uk_12 + 6016*uk_120 + 169200*uk_121 + 169200*uk_122 + 73696*uk_123 + 4758750*uk_124 + 4758750*uk_125 + 2072700*uk_126 + 4758750*uk_127 + 2072700*uk_128 + 902776*uk_129 + 405752*uk_13 + 941192*uk_130 + 76832*uk_131 + 2160900*uk_132 + 2160900*uk_133 + 941192*uk_134 + 6272*uk_135 + 176400*uk_136 + 176400*uk_137 + 76832*uk_138 + 4961250*uk_139 + 11411775*uk_14 + 4961250*uk_140 + 2160900*uk_141 + 4961250*uk_142 + 2160900*uk_143 + 941192*uk_144 + 512*uk_145 + 14400*uk_146 + 14400*uk_147 + 6272*uk_148 + 405000*uk_149 + 11411775*uk_15 + 405000*uk_150 + 176400*uk_151 + 405000*uk_152 + 176400*uk_153 + 76832*uk_154 + 11390625*uk_155 + 11390625*uk_156 + 4961250*uk_157 + 11390625*uk_158 + 4961250*uk_159 + 4970462*uk_16 + 2160900*uk_160 + 11390625*uk_161 + 4961250*uk_162 + 2160900*uk_163 + 941192*uk_164 + 3025*uk_17 + 5170*uk_18 + 5390*uk_19 + 55*uk_2 + 440*uk_20 + 12375*uk_21 + 12375*uk_22 + 5390*uk_23 + 8836*uk_24 + 9212*uk_25 + 752*uk_26 + 21150*uk_27 + 21150*uk_28 + 9212*uk_29 + 94*uk_3 + 9604*uk_30 + 784*uk_31 + 22050*uk_32 + 22050*uk_33 + 9604*uk_34 + 64*uk_35 + 1800*uk_36 + 1800*uk_37 + 784*uk_38 + 50625*uk_39 + 98*uk_4 + 50625*uk_40 + 22050*uk_41 + 50625*uk_42 + 22050*uk_43 + 9604*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 241807194334*uk_47 + 252096862178*uk_48 + 20579335688*uk_49 + 8*uk_5 + 578793816225*uk_50 + 578793816225*uk_51 + 252096862178*uk_52 + 153424975*uk_53 + 262217230*uk_54 + 273375410*uk_55 + 22316360*uk_56 + 627647625*uk_57 + 627647625*uk_58 + 273375410*uk_59 + 225*uk_6 + 448153084*uk_60 + 467223428*uk_61 + 38140688*uk_62 + 1072706850*uk_63 + 1072706850*uk_64 + 467223428*uk_65 + 487105276*uk_66 + 39763696*uk_67 + 1118353950*uk_68 + 1118353950*uk_69 + 225*uk_7 + 487105276*uk_70 + 3246016*uk_71 + 91294200*uk_72 + 91294200*uk_73 + 39763696*uk_74 + 2567649375*uk_75 + 2567649375*uk_76 + 1118353950*uk_77 + 2567649375*uk_78 + 1118353950*uk_79 + 98*uk_8 + 487105276*uk_80 + 166375*uk_81 + 284350*uk_82 + 296450*uk_83 + 24200*uk_84 + 680625*uk_85 + 680625*uk_86 + 296450*uk_87 + 485980*uk_88 + 506660*uk_89 + 2572416961*uk_9 + 41360*uk_90 + 1163250*uk_91 + 1163250*uk_92 + 506660*uk_93 + 528220*uk_94 + 43120*uk_95 + 1212750*uk_96 + 1212750*uk_97 + 528220*uk_98 + 3520*uk_99, + uk_0 + 50719*uk_1 + 2789545*uk_10 + 99880*uk_100 + 99000*uk_101 + 41360*uk_102 + 2834095*uk_103 + 2809125*uk_104 + 1173590*uk_105 + 2784375*uk_106 + 1163250*uk_107 + 485980*uk_108 + 941192*uk_109 + 4970462*uk_11 + 902776*uk_110 + 76832*uk_111 + 2180108*uk_112 + 2160900*uk_113 + 902776*uk_114 + 865928*uk_115 + 73696*uk_116 + 2091124*uk_117 + 2072700*uk_118 + 865928*uk_119 + 4767586*uk_12 + 6272*uk_120 + 177968*uk_121 + 176400*uk_122 + 73696*uk_123 + 5049842*uk_124 + 5005350*uk_125 + 2091124*uk_126 + 4961250*uk_127 + 2072700*uk_128 + 865928*uk_129 + 405752*uk_13 + 830584*uk_130 + 70688*uk_131 + 2005772*uk_132 + 1988100*uk_133 + 830584*uk_134 + 6016*uk_135 + 170704*uk_136 + 169200*uk_137 + 70688*uk_138 + 4843726*uk_139 + 11513213*uk_14 + 4801050*uk_140 + 2005772*uk_141 + 4758750*uk_142 + 1988100*uk_143 + 830584*uk_144 + 512*uk_145 + 14528*uk_146 + 14400*uk_147 + 6016*uk_148 + 412232*uk_149 + 11411775*uk_15 + 408600*uk_150 + 170704*uk_151 + 405000*uk_152 + 169200*uk_153 + 70688*uk_154 + 11697083*uk_155 + 11594025*uk_156 + 4843726*uk_157 + 11491875*uk_158 + 4801050*uk_159 + 4767586*uk_16 + 2005772*uk_160 + 11390625*uk_161 + 4758750*uk_162 + 1988100*uk_163 + 830584*uk_164 + 3025*uk_17 + 5390*uk_18 + 5170*uk_19 + 55*uk_2 + 440*uk_20 + 12485*uk_21 + 12375*uk_22 + 5170*uk_23 + 9604*uk_24 + 9212*uk_25 + 784*uk_26 + 22246*uk_27 + 22050*uk_28 + 9212*uk_29 + 98*uk_3 + 8836*uk_30 + 752*uk_31 + 21338*uk_32 + 21150*uk_33 + 8836*uk_34 + 64*uk_35 + 1816*uk_36 + 1800*uk_37 + 752*uk_38 + 51529*uk_39 + 94*uk_4 + 51075*uk_40 + 21338*uk_41 + 50625*uk_42 + 21150*uk_43 + 8836*uk_44 + 130470415844959*uk_45 + 141482932855*uk_46 + 252096862178*uk_47 + 241807194334*uk_48 + 20579335688*uk_49 + 8*uk_5 + 583938650147*uk_50 + 578793816225*uk_51 + 241807194334*uk_52 + 153424975*uk_53 + 273375410*uk_54 + 262217230*uk_55 + 22316360*uk_56 + 633226715*uk_57 + 627647625*uk_58 + 262217230*uk_59 + 227*uk_6 + 487105276*uk_60 + 467223428*uk_61 + 39763696*uk_62 + 1128294874*uk_63 + 1118353950*uk_64 + 467223428*uk_65 + 448153084*uk_66 + 38140688*uk_67 + 1082242022*uk_68 + 1072706850*uk_69 + 225*uk_7 + 448153084*uk_70 + 3246016*uk_71 + 92105704*uk_72 + 91294200*uk_73 + 38140688*uk_74 + 2613499351*uk_75 + 2590472925*uk_76 + 1082242022*uk_77 + 2567649375*uk_78 + 1072706850*uk_79 + 94*uk_8 + 448153084*uk_80 + 166375*uk_81 + 296450*uk_82 + 284350*uk_83 + 24200*uk_84 + 686675*uk_85 + 680625*uk_86 + 284350*uk_87 + 528220*uk_88 + 506660*uk_89 + 2572416961*uk_9 + 43120*uk_90 + 1223530*uk_91 + 1212750*uk_92 + 506660*uk_93 + 485980*uk_94 + 41360*uk_95 + 1173590*uk_96 + 1163250*uk_97 + 485980*uk_98 + 3520*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 396900*uk_100 + 1367100*uk_101 + 250047*uk_103 + 861273*uk_104 + 2966607*uk_106 + 64000*uk_109 + 1894120*uk_11 + 27200*uk_110 + 160000*uk_111 + 100800*uk_112 + 347200*uk_113 + 11560*uk_115 + 68000*uk_116 + 42840*uk_117 + 147560*uk_118 + 805001*uk_12 + 400000*uk_120 + 252000*uk_121 + 868000*uk_122 + 158760*uk_124 + 546840*uk_125 + 1883560*uk_127 + 4735300*uk_13 + 4913*uk_130 + 28900*uk_131 + 18207*uk_132 + 62713*uk_133 + 170000*uk_135 + 107100*uk_136 + 368900*uk_137 + 67473*uk_139 + 2983239*uk_14 + 232407*uk_140 + 800513*uk_142 + 1000000*uk_145 + 630000*uk_146 + 2170000*uk_147 + 396900*uk_149 + 10275601*uk_15 + 1367100*uk_150 + 4708900*uk_152 + 250047*uk_155 + 861273*uk_156 + 2966607*uk_158 + 10218313*uk_161 + 3969*uk_17 + 2520*uk_18 + 1071*uk_19 + 63*uk_2 + 6300*uk_20 + 3969*uk_21 + 13671*uk_22 + 1600*uk_24 + 680*uk_25 + 4000*uk_26 + 2520*uk_27 + 8680*uk_28 + 40*uk_3 + 289*uk_30 + 1700*uk_31 + 1071*uk_32 + 3689*uk_33 + 10000*uk_35 + 6300*uk_36 + 21700*uk_37 + 3969*uk_39 + 17*uk_4 + 13671*uk_40 + 47089*uk_42 + 106179944855977*uk_45 + 141265316367*uk_46 + 89692264360*uk_47 + 38119212353*uk_48 + 224230660900*uk_49 + 100*uk_5 + 141265316367*uk_50 + 486580534153*uk_51 + 187944057*uk_53 + 119329560*uk_54 + 50715063*uk_55 + 298323900*uk_56 + 187944057*uk_57 + 647362863*uk_58 + 63*uk_6 + 75764800*uk_60 + 32200040*uk_61 + 189412000*uk_62 + 119329560*uk_63 + 411024040*uk_64 + 13685017*uk_66 + 80500100*uk_67 + 50715063*uk_68 + 174685217*uk_69 + 217*uk_7 + 473530000*uk_71 + 298323900*uk_72 + 1027560100*uk_73 + 187944057*uk_75 + 647362863*uk_76 + 2229805417*uk_78 + 250047*uk_81 + 158760*uk_82 + 67473*uk_83 + 396900*uk_84 + 250047*uk_85 + 861273*uk_86 + 100800*uk_88 + 42840*uk_89 + 2242306609*uk_9 + 252000*uk_90 + 158760*uk_91 + 546840*uk_92 + 18207*uk_94 + 107100*uk_95 + 67473*uk_96 + 232407*uk_97 + 630000*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 376740*uk_100 + 1257732*uk_101 + 231840*uk_102 + 266175*uk_103 + 888615*uk_104 + 163800*uk_105 + 2966607*uk_106 + 546840*uk_107 + 100800*uk_108 + 35937*uk_109 + 1562649*uk_11 + 43560*uk_110 + 100188*uk_111 + 70785*uk_112 + 236313*uk_113 + 43560*uk_114 + 52800*uk_115 + 121440*uk_116 + 85800*uk_117 + 286440*uk_118 + 52800*uk_119 + 1894120*uk_12 + 279312*uk_120 + 197340*uk_121 + 658812*uk_122 + 121440*uk_123 + 139425*uk_124 + 465465*uk_125 + 85800*uk_126 + 1553937*uk_127 + 286440*uk_128 + 52800*uk_129 + 4356476*uk_13 + 64000*uk_130 + 147200*uk_131 + 104000*uk_132 + 347200*uk_133 + 64000*uk_134 + 338560*uk_135 + 239200*uk_136 + 798560*uk_137 + 147200*uk_138 + 169000*uk_139 + 3077945*uk_14 + 564200*uk_140 + 104000*uk_141 + 1883560*uk_142 + 347200*uk_143 + 64000*uk_144 + 778688*uk_145 + 550160*uk_146 + 1836688*uk_147 + 338560*uk_148 + 388700*uk_149 + 10275601*uk_15 + 1297660*uk_150 + 239200*uk_151 + 4332188*uk_152 + 798560*uk_153 + 147200*uk_154 + 274625*uk_155 + 916825*uk_156 + 169000*uk_157 + 3060785*uk_158 + 564200*uk_159 + 1894120*uk_16 + 104000*uk_160 + 10218313*uk_161 + 1883560*uk_162 + 347200*uk_163 + 64000*uk_164 + 3969*uk_17 + 2079*uk_18 + 2520*uk_19 + 63*uk_2 + 5796*uk_20 + 4095*uk_21 + 13671*uk_22 + 2520*uk_23 + 1089*uk_24 + 1320*uk_25 + 3036*uk_26 + 2145*uk_27 + 7161*uk_28 + 1320*uk_29 + 33*uk_3 + 1600*uk_30 + 3680*uk_31 + 2600*uk_32 + 8680*uk_33 + 1600*uk_34 + 8464*uk_35 + 5980*uk_36 + 19964*uk_37 + 3680*uk_38 + 4225*uk_39 + 40*uk_4 + 14105*uk_40 + 2600*uk_41 + 47089*uk_42 + 8680*uk_43 + 1600*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 73996118097*uk_47 + 89692264360*uk_48 + 206292208028*uk_49 + 92*uk_5 + 145749929585*uk_50 + 486580534153*uk_51 + 89692264360*uk_52 + 187944057*uk_53 + 98446887*uk_54 + 119329560*uk_55 + 274457988*uk_56 + 193910535*uk_57 + 647362863*uk_58 + 119329560*uk_59 + 65*uk_6 + 51567417*uk_60 + 62505960*uk_61 + 143763708*uk_62 + 101572185*uk_63 + 339094833*uk_64 + 62505960*uk_65 + 75764800*uk_66 + 174259040*uk_67 + 123117800*uk_68 + 411024040*uk_69 + 217*uk_7 + 75764800*uk_70 + 400795792*uk_71 + 283170940*uk_72 + 945355292*uk_73 + 174259040*uk_74 + 200066425*uk_75 + 667914065*uk_76 + 123117800*uk_77 + 2229805417*uk_78 + 411024040*uk_79 + 40*uk_8 + 75764800*uk_80 + 250047*uk_81 + 130977*uk_82 + 158760*uk_83 + 365148*uk_84 + 257985*uk_85 + 861273*uk_86 + 158760*uk_87 + 68607*uk_88 + 83160*uk_89 + 2242306609*uk_9 + 191268*uk_90 + 135135*uk_91 + 451143*uk_92 + 83160*uk_93 + 100800*uk_94 + 231840*uk_95 + 163800*uk_96 + 546840*uk_97 + 100800*uk_98 + 533232*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 371448*uk_100 + 1203048*uk_101 + 182952*uk_102 + 282807*uk_103 + 915957*uk_104 + 139293*uk_105 + 2966607*uk_106 + 451143*uk_107 + 68607*uk_108 + 132651*uk_109 + 2415003*uk_11 + 85833*uk_110 + 228888*uk_111 + 174267*uk_112 + 564417*uk_113 + 85833*uk_114 + 55539*uk_115 + 148104*uk_116 + 112761*uk_117 + 365211*uk_118 + 55539*uk_119 + 1562649*uk_12 + 394944*uk_120 + 300696*uk_121 + 973896*uk_122 + 148104*uk_123 + 228939*uk_124 + 741489*uk_125 + 112761*uk_126 + 2401539*uk_127 + 365211*uk_128 + 55539*uk_129 + 4167064*uk_13 + 35937*uk_130 + 95832*uk_131 + 72963*uk_132 + 236313*uk_133 + 35937*uk_134 + 255552*uk_135 + 194568*uk_136 + 630168*uk_137 + 95832*uk_138 + 148137*uk_139 + 3172651*uk_14 + 479787*uk_140 + 72963*uk_141 + 1553937*uk_142 + 236313*uk_143 + 35937*uk_144 + 681472*uk_145 + 518848*uk_146 + 1680448*uk_147 + 255552*uk_148 + 395032*uk_149 + 10275601*uk_15 + 1279432*uk_150 + 194568*uk_151 + 4143832*uk_152 + 630168*uk_153 + 95832*uk_154 + 300763*uk_155 + 974113*uk_156 + 148137*uk_157 + 3154963*uk_158 + 479787*uk_159 + 1562649*uk_16 + 72963*uk_160 + 10218313*uk_161 + 1553937*uk_162 + 236313*uk_163 + 35937*uk_164 + 3969*uk_17 + 3213*uk_18 + 2079*uk_19 + 63*uk_2 + 5544*uk_20 + 4221*uk_21 + 13671*uk_22 + 2079*uk_23 + 2601*uk_24 + 1683*uk_25 + 4488*uk_26 + 3417*uk_27 + 11067*uk_28 + 1683*uk_29 + 51*uk_3 + 1089*uk_30 + 2904*uk_31 + 2211*uk_32 + 7161*uk_33 + 1089*uk_34 + 7744*uk_35 + 5896*uk_36 + 19096*uk_37 + 2904*uk_38 + 4489*uk_39 + 33*uk_4 + 14539*uk_40 + 2211*uk_41 + 47089*uk_42 + 7161*uk_43 + 1089*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 114357637059*uk_47 + 73996118097*uk_48 + 197322981592*uk_49 + 88*uk_5 + 150234542803*uk_50 + 486580534153*uk_51 + 73996118097*uk_52 + 187944057*uk_53 + 152145189*uk_54 + 98446887*uk_55 + 262525032*uk_56 + 199877013*uk_57 + 647362863*uk_58 + 98446887*uk_59 + 67*uk_6 + 123165153*uk_60 + 79695099*uk_61 + 212520264*uk_62 + 161805201*uk_63 + 524055651*uk_64 + 79695099*uk_65 + 51567417*uk_66 + 137513112*uk_67 + 104697483*uk_68 + 339094833*uk_69 + 217*uk_7 + 51567417*uk_70 + 366701632*uk_71 + 279193288*uk_72 + 904252888*uk_73 + 137513112*uk_74 + 212567617*uk_75 + 688465267*uk_76 + 104697483*uk_77 + 2229805417*uk_78 + 339094833*uk_79 + 33*uk_8 + 51567417*uk_80 + 250047*uk_81 + 202419*uk_82 + 130977*uk_83 + 349272*uk_84 + 265923*uk_85 + 861273*uk_86 + 130977*uk_87 + 163863*uk_88 + 106029*uk_89 + 2242306609*uk_9 + 282744*uk_90 + 215271*uk_91 + 697221*uk_92 + 106029*uk_93 + 68607*uk_94 + 182952*uk_95 + 139293*uk_96 + 451143*uk_97 + 68607*uk_98 + 487872*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 347760*uk_100 + 1093680*uk_101 + 257040*uk_102 + 299943*uk_103 + 943299*uk_104 + 221697*uk_105 + 2966607*uk_106 + 697221*uk_107 + 163863*uk_108 + 6859*uk_109 + 899707*uk_11 + 18411*uk_110 + 28880*uk_111 + 24909*uk_112 + 78337*uk_113 + 18411*uk_114 + 49419*uk_115 + 77520*uk_116 + 66861*uk_117 + 210273*uk_118 + 49419*uk_119 + 2415003*uk_12 + 121600*uk_120 + 104880*uk_121 + 329840*uk_122 + 77520*uk_123 + 90459*uk_124 + 284487*uk_125 + 66861*uk_126 + 894691*uk_127 + 210273*uk_128 + 49419*uk_129 + 3788240*uk_13 + 132651*uk_130 + 208080*uk_131 + 179469*uk_132 + 564417*uk_133 + 132651*uk_134 + 326400*uk_135 + 281520*uk_136 + 885360*uk_137 + 208080*uk_138 + 242811*uk_139 + 3267357*uk_14 + 763623*uk_140 + 179469*uk_141 + 2401539*uk_142 + 564417*uk_143 + 132651*uk_144 + 512000*uk_145 + 441600*uk_146 + 1388800*uk_147 + 326400*uk_148 + 380880*uk_149 + 10275601*uk_15 + 1197840*uk_150 + 281520*uk_151 + 3767120*uk_152 + 885360*uk_153 + 208080*uk_154 + 328509*uk_155 + 1033137*uk_156 + 242811*uk_157 + 3249141*uk_158 + 763623*uk_159 + 2415003*uk_16 + 179469*uk_160 + 10218313*uk_161 + 2401539*uk_162 + 564417*uk_163 + 132651*uk_164 + 3969*uk_17 + 1197*uk_18 + 3213*uk_19 + 63*uk_2 + 5040*uk_20 + 4347*uk_21 + 13671*uk_22 + 3213*uk_23 + 361*uk_24 + 969*uk_25 + 1520*uk_26 + 1311*uk_27 + 4123*uk_28 + 969*uk_29 + 19*uk_3 + 2601*uk_30 + 4080*uk_31 + 3519*uk_32 + 11067*uk_33 + 2601*uk_34 + 6400*uk_35 + 5520*uk_36 + 17360*uk_37 + 4080*uk_38 + 4761*uk_39 + 51*uk_4 + 14973*uk_40 + 3519*uk_41 + 47089*uk_42 + 11067*uk_43 + 2601*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 42603825571*uk_47 + 114357637059*uk_48 + 179384528720*uk_49 + 80*uk_5 + 154719156021*uk_50 + 486580534153*uk_51 + 114357637059*uk_52 + 187944057*uk_53 + 56681541*uk_54 + 152145189*uk_55 + 238659120*uk_56 + 205843491*uk_57 + 647362863*uk_58 + 152145189*uk_59 + 69*uk_6 + 17094433*uk_60 + 45885057*uk_61 + 71976560*uk_62 + 62079783*uk_63 + 195236419*uk_64 + 45885057*uk_65 + 123165153*uk_66 + 193200240*uk_67 + 166635207*uk_68 + 524055651*uk_69 + 217*uk_7 + 123165153*uk_70 + 303059200*uk_71 + 261388560*uk_72 + 822048080*uk_73 + 193200240*uk_74 + 225447633*uk_75 + 709016469*uk_76 + 166635207*uk_77 + 2229805417*uk_78 + 524055651*uk_79 + 51*uk_8 + 123165153*uk_80 + 250047*uk_81 + 75411*uk_82 + 202419*uk_83 + 317520*uk_84 + 273861*uk_85 + 861273*uk_86 + 202419*uk_87 + 22743*uk_88 + 61047*uk_89 + 2242306609*uk_9 + 95760*uk_90 + 82593*uk_91 + 259749*uk_92 + 61047*uk_93 + 163863*uk_94 + 257040*uk_95 + 221697*uk_96 + 697221*uk_97 + 163863*uk_98 + 403200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 357840*uk_100 + 1093680*uk_101 + 95760*uk_102 + 317583*uk_103 + 970641*uk_104 + 84987*uk_105 + 2966607*uk_106 + 259749*uk_107 + 22743*uk_108 + 300763*uk_109 + 3172651*uk_11 + 85291*uk_110 + 359120*uk_111 + 318719*uk_112 + 974113*uk_113 + 85291*uk_114 + 24187*uk_115 + 101840*uk_116 + 90383*uk_117 + 276241*uk_118 + 24187*uk_119 + 899707*uk_12 + 428800*uk_120 + 380560*uk_121 + 1163120*uk_122 + 101840*uk_123 + 337747*uk_124 + 1032269*uk_125 + 90383*uk_126 + 3154963*uk_127 + 276241*uk_128 + 24187*uk_129 + 3788240*uk_13 + 6859*uk_130 + 28880*uk_131 + 25631*uk_132 + 78337*uk_133 + 6859*uk_134 + 121600*uk_135 + 107920*uk_136 + 329840*uk_137 + 28880*uk_138 + 95779*uk_139 + 3362063*uk_14 + 292733*uk_140 + 25631*uk_141 + 894691*uk_142 + 78337*uk_143 + 6859*uk_144 + 512000*uk_145 + 454400*uk_146 + 1388800*uk_147 + 121600*uk_148 + 403280*uk_149 + 10275601*uk_15 + 1232560*uk_150 + 107920*uk_151 + 3767120*uk_152 + 329840*uk_153 + 28880*uk_154 + 357911*uk_155 + 1093897*uk_156 + 95779*uk_157 + 3343319*uk_158 + 292733*uk_159 + 899707*uk_16 + 25631*uk_160 + 10218313*uk_161 + 894691*uk_162 + 78337*uk_163 + 6859*uk_164 + 3969*uk_17 + 4221*uk_18 + 1197*uk_19 + 63*uk_2 + 5040*uk_20 + 4473*uk_21 + 13671*uk_22 + 1197*uk_23 + 4489*uk_24 + 1273*uk_25 + 5360*uk_26 + 4757*uk_27 + 14539*uk_28 + 1273*uk_29 + 67*uk_3 + 361*uk_30 + 1520*uk_31 + 1349*uk_32 + 4123*uk_33 + 361*uk_34 + 6400*uk_35 + 5680*uk_36 + 17360*uk_37 + 1520*uk_38 + 5041*uk_39 + 19*uk_4 + 15407*uk_40 + 1349*uk_41 + 47089*uk_42 + 4123*uk_43 + 361*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 150234542803*uk_47 + 42603825571*uk_48 + 179384528720*uk_49 + 80*uk_5 + 159203769239*uk_50 + 486580534153*uk_51 + 42603825571*uk_52 + 187944057*uk_53 + 199877013*uk_54 + 56681541*uk_55 + 238659120*uk_56 + 211809969*uk_57 + 647362863*uk_58 + 56681541*uk_59 + 71*uk_6 + 212567617*uk_60 + 60280369*uk_61 + 253812080*uk_62 + 225258221*uk_63 + 688465267*uk_64 + 60280369*uk_65 + 17094433*uk_66 + 71976560*uk_67 + 63879197*uk_68 + 195236419*uk_69 + 217*uk_7 + 17094433*uk_70 + 303059200*uk_71 + 268965040*uk_72 + 822048080*uk_73 + 71976560*uk_74 + 238706473*uk_75 + 729567671*uk_76 + 63879197*uk_77 + 2229805417*uk_78 + 195236419*uk_79 + 19*uk_8 + 17094433*uk_80 + 250047*uk_81 + 265923*uk_82 + 75411*uk_83 + 317520*uk_84 + 281799*uk_85 + 861273*uk_86 + 75411*uk_87 + 282807*uk_88 + 80199*uk_89 + 2242306609*uk_9 + 337680*uk_90 + 299691*uk_91 + 915957*uk_92 + 80199*uk_93 + 22743*uk_94 + 95760*uk_95 + 84987*uk_96 + 259749*uk_97 + 22743*uk_98 + 403200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 331128*uk_100 + 984312*uk_101 + 303912*uk_102 + 335727*uk_103 + 997983*uk_104 + 308133*uk_105 + 2966607*uk_106 + 915957*uk_107 + 282807*uk_108 + 117649*uk_109 + 2320297*uk_11 + 160867*uk_110 + 172872*uk_111 + 175273*uk_112 + 521017*uk_113 + 160867*uk_114 + 219961*uk_115 + 236376*uk_116 + 239659*uk_117 + 712411*uk_118 + 219961*uk_119 + 3172651*uk_12 + 254016*uk_120 + 257544*uk_121 + 765576*uk_122 + 236376*uk_123 + 261121*uk_124 + 776209*uk_125 + 239659*uk_126 + 2307361*uk_127 + 712411*uk_128 + 219961*uk_129 + 3409416*uk_13 + 300763*uk_130 + 323208*uk_131 + 327697*uk_132 + 974113*uk_133 + 300763*uk_134 + 347328*uk_135 + 352152*uk_136 + 1046808*uk_137 + 323208*uk_138 + 357043*uk_139 + 3456769*uk_14 + 1061347*uk_140 + 327697*uk_141 + 3154963*uk_142 + 974113*uk_143 + 300763*uk_144 + 373248*uk_145 + 378432*uk_146 + 1124928*uk_147 + 347328*uk_148 + 383688*uk_149 + 10275601*uk_15 + 1140552*uk_150 + 352152*uk_151 + 3390408*uk_152 + 1046808*uk_153 + 323208*uk_154 + 389017*uk_155 + 1156393*uk_156 + 357043*uk_157 + 3437497*uk_158 + 1061347*uk_159 + 3172651*uk_16 + 327697*uk_160 + 10218313*uk_161 + 3154963*uk_162 + 974113*uk_163 + 300763*uk_164 + 3969*uk_17 + 3087*uk_18 + 4221*uk_19 + 63*uk_2 + 4536*uk_20 + 4599*uk_21 + 13671*uk_22 + 4221*uk_23 + 2401*uk_24 + 3283*uk_25 + 3528*uk_26 + 3577*uk_27 + 10633*uk_28 + 3283*uk_29 + 49*uk_3 + 4489*uk_30 + 4824*uk_31 + 4891*uk_32 + 14539*uk_33 + 4489*uk_34 + 5184*uk_35 + 5256*uk_36 + 15624*uk_37 + 4824*uk_38 + 5329*uk_39 + 67*uk_4 + 15841*uk_40 + 4891*uk_41 + 47089*uk_42 + 14539*uk_43 + 4489*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 109873023841*uk_47 + 150234542803*uk_48 + 161446075848*uk_49 + 72*uk_5 + 163688382457*uk_50 + 486580534153*uk_51 + 150234542803*uk_52 + 187944057*uk_53 + 146178711*uk_54 + 199877013*uk_55 + 214793208*uk_56 + 217776447*uk_57 + 647362863*uk_58 + 199877013*uk_59 + 73*uk_6 + 113694553*uk_60 + 155459899*uk_61 + 167061384*uk_62 + 169381681*uk_63 + 503504449*uk_64 + 155459899*uk_65 + 212567617*uk_66 + 228430872*uk_67 + 231603523*uk_68 + 688465267*uk_69 + 217*uk_7 + 212567617*uk_70 + 245477952*uk_71 + 248887368*uk_72 + 739843272*uk_73 + 228430872*uk_74 + 252344137*uk_75 + 750118873*uk_76 + 231603523*uk_77 + 2229805417*uk_78 + 688465267*uk_79 + 67*uk_8 + 212567617*uk_80 + 250047*uk_81 + 194481*uk_82 + 265923*uk_83 + 285768*uk_84 + 289737*uk_85 + 861273*uk_86 + 265923*uk_87 + 151263*uk_88 + 206829*uk_89 + 2242306609*uk_9 + 222264*uk_90 + 225351*uk_91 + 669879*uk_92 + 206829*uk_93 + 282807*uk_94 + 303912*uk_95 + 308133*uk_96 + 915957*uk_97 + 282807*uk_98 + 326592*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 321300*uk_100 + 929628*uk_101 + 209916*uk_102 + 354375*uk_103 + 1025325*uk_104 + 231525*uk_105 + 2966607*uk_106 + 669879*uk_107 + 151263*uk_108 + 21952*uk_109 + 1325884*uk_11 + 38416*uk_110 + 53312*uk_111 + 58800*uk_112 + 170128*uk_113 + 38416*uk_114 + 67228*uk_115 + 93296*uk_116 + 102900*uk_117 + 297724*uk_118 + 67228*uk_119 + 2320297*uk_12 + 129472*uk_120 + 142800*uk_121 + 413168*uk_122 + 93296*uk_123 + 157500*uk_124 + 455700*uk_125 + 102900*uk_126 + 1318492*uk_127 + 297724*uk_128 + 67228*uk_129 + 3220004*uk_13 + 117649*uk_130 + 163268*uk_131 + 180075*uk_132 + 521017*uk_133 + 117649*uk_134 + 226576*uk_135 + 249900*uk_136 + 723044*uk_137 + 163268*uk_138 + 275625*uk_139 + 3551475*uk_14 + 797475*uk_140 + 180075*uk_141 + 2307361*uk_142 + 521017*uk_143 + 117649*uk_144 + 314432*uk_145 + 346800*uk_146 + 1003408*uk_147 + 226576*uk_148 + 382500*uk_149 + 10275601*uk_15 + 1106700*uk_150 + 249900*uk_151 + 3202052*uk_152 + 723044*uk_153 + 163268*uk_154 + 421875*uk_155 + 1220625*uk_156 + 275625*uk_157 + 3531675*uk_158 + 797475*uk_159 + 2320297*uk_16 + 180075*uk_160 + 10218313*uk_161 + 2307361*uk_162 + 521017*uk_163 + 117649*uk_164 + 3969*uk_17 + 1764*uk_18 + 3087*uk_19 + 63*uk_2 + 4284*uk_20 + 4725*uk_21 + 13671*uk_22 + 3087*uk_23 + 784*uk_24 + 1372*uk_25 + 1904*uk_26 + 2100*uk_27 + 6076*uk_28 + 1372*uk_29 + 28*uk_3 + 2401*uk_30 + 3332*uk_31 + 3675*uk_32 + 10633*uk_33 + 2401*uk_34 + 4624*uk_35 + 5100*uk_36 + 14756*uk_37 + 3332*uk_38 + 5625*uk_39 + 49*uk_4 + 16275*uk_40 + 3675*uk_41 + 47089*uk_42 + 10633*uk_43 + 2401*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 62784585052*uk_47 + 109873023841*uk_48 + 152476849412*uk_49 + 68*uk_5 + 168172995675*uk_50 + 486580534153*uk_51 + 109873023841*uk_52 + 187944057*uk_53 + 83530692*uk_54 + 146178711*uk_55 + 202860252*uk_56 + 223742925*uk_57 + 647362863*uk_58 + 146178711*uk_59 + 75*uk_6 + 37124752*uk_60 + 64968316*uk_61 + 90160112*uk_62 + 99441300*uk_63 + 287716828*uk_64 + 64968316*uk_65 + 113694553*uk_66 + 157780196*uk_67 + 174022275*uk_68 + 503504449*uk_69 + 217*uk_7 + 113694553*uk_70 + 218960272*uk_71 + 241500300*uk_72 + 698740868*uk_73 + 157780196*uk_74 + 266360625*uk_75 + 770670075*uk_76 + 174022275*uk_77 + 2229805417*uk_78 + 503504449*uk_79 + 49*uk_8 + 113694553*uk_80 + 250047*uk_81 + 111132*uk_82 + 194481*uk_83 + 269892*uk_84 + 297675*uk_85 + 861273*uk_86 + 194481*uk_87 + 49392*uk_88 + 86436*uk_89 + 2242306609*uk_9 + 119952*uk_90 + 132300*uk_91 + 382788*uk_92 + 86436*uk_93 + 151263*uk_94 + 209916*uk_95 + 231525*uk_96 + 669879*uk_97 + 151263*uk_98 + 291312*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 329868*uk_100 + 929628*uk_101 + 119952*uk_102 + 373527*uk_103 + 1052667*uk_104 + 135828*uk_105 + 2966607*uk_106 + 382788*uk_107 + 49392*uk_108 + 421875*uk_109 + 3551475*uk_11 + 157500*uk_110 + 382500*uk_111 + 433125*uk_112 + 1220625*uk_113 + 157500*uk_114 + 58800*uk_115 + 142800*uk_116 + 161700*uk_117 + 455700*uk_118 + 58800*uk_119 + 1325884*uk_12 + 346800*uk_120 + 392700*uk_121 + 1106700*uk_122 + 142800*uk_123 + 444675*uk_124 + 1253175*uk_125 + 161700*uk_126 + 3531675*uk_127 + 455700*uk_128 + 58800*uk_129 + 3220004*uk_13 + 21952*uk_130 + 53312*uk_131 + 60368*uk_132 + 170128*uk_133 + 21952*uk_134 + 129472*uk_135 + 146608*uk_136 + 413168*uk_137 + 53312*uk_138 + 166012*uk_139 + 3646181*uk_14 + 467852*uk_140 + 60368*uk_141 + 1318492*uk_142 + 170128*uk_143 + 21952*uk_144 + 314432*uk_145 + 356048*uk_146 + 1003408*uk_147 + 129472*uk_148 + 403172*uk_149 + 10275601*uk_15 + 1136212*uk_150 + 146608*uk_151 + 3202052*uk_152 + 413168*uk_153 + 53312*uk_154 + 456533*uk_155 + 1286593*uk_156 + 166012*uk_157 + 3625853*uk_158 + 467852*uk_159 + 1325884*uk_16 + 60368*uk_160 + 10218313*uk_161 + 1318492*uk_162 + 170128*uk_163 + 21952*uk_164 + 3969*uk_17 + 4725*uk_18 + 1764*uk_19 + 63*uk_2 + 4284*uk_20 + 4851*uk_21 + 13671*uk_22 + 1764*uk_23 + 5625*uk_24 + 2100*uk_25 + 5100*uk_26 + 5775*uk_27 + 16275*uk_28 + 2100*uk_29 + 75*uk_3 + 784*uk_30 + 1904*uk_31 + 2156*uk_32 + 6076*uk_33 + 784*uk_34 + 4624*uk_35 + 5236*uk_36 + 14756*uk_37 + 1904*uk_38 + 5929*uk_39 + 28*uk_4 + 16709*uk_40 + 2156*uk_41 + 47089*uk_42 + 6076*uk_43 + 784*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 168172995675*uk_47 + 62784585052*uk_48 + 152476849412*uk_49 + 68*uk_5 + 172657608893*uk_50 + 486580534153*uk_51 + 62784585052*uk_52 + 187944057*uk_53 + 223742925*uk_54 + 83530692*uk_55 + 202860252*uk_56 + 229709403*uk_57 + 647362863*uk_58 + 83530692*uk_59 + 77*uk_6 + 266360625*uk_60 + 99441300*uk_61 + 241500300*uk_62 + 273463575*uk_63 + 770670075*uk_64 + 99441300*uk_65 + 37124752*uk_66 + 90160112*uk_67 + 102093068*uk_68 + 287716828*uk_69 + 217*uk_7 + 37124752*uk_70 + 218960272*uk_71 + 247940308*uk_72 + 698740868*uk_73 + 90160112*uk_74 + 280755937*uk_75 + 791221277*uk_76 + 102093068*uk_77 + 2229805417*uk_78 + 287716828*uk_79 + 28*uk_8 + 37124752*uk_80 + 250047*uk_81 + 297675*uk_82 + 111132*uk_83 + 269892*uk_84 + 305613*uk_85 + 861273*uk_86 + 111132*uk_87 + 354375*uk_88 + 132300*uk_89 + 2242306609*uk_9 + 321300*uk_90 + 363825*uk_91 + 1025325*uk_92 + 132300*uk_93 + 49392*uk_94 + 119952*uk_95 + 135828*uk_96 + 382788*uk_97 + 49392*uk_98 + 291312*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 298620*uk_100 + 820260*uk_101 + 283500*uk_102 + 393183*uk_103 + 1080009*uk_104 + 373275*uk_105 + 2966607*uk_106 + 1025325*uk_107 + 354375*uk_108 + 32768*uk_109 + 1515296*uk_11 + 76800*uk_110 + 61440*uk_111 + 80896*uk_112 + 222208*uk_113 + 76800*uk_114 + 180000*uk_115 + 144000*uk_116 + 189600*uk_117 + 520800*uk_118 + 180000*uk_119 + 3551475*uk_12 + 115200*uk_120 + 151680*uk_121 + 416640*uk_122 + 144000*uk_123 + 199712*uk_124 + 548576*uk_125 + 189600*uk_126 + 1506848*uk_127 + 520800*uk_128 + 180000*uk_129 + 2841180*uk_13 + 421875*uk_130 + 337500*uk_131 + 444375*uk_132 + 1220625*uk_133 + 421875*uk_134 + 270000*uk_135 + 355500*uk_136 + 976500*uk_137 + 337500*uk_138 + 468075*uk_139 + 3740887*uk_14 + 1285725*uk_140 + 444375*uk_141 + 3531675*uk_142 + 1220625*uk_143 + 421875*uk_144 + 216000*uk_145 + 284400*uk_146 + 781200*uk_147 + 270000*uk_148 + 374460*uk_149 + 10275601*uk_15 + 1028580*uk_150 + 355500*uk_151 + 2825340*uk_152 + 976500*uk_153 + 337500*uk_154 + 493039*uk_155 + 1354297*uk_156 + 468075*uk_157 + 3720031*uk_158 + 1285725*uk_159 + 3551475*uk_16 + 444375*uk_160 + 10218313*uk_161 + 3531675*uk_162 + 1220625*uk_163 + 421875*uk_164 + 3969*uk_17 + 2016*uk_18 + 4725*uk_19 + 63*uk_2 + 3780*uk_20 + 4977*uk_21 + 13671*uk_22 + 4725*uk_23 + 1024*uk_24 + 2400*uk_25 + 1920*uk_26 + 2528*uk_27 + 6944*uk_28 + 2400*uk_29 + 32*uk_3 + 5625*uk_30 + 4500*uk_31 + 5925*uk_32 + 16275*uk_33 + 5625*uk_34 + 3600*uk_35 + 4740*uk_36 + 13020*uk_37 + 4500*uk_38 + 6241*uk_39 + 75*uk_4 + 17143*uk_40 + 5925*uk_41 + 47089*uk_42 + 16275*uk_43 + 5625*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 71753811488*uk_47 + 168172995675*uk_48 + 134538396540*uk_49 + 60*uk_5 + 177142222111*uk_50 + 486580534153*uk_51 + 168172995675*uk_52 + 187944057*uk_53 + 95463648*uk_54 + 223742925*uk_55 + 178994340*uk_56 + 235675881*uk_57 + 647362863*uk_58 + 223742925*uk_59 + 79*uk_6 + 48489472*uk_60 + 113647200*uk_61 + 90917760*uk_62 + 119708384*uk_63 + 328819232*uk_64 + 113647200*uk_65 + 266360625*uk_66 + 213088500*uk_67 + 280566525*uk_68 + 770670075*uk_69 + 217*uk_7 + 266360625*uk_70 + 170470800*uk_71 + 224453220*uk_72 + 616536060*uk_73 + 213088500*uk_74 + 295530073*uk_75 + 811772479*uk_76 + 280566525*uk_77 + 2229805417*uk_78 + 770670075*uk_79 + 75*uk_8 + 266360625*uk_80 + 250047*uk_81 + 127008*uk_82 + 297675*uk_83 + 238140*uk_84 + 313551*uk_85 + 861273*uk_86 + 297675*uk_87 + 64512*uk_88 + 151200*uk_89 + 2242306609*uk_9 + 120960*uk_90 + 159264*uk_91 + 437472*uk_92 + 151200*uk_93 + 354375*uk_94 + 283500*uk_95 + 373275*uk_96 + 1025325*uk_97 + 354375*uk_98 + 226800*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 306180*uk_100 + 820260*uk_101 + 120960*uk_102 + 413343*uk_103 + 1107351*uk_104 + 163296*uk_105 + 2966607*uk_106 + 437472*uk_107 + 64512*uk_108 + 117649*uk_109 + 2320297*uk_11 + 76832*uk_110 + 144060*uk_111 + 194481*uk_112 + 521017*uk_113 + 76832*uk_114 + 50176*uk_115 + 94080*uk_116 + 127008*uk_117 + 340256*uk_118 + 50176*uk_119 + 1515296*uk_12 + 176400*uk_120 + 238140*uk_121 + 637980*uk_122 + 94080*uk_123 + 321489*uk_124 + 861273*uk_125 + 127008*uk_126 + 2307361*uk_127 + 340256*uk_128 + 50176*uk_129 + 2841180*uk_13 + 32768*uk_130 + 61440*uk_131 + 82944*uk_132 + 222208*uk_133 + 32768*uk_134 + 115200*uk_135 + 155520*uk_136 + 416640*uk_137 + 61440*uk_138 + 209952*uk_139 + 3835593*uk_14 + 562464*uk_140 + 82944*uk_141 + 1506848*uk_142 + 222208*uk_143 + 32768*uk_144 + 216000*uk_145 + 291600*uk_146 + 781200*uk_147 + 115200*uk_148 + 393660*uk_149 + 10275601*uk_15 + 1054620*uk_150 + 155520*uk_151 + 2825340*uk_152 + 416640*uk_153 + 61440*uk_154 + 531441*uk_155 + 1423737*uk_156 + 209952*uk_157 + 3814209*uk_158 + 562464*uk_159 + 1515296*uk_16 + 82944*uk_160 + 10218313*uk_161 + 1506848*uk_162 + 222208*uk_163 + 32768*uk_164 + 3969*uk_17 + 3087*uk_18 + 2016*uk_19 + 63*uk_2 + 3780*uk_20 + 5103*uk_21 + 13671*uk_22 + 2016*uk_23 + 2401*uk_24 + 1568*uk_25 + 2940*uk_26 + 3969*uk_27 + 10633*uk_28 + 1568*uk_29 + 49*uk_3 + 1024*uk_30 + 1920*uk_31 + 2592*uk_32 + 6944*uk_33 + 1024*uk_34 + 3600*uk_35 + 4860*uk_36 + 13020*uk_37 + 1920*uk_38 + 6561*uk_39 + 32*uk_4 + 17577*uk_40 + 2592*uk_41 + 47089*uk_42 + 6944*uk_43 + 1024*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 109873023841*uk_47 + 71753811488*uk_48 + 134538396540*uk_49 + 60*uk_5 + 181626835329*uk_50 + 486580534153*uk_51 + 71753811488*uk_52 + 187944057*uk_53 + 146178711*uk_54 + 95463648*uk_55 + 178994340*uk_56 + 241642359*uk_57 + 647362863*uk_58 + 95463648*uk_59 + 81*uk_6 + 113694553*uk_60 + 74249504*uk_61 + 139217820*uk_62 + 187944057*uk_63 + 503504449*uk_64 + 74249504*uk_65 + 48489472*uk_66 + 90917760*uk_67 + 122738976*uk_68 + 328819232*uk_69 + 217*uk_7 + 48489472*uk_70 + 170470800*uk_71 + 230135580*uk_72 + 616536060*uk_73 + 90917760*uk_74 + 310683033*uk_75 + 832323681*uk_76 + 122738976*uk_77 + 2229805417*uk_78 + 328819232*uk_79 + 32*uk_8 + 48489472*uk_80 + 250047*uk_81 + 194481*uk_82 + 127008*uk_83 + 238140*uk_84 + 321489*uk_85 + 861273*uk_86 + 127008*uk_87 + 151263*uk_88 + 98784*uk_89 + 2242306609*uk_9 + 185220*uk_90 + 250047*uk_91 + 669879*uk_92 + 98784*uk_93 + 64512*uk_94 + 120960*uk_95 + 163296*uk_96 + 437472*uk_97 + 64512*uk_98 + 226800*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 292824*uk_100 + 765576*uk_101 + 172872*uk_102 + 434007*uk_103 + 1134693*uk_104 + 256221*uk_105 + 2966607*uk_106 + 669879*uk_107 + 151263*uk_108 + 79507*uk_109 + 2036179*uk_11 + 90601*uk_110 + 103544*uk_111 + 153467*uk_112 + 401233*uk_113 + 90601*uk_114 + 103243*uk_115 + 117992*uk_116 + 174881*uk_117 + 457219*uk_118 + 103243*uk_119 + 2320297*uk_12 + 134848*uk_120 + 199864*uk_121 + 522536*uk_122 + 117992*uk_123 + 296227*uk_124 + 774473*uk_125 + 174881*uk_126 + 2024827*uk_127 + 457219*uk_128 + 103243*uk_129 + 2651768*uk_13 + 117649*uk_130 + 134456*uk_131 + 199283*uk_132 + 521017*uk_133 + 117649*uk_134 + 153664*uk_135 + 227752*uk_136 + 595448*uk_137 + 134456*uk_138 + 337561*uk_139 + 3930299*uk_14 + 882539*uk_140 + 199283*uk_141 + 2307361*uk_142 + 521017*uk_143 + 117649*uk_144 + 175616*uk_145 + 260288*uk_146 + 680512*uk_147 + 153664*uk_148 + 385784*uk_149 + 10275601*uk_15 + 1008616*uk_150 + 227752*uk_151 + 2636984*uk_152 + 595448*uk_153 + 134456*uk_154 + 571787*uk_155 + 1494913*uk_156 + 337561*uk_157 + 3908387*uk_158 + 882539*uk_159 + 2320297*uk_16 + 199283*uk_160 + 10218313*uk_161 + 2307361*uk_162 + 521017*uk_163 + 117649*uk_164 + 3969*uk_17 + 2709*uk_18 + 3087*uk_19 + 63*uk_2 + 3528*uk_20 + 5229*uk_21 + 13671*uk_22 + 3087*uk_23 + 1849*uk_24 + 2107*uk_25 + 2408*uk_26 + 3569*uk_27 + 9331*uk_28 + 2107*uk_29 + 43*uk_3 + 2401*uk_30 + 2744*uk_31 + 4067*uk_32 + 10633*uk_33 + 2401*uk_34 + 3136*uk_35 + 4648*uk_36 + 12152*uk_37 + 2744*uk_38 + 6889*uk_39 + 49*uk_4 + 18011*uk_40 + 4067*uk_41 + 47089*uk_42 + 10633*uk_43 + 2401*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 96419184187*uk_47 + 109873023841*uk_48 + 125569170104*uk_49 + 56*uk_5 + 186111448547*uk_50 + 486580534153*uk_51 + 109873023841*uk_52 + 187944057*uk_53 + 128279277*uk_54 + 146178711*uk_55 + 167061384*uk_56 + 247608837*uk_57 + 647362863*uk_58 + 146178711*uk_59 + 83*uk_6 + 87555697*uk_60 + 99772771*uk_61 + 114026024*uk_62 + 169002857*uk_63 + 441850843*uk_64 + 99772771*uk_65 + 113694553*uk_66 + 129936632*uk_67 + 192584651*uk_68 + 503504449*uk_69 + 217*uk_7 + 113694553*uk_70 + 148499008*uk_71 + 220096744*uk_72 + 575433656*uk_73 + 129936632*uk_74 + 326214817*uk_75 + 852874883*uk_76 + 192584651*uk_77 + 2229805417*uk_78 + 503504449*uk_79 + 49*uk_8 + 113694553*uk_80 + 250047*uk_81 + 170667*uk_82 + 194481*uk_83 + 222264*uk_84 + 329427*uk_85 + 861273*uk_86 + 194481*uk_87 + 116487*uk_88 + 132741*uk_89 + 2242306609*uk_9 + 151704*uk_90 + 224847*uk_91 + 587853*uk_92 + 132741*uk_93 + 151263*uk_94 + 172872*uk_95 + 256221*uk_96 + 669879*uk_97 + 151263*uk_98 + 197568*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 278460*uk_100 + 710892*uk_101 + 140868*uk_102 + 455175*uk_103 + 1162035*uk_104 + 230265*uk_105 + 2966607*uk_106 + 587853*uk_107 + 116487*uk_108 + 512*uk_109 + 378824*uk_11 + 2752*uk_110 + 3328*uk_111 + 5440*uk_112 + 13888*uk_113 + 2752*uk_114 + 14792*uk_115 + 17888*uk_116 + 29240*uk_117 + 74648*uk_118 + 14792*uk_119 + 2036179*uk_12 + 21632*uk_120 + 35360*uk_121 + 90272*uk_122 + 17888*uk_123 + 57800*uk_124 + 147560*uk_125 + 29240*uk_126 + 376712*uk_127 + 74648*uk_128 + 14792*uk_129 + 2462356*uk_13 + 79507*uk_130 + 96148*uk_131 + 157165*uk_132 + 401233*uk_133 + 79507*uk_134 + 116272*uk_135 + 190060*uk_136 + 485212*uk_137 + 96148*uk_138 + 310675*uk_139 + 4025005*uk_14 + 793135*uk_140 + 157165*uk_141 + 2024827*uk_142 + 401233*uk_143 + 79507*uk_144 + 140608*uk_145 + 229840*uk_146 + 586768*uk_147 + 116272*uk_148 + 375700*uk_149 + 10275601*uk_15 + 959140*uk_150 + 190060*uk_151 + 2448628*uk_152 + 485212*uk_153 + 96148*uk_154 + 614125*uk_155 + 1567825*uk_156 + 310675*uk_157 + 4002565*uk_158 + 793135*uk_159 + 2036179*uk_16 + 157165*uk_160 + 10218313*uk_161 + 2024827*uk_162 + 401233*uk_163 + 79507*uk_164 + 3969*uk_17 + 504*uk_18 + 2709*uk_19 + 63*uk_2 + 3276*uk_20 + 5355*uk_21 + 13671*uk_22 + 2709*uk_23 + 64*uk_24 + 344*uk_25 + 416*uk_26 + 680*uk_27 + 1736*uk_28 + 344*uk_29 + 8*uk_3 + 1849*uk_30 + 2236*uk_31 + 3655*uk_32 + 9331*uk_33 + 1849*uk_34 + 2704*uk_35 + 4420*uk_36 + 11284*uk_37 + 2236*uk_38 + 7225*uk_39 + 43*uk_4 + 18445*uk_40 + 3655*uk_41 + 47089*uk_42 + 9331*uk_43 + 1849*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 17938452872*uk_47 + 96419184187*uk_48 + 116599943668*uk_49 + 52*uk_5 + 190596061765*uk_50 + 486580534153*uk_51 + 96419184187*uk_52 + 187944057*uk_53 + 23865912*uk_54 + 128279277*uk_55 + 155128428*uk_56 + 253575315*uk_57 + 647362863*uk_58 + 128279277*uk_59 + 85*uk_6 + 3030592*uk_60 + 16289432*uk_61 + 19698848*uk_62 + 32200040*uk_63 + 82204808*uk_64 + 16289432*uk_65 + 87555697*uk_66 + 105881308*uk_67 + 173075215*uk_68 + 441850843*uk_69 + 217*uk_7 + 87555697*uk_70 + 128042512*uk_71 + 209300260*uk_72 + 534331252*uk_73 + 105881308*uk_74 + 342125425*uk_75 + 873426085*uk_76 + 173075215*uk_77 + 2229805417*uk_78 + 441850843*uk_79 + 43*uk_8 + 87555697*uk_80 + 250047*uk_81 + 31752*uk_82 + 170667*uk_83 + 206388*uk_84 + 337365*uk_85 + 861273*uk_86 + 170667*uk_87 + 4032*uk_88 + 21672*uk_89 + 2242306609*uk_9 + 26208*uk_90 + 42840*uk_91 + 109368*uk_92 + 21672*uk_93 + 116487*uk_94 + 140868*uk_95 + 230265*uk_96 + 587853*uk_97 + 116487*uk_98 + 170352*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 285012*uk_100 + 710892*uk_101 + 26208*uk_102 + 476847*uk_103 + 1189377*uk_104 + 43848*uk_105 + 2966607*uk_106 + 109368*uk_107 + 4032*uk_108 + 15625*uk_109 + 1183825*uk_11 + 5000*uk_110 + 32500*uk_111 + 54375*uk_112 + 135625*uk_113 + 5000*uk_114 + 1600*uk_115 + 10400*uk_116 + 17400*uk_117 + 43400*uk_118 + 1600*uk_119 + 378824*uk_12 + 67600*uk_120 + 113100*uk_121 + 282100*uk_122 + 10400*uk_123 + 189225*uk_124 + 471975*uk_125 + 17400*uk_126 + 1177225*uk_127 + 43400*uk_128 + 1600*uk_129 + 2462356*uk_13 + 512*uk_130 + 3328*uk_131 + 5568*uk_132 + 13888*uk_133 + 512*uk_134 + 21632*uk_135 + 36192*uk_136 + 90272*uk_137 + 3328*uk_138 + 60552*uk_139 + 4119711*uk_14 + 151032*uk_140 + 5568*uk_141 + 376712*uk_142 + 13888*uk_143 + 512*uk_144 + 140608*uk_145 + 235248*uk_146 + 586768*uk_147 + 21632*uk_148 + 393588*uk_149 + 10275601*uk_15 + 981708*uk_150 + 36192*uk_151 + 2448628*uk_152 + 90272*uk_153 + 3328*uk_154 + 658503*uk_155 + 1642473*uk_156 + 60552*uk_157 + 4096743*uk_158 + 151032*uk_159 + 378824*uk_16 + 5568*uk_160 + 10218313*uk_161 + 376712*uk_162 + 13888*uk_163 + 512*uk_164 + 3969*uk_17 + 1575*uk_18 + 504*uk_19 + 63*uk_2 + 3276*uk_20 + 5481*uk_21 + 13671*uk_22 + 504*uk_23 + 625*uk_24 + 200*uk_25 + 1300*uk_26 + 2175*uk_27 + 5425*uk_28 + 200*uk_29 + 25*uk_3 + 64*uk_30 + 416*uk_31 + 696*uk_32 + 1736*uk_33 + 64*uk_34 + 2704*uk_35 + 4524*uk_36 + 11284*uk_37 + 416*uk_38 + 7569*uk_39 + 8*uk_4 + 18879*uk_40 + 696*uk_41 + 47089*uk_42 + 1736*uk_43 + 64*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 56057665225*uk_47 + 17938452872*uk_48 + 116599943668*uk_49 + 52*uk_5 + 195080674983*uk_50 + 486580534153*uk_51 + 17938452872*uk_52 + 187944057*uk_53 + 74580975*uk_54 + 23865912*uk_55 + 155128428*uk_56 + 259541793*uk_57 + 647362863*uk_58 + 23865912*uk_59 + 87*uk_6 + 29595625*uk_60 + 9470600*uk_61 + 61558900*uk_62 + 102992775*uk_63 + 256890025*uk_64 + 9470600*uk_65 + 3030592*uk_66 + 19698848*uk_67 + 32957688*uk_68 + 82204808*uk_69 + 217*uk_7 + 3030592*uk_70 + 128042512*uk_71 + 214224972*uk_72 + 534331252*uk_73 + 19698848*uk_74 + 358414857*uk_75 + 893977287*uk_76 + 32957688*uk_77 + 2229805417*uk_78 + 82204808*uk_79 + 8*uk_8 + 3030592*uk_80 + 250047*uk_81 + 99225*uk_82 + 31752*uk_83 + 206388*uk_84 + 345303*uk_85 + 861273*uk_86 + 31752*uk_87 + 39375*uk_88 + 12600*uk_89 + 2242306609*uk_9 + 81900*uk_90 + 137025*uk_91 + 341775*uk_92 + 12600*uk_93 + 4032*uk_94 + 26208*uk_95 + 43848*uk_96 + 109368*uk_97 + 4032*uk_98 + 170352*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 269136*uk_100 + 656208*uk_101 + 75600*uk_102 + 499023*uk_103 + 1216719*uk_104 + 140175*uk_105 + 2966607*uk_106 + 341775*uk_107 + 39375*uk_108 + 125*uk_109 + 236765*uk_11 + 625*uk_110 + 1200*uk_111 + 2225*uk_112 + 5425*uk_113 + 625*uk_114 + 3125*uk_115 + 6000*uk_116 + 11125*uk_117 + 27125*uk_118 + 3125*uk_119 + 1183825*uk_12 + 11520*uk_120 + 21360*uk_121 + 52080*uk_122 + 6000*uk_123 + 39605*uk_124 + 96565*uk_125 + 11125*uk_126 + 235445*uk_127 + 27125*uk_128 + 3125*uk_129 + 2272944*uk_13 + 15625*uk_130 + 30000*uk_131 + 55625*uk_132 + 135625*uk_133 + 15625*uk_134 + 57600*uk_135 + 106800*uk_136 + 260400*uk_137 + 30000*uk_138 + 198025*uk_139 + 4214417*uk_14 + 482825*uk_140 + 55625*uk_141 + 1177225*uk_142 + 135625*uk_143 + 15625*uk_144 + 110592*uk_145 + 205056*uk_146 + 499968*uk_147 + 57600*uk_148 + 380208*uk_149 + 10275601*uk_15 + 927024*uk_150 + 106800*uk_151 + 2260272*uk_152 + 260400*uk_153 + 30000*uk_154 + 704969*uk_155 + 1718857*uk_156 + 198025*uk_157 + 4190921*uk_158 + 482825*uk_159 + 1183825*uk_16 + 55625*uk_160 + 10218313*uk_161 + 1177225*uk_162 + 135625*uk_163 + 15625*uk_164 + 3969*uk_17 + 315*uk_18 + 1575*uk_19 + 63*uk_2 + 3024*uk_20 + 5607*uk_21 + 13671*uk_22 + 1575*uk_23 + 25*uk_24 + 125*uk_25 + 240*uk_26 + 445*uk_27 + 1085*uk_28 + 125*uk_29 + 5*uk_3 + 625*uk_30 + 1200*uk_31 + 2225*uk_32 + 5425*uk_33 + 625*uk_34 + 2304*uk_35 + 4272*uk_36 + 10416*uk_37 + 1200*uk_38 + 7921*uk_39 + 25*uk_4 + 19313*uk_40 + 2225*uk_41 + 47089*uk_42 + 5425*uk_43 + 625*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 11211533045*uk_47 + 56057665225*uk_48 + 107630717232*uk_49 + 48*uk_5 + 199565288201*uk_50 + 486580534153*uk_51 + 56057665225*uk_52 + 187944057*uk_53 + 14916195*uk_54 + 74580975*uk_55 + 143195472*uk_56 + 265508271*uk_57 + 647362863*uk_58 + 74580975*uk_59 + 89*uk_6 + 1183825*uk_60 + 5919125*uk_61 + 11364720*uk_62 + 21072085*uk_63 + 51378005*uk_64 + 5919125*uk_65 + 29595625*uk_66 + 56823600*uk_67 + 105360425*uk_68 + 256890025*uk_69 + 217*uk_7 + 29595625*uk_70 + 109101312*uk_71 + 202292016*uk_72 + 493228848*uk_73 + 56823600*uk_74 + 375083113*uk_75 + 914528489*uk_76 + 105360425*uk_77 + 2229805417*uk_78 + 256890025*uk_79 + 25*uk_8 + 29595625*uk_80 + 250047*uk_81 + 19845*uk_82 + 99225*uk_83 + 190512*uk_84 + 353241*uk_85 + 861273*uk_86 + 99225*uk_87 + 1575*uk_88 + 7875*uk_89 + 2242306609*uk_9 + 15120*uk_90 + 28035*uk_91 + 68355*uk_92 + 7875*uk_93 + 39375*uk_94 + 75600*uk_95 + 140175*uk_96 + 341775*uk_97 + 39375*uk_98 + 145152*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 275184*uk_100 + 656208*uk_101 + 15120*uk_102 + 521703*uk_103 + 1244061*uk_104 + 28665*uk_105 + 2966607*uk_106 + 68355*uk_107 + 1575*uk_108 + 35937*uk_109 + 1562649*uk_11 + 5445*uk_110 + 52272*uk_111 + 99099*uk_112 + 236313*uk_113 + 5445*uk_114 + 825*uk_115 + 7920*uk_116 + 15015*uk_117 + 35805*uk_118 + 825*uk_119 + 236765*uk_12 + 76032*uk_120 + 144144*uk_121 + 343728*uk_122 + 7920*uk_123 + 273273*uk_124 + 651651*uk_125 + 15015*uk_126 + 1553937*uk_127 + 35805*uk_128 + 825*uk_129 + 2272944*uk_13 + 125*uk_130 + 1200*uk_131 + 2275*uk_132 + 5425*uk_133 + 125*uk_134 + 11520*uk_135 + 21840*uk_136 + 52080*uk_137 + 1200*uk_138 + 41405*uk_139 + 4309123*uk_14 + 98735*uk_140 + 2275*uk_141 + 235445*uk_142 + 5425*uk_143 + 125*uk_144 + 110592*uk_145 + 209664*uk_146 + 499968*uk_147 + 11520*uk_148 + 397488*uk_149 + 10275601*uk_15 + 947856*uk_150 + 21840*uk_151 + 2260272*uk_152 + 52080*uk_153 + 1200*uk_154 + 753571*uk_155 + 1796977*uk_156 + 41405*uk_157 + 4285099*uk_158 + 98735*uk_159 + 236765*uk_16 + 2275*uk_160 + 10218313*uk_161 + 235445*uk_162 + 5425*uk_163 + 125*uk_164 + 3969*uk_17 + 2079*uk_18 + 315*uk_19 + 63*uk_2 + 3024*uk_20 + 5733*uk_21 + 13671*uk_22 + 315*uk_23 + 1089*uk_24 + 165*uk_25 + 1584*uk_26 + 3003*uk_27 + 7161*uk_28 + 165*uk_29 + 33*uk_3 + 25*uk_30 + 240*uk_31 + 455*uk_32 + 1085*uk_33 + 25*uk_34 + 2304*uk_35 + 4368*uk_36 + 10416*uk_37 + 240*uk_38 + 8281*uk_39 + 5*uk_4 + 19747*uk_40 + 455*uk_41 + 47089*uk_42 + 1085*uk_43 + 25*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 73996118097*uk_47 + 11211533045*uk_48 + 107630717232*uk_49 + 48*uk_5 + 204049901419*uk_50 + 486580534153*uk_51 + 11211533045*uk_52 + 187944057*uk_53 + 98446887*uk_54 + 14916195*uk_55 + 143195472*uk_56 + 271474749*uk_57 + 647362863*uk_58 + 14916195*uk_59 + 91*uk_6 + 51567417*uk_60 + 7813245*uk_61 + 75007152*uk_62 + 142201059*uk_63 + 339094833*uk_64 + 7813245*uk_65 + 1183825*uk_66 + 11364720*uk_67 + 21545615*uk_68 + 51378005*uk_69 + 217*uk_7 + 1183825*uk_70 + 109101312*uk_71 + 206837904*uk_72 + 493228848*uk_73 + 11364720*uk_74 + 392130193*uk_75 + 935079691*uk_76 + 21545615*uk_77 + 2229805417*uk_78 + 51378005*uk_79 + 5*uk_8 + 1183825*uk_80 + 250047*uk_81 + 130977*uk_82 + 19845*uk_83 + 190512*uk_84 + 361179*uk_85 + 861273*uk_86 + 19845*uk_87 + 68607*uk_88 + 10395*uk_89 + 2242306609*uk_9 + 99792*uk_90 + 189189*uk_91 + 451143*uk_92 + 10395*uk_93 + 1575*uk_94 + 15120*uk_95 + 28665*uk_96 + 68355*uk_97 + 1575*uk_98 + 145152*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 257796*uk_100 + 601524*uk_101 + 91476*uk_102 + 544887*uk_103 + 1271403*uk_104 + 193347*uk_105 + 2966607*uk_106 + 451143*uk_107 + 68607*uk_108 + 4096*uk_109 + 757648*uk_11 + 8448*uk_110 + 11264*uk_111 + 23808*uk_112 + 55552*uk_113 + 8448*uk_114 + 17424*uk_115 + 23232*uk_116 + 49104*uk_117 + 114576*uk_118 + 17424*uk_119 + 1562649*uk_12 + 30976*uk_120 + 65472*uk_121 + 152768*uk_122 + 23232*uk_123 + 138384*uk_124 + 322896*uk_125 + 49104*uk_126 + 753424*uk_127 + 114576*uk_128 + 17424*uk_129 + 2083532*uk_13 + 35937*uk_130 + 47916*uk_131 + 101277*uk_132 + 236313*uk_133 + 35937*uk_134 + 63888*uk_135 + 135036*uk_136 + 315084*uk_137 + 47916*uk_138 + 285417*uk_139 + 4403829*uk_14 + 665973*uk_140 + 101277*uk_141 + 1553937*uk_142 + 236313*uk_143 + 35937*uk_144 + 85184*uk_145 + 180048*uk_146 + 420112*uk_147 + 63888*uk_148 + 380556*uk_149 + 10275601*uk_15 + 887964*uk_150 + 135036*uk_151 + 2071916*uk_152 + 315084*uk_153 + 47916*uk_154 + 804357*uk_155 + 1876833*uk_156 + 285417*uk_157 + 4379277*uk_158 + 665973*uk_159 + 1562649*uk_16 + 101277*uk_160 + 10218313*uk_161 + 1553937*uk_162 + 236313*uk_163 + 35937*uk_164 + 3969*uk_17 + 1008*uk_18 + 2079*uk_19 + 63*uk_2 + 2772*uk_20 + 5859*uk_21 + 13671*uk_22 + 2079*uk_23 + 256*uk_24 + 528*uk_25 + 704*uk_26 + 1488*uk_27 + 3472*uk_28 + 528*uk_29 + 16*uk_3 + 1089*uk_30 + 1452*uk_31 + 3069*uk_32 + 7161*uk_33 + 1089*uk_34 + 1936*uk_35 + 4092*uk_36 + 9548*uk_37 + 1452*uk_38 + 8649*uk_39 + 33*uk_4 + 20181*uk_40 + 3069*uk_41 + 47089*uk_42 + 7161*uk_43 + 1089*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 35876905744*uk_47 + 73996118097*uk_48 + 98661490796*uk_49 + 44*uk_5 + 208534514637*uk_50 + 486580534153*uk_51 + 73996118097*uk_52 + 187944057*uk_53 + 47731824*uk_54 + 98446887*uk_55 + 131262516*uk_56 + 277441227*uk_57 + 647362863*uk_58 + 98446887*uk_59 + 93*uk_6 + 12122368*uk_60 + 25002384*uk_61 + 33336512*uk_62 + 70461264*uk_63 + 164409616*uk_64 + 25002384*uk_65 + 51567417*uk_66 + 68756556*uk_67 + 145326357*uk_68 + 339094833*uk_69 + 217*uk_7 + 51567417*uk_70 + 91675408*uk_71 + 193768476*uk_72 + 452126444*uk_73 + 68756556*uk_74 + 409556097*uk_75 + 955630893*uk_76 + 145326357*uk_77 + 2229805417*uk_78 + 339094833*uk_79 + 33*uk_8 + 51567417*uk_80 + 250047*uk_81 + 63504*uk_82 + 130977*uk_83 + 174636*uk_84 + 369117*uk_85 + 861273*uk_86 + 130977*uk_87 + 16128*uk_88 + 33264*uk_89 + 2242306609*uk_9 + 44352*uk_90 + 93744*uk_91 + 218736*uk_92 + 33264*uk_93 + 68607*uk_94 + 91476*uk_95 + 193347*uk_96 + 451143*uk_97 + 68607*uk_98 + 121968*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 263340*uk_100 + 601524*uk_101 + 44352*uk_102 + 568575*uk_103 + 1298745*uk_104 + 95760*uk_105 + 2966607*uk_106 + 218736*uk_107 + 16128*uk_108 + 79507*uk_109 + 2036179*uk_11 + 29584*uk_110 + 81356*uk_111 + 175655*uk_112 + 401233*uk_113 + 29584*uk_114 + 11008*uk_115 + 30272*uk_116 + 65360*uk_117 + 149296*uk_118 + 11008*uk_119 + 757648*uk_12 + 83248*uk_120 + 179740*uk_121 + 410564*uk_122 + 30272*uk_123 + 388075*uk_124 + 886445*uk_125 + 65360*uk_126 + 2024827*uk_127 + 149296*uk_128 + 11008*uk_129 + 2083532*uk_13 + 4096*uk_130 + 11264*uk_131 + 24320*uk_132 + 55552*uk_133 + 4096*uk_134 + 30976*uk_135 + 66880*uk_136 + 152768*uk_137 + 11264*uk_138 + 144400*uk_139 + 4498535*uk_14 + 329840*uk_140 + 24320*uk_141 + 753424*uk_142 + 55552*uk_143 + 4096*uk_144 + 85184*uk_145 + 183920*uk_146 + 420112*uk_147 + 30976*uk_148 + 397100*uk_149 + 10275601*uk_15 + 907060*uk_150 + 66880*uk_151 + 2071916*uk_152 + 152768*uk_153 + 11264*uk_154 + 857375*uk_155 + 1958425*uk_156 + 144400*uk_157 + 4473455*uk_158 + 329840*uk_159 + 757648*uk_16 + 24320*uk_160 + 10218313*uk_161 + 753424*uk_162 + 55552*uk_163 + 4096*uk_164 + 3969*uk_17 + 2709*uk_18 + 1008*uk_19 + 63*uk_2 + 2772*uk_20 + 5985*uk_21 + 13671*uk_22 + 1008*uk_23 + 1849*uk_24 + 688*uk_25 + 1892*uk_26 + 4085*uk_27 + 9331*uk_28 + 688*uk_29 + 43*uk_3 + 256*uk_30 + 704*uk_31 + 1520*uk_32 + 3472*uk_33 + 256*uk_34 + 1936*uk_35 + 4180*uk_36 + 9548*uk_37 + 704*uk_38 + 9025*uk_39 + 16*uk_4 + 20615*uk_40 + 1520*uk_41 + 47089*uk_42 + 3472*uk_43 + 256*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 96419184187*uk_47 + 35876905744*uk_48 + 98661490796*uk_49 + 44*uk_5 + 213019127855*uk_50 + 486580534153*uk_51 + 35876905744*uk_52 + 187944057*uk_53 + 128279277*uk_54 + 47731824*uk_55 + 131262516*uk_56 + 283407705*uk_57 + 647362863*uk_58 + 47731824*uk_59 + 95*uk_6 + 87555697*uk_60 + 32578864*uk_61 + 89591876*uk_62 + 193437005*uk_63 + 441850843*uk_64 + 32578864*uk_65 + 12122368*uk_66 + 33336512*uk_67 + 71976560*uk_68 + 164409616*uk_69 + 217*uk_7 + 12122368*uk_70 + 91675408*uk_71 + 197935540*uk_72 + 452126444*uk_73 + 33336512*uk_74 + 427360825*uk_75 + 976182095*uk_76 + 71976560*uk_77 + 2229805417*uk_78 + 164409616*uk_79 + 16*uk_8 + 12122368*uk_80 + 250047*uk_81 + 170667*uk_82 + 63504*uk_83 + 174636*uk_84 + 377055*uk_85 + 861273*uk_86 + 63504*uk_87 + 116487*uk_88 + 43344*uk_89 + 2242306609*uk_9 + 119196*uk_90 + 257355*uk_91 + 587853*uk_92 + 43344*uk_93 + 16128*uk_94 + 44352*uk_95 + 95760*uk_96 + 218736*uk_97 + 16128*uk_98 + 121968*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 244440*uk_100 + 546840*uk_101 + 108360*uk_102 + 592767*uk_103 + 1326087*uk_104 + 262773*uk_105 + 2966607*uk_106 + 587853*uk_107 + 116487*uk_108 + 4913*uk_109 + 805001*uk_11 + 12427*uk_110 + 11560*uk_111 + 28033*uk_112 + 62713*uk_113 + 12427*uk_114 + 31433*uk_115 + 29240*uk_116 + 70907*uk_117 + 158627*uk_118 + 31433*uk_119 + 2036179*uk_12 + 27200*uk_120 + 65960*uk_121 + 147560*uk_122 + 29240*uk_123 + 159953*uk_124 + 357833*uk_125 + 70907*uk_126 + 800513*uk_127 + 158627*uk_128 + 31433*uk_129 + 1894120*uk_13 + 79507*uk_130 + 73960*uk_131 + 179353*uk_132 + 401233*uk_133 + 79507*uk_134 + 68800*uk_135 + 166840*uk_136 + 373240*uk_137 + 73960*uk_138 + 404587*uk_139 + 4593241*uk_14 + 905107*uk_140 + 179353*uk_141 + 2024827*uk_142 + 401233*uk_143 + 79507*uk_144 + 64000*uk_145 + 155200*uk_146 + 347200*uk_147 + 68800*uk_148 + 376360*uk_149 + 10275601*uk_15 + 841960*uk_150 + 166840*uk_151 + 1883560*uk_152 + 373240*uk_153 + 73960*uk_154 + 912673*uk_155 + 2041753*uk_156 + 404587*uk_157 + 4567633*uk_158 + 905107*uk_159 + 2036179*uk_16 + 179353*uk_160 + 10218313*uk_161 + 2024827*uk_162 + 401233*uk_163 + 79507*uk_164 + 3969*uk_17 + 1071*uk_18 + 2709*uk_19 + 63*uk_2 + 2520*uk_20 + 6111*uk_21 + 13671*uk_22 + 2709*uk_23 + 289*uk_24 + 731*uk_25 + 680*uk_26 + 1649*uk_27 + 3689*uk_28 + 731*uk_29 + 17*uk_3 + 1849*uk_30 + 1720*uk_31 + 4171*uk_32 + 9331*uk_33 + 1849*uk_34 + 1600*uk_35 + 3880*uk_36 + 8680*uk_37 + 1720*uk_38 + 9409*uk_39 + 43*uk_4 + 21049*uk_40 + 4171*uk_41 + 47089*uk_42 + 9331*uk_43 + 1849*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 38119212353*uk_47 + 96419184187*uk_48 + 89692264360*uk_49 + 40*uk_5 + 217503741073*uk_50 + 486580534153*uk_51 + 96419184187*uk_52 + 187944057*uk_53 + 50715063*uk_54 + 128279277*uk_55 + 119329560*uk_56 + 289374183*uk_57 + 647362863*uk_58 + 128279277*uk_59 + 97*uk_6 + 13685017*uk_60 + 34615043*uk_61 + 32200040*uk_62 + 78085097*uk_63 + 174685217*uk_64 + 34615043*uk_65 + 87555697*uk_66 + 81447160*uk_67 + 197509363*uk_68 + 441850843*uk_69 + 217*uk_7 + 87555697*uk_70 + 75764800*uk_71 + 183729640*uk_72 + 411024040*uk_73 + 81447160*uk_74 + 445544377*uk_75 + 996733297*uk_76 + 197509363*uk_77 + 2229805417*uk_78 + 441850843*uk_79 + 43*uk_8 + 87555697*uk_80 + 250047*uk_81 + 67473*uk_82 + 170667*uk_83 + 158760*uk_84 + 384993*uk_85 + 861273*uk_86 + 170667*uk_87 + 18207*uk_88 + 46053*uk_89 + 2242306609*uk_9 + 42840*uk_90 + 103887*uk_91 + 232407*uk_92 + 46053*uk_93 + 116487*uk_94 + 108360*uk_95 + 262773*uk_96 + 587853*uk_97 + 116487*uk_98 + 100800*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 249480*uk_100 + 546840*uk_101 + 42840*uk_102 + 617463*uk_103 + 1353429*uk_104 + 106029*uk_105 + 2966607*uk_106 + 232407*uk_107 + 18207*uk_108 + 29791*uk_109 + 1467943*uk_11 + 16337*uk_110 + 38440*uk_111 + 95139*uk_112 + 208537*uk_113 + 16337*uk_114 + 8959*uk_115 + 21080*uk_116 + 52173*uk_117 + 114359*uk_118 + 8959*uk_119 + 805001*uk_12 + 49600*uk_120 + 122760*uk_121 + 269080*uk_122 + 21080*uk_123 + 303831*uk_124 + 665973*uk_125 + 52173*uk_126 + 1459759*uk_127 + 114359*uk_128 + 8959*uk_129 + 1894120*uk_13 + 4913*uk_130 + 11560*uk_131 + 28611*uk_132 + 62713*uk_133 + 4913*uk_134 + 27200*uk_135 + 67320*uk_136 + 147560*uk_137 + 11560*uk_138 + 166617*uk_139 + 4687947*uk_14 + 365211*uk_140 + 28611*uk_141 + 800513*uk_142 + 62713*uk_143 + 4913*uk_144 + 64000*uk_145 + 158400*uk_146 + 347200*uk_147 + 27200*uk_148 + 392040*uk_149 + 10275601*uk_15 + 859320*uk_150 + 67320*uk_151 + 1883560*uk_152 + 147560*uk_153 + 11560*uk_154 + 970299*uk_155 + 2126817*uk_156 + 166617*uk_157 + 4661811*uk_158 + 365211*uk_159 + 805001*uk_16 + 28611*uk_160 + 10218313*uk_161 + 800513*uk_162 + 62713*uk_163 + 4913*uk_164 + 3969*uk_17 + 1953*uk_18 + 1071*uk_19 + 63*uk_2 + 2520*uk_20 + 6237*uk_21 + 13671*uk_22 + 1071*uk_23 + 961*uk_24 + 527*uk_25 + 1240*uk_26 + 3069*uk_27 + 6727*uk_28 + 527*uk_29 + 31*uk_3 + 289*uk_30 + 680*uk_31 + 1683*uk_32 + 3689*uk_33 + 289*uk_34 + 1600*uk_35 + 3960*uk_36 + 8680*uk_37 + 680*uk_38 + 9801*uk_39 + 17*uk_4 + 21483*uk_40 + 1683*uk_41 + 47089*uk_42 + 3689*uk_43 + 289*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 69511504879*uk_47 + 38119212353*uk_48 + 89692264360*uk_49 + 40*uk_5 + 221988354291*uk_50 + 486580534153*uk_51 + 38119212353*uk_52 + 187944057*uk_53 + 92480409*uk_54 + 50715063*uk_55 + 119329560*uk_56 + 295340661*uk_57 + 647362863*uk_58 + 50715063*uk_59 + 99*uk_6 + 45506233*uk_60 + 24955031*uk_61 + 58717720*uk_62 + 145326357*uk_63 + 318543631*uk_64 + 24955031*uk_65 + 13685017*uk_66 + 32200040*uk_67 + 79695099*uk_68 + 174685217*uk_69 + 217*uk_7 + 13685017*uk_70 + 75764800*uk_71 + 187517880*uk_72 + 411024040*uk_73 + 32200040*uk_74 + 464106753*uk_75 + 1017284499*uk_76 + 79695099*uk_77 + 2229805417*uk_78 + 174685217*uk_79 + 17*uk_8 + 13685017*uk_80 + 250047*uk_81 + 123039*uk_82 + 67473*uk_83 + 158760*uk_84 + 392931*uk_85 + 861273*uk_86 + 67473*uk_87 + 60543*uk_88 + 33201*uk_89 + 2242306609*uk_9 + 78120*uk_90 + 193347*uk_91 + 423801*uk_92 + 33201*uk_93 + 18207*uk_94 + 42840*uk_95 + 106029*uk_96 + 232407*uk_97 + 18207*uk_98 + 100800*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 254520*uk_100 + 546840*uk_101 + 78120*uk_102 + 642663*uk_103 + 1380771*uk_104 + 197253*uk_105 + 2966607*uk_106 + 423801*uk_107 + 60543*uk_108 + 614125*uk_109 + 4025005*uk_11 + 223975*uk_110 + 289000*uk_111 + 729725*uk_112 + 1567825*uk_113 + 223975*uk_114 + 81685*uk_115 + 105400*uk_116 + 266135*uk_117 + 571795*uk_118 + 81685*uk_119 + 1467943*uk_12 + 136000*uk_120 + 343400*uk_121 + 737800*uk_122 + 105400*uk_123 + 867085*uk_124 + 1862945*uk_125 + 266135*uk_126 + 4002565*uk_127 + 571795*uk_128 + 81685*uk_129 + 1894120*uk_13 + 29791*uk_130 + 38440*uk_131 + 97061*uk_132 + 208537*uk_133 + 29791*uk_134 + 49600*uk_135 + 125240*uk_136 + 269080*uk_137 + 38440*uk_138 + 316231*uk_139 + 4782653*uk_14 + 679427*uk_140 + 97061*uk_141 + 1459759*uk_142 + 208537*uk_143 + 29791*uk_144 + 64000*uk_145 + 161600*uk_146 + 347200*uk_147 + 49600*uk_148 + 408040*uk_149 + 10275601*uk_15 + 876680*uk_150 + 125240*uk_151 + 1883560*uk_152 + 269080*uk_153 + 38440*uk_154 + 1030301*uk_155 + 2213617*uk_156 + 316231*uk_157 + 4755989*uk_158 + 679427*uk_159 + 1467943*uk_16 + 97061*uk_160 + 10218313*uk_161 + 1459759*uk_162 + 208537*uk_163 + 29791*uk_164 + 3969*uk_17 + 5355*uk_18 + 1953*uk_19 + 63*uk_2 + 2520*uk_20 + 6363*uk_21 + 13671*uk_22 + 1953*uk_23 + 7225*uk_24 + 2635*uk_25 + 3400*uk_26 + 8585*uk_27 + 18445*uk_28 + 2635*uk_29 + 85*uk_3 + 961*uk_30 + 1240*uk_31 + 3131*uk_32 + 6727*uk_33 + 961*uk_34 + 1600*uk_35 + 4040*uk_36 + 8680*uk_37 + 1240*uk_38 + 10201*uk_39 + 31*uk_4 + 21917*uk_40 + 3131*uk_41 + 47089*uk_42 + 6727*uk_43 + 961*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 190596061765*uk_47 + 69511504879*uk_48 + 89692264360*uk_49 + 40*uk_5 + 226472967509*uk_50 + 486580534153*uk_51 + 69511504879*uk_52 + 187944057*uk_53 + 253575315*uk_54 + 92480409*uk_55 + 119329560*uk_56 + 301307139*uk_57 + 647362863*uk_58 + 92480409*uk_59 + 101*uk_6 + 342125425*uk_60 + 124775155*uk_61 + 161000200*uk_62 + 406525505*uk_63 + 873426085*uk_64 + 124775155*uk_65 + 45506233*uk_66 + 58717720*uk_67 + 148262243*uk_68 + 318543631*uk_69 + 217*uk_7 + 45506233*uk_70 + 75764800*uk_71 + 191306120*uk_72 + 411024040*uk_73 + 58717720*uk_74 + 483047953*uk_75 + 1037835701*uk_76 + 148262243*uk_77 + 2229805417*uk_78 + 318543631*uk_79 + 31*uk_8 + 45506233*uk_80 + 250047*uk_81 + 337365*uk_82 + 123039*uk_83 + 158760*uk_84 + 400869*uk_85 + 861273*uk_86 + 123039*uk_87 + 455175*uk_88 + 166005*uk_89 + 2242306609*uk_9 + 214200*uk_90 + 540855*uk_91 + 1162035*uk_92 + 166005*uk_93 + 60543*uk_94 + 78120*uk_95 + 197253*uk_96 + 423801*uk_97 + 60543*uk_98 + 100800*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 233604*uk_100 + 492156*uk_101 + 192780*uk_102 + 668367*uk_103 + 1408113*uk_104 + 551565*uk_105 + 2966607*uk_106 + 1162035*uk_107 + 455175*uk_108 + 438976*uk_109 + 3598828*uk_11 + 490960*uk_110 + 207936*uk_111 + 594928*uk_112 + 1253392*uk_113 + 490960*uk_114 + 549100*uk_115 + 232560*uk_116 + 665380*uk_117 + 1401820*uk_118 + 549100*uk_119 + 4025005*uk_12 + 98496*uk_120 + 281808*uk_121 + 593712*uk_122 + 232560*uk_123 + 806284*uk_124 + 1698676*uk_125 + 665380*uk_126 + 3578764*uk_127 + 1401820*uk_128 + 549100*uk_129 + 1704708*uk_13 + 614125*uk_130 + 260100*uk_131 + 744175*uk_132 + 1567825*uk_133 + 614125*uk_134 + 110160*uk_135 + 315180*uk_136 + 664020*uk_137 + 260100*uk_138 + 901765*uk_139 + 4877359*uk_14 + 1899835*uk_140 + 744175*uk_141 + 4002565*uk_142 + 1567825*uk_143 + 614125*uk_144 + 46656*uk_145 + 133488*uk_146 + 281232*uk_147 + 110160*uk_148 + 381924*uk_149 + 10275601*uk_15 + 804636*uk_150 + 315180*uk_151 + 1695204*uk_152 + 664020*uk_153 + 260100*uk_154 + 1092727*uk_155 + 2302153*uk_156 + 901765*uk_157 + 4850167*uk_158 + 1899835*uk_159 + 4025005*uk_16 + 744175*uk_160 + 10218313*uk_161 + 4002565*uk_162 + 1567825*uk_163 + 614125*uk_164 + 3969*uk_17 + 4788*uk_18 + 5355*uk_19 + 63*uk_2 + 2268*uk_20 + 6489*uk_21 + 13671*uk_22 + 5355*uk_23 + 5776*uk_24 + 6460*uk_25 + 2736*uk_26 + 7828*uk_27 + 16492*uk_28 + 6460*uk_29 + 76*uk_3 + 7225*uk_30 + 3060*uk_31 + 8755*uk_32 + 18445*uk_33 + 7225*uk_34 + 1296*uk_35 + 3708*uk_36 + 7812*uk_37 + 3060*uk_38 + 10609*uk_39 + 85*uk_4 + 22351*uk_40 + 8755*uk_41 + 47089*uk_42 + 18445*uk_43 + 7225*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 170415302284*uk_47 + 190596061765*uk_48 + 80723037924*uk_49 + 36*uk_5 + 230957580727*uk_50 + 486580534153*uk_51 + 190596061765*uk_52 + 187944057*uk_53 + 226726164*uk_54 + 253575315*uk_55 + 107396604*uk_56 + 307273617*uk_57 + 647362863*uk_58 + 253575315*uk_59 + 103*uk_6 + 273510928*uk_60 + 305900380*uk_61 + 129557808*uk_62 + 370679284*uk_63 + 780945676*uk_64 + 305900380*uk_65 + 342125425*uk_66 + 144900180*uk_67 + 414575515*uk_68 + 873426085*uk_69 + 217*uk_7 + 342125425*uk_70 + 61369488*uk_71 + 175584924*uk_72 + 369921636*uk_73 + 144900180*uk_74 + 502367977*uk_75 + 1058386903*uk_76 + 414575515*uk_77 + 2229805417*uk_78 + 873426085*uk_79 + 85*uk_8 + 342125425*uk_80 + 250047*uk_81 + 301644*uk_82 + 337365*uk_83 + 142884*uk_84 + 408807*uk_85 + 861273*uk_86 + 337365*uk_87 + 363888*uk_88 + 406980*uk_89 + 2242306609*uk_9 + 172368*uk_90 + 493164*uk_91 + 1038996*uk_92 + 406980*uk_93 + 455175*uk_94 + 192780*uk_95 + 551565*uk_96 + 1162035*uk_97 + 455175*uk_98 + 81648*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 238140*uk_100 + 492156*uk_101 + 172368*uk_102 + 694575*uk_103 + 1435455*uk_104 + 502740*uk_105 + 2966607*uk_106 + 1038996*uk_107 + 363888*uk_108 + 1092727*uk_109 + 4877359*uk_11 + 806284*uk_110 + 381924*uk_111 + 1113945*uk_112 + 2302153*uk_113 + 806284*uk_114 + 594928*uk_115 + 281808*uk_116 + 821940*uk_117 + 1698676*uk_118 + 594928*uk_119 + 3598828*uk_12 + 133488*uk_120 + 389340*uk_121 + 804636*uk_122 + 281808*uk_123 + 1135575*uk_124 + 2346855*uk_125 + 821940*uk_126 + 4850167*uk_127 + 1698676*uk_128 + 594928*uk_129 + 1704708*uk_13 + 438976*uk_130 + 207936*uk_131 + 606480*uk_132 + 1253392*uk_133 + 438976*uk_134 + 98496*uk_135 + 287280*uk_136 + 593712*uk_137 + 207936*uk_138 + 837900*uk_139 + 4972065*uk_14 + 1731660*uk_140 + 606480*uk_141 + 3578764*uk_142 + 1253392*uk_143 + 438976*uk_144 + 46656*uk_145 + 136080*uk_146 + 281232*uk_147 + 98496*uk_148 + 396900*uk_149 + 10275601*uk_15 + 820260*uk_150 + 287280*uk_151 + 1695204*uk_152 + 593712*uk_153 + 207936*uk_154 + 1157625*uk_155 + 2392425*uk_156 + 837900*uk_157 + 4944345*uk_158 + 1731660*uk_159 + 3598828*uk_16 + 606480*uk_160 + 10218313*uk_161 + 3578764*uk_162 + 1253392*uk_163 + 438976*uk_164 + 3969*uk_17 + 6489*uk_18 + 4788*uk_19 + 63*uk_2 + 2268*uk_20 + 6615*uk_21 + 13671*uk_22 + 4788*uk_23 + 10609*uk_24 + 7828*uk_25 + 3708*uk_26 + 10815*uk_27 + 22351*uk_28 + 7828*uk_29 + 103*uk_3 + 5776*uk_30 + 2736*uk_31 + 7980*uk_32 + 16492*uk_33 + 5776*uk_34 + 1296*uk_35 + 3780*uk_36 + 7812*uk_37 + 2736*uk_38 + 11025*uk_39 + 76*uk_4 + 22785*uk_40 + 7980*uk_41 + 47089*uk_42 + 16492*uk_43 + 5776*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 230957580727*uk_47 + 170415302284*uk_48 + 80723037924*uk_49 + 36*uk_5 + 235442193945*uk_50 + 486580534153*uk_51 + 170415302284*uk_52 + 187944057*uk_53 + 307273617*uk_54 + 226726164*uk_55 + 107396604*uk_56 + 313240095*uk_57 + 647362863*uk_58 + 226726164*uk_59 + 105*uk_6 + 502367977*uk_60 + 370679284*uk_61 + 175584924*uk_62 + 512122695*uk_63 + 1058386903*uk_64 + 370679284*uk_65 + 273510928*uk_66 + 129557808*uk_67 + 377876940*uk_68 + 780945676*uk_69 + 217*uk_7 + 273510928*uk_70 + 61369488*uk_71 + 178994340*uk_72 + 369921636*uk_73 + 129557808*uk_74 + 522066825*uk_75 + 1078938105*uk_76 + 377876940*uk_77 + 2229805417*uk_78 + 780945676*uk_79 + 76*uk_8 + 273510928*uk_80 + 250047*uk_81 + 408807*uk_82 + 301644*uk_83 + 142884*uk_84 + 416745*uk_85 + 861273*uk_86 + 301644*uk_87 + 668367*uk_88 + 493164*uk_89 + 2242306609*uk_9 + 233604*uk_90 + 681345*uk_91 + 1408113*uk_92 + 493164*uk_93 + 363888*uk_94 + 172368*uk_95 + 502740*uk_96 + 1038996*uk_97 + 363888*uk_98 + 81648*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 215712*uk_100 + 437472*uk_101 + 207648*uk_102 + 721287*uk_103 + 1462797*uk_104 + 694323*uk_105 + 2966607*uk_106 + 1408113*uk_107 + 668367*uk_108 + 205379*uk_109 + 2793827*uk_11 + 358543*uk_110 + 111392*uk_111 + 372467*uk_112 + 755377*uk_113 + 358543*uk_114 + 625931*uk_115 + 194464*uk_116 + 650239*uk_117 + 1318709*uk_118 + 625931*uk_119 + 4877359*uk_12 + 60416*uk_120 + 202016*uk_121 + 409696*uk_122 + 194464*uk_123 + 675491*uk_124 + 1369921*uk_125 + 650239*uk_126 + 2778251*uk_127 + 1318709*uk_128 + 625931*uk_129 + 1515296*uk_13 + 1092727*uk_130 + 339488*uk_131 + 1135163*uk_132 + 2302153*uk_133 + 1092727*uk_134 + 105472*uk_135 + 352672*uk_136 + 715232*uk_137 + 339488*uk_138 + 1179247*uk_139 + 5066771*uk_14 + 2391557*uk_140 + 1135163*uk_141 + 4850167*uk_142 + 2302153*uk_143 + 1092727*uk_144 + 32768*uk_145 + 109568*uk_146 + 222208*uk_147 + 105472*uk_148 + 366368*uk_149 + 10275601*uk_15 + 743008*uk_150 + 352672*uk_151 + 1506848*uk_152 + 715232*uk_153 + 339488*uk_154 + 1225043*uk_155 + 2484433*uk_156 + 1179247*uk_157 + 5038523*uk_158 + 2391557*uk_159 + 4877359*uk_16 + 1135163*uk_160 + 10218313*uk_161 + 4850167*uk_162 + 2302153*uk_163 + 1092727*uk_164 + 3969*uk_17 + 3717*uk_18 + 6489*uk_19 + 63*uk_2 + 2016*uk_20 + 6741*uk_21 + 13671*uk_22 + 6489*uk_23 + 3481*uk_24 + 6077*uk_25 + 1888*uk_26 + 6313*uk_27 + 12803*uk_28 + 6077*uk_29 + 59*uk_3 + 10609*uk_30 + 3296*uk_31 + 11021*uk_32 + 22351*uk_33 + 10609*uk_34 + 1024*uk_35 + 3424*uk_36 + 6944*uk_37 + 3296*uk_38 + 11449*uk_39 + 103*uk_4 + 23219*uk_40 + 11021*uk_41 + 47089*uk_42 + 22351*uk_43 + 10609*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 132296089931*uk_47 + 230957580727*uk_48 + 71753811488*uk_49 + 32*uk_5 + 239926807163*uk_50 + 486580534153*uk_51 + 230957580727*uk_52 + 187944057*uk_53 + 176011101*uk_54 + 307273617*uk_55 + 95463648*uk_56 + 319206573*uk_57 + 647362863*uk_58 + 307273617*uk_59 + 107*uk_6 + 164835793*uk_60 + 287764181*uk_61 + 89402464*uk_62 + 298939489*uk_63 + 606260459*uk_64 + 287764181*uk_65 + 502367977*uk_66 + 156075488*uk_67 + 521877413*uk_68 + 1058386903*uk_69 + 217*uk_7 + 502367977*uk_70 + 48489472*uk_71 + 162136672*uk_72 + 328819232*uk_73 + 156075488*uk_74 + 542144497*uk_75 + 1099489307*uk_76 + 521877413*uk_77 + 2229805417*uk_78 + 1058386903*uk_79 + 103*uk_8 + 502367977*uk_80 + 250047*uk_81 + 234171*uk_82 + 408807*uk_83 + 127008*uk_84 + 424683*uk_85 + 861273*uk_86 + 408807*uk_87 + 219303*uk_88 + 382851*uk_89 + 2242306609*uk_9 + 118944*uk_90 + 397719*uk_91 + 806589*uk_92 + 382851*uk_93 + 668367*uk_94 + 207648*uk_95 + 694323*uk_96 + 1408113*uk_97 + 668367*uk_98 + 64512*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 219744*uk_100 + 437472*uk_101 + 118944*uk_102 + 748503*uk_103 + 1490139*uk_104 + 405153*uk_105 + 2966607*uk_106 + 806589*uk_107 + 219303*uk_108 + 103823*uk_109 + 2225591*uk_11 + 130331*uk_110 + 70688*uk_111 + 240781*uk_112 + 479353*uk_113 + 130331*uk_114 + 163607*uk_115 + 88736*uk_116 + 302257*uk_117 + 601741*uk_118 + 163607*uk_119 + 2793827*uk_12 + 48128*uk_120 + 163936*uk_121 + 326368*uk_122 + 88736*uk_123 + 558407*uk_124 + 1111691*uk_125 + 302257*uk_126 + 2213183*uk_127 + 601741*uk_128 + 163607*uk_129 + 1515296*uk_13 + 205379*uk_130 + 111392*uk_131 + 379429*uk_132 + 755377*uk_133 + 205379*uk_134 + 60416*uk_135 + 205792*uk_136 + 409696*uk_137 + 111392*uk_138 + 700979*uk_139 + 5161477*uk_14 + 1395527*uk_140 + 379429*uk_141 + 2778251*uk_142 + 755377*uk_143 + 205379*uk_144 + 32768*uk_145 + 111616*uk_146 + 222208*uk_147 + 60416*uk_148 + 380192*uk_149 + 10275601*uk_15 + 756896*uk_150 + 205792*uk_151 + 1506848*uk_152 + 409696*uk_153 + 111392*uk_154 + 1295029*uk_155 + 2578177*uk_156 + 700979*uk_157 + 5132701*uk_158 + 1395527*uk_159 + 2793827*uk_16 + 379429*uk_160 + 10218313*uk_161 + 2778251*uk_162 + 755377*uk_163 + 205379*uk_164 + 3969*uk_17 + 2961*uk_18 + 3717*uk_19 + 63*uk_2 + 2016*uk_20 + 6867*uk_21 + 13671*uk_22 + 3717*uk_23 + 2209*uk_24 + 2773*uk_25 + 1504*uk_26 + 5123*uk_27 + 10199*uk_28 + 2773*uk_29 + 47*uk_3 + 3481*uk_30 + 1888*uk_31 + 6431*uk_32 + 12803*uk_33 + 3481*uk_34 + 1024*uk_35 + 3488*uk_36 + 6944*uk_37 + 1888*uk_38 + 11881*uk_39 + 59*uk_4 + 23653*uk_40 + 6431*uk_41 + 47089*uk_42 + 12803*uk_43 + 3481*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 105388410623*uk_47 + 132296089931*uk_48 + 71753811488*uk_49 + 32*uk_5 + 244411420381*uk_50 + 486580534153*uk_51 + 132296089931*uk_52 + 187944057*uk_53 + 140212233*uk_54 + 176011101*uk_55 + 95463648*uk_56 + 325173051*uk_57 + 647362863*uk_58 + 176011101*uk_59 + 109*uk_6 + 104602777*uk_60 + 131309869*uk_61 + 71218912*uk_62 + 242589419*uk_63 + 482953247*uk_64 + 131309869*uk_65 + 164835793*uk_66 + 89402464*uk_67 + 304527143*uk_68 + 606260459*uk_69 + 217*uk_7 + 164835793*uk_70 + 48489472*uk_71 + 165167264*uk_72 + 328819232*uk_73 + 89402464*uk_74 + 562600993*uk_75 + 1120040509*uk_76 + 304527143*uk_77 + 2229805417*uk_78 + 606260459*uk_79 + 59*uk_8 + 164835793*uk_80 + 250047*uk_81 + 186543*uk_82 + 234171*uk_83 + 127008*uk_84 + 432621*uk_85 + 861273*uk_86 + 234171*uk_87 + 139167*uk_88 + 174699*uk_89 + 2242306609*uk_9 + 94752*uk_90 + 322749*uk_91 + 642537*uk_92 + 174699*uk_93 + 219303*uk_94 + 118944*uk_95 + 405153*uk_96 + 806589*uk_97 + 219303*uk_98 + 64512*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 223776*uk_100 + 437472*uk_101 + 94752*uk_102 + 776223*uk_103 + 1517481*uk_104 + 328671*uk_105 + 2966607*uk_106 + 642537*uk_107 + 139167*uk_108 + 300763*uk_109 + 3172651*uk_11 + 210983*uk_110 + 143648*uk_111 + 498279*uk_112 + 974113*uk_113 + 210983*uk_114 + 148003*uk_115 + 100768*uk_116 + 349539*uk_117 + 683333*uk_118 + 148003*uk_119 + 2225591*uk_12 + 68608*uk_120 + 237984*uk_121 + 465248*uk_122 + 100768*uk_123 + 825507*uk_124 + 1613829*uk_125 + 349539*uk_126 + 3154963*uk_127 + 683333*uk_128 + 148003*uk_129 + 1515296*uk_13 + 103823*uk_130 + 70688*uk_131 + 245199*uk_132 + 479353*uk_133 + 103823*uk_134 + 48128*uk_135 + 166944*uk_136 + 326368*uk_137 + 70688*uk_138 + 579087*uk_139 + 5256183*uk_14 + 1132089*uk_140 + 245199*uk_141 + 2213183*uk_142 + 479353*uk_143 + 103823*uk_144 + 32768*uk_145 + 113664*uk_146 + 222208*uk_147 + 48128*uk_148 + 394272*uk_149 + 10275601*uk_15 + 770784*uk_150 + 166944*uk_151 + 1506848*uk_152 + 326368*uk_153 + 70688*uk_154 + 1367631*uk_155 + 2673657*uk_156 + 579087*uk_157 + 5226879*uk_158 + 1132089*uk_159 + 2225591*uk_16 + 245199*uk_160 + 10218313*uk_161 + 2213183*uk_162 + 479353*uk_163 + 103823*uk_164 + 3969*uk_17 + 4221*uk_18 + 2961*uk_19 + 63*uk_2 + 2016*uk_20 + 6993*uk_21 + 13671*uk_22 + 2961*uk_23 + 4489*uk_24 + 3149*uk_25 + 2144*uk_26 + 7437*uk_27 + 14539*uk_28 + 3149*uk_29 + 67*uk_3 + 2209*uk_30 + 1504*uk_31 + 5217*uk_32 + 10199*uk_33 + 2209*uk_34 + 1024*uk_35 + 3552*uk_36 + 6944*uk_37 + 1504*uk_38 + 12321*uk_39 + 47*uk_4 + 24087*uk_40 + 5217*uk_41 + 47089*uk_42 + 10199*uk_43 + 2209*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 150234542803*uk_47 + 105388410623*uk_48 + 71753811488*uk_49 + 32*uk_5 + 248896033599*uk_50 + 486580534153*uk_51 + 105388410623*uk_52 + 187944057*uk_53 + 199877013*uk_54 + 140212233*uk_55 + 95463648*uk_56 + 331139529*uk_57 + 647362863*uk_58 + 140212233*uk_59 + 111*uk_6 + 212567617*uk_60 + 149114597*uk_61 + 101524832*uk_62 + 352164261*uk_63 + 688465267*uk_64 + 149114597*uk_65 + 104602777*uk_66 + 71218912*uk_67 + 247040601*uk_68 + 482953247*uk_69 + 217*uk_7 + 104602777*uk_70 + 48489472*uk_71 + 168197856*uk_72 + 328819232*uk_73 + 71218912*uk_74 + 583436313*uk_75 + 1140591711*uk_76 + 247040601*uk_77 + 2229805417*uk_78 + 482953247*uk_79 + 47*uk_8 + 104602777*uk_80 + 250047*uk_81 + 265923*uk_82 + 186543*uk_83 + 127008*uk_84 + 440559*uk_85 + 861273*uk_86 + 186543*uk_87 + 282807*uk_88 + 198387*uk_89 + 2242306609*uk_9 + 135072*uk_90 + 468531*uk_91 + 915957*uk_92 + 198387*uk_93 + 139167*uk_94 + 94752*uk_95 + 328671*uk_96 + 642537*uk_97 + 139167*uk_98 + 64512*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 199332*uk_100 + 382788*uk_101 + 118188*uk_102 + 804447*uk_103 + 1544823*uk_104 + 476973*uk_105 + 2966607*uk_106 + 915957*uk_107 + 282807*uk_108 + 216*uk_109 + 284118*uk_11 + 2412*uk_110 + 1008*uk_111 + 4068*uk_112 + 7812*uk_113 + 2412*uk_114 + 26934*uk_115 + 11256*uk_116 + 45426*uk_117 + 87234*uk_118 + 26934*uk_119 + 3172651*uk_12 + 4704*uk_120 + 18984*uk_121 + 36456*uk_122 + 11256*uk_123 + 76614*uk_124 + 147126*uk_125 + 45426*uk_126 + 282534*uk_127 + 87234*uk_128 + 26934*uk_129 + 1325884*uk_13 + 300763*uk_130 + 125692*uk_131 + 507257*uk_132 + 974113*uk_133 + 300763*uk_134 + 52528*uk_135 + 211988*uk_136 + 407092*uk_137 + 125692*uk_138 + 855523*uk_139 + 5350889*uk_14 + 1642907*uk_140 + 507257*uk_141 + 3154963*uk_142 + 974113*uk_143 + 300763*uk_144 + 21952*uk_145 + 88592*uk_146 + 170128*uk_147 + 52528*uk_148 + 357532*uk_149 + 10275601*uk_15 + 686588*uk_150 + 211988*uk_151 + 1318492*uk_152 + 407092*uk_153 + 125692*uk_154 + 1442897*uk_155 + 2770873*uk_156 + 855523*uk_157 + 5321057*uk_158 + 1642907*uk_159 + 3172651*uk_16 + 507257*uk_160 + 10218313*uk_161 + 3154963*uk_162 + 974113*uk_163 + 300763*uk_164 + 3969*uk_17 + 378*uk_18 + 4221*uk_19 + 63*uk_2 + 1764*uk_20 + 7119*uk_21 + 13671*uk_22 + 4221*uk_23 + 36*uk_24 + 402*uk_25 + 168*uk_26 + 678*uk_27 + 1302*uk_28 + 402*uk_29 + 6*uk_3 + 4489*uk_30 + 1876*uk_31 + 7571*uk_32 + 14539*uk_33 + 4489*uk_34 + 784*uk_35 + 3164*uk_36 + 6076*uk_37 + 1876*uk_38 + 12769*uk_39 + 67*uk_4 + 24521*uk_40 + 7571*uk_41 + 47089*uk_42 + 14539*uk_43 + 4489*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 13453839654*uk_47 + 150234542803*uk_48 + 62784585052*uk_49 + 28*uk_5 + 253380646817*uk_50 + 486580534153*uk_51 + 150234542803*uk_52 + 187944057*uk_53 + 17899434*uk_54 + 199877013*uk_55 + 83530692*uk_56 + 337106007*uk_57 + 647362863*uk_58 + 199877013*uk_59 + 113*uk_6 + 1704708*uk_60 + 19035906*uk_61 + 7955304*uk_62 + 32105334*uk_63 + 61653606*uk_64 + 19035906*uk_65 + 212567617*uk_66 + 88834228*uk_67 + 358509563*uk_68 + 688465267*uk_69 + 217*uk_7 + 212567617*uk_70 + 37124752*uk_71 + 149824892*uk_72 + 287716828*uk_73 + 88834228*uk_74 + 604650457*uk_75 + 1161142913*uk_76 + 358509563*uk_77 + 2229805417*uk_78 + 688465267*uk_79 + 67*uk_8 + 212567617*uk_80 + 250047*uk_81 + 23814*uk_82 + 265923*uk_83 + 111132*uk_84 + 448497*uk_85 + 861273*uk_86 + 265923*uk_87 + 2268*uk_88 + 25326*uk_89 + 2242306609*uk_9 + 10584*uk_90 + 42714*uk_91 + 82026*uk_92 + 25326*uk_93 + 282807*uk_94 + 118188*uk_95 + 476973*uk_96 + 915957*uk_97 + 282807*uk_98 + 49392*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 231840*uk_100 + 437472*uk_101 + 12096*uk_102 + 833175*uk_103 + 1572165*uk_104 + 43470*uk_105 + 2966607*uk_106 + 82026*uk_107 + 2268*uk_108 + 681472*uk_109 + 4167064*uk_11 + 46464*uk_110 + 247808*uk_111 + 890560*uk_112 + 1680448*uk_113 + 46464*uk_114 + 3168*uk_115 + 16896*uk_116 + 60720*uk_117 + 114576*uk_118 + 3168*uk_119 + 284118*uk_12 + 90112*uk_120 + 323840*uk_121 + 611072*uk_122 + 16896*uk_123 + 1163800*uk_124 + 2196040*uk_125 + 60720*uk_126 + 4143832*uk_127 + 114576*uk_128 + 3168*uk_129 + 1515296*uk_13 + 216*uk_130 + 1152*uk_131 + 4140*uk_132 + 7812*uk_133 + 216*uk_134 + 6144*uk_135 + 22080*uk_136 + 41664*uk_137 + 1152*uk_138 + 79350*uk_139 + 5445595*uk_14 + 149730*uk_140 + 4140*uk_141 + 282534*uk_142 + 7812*uk_143 + 216*uk_144 + 32768*uk_145 + 117760*uk_146 + 222208*uk_147 + 6144*uk_148 + 423200*uk_149 + 10275601*uk_15 + 798560*uk_150 + 22080*uk_151 + 1506848*uk_152 + 41664*uk_153 + 1152*uk_154 + 1520875*uk_155 + 2869825*uk_156 + 79350*uk_157 + 5415235*uk_158 + 149730*uk_159 + 284118*uk_16 + 4140*uk_160 + 10218313*uk_161 + 282534*uk_162 + 7812*uk_163 + 216*uk_164 + 3969*uk_17 + 5544*uk_18 + 378*uk_19 + 63*uk_2 + 2016*uk_20 + 7245*uk_21 + 13671*uk_22 + 378*uk_23 + 7744*uk_24 + 528*uk_25 + 2816*uk_26 + 10120*uk_27 + 19096*uk_28 + 528*uk_29 + 88*uk_3 + 36*uk_30 + 192*uk_31 + 690*uk_32 + 1302*uk_33 + 36*uk_34 + 1024*uk_35 + 3680*uk_36 + 6944*uk_37 + 192*uk_38 + 13225*uk_39 + 6*uk_4 + 24955*uk_40 + 690*uk_41 + 47089*uk_42 + 1302*uk_43 + 36*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 197322981592*uk_47 + 13453839654*uk_48 + 71753811488*uk_49 + 32*uk_5 + 257865260035*uk_50 + 486580534153*uk_51 + 13453839654*uk_52 + 187944057*uk_53 + 262525032*uk_54 + 17899434*uk_55 + 95463648*uk_56 + 343072485*uk_57 + 647362863*uk_58 + 17899434*uk_59 + 115*uk_6 + 366701632*uk_60 + 25002384*uk_61 + 133346048*uk_62 + 479212360*uk_63 + 904252888*uk_64 + 25002384*uk_65 + 1704708*uk_66 + 9091776*uk_67 + 32673570*uk_68 + 61653606*uk_69 + 217*uk_7 + 1704708*uk_70 + 48489472*uk_71 + 174259040*uk_72 + 328819232*uk_73 + 9091776*uk_74 + 626243425*uk_75 + 1181694115*uk_76 + 32673570*uk_77 + 2229805417*uk_78 + 61653606*uk_79 + 6*uk_8 + 1704708*uk_80 + 250047*uk_81 + 349272*uk_82 + 23814*uk_83 + 127008*uk_84 + 456435*uk_85 + 861273*uk_86 + 23814*uk_87 + 487872*uk_88 + 33264*uk_89 + 2242306609*uk_9 + 177408*uk_90 + 637560*uk_91 + 1203048*uk_92 + 33264*uk_93 + 2268*uk_94 + 12096*uk_95 + 43470*uk_96 + 82026*uk_97 + 2268*uk_98 + 64512*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 206388*uk_100 + 382788*uk_101 + 155232*uk_102 + 862407*uk_103 + 1599507*uk_104 + 648648*uk_105 + 2966607*uk_106 + 1203048*uk_107 + 487872*uk_108 + 614125*uk_109 + 4025005*uk_11 + 635800*uk_110 + 202300*uk_111 + 845325*uk_112 + 1567825*uk_113 + 635800*uk_114 + 658240*uk_115 + 209440*uk_116 + 875160*uk_117 + 1623160*uk_118 + 658240*uk_119 + 4167064*uk_12 + 66640*uk_120 + 278460*uk_121 + 516460*uk_122 + 209440*uk_123 + 1163565*uk_124 + 2158065*uk_125 + 875160*uk_126 + 4002565*uk_127 + 1623160*uk_128 + 658240*uk_129 + 1325884*uk_13 + 681472*uk_130 + 216832*uk_131 + 906048*uk_132 + 1680448*uk_133 + 681472*uk_134 + 68992*uk_135 + 288288*uk_136 + 534688*uk_137 + 216832*uk_138 + 1204632*uk_139 + 5540301*uk_14 + 2234232*uk_140 + 906048*uk_141 + 4143832*uk_142 + 1680448*uk_143 + 681472*uk_144 + 21952*uk_145 + 91728*uk_146 + 170128*uk_147 + 68992*uk_148 + 383292*uk_149 + 10275601*uk_15 + 710892*uk_150 + 288288*uk_151 + 1318492*uk_152 + 534688*uk_153 + 216832*uk_154 + 1601613*uk_155 + 2970513*uk_156 + 1204632*uk_157 + 5509413*uk_158 + 2234232*uk_159 + 4167064*uk_16 + 906048*uk_160 + 10218313*uk_161 + 4143832*uk_162 + 1680448*uk_163 + 681472*uk_164 + 3969*uk_17 + 5355*uk_18 + 5544*uk_19 + 63*uk_2 + 1764*uk_20 + 7371*uk_21 + 13671*uk_22 + 5544*uk_23 + 7225*uk_24 + 7480*uk_25 + 2380*uk_26 + 9945*uk_27 + 18445*uk_28 + 7480*uk_29 + 85*uk_3 + 7744*uk_30 + 2464*uk_31 + 10296*uk_32 + 19096*uk_33 + 7744*uk_34 + 784*uk_35 + 3276*uk_36 + 6076*uk_37 + 2464*uk_38 + 13689*uk_39 + 88*uk_4 + 25389*uk_40 + 10296*uk_41 + 47089*uk_42 + 19096*uk_43 + 7744*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 190596061765*uk_47 + 197322981592*uk_48 + 62784585052*uk_49 + 28*uk_5 + 262349873253*uk_50 + 486580534153*uk_51 + 197322981592*uk_52 + 187944057*uk_53 + 253575315*uk_54 + 262525032*uk_55 + 83530692*uk_56 + 349038963*uk_57 + 647362863*uk_58 + 262525032*uk_59 + 117*uk_6 + 342125425*uk_60 + 354200440*uk_61 + 112700140*uk_62 + 470925585*uk_63 + 873426085*uk_64 + 354200440*uk_65 + 366701632*uk_66 + 116677792*uk_67 + 487546488*uk_68 + 904252888*uk_69 + 217*uk_7 + 366701632*uk_70 + 37124752*uk_71 + 155128428*uk_72 + 287716828*uk_73 + 116677792*uk_74 + 648215217*uk_75 + 1202245317*uk_76 + 487546488*uk_77 + 2229805417*uk_78 + 904252888*uk_79 + 88*uk_8 + 366701632*uk_80 + 250047*uk_81 + 337365*uk_82 + 349272*uk_83 + 111132*uk_84 + 464373*uk_85 + 861273*uk_86 + 349272*uk_87 + 455175*uk_88 + 471240*uk_89 + 2242306609*uk_9 + 149940*uk_90 + 626535*uk_91 + 1162035*uk_92 + 471240*uk_93 + 487872*uk_94 + 155232*uk_95 + 648648*uk_96 + 1203048*uk_97 + 487872*uk_98 + 49392*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 209916*uk_100 + 382788*uk_101 + 149940*uk_102 + 892143*uk_103 + 1626849*uk_104 + 637245*uk_105 + 2966607*uk_106 + 1162035*uk_107 + 455175*uk_108 + 1331000*uk_109 + 5208830*uk_11 + 1028500*uk_110 + 338800*uk_111 + 1439900*uk_112 + 2625700*uk_113 + 1028500*uk_114 + 794750*uk_115 + 261800*uk_116 + 1112650*uk_117 + 2028950*uk_118 + 794750*uk_119 + 4025005*uk_12 + 86240*uk_120 + 366520*uk_121 + 668360*uk_122 + 261800*uk_123 + 1557710*uk_124 + 2840530*uk_125 + 1112650*uk_126 + 5179790*uk_127 + 2028950*uk_128 + 794750*uk_129 + 1325884*uk_13 + 614125*uk_130 + 202300*uk_131 + 859775*uk_132 + 1567825*uk_133 + 614125*uk_134 + 66640*uk_135 + 283220*uk_136 + 516460*uk_137 + 202300*uk_138 + 1203685*uk_139 + 5635007*uk_14 + 2194955*uk_140 + 859775*uk_141 + 4002565*uk_142 + 1567825*uk_143 + 614125*uk_144 + 21952*uk_145 + 93296*uk_146 + 170128*uk_147 + 66640*uk_148 + 396508*uk_149 + 10275601*uk_15 + 723044*uk_150 + 283220*uk_151 + 1318492*uk_152 + 516460*uk_153 + 202300*uk_154 + 1685159*uk_155 + 3072937*uk_156 + 1203685*uk_157 + 5603591*uk_158 + 2194955*uk_159 + 4025005*uk_16 + 859775*uk_160 + 10218313*uk_161 + 4002565*uk_162 + 1567825*uk_163 + 614125*uk_164 + 3969*uk_17 + 6930*uk_18 + 5355*uk_19 + 63*uk_2 + 1764*uk_20 + 7497*uk_21 + 13671*uk_22 + 5355*uk_23 + 12100*uk_24 + 9350*uk_25 + 3080*uk_26 + 13090*uk_27 + 23870*uk_28 + 9350*uk_29 + 110*uk_3 + 7225*uk_30 + 2380*uk_31 + 10115*uk_32 + 18445*uk_33 + 7225*uk_34 + 784*uk_35 + 3332*uk_36 + 6076*uk_37 + 2380*uk_38 + 14161*uk_39 + 85*uk_4 + 25823*uk_40 + 10115*uk_41 + 47089*uk_42 + 18445*uk_43 + 7225*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 246653726990*uk_47 + 190596061765*uk_48 + 62784585052*uk_49 + 28*uk_5 + 266834486471*uk_50 + 486580534153*uk_51 + 190596061765*uk_52 + 187944057*uk_53 + 328156290*uk_54 + 253575315*uk_55 + 83530692*uk_56 + 355005441*uk_57 + 647362863*uk_58 + 253575315*uk_59 + 119*uk_6 + 572971300*uk_60 + 442750550*uk_61 + 145847240*uk_62 + 619850770*uk_63 + 1130316110*uk_64 + 442750550*uk_65 + 342125425*uk_66 + 112700140*uk_67 + 478975595*uk_68 + 873426085*uk_69 + 217*uk_7 + 342125425*uk_70 + 37124752*uk_71 + 157780196*uk_72 + 287716828*uk_73 + 112700140*uk_74 + 670565833*uk_75 + 1222796519*uk_76 + 478975595*uk_77 + 2229805417*uk_78 + 873426085*uk_79 + 85*uk_8 + 342125425*uk_80 + 250047*uk_81 + 436590*uk_82 + 337365*uk_83 + 111132*uk_84 + 472311*uk_85 + 861273*uk_86 + 337365*uk_87 + 762300*uk_88 + 589050*uk_89 + 2242306609*uk_9 + 194040*uk_90 + 824670*uk_91 + 1503810*uk_92 + 589050*uk_93 + 455175*uk_94 + 149940*uk_95 + 637245*uk_96 + 1162035*uk_97 + 455175*uk_98 + 49392*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 182952*uk_100 + 328104*uk_101 + 166320*uk_102 + 922383*uk_103 + 1654191*uk_104 + 838530*uk_105 + 2966607*uk_106 + 1503810*uk_107 + 762300*uk_108 + 74088*uk_109 + 1988826*uk_11 + 194040*uk_110 + 42336*uk_111 + 213444*uk_112 + 382788*uk_113 + 194040*uk_114 + 508200*uk_115 + 110880*uk_116 + 559020*uk_117 + 1002540*uk_118 + 508200*uk_119 + 5208830*uk_12 + 24192*uk_120 + 121968*uk_121 + 218736*uk_122 + 110880*uk_123 + 614922*uk_124 + 1102794*uk_125 + 559020*uk_126 + 1977738*uk_127 + 1002540*uk_128 + 508200*uk_129 + 1136472*uk_13 + 1331000*uk_130 + 290400*uk_131 + 1464100*uk_132 + 2625700*uk_133 + 1331000*uk_134 + 63360*uk_135 + 319440*uk_136 + 572880*uk_137 + 290400*uk_138 + 1610510*uk_139 + 5729713*uk_14 + 2888270*uk_140 + 1464100*uk_141 + 5179790*uk_142 + 2625700*uk_143 + 1331000*uk_144 + 13824*uk_145 + 69696*uk_146 + 124992*uk_147 + 63360*uk_148 + 351384*uk_149 + 10275601*uk_15 + 630168*uk_150 + 319440*uk_151 + 1130136*uk_152 + 572880*uk_153 + 290400*uk_154 + 1771561*uk_155 + 3177097*uk_156 + 1610510*uk_157 + 5697769*uk_158 + 2888270*uk_159 + 5208830*uk_16 + 1464100*uk_160 + 10218313*uk_161 + 5179790*uk_162 + 2625700*uk_163 + 1331000*uk_164 + 3969*uk_17 + 2646*uk_18 + 6930*uk_19 + 63*uk_2 + 1512*uk_20 + 7623*uk_21 + 13671*uk_22 + 6930*uk_23 + 1764*uk_24 + 4620*uk_25 + 1008*uk_26 + 5082*uk_27 + 9114*uk_28 + 4620*uk_29 + 42*uk_3 + 12100*uk_30 + 2640*uk_31 + 13310*uk_32 + 23870*uk_33 + 12100*uk_34 + 576*uk_35 + 2904*uk_36 + 5208*uk_37 + 2640*uk_38 + 14641*uk_39 + 110*uk_4 + 26257*uk_40 + 13310*uk_41 + 47089*uk_42 + 23870*uk_43 + 12100*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 94176877578*uk_47 + 246653726990*uk_48 + 53815358616*uk_49 + 24*uk_5 + 271319099689*uk_50 + 486580534153*uk_51 + 246653726990*uk_52 + 187944057*uk_53 + 125296038*uk_54 + 328156290*uk_55 + 71597736*uk_56 + 360971919*uk_57 + 647362863*uk_58 + 328156290*uk_59 + 121*uk_6 + 83530692*uk_60 + 218770860*uk_61 + 47731824*uk_62 + 240647946*uk_63 + 431575242*uk_64 + 218770860*uk_65 + 572971300*uk_66 + 125011920*uk_67 + 630268430*uk_68 + 1130316110*uk_69 + 217*uk_7 + 572971300*uk_70 + 27275328*uk_71 + 137513112*uk_72 + 246614424*uk_73 + 125011920*uk_74 + 693295273*uk_75 + 1243347721*uk_76 + 630268430*uk_77 + 2229805417*uk_78 + 1130316110*uk_79 + 110*uk_8 + 572971300*uk_80 + 250047*uk_81 + 166698*uk_82 + 436590*uk_83 + 95256*uk_84 + 480249*uk_85 + 861273*uk_86 + 436590*uk_87 + 111132*uk_88 + 291060*uk_89 + 2242306609*uk_9 + 63504*uk_90 + 320166*uk_91 + 574182*uk_92 + 291060*uk_93 + 762300*uk_94 + 166320*uk_95 + 838530*uk_96 + 1503810*uk_97 + 762300*uk_98 + 36288*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 216972*uk_100 + 382788*uk_101 + 74088*uk_102 + 953127*uk_103 + 1681533*uk_104 + 325458*uk_105 + 2966607*uk_106 + 574182*uk_107 + 111132*uk_108 + 1771561*uk_109 + 5729713*uk_11 + 614922*uk_110 + 409948*uk_111 + 1800843*uk_112 + 3177097*uk_113 + 614922*uk_114 + 213444*uk_115 + 142296*uk_116 + 625086*uk_117 + 1102794*uk_118 + 213444*uk_119 + 1988826*uk_12 + 94864*uk_120 + 416724*uk_121 + 735196*uk_122 + 142296*uk_123 + 1830609*uk_124 + 3229611*uk_125 + 625086*uk_126 + 5697769*uk_127 + 1102794*uk_128 + 213444*uk_129 + 1325884*uk_13 + 74088*uk_130 + 49392*uk_131 + 216972*uk_132 + 382788*uk_133 + 74088*uk_134 + 32928*uk_135 + 144648*uk_136 + 255192*uk_137 + 49392*uk_138 + 635418*uk_139 + 5824419*uk_14 + 1121022*uk_140 + 216972*uk_141 + 1977738*uk_142 + 382788*uk_143 + 74088*uk_144 + 21952*uk_145 + 96432*uk_146 + 170128*uk_147 + 32928*uk_148 + 423612*uk_149 + 10275601*uk_15 + 747348*uk_150 + 144648*uk_151 + 1318492*uk_152 + 255192*uk_153 + 49392*uk_154 + 1860867*uk_155 + 3282993*uk_156 + 635418*uk_157 + 5791947*uk_158 + 1121022*uk_159 + 1988826*uk_16 + 216972*uk_160 + 10218313*uk_161 + 1977738*uk_162 + 382788*uk_163 + 74088*uk_164 + 3969*uk_17 + 7623*uk_18 + 2646*uk_19 + 63*uk_2 + 1764*uk_20 + 7749*uk_21 + 13671*uk_22 + 2646*uk_23 + 14641*uk_24 + 5082*uk_25 + 3388*uk_26 + 14883*uk_27 + 26257*uk_28 + 5082*uk_29 + 121*uk_3 + 1764*uk_30 + 1176*uk_31 + 5166*uk_32 + 9114*uk_33 + 1764*uk_34 + 784*uk_35 + 3444*uk_36 + 6076*uk_37 + 1176*uk_38 + 15129*uk_39 + 42*uk_4 + 26691*uk_40 + 5166*uk_41 + 47089*uk_42 + 9114*uk_43 + 1764*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 271319099689*uk_47 + 94176877578*uk_48 + 62784585052*uk_49 + 28*uk_5 + 275803712907*uk_50 + 486580534153*uk_51 + 94176877578*uk_52 + 187944057*uk_53 + 360971919*uk_54 + 125296038*uk_55 + 83530692*uk_56 + 366938397*uk_57 + 647362863*uk_58 + 125296038*uk_59 + 123*uk_6 + 693295273*uk_60 + 240647946*uk_61 + 160431964*uk_62 + 704754699*uk_63 + 1243347721*uk_64 + 240647946*uk_65 + 83530692*uk_66 + 55687128*uk_67 + 244625598*uk_68 + 431575242*uk_69 + 217*uk_7 + 83530692*uk_70 + 37124752*uk_71 + 163083732*uk_72 + 287716828*uk_73 + 55687128*uk_74 + 716403537*uk_75 + 1263898923*uk_76 + 244625598*uk_77 + 2229805417*uk_78 + 431575242*uk_79 + 42*uk_8 + 83530692*uk_80 + 250047*uk_81 + 480249*uk_82 + 166698*uk_83 + 111132*uk_84 + 488187*uk_85 + 861273*uk_86 + 166698*uk_87 + 922383*uk_88 + 320166*uk_89 + 2242306609*uk_9 + 213444*uk_90 + 937629*uk_91 + 1654191*uk_92 + 320166*uk_93 + 111132*uk_94 + 74088*uk_95 + 325458*uk_96 + 574182*uk_97 + 111132*uk_98 + 49392*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 189000*uk_100 + 328104*uk_101 + 182952*uk_102 + 984375*uk_103 + 1708875*uk_104 + 952875*uk_105 + 2966607*uk_106 + 1654191*uk_107 + 922383*uk_108 + 1092727*uk_109 + 4877359*uk_11 + 1283689*uk_110 + 254616*uk_111 + 1326125*uk_112 + 2302153*uk_113 + 1283689*uk_114 + 1508023*uk_115 + 299112*uk_116 + 1557875*uk_117 + 2704471*uk_118 + 1508023*uk_119 + 5729713*uk_12 + 59328*uk_120 + 309000*uk_121 + 536424*uk_122 + 299112*uk_123 + 1609375*uk_124 + 2793875*uk_125 + 1557875*uk_126 + 4850167*uk_127 + 2704471*uk_128 + 1508023*uk_129 + 1136472*uk_13 + 1771561*uk_130 + 351384*uk_131 + 1830125*uk_132 + 3177097*uk_133 + 1771561*uk_134 + 69696*uk_135 + 363000*uk_136 + 630168*uk_137 + 351384*uk_138 + 1890625*uk_139 + 5919125*uk_14 + 3282125*uk_140 + 1830125*uk_141 + 5697769*uk_142 + 3177097*uk_143 + 1771561*uk_144 + 13824*uk_145 + 72000*uk_146 + 124992*uk_147 + 69696*uk_148 + 375000*uk_149 + 10275601*uk_15 + 651000*uk_150 + 363000*uk_151 + 1130136*uk_152 + 630168*uk_153 + 351384*uk_154 + 1953125*uk_155 + 3390625*uk_156 + 1890625*uk_157 + 5886125*uk_158 + 3282125*uk_159 + 5729713*uk_16 + 1830125*uk_160 + 10218313*uk_161 + 5697769*uk_162 + 3177097*uk_163 + 1771561*uk_164 + 3969*uk_17 + 6489*uk_18 + 7623*uk_19 + 63*uk_2 + 1512*uk_20 + 7875*uk_21 + 13671*uk_22 + 7623*uk_23 + 10609*uk_24 + 12463*uk_25 + 2472*uk_26 + 12875*uk_27 + 22351*uk_28 + 12463*uk_29 + 103*uk_3 + 14641*uk_30 + 2904*uk_31 + 15125*uk_32 + 26257*uk_33 + 14641*uk_34 + 576*uk_35 + 3000*uk_36 + 5208*uk_37 + 2904*uk_38 + 15625*uk_39 + 121*uk_4 + 27125*uk_40 + 15125*uk_41 + 47089*uk_42 + 26257*uk_43 + 14641*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 230957580727*uk_47 + 271319099689*uk_48 + 53815358616*uk_49 + 24*uk_5 + 280288326125*uk_50 + 486580534153*uk_51 + 271319099689*uk_52 + 187944057*uk_53 + 307273617*uk_54 + 360971919*uk_55 + 71597736*uk_56 + 372904875*uk_57 + 647362863*uk_58 + 360971919*uk_59 + 125*uk_6 + 502367977*uk_60 + 590160439*uk_61 + 117056616*uk_62 + 609669875*uk_63 + 1058386903*uk_64 + 590160439*uk_65 + 693295273*uk_66 + 137513112*uk_67 + 716214125*uk_68 + 1243347721*uk_69 + 217*uk_7 + 693295273*uk_70 + 27275328*uk_71 + 142059000*uk_72 + 246614424*uk_73 + 137513112*uk_74 + 739890625*uk_75 + 1284450125*uk_76 + 716214125*uk_77 + 2229805417*uk_78 + 1243347721*uk_79 + 121*uk_8 + 693295273*uk_80 + 250047*uk_81 + 408807*uk_82 + 480249*uk_83 + 95256*uk_84 + 496125*uk_85 + 861273*uk_86 + 480249*uk_87 + 668367*uk_88 + 785169*uk_89 + 2242306609*uk_9 + 155736*uk_90 + 811125*uk_91 + 1408113*uk_92 + 785169*uk_93 + 922383*uk_94 + 182952*uk_95 + 952875*uk_96 + 1654191*uk_97 + 922383*uk_98 + 36288*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 192024*uk_100 + 328104*uk_101 + 155736*uk_102 + 1016127*uk_103 + 1736217*uk_104 + 824103*uk_105 + 2966607*uk_106 + 1408113*uk_107 + 668367*uk_108 + 1295029*uk_109 + 5161477*uk_11 + 1223743*uk_110 + 285144*uk_111 + 1508887*uk_112 + 2578177*uk_113 + 1223743*uk_114 + 1156381*uk_115 + 269448*uk_116 + 1425829*uk_117 + 2436259*uk_118 + 1156381*uk_119 + 4877359*uk_12 + 62784*uk_120 + 332232*uk_121 + 567672*uk_122 + 269448*uk_123 + 1758061*uk_124 + 3003931*uk_125 + 1425829*uk_126 + 5132701*uk_127 + 2436259*uk_128 + 1156381*uk_129 + 1136472*uk_13 + 1092727*uk_130 + 254616*uk_131 + 1347343*uk_132 + 2302153*uk_133 + 1092727*uk_134 + 59328*uk_135 + 313944*uk_136 + 536424*uk_137 + 254616*uk_138 + 1661287*uk_139 + 6013831*uk_14 + 2838577*uk_140 + 1347343*uk_141 + 4850167*uk_142 + 2302153*uk_143 + 1092727*uk_144 + 13824*uk_145 + 73152*uk_146 + 124992*uk_147 + 59328*uk_148 + 387096*uk_149 + 10275601*uk_15 + 661416*uk_150 + 313944*uk_151 + 1130136*uk_152 + 536424*uk_153 + 254616*uk_154 + 2048383*uk_155 + 3499993*uk_156 + 1661287*uk_157 + 5980303*uk_158 + 2838577*uk_159 + 4877359*uk_16 + 1347343*uk_160 + 10218313*uk_161 + 4850167*uk_162 + 2302153*uk_163 + 1092727*uk_164 + 3969*uk_17 + 6867*uk_18 + 6489*uk_19 + 63*uk_2 + 1512*uk_20 + 8001*uk_21 + 13671*uk_22 + 6489*uk_23 + 11881*uk_24 + 11227*uk_25 + 2616*uk_26 + 13843*uk_27 + 23653*uk_28 + 11227*uk_29 + 109*uk_3 + 10609*uk_30 + 2472*uk_31 + 13081*uk_32 + 22351*uk_33 + 10609*uk_34 + 576*uk_35 + 3048*uk_36 + 5208*uk_37 + 2472*uk_38 + 16129*uk_39 + 103*uk_4 + 27559*uk_40 + 13081*uk_41 + 47089*uk_42 + 22351*uk_43 + 10609*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 244411420381*uk_47 + 230957580727*uk_48 + 53815358616*uk_49 + 24*uk_5 + 284772939343*uk_50 + 486580534153*uk_51 + 230957580727*uk_52 + 187944057*uk_53 + 325173051*uk_54 + 307273617*uk_55 + 71597736*uk_56 + 378871353*uk_57 + 647362863*uk_58 + 307273617*uk_59 + 127*uk_6 + 562600993*uk_60 + 531632131*uk_61 + 123875448*uk_62 + 655507579*uk_63 + 1120040509*uk_64 + 531632131*uk_65 + 502367977*uk_66 + 117056616*uk_67 + 619424593*uk_68 + 1058386903*uk_69 + 217*uk_7 + 502367977*uk_70 + 27275328*uk_71 + 144331944*uk_72 + 246614424*uk_73 + 117056616*uk_74 + 763756537*uk_75 + 1305001327*uk_76 + 619424593*uk_77 + 2229805417*uk_78 + 1058386903*uk_79 + 103*uk_8 + 502367977*uk_80 + 250047*uk_81 + 432621*uk_82 + 408807*uk_83 + 95256*uk_84 + 504063*uk_85 + 861273*uk_86 + 408807*uk_87 + 748503*uk_88 + 707301*uk_89 + 2242306609*uk_9 + 164808*uk_90 + 872109*uk_91 + 1490139*uk_92 + 707301*uk_93 + 668367*uk_94 + 155736*uk_95 + 824103*uk_96 + 1408113*uk_97 + 668367*uk_98 + 36288*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 162540*uk_100 + 273420*uk_101 + 137340*uk_102 + 1048383*uk_103 + 1763559*uk_104 + 885843*uk_105 + 2966607*uk_106 + 1490139*uk_107 + 748503*uk_108 + 1000*uk_109 + 473530*uk_11 + 10900*uk_110 + 2000*uk_111 + 12900*uk_112 + 21700*uk_113 + 10900*uk_114 + 118810*uk_115 + 21800*uk_116 + 140610*uk_117 + 236530*uk_118 + 118810*uk_119 + 5161477*uk_12 + 4000*uk_120 + 25800*uk_121 + 43400*uk_122 + 21800*uk_123 + 166410*uk_124 + 279930*uk_125 + 140610*uk_126 + 470890*uk_127 + 236530*uk_128 + 118810*uk_129 + 947060*uk_13 + 1295029*uk_130 + 237620*uk_131 + 1532649*uk_132 + 2578177*uk_133 + 1295029*uk_134 + 43600*uk_135 + 281220*uk_136 + 473060*uk_137 + 237620*uk_138 + 1813869*uk_139 + 6108537*uk_14 + 3051237*uk_140 + 1532649*uk_141 + 5132701*uk_142 + 2578177*uk_143 + 1295029*uk_144 + 8000*uk_145 + 51600*uk_146 + 86800*uk_147 + 43600*uk_148 + 332820*uk_149 + 10275601*uk_15 + 559860*uk_150 + 281220*uk_151 + 941780*uk_152 + 473060*uk_153 + 237620*uk_154 + 2146689*uk_155 + 3611097*uk_156 + 1813869*uk_157 + 6074481*uk_158 + 3051237*uk_159 + 5161477*uk_16 + 1532649*uk_160 + 10218313*uk_161 + 5132701*uk_162 + 2578177*uk_163 + 1295029*uk_164 + 3969*uk_17 + 630*uk_18 + 6867*uk_19 + 63*uk_2 + 1260*uk_20 + 8127*uk_21 + 13671*uk_22 + 6867*uk_23 + 100*uk_24 + 1090*uk_25 + 200*uk_26 + 1290*uk_27 + 2170*uk_28 + 1090*uk_29 + 10*uk_3 + 11881*uk_30 + 2180*uk_31 + 14061*uk_32 + 23653*uk_33 + 11881*uk_34 + 400*uk_35 + 2580*uk_36 + 4340*uk_37 + 2180*uk_38 + 16641*uk_39 + 109*uk_4 + 27993*uk_40 + 14061*uk_41 + 47089*uk_42 + 23653*uk_43 + 11881*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 22423066090*uk_47 + 244411420381*uk_48 + 44846132180*uk_49 + 20*uk_5 + 289257552561*uk_50 + 486580534153*uk_51 + 244411420381*uk_52 + 187944057*uk_53 + 29832390*uk_54 + 325173051*uk_55 + 59664780*uk_56 + 384837831*uk_57 + 647362863*uk_58 + 325173051*uk_59 + 129*uk_6 + 4735300*uk_60 + 51614770*uk_61 + 9470600*uk_62 + 61085370*uk_63 + 102756010*uk_64 + 51614770*uk_65 + 562600993*uk_66 + 103229540*uk_67 + 665830533*uk_68 + 1120040509*uk_69 + 217*uk_7 + 562600993*uk_70 + 18941200*uk_71 + 122170740*uk_72 + 205512020*uk_73 + 103229540*uk_74 + 788001273*uk_75 + 1325552529*uk_76 + 665830533*uk_77 + 2229805417*uk_78 + 1120040509*uk_79 + 109*uk_8 + 562600993*uk_80 + 250047*uk_81 + 39690*uk_82 + 432621*uk_83 + 79380*uk_84 + 512001*uk_85 + 861273*uk_86 + 432621*uk_87 + 6300*uk_88 + 68670*uk_89 + 2242306609*uk_9 + 12600*uk_90 + 81270*uk_91 + 136710*uk_92 + 68670*uk_93 + 748503*uk_94 + 137340*uk_95 + 885843*uk_96 + 1490139*uk_97 + 748503*uk_98 + 25200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 198072*uk_100 + 328104*uk_101 + 15120*uk_102 + 1081143*uk_103 + 1790901*uk_104 + 82530*uk_105 + 2966607*uk_106 + 136710*uk_107 + 6300*uk_108 + 238328*uk_109 + 2935886*uk_11 + 38440*uk_110 + 92256*uk_111 + 503564*uk_112 + 834148*uk_113 + 38440*uk_114 + 6200*uk_115 + 14880*uk_116 + 81220*uk_117 + 134540*uk_118 + 6200*uk_119 + 473530*uk_12 + 35712*uk_120 + 194928*uk_121 + 322896*uk_122 + 14880*uk_123 + 1063982*uk_124 + 1762474*uk_125 + 81220*uk_126 + 2919518*uk_127 + 134540*uk_128 + 6200*uk_129 + 1136472*uk_13 + 1000*uk_130 + 2400*uk_131 + 13100*uk_132 + 21700*uk_133 + 1000*uk_134 + 5760*uk_135 + 31440*uk_136 + 52080*uk_137 + 2400*uk_138 + 171610*uk_139 + 6203243*uk_14 + 284270*uk_140 + 13100*uk_141 + 470890*uk_142 + 21700*uk_143 + 1000*uk_144 + 13824*uk_145 + 75456*uk_146 + 124992*uk_147 + 5760*uk_148 + 411864*uk_149 + 10275601*uk_15 + 682248*uk_150 + 31440*uk_151 + 1130136*uk_152 + 52080*uk_153 + 2400*uk_154 + 2248091*uk_155 + 3723937*uk_156 + 171610*uk_157 + 6168659*uk_158 + 284270*uk_159 + 473530*uk_16 + 13100*uk_160 + 10218313*uk_161 + 470890*uk_162 + 21700*uk_163 + 1000*uk_164 + 3969*uk_17 + 3906*uk_18 + 630*uk_19 + 63*uk_2 + 1512*uk_20 + 8253*uk_21 + 13671*uk_22 + 630*uk_23 + 3844*uk_24 + 620*uk_25 + 1488*uk_26 + 8122*uk_27 + 13454*uk_28 + 620*uk_29 + 62*uk_3 + 100*uk_30 + 240*uk_31 + 1310*uk_32 + 2170*uk_33 + 100*uk_34 + 576*uk_35 + 3144*uk_36 + 5208*uk_37 + 240*uk_38 + 17161*uk_39 + 10*uk_4 + 28427*uk_40 + 1310*uk_41 + 47089*uk_42 + 2170*uk_43 + 100*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 139023009758*uk_47 + 22423066090*uk_48 + 53815358616*uk_49 + 24*uk_5 + 293742165779*uk_50 + 486580534153*uk_51 + 22423066090*uk_52 + 187944057*uk_53 + 184960818*uk_54 + 29832390*uk_55 + 71597736*uk_56 + 390804309*uk_57 + 647362863*uk_58 + 29832390*uk_59 + 131*uk_6 + 182024932*uk_60 + 29358860*uk_61 + 70461264*uk_62 + 384601066*uk_63 + 637087262*uk_64 + 29358860*uk_65 + 4735300*uk_66 + 11364720*uk_67 + 62032430*uk_68 + 102756010*uk_69 + 217*uk_7 + 4735300*uk_70 + 27275328*uk_71 + 148877832*uk_72 + 246614424*uk_73 + 11364720*uk_74 + 812624833*uk_75 + 1346103731*uk_76 + 62032430*uk_77 + 2229805417*uk_78 + 102756010*uk_79 + 10*uk_8 + 4735300*uk_80 + 250047*uk_81 + 246078*uk_82 + 39690*uk_83 + 95256*uk_84 + 519939*uk_85 + 861273*uk_86 + 39690*uk_87 + 242172*uk_88 + 39060*uk_89 + 2242306609*uk_9 + 93744*uk_90 + 511686*uk_91 + 847602*uk_92 + 39060*uk_93 + 6300*uk_94 + 15120*uk_95 + 82530*uk_96 + 136710*uk_97 + 6300*uk_98 + 36288*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 167580*uk_100 + 273420*uk_101 + 78120*uk_102 + 1114407*uk_103 + 1818243*uk_104 + 519498*uk_105 + 2966607*uk_106 + 847602*uk_107 + 242172*uk_108 + 125*uk_109 + 236765*uk_11 + 1550*uk_110 + 500*uk_111 + 3325*uk_112 + 5425*uk_113 + 1550*uk_114 + 19220*uk_115 + 6200*uk_116 + 41230*uk_117 + 67270*uk_118 + 19220*uk_119 + 2935886*uk_12 + 2000*uk_120 + 13300*uk_121 + 21700*uk_122 + 6200*uk_123 + 88445*uk_124 + 144305*uk_125 + 41230*uk_126 + 235445*uk_127 + 67270*uk_128 + 19220*uk_129 + 947060*uk_13 + 238328*uk_130 + 76880*uk_131 + 511252*uk_132 + 834148*uk_133 + 238328*uk_134 + 24800*uk_135 + 164920*uk_136 + 269080*uk_137 + 76880*uk_138 + 1096718*uk_139 + 6297949*uk_14 + 1789382*uk_140 + 511252*uk_141 + 2919518*uk_142 + 834148*uk_143 + 238328*uk_144 + 8000*uk_145 + 53200*uk_146 + 86800*uk_147 + 24800*uk_148 + 353780*uk_149 + 10275601*uk_15 + 577220*uk_150 + 164920*uk_151 + 941780*uk_152 + 269080*uk_153 + 76880*uk_154 + 2352637*uk_155 + 3838513*uk_156 + 1096718*uk_157 + 6262837*uk_158 + 1789382*uk_159 + 2935886*uk_16 + 511252*uk_160 + 10218313*uk_161 + 2919518*uk_162 + 834148*uk_163 + 238328*uk_164 + 3969*uk_17 + 315*uk_18 + 3906*uk_19 + 63*uk_2 + 1260*uk_20 + 8379*uk_21 + 13671*uk_22 + 3906*uk_23 + 25*uk_24 + 310*uk_25 + 100*uk_26 + 665*uk_27 + 1085*uk_28 + 310*uk_29 + 5*uk_3 + 3844*uk_30 + 1240*uk_31 + 8246*uk_32 + 13454*uk_33 + 3844*uk_34 + 400*uk_35 + 2660*uk_36 + 4340*uk_37 + 1240*uk_38 + 17689*uk_39 + 62*uk_4 + 28861*uk_40 + 8246*uk_41 + 47089*uk_42 + 13454*uk_43 + 3844*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 11211533045*uk_47 + 139023009758*uk_48 + 44846132180*uk_49 + 20*uk_5 + 298226778997*uk_50 + 486580534153*uk_51 + 139023009758*uk_52 + 187944057*uk_53 + 14916195*uk_54 + 184960818*uk_55 + 59664780*uk_56 + 396770787*uk_57 + 647362863*uk_58 + 184960818*uk_59 + 133*uk_6 + 1183825*uk_60 + 14679430*uk_61 + 4735300*uk_62 + 31489745*uk_63 + 51378005*uk_64 + 14679430*uk_65 + 182024932*uk_66 + 58717720*uk_67 + 390472838*uk_68 + 637087262*uk_69 + 217*uk_7 + 182024932*uk_70 + 18941200*uk_71 + 125958980*uk_72 + 205512020*uk_73 + 58717720*uk_74 + 837627217*uk_75 + 1366654933*uk_76 + 390472838*uk_77 + 2229805417*uk_78 + 637087262*uk_79 + 62*uk_8 + 182024932*uk_80 + 250047*uk_81 + 19845*uk_82 + 246078*uk_83 + 79380*uk_84 + 527877*uk_85 + 861273*uk_86 + 246078*uk_87 + 1575*uk_88 + 19530*uk_89 + 2242306609*uk_9 + 6300*uk_90 + 41895*uk_91 + 68355*uk_92 + 19530*uk_93 + 242172*uk_94 + 78120*uk_95 + 519498*uk_96 + 847602*uk_97 + 242172*uk_98 + 25200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 204120*uk_100 + 328104*uk_101 + 7560*uk_102 + 1148175*uk_103 + 1845585*uk_104 + 42525*uk_105 + 2966607*uk_106 + 68355*uk_107 + 1575*uk_108 + 1092727*uk_109 + 4877359*uk_11 + 53045*uk_110 + 254616*uk_111 + 1432215*uk_112 + 2302153*uk_113 + 53045*uk_114 + 2575*uk_115 + 12360*uk_116 + 69525*uk_117 + 111755*uk_118 + 2575*uk_119 + 236765*uk_12 + 59328*uk_120 + 333720*uk_121 + 536424*uk_122 + 12360*uk_123 + 1877175*uk_124 + 3017385*uk_125 + 69525*uk_126 + 4850167*uk_127 + 111755*uk_128 + 2575*uk_129 + 1136472*uk_13 + 125*uk_130 + 600*uk_131 + 3375*uk_132 + 5425*uk_133 + 125*uk_134 + 2880*uk_135 + 16200*uk_136 + 26040*uk_137 + 600*uk_138 + 91125*uk_139 + 6392655*uk_14 + 146475*uk_140 + 3375*uk_141 + 235445*uk_142 + 5425*uk_143 + 125*uk_144 + 13824*uk_145 + 77760*uk_146 + 124992*uk_147 + 2880*uk_148 + 437400*uk_149 + 10275601*uk_15 + 703080*uk_150 + 16200*uk_151 + 1130136*uk_152 + 26040*uk_153 + 600*uk_154 + 2460375*uk_155 + 3954825*uk_156 + 91125*uk_157 + 6357015*uk_158 + 146475*uk_159 + 236765*uk_16 + 3375*uk_160 + 10218313*uk_161 + 235445*uk_162 + 5425*uk_163 + 125*uk_164 + 3969*uk_17 + 6489*uk_18 + 315*uk_19 + 63*uk_2 + 1512*uk_20 + 8505*uk_21 + 13671*uk_22 + 315*uk_23 + 10609*uk_24 + 515*uk_25 + 2472*uk_26 + 13905*uk_27 + 22351*uk_28 + 515*uk_29 + 103*uk_3 + 25*uk_30 + 120*uk_31 + 675*uk_32 + 1085*uk_33 + 25*uk_34 + 576*uk_35 + 3240*uk_36 + 5208*uk_37 + 120*uk_38 + 18225*uk_39 + 5*uk_4 + 29295*uk_40 + 675*uk_41 + 47089*uk_42 + 1085*uk_43 + 25*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 230957580727*uk_47 + 11211533045*uk_48 + 53815358616*uk_49 + 24*uk_5 + 302711392215*uk_50 + 486580534153*uk_51 + 11211533045*uk_52 + 187944057*uk_53 + 307273617*uk_54 + 14916195*uk_55 + 71597736*uk_56 + 402737265*uk_57 + 647362863*uk_58 + 14916195*uk_59 + 135*uk_6 + 502367977*uk_60 + 24386795*uk_61 + 117056616*uk_62 + 658443465*uk_63 + 1058386903*uk_64 + 24386795*uk_65 + 1183825*uk_66 + 5682360*uk_67 + 31963275*uk_68 + 51378005*uk_69 + 217*uk_7 + 1183825*uk_70 + 27275328*uk_71 + 153423720*uk_72 + 246614424*uk_73 + 5682360*uk_74 + 863008425*uk_75 + 1387206135*uk_76 + 31963275*uk_77 + 2229805417*uk_78 + 51378005*uk_79 + 5*uk_8 + 1183825*uk_80 + 250047*uk_81 + 408807*uk_82 + 19845*uk_83 + 95256*uk_84 + 535815*uk_85 + 861273*uk_86 + 19845*uk_87 + 668367*uk_88 + 32445*uk_89 + 2242306609*uk_9 + 155736*uk_90 + 876015*uk_91 + 1408113*uk_92 + 32445*uk_93 + 1575*uk_94 + 7560*uk_95 + 42525*uk_96 + 68355*uk_97 + 1575*uk_98 + 36288*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 172620*uk_100 + 273420*uk_101 + 129780*uk_102 + 1182447*uk_103 + 1872927*uk_104 + 888993*uk_105 + 2966607*uk_106 + 1408113*uk_107 + 668367*uk_108 + 681472*uk_109 + 4167064*uk_11 + 797632*uk_110 + 154880*uk_111 + 1060928*uk_112 + 1680448*uk_113 + 797632*uk_114 + 933592*uk_115 + 181280*uk_116 + 1241768*uk_117 + 1966888*uk_118 + 933592*uk_119 + 4877359*uk_12 + 35200*uk_120 + 241120*uk_121 + 381920*uk_122 + 181280*uk_123 + 1651672*uk_124 + 2616152*uk_125 + 1241768*uk_126 + 4143832*uk_127 + 1966888*uk_128 + 933592*uk_129 + 947060*uk_13 + 1092727*uk_130 + 212180*uk_131 + 1453433*uk_132 + 2302153*uk_133 + 1092727*uk_134 + 41200*uk_135 + 282220*uk_136 + 447020*uk_137 + 212180*uk_138 + 1933207*uk_139 + 6487361*uk_14 + 3062087*uk_140 + 1453433*uk_141 + 4850167*uk_142 + 2302153*uk_143 + 1092727*uk_144 + 8000*uk_145 + 54800*uk_146 + 86800*uk_147 + 41200*uk_148 + 375380*uk_149 + 10275601*uk_15 + 594580*uk_150 + 282220*uk_151 + 941780*uk_152 + 447020*uk_153 + 212180*uk_154 + 2571353*uk_155 + 4072873*uk_156 + 1933207*uk_157 + 6451193*uk_158 + 3062087*uk_159 + 4877359*uk_16 + 1453433*uk_160 + 10218313*uk_161 + 4850167*uk_162 + 2302153*uk_163 + 1092727*uk_164 + 3969*uk_17 + 5544*uk_18 + 6489*uk_19 + 63*uk_2 + 1260*uk_20 + 8631*uk_21 + 13671*uk_22 + 6489*uk_23 + 7744*uk_24 + 9064*uk_25 + 1760*uk_26 + 12056*uk_27 + 19096*uk_28 + 9064*uk_29 + 88*uk_3 + 10609*uk_30 + 2060*uk_31 + 14111*uk_32 + 22351*uk_33 + 10609*uk_34 + 400*uk_35 + 2740*uk_36 + 4340*uk_37 + 2060*uk_38 + 18769*uk_39 + 103*uk_4 + 29729*uk_40 + 14111*uk_41 + 47089*uk_42 + 22351*uk_43 + 10609*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 197322981592*uk_47 + 230957580727*uk_48 + 44846132180*uk_49 + 20*uk_5 + 307196005433*uk_50 + 486580534153*uk_51 + 230957580727*uk_52 + 187944057*uk_53 + 262525032*uk_54 + 307273617*uk_55 + 59664780*uk_56 + 408703743*uk_57 + 647362863*uk_58 + 307273617*uk_59 + 137*uk_6 + 366701632*uk_60 + 429207592*uk_61 + 83341280*uk_62 + 570887768*uk_63 + 904252888*uk_64 + 429207592*uk_65 + 502367977*uk_66 + 97547180*uk_67 + 668198183*uk_68 + 1058386903*uk_69 + 217*uk_7 + 502367977*uk_70 + 18941200*uk_71 + 129747220*uk_72 + 205512020*uk_73 + 97547180*uk_74 + 888768457*uk_75 + 1407757337*uk_76 + 668198183*uk_77 + 2229805417*uk_78 + 1058386903*uk_79 + 103*uk_8 + 502367977*uk_80 + 250047*uk_81 + 349272*uk_82 + 408807*uk_83 + 79380*uk_84 + 543753*uk_85 + 861273*uk_86 + 408807*uk_87 + 487872*uk_88 + 571032*uk_89 + 2242306609*uk_9 + 110880*uk_90 + 759528*uk_91 + 1203048*uk_92 + 571032*uk_93 + 668367*uk_94 + 129780*uk_95 + 888993*uk_96 + 1408113*uk_97 + 668367*uk_98 + 25200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 175140*uk_100 + 273420*uk_101 + 110880*uk_102 + 1217223*uk_103 + 1900269*uk_104 + 770616*uk_105 + 2966607*uk_106 + 1203048*uk_107 + 487872*uk_108 + 804357*uk_109 + 4403829*uk_11 + 761112*uk_110 + 172980*uk_111 + 1202211*uk_112 + 1876833*uk_113 + 761112*uk_114 + 720192*uk_115 + 163680*uk_116 + 1137576*uk_117 + 1775928*uk_118 + 720192*uk_119 + 4167064*uk_12 + 37200*uk_120 + 258540*uk_121 + 403620*uk_122 + 163680*uk_123 + 1796853*uk_124 + 2805159*uk_125 + 1137576*uk_126 + 4379277*uk_127 + 1775928*uk_128 + 720192*uk_129 + 947060*uk_13 + 681472*uk_130 + 154880*uk_131 + 1076416*uk_132 + 1680448*uk_133 + 681472*uk_134 + 35200*uk_135 + 244640*uk_136 + 381920*uk_137 + 154880*uk_138 + 1700248*uk_139 + 6582067*uk_14 + 2654344*uk_140 + 1076416*uk_141 + 4143832*uk_142 + 1680448*uk_143 + 681472*uk_144 + 8000*uk_145 + 55600*uk_146 + 86800*uk_147 + 35200*uk_148 + 386420*uk_149 + 10275601*uk_15 + 603260*uk_150 + 244640*uk_151 + 941780*uk_152 + 381920*uk_153 + 154880*uk_154 + 2685619*uk_155 + 4192657*uk_156 + 1700248*uk_157 + 6545371*uk_158 + 2654344*uk_159 + 4167064*uk_16 + 1076416*uk_160 + 10218313*uk_161 + 4143832*uk_162 + 1680448*uk_163 + 681472*uk_164 + 3969*uk_17 + 5859*uk_18 + 5544*uk_19 + 63*uk_2 + 1260*uk_20 + 8757*uk_21 + 13671*uk_22 + 5544*uk_23 + 8649*uk_24 + 8184*uk_25 + 1860*uk_26 + 12927*uk_27 + 20181*uk_28 + 8184*uk_29 + 93*uk_3 + 7744*uk_30 + 1760*uk_31 + 12232*uk_32 + 19096*uk_33 + 7744*uk_34 + 400*uk_35 + 2780*uk_36 + 4340*uk_37 + 1760*uk_38 + 19321*uk_39 + 88*uk_4 + 30163*uk_40 + 12232*uk_41 + 47089*uk_42 + 19096*uk_43 + 7744*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 208534514637*uk_47 + 197322981592*uk_48 + 44846132180*uk_49 + 20*uk_5 + 311680618651*uk_50 + 486580534153*uk_51 + 197322981592*uk_52 + 187944057*uk_53 + 277441227*uk_54 + 262525032*uk_55 + 59664780*uk_56 + 414670221*uk_57 + 647362863*uk_58 + 262525032*uk_59 + 139*uk_6 + 409556097*uk_60 + 387536952*uk_61 + 88076580*uk_62 + 612132231*uk_63 + 955630893*uk_64 + 387536952*uk_65 + 366701632*uk_66 + 83341280*uk_67 + 579221896*uk_68 + 904252888*uk_69 + 217*uk_7 + 366701632*uk_70 + 18941200*uk_71 + 131641340*uk_72 + 205512020*uk_73 + 83341280*uk_74 + 914907313*uk_75 + 1428308539*uk_76 + 579221896*uk_77 + 2229805417*uk_78 + 904252888*uk_79 + 88*uk_8 + 366701632*uk_80 + 250047*uk_81 + 369117*uk_82 + 349272*uk_83 + 79380*uk_84 + 551691*uk_85 + 861273*uk_86 + 349272*uk_87 + 544887*uk_88 + 515592*uk_89 + 2242306609*uk_9 + 117180*uk_90 + 814401*uk_91 + 1271403*uk_92 + 515592*uk_93 + 487872*uk_94 + 110880*uk_95 + 770616*uk_96 + 1203048*uk_97 + 487872*uk_98 + 25200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 177660*uk_100 + 273420*uk_101 + 117180*uk_102 + 1252503*uk_103 + 1927611*uk_104 + 826119*uk_105 + 2966607*uk_106 + 1271403*uk_107 + 544887*uk_108 + 1643032*uk_109 + 5587654*uk_11 + 1294932*uk_110 + 278480*uk_111 + 1963284*uk_112 + 3021508*uk_113 + 1294932*uk_114 + 1020582*uk_115 + 219480*uk_116 + 1547334*uk_117 + 2381358*uk_118 + 1020582*uk_119 + 4403829*uk_12 + 47200*uk_120 + 332760*uk_121 + 512120*uk_122 + 219480*uk_123 + 2345958*uk_124 + 3610446*uk_125 + 1547334*uk_126 + 5556502*uk_127 + 2381358*uk_128 + 1020582*uk_129 + 947060*uk_13 + 804357*uk_130 + 172980*uk_131 + 1219509*uk_132 + 1876833*uk_133 + 804357*uk_134 + 37200*uk_135 + 262260*uk_136 + 403620*uk_137 + 172980*uk_138 + 1848933*uk_139 + 6676773*uk_14 + 2845521*uk_140 + 1219509*uk_141 + 4379277*uk_142 + 1876833*uk_143 + 804357*uk_144 + 8000*uk_145 + 56400*uk_146 + 86800*uk_147 + 37200*uk_148 + 397620*uk_149 + 10275601*uk_15 + 611940*uk_150 + 262260*uk_151 + 941780*uk_152 + 403620*uk_153 + 172980*uk_154 + 2803221*uk_155 + 4314177*uk_156 + 1848933*uk_157 + 6639549*uk_158 + 2845521*uk_159 + 4403829*uk_16 + 1219509*uk_160 + 10218313*uk_161 + 4379277*uk_162 + 1876833*uk_163 + 804357*uk_164 + 3969*uk_17 + 7434*uk_18 + 5859*uk_19 + 63*uk_2 + 1260*uk_20 + 8883*uk_21 + 13671*uk_22 + 5859*uk_23 + 13924*uk_24 + 10974*uk_25 + 2360*uk_26 + 16638*uk_27 + 25606*uk_28 + 10974*uk_29 + 118*uk_3 + 8649*uk_30 + 1860*uk_31 + 13113*uk_32 + 20181*uk_33 + 8649*uk_34 + 400*uk_35 + 2820*uk_36 + 4340*uk_37 + 1860*uk_38 + 19881*uk_39 + 93*uk_4 + 30597*uk_40 + 13113*uk_41 + 47089*uk_42 + 20181*uk_43 + 8649*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 264592179862*uk_47 + 208534514637*uk_48 + 44846132180*uk_49 + 20*uk_5 + 316165231869*uk_50 + 486580534153*uk_51 + 208534514637*uk_52 + 187944057*uk_53 + 352022202*uk_54 + 277441227*uk_55 + 59664780*uk_56 + 420636699*uk_57 + 647362863*uk_58 + 277441227*uk_59 + 141*uk_6 + 659343172*uk_60 + 519651822*uk_61 + 111753080*uk_62 + 787859214*uk_63 + 1212520918*uk_64 + 519651822*uk_65 + 409556097*uk_66 + 88076580*uk_67 + 620939889*uk_68 + 955630893*uk_69 + 217*uk_7 + 409556097*uk_70 + 18941200*uk_71 + 133535460*uk_72 + 205512020*uk_73 + 88076580*uk_74 + 941424993*uk_75 + 1448859741*uk_76 + 620939889*uk_77 + 2229805417*uk_78 + 955630893*uk_79 + 93*uk_8 + 409556097*uk_80 + 250047*uk_81 + 468342*uk_82 + 369117*uk_83 + 79380*uk_84 + 559629*uk_85 + 861273*uk_86 + 369117*uk_87 + 877212*uk_88 + 691362*uk_89 + 2242306609*uk_9 + 148680*uk_90 + 1048194*uk_91 + 1613178*uk_92 + 691362*uk_93 + 544887*uk_94 + 117180*uk_95 + 826119*uk_96 + 1271403*uk_97 + 544887*uk_98 + 25200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 144144*uk_100 + 218736*uk_101 + 118944*uk_102 + 1288287*uk_103 + 1954953*uk_104 + 1063062*uk_105 + 2966607*uk_106 + 1613178*uk_107 + 877212*uk_108 + 8000*uk_109 + 947060*uk_11 + 47200*uk_110 + 6400*uk_111 + 57200*uk_112 + 86800*uk_113 + 47200*uk_114 + 278480*uk_115 + 37760*uk_116 + 337480*uk_117 + 512120*uk_118 + 278480*uk_119 + 5587654*uk_12 + 5120*uk_120 + 45760*uk_121 + 69440*uk_122 + 37760*uk_123 + 408980*uk_124 + 620620*uk_125 + 337480*uk_126 + 941780*uk_127 + 512120*uk_128 + 278480*uk_129 + 757648*uk_13 + 1643032*uk_130 + 222784*uk_131 + 1991132*uk_132 + 3021508*uk_133 + 1643032*uk_134 + 30208*uk_135 + 269984*uk_136 + 409696*uk_137 + 222784*uk_138 + 2412982*uk_139 + 6771479*uk_14 + 3661658*uk_140 + 1991132*uk_141 + 5556502*uk_142 + 3021508*uk_143 + 1643032*uk_144 + 4096*uk_145 + 36608*uk_146 + 55552*uk_147 + 30208*uk_148 + 327184*uk_149 + 10275601*uk_15 + 496496*uk_150 + 269984*uk_151 + 753424*uk_152 + 409696*uk_153 + 222784*uk_154 + 2924207*uk_155 + 4437433*uk_156 + 2412982*uk_157 + 6733727*uk_158 + 3661658*uk_159 + 5587654*uk_16 + 1991132*uk_160 + 10218313*uk_161 + 5556502*uk_162 + 3021508*uk_163 + 1643032*uk_164 + 3969*uk_17 + 1260*uk_18 + 7434*uk_19 + 63*uk_2 + 1008*uk_20 + 9009*uk_21 + 13671*uk_22 + 7434*uk_23 + 400*uk_24 + 2360*uk_25 + 320*uk_26 + 2860*uk_27 + 4340*uk_28 + 2360*uk_29 + 20*uk_3 + 13924*uk_30 + 1888*uk_31 + 16874*uk_32 + 25606*uk_33 + 13924*uk_34 + 256*uk_35 + 2288*uk_36 + 3472*uk_37 + 1888*uk_38 + 20449*uk_39 + 118*uk_4 + 31031*uk_40 + 16874*uk_41 + 47089*uk_42 + 25606*uk_43 + 13924*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 44846132180*uk_47 + 264592179862*uk_48 + 35876905744*uk_49 + 16*uk_5 + 320649845087*uk_50 + 486580534153*uk_51 + 264592179862*uk_52 + 187944057*uk_53 + 59664780*uk_54 + 352022202*uk_55 + 47731824*uk_56 + 426603177*uk_57 + 647362863*uk_58 + 352022202*uk_59 + 143*uk_6 + 18941200*uk_60 + 111753080*uk_61 + 15152960*uk_62 + 135429580*uk_63 + 205512020*uk_64 + 111753080*uk_65 + 659343172*uk_66 + 89402464*uk_67 + 799034522*uk_68 + 1212520918*uk_69 + 217*uk_7 + 659343172*uk_70 + 12122368*uk_71 + 108343664*uk_72 + 164409616*uk_73 + 89402464*uk_74 + 968321497*uk_75 + 1469410943*uk_76 + 799034522*uk_77 + 2229805417*uk_78 + 1212520918*uk_79 + 118*uk_8 + 659343172*uk_80 + 250047*uk_81 + 79380*uk_82 + 468342*uk_83 + 63504*uk_84 + 567567*uk_85 + 861273*uk_86 + 468342*uk_87 + 25200*uk_88 + 148680*uk_89 + 2242306609*uk_9 + 20160*uk_90 + 180180*uk_91 + 273420*uk_92 + 148680*uk_93 + 877212*uk_94 + 118944*uk_95 + 1063062*uk_96 + 1613178*uk_97 + 877212*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 182700*uk_100 + 273420*uk_101 + 25200*uk_102 + 1324575*uk_103 + 1982295*uk_104 + 182700*uk_105 + 2966607*uk_106 + 273420*uk_107 + 25200*uk_108 + 571787*uk_109 + 3930299*uk_11 + 137780*uk_110 + 137780*uk_111 + 998905*uk_112 + 1494913*uk_113 + 137780*uk_114 + 33200*uk_115 + 33200*uk_116 + 240700*uk_117 + 360220*uk_118 + 33200*uk_119 + 947060*uk_12 + 33200*uk_120 + 240700*uk_121 + 360220*uk_122 + 33200*uk_123 + 1745075*uk_124 + 2611595*uk_125 + 240700*uk_126 + 3908387*uk_127 + 360220*uk_128 + 33200*uk_129 + 947060*uk_13 + 8000*uk_130 + 8000*uk_131 + 58000*uk_132 + 86800*uk_133 + 8000*uk_134 + 8000*uk_135 + 58000*uk_136 + 86800*uk_137 + 8000*uk_138 + 420500*uk_139 + 6866185*uk_14 + 629300*uk_140 + 58000*uk_141 + 941780*uk_142 + 86800*uk_143 + 8000*uk_144 + 8000*uk_145 + 58000*uk_146 + 86800*uk_147 + 8000*uk_148 + 420500*uk_149 + 10275601*uk_15 + 629300*uk_150 + 58000*uk_151 + 941780*uk_152 + 86800*uk_153 + 8000*uk_154 + 3048625*uk_155 + 4562425*uk_156 + 420500*uk_157 + 6827905*uk_158 + 629300*uk_159 + 947060*uk_16 + 58000*uk_160 + 10218313*uk_161 + 941780*uk_162 + 86800*uk_163 + 8000*uk_164 + 3969*uk_17 + 5229*uk_18 + 1260*uk_19 + 63*uk_2 + 1260*uk_20 + 9135*uk_21 + 13671*uk_22 + 1260*uk_23 + 6889*uk_24 + 1660*uk_25 + 1660*uk_26 + 12035*uk_27 + 18011*uk_28 + 1660*uk_29 + 83*uk_3 + 400*uk_30 + 400*uk_31 + 2900*uk_32 + 4340*uk_33 + 400*uk_34 + 400*uk_35 + 2900*uk_36 + 4340*uk_37 + 400*uk_38 + 21025*uk_39 + 20*uk_4 + 31465*uk_40 + 2900*uk_41 + 47089*uk_42 + 4340*uk_43 + 400*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 186111448547*uk_47 + 44846132180*uk_48 + 44846132180*uk_49 + 20*uk_5 + 325134458305*uk_50 + 486580534153*uk_51 + 44846132180*uk_52 + 187944057*uk_53 + 247608837*uk_54 + 59664780*uk_55 + 59664780*uk_56 + 432569655*uk_57 + 647362863*uk_58 + 59664780*uk_59 + 145*uk_6 + 326214817*uk_60 + 78605980*uk_61 + 78605980*uk_62 + 569893355*uk_63 + 852874883*uk_64 + 78605980*uk_65 + 18941200*uk_66 + 18941200*uk_67 + 137323700*uk_68 + 205512020*uk_69 + 217*uk_7 + 18941200*uk_70 + 18941200*uk_71 + 137323700*uk_72 + 205512020*uk_73 + 18941200*uk_74 + 995596825*uk_75 + 1489962145*uk_76 + 137323700*uk_77 + 2229805417*uk_78 + 205512020*uk_79 + 20*uk_8 + 18941200*uk_80 + 250047*uk_81 + 329427*uk_82 + 79380*uk_83 + 79380*uk_84 + 575505*uk_85 + 861273*uk_86 + 79380*uk_87 + 434007*uk_88 + 104580*uk_89 + 2242306609*uk_9 + 104580*uk_90 + 758205*uk_91 + 1134693*uk_92 + 104580*uk_93 + 25200*uk_94 + 25200*uk_95 + 182700*uk_96 + 273420*uk_97 + 25200*uk_98 + 25200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 148176*uk_100 + 218736*uk_101 + 83664*uk_102 + 1361367*uk_103 + 2009637*uk_104 + 768663*uk_105 + 2966607*uk_106 + 1134693*uk_107 + 434007*uk_108 + 6859*uk_109 + 899707*uk_11 + 29963*uk_110 + 5776*uk_111 + 53067*uk_112 + 78337*uk_113 + 29963*uk_114 + 130891*uk_115 + 25232*uk_116 + 231819*uk_117 + 342209*uk_118 + 130891*uk_119 + 3930299*uk_12 + 4864*uk_120 + 44688*uk_121 + 65968*uk_122 + 25232*uk_123 + 410571*uk_124 + 606081*uk_125 + 231819*uk_126 + 894691*uk_127 + 342209*uk_128 + 130891*uk_129 + 757648*uk_13 + 571787*uk_130 + 110224*uk_131 + 1012683*uk_132 + 1494913*uk_133 + 571787*uk_134 + 21248*uk_135 + 195216*uk_136 + 288176*uk_137 + 110224*uk_138 + 1793547*uk_139 + 6960891*uk_14 + 2647617*uk_140 + 1012683*uk_141 + 3908387*uk_142 + 1494913*uk_143 + 571787*uk_144 + 4096*uk_145 + 37632*uk_146 + 55552*uk_147 + 21248*uk_148 + 345744*uk_149 + 10275601*uk_15 + 510384*uk_150 + 195216*uk_151 + 753424*uk_152 + 288176*uk_153 + 110224*uk_154 + 3176523*uk_155 + 4689153*uk_156 + 1793547*uk_157 + 6922083*uk_158 + 2647617*uk_159 + 3930299*uk_16 + 1012683*uk_160 + 10218313*uk_161 + 3908387*uk_162 + 1494913*uk_163 + 571787*uk_164 + 3969*uk_17 + 1197*uk_18 + 5229*uk_19 + 63*uk_2 + 1008*uk_20 + 9261*uk_21 + 13671*uk_22 + 5229*uk_23 + 361*uk_24 + 1577*uk_25 + 304*uk_26 + 2793*uk_27 + 4123*uk_28 + 1577*uk_29 + 19*uk_3 + 6889*uk_30 + 1328*uk_31 + 12201*uk_32 + 18011*uk_33 + 6889*uk_34 + 256*uk_35 + 2352*uk_36 + 3472*uk_37 + 1328*uk_38 + 21609*uk_39 + 83*uk_4 + 31899*uk_40 + 12201*uk_41 + 47089*uk_42 + 18011*uk_43 + 6889*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 42603825571*uk_47 + 186111448547*uk_48 + 35876905744*uk_49 + 16*uk_5 + 329619071523*uk_50 + 486580534153*uk_51 + 186111448547*uk_52 + 187944057*uk_53 + 56681541*uk_54 + 247608837*uk_55 + 47731824*uk_56 + 438536133*uk_57 + 647362863*uk_58 + 247608837*uk_59 + 147*uk_6 + 17094433*uk_60 + 74675681*uk_61 + 14395312*uk_62 + 132256929*uk_63 + 195236419*uk_64 + 74675681*uk_65 + 326214817*uk_66 + 62884784*uk_67 + 577753953*uk_68 + 852874883*uk_69 + 217*uk_7 + 326214817*uk_70 + 12122368*uk_71 + 111374256*uk_72 + 164409616*uk_73 + 62884784*uk_74 + 1023250977*uk_75 + 1510513347*uk_76 + 577753953*uk_77 + 2229805417*uk_78 + 852874883*uk_79 + 83*uk_8 + 326214817*uk_80 + 250047*uk_81 + 75411*uk_82 + 329427*uk_83 + 63504*uk_84 + 583443*uk_85 + 861273*uk_86 + 329427*uk_87 + 22743*uk_88 + 99351*uk_89 + 2242306609*uk_9 + 19152*uk_90 + 175959*uk_91 + 259749*uk_92 + 99351*uk_93 + 434007*uk_94 + 83664*uk_95 + 768663*uk_96 + 1134693*uk_97 + 434007*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 187740*uk_100 + 273420*uk_101 + 23940*uk_102 + 1398663*uk_103 + 2036979*uk_104 + 178353*uk_105 + 2966607*uk_106 + 259749*uk_107 + 22743*uk_108 + 1728000*uk_109 + 5682360*uk_11 + 273600*uk_110 + 288000*uk_111 + 2145600*uk_112 + 3124800*uk_113 + 273600*uk_114 + 43320*uk_115 + 45600*uk_116 + 339720*uk_117 + 494760*uk_118 + 43320*uk_119 + 899707*uk_12 + 48000*uk_120 + 357600*uk_121 + 520800*uk_122 + 45600*uk_123 + 2664120*uk_124 + 3879960*uk_125 + 339720*uk_126 + 5650680*uk_127 + 494760*uk_128 + 43320*uk_129 + 947060*uk_13 + 6859*uk_130 + 7220*uk_131 + 53789*uk_132 + 78337*uk_133 + 6859*uk_134 + 7600*uk_135 + 56620*uk_136 + 82460*uk_137 + 7220*uk_138 + 421819*uk_139 + 7055597*uk_14 + 614327*uk_140 + 53789*uk_141 + 894691*uk_142 + 78337*uk_143 + 6859*uk_144 + 8000*uk_145 + 59600*uk_146 + 86800*uk_147 + 7600*uk_148 + 444020*uk_149 + 10275601*uk_15 + 646660*uk_150 + 56620*uk_151 + 941780*uk_152 + 82460*uk_153 + 7220*uk_154 + 3307949*uk_155 + 4817617*uk_156 + 421819*uk_157 + 7016261*uk_158 + 614327*uk_159 + 899707*uk_16 + 53789*uk_160 + 10218313*uk_161 + 894691*uk_162 + 78337*uk_163 + 6859*uk_164 + 3969*uk_17 + 7560*uk_18 + 1197*uk_19 + 63*uk_2 + 1260*uk_20 + 9387*uk_21 + 13671*uk_22 + 1197*uk_23 + 14400*uk_24 + 2280*uk_25 + 2400*uk_26 + 17880*uk_27 + 26040*uk_28 + 2280*uk_29 + 120*uk_3 + 361*uk_30 + 380*uk_31 + 2831*uk_32 + 4123*uk_33 + 361*uk_34 + 400*uk_35 + 2980*uk_36 + 4340*uk_37 + 380*uk_38 + 22201*uk_39 + 19*uk_4 + 32333*uk_40 + 2831*uk_41 + 47089*uk_42 + 4123*uk_43 + 361*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 269076793080*uk_47 + 42603825571*uk_48 + 44846132180*uk_49 + 20*uk_5 + 334103684741*uk_50 + 486580534153*uk_51 + 42603825571*uk_52 + 187944057*uk_53 + 357988680*uk_54 + 56681541*uk_55 + 59664780*uk_56 + 444502611*uk_57 + 647362863*uk_58 + 56681541*uk_59 + 149*uk_6 + 681883200*uk_60 + 107964840*uk_61 + 113647200*uk_62 + 846671640*uk_63 + 1233072120*uk_64 + 107964840*uk_65 + 17094433*uk_66 + 17994140*uk_67 + 134056343*uk_68 + 195236419*uk_69 + 217*uk_7 + 17094433*uk_70 + 18941200*uk_71 + 141111940*uk_72 + 205512020*uk_73 + 17994140*uk_74 + 1051283953*uk_75 + 1531064549*uk_76 + 134056343*uk_77 + 2229805417*uk_78 + 195236419*uk_79 + 19*uk_8 + 17094433*uk_80 + 250047*uk_81 + 476280*uk_82 + 75411*uk_83 + 79380*uk_84 + 591381*uk_85 + 861273*uk_86 + 75411*uk_87 + 907200*uk_88 + 143640*uk_89 + 2242306609*uk_9 + 151200*uk_90 + 1126440*uk_91 + 1640520*uk_92 + 143640*uk_93 + 22743*uk_94 + 23940*uk_95 + 178353*uk_96 + 259749*uk_97 + 22743*uk_98 + 25200*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 152208*uk_100 + 218736*uk_101 + 120960*uk_102 + 1436463*uk_103 + 2064321*uk_104 + 1141560*uk_105 + 2966607*uk_106 + 1640520*uk_107 + 907200*uk_108 + 729000*uk_109 + 4261770*uk_11 + 972000*uk_110 + 129600*uk_111 + 1223100*uk_112 + 1757700*uk_113 + 972000*uk_114 + 1296000*uk_115 + 172800*uk_116 + 1630800*uk_117 + 2343600*uk_118 + 1296000*uk_119 + 5682360*uk_12 + 23040*uk_120 + 217440*uk_121 + 312480*uk_122 + 172800*uk_123 + 2052090*uk_124 + 2949030*uk_125 + 1630800*uk_126 + 4238010*uk_127 + 2343600*uk_128 + 1296000*uk_129 + 757648*uk_13 + 1728000*uk_130 + 230400*uk_131 + 2174400*uk_132 + 3124800*uk_133 + 1728000*uk_134 + 30720*uk_135 + 289920*uk_136 + 416640*uk_137 + 230400*uk_138 + 2736120*uk_139 + 7150303*uk_14 + 3932040*uk_140 + 2174400*uk_141 + 5650680*uk_142 + 3124800*uk_143 + 1728000*uk_144 + 4096*uk_145 + 38656*uk_146 + 55552*uk_147 + 30720*uk_148 + 364816*uk_149 + 10275601*uk_15 + 524272*uk_150 + 289920*uk_151 + 753424*uk_152 + 416640*uk_153 + 230400*uk_154 + 3442951*uk_155 + 4947817*uk_156 + 2736120*uk_157 + 7110439*uk_158 + 3932040*uk_159 + 5682360*uk_16 + 2174400*uk_160 + 10218313*uk_161 + 5650680*uk_162 + 3124800*uk_163 + 1728000*uk_164 + 3969*uk_17 + 5670*uk_18 + 7560*uk_19 + 63*uk_2 + 1008*uk_20 + 9513*uk_21 + 13671*uk_22 + 7560*uk_23 + 8100*uk_24 + 10800*uk_25 + 1440*uk_26 + 13590*uk_27 + 19530*uk_28 + 10800*uk_29 + 90*uk_3 + 14400*uk_30 + 1920*uk_31 + 18120*uk_32 + 26040*uk_33 + 14400*uk_34 + 256*uk_35 + 2416*uk_36 + 3472*uk_37 + 1920*uk_38 + 22801*uk_39 + 120*uk_4 + 32767*uk_40 + 18120*uk_41 + 47089*uk_42 + 26040*uk_43 + 14400*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 201807594810*uk_47 + 269076793080*uk_48 + 35876905744*uk_49 + 16*uk_5 + 338588297959*uk_50 + 486580534153*uk_51 + 269076793080*uk_52 + 187944057*uk_53 + 268491510*uk_54 + 357988680*uk_55 + 47731824*uk_56 + 450469089*uk_57 + 647362863*uk_58 + 357988680*uk_59 + 151*uk_6 + 383559300*uk_60 + 511412400*uk_61 + 68188320*uk_62 + 643527270*uk_63 + 924804090*uk_64 + 511412400*uk_65 + 681883200*uk_66 + 90917760*uk_67 + 858036360*uk_68 + 1233072120*uk_69 + 217*uk_7 + 681883200*uk_70 + 12122368*uk_71 + 114404848*uk_72 + 164409616*uk_73 + 90917760*uk_74 + 1079695753*uk_75 + 1551615751*uk_76 + 858036360*uk_77 + 2229805417*uk_78 + 1233072120*uk_79 + 120*uk_8 + 681883200*uk_80 + 250047*uk_81 + 357210*uk_82 + 476280*uk_83 + 63504*uk_84 + 599319*uk_85 + 861273*uk_86 + 476280*uk_87 + 510300*uk_88 + 680400*uk_89 + 2242306609*uk_9 + 90720*uk_90 + 856170*uk_91 + 1230390*uk_92 + 680400*uk_93 + 907200*uk_94 + 120960*uk_95 + 1141560*uk_96 + 1640520*uk_97 + 907200*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 154224*uk_100 + 218736*uk_101 + 90720*uk_102 + 1474767*uk_103 + 2091663*uk_104 + 867510*uk_105 + 2966607*uk_106 + 1230390*uk_107 + 510300*uk_108 + 438976*uk_109 + 3598828*uk_11 + 519840*uk_110 + 92416*uk_111 + 883728*uk_112 + 1253392*uk_113 + 519840*uk_114 + 615600*uk_115 + 109440*uk_116 + 1046520*uk_117 + 1484280*uk_118 + 615600*uk_119 + 4261770*uk_12 + 19456*uk_120 + 186048*uk_121 + 263872*uk_122 + 109440*uk_123 + 1779084*uk_124 + 2523276*uk_125 + 1046520*uk_126 + 3578764*uk_127 + 1484280*uk_128 + 615600*uk_129 + 757648*uk_13 + 729000*uk_130 + 129600*uk_131 + 1239300*uk_132 + 1757700*uk_133 + 729000*uk_134 + 23040*uk_135 + 220320*uk_136 + 312480*uk_137 + 129600*uk_138 + 2106810*uk_139 + 7245009*uk_14 + 2988090*uk_140 + 1239300*uk_141 + 4238010*uk_142 + 1757700*uk_143 + 729000*uk_144 + 4096*uk_145 + 39168*uk_146 + 55552*uk_147 + 23040*uk_148 + 374544*uk_149 + 10275601*uk_15 + 531216*uk_150 + 220320*uk_151 + 753424*uk_152 + 312480*uk_153 + 129600*uk_154 + 3581577*uk_155 + 5079753*uk_156 + 2106810*uk_157 + 7204617*uk_158 + 2988090*uk_159 + 4261770*uk_16 + 1239300*uk_160 + 10218313*uk_161 + 4238010*uk_162 + 1757700*uk_163 + 729000*uk_164 + 3969*uk_17 + 4788*uk_18 + 5670*uk_19 + 63*uk_2 + 1008*uk_20 + 9639*uk_21 + 13671*uk_22 + 5670*uk_23 + 5776*uk_24 + 6840*uk_25 + 1216*uk_26 + 11628*uk_27 + 16492*uk_28 + 6840*uk_29 + 76*uk_3 + 8100*uk_30 + 1440*uk_31 + 13770*uk_32 + 19530*uk_33 + 8100*uk_34 + 256*uk_35 + 2448*uk_36 + 3472*uk_37 + 1440*uk_38 + 23409*uk_39 + 90*uk_4 + 33201*uk_40 + 13770*uk_41 + 47089*uk_42 + 19530*uk_43 + 8100*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 170415302284*uk_47 + 201807594810*uk_48 + 35876905744*uk_49 + 16*uk_5 + 343072911177*uk_50 + 486580534153*uk_51 + 201807594810*uk_52 + 187944057*uk_53 + 226726164*uk_54 + 268491510*uk_55 + 47731824*uk_56 + 456435567*uk_57 + 647362863*uk_58 + 268491510*uk_59 + 153*uk_6 + 273510928*uk_60 + 323894520*uk_61 + 57581248*uk_62 + 550620684*uk_63 + 780945676*uk_64 + 323894520*uk_65 + 383559300*uk_66 + 68188320*uk_67 + 652050810*uk_68 + 924804090*uk_69 + 217*uk_7 + 383559300*uk_70 + 12122368*uk_71 + 115920144*uk_72 + 164409616*uk_73 + 68188320*uk_74 + 1108486377*uk_75 + 1572166953*uk_76 + 652050810*uk_77 + 2229805417*uk_78 + 924804090*uk_79 + 90*uk_8 + 383559300*uk_80 + 250047*uk_81 + 301644*uk_82 + 357210*uk_83 + 63504*uk_84 + 607257*uk_85 + 861273*uk_86 + 357210*uk_87 + 363888*uk_88 + 430920*uk_89 + 2242306609*uk_9 + 76608*uk_90 + 732564*uk_91 + 1038996*uk_92 + 430920*uk_93 + 510300*uk_94 + 90720*uk_95 + 867510*uk_96 + 1230390*uk_97 + 510300*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 156240*uk_100 + 218736*uk_101 + 76608*uk_102 + 1513575*uk_103 + 2119005*uk_104 + 742140*uk_105 + 2966607*uk_106 + 1038996*uk_107 + 363888*uk_108 + 474552*uk_109 + 3693534*uk_11 + 462384*uk_110 + 97344*uk_111 + 943020*uk_112 + 1320228*uk_113 + 462384*uk_114 + 450528*uk_115 + 94848*uk_116 + 918840*uk_117 + 1286376*uk_118 + 450528*uk_119 + 3598828*uk_12 + 19968*uk_120 + 193440*uk_121 + 270816*uk_122 + 94848*uk_123 + 1873950*uk_124 + 2623530*uk_125 + 918840*uk_126 + 3672942*uk_127 + 1286376*uk_128 + 450528*uk_129 + 757648*uk_13 + 438976*uk_130 + 92416*uk_131 + 895280*uk_132 + 1253392*uk_133 + 438976*uk_134 + 19456*uk_135 + 188480*uk_136 + 263872*uk_137 + 92416*uk_138 + 1825900*uk_139 + 7339715*uk_14 + 2556260*uk_140 + 895280*uk_141 + 3578764*uk_142 + 1253392*uk_143 + 438976*uk_144 + 4096*uk_145 + 39680*uk_146 + 55552*uk_147 + 19456*uk_148 + 384400*uk_149 + 10275601*uk_15 + 538160*uk_150 + 188480*uk_151 + 753424*uk_152 + 263872*uk_153 + 92416*uk_154 + 3723875*uk_155 + 5213425*uk_156 + 1825900*uk_157 + 7298795*uk_158 + 2556260*uk_159 + 3598828*uk_16 + 895280*uk_160 + 10218313*uk_161 + 3578764*uk_162 + 1253392*uk_163 + 438976*uk_164 + 3969*uk_17 + 4914*uk_18 + 4788*uk_19 + 63*uk_2 + 1008*uk_20 + 9765*uk_21 + 13671*uk_22 + 4788*uk_23 + 6084*uk_24 + 5928*uk_25 + 1248*uk_26 + 12090*uk_27 + 16926*uk_28 + 5928*uk_29 + 78*uk_3 + 5776*uk_30 + 1216*uk_31 + 11780*uk_32 + 16492*uk_33 + 5776*uk_34 + 256*uk_35 + 2480*uk_36 + 3472*uk_37 + 1216*uk_38 + 24025*uk_39 + 76*uk_4 + 33635*uk_40 + 11780*uk_41 + 47089*uk_42 + 16492*uk_43 + 5776*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 174899915502*uk_47 + 170415302284*uk_48 + 35876905744*uk_49 + 16*uk_5 + 347557524395*uk_50 + 486580534153*uk_51 + 170415302284*uk_52 + 187944057*uk_53 + 232692642*uk_54 + 226726164*uk_55 + 47731824*uk_56 + 462402045*uk_57 + 647362863*uk_58 + 226726164*uk_59 + 155*uk_6 + 288095652*uk_60 + 280708584*uk_61 + 59096544*uk_62 + 572497770*uk_63 + 801496878*uk_64 + 280708584*uk_65 + 273510928*uk_66 + 57581248*uk_67 + 557818340*uk_68 + 780945676*uk_69 + 217*uk_7 + 273510928*uk_70 + 12122368*uk_71 + 117435440*uk_72 + 164409616*uk_73 + 57581248*uk_74 + 1137655825*uk_75 + 1592718155*uk_76 + 557818340*uk_77 + 2229805417*uk_78 + 780945676*uk_79 + 76*uk_8 + 273510928*uk_80 + 250047*uk_81 + 309582*uk_82 + 301644*uk_83 + 63504*uk_84 + 615195*uk_85 + 861273*uk_86 + 301644*uk_87 + 383292*uk_88 + 373464*uk_89 + 2242306609*uk_9 + 78624*uk_90 + 761670*uk_91 + 1066338*uk_92 + 373464*uk_93 + 363888*uk_94 + 76608*uk_95 + 742140*uk_96 + 1038996*uk_97 + 363888*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 158256*uk_100 + 218736*uk_101 + 78624*uk_102 + 1552887*uk_103 + 2146347*uk_104 + 771498*uk_105 + 2966607*uk_106 + 1066338*uk_107 + 383292*uk_108 + 884736*uk_109 + 4545888*uk_11 + 718848*uk_110 + 147456*uk_111 + 1446912*uk_112 + 1999872*uk_113 + 718848*uk_114 + 584064*uk_115 + 119808*uk_116 + 1175616*uk_117 + 1624896*uk_118 + 584064*uk_119 + 3693534*uk_12 + 24576*uk_120 + 241152*uk_121 + 333312*uk_122 + 119808*uk_123 + 2366304*uk_124 + 3270624*uk_125 + 1175616*uk_126 + 4520544*uk_127 + 1624896*uk_128 + 584064*uk_129 + 757648*uk_13 + 474552*uk_130 + 97344*uk_131 + 955188*uk_132 + 1320228*uk_133 + 474552*uk_134 + 19968*uk_135 + 195936*uk_136 + 270816*uk_137 + 97344*uk_138 + 1922622*uk_139 + 7434421*uk_14 + 2657382*uk_140 + 955188*uk_141 + 3672942*uk_142 + 1320228*uk_143 + 474552*uk_144 + 4096*uk_145 + 40192*uk_146 + 55552*uk_147 + 19968*uk_148 + 394384*uk_149 + 10275601*uk_15 + 545104*uk_150 + 195936*uk_151 + 753424*uk_152 + 270816*uk_153 + 97344*uk_154 + 3869893*uk_155 + 5348833*uk_156 + 1922622*uk_157 + 7392973*uk_158 + 2657382*uk_159 + 3693534*uk_16 + 955188*uk_160 + 10218313*uk_161 + 3672942*uk_162 + 1320228*uk_163 + 474552*uk_164 + 3969*uk_17 + 6048*uk_18 + 4914*uk_19 + 63*uk_2 + 1008*uk_20 + 9891*uk_21 + 13671*uk_22 + 4914*uk_23 + 9216*uk_24 + 7488*uk_25 + 1536*uk_26 + 15072*uk_27 + 20832*uk_28 + 7488*uk_29 + 96*uk_3 + 6084*uk_30 + 1248*uk_31 + 12246*uk_32 + 16926*uk_33 + 6084*uk_34 + 256*uk_35 + 2512*uk_36 + 3472*uk_37 + 1248*uk_38 + 24649*uk_39 + 78*uk_4 + 34069*uk_40 + 12246*uk_41 + 47089*uk_42 + 16926*uk_43 + 6084*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 215261434464*uk_47 + 174899915502*uk_48 + 35876905744*uk_49 + 16*uk_5 + 352042137613*uk_50 + 486580534153*uk_51 + 174899915502*uk_52 + 187944057*uk_53 + 286390944*uk_54 + 232692642*uk_55 + 47731824*uk_56 + 468368523*uk_57 + 647362863*uk_58 + 232692642*uk_59 + 157*uk_6 + 436405248*uk_60 + 354579264*uk_61 + 72734208*uk_62 + 713704416*uk_63 + 986457696*uk_64 + 354579264*uk_65 + 288095652*uk_66 + 59096544*uk_67 + 579884838*uk_68 + 801496878*uk_69 + 217*uk_7 + 288095652*uk_70 + 12122368*uk_71 + 118950736*uk_72 + 164409616*uk_73 + 59096544*uk_74 + 1167204097*uk_75 + 1613269357*uk_76 + 579884838*uk_77 + 2229805417*uk_78 + 801496878*uk_79 + 78*uk_8 + 288095652*uk_80 + 250047*uk_81 + 381024*uk_82 + 309582*uk_83 + 63504*uk_84 + 623133*uk_85 + 861273*uk_86 + 309582*uk_87 + 580608*uk_88 + 471744*uk_89 + 2242306609*uk_9 + 96768*uk_90 + 949536*uk_91 + 1312416*uk_92 + 471744*uk_93 + 383292*uk_94 + 78624*uk_95 + 771498*uk_96 + 1066338*uk_97 + 383292*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 160272*uk_100 + 218736*uk_101 + 96768*uk_102 + 1592703*uk_103 + 2173689*uk_104 + 961632*uk_105 + 2966607*uk_106 + 1312416*uk_107 + 580608*uk_108 + 2197000*uk_109 + 6155890*uk_11 + 1622400*uk_110 + 270400*uk_111 + 2687100*uk_112 + 3667300*uk_113 + 1622400*uk_114 + 1198080*uk_115 + 199680*uk_116 + 1984320*uk_117 + 2708160*uk_118 + 1198080*uk_119 + 4545888*uk_12 + 33280*uk_120 + 330720*uk_121 + 451360*uk_122 + 199680*uk_123 + 3286530*uk_124 + 4485390*uk_125 + 1984320*uk_126 + 6121570*uk_127 + 2708160*uk_128 + 1198080*uk_129 + 757648*uk_13 + 884736*uk_130 + 147456*uk_131 + 1465344*uk_132 + 1999872*uk_133 + 884736*uk_134 + 24576*uk_135 + 244224*uk_136 + 333312*uk_137 + 147456*uk_138 + 2426976*uk_139 + 7529127*uk_14 + 3312288*uk_140 + 1465344*uk_141 + 4520544*uk_142 + 1999872*uk_143 + 884736*uk_144 + 4096*uk_145 + 40704*uk_146 + 55552*uk_147 + 24576*uk_148 + 404496*uk_149 + 10275601*uk_15 + 552048*uk_150 + 244224*uk_151 + 753424*uk_152 + 333312*uk_153 + 147456*uk_154 + 4019679*uk_155 + 5485977*uk_156 + 2426976*uk_157 + 7487151*uk_158 + 3312288*uk_159 + 4545888*uk_16 + 1465344*uk_160 + 10218313*uk_161 + 4520544*uk_162 + 1999872*uk_163 + 884736*uk_164 + 3969*uk_17 + 8190*uk_18 + 6048*uk_19 + 63*uk_2 + 1008*uk_20 + 10017*uk_21 + 13671*uk_22 + 6048*uk_23 + 16900*uk_24 + 12480*uk_25 + 2080*uk_26 + 20670*uk_27 + 28210*uk_28 + 12480*uk_29 + 130*uk_3 + 9216*uk_30 + 1536*uk_31 + 15264*uk_32 + 20832*uk_33 + 9216*uk_34 + 256*uk_35 + 2544*uk_36 + 3472*uk_37 + 1536*uk_38 + 25281*uk_39 + 96*uk_4 + 34503*uk_40 + 15264*uk_41 + 47089*uk_42 + 20832*uk_43 + 9216*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 291499859170*uk_47 + 215261434464*uk_48 + 35876905744*uk_49 + 16*uk_5 + 356526750831*uk_50 + 486580534153*uk_51 + 215261434464*uk_52 + 187944057*uk_53 + 387821070*uk_54 + 286390944*uk_55 + 47731824*uk_56 + 474335001*uk_57 + 647362863*uk_58 + 286390944*uk_59 + 159*uk_6 + 800265700*uk_60 + 590965440*uk_61 + 98494240*uk_62 + 978786510*uk_63 + 1335828130*uk_64 + 590965440*uk_65 + 436405248*uk_66 + 72734208*uk_67 + 722796192*uk_68 + 986457696*uk_69 + 217*uk_7 + 436405248*uk_70 + 12122368*uk_71 + 120466032*uk_72 + 164409616*uk_73 + 72734208*uk_74 + 1197131193*uk_75 + 1633820559*uk_76 + 722796192*uk_77 + 2229805417*uk_78 + 986457696*uk_79 + 96*uk_8 + 436405248*uk_80 + 250047*uk_81 + 515970*uk_82 + 381024*uk_83 + 63504*uk_84 + 631071*uk_85 + 861273*uk_86 + 381024*uk_87 + 1064700*uk_88 + 786240*uk_89 + 2242306609*uk_9 + 131040*uk_90 + 1302210*uk_91 + 1777230*uk_92 + 786240*uk_93 + 580608*uk_94 + 96768*uk_95 + 961632*uk_96 + 1312416*uk_97 + 580608*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 121716*uk_100 + 164052*uk_101 + 98280*uk_102 + 1633023*uk_103 + 2201031*uk_104 + 1318590*uk_105 + 2966607*uk_106 + 1777230*uk_107 + 1064700*uk_108 + 6859*uk_109 + 899707*uk_11 + 46930*uk_110 + 4332*uk_111 + 58121*uk_112 + 78337*uk_113 + 46930*uk_114 + 321100*uk_115 + 29640*uk_116 + 397670*uk_117 + 535990*uk_118 + 321100*uk_119 + 6155890*uk_12 + 2736*uk_120 + 36708*uk_121 + 49476*uk_122 + 29640*uk_123 + 492499*uk_124 + 663803*uk_125 + 397670*uk_126 + 894691*uk_127 + 535990*uk_128 + 321100*uk_129 + 568236*uk_13 + 2197000*uk_130 + 202800*uk_131 + 2720900*uk_132 + 3667300*uk_133 + 2197000*uk_134 + 18720*uk_135 + 251160*uk_136 + 338520*uk_137 + 202800*uk_138 + 3369730*uk_139 + 7623833*uk_14 + 4541810*uk_140 + 2720900*uk_141 + 6121570*uk_142 + 3667300*uk_143 + 2197000*uk_144 + 1728*uk_145 + 23184*uk_146 + 31248*uk_147 + 18720*uk_148 + 311052*uk_149 + 10275601*uk_15 + 419244*uk_150 + 251160*uk_151 + 565068*uk_152 + 338520*uk_153 + 202800*uk_154 + 4173281*uk_155 + 5624857*uk_156 + 3369730*uk_157 + 7581329*uk_158 + 4541810*uk_159 + 6155890*uk_16 + 2720900*uk_160 + 10218313*uk_161 + 6121570*uk_162 + 3667300*uk_163 + 2197000*uk_164 + 3969*uk_17 + 1197*uk_18 + 8190*uk_19 + 63*uk_2 + 756*uk_20 + 10143*uk_21 + 13671*uk_22 + 8190*uk_23 + 361*uk_24 + 2470*uk_25 + 228*uk_26 + 3059*uk_27 + 4123*uk_28 + 2470*uk_29 + 19*uk_3 + 16900*uk_30 + 1560*uk_31 + 20930*uk_32 + 28210*uk_33 + 16900*uk_34 + 144*uk_35 + 1932*uk_36 + 2604*uk_37 + 1560*uk_38 + 25921*uk_39 + 130*uk_4 + 34937*uk_40 + 20930*uk_41 + 47089*uk_42 + 28210*uk_43 + 16900*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 42603825571*uk_47 + 291499859170*uk_48 + 26907679308*uk_49 + 12*uk_5 + 361011364049*uk_50 + 486580534153*uk_51 + 291499859170*uk_52 + 187944057*uk_53 + 56681541*uk_54 + 387821070*uk_55 + 35798868*uk_56 + 480301479*uk_57 + 647362863*uk_58 + 387821070*uk_59 + 161*uk_6 + 17094433*uk_60 + 116961910*uk_61 + 10796484*uk_62 + 144852827*uk_63 + 195236419*uk_64 + 116961910*uk_65 + 800265700*uk_66 + 73870680*uk_67 + 991098290*uk_68 + 1335828130*uk_69 + 217*uk_7 + 800265700*uk_70 + 6818832*uk_71 + 91485996*uk_72 + 123307212*uk_73 + 73870680*uk_74 + 1227437113*uk_75 + 1654371761*uk_76 + 991098290*uk_77 + 2229805417*uk_78 + 1335828130*uk_79 + 130*uk_8 + 800265700*uk_80 + 250047*uk_81 + 75411*uk_82 + 515970*uk_83 + 47628*uk_84 + 639009*uk_85 + 861273*uk_86 + 515970*uk_87 + 22743*uk_88 + 155610*uk_89 + 2242306609*uk_9 + 14364*uk_90 + 192717*uk_91 + 259749*uk_92 + 155610*uk_93 + 1064700*uk_94 + 98280*uk_95 + 1318590*uk_96 + 1777230*uk_97 + 1064700*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 164304*uk_100 + 218736*uk_101 + 19152*uk_102 + 1673847*uk_103 + 2228373*uk_104 + 195111*uk_105 + 2966607*uk_106 + 259749*uk_107 + 22743*uk_108 + 571787*uk_109 + 3930299*uk_11 + 130891*uk_110 + 110224*uk_111 + 1122907*uk_112 + 1494913*uk_113 + 130891*uk_114 + 29963*uk_115 + 25232*uk_116 + 257051*uk_117 + 342209*uk_118 + 29963*uk_119 + 899707*uk_12 + 21248*uk_120 + 216464*uk_121 + 288176*uk_122 + 25232*uk_123 + 2205227*uk_124 + 2935793*uk_125 + 257051*uk_126 + 3908387*uk_127 + 342209*uk_128 + 29963*uk_129 + 757648*uk_13 + 6859*uk_130 + 5776*uk_131 + 58843*uk_132 + 78337*uk_133 + 6859*uk_134 + 4864*uk_135 + 49552*uk_136 + 65968*uk_137 + 5776*uk_138 + 504811*uk_139 + 7718539*uk_14 + 672049*uk_140 + 58843*uk_141 + 894691*uk_142 + 78337*uk_143 + 6859*uk_144 + 4096*uk_145 + 41728*uk_146 + 55552*uk_147 + 4864*uk_148 + 425104*uk_149 + 10275601*uk_15 + 565936*uk_150 + 49552*uk_151 + 753424*uk_152 + 65968*uk_153 + 5776*uk_154 + 4330747*uk_155 + 5765473*uk_156 + 504811*uk_157 + 7675507*uk_158 + 672049*uk_159 + 899707*uk_16 + 58843*uk_160 + 10218313*uk_161 + 894691*uk_162 + 78337*uk_163 + 6859*uk_164 + 3969*uk_17 + 5229*uk_18 + 1197*uk_19 + 63*uk_2 + 1008*uk_20 + 10269*uk_21 + 13671*uk_22 + 1197*uk_23 + 6889*uk_24 + 1577*uk_25 + 1328*uk_26 + 13529*uk_27 + 18011*uk_28 + 1577*uk_29 + 83*uk_3 + 361*uk_30 + 304*uk_31 + 3097*uk_32 + 4123*uk_33 + 361*uk_34 + 256*uk_35 + 2608*uk_36 + 3472*uk_37 + 304*uk_38 + 26569*uk_39 + 19*uk_4 + 35371*uk_40 + 3097*uk_41 + 47089*uk_42 + 4123*uk_43 + 361*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 186111448547*uk_47 + 42603825571*uk_48 + 35876905744*uk_49 + 16*uk_5 + 365495977267*uk_50 + 486580534153*uk_51 + 42603825571*uk_52 + 187944057*uk_53 + 247608837*uk_54 + 56681541*uk_55 + 47731824*uk_56 + 486267957*uk_57 + 647362863*uk_58 + 56681541*uk_59 + 163*uk_6 + 326214817*uk_60 + 74675681*uk_61 + 62884784*uk_62 + 640638737*uk_63 + 852874883*uk_64 + 74675681*uk_65 + 17094433*uk_66 + 14395312*uk_67 + 146652241*uk_68 + 195236419*uk_69 + 217*uk_7 + 17094433*uk_70 + 12122368*uk_71 + 123496624*uk_72 + 164409616*uk_73 + 14395312*uk_74 + 1258121857*uk_75 + 1674922963*uk_76 + 146652241*uk_77 + 2229805417*uk_78 + 195236419*uk_79 + 19*uk_8 + 17094433*uk_80 + 250047*uk_81 + 329427*uk_82 + 75411*uk_83 + 63504*uk_84 + 646947*uk_85 + 861273*uk_86 + 75411*uk_87 + 434007*uk_88 + 99351*uk_89 + 2242306609*uk_9 + 83664*uk_90 + 852327*uk_91 + 1134693*uk_92 + 99351*uk_93 + 22743*uk_94 + 19152*uk_95 + 195111*uk_96 + 259749*uk_97 + 22743*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 166320*uk_100 + 218736*uk_101 + 83664*uk_102 + 1715175*uk_103 + 2255715*uk_104 + 862785*uk_105 + 2966607*uk_106 + 1134693*uk_107 + 434007*uk_108 + 4330747*uk_109 + 7718539*uk_11 + 2205227*uk_110 + 425104*uk_111 + 4383885*uk_112 + 5765473*uk_113 + 2205227*uk_114 + 1122907*uk_115 + 216464*uk_116 + 2232285*uk_117 + 2935793*uk_118 + 1122907*uk_119 + 3930299*uk_12 + 41728*uk_120 + 430320*uk_121 + 565936*uk_122 + 216464*uk_123 + 4437675*uk_124 + 5836215*uk_125 + 2232285*uk_126 + 7675507*uk_127 + 2935793*uk_128 + 1122907*uk_129 + 757648*uk_13 + 571787*uk_130 + 110224*uk_131 + 1136685*uk_132 + 1494913*uk_133 + 571787*uk_134 + 21248*uk_135 + 219120*uk_136 + 288176*uk_137 + 110224*uk_138 + 2259675*uk_139 + 7813245*uk_14 + 2971815*uk_140 + 1136685*uk_141 + 3908387*uk_142 + 1494913*uk_143 + 571787*uk_144 + 4096*uk_145 + 42240*uk_146 + 55552*uk_147 + 21248*uk_148 + 435600*uk_149 + 10275601*uk_15 + 572880*uk_150 + 219120*uk_151 + 753424*uk_152 + 288176*uk_153 + 110224*uk_154 + 4492125*uk_155 + 5907825*uk_156 + 2259675*uk_157 + 7769685*uk_158 + 2971815*uk_159 + 3930299*uk_16 + 1136685*uk_160 + 10218313*uk_161 + 3908387*uk_162 + 1494913*uk_163 + 571787*uk_164 + 3969*uk_17 + 10269*uk_18 + 5229*uk_19 + 63*uk_2 + 1008*uk_20 + 10395*uk_21 + 13671*uk_22 + 5229*uk_23 + 26569*uk_24 + 13529*uk_25 + 2608*uk_26 + 26895*uk_27 + 35371*uk_28 + 13529*uk_29 + 163*uk_3 + 6889*uk_30 + 1328*uk_31 + 13695*uk_32 + 18011*uk_33 + 6889*uk_34 + 256*uk_35 + 2640*uk_36 + 3472*uk_37 + 1328*uk_38 + 27225*uk_39 + 83*uk_4 + 35805*uk_40 + 13695*uk_41 + 47089*uk_42 + 18011*uk_43 + 6889*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 365495977267*uk_47 + 186111448547*uk_48 + 35876905744*uk_49 + 16*uk_5 + 369980590485*uk_50 + 486580534153*uk_51 + 186111448547*uk_52 + 187944057*uk_53 + 486267957*uk_54 + 247608837*uk_55 + 47731824*uk_56 + 492234435*uk_57 + 647362863*uk_58 + 247608837*uk_59 + 165*uk_6 + 1258121857*uk_60 + 640638737*uk_61 + 123496624*uk_62 + 1273558935*uk_63 + 1674922963*uk_64 + 640638737*uk_65 + 326214817*uk_66 + 62884784*uk_67 + 648499335*uk_68 + 852874883*uk_69 + 217*uk_7 + 326214817*uk_70 + 12122368*uk_71 + 125011920*uk_72 + 164409616*uk_73 + 62884784*uk_74 + 1289185425*uk_75 + 1695474165*uk_76 + 648499335*uk_77 + 2229805417*uk_78 + 852874883*uk_79 + 83*uk_8 + 326214817*uk_80 + 250047*uk_81 + 646947*uk_82 + 329427*uk_83 + 63504*uk_84 + 654885*uk_85 + 861273*uk_86 + 329427*uk_87 + 1673847*uk_88 + 852327*uk_89 + 2242306609*uk_9 + 164304*uk_90 + 1694385*uk_91 + 2228373*uk_92 + 852327*uk_93 + 434007*uk_94 + 83664*uk_95 + 862785*uk_96 + 1134693*uk_97 + 434007*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 126252*uk_100 + 164052*uk_101 + 123228*uk_102 + 1757007*uk_103 + 2283057*uk_104 + 1714923*uk_105 + 2966607*uk_106 + 2228373*uk_107 + 1673847*uk_108 + 778688*uk_109 + 4356476*uk_11 + 1379632*uk_110 + 101568*uk_111 + 1413488*uk_112 + 1836688*uk_113 + 1379632*uk_114 + 2444348*uk_115 + 179952*uk_116 + 2504332*uk_117 + 3254132*uk_118 + 2444348*uk_119 + 7718539*uk_12 + 13248*uk_120 + 184368*uk_121 + 239568*uk_122 + 179952*uk_123 + 2565788*uk_124 + 3333988*uk_125 + 2504332*uk_126 + 4332188*uk_127 + 3254132*uk_128 + 2444348*uk_129 + 568236*uk_13 + 4330747*uk_130 + 318828*uk_131 + 4437023*uk_132 + 5765473*uk_133 + 4330747*uk_134 + 23472*uk_135 + 326652*uk_136 + 424452*uk_137 + 318828*uk_138 + 4545907*uk_139 + 7907951*uk_14 + 5906957*uk_140 + 4437023*uk_141 + 7675507*uk_142 + 5765473*uk_143 + 4330747*uk_144 + 1728*uk_145 + 24048*uk_146 + 31248*uk_147 + 23472*uk_148 + 334668*uk_149 + 10275601*uk_15 + 434868*uk_150 + 326652*uk_151 + 565068*uk_152 + 424452*uk_153 + 318828*uk_154 + 4657463*uk_155 + 6051913*uk_156 + 4545907*uk_157 + 7863863*uk_158 + 5906957*uk_159 + 7718539*uk_16 + 4437023*uk_160 + 10218313*uk_161 + 7675507*uk_162 + 5765473*uk_163 + 4330747*uk_164 + 3969*uk_17 + 5796*uk_18 + 10269*uk_19 + 63*uk_2 + 756*uk_20 + 10521*uk_21 + 13671*uk_22 + 10269*uk_23 + 8464*uk_24 + 14996*uk_25 + 1104*uk_26 + 15364*uk_27 + 19964*uk_28 + 14996*uk_29 + 92*uk_3 + 26569*uk_30 + 1956*uk_31 + 27221*uk_32 + 35371*uk_33 + 26569*uk_34 + 144*uk_35 + 2004*uk_36 + 2604*uk_37 + 1956*uk_38 + 27889*uk_39 + 163*uk_4 + 36239*uk_40 + 27221*uk_41 + 47089*uk_42 + 35371*uk_43 + 26569*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 206292208028*uk_47 + 365495977267*uk_48 + 26907679308*uk_49 + 12*uk_5 + 374465203703*uk_50 + 486580534153*uk_51 + 365495977267*uk_52 + 187944057*uk_53 + 274457988*uk_54 + 486267957*uk_55 + 35798868*uk_56 + 498200913*uk_57 + 647362863*uk_58 + 486267957*uk_59 + 167*uk_6 + 400795792*uk_60 + 710105588*uk_61 + 52277712*uk_62 + 727531492*uk_63 + 945355292*uk_64 + 710105588*uk_65 + 1258121857*uk_66 + 92622468*uk_67 + 1288996013*uk_68 + 1674922963*uk_69 + 217*uk_7 + 1258121857*uk_70 + 6818832*uk_71 + 94895412*uk_72 + 123307212*uk_73 + 92622468*uk_74 + 1320627817*uk_75 + 1716025367*uk_76 + 1288996013*uk_77 + 2229805417*uk_78 + 1674922963*uk_79 + 163*uk_8 + 1258121857*uk_80 + 250047*uk_81 + 365148*uk_82 + 646947*uk_83 + 47628*uk_84 + 662823*uk_85 + 861273*uk_86 + 646947*uk_87 + 533232*uk_88 + 944748*uk_89 + 2242306609*uk_9 + 69552*uk_90 + 967932*uk_91 + 1257732*uk_92 + 944748*uk_93 + 1673847*uk_94 + 123228*uk_95 + 1714923*uk_96 + 2228373*uk_97 + 1673847*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 127764*uk_100 + 164052*uk_101 + 69552*uk_102 + 1799343*uk_103 + 2310399*uk_104 + 979524*uk_105 + 2966607*uk_106 + 1257732*uk_107 + 533232*uk_108 + 35937*uk_109 + 1562649*uk_11 + 100188*uk_110 + 13068*uk_111 + 184041*uk_112 + 236313*uk_113 + 100188*uk_114 + 279312*uk_115 + 36432*uk_116 + 513084*uk_117 + 658812*uk_118 + 279312*uk_119 + 4356476*uk_12 + 4752*uk_120 + 66924*uk_121 + 85932*uk_122 + 36432*uk_123 + 942513*uk_124 + 1210209*uk_125 + 513084*uk_126 + 1553937*uk_127 + 658812*uk_128 + 279312*uk_129 + 568236*uk_13 + 778688*uk_130 + 101568*uk_131 + 1430416*uk_132 + 1836688*uk_133 + 778688*uk_134 + 13248*uk_135 + 186576*uk_136 + 239568*uk_137 + 101568*uk_138 + 2627612*uk_139 + 8002657*uk_14 + 3373916*uk_140 + 1430416*uk_141 + 4332188*uk_142 + 1836688*uk_143 + 778688*uk_144 + 1728*uk_145 + 24336*uk_146 + 31248*uk_147 + 13248*uk_148 + 342732*uk_149 + 10275601*uk_15 + 440076*uk_150 + 186576*uk_151 + 565068*uk_152 + 239568*uk_153 + 101568*uk_154 + 4826809*uk_155 + 6197737*uk_156 + 2627612*uk_157 + 7958041*uk_158 + 3373916*uk_159 + 4356476*uk_16 + 1430416*uk_160 + 10218313*uk_161 + 4332188*uk_162 + 1836688*uk_163 + 778688*uk_164 + 3969*uk_17 + 2079*uk_18 + 5796*uk_19 + 63*uk_2 + 756*uk_20 + 10647*uk_21 + 13671*uk_22 + 5796*uk_23 + 1089*uk_24 + 3036*uk_25 + 396*uk_26 + 5577*uk_27 + 7161*uk_28 + 3036*uk_29 + 33*uk_3 + 8464*uk_30 + 1104*uk_31 + 15548*uk_32 + 19964*uk_33 + 8464*uk_34 + 144*uk_35 + 2028*uk_36 + 2604*uk_37 + 1104*uk_38 + 28561*uk_39 + 92*uk_4 + 36673*uk_40 + 15548*uk_41 + 47089*uk_42 + 19964*uk_43 + 8464*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 73996118097*uk_47 + 206292208028*uk_48 + 26907679308*uk_49 + 12*uk_5 + 378949816921*uk_50 + 486580534153*uk_51 + 206292208028*uk_52 + 187944057*uk_53 + 98446887*uk_54 + 274457988*uk_55 + 35798868*uk_56 + 504167391*uk_57 + 647362863*uk_58 + 274457988*uk_59 + 169*uk_6 + 51567417*uk_60 + 143763708*uk_61 + 18751788*uk_62 + 264087681*uk_63 + 339094833*uk_64 + 143763708*uk_65 + 400795792*uk_66 + 52277712*uk_67 + 736244444*uk_68 + 945355292*uk_69 + 217*uk_7 + 400795792*uk_70 + 6818832*uk_71 + 96031884*uk_72 + 123307212*uk_73 + 52277712*uk_74 + 1352449033*uk_75 + 1736576569*uk_76 + 736244444*uk_77 + 2229805417*uk_78 + 945355292*uk_79 + 92*uk_8 + 400795792*uk_80 + 250047*uk_81 + 130977*uk_82 + 365148*uk_83 + 47628*uk_84 + 670761*uk_85 + 861273*uk_86 + 365148*uk_87 + 68607*uk_88 + 191268*uk_89 + 2242306609*uk_9 + 24948*uk_90 + 351351*uk_91 + 451143*uk_92 + 191268*uk_93 + 533232*uk_94 + 69552*uk_95 + 979524*uk_96 + 1257732*uk_97 + 533232*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 172368*uk_100 + 218736*uk_101 + 33264*uk_102 + 1842183*uk_103 + 2337741*uk_104 + 355509*uk_105 + 2966607*uk_106 + 451143*uk_107 + 68607*uk_108 + 3869893*uk_109 + 7434421*uk_11 + 813417*uk_110 + 394384*uk_111 + 4214979*uk_112 + 5348833*uk_113 + 813417*uk_114 + 170973*uk_115 + 82896*uk_116 + 885951*uk_117 + 1124277*uk_118 + 170973*uk_119 + 1562649*uk_12 + 40192*uk_120 + 429552*uk_121 + 545104*uk_122 + 82896*uk_123 + 4590837*uk_124 + 5825799*uk_125 + 885951*uk_126 + 7392973*uk_127 + 1124277*uk_128 + 170973*uk_129 + 757648*uk_13 + 35937*uk_130 + 17424*uk_131 + 186219*uk_132 + 236313*uk_133 + 35937*uk_134 + 8448*uk_135 + 90288*uk_136 + 114576*uk_137 + 17424*uk_138 + 964953*uk_139 + 8097363*uk_14 + 1224531*uk_140 + 186219*uk_141 + 1553937*uk_142 + 236313*uk_143 + 35937*uk_144 + 4096*uk_145 + 43776*uk_146 + 55552*uk_147 + 8448*uk_148 + 467856*uk_149 + 10275601*uk_15 + 593712*uk_150 + 90288*uk_151 + 753424*uk_152 + 114576*uk_153 + 17424*uk_154 + 5000211*uk_155 + 6345297*uk_156 + 964953*uk_157 + 8052219*uk_158 + 1224531*uk_159 + 1562649*uk_16 + 186219*uk_160 + 10218313*uk_161 + 1553937*uk_162 + 236313*uk_163 + 35937*uk_164 + 3969*uk_17 + 9891*uk_18 + 2079*uk_19 + 63*uk_2 + 1008*uk_20 + 10773*uk_21 + 13671*uk_22 + 2079*uk_23 + 24649*uk_24 + 5181*uk_25 + 2512*uk_26 + 26847*uk_27 + 34069*uk_28 + 5181*uk_29 + 157*uk_3 + 1089*uk_30 + 528*uk_31 + 5643*uk_32 + 7161*uk_33 + 1089*uk_34 + 256*uk_35 + 2736*uk_36 + 3472*uk_37 + 528*uk_38 + 29241*uk_39 + 33*uk_4 + 37107*uk_40 + 5643*uk_41 + 47089*uk_42 + 7161*uk_43 + 1089*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 352042137613*uk_47 + 73996118097*uk_48 + 35876905744*uk_49 + 16*uk_5 + 383434430139*uk_50 + 486580534153*uk_51 + 73996118097*uk_52 + 187944057*uk_53 + 468368523*uk_54 + 98446887*uk_55 + 47731824*uk_56 + 510133869*uk_57 + 647362863*uk_58 + 98446887*uk_59 + 171*uk_6 + 1167204097*uk_60 + 245335893*uk_61 + 118950736*uk_62 + 1271285991*uk_63 + 1613269357*uk_64 + 245335893*uk_65 + 51567417*uk_66 + 25002384*uk_67 + 267212979*uk_68 + 339094833*uk_69 + 217*uk_7 + 51567417*uk_70 + 12122368*uk_71 + 129557808*uk_72 + 164409616*uk_73 + 25002384*uk_74 + 1384649073*uk_75 + 1757127771*uk_76 + 267212979*uk_77 + 2229805417*uk_78 + 339094833*uk_79 + 33*uk_8 + 51567417*uk_80 + 250047*uk_81 + 623133*uk_82 + 130977*uk_83 + 63504*uk_84 + 678699*uk_85 + 861273*uk_86 + 130977*uk_87 + 1552887*uk_88 + 326403*uk_89 + 2242306609*uk_9 + 158256*uk_90 + 1691361*uk_91 + 2146347*uk_92 + 326403*uk_93 + 68607*uk_94 + 33264*uk_95 + 355509*uk_96 + 451143*uk_97 + 68607*uk_98 + 16128*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 130788*uk_100 + 164052*uk_101 + 118692*uk_102 + 1885527*uk_103 + 2365083*uk_104 + 1711143*uk_105 + 2966607*uk_106 + 2146347*uk_107 + 1552887*uk_108 + 1906624*uk_109 + 5871772*uk_11 + 2414032*uk_110 + 184512*uk_111 + 2660048*uk_112 + 3336592*uk_113 + 2414032*uk_114 + 3056476*uk_115 + 233616*uk_116 + 3367964*uk_117 + 4224556*uk_118 + 3056476*uk_119 + 7434421*uk_12 + 17856*uk_120 + 257424*uk_121 + 322896*uk_122 + 233616*uk_123 + 3711196*uk_124 + 4655084*uk_125 + 3367964*uk_126 + 5839036*uk_127 + 4224556*uk_128 + 3056476*uk_129 + 568236*uk_13 + 3869893*uk_130 + 295788*uk_131 + 4264277*uk_132 + 5348833*uk_133 + 3869893*uk_134 + 22608*uk_135 + 325932*uk_136 + 408828*uk_137 + 295788*uk_138 + 4698853*uk_139 + 8192069*uk_14 + 5893937*uk_140 + 4264277*uk_141 + 7392973*uk_142 + 5348833*uk_143 + 3869893*uk_144 + 1728*uk_145 + 24912*uk_146 + 31248*uk_147 + 22608*uk_148 + 359148*uk_149 + 10275601*uk_15 + 450492*uk_150 + 325932*uk_151 + 565068*uk_152 + 408828*uk_153 + 295788*uk_154 + 5177717*uk_155 + 6494593*uk_156 + 4698853*uk_157 + 8146397*uk_158 + 5893937*uk_159 + 7434421*uk_16 + 4264277*uk_160 + 10218313*uk_161 + 7392973*uk_162 + 5348833*uk_163 + 3869893*uk_164 + 3969*uk_17 + 7812*uk_18 + 9891*uk_19 + 63*uk_2 + 756*uk_20 + 10899*uk_21 + 13671*uk_22 + 9891*uk_23 + 15376*uk_24 + 19468*uk_25 + 1488*uk_26 + 21452*uk_27 + 26908*uk_28 + 19468*uk_29 + 124*uk_3 + 24649*uk_30 + 1884*uk_31 + 27161*uk_32 + 34069*uk_33 + 24649*uk_34 + 144*uk_35 + 2076*uk_36 + 2604*uk_37 + 1884*uk_38 + 29929*uk_39 + 157*uk_4 + 37541*uk_40 + 27161*uk_41 + 47089*uk_42 + 34069*uk_43 + 24649*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 278046019516*uk_47 + 352042137613*uk_48 + 26907679308*uk_49 + 12*uk_5 + 387919043357*uk_50 + 486580534153*uk_51 + 352042137613*uk_52 + 187944057*uk_53 + 369921636*uk_54 + 468368523*uk_55 + 35798868*uk_56 + 516100347*uk_57 + 647362863*uk_58 + 468368523*uk_59 + 173*uk_6 + 728099728*uk_60 + 921868204*uk_61 + 70461264*uk_62 + 1015816556*uk_63 + 1274174524*uk_64 + 921868204*uk_65 + 1167204097*uk_66 + 89213052*uk_67 + 1286154833*uk_68 + 1613269357*uk_69 + 217*uk_7 + 1167204097*uk_70 + 6818832*uk_71 + 98304828*uk_72 + 123307212*uk_73 + 89213052*uk_74 + 1417227937*uk_75 + 1777678973*uk_76 + 1286154833*uk_77 + 2229805417*uk_78 + 1613269357*uk_79 + 157*uk_8 + 1167204097*uk_80 + 250047*uk_81 + 492156*uk_82 + 623133*uk_83 + 47628*uk_84 + 686637*uk_85 + 861273*uk_86 + 623133*uk_87 + 968688*uk_88 + 1226484*uk_89 + 2242306609*uk_9 + 93744*uk_90 + 1351476*uk_91 + 1695204*uk_92 + 1226484*uk_93 + 1552887*uk_94 + 118692*uk_95 + 1711143*uk_96 + 2146347*uk_97 + 1552887*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 132300*uk_100 + 164052*uk_101 + 93744*uk_102 + 1929375*uk_103 + 2392425*uk_104 + 1367100*uk_105 + 2966607*uk_106 + 1695204*uk_107 + 968688*uk_108 + 1092727*uk_109 + 4877359*uk_11 + 1315516*uk_110 + 127308*uk_111 + 1856575*uk_112 + 2302153*uk_113 + 1315516*uk_114 + 1583728*uk_115 + 153264*uk_116 + 2235100*uk_117 + 2771524*uk_118 + 1583728*uk_119 + 5871772*uk_12 + 14832*uk_120 + 216300*uk_121 + 268212*uk_122 + 153264*uk_123 + 3154375*uk_124 + 3911425*uk_125 + 2235100*uk_126 + 4850167*uk_127 + 2771524*uk_128 + 1583728*uk_129 + 568236*uk_13 + 1906624*uk_130 + 184512*uk_131 + 2690800*uk_132 + 3336592*uk_133 + 1906624*uk_134 + 17856*uk_135 + 260400*uk_136 + 322896*uk_137 + 184512*uk_138 + 3797500*uk_139 + 8286775*uk_14 + 4708900*uk_140 + 2690800*uk_141 + 5839036*uk_142 + 3336592*uk_143 + 1906624*uk_144 + 1728*uk_145 + 25200*uk_146 + 31248*uk_147 + 17856*uk_148 + 367500*uk_149 + 10275601*uk_15 + 455700*uk_150 + 260400*uk_151 + 565068*uk_152 + 322896*uk_153 + 184512*uk_154 + 5359375*uk_155 + 6645625*uk_156 + 3797500*uk_157 + 8240575*uk_158 + 4708900*uk_159 + 5871772*uk_16 + 2690800*uk_160 + 10218313*uk_161 + 5839036*uk_162 + 3336592*uk_163 + 1906624*uk_164 + 3969*uk_17 + 6489*uk_18 + 7812*uk_19 + 63*uk_2 + 756*uk_20 + 11025*uk_21 + 13671*uk_22 + 7812*uk_23 + 10609*uk_24 + 12772*uk_25 + 1236*uk_26 + 18025*uk_27 + 22351*uk_28 + 12772*uk_29 + 103*uk_3 + 15376*uk_30 + 1488*uk_31 + 21700*uk_32 + 26908*uk_33 + 15376*uk_34 + 144*uk_35 + 2100*uk_36 + 2604*uk_37 + 1488*uk_38 + 30625*uk_39 + 124*uk_4 + 37975*uk_40 + 21700*uk_41 + 47089*uk_42 + 26908*uk_43 + 15376*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 230957580727*uk_47 + 278046019516*uk_48 + 26907679308*uk_49 + 12*uk_5 + 392403656575*uk_50 + 486580534153*uk_51 + 278046019516*uk_52 + 187944057*uk_53 + 307273617*uk_54 + 369921636*uk_55 + 35798868*uk_56 + 522066825*uk_57 + 647362863*uk_58 + 369921636*uk_59 + 175*uk_6 + 502367977*uk_60 + 604792516*uk_61 + 58528308*uk_62 + 853537825*uk_63 + 1058386903*uk_64 + 604792516*uk_65 + 728099728*uk_66 + 70461264*uk_67 + 1027560100*uk_68 + 1274174524*uk_69 + 217*uk_7 + 728099728*uk_70 + 6818832*uk_71 + 99441300*uk_72 + 123307212*uk_73 + 70461264*uk_74 + 1450185625*uk_75 + 1798230175*uk_76 + 1027560100*uk_77 + 2229805417*uk_78 + 1274174524*uk_79 + 124*uk_8 + 728099728*uk_80 + 250047*uk_81 + 408807*uk_82 + 492156*uk_83 + 47628*uk_84 + 694575*uk_85 + 861273*uk_86 + 492156*uk_87 + 668367*uk_88 + 804636*uk_89 + 2242306609*uk_9 + 77868*uk_90 + 1135575*uk_91 + 1408113*uk_92 + 804636*uk_93 + 968688*uk_94 + 93744*uk_95 + 1367100*uk_96 + 1695204*uk_97 + 968688*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 133812*uk_100 + 164052*uk_101 + 77868*uk_102 + 1973727*uk_103 + 2419767*uk_104 + 1148553*uk_105 + 2966607*uk_106 + 1408113*uk_107 + 668367*uk_108 + 830584*uk_109 + 4451182*uk_11 + 910108*uk_110 + 106032*uk_111 + 1563972*uk_112 + 1917412*uk_113 + 910108*uk_114 + 997246*uk_115 + 116184*uk_116 + 1713714*uk_117 + 2100994*uk_118 + 997246*uk_119 + 4877359*uk_12 + 13536*uk_120 + 199656*uk_121 + 244776*uk_122 + 116184*uk_123 + 2944926*uk_124 + 3610446*uk_125 + 1713714*uk_126 + 4426366*uk_127 + 2100994*uk_128 + 997246*uk_129 + 568236*uk_13 + 1092727*uk_130 + 127308*uk_131 + 1877793*uk_132 + 2302153*uk_133 + 1092727*uk_134 + 14832*uk_135 + 218772*uk_136 + 268212*uk_137 + 127308*uk_138 + 3226887*uk_139 + 8381481*uk_14 + 3956127*uk_140 + 1877793*uk_141 + 4850167*uk_142 + 2302153*uk_143 + 1092727*uk_144 + 1728*uk_145 + 25488*uk_146 + 31248*uk_147 + 14832*uk_148 + 375948*uk_149 + 10275601*uk_15 + 460908*uk_150 + 218772*uk_151 + 565068*uk_152 + 268212*uk_153 + 127308*uk_154 + 5545233*uk_155 + 6798393*uk_156 + 3226887*uk_157 + 8334753*uk_158 + 3956127*uk_159 + 4877359*uk_16 + 1877793*uk_160 + 10218313*uk_161 + 4850167*uk_162 + 2302153*uk_163 + 1092727*uk_164 + 3969*uk_17 + 5922*uk_18 + 6489*uk_19 + 63*uk_2 + 756*uk_20 + 11151*uk_21 + 13671*uk_22 + 6489*uk_23 + 8836*uk_24 + 9682*uk_25 + 1128*uk_26 + 16638*uk_27 + 20398*uk_28 + 9682*uk_29 + 94*uk_3 + 10609*uk_30 + 1236*uk_31 + 18231*uk_32 + 22351*uk_33 + 10609*uk_34 + 144*uk_35 + 2124*uk_36 + 2604*uk_37 + 1236*uk_38 + 31329*uk_39 + 103*uk_4 + 38409*uk_40 + 18231*uk_41 + 47089*uk_42 + 22351*uk_43 + 10609*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 210776821246*uk_47 + 230957580727*uk_48 + 26907679308*uk_49 + 12*uk_5 + 396888269793*uk_50 + 486580534153*uk_51 + 230957580727*uk_52 + 187944057*uk_53 + 280424466*uk_54 + 307273617*uk_55 + 35798868*uk_56 + 528033303*uk_57 + 647362863*uk_58 + 307273617*uk_59 + 177*uk_6 + 418411108*uk_60 + 458471746*uk_61 + 53414184*uk_62 + 787859214*uk_63 + 965906494*uk_64 + 458471746*uk_65 + 502367977*uk_66 + 58528308*uk_67 + 863292543*uk_68 + 1058386903*uk_69 + 217*uk_7 + 502367977*uk_70 + 6818832*uk_71 + 100577772*uk_72 + 123307212*uk_73 + 58528308*uk_74 + 1483522137*uk_75 + 1818781377*uk_76 + 863292543*uk_77 + 2229805417*uk_78 + 1058386903*uk_79 + 103*uk_8 + 502367977*uk_80 + 250047*uk_81 + 373086*uk_82 + 408807*uk_83 + 47628*uk_84 + 702513*uk_85 + 861273*uk_86 + 408807*uk_87 + 556668*uk_88 + 609966*uk_89 + 2242306609*uk_9 + 71064*uk_90 + 1048194*uk_91 + 1285074*uk_92 + 609966*uk_93 + 668367*uk_94 + 77868*uk_95 + 1148553*uk_96 + 1408113*uk_97 + 668367*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 135324*uk_100 + 164052*uk_101 + 71064*uk_102 + 2018583*uk_103 + 2447109*uk_104 + 1060038*uk_105 + 2966607*uk_106 + 1285074*uk_107 + 556668*uk_108 + 912673*uk_109 + 4593241*uk_11 + 884446*uk_110 + 112908*uk_111 + 1684211*uk_112 + 2041753*uk_113 + 884446*uk_114 + 857092*uk_115 + 109416*uk_116 + 1632122*uk_117 + 1978606*uk_118 + 857092*uk_119 + 4451182*uk_12 + 13968*uk_120 + 208356*uk_121 + 252588*uk_122 + 109416*uk_123 + 3107977*uk_124 + 3767771*uk_125 + 1632122*uk_126 + 4567633*uk_127 + 1978606*uk_128 + 857092*uk_129 + 568236*uk_13 + 830584*uk_130 + 106032*uk_131 + 1581644*uk_132 + 1917412*uk_133 + 830584*uk_134 + 13536*uk_135 + 201912*uk_136 + 244776*uk_137 + 106032*uk_138 + 3011854*uk_139 + 8476187*uk_14 + 3651242*uk_140 + 1581644*uk_141 + 4426366*uk_142 + 1917412*uk_143 + 830584*uk_144 + 1728*uk_145 + 25776*uk_146 + 31248*uk_147 + 13536*uk_148 + 384492*uk_149 + 10275601*uk_15 + 466116*uk_150 + 201912*uk_151 + 565068*uk_152 + 244776*uk_153 + 106032*uk_154 + 5735339*uk_155 + 6952897*uk_156 + 3011854*uk_157 + 8428931*uk_158 + 3651242*uk_159 + 4451182*uk_16 + 1581644*uk_160 + 10218313*uk_161 + 4426366*uk_162 + 1917412*uk_163 + 830584*uk_164 + 3969*uk_17 + 6111*uk_18 + 5922*uk_19 + 63*uk_2 + 756*uk_20 + 11277*uk_21 + 13671*uk_22 + 5922*uk_23 + 9409*uk_24 + 9118*uk_25 + 1164*uk_26 + 17363*uk_27 + 21049*uk_28 + 9118*uk_29 + 97*uk_3 + 8836*uk_30 + 1128*uk_31 + 16826*uk_32 + 20398*uk_33 + 8836*uk_34 + 144*uk_35 + 2148*uk_36 + 2604*uk_37 + 1128*uk_38 + 32041*uk_39 + 94*uk_4 + 38843*uk_40 + 16826*uk_41 + 47089*uk_42 + 20398*uk_43 + 8836*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 217503741073*uk_47 + 210776821246*uk_48 + 26907679308*uk_49 + 12*uk_5 + 401372883011*uk_50 + 486580534153*uk_51 + 210776821246*uk_52 + 187944057*uk_53 + 289374183*uk_54 + 280424466*uk_55 + 35798868*uk_56 + 533999781*uk_57 + 647362863*uk_58 + 280424466*uk_59 + 179*uk_6 + 445544377*uk_60 + 431764654*uk_61 + 55118892*uk_62 + 822190139*uk_63 + 996733297*uk_64 + 431764654*uk_65 + 418411108*uk_66 + 53414184*uk_67 + 796761578*uk_68 + 965906494*uk_69 + 217*uk_7 + 418411108*uk_70 + 6818832*uk_71 + 101714244*uk_72 + 123307212*uk_73 + 53414184*uk_74 + 1517237473*uk_75 + 1839332579*uk_76 + 796761578*uk_77 + 2229805417*uk_78 + 965906494*uk_79 + 94*uk_8 + 418411108*uk_80 + 250047*uk_81 + 384993*uk_82 + 373086*uk_83 + 47628*uk_84 + 710451*uk_85 + 861273*uk_86 + 373086*uk_87 + 592767*uk_88 + 574434*uk_89 + 2242306609*uk_9 + 73332*uk_90 + 1093869*uk_91 + 1326087*uk_92 + 574434*uk_93 + 556668*uk_94 + 71064*uk_95 + 1060038*uk_96 + 1285074*uk_97 + 556668*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 136836*uk_100 + 164052*uk_101 + 73332*uk_102 + 2063943*uk_103 + 2474451*uk_104 + 1106091*uk_105 + 2966607*uk_106 + 1326087*uk_107 + 592767*uk_108 + 1404928*uk_109 + 5303536*uk_11 + 1216768*uk_110 + 150528*uk_111 + 2270464*uk_112 + 2722048*uk_113 + 1216768*uk_114 + 1053808*uk_115 + 130368*uk_116 + 1966384*uk_117 + 2357488*uk_118 + 1053808*uk_119 + 4593241*uk_12 + 16128*uk_120 + 243264*uk_121 + 291648*uk_122 + 130368*uk_123 + 3669232*uk_124 + 4399024*uk_125 + 1966384*uk_126 + 5273968*uk_127 + 2357488*uk_128 + 1053808*uk_129 + 568236*uk_13 + 912673*uk_130 + 112908*uk_131 + 1703029*uk_132 + 2041753*uk_133 + 912673*uk_134 + 13968*uk_135 + 210684*uk_136 + 252588*uk_137 + 112908*uk_138 + 3177817*uk_139 + 8570893*uk_14 + 3809869*uk_140 + 1703029*uk_141 + 4567633*uk_142 + 2041753*uk_143 + 912673*uk_144 + 1728*uk_145 + 26064*uk_146 + 31248*uk_147 + 13968*uk_148 + 393132*uk_149 + 10275601*uk_15 + 471324*uk_150 + 210684*uk_151 + 565068*uk_152 + 252588*uk_153 + 112908*uk_154 + 5929741*uk_155 + 7109137*uk_156 + 3177817*uk_157 + 8523109*uk_158 + 3809869*uk_159 + 4593241*uk_16 + 1703029*uk_160 + 10218313*uk_161 + 4567633*uk_162 + 2041753*uk_163 + 912673*uk_164 + 3969*uk_17 + 7056*uk_18 + 6111*uk_19 + 63*uk_2 + 756*uk_20 + 11403*uk_21 + 13671*uk_22 + 6111*uk_23 + 12544*uk_24 + 10864*uk_25 + 1344*uk_26 + 20272*uk_27 + 24304*uk_28 + 10864*uk_29 + 112*uk_3 + 9409*uk_30 + 1164*uk_31 + 17557*uk_32 + 21049*uk_33 + 9409*uk_34 + 144*uk_35 + 2172*uk_36 + 2604*uk_37 + 1164*uk_38 + 32761*uk_39 + 97*uk_4 + 39277*uk_40 + 17557*uk_41 + 47089*uk_42 + 21049*uk_43 + 9409*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 251138340208*uk_47 + 217503741073*uk_48 + 26907679308*uk_49 + 12*uk_5 + 405857496229*uk_50 + 486580534153*uk_51 + 217503741073*uk_52 + 187944057*uk_53 + 334122768*uk_54 + 289374183*uk_55 + 35798868*uk_56 + 539966259*uk_57 + 647362863*uk_58 + 289374183*uk_59 + 181*uk_6 + 593996032*uk_60 + 514442992*uk_61 + 63642432*uk_62 + 959940016*uk_63 + 1150867312*uk_64 + 514442992*uk_65 + 445544377*uk_66 + 55118892*uk_67 + 831376621*uk_68 + 996733297*uk_69 + 217*uk_7 + 445544377*uk_70 + 6818832*uk_71 + 102850716*uk_72 + 123307212*uk_73 + 55118892*uk_74 + 1551331633*uk_75 + 1859883781*uk_76 + 831376621*uk_77 + 2229805417*uk_78 + 996733297*uk_79 + 97*uk_8 + 445544377*uk_80 + 250047*uk_81 + 444528*uk_82 + 384993*uk_83 + 47628*uk_84 + 718389*uk_85 + 861273*uk_86 + 384993*uk_87 + 790272*uk_88 + 684432*uk_89 + 2242306609*uk_9 + 84672*uk_90 + 1277136*uk_91 + 1531152*uk_92 + 684432*uk_93 + 592767*uk_94 + 73332*uk_95 + 1106091*uk_96 + 1326087*uk_97 + 592767*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 138348*uk_100 + 164052*uk_101 + 84672*uk_102 + 2109807*uk_103 + 2501793*uk_104 + 1291248*uk_105 + 2966607*uk_106 + 1531152*uk_107 + 790272*uk_108 + 2685619*uk_109 + 6582067*uk_11 + 2163952*uk_110 + 231852*uk_111 + 3535743*uk_112 + 4192657*uk_113 + 2163952*uk_114 + 1743616*uk_115 + 186816*uk_116 + 2848944*uk_117 + 3378256*uk_118 + 1743616*uk_119 + 5303536*uk_12 + 20016*uk_120 + 305244*uk_121 + 361956*uk_122 + 186816*uk_123 + 4654971*uk_124 + 5519829*uk_125 + 2848944*uk_126 + 6545371*uk_127 + 3378256*uk_128 + 1743616*uk_129 + 568236*uk_13 + 1404928*uk_130 + 150528*uk_131 + 2295552*uk_132 + 2722048*uk_133 + 1404928*uk_134 + 16128*uk_135 + 245952*uk_136 + 291648*uk_137 + 150528*uk_138 + 3750768*uk_139 + 8665599*uk_14 + 4447632*uk_140 + 2295552*uk_141 + 5273968*uk_142 + 2722048*uk_143 + 1404928*uk_144 + 1728*uk_145 + 26352*uk_146 + 31248*uk_147 + 16128*uk_148 + 401868*uk_149 + 10275601*uk_15 + 476532*uk_150 + 245952*uk_151 + 565068*uk_152 + 291648*uk_153 + 150528*uk_154 + 6128487*uk_155 + 7267113*uk_156 + 3750768*uk_157 + 8617287*uk_158 + 4447632*uk_159 + 5303536*uk_16 + 2295552*uk_160 + 10218313*uk_161 + 5273968*uk_162 + 2722048*uk_163 + 1404928*uk_164 + 3969*uk_17 + 8757*uk_18 + 7056*uk_19 + 63*uk_2 + 756*uk_20 + 11529*uk_21 + 13671*uk_22 + 7056*uk_23 + 19321*uk_24 + 15568*uk_25 + 1668*uk_26 + 25437*uk_27 + 30163*uk_28 + 15568*uk_29 + 139*uk_3 + 12544*uk_30 + 1344*uk_31 + 20496*uk_32 + 24304*uk_33 + 12544*uk_34 + 144*uk_35 + 2196*uk_36 + 2604*uk_37 + 1344*uk_38 + 33489*uk_39 + 112*uk_4 + 39711*uk_40 + 20496*uk_41 + 47089*uk_42 + 24304*uk_43 + 12544*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 311680618651*uk_47 + 251138340208*uk_48 + 26907679308*uk_49 + 12*uk_5 + 410342109447*uk_50 + 486580534153*uk_51 + 251138340208*uk_52 + 187944057*uk_53 + 414670221*uk_54 + 334122768*uk_55 + 35798868*uk_56 + 545932737*uk_57 + 647362863*uk_58 + 334122768*uk_59 + 183*uk_6 + 914907313*uk_60 + 737191504*uk_61 + 78984804*uk_62 + 1204518261*uk_63 + 1428308539*uk_64 + 737191504*uk_65 + 593996032*uk_66 + 63642432*uk_67 + 970547088*uk_68 + 1150867312*uk_69 + 217*uk_7 + 593996032*uk_70 + 6818832*uk_71 + 103987188*uk_72 + 123307212*uk_73 + 63642432*uk_74 + 1585804617*uk_75 + 1880434983*uk_76 + 970547088*uk_77 + 2229805417*uk_78 + 1150867312*uk_79 + 112*uk_8 + 593996032*uk_80 + 250047*uk_81 + 551691*uk_82 + 444528*uk_83 + 47628*uk_84 + 726327*uk_85 + 861273*uk_86 + 444528*uk_87 + 1217223*uk_88 + 980784*uk_89 + 2242306609*uk_9 + 105084*uk_90 + 1602531*uk_91 + 1900269*uk_92 + 980784*uk_93 + 790272*uk_94 + 84672*uk_95 + 1291248*uk_96 + 1531152*uk_97 + 790272*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 139860*uk_100 + 164052*uk_101 + 105084*uk_102 + 2156175*uk_103 + 2529135*uk_104 + 1620045*uk_105 + 2966607*uk_106 + 1900269*uk_107 + 1217223*uk_108 + 5639752*uk_109 + 8428834*uk_11 + 4404076*uk_110 + 380208*uk_111 + 5861540*uk_112 + 6875428*uk_113 + 4404076*uk_114 + 3439138*uk_115 + 296904*uk_116 + 4577270*uk_117 + 5369014*uk_118 + 3439138*uk_119 + 6582067*uk_12 + 25632*uk_120 + 395160*uk_121 + 463512*uk_122 + 296904*uk_123 + 6092050*uk_124 + 7145810*uk_125 + 4577270*uk_126 + 8381842*uk_127 + 5369014*uk_128 + 3439138*uk_129 + 568236*uk_13 + 2685619*uk_130 + 231852*uk_131 + 3574385*uk_132 + 4192657*uk_133 + 2685619*uk_134 + 20016*uk_135 + 308580*uk_136 + 361956*uk_137 + 231852*uk_138 + 4757275*uk_139 + 8760305*uk_14 + 5580155*uk_140 + 3574385*uk_141 + 6545371*uk_142 + 4192657*uk_143 + 2685619*uk_144 + 1728*uk_145 + 26640*uk_146 + 31248*uk_147 + 20016*uk_148 + 410700*uk_149 + 10275601*uk_15 + 481740*uk_150 + 308580*uk_151 + 565068*uk_152 + 361956*uk_153 + 231852*uk_154 + 6331625*uk_155 + 7426825*uk_156 + 4757275*uk_157 + 8711465*uk_158 + 5580155*uk_159 + 6582067*uk_16 + 3574385*uk_160 + 10218313*uk_161 + 6545371*uk_162 + 4192657*uk_163 + 2685619*uk_164 + 3969*uk_17 + 11214*uk_18 + 8757*uk_19 + 63*uk_2 + 756*uk_20 + 11655*uk_21 + 13671*uk_22 + 8757*uk_23 + 31684*uk_24 + 24742*uk_25 + 2136*uk_26 + 32930*uk_27 + 38626*uk_28 + 24742*uk_29 + 178*uk_3 + 19321*uk_30 + 1668*uk_31 + 25715*uk_32 + 30163*uk_33 + 19321*uk_34 + 144*uk_35 + 2220*uk_36 + 2604*uk_37 + 1668*uk_38 + 34225*uk_39 + 139*uk_4 + 40145*uk_40 + 25715*uk_41 + 47089*uk_42 + 30163*uk_43 + 19321*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 399130576402*uk_47 + 311680618651*uk_48 + 26907679308*uk_49 + 12*uk_5 + 414826722665*uk_50 + 486580534153*uk_51 + 311680618651*uk_52 + 187944057*uk_53 + 531016542*uk_54 + 414670221*uk_55 + 35798868*uk_56 + 551899215*uk_57 + 647362863*uk_58 + 414670221*uk_59 + 185*uk_6 + 1500332452*uk_60 + 1171607926*uk_61 + 101146008*uk_62 + 1559334290*uk_63 + 1829056978*uk_64 + 1171607926*uk_65 + 914907313*uk_66 + 78984804*uk_67 + 1217682395*uk_68 + 1428308539*uk_69 + 217*uk_7 + 914907313*uk_70 + 6818832*uk_71 + 105123660*uk_72 + 123307212*uk_73 + 78984804*uk_74 + 1620656425*uk_75 + 1900986185*uk_76 + 1217682395*uk_77 + 2229805417*uk_78 + 1428308539*uk_79 + 139*uk_8 + 914907313*uk_80 + 250047*uk_81 + 706482*uk_82 + 551691*uk_83 + 47628*uk_84 + 734265*uk_85 + 861273*uk_86 + 551691*uk_87 + 1996092*uk_88 + 1558746*uk_89 + 2242306609*uk_9 + 134568*uk_90 + 2074590*uk_91 + 2433438*uk_92 + 1558746*uk_93 + 1217223*uk_94 + 105084*uk_95 + 1620045*uk_96 + 1900269*uk_97 + 1217223*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 94248*uk_100 + 109368*uk_101 + 89712*uk_102 + 2203047*uk_103 + 2556477*uk_104 + 2097018*uk_105 + 2966607*uk_106 + 2433438*uk_107 + 1996092*uk_108 + 74088*uk_109 + 1988826*uk_11 + 313992*uk_110 + 14112*uk_111 + 329868*uk_112 + 382788*uk_113 + 313992*uk_114 + 1330728*uk_115 + 59808*uk_116 + 1398012*uk_117 + 1622292*uk_118 + 1330728*uk_119 + 8428834*uk_12 + 2688*uk_120 + 62832*uk_121 + 72912*uk_122 + 59808*uk_123 + 1468698*uk_124 + 1704318*uk_125 + 1398012*uk_126 + 1977738*uk_127 + 1622292*uk_128 + 1330728*uk_129 + 378824*uk_13 + 5639752*uk_130 + 253472*uk_131 + 5924908*uk_132 + 6875428*uk_133 + 5639752*uk_134 + 11392*uk_135 + 266288*uk_136 + 309008*uk_137 + 253472*uk_138 + 6224482*uk_139 + 8855011*uk_14 + 7223062*uk_140 + 5924908*uk_141 + 8381842*uk_142 + 6875428*uk_143 + 5639752*uk_144 + 512*uk_145 + 11968*uk_146 + 13888*uk_147 + 11392*uk_148 + 279752*uk_149 + 10275601*uk_15 + 324632*uk_150 + 266288*uk_151 + 376712*uk_152 + 309008*uk_153 + 253472*uk_154 + 6539203*uk_155 + 7588273*uk_156 + 6224482*uk_157 + 8805643*uk_158 + 7223062*uk_159 + 8428834*uk_16 + 5924908*uk_160 + 10218313*uk_161 + 8381842*uk_162 + 6875428*uk_163 + 5639752*uk_164 + 3969*uk_17 + 2646*uk_18 + 11214*uk_19 + 63*uk_2 + 504*uk_20 + 11781*uk_21 + 13671*uk_22 + 11214*uk_23 + 1764*uk_24 + 7476*uk_25 + 336*uk_26 + 7854*uk_27 + 9114*uk_28 + 7476*uk_29 + 42*uk_3 + 31684*uk_30 + 1424*uk_31 + 33286*uk_32 + 38626*uk_33 + 31684*uk_34 + 64*uk_35 + 1496*uk_36 + 1736*uk_37 + 1424*uk_38 + 34969*uk_39 + 178*uk_4 + 40579*uk_40 + 33286*uk_41 + 47089*uk_42 + 38626*uk_43 + 31684*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 94176877578*uk_47 + 399130576402*uk_48 + 17938452872*uk_49 + 8*uk_5 + 419311335883*uk_50 + 486580534153*uk_51 + 399130576402*uk_52 + 187944057*uk_53 + 125296038*uk_54 + 531016542*uk_55 + 23865912*uk_56 + 557865693*uk_57 + 647362863*uk_58 + 531016542*uk_59 + 187*uk_6 + 83530692*uk_60 + 354011028*uk_61 + 15910608*uk_62 + 371910462*uk_63 + 431575242*uk_64 + 354011028*uk_65 + 1500332452*uk_66 + 67430672*uk_67 + 1576191958*uk_68 + 1829056978*uk_69 + 217*uk_7 + 1500332452*uk_70 + 3030592*uk_71 + 70840088*uk_72 + 82204808*uk_73 + 67430672*uk_74 + 1655887057*uk_75 + 1921537387*uk_76 + 1576191958*uk_77 + 2229805417*uk_78 + 1829056978*uk_79 + 178*uk_8 + 1500332452*uk_80 + 250047*uk_81 + 166698*uk_82 + 706482*uk_83 + 31752*uk_84 + 742203*uk_85 + 861273*uk_86 + 706482*uk_87 + 111132*uk_88 + 470988*uk_89 + 2242306609*uk_9 + 21168*uk_90 + 494802*uk_91 + 574182*uk_92 + 470988*uk_93 + 1996092*uk_94 + 89712*uk_95 + 2097018*uk_96 + 2433438*uk_97 + 1996092*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 142884*uk_100 + 164052*uk_101 + 31752*uk_102 + 2250423*uk_103 + 2583819*uk_104 + 500094*uk_105 + 2966607*uk_106 + 574182*uk_107 + 111132*uk_108 + 1092727*uk_109 + 4877359*uk_11 + 445578*uk_110 + 127308*uk_111 + 2005101*uk_112 + 2302153*uk_113 + 445578*uk_114 + 181692*uk_115 + 51912*uk_116 + 817614*uk_117 + 938742*uk_118 + 181692*uk_119 + 1988826*uk_12 + 14832*uk_120 + 233604*uk_121 + 268212*uk_122 + 51912*uk_123 + 3679263*uk_124 + 4224339*uk_125 + 817614*uk_126 + 4850167*uk_127 + 938742*uk_128 + 181692*uk_129 + 568236*uk_13 + 74088*uk_130 + 21168*uk_131 + 333396*uk_132 + 382788*uk_133 + 74088*uk_134 + 6048*uk_135 + 95256*uk_136 + 109368*uk_137 + 21168*uk_138 + 1500282*uk_139 + 8949717*uk_14 + 1722546*uk_140 + 333396*uk_141 + 1977738*uk_142 + 382788*uk_143 + 74088*uk_144 + 1728*uk_145 + 27216*uk_146 + 31248*uk_147 + 6048*uk_148 + 428652*uk_149 + 10275601*uk_15 + 492156*uk_150 + 95256*uk_151 + 565068*uk_152 + 109368*uk_153 + 21168*uk_154 + 6751269*uk_155 + 7751457*uk_156 + 1500282*uk_157 + 8899821*uk_158 + 1722546*uk_159 + 1988826*uk_16 + 333396*uk_160 + 10218313*uk_161 + 1977738*uk_162 + 382788*uk_163 + 74088*uk_164 + 3969*uk_17 + 6489*uk_18 + 2646*uk_19 + 63*uk_2 + 756*uk_20 + 11907*uk_21 + 13671*uk_22 + 2646*uk_23 + 10609*uk_24 + 4326*uk_25 + 1236*uk_26 + 19467*uk_27 + 22351*uk_28 + 4326*uk_29 + 103*uk_3 + 1764*uk_30 + 504*uk_31 + 7938*uk_32 + 9114*uk_33 + 1764*uk_34 + 144*uk_35 + 2268*uk_36 + 2604*uk_37 + 504*uk_38 + 35721*uk_39 + 42*uk_4 + 41013*uk_40 + 7938*uk_41 + 47089*uk_42 + 9114*uk_43 + 1764*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 230957580727*uk_47 + 94176877578*uk_48 + 26907679308*uk_49 + 12*uk_5 + 423795949101*uk_50 + 486580534153*uk_51 + 94176877578*uk_52 + 187944057*uk_53 + 307273617*uk_54 + 125296038*uk_55 + 35798868*uk_56 + 563832171*uk_57 + 647362863*uk_58 + 125296038*uk_59 + 189*uk_6 + 502367977*uk_60 + 204849078*uk_61 + 58528308*uk_62 + 921820851*uk_63 + 1058386903*uk_64 + 204849078*uk_65 + 83530692*uk_66 + 23865912*uk_67 + 375888114*uk_68 + 431575242*uk_69 + 217*uk_7 + 83530692*uk_70 + 6818832*uk_71 + 107396604*uk_72 + 123307212*uk_73 + 23865912*uk_74 + 1691496513*uk_75 + 1942088589*uk_76 + 375888114*uk_77 + 2229805417*uk_78 + 431575242*uk_79 + 42*uk_8 + 83530692*uk_80 + 250047*uk_81 + 408807*uk_82 + 166698*uk_83 + 47628*uk_84 + 750141*uk_85 + 861273*uk_86 + 166698*uk_87 + 668367*uk_88 + 272538*uk_89 + 2242306609*uk_9 + 77868*uk_90 + 1226421*uk_91 + 1408113*uk_92 + 272538*uk_93 + 111132*uk_94 + 31752*uk_95 + 500094*uk_96 + 574182*uk_97 + 111132*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 144396*uk_100 + 164052*uk_101 + 77868*uk_102 + 2298303*uk_103 + 2611161*uk_104 + 1239399*uk_105 + 2966607*uk_106 + 1408113*uk_107 + 668367*uk_108 + 5451776*uk_109 + 8334128*uk_11 + 3190528*uk_110 + 371712*uk_111 + 5916416*uk_112 + 6721792*uk_113 + 3190528*uk_114 + 1867184*uk_115 + 217536*uk_116 + 3462448*uk_117 + 3933776*uk_118 + 1867184*uk_119 + 4877359*uk_12 + 25344*uk_120 + 403392*uk_121 + 458304*uk_122 + 217536*uk_123 + 6420656*uk_124 + 7294672*uk_125 + 3462448*uk_126 + 8287664*uk_127 + 3933776*uk_128 + 1867184*uk_129 + 568236*uk_13 + 1092727*uk_130 + 127308*uk_131 + 2026319*uk_132 + 2302153*uk_133 + 1092727*uk_134 + 14832*uk_135 + 236076*uk_136 + 268212*uk_137 + 127308*uk_138 + 3757543*uk_139 + 9044423*uk_14 + 4269041*uk_140 + 2026319*uk_141 + 4850167*uk_142 + 2302153*uk_143 + 1092727*uk_144 + 1728*uk_145 + 27504*uk_146 + 31248*uk_147 + 14832*uk_148 + 437772*uk_149 + 10275601*uk_15 + 497364*uk_150 + 236076*uk_151 + 565068*uk_152 + 268212*uk_153 + 127308*uk_154 + 6967871*uk_155 + 7916377*uk_156 + 3757543*uk_157 + 8993999*uk_158 + 4269041*uk_159 + 4877359*uk_16 + 2026319*uk_160 + 10218313*uk_161 + 4850167*uk_162 + 2302153*uk_163 + 1092727*uk_164 + 3969*uk_17 + 11088*uk_18 + 6489*uk_19 + 63*uk_2 + 756*uk_20 + 12033*uk_21 + 13671*uk_22 + 6489*uk_23 + 30976*uk_24 + 18128*uk_25 + 2112*uk_26 + 33616*uk_27 + 38192*uk_28 + 18128*uk_29 + 176*uk_3 + 10609*uk_30 + 1236*uk_31 + 19673*uk_32 + 22351*uk_33 + 10609*uk_34 + 144*uk_35 + 2292*uk_36 + 2604*uk_37 + 1236*uk_38 + 36481*uk_39 + 103*uk_4 + 41447*uk_40 + 19673*uk_41 + 47089*uk_42 + 22351*uk_43 + 10609*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 394645963184*uk_47 + 230957580727*uk_48 + 26907679308*uk_49 + 12*uk_5 + 428280562319*uk_50 + 486580534153*uk_51 + 230957580727*uk_52 + 187944057*uk_53 + 525050064*uk_54 + 307273617*uk_55 + 35798868*uk_56 + 569798649*uk_57 + 647362863*uk_58 + 307273617*uk_59 + 191*uk_6 + 1466806528*uk_60 + 858415184*uk_61 + 100009536*uk_62 + 1591818448*uk_63 + 1808505776*uk_64 + 858415184*uk_65 + 502367977*uk_66 + 58528308*uk_67 + 931575569*uk_68 + 1058386903*uk_69 + 217*uk_7 + 502367977*uk_70 + 6818832*uk_71 + 108533076*uk_72 + 123307212*uk_73 + 58528308*uk_74 + 1727484793*uk_75 + 1962639791*uk_76 + 931575569*uk_77 + 2229805417*uk_78 + 1058386903*uk_79 + 103*uk_8 + 502367977*uk_80 + 250047*uk_81 + 698544*uk_82 + 408807*uk_83 + 47628*uk_84 + 758079*uk_85 + 861273*uk_86 + 408807*uk_87 + 1951488*uk_88 + 1142064*uk_89 + 2242306609*uk_9 + 133056*uk_90 + 2117808*uk_91 + 2406096*uk_92 + 1142064*uk_93 + 668367*uk_94 + 77868*uk_95 + 1239399*uk_96 + 1408113*uk_97 + 668367*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 97272*uk_100 + 109368*uk_101 + 88704*uk_102 + 2346687*uk_103 + 2638503*uk_104 + 2139984*uk_105 + 2966607*uk_106 + 2406096*uk_107 + 1951488*uk_108 + 314432*uk_109 + 3220004*uk_11 + 813824*uk_110 + 36992*uk_111 + 892432*uk_112 + 1003408*uk_113 + 813824*uk_114 + 2106368*uk_115 + 95744*uk_116 + 2309824*uk_117 + 2597056*uk_118 + 2106368*uk_119 + 8334128*uk_12 + 4352*uk_120 + 104992*uk_121 + 118048*uk_122 + 95744*uk_123 + 2532932*uk_124 + 2847908*uk_125 + 2309824*uk_126 + 3202052*uk_127 + 2597056*uk_128 + 2106368*uk_129 + 378824*uk_13 + 5451776*uk_130 + 247808*uk_131 + 5978368*uk_132 + 6721792*uk_133 + 5451776*uk_134 + 11264*uk_135 + 271744*uk_136 + 305536*uk_137 + 247808*uk_138 + 6555824*uk_139 + 9139129*uk_14 + 7371056*uk_140 + 5978368*uk_141 + 8287664*uk_142 + 6721792*uk_143 + 5451776*uk_144 + 512*uk_145 + 12352*uk_146 + 13888*uk_147 + 11264*uk_148 + 297992*uk_149 + 10275601*uk_15 + 335048*uk_150 + 271744*uk_151 + 376712*uk_152 + 305536*uk_153 + 247808*uk_154 + 7189057*uk_155 + 8083033*uk_156 + 6555824*uk_157 + 9088177*uk_158 + 7371056*uk_159 + 8334128*uk_16 + 5978368*uk_160 + 10218313*uk_161 + 8287664*uk_162 + 6721792*uk_163 + 5451776*uk_164 + 3969*uk_17 + 4284*uk_18 + 11088*uk_19 + 63*uk_2 + 504*uk_20 + 12159*uk_21 + 13671*uk_22 + 11088*uk_23 + 4624*uk_24 + 11968*uk_25 + 544*uk_26 + 13124*uk_27 + 14756*uk_28 + 11968*uk_29 + 68*uk_3 + 30976*uk_30 + 1408*uk_31 + 33968*uk_32 + 38192*uk_33 + 30976*uk_34 + 64*uk_35 + 1544*uk_36 + 1736*uk_37 + 1408*uk_38 + 37249*uk_39 + 176*uk_4 + 41881*uk_40 + 33968*uk_41 + 47089*uk_42 + 38192*uk_43 + 30976*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 152476849412*uk_47 + 394645963184*uk_48 + 17938452872*uk_49 + 8*uk_5 + 432765175537*uk_50 + 486580534153*uk_51 + 394645963184*uk_52 + 187944057*uk_53 + 202860252*uk_54 + 525050064*uk_55 + 23865912*uk_56 + 575765127*uk_57 + 647362863*uk_58 + 525050064*uk_59 + 193*uk_6 + 218960272*uk_60 + 566720704*uk_61 + 25760032*uk_62 + 621460772*uk_63 + 698740868*uk_64 + 566720704*uk_65 + 1466806528*uk_66 + 66673024*uk_67 + 1608486704*uk_68 + 1808505776*uk_69 + 217*uk_7 + 1466806528*uk_70 + 3030592*uk_71 + 73113032*uk_72 + 82204808*uk_73 + 66673024*uk_74 + 1763851897*uk_75 + 1983190993*uk_76 + 1608486704*uk_77 + 2229805417*uk_78 + 1808505776*uk_79 + 176*uk_8 + 1466806528*uk_80 + 250047*uk_81 + 269892*uk_82 + 698544*uk_83 + 31752*uk_84 + 766017*uk_85 + 861273*uk_86 + 698544*uk_87 + 291312*uk_88 + 753984*uk_89 + 2242306609*uk_9 + 34272*uk_90 + 826812*uk_91 + 929628*uk_92 + 753984*uk_93 + 1951488*uk_94 + 88704*uk_95 + 2139984*uk_96 + 2406096*uk_97 + 1951488*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 147420*uk_100 + 164052*uk_101 + 51408*uk_102 + 2395575*uk_103 + 2665845*uk_104 + 835380*uk_105 + 2966607*uk_106 + 929628*uk_107 + 291312*uk_108 + 4330747*uk_109 + 7718539*uk_11 + 1806692*uk_110 + 318828*uk_111 + 5180955*uk_112 + 5765473*uk_113 + 1806692*uk_114 + 753712*uk_115 + 133008*uk_116 + 2161380*uk_117 + 2405228*uk_118 + 753712*uk_119 + 3220004*uk_12 + 23472*uk_120 + 381420*uk_121 + 424452*uk_122 + 133008*uk_123 + 6198075*uk_124 + 6897345*uk_125 + 2161380*uk_126 + 7675507*uk_127 + 2405228*uk_128 + 753712*uk_129 + 568236*uk_13 + 314432*uk_130 + 55488*uk_131 + 901680*uk_132 + 1003408*uk_133 + 314432*uk_134 + 9792*uk_135 + 159120*uk_136 + 177072*uk_137 + 55488*uk_138 + 2585700*uk_139 + 9233835*uk_14 + 2877420*uk_140 + 901680*uk_141 + 3202052*uk_142 + 1003408*uk_143 + 314432*uk_144 + 1728*uk_145 + 28080*uk_146 + 31248*uk_147 + 9792*uk_148 + 456300*uk_149 + 10275601*uk_15 + 507780*uk_150 + 159120*uk_151 + 565068*uk_152 + 177072*uk_153 + 55488*uk_154 + 7414875*uk_155 + 8251425*uk_156 + 2585700*uk_157 + 9182355*uk_158 + 2877420*uk_159 + 3220004*uk_16 + 901680*uk_160 + 10218313*uk_161 + 3202052*uk_162 + 1003408*uk_163 + 314432*uk_164 + 3969*uk_17 + 10269*uk_18 + 4284*uk_19 + 63*uk_2 + 756*uk_20 + 12285*uk_21 + 13671*uk_22 + 4284*uk_23 + 26569*uk_24 + 11084*uk_25 + 1956*uk_26 + 31785*uk_27 + 35371*uk_28 + 11084*uk_29 + 163*uk_3 + 4624*uk_30 + 816*uk_31 + 13260*uk_32 + 14756*uk_33 + 4624*uk_34 + 144*uk_35 + 2340*uk_36 + 2604*uk_37 + 816*uk_38 + 38025*uk_39 + 68*uk_4 + 42315*uk_40 + 13260*uk_41 + 47089*uk_42 + 14756*uk_43 + 4624*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 365495977267*uk_47 + 152476849412*uk_48 + 26907679308*uk_49 + 12*uk_5 + 437249788755*uk_50 + 486580534153*uk_51 + 152476849412*uk_52 + 187944057*uk_53 + 486267957*uk_54 + 202860252*uk_55 + 35798868*uk_56 + 581731605*uk_57 + 647362863*uk_58 + 202860252*uk_59 + 195*uk_6 + 1258121857*uk_60 + 524860652*uk_61 + 92622468*uk_62 + 1505115105*uk_63 + 1674922963*uk_64 + 524860652*uk_65 + 218960272*uk_66 + 38640048*uk_67 + 627900780*uk_68 + 698740868*uk_69 + 217*uk_7 + 218960272*uk_70 + 6818832*uk_71 + 110806020*uk_72 + 123307212*uk_73 + 38640048*uk_74 + 1800597825*uk_75 + 2003742195*uk_76 + 627900780*uk_77 + 2229805417*uk_78 + 698740868*uk_79 + 68*uk_8 + 218960272*uk_80 + 250047*uk_81 + 646947*uk_82 + 269892*uk_83 + 47628*uk_84 + 773955*uk_85 + 861273*uk_86 + 269892*uk_87 + 1673847*uk_88 + 698292*uk_89 + 2242306609*uk_9 + 123228*uk_90 + 2002455*uk_91 + 2228373*uk_92 + 698292*uk_93 + 291312*uk_94 + 51408*uk_95 + 835380*uk_96 + 929628*uk_97 + 291312*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 99288*uk_100 + 109368*uk_101 + 82152*uk_102 + 2444967*uk_103 + 2693187*uk_104 + 2022993*uk_105 + 2966607*uk_106 + 2228373*uk_107 + 1673847*uk_108 + 389017*uk_109 + 3456769*uk_11 + 868627*uk_110 + 42632*uk_111 + 1049813*uk_112 + 1156393*uk_113 + 868627*uk_114 + 1939537*uk_115 + 95192*uk_116 + 2344103*uk_117 + 2582083*uk_118 + 1939537*uk_119 + 7718539*uk_12 + 4672*uk_120 + 115048*uk_121 + 126728*uk_122 + 95192*uk_123 + 2833057*uk_124 + 3120677*uk_125 + 2344103*uk_126 + 3437497*uk_127 + 2582083*uk_128 + 1939537*uk_129 + 378824*uk_13 + 4330747*uk_130 + 212552*uk_131 + 5234093*uk_132 + 5765473*uk_133 + 4330747*uk_134 + 10432*uk_135 + 256888*uk_136 + 282968*uk_137 + 212552*uk_138 + 6325867*uk_139 + 9328541*uk_14 + 6968087*uk_140 + 5234093*uk_141 + 7675507*uk_142 + 5765473*uk_143 + 4330747*uk_144 + 512*uk_145 + 12608*uk_146 + 13888*uk_147 + 10432*uk_148 + 310472*uk_149 + 10275601*uk_15 + 341992*uk_150 + 256888*uk_151 + 376712*uk_152 + 282968*uk_153 + 212552*uk_154 + 7645373*uk_155 + 8421553*uk_156 + 6325867*uk_157 + 9276533*uk_158 + 6968087*uk_159 + 7718539*uk_16 + 5234093*uk_160 + 10218313*uk_161 + 7675507*uk_162 + 5765473*uk_163 + 4330747*uk_164 + 3969*uk_17 + 4599*uk_18 + 10269*uk_19 + 63*uk_2 + 504*uk_20 + 12411*uk_21 + 13671*uk_22 + 10269*uk_23 + 5329*uk_24 + 11899*uk_25 + 584*uk_26 + 14381*uk_27 + 15841*uk_28 + 11899*uk_29 + 73*uk_3 + 26569*uk_30 + 1304*uk_31 + 32111*uk_32 + 35371*uk_33 + 26569*uk_34 + 64*uk_35 + 1576*uk_36 + 1736*uk_37 + 1304*uk_38 + 38809*uk_39 + 163*uk_4 + 42749*uk_40 + 32111*uk_41 + 47089*uk_42 + 35371*uk_43 + 26569*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 163688382457*uk_47 + 365495977267*uk_48 + 17938452872*uk_49 + 8*uk_5 + 441734401973*uk_50 + 486580534153*uk_51 + 365495977267*uk_52 + 187944057*uk_53 + 217776447*uk_54 + 486267957*uk_55 + 23865912*uk_56 + 587698083*uk_57 + 647362863*uk_58 + 486267957*uk_59 + 197*uk_6 + 252344137*uk_60 + 563453347*uk_61 + 27654152*uk_62 + 680983493*uk_63 + 750118873*uk_64 + 563453347*uk_65 + 1258121857*uk_66 + 61748312*uk_67 + 1520552183*uk_68 + 1674922963*uk_69 + 217*uk_7 + 1258121857*uk_70 + 3030592*uk_71 + 74628328*uk_72 + 82204808*uk_73 + 61748312*uk_74 + 1837722577*uk_75 + 2024293397*uk_76 + 1520552183*uk_77 + 2229805417*uk_78 + 1674922963*uk_79 + 163*uk_8 + 1258121857*uk_80 + 250047*uk_81 + 289737*uk_82 + 646947*uk_83 + 31752*uk_84 + 781893*uk_85 + 861273*uk_86 + 646947*uk_87 + 335727*uk_88 + 749637*uk_89 + 2242306609*uk_9 + 36792*uk_90 + 906003*uk_91 + 997983*uk_92 + 749637*uk_93 + 1673847*uk_94 + 82152*uk_95 + 2022993*uk_96 + 2228373*uk_97 + 1673847*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 150444*uk_100 + 164052*uk_101 + 55188*uk_102 + 2494863*uk_103 + 2720529*uk_104 + 915201*uk_105 + 2966607*uk_106 + 997983*uk_107 + 335727*uk_108 + 6859000*uk_109 + 8997070*uk_11 + 2635300*uk_110 + 433200*uk_111 + 7183900*uk_112 + 7833700*uk_113 + 2635300*uk_114 + 1012510*uk_115 + 166440*uk_116 + 2760130*uk_117 + 3009790*uk_118 + 1012510*uk_119 + 3456769*uk_12 + 27360*uk_120 + 453720*uk_121 + 494760*uk_122 + 166440*uk_123 + 7524190*uk_124 + 8204770*uk_125 + 2760130*uk_126 + 8946910*uk_127 + 3009790*uk_128 + 1012510*uk_129 + 568236*uk_13 + 389017*uk_130 + 63948*uk_131 + 1060471*uk_132 + 1156393*uk_133 + 389017*uk_134 + 10512*uk_135 + 174324*uk_136 + 190092*uk_137 + 63948*uk_138 + 2890873*uk_139 + 9423247*uk_14 + 3152359*uk_140 + 1060471*uk_141 + 3437497*uk_142 + 1156393*uk_143 + 389017*uk_144 + 1728*uk_145 + 28656*uk_146 + 31248*uk_147 + 10512*uk_148 + 475212*uk_149 + 10275601*uk_15 + 518196*uk_150 + 174324*uk_151 + 565068*uk_152 + 190092*uk_153 + 63948*uk_154 + 7880599*uk_155 + 8593417*uk_156 + 2890873*uk_157 + 9370711*uk_158 + 3152359*uk_159 + 3456769*uk_16 + 1060471*uk_160 + 10218313*uk_161 + 3437497*uk_162 + 1156393*uk_163 + 389017*uk_164 + 3969*uk_17 + 11970*uk_18 + 4599*uk_19 + 63*uk_2 + 756*uk_20 + 12537*uk_21 + 13671*uk_22 + 4599*uk_23 + 36100*uk_24 + 13870*uk_25 + 2280*uk_26 + 37810*uk_27 + 41230*uk_28 + 13870*uk_29 + 190*uk_3 + 5329*uk_30 + 876*uk_31 + 14527*uk_32 + 15841*uk_33 + 5329*uk_34 + 144*uk_35 + 2388*uk_36 + 2604*uk_37 + 876*uk_38 + 39601*uk_39 + 73*uk_4 + 43183*uk_40 + 14527*uk_41 + 47089*uk_42 + 15841*uk_43 + 5329*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 426038255710*uk_47 + 163688382457*uk_48 + 26907679308*uk_49 + 12*uk_5 + 446219015191*uk_50 + 486580534153*uk_51 + 163688382457*uk_52 + 187944057*uk_53 + 566815410*uk_54 + 217776447*uk_55 + 35798868*uk_56 + 593664561*uk_57 + 647362863*uk_58 + 217776447*uk_59 + 199*uk_6 + 1709443300*uk_60 + 656786110*uk_61 + 107964840*uk_62 + 1790416930*uk_63 + 1952364190*uk_64 + 656786110*uk_65 + 252344137*uk_66 + 41481228*uk_67 + 687897031*uk_68 + 750118873*uk_69 + 217*uk_7 + 252344137*uk_70 + 6818832*uk_71 + 113078964*uk_72 + 123307212*uk_73 + 41481228*uk_74 + 1875226153*uk_75 + 2044844599*uk_76 + 687897031*uk_77 + 2229805417*uk_78 + 750118873*uk_79 + 73*uk_8 + 252344137*uk_80 + 250047*uk_81 + 754110*uk_82 + 289737*uk_83 + 47628*uk_84 + 789831*uk_85 + 861273*uk_86 + 289737*uk_87 + 2274300*uk_88 + 873810*uk_89 + 2242306609*uk_9 + 143640*uk_90 + 2382030*uk_91 + 2597490*uk_92 + 873810*uk_93 + 335727*uk_94 + 55188*uk_95 + 915201*uk_96 + 997983*uk_97 + 335727*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 101304*uk_100 + 109368*uk_101 + 95760*uk_102 + 2545263*uk_103 + 2747871*uk_104 + 2405970*uk_105 + 2966607*uk_106 + 2597490*uk_107 + 2274300*uk_108 + 1643032*uk_109 + 5587654*uk_11 + 2645560*uk_110 + 111392*uk_111 + 2798724*uk_112 + 3021508*uk_113 + 2645560*uk_114 + 4259800*uk_115 + 179360*uk_116 + 4506420*uk_117 + 4865140*uk_118 + 4259800*uk_119 + 8997070*uk_12 + 7552*uk_120 + 189744*uk_121 + 204848*uk_122 + 179360*uk_123 + 4767318*uk_124 + 5146806*uk_125 + 4506420*uk_126 + 5556502*uk_127 + 4865140*uk_128 + 4259800*uk_129 + 378824*uk_13 + 6859000*uk_130 + 288800*uk_131 + 7256100*uk_132 + 7833700*uk_133 + 6859000*uk_134 + 12160*uk_135 + 305520*uk_136 + 329840*uk_137 + 288800*uk_138 + 7676190*uk_139 + 9517953*uk_14 + 8287230*uk_140 + 7256100*uk_141 + 8946910*uk_142 + 7833700*uk_143 + 6859000*uk_144 + 512*uk_145 + 12864*uk_146 + 13888*uk_147 + 12160*uk_148 + 323208*uk_149 + 10275601*uk_15 + 348936*uk_150 + 305520*uk_151 + 376712*uk_152 + 329840*uk_153 + 288800*uk_154 + 8120601*uk_155 + 8767017*uk_156 + 7676190*uk_157 + 9464889*uk_158 + 8287230*uk_159 + 8997070*uk_16 + 7256100*uk_160 + 10218313*uk_161 + 8946910*uk_162 + 7833700*uk_163 + 6859000*uk_164 + 3969*uk_17 + 7434*uk_18 + 11970*uk_19 + 63*uk_2 + 504*uk_20 + 12663*uk_21 + 13671*uk_22 + 11970*uk_23 + 13924*uk_24 + 22420*uk_25 + 944*uk_26 + 23718*uk_27 + 25606*uk_28 + 22420*uk_29 + 118*uk_3 + 36100*uk_30 + 1520*uk_31 + 38190*uk_32 + 41230*uk_33 + 36100*uk_34 + 64*uk_35 + 1608*uk_36 + 1736*uk_37 + 1520*uk_38 + 40401*uk_39 + 190*uk_4 + 43617*uk_40 + 38190*uk_41 + 47089*uk_42 + 41230*uk_43 + 36100*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 264592179862*uk_47 + 426038255710*uk_48 + 17938452872*uk_49 + 8*uk_5 + 450703628409*uk_50 + 486580534153*uk_51 + 426038255710*uk_52 + 187944057*uk_53 + 352022202*uk_54 + 566815410*uk_55 + 23865912*uk_56 + 599631039*uk_57 + 647362863*uk_58 + 566815410*uk_59 + 201*uk_6 + 659343172*uk_60 + 1061654260*uk_61 + 44701232*uk_62 + 1123118454*uk_63 + 1212520918*uk_64 + 1061654260*uk_65 + 1709443300*uk_66 + 71976560*uk_67 + 1808411070*uk_68 + 1952364190*uk_69 + 217*uk_7 + 1709443300*uk_70 + 3030592*uk_71 + 76143624*uk_72 + 82204808*uk_73 + 71976560*uk_74 + 1913108553*uk_75 + 2065395801*uk_76 + 1808411070*uk_77 + 2229805417*uk_78 + 1952364190*uk_79 + 190*uk_8 + 1709443300*uk_80 + 250047*uk_81 + 468342*uk_82 + 754110*uk_83 + 31752*uk_84 + 797769*uk_85 + 861273*uk_86 + 754110*uk_87 + 877212*uk_88 + 1412460*uk_89 + 2242306609*uk_9 + 59472*uk_90 + 1494234*uk_91 + 1613178*uk_92 + 1412460*uk_93 + 2274300*uk_94 + 95760*uk_95 + 2405970*uk_96 + 2597490*uk_97 + 2274300*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 102312*uk_100 + 109368*uk_101 + 59472*uk_102 + 2596167*uk_103 + 2775213*uk_104 + 1509102*uk_105 + 2966607*uk_106 + 1613178*uk_107 + 877212*uk_108 + 157464*uk_109 + 2557062*uk_11 + 344088*uk_110 + 23328*uk_111 + 591948*uk_112 + 632772*uk_113 + 344088*uk_114 + 751896*uk_115 + 50976*uk_116 + 1293516*uk_117 + 1382724*uk_118 + 751896*uk_119 + 5587654*uk_12 + 3456*uk_120 + 87696*uk_121 + 93744*uk_122 + 50976*uk_123 + 2225286*uk_124 + 2378754*uk_125 + 1293516*uk_126 + 2542806*uk_127 + 1382724*uk_128 + 751896*uk_129 + 378824*uk_13 + 1643032*uk_130 + 111392*uk_131 + 2826572*uk_132 + 3021508*uk_133 + 1643032*uk_134 + 7552*uk_135 + 191632*uk_136 + 204848*uk_137 + 111392*uk_138 + 4862662*uk_139 + 9612659*uk_14 + 5198018*uk_140 + 2826572*uk_141 + 5556502*uk_142 + 3021508*uk_143 + 1643032*uk_144 + 512*uk_145 + 12992*uk_146 + 13888*uk_147 + 7552*uk_148 + 329672*uk_149 + 10275601*uk_15 + 352408*uk_150 + 191632*uk_151 + 376712*uk_152 + 204848*uk_153 + 111392*uk_154 + 8365427*uk_155 + 8942353*uk_156 + 4862662*uk_157 + 9559067*uk_158 + 5198018*uk_159 + 5587654*uk_16 + 2826572*uk_160 + 10218313*uk_161 + 5556502*uk_162 + 3021508*uk_163 + 1643032*uk_164 + 3969*uk_17 + 3402*uk_18 + 7434*uk_19 + 63*uk_2 + 504*uk_20 + 12789*uk_21 + 13671*uk_22 + 7434*uk_23 + 2916*uk_24 + 6372*uk_25 + 432*uk_26 + 10962*uk_27 + 11718*uk_28 + 6372*uk_29 + 54*uk_3 + 13924*uk_30 + 944*uk_31 + 23954*uk_32 + 25606*uk_33 + 13924*uk_34 + 64*uk_35 + 1624*uk_36 + 1736*uk_37 + 944*uk_38 + 41209*uk_39 + 118*uk_4 + 44051*uk_40 + 23954*uk_41 + 47089*uk_42 + 25606*uk_43 + 13924*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 121084556886*uk_47 + 264592179862*uk_48 + 17938452872*uk_49 + 8*uk_5 + 455188241627*uk_50 + 486580534153*uk_51 + 264592179862*uk_52 + 187944057*uk_53 + 161094906*uk_54 + 352022202*uk_55 + 23865912*uk_56 + 605597517*uk_57 + 647362863*uk_58 + 352022202*uk_59 + 203*uk_6 + 138081348*uk_60 + 301733316*uk_61 + 20456496*uk_62 + 519083586*uk_63 + 554882454*uk_64 + 301733316*uk_65 + 659343172*uk_66 + 44701232*uk_67 + 1134293762*uk_68 + 1212520918*uk_69 + 217*uk_7 + 659343172*uk_70 + 3030592*uk_71 + 76901272*uk_72 + 82204808*uk_73 + 44701232*uk_74 + 1951369777*uk_75 + 2085947003*uk_76 + 1134293762*uk_77 + 2229805417*uk_78 + 1212520918*uk_79 + 118*uk_8 + 659343172*uk_80 + 250047*uk_81 + 214326*uk_82 + 468342*uk_83 + 31752*uk_84 + 805707*uk_85 + 861273*uk_86 + 468342*uk_87 + 183708*uk_88 + 401436*uk_89 + 2242306609*uk_9 + 27216*uk_90 + 690606*uk_91 + 738234*uk_92 + 401436*uk_93 + 877212*uk_94 + 59472*uk_95 + 1509102*uk_96 + 1613178*uk_97 + 877212*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 154980*uk_100 + 164052*uk_101 + 40824*uk_102 + 2647575*uk_103 + 2802555*uk_104 + 697410*uk_105 + 2966607*uk_106 + 738234*uk_107 + 183708*uk_108 + 8365427*uk_109 + 9612659*uk_11 + 2225286*uk_110 + 494508*uk_111 + 8447845*uk_112 + 8942353*uk_113 + 2225286*uk_114 + 591948*uk_115 + 131544*uk_116 + 2247210*uk_117 + 2378754*uk_118 + 591948*uk_119 + 2557062*uk_12 + 29232*uk_120 + 499380*uk_121 + 528612*uk_122 + 131544*uk_123 + 8531075*uk_124 + 9030455*uk_125 + 2247210*uk_126 + 9559067*uk_127 + 2378754*uk_128 + 591948*uk_129 + 568236*uk_13 + 157464*uk_130 + 34992*uk_131 + 597780*uk_132 + 632772*uk_133 + 157464*uk_134 + 7776*uk_135 + 132840*uk_136 + 140616*uk_137 + 34992*uk_138 + 2269350*uk_139 + 9707365*uk_14 + 2402190*uk_140 + 597780*uk_141 + 2542806*uk_142 + 632772*uk_143 + 157464*uk_144 + 1728*uk_145 + 29520*uk_146 + 31248*uk_147 + 7776*uk_148 + 504300*uk_149 + 10275601*uk_15 + 533820*uk_150 + 132840*uk_151 + 565068*uk_152 + 140616*uk_153 + 34992*uk_154 + 8615125*uk_155 + 9119425*uk_156 + 2269350*uk_157 + 9653245*uk_158 + 2402190*uk_159 + 2557062*uk_16 + 597780*uk_160 + 10218313*uk_161 + 2542806*uk_162 + 632772*uk_163 + 157464*uk_164 + 3969*uk_17 + 12789*uk_18 + 3402*uk_19 + 63*uk_2 + 756*uk_20 + 12915*uk_21 + 13671*uk_22 + 3402*uk_23 + 41209*uk_24 + 10962*uk_25 + 2436*uk_26 + 41615*uk_27 + 44051*uk_28 + 10962*uk_29 + 203*uk_3 + 2916*uk_30 + 648*uk_31 + 11070*uk_32 + 11718*uk_33 + 2916*uk_34 + 144*uk_35 + 2460*uk_36 + 2604*uk_37 + 648*uk_38 + 42025*uk_39 + 54*uk_4 + 44485*uk_40 + 11070*uk_41 + 47089*uk_42 + 11718*uk_43 + 2916*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 455188241627*uk_47 + 121084556886*uk_48 + 26907679308*uk_49 + 12*uk_5 + 459672854845*uk_50 + 486580534153*uk_51 + 121084556886*uk_52 + 187944057*uk_53 + 605597517*uk_54 + 161094906*uk_55 + 35798868*uk_56 + 611563995*uk_57 + 647362863*uk_58 + 161094906*uk_59 + 205*uk_6 + 1951369777*uk_60 + 519083586*uk_61 + 115351908*uk_62 + 1970595095*uk_63 + 2085947003*uk_64 + 519083586*uk_65 + 138081348*uk_66 + 30684744*uk_67 + 524197710*uk_68 + 554882454*uk_69 + 217*uk_7 + 138081348*uk_70 + 6818832*uk_71 + 116488380*uk_72 + 123307212*uk_73 + 30684744*uk_74 + 1990009825*uk_75 + 2106498205*uk_76 + 524197710*uk_77 + 2229805417*uk_78 + 554882454*uk_79 + 54*uk_8 + 138081348*uk_80 + 250047*uk_81 + 805707*uk_82 + 214326*uk_83 + 47628*uk_84 + 813645*uk_85 + 861273*uk_86 + 214326*uk_87 + 2596167*uk_88 + 690606*uk_89 + 2242306609*uk_9 + 153468*uk_90 + 2621745*uk_91 + 2775213*uk_92 + 690606*uk_93 + 183708*uk_94 + 40824*uk_95 + 697410*uk_96 + 738234*uk_97 + 183708*uk_98 + 9072*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 104328*uk_100 + 109368*uk_101 + 102312*uk_102 + 2699487*uk_103 + 2829897*uk_104 + 2647323*uk_105 + 2966607*uk_106 + 2775213*uk_107 + 2596167*uk_108 + 3869893*uk_109 + 7434421*uk_11 + 5003747*uk_110 + 197192*uk_111 + 5102343*uk_112 + 5348833*uk_113 + 5003747*uk_114 + 6469813*uk_115 + 254968*uk_116 + 6597297*uk_117 + 6916007*uk_118 + 6469813*uk_119 + 9612659*uk_12 + 10048*uk_120 + 259992*uk_121 + 272552*uk_122 + 254968*uk_123 + 6727293*uk_124 + 7052283*uk_125 + 6597297*uk_126 + 7392973*uk_127 + 6916007*uk_128 + 6469813*uk_129 + 378824*uk_13 + 8365427*uk_130 + 329672*uk_131 + 8530263*uk_132 + 8942353*uk_133 + 8365427*uk_134 + 12992*uk_135 + 336168*uk_136 + 352408*uk_137 + 329672*uk_138 + 8698347*uk_139 + 9802071*uk_14 + 9118557*uk_140 + 8530263*uk_141 + 9559067*uk_142 + 8942353*uk_143 + 8365427*uk_144 + 512*uk_145 + 13248*uk_146 + 13888*uk_147 + 12992*uk_148 + 342792*uk_149 + 10275601*uk_15 + 359352*uk_150 + 336168*uk_151 + 376712*uk_152 + 352408*uk_153 + 329672*uk_154 + 8869743*uk_155 + 9298233*uk_156 + 8698347*uk_157 + 9747423*uk_158 + 9118557*uk_159 + 9612659*uk_16 + 8530263*uk_160 + 10218313*uk_161 + 9559067*uk_162 + 8942353*uk_163 + 8365427*uk_164 + 3969*uk_17 + 9891*uk_18 + 12789*uk_19 + 63*uk_2 + 504*uk_20 + 13041*uk_21 + 13671*uk_22 + 12789*uk_23 + 24649*uk_24 + 31871*uk_25 + 1256*uk_26 + 32499*uk_27 + 34069*uk_28 + 31871*uk_29 + 157*uk_3 + 41209*uk_30 + 1624*uk_31 + 42021*uk_32 + 44051*uk_33 + 41209*uk_34 + 64*uk_35 + 1656*uk_36 + 1736*uk_37 + 1624*uk_38 + 42849*uk_39 + 203*uk_4 + 44919*uk_40 + 42021*uk_41 + 47089*uk_42 + 44051*uk_43 + 41209*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 352042137613*uk_47 + 455188241627*uk_48 + 17938452872*uk_49 + 8*uk_5 + 464157468063*uk_50 + 486580534153*uk_51 + 455188241627*uk_52 + 187944057*uk_53 + 468368523*uk_54 + 605597517*uk_55 + 23865912*uk_56 + 617530473*uk_57 + 647362863*uk_58 + 605597517*uk_59 + 207*uk_6 + 1167204097*uk_60 + 1509187463*uk_61 + 59475368*uk_62 + 1538925147*uk_63 + 1613269357*uk_64 + 1509187463*uk_65 + 1951369777*uk_66 + 76901272*uk_67 + 1989820413*uk_68 + 2085947003*uk_69 + 217*uk_7 + 1951369777*uk_70 + 3030592*uk_71 + 78416568*uk_72 + 82204808*uk_73 + 76901272*uk_74 + 2029028697*uk_75 + 2127049407*uk_76 + 1989820413*uk_77 + 2229805417*uk_78 + 2085947003*uk_79 + 203*uk_8 + 1951369777*uk_80 + 250047*uk_81 + 623133*uk_82 + 805707*uk_83 + 31752*uk_84 + 821583*uk_85 + 861273*uk_86 + 805707*uk_87 + 1552887*uk_88 + 2007873*uk_89 + 2242306609*uk_9 + 79128*uk_90 + 2047437*uk_91 + 2146347*uk_92 + 2007873*uk_93 + 2596167*uk_94 + 102312*uk_95 + 2647323*uk_96 + 2775213*uk_97 + 2596167*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 105336*uk_100 + 109368*uk_101 + 79128*uk_102 + 2751903*uk_103 + 2857239*uk_104 + 2067219*uk_105 + 2966607*uk_106 + 2146347*uk_107 + 1552887*uk_108 + 1685159*uk_109 + 5635007*uk_11 + 2223277*uk_110 + 113288*uk_111 + 2959649*uk_112 + 3072937*uk_113 + 2223277*uk_114 + 2933231*uk_115 + 149464*uk_116 + 3904747*uk_117 + 4054211*uk_118 + 2933231*uk_119 + 7434421*uk_12 + 7616*uk_120 + 198968*uk_121 + 206584*uk_122 + 149464*uk_123 + 5198039*uk_124 + 5397007*uk_125 + 3904747*uk_126 + 5603591*uk_127 + 4054211*uk_128 + 2933231*uk_129 + 378824*uk_13 + 3869893*uk_130 + 197192*uk_131 + 5151641*uk_132 + 5348833*uk_133 + 3869893*uk_134 + 10048*uk_135 + 262504*uk_136 + 272552*uk_137 + 197192*uk_138 + 6857917*uk_139 + 9896777*uk_14 + 7120421*uk_140 + 5151641*uk_141 + 7392973*uk_142 + 5348833*uk_143 + 3869893*uk_144 + 512*uk_145 + 13376*uk_146 + 13888*uk_147 + 10048*uk_148 + 349448*uk_149 + 10275601*uk_15 + 362824*uk_150 + 262504*uk_151 + 376712*uk_152 + 272552*uk_153 + 197192*uk_154 + 9129329*uk_155 + 9478777*uk_156 + 6857917*uk_157 + 9841601*uk_158 + 7120421*uk_159 + 7434421*uk_16 + 5151641*uk_160 + 10218313*uk_161 + 7392973*uk_162 + 5348833*uk_163 + 3869893*uk_164 + 3969*uk_17 + 7497*uk_18 + 9891*uk_19 + 63*uk_2 + 504*uk_20 + 13167*uk_21 + 13671*uk_22 + 9891*uk_23 + 14161*uk_24 + 18683*uk_25 + 952*uk_26 + 24871*uk_27 + 25823*uk_28 + 18683*uk_29 + 119*uk_3 + 24649*uk_30 + 1256*uk_31 + 32813*uk_32 + 34069*uk_33 + 24649*uk_34 + 64*uk_35 + 1672*uk_36 + 1736*uk_37 + 1256*uk_38 + 43681*uk_39 + 157*uk_4 + 45353*uk_40 + 32813*uk_41 + 47089*uk_42 + 34069*uk_43 + 24649*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 266834486471*uk_47 + 352042137613*uk_48 + 17938452872*uk_49 + 8*uk_5 + 468642081281*uk_50 + 486580534153*uk_51 + 352042137613*uk_52 + 187944057*uk_53 + 355005441*uk_54 + 468368523*uk_55 + 23865912*uk_56 + 623496951*uk_57 + 647362863*uk_58 + 468368523*uk_59 + 209*uk_6 + 670565833*uk_60 + 884696099*uk_61 + 45080056*uk_62 + 1177716463*uk_63 + 1222796519*uk_64 + 884696099*uk_65 + 1167204097*uk_66 + 59475368*uk_67 + 1553793989*uk_68 + 1613269357*uk_69 + 217*uk_7 + 1167204097*uk_70 + 3030592*uk_71 + 79174216*uk_72 + 82204808*uk_73 + 59475368*uk_74 + 2068426393*uk_75 + 2147600609*uk_76 + 1553793989*uk_77 + 2229805417*uk_78 + 1613269357*uk_79 + 157*uk_8 + 1167204097*uk_80 + 250047*uk_81 + 472311*uk_82 + 623133*uk_83 + 31752*uk_84 + 829521*uk_85 + 861273*uk_86 + 623133*uk_87 + 892143*uk_88 + 1177029*uk_89 + 2242306609*uk_9 + 59976*uk_90 + 1566873*uk_91 + 1626849*uk_92 + 1177029*uk_93 + 1552887*uk_94 + 79128*uk_95 + 2067219*uk_96 + 2146347*uk_97 + 1552887*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 106344*uk_100 + 109368*uk_101 + 59976*uk_102 + 2804823*uk_103 + 2884581*uk_104 + 1581867*uk_105 + 2966607*uk_106 + 1626849*uk_107 + 892143*uk_108 + 704969*uk_109 + 4214417*uk_11 + 942599*uk_110 + 63368*uk_111 + 1671331*uk_112 + 1718857*uk_113 + 942599*uk_114 + 1260329*uk_115 + 84728*uk_116 + 2234701*uk_117 + 2298247*uk_118 + 1260329*uk_119 + 5635007*uk_12 + 5696*uk_120 + 150232*uk_121 + 154504*uk_122 + 84728*uk_123 + 3962369*uk_124 + 4075043*uk_125 + 2234701*uk_126 + 4190921*uk_127 + 2298247*uk_128 + 1260329*uk_129 + 378824*uk_13 + 1685159*uk_130 + 113288*uk_131 + 2987971*uk_132 + 3072937*uk_133 + 1685159*uk_134 + 7616*uk_135 + 200872*uk_136 + 206584*uk_137 + 113288*uk_138 + 5297999*uk_139 + 9991483*uk_14 + 5448653*uk_140 + 2987971*uk_141 + 5603591*uk_142 + 3072937*uk_143 + 1685159*uk_144 + 512*uk_145 + 13504*uk_146 + 13888*uk_147 + 7616*uk_148 + 356168*uk_149 + 10275601*uk_15 + 366296*uk_150 + 200872*uk_151 + 376712*uk_152 + 206584*uk_153 + 113288*uk_154 + 9393931*uk_155 + 9661057*uk_156 + 5297999*uk_157 + 9935779*uk_158 + 5448653*uk_159 + 5635007*uk_16 + 2987971*uk_160 + 10218313*uk_161 + 5603591*uk_162 + 3072937*uk_163 + 1685159*uk_164 + 3969*uk_17 + 5607*uk_18 + 7497*uk_19 + 63*uk_2 + 504*uk_20 + 13293*uk_21 + 13671*uk_22 + 7497*uk_23 + 7921*uk_24 + 10591*uk_25 + 712*uk_26 + 18779*uk_27 + 19313*uk_28 + 10591*uk_29 + 89*uk_3 + 14161*uk_30 + 952*uk_31 + 25109*uk_32 + 25823*uk_33 + 14161*uk_34 + 64*uk_35 + 1688*uk_36 + 1736*uk_37 + 952*uk_38 + 44521*uk_39 + 119*uk_4 + 45787*uk_40 + 25109*uk_41 + 47089*uk_42 + 25823*uk_43 + 14161*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 199565288201*uk_47 + 266834486471*uk_48 + 17938452872*uk_49 + 8*uk_5 + 473126694499*uk_50 + 486580534153*uk_51 + 266834486471*uk_52 + 187944057*uk_53 + 265508271*uk_54 + 355005441*uk_55 + 23865912*uk_56 + 629463429*uk_57 + 647362863*uk_58 + 355005441*uk_59 + 211*uk_6 + 375083113*uk_60 + 501515623*uk_61 + 33715336*uk_62 + 889241987*uk_63 + 914528489*uk_64 + 501515623*uk_65 + 670565833*uk_66 + 45080056*uk_67 + 1188986477*uk_68 + 1222796519*uk_69 + 217*uk_7 + 670565833*uk_70 + 3030592*uk_71 + 79931864*uk_72 + 82204808*uk_73 + 45080056*uk_74 + 2108202913*uk_75 + 2168151811*uk_76 + 1188986477*uk_77 + 2229805417*uk_78 + 1222796519*uk_79 + 119*uk_8 + 670565833*uk_80 + 250047*uk_81 + 353241*uk_82 + 472311*uk_83 + 31752*uk_84 + 837459*uk_85 + 861273*uk_86 + 472311*uk_87 + 499023*uk_88 + 667233*uk_89 + 2242306609*uk_9 + 44856*uk_90 + 1183077*uk_91 + 1216719*uk_92 + 667233*uk_93 + 892143*uk_94 + 59976*uk_95 + 1581867*uk_96 + 1626849*uk_97 + 892143*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 107352*uk_100 + 109368*uk_101 + 44856*uk_102 + 2858247*uk_103 + 2911923*uk_104 + 1194291*uk_105 + 2966607*uk_106 + 1216719*uk_107 + 499023*uk_108 + 300763*uk_109 + 3172651*uk_11 + 399521*uk_110 + 35912*uk_111 + 956157*uk_112 + 974113*uk_113 + 399521*uk_114 + 530707*uk_115 + 47704*uk_116 + 1270119*uk_117 + 1293971*uk_118 + 530707*uk_119 + 4214417*uk_12 + 4288*uk_120 + 114168*uk_121 + 116312*uk_122 + 47704*uk_123 + 3039723*uk_124 + 3096807*uk_125 + 1270119*uk_126 + 3154963*uk_127 + 1293971*uk_128 + 530707*uk_129 + 378824*uk_13 + 704969*uk_130 + 63368*uk_131 + 1687173*uk_132 + 1718857*uk_133 + 704969*uk_134 + 5696*uk_135 + 151656*uk_136 + 154504*uk_137 + 63368*uk_138 + 4037841*uk_139 + 10086189*uk_14 + 4113669*uk_140 + 1687173*uk_141 + 4190921*uk_142 + 1718857*uk_143 + 704969*uk_144 + 512*uk_145 + 13632*uk_146 + 13888*uk_147 + 5696*uk_148 + 362952*uk_149 + 10275601*uk_15 + 369768*uk_150 + 151656*uk_151 + 376712*uk_152 + 154504*uk_153 + 63368*uk_154 + 9663597*uk_155 + 9845073*uk_156 + 4037841*uk_157 + 10029957*uk_158 + 4113669*uk_159 + 4214417*uk_16 + 1687173*uk_160 + 10218313*uk_161 + 4190921*uk_162 + 1718857*uk_163 + 704969*uk_164 + 3969*uk_17 + 4221*uk_18 + 5607*uk_19 + 63*uk_2 + 504*uk_20 + 13419*uk_21 + 13671*uk_22 + 5607*uk_23 + 4489*uk_24 + 5963*uk_25 + 536*uk_26 + 14271*uk_27 + 14539*uk_28 + 5963*uk_29 + 67*uk_3 + 7921*uk_30 + 712*uk_31 + 18957*uk_32 + 19313*uk_33 + 7921*uk_34 + 64*uk_35 + 1704*uk_36 + 1736*uk_37 + 712*uk_38 + 45369*uk_39 + 89*uk_4 + 46221*uk_40 + 18957*uk_41 + 47089*uk_42 + 19313*uk_43 + 7921*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 150234542803*uk_47 + 199565288201*uk_48 + 17938452872*uk_49 + 8*uk_5 + 477611307717*uk_50 + 486580534153*uk_51 + 199565288201*uk_52 + 187944057*uk_53 + 199877013*uk_54 + 265508271*uk_55 + 23865912*uk_56 + 635429907*uk_57 + 647362863*uk_58 + 265508271*uk_59 + 213*uk_6 + 212567617*uk_60 + 282365939*uk_61 + 25381208*uk_62 + 675774663*uk_63 + 688465267*uk_64 + 282365939*uk_65 + 375083113*uk_66 + 33715336*uk_67 + 897670821*uk_68 + 914528489*uk_69 + 217*uk_7 + 375083113*uk_70 + 3030592*uk_71 + 80689512*uk_72 + 82204808*uk_73 + 33715336*uk_74 + 2148358257*uk_75 + 2188703013*uk_76 + 897670821*uk_77 + 2229805417*uk_78 + 914528489*uk_79 + 89*uk_8 + 375083113*uk_80 + 250047*uk_81 + 265923*uk_82 + 353241*uk_83 + 31752*uk_84 + 845397*uk_85 + 861273*uk_86 + 353241*uk_87 + 282807*uk_88 + 375669*uk_89 + 2242306609*uk_9 + 33768*uk_90 + 899073*uk_91 + 915957*uk_92 + 375669*uk_93 + 499023*uk_94 + 44856*uk_95 + 1194291*uk_96 + 1216719*uk_97 + 499023*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 108360*uk_100 + 109368*uk_101 + 33768*uk_102 + 2912175*uk_103 + 2939265*uk_104 + 907515*uk_105 + 2966607*uk_106 + 915957*uk_107 + 282807*uk_108 + 148877*uk_109 + 2509709*uk_11 + 188203*uk_110 + 22472*uk_111 + 603935*uk_112 + 609553*uk_113 + 188203*uk_114 + 237917*uk_115 + 28408*uk_116 + 763465*uk_117 + 770567*uk_118 + 237917*uk_119 + 3172651*uk_12 + 3392*uk_120 + 91160*uk_121 + 92008*uk_122 + 28408*uk_123 + 2449925*uk_124 + 2472715*uk_125 + 763465*uk_126 + 2495717*uk_127 + 770567*uk_128 + 237917*uk_129 + 378824*uk_13 + 300763*uk_130 + 35912*uk_131 + 965135*uk_132 + 974113*uk_133 + 300763*uk_134 + 4288*uk_135 + 115240*uk_136 + 116312*uk_137 + 35912*uk_138 + 3097075*uk_139 + 10180895*uk_14 + 3125885*uk_140 + 965135*uk_141 + 3154963*uk_142 + 974113*uk_143 + 300763*uk_144 + 512*uk_145 + 13760*uk_146 + 13888*uk_147 + 4288*uk_148 + 369800*uk_149 + 10275601*uk_15 + 373240*uk_150 + 115240*uk_151 + 376712*uk_152 + 116312*uk_153 + 35912*uk_154 + 9938375*uk_155 + 10030825*uk_156 + 3097075*uk_157 + 10124135*uk_158 + 3125885*uk_159 + 3172651*uk_16 + 965135*uk_160 + 10218313*uk_161 + 3154963*uk_162 + 974113*uk_163 + 300763*uk_164 + 3969*uk_17 + 3339*uk_18 + 4221*uk_19 + 63*uk_2 + 504*uk_20 + 13545*uk_21 + 13671*uk_22 + 4221*uk_23 + 2809*uk_24 + 3551*uk_25 + 424*uk_26 + 11395*uk_27 + 11501*uk_28 + 3551*uk_29 + 53*uk_3 + 4489*uk_30 + 536*uk_31 + 14405*uk_32 + 14539*uk_33 + 4489*uk_34 + 64*uk_35 + 1720*uk_36 + 1736*uk_37 + 536*uk_38 + 46225*uk_39 + 67*uk_4 + 46655*uk_40 + 14405*uk_41 + 47089*uk_42 + 14539*uk_43 + 4489*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 118842250277*uk_47 + 150234542803*uk_48 + 17938452872*uk_49 + 8*uk_5 + 482095920935*uk_50 + 486580534153*uk_51 + 150234542803*uk_52 + 187944057*uk_53 + 158111667*uk_54 + 199877013*uk_55 + 23865912*uk_56 + 641396385*uk_57 + 647362863*uk_58 + 199877013*uk_59 + 215*uk_6 + 133014577*uk_60 + 168150503*uk_61 + 20077672*uk_62 + 539587435*uk_63 + 544606853*uk_64 + 168150503*uk_65 + 212567617*uk_66 + 25381208*uk_67 + 682119965*uk_68 + 688465267*uk_69 + 217*uk_7 + 212567617*uk_70 + 3030592*uk_71 + 81447160*uk_72 + 82204808*uk_73 + 25381208*uk_74 + 2188892425*uk_75 + 2209254215*uk_76 + 682119965*uk_77 + 2229805417*uk_78 + 688465267*uk_79 + 67*uk_8 + 212567617*uk_80 + 250047*uk_81 + 210357*uk_82 + 265923*uk_83 + 31752*uk_84 + 853335*uk_85 + 861273*uk_86 + 265923*uk_87 + 176967*uk_88 + 223713*uk_89 + 2242306609*uk_9 + 26712*uk_90 + 717885*uk_91 + 724563*uk_92 + 223713*uk_93 + 282807*uk_94 + 33768*uk_95 + 907515*uk_96 + 915957*uk_97 + 282807*uk_98 + 4032*uk_99, + uk_0 + 47353*uk_1 + 2983239*uk_10 + 109368*uk_100 + 109368*uk_101 + 26712*uk_102 + 2966607*uk_103 + 2966607*uk_104 + 724563*uk_105 + 2966607*uk_106 + 724563*uk_107 + 176967*uk_108 + 103823*uk_109 + 2225591*uk_11 + 117077*uk_110 + 17672*uk_111 + 479353*uk_112 + 479353*uk_113 + 117077*uk_114 + 132023*uk_115 + 19928*uk_116 + 540547*uk_117 + 540547*uk_118 + 132023*uk_119 + 2509709*uk_12 + 3008*uk_120 + 81592*uk_121 + 81592*uk_122 + 19928*uk_123 + 2213183*uk_124 + 2213183*uk_125 + 540547*uk_126 + 2213183*uk_127 + 540547*uk_128 + 132023*uk_129 + 378824*uk_13 + 148877*uk_130 + 22472*uk_131 + 609553*uk_132 + 609553*uk_133 + 148877*uk_134 + 3392*uk_135 + 92008*uk_136 + 92008*uk_137 + 22472*uk_138 + 2495717*uk_139 + 10275601*uk_14 + 2495717*uk_140 + 609553*uk_141 + 2495717*uk_142 + 609553*uk_143 + 148877*uk_144 + 512*uk_145 + 13888*uk_146 + 13888*uk_147 + 3392*uk_148 + 376712*uk_149 + 10275601*uk_15 + 376712*uk_150 + 92008*uk_151 + 376712*uk_152 + 92008*uk_153 + 22472*uk_154 + 10218313*uk_155 + 10218313*uk_156 + 2495717*uk_157 + 10218313*uk_158 + 2495717*uk_159 + 2509709*uk_16 + 609553*uk_160 + 10218313*uk_161 + 2495717*uk_162 + 609553*uk_163 + 148877*uk_164 + 3969*uk_17 + 2961*uk_18 + 3339*uk_19 + 63*uk_2 + 504*uk_20 + 13671*uk_21 + 13671*uk_22 + 3339*uk_23 + 2209*uk_24 + 2491*uk_25 + 376*uk_26 + 10199*uk_27 + 10199*uk_28 + 2491*uk_29 + 47*uk_3 + 2809*uk_30 + 424*uk_31 + 11501*uk_32 + 11501*uk_33 + 2809*uk_34 + 64*uk_35 + 1736*uk_36 + 1736*uk_37 + 424*uk_38 + 47089*uk_39 + 53*uk_4 + 47089*uk_40 + 11501*uk_41 + 47089*uk_42 + 11501*uk_43 + 2809*uk_44 + 106179944855977*uk_45 + 141265316367*uk_46 + 105388410623*uk_47 + 118842250277*uk_48 + 17938452872*uk_49 + 8*uk_5 + 486580534153*uk_50 + 486580534153*uk_51 + 118842250277*uk_52 + 187944057*uk_53 + 140212233*uk_54 + 158111667*uk_55 + 23865912*uk_56 + 647362863*uk_57 + 647362863*uk_58 + 158111667*uk_59 + 217*uk_6 + 104602777*uk_60 + 117956323*uk_61 + 17804728*uk_62 + 482953247*uk_63 + 482953247*uk_64 + 117956323*uk_65 + 133014577*uk_66 + 20077672*uk_67 + 544606853*uk_68 + 544606853*uk_69 + 217*uk_7 + 133014577*uk_70 + 3030592*uk_71 + 82204808*uk_72 + 82204808*uk_73 + 20077672*uk_74 + 2229805417*uk_75 + 2229805417*uk_76 + 544606853*uk_77 + 2229805417*uk_78 + 544606853*uk_79 + 53*uk_8 + 133014577*uk_80 + 250047*uk_81 + 186543*uk_82 + 210357*uk_83 + 31752*uk_84 + 861273*uk_85 + 861273*uk_86 + 210357*uk_87 + 139167*uk_88 + 156933*uk_89 + 2242306609*uk_9 + 23688*uk_90 + 642537*uk_91 + 642537*uk_92 + 156933*uk_93 + 176967*uk_94 + 26712*uk_95 + 724563*uk_96 + 724563*uk_97 + 176967*uk_98 + 4032*uk_99, + ] + +def sol_165x165(): + return { + uk_0: -QQ(295441,1683)*uk_2 - QQ(175799,1683)*uk_7 + QQ(2401696807,1)*uk_9 - QQ(9606787228,1683)*uk_10 + QQ(9606787228,1683)*uk_15 - QQ(29030443,1683)*uk_17 - QQ(5965893,187)*uk_22 + QQ(262901,99)*uk_42 + QQ(235539209256104,1)*uk_45 - QQ(232597130667529,1683)*uk_46 + QQ(1364372733998209,1683)*uk_51 - QQ(1133600892904,1683)*uk_53 - QQ(172922170104,187)*uk_58 + QQ(249776467928,99)*uk_78 - QQ(2401889209,1683)*uk_81 - QQ(636292759,187)*uk_86 - QQ(1034157281,187)*uk_106 + QQ(10558824289,1683)*uk_161, + uk_1: QQ(4,1683)*uk_2 - QQ(4,1683)*uk_7 - QQ(98072,1)*uk_9 + QQ(96847,1683)*uk_10 - QQ(568087,1683)*uk_15 + QQ(472,1683)*uk_17 + QQ(72,187)*uk_22 - QQ(104,99)*uk_42 - QQ(7216420377,1)*uk_45 - QQ(108808244,1683)*uk_46 - QQ(46106641036,1683)*uk_51 + QQ(17259541,1683)*uk_53 + QQ(1095291,187)*uk_58 - QQ(9936587,99)*uk_78 + QQ(41836,1683)*uk_81 + QQ(10036,187)*uk_86 + QQ(10124,187)*uk_106 - QQ(8,1)*uk_149 - QQ(586156,1683)*uk_161, + uk_3: -QQ(295441,1683)*uk_18 - QQ(175799,1683)*uk_28 + QQ(2401696807,1)*uk_47 - QQ(9606787228,1683)*uk_54 + QQ(9606787228,1683)*uk_64 - QQ(29030443,1683)*uk_82 - QQ(5965893,187)*uk_92 + QQ(262901,99)*uk_127 + QQ(8,1)*uk_149, + uk_4: -QQ(295441,1683)*uk_19 + QQ(1602583,3366)*uk_29 - QQ(175799,1683)*uk_33 - QQ(45670,99)*uk_34 - QQ(76006,187)*uk_38 + QQ(295441,1683)*uk_41 - QQ(45670,99)*uk_44 + QQ(2401696807,1)*uk_48 - QQ(9606787228,1683)*uk_55 + QQ(74452601017,3366)*uk_65 + QQ(9606787228,1683)*uk_69 - QQ(2401696807,99)*uk_70 - QQ(4803393614,187)*uk_74 + QQ(9606787228,1683)*uk_77 - QQ(2401696807,99)*uk_80 - QQ(29030443,1683)*uk_83 + QQ(11596905,374)*uk_93 - QQ(5965893,187)*uk_97 - QQ(769658,33)*uk_98 - QQ(17335370,1683)*uk_102 + QQ(29030443,1683)*uk_105 - QQ(769658,33)*uk_108 + QQ(77314807,3366)*uk_114 + QQ(750229,198)*uk_119 + QQ(72457964,1683)*uk_123 + QQ(11596905,374)*uk_126 + QQ(31304645,306)*uk_128 + QQ(750229,198)*uk_129 - QQ(3191393,99)*uk_134 - QQ(647642,9)*uk_138 - QQ(769658,33)*uk_141 + QQ(262901,99)*uk_142 - QQ(10478626,99)*uk_143 - QQ(3191393,99)*uk_144 - QQ(20480616,187)*uk_148 - QQ(17335370,1683)*uk_151 - QQ(174199750,1683)*uk_153 - QQ(647642,9)*uk_154 + QQ(29030443,1683)*uk_157 + QQ(5965893,187)*uk_159 - QQ(769658,33)*uk_160 - QQ(10478626,99)*uk_163 - QQ(3191393,99)*uk_164, + uk_5: -QQ(295441,1683)*uk_20 - QQ(175799,1683)*uk_37 + QQ(2401696807,1)*uk_49 - QQ(9606787228,1683)*uk_56 + QQ(9606787228,1683)*uk_73 - QQ(29030443,1683)*uk_84 - QQ(5965893,187)*uk_101 + QQ(262901,99)*uk_152, + uk_6: -QQ(295441,1683)*uk_21 - QQ(175799,1683)*uk_40 + QQ(2401696807,1)*uk_50 - QQ(9606787228,1683)*uk_57 + QQ(9606787228,1683)*uk_76 - QQ(29030443,1683)*uk_85 - QQ(5965893,187)*uk_104 + QQ(262901,99)*uk_158, + uk_8: -QQ(295441,1683)*uk_23 - QQ(1602583,3366)*uk_29 + QQ(45670,99)*uk_34 + QQ(76006,187)*uk_38 - QQ(295441,1683)*uk_41 - QQ(175799,1683)*uk_43 + QQ(45670,99)*uk_44 + QQ(2401696807,1)*uk_52 - QQ(9606787228,1683)*uk_59 - QQ(74452601017,3366)*uk_65 + QQ(2401696807,99)*uk_70 + QQ(4803393614,187)*uk_74 - QQ(9606787228,1683)*uk_77 + QQ(9606787228,1683)*uk_79 + QQ(2401696807,99)*uk_80 - QQ(29030443,1683)*uk_87 - QQ(11596905,374)*uk_93 + QQ(769658,33)*uk_98 + QQ(17335370,1683)*uk_102 - QQ(29030443,1683)*uk_105 - QQ(5965893,187)*uk_107 + QQ(769658,33)*uk_108 - QQ(77314807,3366)*uk_114 - QQ(750229,198)*uk_119 - QQ(72457964,1683)*uk_123 - QQ(11596905,374)*uk_126 - QQ(31304645,306)*uk_128 - QQ(750229,198)*uk_129 + QQ(3191393,99)*uk_134 + QQ(647642,9)*uk_138 + QQ(769658,33)*uk_141 + QQ(10478626,99)*uk_143 + QQ(3191393,99)*uk_144 + QQ(20480616,187)*uk_148 + QQ(17335370,1683)*uk_151 + QQ(174199750,1683)*uk_153 + QQ(647642,9)*uk_154 - QQ(29030443,1683)*uk_157 - QQ(5965893,187)*uk_159 + QQ(769658,33)*uk_160 + QQ(262901,99)*uk_162 + QQ(10478626,99)*uk_163 + QQ(3191393,99)*uk_164, + uk_11: QQ(4,1683)*uk_18 - QQ(4,1683)*uk_28 - QQ(98072,1)*uk_47 + QQ(96847,1683)*uk_54 - QQ(568087,1683)*uk_64 + QQ(472,1683)*uk_82 + QQ(72,187)*uk_92 - QQ(104,99)*uk_127, + uk_12: QQ(4,1683)*uk_19 - QQ(31,3366)*uk_29 - QQ(4,1683)*uk_33 + QQ(1,99)*uk_34 + QQ(2,187)*uk_38 - QQ(4,1683)*uk_41 + QQ(1,99)*uk_44 - QQ(98072,1)*uk_48 + QQ(96847,1683)*uk_55 - QQ(1437649,3366)*uk_65 - QQ(568087,1683)*uk_69 + QQ(52402,99)*uk_70 + QQ(120138,187)*uk_74 - QQ(96847,1683)*uk_77 + QQ(52402,99)*uk_80 + QQ(472,1683)*uk_83 - QQ(225,374)*uk_93 + QQ(72,187)*uk_97 + QQ(17,33)*uk_98 + QQ(590,1683)*uk_102 - QQ(472,1683)*uk_105 + QQ(17,33)*uk_108 - QQ(1519,3366)*uk_114 - QQ(13,198)*uk_119 - QQ(1388,1683)*uk_123 - QQ(225,374)*uk_126 - QQ(605,306)*uk_128 - QQ(13,198)*uk_129 + QQ(68,99)*uk_134 + QQ(14,9)*uk_138 + QQ(17,33)*uk_141 - QQ(104,99)*uk_142 + QQ(229,99)*uk_143 + QQ(68,99)*uk_144 + QQ(472,187)*uk_148 + QQ(590,1683)*uk_151 + QQ(4450,1683)*uk_153 + QQ(14,9)*uk_154 - QQ(472,1683)*uk_157 - QQ(72,187)*uk_159 + QQ(17,33)*uk_160 + QQ(229,99)*uk_163 + QQ(68,99)*uk_164, + uk_13: QQ(4,1683)*uk_20 - QQ(4,1683)*uk_37 - QQ(98072,1)*uk_49 + QQ(96847,1683)*uk_56 - QQ(568087,1683)*uk_73 + QQ(472,1683)*uk_84 + QQ(72,187)*uk_101 - QQ(104,99)*uk_152, + uk_14: QQ(4,1683)*uk_21 - QQ(4,1683)*uk_40 - QQ(98072,1)*uk_50 + QQ(96847,1683)*uk_57 - QQ(568087,1683)*uk_76 + QQ(472,1683)*uk_85 + QQ(72,187)*uk_104 - QQ(104,99)*uk_158, + uk_16: QQ(4,1683)*uk_23 + QQ(31,3366)*uk_29 - QQ(1,99)*uk_34 - QQ(2,187)*uk_38 + QQ(4,1683)*uk_41 - QQ(4,1683)*uk_43 - QQ(1,99)*uk_44 - QQ(98072,1)*uk_52 + QQ(96847,1683)*uk_59 + QQ(1437649,3366)*uk_65 - QQ(52402,99)*uk_70 - QQ(120138,187)*uk_74 + QQ(96847,1683)*uk_77 - QQ(568087,1683)*uk_79 - QQ(52402,99)*uk_80 + QQ(472,1683)*uk_87 + QQ(225,374)*uk_93 - QQ(17,33)*uk_98 - QQ(590,1683)*uk_102 + QQ(472,1683)*uk_105 + QQ(72,187)*uk_107 - QQ(17,33)*uk_108 + QQ(1519,3366)*uk_114 + QQ(13,198)*uk_119 + QQ(1388,1683)*uk_123 + QQ(225,374)*uk_126 + QQ(605,306)*uk_128 + QQ(13,198)*uk_129 - QQ(68,99)*uk_134 - QQ(14,9)*uk_138 - QQ(17,33)*uk_141 - QQ(229,99)*uk_143 - QQ(68,99)*uk_144 - QQ(472,187)*uk_148 - QQ(590,1683)*uk_151 - QQ(4450,1683)*uk_153 - QQ(14,9)*uk_154 + QQ(472,1683)*uk_157 + QQ(72,187)*uk_159 - QQ(17,33)*uk_160 - QQ(104,99)*uk_162 - QQ(229,99)*uk_163 - QQ(68,99)*uk_164, + uk_24: -QQ(295441,1683)*uk_88 - QQ(175799,1683)*uk_113, + uk_26: -QQ(295441,1683)*uk_90 - QQ(175799,1683)*uk_122, uk_25: -uk_29 - QQ(295441,1683)*uk_89 - QQ(295441,1683)*uk_93 - QQ(175799,1683)*uk_118 - QQ(175799,1683)*uk_128, + uk_27: -QQ(295441,1683)*uk_91 - QQ(175799,1683)*uk_125 - QQ(4,1)*uk_149, + uk_30: -uk_34 - uk_44 - QQ(295441,1683)*uk_94 - QQ(295441,1683)*uk_98 - QQ(295441,1683)*uk_108 - QQ(175799,1683)*uk_133 - QQ(175799,1683)*uk_143 - QQ(175799,1683)*uk_163, + uk_31: -uk_38 - QQ(295441,1683)*uk_95 - QQ(295441,1683)*uk_102 - QQ(175799,1683)*uk_137 - QQ(175799,1683)*uk_153, + uk_32: -uk_41 - QQ(295441,1683)*uk_96 - QQ(295441,1683)*uk_105 - QQ(175799,1683)*uk_140 + QQ(4,1)*uk_149 - QQ(175799,1683)*uk_159, + uk_35: -QQ(295441,1683)*uk_99 - QQ(175799,1683)*uk_147, + uk_36: -QQ(295441,1683)*uk_100 - QQ(2,1)*uk_149 - QQ(175799,1683)*uk_150, + uk_39: -QQ(295441,1683)*uk_103 - QQ(175799,1683)*uk_156, + uk_60: QQ(4,1683)*uk_88 - QQ(4,1683)*uk_113, + uk_61: -uk_65 + QQ(4,1683)*uk_89 + QQ(4,1683)*uk_93 - QQ(4,1683)*uk_118 - QQ(4,1683)*uk_128, + uk_62: QQ(4,1683)*uk_90 - QQ(4,1683)*uk_122, + uk_63: QQ(4,1683)*uk_91 - QQ(4,1683)*uk_125, + uk_66: -uk_70 - uk_80 + QQ(4,1683)*uk_94 + QQ(4,1683)*uk_98 + QQ(4,1683)*uk_108 - QQ(4,1683)*uk_133 - QQ(4,1683)*uk_143 - QQ(4,1683)*uk_163, + uk_67: -uk_74 + QQ(4,1683)*uk_95 + QQ(4,1683)*uk_102 - QQ(4,1683)*uk_137 - QQ(4,1683)*uk_153, + uk_68: -uk_77 + QQ(4,1683)*uk_96 + QQ(4,1683)*uk_105 - QQ(4,1683)*uk_140 - QQ(4,1683)*uk_159, + uk_71: QQ(4,1683)*uk_99 - QQ(4,1683)*uk_147, + uk_72: QQ(4,1683)*uk_100 - QQ(4,1683)*uk_150, + uk_75: QQ(4,1683)*uk_103 - QQ(4,1683)*uk_156, + uk_109: 0, + uk_110: -uk_114, + uk_111: 0, + uk_112: 0, + uk_115: -uk_119 - uk_129, + uk_116: -uk_123, + uk_117: -uk_126, + uk_120: 0, + uk_121: 0, + uk_124: 0, + uk_130: -uk_134 - uk_144 - uk_164, + uk_131: -uk_138 - uk_154, + uk_132: -uk_141 - uk_160, + uk_135: -uk_148, + uk_136: -uk_151, + uk_139: -uk_157, + uk_145: 0, + uk_146: 0, + uk_155: 0, + } + +def time_eqs_165x165(): + if len(eqs_165x165()) != 165: + raise ValueError("length should be 165") + +def time_solve_lin_sys_165x165(): + eqs = eqs_165x165() + sol = solve_lin_sys(eqs, R_165) + if sol != sol_165x165(): + raise ValueError("Value should be equal") + +def time_verify_sol_165x165(): + eqs = eqs_165x165() + sol = sol_165x165() + zeros = [ eq.compose(sol) for eq in eqs ] + if not all(zero == 0 for zero in zeros): + raise ValueError("All should be 0") + +def time_to_expr_eqs_165x165(): + eqs = eqs_165x165() + assert [ R_165.from_expr(eq.as_expr()) for eq in eqs ] == eqs + +# Benchmark R_49: shows how fast are arithmetics in rational function fields. +F_abc, a, b, c = field("a,b,c", ZZ) +R_49, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49 = ring("k1:50", F_abc) + +def eqs_189x49(): + return [ + -b*k8/a+c*k8/a, + -b*k11/a+c*k11/a, + -b*k10/a+c*k10/a+k2, + -k3-b*k9/a+c*k9/a, + -b*k14/a+c*k14/a, + -b*k15/a+c*k15/a, + -b*k18/a+c*k18/a-k2, + -b*k17/a+c*k17/a, + -b*k16/a+c*k16/a+k4, + -b*k13/a+c*k13/a-b*k21/a+c*k21/a+b*k5/a-c*k5/a, + b*k44/a-c*k44/a, + -b*k45/a+c*k45/a, + -b*k20/a+c*k20/a, + -b*k44/a+c*k44/a, + b*k46/a-c*k46/a, + b**2*k47/a**2-2*b*c*k47/a**2+c**2*k47/a**2, + k3, + -k4, + -b*k12/a+c*k12/a-a*k6/b+c*k6/b, + -b*k19/a+c*k19/a+a*k7/c-b*k7/c, + b*k45/a-c*k45/a, + -b*k46/a+c*k46/a, + -k48+c*k48/a+c*k48/b-c**2*k48/(a*b), + -k49+b*k49/a+b*k49/c-b**2*k49/(a*c), + a*k1/b-c*k1/b, + a*k4/b-c*k4/b, + a*k3/b-c*k3/b+k9, + -k10+a*k2/b-c*k2/b, + a*k7/b-c*k7/b, + -k9, + k11, + b*k12/a-c*k12/a+a*k6/b-c*k6/b, + a*k15/b-c*k15/b, + k10+a*k18/b-c*k18/b, + -k11+a*k17/b-c*k17/b, + a*k16/b-c*k16/b, + -a*k13/b+c*k13/b+a*k21/b-c*k21/b+a*k5/b-c*k5/b, + -a*k44/b+c*k44/b, + a*k45/b-c*k45/b, + a*k14/c-b*k14/c+a*k20/b-c*k20/b, + a*k44/b-c*k44/b, + -a*k46/b+c*k46/b, + -k47+c*k47/a+c*k47/b-c**2*k47/(a*b), + a*k19/b-c*k19/b, + -a*k45/b+c*k45/b, + a*k46/b-c*k46/b, + a**2*k48/b**2-2*a*c*k48/b**2+c**2*k48/b**2, + -k49+a*k49/b+a*k49/c-a**2*k49/(b*c), + k16, + -k17, + -a*k1/c+b*k1/c, + -k16-a*k4/c+b*k4/c, + -a*k3/c+b*k3/c, + k18-a*k2/c+b*k2/c, + b*k19/a-c*k19/a-a*k7/c+b*k7/c, + -a*k6/c+b*k6/c, + -a*k8/c+b*k8/c, + -a*k11/c+b*k11/c+k17, + -a*k10/c+b*k10/c-k18, + -a*k9/c+b*k9/c, + -a*k14/c+b*k14/c-a*k20/b+c*k20/b, + -a*k13/c+b*k13/c+a*k21/c-b*k21/c-a*k5/c+b*k5/c, + a*k44/c-b*k44/c, + -a*k45/c+b*k45/c, + -a*k44/c+b*k44/c, + a*k46/c-b*k46/c, + -k47+b*k47/a+b*k47/c-b**2*k47/(a*c), + -a*k12/c+b*k12/c, + a*k45/c-b*k45/c, + -a*k46/c+b*k46/c, + -k48+a*k48/b+a*k48/c-a**2*k48/(b*c), + a**2*k49/c**2-2*a*b*k49/c**2+b**2*k49/c**2, + k8, + k11, + -k15, + k10-k18, + -k17, + k9, + -k16, + -k29, + k14-k32, + -k21+k23-k31, + -k24-k30, + -k35, + k44, + -k45, + k36, + k13-k23+k39, + -k20+k38, + k25+k37, + b*k26/a-c*k26/a-k34+k42, + -2*k44, + k45, + k46, + b*k47/a-c*k47/a, + k41, + k44, + -k46, + -b*k47/a+c*k47/a, + k12+k24, + -k19-k25, + -a*k27/b+c*k27/b-k33, + k45, + -k46, + -a*k48/b+c*k48/b, + a*k28/c-b*k28/c+k40, + -k45, + k46, + a*k48/b-c*k48/b, + a*k49/c-b*k49/c, + -a*k49/c+b*k49/c, + -k1, + -k4, + -k3, + k15, + k18-k2, + k17, + k16, + k22, + k25-k7, + k24+k30, + k21+k23-k31, + k28, + -k44, + k45, + -k30-k6, + k20+k32, + k27+b*k33/a-c*k33/a, + k44, + -k46, + -b*k47/a+c*k47/a, + -k36, + k31-k39-k5, + -k32-k38, + k19-k37, + k26-a*k34/b+c*k34/b-k42, + k44, + -2*k45, + k46, + a*k48/b-c*k48/b, + a*k35/c-b*k35/c-k41, + -k44, + k46, + b*k47/a-c*k47/a, + -a*k49/c+b*k49/c, + -k40, + k45, + -k46, + -a*k48/b+c*k48/b, + a*k49/c-b*k49/c, + k1, + k4, + k3, + -k8, + -k11, + -k10+k2, + -k9, + k37+k7, + -k14-k38, + -k22, + -k25-k37, + -k24+k6, + -k13-k23+k39, + -k28+b*k40/a-c*k40/a, + k44, + -k45, + -k27, + -k44, + k46, + b*k47/a-c*k47/a, + k29, + k32+k38, + k31-k39+k5, + -k12+k30, + k35-a*k41/b+c*k41/b, + -k44, + k45, + -k26+k34+a*k42/c-b*k42/c, + k44, + k45, + -2*k46, + -b*k47/a+c*k47/a, + -a*k48/b+c*k48/b, + a*k49/c-b*k49/c, + k33, + -k45, + k46, + a*k48/b-c*k48/b, + -a*k49/c+b*k49/c, + ] + +def sol_189x49(): + return { + k49: 0, k48: 0, k47: 0, k46: 0, k45: 0, k44: 0, k41: 0, k40: 0, + k38: 0, k37: 0, k36: 0, k35: 0, k33: 0, k32: 0, k30: 0, k29: 0, + k28: 0, k27: 0, k25: 0, k24: 0, k22: 0, k21: 0, k20: 0, k19: 0, + k18: 0, k17: 0, k16: 0, k15: 0, k14: 0, k13: 0, k12: 0, k11: 0, + k10: 0, k9: 0, k8: 0, k7: 0, k6: 0, k5: 0, k4: 0, k3: 0, + k2: 0, k1: 0, + k34: b/c*k42, + k31: k39, + k26: a/c*k42, + k23: k39, + } + +def time_eqs_189x49(): + if len(eqs_189x49()) != 189: + raise ValueError("Length should be equal to 189") + +def time_solve_lin_sys_189x49(): + eqs = eqs_189x49() + sol = solve_lin_sys(eqs, R_49) + if sol != sol_189x49(): + raise ValueError("Values should be equal") + +def time_verify_sol_189x49(): + eqs = eqs_189x49() + sol = sol_189x49() + zeros = [ eq.compose(sol) for eq in eqs ] + assert all(zero == 0 for zero in zeros) + +def time_to_expr_eqs_189x49(): + eqs = eqs_189x49() + assert [ R_49.from_expr(eq.as_expr()) for eq in eqs ] == eqs + +# Benchmark R_8: shows how fast polynomial GCDs are computed. + +F_a5_5, a_11, a_12, a_13, a_14, a_21, a_22, a_23, a_24, a_31, a_32, a_33, a_34, a_41, a_42, a_43, a_44 = field("a_(1:5)(1:5)", ZZ) +R_8, x0, x1, x2, x3, x4, x5, x6, x7 = ring("x:8", F_a5_5) + +def eqs_10x8(): + return [ + (a_33*a_34 + a_33*a_44 + a_43*a_44)*x3 + (a_33*a_34 + a_33*a_44 + a_43*a_44)*x4 + (a_12*a_34 + a_12*a_44 + a_22*a_34 + a_22*a_44)*x5 + (a_12*a_44 + a_22*a_44)*x6 + (a_12*a_33 + a_22*a_33)*x7 - a_12*a_33 - a_12*a_43 - a_22*a_33 - a_22*a_43, + (a_33 + a_34 + a_43 + a_44)*x3 + (a_33 + a_34 + a_43 + a_44)*x4 + (a_12 + a_22 + a_34 + a_44)*x5 + (a_12 + a_22 + a_44)*x6 + (a_12 + a_22 + a_33)*x7 - a_12 - a_22 - a_33 - a_43, + x3 + x4 + x5 + x6 + x7 - 1, + (a_12*a_33*a_34 + a_12*a_33*a_44 + a_12*a_43*a_44 + a_22*a_33*a_34 + a_22*a_33*a_44 + a_22*a_43*a_44)*x0 + (a_22*a_33*a_34 + a_22*a_33*a_44 + a_22*a_43*a_44)*x1 + (a_12*a_33*a_34 + a_12*a_33*a_44 + a_12*a_43*a_44 + a_22*a_33*a_34 + a_22*a_33*a_44 + a_22*a_43*a_44)*x2 + (a_11*a_33*a_34 + a_11*a_33*a_44 + a_11*a_43*a_44 + a_31*a_33*a_34 + a_31*a_33*a_44 + a_31*a_43*a_44)*x3 + (a_11*a_33*a_34 + a_11*a_33*a_44 + a_11*a_43*a_44 + a_21*a_33*a_34 + a_21*a_33*a_44 + a_21*a_43*a_44 + a_31*a_33*a_34 + a_31*a_33*a_44 + a_31*a_43*a_44)*x4 + (a_11*a_12*a_34 + a_11*a_12*a_44 + a_11*a_22*a_34 + a_11*a_22*a_44 + a_12*a_31*a_34 + a_12*a_31*a_44 + a_21*a_22*a_34 + a_21*a_22*a_44 + a_22*a_31*a_34 + a_22*a_31*a_44)*x5 + (a_11*a_12*a_44 + a_11*a_22*a_44 + a_12*a_31*a_44 + a_21*a_22*a_44 + a_22*a_31*a_44)*x6 + (a_11*a_12*a_33 + a_11*a_22*a_33 + a_12*a_31*a_33 + a_21*a_22*a_33 + a_22*a_31*a_33)*x7 - a_11*a_12*a_33 - a_11*a_12*a_43 - a_11*a_22*a_33 - a_11*a_22*a_43 - a_12*a_31*a_33 - a_12*a_31*a_43 - a_21*a_22*a_33 - a_21*a_22*a_43 - a_22*a_31*a_33 - a_22*a_31*a_43, + (a_12*a_33 + a_12*a_34 + a_12*a_43 + a_12*a_44 + a_22*a_33 + a_22*a_34 + a_22*a_43 + a_22*a_44 + a_33*a_34 + a_33*a_44 + a_43*a_44)*x0 + (a_22*a_33 + a_22*a_34 + a_22*a_43 + a_22*a_44 + a_33*a_34 + a_33*a_44 + a_43*a_44)*x1 + (a_12*a_33 + a_12*a_34 + a_12*a_43 + a_12*a_44 + a_22*a_33 + a_22*a_34 + a_22*a_43 + a_22*a_44 + a_33*a_34 + a_33*a_44 + a_43*a_44)*x2 + (a_11*a_33 + a_11*a_34 + a_11*a_43 + a_11*a_44 + a_31*a_33 + a_31*a_34 + a_31*a_43 + a_31*a_44 + a_33*a_34 + a_33*a_44 + a_43*a_44)*x3 + (a_11*a_33 + a_11*a_34 + a_11*a_43 + a_11*a_44 + a_21*a_33 + a_21*a_34 + a_21*a_43 + a_21*a_44 + a_31*a_33 + a_31*a_34 + a_31*a_43 + a_31*a_44 + a_33*a_34 + a_33*a_44 + a_43*a_44)*x4 + (a_11*a_12 + a_11*a_22 + a_11*a_34 + a_11*a_44 + a_12*a_31 + a_12*a_34 + a_12*a_44 + a_21*a_22 + a_21*a_34 + a_21*a_44 + a_22*a_31 + a_22*a_34 + a_22*a_44 + a_31*a_34 + a_31*a_44)*x5 + (a_11*a_12 + a_11*a_22 + a_11*a_44 + a_12*a_31 + a_12*a_44 + a_21*a_22 + a_21*a_44 + a_22*a_31 + a_22*a_44 + a_31*a_44)*x6 + (a_11*a_12 + a_11*a_22 + a_11*a_33 + a_12*a_31 + a_12*a_33 + a_21*a_22 + a_21*a_33 + a_22*a_31 + a_22*a_33 + a_31*a_33)*x7 - a_11*a_12 - a_11*a_22 - a_11*a_33 - a_11*a_43 - a_12*a_31 - a_12*a_33 - a_12*a_43 - a_21*a_22 - a_21*a_33 - a_21*a_43 - a_22*a_31 - a_22*a_33 - a_22*a_43 - a_31*a_33 - a_31*a_43, + (a_12 + a_22 + a_33 + a_34 + a_43 + a_44)*x0 + (a_22 + a_33 + a_34 + a_43 + a_44)*x1 + (a_12 + a_22 + a_33 + a_34 + a_43 + a_44)*x2 + (a_11 + a_31 + a_33 + a_34 + a_43 + a_44)*x3 + (a_11 + a_21 + a_31 + a_33 + a_34 + a_43 + a_44)*x4 + (a_11 + a_12 + a_21 + a_22 + a_31 + a_34 + a_44)*x5 + (a_11 + a_12 + a_21 + a_22 + a_31 + a_44)*x6 + (a_11 + a_12 + a_21 + a_22 + a_31 + a_33)*x7 - a_11 - a_12 - a_21 - a_22 - a_31 - a_33 - a_43, + x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7 - 1, + (a_12*a_34 + a_12*a_44 + a_22*a_34 + a_22*a_44)*x2 + (a_31*a_34 + a_31*a_44)*x3 + (a_31*a_34 + a_31*a_44)*x4 + (a_12*a_31 + a_22*a_31)*x7 - a_12*a_31 - a_22*a_31, + (a_12 + a_22 + a_34 + a_44)*x2 + a_31*x3 + a_31*x4 + a_31*x7 - a_31, + x2, + ] + +def sol_10x8(): + return { + x0: -a_21/a_12*x4, + x1: a_21/a_12*x4, + x2: 0, + x3: -x4, + x5: a_43/a_34, + x6: -a_43/a_34, + x7: 1, + } + +def time_eqs_10x8(): + if len(eqs_10x8()) != 10: + raise ValueError("Value should be equal to 10") + +def time_solve_lin_sys_10x8(): + eqs = eqs_10x8() + sol = solve_lin_sys(eqs, R_8) + if sol != sol_10x8(): + raise ValueError("Values should be equal") + +def time_verify_sol_10x8(): + eqs = eqs_10x8() + sol = sol_10x8() + zeros = [ eq.compose(sol) for eq in eqs ] + if not all(zero == 0 for zero in zeros): + raise ValueError("All values in zero should be 0") + +def time_to_expr_eqs_10x8(): + eqs = eqs_10x8() + assert [ R_8.from_expr(eq.as_expr()) for eq in eqs ] == eqs diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/compatibility.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..eb239d282a738d1e5611a2249d313ff1d3b7671c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/compatibility.py @@ -0,0 +1,1152 @@ +"""Compatibility interface between dense and sparse polys. """ + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from sympy.core.expr import Expr + from sympy.polys.domains.domain import Domain + from sympy.polys.orderings import MonomialOrder + from sympy.polys.rings import PolyElement + +from sympy.polys.densearith import dup_add_term +from sympy.polys.densearith import dmp_add_term +from sympy.polys.densearith import dup_sub_term +from sympy.polys.densearith import dmp_sub_term +from sympy.polys.densearith import dup_mul_term +from sympy.polys.densearith import dmp_mul_term +from sympy.polys.densearith import dup_add_ground +from sympy.polys.densearith import dmp_add_ground +from sympy.polys.densearith import dup_sub_ground +from sympy.polys.densearith import dmp_sub_ground +from sympy.polys.densearith import dup_mul_ground +from sympy.polys.densearith import dmp_mul_ground +from sympy.polys.densearith import dup_quo_ground +from sympy.polys.densearith import dmp_quo_ground +from sympy.polys.densearith import dup_exquo_ground +from sympy.polys.densearith import dmp_exquo_ground +from sympy.polys.densearith import dup_lshift +from sympy.polys.densearith import dup_rshift +from sympy.polys.densearith import dup_abs +from sympy.polys.densearith import dmp_abs +from sympy.polys.densearith import dup_neg +from sympy.polys.densearith import dmp_neg +from sympy.polys.densearith import dup_add +from sympy.polys.densearith import dmp_add +from sympy.polys.densearith import dup_sub +from sympy.polys.densearith import dmp_sub +from sympy.polys.densearith import dup_add_mul +from sympy.polys.densearith import dmp_add_mul +from sympy.polys.densearith import dup_sub_mul +from sympy.polys.densearith import dmp_sub_mul +from sympy.polys.densearith import dup_mul +from sympy.polys.densearith import dmp_mul +from sympy.polys.densearith import dup_sqr +from sympy.polys.densearith import dmp_sqr +from sympy.polys.densearith import dup_pow +from sympy.polys.densearith import dmp_pow +from sympy.polys.densearith import dup_pdiv +from sympy.polys.densearith import dup_prem +from sympy.polys.densearith import dup_pquo +from sympy.polys.densearith import dup_pexquo +from sympy.polys.densearith import dmp_pdiv +from sympy.polys.densearith import dmp_prem +from sympy.polys.densearith import dmp_pquo +from sympy.polys.densearith import dmp_pexquo +from sympy.polys.densearith import dup_rr_div +from sympy.polys.densearith import dmp_rr_div +from sympy.polys.densearith import dup_ff_div +from sympy.polys.densearith import dmp_ff_div +from sympy.polys.densearith import dup_div +from sympy.polys.densearith import dup_rem +from sympy.polys.densearith import dup_quo +from sympy.polys.densearith import dup_exquo +from sympy.polys.densearith import dmp_div +from sympy.polys.densearith import dmp_rem +from sympy.polys.densearith import dmp_quo +from sympy.polys.densearith import dmp_exquo +from sympy.polys.densearith import dup_max_norm +from sympy.polys.densearith import dmp_max_norm +from sympy.polys.densearith import dup_l1_norm +from sympy.polys.densearith import dmp_l1_norm +from sympy.polys.densearith import dup_l2_norm_squared +from sympy.polys.densearith import dmp_l2_norm_squared +from sympy.polys.densearith import dup_expand +from sympy.polys.densearith import dmp_expand +from sympy.polys.densebasic import dup_LC +from sympy.polys.densebasic import dmp_LC +from sympy.polys.densebasic import dup_TC +from sympy.polys.densebasic import dmp_TC +from sympy.polys.densebasic import dmp_ground_LC +from sympy.polys.densebasic import dmp_ground_TC +from sympy.polys.densebasic import dup_degree +from sympy.polys.densebasic import dmp_degree +from sympy.polys.densebasic import dmp_degree_in +from sympy.polys.densebasic import dmp_to_dict +from sympy.polys.densetools import dup_integrate +from sympy.polys.densetools import dmp_integrate +from sympy.polys.densetools import dmp_integrate_in +from sympy.polys.densetools import dup_diff +from sympy.polys.densetools import dmp_diff +from sympy.polys.densetools import dmp_diff_in +from sympy.polys.densetools import dup_eval +from sympy.polys.densetools import dmp_eval +from sympy.polys.densetools import dmp_eval_in +from sympy.polys.densetools import dmp_eval_tail +from sympy.polys.densetools import dmp_diff_eval_in +from sympy.polys.densetools import dup_trunc +from sympy.polys.densetools import dmp_trunc +from sympy.polys.densetools import dmp_ground_trunc +from sympy.polys.densetools import dup_monic +from sympy.polys.densetools import dmp_ground_monic +from sympy.polys.densetools import dup_content +from sympy.polys.densetools import dmp_ground_content +from sympy.polys.densetools import dup_primitive +from sympy.polys.densetools import dmp_ground_primitive +from sympy.polys.densetools import dup_extract +from sympy.polys.densetools import dmp_ground_extract +from sympy.polys.densetools import dup_real_imag +from sympy.polys.densetools import dup_mirror +from sympy.polys.densetools import dup_scale +from sympy.polys.densetools import dup_shift +from sympy.polys.densetools import dmp_shift +from sympy.polys.densetools import dup_transform +from sympy.polys.densetools import dup_compose +from sympy.polys.densetools import dmp_compose +from sympy.polys.densetools import dup_decompose +from sympy.polys.densetools import dmp_lift +from sympy.polys.densetools import dup_sign_variations +from sympy.polys.densetools import dup_clear_denoms +from sympy.polys.densetools import dmp_clear_denoms +from sympy.polys.densetools import dup_revert +from sympy.polys.euclidtools import dup_half_gcdex +from sympy.polys.euclidtools import dmp_half_gcdex +from sympy.polys.euclidtools import dup_gcdex +from sympy.polys.euclidtools import dmp_gcdex +from sympy.polys.euclidtools import dup_invert +from sympy.polys.euclidtools import dmp_invert +from sympy.polys.euclidtools import dup_euclidean_prs +from sympy.polys.euclidtools import dmp_euclidean_prs +from sympy.polys.euclidtools import dup_primitive_prs +from sympy.polys.euclidtools import dmp_primitive_prs +from sympy.polys.euclidtools import dup_inner_subresultants +from sympy.polys.euclidtools import dup_subresultants +from sympy.polys.euclidtools import dup_prs_resultant +from sympy.polys.euclidtools import dup_resultant +from sympy.polys.euclidtools import dmp_inner_subresultants +from sympy.polys.euclidtools import dmp_subresultants +from sympy.polys.euclidtools import dmp_prs_resultant +from sympy.polys.euclidtools import dmp_zz_modular_resultant +from sympy.polys.euclidtools import dmp_zz_collins_resultant +from sympy.polys.euclidtools import dmp_qq_collins_resultant +from sympy.polys.euclidtools import dmp_resultant +from sympy.polys.euclidtools import dup_discriminant +from sympy.polys.euclidtools import dmp_discriminant +from sympy.polys.euclidtools import dup_rr_prs_gcd +from sympy.polys.euclidtools import dup_ff_prs_gcd +from sympy.polys.euclidtools import dmp_rr_prs_gcd +from sympy.polys.euclidtools import dmp_ff_prs_gcd +from sympy.polys.euclidtools import dup_zz_heu_gcd +from sympy.polys.euclidtools import dmp_zz_heu_gcd +from sympy.polys.euclidtools import dup_qq_heu_gcd +from sympy.polys.euclidtools import dmp_qq_heu_gcd +from sympy.polys.euclidtools import dup_inner_gcd +from sympy.polys.euclidtools import dmp_inner_gcd +from sympy.polys.euclidtools import dup_gcd +from sympy.polys.euclidtools import dmp_gcd +from sympy.polys.euclidtools import dup_rr_lcm +from sympy.polys.euclidtools import dup_ff_lcm +from sympy.polys.euclidtools import dup_lcm +from sympy.polys.euclidtools import dmp_rr_lcm +from sympy.polys.euclidtools import dmp_ff_lcm +from sympy.polys.euclidtools import dmp_lcm +from sympy.polys.euclidtools import dmp_content +from sympy.polys.euclidtools import dmp_primitive +from sympy.polys.euclidtools import dup_cancel +from sympy.polys.euclidtools import dmp_cancel +from sympy.polys.factortools import dup_trial_division +from sympy.polys.factortools import dmp_trial_division +from sympy.polys.factortools import dup_zz_mignotte_bound +from sympy.polys.factortools import dmp_zz_mignotte_bound +from sympy.polys.factortools import dup_zz_hensel_step +from sympy.polys.factortools import dup_zz_hensel_lift +from sympy.polys.factortools import dup_zz_zassenhaus +from sympy.polys.factortools import dup_zz_irreducible_p +from sympy.polys.factortools import dup_cyclotomic_p +from sympy.polys.factortools import dup_zz_cyclotomic_poly +from sympy.polys.factortools import dup_zz_cyclotomic_factor +from sympy.polys.factortools import dup_zz_factor_sqf +from sympy.polys.factortools import dup_zz_factor +from sympy.polys.factortools import dmp_zz_wang_non_divisors +from sympy.polys.factortools import dmp_zz_wang_lead_coeffs +from sympy.polys.factortools import dup_zz_diophantine +from sympy.polys.factortools import dmp_zz_diophantine +from sympy.polys.factortools import dmp_zz_wang_hensel_lifting +from sympy.polys.factortools import dmp_zz_wang +from sympy.polys.factortools import dmp_zz_factor +from sympy.polys.factortools import dup_qq_i_factor +from sympy.polys.factortools import dup_zz_i_factor +from sympy.polys.factortools import dmp_qq_i_factor +from sympy.polys.factortools import dmp_zz_i_factor +from sympy.polys.factortools import dup_ext_factor +from sympy.polys.factortools import dmp_ext_factor +from sympy.polys.factortools import dup_gf_factor +from sympy.polys.factortools import dmp_gf_factor +from sympy.polys.factortools import dup_factor_list +from sympy.polys.factortools import dup_factor_list_include +from sympy.polys.factortools import dmp_factor_list +from sympy.polys.factortools import dmp_factor_list_include +from sympy.polys.factortools import dup_irreducible_p +from sympy.polys.factortools import dmp_irreducible_p +from sympy.polys.rootisolation import dup_sturm +from sympy.polys.rootisolation import dup_root_upper_bound +from sympy.polys.rootisolation import dup_root_lower_bound +from sympy.polys.rootisolation import dup_step_refine_real_root +from sympy.polys.rootisolation import dup_inner_refine_real_root +from sympy.polys.rootisolation import dup_outer_refine_real_root +from sympy.polys.rootisolation import dup_refine_real_root +from sympy.polys.rootisolation import dup_inner_isolate_real_roots +from sympy.polys.rootisolation import dup_inner_isolate_positive_roots +from sympy.polys.rootisolation import dup_inner_isolate_negative_roots +from sympy.polys.rootisolation import dup_isolate_real_roots_sqf +from sympy.polys.rootisolation import dup_isolate_real_roots +from sympy.polys.rootisolation import dup_isolate_real_roots_list +from sympy.polys.rootisolation import dup_count_real_roots +from sympy.polys.rootisolation import dup_count_complex_roots +from sympy.polys.rootisolation import dup_isolate_complex_roots_sqf +from sympy.polys.rootisolation import dup_isolate_all_roots_sqf +from sympy.polys.rootisolation import dup_isolate_all_roots + +from sympy.polys.sqfreetools import ( + dup_sqf_p, dmp_sqf_p, dmp_norm, dup_sqf_norm, dmp_sqf_norm, + dup_gf_sqf_part, dmp_gf_sqf_part, dup_sqf_part, dmp_sqf_part, + dup_gf_sqf_list, dmp_gf_sqf_list, dup_sqf_list, dup_sqf_list_include, + dmp_sqf_list, dmp_sqf_list_include, dup_gff_list, dmp_gff_list) + +from sympy.polys.galoistools import ( + gf_degree, gf_LC, gf_TC, gf_strip, gf_from_dict, + gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground, + gf_mul_ground, gf_quo_ground, gf_add, gf_sub, gf_mul, gf_sqr, gf_add_mul, gf_sub_mul, + gf_expand, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_pow, gf_pow_mod, + gf_gcd, gf_lcm, gf_cofactors, gf_gcdex, gf_monic, gf_diff, gf_eval, gf_multi_eval, + gf_compose, gf_compose_mod, gf_trace_map, gf_random, gf_irreducible, gf_irred_p_ben_or, + gf_irred_p_rabin, gf_irreducible_p, gf_sqf_p, gf_sqf_part, gf_Qmatrix, + gf_berlekamp, gf_ddf_zassenhaus, gf_edf_zassenhaus, gf_ddf_shoup, gf_edf_shoup, + gf_zassenhaus, gf_shoup, gf_factor_sqf, gf_factor) + +from sympy.utilities import public + +@public +class IPolys: + + gens: tuple[PolyElement, ...] + symbols: tuple[Expr, ...] + ngens: int + domain: Domain + order: MonomialOrder + + def drop(self, gen): + pass + + def clone(self, symbols=None, domain=None, order=None): + pass + + def to_ground(self): + pass + + def ground_new(self, element): + pass + + def domain_new(self, element): + pass + + def from_dict(self, d): + pass + + def wrap(self, element): + from sympy.polys.rings import PolyElement + if isinstance(element, PolyElement): + if element.ring == self: + return element + else: + raise NotImplementedError("domain conversions") + else: + return self.ground_new(element) + + def to_dense(self, element): + return self.wrap(element).to_dense() + + def from_dense(self, element): + return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain)) + + def dup_add_term(self, f, c, i): + return self.from_dense(dup_add_term(self.to_dense(f), c, i, self.domain)) + def dmp_add_term(self, f, c, i): + return self.from_dense(dmp_add_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + def dup_sub_term(self, f, c, i): + return self.from_dense(dup_sub_term(self.to_dense(f), c, i, self.domain)) + def dmp_sub_term(self, f, c, i): + return self.from_dense(dmp_sub_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + def dup_mul_term(self, f, c, i): + return self.from_dense(dup_mul_term(self.to_dense(f), c, i, self.domain)) + def dmp_mul_term(self, f, c, i): + return self.from_dense(dmp_mul_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + + def dup_add_ground(self, f, c): + return self.from_dense(dup_add_ground(self.to_dense(f), c, self.domain)) + def dmp_add_ground(self, f, c): + return self.from_dense(dmp_add_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_sub_ground(self, f, c): + return self.from_dense(dup_sub_ground(self.to_dense(f), c, self.domain)) + def dmp_sub_ground(self, f, c): + return self.from_dense(dmp_sub_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_mul_ground(self, f, c): + return self.from_dense(dup_mul_ground(self.to_dense(f), c, self.domain)) + def dmp_mul_ground(self, f, c): + return self.from_dense(dmp_mul_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_quo_ground(self, f, c): + return self.from_dense(dup_quo_ground(self.to_dense(f), c, self.domain)) + def dmp_quo_ground(self, f, c): + return self.from_dense(dmp_quo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_exquo_ground(self, f, c): + return self.from_dense(dup_exquo_ground(self.to_dense(f), c, self.domain)) + def dmp_exquo_ground(self, f, c): + return self.from_dense(dmp_exquo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + + def dup_lshift(self, f, n): + return self.from_dense(dup_lshift(self.to_dense(f), n, self.domain)) + def dup_rshift(self, f, n): + return self.from_dense(dup_rshift(self.to_dense(f), n, self.domain)) + + def dup_abs(self, f): + return self.from_dense(dup_abs(self.to_dense(f), self.domain)) + def dmp_abs(self, f): + return self.from_dense(dmp_abs(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_neg(self, f): + return self.from_dense(dup_neg(self.to_dense(f), self.domain)) + def dmp_neg(self, f): + return self.from_dense(dmp_neg(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_add(self, f, g): + return self.from_dense(dup_add(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_add(self, f, g): + return self.from_dense(dmp_add(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_sub(self, f, g): + return self.from_dense(dup_sub(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_sub(self, f, g): + return self.from_dense(dmp_sub(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_add_mul(self, f, g, h): + return self.from_dense(dup_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) + def dmp_add_mul(self, f, g, h): + return self.from_dense(dmp_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) + def dup_sub_mul(self, f, g, h): + return self.from_dense(dup_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) + def dmp_sub_mul(self, f, g, h): + return self.from_dense(dmp_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) + + def dup_mul(self, f, g): + return self.from_dense(dup_mul(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_mul(self, f, g): + return self.from_dense(dmp_mul(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_sqr(self, f): + return self.from_dense(dup_sqr(self.to_dense(f), self.domain)) + def dmp_sqr(self, f): + return self.from_dense(dmp_sqr(self.to_dense(f), self.ngens-1, self.domain)) + def dup_pow(self, f, n): + return self.from_dense(dup_pow(self.to_dense(f), n, self.domain)) + def dmp_pow(self, f, n): + return self.from_dense(dmp_pow(self.to_dense(f), n, self.ngens-1, self.domain)) + + def dup_pdiv(self, f, g): + q, r = dup_pdiv(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_prem(self, f, g): + return self.from_dense(dup_prem(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_pquo(self, f, g): + return self.from_dense(dup_pquo(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_pexquo(self, f, g): + return self.from_dense(dup_pexquo(self.to_dense(f), self.to_dense(g), self.domain)) + + def dmp_pdiv(self, f, g): + q, r = dmp_pdiv(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_prem(self, f, g): + return self.from_dense(dmp_prem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_pquo(self, f, g): + return self.from_dense(dmp_pquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_pexquo(self, f, g): + return self.from_dense(dmp_pexquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_rr_div(self, f, g): + q, r = dup_rr_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_rr_div(self, f, g): + q, r = dmp_rr_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_ff_div(self, f, g): + q, r = dup_ff_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_ff_div(self, f, g): + q, r = dmp_ff_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + + def dup_div(self, f, g): + q, r = dup_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_rem(self, f, g): + return self.from_dense(dup_rem(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_quo(self, f, g): + return self.from_dense(dup_quo(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_exquo(self, f, g): + return self.from_dense(dup_exquo(self.to_dense(f), self.to_dense(g), self.domain)) + + def dmp_div(self, f, g): + q, r = dmp_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_rem(self, f, g): + return self.from_dense(dmp_rem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_quo(self, f, g): + return self.from_dense(dmp_quo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_exquo(self, f, g): + return self.from_dense(dmp_exquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_max_norm(self, f): + return dup_max_norm(self.to_dense(f), self.domain) + def dmp_max_norm(self, f): + return dmp_max_norm(self.to_dense(f), self.ngens-1, self.domain) + + def dup_l1_norm(self, f): + return dup_l1_norm(self.to_dense(f), self.domain) + def dmp_l1_norm(self, f): + return dmp_l1_norm(self.to_dense(f), self.ngens-1, self.domain) + + def dup_l2_norm_squared(self, f): + return dup_l2_norm_squared(self.to_dense(f), self.domain) + def dmp_l2_norm_squared(self, f): + return dmp_l2_norm_squared(self.to_dense(f), self.ngens-1, self.domain) + + def dup_expand(self, polys): + return self.from_dense(dup_expand(list(map(self.to_dense, polys)), self.domain)) + def dmp_expand(self, polys): + return self.from_dense(dmp_expand(list(map(self.to_dense, polys)), self.ngens-1, self.domain)) + + def dup_LC(self, f): + return dup_LC(self.to_dense(f), self.domain) + def dmp_LC(self, f): + LC = dmp_LC(self.to_dense(f), self.domain) + if isinstance(LC, list): + return self[1:].from_dense(LC) + else: + return LC + def dup_TC(self, f): + return dup_TC(self.to_dense(f), self.domain) + def dmp_TC(self, f): + TC = dmp_TC(self.to_dense(f), self.domain) + if isinstance(TC, list): + return self[1:].from_dense(TC) + else: + return TC + + def dmp_ground_LC(self, f): + return dmp_ground_LC(self.to_dense(f), self.ngens-1, self.domain) + def dmp_ground_TC(self, f): + return dmp_ground_TC(self.to_dense(f), self.ngens-1, self.domain) + + def dup_degree(self, f): + return dup_degree(self.to_dense(f)) + def dmp_degree(self, f): + return dmp_degree(self.to_dense(f), self.ngens-1) + def dmp_degree_in(self, f, j): + return dmp_degree_in(self.to_dense(f), j, self.ngens-1) + def dup_integrate(self, f, m): + return self.from_dense(dup_integrate(self.to_dense(f), m, self.domain)) + def dmp_integrate(self, f, m): + return self.from_dense(dmp_integrate(self.to_dense(f), m, self.ngens-1, self.domain)) + + def dup_diff(self, f, m): + return self.from_dense(dup_diff(self.to_dense(f), m, self.domain)) + def dmp_diff(self, f, m): + return self.from_dense(dmp_diff(self.to_dense(f), m, self.ngens-1, self.domain)) + + def dmp_diff_in(self, f, m, j): + return self.from_dense(dmp_diff_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) + def dmp_integrate_in(self, f, m, j): + return self.from_dense(dmp_integrate_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) + + def dup_eval(self, f, a): + return dup_eval(self.to_dense(f), a, self.domain) + def dmp_eval(self, f, a): + result = dmp_eval(self.to_dense(f), a, self.ngens-1, self.domain) + return self[1:].from_dense(result) + + def dmp_eval_in(self, f, a, j): + result = dmp_eval_in(self.to_dense(f), a, j, self.ngens-1, self.domain) + return self.drop(j).from_dense(result) + def dmp_diff_eval_in(self, f, m, a, j): + result = dmp_diff_eval_in(self.to_dense(f), m, a, j, self.ngens-1, self.domain) + return self.drop(j).from_dense(result) + + def dmp_eval_tail(self, f, A): + result = dmp_eval_tail(self.to_dense(f), A, self.ngens-1, self.domain) + if isinstance(result, list): + return self[:-len(A)].from_dense(result) + else: + return result + + def dup_trunc(self, f, p): + return self.from_dense(dup_trunc(self.to_dense(f), p, self.domain)) + def dmp_trunc(self, f, g): + return self.from_dense(dmp_trunc(self.to_dense(f), self[1:].to_dense(g), self.ngens-1, self.domain)) + def dmp_ground_trunc(self, f, p): + return self.from_dense(dmp_ground_trunc(self.to_dense(f), p, self.ngens-1, self.domain)) + + def dup_monic(self, f): + return self.from_dense(dup_monic(self.to_dense(f), self.domain)) + def dmp_ground_monic(self, f): + return self.from_dense(dmp_ground_monic(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_extract(self, f, g): + c, F, G = dup_extract(self.to_dense(f), self.to_dense(g), self.domain) + return (c, self.from_dense(F), self.from_dense(G)) + def dmp_ground_extract(self, f, g): + c, F, G = dmp_ground_extract(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (c, self.from_dense(F), self.from_dense(G)) + + def dup_real_imag(self, f): + p, q = dup_real_imag(self.wrap(f).drop(1).to_dense(), self.domain) + return (self.from_dense(p), self.from_dense(q)) + + def dup_mirror(self, f): + return self.from_dense(dup_mirror(self.to_dense(f), self.domain)) + def dup_scale(self, f, a): + return self.from_dense(dup_scale(self.to_dense(f), a, self.domain)) + def dup_shift(self, f, a): + return self.from_dense(dup_shift(self.to_dense(f), a, self.domain)) + def dmp_shift(self, f, a): + return self.from_dense(dmp_shift(self.to_dense(f), a, self.ngens-1, self.domain)) + def dup_transform(self, f, p, q): + return self.from_dense(dup_transform(self.to_dense(f), self.to_dense(p), self.to_dense(q), self.domain)) + + def dup_compose(self, f, g): + return self.from_dense(dup_compose(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_compose(self, f, g): + return self.from_dense(dmp_compose(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_decompose(self, f): + components = dup_decompose(self.to_dense(f), self.domain) + return list(map(self.from_dense, components)) + + def dmp_lift(self, f): + result = dmp_lift(self.to_dense(f), self.ngens-1, self.domain) + return self.to_ground().from_dense(result) + + def dup_sign_variations(self, f): + return dup_sign_variations(self.to_dense(f), self.domain) + + def dup_clear_denoms(self, f, convert=False): + c, F = dup_clear_denoms(self.to_dense(f), self.domain, convert=convert) + if convert: + ring = self.clone(domain=self.domain.get_ring()) + else: + ring = self + return (c, ring.from_dense(F)) + def dmp_clear_denoms(self, f, convert=False): + c, F = dmp_clear_denoms(self.to_dense(f), self.ngens-1, self.domain, convert=convert) + if convert: + ring = self.clone(domain=self.domain.get_ring()) + else: + ring = self + return (c, ring.from_dense(F)) + + def dup_revert(self, f, n): + return self.from_dense(dup_revert(self.to_dense(f), n, self.domain)) + + def dup_half_gcdex(self, f, g): + s, h = dup_half_gcdex(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(s), self.from_dense(h)) + def dmp_half_gcdex(self, f, g): + s, h = dmp_half_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(s), self.from_dense(h)) + def dup_gcdex(self, f, g): + s, t, h = dup_gcdex(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) + def dmp_gcdex(self, f, g): + s, t, h = dmp_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) + + def dup_invert(self, f, g): + return self.from_dense(dup_invert(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_invert(self, f, g): + return self.from_dense(dmp_invert(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_euclidean_prs(self, f, g): + prs = dup_euclidean_prs(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_euclidean_prs(self, f, g): + prs = dmp_euclidean_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + def dup_primitive_prs(self, f, g): + prs = dup_primitive_prs(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_primitive_prs(self, f, g): + prs = dmp_primitive_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + + def dup_inner_subresultants(self, f, g): + prs, sres = dup_inner_subresultants(self.to_dense(f), self.to_dense(g), self.domain) + return (list(map(self.from_dense, prs)), sres) + def dmp_inner_subresultants(self, f, g): + prs, sres = dmp_inner_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (list(map(self.from_dense, prs)), sres) + + def dup_subresultants(self, f, g): + prs = dup_subresultants(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_subresultants(self, f, g): + prs = dmp_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + + def dup_prs_resultant(self, f, g): + res, prs = dup_prs_resultant(self.to_dense(f), self.to_dense(g), self.domain) + return (res, list(map(self.from_dense, prs))) + def dmp_prs_resultant(self, f, g): + res, prs = dmp_prs_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self[1:].from_dense(res), list(map(self.from_dense, prs))) + + def dmp_zz_modular_resultant(self, f, g, p): + res = dmp_zz_modular_resultant(self.to_dense(f), self.to_dense(g), self.domain_new(p), self.ngens-1, self.domain) + return self[1:].from_dense(res) + def dmp_zz_collins_resultant(self, f, g): + res = dmp_zz_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self[1:].from_dense(res) + def dmp_qq_collins_resultant(self, f, g): + res = dmp_qq_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self[1:].from_dense(res) + + def dup_resultant(self, f, g): #, includePRS=False): + return dup_resultant(self.to_dense(f), self.to_dense(g), self.domain) #, includePRS=includePRS) + def dmp_resultant(self, f, g): #, includePRS=False): + res = dmp_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) #, includePRS=includePRS) + if isinstance(res, list): + return self[1:].from_dense(res) + else: + return res + + def dup_discriminant(self, f): + return dup_discriminant(self.to_dense(f), self.domain) + def dmp_discriminant(self, f): + disc = dmp_discriminant(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(disc, list): + return self[1:].from_dense(disc) + else: + return disc + + def dup_rr_prs_gcd(self, f, g): + H, F, G = dup_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_ff_prs_gcd(self, f, g): + H, F, G = dup_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_rr_prs_gcd(self, f, g): + H, F, G = dmp_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_ff_prs_gcd(self, f, g): + H, F, G = dmp_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_zz_heu_gcd(self, f, g): + H, F, G = dup_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_zz_heu_gcd(self, f, g): + H, F, G = dmp_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_qq_heu_gcd(self, f, g): + H, F, G = dup_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_qq_heu_gcd(self, f, g): + H, F, G = dmp_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_inner_gcd(self, f, g): + H, F, G = dup_inner_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_inner_gcd(self, f, g): + H, F, G = dmp_inner_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_gcd(self, f, g): + H = dup_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dmp_gcd(self, f, g): + H = dmp_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dup_rr_lcm(self, f, g): + H = dup_rr_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dup_ff_lcm(self, f, g): + H = dup_ff_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dup_lcm(self, f, g): + H = dup_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dmp_rr_lcm(self, f, g): + H = dmp_rr_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dmp_ff_lcm(self, f, g): + H = dmp_ff_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dmp_lcm(self, f, g): + H = dmp_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + + def dup_content(self, f): + cont = dup_content(self.to_dense(f), self.domain) + return cont + def dup_primitive(self, f): + cont, prim = dup_primitive(self.to_dense(f), self.domain) + return cont, self.from_dense(prim) + + def dmp_content(self, f): + cont = dmp_content(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(cont, list): + return self[1:].from_dense(cont) + else: + return cont + def dmp_primitive(self, f): + cont, prim = dmp_primitive(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(cont, list): + return (self[1:].from_dense(cont), self.from_dense(prim)) + else: + return (cont, self.from_dense(prim)) + + def dmp_ground_content(self, f): + cont = dmp_ground_content(self.to_dense(f), self.ngens-1, self.domain) + return cont + def dmp_ground_primitive(self, f): + cont, prim = dmp_ground_primitive(self.to_dense(f), self.ngens-1, self.domain) + return (cont, self.from_dense(prim)) + + def dup_cancel(self, f, g, include=True): + result = dup_cancel(self.to_dense(f), self.to_dense(g), self.domain, include=include) + if not include: + cf, cg, F, G = result + return (cf, cg, self.from_dense(F), self.from_dense(G)) + else: + F, G = result + return (self.from_dense(F), self.from_dense(G)) + def dmp_cancel(self, f, g, include=True): + result = dmp_cancel(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain, include=include) + if not include: + cf, cg, F, G = result + return (cf, cg, self.from_dense(F), self.from_dense(G)) + else: + F, G = result + return (self.from_dense(F), self.from_dense(G)) + + def dup_trial_division(self, f, factors): + factors = dup_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_trial_division(self, f, factors): + factors = dmp_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_zz_mignotte_bound(self, f): + return dup_zz_mignotte_bound(self.to_dense(f), self.domain) + def dmp_zz_mignotte_bound(self, f): + return dmp_zz_mignotte_bound(self.to_dense(f), self.ngens-1, self.domain) + + def dup_zz_hensel_step(self, m, f, g, h, s, t): + D = self.to_dense + G, H, S, T = dup_zz_hensel_step(m, D(f), D(g), D(h), D(s), D(t), self.domain) + return (self.from_dense(G), self.from_dense(H), self.from_dense(S), self.from_dense(T)) + def dup_zz_hensel_lift(self, p, f, f_list, l): + D = self.to_dense + polys = dup_zz_hensel_lift(p, D(f), list(map(D, f_list)), l, self.domain) + return list(map(self.from_dense, polys)) + + def dup_zz_zassenhaus(self, f): + factors = dup_zz_zassenhaus(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_zz_irreducible_p(self, f): + return dup_zz_irreducible_p(self.to_dense(f), self.domain) + def dup_cyclotomic_p(self, f, irreducible=False): + return dup_cyclotomic_p(self.to_dense(f), self.domain, irreducible=irreducible) + def dup_zz_cyclotomic_poly(self, n): + F = dup_zz_cyclotomic_poly(n, self.domain) + return self.from_dense(F) + def dup_zz_cyclotomic_factor(self, f): + result = dup_zz_cyclotomic_factor(self.to_dense(f), self.domain) + if result is None: + return result + else: + return list(map(self.from_dense, result)) + + # E: List[ZZ], cs: ZZ, ct: ZZ + def dmp_zz_wang_non_divisors(self, E, cs, ct): + return dmp_zz_wang_non_divisors(E, cs, ct, self.domain) + + # f: Poly, T: List[(Poly, int)], ct: ZZ, A: List[ZZ] + #def dmp_zz_wang_test_points(f, T, ct, A): + # dmp_zz_wang_test_points(self.to_dense(f), T, ct, A, self.ngens-1, self.domain) + + # f: Poly, T: List[(Poly, int)], cs: ZZ, E: List[ZZ], H: List[Poly], A: List[ZZ] + def dmp_zz_wang_lead_coeffs(self, f, T, cs, E, H, A): + mv = self[1:] + T = [ (mv.to_dense(t), k) for t, k in T ] + uv = self[:1] + H = list(map(uv.to_dense, H)) + f, HH, CC = dmp_zz_wang_lead_coeffs(self.to_dense(f), T, cs, E, H, A, self.ngens-1, self.domain) + return self.from_dense(f), list(map(uv.from_dense, HH)), list(map(mv.from_dense, CC)) + + # f: List[Poly], m: int, p: ZZ + def dup_zz_diophantine(self, F, m, p): + result = dup_zz_diophantine(list(map(self.to_dense, F)), m, p, self.domain) + return list(map(self.from_dense, result)) + + # f: List[Poly], c: List[Poly], A: List[ZZ], d: int, p: ZZ + def dmp_zz_diophantine(self, F, c, A, d, p): + result = dmp_zz_diophantine(list(map(self.to_dense, F)), self.to_dense(c), A, d, p, self.ngens-1, self.domain) + return list(map(self.from_dense, result)) + + # f: Poly, H: List[Poly], LC: List[Poly], A: List[ZZ], p: ZZ + def dmp_zz_wang_hensel_lifting(self, f, H, LC, A, p): + uv = self[:1] + mv = self[1:] + H = list(map(uv.to_dense, H)) + LC = list(map(mv.to_dense, LC)) + result = dmp_zz_wang_hensel_lifting(self.to_dense(f), H, LC, A, p, self.ngens-1, self.domain) + return list(map(self.from_dense, result)) + + def dmp_zz_wang(self, f, mod=None, seed=None): + factors = dmp_zz_wang(self.to_dense(f), self.ngens-1, self.domain, mod=mod, seed=seed) + return [ self.from_dense(g) for g in factors ] + + def dup_zz_factor_sqf(self, f): + coeff, factors = dup_zz_factor_sqf(self.to_dense(f), self.domain) + return (coeff, [ self.from_dense(g) for g in factors ]) + + def dup_zz_factor(self, f): + coeff, factors = dup_zz_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_zz_factor(self, f): + coeff, factors = dmp_zz_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_qq_i_factor(self, f): + coeff, factors = dup_qq_i_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_qq_i_factor(self, f): + coeff, factors = dmp_qq_i_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_zz_i_factor(self, f): + coeff, factors = dup_zz_i_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_zz_i_factor(self, f): + coeff, factors = dmp_zz_i_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_ext_factor(self, f): + coeff, factors = dup_ext_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_ext_factor(self, f): + coeff, factors = dmp_ext_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_gf_factor(self, f): + coeff, factors = dup_gf_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_gf_factor(self, f): + coeff, factors = dmp_gf_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_factor_list(self, f): + coeff, factors = dup_factor_list(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dup_factor_list_include(self, f): + factors = dup_factor_list_include(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dmp_factor_list(self, f): + coeff, factors = dmp_factor_list(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_factor_list_include(self, f): + factors = dmp_factor_list_include(self.to_dense(f), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_irreducible_p(self, f): + return dup_irreducible_p(self.to_dense(f), self.domain) + def dmp_irreducible_p(self, f): + return dmp_irreducible_p(self.to_dense(f), self.ngens-1, self.domain) + + def dup_sturm(self, f): + seq = dup_sturm(self.to_dense(f), self.domain) + return list(map(self.from_dense, seq)) + + def dup_sqf_p(self, f): + return dup_sqf_p(self.to_dense(f), self.domain) + def dmp_sqf_p(self, f): + return dmp_sqf_p(self.to_dense(f), self.ngens-1, self.domain) + + def dmp_norm(self, f): + n = dmp_norm(self.to_dense(f), self.ngens-1, self.domain) + return self.to_ground().from_dense(n) + + def dup_sqf_norm(self, f): + s, F, R = dup_sqf_norm(self.to_dense(f), self.domain) + return (s, self.from_dense(F), self.to_ground().from_dense(R)) + def dmp_sqf_norm(self, f): + s, F, R = dmp_sqf_norm(self.to_dense(f), self.ngens-1, self.domain) + return (s, self.from_dense(F), self.to_ground().from_dense(R)) + + def dup_gf_sqf_part(self, f): + return self.from_dense(dup_gf_sqf_part(self.to_dense(f), self.domain)) + def dmp_gf_sqf_part(self, f): + return self.from_dense(dmp_gf_sqf_part(self.to_dense(f), self.domain)) + def dup_sqf_part(self, f): + return self.from_dense(dup_sqf_part(self.to_dense(f), self.domain)) + def dmp_sqf_part(self, f): + return self.from_dense(dmp_sqf_part(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_gf_sqf_list(self, f, all=False): + coeff, factors = dup_gf_sqf_list(self.to_dense(f), self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_gf_sqf_list(self, f, all=False): + coeff, factors = dmp_gf_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_sqf_list(self, f, all=False): + coeff, factors = dup_sqf_list(self.to_dense(f), self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dup_sqf_list_include(self, f, all=False): + factors = dup_sqf_list_include(self.to_dense(f), self.domain, all=all) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_sqf_list(self, f, all=False): + coeff, factors = dmp_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_sqf_list_include(self, f, all=False): + factors = dmp_sqf_list_include(self.to_dense(f), self.ngens-1, self.domain, all=all) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_gff_list(self, f): + factors = dup_gff_list(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_gff_list(self, f): + factors = dmp_gff_list(self.to_dense(f), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_root_upper_bound(self, f): + return dup_root_upper_bound(self.to_dense(f), self.domain) + def dup_root_lower_bound(self, f): + return dup_root_lower_bound(self.to_dense(f), self.domain) + + def dup_step_refine_real_root(self, f, M, fast=False): + return dup_step_refine_real_root(self.to_dense(f), M, self.domain, fast=fast) + def dup_inner_refine_real_root(self, f, M, eps=None, steps=None, disjoint=None, fast=False, mobius=False): + return dup_inner_refine_real_root(self.to_dense(f), M, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast, mobius=mobius) + def dup_outer_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): + return dup_outer_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + def dup_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): + return dup_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + def dup_inner_isolate_real_roots(self, f, eps=None, fast=False): + return dup_inner_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, fast=fast) + def dup_inner_isolate_positive_roots(self, f, eps=None, inf=None, sup=None, fast=False, mobius=False): + return dup_inner_isolate_positive_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, mobius=mobius) + def dup_inner_isolate_negative_roots(self, f, inf=None, sup=None, eps=None, fast=False, mobius=False): + return dup_inner_isolate_negative_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, eps=eps, fast=fast, mobius=mobius) + def dup_isolate_real_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): + return dup_isolate_real_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) + def dup_isolate_real_roots(self, f, eps=None, inf=None, sup=None, basis=False, fast=False): + return dup_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, basis=basis, fast=fast) + def dup_isolate_real_roots_list(self, polys, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): + return dup_isolate_real_roots_list(list(map(self.to_dense, polys)), self.domain, eps=eps, inf=inf, sup=sup, strict=strict, basis=basis, fast=fast) + def dup_count_real_roots(self, f, inf=None, sup=None): + return dup_count_real_roots(self.to_dense(f), self.domain, inf=inf, sup=sup) + def dup_count_complex_roots(self, f, inf=None, sup=None, exclude=None): + return dup_count_complex_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, exclude=exclude) + def dup_isolate_complex_roots_sqf(self, f, eps=None, inf=None, sup=None, blackbox=False): + return dup_isolate_complex_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, blackbox=blackbox) + def dup_isolate_all_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): + return dup_isolate_all_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) + def dup_isolate_all_roots(self, f, eps=None, inf=None, sup=None, fast=False): + return dup_isolate_all_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast) + + def fateman_poly_F_1(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_1 + return tuple(map(self.from_dense, dmp_fateman_poly_F_1(self.ngens-1, self.domain))) + def fateman_poly_F_2(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_2 + return tuple(map(self.from_dense, dmp_fateman_poly_F_2(self.ngens-1, self.domain))) + def fateman_poly_F_3(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_3 + return tuple(map(self.from_dense, dmp_fateman_poly_F_3(self.ngens-1, self.domain))) + + def to_gf_dense(self, element): + return gf_strip([ self.domain.dom.convert(c, self.domain) for c in self.wrap(element).to_dense() ]) + + def from_gf_dense(self, element): + return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain.dom)) + + def gf_degree(self, f): + return gf_degree(self.to_gf_dense(f)) + + def gf_LC(self, f): + return gf_LC(self.to_gf_dense(f), self.domain.dom) + def gf_TC(self, f): + return gf_TC(self.to_gf_dense(f), self.domain.dom) + + def gf_strip(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f))) + def gf_trunc(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod)) + def gf_normal(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_from_dict(self, f): + return self.from_gf_dense(gf_from_dict(f, self.domain.mod, self.domain.dom)) + def gf_to_dict(self, f, symmetric=True): + return gf_to_dict(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) + + def gf_from_int_poly(self, f): + return self.from_gf_dense(gf_from_int_poly(f, self.domain.mod)) + def gf_to_int_poly(self, f, symmetric=True): + return gf_to_int_poly(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) + + def gf_neg(self, f): + return self.from_gf_dense(gf_neg(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_add_ground(self, f, a): + return self.from_gf_dense(gf_add_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_sub_ground(self, f, a): + return self.from_gf_dense(gf_sub_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_mul_ground(self, f, a): + return self.from_gf_dense(gf_mul_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_quo_ground(self, f, a): + return self.from_gf_dense(gf_quo_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + + def gf_add(self, f, g): + return self.from_gf_dense(gf_add(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_sub(self, f, g): + return self.from_gf_dense(gf_sub(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_mul(self, f, g): + return self.from_gf_dense(gf_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_sqr(self, f): + return self.from_gf_dense(gf_sqr(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_add_mul(self, f, g, h): + return self.from_gf_dense(gf_add_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) + def gf_sub_mul(self, f, g, h): + return self.from_gf_dense(gf_sub_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) + + def gf_expand(self, F): + return self.from_gf_dense(gf_expand(list(map(self.to_gf_dense, F)), self.domain.mod, self.domain.dom)) + + def gf_div(self, f, g): + q, r = gf_div(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) + return self.from_gf_dense(q), self.from_gf_dense(r) + def gf_rem(self, f, g): + return self.from_gf_dense(gf_rem(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_quo(self, f, g): + return self.from_gf_dense(gf_quo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_exquo(self, f, g): + return self.from_gf_dense(gf_exquo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_lshift(self, f, n): + return self.from_gf_dense(gf_lshift(self.to_gf_dense(f), n, self.domain.dom)) + def gf_rshift(self, f, n): + return self.from_gf_dense(gf_rshift(self.to_gf_dense(f), n, self.domain.dom)) + + def gf_pow(self, f, n): + return self.from_gf_dense(gf_pow(self.to_gf_dense(f), n, self.domain.mod, self.domain.dom)) + def gf_pow_mod(self, f, n, g): + return self.from_gf_dense(gf_pow_mod(self.to_gf_dense(f), n, self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_cofactors(self, f, g): + h, cff, cfg = gf_cofactors(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) + return self.from_gf_dense(h), self.from_gf_dense(cff), self.from_gf_dense(cfg) + def gf_gcd(self, f, g): + return self.from_gf_dense(gf_gcd(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_lcm(self, f, g): + return self.from_gf_dense(gf_lcm(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_gcdex(self, f, g): + return self.from_gf_dense(gf_gcdex(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_monic(self, f): + return self.from_gf_dense(gf_monic(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + def gf_diff(self, f): + return self.from_gf_dense(gf_diff(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_eval(self, f, a): + return gf_eval(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom) + def gf_multi_eval(self, f, A): + return gf_multi_eval(self.to_gf_dense(f), A, self.domain.mod, self.domain.dom) + + def gf_compose(self, f, g): + return self.from_gf_dense(gf_compose(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_compose_mod(self, g, h, f): + return self.from_gf_dense(gf_compose_mod(self.to_gf_dense(g), self.to_gf_dense(h), self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_trace_map(self, a, b, c, n, f): + a = self.to_gf_dense(a) + b = self.to_gf_dense(b) + c = self.to_gf_dense(c) + f = self.to_gf_dense(f) + U, V = gf_trace_map(a, b, c, n, f, self.domain.mod, self.domain.dom) + return self.from_gf_dense(U), self.from_gf_dense(V) + + def gf_random(self, n): + return self.from_gf_dense(gf_random(n, self.domain.mod, self.domain.dom)) + def gf_irreducible(self, n): + return self.from_gf_dense(gf_irreducible(n, self.domain.mod, self.domain.dom)) + + def gf_irred_p_ben_or(self, f): + return gf_irred_p_ben_or(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_irred_p_rabin(self, f): + return gf_irred_p_rabin(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_irreducible_p(self, f): + return gf_irreducible_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_sqf_p(self, f): + return gf_sqf_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + + def gf_sqf_part(self, f): + return self.from_gf_dense(gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + def gf_sqf_list(self, f, all=False): + coeff, factors = gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ] + + def gf_Qmatrix(self, f): + return gf_Qmatrix(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_berlekamp(self, f): + factors = gf_berlekamp(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_ddf_zassenhaus(self, f): + factors = gf_ddf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ (self.from_gf_dense(g), k) for g, k in factors ] + def gf_edf_zassenhaus(self, f, n): + factors = gf_edf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_ddf_shoup(self, f): + factors = gf_ddf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ (self.from_gf_dense(g), k) for g, k in factors ] + def gf_edf_shoup(self, f, n): + factors = gf_edf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_zassenhaus(self, f): + factors = gf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + def gf_shoup(self, f): + factors = gf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_factor_sqf(self, f, method=None): + coeff, factors = gf_factor_sqf(self.to_gf_dense(f), self.domain.mod, self.domain.dom, method=method) + return coeff, [ self.from_gf_dense(g) for g in factors ] + def gf_factor(self, f): + coeff, factors = gf_factor(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/constructor.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..49ce4782b987419ee8b736974f8755301380bdda --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/constructor.py @@ -0,0 +1,387 @@ +"""Tools for constructing domains for expressions. """ +from math import prod + +from sympy.core import sympify +from sympy.core.evalf import pure_complex +from sympy.core.sorting import ordered +from sympy.polys.domains import ZZ, QQ, ZZ_I, QQ_I, EX +from sympy.polys.domains.complexfield import ComplexField +from sympy.polys.domains.realfield import RealField +from sympy.polys.polyoptions import build_options +from sympy.polys.polyutils import parallel_dict_from_basic +from sympy.utilities import public + + +def _construct_simple(coeffs, opt): + """Handle simple domains, e.g.: ZZ, QQ, RR and algebraic domains. """ + rationals = floats = complexes = algebraics = False + float_numbers = [] + + if opt.extension is True: + is_algebraic = lambda coeff: coeff.is_number and coeff.is_algebraic + else: + is_algebraic = lambda coeff: False + + for coeff in coeffs: + if coeff.is_Rational: + if not coeff.is_Integer: + rationals = True + elif coeff.is_Float: + if algebraics: + # there are both reals and algebraics -> EX + return False + else: + floats = True + float_numbers.append(coeff) + else: + is_complex = pure_complex(coeff) + if is_complex: + complexes = True + x, y = is_complex + if x.is_Rational and y.is_Rational: + if not (x.is_Integer and y.is_Integer): + rationals = True + continue + else: + floats = True + if x.is_Float: + float_numbers.append(x) + if y.is_Float: + float_numbers.append(y) + elif is_algebraic(coeff): + if floats: + # there are both algebraics and reals -> EX + return False + algebraics = True + else: + # this is a composite domain, e.g. ZZ[X], EX + return None + + # Use the maximum precision of all coefficients for the RR or CC + # precision + max_prec = max(c._prec for c in float_numbers) if float_numbers else 53 + + if algebraics: + domain, result = _construct_algebraic(coeffs, opt) + else: + if floats and complexes: + domain = ComplexField(prec=max_prec) + elif floats: + domain = RealField(prec=max_prec) + elif rationals or opt.field: + domain = QQ_I if complexes else QQ + else: + domain = ZZ_I if complexes else ZZ + + result = [domain.from_sympy(coeff) for coeff in coeffs] + + return domain, result + + +def _construct_algebraic(coeffs, opt): + """We know that coefficients are algebraic so construct the extension. """ + from sympy.polys.numberfields import primitive_element + + exts = set() + + def build_trees(args): + trees = [] + for a in args: + if a.is_Rational: + tree = ('Q', QQ.from_sympy(a)) + elif a.is_Add: + tree = ('+', build_trees(a.args)) + elif a.is_Mul: + tree = ('*', build_trees(a.args)) + else: + tree = ('e', a) + exts.add(a) + trees.append(tree) + return trees + + trees = build_trees(coeffs) + exts = list(ordered(exts)) + + g, span, H = primitive_element(exts, ex=True, polys=True) + root = sum(s*ext for s, ext in zip(span, exts)) + + domain, g = QQ.algebraic_field((g, root)), g.rep.to_list() + + exts_dom = [domain.dtype.from_list(h, g, QQ) for h in H] + exts_map = dict(zip(exts, exts_dom)) + + def convert_tree(tree): + op, args = tree + if op == 'Q': + return domain.dtype.from_list([args], g, QQ) + elif op == '+': + return sum((convert_tree(a) for a in args), domain.zero) + elif op == '*': + return prod(convert_tree(a) for a in args) + elif op == 'e': + return exts_map[args] + else: + raise RuntimeError + + result = [convert_tree(tree) for tree in trees] + + return domain, result + + +def _construct_composite(coeffs, opt): + """Handle composite domains, e.g.: ZZ[X], QQ[X], ZZ(X), QQ(X). """ + numers, denoms = [], [] + + for coeff in coeffs: + numer, denom = coeff.as_numer_denom() + + numers.append(numer) + denoms.append(denom) + + polys, gens = parallel_dict_from_basic(numers + denoms) # XXX: sorting + if not gens: + return None + + if opt.composite is None: + if any(gen.is_number and gen.is_algebraic for gen in gens): + return None # generators are number-like so lets better use EX + + all_symbols = set() + + for gen in gens: + symbols = gen.free_symbols + + if all_symbols & symbols: + return None # there could be algebraic relations between generators + else: + all_symbols |= symbols + + n = len(gens) + k = len(polys)//2 + + numers = polys[:k] + denoms = polys[k:] + + if opt.field: + fractions = True + else: + fractions, zeros = False, (0,)*n + + for denom in denoms: + if len(denom) > 1 or zeros not in denom: + fractions = True + break + + coeffs = set() + + if not fractions: + for numer, denom in zip(numers, denoms): + denom = denom[zeros] + + for monom, coeff in numer.items(): + coeff /= denom + coeffs.add(coeff) + numer[monom] = coeff + else: + for numer, denom in zip(numers, denoms): + coeffs.update(list(numer.values())) + coeffs.update(list(denom.values())) + + rationals = floats = complexes = False + float_numbers = [] + + for coeff in coeffs: + if coeff.is_Rational: + if not coeff.is_Integer: + rationals = True + elif coeff.is_Float: + floats = True + float_numbers.append(coeff) + else: + is_complex = pure_complex(coeff) + if is_complex is not None: + complexes = True + x, y = is_complex + if x.is_Rational and y.is_Rational: + if not (x.is_Integer and y.is_Integer): + rationals = True + else: + floats = True + if x.is_Float: + float_numbers.append(x) + if y.is_Float: + float_numbers.append(y) + + max_prec = max(c._prec for c in float_numbers) if float_numbers else 53 + + if floats and complexes: + ground = ComplexField(prec=max_prec) + elif floats: + ground = RealField(prec=max_prec) + elif complexes: + if rationals: + ground = QQ_I + else: + ground = ZZ_I + elif rationals: + ground = QQ + else: + ground = ZZ + + result = [] + + if not fractions: + domain = ground.poly_ring(*gens) + + for numer in numers: + for monom, coeff in numer.items(): + numer[monom] = ground.from_sympy(coeff) + + result.append(domain(numer)) + else: + domain = ground.frac_field(*gens) + + for numer, denom in zip(numers, denoms): + for monom, coeff in numer.items(): + numer[monom] = ground.from_sympy(coeff) + + for monom, coeff in denom.items(): + denom[monom] = ground.from_sympy(coeff) + + result.append(domain((numer, denom))) + + return domain, result + + +def _construct_expression(coeffs, opt): + """The last resort case, i.e. use the expression domain. """ + domain, result = EX, [] + + for coeff in coeffs: + result.append(domain.from_sympy(coeff)) + + return domain, result + + +@public +def construct_domain(obj, **args): + """Construct a minimal domain for a list of expressions. + + Explanation + =========== + + Given a list of normal SymPy expressions (of type :py:class:`~.Expr`) + ``construct_domain`` will find a minimal :py:class:`~.Domain` that can + represent those expressions. The expressions will be converted to elements + of the domain and both the domain and the domain elements are returned. + + Parameters + ========== + + obj: list or dict + The expressions to build a domain for. + + **args: keyword arguments + Options that affect the choice of domain. + + Returns + ======= + + (K, elements): Domain and list of domain elements + The domain K that can represent the expressions and the list or dict + of domain elements representing the same expressions as elements of K. + + Examples + ======== + + Given a list of :py:class:`~.Integer` ``construct_domain`` will return the + domain :ref:`ZZ` and a list of integers as elements of :ref:`ZZ`. + + >>> from sympy import construct_domain, S + >>> expressions = [S(2), S(3), S(4)] + >>> K, elements = construct_domain(expressions) + >>> K + ZZ + >>> elements + [2, 3, 4] + >>> type(elements[0]) # doctest: +SKIP + + >>> type(expressions[0]) + + + If there are any :py:class:`~.Rational` then :ref:`QQ` is returned + instead. + + >>> construct_domain([S(1)/2, S(3)/4]) + (QQ, [1/2, 3/4]) + + If there are symbols then a polynomial ring :ref:`K[x]` is returned. + + >>> from sympy import symbols + >>> x, y = symbols('x, y') + >>> construct_domain([2*x + 1, S(3)/4]) + (QQ[x], [2*x + 1, 3/4]) + >>> construct_domain([2*x + 1, y]) + (ZZ[x,y], [2*x + 1, y]) + + If any symbols appear with negative powers then a rational function field + :ref:`K(x)` will be returned. + + >>> construct_domain([y/x, x/(1 - y)]) + (ZZ(x,y), [y/x, -x/(y - 1)]) + + Irrational algebraic numbers will result in the :ref:`EX` domain by + default. The keyword argument ``extension=True`` leads to the construction + of an algebraic number field :ref:`QQ(a)`. + + >>> from sympy import sqrt + >>> construct_domain([sqrt(2)]) + (EX, [EX(sqrt(2))]) + >>> construct_domain([sqrt(2)], extension=True) # doctest: +SKIP + (QQ, [ANP([1, 0], [1, 0, -2], QQ)]) + + See also + ======== + + Domain + Expr + """ + opt = build_options(args) + + if hasattr(obj, '__iter__'): + if isinstance(obj, dict): + if not obj: + monoms, coeffs = [], [] + else: + monoms, coeffs = list(zip(*list(obj.items()))) + else: + coeffs = obj + else: + coeffs = [obj] + + coeffs = list(map(sympify, coeffs)) + result = _construct_simple(coeffs, opt) + + if result is not None: + if result is not False: + domain, coeffs = result + else: + domain, coeffs = _construct_expression(coeffs, opt) + else: + if opt.composite is False: + result = None + else: + result = _construct_composite(coeffs, opt) + + if result is not None: + domain, coeffs = result + else: + domain, coeffs = _construct_expression(coeffs, opt) + + if hasattr(obj, '__iter__'): + if isinstance(obj, dict): + return domain, dict(list(zip(monoms, coeffs))) + else: + return domain, coeffs + else: + return domain, coeffs[0] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densearith.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densearith.py new file mode 100644 index 0000000000000000000000000000000000000000..1088691ca3fb020e9074c1c7c017c1baaba637c8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densearith.py @@ -0,0 +1,1875 @@ +"""Arithmetics for dense recursive polynomials in ``K[x]`` or ``K[X]``. """ + + +from sympy.polys.densebasic import ( + dup_slice, + dup_LC, dmp_LC, + dup_degree, dmp_degree, + dup_strip, dmp_strip, + dmp_zero_p, dmp_zero, + dmp_one_p, dmp_one, + dmp_ground, dmp_zeros) +from sympy.polys.polyerrors import (ExactQuotientFailed, PolynomialDivisionFailed) + +def dup_add_term(f, c, i, K): + """ + Add ``c*x**i`` to ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_add_term(x**2 - 1, ZZ(2), 4) + 2*x**4 + x**2 - 1 + + """ + if not c: + return f + + n = len(f) + m = n - i - 1 + + if i == n - 1: + return dup_strip([f[0] + c] + f[1:]) + else: + if i >= n: + return [c] + [K.zero]*(i - n) + f + else: + return f[:m] + [f[m] + c] + f[m + 1:] + + +def dmp_add_term(f, c, i, u, K): + """ + Add ``c(x_2..x_u)*x_0**i`` to ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_add_term(x*y + 1, 2, 2) + 2*x**2 + x*y + 1 + + """ + if not u: + return dup_add_term(f, c, i, K) + + v = u - 1 + + if dmp_zero_p(c, v): + return f + + n = len(f) + m = n - i - 1 + + if i == n - 1: + return dmp_strip([dmp_add(f[0], c, v, K)] + f[1:], u) + else: + if i >= n: + return [c] + dmp_zeros(i - n, v, K) + f + else: + return f[:m] + [dmp_add(f[m], c, v, K)] + f[m + 1:] + + +def dup_sub_term(f, c, i, K): + """ + Subtract ``c*x**i`` from ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sub_term(2*x**4 + x**2 - 1, ZZ(2), 4) + x**2 - 1 + + """ + if not c: + return f + + n = len(f) + m = n - i - 1 + + if i == n - 1: + return dup_strip([f[0] - c] + f[1:]) + else: + if i >= n: + return [-c] + [K.zero]*(i - n) + f + else: + return f[:m] + [f[m] - c] + f[m + 1:] + + +def dmp_sub_term(f, c, i, u, K): + """ + Subtract ``c(x_2..x_u)*x_0**i`` from ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_sub_term(2*x**2 + x*y + 1, 2, 2) + x*y + 1 + + """ + if not u: + return dup_add_term(f, -c, i, K) + + v = u - 1 + + if dmp_zero_p(c, v): + return f + + n = len(f) + m = n - i - 1 + + if i == n - 1: + return dmp_strip([dmp_sub(f[0], c, v, K)] + f[1:], u) + else: + if i >= n: + return [dmp_neg(c, v, K)] + dmp_zeros(i - n, v, K) + f + else: + return f[:m] + [dmp_sub(f[m], c, v, K)] + f[m + 1:] + + +def dup_mul_term(f, c, i, K): + """ + Multiply ``f`` by ``c*x**i`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_mul_term(x**2 - 1, ZZ(3), 2) + 3*x**4 - 3*x**2 + + """ + if not c or not f: + return [] + else: + return [ cf * c for cf in f ] + [K.zero]*i + + +def dmp_mul_term(f, c, i, u, K): + """ + Multiply ``f`` by ``c(x_2..x_u)*x_0**i`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_mul_term(x**2*y + x, 3*y, 2) + 3*x**4*y**2 + 3*x**3*y + + """ + if not u: + return dup_mul_term(f, c, i, K) + + v = u - 1 + + if dmp_zero_p(f, u): + return f + if dmp_zero_p(c, v): + return dmp_zero(u) + else: + return [ dmp_mul(cf, c, v, K) for cf in f ] + dmp_zeros(i, v, K) + + +def dup_add_ground(f, c, K): + """ + Add an element of the ground domain to ``f``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_add_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) + x**3 + 2*x**2 + 3*x + 8 + + """ + return dup_add_term(f, c, 0, K) + + +def dmp_add_ground(f, c, u, K): + """ + Add an element of the ground domain to ``f``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_add_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) + x**3 + 2*x**2 + 3*x + 8 + + """ + return dmp_add_term(f, dmp_ground(c, u - 1), 0, u, K) + + +def dup_sub_ground(f, c, K): + """ + Subtract an element of the ground domain from ``f``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sub_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) + x**3 + 2*x**2 + 3*x + + """ + return dup_sub_term(f, c, 0, K) + + +def dmp_sub_ground(f, c, u, K): + """ + Subtract an element of the ground domain from ``f``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_sub_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4)) + x**3 + 2*x**2 + 3*x + + """ + return dmp_sub_term(f, dmp_ground(c, u - 1), 0, u, K) + + +def dup_mul_ground(f, c, K): + """ + Multiply ``f`` by a constant value in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_mul_ground(x**2 + 2*x - 1, ZZ(3)) + 3*x**2 + 6*x - 3 + + """ + if not c or not f: + return [] + else: + return [ cf * c for cf in f ] + + +def dmp_mul_ground(f, c, u, K): + """ + Multiply ``f`` by a constant value in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_mul_ground(2*x + 2*y, ZZ(3)) + 6*x + 6*y + + """ + if not u: + return dup_mul_ground(f, c, K) + + v = u - 1 + + return [ dmp_mul_ground(cf, c, v, K) for cf in f ] + + +def dup_quo_ground(f, c, K): + """ + Quotient by a constant in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x = ring("x", ZZ) + >>> R.dup_quo_ground(3*x**2 + 2, ZZ(2)) + x**2 + 1 + + >>> R, x = ring("x", QQ) + >>> R.dup_quo_ground(3*x**2 + 2, QQ(2)) + 3/2*x**2 + 1 + + """ + if not c: + raise ZeroDivisionError('polynomial division') + if not f: + return f + + if K.is_Field: + return [ K.quo(cf, c) for cf in f ] + else: + return [ cf // c for cf in f ] + + +def dmp_quo_ground(f, c, u, K): + """ + Quotient by a constant in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x,y = ring("x,y", ZZ) + >>> R.dmp_quo_ground(2*x**2*y + 3*x, ZZ(2)) + x**2*y + x + + >>> R, x,y = ring("x,y", QQ) + >>> R.dmp_quo_ground(2*x**2*y + 3*x, QQ(2)) + x**2*y + 3/2*x + + """ + if not u: + return dup_quo_ground(f, c, K) + + v = u - 1 + + return [ dmp_quo_ground(cf, c, v, K) for cf in f ] + + +def dup_exquo_ground(f, c, K): + """ + Exact quotient by a constant in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> R.dup_exquo_ground(x**2 + 2, QQ(2)) + 1/2*x**2 + 1 + + """ + if not c: + raise ZeroDivisionError('polynomial division') + if not f: + return f + + return [ K.exquo(cf, c) for cf in f ] + + +def dmp_exquo_ground(f, c, u, K): + """ + Exact quotient by a constant in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y = ring("x,y", QQ) + + >>> R.dmp_exquo_ground(x**2*y + 2*x, QQ(2)) + 1/2*x**2*y + x + + """ + if not u: + return dup_exquo_ground(f, c, K) + + v = u - 1 + + return [ dmp_exquo_ground(cf, c, v, K) for cf in f ] + + +def dup_lshift(f, n, K): + """ + Efficiently multiply ``f`` by ``x**n`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_lshift(x**2 + 1, 2) + x**4 + x**2 + + """ + if not f: + return f + else: + return f + [K.zero]*n + + +def dup_rshift(f, n, K): + """ + Efficiently divide ``f`` by ``x**n`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_rshift(x**4 + x**2, 2) + x**2 + 1 + >>> R.dup_rshift(x**4 + x**2 + 2, 2) + x**2 + 1 + + """ + return f[:-n] + + +def dup_abs(f, K): + """ + Make all coefficients positive in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_abs(x**2 - 1) + x**2 + 1 + + """ + return [ K.abs(coeff) for coeff in f ] + + +def dmp_abs(f, u, K): + """ + Make all coefficients positive in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_abs(x**2*y - x) + x**2*y + x + + """ + if not u: + return dup_abs(f, K) + + v = u - 1 + + return [ dmp_abs(cf, v, K) for cf in f ] + + +def dup_neg(f, K): + """ + Negate a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_neg(x**2 - 1) + -x**2 + 1 + + """ + return [ -coeff for coeff in f ] + + +def dmp_neg(f, u, K): + """ + Negate a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_neg(x**2*y - x) + -x**2*y + x + + """ + if not u: + return dup_neg(f, K) + + v = u - 1 + + return [ dmp_neg(cf, v, K) for cf in f ] + + +def dup_add(f, g, K): + """ + Add dense polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_add(x**2 - 1, x - 2) + x**2 + x - 3 + + """ + if not f: + return g + if not g: + return f + + df = dup_degree(f) + dg = dup_degree(g) + + if df == dg: + return dup_strip([ a + b for a, b in zip(f, g) ]) + else: + k = abs(df - dg) + + if df > dg: + h, f = f[:k], f[k:] + else: + h, g = g[:k], g[k:] + + return h + [ a + b for a, b in zip(f, g) ] + + +def dmp_add(f, g, u, K): + """ + Add dense polynomials in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_add(x**2 + y, x**2*y + x) + x**2*y + x**2 + x + y + + """ + if not u: + return dup_add(f, g, K) + + df = dmp_degree(f, u) + + if df < 0: + return g + + dg = dmp_degree(g, u) + + if dg < 0: + return f + + v = u - 1 + + if df == dg: + return dmp_strip([ dmp_add(a, b, v, K) for a, b in zip(f, g) ], u) + else: + k = abs(df - dg) + + if df > dg: + h, f = f[:k], f[k:] + else: + h, g = g[:k], g[k:] + + return h + [ dmp_add(a, b, v, K) for a, b in zip(f, g) ] + + +def dup_sub(f, g, K): + """ + Subtract dense polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sub(x**2 - 1, x - 2) + x**2 - x + 1 + + """ + if not f: + return dup_neg(g, K) + if not g: + return f + + df = dup_degree(f) + dg = dup_degree(g) + + if df == dg: + return dup_strip([ a - b for a, b in zip(f, g) ]) + else: + k = abs(df - dg) + + if df > dg: + h, f = f[:k], f[k:] + else: + h, g = dup_neg(g[:k], K), g[k:] + + return h + [ a - b for a, b in zip(f, g) ] + + +def dmp_sub(f, g, u, K): + """ + Subtract dense polynomials in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_sub(x**2 + y, x**2*y + x) + -x**2*y + x**2 - x + y + + """ + if not u: + return dup_sub(f, g, K) + + df = dmp_degree(f, u) + + if df < 0: + return dmp_neg(g, u, K) + + dg = dmp_degree(g, u) + + if dg < 0: + return f + + v = u - 1 + + if df == dg: + return dmp_strip([ dmp_sub(a, b, v, K) for a, b in zip(f, g) ], u) + else: + k = abs(df - dg) + + if df > dg: + h, f = f[:k], f[k:] + else: + h, g = dmp_neg(g[:k], u, K), g[k:] + + return h + [ dmp_sub(a, b, v, K) for a, b in zip(f, g) ] + + +def dup_add_mul(f, g, h, K): + """ + Returns ``f + g*h`` where ``f, g, h`` are in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_add_mul(x**2 - 1, x - 2, x + 2) + 2*x**2 - 5 + + """ + return dup_add(f, dup_mul(g, h, K), K) + + +def dmp_add_mul(f, g, h, u, K): + """ + Returns ``f + g*h`` where ``f, g, h`` are in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_add_mul(x**2 + y, x, x + 2) + 2*x**2 + 2*x + y + + """ + return dmp_add(f, dmp_mul(g, h, u, K), u, K) + + +def dup_sub_mul(f, g, h, K): + """ + Returns ``f - g*h`` where ``f, g, h`` are in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sub_mul(x**2 - 1, x - 2, x + 2) + 3 + + """ + return dup_sub(f, dup_mul(g, h, K), K) + + +def dmp_sub_mul(f, g, h, u, K): + """ + Returns ``f - g*h`` where ``f, g, h`` are in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_sub_mul(x**2 + y, x, x + 2) + -2*x + y + + """ + return dmp_sub(f, dmp_mul(g, h, u, K), u, K) + + +def dup_mul(f, g, K): + """ + Multiply dense polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_mul(x - 2, x + 2) + x**2 - 4 + + """ + if f == g: + return dup_sqr(f, K) + + if not (f and g): + return [] + + df = dup_degree(f) + dg = dup_degree(g) + + n = max(df, dg) + 1 + + if n < 100 or not K.is_Exact: + h = [] + + for i in range(0, df + dg + 1): + coeff = K.zero + + for j in range(max(0, i - dg), min(df, i) + 1): + coeff += f[j]*g[i - j] + + h.append(coeff) + + return dup_strip(h) + else: + # Use Karatsuba's algorithm (divide and conquer), see e.g.: + # Joris van der Hoeven, Relax But Don't Be Too Lazy, + # J. Symbolic Computation, 11 (2002), section 3.1.1. + n2 = n//2 + + fl, gl = dup_slice(f, 0, n2, K), dup_slice(g, 0, n2, K) + + fh = dup_rshift(dup_slice(f, n2, n, K), n2, K) + gh = dup_rshift(dup_slice(g, n2, n, K), n2, K) + + lo, hi = dup_mul(fl, gl, K), dup_mul(fh, gh, K) + + mid = dup_mul(dup_add(fl, fh, K), dup_add(gl, gh, K), K) + mid = dup_sub(mid, dup_add(lo, hi, K), K) + + return dup_add(dup_add(lo, dup_lshift(mid, n2, K), K), + dup_lshift(hi, 2*n2, K), K) + + +def dmp_mul(f, g, u, K): + """ + Multiply dense polynomials in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_mul(x*y + 1, x) + x**2*y + x + + """ + if not u: + return dup_mul(f, g, K) + + if f == g: + return dmp_sqr(f, u, K) + + df = dmp_degree(f, u) + + if df < 0: + return f + + dg = dmp_degree(g, u) + + if dg < 0: + return g + + h, v = [], u - 1 + + for i in range(0, df + dg + 1): + coeff = dmp_zero(v) + + for j in range(max(0, i - dg), min(df, i) + 1): + coeff = dmp_add(coeff, dmp_mul(f[j], g[i - j], v, K), v, K) + + h.append(coeff) + + return dmp_strip(h, u) + + +def dup_sqr(f, K): + """ + Square dense polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sqr(x**2 + 1) + x**4 + 2*x**2 + 1 + + """ + df, h = len(f) - 1, [] + + for i in range(0, 2*df + 1): + c = K.zero + + jmin = max(0, i - df) + jmax = min(i, df) + + n = jmax - jmin + 1 + + jmax = jmin + n // 2 - 1 + + for j in range(jmin, jmax + 1): + c += f[j]*f[i - j] + + c += c + + if n & 1: + elem = f[jmax + 1] + c += elem**2 + + h.append(c) + + return dup_strip(h) + + +def dmp_sqr(f, u, K): + """ + Square dense polynomials in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_sqr(x**2 + x*y + y**2) + x**4 + 2*x**3*y + 3*x**2*y**2 + 2*x*y**3 + y**4 + + """ + if not u: + return dup_sqr(f, K) + + df = dmp_degree(f, u) + + if df < 0: + return f + + h, v = [], u - 1 + + for i in range(0, 2*df + 1): + c = dmp_zero(v) + + jmin = max(0, i - df) + jmax = min(i, df) + + n = jmax - jmin + 1 + + jmax = jmin + n // 2 - 1 + + for j in range(jmin, jmax + 1): + c = dmp_add(c, dmp_mul(f[j], f[i - j], v, K), v, K) + + c = dmp_mul_ground(c, K(2), v, K) + + if n & 1: + elem = dmp_sqr(f[jmax + 1], v, K) + c = dmp_add(c, elem, v, K) + + h.append(c) + + return dmp_strip(h, u) + + +def dup_pow(f, n, K): + """ + Raise ``f`` to the ``n``-th power in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_pow(x - 2, 3) + x**3 - 6*x**2 + 12*x - 8 + + """ + if not n: + return [K.one] + if n < 0: + raise ValueError("Cannot raise polynomial to a negative power") + if n == 1 or not f or f == [K.one]: + return f + + g = [K.one] + + while True: + n, m = n//2, n + + if m % 2: + g = dup_mul(g, f, K) + + if not n: + break + + f = dup_sqr(f, K) + + return g + + +def dmp_pow(f, n, u, K): + """ + Raise ``f`` to the ``n``-th power in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_pow(x*y + 1, 3) + x**3*y**3 + 3*x**2*y**2 + 3*x*y + 1 + + """ + if not u: + return dup_pow(f, n, K) + + if not n: + return dmp_one(u, K) + if n < 0: + raise ValueError("Cannot raise polynomial to a negative power") + if n == 1 or dmp_zero_p(f, u) or dmp_one_p(f, u, K): + return f + + g = dmp_one(u, K) + + while True: + n, m = n//2, n + + if m & 1: + g = dmp_mul(g, f, u, K) + + if not n: + break + + f = dmp_sqr(f, u, K) + + return g + + +def dup_pdiv(f, g, K): + """ + Polynomial pseudo-division in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_pdiv(x**2 + 1, 2*x - 4) + (2*x + 4, 20) + + """ + df = dup_degree(f) + dg = dup_degree(g) + + q, r, dr = [], f, df + + if not g: + raise ZeroDivisionError("polynomial division") + elif df < dg: + return q, r + + N = df - dg + 1 + lc_g = dup_LC(g, K) + + while True: + lc_r = dup_LC(r, K) + j, N = dr - dg, N - 1 + + Q = dup_mul_ground(q, lc_g, K) + q = dup_add_term(Q, lc_r, j, K) + + R = dup_mul_ground(r, lc_g, K) + G = dup_mul_term(g, lc_r, j, K) + r = dup_sub(R, G, K) + + _dr, dr = dr, dup_degree(r) + + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + c = lc_g**N + + q = dup_mul_ground(q, c, K) + r = dup_mul_ground(r, c, K) + + return q, r + + +def dup_prem(f, g, K): + """ + Polynomial pseudo-remainder in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_prem(x**2 + 1, 2*x - 4) + 20 + + """ + df = dup_degree(f) + dg = dup_degree(g) + + r, dr = f, df + + if not g: + raise ZeroDivisionError("polynomial division") + elif df < dg: + return r + + N = df - dg + 1 + lc_g = dup_LC(g, K) + + while True: + lc_r = dup_LC(r, K) + j, N = dr - dg, N - 1 + + R = dup_mul_ground(r, lc_g, K) + G = dup_mul_term(g, lc_r, j, K) + r = dup_sub(R, G, K) + + _dr, dr = dr, dup_degree(r) + + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + return dup_mul_ground(r, lc_g**N, K) + + +def dup_pquo(f, g, K): + """ + Polynomial exact pseudo-quotient in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_pquo(x**2 - 1, 2*x - 2) + 2*x + 2 + + >>> R.dup_pquo(x**2 + 1, 2*x - 4) + 2*x + 4 + + """ + return dup_pdiv(f, g, K)[0] + + +def dup_pexquo(f, g, K): + """ + Polynomial pseudo-quotient in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_pexquo(x**2 - 1, 2*x - 2) + 2*x + 2 + + >>> R.dup_pexquo(x**2 + 1, 2*x - 4) + Traceback (most recent call last): + ... + ExactQuotientFailed: [2, -4] does not divide [1, 0, 1] + + """ + q, r = dup_pdiv(f, g, K) + + if not r: + return q + else: + raise ExactQuotientFailed(f, g) + + +def dmp_pdiv(f, g, u, K): + """ + Polynomial pseudo-division in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_pdiv(x**2 + x*y, 2*x + 2) + (2*x + 2*y - 2, -4*y + 4) + + """ + if not u: + return dup_pdiv(f, g, K) + + df = dmp_degree(f, u) + dg = dmp_degree(g, u) + + if dg < 0: + raise ZeroDivisionError("polynomial division") + + q, r, dr = dmp_zero(u), f, df + + if df < dg: + return q, r + + N = df - dg + 1 + lc_g = dmp_LC(g, K) + + while True: + lc_r = dmp_LC(r, K) + j, N = dr - dg, N - 1 + + Q = dmp_mul_term(q, lc_g, 0, u, K) + q = dmp_add_term(Q, lc_r, j, u, K) + + R = dmp_mul_term(r, lc_g, 0, u, K) + G = dmp_mul_term(g, lc_r, j, u, K) + r = dmp_sub(R, G, u, K) + + _dr, dr = dr, dmp_degree(r, u) + + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + c = dmp_pow(lc_g, N, u - 1, K) + + q = dmp_mul_term(q, c, 0, u, K) + r = dmp_mul_term(r, c, 0, u, K) + + return q, r + + +def dmp_prem(f, g, u, K): + """ + Polynomial pseudo-remainder in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_prem(x**2 + x*y, 2*x + 2) + -4*y + 4 + + """ + if not u: + return dup_prem(f, g, K) + + df = dmp_degree(f, u) + dg = dmp_degree(g, u) + + if dg < 0: + raise ZeroDivisionError("polynomial division") + + r, dr = f, df + + if df < dg: + return r + + N = df - dg + 1 + lc_g = dmp_LC(g, K) + + while True: + lc_r = dmp_LC(r, K) + j, N = dr - dg, N - 1 + + R = dmp_mul_term(r, lc_g, 0, u, K) + G = dmp_mul_term(g, lc_r, j, u, K) + r = dmp_sub(R, G, u, K) + + _dr, dr = dr, dmp_degree(r, u) + + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + c = dmp_pow(lc_g, N, u - 1, K) + + return dmp_mul_term(r, c, 0, u, K) + + +def dmp_pquo(f, g, u, K): + """ + Polynomial exact pseudo-quotient in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x**2 + x*y + >>> g = 2*x + 2*y + >>> h = 2*x + 2 + + >>> R.dmp_pquo(f, g) + 2*x + + >>> R.dmp_pquo(f, h) + 2*x + 2*y - 2 + + """ + return dmp_pdiv(f, g, u, K)[0] + + +def dmp_pexquo(f, g, u, K): + """ + Polynomial pseudo-quotient in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x**2 + x*y + >>> g = 2*x + 2*y + >>> h = 2*x + 2 + + >>> R.dmp_pexquo(f, g) + 2*x + + >>> R.dmp_pexquo(f, h) + Traceback (most recent call last): + ... + ExactQuotientFailed: [[2], [2]] does not divide [[1], [1, 0], []] + + """ + q, r = dmp_pdiv(f, g, u, K) + + if dmp_zero_p(r, u): + return q + else: + raise ExactQuotientFailed(f, g) + + +def dup_rr_div(f, g, K): + """ + Univariate division with remainder over a ring. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_rr_div(x**2 + 1, 2*x - 4) + (0, x**2 + 1) + + """ + df = dup_degree(f) + dg = dup_degree(g) + + q, r, dr = [], f, df + + if not g: + raise ZeroDivisionError("polynomial division") + elif df < dg: + return q, r + + lc_g = dup_LC(g, K) + + while True: + lc_r = dup_LC(r, K) + + if lc_r % lc_g: + break + + c = K.exquo(lc_r, lc_g) + j = dr - dg + + q = dup_add_term(q, c, j, K) + h = dup_mul_term(g, c, j, K) + r = dup_sub(r, h, K) + + _dr, dr = dr, dup_degree(r) + + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + return q, r + + +def dmp_rr_div(f, g, u, K): + """ + Multivariate division with remainder over a ring. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_rr_div(x**2 + x*y, 2*x + 2) + (0, x**2 + x*y) + + """ + if not u: + return dup_rr_div(f, g, K) + + df = dmp_degree(f, u) + dg = dmp_degree(g, u) + + if dg < 0: + raise ZeroDivisionError("polynomial division") + + q, r, dr = dmp_zero(u), f, df + + if df < dg: + return q, r + + lc_g, v = dmp_LC(g, K), u - 1 + + while True: + lc_r = dmp_LC(r, K) + c, R = dmp_rr_div(lc_r, lc_g, v, K) + + if not dmp_zero_p(R, v): + break + + j = dr - dg + + q = dmp_add_term(q, c, j, u, K) + h = dmp_mul_term(g, c, j, u, K) + r = dmp_sub(r, h, u, K) + + _dr, dr = dr, dmp_degree(r, u) + + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + return q, r + + +def dup_ff_div(f, g, K): + """ + Polynomial division with remainder over a field. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> R.dup_ff_div(x**2 + 1, 2*x - 4) + (1/2*x + 1, 5) + + """ + df = dup_degree(f) + dg = dup_degree(g) + + q, r, dr = [], f, df + + if not g: + raise ZeroDivisionError("polynomial division") + elif df < dg: + return q, r + + lc_g = dup_LC(g, K) + + while True: + lc_r = dup_LC(r, K) + + c = K.exquo(lc_r, lc_g) + j = dr - dg + + q = dup_add_term(q, c, j, K) + h = dup_mul_term(g, c, j, K) + r = dup_sub(r, h, K) + + _dr, dr = dr, dup_degree(r) + + if dr < dg: + break + elif dr == _dr and not K.is_Exact: + # remove leading term created by rounding error + r = dup_strip(r[1:]) + dr = dup_degree(r) + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + return q, r + + +def dmp_ff_div(f, g, u, K): + """ + Polynomial division with remainder over a field. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y = ring("x,y", QQ) + + >>> R.dmp_ff_div(x**2 + x*y, 2*x + 2) + (1/2*x + 1/2*y - 1/2, -y + 1) + + """ + if not u: + return dup_ff_div(f, g, K) + + df = dmp_degree(f, u) + dg = dmp_degree(g, u) + + if dg < 0: + raise ZeroDivisionError("polynomial division") + + q, r, dr = dmp_zero(u), f, df + + if df < dg: + return q, r + + lc_g, v = dmp_LC(g, K), u - 1 + + while True: + lc_r = dmp_LC(r, K) + c, R = dmp_ff_div(lc_r, lc_g, v, K) + + if not dmp_zero_p(R, v): + break + + j = dr - dg + + q = dmp_add_term(q, c, j, u, K) + h = dmp_mul_term(g, c, j, u, K) + r = dmp_sub(r, h, u, K) + + _dr, dr = dr, dmp_degree(r, u) + + if dr < dg: + break + elif not (dr < _dr): + raise PolynomialDivisionFailed(f, g, K) + + return q, r + + +def dup_div(f, g, K): + """ + Polynomial division with remainder in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x = ring("x", ZZ) + >>> R.dup_div(x**2 + 1, 2*x - 4) + (0, x**2 + 1) + + >>> R, x = ring("x", QQ) + >>> R.dup_div(x**2 + 1, 2*x - 4) + (1/2*x + 1, 5) + + """ + if K.is_Field: + return dup_ff_div(f, g, K) + else: + return dup_rr_div(f, g, K) + + +def dup_rem(f, g, K): + """ + Returns polynomial remainder in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x = ring("x", ZZ) + >>> R.dup_rem(x**2 + 1, 2*x - 4) + x**2 + 1 + + >>> R, x = ring("x", QQ) + >>> R.dup_rem(x**2 + 1, 2*x - 4) + 5 + + """ + return dup_div(f, g, K)[1] + + +def dup_quo(f, g, K): + """ + Returns exact polynomial quotient in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x = ring("x", ZZ) + >>> R.dup_quo(x**2 + 1, 2*x - 4) + 0 + + >>> R, x = ring("x", QQ) + >>> R.dup_quo(x**2 + 1, 2*x - 4) + 1/2*x + 1 + + """ + return dup_div(f, g, K)[0] + + +def dup_exquo(f, g, K): + """ + Returns polynomial quotient in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_exquo(x**2 - 1, x - 1) + x + 1 + + >>> R.dup_exquo(x**2 + 1, 2*x - 4) + Traceback (most recent call last): + ... + ExactQuotientFailed: [2, -4] does not divide [1, 0, 1] + + """ + q, r = dup_div(f, g, K) + + if not r: + return q + else: + raise ExactQuotientFailed(f, g) + + +def dmp_div(f, g, u, K): + """ + Polynomial division with remainder in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x,y = ring("x,y", ZZ) + >>> R.dmp_div(x**2 + x*y, 2*x + 2) + (0, x**2 + x*y) + + >>> R, x,y = ring("x,y", QQ) + >>> R.dmp_div(x**2 + x*y, 2*x + 2) + (1/2*x + 1/2*y - 1/2, -y + 1) + + """ + if K.is_Field: + return dmp_ff_div(f, g, u, K) + else: + return dmp_rr_div(f, g, u, K) + + +def dmp_rem(f, g, u, K): + """ + Returns polynomial remainder in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x,y = ring("x,y", ZZ) + >>> R.dmp_rem(x**2 + x*y, 2*x + 2) + x**2 + x*y + + >>> R, x,y = ring("x,y", QQ) + >>> R.dmp_rem(x**2 + x*y, 2*x + 2) + -y + 1 + + """ + return dmp_div(f, g, u, K)[1] + + +def dmp_quo(f, g, u, K): + """ + Returns exact polynomial quotient in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x,y = ring("x,y", ZZ) + >>> R.dmp_quo(x**2 + x*y, 2*x + 2) + 0 + + >>> R, x,y = ring("x,y", QQ) + >>> R.dmp_quo(x**2 + x*y, 2*x + 2) + 1/2*x + 1/2*y - 1/2 + + """ + return dmp_div(f, g, u, K)[0] + + +def dmp_exquo(f, g, u, K): + """ + Returns polynomial quotient in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x**2 + x*y + >>> g = x + y + >>> h = 2*x + 2 + + >>> R.dmp_exquo(f, g) + x + + >>> R.dmp_exquo(f, h) + Traceback (most recent call last): + ... + ExactQuotientFailed: [[2], [2]] does not divide [[1], [1, 0], []] + + """ + q, r = dmp_div(f, g, u, K) + + if dmp_zero_p(r, u): + return q + else: + raise ExactQuotientFailed(f, g) + + +def dup_max_norm(f, K): + """ + Returns maximum norm of a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_max_norm(-x**2 + 2*x - 3) + 3 + + """ + if not f: + return K.zero + else: + return max(dup_abs(f, K)) + + +def dmp_max_norm(f, u, K): + """ + Returns maximum norm of a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_max_norm(2*x*y - x - 3) + 3 + + """ + if not u: + return dup_max_norm(f, K) + + v = u - 1 + + return max(dmp_max_norm(c, v, K) for c in f) + + +def dup_l1_norm(f, K): + """ + Returns l1 norm of a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_l1_norm(2*x**3 - 3*x**2 + 1) + 6 + + """ + if not f: + return K.zero + else: + return sum(dup_abs(f, K)) + + +def dmp_l1_norm(f, u, K): + """ + Returns l1 norm of a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_l1_norm(2*x*y - x - 3) + 6 + + """ + if not u: + return dup_l1_norm(f, K) + + v = u - 1 + + return sum(dmp_l1_norm(c, v, K) for c in f) + + +def dup_l2_norm_squared(f, K): + """ + Returns squared l2 norm of a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_l2_norm_squared(2*x**3 - 3*x**2 + 1) + 14 + + """ + return sum([coeff**2 for coeff in f], K.zero) + + +def dmp_l2_norm_squared(f, u, K): + """ + Returns squared l2 norm of a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_l2_norm_squared(2*x*y - x - 3) + 14 + + """ + if not u: + return dup_l2_norm_squared(f, K) + + v = u - 1 + + return sum(dmp_l2_norm_squared(c, v, K) for c in f) + + +def dup_expand(polys, K): + """ + Multiply together several polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_expand([x**2 - 1, x, 2]) + 2*x**3 - 2*x + + """ + if not polys: + return [K.one] + + f = polys[0] + + for g in polys[1:]: + f = dup_mul(f, g, K) + + return f + + +def dmp_expand(polys, u, K): + """ + Multiply together several polynomials in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_expand([x**2 + y**2, x + 1]) + x**3 + x**2 + x*y**2 + y**2 + + """ + if not polys: + return dmp_one(u, K) + + f = polys[0] + + for g in polys[1:]: + f = dmp_mul(f, g, u, K) + + return f diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densebasic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densebasic.py new file mode 100644 index 0000000000000000000000000000000000000000..b3a8a9497302b1af5bca20de100b7ae41e96b439 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densebasic.py @@ -0,0 +1,1887 @@ +"""Basic tools for dense recursive polynomials in ``K[x]`` or ``K[X]``. """ + + +from sympy.core import igcd +from sympy.polys.monomials import monomial_min, monomial_div +from sympy.polys.orderings import monomial_key + +import random + + +ninf = float('-inf') + + +def poly_LC(f, K): + """ + Return leading coefficient of ``f``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import poly_LC + + >>> poly_LC([], ZZ) + 0 + >>> poly_LC([ZZ(1), ZZ(2), ZZ(3)], ZZ) + 1 + + """ + if not f: + return K.zero + else: + return f[0] + + +def poly_TC(f, K): + """ + Return trailing coefficient of ``f``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import poly_TC + + >>> poly_TC([], ZZ) + 0 + >>> poly_TC([ZZ(1), ZZ(2), ZZ(3)], ZZ) + 3 + + """ + if not f: + return K.zero + else: + return f[-1] + +dup_LC = dmp_LC = poly_LC +dup_TC = dmp_TC = poly_TC + + +def dmp_ground_LC(f, u, K): + """ + Return the ground leading coefficient. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_ground_LC + + >>> f = ZZ.map([[[1], [2, 3]]]) + + >>> dmp_ground_LC(f, 2, ZZ) + 1 + + """ + while u: + f = dmp_LC(f, K) + u -= 1 + + return dup_LC(f, K) + + +def dmp_ground_TC(f, u, K): + """ + Return the ground trailing coefficient. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_ground_TC + + >>> f = ZZ.map([[[1], [2, 3]]]) + + >>> dmp_ground_TC(f, 2, ZZ) + 3 + + """ + while u: + f = dmp_TC(f, K) + u -= 1 + + return dup_TC(f, K) + + +def dmp_true_LT(f, u, K): + """ + Return the leading term ``c * x_1**n_1 ... x_k**n_k``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_true_LT + + >>> f = ZZ.map([[4], [2, 0], [3, 0, 0]]) + + >>> dmp_true_LT(f, 1, ZZ) + ((2, 0), 4) + + """ + monom = [] + + while u: + monom.append(len(f) - 1) + f, u = f[0], u - 1 + + if not f: + monom.append(0) + else: + monom.append(len(f) - 1) + + return tuple(monom), dup_LC(f, K) + + +def dup_degree(f): + """ + Return the leading degree of ``f`` in ``K[x]``. + + Note that the degree of 0 is negative infinity (``float('-inf')``). + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_degree + + >>> f = ZZ.map([1, 2, 0, 3]) + + >>> dup_degree(f) + 3 + + """ + if not f: + return ninf + return len(f) - 1 + + +def dmp_degree(f, u): + """ + Return the leading degree of ``f`` in ``x_0`` in ``K[X]``. + + Note that the degree of 0 is negative infinity (``float('-inf')``). + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_degree + + >>> dmp_degree([[[]]], 2) + -inf + + >>> f = ZZ.map([[2], [1, 2, 3]]) + + >>> dmp_degree(f, 1) + 1 + + """ + if dmp_zero_p(f, u): + return ninf + else: + return len(f) - 1 + + +def _rec_degree_in(g, v, i, j): + """Recursive helper function for :func:`dmp_degree_in`.""" + if i == j: + return dmp_degree(g, v) + + v, i = v - 1, i + 1 + + return max(_rec_degree_in(c, v, i, j) for c in g) + + +def dmp_degree_in(f, j, u): + """ + Return the leading degree of ``f`` in ``x_j`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_degree_in + + >>> f = ZZ.map([[2], [1, 2, 3]]) + + >>> dmp_degree_in(f, 0, 1) + 1 + >>> dmp_degree_in(f, 1, 1) + 2 + + """ + if not j: + return dmp_degree(f, u) + if j < 0 or j > u: + raise IndexError("0 <= j <= %s expected, got %s" % (u, j)) + + return _rec_degree_in(f, u, 0, j) + + +def _rec_degree_list(g, v, i, degs): + """Recursive helper for :func:`dmp_degree_list`.""" + degs[i] = max(degs[i], dmp_degree(g, v)) + + if v > 0: + v, i = v - 1, i + 1 + + for c in g: + _rec_degree_list(c, v, i, degs) + + +def dmp_degree_list(f, u): + """ + Return a list of degrees of ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_degree_list + + >>> f = ZZ.map([[1], [1, 2, 3]]) + + >>> dmp_degree_list(f, 1) + (1, 2) + + """ + degs = [ninf]*(u + 1) + _rec_degree_list(f, u, 0, degs) + return tuple(degs) + + +def dup_strip(f): + """ + Remove leading zeros from ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.densebasic import dup_strip + + >>> dup_strip([0, 0, 1, 2, 3, 0]) + [1, 2, 3, 0] + + """ + if not f or f[0]: + return f + + i = 0 + + for cf in f: + if cf: + break + else: + i += 1 + + return f[i:] + + +def dmp_strip(f, u): + """ + Remove leading zeros from ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.densebasic import dmp_strip + + >>> dmp_strip([[], [0, 1, 2], [1]], 1) + [[0, 1, 2], [1]] + + """ + if not u: + return dup_strip(f) + + if dmp_zero_p(f, u): + return f + + i, v = 0, u - 1 + + for c in f: + if not dmp_zero_p(c, v): + break + else: + i += 1 + + if i == len(f): + return dmp_zero(u) + else: + return f[i:] + + +def _rec_validate(f, g, i, K): + """Recursive helper for :func:`dmp_validate`.""" + if not isinstance(g, list): + if K is not None and not K.of_type(g): + raise TypeError("%s in %s in not of type %s" % (g, f, K.dtype)) + + return {i - 1} + elif not g: + return {i} + else: + levels = set() + + for c in g: + levels |= _rec_validate(f, c, i + 1, K) + + return levels + + +def _rec_strip(g, v): + """Recursive helper for :func:`_rec_strip`.""" + if not v: + return dup_strip(g) + + w = v - 1 + + return dmp_strip([ _rec_strip(c, w) for c in g ], v) + + +def dmp_validate(f, K=None): + """ + Return the number of levels in ``f`` and recursively strip it. + + Examples + ======== + + >>> from sympy.polys.densebasic import dmp_validate + + >>> dmp_validate([[], [0, 1, 2], [1]]) + ([[1, 2], [1]], 1) + + >>> dmp_validate([[1], 1]) + Traceback (most recent call last): + ... + ValueError: invalid data structure for a multivariate polynomial + + """ + levels = _rec_validate(f, f, 0, K) + + u = levels.pop() + + if not levels: + return _rec_strip(f, u), u + else: + raise ValueError( + "invalid data structure for a multivariate polynomial") + + +def dup_reverse(f): + """ + Compute ``x**n * f(1/x)``, i.e.: reverse ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_reverse + + >>> f = ZZ.map([1, 2, 3, 0]) + + >>> dup_reverse(f) + [3, 2, 1] + + """ + return dup_strip(list(reversed(f))) + + +def dup_copy(f): + """ + Create a new copy of a polynomial ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_copy + + >>> f = ZZ.map([1, 2, 3, 0]) + + >>> dup_copy([1, 2, 3, 0]) + [1, 2, 3, 0] + + """ + return list(f) + + +def dmp_copy(f, u): + """ + Create a new copy of a polynomial ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_copy + + >>> f = ZZ.map([[1], [1, 2]]) + + >>> dmp_copy(f, 1) + [[1], [1, 2]] + + """ + if not u: + return list(f) + + v = u - 1 + + return [ dmp_copy(c, v) for c in f ] + + +def dup_to_tuple(f): + """ + Convert `f` into a tuple. + + This is needed for hashing. This is similar to dup_copy(). + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_copy + + >>> f = ZZ.map([1, 2, 3, 0]) + + >>> dup_copy([1, 2, 3, 0]) + [1, 2, 3, 0] + + """ + return tuple(f) + + +def dmp_to_tuple(f, u): + """ + Convert `f` into a nested tuple of tuples. + + This is needed for hashing. This is similar to dmp_copy(). + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_to_tuple + + >>> f = ZZ.map([[1], [1, 2]]) + + >>> dmp_to_tuple(f, 1) + ((1,), (1, 2)) + + """ + if not u: + return tuple(f) + v = u - 1 + + return tuple(dmp_to_tuple(c, v) for c in f) + + +def dup_normal(f, K): + """ + Normalize univariate polynomial in the given domain. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_normal + + >>> dup_normal([0, 1, 2, 3], ZZ) + [1, 2, 3] + + """ + return dup_strip([ K.normal(c) for c in f ]) + + +def dmp_normal(f, u, K): + """ + Normalize a multivariate polynomial in the given domain. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_normal + + >>> dmp_normal([[], [0, 1, 2]], 1, ZZ) + [[1, 2]] + + """ + if not u: + return dup_normal(f, K) + + v = u - 1 + + return dmp_strip([ dmp_normal(c, v, K) for c in f ], u) + + +def dup_convert(f, K0, K1): + """ + Convert the ground domain of ``f`` from ``K0`` to ``K1``. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_convert + + >>> R, x = ring("x", ZZ) + + >>> dup_convert([R(1), R(2)], R.to_domain(), ZZ) + [1, 2] + >>> dup_convert([ZZ(1), ZZ(2)], ZZ, R.to_domain()) + [1, 2] + + """ + if K0 is not None and K0 == K1: + return f + else: + return dup_strip([ K1.convert(c, K0) for c in f ]) + + +def dmp_convert(f, u, K0, K1): + """ + Convert the ground domain of ``f`` from ``K0`` to ``K1``. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_convert + + >>> R, x = ring("x", ZZ) + + >>> dmp_convert([[R(1)], [R(2)]], 1, R.to_domain(), ZZ) + [[1], [2]] + >>> dmp_convert([[ZZ(1)], [ZZ(2)]], 1, ZZ, R.to_domain()) + [[1], [2]] + + """ + if not u: + return dup_convert(f, K0, K1) + if K0 is not None and K0 == K1: + return f + + v = u - 1 + + return dmp_strip([ dmp_convert(c, v, K0, K1) for c in f ], u) + + +def dup_from_sympy(f, K): + """ + Convert the ground domain of ``f`` from SymPy to ``K``. + + Examples + ======== + + >>> from sympy import S + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_from_sympy + + >>> dup_from_sympy([S(1), S(2)], ZZ) == [ZZ(1), ZZ(2)] + True + + """ + return dup_strip([ K.from_sympy(c) for c in f ]) + + +def dmp_from_sympy(f, u, K): + """ + Convert the ground domain of ``f`` from SymPy to ``K``. + + Examples + ======== + + >>> from sympy import S + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_from_sympy + + >>> dmp_from_sympy([[S(1)], [S(2)]], 1, ZZ) == [[ZZ(1)], [ZZ(2)]] + True + + """ + if not u: + return dup_from_sympy(f, K) + + v = u - 1 + + return dmp_strip([ dmp_from_sympy(c, v, K) for c in f ], u) + + +def dup_nth(f, n, K): + """ + Return the ``n``-th coefficient of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_nth + + >>> f = ZZ.map([1, 2, 3]) + + >>> dup_nth(f, 0, ZZ) + 3 + >>> dup_nth(f, 4, ZZ) + 0 + + """ + if n < 0: + raise IndexError("'n' must be non-negative, got %i" % n) + elif n >= len(f): + return K.zero + else: + return f[dup_degree(f) - n] + + +def dmp_nth(f, n, u, K): + """ + Return the ``n``-th coefficient of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_nth + + >>> f = ZZ.map([[1], [2], [3]]) + + >>> dmp_nth(f, 0, 1, ZZ) + [3] + >>> dmp_nth(f, 4, 1, ZZ) + [] + + """ + if n < 0: + raise IndexError("'n' must be non-negative, got %i" % n) + elif n >= len(f): + return dmp_zero(u - 1) + else: + return f[dmp_degree(f, u) - n] + + +def dmp_ground_nth(f, N, u, K): + """ + Return the ground ``n``-th coefficient of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_ground_nth + + >>> f = ZZ.map([[1], [2, 3]]) + + >>> dmp_ground_nth(f, (0, 1), 1, ZZ) + 2 + + """ + v = u + + for n in N: + if n < 0: + raise IndexError("`n` must be non-negative, got %i" % n) + elif n >= len(f): + return K.zero + else: + d = dmp_degree(f, v) + if d == ninf: + d = -1 + f, v = f[d - n], v - 1 + + return f + + +def dmp_zero_p(f, u): + """ + Return ``True`` if ``f`` is zero in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.densebasic import dmp_zero_p + + >>> dmp_zero_p([[[[[]]]]], 4) + True + >>> dmp_zero_p([[[[[1]]]]], 4) + False + + """ + while u: + if len(f) != 1: + return False + + f = f[0] + u -= 1 + + return not f + + +def dmp_zero(u): + """ + Return a multivariate zero. + + Examples + ======== + + >>> from sympy.polys.densebasic import dmp_zero + + >>> dmp_zero(4) + [[[[[]]]]] + + """ + r = [] + + for i in range(u): + r = [r] + + return r + + +def dmp_one_p(f, u, K): + """ + Return ``True`` if ``f`` is one in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_one_p + + >>> dmp_one_p([[[ZZ(1)]]], 2, ZZ) + True + + """ + return dmp_ground_p(f, K.one, u) + + +def dmp_one(u, K): + """ + Return a multivariate one over ``K``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_one + + >>> dmp_one(2, ZZ) + [[[1]]] + + """ + return dmp_ground(K.one, u) + + +def dmp_ground_p(f, c, u): + """ + Return True if ``f`` is constant in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.densebasic import dmp_ground_p + + >>> dmp_ground_p([[[3]]], 3, 2) + True + >>> dmp_ground_p([[[4]]], None, 2) + True + + """ + if c is not None and not c: + return dmp_zero_p(f, u) + + while u: + if len(f) != 1: + return False + f = f[0] + u -= 1 + + if c is None: + return len(f) <= 1 + else: + return f == [c] + + +def dmp_ground(c, u): + """ + Return a multivariate constant. + + Examples + ======== + + >>> from sympy.polys.densebasic import dmp_ground + + >>> dmp_ground(3, 5) + [[[[[[3]]]]]] + >>> dmp_ground(1, -1) + 1 + + """ + if not c: + return dmp_zero(u) + + for i in range(u + 1): + c = [c] + + return c + + +def dmp_zeros(n, u, K): + """ + Return a list of multivariate zeros. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_zeros + + >>> dmp_zeros(3, 2, ZZ) + [[[[]]], [[[]]], [[[]]]] + >>> dmp_zeros(3, -1, ZZ) + [0, 0, 0] + + """ + if not n: + return [] + + if u < 0: + return [K.zero]*n + else: + return [ dmp_zero(u) for i in range(n) ] + + +def dmp_grounds(c, n, u): + """ + Return a list of multivariate constants. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_grounds + + >>> dmp_grounds(ZZ(4), 3, 2) + [[[[4]]], [[[4]]], [[[4]]]] + >>> dmp_grounds(ZZ(4), 3, -1) + [4, 4, 4] + + """ + if not n: + return [] + + if u < 0: + return [c]*n + else: + return [ dmp_ground(c, u) for i in range(n) ] + + +def dmp_negative_p(f, u, K): + """ + Return ``True`` if ``LC(f)`` is negative. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_negative_p + + >>> dmp_negative_p([[ZZ(1)], [-ZZ(1)]], 1, ZZ) + False + >>> dmp_negative_p([[-ZZ(1)], [ZZ(1)]], 1, ZZ) + True + + """ + return K.is_negative(dmp_ground_LC(f, u, K)) + + +def dmp_positive_p(f, u, K): + """ + Return ``True`` if ``LC(f)`` is positive. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_positive_p + + >>> dmp_positive_p([[ZZ(1)], [-ZZ(1)]], 1, ZZ) + True + >>> dmp_positive_p([[-ZZ(1)], [ZZ(1)]], 1, ZZ) + False + + """ + return K.is_positive(dmp_ground_LC(f, u, K)) + + +def dup_from_dict(f, K): + """ + Create a ``K[x]`` polynomial from a ``dict``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_from_dict + + >>> dup_from_dict({(0,): ZZ(7), (2,): ZZ(5), (4,): ZZ(1)}, ZZ) + [1, 0, 5, 0, 7] + >>> dup_from_dict({}, ZZ) + [] + + """ + if not f: + return [] + + n, h = max(f.keys()), [] + + if isinstance(n, int): + for k in range(n, -1, -1): + h.append(f.get(k, K.zero)) + else: + (n,) = n + + for k in range(n, -1, -1): + h.append(f.get((k,), K.zero)) + + return dup_strip(h) + + +def dup_from_raw_dict(f, K): + """ + Create a ``K[x]`` polynomial from a raw ``dict``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_from_raw_dict + + >>> dup_from_raw_dict({0: ZZ(7), 2: ZZ(5), 4: ZZ(1)}, ZZ) + [1, 0, 5, 0, 7] + + """ + if not f: + return [] + + n, h = max(f.keys()), [] + + for k in range(n, -1, -1): + h.append(f.get(k, K.zero)) + + return dup_strip(h) + + +def dmp_from_dict(f, u, K): + """ + Create a ``K[X]`` polynomial from a ``dict``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_from_dict + + >>> dmp_from_dict({(0, 0): ZZ(3), (0, 1): ZZ(2), (2, 1): ZZ(1)}, 1, ZZ) + [[1, 0], [], [2, 3]] + >>> dmp_from_dict({}, 0, ZZ) + [] + + """ + if not u: + return dup_from_dict(f, K) + if not f: + return dmp_zero(u) + + coeffs = {} + + for monom, coeff in f.items(): + head, tail = monom[0], monom[1:] + + if head in coeffs: + coeffs[head][tail] = coeff + else: + coeffs[head] = { tail: coeff } + + n, v, h = max(coeffs.keys()), u - 1, [] + + for k in range(n, -1, -1): + coeff = coeffs.get(k) + + if coeff is not None: + h.append(dmp_from_dict(coeff, v, K)) + else: + h.append(dmp_zero(v)) + + return dmp_strip(h, u) + + +def dup_to_dict(f, K=None, zero=False): + """ + Convert ``K[x]`` polynomial to a ``dict``. + + Examples + ======== + + >>> from sympy.polys.densebasic import dup_to_dict + + >>> dup_to_dict([1, 0, 5, 0, 7]) + {(0,): 7, (2,): 5, (4,): 1} + >>> dup_to_dict([]) + {} + + """ + if not f and zero: + return {(0,): K.zero} + + n, result = len(f) - 1, {} + + for k in range(0, n + 1): + if f[n - k]: + result[(k,)] = f[n - k] + + return result + + +def dup_to_raw_dict(f, K=None, zero=False): + """ + Convert a ``K[x]`` polynomial to a raw ``dict``. + + Examples + ======== + + >>> from sympy.polys.densebasic import dup_to_raw_dict + + >>> dup_to_raw_dict([1, 0, 5, 0, 7]) + {0: 7, 2: 5, 4: 1} + + """ + if not f and zero: + return {0: K.zero} + + n, result = len(f) - 1, {} + + for k in range(0, n + 1): + if f[n - k]: + result[k] = f[n - k] + + return result + + +def dmp_to_dict(f, u, K=None, zero=False): + """ + Convert a ``K[X]`` polynomial to a ``dict````. + + Examples + ======== + + >>> from sympy.polys.densebasic import dmp_to_dict + + >>> dmp_to_dict([[1, 0], [], [2, 3]], 1) + {(0, 0): 3, (0, 1): 2, (2, 1): 1} + >>> dmp_to_dict([], 0) + {} + + """ + if not u: + return dup_to_dict(f, K, zero=zero) + + if dmp_zero_p(f, u) and zero: + return {(0,)*(u + 1): K.zero} + + n, v, result = dmp_degree(f, u), u - 1, {} + + if n == ninf: + n = -1 + + for k in range(0, n + 1): + h = dmp_to_dict(f[n - k], v) + + for exp, coeff in h.items(): + result[(k,) + exp] = coeff + + return result + + +def dmp_swap(f, i, j, u, K): + """ + Transform ``K[..x_i..x_j..]`` to ``K[..x_j..x_i..]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_swap + + >>> f = ZZ.map([[[2], [1, 0]], []]) + + >>> dmp_swap(f, 0, 1, 2, ZZ) + [[[2], []], [[1, 0], []]] + >>> dmp_swap(f, 1, 2, 2, ZZ) + [[[1], [2, 0]], [[]]] + >>> dmp_swap(f, 0, 2, 2, ZZ) + [[[1, 0]], [[2, 0], []]] + + """ + if i < 0 or j < 0 or i > u or j > u: + raise IndexError("0 <= i < j <= %s expected" % u) + elif i == j: + return f + + F, H = dmp_to_dict(f, u), {} + + for exp, coeff in F.items(): + H[exp[:i] + (exp[j],) + + exp[i + 1:j] + + (exp[i],) + exp[j + 1:]] = coeff + + return dmp_from_dict(H, u, K) + + +def dmp_permute(f, P, u, K): + """ + Return a polynomial in ``K[x_{P(1)},..,x_{P(n)}]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_permute + + >>> f = ZZ.map([[[2], [1, 0]], []]) + + >>> dmp_permute(f, [1, 0, 2], 2, ZZ) + [[[2], []], [[1, 0], []]] + >>> dmp_permute(f, [1, 2, 0], 2, ZZ) + [[[1], []], [[2, 0], []]] + + """ + F, H = dmp_to_dict(f, u), {} + + for exp, coeff in F.items(): + new_exp = [0]*len(exp) + + for e, p in zip(exp, P): + new_exp[p] = e + + H[tuple(new_exp)] = coeff + + return dmp_from_dict(H, u, K) + + +def dmp_nest(f, l, K): + """ + Return a multivariate value nested ``l``-levels. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_nest + + >>> dmp_nest([[ZZ(1)]], 2, ZZ) + [[[[1]]]] + + """ + if not isinstance(f, list): + return dmp_ground(f, l) + + for i in range(l): + f = [f] + + return f + + +def dmp_raise(f, l, u, K): + """ + Return a multivariate polynomial raised ``l``-levels. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_raise + + >>> f = ZZ.map([[], [1, 2]]) + + >>> dmp_raise(f, 2, 1, ZZ) + [[[[]]], [[[1]], [[2]]]] + + """ + if not l: + return f + + if not u: + if not f: + return dmp_zero(l) + + k = l - 1 + + return [ dmp_ground(c, k) for c in f ] + + v = u - 1 + + return [ dmp_raise(c, l, v, K) for c in f ] + + +def dup_deflate(f, K): + """ + Map ``x**m`` to ``y`` in a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_deflate + + >>> f = ZZ.map([1, 0, 0, 1, 0, 0, 1]) + + >>> dup_deflate(f, ZZ) + (3, [1, 1, 1]) + + """ + if dup_degree(f) <= 0: + return 1, f + + g = 0 + + for i in range(len(f)): + if not f[-i - 1]: + continue + + g = igcd(g, i) + + if g == 1: + return 1, f + + return g, f[::g] + + +def dmp_deflate(f, u, K): + """ + Map ``x_i**m_i`` to ``y_i`` in a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_deflate + + >>> f = ZZ.map([[1, 0, 0, 2], [], [3, 0, 0, 4]]) + + >>> dmp_deflate(f, 1, ZZ) + ((2, 3), [[1, 2], [3, 4]]) + + """ + if dmp_zero_p(f, u): + return (1,)*(u + 1), f + + F = dmp_to_dict(f, u) + B = [0]*(u + 1) + + for M in F.keys(): + for i, m in enumerate(M): + B[i] = igcd(B[i], m) + + for i, b in enumerate(B): + if not b: + B[i] = 1 + + B = tuple(B) + + if all(b == 1 for b in B): + return B, f + + H = {} + + for A, coeff in F.items(): + N = [ a // b for a, b in zip(A, B) ] + H[tuple(N)] = coeff + + return B, dmp_from_dict(H, u, K) + + +def dup_multi_deflate(polys, K): + """ + Map ``x**m`` to ``y`` in a set of polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_multi_deflate + + >>> f = ZZ.map([1, 0, 2, 0, 3]) + >>> g = ZZ.map([4, 0, 0]) + + >>> dup_multi_deflate((f, g), ZZ) + (2, ([1, 2, 3], [4, 0])) + + """ + G = 0 + + for p in polys: + if dup_degree(p) <= 0: + return 1, polys + + g = 0 + + for i in range(len(p)): + if not p[-i - 1]: + continue + + g = igcd(g, i) + + if g == 1: + return 1, polys + + G = igcd(G, g) + + return G, tuple([ p[::G] for p in polys ]) + + +def dmp_multi_deflate(polys, u, K): + """ + Map ``x_i**m_i`` to ``y_i`` in a set of polynomials in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_multi_deflate + + >>> f = ZZ.map([[1, 0, 0, 2], [], [3, 0, 0, 4]]) + >>> g = ZZ.map([[1, 0, 2], [], [3, 0, 4]]) + + >>> dmp_multi_deflate((f, g), 1, ZZ) + ((2, 1), ([[1, 0, 0, 2], [3, 0, 0, 4]], [[1, 0, 2], [3, 0, 4]])) + + """ + if not u: + M, H = dup_multi_deflate(polys, K) + return (M,), H + + F, B = [], [0]*(u + 1) + + for p in polys: + f = dmp_to_dict(p, u) + + if not dmp_zero_p(p, u): + for M in f.keys(): + for i, m in enumerate(M): + B[i] = igcd(B[i], m) + + F.append(f) + + for i, b in enumerate(B): + if not b: + B[i] = 1 + + B = tuple(B) + + if all(b == 1 for b in B): + return B, polys + + H = [] + + for f in F: + h = {} + + for A, coeff in f.items(): + N = [ a // b for a, b in zip(A, B) ] + h[tuple(N)] = coeff + + H.append(dmp_from_dict(h, u, K)) + + return B, tuple(H) + + +def dup_inflate(f, m, K): + """ + Map ``y`` to ``x**m`` in a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_inflate + + >>> f = ZZ.map([1, 1, 1]) + + >>> dup_inflate(f, 3, ZZ) + [1, 0, 0, 1, 0, 0, 1] + + """ + if m <= 0: + raise IndexError("'m' must be positive, got %s" % m) + if m == 1 or not f: + return f + + result = [f[0]] + + for coeff in f[1:]: + result.extend([K.zero]*(m - 1)) + result.append(coeff) + + return result + + +def _rec_inflate(g, M, v, i, K): + """Recursive helper for :func:`dmp_inflate`.""" + if not v: + return dup_inflate(g, M[i], K) + if M[i] <= 0: + raise IndexError("all M[i] must be positive, got %s" % M[i]) + + w, j = v - 1, i + 1 + + g = [ _rec_inflate(c, M, w, j, K) for c in g ] + + result = [g[0]] + + for coeff in g[1:]: + for _ in range(1, M[i]): + result.append(dmp_zero(w)) + + result.append(coeff) + + return result + + +def dmp_inflate(f, M, u, K): + """ + Map ``y_i`` to ``x_i**k_i`` in a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_inflate + + >>> f = ZZ.map([[1, 2], [3, 4]]) + + >>> dmp_inflate(f, (2, 3), 1, ZZ) + [[1, 0, 0, 2], [], [3, 0, 0, 4]] + + """ + if not u: + return dup_inflate(f, M[0], K) + + if all(m == 1 for m in M): + return f + else: + return _rec_inflate(f, M, u, 0, K) + + +def dmp_exclude(f, u, K): + """ + Exclude useless levels from ``f``. + + Return the levels excluded, the new excluded ``f``, and the new ``u``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_exclude + + >>> f = ZZ.map([[[1]], [[1], [2]]]) + + >>> dmp_exclude(f, 2, ZZ) + ([2], [[1], [1, 2]], 1) + + """ + if not u or dmp_ground_p(f, None, u): + return [], f, u + + J, F = [], dmp_to_dict(f, u) + + for j in range(0, u + 1): + for monom in F.keys(): + if monom[j]: + break + else: + J.append(j) + + if not J: + return [], f, u + + f = {} + + for monom, coeff in F.items(): + monom = list(monom) + + for j in reversed(J): + del monom[j] + + f[tuple(monom)] = coeff + + u -= len(J) + + return J, dmp_from_dict(f, u, K), u + + +def dmp_include(f, J, u, K): + """ + Include useless levels in ``f``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_include + + >>> f = ZZ.map([[1], [1, 2]]) + + >>> dmp_include(f, [2], 1, ZZ) + [[[1]], [[1], [2]]] + + """ + if not J: + return f + + F, f = dmp_to_dict(f, u), {} + + for monom, coeff in F.items(): + monom = list(monom) + + for j in J: + monom.insert(j, 0) + + f[tuple(monom)] = coeff + + u += len(J) + + return dmp_from_dict(f, u, K) + + +def dmp_inject(f, u, K, front=False): + """ + Convert ``f`` from ``K[X][Y]`` to ``K[X,Y]``. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_inject + + >>> R, x,y = ring("x,y", ZZ) + + >>> dmp_inject([R(1), x + 2], 0, R.to_domain()) + ([[[1]], [[1], [2]]], 2) + >>> dmp_inject([R(1), x + 2], 0, R.to_domain(), front=True) + ([[[1]], [[1, 2]]], 2) + + """ + f, h = dmp_to_dict(f, u), {} + + v = K.ngens - 1 + + for f_monom, g in f.items(): + g = g.to_dict() + + for g_monom, c in g.items(): + if front: + h[g_monom + f_monom] = c + else: + h[f_monom + g_monom] = c + + w = u + v + 1 + + return dmp_from_dict(h, w, K.dom), w + + +def dmp_eject(f, u, K, front=False): + """ + Convert ``f`` from ``K[X,Y]`` to ``K[X][Y]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_eject + + >>> dmp_eject([[[1]], [[1], [2]]], 2, ZZ['x', 'y']) + [1, x + 2] + + """ + f, h = dmp_to_dict(f, u), {} + + n = K.ngens + v = u - K.ngens + 1 + + for monom, c in f.items(): + if front: + g_monom, f_monom = monom[:n], monom[n:] + else: + g_monom, f_monom = monom[-n:], monom[:-n] + + if f_monom in h: + h[f_monom][g_monom] = c + else: + h[f_monom] = {g_monom: c} + + for monom, c in h.items(): + h[monom] = K(c) + + return dmp_from_dict(h, v - 1, K) + + +def dup_terms_gcd(f, K): + """ + Remove GCD of terms from ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_terms_gcd + + >>> f = ZZ.map([1, 0, 1, 0, 0]) + + >>> dup_terms_gcd(f, ZZ) + (2, [1, 0, 1]) + + """ + if dup_TC(f, K) or not f: + return 0, f + + i = 0 + + for c in reversed(f): + if not c: + i += 1 + else: + break + + return i, f[:-i] + + +def dmp_terms_gcd(f, u, K): + """ + Remove GCD of terms from ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_terms_gcd + + >>> f = ZZ.map([[1, 0], [1, 0, 0], [], []]) + + >>> dmp_terms_gcd(f, 1, ZZ) + ((2, 1), [[1], [1, 0]]) + + """ + if dmp_ground_TC(f, u, K) or dmp_zero_p(f, u): + return (0,)*(u + 1), f + + F = dmp_to_dict(f, u) + G = monomial_min(*list(F.keys())) + + if all(g == 0 for g in G): + return G, f + + f = {} + + for monom, coeff in F.items(): + f[monomial_div(monom, G)] = coeff + + return G, dmp_from_dict(f, u, K) + + +def _rec_list_terms(g, v, monom): + """Recursive helper for :func:`dmp_list_terms`.""" + d, terms = dmp_degree(g, v), [] + + if not v: + for i, c in enumerate(g): + if not c: + continue + + terms.append((monom + (d - i,), c)) + else: + w = v - 1 + + for i, c in enumerate(g): + terms.extend(_rec_list_terms(c, w, monom + (d - i,))) + + return terms + + +def dmp_list_terms(f, u, K, order=None): + """ + List all non-zero terms from ``f`` in the given order ``order``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_list_terms + + >>> f = ZZ.map([[1, 1], [2, 3]]) + + >>> dmp_list_terms(f, 1, ZZ) + [((1, 1), 1), ((1, 0), 1), ((0, 1), 2), ((0, 0), 3)] + >>> dmp_list_terms(f, 1, ZZ, order='grevlex') + [((1, 1), 1), ((1, 0), 1), ((0, 1), 2), ((0, 0), 3)] + + """ + def sort(terms, O): + return sorted(terms, key=lambda term: O(term[0]), reverse=True) + + terms = _rec_list_terms(f, u, ()) + + if not terms: + return [((0,)*(u + 1), K.zero)] + + if order is None: + return terms + else: + return sort(terms, monomial_key(order)) + + +def dup_apply_pairs(f, g, h, args, K): + """ + Apply ``h`` to pairs of coefficients of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_apply_pairs + + >>> h = lambda x, y, z: 2*x + y - z + + >>> dup_apply_pairs([1, 2, 3], [3, 2, 1], h, (1,), ZZ) + [4, 5, 6] + + """ + n, m = len(f), len(g) + + if n != m: + if n > m: + g = [K.zero]*(n - m) + g + else: + f = [K.zero]*(m - n) + f + + result = [] + + for a, b in zip(f, g): + result.append(h(a, b, *args)) + + return dup_strip(result) + + +def dmp_apply_pairs(f, g, h, args, u, K): + """ + Apply ``h`` to pairs of coefficients of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dmp_apply_pairs + + >>> h = lambda x, y, z: 2*x + y - z + + >>> dmp_apply_pairs([[1], [2, 3]], [[3], [2, 1]], h, (1,), 1, ZZ) + [[4], [5, 6]] + + """ + if not u: + return dup_apply_pairs(f, g, h, args, K) + + n, m, v = len(f), len(g), u - 1 + + if n != m: + if n > m: + g = dmp_zeros(n - m, v, K) + g + else: + f = dmp_zeros(m - n, v, K) + f + + result = [] + + for a, b in zip(f, g): + result.append(dmp_apply_pairs(a, b, h, args, v, K)) + + return dmp_strip(result, u) + + +def dup_slice(f, m, n, K): + """Take a continuous subsequence of terms of ``f`` in ``K[x]``. """ + k = len(f) + + if k >= m: + M = k - m + else: + M = 0 + if k >= n: + N = k - n + else: + N = 0 + + f = f[N:M] + + while f and f[0] == K.zero: + f.pop(0) + + if not f: + return [] + else: + return f + [K.zero]*m + + +def dmp_slice(f, m, n, u, K): + """Take a continuous subsequence of terms of ``f`` in ``K[X]``. """ + return dmp_slice_in(f, m, n, 0, u, K) + + +def dmp_slice_in(f, m, n, j, u, K): + """Take a continuous subsequence of terms of ``f`` in ``x_j`` in ``K[X]``. """ + if j < 0 or j > u: + raise IndexError("-%s <= j < %s expected, got %s" % (u, u, j)) + + if not u: + return dup_slice(f, m, n, K) + + f, g = dmp_to_dict(f, u), {} + + for monom, coeff in f.items(): + k = monom[j] + + if k < m or k >= n: + monom = monom[:j] + (0,) + monom[j + 1:] + + if monom in g: + g[monom] += coeff + else: + g[monom] = coeff + + return dmp_from_dict(g, u, K) + + +def dup_random(n, a, b, K): + """ + Return a polynomial of degree ``n`` with coefficients in ``[a, b]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.densebasic import dup_random + + >>> dup_random(3, -10, 10, ZZ) #doctest: +SKIP + [-2, -8, 9, -4] + + """ + f = [ K.convert(random.randint(a, b)) for _ in range(0, n + 1) ] + + while not f[0]: + f[0] = K.convert(random.randint(a, b)) + + return f diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densetools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densetools.py new file mode 100644 index 0000000000000000000000000000000000000000..122bf778a4843847be6db17708887416ba458f49 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/densetools.py @@ -0,0 +1,1438 @@ +"""Advanced tools for dense recursive polynomials in ``K[x]`` or ``K[X]``. """ + + +from sympy.polys.densearith import ( + dup_add_term, dmp_add_term, + dup_lshift, + dup_add, dmp_add, + dup_sub, dmp_sub, + dup_mul, dmp_mul, + dup_sqr, + dup_div, + dup_rem, dmp_rem, + dup_mul_ground, dmp_mul_ground, + dup_quo_ground, dmp_quo_ground, + dup_exquo_ground, dmp_exquo_ground, +) +from sympy.polys.densebasic import ( + dup_strip, dmp_strip, + dup_convert, dmp_convert, + dup_degree, dmp_degree, + dmp_to_dict, + dmp_from_dict, + dup_LC, dmp_LC, dmp_ground_LC, + dup_TC, dmp_TC, + dmp_zero, dmp_ground, + dmp_zero_p, + dup_to_raw_dict, dup_from_raw_dict, + dmp_zeros, + dmp_include, +) +from sympy.polys.polyerrors import ( + MultivariatePolynomialError, + DomainError +) + +from math import ceil as _ceil, log2 as _log2 + + +def dup_integrate(f, m, K): + """ + Computes the indefinite integral of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> R.dup_integrate(x**2 + 2*x, 1) + 1/3*x**3 + x**2 + >>> R.dup_integrate(x**2 + 2*x, 2) + 1/12*x**4 + 1/3*x**3 + + """ + if m <= 0 or not f: + return f + + g = [K.zero]*m + + for i, c in enumerate(reversed(f)): + n = i + 1 + + for j in range(1, m): + n *= i + j + 1 + + g.insert(0, K.exquo(c, K(n))) + + return g + + +def dmp_integrate(f, m, u, K): + """ + Computes the indefinite integral of ``f`` in ``x_0`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y = ring("x,y", QQ) + + >>> R.dmp_integrate(x + 2*y, 1) + 1/2*x**2 + 2*x*y + >>> R.dmp_integrate(x + 2*y, 2) + 1/6*x**3 + x**2*y + + """ + if not u: + return dup_integrate(f, m, K) + + if m <= 0 or dmp_zero_p(f, u): + return f + + g, v = dmp_zeros(m, u - 1, K), u - 1 + + for i, c in enumerate(reversed(f)): + n = i + 1 + + for j in range(1, m): + n *= i + j + 1 + + g.insert(0, dmp_quo_ground(c, K(n), v, K)) + + return g + + +def _rec_integrate_in(g, m, v, i, j, K): + """Recursive helper for :func:`dmp_integrate_in`.""" + if i == j: + return dmp_integrate(g, m, v, K) + + w, i = v - 1, i + 1 + + return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c in g ], v) + + +def dmp_integrate_in(f, m, j, u, K): + """ + Computes the indefinite integral of ``f`` in ``x_j`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y = ring("x,y", QQ) + + >>> R.dmp_integrate_in(x + 2*y, 1, 0) + 1/2*x**2 + 2*x*y + >>> R.dmp_integrate_in(x + 2*y, 1, 1) + x*y + y**2 + + """ + if j < 0 or j > u: + raise IndexError("0 <= j <= u expected, got u = %d, j = %d" % (u, j)) + + return _rec_integrate_in(f, m, u, 0, j, K) + + +def dup_diff(f, m, K): + """ + ``m``-th order derivative of a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_diff(x**3 + 2*x**2 + 3*x + 4, 1) + 3*x**2 + 4*x + 3 + >>> R.dup_diff(x**3 + 2*x**2 + 3*x + 4, 2) + 6*x + 4 + + """ + if m <= 0: + return f + + n = dup_degree(f) + + if n < m: + return [] + + deriv = [] + + if m == 1: + for coeff in f[:-m]: + deriv.append(K(n)*coeff) + n -= 1 + else: + for coeff in f[:-m]: + k = n + + for i in range(n - 1, n - m, -1): + k *= i + + deriv.append(K(k)*coeff) + n -= 1 + + return dup_strip(deriv) + + +def dmp_diff(f, m, u, K): + """ + ``m``-th order derivative in ``x_0`` of a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1 + + >>> R.dmp_diff(f, 1) + y**2 + 2*y + 3 + >>> R.dmp_diff(f, 2) + 0 + + """ + if not u: + return dup_diff(f, m, K) + if m <= 0: + return f + + n = dmp_degree(f, u) + + if n < m: + return dmp_zero(u) + + deriv, v = [], u - 1 + + if m == 1: + for coeff in f[:-m]: + deriv.append(dmp_mul_ground(coeff, K(n), v, K)) + n -= 1 + else: + for coeff in f[:-m]: + k = n + + for i in range(n - 1, n - m, -1): + k *= i + + deriv.append(dmp_mul_ground(coeff, K(k), v, K)) + n -= 1 + + return dmp_strip(deriv, u) + + +def _rec_diff_in(g, m, v, i, j, K): + """Recursive helper for :func:`dmp_diff_in`.""" + if i == j: + return dmp_diff(g, m, v, K) + + w, i = v - 1, i + 1 + + return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c in g ], v) + + +def dmp_diff_in(f, m, j, u, K): + """ + ``m``-th order derivative in ``x_j`` of a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1 + + >>> R.dmp_diff_in(f, 1, 0) + y**2 + 2*y + 3 + >>> R.dmp_diff_in(f, 1, 1) + 2*x*y + 2*x + 4*y + 3 + + """ + if j < 0 or j > u: + raise IndexError("0 <= j <= %s expected, got %s" % (u, j)) + + return _rec_diff_in(f, m, u, 0, j, K) + + +def dup_eval(f, a, K): + """ + Evaluate a polynomial at ``x = a`` in ``K[x]`` using Horner scheme. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_eval(x**2 + 2*x + 3, 2) + 11 + + """ + if not a: + return K.convert(dup_TC(f, K)) + + result = K.zero + + for c in f: + result *= a + result += c + + return result + + +def dmp_eval(f, a, u, K): + """ + Evaluate a polynomial at ``x_0 = a`` in ``K[X]`` using the Horner scheme. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_eval(2*x*y + 3*x + y + 2, 2) + 5*y + 8 + + """ + if not u: + return dup_eval(f, a, K) + + if not a: + return dmp_TC(f, K) + + result, v = dmp_LC(f, K), u - 1 + + for coeff in f[1:]: + result = dmp_mul_ground(result, a, v, K) + result = dmp_add(result, coeff, v, K) + + return result + + +def _rec_eval_in(g, a, v, i, j, K): + """Recursive helper for :func:`dmp_eval_in`.""" + if i == j: + return dmp_eval(g, a, v, K) + + v, i = v - 1, i + 1 + + return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ], v) + + +def dmp_eval_in(f, a, j, u, K): + """ + Evaluate a polynomial at ``x_j = a`` in ``K[X]`` using the Horner scheme. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 2*x*y + 3*x + y + 2 + + >>> R.dmp_eval_in(f, 2, 0) + 5*y + 8 + >>> R.dmp_eval_in(f, 2, 1) + 7*x + 4 + + """ + if j < 0 or j > u: + raise IndexError("0 <= j <= %s expected, got %s" % (u, j)) + + return _rec_eval_in(f, a, u, 0, j, K) + + +def _rec_eval_tail(g, i, A, u, K): + """Recursive helper for :func:`dmp_eval_tail`.""" + if i == u: + return dup_eval(g, A[-1], K) + else: + h = [ _rec_eval_tail(c, i + 1, A, u, K) for c in g ] + + if i < u - len(A) + 1: + return h + else: + return dup_eval(h, A[-u + i - 1], K) + + +def dmp_eval_tail(f, A, u, K): + """ + Evaluate a polynomial at ``x_j = a_j, ...`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 2*x*y + 3*x + y + 2 + + >>> R.dmp_eval_tail(f, [2]) + 7*x + 4 + >>> R.dmp_eval_tail(f, [2, 2]) + 18 + + """ + if not A: + return f + + if dmp_zero_p(f, u): + return dmp_zero(u - len(A)) + + e = _rec_eval_tail(f, 0, A, u, K) + + if u == len(A) - 1: + return e + else: + return dmp_strip(e, u - len(A)) + + +def _rec_diff_eval(g, m, a, v, i, j, K): + """Recursive helper for :func:`dmp_diff_eval`.""" + if i == j: + return dmp_eval(dmp_diff(g, m, v, K), a, v, K) + + v, i = v - 1, i + 1 + + return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in g ], v) + + +def dmp_diff_eval_in(f, m, a, j, u, K): + """ + Differentiate and evaluate a polynomial in ``x_j`` at ``a`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1 + + >>> R.dmp_diff_eval_in(f, 1, 2, 0) + y**2 + 2*y + 3 + >>> R.dmp_diff_eval_in(f, 1, 2, 1) + 6*x + 11 + + """ + if j > u: + raise IndexError("-%s <= j < %s expected, got %s" % (u, u, j)) + if not j: + return dmp_eval(dmp_diff(f, m, u, K), a, u, K) + + return _rec_diff_eval(f, m, a, u, 0, j, K) + + +def dup_trunc(f, p, K): + """ + Reduce a ``K[x]`` polynomial modulo a constant ``p`` in ``K``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_trunc(2*x**3 + 3*x**2 + 5*x + 7, ZZ(3)) + -x**3 - x + 1 + + """ + if K.is_ZZ: + g = [] + + for c in f: + c = c % p + + if c > p // 2: + g.append(c - p) + else: + g.append(c) + elif K.is_FiniteField: + # XXX: python-flint's nmod does not support % + pi = int(p) + g = [ K(int(c) % pi) for c in f ] + else: + g = [ c % p for c in f ] + + return dup_strip(g) + + +def dmp_trunc(f, p, u, K): + """ + Reduce a ``K[X]`` polynomial modulo a polynomial ``p`` in ``K[Y]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3 + >>> g = (y - 1).drop(x) + + >>> R.dmp_trunc(f, g) + 11*x**2 + 11*x + 5 + + """ + return dmp_strip([ dmp_rem(c, p, u - 1, K) for c in f ], u) + + +def dmp_ground_trunc(f, p, u, K): + """ + Reduce a ``K[X]`` polynomial modulo a constant ``p`` in ``K``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3 + + >>> R.dmp_ground_trunc(f, ZZ(3)) + -x**2 - x*y - y + + """ + if not u: + return dup_trunc(f, p, K) + + v = u - 1 + + return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f ], u) + + +def dup_monic(f, K): + """ + Divide all coefficients by ``LC(f)`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x = ring("x", ZZ) + >>> R.dup_monic(3*x**2 + 6*x + 9) + x**2 + 2*x + 3 + + >>> R, x = ring("x", QQ) + >>> R.dup_monic(3*x**2 + 4*x + 2) + x**2 + 4/3*x + 2/3 + + """ + if not f: + return f + + lc = dup_LC(f, K) + + if K.is_one(lc): + return f + else: + return dup_exquo_ground(f, lc, K) + + +def dmp_ground_monic(f, u, K): + """ + Divide all coefficients by ``LC(f)`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x,y = ring("x,y", ZZ) + >>> f = 3*x**2*y + 6*x**2 + 3*x*y + 9*y + 3 + + >>> R.dmp_ground_monic(f) + x**2*y + 2*x**2 + x*y + 3*y + 1 + + >>> R, x,y = ring("x,y", QQ) + >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3 + + >>> R.dmp_ground_monic(f) + x**2*y + 8/3*x**2 + 5/3*x*y + 2*x + 2/3*y + 1 + + """ + if not u: + return dup_monic(f, K) + + if dmp_zero_p(f, u): + return f + + lc = dmp_ground_LC(f, u, K) + + if K.is_one(lc): + return f + else: + return dmp_exquo_ground(f, lc, u, K) + + +def dup_content(f, K): + """ + Compute the GCD of coefficients of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x = ring("x", ZZ) + >>> f = 6*x**2 + 8*x + 12 + + >>> R.dup_content(f) + 2 + + >>> R, x = ring("x", QQ) + >>> f = 6*x**2 + 8*x + 12 + + >>> R.dup_content(f) + 2 + + """ + from sympy.polys.domains import QQ + + if not f: + return K.zero + + cont = K.zero + + if K == QQ: + for c in f: + cont = K.gcd(cont, c) + else: + for c in f: + cont = K.gcd(cont, c) + + if K.is_one(cont): + break + + return cont + + +def dmp_ground_content(f, u, K): + """ + Compute the GCD of coefficients of ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x,y = ring("x,y", ZZ) + >>> f = 2*x*y + 6*x + 4*y + 12 + + >>> R.dmp_ground_content(f) + 2 + + >>> R, x,y = ring("x,y", QQ) + >>> f = 2*x*y + 6*x + 4*y + 12 + + >>> R.dmp_ground_content(f) + 2 + + """ + from sympy.polys.domains import QQ + + if not u: + return dup_content(f, K) + + if dmp_zero_p(f, u): + return K.zero + + cont, v = K.zero, u - 1 + + if K == QQ: + for c in f: + cont = K.gcd(cont, dmp_ground_content(c, v, K)) + else: + for c in f: + cont = K.gcd(cont, dmp_ground_content(c, v, K)) + + if K.is_one(cont): + break + + return cont + + +def dup_primitive(f, K): + """ + Compute content and the primitive form of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x = ring("x", ZZ) + >>> f = 6*x**2 + 8*x + 12 + + >>> R.dup_primitive(f) + (2, 3*x**2 + 4*x + 6) + + >>> R, x = ring("x", QQ) + >>> f = 6*x**2 + 8*x + 12 + + >>> R.dup_primitive(f) + (2, 3*x**2 + 4*x + 6) + + """ + if not f: + return K.zero, f + + cont = dup_content(f, K) + + if K.is_one(cont): + return cont, f + else: + return cont, dup_quo_ground(f, cont, K) + + +def dmp_ground_primitive(f, u, K): + """ + Compute content and the primitive form of ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ, QQ + + >>> R, x,y = ring("x,y", ZZ) + >>> f = 2*x*y + 6*x + 4*y + 12 + + >>> R.dmp_ground_primitive(f) + (2, x*y + 3*x + 2*y + 6) + + >>> R, x,y = ring("x,y", QQ) + >>> f = 2*x*y + 6*x + 4*y + 12 + + >>> R.dmp_ground_primitive(f) + (2, x*y + 3*x + 2*y + 6) + + """ + if not u: + return dup_primitive(f, K) + + if dmp_zero_p(f, u): + return K.zero, f + + cont = dmp_ground_content(f, u, K) + + if K.is_one(cont): + return cont, f + else: + return cont, dmp_quo_ground(f, cont, u, K) + + +def dup_extract(f, g, K): + """ + Extract common content from a pair of polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_extract(6*x**2 + 12*x + 18, 4*x**2 + 8*x + 12) + (2, 3*x**2 + 6*x + 9, 2*x**2 + 4*x + 6) + + """ + fc = dup_content(f, K) + gc = dup_content(g, K) + + gcd = K.gcd(fc, gc) + + if not K.is_one(gcd): + f = dup_quo_ground(f, gcd, K) + g = dup_quo_ground(g, gcd, K) + + return gcd, f, g + + +def dmp_ground_extract(f, g, u, K): + """ + Extract common content from a pair of polynomials in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_ground_extract(6*x*y + 12*x + 18, 4*x*y + 8*x + 12) + (2, 3*x*y + 6*x + 9, 2*x*y + 4*x + 6) + + """ + fc = dmp_ground_content(f, u, K) + gc = dmp_ground_content(g, u, K) + + gcd = K.gcd(fc, gc) + + if not K.is_one(gcd): + f = dmp_quo_ground(f, gcd, u, K) + g = dmp_quo_ground(g, gcd, u, K) + + return gcd, f, g + + +def dup_real_imag(f, K): + """ + Find ``f1`` and ``f2``, such that ``f(x+I*y) = f1(x,y) + f2(x,y)*I``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dup_real_imag(x**3 + x**2 + x + 1) + (x**3 + x**2 - 3*x*y**2 + x - y**2 + 1, 3*x**2*y + 2*x*y - y**3 + y) + + >>> from sympy.abc import x, y, z + >>> from sympy import I + >>> (z**3 + z**2 + z + 1).subs(z, x+I*y).expand().collect(I) + x**3 + x**2 - 3*x*y**2 + x - y**2 + I*(3*x**2*y + 2*x*y - y**3 + y) + 1 + + """ + if not K.is_ZZ and not K.is_QQ: + raise DomainError("computing real and imaginary parts is not supported over %s" % K) + + f1 = dmp_zero(1) + f2 = dmp_zero(1) + + if not f: + return f1, f2 + + g = [[[K.one, K.zero]], [[K.one], []]] + h = dmp_ground(f[0], 2) + + for c in f[1:]: + h = dmp_mul(h, g, 2, K) + h = dmp_add_term(h, dmp_ground(c, 1), 0, 2, K) + + H = dup_to_raw_dict(h) + + for k, h in H.items(): + m = k % 4 + + if not m: + f1 = dmp_add(f1, h, 1, K) + elif m == 1: + f2 = dmp_add(f2, h, 1, K) + elif m == 2: + f1 = dmp_sub(f1, h, 1, K) + else: + f2 = dmp_sub(f2, h, 1, K) + + return f1, f2 + + +def dup_mirror(f, K): + """ + Evaluate efficiently the composition ``f(-x)`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_mirror(x**3 + 2*x**2 - 4*x + 2) + -x**3 + 2*x**2 + 4*x + 2 + + """ + f = list(f) + + for i in range(len(f) - 2, -1, -2): + f[i] = -f[i] + + return f + + +def dup_scale(f, a, K): + """ + Evaluate efficiently composition ``f(a*x)`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_scale(x**2 - 2*x + 1, ZZ(2)) + 4*x**2 - 4*x + 1 + + """ + f, n, b = list(f), len(f) - 1, a + + for i in range(n - 1, -1, -1): + f[i], b = b*f[i], b*a + + return f + + +def dup_shift(f, a, K): + """ + Evaluate efficiently Taylor shift ``f(x + a)`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_shift(x**2 - 2*x + 1, ZZ(2)) + x**2 + 2*x + 1 + + """ + f, n = list(f), len(f) - 1 + + for i in range(n, 0, -1): + for j in range(0, i): + f[j + 1] += a*f[j] + + return f + + +def dmp_shift(f, a, u, K): + """ + Evaluate efficiently Taylor shift ``f(X + A)`` in ``K[X]``. + + Examples + ======== + + >>> from sympy import symbols, ring, ZZ + >>> x, y = symbols('x y') + >>> R, _, _ = ring([x, y], ZZ) + + >>> p = x**2*y + 2*x*y + 3*x + 4*y + 5 + + >>> R.dmp_shift(R(p), [ZZ(1), ZZ(2)]) + x**2*y + 2*x**2 + 4*x*y + 11*x + 7*y + 22 + + >>> p.subs({x: x + 1, y: y + 2}).expand() + x**2*y + 2*x**2 + 4*x*y + 11*x + 7*y + 22 + """ + if not u: + return dup_shift(f, a[0], K) + + if dmp_zero_p(f, u): + return f + + a0, a1 = a[0], a[1:] + + if any(a1): + f = [ dmp_shift(c, a1, u-1, K) for c in f ] + else: + f = list(f) + + if a0: + n = len(f) - 1 + + for i in range(n, 0, -1): + for j in range(0, i): + afj = dmp_mul_ground(f[j], a0, u-1, K) + f[j + 1] = dmp_add(f[j + 1], afj, u-1, K) + + return dmp_strip(f, u) + + +def dup_transform(f, p, q, K): + """ + Evaluate functional transformation ``q**n * f(p/q)`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_transform(x**2 - 2*x + 1, x**2 + 1, x - 1) + x**4 - 2*x**3 + 5*x**2 - 4*x + 4 + + """ + if not f: + return [] + + n = len(f) - 1 + h, Q = [f[0]], [[K.one]] + + for i in range(0, n): + Q.append(dup_mul(Q[-1], q, K)) + + for c, q in zip(f[1:], Q[1:]): + h = dup_mul(h, p, K) + q = dup_mul_ground(q, c, K) + h = dup_add(h, q, K) + + return h + + +def dup_compose(f, g, K): + """ + Evaluate functional composition ``f(g)`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_compose(x**2 + x, x - 1) + x**2 - x + + """ + if len(g) <= 1: + return dup_strip([dup_eval(f, dup_LC(g, K), K)]) + + if not f: + return [] + + h = [f[0]] + + for c in f[1:]: + h = dup_mul(h, g, K) + h = dup_add_term(h, c, 0, K) + + return h + + +def dmp_compose(f, g, u, K): + """ + Evaluate functional composition ``f(g)`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_compose(x*y + 2*x + y, y) + y**2 + 3*y + + """ + if not u: + return dup_compose(f, g, K) + + if dmp_zero_p(f, u): + return f + + h = [f[0]] + + for c in f[1:]: + h = dmp_mul(h, g, u, K) + h = dmp_add_term(h, c, 0, u, K) + + return h + + +def _dup_right_decompose(f, s, K): + """Helper function for :func:`_dup_decompose`.""" + n = len(f) - 1 + lc = dup_LC(f, K) + + f = dup_to_raw_dict(f) + g = { s: K.one } + + r = n // s + + for i in range(1, s): + coeff = K.zero + + for j in range(0, i): + if not n + j - i in f: + continue + + if not s - j in g: + continue + + fc, gc = f[n + j - i], g[s - j] + coeff += (i - r*j)*fc*gc + + g[s - i] = K.quo(coeff, i*r*lc) + + return dup_from_raw_dict(g, K) + + +def _dup_left_decompose(f, h, K): + """Helper function for :func:`_dup_decompose`.""" + g, i = {}, 0 + + while f: + q, r = dup_div(f, h, K) + + if dup_degree(r) > 0: + return None + else: + g[i] = dup_LC(r, K) + f, i = q, i + 1 + + return dup_from_raw_dict(g, K) + + +def _dup_decompose(f, K): + """Helper function for :func:`dup_decompose`.""" + df = len(f) - 1 + + for s in range(2, df): + if df % s != 0: + continue + + h = _dup_right_decompose(f, s, K) + + if h is not None: + g = _dup_left_decompose(f, h, K) + + if g is not None: + return g, h + + return None + + +def dup_decompose(f, K): + """ + Computes functional decomposition of ``f`` in ``K[x]``. + + Given a univariate polynomial ``f`` with coefficients in a field of + characteristic zero, returns list ``[f_1, f_2, ..., f_n]``, where:: + + f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n)) + + and ``f_2, ..., f_n`` are monic and homogeneous polynomials of at + least second degree. + + Unlike factorization, complete functional decompositions of + polynomials are not unique, consider examples: + + 1. ``f o g = f(x + b) o (g - b)`` + 2. ``x**n o x**m = x**m o x**n`` + 3. ``T_n o T_m = T_m o T_n`` + + where ``T_n`` and ``T_m`` are Chebyshev polynomials. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_decompose(x**4 - 2*x**3 + x**2) + [x**2, x**2 - x] + + References + ========== + + .. [1] [Kozen89]_ + + """ + F = [] + + while True: + result = _dup_decompose(f, K) + + if result is not None: + f, h = result + F = [h] + F + else: + break + + return [f] + F + + +def dmp_alg_inject(f, u, K): + """ + Convert polynomial from ``K(a)[X]`` to ``K[a,X]``. + + Examples + ======== + + >>> from sympy.polys.densetools import dmp_alg_inject + >>> from sympy import QQ, sqrt + + >>> K = QQ.algebraic_field(sqrt(2)) + + >>> p = [K.from_sympy(sqrt(2)), K.zero, K.one] + >>> P, lev, dom = dmp_alg_inject(p, 0, K) + >>> P + [[1, 0, 0], [1]] + >>> lev + 1 + >>> dom + QQ + + """ + if K.is_GaussianRing or K.is_GaussianField: + return _dmp_alg_inject_gaussian(f, u, K) + elif K.is_Algebraic: + return _dmp_alg_inject_alg(f, u, K) + else: + raise DomainError('computation can be done only in an algebraic domain') + + +def _dmp_alg_inject_gaussian(f, u, K): + """Helper function for :func:`dmp_alg_inject`.""" + f, h = dmp_to_dict(f, u), {} + + for f_monom, g in f.items(): + x, y = g.x, g.y + if x: + h[(0,) + f_monom] = x + if y: + h[(1,) + f_monom] = y + + F = dmp_from_dict(h, u + 1, K.dom) + + return F, u + 1, K.dom + + +def _dmp_alg_inject_alg(f, u, K): + """Helper function for :func:`dmp_alg_inject`.""" + f, h = dmp_to_dict(f, u), {} + + for f_monom, g in f.items(): + for g_monom, c in g.to_dict().items(): + h[g_monom + f_monom] = c + + F = dmp_from_dict(h, u + 1, K.dom) + + return F, u + 1, K.dom + + +def dmp_lift(f, u, K): + """ + Convert algebraic coefficients to integers in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> from sympy import I + + >>> K = QQ.algebraic_field(I) + >>> R, x = ring("x", K) + + >>> f = x**2 + K([QQ(1), QQ(0)])*x + K([QQ(2), QQ(0)]) + + >>> R.dmp_lift(f) + x**4 + x**2 + 4*x + 4 + + """ + # Circular import. Probably dmp_lift should be moved to euclidtools + from .euclidtools import dmp_resultant + + F, v, K2 = dmp_alg_inject(f, u, K) + + p_a = K.mod.to_list() + P_A = dmp_include(p_a, list(range(1, v + 1)), 0, K2) + + return dmp_resultant(F, P_A, v, K2) + + +def dup_sign_variations(f, K): + """ + Compute the number of sign variations of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sign_variations(x**4 - x**2 - x + 1) + 2 + + """ + def is_negative_sympy(a): + if not a: + # XXX: requires zero equivalence testing in the domain + return False + else: + # XXX: This is inefficient. It should not be necessary to use a + # symbolic expression here at least for algebraic fields. If the + # domain elements can be numerically evaluated to real values with + # precision then this should work. We first need to rule out zero + # elements though. + return bool(K.to_sympy(a) < 0) + + # XXX: There should be a way to check for real numeric domains and + # Domain.is_negative should be fixed to handle all real numeric domains. + # It should not be necessary to special case all these different domains + # in this otherwise generic function. + if K.is_ZZ or K.is_QQ or K.is_RR: + is_negative = K.is_negative + elif K.is_AlgebraicField and K.ext.is_comparable: + is_negative = is_negative_sympy + elif ((K.is_PolynomialRing or K.is_FractionField) and len(K.symbols) == 1 and + (K.dom.is_ZZ or K.dom.is_QQ or K.is_AlgebraicField) and + K.symbols[0].is_transcendental and K.symbols[0].is_comparable): + # We can handle a polynomial ring like QQ[E] if there is a single + # transcendental generator because then zero equivalence is assured. + is_negative = is_negative_sympy + else: + raise DomainError("sign variation counting not supported over %s" % K) + + prev, k = K.zero, 0 + + for coeff in f: + if is_negative(coeff*prev): + k += 1 + + if coeff: + prev = coeff + + return k + + +def dup_clear_denoms(f, K0, K1=None, convert=False): + """ + Clear denominators, i.e. transform ``K_0`` to ``K_1``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = QQ(1,2)*x + QQ(1,3) + + >>> R.dup_clear_denoms(f, convert=False) + (6, 3*x + 2) + >>> R.dup_clear_denoms(f, convert=True) + (6, 3*x + 2) + + """ + if K1 is None: + if K0.has_assoc_Ring: + K1 = K0.get_ring() + else: + K1 = K0 + + common = K1.one + + for c in f: + common = K1.lcm(common, K0.denom(c)) + + if K1.is_one(common): + if not convert: + return common, f + else: + return common, dup_convert(f, K0, K1) + + # Use quo rather than exquo to handle inexact domains by discarding the + # remainder. + f = [K0.numer(c)*K1.quo(common, K0.denom(c)) for c in f] + + if not convert: + return common, dup_convert(f, K1, K0) + else: + return common, f + + +def _rec_clear_denoms(g, v, K0, K1): + """Recursive helper for :func:`dmp_clear_denoms`.""" + common = K1.one + + if not v: + for c in g: + common = K1.lcm(common, K0.denom(c)) + else: + w = v - 1 + + for c in g: + common = K1.lcm(common, _rec_clear_denoms(c, w, K0, K1)) + + return common + + +def dmp_clear_denoms(f, u, K0, K1=None, convert=False): + """ + Clear denominators, i.e. transform ``K_0`` to ``K_1``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y = ring("x,y", QQ) + + >>> f = QQ(1,2)*x + QQ(1,3)*y + 1 + + >>> R.dmp_clear_denoms(f, convert=False) + (6, 3*x + 2*y + 6) + >>> R.dmp_clear_denoms(f, convert=True) + (6, 3*x + 2*y + 6) + + """ + if not u: + return dup_clear_denoms(f, K0, K1, convert=convert) + + if K1 is None: + if K0.has_assoc_Ring: + K1 = K0.get_ring() + else: + K1 = K0 + + common = _rec_clear_denoms(f, u, K0, K1) + + if not K1.is_one(common): + f = dmp_mul_ground(f, common, u, K0) + + if not convert: + return common, f + else: + return common, dmp_convert(f, u, K0, K1) + + +def dup_revert(f, n, K): + """ + Compute ``f**(-1)`` mod ``x**n`` using Newton iteration. + + This function computes first ``2**n`` terms of a polynomial that + is a result of inversion of a polynomial modulo ``x**n``. This is + useful to efficiently compute series expansion of ``1/f``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = -QQ(1,720)*x**6 + QQ(1,24)*x**4 - QQ(1,2)*x**2 + 1 + + >>> R.dup_revert(f, 8) + 61/720*x**6 + 5/24*x**4 + 1/2*x**2 + 1 + + """ + g = [K.revert(dup_TC(f, K))] + h = [K.one, K.zero, K.zero] + + N = int(_ceil(_log2(n))) + + for i in range(1, N + 1): + a = dup_mul_ground(g, K(2), K) + b = dup_mul(f, dup_sqr(g, K), K) + g = dup_rem(dup_sub(a, b, K), h, K) + h = dup_lshift(h, dup_degree(h), K) + + return g + + +def dmp_revert(f, g, u, K): + """ + Compute ``f**(-1)`` mod ``x**n`` using Newton iteration. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y = ring("x,y", QQ) + + """ + if not u: + return dup_revert(f, g, K) + else: + raise MultivariatePolynomialError(f, g) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/dispersion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/dispersion.py new file mode 100644 index 0000000000000000000000000000000000000000..699277d221f24b9bff42c55c3bb34fe5783ae7a1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/dispersion.py @@ -0,0 +1,212 @@ +from sympy.core import S +from sympy.polys import Poly + + +def dispersionset(p, q=None, *gens, **args): + r"""Compute the *dispersion set* of two polynomials. + + For two polynomials `f(x)` and `g(x)` with `\deg f > 0` + and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as: + + .. math:: + \operatorname{J}(f, g) + & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\ + & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\} + + For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`. + + Examples + ======== + + >>> from sympy import poly + >>> from sympy.polys.dispersion import dispersion, dispersionset + >>> from sympy.abc import x + + Dispersion set and dispersion of a simple polynomial: + + >>> fp = poly((x - 3)*(x + 3), x) + >>> sorted(dispersionset(fp)) + [0, 6] + >>> dispersion(fp) + 6 + + Note that the definition of the dispersion is not symmetric: + + >>> fp = poly(x**4 - 3*x**2 + 1, x) + >>> gp = fp.shift(-3) + >>> sorted(dispersionset(fp, gp)) + [2, 3, 4] + >>> dispersion(fp, gp) + 4 + >>> sorted(dispersionset(gp, fp)) + [] + >>> dispersion(gp, fp) + -oo + + Computing the dispersion also works over field extensions: + + >>> from sympy import sqrt + >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ') + >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ') + >>> sorted(dispersionset(fp, gp)) + [2] + >>> sorted(dispersionset(gp, fp)) + [1, 4] + + We can even perform the computations for polynomials + having symbolic coefficients: + + >>> from sympy.abc import a + >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) + >>> sorted(dispersionset(fp)) + [0, 1] + + See Also + ======== + + dispersion + + References + ========== + + .. [1] [ManWright94]_ + .. [2] [Koepf98]_ + .. [3] [Abramov71]_ + .. [4] [Man93]_ + """ + # Check for valid input + same = False if q is not None else True + if same: + q = p + + p = Poly(p, *gens, **args) + q = Poly(q, *gens, **args) + + if not p.is_univariate or not q.is_univariate: + raise ValueError("Polynomials need to be univariate") + + # The generator + if not p.gen == q.gen: + raise ValueError("Polynomials must have the same generator") + gen = p.gen + + # We define the dispersion of constant polynomials to be zero + if p.degree() < 1 or q.degree() < 1: + return {0} + + # Factor p and q over the rationals + fp = p.factor_list() + fq = q.factor_list() if not same else fp + + # Iterate over all pairs of factors + J = set() + for s, unused in fp[1]: + for t, unused in fq[1]: + m = s.degree() + n = t.degree() + if n != m: + continue + an = s.LC() + bn = t.LC() + if not (an - bn).is_zero: + continue + # Note that the roles of `s` and `t` below are switched + # w.r.t. the original paper. This is for consistency + # with the description in the book of W. Koepf. + anm1 = s.coeff_monomial(gen**(m-1)) + bnm1 = t.coeff_monomial(gen**(n-1)) + alpha = (anm1 - bnm1) / S(n*bn) + if not alpha.is_integer: + continue + if alpha < 0 or alpha in J: + continue + if n > 1 and not (s - t.shift(alpha)).is_zero: + continue + J.add(alpha) + + return J + + +def dispersion(p, q=None, *gens, **args): + r"""Compute the *dispersion* of polynomials. + + For two polynomials `f(x)` and `g(x)` with `\deg f > 0` + and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as: + + .. math:: + \operatorname{dis}(f, g) + & := \max\{ J(f,g) \cup \{0\} \} \\ + & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \} + + and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`. + Note that we make the definition `\max\{\} := -\infty`. + + Examples + ======== + + >>> from sympy import poly + >>> from sympy.polys.dispersion import dispersion, dispersionset + >>> from sympy.abc import x + + Dispersion set and dispersion of a simple polynomial: + + >>> fp = poly((x - 3)*(x + 3), x) + >>> sorted(dispersionset(fp)) + [0, 6] + >>> dispersion(fp) + 6 + + Note that the definition of the dispersion is not symmetric: + + >>> fp = poly(x**4 - 3*x**2 + 1, x) + >>> gp = fp.shift(-3) + >>> sorted(dispersionset(fp, gp)) + [2, 3, 4] + >>> dispersion(fp, gp) + 4 + >>> sorted(dispersionset(gp, fp)) + [] + >>> dispersion(gp, fp) + -oo + + The maximum of an empty set is defined to be `-\infty` + as seen in this example. + + Computing the dispersion also works over field extensions: + + >>> from sympy import sqrt + >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ') + >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ') + >>> sorted(dispersionset(fp, gp)) + [2] + >>> sorted(dispersionset(gp, fp)) + [1, 4] + + We can even perform the computations for polynomials + having symbolic coefficients: + + >>> from sympy.abc import a + >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) + >>> sorted(dispersionset(fp)) + [0, 1] + + See Also + ======== + + dispersionset + + References + ========== + + .. [1] [ManWright94]_ + .. [2] [Koepf98]_ + .. [3] [Abramov71]_ + .. [4] [Man93]_ + """ + J = dispersionset(p, q, *gens, **args) + if not J: + # Definition for maximum of empty set + j = S.NegativeInfinity + else: + j = max(J) + return j diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/distributedmodules.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/distributedmodules.py new file mode 100644 index 0000000000000000000000000000000000000000..df4581e58951a9c29b9e5b085311f5e6cb00f381 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/distributedmodules.py @@ -0,0 +1,739 @@ +r""" +Sparse distributed elements of free modules over multivariate (generalized) +polynomial rings. + +This code and its data structures are very much like the distributed +polynomials, except that the first "exponent" of the monomial is +a module generator index. That is, the multi-exponent ``(i, e_1, ..., e_n)`` +represents the "monomial" `x_1^{e_1} \cdots x_n^{e_n} f_i` of the free module +`F` generated by `f_1, \ldots, f_r` over (a localization of) the ring +`K[x_1, \ldots, x_n]`. A module element is simply stored as a list of terms +ordered by the monomial order. Here a term is a pair of a multi-exponent and a +coefficient. In general, this coefficient should never be zero (since it can +then be omitted). The zero module element is stored as an empty list. + +The main routines are ``sdm_nf_mora`` and ``sdm_groebner`` which can be used +to compute, respectively, weak normal forms and standard bases. They work with +arbitrary (not necessarily global) monomial orders. + +In general, product orders have to be used to construct valid monomial orders +for modules. However, ``lex`` can be used as-is. + +Note that the "level" (number of variables, i.e. parameter u+1 in +distributedpolys.py) is never needed in this code. + +The main reference for this file is [SCA], +"A Singular Introduction to Commutative Algebra". +""" + + +from itertools import permutations + +from sympy.polys.monomials import ( + monomial_mul, monomial_lcm, monomial_div, monomial_deg +) + +from sympy.polys.polytools import Poly +from sympy.polys.polyutils import parallel_dict_from_expr +from sympy.core.singleton import S +from sympy.core.sympify import sympify + +# Additional monomial tools. + + +def sdm_monomial_mul(M, X): + """ + Multiply tuple ``X`` representing a monomial of `K[X]` into the tuple + ``M`` representing a monomial of `F`. + + Examples + ======== + + Multiplying `xy^3` into `x f_1` yields `x^2 y^3 f_1`: + + >>> from sympy.polys.distributedmodules import sdm_monomial_mul + >>> sdm_monomial_mul((1, 1, 0), (1, 3)) + (1, 2, 3) + """ + return (M[0],) + monomial_mul(X, M[1:]) + + +def sdm_monomial_deg(M): + """ + Return the total degree of ``M``. + + Examples + ======== + + For example, the total degree of `x^2 y f_5` is 3: + + >>> from sympy.polys.distributedmodules import sdm_monomial_deg + >>> sdm_monomial_deg((5, 2, 1)) + 3 + """ + return monomial_deg(M[1:]) + + +def sdm_monomial_lcm(A, B): + r""" + Return the "least common multiple" of ``A`` and ``B``. + + IF `A = M e_j` and `B = N e_j`, where `M` and `N` are polynomial monomials, + this returns `\lcm(M, N) e_j`. Note that ``A`` and ``B`` involve distinct + monomials. + + Otherwise the result is undefined. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_monomial_lcm + >>> sdm_monomial_lcm((1, 2, 3), (1, 0, 5)) + (1, 2, 5) + """ + return (A[0],) + monomial_lcm(A[1:], B[1:]) + + +def sdm_monomial_divides(A, B): + """ + Does there exist a (polynomial) monomial X such that XA = B? + + Examples + ======== + + Positive examples: + + In the following examples, the monomial is given in terms of x, y and the + generator(s), f_1, f_2 etc. The tuple form of that monomial is used in + the call to sdm_monomial_divides. + Note: the generator appears last in the expression but first in the tuple + and other factors appear in the same order that they appear in the monomial + expression. + + `A = f_1` divides `B = f_1` + + >>> from sympy.polys.distributedmodules import sdm_monomial_divides + >>> sdm_monomial_divides((1, 0, 0), (1, 0, 0)) + True + + `A = f_1` divides `B = x^2 y f_1` + + >>> sdm_monomial_divides((1, 0, 0), (1, 2, 1)) + True + + `A = xy f_5` divides `B = x^2 y f_5` + + >>> sdm_monomial_divides((5, 1, 1), (5, 2, 1)) + True + + Negative examples: + + `A = f_1` does not divide `B = f_2` + + >>> sdm_monomial_divides((1, 0, 0), (2, 0, 0)) + False + + `A = x f_1` does not divide `B = f_1` + + >>> sdm_monomial_divides((1, 1, 0), (1, 0, 0)) + False + + `A = xy^2 f_5` does not divide `B = y f_5` + + >>> sdm_monomial_divides((5, 1, 2), (5, 0, 1)) + False + """ + return A[0] == B[0] and all(a <= b for a, b in zip(A[1:], B[1:])) + + +# The actual distributed modules code. + +def sdm_LC(f, K): + """Returns the leading coefficient of ``f``. """ + if not f: + return K.zero + else: + return f[0][1] + + +def sdm_to_dict(f): + """Make a dictionary from a distributed polynomial. """ + return dict(f) + + +def sdm_from_dict(d, O): + """ + Create an sdm from a dictionary. + + Here ``O`` is the monomial order to use. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_from_dict + >>> from sympy.polys import QQ, lex + >>> dic = {(1, 1, 0): QQ(1), (1, 0, 0): QQ(2), (0, 1, 0): QQ(0)} + >>> sdm_from_dict(dic, lex) + [((1, 1, 0), 1), ((1, 0, 0), 2)] + """ + return sdm_strip(sdm_sort(list(d.items()), O)) + + +def sdm_sort(f, O): + """Sort terms in ``f`` using the given monomial order ``O``. """ + return sorted(f, key=lambda term: O(term[0]), reverse=True) + + +def sdm_strip(f): + """Remove terms with zero coefficients from ``f`` in ``K[X]``. """ + return [ (monom, coeff) for monom, coeff in f if coeff ] + + +def sdm_add(f, g, O, K): + """ + Add two module elements ``f``, ``g``. + + Addition is done over the ground field ``K``, monomials are ordered + according to ``O``. + + Examples + ======== + + All examples use lexicographic order. + + `(xy f_1) + (f_2) = f_2 + xy f_1` + + >>> from sympy.polys.distributedmodules import sdm_add + >>> from sympy.polys import lex, QQ + >>> sdm_add([((1, 1, 1), QQ(1))], [((2, 0, 0), QQ(1))], lex, QQ) + [((2, 0, 0), 1), ((1, 1, 1), 1)] + + `(xy f_1) + (-xy f_1)` = 0` + + >>> sdm_add([((1, 1, 1), QQ(1))], [((1, 1, 1), QQ(-1))], lex, QQ) + [] + + `(f_1) + (2f_1) = 3f_1` + + >>> sdm_add([((1, 0, 0), QQ(1))], [((1, 0, 0), QQ(2))], lex, QQ) + [((1, 0, 0), 3)] + + `(yf_1) + (xf_1) = xf_1 + yf_1` + + >>> sdm_add([((1, 0, 1), QQ(1))], [((1, 1, 0), QQ(1))], lex, QQ) + [((1, 1, 0), 1), ((1, 0, 1), 1)] + """ + h = dict(f) + + for monom, c in g: + if monom in h: + coeff = h[monom] + c + + if not coeff: + del h[monom] + else: + h[monom] = coeff + else: + h[monom] = c + + return sdm_from_dict(h, O) + + +def sdm_LM(f): + r""" + Returns the leading monomial of ``f``. + + Only valid if `f \ne 0`. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_LM, sdm_from_dict + >>> from sympy.polys import QQ, lex + >>> dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(1), (4, 0, 1): QQ(1)} + >>> sdm_LM(sdm_from_dict(dic, lex)) + (4, 0, 1) + """ + return f[0][0] + + +def sdm_LT(f): + r""" + Returns the leading term of ``f``. + + Only valid if `f \ne 0`. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_LT, sdm_from_dict + >>> from sympy.polys import QQ, lex + >>> dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(2), (4, 0, 1): QQ(3)} + >>> sdm_LT(sdm_from_dict(dic, lex)) + ((4, 0, 1), 3) + """ + return f[0] + + +def sdm_mul_term(f, term, O, K): + """ + Multiply a distributed module element ``f`` by a (polynomial) term ``term``. + + Multiplication of coefficients is done over the ground field ``K``, and + monomials are ordered according to ``O``. + + Examples + ======== + + `0 f_1 = 0` + + >>> from sympy.polys.distributedmodules import sdm_mul_term + >>> from sympy.polys import lex, QQ + >>> sdm_mul_term([((1, 0, 0), QQ(1))], ((0, 0), QQ(0)), lex, QQ) + [] + + `x 0 = 0` + + >>> sdm_mul_term([], ((1, 0), QQ(1)), lex, QQ) + [] + + `(x) (f_1) = xf_1` + + >>> sdm_mul_term([((1, 0, 0), QQ(1))], ((1, 0), QQ(1)), lex, QQ) + [((1, 1, 0), 1)] + + `(2xy) (3x f_1 + 4y f_2) = 8xy^2 f_2 + 6x^2y f_1` + + >>> f = [((2, 0, 1), QQ(4)), ((1, 1, 0), QQ(3))] + >>> sdm_mul_term(f, ((1, 1), QQ(2)), lex, QQ) + [((2, 1, 2), 8), ((1, 2, 1), 6)] + """ + X, c = term + + if not f or not c: + return [] + else: + if K.is_one(c): + return [ (sdm_monomial_mul(f_M, X), f_c) for f_M, f_c in f ] + else: + return [ (sdm_monomial_mul(f_M, X), f_c * c) for f_M, f_c in f ] + + +def sdm_zero(): + """Return the zero module element.""" + return [] + + +def sdm_deg(f): + """ + Degree of ``f``. + + This is the maximum of the degrees of all its monomials. + Invalid if ``f`` is zero. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_deg + >>> sdm_deg([((1, 2, 3), 1), ((10, 0, 1), 1), ((2, 3, 4), 4)]) + 7 + """ + return max(sdm_monomial_deg(M[0]) for M in f) + + +# Conversion + +def sdm_from_vector(vec, O, K, **opts): + """ + Create an sdm from an iterable of expressions. + + Coefficients are created in the ground field ``K``, and terms are ordered + according to monomial order ``O``. Named arguments are passed on to the + polys conversion code and can be used to specify for example generators. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_from_vector + >>> from sympy.abc import x, y, z + >>> from sympy.polys import QQ, lex + >>> sdm_from_vector([x**2+y**2, 2*z], lex, QQ) + [((1, 0, 0, 1), 2), ((0, 2, 0, 0), 1), ((0, 0, 2, 0), 1)] + """ + dics, gens = parallel_dict_from_expr(sympify(vec), **opts) + dic = {} + for i, d in enumerate(dics): + for k, v in d.items(): + dic[(i,) + k] = K.convert(v) + return sdm_from_dict(dic, O) + + +def sdm_to_vector(f, gens, K, n=None): + """ + Convert sdm ``f`` into a list of polynomial expressions. + + The generators for the polynomial ring are specified via ``gens``. The rank + of the module is guessed, or passed via ``n``. The ground field is assumed + to be ``K``. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_to_vector + >>> from sympy.abc import x, y, z + >>> from sympy.polys import QQ + >>> f = [((1, 0, 0, 1), QQ(2)), ((0, 2, 0, 0), QQ(1)), ((0, 0, 2, 0), QQ(1))] + >>> sdm_to_vector(f, [x, y, z], QQ) + [x**2 + y**2, 2*z] + """ + dic = sdm_to_dict(f) + dics = {} + for k, v in dic.items(): + dics.setdefault(k[0], []).append((k[1:], v)) + n = n or len(dics) + res = [] + for k in range(n): + if k in dics: + res.append(Poly(dict(dics[k]), gens=gens, domain=K).as_expr()) + else: + res.append(S.Zero) + return res + +# Algorithms. + + +def sdm_spoly(f, g, O, K, phantom=None): + """ + Compute the generalized s-polynomial of ``f`` and ``g``. + + The ground field is assumed to be ``K``, and monomials ordered according to + ``O``. + + This is invalid if either of ``f`` or ``g`` is zero. + + If the leading terms of `f` and `g` involve different basis elements of + `F`, their s-poly is defined to be zero. Otherwise it is a certain linear + combination of `f` and `g` in which the leading terms cancel. + See [SCA, defn 2.3.6] for details. + + If ``phantom`` is not ``None``, it should be a pair of module elements on + which to perform the same operation(s) as on ``f`` and ``g``. The in this + case both results are returned. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_spoly + >>> from sympy.polys import QQ, lex + >>> f = [((2, 1, 1), QQ(1)), ((1, 0, 1), QQ(1))] + >>> g = [((2, 3, 0), QQ(1))] + >>> h = [((1, 2, 3), QQ(1))] + >>> sdm_spoly(f, h, lex, QQ) + [] + >>> sdm_spoly(f, g, lex, QQ) + [((1, 2, 1), 1)] + """ + if not f or not g: + return sdm_zero() + LM1 = sdm_LM(f) + LM2 = sdm_LM(g) + if LM1[0] != LM2[0]: + return sdm_zero() + LM1 = LM1[1:] + LM2 = LM2[1:] + lcm = monomial_lcm(LM1, LM2) + m1 = monomial_div(lcm, LM1) + m2 = monomial_div(lcm, LM2) + c = K.quo(-sdm_LC(f, K), sdm_LC(g, K)) + r1 = sdm_add(sdm_mul_term(f, (m1, K.one), O, K), + sdm_mul_term(g, (m2, c), O, K), O, K) + if phantom is None: + return r1 + r2 = sdm_add(sdm_mul_term(phantom[0], (m1, K.one), O, K), + sdm_mul_term(phantom[1], (m2, c), O, K), O, K) + return r1, r2 + + +def sdm_ecart(f): + """ + Compute the ecart of ``f``. + + This is defined to be the difference of the total degree of `f` and the + total degree of the leading monomial of `f` [SCA, defn 2.3.7]. + + Invalid if f is zero. + + Examples + ======== + + >>> from sympy.polys.distributedmodules import sdm_ecart + >>> sdm_ecart([((1, 2, 3), 1), ((1, 0, 1), 1)]) + 0 + >>> sdm_ecart([((2, 2, 1), 1), ((1, 5, 1), 1)]) + 3 + """ + return sdm_deg(f) - sdm_monomial_deg(sdm_LM(f)) + + +def sdm_nf_mora(f, G, O, K, phantom=None): + r""" + Compute a weak normal form of ``f`` with respect to ``G`` and order ``O``. + + The ground field is assumed to be ``K``, and monomials ordered according to + ``O``. + + Weak normal forms are defined in [SCA, defn 2.3.3]. They are not unique. + This function deterministically computes a weak normal form, depending on + the order of `G`. + + The most important property of a weak normal form is the following: if + `R` is the ring associated with the monomial ordering (if the ordering is + global, we just have `R = K[x_1, \ldots, x_n]`, otherwise it is a certain + localization thereof), `I` any ideal of `R` and `G` a standard basis for + `I`, then for any `f \in R`, we have `f \in I` if and only if + `NF(f | G) = 0`. + + This is the generalized Mora algorithm for computing weak normal forms with + respect to arbitrary monomial orders [SCA, algorithm 2.3.9]. + + If ``phantom`` is not ``None``, it should be a pair of "phantom" arguments + on which to perform the same computations as on ``f``, ``G``, both results + are then returned. + """ + from itertools import repeat + h = f + T = list(G) + if phantom is not None: + # "phantom" variables with suffix p + hp = phantom[0] + Tp = list(phantom[1]) + phantom = True + else: + Tp = repeat([]) + phantom = False + while h: + # TODO better data structure!!! + Th = [(g, sdm_ecart(g), gp) for g, gp in zip(T, Tp) + if sdm_monomial_divides(sdm_LM(g), sdm_LM(h))] + if not Th: + break + g, _, gp = min(Th, key=lambda x: x[1]) + if sdm_ecart(g) > sdm_ecart(h): + T.append(h) + if phantom: + Tp.append(hp) + if phantom: + h, hp = sdm_spoly(h, g, O, K, phantom=(hp, gp)) + else: + h = sdm_spoly(h, g, O, K) + if phantom: + return h, hp + return h + + +def sdm_nf_buchberger(f, G, O, K, phantom=None): + r""" + Compute a weak normal form of ``f`` with respect to ``G`` and order ``O``. + + The ground field is assumed to be ``K``, and monomials ordered according to + ``O``. + + This is the standard Buchberger algorithm for computing weak normal forms with + respect to *global* monomial orders [SCA, algorithm 1.6.10]. + + If ``phantom`` is not ``None``, it should be a pair of "phantom" arguments + on which to perform the same computations as on ``f``, ``G``, both results + are then returned. + """ + from itertools import repeat + h = f + T = list(G) + if phantom is not None: + # "phantom" variables with suffix p + hp = phantom[0] + Tp = list(phantom[1]) + phantom = True + else: + Tp = repeat([]) + phantom = False + while h: + try: + g, gp = next((g, gp) for g, gp in zip(T, Tp) + if sdm_monomial_divides(sdm_LM(g), sdm_LM(h))) + except StopIteration: + break + if phantom: + h, hp = sdm_spoly(h, g, O, K, phantom=(hp, gp)) + else: + h = sdm_spoly(h, g, O, K) + if phantom: + return h, hp + return h + + +def sdm_nf_buchberger_reduced(f, G, O, K): + r""" + Compute a reduced normal form of ``f`` with respect to ``G`` and order ``O``. + + The ground field is assumed to be ``K``, and monomials ordered according to + ``O``. + + In contrast to weak normal forms, reduced normal forms *are* unique, but + their computation is more expensive. + + This is the standard Buchberger algorithm for computing reduced normal forms + with respect to *global* monomial orders [SCA, algorithm 1.6.11]. + + The ``pantom`` option is not supported, so this normal form cannot be used + as a normal form for the "extended" groebner algorithm. + """ + h = sdm_zero() + g = f + while g: + g = sdm_nf_buchberger(g, G, O, K) + if g: + h = sdm_add(h, [sdm_LT(g)], O, K) + g = g[1:] + return h + + +def sdm_groebner(G, NF, O, K, extended=False): + """ + Compute a minimal standard basis of ``G`` with respect to order ``O``. + + The algorithm uses a normal form ``NF``, for example ``sdm_nf_mora``. + The ground field is assumed to be ``K``, and monomials ordered according + to ``O``. + + Let `N` denote the submodule generated by elements of `G`. A standard + basis for `N` is a subset `S` of `N`, such that `in(S) = in(N)`, where for + any subset `X` of `F`, `in(X)` denotes the submodule generated by the + initial forms of elements of `X`. [SCA, defn 2.3.2] + + A standard basis is called minimal if no subset of it is a standard basis. + + One may show that standard bases are always generating sets. + + Minimal standard bases are not unique. This algorithm computes a + deterministic result, depending on the particular order of `G`. + + If ``extended=True``, also compute the transition matrix from the initial + generators to the groebner basis. That is, return a list of coefficient + vectors, expressing the elements of the groebner basis in terms of the + elements of ``G``. + + This functions implements the "sugar" strategy, see + + Giovini et al: "One sugar cube, please" OR Selection strategies in + Buchberger algorithm. + """ + + # The critical pair set. + # A critical pair is stored as (i, j, s, t) where (i, j) defines the pair + # (by indexing S), s is the sugar of the pair, and t is the lcm of their + # leading monomials. + P = [] + + # The eventual standard basis. + S = [] + Sugars = [] + + def Ssugar(i, j): + """Compute the sugar of the S-poly corresponding to (i, j).""" + LMi = sdm_LM(S[i]) + LMj = sdm_LM(S[j]) + return max(Sugars[i] - sdm_monomial_deg(LMi), + Sugars[j] - sdm_monomial_deg(LMj)) \ + + sdm_monomial_deg(sdm_monomial_lcm(LMi, LMj)) + + ourkey = lambda p: (p[2], O(p[3]), p[1]) + + def update(f, sugar, P): + """Add f with sugar ``sugar`` to S, update P.""" + if not f: + return P + k = len(S) + S.append(f) + Sugars.append(sugar) + + LMf = sdm_LM(f) + + def removethis(pair): + i, j, s, t = pair + if LMf[0] != t[0]: + return False + tik = sdm_monomial_lcm(LMf, sdm_LM(S[i])) + tjk = sdm_monomial_lcm(LMf, sdm_LM(S[j])) + return tik != t and tjk != t and sdm_monomial_divides(tik, t) and \ + sdm_monomial_divides(tjk, t) + # apply the chain criterion + P = [p for p in P if not removethis(p)] + + # new-pair set + N = [(i, k, Ssugar(i, k), sdm_monomial_lcm(LMf, sdm_LM(S[i]))) + for i in range(k) if LMf[0] == sdm_LM(S[i])[0]] + # TODO apply the product criterion? + N.sort(key=ourkey) + remove = set() + for i, p in enumerate(N): + for j in range(i + 1, len(N)): + if sdm_monomial_divides(p[3], N[j][3]): + remove.add(j) + + # TODO mergesort? + P.extend(reversed([p for i, p in enumerate(N) if i not in remove])) + P.sort(key=ourkey, reverse=True) + # NOTE reverse-sort, because we want to pop from the end + return P + + # Figure out the number of generators in the ground ring. + try: + # NOTE: we look for the first non-zero vector, take its first monomial + # the number of generators in the ring is one less than the length + # (since the zeroth entry is for the module generators) + numgens = len(next(x[0] for x in G if x)[0]) - 1 + except StopIteration: + # No non-zero elements in G ... + if extended: + return [], [] + return [] + + # This list will store expressions of the elements of S in terms of the + # initial generators + coefficients = [] + + # First add all the elements of G to S + for i, f in enumerate(G): + P = update(f, sdm_deg(f), P) + if extended and f: + coefficients.append(sdm_from_dict({(i,) + (0,)*numgens: K(1)}, O)) + + # Now carry out the buchberger algorithm. + while P: + i, j, s, t = P.pop() + f, g = S[i], S[j] + if extended: + sp, coeff = sdm_spoly(f, g, O, K, + phantom=(coefficients[i], coefficients[j])) + h, hcoeff = NF(sp, S, O, K, phantom=(coeff, coefficients)) + if h: + coefficients.append(hcoeff) + else: + h = NF(sdm_spoly(f, g, O, K), S, O, K) + P = update(h, Ssugar(i, j), P) + + # Finally interreduce the standard basis. + # (TODO again, better data structures) + S = {(tuple(f), i) for i, f in enumerate(S)} + for (a, ai), (b, bi) in permutations(S, 2): + A = sdm_LM(a) + B = sdm_LM(b) + if sdm_monomial_divides(A, B) and (b, bi) in S and (a, ai) in S: + S.remove((b, bi)) + + L = sorted(((list(f), i) for f, i in S), key=lambda p: O(sdm_LM(p[0])), + reverse=True) + res = [x[0] for x in L] + if extended: + return res, [coefficients[i] for _, i in L] + return res diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domainmatrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domainmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ccaaa4cb96e0c49da58d8e9128c1b6fa551ade --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domainmatrix.py @@ -0,0 +1,12 @@ +""" +Stub module to expose DomainMatrix which has now moved to +sympy.polys.matrices package. It should now be imported as: + + >>> from sympy.polys.matrices import DomainMatrix + +This module might be removed in future. +""" + +from sympy.polys.matrices.domainmatrix import DomainMatrix + +__all__ = ['DomainMatrix'] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6839b4494afd0ee0c0ecd9ddee65d1afbdc6b53 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__init__.py @@ -0,0 +1,57 @@ +"""Implementation of mathematical domains. """ + +__all__ = [ + 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField', + 'ComplexField', 'AlgebraicField', 'PolynomialRing', 'FractionField', + 'ExpressionDomain', 'PythonRational', + + 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', +] + +from .domain import Domain +from .finitefield import FiniteField, FF, GF +from .integerring import IntegerRing, ZZ +from .rationalfield import RationalField, QQ +from .algebraicfield import AlgebraicField +from .gaussiandomains import ZZ_I, QQ_I +from .realfield import RealField, RR +from .complexfield import ComplexField, CC +from .polynomialring import PolynomialRing +from .fractionfield import FractionField +from .expressiondomain import ExpressionDomain, EX +from .expressionrawdomain import EXRAW +from .pythonrational import PythonRational + + +# This is imported purely for backwards compatibility because some parts of +# the codebase used to import this from here and it's possible that downstream +# does as well: +from sympy.external.gmpy import GROUND_TYPES # noqa: F401 + +# +# The rest of these are obsolete and provided only for backwards +# compatibility: +# + +from .pythonfinitefield import PythonFiniteField +from .gmpyfinitefield import GMPYFiniteField +from .pythonintegerring import PythonIntegerRing +from .gmpyintegerring import GMPYIntegerRing +from .pythonrationalfield import PythonRationalField +from .gmpyrationalfield import GMPYRationalField + +FF_python = PythonFiniteField +FF_gmpy = GMPYFiniteField + +ZZ_python = PythonIntegerRing +ZZ_gmpy = GMPYIntegerRing + +QQ_python = PythonRationalField +QQ_gmpy = GMPYRationalField + +__all__.extend(( + 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', + 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', + + 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', +)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0b994ee100e9a8c4332576293b8d66357ec4c0f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/algebraicfield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/algebraicfield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1719cc2fbb0e5b0d1681d36b27a31ea898b4db5d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/algebraicfield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/characteristiczero.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/characteristiczero.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26ea5e1f5c46eb21ef21892c01e5ce36c44c66f8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/characteristiczero.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09aa87878d002acebaff0a3d57cb178dec34a26b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/compositedomain.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/compositedomain.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17c9bb5ad5ee9645f2740e3571836a68647bc5b6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/compositedomain.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/domain.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/domain.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55a7a6ceb384e80b06ee0755811ab78562ff927b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/domain.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/domainelement.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/domainelement.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5771589e43fbc98b273837a3bd86aee4a91d9fa9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/domainelement.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressiondomain.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressiondomain.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6efd6da72e90b09949e8cd7850fa7e2f2116746d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressiondomain.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..228422c075fd2f34b4c50c2cb74d6daa01b7a499 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/field.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/field.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12441f7ff05efecce1a6fbc1c3c7a6d51d7f8331 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/field.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/finitefield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/finitefield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ae829e9b58929be6d38556d2b580d61333ad142 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/finitefield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca281ff70beade1230270821bd92bb4214701539 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gaussiandomains.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gaussiandomains.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31e1b4b304a36c5b3e5b2c4f370e9850b82e1886 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gaussiandomains.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11ee946710e67fdaff3adf8128cc82549ef26994 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0262fe0b07ed51e0966829723c36d5fad074391e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab78ae1d8f5132562c07001d235f9c47791ed89c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/groundtypes.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/groundtypes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..250060175d30aedd678caaedfa762b55674c6fe8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/groundtypes.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/integerring.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/integerring.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1a760a060792aba007368720d00ba7eb8105e96 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/integerring.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/modularinteger.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/modularinteger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f35307ea4cd63f9a2693ce148875ec791f290078 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/modularinteger.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/polynomialring.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/polynomialring.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9469c63ca1052d4c2c174b21fa1733e7d3ddf17d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/polynomialring.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonfinitefield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonfinitefield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..952bb548327d1c95fa9202fc8497e76eaeafd5c7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonfinitefield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df38ce0846f47c92dde0a85c7af2ba4a274032f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..427b09bebd50ae27a99917ed085da4fd5b73102f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrationalfield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrationalfield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ba85c5e8183efec7c9d839a63d807f0019aee60 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrationalfield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/rationalfield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/rationalfield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c35ac64c4729df5dd3b726f496be4e024ea8256 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/rationalfield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/realfield.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/realfield.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f83562f8d0c236fef551dc7b80221f87c83f7fb7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/realfield.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/ring.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/ring.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09cf79d9b27a055c2e1a38ac8837f0a6d406f5a2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/ring.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..755abb0f22dfae69e1dbcc53259cc9753030e90a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/algebraicfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/algebraicfield.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee3f10d90fc4a3331471ea9a24589d65654d1cd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/algebraicfield.py @@ -0,0 +1,638 @@ +"""Implementation of :class:`AlgebraicField` class. """ + + +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.singleton import S +from sympy.core.symbol import Dummy, symbols +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.domains.field import Field +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.polyclasses import ANP +from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed +from sympy.utilities import public + +@public +class AlgebraicField(Field, CharacteristicZero, SimpleDomain): + r"""Algebraic number field :ref:`QQ(a)` + + A :ref:`QQ(a)` domain represents an `algebraic number field`_ + `\mathbb{Q}(a)` as a :py:class:`~.Domain` in the domain system (see + :ref:`polys-domainsintro`). + + A :py:class:`~.Poly` created from an expression involving `algebraic + numbers`_ will treat the algebraic numbers as generators if the generators + argument is not specified. + + >>> from sympy import Poly, Symbol, sqrt + >>> x = Symbol('x') + >>> Poly(x**2 + sqrt(2)) + Poly(x**2 + (sqrt(2)), x, sqrt(2), domain='ZZ') + + That is a multivariate polynomial with ``sqrt(2)`` treated as one of the + generators (variables). If the generators are explicitly specified then + ``sqrt(2)`` will be considered to be a coefficient but by default the + :ref:`EX` domain is used. To make a :py:class:`~.Poly` with a :ref:`QQ(a)` + domain the argument ``extension=True`` can be given. + + >>> Poly(x**2 + sqrt(2), x) + Poly(x**2 + sqrt(2), x, domain='EX') + >>> Poly(x**2 + sqrt(2), x, extension=True) + Poly(x**2 + sqrt(2), x, domain='QQ') + + A generator of the algebraic field extension can also be specified + explicitly which is particularly useful if the coefficients are all + rational but an extension field is needed (e.g. to factor the + polynomial). + + >>> Poly(x**2 + 1) + Poly(x**2 + 1, x, domain='ZZ') + >>> Poly(x**2 + 1, extension=sqrt(2)) + Poly(x**2 + 1, x, domain='QQ') + + It is possible to factorise a polynomial over a :ref:`QQ(a)` domain using + the ``extension`` argument to :py:func:`~.factor` or by specifying the domain + explicitly. + + >>> from sympy import factor, QQ + >>> factor(x**2 - 2) + x**2 - 2 + >>> factor(x**2 - 2, extension=sqrt(2)) + (x - sqrt(2))*(x + sqrt(2)) + >>> factor(x**2 - 2, domain='QQ') + (x - sqrt(2))*(x + sqrt(2)) + >>> factor(x**2 - 2, domain=QQ.algebraic_field(sqrt(2))) + (x - sqrt(2))*(x + sqrt(2)) + + The ``extension=True`` argument can be used but will only create an + extension that contains the coefficients which is usually not enough to + factorise the polynomial. + + >>> p = x**3 + sqrt(2)*x**2 - 2*x - 2*sqrt(2) + >>> factor(p) # treats sqrt(2) as a symbol + (x + sqrt(2))*(x**2 - 2) + >>> factor(p, extension=True) + (x - sqrt(2))*(x + sqrt(2))**2 + >>> factor(x**2 - 2, extension=True) # all rational coefficients + x**2 - 2 + + It is also possible to use :ref:`QQ(a)` with the :py:func:`~.cancel` + and :py:func:`~.gcd` functions. + + >>> from sympy import cancel, gcd + >>> cancel((x**2 - 2)/(x - sqrt(2))) + (x**2 - 2)/(x - sqrt(2)) + >>> cancel((x**2 - 2)/(x - sqrt(2)), extension=sqrt(2)) + x + sqrt(2) + >>> gcd(x**2 - 2, x - sqrt(2)) + 1 + >>> gcd(x**2 - 2, x - sqrt(2), extension=sqrt(2)) + x - sqrt(2) + + When using the domain directly :ref:`QQ(a)` can be used as a constructor + to create instances which then support the operations ``+,-,*,**,/``. The + :py:meth:`~.Domain.algebraic_field` method is used to construct a + particular :ref:`QQ(a)` domain. The :py:meth:`~.Domain.from_sympy` method + can be used to create domain elements from normal SymPy expressions. + + >>> K = QQ.algebraic_field(sqrt(2)) + >>> K + QQ + >>> xk = K.from_sympy(3 + 4*sqrt(2)) + >>> xk # doctest: +SKIP + ANP([4, 3], [1, 0, -2], QQ) + + Elements of :ref:`QQ(a)` are instances of :py:class:`~.ANP` which have + limited printing support. The raw display shows the internal + representation of the element as the list ``[4, 3]`` representing the + coefficients of ``1`` and ``sqrt(2)`` for this element in the form + ``a * sqrt(2) + b * 1`` where ``a`` and ``b`` are elements of :ref:`QQ`. + The minimal polynomial for the generator ``(x**2 - 2)`` is also shown in + the :ref:`dup-representation` as the list ``[1, 0, -2]``. We can use + :py:meth:`~.Domain.to_sympy` to get a better printed form for the + elements and to see the results of operations. + + >>> xk = K.from_sympy(3 + 4*sqrt(2)) + >>> yk = K.from_sympy(2 + 3*sqrt(2)) + >>> xk * yk # doctest: +SKIP + ANP([17, 30], [1, 0, -2], QQ) + >>> K.to_sympy(xk * yk) + 17*sqrt(2) + 30 + >>> K.to_sympy(xk + yk) + 5 + 7*sqrt(2) + >>> K.to_sympy(xk ** 2) + 24*sqrt(2) + 41 + >>> K.to_sympy(xk / yk) + sqrt(2)/14 + 9/7 + + Any expression representing an algebraic number can be used to generate + a :ref:`QQ(a)` domain provided its `minimal polynomial`_ can be computed. + The function :py:func:`~.minpoly` function is used for this. + + >>> from sympy import exp, I, pi, minpoly + >>> g = exp(2*I*pi/3) + >>> g + exp(2*I*pi/3) + >>> g.is_algebraic + True + >>> minpoly(g, x) + x**2 + x + 1 + >>> factor(x**3 - 1, extension=g) + (x - 1)*(x - exp(2*I*pi/3))*(x + 1 + exp(2*I*pi/3)) + + It is also possible to make an algebraic field from multiple extension + elements. + + >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) + >>> K + QQ + >>> p = x**4 - 5*x**2 + 6 + >>> factor(p) + (x**2 - 3)*(x**2 - 2) + >>> factor(p, domain=K) + (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3)) + >>> factor(p, extension=[sqrt(2), sqrt(3)]) + (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3)) + + Multiple extension elements are always combined together to make a single + `primitive element`_. In the case of ``[sqrt(2), sqrt(3)]`` the primitive + element chosen is ``sqrt(2) + sqrt(3)`` which is why the domain displays + as ``QQ``. The minimal polynomial for the primitive + element is computed using the :py:func:`~.primitive_element` function. + + >>> from sympy import primitive_element + >>> primitive_element([sqrt(2), sqrt(3)], x) + (x**4 - 10*x**2 + 1, [1, 1]) + >>> minpoly(sqrt(2) + sqrt(3), x) + x**4 - 10*x**2 + 1 + + The extension elements that generate the domain can be accessed from the + domain using the :py:attr:`~.ext` and :py:attr:`~.orig_ext` attributes as + instances of :py:class:`~.AlgebraicNumber`. The minimal polynomial for + the primitive element as a :py:class:`~.DMP` instance is available as + :py:attr:`~.mod`. + + >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) + >>> K + QQ + >>> K.ext + sqrt(2) + sqrt(3) + >>> K.orig_ext + (sqrt(2), sqrt(3)) + >>> K.mod # doctest: +SKIP + DMP_Python([1, 0, -10, 0, 1], QQ) + + The `discriminant`_ of the field can be obtained from the + :py:meth:`~.discriminant` method, and an `integral basis`_ from the + :py:meth:`~.integral_basis` method. The latter returns a list of + :py:class:`~.ANP` instances by default, but can be made to return instances + of :py:class:`~.Expr` or :py:class:`~.AlgebraicNumber` by passing a ``fmt`` + argument. The maximal order, or ring of integers, of the field can also be + obtained from the :py:meth:`~.maximal_order` method, as a + :py:class:`~sympy.polys.numberfields.modules.Submodule`. + + >>> zeta5 = exp(2*I*pi/5) + >>> K = QQ.algebraic_field(zeta5) + >>> K + QQ + >>> K.discriminant() + 125 + >>> K = QQ.algebraic_field(sqrt(5)) + >>> K + QQ + >>> K.integral_basis(fmt='sympy') + [1, 1/2 + sqrt(5)/2] + >>> K.maximal_order() + Submodule[[2, 0], [1, 1]]/2 + + The factorization of a rational prime into prime ideals of the field is + computed by the :py:meth:`~.primes_above` method, which returns a list + of :py:class:`~sympy.polys.numberfields.primes.PrimeIdeal` instances. + + >>> zeta7 = exp(2*I*pi/7) + >>> K = QQ.algebraic_field(zeta7) + >>> K + QQ + >>> K.primes_above(11) + [(11, _x**3 + 5*_x**2 + 4*_x - 1), (11, _x**3 - 4*_x**2 - 5*_x - 1)] + + The Galois group of the Galois closure of the field can be computed (when + the minimal polynomial of the field is of sufficiently small degree). + + >>> K.galois_group(by_name=True)[0] + S6TransitiveSubgroups.C6 + + Notes + ===== + + It is not currently possible to generate an algebraic extension over any + domain other than :ref:`QQ`. Ideally it would be possible to generate + extensions like ``QQ(x)(sqrt(x**2 - 2))``. This is equivalent to the + quotient ring ``QQ(x)[y]/(y**2 - x**2 + 2)`` and there are two + implementations of this kind of quotient ring/extension in the + :py:class:`~.QuotientRing` and :py:class:`~.MonogenicFiniteExtension` + classes. Each of those implementations needs some work to make them fully + usable though. + + .. _algebraic number field: https://en.wikipedia.org/wiki/Algebraic_number_field + .. _algebraic numbers: https://en.wikipedia.org/wiki/Algebraic_number + .. _discriminant: https://en.wikipedia.org/wiki/Discriminant_of_an_algebraic_number_field + .. _integral basis: https://en.wikipedia.org/wiki/Algebraic_number_field#Integral_basis + .. _minimal polynomial: https://en.wikipedia.org/wiki/Minimal_polynomial_(field_theory) + .. _primitive element: https://en.wikipedia.org/wiki/Primitive_element_theorem + """ + + dtype = ANP + + is_AlgebraicField = is_Algebraic = True + is_Numerical = True + + has_assoc_Ring = False + has_assoc_Field = True + + def __init__(self, dom, *ext, alias=None): + r""" + Parameters + ========== + + dom : :py:class:`~.Domain` + The base field over which this is an extension field. + Currently only :ref:`QQ` is accepted. + + *ext : One or more :py:class:`~.Expr` + Generators of the extension. These should be expressions that are + algebraic over `\mathbb{Q}`. + + alias : str, :py:class:`~.Symbol`, None, optional (default=None) + If provided, this will be used as the alias symbol for the + primitive element of the :py:class:`~.AlgebraicField`. + If ``None``, while ``ext`` consists of exactly one + :py:class:`~.AlgebraicNumber`, its alias (if any) will be used. + """ + if not dom.is_QQ: + raise DomainError("ground domain must be a rational field") + + from sympy.polys.numberfields import to_number_field + if len(ext) == 1 and isinstance(ext[0], tuple): + orig_ext = ext[0][1:] + else: + orig_ext = ext + + if alias is None and len(ext) == 1: + alias = getattr(ext[0], 'alias', None) + + self.orig_ext = orig_ext + """ + Original elements given to generate the extension. + + >>> from sympy import QQ, sqrt + >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) + >>> K.orig_ext + (sqrt(2), sqrt(3)) + """ + + self.ext = to_number_field(ext, alias=alias) + """ + Primitive element used for the extension. + + >>> from sympy import QQ, sqrt + >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) + >>> K.ext + sqrt(2) + sqrt(3) + """ + + self.mod = self.ext.minpoly.rep + """ + Minimal polynomial for the primitive element of the extension. + + >>> from sympy import QQ, sqrt + >>> K = QQ.algebraic_field(sqrt(2)) + >>> K.mod + DMP([1, 0, -2], QQ) + """ + + self.domain = self.dom = dom + + self.ngens = 1 + self.symbols = self.gens = (self.ext,) + self.unit = self([dom(1), dom(0)]) + + self.zero = self.dtype.zero(self.mod.to_list(), dom) + self.one = self.dtype.one(self.mod.to_list(), dom) + + self._maximal_order = None + self._discriminant = None + self._nilradicals_mod_p = {} + + def new(self, element): + return self.dtype(element, self.mod.to_list(), self.dom) + + def __str__(self): + return str(self.dom) + '<' + str(self.ext) + '>' + + def __hash__(self): + return hash((self.__class__.__name__, self.dtype, self.dom, self.ext)) + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + if isinstance(other, AlgebraicField): + return self.dtype == other.dtype and self.ext == other.ext + else: + return NotImplemented + + def algebraic_field(self, *extension, alias=None): + r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """ + return AlgebraicField(self.dom, *((self.ext,) + extension), alias=alias) + + def to_alg_num(self, a): + """Convert ``a`` of ``dtype`` to an :py:class:`~.AlgebraicNumber`. """ + return self.ext.field_element(a) + + def to_sympy(self, a): + """Convert ``a`` of ``dtype`` to a SymPy object. """ + # Precompute a converter to be reused: + if not hasattr(self, '_converter'): + self._converter = _make_converter(self) + + return self._converter(a) + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + try: + return self([self.dom.from_sympy(a)]) + except CoercionFailed: + pass + + from sympy.polys.numberfields import to_number_field + + try: + return self(to_number_field(a, self.ext).native_coeffs()) + except (NotAlgebraic, IsomorphismFailed): + raise CoercionFailed( + "%s is not a valid algebraic number in %s" % (a, self)) + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_QQ(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def get_ring(self): + """Returns a ring associated with ``self``. """ + raise DomainError('there is no ring associated with %s' % self) + + def is_positive(self, a): + """Returns True if ``a`` is positive. """ + return self.dom.is_positive(a.LC()) + + def is_negative(self, a): + """Returns True if ``a`` is negative. """ + return self.dom.is_negative(a.LC()) + + def is_nonpositive(self, a): + """Returns True if ``a`` is non-positive. """ + return self.dom.is_nonpositive(a.LC()) + + def is_nonnegative(self, a): + """Returns True if ``a`` is non-negative. """ + return self.dom.is_nonnegative(a.LC()) + + def numer(self, a): + """Returns numerator of ``a``. """ + return a + + def denom(self, a): + """Returns denominator of ``a``. """ + return self.one + + def from_AlgebraicField(K1, a, K0): + """Convert AlgebraicField element 'a' to another AlgebraicField """ + return K1.from_sympy(K0.to_sympy(a)) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a GaussianInteger element 'a' to ``dtype``. """ + return K1.from_sympy(K0.to_sympy(a)) + + def from_GaussianRationalField(K1, a, K0): + """Convert a GaussianRational element 'a' to ``dtype``. """ + return K1.from_sympy(K0.to_sympy(a)) + + def _do_round_two(self): + from sympy.polys.numberfields.basis import round_two + ZK, dK = round_two(self, radicals=self._nilradicals_mod_p) + self._maximal_order = ZK + self._discriminant = dK + + def maximal_order(self): + """ + Compute the maximal order, or ring of integers, of the field. + + Returns + ======= + + :py:class:`~sympy.polys.numberfields.modules.Submodule`. + + See Also + ======== + + integral_basis + + """ + if self._maximal_order is None: + self._do_round_two() + return self._maximal_order + + def integral_basis(self, fmt=None): + r""" + Get an integral basis for the field. + + Parameters + ========== + + fmt : str, None, optional (default=None) + If ``None``, return a list of :py:class:`~.ANP` instances. + If ``"sympy"``, convert each element of the list to an + :py:class:`~.Expr`, using ``self.to_sympy()``. + If ``"alg"``, convert each element of the list to an + :py:class:`~.AlgebraicNumber`, using ``self.to_alg_num()``. + + Examples + ======== + + >>> from sympy import QQ, AlgebraicNumber, sqrt + >>> alpha = AlgebraicNumber(sqrt(5), alias='alpha') + >>> k = QQ.algebraic_field(alpha) + >>> B0 = k.integral_basis() + >>> B1 = k.integral_basis(fmt='sympy') + >>> B2 = k.integral_basis(fmt='alg') + >>> print(B0[1]) # doctest: +SKIP + ANP([mpq(1,2), mpq(1,2)], [mpq(1,1), mpq(0,1), mpq(-5,1)], QQ) + >>> print(B1[1]) + 1/2 + alpha/2 + >>> print(B2[1]) + alpha/2 + 1/2 + + In the last two cases we get legible expressions, which print somewhat + differently because of the different types involved: + + >>> print(type(B1[1])) + + >>> print(type(B2[1])) + + + See Also + ======== + + to_sympy + to_alg_num + maximal_order + """ + ZK = self.maximal_order() + M = ZK.QQ_matrix + n = M.shape[1] + B = [self.new(list(reversed(M[:, j].flat()))) for j in range(n)] + if fmt == 'sympy': + return [self.to_sympy(b) for b in B] + elif fmt == 'alg': + return [self.to_alg_num(b) for b in B] + return B + + def discriminant(self): + """Get the discriminant of the field.""" + if self._discriminant is None: + self._do_round_two() + return self._discriminant + + def primes_above(self, p): + """Compute the prime ideals lying above a given rational prime *p*.""" + from sympy.polys.numberfields.primes import prime_decomp + ZK = self.maximal_order() + dK = self.discriminant() + rad = self._nilradicals_mod_p.get(p) + return prime_decomp(p, ZK=ZK, dK=dK, radical=rad) + + def galois_group(self, by_name=False, max_tries=30, randomize=False): + """ + Compute the Galois group of the Galois closure of this field. + + Examples + ======== + + If the field is Galois, the order of the group will equal the degree + of the field: + + >>> from sympy import QQ + >>> from sympy.abc import x + >>> k = QQ.alg_field_from_poly(x**4 + 1) + >>> G, _ = k.galois_group() + >>> G.order() + 4 + + If the field is not Galois, then its Galois closure is a proper + extension, and the order of the Galois group will be greater than the + degree of the field: + + >>> k = QQ.alg_field_from_poly(x**4 - 2) + >>> G, _ = k.galois_group() + >>> G.order() + 8 + + See Also + ======== + + sympy.polys.numberfields.galoisgroups.galois_group + + """ + return self.ext.minpoly_of_element().galois_group( + by_name=by_name, max_tries=max_tries, randomize=randomize) + + +def _make_converter(K): + """Construct the converter to convert back to Expr""" + # Precompute the effect of converting to SymPy and expanding expressions + # like (sqrt(2) + sqrt(3))**2. Asking Expr to do the expansion on every + # conversion from K to Expr is slow. Here we compute the expansions for + # each power of the generator and collect together the resulting algebraic + # terms and the rational coefficients into a matrix. + + ext = K.ext.as_expr() + todom = K.dom.from_sympy + toexpr = K.dom.to_sympy + + if not ext.is_Add: + powers = [ext**n for n in range(K.mod.degree())] + else: + # primitive_element generates a QQ-linear combination of lower degree + # algebraic numbers to generate the higher degree extension e.g. + # QQ That means that we end up having high powers of low + # degree algebraic numbers that can be reduced. Here we will use the + # minimal polynomials of the algebraic numbers to reduce those powers + # before converting to Expr. + from sympy.polys.numberfields.minpoly import minpoly + + # Decompose ext as a linear combination of gens and make a symbol for + # each gen. + gens, coeffs = zip(*ext.as_coefficients_dict().items()) + syms = symbols(f'a:{len(gens)}', cls=Dummy) + sym2gen = dict(zip(syms, gens)) + + # Make a polynomial ring that can express ext and minpolys of all gens + # in terms of syms. + R = K.dom[syms] + monoms = [R.ring.monomial_basis(i) for i in range(R.ngens)] + ext_dict = {m: todom(c) for m, c in zip(monoms, coeffs)} + ext_poly = R.ring.from_dict(ext_dict) + minpolys = [R.from_sympy(minpoly(g, s)) for s, g in sym2gen.items()] + + # Compute all powers of ext_poly reduced modulo minpolys + powers = [R.one, ext_poly] + for n in range(2, K.mod.degree()): + ext_poly_n = (powers[-1] * ext_poly).rem(minpolys) + powers.append(ext_poly_n) + + # Convert the powers back to Expr. This will recombine some things like + # sqrt(2)*sqrt(3) -> sqrt(6). + powers = [p.as_expr().xreplace(sym2gen) for p in powers] + + # This also expands some rational powers + powers = [p.expand() for p in powers] + + # Collect the rational coefficients and algebraic Expr that can + # map the ANP coefficients into an expanded SymPy expression + terms = [dict(t.as_coeff_Mul()[::-1] for t in Add.make_args(p)) for p in powers] + algebraics = set().union(*terms) + matrix = [[todom(t.get(a, S.Zero)) for t in terms] for a in algebraics] + + # Create a function to do the conversion efficiently: + + def converter(a): + """Convert a to Expr using converter""" + ai = a.to_list()[::-1] + coeffs_dom = [sum(mij*aj for mij, aj in zip(mi, ai)) for mi in matrix] + coeffs_sympy = [toexpr(c) for c in coeffs_dom] + res = Add(*(Mul(c, a) for c, a in zip(coeffs_sympy, algebraics))) + return res + + return converter diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/characteristiczero.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/characteristiczero.py new file mode 100644 index 0000000000000000000000000000000000000000..755a354bea9594b9e8f73256c448b3debae037b2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/characteristiczero.py @@ -0,0 +1,15 @@ +"""Implementation of :class:`CharacteristicZero` class. """ + + +from sympy.polys.domains.domain import Domain +from sympy.utilities import public + +@public +class CharacteristicZero(Domain): + """Domain that has infinite number of elements. """ + + has_CharacteristicZero = True + + def characteristic(self): + """Return the characteristic of this domain. """ + return 0 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/complexfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/complexfield.py new file mode 100644 index 0000000000000000000000000000000000000000..69f0bff2c1b311a150add88d5a1f146ea7b1726a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/complexfield.py @@ -0,0 +1,198 @@ +"""Implementation of :class:`ComplexField` class. """ + + +from sympy.external.gmpy import SYMPY_INTS +from sympy.core.numbers import Float, I +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.domains.field import Field +from sympy.polys.domains.gaussiandomains import QQ_I +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.polyerrors import DomainError, CoercionFailed +from sympy.utilities import public + +from mpmath import MPContext + + +@public +class ComplexField(Field, CharacteristicZero, SimpleDomain): + """Complex numbers up to the given precision. """ + + rep = 'CC' + + is_ComplexField = is_CC = True + + is_Exact = False + is_Numerical = True + + has_assoc_Ring = False + has_assoc_Field = True + + _default_precision = 53 + + @property + def has_default_precision(self): + return self.precision == self._default_precision + + @property + def precision(self): + return self._context.prec + + @property + def dps(self): + return self._context.dps + + @property + def tolerance(self): + return self._tolerance + + def __init__(self, prec=None, dps=None, tol=None): + # XXX: The tolerance parameter is ignored but is kept for backward + # compatibility for now. + + context = MPContext() + + if prec is None and dps is None: + context.prec = self._default_precision + elif dps is None: + context.prec = prec + elif prec is None: + context.dps = dps + else: + raise TypeError("Cannot set both prec and dps") + + self._context = context + + self._dtype = context.mpc + self.zero = self.dtype(0) + self.one = self.dtype(1) + + # XXX: Neither of these is actually used anywhere. + self._max_denom = max(2**context.prec // 200, 99) + self._tolerance = self.one / self._max_denom + + @property + def tp(self): + # XXX: Domain treats tp as an alias of dtype. Here we need two separate + # things: dtype is a callable to make/convert instances. We use tp with + # isinstance to check if an object is an instance of the domain + # already. + return self._dtype + + def dtype(self, x, y=0): + # XXX: This is needed because mpmath does not recognise fmpz. + # It might be better to add conversion routines to mpmath and if that + # happens then this can be removed. + if isinstance(x, SYMPY_INTS): + x = int(x) + if isinstance(y, SYMPY_INTS): + y = int(y) + return self._dtype(x, y) + + def __eq__(self, other): + return isinstance(other, ComplexField) and self.precision == other.precision + + def __hash__(self): + return hash((self.__class__.__name__, self._dtype, self.precision)) + + def to_sympy(self, element): + """Convert ``element`` to SymPy number. """ + return Float(element.real, self.dps) + I*Float(element.imag, self.dps) + + def from_sympy(self, expr): + """Convert SymPy's number to ``dtype``. """ + number = expr.evalf(n=self.dps) + real, imag = number.as_real_imag() + + if real.is_Number and imag.is_Number: + return self.dtype(real, imag) + else: + raise CoercionFailed("expected complex number, got %s" % expr) + + def from_ZZ(self, element, base): + return self.dtype(element) + + def from_ZZ_gmpy(self, element, base): + return self.dtype(int(element)) + + def from_ZZ_python(self, element, base): + return self.dtype(element) + + def from_QQ(self, element, base): + return self.dtype(int(element.numerator)) / int(element.denominator) + + def from_QQ_python(self, element, base): + return self.dtype(element.numerator) / element.denominator + + def from_QQ_gmpy(self, element, base): + return self.dtype(int(element.numerator)) / int(element.denominator) + + def from_GaussianIntegerRing(self, element, base): + return self.dtype(int(element.x), int(element.y)) + + def from_GaussianRationalField(self, element, base): + x = element.x + y = element.y + return (self.dtype(int(x.numerator)) / int(x.denominator) + + self.dtype(0, int(y.numerator)) / int(y.denominator)) + + def from_AlgebraicField(self, element, base): + return self.from_sympy(base.to_sympy(element).evalf(self.dps)) + + def from_RealField(self, element, base): + return self.dtype(element) + + def from_ComplexField(self, element, base): + return self.dtype(element) + + def get_ring(self): + """Returns a ring associated with ``self``. """ + raise DomainError("there is no ring associated with %s" % self) + + def get_exact(self): + """Returns an exact domain associated with ``self``. """ + return QQ_I + + def is_negative(self, element): + """Returns ``False`` for any ``ComplexElement``. """ + return False + + def is_positive(self, element): + """Returns ``False`` for any ``ComplexElement``. """ + return False + + def is_nonnegative(self, element): + """Returns ``False`` for any ``ComplexElement``. """ + return False + + def is_nonpositive(self, element): + """Returns ``False`` for any ``ComplexElement``. """ + return False + + def gcd(self, a, b): + """Returns GCD of ``a`` and ``b``. """ + return self.one + + def lcm(self, a, b): + """Returns LCM of ``a`` and ``b``. """ + return a*b + + def almosteq(self, a, b, tolerance=None): + """Check if ``a`` and ``b`` are almost equal. """ + return self._context.almosteq(a, b, tolerance) + + def is_square(self, a): + """Returns ``True``. Every complex number has a complex square root.""" + return True + + def exsqrt(self, a): + r"""Returns the principal complex square root of ``a``. + + Explanation + =========== + The argument of the principal square root is always within + $(-\frac{\pi}{2}, \frac{\pi}{2}]$. The square root may be + slightly inaccurate due to floating point rounding error. + """ + return a ** 0.5 + +CC = ComplexField() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/compositedomain.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/compositedomain.py new file mode 100644 index 0000000000000000000000000000000000000000..a8f63ba7bb86b1d69493b77bfa8c7f33652adbbf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/compositedomain.py @@ -0,0 +1,52 @@ +"""Implementation of :class:`CompositeDomain` class. """ + + +from sympy.polys.domains.domain import Domain +from sympy.polys.polyerrors import GeneratorsError + +from sympy.utilities import public + +@public +class CompositeDomain(Domain): + """Base class for composite domains, e.g. ZZ[x], ZZ(X). """ + + is_Composite = True + + gens, ngens, symbols, domain = [None]*4 + + def inject(self, *symbols): + """Inject generators into this domain. """ + if not (set(self.symbols) & set(symbols)): + return self.__class__(self.domain, self.symbols + symbols, self.order) + else: + raise GeneratorsError("common generators in %s and %s" % (self.symbols, symbols)) + + def drop(self, *symbols): + """Drop generators from this domain. """ + symset = set(symbols) + newsyms = tuple(s for s in self.symbols if s not in symset) + domain = self.domain.drop(*symbols) + if not newsyms: + return domain + else: + return self.__class__(domain, newsyms, self.order) + + def set_domain(self, domain): + """Set the ground domain of this domain. """ + return self.__class__(domain, self.symbols, self.order) + + @property + def is_Exact(self): + """Returns ``True`` if this domain is exact. """ + return self.domain.is_Exact + + def get_exact(self): + """Returns an exact version of this domain. """ + return self.set_domain(self.domain.get_exact()) + + @property + def has_CharacteristicZero(self): + return self.domain.has_CharacteristicZero + + def characteristic(self): + return self.domain.characteristic() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/domain.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/domain.py new file mode 100644 index 0000000000000000000000000000000000000000..1d7fc1eac6184601c199fb6724a11e92346789f1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/domain.py @@ -0,0 +1,1382 @@ +"""Implementation of :class:`Domain` class. """ + +from __future__ import annotations +from typing import Any + +from sympy.core.numbers import AlgebraicNumber +from sympy.core import Basic, sympify +from sympy.core.sorting import ordered +from sympy.external.gmpy import GROUND_TYPES +from sympy.polys.domains.domainelement import DomainElement +from sympy.polys.orderings import lex +from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError +from sympy.polys.polyutils import _unify_gens, _not_a_coeff +from sympy.utilities import public +from sympy.utilities.iterables import is_sequence + + +@public +class Domain: + """Superclass for all domains in the polys domains system. + + See :ref:`polys-domainsintro` for an introductory explanation of the + domains system. + + The :py:class:`~.Domain` class is an abstract base class for all of the + concrete domain types. There are many different :py:class:`~.Domain` + subclasses each of which has an associated ``dtype`` which is a class + representing the elements of the domain. The coefficients of a + :py:class:`~.Poly` are elements of a domain which must be a subclass of + :py:class:`~.Domain`. + + Examples + ======== + + The most common example domains are the integers :ref:`ZZ` and the + rationals :ref:`QQ`. + + >>> from sympy import Poly, symbols, Domain + >>> x, y = symbols('x, y') + >>> p = Poly(x**2 + y) + >>> p + Poly(x**2 + y, x, y, domain='ZZ') + >>> p.domain + ZZ + >>> isinstance(p.domain, Domain) + True + >>> Poly(x**2 + y/2) + Poly(x**2 + 1/2*y, x, y, domain='QQ') + + The domains can be used directly in which case the domain object e.g. + (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of + ``dtype``. + + >>> from sympy import ZZ, QQ + >>> ZZ(2) + 2 + >>> ZZ.dtype # doctest: +SKIP + + >>> type(ZZ(2)) # doctest: +SKIP + + >>> QQ(1, 2) + 1/2 + >>> type(QQ(1, 2)) # doctest: +SKIP + + + The corresponding domain elements can be used with the arithmetic + operations ``+,-,*,**`` and depending on the domain some combination of + ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor + division) and ``%`` (modulo division) can be used but ``/`` (true + division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements + can be used with ``/`` but ``//`` and ``%`` should not be used. Some + domains have a :py:meth:`~.Domain.gcd` method. + + >>> ZZ(2) + ZZ(3) + 5 + >>> ZZ(5) // ZZ(2) + 2 + >>> ZZ(5) % ZZ(2) + 1 + >>> QQ(1, 2) / QQ(2, 3) + 3/4 + >>> ZZ.gcd(ZZ(4), ZZ(2)) + 2 + >>> QQ.gcd(QQ(2,7), QQ(5,3)) + 1/21 + >>> ZZ.is_Field + False + >>> QQ.is_Field + True + + There are also many other domains including: + + 1. :ref:`GF(p)` for finite fields of prime order. + 2. :ref:`RR` for real (floating point) numbers. + 3. :ref:`CC` for complex (floating point) numbers. + 4. :ref:`QQ(a)` for algebraic number fields. + 5. :ref:`K[x]` for polynomial rings. + 6. :ref:`K(x)` for rational function fields. + 7. :ref:`EX` for arbitrary expressions. + + Each domain is represented by a domain object and also an implementation + class (``dtype``) for the elements of the domain. For example the + :ref:`K[x]` domains are represented by a domain object which is an + instance of :py:class:`~.PolynomialRing` and the elements are always + instances of :py:class:`~.PolyElement`. The implementation class + represents particular types of mathematical expressions in a way that is + more efficient than a normal SymPy expression which is of type + :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and + :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr` + to a domain element and vice versa. + + >>> from sympy import Symbol, ZZ, Expr + >>> x = Symbol('x') + >>> K = ZZ[x] # polynomial ring domain + >>> K + ZZ[x] + >>> type(K) # class of the domain + + >>> K.dtype # doctest: +SKIP + + >>> p_expr = x**2 + 1 # Expr + >>> p_expr + x**2 + 1 + >>> type(p_expr) + + >>> isinstance(p_expr, Expr) + True + >>> p_domain = K.from_sympy(p_expr) + >>> p_domain # domain element + x**2 + 1 + >>> type(p_domain) + + >>> K.to_sympy(p_domain) == p_expr + True + + The :py:meth:`~.Domain.convert_from` method is used to convert domain + elements from one domain to another. + + >>> from sympy import ZZ, QQ + >>> ez = ZZ(2) + >>> eq = QQ.convert_from(ez, ZZ) + >>> type(ez) # doctest: +SKIP + + >>> type(eq) # doctest: +SKIP + + + Elements from different domains should not be mixed in arithmetic or other + operations: they should be converted to a common domain first. The domain + method :py:meth:`~.Domain.unify` is used to find a domain that can + represent all the elements of two given domains. + + >>> from sympy import ZZ, QQ, symbols + >>> x, y = symbols('x, y') + >>> ZZ.unify(QQ) + QQ + >>> ZZ[x].unify(QQ) + QQ[x] + >>> ZZ[x].unify(QQ[y]) + QQ[x,y] + + If a domain is a :py:class:`~.Ring` then is might have an associated + :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and + :py:meth:`~.Domain.get_ring` methods will find or create the associated + domain. + + >>> from sympy import ZZ, QQ, Symbol + >>> x = Symbol('x') + >>> ZZ.has_assoc_Field + True + >>> ZZ.get_field() + QQ + >>> QQ.has_assoc_Ring + True + >>> QQ.get_ring() + ZZ + >>> K = QQ[x] + >>> K + QQ[x] + >>> K.get_field() + QQ(x) + + See also + ======== + + DomainElement: abstract base class for domain elements + construct_domain: construct a minimal domain for some expressions + + """ + + dtype: type | None = None + """The type (class) of the elements of this :py:class:`~.Domain`: + + >>> from sympy import ZZ, QQ, Symbol + >>> ZZ.dtype + + >>> z = ZZ(2) + >>> z + 2 + >>> type(z) + + >>> type(z) == ZZ.dtype + True + + Every domain has an associated **dtype** ("datatype") which is the + class of the associated domain elements. + + See also + ======== + + of_type + """ + + zero: Any = None + """The zero element of the :py:class:`~.Domain`: + + >>> from sympy import QQ + >>> QQ.zero + 0 + >>> QQ.of_type(QQ.zero) + True + + See also + ======== + + of_type + one + """ + + one: Any = None + """The one element of the :py:class:`~.Domain`: + + >>> from sympy import QQ + >>> QQ.one + 1 + >>> QQ.of_type(QQ.one) + True + + See also + ======== + + of_type + zero + """ + + is_Ring = False + """Boolean flag indicating if the domain is a :py:class:`~.Ring`. + + >>> from sympy import ZZ + >>> ZZ.is_Ring + True + + Basically every :py:class:`~.Domain` represents a ring so this flag is + not that useful. + + See also + ======== + + is_PID + is_Field + get_ring + has_assoc_Ring + """ + + is_Field = False + """Boolean flag indicating if the domain is a :py:class:`~.Field`. + + >>> from sympy import ZZ, QQ + >>> ZZ.is_Field + False + >>> QQ.is_Field + True + + See also + ======== + + is_PID + is_Ring + get_field + has_assoc_Field + """ + + has_assoc_Ring = False + """Boolean flag indicating if the domain has an associated + :py:class:`~.Ring`. + + >>> from sympy import QQ + >>> QQ.has_assoc_Ring + True + >>> QQ.get_ring() + ZZ + + See also + ======== + + is_Field + get_ring + """ + + has_assoc_Field = False + """Boolean flag indicating if the domain has an associated + :py:class:`~.Field`. + + >>> from sympy import ZZ + >>> ZZ.has_assoc_Field + True + >>> ZZ.get_field() + QQ + + See also + ======== + + is_Field + get_field + """ + + is_FiniteField = is_FF = False + is_IntegerRing = is_ZZ = False + is_RationalField = is_QQ = False + is_GaussianRing = is_ZZ_I = False + is_GaussianField = is_QQ_I = False + is_RealField = is_RR = False + is_ComplexField = is_CC = False + is_AlgebraicField = is_Algebraic = False + is_PolynomialRing = is_Poly = False + is_FractionField = is_Frac = False + is_SymbolicDomain = is_EX = False + is_SymbolicRawDomain = is_EXRAW = False + is_FiniteExtension = False + + is_Exact = True + is_Numerical = False + + is_Simple = False + is_Composite = False + + is_PID = False + """Boolean flag indicating if the domain is a `principal ideal domain`_. + + >>> from sympy import ZZ + >>> ZZ.has_assoc_Field + True + >>> ZZ.get_field() + QQ + + .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain + + See also + ======== + + is_Field + get_field + """ + + has_CharacteristicZero = False + + rep: str | None = None + alias: str | None = None + + def __init__(self): + raise NotImplementedError + + def __str__(self): + return self.rep + + def __repr__(self): + return str(self) + + def __hash__(self): + return hash((self.__class__.__name__, self.dtype)) + + def new(self, *args): + return self.dtype(*args) + + @property + def tp(self): + """Alias for :py:attr:`~.Domain.dtype`""" + return self.dtype + + def __call__(self, *args): + """Construct an element of ``self`` domain from ``args``. """ + return self.new(*args) + + def normal(self, *args): + return self.dtype(*args) + + def convert_from(self, element, base): + """Convert ``element`` to ``self.dtype`` given the base domain. """ + if base.alias is not None: + method = "from_" + base.alias + else: + method = "from_" + base.__class__.__name__ + + _convert = getattr(self, method) + + if _convert is not None: + result = _convert(element, base) + + if result is not None: + return result + + raise CoercionFailed("Cannot convert %s of type %s from %s to %s" % (element, type(element), base, self)) + + def convert(self, element, base=None): + """Convert ``element`` to ``self.dtype``. """ + + if base is not None: + if _not_a_coeff(element): + raise CoercionFailed('%s is not in any domain' % element) + return self.convert_from(element, base) + + if self.of_type(element): + return element + + if _not_a_coeff(element): + raise CoercionFailed('%s is not in any domain' % element) + + from sympy.polys.domains import ZZ, QQ, RealField, ComplexField + + if ZZ.of_type(element): + return self.convert_from(element, ZZ) + + if isinstance(element, int): + return self.convert_from(ZZ(element), ZZ) + + if GROUND_TYPES != 'python': + if isinstance(element, ZZ.tp): + return self.convert_from(element, ZZ) + if isinstance(element, QQ.tp): + return self.convert_from(element, QQ) + + if isinstance(element, float): + parent = RealField() + return self.convert_from(parent(element), parent) + + if isinstance(element, complex): + parent = ComplexField() + return self.convert_from(parent(element), parent) + + if type(element).__name__ == 'mpf': + parent = RealField() + return self.convert_from(parent(element), parent) + + if type(element).__name__ == 'mpc': + parent = ComplexField() + return self.convert_from(parent(element), parent) + + if isinstance(element, DomainElement): + return self.convert_from(element, element.parent()) + + # TODO: implement this in from_ methods + if self.is_Numerical and getattr(element, 'is_ground', False): + return self.convert(element.LC()) + + if isinstance(element, Basic): + try: + return self.from_sympy(element) + except (TypeError, ValueError): + pass + else: # TODO: remove this branch + if not is_sequence(element): + try: + element = sympify(element, strict=True) + if isinstance(element, Basic): + return self.from_sympy(element) + except (TypeError, ValueError): + pass + + raise CoercionFailed("Cannot convert %s of type %s to %s" % (element, type(element), self)) + + def of_type(self, element): + """Check if ``a`` is of type ``dtype``. """ + return isinstance(element, self.tp) + + def __contains__(self, a): + """Check if ``a`` belongs to this domain. """ + try: + if _not_a_coeff(a): + raise CoercionFailed + self.convert(a) # this might raise, too + except CoercionFailed: + return False + + return True + + def to_sympy(self, a): + """Convert domain element *a* to a SymPy expression (Expr). + + Explanation + =========== + + Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most + public SymPy functions work with objects of type :py:class:`~.Expr`. + The elements of a :py:class:`~.Domain` have a different internal + representation. It is not possible to mix domain elements with + :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and + :py:meth:`~.Domain.from_sympy` methods to convert its domain elements + to and from :py:class:`~.Expr`. + + Parameters + ========== + + a: domain element + An element of this :py:class:`~.Domain`. + + Returns + ======= + + expr: Expr + A normal SymPy expression of type :py:class:`~.Expr`. + + Examples + ======== + + Construct an element of the :ref:`QQ` domain and then convert it to + :py:class:`~.Expr`. + + >>> from sympy import QQ, Expr + >>> q_domain = QQ(2) + >>> q_domain + 2 + >>> q_expr = QQ.to_sympy(q_domain) + >>> q_expr + 2 + + Although the printed forms look similar these objects are not of the + same type. + + >>> isinstance(q_domain, Expr) + False + >>> isinstance(q_expr, Expr) + True + + Construct an element of :ref:`K[x]` and convert to + :py:class:`~.Expr`. + + >>> from sympy import Symbol + >>> x = Symbol('x') + >>> K = QQ[x] + >>> x_domain = K.gens[0] # generator x as a domain element + >>> p_domain = x_domain**2/3 + 1 + >>> p_domain + 1/3*x**2 + 1 + >>> p_expr = K.to_sympy(p_domain) + >>> p_expr + x**2/3 + 1 + + The :py:meth:`~.Domain.from_sympy` method is used for the opposite + conversion from a normal SymPy expression to a domain element. + + >>> p_domain == p_expr + False + >>> K.from_sympy(p_expr) == p_domain + True + >>> K.to_sympy(p_domain) == p_expr + True + >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain + True + >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr + True + + The :py:meth:`~.Domain.from_sympy` method makes it easier to construct + domain elements interactively. + + >>> from sympy import Symbol + >>> x = Symbol('x') + >>> K = QQ[x] + >>> K.from_sympy(x**2/3 + 1) + 1/3*x**2 + 1 + + See also + ======== + + from_sympy + convert_from + """ + raise NotImplementedError + + def from_sympy(self, a): + """Convert a SymPy expression to an element of this domain. + + Explanation + =========== + + See :py:meth:`~.Domain.to_sympy` for explanation and examples. + + Parameters + ========== + + expr: Expr + A normal SymPy expression of type :py:class:`~.Expr`. + + Returns + ======= + + a: domain element + An element of this :py:class:`~.Domain`. + + See also + ======== + + to_sympy + convert_from + """ + raise NotImplementedError + + def sum(self, args): + return sum(args, start=self.zero) + + def from_FF(K1, a, K0): + """Convert ``ModularInteger(int)`` to ``dtype``. """ + return None + + def from_FF_python(K1, a, K0): + """Convert ``ModularInteger(int)`` to ``dtype``. """ + return None + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return None + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return None + + def from_FF_gmpy(K1, a, K0): + """Convert ``ModularInteger(mpz)`` to ``dtype``. """ + return None + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return None + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return None + + def from_RealField(K1, a, K0): + """Convert a real element object to ``dtype``. """ + return None + + def from_ComplexField(K1, a, K0): + """Convert a complex element to ``dtype``. """ + return None + + def from_AlgebraicField(K1, a, K0): + """Convert an algebraic number to ``dtype``. """ + return None + + def from_PolynomialRing(K1, a, K0): + """Convert a polynomial to ``dtype``. """ + if a.is_ground: + return K1.convert(a.LC, K0.dom) + + def from_FractionField(K1, a, K0): + """Convert a rational function to ``dtype``. """ + return None + + def from_MonogenicFiniteExtension(K1, a, K0): + """Convert an ``ExtensionElement`` to ``dtype``. """ + return K1.convert_from(a.rep, K0.ring) + + def from_ExpressionDomain(K1, a, K0): + """Convert a ``EX`` object to ``dtype``. """ + return K1.from_sympy(a.ex) + + def from_ExpressionRawDomain(K1, a, K0): + """Convert a ``EX`` object to ``dtype``. """ + return K1.from_sympy(a) + + def from_GlobalPolynomialRing(K1, a, K0): + """Convert a polynomial to ``dtype``. """ + if a.degree() <= 0: + return K1.convert(a.LC(), K0.dom) + + def from_GeneralizedPolynomialRing(K1, a, K0): + return K1.from_FractionField(a, K0) + + def unify_with_symbols(K0, K1, symbols): + if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))): + raise UnificationFailed("Cannot unify %s with %s, given %s generators" % (K0, K1, tuple(symbols))) + + return K0.unify(K1) + + def unify_composite(K0, K1): + """Unify two domains where at least one is composite.""" + K0_ground = K0.dom if K0.is_Composite else K0 + K1_ground = K1.dom if K1.is_Composite else K1 + + K0_symbols = K0.symbols if K0.is_Composite else () + K1_symbols = K1.symbols if K1.is_Composite else () + + domain = K0_ground.unify(K1_ground) + symbols = _unify_gens(K0_symbols, K1_symbols) + order = K0.order if K0.is_Composite else K1.order + + # E.g. ZZ[x].unify(QQ.frac_field(x)) -> ZZ.frac_field(x) + if ((K0.is_FractionField and K1.is_PolynomialRing or + K1.is_FractionField and K0.is_PolynomialRing) and + (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field + and domain.has_assoc_Ring): + domain = domain.get_ring() + + if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing): + cls = K0.__class__ + else: + cls = K1.__class__ + + # Here cls might be PolynomialRing, FractionField, GlobalPolynomialRing + # (dense/old Polynomialring) or dense/old FractionField. + + from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing + if cls == GlobalPolynomialRing: + return cls(domain, symbols) + + return cls(domain, symbols, order) + + def unify(K0, K1, symbols=None): + """ + Construct a minimal domain that contains elements of ``K0`` and ``K1``. + + Known domains (from smallest to largest): + + - ``GF(p)`` + - ``ZZ`` + - ``QQ`` + - ``RR(prec, tol)`` + - ``CC(prec, tol)`` + - ``ALG(a, b, c)`` + - ``K[x, y, z]`` + - ``K(x, y, z)`` + - ``EX`` + + """ + if symbols is not None: + return K0.unify_with_symbols(K1, symbols) + + if K0 == K1: + return K0 + + if not (K0.has_CharacteristicZero and K1.has_CharacteristicZero): + # Reject unification of domains with different characteristics. + if K0.characteristic() != K1.characteristic(): + raise UnificationFailed("Cannot unify %s with %s" % (K0, K1)) + + # We do not get here if K0 == K1. The two domains have the same + # characteristic but are unequal so at least one is composite and + # we are unifying something like GF(3).unify(GF(3)[x]). + return K0.unify_composite(K1) + + # From here we know both domains have characteristic zero and it can be + # acceptable to fall back on EX. + + if K0.is_EXRAW: + return K0 + if K1.is_EXRAW: + return K1 + + if K0.is_EX: + return K0 + if K1.is_EX: + return K1 + + if K0.is_FiniteExtension or K1.is_FiniteExtension: + if K1.is_FiniteExtension: + K0, K1 = K1, K0 + if K1.is_FiniteExtension: + # Unifying two extensions. + # Try to ensure that K0.unify(K1) == K1.unify(K0) + if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus: + K0, K1 = K1, K0 + return K1.set_domain(K0) + else: + # Drop the generator from other and unify with the base domain + K1 = K1.drop(K0.symbol) + K1 = K0.domain.unify(K1) + return K0.set_domain(K1) + + if K0.is_Composite or K1.is_Composite: + return K0.unify_composite(K1) + + if K1.is_ComplexField: + K0, K1 = K1, K0 + if K0.is_ComplexField: + if K1.is_ComplexField or K1.is_RealField: + if K0.precision >= K1.precision: + return K0 + else: + from sympy.polys.domains.complexfield import ComplexField + return ComplexField(prec=K1.precision) + else: + return K0 + + if K1.is_RealField: + K0, K1 = K1, K0 + if K0.is_RealField: + if K1.is_RealField: + if K0.precision >= K1.precision: + return K0 + else: + return K1 + elif K1.is_GaussianRing or K1.is_GaussianField: + from sympy.polys.domains.complexfield import ComplexField + return ComplexField(prec=K0.precision) + else: + return K0 + + if K1.is_AlgebraicField: + K0, K1 = K1, K0 + if K0.is_AlgebraicField: + if K1.is_GaussianRing: + K1 = K1.get_field() + if K1.is_GaussianField: + K1 = K1.as_AlgebraicField() + if K1.is_AlgebraicField: + return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext)) + else: + return K0 + + if K0.is_GaussianField: + return K0 + if K1.is_GaussianField: + return K1 + + if K0.is_GaussianRing: + if K1.is_RationalField: + K0 = K0.get_field() + return K0 + if K1.is_GaussianRing: + if K0.is_RationalField: + K1 = K1.get_field() + return K1 + + if K0.is_RationalField: + return K0 + if K1.is_RationalField: + return K1 + + if K0.is_IntegerRing: + return K0 + if K1.is_IntegerRing: + return K1 + + from sympy.polys.domains import EX + return EX + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + # XXX: Remove this. + return isinstance(other, Domain) and self.dtype == other.dtype + + def __ne__(self, other): + """Returns ``False`` if two domains are equivalent. """ + return not self == other + + def map(self, seq): + """Rersively apply ``self`` to all elements of ``seq``. """ + result = [] + + for elt in seq: + if isinstance(elt, list): + result.append(self.map(elt)) + else: + result.append(self(elt)) + + return result + + def get_ring(self): + """Returns a ring associated with ``self``. """ + raise DomainError('there is no ring associated with %s' % self) + + def get_field(self): + """Returns a field associated with ``self``. """ + raise DomainError('there is no field associated with %s' % self) + + def get_exact(self): + """Returns an exact domain associated with ``self``. """ + return self + + def __getitem__(self, symbols): + """The mathematical way to make a polynomial ring. """ + if hasattr(symbols, '__iter__'): + return self.poly_ring(*symbols) + else: + return self.poly_ring(symbols) + + def poly_ring(self, *symbols, order=lex): + """Returns a polynomial ring, i.e. `K[X]`. """ + from sympy.polys.domains.polynomialring import PolynomialRing + return PolynomialRing(self, symbols, order) + + def frac_field(self, *symbols, order=lex): + """Returns a fraction field, i.e. `K(X)`. """ + from sympy.polys.domains.fractionfield import FractionField + return FractionField(self, symbols, order) + + def old_poly_ring(self, *symbols, **kwargs): + """Returns a polynomial ring, i.e. `K[X]`. """ + from sympy.polys.domains.old_polynomialring import PolynomialRing + return PolynomialRing(self, *symbols, **kwargs) + + def old_frac_field(self, *symbols, **kwargs): + """Returns a fraction field, i.e. `K(X)`. """ + from sympy.polys.domains.old_fractionfield import FractionField + return FractionField(self, *symbols, **kwargs) + + def algebraic_field(self, *extension, alias=None): + r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """ + raise DomainError("Cannot create algebraic field over %s" % self) + + def alg_field_from_poly(self, poly, alias=None, root_index=-1): + r""" + Convenience method to construct an algebraic extension on a root of a + polynomial, chosen by root index. + + Parameters + ========== + + poly : :py:class:`~.Poly` + The polynomial whose root generates the extension. + alias : str, optional (default=None) + Symbol name for the generator of the extension. + E.g. "alpha" or "theta". + root_index : int, optional (default=-1) + Specifies which root of the polynomial is desired. The ordering is + as defined by the :py:class:`~.ComplexRootOf` class. The default of + ``-1`` selects the most natural choice in the common cases of + quadratic and cyclotomic fields (the square root on the positive + real or imaginary axis, resp. $\mathrm{e}^{2\pi i/n}$). + + Examples + ======== + + >>> from sympy import QQ, Poly + >>> from sympy.abc import x + >>> f = Poly(x**2 - 2) + >>> K = QQ.alg_field_from_poly(f) + >>> K.ext.minpoly == f + True + >>> g = Poly(8*x**3 - 6*x - 1) + >>> L = QQ.alg_field_from_poly(g, "alpha") + >>> L.ext.minpoly == g + True + >>> L.to_sympy(L([1, 1, 1])) + alpha**2 + alpha + 1 + + """ + from sympy.polys.rootoftools import CRootOf + root = CRootOf(poly, root_index) + alpha = AlgebraicNumber(root, alias=alias) + return self.algebraic_field(alpha, alias=alias) + + def cyclotomic_field(self, n, ss=False, alias="zeta", gen=None, root_index=-1): + r""" + Convenience method to construct a cyclotomic field. + + Parameters + ========== + + n : int + Construct the nth cyclotomic field. + ss : boolean, optional (default=False) + If True, append *n* as a subscript on the alias string. + alias : str, optional (default="zeta") + Symbol name for the generator. + gen : :py:class:`~.Symbol`, optional (default=None) + Desired variable for the cyclotomic polynomial that defines the + field. If ``None``, a dummy variable will be used. + root_index : int, optional (default=-1) + Specifies which root of the polynomial is desired. The ordering is + as defined by the :py:class:`~.ComplexRootOf` class. The default of + ``-1`` selects the root $\mathrm{e}^{2\pi i/n}$. + + Examples + ======== + + >>> from sympy import QQ, latex + >>> K = QQ.cyclotomic_field(5) + >>> K.to_sympy(K([-1, 1])) + 1 - zeta + >>> L = QQ.cyclotomic_field(7, True) + >>> a = L.to_sympy(L([-1, 1])) + >>> print(a) + 1 - zeta7 + >>> print(latex(a)) + 1 - \zeta_{7} + + """ + from sympy.polys.specialpolys import cyclotomic_poly + if ss: + alias += str(n) + return self.alg_field_from_poly(cyclotomic_poly(n, gen), alias=alias, + root_index=root_index) + + def inject(self, *symbols): + """Inject generators into this domain. """ + raise NotImplementedError + + def drop(self, *symbols): + """Drop generators from this domain. """ + if self.is_Simple: + return self + raise NotImplementedError # pragma: no cover + + def is_zero(self, a): + """Returns True if ``a`` is zero. """ + return not a + + def is_one(self, a): + """Returns True if ``a`` is one. """ + return a == self.one + + def is_positive(self, a): + """Returns True if ``a`` is positive. """ + return a > 0 + + def is_negative(self, a): + """Returns True if ``a`` is negative. """ + return a < 0 + + def is_nonpositive(self, a): + """Returns True if ``a`` is non-positive. """ + return a <= 0 + + def is_nonnegative(self, a): + """Returns True if ``a`` is non-negative. """ + return a >= 0 + + def canonical_unit(self, a): + if self.is_negative(a): + return -self.one + else: + return self.one + + def abs(self, a): + """Absolute value of ``a``, implies ``__abs__``. """ + return abs(a) + + def neg(self, a): + """Returns ``a`` negated, implies ``__neg__``. """ + return -a + + def pos(self, a): + """Returns ``a`` positive, implies ``__pos__``. """ + return +a + + def add(self, a, b): + """Sum of ``a`` and ``b``, implies ``__add__``. """ + return a + b + + def sub(self, a, b): + """Difference of ``a`` and ``b``, implies ``__sub__``. """ + return a - b + + def mul(self, a, b): + """Product of ``a`` and ``b``, implies ``__mul__``. """ + return a * b + + def pow(self, a, b): + """Raise ``a`` to power ``b``, implies ``__pow__``. """ + return a ** b + + def exquo(self, a, b): + """Exact quotient of *a* and *b*. Analogue of ``a / b``. + + Explanation + =========== + + This is essentially the same as ``a / b`` except that an error will be + raised if the division is inexact (if there is any remainder) and the + result will always be a domain element. When working in a + :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ` + or :ref:`K[x]`) ``exquo`` should be used instead of ``/``. + + The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does + not raise an exception) then ``a == b*q``. + + Examples + ======== + + We can use ``K.exquo`` instead of ``/`` for exact division. + + >>> from sympy import ZZ + >>> ZZ.exquo(ZZ(4), ZZ(2)) + 2 + >>> ZZ.exquo(ZZ(5), ZZ(2)) + Traceback (most recent call last): + ... + ExactQuotientFailed: 2 does not divide 5 in ZZ + + Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero + divisor) is always exact so in that case ``/`` can be used instead of + :py:meth:`~.Domain.exquo`. + + >>> from sympy import QQ + >>> QQ.exquo(QQ(5), QQ(2)) + 5/2 + >>> QQ(5) / QQ(2) + 5/2 + + Parameters + ========== + + a: domain element + The dividend + b: domain element + The divisor + + Returns + ======= + + q: domain element + The exact quotient + + Raises + ====== + + ExactQuotientFailed: if exact division is not possible. + ZeroDivisionError: when the divisor is zero. + + See also + ======== + + quo: Analogue of ``a // b`` + rem: Analogue of ``a % b`` + div: Analogue of ``divmod(a, b)`` + + Notes + ===== + + Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int`` + (or ``mpz``) division as ``a / b`` should not be used as it would give + a ``float`` which is not a domain element. + + >>> ZZ(4) / ZZ(2) # doctest: +SKIP + 2.0 + >>> ZZ(5) / ZZ(2) # doctest: +SKIP + 2.5 + + On the other hand with `SYMPY_GROUND_TYPES=flint` elements of :ref:`ZZ` + are ``flint.fmpz`` and division would raise an exception: + + >>> ZZ(4) / ZZ(2) # doctest: +SKIP + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for /: 'fmpz' and 'fmpz' + + Using ``/`` with :ref:`ZZ` will lead to incorrect results so + :py:meth:`~.Domain.exquo` should be used instead. + + """ + raise NotImplementedError + + def quo(self, a, b): + """Quotient of *a* and *b*. Analogue of ``a // b``. + + ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See + :py:meth:`~.Domain.div` for more explanation. + + See also + ======== + + rem: Analogue of ``a % b`` + div: Analogue of ``divmod(a, b)`` + exquo: Analogue of ``a / b`` + """ + raise NotImplementedError + + def rem(self, a, b): + """Modulo division of *a* and *b*. Analogue of ``a % b``. + + ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See + :py:meth:`~.Domain.div` for more explanation. + + See also + ======== + + quo: Analogue of ``a // b`` + div: Analogue of ``divmod(a, b)`` + exquo: Analogue of ``a / b`` + """ + raise NotImplementedError + + def div(self, a, b): + """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)`` + + Explanation + =========== + + This is essentially the same as ``divmod(a, b)`` except that is more + consistent when working over some :py:class:`~.Field` domains such as + :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the + :py:meth:`~.Domain.div` method should be used instead of ``divmod``. + + The key invariant is that if ``q, r = K.div(a, b)`` then + ``a == b*q + r``. + + The result of ``K.div(a, b)`` is the same as the tuple + ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and + remainder are needed then it is more efficient to use + :py:meth:`~.Domain.div`. + + Examples + ======== + + We can use ``K.div`` instead of ``divmod`` for floor division and + remainder. + + >>> from sympy import ZZ, QQ + >>> ZZ.div(ZZ(5), ZZ(2)) + (2, 1) + + If ``K`` is a :py:class:`~.Field` then the division is always exact + with a remainder of :py:attr:`~.Domain.zero`. + + >>> QQ.div(QQ(5), QQ(2)) + (5/2, 0) + + Parameters + ========== + + a: domain element + The dividend + b: domain element + The divisor + + Returns + ======= + + (q, r): tuple of domain elements + The quotient and remainder + + Raises + ====== + + ZeroDivisionError: when the divisor is zero. + + See also + ======== + + quo: Analogue of ``a // b`` + rem: Analogue of ``a % b`` + exquo: Analogue of ``a / b`` + + Notes + ===== + + If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as + the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type + defines ``divmod`` in a way that is undesirable so + :py:meth:`~.Domain.div` should be used instead of ``divmod``. + + >>> a = QQ(1) + >>> b = QQ(3, 2) + >>> a # doctest: +SKIP + mpq(1,1) + >>> b # doctest: +SKIP + mpq(3,2) + >>> divmod(a, b) # doctest: +SKIP + (mpz(0), mpq(1,1)) + >>> QQ.div(a, b) # doctest: +SKIP + (mpq(2,3), mpq(0,1)) + + Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so + :py:meth:`~.Domain.div` should be used instead. + + """ + raise NotImplementedError + + def invert(self, a, b): + """Returns inversion of ``a mod b``, implies something. """ + raise NotImplementedError + + def revert(self, a): + """Returns ``a**(-1)`` if possible. """ + raise NotImplementedError + + def numer(self, a): + """Returns numerator of ``a``. """ + raise NotImplementedError + + def denom(self, a): + """Returns denominator of ``a``. """ + raise NotImplementedError + + def half_gcdex(self, a, b): + """Half extended GCD of ``a`` and ``b``. """ + s, t, h = self.gcdex(a, b) + return s, h + + def gcdex(self, a, b): + """Extended GCD of ``a`` and ``b``. """ + raise NotImplementedError + + def cofactors(self, a, b): + """Returns GCD and cofactors of ``a`` and ``b``. """ + gcd = self.gcd(a, b) + cfa = self.quo(a, gcd) + cfb = self.quo(b, gcd) + return gcd, cfa, cfb + + def gcd(self, a, b): + """Returns GCD of ``a`` and ``b``. """ + raise NotImplementedError + + def lcm(self, a, b): + """Returns LCM of ``a`` and ``b``. """ + raise NotImplementedError + + def log(self, a, b): + """Returns b-base logarithm of ``a``. """ + raise NotImplementedError + + def sqrt(self, a): + """Returns a (possibly inexact) square root of ``a``. + + Explanation + =========== + There is no universal definition of "inexact square root" for all + domains. It is not recommended to implement this method for domains + other then :ref:`ZZ`. + + See also + ======== + exsqrt + """ + raise NotImplementedError + + def is_square(self, a): + """Returns whether ``a`` is a square in the domain. + + Explanation + =========== + Returns ``True`` if there is an element ``b`` in the domain such that + ``b * b == a``, otherwise returns ``False``. For inexact domains like + :ref:`RR` and :ref:`CC`, a tiny difference in this equality can be + tolerated. + + See also + ======== + exsqrt + """ + raise NotImplementedError + + def exsqrt(self, a): + """Principal square root of a within the domain if ``a`` is square. + + Explanation + =========== + The implementation of this method should return an element ``b`` in the + domain such that ``b * b == a``, or ``None`` if there is no such ``b``. + For inexact domains like :ref:`RR` and :ref:`CC`, a tiny difference in + this equality can be tolerated. The choice of a "principal" square root + should follow a consistent rule whenever possible. + + See also + ======== + sqrt, is_square + """ + raise NotImplementedError + + def evalf(self, a, prec=None, **options): + """Returns numerical approximation of ``a``. """ + return self.to_sympy(a).evalf(prec, **options) + + n = evalf + + def real(self, a): + return a + + def imag(self, a): + return self.zero + + def almosteq(self, a, b, tolerance=None): + """Check if ``a`` and ``b`` are almost equal. """ + return a == b + + def characteristic(self): + """Return the characteristic of this domain. """ + raise NotImplementedError('characteristic()') + + +__all__ = ['Domain'] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/domainelement.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/domainelement.py new file mode 100644 index 0000000000000000000000000000000000000000..b1033e86a7edcbffa633efd65ca7ced48f3b1f1a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/domainelement.py @@ -0,0 +1,38 @@ +"""Trait for implementing domain elements. """ + + +from sympy.utilities import public + +@public +class DomainElement: + """ + Represents an element of a domain. + + Mix in this trait into a class whose instances should be recognized as + elements of a domain. Method ``parent()`` gives that domain. + """ + + __slots__ = () + + def parent(self): + """Get the domain associated with ``self`` + + Examples + ======== + + >>> from sympy import ZZ, symbols + >>> x, y = symbols('x, y') + >>> K = ZZ[x,y] + >>> p = K(x)**2 + K(y)**2 + >>> p + x**2 + y**2 + >>> p.parent() + ZZ[x,y] + + Notes + ===== + + This is used by :py:meth:`~.Domain.convert` to identify the domain + associated with a domain element. + """ + raise NotImplementedError("abstract method") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/expressiondomain.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/expressiondomain.py new file mode 100644 index 0000000000000000000000000000000000000000..26cd5aa5bf34985f885093be227df6aa9b35d36c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/expressiondomain.py @@ -0,0 +1,278 @@ +"""Implementation of :class:`ExpressionDomain` class. """ + + +from sympy.core import sympify, SympifyError +from sympy.polys.domains.domainelement import DomainElement +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.domains.field import Field +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.polyutils import PicklableWithSlots +from sympy.utilities import public + +eflags = {"deep": False, "mul": True, "power_exp": False, "power_base": False, + "basic": False, "multinomial": False, "log": False} + +@public +class ExpressionDomain(Field, CharacteristicZero, SimpleDomain): + """A class for arbitrary expressions. """ + + is_SymbolicDomain = is_EX = True + + class Expression(DomainElement, PicklableWithSlots): + """An arbitrary expression. """ + + __slots__ = ('ex',) + + def __init__(self, ex): + if not isinstance(ex, self.__class__): + self.ex = sympify(ex) + else: + self.ex = ex.ex + + def __repr__(f): + return 'EX(%s)' % repr(f.ex) + + def __str__(f): + return 'EX(%s)' % str(f.ex) + + def __hash__(self): + return hash((self.__class__.__name__, self.ex)) + + def parent(self): + return EX + + def as_expr(f): + return f.ex + + def numer(f): + return f.__class__(f.ex.as_numer_denom()[0]) + + def denom(f): + return f.__class__(f.ex.as_numer_denom()[1]) + + def simplify(f, ex): + return f.__class__(ex.cancel().expand(**eflags)) + + def __abs__(f): + return f.__class__(abs(f.ex)) + + def __neg__(f): + return f.__class__(-f.ex) + + def _to_ex(f, g): + try: + return f.__class__(g) + except SympifyError: + return None + + def __lt__(f, g): + return f.ex.sort_key() < g.ex.sort_key() + + def __add__(f, g): + g = f._to_ex(g) + + if g is None: + return NotImplemented + elif g == EX.zero: + return f + elif f == EX.zero: + return g + else: + return f.simplify(f.ex + g.ex) + + def __radd__(f, g): + return f.simplify(f.__class__(g).ex + f.ex) + + def __sub__(f, g): + g = f._to_ex(g) + + if g is None: + return NotImplemented + elif g == EX.zero: + return f + elif f == EX.zero: + return -g + else: + return f.simplify(f.ex - g.ex) + + def __rsub__(f, g): + return f.simplify(f.__class__(g).ex - f.ex) + + def __mul__(f, g): + g = f._to_ex(g) + + if g is None: + return NotImplemented + + if EX.zero in (f, g): + return EX.zero + elif f.ex.is_Number and g.ex.is_Number: + return f.__class__(f.ex*g.ex) + + return f.simplify(f.ex*g.ex) + + def __rmul__(f, g): + return f.simplify(f.__class__(g).ex*f.ex) + + def __pow__(f, n): + n = f._to_ex(n) + + if n is not None: + return f.simplify(f.ex**n.ex) + else: + return NotImplemented + + def __truediv__(f, g): + g = f._to_ex(g) + + if g is not None: + return f.simplify(f.ex/g.ex) + else: + return NotImplemented + + def __rtruediv__(f, g): + return f.simplify(f.__class__(g).ex/f.ex) + + def __eq__(f, g): + return f.ex == f.__class__(g).ex + + def __ne__(f, g): + return not f == g + + def __bool__(f): + return not f.ex.is_zero + + def gcd(f, g): + from sympy.polys import gcd + return f.__class__(gcd(f.ex, f.__class__(g).ex)) + + def lcm(f, g): + from sympy.polys import lcm + return f.__class__(lcm(f.ex, f.__class__(g).ex)) + + dtype = Expression + + zero = Expression(0) + one = Expression(1) + + rep = 'EX' + + has_assoc_Ring = False + has_assoc_Field = True + + def __init__(self): + pass + + def __eq__(self, other): + if isinstance(other, ExpressionDomain): + return True + else: + return NotImplemented + + def __hash__(self): + return hash("EX") + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return a.as_expr() + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + return self.dtype(a) + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_QQ(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a ``GaussianRational`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_GaussianRationalField(K1, a, K0): + """Convert a ``GaussianRational`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_AlgebraicField(K1, a, K0): + """Convert an ``ANP`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_ComplexField(K1, a, K0): + """Convert a mpmath ``mpc`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_PolynomialRing(K1, a, K0): + """Convert a ``DMP`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_FractionField(K1, a, K0): + """Convert a ``DMF`` object to ``dtype``. """ + return K1(K0.to_sympy(a)) + + def from_ExpressionDomain(K1, a, K0): + """Convert a ``EX`` object to ``dtype``. """ + return a + + def get_ring(self): + """Returns a ring associated with ``self``. """ + return self # XXX: EX is not a ring but we don't have much choice here. + + def get_field(self): + """Returns a field associated with ``self``. """ + return self + + def is_positive(self, a): + """Returns True if ``a`` is positive. """ + return a.ex.as_coeff_mul()[0].is_positive + + def is_negative(self, a): + """Returns True if ``a`` is negative. """ + return a.ex.could_extract_minus_sign() + + def is_nonpositive(self, a): + """Returns True if ``a`` is non-positive. """ + return a.ex.as_coeff_mul()[0].is_nonpositive + + def is_nonnegative(self, a): + """Returns True if ``a`` is non-negative. """ + return a.ex.as_coeff_mul()[0].is_nonnegative + + def numer(self, a): + """Returns numerator of ``a``. """ + return a.numer() + + def denom(self, a): + """Returns denominator of ``a``. """ + return a.denom() + + def gcd(self, a, b): + return self(1) + + def lcm(self, a, b): + return a.lcm(b) + + +EX = ExpressionDomain() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/expressionrawdomain.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/expressionrawdomain.py new file mode 100644 index 0000000000000000000000000000000000000000..9811ca26c965197a13f56ab8266ad744e4571560 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/expressionrawdomain.py @@ -0,0 +1,57 @@ +"""Implementation of :class:`ExpressionRawDomain` class. """ + + +from sympy.core import Expr, S, sympify, Add +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.domains.field import Field +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + + +@public +class ExpressionRawDomain(Field, CharacteristicZero, SimpleDomain): + """A class for arbitrary expressions but without automatic simplification. """ + + is_SymbolicRawDomain = is_EXRAW = True + + dtype = Expr + + zero = S.Zero + one = S.One + + rep = 'EXRAW' + + has_assoc_Ring = False + has_assoc_Field = True + + def __init__(self): + pass + + @classmethod + def new(self, a): + return sympify(a) + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return a + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + if not isinstance(a, Expr): + raise CoercionFailed(f"Expecting an Expr instance but found: {type(a).__name__}") + return a + + def convert_from(self, a, K): + """Convert a domain element from another domain to EXRAW""" + return K.to_sympy(a) + + def get_field(self): + """Returns a field associated with ``self``. """ + return self + + def sum(self, items): + return Add(*items) + + +EXRAW = ExpressionRawDomain() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/field.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/field.py new file mode 100644 index 0000000000000000000000000000000000000000..a6370294365a38dee1b2eda9942a66aeef8fdae9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/field.py @@ -0,0 +1,118 @@ +"""Implementation of :class:`Field` class. """ + + +from sympy.polys.domains.ring import Ring +from sympy.polys.polyerrors import NotReversible, DomainError +from sympy.utilities import public + +@public +class Field(Ring): + """Represents a field domain. """ + + is_Field = True + is_PID = True + + def get_ring(self): + """Returns a ring associated with ``self``. """ + raise DomainError('there is no ring associated with %s' % self) + + def get_field(self): + """Returns a field associated with ``self``. """ + return self + + def exquo(self, a, b): + """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return a / b + + def quo(self, a, b): + """Quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return a / b + + def rem(self, a, b): + """Remainder of ``a`` and ``b``, implies nothing. """ + return self.zero + + def div(self, a, b): + """Division of ``a`` and ``b``, implies ``__truediv__``. """ + return a / b, self.zero + + def gcd(self, a, b): + """ + Returns GCD of ``a`` and ``b``. + + This definition of GCD over fields allows to clear denominators + in `primitive()`. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy import S, gcd, primitive + >>> from sympy.abc import x + + >>> QQ.gcd(QQ(2, 3), QQ(4, 9)) + 2/9 + >>> gcd(S(2)/3, S(4)/9) + 2/9 + >>> primitive(2*x/3 + S(4)/9) + (2/9, 3*x + 2) + + """ + try: + ring = self.get_ring() + except DomainError: + return self.one + + p = ring.gcd(self.numer(a), self.numer(b)) + q = ring.lcm(self.denom(a), self.denom(b)) + + return self.convert(p, ring)/q + + def gcdex(self, a, b): + """ + Returns x, y, g such that a * x + b * y == g == gcd(a, b) + """ + d = self.gcd(a, b) + + if a == self.zero: + if b == self.zero: + return self.zero, self.one, self.zero + else: + return self.zero, d/b, d + else: + return d/a, self.zero, d + + def lcm(self, a, b): + """ + Returns LCM of ``a`` and ``b``. + + >>> from sympy.polys.domains import QQ + >>> from sympy import S, lcm + + >>> QQ.lcm(QQ(2, 3), QQ(4, 9)) + 4/3 + >>> lcm(S(2)/3, S(4)/9) + 4/3 + + """ + + try: + ring = self.get_ring() + except DomainError: + return a*b + + p = ring.lcm(self.numer(a), self.numer(b)) + q = ring.gcd(self.denom(a), self.denom(b)) + + return self.convert(p, ring)/q + + def revert(self, a): + """Returns ``a**(-1)`` if possible. """ + if a: + return 1/a + else: + raise NotReversible('zero is not reversible') + + def is_unit(self, a): + """Return true if ``a`` is a invertible""" + return bool(a) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/finitefield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/finitefield.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c48ac07f63aefb9a58c83bb95c5261e67e6a9e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/finitefield.py @@ -0,0 +1,368 @@ +"""Implementation of :class:`FiniteField` class. """ + +import operator + +from sympy.external.gmpy import GROUND_TYPES +from sympy.utilities.decorator import doctest_depends_on + +from sympy.core.numbers import int_valued +from sympy.polys.domains.field import Field + +from sympy.polys.domains.modularinteger import ModularIntegerFactory +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.galoistools import gf_zassenhaus, gf_irred_p_rabin +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public +from sympy.polys.domains.groundtypes import SymPyInteger + + +if GROUND_TYPES == 'flint': + __doctest_skip__ = ['FiniteField'] + + +if GROUND_TYPES == 'flint': + import flint + # Don't use python-flint < 0.5.0 because nmod was missing some features in + # previous versions of python-flint and fmpz_mod was not yet added. + _major, _minor, *_ = flint.__version__.split('.') + if (int(_major), int(_minor)) < (0, 5): + flint = None +else: + flint = None + + +def _modular_int_factory_nmod(mod): + # nmod only recognises int + index = operator.index + mod = index(mod) + nmod = flint.nmod + nmod_poly = flint.nmod_poly + + # flint's nmod is only for moduli up to 2^64-1 (on a 64-bit machine) + try: + nmod(0, mod) + except OverflowError: + return None, None + + def ctx(x): + try: + return nmod(x, mod) + except TypeError: + return nmod(index(x), mod) + + def poly_ctx(cs): + return nmod_poly(cs, mod) + + return ctx, poly_ctx + + +def _modular_int_factory_fmpz_mod(mod): + index = operator.index + fctx = flint.fmpz_mod_ctx(mod) + fctx_poly = flint.fmpz_mod_poly_ctx(mod) + fmpz_mod_poly = flint.fmpz_mod_poly + + def ctx(x): + try: + return fctx(x) + except TypeError: + # x might be Integer + return fctx(index(x)) + + def poly_ctx(cs): + return fmpz_mod_poly(cs, fctx_poly) + + return ctx, poly_ctx + + +def _modular_int_factory(mod, dom, symmetric, self): + # Convert the modulus to ZZ + try: + mod = dom.convert(mod) + except CoercionFailed: + raise ValueError('modulus must be an integer, got %s' % mod) + + ctx, poly_ctx, is_flint = None, None, False + + # Don't use flint if the modulus is not prime as it often crashes. + if flint is not None and mod.is_prime(): + + is_flint = True + + # Try to use flint's nmod first + ctx, poly_ctx = _modular_int_factory_nmod(mod) + + if ctx is None: + # Use fmpz_mod for larger moduli + ctx, poly_ctx = _modular_int_factory_fmpz_mod(mod) + + if ctx is None: + # Use the Python implementation if flint is not available or the + # modulus is not prime. + ctx = ModularIntegerFactory(mod, dom, symmetric, self) + poly_ctx = None # not used + + return ctx, poly_ctx, is_flint + + +@public +@doctest_depends_on(modules=['python', 'gmpy']) +class FiniteField(Field, SimpleDomain): + r"""Finite field of prime order :ref:`GF(p)` + + A :ref:`GF(p)` domain represents a `finite field`_ `\mathbb{F}_p` of prime + order as :py:class:`~.Domain` in the domain system (see + :ref:`polys-domainsintro`). + + A :py:class:`~.Poly` created from an expression with integer + coefficients will have the domain :ref:`ZZ`. However, if the ``modulus=p`` + option is given then the domain will be a finite field instead. + + >>> from sympy import Poly, Symbol + >>> x = Symbol('x') + >>> p = Poly(x**2 + 1) + >>> p + Poly(x**2 + 1, x, domain='ZZ') + >>> p.domain + ZZ + >>> p2 = Poly(x**2 + 1, modulus=2) + >>> p2 + Poly(x**2 + 1, x, modulus=2) + >>> p2.domain + GF(2) + + It is possible to factorise a polynomial over :ref:`GF(p)` using the + modulus argument to :py:func:`~.factor` or by specifying the domain + explicitly. The domain can also be given as a string. + + >>> from sympy import factor, GF + >>> factor(x**2 + 1) + x**2 + 1 + >>> factor(x**2 + 1, modulus=2) + (x + 1)**2 + >>> factor(x**2 + 1, domain=GF(2)) + (x + 1)**2 + >>> factor(x**2 + 1, domain='GF(2)') + (x + 1)**2 + + It is also possible to use :ref:`GF(p)` with the :py:func:`~.cancel` + and :py:func:`~.gcd` functions. + + >>> from sympy import cancel, gcd + >>> cancel((x**2 + 1)/(x + 1)) + (x**2 + 1)/(x + 1) + >>> cancel((x**2 + 1)/(x + 1), domain=GF(2)) + x + 1 + >>> gcd(x**2 + 1, x + 1) + 1 + >>> gcd(x**2 + 1, x + 1, domain=GF(2)) + x + 1 + + When using the domain directly :ref:`GF(p)` can be used as a constructor + to create instances which then support the operations ``+,-,*,**,/`` + + >>> from sympy import GF + >>> K = GF(5) + >>> K + GF(5) + >>> x = K(3) + >>> y = K(2) + >>> x + 3 mod 5 + >>> y + 2 mod 5 + >>> x * y + 1 mod 5 + >>> x / y + 4 mod 5 + + Notes + ===== + + It is also possible to create a :ref:`GF(p)` domain of **non-prime** + order but the resulting ring is **not** a field: it is just the ring of + the integers modulo ``n``. + + >>> K = GF(9) + >>> z = K(3) + >>> z + 3 mod 9 + >>> z**2 + 0 mod 9 + + It would be good to have a proper implementation of prime power fields + (``GF(p**n)``) but these are not yet implemented in SymPY. + + .. _finite field: https://en.wikipedia.org/wiki/Finite_field + """ + + rep = 'FF' + alias = 'FF' + + is_FiniteField = is_FF = True + is_Numerical = True + + has_assoc_Ring = False + has_assoc_Field = True + + dom = None + mod = None + + def __init__(self, mod, symmetric=True): + from sympy.polys.domains import ZZ + dom = ZZ + + if mod <= 0: + raise ValueError('modulus must be a positive integer, got %s' % mod) + + ctx, poly_ctx, is_flint = _modular_int_factory(mod, dom, symmetric, self) + + self.dtype = ctx + self._poly_ctx = poly_ctx + self._is_flint = is_flint + + self.zero = self.dtype(0) + self.one = self.dtype(1) + self.dom = dom + self.mod = mod + self.sym = symmetric + self._tp = type(self.zero) + + @property + def tp(self): + return self._tp + + @property + def is_Field(self): + is_field = getattr(self, '_is_field', None) + if is_field is None: + from sympy.ntheory.primetest import isprime + self._is_field = is_field = isprime(self.mod) + return is_field + + def __str__(self): + return 'GF(%s)' % self.mod + + def __hash__(self): + return hash((self.__class__.__name__, self.dtype, self.mod, self.dom)) + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + return isinstance(other, FiniteField) and \ + self.mod == other.mod and self.dom == other.dom + + def characteristic(self): + """Return the characteristic of this domain. """ + return self.mod + + def get_field(self): + """Returns a field associated with ``self``. """ + return self + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return SymPyInteger(self.to_int(a)) + + def from_sympy(self, a): + """Convert SymPy's Integer to SymPy's ``Integer``. """ + if a.is_Integer: + return self.dtype(self.dom.dtype(int(a))) + elif int_valued(a): + return self.dtype(self.dom.dtype(int(a))) + else: + raise CoercionFailed("expected an integer, got %s" % a) + + def to_int(self, a): + """Convert ``val`` to a Python ``int`` object. """ + aval = int(a) + if self.sym and aval > self.mod // 2: + aval -= self.mod + return aval + + def is_positive(self, a): + """Returns True if ``a`` is positive. """ + return bool(a) + + def is_nonnegative(self, a): + """Returns True if ``a`` is non-negative. """ + return True + + def is_negative(self, a): + """Returns True if ``a`` is negative. """ + return False + + def is_nonpositive(self, a): + """Returns True if ``a`` is non-positive. """ + return not a + + def from_FF(K1, a, K0=None): + """Convert ``ModularInteger(int)`` to ``dtype``. """ + return K1.dtype(K1.dom.from_ZZ(int(a), K0.dom)) + + def from_FF_python(K1, a, K0=None): + """Convert ``ModularInteger(int)`` to ``dtype``. """ + return K1.dtype(K1.dom.from_ZZ_python(int(a), K0.dom)) + + def from_ZZ(K1, a, K0=None): + """Convert Python's ``int`` to ``dtype``. """ + return K1.dtype(K1.dom.from_ZZ_python(a, K0)) + + def from_ZZ_python(K1, a, K0=None): + """Convert Python's ``int`` to ``dtype``. """ + return K1.dtype(K1.dom.from_ZZ_python(a, K0)) + + def from_QQ(K1, a, K0=None): + """Convert Python's ``Fraction`` to ``dtype``. """ + if a.denominator == 1: + return K1.from_ZZ_python(a.numerator) + + def from_QQ_python(K1, a, K0=None): + """Convert Python's ``Fraction`` to ``dtype``. """ + if a.denominator == 1: + return K1.from_ZZ_python(a.numerator) + + def from_FF_gmpy(K1, a, K0=None): + """Convert ``ModularInteger(mpz)`` to ``dtype``. """ + return K1.dtype(K1.dom.from_ZZ_gmpy(a.val, K0.dom)) + + def from_ZZ_gmpy(K1, a, K0=None): + """Convert GMPY's ``mpz`` to ``dtype``. """ + return K1.dtype(K1.dom.from_ZZ_gmpy(a, K0)) + + def from_QQ_gmpy(K1, a, K0=None): + """Convert GMPY's ``mpq`` to ``dtype``. """ + if a.denominator == 1: + return K1.from_ZZ_gmpy(a.numerator) + + def from_RealField(K1, a, K0): + """Convert mpmath's ``mpf`` to ``dtype``. """ + p, q = K0.to_rational(a) + + if q == 1: + return K1.dtype(K1.dom.dtype(p)) + + def is_square(self, a): + """Returns True if ``a`` is a quadratic residue modulo p. """ + # a is not a square <=> x**2-a is irreducible + poly = [int(x) for x in [self.one, self.zero, -a]] + return not gf_irred_p_rabin(poly, self.mod, self.dom) + + def exsqrt(self, a): + """Square root modulo p of ``a`` if it is a quadratic residue. + + Explanation + =========== + Always returns the square root that is no larger than ``p // 2``. + """ + # x**2-a is not square-free if a=0 or the field is characteristic 2 + if self.mod == 2 or a == 0: + return a + # Otherwise, use square-free factorization routine to factorize x**2-a + poly = [int(x) for x in [self.one, self.zero, -a]] + for factor in gf_zassenhaus(poly, self.mod, self.dom): + if len(factor) == 2 and factor[1] <= self.mod // 2: + return self.dtype(factor[1]) + return None + + +FF = GF = FiniteField diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/fractionfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/fractionfield.py new file mode 100644 index 0000000000000000000000000000000000000000..78f5054ddd5480fe6f77442f7a25f22603a4d90d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/fractionfield.py @@ -0,0 +1,181 @@ +"""Implementation of :class:`FractionField` class. """ + + +from sympy.polys.domains.compositedomain import CompositeDomain +from sympy.polys.domains.field import Field +from sympy.polys.polyerrors import CoercionFailed, GeneratorsError +from sympy.utilities import public + +@public +class FractionField(Field, CompositeDomain): + """A class for representing multivariate rational function fields. """ + + is_FractionField = is_Frac = True + + has_assoc_Ring = True + has_assoc_Field = True + + def __init__(self, domain_or_field, symbols=None, order=None): + from sympy.polys.fields import FracField + + if isinstance(domain_or_field, FracField) and symbols is None and order is None: + field = domain_or_field + else: + field = FracField(symbols, domain_or_field, order) + + self.field = field + self.dtype = field.dtype + + self.gens = field.gens + self.ngens = field.ngens + self.symbols = field.symbols + self.domain = field.domain + + # TODO: remove this + self.dom = self.domain + + def new(self, element): + return self.field.field_new(element) + + def of_type(self, element): + """Check if ``a`` is of type ``dtype``. """ + return self.field.is_element(element) + + @property + def zero(self): + return self.field.zero + + @property + def one(self): + return self.field.one + + @property + def order(self): + return self.field.order + + def __str__(self): + return str(self.domain) + '(' + ','.join(map(str, self.symbols)) + ')' + + def __hash__(self): + return hash((self.__class__.__name__, self.field, self.domain, self.symbols)) + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + if not isinstance(other, FractionField): + return NotImplemented + return self.field == other.field + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return a.as_expr() + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + return self.field.from_expr(a) + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + dom = K1.domain + conv = dom.convert_from + if dom.is_ZZ: + return K1(conv(K0.numer(a), K0)) / K1(conv(K0.denom(a), K0)) + else: + return K1(conv(a, K0)) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianRationalField(K1, a, K0): + """Convert a ``GaussianRational`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a ``GaussianInteger`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_ComplexField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1(K1.domain.convert(a, K0)) + + def from_AlgebraicField(K1, a, K0): + """Convert an algebraic number to ``dtype``. """ + if K1.domain != K0: + a = K1.domain.convert_from(a, K0) + if a is not None: + return K1.new(a) + + def from_PolynomialRing(K1, a, K0): + """Convert a polynomial to ``dtype``. """ + if a.is_ground: + return K1.convert_from(a.coeff(1), K0.domain) + try: + return K1.new(a.set_ring(K1.field.ring)) + except (CoercionFailed, GeneratorsError): + # XXX: We get here if K1=ZZ(x,y) and K0=QQ[x,y] + # and the poly a in K0 has non-integer coefficients. + # It seems that K1.new can handle this but K1.new doesn't work + # when K0.domain is an algebraic field... + try: + return K1.new(a) + except (CoercionFailed, GeneratorsError): + return None + + def from_FractionField(K1, a, K0): + """Convert a rational function to ``dtype``. """ + try: + return a.set_field(K1.field) + except (CoercionFailed, GeneratorsError): + return None + + def get_ring(self): + """Returns a field associated with ``self``. """ + return self.field.to_ring().to_domain() + + def is_positive(self, a): + """Returns True if ``LC(a)`` is positive. """ + return self.domain.is_positive(a.numer.LC) + + def is_negative(self, a): + """Returns True if ``LC(a)`` is negative. """ + return self.domain.is_negative(a.numer.LC) + + def is_nonpositive(self, a): + """Returns True if ``LC(a)`` is non-positive. """ + return self.domain.is_nonpositive(a.numer.LC) + + def is_nonnegative(self, a): + """Returns True if ``LC(a)`` is non-negative. """ + return self.domain.is_nonnegative(a.numer.LC) + + def numer(self, a): + """Returns numerator of ``a``. """ + return a.numer + + def denom(self, a): + """Returns denominator of ``a``. """ + return a.denom + + def factorial(self, a): + """Returns factorial of ``a``. """ + return self.dtype(self.domain.factorial(a)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gaussiandomains.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gaussiandomains.py new file mode 100644 index 0000000000000000000000000000000000000000..a96bed78e29445c90c53605a85faa4df16bf807c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gaussiandomains.py @@ -0,0 +1,706 @@ +"""Domains of Gaussian type.""" + +from __future__ import annotations +from sympy.core.numbers import I +from sympy.polys.polyclasses import DMP +from sympy.polys.polyerrors import CoercionFailed +from sympy.polys.domains.integerring import ZZ +from sympy.polys.domains.rationalfield import QQ +from sympy.polys.domains.algebraicfield import AlgebraicField +from sympy.polys.domains.domain import Domain +from sympy.polys.domains.domainelement import DomainElement +from sympy.polys.domains.field import Field +from sympy.polys.domains.ring import Ring + + +class GaussianElement(DomainElement): + """Base class for elements of Gaussian type domains.""" + base: Domain + _parent: Domain + + __slots__ = ('x', 'y') + + def __new__(cls, x, y=0): + conv = cls.base.convert + return cls.new(conv(x), conv(y)) + + @classmethod + def new(cls, x, y): + """Create a new GaussianElement of the same domain.""" + obj = super().__new__(cls) + obj.x = x + obj.y = y + return obj + + def parent(self): + """The domain that this is an element of (ZZ_I or QQ_I)""" + return self._parent + + def __hash__(self): + return hash((self.x, self.y)) + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self.x == other.x and self.y == other.y + else: + return NotImplemented + + def __lt__(self, other): + if not isinstance(other, GaussianElement): + return NotImplemented + return [self.y, self.x] < [other.y, other.x] + + def __pos__(self): + return self + + def __neg__(self): + return self.new(-self.x, -self.y) + + def __repr__(self): + return "%s(%s, %s)" % (self._parent.rep, self.x, self.y) + + def __str__(self): + return str(self._parent.to_sympy(self)) + + @classmethod + def _get_xy(cls, other): + if not isinstance(other, cls): + try: + other = cls._parent.convert(other) + except CoercionFailed: + return None, None + return other.x, other.y + + def __add__(self, other): + x, y = self._get_xy(other) + if x is not None: + return self.new(self.x + x, self.y + y) + else: + return NotImplemented + + __radd__ = __add__ + + def __sub__(self, other): + x, y = self._get_xy(other) + if x is not None: + return self.new(self.x - x, self.y - y) + else: + return NotImplemented + + def __rsub__(self, other): + x, y = self._get_xy(other) + if x is not None: + return self.new(x - self.x, y - self.y) + else: + return NotImplemented + + def __mul__(self, other): + x, y = self._get_xy(other) + if x is not None: + return self.new(self.x*x - self.y*y, self.x*y + self.y*x) + else: + return NotImplemented + + __rmul__ = __mul__ + + def __pow__(self, exp): + if exp == 0: + return self.new(1, 0) + if exp < 0: + self, exp = 1/self, -exp + if exp == 1: + return self + pow2 = self + prod = self if exp % 2 else self._parent.one + exp //= 2 + while exp: + pow2 *= pow2 + if exp % 2: + prod *= pow2 + exp //= 2 + return prod + + def __bool__(self): + return bool(self.x) or bool(self.y) + + def quadrant(self): + """Return quadrant index 0-3. + + 0 is included in quadrant 0. + """ + if self.y > 0: + return 0 if self.x > 0 else 1 + elif self.y < 0: + return 2 if self.x < 0 else 3 + else: + return 0 if self.x >= 0 else 2 + + def __rdivmod__(self, other): + try: + other = self._parent.convert(other) + except CoercionFailed: + return NotImplemented + else: + return other.__divmod__(self) + + def __rtruediv__(self, other): + try: + other = QQ_I.convert(other) + except CoercionFailed: + return NotImplemented + else: + return other.__truediv__(self) + + def __floordiv__(self, other): + qr = self.__divmod__(other) + return qr if qr is NotImplemented else qr[0] + + def __rfloordiv__(self, other): + qr = self.__rdivmod__(other) + return qr if qr is NotImplemented else qr[0] + + def __mod__(self, other): + qr = self.__divmod__(other) + return qr if qr is NotImplemented else qr[1] + + def __rmod__(self, other): + qr = self.__rdivmod__(other) + return qr if qr is NotImplemented else qr[1] + + +class GaussianInteger(GaussianElement): + """Gaussian integer: domain element for :ref:`ZZ_I` + + >>> from sympy import ZZ_I + >>> z = ZZ_I(2, 3) + >>> z + (2 + 3*I) + >>> type(z) + + """ + base = ZZ + + def __truediv__(self, other): + """Return a Gaussian rational.""" + return QQ_I.convert(self)/other + + def __divmod__(self, other): + if not other: + raise ZeroDivisionError('divmod({}, 0)'.format(self)) + x, y = self._get_xy(other) + if x is None: + return NotImplemented + + # multiply self and other by x - I*y + # self/other == (a + I*b)/c + a, b = self.x*x + self.y*y, -self.x*y + self.y*x + c = x*x + y*y + + # find integers qx and qy such that + # |a - qx*c| <= c/2 and |b - qy*c| <= c/2 + qx = (2*a + c) // (2*c) # -c <= 2*a - qx*2*c < c + qy = (2*b + c) // (2*c) + + q = GaussianInteger(qx, qy) + # |self/other - q| < 1 since + # |a/c - qx|**2 + |b/c - qy|**2 <= 1/4 + 1/4 < 1 + + return q, self - q*other # |r| < |other| + + +class GaussianRational(GaussianElement): + """Gaussian rational: domain element for :ref:`QQ_I` + + >>> from sympy import QQ_I, QQ + >>> z = QQ_I(QQ(2, 3), QQ(4, 5)) + >>> z + (2/3 + 4/5*I) + >>> type(z) + + """ + base = QQ + + def __truediv__(self, other): + """Return a Gaussian rational.""" + if not other: + raise ZeroDivisionError('{} / 0'.format(self)) + x, y = self._get_xy(other) + if x is None: + return NotImplemented + c = x*x + y*y + + return GaussianRational((self.x*x + self.y*y)/c, + (-self.x*y + self.y*x)/c) + + def __divmod__(self, other): + try: + other = self._parent.convert(other) + except CoercionFailed: + return NotImplemented + if not other: + raise ZeroDivisionError('{} % 0'.format(self)) + else: + return self/other, QQ_I.zero + + +class GaussianDomain(): + """Base class for Gaussian domains.""" + dom: Domain + + is_Numerical = True + is_Exact = True + + has_assoc_Ring = True + has_assoc_Field = True + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + conv = self.dom.to_sympy + return conv(a.x) + I*conv(a.y) + + def from_sympy(self, a): + """Convert a SymPy object to ``self.dtype``.""" + r, b = a.as_coeff_Add() + x = self.dom.from_sympy(r) # may raise CoercionFailed + if not b: + return self.new(x, 0) + r, b = b.as_coeff_Mul() + y = self.dom.from_sympy(r) + if b is I: + return self.new(x, y) + else: + raise CoercionFailed("{} is not Gaussian".format(a)) + + def inject(self, *gens): + """Inject generators into this domain. """ + return self.poly_ring(*gens) + + def canonical_unit(self, d): + unit = self.units[-d.quadrant()] # - for inverse power + return unit + + def is_negative(self, element): + """Returns ``False`` for any ``GaussianElement``. """ + return False + + def is_positive(self, element): + """Returns ``False`` for any ``GaussianElement``. """ + return False + + def is_nonnegative(self, element): + """Returns ``False`` for any ``GaussianElement``. """ + return False + + def is_nonpositive(self, element): + """Returns ``False`` for any ``GaussianElement``. """ + return False + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY mpz to ``self.dtype``.""" + return K1(a) + + def from_ZZ(K1, a, K0): + """Convert a ZZ_python element to ``self.dtype``.""" + return K1(a) + + def from_ZZ_python(K1, a, K0): + """Convert a ZZ_python element to ``self.dtype``.""" + return K1(a) + + def from_QQ(K1, a, K0): + """Convert a GMPY mpq to ``self.dtype``.""" + return K1(a) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY mpq to ``self.dtype``.""" + return K1(a) + + def from_QQ_python(K1, a, K0): + """Convert a QQ_python element to ``self.dtype``.""" + return K1(a) + + def from_AlgebraicField(K1, a, K0): + """Convert an element from ZZ or QQ to ``self.dtype``.""" + if K0.ext.args[0] == I: + return K1.from_sympy(K0.to_sympy(a)) + + +class GaussianIntegerRing(GaussianDomain, Ring): + r"""Ring of Gaussian integers ``ZZ_I`` + + The :ref:`ZZ_I` domain represents the `Gaussian integers`_ `\mathbb{Z}[i]` + as a :py:class:`~.Domain` in the domain system (see + :ref:`polys-domainsintro`). + + By default a :py:class:`~.Poly` created from an expression with + coefficients that are combinations of integers and ``I`` (`\sqrt{-1}`) + will have the domain :ref:`ZZ_I`. + + >>> from sympy import Poly, Symbol, I + >>> x = Symbol('x') + >>> p = Poly(x**2 + I) + >>> p + Poly(x**2 + I, x, domain='ZZ_I') + >>> p.domain + ZZ_I + + The :ref:`ZZ_I` domain can be used to factorise polynomials that are + reducible over the Gaussian integers. + + >>> from sympy import factor + >>> factor(x**2 + 1) + x**2 + 1 + >>> factor(x**2 + 1, domain='ZZ_I') + (x - I)*(x + I) + + The corresponding `field of fractions`_ is the domain of the Gaussian + rationals :ref:`QQ_I`. Conversely :ref:`ZZ_I` is the `ring of integers`_ + of :ref:`QQ_I`. + + >>> from sympy import ZZ_I, QQ_I + >>> ZZ_I.get_field() + QQ_I + >>> QQ_I.get_ring() + ZZ_I + + When using the domain directly :ref:`ZZ_I` can be used as a constructor. + + >>> ZZ_I(3, 4) + (3 + 4*I) + >>> ZZ_I(5) + (5 + 0*I) + + The domain elements of :ref:`ZZ_I` are instances of + :py:class:`~.GaussianInteger` which support the rings operations + ``+,-,*,**``. + + >>> z1 = ZZ_I(5, 1) + >>> z2 = ZZ_I(2, 3) + >>> z1 + (5 + 1*I) + >>> z2 + (2 + 3*I) + >>> z1 + z2 + (7 + 4*I) + >>> z1 * z2 + (7 + 17*I) + >>> z1 ** 2 + (24 + 10*I) + + Both floor (``//``) and modulo (``%``) division work with + :py:class:`~.GaussianInteger` (see the :py:meth:`~.Domain.div` method). + + >>> z3, z4 = ZZ_I(5), ZZ_I(1, 3) + >>> z3 // z4 # floor division + (1 + -1*I) + >>> z3 % z4 # modulo division (remainder) + (1 + -2*I) + >>> (z3//z4)*z4 + z3%z4 == z3 + True + + True division (``/``) in :ref:`ZZ_I` gives an element of :ref:`QQ_I`. The + :py:meth:`~.Domain.exquo` method can be used to divide in :ref:`ZZ_I` when + exact division is possible. + + >>> z1 / z2 + (1 + -1*I) + >>> ZZ_I.exquo(z1, z2) + (1 + -1*I) + >>> z3 / z4 + (1/2 + -3/2*I) + >>> ZZ_I.exquo(z3, z4) + Traceback (most recent call last): + ... + ExactQuotientFailed: (1 + 3*I) does not divide (5 + 0*I) in ZZ_I + + The :py:meth:`~.Domain.gcd` method can be used to compute the `gcd`_ of any + two elements. + + >>> ZZ_I.gcd(ZZ_I(10), ZZ_I(2)) + (2 + 0*I) + >>> ZZ_I.gcd(ZZ_I(5), ZZ_I(2, 1)) + (2 + 1*I) + + .. _Gaussian integers: https://en.wikipedia.org/wiki/Gaussian_integer + .. _gcd: https://en.wikipedia.org/wiki/Greatest_common_divisor + + """ + dom = ZZ + mod = DMP([ZZ.one, ZZ.zero, ZZ.one], ZZ) + dtype = GaussianInteger + zero = dtype(ZZ(0), ZZ(0)) + one = dtype(ZZ(1), ZZ(0)) + imag_unit = dtype(ZZ(0), ZZ(1)) + units = (one, imag_unit, -one, -imag_unit) # powers of i + + rep = 'ZZ_I' + + is_GaussianRing = True + is_ZZ_I = True + is_PID = True + + def __init__(self): # override Domain.__init__ + """For constructing ZZ_I.""" + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + if isinstance(other, GaussianIntegerRing): + return True + else: + return NotImplemented + + def __hash__(self): + """Compute hash code of ``self``. """ + return hash('ZZ_I') + + @property + def has_CharacteristicZero(self): + return True + + def characteristic(self): + return 0 + + def get_ring(self): + """Returns a ring associated with ``self``. """ + return self + + def get_field(self): + """Returns a field associated with ``self``. """ + return QQ_I + + def normalize(self, d, *args): + """Return first quadrant element associated with ``d``. + + Also multiply the other arguments by the same power of i. + """ + unit = self.canonical_unit(d) + d *= unit + args = tuple(a*unit for a in args) + return (d,) + args if args else d + + def gcd(self, a, b): + """Greatest common divisor of a and b over ZZ_I.""" + while b: + a, b = b, a % b + return self.normalize(a) + + def gcdex(self, a, b): + """Return x, y, g such that x * a + y * b = g = gcd(a, b)""" + x_a = self.one + x_b = self.zero + y_a = self.zero + y_b = self.one + while b: + q = a // b + a, b = b, a - q * b + x_a, x_b = x_b, x_a - q * x_b + y_a, y_b = y_b, y_a - q * y_b + + a, x_a, y_a = self.normalize(a, x_a, y_a) + return x_a, y_a, a + + def lcm(self, a, b): + """Least common multiple of a and b over ZZ_I.""" + return (a * b) // self.gcd(a, b) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a ZZ_I element to ZZ_I.""" + return a + + def from_GaussianRationalField(K1, a, K0): + """Convert a QQ_I element to ZZ_I.""" + return K1.new(ZZ.convert(a.x), ZZ.convert(a.y)) + +ZZ_I = GaussianInteger._parent = GaussianIntegerRing() + + +class GaussianRationalField(GaussianDomain, Field): + r"""Field of Gaussian rationals ``QQ_I`` + + The :ref:`QQ_I` domain represents the `Gaussian rationals`_ `\mathbb{Q}(i)` + as a :py:class:`~.Domain` in the domain system (see + :ref:`polys-domainsintro`). + + By default a :py:class:`~.Poly` created from an expression with + coefficients that are combinations of rationals and ``I`` (`\sqrt{-1}`) + will have the domain :ref:`QQ_I`. + + >>> from sympy import Poly, Symbol, I + >>> x = Symbol('x') + >>> p = Poly(x**2 + I/2) + >>> p + Poly(x**2 + I/2, x, domain='QQ_I') + >>> p.domain + QQ_I + + The polys option ``gaussian=True`` can be used to specify that the domain + should be :ref:`QQ_I` even if the coefficients do not contain ``I`` or are + all integers. + + >>> Poly(x**2) + Poly(x**2, x, domain='ZZ') + >>> Poly(x**2 + I) + Poly(x**2 + I, x, domain='ZZ_I') + >>> Poly(x**2/2) + Poly(1/2*x**2, x, domain='QQ') + >>> Poly(x**2, gaussian=True) + Poly(x**2, x, domain='QQ_I') + >>> Poly(x**2 + I, gaussian=True) + Poly(x**2 + I, x, domain='QQ_I') + >>> Poly(x**2/2, gaussian=True) + Poly(1/2*x**2, x, domain='QQ_I') + + The :ref:`QQ_I` domain can be used to factorise polynomials that are + reducible over the Gaussian rationals. + + >>> from sympy import factor, QQ_I + >>> factor(x**2/4 + 1) + (x**2 + 4)/4 + >>> factor(x**2/4 + 1, domain='QQ_I') + (x - 2*I)*(x + 2*I)/4 + >>> factor(x**2/4 + 1, domain=QQ_I) + (x - 2*I)*(x + 2*I)/4 + + It is also possible to specify the :ref:`QQ_I` domain explicitly with + polys functions like :py:func:`~.apart`. + + >>> from sympy import apart + >>> apart(1/(1 + x**2)) + 1/(x**2 + 1) + >>> apart(1/(1 + x**2), domain=QQ_I) + I/(2*(x + I)) - I/(2*(x - I)) + + The corresponding `ring of integers`_ is the domain of the Gaussian + integers :ref:`ZZ_I`. Conversely :ref:`QQ_I` is the `field of fractions`_ + of :ref:`ZZ_I`. + + >>> from sympy import ZZ_I, QQ_I, QQ + >>> ZZ_I.get_field() + QQ_I + >>> QQ_I.get_ring() + ZZ_I + + When using the domain directly :ref:`QQ_I` can be used as a constructor. + + >>> QQ_I(3, 4) + (3 + 4*I) + >>> QQ_I(5) + (5 + 0*I) + >>> QQ_I(QQ(2, 3), QQ(4, 5)) + (2/3 + 4/5*I) + + The domain elements of :ref:`QQ_I` are instances of + :py:class:`~.GaussianRational` which support the field operations + ``+,-,*,**,/``. + + >>> z1 = QQ_I(5, 1) + >>> z2 = QQ_I(2, QQ(1, 2)) + >>> z1 + (5 + 1*I) + >>> z2 + (2 + 1/2*I) + >>> z1 + z2 + (7 + 3/2*I) + >>> z1 * z2 + (19/2 + 9/2*I) + >>> z2 ** 2 + (15/4 + 2*I) + + True division (``/``) in :ref:`QQ_I` gives an element of :ref:`QQ_I` and + is always exact. + + >>> z1 / z2 + (42/17 + -2/17*I) + >>> QQ_I.exquo(z1, z2) + (42/17 + -2/17*I) + >>> z1 == (z1/z2)*z2 + True + + Both floor (``//``) and modulo (``%``) division can be used with + :py:class:`~.GaussianRational` (see :py:meth:`~.Domain.div`) + but division is always exact so there is no remainder. + + >>> z1 // z2 + (42/17 + -2/17*I) + >>> z1 % z2 + (0 + 0*I) + >>> QQ_I.div(z1, z2) + ((42/17 + -2/17*I), (0 + 0*I)) + >>> (z1//z2)*z2 + z1%z2 == z1 + True + + .. _Gaussian rationals: https://en.wikipedia.org/wiki/Gaussian_rational + """ + dom = QQ + mod = DMP([QQ.one, QQ.zero, QQ.one], QQ) + dtype = GaussianRational + zero = dtype(QQ(0), QQ(0)) + one = dtype(QQ(1), QQ(0)) + imag_unit = dtype(QQ(0), QQ(1)) + units = (one, imag_unit, -one, -imag_unit) # powers of i + + rep = 'QQ_I' + + is_GaussianField = True + is_QQ_I = True + + def __init__(self): # override Domain.__init__ + """For constructing QQ_I.""" + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + if isinstance(other, GaussianRationalField): + return True + else: + return NotImplemented + + def __hash__(self): + """Compute hash code of ``self``. """ + return hash('QQ_I') + + @property + def has_CharacteristicZero(self): + return True + + def characteristic(self): + return 0 + + def get_ring(self): + """Returns a ring associated with ``self``. """ + return ZZ_I + + def get_field(self): + """Returns a field associated with ``self``. """ + return self + + def as_AlgebraicField(self): + """Get equivalent domain as an ``AlgebraicField``. """ + return AlgebraicField(self.dom, I) + + def numer(self, a): + """Get the numerator of ``a``.""" + ZZ_I = self.get_ring() + return ZZ_I.convert(a * self.denom(a)) + + def denom(self, a): + """Get the denominator of ``a``.""" + ZZ = self.dom.get_ring() + QQ = self.dom + ZZ_I = self.get_ring() + denom_ZZ = ZZ.lcm(QQ.denom(a.x), QQ.denom(a.y)) + return ZZ_I(denom_ZZ, ZZ.zero) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a ZZ_I element to QQ_I.""" + return K1.new(a.x, a.y) + + def from_GaussianRationalField(K1, a, K0): + """Convert a QQ_I element to QQ_I.""" + return a + + def from_ComplexField(K1, a, K0): + """Convert a ComplexField element to QQ_I.""" + return K1.new(QQ.convert(a.real), QQ.convert(a.imag)) + + +QQ_I = GaussianRational._parent = GaussianRationalField() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyfinitefield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyfinitefield.py new file mode 100644 index 0000000000000000000000000000000000000000..2e8315a29eca8160102d66b83d953caf998b0fd7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyfinitefield.py @@ -0,0 +1,16 @@ +"""Implementation of :class:`GMPYFiniteField` class. """ + + +from sympy.polys.domains.finitefield import FiniteField +from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing + +from sympy.utilities import public + +@public +class GMPYFiniteField(FiniteField): + """Finite field based on GMPY integers. """ + + alias = 'FF_gmpy' + + def __init__(self, mod, symmetric=True): + super().__init__(mod, GMPYIntegerRing(), symmetric) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyintegerring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyintegerring.py new file mode 100644 index 0000000000000000000000000000000000000000..f132bbe5aff7a4164a09b9b90f00ae5f140cbd03 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyintegerring.py @@ -0,0 +1,105 @@ +"""Implementation of :class:`GMPYIntegerRing` class. """ + + +from sympy.polys.domains.groundtypes import ( + GMPYInteger, SymPyInteger, + factorial as gmpy_factorial, + gmpy_gcdex, gmpy_gcd, gmpy_lcm, sqrt as gmpy_sqrt, +) +from sympy.core.numbers import int_valued +from sympy.polys.domains.integerring import IntegerRing +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +@public +class GMPYIntegerRing(IntegerRing): + """Integer ring based on GMPY's ``mpz`` type. + + This will be the implementation of :ref:`ZZ` if ``gmpy`` or ``gmpy2`` is + installed. Elements will be of type ``gmpy.mpz``. + """ + + dtype = GMPYInteger + zero = dtype(0) + one = dtype(1) + tp = type(one) + alias = 'ZZ_gmpy' + + def __init__(self): + """Allow instantiation of this domain. """ + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return SymPyInteger(int(a)) + + def from_sympy(self, a): + """Convert SymPy's Integer to ``dtype``. """ + if a.is_Integer: + return GMPYInteger(a.p) + elif int_valued(a): + return GMPYInteger(int(a)) + else: + raise CoercionFailed("expected an integer, got %s" % a) + + def from_FF_python(K1, a, K0): + """Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """ + return K0.to_int(a) + + def from_ZZ_python(K1, a, K0): + """Convert Python's ``int`` to GMPY's ``mpz``. """ + return GMPYInteger(a) + + def from_QQ(K1, a, K0): + """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ + if a.denominator == 1: + return GMPYInteger(a.numerator) + + def from_QQ_python(K1, a, K0): + """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ + if a.denominator == 1: + return GMPYInteger(a.numerator) + + def from_FF_gmpy(K1, a, K0): + """Convert ``ModularInteger(mpz)`` to GMPY's ``mpz``. """ + return K0.to_int(a) + + def from_ZZ_gmpy(K1, a, K0): + """Convert GMPY's ``mpz`` to GMPY's ``mpz``. """ + return a + + def from_QQ_gmpy(K1, a, K0): + """Convert GMPY ``mpq`` to GMPY's ``mpz``. """ + if a.denominator == 1: + return a.numerator + + def from_RealField(K1, a, K0): + """Convert mpmath's ``mpf`` to GMPY's ``mpz``. """ + p, q = K0.to_rational(a) + + if q == 1: + return GMPYInteger(p) + + def from_GaussianIntegerRing(K1, a, K0): + if a.y == 0: + return a.x + + def gcdex(self, a, b): + """Compute extended GCD of ``a`` and ``b``. """ + h, s, t = gmpy_gcdex(a, b) + return s, t, h + + def gcd(self, a, b): + """Compute GCD of ``a`` and ``b``. """ + return gmpy_gcd(a, b) + + def lcm(self, a, b): + """Compute LCM of ``a`` and ``b``. """ + return gmpy_lcm(a, b) + + def sqrt(self, a): + """Compute square root of ``a``. """ + return gmpy_sqrt(a) + + def factorial(self, a): + """Compute factorial of ``a``. """ + return gmpy_factorial(a) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyrationalfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyrationalfield.py new file mode 100644 index 0000000000000000000000000000000000000000..10bae5b2b7b476f96ba06f637c549ee4afff4c6d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/gmpyrationalfield.py @@ -0,0 +1,100 @@ +"""Implementation of :class:`GMPYRationalField` class. """ + + +from sympy.polys.domains.groundtypes import ( + GMPYRational, SymPyRational, + gmpy_numer, gmpy_denom, factorial as gmpy_factorial, +) +from sympy.polys.domains.rationalfield import RationalField +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +@public +class GMPYRationalField(RationalField): + """Rational field based on GMPY's ``mpq`` type. + + This will be the implementation of :ref:`QQ` if ``gmpy`` or ``gmpy2`` is + installed. Elements will be of type ``gmpy.mpq``. + """ + + dtype = GMPYRational + zero = dtype(0) + one = dtype(1) + tp = type(one) + alias = 'QQ_gmpy' + + def __init__(self): + pass + + def get_ring(self): + """Returns ring associated with ``self``. """ + from sympy.polys.domains import GMPYIntegerRing + return GMPYIntegerRing() + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return SymPyRational(int(gmpy_numer(a)), + int(gmpy_denom(a))) + + def from_sympy(self, a): + """Convert SymPy's Integer to ``dtype``. """ + if a.is_Rational: + return GMPYRational(a.p, a.q) + elif a.is_Float: + from sympy.polys.domains import RR + return GMPYRational(*map(int, RR.to_rational(a))) + else: + raise CoercionFailed("expected ``Rational`` object, got %s" % a) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return GMPYRational(a) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return GMPYRational(a.numerator, a.denominator) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return GMPYRational(a) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return a + + def from_GaussianRationalField(K1, a, K0): + """Convert a ``GaussianElement`` object to ``dtype``. """ + if a.y == 0: + return GMPYRational(a.x) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return GMPYRational(*map(int, K0.to_rational(a))) + + def exquo(self, a, b): + """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return GMPYRational(a) / GMPYRational(b) + + def quo(self, a, b): + """Quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return GMPYRational(a) / GMPYRational(b) + + def rem(self, a, b): + """Remainder of ``a`` and ``b``, implies nothing. """ + return self.zero + + def div(self, a, b): + """Division of ``a`` and ``b``, implies ``__truediv__``. """ + return GMPYRational(a) / GMPYRational(b), self.zero + + def numer(self, a): + """Returns numerator of ``a``. """ + return a.numerator + + def denom(self, a): + """Returns denominator of ``a``. """ + return a.denominator + + def factorial(self, a): + """Returns factorial of ``a``. """ + return GMPYRational(gmpy_factorial(int(a))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/groundtypes.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/groundtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..1d50cf912a998767c4a52c5a2f3aab825e072aec --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/groundtypes.py @@ -0,0 +1,99 @@ +"""Ground types for various mathematical domains in SymPy. """ + +import builtins +from sympy.external.gmpy import GROUND_TYPES, factorial, sqrt, is_square, sqrtrem + +PythonInteger = builtins.int +PythonReal = builtins.float +PythonComplex = builtins.complex + +from .pythonrational import PythonRational + +from sympy.core.intfunc import ( + igcdex as python_gcdex, + igcd2 as python_gcd, + ilcm as python_lcm, +) + +from sympy.core.numbers import (Float as SymPyReal, Integer as SymPyInteger, Rational as SymPyRational) + + +class _GMPYInteger: + def __init__(self, obj): + pass + +class _GMPYRational: + def __init__(self, obj): + pass + + +if GROUND_TYPES == 'gmpy': + + from gmpy2 import ( + mpz as GMPYInteger, + mpq as GMPYRational, + numer as gmpy_numer, + denom as gmpy_denom, + gcdext as gmpy_gcdex, + gcd as gmpy_gcd, + lcm as gmpy_lcm, + qdiv as gmpy_qdiv, + ) + gcdex = gmpy_gcdex + gcd = gmpy_gcd + lcm = gmpy_lcm + +elif GROUND_TYPES == 'flint': + + from flint import fmpz as _fmpz + + GMPYInteger = _GMPYInteger + GMPYRational = _GMPYRational + gmpy_numer = None + gmpy_denom = None + gmpy_gcdex = None + gmpy_gcd = None + gmpy_lcm = None + gmpy_qdiv = None + + def gcd(a, b): + return a.gcd(b) + + def gcdex(a, b): + x, y, g = python_gcdex(a, b) + return _fmpz(x), _fmpz(y), _fmpz(g) + + def lcm(a, b): + return a.lcm(b) + +else: + GMPYInteger = _GMPYInteger + GMPYRational = _GMPYRational + gmpy_numer = None + gmpy_denom = None + gmpy_gcdex = None + gmpy_gcd = None + gmpy_lcm = None + gmpy_qdiv = None + gcdex = python_gcdex + gcd = python_gcd + lcm = python_lcm + + +__all__ = [ + 'PythonInteger', 'PythonReal', 'PythonComplex', + + 'PythonRational', + + 'python_gcdex', 'python_gcd', 'python_lcm', + + 'SymPyReal', 'SymPyInteger', 'SymPyRational', + + 'GMPYInteger', 'GMPYRational', 'gmpy_numer', + 'gmpy_denom', 'gmpy_gcdex', 'gmpy_gcd', 'gmpy_lcm', + 'gmpy_qdiv', + + 'factorial', 'sqrt', 'is_square', 'sqrtrem', + + 'GMPYInteger', 'GMPYRational', +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/integerring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/integerring.py new file mode 100644 index 0000000000000000000000000000000000000000..65eaa9631cfdf138997a4ebdb362c4233fb098fb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/integerring.py @@ -0,0 +1,276 @@ +"""Implementation of :class:`IntegerRing` class. """ + +from sympy.external.gmpy import MPZ, GROUND_TYPES + +from sympy.core.numbers import int_valued +from sympy.polys.domains.groundtypes import ( + SymPyInteger, + factorial, + gcdex, gcd, lcm, sqrt, is_square, sqrtrem, +) + +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.domains.ring import Ring +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +import math + +@public +class IntegerRing(Ring, CharacteristicZero, SimpleDomain): + r"""The domain ``ZZ`` representing the integers `\mathbb{Z}`. + + The :py:class:`IntegerRing` class represents the ring of integers as a + :py:class:`~.Domain` in the domain system. :py:class:`IntegerRing` is a + super class of :py:class:`PythonIntegerRing` and + :py:class:`GMPYIntegerRing` one of which will be the implementation for + :ref:`ZZ` depending on whether or not ``gmpy`` or ``gmpy2`` is installed. + + See also + ======== + + Domain + """ + + rep = 'ZZ' + alias = 'ZZ' + dtype = MPZ + zero = dtype(0) + one = dtype(1) + tp = type(one) + + + is_IntegerRing = is_ZZ = True + is_Numerical = True + is_PID = True + + has_assoc_Ring = True + has_assoc_Field = True + + def __init__(self): + """Allow instantiation of this domain. """ + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + if isinstance(other, IntegerRing): + return True + else: + return NotImplemented + + def __hash__(self): + """Compute a hash value for this domain. """ + return hash('ZZ') + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return SymPyInteger(int(a)) + + def from_sympy(self, a): + """Convert SymPy's Integer to ``dtype``. """ + if a.is_Integer: + return MPZ(a.p) + elif int_valued(a): + return MPZ(int(a)) + else: + raise CoercionFailed("expected an integer, got %s" % a) + + def get_field(self): + r"""Return the associated field of fractions :ref:`QQ` + + Returns + ======= + + :ref:`QQ`: + The associated field of fractions :ref:`QQ`, a + :py:class:`~.Domain` representing the rational numbers + `\mathbb{Q}`. + + Examples + ======== + + >>> from sympy import ZZ + >>> ZZ.get_field() + QQ + """ + from sympy.polys.domains import QQ + return QQ + + def algebraic_field(self, *extension, alias=None): + r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. + + Parameters + ========== + + *extension : One or more :py:class:`~.Expr`. + Generators of the extension. These should be expressions that are + algebraic over `\mathbb{Q}`. + + alias : str, :py:class:`~.Symbol`, None, optional (default=None) + If provided, this will be used as the alias symbol for the + primitive element of the returned :py:class:`~.AlgebraicField`. + + Returns + ======= + + :py:class:`~.AlgebraicField` + A :py:class:`~.Domain` representing the algebraic field extension. + + Examples + ======== + + >>> from sympy import ZZ, sqrt + >>> ZZ.algebraic_field(sqrt(2)) + QQ + """ + return self.get_field().algebraic_field(*extension, alias=alias) + + def from_AlgebraicField(K1, a, K0): + """Convert a :py:class:`~.ANP` object to :ref:`ZZ`. + + See :py:meth:`~.Domain.convert`. + """ + if a.is_ground: + return K1.convert(a.LC(), K0.dom) + + def log(self, a, b): + r"""Logarithm of *a* to the base *b*. + + Parameters + ========== + + a: number + b: number + + Returns + ======= + + $\\lfloor\log(a, b)\\rfloor$: + Floor of the logarithm of *a* to the base *b* + + Examples + ======== + + >>> from sympy import ZZ + >>> ZZ.log(ZZ(8), ZZ(2)) + 3 + >>> ZZ.log(ZZ(9), ZZ(2)) + 3 + + Notes + ===== + + This function uses ``math.log`` which is based on ``float`` so it will + fail for large integer arguments. + """ + return self.dtype(int(math.log(int(a), b))) + + def from_FF(K1, a, K0): + """Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """ + return MPZ(K0.to_int(a)) + + def from_FF_python(K1, a, K0): + """Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """ + return MPZ(K0.to_int(a)) + + def from_ZZ(K1, a, K0): + """Convert Python's ``int`` to GMPY's ``mpz``. """ + return MPZ(a) + + def from_ZZ_python(K1, a, K0): + """Convert Python's ``int`` to GMPY's ``mpz``. """ + return MPZ(a) + + def from_QQ(K1, a, K0): + """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ + if a.denominator == 1: + return MPZ(a.numerator) + + def from_QQ_python(K1, a, K0): + """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ + if a.denominator == 1: + return MPZ(a.numerator) + + def from_FF_gmpy(K1, a, K0): + """Convert ``ModularInteger(mpz)`` to GMPY's ``mpz``. """ + return MPZ(K0.to_int(a)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert GMPY's ``mpz`` to GMPY's ``mpz``. """ + return a + + def from_QQ_gmpy(K1, a, K0): + """Convert GMPY ``mpq`` to GMPY's ``mpz``. """ + if a.denominator == 1: + return a.numerator + + def from_RealField(K1, a, K0): + """Convert mpmath's ``mpf`` to GMPY's ``mpz``. """ + p, q = K0.to_rational(a) + + if q == 1: + # XXX: If MPZ is flint.fmpz and p is a gmpy2.mpz, then we need + # to convert via int because fmpz and mpz do not know about each + # other. + return MPZ(int(p)) + + def from_GaussianIntegerRing(K1, a, K0): + if a.y == 0: + return a.x + + def from_EX(K1, a, K0): + """Convert ``Expression`` to GMPY's ``mpz``. """ + if a.is_Integer: + return K1.from_sympy(a) + + def gcdex(self, a, b): + """Compute extended GCD of ``a`` and ``b``. """ + h, s, t = gcdex(a, b) + # XXX: This conditional logic should be handled somewhere else. + if GROUND_TYPES == 'gmpy': + return s, t, h + else: + return h, s, t + + def gcd(self, a, b): + """Compute GCD of ``a`` and ``b``. """ + return gcd(a, b) + + def lcm(self, a, b): + """Compute LCM of ``a`` and ``b``. """ + return lcm(a, b) + + def sqrt(self, a): + """Compute square root of ``a``. """ + return sqrt(a) + + def is_square(self, a): + """Return ``True`` if ``a`` is a square. + + Explanation + =========== + An integer is a square if and only if there exists an integer + ``b`` such that ``b * b == a``. + """ + return is_square(a) + + def exsqrt(self, a): + """Non-negative square root of ``a`` if ``a`` is a square. + + See also + ======== + is_square + """ + if a < 0: + return None + root, rem = sqrtrem(a) + if rem != 0: + return None + return root + + def factorial(self, a): + """Compute factorial of ``a``. """ + return factorial(a) + + +ZZ = IntegerRing() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/modularinteger.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/modularinteger.py new file mode 100644 index 0000000000000000000000000000000000000000..39a0237563c69a77e4736466d1ebcaa7ca39485f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/modularinteger.py @@ -0,0 +1,237 @@ +"""Implementation of :class:`ModularInteger` class. """ + +from __future__ import annotations +from typing import Any + +import operator + +from sympy.polys.polyutils import PicklableWithSlots +from sympy.polys.polyerrors import CoercionFailed +from sympy.polys.domains.domainelement import DomainElement + +from sympy.utilities import public +from sympy.utilities.exceptions import sympy_deprecation_warning + +@public +class ModularInteger(PicklableWithSlots, DomainElement): + """A class representing a modular integer. """ + + mod, dom, sym, _parent = None, None, None, None + + __slots__ = ('val',) + + def parent(self): + return self._parent + + def __init__(self, val): + if isinstance(val, self.__class__): + self.val = val.val % self.mod + else: + self.val = self.dom.convert(val) % self.mod + + def modulus(self): + return self.mod + + def __hash__(self): + return hash((self.val, self.mod)) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, self.val) + + def __str__(self): + return "%s mod %s" % (self.val, self.mod) + + def __int__(self): + return int(self.val) + + def to_int(self): + + sympy_deprecation_warning( + """ModularInteger.to_int() is deprecated. + + Use int(a) or K = GF(p) and K.to_int(a) instead of a.to_int(). + """, + deprecated_since_version="1.13", + active_deprecations_target="modularinteger-to-int", + ) + + if self.sym: + if self.val <= self.mod // 2: + return self.val + else: + return self.val - self.mod + else: + return self.val + + def __pos__(self): + return self + + def __neg__(self): + return self.__class__(-self.val) + + @classmethod + def _get_val(cls, other): + if isinstance(other, cls): + return other.val + else: + try: + return cls.dom.convert(other) + except CoercionFailed: + return None + + def __add__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val + val) + else: + return NotImplemented + + def __radd__(self, other): + return self.__add__(other) + + def __sub__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val - val) + else: + return NotImplemented + + def __rsub__(self, other): + return (-self).__add__(other) + + def __mul__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val * val) + else: + return NotImplemented + + def __rmul__(self, other): + return self.__mul__(other) + + def __truediv__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val * self._invert(val)) + else: + return NotImplemented + + def __rtruediv__(self, other): + return self.invert().__mul__(other) + + def __mod__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val % val) + else: + return NotImplemented + + def __rmod__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(val % self.val) + else: + return NotImplemented + + def __pow__(self, exp): + if not exp: + return self.__class__(self.dom.one) + + if exp < 0: + val, exp = self.invert().val, -exp + else: + val = self.val + + return self.__class__(pow(val, int(exp), self.mod)) + + def _compare(self, other, op): + val = self._get_val(other) + + if val is None: + return NotImplemented + + return op(self.val, val % self.mod) + + def _compare_deprecated(self, other, op): + val = self._get_val(other) + + if val is None: + return NotImplemented + + sympy_deprecation_warning( + """Ordered comparisons with modular integers are deprecated. + + Use e.g. int(a) < int(b) instead of a < b. + """, + deprecated_since_version="1.13", + active_deprecations_target="modularinteger-compare", + stacklevel=4, + ) + + return op(self.val, val % self.mod) + + def __eq__(self, other): + return self._compare(other, operator.eq) + + def __ne__(self, other): + return self._compare(other, operator.ne) + + def __lt__(self, other): + return self._compare_deprecated(other, operator.lt) + + def __le__(self, other): + return self._compare_deprecated(other, operator.le) + + def __gt__(self, other): + return self._compare_deprecated(other, operator.gt) + + def __ge__(self, other): + return self._compare_deprecated(other, operator.ge) + + def __bool__(self): + return bool(self.val) + + @classmethod + def _invert(cls, value): + return cls.dom.invert(value, cls.mod) + + def invert(self): + return self.__class__(self._invert(self.val)) + +_modular_integer_cache: dict[tuple[Any, Any, Any], type[ModularInteger]] = {} + +def ModularIntegerFactory(_mod, _dom, _sym, parent): + """Create custom class for specific integer modulus.""" + try: + _mod = _dom.convert(_mod) + except CoercionFailed: + ok = False + else: + ok = True + + if not ok or _mod < 1: + raise ValueError("modulus must be a positive integer, got %s" % _mod) + + key = _mod, _dom, _sym + + try: + cls = _modular_integer_cache[key] + except KeyError: + class cls(ModularInteger): + mod, dom, sym = _mod, _dom, _sym + _parent = parent + + if _sym: + cls.__name__ = "SymmetricModularIntegerMod%s" % _mod + else: + cls.__name__ = "ModularIntegerMod%s" % _mod + + _modular_integer_cache[key] = cls + + return cls diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/mpelements.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/mpelements.py new file mode 100644 index 0000000000000000000000000000000000000000..04ae8eaddcbb7fd8fae684374d9d2c05e79f6c7a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/mpelements.py @@ -0,0 +1,181 @@ +# +# This module is deprecated and should not be used any more. The actual +# implementation of RR and CC now uses mpmath's mpf and mpc types directly. +# +"""Real and complex elements. """ + + +from sympy.external.gmpy import MPQ +from sympy.polys.domains.domainelement import DomainElement +from sympy.utilities import public + +from mpmath.ctx_mp_python import PythonMPContext, _mpf, _mpc, _constant +from mpmath.libmp import (MPZ_ONE, fzero, fone, finf, fninf, fnan, + round_nearest, mpf_mul, repr_dps, int_types, + from_int, from_float, from_str, to_rational) + + +@public +class RealElement(_mpf, DomainElement): + """An element of a real domain. """ + + __slots__ = ('__mpf__',) + + def _set_mpf(self, val): + self.__mpf__ = val + + _mpf_ = property(lambda self: self.__mpf__, _set_mpf) + + def parent(self): + return self.context._parent + +@public +class ComplexElement(_mpc, DomainElement): + """An element of a complex domain. """ + + __slots__ = ('__mpc__',) + + def _set_mpc(self, val): + self.__mpc__ = val + + _mpc_ = property(lambda self: self.__mpc__, _set_mpc) + + def parent(self): + return self.context._parent + +new = object.__new__ + +@public +class MPContext(PythonMPContext): + + def __init__(ctx, prec=53, dps=None, tol=None, real=False): + ctx._prec_rounding = [prec, round_nearest] + + if dps is None: + ctx._set_prec(prec) + else: + ctx._set_dps(dps) + + ctx.mpf = RealElement + ctx.mpc = ComplexElement + ctx.mpf._ctxdata = [ctx.mpf, new, ctx._prec_rounding] + ctx.mpc._ctxdata = [ctx.mpc, new, ctx._prec_rounding] + + if real: + ctx.mpf.context = ctx + else: + ctx.mpc.context = ctx + + ctx.constant = _constant + ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding] + ctx.constant.context = ctx + + ctx.types = [ctx.mpf, ctx.mpc, ctx.constant] + ctx.trap_complex = True + ctx.pretty = True + + if tol is None: + ctx.tol = ctx._make_tol() + elif tol is False: + ctx.tol = fzero + else: + ctx.tol = ctx._convert_tol(tol) + + ctx.tolerance = ctx.make_mpf(ctx.tol) + + if not ctx.tolerance: + ctx.max_denom = 1000000 + else: + ctx.max_denom = int(1/ctx.tolerance) + + ctx.zero = ctx.make_mpf(fzero) + ctx.one = ctx.make_mpf(fone) + ctx.j = ctx.make_mpc((fzero, fone)) + ctx.inf = ctx.make_mpf(finf) + ctx.ninf = ctx.make_mpf(fninf) + ctx.nan = ctx.make_mpf(fnan) + + def _make_tol(ctx): + hundred = (0, 25, 2, 5) + eps = (0, MPZ_ONE, 1-ctx.prec, 1) + return mpf_mul(hundred, eps) + + def make_tol(ctx): + return ctx.make_mpf(ctx._make_tol()) + + def _convert_tol(ctx, tol): + if isinstance(tol, int_types): + return from_int(tol) + if isinstance(tol, float): + return from_float(tol) + if hasattr(tol, "_mpf_"): + return tol._mpf_ + prec, rounding = ctx._prec_rounding + if isinstance(tol, str): + return from_str(tol, prec, rounding) + raise ValueError("expected a real number, got %s" % tol) + + def _convert_fallback(ctx, x, strings): + raise TypeError("cannot create mpf from " + repr(x)) + + @property + def _repr_digits(ctx): + return repr_dps(ctx._prec) + + @property + def _str_digits(ctx): + return ctx._dps + + def to_rational(ctx, s, limit=True): + p, q = to_rational(s._mpf_) + + # Needed for GROUND_TYPES=flint if gmpy2 is installed because mpmath's + # to_rational() function returns a gmpy2.mpz instance and if MPQ is + # flint.fmpq then MPQ(p, q) will fail. + p = int(p) + + if not limit or q <= ctx.max_denom: + return p, q + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = p, q + + while True: + a = n//d + q2 = q0 + a*q1 + if q2 > ctx.max_denom: + break + p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2 + n, d = d, n - a*d + + k = (ctx.max_denom - q0)//q1 + + number = MPQ(p, q) + bound1 = MPQ(p0 + k*p1, q0 + k*q1) + bound2 = MPQ(p1, q1) + + if not bound2 or not bound1: + return p, q + elif abs(bound2 - number) <= abs(bound1 - number): + return bound2.numerator, bound2.denominator + else: + return bound1.numerator, bound1.denominator + + def almosteq(ctx, s, t, rel_eps=None, abs_eps=None): + t = ctx.convert(t) + if abs_eps is None and rel_eps is None: + rel_eps = abs_eps = ctx.tolerance or ctx.make_tol() + if abs_eps is None: + abs_eps = ctx.convert(rel_eps) + elif rel_eps is None: + rel_eps = ctx.convert(abs_eps) + diff = abs(s-t) + if diff <= abs_eps: + return True + abss = abs(s) + abst = abs(t) + if abss < abst: + err = diff/abst + else: + err = diff/abss + return err <= rel_eps diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/old_fractionfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/old_fractionfield.py new file mode 100644 index 0000000000000000000000000000000000000000..25d849c39e45259728479ab0305d4956053ae743 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/old_fractionfield.py @@ -0,0 +1,188 @@ +"""Implementation of :class:`FractionField` class. """ + + +from sympy.polys.domains.field import Field +from sympy.polys.domains.compositedomain import CompositeDomain +from sympy.polys.polyclasses import DMF +from sympy.polys.polyerrors import GeneratorsNeeded +from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder +from sympy.utilities import public + +@public +class FractionField(Field, CompositeDomain): + """A class for representing rational function fields. """ + + dtype = DMF + is_FractionField = is_Frac = True + + has_assoc_Ring = True + has_assoc_Field = True + + def __init__(self, dom, *gens): + if not gens: + raise GeneratorsNeeded("generators not specified") + + lev = len(gens) - 1 + self.ngens = len(gens) + + self.zero = self.dtype.zero(lev, dom) + self.one = self.dtype.one(lev, dom) + + self.domain = self.dom = dom + self.symbols = self.gens = gens + + def set_domain(self, dom): + """Make a new fraction field with given domain. """ + return self.__class__(dom, *self.gens) + + def new(self, element): + return self.dtype(element, self.dom, len(self.gens) - 1) + + def __str__(self): + return str(self.dom) + '(' + ','.join(map(str, self.gens)) + ')' + + def __hash__(self): + return hash((self.__class__.__name__, self.dtype, self.dom, self.gens)) + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + return isinstance(other, FractionField) and \ + self.dtype == other.dtype and self.dom == other.dom and self.gens == other.gens + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) / + basic_from_dict(a.denom().to_sympy_dict(), *self.gens)) + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + p, q = a.as_numer_denom() + + num, _ = dict_from_basic(p, gens=self.gens) + den, _ = dict_from_basic(q, gens=self.gens) + + for k, v in num.items(): + num[k] = self.dom.from_sympy(v) + + for k, v in den.items(): + den[k] = self.dom.from_sympy(v) + + return self((num, den)).cancel() + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1(K1.dom.convert(a, K0)) + + def from_GlobalPolynomialRing(K1, a, K0): + """Convert a ``DMF`` object to ``dtype``. """ + if K1.gens == K0.gens: + if K1.dom == K0.dom: + return K1(a.to_list()) + else: + return K1(a.convert(K1.dom).to_list()) + else: + monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens) + + if K1.dom != K0.dom: + coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ] + + return K1(dict(zip(monoms, coeffs))) + + def from_FractionField(K1, a, K0): + """ + Convert a fraction field element to another fraction field. + + Examples + ======== + + >>> from sympy.polys.polyclasses import DMF + >>> from sympy.polys.domains import ZZ, QQ + >>> from sympy.abc import x + + >>> f = DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(1)]), ZZ) + + >>> QQx = QQ.old_frac_field(x) + >>> ZZx = ZZ.old_frac_field(x) + + >>> QQx.from_FractionField(f, ZZx) + DMF([1, 2], [1, 1], QQ) + + """ + if K1.gens == K0.gens: + if K1.dom == K0.dom: + return a + else: + return K1((a.numer().convert(K1.dom).to_list(), + a.denom().convert(K1.dom).to_list())) + elif set(K0.gens).issubset(K1.gens): + nmonoms, ncoeffs = _dict_reorder( + a.numer().to_dict(), K0.gens, K1.gens) + dmonoms, dcoeffs = _dict_reorder( + a.denom().to_dict(), K0.gens, K1.gens) + + if K1.dom != K0.dom: + ncoeffs = [ K1.dom.convert(c, K0.dom) for c in ncoeffs ] + dcoeffs = [ K1.dom.convert(c, K0.dom) for c in dcoeffs ] + + return K1((dict(zip(nmonoms, ncoeffs)), dict(zip(dmonoms, dcoeffs)))) + + def get_ring(self): + """Returns a ring associated with ``self``. """ + from sympy.polys.domains import PolynomialRing + return PolynomialRing(self.dom, *self.gens) + + def poly_ring(self, *gens): + """Returns a polynomial ring, i.e. `K[X]`. """ + raise NotImplementedError('nested domains not allowed') + + def frac_field(self, *gens): + """Returns a fraction field, i.e. `K(X)`. """ + raise NotImplementedError('nested domains not allowed') + + def is_positive(self, a): + """Returns True if ``a`` is positive. """ + return self.dom.is_positive(a.numer().LC()) + + def is_negative(self, a): + """Returns True if ``a`` is negative. """ + return self.dom.is_negative(a.numer().LC()) + + def is_nonpositive(self, a): + """Returns True if ``a`` is non-positive. """ + return self.dom.is_nonpositive(a.numer().LC()) + + def is_nonnegative(self, a): + """Returns True if ``a`` is non-negative. """ + return self.dom.is_nonnegative(a.numer().LC()) + + def numer(self, a): + """Returns numerator of ``a``. """ + return a.numer() + + def denom(self, a): + """Returns denominator of ``a``. """ + return a.denom() + + def factorial(self, a): + """Returns factorial of ``a``. """ + return self.dtype(self.dom.factorial(a)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/old_polynomialring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/old_polynomialring.py new file mode 100644 index 0000000000000000000000000000000000000000..c29a4529aac3c64b29d8c670ac45b6c100294ced --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/old_polynomialring.py @@ -0,0 +1,490 @@ +"""Implementation of :class:`PolynomialRing` class. """ + + +from sympy.polys.agca.modules import FreeModulePolyRing +from sympy.polys.domains.compositedomain import CompositeDomain +from sympy.polys.domains.old_fractionfield import FractionField +from sympy.polys.domains.ring import Ring +from sympy.polys.orderings import monomial_key, build_product_order +from sympy.polys.polyclasses import DMP, DMF +from sympy.polys.polyerrors import (GeneratorsNeeded, PolynomialError, + CoercionFailed, ExactQuotientFailed, NotReversible) +from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder +from sympy.utilities import public +from sympy.utilities.iterables import iterable + + +@public +class PolynomialRingBase(Ring, CompositeDomain): + """ + Base class for generalized polynomial rings. + + This base class should be used for uniform access to generalized polynomial + rings. Subclasses only supply information about the element storage etc. + + Do not instantiate. + """ + + has_assoc_Ring = True + has_assoc_Field = True + + default_order = "grevlex" + + def __init__(self, dom, *gens, **opts): + if not gens: + raise GeneratorsNeeded("generators not specified") + + lev = len(gens) - 1 + self.ngens = len(gens) + + self.zero = self.dtype.zero(lev, dom) + self.one = self.dtype.one(lev, dom) + + self.domain = self.dom = dom + self.symbols = self.gens = gens + # NOTE 'order' may not be set if inject was called through CompositeDomain + self.order = opts.get('order', monomial_key(self.default_order)) + + def set_domain(self, dom): + """Return a new polynomial ring with given domain. """ + return self.__class__(dom, *self.gens, order=self.order) + + def new(self, element): + return self.dtype(element, self.dom, len(self.gens) - 1) + + def _ground_new(self, element): + return self.one.ground_new(element) + + def _from_dict(self, element): + return DMP.from_dict(element, len(self.gens) - 1, self.dom) + + def __str__(self): + s_order = str(self.order) + orderstr = ( + " order=" + s_order) if s_order != self.default_order else "" + return str(self.dom) + '[' + ','.join(map(str, self.gens)) + orderstr + ']' + + def __hash__(self): + return hash((self.__class__.__name__, self.dtype, self.dom, + self.gens, self.order)) + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + return isinstance(other, PolynomialRingBase) and \ + self.dtype == other.dtype and self.dom == other.dom and \ + self.gens == other.gens and self.order == other.order + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1._ground_new(K1.dom.convert(a, K0)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1._ground_new(K1.dom.convert(a, K0)) + + def from_QQ(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1._ground_new(K1.dom.convert(a, K0)) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return K1._ground_new(K1.dom.convert(a, K0)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return K1._ground_new(K1.dom.convert(a, K0)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return K1._ground_new(K1.dom.convert(a, K0)) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return K1._ground_new(K1.dom.convert(a, K0)) + + def from_AlgebraicField(K1, a, K0): + """Convert a ``ANP`` object to ``dtype``. """ + if K1.dom == K0: + return K1._ground_new(a) + + def from_PolynomialRing(K1, a, K0): + """Convert a ``PolyElement`` object to ``dtype``. """ + if K1.gens == K0.symbols: + if K1.dom == K0.dom: + return K1(dict(a)) # set the correct ring + else: + convert_dom = lambda c: K1.dom.convert_from(c, K0.dom) + return K1._from_dict({m: convert_dom(c) for m, c in a.items()}) + else: + monoms, coeffs = _dict_reorder(a.to_dict(), K0.symbols, K1.gens) + + if K1.dom != K0.dom: + coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ] + + return K1._from_dict(dict(zip(monoms, coeffs))) + + def from_GlobalPolynomialRing(K1, a, K0): + """Convert a ``DMP`` object to ``dtype``. """ + if K1.gens == K0.gens: + if K1.dom != K0.dom: + a = a.convert(K1.dom) + return K1(a.to_list()) + else: + monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens) + + if K1.dom != K0.dom: + coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ] + + return K1(dict(zip(monoms, coeffs))) + + def get_field(self): + """Returns a field associated with ``self``. """ + return FractionField(self.dom, *self.gens) + + def poly_ring(self, *gens): + """Returns a polynomial ring, i.e. ``K[X]``. """ + raise NotImplementedError('nested domains not allowed') + + def frac_field(self, *gens): + """Returns a fraction field, i.e. ``K(X)``. """ + raise NotImplementedError('nested domains not allowed') + + def revert(self, a): + try: + return self.exquo(self.one, a) + except (ExactQuotientFailed, ZeroDivisionError): + raise NotReversible('%s is not a unit' % a) + + def gcdex(self, a, b): + """Extended GCD of ``a`` and ``b``. """ + return a.gcdex(b) + + def gcd(self, a, b): + """Returns GCD of ``a`` and ``b``. """ + return a.gcd(b) + + def lcm(self, a, b): + """Returns LCM of ``a`` and ``b``. """ + return a.lcm(b) + + def factorial(self, a): + """Returns factorial of ``a``. """ + return self.dtype(self.dom.factorial(a)) + + def _vector_to_sdm(self, v, order): + """ + For internal use by the modules class. + + Convert an iterable of elements of this ring into a sparse distributed + module element. + """ + raise NotImplementedError + + def _sdm_to_dics(self, s, n): + """Helper for _sdm_to_vector.""" + from sympy.polys.distributedmodules import sdm_to_dict + dic = sdm_to_dict(s) + res = [{} for _ in range(n)] + for k, v in dic.items(): + res[k[0]][k[1:]] = v + return res + + def _sdm_to_vector(self, s, n): + """ + For internal use by the modules class. + + Convert a sparse distributed module into a list of length ``n``. + + Examples + ======== + + >>> from sympy import QQ, ilex + >>> from sympy.abc import x, y + >>> R = QQ.old_poly_ring(x, y, order=ilex) + >>> L = [((1, 1, 1), QQ(1)), ((0, 1, 0), QQ(1)), ((0, 0, 1), QQ(2))] + >>> R._sdm_to_vector(L, 2) + [DMF([[1], [2, 0]], [[1]], QQ), DMF([[1, 0], []], [[1]], QQ)] + """ + dics = self._sdm_to_dics(s, n) + # NOTE this works for global and local rings! + return [self(x) for x in dics] + + def free_module(self, rank): + """ + Generate a free module of rank ``rank`` over ``self``. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(2) + QQ[x]**2 + """ + return FreeModulePolyRing(self, rank) + + +def _vector_to_sdm_helper(v, order): + """Helper method for common code in Global and Local poly rings.""" + from sympy.polys.distributedmodules import sdm_from_dict + d = {} + for i, e in enumerate(v): + for key, value in e.to_dict().items(): + d[(i,) + key] = value + return sdm_from_dict(d, order) + + +@public +class GlobalPolynomialRing(PolynomialRingBase): + """A true polynomial ring, with objects DMP. """ + + is_PolynomialRing = is_Poly = True + dtype = DMP + + def new(self, element): + if isinstance(element, dict): + return DMP.from_dict(element, len(self.gens) - 1, self.dom) + elif element in self.dom: + return self._ground_new(self.dom.convert(element)) + else: + return self.dtype(element, self.dom, len(self.gens) - 1) + + def from_FractionField(K1, a, K0): + """ + Convert a ``DMF`` object to ``DMP``. + + Examples + ======== + + >>> from sympy.polys.polyclasses import DMP, DMF + >>> from sympy.polys.domains import ZZ + >>> from sympy.abc import x + + >>> f = DMF(([ZZ(1), ZZ(1)], [ZZ(1)]), ZZ) + >>> K = ZZ.old_frac_field(x) + + >>> F = ZZ.old_poly_ring(x).from_FractionField(f, K) + + >>> F == DMP([ZZ(1), ZZ(1)], ZZ) + True + >>> type(F) # doctest: +SKIP + + + """ + if a.denom().is_one: + return K1.from_GlobalPolynomialRing(a.numer(), K0) + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return basic_from_dict(a.to_sympy_dict(), *self.gens) + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + try: + rep, _ = dict_from_basic(a, gens=self.gens) + except PolynomialError: + raise CoercionFailed("Cannot convert %s to type %s" % (a, self)) + + for k, v in rep.items(): + rep[k] = self.dom.from_sympy(v) + + return DMP.from_dict(rep, self.ngens - 1, self.dom) + + def is_positive(self, a): + """Returns True if ``LC(a)`` is positive. """ + return self.dom.is_positive(a.LC()) + + def is_negative(self, a): + """Returns True if ``LC(a)`` is negative. """ + return self.dom.is_negative(a.LC()) + + def is_nonpositive(self, a): + """Returns True if ``LC(a)`` is non-positive. """ + return self.dom.is_nonpositive(a.LC()) + + def is_nonnegative(self, a): + """Returns True if ``LC(a)`` is non-negative. """ + return self.dom.is_nonnegative(a.LC()) + + def _vector_to_sdm(self, v, order): + """ + Examples + ======== + + >>> from sympy import lex, QQ + >>> from sympy.abc import x, y + >>> R = QQ.old_poly_ring(x, y) + >>> f = R.convert(x + 2*y) + >>> g = R.convert(x * y) + >>> R._vector_to_sdm([f, g], lex) + [((1, 1, 1), 1), ((0, 1, 0), 1), ((0, 0, 1), 2)] + """ + return _vector_to_sdm_helper(v, order) + + +class GeneralizedPolynomialRing(PolynomialRingBase): + """A generalized polynomial ring, with objects DMF. """ + + dtype = DMF + + def new(self, a): + """Construct an element of ``self`` domain from ``a``. """ + res = self.dtype(a, self.dom, len(self.gens) - 1) + + # make sure res is actually in our ring + if res.denom().terms(order=self.order)[0][0] != (0,)*len(self.gens): + from sympy.printing.str import sstr + raise CoercionFailed("denominator %s not allowed in %s" + % (sstr(res), self)) + return res + + def __contains__(self, a): + try: + a = self.convert(a) + except CoercionFailed: + return False + return a.denom().terms(order=self.order)[0][0] == (0,)*len(self.gens) + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) / + basic_from_dict(a.denom().to_sympy_dict(), *self.gens)) + + def from_sympy(self, a): + """Convert SymPy's expression to ``dtype``. """ + p, q = a.as_numer_denom() + + num, _ = dict_from_basic(p, gens=self.gens) + den, _ = dict_from_basic(q, gens=self.gens) + + for k, v in num.items(): + num[k] = self.dom.from_sympy(v) + + for k, v in den.items(): + den[k] = self.dom.from_sympy(v) + + return self((num, den)).cancel() + + def exquo(self, a, b): + """Exact quotient of ``a`` and ``b``. """ + # Elements are DMF that will always divide (except 0). The result is + # not guaranteed to be in this ring, so we have to check that. + r = a / b + + try: + r = self.new((r.num, r.den)) + except CoercionFailed: + raise ExactQuotientFailed(a, b, self) + + return r + + def from_FractionField(K1, a, K0): + dmf = K1.get_field().from_FractionField(a, K0) + return K1((dmf.num, dmf.den)) + + def _vector_to_sdm(self, v, order): + """ + Turn an iterable into a sparse distributed module. + + Note that the vector is multiplied by a unit first to make all entries + polynomials. + + Examples + ======== + + >>> from sympy import ilex, QQ + >>> from sympy.abc import x, y + >>> R = QQ.old_poly_ring(x, y, order=ilex) + >>> f = R.convert((x + 2*y) / (1 + x)) + >>> g = R.convert(x * y) + >>> R._vector_to_sdm([f, g], ilex) + [((0, 0, 1), 2), ((0, 1, 0), 1), ((1, 1, 1), 1), ((1, + 2, 1), 1)] + """ + # NOTE this is quite inefficient... + u = self.one.numer() + for x in v: + u *= x.denom() + return _vector_to_sdm_helper([x.numer()*u/x.denom() for x in v], order) + + +@public +def PolynomialRing(dom, *gens, **opts): + r""" + Create a generalized multivariate polynomial ring. + + A generalized polynomial ring is defined by a ground field `K`, a set + of generators (typically `x_1, \ldots, x_n`) and a monomial order `<`. + The monomial order can be global, local or mixed. In any case it induces + a total ordering on the monomials, and there exists for every (non-zero) + polynomial `f \in K[x_1, \ldots, x_n]` a well-defined "leading monomial" + `LM(f) = LM(f, >)`. One can then define a multiplicative subset + `S = S_> = \{f \in K[x_1, \ldots, x_n] | LM(f) = 1\}`. The generalized + polynomial ring corresponding to the monomial order is + `R = S^{-1}K[x_1, \ldots, x_n]`. + + If `>` is a so-called global order, that is `1` is the smallest monomial, + then we just have `S = K` and `R = K[x_1, \ldots, x_n]`. + + Examples + ======== + + A few examples may make this clearer. + + >>> from sympy.abc import x, y + >>> from sympy import QQ + + Our first ring uses global lexicographic order. + + >>> R1 = QQ.old_poly_ring(x, y, order=(("lex", x, y),)) + + The second ring uses local lexicographic order. Note that when using a + single (non-product) order, you can just specify the name and omit the + variables: + + >>> R2 = QQ.old_poly_ring(x, y, order="ilex") + + The third and fourth rings use a mixed orders: + + >>> o1 = (("ilex", x), ("lex", y)) + >>> o2 = (("lex", x), ("ilex", y)) + >>> R3 = QQ.old_poly_ring(x, y, order=o1) + >>> R4 = QQ.old_poly_ring(x, y, order=o2) + + We will investigate what elements of `K(x, y)` are contained in the various + rings. + + >>> L = [x, 1/x, y/(1 + x), 1/(1 + y), 1/(1 + x*y)] + >>> test = lambda R: [f in R for f in L] + + The first ring is just `K[x, y]`: + + >>> test(R1) + [True, False, False, False, False] + + The second ring is R1 localised at the maximal ideal (x, y): + + >>> test(R2) + [True, False, True, True, True] + + The third ring is R1 localised at the prime ideal (x): + + >>> test(R3) + [True, False, True, False, True] + + Finally the fourth ring is R1 localised at `S = K[x, y] \setminus yK[y]`: + + >>> test(R4) + [True, False, False, True, False] + """ + + order = opts.get("order", GeneralizedPolynomialRing.default_order) + if iterable(order): + order = build_product_order(order, gens) + order = monomial_key(order) + opts['order'] = order + + if order.is_global: + return GlobalPolynomialRing(dom, *gens, **opts) + else: + return GeneralizedPolynomialRing(dom, *gens, **opts) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/polynomialring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/polynomialring.py new file mode 100644 index 0000000000000000000000000000000000000000..daccdcdede4d409e995a79540b0c3f9e8017d2d9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/polynomialring.py @@ -0,0 +1,203 @@ +"""Implementation of :class:`PolynomialRing` class. """ + + +from sympy.polys.domains.ring import Ring +from sympy.polys.domains.compositedomain import CompositeDomain + +from sympy.polys.polyerrors import CoercionFailed, GeneratorsError +from sympy.utilities import public + +@public +class PolynomialRing(Ring, CompositeDomain): + """A class for representing multivariate polynomial rings. """ + + is_PolynomialRing = is_Poly = True + + has_assoc_Ring = True + has_assoc_Field = True + + def __init__(self, domain_or_ring, symbols=None, order=None): + from sympy.polys.rings import PolyRing + + if isinstance(domain_or_ring, PolyRing) and symbols is None and order is None: + ring = domain_or_ring + else: + ring = PolyRing(symbols, domain_or_ring, order) + + self.ring = ring + self.dtype = ring.dtype + + self.gens = ring.gens + self.ngens = ring.ngens + self.symbols = ring.symbols + self.domain = ring.domain + + + if symbols: + if ring.domain.is_Field and ring.domain.is_Exact and len(symbols)==1: + self.is_PID = True + + # TODO: remove this + self.dom = self.domain + + def new(self, element): + return self.ring.ring_new(element) + + def of_type(self, element): + """Check if ``a`` is of type ``dtype``. """ + return self.ring.is_element(element) + + @property + def zero(self): + return self.ring.zero + + @property + def one(self): + return self.ring.one + + @property + def order(self): + return self.ring.order + + def __str__(self): + return str(self.domain) + '[' + ','.join(map(str, self.symbols)) + ']' + + def __hash__(self): + return hash((self.__class__.__name__, self.ring, self.domain, self.symbols)) + + def __eq__(self, other): + """Returns `True` if two domains are equivalent. """ + if not isinstance(other, PolynomialRing): + return NotImplemented + return self.ring == other.ring + + def is_unit(self, a): + """Returns ``True`` if ``a`` is a unit of ``self``""" + if not a.is_ground: + return False + K = self.domain + return K.is_unit(K.convert_from(a, self)) + + def canonical_unit(self, a): + u = self.domain.canonical_unit(a.LC) + return self.ring.ground_new(u) + + def to_sympy(self, a): + """Convert `a` to a SymPy object. """ + return a.as_expr() + + def from_sympy(self, a): + """Convert SymPy's expression to `dtype`. """ + return self.ring.from_expr(a) + + def from_ZZ(K1, a, K0): + """Convert a Python `int` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_python(K1, a, K0): + """Convert a Python `int` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ(K1, a, K0): + """Convert a Python `Fraction` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ_python(K1, a, K0): + """Convert a Python `Fraction` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY `mpz` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY `mpq` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianIntegerRing(K1, a, K0): + """Convert a `GaussianInteger` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_GaussianRationalField(K1, a, K0): + """Convert a `GaussianRational` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_RealField(K1, a, K0): + """Convert a mpmath `mpf` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_ComplexField(K1, a, K0): + """Convert a mpmath `mpf` object to `dtype`. """ + return K1(K1.domain.convert(a, K0)) + + def from_AlgebraicField(K1, a, K0): + """Convert an algebraic number to ``dtype``. """ + if K1.domain != K0: + a = K1.domain.convert_from(a, K0) + if a is not None: + return K1.new(a) + + def from_PolynomialRing(K1, a, K0): + """Convert a polynomial to ``dtype``. """ + try: + return a.set_ring(K1.ring) + except (CoercionFailed, GeneratorsError): + return None + + def from_FractionField(K1, a, K0): + """Convert a rational function to ``dtype``. """ + if K1.domain == K0: + return K1.ring.from_list([a]) + + q, r = K0.numer(a).div(K0.denom(a)) + + if r.is_zero: + return K1.from_PolynomialRing(q, K0.field.ring.to_domain()) + else: + return None + + def from_GlobalPolynomialRing(K1, a, K0): + """Convert from old poly ring to ``dtype``. """ + if K1.symbols == K0.gens: + ad = a.to_dict() + if K1.domain != K0.domain: + ad = {m: K1.domain.convert(c) for m, c in ad.items()} + return K1(ad) + elif a.is_ground and K0.domain == K1: + return K1.convert_from(a.to_list()[0], K0.domain) + + def get_field(self): + """Returns a field associated with `self`. """ + return self.ring.to_field().to_domain() + + def is_positive(self, a): + """Returns True if `LC(a)` is positive. """ + return self.domain.is_positive(a.LC) + + def is_negative(self, a): + """Returns True if `LC(a)` is negative. """ + return self.domain.is_negative(a.LC) + + def is_nonpositive(self, a): + """Returns True if `LC(a)` is non-positive. """ + return self.domain.is_nonpositive(a.LC) + + def is_nonnegative(self, a): + """Returns True if `LC(a)` is non-negative. """ + return self.domain.is_nonnegative(a.LC) + + def gcdex(self, a, b): + """Extended GCD of `a` and `b`. """ + return a.gcdex(b) + + def gcd(self, a, b): + """Returns GCD of `a` and `b`. """ + return a.gcd(b) + + def lcm(self, a, b): + """Returns LCM of `a` and `b`. """ + return a.lcm(b) + + def factorial(self, a): + """Returns factorial of `a`. """ + return self.dtype(self.domain.factorial(a)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonfinitefield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonfinitefield.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa4f6d1b43317283041206eaa43e06a5cc8db --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonfinitefield.py @@ -0,0 +1,16 @@ +"""Implementation of :class:`PythonFiniteField` class. """ + + +from sympy.polys.domains.finitefield import FiniteField +from sympy.polys.domains.pythonintegerring import PythonIntegerRing + +from sympy.utilities import public + +@public +class PythonFiniteField(FiniteField): + """Finite field based on Python's integers. """ + + alias = 'FF_python' + + def __init__(self, mod, symmetric=True): + super().__init__(mod, PythonIntegerRing(), symmetric) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonintegerring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonintegerring.py new file mode 100644 index 0000000000000000000000000000000000000000..81ee9637a4ebcfaf3c5f11d12c18265305984c25 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonintegerring.py @@ -0,0 +1,98 @@ +"""Implementation of :class:`PythonIntegerRing` class. """ + + +from sympy.core.numbers import int_valued +from sympy.polys.domains.groundtypes import ( + PythonInteger, SymPyInteger, sqrt as python_sqrt, + factorial as python_factorial, python_gcdex, python_gcd, python_lcm, +) +from sympy.polys.domains.integerring import IntegerRing +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +@public +class PythonIntegerRing(IntegerRing): + """Integer ring based on Python's ``int`` type. + + This will be used as :ref:`ZZ` if ``gmpy`` and ``gmpy2`` are not + installed. Elements are instances of the standard Python ``int`` type. + """ + + dtype = PythonInteger + zero = dtype(0) + one = dtype(1) + alias = 'ZZ_python' + + def __init__(self): + """Allow instantiation of this domain. """ + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return SymPyInteger(a) + + def from_sympy(self, a): + """Convert SymPy's Integer to ``dtype``. """ + if a.is_Integer: + return PythonInteger(a.p) + elif int_valued(a): + return PythonInteger(int(a)) + else: + raise CoercionFailed("expected an integer, got %s" % a) + + def from_FF_python(K1, a, K0): + """Convert ``ModularInteger(int)`` to Python's ``int``. """ + return K0.to_int(a) + + def from_ZZ_python(K1, a, K0): + """Convert Python's ``int`` to Python's ``int``. """ + return a + + def from_QQ(K1, a, K0): + """Convert Python's ``Fraction`` to Python's ``int``. """ + if a.denominator == 1: + return a.numerator + + def from_QQ_python(K1, a, K0): + """Convert Python's ``Fraction`` to Python's ``int``. """ + if a.denominator == 1: + return a.numerator + + def from_FF_gmpy(K1, a, K0): + """Convert ``ModularInteger(mpz)`` to Python's ``int``. """ + return PythonInteger(K0.to_int(a)) + + def from_ZZ_gmpy(K1, a, K0): + """Convert GMPY's ``mpz`` to Python's ``int``. """ + return PythonInteger(a) + + def from_QQ_gmpy(K1, a, K0): + """Convert GMPY's ``mpq`` to Python's ``int``. """ + if a.denom() == 1: + return PythonInteger(a.numer()) + + def from_RealField(K1, a, K0): + """Convert mpmath's ``mpf`` to Python's ``int``. """ + p, q = K0.to_rational(a) + + if q == 1: + return PythonInteger(p) + + def gcdex(self, a, b): + """Compute extended GCD of ``a`` and ``b``. """ + return python_gcdex(a, b) + + def gcd(self, a, b): + """Compute GCD of ``a`` and ``b``. """ + return python_gcd(a, b) + + def lcm(self, a, b): + """Compute LCM of ``a`` and ``b``. """ + return python_lcm(a, b) + + def sqrt(self, a): + """Compute square root of ``a``. """ + return python_sqrt(a) + + def factorial(self, a): + """Compute factorial of ``a``. """ + return python_factorial(a) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonrational.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonrational.py new file mode 100644 index 0000000000000000000000000000000000000000..87b56d6c929c3ce3ce153dce7b3c210821d706a0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonrational.py @@ -0,0 +1,22 @@ +""" +Rational number type based on Python integers. + +The PythonRational class from here has been moved to +sympy.external.pythonmpq + +This module is just left here for backwards compatibility. +""" + + +from sympy.core.numbers import Rational +from sympy.core.sympify import _sympy_converter +from sympy.utilities import public +from sympy.external.pythonmpq import PythonMPQ + + +PythonRational = public(PythonMPQ) + + +def sympify_pythonrational(arg): + return Rational(arg.numerator, arg.denominator) +_sympy_converter[PythonRational] = sympify_pythonrational diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonrationalfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonrationalfield.py new file mode 100644 index 0000000000000000000000000000000000000000..51afaef636f000855d51a69fb93eb416ae1e5347 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/pythonrationalfield.py @@ -0,0 +1,73 @@ +"""Implementation of :class:`PythonRationalField` class. """ + + +from sympy.polys.domains.groundtypes import PythonInteger, PythonRational, SymPyRational +from sympy.polys.domains.rationalfield import RationalField +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +@public +class PythonRationalField(RationalField): + """Rational field based on :ref:`MPQ`. + + This will be used as :ref:`QQ` if ``gmpy`` and ``gmpy2`` are not + installed. Elements are instances of :ref:`MPQ`. + """ + + dtype = PythonRational + zero = dtype(0) + one = dtype(1) + alias = 'QQ_python' + + def __init__(self): + pass + + def get_ring(self): + """Returns ring associated with ``self``. """ + from sympy.polys.domains import PythonIntegerRing + return PythonIntegerRing() + + def to_sympy(self, a): + """Convert `a` to a SymPy object. """ + return SymPyRational(a.numerator, a.denominator) + + def from_sympy(self, a): + """Convert SymPy's Rational to `dtype`. """ + if a.is_Rational: + return PythonRational(a.p, a.q) + elif a.is_Float: + from sympy.polys.domains import RR + p, q = RR.to_rational(a) + return PythonRational(int(p), int(q)) + else: + raise CoercionFailed("expected `Rational` object, got %s" % a) + + def from_ZZ_python(K1, a, K0): + """Convert a Python `int` object to `dtype`. """ + return PythonRational(a) + + def from_QQ_python(K1, a, K0): + """Convert a Python `Fraction` object to `dtype`. """ + return a + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY `mpz` object to `dtype`. """ + return PythonRational(PythonInteger(a)) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY `mpq` object to `dtype`. """ + return PythonRational(PythonInteger(a.numer()), + PythonInteger(a.denom())) + + def from_RealField(K1, a, K0): + """Convert a mpmath `mpf` object to `dtype`. """ + p, q = K0.to_rational(a) + return PythonRational(int(p), int(q)) + + def numer(self, a): + """Returns numerator of `a`. """ + return a.numerator + + def denom(self, a): + """Returns denominator of `a`. """ + return a.denominator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/quotientring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/quotientring.py new file mode 100644 index 0000000000000000000000000000000000000000..7e8abf6b210a5627c9c139e41248637c9b88931f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/quotientring.py @@ -0,0 +1,202 @@ +"""Implementation of :class:`QuotientRing` class.""" + + +from sympy.polys.agca.modules import FreeModuleQuotientRing +from sympy.polys.domains.ring import Ring +from sympy.polys.polyerrors import NotReversible, CoercionFailed +from sympy.utilities import public + +# TODO +# - successive quotients (when quotient ideals are implemented) +# - poly rings over quotients? +# - division by non-units in integral domains? + +@public +class QuotientRingElement: + """ + Class representing elements of (commutative) quotient rings. + + Attributes: + + - ring - containing ring + - data - element of ring.ring (i.e. base ring) representing self + """ + + def __init__(self, ring, data): + self.ring = ring + self.data = data + + def __str__(self): + from sympy.printing.str import sstr + data = self.ring.ring.to_sympy(self.data) + return sstr(data) + " + " + str(self.ring.base_ideal) + + __repr__ = __str__ + + def __bool__(self): + return not self.ring.is_zero(self) + + def __add__(self, om): + if not isinstance(om, self.__class__) or om.ring != self.ring: + try: + om = self.ring.convert(om) + except (NotImplementedError, CoercionFailed): + return NotImplemented + return self.ring(self.data + om.data) + + __radd__ = __add__ + + def __neg__(self): + return self.ring(self.data*self.ring.ring.convert(-1)) + + def __sub__(self, om): + return self.__add__(-om) + + def __rsub__(self, om): + return (-self).__add__(om) + + def __mul__(self, o): + if not isinstance(o, self.__class__): + try: + o = self.ring.convert(o) + except (NotImplementedError, CoercionFailed): + return NotImplemented + return self.ring(self.data*o.data) + + __rmul__ = __mul__ + + def __rtruediv__(self, o): + return self.ring.revert(self)*o + + def __truediv__(self, o): + if not isinstance(o, self.__class__): + try: + o = self.ring.convert(o) + except (NotImplementedError, CoercionFailed): + return NotImplemented + return self.ring.revert(o)*self + + def __pow__(self, oth): + if oth < 0: + return self.ring.revert(self) ** -oth + return self.ring(self.data ** oth) + + def __eq__(self, om): + if not isinstance(om, self.__class__) or om.ring != self.ring: + return False + return self.ring.is_zero(self - om) + + def __ne__(self, om): + return not self == om + + +class QuotientRing(Ring): + """ + Class representing (commutative) quotient rings. + + You should not usually instantiate this by hand, instead use the constructor + from the base ring in the construction. + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> I = QQ.old_poly_ring(x).ideal(x**3 + 1) + >>> QQ.old_poly_ring(x).quotient_ring(I) + QQ[x]/ + + Shorter versions are possible: + + >>> QQ.old_poly_ring(x)/I + QQ[x]/ + + >>> QQ.old_poly_ring(x)/[x**3 + 1] + QQ[x]/ + + Attributes: + + - ring - the base ring + - base_ideal - the ideal used to form the quotient + """ + + has_assoc_Ring = True + has_assoc_Field = False + dtype = QuotientRingElement + + def __init__(self, ring, ideal): + if not ideal.ring == ring: + raise ValueError('Ideal must belong to %s, got %s' % (ring, ideal)) + self.ring = ring + self.base_ideal = ideal + self.zero = self(self.ring.zero) + self.one = self(self.ring.one) + + def __str__(self): + return str(self.ring) + "/" + str(self.base_ideal) + + def __hash__(self): + return hash((self.__class__.__name__, self.dtype, self.ring, self.base_ideal)) + + def new(self, a): + """Construct an element of ``self`` domain from ``a``. """ + if not isinstance(a, self.ring.dtype): + a = self.ring(a) + # TODO optionally disable reduction? + return self.dtype(self, self.base_ideal.reduce_element(a)) + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + return isinstance(other, QuotientRing) and \ + self.ring == other.ring and self.base_ideal == other.base_ideal + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return K1(K1.ring.convert(a, K0)) + + from_ZZ_python = from_ZZ + from_QQ_python = from_ZZ_python + from_ZZ_gmpy = from_ZZ_python + from_QQ_gmpy = from_ZZ_python + from_RealField = from_ZZ_python + from_GlobalPolynomialRing = from_ZZ_python + from_FractionField = from_ZZ_python + + def from_sympy(self, a): + return self(self.ring.from_sympy(a)) + + def to_sympy(self, a): + return self.ring.to_sympy(a.data) + + def from_QuotientRing(self, a, K0): + if K0 == self: + return a + + def poly_ring(self, *gens): + """Returns a polynomial ring, i.e. ``K[X]``. """ + raise NotImplementedError('nested domains not allowed') + + def frac_field(self, *gens): + """Returns a fraction field, i.e. ``K(X)``. """ + raise NotImplementedError('nested domains not allowed') + + def revert(self, a): + """ + Compute a**(-1), if possible. + """ + I = self.ring.ideal(a.data) + self.base_ideal + try: + return self(I.in_terms_of_generators(1)[0]) + except ValueError: # 1 not in I + raise NotReversible('%s not a unit in %r' % (a, self)) + + def is_zero(self, a): + return self.base_ideal.contains(a.data) + + def free_module(self, rank): + """ + Generate a free module of rank ``rank`` over ``self``. + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) + (QQ[x]/)**2 + """ + return FreeModuleQuotientRing(self, rank) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/rationalfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/rationalfield.py new file mode 100644 index 0000000000000000000000000000000000000000..6da570332de8a6d39a21bb3d57447670c7a98441 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/rationalfield.py @@ -0,0 +1,200 @@ +"""Implementation of :class:`RationalField` class. """ + + +from sympy.external.gmpy import MPQ + +from sympy.polys.domains.groundtypes import SymPyRational, is_square, sqrtrem + +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.domains.field import Field +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +@public +class RationalField(Field, CharacteristicZero, SimpleDomain): + r"""Abstract base class for the domain :ref:`QQ`. + + The :py:class:`RationalField` class represents the field of rational + numbers $\mathbb{Q}$ as a :py:class:`~.Domain` in the domain system. + :py:class:`RationalField` is a superclass of + :py:class:`PythonRationalField` and :py:class:`GMPYRationalField` one of + which will be the implementation for :ref:`QQ` depending on whether either + of ``gmpy`` or ``gmpy2`` is installed or not. + + See also + ======== + + Domain + """ + + rep = 'QQ' + alias = 'QQ' + + is_RationalField = is_QQ = True + is_Numerical = True + + has_assoc_Ring = True + has_assoc_Field = True + + dtype = MPQ + zero = dtype(0) + one = dtype(1) + tp = type(one) + + def __init__(self): + pass + + def __eq__(self, other): + """Returns ``True`` if two domains are equivalent. """ + if isinstance(other, RationalField): + return True + else: + return NotImplemented + + def __hash__(self): + """Returns hash code of ``self``. """ + return hash('QQ') + + def get_ring(self): + """Returns ring associated with ``self``. """ + from sympy.polys.domains import ZZ + return ZZ + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return SymPyRational(int(a.numerator), int(a.denominator)) + + def from_sympy(self, a): + """Convert SymPy's Integer to ``dtype``. """ + if a.is_Rational: + return MPQ(a.p, a.q) + elif a.is_Float: + from sympy.polys.domains import RR + return MPQ(*map(int, RR.to_rational(a))) + else: + raise CoercionFailed("expected `Rational` object, got %s" % a) + + def algebraic_field(self, *extension, alias=None): + r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. + + Parameters + ========== + + *extension : One or more :py:class:`~.Expr` + Generators of the extension. These should be expressions that are + algebraic over `\mathbb{Q}`. + + alias : str, :py:class:`~.Symbol`, None, optional (default=None) + If provided, this will be used as the alias symbol for the + primitive element of the returned :py:class:`~.AlgebraicField`. + + Returns + ======= + + :py:class:`~.AlgebraicField` + A :py:class:`~.Domain` representing the algebraic field extension. + + Examples + ======== + + >>> from sympy import QQ, sqrt + >>> QQ.algebraic_field(sqrt(2)) + QQ + """ + from sympy.polys.domains import AlgebraicField + return AlgebraicField(self, *extension, alias=alias) + + def from_AlgebraicField(K1, a, K0): + """Convert a :py:class:`~.ANP` object to :ref:`QQ`. + + See :py:meth:`~.Domain.convert` + """ + if a.is_ground: + return K1.convert(a.LC(), K0.dom) + + def from_ZZ(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return MPQ(a) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return MPQ(a) + + def from_QQ(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return MPQ(a.numerator, a.denominator) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return MPQ(a.numerator, a.denominator) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return MPQ(a) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return a + + def from_GaussianRationalField(K1, a, K0): + """Convert a ``GaussianElement`` object to ``dtype``. """ + if a.y == 0: + return MPQ(a.x) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return MPQ(*map(int, K0.to_rational(a))) + + def exquo(self, a, b): + """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return MPQ(a) / MPQ(b) + + def quo(self, a, b): + """Quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return MPQ(a) / MPQ(b) + + def rem(self, a, b): + """Remainder of ``a`` and ``b``, implies nothing. """ + return self.zero + + def div(self, a, b): + """Division of ``a`` and ``b``, implies ``__truediv__``. """ + return MPQ(a) / MPQ(b), self.zero + + def numer(self, a): + """Returns numerator of ``a``. """ + return a.numerator + + def denom(self, a): + """Returns denominator of ``a``. """ + return a.denominator + + def is_square(self, a): + """Return ``True`` if ``a`` is a square. + + Explanation + =========== + A rational number is a square if and only if there exists + a rational number ``b`` such that ``b * b == a``. + """ + return is_square(a.numerator) and is_square(a.denominator) + + def exsqrt(self, a): + """Non-negative square root of ``a`` if ``a`` is a square. + + See also + ======== + is_square + """ + if a.numerator < 0: # denominator is always positive + return None + p_sqrt, p_rem = sqrtrem(a.numerator) + if p_rem != 0: + return None + q_sqrt, q_rem = sqrtrem(a.denominator) + if q_rem != 0: + return None + return MPQ(p_sqrt, q_sqrt) + +QQ = RationalField() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/realfield.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/realfield.py new file mode 100644 index 0000000000000000000000000000000000000000..12f543b2619aa238969ecbe20215d6fd59792904 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/realfield.py @@ -0,0 +1,220 @@ +"""Implementation of :class:`RealField` class. """ + + +from sympy.external.gmpy import SYMPY_INTS, MPQ +from sympy.core.numbers import Float +from sympy.polys.domains.field import Field +from sympy.polys.domains.simpledomain import SimpleDomain +from sympy.polys.domains.characteristiczero import CharacteristicZero +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +from mpmath import MPContext +from mpmath.libmp import to_rational as _mpmath_to_rational + + +def to_rational(s, max_denom, limit=True): + + p, q = _mpmath_to_rational(s._mpf_) + + # Needed for GROUND_TYPES=flint if gmpy2 is installed because mpmath's + # to_rational() function returns a gmpy2.mpz instance and if MPQ is + # flint.fmpq then MPQ(p, q) will fail. + p = int(p) + q = int(q) + + if not limit or q <= max_denom: + return p, q + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = p, q + + while True: + a = n//d + q2 = q0 + a*q1 + if q2 > max_denom: + break + p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2 + n, d = d, n - a*d + + k = (max_denom - q0)//q1 + + number = MPQ(p, q) + bound1 = MPQ(p0 + k*p1, q0 + k*q1) + bound2 = MPQ(p1, q1) + + if not bound2 or not bound1: + return p, q + elif abs(bound2 - number) <= abs(bound1 - number): + return bound2.numerator, bound2.denominator + else: + return bound1.numerator, bound1.denominator + + +@public +class RealField(Field, CharacteristicZero, SimpleDomain): + """Real numbers up to the given precision. """ + + rep = 'RR' + + is_RealField = is_RR = True + + is_Exact = False + is_Numerical = True + is_PID = False + + has_assoc_Ring = False + has_assoc_Field = True + + _default_precision = 53 + + @property + def has_default_precision(self): + return self.precision == self._default_precision + + @property + def precision(self): + return self._context.prec + + @property + def dps(self): + return self._context.dps + + @property + def tolerance(self): + return self._tolerance + + def __init__(self, prec=None, dps=None, tol=None): + # XXX: The tol parameter is ignored but is kept for now for backwards + # compatibility. + + context = MPContext() + + if prec is None and dps is None: + context.prec = self._default_precision + elif dps is None: + context.prec = prec + elif prec is None: + context.dps = dps + else: + raise TypeError("Cannot set both prec and dps") + + self._context = context + + self._dtype = context.mpf + self.zero = self.dtype(0) + self.one = self.dtype(1) + + # Only max_denom here is used for anything and is only used for + # to_rational. + self._max_denom = max(2**context.prec // 200, 99) + self._tolerance = self.one / self._max_denom + + @property + def tp(self): + # XXX: Domain treats tp as an alias of dtype. Here we need to two + # separate things: dtype is a callable to make/convert instances. + # We use tp with isinstance to check if an object is an instance + # of the domain already. + return self._dtype + + def dtype(self, arg): + # XXX: This is needed because mpmath does not recognise fmpz. + # It might be better to add conversion routines to mpmath and if that + # happens then this can be removed. + if isinstance(arg, SYMPY_INTS): + arg = int(arg) + return self._dtype(arg) + + def __eq__(self, other): + return isinstance(other, RealField) and self.precision == other.precision + + def __hash__(self): + return hash((self.__class__.__name__, self._dtype, self.precision)) + + def to_sympy(self, element): + """Convert ``element`` to SymPy number. """ + return Float(element, self.dps) + + def from_sympy(self, expr): + """Convert SymPy's number to ``dtype``. """ + number = expr.evalf(n=self.dps) + + if number.is_Number: + return self.dtype(number) + else: + raise CoercionFailed("expected real number, got %s" % expr) + + def from_ZZ(self, element, base): + return self.dtype(element) + + def from_ZZ_python(self, element, base): + return self.dtype(element) + + def from_ZZ_gmpy(self, element, base): + return self.dtype(int(element)) + + # XXX: We need to convert the denominators to int here because mpmath does + # not recognise mpz. Ideally mpmath would handle this and if it changed to + # do so then the calls to int here could be removed. + + def from_QQ(self, element, base): + return self.dtype(element.numerator) / int(element.denominator) + + def from_QQ_python(self, element, base): + return self.dtype(element.numerator) / int(element.denominator) + + def from_QQ_gmpy(self, element, base): + return self.dtype(int(element.numerator)) / int(element.denominator) + + def from_AlgebraicField(self, element, base): + return self.from_sympy(base.to_sympy(element).evalf(self.dps)) + + def from_RealField(self, element, base): + return self.dtype(element) + + def from_ComplexField(self, element, base): + if not element.imag: + return self.dtype(element.real) + + def to_rational(self, element, limit=True): + """Convert a real number to rational number. """ + return to_rational(element, self._max_denom, limit=limit) + + def get_ring(self): + """Returns a ring associated with ``self``. """ + return self + + def get_exact(self): + """Returns an exact domain associated with ``self``. """ + from sympy.polys.domains import QQ + return QQ + + def gcd(self, a, b): + """Returns GCD of ``a`` and ``b``. """ + return self.one + + def lcm(self, a, b): + """Returns LCM of ``a`` and ``b``. """ + return a*b + + def almosteq(self, a, b, tolerance=None): + """Check if ``a`` and ``b`` are almost equal. """ + return self._context.almosteq(a, b, tolerance) + + def is_square(self, a): + """Returns ``True`` if ``a >= 0`` and ``False`` otherwise. """ + return a >= 0 + + def exsqrt(self, a): + """Non-negative square root for ``a >= 0`` and ``None`` otherwise. + + Explanation + =========== + The square root may be slightly inaccurate due to floating point + rounding error. + """ + return a ** 0.5 if a >= 0 else None + + +RR = RealField() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/ring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/ring.py new file mode 100644 index 0000000000000000000000000000000000000000..c69e6944d8f51e4b319609368a476e6e847ae126 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/ring.py @@ -0,0 +1,118 @@ +"""Implementation of :class:`Ring` class. """ + + +from sympy.polys.domains.domain import Domain +from sympy.polys.polyerrors import ExactQuotientFailed, NotInvertible, NotReversible + +from sympy.utilities import public + +@public +class Ring(Domain): + """Represents a ring domain. """ + + is_Ring = True + + def get_ring(self): + """Returns a ring associated with ``self``. """ + return self + + def exquo(self, a, b): + """Exact quotient of ``a`` and ``b``, implies ``__floordiv__``. """ + if a % b: + raise ExactQuotientFailed(a, b, self) + else: + return a // b + + def quo(self, a, b): + """Quotient of ``a`` and ``b``, implies ``__floordiv__``. """ + return a // b + + def rem(self, a, b): + """Remainder of ``a`` and ``b``, implies ``__mod__``. """ + return a % b + + def div(self, a, b): + """Division of ``a`` and ``b``, implies ``__divmod__``. """ + return divmod(a, b) + + def invert(self, a, b): + """Returns inversion of ``a mod b``. """ + s, t, h = self.gcdex(a, b) + + if self.is_one(h): + return s % b + else: + raise NotInvertible("zero divisor") + + def revert(self, a): + """Returns ``a**(-1)`` if possible. """ + if self.is_one(a) or self.is_one(-a): + return a + else: + raise NotReversible('only units are reversible in a ring') + + def is_unit(self, a): + try: + self.revert(a) + return True + except NotReversible: + return False + + def numer(self, a): + """Returns numerator of ``a``. """ + return a + + def denom(self, a): + """Returns denominator of `a`. """ + return self.one + + def free_module(self, rank): + """ + Generate a free module of rank ``rank`` over self. + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).free_module(2) + QQ[x]**2 + """ + raise NotImplementedError + + def ideal(self, *gens): + """ + Generate an ideal of ``self``. + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).ideal(x**2) + + """ + from sympy.polys.agca.ideals import ModuleImplementedIdeal + return ModuleImplementedIdeal(self, self.free_module(1).submodule( + *[[x] for x in gens])) + + def quotient_ring(self, e): + """ + Form a quotient ring of ``self``. + + Here ``e`` can be an ideal or an iterable. + + >>> from sympy.abc import x + >>> from sympy import QQ + >>> QQ.old_poly_ring(x).quotient_ring(QQ.old_poly_ring(x).ideal(x**2)) + QQ[x]/ + >>> QQ.old_poly_ring(x).quotient_ring([x**2]) + QQ[x]/ + + The division operator has been overloaded for this: + + >>> QQ.old_poly_ring(x)/[x**2] + QQ[x]/ + """ + from sympy.polys.agca.ideals import Ideal + from sympy.polys.domains.quotientring import QuotientRing + if not isinstance(e, Ideal): + e = self.ideal(*e) + return QuotientRing(self, e) + + def __truediv__(self, e): + return self.quotient_ring(e) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/simpledomain.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/simpledomain.py new file mode 100644 index 0000000000000000000000000000000000000000..88cf634555d8bd9229d7fc511af3cf96fececbb8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/simpledomain.py @@ -0,0 +1,15 @@ +"""Implementation of :class:`SimpleDomain` class. """ + + +from sympy.polys.domains.domain import Domain +from sympy.utilities import public + +@public +class SimpleDomain(Domain): + """Base class for simple domains, e.g. ZZ, QQ. """ + + is_Simple = True + + def inject(self, *gens): + """Inject generators into this domain. """ + return self.poly_ring(*gens) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_domains.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_domains.py new file mode 100644 index 0000000000000000000000000000000000000000..403cb37a4f093517183345f0b53fc5253f6756bd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_domains.py @@ -0,0 +1,1434 @@ +"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """ + +from sympy.external.gmpy import GROUND_TYPES + +from sympy.core.numbers import (AlgebraicNumber, E, Float, I, Integer, + Rational, oo, pi, _illegal) +from sympy.core.singleton import S +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import sin +from sympy.polys.polytools import Poly +from sympy.abc import x, y, z + +from sympy.polys.domains import (ZZ, QQ, RR, CC, FF, GF, EX, EXRAW, ZZ_gmpy, + ZZ_python, QQ_gmpy, QQ_python) +from sympy.polys.domains.algebraicfield import AlgebraicField +from sympy.polys.domains.gaussiandomains import ZZ_I, QQ_I +from sympy.polys.domains.polynomialring import PolynomialRing +from sympy.polys.domains.realfield import RealField + +from sympy.polys.numberfields.subfield import field_isomorphism +from sympy.polys.rings import ring, PolyElement +from sympy.polys.specialpolys import cyclotomic_poly +from sympy.polys.fields import field, FracElement + +from sympy.polys.agca.extensions import FiniteExtension + +from sympy.polys.polyerrors import ( + UnificationFailed, + GeneratorsError, + CoercionFailed, + NotInvertible, + DomainError) + +from sympy.testing.pytest import raises, warns_deprecated_sympy + +from itertools import product + +ALG = QQ.algebraic_field(sqrt(2), sqrt(3)) + +def unify(K0, K1): + return K0.unify(K1) + +def test_Domain_unify(): + F3 = GF(3) + F5 = GF(5) + + assert unify(F3, F3) == F3 + raises(UnificationFailed, lambda: unify(F3, ZZ)) + raises(UnificationFailed, lambda: unify(F3, QQ)) + raises(UnificationFailed, lambda: unify(F3, ZZ_I)) + raises(UnificationFailed, lambda: unify(F3, QQ_I)) + raises(UnificationFailed, lambda: unify(F3, ALG)) + raises(UnificationFailed, lambda: unify(F3, RR)) + raises(UnificationFailed, lambda: unify(F3, CC)) + raises(UnificationFailed, lambda: unify(F3, ZZ[x])) + raises(UnificationFailed, lambda: unify(F3, ZZ.frac_field(x))) + raises(UnificationFailed, lambda: unify(F3, EX)) + + assert unify(F5, F5) == F5 + raises(UnificationFailed, lambda: unify(F5, F3)) + raises(UnificationFailed, lambda: unify(F5, F3[x])) + raises(UnificationFailed, lambda: unify(F5, F3.frac_field(x))) + + raises(UnificationFailed, lambda: unify(ZZ, F3)) + assert unify(ZZ, ZZ) == ZZ + assert unify(ZZ, QQ) == QQ + assert unify(ZZ, ALG) == ALG + assert unify(ZZ, RR) == RR + assert unify(ZZ, CC) == CC + assert unify(ZZ, ZZ[x]) == ZZ[x] + assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) + assert unify(ZZ, EX) == EX + + raises(UnificationFailed, lambda: unify(QQ, F3)) + assert unify(QQ, ZZ) == QQ + assert unify(QQ, QQ) == QQ + assert unify(QQ, ALG) == ALG + assert unify(QQ, RR) == RR + assert unify(QQ, CC) == CC + assert unify(QQ, ZZ[x]) == QQ[x] + assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) + assert unify(QQ, EX) == EX + + raises(UnificationFailed, lambda: unify(ZZ_I, F3)) + assert unify(ZZ_I, ZZ) == ZZ_I + assert unify(ZZ_I, ZZ_I) == ZZ_I + assert unify(ZZ_I, QQ) == QQ_I + assert unify(ZZ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) + assert unify(ZZ_I, RR) == CC + assert unify(ZZ_I, CC) == CC + assert unify(ZZ_I, ZZ[x]) == ZZ_I[x] + assert unify(ZZ_I, ZZ_I[x]) == ZZ_I[x] + assert unify(ZZ_I, ZZ.frac_field(x)) == ZZ_I.frac_field(x) + assert unify(ZZ_I, ZZ_I.frac_field(x)) == ZZ_I.frac_field(x) + assert unify(ZZ_I, EX) == EX + + raises(UnificationFailed, lambda: unify(QQ_I, F3)) + assert unify(QQ_I, ZZ) == QQ_I + assert unify(QQ_I, ZZ_I) == QQ_I + assert unify(QQ_I, QQ) == QQ_I + assert unify(QQ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) + assert unify(QQ_I, RR) == CC + assert unify(QQ_I, CC) == CC + assert unify(QQ_I, ZZ[x]) == QQ_I[x] + assert unify(QQ_I, ZZ_I[x]) == QQ_I[x] + assert unify(QQ_I, QQ[x]) == QQ_I[x] + assert unify(QQ_I, QQ_I[x]) == QQ_I[x] + assert unify(QQ_I, ZZ.frac_field(x)) == QQ_I.frac_field(x) + assert unify(QQ_I, ZZ_I.frac_field(x)) == QQ_I.frac_field(x) + assert unify(QQ_I, QQ.frac_field(x)) == QQ_I.frac_field(x) + assert unify(QQ_I, QQ_I.frac_field(x)) == QQ_I.frac_field(x) + assert unify(QQ_I, EX) == EX + + raises(UnificationFailed, lambda: unify(RR, F3)) + assert unify(RR, ZZ) == RR + assert unify(RR, QQ) == RR + assert unify(RR, ALG) == RR + assert unify(RR, RR) == RR + assert unify(RR, CC) == CC + assert unify(RR, ZZ[x]) == RR[x] + assert unify(RR, ZZ.frac_field(x)) == RR.frac_field(x) + assert unify(RR, EX) == EX + assert RR[x].unify(ZZ.frac_field(y)) == RR.frac_field(x, y) + + raises(UnificationFailed, lambda: unify(CC, F3)) + assert unify(CC, ZZ) == CC + assert unify(CC, QQ) == CC + assert unify(CC, ALG) == CC + assert unify(CC, RR) == CC + assert unify(CC, CC) == CC + assert unify(CC, ZZ[x]) == CC[x] + assert unify(CC, ZZ.frac_field(x)) == CC.frac_field(x) + assert unify(CC, EX) == EX + + raises(UnificationFailed, lambda: unify(ZZ[x], F3)) + assert unify(ZZ[x], ZZ) == ZZ[x] + assert unify(ZZ[x], QQ) == QQ[x] + assert unify(ZZ[x], ALG) == ALG[x] + assert unify(ZZ[x], RR) == RR[x] + assert unify(ZZ[x], CC) == CC[x] + assert unify(ZZ[x], ZZ[x]) == ZZ[x] + assert unify(ZZ[x], ZZ.frac_field(x)) == ZZ.frac_field(x) + assert unify(ZZ[x], EX) == EX + + raises(UnificationFailed, lambda: unify(ZZ.frac_field(x), F3)) + assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) + assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) + assert unify(ZZ.frac_field(x), ALG) == ALG.frac_field(x) + assert unify(ZZ.frac_field(x), RR) == RR.frac_field(x) + assert unify(ZZ.frac_field(x), CC) == CC.frac_field(x) + assert unify(ZZ.frac_field(x), ZZ[x]) == ZZ.frac_field(x) + assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) + assert unify(ZZ.frac_field(x), EX) == EX + + raises(UnificationFailed, lambda: unify(EX, F3)) + assert unify(EX, ZZ) == EX + assert unify(EX, QQ) == EX + assert unify(EX, ALG) == EX + assert unify(EX, RR) == EX + assert unify(EX, CC) == EX + assert unify(EX, ZZ[x]) == EX + assert unify(EX, ZZ.frac_field(x)) == EX + assert unify(EX, EX) == EX + +def test_Domain_unify_composite(): + assert unify(ZZ.poly_ring(x), ZZ) == ZZ.poly_ring(x) + assert unify(ZZ.poly_ring(x), QQ) == QQ.poly_ring(x) + assert unify(QQ.poly_ring(x), ZZ) == QQ.poly_ring(x) + assert unify(QQ.poly_ring(x), QQ) == QQ.poly_ring(x) + + assert unify(ZZ, ZZ.poly_ring(x)) == ZZ.poly_ring(x) + assert unify(QQ, ZZ.poly_ring(x)) == QQ.poly_ring(x) + assert unify(ZZ, QQ.poly_ring(x)) == QQ.poly_ring(x) + assert unify(QQ, QQ.poly_ring(x)) == QQ.poly_ring(x) + + assert unify(ZZ.poly_ring(x, y), ZZ) == ZZ.poly_ring(x, y) + assert unify(ZZ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) + assert unify(QQ.poly_ring(x, y), ZZ) == QQ.poly_ring(x, y) + assert unify(QQ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) + + assert unify(ZZ, ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) + assert unify(QQ, ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) + assert unify(ZZ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) + assert unify(QQ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) + + assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) + assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) + assert unify(QQ.frac_field(x), ZZ) == QQ.frac_field(x) + assert unify(QQ.frac_field(x), QQ) == QQ.frac_field(x) + + assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) + assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) + assert unify(ZZ, QQ.frac_field(x)) == QQ.frac_field(x) + assert unify(QQ, QQ.frac_field(x)) == QQ.frac_field(x) + + assert unify(ZZ.frac_field(x, y), ZZ) == ZZ.frac_field(x, y) + assert unify(ZZ.frac_field(x, y), QQ) == QQ.frac_field(x, y) + assert unify(QQ.frac_field(x, y), ZZ) == QQ.frac_field(x, y) + assert unify(QQ.frac_field(x, y), QQ) == QQ.frac_field(x, y) + + assert unify(ZZ, ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) + assert unify(QQ, ZZ.frac_field(x, y)) == QQ.frac_field(x, y) + assert unify(ZZ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) + assert unify(QQ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) + + assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x)) == ZZ.poly_ring(x) + assert unify(ZZ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) + assert unify(QQ.poly_ring(x), ZZ.poly_ring(x)) == QQ.poly_ring(x) + assert unify(QQ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) + + assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x)) == ZZ.poly_ring(x, y) + assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) + assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x)) == QQ.poly_ring(x, y) + assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) + + assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) + assert unify(ZZ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) + assert unify(QQ.poly_ring(x), ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) + assert unify(QQ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) + + assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x, z)) == ZZ.poly_ring(x, y, z) + assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) + assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) + assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) + + assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) + assert unify(ZZ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) + assert unify(QQ.frac_field(x), ZZ.frac_field(x)) == QQ.frac_field(x) + assert unify(QQ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) + + assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) + assert unify(ZZ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) + assert unify(QQ.frac_field(x, y), ZZ.frac_field(x)) == QQ.frac_field(x, y) + assert unify(QQ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) + + assert unify(ZZ.frac_field(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) + assert unify(ZZ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) + assert unify(QQ.frac_field(x), ZZ.frac_field(x, y)) == QQ.frac_field(x, y) + assert unify(QQ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) + + assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) + assert unify(ZZ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) + assert unify(QQ.frac_field(x, y), ZZ.frac_field(x, z)) == QQ.frac_field(x, y, z) + assert unify(QQ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) + + assert unify(ZZ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) + assert unify(ZZ.poly_ring(x), QQ.frac_field(x)) == ZZ.frac_field(x) + assert unify(QQ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) + assert unify(QQ.poly_ring(x), QQ.frac_field(x)) == QQ.frac_field(x) + + assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) + assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x)) == ZZ.frac_field(x, y) + assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) + assert unify(QQ.poly_ring(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) + + assert unify(ZZ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) + assert unify(ZZ.poly_ring(x), QQ.frac_field(x, y)) == ZZ.frac_field(x, y) + assert unify(QQ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) + assert unify(QQ.poly_ring(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) + + assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) + assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x, z)) == ZZ.frac_field(x, y, z) + assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) + assert unify(QQ.poly_ring(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) + + assert unify(ZZ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) + assert unify(ZZ.frac_field(x), QQ.poly_ring(x)) == ZZ.frac_field(x) + assert unify(QQ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) + assert unify(QQ.frac_field(x), QQ.poly_ring(x)) == QQ.frac_field(x) + + assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) + assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x)) == ZZ.frac_field(x, y) + assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) + assert unify(QQ.frac_field(x, y), QQ.poly_ring(x)) == QQ.frac_field(x, y) + + assert unify(ZZ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) + assert unify(ZZ.frac_field(x), QQ.poly_ring(x, y)) == ZZ.frac_field(x, y) + assert unify(QQ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) + assert unify(QQ.frac_field(x), QQ.poly_ring(x, y)) == QQ.frac_field(x, y) + + assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) + assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) + assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) + assert unify(QQ.frac_field(x, y), QQ.poly_ring(x, z)) == QQ.frac_field(x, y, z) + +def test_Domain_unify_algebraic(): + sqrt5 = QQ.algebraic_field(sqrt(5)) + sqrt7 = QQ.algebraic_field(sqrt(7)) + sqrt57 = QQ.algebraic_field(sqrt(5), sqrt(7)) + + assert sqrt5.unify(sqrt7) == sqrt57 + + assert sqrt5.unify(sqrt5[x, y]) == sqrt5[x, y] + assert sqrt5[x, y].unify(sqrt5) == sqrt5[x, y] + + assert sqrt5.unify(sqrt5.frac_field(x, y)) == sqrt5.frac_field(x, y) + assert sqrt5.frac_field(x, y).unify(sqrt5) == sqrt5.frac_field(x, y) + + assert sqrt5.unify(sqrt7[x, y]) == sqrt57[x, y] + assert sqrt5[x, y].unify(sqrt7) == sqrt57[x, y] + + assert sqrt5.unify(sqrt7.frac_field(x, y)) == sqrt57.frac_field(x, y) + assert sqrt5.frac_field(x, y).unify(sqrt7) == sqrt57.frac_field(x, y) + +def test_Domain_unify_FiniteExtension(): + KxZZ = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) + KxQQ = FiniteExtension(Poly(x**2 - 2, x, domain=QQ)) + KxZZy = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) + KxQQy = FiniteExtension(Poly(x**2 - 2, x, domain=QQ[y])) + + assert KxZZ.unify(KxZZ) == KxZZ + assert KxQQ.unify(KxQQ) == KxQQ + assert KxZZy.unify(KxZZy) == KxZZy + assert KxQQy.unify(KxQQy) == KxQQy + + assert KxZZ.unify(ZZ) == KxZZ + assert KxZZ.unify(QQ) == KxQQ + assert KxQQ.unify(ZZ) == KxQQ + assert KxQQ.unify(QQ) == KxQQ + + assert KxZZ.unify(ZZ[y]) == KxZZy + assert KxZZ.unify(QQ[y]) == KxQQy + assert KxQQ.unify(ZZ[y]) == KxQQy + assert KxQQ.unify(QQ[y]) == KxQQy + + assert KxZZy.unify(ZZ) == KxZZy + assert KxZZy.unify(QQ) == KxQQy + assert KxQQy.unify(ZZ) == KxQQy + assert KxQQy.unify(QQ) == KxQQy + + assert KxZZy.unify(ZZ[y]) == KxZZy + assert KxZZy.unify(QQ[y]) == KxQQy + assert KxQQy.unify(ZZ[y]) == KxQQy + assert KxQQy.unify(QQ[y]) == KxQQy + + K = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) + assert K.unify(ZZ) == K + assert K.unify(ZZ[x]) == K + assert K.unify(ZZ[y]) == K + assert K.unify(ZZ[x, y]) == K + + Kz = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y, z])) + assert K.unify(ZZ[z]) == Kz + assert K.unify(ZZ[x, z]) == Kz + assert K.unify(ZZ[y, z]) == Kz + assert K.unify(ZZ[x, y, z]) == Kz + + Kx = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) + Ky = FiniteExtension(Poly(y**2 - 2, y, domain=ZZ)) + Kxy = FiniteExtension(Poly(y**2 - 2, y, domain=Kx)) + assert Kx.unify(Kx) == Kx + assert Ky.unify(Ky) == Ky + assert Kx.unify(Ky) == Kxy + assert Ky.unify(Kx) == Kxy + +def test_Domain_unify_with_symbols(): + raises(UnificationFailed, lambda: ZZ[x, y].unify_with_symbols(ZZ, (y, z))) + raises(UnificationFailed, lambda: ZZ.unify_with_symbols(ZZ[x, y], (y, z))) + +def test_Domain__contains__(): + assert (0 in EX) is True + assert (0 in ZZ) is True + assert (0 in QQ) is True + assert (0 in RR) is True + assert (0 in CC) is True + assert (0 in ALG) is True + assert (0 in ZZ[x, y]) is True + assert (0 in QQ[x, y]) is True + assert (0 in RR[x, y]) is True + + assert (-7 in EX) is True + assert (-7 in ZZ) is True + assert (-7 in QQ) is True + assert (-7 in RR) is True + assert (-7 in CC) is True + assert (-7 in ALG) is True + assert (-7 in ZZ[x, y]) is True + assert (-7 in QQ[x, y]) is True + assert (-7 in RR[x, y]) is True + + assert (17 in EX) is True + assert (17 in ZZ) is True + assert (17 in QQ) is True + assert (17 in RR) is True + assert (17 in CC) is True + assert (17 in ALG) is True + assert (17 in ZZ[x, y]) is True + assert (17 in QQ[x, y]) is True + assert (17 in RR[x, y]) is True + + assert (Rational(-1, 7) in EX) is True + assert (Rational(-1, 7) in ZZ) is False + assert (Rational(-1, 7) in QQ) is True + assert (Rational(-1, 7) in RR) is True + assert (Rational(-1, 7) in CC) is True + assert (Rational(-1, 7) in ALG) is True + assert (Rational(-1, 7) in ZZ[x, y]) is False + assert (Rational(-1, 7) in QQ[x, y]) is True + assert (Rational(-1, 7) in RR[x, y]) is True + + assert (Rational(3, 5) in EX) is True + assert (Rational(3, 5) in ZZ) is False + assert (Rational(3, 5) in QQ) is True + assert (Rational(3, 5) in RR) is True + assert (Rational(3, 5) in CC) is True + assert (Rational(3, 5) in ALG) is True + assert (Rational(3, 5) in ZZ[x, y]) is False + assert (Rational(3, 5) in QQ[x, y]) is True + assert (Rational(3, 5) in RR[x, y]) is True + + assert (3.0 in EX) is True + assert (3.0 in ZZ) is True + assert (3.0 in QQ) is True + assert (3.0 in RR) is True + assert (3.0 in CC) is True + assert (3.0 in ALG) is True + assert (3.0 in ZZ[x, y]) is True + assert (3.0 in QQ[x, y]) is True + assert (3.0 in RR[x, y]) is True + + assert (3.14 in EX) is True + assert (3.14 in ZZ) is False + assert (3.14 in QQ) is True + assert (3.14 in RR) is True + assert (3.14 in CC) is True + assert (3.14 in ALG) is True + assert (3.14 in ZZ[x, y]) is False + assert (3.14 in QQ[x, y]) is True + assert (3.14 in RR[x, y]) is True + + assert (oo in ALG) is False + assert (oo in ZZ[x, y]) is False + assert (oo in QQ[x, y]) is False + + assert (-oo in ZZ) is False + assert (-oo in QQ) is False + assert (-oo in ALG) is False + assert (-oo in ZZ[x, y]) is False + assert (-oo in QQ[x, y]) is False + + assert (sqrt(7) in EX) is True + assert (sqrt(7) in ZZ) is False + assert (sqrt(7) in QQ) is False + assert (sqrt(7) in RR) is True + assert (sqrt(7) in CC) is True + assert (sqrt(7) in ALG) is False + assert (sqrt(7) in ZZ[x, y]) is False + assert (sqrt(7) in QQ[x, y]) is False + assert (sqrt(7) in RR[x, y]) is True + + assert (2*sqrt(3) + 1 in EX) is True + assert (2*sqrt(3) + 1 in ZZ) is False + assert (2*sqrt(3) + 1 in QQ) is False + assert (2*sqrt(3) + 1 in RR) is True + assert (2*sqrt(3) + 1 in CC) is True + assert (2*sqrt(3) + 1 in ALG) is True + assert (2*sqrt(3) + 1 in ZZ[x, y]) is False + assert (2*sqrt(3) + 1 in QQ[x, y]) is False + assert (2*sqrt(3) + 1 in RR[x, y]) is True + + assert (sin(1) in EX) is True + assert (sin(1) in ZZ) is False + assert (sin(1) in QQ) is False + assert (sin(1) in RR) is True + assert (sin(1) in CC) is True + assert (sin(1) in ALG) is False + assert (sin(1) in ZZ[x, y]) is False + assert (sin(1) in QQ[x, y]) is False + assert (sin(1) in RR[x, y]) is True + + assert (x**2 + 1 in EX) is True + assert (x**2 + 1 in ZZ) is False + assert (x**2 + 1 in QQ) is False + assert (x**2 + 1 in RR) is False + assert (x**2 + 1 in CC) is False + assert (x**2 + 1 in ALG) is False + assert (x**2 + 1 in ZZ[x]) is True + assert (x**2 + 1 in QQ[x]) is True + assert (x**2 + 1 in RR[x]) is True + assert (x**2 + 1 in ZZ[x, y]) is True + assert (x**2 + 1 in QQ[x, y]) is True + assert (x**2 + 1 in RR[x, y]) is True + + assert (x**2 + y**2 in EX) is True + assert (x**2 + y**2 in ZZ) is False + assert (x**2 + y**2 in QQ) is False + assert (x**2 + y**2 in RR) is False + assert (x**2 + y**2 in CC) is False + assert (x**2 + y**2 in ALG) is False + assert (x**2 + y**2 in ZZ[x]) is False + assert (x**2 + y**2 in QQ[x]) is False + assert (x**2 + y**2 in RR[x]) is False + assert (x**2 + y**2 in ZZ[x, y]) is True + assert (x**2 + y**2 in QQ[x, y]) is True + assert (x**2 + y**2 in RR[x, y]) is True + + assert (Rational(3, 2)*x/(y + 1) - z in QQ[x, y, z]) is False + + +def test_issue_14433(): + assert (Rational(2, 3)*x in QQ.frac_field(1/x)) is True + assert (1/x in QQ.frac_field(x)) is True + assert ((x**2 + y**2) in QQ.frac_field(1/x, 1/y)) is True + assert ((x + y) in QQ.frac_field(1/x, y)) is True + assert ((x - y) in QQ.frac_field(x, 1/y)) is True + + +def test_Domain_is_field(): + assert ZZ.is_Field is False + assert GF(5).is_Field is True + assert GF(6).is_Field is False + assert QQ.is_Field is True + assert RR.is_Field is True + assert CC.is_Field is True + assert EX.is_Field is True + assert ALG.is_Field is True + assert QQ[x].is_Field is False + assert ZZ.frac_field(x).is_Field is True + + +def test_Domain_get_ring(): + assert ZZ.has_assoc_Ring is True + assert QQ.has_assoc_Ring is True + assert ZZ[x].has_assoc_Ring is True + assert QQ[x].has_assoc_Ring is True + assert ZZ[x, y].has_assoc_Ring is True + assert QQ[x, y].has_assoc_Ring is True + assert ZZ.frac_field(x).has_assoc_Ring is True + assert QQ.frac_field(x).has_assoc_Ring is True + assert ZZ.frac_field(x, y).has_assoc_Ring is True + assert QQ.frac_field(x, y).has_assoc_Ring is True + + assert EX.has_assoc_Ring is False + assert RR.has_assoc_Ring is False + assert ALG.has_assoc_Ring is False + + assert ZZ.get_ring() == ZZ + assert QQ.get_ring() == ZZ + assert ZZ[x].get_ring() == ZZ[x] + assert QQ[x].get_ring() == QQ[x] + assert ZZ[x, y].get_ring() == ZZ[x, y] + assert QQ[x, y].get_ring() == QQ[x, y] + assert ZZ.frac_field(x).get_ring() == ZZ[x] + assert QQ.frac_field(x).get_ring() == QQ[x] + assert ZZ.frac_field(x, y).get_ring() == ZZ[x, y] + assert QQ.frac_field(x, y).get_ring() == QQ[x, y] + + assert EX.get_ring() == EX + + assert RR.get_ring() == RR + # XXX: This should also be like RR + raises(DomainError, lambda: ALG.get_ring()) + + +def test_Domain_get_field(): + assert EX.has_assoc_Field is True + assert ZZ.has_assoc_Field is True + assert QQ.has_assoc_Field is True + assert RR.has_assoc_Field is True + assert ALG.has_assoc_Field is True + assert ZZ[x].has_assoc_Field is True + assert QQ[x].has_assoc_Field is True + assert ZZ[x, y].has_assoc_Field is True + assert QQ[x, y].has_assoc_Field is True + + assert EX.get_field() == EX + assert ZZ.get_field() == QQ + assert QQ.get_field() == QQ + assert RR.get_field() == RR + assert ALG.get_field() == ALG + assert ZZ[x].get_field() == ZZ.frac_field(x) + assert QQ[x].get_field() == QQ.frac_field(x) + assert ZZ[x, y].get_field() == ZZ.frac_field(x, y) + assert QQ[x, y].get_field() == QQ.frac_field(x, y) + + +def test_Domain_set_domain(): + doms = [GF(5), ZZ, QQ, ALG, RR, CC, EX, ZZ[z], QQ[z], RR[z], CC[z], EX[z]] + for D1 in doms: + for D2 in doms: + assert D1[x].set_domain(D2) == D2[x] + assert D1[x, y].set_domain(D2) == D2[x, y] + assert D1.frac_field(x).set_domain(D2) == D2.frac_field(x) + assert D1.frac_field(x, y).set_domain(D2) == D2.frac_field(x, y) + assert D1.old_poly_ring(x).set_domain(D2) == D2.old_poly_ring(x) + assert D1.old_poly_ring(x, y).set_domain(D2) == D2.old_poly_ring(x, y) + assert D1.old_frac_field(x).set_domain(D2) == D2.old_frac_field(x) + assert D1.old_frac_field(x, y).set_domain(D2) == D2.old_frac_field(x, y) + + +def test_Domain_is_Exact(): + exact = [GF(5), ZZ, QQ, ALG, EX] + inexact = [RR, CC] + for D in exact + inexact: + for R in D, D[x], D.frac_field(x), D.old_poly_ring(x), D.old_frac_field(x): + if D in exact: + assert R.is_Exact is True + else: + assert R.is_Exact is False + + +def test_Domain_get_exact(): + assert EX.get_exact() == EX + assert ZZ.get_exact() == ZZ + assert QQ.get_exact() == QQ + assert RR.get_exact() == QQ + assert CC.get_exact() == QQ_I + assert ALG.get_exact() == ALG + assert ZZ[x].get_exact() == ZZ[x] + assert QQ[x].get_exact() == QQ[x] + assert RR[x].get_exact() == QQ[x] + assert CC[x].get_exact() == QQ_I[x] + assert ZZ[x, y].get_exact() == ZZ[x, y] + assert QQ[x, y].get_exact() == QQ[x, y] + assert RR[x, y].get_exact() == QQ[x, y] + assert CC[x, y].get_exact() == QQ_I[x, y] + assert ZZ.frac_field(x).get_exact() == ZZ.frac_field(x) + assert QQ.frac_field(x).get_exact() == QQ.frac_field(x) + assert RR.frac_field(x).get_exact() == QQ.frac_field(x) + assert CC.frac_field(x).get_exact() == QQ_I.frac_field(x) + assert ZZ.frac_field(x, y).get_exact() == ZZ.frac_field(x, y) + assert QQ.frac_field(x, y).get_exact() == QQ.frac_field(x, y) + assert RR.frac_field(x, y).get_exact() == QQ.frac_field(x, y) + assert CC.frac_field(x, y).get_exact() == QQ_I.frac_field(x, y) + assert ZZ.old_poly_ring(x).get_exact() == ZZ.old_poly_ring(x) + assert QQ.old_poly_ring(x).get_exact() == QQ.old_poly_ring(x) + assert RR.old_poly_ring(x).get_exact() == QQ.old_poly_ring(x) + assert CC.old_poly_ring(x).get_exact() == QQ_I.old_poly_ring(x) + assert ZZ.old_poly_ring(x, y).get_exact() == ZZ.old_poly_ring(x, y) + assert QQ.old_poly_ring(x, y).get_exact() == QQ.old_poly_ring(x, y) + assert RR.old_poly_ring(x, y).get_exact() == QQ.old_poly_ring(x, y) + assert CC.old_poly_ring(x, y).get_exact() == QQ_I.old_poly_ring(x, y) + assert ZZ.old_frac_field(x).get_exact() == ZZ.old_frac_field(x) + assert QQ.old_frac_field(x).get_exact() == QQ.old_frac_field(x) + assert RR.old_frac_field(x).get_exact() == QQ.old_frac_field(x) + assert CC.old_frac_field(x).get_exact() == QQ_I.old_frac_field(x) + assert ZZ.old_frac_field(x, y).get_exact() == ZZ.old_frac_field(x, y) + assert QQ.old_frac_field(x, y).get_exact() == QQ.old_frac_field(x, y) + assert RR.old_frac_field(x, y).get_exact() == QQ.old_frac_field(x, y) + assert CC.old_frac_field(x, y).get_exact() == QQ_I.old_frac_field(x, y) + + +def test_Domain_characteristic(): + for F, c in [(FF(3), 3), (FF(5), 5), (FF(7), 7)]: + for R in F, F[x], F.frac_field(x), F.old_poly_ring(x), F.old_frac_field(x): + assert R.has_CharacteristicZero is False + assert R.characteristic() == c + for D in ZZ, QQ, ZZ_I, QQ_I, ALG: + for R in D, D[x], D.frac_field(x), D.old_poly_ring(x), D.old_frac_field(x): + assert R.has_CharacteristicZero is True + assert R.characteristic() == 0 + + +def test_Domain_is_unit(): + nums = [-2, -1, 0, 1, 2] + invring = [False, True, False, True, False] + invfield = [True, True, False, True, True] + ZZx, QQx, QQxf = ZZ[x], QQ[x], QQ.frac_field(x) + assert [ZZ.is_unit(ZZ(n)) for n in nums] == invring + assert [QQ.is_unit(QQ(n)) for n in nums] == invfield + assert [ZZx.is_unit(ZZx(n)) for n in nums] == invring + assert [QQx.is_unit(QQx(n)) for n in nums] == invfield + assert [QQxf.is_unit(QQxf(n)) for n in nums] == invfield + assert ZZx.is_unit(ZZx(x)) is False + assert QQx.is_unit(QQx(x)) is False + assert QQxf.is_unit(QQxf(x)) is True + + +def test_Domain_convert(): + + def check_element(e1, e2, K1, K2, K3): + if isinstance(e1, PolyElement): + assert isinstance(e2, PolyElement) and e1.ring == e2.ring + elif isinstance(e1, FracElement): + assert isinstance(e2, FracElement) and e1.field == e2.field + else: + assert type(e1) is type(e2), '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) + assert e1 == e2, '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) + + def check_domains(K1, K2): + K3 = K1.unify(K2) + check_element(K3.convert_from(K1.one, K1), K3.one, K1, K2, K3) + check_element(K3.convert_from(K2.one, K2), K3.one, K1, K2, K3) + check_element(K3.convert_from(K1.zero, K1), K3.zero, K1, K2, K3) + check_element(K3.convert_from(K2.zero, K2), K3.zero, K1, K2, K3) + + def composite_domains(K): + domains = [ + K, + K[y], K[z], K[y, z], + K.frac_field(y), K.frac_field(z), K.frac_field(y, z), + # XXX: These should be tested and made to work... + # K.old_poly_ring(y), K.old_frac_field(y), + ] + return domains + + QQ2 = QQ.algebraic_field(sqrt(2)) + QQ3 = QQ.algebraic_field(sqrt(3)) + doms = [ZZ, QQ, QQ2, QQ3, QQ_I, ZZ_I, RR, CC] + + for i, K1 in enumerate(doms): + for K2 in doms[i:]: + for K3 in composite_domains(K1): + for K4 in composite_domains(K2): + check_domains(K3, K4) + + assert QQ.convert(10e-52) == QQ(1684996666696915, 1684996666696914987166688442938726917102321526408785780068975640576) + + R, xr = ring("x", ZZ) + assert ZZ.convert(xr - xr) == 0 + assert ZZ.convert(xr - xr, R.to_domain()) == 0 + + assert CC.convert(ZZ_I(1, 2)) == CC(1, 2) + assert CC.convert(QQ_I(1, 2)) == CC(1, 2) + + assert QQ.convert_from(RR(0.5), RR) == QQ(1, 2) + assert RR.convert_from(QQ(1, 2), QQ) == RR(0.5) + assert QQ_I.convert_from(CC(0.5, 0.75), CC) == QQ_I(QQ(1, 2), QQ(3, 4)) + assert CC.convert_from(QQ_I(QQ(1, 2), QQ(3, 4)), QQ_I) == CC(0.5, 0.75) + + K1 = QQ.frac_field(x) + K2 = ZZ.frac_field(x) + K3 = QQ[x] + K4 = ZZ[x] + Ks = [K1, K2, K3, K4] + for Ka, Kb in product(Ks, Ks): + assert Ka.convert_from(Kb.from_sympy(x), Kb) == Ka.from_sympy(x) + + assert K2.convert_from(QQ(1, 2), QQ) == K2(QQ(1, 2)) + + +def test_EX_convert(): + + elements = [ + (ZZ, ZZ(3)), + (QQ, QQ(1,2)), + (ZZ_I, ZZ_I(1,2)), + (QQ_I, QQ_I(1,2)), + (RR, RR(3)), + (CC, CC(1,2)), + (EX, EX(3)), + (EXRAW, EXRAW(3)), + (ALG, ALG.from_sympy(sqrt(2))), + ] + + for R, e in elements: + for EE in EX, EXRAW: + elem = EE.from_sympy(R.to_sympy(e)) + assert EE.convert_from(e, R) == elem + assert R.convert_from(elem, EE) == e + + +def test_GlobalPolynomialRing_convert(): + K1 = QQ.old_poly_ring(x) + K2 = QQ[x] + assert K1.convert(x) == K1.convert(K2.convert(x), K2) + assert K2.convert(x) == K2.convert(K1.convert(x), K1) + + K1 = QQ.old_poly_ring(x, y) + K2 = QQ[x] + assert K1.convert(x) == K1.convert(K2.convert(x), K2) + #assert K2.convert(x) == K2.convert(K1.convert(x), K1) + + K1 = ZZ.old_poly_ring(x, y) + K2 = QQ[x] + assert K1.convert(x) == K1.convert(K2.convert(x), K2) + #assert K2.convert(x) == K2.convert(K1.convert(x), K1) + + +def test_PolynomialRing__init(): + R, = ring("", ZZ) + assert ZZ.poly_ring() == R.to_domain() + + +def test_FractionField__init(): + F, = field("", ZZ) + assert ZZ.frac_field() == F.to_domain() + + +def test_FractionField_convert(): + K = QQ.frac_field(x) + assert K.convert(QQ(2, 3), QQ) == K.from_sympy(Rational(2, 3)) + K = QQ.frac_field(x) + assert K.convert(ZZ(2), ZZ) == K.from_sympy(Integer(2)) + + +def test_inject(): + assert ZZ.inject(x, y, z) == ZZ[x, y, z] + assert ZZ[x].inject(y, z) == ZZ[x, y, z] + assert ZZ.frac_field(x).inject(y, z) == ZZ.frac_field(x, y, z) + raises(GeneratorsError, lambda: ZZ[x].inject(x)) + + +def test_drop(): + assert ZZ.drop(x) == ZZ + assert ZZ[x].drop(x) == ZZ + assert ZZ[x, y].drop(x) == ZZ[y] + assert ZZ.frac_field(x).drop(x) == ZZ + assert ZZ.frac_field(x, y).drop(x) == ZZ.frac_field(y) + assert ZZ[x][y].drop(y) == ZZ[x] + assert ZZ[x][y].drop(x) == ZZ[y] + assert ZZ.frac_field(x)[y].drop(x) == ZZ[y] + assert ZZ.frac_field(x)[y].drop(y) == ZZ.frac_field(x) + Ky = FiniteExtension(Poly(x**2-1, x, domain=ZZ[y])) + K = FiniteExtension(Poly(x**2-1, x, domain=ZZ)) + assert Ky.drop(y) == K + raises(GeneratorsError, lambda: Ky.drop(x)) + + +def test_Domain_map(): + seq = ZZ.map([1, 2, 3, 4]) + + assert all(ZZ.of_type(elt) for elt in seq) + + seq = ZZ.map([[1, 2, 3, 4]]) + + assert all(ZZ.of_type(elt) for elt in seq[0]) and len(seq) == 1 + + +def test_Domain___eq__(): + assert (ZZ[x, y] == ZZ[x, y]) is True + assert (QQ[x, y] == QQ[x, y]) is True + + assert (ZZ[x, y] == QQ[x, y]) is False + assert (QQ[x, y] == ZZ[x, y]) is False + + assert (ZZ.frac_field(x, y) == ZZ.frac_field(x, y)) is True + assert (QQ.frac_field(x, y) == QQ.frac_field(x, y)) is True + + assert (ZZ.frac_field(x, y) == QQ.frac_field(x, y)) is False + assert (QQ.frac_field(x, y) == ZZ.frac_field(x, y)) is False + + assert RealField()[x] == RR[x] + + +def test_Domain__algebraic_field(): + alg = ZZ.algebraic_field(sqrt(2)) + assert alg.ext.minpoly == Poly(x**2 - 2) + assert alg.dom == QQ + + alg = QQ.algebraic_field(sqrt(2)) + assert alg.ext.minpoly == Poly(x**2 - 2) + assert alg.dom == QQ + + alg = alg.algebraic_field(sqrt(3)) + assert alg.ext.minpoly == Poly(x**4 - 10*x**2 + 1) + assert alg.dom == QQ + + +def test_Domain_alg_field_from_poly(): + f = Poly(x**2 - 2) + g = Poly(x**2 - 3) + h = Poly(x**4 - 10*x**2 + 1) + + alg = ZZ.alg_field_from_poly(f) + assert alg.ext.minpoly == f + assert alg.dom == QQ + + alg = QQ.alg_field_from_poly(f) + assert alg.ext.minpoly == f + assert alg.dom == QQ + + alg = alg.alg_field_from_poly(g) + assert alg.ext.minpoly == h + assert alg.dom == QQ + + +def test_Domain_cyclotomic_field(): + K = ZZ.cyclotomic_field(12) + assert K.ext.minpoly == Poly(cyclotomic_poly(12)) + assert K.dom == QQ + + F = QQ.cyclotomic_field(3) + assert F.ext.minpoly == Poly(cyclotomic_poly(3)) + assert F.dom == QQ + + E = F.cyclotomic_field(4) + assert field_isomorphism(E.ext, K.ext) is not None + assert E.dom == QQ + + +def test_PolynomialRing_from_FractionField(): + F, x,y = field("x,y", ZZ) + R, X,Y = ring("x,y", ZZ) + + f = (x**2 + y**2)/(x + 1) + g = (x**2 + y**2)/4 + h = x**2 + y**2 + + assert R.to_domain().from_FractionField(f, F.to_domain()) is None + assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 + assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 + + F, x,y = field("x,y", QQ) + R, X,Y = ring("x,y", QQ) + + f = (x**2 + y**2)/(x + 1) + g = (x**2 + y**2)/4 + h = x**2 + y**2 + + assert R.to_domain().from_FractionField(f, F.to_domain()) is None + assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 + assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 + + +def test_FractionField_from_PolynomialRing(): + R, x,y = ring("x,y", QQ) + F, X,Y = field("x,y", ZZ) + + f = 3*x**2 + 5*y**2 + g = x**2/3 + y**2/5 + + assert F.to_domain().from_PolynomialRing(f, R.to_domain()) == 3*X**2 + 5*Y**2 + assert F.to_domain().from_PolynomialRing(g, R.to_domain()) == (5*X**2 + 3*Y**2)/15 + + +def test_FF_of_type(): + # XXX: of_type is not very useful here because in the case of ground types + # = flint all elements are of type nmod. + assert FF(3).of_type(FF(3)(1)) is True + assert FF(5).of_type(FF(5)(3)) is True + + +def test___eq__(): + assert not QQ[x] == ZZ[x] + assert not QQ.frac_field(x) == ZZ.frac_field(x) + + +def test_RealField_from_sympy(): + assert RR.convert(S.Zero) == RR.dtype(0) + assert RR.convert(S(0.0)) == RR.dtype(0.0) + assert RR.convert(S.One) == RR.dtype(1) + assert RR.convert(S(1.0)) == RR.dtype(1.0) + assert RR.convert(sin(1)) == RR.dtype(sin(1).evalf()) + + +def test_not_in_any_domain(): + check = list(_illegal) + [x] + [ + float(i) for i in _illegal[:3]] + for dom in (ZZ, QQ, RR, CC, EX): + for i in check: + if i == x and dom == EX: + continue + assert i not in dom, (i, dom) + raises(CoercionFailed, lambda: dom.convert(i)) + + +def test_ModularInteger(): + F3 = FF(3) + + a = F3(0) + assert F3.of_type(a) and a == 0 + a = F3(1) + assert F3.of_type(a) and a == 1 + a = F3(2) + assert F3.of_type(a) and a == 2 + a = F3(3) + assert F3.of_type(a) and a == 0 + a = F3(4) + assert F3.of_type(a) and a == 1 + + a = F3(F3(0)) + assert F3.of_type(a) and a == 0 + a = F3(F3(1)) + assert F3.of_type(a) and a == 1 + a = F3(F3(2)) + assert F3.of_type(a) and a == 2 + a = F3(F3(3)) + assert F3.of_type(a) and a == 0 + a = F3(F3(4)) + assert F3.of_type(a) and a == 1 + + a = -F3(1) + assert F3.of_type(a) and a == 2 + a = -F3(2) + assert F3.of_type(a) and a == 1 + + a = 2 + F3(2) + assert F3.of_type(a) and a == 1 + a = F3(2) + 2 + assert F3.of_type(a) and a == 1 + a = F3(2) + F3(2) + assert F3.of_type(a) and a == 1 + a = F3(2) + F3(2) + assert F3.of_type(a) and a == 1 + + a = 3 - F3(2) + assert F3.of_type(a) and a == 1 + a = F3(3) - 2 + assert F3.of_type(a) and a == 1 + a = F3(3) - F3(2) + assert F3.of_type(a) and a == 1 + a = F3(3) - F3(2) + assert F3.of_type(a) and a == 1 + + a = 2*F3(2) + assert F3.of_type(a) and a == 1 + a = F3(2)*2 + assert F3.of_type(a) and a == 1 + a = F3(2)*F3(2) + assert F3.of_type(a) and a == 1 + a = F3(2)*F3(2) + assert F3.of_type(a) and a == 1 + + a = 2/F3(2) + assert F3.of_type(a) and a == 1 + a = F3(2)/2 + assert F3.of_type(a) and a == 1 + a = F3(2)/F3(2) + assert F3.of_type(a) and a == 1 + a = F3(2)/F3(2) + assert F3.of_type(a) and a == 1 + + a = F3(2)**0 + assert F3.of_type(a) and a == 1 + a = F3(2)**1 + assert F3.of_type(a) and a == 2 + a = F3(2)**2 + assert F3.of_type(a) and a == 1 + + F7 = FF(7) + + a = F7(3)**100000000000 + assert F7.of_type(a) and a == 4 + a = F7(3)**-100000000000 + assert F7.of_type(a) and a == 2 + + assert bool(F3(3)) is False + assert bool(F3(4)) is True + + F5 = FF(5) + + a = F5(1)**(-1) + assert F5.of_type(a) and a == 1 + a = F5(2)**(-1) + assert F5.of_type(a) and a == 3 + a = F5(3)**(-1) + assert F5.of_type(a) and a == 2 + a = F5(4)**(-1) + assert F5.of_type(a) and a == 4 + + if GROUND_TYPES != 'flint': + # XXX: This gives a core dump with python-flint... + raises(NotInvertible, lambda: F5(0)**(-1)) + raises(NotInvertible, lambda: F5(5)**(-1)) + + raises(ValueError, lambda: FF(0)) + raises(ValueError, lambda: FF(2.1)) + + for n1 in range(5): + for n2 in range(5): + if GROUND_TYPES != 'flint': + with warns_deprecated_sympy(): + assert (F5(n1) < F5(n2)) is (n1 < n2) + with warns_deprecated_sympy(): + assert (F5(n1) <= F5(n2)) is (n1 <= n2) + with warns_deprecated_sympy(): + assert (F5(n1) > F5(n2)) is (n1 > n2) + with warns_deprecated_sympy(): + assert (F5(n1) >= F5(n2)) is (n1 >= n2) + else: + raises(TypeError, lambda: F5(n1) < F5(n2)) + raises(TypeError, lambda: F5(n1) <= F5(n2)) + raises(TypeError, lambda: F5(n1) > F5(n2)) + raises(TypeError, lambda: F5(n1) >= F5(n2)) + + # https://github.com/sympy/sympy/issues/26789 + assert GF(Integer(5)) == F5 + assert F5(Integer(3)) == F5(3) + + +def test_QQ_int(): + assert int(QQ(2**2000, 3**1250)) == 455431 + assert int(QQ(2**100, 3)) == 422550200076076467165567735125 + + +def test_RR_double(): + assert RR(3.14) > 1e-50 + assert RR(1e-13) > 1e-50 + assert RR(1e-14) > 1e-50 + assert RR(1e-15) > 1e-50 + assert RR(1e-20) > 1e-50 + assert RR(1e-40) > 1e-50 + + +def test_RR_Float(): + f1 = Float("1.01") + f2 = Float("1.0000000000000000000001") + assert f1._prec == 53 + assert f2._prec == 80 + assert RR(f1)-1 > 1e-50 + assert RR(f2)-1 < 1e-50 # RR's precision is lower than f2's + + RR2 = RealField(prec=f2._prec) + assert RR2(f1)-1 > 1e-50 + assert RR2(f2)-1 > 1e-50 # RR's precision is equal to f2's + + +def test_CC_double(): + assert CC(3.14).real > 1e-50 + assert CC(1e-13).real > 1e-50 + assert CC(1e-14).real > 1e-50 + assert CC(1e-15).real > 1e-50 + assert CC(1e-20).real > 1e-50 + assert CC(1e-40).real > 1e-50 + + assert CC(3.14j).imag > 1e-50 + assert CC(1e-13j).imag > 1e-50 + assert CC(1e-14j).imag > 1e-50 + assert CC(1e-15j).imag > 1e-50 + assert CC(1e-20j).imag > 1e-50 + assert CC(1e-40j).imag > 1e-50 + + +def test_gaussian_domains(): + I = S.ImaginaryUnit + a, b, c, d = [ZZ_I.convert(x) for x in (5, 2 + I, 3 - I, 5 - 5*I)] + assert ZZ_I.gcd(a, b) == b + assert ZZ_I.gcd(a, c) == b + assert ZZ_I.lcm(a, b) == a + assert ZZ_I.lcm(a, c) == d + assert ZZ_I(3, 4) != QQ_I(3, 4) # XXX is this right or should QQ->ZZ if possible? + assert ZZ_I(3, 0) != 3 # and should this go to Integer? + assert QQ_I(S(3)/4, 0) != S(3)/4 # and this to Rational? + assert ZZ_I(0, 0).quadrant() == 0 + assert ZZ_I(-1, 0).quadrant() == 2 + + assert QQ_I.convert(QQ(3, 2)) == QQ_I(QQ(3, 2), QQ(0)) + assert QQ_I.convert(QQ(3, 2), QQ) == QQ_I(QQ(3, 2), QQ(0)) + + for G in (QQ_I, ZZ_I): + + q = G(3, 4) + assert str(q) == '3 + 4*I' + assert q.parent() == G + assert q._get_xy(pi) == (None, None) + assert q._get_xy(2) == (2, 0) + assert q._get_xy(2*I) == (0, 2) + + assert hash(q) == hash((3, 4)) + assert G(1, 2) == G(1, 2) + assert G(1, 2) != G(1, 3) + assert G(3, 0) == G(3) + + assert q + q == G(6, 8) + assert q - q == G(0, 0) + assert 3 - q == -q + 3 == G(0, -4) + assert 3 + q == q + 3 == G(6, 4) + assert q * q == G(-7, 24) + assert 3 * q == q * 3 == G(9, 12) + assert q ** 0 == G(1, 0) + assert q ** 1 == q + assert q ** 2 == q * q == G(-7, 24) + assert q ** 3 == q * q * q == G(-117, 44) + assert 1 / q == q ** -1 == QQ_I(S(3)/25, - S(4)/25) + assert q / 1 == QQ_I(3, 4) + assert q / 2 == QQ_I(S(3)/2, 2) + assert q/3 == QQ_I(1, S(4)/3) + assert 3/q == QQ_I(S(9)/25, -S(12)/25) + i, r = divmod(q, 2) + assert 2*i + r == q + i, r = divmod(2, q) + assert q*i + r == G(2, 0) + + a, b = G(2, 0), G(1, -1) + c, d, g = G.gcdex(a, b) + assert g == G.gcd(a, b) + assert c * a + d * b == g + + raises(ZeroDivisionError, lambda: q % 0) + raises(ZeroDivisionError, lambda: q / 0) + raises(ZeroDivisionError, lambda: q // 0) + raises(ZeroDivisionError, lambda: divmod(q, 0)) + raises(ZeroDivisionError, lambda: divmod(q, 0)) + raises(TypeError, lambda: q + x) + raises(TypeError, lambda: q - x) + raises(TypeError, lambda: x + q) + raises(TypeError, lambda: x - q) + raises(TypeError, lambda: q * x) + raises(TypeError, lambda: x * q) + raises(TypeError, lambda: q / x) + raises(TypeError, lambda: x / q) + raises(TypeError, lambda: q // x) + raises(TypeError, lambda: x // q) + + assert G.from_sympy(S(2)) == G(2, 0) + assert G.to_sympy(G(2, 0)) == S(2) + raises(CoercionFailed, lambda: G.from_sympy(pi)) + + PR = G.inject(x) + assert isinstance(PR, PolynomialRing) + assert PR.domain == G + assert len(PR.gens) == 1 and PR.gens[0].as_expr() == x + + if G is QQ_I: + AF = G.as_AlgebraicField() + assert isinstance(AF, AlgebraicField) + assert AF.domain == QQ + assert AF.ext.args[0] == I + + for qi in [G(-1, 0), G(1, 0), G(0, -1), G(0, 1)]: + assert G.is_negative(qi) is False + assert G.is_positive(qi) is False + assert G.is_nonnegative(qi) is False + assert G.is_nonpositive(qi) is False + + domains = [ZZ, QQ, AlgebraicField(QQ, I)] + + # XXX: These domains are all obsolete because ZZ/QQ with MPZ/MPQ + # already use either gmpy, flint or python depending on the + # availability of these libraries. We can keep these tests for now but + # ideally we should remove these alternate domains entirely. + domains += [ZZ_python(), QQ_python()] + if GROUND_TYPES == 'gmpy': + domains += [ZZ_gmpy(), QQ_gmpy()] + + for K in domains: + assert G.convert(K(2)) == G(2, 0) + assert G.convert(K(2), K) == G(2, 0) + + for K in ZZ_I, QQ_I: + assert G.convert(K(1, 1)) == G(1, 1) + assert G.convert(K(1, 1), K) == G(1, 1) + + if G == ZZ_I: + assert repr(q) == 'ZZ_I(3, 4)' + assert q//3 == G(1, 1) + assert 12//q == G(1, -2) + assert 12 % q == G(1, 2) + assert q % 2 == G(-1, 0) + assert i == G(0, 0) + assert r == G(2, 0) + assert G.get_ring() == G + assert G.get_field() == QQ_I + else: + assert repr(q) == 'QQ_I(3, 4)' + assert G.get_ring() == ZZ_I + assert G.get_field() == G + assert q//3 == G(1, S(4)/3) + assert 12//q == G(S(36)/25, -S(48)/25) + assert 12 % q == G(0, 0) + assert q % 2 == G(0, 0) + assert i == G(S(6)/25, -S(8)/25), (G,i) + assert r == G(0, 0) + q2 = G(S(3)/2, S(5)/3) + assert G.numer(q2) == ZZ_I(9, 10) + assert G.denom(q2) == ZZ_I(6) + + +def test_EX_EXRAW(): + assert EXRAW.zero is S.Zero + assert EXRAW.one is S.One + + assert EX(1) == EX.Expression(1) + assert EX(1).ex is S.One + assert EXRAW(1) is S.One + + # EX has cancelling but EXRAW does not + assert 2*EX((x + y*x)/x) == EX(2 + 2*y) != 2*((x + y*x)/x) + assert 2*EXRAW((x + y*x)/x) == 2*((x + y*x)/x) != (1 + y) + + assert EXRAW.convert_from(EX(1), EX) is EXRAW.one + assert EX.convert_from(EXRAW(1), EXRAW) == EX.one + + assert EXRAW.from_sympy(S.One) is S.One + assert EXRAW.to_sympy(EXRAW.one) is S.One + raises(CoercionFailed, lambda: EXRAW.from_sympy([])) + + assert EXRAW.get_field() == EXRAW + + assert EXRAW.unify(EX) == EXRAW + assert EX.unify(EXRAW) == EXRAW + + +def test_EX_ordering(): + elements = [EX(1), EX(x), EX(3)] + assert sorted(elements) == [EX(1), EX(3), EX(x)] + + +def test_canonical_unit(): + + for K in [ZZ, QQ, RR]: # CC? + assert K.canonical_unit(K(2)) == K(1) + assert K.canonical_unit(K(-2)) == K(-1) + + for K in [ZZ_I, QQ_I]: + i = K.from_sympy(I) + assert K.canonical_unit(K(2)) == K(1) + assert K.canonical_unit(K(2)*i) == -i + assert K.canonical_unit(-K(2)) == K(-1) + assert K.canonical_unit(-K(2)*i) == i + + K = ZZ[x] + assert K.canonical_unit(K(x + 1)) == K(1) + assert K.canonical_unit(K(-x + 1)) == K(-1) + + K = ZZ_I[x] + assert K.canonical_unit(K.from_sympy(I*x)) == ZZ_I(0, -1) + + K = ZZ_I.frac_field(x, y) + i = K.from_sympy(I) + assert i / i == K.one + assert (K.one + i)/(i - K.one) == -i + + +def test_Domain_is_negative(): + I = S.ImaginaryUnit + a, b = [CC.convert(x) for x in (2 + I, 5)] + assert CC.is_negative(a) == False + assert CC.is_negative(b) == False + + +def test_Domain_is_positive(): + I = S.ImaginaryUnit + a, b = [CC.convert(x) for x in (2 + I, 5)] + assert CC.is_positive(a) == False + assert CC.is_positive(b) == False + + +def test_Domain_is_nonnegative(): + I = S.ImaginaryUnit + a, b = [CC.convert(x) for x in (2 + I, 5)] + assert CC.is_nonnegative(a) == False + assert CC.is_nonnegative(b) == False + + +def test_Domain_is_nonpositive(): + I = S.ImaginaryUnit + a, b = [CC.convert(x) for x in (2 + I, 5)] + assert CC.is_nonpositive(a) == False + assert CC.is_nonpositive(b) == False + + +def test_exponential_domain(): + K = ZZ[E] + eK = K.from_sympy(E) + assert K.from_sympy(exp(3)) == eK ** 3 + assert K.convert(exp(3)) == eK ** 3 + + +def test_AlgebraicField_alias(): + # No default alias: + k = QQ.algebraic_field(sqrt(2)) + assert k.ext.alias is None + + # For a single extension, its alias is used: + alpha = AlgebraicNumber(sqrt(2), alias='alpha') + k = QQ.algebraic_field(alpha) + assert k.ext.alias.name == 'alpha' + + # Can override the alias of a single extension: + k = QQ.algebraic_field(alpha, alias='theta') + assert k.ext.alias.name == 'theta' + + # With multiple extensions, no default alias: + k = QQ.algebraic_field(sqrt(2), sqrt(3)) + assert k.ext.alias is None + + # With multiple extensions, no default alias, even if one of + # the extensions has one: + k = QQ.algebraic_field(alpha, sqrt(3)) + assert k.ext.alias is None + + # With multiple extensions, may set an alias: + k = QQ.algebraic_field(sqrt(2), sqrt(3), alias='theta') + assert k.ext.alias.name == 'theta' + + # Alias is passed to constructed field elements: + k = QQ.algebraic_field(alpha) + beta = k.to_alg_num(k([1, 2, 3])) + assert beta.alias is alpha.alias + + +def test_exsqrt(): + assert ZZ.is_square(ZZ(4)) is True + assert ZZ.exsqrt(ZZ(4)) == ZZ(2) + assert ZZ.is_square(ZZ(42)) is False + assert ZZ.exsqrt(ZZ(42)) is None + assert ZZ.is_square(ZZ(0)) is True + assert ZZ.exsqrt(ZZ(0)) == ZZ(0) + assert ZZ.is_square(ZZ(-1)) is False + assert ZZ.exsqrt(ZZ(-1)) is None + + assert QQ.is_square(QQ(9, 4)) is True + assert QQ.exsqrt(QQ(9, 4)) == QQ(3, 2) + assert QQ.is_square(QQ(18, 8)) is True + assert QQ.exsqrt(QQ(18, 8)) == QQ(3, 2) + assert QQ.is_square(QQ(-9, -4)) is True + assert QQ.exsqrt(QQ(-9, -4)) == QQ(3, 2) + assert QQ.is_square(QQ(11, 4)) is False + assert QQ.exsqrt(QQ(11, 4)) is None + assert QQ.is_square(QQ(9, 5)) is False + assert QQ.exsqrt(QQ(9, 5)) is None + assert QQ.is_square(QQ(4)) is True + assert QQ.exsqrt(QQ(4)) == QQ(2) + assert QQ.is_square(QQ(0)) is True + assert QQ.exsqrt(QQ(0)) == QQ(0) + assert QQ.is_square(QQ(-16, 9)) is False + assert QQ.exsqrt(QQ(-16, 9)) is None + + assert RR.is_square(RR(6.25)) is True + assert RR.exsqrt(RR(6.25)) == RR(2.5) + assert RR.is_square(RR(2)) is True + assert RR.almosteq(RR.exsqrt(RR(2)), RR(1.4142135623730951), tolerance=1e-15) + assert RR.is_square(RR(0)) is True + assert RR.exsqrt(RR(0)) == RR(0) + assert RR.is_square(RR(-1)) is False + assert RR.exsqrt(RR(-1)) is None + + assert CC.is_square(CC(2)) is True + assert CC.almosteq(CC.exsqrt(CC(2)), CC(1.4142135623730951), tolerance=1e-15) + assert CC.is_square(CC(0)) is True + assert CC.exsqrt(CC(0)) == CC(0) + assert CC.is_square(CC(-1)) is True + assert CC.exsqrt(CC(-1)) == CC(0, 1) + assert CC.is_square(CC(0, 2)) is True + assert CC.exsqrt(CC(0, 2)) == CC(1, 1) + assert CC.is_square(CC(-3, -4)) is True + assert CC.exsqrt(CC(-3, -4)) == CC(1, -2) + + F2 = FF(2) + assert F2.is_square(F2(1)) is True + assert F2.exsqrt(F2(1)) == F2(1) + assert F2.is_square(F2(0)) is True + assert F2.exsqrt(F2(0)) == F2(0) + + F7 = FF(7) + assert F7.is_square(F7(2)) is True + assert F7.exsqrt(F7(2)) == F7(3) + assert F7.is_square(F7(3)) is False + assert F7.exsqrt(F7(3)) is None + assert F7.is_square(F7(0)) is True + assert F7.exsqrt(F7(0)) == F7(0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_polynomialring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_polynomialring.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb1fdf3f9f9250518289019b0bb108047e8cb6c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_polynomialring.py @@ -0,0 +1,93 @@ +"""Tests for the PolynomialRing classes. """ + +from sympy.polys.domains import QQ, ZZ +from sympy.polys.polyerrors import ExactQuotientFailed, CoercionFailed, NotReversible + +from sympy.abc import x, y + +from sympy.testing.pytest import raises + + +def test_build_order(): + R = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) + assert R.order((1, 5)) == ((1,), (-5,)) + + +def test_globalring(): + Qxy = QQ.old_frac_field(x, y) + R = QQ.old_poly_ring(x, y) + X = R.convert(x) + Y = R.convert(y) + + assert x in R + assert 1/x not in R + assert 1/(1 + x) not in R + assert Y in R + assert X * (Y**2 + 1) == R.convert(x * (y**2 + 1)) + assert X + 1 == R.convert(x + 1) + raises(ExactQuotientFailed, lambda: X/Y) + raises(TypeError, lambda: x/Y) + raises(TypeError, lambda: X/y) + assert X**2 / X == X + + assert R.from_GlobalPolynomialRing(ZZ.old_poly_ring(x, y).convert(x), ZZ.old_poly_ring(x, y)) == X + assert R.from_FractionField(Qxy.convert(x), Qxy) == X + assert R.from_FractionField(Qxy.convert(x/y), Qxy) is None + + assert R._sdm_to_vector(R._vector_to_sdm([X, Y], R.order), 2) == [X, Y] + + +def test_localring(): + Qxy = QQ.old_frac_field(x, y) + R = QQ.old_poly_ring(x, y, order="ilex") + X = R.convert(x) + Y = R.convert(y) + + assert x in R + assert 1/x not in R + assert 1/(1 + x) in R + assert Y in R + assert X*(Y**2 + 1)/(1 + X) == R.convert(x*(y**2 + 1)/(1 + x)) + raises(TypeError, lambda: x/Y) + raises(TypeError, lambda: X/y) + assert X + 1 == R.convert(x + 1) + assert X**2 / X == X + + assert R.from_GlobalPolynomialRing(ZZ.old_poly_ring(x, y).convert(x), ZZ.old_poly_ring(x, y)) == X + assert R.from_FractionField(Qxy.convert(x), Qxy) == X + raises(CoercionFailed, lambda: R.from_FractionField(Qxy.convert(x/y), Qxy)) + raises(ExactQuotientFailed, lambda: R.exquo(X, Y)) + raises(NotReversible, lambda: R.revert(X)) + + assert R._sdm_to_vector( + R._vector_to_sdm([X/(X + 1), Y/(1 + X*Y)], R.order), 2) == \ + [X*(1 + X*Y), Y*(1 + X)] + + +def test_conversion(): + L = QQ.old_poly_ring(x, y, order="ilex") + G = QQ.old_poly_ring(x, y) + + assert L.convert(x) == L.convert(G.convert(x), G) + assert G.convert(x) == G.convert(L.convert(x), L) + raises(CoercionFailed, lambda: G.convert(L.convert(1/(1 + x)), L)) + + +def test_units(): + R = QQ.old_poly_ring(x) + assert R.is_unit(R.convert(1)) + assert R.is_unit(R.convert(2)) + assert not R.is_unit(R.convert(x)) + assert not R.is_unit(R.convert(1 + x)) + + R = QQ.old_poly_ring(x, order='ilex') + assert R.is_unit(R.convert(1)) + assert R.is_unit(R.convert(2)) + assert not R.is_unit(R.convert(x)) + assert R.is_unit(R.convert(1 + x)) + + R = ZZ.old_poly_ring(x) + assert R.is_unit(R.convert(1)) + assert not R.is_unit(R.convert(2)) + assert not R.is_unit(R.convert(x)) + assert not R.is_unit(R.convert(1 + x)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_quotientring.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_quotientring.py new file mode 100644 index 0000000000000000000000000000000000000000..aff167bdd72dc4400785efefef7b3e9057fd0727 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/domains/tests/test_quotientring.py @@ -0,0 +1,52 @@ +"""Tests for quotient rings.""" + +from sympy.polys.domains.integerring import ZZ +from sympy.polys.domains.rationalfield import QQ +from sympy.abc import x, y + +from sympy.polys.polyerrors import NotReversible + +from sympy.testing.pytest import raises + + +def test_QuotientRingElement(): + R = QQ.old_poly_ring(x)/[x**10] + X = R.convert(x) + + assert X*(X + 1) == R.convert(x**2 + x) + assert X*x == R.convert(x**2) + assert x*X == R.convert(x**2) + assert X + x == R.convert(2*x) + assert x + X == 2*X + assert X**2 == R.convert(x**2) + assert 1/(1 - X) == R.convert(sum(x**i for i in range(10))) + assert X**10 == R.zero + assert X != x + + raises(NotReversible, lambda: 1/X) + + +def test_QuotientRing(): + I = QQ.old_poly_ring(x).ideal(x**2 + 1) + R = QQ.old_poly_ring(x)/I + + assert R == QQ.old_poly_ring(x)/[x**2 + 1] + assert R == QQ.old_poly_ring(x)/QQ.old_poly_ring(x).ideal(x**2 + 1) + assert R != QQ.old_poly_ring(x) + + assert R.convert(1)/x == -x + I + assert -1 + I == x**2 + I + assert R.convert(ZZ(1), ZZ) == 1 + I + assert R.convert(R.convert(x), R) == R.convert(x) + + X = R.convert(x) + Y = QQ.old_poly_ring(x).convert(x) + assert -1 + I == X**2 + I + assert -1 + I == Y**2 + I + assert R.to_sympy(X) == x + + raises(ValueError, lambda: QQ.old_poly_ring(x)/QQ.old_poly_ring(x, y).ideal(x)) + + R = QQ.old_poly_ring(x, order="ilex") + I = R.ideal(x) + assert R.convert(1) + I == (R/I).convert(1) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/euclidtools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/euclidtools.py new file mode 100644 index 0000000000000000000000000000000000000000..768a44a94930f05e701e9f27a8b0f570a3312314 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/euclidtools.py @@ -0,0 +1,1912 @@ +"""Euclidean algorithms, GCDs, LCMs and polynomial remainder sequences. """ + + +from sympy.polys.densearith import ( + dup_sub_mul, + dup_neg, dmp_neg, + dmp_add, + dmp_sub, + dup_mul, dmp_mul, + dmp_pow, + dup_div, dmp_div, + dup_rem, + dup_quo, dmp_quo, + dup_prem, dmp_prem, + dup_mul_ground, dmp_mul_ground, + dmp_mul_term, + dup_quo_ground, dmp_quo_ground, + dup_max_norm, dmp_max_norm) +from sympy.polys.densebasic import ( + dup_strip, dmp_raise, + dmp_zero, dmp_one, dmp_ground, + dmp_one_p, dmp_zero_p, + dmp_zeros, + dup_degree, dmp_degree, dmp_degree_in, + dup_LC, dmp_LC, dmp_ground_LC, + dmp_multi_deflate, dmp_inflate, + dup_convert, dmp_convert, + dmp_apply_pairs) +from sympy.polys.densetools import ( + dup_clear_denoms, dmp_clear_denoms, + dup_diff, dmp_diff, + dup_eval, dmp_eval, dmp_eval_in, + dup_trunc, dmp_ground_trunc, + dup_monic, dmp_ground_monic, + dup_primitive, dmp_ground_primitive, + dup_extract, dmp_ground_extract) +from sympy.polys.galoistools import ( + gf_int, gf_crt) +from sympy.polys.polyconfig import query +from sympy.polys.polyerrors import ( + MultivariatePolynomialError, + HeuristicGCDFailed, + HomomorphismFailed, + NotInvertible, + DomainError) + + + + +def dup_half_gcdex(f, g, K): + """ + Half extended Euclidean algorithm in `F[x]`. + + Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 + >>> g = x**3 + x**2 - 4*x - 4 + + >>> R.dup_half_gcdex(f, g) + (-1/5*x + 3/5, x + 1) + + """ + if not K.is_Field: + raise DomainError("Cannot compute half extended GCD over %s" % K) + + a, b = [K.one], [] + + while g: + q, r = dup_div(f, g, K) + f, g = g, r + a, b = b, dup_sub_mul(a, q, b, K) + + a = dup_quo_ground(a, dup_LC(f, K), K) + f = dup_monic(f, K) + + return a, f + + +def dmp_half_gcdex(f, g, u, K): + """ + Half extended Euclidean algorithm in `F[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + """ + if not u: + return dup_half_gcdex(f, g, K) + else: + raise MultivariatePolynomialError(f, g) + + +def dup_gcdex(f, g, K): + """ + Extended Euclidean algorithm in `F[x]`. + + Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 + >>> g = x**3 + x**2 - 4*x - 4 + + >>> R.dup_gcdex(f, g) + (-1/5*x + 3/5, 1/5*x**2 - 6/5*x + 2, x + 1) + + """ + s, h = dup_half_gcdex(f, g, K) + + F = dup_sub_mul(h, s, f, K) + t = dup_quo(F, g, K) + + return s, t, h + + +def dmp_gcdex(f, g, u, K): + """ + Extended Euclidean algorithm in `F[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + """ + if not u: + return dup_gcdex(f, g, K) + else: + raise MultivariatePolynomialError(f, g) + + +def dup_invert(f, g, K): + """ + Compute multiplicative inverse of `f` modulo `g` in `F[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = x**2 - 1 + >>> g = 2*x - 1 + >>> h = x - 1 + + >>> R.dup_invert(f, g) + -4/3 + + >>> R.dup_invert(f, h) + Traceback (most recent call last): + ... + NotInvertible: zero divisor + + """ + s, h = dup_half_gcdex(f, g, K) + + if h == [K.one]: + return dup_rem(s, g, K) + else: + raise NotInvertible("zero divisor") + + +def dmp_invert(f, g, u, K): + """ + Compute multiplicative inverse of `f` modulo `g` in `F[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + """ + if not u: + return dup_invert(f, g, K) + else: + raise MultivariatePolynomialError(f, g) + + +def dup_euclidean_prs(f, g, K): + """ + Euclidean polynomial remainder sequence (PRS) in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 + >>> g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 + + >>> prs = R.dup_euclidean_prs(f, g) + + >>> prs[0] + x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 + >>> prs[1] + 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 + >>> prs[2] + -5/9*x**4 + 1/9*x**2 - 1/3 + >>> prs[3] + -117/25*x**2 - 9*x + 441/25 + >>> prs[4] + 233150/19773*x - 102500/6591 + >>> prs[5] + -1288744821/543589225 + + """ + prs = [f, g] + h = dup_rem(f, g, K) + + while h: + prs.append(h) + f, g = g, h + h = dup_rem(f, g, K) + + return prs + + +def dmp_euclidean_prs(f, g, u, K): + """ + Euclidean polynomial remainder sequence (PRS) in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + """ + if not u: + return dup_euclidean_prs(f, g, K) + else: + raise MultivariatePolynomialError(f, g) + + +def dup_primitive_prs(f, g, K): + """ + Primitive polynomial remainder sequence (PRS) in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 + >>> g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 + + >>> prs = R.dup_primitive_prs(f, g) + + >>> prs[0] + x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 + >>> prs[1] + 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 + >>> prs[2] + -5*x**4 + x**2 - 3 + >>> prs[3] + 13*x**2 + 25*x - 49 + >>> prs[4] + 4663*x - 6150 + >>> prs[5] + 1 + + """ + prs = [f, g] + _, h = dup_primitive(dup_prem(f, g, K), K) + + while h: + prs.append(h) + f, g = g, h + _, h = dup_primitive(dup_prem(f, g, K), K) + + return prs + + +def dmp_primitive_prs(f, g, u, K): + """ + Primitive polynomial remainder sequence (PRS) in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + """ + if not u: + return dup_primitive_prs(f, g, K) + else: + raise MultivariatePolynomialError(f, g) + + +def dup_inner_subresultants(f, g, K): + """ + Subresultant PRS algorithm in `K[x]`. + + Computes the subresultant polynomial remainder sequence (PRS) + and the non-zero scalar subresultants of `f` and `g`. + By [1] Thm. 3, these are the constants '-c' (- to optimize + computation of sign). + The first subdeterminant is set to 1 by convention to match + the polynomial and the scalar subdeterminants. + If 'deg(f) < deg(g)', the subresultants of '(g,f)' are computed. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_inner_subresultants(x**2 + 1, x**2 - 1) + ([x**2 + 1, x**2 - 1, -2], [1, 1, 4]) + + References + ========== + + .. [1] W.S. Brown, The Subresultant PRS Algorithm. + ACM Transaction of Mathematical Software 4 (1978) 237-249 + + """ + n = dup_degree(f) + m = dup_degree(g) + + if n < m: + f, g = g, f + n, m = m, n + + if not f: + return [], [] + + if not g: + return [f], [K.one] + + R = [f, g] + d = n - m + + b = (-K.one)**(d + 1) + + h = dup_prem(f, g, K) + h = dup_mul_ground(h, b, K) + + lc = dup_LC(g, K) + c = lc**d + + # Conventional first scalar subdeterminant is 1 + S = [K.one, c] + c = -c + + while h: + k = dup_degree(h) + R.append(h) + + f, g, m, d = g, h, k, m - k + + b = -lc * c**d + + h = dup_prem(f, g, K) + h = dup_quo_ground(h, b, K) + + lc = dup_LC(g, K) + + if d > 1: # abnormal case + q = c**(d - 1) + c = K.quo((-lc)**d, q) + else: + c = -lc + + S.append(-c) + + return R, S + + +def dup_subresultants(f, g, K): + """ + Computes subresultant PRS of two polynomials in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_subresultants(x**2 + 1, x**2 - 1) + [x**2 + 1, x**2 - 1, -2] + + """ + return dup_inner_subresultants(f, g, K)[0] + + +def dup_prs_resultant(f, g, K): + """ + Resultant algorithm in `K[x]` using subresultant PRS. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_prs_resultant(x**2 + 1, x**2 - 1) + (4, [x**2 + 1, x**2 - 1, -2]) + + """ + if not f or not g: + return (K.zero, []) + + R, S = dup_inner_subresultants(f, g, K) + + if dup_degree(R[-1]) > 0: + return (K.zero, R) + + return S[-1], R + + +def dup_resultant(f, g, K, includePRS=False): + """ + Computes resultant of two polynomials in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_resultant(x**2 + 1, x**2 - 1) + 4 + + """ + if includePRS: + return dup_prs_resultant(f, g, K) + return dup_prs_resultant(f, g, K)[0] + + +def dmp_inner_subresultants(f, g, u, K): + """ + Subresultant PRS algorithm in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 3*x**2*y - y**3 - 4 + >>> g = x**2 + x*y**3 - 9 + + >>> a = 3*x*y**4 + y**3 - 27*y + 4 + >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 + + >>> prs = [f, g, a, b] + >>> sres = [[1], [1], [3, 0, 0, 0, 0], [-3, 0, 0, -12, 1, 0, -54, 8, 729, -216, 16]] + + >>> R.dmp_inner_subresultants(f, g) == (prs, sres) + True + + """ + if not u: + return dup_inner_subresultants(f, g, K) + + n = dmp_degree(f, u) + m = dmp_degree(g, u) + + if n < m: + f, g = g, f + n, m = m, n + + if dmp_zero_p(f, u): + return [], [] + + v = u - 1 + if dmp_zero_p(g, u): + return [f], [dmp_ground(K.one, v)] + + R = [f, g] + d = n - m + + b = dmp_pow(dmp_ground(-K.one, v), d + 1, v, K) + + h = dmp_prem(f, g, u, K) + h = dmp_mul_term(h, b, 0, u, K) + + lc = dmp_LC(g, K) + c = dmp_pow(lc, d, v, K) + + S = [dmp_ground(K.one, v), c] + c = dmp_neg(c, v, K) + + while not dmp_zero_p(h, u): + k = dmp_degree(h, u) + R.append(h) + + f, g, m, d = g, h, k, m - k + + b = dmp_mul(dmp_neg(lc, v, K), + dmp_pow(c, d, v, K), v, K) + + h = dmp_prem(f, g, u, K) + h = [ dmp_quo(ch, b, v, K) for ch in h ] + + lc = dmp_LC(g, K) + + if d > 1: + p = dmp_pow(dmp_neg(lc, v, K), d, v, K) + q = dmp_pow(c, d - 1, v, K) + c = dmp_quo(p, q, v, K) + else: + c = dmp_neg(lc, v, K) + + S.append(dmp_neg(c, v, K)) + + return R, S + + +def dmp_subresultants(f, g, u, K): + """ + Computes subresultant PRS of two polynomials in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 3*x**2*y - y**3 - 4 + >>> g = x**2 + x*y**3 - 9 + + >>> a = 3*x*y**4 + y**3 - 27*y + 4 + >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 + + >>> R.dmp_subresultants(f, g) == [f, g, a, b] + True + + """ + return dmp_inner_subresultants(f, g, u, K)[0] + + +def dmp_prs_resultant(f, g, u, K): + """ + Resultant algorithm in `K[X]` using subresultant PRS. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 3*x**2*y - y**3 - 4 + >>> g = x**2 + x*y**3 - 9 + + >>> a = 3*x*y**4 + y**3 - 27*y + 4 + >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 + + >>> res, prs = R.dmp_prs_resultant(f, g) + + >>> res == b # resultant has n-1 variables + False + >>> res == b.drop(x) + True + >>> prs == [f, g, a, b] + True + + """ + if not u: + return dup_prs_resultant(f, g, K) + + if dmp_zero_p(f, u) or dmp_zero_p(g, u): + return (dmp_zero(u - 1), []) + + R, S = dmp_inner_subresultants(f, g, u, K) + + if dmp_degree(R[-1], u) > 0: + return (dmp_zero(u - 1), R) + + return S[-1], R + + +def dmp_zz_modular_resultant(f, g, p, u, K): + """ + Compute resultant of `f` and `g` modulo a prime `p`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x + y + 2 + >>> g = 2*x*y + x + 3 + + >>> R.dmp_zz_modular_resultant(f, g, 5) + -2*y**2 + 1 + + """ + if not u: + return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) + + v = u - 1 + + n = dmp_degree(f, u) + m = dmp_degree(g, u) + + N = dmp_degree_in(f, 1, u) + M = dmp_degree_in(g, 1, u) + + B = n*M + m*N + + D, a = [K.one], -K.one + r = dmp_zero(v) + + while dup_degree(D) <= B: + while True: + a += K.one + + if a == p: + raise HomomorphismFailed('no luck') + + F = dmp_eval_in(f, gf_int(a, p), 1, u, K) + + if dmp_degree(F, v) == n: + G = dmp_eval_in(g, gf_int(a, p), 1, u, K) + + if dmp_degree(G, v) == m: + break + + R = dmp_zz_modular_resultant(F, G, p, v, K) + e = dmp_eval(r, a, v, K) + + if not v: + R = dup_strip([R]) + e = dup_strip([e]) + else: + R = [R] + e = [e] + + d = K.invert(dup_eval(D, a, K), p) + d = dup_mul_ground(D, d, K) + d = dmp_raise(d, v, 0, K) + + c = dmp_mul(d, dmp_sub(R, e, v, K), v, K) + r = dmp_add(r, c, v, K) + + r = dmp_ground_trunc(r, p, v, K) + + D = dup_mul(D, [K.one, -a], K) + D = dup_trunc(D, p, K) + + return r + + +def _collins_crt(r, R, P, p, K): + """Wrapper of CRT for Collins's resultant algorithm. """ + return gf_int(gf_crt([r, R], [P, p], K), P*p) + + +def dmp_zz_collins_resultant(f, g, u, K): + """ + Collins's modular resultant algorithm in `Z[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x + y + 2 + >>> g = 2*x*y + x + 3 + + >>> R.dmp_zz_collins_resultant(f, g) + -2*y**2 - 5*y + 1 + + """ + + n = dmp_degree(f, u) + m = dmp_degree(g, u) + + if n < 0 or m < 0: + return dmp_zero(u - 1) + + A = dmp_max_norm(f, u, K) + B = dmp_max_norm(g, u, K) + + a = dmp_ground_LC(f, u, K) + b = dmp_ground_LC(g, u, K) + + v = u - 1 + + B = K(2)*K.factorial(K(n + m))*A**m*B**n + r, p, P = dmp_zero(v), K.one, K.one + + from sympy.ntheory import nextprime + + while P <= B: + p = K(nextprime(p)) + + while not (a % p) or not (b % p): + p = K(nextprime(p)) + + F = dmp_ground_trunc(f, p, u, K) + G = dmp_ground_trunc(g, p, u, K) + + try: + R = dmp_zz_modular_resultant(F, G, p, u, K) + except HomomorphismFailed: + continue + + if K.is_one(P): + r = R + else: + r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K) + + P *= p + + return r + + +def dmp_qq_collins_resultant(f, g, u, K0): + """ + Collins's modular resultant algorithm in `Q[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y = ring("x,y", QQ) + + >>> f = QQ(1,2)*x + y + QQ(2,3) + >>> g = 2*x*y + x + 3 + + >>> R.dmp_qq_collins_resultant(f, g) + -2*y**2 - 7/3*y + 5/6 + + """ + n = dmp_degree(f, u) + m = dmp_degree(g, u) + + if n < 0 or m < 0: + return dmp_zero(u - 1) + + K1 = K0.get_ring() + + cf, f = dmp_clear_denoms(f, u, K0, K1) + cg, g = dmp_clear_denoms(g, u, K0, K1) + + f = dmp_convert(f, u, K0, K1) + g = dmp_convert(g, u, K0, K1) + + r = dmp_zz_collins_resultant(f, g, u, K1) + r = dmp_convert(r, u - 1, K1, K0) + + c = K0.convert(cf**m * cg**n, K1) + + return dmp_quo_ground(r, c, u - 1, K0) + + +def dmp_resultant(f, g, u, K, includePRS=False): + """ + Computes resultant of two polynomials in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = 3*x**2*y - y**3 - 4 + >>> g = x**2 + x*y**3 - 9 + + >>> R.dmp_resultant(f, g) + -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16 + + """ + if not u: + return dup_resultant(f, g, K, includePRS=includePRS) + + if includePRS: + return dmp_prs_resultant(f, g, u, K) + + if K.is_Field: + if K.is_QQ and query('USE_COLLINS_RESULTANT'): + return dmp_qq_collins_resultant(f, g, u, K) + else: + if K.is_ZZ and query('USE_COLLINS_RESULTANT'): + return dmp_zz_collins_resultant(f, g, u, K) + + return dmp_prs_resultant(f, g, u, K)[0] + + +def dup_discriminant(f, K): + """ + Computes discriminant of a polynomial in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_discriminant(x**2 + 2*x + 3) + -8 + + """ + d = dup_degree(f) + + if d <= 0: + return K.zero + else: + s = (-1)**((d*(d - 1)) // 2) + c = dup_LC(f, K) + + r = dup_resultant(f, dup_diff(f, 1, K), K) + + return K.quo(r, c*K(s)) + + +def dmp_discriminant(f, u, K): + """ + Computes discriminant of a polynomial in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y,z,t = ring("x,y,z,t", ZZ) + + >>> R.dmp_discriminant(x**2*y + x*z + t) + -4*y*t + z**2 + + """ + if not u: + return dup_discriminant(f, K) + + d, v = dmp_degree(f, u), u - 1 + + if d <= 0: + return dmp_zero(v) + else: + s = (-1)**((d*(d - 1)) // 2) + c = dmp_LC(f, K) + + r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) + c = dmp_mul_ground(c, K(s), v, K) + + return dmp_quo(r, c, v, K) + + +def _dup_rr_trivial_gcd(f, g, K): + """Handle trivial cases in GCD algorithm over a ring. """ + if not (f or g): + return [], [], [] + elif not f: + if K.is_nonnegative(dup_LC(g, K)): + return g, [], [K.one] + else: + return dup_neg(g, K), [], [-K.one] + elif not g: + if K.is_nonnegative(dup_LC(f, K)): + return f, [K.one], [] + else: + return dup_neg(f, K), [-K.one], [] + + return None + + +def _dup_ff_trivial_gcd(f, g, K): + """Handle trivial cases in GCD algorithm over a field. """ + if not (f or g): + return [], [], [] + elif not f: + return dup_monic(g, K), [], [dup_LC(g, K)] + elif not g: + return dup_monic(f, K), [dup_LC(f, K)], [] + else: + return None + + +def _dmp_rr_trivial_gcd(f, g, u, K): + """Handle trivial cases in GCD algorithm over a ring. """ + zero_f = dmp_zero_p(f, u) + zero_g = dmp_zero_p(g, u) + if_contain_one = dmp_one_p(f, u, K) or dmp_one_p(g, u, K) + + if zero_f and zero_g: + return tuple(dmp_zeros(3, u, K)) + elif zero_f: + if K.is_nonnegative(dmp_ground_LC(g, u, K)): + return g, dmp_zero(u), dmp_one(u, K) + else: + return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) + elif zero_g: + if K.is_nonnegative(dmp_ground_LC(f, u, K)): + return f, dmp_one(u, K), dmp_zero(u) + else: + return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) + elif if_contain_one: + return dmp_one(u, K), f, g + elif query('USE_SIMPLIFY_GCD'): + return _dmp_simplify_gcd(f, g, u, K) + else: + return None + + +def _dmp_ff_trivial_gcd(f, g, u, K): + """Handle trivial cases in GCD algorithm over a field. """ + zero_f = dmp_zero_p(f, u) + zero_g = dmp_zero_p(g, u) + + if zero_f and zero_g: + return tuple(dmp_zeros(3, u, K)) + elif zero_f: + return (dmp_ground_monic(g, u, K), + dmp_zero(u), + dmp_ground(dmp_ground_LC(g, u, K), u)) + elif zero_g: + return (dmp_ground_monic(f, u, K), + dmp_ground(dmp_ground_LC(f, u, K), u), + dmp_zero(u)) + elif query('USE_SIMPLIFY_GCD'): + return _dmp_simplify_gcd(f, g, u, K) + else: + return None + + +def _dmp_simplify_gcd(f, g, u, K): + """Try to eliminate `x_0` from GCD computation in `K[X]`. """ + df = dmp_degree(f, u) + dg = dmp_degree(g, u) + + if df > 0 and dg > 0: + return None + + if not (df or dg): + F = dmp_LC(f, K) + G = dmp_LC(g, K) + else: + if not df: + F = dmp_LC(f, K) + G = dmp_content(g, u, K) + else: + F = dmp_content(f, u, K) + G = dmp_LC(g, K) + + v = u - 1 + h = dmp_gcd(F, G, v, K) + + cff = [ dmp_quo(cf, h, v, K) for cf in f ] + cfg = [ dmp_quo(cg, h, v, K) for cg in g ] + + return [h], cff, cfg + + +def dup_rr_prs_gcd(f, g, K): + """ + Computes polynomial GCD using subresultants over a ring. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, + and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_rr_prs_gcd(x**2 - 1, x**2 - 3*x + 2) + (x - 1, x + 1, x - 2) + + """ + result = _dup_rr_trivial_gcd(f, g, K) + + if result is not None: + return result + + fc, F = dup_primitive(f, K) + gc, G = dup_primitive(g, K) + + c = K.gcd(fc, gc) + + h = dup_subresultants(F, G, K)[-1] + _, h = dup_primitive(h, K) + + c *= K.canonical_unit(dup_LC(h, K)) + + h = dup_mul_ground(h, c, K) + + cff = dup_quo(f, h, K) + cfg = dup_quo(g, h, K) + + return h, cff, cfg + + +def dup_ff_prs_gcd(f, g, K): + """ + Computes polynomial GCD using subresultants over a field. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, + and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> R.dup_ff_prs_gcd(x**2 - 1, x**2 - 3*x + 2) + (x - 1, x + 1, x - 2) + + """ + result = _dup_ff_trivial_gcd(f, g, K) + + if result is not None: + return result + + h = dup_subresultants(f, g, K)[-1] + h = dup_monic(h, K) + + cff = dup_quo(f, h, K) + cfg = dup_quo(g, h, K) + + return h, cff, cfg + + +def dmp_rr_prs_gcd(f, g, u, K): + """ + Computes polynomial GCD using subresultants over a ring. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, + and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> f = x**2 + 2*x*y + y**2 + >>> g = x**2 + x*y + + >>> R.dmp_rr_prs_gcd(f, g) + (x + y, x + y, x) + + """ + if not u: + return dup_rr_prs_gcd(f, g, K) + + result = _dmp_rr_trivial_gcd(f, g, u, K) + + if result is not None: + return result + + fc, F = dmp_primitive(f, u, K) + gc, G = dmp_primitive(g, u, K) + + h = dmp_subresultants(F, G, u, K)[-1] + c, _, _ = dmp_rr_prs_gcd(fc, gc, u - 1, K) + + _, h = dmp_primitive(h, u, K) + h = dmp_mul_term(h, c, 0, u, K) + + unit = K.canonical_unit(dmp_ground_LC(h, u, K)) + + if unit != K.one: + h = dmp_mul_ground(h, unit, u, K) + + cff = dmp_quo(f, h, u, K) + cfg = dmp_quo(g, h, u, K) + + return h, cff, cfg + + +def dmp_ff_prs_gcd(f, g, u, K): + """ + Computes polynomial GCD using subresultants over a field. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``, + and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y, = ring("x,y", QQ) + + >>> f = QQ(1,2)*x**2 + x*y + QQ(1,2)*y**2 + >>> g = x**2 + x*y + + >>> R.dmp_ff_prs_gcd(f, g) + (x + y, 1/2*x + 1/2*y, x) + + """ + if not u: + return dup_ff_prs_gcd(f, g, K) + + result = _dmp_ff_trivial_gcd(f, g, u, K) + + if result is not None: + return result + + fc, F = dmp_primitive(f, u, K) + gc, G = dmp_primitive(g, u, K) + + h = dmp_subresultants(F, G, u, K)[-1] + c, _, _ = dmp_ff_prs_gcd(fc, gc, u - 1, K) + + _, h = dmp_primitive(h, u, K) + h = dmp_mul_term(h, c, 0, u, K) + h = dmp_ground_monic(h, u, K) + + cff = dmp_quo(f, h, u, K) + cfg = dmp_quo(g, h, u, K) + + return h, cff, cfg + +HEU_GCD_MAX = 6 + + +def _dup_zz_gcd_interpolate(h, x, K): + """Interpolate polynomial GCD from integer GCD. """ + f = [] + + while h: + g = h % x + + if g > x // 2: + g -= x + + f.insert(0, g) + h = (h - g) // x + + return f + + +def dup_zz_heu_gcd(f, g, K): + """ + Heuristic polynomial GCD in `Z[x]`. + + Given univariate polynomials `f` and `g` in `Z[x]`, returns + their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg`` + such that:: + + h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) + + The algorithm is purely heuristic which means it may fail to compute + the GCD. This will be signaled by raising an exception. In this case + you will need to switch to another GCD method. + + The algorithm computes the polynomial GCD by evaluating polynomials + f and g at certain points and computing (fast) integer GCD of those + evaluations. The polynomial GCD is recovered from the integer image + by interpolation. The final step is to verify if the result is the + correct GCD. This gives cofactors as a side effect. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_zz_heu_gcd(x**2 - 1, x**2 - 3*x + 2) + (x - 1, x + 1, x - 2) + + References + ========== + + .. [1] [Liao95]_ + + """ + result = _dup_rr_trivial_gcd(f, g, K) + + if result is not None: + return result + + df = dup_degree(f) + dg = dup_degree(g) + + gcd, f, g = dup_extract(f, g, K) + + if df == 0 or dg == 0: + return [gcd], f, g + + f_norm = dup_max_norm(f, K) + g_norm = dup_max_norm(g, K) + + B = K(2*min(f_norm, g_norm) + 29) + + x = max(min(B, 99*K.sqrt(B)), + 2*min(f_norm // abs(dup_LC(f, K)), + g_norm // abs(dup_LC(g, K))) + 4) + + for i in range(0, HEU_GCD_MAX): + ff = dup_eval(f, x, K) + gg = dup_eval(g, x, K) + + if ff and gg: + h = K.gcd(ff, gg) + + cff = ff // h + cfg = gg // h + + h = _dup_zz_gcd_interpolate(h, x, K) + h = dup_primitive(h, K)[1] + + cff_, r = dup_div(f, h, K) + + if not r: + cfg_, r = dup_div(g, h, K) + + if not r: + h = dup_mul_ground(h, gcd, K) + return h, cff_, cfg_ + + cff = _dup_zz_gcd_interpolate(cff, x, K) + + h, r = dup_div(f, cff, K) + + if not r: + cfg_, r = dup_div(g, h, K) + + if not r: + h = dup_mul_ground(h, gcd, K) + return h, cff, cfg_ + + cfg = _dup_zz_gcd_interpolate(cfg, x, K) + + h, r = dup_div(g, cfg, K) + + if not r: + cff_, r = dup_div(f, h, K) + + if not r: + h = dup_mul_ground(h, gcd, K) + return h, cff_, cfg + + x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 + + raise HeuristicGCDFailed('no luck') + + +def _dmp_zz_gcd_interpolate(h, x, v, K): + """Interpolate polynomial GCD from integer GCD. """ + f = [] + + while not dmp_zero_p(h, v): + g = dmp_ground_trunc(h, x, v, K) + f.insert(0, g) + + h = dmp_sub(h, g, v, K) + h = dmp_quo_ground(h, x, v, K) + + if K.is_negative(dmp_ground_LC(f, v + 1, K)): + return dmp_neg(f, v + 1, K) + else: + return f + + +def dmp_zz_heu_gcd(f, g, u, K): + """ + Heuristic polynomial GCD in `Z[X]`. + + Given univariate polynomials `f` and `g` in `Z[X]`, returns + their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg`` + such that:: + + h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) + + The algorithm is purely heuristic which means it may fail to compute + the GCD. This will be signaled by raising an exception. In this case + you will need to switch to another GCD method. + + The algorithm computes the polynomial GCD by evaluating polynomials + f and g at certain points and computing (fast) integer GCD of those + evaluations. The polynomial GCD is recovered from the integer image + by interpolation. The evaluation process reduces f and g variable by + variable into a large integer. The final step is to verify if the + interpolated polynomial is the correct GCD. This gives cofactors of + the input polynomials as a side effect. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> f = x**2 + 2*x*y + y**2 + >>> g = x**2 + x*y + + >>> R.dmp_zz_heu_gcd(f, g) + (x + y, x + y, x) + + References + ========== + + .. [1] [Liao95]_ + + """ + if not u: + return dup_zz_heu_gcd(f, g, K) + + result = _dmp_rr_trivial_gcd(f, g, u, K) + + if result is not None: + return result + + gcd, f, g = dmp_ground_extract(f, g, u, K) + + f_norm = dmp_max_norm(f, u, K) + g_norm = dmp_max_norm(g, u, K) + + B = K(2*min(f_norm, g_norm) + 29) + + x = max(min(B, 99*K.sqrt(B)), + 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), + g_norm // abs(dmp_ground_LC(g, u, K))) + 4) + + for i in range(0, HEU_GCD_MAX): + ff = dmp_eval(f, x, u, K) + gg = dmp_eval(g, x, u, K) + + v = u - 1 + + if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): + h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) + + h = _dmp_zz_gcd_interpolate(h, x, v, K) + h = dmp_ground_primitive(h, u, K)[1] + + cff_, r = dmp_div(f, h, u, K) + + if dmp_zero_p(r, u): + cfg_, r = dmp_div(g, h, u, K) + + if dmp_zero_p(r, u): + h = dmp_mul_ground(h, gcd, u, K) + return h, cff_, cfg_ + + cff = _dmp_zz_gcd_interpolate(cff, x, v, K) + + h, r = dmp_div(f, cff, u, K) + + if dmp_zero_p(r, u): + cfg_, r = dmp_div(g, h, u, K) + + if dmp_zero_p(r, u): + h = dmp_mul_ground(h, gcd, u, K) + return h, cff, cfg_ + + cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) + + h, r = dmp_div(g, cfg, u, K) + + if dmp_zero_p(r, u): + cff_, r = dmp_div(f, h, u, K) + + if dmp_zero_p(r, u): + h = dmp_mul_ground(h, gcd, u, K) + return h, cff_, cfg + + x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 + + raise HeuristicGCDFailed('no luck') + + +def dup_qq_heu_gcd(f, g, K0): + """ + Heuristic polynomial GCD in `Q[x]`. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, + ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = QQ(1,2)*x**2 + QQ(7,4)*x + QQ(3,2) + >>> g = QQ(1,2)*x**2 + x + + >>> R.dup_qq_heu_gcd(f, g) + (x + 2, 1/2*x + 3/4, 1/2*x) + + """ + result = _dup_ff_trivial_gcd(f, g, K0) + + if result is not None: + return result + + K1 = K0.get_ring() + + cf, f = dup_clear_denoms(f, K0, K1) + cg, g = dup_clear_denoms(g, K0, K1) + + f = dup_convert(f, K0, K1) + g = dup_convert(g, K0, K1) + + h, cff, cfg = dup_zz_heu_gcd(f, g, K1) + + h = dup_convert(h, K1, K0) + + c = dup_LC(h, K0) + h = dup_monic(h, K0) + + cff = dup_convert(cff, K1, K0) + cfg = dup_convert(cfg, K1, K0) + + cff = dup_mul_ground(cff, K0.quo(c, cf), K0) + cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) + + return h, cff, cfg + + +def dmp_qq_heu_gcd(f, g, u, K0): + """ + Heuristic polynomial GCD in `Q[X]`. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, + ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y, = ring("x,y", QQ) + + >>> f = QQ(1,4)*x**2 + x*y + y**2 + >>> g = QQ(1,2)*x**2 + x*y + + >>> R.dmp_qq_heu_gcd(f, g) + (x + 2*y, 1/4*x + 1/2*y, 1/2*x) + + """ + result = _dmp_ff_trivial_gcd(f, g, u, K0) + + if result is not None: + return result + + K1 = K0.get_ring() + + cf, f = dmp_clear_denoms(f, u, K0, K1) + cg, g = dmp_clear_denoms(g, u, K0, K1) + + f = dmp_convert(f, u, K0, K1) + g = dmp_convert(g, u, K0, K1) + + h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) + + h = dmp_convert(h, u, K1, K0) + + c = dmp_ground_LC(h, u, K0) + h = dmp_ground_monic(h, u, K0) + + cff = dmp_convert(cff, u, K1, K0) + cfg = dmp_convert(cfg, u, K1, K0) + + cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) + cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) + + return h, cff, cfg + + +def dup_inner_gcd(f, g, K): + """ + Computes polynomial GCD and cofactors of `f` and `g` in `K[x]`. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, + ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_inner_gcd(x**2 - 1, x**2 - 3*x + 2) + (x - 1, x + 1, x - 2) + + """ + # XXX: This used to check for K.is_Exact but leads to awkward results when + # the domain is something like RR[z] e.g.: + # + # >>> g, p, q = Poly(1, x).cancel(Poly(51.05*x*y - 1.0, x)) + # >>> g + # 1.0 + # >>> p + # Poly(17592186044421.0, x, domain='RR[y]') + # >>> q + # Poly(898081097567692.0*y*x - 17592186044421.0, x, domain='RR[y]')) + # + # Maybe it would be better to flatten into multivariate polynomials first. + if K.is_RR or K.is_CC: + try: + exact = K.get_exact() + except DomainError: + return [K.one], f, g + + f = dup_convert(f, K, exact) + g = dup_convert(g, K, exact) + + h, cff, cfg = dup_inner_gcd(f, g, exact) + + h = dup_convert(h, exact, K) + cff = dup_convert(cff, exact, K) + cfg = dup_convert(cfg, exact, K) + + return h, cff, cfg + elif K.is_Field: + if K.is_QQ and query('USE_HEU_GCD'): + try: + return dup_qq_heu_gcd(f, g, K) + except HeuristicGCDFailed: + pass + + return dup_ff_prs_gcd(f, g, K) + else: + if K.is_ZZ and query('USE_HEU_GCD'): + try: + return dup_zz_heu_gcd(f, g, K) + except HeuristicGCDFailed: + pass + + return dup_rr_prs_gcd(f, g, K) + + +def _dmp_inner_gcd(f, g, u, K): + """Helper function for `dmp_inner_gcd()`. """ + if not K.is_Exact: + try: + exact = K.get_exact() + except DomainError: + return dmp_one(u, K), f, g + + f = dmp_convert(f, u, K, exact) + g = dmp_convert(g, u, K, exact) + + h, cff, cfg = _dmp_inner_gcd(f, g, u, exact) + + h = dmp_convert(h, u, exact, K) + cff = dmp_convert(cff, u, exact, K) + cfg = dmp_convert(cfg, u, exact, K) + + return h, cff, cfg + elif K.is_Field: + if K.is_QQ and query('USE_HEU_GCD'): + try: + return dmp_qq_heu_gcd(f, g, u, K) + except HeuristicGCDFailed: + pass + + return dmp_ff_prs_gcd(f, g, u, K) + else: + if K.is_ZZ and query('USE_HEU_GCD'): + try: + return dmp_zz_heu_gcd(f, g, u, K) + except HeuristicGCDFailed: + pass + + return dmp_rr_prs_gcd(f, g, u, K) + + +def dmp_inner_gcd(f, g, u, K): + """ + Computes polynomial GCD and cofactors of `f` and `g` in `K[X]`. + + Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, + ``cff = quo(f, h)``, and ``cfg = quo(g, h)``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> f = x**2 + 2*x*y + y**2 + >>> g = x**2 + x*y + + >>> R.dmp_inner_gcd(f, g) + (x + y, x + y, x) + + """ + if not u: + return dup_inner_gcd(f, g, K) + + J, (f, g) = dmp_multi_deflate((f, g), u, K) + h, cff, cfg = _dmp_inner_gcd(f, g, u, K) + + return (dmp_inflate(h, J, u, K), + dmp_inflate(cff, J, u, K), + dmp_inflate(cfg, J, u, K)) + + +def dup_gcd(f, g, K): + """ + Computes polynomial GCD of `f` and `g` in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_gcd(x**2 - 1, x**2 - 3*x + 2) + x - 1 + + """ + return dup_inner_gcd(f, g, K)[0] + + +def dmp_gcd(f, g, u, K): + """ + Computes polynomial GCD of `f` and `g` in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> f = x**2 + 2*x*y + y**2 + >>> g = x**2 + x*y + + >>> R.dmp_gcd(f, g) + x + y + + """ + return dmp_inner_gcd(f, g, u, K)[0] + + +def dup_rr_lcm(f, g, K): + """ + Computes polynomial LCM over a ring in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_rr_lcm(x**2 - 1, x**2 - 3*x + 2) + x**3 - 2*x**2 - x + 2 + + """ + if not f or not g: + return dmp_zero(0) + + fc, f = dup_primitive(f, K) + gc, g = dup_primitive(g, K) + + c = K.lcm(fc, gc) + + h = dup_quo(dup_mul(f, g, K), + dup_gcd(f, g, K), K) + + u = K.canonical_unit(dup_LC(h, K)) + + return dup_mul_ground(h, c*u, K) + + +def dup_ff_lcm(f, g, K): + """ + Computes polynomial LCM over a field in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> f = QQ(1,2)*x**2 + QQ(7,4)*x + QQ(3,2) + >>> g = QQ(1,2)*x**2 + x + + >>> R.dup_ff_lcm(f, g) + x**3 + 7/2*x**2 + 3*x + + """ + h = dup_quo(dup_mul(f, g, K), + dup_gcd(f, g, K), K) + + return dup_monic(h, K) + + +def dup_lcm(f, g, K): + """ + Computes polynomial LCM of `f` and `g` in `K[x]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_lcm(x**2 - 1, x**2 - 3*x + 2) + x**3 - 2*x**2 - x + 2 + + """ + if K.is_Field: + return dup_ff_lcm(f, g, K) + else: + return dup_rr_lcm(f, g, K) + + +def dmp_rr_lcm(f, g, u, K): + """ + Computes polynomial LCM over a ring in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> f = x**2 + 2*x*y + y**2 + >>> g = x**2 + x*y + + >>> R.dmp_rr_lcm(f, g) + x**3 + 2*x**2*y + x*y**2 + + """ + fc, f = dmp_ground_primitive(f, u, K) + gc, g = dmp_ground_primitive(g, u, K) + + c = K.lcm(fc, gc) + + h = dmp_quo(dmp_mul(f, g, u, K), + dmp_gcd(f, g, u, K), u, K) + + return dmp_mul_ground(h, c, u, K) + + +def dmp_ff_lcm(f, g, u, K): + """ + Computes polynomial LCM over a field in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x,y, = ring("x,y", QQ) + + >>> f = QQ(1,4)*x**2 + x*y + y**2 + >>> g = QQ(1,2)*x**2 + x*y + + >>> R.dmp_ff_lcm(f, g) + x**3 + 4*x**2*y + 4*x*y**2 + + """ + h = dmp_quo(dmp_mul(f, g, u, K), + dmp_gcd(f, g, u, K), u, K) + + return dmp_ground_monic(h, u, K) + + +def dmp_lcm(f, g, u, K): + """ + Computes polynomial LCM of `f` and `g` in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> f = x**2 + 2*x*y + y**2 + >>> g = x**2 + x*y + + >>> R.dmp_lcm(f, g) + x**3 + 2*x**2*y + x*y**2 + + """ + if not u: + return dup_lcm(f, g, K) + + if K.is_Field: + return dmp_ff_lcm(f, g, u, K) + else: + return dmp_rr_lcm(f, g, u, K) + + +def dmp_content(f, u, K): + """ + Returns GCD of multivariate coefficients. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> R.dmp_content(2*x*y + 6*x + 4*y + 12) + 2*y + 6 + + """ + cont, v = dmp_LC(f, K), u - 1 + + if dmp_zero_p(f, u): + return cont + + for c in f[1:]: + cont = dmp_gcd(cont, c, v, K) + + if dmp_one_p(cont, v, K): + break + + if K.is_negative(dmp_ground_LC(cont, v, K)): + return dmp_neg(cont, v, K) + else: + return cont + + +def dmp_primitive(f, u, K): + """ + Returns multivariate content and a primitive polynomial. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y, = ring("x,y", ZZ) + + >>> R.dmp_primitive(2*x*y + 6*x + 4*y + 12) + (2*y + 6, x + 2) + + """ + cont, v = dmp_content(f, u, K), u - 1 + + if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): + return cont, f + else: + return cont, [ dmp_quo(c, cont, v, K) for c in f ] + + +def dup_cancel(f, g, K, include=True): + """ + Cancel common factors in a rational function `f/g`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_cancel(2*x**2 - 2, x**2 - 2*x + 1) + (2*x + 2, x - 1) + + """ + return dmp_cancel(f, g, 0, K, include=include) + + +def dmp_cancel(f, g, u, K, include=True): + """ + Cancel common factors in a rational function `f/g`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_cancel(2*x**2 - 2, x**2 - 2*x + 1) + (2*x + 2, x - 1) + + """ + K0 = None + + if K.is_Field and K.has_assoc_Ring: + K0, K = K, K.get_ring() + + cq, f = dmp_clear_denoms(f, u, K0, K, convert=True) + cp, g = dmp_clear_denoms(g, u, K0, K, convert=True) + else: + cp, cq = K.one, K.one + + _, p, q = dmp_inner_gcd(f, g, u, K) + + if K0 is not None: + _, cp, cq = K.cofactors(cp, cq) + + p = dmp_convert(p, u, K, K0) + q = dmp_convert(q, u, K, K0) + + K = K0 + + p_neg = K.is_negative(dmp_ground_LC(p, u, K)) + q_neg = K.is_negative(dmp_ground_LC(q, u, K)) + + if p_neg and q_neg: + p, q = dmp_neg(p, u, K), dmp_neg(q, u, K) + elif p_neg: + cp, p = -cp, dmp_neg(p, u, K) + elif q_neg: + cp, q = -cp, dmp_neg(q, u, K) + + if not include: + return cp, cq, p, q + + p = dmp_mul_ground(p, cp, u, K) + q = dmp_mul_ground(q, cq, u, K) + + return p, q diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/factortools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/factortools.py new file mode 100644 index 0000000000000000000000000000000000000000..021a6b06cb8802748deef6c69448ebc50503269b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/factortools.py @@ -0,0 +1,1648 @@ +"""Polynomial factorization routines in characteristic zero. """ + +from sympy.external.gmpy import GROUND_TYPES + +from sympy.core.random import _randint + +from sympy.polys.galoistools import ( + gf_from_int_poly, gf_to_int_poly, + gf_lshift, gf_add_mul, gf_mul, + gf_div, gf_rem, + gf_gcdex, + gf_sqf_p, + gf_factor_sqf, gf_factor) + +from sympy.polys.densebasic import ( + dup_LC, dmp_LC, dmp_ground_LC, + dup_TC, + dup_convert, dmp_convert, + dup_degree, dmp_degree, + dmp_degree_in, dmp_degree_list, + dmp_from_dict, + dmp_zero_p, + dmp_one, + dmp_nest, dmp_raise, + dup_strip, + dmp_ground, + dup_inflate, + dmp_exclude, dmp_include, + dmp_inject, dmp_eject, + dup_terms_gcd, dmp_terms_gcd) + +from sympy.polys.densearith import ( + dup_neg, dmp_neg, + dup_add, dmp_add, + dup_sub, dmp_sub, + dup_mul, dmp_mul, + dup_sqr, + dmp_pow, + dup_div, dmp_div, + dup_quo, dmp_quo, + dmp_expand, + dmp_add_mul, + dup_sub_mul, dmp_sub_mul, + dup_lshift, + dup_max_norm, dmp_max_norm, + dup_l1_norm, + dup_mul_ground, dmp_mul_ground, + dup_quo_ground, dmp_quo_ground) + +from sympy.polys.densetools import ( + dup_clear_denoms, dmp_clear_denoms, + dup_trunc, dmp_ground_trunc, + dup_content, + dup_monic, dmp_ground_monic, + dup_primitive, dmp_ground_primitive, + dmp_eval_tail, + dmp_eval_in, dmp_diff_eval_in, + dup_shift, dmp_shift, dup_mirror) + +from sympy.polys.euclidtools import ( + dmp_primitive, + dup_inner_gcd, dmp_inner_gcd) + +from sympy.polys.sqfreetools import ( + dup_sqf_p, + dup_sqf_norm, dmp_sqf_norm, + dup_sqf_part, dmp_sqf_part, + _dup_check_degrees, _dmp_check_degrees, + ) + +from sympy.polys.polyutils import _sort_factors +from sympy.polys.polyconfig import query + +from sympy.polys.polyerrors import ( + ExtraneousFactors, DomainError, CoercionFailed, EvaluationFailed) + +from sympy.utilities import subsets + +from math import ceil as _ceil, log as _log, log2 as _log2 + + +if GROUND_TYPES == 'flint': + from flint import fmpz_poly +else: + fmpz_poly = None + + +def dup_trial_division(f, factors, K): + """ + Determine multiplicities of factors for a univariate polynomial + using trial division. + + An error will be raised if any factor does not divide ``f``. + """ + result = [] + + for factor in factors: + k = 0 + + while True: + q, r = dup_div(f, factor, K) + + if not r: + f, k = q, k + 1 + else: + break + + if k == 0: + raise RuntimeError("trial division failed") + + result.append((factor, k)) + + return _sort_factors(result) + + +def dmp_trial_division(f, factors, u, K): + """ + Determine multiplicities of factors for a multivariate polynomial + using trial division. + + An error will be raised if any factor does not divide ``f``. + """ + result = [] + + for factor in factors: + k = 0 + + while True: + q, r = dmp_div(f, factor, u, K) + + if dmp_zero_p(r, u): + f, k = q, k + 1 + else: + break + + if k == 0: + raise RuntimeError("trial division failed") + + result.append((factor, k)) + + return _sort_factors(result) + + +def dup_zz_mignotte_bound(f, K): + """ + The Knuth-Cohen variant of Mignotte bound for + univariate polynomials in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> f = x**3 + 14*x**2 + 56*x + 64 + >>> R.dup_zz_mignotte_bound(f) + 152 + + By checking ``factor(f)`` we can see that max coeff is 8 + + Also consider a case that ``f`` is irreducible for example + ``f = 2*x**2 + 3*x + 4``. To avoid a bug for these cases, we return the + bound plus the max coefficient of ``f`` + + >>> f = 2*x**2 + 3*x + 4 + >>> R.dup_zz_mignotte_bound(f) + 6 + + Lastly, to see the difference between the new and the old Mignotte bound + consider the irreducible polynomial: + + >>> f = 87*x**7 + 4*x**6 + 80*x**5 + 17*x**4 + 9*x**3 + 12*x**2 + 49*x + 26 + >>> R.dup_zz_mignotte_bound(f) + 744 + + The new Mignotte bound is 744 whereas the old one (SymPy 1.5.1) is 1937664. + + + References + ========== + + ..[1] [Abbott13]_ + + """ + from sympy.functions.combinatorial.factorials import binomial + d = dup_degree(f) + delta = _ceil(d / 2) + delta2 = _ceil(delta / 2) + + # euclidean-norm + eucl_norm = K.sqrt( sum( cf**2 for cf in f ) ) + + # biggest values of binomial coefficients (p. 538 of reference) + t1 = binomial(delta - 1, delta2) + t2 = binomial(delta - 1, delta2 - 1) + + lc = K.abs(dup_LC(f, K)) # leading coefficient + bound = t1 * eucl_norm + t2 * lc # (p. 538 of reference) + bound += dup_max_norm(f, K) # add max coeff for irreducible polys + bound = _ceil(bound / 2) * 2 # round up to even integer + + return bound + +def dmp_zz_mignotte_bound(f, u, K): + """Mignotte bound for multivariate polynomials in `K[X]`. """ + a = dmp_max_norm(f, u, K) + b = abs(dmp_ground_LC(f, u, K)) + n = sum(dmp_degree_list(f, u)) + + return K.sqrt(K(n + 1))*2**n*a*b + + +def dup_zz_hensel_step(m, f, g, h, s, t, K): + """ + One step in Hensel lifting in `Z[x]`. + + Given positive integer `m` and `Z[x]` polynomials `f`, `g`, `h`, `s` + and `t` such that:: + + f = g*h (mod m) + s*g + t*h = 1 (mod m) + + lc(f) is not a zero divisor (mod m) + lc(h) = 1 + + deg(f) = deg(g) + deg(h) + deg(s) < deg(h) + deg(t) < deg(g) + + returns polynomials `G`, `H`, `S` and `T`, such that:: + + f = G*H (mod m**2) + S*G + T*H = 1 (mod m**2) + + References + ========== + + .. [1] [Gathen99]_ + + """ + M = m**2 + + e = dup_sub_mul(f, g, h, K) + e = dup_trunc(e, M, K) + + q, r = dup_div(dup_mul(s, e, K), h, K) + + q = dup_trunc(q, M, K) + r = dup_trunc(r, M, K) + + u = dup_add(dup_mul(t, e, K), dup_mul(q, g, K), K) + G = dup_trunc(dup_add(g, u, K), M, K) + H = dup_trunc(dup_add(h, r, K), M, K) + + u = dup_add(dup_mul(s, G, K), dup_mul(t, H, K), K) + b = dup_trunc(dup_sub(u, [K.one], K), M, K) + + c, d = dup_div(dup_mul(s, b, K), H, K) + + c = dup_trunc(c, M, K) + d = dup_trunc(d, M, K) + + u = dup_add(dup_mul(t, b, K), dup_mul(c, G, K), K) + S = dup_trunc(dup_sub(s, d, K), M, K) + T = dup_trunc(dup_sub(t, u, K), M, K) + + return G, H, S, T + + +def dup_zz_hensel_lift(p, f, f_list, l, K): + r""" + Multifactor Hensel lifting in `Z[x]`. + + Given a prime `p`, polynomial `f` over `Z[x]` such that `lc(f)` + is a unit modulo `p`, monic pair-wise coprime polynomials `f_i` + over `Z[x]` satisfying:: + + f = lc(f) f_1 ... f_r (mod p) + + and a positive integer `l`, returns a list of monic polynomials + `F_1,\ F_2,\ \dots,\ F_r` satisfying:: + + f = lc(f) F_1 ... F_r (mod p**l) + + F_i = f_i (mod p), i = 1..r + + References + ========== + + .. [1] [Gathen99]_ + + """ + r = len(f_list) + lc = dup_LC(f, K) + + if r == 1: + F = dup_mul_ground(f, K.gcdex(lc, p**l)[0], K) + return [ dup_trunc(F, p**l, K) ] + + m = p + k = r // 2 + d = int(_ceil(_log2(l))) + + g = gf_from_int_poly([lc], p) + + for f_i in f_list[:k]: + g = gf_mul(g, gf_from_int_poly(f_i, p), p, K) + + h = gf_from_int_poly(f_list[k], p) + + for f_i in f_list[k + 1:]: + h = gf_mul(h, gf_from_int_poly(f_i, p), p, K) + + s, t, _ = gf_gcdex(g, h, p, K) + + g = gf_to_int_poly(g, p) + h = gf_to_int_poly(h, p) + s = gf_to_int_poly(s, p) + t = gf_to_int_poly(t, p) + + for _ in range(1, d + 1): + (g, h, s, t), m = dup_zz_hensel_step(m, f, g, h, s, t, K), m**2 + + return dup_zz_hensel_lift(p, g, f_list[:k], l, K) \ + + dup_zz_hensel_lift(p, h, f_list[k:], l, K) + +def _test_pl(fc, q, pl): + if q > pl // 2: + q = q - pl + if not q: + return True + return fc % q == 0 + +def dup_zz_zassenhaus(f, K): + """Factor primitive square-free polynomials in `Z[x]`. """ + n = dup_degree(f) + + if n == 1: + return [f] + + from sympy.ntheory import isprime + + fc = f[-1] + A = dup_max_norm(f, K) + b = dup_LC(f, K) + B = int(abs(K.sqrt(K(n + 1))*2**n*A*b)) + C = int((n + 1)**(2*n)*A**(2*n - 1)) + gamma = int(_ceil(2*_log2(C))) + bound = int(2*gamma*_log(gamma)) + a = [] + # choose a prime number `p` such that `f` be square free in Z_p + # if there are many factors in Z_p, choose among a few different `p` + # the one with fewer factors + for px in range(3, bound + 1): + if not isprime(px) or b % px == 0: + continue + + px = K.convert(px) + + F = gf_from_int_poly(f, px) + + if not gf_sqf_p(F, px, K): + continue + fsqfx = gf_factor_sqf(F, px, K)[1] + a.append((px, fsqfx)) + if len(fsqfx) < 15 or len(a) > 4: + break + p, fsqf = min(a, key=lambda x: len(x[1])) + + l = int(_ceil(_log(2*B + 1, p))) + + modular = [gf_to_int_poly(ff, p) for ff in fsqf] + + g = dup_zz_hensel_lift(p, f, modular, l, K) + + sorted_T = range(len(g)) + T = set(sorted_T) + factors, s = [], 1 + pl = p**l + + while 2*s <= len(T): + for S in subsets(sorted_T, s): + # lift the constant coefficient of the product `G` of the factors + # in the subset `S`; if it is does not divide `fc`, `G` does + # not divide the input polynomial + + if b == 1: + q = 1 + for i in S: + q = q*g[i][-1] + q = q % pl + if not _test_pl(fc, q, pl): + continue + else: + G = [b] + for i in S: + G = dup_mul(G, g[i], K) + G = dup_trunc(G, pl, K) + G = dup_primitive(G, K)[1] + q = G[-1] + if q and fc % q != 0: + continue + + H = [b] + S = set(S) + T_S = T - S + + if b == 1: + G = [b] + for i in S: + G = dup_mul(G, g[i], K) + G = dup_trunc(G, pl, K) + + for i in T_S: + H = dup_mul(H, g[i], K) + + H = dup_trunc(H, pl, K) + + G_norm = dup_l1_norm(G, K) + H_norm = dup_l1_norm(H, K) + + if G_norm*H_norm <= B: + T = T_S + sorted_T = [i for i in sorted_T if i not in S] + + G = dup_primitive(G, K)[1] + f = dup_primitive(H, K)[1] + + factors.append(G) + b = dup_LC(f, K) + + break + else: + s += 1 + + return factors + [f] + + +def dup_zz_irreducible_p(f, K): + """Test irreducibility using Eisenstein's criterion. """ + lc = dup_LC(f, K) + tc = dup_TC(f, K) + + e_fc = dup_content(f[1:], K) + + if e_fc: + from sympy.ntheory import factorint + e_ff = factorint(int(e_fc)) + + for p in e_ff.keys(): + if (lc % p) and (tc % p**2): + return True + + +def dup_cyclotomic_p(f, K, irreducible=False): + """ + Efficiently test if ``f`` is a cyclotomic polynomial. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 + >>> R.dup_cyclotomic_p(f) + False + + >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 + >>> R.dup_cyclotomic_p(g) + True + + References + ========== + + Bradford, Russell J., and James H. Davenport. "Effective tests for + cyclotomic polynomials." In International Symposium on Symbolic and + Algebraic Computation, pp. 244-251. Springer, Berlin, Heidelberg, 1988. + + """ + if K.is_QQ: + try: + K0, K = K, K.get_ring() + f = dup_convert(f, K0, K) + except CoercionFailed: + return False + elif not K.is_ZZ: + return False + + lc = dup_LC(f, K) + tc = dup_TC(f, K) + + if lc != 1 or (tc != -1 and tc != 1): + return False + + if not irreducible: + coeff, factors = dup_factor_list(f, K) + + if coeff != K.one or factors != [(f, 1)]: + return False + + n = dup_degree(f) + g, h = [], [] + + for i in range(n, -1, -2): + g.insert(0, f[i]) + + for i in range(n - 1, -1, -2): + h.insert(0, f[i]) + + g = dup_sqr(dup_strip(g), K) + h = dup_sqr(dup_strip(h), K) + + F = dup_sub(g, dup_lshift(h, 1, K), K) + + if K.is_negative(dup_LC(F, K)): + F = dup_neg(F, K) + + if F == f: + return True + + g = dup_mirror(f, K) + + if K.is_negative(dup_LC(g, K)): + g = dup_neg(g, K) + + if F == g and dup_cyclotomic_p(g, K): + return True + + G = dup_sqf_part(F, K) + + if dup_sqr(G, K) == F and dup_cyclotomic_p(G, K): + return True + + return False + + +def dup_zz_cyclotomic_poly(n, K): + """Efficiently generate n-th cyclotomic polynomial. """ + from sympy.ntheory import factorint + h = [K.one, -K.one] + + for p, k in factorint(n).items(): + h = dup_quo(dup_inflate(h, p, K), h, K) + h = dup_inflate(h, p**(k - 1), K) + + return h + + +def _dup_cyclotomic_decompose(n, K): + from sympy.ntheory import factorint + + H = [[K.one, -K.one]] + + for p, k in factorint(n).items(): + Q = [ dup_quo(dup_inflate(h, p, K), h, K) for h in H ] + H.extend(Q) + + for i in range(1, k): + Q = [ dup_inflate(q, p, K) for q in Q ] + H.extend(Q) + + return H + + +def dup_zz_cyclotomic_factor(f, K): + """ + Efficiently factor polynomials `x**n - 1` and `x**n + 1` in `Z[x]`. + + Given a univariate polynomial `f` in `Z[x]` returns a list of factors + of `f`, provided that `f` is in the form `x**n - 1` or `x**n + 1` for + `n >= 1`. Otherwise returns None. + + Factorization is performed using cyclotomic decomposition of `f`, + which makes this method much faster that any other direct factorization + approach (e.g. Zassenhaus's). + + References + ========== + + .. [1] [Weisstein09]_ + + """ + lc_f, tc_f = dup_LC(f, K), dup_TC(f, K) + + if dup_degree(f) <= 0: + return None + + if lc_f != 1 or tc_f not in [-1, 1]: + return None + + if any(bool(cf) for cf in f[1:-1]): + return None + + n = dup_degree(f) + F = _dup_cyclotomic_decompose(n, K) + + if not K.is_one(tc_f): + return F + else: + H = [] + + for h in _dup_cyclotomic_decompose(2*n, K): + if h not in F: + H.append(h) + + return H + + +def dup_zz_factor_sqf(f, K): + """Factor square-free (non-primitive) polynomials in `Z[x]`. """ + cont, g = dup_primitive(f, K) + + n = dup_degree(g) + + if dup_LC(g, K) < 0: + cont, g = -cont, dup_neg(g, K) + + if n <= 0: + return cont, [] + elif n == 1: + return cont, [g] + + if query('USE_IRREDUCIBLE_IN_FACTOR'): + if dup_zz_irreducible_p(g, K): + return cont, [g] + + factors = None + + if query('USE_CYCLOTOMIC_FACTOR'): + factors = dup_zz_cyclotomic_factor(g, K) + + if factors is None: + factors = dup_zz_zassenhaus(g, K) + + return cont, _sort_factors(factors, multiple=False) + + +def dup_zz_factor(f, K): + """ + Factor (non square-free) polynomials in `Z[x]`. + + Given a univariate polynomial `f` in `Z[x]` computes its complete + factorization `f_1, ..., f_n` into irreducibles over integers:: + + f = content(f) f_1**k_1 ... f_n**k_n + + The factorization is computed by reducing the input polynomial + into a primitive square-free polynomial and factoring it using + Zassenhaus algorithm. Trial division is used to recover the + multiplicities of factors. + + The result is returned as a tuple consisting of:: + + (content(f), [(f_1, k_1), ..., (f_n, k_n)) + + Examples + ======== + + Consider the polynomial `f = 2*x**4 - 2`:: + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_zz_factor(2*x**4 - 2) + (2, [(x - 1, 1), (x + 1, 1), (x**2 + 1, 1)]) + + In result we got the following factorization:: + + f = 2 (x - 1) (x + 1) (x**2 + 1) + + Note that this is a complete factorization over integers, + however over Gaussian integers we can factor the last term. + + By default, polynomials `x**n - 1` and `x**n + 1` are factored + using cyclotomic decomposition to speedup computations. To + disable this behaviour set cyclotomic=False. + + References + ========== + + .. [1] [Gathen99]_ + + """ + if GROUND_TYPES == 'flint': + f_flint = fmpz_poly(f[::-1]) + cont, factors = f_flint.factor() + factors = [(fac.coeffs()[::-1], exp) for fac, exp in factors] + return cont, _sort_factors(factors) + + cont, g = dup_primitive(f, K) + + n = dup_degree(g) + + if dup_LC(g, K) < 0: + cont, g = -cont, dup_neg(g, K) + + if n <= 0: + return cont, [] + elif n == 1: + return cont, [(g, 1)] + + if query('USE_IRREDUCIBLE_IN_FACTOR'): + if dup_zz_irreducible_p(g, K): + return cont, [(g, 1)] + + g = dup_sqf_part(g, K) + H = None + + if query('USE_CYCLOTOMIC_FACTOR'): + H = dup_zz_cyclotomic_factor(g, K) + + if H is None: + H = dup_zz_zassenhaus(g, K) + + factors = dup_trial_division(f, H, K) + + _dup_check_degrees(f, factors) + + return cont, factors + + +def dmp_zz_wang_non_divisors(E, cs, ct, K): + """Wang/EEZ: Compute a set of valid divisors. """ + result = [ cs*ct ] + + for q in E: + q = abs(q) + + for r in reversed(result): + while r != 1: + r = K.gcd(r, q) + q = q // r + + if K.is_one(q): + return None + + result.append(q) + + return result[1:] + + +def dmp_zz_wang_test_points(f, T, ct, A, u, K): + """Wang/EEZ: Test evaluation points for suitability. """ + if not dmp_eval_tail(dmp_LC(f, K), A, u - 1, K): + raise EvaluationFailed('no luck') + + g = dmp_eval_tail(f, A, u, K) + + if not dup_sqf_p(g, K): + raise EvaluationFailed('no luck') + + c, h = dup_primitive(g, K) + + if K.is_negative(dup_LC(h, K)): + c, h = -c, dup_neg(h, K) + + v = u - 1 + + E = [ dmp_eval_tail(t, A, v, K) for t, _ in T ] + D = dmp_zz_wang_non_divisors(E, c, ct, K) + + if D is not None: + return c, h, E + else: + raise EvaluationFailed('no luck') + + +def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K): + """Wang/EEZ: Compute correct leading coefficients. """ + C, J, v = [], [0]*len(E), u - 1 + + for h in H: + c = dmp_one(v, K) + d = dup_LC(h, K)*cs + + for i in reversed(range(len(E))): + k, e, (t, _) = 0, E[i], T[i] + + while not (d % e): + d, k = d//e, k + 1 + + if k != 0: + c, J[i] = dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1 + + C.append(c) + + if not all(J): + raise ExtraneousFactors # pragma: no cover + + CC, HH = [], [] + + for c, h in zip(C, H): + d = dmp_eval_tail(c, A, v, K) + lc = dup_LC(h, K) + + if K.is_one(cs): + cc = lc//d + else: + g = K.gcd(lc, d) + d, cc = d//g, lc//g + h, cs = dup_mul_ground(h, d, K), cs//d + + c = dmp_mul_ground(c, cc, v, K) + + CC.append(c) + HH.append(h) + + if K.is_one(cs): + return f, HH, CC + + CCC, HHH = [], [] + + for c, h in zip(CC, HH): + CCC.append(dmp_mul_ground(c, cs, v, K)) + HHH.append(dmp_mul_ground(h, cs, 0, K)) + + f = dmp_mul_ground(f, cs**(len(H) - 1), u, K) + + return f, HHH, CCC + + +def dup_zz_diophantine(F, m, p, K): + """Wang/EEZ: Solve univariate Diophantine equations. """ + if len(F) == 2: + a, b = F + + f = gf_from_int_poly(a, p) + g = gf_from_int_poly(b, p) + + s, t, G = gf_gcdex(g, f, p, K) + + s = gf_lshift(s, m, K) + t = gf_lshift(t, m, K) + + q, s = gf_div(s, f, p, K) + + t = gf_add_mul(t, q, g, p, K) + + s = gf_to_int_poly(s, p) + t = gf_to_int_poly(t, p) + + result = [s, t] + else: + G = [F[-1]] + + for f in reversed(F[1:-1]): + G.insert(0, dup_mul(f, G[0], K)) + + S, T = [], [[1]] + + for f, g in zip(F, G): + t, s = dmp_zz_diophantine([g, f], T[-1], [], 0, p, 1, K) + T.append(t) + S.append(s) + + result, S = [], S + [T[-1]] + + for s, f in zip(S, F): + s = gf_from_int_poly(s, p) + f = gf_from_int_poly(f, p) + + r = gf_rem(gf_lshift(s, m, K), f, p, K) + s = gf_to_int_poly(r, p) + + result.append(s) + + return result + + +def dmp_zz_diophantine(F, c, A, d, p, u, K): + """Wang/EEZ: Solve multivariate Diophantine equations. """ + if not A: + S = [ [] for _ in F ] + n = dup_degree(c) + + for i, coeff in enumerate(c): + if not coeff: + continue + + T = dup_zz_diophantine(F, n - i, p, K) + + for j, (s, t) in enumerate(zip(S, T)): + t = dup_mul_ground(t, coeff, K) + S[j] = dup_trunc(dup_add(s, t, K), p, K) + else: + n = len(A) + e = dmp_expand(F, u, K) + + a, A = A[-1], A[:-1] + B, G = [], [] + + for f in F: + B.append(dmp_quo(e, f, u, K)) + G.append(dmp_eval_in(f, a, n, u, K)) + + C = dmp_eval_in(c, a, n, u, K) + + v = u - 1 + + S = dmp_zz_diophantine(G, C, A, d, p, v, K) + S = [ dmp_raise(s, 1, v, K) for s in S ] + + for s, b in zip(S, B): + c = dmp_sub_mul(c, s, b, u, K) + + c = dmp_ground_trunc(c, p, u, K) + + m = dmp_nest([K.one, -a], n, K) + M = dmp_one(n, K) + + for k in range(0, d): + if dmp_zero_p(c, u): + break + + M = dmp_mul(M, m, u, K) + C = dmp_diff_eval_in(c, k + 1, a, n, u, K) + + if not dmp_zero_p(C, v): + C = dmp_quo_ground(C, K.factorial(K(k) + 1), v, K) + T = dmp_zz_diophantine(G, C, A, d, p, v, K) + + for i, t in enumerate(T): + T[i] = dmp_mul(dmp_raise(t, 1, v, K), M, u, K) + + for i, (s, t) in enumerate(zip(S, T)): + S[i] = dmp_add(s, t, u, K) + + for t, b in zip(T, B): + c = dmp_sub_mul(c, t, b, u, K) + + c = dmp_ground_trunc(c, p, u, K) + + S = [ dmp_ground_trunc(s, p, u, K) for s in S ] + + return S + + +def dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K): + """Wang/EEZ: Parallel Hensel lifting algorithm. """ + S, n, v = [f], len(A), u - 1 + + H = list(H) + + for i, a in enumerate(reversed(A[1:])): + s = dmp_eval_in(S[0], a, n - i, u - i, K) + S.insert(0, dmp_ground_trunc(s, p, v - i, K)) + + d = max(dmp_degree_list(f, u)[1:]) + + for j, s, a in zip(range(2, n + 2), S, A): + G, w = list(H), j - 1 + + I, J = A[:j - 2], A[j - 1:] + + for i, (h, lc) in enumerate(zip(H, LC)): + lc = dmp_ground_trunc(dmp_eval_tail(lc, J, v, K), p, w - 1, K) + H[i] = [lc] + dmp_raise(h[1:], 1, w - 1, K) + + m = dmp_nest([K.one, -a], w, K) + M = dmp_one(w, K) + + c = dmp_sub(s, dmp_expand(H, w, K), w, K) + + dj = dmp_degree_in(s, w, w) + + for k in range(0, dj): + if dmp_zero_p(c, w): + break + + M = dmp_mul(M, m, w, K) + C = dmp_diff_eval_in(c, k + 1, a, w, w, K) + + if not dmp_zero_p(C, w - 1): + C = dmp_quo_ground(C, K.factorial(K(k) + 1), w - 1, K) + T = dmp_zz_diophantine(G, C, I, d, p, w - 1, K) + + for i, (h, t) in enumerate(zip(H, T)): + h = dmp_add_mul(h, dmp_raise(t, 1, w - 1, K), M, w, K) + H[i] = dmp_ground_trunc(h, p, w, K) + + h = dmp_sub(s, dmp_expand(H, w, K), w, K) + c = dmp_ground_trunc(h, p, w, K) + + if dmp_expand(H, u, K) != f: + raise ExtraneousFactors # pragma: no cover + else: + return H + + +def dmp_zz_wang(f, u, K, mod=None, seed=None): + r""" + Factor primitive square-free polynomials in `Z[X]`. + + Given a multivariate polynomial `f` in `Z[x_1,...,x_n]`, which is + primitive and square-free in `x_1`, computes factorization of `f` into + irreducibles over integers. + + The procedure is based on Wang's Enhanced Extended Zassenhaus + algorithm. The algorithm works by viewing `f` as a univariate polynomial + in `Z[x_2,...,x_n][x_1]`, for which an evaluation mapping is computed:: + + x_2 -> a_2, ..., x_n -> a_n + + where `a_i`, for `i = 2, \dots, n`, are carefully chosen integers. The + mapping is used to transform `f` into a univariate polynomial in `Z[x_1]`, + which can be factored efficiently using Zassenhaus algorithm. The last + step is to lift univariate factors to obtain true multivariate + factors. For this purpose a parallel Hensel lifting procedure is used. + + The parameter ``seed`` is passed to _randint and can be used to seed randint + (when an integer) or (for testing purposes) can be a sequence of numbers. + + References + ========== + + .. [1] [Wang78]_ + .. [2] [Geddes92]_ + + """ + from sympy.ntheory import nextprime + + randint = _randint(seed) + + ct, T = dmp_zz_factor(dmp_LC(f, K), u - 1, K) + + b = dmp_zz_mignotte_bound(f, u, K) + p = K(nextprime(b)) + + if mod is None: + if u == 1: + mod = 2 + else: + mod = 1 + + history, configs, A, r = set(), [], [K.zero]*u, None + + try: + cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K) + + _, H = dup_zz_factor_sqf(s, K) + + r = len(H) + + if r == 1: + return [f] + + configs = [(s, cs, E, H, A)] + except EvaluationFailed: + pass + + eez_num_configs = query('EEZ_NUMBER_OF_CONFIGS') + eez_num_tries = query('EEZ_NUMBER_OF_TRIES') + eez_mod_step = query('EEZ_MODULUS_STEP') + + while len(configs) < eez_num_configs: + for _ in range(eez_num_tries): + A = [ K(randint(-mod, mod)) for _ in range(u) ] + + if tuple(A) not in history: + history.add(tuple(A)) + else: + continue + + try: + cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K) + except EvaluationFailed: + continue + + _, H = dup_zz_factor_sqf(s, K) + + rr = len(H) + + if r is not None: + if rr != r: # pragma: no cover + if rr < r: + configs, r = [], rr + else: + continue + else: + r = rr + + if r == 1: + return [f] + + configs.append((s, cs, E, H, A)) + + if len(configs) == eez_num_configs: + break + else: + mod += eez_mod_step + + s_norm, s_arg, i = None, 0, 0 + + for s, _, _, _, _ in configs: + _s_norm = dup_max_norm(s, K) + + if s_norm is not None: + if _s_norm < s_norm: + s_norm = _s_norm + s_arg = i + else: + s_norm = _s_norm + + i += 1 + + _, cs, E, H, A = configs[s_arg] + orig_f = f + + try: + f, H, LC = dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K) + factors = dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K) + except ExtraneousFactors: # pragma: no cover + if query('EEZ_RESTART_IF_NEEDED'): + return dmp_zz_wang(orig_f, u, K, mod + 1) + else: + raise ExtraneousFactors( + "we need to restart algorithm with better parameters") + + result = [] + + for f in factors: + _, f = dmp_ground_primitive(f, u, K) + + if K.is_negative(dmp_ground_LC(f, u, K)): + f = dmp_neg(f, u, K) + + result.append(f) + + return result + + +def dmp_zz_factor(f, u, K): + r""" + Factor (non square-free) polynomials in `Z[X]`. + + Given a multivariate polynomial `f` in `Z[x]` computes its complete + factorization `f_1, \dots, f_n` into irreducibles over integers:: + + f = content(f) f_1**k_1 ... f_n**k_n + + The factorization is computed by reducing the input polynomial + into a primitive square-free polynomial and factoring it using + Enhanced Extended Zassenhaus (EEZ) algorithm. Trial division + is used to recover the multiplicities of factors. + + The result is returned as a tuple consisting of:: + + (content(f), [(f_1, k_1), ..., (f_n, k_n)) + + Consider polynomial `f = 2*(x**2 - y**2)`:: + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_zz_factor(2*x**2 - 2*y**2) + (2, [(x - y, 1), (x + y, 1)]) + + In result we got the following factorization:: + + f = 2 (x - y) (x + y) + + References + ========== + + .. [1] [Gathen99]_ + + """ + if not u: + return dup_zz_factor(f, K) + + if dmp_zero_p(f, u): + return K.zero, [] + + cont, g = dmp_ground_primitive(f, u, K) + + if dmp_ground_LC(g, u, K) < 0: + cont, g = -cont, dmp_neg(g, u, K) + + if all(d <= 0 for d in dmp_degree_list(g, u)): + return cont, [] + + G, g = dmp_primitive(g, u, K) + + factors = [] + + if dmp_degree(g, u) > 0: + g = dmp_sqf_part(g, u, K) + H = dmp_zz_wang(g, u, K) + factors = dmp_trial_division(f, H, u, K) + + for g, k in dmp_zz_factor(G, u - 1, K)[1]: + factors.insert(0, ([g], k)) + + _dmp_check_degrees(f, u, factors) + + return cont, _sort_factors(factors) + + +def dup_qq_i_factor(f, K0): + """Factor univariate polynomials into irreducibles in `QQ_I[x]`. """ + # Factor in QQ + K1 = K0.as_AlgebraicField() + f = dup_convert(f, K0, K1) + coeff, factors = dup_factor_list(f, K1) + factors = [(dup_convert(fac, K1, K0), i) for fac, i in factors] + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dup_zz_i_factor(f, K0): + """Factor univariate polynomials into irreducibles in `ZZ_I[x]`. """ + # First factor in QQ_I + K1 = K0.get_field() + f = dup_convert(f, K0, K1) + coeff, factors = dup_qq_i_factor(f, K1) + + new_factors = [] + for fac, i in factors: + # Extract content + fac_denom, fac_num = dup_clear_denoms(fac, K1) + fac_num_ZZ_I = dup_convert(fac_num, K1, K0) + content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, 0, K0) + + coeff = (coeff * content ** i) // fac_denom ** i + new_factors.append((fac_prim, i)) + + factors = new_factors + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dmp_qq_i_factor(f, u, K0): + """Factor multivariate polynomials into irreducibles in `QQ_I[X]`. """ + # Factor in QQ + K1 = K0.as_AlgebraicField() + f = dmp_convert(f, u, K0, K1) + coeff, factors = dmp_factor_list(f, u, K1) + factors = [(dmp_convert(fac, u, K1, K0), i) for fac, i in factors] + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dmp_zz_i_factor(f, u, K0): + """Factor multivariate polynomials into irreducibles in `ZZ_I[X]`. """ + # First factor in QQ_I + K1 = K0.get_field() + f = dmp_convert(f, u, K0, K1) + coeff, factors = dmp_qq_i_factor(f, u, K1) + + new_factors = [] + for fac, i in factors: + # Extract content + fac_denom, fac_num = dmp_clear_denoms(fac, u, K1) + fac_num_ZZ_I = dmp_convert(fac_num, u, K1, K0) + content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, u, K0) + + coeff = (coeff * content ** i) // fac_denom ** i + new_factors.append((fac_prim, i)) + + factors = new_factors + coeff = K0.convert(coeff, K1) + return coeff, factors + + +def dup_ext_factor(f, K): + r"""Factor univariate polynomials over algebraic number fields. + + The domain `K` must be an algebraic number field `k(a)` (see :ref:`QQ(a)`). + + Examples + ======== + + First define the algebraic number field `K = \mathbb{Q}(\sqrt{2})`: + + >>> from sympy import QQ, sqrt + >>> from sympy.polys.factortools import dup_ext_factor + >>> K = QQ.algebraic_field(sqrt(2)) + + We can now factorise the polynomial `x^2 - 2` over `K`: + + >>> p = [K(1), K(0), K(-2)] # x^2 - 2 + >>> p1 = [K(1), -K.unit] # x - sqrt(2) + >>> p2 = [K(1), +K.unit] # x + sqrt(2) + >>> dup_ext_factor(p, K) == (K.one, [(p1, 1), (p2, 1)]) + True + + Usually this would be done at a higher level: + + >>> from sympy import factor + >>> from sympy.abc import x + >>> factor(x**2 - 2, extension=sqrt(2)) + (x - sqrt(2))*(x + sqrt(2)) + + Explanation + =========== + + Uses Trager's algorithm. In particular this function is algorithm + ``alg_factor`` from [Trager76]_. + + If `f` is a polynomial in `k(a)[x]` then its norm `g(x)` is a polynomial in + `k[x]`. If `g(x)` is square-free and has irreducible factors `g_1(x)`, + `g_2(x)`, `\cdots` then the irreducible factors of `f` in `k(a)[x]` are + given by `f_i(x) = \gcd(f(x), g_i(x))` where the GCD is computed in + `k(a)[x]`. + + The first step in Trager's algorithm is to find an integer shift `s` so + that `f(x-sa)` has square-free norm. Then the norm is factorized in `k[x]` + and the GCD of (shifted) `f` with each factor gives the shifted factors of + `f`. At the end the shift is undone to recover the unshifted factors of `f` + in `k(a)[x]`. + + The algorithm reduces the problem of factorization in `k(a)[x]` to + factorization in `k[x]` with the main additional steps being to compute the + norm (a resultant calculation in `k[x,y]`) and some polynomial GCDs in + `k(a)[x]`. + + In practice in SymPy the base field `k` will be the rationals :ref:`QQ` and + this function factorizes a polynomial with coefficients in an algebraic + number field like `\mathbb{Q}(\sqrt{2})`. + + See Also + ======== + + dmp_ext_factor: + Analogous function for multivariate polynomials over ``k(a)``. + dup_sqf_norm: + Subroutine ``sqfr_norm`` also from [Trager76]_. + sympy.polys.polytools.factor: + The high-level function that ultimately uses this function as needed. + """ + n, lc = dup_degree(f), dup_LC(f, K) + + f = dup_monic(f, K) + + if n <= 0: + return lc, [] + if n == 1: + return lc, [(f, 1)] + + f, F = dup_sqf_part(f, K), f + s, g, r = dup_sqf_norm(f, K) + + factors = dup_factor_list_include(r, K.dom) + + if len(factors) == 1: + return lc, [(f, n//dup_degree(f))] + + H = s*K.unit + + for i, (factor, _) in enumerate(factors): + h = dup_convert(factor, K.dom, K) + h, _, g = dup_inner_gcd(h, g, K) + h = dup_shift(h, H, K) + factors[i] = h + + factors = dup_trial_division(F, factors, K) + + _dup_check_degrees(F, factors) + + return lc, factors + + +def dmp_ext_factor(f, u, K): + r"""Factor multivariate polynomials over algebraic number fields. + + The domain `K` must be an algebraic number field `k(a)` (see :ref:`QQ(a)`). + + Examples + ======== + + First define the algebraic number field `K = \mathbb{Q}(\sqrt{2})`: + + >>> from sympy import QQ, sqrt + >>> from sympy.polys.factortools import dmp_ext_factor + >>> K = QQ.algebraic_field(sqrt(2)) + + We can now factorise the polynomial `x^2 y^2 - 2` over `K`: + + >>> p = [[K(1),K(0),K(0)], [], [K(-2)]] # x**2*y**2 - 2 + >>> p1 = [[K(1),K(0)], [-K.unit]] # x*y - sqrt(2) + >>> p2 = [[K(1),K(0)], [+K.unit]] # x*y + sqrt(2) + >>> dmp_ext_factor(p, 1, K) == (K.one, [(p1, 1), (p2, 1)]) + True + + Usually this would be done at a higher level: + + >>> from sympy import factor + >>> from sympy.abc import x, y + >>> factor(x**2*y**2 - 2, extension=sqrt(2)) + (x*y - sqrt(2))*(x*y + sqrt(2)) + + Explanation + =========== + + This is Trager's algorithm for multivariate polynomials. In particular this + function is algorithm ``alg_factor`` from [Trager76]_. + + See :func:`dup_ext_factor` for explanation. + + See Also + ======== + + dup_ext_factor: + Analogous function for univariate polynomials over ``k(a)``. + dmp_sqf_norm: + Multivariate version of subroutine ``sqfr_norm`` also from [Trager76]_. + sympy.polys.polytools.factor: + The high-level function that ultimately uses this function as needed. + """ + if not u: + return dup_ext_factor(f, K) + + lc = dmp_ground_LC(f, u, K) + f = dmp_ground_monic(f, u, K) + + if all(d <= 0 for d in dmp_degree_list(f, u)): + return lc, [] + + f, F = dmp_sqf_part(f, u, K), f + s, g, r = dmp_sqf_norm(f, u, K) + + factors = dmp_factor_list_include(r, u, K.dom) + + if len(factors) == 1: + factors = [f] + else: + for i, (factor, _) in enumerate(factors): + h = dmp_convert(factor, u, K.dom, K) + h, _, g = dmp_inner_gcd(h, g, u, K) + a = [si*K.unit for si in s] + h = dmp_shift(h, a, u, K) + factors[i] = h + + result = dmp_trial_division(F, factors, u, K) + + _dmp_check_degrees(F, u, result) + + return lc, result + + +def dup_gf_factor(f, K): + """Factor univariate polynomials over finite fields. """ + f = dup_convert(f, K, K.dom) + + coeff, factors = gf_factor(f, K.mod, K.dom) + + for i, (f, k) in enumerate(factors): + factors[i] = (dup_convert(f, K.dom, K), k) + + return K.convert(coeff, K.dom), factors + + +def dmp_gf_factor(f, u, K): + """Factor multivariate polynomials over finite fields. """ + raise NotImplementedError('multivariate polynomials over finite fields') + + +def dup_factor_list(f, K0): + """Factor univariate polynomials into irreducibles in `K[x]`. """ + j, f = dup_terms_gcd(f, K0) + cont, f = dup_primitive(f, K0) + + if K0.is_FiniteField: + coeff, factors = dup_gf_factor(f, K0) + elif K0.is_Algebraic: + coeff, factors = dup_ext_factor(f, K0) + elif K0.is_GaussianRing: + coeff, factors = dup_zz_i_factor(f, K0) + elif K0.is_GaussianField: + coeff, factors = dup_qq_i_factor(f, K0) + else: + if not K0.is_Exact: + K0_inexact, K0 = K0, K0.get_exact() + f = dup_convert(f, K0_inexact, K0) + else: + K0_inexact = None + + if K0.is_Field: + K = K0.get_ring() + + denom, f = dup_clear_denoms(f, K0, K) + f = dup_convert(f, K0, K) + else: + K = K0 + + if K.is_ZZ: + coeff, factors = dup_zz_factor(f, K) + elif K.is_Poly: + f, u = dmp_inject(f, 0, K) + + coeff, factors = dmp_factor_list(f, u, K.dom) + + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_eject(f, u, K), k) + + coeff = K.convert(coeff, K.dom) + else: # pragma: no cover + raise DomainError('factorization not supported over %s' % K0) + + if K0.is_Field: + for i, (f, k) in enumerate(factors): + factors[i] = (dup_convert(f, K, K0), k) + + coeff = K0.convert(coeff, K) + coeff = K0.quo(coeff, denom) + + if K0_inexact: + for i, (f, k) in enumerate(factors): + max_norm = dup_max_norm(f, K0) + f = dup_quo_ground(f, max_norm, K0) + f = dup_convert(f, K0, K0_inexact) + factors[i] = (f, k) + coeff = K0.mul(coeff, K0.pow(max_norm, k)) + + coeff = K0_inexact.convert(coeff, K0) + K0 = K0_inexact + + if j: + factors.insert(0, ([K0.one, K0.zero], j)) + + return coeff*cont, _sort_factors(factors) + + +def dup_factor_list_include(f, K): + """Factor univariate polynomials into irreducibles in `K[x]`. """ + coeff, factors = dup_factor_list(f, K) + + if not factors: + return [(dup_strip([coeff]), 1)] + else: + g = dup_mul_ground(factors[0][0], coeff, K) + return [(g, factors[0][1])] + factors[1:] + + +def dmp_factor_list(f, u, K0): + """Factor multivariate polynomials into irreducibles in `K[X]`. """ + if not u: + return dup_factor_list(f, K0) + + J, f = dmp_terms_gcd(f, u, K0) + cont, f = dmp_ground_primitive(f, u, K0) + + if K0.is_FiniteField: # pragma: no cover + coeff, factors = dmp_gf_factor(f, u, K0) + elif K0.is_Algebraic: + coeff, factors = dmp_ext_factor(f, u, K0) + elif K0.is_GaussianRing: + coeff, factors = dmp_zz_i_factor(f, u, K0) + elif K0.is_GaussianField: + coeff, factors = dmp_qq_i_factor(f, u, K0) + else: + if not K0.is_Exact: + K0_inexact, K0 = K0, K0.get_exact() + f = dmp_convert(f, u, K0_inexact, K0) + else: + K0_inexact = None + + if K0.is_Field: + K = K0.get_ring() + + denom, f = dmp_clear_denoms(f, u, K0, K) + f = dmp_convert(f, u, K0, K) + else: + K = K0 + + if K.is_ZZ: + levels, f, v = dmp_exclude(f, u, K) + coeff, factors = dmp_zz_factor(f, v, K) + + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_include(f, levels, v, K), k) + elif K.is_Poly: + f, v = dmp_inject(f, u, K) + + coeff, factors = dmp_factor_list(f, v, K.dom) + + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_eject(f, v, K), k) + + coeff = K.convert(coeff, K.dom) + else: # pragma: no cover + raise DomainError('factorization not supported over %s' % K0) + + if K0.is_Field: + for i, (f, k) in enumerate(factors): + factors[i] = (dmp_convert(f, u, K, K0), k) + + coeff = K0.convert(coeff, K) + coeff = K0.quo(coeff, denom) + + if K0_inexact: + for i, (f, k) in enumerate(factors): + max_norm = dmp_max_norm(f, u, K0) + f = dmp_quo_ground(f, max_norm, u, K0) + f = dmp_convert(f, u, K0, K0_inexact) + factors[i] = (f, k) + coeff = K0.mul(coeff, K0.pow(max_norm, k)) + + coeff = K0_inexact.convert(coeff, K0) + K0 = K0_inexact + + for i, j in enumerate(reversed(J)): + if not j: + continue + + term = {(0,)*(u - i) + (1,) + (0,)*i: K0.one} + factors.insert(0, (dmp_from_dict(term, u, K0), j)) + + return coeff*cont, _sort_factors(factors) + + +def dmp_factor_list_include(f, u, K): + """Factor multivariate polynomials into irreducibles in `K[X]`. """ + if not u: + return dup_factor_list_include(f, K) + + coeff, factors = dmp_factor_list(f, u, K) + + if not factors: + return [(dmp_ground(coeff, u), 1)] + else: + g = dmp_mul_ground(factors[0][0], coeff, u, K) + return [(g, factors[0][1])] + factors[1:] + + +def dup_irreducible_p(f, K): + """ + Returns ``True`` if a univariate polynomial ``f`` has no factors + over its domain. + """ + return dmp_irreducible_p(f, 0, K) + + +def dmp_irreducible_p(f, u, K): + """ + Returns ``True`` if a multivariate polynomial ``f`` has no factors + over its domain. + """ + _, factors = dmp_factor_list(f, u, K) + + if not factors: + return True + elif len(factors) > 1: + return False + else: + _, k = factors[0] + return k == 1 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/fglmtools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/fglmtools.py new file mode 100644 index 0000000000000000000000000000000000000000..d68fe5bc2a40741e39b89163d393f7b57e6b1c49 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/fglmtools.py @@ -0,0 +1,153 @@ +"""Implementation of matrix FGLM Groebner basis conversion algorithm. """ + + +from sympy.polys.monomials import monomial_mul, monomial_div + +def matrix_fglm(F, ring, O_to): + """ + Converts the reduced Groebner basis ``F`` of a zero-dimensional + ideal w.r.t. ``O_from`` to a reduced Groebner basis + w.r.t. ``O_to``. + + References + ========== + + .. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient + Computation of Zero-dimensional Groebner Bases by Change of + Ordering + """ + domain = ring.domain + ngens = ring.ngens + + ring_to = ring.clone(order=O_to) + + old_basis = _basis(F, ring) + M = _representing_matrices(old_basis, F, ring) + + # V contains the normalforms (wrt O_from) of S + S = [ring.zero_monom] + V = [[domain.one] + [domain.zero] * (len(old_basis) - 1)] + G = [] + + L = [(i, 0) for i in range(ngens)] # (i, j) corresponds to x_i * S[j] + L.sort(key=lambda k_l: O_to(_incr_k(S[k_l[1]], k_l[0])), reverse=True) + t = L.pop() + + P = _identity_matrix(len(old_basis), domain) + + while True: + s = len(S) + v = _matrix_mul(M[t[0]], V[t[1]]) + _lambda = _matrix_mul(P, v) + + if all(_lambda[i] == domain.zero for i in range(s, len(old_basis))): + # there is a linear combination of v by V + lt = ring.term_new(_incr_k(S[t[1]], t[0]), domain.one) + rest = ring.from_dict({S[i]: _lambda[i] for i in range(s)}) + + g = (lt - rest).set_ring(ring_to) + if g: + G.append(g) + else: + # v is linearly independent from V + P = _update(s, _lambda, P) + S.append(_incr_k(S[t[1]], t[0])) + V.append(v) + + L.extend([(i, s) for i in range(ngens)]) + L = list(set(L)) + L.sort(key=lambda k_l: O_to(_incr_k(S[k_l[1]], k_l[0])), reverse=True) + + L = [(k, l) for (k, l) in L if all(monomial_div(_incr_k(S[l], k), g.LM) is None for g in G)] + + if not L: + G = [ g.monic() for g in G ] + return sorted(G, key=lambda g: O_to(g.LM), reverse=True) + + t = L.pop() + + +def _incr_k(m, k): + return tuple(list(m[:k]) + [m[k] + 1] + list(m[k + 1:])) + + +def _identity_matrix(n, domain): + M = [[domain.zero]*n for _ in range(n)] + + for i in range(n): + M[i][i] = domain.one + + return M + + +def _matrix_mul(M, v): + return [sum(row[i] * v[i] for i in range(len(v))) for row in M] + + +def _update(s, _lambda, P): + """ + Update ``P`` such that for the updated `P'` `P' v = e_{s}`. + """ + k = min(j for j in range(s, len(_lambda)) if _lambda[j] != 0) + + for r in range(len(_lambda)): + if r != k: + P[r] = [P[r][j] - (P[k][j] * _lambda[r]) / _lambda[k] for j in range(len(P[r]))] + + P[k] = [P[k][j] / _lambda[k] for j in range(len(P[k]))] + P[k], P[s] = P[s], P[k] + + return P + + +def _representing_matrices(basis, G, ring): + r""" + Compute the matrices corresponding to the linear maps `m \mapsto + x_i m` for all variables `x_i`. + """ + domain = ring.domain + u = ring.ngens-1 + + def var(i): + return tuple([0] * i + [1] + [0] * (u - i)) + + def representing_matrix(m): + M = [[domain.zero] * len(basis) for _ in range(len(basis))] + + for i, v in enumerate(basis): + r = ring.term_new(monomial_mul(m, v), domain.one).rem(G) + + for monom, coeff in r.terms(): + j = basis.index(monom) + M[j][i] = coeff + + return M + + return [representing_matrix(var(i)) for i in range(u + 1)] + + +def _basis(G, ring): + r""" + Computes a list of monomials which are not divisible by the leading + monomials wrt to ``O`` of ``G``. These monomials are a basis of + `K[X_1, \ldots, X_n]/(G)`. + """ + order = ring.order + + leading_monomials = [g.LM for g in G] + candidates = [ring.zero_monom] + basis = [] + + while candidates: + t = candidates.pop() + basis.append(t) + + new_candidates = [_incr_k(t, k) for k in range(ring.ngens) + if all(monomial_div(_incr_k(t, k), lmg) is None + for lmg in leading_monomials)] + candidates.extend(new_candidates) + candidates.sort(key=order, reverse=True) + + basis = list(set(basis)) + + return sorted(basis, key=order) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/fields.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/fields.py new file mode 100644 index 0000000000000000000000000000000000000000..ee844df55690af0b140132249990b335d926b6d4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/fields.py @@ -0,0 +1,639 @@ +"""Sparse rational function fields. """ + +from __future__ import annotations +from functools import reduce + +from operator import add, mul, lt, le, gt, ge + +from sympy.core.expr import Expr +from sympy.core.mod import Mod +from sympy.core.numbers import Exp1 +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import CantSympify, sympify +from sympy.functions.elementary.exponential import ExpBase +from sympy.polys.domains.domain import Domain +from sympy.polys.domains.domainelement import DomainElement +from sympy.polys.domains.fractionfield import FractionField +from sympy.polys.domains.polynomialring import PolynomialRing +from sympy.polys.constructor import construct_domain +from sympy.polys.orderings import lex, MonomialOrder +from sympy.polys.polyerrors import CoercionFailed +from sympy.polys.polyoptions import build_options +from sympy.polys.polyutils import _parallel_dict_from_expr +from sympy.polys.rings import PolyRing, PolyElement +from sympy.printing.defaults import DefaultPrinting +from sympy.utilities import public +from sympy.utilities.iterables import is_sequence +from sympy.utilities.magic import pollute + +@public +def field(symbols, domain, order=lex): + """Construct new rational function field returning (field, x1, ..., xn). """ + _field = FracField(symbols, domain, order) + return (_field,) + _field.gens + +@public +def xfield(symbols, domain, order=lex): + """Construct new rational function field returning (field, (x1, ..., xn)). """ + _field = FracField(symbols, domain, order) + return (_field, _field.gens) + +@public +def vfield(symbols, domain, order=lex): + """Construct new rational function field and inject generators into global namespace. """ + _field = FracField(symbols, domain, order) + pollute([ sym.name for sym in _field.symbols ], _field.gens) + return _field + +@public +def sfield(exprs, *symbols, **options): + """Construct a field deriving generators and domain + from options and input expressions. + + Parameters + ========== + + exprs : py:class:`~.Expr` or sequence of :py:class:`~.Expr` (sympifiable) + + symbols : sequence of :py:class:`~.Symbol`/:py:class:`~.Expr` + + options : keyword arguments understood by :py:class:`~.Options` + + Examples + ======== + + >>> from sympy import exp, log, symbols, sfield + + >>> x = symbols("x") + >>> K, f = sfield((x*log(x) + 4*x**2)*exp(1/x + log(x)/3)/x**2) + >>> K + Rational function field in x, exp(1/x), log(x), x**(1/3) over ZZ with lex order + >>> f + (4*x**2*(exp(1/x)) + x*(exp(1/x))*(log(x)))/((x**(1/3))**5) + """ + single = False + if not is_sequence(exprs): + exprs, single = [exprs], True + + exprs = list(map(sympify, exprs)) + opt = build_options(symbols, options) + numdens = [] + for expr in exprs: + numdens.extend(expr.as_numer_denom()) + reps, opt = _parallel_dict_from_expr(numdens, opt) + + if opt.domain is None: + # NOTE: this is inefficient because construct_domain() automatically + # performs conversion to the target domain. It shouldn't do this. + coeffs = sum([list(rep.values()) for rep in reps], []) + opt.domain, _ = construct_domain(coeffs, opt=opt) + + _field = FracField(opt.gens, opt.domain, opt.order) + fracs = [] + for i in range(0, len(reps), 2): + fracs.append(_field(tuple(reps[i:i+2]))) + + if single: + return (_field, fracs[0]) + else: + return (_field, fracs) + + +class FracField(DefaultPrinting): + """Multivariate distributed rational function field. """ + + ring: PolyRing + gens: tuple[FracElement, ...] + symbols: tuple[Expr, ...] + ngens: int + domain: Domain + order: MonomialOrder + + def __new__(cls, symbols, domain, order=lex): + ring = PolyRing(symbols, domain, order) + symbols = ring.symbols + ngens = ring.ngens + domain = ring.domain + order = ring.order + + _hash_tuple = (cls.__name__, symbols, ngens, domain, order) + + obj = object.__new__(cls) + obj._hash_tuple = _hash_tuple + obj._hash = hash(_hash_tuple) + obj.ring = ring + obj.symbols = symbols + obj.ngens = ngens + obj.domain = domain + obj.order = order + + obj.dtype = FracElement(obj, ring.zero).raw_new + + obj.zero = obj.dtype(ring.zero) + obj.one = obj.dtype(ring.one) + + obj.gens = obj._gens() + + for symbol, generator in zip(obj.symbols, obj.gens): + if isinstance(symbol, Symbol): + name = symbol.name + + if not hasattr(obj, name): + setattr(obj, name, generator) + + return obj + + def _gens(self): + """Return a list of polynomial generators. """ + return tuple([ self.dtype(gen) for gen in self.ring.gens ]) + + def __getnewargs__(self): + return (self.symbols, self.domain, self.order) + + def __hash__(self): + return self._hash + + def index(self, gen): + if self.is_element(gen): + return self.ring.index(gen.to_poly()) + else: + raise ValueError("expected a %s, got %s instead" % (self.dtype,gen)) + + def __eq__(self, other): + return isinstance(other, FracField) and \ + (self.symbols, self.ngens, self.domain, self.order) == \ + (other.symbols, other.ngens, other.domain, other.order) + + def __ne__(self, other): + return not self == other + + def is_element(self, element): + """True if ``element`` is an element of this field. False otherwise. """ + return isinstance(element, FracElement) and element.field == self + + def raw_new(self, numer, denom=None): + return self.dtype(numer, denom) + + def new(self, numer, denom=None): + if denom is None: denom = self.ring.one + numer, denom = numer.cancel(denom) + return self.raw_new(numer, denom) + + def domain_new(self, element): + return self.domain.convert(element) + + def ground_new(self, element): + try: + return self.new(self.ring.ground_new(element)) + except CoercionFailed: + domain = self.domain + + if not domain.is_Field and domain.has_assoc_Field: + ring = self.ring + ground_field = domain.get_field() + element = ground_field.convert(element) + numer = ring.ground_new(ground_field.numer(element)) + denom = ring.ground_new(ground_field.denom(element)) + return self.raw_new(numer, denom) + else: + raise + + def field_new(self, element): + if isinstance(element, FracElement): + if self == element.field: + return element + + if isinstance(self.domain, FractionField) and \ + self.domain.field == element.field: + return self.ground_new(element) + elif isinstance(self.domain, PolynomialRing) and \ + self.domain.ring.to_field() == element.field: + return self.ground_new(element) + else: + raise NotImplementedError("conversion") + elif isinstance(element, PolyElement): + denom, numer = element.clear_denoms() + + if isinstance(self.domain, PolynomialRing) and \ + numer.ring == self.domain.ring: + numer = self.ring.ground_new(numer) + elif isinstance(self.domain, FractionField) and \ + numer.ring == self.domain.field.to_ring(): + numer = self.ring.ground_new(numer) + else: + numer = numer.set_ring(self.ring) + + denom = self.ring.ground_new(denom) + return self.raw_new(numer, denom) + elif isinstance(element, tuple) and len(element) == 2: + numer, denom = list(map(self.ring.ring_new, element)) + return self.new(numer, denom) + elif isinstance(element, str): + raise NotImplementedError("parsing") + elif isinstance(element, Expr): + return self.from_expr(element) + else: + return self.ground_new(element) + + __call__ = field_new + + def _rebuild_expr(self, expr, mapping): + domain = self.domain + powers = tuple((gen, gen.as_base_exp()) for gen in mapping.keys() + if gen.is_Pow or isinstance(gen, ExpBase)) + + def _rebuild(expr): + generator = mapping.get(expr) + + if generator is not None: + return generator + elif expr.is_Add: + return reduce(add, list(map(_rebuild, expr.args))) + elif expr.is_Mul: + return reduce(mul, list(map(_rebuild, expr.args))) + elif expr.is_Pow or isinstance(expr, (ExpBase, Exp1)): + b, e = expr.as_base_exp() + # look for bg**eg whose integer power may be b**e + for gen, (bg, eg) in powers: + if bg == b and Mod(e, eg) == 0: + return mapping.get(gen)**int(e/eg) + if e.is_Integer and e is not S.One: + return _rebuild(b)**int(e) + elif mapping.get(1/expr) is not None: + return 1/mapping.get(1/expr) + + try: + return domain.convert(expr) + except CoercionFailed: + if not domain.is_Field and domain.has_assoc_Field: + return domain.get_field().convert(expr) + else: + raise + + return _rebuild(expr) + + def from_expr(self, expr): + mapping = dict(list(zip(self.symbols, self.gens))) + + try: + frac = self._rebuild_expr(sympify(expr), mapping) + except CoercionFailed: + raise ValueError("expected an expression convertible to a rational function in %s, got %s" % (self, expr)) + else: + return self.field_new(frac) + + def to_domain(self): + return FractionField(self) + + def to_ring(self): + return PolyRing(self.symbols, self.domain, self.order) + +class FracElement(DomainElement, DefaultPrinting, CantSympify): + """Element of multivariate distributed rational function field. """ + + def __init__(self, field, numer, denom=None): + if denom is None: + denom = field.ring.one + elif not denom: + raise ZeroDivisionError("zero denominator") + + self.field = field + self.numer = numer + self.denom = denom + + def raw_new(f, numer, denom=None): + return f.__class__(f.field, numer, denom) + + def new(f, numer, denom): + return f.raw_new(*numer.cancel(denom)) + + def to_poly(f): + if f.denom != 1: + raise ValueError("f.denom should be 1") + return f.numer + + def parent(self): + return self.field.to_domain() + + def __getnewargs__(self): + return (self.field, self.numer, self.denom) + + _hash = None + + def __hash__(self): + _hash = self._hash + if _hash is None: + self._hash = _hash = hash((self.field, self.numer, self.denom)) + return _hash + + def copy(self): + return self.raw_new(self.numer.copy(), self.denom.copy()) + + def set_field(self, new_field): + if self.field == new_field: + return self + else: + new_ring = new_field.ring + numer = self.numer.set_ring(new_ring) + denom = self.denom.set_ring(new_ring) + return new_field.new(numer, denom) + + def as_expr(self, *symbols): + return self.numer.as_expr(*symbols)/self.denom.as_expr(*symbols) + + def __eq__(f, g): + if isinstance(g, FracElement) and f.field == g.field: + return f.numer == g.numer and f.denom == g.denom + else: + return f.numer == g and f.denom == f.field.ring.one + + def __ne__(f, g): + return not f == g + + def __bool__(f): + return bool(f.numer) + + def sort_key(self): + return (self.denom.sort_key(), self.numer.sort_key()) + + def _cmp(f1, f2, op): + if f1.field.is_element(f2): + return op(f1.sort_key(), f2.sort_key()) + else: + return NotImplemented + + def __lt__(f1, f2): + return f1._cmp(f2, lt) + def __le__(f1, f2): + return f1._cmp(f2, le) + def __gt__(f1, f2): + return f1._cmp(f2, gt) + def __ge__(f1, f2): + return f1._cmp(f2, ge) + + def __pos__(f): + """Negate all coefficients in ``f``. """ + return f.raw_new(f.numer, f.denom) + + def __neg__(f): + """Negate all coefficients in ``f``. """ + return f.raw_new(-f.numer, f.denom) + + def _extract_ground(self, element): + domain = self.field.domain + + try: + element = domain.convert(element) + except CoercionFailed: + if not domain.is_Field and domain.has_assoc_Field: + ground_field = domain.get_field() + + try: + element = ground_field.convert(element) + except CoercionFailed: + pass + else: + return -1, ground_field.numer(element), ground_field.denom(element) + + return 0, None, None + else: + return 1, element, None + + def __add__(f, g): + """Add rational functions ``f`` and ``g``. """ + field = f.field + + if not g: + return f + elif not f: + return g + elif field.is_element(g): + if f.denom == g.denom: + return f.new(f.numer + g.numer, f.denom) + else: + return f.new(f.numer*g.denom + f.denom*g.numer, f.denom*g.denom) + elif field.ring.is_element(g): + return f.new(f.numer + f.denom*g, f.denom) + else: + if isinstance(g, FracElement): + if isinstance(field.domain, FractionField) and field.domain.field == g.field: + pass + elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: + return g.__radd__(f) + else: + return NotImplemented + elif isinstance(g, PolyElement): + if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: + pass + else: + return g.__radd__(f) + + return f.__radd__(g) + + def __radd__(f, c): + if f.field.ring.is_element(c): + return f.new(f.numer + f.denom*c, f.denom) + + op, g_numer, g_denom = f._extract_ground(c) + + if op == 1: + return f.new(f.numer + f.denom*g_numer, f.denom) + elif not op: + return NotImplemented + else: + return f.new(f.numer*g_denom + f.denom*g_numer, f.denom*g_denom) + + def __sub__(f, g): + """Subtract rational functions ``f`` and ``g``. """ + field = f.field + + if not g: + return f + elif not f: + return -g + elif field.is_element(g): + if f.denom == g.denom: + return f.new(f.numer - g.numer, f.denom) + else: + return f.new(f.numer*g.denom - f.denom*g.numer, f.denom*g.denom) + elif field.ring.is_element(g): + return f.new(f.numer - f.denom*g, f.denom) + else: + if isinstance(g, FracElement): + if isinstance(field.domain, FractionField) and field.domain.field == g.field: + pass + elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: + return g.__rsub__(f) + else: + return NotImplemented + elif isinstance(g, PolyElement): + if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: + pass + else: + return g.__rsub__(f) + + op, g_numer, g_denom = f._extract_ground(g) + + if op == 1: + return f.new(f.numer - f.denom*g_numer, f.denom) + elif not op: + return NotImplemented + else: + return f.new(f.numer*g_denom - f.denom*g_numer, f.denom*g_denom) + + def __rsub__(f, c): + if f.field.ring.is_element(c): + return f.new(-f.numer + f.denom*c, f.denom) + + op, g_numer, g_denom = f._extract_ground(c) + + if op == 1: + return f.new(-f.numer + f.denom*g_numer, f.denom) + elif not op: + return NotImplemented + else: + return f.new(-f.numer*g_denom + f.denom*g_numer, f.denom*g_denom) + + def __mul__(f, g): + """Multiply rational functions ``f`` and ``g``. """ + field = f.field + + if not f or not g: + return field.zero + elif field.is_element(g): + return f.new(f.numer*g.numer, f.denom*g.denom) + elif field.ring.is_element(g): + return f.new(f.numer*g, f.denom) + else: + if isinstance(g, FracElement): + if isinstance(field.domain, FractionField) and field.domain.field == g.field: + pass + elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: + return g.__rmul__(f) + else: + return NotImplemented + elif isinstance(g, PolyElement): + if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: + pass + else: + return g.__rmul__(f) + + return f.__rmul__(g) + + def __rmul__(f, c): + if f.field.ring.is_element(c): + return f.new(f.numer*c, f.denom) + + op, g_numer, g_denom = f._extract_ground(c) + + if op == 1: + return f.new(f.numer*g_numer, f.denom) + elif not op: + return NotImplemented + else: + return f.new(f.numer*g_numer, f.denom*g_denom) + + def __truediv__(f, g): + """Computes quotient of fractions ``f`` and ``g``. """ + field = f.field + + if not g: + raise ZeroDivisionError + elif field.is_element(g): + return f.new(f.numer*g.denom, f.denom*g.numer) + elif field.ring.is_element(g): + return f.new(f.numer, f.denom*g) + else: + if isinstance(g, FracElement): + if isinstance(field.domain, FractionField) and field.domain.field == g.field: + pass + elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: + return g.__rtruediv__(f) + else: + return NotImplemented + elif isinstance(g, PolyElement): + if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: + pass + else: + return g.__rtruediv__(f) + + op, g_numer, g_denom = f._extract_ground(g) + + if op == 1: + return f.new(f.numer, f.denom*g_numer) + elif not op: + return NotImplemented + else: + return f.new(f.numer*g_denom, f.denom*g_numer) + + def __rtruediv__(f, c): + if not f: + raise ZeroDivisionError + elif f.field.ring.is_element(c): + return f.new(f.denom*c, f.numer) + + op, g_numer, g_denom = f._extract_ground(c) + + if op == 1: + return f.new(f.denom*g_numer, f.numer) + elif not op: + return NotImplemented + else: + return f.new(f.denom*g_numer, f.numer*g_denom) + + def __pow__(f, n): + """Raise ``f`` to a non-negative power ``n``. """ + if n >= 0: + return f.raw_new(f.numer**n, f.denom**n) + elif not f: + raise ZeroDivisionError + else: + return f.raw_new(f.denom**-n, f.numer**-n) + + def diff(f, x): + """Computes partial derivative in ``x``. + + Examples + ======== + + >>> from sympy.polys.fields import field + >>> from sympy.polys.domains import ZZ + + >>> _, x, y, z = field("x,y,z", ZZ) + >>> ((x**2 + y)/(z + 1)).diff(x) + 2*x/(z + 1) + + """ + x = x.to_poly() + return f.new(f.numer.diff(x)*f.denom - f.numer*f.denom.diff(x), f.denom**2) + + def __call__(f, *values): + if 0 < len(values) <= f.field.ngens: + return f.evaluate(list(zip(f.field.gens, values))) + else: + raise ValueError("expected at least 1 and at most %s values, got %s" % (f.field.ngens, len(values))) + + def evaluate(f, x, a=None): + if isinstance(x, list) and a is None: + x = [ (X.to_poly(), a) for X, a in x ] + numer, denom = f.numer.evaluate(x), f.denom.evaluate(x) + else: + x = x.to_poly() + numer, denom = f.numer.evaluate(x, a), f.denom.evaluate(x, a) + + field = numer.ring.to_field() + return field.new(numer, denom) + + def subs(f, x, a=None): + if isinstance(x, list) and a is None: + x = [ (X.to_poly(), a) for X, a in x ] + numer, denom = f.numer.subs(x), f.denom.subs(x) + else: + x = x.to_poly() + numer, denom = f.numer.subs(x, a), f.denom.subs(x, a) + + return f.new(numer, denom) + + def compose(f, x, a=None): + raise NotImplementedError diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/galoistools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/galoistools.py new file mode 100644 index 0000000000000000000000000000000000000000..b09f85057eced59b8054c6007f2b291a35a2fafb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/galoistools.py @@ -0,0 +1,2532 @@ +"""Dense univariate polynomials with coefficients in Galois fields. """ + +from math import ceil as _ceil, sqrt as _sqrt, prod + +from sympy.core.random import uniform, _randint +from sympy.external.gmpy import SYMPY_INTS, MPZ, invert +from sympy.polys.polyconfig import query +from sympy.polys.polyerrors import ExactQuotientFailed +from sympy.polys.polyutils import _sort_factors + + +def gf_crt(U, M, K=None): + """ + Chinese Remainder Theorem. + + Given a set of integer residues ``u_0,...,u_n`` and a set of + co-prime integer moduli ``m_0,...,m_n``, returns an integer + ``u``, such that ``u = u_i mod m_i`` for ``i = ``0,...,n``. + + Examples + ======== + + Consider a set of residues ``U = [49, 76, 65]`` + and a set of moduli ``M = [99, 97, 95]``. Then we have:: + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_crt + + >>> gf_crt([49, 76, 65], [99, 97, 95], ZZ) + 639985 + + This is the correct result because:: + + >>> [639985 % m for m in [99, 97, 95]] + [49, 76, 65] + + Note: this is a low-level routine with no error checking. + + See Also + ======== + + sympy.ntheory.modular.crt : a higher level crt routine + sympy.ntheory.modular.solve_congruence + + """ + p = prod(M, start=K.one) + v = K.zero + + for u, m in zip(U, M): + e = p // m + s, _, _ = K.gcdex(e, m) + v += e*(u*s % m) + + return v % p + + +def gf_crt1(M, K): + """ + First part of the Chinese Remainder Theorem. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2 + >>> U = [49, 76, 65] + >>> M = [99, 97, 95] + + The following two codes have the same result. + + >>> gf_crt(U, M, ZZ) + 639985 + + >>> p, E, S = gf_crt1(M, ZZ) + >>> gf_crt2(U, M, p, E, S, ZZ) + 639985 + + However, it is faster when we want to fix ``M`` and + compute for multiple U, i.e. the following cases: + + >>> p, E, S = gf_crt1(M, ZZ) + >>> Us = [[49, 76, 65], [23, 42, 67]] + >>> for U in Us: + ... print(gf_crt2(U, M, p, E, S, ZZ)) + 639985 + 236237 + + See Also + ======== + + sympy.ntheory.modular.crt1 : a higher level crt routine + sympy.polys.galoistools.gf_crt + sympy.polys.galoistools.gf_crt2 + + """ + E, S = [], [] + p = prod(M, start=K.one) + + for m in M: + E.append(p // m) + S.append(K.gcdex(E[-1], m)[0] % m) + + return p, E, S + + +def gf_crt2(U, M, p, E, S, K): + """ + Second part of the Chinese Remainder Theorem. + + See ``gf_crt1`` for usage. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_crt2 + + >>> U = [49, 76, 65] + >>> M = [99, 97, 95] + >>> p = 912285 + >>> E = [9215, 9405, 9603] + >>> S = [62, 24, 12] + + >>> gf_crt2(U, M, p, E, S, ZZ) + 639985 + + See Also + ======== + + sympy.ntheory.modular.crt2 : a higher level crt routine + sympy.polys.galoistools.gf_crt + sympy.polys.galoistools.gf_crt1 + + """ + v = K.zero + + for u, m, e, s in zip(U, M, E, S): + v += e*(u*s % m) + + return v % p + + +def gf_int(a, p): + """ + Coerce ``a mod p`` to an integer in the range ``[-p/2, p/2]``. + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_int + + >>> gf_int(2, 7) + 2 + >>> gf_int(5, 7) + -2 + + """ + if a <= p // 2: + return a + else: + return a - p + + +def gf_degree(f): + """ + Return the leading degree of ``f``. + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_degree + + >>> gf_degree([1, 1, 2, 0]) + 3 + >>> gf_degree([]) + -1 + + """ + return len(f) - 1 + + +def gf_LC(f, K): + """ + Return the leading coefficient of ``f``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_LC + + >>> gf_LC([3, 0, 1], ZZ) + 3 + + """ + if not f: + return K.zero + else: + return f[0] + + +def gf_TC(f, K): + """ + Return the trailing coefficient of ``f``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_TC + + >>> gf_TC([3, 0, 1], ZZ) + 1 + + """ + if not f: + return K.zero + else: + return f[-1] + + +def gf_strip(f): + """ + Remove leading zeros from ``f``. + + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_strip + + >>> gf_strip([0, 0, 0, 3, 0, 1]) + [3, 0, 1] + + """ + if not f or f[0]: + return f + + k = 0 + + for coeff in f: + if coeff: + break + else: + k += 1 + + return f[k:] + + +def gf_trunc(f, p): + """ + Reduce all coefficients modulo ``p``. + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_trunc + + >>> gf_trunc([7, -2, 3], 5) + [2, 3, 3] + + """ + return gf_strip([ a % p for a in f ]) + + +def gf_normal(f, p, K): + """ + Normalize all coefficients in ``K``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_normal + + >>> gf_normal([5, 10, 21, -3], 5, ZZ) + [1, 2] + + """ + return gf_trunc(list(map(K, f)), p) + + +def gf_from_dict(f, p, K): + """ + Create a ``GF(p)[x]`` polynomial from a dict. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_from_dict + + >>> gf_from_dict({10: ZZ(4), 4: ZZ(33), 0: ZZ(-1)}, 5, ZZ) + [4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4] + + """ + n, h = max(f.keys()), [] + + if isinstance(n, SYMPY_INTS): + for k in range(n, -1, -1): + h.append(f.get(k, K.zero) % p) + else: + (n,) = n + + for k in range(n, -1, -1): + h.append(f.get((k,), K.zero) % p) + + return gf_trunc(h, p) + + +def gf_to_dict(f, p, symmetric=True): + """ + Convert a ``GF(p)[x]`` polynomial to a dict. + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_to_dict + + >>> gf_to_dict([4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4], 5) + {0: -1, 4: -2, 10: -1} + >>> gf_to_dict([4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4], 5, symmetric=False) + {0: 4, 4: 3, 10: 4} + + """ + n, result = gf_degree(f), {} + + for k in range(0, n + 1): + if symmetric: + a = gf_int(f[n - k], p) + else: + a = f[n - k] + + if a: + result[k] = a + + return result + + +def gf_from_int_poly(f, p): + """ + Create a ``GF(p)[x]`` polynomial from ``Z[x]``. + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_from_int_poly + + >>> gf_from_int_poly([7, -2, 3], 5) + [2, 3, 3] + + """ + return gf_trunc(f, p) + + +def gf_to_int_poly(f, p, symmetric=True): + """ + Convert a ``GF(p)[x]`` polynomial to ``Z[x]``. + + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_to_int_poly + + >>> gf_to_int_poly([2, 3, 3], 5) + [2, -2, -2] + >>> gf_to_int_poly([2, 3, 3], 5, symmetric=False) + [2, 3, 3] + + """ + if symmetric: + return [ gf_int(c, p) for c in f ] + else: + return f + + +def gf_neg(f, p, K): + """ + Negate a polynomial in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_neg + + >>> gf_neg([3, 2, 1, 0], 5, ZZ) + [2, 3, 4, 0] + + """ + return [ -coeff % p for coeff in f ] + + +def gf_add_ground(f, a, p, K): + """ + Compute ``f + a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_add_ground + + >>> gf_add_ground([3, 2, 4], 2, 5, ZZ) + [3, 2, 1] + + """ + if not f: + a = a % p + else: + a = (f[-1] + a) % p + + if len(f) > 1: + return f[:-1] + [a] + + if not a: + return [] + else: + return [a] + + +def gf_sub_ground(f, a, p, K): + """ + Compute ``f - a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_sub_ground + + >>> gf_sub_ground([3, 2, 4], 2, 5, ZZ) + [3, 2, 2] + + """ + if not f: + a = -a % p + else: + a = (f[-1] - a) % p + + if len(f) > 1: + return f[:-1] + [a] + + if not a: + return [] + else: + return [a] + + +def gf_mul_ground(f, a, p, K): + """ + Compute ``f * a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_mul_ground + + >>> gf_mul_ground([3, 2, 4], 2, 5, ZZ) + [1, 4, 3] + + """ + if not a: + return [] + else: + return [ (a*b) % p for b in f ] + + +def gf_quo_ground(f, a, p, K): + """ + Compute ``f/a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_quo_ground + + >>> gf_quo_ground(ZZ.map([3, 2, 4]), ZZ(2), 5, ZZ) + [4, 1, 2] + + """ + return gf_mul_ground(f, K.invert(a, p), p, K) + + +def gf_add(f, g, p, K): + """ + Add polynomials in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_add + + >>> gf_add([3, 2, 4], [2, 2, 2], 5, ZZ) + [4, 1] + + """ + if not f: + return g + if not g: + return f + + df = gf_degree(f) + dg = gf_degree(g) + + if df == dg: + return gf_strip([ (a + b) % p for a, b in zip(f, g) ]) + else: + k = abs(df - dg) + + if df > dg: + h, f = f[:k], f[k:] + else: + h, g = g[:k], g[k:] + + return h + [ (a + b) % p for a, b in zip(f, g) ] + + +def gf_sub(f, g, p, K): + """ + Subtract polynomials in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_sub + + >>> gf_sub([3, 2, 4], [2, 2, 2], 5, ZZ) + [1, 0, 2] + + """ + if not g: + return f + if not f: + return gf_neg(g, p, K) + + df = gf_degree(f) + dg = gf_degree(g) + + if df == dg: + return gf_strip([ (a - b) % p for a, b in zip(f, g) ]) + else: + k = abs(df - dg) + + if df > dg: + h, f = f[:k], f[k:] + else: + h, g = gf_neg(g[:k], p, K), g[k:] + + return h + [ (a - b) % p for a, b in zip(f, g) ] + + +def gf_mul(f, g, p, K): + """ + Multiply polynomials in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_mul + + >>> gf_mul([3, 2, 4], [2, 2, 2], 5, ZZ) + [1, 0, 3, 2, 3] + + """ + df = gf_degree(f) + dg = gf_degree(g) + + dh = df + dg + h = [0]*(dh + 1) + + for i in range(0, dh + 1): + coeff = K.zero + + for j in range(max(0, i - dg), min(i, df) + 1): + coeff += f[j]*g[i - j] + + h[i] = coeff % p + + return gf_strip(h) + + +def gf_sqr(f, p, K): + """ + Square polynomials in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_sqr + + >>> gf_sqr([3, 2, 4], 5, ZZ) + [4, 2, 3, 1, 1] + + """ + df = gf_degree(f) + + dh = 2*df + h = [0]*(dh + 1) + + for i in range(0, dh + 1): + coeff = K.zero + + jmin = max(0, i - df) + jmax = min(i, df) + + n = jmax - jmin + 1 + + jmax = jmin + n // 2 - 1 + + for j in range(jmin, jmax + 1): + coeff += f[j]*f[i - j] + + coeff += coeff + + if n & 1: + elem = f[jmax + 1] + coeff += elem**2 + + h[i] = coeff % p + + return gf_strip(h) + + +def gf_add_mul(f, g, h, p, K): + """ + Returns ``f + g*h`` where ``f``, ``g``, ``h`` in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_add_mul + >>> gf_add_mul([3, 2, 4], [2, 2, 2], [1, 4], 5, ZZ) + [2, 3, 2, 2] + """ + return gf_add(f, gf_mul(g, h, p, K), p, K) + + +def gf_sub_mul(f, g, h, p, K): + """ + Compute ``f - g*h`` where ``f``, ``g``, ``h`` in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_sub_mul + + >>> gf_sub_mul([3, 2, 4], [2, 2, 2], [1, 4], 5, ZZ) + [3, 3, 2, 1] + + """ + return gf_sub(f, gf_mul(g, h, p, K), p, K) + + +def gf_expand(F, p, K): + """ + Expand results of :func:`~.factor` in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_expand + + >>> gf_expand([([3, 2, 4], 1), ([2, 2], 2), ([3, 1], 3)], 5, ZZ) + [4, 3, 0, 3, 0, 1, 4, 1] + + """ + if isinstance(F, tuple): + lc, F = F + else: + lc = K.one + + g = [lc] + + for f, k in F: + f = gf_pow(f, k, p, K) + g = gf_mul(g, f, p, K) + + return g + + +def gf_div(f, g, p, K): + """ + Division with remainder in ``GF(p)[x]``. + + Given univariate polynomials ``f`` and ``g`` with coefficients in a + finite field with ``p`` elements, returns polynomials ``q`` and ``r`` + (quotient and remainder) such that ``f = q*g + r``. + + Consider polynomials ``x**3 + x + 1`` and ``x**2 + x`` in GF(2):: + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_div, gf_add_mul + + >>> gf_div(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) + ([1, 1], [1]) + + As result we obtained quotient ``x + 1`` and remainder ``1``, thus:: + + >>> gf_add_mul(ZZ.map([1]), ZZ.map([1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) + [1, 0, 1, 1] + + References + ========== + + .. [1] [Monagan93]_ + .. [2] [Gathen99]_ + + """ + df = gf_degree(f) + dg = gf_degree(g) + + if not g: + raise ZeroDivisionError("polynomial division") + elif df < dg: + return [], f + + inv = K.invert(g[0], p) + + h, dq, dr = list(f), df - dg, dg - 1 + + for i in range(0, df + 1): + coeff = h[i] + + for j in range(max(0, dg - i), min(df - i, dr) + 1): + coeff -= h[i + j - dg] * g[dg - j] + + if i <= dq: + coeff *= inv + + h[i] = coeff % p + + return h[:dq + 1], gf_strip(h[dq + 1:]) + + +def gf_rem(f, g, p, K): + """ + Compute polynomial remainder in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_rem + + >>> gf_rem(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) + [1] + + """ + return gf_div(f, g, p, K)[1] + + +def gf_quo(f, g, p, K): + """ + Compute exact quotient in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_quo + + >>> gf_quo(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) + [1, 1] + >>> gf_quo(ZZ.map([1, 0, 3, 2, 3]), ZZ.map([2, 2, 2]), 5, ZZ) + [3, 2, 4] + + """ + df = gf_degree(f) + dg = gf_degree(g) + + if not g: + raise ZeroDivisionError("polynomial division") + elif df < dg: + return [] + + inv = K.invert(g[0], p) + + h, dq, dr = f[:], df - dg, dg - 1 + + for i in range(0, dq + 1): + coeff = h[i] + + for j in range(max(0, dg - i), min(df - i, dr) + 1): + coeff -= h[i + j - dg] * g[dg - j] + + h[i] = (coeff * inv) % p + + return h[:dq + 1] + + +def gf_exquo(f, g, p, K): + """ + Compute polynomial quotient in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_exquo + + >>> gf_exquo(ZZ.map([1, 0, 3, 2, 3]), ZZ.map([2, 2, 2]), 5, ZZ) + [3, 2, 4] + + >>> gf_exquo(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ) + Traceback (most recent call last): + ... + ExactQuotientFailed: [1, 1, 0] does not divide [1, 0, 1, 1] + + """ + q, r = gf_div(f, g, p, K) + + if not r: + return q + else: + raise ExactQuotientFailed(f, g) + + +def gf_lshift(f, n, K): + """ + Efficiently multiply ``f`` by ``x**n``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_lshift + + >>> gf_lshift([3, 2, 4], 4, ZZ) + [3, 2, 4, 0, 0, 0, 0] + + """ + if not f: + return f + else: + return f + [K.zero]*n + + +def gf_rshift(f, n, K): + """ + Efficiently divide ``f`` by ``x**n``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_rshift + + >>> gf_rshift([1, 2, 3, 4, 0], 3, ZZ) + ([1, 2], [3, 4, 0]) + + """ + if not n: + return f, [] + else: + return f[:-n], f[-n:] + + +def gf_pow(f, n, p, K): + """ + Compute ``f**n`` in ``GF(p)[x]`` using repeated squaring. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_pow + + >>> gf_pow([3, 2, 4], 3, 5, ZZ) + [2, 4, 4, 2, 2, 1, 4] + + """ + if not n: + return [K.one] + elif n == 1: + return f + elif n == 2: + return gf_sqr(f, p, K) + + h = [K.one] + + while True: + if n & 1: + h = gf_mul(h, f, p, K) + n -= 1 + + n >>= 1 + + if not n: + break + + f = gf_sqr(f, p, K) + + return h + +def gf_frobenius_monomial_base(g, p, K): + """ + return the list of ``x**(i*p) mod g in Z_p`` for ``i = 0, .., n - 1`` + where ``n = gf_degree(g)`` + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_frobenius_monomial_base + >>> g = ZZ.map([1, 0, 2, 1]) + >>> gf_frobenius_monomial_base(g, 5, ZZ) + [[1], [4, 4, 2], [1, 2]] + + """ + n = gf_degree(g) + if n == 0: + return [] + b = [0]*n + b[0] = [1] + if p < n: + for i in range(1, n): + mon = gf_lshift(b[i - 1], p, K) + b[i] = gf_rem(mon, g, p, K) + elif n > 1: + b[1] = gf_pow_mod([K.one, K.zero], p, g, p, K) + for i in range(2, n): + b[i] = gf_mul(b[i - 1], b[1], p, K) + b[i] = gf_rem(b[i], g, p, K) + + return b + +def gf_frobenius_map(f, g, b, p, K): + """ + compute gf_pow_mod(f, p, g, p, K) using the Frobenius map + + Parameters + ========== + + f, g : polynomials in ``GF(p)[x]`` + b : frobenius monomial base + p : prime number + K : domain + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_frobenius_monomial_base, gf_frobenius_map + >>> f = ZZ.map([2, 1, 0, 1]) + >>> g = ZZ.map([1, 0, 2, 1]) + >>> p = 5 + >>> b = gf_frobenius_monomial_base(g, p, ZZ) + >>> r = gf_frobenius_map(f, g, b, p, ZZ) + >>> gf_frobenius_map(f, g, b, p, ZZ) + [4, 0, 3] + """ + m = gf_degree(g) + if gf_degree(f) >= m: + f = gf_rem(f, g, p, K) + if not f: + return [] + n = gf_degree(f) + sf = [f[-1]] + for i in range(1, n + 1): + v = gf_mul_ground(b[i], f[n - i], p, K) + sf = gf_add(sf, v, p, K) + return sf + +def _gf_pow_pnm1d2(f, n, g, b, p, K): + """ + utility function for ``gf_edf_zassenhaus`` + Compute ``f**((p**n - 1) // 2)`` in ``GF(p)[x]/(g)`` + ``f**((p**n - 1) // 2) = (f*f**p*...*f**(p**n - 1))**((p - 1) // 2)`` + """ + f = gf_rem(f, g, p, K) + h = f + r = f + for i in range(1, n): + h = gf_frobenius_map(h, g, b, p, K) + r = gf_mul(r, h, p, K) + r = gf_rem(r, g, p, K) + + res = gf_pow_mod(r, (p - 1)//2, g, p, K) + return res + +def gf_pow_mod(f, n, g, p, K): + """ + Compute ``f**n`` in ``GF(p)[x]/(g)`` using repeated squaring. + + Given polynomials ``f`` and ``g`` in ``GF(p)[x]`` and a non-negative + integer ``n``, efficiently computes ``f**n (mod g)`` i.e. the remainder + of ``f**n`` from division by ``g``, using the repeated squaring algorithm. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_pow_mod + + >>> gf_pow_mod(ZZ.map([3, 2, 4]), 3, ZZ.map([1, 1]), 5, ZZ) + [] + + References + ========== + + .. [1] [Gathen99]_ + + """ + if not n: + return [K.one] + elif n == 1: + return gf_rem(f, g, p, K) + elif n == 2: + return gf_rem(gf_sqr(f, p, K), g, p, K) + + h = [K.one] + + while True: + if n & 1: + h = gf_mul(h, f, p, K) + h = gf_rem(h, g, p, K) + n -= 1 + + n >>= 1 + + if not n: + break + + f = gf_sqr(f, p, K) + f = gf_rem(f, g, p, K) + + return h + + +def gf_gcd(f, g, p, K): + """ + Euclidean Algorithm in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_gcd + + >>> gf_gcd(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ) + [1, 3] + + """ + while g: + f, g = g, gf_rem(f, g, p, K) + + return gf_monic(f, p, K)[1] + + +def gf_lcm(f, g, p, K): + """ + Compute polynomial LCM in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_lcm + + >>> gf_lcm(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ) + [1, 2, 0, 4] + + """ + if not f or not g: + return [] + + h = gf_quo(gf_mul(f, g, p, K), + gf_gcd(f, g, p, K), p, K) + + return gf_monic(h, p, K)[1] + + +def gf_cofactors(f, g, p, K): + """ + Compute polynomial GCD and cofactors in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_cofactors + + >>> gf_cofactors(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ) + ([1, 3], [3, 3], [2, 1]) + + """ + if not f and not g: + return ([], [], []) + + h = gf_gcd(f, g, p, K) + + return (h, gf_quo(f, h, p, K), + gf_quo(g, h, p, K)) + + +def gf_gcdex(f, g, p, K): + """ + Extended Euclidean Algorithm in ``GF(p)[x]``. + + Given polynomials ``f`` and ``g`` in ``GF(p)[x]``, computes polynomials + ``s``, ``t`` and ``h``, such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. + The typical application of EEA is solving polynomial diophantine equations. + + Consider polynomials ``f = (x + 7) (x + 1)``, ``g = (x + 7) (x**2 + 1)`` + in ``GF(11)[x]``. Application of Extended Euclidean Algorithm gives:: + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_gcdex, gf_mul, gf_add + + >>> s, t, g = gf_gcdex(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) + >>> s, t, g + ([5, 6], [6], [1, 7]) + + As result we obtained polynomials ``s = 5*x + 6`` and ``t = 6``, and + additionally ``gcd(f, g) = x + 7``. This is correct because:: + + >>> S = gf_mul(s, ZZ.map([1, 8, 7]), 11, ZZ) + >>> T = gf_mul(t, ZZ.map([1, 7, 1, 7]), 11, ZZ) + + >>> gf_add(S, T, 11, ZZ) == [1, 7] + True + + References + ========== + + .. [1] [Gathen99]_ + + """ + if not (f or g): + return [K.one], [], [] + + p0, r0 = gf_monic(f, p, K) + p1, r1 = gf_monic(g, p, K) + + if not f: + return [], [K.invert(p1, p)], r1 + if not g: + return [K.invert(p0, p)], [], r0 + + s0, s1 = [K.invert(p0, p)], [] + t0, t1 = [], [K.invert(p1, p)] + + while True: + Q, R = gf_div(r0, r1, p, K) + + if not R: + break + + (lc, r1), r0 = gf_monic(R, p, K), r1 + + inv = K.invert(lc, p) + + s = gf_sub_mul(s0, s1, Q, p, K) + t = gf_sub_mul(t0, t1, Q, p, K) + + s1, s0 = gf_mul_ground(s, inv, p, K), s1 + t1, t0 = gf_mul_ground(t, inv, p, K), t1 + + return s1, t1, r1 + + +def gf_monic(f, p, K): + """ + Compute LC and a monic polynomial in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_monic + + >>> gf_monic(ZZ.map([3, 2, 4]), 5, ZZ) + (3, [1, 4, 3]) + + """ + if not f: + return K.zero, [] + else: + lc = f[0] + + if K.is_one(lc): + return lc, list(f) + else: + return lc, gf_quo_ground(f, lc, p, K) + + +def gf_diff(f, p, K): + """ + Differentiate polynomial in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_diff + + >>> gf_diff([3, 2, 4], 5, ZZ) + [1, 2] + + """ + df = gf_degree(f) + + h, n = [K.zero]*df, df + + for coeff in f[:-1]: + coeff *= K(n) + coeff %= p + + if coeff: + h[df - n] = coeff + + n -= 1 + + return gf_strip(h) + + +def gf_eval(f, a, p, K): + """ + Evaluate ``f(a)`` in ``GF(p)`` using Horner scheme. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_eval + + >>> gf_eval([3, 2, 4], 2, 5, ZZ) + 0 + + """ + result = K.zero + + for c in f: + result *= a + result += c + result %= p + + return result + + +def gf_multi_eval(f, A, p, K): + """ + Evaluate ``f(a)`` for ``a`` in ``[a_1, ..., a_n]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_multi_eval + + >>> gf_multi_eval([3, 2, 4], [0, 1, 2, 3, 4], 5, ZZ) + [4, 4, 0, 2, 0] + + """ + return [ gf_eval(f, a, p, K) for a in A ] + + +def gf_compose(f, g, p, K): + """ + Compute polynomial composition ``f(g)`` in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_compose + + >>> gf_compose([3, 2, 4], [2, 2, 2], 5, ZZ) + [2, 4, 0, 3, 0] + + """ + if len(g) <= 1: + return gf_strip([gf_eval(f, gf_LC(g, K), p, K)]) + + if not f: + return [] + + h = [f[0]] + + for c in f[1:]: + h = gf_mul(h, g, p, K) + h = gf_add_ground(h, c, p, K) + + return h + + +def gf_compose_mod(g, h, f, p, K): + """ + Compute polynomial composition ``g(h)`` in ``GF(p)[x]/(f)``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_compose_mod + + >>> gf_compose_mod(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 2]), ZZ.map([4, 3]), 5, ZZ) + [4] + + """ + if not g: + return [] + + comp = [g[0]] + + for a in g[1:]: + comp = gf_mul(comp, h, p, K) + comp = gf_add_ground(comp, a, p, K) + comp = gf_rem(comp, f, p, K) + + return comp + + +def gf_trace_map(a, b, c, n, f, p, K): + """ + Compute polynomial trace map in ``GF(p)[x]/(f)``. + + Given a polynomial ``f`` in ``GF(p)[x]``, polynomials ``a``, ``b``, + ``c`` in the quotient ring ``GF(p)[x]/(f)`` such that ``b = c**t + (mod f)`` for some positive power ``t`` of ``p``, and a positive + integer ``n``, returns a mapping:: + + a -> a**t**n, a + a**t + a**t**2 + ... + a**t**n (mod f) + + In factorization context, ``b = x**p mod f`` and ``c = x mod f``. + This way we can efficiently compute trace polynomials in equal + degree factorization routine, much faster than with other methods, + like iterated Frobenius algorithm, for large degrees. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_trace_map + + >>> gf_trace_map([1, 2], [4, 4], [1, 1], 4, [3, 2, 4], 5, ZZ) + ([1, 3], [1, 3]) + + References + ========== + + .. [1] [Gathen92]_ + + """ + u = gf_compose_mod(a, b, f, p, K) + v = b + + if n & 1: + U = gf_add(a, u, p, K) + V = b + else: + U = a + V = c + + n >>= 1 + + while n: + u = gf_add(u, gf_compose_mod(u, v, f, p, K), p, K) + v = gf_compose_mod(v, v, f, p, K) + + if n & 1: + U = gf_add(U, gf_compose_mod(u, V, f, p, K), p, K) + V = gf_compose_mod(v, V, f, p, K) + + n >>= 1 + + return gf_compose_mod(a, V, f, p, K), U + +def _gf_trace_map(f, n, g, b, p, K): + """ + utility for ``gf_edf_shoup`` + """ + f = gf_rem(f, g, p, K) + h = f + r = f + for i in range(1, n): + h = gf_frobenius_map(h, g, b, p, K) + r = gf_add(r, h, p, K) + r = gf_rem(r, g, p, K) + return r + + +def gf_random(n, p, K): + """ + Generate a random polynomial in ``GF(p)[x]`` of degree ``n``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_random + >>> gf_random(10, 5, ZZ) #doctest: +SKIP + [1, 2, 3, 2, 1, 1, 1, 2, 0, 4, 2] + + """ + pi = int(p) + return [K.one] + [ K(int(uniform(0, pi))) for i in range(0, n) ] + + +def gf_irreducible(n, p, K): + """ + Generate random irreducible polynomial of degree ``n`` in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_irreducible + >>> gf_irreducible(10, 5, ZZ) #doctest: +SKIP + [1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4] + + """ + while True: + f = gf_random(n, p, K) + if gf_irreducible_p(f, p, K): + return f + + +def gf_irred_p_ben_or(f, p, K): + """ + Ben-Or's polynomial irreducibility test over finite fields. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_irred_p_ben_or + + >>> gf_irred_p_ben_or(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ) + True + >>> gf_irred_p_ben_or(ZZ.map([3, 2, 4]), 5, ZZ) + False + + """ + n = gf_degree(f) + + if n <= 1: + return True + + _, f = gf_monic(f, p, K) + if n < 5: + H = h = gf_pow_mod([K.one, K.zero], p, f, p, K) + + for i in range(0, n//2): + g = gf_sub(h, [K.one, K.zero], p, K) + + if gf_gcd(f, g, p, K) == [K.one]: + h = gf_compose_mod(h, H, f, p, K) + else: + return False + else: + b = gf_frobenius_monomial_base(f, p, K) + H = h = gf_frobenius_map([K.one, K.zero], f, b, p, K) + for i in range(0, n//2): + g = gf_sub(h, [K.one, K.zero], p, K) + if gf_gcd(f, g, p, K) == [K.one]: + h = gf_frobenius_map(h, f, b, p, K) + else: + return False + + return True + + +def gf_irred_p_rabin(f, p, K): + """ + Rabin's polynomial irreducibility test over finite fields. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_irred_p_rabin + + >>> gf_irred_p_rabin(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ) + True + >>> gf_irred_p_rabin(ZZ.map([3, 2, 4]), 5, ZZ) + False + + """ + n = gf_degree(f) + + if n <= 1: + return True + + _, f = gf_monic(f, p, K) + + x = [K.one, K.zero] + + from sympy.ntheory import factorint + + indices = { n//d for d in factorint(n) } + + b = gf_frobenius_monomial_base(f, p, K) + h = b[1] + + for i in range(1, n): + if i in indices: + g = gf_sub(h, x, p, K) + + if gf_gcd(f, g, p, K) != [K.one]: + return False + + h = gf_frobenius_map(h, f, b, p, K) + + return h == x + +_irred_methods = { + 'ben-or': gf_irred_p_ben_or, + 'rabin': gf_irred_p_rabin, +} + + +def gf_irreducible_p(f, p, K): + """ + Test irreducibility of a polynomial ``f`` in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_irreducible_p + + >>> gf_irreducible_p(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ) + True + >>> gf_irreducible_p(ZZ.map([3, 2, 4]), 5, ZZ) + False + + """ + method = query('GF_IRRED_METHOD') + + if method is not None: + irred = _irred_methods[method](f, p, K) + else: + irred = gf_irred_p_rabin(f, p, K) + + return irred + + +def gf_sqf_p(f, p, K): + """ + Return ``True`` if ``f`` is square-free in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_sqf_p + + >>> gf_sqf_p(ZZ.map([3, 2, 4]), 5, ZZ) + True + >>> gf_sqf_p(ZZ.map([2, 4, 4, 2, 2, 1, 4]), 5, ZZ) + False + + """ + _, f = gf_monic(f, p, K) + + if not f: + return True + else: + return gf_gcd(f, gf_diff(f, p, K), p, K) == [K.one] + + +def gf_sqf_part(f, p, K): + """ + Return square-free part of a ``GF(p)[x]`` polynomial. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_sqf_part + + >>> gf_sqf_part(ZZ.map([1, 1, 3, 0, 1, 0, 2, 2, 1]), 5, ZZ) + [1, 4, 3] + + """ + _, sqf = gf_sqf_list(f, p, K) + + g = [K.one] + + for f, _ in sqf: + g = gf_mul(g, f, p, K) + + return g + + +def gf_sqf_list(f, p, K, all=False): + """ + Return the square-free decomposition of a ``GF(p)[x]`` polynomial. + + Given a polynomial ``f`` in ``GF(p)[x]``, returns the leading coefficient + of ``f`` and a square-free decomposition ``f_1**e_1 f_2**e_2 ... f_k**e_k`` + such that all ``f_i`` are monic polynomials and ``(f_i, f_j)`` for ``i != j`` + are co-prime and ``e_1 ... e_k`` are given in increasing order. All trivial + terms (i.e. ``f_i = 1``) are not included in the output. + + Consider polynomial ``f = x**11 + 1`` over ``GF(11)[x]``:: + + >>> from sympy.polys.domains import ZZ + + >>> from sympy.polys.galoistools import ( + ... gf_from_dict, gf_diff, gf_sqf_list, gf_pow, + ... ) + ... # doctest: +NORMALIZE_WHITESPACE + + >>> f = gf_from_dict({11: ZZ(1), 0: ZZ(1)}, 11, ZZ) + + Note that ``f'(x) = 0``:: + + >>> gf_diff(f, 11, ZZ) + [] + + This phenomenon does not happen in characteristic zero. However we can + still compute square-free decomposition of ``f`` using ``gf_sqf()``:: + + >>> gf_sqf_list(f, 11, ZZ) + (1, [([1, 1], 11)]) + + We obtained factorization ``f = (x + 1)**11``. This is correct because:: + + >>> gf_pow([1, 1], 11, 11, ZZ) == f + True + + References + ========== + + .. [1] [Geddes92]_ + + """ + n, sqf, factors, r = 1, False, [], int(p) + + lc, f = gf_monic(f, p, K) + + if gf_degree(f) < 1: + return lc, [] + + while True: + F = gf_diff(f, p, K) + + if F != []: + g = gf_gcd(f, F, p, K) + h = gf_quo(f, g, p, K) + + i = 1 + + while h != [K.one]: + G = gf_gcd(g, h, p, K) + H = gf_quo(h, G, p, K) + + if gf_degree(H) > 0: + factors.append((H, i*n)) + + g, h, i = gf_quo(g, G, p, K), G, i + 1 + + if g == [K.one]: + sqf = True + else: + f = g + + if not sqf: + d = gf_degree(f) // r + + for i in range(0, d + 1): + f[i] = f[i*r] + + f, n = f[:d + 1], n*r + else: + break + + if all: + raise ValueError("'all=True' is not supported yet") + + return lc, factors + + +def gf_Qmatrix(f, p, K): + """ + Calculate Berlekamp's ``Q`` matrix. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_Qmatrix + + >>> gf_Qmatrix([3, 2, 4], 5, ZZ) + [[1, 0], + [3, 4]] + + >>> gf_Qmatrix([1, 0, 0, 0, 1], 5, ZZ) + [[1, 0, 0, 0], + [0, 4, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 4]] + + """ + n, r = gf_degree(f), int(p) + + q = [K.one] + [K.zero]*(n - 1) + Q = [list(q)] + [[]]*(n - 1) + + for i in range(1, (n - 1)*r + 1): + qq, c = [(-q[-1]*f[-1]) % p], q[-1] + + for j in range(1, n): + qq.append((q[j - 1] - c*f[-j - 1]) % p) + + if not (i % r): + Q[i//r] = list(qq) + + q = qq + + return Q + + +def gf_Qbasis(Q, p, K): + """ + Compute a basis of the kernel of ``Q``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_Qmatrix, gf_Qbasis + + >>> gf_Qbasis(gf_Qmatrix([1, 0, 0, 0, 1], 5, ZZ), 5, ZZ) + [[1, 0, 0, 0], [0, 0, 1, 0]] + + >>> gf_Qbasis(gf_Qmatrix([3, 2, 4], 5, ZZ), 5, ZZ) + [[1, 0]] + + """ + Q, n = [ list(q) for q in Q ], len(Q) + + for k in range(0, n): + Q[k][k] = (Q[k][k] - K.one) % p + + for k in range(0, n): + for i in range(k, n): + if Q[k][i]: + break + else: + continue + + inv = K.invert(Q[k][i], p) + + for j in range(0, n): + Q[j][i] = (Q[j][i]*inv) % p + + for j in range(0, n): + t = Q[j][k] + Q[j][k] = Q[j][i] + Q[j][i] = t + + for i in range(0, n): + if i != k: + q = Q[k][i] + + for j in range(0, n): + Q[j][i] = (Q[j][i] - Q[j][k]*q) % p + + for i in range(0, n): + for j in range(0, n): + if i == j: + Q[i][j] = (K.one - Q[i][j]) % p + else: + Q[i][j] = (-Q[i][j]) % p + + basis = [] + + for q in Q: + if any(q): + basis.append(q) + + return basis + + +def gf_berlekamp(f, p, K): + """ + Factor a square-free ``f`` in ``GF(p)[x]`` for small ``p``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_berlekamp + + >>> gf_berlekamp([1, 0, 0, 0, 1], 5, ZZ) + [[1, 0, 2], [1, 0, 3]] + + """ + Q = gf_Qmatrix(f, p, K) + V = gf_Qbasis(Q, p, K) + + for i, v in enumerate(V): + V[i] = gf_strip(list(reversed(v))) + + factors = [f] + + for k in range(1, len(V)): + for f in list(factors): + s = K.zero + + while s < p: + g = gf_sub_ground(V[k], s, p, K) + h = gf_gcd(f, g, p, K) + + if h != [K.one] and h != f: + factors.remove(f) + + f = gf_quo(f, h, p, K) + factors.extend([f, h]) + + if len(factors) == len(V): + return _sort_factors(factors, multiple=False) + + s += K.one + + return _sort_factors(factors, multiple=False) + + +def gf_ddf_zassenhaus(f, p, K): + """ + Cantor-Zassenhaus: Deterministic Distinct Degree Factorization + + Given a monic square-free polynomial ``f`` in ``GF(p)[x]``, computes + partial distinct degree factorization ``f_1 ... f_d`` of ``f`` where + ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a + list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0`` + is an argument to the equal degree factorization routine. + + Consider the polynomial ``x**15 - 1`` in ``GF(11)[x]``:: + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_from_dict + + >>> f = gf_from_dict({15: ZZ(1), 0: ZZ(-1)}, 11, ZZ) + + Distinct degree factorization gives:: + + >>> from sympy.polys.galoistools import gf_ddf_zassenhaus + + >>> gf_ddf_zassenhaus(f, 11, ZZ) + [([1, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 2)] + + which means ``x**15 - 1 = (x**5 - 1) (x**10 + x**5 + 1)``. To obtain + factorization into irreducibles, use equal degree factorization + procedure (EDF) with each of the factors. + + References + ========== + + .. [1] [Gathen99]_ + .. [2] [Geddes92]_ + + """ + i, g, factors = 1, [K.one, K.zero], [] + + b = gf_frobenius_monomial_base(f, p, K) + while 2*i <= gf_degree(f): + g = gf_frobenius_map(g, f, b, p, K) + h = gf_gcd(f, gf_sub(g, [K.one, K.zero], p, K), p, K) + + if h != [K.one]: + factors.append((h, i)) + + f = gf_quo(f, h, p, K) + g = gf_rem(g, f, p, K) + b = gf_frobenius_monomial_base(f, p, K) + + i += 1 + + if f != [K.one]: + return factors + [(f, gf_degree(f))] + else: + return factors + + +def gf_edf_zassenhaus(f, n, p, K): + """ + Cantor-Zassenhaus: Probabilistic Equal Degree Factorization + + Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and + an integer ``n``, such that ``n`` divides ``deg(f)``, returns all + irreducible factors ``f_1,...,f_d`` of ``f``, each of degree ``n``. + EDF procedure gives complete factorization over Galois fields. + + Consider the square-free polynomial ``f = x**3 + x**2 + x + 1`` in + ``GF(5)[x]``. Let's compute its irreducible factors of degree one:: + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_edf_zassenhaus + + >>> gf_edf_zassenhaus([1,1,1,1], 1, 5, ZZ) + [[1, 1], [1, 2], [1, 3]] + + Notes + ===== + + The case p == 2 is handled by Cohen's Algorithm 3.4.8. The case p odd is + as in Geddes Algorithm 8.9 (or Cohen's Algorithm 3.4.6). + + References + ========== + + .. [1] [Gathen99]_ + .. [2] [Geddes92]_ Algorithm 8.9 + .. [3] [Cohen93]_ Algorithm 3.4.8 + + """ + factors = [f] + + if gf_degree(f) <= n: + return factors + + N = gf_degree(f) // n + if p != 2: + b = gf_frobenius_monomial_base(f, p, K) + + t = [K.one, K.zero] + while len(factors) < N: + if p == 2: + h = r = t + + for i in range(n - 1): + r = gf_pow_mod(r, 2, f, p, K) + h = gf_add(h, r, p, K) + + g = gf_gcd(f, h, p, K) + t += [K.zero, K.zero] + else: + r = gf_random(2 * n - 1, p, K) + h = _gf_pow_pnm1d2(r, n, f, b, p, K) + g = gf_gcd(f, gf_sub_ground(h, K.one, p, K), p, K) + + if g != [K.one] and g != f: + factors = gf_edf_zassenhaus(g, n, p, K) \ + + gf_edf_zassenhaus(gf_quo(f, g, p, K), n, p, K) + + return _sort_factors(factors, multiple=False) + + +def gf_ddf_shoup(f, p, K): + """ + Kaltofen-Shoup: Deterministic Distinct Degree Factorization + + Given a monic square-free polynomial ``f`` in ``GF(p)[x]``, computes + partial distinct degree factorization ``f_1,...,f_d`` of ``f`` where + ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a + list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0`` + is an argument to the equal degree factorization routine. + + This algorithm is an improved version of Zassenhaus algorithm for + large ``deg(f)`` and modulus ``p`` (especially for ``deg(f) ~ lg(p)``). + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_ddf_shoup, gf_from_dict + + >>> f = gf_from_dict({6: ZZ(1), 5: ZZ(-1), 4: ZZ(1), 3: ZZ(1), 1: ZZ(-1)}, 3, ZZ) + + >>> gf_ddf_shoup(f, 3, ZZ) + [([1, 1, 0], 1), ([1, 1, 0, 1, 2], 2)] + + References + ========== + + .. [1] [Kaltofen98]_ + .. [2] [Shoup95]_ + .. [3] [Gathen92]_ + + """ + n = gf_degree(f) + k = int(_ceil(_sqrt(n//2))) + b = gf_frobenius_monomial_base(f, p, K) + h = gf_frobenius_map([K.one, K.zero], f, b, p, K) + # U[i] = x**(p**i) + U = [[K.one, K.zero], h] + [K.zero]*(k - 1) + + for i in range(2, k + 1): + U[i] = gf_frobenius_map(U[i-1], f, b, p, K) + + h, U = U[k], U[:k] + # V[i] = x**(p**(k*(i+1))) + V = [h] + [K.zero]*(k - 1) + + for i in range(1, k): + V[i] = gf_compose_mod(V[i - 1], h, f, p, K) + + factors = [] + + for i, v in enumerate(V): + h, j = [K.one], k - 1 + + for u in U: + g = gf_sub(v, u, p, K) + h = gf_mul(h, g, p, K) + h = gf_rem(h, f, p, K) + + g = gf_gcd(f, h, p, K) + f = gf_quo(f, g, p, K) + + for u in reversed(U): + h = gf_sub(v, u, p, K) + F = gf_gcd(g, h, p, K) + + if F != [K.one]: + factors.append((F, k*(i + 1) - j)) + + g, j = gf_quo(g, F, p, K), j - 1 + + if f != [K.one]: + factors.append((f, gf_degree(f))) + + return factors + +def gf_edf_shoup(f, n, p, K): + """ + Gathen-Shoup: Probabilistic Equal Degree Factorization + + Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and integer + ``n`` such that ``n`` divides ``deg(f)``, returns all irreducible factors + ``f_1,...,f_d`` of ``f``, each of degree ``n``. This is a complete + factorization over Galois fields. + + This algorithm is an improved version of Zassenhaus algorithm for + large ``deg(f)`` and modulus ``p`` (especially for ``deg(f) ~ lg(p)``). + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_edf_shoup + + >>> gf_edf_shoup(ZZ.map([1, 2837, 2277]), 1, 2917, ZZ) + [[1, 852], [1, 1985]] + + References + ========== + + .. [1] [Shoup91]_ + .. [2] [Gathen92]_ + + """ + N, q = gf_degree(f), int(p) + + if not N: + return [] + if N <= n: + return [f] + + factors, x = [f], [K.one, K.zero] + + r = gf_random(N - 1, p, K) + + if p == 2: + h = gf_pow_mod(x, q, f, p, K) + H = gf_trace_map(r, h, x, n - 1, f, p, K)[1] + h1 = gf_gcd(f, H, p, K) + h2 = gf_quo(f, h1, p, K) + + factors = gf_edf_shoup(h1, n, p, K) \ + + gf_edf_shoup(h2, n, p, K) + else: + b = gf_frobenius_monomial_base(f, p, K) + H = _gf_trace_map(r, n, f, b, p, K) + h = gf_pow_mod(H, (q - 1)//2, f, p, K) + + h1 = gf_gcd(f, h, p, K) + h2 = gf_gcd(f, gf_sub_ground(h, K.one, p, K), p, K) + h3 = gf_quo(f, gf_mul(h1, h2, p, K), p, K) + + factors = gf_edf_shoup(h1, n, p, K) \ + + gf_edf_shoup(h2, n, p, K) \ + + gf_edf_shoup(h3, n, p, K) + + return _sort_factors(factors, multiple=False) + + +def gf_zassenhaus(f, p, K): + """ + Factor a square-free ``f`` in ``GF(p)[x]`` for medium ``p``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_zassenhaus + + >>> gf_zassenhaus(ZZ.map([1, 4, 3]), 5, ZZ) + [[1, 1], [1, 3]] + + """ + factors = [] + + for factor, n in gf_ddf_zassenhaus(f, p, K): + factors += gf_edf_zassenhaus(factor, n, p, K) + + return _sort_factors(factors, multiple=False) + + +def gf_shoup(f, p, K): + """ + Factor a square-free ``f`` in ``GF(p)[x]`` for large ``p``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_shoup + + >>> gf_shoup(ZZ.map([1, 4, 3]), 5, ZZ) + [[1, 1], [1, 3]] + + """ + factors = [] + + for factor, n in gf_ddf_shoup(f, p, K): + factors += gf_edf_shoup(factor, n, p, K) + + return _sort_factors(factors, multiple=False) + +_factor_methods = { + 'berlekamp': gf_berlekamp, # ``p`` : small + 'zassenhaus': gf_zassenhaus, # ``p`` : medium + 'shoup': gf_shoup, # ``p`` : large +} + + +def gf_factor_sqf(f, p, K, method=None): + """ + Factor a square-free polynomial ``f`` in ``GF(p)[x]``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_factor_sqf + + >>> gf_factor_sqf(ZZ.map([3, 2, 4]), 5, ZZ) + (3, [[1, 1], [1, 3]]) + + """ + lc, f = gf_monic(f, p, K) + + if gf_degree(f) < 1: + return lc, [] + + method = method or query('GF_FACTOR_METHOD') + + if method is not None: + factors = _factor_methods[method](f, p, K) + else: + factors = gf_zassenhaus(f, p, K) + + return lc, factors + + +def gf_factor(f, p, K): + """ + Factor (non square-free) polynomials in ``GF(p)[x]``. + + Given a possibly non square-free polynomial ``f`` in ``GF(p)[x]``, + returns its complete factorization into irreducibles:: + + f_1(x)**e_1 f_2(x)**e_2 ... f_d(x)**e_d + + where each ``f_i`` is a monic polynomial and ``gcd(f_i, f_j) == 1``, + for ``i != j``. The result is given as a tuple consisting of the + leading coefficient of ``f`` and a list of factors of ``f`` with + their multiplicities. + + The algorithm proceeds by first computing square-free decomposition + of ``f`` and then iteratively factoring each of square-free factors. + + Consider a non square-free polynomial ``f = (7*x + 1) (x + 2)**2`` in + ``GF(11)[x]``. We obtain its factorization into irreducibles as follows:: + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.galoistools import gf_factor + + >>> gf_factor(ZZ.map([5, 2, 7, 2]), 11, ZZ) + (5, [([1, 2], 1), ([1, 8], 2)]) + + We arrived with factorization ``f = 5 (x + 2) (x + 8)**2``. We did not + recover the exact form of the input polynomial because we requested to + get monic factors of ``f`` and its leading coefficient separately. + + Square-free factors of ``f`` can be factored into irreducibles over + ``GF(p)`` using three very different methods: + + Berlekamp + efficient for very small values of ``p`` (usually ``p < 25``) + Cantor-Zassenhaus + efficient on average input and with "typical" ``p`` + Shoup-Kaltofen-Gathen + efficient with very large inputs and modulus + + If you want to use a specific factorization method, instead of the default + one, set ``GF_FACTOR_METHOD`` with one of ``berlekamp``, ``zassenhaus`` or + ``shoup`` values. + + References + ========== + + .. [1] [Gathen99]_ + + """ + lc, f = gf_monic(f, p, K) + + if gf_degree(f) < 1: + return lc, [] + + factors = [] + + for g, n in gf_sqf_list(f, p, K)[1]: + for h in gf_factor_sqf(g, p, K)[1]: + factors.append((h, n)) + + return lc, _sort_factors(factors) + + +def gf_value(f, a): + """ + Value of polynomial 'f' at 'a' in field R. + + Examples + ======== + + >>> from sympy.polys.galoistools import gf_value + + >>> gf_value([1, 7, 2, 4], 11) + 2204 + + """ + result = 0 + for c in f: + result *= a + result += c + return result + + +def linear_congruence(a, b, m): + """ + Returns the values of x satisfying a*x congruent b mod(m) + + Here m is positive integer and a, b are natural numbers. + This function returns only those values of x which are distinct mod(m). + + Examples + ======== + + >>> from sympy.polys.galoistools import linear_congruence + + >>> linear_congruence(3, 12, 15) + [4, 9, 14] + + There are 3 solutions distinct mod(15) since gcd(a, m) = gcd(3, 15) = 3. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Linear_congruence_theorem + + """ + from sympy.polys.polytools import gcdex + if a % m == 0: + if b % m == 0: + return list(range(m)) + else: + return [] + r, _, g = gcdex(a, m) + if b % g != 0: + return [] + return [(r * b // g + t * m // g) % m for t in range(g)] + + +def _raise_mod_power(x, s, p, f): + """ + Used in gf_csolve to generate solutions of f(x) cong 0 mod(p**(s + 1)) + from the solutions of f(x) cong 0 mod(p**s). + + Examples + ======== + + >>> from sympy.polys.galoistools import _raise_mod_power + >>> from sympy.polys.galoistools import csolve_prime + + These is the solutions of f(x) = x**2 + x + 7 cong 0 mod(3) + + >>> f = [1, 1, 7] + >>> csolve_prime(f, 3) + [1] + >>> [ i for i in range(3) if not (i**2 + i + 7) % 3] + [1] + + The solutions of f(x) cong 0 mod(9) are constructed from the + values returned from _raise_mod_power: + + >>> x, s, p = 1, 1, 3 + >>> V = _raise_mod_power(x, s, p, f) + >>> [x + v * p**s for v in V] + [1, 4, 7] + + And these are confirmed with the following: + + >>> [ i for i in range(3**2) if not (i**2 + i + 7) % 3**2] + [1, 4, 7] + + """ + from sympy.polys.domains import ZZ + f_f = gf_diff(f, p, ZZ) + alpha = gf_value(f_f, x) + beta = - gf_value(f, x) // p**s + return linear_congruence(alpha, beta, p) + + +def _csolve_prime_las_vegas(f, p, seed=None): + r""" Solutions of `f(x) \equiv 0 \pmod{p}`, `f(0) \not\equiv 0 \pmod{p}`. + + Explanation + =========== + + This algorithm is classified as the Las Vegas method. + That is, it always returns the correct answer and solves the problem + fast in many cases, but if it is unlucky, it does not answer forever. + + Suppose the polynomial f is not a zero polynomial. Assume further + that it is of degree at most p-1 and `f(0)\not\equiv 0 \pmod{p}`. + These assumptions are not an essential part of the algorithm, + only that it is more convenient for the function calling this + function to resolve them. + + Note that `x^{p-1} - 1 \equiv \prod_{a=1}^{p-1}(x - a) \pmod{p}`. + Thus, the greatest common divisor with f is `\prod_{s \in S}(x - s)`, + with S being the set of solutions to f. Furthermore, + when a is randomly determined, `(x+a)^{(p-1)/2}-1` is + a polynomial with (p-1)/2 randomly chosen solutions. + The greatest common divisor of f may be a nontrivial factor of f. + + When p is large and the degree of f is small, + it is faster than naive solution methods. + + Parameters + ========== + + f : polynomial + p : prime number + + Returns + ======= + + list[int] + a list of solutions, sorted in ascending order + by integers in the range [1, p). The same value + does not exist in the list even if there is + a multiple solution. If no solution exists, returns []. + + Examples + ======== + + >>> from sympy.polys.galoistools import _csolve_prime_las_vegas + >>> _csolve_prime_las_vegas([1, 4, 3], 7) # x^2 + 4x + 3 = 0 (mod 7) + [4, 6] + >>> _csolve_prime_las_vegas([5, 7, 1, 9], 11) # 5x^3 + 7x^2 + x + 9 = 0 (mod 11) + [1, 5, 8] + + References + ========== + + .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nd Ed., Algorithm 2.3.10 + + """ + from sympy.polys.domains import ZZ + from sympy.ntheory import sqrt_mod + randint = _randint(seed) + root = set() + g = gf_pow_mod([1, 0], p - 1, f, p, ZZ) + g = gf_sub_ground(g, 1, p, ZZ) + # We want to calculate gcd(x**(p-1) - 1, f(x)) + factors = [gf_gcd(f, g, p, ZZ)] + while factors: + f = factors.pop() + # If the degree is small, solve directly + if len(f) <= 1: + continue + if len(f) == 2: + root.add(-invert(f[0], p) * f[1] % p) + continue + if len(f) == 3: + inv = invert(f[0], p) + b = f[1] * inv % p + b = (b + p * (b % 2)) // 2 + root.update((r - b) % p for r in + sqrt_mod(b**2 - f[2] * inv, p, all_roots=True)) + continue + while True: + # Determine `a` randomly and + # compute gcd((x+a)**((p-1)//2)-1, f(x)) + a = randint(0, p - 1) + g = gf_pow_mod([1, a], (p - 1) // 2, f, p, ZZ) + g = gf_sub_ground(g, 1, p, ZZ) + g = gf_gcd(f, g, p, ZZ) + if 1 < len(g) < len(f): + factors.append(g) + factors.append(gf_div(f, g, p, ZZ)[0]) + break + return sorted(root) + + +def csolve_prime(f, p, e=1): + r""" Solutions of `f(x) \equiv 0 \pmod{p^e}`. + + Parameters + ========== + + f : polynomial + p : prime number + e : positive integer + + Returns + ======= + + list[int] + a list of solutions, sorted in ascending order + by integers in the range [1, p**e). The same value + does not exist in the list even if there is + a multiple solution. If no solution exists, returns []. + + Examples + ======== + + >>> from sympy.polys.galoistools import csolve_prime + >>> csolve_prime([1, 1, 7], 3, 1) + [1] + >>> csolve_prime([1, 1, 7], 3, 2) + [1, 4, 7] + + Solutions [7, 4, 1] (mod 3**2) are generated by ``_raise_mod_power()`` + from solution [1] (mod 3). + """ + from sympy.polys.domains import ZZ + g = [MPZ(int(c)) for c in f] + # Convert to polynomial of degree at most p-1 + for i in range(len(g) - p): + g[i + p - 1] += g[i] + g[i] = 0 + g = gf_trunc(g, p) + # Checks whether g(x) is divisible by x + k = 0 + while k < len(g) and g[len(g) - k - 1] == 0: + k += 1 + if k: + g = g[:-k] + root_zero = [0] + else: + root_zero = [] + if g == []: + X1 = list(range(p)) + elif len(g)**2 < p: + # The conditions under which `_csolve_prime_las_vegas` is faster than + # a naive solution are worth considering. + X1 = root_zero + _csolve_prime_las_vegas(g, p) + else: + X1 = root_zero + [i for i in range(p) if gf_eval(g, i, p, ZZ) == 0] + if e == 1: + return X1 + X = [] + S = list(zip(X1, [1]*len(X1))) + while S: + x, s = S.pop() + if s == e: + X.append(x) + else: + s1 = s + 1 + ps = p**s + S.extend([(x + v*ps, s1) for v in _raise_mod_power(x, s, p, f)]) + return sorted(X) + + +def gf_csolve(f, n): + """ + To solve f(x) congruent 0 mod(n). + + n is divided into canonical factors and f(x) cong 0 mod(p**e) will be + solved for each factor. Applying the Chinese Remainder Theorem to the + results returns the final answers. + + Examples + ======== + + Solve [1, 1, 7] congruent 0 mod(189): + + >>> from sympy.polys.galoistools import gf_csolve + >>> gf_csolve([1, 1, 7], 189) + [13, 49, 76, 112, 139, 175] + + See Also + ======== + + sympy.ntheory.residue_ntheory.polynomial_congruence : a higher level solving routine + + References + ========== + + .. [1] 'An introduction to the Theory of Numbers' 5th Edition by Ivan Niven, + Zuckerman and Montgomery. + + """ + from sympy.polys.domains import ZZ + from sympy.ntheory import factorint + P = factorint(n) + X = [csolve_prime(f, p, e) for p, e in P.items()] + pools = list(map(tuple, X)) + perms = [[]] + for pool in pools: + perms = [x + [y] for x in perms for y in pool] + dist_factors = [pow(p, e) for p, e in P.items()] + return sorted([gf_crt(per, dist_factors, ZZ) for per in perms]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/groebnertools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/groebnertools.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5c2f228ab4f4182e4c8fff68d974aa25c9d531 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/groebnertools.py @@ -0,0 +1,862 @@ +"""Groebner bases algorithms. """ + + +from sympy.core.symbol import Dummy +from sympy.polys.monomials import monomial_mul, monomial_lcm, monomial_divides, term_div +from sympy.polys.orderings import lex +from sympy.polys.polyerrors import DomainError +from sympy.polys.polyconfig import query + +def groebner(seq, ring, method=None): + """ + Computes Groebner basis for a set of polynomials in `K[X]`. + + Wrapper around the (default) improved Buchberger and the other algorithms + for computing Groebner bases. The choice of algorithm can be changed via + ``method`` argument or :func:`sympy.polys.polyconfig.setup`, where + ``method`` can be either ``buchberger`` or ``f5b``. + + """ + if method is None: + method = query('groebner') + + _groebner_methods = { + 'buchberger': _buchberger, + 'f5b': _f5b, + } + + try: + _groebner = _groebner_methods[method] + except KeyError: + raise ValueError("'%s' is not a valid Groebner bases algorithm (valid are 'buchberger' and 'f5b')" % method) + + domain, orig = ring.domain, None + + if not domain.is_Field or not domain.has_assoc_Field: + try: + orig, ring = ring, ring.clone(domain=domain.get_field()) + except DomainError: + raise DomainError("Cannot compute a Groebner basis over %s" % domain) + else: + seq = [ s.set_ring(ring) for s in seq ] + + G = _groebner(seq, ring) + + if orig is not None: + G = [ g.clear_denoms()[1].set_ring(orig) for g in G ] + + return G + +def _buchberger(f, ring): + """ + Computes Groebner basis for a set of polynomials in `K[X]`. + + Given a set of multivariate polynomials `F`, finds another + set `G`, such that Ideal `F = Ideal G` and `G` is a reduced + Groebner basis. + + The resulting basis is unique and has monic generators if the + ground domains is a field. Otherwise the result is non-unique + but Groebner bases over e.g. integers can be computed (if the + input polynomials are monic). + + Groebner bases can be used to choose specific generators for a + polynomial ideal. Because these bases are unique you can check + for ideal equality by comparing the Groebner bases. To see if + one polynomial lies in an ideal, divide by the elements in the + base and see if the remainder vanishes. + + They can also be used to solve systems of polynomial equations + as, by choosing lexicographic ordering, you can eliminate one + variable at a time, provided that the ideal is zero-dimensional + (finite number of solutions). + + Notes + ===== + + Algorithm used: an improved version of Buchberger's algorithm + as presented in T. Becker, V. Weispfenning, Groebner Bases: A + Computational Approach to Commutative Algebra, Springer, 1993, + page 232. + + References + ========== + + .. [1] [Bose03]_ + .. [2] [Giovini91]_ + .. [3] [Ajwa95]_ + .. [4] [Cox97]_ + + """ + order = ring.order + + monomial_mul = ring.monomial_mul + monomial_div = ring.monomial_div + monomial_lcm = ring.monomial_lcm + + def select(P): + # normal selection strategy + # select the pair with minimum LCM(LM(f), LM(g)) + pr = min(P, key=lambda pair: order(monomial_lcm(f[pair[0]].LM, f[pair[1]].LM))) + return pr + + def normal(g, J): + h = g.rem([ f[j] for j in J ]) + + if not h: + return None + else: + h = h.monic() + + if h not in I: + I[h] = len(f) + f.append(h) + + return h.LM, I[h] + + def update(G, B, ih): + # update G using the set of critical pairs B and h + # [BW] page 230 + h = f[ih] + mh = h.LM + + # filter new pairs (h, g), g in G + C = G.copy() + D = set() + + while C: + # select a pair (h, g) by popping an element from C + ig = C.pop() + g = f[ig] + mg = g.LM + LCMhg = monomial_lcm(mh, mg) + + def lcm_divides(ip): + # LCM(LM(h), LM(p)) divides LCM(LM(h), LM(g)) + m = monomial_lcm(mh, f[ip].LM) + return monomial_div(LCMhg, m) + + # HT(h) and HT(g) disjoint: mh*mg == LCMhg + if monomial_mul(mh, mg) == LCMhg or ( + not any(lcm_divides(ipx) for ipx in C) and + not any(lcm_divides(pr[1]) for pr in D)): + D.add((ih, ig)) + + E = set() + + while D: + # select h, g from D (h the same as above) + ih, ig = D.pop() + mg = f[ig].LM + LCMhg = monomial_lcm(mh, mg) + + if not monomial_mul(mh, mg) == LCMhg: + E.add((ih, ig)) + + # filter old pairs + B_new = set() + + while B: + # select g1, g2 from B (-> CP) + ig1, ig2 = B.pop() + mg1 = f[ig1].LM + mg2 = f[ig2].LM + LCM12 = monomial_lcm(mg1, mg2) + + # if HT(h) does not divide lcm(HT(g1), HT(g2)) + if not monomial_div(LCM12, mh) or \ + monomial_lcm(mg1, mh) == LCM12 or \ + monomial_lcm(mg2, mh) == LCM12: + B_new.add((ig1, ig2)) + + B_new |= E + + # filter polynomials + G_new = set() + + while G: + ig = G.pop() + mg = f[ig].LM + + if not monomial_div(mg, mh): + G_new.add(ig) + + G_new.add(ih) + + return G_new, B_new + # end of update ################################ + + if not f: + return [] + + # replace f with a reduced list of initial polynomials; see [BW] page 203 + f1 = f[:] + + while True: + f = f1[:] + f1 = [] + + for i in range(len(f)): + p = f[i] + r = p.rem(f[:i]) + + if r: + f1.append(r.monic()) + + if f == f1: + break + + I = {} # ip = I[p]; p = f[ip] + F = set() # set of indices of polynomials + G = set() # set of indices of intermediate would-be Groebner basis + CP = set() # set of pairs of indices of critical pairs + + for i, h in enumerate(f): + I[h] = i + F.add(i) + + ##################################### + # algorithm GROEBNERNEWS2 in [BW] page 232 + + while F: + # select p with minimum monomial according to the monomial ordering + h = min([f[x] for x in F], key=lambda f: order(f.LM)) + ih = I[h] + F.remove(ih) + G, CP = update(G, CP, ih) + + # count the number of critical pairs which reduce to zero + reductions_to_zero = 0 + + while CP: + ig1, ig2 = select(CP) + CP.remove((ig1, ig2)) + + h = spoly(f[ig1], f[ig2], ring) + # ordering divisors is on average more efficient [Cox] page 111 + G1 = sorted(G, key=lambda g: order(f[g].LM)) + ht = normal(h, G1) + + if ht: + G, CP = update(G, CP, ht[1]) + else: + reductions_to_zero += 1 + + ###################################### + # now G is a Groebner basis; reduce it + Gr = set() + + for ig in G: + ht = normal(f[ig], G - {ig}) + + if ht: + Gr.add(ht[1]) + + Gr = [f[ig] for ig in Gr] + + # order according to the monomial ordering + Gr = sorted(Gr, key=lambda f: order(f.LM), reverse=True) + + return Gr + +def spoly(p1, p2, ring): + """ + Compute LCM(LM(p1), LM(p2))/LM(p1)*p1 - LCM(LM(p1), LM(p2))/LM(p2)*p2 + This is the S-poly provided p1 and p2 are monic + """ + LM1 = p1.LM + LM2 = p2.LM + LCM12 = ring.monomial_lcm(LM1, LM2) + m1 = ring.monomial_div(LCM12, LM1) + m2 = ring.monomial_div(LCM12, LM2) + s1 = p1.mul_monom(m1) + s2 = p2.mul_monom(m2) + s = s1 - s2 + return s + +# F5B + +# convenience functions + + +def Sign(f): + return f[0] + + +def Polyn(f): + return f[1] + + +def Num(f): + return f[2] + + +def sig(monomial, index): + return (monomial, index) + + +def lbp(signature, polynomial, number): + return (signature, polynomial, number) + +# signature functions + + +def sig_cmp(u, v, order): + """ + Compare two signatures by extending the term order to K[X]^n. + + u < v iff + - the index of v is greater than the index of u + or + - the index of v is equal to the index of u and u[0] < v[0] w.r.t. order + + u > v otherwise + """ + if u[1] > v[1]: + return -1 + if u[1] == v[1]: + #if u[0] == v[0]: + # return 0 + if order(u[0]) < order(v[0]): + return -1 + return 1 + + +def sig_key(s, order): + """ + Key for comparing two signatures. + + s = (m, k), t = (n, l) + + s < t iff [k > l] or [k == l and m < n] + s > t otherwise + """ + return (-s[1], order(s[0])) + + +def sig_mult(s, m): + """ + Multiply a signature by a monomial. + + The product of a signature (m, i) and a monomial n is defined as + (m * t, i). + """ + return sig(monomial_mul(s[0], m), s[1]) + +# labeled polynomial functions + + +def lbp_sub(f, g): + """ + Subtract labeled polynomial g from f. + + The signature and number of the difference of f and g are signature + and number of the maximum of f and g, w.r.t. lbp_cmp. + """ + if sig_cmp(Sign(f), Sign(g), Polyn(f).ring.order) < 0: + max_poly = g + else: + max_poly = f + + ret = Polyn(f) - Polyn(g) + + return lbp(Sign(max_poly), ret, Num(max_poly)) + + +def lbp_mul_term(f, cx): + """ + Multiply a labeled polynomial with a term. + + The product of a labeled polynomial (s, p, k) by a monomial is + defined as (m * s, m * p, k). + """ + return lbp(sig_mult(Sign(f), cx[0]), Polyn(f).mul_term(cx), Num(f)) + + +def lbp_cmp(f, g): + """ + Compare two labeled polynomials. + + f < g iff + - Sign(f) < Sign(g) + or + - Sign(f) == Sign(g) and Num(f) > Num(g) + + f > g otherwise + """ + if sig_cmp(Sign(f), Sign(g), Polyn(f).ring.order) == -1: + return -1 + if Sign(f) == Sign(g): + if Num(f) > Num(g): + return -1 + #if Num(f) == Num(g): + # return 0 + return 1 + + +def lbp_key(f): + """ + Key for comparing two labeled polynomials. + """ + return (sig_key(Sign(f), Polyn(f).ring.order), -Num(f)) + +# algorithm and helper functions + + +def critical_pair(f, g, ring): + """ + Compute the critical pair corresponding to two labeled polynomials. + + A critical pair is a tuple (um, f, vm, g), where um and vm are + terms such that um * f - vm * g is the S-polynomial of f and g (so, + wlog assume um * f > vm * g). + For performance sake, a critical pair is represented as a tuple + (Sign(um * f), um, f, Sign(vm * g), vm, g), since um * f creates + a new, relatively expensive object in memory, whereas Sign(um * + f) and um are lightweight and f (in the tuple) is a reference to + an already existing object in memory. + """ + domain = ring.domain + + ltf = Polyn(f).LT + ltg = Polyn(g).LT + lt = (monomial_lcm(ltf[0], ltg[0]), domain.one) + + um = term_div(lt, ltf, domain) + vm = term_div(lt, ltg, domain) + + # The full information is not needed (now), so only the product + # with the leading term is considered: + fr = lbp_mul_term(lbp(Sign(f), Polyn(f).leading_term(), Num(f)), um) + gr = lbp_mul_term(lbp(Sign(g), Polyn(g).leading_term(), Num(g)), vm) + + # return in proper order, such that the S-polynomial is just + # u_first * f_first - u_second * f_second: + if lbp_cmp(fr, gr) == -1: + return (Sign(gr), vm, g, Sign(fr), um, f) + else: + return (Sign(fr), um, f, Sign(gr), vm, g) + + +def cp_cmp(c, d): + """ + Compare two critical pairs c and d. + + c < d iff + - lbp(c[0], _, Num(c[2]) < lbp(d[0], _, Num(d[2])) (this + corresponds to um_c * f_c and um_d * f_d) + or + - lbp(c[0], _, Num(c[2]) >< lbp(d[0], _, Num(d[2])) and + lbp(c[3], _, Num(c[5])) < lbp(d[3], _, Num(d[5])) (this + corresponds to vm_c * g_c and vm_d * g_d) + + c > d otherwise + """ + zero = Polyn(c[2]).ring.zero + + c0 = lbp(c[0], zero, Num(c[2])) + d0 = lbp(d[0], zero, Num(d[2])) + + r = lbp_cmp(c0, d0) + + if r == -1: + return -1 + if r == 0: + c1 = lbp(c[3], zero, Num(c[5])) + d1 = lbp(d[3], zero, Num(d[5])) + + r = lbp_cmp(c1, d1) + + if r == -1: + return -1 + #if r == 0: + # return 0 + return 1 + + +def cp_key(c, ring): + """ + Key for comparing critical pairs. + """ + return (lbp_key(lbp(c[0], ring.zero, Num(c[2]))), lbp_key(lbp(c[3], ring.zero, Num(c[5])))) + + +def s_poly(cp): + """ + Compute the S-polynomial of a critical pair. + + The S-polynomial of a critical pair cp is cp[1] * cp[2] - cp[4] * cp[5]. + """ + return lbp_sub(lbp_mul_term(cp[2], cp[1]), lbp_mul_term(cp[5], cp[4])) + + +def is_rewritable_or_comparable(sign, num, B): + """ + Check if a labeled polynomial is redundant by checking if its + signature and number imply rewritability or comparability. + + (sign, num) is comparable if there exists a labeled polynomial + h in B, such that sign[1] (the index) is less than Sign(h)[1] + and sign[0] is divisible by the leading monomial of h. + + (sign, num) is rewritable if there exists a labeled polynomial + h in B, such thatsign[1] is equal to Sign(h)[1], num < Num(h) + and sign[0] is divisible by Sign(h)[0]. + """ + for h in B: + # comparable + if sign[1] < Sign(h)[1]: + if monomial_divides(Polyn(h).LM, sign[0]): + return True + + # rewritable + if sign[1] == Sign(h)[1]: + if num < Num(h): + if monomial_divides(Sign(h)[0], sign[0]): + return True + return False + + +def f5_reduce(f, B): + """ + F5-reduce a labeled polynomial f by B. + + Continuously searches for non-zero labeled polynomial h in B, such + that the leading term lt_h of h divides the leading term lt_f of + f and Sign(lt_h * h) < Sign(f). If such a labeled polynomial h is + found, f gets replaced by f - lt_f / lt_h * h. If no such h can be + found or f is 0, f is no further F5-reducible and f gets returned. + + A polynomial that is reducible in the usual sense need not be + F5-reducible, e.g.: + + >>> from sympy.polys.groebnertools import lbp, sig, f5_reduce, Polyn + >>> from sympy.polys import ring, QQ, lex + + >>> R, x,y,z = ring("x,y,z", QQ, lex) + + >>> f = lbp(sig((1, 1, 1), 4), x, 3) + >>> g = lbp(sig((0, 0, 0), 2), x, 2) + + >>> Polyn(f).rem([Polyn(g)]) + 0 + >>> f5_reduce(f, [g]) + (((1, 1, 1), 4), x, 3) + + """ + order = Polyn(f).ring.order + domain = Polyn(f).ring.domain + + if not Polyn(f): + return f + + while True: + g = f + + for h in B: + if Polyn(h): + if monomial_divides(Polyn(h).LM, Polyn(f).LM): + t = term_div(Polyn(f).LT, Polyn(h).LT, domain) + if sig_cmp(sig_mult(Sign(h), t[0]), Sign(f), order) < 0: + # The following check need not be done and is in general slower than without. + #if not is_rewritable_or_comparable(Sign(gp), Num(gp), B): + hp = lbp_mul_term(h, t) + f = lbp_sub(f, hp) + break + + if g == f or not Polyn(f): + return f + + +def _f5b(F, ring): + """ + Computes a reduced Groebner basis for the ideal generated by F. + + f5b is an implementation of the F5B algorithm by Yao Sun and + Dingkang Wang. Similarly to Buchberger's algorithm, the algorithm + proceeds by computing critical pairs, computing the S-polynomial, + reducing it and adjoining the reduced S-polynomial if it is not 0. + + Unlike Buchberger's algorithm, each polynomial contains additional + information, namely a signature and a number. The signature + specifies the path of computation (i.e. from which polynomial in + the original basis was it derived and how), the number says when + the polynomial was added to the basis. With this information it + is (often) possible to decide if an S-polynomial will reduce to + 0 and can be discarded. + + Optimizations include: Reducing the generators before computing + a Groebner basis, removing redundant critical pairs when a new + polynomial enters the basis and sorting the critical pairs and + the current basis. + + Once a Groebner basis has been found, it gets reduced. + + References + ========== + + .. [1] Yao Sun, Dingkang Wang: "A New Proof for the Correctness of F5 + (F5-Like) Algorithm", https://arxiv.org/abs/1004.0084 (specifically + v4) + + .. [2] Thomas Becker, Volker Weispfenning, Groebner bases: A computational + approach to commutative algebra, 1993, p. 203, 216 + """ + order = ring.order + + # reduce polynomials (like in Mario Pernici's implementation) (Becker, Weispfenning, p. 203) + B = F + while True: + F = B + B = [] + + for i in range(len(F)): + p = F[i] + r = p.rem(F[:i]) + + if r: + B.append(r) + + if F == B: + break + + # basis + B = [lbp(sig(ring.zero_monom, i + 1), F[i], i + 1) for i in range(len(F))] + B.sort(key=lambda f: order(Polyn(f).LM), reverse=True) + + # critical pairs + CP = [critical_pair(B[i], B[j], ring) for i in range(len(B)) for j in range(i + 1, len(B))] + CP.sort(key=lambda cp: cp_key(cp, ring), reverse=True) + + k = len(B) + + reductions_to_zero = 0 + + while len(CP): + cp = CP.pop() + + # discard redundant critical pairs: + if is_rewritable_or_comparable(cp[0], Num(cp[2]), B): + continue + if is_rewritable_or_comparable(cp[3], Num(cp[5]), B): + continue + + s = s_poly(cp) + + p = f5_reduce(s, B) + + p = lbp(Sign(p), Polyn(p).monic(), k + 1) + + if Polyn(p): + # remove old critical pairs, that become redundant when adding p: + indices = [] + for i, cp in enumerate(CP): + if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p]): + indices.append(i) + elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p]): + indices.append(i) + + for i in reversed(indices): + del CP[i] + + # only add new critical pairs that are not made redundant by p: + for g in B: + if Polyn(g): + cp = critical_pair(p, g, ring) + if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p]): + continue + elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p]): + continue + + CP.append(cp) + + # sort (other sorting methods/selection strategies were not as successful) + CP.sort(key=lambda cp: cp_key(cp, ring), reverse=True) + + # insert p into B: + m = Polyn(p).LM + if order(m) <= order(Polyn(B[-1]).LM): + B.append(p) + else: + for i, q in enumerate(B): + if order(m) > order(Polyn(q).LM): + B.insert(i, p) + break + + k += 1 + + #print(len(B), len(CP), "%d critical pairs removed" % len(indices)) + else: + reductions_to_zero += 1 + + # reduce Groebner basis: + H = [Polyn(g).monic() for g in B] + H = red_groebner(H, ring) + + return sorted(H, key=lambda f: order(f.LM), reverse=True) + + +def red_groebner(G, ring): + """ + Compute reduced Groebner basis, from BeckerWeispfenning93, p. 216 + + Selects a subset of generators, that already generate the ideal + and computes a reduced Groebner basis for them. + """ + def reduction(P): + """ + The actual reduction algorithm. + """ + Q = [] + for i, p in enumerate(P): + h = p.rem(P[:i] + P[i + 1:]) + if h: + Q.append(h) + + return [p.monic() for p in Q] + + F = G + H = [] + + while F: + f0 = F.pop() + + if not any(monomial_divides(f.LM, f0.LM) for f in F + H): + H.append(f0) + + # Becker, Weispfenning, p. 217: H is Groebner basis of the ideal generated by G. + return reduction(H) + + +def is_groebner(G, ring): + """ + Check if G is a Groebner basis. + """ + for i in range(len(G)): + for j in range(i + 1, len(G)): + s = spoly(G[i], G[j], ring) + s = s.rem(G) + if s: + return False + + return True + + +def is_minimal(G, ring): + """ + Checks if G is a minimal Groebner basis. + """ + order = ring.order + domain = ring.domain + + G.sort(key=lambda g: order(g.LM)) + + for i, g in enumerate(G): + if g.LC != domain.one: + return False + + for h in G[:i] + G[i + 1:]: + if monomial_divides(h.LM, g.LM): + return False + + return True + + +def is_reduced(G, ring): + """ + Checks if G is a reduced Groebner basis. + """ + order = ring.order + domain = ring.domain + + G.sort(key=lambda g: order(g.LM)) + + for i, g in enumerate(G): + if g.LC != domain.one: + return False + + for term in g.terms(): + for h in G[:i] + G[i + 1:]: + if monomial_divides(h.LM, term[0]): + return False + + return True + +def groebner_lcm(f, g): + """ + Computes LCM of two polynomials using Groebner bases. + + The LCM is computed as the unique generator of the intersection + of the two ideals generated by `f` and `g`. The approach is to + compute a Groebner basis with respect to lexicographic ordering + of `t*f` and `(1 - t)*g`, where `t` is an unrelated variable and + then filtering out the solution that does not contain `t`. + + References + ========== + + .. [1] [Cox97]_ + + """ + if f.ring != g.ring: + raise ValueError("Values should be equal") + + ring = f.ring + domain = ring.domain + + if not f or not g: + return ring.zero + + if len(f) <= 1 and len(g) <= 1: + monom = monomial_lcm(f.LM, g.LM) + coeff = domain.lcm(f.LC, g.LC) + return ring.term_new(monom, coeff) + + fc, f = f.primitive() + gc, g = g.primitive() + + lcm = domain.lcm(fc, gc) + + f_terms = [ ((1,) + monom, coeff) for monom, coeff in f.terms() ] + g_terms = [ ((0,) + monom, coeff) for monom, coeff in g.terms() ] \ + + [ ((1,) + monom,-coeff) for monom, coeff in g.terms() ] + + t = Dummy("t") + t_ring = ring.clone(symbols=(t,) + ring.symbols, order=lex) + + F = t_ring.from_terms(f_terms) + G = t_ring.from_terms(g_terms) + + basis = groebner([F, G], t_ring) + + def is_independent(h, j): + return not any(monom[j] for monom in h.monoms()) + + H = [ h for h in basis if is_independent(h, 0) ] + + h_terms = [ (monom[1:], coeff*lcm) for monom, coeff in H[0].terms() ] + h = ring.from_terms(h_terms) + + return h + +def groebner_gcd(f, g): + """Computes GCD of two polynomials using Groebner bases. """ + if f.ring != g.ring: + raise ValueError("Values should be equal") + domain = f.ring.domain + + if not domain.is_Field: + fc, f = f.primitive() + gc, g = g.primitive() + gcd = domain.gcd(fc, gc) + + H = (f*g).quo([groebner_lcm(f, g)]) + + if len(H) != 1: + raise ValueError("Length should be 1") + h = H[0] + + if not domain.is_Field: + return gcd*h + else: + return h.monic() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/heuristicgcd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/heuristicgcd.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9eeac952e88552d729f0bd3073dee21b6ab68b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/heuristicgcd.py @@ -0,0 +1,149 @@ +"""Heuristic polynomial GCD algorithm (HEUGCD). """ + +from .polyerrors import HeuristicGCDFailed + +HEU_GCD_MAX = 6 + +def heugcd(f, g): + """ + Heuristic polynomial GCD in ``Z[X]``. + + Given univariate polynomials ``f`` and ``g`` in ``Z[X]``, returns + their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg`` + such that:: + + h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) + + The algorithm is purely heuristic which means it may fail to compute + the GCD. This will be signaled by raising an exception. In this case + you will need to switch to another GCD method. + + The algorithm computes the polynomial GCD by evaluating polynomials + ``f`` and ``g`` at certain points and computing (fast) integer GCD + of those evaluations. The polynomial GCD is recovered from the integer + image by interpolation. The evaluation process reduces f and g variable + by variable into a large integer. The final step is to verify if the + interpolated polynomial is the correct GCD. This gives cofactors of + the input polynomials as a side effect. + + Examples + ======== + + >>> from sympy.polys.heuristicgcd import heugcd + >>> from sympy.polys import ring, ZZ + + >>> R, x,y, = ring("x,y", ZZ) + + >>> f = x**2 + 2*x*y + y**2 + >>> g = x**2 + x*y + + >>> h, cff, cfg = heugcd(f, g) + >>> h, cff, cfg + (x + y, x + y, x) + + >>> cff*h == f + True + >>> cfg*h == g + True + + References + ========== + + .. [1] [Liao95]_ + + """ + assert f.ring == g.ring and f.ring.domain.is_ZZ + + ring = f.ring + x0 = ring.gens[0] + domain = ring.domain + + gcd, f, g = f.extract_ground(g) + + f_norm = f.max_norm() + g_norm = g.max_norm() + + B = domain(2*min(f_norm, g_norm) + 29) + + x = max(min(B, 99*domain.sqrt(B)), + 2*min(f_norm // abs(f.LC), + g_norm // abs(g.LC)) + 4) + + for i in range(0, HEU_GCD_MAX): + ff = f.evaluate(x0, x) + gg = g.evaluate(x0, x) + + if ff and gg: + if ring.ngens == 1: + h, cff, cfg = domain.cofactors(ff, gg) + else: + h, cff, cfg = heugcd(ff, gg) + + h = _gcd_interpolate(h, x, ring) + h = h.primitive()[1] + + cff_, r = f.div(h) + + if not r: + cfg_, r = g.div(h) + + if not r: + h = h.mul_ground(gcd) + return h, cff_, cfg_ + + cff = _gcd_interpolate(cff, x, ring) + + h, r = f.div(cff) + + if not r: + cfg_, r = g.div(h) + + if not r: + h = h.mul_ground(gcd) + return h, cff, cfg_ + + cfg = _gcd_interpolate(cfg, x, ring) + + h, r = g.div(cfg) + + if not r: + cff_, r = f.div(h) + + if not r: + h = h.mul_ground(gcd) + return h, cff_, cfg + + x = 73794*x * domain.sqrt(domain.sqrt(x)) // 27011 + + raise HeuristicGCDFailed('no luck') + +def _gcd_interpolate(h, x, ring): + """Interpolate polynomial GCD from integer GCD. """ + f, i = ring.zero, 0 + + # TODO: don't expose poly repr implementation details + if ring.ngens == 1: + while h: + g = h % x + if g > x // 2: g -= x + h = (h - g) // x + + # f += X**i*g + if g: + f[(i,)] = g + i += 1 + else: + while h: + g = h.trunc_ground(x) + h = (h - g).quo_ground(x) + + # f += X**i*g + if g: + for monom, coeff in g.iterterms(): + f[(i,) + monom] = coeff + i += 1 + + if f.LC < 0: + return -f + else: + return f diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ebc3d71ba3dac9ccc695d046d6b3d2ad940fa1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__init__.py @@ -0,0 +1,15 @@ +""" + +sympy.polys.matrices package. + +The main export from this package is the DomainMatrix class which is a +lower-level implementation of matrices based on the polys Domains. This +implementation is typically a lot faster than SymPy's standard Matrix class +but is a work in progress and is still experimental. + +""" +from .domainmatrix import DomainMatrix, DM + +__all__ = [ + 'DomainMatrix', 'DM', +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..962f68a231cc1e27c0ad9f1828a6b9ae79833f84 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a5c0abefb20cd821626241f020b5266074767eb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a6df18b1cf43f65865a320895365df04d3b368b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bb455feea4a092d5a314a8987da2fe9ebe602b2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dfm.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dfm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42a2c14216784b0569ac118d6254e4244f97673f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dfm.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dd6041325743846c3a45e80cb5c5b383911188b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7d9bf8fbecc6b734125aa9b85a33962de20c71b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1203c112a2745bf043eee4dabbc5516ecd8469a0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..003d59e60d70b25fa1df8fe559cb47fc757e2ba1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a16152e5d1bb0a9573e2ffe4bc30671e9ea2c9eb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4acf11b2e16fef2726679b7023de81b6e2a082e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/rref.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/rref.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff715434700593bccffa1bcf1b1591cadf0cce05 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/rref.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..029a2703f4fb3634189e97ce33cf7ce9fcf52f86 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/_dfm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/_dfm.py new file mode 100644 index 0000000000000000000000000000000000000000..1d02076014168ed4966fecd07f3d7a1d4828ae63 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/_dfm.py @@ -0,0 +1,951 @@ +# +# sympy.polys.matrices.dfm +# +# This modules defines the DFM class which is a wrapper for dense flint +# matrices as found in python-flint. +# +# As of python-flint 0.4.1 matrices over the following domains can be supported +# by python-flint: +# +# ZZ: flint.fmpz_mat +# QQ: flint.fmpq_mat +# GF(p): flint.nmod_mat (p prime and p < ~2**62) +# +# The underlying flint library has many more domains, but these are not yet +# supported by python-flint. +# +# The DFM class is a wrapper for the flint matrices and provides a common +# interface for all supported domains that is interchangeable with the DDM +# and SDM classes so that DomainMatrix can be used with any as its internal +# matrix representation. +# + +# TODO: +# +# Implement the following methods that are provided by python-flint: +# +# - hnf (Hermite normal form) +# - snf (Smith normal form) +# - minpoly +# - is_hnf +# - is_snf +# - rank +# +# The other types DDM and SDM do not have these methods and the algorithms +# for hnf, snf and rank are already implemented. Algorithms for minpoly, +# is_hnf and is_snf would need to be added. +# +# Add more methods to python-flint to expose more of Flint's functionality +# and also to make some of the above methods simpler or more efficient e.g. +# slicing, fancy indexing etc. + +from sympy.external.gmpy import GROUND_TYPES +from sympy.external.importtools import import_module +from sympy.utilities.decorator import doctest_depends_on + +from sympy.polys.domains import ZZ, QQ + +from .exceptions import ( + DMBadInputError, + DMDomainError, + DMNonSquareMatrixError, + DMNonInvertibleMatrixError, + DMRankError, + DMShapeError, + DMValueError, +) + + +if GROUND_TYPES != 'flint': + __doctest_skip__ = ['*'] + + +flint = import_module('flint') + + +__all__ = ['DFM'] + + +@doctest_depends_on(ground_types=['flint']) +class DFM: + """ + Dense FLINT matrix. This class is a wrapper for matrices from python-flint. + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.matrices.dfm import DFM + >>> dfm = DFM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> dfm + [[1, 2], [3, 4]] + >>> dfm.rep + [1, 2] + [3, 4] + >>> type(dfm.rep) # doctest: +SKIP + + + Usually, the DFM class is not instantiated directly, but is created as the + internal representation of :class:`~.DomainMatrix`. When + `SYMPY_GROUND_TYPES` is set to `flint` and `python-flint` is installed, the + :class:`DFM` class is used automatically as the internal representation of + :class:`~.DomainMatrix` in dense format if the domain is supported by + python-flint. + + >>> from sympy.polys.matrices.domainmatrix import DM + >>> dM = DM([[1, 2], [3, 4]], ZZ) + >>> dM.rep + [[1, 2], [3, 4]] + + A :class:`~.DomainMatrix` can be converted to :class:`DFM` by calling the + :meth:`to_dfm` method: + + >>> dM.to_dfm() + [[1, 2], [3, 4]] + + """ + + fmt = 'dense' + is_DFM = True + is_DDM = False + + def __new__(cls, rowslist, shape, domain): + """Construct from a nested list.""" + flint_mat = cls._get_flint_func(domain) + + if 0 not in shape: + try: + rep = flint_mat(rowslist) + except (ValueError, TypeError): + raise DMBadInputError(f"Input should be a list of list of {domain}") + else: + rep = flint_mat(*shape) + + return cls._new(rep, shape, domain) + + @classmethod + def _new(cls, rep, shape, domain): + """Internal constructor from a flint matrix.""" + cls._check(rep, shape, domain) + obj = object.__new__(cls) + obj.rep = rep + obj.shape = obj.rows, obj.cols = shape + obj.domain = domain + return obj + + def _new_rep(self, rep): + """Create a new DFM with the same shape and domain but a new rep.""" + return self._new(rep, self.shape, self.domain) + + @classmethod + def _check(cls, rep, shape, domain): + repshape = (rep.nrows(), rep.ncols()) + if repshape != shape: + raise DMBadInputError("Shape of rep does not match shape of DFM") + if domain == ZZ and not isinstance(rep, flint.fmpz_mat): + raise RuntimeError("Rep is not a flint.fmpz_mat") + elif domain == QQ and not isinstance(rep, flint.fmpq_mat): + raise RuntimeError("Rep is not a flint.fmpq_mat") + elif domain.is_FF and not isinstance(rep, (flint.fmpz_mod_mat, flint.nmod_mat)): + raise RuntimeError("Rep is not a flint.fmpz_mod_mat or flint.nmod_mat") + elif domain not in (ZZ, QQ) and not domain.is_FF: + raise NotImplementedError("Only ZZ and QQ are supported by DFM") + + @classmethod + def _supports_domain(cls, domain): + """Return True if the given domain is supported by DFM.""" + return domain in (ZZ, QQ) or domain.is_FF and domain._is_flint + + @classmethod + def _get_flint_func(cls, domain): + """Return the flint matrix class for the given domain.""" + if domain == ZZ: + return flint.fmpz_mat + elif domain == QQ: + return flint.fmpq_mat + elif domain.is_FF: + c = domain.characteristic() + if isinstance(domain.one, flint.nmod): + _cls = flint.nmod_mat + def _func(*e): + if len(e) == 1 and isinstance(e[0], flint.nmod_mat): + return _cls(e[0]) + else: + return _cls(*e, c) + else: + m = flint.fmpz_mod_ctx(c) + _func = lambda *e: flint.fmpz_mod_mat(*e, m) + return _func + else: + raise NotImplementedError("Only ZZ and QQ are supported by DFM") + + @property + def _func(self): + """Callable to create a flint matrix of the same domain.""" + return self._get_flint_func(self.domain) + + def __str__(self): + """Return ``str(self)``.""" + return str(self.to_ddm()) + + def __repr__(self): + """Return ``repr(self)``.""" + return f'DFM{repr(self.to_ddm())[3:]}' + + def __eq__(self, other): + """Return ``self == other``.""" + if not isinstance(other, DFM): + return NotImplemented + # Compare domains first because we do *not* want matrices with + # different domains to be equal but e.g. a flint fmpz_mat and fmpq_mat + # with the same entries will compare equal. + return self.domain == other.domain and self.rep == other.rep + + @classmethod + def from_list(cls, rowslist, shape, domain): + """Construct from a nested list.""" + return cls(rowslist, shape, domain) + + def to_list(self): + """Convert to a nested list.""" + return self.rep.tolist() + + def copy(self): + """Return a copy of self.""" + return self._new_rep(self._func(self.rep)) + + def to_ddm(self): + """Convert to a DDM.""" + return DDM.from_list(self.to_list(), self.shape, self.domain) + + def to_sdm(self): + """Convert to a SDM.""" + return SDM.from_list(self.to_list(), self.shape, self.domain) + + def to_dfm(self): + """Return self.""" + return self + + def to_dfm_or_ddm(self): + """ + Convert to a :class:`DFM`. + + This :class:`DFM` method exists to parallel the :class:`~.DDM` and + :class:`~.SDM` methods. For :class:`DFM` it will always return self. + + See Also + ======== + + to_ddm + to_sdm + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm_or_ddm + """ + return self + + @classmethod + def from_ddm(cls, ddm): + """Convert from a DDM.""" + return cls.from_list(ddm.to_list(), ddm.shape, ddm.domain) + + @classmethod + def from_list_flat(cls, elements, shape, domain): + """Inverse of :meth:`to_list_flat`.""" + func = cls._get_flint_func(domain) + try: + rep = func(*shape, elements) + except ValueError: + raise DMBadInputError(f"Incorrect number of elements for shape {shape}") + except TypeError: + raise DMBadInputError(f"Input should be a list of {domain}") + return cls(rep, shape, domain) + + def to_list_flat(self): + """Convert to a flat list.""" + return self.rep.entries() + + def to_flat_nz(self): + """Convert to a flat list of non-zeros.""" + return self.to_ddm().to_flat_nz() + + @classmethod + def from_flat_nz(cls, elements, data, domain): + """Inverse of :meth:`to_flat_nz`.""" + return DDM.from_flat_nz(elements, data, domain).to_dfm() + + def to_dod(self): + """Convert to a DOD.""" + return self.to_ddm().to_dod() + + @classmethod + def from_dod(cls, dod, shape, domain): + """Inverse of :meth:`to_dod`.""" + return DDM.from_dod(dod, shape, domain).to_dfm() + + def to_dok(self): + """Convert to a DOK.""" + return self.to_ddm().to_dok() + + @classmethod + def from_dok(cls, dok, shape, domain): + """Inverse of :math:`to_dod`.""" + return DDM.from_dok(dok, shape, domain).to_dfm() + + def iter_values(self): + """Iterate over the non-zero values of the matrix.""" + m, n = self.shape + rep = self.rep + for i in range(m): + for j in range(n): + repij = rep[i, j] + if repij: + yield rep[i, j] + + def iter_items(self): + """Iterate over indices and values of nonzero elements of the matrix.""" + m, n = self.shape + rep = self.rep + for i in range(m): + for j in range(n): + repij = rep[i, j] + if repij: + yield ((i, j), repij) + + def convert_to(self, domain): + """Convert to a new domain.""" + if domain == self.domain: + return self.copy() + elif domain == QQ and self.domain == ZZ: + return self._new(flint.fmpq_mat(self.rep), self.shape, domain) + elif self._supports_domain(domain): + # XXX: Use more efficient conversions when possible. + return self.to_ddm().convert_to(domain).to_dfm() + else: + # It is the callers responsibility to convert to DDM before calling + # this method if the domain is not supported by DFM. + raise NotImplementedError("Only ZZ and QQ are supported by DFM") + + def getitem(self, i, j): + """Get the ``(i, j)``-th entry.""" + # XXX: flint matrices do not support negative indices + # XXX: They also raise ValueError instead of IndexError + m, n = self.shape + if i < 0: + i += m + if j < 0: + j += n + try: + return self.rep[i, j] + except ValueError: + raise IndexError(f"Invalid indices ({i}, {j}) for Matrix of shape {self.shape}") + + def setitem(self, i, j, value): + """Set the ``(i, j)``-th entry.""" + # XXX: flint matrices do not support negative indices + # XXX: They also raise ValueError instead of IndexError + m, n = self.shape + if i < 0: + i += m + if j < 0: + j += n + try: + self.rep[i, j] = value + except ValueError: + raise IndexError(f"Invalid indices ({i}, {j}) for Matrix of shape {self.shape}") + + def _extract(self, i_indices, j_indices): + """Extract a submatrix with no checking.""" + # Indices must be positive and in range. + M = self.rep + lol = [[M[i, j] for j in j_indices] for i in i_indices] + shape = (len(i_indices), len(j_indices)) + return self.from_list(lol, shape, self.domain) + + def extract(self, rowslist, colslist): + """Extract a submatrix.""" + # XXX: flint matrices do not support fancy indexing or negative indices + # + # Check and convert negative indices before calling _extract. + m, n = self.shape + + new_rows = [] + new_cols = [] + + for i in rowslist: + if i < 0: + i_pos = i + m + else: + i_pos = i + if not 0 <= i_pos < m: + raise IndexError(f"Invalid row index {i} for Matrix of shape {self.shape}") + new_rows.append(i_pos) + + for j in colslist: + if j < 0: + j_pos = j + n + else: + j_pos = j + if not 0 <= j_pos < n: + raise IndexError(f"Invalid column index {j} for Matrix of shape {self.shape}") + new_cols.append(j_pos) + + return self._extract(new_rows, new_cols) + + def extract_slice(self, rowslice, colslice): + """Slice a DFM.""" + # XXX: flint matrices do not support slicing + m, n = self.shape + i_indices = range(m)[rowslice] + j_indices = range(n)[colslice] + return self._extract(i_indices, j_indices) + + def neg(self): + """Negate a DFM matrix.""" + return self._new_rep(-self.rep) + + def add(self, other): + """Add two DFM matrices.""" + return self._new_rep(self.rep + other.rep) + + def sub(self, other): + """Subtract two DFM matrices.""" + return self._new_rep(self.rep - other.rep) + + def mul(self, other): + """Multiply a DFM matrix from the right by a scalar.""" + return self._new_rep(self.rep * other) + + def rmul(self, other): + """Multiply a DFM matrix from the left by a scalar.""" + return self._new_rep(other * self.rep) + + def mul_elementwise(self, other): + """Elementwise multiplication of two DFM matrices.""" + # XXX: flint matrices do not support elementwise multiplication + return self.to_ddm().mul_elementwise(other.to_ddm()).to_dfm() + + def matmul(self, other): + """Multiply two DFM matrices.""" + shape = (self.rows, other.cols) + return self._new(self.rep * other.rep, shape, self.domain) + + # XXX: For the most part DomainMatrix does not expect DDM, SDM, or DFM to + # have arithmetic operators defined. The only exception is negation. + # Perhaps that should be removed. + + def __neg__(self): + """Negate a DFM matrix.""" + return self.neg() + + @classmethod + def zeros(cls, shape, domain): + """Return a zero DFM matrix.""" + func = cls._get_flint_func(domain) + return cls._new(func(*shape), shape, domain) + + # XXX: flint matrices do not have anything like ones or eye + # In the methods below we convert to DDM and then back to DFM which is + # probably about as efficient as implementing these methods directly. + + @classmethod + def ones(cls, shape, domain): + """Return a one DFM matrix.""" + # XXX: flint matrices do not have anything like ones + return DDM.ones(shape, domain).to_dfm() + + @classmethod + def eye(cls, n, domain): + """Return the identity matrix of size n.""" + # XXX: flint matrices do not have anything like eye + return DDM.eye(n, domain).to_dfm() + + @classmethod + def diag(cls, elements, domain): + """Return a diagonal matrix.""" + return DDM.diag(elements, domain).to_dfm() + + def applyfunc(self, func, domain): + """Apply a function to each entry of a DFM matrix.""" + return self.to_ddm().applyfunc(func, domain).to_dfm() + + def transpose(self): + """Transpose a DFM matrix.""" + return self._new(self.rep.transpose(), (self.cols, self.rows), self.domain) + + def hstack(self, *others): + """Horizontally stack matrices.""" + return self.to_ddm().hstack(*[o.to_ddm() for o in others]).to_dfm() + + def vstack(self, *others): + """Vertically stack matrices.""" + return self.to_ddm().vstack(*[o.to_ddm() for o in others]).to_dfm() + + def diagonal(self): + """Return the diagonal of a DFM matrix.""" + M = self.rep + m, n = self.shape + return [M[i, i] for i in range(min(m, n))] + + def is_upper(self): + """Return ``True`` if the matrix is upper triangular.""" + M = self.rep + for i in range(self.rows): + for j in range(min(i, self.cols)): + if M[i, j]: + return False + return True + + def is_lower(self): + """Return ``True`` if the matrix is lower triangular.""" + M = self.rep + for i in range(self.rows): + for j in range(i + 1, self.cols): + if M[i, j]: + return False + return True + + def is_diagonal(self): + """Return ``True`` if the matrix is diagonal.""" + return self.is_upper() and self.is_lower() + + def is_zero_matrix(self): + """Return ``True`` if the matrix is the zero matrix.""" + M = self.rep + for i in range(self.rows): + for j in range(self.cols): + if M[i, j]: + return False + return True + + def nnz(self): + """Return the number of non-zero elements in the matrix.""" + return self.to_ddm().nnz() + + def scc(self): + """Return the strongly connected components of the matrix.""" + return self.to_ddm().scc() + + @doctest_depends_on(ground_types='flint') + def det(self): + """ + Compute the determinant of the matrix using FLINT. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> dfm = M.to_DM().to_dfm() + >>> dfm + [[1, 2], [3, 4]] + >>> dfm.det() + -2 + + Notes + ===== + + Calls the ``.det()`` method of the underlying FLINT matrix. + + For :ref:`ZZ` or :ref:`QQ` this calls ``fmpz_mat_det`` or + ``fmpq_mat_det`` respectively. + + At the time of writing the implementation of ``fmpz_mat_det`` uses one + of several algorithms depending on the size of the matrix and bit size + of the entries. The algorithms used are: + + - Cofactor for very small (up to 4x4) matrices. + - Bareiss for small (up to 25x25) matrices. + - Modular algorithms for larger matrices (up to 60x60) or for larger + matrices with large bit sizes. + - Modular "accelerated" for larger matrices (60x60 upwards) if the bit + size is smaller than the dimensions of the matrix. + + The implementation of ``fmpq_mat_det`` clears denominators from each + row (not the whole matrix) and then calls ``fmpz_mat_det`` and divides + by the product of the denominators. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.det + Higher level interface to compute the determinant of a matrix. + """ + # XXX: At least the first three algorithms described above should also + # be implemented in the pure Python DDM and SDM classes which at the + # time of writng just use Bareiss for all matrices and domains. + # Probably in Python the thresholds would be different though. + return self.rep.det() + + @doctest_depends_on(ground_types='flint') + def charpoly(self): + """ + Compute the characteristic polynomial of the matrix using FLINT. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> dfm = M.to_DM().to_dfm() # need ground types = 'flint' + >>> dfm + [[1, 2], [3, 4]] + >>> dfm.charpoly() + [1, -5, -2] + + Notes + ===== + + Calls the ``.charpoly()`` method of the underlying FLINT matrix. + + For :ref:`ZZ` or :ref:`QQ` this calls ``fmpz_mat_charpoly`` or + ``fmpq_mat_charpoly`` respectively. + + At the time of writing the implementation of ``fmpq_mat_charpoly`` + clears a denominator from the whole matrix and then calls + ``fmpz_mat_charpoly``. The coefficients of the characteristic + polynomial are then multiplied by powers of the denominator. + + The ``fmpz_mat_charpoly`` method uses a modular algorithm with CRT + reconstruction. The modular algorithm uses ``nmod_mat_charpoly`` which + uses Berkowitz for small matrices and non-prime moduli or otherwise + the Danilevsky method. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.charpoly + Higher level interface to compute the characteristic polynomial of + a matrix. + """ + # FLINT polynomial coefficients are in reverse order compared to SymPy. + return self.rep.charpoly().coeffs()[::-1] + + @doctest_depends_on(ground_types='flint') + def inv(self): + """ + Compute the inverse of a matrix using FLINT. + + Examples + ======== + + >>> from sympy import Matrix, QQ + >>> M = Matrix([[1, 2], [3, 4]]) + >>> dfm = M.to_DM().to_dfm().convert_to(QQ) + >>> dfm + [[1, 2], [3, 4]] + >>> dfm.inv() + [[-2, 1], [3/2, -1/2]] + >>> dfm.matmul(dfm.inv()) + [[1, 0], [0, 1]] + + Notes + ===== + + Calls the ``.inv()`` method of the underlying FLINT matrix. + + For now this will raise an error if the domain is :ref:`ZZ` but will + use the FLINT method for :ref:`QQ`. + + The FLINT methods for :ref:`ZZ` and :ref:`QQ` are ``fmpz_mat_inv`` and + ``fmpq_mat_inv`` respectively. The ``fmpz_mat_inv`` method computes an + inverse with denominator. This is implemented by calling + ``fmpz_mat_solve`` (see notes in :meth:`lu_solve` about the algorithm). + + The ``fmpq_mat_inv`` method clears denominators from each row and then + multiplies those into the rhs identity matrix before calling + ``fmpz_mat_solve``. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.inv + Higher level method for computing the inverse of a matrix. + """ + # TODO: Implement similar algorithms for DDM and SDM. + # + # XXX: The flint fmpz_mat and fmpq_mat inv methods both return fmpq_mat + # by default. The fmpz_mat method has an optional argument to return + # fmpz_mat instead for unimodular matrices. + # + # The convention in DomainMatrix is to raise an error if the matrix is + # not over a field regardless of whether the matrix is invertible over + # its domain or over any associated field. Maybe DomainMatrix.inv + # should be changed to always return a matrix over an associated field + # except with a unimodular argument for returning an inverse over a + # ring if possible. + # + # For now we follow the existing DomainMatrix convention... + K = self.domain + m, n = self.shape + + if m != n: + raise DMNonSquareMatrixError("cannot invert a non-square matrix") + + if K == ZZ: + raise DMDomainError("field expected, got %s" % K) + elif K == QQ or K.is_FF: + try: + return self._new_rep(self.rep.inv()) + except ZeroDivisionError: + raise DMNonInvertibleMatrixError("matrix is not invertible") + else: + # If more domains are added for DFM then we will need to consider + # what happens here. + raise NotImplementedError("DFM.inv() is not implemented for %s" % K) + + def lu(self): + """Return the LU decomposition of the matrix.""" + L, U, swaps = self.to_ddm().lu() + return L.to_dfm(), U.to_dfm(), swaps + + def qr(self): + """Return the QR decomposition of the matrix.""" + Q, R = self.to_ddm().qr() + return Q.to_dfm(), R.to_dfm() + + # XXX: The lu_solve function should be renamed to solve. Whether or not it + # uses an LU decomposition is an implementation detail. A method called + # lu_solve would make sense for a situation in which an LU decomposition is + # reused several times to solve with different rhs but that would imply a + # different call signature. + # + # The underlying python-flint method has an algorithm= argument so we could + # use that and have e.g. solve_lu and solve_modular or perhaps also a + # method= argument to choose between the two. Flint itself has more + # possible algorithms to choose from than are exposed by python-flint. + + @doctest_depends_on(ground_types='flint') + def lu_solve(self, rhs): + """ + Solve a matrix equation using FLINT. + + Examples + ======== + + >>> from sympy import Matrix, QQ + >>> M = Matrix([[1, 2], [3, 4]]) + >>> dfm = M.to_DM().to_dfm().convert_to(QQ) + >>> dfm + [[1, 2], [3, 4]] + >>> rhs = Matrix([1, 2]).to_DM().to_dfm().convert_to(QQ) + >>> dfm.lu_solve(rhs) + [[0], [1/2]] + + Notes + ===== + + Calls the ``.solve()`` method of the underlying FLINT matrix. + + For now this will raise an error if the domain is :ref:`ZZ` but will + use the FLINT method for :ref:`QQ`. + + The FLINT methods for :ref:`ZZ` and :ref:`QQ` are ``fmpz_mat_solve`` + and ``fmpq_mat_solve`` respectively. The ``fmpq_mat_solve`` method + uses one of two algorithms: + + - For small matrices (<25 rows) it clears denominators between the + matrix and rhs and uses ``fmpz_mat_solve``. + - For larger matrices it uses ``fmpq_mat_solve_dixon`` which is a + modular approach with CRT reconstruction over :ref:`QQ`. + + The ``fmpz_mat_solve`` method uses one of four algorithms: + + - For very small (<= 3x3) matrices it uses a Cramer's rule. + - For small (<= 15x15) matrices it uses a fraction-free LU solve. + - Otherwise it uses either Dixon or another multimodular approach. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.lu_solve + Higher level interface to solve a matrix equation. + """ + if not self.domain == rhs.domain: + raise DMDomainError("Domains must match: %s != %s" % (self.domain, rhs.domain)) + + # XXX: As for inv we should consider whether to return a matrix over + # over an associated field or attempt to find a solution in the ring. + # For now we follow the existing DomainMatrix convention... + if not self.domain.is_Field: + raise DMDomainError("Field expected, got %s" % self.domain) + + m, n = self.shape + j, k = rhs.shape + if m != j: + raise DMShapeError("Matrix size mismatch: %s * %s vs %s * %s" % (m, n, j, k)) + sol_shape = (n, k) + + # XXX: The Flint solve method only handles square matrices. Probably + # Flint has functions that could be used to solve non-square systems + # but they are not exposed in python-flint yet. Alternatively we could + # put something here using the features that are available like rref. + if m != n: + return self.to_ddm().lu_solve(rhs.to_ddm()).to_dfm() + + try: + sol = self.rep.solve(rhs.rep) + except ZeroDivisionError: + raise DMNonInvertibleMatrixError("Matrix det == 0; not invertible.") + + return self._new(sol, sol_shape, self.domain) + + def fflu(self): + """ + Fraction-free LU decomposition of DFM. + + Explanation + =========== + + Uses `python-flint` if possible for a matrix of + integers otherwise uses the DDM method. + + See Also + ======== + + sympy.polys.matrices.ddm.DDM.fflu + """ + if self.domain == ZZ: + fflu = getattr(self.rep, 'fflu', None) + if fflu is not None: + P, L, D, U = self.rep.fflu() + m, n = self.shape + return ( + self._new(P, (m, m), self.domain), + self._new(L, (m, m), self.domain), + self._new(D, (m, m), self.domain), + self._new(U, self.shape, self.domain) + ) + ddm_p, ddm_l, ddm_d, ddm_u = self.to_ddm().fflu() + P = ddm_p.to_dfm() + L = ddm_l.to_dfm() + D = ddm_d.to_dfm() + U = ddm_u.to_dfm() + return P, L, D, U + + def nullspace(self): + """Return a basis for the nullspace of the matrix.""" + # Code to compute nullspace using flint: + # + # V, nullity = self.rep.nullspace() + # V_dfm = self._new_rep(V)._extract(range(self.rows), range(nullity)) + # + # XXX: That gives the nullspace but does not give us nonpivots. So we + # use the slower DDM method anyway. It would be better to change the + # signature of the nullspace method to not return nonpivots. + # + # XXX: Also python-flint exposes a nullspace method for fmpz_mat but + # not for fmpq_mat. This is the reverse of the situation for DDM etc + # which only allow nullspace over a field. The nullspace method for + # DDM, SDM etc should be changed to allow nullspace over ZZ as well. + # The DomainMatrix nullspace method does allow the domain to be a ring + # but does not directly call the lower-level nullspace methods and uses + # rref_den instead. Nullspace methods should also be added to all + # matrix types in python-flint. + ddm, nonpivots = self.to_ddm().nullspace() + return ddm.to_dfm(), nonpivots + + def nullspace_from_rref(self, pivots=None): + """Return a basis for the nullspace of the matrix.""" + # XXX: Use the flint nullspace method!!! + sdm, nonpivots = self.to_sdm().nullspace_from_rref(pivots=pivots) + return sdm.to_dfm(), nonpivots + + def particular(self): + """Return a particular solution to the system.""" + return self.to_ddm().particular().to_dfm() + + def _lll(self, transform=False, delta=0.99, eta=0.51, rep='zbasis', gram='approx'): + """Call the fmpz_mat.lll() method but check rank to avoid segfaults.""" + + # XXX: There are tests that pass e.g. QQ(5,6) for delta. That fails + # with a TypeError in flint because if QQ is fmpq then conversion with + # float fails. We handle that here but there are two better fixes: + # + # - Make python-flint's fmpq convert with float(x) + # - Change the tests because delta should just be a float. + + def to_float(x): + if QQ.of_type(x): + return float(x.numerator) / float(x.denominator) + else: + return float(x) + + delta = to_float(delta) + eta = to_float(eta) + + if not 0.25 < delta < 1: + raise DMValueError("delta must be between 0.25 and 1") + + # XXX: The flint lll method segfaults if the matrix is not full rank. + m, n = self.shape + if self.rep.rank() != m: + raise DMRankError("Matrix must have full row rank for Flint LLL.") + + # Actually call the flint method. + return self.rep.lll(transform=transform, delta=delta, eta=eta, rep=rep, gram=gram) + + @doctest_depends_on(ground_types='flint') + def lll(self, delta=0.75): + """Compute LLL-reduced basis using FLINT. + + See :meth:`lll_transform` for more information. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2, 3], [4, 5, 6]]) + >>> M.to_DM().to_dfm().lll() + [[2, 1, 0], [-1, 1, 3]] + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.lll + Higher level interface to compute LLL-reduced basis. + lll_transform + Compute LLL-reduced basis and transform matrix. + """ + if self.domain != ZZ: + raise DMDomainError("ZZ expected, got %s" % self.domain) + elif self.rows > self.cols: + raise DMShapeError("Matrix must not have more rows than columns.") + + rep = self._lll(delta=delta) + return self._new_rep(rep) + + @doctest_depends_on(ground_types='flint') + def lll_transform(self, delta=0.75): + """Compute LLL-reduced basis and transform using FLINT. + + Examples + ======== + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2, 3], [4, 5, 6]]).to_DM().to_dfm() + >>> M_lll, T = M.lll_transform() + >>> M_lll + [[2, 1, 0], [-1, 1, 3]] + >>> T + [[-2, 1], [3, -1]] + >>> T.matmul(M) == M_lll + True + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.lll + Higher level interface to compute LLL-reduced basis. + lll + Compute LLL-reduced basis without transform matrix. + """ + if self.domain != ZZ: + raise DMDomainError("ZZ expected, got %s" % self.domain) + elif self.rows > self.cols: + raise DMShapeError("Matrix must not have more rows than columns.") + + rep, T = self._lll(transform=True, delta=delta) + basis = self._new_rep(rep) + T_dfm = self._new(T, (self.rows, self.rows), self.domain) + return basis, T_dfm + + +# Avoid circular imports +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.ddm import SDM diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/_typing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..fc7c3b601fe85d591ddf853acbf33f5bba64b11c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/_typing.py @@ -0,0 +1,16 @@ +from typing import TypeVar, Protocol + + +T = TypeVar('T') + + +class RingElement(Protocol): + """A ring element. + + Must support ``+``, ``-``, ``*``, ``**`` and ``-``. + """ + def __add__(self: T, other: T, /) -> T: ... + def __sub__(self: T, other: T, /) -> T: ... + def __mul__(self: T, other: T, /) -> T: ... + def __pow__(self: T, other: int, /) -> T: ... + def __neg__(self: T, /) -> T: ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/ddm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/ddm.py new file mode 100644 index 0000000000000000000000000000000000000000..9b7836ef298fe27a1c02ed069f33711a632d6ed8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/ddm.py @@ -0,0 +1,1176 @@ +""" + +Module for the DDM class. + +The DDM class is an internal representation used by DomainMatrix. The letters +DDM stand for Dense Domain Matrix. A DDM instance represents a matrix using +elements from a polynomial Domain (e.g. ZZ, QQ, ...) in a dense-matrix +representation. + +Basic usage: + + >>> from sympy import ZZ, QQ + >>> from sympy.polys.matrices.ddm import DDM + >>> A = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) + >>> A.shape + (2, 2) + >>> A + [[0, 1], [-1, 0]] + >>> type(A) + + >>> A @ A + [[-1, 0], [0, -1]] + +The ddm_* functions are designed to operate on DDM as well as on an ordinary +list of lists: + + >>> from sympy.polys.matrices.dense import ddm_idet + >>> ddm_idet(A, QQ) + 1 + >>> ddm_idet([[0, 1], [-1, 0]], QQ) + 1 + >>> A + [[-1, 0], [0, -1]] + +Note that ddm_idet modifies the input matrix in-place. It is recommended to +use the DDM.det method as a friendlier interface to this instead which takes +care of copying the matrix: + + >>> B = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) + >>> B.det() + 1 + +Normally DDM would not be used directly and is just part of the internal +representation of DomainMatrix which adds further functionality including e.g. +unifying domains. + +The dense format used by DDM is a list of lists of elements e.g. the 2x2 +identity matrix is like [[1, 0], [0, 1]]. The DDM class itself is a subclass +of list and its list items are plain lists. Elements are accessed as e.g. +ddm[i][j] where ddm[i] gives the ith row and ddm[i][j] gets the element in the +jth column of that row. Subclassing list makes e.g. iteration and indexing +very efficient. We do not override __getitem__ because it would lose that +benefit. + +The core routines are implemented by the ddm_* functions defined in dense.py. +Those functions are intended to be able to operate on a raw list-of-lists +representation of matrices with most functions operating in-place. The DDM +class takes care of copying etc and also stores a Domain object associated +with its elements. This makes it possible to implement things like A + B with +domain checking and also shape checking so that the list of lists +representation is friendlier. + +""" +from itertools import chain + +from sympy.external.gmpy import GROUND_TYPES +from sympy.utilities.decorator import doctest_depends_on + +from .exceptions import ( + DMBadInputError, + DMDomainError, + DMNonSquareMatrixError, + DMShapeError, +) + +from sympy.polys.domains import QQ + +from .dense import ( + ddm_transpose, + ddm_iadd, + ddm_isub, + ddm_ineg, + ddm_imul, + ddm_irmul, + ddm_imatmul, + ddm_irref, + ddm_irref_den, + ddm_idet, + ddm_iinv, + ddm_ilu_split, + ddm_ilu_solve, + ddm_berk, + ) + +from .lll import ddm_lll, ddm_lll_transform + + +if GROUND_TYPES != 'flint': + __doctest_skip__ = ['DDM.to_dfm', 'DDM.to_dfm_or_ddm'] + + +class DDM(list): + """Dense matrix based on polys domain elements + + This is a list subclass and is a wrapper for a list of lists that supports + basic matrix arithmetic +, -, *, **. + """ + + fmt = 'dense' + is_DFM = False + is_DDM = True + + def __init__(self, rowslist, shape, domain): + if not (isinstance(rowslist, list) and all(type(row) is list for row in rowslist)): + raise DMBadInputError("rowslist must be a list of lists") + m, n = shape + if len(rowslist) != m or any(len(row) != n for row in rowslist): + raise DMBadInputError("Inconsistent row-list/shape") + + super().__init__([i.copy() for i in rowslist]) + self.shape = (m, n) + self.rows = m + self.cols = n + self.domain = domain + + def getitem(self, i, j): + return self[i][j] + + def setitem(self, i, j, value): + self[i][j] = value + + def extract_slice(self, slice1, slice2): + ddm = [row[slice2] for row in self[slice1]] + rows = len(ddm) + cols = len(ddm[0]) if ddm else len(range(self.shape[1])[slice2]) + return DDM(ddm, (rows, cols), self.domain) + + def extract(self, rows, cols): + ddm = [] + for i in rows: + rowi = self[i] + ddm.append([rowi[j] for j in cols]) + return DDM(ddm, (len(rows), len(cols)), self.domain) + + @classmethod + def from_list(cls, rowslist, shape, domain): + """ + Create a :class:`DDM` from a list of lists. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.ddm import DDM + >>> A = DDM.from_list([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) + >>> A + [[0, 1], [-1, 0]] + >>> A == DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) + True + + See Also + ======== + + from_list_flat + """ + return cls(rowslist, shape, domain) + + @classmethod + def from_ddm(cls, other): + return other.copy() + + def to_list(self): + """ + Convert to a list of lists. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.ddm import DDM + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> A.to_list() + [[1, 2], [3, 4]] + + See Also + ======== + + to_list_flat + sympy.polys.matrices.domainmatrix.DomainMatrix.to_list + """ + return [row[:] for row in self] + + def to_list_flat(self): + """ + Convert to a flat list of elements. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.ddm import DDM + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> A.to_list_flat() + [1, 2, 3, 4] + >>> A == DDM.from_list_flat(A.to_list_flat(), A.shape, A.domain) + True + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.to_list_flat + """ + flat = [] + for row in self: + flat.extend(row) + return flat + + @classmethod + def from_list_flat(cls, flat, shape, domain): + """ + Create a :class:`DDM` from a flat list of elements. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.ddm import DDM + >>> A = DDM.from_list_flat([1, 2, 3, 4], (2, 2), QQ) + >>> A + [[1, 2], [3, 4]] + >>> A == DDM.from_list_flat(A.to_list_flat(), A.shape, A.domain) + True + + See Also + ======== + + to_list_flat + sympy.polys.matrices.domainmatrix.DomainMatrix.from_list_flat + """ + assert type(flat) is list + rows, cols = shape + if not (len(flat) == rows*cols): + raise DMBadInputError("Inconsistent flat-list shape") + lol = [flat[i*cols:(i+1)*cols] for i in range(rows)] + return cls(lol, shape, domain) + + def flatiter(self): + return chain.from_iterable(self) + + def flat(self): + items = [] + for row in self: + items.extend(row) + return items + + def to_flat_nz(self): + """ + Convert to a flat list of nonzero elements and data. + + Explanation + =========== + + This is used to operate on a list of the elements of a matrix and then + reconstruct a matrix using :meth:`from_flat_nz`. Zero elements are + included in the list but that may change in the future. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> elements, data = A.to_flat_nz() + >>> elements + [1, 2, 3, 4] + >>> A == DDM.from_flat_nz(elements, data, A.domain) + True + + See Also + ======== + + from_flat_nz + sympy.polys.matrices.sdm.SDM.to_flat_nz + sympy.polys.matrices.domainmatrix.DomainMatrix.to_flat_nz + """ + return self.to_sdm().to_flat_nz() + + @classmethod + def from_flat_nz(cls, elements, data, domain): + """ + Reconstruct a :class:`DDM` after calling :meth:`to_flat_nz`. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> elements, data = A.to_flat_nz() + >>> elements + [1, 2, 3, 4] + >>> A == DDM.from_flat_nz(elements, data, A.domain) + True + + See Also + ======== + + to_flat_nz + sympy.polys.matrices.sdm.SDM.from_flat_nz + sympy.polys.matrices.domainmatrix.DomainMatrix.from_flat_nz + """ + return SDM.from_flat_nz(elements, data, domain).to_ddm() + + def to_dod(self): + """ + Convert to a dictionary of dictionaries (dod) format. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> A.to_dod() + {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}} + + See Also + ======== + + from_dod + sympy.polys.matrices.sdm.SDM.to_dod + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dod + """ + dod = {} + for i, row in enumerate(self): + row = {j:e for j, e in enumerate(row) if e} + if row: + dod[i] = row + return dod + + @classmethod + def from_dod(cls, dod, shape, domain): + """ + Create a :class:`DDM` from a dictionary of dictionaries (dod) format. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> dod = {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}} + >>> A = DDM.from_dod(dod, (2, 2), QQ) + >>> A + [[1, 2], [3, 4]] + + See Also + ======== + + to_dod + sympy.polys.matrices.sdm.SDM.from_dod + sympy.polys.matrices.domainmatrix.DomainMatrix.from_dod + """ + rows, cols = shape + lol = [[domain.zero] * cols for _ in range(rows)] + for i, row in dod.items(): + for j, element in row.items(): + lol[i][j] = element + return DDM(lol, shape, domain) + + def to_dok(self): + """ + Convert :class:`DDM` to dictionary of keys (dok) format. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> A.to_dok() + {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4} + + See Also + ======== + + from_dok + sympy.polys.matrices.sdm.SDM.to_dok + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dok + """ + dok = {} + for i, row in enumerate(self): + for j, element in enumerate(row): + if element: + dok[i, j] = element + return dok + + @classmethod + def from_dok(cls, dok, shape, domain): + """ + Create a :class:`DDM` from a dictionary of keys (dok) format. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> dok = {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4} + >>> A = DDM.from_dok(dok, (2, 2), QQ) + >>> A + [[1, 2], [3, 4]] + + See Also + ======== + + to_dok + sympy.polys.matrices.sdm.SDM.from_dok + sympy.polys.matrices.domainmatrix.DomainMatrix.from_dok + """ + rows, cols = shape + lol = [[domain.zero] * cols for _ in range(rows)] + for (i, j), element in dok.items(): + lol[i][j] = element + return DDM(lol, shape, domain) + + def iter_values(self): + """ + Iterate over the non-zero values of the matrix. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[QQ(1), QQ(0)], [QQ(3), QQ(4)]], (2, 2), QQ) + >>> list(A.iter_values()) + [1, 3, 4] + + See Also + ======== + + iter_items + to_list_flat + sympy.polys.matrices.domainmatrix.DomainMatrix.iter_values + """ + for row in self: + yield from filter(None, row) + + def iter_items(self): + """ + Iterate over indices and values of nonzero elements of the matrix. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[QQ(1), QQ(0)], [QQ(3), QQ(4)]], (2, 2), QQ) + >>> list(A.iter_items()) + [((0, 0), 1), ((1, 0), 3), ((1, 1), 4)] + + See Also + ======== + + iter_values + to_dok + sympy.polys.matrices.domainmatrix.DomainMatrix.iter_items + """ + for i, row in enumerate(self): + for j, element in enumerate(row): + if element: + yield (i, j), element + + def to_ddm(self): + """ + Convert to a :class:`DDM`. + + This just returns ``self`` but exists to parallel the corresponding + method in other matrix types like :class:`~.SDM`. + + See Also + ======== + + to_sdm + to_dfm + to_dfm_or_ddm + sympy.polys.matrices.sdm.SDM.to_ddm + sympy.polys.matrices.domainmatrix.DomainMatrix.to_ddm + """ + return self + + def to_sdm(self): + """ + Convert to a :class:`~.SDM`. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> A.to_sdm() + {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}} + >>> type(A.to_sdm()) + + + See Also + ======== + + SDM + sympy.polys.matrices.sdm.SDM.to_ddm + """ + return SDM.from_list(self, self.shape, self.domain) + + @doctest_depends_on(ground_types=['flint']) + def to_dfm(self): + """ + Convert to :class:`~.DDM` to :class:`~.DFM`. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> A.to_dfm() + [[1, 2], [3, 4]] + >>> type(A.to_dfm()) + + + See Also + ======== + + DFM + sympy.polys.matrices._dfm.DFM.to_ddm + """ + return DFM(list(self), self.shape, self.domain) + + @doctest_depends_on(ground_types=['flint']) + def to_dfm_or_ddm(self): + """ + Convert to :class:`~.DFM` if possible or otherwise return self. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy import QQ + >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ) + >>> A.to_dfm_or_ddm() + [[1, 2], [3, 4]] + >>> type(A.to_dfm_or_ddm()) + + + See Also + ======== + + to_dfm + to_ddm + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm_or_ddm + """ + if DFM._supports_domain(self.domain): + return self.to_dfm() + return self + + def convert_to(self, K): + Kold = self.domain + if K == Kold: + return self.copy() + rows = [[K.convert_from(e, Kold) for e in row] for row in self] + return DDM(rows, self.shape, K) + + def __str__(self): + rowsstr = ['[%s]' % ', '.join(map(str, row)) for row in self] + return '[%s]' % ', '.join(rowsstr) + + def __repr__(self): + cls = type(self).__name__ + rows = list.__repr__(self) + return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain) + + def __eq__(self, other): + if not isinstance(other, DDM): + return False + return (super().__eq__(other) and self.domain == other.domain) + + def __ne__(self, other): + return not self.__eq__(other) + + @classmethod + def zeros(cls, shape, domain): + z = domain.zero + m, n = shape + rowslist = [[z] * n for _ in range(m)] + return DDM(rowslist, shape, domain) + + @classmethod + def ones(cls, shape, domain): + one = domain.one + m, n = shape + rowlist = [[one] * n for _ in range(m)] + return DDM(rowlist, shape, domain) + + @classmethod + def eye(cls, size, domain): + if isinstance(size, tuple): + m, n = size + elif isinstance(size, int): + m = n = size + one = domain.one + ddm = cls.zeros((m, n), domain) + for i in range(min(m, n)): + ddm[i][i] = one + return ddm + + def copy(self): + copyrows = [row[:] for row in self] + return DDM(copyrows, self.shape, self.domain) + + def transpose(self): + rows, cols = self.shape + if rows: + ddmT = ddm_transpose(self) + else: + ddmT = [[]] * cols + return DDM(ddmT, (cols, rows), self.domain) + + def __add__(a, b): + if not isinstance(b, DDM): + return NotImplemented + return a.add(b) + + def __sub__(a, b): + if not isinstance(b, DDM): + return NotImplemented + return a.sub(b) + + def __neg__(a): + return a.neg() + + def __mul__(a, b): + if b in a.domain: + return a.mul(b) + else: + return NotImplemented + + def __rmul__(a, b): + if b in a.domain: + return a.mul(b) + else: + return NotImplemented + + def __matmul__(a, b): + if isinstance(b, DDM): + return a.matmul(b) + else: + return NotImplemented + + @classmethod + def _check(cls, a, op, b, ashape, bshape): + if a.domain != b.domain: + msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain) + raise DMDomainError(msg) + if ashape != bshape: + msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape) + raise DMShapeError(msg) + + def add(a, b): + """a + b""" + a._check(a, '+', b, a.shape, b.shape) + c = a.copy() + ddm_iadd(c, b) + return c + + def sub(a, b): + """a - b""" + a._check(a, '-', b, a.shape, b.shape) + c = a.copy() + ddm_isub(c, b) + return c + + def neg(a): + """-a""" + b = a.copy() + ddm_ineg(b) + return b + + def mul(a, b): + c = a.copy() + ddm_imul(c, b) + return c + + def rmul(a, b): + c = a.copy() + ddm_irmul(c, b) + return c + + def matmul(a, b): + """a @ b (matrix product)""" + m, o = a.shape + o2, n = b.shape + a._check(a, '*', b, o, o2) + c = a.zeros((m, n), a.domain) + ddm_imatmul(c, a, b) + return c + + def mul_elementwise(a, b): + assert a.shape == b.shape + assert a.domain == b.domain + c = [[aij * bij for aij, bij in zip(ai, bi)] for ai, bi in zip(a, b)] + return DDM(c, a.shape, a.domain) + + def hstack(A, *B): + """Horizontally stacks :py:class:`~.DDM` matrices. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import DDM + + >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + >>> A.hstack(B) + [[1, 2, 5, 6], [3, 4, 7, 8]] + + >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + >>> A.hstack(B, C) + [[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]] + """ + Anew = list(A.copy()) + rows, cols = A.shape + domain = A.domain + + for Bk in B: + Bkrows, Bkcols = Bk.shape + assert Bkrows == rows + assert Bk.domain == domain + + cols += Bkcols + + for i, Bki in enumerate(Bk): + Anew[i].extend(Bki) + + return DDM(Anew, (rows, cols), A.domain) + + def vstack(A, *B): + """Vertically stacks :py:class:`~.DDM` matrices. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import DDM + + >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + >>> A.vstack(B) + [[1, 2], [3, 4], [5, 6], [7, 8]] + + >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + >>> A.vstack(B, C) + [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]] + """ + Anew = list(A.copy()) + rows, cols = A.shape + domain = A.domain + + for Bk in B: + Bkrows, Bkcols = Bk.shape + assert Bkcols == cols + assert Bk.domain == domain + + rows += Bkrows + + Anew.extend(Bk.copy()) + + return DDM(Anew, (rows, cols), A.domain) + + def applyfunc(self, func, domain): + elements = [list(map(func, row)) for row in self] + return DDM(elements, self.shape, domain) + + def nnz(a): + """Number of non-zero entries in :py:class:`~.DDM` matrix. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.nnz + """ + return sum(sum(map(bool, row)) for row in a) + + def scc(a): + """Strongly connected components of a square matrix *a*. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import DDM + >>> A = DDM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ) + >>> A.scc() + [[0], [1]] + + See also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.scc + + """ + return a.to_sdm().scc() + + @classmethod + def diag(cls, values, domain): + """Returns a square diagonal matrix with *values* on the diagonal. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import DDM + >>> DDM.diag([ZZ(1), ZZ(2), ZZ(3)], ZZ) + [[1, 0, 0], [0, 2, 0], [0, 0, 3]] + + See also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.diag + """ + return SDM.diag(values, domain).to_ddm() + + def rref(a): + """Reduced-row echelon form of a and list of pivots. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.rref + Higher level interface to this function. + sympy.polys.matrices.dense.ddm_irref + The underlying algorithm. + """ + b = a.copy() + K = a.domain + partial_pivot = K.is_RealField or K.is_ComplexField + pivots = ddm_irref(b, _partial_pivot=partial_pivot) + return b, pivots + + def rref_den(a): + """Reduced-row echelon form of a with denominator and list of pivots + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den + Higher level interface to this function. + sympy.polys.matrices.dense.ddm_irref_den + The underlying algorithm. + """ + b = a.copy() + K = a.domain + denom, pivots = ddm_irref_den(b, K) + return b, denom, pivots + + def nullspace(a): + """Returns a basis for the nullspace of a. + + The domain of the matrix must be a field. + + See Also + ======== + + rref + sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace + """ + rref, pivots = a.rref() + return rref.nullspace_from_rref(pivots) + + def nullspace_from_rref(a, pivots=None): + """Compute the nullspace of a matrix from its rref. + + The domain of the matrix can be any domain. + + Returns a tuple (basis, nonpivots). + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace + The higher level interface to this function. + """ + m, n = a.shape + K = a.domain + + if pivots is None: + pivots = [] + last_pivot = -1 + for i in range(m): + ai = a[i] + for j in range(last_pivot+1, n): + if ai[j]: + last_pivot = j + pivots.append(j) + break + + if not pivots: + return (a.eye(n, K), list(range(n))) + + # After rref the pivots are all one but after rref_den they may not be. + pivot_val = a[0][pivots[0]] + + basis = [] + nonpivots = [] + for i in range(n): + if i in pivots: + continue + nonpivots.append(i) + vec = [pivot_val if i == j else K.zero for j in range(n)] + for ii, jj in enumerate(pivots): + vec[jj] -= a[ii][i] + basis.append(vec) + + basis_ddm = DDM(basis, (len(basis), n), K) + + return (basis_ddm, nonpivots) + + def particular(a): + return a.to_sdm().particular().to_ddm() + + def det(a): + """Determinant of a""" + m, n = a.shape + if m != n: + raise DMNonSquareMatrixError("Determinant of non-square matrix") + b = a.copy() + K = b.domain + deta = ddm_idet(b, K) + return deta + + def inv(a): + """Inverse of a""" + m, n = a.shape + if m != n: + raise DMNonSquareMatrixError("Determinant of non-square matrix") + ainv = a.copy() + K = a.domain + ddm_iinv(ainv, a, K) + return ainv + + def lu(a): + """L, U decomposition of a""" + m, n = a.shape + K = a.domain + + U = a.copy() + L = a.eye(m, K) + swaps = ddm_ilu_split(L, U, K) + + return L, U, swaps + + def _fflu(self): + """ + Private method for Phase 1 of fraction-free LU decomposition. + Performs row operations and elimination to compute U and permutation indices. + + Returns: + LU : decomposition as a single matrix. + perm (list): Permutation indices for row swaps. + """ + rows, cols = self.shape + K = self.domain + + LU = self.copy() + perm = list(range(rows)) + rank = 0 + + for j in range(min(rows, cols)): + # Skip columns where all entries are zero + if all(LU[i][j] == K.zero for i in range(rows)): + continue + + # Find the first non-zero pivot in the current column + pivot_row = -1 + for i in range(rank, rows): + if LU[i][j] != K.zero: + pivot_row = i + break + + # If no pivot is found, skip column + if pivot_row == -1: + continue + + # Swap rows to bring the pivot to the current rank + if pivot_row != rank: + LU[rank], LU[pivot_row] = LU[pivot_row], LU[rank] + perm[rank], perm[pivot_row] = perm[pivot_row], perm[rank] + + # Found pivot - (Gauss-Bareiss elimination) + pivot = LU[rank][j] + for i in range(rank + 1, rows): + multiplier = LU[i][j] + # Denominator is previous pivot or 1 + denominator = LU[rank - 1][rank - 1] if rank > 0 else K.one + for k in range(j + 1, cols): + LU[i][k] = K.exquo(pivot * LU[i][k] - LU[rank][k] * multiplier, denominator) + # Keep the multiplier for L matrix + LU[i][j] = multiplier + rank += 1 + + return LU, perm + + def fflu(self): + """ + Fraction-free LU decomposition of DDM. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.fflu + The higher-level interface to this function. + """ + rows, cols = self.shape + K = self.domain + + # Phase 1: Perform row operations and get permutation + U, perm = self._fflu() + + # Phase 2: Construct P, L, D matrices + # Create P from permutation + P = self.zeros((rows, rows), K) + for i, pi in enumerate(perm): + P[i][pi] = K.one + + # Create L matrix + L = self.zeros((rows, rows), K) + i = j = 0 + while i < rows and j < cols: + if U[i][j] != K.zero: + # Found non-zero pivot + # Diagonal entry is the pivot + L[i][i] = U[i][j] + for l in range(i + 1, rows): + # Off-diagonal entries are the multipliers + L[l][i] = U[l][j] + # zero out the entries in U + U[l][j] = K.zero + i += 1 + j += 1 + + # Fill remaining diagonal of L with ones + for i in range(i, rows): + L[i][i] = K.one + + # Create D matrix - using FLINT's approach with accumulator + D = self.zeros((rows, rows), K) + if rows >= 1: + D[0][0] = L[0][0] + di = K.one + for i in range(1, rows): + # Accumulate product of pivots + di = L[i - 1][i - 1] * L[i][i] + D[i][i] = di + + return P, L, D, U + + def qr(self): + """ + QR decomposition for DDM. + + Returns: + - Q: Orthogonal matrix as a DDM. + - R: Upper triangular matrix as a DDM. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.qr + The higher-level interface to this function. + """ + rows, cols = self.shape + K = self.domain + Q = self.copy() + R = self.zeros((min(rows, cols), cols), K) + + # Check that the domain is a field + if not K.is_Field: + raise DMDomainError("QR decomposition requires a field (e.g. QQ).") + + dot_cols = lambda i, j: K.sum(Q[k][i] * Q[k][j] for k in range(rows)) + + for j in range(cols): + for i in range(min(j, rows)): + dot_ii = dot_cols(i, i) + if dot_ii != K.zero: + R[i][j] = dot_cols(i, j) / dot_ii + for k in range(rows): + Q[k][j] -= R[i][j] * Q[k][i] + + if j < rows: + dot_jj = dot_cols(j, j) + if dot_jj != K.zero: + R[j][j] = K.one + + Q = Q.extract(range(rows), range(min(rows, cols))) + + return Q, R + + def lu_solve(a, b): + """x where a*x = b""" + m, n = a.shape + m2, o = b.shape + a._check(a, 'lu_solve', b, m, m2) + if not a.domain.is_Field: + raise DMDomainError("lu_solve requires a field") + + L, U, swaps = a.lu() + x = a.zeros((n, o), a.domain) + ddm_ilu_solve(x, L, U, swaps, b) + return x + + def charpoly(a): + """Coefficients of characteristic polynomial of a""" + K = a.domain + m, n = a.shape + if m != n: + raise DMNonSquareMatrixError("Charpoly of non-square matrix") + vec = ddm_berk(a, K) + coeffs = [vec[i][0] for i in range(n+1)] + return coeffs + + def is_zero_matrix(self): + """ + Says whether this matrix has all zero entries. + """ + zero = self.domain.zero + return all(Mij == zero for Mij in self.flatiter()) + + def is_upper(self): + """ + Says whether this matrix is upper-triangular. True can be returned + even if the matrix is not square. + """ + zero = self.domain.zero + return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[:i]) + + def is_lower(self): + """ + Says whether this matrix is lower-triangular. True can be returned + even if the matrix is not square. + """ + zero = self.domain.zero + return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[i+1:]) + + def is_diagonal(self): + """ + Says whether this matrix is diagonal. True can be returned even if + the matrix is not square. + """ + return self.is_upper() and self.is_lower() + + def diagonal(self): + """ + Returns a list of the elements from the diagonal of the matrix. + """ + m, n = self.shape + return [self[i][i] for i in range(min(m, n))] + + def lll(A, delta=QQ(3, 4)): + return ddm_lll(A, delta=delta) + + def lll_transform(A, delta=QQ(3, 4)): + return ddm_lll_transform(A, delta=delta) + + +from .sdm import SDM +from .dfm import DFM diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/dense.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/dense.py new file mode 100644 index 0000000000000000000000000000000000000000..47ab2d6897c6d9f3781af23ccb68f96f15c7e859 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/dense.py @@ -0,0 +1,824 @@ +""" + +Module for the ddm_* routines for operating on a matrix in list of lists +matrix representation. + +These routines are used internally by the DDM class which also provides a +friendlier interface for them. The idea here is to implement core matrix +routines in a way that can be applied to any simple list representation +without the need to use any particular matrix class. For example we can +compute the RREF of a matrix like: + + >>> from sympy.polys.matrices.dense import ddm_irref + >>> M = [[1, 2, 3], [4, 5, 6]] + >>> pivots = ddm_irref(M) + >>> M + [[1.0, 0.0, -1.0], [0, 1.0, 2.0]] + +These are lower-level routines that work mostly in place.The routines at this +level should not need to know what the domain of the elements is but should +ideally document what operations they will use and what functions they need to +be provided with. + +The next-level up is the DDM class which uses these routines but wraps them up +with an interface that handles copying etc and keeps track of the Domain of +the elements of the matrix: + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.matrices.ddm import DDM + >>> M = DDM([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ) + >>> M + [[1, 2, 3], [4, 5, 6]] + >>> Mrref, pivots = M.rref() + >>> Mrref + [[1, 0, -1], [0, 1, 2]] + +""" +from __future__ import annotations +from operator import mul +from .exceptions import ( + DMShapeError, + DMDomainError, + DMNonInvertibleMatrixError, + DMNonSquareMatrixError, +) +from typing import Sequence, TypeVar +from sympy.polys.matrices._typing import RingElement + + +#: Type variable for the elements of the matrix +T = TypeVar('T') + +#: Type variable for the elements of the matrix that are in a ring +R = TypeVar('R', bound=RingElement) + + +def ddm_transpose(matrix: Sequence[Sequence[T]]) -> list[list[T]]: + """matrix transpose""" + return list(map(list, zip(*matrix))) + + +def ddm_iadd(a: list[list[R]], b: Sequence[Sequence[R]]) -> None: + """a += b""" + for ai, bi in zip(a, b): + for j, bij in enumerate(bi): + ai[j] += bij + + +def ddm_isub(a: list[list[R]], b: Sequence[Sequence[R]]) -> None: + """a -= b""" + for ai, bi in zip(a, b): + for j, bij in enumerate(bi): + ai[j] -= bij + + +def ddm_ineg(a: list[list[R]]) -> None: + """a <-- -a""" + for ai in a: + for j, aij in enumerate(ai): + ai[j] = -aij + + +def ddm_imul(a: list[list[R]], b: R) -> None: + """a <-- a*b""" + for ai in a: + for j, aij in enumerate(ai): + ai[j] = aij * b + + +def ddm_irmul(a: list[list[R]], b: R) -> None: + """a <-- b*a""" + for ai in a: + for j, aij in enumerate(ai): + ai[j] = b * aij + + +def ddm_imatmul( + a: list[list[R]], b: Sequence[Sequence[R]], c: Sequence[Sequence[R]] +) -> None: + """a += b @ c""" + cT = list(zip(*c)) + + for bi, ai in zip(b, a): + for j, cTj in enumerate(cT): + ai[j] = sum(map(mul, bi, cTj), ai[j]) + + +def ddm_irref(a, _partial_pivot=False): + """In-place reduced row echelon form of a matrix. + + Compute the reduced row echelon form of $a$. Modifies $a$ in place and + returns a list of the pivot columns. + + Uses naive Gauss-Jordan elimination in the ground domain which must be a + field. + + This routine is only really suitable for use with simple field domains like + :ref:`GF(p)`, :ref:`QQ` and :ref:`QQ(a)` although even for :ref:`QQ` with + larger matrices it is possibly more efficient to use fraction free + approaches. + + This method is not suitable for use with rational function fields + (:ref:`K(x)`) because the elements will blowup leading to costly gcd + operations. In this case clearing denominators and using fraction free + approaches is likely to be more efficient. + + For inexact numeric domains like :ref:`RR` and :ref:`CC` pass + ``_partial_pivot=True`` to use partial pivoting to control rounding errors. + + Examples + ======== + + >>> from sympy.polys.matrices.dense import ddm_irref + >>> from sympy import QQ + >>> M = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]] + >>> pivots = ddm_irref(M) + >>> M + [[1, 0, -1], [0, 1, 2]] + >>> pivots + [0, 1] + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.rref + Higher level interface to this routine. + ddm_irref_den + The fraction free version of this routine. + sdm_irref + A sparse version of this routine. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Row_echelon_form#Reduced_row_echelon_form + """ + # We compute aij**-1 below and then use multiplication instead of division + # in the innermost loop. The domain here is a field so either operation is + # defined. There are significant performance differences for some domains + # though. In the case of e.g. QQ or QQ(x) inversion is free but + # multiplication and division have the same cost so it makes no difference. + # In cases like GF(p), QQ, RR or CC though multiplication is + # faster than division so reusing a precomputed inverse for many + # multiplications can be a lot faster. The biggest win is QQ when + # deg(minpoly(a)) is large. + # + # With domains like QQ(x) this can perform badly for other reasons. + # Typically the initial matrix has simple denominators and the + # fraction-free approach with exquo (ddm_irref_den) will preserve that + # property throughout. The method here causes denominator blowup leading to + # expensive gcd reductions in the intermediate expressions. With many + # generators like QQ(x,y,z,...) this is extremely bad. + # + # TODO: Use a nontrivial pivoting strategy to control intermediate + # expression growth. Rearranging rows and/or columns could defer the most + # complicated elements until the end. If the first pivot is a + # complicated/large element then the first round of reduction will + # immediately introduce expression blowup across the whole matrix. + + # a is (m x n) + m = len(a) + if not m: + return [] + n = len(a[0]) + + i = 0 + pivots = [] + + for j in range(n): + # Proper pivoting should be used for all domains for performance + # reasons but it is only strictly needed for RR and CC (and possibly + # other domains like RR(x)). This path is used by DDM.rref() if the + # domain is RR or CC. It uses partial (row) pivoting based on the + # absolute value of the pivot candidates. + if _partial_pivot: + ip = max(range(i, m), key=lambda ip: abs(a[ip][j])) + a[i], a[ip] = a[ip], a[i] + + # pivot + aij = a[i][j] + + # zero-pivot + if not aij: + for ip in range(i+1, m): + aij = a[ip][j] + # row-swap + if aij: + a[i], a[ip] = a[ip], a[i] + break + else: + # next column + continue + + # normalise row + ai = a[i] + aijinv = aij**-1 + for l in range(j, n): + ai[l] *= aijinv # ai[j] = one + + # eliminate above and below to the right + for k, ak in enumerate(a): + if k == i or not ak[j]: + continue + akj = ak[j] + ak[j] -= akj # ak[j] = zero + for l in range(j+1, n): + ak[l] -= akj * ai[l] + + # next row + pivots.append(j) + i += 1 + + # no more rows? + if i >= m: + break + + return pivots + + +def ddm_irref_den(a, K): + """a <-- rref(a); return (den, pivots) + + Compute the fraction-free reduced row echelon form (RREF) of $a$. Modifies + $a$ in place and returns a tuple containing the denominator of the RREF and + a list of the pivot columns. + + Explanation + =========== + + The algorithm used is the fraction-free version of Gauss-Jordan elimination + described as FFGJ in [1]_. Here it is modified to handle zero or missing + pivots and to avoid redundant arithmetic. + + The domain $K$ must support exact division (``K.exquo``) but does not need + to be a field. This method is suitable for most exact rings and fields like + :ref:`ZZ`, :ref:`QQ` and :ref:`QQ(a)`. In the case of :ref:`QQ` or + :ref:`K(x)` it might be more efficient to clear denominators and use + :ref:`ZZ` or :ref:`K[x]` instead. + + For inexact domains like :ref:`RR` and :ref:`CC` use ``ddm_irref`` instead. + + Examples + ======== + + >>> from sympy.polys.matrices.dense import ddm_irref_den + >>> from sympy import ZZ, Matrix + >>> M = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)]] + >>> den, pivots = ddm_irref_den(M, ZZ) + >>> M + [[-3, 0, 3], [0, -3, -6]] + >>> den + -3 + >>> pivots + [0, 1] + >>> Matrix(M).rref()[0] + Matrix([ + [1, 0, -1], + [0, 1, 2]]) + + See Also + ======== + + ddm_irref + A version of this routine that uses field division. + sdm_irref + A sparse version of :func:`ddm_irref`. + sdm_rref_den + A sparse version of :func:`ddm_irref_den`. + sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den + Higher level interface. + + References + ========== + + .. [1] Fraction-free algorithms for linear and polynomial equations. + George C. Nakos , Peter R. Turner , Robert M. Williams. + https://dl.acm.org/doi/10.1145/271130.271133 + """ + # + # A simpler presentation of this algorithm is given in [1]: + # + # Given an n x n matrix A and n x 1 matrix b: + # + # for i in range(n): + # if i != 0: + # d = a[i-1][i-1] + # for j in range(n): + # if j == i: + # continue + # b[j] = a[i][i]*b[j] - a[j][i]*b[i] + # for k in range(n): + # a[j][k] = a[i][i]*a[j][k] - a[j][i]*a[i][k] + # if i != 0: + # a[j][k] /= d + # + # Our version here is a bit more complicated because: + # + # 1. We use row-swaps to avoid zero pivots. + # 2. We allow for some columns to be missing pivots. + # 3. We avoid a lot of redundant arithmetic. + # + # TODO: Use a non-trivial pivoting strategy. Even just row swapping makes a + # big difference to performance if e.g. the upper-left entry of the matrix + # is a huge polynomial. + + # a is (m x n) + m = len(a) + if not m: + return K.one, [] + n = len(a[0]) + + d = None + pivots = [] + no_pivots = [] + + # i, j will be the row and column indices of the current pivot + i = 0 + for j in range(n): + # next pivot? + aij = a[i][j] + + # swap rows if zero + if not aij: + for ip in range(i+1, m): + aij = a[ip][j] + # row-swap + if aij: + a[i], a[ip] = a[ip], a[i] + break + else: + # go to next column + no_pivots.append(j) + continue + + # Now aij is the pivot and i,j are the row and column. We need to clear + # the column above and below but we also need to keep track of the + # denominator of the RREF which means also multiplying everything above + # and to the left by the current pivot aij and dividing by d (which we + # multiplied everything by in the previous iteration so this is an + # exact division). + # + # First handle the upper left corner which is usually already diagonal + # with all diagonal entries equal to the current denominator but there + # can be other non-zero entries in any column that has no pivot. + + # Update previous pivots in the matrix + if pivots: + pivot_val = aij * a[0][pivots[0]] + # Divide out the common factor + if d is not None: + pivot_val = K.exquo(pivot_val, d) + + # Could defer this until the end but it is pretty cheap and + # helps when debugging. + for ip, jp in enumerate(pivots): + a[ip][jp] = pivot_val + + # Update columns without pivots + for jnp in no_pivots: + for ip in range(i): + aijp = a[ip][jnp] + if aijp: + aijp *= aij + if d is not None: + aijp = K.exquo(aijp, d) + a[ip][jnp] = aijp + + # Eliminate above, below and to the right as in ordinary division free + # Gauss-Jordan elmination except also dividing out d from every entry. + + for jp, aj in enumerate(a): + + # Skip the current row + if jp == i: + continue + + # Eliminate to the right in all rows + for kp in range(j+1, n): + ajk = aij * aj[kp] - aj[j] * a[i][kp] + if d is not None: + ajk = K.exquo(ajk, d) + aj[kp] = ajk + + # Set to zero above and below the pivot + aj[j] = K.zero + + # next row + pivots.append(j) + i += 1 + + # no more rows left? + if i >= m: + break + + if not K.is_one(aij): + d = aij + else: + d = None + + if not pivots: + denom = K.one + else: + denom = a[0][pivots[0]] + + return denom, pivots + + +def ddm_idet(a, K): + """a <-- echelon(a); return det + + Explanation + =========== + + Compute the determinant of $a$ using the Bareiss fraction-free algorithm. + The matrix $a$ is modified in place. Its diagonal elements are the + determinants of the leading principal minors. The determinant of $a$ is + returned. + + The domain $K$ must support exact division (``K.exquo``). This method is + suitable for most exact rings and fields like :ref:`ZZ`, :ref:`QQ` and + :ref:`QQ(a)` but not for inexact domains like :ref:`RR` and :ref:`CC`. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.ddm import ddm_idet + >>> a = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]] + >>> a + [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + >>> ddm_idet(a, ZZ) + 0 + >>> a + [[1, 2, 3], [4, -3, -6], [7, -6, 0]] + >>> [a[i][i] for i in range(len(a))] + [1, -3, 0] + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.det + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Bareiss_algorithm + .. [2] https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf + """ + # Bareiss algorithm + # https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf + + # a is (m x n) + m = len(a) + if not m: + return K.one + n = len(a[0]) + + exquo = K.exquo + # uf keeps track of the sign change from row swaps + uf = K.one + + for k in range(n-1): + if not a[k][k]: + for i in range(k+1, n): + if a[i][k]: + a[k], a[i] = a[i], a[k] + uf = -uf + break + else: + return K.zero + + akkm1 = a[k-1][k-1] if k else K.one + + for i in range(k+1, n): + for j in range(k+1, n): + a[i][j] = exquo(a[i][j]*a[k][k] - a[i][k]*a[k][j], akkm1) + + return uf * a[-1][-1] + + +def ddm_iinv(ainv, a, K): + """ainv <-- inv(a) + + Compute the inverse of a matrix $a$ over a field $K$ using Gauss-Jordan + elimination. The result is stored in $ainv$. + + Uses division in the ground domain which should be an exact field. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import ddm_iinv, ddm_imatmul + >>> from sympy import QQ + >>> a = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] + >>> ainv = [[None, None], [None, None]] + >>> ddm_iinv(ainv, a, QQ) + >>> ainv + [[-2, 1], [3/2, -1/2]] + >>> result = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]] + >>> ddm_imatmul(result, a, ainv) + >>> result + [[1, 0], [0, 1]] + + See Also + ======== + + ddm_irref: the underlying routine. + """ + if not K.is_Field: + raise DMDomainError('Not a field') + + # a is (m x n) + m = len(a) + if not m: + return + n = len(a[0]) + if m != n: + raise DMNonSquareMatrixError + + eye = [[K.one if i==j else K.zero for j in range(n)] for i in range(n)] + Aaug = [row + eyerow for row, eyerow in zip(a, eye)] + pivots = ddm_irref(Aaug) + if pivots != list(range(n)): + raise DMNonInvertibleMatrixError('Matrix det == 0; not invertible.') + ainv[:] = [row[n:] for row in Aaug] + + +def ddm_ilu_split(L, U, K): + """L, U <-- LU(U) + + Compute the LU decomposition of a matrix $L$ in place and store the lower + and upper triangular matrices in $L$ and $U$, respectively. Returns a list + of row swaps that were performed. + + Uses division in the ground domain which should be an exact field. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import ddm_ilu_split + >>> from sympy import QQ + >>> L = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]] + >>> U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] + >>> swaps = ddm_ilu_split(L, U, QQ) + >>> swaps + [] + >>> L + [[0, 0], [3, 0]] + >>> U + [[1, 2], [0, -2]] + + See Also + ======== + + ddm_ilu + ddm_ilu_solve + """ + m = len(U) + if not m: + return [] + n = len(U[0]) + + swaps = ddm_ilu(U) + + zeros = [K.zero] * min(m, n) + for i in range(1, m): + j = min(i, n) + L[i][:j] = U[i][:j] + U[i][:j] = zeros[:j] + + return swaps + + +def ddm_ilu(a): + """a <-- LU(a) + + Computes the LU decomposition of a matrix in place. Returns a list of + row swaps that were performed. + + Uses division in the ground domain which should be an exact field. + + This is only suitable for domains like :ref:`GF(p)`, :ref:`QQ`, :ref:`QQ_I` + and :ref:`QQ(a)`. With a rational function field like :ref:`K(x)` it is + better to clear denominators and use division-free algorithms. Pivoting is + used to avoid exact zeros but not for floating point accuracy so :ref:`RR` + and :ref:`CC` are not suitable (use :func:`ddm_irref` instead). + + Examples + ======== + + >>> from sympy.polys.matrices.dense import ddm_ilu + >>> from sympy import QQ + >>> a = [[QQ(1, 2), QQ(1, 3)], [QQ(1, 4), QQ(1, 5)]] + >>> swaps = ddm_ilu(a) + >>> swaps + [] + >>> a + [[1/2, 1/3], [1/2, 1/30]] + + The same example using ``Matrix``: + + >>> from sympy import Matrix, S + >>> M = Matrix([[S(1)/2, S(1)/3], [S(1)/4, S(1)/5]]) + >>> L, U, swaps = M.LUdecomposition() + >>> L + Matrix([ + [ 1, 0], + [1/2, 1]]) + >>> U + Matrix([ + [1/2, 1/3], + [ 0, 1/30]]) + >>> swaps + [] + + See Also + ======== + + ddm_irref + ddm_ilu_solve + sympy.matrices.matrixbase.MatrixBase.LUdecomposition + """ + m = len(a) + if not m: + return [] + n = len(a[0]) + + swaps = [] + + for i in range(min(m, n)): + if not a[i][i]: + for ip in range(i+1, m): + if a[ip][i]: + swaps.append((i, ip)) + a[i], a[ip] = a[ip], a[i] + break + else: + # M = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]) + continue + for j in range(i+1, m): + l_ji = a[j][i] / a[i][i] + a[j][i] = l_ji + for k in range(i+1, n): + a[j][k] -= l_ji * a[i][k] + + return swaps + + +def ddm_ilu_solve(x, L, U, swaps, b): + """x <-- solve(L*U*x = swaps(b)) + + Solve a linear system, $A*x = b$, given an LU factorization of $A$. + + Uses division in the ground domain which must be a field. + + Modifies $x$ in place. + + Examples + ======== + + Compute the LU decomposition of $A$ (in place): + + >>> from sympy import QQ + >>> from sympy.polys.matrices.dense import ddm_ilu, ddm_ilu_solve + >>> A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] + >>> swaps = ddm_ilu(A) + >>> A + [[1, 2], [3, -2]] + >>> L = U = A + + Solve the linear system: + + >>> b = [[QQ(5)], [QQ(6)]] + >>> x = [[None], [None]] + >>> ddm_ilu_solve(x, L, U, swaps, b) + >>> x + [[-4], [9/2]] + + See Also + ======== + + ddm_ilu + Compute the LU decomposition of a matrix in place. + ddm_ilu_split + Compute the LU decomposition of a matrix and separate $L$ and $U$. + sympy.polys.matrices.domainmatrix.DomainMatrix.lu_solve + Higher level interface to this function. + """ + m = len(U) + if not m: + return + n = len(U[0]) + + m2 = len(b) + if not m2: + raise DMShapeError("Shape mismtch") + o = len(b[0]) + + if m != m2: + raise DMShapeError("Shape mismtch") + if m < n: + raise NotImplementedError("Underdetermined") + + if swaps: + b = [row[:] for row in b] + for i1, i2 in swaps: + b[i1], b[i2] = b[i2], b[i1] + + # solve Ly = b + y = [[None] * o for _ in range(m)] + for k in range(o): + for i in range(m): + rhs = b[i][k] + for j in range(i): + rhs -= L[i][j] * y[j][k] + y[i][k] = rhs + + if m > n: + for i in range(n, m): + for j in range(o): + if y[i][j]: + raise DMNonInvertibleMatrixError + + # Solve Ux = y + for k in range(o): + for i in reversed(range(n)): + if not U[i][i]: + raise DMNonInvertibleMatrixError + rhs = y[i][k] + for j in range(i+1, n): + rhs -= U[i][j] * x[j][k] + x[i][k] = rhs / U[i][i] + + +def ddm_berk(M, K): + """ + Berkowitz algorithm for computing the characteristic polynomial. + + Explanation + =========== + + The Berkowitz algorithm is a division-free algorithm for computing the + characteristic polynomial of a matrix over any commutative ring using only + arithmetic in the coefficient ring. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.polys.matrices.dense import ddm_berk + >>> from sympy.polys.domains import ZZ + >>> M = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] + >>> ddm_berk(M, ZZ) + [[1], [-5], [-2]] + >>> Matrix(M).charpoly() + PurePoly(lambda**2 - 5*lambda - 2, lambda, domain='ZZ') + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.charpoly + The high-level interface to this function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Samuelson%E2%80%93Berkowitz_algorithm + """ + m = len(M) + if not m: + return [[K.one]] + n = len(M[0]) + + if m != n: + raise DMShapeError("Not square") + + if n == 1: + return [[K.one], [-M[0][0]]] + + a = M[0][0] + R = [M[0][1:]] + C = [[row[0]] for row in M[1:]] + A = [row[1:] for row in M[1:]] + + q = ddm_berk(A, K) + + T = [[K.zero] * n for _ in range(n+1)] + for i in range(n): + T[i][i] = K.one + T[i+1][i] = -a + for i in range(2, n+1): + if i == 2: + AnC = C + else: + C = AnC + AnC = [[K.zero] for row in C] + ddm_imatmul(AnC, A, C) + RAnC = [[K.zero]] + ddm_imatmul(RAnC, R, AnC) + for j in range(0, n+1-i): + T[i+j][j] = -RAnC[0][0] + + qout = [[K.zero] for _ in range(n+1)] + ddm_imatmul(qout, T, q) + return qout diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/dfm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/dfm.py new file mode 100644 index 0000000000000000000000000000000000000000..22938b7004654121f74b020bd6649bee84909e1e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/dfm.py @@ -0,0 +1,35 @@ +""" +sympy.polys.matrices.dfm + +Provides the :class:`DFM` class if ``GROUND_TYPES=flint'``. Otherwise, ``DFM`` +is a placeholder class that raises NotImplementedError when instantiated. +""" + +from sympy.external.gmpy import GROUND_TYPES + +if GROUND_TYPES == "flint": # pragma: no cover + # When python-flint is installed we will try to use it for dense matrices + # if the domain is supported by python-flint. + from ._dfm import DFM + +else: # pragma: no cover + # Other code should be able to import this and it should just present as a + # version of DFM that does not support any domains. + class DFM_dummy: + """ + Placeholder class for DFM when python-flint is not installed. + """ + def __init__(*args, **kwargs): + raise NotImplementedError("DFM requires GROUND_TYPES=flint.") + + @classmethod + def _supports_domain(cls, domain): + return False + + @classmethod + def _get_flint_func(cls, domain): + raise NotImplementedError("DFM requires GROUND_TYPES=flint.") + + # mypy really struggles with this kind of conditional type assignment. + # Maybe there is a better way to annotate this rather than type: ignore. + DFM = DFM_dummy # type: ignore diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/domainmatrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/domainmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..627835eca93b5e70f9aa121f097c9828a709ca78 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/domainmatrix.py @@ -0,0 +1,3983 @@ +""" + +Module for the DomainMatrix class. + +A DomainMatrix represents a matrix with elements that are in a particular +Domain. Each DomainMatrix internally wraps a DDM which is used for the +lower-level operations. The idea is that the DomainMatrix class provides the +convenience routines for converting between Expr and the poly domains as well +as unifying matrices with different domains. + +""" +from __future__ import annotations +from collections import Counter +from functools import reduce + +from sympy.external.gmpy import GROUND_TYPES +from sympy.utilities.decorator import doctest_depends_on + +from sympy.core.sympify import _sympify + +from ..domains import Domain + +from ..constructor import construct_domain + +from .exceptions import ( + DMFormatError, + DMBadInputError, + DMShapeError, + DMDomainError, + DMNotAField, + DMNonSquareMatrixError, + DMNonInvertibleMatrixError +) + +from .domainscalar import DomainScalar + +from sympy.polys.domains import ZZ, EXRAW, QQ + +from sympy.polys.densearith import dup_mul +from sympy.polys.densebasic import dup_convert +from sympy.polys.densetools import ( + dup_mul_ground, + dup_quo_ground, + dup_content, + dup_clear_denoms, + dup_primitive, + dup_transform, +) +from sympy.polys.factortools import dup_factor_list +from sympy.polys.polyutils import _sort_factors + +from .ddm import DDM + +from .sdm import SDM + +from .dfm import DFM + +from .rref import _dm_rref, _dm_rref_den + + +if GROUND_TYPES != 'flint': + __doctest_skip__ = ['DomainMatrix.to_dfm', 'DomainMatrix.to_dfm_or_ddm'] +else: + __doctest_skip__ = ['DomainMatrix.from_list'] + + +def DM(rows, domain): + """Convenient alias for DomainMatrix.from_list + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> DM([[1, 2], [3, 4]], ZZ) + DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) + + See Also + ======== + + DomainMatrix.from_list + """ + return DomainMatrix.from_list(rows, domain) + + +class DomainMatrix: + r""" + Associate Matrix with :py:class:`~.Domain` + + Explanation + =========== + + DomainMatrix uses :py:class:`~.Domain` for its internal representation + which makes it faster than the SymPy Matrix class (currently) for many + common operations, but this advantage makes it not entirely compatible + with Matrix. DomainMatrix are analogous to numpy arrays with "dtype". + In the DomainMatrix, each element has a domain such as :ref:`ZZ` + or :ref:`QQ(a)`. + + + Examples + ======== + + Creating a DomainMatrix from the existing Matrix class: + + >>> from sympy import Matrix + >>> from sympy.polys.matrices import DomainMatrix + >>> Matrix1 = Matrix([ + ... [1, 2], + ... [3, 4]]) + >>> A = DomainMatrix.from_Matrix(Matrix1) + >>> A + DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) + + Directly forming a DomainMatrix: + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> A + DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) + + See Also + ======== + + DDM + SDM + Domain + Poly + + """ + rep: SDM | DDM | DFM + shape: tuple[int, int] + domain: Domain + + def __new__(cls, rows, shape, domain, *, fmt=None): + """ + Creates a :py:class:`~.DomainMatrix`. + + Parameters + ========== + + rows : Represents elements of DomainMatrix as list of lists + shape : Represents dimension of DomainMatrix + domain : Represents :py:class:`~.Domain` of DomainMatrix + + Raises + ====== + + TypeError + If any of rows, shape and domain are not provided + + """ + if isinstance(rows, (DDM, SDM, DFM)): + raise TypeError("Use from_rep to initialise from SDM/DDM") + elif isinstance(rows, list): + rep = DDM(rows, shape, domain) + elif isinstance(rows, dict): + rep = SDM(rows, shape, domain) + else: + msg = "Input should be list-of-lists or dict-of-dicts" + raise TypeError(msg) + + if fmt is not None: + if fmt == 'sparse': + rep = rep.to_sdm() + elif fmt == 'dense': + rep = rep.to_ddm() + else: + raise ValueError("fmt should be 'sparse' or 'dense'") + + # Use python-flint for dense matrices if possible + if rep.fmt == 'dense' and DFM._supports_domain(domain): + rep = rep.to_dfm() + + return cls.from_rep(rep) + + def __reduce__(self): + rep = self.rep + if rep.fmt == 'dense': + arg = self.to_list() + elif rep.fmt == 'sparse': + arg = dict(rep) + else: + raise RuntimeError # pragma: no cover + args = (arg, rep.shape, rep.domain) + return (self.__class__, args) + + def __getitem__(self, key): + i, j = key + m, n = self.shape + if not (isinstance(i, slice) or isinstance(j, slice)): + return DomainScalar(self.rep.getitem(i, j), self.domain) + + if not isinstance(i, slice): + if not -m <= i < m: + raise IndexError("Row index out of range") + i = i % m + i = slice(i, i+1) + if not isinstance(j, slice): + if not -n <= j < n: + raise IndexError("Column index out of range") + j = j % n + j = slice(j, j+1) + + return self.from_rep(self.rep.extract_slice(i, j)) + + def getitem_sympy(self, i, j): + return self.domain.to_sympy(self.rep.getitem(i, j)) + + def extract(self, rowslist, colslist): + return self.from_rep(self.rep.extract(rowslist, colslist)) + + def __setitem__(self, key, value): + i, j = key + if not self.domain.of_type(value): + raise TypeError + if isinstance(i, int) and isinstance(j, int): + self.rep.setitem(i, j, value) + else: + raise NotImplementedError + + @classmethod + def from_rep(cls, rep): + """Create a new DomainMatrix efficiently from DDM/SDM. + + Examples + ======== + + Create a :py:class:`~.DomainMatrix` with an dense internal + representation as :py:class:`~.DDM`: + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy.polys.matrices.ddm import DDM + >>> drep = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> dM = DomainMatrix.from_rep(drep) + >>> dM + DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) + + Create a :py:class:`~.DomainMatrix` with a sparse internal + representation as :py:class:`~.SDM`: + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import ZZ + >>> drep = SDM({0:{1:ZZ(1)},1:{0:ZZ(2)}}, (2, 2), ZZ) + >>> dM = DomainMatrix.from_rep(drep) + >>> dM + DomainMatrix({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ) + + Parameters + ========== + + rep: SDM or DDM + The internal sparse or dense representation of the matrix. + + Returns + ======= + + DomainMatrix + A :py:class:`~.DomainMatrix` wrapping *rep*. + + Notes + ===== + + This takes ownership of rep as its internal representation. If rep is + being mutated elsewhere then a copy should be provided to + ``from_rep``. Only minimal verification or checking is done on *rep* + as this is supposed to be an efficient internal routine. + + """ + if not (isinstance(rep, (DDM, SDM)) or (DFM is not None and isinstance(rep, DFM))): + raise TypeError("rep should be of type DDM or SDM") + self = super().__new__(cls) + self.rep = rep + self.shape = rep.shape + self.domain = rep.domain + return self + + @classmethod + @doctest_depends_on(ground_types=['python', 'gmpy']) + def from_list(cls, rows, domain): + r""" + Convert a list of lists into a DomainMatrix + + Parameters + ========== + + rows: list of lists + Each element of the inner lists should be either the single arg, + or tuple of args, that would be passed to the domain constructor + in order to form an element of the domain. See examples. + + Returns + ======= + + DomainMatrix containing elements defined in rows + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import FF, QQ, ZZ + >>> A = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], ZZ) + >>> A + DomainMatrix([[1, 0, 1], [0, 0, 1]], (2, 3), ZZ) + >>> B = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], FF(7)) + >>> B + DomainMatrix([[1 mod 7, 0 mod 7, 1 mod 7], [0 mod 7, 0 mod 7, 1 mod 7]], (2, 3), GF(7)) + >>> C = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ) + >>> C + DomainMatrix([[1/2, 3], [1/4, 5]], (2, 2), QQ) + + See Also + ======== + + from_list_sympy + + """ + nrows = len(rows) + ncols = 0 if not nrows else len(rows[0]) + conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e) + domain_rows = [[conv(e) for e in row] for row in rows] + return DomainMatrix(domain_rows, (nrows, ncols), domain) + + @classmethod + def from_list_sympy(cls, nrows, ncols, rows, **kwargs): + r""" + Convert a list of lists of Expr into a DomainMatrix using construct_domain + + Parameters + ========== + + nrows: number of rows + ncols: number of columns + rows: list of lists + + Returns + ======= + + DomainMatrix containing elements of rows + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy.abc import x, y, z + >>> A = DomainMatrix.from_list_sympy(1, 3, [[x, y, z]]) + >>> A + DomainMatrix([[x, y, z]], (1, 3), ZZ[x,y,z]) + + See Also + ======== + + sympy.polys.constructor.construct_domain, from_dict_sympy + + """ + assert len(rows) == nrows + assert all(len(row) == ncols for row in rows) + + items_sympy = [_sympify(item) for row in rows for item in row] + + domain, items_domain = cls.get_domain(items_sympy, **kwargs) + + domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)] + + return DomainMatrix(domain_rows, (nrows, ncols), domain) + + @classmethod + def from_dict_sympy(cls, nrows, ncols, elemsdict, **kwargs): + """ + + Parameters + ========== + + nrows: number of rows + ncols: number of cols + elemsdict: dict of dicts containing non-zero elements of the DomainMatrix + + Returns + ======= + + DomainMatrix containing elements of elemsdict + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy.abc import x,y,z + >>> elemsdict = {0: {0:x}, 1:{1: y}, 2: {2: z}} + >>> A = DomainMatrix.from_dict_sympy(3, 3, elemsdict) + >>> A + DomainMatrix({0: {0: x}, 1: {1: y}, 2: {2: z}}, (3, 3), ZZ[x,y,z]) + + See Also + ======== + + from_list_sympy + + """ + if not all(0 <= r < nrows for r in elemsdict): + raise DMBadInputError("Row out of range") + if not all(0 <= c < ncols for row in elemsdict.values() for c in row): + raise DMBadInputError("Column out of range") + + items_sympy = [_sympify(item) for row in elemsdict.values() for item in row.values()] + domain, items_domain = cls.get_domain(items_sympy, **kwargs) + + idx = 0 + items_dict = {} + for i, row in elemsdict.items(): + items_dict[i] = {} + for j in row: + items_dict[i][j] = items_domain[idx] + idx += 1 + + return DomainMatrix(items_dict, (nrows, ncols), domain) + + @classmethod + def from_Matrix(cls, M, fmt='sparse',**kwargs): + r""" + Convert Matrix to DomainMatrix + + Parameters + ========== + + M: Matrix + + Returns + ======= + + Returns DomainMatrix with identical elements as M + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.polys.matrices import DomainMatrix + >>> M = Matrix([ + ... [1.0, 3.4], + ... [2.4, 1]]) + >>> A = DomainMatrix.from_Matrix(M) + >>> A + DomainMatrix({0: {0: 1.0, 1: 3.4}, 1: {0: 2.4, 1: 1.0}}, (2, 2), RR) + + We can keep internal representation as ddm using fmt='dense' + >>> from sympy import Matrix, QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense') + >>> A.rep + [[1/2, 3/4], [0, 0]] + + See Also + ======== + + Matrix + + """ + if fmt == 'dense': + return cls.from_list_sympy(*M.shape, M.tolist(), **kwargs) + + return cls.from_dict_sympy(*M.shape, M.todod(), **kwargs) + + @classmethod + def get_domain(cls, items_sympy, **kwargs): + K, items_K = construct_domain(items_sympy, **kwargs) + return K, items_K + + def choose_domain(self, **opts): + """Convert to a domain found by :func:`~.construct_domain`. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> M = DM([[1, 2], [3, 4]], ZZ) + >>> M + DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) + >>> M.choose_domain(field=True) + DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ) + + >>> from sympy.abc import x + >>> M = DM([[1, x], [x**2, x**3]], ZZ[x]) + >>> M.choose_domain(field=True).domain + ZZ(x) + + Keyword arguments are passed to :func:`~.construct_domain`. + + See Also + ======== + + construct_domain + convert_to + """ + elements, data = self.to_sympy().to_flat_nz() + dom, elements_dom = construct_domain(elements, **opts) + return self.from_flat_nz(elements_dom, data, dom) + + def copy(self): + return self.from_rep(self.rep.copy()) + + def convert_to(self, K): + r""" + Change the domain of DomainMatrix to desired domain or field + + Parameters + ========== + + K : Represents the desired domain or field. + Alternatively, ``None`` may be passed, in which case this method + just returns a copy of this DomainMatrix. + + Returns + ======= + + DomainMatrix + DomainMatrix with the desired domain or field + + Examples + ======== + + >>> from sympy import ZZ, ZZ_I + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + >>> A.convert_to(ZZ_I) + DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ_I) + + """ + if K == self.domain: + return self.copy() + + rep = self.rep + + # The DFM, DDM and SDM types do not do any implicit conversions so we + # manage switching between DDM and DFM here. + if rep.is_DFM and not DFM._supports_domain(K): + rep_K = rep.to_ddm().convert_to(K) + elif rep.is_DDM and DFM._supports_domain(K): + rep_K = rep.convert_to(K).to_dfm() + else: + rep_K = rep.convert_to(K) + + return self.from_rep(rep_K) + + def to_sympy(self): + return self.convert_to(EXRAW) + + def to_field(self): + r""" + Returns a DomainMatrix with the appropriate field + + Returns + ======= + + DomainMatrix + DomainMatrix with the appropriate field + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + >>> A.to_field() + DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ) + + """ + K = self.domain.get_field() + return self.convert_to(K) + + def to_sparse(self): + """ + Return a sparse DomainMatrix representation of *self*. + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ) + >>> A.rep + [[1, 0], [0, 2]] + >>> B = A.to_sparse() + >>> B.rep + {0: {0: 1}, 1: {1: 2}} + """ + if self.rep.fmt == 'sparse': + return self + + return self.from_rep(self.rep.to_sdm()) + + def to_dense(self): + """ + Return a dense DomainMatrix representation of *self*. + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ) + >>> A.rep + {0: {0: 1}, 1: {1: 2}} + >>> B = A.to_dense() + >>> B.rep + [[1, 0], [0, 2]] + + """ + rep = self.rep + + if rep.fmt == 'dense': + return self + + return self.from_rep(rep.to_dfm_or_ddm()) + + def to_ddm(self): + """ + Return a :class:`~.DDM` representation of *self*. + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ) + >>> ddm = A.to_ddm() + >>> ddm + [[1, 0], [0, 2]] + >>> type(ddm) + + + See Also + ======== + + to_sdm + to_dense + sympy.polys.matrices.ddm.DDM.to_sdm + """ + return self.rep.to_ddm() + + def to_sdm(self): + """ + Return a :class:`~.SDM` representation of *self*. + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ) + >>> sdm = A.to_sdm() + >>> sdm + {0: {0: 1}, 1: {1: 2}} + >>> type(sdm) + + + See Also + ======== + + to_ddm + to_sparse + sympy.polys.matrices.sdm.SDM.to_ddm + """ + return self.rep.to_sdm() + + @doctest_depends_on(ground_types=['flint']) + def to_dfm(self): + """ + Return a :class:`~.DFM` representation of *self*. + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ) + >>> dfm = A.to_dfm() + >>> dfm + [[1, 0], [0, 2]] + >>> type(dfm) + + + See Also + ======== + + to_ddm + to_dense + DFM + """ + return self.rep.to_dfm() + + @doctest_depends_on(ground_types=['flint']) + def to_dfm_or_ddm(self): + """ + Return a :class:`~.DFM` or :class:`~.DDM` representation of *self*. + + Explanation + =========== + + The :class:`~.DFM` representation can only be used if the ground types + are ``flint`` and the ground domain is supported by ``python-flint``. + This method will return a :class:`~.DFM` representation if possible, + but will return a :class:`~.DDM` representation otherwise. + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ) + >>> dfm = A.to_dfm_or_ddm() + >>> dfm + [[1, 0], [0, 2]] + >>> type(dfm) # Depends on the ground domain and ground types + + + See Also + ======== + + to_ddm: Always return a :class:`~.DDM` representation. + to_dfm: Returns a :class:`~.DFM` representation or raise an error. + to_dense: Convert internally to a :class:`~.DFM` or :class:`~.DDM` + DFM: The :class:`~.DFM` dense FLINT matrix representation. + DDM: The Python :class:`~.DDM` dense domain matrix representation. + """ + return self.rep.to_dfm_or_ddm() + + @classmethod + def _unify_domain(cls, *matrices): + """Convert matrices to a common domain""" + domains = {matrix.domain for matrix in matrices} + if len(domains) == 1: + return matrices + domain = reduce(lambda x, y: x.unify(y), domains) + return tuple(matrix.convert_to(domain) for matrix in matrices) + + @classmethod + def _unify_fmt(cls, *matrices, fmt=None): + """Convert matrices to the same format. + + If all matrices have the same format, then return unmodified. + Otherwise convert both to the preferred format given as *fmt* which + should be 'dense' or 'sparse'. + """ + formats = {matrix.rep.fmt for matrix in matrices} + if len(formats) == 1: + return matrices + if fmt == 'sparse': + return tuple(matrix.to_sparse() for matrix in matrices) + elif fmt == 'dense': + return tuple(matrix.to_dense() for matrix in matrices) + else: + raise ValueError("fmt should be 'sparse' or 'dense'") + + def unify(self, *others, fmt=None): + """ + Unifies the domains and the format of self and other + matrices. + + Parameters + ========== + + others : DomainMatrix + + fmt: string 'dense', 'sparse' or `None` (default) + The preferred format to convert to if self and other are not + already in the same format. If `None` or not specified then no + conversion if performed. + + Returns + ======= + + Tuple[DomainMatrix] + Matrices with unified domain and format + + Examples + ======== + + Unify the domain of DomainMatrix that have different domains: + + >>> from sympy import ZZ, QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + >>> B = DomainMatrix([[QQ(1, 2), QQ(2)]], (1, 2), QQ) + >>> Aq, Bq = A.unify(B) + >>> Aq + DomainMatrix([[1, 2]], (1, 2), QQ) + >>> Bq + DomainMatrix([[1/2, 2]], (1, 2), QQ) + + Unify the format (dense or sparse): + + >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + >>> B = DomainMatrix({0:{0: ZZ(1)}}, (2, 2), ZZ) + >>> B.rep + {0: {0: 1}} + + >>> A2, B2 = A.unify(B, fmt='dense') + >>> B2.rep + [[1, 0], [0, 0]] + + See Also + ======== + + convert_to, to_dense, to_sparse + + """ + matrices = (self,) + others + matrices = DomainMatrix._unify_domain(*matrices) + if fmt is not None: + matrices = DomainMatrix._unify_fmt(*matrices, fmt=fmt) + return matrices + + def to_Matrix(self): + r""" + Convert DomainMatrix to Matrix + + Returns + ======= + + Matrix + MutableDenseMatrix for the DomainMatrix + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + >>> A.to_Matrix() + Matrix([ + [1, 2], + [3, 4]]) + + See Also + ======== + + from_Matrix + + """ + from sympy.matrices.dense import MutableDenseMatrix + + # XXX: If the internal representation of RepMatrix changes then this + # might need to be changed also. + if self.domain in (ZZ, QQ, EXRAW): + if self.rep.fmt == "sparse": + rep = self.copy() + else: + rep = self.to_sparse() + else: + rep = self.convert_to(EXRAW).to_sparse() + + return MutableDenseMatrix._fromrep(rep) + + def to_list(self): + """ + Convert :class:`DomainMatrix` to list of lists. + + See Also + ======== + + from_list + to_list_flat + to_flat_nz + to_dok + """ + return self.rep.to_list() + + def to_list_flat(self): + """ + Convert :class:`DomainMatrix` to flat list. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> A.to_list_flat() + [1, 2, 3, 4] + + See Also + ======== + + from_list_flat + to_list + to_flat_nz + to_dok + """ + return self.rep.to_list_flat() + + @classmethod + def from_list_flat(cls, elements, shape, domain): + """ + Create :class:`DomainMatrix` from flat list. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> element_list = [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] + >>> A = DomainMatrix.from_list_flat(element_list, (2, 2), ZZ) + >>> A + DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) + >>> A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain) + True + + See Also + ======== + + to_list_flat + """ + ddm = DDM.from_list_flat(elements, shape, domain) + return cls.from_rep(ddm.to_dfm_or_ddm()) + + def to_flat_nz(self): + """ + Convert :class:`DomainMatrix` to list of nonzero elements and data. + + Explanation + =========== + + Returns a tuple ``(elements, data)`` where ``elements`` is a list of + elements of the matrix with zeros possibly excluded. The matrix can be + reconstructed by passing these to :meth:`from_flat_nz`. The idea is to + be able to modify a flat list of the elements and then create a new + matrix of the same shape with the modified elements in the same + positions. + + The format of ``data`` differs depending on whether the underlying + representation is dense or sparse but either way it represents the + positions of the elements in the list in a way that + :meth:`from_flat_nz` can use to reconstruct the matrix. The + :meth:`from_flat_nz` method should be called on the same + :class:`DomainMatrix` that was used to call :meth:`to_flat_nz`. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> elements, data = A.to_flat_nz() + >>> elements + [1, 2, 3, 4] + >>> A == A.from_flat_nz(elements, data, A.domain) + True + + Create a matrix with the elements doubled: + + >>> elements_doubled = [2*x for x in elements] + >>> A2 = A.from_flat_nz(elements_doubled, data, A.domain) + >>> A2 == 2*A + True + + See Also + ======== + + from_flat_nz + """ + return self.rep.to_flat_nz() + + def from_flat_nz(self, elements, data, domain): + """ + Reconstruct :class:`DomainMatrix` after calling :meth:`to_flat_nz`. + + See :meth:`to_flat_nz` for explanation. + + See Also + ======== + + to_flat_nz + """ + rep = self.rep.from_flat_nz(elements, data, domain) + return self.from_rep(rep) + + def to_dod(self): + """ + Convert :class:`DomainMatrix` to dictionary of dictionaries (dod) format. + + Explanation + =========== + + Returns a dictionary of dictionaries representing the matrix. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> A = DM([[ZZ(1), ZZ(2), ZZ(0)], [ZZ(3), ZZ(0), ZZ(4)]], ZZ) + >>> A.to_dod() + {0: {0: 1, 1: 2}, 1: {0: 3, 2: 4}} + >>> A.to_sparse() == A.from_dod(A.to_dod(), A.shape, A.domain) + True + >>> A == A.from_dod_like(A.to_dod()) + True + + See Also + ======== + + from_dod + from_dod_like + to_dok + to_list + to_list_flat + to_flat_nz + sympy.matrices.matrixbase.MatrixBase.todod + """ + return self.rep.to_dod() + + @classmethod + def from_dod(cls, dod, shape, domain): + """ + Create sparse :class:`DomainMatrix` from dict of dict (dod) format. + + See :meth:`to_dod` for explanation. + + See Also + ======== + + to_dod + from_dod_like + """ + return cls.from_rep(SDM.from_dod(dod, shape, domain)) + + def from_dod_like(self, dod, domain=None): + """ + Create :class:`DomainMatrix` like ``self`` from dict of dict (dod) format. + + See :meth:`to_dod` for explanation. + + See Also + ======== + + to_dod + from_dod + """ + if domain is None: + domain = self.domain + return self.from_rep(self.rep.from_dod(dod, self.shape, domain)) + + def to_dok(self): + """ + Convert :class:`DomainMatrix` to dictionary of keys (dok) format. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(0)], + ... [ZZ(0), ZZ(4)]], (2, 2), ZZ) + >>> A.to_dok() + {(0, 0): 1, (1, 1): 4} + + The matrix can be reconstructed by calling :meth:`from_dok` although + the reconstructed matrix will always be in sparse format: + + >>> A.to_sparse() == A.from_dok(A.to_dok(), A.shape, A.domain) + True + + See Also + ======== + + from_dok + to_list + to_list_flat + to_flat_nz + """ + return self.rep.to_dok() + + @classmethod + def from_dok(cls, dok, shape, domain): + """ + Create :class:`DomainMatrix` from dictionary of keys (dok) format. + + See :meth:`to_dok` for explanation. + + See Also + ======== + + to_dok + """ + return cls.from_rep(SDM.from_dok(dok, shape, domain)) + + def iter_values(self): + """ + Iterate over nonzero elements of the matrix. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> list(A.iter_values()) + [1, 3, 4] + + See Also + ======== + + iter_items + to_list_flat + sympy.matrices.matrixbase.MatrixBase.iter_values + """ + return self.rep.iter_values() + + def iter_items(self): + """ + Iterate over indices and values of nonzero elements of the matrix. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> list(A.iter_items()) + [((0, 0), 1), ((1, 0), 3), ((1, 1), 4)] + + See Also + ======== + + iter_values + to_dok + sympy.matrices.matrixbase.MatrixBase.iter_items + """ + return self.rep.iter_items() + + def nnz(self): + """ + Number of nonzero elements in the matrix. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> A = DM([[1, 0], [0, 4]], ZZ) + >>> A.nnz() + 2 + """ + return self.rep.nnz() + + def __repr__(self): + return 'DomainMatrix(%s, %r, %r)' % (str(self.rep), self.shape, self.domain) + + def transpose(self): + """Matrix transpose of ``self``""" + return self.from_rep(self.rep.transpose()) + + def flat(self): + rows, cols = self.shape + return [self[i,j].element for i in range(rows) for j in range(cols)] + + @property + def is_zero_matrix(self): + return self.rep.is_zero_matrix() + + @property + def is_upper(self): + """ + Says whether this matrix is upper-triangular. True can be returned + even if the matrix is not square. + """ + return self.rep.is_upper() + + @property + def is_lower(self): + """ + Says whether this matrix is lower-triangular. True can be returned + even if the matrix is not square. + """ + return self.rep.is_lower() + + @property + def is_diagonal(self): + """ + True if the matrix is diagonal. + + Can return true for non-square matrices. A matrix is diagonal if + ``M[i,j] == 0`` whenever ``i != j``. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> M = DM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], ZZ) + >>> M.is_diagonal + True + + See Also + ======== + + is_upper + is_lower + is_square + diagonal + """ + return self.rep.is_diagonal() + + def diagonal(self): + """ + Get the diagonal entries of the matrix as a list. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> M = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ) + >>> M.diagonal() + [1, 4] + + See Also + ======== + + is_diagonal + diag + """ + return self.rep.diagonal() + + @property + def is_square(self): + """ + True if the matrix is square. + """ + return self.shape[0] == self.shape[1] + + def rank(self): + rref, pivots = self.rref() + return len(pivots) + + def hstack(A, *B): + r"""Horizontally stack the given matrices. + + Parameters + ========== + + B: DomainMatrix + Matrices to stack horizontally. + + Returns + ======= + + DomainMatrix + DomainMatrix by stacking horizontally. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + + >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + >>> A.hstack(B) + DomainMatrix([[1, 2, 5, 6], [3, 4, 7, 8]], (2, 4), ZZ) + + >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + >>> A.hstack(B, C) + DomainMatrix([[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]], (2, 6), ZZ) + + See Also + ======== + + unify + """ + A, *B = A.unify(*B, fmt=A.rep.fmt) + return DomainMatrix.from_rep(A.rep.hstack(*(Bk.rep for Bk in B))) + + def vstack(A, *B): + r"""Vertically stack the given matrices. + + Parameters + ========== + + B: DomainMatrix + Matrices to stack vertically. + + Returns + ======= + + DomainMatrix + DomainMatrix by stacking vertically. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + + >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + >>> A.vstack(B) + DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8]], (4, 2), ZZ) + + >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + >>> A.vstack(B, C) + DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]], (6, 2), ZZ) + + See Also + ======== + + unify + """ + A, *B = A.unify(*B, fmt='dense') + return DomainMatrix.from_rep(A.rep.vstack(*(Bk.rep for Bk in B))) + + def applyfunc(self, func, domain=None): + if domain is None: + domain = self.domain + return self.from_rep(self.rep.applyfunc(func, domain)) + + def __add__(A, B): + if not isinstance(B, DomainMatrix): + return NotImplemented + A, B = A.unify(B, fmt='dense') + return A.add(B) + + def __sub__(A, B): + if not isinstance(B, DomainMatrix): + return NotImplemented + A, B = A.unify(B, fmt='dense') + return A.sub(B) + + def __neg__(A): + return A.neg() + + def __mul__(A, B): + """A * B""" + if isinstance(B, DomainMatrix): + A, B = A.unify(B, fmt='dense') + return A.matmul(B) + elif B in A.domain: + return A.scalarmul(B) + elif isinstance(B, DomainScalar): + A, B = A.unify(B) + return A.scalarmul(B.element) + else: + return NotImplemented + + def __rmul__(A, B): + if B in A.domain: + return A.rscalarmul(B) + elif isinstance(B, DomainScalar): + A, B = A.unify(B) + return A.rscalarmul(B.element) + else: + return NotImplemented + + def __pow__(A, n): + """A ** n""" + if not isinstance(n, int): + return NotImplemented + return A.pow(n) + + def _check(a, op, b, ashape, bshape): + if a.domain != b.domain: + msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain) + raise DMDomainError(msg) + if ashape != bshape: + msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape) + raise DMShapeError(msg) + if a.rep.fmt != b.rep.fmt: + msg = "Format mismatch: %s %s %s" % (a.rep.fmt, op, b.rep.fmt) + raise DMFormatError(msg) + if type(a.rep) != type(b.rep): + msg = "Type mismatch: %s %s %s" % (type(a.rep), op, type(b.rep)) + raise DMFormatError(msg) + + def add(A, B): + r""" + Adds two DomainMatrix matrices of the same Domain + + Parameters + ========== + + A, B: DomainMatrix + matrices to add + + Returns + ======= + + DomainMatrix + DomainMatrix after Addition + + Raises + ====== + + DMShapeError + If the dimensions of the two DomainMatrix are not equal + + ValueError + If the domain of the two DomainMatrix are not same + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DomainMatrix([ + ... [ZZ(4), ZZ(3)], + ... [ZZ(2), ZZ(1)]], (2, 2), ZZ) + + >>> A.add(B) + DomainMatrix([[5, 5], [5, 5]], (2, 2), ZZ) + + See Also + ======== + + sub, matmul + + """ + A._check('+', B, A.shape, B.shape) + return A.from_rep(A.rep.add(B.rep)) + + + def sub(A, B): + r""" + Subtracts two DomainMatrix matrices of the same Domain + + Parameters + ========== + + A, B: DomainMatrix + matrices to subtract + + Returns + ======= + + DomainMatrix + DomainMatrix after Subtraction + + Raises + ====== + + DMShapeError + If the dimensions of the two DomainMatrix are not equal + + ValueError + If the domain of the two DomainMatrix are not same + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DomainMatrix([ + ... [ZZ(4), ZZ(3)], + ... [ZZ(2), ZZ(1)]], (2, 2), ZZ) + + >>> A.sub(B) + DomainMatrix([[-3, -1], [1, 3]], (2, 2), ZZ) + + See Also + ======== + + add, matmul + + """ + A._check('-', B, A.shape, B.shape) + return A.from_rep(A.rep.sub(B.rep)) + + def neg(A): + r""" + Returns the negative of DomainMatrix + + Parameters + ========== + + A : Represents a DomainMatrix + + Returns + ======= + + DomainMatrix + DomainMatrix after Negation + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + >>> A.neg() + DomainMatrix([[-1, -2], [-3, -4]], (2, 2), ZZ) + + """ + return A.from_rep(A.rep.neg()) + + def mul(A, b): + r""" + Performs term by term multiplication for the second DomainMatrix + w.r.t first DomainMatrix. Returns a DomainMatrix whose rows are + list of DomainMatrix matrices created after term by term multiplication. + + Parameters + ========== + + A, B: DomainMatrix + matrices to multiply term-wise + + Returns + ======= + + DomainMatrix + DomainMatrix after term by term multiplication + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> b = ZZ(2) + + >>> A.mul(b) + DomainMatrix([[2, 4], [6, 8]], (2, 2), ZZ) + + See Also + ======== + + matmul + + """ + return A.from_rep(A.rep.mul(b)) + + def rmul(A, b): + return A.from_rep(A.rep.rmul(b)) + + def matmul(A, B): + r""" + Performs matrix multiplication of two DomainMatrix matrices + + Parameters + ========== + + A, B: DomainMatrix + to multiply + + Returns + ======= + + DomainMatrix + DomainMatrix after multiplication + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DomainMatrix([ + ... [ZZ(1), ZZ(1)], + ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) + + >>> A.matmul(B) + DomainMatrix([[1, 3], [3, 7]], (2, 2), ZZ) + + See Also + ======== + + mul, pow, add, sub + + """ + + A._check('*', B, A.shape[1], B.shape[0]) + return A.from_rep(A.rep.matmul(B.rep)) + + def _scalarmul(A, lamda, reverse): + if lamda == A.domain.zero: + return DomainMatrix.zeros(A.shape, A.domain) + elif lamda == A.domain.one: + return A.copy() + elif reverse: + return A.rmul(lamda) + else: + return A.mul(lamda) + + def scalarmul(A, lamda): + return A._scalarmul(lamda, reverse=False) + + def rscalarmul(A, lamda): + return A._scalarmul(lamda, reverse=True) + + def mul_elementwise(A, B): + assert A.domain == B.domain + return A.from_rep(A.rep.mul_elementwise(B.rep)) + + def __truediv__(A, lamda): + """ Method for Scalar Division""" + if isinstance(lamda, int) or ZZ.of_type(lamda): + lamda = DomainScalar(ZZ(lamda), ZZ) + elif A.domain.is_Field and lamda in A.domain: + K = A.domain + lamda = DomainScalar(K.convert(lamda), K) + + if not isinstance(lamda, DomainScalar): + return NotImplemented + + A, lamda = A.to_field().unify(lamda) + if lamda.element == lamda.domain.zero: + raise ZeroDivisionError + if lamda.element == lamda.domain.one: + return A + + return A.mul(1 / lamda.element) + + def pow(A, n): + r""" + Computes A**n + + Parameters + ========== + + A : DomainMatrix + + n : exponent for A + + Returns + ======= + + DomainMatrix + DomainMatrix on computing A**n + + Raises + ====== + + NotImplementedError + if n is negative. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(1)], + ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) + + >>> A.pow(2) + DomainMatrix([[1, 2], [0, 1]], (2, 2), ZZ) + + See Also + ======== + + matmul + + """ + nrows, ncols = A.shape + if nrows != ncols: + raise DMNonSquareMatrixError('Power of a nonsquare matrix') + if n < 0: + raise NotImplementedError('Negative powers') + elif n == 0: + return A.eye(nrows, A.domain) + elif n == 1: + return A + elif n % 2 == 1: + return A * A**(n - 1) + else: + sqrtAn = A ** (n // 2) + return sqrtAn * sqrtAn + + def scc(self): + """Compute the strongly connected components of a DomainMatrix + + Explanation + =========== + + A square matrix can be considered as the adjacency matrix for a + directed graph where the row and column indices are the vertices. In + this graph if there is an edge from vertex ``i`` to vertex ``j`` if + ``M[i, j]`` is nonzero. This routine computes the strongly connected + components of that graph which are subsets of the rows and columns that + are connected by some nonzero element of the matrix. The strongly + connected components are useful because many operations such as the + determinant can be computed by working with the submatrices + corresponding to each component. + + Examples + ======== + + Find the strongly connected components of a matrix: + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> M = DomainMatrix([[ZZ(1), ZZ(0), ZZ(2)], + ... [ZZ(0), ZZ(3), ZZ(0)], + ... [ZZ(4), ZZ(6), ZZ(5)]], (3, 3), ZZ) + >>> M.scc() + [[1], [0, 2]] + + Compute the determinant from the components: + + >>> MM = M.to_Matrix() + >>> MM + Matrix([ + [1, 0, 2], + [0, 3, 0], + [4, 6, 5]]) + >>> MM[[1], [1]] + Matrix([[3]]) + >>> MM[[0, 2], [0, 2]] + Matrix([ + [1, 2], + [4, 5]]) + >>> MM.det() + -9 + >>> MM[[1], [1]].det() * MM[[0, 2], [0, 2]].det() + -9 + + The components are given in reverse topological order and represent a + permutation of the rows and columns that will bring the matrix into + block lower-triangular form: + + >>> MM[[1, 0, 2], [1, 0, 2]] + Matrix([ + [3, 0, 0], + [0, 1, 2], + [6, 4, 5]]) + + Returns + ======= + + List of lists of integers + Each list represents a strongly connected component. + + See also + ======== + + sympy.matrices.matrixbase.MatrixBase.strongly_connected_components + sympy.utilities.iterables.strongly_connected_components + + """ + if not self.is_square: + raise DMNonSquareMatrixError('Matrix must be square for scc') + + return self.rep.scc() + + def clear_denoms(self, convert=False): + """ + Clear denominators, but keep the domain unchanged. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DM + >>> A = DM([[(1,2), (1,3)], [(1,4), (1,5)]], QQ) + >>> den, Anum = A.clear_denoms() + >>> den.to_sympy() + 60 + >>> Anum.to_Matrix() + Matrix([ + [30, 20], + [15, 12]]) + >>> den * A == Anum + True + + The numerator matrix will be in the same domain as the original matrix + unless ``convert`` is set to ``True``: + + >>> A.clear_denoms()[1].domain + QQ + >>> A.clear_denoms(convert=True)[1].domain + ZZ + + The denominator is always in the associated ring: + + >>> A.clear_denoms()[0].domain + ZZ + >>> A.domain.get_ring() + ZZ + + See Also + ======== + + sympy.polys.polytools.Poly.clear_denoms + clear_denoms_rowwise + """ + elems0, data = self.to_flat_nz() + + K0 = self.domain + K1 = K0.get_ring() if K0.has_assoc_Ring else K0 + + den, elems1 = dup_clear_denoms(elems0, K0, K1, convert=convert) + + if convert: + Kden, Knum = K1, K1 + else: + Kden, Knum = K1, K0 + + den = DomainScalar(den, Kden) + num = self.from_flat_nz(elems1, data, Knum) + + return den, num + + def clear_denoms_rowwise(self, convert=False): + """ + Clear denominators from each row of the matrix. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DM + >>> A = DM([[(1,2), (1,3), (1,4)], [(1,5), (1,6), (1,7)]], QQ) + >>> den, Anum = A.clear_denoms_rowwise() + >>> den.to_Matrix() + Matrix([ + [12, 0], + [ 0, 210]]) + >>> Anum.to_Matrix() + Matrix([ + [ 6, 4, 3], + [42, 35, 30]]) + + The denominator matrix is a diagonal matrix with the denominators of + each row on the diagonal. The invariants are: + + >>> den * A == Anum + True + >>> A == den.to_field().inv() * Anum + True + + The numerator matrix will be in the same domain as the original matrix + unless ``convert`` is set to ``True``: + + >>> A.clear_denoms_rowwise()[1].domain + QQ + >>> A.clear_denoms_rowwise(convert=True)[1].domain + ZZ + + The domain of the denominator matrix is the associated ring: + + >>> A.clear_denoms_rowwise()[0].domain + ZZ + + See Also + ======== + + sympy.polys.polytools.Poly.clear_denoms + clear_denoms + """ + dod = self.to_dod() + + K0 = self.domain + K1 = K0.get_ring() if K0.has_assoc_Ring else K0 + + diagonals = [K0.one] * self.shape[0] + dod_num = {} + for i, rowi in dod.items(): + indices, elems = zip(*rowi.items()) + den, elems_num = dup_clear_denoms(elems, K0, K1, convert=convert) + rowi_num = dict(zip(indices, elems_num)) + diagonals[i] = den + dod_num[i] = rowi_num + + if convert: + Kden, Knum = K1, K1 + else: + Kden, Knum = K1, K0 + + den = self.diag(diagonals, Kden) + num = self.from_dod_like(dod_num, Knum) + + return den, num + + def cancel_denom(self, denom): + """ + Cancel factors between a matrix and a denominator. + + Returns a matrix and denominator on lowest terms. + + Requires ``gcd`` in the ground domain. + + Methods like :meth:`solve_den`, :meth:`inv_den` and :meth:`rref_den` + return a matrix and denominator but not necessarily on lowest terms. + Reduction to lowest terms without fractions can be performed with + :meth:`cancel_denom`. + + Examples + ======== + + >>> from sympy.polys.matrices import DM + >>> from sympy import ZZ + >>> M = DM([[2, 2, 0], + ... [0, 2, 2], + ... [0, 0, 2]], ZZ) + >>> Minv, den = M.inv_den() + >>> Minv.to_Matrix() + Matrix([ + [1, -1, 1], + [0, 1, -1], + [0, 0, 1]]) + >>> den + 2 + >>> Minv_reduced, den_reduced = Minv.cancel_denom(den) + >>> Minv_reduced.to_Matrix() + Matrix([ + [1, -1, 1], + [0, 1, -1], + [0, 0, 1]]) + >>> den_reduced + 2 + >>> Minv_reduced.to_field() / den_reduced == Minv.to_field() / den + True + + The denominator is made canonical with respect to units (e.g. a + negative denominator is made positive): + + >>> M = DM([[2, 2, 0]], ZZ) + >>> den = ZZ(-4) + >>> M.cancel_denom(den) + (DomainMatrix([[-1, -1, 0]], (1, 3), ZZ), 2) + + Any factor common to _all_ elements will be cancelled but there can + still be factors in common between _some_ elements of the matrix and + the denominator. To cancel factors between each element and the + denominator, use :meth:`cancel_denom_elementwise` or otherwise convert + to a field and use division: + + >>> M = DM([[4, 6]], ZZ) + >>> den = ZZ(12) + >>> M.cancel_denom(den) + (DomainMatrix([[2, 3]], (1, 2), ZZ), 6) + >>> numers, denoms = M.cancel_denom_elementwise(den) + >>> numers + DomainMatrix([[1, 1]], (1, 2), ZZ) + >>> denoms + DomainMatrix([[3, 2]], (1, 2), ZZ) + >>> M.to_field() / den + DomainMatrix([[1/3, 1/2]], (1, 2), QQ) + + See Also + ======== + + solve_den + inv_den + rref_den + cancel_denom_elementwise + """ + M = self + K = self.domain + + if K.is_zero(denom): + raise ZeroDivisionError('denominator is zero') + elif K.is_one(denom): + return (M.copy(), denom) + + elements, data = M.to_flat_nz() + + # First canonicalize the denominator (e.g. multiply by -1). + if K.is_negative(denom): + u = -K.one + else: + u = K.canonical_unit(denom) + + # Often after e.g. solve_den the denominator will be much more + # complicated than the elements of the numerator. Hopefully it will be + # quicker to find the gcd of the numerator and if there is no content + # then we do not need to look at the denominator at all. + content = dup_content(elements, K) + common = K.gcd(content, denom) + + if not K.is_one(content): + + common = K.gcd(content, denom) + + if not K.is_one(common): + elements = dup_quo_ground(elements, common, K) + denom = K.quo(denom, common) + + if not K.is_one(u): + elements = dup_mul_ground(elements, u, K) + denom = u * denom + elif K.is_one(common): + return (M.copy(), denom) + + M_cancelled = M.from_flat_nz(elements, data, K) + + return M_cancelled, denom + + def cancel_denom_elementwise(self, denom): + """ + Cancel factors between the elements of a matrix and a denominator. + + Returns a matrix of numerators and matrix of denominators. + + Requires ``gcd`` in the ground domain. + + Examples + ======== + + >>> from sympy.polys.matrices import DM + >>> from sympy import ZZ + >>> M = DM([[2, 3], [4, 12]], ZZ) + >>> denom = ZZ(6) + >>> numers, denoms = M.cancel_denom_elementwise(denom) + >>> numers.to_Matrix() + Matrix([ + [1, 1], + [2, 2]]) + >>> denoms.to_Matrix() + Matrix([ + [3, 2], + [3, 1]]) + >>> M_frac = (M.to_field() / denom).to_Matrix() + >>> M_frac + Matrix([ + [1/3, 1/2], + [2/3, 2]]) + >>> denoms_inverted = denoms.to_Matrix().applyfunc(lambda e: 1/e) + >>> numers.to_Matrix().multiply_elementwise(denoms_inverted) == M_frac + True + + Use :meth:`cancel_denom` to cancel factors between the matrix and the + denominator while preserving the form of a matrix with a scalar + denominator. + + See Also + ======== + + cancel_denom + """ + K = self.domain + M = self + + if K.is_zero(denom): + raise ZeroDivisionError('denominator is zero') + elif K.is_one(denom): + M_numers = M.copy() + M_denoms = M.ones(M.shape, M.domain) + return (M_numers, M_denoms) + + elements, data = M.to_flat_nz() + + cofactors = [K.cofactors(numer, denom) for numer in elements] + gcds, numers, denoms = zip(*cofactors) + + M_numers = M.from_flat_nz(list(numers), data, K) + M_denoms = M.from_flat_nz(list(denoms), data, K) + + return (M_numers, M_denoms) + + def content(self): + """ + Return the gcd of the elements of the matrix. + + Requires ``gcd`` in the ground domain. + + Examples + ======== + + >>> from sympy.polys.matrices import DM + >>> from sympy import ZZ + >>> M = DM([[2, 4], [4, 12]], ZZ) + >>> M.content() + 2 + + See Also + ======== + + primitive + cancel_denom + """ + K = self.domain + elements, _ = self.to_flat_nz() + return dup_content(elements, K) + + def primitive(self): + """ + Factor out gcd of the elements of a matrix. + + Requires ``gcd`` in the ground domain. + + Examples + ======== + + >>> from sympy.polys.matrices import DM + >>> from sympy import ZZ + >>> M = DM([[2, 4], [4, 12]], ZZ) + >>> content, M_primitive = M.primitive() + >>> content + 2 + >>> M_primitive + DomainMatrix([[1, 2], [2, 6]], (2, 2), ZZ) + >>> content * M_primitive == M + True + >>> M_primitive.content() == ZZ(1) + True + + See Also + ======== + + content + cancel_denom + """ + K = self.domain + elements, data = self.to_flat_nz() + content, prims = dup_primitive(elements, K) + M_primitive = self.from_flat_nz(prims, data, K) + return content, M_primitive + + def rref(self, *, method='auto'): + r""" + Returns reduced-row echelon form (RREF) and list of pivots. + + If the domain is not a field then it will be converted to a field. See + :meth:`rref_den` for the fraction-free version of this routine that + returns RREF with denominator instead. + + The domain must either be a field or have an associated fraction field + (see :meth:`to_field`). + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [QQ(2), QQ(-1), QQ(0)], + ... [QQ(-1), QQ(2), QQ(-1)], + ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ) + + >>> rref_matrix, rref_pivots = A.rref() + >>> rref_matrix + DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ) + >>> rref_pivots + (0, 1, 2) + + Parameters + ========== + + method : str, optional (default: 'auto') + The method to use to compute the RREF. The default is ``'auto'``, + which will attempt to choose the fastest method. The other options + are: + + - ``A.rref(method='GJ')`` uses Gauss-Jordan elimination with + division. If the domain is not a field then it will be converted + to a field with :meth:`to_field` first and RREF will be computed + by inverting the pivot elements in each row. This is most + efficient for very sparse matrices or for matrices whose elements + have complex denominators. + + - ``A.rref(method='FF')`` uses fraction-free Gauss-Jordan + elimination. Elimination is performed using exact division + (``exquo``) to control the growth of the coefficients. In this + case the current domain is always used for elimination but if + the domain is not a field then it will be converted to a field + at the end and divided by the denominator. This is most efficient + for dense matrices or for matrices with simple denominators. + + - ``A.rref(method='CD')`` clears the denominators before using + fraction-free Gauss-Jordan elimination in the associated ring. + This is most efficient for dense matrices with very simple + denominators. + + - ``A.rref(method='GJ_dense')``, ``A.rref(method='FF_dense')``, and + ``A.rref(method='CD_dense')`` are the same as the above methods + except that the dense implementations of the algorithms are used. + By default ``A.rref(method='auto')`` will usually choose the + sparse implementations for RREF. + + Regardless of which algorithm is used the returned matrix will + always have the same format (sparse or dense) as the input and its + domain will always be the field of fractions of the input domain. + + Returns + ======= + + (DomainMatrix, list) + reduced-row echelon form and list of pivots for the DomainMatrix + + See Also + ======== + + rref_den + RREF with denominator + sympy.polys.matrices.sdm.sdm_irref + Sparse implementation of ``method='GJ'``. + sympy.polys.matrices.sdm.sdm_rref_den + Sparse implementation of ``method='FF'`` and ``method='CD'``. + sympy.polys.matrices.dense.ddm_irref + Dense implementation of ``method='GJ'``. + sympy.polys.matrices.dense.ddm_irref_den + Dense implementation of ``method='FF'`` and ``method='CD'``. + clear_denoms + Clear denominators from a matrix, used by ``method='CD'`` and + by ``method='GJ'`` when the original domain is not a field. + + """ + return _dm_rref(self, method=method) + + def rref_den(self, *, method='auto', keep_domain=True): + r""" + Returns reduced-row echelon form with denominator and list of pivots. + + Requires exact division in the ground domain (``exquo``). + + Examples + ======== + + >>> from sympy import ZZ, QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(2), ZZ(-1), ZZ(0)], + ... [ZZ(-1), ZZ(2), ZZ(-1)], + ... [ZZ(0), ZZ(0), ZZ(2)]], (3, 3), ZZ) + + >>> A_rref, denom, pivots = A.rref_den() + >>> A_rref + DomainMatrix([[6, 0, 0], [0, 6, 0], [0, 0, 6]], (3, 3), ZZ) + >>> denom + 6 + >>> pivots + (0, 1, 2) + >>> A_rref.to_field() / denom + DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ) + >>> A_rref.to_field() / denom == A.convert_to(QQ).rref()[0] + True + + Parameters + ========== + + method : str, optional (default: 'auto') + The method to use to compute the RREF. The default is ``'auto'``, + which will attempt to choose the fastest method. The other options + are: + + - ``A.rref(method='FF')`` uses fraction-free Gauss-Jordan + elimination. Elimination is performed using exact division + (``exquo``) to control the growth of the coefficients. In this + case the current domain is always used for elimination and the + result is always returned as a matrix over the current domain. + This is most efficient for dense matrices or for matrices with + simple denominators. + + - ``A.rref(method='CD')`` clears denominators before using + fraction-free Gauss-Jordan elimination in the associated ring. + The result will be converted back to the original domain unless + ``keep_domain=False`` is passed in which case the result will be + over the ring used for elimination. This is most efficient for + dense matrices with very simple denominators. + + - ``A.rref(method='GJ')`` uses Gauss-Jordan elimination with + division. If the domain is not a field then it will be converted + to a field with :meth:`to_field` first and RREF will be computed + by inverting the pivot elements in each row. The result is + converted back to the original domain by clearing denominators + unless ``keep_domain=False`` is passed in which case the result + will be over the field used for elimination. This is most + efficient for very sparse matrices or for matrices whose elements + have complex denominators. + + - ``A.rref(method='GJ_dense')``, ``A.rref(method='FF_dense')``, and + ``A.rref(method='CD_dense')`` are the same as the above methods + except that the dense implementations of the algorithms are used. + By default ``A.rref(method='auto')`` will usually choose the + sparse implementations for RREF. + + Regardless of which algorithm is used the returned matrix will + always have the same format (sparse or dense) as the input and if + ``keep_domain=True`` its domain will always be the same as the + input. + + keep_domain : bool, optional + If True (the default), the domain of the returned matrix and + denominator are the same as the domain of the input matrix. If + False, the domain of the returned matrix might be changed to an + associated ring or field if the algorithm used a different domain. + This is useful for efficiency if the caller does not need the + result to be in the original domain e.g. it avoids clearing + denominators in the case of ``A.rref(method='GJ')``. + + Returns + ======= + + (DomainMatrix, scalar, list) + Reduced-row echelon form, denominator and list of pivot indices. + + See Also + ======== + + rref + RREF without denominator for field domains. + sympy.polys.matrices.sdm.sdm_irref + Sparse implementation of ``method='GJ'``. + sympy.polys.matrices.sdm.sdm_rref_den + Sparse implementation of ``method='FF'`` and ``method='CD'``. + sympy.polys.matrices.dense.ddm_irref + Dense implementation of ``method='GJ'``. + sympy.polys.matrices.dense.ddm_irref_den + Dense implementation of ``method='FF'`` and ``method='CD'``. + clear_denoms + Clear denominators from a matrix, used by ``method='CD'``. + + """ + return _dm_rref_den(self, method=method, keep_domain=keep_domain) + + def columnspace(self): + r""" + Returns the columnspace for the DomainMatrix + + Returns + ======= + + DomainMatrix + The columns of this matrix form a basis for the columnspace. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [QQ(1), QQ(-1)], + ... [QQ(2), QQ(-2)]], (2, 2), QQ) + >>> A.columnspace() + DomainMatrix([[1], [2]], (2, 1), QQ) + + """ + if not self.domain.is_Field: + raise DMNotAField('Not a field') + rref, pivots = self.rref() + rows, cols = self.shape + return self.extract(range(rows), pivots) + + def rowspace(self): + r""" + Returns the rowspace for the DomainMatrix + + Returns + ======= + + DomainMatrix + The rows of this matrix form a basis for the rowspace. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [QQ(1), QQ(-1)], + ... [QQ(2), QQ(-2)]], (2, 2), QQ) + >>> A.rowspace() + DomainMatrix([[1, -1]], (1, 2), QQ) + + """ + if not self.domain.is_Field: + raise DMNotAField('Not a field') + rref, pivots = self.rref() + rows, cols = self.shape + return self.extract(range(len(pivots)), range(cols)) + + def nullspace(self, divide_last=False): + r""" + Returns the nullspace for the DomainMatrix + + Returns + ======= + + DomainMatrix + The rows of this matrix form a basis for the nullspace. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DM + >>> A = DM([ + ... [QQ(2), QQ(-2)], + ... [QQ(4), QQ(-4)]], QQ) + >>> A.nullspace() + DomainMatrix([[1, 1]], (1, 2), QQ) + + The returned matrix is a basis for the nullspace: + + >>> A_null = A.nullspace().transpose() + >>> A * A_null + DomainMatrix([[0], [0]], (2, 1), QQ) + >>> rows, cols = A.shape + >>> nullity = rows - A.rank() + >>> A_null.shape == (cols, nullity) + True + + Nullspace can also be computed for non-field rings. If the ring is not + a field then division is not used. Setting ``divide_last`` to True will + raise an error in this case: + + >>> from sympy import ZZ + >>> B = DM([[6, -3], + ... [4, -2]], ZZ) + >>> B.nullspace() + DomainMatrix([[3, 6]], (1, 2), ZZ) + >>> B.nullspace(divide_last=True) + Traceback (most recent call last): + ... + DMNotAField: Cannot normalize vectors over a non-field + + Over a ring with ``gcd`` defined the nullspace can potentially be + reduced with :meth:`primitive`: + + >>> B.nullspace().primitive() + (3, DomainMatrix([[1, 2]], (1, 2), ZZ)) + + A matrix over a ring can often be normalized by converting it to a + field but it is often a bad idea to do so: + + >>> from sympy.abc import a, b, c + >>> from sympy import Matrix + >>> M = Matrix([[ a*b, b + c, c], + ... [ a - b, b*c, c**2], + ... [a*b + a - b, b*c + b + c, c**2 + c]]) + >>> M.to_DM().domain + ZZ[a,b,c] + >>> M.to_DM().nullspace().to_Matrix().transpose() + Matrix([ + [ c**3], + [ -a*b*c**2 + a*c - b*c], + [a*b**2*c - a*b - a*c + b**2 + b*c]]) + + The unnormalized form here is nicer than the normalized form that + spreads a large denominator throughout the matrix: + + >>> M.to_DM().to_field().nullspace(divide_last=True).to_Matrix().transpose() + Matrix([ + [ c**3/(a*b**2*c - a*b - a*c + b**2 + b*c)], + [(-a*b*c**2 + a*c - b*c)/(a*b**2*c - a*b - a*c + b**2 + b*c)], + [ 1]]) + + Parameters + ========== + + divide_last : bool, optional + If False (the default), the vectors are not normalized and the RREF + is computed using :meth:`rref_den` and the denominator is + discarded. If True, then each row is divided by its final element; + the domain must be a field in this case. + + See Also + ======== + + nullspace_from_rref + rref + rref_den + rowspace + """ + A = self + K = A.domain + + if divide_last and not K.is_Field: + raise DMNotAField("Cannot normalize vectors over a non-field") + + if divide_last: + A_rref, pivots = A.rref() + else: + A_rref, den, pivots = A.rref_den() + + # Ensure that the sign is canonical before discarding the + # denominator. Then M.nullspace().primitive() is canonical. + u = K.canonical_unit(den) + if u != K.one: + A_rref *= u + + A_null = A_rref.nullspace_from_rref(pivots) + + return A_null + + def nullspace_from_rref(self, pivots=None): + """ + Compute nullspace from rref and pivots. + + The domain of the matrix can be any domain. + + The matrix must be in reduced row echelon form already. Otherwise the + result will be incorrect. Use :meth:`rref` or :meth:`rref_den` first + to get the reduced row echelon form or use :meth:`nullspace` instead. + + See Also + ======== + + nullspace + rref + rref_den + sympy.polys.matrices.sdm.SDM.nullspace_from_rref + sympy.polys.matrices.ddm.DDM.nullspace_from_rref + """ + null_rep, nonpivots = self.rep.nullspace_from_rref(pivots) + return self.from_rep(null_rep) + + def inv(self): + r""" + Finds the inverse of the DomainMatrix if exists + + Returns + ======= + + DomainMatrix + DomainMatrix after inverse + + Raises + ====== + + ValueError + If the domain of DomainMatrix not a Field + + DMNonSquareMatrixError + If the DomainMatrix is not a not Square DomainMatrix + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [QQ(2), QQ(-1), QQ(0)], + ... [QQ(-1), QQ(2), QQ(-1)], + ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ) + >>> A.inv() + DomainMatrix([[2/3, 1/3, 1/6], [1/3, 2/3, 1/3], [0, 0, 1/2]], (3, 3), QQ) + + See Also + ======== + + neg + + """ + if not self.domain.is_Field: + raise DMNotAField('Not a field') + m, n = self.shape + if m != n: + raise DMNonSquareMatrixError + inv = self.rep.inv() + return self.from_rep(inv) + + def det(self): + r""" + Returns the determinant of a square :class:`DomainMatrix`. + + Returns + ======= + + determinant: DomainElement + Determinant of the matrix. + + Raises + ====== + + ValueError + If the domain of DomainMatrix is not a Field + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + >>> A.det() + -2 + + """ + m, n = self.shape + if m != n: + raise DMNonSquareMatrixError + return self.rep.det() + + def adj_det(self): + """ + Adjugate and determinant of a square :class:`DomainMatrix`. + + Returns + ======= + + (adjugate, determinant) : (DomainMatrix, DomainScalar) + The adjugate matrix and determinant of this matrix. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> A = DM([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], ZZ) + >>> adjA, detA = A.adj_det() + >>> adjA + DomainMatrix([[4, -2], [-3, 1]], (2, 2), ZZ) + >>> detA + -2 + + See Also + ======== + + adjugate + Returns only the adjugate matrix. + det + Returns only the determinant. + inv_den + Returns a matrix/denominator pair representing the inverse matrix + but perhaps differing from the adjugate and determinant by a common + factor. + """ + m, n = self.shape + I_m = self.eye((m, m), self.domain) + adjA, detA = self.solve_den_charpoly(I_m, check=False) + if self.rep.fmt == "dense": + adjA = adjA.to_dense() + return adjA, detA + + def adjugate(self): + """ + Adjugate of a square :class:`DomainMatrix`. + + The adjugate matrix is the transpose of the cofactor matrix and is + related to the inverse by:: + + adj(A) = det(A) * A.inv() + + Unlike the inverse matrix the adjugate matrix can be computed and + expressed without division or fractions in the ground domain. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ) + >>> A.adjugate() + DomainMatrix([[4, -2], [-3, 1]], (2, 2), ZZ) + + Returns + ======= + + DomainMatrix + The adjugate matrix of this matrix with the same domain. + + See Also + ======== + + adj_det + """ + adjA, detA = self.adj_det() + return adjA + + def inv_den(self, method=None): + """ + Return the inverse as a :class:`DomainMatrix` with denominator. + + Returns + ======= + + (inv, den) : (:class:`DomainMatrix`, :class:`~.DomainElement`) + The inverse matrix and its denominator. + + This is more or less equivalent to :meth:`adj_det` except that ``inv`` + and ``den`` are not guaranteed to be the adjugate and inverse. The + ratio ``inv/den`` is equivalent to ``adj/det`` but some factors + might be cancelled between ``inv`` and ``den``. In simple cases this + might just be a minus sign so that ``(inv, den) == (-adj, -det)`` but + factors more complicated than ``-1`` can also be cancelled. + Cancellation is not guaranteed to be complete so ``inv`` and ``den`` + may not be on lowest terms. The denominator ``den`` will be zero if and + only if the determinant is zero. + + If the actual adjugate and determinant are needed, use :meth:`adj_det` + instead. If the intention is to compute the inverse matrix or solve a + system of equations then :meth:`inv_den` is more efficient. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(2), ZZ(-1), ZZ(0)], + ... [ZZ(-1), ZZ(2), ZZ(-1)], + ... [ZZ(0), ZZ(0), ZZ(2)]], (3, 3), ZZ) + >>> Ainv, den = A.inv_den() + >>> den + 6 + >>> Ainv + DomainMatrix([[4, 2, 1], [2, 4, 2], [0, 0, 3]], (3, 3), ZZ) + >>> A * Ainv == den * A.eye(A.shape, A.domain).to_dense() + True + + Parameters + ========== + + method : str, optional + The method to use to compute the inverse. Can be one of ``None``, + ``'rref'`` or ``'charpoly'``. If ``None`` then the method is + chosen automatically (see :meth:`solve_den` for details). + + See Also + ======== + + inv + det + adj_det + solve_den + """ + I = self.eye(self.shape, self.domain) + return self.solve_den(I, method=method) + + def solve_den(self, b, method=None): + """ + Solve matrix equation $Ax = b$ without fractions in the ground domain. + + Examples + ======== + + Solve a matrix equation over the integers: + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ) + >>> b = DM([[ZZ(5)], [ZZ(6)]], ZZ) + >>> xnum, xden = A.solve_den(b) + >>> xden + -2 + >>> xnum + DomainMatrix([[8], [-9]], (2, 1), ZZ) + >>> A * xnum == xden * b + True + + Solve a matrix equation over a polynomial ring: + + >>> from sympy import ZZ + >>> from sympy.abc import x, y, z, a, b + >>> R = ZZ[x, y, z, a, b] + >>> M = DM([[x*y, x*z], [y*z, x*z]], R) + >>> b = DM([[a], [b]], R) + >>> M.to_Matrix() + Matrix([ + [x*y, x*z], + [y*z, x*z]]) + >>> b.to_Matrix() + Matrix([ + [a], + [b]]) + >>> xnum, xden = M.solve_den(b) + >>> xden + x**2*y*z - x*y*z**2 + >>> xnum.to_Matrix() + Matrix([ + [ a*x*z - b*x*z], + [-a*y*z + b*x*y]]) + >>> M * xnum == xden * b + True + + The solution can be expressed over a fraction field which will cancel + gcds between the denominator and the elements of the numerator: + + >>> xsol = xnum.to_field() / xden + >>> xsol.to_Matrix() + Matrix([ + [ (a - b)/(x*y - y*z)], + [(-a*z + b*x)/(x**2*z - x*z**2)]]) + >>> (M * xsol).to_Matrix() == b.to_Matrix() + True + + When solving a large system of equations this cancellation step might + be a lot slower than :func:`solve_den` itself. The solution can also be + expressed as a ``Matrix`` without attempting any polynomial + cancellation between the numerator and denominator giving a less + simplified result more quickly: + + >>> xsol_uncancelled = xnum.to_Matrix() / xnum.domain.to_sympy(xden) + >>> xsol_uncancelled + Matrix([ + [ (a*x*z - b*x*z)/(x**2*y*z - x*y*z**2)], + [(-a*y*z + b*x*y)/(x**2*y*z - x*y*z**2)]]) + >>> from sympy import cancel + >>> cancel(xsol_uncancelled) == xsol.to_Matrix() + True + + Parameters + ========== + + self : :class:`DomainMatrix` + The ``m x n`` matrix $A$ in the equation $Ax = b$. Underdetermined + systems are not supported so ``m >= n``: $A$ should be square or + have more rows than columns. + b : :class:`DomainMatrix` + The ``n x m`` matrix $b$ for the rhs. + cp : list of :class:`~.DomainElement`, optional + The characteristic polynomial of the matrix $A$. If not given, it + will be computed using :meth:`charpoly`. + method: str, optional + The method to use for solving the system. Can be one of ``None``, + ``'charpoly'`` or ``'rref'``. If ``None`` (the default) then the + method will be chosen automatically. + + The ``charpoly`` method uses :meth:`solve_den_charpoly` and can + only be used if the matrix is square. This method is division free + and can be used with any domain. + + The ``rref`` method is fraction free but requires exact division + in the ground domain (``exquo``). This is also suitable for most + domains. This method can be used with overdetermined systems (more + equations than unknowns) but not underdetermined systems as a + unique solution is sought. + + Returns + ======= + + (xnum, xden) : (DomainMatrix, DomainElement) + The solution of the equation $Ax = b$ as a pair consisting of an + ``n x m`` matrix numerator ``xnum`` and a scalar denominator + ``xden``. + + The solution $x$ is given by ``x = xnum / xden``. The division free + invariant is ``A * xnum == xden * b``. If $A$ is square then the + denominator ``xden`` will be a divisor of the determinant $det(A)$. + + Raises + ====== + + DMNonInvertibleMatrixError + If the system $Ax = b$ does not have a unique solution. + + See Also + ======== + + solve_den_charpoly + solve_den_rref + inv_den + """ + m, n = self.shape + bm, bn = b.shape + + if m != bm: + raise DMShapeError("Matrix equation shape mismatch.") + + if method is None: + method = 'rref' + elif method == 'charpoly' and m != n: + raise DMNonSquareMatrixError("method='charpoly' requires a square matrix.") + + if method == 'charpoly': + xnum, xden = self.solve_den_charpoly(b) + elif method == 'rref': + xnum, xden = self.solve_den_rref(b) + else: + raise DMBadInputError("method should be 'rref' or 'charpoly'") + + return xnum, xden + + def solve_den_rref(self, b): + """ + Solve matrix equation $Ax = b$ using fraction-free RREF + + Solves the matrix equation $Ax = b$ for $x$ and returns the solution + as a numerator/denominator pair. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ) + >>> b = DM([[ZZ(5)], [ZZ(6)]], ZZ) + >>> xnum, xden = A.solve_den_rref(b) + >>> xden + -2 + >>> xnum + DomainMatrix([[8], [-9]], (2, 1), ZZ) + >>> A * xnum == xden * b + True + + See Also + ======== + + solve_den + solve_den_charpoly + """ + A = self + m, n = A.shape + bm, bn = b.shape + + if m != bm: + raise DMShapeError("Matrix equation shape mismatch.") + + if m < n: + raise DMShapeError("Underdetermined matrix equation.") + + Aaug = A.hstack(b) + Aaug_rref, denom, pivots = Aaug.rref_den() + + # XXX: We check here if there are pivots after the last column. If + # there were than it possibly means that rref_den performed some + # unnecessary elimination. It would be better if rref methods had a + # parameter indicating how many columns should be used for elimination. + if len(pivots) != n or pivots and pivots[-1] >= n: + raise DMNonInvertibleMatrixError("Non-unique solution.") + + xnum = Aaug_rref[:n, n:] + xden = denom + + return xnum, xden + + def solve_den_charpoly(self, b, cp=None, check=True): + """ + Solve matrix equation $Ax = b$ using the characteristic polynomial. + + This method solves the square matrix equation $Ax = b$ for $x$ using + the characteristic polynomial without any division or fractions in the + ground domain. + + Examples + ======== + + Solve a matrix equation over the integers: + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DM + >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ) + >>> b = DM([[ZZ(5)], [ZZ(6)]], ZZ) + >>> xnum, detA = A.solve_den_charpoly(b) + >>> detA + -2 + >>> xnum + DomainMatrix([[8], [-9]], (2, 1), ZZ) + >>> A * xnum == detA * b + True + + Parameters + ========== + + self : DomainMatrix + The ``n x n`` matrix `A` in the equation `Ax = b`. Must be square + and invertible. + b : DomainMatrix + The ``n x m`` matrix `b` for the rhs. + cp : list, optional + The characteristic polynomial of the matrix `A` if known. If not + given, it will be computed using :meth:`charpoly`. + check : bool, optional + If ``True`` (the default) check that the determinant is not zero + and raise an error if it is. If ``False`` then if the determinant + is zero the return value will be equal to ``(A.adjugate()*b, 0)``. + + Returns + ======= + + (xnum, detA) : (DomainMatrix, DomainElement) + The solution of the equation `Ax = b` as a matrix numerator and + scalar denominator pair. The denominator is equal to the + determinant of `A` and the numerator is ``adj(A)*b``. + + The solution $x$ is given by ``x = xnum / detA``. The division free + invariant is ``A * xnum == detA * b``. + + If ``b`` is the identity matrix, then ``xnum`` is the adjugate matrix + and we have ``A * adj(A) == detA * I``. + + See Also + ======== + + solve_den + Main frontend for solving matrix equations with denominator. + solve_den_rref + Solve matrix equations using fraction-free RREF. + inv_den + Invert a matrix using the characteristic polynomial. + """ + A, b = self.unify(b) + m, n = self.shape + mb, nb = b.shape + + if m != n: + raise DMNonSquareMatrixError("Matrix must be square") + + if mb != m: + raise DMShapeError("Matrix and vector must have the same number of rows") + + f, detA = self.adj_poly_det(cp=cp) + + if check and not detA: + raise DMNonInvertibleMatrixError("Matrix is not invertible") + + # Compute adj(A)*b = det(A)*inv(A)*b using Horner's method without + # constructing inv(A) explicitly. + adjA_b = self.eval_poly_mul(f, b) + + return (adjA_b, detA) + + def adj_poly_det(self, cp=None): + """ + Return the polynomial $p$ such that $p(A) = adj(A)$ and also the + determinant of $A$. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DM + >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ) + >>> p, detA = A.adj_poly_det() + >>> p + [-1, 5] + >>> p_A = A.eval_poly(p) + >>> p_A + DomainMatrix([[4, -2], [-3, 1]], (2, 2), QQ) + >>> p[0]*A**1 + p[1]*A**0 == p_A + True + >>> p_A == A.adjugate() + True + >>> A * A.adjugate() == detA * A.eye(A.shape, A.domain).to_dense() + True + + See Also + ======== + + adjugate + eval_poly + adj_det + """ + + # Cayley-Hamilton says that a matrix satisfies its own minimal + # polynomial + # + # p[0]*A^n + p[1]*A^(n-1) + ... + p[n]*I = 0 + # + # with p[0]=1 and p[n]=(-1)^n*det(A) or + # + # det(A)*I = -(-1)^n*(p[0]*A^(n-1) + p[1]*A^(n-2) + ... + p[n-1]*A). + # + # Define a new polynomial f with f[i] = -(-1)^n*p[i] for i=0..n-1. Then + # + # det(A)*I = f[0]*A^n + f[1]*A^(n-1) + ... + f[n-1]*A. + # + # Multiplying on the right by inv(A) gives + # + # det(A)*inv(A) = f[0]*A^(n-1) + f[1]*A^(n-2) + ... + f[n-1]. + # + # So adj(A) = det(A)*inv(A) = f(A) + + A = self + m, n = self.shape + + if m != n: + raise DMNonSquareMatrixError("Matrix must be square") + + if cp is None: + cp = A.charpoly() + + if len(cp) % 2: + # n is even + detA = cp[-1] + f = [-cpi for cpi in cp[:-1]] + else: + # n is odd + detA = -cp[-1] + f = cp[:-1] + + return f, detA + + def eval_poly(self, p): + """ + Evaluate polynomial function of a matrix $p(A)$. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DM + >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ) + >>> p = [QQ(1), QQ(2), QQ(3)] + >>> p_A = A.eval_poly(p) + >>> p_A + DomainMatrix([[12, 14], [21, 33]], (2, 2), QQ) + >>> p_A == p[0]*A**2 + p[1]*A + p[2]*A**0 + True + + See Also + ======== + + eval_poly_mul + """ + A = self + m, n = A.shape + + if m != n: + raise DMNonSquareMatrixError("Matrix must be square") + + if not p: + return self.zeros(self.shape, self.domain) + elif len(p) == 1: + return p[0] * self.eye(self.shape, self.domain) + + # Evaluate p(A) using Horner's method: + # XXX: Use Paterson-Stockmeyer method? + I = A.eye(A.shape, A.domain) + p_A = p[0] * I + for pi in p[1:]: + p_A = A*p_A + pi*I + + return p_A + + def eval_poly_mul(self, p, B): + r""" + Evaluate polynomial matrix product $p(A) \times B$. + + Evaluate the polynomial matrix product $p(A) \times B$ using Horner's + method without creating the matrix $p(A)$ explicitly. If $B$ is a + column matrix then this method will only use matrix-vector multiplies + and no matrix-matrix multiplies are needed. + + If $B$ is square or wide or if $A$ can be represented in a simpler + domain than $B$ then it might be faster to evaluate $p(A)$ explicitly + (see :func:`eval_poly`) and then multiply with $B$. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DM + >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ) + >>> b = DM([[QQ(5)], [QQ(6)]], QQ) + >>> p = [QQ(1), QQ(2), QQ(3)] + >>> p_A_b = A.eval_poly_mul(p, b) + >>> p_A_b + DomainMatrix([[144], [303]], (2, 1), QQ) + >>> p_A_b == p[0]*A**2*b + p[1]*A*b + p[2]*b + True + >>> A.eval_poly_mul(p, b) == A.eval_poly(p)*b + True + + See Also + ======== + + eval_poly + solve_den_charpoly + """ + A = self + m, n = A.shape + mb, nb = B.shape + + if m != n: + raise DMNonSquareMatrixError("Matrix must be square") + + if mb != n: + raise DMShapeError("Matrices are not aligned") + + if A.domain != B.domain: + raise DMDomainError("Matrices must have the same domain") + + # Given a polynomial p(x) = p[0]*x^n + p[1]*x^(n-1) + ... + p[n-1] + # and matrices A and B we want to find + # + # p(A)*B = p[0]*A^n*B + p[1]*A^(n-1)*B + ... + p[n-1]*B + # + # Factoring out A term by term we get + # + # p(A)*B = A*(...A*(A*(A*(p[0]*B) + p[1]*B) + p[2]*B) + ...) + p[n-1]*B + # + # where each pair of brackets represents one iteration of the loop + # below starting from the innermost p[0]*B. If B is a column matrix + # then products like A*(...) are matrix-vector multiplies and products + # like p[i]*B are scalar-vector multiplies so there are no + # matrix-matrix multiplies. + + if not p: + return B.zeros(B.shape, B.domain, fmt=B.rep.fmt) + + p_A_B = p[0]*B + + for p_i in p[1:]: + p_A_B = A*p_A_B + p_i*B + + return p_A_B + + def lu(self): + r""" + Returns Lower and Upper decomposition of the DomainMatrix + + Returns + ======= + + (L, U, exchange) + L, U are Lower and Upper decomposition of the DomainMatrix, + exchange is the list of indices of rows exchanged in the + decomposition. + + Raises + ====== + + ValueError + If the domain of DomainMatrix not a Field + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [QQ(1), QQ(-1)], + ... [QQ(2), QQ(-2)]], (2, 2), QQ) + >>> L, U, exchange = A.lu() + >>> L + DomainMatrix([[1, 0], [2, 1]], (2, 2), QQ) + >>> U + DomainMatrix([[1, -1], [0, 0]], (2, 2), QQ) + >>> exchange + [] + + See Also + ======== + + lu_solve + + """ + if not self.domain.is_Field: + raise DMNotAField('Not a field') + L, U, swaps = self.rep.lu() + return self.from_rep(L), self.from_rep(U), swaps + + def qr(self): + r""" + QR decomposition of the DomainMatrix. + + Explanation + =========== + + The QR decomposition expresses a matrix as the product of an orthogonal + matrix (Q) and an upper triangular matrix (R). In this implementation, + Q is not orthonormal: its columns are orthogonal but not normalized to + unit vectors. This avoids unnecessary divisions and is particularly + suited for exact arithmetic domains. + + Note + ==== + + This implementation is valid only for matrices over real domains. For + matrices over complex domains, a proper QR decomposition would require + handling conjugation to ensure orthogonality. + + Returns + ======= + + (Q, R) + Q is the orthogonal matrix, and R is the upper triangular matrix + resulting from the QR decomposition of the DomainMatrix. + + Raises + ====== + + DMDomainError + If the domain of the DomainMatrix is not a field (e.g., QQ). + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([[1, 2], [3, 4], [5, 6]], (3, 2), QQ) + >>> Q, R = A.qr() + >>> Q + DomainMatrix([[1, 26/35], [3, 8/35], [5, -2/7]], (3, 2), QQ) + >>> R + DomainMatrix([[1, 44/35], [0, 1]], (2, 2), QQ) + >>> Q * R == A + True + >>> (Q.transpose() * Q).is_diagonal + True + >>> R.is_upper + True + + See Also + ======== + + lu + + """ + ddm_q, ddm_r = self.rep.qr() + Q = self.from_rep(ddm_q) + R = self.from_rep(ddm_r) + return Q, R + + def lu_solve(self, rhs): + r""" + Solver for DomainMatrix x in the A*x = B + + Parameters + ========== + + rhs : DomainMatrix B + + Returns + ======= + + DomainMatrix + x in A*x = B + + Raises + ====== + + DMShapeError + If the DomainMatrix A and rhs have different number of rows + + ValueError + If the domain of DomainMatrix A not a Field + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [QQ(1), QQ(2)], + ... [QQ(3), QQ(4)]], (2, 2), QQ) + >>> B = DomainMatrix([ + ... [QQ(1), QQ(1)], + ... [QQ(0), QQ(1)]], (2, 2), QQ) + + >>> A.lu_solve(B) + DomainMatrix([[-2, -1], [3/2, 1]], (2, 2), QQ) + + See Also + ======== + + lu + + """ + if self.shape[0] != rhs.shape[0]: + raise DMShapeError("Shape") + if not self.domain.is_Field: + raise DMNotAField('Not a field') + sol = self.rep.lu_solve(rhs.rep) + return self.from_rep(sol) + + def fflu(self): + """ + Fraction-free LU decomposition of DomainMatrix. + + Explanation + =========== + + This method computes the PLDU decomposition + using Gauss-Bareiss elimination in a fraction-free manner, + it ensures that all intermediate results remain in + the domain of the input matrix. Unlike standard + LU decomposition, which introduces division, this approach + avoids fractions, making it particularly suitable + for exact arithmetic over integers or polynomials. + + This method satisfies the invariant: + + P * A = L * inv(D) * U + + Returns + ======= + + (P, L, D, U) + - P (Permutation matrix) + - L (Lower triangular matrix) + - D (Diagonal matrix) + - U (Upper triangular matrix) + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) + >>> P, L, D, U = A.fflu() + >>> P + DomainMatrix([[1, 0], [0, 1]], (2, 2), ZZ) + >>> L + DomainMatrix([[1, 0], [3, -2]], (2, 2), ZZ) + >>> D + DomainMatrix([[1, 0], [0, -2]], (2, 2), ZZ) + >>> U + DomainMatrix([[1, 2], [0, -2]], (2, 2), ZZ) + >>> L.is_lower and U.is_upper and D.is_diagonal + True + >>> L * D.to_field().inv() * U == P * A.to_field() + True + >>> I, d = D.inv_den() + >>> L * I * U == d * P * A + True + + See Also + ======== + + sympy.polys.matrices.ddm.DDM.fflu + + References + ========== + + .. [1] Nakos, G. C., Turner, P. R., & Williams, R. M. (1997). Fraction-free + algorithms for linear and polynomial equations. ACM SIGSAM Bulletin, + 31(3), 11-19. https://doi.org/10.1145/271130.271133 + .. [2] Middeke, J.; Jeffrey, D.J.; Koutschan, C. (2020), "Common Factors + in Fraction-Free Matrix Decompositions", Mathematics in Computer Science, + 15 (4): 589–608, arXiv:2005.12380, doi:10.1007/s11786-020-00495-9 + .. [3] https://en.wikipedia.org/wiki/Bareiss_algorithm + """ + from_rep = self.from_rep + P, L, D, U = self.rep.fflu() + return from_rep(P), from_rep(L), from_rep(D), from_rep(U) + + def _solve(A, b): + # XXX: Not sure about this method or its signature. It is just created + # because it is needed by the holonomic module. + if A.shape[0] != b.shape[0]: + raise DMShapeError("Shape") + if A.domain != b.domain or not A.domain.is_Field: + raise DMNotAField('Not a field') + Aaug = A.hstack(b) + Arref, pivots = Aaug.rref() + particular = Arref.from_rep(Arref.rep.particular()) + nullspace_rep, nonpivots = Arref[:,:-1].rep.nullspace() + nullspace = Arref.from_rep(nullspace_rep) + return particular, nullspace + + def charpoly(self): + r""" + Characteristic polynomial of a square matrix. + + Computes the characteristic polynomial in a fully expanded form using + division free arithmetic. If a factorization of the characteristic + polynomial is needed then it is more efficient to call + :meth:`charpoly_factor_list` than calling :meth:`charpoly` and then + factorizing the result. + + Returns + ======= + + list: list of DomainElement + coefficients of the characteristic polynomial + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + >>> A.charpoly() + [1, -5, -2] + + See Also + ======== + + charpoly_factor_list + Compute the factorisation of the characteristic polynomial. + charpoly_factor_blocks + A partial factorisation of the characteristic polynomial that can + be computed more efficiently than either the full factorisation or + the fully expanded polynomial. + """ + M = self + K = M.domain + + factors = M.charpoly_factor_blocks() + + cp = [K.one] + + for f, mult in factors: + for _ in range(mult): + cp = dup_mul(cp, f, K) + + return cp + + def charpoly_factor_list(self): + """ + Full factorization of the characteristic polynomial. + + Examples + ======== + + >>> from sympy.polys.matrices import DM + >>> from sympy import ZZ + >>> M = DM([[6, -1, 0, 0], + ... [9, 12, 0, 0], + ... [0, 0, 1, 2], + ... [0, 0, 5, 6]], ZZ) + + Compute the factorization of the characteristic polynomial: + + >>> M.charpoly_factor_list() + [([1, -9], 2), ([1, -7, -4], 1)] + + Use :meth:`charpoly` to get the unfactorized characteristic polynomial: + + >>> M.charpoly() + [1, -25, 203, -495, -324] + + The same calculations with ``Matrix``: + + >>> M.to_Matrix().charpoly().as_expr() + lambda**4 - 25*lambda**3 + 203*lambda**2 - 495*lambda - 324 + >>> M.to_Matrix().charpoly().as_expr().factor() + (lambda - 9)**2*(lambda**2 - 7*lambda - 4) + + Returns + ======= + + list: list of pairs (factor, multiplicity) + A full factorization of the characteristic polynomial. + + See Also + ======== + + charpoly + Expanded form of the characteristic polynomial. + charpoly_factor_blocks + A partial factorisation of the characteristic polynomial that can + be computed more efficiently. + """ + M = self + K = M.domain + + # It is more efficient to start from the partial factorization provided + # for free by M.charpoly_factor_blocks than the expanded M.charpoly. + factors = M.charpoly_factor_blocks() + + factors_irreducible = [] + + for factor_i, mult_i in factors: + + _, factors_list = dup_factor_list(factor_i, K) + + for factor_j, mult_j in factors_list: + factors_irreducible.append((factor_j, mult_i * mult_j)) + + return _collect_factors(factors_irreducible) + + def charpoly_factor_blocks(self): + """ + Partial factorisation of the characteristic polynomial. + + This factorisation arises from a block structure of the matrix (if any) + and so the factors are not guaranteed to be irreducible. The + :meth:`charpoly_factor_blocks` method is the most efficient way to get + a representation of the characteristic polynomial but the result is + neither fully expanded nor fully factored. + + Examples + ======== + + >>> from sympy.polys.matrices import DM + >>> from sympy import ZZ + >>> M = DM([[6, -1, 0, 0], + ... [9, 12, 0, 0], + ... [0, 0, 1, 2], + ... [0, 0, 5, 6]], ZZ) + + This computes a partial factorization using only the block structure of + the matrix to reveal factors: + + >>> M.charpoly_factor_blocks() + [([1, -18, 81], 1), ([1, -7, -4], 1)] + + These factors correspond to the two diagonal blocks in the matrix: + + >>> DM([[6, -1], [9, 12]], ZZ).charpoly() + [1, -18, 81] + >>> DM([[1, 2], [5, 6]], ZZ).charpoly() + [1, -7, -4] + + Use :meth:`charpoly_factor_list` to get a complete factorization into + irreducibles: + + >>> M.charpoly_factor_list() + [([1, -9], 2), ([1, -7, -4], 1)] + + Use :meth:`charpoly` to get the expanded characteristic polynomial: + + >>> M.charpoly() + [1, -25, 203, -495, -324] + + Returns + ======= + + list: list of pairs (factor, multiplicity) + A partial factorization of the characteristic polynomial. + + See Also + ======== + + charpoly + Compute the fully expanded characteristic polynomial. + charpoly_factor_list + Compute a full factorization of the characteristic polynomial. + """ + M = self + + if not M.is_square: + raise DMNonSquareMatrixError("not square") + + # scc returns indices that permute the matrix into block triangular + # form and can extract the diagonal blocks. M.charpoly() is equal to + # the product of the diagonal block charpolys. + components = M.scc() + + block_factors = [] + + for indices in components: + block = M.extract(indices, indices) + block_factors.append((block.charpoly_base(), 1)) + + return _collect_factors(block_factors) + + def charpoly_base(self): + """ + Base case for :meth:`charpoly_factor_blocks` after block decomposition. + + This method is used internally by :meth:`charpoly_factor_blocks` as the + base case for computing the characteristic polynomial of a block. It is + more efficient to call :meth:`charpoly_factor_blocks`, :meth:`charpoly` + or :meth:`charpoly_factor_list` rather than call this method directly. + + This will use either the dense or the sparse implementation depending + on the sparsity of the matrix and will clear denominators if possible + before calling :meth:`charpoly_berk` to compute the characteristic + polynomial using the Berkowitz algorithm. + + See Also + ======== + + charpoly + charpoly_factor_list + charpoly_factor_blocks + charpoly_berk + """ + M = self + K = M.domain + + # It seems that the sparse implementation is always faster for random + # matrices with fewer than 50% non-zero entries. This does not seem to + # depend on domain, size, bit count etc. + density = self.nnz() / self.shape[0]**2 + if density < 0.5: + M = M.to_sparse() + else: + M = M.to_dense() + + # Clearing denominators is always more efficient if it can be done. + # Doing it here after block decomposition is good because each block + # might have a smaller denominator. However it might be better for + # charpoly and charpoly_factor_list to restore the denominators only at + # the very end so that they can call e.g. dup_factor_list before + # restoring the denominators. The methods would need to be changed to + # return (poly, denom) pairs to make that work though. + clear_denoms = K.is_Field and K.has_assoc_Ring + + if clear_denoms: + clear_denoms = True + d, M = M.clear_denoms(convert=True) + d = d.element + K_f = K + K_r = M.domain + + # Berkowitz algorithm over K_r. + cp = M.charpoly_berk() + + if clear_denoms: + # Restore the denominator in the charpoly over K_f. + # + # If M = N/d then p_M(x) = p_N(x*d)/d^n. + cp = dup_convert(cp, K_r, K_f) + p = [K_f.one, K_f.zero] + q = [K_f.one/d] + cp = dup_transform(cp, p, q, K_f) + + return cp + + def charpoly_berk(self): + """Compute the characteristic polynomial using the Berkowitz algorithm. + + This method directly calls the underlying implementation of the + Berkowitz algorithm (:meth:`sympy.polys.matrices.dense.ddm_berk` or + :meth:`sympy.polys.matrices.sdm.sdm_berk`). + + This is used by :meth:`charpoly` and other methods as the base case for + for computing the characteristic polynomial. However those methods will + apply other optimizations such as block decomposition, clearing + denominators and converting between dense and sparse representations + before calling this method. It is more efficient to call those methods + instead of this one but this method is provided for direct access to + the Berkowitz algorithm. + + Examples + ======== + + >>> from sympy.polys.matrices import DM + >>> from sympy import QQ + >>> M = DM([[6, -1, 0, 0], + ... [9, 12, 0, 0], + ... [0, 0, 1, 2], + ... [0, 0, 5, 6]], QQ) + >>> M.charpoly_berk() + [1, -25, 203, -495, -324] + + See Also + ======== + + charpoly + charpoly_base + charpoly_factor_list + charpoly_factor_blocks + sympy.polys.matrices.dense.ddm_berk + sympy.polys.matrices.sdm.sdm_berk + """ + return self.rep.charpoly() + + @classmethod + def eye(cls, shape, domain): + r""" + Return identity matrix of size n or shape (m, n). + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> DomainMatrix.eye(3, QQ) + DomainMatrix({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}, (3, 3), QQ) + + """ + if isinstance(shape, int): + shape = (shape, shape) + return cls.from_rep(SDM.eye(shape, domain)) + + @classmethod + def diag(cls, diagonal, domain, shape=None): + r""" + Return diagonal matrix with entries from ``diagonal``. + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import ZZ + >>> DomainMatrix.diag([ZZ(5), ZZ(6)], ZZ) + DomainMatrix({0: {0: 5}, 1: {1: 6}}, (2, 2), ZZ) + + """ + if shape is None: + N = len(diagonal) + shape = (N, N) + return cls.from_rep(SDM.diag(diagonal, domain, shape)) + + @classmethod + def zeros(cls, shape, domain, *, fmt='sparse'): + """Returns a zero DomainMatrix of size shape, belonging to the specified domain + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> DomainMatrix.zeros((2, 3), QQ) + DomainMatrix({}, (2, 3), QQ) + + """ + return cls.from_rep(SDM.zeros(shape, domain)) + + @classmethod + def ones(cls, shape, domain): + """Returns a DomainMatrix of 1s, of size shape, belonging to the specified domain + + Examples + ======== + + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy import QQ + >>> DomainMatrix.ones((2,3), QQ) + DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ) + + """ + return cls.from_rep(DDM.ones(shape, domain).to_dfm_or_ddm()) + + def __eq__(A, B): + r""" + Checks for two DomainMatrix matrices to be equal or not + + Parameters + ========== + + A, B: DomainMatrix + to check equality + + Returns + ======= + + Boolean + True for equal, else False + + Raises + ====== + + NotImplementedError + If B is not a DomainMatrix + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> A = DomainMatrix([ + ... [ZZ(1), ZZ(2)], + ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) + >>> B = DomainMatrix([ + ... [ZZ(1), ZZ(1)], + ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) + >>> A.__eq__(A) + True + >>> A.__eq__(B) + False + + """ + if not isinstance(A, type(B)): + return NotImplemented + return A.domain == B.domain and A.rep == B.rep + + def unify_eq(A, B): + if A.shape != B.shape: + return False + if A.domain != B.domain: + A, B = A.unify(B) + return A == B + + def lll(A, delta=QQ(3, 4)): + """ + Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm. + See [1]_ and [2]_. + + Parameters + ========== + + delta : QQ, optional + The Lovász parameter. Must be in the interval (0.25, 1), with larger + values producing a more reduced basis. The default is 0.75 for + historical reasons. + + Returns + ======= + + The reduced basis as a DomainMatrix over ZZ. + + Throws + ====== + + DMValueError: if delta is not in the range (0.25, 1) + DMShapeError: if the matrix is not of shape (m, n) with m <= n + DMDomainError: if the matrix domain is not ZZ + DMRankError: if the matrix contains linearly dependent rows + + Examples + ======== + + >>> from sympy.polys.domains import ZZ, QQ + >>> from sympy.polys.matrices import DM + >>> x = DM([[1, 0, 0, 0, -20160], + ... [0, 1, 0, 0, 33768], + ... [0, 0, 1, 0, 39578], + ... [0, 0, 0, 1, 47757]], ZZ) + >>> y = DM([[10, -3, -2, 8, -4], + ... [3, -9, 8, 1, -11], + ... [-3, 13, -9, -3, -9], + ... [-12, -7, -11, 9, -1]], ZZ) + >>> assert x.lll(delta=QQ(5, 6)) == y + + Notes + ===== + + The implementation is derived from the Maple code given in Figures 4.3 + and 4.4 of [3]_ (pp.68-69). It uses the efficient method of only calculating + state updates as they are required. + + See also + ======== + + lll_transform + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Lenstra%E2%80%93Lenstra%E2%80%93Lov%C3%A1sz_lattice_basis_reduction_algorithm + .. [2] https://web.archive.org/web/20221029115428/https://web.cs.elte.hu/~lovasz/scans/lll.pdf + .. [3] Murray R. Bremner, "Lattice Basis Reduction: An Introduction to the LLL Algorithm and Its Applications" + + """ + return DomainMatrix.from_rep(A.rep.lll(delta=delta)) + + def lll_transform(A, delta=QQ(3, 4)): + """ + Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm + and returns the reduced basis and transformation matrix. + + Explanation + =========== + + Parameters, algorithm and basis are the same as for :meth:`lll` except that + the return value is a tuple `(B, T)` with `B` the reduced basis and + `T` a transformation matrix. The original basis `A` is transformed to + `B` with `T*A == B`. If only `B` is needed then :meth:`lll` should be + used as it is a little faster. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ, QQ + >>> from sympy.polys.matrices import DM + >>> X = DM([[1, 0, 0, 0, -20160], + ... [0, 1, 0, 0, 33768], + ... [0, 0, 1, 0, 39578], + ... [0, 0, 0, 1, 47757]], ZZ) + >>> B, T = X.lll_transform(delta=QQ(5, 6)) + >>> T * X == B + True + + See also + ======== + + lll + + """ + reduced, transform = A.rep.lll_transform(delta=delta) + return DomainMatrix.from_rep(reduced), DomainMatrix.from_rep(transform) + + +def _collect_factors(factors_list): + """ + Collect repeating factors and sort. + + >>> from sympy.polys.matrices.domainmatrix import _collect_factors + >>> _collect_factors([([1, 2], 2), ([1, 4], 3), ([1, 2], 5)]) + [([1, 4], 3), ([1, 2], 7)] + """ + factors = Counter() + for factor, exponent in factors_list: + factors[tuple(factor)] += exponent + + factors_list = [(list(f), e) for f, e in factors.items()] + + return _sort_factors(factors_list) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/domainscalar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/domainscalar.py new file mode 100644 index 0000000000000000000000000000000000000000..df439a60a0ea0df5f6fac988c06da2a06a4fbac2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/domainscalar.py @@ -0,0 +1,122 @@ +""" + +Module for the DomainScalar class. + +A DomainScalar represents an element which is in a particular +Domain. The idea is that the DomainScalar class provides the +convenience routines for unifying elements with different domains. + +It assists in Scalar Multiplication and getitem for DomainMatrix. + +""" +from ..constructor import construct_domain + +from sympy.polys.domains import Domain, ZZ + + +class DomainScalar: + r""" + docstring + """ + + def __new__(cls, element, domain): + if not isinstance(domain, Domain): + raise TypeError("domain should be of type Domain") + if not domain.of_type(element): + raise TypeError("element %s should be in domain %s" % (element, domain)) + return cls.new(element, domain) + + @classmethod + def new(cls, element, domain): + obj = super().__new__(cls) + obj.element = element + obj.domain = domain + return obj + + def __repr__(self): + return repr(self.element) + + @classmethod + def from_sympy(cls, expr): + [domain, [element]] = construct_domain([expr]) + return cls.new(element, domain) + + def to_sympy(self): + return self.domain.to_sympy(self.element) + + def to_domain(self, domain): + element = domain.convert_from(self.element, self.domain) + return self.new(element, domain) + + def convert_to(self, domain): + return self.to_domain(domain) + + def unify(self, other): + domain = self.domain.unify(other.domain) + return self.to_domain(domain), other.to_domain(domain) + + def __bool__(self): + return bool(self.element) + + def __add__(self, other): + if not isinstance(other, DomainScalar): + return NotImplemented + self, other = self.unify(other) + return self.new(self.element + other.element, self.domain) + + def __sub__(self, other): + if not isinstance(other, DomainScalar): + return NotImplemented + self, other = self.unify(other) + return self.new(self.element - other.element, self.domain) + + def __mul__(self, other): + if not isinstance(other, DomainScalar): + if isinstance(other, int): + other = DomainScalar(ZZ(other), ZZ) + else: + return NotImplemented + + self, other = self.unify(other) + return self.new(self.element * other.element, self.domain) + + def __floordiv__(self, other): + if not isinstance(other, DomainScalar): + return NotImplemented + self, other = self.unify(other) + return self.new(self.domain.quo(self.element, other.element), self.domain) + + def __mod__(self, other): + if not isinstance(other, DomainScalar): + return NotImplemented + self, other = self.unify(other) + return self.new(self.domain.rem(self.element, other.element), self.domain) + + def __divmod__(self, other): + if not isinstance(other, DomainScalar): + return NotImplemented + self, other = self.unify(other) + q, r = self.domain.div(self.element, other.element) + return (self.new(q, self.domain), self.new(r, self.domain)) + + def __pow__(self, n): + if not isinstance(n, int): + return NotImplemented + return self.new(self.element**n, self.domain) + + def __pos__(self): + return self.new(+self.element, self.domain) + + def __neg__(self): + return self.new(-self.element, self.domain) + + def __eq__(self, other): + if not isinstance(other, DomainScalar): + return NotImplemented + return self.element == other.element and self.domain == other.domain + + def is_zero(self): + return self.element == self.domain.zero + + def is_one(self): + return self.element == self.domain.one diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/eigen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/eigen.py new file mode 100644 index 0000000000000000000000000000000000000000..17d673c6ea09002e1cfd5357f301c447a7af4341 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/eigen.py @@ -0,0 +1,90 @@ +""" + +Routines for computing eigenvectors with DomainMatrix. + +""" +from sympy.core.symbol import Dummy + +from ..agca.extensions import FiniteExtension +from ..factortools import dup_factor_list +from ..polyroots import roots +from ..polytools import Poly +from ..rootoftools import CRootOf + +from .domainmatrix import DomainMatrix + + +def dom_eigenvects(A, l=Dummy('lambda')): + charpoly = A.charpoly() + rows, cols = A.shape + domain = A.domain + _, factors = dup_factor_list(charpoly, domain) + + rational_eigenvects = [] + algebraic_eigenvects = [] + for base, exp in factors: + if len(base) == 2: + field = domain + eigenval = -base[1] / base[0] + + EE_items = [ + [eigenval if i == j else field.zero for j in range(cols)] + for i in range(rows)] + EE = DomainMatrix(EE_items, (rows, cols), field) + + basis = (A - EE).nullspace(divide_last=True) + rational_eigenvects.append((field, eigenval, exp, basis)) + else: + minpoly = Poly.from_list(base, l, domain=domain) + field = FiniteExtension(minpoly) + eigenval = field(l) + + AA_items = [ + [Poly.from_list([item], l, domain=domain).rep for item in row] + for row in A.rep.to_ddm()] + AA_items = [[field(item) for item in row] for row in AA_items] + AA = DomainMatrix(AA_items, (rows, cols), field) + EE_items = [ + [eigenval if i == j else field.zero for j in range(cols)] + for i in range(rows)] + EE = DomainMatrix(EE_items, (rows, cols), field) + + basis = (AA - EE).nullspace(divide_last=True) + algebraic_eigenvects.append((field, minpoly, exp, basis)) + + return rational_eigenvects, algebraic_eigenvects + + +def dom_eigenvects_to_sympy( + rational_eigenvects, algebraic_eigenvects, + Matrix, **kwargs +): + result = [] + + for field, eigenvalue, multiplicity, eigenvects in rational_eigenvects: + eigenvects = eigenvects.rep.to_ddm() + eigenvalue = field.to_sympy(eigenvalue) + new_eigenvects = [ + Matrix([field.to_sympy(x) for x in vect]) + for vect in eigenvects] + result.append((eigenvalue, multiplicity, new_eigenvects)) + + for field, minpoly, multiplicity, eigenvects in algebraic_eigenvects: + eigenvects = eigenvects.rep.to_ddm() + l = minpoly.gens[0] + + eigenvects = [[field.to_sympy(x) for x in vect] for vect in eigenvects] + + degree = minpoly.degree() + minpoly = minpoly.as_expr() + eigenvals = roots(minpoly, l, **kwargs) + if len(eigenvals) != degree: + eigenvals = [CRootOf(minpoly, l, idx) for idx in range(degree)] + + for eigenvalue in eigenvals: + new_eigenvects = [ + Matrix([x.subs(l, eigenvalue) for x in vect]) + for vect in eigenvects] + result.append((eigenvalue, multiplicity, new_eigenvects)) + + return result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e5a4195c66aceed2d5ac1994381d3dec6a64ba --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/exceptions.py @@ -0,0 +1,67 @@ +""" + +Module to define exceptions to be used in sympy.polys.matrices modules and +classes. + +Ideally all exceptions raised in these modules would be defined and documented +here and not e.g. imported from matrices. Also ideally generic exceptions like +ValueError/TypeError would not be raised anywhere. + +""" + + +class DMError(Exception): + """Base class for errors raised by DomainMatrix""" + pass + + +class DMBadInputError(DMError): + """list of lists is inconsistent with shape""" + pass + + +class DMDomainError(DMError): + """domains do not match""" + pass + + +class DMNotAField(DMDomainError): + """domain is not a field""" + pass + + +class DMFormatError(DMError): + """mixed dense/sparse not supported""" + pass + + +class DMNonInvertibleMatrixError(DMError): + """The matrix in not invertible""" + pass + + +class DMRankError(DMError): + """matrix does not have expected rank""" + pass + + +class DMShapeError(DMError): + """shapes are inconsistent""" + pass + + +class DMNonSquareMatrixError(DMShapeError): + """The matrix is not square""" + pass + + +class DMValueError(DMError): + """The value passed is invalid""" + pass + + +__all__ = [ + 'DMError', 'DMBadInputError', 'DMDomainError', 'DMFormatError', + 'DMRankError', 'DMShapeError', 'DMNotAField', + 'DMNonInvertibleMatrixError', 'DMNonSquareMatrixError', 'DMValueError' +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/linsolve.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/linsolve.py new file mode 100644 index 0000000000000000000000000000000000000000..af74058d859b744cf8fe1059ddb7c775fece79c7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/linsolve.py @@ -0,0 +1,230 @@ +# +# sympy.polys.matrices.linsolve module +# +# This module defines the _linsolve function which is the internal workhorse +# used by linsolve. This computes the solution of a system of linear equations +# using the SDM sparse matrix implementation in sympy.polys.matrices.sdm. This +# is a replacement for solve_lin_sys in sympy.polys.solvers which is +# inefficient for large sparse systems due to the use of a PolyRing with many +# generators: +# +# https://github.com/sympy/sympy/issues/20857 +# +# The implementation of _linsolve here handles: +# +# - Extracting the coefficients from the Expr/Eq input equations. +# - Constructing a domain and converting the coefficients to +# that domain. +# - Using the SDM.rref, SDM.nullspace etc methods to generate the full +# solution working with arithmetic only in the domain of the coefficients. +# +# The routines here are particularly designed to be efficient for large sparse +# systems of linear equations although as well as dense systems. It is +# possible that for some small dense systems solve_lin_sys which uses the +# dense matrix implementation DDM will be more efficient. With smaller systems +# though the bulk of the time is spent just preprocessing the inputs and the +# relative time spent in rref is too small to be noticeable. +# + +from collections import defaultdict + +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.singleton import S + +from sympy.polys.constructor import construct_domain +from sympy.polys.solvers import PolyNonlinearError + +from .sdm import ( + SDM, + sdm_irref, + sdm_particular_from_rref, + sdm_nullspace_from_rref +) + +from sympy.utilities.misc import filldedent + + +def _linsolve(eqs, syms): + + """Solve a linear system of equations. + + Examples + ======== + + Solve a linear system with a unique solution: + + >>> from sympy import symbols, Eq + >>> from sympy.polys.matrices.linsolve import _linsolve + >>> x, y = symbols('x, y') + >>> eqs = [Eq(x + y, 1), Eq(x - y, 2)] + >>> _linsolve(eqs, [x, y]) + {x: 3/2, y: -1/2} + + In the case of underdetermined systems the solution will be expressed in + terms of the unknown symbols that are unconstrained: + + >>> _linsolve([Eq(x + y, 0)], [x, y]) + {x: -y, y: y} + + """ + # Number of unknowns (columns in the non-augmented matrix) + nsyms = len(syms) + + # Convert to sparse augmented matrix (len(eqs) x (nsyms+1)) + eqsdict, const = _linear_eq_to_dict(eqs, syms) + Aaug = sympy_dict_to_dm(eqsdict, const, syms) + K = Aaug.domain + + # sdm_irref has issues with float matrices. This uses the ddm_rref() + # function. When sdm_rref() can handle float matrices reasonably this + # should be removed... + if K.is_RealField or K.is_ComplexField: + Aaug = Aaug.to_ddm().rref()[0].to_sdm() + + # Compute reduced-row echelon form (RREF) + Arref, pivots, nzcols = sdm_irref(Aaug) + + # No solution: + if pivots and pivots[-1] == nsyms: + return None + + # Particular solution for non-homogeneous system: + P = sdm_particular_from_rref(Arref, nsyms+1, pivots) + + # Nullspace - general solution to homogeneous system + # Note: using nsyms not nsyms+1 to ignore last column + V, nonpivots = sdm_nullspace_from_rref(Arref, K.one, nsyms, pivots, nzcols) + + # Collect together terms from particular and nullspace: + sol = defaultdict(list) + for i, v in P.items(): + sol[syms[i]].append(K.to_sympy(v)) + for npi, Vi in zip(nonpivots, V): + sym = syms[npi] + for i, v in Vi.items(): + sol[syms[i]].append(sym * K.to_sympy(v)) + + # Use a single call to Add for each term: + sol = {s: Add(*terms) for s, terms in sol.items()} + + # Fill in the zeros: + zero = S.Zero + for s in set(syms) - set(sol): + sol[s] = zero + + # All done! + return sol + + +def sympy_dict_to_dm(eqs_coeffs, eqs_rhs, syms): + """Convert a system of dict equations to a sparse augmented matrix""" + elems = set(eqs_rhs).union(*(e.values() for e in eqs_coeffs)) + K, elems_K = construct_domain(elems, field=True, extension=True) + elem_map = dict(zip(elems, elems_K)) + neqs = len(eqs_coeffs) + nsyms = len(syms) + sym2index = dict(zip(syms, range(nsyms))) + eqsdict = [] + for eq, rhs in zip(eqs_coeffs, eqs_rhs): + eqdict = {sym2index[s]: elem_map[c] for s, c in eq.items()} + if rhs: + eqdict[nsyms] = -elem_map[rhs] + if eqdict: + eqsdict.append(eqdict) + sdm_aug = SDM(enumerate(eqsdict), (neqs, nsyms + 1), K) + return sdm_aug + + +def _linear_eq_to_dict(eqs, syms): + """Convert a system Expr/Eq equations into dict form, returning + the coefficient dictionaries and a list of syms-independent terms + from each expression in ``eqs```. + + Examples + ======== + + >>> from sympy.polys.matrices.linsolve import _linear_eq_to_dict + >>> from sympy.abc import x + >>> _linear_eq_to_dict([2*x + 3], {x}) + ([{x: 2}], [3]) + """ + coeffs = [] + ind = [] + symset = set(syms) + for e in eqs: + if e.is_Equality: + coeff, terms = _lin_eq2dict(e.lhs, symset) + cR, tR = _lin_eq2dict(e.rhs, symset) + # there were no nonlinear errors so now + # cancellation is allowed + coeff -= cR + for k, v in tR.items(): + if k in terms: + terms[k] -= v + else: + terms[k] = -v + # don't store coefficients of 0, however + terms = {k: v for k, v in terms.items() if v} + c, d = coeff, terms + else: + c, d = _lin_eq2dict(e, symset) + coeffs.append(d) + ind.append(c) + return coeffs, ind + + +def _lin_eq2dict(a, symset): + """return (c, d) where c is the sym-independent part of ``a`` and + ``d`` is an efficiently calculated dictionary mapping symbols to + their coefficients. A PolyNonlinearError is raised if non-linearity + is detected. + + The values in the dictionary will be non-zero. + + Examples + ======== + + >>> from sympy.polys.matrices.linsolve import _lin_eq2dict + >>> from sympy.abc import x, y + >>> _lin_eq2dict(x + 2*y + 3, {x, y}) + (3, {x: 1, y: 2}) + """ + if a in symset: + return S.Zero, {a: S.One} + elif a.is_Add: + terms_list = defaultdict(list) + coeff_list = [] + for ai in a.args: + ci, ti = _lin_eq2dict(ai, symset) + coeff_list.append(ci) + for mij, cij in ti.items(): + terms_list[mij].append(cij) + coeff = Add(*coeff_list) + terms = {sym: Add(*coeffs) for sym, coeffs in terms_list.items()} + return coeff, terms + elif a.is_Mul: + terms = terms_coeff = None + coeff_list = [] + for ai in a.args: + ci, ti = _lin_eq2dict(ai, symset) + if not ti: + coeff_list.append(ci) + elif terms is None: + terms = ti + terms_coeff = ci + else: + # since ti is not null and we already have + # a term, this is a cross term + raise PolyNonlinearError(filldedent(''' + nonlinear cross-term: %s''' % a)) + coeff = Mul._from_args(coeff_list) + if terms is None: + return coeff, {} + else: + terms = {sym: coeff * c for sym, c in terms.items()} + return coeff * terms_coeff, terms + elif not a.has_xfree(symset): + return a, {} + else: + raise PolyNonlinearError('nonlinear term: %s' % a) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/lll.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/lll.py new file mode 100644 index 0000000000000000000000000000000000000000..f33f91d92c5e20f89f302991e494a6a5b9fa4b2e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/lll.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +from math import floor as mfloor + +from sympy.polys.domains import ZZ, QQ +from sympy.polys.matrices.exceptions import DMRankError, DMShapeError, DMValueError, DMDomainError + + +def _ddm_lll(x, delta=QQ(3, 4), return_transform=False): + if QQ(1, 4) >= delta or delta >= QQ(1, 1): + raise DMValueError("delta must lie in range (0.25, 1)") + if x.shape[0] > x.shape[1]: + raise DMShapeError("input matrix must have shape (m, n) with m <= n") + if x.domain != ZZ: + raise DMDomainError("input matrix domain must be ZZ") + m = x.shape[0] + n = x.shape[1] + k = 1 + y = x.copy() + y_star = x.zeros((m, n), QQ) + mu = x.zeros((m, m), QQ) + g_star = [QQ(0, 1) for _ in range(m)] + half = QQ(1, 2) + T = x.eye(m, ZZ) if return_transform else None + linear_dependent_error = "input matrix contains linearly dependent rows" + + def closest_integer(x): + return ZZ(mfloor(x + half)) + + def lovasz_condition(k: int) -> bool: + return g_star[k] >= ((delta - mu[k][k - 1] ** 2) * g_star[k - 1]) + + def mu_small(k: int, j: int) -> bool: + return abs(mu[k][j]) <= half + + def dot_rows(x, y, rows: tuple[int, int]): + return sum(x[rows[0]][z] * y[rows[1]][z] for z in range(x.shape[1])) + + def reduce_row(T, mu, y, rows: tuple[int, int]): + r = closest_integer(mu[rows[0]][rows[1]]) + y[rows[0]] = [y[rows[0]][z] - r * y[rows[1]][z] for z in range(n)] + mu[rows[0]][:rows[1]] = [mu[rows[0]][z] - r * mu[rows[1]][z] for z in range(rows[1])] + mu[rows[0]][rows[1]] -= r + if return_transform: + T[rows[0]] = [T[rows[0]][z] - r * T[rows[1]][z] for z in range(m)] + + for i in range(m): + y_star[i] = [QQ.convert_from(z, ZZ) for z in y[i]] + for j in range(i): + row_dot = dot_rows(y, y_star, (i, j)) + try: + mu[i][j] = row_dot / g_star[j] + except ZeroDivisionError: + raise DMRankError(linear_dependent_error) + y_star[i] = [y_star[i][z] - mu[i][j] * y_star[j][z] for z in range(n)] + g_star[i] = dot_rows(y_star, y_star, (i, i)) + while k < m: + if not mu_small(k, k - 1): + reduce_row(T, mu, y, (k, k - 1)) + if lovasz_condition(k): + for l in range(k - 2, -1, -1): + if not mu_small(k, l): + reduce_row(T, mu, y, (k, l)) + k += 1 + else: + nu = mu[k][k - 1] + alpha = g_star[k] + nu ** 2 * g_star[k - 1] + try: + beta = g_star[k - 1] / alpha + except ZeroDivisionError: + raise DMRankError(linear_dependent_error) + mu[k][k - 1] = nu * beta + g_star[k] = g_star[k] * beta + g_star[k - 1] = alpha + y[k], y[k - 1] = y[k - 1], y[k] + mu[k][:k - 1], mu[k - 1][:k - 1] = mu[k - 1][:k - 1], mu[k][:k - 1] + for i in range(k + 1, m): + xi = mu[i][k] + mu[i][k] = mu[i][k - 1] - nu * xi + mu[i][k - 1] = mu[k][k - 1] * mu[i][k] + xi + if return_transform: + T[k], T[k - 1] = T[k - 1], T[k] + k = max(k - 1, 1) + assert all(lovasz_condition(i) for i in range(1, m)) + assert all(mu_small(i, j) for i in range(m) for j in range(i)) + return y, T + + +def ddm_lll(x, delta=QQ(3, 4)): + return _ddm_lll(x, delta=delta, return_transform=False)[0] + + +def ddm_lll_transform(x, delta=QQ(3, 4)): + return _ddm_lll(x, delta=delta, return_transform=True) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/normalforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/normalforms.py new file mode 100644 index 0000000000000000000000000000000000000000..506a68b6946acbeb235eed7650246104da265b78 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/normalforms.py @@ -0,0 +1,540 @@ +'''Functions returning normal forms of matrices''' + +from collections import defaultdict + +from .domainmatrix import DomainMatrix +from .exceptions import DMDomainError, DMShapeError +from sympy.ntheory.modular import symmetric_residue +from sympy.polys.domains import QQ, ZZ + + +# TODO (future work): +# There are faster algorithms for Smith and Hermite normal forms, which +# we should implement. See e.g. the Kannan-Bachem algorithm: +# + + +def smith_normal_form(m): + ''' + Return the Smith Normal Form of a matrix `m` over the ring `domain`. + This will only work if the ring is a principal ideal domain. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy.polys.matrices.normalforms import smith_normal_form + >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)], + ... [ZZ(3), ZZ(9), ZZ(6)], + ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ) + >>> print(smith_normal_form(m).to_Matrix()) + Matrix([[1, 0, 0], [0, 10, 0], [0, 0, 30]]) + + ''' + invs = invariant_factors(m) + smf = DomainMatrix.diag(invs, m.domain, m.shape) + return smf + + +def is_smith_normal_form(m): + ''' + Checks that the matrix is in Smith Normal Form + ''' + domain = m.domain + shape = m.shape + zero = domain.zero + m = m.to_list() + + for i in range(shape[0]): + for j in range(shape[1]): + if i == j: + continue + if not m[i][j] == zero: + return False + + upper = min(shape[0], shape[1]) + for i in range(1, upper): + if m[i-1][i-1] == zero: + if m[i][i] != zero: + return False + else: + r = domain.div(m[i][i], m[i-1][i-1])[1] + if r != zero: + return False + + return True + + +def add_columns(m, i, j, a, b, c, d): + # replace m[:, i] by a*m[:, i] + b*m[:, j] + # and m[:, j] by c*m[:, i] + d*m[:, j] + for k in range(len(m)): + e = m[k][i] + m[k][i] = a*e + b*m[k][j] + m[k][j] = c*e + d*m[k][j] + + +def invariant_factors(m): + ''' + Return the tuple of abelian invariants for a matrix `m` + (as in the Smith-Normal form) + + References + ========== + + [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm + [2] https://web.archive.org/web/20200331143852/https://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf + + ''' + domain = m.domain + shape = m.shape + m = m.to_list() + return _smith_normal_decomp(m, domain, shape=shape, full=False) + + +def smith_normal_decomp(m): + ''' + Return the Smith-Normal form decomposition of matrix `m`. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy.polys.matrices.normalforms import smith_normal_decomp + >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)], + ... [ZZ(3), ZZ(9), ZZ(6)], + ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ) + >>> a, s, t = smith_normal_decomp(m) + >>> assert a == s * m * t + ''' + domain = m.domain + rows, cols = shape = m.shape + m = m.to_list() + + invs, s, t = _smith_normal_decomp(m, domain, shape=shape, full=True) + smf = DomainMatrix.diag(invs, domain, shape).to_dense() + + s = DomainMatrix(s, domain=domain, shape=(rows, rows)) + t = DomainMatrix(t, domain=domain, shape=(cols, cols)) + return smf, s, t + + +def _smith_normal_decomp(m, domain, shape, full): + ''' + Return the tuple of abelian invariants for a matrix `m` + (as in the Smith-Normal form). If `full=True` then invertible matrices + ``s, t`` such that the product ``s, m, t`` is the Smith Normal Form + are also returned. + ''' + if not domain.is_PID: + msg = f"The matrix entries must be over a principal ideal domain, but got {domain}" + raise ValueError(msg) + + rows, cols = shape + zero = domain.zero + one = domain.one + + def eye(n): + return [[one if i == j else zero for i in range(n)] for j in range(n)] + + if 0 in shape: + if full: + return (), eye(rows), eye(cols) + else: + return () + + if full: + s = eye(rows) + t = eye(cols) + + def add_rows(m, i, j, a, b, c, d): + # replace m[i, :] by a*m[i, :] + b*m[j, :] + # and m[j, :] by c*m[i, :] + d*m[j, :] + for k in range(len(m[0])): + e = m[i][k] + m[i][k] = a*e + b*m[j][k] + m[j][k] = c*e + d*m[j][k] + + def clear_column(): + # make m[1:, 0] zero by row and column operations + pivot = m[0][0] + for j in range(1, rows): + if m[j][0] == zero: + continue + d, r = domain.div(m[j][0], pivot) + if r == zero: + add_rows(m, 0, j, 1, 0, -d, 1) + if full: + add_rows(s, 0, j, 1, 0, -d, 1) + else: + a, b, g = domain.gcdex(pivot, m[j][0]) + d_0 = domain.exquo(m[j][0], g) + d_j = domain.exquo(pivot, g) + add_rows(m, 0, j, a, b, d_0, -d_j) + if full: + add_rows(s, 0, j, a, b, d_0, -d_j) + pivot = g + + def clear_row(): + # make m[0, 1:] zero by row and column operations + pivot = m[0][0] + for j in range(1, cols): + if m[0][j] == zero: + continue + d, r = domain.div(m[0][j], pivot) + if r == zero: + add_columns(m, 0, j, 1, 0, -d, 1) + if full: + add_columns(t, 0, j, 1, 0, -d, 1) + else: + a, b, g = domain.gcdex(pivot, m[0][j]) + d_0 = domain.exquo(m[0][j], g) + d_j = domain.exquo(pivot, g) + add_columns(m, 0, j, a, b, d_0, -d_j) + if full: + add_columns(t, 0, j, a, b, d_0, -d_j) + pivot = g + + # permute the rows and columns until m[0,0] is non-zero if possible + ind = [i for i in range(rows) if m[i][0] != zero] + if ind and ind[0] != zero: + m[0], m[ind[0]] = m[ind[0]], m[0] + if full: + s[0], s[ind[0]] = s[ind[0]], s[0] + else: + ind = [j for j in range(cols) if m[0][j] != zero] + if ind and ind[0] != zero: + for row in m: + row[0], row[ind[0]] = row[ind[0]], row[0] + if full: + for row in t: + row[0], row[ind[0]] = row[ind[0]], row[0] + + # make the first row and column except m[0,0] zero + while (any(m[0][i] != zero for i in range(1,cols)) or + any(m[i][0] != zero for i in range(1,rows))): + clear_column() + clear_row() + + def to_domain_matrix(m): + return DomainMatrix(m, shape=(len(m), len(m[0])), domain=domain) + + if m[0][0] != 0: + c = domain.canonical_unit(m[0][0]) + if domain.is_Field: + c = 1 / m[0][0] + if c != domain.one: + m[0][0] *= c + if full: + s[0] = [elem * c for elem in s[0]] + + if 1 in shape: + invs = () + else: + lower_right = [r[1:] for r in m[1:]] + ret = _smith_normal_decomp(lower_right, domain, + shape=(rows - 1, cols - 1), full=full) + if full: + invs, s_small, t_small = ret + s2 = [[1] + [0]*(rows-1)] + [[0] + row for row in s_small] + t2 = [[1] + [0]*(cols-1)] + [[0] + row for row in t_small] + s, s2, t, t2 = list(map(to_domain_matrix, [s, s2, t, t2])) + s = s2 * s + t = t * t2 + s = s.to_list() + t = t.to_list() + else: + invs = ret + + if m[0][0]: + result = [m[0][0]] + result.extend(invs) + # in case m[0] doesn't divide the invariants of the rest of the matrix + for i in range(len(result)-1): + a, b = result[i], result[i+1] + if b and domain.div(b, a)[1] != zero: + if full: + x, y, d = domain.gcdex(a, b) + else: + d = domain.gcd(a, b) + + alpha = domain.div(a, d)[0] + if full: + beta = domain.div(b, d)[0] + add_rows(s, i, i + 1, 1, 0, x, 1) + add_columns(t, i, i + 1, 1, y, 0, 1) + add_rows(s, i, i + 1, 1, -alpha, 0, 1) + add_columns(t, i, i + 1, 1, 0, -beta, 1) + add_rows(s, i, i + 1, 0, 1, -1, 0) + + result[i+1] = b * alpha + result[i] = d + else: + break + else: + if full: + if rows > 1: + s = s[1:] + [s[0]] + if cols > 1: + t = [row[1:] + [row[0]] for row in t] + result = invs + (m[0][0],) + + if full: + return tuple(result), s, t + else: + return tuple(result) + + +def _gcdex(a, b): + r""" + This supports the functions that compute Hermite Normal Form. + + Explanation + =========== + + Let x, y be the coefficients returned by the extended Euclidean + Algorithm, so that x*a + y*b = g. In the algorithms for computing HNF, + it is critical that x, y not only satisfy the condition of being small + in magnitude -- namely that |x| <= |b|/g, |y| <- |a|/g -- but also that + y == 0 when a | b. + + """ + x, y, g = ZZ.gcdex(a, b) + if a != 0 and b % a == 0: + y = 0 + x = -1 if a < 0 else 1 + return x, y, g + + +def _hermite_normal_form(A): + r""" + Compute the Hermite Normal Form of DomainMatrix *A* over :ref:`ZZ`. + + Parameters + ========== + + A : :py:class:`~.DomainMatrix` over domain :ref:`ZZ`. + + Returns + ======= + + :py:class:`~.DomainMatrix` + The HNF of matrix *A*. + + Raises + ====== + + DMDomainError + If the domain of the matrix is not :ref:`ZZ`. + + References + ========== + + .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* + (See Algorithm 2.4.5.) + + """ + if not A.domain.is_ZZ: + raise DMDomainError('Matrix must be over domain ZZ.') + # We work one row at a time, starting from the bottom row, and working our + # way up. + m, n = A.shape + A = A.to_ddm().copy() + # Our goal is to put pivot entries in the rightmost columns. + # Invariant: Before processing each row, k should be the index of the + # leftmost column in which we have so far put a pivot. + k = n + for i in range(m - 1, -1, -1): + if k == 0: + # This case can arise when n < m and we've already found n pivots. + # We don't need to consider any more rows, because this is already + # the maximum possible number of pivots. + break + k -= 1 + # k now points to the column in which we want to put a pivot. + # We want zeros in all entries to the left of the pivot column. + for j in range(k - 1, -1, -1): + if A[i][j] != 0: + # Replace cols j, k by lin combs of these cols such that, in row i, + # col j has 0, while col k has the gcd of their row i entries. Note + # that this ensures a nonzero entry in col k. + u, v, d = _gcdex(A[i][k], A[i][j]) + r, s = A[i][k] // d, A[i][j] // d + add_columns(A, k, j, u, v, -s, r) + b = A[i][k] + # Do not want the pivot entry to be negative. + if b < 0: + add_columns(A, k, k, -1, 0, -1, 0) + b = -b + # The pivot entry will be 0 iff the row was 0 from the pivot col all the + # way to the left. In this case, we are still working on the same pivot + # col for the next row. Therefore: + if b == 0: + k += 1 + # If the pivot entry is nonzero, then we want to reduce all entries to its + # right in the sense of the division algorithm, i.e. make them all remainders + # w.r.t. the pivot as divisor. + else: + for j in range(k + 1, n): + q = A[i][j] // b + add_columns(A, j, k, 1, -q, 0, 1) + # Finally, the HNF consists of those columns of A in which we succeeded in making + # a nonzero pivot. + return DomainMatrix.from_rep(A.to_dfm_or_ddm())[:, k:] + + +def _hermite_normal_form_modulo_D(A, D): + r""" + Perform the mod *D* Hermite Normal Form reduction algorithm on + :py:class:`~.DomainMatrix` *A*. + + Explanation + =========== + + If *A* is an $m \times n$ matrix of rank $m$, having Hermite Normal Form + $W$, and if *D* is any positive integer known in advance to be a multiple + of $\det(W)$, then the HNF of *A* can be computed by an algorithm that + works mod *D* in order to prevent coefficient explosion. + + Parameters + ========== + + A : :py:class:`~.DomainMatrix` over :ref:`ZZ` + $m \times n$ matrix, having rank $m$. + D : :ref:`ZZ` + Positive integer, known to be a multiple of the determinant of the + HNF of *A*. + + Returns + ======= + + :py:class:`~.DomainMatrix` + The HNF of matrix *A*. + + Raises + ====== + + DMDomainError + If the domain of the matrix is not :ref:`ZZ`, or + if *D* is given but is not in :ref:`ZZ`. + + DMShapeError + If the matrix has more rows than columns. + + References + ========== + + .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* + (See Algorithm 2.4.8.) + + """ + if not A.domain.is_ZZ: + raise DMDomainError('Matrix must be over domain ZZ.') + if not ZZ.of_type(D) or D < 1: + raise DMDomainError('Modulus D must be positive element of domain ZZ.') + + def add_columns_mod_R(m, R, i, j, a, b, c, d): + # replace m[:, i] by (a*m[:, i] + b*m[:, j]) % R + # and m[:, j] by (c*m[:, i] + d*m[:, j]) % R + for k in range(len(m)): + e = m[k][i] + m[k][i] = symmetric_residue((a * e + b * m[k][j]) % R, R) + m[k][j] = symmetric_residue((c * e + d * m[k][j]) % R, R) + + W = defaultdict(dict) + + m, n = A.shape + if n < m: + raise DMShapeError('Matrix must have at least as many columns as rows.') + A = A.to_list() + k = n + R = D + for i in range(m - 1, -1, -1): + k -= 1 + for j in range(k - 1, -1, -1): + if A[i][j] != 0: + u, v, d = _gcdex(A[i][k], A[i][j]) + r, s = A[i][k] // d, A[i][j] // d + add_columns_mod_R(A, R, k, j, u, v, -s, r) + b = A[i][k] + if b == 0: + A[i][k] = b = R + u, v, d = _gcdex(b, R) + for ii in range(m): + W[ii][i] = u*A[ii][k] % R + if W[i][i] == 0: + W[i][i] = R + for j in range(i + 1, m): + q = W[i][j] // W[i][i] + add_columns(W, j, i, 1, -q, 0, 1) + R //= d + return DomainMatrix(W, (m, m), ZZ).to_dense() + + +def hermite_normal_form(A, *, D=None, check_rank=False): + r""" + Compute the Hermite Normal Form of :py:class:`~.DomainMatrix` *A* over + :ref:`ZZ`. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices import DomainMatrix + >>> from sympy.polys.matrices.normalforms import hermite_normal_form + >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)], + ... [ZZ(3), ZZ(9), ZZ(6)], + ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ) + >>> print(hermite_normal_form(m).to_Matrix()) + Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]]) + + Parameters + ========== + + A : $m \times n$ ``DomainMatrix`` over :ref:`ZZ`. + + D : :ref:`ZZ`, optional + Let $W$ be the HNF of *A*. If known in advance, a positive integer *D* + being any multiple of $\det(W)$ may be provided. In this case, if *A* + also has rank $m$, then we may use an alternative algorithm that works + mod *D* in order to prevent coefficient explosion. + + check_rank : boolean, optional (default=False) + The basic assumption is that, if you pass a value for *D*, then + you already believe that *A* has rank $m$, so we do not waste time + checking it for you. If you do want this to be checked (and the + ordinary, non-modulo *D* algorithm to be used if the check fails), then + set *check_rank* to ``True``. + + Returns + ======= + + :py:class:`~.DomainMatrix` + The HNF of matrix *A*. + + Raises + ====== + + DMDomainError + If the domain of the matrix is not :ref:`ZZ`, or + if *D* is given but is not in :ref:`ZZ`. + + DMShapeError + If the mod *D* algorithm is used but the matrix has more rows than + columns. + + References + ========== + + .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* + (See Algorithms 2.4.5 and 2.4.8.) + + """ + if not A.domain.is_ZZ: + raise DMDomainError('Matrix must be over domain ZZ.') + if D is not None and (not check_rank or A.convert_to(QQ).rank() == A.shape[0]): + return _hermite_normal_form_modulo_D(A, D) + else: + return _hermite_normal_form(A) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/rref.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/rref.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a71b04971e8dc8ecac5cc2691f98ba68e35d45 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/rref.py @@ -0,0 +1,422 @@ +# Algorithms for computing the reduced row echelon form of a matrix. +# +# We need to choose carefully which algorithms to use depending on the domain, +# shape, and sparsity of the matrix as well as things like the bit count in the +# case of ZZ or QQ. This is important because the algorithms have different +# performance characteristics in the extremes of dense vs sparse. +# +# In all cases we use the sparse implementations but we need to choose between +# Gauss-Jordan elimination with division and fraction-free Gauss-Jordan +# elimination. For very sparse matrices over ZZ with low bit counts it is +# asymptotically faster to use Gauss-Jordan elimination with division. For +# dense matrices with high bit counts it is asymptotically faster to use +# fraction-free Gauss-Jordan. +# +# The most important thing is to get the extreme cases right because it can +# make a big difference. In between the extremes though we have to make a +# choice and here we use empirically determined thresholds based on timings +# with random sparse matrices. +# +# In the case of QQ we have to consider the denominators as well. If the +# denominators are small then it is faster to clear them and use fraction-free +# Gauss-Jordan over ZZ. If the denominators are large then it is faster to use +# Gauss-Jordan elimination with division over QQ. +# +# Timings for the various algorithms can be found at +# +# https://github.com/sympy/sympy/issues/25410 +# https://github.com/sympy/sympy/pull/25443 + +from sympy.polys.domains import ZZ + +from sympy.polys.matrices.sdm import SDM, sdm_irref, sdm_rref_den +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.dense import ddm_irref, ddm_irref_den + + +def _dm_rref(M, *, method='auto'): + """ + Compute the reduced row echelon form of a ``DomainMatrix``. + + This function is the implementation of :meth:`DomainMatrix.rref`. + + Chooses the best algorithm depending on the domain, shape, and sparsity of + the matrix as well as things like the bit count in the case of :ref:`ZZ` or + :ref:`QQ`. The result is returned over the field associated with the domain + of the Matrix. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.rref + The ``DomainMatrix`` method that calls this function. + sympy.polys.matrices.rref._dm_rref_den + Alternative function for computing RREF with denominator. + """ + method, use_fmt = _dm_rref_choose_method(M, method, denominator=False) + + M, old_fmt = _dm_to_fmt(M, use_fmt) + + if method == 'GJ': + # Use Gauss-Jordan with division over the associated field. + Mf = _to_field(M) + M_rref, pivots = _dm_rref_GJ(Mf) + + elif method == 'FF': + # Use fraction-free GJ over the current domain. + M_rref_f, den, pivots = _dm_rref_den_FF(M) + M_rref = _to_field(M_rref_f) / den + + elif method == 'CD': + # Clear denominators and use fraction-free GJ in the associated ring. + _, Mr = M.clear_denoms_rowwise(convert=True) + M_rref_f, den, pivots = _dm_rref_den_FF(Mr) + M_rref = _to_field(M_rref_f) / den + + else: + raise ValueError(f"Unknown method for rref: {method}") + + M_rref, _ = _dm_to_fmt(M_rref, old_fmt) + + # Invariants: + # - M_rref is in the same format (sparse or dense) as the input matrix. + # - M_rref is in the associated field domain and any denominator was + # divided in (so is implicitly 1 now). + + return M_rref, pivots + + +def _dm_rref_den(M, *, keep_domain=True, method='auto'): + """ + Compute the reduced row echelon form of a ``DomainMatrix`` with denominator. + + This function is the implementation of :meth:`DomainMatrix.rref_den`. + + Chooses the best algorithm depending on the domain, shape, and sparsity of + the matrix as well as things like the bit count in the case of :ref:`ZZ` or + :ref:`QQ`. The result is returned over the same domain as the input matrix + unless ``keep_domain=False`` in which case the result might be over an + associated ring or field domain. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den + The ``DomainMatrix`` method that calls this function. + sympy.polys.matrices.rref._dm_rref + Alternative function for computing RREF without denominator. + """ + method, use_fmt = _dm_rref_choose_method(M, method, denominator=True) + + M, old_fmt = _dm_to_fmt(M, use_fmt) + + if method == 'FF': + # Use fraction-free GJ over the current domain. + M_rref, den, pivots = _dm_rref_den_FF(M) + + elif method == 'GJ': + # Use Gauss-Jordan with division over the associated field. + M_rref_f, pivots = _dm_rref_GJ(_to_field(M)) + + # Convert back to the ring? + if keep_domain and M_rref_f.domain != M.domain: + _, M_rref = M_rref_f.clear_denoms(convert=True) + + if pivots: + den = M_rref[0, pivots[0]].element + else: + den = M_rref.domain.one + else: + # Possibly an associated field + M_rref = M_rref_f + den = M_rref.domain.one + + elif method == 'CD': + # Clear denominators and use fraction-free GJ in the associated ring. + _, Mr = M.clear_denoms_rowwise(convert=True) + + M_rref_r, den, pivots = _dm_rref_den_FF(Mr) + + if keep_domain and M_rref_r.domain != M.domain: + # Convert back to the field + M_rref = _to_field(M_rref_r) / den + den = M.domain.one + else: + # Possibly an associated ring + M_rref = M_rref_r + + if pivots: + den = M_rref[0, pivots[0]].element + else: + den = M_rref.domain.one + else: + raise ValueError(f"Unknown method for rref: {method}") + + M_rref, _ = _dm_to_fmt(M_rref, old_fmt) + + # Invariants: + # - M_rref is in the same format (sparse or dense) as the input matrix. + # - If keep_domain=True then M_rref and den are in the same domain as the + # input matrix + # - If keep_domain=False then M_rref might be in an associated ring or + # field domain but den is always in the same domain as M_rref. + + return M_rref, den, pivots + + +def _dm_to_fmt(M, fmt): + """Convert a matrix to the given format and return the old format.""" + old_fmt = M.rep.fmt + if old_fmt == fmt: + pass + elif fmt == 'dense': + M = M.to_dense() + elif fmt == 'sparse': + M = M.to_sparse() + else: + raise ValueError(f'Unknown format: {fmt}') # pragma: no cover + return M, old_fmt + + +# These are the four basic implementations that we want to choose between: + + +def _dm_rref_GJ(M): + """Compute RREF using Gauss-Jordan elimination with division.""" + if M.rep.fmt == 'sparse': + return _dm_rref_GJ_sparse(M) + else: + return _dm_rref_GJ_dense(M) + + +def _dm_rref_den_FF(M): + """Compute RREF using fraction-free Gauss-Jordan elimination.""" + if M.rep.fmt == 'sparse': + return _dm_rref_den_FF_sparse(M) + else: + return _dm_rref_den_FF_dense(M) + + +def _dm_rref_GJ_sparse(M): + """Compute RREF using sparse Gauss-Jordan elimination with division.""" + M_rref_d, pivots, _ = sdm_irref(M.rep) + M_rref_sdm = SDM(M_rref_d, M.shape, M.domain) + pivots = tuple(pivots) + return M.from_rep(M_rref_sdm), pivots + + +def _dm_rref_GJ_dense(M): + """Compute RREF using dense Gauss-Jordan elimination with division.""" + partial_pivot = M.domain.is_RR or M.domain.is_CC + ddm = M.rep.to_ddm().copy() + pivots = ddm_irref(ddm, _partial_pivot=partial_pivot) + M_rref_ddm = DDM(ddm, M.shape, M.domain) + pivots = tuple(pivots) + return M.from_rep(M_rref_ddm.to_dfm_or_ddm()), pivots + + +def _dm_rref_den_FF_sparse(M): + """Compute RREF using sparse fraction-free Gauss-Jordan elimination.""" + M_rref_d, den, pivots = sdm_rref_den(M.rep, M.domain) + M_rref_sdm = SDM(M_rref_d, M.shape, M.domain) + pivots = tuple(pivots) + return M.from_rep(M_rref_sdm), den, pivots + + +def _dm_rref_den_FF_dense(M): + """Compute RREF using sparse fraction-free Gauss-Jordan elimination.""" + ddm = M.rep.to_ddm().copy() + den, pivots = ddm_irref_den(ddm, M.domain) + M_rref_ddm = DDM(ddm, M.shape, M.domain) + pivots = tuple(pivots) + return M.from_rep(M_rref_ddm.to_dfm_or_ddm()), den, pivots + + +def _dm_rref_choose_method(M, method, *, denominator=False): + """Choose the fastest method for computing RREF for M.""" + + if method != 'auto': + if method.endswith('_dense'): + method = method[:-len('_dense')] + use_fmt = 'dense' + else: + use_fmt = 'sparse' + + else: + # The sparse implementations are always faster + use_fmt = 'sparse' + + K = M.domain + + if K.is_ZZ: + method = _dm_rref_choose_method_ZZ(M, denominator=denominator) + elif K.is_QQ: + method = _dm_rref_choose_method_QQ(M, denominator=denominator) + elif K.is_RR or K.is_CC: + # TODO: Add partial pivot support to the sparse implementations. + method = 'GJ' + use_fmt = 'dense' + elif K.is_EX and M.rep.fmt == 'dense' and not denominator: + # Do not switch to the sparse implementation for EX because the + # domain does not have proper canonicalization and the sparse + # implementation gives equivalent but non-identical results over EX + # from performing arithmetic in a different order. Specifically + # test_issue_23718 ends up getting a more complicated expression + # when using the sparse implementation. Probably the best fix for + # this is something else but for now we stick with the dense + # implementation for EX if the matrix is already dense. + method = 'GJ' + use_fmt = 'dense' + else: + # This is definitely suboptimal. More work is needed to determine + # the best method for computing RREF over different domains. + if denominator: + method = 'FF' + else: + method = 'GJ' + + return method, use_fmt + + +def _dm_rref_choose_method_QQ(M, *, denominator=False): + """Choose the fastest method for computing RREF over QQ.""" + # The same sorts of considerations apply here as in the case of ZZ. Here + # though a new more significant consideration is what sort of denominators + # we have and what to do with them so we focus on that. + + # First compute the density. This is the average number of non-zero entries + # per row but only counting rows that have at least one non-zero entry + # since RREF can ignore fully zero rows. + density, _, ncols = _dm_row_density(M) + + # For sparse matrices use Gauss-Jordan elimination over QQ regardless. + if density < min(5, ncols/2): + return 'GJ' + + # Compare the bit-length of the lcm of the denominators to the bit length + # of the numerators. + # + # The threshold here is empirical: we prefer rref over QQ if clearing + # denominators would result in a numerator matrix having 5x the bit size of + # the current numerators. + numers, denoms = _dm_QQ_numers_denoms(M) + numer_bits = max([n.bit_length() for n in numers], default=1) + + denom_lcm = ZZ.one + for d in denoms: + denom_lcm = ZZ.lcm(denom_lcm, d) + if denom_lcm.bit_length() > 5*numer_bits: + return 'GJ' + + # If we get here then the matrix is dense and the lcm of the denominators + # is not too large compared to the numerators. For particularly small + # denominators it is fastest just to clear them and use fraction-free + # Gauss-Jordan over ZZ. With very small denominators this is a little + # faster than using rref_den over QQ but there is an intermediate regime + # where rref_den over QQ is significantly faster. The small denominator + # case is probably very common because small fractions like 1/2 or 1/3 are + # often seen in user inputs. + + if denom_lcm.bit_length() < 50: + return 'CD' + else: + return 'FF' + + +def _dm_rref_choose_method_ZZ(M, *, denominator=False): + """Choose the fastest method for computing RREF over ZZ.""" + # In the extreme of very sparse matrices and low bit counts it is faster to + # use Gauss-Jordan elimination over QQ rather than fraction-free + # Gauss-Jordan over ZZ. In the opposite extreme of dense matrices and high + # bit counts it is faster to use fraction-free Gauss-Jordan over ZZ. These + # two extreme cases need to be handled differently because they lead to + # different asymptotic complexities. In between these two extremes we need + # a threshold for deciding which method to use. This threshold is + # determined empirically by timing the two methods with random matrices. + + # The disadvantage of using empirical timings is that future optimisations + # might change the relative speeds so this can easily become out of date. + # The main thing is to get the asymptotic complexity right for the extreme + # cases though so the precise value of the threshold is hopefully not too + # important. + + # Empirically determined parameter. + PARAM = 10000 + + # First compute the density. This is the average number of non-zero entries + # per row but only counting rows that have at least one non-zero entry + # since RREF can ignore fully zero rows. + density, nrows_nz, ncols = _dm_row_density(M) + + # For small matrices use QQ if more than half the entries are zero. + if nrows_nz < 10: + if density < ncols/2: + return 'GJ' + else: + return 'FF' + + # These are just shortcuts for the formula below. + if density < 5: + return 'GJ' + elif density > 5 + PARAM/nrows_nz: + return 'FF' # pragma: no cover + + # Maximum bitsize of any entry. + elements = _dm_elements(M) + bits = max([e.bit_length() for e in elements], default=1) + + # Wideness parameter. This is 1 for square or tall matrices but >1 for wide + # matrices. + wideness = max(1, 2/3*ncols/nrows_nz) + + max_density = (5 + PARAM/(nrows_nz*bits**2)) * wideness + + if density < max_density: + return 'GJ' + else: + return 'FF' + + +def _dm_row_density(M): + """Density measure for sparse matrices. + + Defines the "density", ``d`` as the average number of non-zero entries per + row except ignoring rows that are fully zero. RREF can ignore fully zero + rows so they are excluded. By definition ``d >= 1`` except that we define + ``d = 0`` for the zero matrix. + + Returns ``(density, nrows_nz, ncols)`` where ``nrows_nz`` counts the number + of nonzero rows and ``ncols`` is the number of columns. + """ + # Uses the SDM dict-of-dicts representation. + ncols = M.shape[1] + rows_nz = M.rep.to_sdm().values() + if not rows_nz: + return 0, 0, ncols + else: + nrows_nz = len(rows_nz) + density = sum(map(len, rows_nz)) / nrows_nz + return density, nrows_nz, ncols + + +def _dm_elements(M): + """Return nonzero elements of a DomainMatrix.""" + elements, _ = M.to_flat_nz() + return elements + + +def _dm_QQ_numers_denoms(Mq): + """Returns the numerators and denominators of a DomainMatrix over QQ.""" + elements = _dm_elements(Mq) + numers = [e.numerator for e in elements] + denoms = [e.denominator for e in elements] + return numers, denoms + + +def _to_field(M): + """Convert a DomainMatrix to a field if possible.""" + K = M.domain + if K.has_assoc_Field: + return M.to_field() + else: + return M diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/sdm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/sdm.py new file mode 100644 index 0000000000000000000000000000000000000000..84558d83b6f58a3a9074d31f1a315ac901cd68da --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/sdm.py @@ -0,0 +1,2197 @@ +""" + +Module for the SDM class. + +""" + +from operator import add, neg, pos, sub, mul +from collections import defaultdict + +from sympy.external.gmpy import GROUND_TYPES +from sympy.utilities.decorator import doctest_depends_on +from sympy.utilities.iterables import _strongly_connected_components + +from .exceptions import DMBadInputError, DMDomainError, DMShapeError + +from sympy.polys.domains import QQ + +from .ddm import DDM + + +if GROUND_TYPES != 'flint': + __doctest_skip__ = ['SDM.to_dfm', 'SDM.to_dfm_or_ddm'] + + +class SDM(dict): + r"""Sparse matrix based on polys domain elements + + This is a dict subclass and is a wrapper for a dict of dicts that supports + basic matrix arithmetic +, -, *, **. + + + In order to create a new :py:class:`~.SDM`, a dict + of dicts mapping non-zero elements to their + corresponding row and column in the matrix is needed. + + We also need to specify the shape and :py:class:`~.Domain` + of our :py:class:`~.SDM` object. + + We declare a 2x2 :py:class:`~.SDM` matrix belonging + to QQ domain as shown below. + The 2x2 Matrix in the example is + + .. math:: + A = \left[\begin{array}{ccc} + 0 & \frac{1}{2} \\ + 0 & 0 \end{array} \right] + + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> elemsdict = {0:{1:QQ(1, 2)}} + >>> A = SDM(elemsdict, (2, 2), QQ) + >>> A + {0: {1: 1/2}} + + We can manipulate :py:class:`~.SDM` the same way + as a Matrix class + + >>> from sympy import ZZ + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ) + >>> A + B + {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}} + + Multiplication + + >>> A*B + {0: {1: 8}, 1: {0: 3}} + >>> A*ZZ(2) + {0: {1: 4}, 1: {0: 2}} + + """ + + fmt = 'sparse' + is_DFM = False + is_DDM = False + + def __init__(self, elemsdict, shape, domain): + super().__init__(elemsdict) + self.shape = self.rows, self.cols = m, n = shape + self.domain = domain + + if not all(0 <= r < m for r in self): + raise DMBadInputError("Row out of range") + if not all(0 <= c < n for row in self.values() for c in row): + raise DMBadInputError("Column out of range") + + def getitem(self, i, j): + try: + return self[i][j] + except KeyError: + m, n = self.shape + if -m <= i < m and -n <= j < n: + try: + return self[i % m][j % n] + except KeyError: + return self.domain.zero + else: + raise IndexError("index out of range") + + def setitem(self, i, j, value): + m, n = self.shape + if not (-m <= i < m and -n <= j < n): + raise IndexError("index out of range") + i, j = i % m, j % n + if value: + try: + self[i][j] = value + except KeyError: + self[i] = {j: value} + else: + rowi = self.get(i, None) + if rowi is not None: + try: + del rowi[j] + except KeyError: + pass + else: + if not rowi: + del self[i] + + def extract_slice(self, slice1, slice2): + m, n = self.shape + ri = range(m)[slice1] + ci = range(n)[slice2] + + sdm = {} + for i, row in self.items(): + if i in ri: + row = {ci.index(j): e for j, e in row.items() if j in ci} + if row: + sdm[ri.index(i)] = row + + return self.new(sdm, (len(ri), len(ci)), self.domain) + + def extract(self, rows, cols): + if not (self and rows and cols): + return self.zeros((len(rows), len(cols)), self.domain) + + m, n = self.shape + if not (-m <= min(rows) <= max(rows) < m): + raise IndexError('Row index out of range') + if not (-n <= min(cols) <= max(cols) < n): + raise IndexError('Column index out of range') + + # rows and cols can contain duplicates e.g. M[[1, 2, 2], [0, 1]] + # Build a map from row/col in self to list of rows/cols in output + rowmap = defaultdict(list) + colmap = defaultdict(list) + for i2, i1 in enumerate(rows): + rowmap[i1 % m].append(i2) + for j2, j1 in enumerate(cols): + colmap[j1 % n].append(j2) + + # Used to efficiently skip zero rows/cols + rowset = set(rowmap) + colset = set(colmap) + + sdm1 = self + sdm2 = {} + for i1 in rowset & sdm1.keys(): + row1 = sdm1[i1] + row2 = {} + for j1 in colset & row1.keys(): + row1_j1 = row1[j1] + for j2 in colmap[j1]: + row2[j2] = row1_j1 + if row2: + for i2 in rowmap[i1]: + sdm2[i2] = row2.copy() + + return self.new(sdm2, (len(rows), len(cols)), self.domain) + + def __str__(self): + rowsstr = [] + for i, row in self.items(): + elemsstr = ', '.join('%s: %s' % (j, elem) for j, elem in row.items()) + rowsstr.append('%s: {%s}' % (i, elemsstr)) + return '{%s}' % ', '.join(rowsstr) + + def __repr__(self): + cls = type(self).__name__ + rows = dict.__repr__(self) + return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain) + + @classmethod + def new(cls, sdm, shape, domain): + """ + + Parameters + ========== + + sdm: A dict of dicts for non-zero elements in SDM + shape: tuple representing dimension of SDM + domain: Represents :py:class:`~.Domain` of SDM + + Returns + ======= + + An :py:class:`~.SDM` object + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> elemsdict = {0:{1: QQ(2)}} + >>> A = SDM.new(elemsdict, (2, 2), QQ) + >>> A + {0: {1: 2}} + + """ + return cls(sdm, shape, domain) + + def copy(A): + """ + Returns the copy of a :py:class:`~.SDM` object + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> elemsdict = {0:{1:QQ(2)}, 1:{}} + >>> A = SDM(elemsdict, (2, 2), QQ) + >>> B = A.copy() + >>> B + {0: {1: 2}, 1: {}} + + """ + Ac = {i: Ai.copy() for i, Ai in A.items()} + return A.new(Ac, A.shape, A.domain) + + @classmethod + def from_list(cls, ddm, shape, domain): + """ + Create :py:class:`~.SDM` object from a list of lists. + + Parameters + ========== + + ddm: + list of lists containing domain elements + shape: + Dimensions of :py:class:`~.SDM` matrix + domain: + Represents :py:class:`~.Domain` of :py:class:`~.SDM` object + + Returns + ======= + + :py:class:`~.SDM` containing elements of ddm + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> ddm = [[QQ(1, 2), QQ(0)], [QQ(0), QQ(3, 4)]] + >>> A = SDM.from_list(ddm, (2, 2), QQ) + >>> A + {0: {0: 1/2}, 1: {1: 3/4}} + + See Also + ======== + + to_list + from_list_flat + from_dok + from_ddm + """ + + m, n = shape + if not (len(ddm) == m and all(len(row) == n for row in ddm)): + raise DMBadInputError("Inconsistent row-list/shape") + getrow = lambda i: {j:ddm[i][j] for j in range(n) if ddm[i][j]} + irows = ((i, getrow(i)) for i in range(m)) + sdm = {i: row for i, row in irows if row} + return cls(sdm, shape, domain) + + @classmethod + def from_ddm(cls, ddm): + """ + Create :py:class:`~.SDM` from a :py:class:`~.DDM`. + + Examples + ======== + + >>> from sympy.polys.matrices.ddm import DDM + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> ddm = DDM( [[QQ(1, 2), 0], [0, QQ(3, 4)]], (2, 2), QQ) + >>> A = SDM.from_ddm(ddm) + >>> A + {0: {0: 1/2}, 1: {1: 3/4}} + >>> SDM.from_ddm(ddm).to_ddm() == ddm + True + + See Also + ======== + + to_ddm + from_list + from_list_flat + from_dok + """ + return cls.from_list(ddm, ddm.shape, ddm.domain) + + def to_list(M): + """ + Convert a :py:class:`~.SDM` object to a list of lists. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> elemsdict = {0:{1:QQ(2)}, 1:{}} + >>> A = SDM(elemsdict, (2, 2), QQ) + >>> A.to_list() + [[0, 2], [0, 0]] + + + """ + m, n = M.shape + zero = M.domain.zero + ddm = [[zero] * n for _ in range(m)] + for i, row in M.items(): + for j, e in row.items(): + ddm[i][j] = e + return ddm + + def to_list_flat(M): + """ + Convert :py:class:`~.SDM` to a flat list. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0:{1:QQ(2)}, 1:{0: QQ(3)}}, (2, 2), QQ) + >>> A.to_list_flat() + [0, 2, 3, 0] + >>> A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain) + True + + See Also + ======== + + from_list_flat + to_list + to_dok + to_ddm + """ + m, n = M.shape + zero = M.domain.zero + flat = [zero] * (m * n) + for i, row in M.items(): + for j, e in row.items(): + flat[i*n + j] = e + return flat + + @classmethod + def from_list_flat(cls, elements, shape, domain): + """ + Create :py:class:`~.SDM` from a flat list of elements. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM.from_list_flat([QQ(0), QQ(2), QQ(0), QQ(0)], (2, 2), QQ) + >>> A + {0: {1: 2}} + >>> A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain) + True + + See Also + ======== + + to_list_flat + from_list + from_dok + from_ddm + """ + m, n = shape + if len(elements) != m * n: + raise DMBadInputError("Inconsistent flat-list shape") + sdm = defaultdict(dict) + for inj, element in enumerate(elements): + if element: + i, j = divmod(inj, n) + sdm[i][j] = element + return cls(sdm, shape, domain) + + def to_flat_nz(M): + """ + Convert :class:`SDM` to a flat list of nonzero elements and data. + + Explanation + =========== + + This is used to operate on a list of the elements of a matrix and then + reconstruct a modified matrix with elements in the same positions using + :meth:`from_flat_nz`. Zero elements are omitted from the list. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0:{1:QQ(2)}, 1:{0: QQ(3)}}, (2, 2), QQ) + >>> elements, data = A.to_flat_nz() + >>> elements + [2, 3] + >>> A == A.from_flat_nz(elements, data, A.domain) + True + + See Also + ======== + + from_flat_nz + to_list_flat + sympy.polys.matrices.ddm.DDM.to_flat_nz + sympy.polys.matrices.domainmatrix.DomainMatrix.to_flat_nz + """ + dok = M.to_dok() + indices = tuple(dok) + elements = list(dok.values()) + data = (indices, M.shape) + return elements, data + + @classmethod + def from_flat_nz(cls, elements, data, domain): + """ + Reconstruct a :class:`~.SDM` after calling :meth:`to_flat_nz`. + + See :meth:`to_flat_nz` for explanation. + + See Also + ======== + + to_flat_nz + from_list_flat + sympy.polys.matrices.ddm.DDM.from_flat_nz + sympy.polys.matrices.domainmatrix.DomainMatrix.from_flat_nz + """ + indices, shape = data + dok = dict(zip(indices, elements)) + return cls.from_dok(dok, shape, domain) + + def to_dod(M): + """ + Convert to dictionary of dictionaries (dod) format. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ) + >>> A.to_dod() + {0: {1: 2}, 1: {0: 3}} + + See Also + ======== + + from_dod + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dod + """ + return {i: row.copy() for i, row in M.items()} + + @classmethod + def from_dod(cls, dod, shape, domain): + """ + Create :py:class:`~.SDM` from dictionary of dictionaries (dod) format. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> dod = {0: {1: QQ(2)}, 1: {0: QQ(3)}} + >>> A = SDM.from_dod(dod, (2, 2), QQ) + >>> A + {0: {1: 2}, 1: {0: 3}} + >>> A == SDM.from_dod(A.to_dod(), A.shape, A.domain) + True + + See Also + ======== + + to_dod + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dod + """ + sdm = defaultdict(dict) + for i, row in dod.items(): + for j, e in row.items(): + if e: + sdm[i][j] = e + return cls(sdm, shape, domain) + + def to_dok(M): + """ + Convert to dictionary of keys (dok) format. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ) + >>> A.to_dok() + {(0, 1): 2, (1, 0): 3} + + See Also + ======== + + from_dok + to_list + to_list_flat + to_ddm + """ + return {(i, j): e for i, row in M.items() for j, e in row.items()} + + @classmethod + def from_dok(cls, dok, shape, domain): + """ + Create :py:class:`~.SDM` from dictionary of keys (dok) format. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> dok = {(0, 1): QQ(2), (1, 0): QQ(3)} + >>> A = SDM.from_dok(dok, (2, 2), QQ) + >>> A + {0: {1: 2}, 1: {0: 3}} + >>> A == SDM.from_dok(A.to_dok(), A.shape, A.domain) + True + + See Also + ======== + + to_dok + from_list + from_list_flat + from_ddm + """ + sdm = defaultdict(dict) + for (i, j), e in dok.items(): + if e: + sdm[i][j] = e + return cls(sdm, shape, domain) + + def iter_values(M): + """ + Iterate over the nonzero values of a :py:class:`~.SDM` matrix. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ) + >>> list(A.iter_values()) + [2, 3] + + """ + for row in M.values(): + yield from row.values() + + def iter_items(M): + """ + Iterate over indices and values of the nonzero elements. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ) + >>> list(A.iter_items()) + [((0, 1), 2), ((1, 0), 3)] + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.iter_items + """ + for i, row in M.items(): + for j, e in row.items(): + yield (i, j), e + + def to_ddm(M): + """ + Convert a :py:class:`~.SDM` object to a :py:class:`~.DDM` object + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ) + >>> A.to_ddm() + [[0, 2], [0, 0]] + + """ + return DDM(M.to_list(), M.shape, M.domain) + + def to_sdm(M): + """ + Convert to :py:class:`~.SDM` format (returns self). + """ + return M + + @doctest_depends_on(ground_types=['flint']) + def to_dfm(M): + """ + Convert a :py:class:`~.SDM` object to a :py:class:`~.DFM` object + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ) + >>> A.to_dfm() + [[0, 2], [0, 0]] + + See Also + ======== + + to_ddm + to_dfm_or_ddm + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm + """ + return M.to_ddm().to_dfm() + + @doctest_depends_on(ground_types=['flint']) + def to_dfm_or_ddm(M): + """ + Convert to :py:class:`~.DFM` if possible, else :py:class:`~.DDM`. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ) + >>> A.to_dfm_or_ddm() + [[0, 2], [0, 0]] + >>> type(A.to_dfm_or_ddm()) # depends on the ground types + + + See Also + ======== + + to_ddm + to_dfm + sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm_or_ddm + """ + return M.to_ddm().to_dfm_or_ddm() + + @classmethod + def zeros(cls, shape, domain): + r""" + + Returns a :py:class:`~.SDM` of size shape, + belonging to the specified domain + + In the example below we declare a matrix A where, + + .. math:: + A := \left[\begin{array}{ccc} + 0 & 0 & 0 \\ + 0 & 0 & 0 \end{array} \right] + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM.zeros((2, 3), QQ) + >>> A + {} + + """ + return cls({}, shape, domain) + + @classmethod + def ones(cls, shape, domain): + one = domain.one + m, n = shape + row = dict(zip(range(n), [one]*n)) + sdm = {i: row.copy() for i in range(m)} + return cls(sdm, shape, domain) + + @classmethod + def eye(cls, shape, domain): + """ + + Returns a identity :py:class:`~.SDM` matrix of dimensions + size x size, belonging to the specified domain + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> I = SDM.eye((2, 2), QQ) + >>> I + {0: {0: 1}, 1: {1: 1}} + + """ + if isinstance(shape, int): + rows, cols = shape, shape + else: + rows, cols = shape + one = domain.one + sdm = {i: {i: one} for i in range(min(rows, cols))} + return cls(sdm, (rows, cols), domain) + + @classmethod + def diag(cls, diagonal, domain, shape=None): + if shape is None: + shape = (len(diagonal), len(diagonal)) + sdm = {i: {i: v} for i, v in enumerate(diagonal) if v} + return cls(sdm, shape, domain) + + def transpose(M): + """ + + Returns the transpose of a :py:class:`~.SDM` matrix + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy import QQ + >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ) + >>> A.transpose() + {1: {0: 2}} + + """ + MT = sdm_transpose(M) + return M.new(MT, M.shape[::-1], M.domain) + + def __add__(A, B): + if not isinstance(B, SDM): + return NotImplemented + elif A.shape != B.shape: + raise DMShapeError("Matrix size mismatch: %s + %s" % (A.shape, B.shape)) + return A.add(B) + + def __sub__(A, B): + if not isinstance(B, SDM): + return NotImplemented + elif A.shape != B.shape: + raise DMShapeError("Matrix size mismatch: %s - %s" % (A.shape, B.shape)) + return A.sub(B) + + def __neg__(A): + return A.neg() + + def __mul__(A, B): + """A * B""" + if isinstance(B, SDM): + return A.matmul(B) + elif B in A.domain: + return A.mul(B) + else: + return NotImplemented + + def __rmul__(a, b): + if b in a.domain: + return a.rmul(b) + else: + return NotImplemented + + def matmul(A, B): + """ + Performs matrix multiplication of two SDM matrices + + Parameters + ========== + + A, B: SDM to multiply + + Returns + ======= + + SDM + SDM after multiplication + + Raises + ====== + + DomainError + If domain of A does not match + with that of B + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> B = SDM({0:{0:ZZ(2), 1:ZZ(3)}, 1:{0:ZZ(4)}}, (2, 2), ZZ) + >>> A.matmul(B) + {0: {0: 8}, 1: {0: 2, 1: 3}} + + """ + if A.domain != B.domain: + raise DMDomainError + m, n = A.shape + n2, o = B.shape + if n != n2: + raise DMShapeError + C = sdm_matmul(A, B, A.domain, m, o) + return A.new(C, (m, o), A.domain) + + def mul(A, b): + """ + Multiplies each element of A with a scalar b + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> A.mul(ZZ(3)) + {0: {1: 6}, 1: {0: 3}} + + """ + Csdm = unop_dict(A, lambda aij: aij*b) + return A.new(Csdm, A.shape, A.domain) + + def rmul(A, b): + Csdm = unop_dict(A, lambda aij: b*aij) + return A.new(Csdm, A.shape, A.domain) + + def mul_elementwise(A, B): + if A.domain != B.domain: + raise DMDomainError + if A.shape != B.shape: + raise DMShapeError + zero = A.domain.zero + fzero = lambda e: zero + Csdm = binop_dict(A, B, mul, fzero, fzero) + return A.new(Csdm, A.shape, A.domain) + + def add(A, B): + """ + + Adds two :py:class:`~.SDM` matrices + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ) + >>> A.add(B) + {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}} + + """ + Csdm = binop_dict(A, B, add, pos, pos) + return A.new(Csdm, A.shape, A.domain) + + def sub(A, B): + """ + + Subtracts two :py:class:`~.SDM` matrices + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ) + >>> A.sub(B) + {0: {0: -3, 1: 2}, 1: {0: 1, 1: -4}} + + """ + Csdm = binop_dict(A, B, sub, pos, neg) + return A.new(Csdm, A.shape, A.domain) + + def neg(A): + """ + + Returns the negative of a :py:class:`~.SDM` matrix + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> A.neg() + {0: {1: -2}, 1: {0: -1}} + + """ + Csdm = unop_dict(A, neg) + return A.new(Csdm, A.shape, A.domain) + + def convert_to(A, K): + """ + Converts the :py:class:`~.Domain` of a :py:class:`~.SDM` matrix to K + + Examples + ======== + + >>> from sympy import ZZ, QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> A.convert_to(QQ) + {0: {1: 2}, 1: {0: 1}} + + """ + Kold = A.domain + if K == Kold: + return A.copy() + Ak = unop_dict(A, lambda e: K.convert_from(e, Kold)) + return A.new(Ak, A.shape, K) + + def nnz(A): + """Number of non-zero elements in the :py:class:`~.SDM` matrix. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + >>> A.nnz() + 2 + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.nnz + """ + return sum(map(len, A.values())) + + def scc(A): + """Strongly connected components of a square matrix *A*. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0: ZZ(2)}, 1:{1:ZZ(1)}}, (2, 2), ZZ) + >>> A.scc() + [[0], [1]] + + See also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.scc + """ + rows, cols = A.shape + assert rows == cols + V = range(rows) + Emap = {v: list(A.get(v, [])) for v in V} + return _strongly_connected_components(V, Emap) + + def rref(A): + """ + + Returns reduced-row echelon form and list of pivots for the :py:class:`~.SDM` + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ) + >>> A.rref() + ({0: {0: 1, 1: 2}}, [0]) + + """ + B, pivots, _ = sdm_irref(A) + return A.new(B, A.shape, A.domain), pivots + + def rref_den(A): + """ + + Returns reduced-row echelon form (RREF) with denominator and pivots. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ) + >>> A.rref_den() + ({0: {0: 1, 1: 2}}, 1, [0]) + + """ + K = A.domain + A_rref_sdm, denom, pivots = sdm_rref_den(A, K) + A_rref = A.new(A_rref_sdm, A.shape, A.domain) + return A_rref, denom, pivots + + def inv(A): + """ + + Returns inverse of a matrix A + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + >>> A.inv() + {0: {0: -2, 1: 1}, 1: {0: 3/2, 1: -1/2}} + + """ + return A.to_dfm_or_ddm().inv().to_sdm() + + def det(A): + """ + Returns determinant of A + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + >>> A.det() + -2 + + """ + # It would be better to have a sparse implementation of det for use + # with very sparse matrices. Extremely sparse matrices probably just + # have determinant zero and we could probably detect that very quickly. + # In the meantime, we convert to a dense matrix and use ddm_idet. + # + # If GROUND_TYPES=flint though then we will use Flint's implementation + # if possible (dfm). + return A.to_dfm_or_ddm().det() + + def lu(A): + """ + + Returns LU decomposition for a matrix A + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + >>> A.lu() + ({0: {0: 1}, 1: {0: 3, 1: 1}}, {0: {0: 1, 1: 2}, 1: {1: -2}}, []) + + """ + L, U, swaps = A.to_ddm().lu() + return A.from_ddm(L), A.from_ddm(U), swaps + + def qr(self): + """ + QR decomposition for SDM (Sparse Domain Matrix). + + Returns: + - Q: Orthogonal matrix as a SDM. + - R: Upper triangular matrix as a SDM. + """ + ddm_q, ddm_r = self.to_ddm().qr() + Q = ddm_q.to_sdm() + R = ddm_r.to_sdm() + return Q, R + + def lu_solve(A, b): + """ + + Uses LU decomposition to solve Ax = b, + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + >>> b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ) + >>> A.lu_solve(b) + {1: {0: 1/2}} + + """ + return A.from_ddm(A.to_ddm().lu_solve(b.to_ddm())) + + def fflu(self): + """ + Fraction free LU decomposition of SDM. + + Uses DDM implementation. + + See Also + ======== + + sympy.polys.matrices.ddm.DDM.fflu + """ + ddm_p, ddm_l, ddm_d, ddm_u = self.to_dfm_or_ddm().fflu() + P = ddm_p.to_sdm() + L = ddm_l.to_sdm() + D = ddm_d.to_sdm() + U = ddm_u.to_sdm() + return P, L, D, U + + def nullspace(A): + """ + Nullspace of a :py:class:`~.SDM` matrix A. + + The domain of the matrix must be a field. + + It is better to use the :meth:`~.DomainMatrix.nullspace` method rather + than this method which is otherwise no longer used. + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ) + >>> A.nullspace() + ({0: {0: -2, 1: 1}}, [1]) + + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace + The preferred way to get the nullspace of a matrix. + + """ + ncols = A.shape[1] + one = A.domain.one + B, pivots, nzcols = sdm_irref(A) + K, nonpivots = sdm_nullspace_from_rref(B, one, ncols, pivots, nzcols) + K = dict(enumerate(K)) + shape = (len(K), ncols) + return A.new(K, shape, A.domain), nonpivots + + def nullspace_from_rref(A, pivots=None): + """ + Returns nullspace for a :py:class:`~.SDM` matrix ``A`` in RREF. + + The domain of the matrix can be any domain. + + The matrix must already be in reduced row echelon form (RREF). + + Examples + ======== + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import SDM + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ) + >>> A_rref, pivots = A.rref() + >>> A_null, nonpivots = A_rref.nullspace_from_rref(pivots) + >>> A_null + {0: {0: -2, 1: 1}} + >>> pivots + [0] + >>> nonpivots + [1] + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace + The higher-level function that would usually be called instead of + calling this one directly. + + sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace_from_rref + The higher-level direct equivalent of this function. + + sympy.polys.matrices.ddm.DDM.nullspace_from_rref + The equivalent function for dense :py:class:`~.DDM` matrices. + + """ + m, n = A.shape + K = A.domain + + if pivots is None: + pivots = sorted(map(min, A.values())) + + if not pivots: + return A.eye((n, n), K), list(range(n)) + elif len(pivots) == n: + return A.zeros((0, n), K), [] + + # In fraction-free RREF the nonzero entry inserted for the pivots is + # not necessarily 1. + pivot_val = A[0][pivots[0]] + assert not K.is_zero(pivot_val) + + pivots_set = set(pivots) + + # Loop once over all nonzero entries making a map from column indices + # to the nonzero entries in that column along with the row index of the + # nonzero entry. This is basically the transpose of the matrix. + nonzero_cols = defaultdict(list) + for i, Ai in A.items(): + for j, Aij in Ai.items(): + nonzero_cols[j].append((i, Aij)) + + # Usually in SDM we want to avoid looping over the dimensions of the + # matrix because it is optimised to support extremely sparse matrices. + # Here in nullspace though every zero column becomes a nonzero column + # so we need to loop once over the columns at least (range(n)) rather + # than just the nonzero entries of the matrix. We can still avoid + # an inner loop over the rows though by using the nonzero_cols map. + basis = [] + nonpivots = [] + for j in range(n): + if j in pivots_set: + continue + nonpivots.append(j) + + vec = {j: pivot_val} + for ip, Aij in nonzero_cols[j]: + vec[pivots[ip]] = -Aij + + basis.append(vec) + + sdm = dict(enumerate(basis)) + A_null = A.new(sdm, (len(basis), n), K) + + return (A_null, nonpivots) + + def particular(A): + ncols = A.shape[1] + B, pivots, nzcols = sdm_irref(A) + P = sdm_particular_from_rref(B, ncols, pivots) + rep = {0:P} if P else {} + return A.new(rep, (1, ncols-1), A.domain) + + def hstack(A, *B): + """Horizontally stacks :py:class:`~.SDM` matrices. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + + >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ) + >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ) + >>> A.hstack(B) + {0: {0: 1, 1: 2, 2: 5, 3: 6}, 1: {0: 3, 1: 4, 2: 7, 3: 8}} + + >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ) + >>> A.hstack(B, C) + {0: {0: 1, 1: 2, 2: 5, 3: 6, 4: 9, 5: 10}, 1: {0: 3, 1: 4, 2: 7, 3: 8, 4: 11, 5: 12}} + """ + Anew = dict(A.copy()) + rows, cols = A.shape + domain = A.domain + + for Bk in B: + Bkrows, Bkcols = Bk.shape + assert Bkrows == rows + assert Bk.domain == domain + + for i, Bki in Bk.items(): + Ai = Anew.get(i, None) + if Ai is None: + Anew[i] = Ai = {} + for j, Bkij in Bki.items(): + Ai[j + cols] = Bkij + cols += Bkcols + + return A.new(Anew, (rows, cols), A.domain) + + def vstack(A, *B): + """Vertically stacks :py:class:`~.SDM` matrices. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.polys.matrices.sdm import SDM + + >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ) + >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ) + >>> A.vstack(B) + {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}} + + >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ) + >>> A.vstack(B, C) + {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}, 4: {0: 9, 1: 10}, 5: {0: 11, 1: 12}} + """ + Anew = dict(A.copy()) + rows, cols = A.shape + domain = A.domain + + for Bk in B: + Bkrows, Bkcols = Bk.shape + assert Bkcols == cols + assert Bk.domain == domain + + for i, Bki in Bk.items(): + Anew[i + rows] = Bki + rows += Bkrows + + return A.new(Anew, (rows, cols), A.domain) + + def applyfunc(self, func, domain): + sdm = {i: {j: func(e) for j, e in row.items()} for i, row in self.items()} + return self.new(sdm, self.shape, domain) + + def charpoly(A): + """ + Returns the coefficients of the characteristic polynomial + of the :py:class:`~.SDM` matrix. These elements will be domain elements. + The domain of the elements will be same as domain of the :py:class:`~.SDM`. + + Examples + ======== + + >>> from sympy import QQ, Symbol + >>> from sympy.polys.matrices.sdm import SDM + >>> from sympy.polys import Poly + >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + >>> A.charpoly() + [1, -5, -2] + + We can create a polynomial using the + coefficients using :py:class:`~.Poly` + + >>> x = Symbol('x') + >>> p = Poly(A.charpoly(), x, domain=A.domain) + >>> p + Poly(x**2 - 5*x - 2, x, domain='QQ') + + """ + K = A.domain + n, _ = A.shape + pdict = sdm_berk(A, n, K) + plist = [K.zero] * (n + 1) + for i, pi in pdict.items(): + plist[i] = pi + return plist + + def is_zero_matrix(self): + """ + Says whether this matrix has all zero entries. + """ + return not self + + def is_upper(self): + """ + Says whether this matrix is upper-triangular. True can be returned + even if the matrix is not square. + """ + return all(i <= j for i, row in self.items() for j in row) + + def is_lower(self): + """ + Says whether this matrix is lower-triangular. True can be returned + even if the matrix is not square. + """ + return all(i >= j for i, row in self.items() for j in row) + + def is_diagonal(self): + """ + Says whether this matrix is diagonal. True can be returned + even if the matrix is not square. + """ + return all(i == j for i, row in self.items() for j in row) + + def diagonal(self): + """ + Returns the diagonal of the matrix as a list. + """ + m, n = self.shape + zero = self.domain.zero + return [row.get(i, zero) for i, row in self.items() if i < n] + + def lll(A, delta=QQ(3, 4)): + """ + Returns the LLL-reduced basis for the :py:class:`~.SDM` matrix. + """ + return A.to_dfm_or_ddm().lll(delta=delta).to_sdm() + + def lll_transform(A, delta=QQ(3, 4)): + """ + Returns the LLL-reduced basis and transformation matrix. + """ + reduced, transform = A.to_dfm_or_ddm().lll_transform(delta=delta) + return reduced.to_sdm(), transform.to_sdm() + + +def binop_dict(A, B, fab, fa, fb): + Anz, Bnz = set(A), set(B) + C = {} + + for i in Anz & Bnz: + Ai, Bi = A[i], B[i] + Ci = {} + Anzi, Bnzi = set(Ai), set(Bi) + for j in Anzi & Bnzi: + Cij = fab(Ai[j], Bi[j]) + if Cij: + Ci[j] = Cij + for j in Anzi - Bnzi: + Cij = fa(Ai[j]) + if Cij: + Ci[j] = Cij + for j in Bnzi - Anzi: + Cij = fb(Bi[j]) + if Cij: + Ci[j] = Cij + if Ci: + C[i] = Ci + + for i in Anz - Bnz: + Ai = A[i] + Ci = {} + for j, Aij in Ai.items(): + Cij = fa(Aij) + if Cij: + Ci[j] = Cij + if Ci: + C[i] = Ci + + for i in Bnz - Anz: + Bi = B[i] + Ci = {} + for j, Bij in Bi.items(): + Cij = fb(Bij) + if Cij: + Ci[j] = Cij + if Ci: + C[i] = Ci + + return C + + +def unop_dict(A, f): + B = {} + for i, Ai in A.items(): + Bi = {} + for j, Aij in Ai.items(): + Bij = f(Aij) + if Bij: + Bi[j] = Bij + if Bi: + B[i] = Bi + return B + + +def sdm_transpose(M): + MT = {} + for i, Mi in M.items(): + for j, Mij in Mi.items(): + try: + MT[j][i] = Mij + except KeyError: + MT[j] = {i: Mij} + return MT + + +def sdm_dotvec(A, B, K): + return K.sum(A[j] * B[j] for j in A.keys() & B.keys()) + + +def sdm_matvecmul(A, B, K): + C = {} + for i, Ai in A.items(): + Ci = sdm_dotvec(Ai, B, K) + if Ci: + C[i] = Ci + return C + + +def sdm_matmul(A, B, K, m, o): + # + # Should be fast if A and B are very sparse. + # Consider e.g. A = B = eye(1000). + # + # The idea here is that we compute C = A*B in terms of the rows of C and + # B since the dict of dicts representation naturally stores the matrix as + # rows. The ith row of C (Ci) is equal to the sum of Aik * Bk where Bk is + # the kth row of B. The algorithm below loops over each nonzero element + # Aik of A and if the corresponding row Bj is nonzero then we do + # Ci += Aik * Bk. + # To make this more efficient we don't need to loop over all elements Aik. + # Instead for each row Ai we compute the intersection of the nonzero + # columns in Ai with the nonzero rows in B. That gives the k such that + # Aik and Bk are both nonzero. In Python the intersection of two sets + # of int can be computed very efficiently. + # + if K.is_EXRAW: + return sdm_matmul_exraw(A, B, K, m, o) + + C = {} + B_knz = set(B) + for i, Ai in A.items(): + Ci = {} + Ai_knz = set(Ai) + for k in Ai_knz & B_knz: + Aik = Ai[k] + for j, Bkj in B[k].items(): + Cij = Ci.get(j, None) + if Cij is not None: + Cij = Cij + Aik * Bkj + if Cij: + Ci[j] = Cij + else: + Ci.pop(j) + else: + Cij = Aik * Bkj + if Cij: + Ci[j] = Cij + if Ci: + C[i] = Ci + return C + + +def sdm_matmul_exraw(A, B, K, m, o): + # + # Like sdm_matmul above except that: + # + # - Handles cases like 0*oo -> nan (sdm_matmul skips multiplication by zero) + # - Uses K.sum (Add(*items)) for efficient addition of Expr + # + zero = K.zero + C = {} + B_knz = set(B) + for i, Ai in A.items(): + Ci_list = defaultdict(list) + Ai_knz = set(Ai) + + # Nonzero row/column pair + for k in Ai_knz & B_knz: + Aik = Ai[k] + if zero * Aik == zero: + # This is the main inner loop: + for j, Bkj in B[k].items(): + Ci_list[j].append(Aik * Bkj) + else: + for j in range(o): + Ci_list[j].append(Aik * B[k].get(j, zero)) + + # Zero row in B, check for infinities in A + for k in Ai_knz - B_knz: + zAik = zero * Ai[k] + if zAik != zero: + for j in range(o): + Ci_list[j].append(zAik) + + # Add terms using K.sum (Add(*terms)) for efficiency + Ci = {} + for j, Cij_list in Ci_list.items(): + Cij = K.sum(Cij_list) + if Cij: + Ci[j] = Cij + if Ci: + C[i] = Ci + + # Find all infinities in B + for k, Bk in B.items(): + for j, Bkj in Bk.items(): + if zero * Bkj != zero: + for i in range(m): + Aik = A.get(i, {}).get(k, zero) + # If Aik is not zero then this was handled above + if Aik == zero: + Ci = C.get(i, {}) + Cij = Ci.get(j, zero) + Aik * Bkj + if Cij != zero: + Ci[j] = Cij + C[i] = Ci + else: + Ci.pop(j, None) + if Ci: + C[i] = Ci + else: + C.pop(i, None) + + return C + + +def sdm_irref(A): + """RREF and pivots of a sparse matrix *A*. + + Compute the reduced row echelon form (RREF) of the matrix *A* and return a + list of the pivot columns. This routine does not work in place and leaves + the original matrix *A* unmodified. + + The domain of the matrix must be a field. + + Examples + ======== + + This routine works with a dict of dicts sparse representation of a matrix: + + >>> from sympy import QQ + >>> from sympy.polys.matrices.sdm import sdm_irref + >>> A = {0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}} + >>> Arref, pivots, _ = sdm_irref(A) + >>> Arref + {0: {0: 1}, 1: {1: 1}} + >>> pivots + [0, 1] + + The analogous calculation with :py:class:`~.MutableDenseMatrix` would be + + >>> from sympy import Matrix + >>> M = Matrix([[1, 2], [3, 4]]) + >>> Mrref, pivots = M.rref() + >>> Mrref + Matrix([ + [1, 0], + [0, 1]]) + >>> pivots + (0, 1) + + Notes + ===== + + The cost of this algorithm is determined purely by the nonzero elements of + the matrix. No part of the cost of any step in this algorithm depends on + the number of rows or columns in the matrix. No step depends even on the + number of nonzero rows apart from the primary loop over those rows. The + implementation is much faster than ddm_rref for sparse matrices. In fact + at the time of writing it is also (slightly) faster than the dense + implementation even if the input is a fully dense matrix so it seems to be + faster in all cases. + + The elements of the matrix should support exact division with ``/``. For + example elements of any domain that is a field (e.g. ``QQ``) should be + fine. No attempt is made to handle inexact arithmetic. + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.rref + The higher-level function that would normally be used to call this + routine. + sympy.polys.matrices.dense.ddm_irref + The dense equivalent of this routine. + sdm_rref_den + Fraction-free version of this routine. + """ + # + # Any zeros in the matrix are not stored at all so an element is zero if + # its row dict has no index at that key. A row is entirely zero if its + # row index is not in the outer dict. Since rref reorders the rows and + # removes zero rows we can completely discard the row indices. The first + # step then copies the row dicts into a list sorted by the index of the + # first nonzero column in each row. + # + # The algorithm then processes each row Ai one at a time. Previously seen + # rows are used to cancel their pivot columns from Ai. Then a pivot from + # Ai is chosen and is cancelled from all previously seen rows. At this + # point Ai joins the previously seen rows. Once all rows are seen all + # elimination has occurred and the rows are sorted by pivot column index. + # + # The previously seen rows are stored in two separate groups. The reduced + # group consists of all rows that have been reduced to a single nonzero + # element (the pivot). There is no need to attempt any further reduction + # with these. Rows that still have other nonzeros need to be considered + # when Ai is cancelled from the previously seen rows. + # + # A dict nonzerocolumns is used to map from a column index to a set of + # previously seen rows that still have a nonzero element in that column. + # This means that we can cancel the pivot from Ai into the previously seen + # rows without needing to loop over each row that might have a zero in + # that column. + # + + # Row dicts sorted by index of first nonzero column + # (Maybe sorting is not needed/useful.) + Arows = sorted((Ai.copy() for Ai in A.values()), key=min) + + # Each processed row has an associated pivot column. + # pivot_row_map maps from the pivot column index to the row dict. + # This means that we can represent a set of rows purely as a set of their + # pivot indices. + pivot_row_map = {} + + # Set of pivot indices for rows that are fully reduced to a single nonzero. + reduced_pivots = set() + + # Set of pivot indices for rows not fully reduced + nonreduced_pivots = set() + + # Map from column index to a set of pivot indices representing the rows + # that have a nonzero at that column. + nonzero_columns = defaultdict(set) + + while Arows: + # Select pivot element and row + Ai = Arows.pop() + + # Nonzero columns from fully reduced pivot rows can be removed + Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced_pivots} + + # Others require full row cancellation + for j in nonreduced_pivots & set(Ai): + Aj = pivot_row_map[j] + Aij = Ai[j] + Ainz = set(Ai) + Ajnz = set(Aj) + for k in Ajnz - Ainz: + Ai[k] = - Aij * Aj[k] + Ai.pop(j) + Ainz.remove(j) + for k in Ajnz & Ainz: + Aik = Ai[k] - Aij * Aj[k] + if Aik: + Ai[k] = Aik + else: + Ai.pop(k) + + # We have now cancelled previously seen pivots from Ai. + # If it is zero then discard it. + if not Ai: + continue + + # Choose a pivot from Ai: + j = min(Ai) + Aij = Ai[j] + pivot_row_map[j] = Ai + Ainz = set(Ai) + + # Normalise the pivot row to make the pivot 1. + # + # This approach is slow for some domains. Cross cancellation might be + # better for e.g. QQ(x) with division delayed to the final steps. + Aijinv = Aij**-1 + for l in Ai: + Ai[l] *= Aijinv + + # Use Aij to cancel column j from all previously seen rows + for k in nonzero_columns.pop(j, ()): + Ak = pivot_row_map[k] + Akj = Ak[j] + Aknz = set(Ak) + for l in Ainz - Aknz: + Ak[l] = - Akj * Ai[l] + nonzero_columns[l].add(k) + Ak.pop(j) + Aknz.remove(j) + for l in Ainz & Aknz: + Akl = Ak[l] - Akj * Ai[l] + if Akl: + Ak[l] = Akl + else: + # Drop nonzero elements + Ak.pop(l) + if l != j: + nonzero_columns[l].remove(k) + if len(Ak) == 1: + reduced_pivots.add(k) + nonreduced_pivots.remove(k) + + if len(Ai) == 1: + reduced_pivots.add(j) + else: + nonreduced_pivots.add(j) + for l in Ai: + if l != j: + nonzero_columns[l].add(j) + + # All done! + pivots = sorted(reduced_pivots | nonreduced_pivots) + pivot2row = {p: n for n, p in enumerate(pivots)} + nonzero_columns = {c: {pivot2row[p] for p in s} for c, s in nonzero_columns.items()} + rows = [pivot_row_map[i] for i in pivots] + rref = dict(enumerate(rows)) + return rref, pivots, nonzero_columns + + +def sdm_rref_den(A, K): + """ + Return the reduced row echelon form (RREF) of A with denominator. + + The RREF is computed using fraction-free Gauss-Jordan elimination. + + Explanation + =========== + + The algorithm used is the fraction-free version of Gauss-Jordan elimination + described as FFGJ in [1]_. Here it is modified to handle zero or missing + pivots and to avoid redundant arithmetic. This implementation is also + optimized for sparse matrices. + + The domain $K$ must support exact division (``K.exquo``) but does not need + to be a field. This method is suitable for most exact rings and fields like + :ref:`ZZ`, :ref:`QQ` and :ref:`QQ(a)`. In the case of :ref:`QQ` or + :ref:`K(x)` it might be more efficient to clear denominators and use + :ref:`ZZ` or :ref:`K[x]` instead. + + For inexact domains like :ref:`RR` and :ref:`CC` use ``ddm_irref`` instead. + + Examples + ======== + + >>> from sympy.polys.matrices.sdm import sdm_rref_den + >>> from sympy.polys.domains import ZZ + >>> A = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}} + >>> A_rref, den, pivots = sdm_rref_den(A, ZZ) + >>> A_rref + {0: {0: -2}, 1: {1: -2}} + >>> den + -2 + >>> pivots + [0, 1] + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den + Higher-level interface to ``sdm_rref_den`` that would usually be used + instead of calling this function directly. + sympy.polys.matrices.sdm.sdm_rref_den + The ``SDM`` method that uses this function. + sdm_irref + Computes RREF using field division. + ddm_irref_den + The dense version of this algorithm. + + References + ========== + + .. [1] Fraction-free algorithms for linear and polynomial equations. + George C. Nakos , Peter R. Turner , Robert M. Williams. + https://dl.acm.org/doi/10.1145/271130.271133 + """ + # + # We represent each row of the matrix as a dict mapping column indices to + # nonzero elements. We will build the RREF matrix starting from an empty + # matrix and appending one row at a time. At each step we will have the + # RREF of the rows we have processed so far. + # + # Our representation of the RREF divides it into three parts: + # + # 1. Fully reduced rows having only a single nonzero element (the pivot). + # 2. Partially reduced rows having nonzeros after the pivot. + # 3. The current denominator and divisor. + # + # For example if the incremental RREF might be: + # + # [2, 0, 0, 0, 0, 0, 0, 0, 0, 0] + # [0, 0, 2, 0, 0, 0, 7, 0, 0, 0] + # [0, 0, 0, 0, 0, 2, 0, 0, 0, 0] + # [0, 0, 0, 0, 0, 0, 0, 2, 0, 0] + # [0, 0, 0, 0, 0, 0, 0, 0, 2, 0] + # + # Here the second row is partially reduced and the other rows are fully + # reduced. The denominator would be 2 in this case. We distinguish the + # fully reduced rows because we can handle them more efficiently when + # adding a new row. + # + # When adding a new row we need to multiply it by the current denominator. + # Then we reduce the new row by cross cancellation with the previous rows. + # Then if it is not reduced to zero we take its leading entry as the new + # pivot, cross cancel the new row from the previous rows and update the + # denominator. In the fraction-free version this last step requires + # multiplying and dividing the whole matrix by the new pivot and the + # current divisor. The advantage of building the RREF one row at a time is + # that in the sparse case we only need to work with the relatively sparse + # upper rows of the matrix. The simple version of FFGJ in [1] would + # multiply and divide all the dense lower rows at each step. + + # Handle the trivial cases. + if not A: + return ({}, K.one, []) + elif len(A) == 1: + Ai, = A.values() + j = min(Ai) + Aij = Ai[j] + return ({0: Ai.copy()}, Aij, [j]) + + # For inexact domains like RR[x] we use quo and discard the remainder. + # Maybe it would be better for K.exquo to do this automatically. + if K.is_Exact: + exquo = K.exquo + else: + exquo = K.quo + + # Make sure we have the rows in order to make this deterministic from the + # outset. + _, rows_in_order = zip(*sorted(A.items())) + + col_to_row_reduced = {} + col_to_row_unreduced = {} + reduced = col_to_row_reduced.keys() + unreduced = col_to_row_unreduced.keys() + + # Our representation of the RREF so far. + A_rref_rows = [] + denom = None + divisor = None + + # The rows that remain to be added to the RREF. These are sorted by the + # column index of their leading entry. Note that sorted() is stable so the + # previous sort by unique row index is still needed to make this + # deterministic (there may be multiple rows with the same leading column). + A_rows = sorted(rows_in_order, key=min) + + for Ai in A_rows: + + # All fully reduced columns can be immediately discarded. + Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced} + + # We need to multiply the new row by the current denominator to bring + # it into the same scale as the previous rows and then cross-cancel to + # reduce it wrt the previous unreduced rows. All pivots in the previous + # rows are equal to denom so the coefficients we need to make a linear + # combination of the previous rows to cancel into the new row are just + # the ones that are already in the new row *before* we multiply by + # denom. We compute that linear combination first and then multiply the + # new row by denom before subtraction. + Ai_cancel = {} + + for j in unreduced & Ai.keys(): + # Remove the pivot column from the new row since it would become + # zero anyway. + Aij = Ai.pop(j) + + Aj = A_rref_rows[col_to_row_unreduced[j]] + + for k, Ajk in Aj.items(): + Aik_cancel = Ai_cancel.get(k) + if Aik_cancel is None: + Ai_cancel[k] = Aij * Ajk + else: + Aik_cancel = Aik_cancel + Aij * Ajk + if Aik_cancel: + Ai_cancel[k] = Aik_cancel + else: + Ai_cancel.pop(k) + + # Multiply the new row by the current denominator and subtract. + Ai_nz = set(Ai) + Ai_cancel_nz = set(Ai_cancel) + + d = denom or K.one + + for k in Ai_cancel_nz - Ai_nz: + Ai[k] = -Ai_cancel[k] + + for k in Ai_nz - Ai_cancel_nz: + Ai[k] = Ai[k] * d + + for k in Ai_cancel_nz & Ai_nz: + Aik = Ai[k] * d - Ai_cancel[k] + if Aik: + Ai[k] = Aik + else: + Ai.pop(k) + + # Now Ai has the same scale as the other rows and is reduced wrt the + # unreduced rows. + + # If the row is reduced to zero then discard it. + if not Ai: + continue + + # Choose a pivot for this row. + j = min(Ai) + Aij = Ai.pop(j) + + # Cross cancel the unreduced rows by the new row. + # a[k][l] = (a[i][j]*a[k][l] - a[k][j]*a[i][l]) / divisor + for pk, k in list(col_to_row_unreduced.items()): + + Ak = A_rref_rows[k] + + if j not in Ak: + # This row is already reduced wrt the new row but we need to + # bring it to the same scale as the new denominator. This step + # is not needed in sdm_irref. + for l, Akl in Ak.items(): + Akl = Akl * Aij + if divisor is not None: + Akl = exquo(Akl, divisor) + Ak[l] = Akl + continue + + Akj = Ak.pop(j) + Ai_nz = set(Ai) + Ak_nz = set(Ak) + + for l in Ai_nz - Ak_nz: + Ak[l] = - Akj * Ai[l] + if divisor is not None: + Ak[l] = exquo(Ak[l], divisor) + + # This loop also not needed in sdm_irref. + for l in Ak_nz - Ai_nz: + Ak[l] = Aij * Ak[l] + if divisor is not None: + Ak[l] = exquo(Ak[l], divisor) + + for l in Ai_nz & Ak_nz: + Akl = Aij * Ak[l] - Akj * Ai[l] + if Akl: + if divisor is not None: + Akl = exquo(Akl, divisor) + Ak[l] = Akl + else: + Ak.pop(l) + + if not Ak: + col_to_row_unreduced.pop(pk) + col_to_row_reduced[pk] = k + + i = len(A_rref_rows) + A_rref_rows.append(Ai) + if Ai: + col_to_row_unreduced[j] = i + else: + col_to_row_reduced[j] = i + + # Update the denominator. + if not K.is_one(Aij): + if denom is None: + denom = Aij + else: + denom *= Aij + + if divisor is not None: + denom = exquo(denom, divisor) + + # Update the divisor. + divisor = denom + + if denom is None: + denom = K.one + + # Sort the rows by their leading column index. + col_to_row = {**col_to_row_reduced, **col_to_row_unreduced} + row_to_col = {i: j for j, i in col_to_row.items()} + A_rref_rows_col = [(row_to_col[i], Ai) for i, Ai in enumerate(A_rref_rows)] + pivots, A_rref = zip(*sorted(A_rref_rows_col)) + pivots = list(pivots) + + # Insert the pivot values + for i, Ai in enumerate(A_rref): + Ai[pivots[i]] = denom + + A_rref_sdm = dict(enumerate(A_rref)) + + return A_rref_sdm, denom, pivots + + +def sdm_nullspace_from_rref(A, one, ncols, pivots, nonzero_cols): + """Get nullspace from A which is in RREF""" + nonpivots = sorted(set(range(ncols)) - set(pivots)) + + K = [] + for j in nonpivots: + Kj = {j:one} + for i in nonzero_cols.get(j, ()): + Kj[pivots[i]] = -A[i][j] + K.append(Kj) + + return K, nonpivots + + +def sdm_particular_from_rref(A, ncols, pivots): + """Get a particular solution from A which is in RREF""" + P = {} + for i, j in enumerate(pivots): + Ain = A[i].get(ncols-1, None) + if Ain is not None: + P[j] = Ain / A[i][j] + return P + + +def sdm_berk(M, n, K): + """ + Berkowitz algorithm for computing the characteristic polynomial. + + Explanation + =========== + + The Berkowitz algorithm is a division-free algorithm for computing the + characteristic polynomial of a matrix over any commutative ring using only + arithmetic in the coefficient ring. This implementation is for sparse + matrices represented in a dict-of-dicts format (like :class:`SDM`). + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.polys.matrices.sdm import sdm_berk + >>> from sympy.polys.domains import ZZ + >>> M = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}} + >>> sdm_berk(M, 2, ZZ) + {0: 1, 1: -5, 2: -2} + >>> Matrix([[1, 2], [3, 4]]).charpoly() + PurePoly(lambda**2 - 5*lambda - 2, lambda, domain='ZZ') + + See Also + ======== + + sympy.polys.matrices.domainmatrix.DomainMatrix.charpoly + The high-level interface to this function. + sympy.polys.matrices.dense.ddm_berk + The dense version of this function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Samuelson%E2%80%93Berkowitz_algorithm + """ + zero = K.zero + one = K.one + + if n == 0: + return {0: one} + elif n == 1: + pdict = {0: one} + if M00 := M.get(0, {}).get(0, zero): + pdict[1] = -M00 + + # M = [[a, R], + # [C, A]] + a, R, C, A = K.zero, {}, {}, defaultdict(dict) + for i, Mi in M.items(): + for j, Mij in Mi.items(): + if i and j: + A[i-1][j-1] = Mij + elif i: + C[i-1] = Mij + elif j: + R[j-1] = Mij + else: + a = Mij + + # T = [ 1, 0, 0, 0, 0, ... ] + # [ -a, 1, 0, 0, 0, ... ] + # [ -R*C, -a, 1, 0, 0, ... ] + # [ -R*A*C, -R*C, -a, 1, 0, ... ] + # [-R*A^2*C, -R*A*C, -R*C, -a, 1, ... ] + # [ ... ] + # T is (n+1) x n + # + # In the sparse case we might have A^m*C = 0 for some m making T banded + # rather than triangular so we just compute the nonzero entries of the + # first column rather than constructing the matrix explicitly. + + AnC = C + RC = sdm_dotvec(R, C, K) + + Tvals = [one, -a, -RC] + for i in range(3, n+1): + AnC = sdm_matvecmul(A, AnC, K) + if not AnC: + break + RAnC = sdm_dotvec(R, AnC, K) + Tvals.append(-RAnC) + + # Strip trailing zeros + while Tvals and not Tvals[-1]: + Tvals.pop() + + q = sdm_berk(A, n-1, K) + + # This would be the explicit multiplication T*q but we can do better: + # + # T = {} + # for i in range(n+1): + # Ti = {} + # for j in range(max(0, i-len(Tvals)+1), min(i+1, n)): + # Ti[j] = Tvals[i-j] + # T[i] = Ti + # Tq = sdm_matvecmul(T, q, K) + # + # In the sparse case q might be mostly zero. We know that T[i,j] is nonzero + # for i <= j < i + len(Tvals) so if q does not have a nonzero entry in that + # range then Tq[j] must be zero. We exploit this potential banded + # structure and the potential sparsity of q to compute Tq more efficiently. + + Tvals = Tvals[::-1] + + Tq = {} + + for i in range(min(q), min(max(q)+len(Tvals), n+1)): + Ti = dict(enumerate(Tvals, i-len(Tvals)+1)) + if Tqi := sdm_dotvec(Ti, q, K): + Tq[i] = Tqi + + return Tq diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_ddm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_ddm.py new file mode 100644 index 0000000000000000000000000000000000000000..44c862461e85d503696e621874c10d67d8ee1f1d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_ddm.py @@ -0,0 +1,558 @@ +from sympy.testing.pytest import raises +from sympy.external.gmpy import GROUND_TYPES + +from sympy.polys import ZZ, QQ + +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.exceptions import ( + DMShapeError, DMNonInvertibleMatrixError, DMDomainError, + DMBadInputError) + + +def test_DDM_init(): + items = [[ZZ(0), ZZ(1), ZZ(2)], [ZZ(3), ZZ(4), ZZ(5)]] + shape = (2, 3) + ddm = DDM(items, shape, ZZ) + assert ddm.shape == shape + assert ddm.rows == 2 + assert ddm.cols == 3 + assert ddm.domain == ZZ + + raises(DMBadInputError, lambda: DDM([[ZZ(2), ZZ(3)]], (2, 2), ZZ)) + raises(DMBadInputError, lambda: DDM([[ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ)) + + +def test_DDM_getsetitem(): + ddm = DDM([[ZZ(2), ZZ(3)], [ZZ(4), ZZ(5)]], (2, 2), ZZ) + + assert ddm[0][0] == ZZ(2) + assert ddm[0][1] == ZZ(3) + assert ddm[1][0] == ZZ(4) + assert ddm[1][1] == ZZ(5) + + raises(IndexError, lambda: ddm[2][0]) + raises(IndexError, lambda: ddm[0][2]) + + ddm[0][0] = ZZ(-1) + assert ddm[0][0] == ZZ(-1) + + +def test_DDM_str(): + ddm = DDM([[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ) + if GROUND_TYPES == 'gmpy': # pragma: no cover + assert str(ddm) == '[[0, 1], [2, 3]]' + assert repr(ddm) == 'DDM([[mpz(0), mpz(1)], [mpz(2), mpz(3)]], (2, 2), ZZ)' + else: # pragma: no cover + assert repr(ddm) == 'DDM([[0, 1], [2, 3]], (2, 2), ZZ)' + assert str(ddm) == '[[0, 1], [2, 3]]' + + +def test_DDM_eq(): + items = [[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]] + ddm1 = DDM(items, (2, 2), ZZ) + ddm2 = DDM(items, (2, 2), ZZ) + + assert (ddm1 == ddm1) is True + assert (ddm1 == items) is False + assert (items == ddm1) is False + assert (ddm1 == ddm2) is True + assert (ddm2 == ddm1) is True + + assert (ddm1 != ddm1) is False + assert (ddm1 != items) is True + assert (items != ddm1) is True + assert (ddm1 != ddm2) is False + assert (ddm2 != ddm1) is False + + ddm3 = DDM([[ZZ(0), ZZ(1)], [ZZ(3), ZZ(3)]], (2, 2), ZZ) + ddm3 = DDM(items, (2, 2), QQ) + + assert (ddm1 == ddm3) is False + assert (ddm3 == ddm1) is False + assert (ddm1 != ddm3) is True + assert (ddm3 != ddm1) is True + + +def test_DDM_convert_to(): + ddm = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + assert ddm.convert_to(ZZ) == ddm + ddmq = ddm.convert_to(QQ) + assert ddmq.domain == QQ + + +def test_DDM_zeros(): + ddmz = DDM.zeros((3, 4), QQ) + assert list(ddmz) == [[QQ(0)] * 4] * 3 + assert ddmz.shape == (3, 4) + assert ddmz.domain == QQ + +def test_DDM_ones(): + ddmone = DDM.ones((2, 3), QQ) + assert list(ddmone) == [[QQ(1)] * 3] * 2 + assert ddmone.shape == (2, 3) + assert ddmone.domain == QQ + +def test_DDM_eye(): + ddmz = DDM.eye(3, QQ) + f = lambda i, j: QQ(1) if i == j else QQ(0) + assert list(ddmz) == [[f(i, j) for i in range(3)] for j in range(3)] + assert ddmz.shape == (3, 3) + assert ddmz.domain == QQ + + +def test_DDM_copy(): + ddm1 = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + ddm2 = ddm1.copy() + assert (ddm1 == ddm2) is True + ddm1[0][0] = QQ(-1) + assert (ddm1 == ddm2) is False + ddm2[0][0] = QQ(-1) + assert (ddm1 == ddm2) is True + + +def test_DDM_transpose(): + ddm = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + ddmT = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) + assert ddm.transpose() == ddmT + ddm02 = DDM([], (0, 2), QQ) + ddm02T = DDM([[], []], (2, 0), QQ) + assert ddm02.transpose() == ddm02T + assert ddm02T.transpose() == ddm02 + ddm0 = DDM([], (0, 0), QQ) + assert ddm0.transpose() == ddm0 + + +def test_DDM_add(): + A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ) + C = DDM([[ZZ(4)], [ZZ(6)]], (2, 1), ZZ) + AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + assert A + B == A.add(B) == C + + raises(DMShapeError, lambda: A + DDM([[ZZ(5)]], (1, 1), ZZ)) + raises(TypeError, lambda: A + ZZ(1)) + raises(TypeError, lambda: ZZ(1) + A) + raises(DMDomainError, lambda: A + AQ) + raises(DMDomainError, lambda: AQ + A) + + +def test_DDM_sub(): + A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ) + C = DDM([[ZZ(-2)], [ZZ(-2)]], (2, 1), ZZ) + AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + D = DDM([[ZZ(5)]], (1, 1), ZZ) + assert A - B == A.sub(B) == C + + raises(TypeError, lambda: A - ZZ(1)) + raises(TypeError, lambda: ZZ(1) - A) + raises(DMShapeError, lambda: A - D) + raises(DMShapeError, lambda: D - A) + raises(DMShapeError, lambda: A.sub(D)) + raises(DMShapeError, lambda: D.sub(A)) + raises(DMDomainError, lambda: A - AQ) + raises(DMDomainError, lambda: AQ - A) + raises(DMDomainError, lambda: A.sub(AQ)) + raises(DMDomainError, lambda: AQ.sub(A)) + + +def test_DDM_neg(): + A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + An = DDM([[ZZ(-1)], [ZZ(-2)]], (2, 1), ZZ) + assert -A == A.neg() == An + assert -An == An.neg() == A + + +def test_DDM_mul(): + A = DDM([[ZZ(1)]], (1, 1), ZZ) + A2 = DDM([[ZZ(2)]], (1, 1), ZZ) + assert A * ZZ(2) == A2 + assert ZZ(2) * A == A2 + raises(TypeError, lambda: [[1]] * A) + raises(TypeError, lambda: A * [[1]]) + + +def test_DDM_matmul(): + A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + B = DDM([[ZZ(3), ZZ(4)]], (1, 2), ZZ) + AB = DDM([[ZZ(3), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) + BA = DDM([[ZZ(11)]], (1, 1), ZZ) + + assert A @ B == A.matmul(B) == AB + assert B @ A == B.matmul(A) == BA + + raises(TypeError, lambda: A @ 1) + raises(TypeError, lambda: A @ [[3, 4]]) + + Bq = DDM([[QQ(3), QQ(4)]], (1, 2), QQ) + + raises(DMDomainError, lambda: A @ Bq) + raises(DMDomainError, lambda: Bq @ A) + + C = DDM([[ZZ(1)]], (1, 1), ZZ) + + assert A @ C == A.matmul(C) == A + + raises(DMShapeError, lambda: C @ A) + raises(DMShapeError, lambda: C.matmul(A)) + + Z04 = DDM([], (0, 4), ZZ) + Z40 = DDM([[]]*4, (4, 0), ZZ) + Z50 = DDM([[]]*5, (5, 0), ZZ) + Z05 = DDM([], (0, 5), ZZ) + Z45 = DDM([[0] * 5] * 4, (4, 5), ZZ) + Z54 = DDM([[0] * 4] * 5, (5, 4), ZZ) + Z00 = DDM([], (0, 0), ZZ) + + assert Z04 @ Z45 == Z04.matmul(Z45) == Z05 + assert Z45 @ Z50 == Z45.matmul(Z50) == Z40 + assert Z00 @ Z04 == Z00.matmul(Z04) == Z04 + assert Z50 @ Z00 == Z50.matmul(Z00) == Z50 + assert Z00 @ Z00 == Z00.matmul(Z00) == Z00 + assert Z50 @ Z04 == Z50.matmul(Z04) == Z54 + + raises(DMShapeError, lambda: Z05 @ Z40) + raises(DMShapeError, lambda: Z05.matmul(Z40)) + + +def test_DDM_hstack(): + A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ) + B = DDM([[ZZ(4), ZZ(5)]], (1, 2), ZZ) + C = DDM([[ZZ(6)]], (1, 1), ZZ) + + Ah = A.hstack(B) + assert Ah.shape == (1, 5) + assert Ah.domain == ZZ + assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5)]], (1, 5), ZZ) + + Ah = A.hstack(B, C) + assert Ah.shape == (1, 6) + assert Ah.domain == ZZ + assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5), ZZ(6)]], (1, 6), ZZ) + + +def test_DDM_vstack(): + A = DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)]], (3, 1), ZZ) + B = DDM([[ZZ(4)], [ZZ(5)]], (2, 1), ZZ) + C = DDM([[ZZ(6)]], (1, 1), ZZ) + + Ah = A.vstack(B) + assert Ah.shape == (5, 1) + assert Ah.domain == ZZ + assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)]], (5, 1), ZZ) + + Ah = A.vstack(B, C) + assert Ah.shape == (6, 1) + assert Ah.domain == ZZ + assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)], [ZZ(6)]], (6, 1), ZZ) + + +def test_DDM_applyfunc(): + A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ) + B = DDM([[ZZ(2), ZZ(4), ZZ(6)]], (1, 3), ZZ) + assert A.applyfunc(lambda x: 2*x, ZZ) == B + +def test_DDM_rref(): + + A = DDM([], (0, 4), QQ) + assert A.rref() == (A, []) + + A = DDM([[QQ(0), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) + Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) + pivots = [0, 1] + assert A.rref() == (Ar, pivots) + + A = DDM([[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]], (2, 3), QQ) + Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ) + pivots = [0, 1] + assert A.rref() == (Ar, pivots) + + A = DDM([[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]], (2, 3), QQ) + Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ) + pivots = [0, 1] + assert A.rref() == (Ar, pivots) + + A = DDM([[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]], (3, 2), QQ) + Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]], (3, 2), QQ) + pivots = [0, 1] + assert A.rref() == (Ar, pivots) + + A = DDM([[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]], (2, 3), QQ) + Ar = DDM([[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]], (2, 3), QQ) + pivots = [0, 2] + assert A.rref() == (Ar, pivots) + + +def test_DDM_nullspace(): + # more tests are in test_nullspace.py + A = DDM([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) + Anull = DDM([[QQ(-1), QQ(1)]], (1, 2), QQ) + nonpivots = [1] + assert A.nullspace() == (Anull, nonpivots) + + +def test_DDM_particular(): + A = DDM([[QQ(1), QQ(0)]], (1, 2), QQ) + assert A.particular() == DDM.zeros((1, 1), QQ) + + +def test_DDM_det(): + # 0x0 case + A = DDM([], (0, 0), ZZ) + assert A.det() == ZZ(1) + + # 1x1 case + A = DDM([[ZZ(2)]], (1, 1), ZZ) + assert A.det() == ZZ(2) + + # 2x2 case + A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.det() == ZZ(-2) + + # 3x3 with swap + A = DDM([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ) + assert A.det() == ZZ(0) + + # 2x2 QQ case + A = DDM([[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]], (2, 2), QQ) + assert A.det() == QQ(-1, 24) + + # Nonsquare error + A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + raises(DMShapeError, lambda: A.det()) + + # Nonsquare error with empty matrix + A = DDM([], (0, 1), ZZ) + raises(DMShapeError, lambda: A.det()) + + +def test_DDM_inv(): + A = DDM([[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]], (2, 2), QQ) + Ainv = DDM([[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ) + assert A.inv() == Ainv + + A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) + raises(DMShapeError, lambda: A.inv()) + + A = DDM([[ZZ(2)]], (1, 1), ZZ) + raises(DMDomainError, lambda: A.inv()) + + A = DDM([], (0, 0), QQ) + assert A.inv() == A + + A = DDM([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) + raises(DMNonInvertibleMatrixError, lambda: A.inv()) + + +def test_DDM_lu(): + A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + L, U, swaps = A.lu() + assert L == DDM([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ) + assert U == DDM([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ) + assert swaps == [] + + A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]] + Lexp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]] + Uexp = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]] + to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows] + A = DDM(to_dom(A, QQ), (4, 4), QQ) + Lexp = DDM(to_dom(Lexp, QQ), (4, 4), QQ) + Uexp = DDM(to_dom(Uexp, QQ), (4, 4), QQ) + L, U, swaps = A.lu() + assert L == Lexp + assert U == Uexp + assert swaps == [] + + +def test_DDM_lu_solve(): + # Basic example + A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + x = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) + assert A.lu_solve(b) == x + + # Example with swaps + A = DDM([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + assert A.lu_solve(b) == x + + # Overdetermined, consistent + A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) + b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) + assert A.lu_solve(b) == x + + # Overdetermined, inconsistent + b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) + raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) + + # Square, noninvertible + A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) + b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) + + # Underdetermined + A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) + b = DDM([[QQ(3)]], (1, 1), QQ) + raises(NotImplementedError, lambda: A.lu_solve(b)) + + # Domain mismatch + bz = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + raises(DMDomainError, lambda: A.lu_solve(bz)) + + # Shape mismatch + b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) + raises(DMShapeError, lambda: A.lu_solve(b3)) + + +def test_DDM_charpoly(): + A = DDM([], (0, 0), ZZ) + assert A.charpoly() == [ZZ(1)] + + A = DDM([ + [ZZ(1), ZZ(2), ZZ(3)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) + Avec = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)] + assert A.charpoly() == Avec + + A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: A.charpoly()) + + +def test_DDM_getitem(): + dm = DDM([ + [ZZ(1), ZZ(2), ZZ(3)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) + + assert dm.getitem(1, 1) == ZZ(5) + assert dm.getitem(1, -2) == ZZ(5) + assert dm.getitem(-1, -3) == ZZ(7) + + raises(IndexError, lambda: dm.getitem(3, 3)) + + +def test_DDM_setitem(): + dm = DDM.zeros((3, 3), ZZ) + dm.setitem(0, 0, 1) + dm.setitem(1, -2, 1) + dm.setitem(-1, -1, 1) + assert dm == DDM.eye(3, ZZ) + + raises(IndexError, lambda: dm.setitem(3, 3, 0)) + + +def test_DDM_extract_slice(): + dm = DDM([ + [ZZ(1), ZZ(2), ZZ(3)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) + + assert dm.extract_slice(slice(0, 3), slice(0, 3)) == dm + assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ) + assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ) + assert dm.extract_slice(slice(2, 3), slice(-2)) == DDM([[ZZ(7)]], (1, 1), ZZ) + assert dm.extract_slice(slice(0, 2), slice(-2)) == DDM([[1], [4]], (2, 1), ZZ) + assert dm.extract_slice(slice(-1), slice(-1)) == DDM([[1, 2], [4, 5]], (2, 2), ZZ) + + assert dm.extract_slice(slice(2), slice(3, 4)) == DDM([[], []], (2, 0), ZZ) + assert dm.extract_slice(slice(3, 4), slice(2)) == DDM([], (0, 2), ZZ) + assert dm.extract_slice(slice(3, 4), slice(3, 4)) == DDM([], (0, 0), ZZ) + + +def test_DDM_extract(): + dm1 = DDM([ + [ZZ(1), ZZ(2), ZZ(3)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) + dm2 = DDM([ + [ZZ(6), ZZ(4)], + [ZZ(3), ZZ(1)]], (2, 2), ZZ) + assert dm1.extract([1, 0], [2, 0]) == dm2 + assert dm1.extract([-2, 0], [-1, 0]) == dm2 + + assert dm1.extract([], []) == DDM.zeros((0, 0), ZZ) + assert dm1.extract([1], []) == DDM.zeros((1, 0), ZZ) + assert dm1.extract([], [1]) == DDM.zeros((0, 1), ZZ) + + raises(IndexError, lambda: dm2.extract([2], [0])) + raises(IndexError, lambda: dm2.extract([0], [2])) + raises(IndexError, lambda: dm2.extract([-3], [0])) + raises(IndexError, lambda: dm2.extract([0], [-3])) + + +def test_DDM_flat(): + dm = DDM([ + [ZZ(6), ZZ(4)], + [ZZ(3), ZZ(1)]], (2, 2), ZZ) + assert dm.flat() == [ZZ(6), ZZ(4), ZZ(3), ZZ(1)] + + +def test_DDM_is_zero_matrix(): + A = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ) + Azero = DDM.zeros((1, 2), QQ) + assert A.is_zero_matrix() is False + assert Azero.is_zero_matrix() is True + + +def test_DDM_is_upper(): + # Wide matrices: + A = DDM([ + [QQ(1), QQ(2), QQ(3), QQ(4)], + [QQ(0), QQ(5), QQ(6), QQ(7)], + [QQ(0), QQ(0), QQ(8), QQ(9)] + ], (3, 4), QQ) + B = DDM([ + [QQ(1), QQ(2), QQ(3), QQ(4)], + [QQ(0), QQ(5), QQ(6), QQ(7)], + [QQ(0), QQ(7), QQ(8), QQ(9)] + ], (3, 4), QQ) + assert A.is_upper() is True + assert B.is_upper() is False + + # Tall matrices: + A = DDM([ + [QQ(1), QQ(2), QQ(3)], + [QQ(0), QQ(5), QQ(6)], + [QQ(0), QQ(0), QQ(8)], + [QQ(0), QQ(0), QQ(0)] + ], (4, 3), QQ) + B = DDM([ + [QQ(1), QQ(2), QQ(3)], + [QQ(0), QQ(5), QQ(6)], + [QQ(0), QQ(0), QQ(8)], + [QQ(0), QQ(0), QQ(10)] + ], (4, 3), QQ) + assert A.is_upper() is True + assert B.is_upper() is False + + +def test_DDM_is_lower(): + # Tall matrices: + A = DDM([ + [QQ(1), QQ(2), QQ(3), QQ(4)], + [QQ(0), QQ(5), QQ(6), QQ(7)], + [QQ(0), QQ(0), QQ(8), QQ(9)] + ], (3, 4), QQ).transpose() + B = DDM([ + [QQ(1), QQ(2), QQ(3), QQ(4)], + [QQ(0), QQ(5), QQ(6), QQ(7)], + [QQ(0), QQ(7), QQ(8), QQ(9)] + ], (3, 4), QQ).transpose() + assert A.is_lower() is True + assert B.is_lower() is False + + # Wide matrices: + A = DDM([ + [QQ(1), QQ(2), QQ(3)], + [QQ(0), QQ(5), QQ(6)], + [QQ(0), QQ(0), QQ(8)], + [QQ(0), QQ(0), QQ(0)] + ], (4, 3), QQ).transpose() + B = DDM([ + [QQ(1), QQ(2), QQ(3)], + [QQ(0), QQ(5), QQ(6)], + [QQ(0), QQ(0), QQ(8)], + [QQ(0), QQ(0), QQ(10)] + ], (4, 3), QQ).transpose() + assert A.is_lower() is True + assert B.is_lower() is False diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_dense.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_dense.py new file mode 100644 index 0000000000000000000000000000000000000000..75315ebf6b2ae7d53b4a5737578d3ac5ed4ea36a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_dense.py @@ -0,0 +1,350 @@ +from sympy.testing.pytest import raises + +from sympy.polys import ZZ, QQ + +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.dense import ( + ddm_transpose, + ddm_iadd, ddm_isub, ddm_ineg, ddm_imatmul, ddm_imul, ddm_irref, + ddm_idet, ddm_iinv, ddm_ilu, ddm_ilu_split, ddm_ilu_solve, ddm_berk) + +from sympy.polys.matrices.exceptions import ( + DMDomainError, + DMNonInvertibleMatrixError, + DMNonSquareMatrixError, + DMShapeError, +) + + +def test_ddm_transpose(): + a = [[1, 2], [3, 4]] + assert ddm_transpose(a) == [[1, 3], [2, 4]] + + +def test_ddm_iadd(): + a = [[1, 2], [3, 4]] + b = [[5, 6], [7, 8]] + ddm_iadd(a, b) + assert a == [[6, 8], [10, 12]] + + +def test_ddm_isub(): + a = [[1, 2], [3, 4]] + b = [[5, 6], [7, 8]] + ddm_isub(a, b) + assert a == [[-4, -4], [-4, -4]] + + +def test_ddm_ineg(): + a = [[1, 2], [3, 4]] + ddm_ineg(a) + assert a == [[-1, -2], [-3, -4]] + + +def test_ddm_matmul(): + a = [[1, 2], [3, 4]] + ddm_imul(a, 2) + assert a == [[2, 4], [6, 8]] + + a = [[1, 2], [3, 4]] + ddm_imul(a, 0) + assert a == [[0, 0], [0, 0]] + + +def test_ddm_imatmul(): + a = [[1, 2, 3], [4, 5, 6]] + b = [[1, 2], [3, 4], [5, 6]] + + c1 = [[0, 0], [0, 0]] + ddm_imatmul(c1, a, b) + assert c1 == [[22, 28], [49, 64]] + + c2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] + ddm_imatmul(c2, b, a) + assert c2 == [[9, 12, 15], [19, 26, 33], [29, 40, 51]] + + b3 = [[1], [2], [3]] + c3 = [[0], [0]] + ddm_imatmul(c3, a, b3) + assert c3 == [[14], [32]] + + +def test_ddm_irref(): + # Empty matrix + A = [] + Ar = [] + pivots = [] + assert ddm_irref(A) == pivots + assert A == Ar + + # Standard square case + A = [[QQ(0), QQ(1)], [QQ(1), QQ(1)]] + Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] + pivots = [0, 1] + assert ddm_irref(A) == pivots + assert A == Ar + + # m < n case + A = [[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]] + Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]] + pivots = [0, 1] + assert ddm_irref(A) == pivots + assert A == Ar + + # same m < n but reversed + A = [[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]] + Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]] + pivots = [0, 1] + assert ddm_irref(A) == pivots + assert A == Ar + + # m > n case + A = [[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]] + Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]] + pivots = [0, 1] + assert ddm_irref(A) == pivots + assert A == Ar + + # Example with missing pivot + A = [[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]] + Ar = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]] + pivots = [0, 2] + assert ddm_irref(A) == pivots + assert A == Ar + + # Example with missing pivot and no replacement + A = [[QQ(0), QQ(1)], [QQ(0), QQ(2)], [QQ(1), QQ(0)]] + Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]] + pivots = [0, 1] + assert ddm_irref(A) == pivots + assert A == Ar + + +def test_ddm_idet(): + A = [] + assert ddm_idet(A, ZZ) == ZZ(1) + + A = [[ZZ(2)]] + assert ddm_idet(A, ZZ) == ZZ(2) + + A = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] + assert ddm_idet(A, ZZ) == ZZ(-2) + + A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]] + assert ddm_idet(A, ZZ) == ZZ(-1) + + A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]] + assert ddm_idet(A, ZZ) == ZZ(0) + + A = [[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]] + assert ddm_idet(A, QQ) == QQ(-1, 24) + + +def test_ddm_inv(): + A = [] + Ainv = [] + ddm_iinv(Ainv, A, QQ) + assert Ainv == A + + A = [] + Ainv = [] + raises(DMDomainError, lambda: ddm_iinv(Ainv, A, ZZ)) + + A = [[QQ(1), QQ(2)]] + Ainv = [[QQ(0), QQ(0)]] + raises(DMNonSquareMatrixError, lambda: ddm_iinv(Ainv, A, QQ)) + + A = [[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]] + Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]] + Ainv_expected = [[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]] + ddm_iinv(Ainv, A, QQ) + assert Ainv == Ainv_expected + + A = [[QQ(1, 1), QQ(2, 1)], [QQ(2, 1), QQ(4, 1)]] + Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]] + raises(DMNonInvertibleMatrixError, lambda: ddm_iinv(Ainv, A, QQ)) + + +def test_ddm_ilu(): + A = [] + Alu = [] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [] + + A = [[]] + Alu = [[]] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [] + + A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] + Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)]] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [] + + A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]] + Alu = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [(0, 1)] + + A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)], [QQ(7), QQ(8), QQ(9)]] + Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)], [QQ(7), QQ(2), QQ(0)]] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [] + + A = [[QQ(0), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(1), QQ(1), QQ(2)]] + Alu = [[QQ(1), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(0), QQ(1), QQ(-1)]] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [(0, 2)] + + A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]] + Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)]] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [] + + A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]] + Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)], [QQ(5), QQ(2)]] + swaps = ddm_ilu(A) + assert A == Alu + assert swaps == [] + + +def test_ddm_ilu_split(): + U = [] + L = [] + Uexp = [] + Lexp = [] + swaps = ddm_ilu_split(L, U, QQ) + assert U == Uexp + assert L == Lexp + assert swaps == [] + + U = [[]] + L = [[QQ(1)]] + Uexp = [[]] + Lexp = [[QQ(1)]] + swaps = ddm_ilu_split(L, U, QQ) + assert U == Uexp + assert L == Lexp + assert swaps == [] + + U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] + L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] + Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]] + Lexp = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]] + swaps = ddm_ilu_split(L, U, QQ) + assert U == Uexp + assert L == Lexp + assert swaps == [] + + U = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]] + L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] + Uexp = [[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]] + Lexp = [[QQ(1), QQ(0)], [QQ(4), QQ(1)]] + swaps = ddm_ilu_split(L, U, QQ) + assert U == Uexp + assert L == Lexp + assert swaps == [] + + U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]] + L = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(1), QQ(0)], [QQ(0), QQ(0), QQ(1)]] + Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]] + Lexp = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]] + swaps = ddm_ilu_split(L, U, QQ) + assert U == Uexp + assert L == Lexp + assert swaps == [] + + +def test_ddm_ilu_solve(): + # Basic example + # A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] + U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]] + L = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]] + swaps = [] + b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ) + xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) + ddm_ilu_solve(x, L, U, swaps, b) + assert x == xexp + + # Example with swaps + # A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]] + U = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]] + L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] + swaps = [(0, 1)] + b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ) + xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) + ddm_ilu_solve(x, L, U, swaps, b) + assert x == xexp + + # Overdetermined, consistent + # A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) + U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]] + L = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]] + swaps = [] + b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) + x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ) + xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) + ddm_ilu_solve(x, L, U, swaps, b) + assert x == xexp + + # Overdetermined, inconsistent + b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) + raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) + + # Square, noninvertible + # A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) + U = [[QQ(1), QQ(2)], [QQ(0), QQ(0)]] + L = [[QQ(1), QQ(0)], [QQ(1), QQ(1)]] + swaps = [] + b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) + raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) + + # Underdetermined + # A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) + U = [[QQ(1), QQ(2)]] + L = [[QQ(1)]] + swaps = [] + b = DDM([[QQ(3)]], (1, 1), QQ) + raises(NotImplementedError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) + + # Shape mismatch + b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) + raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b3)) + + # Empty shape mismatch + U = [[QQ(1)]] + L = [[QQ(1)]] + swaps = [] + x = [[QQ(1)]] + b = [] + raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) + + # Empty system + U = [] + L = [] + swaps = [] + b = [] + x = [] + ddm_ilu_solve(x, L, U, swaps, b) + assert x == [] + + +def test_ddm_charpoly(): + A = [] + assert ddm_berk(A, ZZ) == [[ZZ(1)]] + + A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]] + Avec = [[ZZ(1)], [ZZ(-15)], [ZZ(-18)], [ZZ(0)]] + assert ddm_berk(A, ZZ) == Avec + + A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: ddm_berk(A, ZZ)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..2f45029fb080ca91e98ea04aa4717fa675492052 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py @@ -0,0 +1,1383 @@ +from sympy.external.gmpy import GROUND_TYPES + +from sympy import Integer, Rational, S, sqrt, Matrix, symbols +from sympy import FF, ZZ, QQ, QQ_I, EXRAW + +from sympy.polys.matrices.domainmatrix import DomainMatrix, DomainScalar, DM +from sympy.polys.matrices.exceptions import ( + DMBadInputError, DMDomainError, DMShapeError, DMFormatError, DMNotAField, + DMNonSquareMatrixError, DMNonInvertibleMatrixError, +) +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.sdm import SDM + +from sympy.testing.pytest import raises + + +def test_DM(): + ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A = DM([[1, 2], [3, 4]], ZZ) + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == ZZ + + +def test_DomainMatrix_init(): + lol = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] + dod = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}} + ddm = DDM(lol, (2, 2), ZZ) + sdm = SDM(dod, (2, 2), ZZ) + + A = DomainMatrix(lol, (2, 2), ZZ) + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == ZZ + + A = DomainMatrix(dod, (2, 2), ZZ) + assert A.rep == sdm + assert A.shape == (2, 2) + assert A.domain == ZZ + + raises(TypeError, lambda: DomainMatrix(ddm, (2, 2), ZZ)) + raises(TypeError, lambda: DomainMatrix(sdm, (2, 2), ZZ)) + raises(TypeError, lambda: DomainMatrix(Matrix([[1]]), (1, 1), ZZ)) + + for fmt, rep in [('sparse', sdm), ('dense', ddm)]: + if fmt == 'dense' and GROUND_TYPES == 'flint': + rep = rep.to_dfm() + A = DomainMatrix(lol, (2, 2), ZZ, fmt=fmt) + assert A.rep == rep + A = DomainMatrix(dod, (2, 2), ZZ, fmt=fmt) + assert A.rep == rep + + raises(ValueError, lambda: DomainMatrix(lol, (2, 2), ZZ, fmt='invalid')) + + raises(DMBadInputError, lambda: DomainMatrix([[ZZ(1), ZZ(2)]], (2, 2), ZZ)) + + # uses copy + was = [i.copy() for i in lol] + A[0,0] = ZZ(42) + assert was == lol + + +def test_DomainMatrix_from_rep(): + ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A = DomainMatrix.from_rep(ddm) + # XXX: Should from_rep convert to DFM? + assert A.rep == ddm + assert A.shape == (2, 2) + assert A.domain == ZZ + + sdm = SDM({0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) + A = DomainMatrix.from_rep(sdm) + assert A.rep == sdm + assert A.shape == (2, 2) + assert A.domain == ZZ + + A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ) + raises(TypeError, lambda: DomainMatrix.from_rep(A)) + + +def test_DomainMatrix_from_list(): + ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A = DomainMatrix.from_list([[1, 2], [3, 4]], ZZ) + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == ZZ + + dom = FF(7) + ddm = DDM([[dom(1), dom(2)], [dom(3), dom(4)]], (2, 2), dom) + A = DomainMatrix.from_list([[1, 2], [3, 4]], dom) + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == dom + + dom = FF(2**127-1) + ddm = DDM([[dom(1), dom(2)], [dom(3), dom(4)]], (2, 2), dom) + A = DomainMatrix.from_list([[1, 2], [3, 4]], dom) + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == dom + + ddm = DDM([[QQ(1, 2), QQ(3, 1)], [QQ(1, 4), QQ(5, 1)]], (2, 2), QQ) + A = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ) + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == QQ + + +def test_DomainMatrix_from_list_sympy(): + ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A = DomainMatrix.from_list_sympy(2, 2, [[1, 2], [3, 4]]) + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == ZZ + + K = QQ.algebraic_field(sqrt(2)) + ddm = DDM( + [[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))], + [K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]], + (2, 2), + K + ) + A = DomainMatrix.from_list_sympy( + 2, 2, [[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]], + extension=True) + assert A.rep == ddm + assert A.shape == (2, 2) + assert A.domain == K + + +def test_DomainMatrix_from_dict_sympy(): + sdm = SDM({0: {0: QQ(1, 2)}, 1: {1: QQ(2, 3)}}, (2, 2), QQ) + sympy_dict = {0: {0: Rational(1, 2)}, 1: {1: Rational(2, 3)}} + A = DomainMatrix.from_dict_sympy(2, 2, sympy_dict) + assert A.rep == sdm + assert A.shape == (2, 2) + assert A.domain == QQ + + fds = DomainMatrix.from_dict_sympy + raises(DMBadInputError, lambda: fds(2, 2, {3: {0: Rational(1, 2)}})) + raises(DMBadInputError, lambda: fds(2, 2, {0: {3: Rational(1, 2)}})) + + +def test_DomainMatrix_from_Matrix(): + sdm = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ) + A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]])) + assert A.rep == sdm + assert A.shape == (2, 2) + assert A.domain == ZZ + + K = QQ.algebraic_field(sqrt(2)) + sdm = SDM( + {0: {0: K.convert(1 + sqrt(2)), 1: K.convert(2 + sqrt(2))}, + 1: {0: K.convert(3 + sqrt(2)), 1: K.convert(4 + sqrt(2))}}, + (2, 2), + K + ) + A = DomainMatrix.from_Matrix( + Matrix([[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]]), + extension=True) + assert A.rep == sdm + assert A.shape == (2, 2) + assert A.domain == K + + A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense') + ddm = DDM([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]], (2, 2), QQ) + + if GROUND_TYPES != 'flint': + assert A.rep == ddm + else: + assert A.rep == ddm.to_dfm() + assert A.shape == (2, 2) + assert A.domain == QQ + + +def test_DomainMatrix_eq(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A == A + B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(1)]], (2, 2), ZZ) + assert A != B + C = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] + assert A != C + + +def test_DomainMatrix_unify_eq(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + B1 = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + B2 = DomainMatrix([[QQ(1), QQ(3)], [QQ(3), QQ(4)]], (2, 2), QQ) + B3 = DomainMatrix([[ZZ(1)]], (1, 1), ZZ) + assert A.unify_eq(B1) is True + assert A.unify_eq(B2) is False + assert A.unify_eq(B3) is False + + +def test_DomainMatrix_get_domain(): + K, items = DomainMatrix.get_domain([1, 2, 3, 4]) + assert items == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] + assert K == ZZ + + K, items = DomainMatrix.get_domain([1, 2, 3, Rational(1, 2)]) + assert items == [QQ(1), QQ(2), QQ(3), QQ(1, 2)] + assert K == QQ + + +def test_DomainMatrix_convert_to(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Aq = A.convert_to(QQ) + assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + + +def test_DomainMatrix_choose_domain(): + A = [[1, 2], [3, 0]] + assert DM(A, QQ).choose_domain() == DM(A, ZZ) + assert DM(A, QQ).choose_domain(field=True) == DM(A, QQ) + assert DM(A, ZZ).choose_domain(field=True) == DM(A, QQ) + + x = symbols('x') + B = [[1, x], [x**2, x**3]] + assert DM(B, QQ[x]).choose_domain(field=True) == DM(B, ZZ.frac_field(x)) + + +def test_DomainMatrix_to_flat_nz(): + Adm = DM([[1, 2], [3, 0]], ZZ) + Addm = Adm.rep.to_ddm() + Asdm = Adm.rep.to_sdm() + for A in [Adm, Addm, Asdm]: + elems, data = A.to_flat_nz() + assert A.from_flat_nz(elems, data, A.domain) == A + elemsq = [QQ(e) for e in elems] + assert A.from_flat_nz(elemsq, data, QQ) == A.convert_to(QQ) + elems2 = [2*e for e in elems] + assert A.from_flat_nz(elems2, data, A.domain) == 2*A + + +def test_DomainMatrix_to_sympy(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.to_sympy() == A.convert_to(EXRAW) + + +def test_DomainMatrix_to_field(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Aq = A.to_field() + assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + + +def test_DomainMatrix_to_sparse(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A_sparse = A.to_sparse() + assert A_sparse.rep == {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}} + + +def test_DomainMatrix_to_dense(): + A = DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) + A_dense = A.to_dense() + ddm = DDM([[1, 2], [3, 4]], (2, 2), ZZ) + if GROUND_TYPES != 'flint': + assert A_dense.rep == ddm + else: + assert A_dense.rep == ddm.to_dfm() + + +def test_DomainMatrix_unify(): + Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + assert Az.unify(Az) == (Az, Az) + assert Az.unify(Aq) == (Aq, Aq) + assert Aq.unify(Az) == (Aq, Aq) + assert Aq.unify(Aq) == (Aq, Aq) + + As = DomainMatrix({0: {1: ZZ(1)}, 1:{0:ZZ(2)}}, (2, 2), ZZ) + Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + assert As.unify(As) == (As, As) + assert Ad.unify(Ad) == (Ad, Ad) + + Bs, Bd = As.unify(Ad, fmt='dense') + assert Bs.rep == DDM([[0, 1], [2, 0]], (2, 2), ZZ).to_dfm_or_ddm() + assert Bd.rep == DDM([[1, 2],[3, 4]], (2, 2), ZZ).to_dfm_or_ddm() + + Bs, Bd = As.unify(Ad, fmt='sparse') + assert Bs.rep == SDM({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ) + assert Bd.rep == SDM({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) + + raises(ValueError, lambda: As.unify(Ad, fmt='invalid')) + + +def test_DomainMatrix_to_Matrix(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A_Matrix = Matrix([[1, 2], [3, 4]]) + assert A.to_Matrix() == A_Matrix + assert A.to_sparse().to_Matrix() == A_Matrix + assert A.convert_to(QQ).to_Matrix() == A_Matrix + assert A.convert_to(QQ.algebraic_field(sqrt(2))).to_Matrix() == A_Matrix + + +def test_DomainMatrix_to_list(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.to_list() == [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] + + +def test_DomainMatrix_to_list_flat(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.to_list_flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] + + +def test_DomainMatrix_flat(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] + + +def test_DomainMatrix_from_list_flat(): + nums = [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + assert DomainMatrix.from_list_flat(nums, (2, 2), ZZ) == A + assert DDM.from_list_flat(nums, (2, 2), ZZ) == A.rep.to_ddm() + assert SDM.from_list_flat(nums, (2, 2), ZZ) == A.rep.to_sdm() + + assert A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain) + + raises(DMBadInputError, DomainMatrix.from_list_flat, nums, (2, 3), ZZ) + raises(DMBadInputError, DDM.from_list_flat, nums, (2, 3), ZZ) + raises(DMBadInputError, SDM.from_list_flat, nums, (2, 3), ZZ) + + +def test_DomainMatrix_to_dod(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.to_dod() == {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}} + A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(4)]], (2, 2), ZZ) + assert A.to_dod() == {0: {0: ZZ(1)}, 1: {1: ZZ(4)}} + + +def test_DomainMatrix_from_dod(): + items = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}} + A = DM([[1, 2], [3, 4]], ZZ) + assert DomainMatrix.from_dod(items, (2, 2), ZZ) == A.to_sparse() + assert A.from_dod_like(items) == A + assert A.from_dod_like(items, QQ) == A.convert_to(QQ) + + +def test_DomainMatrix_to_dok(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.to_dok() == {(0, 0):ZZ(1), (0, 1):ZZ(2), (1, 0):ZZ(3), (1, 1):ZZ(4)} + A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(4)]], (2, 2), ZZ) + dok = {(0, 0):ZZ(1), (1, 1):ZZ(4)} + assert A.to_dok() == dok + assert A.to_dense().to_dok() == dok + assert A.to_sparse().to_dok() == dok + assert A.rep.to_ddm().to_dok() == dok + assert A.rep.to_sdm().to_dok() == dok + + +def test_DomainMatrix_from_dok(): + items = {(0, 0): ZZ(1), (1, 1): ZZ(2)} + A = DM([[1, 0], [0, 2]], ZZ) + assert DomainMatrix.from_dok(items, (2, 2), ZZ) == A.to_sparse() + assert DDM.from_dok(items, (2, 2), ZZ) == A.rep.to_ddm() + assert SDM.from_dok(items, (2, 2), ZZ) == A.rep.to_sdm() + + +def test_DomainMatrix_repr(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert repr(A) == 'DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)' + + +def test_DomainMatrix_transpose(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + AT = DomainMatrix([[ZZ(1), ZZ(3)], [ZZ(2), ZZ(4)]], (2, 2), ZZ) + assert A.transpose() == AT + + +def test_DomainMatrix_is_zero_matrix(): + A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ) + B = DomainMatrix([[ZZ(0)]], (1, 1), ZZ) + assert A.is_zero_matrix is False + assert B.is_zero_matrix is True + + +def test_DomainMatrix_is_upper(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(0), ZZ(4)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.is_upper is True + assert B.is_upper is False + + +def test_DomainMatrix_is_lower(): + A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.is_lower is True + assert B.is_lower is False + + +def test_DomainMatrix_is_diagonal(): + A = DM([[1, 0], [0, 4]], ZZ) + B = DM([[1, 2], [3, 4]], ZZ) + assert A.is_diagonal is A.to_sparse().is_diagonal is True + assert B.is_diagonal is B.to_sparse().is_diagonal is False + + +def test_DomainMatrix_is_square(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]], (3, 2), ZZ) + assert A.is_square is True + assert B.is_square is False + + +def test_DomainMatrix_diagonal(): + A = DM([[1, 2], [3, 4]], ZZ) + assert A.diagonal() == A.to_sparse().diagonal() == [ZZ(1), ZZ(4)] + A = DM([[1, 2], [3, 4], [5, 6]], ZZ) + assert A.diagonal() == A.to_sparse().diagonal() == [ZZ(1), ZZ(4)] + A = DM([[1, 2, 3], [4, 5, 6]], ZZ) + assert A.diagonal() == A.to_sparse().diagonal() == [ZZ(1), ZZ(5)] + + +def test_DomainMatrix_rank(): + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(6), QQ(8)]], (3, 2), QQ) + assert A.rank() == 2 + + +def test_DomainMatrix_add(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) + assert A + A == A.add(A) == B + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + L = [[2, 3], [3, 4]] + raises(TypeError, lambda: A + L) + raises(TypeError, lambda: L + A) + + A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: A1 + A2) + raises(DMShapeError, lambda: A2 + A1) + raises(DMShapeError, lambda: A1.add(A2)) + raises(DMShapeError, lambda: A2.add(A1)) + + Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Asum = DomainMatrix([[QQ(2), QQ(4)], [QQ(6), QQ(8)]], (2, 2), QQ) + assert Az + Aq == Asum + assert Aq + Az == Asum + raises(DMDomainError, lambda: Az.add(Aq)) + raises(DMDomainError, lambda: Aq.add(Az)) + + As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) + Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + Asd = As + Ad + Ads = Ad + As + assert Asd == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ) + assert Asd.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ).to_dfm_or_ddm() + assert Ads == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ) + assert Ads.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ).to_dfm_or_ddm() + raises(DMFormatError, lambda: As.add(Ad)) + + +def test_DomainMatrix_sub(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) + assert A - A == A.sub(A) == B + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + L = [[2, 3], [3, 4]] + raises(TypeError, lambda: A - L) + raises(TypeError, lambda: L - A) + + A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: A1 - A2) + raises(DMShapeError, lambda: A2 - A1) + raises(DMShapeError, lambda: A1.sub(A2)) + raises(DMShapeError, lambda: A2.sub(A1)) + + Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Adiff = DomainMatrix([[QQ(0), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ) + assert Az - Aq == Adiff + assert Aq - Az == Adiff + raises(DMDomainError, lambda: Az.sub(Aq)) + raises(DMDomainError, lambda: Aq.sub(Az)) + + As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) + Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + Asd = As - Ad + Ads = Ad - As + assert Asd == DomainMatrix([[-1, -1], [-1, -4]], (2, 2), ZZ) + assert Asd.rep == DDM([[-1, -1], [-1, -4]], (2, 2), ZZ).to_dfm_or_ddm() + assert Asd == -Ads + assert Asd.rep == -Ads.rep + + +def test_DomainMatrix_neg(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Aneg = DomainMatrix([[ZZ(-1), ZZ(-2)], [ZZ(-3), ZZ(-4)]], (2, 2), ZZ) + assert -A == A.neg() == Aneg + + +def test_DomainMatrix_mul(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ) + assert A*A == A.matmul(A) == A2 + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + L = [[1, 2], [3, 4]] + raises(TypeError, lambda: A * L) + raises(TypeError, lambda: L * A) + + Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Aprod = DomainMatrix([[QQ(7), QQ(10)], [QQ(15), QQ(22)]], (2, 2), QQ) + assert Az * Aq == Aprod + assert Aq * Az == Aprod + raises(DMDomainError, lambda: Az.matmul(Aq)) + raises(DMDomainError, lambda: Aq.matmul(Az)) + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + AA = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) + x = ZZ(2) + assert A * x == x * A == A.mul(x) == AA + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + AA = DomainMatrix.zeros((2, 2), ZZ) + x = ZZ(0) + assert A * x == x * A == A.mul(x).to_sparse() == AA + + As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) + Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + + Asd = As * Ad + Ads = Ad * As + assert Asd == DomainMatrix([[3, 4], [2, 4]], (2, 2), ZZ) + assert Asd.rep == DDM([[3, 4], [2, 4]], (2, 2), ZZ).to_dfm_or_ddm() + assert Ads == DomainMatrix([[4, 1], [8, 3]], (2, 2), ZZ) + assert Ads.rep == DDM([[4, 1], [8, 3]], (2, 2), ZZ).to_dfm_or_ddm() + + +def test_DomainMatrix_mul_elementwise(): + A = DomainMatrix([[ZZ(2), ZZ(2)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(4), ZZ(0)], [ZZ(3), ZZ(0)]], (2, 2), ZZ) + C = DomainMatrix([[ZZ(8), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) + assert A.mul_elementwise(B) == C + assert B.mul_elementwise(A) == C + + +def test_DomainMatrix_pow(): + eye = DomainMatrix.eye(2, ZZ) + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ) + A3 = DomainMatrix([[ZZ(37), ZZ(54)], [ZZ(81), ZZ(118)]], (2, 2), ZZ) + assert A**0 == A.pow(0) == eye + assert A**1 == A.pow(1) == A + assert A**2 == A.pow(2) == A2 + assert A**3 == A.pow(3) == A3 + + raises(TypeError, lambda: A ** Rational(1, 2)) + raises(NotImplementedError, lambda: A ** -1) + raises(NotImplementedError, lambda: A.pow(-1)) + + A = DomainMatrix.zeros((2, 1), ZZ) + raises(DMNonSquareMatrixError, lambda: A ** 1) + + +def test_DomainMatrix_clear_denoms(): + A = DM([[(1,2),(1,3)],[(1,4),(1,5)]], QQ) + + den_Z = DomainScalar(ZZ(60), ZZ) + Anum_Z = DM([[30, 20], [15, 12]], ZZ) + Anum_Q = Anum_Z.convert_to(QQ) + + assert A.clear_denoms() == (den_Z, Anum_Q) + assert A.clear_denoms(convert=True) == (den_Z, Anum_Z) + assert A * den_Z == Anum_Q + assert A == Anum_Q / den_Z + + +def test_DomainMatrix_clear_denoms_rowwise(): + A = DM([[(1,2),(1,3)],[(1,4),(1,5)]], QQ) + + den_Z = DM([[6, 0], [0, 20]], ZZ).to_sparse() + Anum_Z = DM([[3, 2], [5, 4]], ZZ) + Anum_Q = DM([[3, 2], [5, 4]], QQ) + + assert A.clear_denoms_rowwise() == (den_Z, Anum_Q) + assert A.clear_denoms_rowwise(convert=True) == (den_Z, Anum_Z) + assert den_Z * A == Anum_Q + assert A == den_Z.to_field().inv() * Anum_Q + + A = DM([[(1,2),(1,3),0,0],[0,0,0,0], [(1,4),(1,5),(1,6),(1,7)]], QQ) + den_Z = DM([[6, 0, 0], [0, 1, 0], [0, 0, 420]], ZZ).to_sparse() + Anum_Z = DM([[3, 2, 0, 0], [0, 0, 0, 0], [105, 84, 70, 60]], ZZ) + Anum_Q = Anum_Z.convert_to(QQ) + + assert A.clear_denoms_rowwise() == (den_Z, Anum_Q) + assert A.clear_denoms_rowwise(convert=True) == (den_Z, Anum_Z) + assert den_Z * A == Anum_Q + assert A == den_Z.to_field().inv() * Anum_Q + + +def test_DomainMatrix_cancel_denom(): + A = DM([[2, 4], [6, 8]], ZZ) + assert A.cancel_denom(ZZ(1)) == (DM([[2, 4], [6, 8]], ZZ), ZZ(1)) + assert A.cancel_denom(ZZ(3)) == (DM([[2, 4], [6, 8]], ZZ), ZZ(3)) + assert A.cancel_denom(ZZ(4)) == (DM([[1, 2], [3, 4]], ZZ), ZZ(2)) + + A = DM([[1, 2], [3, 4]], ZZ) + assert A.cancel_denom(ZZ(2)) == (A, ZZ(2)) + assert A.cancel_denom(ZZ(-2)) == (-A, ZZ(2)) + + # Test canonicalization of denominator over Gaussian rationals. + A = DM([[1, 2], [3, 4]], QQ_I) + assert A.cancel_denom(QQ_I(0,2)) == (QQ_I(0,-1)*A, QQ_I(2)) + + raises(ZeroDivisionError, lambda: A.cancel_denom(ZZ(0))) + + +def test_DomainMatrix_cancel_denom_elementwise(): + A = DM([[2, 4], [6, 8]], ZZ) + numers, denoms = A.cancel_denom_elementwise(ZZ(1)) + assert numers == DM([[2, 4], [6, 8]], ZZ) + assert denoms == DM([[1, 1], [1, 1]], ZZ) + numers, denoms = A.cancel_denom_elementwise(ZZ(4)) + assert numers == DM([[1, 1], [3, 2]], ZZ) + assert denoms == DM([[2, 1], [2, 1]], ZZ) + + raises(ZeroDivisionError, lambda: A.cancel_denom_elementwise(ZZ(0))) + + +def test_DomainMatrix_content_primitive(): + A = DM([[2, 4], [6, 8]], ZZ) + A_primitive = DM([[1, 2], [3, 4]], ZZ) + A_content = ZZ(2) + assert A.content() == A_content + assert A.primitive() == (A_content, A_primitive) + + +def test_DomainMatrix_scc(): + Ad = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], + [ZZ(0), ZZ(1), ZZ(0)], + [ZZ(2), ZZ(0), ZZ(4)]], (3, 3), ZZ) + As = Ad.to_sparse() + Addm = Ad.rep + Asdm = As.rep + for A in [Ad, As, Addm, Asdm]: + assert Ad.scc() == [[1], [0, 2]] + + A = DM([[ZZ(1), ZZ(2), ZZ(3)]], ZZ) + raises(DMNonSquareMatrixError, lambda: A.scc()) + + +def test_DomainMatrix_rref(): + # More tests in test_rref.py + A = DomainMatrix([], (0, 1), QQ) + assert A.rref() == (A, ()) + + A = DomainMatrix([[QQ(1)]], (1, 1), QQ) + assert A.rref() == (A, (0,)) + + A = DomainMatrix([[QQ(0)]], (1, 1), QQ) + assert A.rref() == (A, ()) + + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Ar, pivots = A.rref() + assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) + assert pivots == (0, 1) + + A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Ar, pivots = A.rref() + assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) + assert pivots == (0, 1) + + A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) + Ar, pivots = A.rref() + assert Ar == DomainMatrix([[QQ(0), QQ(1)], [QQ(0), QQ(0)]], (2, 2), QQ) + assert pivots == (1,) + + Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + Ar, pivots = Az.rref() + assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) + assert pivots == (0, 1) + + methods = ('auto', 'GJ', 'FF', 'CD', 'GJ_dense', 'FF_dense', 'CD_dense') + Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + for method in methods: + Ar, pivots = Az.rref(method=method) + assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) + assert pivots == (0, 1) + + raises(ValueError, lambda: Az.rref(method='foo')) + raises(ValueError, lambda: Az.rref_den(method='foo')) + + +def test_DomainMatrix_columnspace(): + A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ) + Acol = DomainMatrix([[QQ(1), QQ(1)], [QQ(2), QQ(3)]], (2, 2), QQ) + assert A.columnspace() == Acol + + Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ) + raises(DMNotAField, lambda: Az.columnspace()) + + A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse') + Acol = DomainMatrix({0: {0: QQ(1), 1: QQ(1)}, 1: {0: QQ(2), 1: QQ(3)}}, (2, 2), QQ) + assert A.columnspace() == Acol + + +def test_DomainMatrix_rowspace(): + A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ) + assert A.rowspace() == A + + Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ) + raises(DMNotAField, lambda: Az.rowspace()) + + A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse') + assert A.rowspace() == A + + +def test_DomainMatrix_nullspace(): + A = DomainMatrix([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) + Anull = DomainMatrix([[QQ(-1), QQ(1)]], (1, 2), QQ) + assert A.nullspace() == Anull + + A = DomainMatrix([[ZZ(1), ZZ(1)], [ZZ(1), ZZ(1)]], (2, 2), ZZ) + Anull = DomainMatrix([[ZZ(-1), ZZ(1)]], (1, 2), ZZ) + assert A.nullspace() == Anull + + raises(DMNotAField, lambda: A.nullspace(divide_last=True)) + + A = DomainMatrix([[ZZ(2), ZZ(2)], [ZZ(2), ZZ(2)]], (2, 2), ZZ) + Anull = DomainMatrix([[ZZ(-2), ZZ(2)]], (1, 2), ZZ) + + Arref, den, pivots = A.rref_den() + assert den == ZZ(2) + assert Arref.nullspace_from_rref() == Anull + assert Arref.nullspace_from_rref(pivots) == Anull + assert Arref.to_sparse().nullspace_from_rref() == Anull.to_sparse() + assert Arref.to_sparse().nullspace_from_rref(pivots) == Anull.to_sparse() + + +def test_DomainMatrix_solve(): + # XXX: Maybe the _solve method should be changed... + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) + b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) + particular = DomainMatrix([[1, 0]], (1, 2), QQ) + nullspace = DomainMatrix([[-2, 1]], (1, 2), QQ) + assert A._solve(b) == (particular, nullspace) + + b3 = DomainMatrix([[QQ(1)], [QQ(1)], [QQ(1)]], (3, 1), QQ) + raises(DMShapeError, lambda: A._solve(b3)) + + bz = DomainMatrix([[ZZ(1)], [ZZ(1)]], (2, 1), ZZ) + raises(DMNotAField, lambda: A._solve(bz)) + + +def test_DomainMatrix_inv(): + A = DomainMatrix([], (0, 0), QQ) + assert A.inv() == A + + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Ainv = DomainMatrix([[QQ(-2), QQ(1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ) + assert A.inv() == Ainv + + Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + raises(DMNotAField, lambda: Az.inv()) + + Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) + raises(DMNonSquareMatrixError, lambda: Ans.inv()) + + Aninv = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(6)]], (2, 2), QQ) + raises(DMNonInvertibleMatrixError, lambda: Aninv.inv()) + + Z3 = FF(3) + assert DM([[1, 2], [3, 4]], Z3).inv() == DM([[1, 1], [0, 1]], Z3) + + Z6 = FF(6) + raises(DMNotAField, lambda: DM([[1, 2], [3, 4]], Z6).inv()) + + +def test_DomainMatrix_det(): + A = DomainMatrix([], (0, 0), ZZ) + assert A.det() == 1 + + A = DomainMatrix([[1]], (1, 1), ZZ) + assert A.det() == 1 + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.det() == ZZ(-2) + + A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ) + assert A.det() == ZZ(-1) + + A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ) + assert A.det() == ZZ(0) + + Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) + raises(DMNonSquareMatrixError, lambda: Ans.det()) + + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + assert A.det() == QQ(-2) + + +def test_DomainMatrix_eval_poly(): + dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + p = [ZZ(1), ZZ(2), ZZ(3)] + result = DomainMatrix([[ZZ(12), ZZ(14)], [ZZ(21), ZZ(33)]], (2, 2), ZZ) + assert dM.eval_poly(p) == result == p[0]*dM**2 + p[1]*dM + p[2]*dM**0 + assert dM.eval_poly([]) == dM.zeros(dM.shape, dM.domain) + assert dM.eval_poly([ZZ(2)]) == 2*dM.eye(2, dM.domain) + + dM2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMNonSquareMatrixError, lambda: dM2.eval_poly([ZZ(1)])) + + +def test_DomainMatrix_eval_poly_mul(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + p = [ZZ(1), ZZ(2), ZZ(3)] + result = DomainMatrix([[ZZ(40)], [ZZ(87)]], (2, 1), ZZ) + assert A.eval_poly_mul(p, b) == result == p[0]*A**2*b + p[1]*A*b + p[2]*b + + dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + dM1 = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + raises(DMNonSquareMatrixError, lambda: dM1.eval_poly_mul([ZZ(1)], b)) + b1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: dM.eval_poly_mul([ZZ(1)], b1)) + bq = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) + raises(DMDomainError, lambda: dM.eval_poly_mul([ZZ(1)], bq)) + + +def _check_solve_den(A, b, xnum, xden): + # Examples for solve_den, solve_den_charpoly, solve_den_rref should use + # this so that all methods and types are tested. + + case1 = (A, xnum, b) + case2 = (A.to_sparse(), xnum.to_sparse(), b.to_sparse()) + + for Ai, xnum_i, b_i in [case1, case2]: + # The key invariant for solve_den: + assert Ai*xnum_i == xden*b_i + + # solve_den_rref can differ at least by a minus sign + answers = [(xnum_i, xden), (-xnum_i, -xden)] + assert Ai.solve_den(b) in answers + assert Ai.solve_den(b, method='rref') in answers + assert Ai.solve_den_rref(b) in answers + + # charpoly can only be used if A is square and guarantees to return the + # actual determinant as a denominator. + m, n = Ai.shape + if m == n: + assert Ai.solve_den(b_i, method='charpoly') == (xnum_i, xden) + assert Ai.solve_den_charpoly(b_i) == (xnum_i, xden) + else: + raises(DMNonSquareMatrixError, lambda: Ai.solve_den_charpoly(b)) + raises(DMNonSquareMatrixError, lambda: Ai.solve_den(b, method='charpoly')) + + +def test_DomainMatrix_solve_den(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + result = DomainMatrix([[ZZ(0)], [ZZ(-1)]], (2, 1), ZZ) + den = ZZ(-2) + _check_solve_den(A, b, result, den) + + A = DomainMatrix([ + [ZZ(1), ZZ(2), ZZ(3)], + [ZZ(1), ZZ(2), ZZ(4)], + [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(2)], [ZZ(3)]], (3, 1), ZZ) + result = DomainMatrix([[ZZ(2)], [ZZ(0)], [ZZ(-1)]], (3, 1), ZZ) + den = ZZ(-1) + _check_solve_den(A, b, result, den) + + A = DomainMatrix([[ZZ(2)], [ZZ(2)]], (2, 1), ZZ) + b = DomainMatrix([[ZZ(3)], [ZZ(3)]], (2, 1), ZZ) + result = DomainMatrix([[ZZ(3)]], (1, 1), ZZ) + den = ZZ(2) + _check_solve_den(A, b, result, den) + + +def test_DomainMatrix_solve_den_charpoly(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + A1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMNonSquareMatrixError, lambda: A1.solve_den_charpoly(b)) + b1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: A.solve_den_charpoly(b1)) + bq = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) + raises(DMDomainError, lambda: A.solve_den_charpoly(bq)) + + +def test_DomainMatrix_solve_den_charpoly_check(): + # Test check + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(2), ZZ(4)]], (2, 2), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(3)]], (2, 1), ZZ) + raises(DMNonInvertibleMatrixError, lambda: A.solve_den_charpoly(b)) + adjAb = DomainMatrix([[ZZ(-2)], [ZZ(1)]], (2, 1), ZZ) + assert A.adjugate() * b == adjAb + assert A.solve_den_charpoly(b, check=False) == (adjAb, ZZ(0)) + + +def test_DomainMatrix_solve_den_errors(): + A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + raises(DMShapeError, lambda: A.solve_den(b)) + raises(DMShapeError, lambda: A.solve_den_rref(b)) + + A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + b = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: A.solve_den(b)) + raises(DMShapeError, lambda: A.solve_den_rref(b)) + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + b1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + raises(DMShapeError, lambda: A.solve_den(b1)) + + A = DomainMatrix([[ZZ(2)]], (1, 1), ZZ) + b = DomainMatrix([[ZZ(2)]], (1, 1), ZZ) + raises(DMBadInputError, lambda: A.solve_den(b1, method='invalid')) + + A = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + raises(DMNonSquareMatrixError, lambda: A.solve_den_charpoly(b)) + + +def test_DomainMatrix_solve_den_rref_underdetermined(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(1), ZZ(2)]], (2, 2), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(1)]], (2, 1), ZZ) + raises(DMNonInvertibleMatrixError, lambda: A.solve_den(b)) + raises(DMNonInvertibleMatrixError, lambda: A.solve_den_rref(b)) + + +def test_DomainMatrix_adj_poly_det(): + A = DM([[ZZ(1), ZZ(2), ZZ(3)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8), ZZ(9)]], ZZ) + p, detA = A.adj_poly_det() + assert p == [ZZ(1), ZZ(-15), ZZ(-18)] + assert A.adjugate() == p[0]*A**2 + p[1]*A**1 + p[2]*A**0 == A.eval_poly(p) + assert A.det() == detA + + A = DM([[ZZ(1), ZZ(2), ZZ(3)], + [ZZ(7), ZZ(8), ZZ(9)]], ZZ) + raises(DMNonSquareMatrixError, lambda: A.adj_poly_det()) + + +def test_DomainMatrix_inv_den(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + den = ZZ(-2) + result = DomainMatrix([[ZZ(4), ZZ(-2)], [ZZ(-3), ZZ(1)]], (2, 2), ZZ) + assert A.inv_den() == (result, den) + + +def test_DomainMatrix_adjugate(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + result = DomainMatrix([[ZZ(4), ZZ(-2)], [ZZ(-3), ZZ(1)]], (2, 2), ZZ) + assert A.adjugate() == result + + +def test_DomainMatrix_adj_det(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + adjA = DomainMatrix([[ZZ(4), ZZ(-2)], [ZZ(-3), ZZ(1)]], (2, 2), ZZ) + assert A.adj_det() == (adjA, ZZ(-2)) + + +def test_DomainMatrix_lu(): + A = DomainMatrix([], (0, 0), QQ) + assert A.lu() == (A, A, []) + + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + L = DomainMatrix([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ) + U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ) + swaps = [] + assert A.lu() == (L, U, swaps) + + A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) + U = DomainMatrix([[QQ(3), QQ(4)], [QQ(0), QQ(2)]], (2, 2), QQ) + swaps = [(0, 1)] + assert A.lu() == (L, U, swaps) + + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) + L = DomainMatrix([[QQ(1), QQ(0)], [QQ(2), QQ(1)]], (2, 2), QQ) + U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(0)]], (2, 2), QQ) + swaps = [] + assert A.lu() == (L, U, swaps) + + A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) + L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) + U = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) + swaps = [] + assert A.lu() == (L, U, swaps) + + A = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ) + L = DomainMatrix([[QQ(1), QQ(0)], [QQ(4), QQ(1)]], (2, 2), QQ) + U = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]], (2, 3), QQ) + swaps = [] + assert A.lu() == (L, U, swaps) + + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) + L = DomainMatrix([ + [QQ(1), QQ(0), QQ(0)], + [QQ(3), QQ(1), QQ(0)], + [QQ(5), QQ(2), QQ(1)]], (3, 3), QQ) + U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]], (3, 2), QQ) + swaps = [] + assert A.lu() == (L, U, swaps) + + A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]] + L = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]] + U = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]] + to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows] + A = DomainMatrix(to_dom(A, QQ), (4, 4), QQ) + L = DomainMatrix(to_dom(L, QQ), (4, 4), QQ) + U = DomainMatrix(to_dom(U, QQ), (4, 4), QQ) + assert A.lu() == (L, U, []) + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + raises(DMNotAField, lambda: A.lu()) + + +def test_DomainMatrix_lu_solve(): + # Base case + A = b = x = DomainMatrix([], (0, 0), QQ) + assert A.lu_solve(b) == x + + # Basic example + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) + x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) + assert A.lu_solve(b) == x + + # Example with swaps + A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) + x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) + assert A.lu_solve(b) == x + + # Non-invertible + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) + b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) + raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) + + # Overdetermined, consistent + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) + b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) + x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) + assert A.lu_solve(b) == x + + # Overdetermined, inconsistent + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) + b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) + raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) + + # Underdetermined + A = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) + b = DomainMatrix([[QQ(1)]], (1, 1), QQ) + raises(NotImplementedError, lambda: A.lu_solve(b)) + + # Non-field + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) + raises(DMNotAField, lambda: A.lu_solve(b)) + + # Shape mismatch + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + b = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) + raises(DMShapeError, lambda: A.lu_solve(b)) + + +def test_DomainMatrix_charpoly(): + A = DomainMatrix([], (0, 0), ZZ) + p = [ZZ(1)] + assert A.charpoly() == p + assert A.to_sparse().charpoly() == p + + A = DomainMatrix([[1]], (1, 1), ZZ) + p = [ZZ(1), ZZ(-1)] + assert A.charpoly() == p + assert A.to_sparse().charpoly() == p + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + p = [ZZ(1), ZZ(-5), ZZ(-2)] + assert A.charpoly() == p + assert A.to_sparse().charpoly() == p + + A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) + p = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)] + assert A.charpoly() == p + assert A.to_sparse().charpoly() == p + + A = DomainMatrix([[ZZ(0), ZZ(1), ZZ(0)], + [ZZ(1), ZZ(0), ZZ(1)], + [ZZ(0), ZZ(1), ZZ(0)]], (3, 3), ZZ) + p = [ZZ(1), ZZ(0), ZZ(-2), ZZ(0)] + assert A.charpoly() == p + assert A.to_sparse().charpoly() == p + + A = DM([[17, 0, 30, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [69, 0, 0, 0, 0, 86, 0, 0, 0, 0], + [23, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 13, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 0, 32, 0, 0], + [ 0, 0, 0, 0, 37, 67, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], ZZ) + p = ZZ.map([1, -17, -2070, 0, -771420, 0, 0, 0, 0, 0, 0]) + assert A.charpoly() == p + assert A.to_sparse().charpoly() == p + + Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) + raises(DMNonSquareMatrixError, lambda: Ans.charpoly()) + + +def test_DomainMatrix_charpoly_factor_list(): + A = DomainMatrix([], (0, 0), ZZ) + assert A.charpoly_factor_list() == [] + + A = DM([[1]], ZZ) + assert A.charpoly_factor_list() == [ + ([ZZ(1), ZZ(-1)], 1) + ] + + A = DM([[1, 2], [3, 4]], ZZ) + assert A.charpoly_factor_list() == [ + ([ZZ(1), ZZ(-5), ZZ(-2)], 1) + ] + + A = DM([[1, 2, 0], [3, 4, 0], [0, 0, 1]], ZZ) + assert A.charpoly_factor_list() == [ + ([ZZ(1), ZZ(-1)], 1), + ([ZZ(1), ZZ(-5), ZZ(-2)], 1) + ] + + +def test_DomainMatrix_eye(): + A = DomainMatrix.eye(3, QQ) + assert A.rep == SDM.eye((3, 3), QQ) + assert A.shape == (3, 3) + assert A.domain == QQ + + +def test_DomainMatrix_zeros(): + A = DomainMatrix.zeros((1, 2), QQ) + assert A.rep == SDM.zeros((1, 2), QQ) + assert A.shape == (1, 2) + assert A.domain == QQ + + +def test_DomainMatrix_ones(): + A = DomainMatrix.ones((2, 3), QQ) + if GROUND_TYPES != 'flint': + assert A.rep == DDM.ones((2, 3), QQ) + else: + assert A.rep == SDM.ones((2, 3), QQ).to_dfm() + assert A.shape == (2, 3) + assert A.domain == QQ + + +def test_DomainMatrix_diag(): + A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (2, 2), ZZ) + assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ) == A + + A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (3, 4), ZZ) + assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ, (3, 4)) == A + + +def test_DomainMatrix_hstack(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + + AB = DomainMatrix([ + [ZZ(1), ZZ(2), ZZ(5), ZZ(6)], + [ZZ(3), ZZ(4), ZZ(7), ZZ(8)]], (2, 4), ZZ) + ABC = DomainMatrix([ + [ZZ(1), ZZ(2), ZZ(5), ZZ(6), ZZ(9), ZZ(10)], + [ZZ(3), ZZ(4), ZZ(7), ZZ(8), ZZ(11), ZZ(12)]], (2, 6), ZZ) + assert A.hstack(B) == AB + assert A.hstack(B, C) == ABC + + +def test_DomainMatrix_vstack(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) + C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) + + AB = DomainMatrix([ + [ZZ(1), ZZ(2)], + [ZZ(3), ZZ(4)], + [ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8)]], (4, 2), ZZ) + ABC = DomainMatrix([ + [ZZ(1), ZZ(2)], + [ZZ(3), ZZ(4)], + [ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8)], + [ZZ(9), ZZ(10)], + [ZZ(11), ZZ(12)]], (6, 2), ZZ) + assert A.vstack(B) == AB + assert A.vstack(B, C) == ABC + + +def test_DomainMatrix_applyfunc(): + A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) + B = DomainMatrix([[ZZ(2), ZZ(4)]], (1, 2), ZZ) + assert A.applyfunc(lambda x: 2*x) == B + + +def test_DomainMatrix_scalarmul(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + lamda = DomainScalar(QQ(3)/QQ(2), QQ) + assert A * lamda == DomainMatrix([[QQ(3, 2), QQ(3)], [QQ(9, 2), QQ(6)]], (2, 2), QQ) + assert A * 2 == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) + assert 2 * A == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) + assert A * DomainScalar(ZZ(0), ZZ) == DomainMatrix({}, (2, 2), ZZ) + assert A * DomainScalar(ZZ(1), ZZ) == A + + raises(TypeError, lambda: A * 1.5) + + +def test_DomainMatrix_truediv(): + A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]])) + lamda = DomainScalar(QQ(3)/QQ(2), QQ) + assert A / lamda == DomainMatrix({0: {0: QQ(2, 3), 1: QQ(4, 3)}, 1: {0: QQ(2), 1: QQ(8, 3)}}, (2, 2), QQ) + b = DomainScalar(ZZ(1), ZZ) + assert A / b == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ) + + assert A / 1 == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ) + assert A / 2 == DomainMatrix({0: {0: QQ(1, 2), 1: QQ(1)}, 1: {0: QQ(3, 2), 1: QQ(2)}}, (2, 2), QQ) + + raises(ZeroDivisionError, lambda: A / 0) + raises(TypeError, lambda: A / 1.5) + raises(ZeroDivisionError, lambda: A / DomainScalar(ZZ(0), ZZ)) + + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A.to_field() / 2 == DomainMatrix([[QQ(1, 2), QQ(1)], [QQ(3, 2), QQ(2)]], (2, 2), QQ) + assert A / 2 == DomainMatrix([[QQ(1, 2), QQ(1)], [QQ(3, 2), QQ(2)]], (2, 2), QQ) + assert A.to_field() / QQ(2,3) == DomainMatrix([[QQ(3, 2), QQ(3)], [QQ(9, 2), QQ(6)]], (2, 2), QQ) + + +def test_DomainMatrix_getitem(): + dM = DomainMatrix([ + [ZZ(1), ZZ(2), ZZ(3)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) + + assert dM[1:,:-2] == DomainMatrix([[ZZ(4)], [ZZ(7)]], (2, 1), ZZ) + assert dM[2,:-2] == DomainMatrix([[ZZ(7)]], (1, 1), ZZ) + assert dM[:-2,:-2] == DomainMatrix([[ZZ(1)]], (1, 1), ZZ) + assert dM[:-1,0:2] == DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(4), ZZ(5)]], (2, 2), ZZ) + assert dM[:, -1] == DomainMatrix([[ZZ(3)], [ZZ(6)], [ZZ(9)]], (3, 1), ZZ) + assert dM[-1, :] == DomainMatrix([[ZZ(7), ZZ(8), ZZ(9)]], (1, 3), ZZ) + assert dM[::-1, :] == DomainMatrix([ + [ZZ(7), ZZ(8), ZZ(9)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(1), ZZ(2), ZZ(3)]], (3, 3), ZZ) + + raises(IndexError, lambda: dM[4, :-2]) + raises(IndexError, lambda: dM[:-2, 4]) + + assert dM[1, 2] == DomainScalar(ZZ(6), ZZ) + assert dM[-2, 2] == DomainScalar(ZZ(6), ZZ) + assert dM[1, -2] == DomainScalar(ZZ(5), ZZ) + assert dM[-1, -3] == DomainScalar(ZZ(7), ZZ) + + raises(IndexError, lambda: dM[3, 3]) + raises(IndexError, lambda: dM[1, 4]) + raises(IndexError, lambda: dM[-1, -4]) + + dM = DomainMatrix({0: {0: ZZ(1)}}, (10, 10), ZZ) + assert dM[5, 5] == DomainScalar(ZZ(0), ZZ) + assert dM[0, 0] == DomainScalar(ZZ(1), ZZ) + + dM = DomainMatrix({1: {0: 1}}, (2,1), ZZ) + assert dM[0:, 0] == DomainMatrix({1: {0: 1}}, (2, 1), ZZ) + raises(IndexError, lambda: dM[3, 0]) + + dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) + assert dM[:2,:2] == DomainMatrix({}, (2, 2), ZZ) + assert dM[2:,2:] == DomainMatrix({0: {0: 1}, 2: {2: 1}}, (3, 3), ZZ) + assert dM[3:,3:] == DomainMatrix({1: {1: 1}}, (2, 2), ZZ) + assert dM[2:, 6:] == DomainMatrix({}, (3, 0), ZZ) + + +def test_DomainMatrix_getitem_sympy(): + dM = DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) + val1 = dM.getitem_sympy(0, 0) + assert val1 is S.Zero + val2 = dM.getitem_sympy(2, 2) + assert val2 == 2 and isinstance(val2, Integer) + + +def test_DomainMatrix_extract(): + dM1 = DomainMatrix([ + [ZZ(1), ZZ(2), ZZ(3)], + [ZZ(4), ZZ(5), ZZ(6)], + [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) + dM2 = DomainMatrix([ + [ZZ(1), ZZ(3)], + [ZZ(7), ZZ(9)]], (2, 2), ZZ) + assert dM1.extract([0, 2], [0, 2]) == dM2 + assert dM1.to_sparse().extract([0, 2], [0, 2]) == dM2.to_sparse() + assert dM1.extract([0, -1], [0, -1]) == dM2 + assert dM1.to_sparse().extract([0, -1], [0, -1]) == dM2.to_sparse() + + dM3 = DomainMatrix([ + [ZZ(1), ZZ(2), ZZ(2)], + [ZZ(4), ZZ(5), ZZ(5)], + [ZZ(4), ZZ(5), ZZ(5)]], (3, 3), ZZ) + assert dM1.extract([0, 1, 1], [0, 1, 1]) == dM3 + assert dM1.to_sparse().extract([0, 1, 1], [0, 1, 1]) == dM3.to_sparse() + + empty = [ + ([], [], (0, 0)), + ([1], [], (1, 0)), + ([], [1], (0, 1)), + ] + for rows, cols, size in empty: + assert dM1.extract(rows, cols) == DomainMatrix.zeros(size, ZZ).to_dense() + assert dM1.to_sparse().extract(rows, cols) == DomainMatrix.zeros(size, ZZ) + + dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + bad_indices = [([2], [0]), ([0], [2]), ([-3], [0]), ([0], [-3])] + for rows, cols in bad_indices: + raises(IndexError, lambda: dM.extract(rows, cols)) + raises(IndexError, lambda: dM.to_sparse().extract(rows, cols)) + + +def test_DomainMatrix_setitem(): + dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) + dM[2, 2] = ZZ(2) + assert dM == DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) + def setitem(i, j, val): + dM[i, j] = val + raises(TypeError, lambda: setitem(2, 2, QQ(1, 2))) + raises(NotImplementedError, lambda: setitem(slice(1, 2), 2, ZZ(1))) + + +def test_DomainMatrix_pickling(): + import pickle + dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) + assert pickle.loads(pickle.dumps(dM)) == dM + dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert pickle.loads(pickle.dumps(dM)) == dM + + +def test_DomainMatrix_fflu(): + A = DM([[1, 2], [3, 4]], ZZ) + P, L, D, U = A.fflu() + assert P.shape == A.shape + assert L.shape == A.shape + assert D.shape == A.shape + assert U.shape == A.shape + assert P == DM([[1, 0], [0, 1]], ZZ) + assert L == DM([[1, 0], [3, -2]], ZZ) + assert D == DM([[1, 0], [0, -2]], ZZ) + assert U == DM([[1, 2], [0, -2]], ZZ) + di, d = D.inv_den() + assert P.matmul(A).rmul(d) == L.matmul(di).matmul(U) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainscalar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainscalar.py new file mode 100644 index 0000000000000000000000000000000000000000..8c507caf079cc62ba23ba171a50d0d27c98eb6d9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainscalar.py @@ -0,0 +1,153 @@ +from sympy.testing.pytest import raises + +from sympy.core.symbol import S +from sympy.polys import ZZ, QQ +from sympy.polys.matrices.domainscalar import DomainScalar +from sympy.polys.matrices.domainmatrix import DomainMatrix + + +def test_DomainScalar___new__(): + raises(TypeError, lambda: DomainScalar(ZZ(1), QQ)) + raises(TypeError, lambda: DomainScalar(ZZ(1), 1)) + + +def test_DomainScalar_new(): + A = DomainScalar(ZZ(1), ZZ) + B = A.new(ZZ(4), ZZ) + assert B == DomainScalar(ZZ(4), ZZ) + + +def test_DomainScalar_repr(): + A = DomainScalar(ZZ(1), ZZ) + assert repr(A) in {'1', 'mpz(1)'} + + +def test_DomainScalar_from_sympy(): + expr = S(1) + B = DomainScalar.from_sympy(expr) + assert B == DomainScalar(ZZ(1), ZZ) + + +def test_DomainScalar_to_sympy(): + B = DomainScalar(ZZ(1), ZZ) + expr = B.to_sympy() + assert expr.is_Integer and expr == 1 + + +def test_DomainScalar_to_domain(): + A = DomainScalar(ZZ(1), ZZ) + B = A.to_domain(QQ) + assert B == DomainScalar(QQ(1), QQ) + + +def test_DomainScalar_convert_to(): + A = DomainScalar(ZZ(1), ZZ) + B = A.convert_to(QQ) + assert B == DomainScalar(QQ(1), QQ) + + +def test_DomainScalar_unify(): + A = DomainScalar(ZZ(1), ZZ) + B = DomainScalar(QQ(2), QQ) + A, B = A.unify(B) + assert A.domain == B.domain == QQ + + +def test_DomainScalar_add(): + A = DomainScalar(ZZ(1), ZZ) + B = DomainScalar(QQ(2), QQ) + assert A + B == DomainScalar(QQ(3), QQ) + + raises(TypeError, lambda: A + 1.5) + +def test_DomainScalar_sub(): + A = DomainScalar(ZZ(1), ZZ) + B = DomainScalar(QQ(2), QQ) + assert A - B == DomainScalar(QQ(-1), QQ) + + raises(TypeError, lambda: A - 1.5) + +def test_DomainScalar_mul(): + A = DomainScalar(ZZ(1), ZZ) + B = DomainScalar(QQ(2), QQ) + dm = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + assert A * B == DomainScalar(QQ(2), QQ) + assert A * dm == dm + assert B * 2 == DomainScalar(QQ(4), QQ) + + raises(TypeError, lambda: A * 1.5) + + +def test_DomainScalar_floordiv(): + A = DomainScalar(ZZ(-5), ZZ) + B = DomainScalar(QQ(2), QQ) + assert A // B == DomainScalar(QQ(-5, 2), QQ) + C = DomainScalar(ZZ(2), ZZ) + assert A // C == DomainScalar(ZZ(-3), ZZ) + + raises(TypeError, lambda: A // 1.5) + + +def test_DomainScalar_mod(): + A = DomainScalar(ZZ(5), ZZ) + B = DomainScalar(QQ(2), QQ) + assert A % B == DomainScalar(QQ(0), QQ) + C = DomainScalar(ZZ(2), ZZ) + assert A % C == DomainScalar(ZZ(1), ZZ) + + raises(TypeError, lambda: A % 1.5) + + +def test_DomainScalar_divmod(): + A = DomainScalar(ZZ(5), ZZ) + B = DomainScalar(QQ(2), QQ) + assert divmod(A, B) == (DomainScalar(QQ(5, 2), QQ), DomainScalar(QQ(0), QQ)) + C = DomainScalar(ZZ(2), ZZ) + assert divmod(A, C) == (DomainScalar(ZZ(2), ZZ), DomainScalar(ZZ(1), ZZ)) + + raises(TypeError, lambda: divmod(A, 1.5)) + + +def test_DomainScalar_pow(): + A = DomainScalar(ZZ(-5), ZZ) + B = A**(2) + assert B == DomainScalar(ZZ(25), ZZ) + + raises(TypeError, lambda: A**(1.5)) + + +def test_DomainScalar_pos(): + A = DomainScalar(QQ(2), QQ) + B = DomainScalar(QQ(2), QQ) + assert +A == B + + +def test_DomainScalar_neg(): + A = DomainScalar(QQ(2), QQ) + B = DomainScalar(QQ(-2), QQ) + assert -A == B + + +def test_DomainScalar_eq(): + A = DomainScalar(QQ(2), QQ) + assert A == A + B = DomainScalar(ZZ(-5), ZZ) + assert A != B + C = DomainScalar(ZZ(2), ZZ) + assert A != C + D = [1] + assert A != D + + +def test_DomainScalar_isZero(): + A = DomainScalar(ZZ(0), ZZ) + assert A.is_zero() == True + B = DomainScalar(ZZ(1), ZZ) + assert B.is_zero() == False + + +def test_DomainScalar_isOne(): + A = DomainScalar(ZZ(1), ZZ) + assert A.is_one() == True + B = DomainScalar(ZZ(0), ZZ) + assert B.is_one() == False diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_eigen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_eigen.py new file mode 100644 index 0000000000000000000000000000000000000000..70482eab686d5b4e1c45d552f5eccb5bdaa9e1ed --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_eigen.py @@ -0,0 +1,90 @@ +""" +Tests for the sympy.polys.matrices.eigen module +""" + +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.matrices.dense import Matrix + +from sympy.polys.agca.extensions import FiniteExtension +from sympy.polys.domains import QQ +from sympy.polys.polytools import Poly +from sympy.polys.rootoftools import CRootOf +from sympy.polys.matrices.domainmatrix import DomainMatrix + +from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy + + +def test_dom_eigenvects_rational(): + # Rational eigenvalues + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) + rational_eigenvects = [ + (QQ, QQ(3), 1, DomainMatrix([[QQ(1), QQ(1)]], (1, 2), QQ)), + (QQ, QQ(0), 1, DomainMatrix([[QQ(-2), QQ(1)]], (1, 2), QQ)), + ] + assert dom_eigenvects(A) == (rational_eigenvects, []) + + # Test converting to Expr: + sympy_eigenvects = [ + (S(3), 1, [Matrix([1, 1])]), + (S(0), 1, [Matrix([-2, 1])]), + ] + assert dom_eigenvects_to_sympy(rational_eigenvects, [], Matrix) == sympy_eigenvects + + +def test_dom_eigenvects_algebraic(): + # Algebraic eigenvalues + A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) + Avects = dom_eigenvects(A) + + # Extract the dummy to build the expected result: + lamda = Avects[1][0][1].gens[0] + irreducible = Poly(lamda**2 - 5*lamda - 2, lamda, domain=QQ) + K = FiniteExtension(irreducible) + KK = K.from_sympy + algebraic_eigenvects = [ + (K, irreducible, 1, DomainMatrix([[KK((lamda-4)/3), KK(1)]], (1, 2), K)), + ] + assert Avects == ([], algebraic_eigenvects) + + # Test converting to Expr: + sympy_eigenvects = [ + (S(5)/2 - sqrt(33)/2, 1, [Matrix([[-sqrt(33)/6 - S(1)/2], [1]])]), + (S(5)/2 + sqrt(33)/2, 1, [Matrix([[-S(1)/2 + sqrt(33)/6], [1]])]), + ] + assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects + + +def test_dom_eigenvects_rootof(): + # Algebraic eigenvalues + A = DomainMatrix([ + [0, 0, 0, 0, -1], + [1, 0, 0, 0, 1], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 0]], (5, 5), QQ) + Avects = dom_eigenvects(A) + + # Extract the dummy to build the expected result: + lamda = Avects[1][0][1].gens[0] + irreducible = Poly(lamda**5 - lamda + 1, lamda, domain=QQ) + K = FiniteExtension(irreducible) + KK = K.from_sympy + algebraic_eigenvects = [ + (K, irreducible, 1, + DomainMatrix([ + [KK(lamda**4-1), KK(lamda**3), KK(lamda**2), KK(lamda), KK(1)] + ], (1, 5), K)), + ] + assert Avects == ([], algebraic_eigenvects) + + # Test converting to Expr (slow): + l0, l1, l2, l3, l4 = [CRootOf(lamda**5 - lamda + 1, i) for i in range(5)] + sympy_eigenvects = [ + (l0, 1, [Matrix([-1 + l0**4, l0**3, l0**2, l0, 1])]), + (l1, 1, [Matrix([-1 + l1**4, l1**3, l1**2, l1, 1])]), + (l2, 1, [Matrix([-1 + l2**4, l2**3, l2**2, l2, 1])]), + (l3, 1, [Matrix([-1 + l3**4, l3**3, l3**2, l3, 1])]), + (l4, 1, [Matrix([-1 + l4**4, l4**3, l4**2, l4, 1])]), + ] + assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_fflu.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_fflu.py new file mode 100644 index 0000000000000000000000000000000000000000..0a4676ce0c3ee2d495b7011ddc48db8c8c40648b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_fflu.py @@ -0,0 +1,301 @@ +from sympy.polys.matrices import DomainMatrix, DM +from sympy.polys.domains import ZZ, QQ +from sympy import Matrix +import pytest + + +FFLU_EXAMPLES = [ + ( + 'zz_2x3', + DM([[1, 2, 3], [4, 5, 6]], ZZ), + DM([[1, 0], [0, 1]], ZZ), + DM([[1, 0], [4, -3]], ZZ), + DM([[1, 0], [0, -3]], ZZ), + DM([[1, 2, 3], [0, -3, -6]], ZZ), + ), + + ( + 'zz_2x2', + DM([[4, 3], [6, 3]], ZZ), + DM([[1, 0], [0, 1]], ZZ), + DM([[1, 0], [6, -6]], ZZ), + DM([[4, 0], [0, -3]], ZZ), + DM([[4, 3], [0, -3]], ZZ), + ), + + ( + 'zz_3x2', + DM([[1, 2], [3, 4], [5, 6]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[1, 0, 0], [3, 1, 0], [5, 2, 1]], ZZ), + DM([[1, 0], [0, -2]], ZZ), + DM([[1, 2], [0, -2], [0, 0]], ZZ), + ), + + ( + 'zz_3x3', + DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[1, 0, 0], [4, 1, 0], [7, 2, 1]], ZZ), + DM([[1, 0, 0], [0, -3, 0], [0, 0, 0]], ZZ), + DM([[1, 2, 3], [0, -3, -6], [0, 0, 0]], ZZ), + ), + + ( + 'zz_zero', + DM([[0, 0, 0], [0, 0, 0], [0, 0, 0]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[0, 0, 0], [0, 0, 0], [0, 0, 0]], ZZ), + DM([[0, 0, 0], [0, 0, 0], [0, 0, 0]], ZZ), + ), + + ( + 'zz_empty', + DM([], ZZ), + DM([], ZZ), + DM([], ZZ), + DM([], ZZ), + DM([], ZZ), + ), + + ( + 'zz_empty_0x2', + DomainMatrix([], (0, 2), ZZ), + DomainMatrix([], (0, 0), ZZ), + DomainMatrix([], (0, 0), ZZ), + DomainMatrix([], (0, 0), ZZ), + DomainMatrix([], (0, 2), ZZ) + ), + + ( + + 'zz_empty_2x0', + DomainMatrix([[], []], (2, 0), ZZ), + DomainMatrix.eye((2, 2), ZZ), + DomainMatrix.eye((2, 2), ZZ), + DomainMatrix.eye((2, 2), ZZ), + DomainMatrix([[], []], (2, 0), ZZ) + + ), + + ( + 'zz_negative', + DM([[-1, -2], [-3, -4]], ZZ), + DM([[1, 0], [0, 1]], ZZ), + DM([[-1, 0], [-3, -2]], ZZ), + DM([[-1, 0], [0, 2]], ZZ), + DM([[-1, -2], [0, -2]], ZZ), + ), + + ( + 'zz_mixed_signs', + DM([[1, -2], [-3, 4]], ZZ), + DM([[1, 0], [0, 1]], ZZ), + DM([[1, 0], [-3, 1]], ZZ), + DM([[1, 0], [0, -2]], ZZ), + DM([[1, -2], [0, -2]], ZZ), + ), + + ( + 'zz_upper_triangular', + DM([[1, 2, 3], [0, 4, 5], [0, 0, 6]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[1, 0, 0], [0, 4, 0], [0, 0, 24]], ZZ), + DM([[1, 0, 0], [0, 4, 0], [0, 0, 96]], ZZ), + DM([[1, 2, 3], [0, 4, 5], [0, 0, 24]], ZZ), + ), + + ( + 'zz_lower_triangular', + DM([[1, 0, 0], [2, 3, 0], [4, 5, 6]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[1, 0, 0], [2, 3, 0], [4, 5, 18]], ZZ), + DM([[1, 0, 0], [0, 3, 0], [0, 0, 54]], ZZ), + DM([[1, 0, 0], [0, 3, 0], [0, 0, 18]], ZZ), + ), + + ( + 'zz_diagonal', + DM([[2, 0, 0], [0, 3, 0], [0, 0, 4]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[2, 0, 0], [0, 6, 0], [0, 0, 24]], ZZ), + DM([[2, 0, 0], [0, 12, 0], [0, 0, 144]], ZZ), + DM([[2, 0, 0], [0, 6, 0], [0, 0, 24]], ZZ) + + ), + + ( + 'rank_deficient_3x3', + DM([[1, 2, 3], [2, 4, 6], [3, 6, 9]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[1, 0, 0], [2, 1, 0], [3, 0, 1]], ZZ), + DM([[1, 0, 0], [0, 0, 0], [0, 0, 0]], ZZ), + DM([[1, 2, 3], [0, 0, 0], [0, 0, 0]], ZZ), + ), + + ( + 'zz_1x1', + DM([[5]], ZZ), + DM([[1]], ZZ), + DM([[5]], ZZ), + DM([[5]], ZZ), + DM([[5]], ZZ), + ), + + ( + 'zz_nx1_2rows', + DM([[81], [54]], ZZ), + DM([[1, 0], [0, 1]], ZZ), + DM([[81, 0], [54, 81]], ZZ), + DM([[81, 0], [0, 81]], ZZ), + DM([[81], [0]], ZZ), + ), + + ( + 'zz_nx2_3rows', + DM([[2, 7], [7, 45], [25, 84]], ZZ), + DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ZZ), + DM([[2, 0, 0], [7, 82, 0], [25, 41, 41]], ZZ), + DM([[2, 0, 0], [0, 82, 0], [0, 0, 41]], ZZ), + DM([[2, 7], [0, 82], [0, 0]], ZZ), + ), + + ( + + 'zz_1x2', + DM([[0, 28]], ZZ), + DM([[1]], ZZ), + DM([[28]], ZZ), + DM([[28]], ZZ), + DM([[0, 28]], ZZ) + ), + + ( + 'zz_nx3_4rows', + DM([[84, 30, 9], [20, 59, 13], [53, 46, 81], [63, 48, 29]], ZZ), + DM([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], ZZ), + DM([[84, 0, 0, 0], [20, 365904, 0, 0], [53, 303411, 303411, 0], [63, 303411, 303411, 303411]], ZZ), + DM([[84, 0, 0, 0], [0, 365904, 0, 0], [0, 0, 1321658316, 0], [0, 0, 0, 303411]], ZZ), + DM([[84, 30, 9], [0, 365904, 13], [0, 0, 1321658316], [0, 0, 0]], ZZ), + ), + + ( + 'fflu_row_swap', + DM([[0, 1, 2], [3, 4, 5], [6, 7, 8]], ZZ), + DM([[0, 1, 0], [1, 0, 0], [0, 0, 1]], ZZ), + DM([[3, 0, 0], [0, 3, 0], [6, -3, 1]], ZZ), + DM([[3, 0, 0], [0, 9, 0], [0, 0, 3]], ZZ), + DM([[3, 4, 5], [0, 3, 6], [0, 0, 0]], ZZ) + ), +] + + +def _check_fflu(A, P, L, D, U): + P_field = P.to_field().to_dense() + L_field = L.to_field().to_dense() + D_field = D.to_field().to_dense() + U_field = U.to_field().to_dense() + m, n = A.shape + assert P_field.shape == (m, m) + assert L_field.shape == (m, m) + assert D_field.shape == (m, m) + assert U_field.shape == (m, n) + assert L_field.is_lower + assert D_field.is_diagonal + di, d = D.inv_den() + assert P.matmul(A).rmul(d) == L.matmul(di).matmul(U) + assert U_field.is_upper + + +def _to_DM(A, ans): + if isinstance(A, DomainMatrix): + return A + elif isinstance(A, Matrix): + return A.to_DM(ans.domain) + return DomainMatrix(A.to_list(), A.shape, A.domain) + + +def _check_fflu_result(result, A, P_ans, L_ans, D_ans, U_ans): + P, L, D, U = result + P = _to_DM(P, P_ans) + L = _to_DM(L, L_ans) + D = _to_DM(D, D_ans) + U = _to_DM(U, U_ans) + A = _to_DM(A, P_ans) + m, n = A.shape + assert P.shape == (m, m) + assert L.shape == (m, m) + assert D.shape == (m, m) + assert U.shape == (m, n) + assert L.is_lower + assert D.is_diagonal + di, d = D.inv_den() + assert P.matmul(A).rmul(d) == L.matmul(di).matmul(U) + assert U.is_upper + + +@pytest.mark.parametrize('name, A, P_ans, L_ans, D_ans, U_ans', FFLU_EXAMPLES) +def test_dm_dense_fflu(name, A, P_ans, L_ans, D_ans, U_ans): + A = A.to_dense() + _check_fflu_result(A.fflu(), A, P_ans, L_ans, D_ans, U_ans) + + +@pytest.mark.parametrize('name, A, P_ans, L_ans, D_ans, U_ans', FFLU_EXAMPLES) +def test_dm_sparse_fflu(name, A, P_ans, L_ans, D_ans, U_ans): + A = A.to_sparse() + _check_fflu_result(A.fflu(), A, P_ans, L_ans, D_ans, U_ans) + + +@pytest.mark.parametrize('name, A, P_ans, L_ans, D_ans, U_ans', FFLU_EXAMPLES) +def test_ddm_fflu(name, A, P_ans, L_ans, D_ans, U_ans): + A = A.to_ddm() + _check_fflu_result(A.fflu(), A, P_ans, L_ans, D_ans, U_ans) + + +@pytest.mark.parametrize('name, A, P_ans, L_ans, D_ans, U_ans', FFLU_EXAMPLES) +def test_sdm_fflu(name, A, P_ans, L_ans, D_ans, U_ans): + A = A.to_sdm() + _check_fflu_result(A.fflu(), A, P_ans, L_ans, D_ans, U_ans) + + +@pytest.mark.parametrize('name, A, P_ans, L_ans, D_ans, U_ans', FFLU_EXAMPLES) +def test_dfm_fflu(name, A, P_ans, L_ans, D_ans, U_ans): + pytest.importorskip('flint') + if A.domain not in (ZZ, QQ) and not A.domain.is_FF: + pytest.skip("Domain not supported by DFM") + A = A.to_dfm() + _check_fflu_result(A.fflu(), A, P_ans, L_ans, D_ans, U_ans) + + +def test_fflu_empty_matrix(): + A = DomainMatrix([], (0, 0), ZZ) + P, L, D, U = A.fflu() + assert P.shape == (0, 0) + assert L.shape == (0, 0) + assert D.shape == (0, 0) + assert U.shape == (0, 0) + + +def test_fflu_properties(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) + P, L, D, U = A.fflu() + assert P.shape == (2, 2) + assert L.shape == (2, 2) + assert D.shape == (2, 2) + assert U.shape == (2, 2) + assert L.is_lower + assert U.is_upper + assert D.is_diagonal + di, d = D.inv_den() + assert P.matmul(A).rmul(d) == L.matmul(di).matmul(U) + + +def test_fflu_rank_deficient(): + A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(2), ZZ(4)]], (2, 2), ZZ) + P, L, D, U = A.fflu() + assert P.shape == (2, 2) + assert L.shape == (2, 2) + assert D.shape == (2, 2) + assert U.shape == (2, 2) + assert U.getitem_sympy(1, 1) == 0 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_inverse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_inverse.py new file mode 100644 index 0000000000000000000000000000000000000000..47c82799324518bd7d1cc2405ade0aa0a5a4f6e9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_inverse.py @@ -0,0 +1,193 @@ +from sympy import ZZ, Matrix +from sympy.polys.matrices import DM, DomainMatrix +from sympy.polys.matrices.dense import ddm_iinv +from sympy.polys.matrices.exceptions import DMNonInvertibleMatrixError +from sympy.matrices.exceptions import NonInvertibleMatrixError + +import pytest +from sympy.testing.pytest import raises +from sympy.core.numbers import all_close + +from sympy.abc import x + + +# Examples are given as adjugate matrix and determinant adj_det should match +# these exactly but inv_den only matches after cancel_denom. + + +INVERSE_EXAMPLES = [ + + ( + 'zz_1', + DomainMatrix([], (0, 0), ZZ), + DomainMatrix([], (0, 0), ZZ), + ZZ(1), + ), + + ( + 'zz_2', + DM([[2]], ZZ), + DM([[1]], ZZ), + ZZ(2), + ), + + ( + 'zz_3', + DM([[2, 0], + [0, 2]], ZZ), + DM([[2, 0], + [0, 2]], ZZ), + ZZ(4), + ), + + ( + 'zz_4', + DM([[1, 2], + [3, 4]], ZZ), + DM([[ 4, -2], + [-3, 1]], ZZ), + ZZ(-2), + ), + + ( + 'zz_5', + DM([[2, 2, 0], + [0, 2, 2], + [0, 0, 2]], ZZ), + DM([[4, -4, 4], + [0, 4, -4], + [0, 0, 4]], ZZ), + ZZ(8), + ), + + ( + 'zz_6', + DM([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], ZZ), + DM([[-3, 6, -3], + [ 6, -12, 6], + [-3, 6, -3]], ZZ), + ZZ(0), + ), +] + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_Matrix_inv(name, A, A_inv, den): + + def _check(**kwargs): + if den != 0: + assert A.inv(**kwargs) == A_inv + else: + raises(NonInvertibleMatrixError, lambda: A.inv(**kwargs)) + + K = A.domain + A = A.to_Matrix() + A_inv = A_inv.to_Matrix() / K.to_sympy(den) + _check() + for method in ['GE', 'LU', 'ADJ', 'CH', 'LDL', 'QR']: + _check(method=method) + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_dm_inv_den(name, A, A_inv, den): + if den != 0: + A_inv_f, den_f = A.inv_den() + assert A_inv_f.cancel_denom(den_f) == A_inv.cancel_denom(den) + else: + raises(DMNonInvertibleMatrixError, lambda: A.inv_den()) + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_dm_inv(name, A, A_inv, den): + A = A.to_field() + if den != 0: + A_inv = A_inv.to_field() / den + assert A.inv() == A_inv + else: + raises(DMNonInvertibleMatrixError, lambda: A.inv()) + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_ddm_inv(name, A, A_inv, den): + A = A.to_field().to_ddm() + if den != 0: + A_inv = (A_inv.to_field() / den).to_ddm() + assert A.inv() == A_inv + else: + raises(DMNonInvertibleMatrixError, lambda: A.inv()) + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_sdm_inv(name, A, A_inv, den): + A = A.to_field().to_sdm() + if den != 0: + A_inv = (A_inv.to_field() / den).to_sdm() + assert A.inv() == A_inv + else: + raises(DMNonInvertibleMatrixError, lambda: A.inv()) + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_dense_ddm_iinv(name, A, A_inv, den): + A = A.to_field().to_ddm().copy() + K = A.domain + A_result = A.copy() + if den != 0: + A_inv = (A_inv.to_field() / den).to_ddm() + ddm_iinv(A_result, A, K) + assert A_result == A_inv + else: + raises(DMNonInvertibleMatrixError, lambda: ddm_iinv(A_result, A, K)) + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_Matrix_adjugate(name, A, A_inv, den): + A = A.to_Matrix() + A_inv = A_inv.to_Matrix() + assert A.adjugate() == A_inv + for method in ["bareiss", "berkowitz", "bird", "laplace", "lu"]: + assert A.adjugate(method=method) == A_inv + + +@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES) +def test_dm_adj_det(name, A, A_inv, den): + assert A.adj_det() == (A_inv, den) + + +def test_inverse_inexact(): + + M = Matrix([[x-0.3, -0.06, -0.22], + [-0.46, x-0.48, -0.41], + [-0.14, -0.39, x-0.64]]) + + Mn = Matrix([[1.0*x**2 - 1.12*x + 0.1473, 0.06*x + 0.0474, 0.22*x - 0.081], + [0.46*x - 0.237, 1.0*x**2 - 0.94*x + 0.1612, 0.41*x - 0.0218], + [0.14*x + 0.1122, 0.39*x - 0.1086, 1.0*x**2 - 0.78*x + 0.1164]]) + + d = 1.0*x**3 - 1.42*x**2 + 0.4249*x - 0.0546540000000002 + + Mi = Mn / d + + M_dm = M.to_DM() + M_dmd = M_dm.to_dense() + M_dm_num, M_dm_den = M_dm.inv_den() + M_dmd_num, M_dmd_den = M_dmd.inv_den() + + # XXX: We don't check M_dm().to_field().inv() which currently uses division + # and produces a more complicate result from gcd cancellation failing. + # DomainMatrix.inv() over RR(x) should be changed to clear denominators and + # use DomainMatrix.inv_den(). + + Minvs = [ + M.inv(), + (M_dm_num.to_field() / M_dm_den).to_Matrix(), + (M_dmd_num.to_field() / M_dmd_den).to_Matrix(), + M_dm_num.to_Matrix() / M_dm_den.as_expr(), + M_dmd_num.to_Matrix() / M_dmd_den.as_expr(), + ] + + for Minv in Minvs: + for Mi1, Mi2 in zip(Minv.flat(), Mi.flat()): + assert all_close(Mi2, Mi1) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_linsolve.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_linsolve.py new file mode 100644 index 0000000000000000000000000000000000000000..25300ef2cb4792e4424c9c15c0bbbc313ce062e6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_linsolve.py @@ -0,0 +1,112 @@ +# +# test_linsolve.py +# +# Test the internal implementation of linsolve. +# + +from sympy.testing.pytest import raises + +from sympy.core.numbers import I +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.abc import x, y, z + +from sympy.polys.matrices.linsolve import _linsolve +from sympy.polys.solvers import PolyNonlinearError + + +def test__linsolve(): + assert _linsolve([], [x]) == {x:x} + assert _linsolve([S.Zero], [x]) == {x:x} + assert _linsolve([x-1,x-2], [x]) is None + assert _linsolve([x-1], [x]) == {x:1} + assert _linsolve([x-1, y], [x, y]) == {x:1, y:S.Zero} + assert _linsolve([2*I], [x]) is None + raises(PolyNonlinearError, lambda: _linsolve([x*(1 + x)], [x])) + + +def test__linsolve_float(): + + # This should give the exact answer: + eqs = [ + y - x, + y - 0.0216 * x + ] + # Should _linsolve return floats here? + sol = {x:0, y:0} + assert _linsolve(eqs, (x, y)) == sol + + # Other cases should be close to eps + + def all_close(sol1, sol2, eps=1e-15): + close = lambda a, b: abs(a - b) < eps + assert sol1.keys() == sol2.keys() + return all(close(sol1[s], sol2[s]) for s in sol1) + + eqs = [ + 0.8*x + 0.8*z + 0.2, + 0.9*x + 0.7*y + 0.2*z + 0.9, + 0.7*x + 0.2*y + 0.2*z + 0.5 + ] + sol_exact = {x:-29/42, y:-11/21, z:37/84} + sol_linsolve = _linsolve(eqs, [x,y,z]) + assert all_close(sol_exact, sol_linsolve) + + eqs = [ + 0.9*x + 0.3*y + 0.4*z + 0.6, + 0.6*x + 0.9*y + 0.1*z + 0.7, + 0.4*x + 0.6*y + 0.9*z + 0.5 + ] + sol_exact = {x:-88/175, y:-46/105, z:-1/25} + sol_linsolve = _linsolve(eqs, [x,y,z]) + assert all_close(sol_exact, sol_linsolve) + + eqs = [ + 0.4*x + 0.3*y + 0.6*z + 0.7, + 0.4*x + 0.3*y + 0.9*z + 0.9, + 0.7*x + 0.9*y, + ] + sol_exact = {x:-9/5, y:7/5, z:-2/3} + sol_linsolve = _linsolve(eqs, [x,y,z]) + assert all_close(sol_exact, sol_linsolve) + + eqs = [ + x*(0.7 + 0.6*I) + y*(0.4 + 0.7*I) + z*(0.9 + 0.1*I) + 0.5, + 0.2*I*x + 0.2*I*y + z*(0.9 + 0.2*I) + 0.1, + x*(0.9 + 0.7*I) + y*(0.9 + 0.7*I) + z*(0.9 + 0.4*I) + 0.4, + ] + sol_exact = { + x:-6157/7995 - 411/5330*I, + y:8519/15990 + 1784/7995*I, + z:-34/533 + 107/1599*I, + } + sol_linsolve = _linsolve(eqs, [x,y,z]) + assert all_close(sol_exact, sol_linsolve) + + # XXX: This system for x and y over RR(z) is problematic. + # + # eqs = [ + # x*(0.2*z + 0.9) + y*(0.5*z + 0.8) + 0.6, + # 0.1*x*z + y*(0.1*z + 0.6) + 0.9, + # ] + # + # linsolve(eqs, [x, y]) + # The solution for x comes out as + # + # -3.9e-5*z**2 - 3.6e-5*z - 8.67361737988404e-20 + # x = ---------------------------------------------- + # 3.0e-6*z**3 - 1.3e-5*z**2 - 5.4e-5*z + # + # The 8e-20 in the numerator should be zero which would allow z to cancel + # from top and bottom. It should be possible to avoid this somehow because + # the inverse of the matrix only has a quadratic factor (the determinant) + # in the denominator. + + +def test__linsolve_deprecated(): + raises(PolyNonlinearError, lambda: + _linsolve([Eq(x**2, x**2 + y)], [x, y])) + raises(PolyNonlinearError, lambda: + _linsolve([(x + y)**2 - x**2], [x])) + raises(PolyNonlinearError, lambda: + _linsolve([Eq((x + y)**2, x**2)], [x])) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_lll.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_lll.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf91a00703532f02d763656d6117018fbc496cf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_lll.py @@ -0,0 +1,145 @@ +from sympy.polys.domains import ZZ, QQ +from sympy.polys.matrices import DM +from sympy.polys.matrices.domainmatrix import DomainMatrix +from sympy.polys.matrices.exceptions import DMRankError, DMValueError, DMShapeError, DMDomainError +from sympy.polys.matrices.lll import _ddm_lll, ddm_lll, ddm_lll_transform +from sympy.testing.pytest import raises + + +def test_lll(): + normal_test_data = [ + ( + DM([[1, 0, 0, 0, -20160], + [0, 1, 0, 0, 33768], + [0, 0, 1, 0, 39578], + [0, 0, 0, 1, 47757]], ZZ), + DM([[10, -3, -2, 8, -4], + [3, -9, 8, 1, -11], + [-3, 13, -9, -3, -9], + [-12, -7, -11, 9, -1]], ZZ) + ), + ( + DM([[20, 52, 3456], + [14, 31, -1], + [34, -442, 0]], ZZ), + DM([[14, 31, -1], + [188, -101, -11], + [236, 13, 3443]], ZZ) + ), + ( + DM([[34, -1, -86, 12], + [-54, 34, 55, 678], + [23, 3498, 234, 6783], + [87, 49, 665, 11]], ZZ), + DM([[34, -1, -86, 12], + [291, 43, 149, 83], + [-54, 34, 55, 678], + [-189, 3077, -184, -223]], ZZ) + ) + ] + delta = QQ(5, 6) + for basis_dm, reduced_dm in normal_test_data: + reduced = _ddm_lll(basis_dm.rep.to_ddm(), delta=delta)[0] + assert reduced == reduced_dm.rep.to_ddm() + + reduced = ddm_lll(basis_dm.rep.to_ddm(), delta=delta) + assert reduced == reduced_dm.rep.to_ddm() + + reduced, transform = _ddm_lll(basis_dm.rep.to_ddm(), delta=delta, return_transform=True) + assert reduced == reduced_dm.rep.to_ddm() + assert transform.matmul(basis_dm.rep.to_ddm()) == reduced_dm.rep.to_ddm() + + reduced, transform = ddm_lll_transform(basis_dm.rep.to_ddm(), delta=delta) + assert reduced == reduced_dm.rep.to_ddm() + assert transform.matmul(basis_dm.rep.to_ddm()) == reduced_dm.rep.to_ddm() + + reduced = basis_dm.rep.lll(delta=delta) + assert reduced == reduced_dm.rep + + reduced, transform = basis_dm.rep.lll_transform(delta=delta) + assert reduced == reduced_dm.rep + assert transform.matmul(basis_dm.rep) == reduced_dm.rep + + reduced = basis_dm.rep.to_sdm().lll(delta=delta) + assert reduced == reduced_dm.rep.to_sdm() + + reduced, transform = basis_dm.rep.to_sdm().lll_transform(delta=delta) + assert reduced == reduced_dm.rep.to_sdm() + assert transform.matmul(basis_dm.rep.to_sdm()) == reduced_dm.rep.to_sdm() + + reduced = basis_dm.lll(delta=delta) + assert reduced == reduced_dm + + reduced, transform = basis_dm.lll_transform(delta=delta) + assert reduced == reduced_dm + assert transform.matmul(basis_dm) == reduced_dm + + +def test_lll_linear_dependent(): + linear_dependent_test_data = [ + DM([[0, -1, -2, -3], + [1, 0, -1, -2], + [2, 1, 0, -1], + [3, 2, 1, 0]], ZZ), + DM([[1, 0, 0, 1], + [0, 1, 0, 1], + [0, 0, 1, 1], + [1, 2, 3, 6]], ZZ), + DM([[3, -5, 1], + [4, 6, 0], + [10, -4, 2]], ZZ) + ] + for not_basis in linear_dependent_test_data: + raises(DMRankError, lambda: _ddm_lll(not_basis.rep.to_ddm())) + raises(DMRankError, lambda: ddm_lll(not_basis.rep.to_ddm())) + raises(DMRankError, lambda: not_basis.rep.lll()) + raises(DMRankError, lambda: not_basis.rep.to_sdm().lll()) + raises(DMRankError, lambda: not_basis.lll()) + raises(DMRankError, lambda: _ddm_lll(not_basis.rep.to_ddm(), return_transform=True)) + raises(DMRankError, lambda: ddm_lll_transform(not_basis.rep.to_ddm())) + raises(DMRankError, lambda: not_basis.rep.lll_transform()) + raises(DMRankError, lambda: not_basis.rep.to_sdm().lll_transform()) + raises(DMRankError, lambda: not_basis.lll_transform()) + + +def test_lll_wrong_delta(): + dummy_matrix = DomainMatrix.ones((3, 3), ZZ) + for wrong_delta in [QQ(-1, 4), QQ(0, 1), QQ(1, 4), QQ(1, 1), QQ(100, 1)]: + raises(DMValueError, lambda: _ddm_lll(dummy_matrix.rep, delta=wrong_delta)) + raises(DMValueError, lambda: ddm_lll(dummy_matrix.rep, delta=wrong_delta)) + raises(DMValueError, lambda: dummy_matrix.rep.lll(delta=wrong_delta)) + raises(DMValueError, lambda: dummy_matrix.rep.to_sdm().lll(delta=wrong_delta)) + raises(DMValueError, lambda: dummy_matrix.lll(delta=wrong_delta)) + raises(DMValueError, lambda: _ddm_lll(dummy_matrix.rep, delta=wrong_delta, return_transform=True)) + raises(DMValueError, lambda: ddm_lll_transform(dummy_matrix.rep, delta=wrong_delta)) + raises(DMValueError, lambda: dummy_matrix.rep.lll_transform(delta=wrong_delta)) + raises(DMValueError, lambda: dummy_matrix.rep.to_sdm().lll_transform(delta=wrong_delta)) + raises(DMValueError, lambda: dummy_matrix.lll_transform(delta=wrong_delta)) + + +def test_lll_wrong_shape(): + wrong_shape_matrix = DomainMatrix.ones((4, 3), ZZ) + raises(DMShapeError, lambda: _ddm_lll(wrong_shape_matrix.rep)) + raises(DMShapeError, lambda: ddm_lll(wrong_shape_matrix.rep)) + raises(DMShapeError, lambda: wrong_shape_matrix.rep.lll()) + raises(DMShapeError, lambda: wrong_shape_matrix.rep.to_sdm().lll()) + raises(DMShapeError, lambda: wrong_shape_matrix.lll()) + raises(DMShapeError, lambda: _ddm_lll(wrong_shape_matrix.rep, return_transform=True)) + raises(DMShapeError, lambda: ddm_lll_transform(wrong_shape_matrix.rep)) + raises(DMShapeError, lambda: wrong_shape_matrix.rep.lll_transform()) + raises(DMShapeError, lambda: wrong_shape_matrix.rep.to_sdm().lll_transform()) + raises(DMShapeError, lambda: wrong_shape_matrix.lll_transform()) + + +def test_lll_wrong_domain(): + wrong_domain_matrix = DomainMatrix.ones((3, 3), QQ) + raises(DMDomainError, lambda: _ddm_lll(wrong_domain_matrix.rep)) + raises(DMDomainError, lambda: ddm_lll(wrong_domain_matrix.rep)) + raises(DMDomainError, lambda: wrong_domain_matrix.rep.lll()) + raises(DMDomainError, lambda: wrong_domain_matrix.rep.to_sdm().lll()) + raises(DMDomainError, lambda: wrong_domain_matrix.lll()) + raises(DMDomainError, lambda: _ddm_lll(wrong_domain_matrix.rep, return_transform=True)) + raises(DMDomainError, lambda: ddm_lll_transform(wrong_domain_matrix.rep)) + raises(DMDomainError, lambda: wrong_domain_matrix.rep.lll_transform()) + raises(DMDomainError, lambda: wrong_domain_matrix.rep.to_sdm().lll_transform()) + raises(DMDomainError, lambda: wrong_domain_matrix.lll_transform()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_normalforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_normalforms.py new file mode 100644 index 0000000000000000000000000000000000000000..542d9064aea204759158578a4bfbbf5acbb06db3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_normalforms.py @@ -0,0 +1,156 @@ +from sympy.testing.pytest import raises + +from sympy.core.symbol import Symbol +from sympy.polys.matrices.normalforms import ( + invariant_factors, + smith_normal_form, + smith_normal_decomp, + is_smith_normal_form, + hermite_normal_form, + _hermite_normal_form, + _hermite_normal_form_modulo_D +) +from sympy.polys.domains import ZZ, QQ +from sympy.polys.matrices import DomainMatrix, DM +from sympy.polys.matrices.exceptions import DMDomainError, DMShapeError + + +def test_is_smith_normal_form(): + + snf_examples = [ + DM([[0, 0], [0, 0]], ZZ), + DM([[1, 0], [0, 0]], ZZ), + DM([[1, 0], [0, 1]], ZZ), + DM([[1, 0], [0, 2]], ZZ), + ] + + non_snf_examples = [ + DM([[0, 1], [0, 0]], ZZ), + DM([[0, 0], [0, 1]], ZZ), + DM([[2, 0], [0, 3]], ZZ), + ] + + for m in snf_examples: + assert is_smith_normal_form(m) is True + + for m in non_snf_examples: + assert is_smith_normal_form(m) is False + + +def test_smith_normal(): + + m = DM([ + [12, 6, 4, 8], + [3, 9, 6, 12], + [2, 16, 14, 28], + [20, 10, 10, 20]], ZZ) + + smf = DM([ + [1, 0, 0, 0], + [0, 10, 0, 0], + [0, 0, 30, 0], + [0, 0, 0, 0]], ZZ) + + s = DM([ + [0, 1, -1, 0], + [1, -4, 0, 0], + [0, -2, 3, 0], + [-2, 2, -1, 1]], ZZ) + + t = DM([ + [1, 1, 10, 0], + [0, -1, -2, 0], + [0, 1, 3, -2], + [0, 0, 0, 1]], ZZ) + + assert smith_normal_form(m).to_dense() == smf + assert smith_normal_decomp(m) == (smf, s, t) + assert is_smith_normal_form(smf) + assert smf == s * m * t + + m00 = DomainMatrix.zeros((0, 0), ZZ).to_dense() + m01 = DomainMatrix.zeros((0, 1), ZZ).to_dense() + m10 = DomainMatrix.zeros((1, 0), ZZ).to_dense() + i11 = DM([[1]], ZZ) + + assert smith_normal_form(m00) == m00.to_sparse() + assert smith_normal_form(m01) == m01.to_sparse() + assert smith_normal_form(m10) == m10.to_sparse() + assert smith_normal_form(i11) == i11.to_sparse() + + assert smith_normal_decomp(m00) == (m00, m00, m00) + assert smith_normal_decomp(m01) == (m01, m00, i11) + assert smith_normal_decomp(m10) == (m10, i11, m00) + assert smith_normal_decomp(i11) == (i11, i11, i11) + + x = Symbol('x') + m = DM([[x-1, 1, -1], + [ 0, x, -1], + [ 0, -1, x]], QQ[x]) + dx = m.domain.gens[0] + assert invariant_factors(m) == (1, dx-1, dx**2-1) + + zr = DomainMatrix([], (0, 2), ZZ) + zc = DomainMatrix([[], []], (2, 0), ZZ) + assert smith_normal_form(zr).to_dense() == zr + assert smith_normal_form(zc).to_dense() == zc + + assert smith_normal_form(DM([[2, 4]], ZZ)).to_dense() == DM([[2, 0]], ZZ) + assert smith_normal_form(DM([[0, -2]], ZZ)).to_dense() == DM([[2, 0]], ZZ) + assert smith_normal_form(DM([[0], [-2]], ZZ)).to_dense() == DM([[2], [0]], ZZ) + + assert smith_normal_decomp(DM([[0, -2]], ZZ)) == ( + DM([[2, 0]], ZZ), DM([[-1]], ZZ), DM([[0, 1], [1, 0]], ZZ) + ) + assert smith_normal_decomp(DM([[0], [-2]], ZZ)) == ( + DM([[2], [0]], ZZ), DM([[0, -1], [1, 0]], ZZ), DM([[1]], ZZ) + ) + + m = DM([[3, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0]], ZZ) + snf = DM([[1, 0, 0, 0], [0, 6, 0, 0], [0, 0, 0, 0]], ZZ) + s = DM([[1, 0, 1], [2, 0, 3], [0, 1, 0]], ZZ) + t = DM([[1, -2, 0, 0], [0, 0, 0, 1], [-1, 3, 0, 0], [0, 0, 1, 0]], ZZ) + + assert smith_normal_form(m).to_dense() == snf + assert smith_normal_decomp(m) == (snf, s, t) + assert is_smith_normal_form(snf) + assert snf == s * m * t + + raises(ValueError, lambda: smith_normal_form(DM([[1]], ZZ[x]))) + + +def test_hermite_normal(): + m = DM([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ) + hnf = DM([[1, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ) + assert hermite_normal_form(m) == hnf + assert hermite_normal_form(m, D=ZZ(2)) == hnf + assert hermite_normal_form(m, D=ZZ(2), check_rank=True) == hnf + + m = m.transpose() + hnf = DM([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]], ZZ) + assert hermite_normal_form(m) == hnf + raises(DMShapeError, lambda: _hermite_normal_form_modulo_D(m, ZZ(96))) + raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, QQ(96))) + + m = DM([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ) + hnf = DM([[4, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ) + assert hermite_normal_form(m) == hnf + assert hermite_normal_form(m, D=ZZ(8)) == hnf + assert hermite_normal_form(m, D=ZZ(8), check_rank=True) == hnf + + m = DM([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]], ZZ) + hnf = DM([[26, 2], [0, 9], [0, 1]], ZZ) + assert hermite_normal_form(m) == hnf + + m = DM([[2, 7], [0, 0], [0, 0]], ZZ) + hnf = DM([[1], [0], [0]], ZZ) + assert hermite_normal_form(m) == hnf + + m = DM([[-2, 1], [0, 1]], ZZ) + hnf = DM([[2, 1], [0, 1]], ZZ) + assert hermite_normal_form(m) == hnf + + m = DomainMatrix([[QQ(1)]], (1, 1), QQ) + raises(DMDomainError, lambda: hermite_normal_form(m)) + raises(DMDomainError, lambda: _hermite_normal_form(m)) + raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, ZZ(1))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_nullspace.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_nullspace.py new file mode 100644 index 0000000000000000000000000000000000000000..dbb025b7dc9dff31bc97d86e175147ffede5a7e3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_nullspace.py @@ -0,0 +1,209 @@ +from sympy import ZZ, Matrix +from sympy.polys.matrices import DM, DomainMatrix +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.sdm import SDM + +import pytest + +zeros = lambda shape, K: DomainMatrix.zeros(shape, K).to_dense() +eye = lambda n, K: DomainMatrix.eye(n, K).to_dense() + + +# +# DomainMatrix.nullspace can have a divided answer or can return an undivided +# uncanonical answer. The uncanonical answer is not unique but we can make it +# unique by making it primitive (remove gcd). The tests here all show the +# primitive form. We test two things: +# +# A.nullspace().primitive()[1] == answer. +# A.nullspace(divide_last=True) == _divide_last(answer). +# +# The nullspace as returned by DomainMatrix and related classes is the +# transpose of the nullspace as returned by Matrix. Matrix returns a list of +# of column vectors whereas DomainMatrix returns a matrix whose rows are the +# nullspace vectors. +# + + +NULLSPACE_EXAMPLES = [ + + ( + 'zz_1', + DM([[ 1, 2, 3]], ZZ), + DM([[-2, 1, 0], + [-3, 0, 1]], ZZ), + ), + + ( + 'zz_2', + zeros((0, 0), ZZ), + zeros((0, 0), ZZ), + ), + + ( + 'zz_3', + zeros((2, 0), ZZ), + zeros((0, 0), ZZ), + ), + + ( + 'zz_4', + zeros((0, 2), ZZ), + eye(2, ZZ), + ), + + ( + 'zz_5', + zeros((2, 2), ZZ), + eye(2, ZZ), + ), + + ( + 'zz_6', + DM([[1, 2], + [3, 4]], ZZ), + zeros((0, 2), ZZ), + ), + + ( + 'zz_7', + DM([[1, 1], + [1, 1]], ZZ), + DM([[-1, 1]], ZZ), + ), + + ( + 'zz_8', + DM([[1], + [1]], ZZ), + zeros((0, 1), ZZ), + ), + + ( + 'zz_9', + DM([[1, 1]], ZZ), + DM([[-1, 1]], ZZ), + ), + + ( + 'zz_10', + DM([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], ZZ), + DM([[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + [-1, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [ 0, -1, 0, 0, 0, 0, 0, 1, 0, 0], + [ 0, 0, 0, -1, 0, 0, 0, 0, 1, 0], + [ 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]], ZZ), + ), + +] + + +def _to_DM(A, ans): + """Convert the answer to DomainMatrix.""" + if isinstance(A, DomainMatrix): + return A.to_dense() + elif isinstance(A, DDM): + return DomainMatrix(list(A), A.shape, A.domain).to_dense() + elif isinstance(A, SDM): + return DomainMatrix(dict(A), A.shape, A.domain).to_dense() + else: + assert False # pragma: no cover + + +def _divide_last(null): + """Normalize the nullspace by the rightmost non-zero entry.""" + null = null.to_field() + + if null.is_zero_matrix: + return null + + rows = [] + for i in range(null.shape[0]): + for j in reversed(range(null.shape[1])): + if null[i, j]: + rows.append(null[i, :] / null[i, j]) + break + else: + assert False # pragma: no cover + + return DomainMatrix.vstack(*rows) + + +def _check_primitive(null, null_ans): + """Check that the primitive of the answer matches.""" + null = _to_DM(null, null_ans) + cont, null_prim = null.primitive() + assert null_prim == null_ans + + +def _check_divided(null, null_ans): + """Check the divided answer.""" + null = _to_DM(null, null_ans) + null_ans_norm = _divide_last(null_ans) + assert null == null_ans_norm + + +@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES) +def test_Matrix_nullspace(name, A, A_null): + A = A.to_Matrix() + + A_null_cols = A.nullspace() + + # We have to patch up the case where the nullspace is empty + if A_null_cols: + A_null_found = Matrix.hstack(*A_null_cols) + else: + A_null_found = Matrix.zeros(A.cols, 0) + + A_null_found = A_null_found.to_DM().to_field().to_dense() + + # The Matrix result is the transpose of DomainMatrix result. + A_null_found = A_null_found.transpose() + + _check_divided(A_null_found, A_null) + + +@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES) +def test_dm_dense_nullspace(name, A, A_null): + A = A.to_field().to_dense() + A_null_found = A.nullspace(divide_last=True) + _check_divided(A_null_found, A_null) + + +@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES) +def test_dm_sparse_nullspace(name, A, A_null): + A = A.to_field().to_sparse() + A_null_found = A.nullspace(divide_last=True) + _check_divided(A_null_found, A_null) + + +@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES) +def test_ddm_nullspace(name, A, A_null): + A = A.to_field().to_ddm() + A_null_found, _ = A.nullspace() + _check_divided(A_null_found, A_null) + + +@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES) +def test_sdm_nullspace(name, A, A_null): + A = A.to_field().to_sdm() + A_null_found, _ = A.nullspace() + _check_divided(A_null_found, A_null) + + +@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES) +def test_dm_dense_nullspace_fracfree(name, A, A_null): + A = A.to_dense() + A_null_found = A.nullspace() + _check_primitive(A_null_found, A_null) + + +@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES) +def test_dm_sparse_nullspace_fracfree(name, A, A_null): + A = A.to_sparse() + A_null_found = A.nullspace() + _check_primitive(A_null_found, A_null) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_rref.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_rref.py new file mode 100644 index 0000000000000000000000000000000000000000..49def18c8132c0537540163a96bf6cf323c5a85c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_rref.py @@ -0,0 +1,737 @@ +from sympy import ZZ, QQ, ZZ_I, EX, Matrix, eye, zeros, symbols +from sympy.polys.matrices import DM, DomainMatrix +from sympy.polys.matrices.dense import ddm_irref_den, ddm_irref +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.sdm import SDM, sdm_irref, sdm_rref_den + +import pytest + + +# +# The dense and sparse implementations of rref_den are ddm_irref_den and +# sdm_irref_den. These can give results that differ by some factor and also +# give different results if the order of the rows is changed. The tests below +# show all results on lowest terms as should be returned by cancel_denom. +# +# The EX domain is also a case where the dense and sparse implementations +# can give results in different forms: the results should be equivalent but +# are not canonical because EX does not have a canonical form. +# + + +a, b, c, d = symbols('a, b, c, d') + + +qq_large_1 = DM([ +[ (1,2), (1,3), (1,5), (1,7), (1,11), (1,13), (1,17), (1,19), (1,23), (1,29), (1,31)], +[ (1,37), (1,41), (1,43), (1,47), (1,53), (1,59), (1,61), (1,67), (1,71), (1,73), (1,79)], +[ (1,83), (1,89), (1,97),(1,101),(1,103),(1,107),(1,109),(1,113),(1,127),(1,131),(1,137)], +[(1,139),(1,149),(1,151),(1,157),(1,163),(1,167),(1,173),(1,179),(1,181),(1,191),(1,193)], +[(1,197),(1,199),(1,211),(1,223),(1,227),(1,229),(1,233),(1,239),(1,241),(1,251),(1,257)], +[(1,263),(1,269),(1,271),(1,277),(1,281),(1,283),(1,293),(1,307),(1,311),(1,313),(1,317)], +[(1,331),(1,337),(1,347),(1,349),(1,353),(1,359),(1,367),(1,373),(1,379),(1,383),(1,389)], +[(1,397),(1,401),(1,409),(1,419),(1,421),(1,431),(1,433),(1,439),(1,443),(1,449),(1,457)], +[(1,461),(1,463),(1,467),(1,479),(1,487),(1,491),(1,499),(1,503),(1,509),(1,521),(1,523)], +[(1,541),(1,547),(1,557),(1,563),(1,569),(1,571),(1,577),(1,587),(1,593),(1,599),(1,601)], +[(1,607),(1,613),(1,617),(1,619),(1,631),(1,641),(1,643),(1,647),(1,653),(1,659),(1,661)]], + QQ) + +qq_large_2 = qq_large_1 + 10**100 * DomainMatrix.eye(11, QQ) + + +RREF_EXAMPLES = [ + ( + 'zz_1', + DM([[1, 2, 3]], ZZ), + DM([[1, 2, 3]], ZZ), + ZZ(1), + ), + + ( + 'zz_2', + DomainMatrix([], (0, 0), ZZ), + DomainMatrix([], (0, 0), ZZ), + ZZ(1), + ), + + ( + 'zz_3', + DM([[1, 2], + [3, 4]], ZZ), + DM([[1, 0], + [0, 1]], ZZ), + ZZ(1), + ), + + ( + 'zz_4', + DM([[1, 0], + [3, 4]], ZZ), + DM([[1, 0], + [0, 1]], ZZ), + ZZ(1), + ), + + ( + 'zz_5', + DM([[0, 2], + [3, 4]], ZZ), + DM([[1, 0], + [0, 1]], ZZ), + ZZ(1), + ), + + ( + 'zz_6', + DM([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], ZZ), + DM([[1, 0, -1], + [0, 1, 2], + [0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_7', + DM([[0, 0, 0], + [0, 0, 0], + [1, 0, 0]], ZZ), + DM([[1, 0, 0], + [0, 0, 0], + [0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_8', + DM([[0, 0, 0], + [0, 0, 0], + [0, 0, 0]], ZZ), + DM([[0, 0, 0], + [0, 0, 0], + [0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_9', + DM([[1, 1, 0], + [0, 0, 2], + [0, 0, 0]], ZZ), + DM([[1, 1, 0], + [0, 0, 1], + [0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_10', + DM([[2, 2, 0], + [0, 0, 2], + [0, 0, 0]], ZZ), + DM([[1, 1, 0], + [0, 0, 1], + [0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_11', + DM([[2, 2, 0], + [0, 2, 2], + [0, 0, 2]], ZZ), + DM([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]], ZZ), + ZZ(1), + ), + + ( + 'zz_12', + DM([[ 1, 2, 3], + [ 4, 5, 6], + [ 7, 8, 9], + [10, 11, 12]], ZZ), + DM([[1, 0, -1], + [0, 1, 2], + [0, 0, 0], + [0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_13', + DM([[ 1, 2, 3], + [ 4, 5, 6], + [ 7, 8, 9], + [10, 11, 13]], ZZ), + DM([[ 1, 0, 0], + [ 0, 1, 0], + [ 0, 0, 1], + [ 0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_14', + DM([[1, 2, 4, 3], + [4, 5, 10, 6], + [7, 8, 16, 9]], ZZ), + DM([[1, 0, 0, -1], + [0, 1, 2, 2], + [0, 0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_15', + DM([[1, 2, 4, 3], + [4, 5, 10, 6], + [7, 8, 17, 9]], ZZ), + DM([[1, 0, 0, -1], + [0, 1, 0, 2], + [0, 0, 1, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_16', + DM([[1, 2, 0, 1], + [1, 1, 9, 0]], ZZ), + DM([[1, 0, 18, -1], + [0, 1, -9, 1]], ZZ), + ZZ(1), + ), + + ( + 'zz_17', + DM([[1, 1, 1], + [1, 2, 2]], ZZ), + DM([[1, 0, 0], + [0, 1, 1]], ZZ), + ZZ(1), + ), + + ( + # Here the sparse implementation and dense implementation give very + # different denominators: 4061232 and -1765176. + 'zz_18', + DM([[94, 24, 0, 27, 0], + [79, 0, 0, 0, 0], + [85, 16, 71, 81, 0], + [ 0, 0, 72, 77, 0], + [21, 0, 34, 0, 0]], ZZ), + DM([[ 1, 0, 0, 0, 0], + [ 0, 1, 0, 0, 0], + [ 0, 0, 1, 0, 0], + [ 0, 0, 0, 1, 0], + [ 0, 0, 0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + # Let's have a denominator that cannot be cancelled. + 'zz_19', + DM([[1, 2, 4], + [4, 5, 6]], ZZ), + DM([[3, 0, -8], + [0, 3, 10]], ZZ), + ZZ(3), + ), + + ( + 'zz_20', + DM([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 4]], ZZ), + DM([[0, 0, 0, 0, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_21', + DM([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], ZZ), + DM([[1, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_22', + DM([[1, 1, 1, 0, 1], + [1, 1, 0, 1, 0], + [1, 0, 1, 0, 1], + [1, 1, 0, 1, 0], + [1, 0, 0, 0, 0]], ZZ), + DM([[1, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 1], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], ZZ), + ZZ(1), + ), + + ( + 'zz_large_1', + DM([ +[ 0, 0, 0, 81, 0, 0, 75, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0], +[ 0, 0, 0, 0, 0, 86, 0, 92, 79, 54, 0, 7, 0, 0, 0, 0, 79, 0, 0, 0], +[89, 54, 81, 0, 0, 20, 0, 0, 0, 0, 0, 0, 51, 0, 94, 0, 0, 77, 0, 0], +[ 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 48, 29, 0, 0, 5, 0, 32, 0], +[ 0, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 11], +[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 43, 0, 0], +[ 0, 0, 0, 0, 0, 38, 91, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 26, 0, 0], +[69, 0, 0, 0, 0, 0, 94, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 55], +[ 0, 13, 18, 49, 49, 88, 0, 0, 35, 54, 0, 0, 51, 0, 0, 0, 0, 0, 0, 87], +[ 0, 0, 0, 0, 31, 0, 40, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 88, 0], +[ 0, 0, 0, 0, 0, 0, 0, 0, 98, 0, 0, 0, 15, 53, 0, 92, 0, 0, 0, 0], +[ 0, 0, 0, 95, 0, 0, 0, 36, 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, 73, 19], +[ 0, 65, 14, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 0, 0, 0, 34, 0, 0], +[ 0, 0, 0, 16, 39, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 0], +[ 0, 17, 0, 0, 0, 99, 84, 13, 50, 84, 0, 0, 0, 0, 95, 0, 43, 33, 20, 0], +[79, 0, 17, 52, 99, 12, 69, 0, 98, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[ 0, 0, 0, 82, 0, 44, 0, 0, 0, 97, 0, 0, 0, 0, 0, 10, 0, 0, 31, 0], +[ 0, 0, 21, 0, 67, 0, 0, 0, 0, 0, 4, 0, 50, 0, 0, 0, 33, 0, 0, 0], +[ 0, 0, 0, 0, 9, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8], +[ 0, 77, 0, 0, 0, 0, 0, 0, 0, 0, 34, 93, 0, 0, 0, 0, 47, 0, 0, 0]], + ZZ), + DM([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], ZZ), + ZZ(1), + ), + + ( + 'zz_large_2', + DM([ +[ 0, 0, 0, 0, 50, 0, 6, 81, 0, 1, 86, 0, 0, 98, 82, 94, 4, 0, 0, 29], +[ 0, 44, 43, 0, 62, 0, 0, 0, 60, 0, 0, 0, 0, 71, 9, 0, 57, 41, 0, 93], +[ 0, 0, 28, 0, 74, 89, 42, 0, 28, 0, 6, 0, 0, 0, 44, 0, 0, 0, 77, 19], +[ 0, 21, 82, 0, 30, 88, 0, 89, 68, 0, 0, 0, 79, 41, 0, 0, 99, 0, 0, 0], +[31, 0, 0, 0, 19, 64, 0, 0, 79, 0, 5, 0, 72, 10, 60, 32, 64, 59, 0, 24], +[ 0, 0, 0, 0, 0, 57, 0, 94, 0, 83, 20, 0, 0, 9, 31, 0, 49, 26, 58, 0], +[ 0, 65, 56, 31, 64, 0, 0, 0, 0, 0, 0, 52, 85, 0, 0, 0, 0, 51, 0, 0], +[ 0, 35, 0, 0, 0, 69, 0, 0, 64, 0, 0, 0, 0, 70, 0, 0, 90, 0, 75, 76], +[69, 7, 0, 90, 0, 0, 84, 0, 47, 69, 19, 20, 42, 0, 0, 32, 71, 35, 0, 0], +[39, 0, 90, 0, 0, 4, 85, 0, 0, 55, 0, 0, 0, 35, 67, 40, 0, 40, 0, 77], +[98, 63, 0, 71, 0, 50, 0, 2, 61, 0, 38, 0, 0, 0, 0, 75, 0, 40, 33, 56], +[ 0, 73, 0, 64, 0, 38, 0, 35, 61, 0, 0, 52, 0, 7, 0, 51, 0, 0, 0, 34], +[ 0, 0, 28, 0, 34, 5, 63, 45, 14, 42, 60, 16, 76, 54, 99, 0, 28, 30, 0, 0], +[58, 37, 14, 0, 0, 0, 94, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 8, 90, 53], +[86, 74, 94, 0, 49, 10, 60, 0, 40, 18, 0, 0, 0, 31, 60, 24, 0, 1, 0, 29], +[53, 0, 0, 97, 0, 0, 58, 0, 0, 39, 44, 47, 0, 0, 0, 12, 50, 0, 0, 11], +[ 4, 0, 92, 10, 28, 0, 0, 89, 0, 0, 18, 54, 23, 39, 0, 2, 0, 48, 0, 92], +[ 0, 0, 90, 77, 95, 33, 0, 0, 49, 22, 39, 0, 0, 0, 0, 0, 0, 40, 0, 0], +[96, 0, 0, 0, 0, 38, 86, 0, 22, 76, 0, 0, 0, 0, 83, 88, 95, 65, 72, 0], +[81, 65, 0, 4, 60, 0, 19, 0, 0, 68, 0, 0, 89, 0, 67, 22, 0, 0, 55, 33]], + ZZ), + DM([ +[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], +[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], + ZZ), + ZZ(1), + ), + + ( + 'zz_large_3', + DM([ +[62,35,89,58,22,47,30,28,52,72,17,56,80,26,64,21,10,35,24,42,96,32,23,50,92,37,76,94,63,66], +[20,47,96,34,10,98,19,6,29,2,19,92,61,94,38,41,32,9,5,94,31,58,27,41,72,85,61,62,40,46], +[69,26,35,68,25,52,94,13,38,65,81,10,29,15,5,4,13,99,85,0,80,51,60,60,26,77,85,2,87,25], +[99,58,69,15,52,12,18,7,27,56,12,54,21,92,38,95,33,83,28,1,44,8,29,84,92,12,2,25,46,46], +[93,13,55,48,35,87,24,40,23,35,25,32,0,19,0,85,4,79,26,11,46,75,7,96,76,11,7,57,99,75], +[128,85,26,51,161,173,77,78,85,103,123,58,91,147,38,91,161,36,123,81,102,25,75,59,17,150,112,65,77,143], +[15,59,61,82,12,83,34,8,94,71,66,7,91,21,48,69,26,12,64,38,97,87,38,15,51,33,93,43,66,89], +[74,74,53,39,69,90,41,80,32,66,40,83,87,87,61,38,12,80,24,49,37,90,19,33,56,0,46,57,56,60], +[82,11,0,25,56,58,39,49,92,93,80,38,19,62,33,85,19,61,14,30,45,91,97,34,97,53,92,28,33,43], +[83,79,41,16,95,35,53,45,26,4,71,76,61,69,69,72,87,92,59,72,54,11,22,83,8,57,77,55,19,22], +[49,34,13,31,72,77,52,70,46,41,37,6,42,66,35,6,75,33,62,57,30,14,26,31,9,95,89,13,12,90], +[29,3,49,30,51,32,77,41,38,50,16,1,87,81,93,88,58,91,83,0,38,67,29,64,60,84,5,60,23,28], +[79,51,13,20,89,96,25,8,39,62,86,52,49,81,3,85,86,3,61,24,72,11,49,28,8,55,23,52,65,53], +[96,86,73,20,41,20,37,18,10,61,85,24,40,83,69,41,4,92,23,99,64,33,18,36,32,56,60,98,39,24], +[32,62,47,80,51,66,17,1,9,30,65,75,75,88,99,92,64,53,53,86,38,51,41,14,35,18,39,25,26,32], +[39,21,8,16,33,6,35,85,75,62,43,34,18,68,71,28,32,18,12,0,81,53,1,99,3,5,45,99,35,33], +[19,95,89,45,75,94,92,5,84,93,34,17,50,56,79,98,68,82,65,81,51,90,5,95,33,71,46,61,14,7], +[53,92,8,49,67,84,21,79,49,95,66,48,36,14,62,97,26,45,58,31,83,48,11,89,67,72,91,34,56,89], +[56,76,99,92,40,8,0,16,15,48,35,72,91,46,81,14,86,60,51,7,33,12,53,78,48,21,3,89,15,79], +[81,43,33,49,6,49,36,32,57,74,87,91,17,37,31,17,67,1,40,38,69,8,3,48,59,37,64,97,11,3], +[98,48,77,16,2,48,57,38,63,59,79,35,16,71,60,86,71,41,14,76,80,97,77,69,4,58,22,55,26,73], +[80,47,78,44,31,48,47,29,29,62,19,21,17,24,19,3,53,93,97,57,13,54,12,10,77,66,60,75,32,21], +[86,63,2,13,71,38,86,23,18,15,91,65,77,65,9,92,50,0,17,42,99,80,99,27,10,99,92,9,87,84], +[66,27,72,13,13,15,72,75,39,3,14,71,15,68,10,19,49,54,11,29,47,20,63,13,97,47,24,62,16,96], +[42,63,83,60,49,68,9,53,75,87,40,25,12,63,0,12,0,95,46,46,55,25,89,1,51,1,1,96,80,52], +[35,9,97,13,86,39,66,48,41,57,23,38,11,9,35,72,88,13,41,60,10,64,71,23,1,5,23,57,6,19], +[70,61,5,50,72,60,77,13,41,94,1,45,52,22,99,47,27,18,99,42,16,48,26,9,88,77,10,94,11,92], +[55,68,58,2,72,56,81,52,79,37,1,40,21,46,27,60,37,13,97,42,85,98,69,60,76,44,42,46,29,73], +[73,0,43,17,89,97,45,2,68,14,55,60,95,2,74,85,88,68,93,76,38,76,2,51,45,76,50,79,56,18], +[72,58,41,39,24,80,23,79,44,7,98,75,30,6,85,60,20,58,77,71,90,51,38,80,30,15,33,10,82,8]], + ZZ), + Matrix([ + [eye(29) * 2028539767964472550625641331179545072876560857886207583101, + Matrix([ 4260575808093245475167216057435155595594339172099000182569, + 169148395880755256182802335904188369274227936894862744452, + 4915975976683942569102447281579134986891620721539038348914, + 6113916866367364958834844982578214901958429746875633283248, + 5585689617819894460378537031623265659753379011388162534838, + 359776822829880747716695359574308645968094838905181892423, + -2800926112141776386671436511182421432449325232461665113305, + 941642292388230001722444876624818265766384442910688463158, + 3648811843256146649321864698600908938933015862008642023935, + -4104526163246702252932955226754097174212129127510547462419, + -704814955438106792441896903238080197619233342348191408078, + 1640882266829725529929398131287244562048075707575030019335, + -4068330845192910563212155694231438198040299927120544468520, + 136589038308366497790495711534532612862715724187671166593, + 2544937011460702462290799932536905731142196510605191645593, + 755591839174293940486133926192300657264122907519174116472, + -3683838489869297144348089243628436188645897133242795965021, + -522207137101161299969706310062775465103537953077871128403, + -2260451796032703984456606059649402832441331339246756656334, + -6476809325293587953616004856993300606040336446656916663680, + 3521944238996782387785653800944972787867472610035040989081, + 2270762115788407950241944504104975551914297395787473242379, + -3259947194628712441902262570532921252128444706733549251156, + -5624569821491886970999097239695637132075823246850431083557, + -3262698255682055804320585332902837076064075936601504555698, + 5786719943788937667411185880136324396357603606944869545501, + -955257841973865996077323863289453200904051299086000660036, + -1294235552446355326174641248209752679127075717918392702116, + -3718353510747301598130831152458342785269166356215331448279, + ]),], + [zeros(1, 29), zeros(1, 1)], + ]).to_DM().to_dense(), + ZZ(2028539767964472550625641331179545072876560857886207583101), + ), + + + ( + 'qq_1', + DM([[(1,2), 0], [0, 2]], QQ), + DM([[1, 0], [0, 1]], QQ), + QQ(1), + ), + + ( + # Standard square case + 'qq_2', + DM([[0, 1], + [1, 1]], QQ), + DM([[1, 0], + [0, 1]], QQ), + QQ(1), + ), + + ( + # m < n case + 'qq_3', + DM([[1, 2, 1], + [3, 4, 1]], QQ), + DM([[1, 0, -1], + [0, 1, 1]], QQ), + QQ(1), + ), + + ( + # same m < n but reversed + 'qq_4', + DM([[3, 4, 1], + [1, 2, 1]], QQ), + DM([[1, 0, -1], + [0, 1, 1]], QQ), + QQ(1), + ), + + ( + # m > n case + 'qq_5', + DM([[1, 0], + [1, 3], + [0, 1]], QQ), + DM([[1, 0], + [0, 1], + [0, 0]], QQ), + QQ(1), + ), + + ( + # Example with missing pivot + 'qq_6', + DM([[1, 0, 1], + [3, 0, 1]], QQ), + DM([[1, 0, 0], + [0, 0, 1]], QQ), + QQ(1), + ), + + ( + # This is intended to trigger the threshold where we give up on + # clearing denominators. + 'qq_large_1', + qq_large_1, + DomainMatrix.eye(11, QQ).to_dense(), + QQ(1), + ), + + ( + # This is intended to trigger the threshold where we use rref_den over + # QQ. + 'qq_large_2', + qq_large_2, + DomainMatrix.eye(11, QQ).to_dense(), + QQ(1), + ), + + ( + # Example with missing pivot and no replacement + + # This example is just enough to show a different result from the dense + # and sparse versions of the algorithm: + # + # >>> A = Matrix([[0, 1], [0, 2], [1, 0]]) + # >>> A.to_DM().to_sparse().rref_den()[0].to_Matrix() + # Matrix([ + # [1, 0], + # [0, 1], + # [0, 0]]) + # >>> A.to_DM().to_dense().rref_den()[0].to_Matrix() + # Matrix([ + # [2, 0], + # [0, 2], + # [0, 0]]) + # + 'qq_7', + DM([[0, 1], + [0, 2], + [1, 0]], QQ), + DM([[1, 0], + [0, 1], + [0, 0]], QQ), + QQ(1), + ), + + ( + # Gaussian integers + 'zz_i_1', + DM([[(0,1), 1, 1], + [ 1, 1, 1]], ZZ_I), + DM([[1, 0, 0], + [0, 1, 1]], ZZ_I), + ZZ_I(1), + ), + + ( + # EX: test_issue_23718 + 'EX_1', + DM([ + [a, b, 1], + [c, d, 1]], EX), + DM([[a*d - b*c, 0, -b + d], + [ 0, a*d - b*c, a - c]], EX), + EX(a*d - b*c), + ), + +] + + +def _to_DM(A, ans): + """Convert the answer to DomainMatrix.""" + if isinstance(A, DomainMatrix): + return A.to_dense() + elif isinstance(A, Matrix): + return A.to_DM(ans.domain).to_dense() + + if not (hasattr(A, 'shape') and hasattr(A, 'domain')): + shape, domain = ans.shape, ans.domain + else: + shape, domain = A.shape, A.domain + + if isinstance(A, (DDM, list)): + return DomainMatrix(list(A), shape, domain).to_dense() + elif isinstance(A, (SDM, dict)): + return DomainMatrix(dict(A), shape, domain).to_dense() + else: + assert False # pragma: no cover + + +def _pivots(A_rref): + """Return the pivots from the rref of A.""" + return tuple(sorted(map(min, A_rref.to_sdm().values()))) + + +def _check_cancel(result, rref_ans, den_ans): + """Check the cancelled result.""" + rref, den, pivots = result + if isinstance(rref, (DDM, SDM, list, dict)): + assert type(pivots) is list + pivots = tuple(pivots) + rref = _to_DM(rref, rref_ans) + rref2, den2 = rref.cancel_denom(den) + assert rref2 == rref_ans + assert den2 == den_ans + assert pivots == _pivots(rref) + + +def _check_divide(result, rref_ans, den_ans): + """Check the divided result.""" + rref, pivots = result + if isinstance(rref, (DDM, SDM, list, dict)): + assert type(pivots) is list + pivots = tuple(pivots) + rref_ans = rref_ans.to_field() / den_ans + rref = _to_DM(rref, rref_ans) + assert rref == rref_ans + assert _pivots(rref) == pivots + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_Matrix_rref(name, A, A_rref, den): + K = A.domain + A = A.to_Matrix() + A_rref_found, pivots = A.rref() + if K.is_EX: + A_rref_found = A_rref_found.expand() + _check_divide((A_rref_found, pivots), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_dm_dense_rref(name, A, A_rref, den): + A = A.to_field() + _check_divide(A.rref(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_dm_dense_rref_den(name, A, A_rref, den): + _check_cancel(A.rref_den(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_dm_sparse_rref(name, A, A_rref, den): + A = A.to_field().to_sparse() + _check_divide(A.rref(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_dm_sparse_rref_den(name, A, A_rref, den): + A = A.to_sparse() + _check_cancel(A.rref_den(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_dm_sparse_rref_den_keep_domain(name, A, A_rref, den): + A = A.to_sparse() + A_rref_f, den_f, pivots_f = A.rref_den(keep_domain=False) + A_rref_f = A_rref_f.to_field() / den_f + _check_divide((A_rref_f, pivots_f), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_dm_sparse_rref_den_keep_domain_CD(name, A, A_rref, den): + A = A.to_sparse() + A_rref_f, den_f, pivots_f = A.rref_den(keep_domain=False, method='CD') + A_rref_f = A_rref_f.to_field() / den_f + _check_divide((A_rref_f, pivots_f), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_dm_sparse_rref_den_keep_domain_GJ(name, A, A_rref, den): + A = A.to_sparse() + A_rref_f, den_f, pivots_f = A.rref_den(keep_domain=False, method='GJ') + A_rref_f = A_rref_f.to_field() / den_f + _check_divide((A_rref_f, pivots_f), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_ddm_rref_den(name, A, A_rref, den): + A = A.to_ddm() + _check_cancel(A.rref_den(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_sdm_rref_den(name, A, A_rref, den): + A = A.to_sdm() + _check_cancel(A.rref_den(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_ddm_rref(name, A, A_rref, den): + A = A.to_field().to_ddm() + _check_divide(A.rref(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_sdm_rref(name, A, A_rref, den): + A = A.to_field().to_sdm() + _check_divide(A.rref(), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_ddm_irref(name, A, A_rref, den): + A = A.to_field().to_ddm().copy() + pivots_found = ddm_irref(A) + _check_divide((A, pivots_found), A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_ddm_irref_den(name, A, A_rref, den): + A = A.to_ddm().copy() + (den_found, pivots_found) = ddm_irref_den(A, A.domain) + result = (A, den_found, pivots_found) + _check_cancel(result, A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_sparse_sdm_rref(name, A, A_rref, den): + A = A.to_field().to_sdm() + _check_divide(sdm_irref(A)[:2], A_rref, den) + + +@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES) +def test_sparse_sdm_rref_den(name, A, A_rref, den): + A = A.to_sdm().copy() + K = A.domain + _check_cancel(sdm_rref_den(A, K), A_rref, den) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_sdm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_sdm.py new file mode 100644 index 0000000000000000000000000000000000000000..cd7e5d460a1b2d44279a2a1772cc901f80ca733e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_sdm.py @@ -0,0 +1,428 @@ +""" +Tests for the basic functionality of the SDM class. +""" + +from itertools import product + +from sympy.core.singleton import S +from sympy.external.gmpy import GROUND_TYPES +from sympy.testing.pytest import raises + +from sympy.polys.domains import QQ, ZZ, EXRAW +from sympy.polys.matrices.sdm import SDM +from sympy.polys.matrices.ddm import DDM +from sympy.polys.matrices.exceptions import (DMBadInputError, DMDomainError, + DMShapeError) + + +def test_SDM(): + A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) + assert A.domain == ZZ + assert A.shape == (2, 2) + assert dict(A) == {0:{0:ZZ(1)}} + + raises(DMBadInputError, lambda: SDM({5:{1:ZZ(0)}}, (2, 2), ZZ)) + raises(DMBadInputError, lambda: SDM({0:{5:ZZ(0)}}, (2, 2), ZZ)) + + +def test_DDM_str(): + sdm = SDM({0:{0:ZZ(1)}, 1:{1:ZZ(1)}}, (2, 2), ZZ) + assert str(sdm) == '{0: {0: 1}, 1: {1: 1}}' + if GROUND_TYPES == 'gmpy': # pragma: no cover + assert repr(sdm) == 'SDM({0: {0: mpz(1)}, 1: {1: mpz(1)}}, (2, 2), ZZ)' + else: # pragma: no cover + assert repr(sdm) == 'SDM({0: {0: 1}, 1: {1: 1}}, (2, 2), ZZ)' + + +def test_SDM_new(): + A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) + B = A.new({}, (2, 2), ZZ) + assert B == SDM({}, (2, 2), ZZ) + + +def test_SDM_copy(): + A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) + B = A.copy() + assert A == B + A[0][0] = ZZ(2) + assert A != B + + +def test_SDM_from_list(): + A = SDM.from_list([[ZZ(0), ZZ(1)], [ZZ(1), ZZ(0)]], (2, 2), ZZ) + assert A == SDM({0:{1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + + raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ)) + raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0), ZZ(1)]], (2, 2), ZZ)) + + +def test_SDM_to_list(): + A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) + assert A.to_list() == [[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]] + + A = SDM({}, (0, 2), ZZ) + assert A.to_list() == [] + + A = SDM({}, (2, 0), ZZ) + assert A.to_list() == [[], []] + + +def test_SDM_to_list_flat(): + A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) + assert A.to_list_flat() == [ZZ(0), ZZ(1), ZZ(0), ZZ(0)] + + +def test_SDM_to_dok(): + A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) + assert A.to_dok() == {(0, 1): ZZ(1)} + + +def test_SDM_from_ddm(): + A = DDM([[ZZ(1), ZZ(0)], [ZZ(1), ZZ(0)]], (2, 2), ZZ) + B = SDM.from_ddm(A) + assert B.domain == ZZ + assert B.shape == (2, 2) + assert dict(B) == {0:{0:ZZ(1)}, 1:{0:ZZ(1)}} + + +def test_SDM_to_ddm(): + A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) + B = DDM([[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) + assert A.to_ddm() == B + + +def test_SDM_to_sdm(): + A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) + assert A.to_sdm() == A + + +def test_SDM_getitem(): + A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + assert A.getitem(0, 0) == ZZ.zero + assert A.getitem(0, 1) == ZZ.one + assert A.getitem(1, 0) == ZZ.zero + assert A.getitem(-2, -2) == ZZ.zero + assert A.getitem(-2, -1) == ZZ.one + assert A.getitem(-1, -2) == ZZ.zero + raises(IndexError, lambda: A.getitem(2, 0)) + raises(IndexError, lambda: A.getitem(0, 2)) + + +def test_SDM_setitem(): + A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + A.setitem(0, 0, ZZ(1)) + assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ) + A.setitem(1, 0, ZZ(1)) + assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) + A.setitem(1, 0, ZZ(0)) + assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ) + # Repeat the above test so that this time the row is empty + A.setitem(1, 0, ZZ(0)) + assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ) + A.setitem(0, 0, ZZ(0)) + assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + # This time the row is there but column is empty + A.setitem(0, 0, ZZ(0)) + assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + raises(IndexError, lambda: A.setitem(2, 0, ZZ(1))) + raises(IndexError, lambda: A.setitem(0, 2, ZZ(1))) + + +def test_SDM_extract_slice(): + A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) + B = A.extract_slice(slice(1, 2), slice(1, 2)) + assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ) + + +def test_SDM_extract(): + A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) + B = A.extract([1], [1]) + assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ) + B = A.extract([1, 0], [1, 0]) + assert B == SDM({0:{0:ZZ(4), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(1)}}, (2, 2), ZZ) + B = A.extract([1, 1], [1, 1]) + assert B == SDM({0:{0:ZZ(4), 1:ZZ(4)}, 1:{0:ZZ(4), 1:ZZ(4)}}, (2, 2), ZZ) + B = A.extract([-1], [-1]) + assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ) + + A = SDM({}, (2, 2), ZZ) + B = A.extract([0, 1, 0], [0, 0]) + assert B == SDM({}, (3, 2), ZZ) + + A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) + assert A.extract([], []) == SDM.zeros((0, 0), ZZ) + assert A.extract([1], []) == SDM.zeros((1, 0), ZZ) + assert A.extract([], [1]) == SDM.zeros((0, 1), ZZ) + + raises(IndexError, lambda: A.extract([2], [0])) + raises(IndexError, lambda: A.extract([0], [2])) + raises(IndexError, lambda: A.extract([-3], [0])) + raises(IndexError, lambda: A.extract([0], [-3])) + + +def test_SDM_zeros(): + A = SDM.zeros((2, 2), ZZ) + assert A.domain == ZZ + assert A.shape == (2, 2) + assert dict(A) == {} + +def test_SDM_ones(): + A = SDM.ones((1, 2), QQ) + assert A.domain == QQ + assert A.shape == (1, 2) + assert dict(A) == {0:{0:QQ(1), 1:QQ(1)}} + +def test_SDM_eye(): + A = SDM.eye((2, 2), ZZ) + assert A.domain == ZZ + assert A.shape == (2, 2) + assert dict(A) == {0:{0:ZZ(1)}, 1:{1:ZZ(1)}} + + +def test_SDM_diag(): + A = SDM.diag([ZZ(1), ZZ(2)], ZZ, (2, 3)) + assert A == SDM({0:{0:ZZ(1)}, 1:{1:ZZ(2)}}, (2, 3), ZZ) + + +def test_SDM_transpose(): + A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(1), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(4)}}, (2, 2), ZZ) + assert A.transpose() == B + + A = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ) + B = SDM({1:{0:ZZ(2)}}, (2, 2), ZZ) + assert A.transpose() == B + + A = SDM({0:{1:ZZ(2)}}, (1, 2), ZZ) + B = SDM({1:{0:ZZ(2)}}, (2, 1), ZZ) + assert A.transpose() == B + + +def test_SDM_mul(): + A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) + assert A*ZZ(2) == B + assert ZZ(2)*A == B + + raises(TypeError, lambda: A*QQ(1, 2)) + raises(TypeError, lambda: QQ(1, 2)*A) + + +def test_SDM_mul_elementwise(): + A = SDM({0:{0:ZZ(2), 1:ZZ(2)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(4)}, 1:{0:ZZ(3)}}, (2, 2), ZZ) + C = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ) + assert A.mul_elementwise(B) == C + assert B.mul_elementwise(A) == C + + Aq = A.convert_to(QQ) + A1 = SDM({0:{0:ZZ(1)}}, (1, 1), ZZ) + + raises(DMDomainError, lambda: Aq.mul_elementwise(B)) + raises(DMShapeError, lambda: A1.mul_elementwise(B)) + + +def test_SDM_matmul(): + A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) + assert A.matmul(A) == A*A == B + + C = SDM({0:{0:ZZ(2)}}, (2, 2), QQ) + raises(DMDomainError, lambda: A.matmul(C)) + + A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(7), 1:ZZ(10)}, 1:{0:ZZ(15), 1:ZZ(22)}}, (2, 2), ZZ) + assert A.matmul(A) == A*A == B + + A22 = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) + A32 = SDM({0:{0:ZZ(2)}}, (3, 2), ZZ) + A23 = SDM({0:{0:ZZ(4)}}, (2, 3), ZZ) + A33 = SDM({0:{0:ZZ(8)}}, (3, 3), ZZ) + A22 = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ) + assert A32.matmul(A23) == A33 + assert A23.matmul(A32) == A22 + # XXX: @ not supported by SDM... + #assert A32.matmul(A23) == A32 @ A23 == A33 + #assert A23.matmul(A32) == A23 @ A32 == A22 + #raises(DMShapeError, lambda: A23 @ A22) + raises(DMShapeError, lambda: A23.matmul(A22)) + + A = SDM({0: {0: ZZ(-1), 1: ZZ(1)}}, (1, 2), ZZ) + B = SDM({0: {0: ZZ(-1)}, 1: {0: ZZ(-1)}}, (2, 1), ZZ) + assert A.matmul(B) == A*B == SDM({}, (1, 1), ZZ) + + +def test_matmul_exraw(): + + def dm(d): + result = {} + for i, row in d.items(): + row = {j:val for j, val in row.items() if val} + if row: + result[i] = row + return SDM(result, (2, 2), EXRAW) + + values = [S.NegativeInfinity, S.NegativeOne, S.Zero, S.One, S.Infinity] + for a, b, c, d in product(*[values]*4): + Ad = dm({0: {0:a, 1:b}, 1: {0:c, 1:d}}) + Ad2 = dm({0: {0:a*a + b*c, 1:a*b + b*d}, 1:{0:c*a + d*c, 1: c*b + d*d}}) + assert Ad * Ad == Ad2 + + +def test_SDM_add(): + A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) + C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{1:ZZ(6)}}, (2, 2), ZZ) + assert A.add(B) == B.add(A) == A + B == B + A == C + + A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) + C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) + assert A.add(B) == B.add(A) == A + B == B + A == C + + raises(TypeError, lambda: A + []) + + +def test_SDM_sub(): + A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) + B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) + C = SDM({0:{0:ZZ(-1), 1:ZZ(1)}, 1:{0:ZZ(4)}}, (2, 2), ZZ) + assert A.sub(B) == A - B == C + + raises(TypeError, lambda: A - []) + + +def test_SDM_neg(): + A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) + B = SDM({0:{1:ZZ(-1)}, 1:{0:ZZ(-2), 1:ZZ(-3)}}, (2, 2), ZZ) + assert A.neg() == -A == B + + +def test_SDM_convert_to(): + A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) + B = SDM({0:{1:QQ(1)}, 1:{0:QQ(2), 1:QQ(3)}}, (2, 2), QQ) + C = A.convert_to(QQ) + assert C == B + assert C.domain == QQ + + D = A.convert_to(ZZ) + assert D == A + assert D.domain == ZZ + + +def test_SDM_hstack(): + A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ) + AA = SDM({0:{1:ZZ(1), 3:ZZ(1)}}, (2, 4), ZZ) + AB = SDM({0:{1:ZZ(1)}, 1:{3:ZZ(1)}}, (2, 4), ZZ) + assert SDM.hstack(A) == A + assert SDM.hstack(A, A) == AA + assert SDM.hstack(A, B) == AB + + +def test_SDM_vstack(): + A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ) + AA = SDM({0:{1:ZZ(1)}, 2:{1:ZZ(1)}}, (4, 2), ZZ) + AB = SDM({0:{1:ZZ(1)}, 3:{1:ZZ(1)}}, (4, 2), ZZ) + assert SDM.vstack(A) == A + assert SDM.vstack(A, A) == AA + assert SDM.vstack(A, B) == AB + + +def test_SDM_applyfunc(): + A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) + B = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ) + assert A.applyfunc(lambda x: 2*x, ZZ) == B + + +def test_SDM_inv(): + A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + B = SDM({0:{0:QQ(-2), 1:QQ(1)}, 1:{0:QQ(3, 2), 1:QQ(-1, 2)}}, (2, 2), QQ) + assert A.inv() == B + + +def test_SDM_det(): + A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + assert A.det() == QQ(-2) + + +def test_SDM_lu(): + A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + L = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(1)}}, (2, 2), QQ) + #U = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(-2)}}, (2, 2), QQ) + #swaps = [] + # This doesn't quite work. U has some nonzero elements in the lower part. + #assert A.lu() == (L, U, swaps) + assert A.lu()[0] == L + + +def test_SDM_lu_solve(): + A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ) + x = SDM({1:{0:QQ(1, 2)}}, (2, 1), QQ) + assert A.matmul(x) == b + assert A.lu_solve(b) == x + + +def test_SDM_charpoly(): + A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) + assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)] + + +def test_SDM_nullspace(): + # More tests are in test_nullspace.py + A = SDM({0:{0:QQ(1), 1:QQ(1)}}, (2, 2), QQ) + assert A.nullspace()[0] == SDM({0:{0:QQ(-1), 1:QQ(1)}}, (1, 2), QQ) + + +def test_SDM_rref(): + # More tests are in test_rref.py + + A = SDM({0:{0:QQ(1), 1:QQ(2)}, + 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) + A_rref = SDM({0:{0:QQ(1)}, 1:{1:QQ(1)}}, (2, 2), QQ) + assert A.rref() == (A_rref, [0, 1]) + + A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(2)}, + 1: {0: QQ(3), 2: QQ(4)}}, (2, 3), ZZ) + A_rref = SDM({0: {0: QQ(1,1), 2: QQ(4,3)}, + 1: {1: QQ(1,1), 2: QQ(1,3)}}, (2, 3), QQ) + assert A.rref() == (A_rref, [0, 1]) + + +def test_SDM_particular(): + A = SDM({0:{0:QQ(1)}}, (2, 2), QQ) + Apart = SDM.zeros((1, 2), QQ) + assert A.particular() == Apart + + +def test_SDM_is_zero_matrix(): + A = SDM({0: {0: QQ(1)}}, (2, 2), QQ) + Azero = SDM.zeros((1, 2), QQ) + assert A.is_zero_matrix() is False + assert Azero.is_zero_matrix() is True + + +def test_SDM_is_upper(): + A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, + 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, + 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ) + B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, + 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, + 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ) + assert A.is_upper() is True + assert B.is_upper() is False + + +def test_SDM_is_lower(): + A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, + 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, + 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ + ).transpose() + B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, + 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, + 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ + ).transpose() + assert A.is_lower() is True + assert B.is_lower() is False diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_xxm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_xxm.py new file mode 100644 index 0000000000000000000000000000000000000000..628d66d15f5db82718231ba8f89bc0dadd393594 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_xxm.py @@ -0,0 +1,1023 @@ +# +# Test basic features of DDM, SDM and DFM. +# +# These three types are supposed to be interchangeable, so we should use the +# same tests for all of them for the most part. +# +# The tests here cover the basic part of the interface that the three types +# should expose and that DomainMatrix should mostly rely on. +# +# More in-depth tests of the heavier algorithms like rref etc should go in +# their own test files. +# +# Any new methods added to the DDM, SDM or DFM classes should be tested here +# and added to all classes. +# + +from sympy.external.gmpy import GROUND_TYPES + +from sympy import ZZ, QQ, GF, ZZ_I, symbols + +from sympy.polys.matrices.exceptions import ( + DMBadInputError, + DMDomainError, + DMNonSquareMatrixError, + DMNonInvertibleMatrixError, + DMShapeError, +) + +from sympy.polys.matrices.domainmatrix import DM, DomainMatrix, DDM, SDM, DFM + +from sympy.testing.pytest import raises, skip +import pytest + + +def test_XXM_constructors(): + """Test the DDM, etc constructors.""" + + lol = [ + [ZZ(1), ZZ(2)], + [ZZ(3), ZZ(4)], + [ZZ(5), ZZ(6)], + ] + dod = { + 0: {0: ZZ(1), 1: ZZ(2)}, + 1: {0: ZZ(3), 1: ZZ(4)}, + 2: {0: ZZ(5), 1: ZZ(6)}, + } + + lol_0x0 = [] + lol_0x2 = [] + lol_2x0 = [[], []] + dod_0x0 = {} + dod_0x2 = {} + dod_2x0 = {} + + lol_bad = [ + [ZZ(1), ZZ(2)], + [ZZ(3), ZZ(4)], + [ZZ(5), ZZ(6), ZZ(7)], + ] + dod_bad = { + 0: {0: ZZ(1), 1: ZZ(2)}, + 1: {0: ZZ(3), 1: ZZ(4)}, + 2: {0: ZZ(5), 1: ZZ(6), 2: ZZ(7)}, + } + + XDM_dense = [DDM] + XDM_sparse = [SDM] + + if GROUND_TYPES == 'flint': + XDM_dense.append(DFM) + + for XDM in XDM_dense: + + A = XDM(lol, (3, 2), ZZ) + assert A.rows == 3 + assert A.cols == 2 + assert A.domain == ZZ + assert A.shape == (3, 2) + if XDM is not DFM: + assert ZZ.of_type(A[0][0]) is True + else: + assert ZZ.of_type(A.rep[0, 0]) is True + + Adm = DomainMatrix(lol, (3, 2), ZZ) + if XDM is DFM: + assert Adm.rep == A + assert Adm.rep.to_ddm() != A + elif GROUND_TYPES == 'flint': + assert Adm.rep.to_ddm() == A + assert Adm.rep != A + else: + assert Adm.rep == A + assert Adm.rep.to_ddm() == A + + assert XDM(lol_0x0, (0, 0), ZZ).shape == (0, 0) + assert XDM(lol_0x2, (0, 2), ZZ).shape == (0, 2) + assert XDM(lol_2x0, (2, 0), ZZ).shape == (2, 0) + raises(DMBadInputError, lambda: XDM(lol, (2, 3), ZZ)) + raises(DMBadInputError, lambda: XDM(lol_bad, (3, 2), ZZ)) + raises(DMBadInputError, lambda: XDM(dod, (3, 2), ZZ)) + + for XDM in XDM_sparse: + + A = XDM(dod, (3, 2), ZZ) + assert A.rows == 3 + assert A.cols == 2 + assert A.domain == ZZ + assert A.shape == (3, 2) + assert ZZ.of_type(A[0][0]) is True + + assert DomainMatrix(dod, (3, 2), ZZ).rep == A + + assert XDM(dod_0x0, (0, 0), ZZ).shape == (0, 0) + assert XDM(dod_0x2, (0, 2), ZZ).shape == (0, 2) + assert XDM(dod_2x0, (2, 0), ZZ).shape == (2, 0) + raises(DMBadInputError, lambda: XDM(dod, (2, 3), ZZ)) + raises(DMBadInputError, lambda: XDM(lol, (3, 2), ZZ)) + raises(DMBadInputError, lambda: XDM(dod_bad, (3, 2), ZZ)) + + raises(DMBadInputError, lambda: DomainMatrix(lol, (2, 3), ZZ)) + raises(DMBadInputError, lambda: DomainMatrix(lol_bad, (3, 2), ZZ)) + raises(DMBadInputError, lambda: DomainMatrix(dod_bad, (3, 2), ZZ)) + + +def test_XXM_eq(): + """Test equality for DDM, SDM, DFM and DomainMatrix.""" + + lol1 = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] + dod1 = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}} + + lol2 = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(5)]] + dod2 = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(5)}} + + A1_ddm = DDM(lol1, (2, 2), ZZ) + A1_sdm = SDM(dod1, (2, 2), ZZ) + A1_dm_d = DomainMatrix(lol1, (2, 2), ZZ) + A1_dm_s = DomainMatrix(dod1, (2, 2), ZZ) + + A2_ddm = DDM(lol2, (2, 2), ZZ) + A2_sdm = SDM(dod2, (2, 2), ZZ) + A2_dm_d = DomainMatrix(lol2, (2, 2), ZZ) + A2_dm_s = DomainMatrix(dod2, (2, 2), ZZ) + + A1_all = [A1_ddm, A1_sdm, A1_dm_d, A1_dm_s] + A2_all = [A2_ddm, A2_sdm, A2_dm_d, A2_dm_s] + + if GROUND_TYPES == 'flint': + + A1_dfm = DFM([[1, 2], [3, 4]], (2, 2), ZZ) + A2_dfm = DFM([[1, 2], [3, 5]], (2, 2), ZZ) + + A1_all.append(A1_dfm) + A2_all.append(A2_dfm) + + for n, An in enumerate(A1_all): + for m, Am in enumerate(A1_all): + if n == m: + assert (An == Am) is True + assert (An != Am) is False + else: + assert (An == Am) is False + assert (An != Am) is True + + for n, An in enumerate(A2_all): + for m, Am in enumerate(A2_all): + if n == m: + assert (An == Am) is True + assert (An != Am) is False + else: + assert (An == Am) is False + assert (An != Am) is True + + for n, A1 in enumerate(A1_all): + for m, A2 in enumerate(A2_all): + assert (A1 == A2) is False + assert (A1 != A2) is True + + +def test_to_XXM(): + """Test to_ddm etc. for DDM, SDM, DFM and DomainMatrix.""" + + lol = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] + dod = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}} + + A_ddm = DDM(lol, (2, 2), ZZ) + A_sdm = SDM(dod, (2, 2), ZZ) + A_dm_d = DomainMatrix(lol, (2, 2), ZZ) + A_dm_s = DomainMatrix(dod, (2, 2), ZZ) + + A_all = [A_ddm, A_sdm, A_dm_d, A_dm_s] + + if GROUND_TYPES == 'flint': + A_dfm = DFM(lol, (2, 2), ZZ) + A_all.append(A_dfm) + + for A in A_all: + assert A.to_ddm() == A_ddm + assert A.to_sdm() == A_sdm + if GROUND_TYPES != 'flint': + raises(NotImplementedError, lambda: A.to_dfm()) + assert A.to_dfm_or_ddm() == A_ddm + + # Add e.g. DDM.to_DM()? + # assert A.to_DM() == A_dm + + if GROUND_TYPES == 'flint': + for A in A_all: + assert A.to_dfm() == A_dfm + for K in [ZZ, QQ, GF(5), ZZ_I]: + if isinstance(A, DFM) and not DFM._supports_domain(K): + raises(NotImplementedError, lambda: A.convert_to(K)) + else: + A_K = A.convert_to(K) + if DFM._supports_domain(K): + A_dfm_K = A_dfm.convert_to(K) + assert A_K.to_dfm() == A_dfm_K + assert A_K.to_dfm_or_ddm() == A_dfm_K + else: + raises(NotImplementedError, lambda: A_K.to_dfm()) + assert A_K.to_dfm_or_ddm() == A_ddm.convert_to(K) + + +def test_DFM_domains(): + """Test which domains are supported by DFM.""" + + x, y = symbols('x, y') + + if GROUND_TYPES in ('python', 'gmpy'): + + supported = [] + flint_funcs = {} + not_supported = [ZZ, QQ, GF(5), QQ[x], QQ[x,y]] + + elif GROUND_TYPES == 'flint': + + import flint + supported = [ZZ, QQ] + flint_funcs = { + ZZ: flint.fmpz_mat, + QQ: flint.fmpq_mat, + GF(5): None, + } + not_supported = [ + # Other domains could be supported but not implemented as matrices + # in python-flint: + QQ[x], + QQ[x,y], + QQ.frac_field(x,y), + # Others would potentially never be supported by python-flint: + ZZ_I, + ] + + else: + assert False, "Unknown GROUND_TYPES: %s" % GROUND_TYPES + + for domain in supported: + assert DFM._supports_domain(domain) is True + if flint_funcs[domain] is not None: + assert DFM._get_flint_func(domain) == flint_funcs[domain] + for domain in not_supported: + assert DFM._supports_domain(domain) is False + raises(NotImplementedError, lambda: DFM._get_flint_func(domain)) + + +def _DM(lol, typ, K): + """Make a DM of type typ over K from lol.""" + A = DM(lol, K) + + if typ == 'DDM': + return A.to_ddm() + elif typ == 'SDM': + return A.to_sdm() + elif typ == 'DFM': + if GROUND_TYPES != 'flint': + skip("DFM not supported in this ground type") + return A.to_dfm() + else: + assert False, "Unknown type %s" % typ + + +def _DMZ(lol, typ): + """Make a DM of type typ over ZZ from lol.""" + return _DM(lol, typ, ZZ) + + +def _DMQ(lol, typ): + """Make a DM of type typ over QQ from lol.""" + return _DM(lol, typ, QQ) + + +def DM_ddm(lol, K): + """Make a DDM over K from lol.""" + return _DM(lol, 'DDM', K) + + +def DM_sdm(lol, K): + """Make a SDM over K from lol.""" + return _DM(lol, 'SDM', K) + + +def DM_dfm(lol, K): + """Make a DFM over K from lol.""" + return _DM(lol, 'DFM', K) + + +def DMZ_ddm(lol): + """Make a DDM from lol.""" + return _DMZ(lol, 'DDM') + + +def DMZ_sdm(lol): + """Make a SDM from lol.""" + return _DMZ(lol, 'SDM') + + +def DMZ_dfm(lol): + """Make a DFM from lol.""" + return _DMZ(lol, 'DFM') + + +def DMQ_ddm(lol): + """Make a DDM from lol.""" + return _DMQ(lol, 'DDM') + + +def DMQ_sdm(lol): + """Make a SDM from lol.""" + return _DMQ(lol, 'SDM') + + +def DMQ_dfm(lol): + """Make a DFM from lol.""" + return _DMQ(lol, 'DFM') + + +DM_all = [DM_ddm, DM_sdm, DM_dfm] +DMZ_all = [DMZ_ddm, DMZ_sdm, DMZ_dfm] +DMQ_all = [DMQ_ddm, DMQ_sdm, DMQ_dfm] + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XDM_getitem(DM): + """Test getitem for DDM, etc.""" + + lol = [[0, 1], [2, 0]] + A = DM(lol) + m, n = A.shape + + indices = [-3, -2, -1, 0, 1, 2] + + for i in indices: + for j in indices: + if -2 <= i < m and -2 <= j < n: + assert A.getitem(i, j) == ZZ(lol[i][j]) + else: + raises(IndexError, lambda: A.getitem(i, j)) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XDM_setitem(DM): + """Test setitem for DDM, etc.""" + + A = DM([[0, 1, 2], [3, 4, 5]]) + + A.setitem(0, 0, ZZ(6)) + assert A == DM([[6, 1, 2], [3, 4, 5]]) + + A.setitem(0, 1, ZZ(7)) + assert A == DM([[6, 7, 2], [3, 4, 5]]) + + A.setitem(0, 2, ZZ(8)) + assert A == DM([[6, 7, 8], [3, 4, 5]]) + + A.setitem(0, -1, ZZ(9)) + assert A == DM([[6, 7, 9], [3, 4, 5]]) + + A.setitem(0, -2, ZZ(10)) + assert A == DM([[6, 10, 9], [3, 4, 5]]) + + A.setitem(0, -3, ZZ(11)) + assert A == DM([[11, 10, 9], [3, 4, 5]]) + + raises(IndexError, lambda: A.setitem(0, 3, ZZ(12))) + raises(IndexError, lambda: A.setitem(0, -4, ZZ(13))) + + A.setitem(1, 0, ZZ(14)) + assert A == DM([[11, 10, 9], [14, 4, 5]]) + + A.setitem(1, 1, ZZ(15)) + assert A == DM([[11, 10, 9], [14, 15, 5]]) + + A.setitem(-1, 1, ZZ(16)) + assert A == DM([[11, 10, 9], [14, 16, 5]]) + + A.setitem(-2, 1, ZZ(17)) + assert A == DM([[11, 17, 9], [14, 16, 5]]) + + raises(IndexError, lambda: A.setitem(2, 0, ZZ(18))) + raises(IndexError, lambda: A.setitem(-3, 0, ZZ(19))) + + A.setitem(1, 2, ZZ(0)) + assert A == DM([[11, 17, 9], [14, 16, 0]]) + + A.setitem(1, -2, ZZ(0)) + assert A == DM([[11, 17, 9], [14, 0, 0]]) + + A.setitem(1, -3, ZZ(0)) + assert A == DM([[11, 17, 9], [0, 0, 0]]) + + A.setitem(0, 0, ZZ(0)) + assert A == DM([[0, 17, 9], [0, 0, 0]]) + + A.setitem(0, -1, ZZ(0)) + assert A == DM([[0, 17, 0], [0, 0, 0]]) + + A.setitem(0, 0, ZZ(0)) + assert A == DM([[0, 17, 0], [0, 0, 0]]) + + A.setitem(0, -2, ZZ(0)) + assert A == DM([[0, 0, 0], [0, 0, 0]]) + + A.setitem(0, -3, ZZ(1)) + assert A == DM([[1, 0, 0], [0, 0, 0]]) + + +class _Sliced: + def __getitem__(self, item): + return item + + +_slice = _Sliced() + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_extract_slice(DM): + A = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + assert A.extract_slice(*_slice[:,:]) == A + assert A.extract_slice(*_slice[1:,:]) == DM([[4, 5, 6], [7, 8, 9]]) + assert A.extract_slice(*_slice[1:,1:]) == DM([[5, 6], [8, 9]]) + assert A.extract_slice(*_slice[1:,:-1]) == DM([[4, 5], [7, 8]]) + assert A.extract_slice(*_slice[1:,:-1:2]) == DM([[4], [7]]) + assert A.extract_slice(*_slice[:,::2]) == DM([[1, 3], [4, 6], [7, 9]]) + assert A.extract_slice(*_slice[::2,:]) == DM([[1, 2, 3], [7, 8, 9]]) + assert A.extract_slice(*_slice[::2,::2]) == DM([[1, 3], [7, 9]]) + assert A.extract_slice(*_slice[::2,::-2]) == DM([[3, 1], [9, 7]]) + assert A.extract_slice(*_slice[::-2,::2]) == DM([[7, 9], [1, 3]]) + assert A.extract_slice(*_slice[::-2,::-2]) == DM([[9, 7], [3, 1]]) + assert A.extract_slice(*_slice[:,::-1]) == DM([[3, 2, 1], [6, 5, 4], [9, 8, 7]]) + assert A.extract_slice(*_slice[::-1,:]) == DM([[7, 8, 9], [4, 5, 6], [1, 2, 3]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_extract(DM): + + A = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + + assert A.extract([0, 1, 2], [0, 1, 2]) == A + assert A.extract([1, 2], [1, 2]) == DM([[5, 6], [8, 9]]) + assert A.extract([1, 2], [0, 1]) == DM([[4, 5], [7, 8]]) + assert A.extract([1, 2], [0, 2]) == DM([[4, 6], [7, 9]]) + assert A.extract([1, 2], [0]) == DM([[4], [7]]) + assert A.extract([1, 2], []) == DM([[1]]).zeros((2, 0), ZZ) + assert A.extract([], [0, 1, 2]) == DM([[1]]).zeros((0, 3), ZZ) + + raises(IndexError, lambda: A.extract([1, 2], [0, 3])) + raises(IndexError, lambda: A.extract([1, 2], [0, -4])) + raises(IndexError, lambda: A.extract([3, 1], [0, 1])) + raises(IndexError, lambda: A.extract([-4, 2], [3, 1])) + + B = DM([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) + assert B.extract([1, 2], [1, 2]) == DM([[0, 0], [0, 0]]) + + +def test_XXM_str(): + + A = DomainMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ) + + assert str(A) == \ + 'DomainMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)' + assert str(A.to_ddm()) == \ + '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]' + assert str(A.to_sdm()) == \ + '{0: {0: 1, 1: 2, 2: 3}, 1: {0: 4, 1: 5, 2: 6}, 2: {0: 7, 1: 8, 2: 9}}' + + assert repr(A) == \ + 'DomainMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)' + assert repr(A.to_ddm()) == \ + 'DDM([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)' + assert repr(A.to_sdm()) == \ + 'SDM({0: {0: 1, 1: 2, 2: 3}, 1: {0: 4, 1: 5, 2: 6}, 2: {0: 7, 1: 8, 2: 9}}, (3, 3), ZZ)' + + B = DomainMatrix({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3)}}, (2, 2), ZZ) + + assert str(B) == \ + 'DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3}}, (2, 2), ZZ)' + assert str(B.to_ddm()) == \ + '[[1, 2], [3, 0]]' + assert str(B.to_sdm()) == \ + '{0: {0: 1, 1: 2}, 1: {0: 3}}' + + assert repr(B) == \ + 'DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3}}, (2, 2), ZZ)' + + if GROUND_TYPES != 'gmpy': + assert repr(B.to_ddm()) == \ + 'DDM([[1, 2], [3, 0]], (2, 2), ZZ)' + assert repr(B.to_sdm()) == \ + 'SDM({0: {0: 1, 1: 2}, 1: {0: 3}}, (2, 2), ZZ)' + else: + assert repr(B.to_ddm()) == \ + 'DDM([[mpz(1), mpz(2)], [mpz(3), mpz(0)]], (2, 2), ZZ)' + assert repr(B.to_sdm()) == \ + 'SDM({0: {0: mpz(1), 1: mpz(2)}, 1: {0: mpz(3)}}, (2, 2), ZZ)' + + if GROUND_TYPES == 'flint': + + assert str(A.to_dfm()) == \ + '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]' + assert str(B.to_dfm()) == \ + '[[1, 2], [3, 0]]' + + assert repr(A.to_dfm()) == \ + 'DFM([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)' + assert repr(B.to_dfm()) == \ + 'DFM([[1, 2], [3, 0]], (2, 2), ZZ)' + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_from_list(DM): + T = type(DM([[0]])) + + lol = [[1, 2, 4], [4, 5, 6]] + lol_ZZ = [[ZZ(1), ZZ(2), ZZ(4)], [ZZ(4), ZZ(5), ZZ(6)]] + lol_ZZ_bad = [[ZZ(1), ZZ(2), ZZ(4)], [ZZ(4), ZZ(5), ZZ(6), ZZ(7)]] + + assert T.from_list(lol_ZZ, (2, 3), ZZ) == DM(lol) + raises(DMBadInputError, lambda: T.from_list(lol_ZZ_bad, (3, 2), ZZ)) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_to_list(DM): + lol = [[1, 2, 4], [4, 5, 6]] + assert DM(lol).to_list() == [[ZZ(1), ZZ(2), ZZ(4)], [ZZ(4), ZZ(5), ZZ(6)]] + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_to_list_flat(DM): + lol = [[1, 2, 4], [4, 5, 6]] + assert DM(lol).to_list_flat() == [ZZ(1), ZZ(2), ZZ(4), ZZ(4), ZZ(5), ZZ(6)] + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_from_list_flat(DM): + T = type(DM([[0]])) + flat = [ZZ(1), ZZ(2), ZZ(4), ZZ(4), ZZ(5), ZZ(6)] + assert T.from_list_flat(flat, (2, 3), ZZ) == DM([[1, 2, 4], [4, 5, 6]]) + raises(DMBadInputError, lambda: T.from_list_flat(flat, (3, 3), ZZ)) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_to_flat_nz(DM): + M = DM([[1, 2, 0], [0, 0, 0], [0, 0, 3]]) + elements = [ZZ(1), ZZ(2), ZZ(3)] + indices = ((0, 0), (0, 1), (2, 2)) + assert M.to_flat_nz() == (elements, (indices, M.shape)) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_from_flat_nz(DM): + T = type(DM([[0]])) + elements = [ZZ(1), ZZ(2), ZZ(3)] + indices = ((0, 0), (0, 1), (2, 2)) + data = (indices, (3, 3)) + result = DM([[1, 2, 0], [0, 0, 0], [0, 0, 3]]) + assert T.from_flat_nz(elements, data, ZZ) == result + raises(DMBadInputError, lambda: T.from_flat_nz(elements, (indices, (2, 3)), ZZ)) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_to_dod(DM): + dod = {0: {0: ZZ(1), 2: ZZ(4)}, 1: {0: ZZ(4), 1: ZZ(5), 2: ZZ(6)}} + assert DM([[1, 0, 4], [4, 5, 6]]).to_dod() == dod + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_from_dod(DM): + T = type(DM([[0]])) + dod = {0: {0: ZZ(1), 2: ZZ(4)}, 1: {0: ZZ(4), 1: ZZ(5), 2: ZZ(6)}} + assert T.from_dod(dod, (2, 3), ZZ) == DM([[1, 0, 4], [4, 5, 6]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_to_dok(DM): + dod = {(0, 0): ZZ(1), (0, 2): ZZ(4), + (1, 0): ZZ(4), (1, 1): ZZ(5), (1, 2): ZZ(6)} + assert DM([[1, 0, 4], [4, 5, 6]]).to_dok() == dod + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_from_dok(DM): + T = type(DM([[0]])) + dod = {(0, 0): ZZ(1), (0, 2): ZZ(4), + (1, 0): ZZ(4), (1, 1): ZZ(5), (1, 2): ZZ(6)} + assert T.from_dok(dod, (2, 3), ZZ) == DM([[1, 0, 4], [4, 5, 6]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_iter_values(DM): + values = [ZZ(1), ZZ(4), ZZ(4), ZZ(5), ZZ(6)] + assert sorted(DM([[1, 0, 4], [4, 5, 6]]).iter_values()) == values + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_iter_items(DM): + items = [((0, 0), ZZ(1)), ((0, 2), ZZ(4)), + ((1, 0), ZZ(4)), ((1, 1), ZZ(5)), ((1, 2), ZZ(6))] + assert sorted(DM([[1, 0, 4], [4, 5, 6]]).iter_items()) == items + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_from_ddm(DM): + T = type(DM([[0]])) + ddm = DDM([[1, 2, 4], [4, 5, 6]], (2, 3), ZZ) + assert T.from_ddm(ddm) == DM([[1, 2, 4], [4, 5, 6]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_zeros(DM): + T = type(DM([[0]])) + assert T.zeros((2, 3), ZZ) == DM([[0, 0, 0], [0, 0, 0]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_ones(DM): + T = type(DM([[0]])) + assert T.ones((2, 3), ZZ) == DM([[1, 1, 1], [1, 1, 1]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_eye(DM): + T = type(DM([[0]])) + assert T.eye(3, ZZ) == DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + assert T.eye((3, 2), ZZ) == DM([[1, 0], [0, 1], [0, 0]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_diag(DM): + T = type(DM([[0]])) + assert T.diag([1, 2, 3], ZZ) == DM([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_transpose(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + assert A.transpose() == DM([[1, 4], [2, 5], [3, 6]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_add(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + B = DM([[1, 2, 3], [4, 5, 6]]) + C = DM([[2, 4, 6], [8, 10, 12]]) + assert A.add(B) == C + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_sub(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + B = DM([[1, 2, 3], [4, 5, 6]]) + C = DM([[0, 0, 0], [0, 0, 0]]) + assert A.sub(B) == C + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_mul(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + b = ZZ(2) + assert A.mul(b) == DM([[2, 4, 6], [8, 10, 12]]) + assert A.rmul(b) == DM([[2, 4, 6], [8, 10, 12]]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_matmul(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + B = DM([[1, 2], [3, 4], [5, 6]]) + C = DM([[22, 28], [49, 64]]) + assert A.matmul(B) == C + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_mul_elementwise(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + B = DM([[1, 2, 3], [4, 5, 6]]) + C = DM([[1, 4, 9], [16, 25, 36]]) + assert A.mul_elementwise(B) == C + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_neg(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + C = DM([[-1, -2, -3], [-4, -5, -6]]) + assert A.neg() == C + + +@pytest.mark.parametrize('DM', DM_all) +def test_XXM_convert_to(DM): + A = DM([[1, 2, 3], [4, 5, 6]], ZZ) + B = DM([[1, 2, 3], [4, 5, 6]], QQ) + assert A.convert_to(QQ) == B + assert B.convert_to(ZZ) == A + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_scc(DM): + A = DM([ + [0, 1, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 1], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 1, 0, 1]]) + assert A.scc() == [[0, 1], [2], [3, 5], [4]] + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_hstack(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + B = DM([[7, 8], [9, 10]]) + C = DM([[1, 2, 3, 7, 8], [4, 5, 6, 9, 10]]) + ABC = DM([[1, 2, 3, 7, 8, 1, 2, 3, 7, 8], + [4, 5, 6, 9, 10, 4, 5, 6, 9, 10]]) + assert A.hstack(B) == C + assert A.hstack(B, C) == ABC + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_vstack(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + B = DM([[7, 8, 9]]) + C = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + ABC = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]]) + assert A.vstack(B) == C + assert A.vstack(B, C) == ABC + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_applyfunc(DM): + A = DM([[1, 2, 3], [4, 5, 6]]) + B = DM([[2, 4, 6], [8, 10, 12]]) + assert A.applyfunc(lambda x: 2*x, ZZ) == B + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_is_upper(DM): + assert DM([[1, 2, 3], [0, 5, 6]]).is_upper() is True + assert DM([[1, 2, 3], [4, 5, 6]]).is_upper() is False + assert DM([]).is_upper() is True + assert DM([[], []]).is_upper() is True + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_is_lower(DM): + assert DM([[1, 0, 0], [4, 5, 0]]).is_lower() is True + assert DM([[1, 2, 3], [4, 5, 6]]).is_lower() is False + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_is_diagonal(DM): + assert DM([[1, 0, 0], [0, 5, 0]]).is_diagonal() is True + assert DM([[1, 2, 3], [4, 5, 6]]).is_diagonal() is False + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_diagonal(DM): + assert DM([[1, 0, 0], [0, 5, 0]]).diagonal() == [1, 5] + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_is_zero_matrix(DM): + assert DM([[0, 0, 0], [0, 0, 0]]).is_zero_matrix() is True + assert DM([[1, 0, 0], [0, 0, 0]]).is_zero_matrix() is False + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_det_ZZ(DM): + assert DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).det() == 0 + assert DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]]).det() == -3 + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_det_QQ(DM): + dM1 = DM([[(1,2), (2,3)], [(3,4), (4,5)]]) + assert dM1.det() == QQ(-1,10) + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_inv_QQ(DM): + dM1 = DM([[(1,2), (2,3)], [(3,4), (4,5)]]) + dM2 = DM([[(-8,1), (20,3)], [(15,2), (-5,1)]]) + assert dM1.inv() == dM2 + assert dM1.matmul(dM2) == DM([[1, 0], [0, 1]]) + + dM3 = DM([[(1,2), (2,3)], [(1,4), (1,3)]]) + raises(DMNonInvertibleMatrixError, lambda: dM3.inv()) + + dM4 = DM([[(1,2), (2,3), (3,4)], [(1,4), (1,3), (1,2)]]) + raises(DMNonSquareMatrixError, lambda: dM4.inv()) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_inv_ZZ(DM): + dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) + # XXX: Maybe this should return a DM over QQ instead? + # XXX: Handle unimodular matrices? + raises(DMDomainError, lambda: dM1.inv()) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_charpoly_ZZ(DM): + dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) + assert dM1.charpoly() == [1, -16, -12, 3] + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_charpoly_QQ(DM): + dM1 = DM([[(1,2), (2,3)], [(3,4), (4,5)]]) + assert dM1.charpoly() == [QQ(1,1), QQ(-13,10), QQ(-1,10)] + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_lu_solve_ZZ(DM): + dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) + dM2 = DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + raises(DMDomainError, lambda: dM1.lu_solve(dM2)) + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_lu_solve_QQ(DM): + dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) + dM2 = DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + dM3 = DM([[(-2,3),(-4,3),(1,1)],[(-2,3),(11,3),(-2,1)],[(1,1),(-2,1),(1,1)]]) + assert dM1.lu_solve(dM2) == dM3 == dM1.inv() + + dM4 = DM([[1, 2, 3], [4, 5, 6]]) + dM5 = DM([[1, 0], [0, 1], [0, 0]]) + raises(DMShapeError, lambda: dM4.lu_solve(dM5)) + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_nullspace_QQ(DM): + dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + # XXX: Change the signature to just return the nullspace. Possibly + # returning the rank or nullity makes sense but the list of nonpivots is + # not useful. + assert dM1.nullspace() == (DM([[1, -2, 1]]), [2]) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_lll(DM): + M = DM([[1, 2, 3], [4, 5, 20]]) + M_lll = DM([[1, 2, 3], [-1, -5, 5]]) + T = DM([[1, 0], [-5, 1]]) + assert M.lll() == M_lll + assert M.lll_transform() == (M_lll, T) + assert T.matmul(M) == M_lll + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_mixed_signs(DM): + lol = [[QQ(1), QQ(-2)], [QQ(-3), QQ(4)]] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_large_matrix(DM): + lol = [[QQ(i + j) for j in range(10)] for i in range(10)] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_identity_matrix(DM): + T = type(DM([[0]])) + A = T.eye(3, QQ) + Q, R = A.qr() + assert Q == A + assert R == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + assert Q.shape == (3, 3) + assert R.shape == (3, 3) + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_square_matrix(DM): + lol = [[QQ(3), QQ(1)], [QQ(4), QQ(3)]] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_matrix_with_zero_columns(DM): + lol = [[QQ(3), QQ(0)], [QQ(4), QQ(0)]] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_linearly_dependent_columns(DM): + lol = [[QQ(1), QQ(2)], [QQ(2), QQ(4)]] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_qr_non_field(DM): + lol = [[ZZ(3), ZZ(1)], [ZZ(4), ZZ(3)]] + A = DM(lol) + with pytest.raises(DMDomainError): + A.qr() + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_field(DM): + lol = [[QQ(3), QQ(1)], [QQ(4), QQ(3)]] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_tall_matrix(DM): + lol = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_wide_matrix(DM): + lol = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]] + A = DM(lol) + Q, R = A.qr() + assert Q.matmul(R) == A + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_empty_matrix_0x0(DM): + T = type(DM([[0]])) + A = T.zeros((0, 0), QQ) + Q, R = A.qr() + assert Q.matmul(R).shape == A.shape + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + assert Q.shape == (0, 0) + assert R.shape == (0, 0) + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_empty_matrix_2x0(DM): + T = type(DM([[0]])) + A = T.zeros((2, 0), QQ) + Q, R = A.qr() + assert Q.matmul(R).shape == A.shape + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + assert Q.shape == (2, 0) + assert R.shape == (0, 0) + + +@pytest.mark.parametrize('DM', DMQ_all) +def test_XXM_qr_empty_matrix_0x2(DM): + T = type(DM([[0]])) + A = T.zeros((0, 2), QQ) + Q, R = A.qr() + assert Q.matmul(R).shape == A.shape + assert (Q.transpose().matmul(Q)).is_diagonal + assert R.is_upper + assert Q.shape == (0, 0) + assert R.shape == (0, 2) + + +@pytest.mark.parametrize('DM', DMZ_all) +def test_XXM_fflu(DM): + A = DM([[1, 2], [3, 4]]) + P, L, D, U = A.fflu() + A_field = A.convert_to(QQ) + P_field = P.convert_to(QQ) + L_field = L.convert_to(QQ) + D_field = D.convert_to(QQ) + U_field = U.convert_to(QQ) + assert P.shape == A.shape + assert L.shape == A.shape + assert D.shape == A.shape + assert U.shape == A.shape + assert P == DM([[1, 0], [0, 1]]) + assert L == DM([[1, 0], [3, -2]]) + assert D == DM([[1, 0], [0, -2]]) + assert U == DM([[1, 2], [0, -2]]) + assert L_field.matmul(D_field.inv()).matmul(U_field) == P_field.matmul(A_field) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/modulargcd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/modulargcd.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0012316c499cfde85f56c5c37a3475f4175a4e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/modulargcd.py @@ -0,0 +1,2278 @@ +from sympy.core.symbol import Dummy +from sympy.ntheory import nextprime +from sympy.ntheory.modular import crt +from sympy.polys.domains import PolynomialRing +from sympy.polys.galoistools import ( + gf_gcd, gf_from_dict, gf_gcdex, gf_div, gf_lcm) +from sympy.polys.polyerrors import ModularGCDFailed + +from mpmath import sqrt +import random + + +def _trivial_gcd(f, g): + """ + Compute the GCD of two polynomials in trivial cases, i.e. when one + or both polynomials are zero. + """ + ring = f.ring + + if not (f or g): + return ring.zero, ring.zero, ring.zero + elif not f: + if g.LC < ring.domain.zero: + return -g, ring.zero, -ring.one + else: + return g, ring.zero, ring.one + elif not g: + if f.LC < ring.domain.zero: + return -f, -ring.one, ring.zero + else: + return f, ring.one, ring.zero + return None + + +def _gf_gcd(fp, gp, p): + r""" + Compute the GCD of two univariate polynomials in `\mathbb{Z}_p[x]`. + """ + dom = fp.ring.domain + + while gp: + rem = fp + deg = gp.degree() + lcinv = dom.invert(gp.LC, p) + + while True: + degrem = rem.degree() + if degrem < deg: + break + rem = (rem - gp.mul_monom((degrem - deg,)).mul_ground(lcinv * rem.LC)).trunc_ground(p) + + fp = gp + gp = rem + + return fp.mul_ground(dom.invert(fp.LC, p)).trunc_ground(p) + + +def _degree_bound_univariate(f, g): + r""" + Compute an upper bound for the degree of the GCD of two univariate + integer polynomials `f` and `g`. + + The function chooses a suitable prime `p` and computes the GCD of + `f` and `g` in `\mathbb{Z}_p[x]`. The choice of `p` guarantees that + the degree in `\mathbb{Z}_p[x]` is greater than or equal to the degree + in `\mathbb{Z}[x]`. + + Parameters + ========== + + f : PolyElement + univariate integer polynomial + g : PolyElement + univariate integer polynomial + + """ + gamma = f.ring.domain.gcd(f.LC, g.LC) + p = 1 + + p = nextprime(p) + while gamma % p == 0: + p = nextprime(p) + + fp = f.trunc_ground(p) + gp = g.trunc_ground(p) + hp = _gf_gcd(fp, gp, p) + deghp = hp.degree() + return deghp + + +def _chinese_remainder_reconstruction_univariate(hp, hq, p, q): + r""" + Construct a polynomial `h_{pq}` in `\mathbb{Z}_{p q}[x]` such that + + .. math :: + + h_{pq} = h_p \; \mathrm{mod} \, p + + h_{pq} = h_q \; \mathrm{mod} \, q + + for relatively prime integers `p` and `q` and polynomials + `h_p` and `h_q` in `\mathbb{Z}_p[x]` and `\mathbb{Z}_q[x]` + respectively. + + The coefficients of the polynomial `h_{pq}` are computed with the + Chinese Remainder Theorem. The symmetric representation in + `\mathbb{Z}_p[x]`, `\mathbb{Z}_q[x]` and `\mathbb{Z}_{p q}[x]` is used. + It is assumed that `h_p` and `h_q` have the same degree. + + Parameters + ========== + + hp : PolyElement + univariate integer polynomial with coefficients in `\mathbb{Z}_p` + hq : PolyElement + univariate integer polynomial with coefficients in `\mathbb{Z}_q` + p : Integer + modulus of `h_p`, relatively prime to `q` + q : Integer + modulus of `h_q`, relatively prime to `p` + + Examples + ======== + + >>> from sympy.polys.modulargcd import _chinese_remainder_reconstruction_univariate + >>> from sympy.polys import ring, ZZ + + >>> R, x = ring("x", ZZ) + >>> p = 3 + >>> q = 5 + + >>> hp = -x**3 - 1 + >>> hq = 2*x**3 - 2*x**2 + x + + >>> hpq = _chinese_remainder_reconstruction_univariate(hp, hq, p, q) + >>> hpq + 2*x**3 + 3*x**2 + 6*x + 5 + + >>> hpq.trunc_ground(p) == hp + True + >>> hpq.trunc_ground(q) == hq + True + + """ + n = hp.degree() + x = hp.ring.gens[0] + hpq = hp.ring.zero + + for i in range(n+1): + hpq[(i,)] = crt([p, q], [hp.coeff(x**i), hq.coeff(x**i)], symmetric=True)[0] + + hpq.strip_zero() + return hpq + + +def modgcd_univariate(f, g): + r""" + Computes the GCD of two polynomials in `\mathbb{Z}[x]` using a modular + algorithm. + + The algorithm computes the GCD of two univariate integer polynomials + `f` and `g` by computing the GCD in `\mathbb{Z}_p[x]` for suitable + primes `p` and then reconstructing the coefficients with the Chinese + Remainder Theorem. Trial division is only made for candidates which + are very likely the desired GCD. + + Parameters + ========== + + f : PolyElement + univariate integer polynomial + g : PolyElement + univariate integer polynomial + + Returns + ======= + + h : PolyElement + GCD of the polynomials `f` and `g` + cff : PolyElement + cofactor of `f`, i.e. `\frac{f}{h}` + cfg : PolyElement + cofactor of `g`, i.e. `\frac{g}{h}` + + Examples + ======== + + >>> from sympy.polys.modulargcd import modgcd_univariate + >>> from sympy.polys import ring, ZZ + + >>> R, x = ring("x", ZZ) + + >>> f = x**5 - 1 + >>> g = x - 1 + + >>> h, cff, cfg = modgcd_univariate(f, g) + >>> h, cff, cfg + (x - 1, x**4 + x**3 + x**2 + x + 1, 1) + + >>> cff * h == f + True + >>> cfg * h == g + True + + >>> f = 6*x**2 - 6 + >>> g = 2*x**2 + 4*x + 2 + + >>> h, cff, cfg = modgcd_univariate(f, g) + >>> h, cff, cfg + (2*x + 2, 3*x - 3, x + 1) + + >>> cff * h == f + True + >>> cfg * h == g + True + + References + ========== + + 1. [Monagan00]_ + + """ + assert f.ring == g.ring and f.ring.domain.is_ZZ + + result = _trivial_gcd(f, g) + if result is not None: + return result + + ring = f.ring + + cf, f = f.primitive() + cg, g = g.primitive() + ch = ring.domain.gcd(cf, cg) + + bound = _degree_bound_univariate(f, g) + if bound == 0: + return ring(ch), f.mul_ground(cf // ch), g.mul_ground(cg // ch) + + gamma = ring.domain.gcd(f.LC, g.LC) + m = 1 + p = 1 + + while True: + p = nextprime(p) + while gamma % p == 0: + p = nextprime(p) + + fp = f.trunc_ground(p) + gp = g.trunc_ground(p) + hp = _gf_gcd(fp, gp, p) + deghp = hp.degree() + + if deghp > bound: + continue + elif deghp < bound: + m = 1 + bound = deghp + continue + + hp = hp.mul_ground(gamma).trunc_ground(p) + if m == 1: + m = p + hlastm = hp + continue + + hm = _chinese_remainder_reconstruction_univariate(hp, hlastm, p, m) + m *= p + + if not hm == hlastm: + hlastm = hm + continue + + h = hm.quo_ground(hm.content()) + fquo, frem = f.div(h) + gquo, grem = g.div(h) + if not frem and not grem: + if h.LC < 0: + ch = -ch + h = h.mul_ground(ch) + cff = fquo.mul_ground(cf // ch) + cfg = gquo.mul_ground(cg // ch) + return h, cff, cfg + + +def _primitive(f, p): + r""" + Compute the content and the primitive part of a polynomial in + `\mathbb{Z}_p[x_0, \ldots, x_{k-2}, y] \cong \mathbb{Z}_p[y][x_0, \ldots, x_{k-2}]`. + + Parameters + ========== + + f : PolyElement + integer polynomial in `\mathbb{Z}_p[x0, \ldots, x{k-2}, y]` + p : Integer + modulus of `f` + + Returns + ======= + + contf : PolyElement + integer polynomial in `\mathbb{Z}_p[y]`, content of `f` + ppf : PolyElement + primitive part of `f`, i.e. `\frac{f}{contf}` + + Examples + ======== + + >>> from sympy.polys.modulargcd import _primitive + >>> from sympy.polys import ring, ZZ + + >>> R, x, y = ring("x, y", ZZ) + >>> p = 3 + + >>> f = x**2*y**2 + x**2*y - y**2 - y + >>> _primitive(f, p) + (y**2 + y, x**2 - 1) + + >>> R, x, y, z = ring("x, y, z", ZZ) + + >>> f = x*y*z - y**2*z**2 + >>> _primitive(f, p) + (z, x*y - y**2*z) + + """ + ring = f.ring + dom = ring.domain + k = ring.ngens + + coeffs = {} + for monom, coeff in f.iterterms(): + if monom[:-1] not in coeffs: + coeffs[monom[:-1]] = {} + coeffs[monom[:-1]][monom[-1]] = coeff + + cont = [] + for coeff in iter(coeffs.values()): + cont = gf_gcd(cont, gf_from_dict(coeff, p, dom), p, dom) + + yring = ring.clone(symbols=ring.symbols[k-1]) + contf = yring.from_dense(cont).trunc_ground(p) + + return contf, f.quo(contf.set_ring(ring)) + + +def _deg(f): + r""" + Compute the degree of a multivariate polynomial + `f \in K[x_0, \ldots, x_{k-2}, y] \cong K[y][x_0, \ldots, x_{k-2}]`. + + Parameters + ========== + + f : PolyElement + polynomial in `K[x_0, \ldots, x_{k-2}, y]` + + Returns + ======= + + degf : Integer tuple + degree of `f` in `x_0, \ldots, x_{k-2}` + + Examples + ======== + + >>> from sympy.polys.modulargcd import _deg + >>> from sympy.polys import ring, ZZ + + >>> R, x, y = ring("x, y", ZZ) + + >>> f = x**2*y**2 + x**2*y - 1 + >>> _deg(f) + (2,) + + >>> R, x, y, z = ring("x, y, z", ZZ) + + >>> f = x**2*y**2 + x**2*y - 1 + >>> _deg(f) + (2, 2) + + >>> f = x*y*z - y**2*z**2 + >>> _deg(f) + (1, 1) + + """ + k = f.ring.ngens + degf = (0,) * (k-1) + for monom in f.itermonoms(): + if monom[:-1] > degf: + degf = monom[:-1] + return degf + + +def _LC(f): + r""" + Compute the leading coefficient of a multivariate polynomial + `f \in K[x_0, \ldots, x_{k-2}, y] \cong K[y][x_0, \ldots, x_{k-2}]`. + + Parameters + ========== + + f : PolyElement + polynomial in `K[x_0, \ldots, x_{k-2}, y]` + + Returns + ======= + + lcf : PolyElement + polynomial in `K[y]`, leading coefficient of `f` + + Examples + ======== + + >>> from sympy.polys.modulargcd import _LC + >>> from sympy.polys import ring, ZZ + + >>> R, x, y = ring("x, y", ZZ) + + >>> f = x**2*y**2 + x**2*y - 1 + >>> _LC(f) + y**2 + y + + >>> R, x, y, z = ring("x, y, z", ZZ) + + >>> f = x**2*y**2 + x**2*y - 1 + >>> _LC(f) + 1 + + >>> f = x*y*z - y**2*z**2 + >>> _LC(f) + z + + """ + ring = f.ring + k = ring.ngens + yring = ring.clone(symbols=ring.symbols[k-1]) + y = yring.gens[0] + degf = _deg(f) + + lcf = yring.zero + for monom, coeff in f.iterterms(): + if monom[:-1] == degf: + lcf += coeff*y**monom[-1] + return lcf + + +def _swap(f, i): + """ + Make the variable `x_i` the leading one in a multivariate polynomial `f`. + """ + ring = f.ring + fswap = ring.zero + for monom, coeff in f.iterterms(): + monomswap = (monom[i],) + monom[:i] + monom[i+1:] + fswap[monomswap] = coeff + return fswap + + +def _degree_bound_bivariate(f, g): + r""" + Compute upper degree bounds for the GCD of two bivariate + integer polynomials `f` and `g`. + + The GCD is viewed as a polynomial in `\mathbb{Z}[y][x]` and the + function returns an upper bound for its degree and one for the degree + of its content. This is done by choosing a suitable prime `p` and + computing the GCD of the contents of `f \; \mathrm{mod} \, p` and + `g \; \mathrm{mod} \, p`. The choice of `p` guarantees that the degree + of the content in `\mathbb{Z}_p[y]` is greater than or equal to the + degree in `\mathbb{Z}[y]`. To obtain the degree bound in the variable + `x`, the polynomials are evaluated at `y = a` for a suitable + `a \in \mathbb{Z}_p` and then their GCD in `\mathbb{Z}_p[x]` is + computed. If no such `a` exists, i.e. the degree in `\mathbb{Z}_p[x]` + is always smaller than the one in `\mathbb{Z}[y][x]`, then the bound is + set to the minimum of the degrees of `f` and `g` in `x`. + + Parameters + ========== + + f : PolyElement + bivariate integer polynomial + g : PolyElement + bivariate integer polynomial + + Returns + ======= + + xbound : Integer + upper bound for the degree of the GCD of the polynomials `f` and + `g` in the variable `x` + ycontbound : Integer + upper bound for the degree of the content of the GCD of the + polynomials `f` and `g` in the variable `y` + + References + ========== + + 1. [Monagan00]_ + + """ + ring = f.ring + + gamma1 = ring.domain.gcd(f.LC, g.LC) + gamma2 = ring.domain.gcd(_swap(f, 1).LC, _swap(g, 1).LC) + badprimes = gamma1 * gamma2 + p = 1 + + p = nextprime(p) + while badprimes % p == 0: + p = nextprime(p) + + fp = f.trunc_ground(p) + gp = g.trunc_ground(p) + contfp, fp = _primitive(fp, p) + contgp, gp = _primitive(gp, p) + conthp = _gf_gcd(contfp, contgp, p) # polynomial in Z_p[y] + ycontbound = conthp.degree() + + # polynomial in Z_p[y] + delta = _gf_gcd(_LC(fp), _LC(gp), p) + + for a in range(p): + if not delta.evaluate(0, a) % p: + continue + fpa = fp.evaluate(1, a).trunc_ground(p) + gpa = gp.evaluate(1, a).trunc_ground(p) + hpa = _gf_gcd(fpa, gpa, p) + xbound = hpa.degree() + return xbound, ycontbound + + return min(fp.degree(), gp.degree()), ycontbound + + +def _chinese_remainder_reconstruction_multivariate(hp, hq, p, q): + r""" + Construct a polynomial `h_{pq}` in + `\mathbb{Z}_{p q}[x_0, \ldots, x_{k-1}]` such that + + .. math :: + + h_{pq} = h_p \; \mathrm{mod} \, p + + h_{pq} = h_q \; \mathrm{mod} \, q + + for relatively prime integers `p` and `q` and polynomials + `h_p` and `h_q` in `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]` and + `\mathbb{Z}_q[x_0, \ldots, x_{k-1}]` respectively. + + The coefficients of the polynomial `h_{pq}` are computed with the + Chinese Remainder Theorem. The symmetric representation in + `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`, + `\mathbb{Z}_q[x_0, \ldots, x_{k-1}]` and + `\mathbb{Z}_{p q}[x_0, \ldots, x_{k-1}]` is used. + + Parameters + ========== + + hp : PolyElement + multivariate integer polynomial with coefficients in `\mathbb{Z}_p` + hq : PolyElement + multivariate integer polynomial with coefficients in `\mathbb{Z}_q` + p : Integer + modulus of `h_p`, relatively prime to `q` + q : Integer + modulus of `h_q`, relatively prime to `p` + + Examples + ======== + + >>> from sympy.polys.modulargcd import _chinese_remainder_reconstruction_multivariate + >>> from sympy.polys import ring, ZZ + + >>> R, x, y = ring("x, y", ZZ) + >>> p = 3 + >>> q = 5 + + >>> hp = x**3*y - x**2 - 1 + >>> hq = -x**3*y - 2*x*y**2 + 2 + + >>> hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q) + >>> hpq + 4*x**3*y + 5*x**2 + 3*x*y**2 + 2 + + >>> hpq.trunc_ground(p) == hp + True + >>> hpq.trunc_ground(q) == hq + True + + >>> R, x, y, z = ring("x, y, z", ZZ) + >>> p = 6 + >>> q = 5 + + >>> hp = 3*x**4 - y**3*z + z + >>> hq = -2*x**4 + z + + >>> hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q) + >>> hpq + 3*x**4 + 5*y**3*z + z + + >>> hpq.trunc_ground(p) == hp + True + >>> hpq.trunc_ground(q) == hq + True + + """ + hpmonoms = set(hp.monoms()) + hqmonoms = set(hq.monoms()) + monoms = hpmonoms.intersection(hqmonoms) + hpmonoms.difference_update(monoms) + hqmonoms.difference_update(monoms) + + domain = hp.ring.domain + zero = domain.zero + + hpq = hp.ring.zero + + if isinstance(hp.ring.domain, PolynomialRing): + crt_ = _chinese_remainder_reconstruction_multivariate + else: + def crt_(cp, cq, p, q): + return domain(crt([p, q], [cp, cq], symmetric=True)[0]) + + for monom in monoms: + hpq[monom] = crt_(hp[monom], hq[monom], p, q) + for monom in hpmonoms: + hpq[monom] = crt_(hp[monom], zero, p, q) + for monom in hqmonoms: + hpq[monom] = crt_(zero, hq[monom], p, q) + + return hpq + + +def _interpolate_multivariate(evalpoints, hpeval, ring, i, p, ground=False): + r""" + Reconstruct a polynomial `h_p` in `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]` + from a list of evaluation points in `\mathbb{Z}_p` and a list of + polynomials in + `\mathbb{Z}_p[x_0, \ldots, x_{i-1}, x_{i+1}, \ldots, x_{k-1}]`, which + are the images of `h_p` evaluated in the variable `x_i`. + + It is also possible to reconstruct a parameter of the ground domain, + i.e. if `h_p` is a polynomial over `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`. + In this case, one has to set ``ground=True``. + + Parameters + ========== + + evalpoints : list of Integer objects + list of evaluation points in `\mathbb{Z}_p` + hpeval : list of PolyElement objects + list of polynomials in (resp. over) + `\mathbb{Z}_p[x_0, \ldots, x_{i-1}, x_{i+1}, \ldots, x_{k-1}]`, + images of `h_p` evaluated in the variable `x_i` + ring : PolyRing + `h_p` will be an element of this ring + i : Integer + index of the variable which has to be reconstructed + p : Integer + prime number, modulus of `h_p` + ground : Boolean + indicates whether `x_i` is in the ground domain, default is + ``False`` + + Returns + ======= + + hp : PolyElement + interpolated polynomial in (resp. over) + `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]` + + """ + hp = ring.zero + + if ground: + domain = ring.domain.domain + y = ring.domain.gens[i] + else: + domain = ring.domain + y = ring.gens[i] + + for a, hpa in zip(evalpoints, hpeval): + numer = ring.one + denom = domain.one + for b in evalpoints: + if b == a: + continue + + numer *= y - b + denom *= a - b + + denom = domain.invert(denom, p) + coeff = numer.mul_ground(denom) + hp += hpa.set_ring(ring) * coeff + + return hp.trunc_ground(p) + + +def modgcd_bivariate(f, g): + r""" + Computes the GCD of two polynomials in `\mathbb{Z}[x, y]` using a + modular algorithm. + + The algorithm computes the GCD of two bivariate integer polynomials + `f` and `g` by calculating the GCD in `\mathbb{Z}_p[x, y]` for + suitable primes `p` and then reconstructing the coefficients with the + Chinese Remainder Theorem. To compute the bivariate GCD over + `\mathbb{Z}_p`, the polynomials `f \; \mathrm{mod} \, p` and + `g \; \mathrm{mod} \, p` are evaluated at `y = a` for certain + `a \in \mathbb{Z}_p` and then their univariate GCD in `\mathbb{Z}_p[x]` + is computed. Interpolating those yields the bivariate GCD in + `\mathbb{Z}_p[x, y]`. To verify the result in `\mathbb{Z}[x, y]`, trial + division is done, but only for candidates which are very likely the + desired GCD. + + Parameters + ========== + + f : PolyElement + bivariate integer polynomial + g : PolyElement + bivariate integer polynomial + + Returns + ======= + + h : PolyElement + GCD of the polynomials `f` and `g` + cff : PolyElement + cofactor of `f`, i.e. `\frac{f}{h}` + cfg : PolyElement + cofactor of `g`, i.e. `\frac{g}{h}` + + Examples + ======== + + >>> from sympy.polys.modulargcd import modgcd_bivariate + >>> from sympy.polys import ring, ZZ + + >>> R, x, y = ring("x, y", ZZ) + + >>> f = x**2 - y**2 + >>> g = x**2 + 2*x*y + y**2 + + >>> h, cff, cfg = modgcd_bivariate(f, g) + >>> h, cff, cfg + (x + y, x - y, x + y) + + >>> cff * h == f + True + >>> cfg * h == g + True + + >>> f = x**2*y - x**2 - 4*y + 4 + >>> g = x + 2 + + >>> h, cff, cfg = modgcd_bivariate(f, g) + >>> h, cff, cfg + (x + 2, x*y - x - 2*y + 2, 1) + + >>> cff * h == f + True + >>> cfg * h == g + True + + References + ========== + + 1. [Monagan00]_ + + """ + assert f.ring == g.ring and f.ring.domain.is_ZZ + + result = _trivial_gcd(f, g) + if result is not None: + return result + + ring = f.ring + + cf, f = f.primitive() + cg, g = g.primitive() + ch = ring.domain.gcd(cf, cg) + + xbound, ycontbound = _degree_bound_bivariate(f, g) + if xbound == ycontbound == 0: + return ring(ch), f.mul_ground(cf // ch), g.mul_ground(cg // ch) + + fswap = _swap(f, 1) + gswap = _swap(g, 1) + degyf = fswap.degree() + degyg = gswap.degree() + + ybound, xcontbound = _degree_bound_bivariate(fswap, gswap) + if ybound == xcontbound == 0: + return ring(ch), f.mul_ground(cf // ch), g.mul_ground(cg // ch) + + # TODO: to improve performance, choose the main variable here + + gamma1 = ring.domain.gcd(f.LC, g.LC) + gamma2 = ring.domain.gcd(fswap.LC, gswap.LC) + badprimes = gamma1 * gamma2 + m = 1 + p = 1 + + while True: + p = nextprime(p) + while badprimes % p == 0: + p = nextprime(p) + + fp = f.trunc_ground(p) + gp = g.trunc_ground(p) + contfp, fp = _primitive(fp, p) + contgp, gp = _primitive(gp, p) + conthp = _gf_gcd(contfp, contgp, p) # monic polynomial in Z_p[y] + degconthp = conthp.degree() + + if degconthp > ycontbound: + continue + elif degconthp < ycontbound: + m = 1 + ycontbound = degconthp + continue + + # polynomial in Z_p[y] + delta = _gf_gcd(_LC(fp), _LC(gp), p) + + degcontfp = contfp.degree() + degcontgp = contgp.degree() + degdelta = delta.degree() + + N = min(degyf - degcontfp, degyg - degcontgp, + ybound - ycontbound + degdelta) + 1 + + if p < N: + continue + + n = 0 + evalpoints = [] + hpeval = [] + unlucky = False + + for a in range(p): + deltaa = delta.evaluate(0, a) + if not deltaa % p: + continue + + fpa = fp.evaluate(1, a).trunc_ground(p) + gpa = gp.evaluate(1, a).trunc_ground(p) + hpa = _gf_gcd(fpa, gpa, p) # monic polynomial in Z_p[x] + deghpa = hpa.degree() + + if deghpa > xbound: + continue + elif deghpa < xbound: + m = 1 + xbound = deghpa + unlucky = True + break + + hpa = hpa.mul_ground(deltaa).trunc_ground(p) + evalpoints.append(a) + hpeval.append(hpa) + n += 1 + + if n == N: + break + + if unlucky: + continue + if n < N: + continue + + hp = _interpolate_multivariate(evalpoints, hpeval, ring, 1, p) + + hp = _primitive(hp, p)[1] + hp = hp * conthp.set_ring(ring) + degyhp = hp.degree(1) + + if degyhp > ybound: + continue + if degyhp < ybound: + m = 1 + ybound = degyhp + continue + + hp = hp.mul_ground(gamma1).trunc_ground(p) + if m == 1: + m = p + hlastm = hp + continue + + hm = _chinese_remainder_reconstruction_multivariate(hp, hlastm, p, m) + m *= p + + if not hm == hlastm: + hlastm = hm + continue + + h = hm.quo_ground(hm.content()) + fquo, frem = f.div(h) + gquo, grem = g.div(h) + if not frem and not grem: + if h.LC < 0: + ch = -ch + h = h.mul_ground(ch) + cff = fquo.mul_ground(cf // ch) + cfg = gquo.mul_ground(cg // ch) + return h, cff, cfg + + +def _modgcd_multivariate_p(f, g, p, degbound, contbound): + r""" + Compute the GCD of two polynomials in + `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`. + + The algorithm reduces the problem step by step by evaluating the + polynomials `f` and `g` at `x_{k-1} = a` for suitable + `a \in \mathbb{Z}_p` and then calls itself recursively to compute the GCD + in `\mathbb{Z}_p[x_0, \ldots, x_{k-2}]`. If these recursive calls are + successful for enough evaluation points, the GCD in `k` variables is + interpolated, otherwise the algorithm returns ``None``. Every time a GCD + or a content is computed, their degrees are compared with the bounds. If + a degree greater then the bound is encountered, then the current call + returns ``None`` and a new evaluation point has to be chosen. If at some + point the degree is smaller, the correspondent bound is updated and the + algorithm fails. + + Parameters + ========== + + f : PolyElement + multivariate integer polynomial with coefficients in `\mathbb{Z}_p` + g : PolyElement + multivariate integer polynomial with coefficients in `\mathbb{Z}_p` + p : Integer + prime number, modulus of `f` and `g` + degbound : list of Integer objects + ``degbound[i]`` is an upper bound for the degree of the GCD of `f` + and `g` in the variable `x_i` + contbound : list of Integer objects + ``contbound[i]`` is an upper bound for the degree of the content of + the GCD in `\mathbb{Z}_p[x_i][x_0, \ldots, x_{i-1}]`, + ``contbound[0]`` is not used can therefore be chosen + arbitrarily. + + Returns + ======= + + h : PolyElement + GCD of the polynomials `f` and `g` or ``None`` + + References + ========== + + 1. [Monagan00]_ + 2. [Brown71]_ + + """ + ring = f.ring + k = ring.ngens + + if k == 1: + h = _gf_gcd(f, g, p).trunc_ground(p) + degh = h.degree() + + if degh > degbound[0]: + return None + if degh < degbound[0]: + degbound[0] = degh + raise ModularGCDFailed + + return h + + degyf = f.degree(k-1) + degyg = g.degree(k-1) + + contf, f = _primitive(f, p) + contg, g = _primitive(g, p) + + conth = _gf_gcd(contf, contg, p) # polynomial in Z_p[y] + + degcontf = contf.degree() + degcontg = contg.degree() + degconth = conth.degree() + + if degconth > contbound[k-1]: + return None + if degconth < contbound[k-1]: + contbound[k-1] = degconth + raise ModularGCDFailed + + lcf = _LC(f) + lcg = _LC(g) + + delta = _gf_gcd(lcf, lcg, p) # polynomial in Z_p[y] + + evaltest = delta + + for i in range(k-1): + evaltest *= _gf_gcd(_LC(_swap(f, i)), _LC(_swap(g, i)), p) + + degdelta = delta.degree() + + N = min(degyf - degcontf, degyg - degcontg, + degbound[k-1] - contbound[k-1] + degdelta) + 1 + + if p < N: + return None + + n = 0 + d = 0 + evalpoints = [] + heval = [] + points = list(range(p)) + + while points: + a = random.sample(points, 1)[0] + points.remove(a) + + if not evaltest.evaluate(0, a) % p: + continue + + deltaa = delta.evaluate(0, a) % p + + fa = f.evaluate(k-1, a).trunc_ground(p) + ga = g.evaluate(k-1, a).trunc_ground(p) + + # polynomials in Z_p[x_0, ..., x_{k-2}] + ha = _modgcd_multivariate_p(fa, ga, p, degbound, contbound) + + if ha is None: + d += 1 + if d > n: + return None + continue + + if ha.is_ground: + h = conth.set_ring(ring).trunc_ground(p) + return h + + ha = ha.mul_ground(deltaa).trunc_ground(p) + + evalpoints.append(a) + heval.append(ha) + n += 1 + + if n == N: + h = _interpolate_multivariate(evalpoints, heval, ring, k-1, p) + + h = _primitive(h, p)[1] * conth.set_ring(ring) + degyh = h.degree(k-1) + + if degyh > degbound[k-1]: + return None + if degyh < degbound[k-1]: + degbound[k-1] = degyh + raise ModularGCDFailed + + return h + + return None + + +def modgcd_multivariate(f, g): + r""" + Compute the GCD of two polynomials in `\mathbb{Z}[x_0, \ldots, x_{k-1}]` + using a modular algorithm. + + The algorithm computes the GCD of two multivariate integer polynomials + `f` and `g` by calculating the GCD in + `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]` for suitable primes `p` and then + reconstructing the coefficients with the Chinese Remainder Theorem. To + compute the multivariate GCD over `\mathbb{Z}_p` the recursive + subroutine :func:`_modgcd_multivariate_p` is used. To verify the result in + `\mathbb{Z}[x_0, \ldots, x_{k-1}]`, trial division is done, but only for + candidates which are very likely the desired GCD. + + Parameters + ========== + + f : PolyElement + multivariate integer polynomial + g : PolyElement + multivariate integer polynomial + + Returns + ======= + + h : PolyElement + GCD of the polynomials `f` and `g` + cff : PolyElement + cofactor of `f`, i.e. `\frac{f}{h}` + cfg : PolyElement + cofactor of `g`, i.e. `\frac{g}{h}` + + Examples + ======== + + >>> from sympy.polys.modulargcd import modgcd_multivariate + >>> from sympy.polys import ring, ZZ + + >>> R, x, y = ring("x, y", ZZ) + + >>> f = x**2 - y**2 + >>> g = x**2 + 2*x*y + y**2 + + >>> h, cff, cfg = modgcd_multivariate(f, g) + >>> h, cff, cfg + (x + y, x - y, x + y) + + >>> cff * h == f + True + >>> cfg * h == g + True + + >>> R, x, y, z = ring("x, y, z", ZZ) + + >>> f = x*z**2 - y*z**2 + >>> g = x**2*z + z + + >>> h, cff, cfg = modgcd_multivariate(f, g) + >>> h, cff, cfg + (z, x*z - y*z, x**2 + 1) + + >>> cff * h == f + True + >>> cfg * h == g + True + + References + ========== + + 1. [Monagan00]_ + 2. [Brown71]_ + + See also + ======== + + _modgcd_multivariate_p + + """ + assert f.ring == g.ring and f.ring.domain.is_ZZ + + result = _trivial_gcd(f, g) + if result is not None: + return result + + ring = f.ring + k = ring.ngens + + # divide out integer content + cf, f = f.primitive() + cg, g = g.primitive() + ch = ring.domain.gcd(cf, cg) + + gamma = ring.domain.gcd(f.LC, g.LC) + + badprimes = ring.domain.one + for i in range(k): + badprimes *= ring.domain.gcd(_swap(f, i).LC, _swap(g, i).LC) + + degbound = [min(fdeg, gdeg) for fdeg, gdeg in zip(f.degrees(), g.degrees())] + contbound = list(degbound) + + m = 1 + p = 1 + + while True: + p = nextprime(p) + while badprimes % p == 0: + p = nextprime(p) + + fp = f.trunc_ground(p) + gp = g.trunc_ground(p) + + try: + # monic GCD of fp, gp in Z_p[x_0, ..., x_{k-2}, y] + hp = _modgcd_multivariate_p(fp, gp, p, degbound, contbound) + except ModularGCDFailed: + m = 1 + continue + + if hp is None: + continue + + hp = hp.mul_ground(gamma).trunc_ground(p) + if m == 1: + m = p + hlastm = hp + continue + + hm = _chinese_remainder_reconstruction_multivariate(hp, hlastm, p, m) + m *= p + + if not hm == hlastm: + hlastm = hm + continue + + h = hm.primitive()[1] + fquo, frem = f.div(h) + gquo, grem = g.div(h) + if not frem and not grem: + if h.LC < 0: + ch = -ch + h = h.mul_ground(ch) + cff = fquo.mul_ground(cf // ch) + cfg = gquo.mul_ground(cg // ch) + return h, cff, cfg + + +def _gf_div(f, g, p): + r""" + Compute `\frac f g` modulo `p` for two univariate polynomials over + `\mathbb Z_p`. + """ + ring = f.ring + densequo, denserem = gf_div(f.to_dense(), g.to_dense(), p, ring.domain) + return ring.from_dense(densequo), ring.from_dense(denserem) + + +def _rational_function_reconstruction(c, p, m): + r""" + Reconstruct a rational function `\frac a b` in `\mathbb Z_p(t)` from + + .. math:: + + c = \frac a b \; \mathrm{mod} \, m, + + where `c` and `m` are polynomials in `\mathbb Z_p[t]` and `m` has + positive degree. + + The algorithm is based on the Euclidean Algorithm. In general, `m` is + not irreducible, so it is possible that `b` is not invertible modulo + `m`. In that case ``None`` is returned. + + Parameters + ========== + + c : PolyElement + univariate polynomial in `\mathbb Z[t]` + p : Integer + prime number + m : PolyElement + modulus, not necessarily irreducible + + Returns + ======= + + frac : FracElement + either `\frac a b` in `\mathbb Z(t)` or ``None`` + + References + ========== + + 1. [Hoeij04]_ + + """ + ring = c.ring + domain = ring.domain + M = m.degree() + N = M // 2 + D = M - N - 1 + + r0, s0 = m, ring.zero + r1, s1 = c, ring.one + + while r1.degree() > N: + quo = _gf_div(r0, r1, p)[0] + r0, r1 = r1, (r0 - quo*r1).trunc_ground(p) + s0, s1 = s1, (s0 - quo*s1).trunc_ground(p) + + a, b = r1, s1 + if b.degree() > D or _gf_gcd(b, m, p) != 1: + return None + + lc = b.LC + if lc != 1: + lcinv = domain.invert(lc, p) + a = a.mul_ground(lcinv).trunc_ground(p) + b = b.mul_ground(lcinv).trunc_ground(p) + + field = ring.to_field() + + return field(a) / field(b) + + +def _rational_reconstruction_func_coeffs(hm, p, m, ring, k): + r""" + Reconstruct every coefficient `c_h` of a polynomial `h` in + `\mathbb Z_p(t_k)[t_1, \ldots, t_{k-1}][x, z]` from the corresponding + coefficient `c_{h_m}` of a polynomial `h_m` in + `\mathbb Z_p[t_1, \ldots, t_k][x, z] \cong \mathbb Z_p[t_k][t_1, \ldots, t_{k-1}][x, z]` + such that + + .. math:: + + c_{h_m} = c_h \; \mathrm{mod} \, m, + + where `m \in \mathbb Z_p[t]`. + + The reconstruction is based on the Euclidean Algorithm. In general, `m` + is not irreducible, so it is possible that this fails for some + coefficient. In that case ``None`` is returned. + + Parameters + ========== + + hm : PolyElement + polynomial in `\mathbb Z[t_1, \ldots, t_k][x, z]` + p : Integer + prime number, modulus of `\mathbb Z_p` + m : PolyElement + modulus, polynomial in `\mathbb Z[t]`, not necessarily irreducible + ring : PolyRing + `\mathbb Z(t_k)[t_1, \ldots, t_{k-1}][x, z]`, `h` will be an + element of this ring + k : Integer + index of the parameter `t_k` which will be reconstructed + + Returns + ======= + + h : PolyElement + reconstructed polynomial in + `\mathbb Z(t_k)[t_1, \ldots, t_{k-1}][x, z]` or ``None`` + + See also + ======== + + _rational_function_reconstruction + + """ + h = ring.zero + + for monom, coeff in hm.iterterms(): + if k == 0: + coeffh = _rational_function_reconstruction(coeff, p, m) + + if not coeffh: + return None + + else: + coeffh = ring.domain.zero + for mon, c in coeff.drop_to_ground(k).iterterms(): + ch = _rational_function_reconstruction(c, p, m) + + if not ch: + return None + + coeffh[mon] = ch + + h[monom] = coeffh + + return h + + +def _gf_gcdex(f, g, p): + r""" + Extended Euclidean Algorithm for two univariate polynomials over + `\mathbb Z_p`. + + Returns polynomials `s, t` and `h`, such that `h` is the GCD of `f` and + `g` and `sf + tg = h \; \mathrm{mod} \, p`. + + """ + ring = f.ring + s, t, h = gf_gcdex(f.to_dense(), g.to_dense(), p, ring.domain) + return ring.from_dense(s), ring.from_dense(t), ring.from_dense(h) + + +def _trunc(f, minpoly, p): + r""" + Compute the reduced representation of a polynomial `f` in + `\mathbb Z_p[z] / (\check m_{\alpha}(z))[x]` + + Parameters + ========== + + f : PolyElement + polynomial in `\mathbb Z[x, z]` + minpoly : PolyElement + polynomial `\check m_{\alpha} \in \mathbb Z[z]`, not necessarily + irreducible + p : Integer + prime number, modulus of `\mathbb Z_p` + + Returns + ======= + + ftrunc : PolyElement + polynomial in `\mathbb Z[x, z]`, reduced modulo + `\check m_{\alpha}(z)` and `p` + + """ + ring = f.ring + minpoly = minpoly.set_ring(ring) + p_ = ring.ground_new(p) + + return f.trunc_ground(p).rem([minpoly, p_]).trunc_ground(p) + + +def _euclidean_algorithm(f, g, minpoly, p): + r""" + Compute the monic GCD of two univariate polynomials in + `\mathbb{Z}_p[z]/(\check m_{\alpha}(z))[x]` with the Euclidean + Algorithm. + + In general, `\check m_{\alpha}(z)` is not irreducible, so it is possible + that some leading coefficient is not invertible modulo + `\check m_{\alpha}(z)`. In that case ``None`` is returned. + + Parameters + ========== + + f, g : PolyElement + polynomials in `\mathbb Z[x, z]` + minpoly : PolyElement + polynomial in `\mathbb Z[z]`, not necessarily irreducible + p : Integer + prime number, modulus of `\mathbb Z_p` + + Returns + ======= + + h : PolyElement + GCD of `f` and `g` in `\mathbb Z[z, x]` or ``None``, coefficients + are in `\left[ -\frac{p-1} 2, \frac{p-1} 2 \right]` + + """ + ring = f.ring + + f = _trunc(f, minpoly, p) + g = _trunc(g, minpoly, p) + + while g: + rem = f + deg = g.degree(0) # degree in x + lcinv, _, gcd = _gf_gcdex(ring.dmp_LC(g), minpoly, p) + + if not gcd == 1: + return None + + while True: + degrem = rem.degree(0) # degree in x + if degrem < deg: + break + quo = (lcinv * ring.dmp_LC(rem)).set_ring(ring) + rem = _trunc(rem - g.mul_monom((degrem - deg, 0))*quo, minpoly, p) + + f = g + g = rem + + lcfinv = _gf_gcdex(ring.dmp_LC(f), minpoly, p)[0].set_ring(ring) + + return _trunc(f * lcfinv, minpoly, p) + + +def _trial_division(f, h, minpoly, p=None): + r""" + Check if `h` divides `f` in + `\mathbb K[t_1, \ldots, t_k][z]/(m_{\alpha}(z))`, where `\mathbb K` is + either `\mathbb Q` or `\mathbb Z_p`. + + This algorithm is based on pseudo division and does not use any + fractions. By default `\mathbb K` is `\mathbb Q`, if a prime number `p` + is given, `\mathbb Z_p` is chosen instead. + + Parameters + ========== + + f, h : PolyElement + polynomials in `\mathbb Z[t_1, \ldots, t_k][x, z]` + minpoly : PolyElement + polynomial `m_{\alpha}(z)` in `\mathbb Z[t_1, \ldots, t_k][z]` + p : Integer or None + if `p` is given, `\mathbb K` is set to `\mathbb Z_p` instead of + `\mathbb Q`, default is ``None`` + + Returns + ======= + + rem : PolyElement + remainder of `\frac f h` + + References + ========== + + .. [1] [Hoeij02]_ + + """ + ring = f.ring + + zxring = ring.clone(symbols=(ring.symbols[1], ring.symbols[0])) + + minpoly = minpoly.set_ring(ring) + + rem = f + + degrem = rem.degree() + degh = h.degree() + degm = minpoly.degree(1) + + lch = _LC(h).set_ring(ring) + lcm = minpoly.LC + + while rem and degrem >= degh: + # polynomial in Z[t_1, ..., t_k][z] + lcrem = _LC(rem).set_ring(ring) + rem = rem*lch - h.mul_monom((degrem - degh, 0))*lcrem + if p: + rem = rem.trunc_ground(p) + degrem = rem.degree(1) + + while rem and degrem >= degm: + # polynomial in Z[t_1, ..., t_k][x] + lcrem = _LC(rem.set_ring(zxring)).set_ring(ring) + rem = rem.mul_ground(lcm) - minpoly.mul_monom((0, degrem - degm))*lcrem + if p: + rem = rem.trunc_ground(p) + degrem = rem.degree(1) + + degrem = rem.degree() + + return rem + + +def _evaluate_ground(f, i, a): + r""" + Evaluate a polynomial `f` at `a` in the `i`-th variable of the ground + domain. + """ + ring = f.ring.clone(domain=f.ring.domain.ring.drop(i)) + fa = ring.zero + + for monom, coeff in f.iterterms(): + fa[monom] = coeff.evaluate(i, a) + + return fa + + +def _func_field_modgcd_p(f, g, minpoly, p): + r""" + Compute the GCD of two polynomials `f` and `g` in + `\mathbb Z_p(t_1, \ldots, t_k)[z]/(\check m_\alpha(z))[x]`. + + The algorithm reduces the problem step by step by evaluating the + polynomials `f` and `g` at `t_k = a` for suitable `a \in \mathbb Z_p` + and then calls itself recursively to compute the GCD in + `\mathbb Z_p(t_1, \ldots, t_{k-1})[z]/(\check m_\alpha(z))[x]`. If these + recursive calls are successful, the GCD over `k` variables is + interpolated, otherwise the algorithm returns ``None``. After + interpolation, Rational Function Reconstruction is used to obtain the + correct coefficients. If this fails, a new evaluation point has to be + chosen, otherwise the desired polynomial is obtained by clearing + denominators. The result is verified with a fraction free trial + division. + + Parameters + ========== + + f, g : PolyElement + polynomials in `\mathbb Z[t_1, \ldots, t_k][x, z]` + minpoly : PolyElement + polynomial in `\mathbb Z[t_1, \ldots, t_k][z]`, not necessarily + irreducible + p : Integer + prime number, modulus of `\mathbb Z_p` + + Returns + ======= + + h : PolyElement + primitive associate in `\mathbb Z[t_1, \ldots, t_k][x, z]` of the + GCD of the polynomials `f` and `g` or ``None``, coefficients are + in `\left[ -\frac{p-1} 2, \frac{p-1} 2 \right]` + + References + ========== + + 1. [Hoeij04]_ + + """ + ring = f.ring + domain = ring.domain # Z[t_1, ..., t_k] + + if isinstance(domain, PolynomialRing): + k = domain.ngens + else: + return _euclidean_algorithm(f, g, minpoly, p) + + if k == 1: + qdomain = domain.ring.to_field() + else: + qdomain = domain.ring.drop_to_ground(k - 1) + qdomain = qdomain.clone(domain=qdomain.domain.ring.to_field()) + + qring = ring.clone(domain=qdomain) # = Z(t_k)[t_1, ..., t_{k-1}][x, z] + + n = 1 + d = 1 + + # polynomial in Z_p[t_1, ..., t_k][z] + gamma = ring.dmp_LC(f) * ring.dmp_LC(g) + # polynomial in Z_p[t_1, ..., t_k] + delta = minpoly.LC + + evalpoints = [] + heval = [] + LMlist = [] + points = list(range(p)) + + while points: + a = random.sample(points, 1)[0] + points.remove(a) + + if k == 1: + test = delta.evaluate(k-1, a) % p == 0 + else: + test = delta.evaluate(k-1, a).trunc_ground(p) == 0 + + if test: + continue + + gammaa = _evaluate_ground(gamma, k-1, a) + minpolya = _evaluate_ground(minpoly, k-1, a) + + if gammaa.rem([minpolya, gammaa.ring(p)]) == 0: + continue + + fa = _evaluate_ground(f, k-1, a) + ga = _evaluate_ground(g, k-1, a) + + # polynomial in Z_p[x, t_1, ..., t_{k-1}, z]/(minpoly) + ha = _func_field_modgcd_p(fa, ga, minpolya, p) + + if ha is None: + d += 1 + if d > n: + return None + continue + + if ha == 1: + return ha + + LM = [ha.degree()] + [0]*(k-1) + if k > 1: + for monom, coeff in ha.iterterms(): + if monom[0] == LM[0] and coeff.LM > tuple(LM[1:]): + LM[1:] = coeff.LM + + evalpoints_a = [a] + heval_a = [ha] + if k == 1: + m = qring.domain.get_ring().one + else: + m = qring.domain.domain.get_ring().one + + t = m.ring.gens[0] + + for b, hb, LMhb in zip(evalpoints, heval, LMlist): + if LMhb == LM: + evalpoints_a.append(b) + heval_a.append(hb) + m *= (t - b) + + m = m.trunc_ground(p) + evalpoints.append(a) + heval.append(ha) + LMlist.append(LM) + n += 1 + + # polynomial in Z_p[t_1, ..., t_k][x, z] + h = _interpolate_multivariate(evalpoints_a, heval_a, ring, k-1, p, ground=True) + + # polynomial in Z_p(t_k)[t_1, ..., t_{k-1}][x, z] + h = _rational_reconstruction_func_coeffs(h, p, m, qring, k-1) + + if h is None: + continue + + if k == 1: + dom = qring.domain.field + den = dom.ring.one + + for coeff in h.itercoeffs(): + den = dom.ring.from_dense(gf_lcm(den.to_dense(), coeff.denom.to_dense(), + p, dom.domain)) + + else: + dom = qring.domain.domain.field + den = dom.ring.one + + for coeff in h.itercoeffs(): + for c in coeff.itercoeffs(): + den = dom.ring.from_dense(gf_lcm(den.to_dense(), c.denom.to_dense(), + p, dom.domain)) + + den = qring.domain_new(den.trunc_ground(p)) + h = ring(h.mul_ground(den).as_expr()).trunc_ground(p) + + if not _trial_division(f, h, minpoly, p) and not _trial_division(g, h, minpoly, p): + return h + + return None + + +def _integer_rational_reconstruction(c, m, domain): + r""" + Reconstruct a rational number `\frac a b` from + + .. math:: + + c = \frac a b \; \mathrm{mod} \, m, + + where `c` and `m` are integers. + + The algorithm is based on the Euclidean Algorithm. In general, `m` is + not a prime number, so it is possible that `b` is not invertible modulo + `m`. In that case ``None`` is returned. + + Parameters + ========== + + c : Integer + `c = \frac a b \; \mathrm{mod} \, m` + m : Integer + modulus, not necessarily prime + domain : IntegerRing + `a, b, c` are elements of ``domain`` + + Returns + ======= + + frac : Rational + either `\frac a b` in `\mathbb Q` or ``None`` + + References + ========== + + 1. [Wang81]_ + + """ + if c < 0: + c += m + + r0, s0 = m, domain.zero + r1, s1 = c, domain.one + + bound = sqrt(m / 2) # still correct if replaced by ZZ.sqrt(m // 2) ? + + while int(r1) >= bound: + quo = r0 // r1 + r0, r1 = r1, r0 - quo*r1 + s0, s1 = s1, s0 - quo*s1 + + if abs(int(s1)) >= bound: + return None + + if s1 < 0: + a, b = -r1, -s1 + elif s1 > 0: + a, b = r1, s1 + else: + return None + + field = domain.get_field() + + return field(a) / field(b) + + +def _rational_reconstruction_int_coeffs(hm, m, ring): + r""" + Reconstruct every rational coefficient `c_h` of a polynomial `h` in + `\mathbb Q[t_1, \ldots, t_k][x, z]` from the corresponding integer + coefficient `c_{h_m}` of a polynomial `h_m` in + `\mathbb Z[t_1, \ldots, t_k][x, z]` such that + + .. math:: + + c_{h_m} = c_h \; \mathrm{mod} \, m, + + where `m \in \mathbb Z`. + + The reconstruction is based on the Euclidean Algorithm. In general, + `m` is not a prime number, so it is possible that this fails for some + coefficient. In that case ``None`` is returned. + + Parameters + ========== + + hm : PolyElement + polynomial in `\mathbb Z[t_1, \ldots, t_k][x, z]` + m : Integer + modulus, not necessarily prime + ring : PolyRing + `\mathbb Q[t_1, \ldots, t_k][x, z]`, `h` will be an element of this + ring + + Returns + ======= + + h : PolyElement + reconstructed polynomial in `\mathbb Q[t_1, \ldots, t_k][x, z]` or + ``None`` + + See also + ======== + + _integer_rational_reconstruction + + """ + h = ring.zero + + if isinstance(ring.domain, PolynomialRing): + reconstruction = _rational_reconstruction_int_coeffs + domain = ring.domain.ring + else: + reconstruction = _integer_rational_reconstruction + domain = hm.ring.domain + + for monom, coeff in hm.iterterms(): + coeffh = reconstruction(coeff, m, domain) + + if not coeffh: + return None + + h[monom] = coeffh + + return h + + +def _func_field_modgcd_m(f, g, minpoly): + r""" + Compute the GCD of two polynomials in + `\mathbb Q(t_1, \ldots, t_k)[z]/(m_{\alpha}(z))[x]` using a modular + algorithm. + + The algorithm computes the GCD of two polynomials `f` and `g` by + calculating the GCD in + `\mathbb Z_p(t_1, \ldots, t_k)[z] / (\check m_{\alpha}(z))[x]` for + suitable primes `p` and the primitive associate `\check m_{\alpha}(z)` + of `m_{\alpha}(z)`. Then the coefficients are reconstructed with the + Chinese Remainder Theorem and Rational Reconstruction. To compute the + GCD over `\mathbb Z_p(t_1, \ldots, t_k)[z] / (\check m_{\alpha})[x]`, + the recursive subroutine ``_func_field_modgcd_p`` is used. To verify the + result in `\mathbb Q(t_1, \ldots, t_k)[z] / (m_{\alpha}(z))[x]`, a + fraction free trial division is used. + + Parameters + ========== + + f, g : PolyElement + polynomials in `\mathbb Z[t_1, \ldots, t_k][x, z]` + minpoly : PolyElement + irreducible polynomial in `\mathbb Z[t_1, \ldots, t_k][z]` + + Returns + ======= + + h : PolyElement + the primitive associate in `\mathbb Z[t_1, \ldots, t_k][x, z]` of + the GCD of `f` and `g` + + Examples + ======== + + >>> from sympy.polys.modulargcd import _func_field_modgcd_m + >>> from sympy.polys import ring, ZZ + + >>> R, x, z = ring('x, z', ZZ) + >>> minpoly = (z**2 - 2).drop(0) + + >>> f = x**2 + 2*x*z + 2 + >>> g = x + z + >>> _func_field_modgcd_m(f, g, minpoly) + x + z + + >>> D, t = ring('t', ZZ) + >>> R, x, z = ring('x, z', D) + >>> minpoly = (z**2-3).drop(0) + + >>> f = x**2 + (t + 1)*x*z + 3*t + >>> g = x*z + 3*t + >>> _func_field_modgcd_m(f, g, minpoly) + x + t*z + + References + ========== + + 1. [Hoeij04]_ + + See also + ======== + + _func_field_modgcd_p + + """ + ring = f.ring + domain = ring.domain + + if isinstance(domain, PolynomialRing): + k = domain.ngens + QQdomain = domain.ring.clone(domain=domain.domain.get_field()) + QQring = ring.clone(domain=QQdomain) + else: + k = 0 + QQring = ring.clone(domain=ring.domain.get_field()) + + cf, f = f.primitive() + cg, g = g.primitive() + + # polynomial in Z[t_1, ..., t_k][z] + gamma = ring.dmp_LC(f) * ring.dmp_LC(g) + # polynomial in Z[t_1, ..., t_k] + delta = minpoly.LC + + p = 1 + primes = [] + hplist = [] + LMlist = [] + + while True: + p = nextprime(p) + + if gamma.trunc_ground(p) == 0: + continue + + if k == 0: + test = (delta % p == 0) + else: + test = (delta.trunc_ground(p) == 0) + + if test: + continue + + fp = f.trunc_ground(p) + gp = g.trunc_ground(p) + minpolyp = minpoly.trunc_ground(p) + + hp = _func_field_modgcd_p(fp, gp, minpolyp, p) + + if hp is None: + continue + + if hp == 1: + return ring.one + + LM = [hp.degree()] + [0]*k + if k > 0: + for monom, coeff in hp.iterterms(): + if monom[0] == LM[0] and coeff.LM > tuple(LM[1:]): + LM[1:] = coeff.LM + + hm = hp + m = p + + for q, hq, LMhq in zip(primes, hplist, LMlist): + if LMhq == LM: + hm = _chinese_remainder_reconstruction_multivariate(hq, hm, q, m) + m *= q + + primes.append(p) + hplist.append(hp) + LMlist.append(LM) + + hm = _rational_reconstruction_int_coeffs(hm, m, QQring) + + if hm is None: + continue + + if k == 0: + h = hm.clear_denoms()[1] + else: + den = domain.domain.one + for coeff in hm.itercoeffs(): + den = domain.domain.lcm(den, coeff.clear_denoms()[0]) + h = hm.mul_ground(den) + + # convert back to Z[t_1, ..., t_k][x, z] from Q[t_1, ..., t_k][x, z] + h = h.set_ring(ring) + h = h.primitive()[1] + + if not (_trial_division(f.mul_ground(cf), h, minpoly) or + _trial_division(g.mul_ground(cg), h, minpoly)): + return h + + +def _to_ZZ_poly(f, ring): + r""" + Compute an associate of a polynomial + `f \in \mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` in + `\mathbb Z[x_1, \ldots, x_{n-1}][z] / (\check m_{\alpha}(z))[x_0]`, + where `\check m_{\alpha}(z) \in \mathbb Z[z]` is the primitive associate + of the minimal polynomial `m_{\alpha}(z)` of `\alpha` over + `\mathbb Q`. + + Parameters + ========== + + f : PolyElement + polynomial in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` + ring : PolyRing + `\mathbb Z[x_1, \ldots, x_{n-1}][x_0, z]` + + Returns + ======= + + f_ : PolyElement + associate of `f` in + `\mathbb Z[x_1, \ldots, x_{n-1}][x_0, z]` + + """ + f_ = ring.zero + + if isinstance(ring.domain, PolynomialRing): + domain = ring.domain.domain + else: + domain = ring.domain + + den = domain.one + + for coeff in f.itercoeffs(): + for c in coeff.to_list(): + if c: + den = domain.lcm(den, c.denominator) + + for monom, coeff in f.iterterms(): + coeff = coeff.to_list() + m = ring.domain.one + if isinstance(ring.domain, PolynomialRing): + m = m.mul_monom(monom[1:]) + n = len(coeff) + + for i in range(n): + if coeff[i]: + c = domain.convert(coeff[i] * den) * m + + if (monom[0], n-i-1) not in f_: + f_[(monom[0], n-i-1)] = c + else: + f_[(monom[0], n-i-1)] += c + + return f_ + + +def _to_ANP_poly(f, ring): + r""" + Convert a polynomial + `f \in \mathbb Z[x_1, \ldots, x_{n-1}][z]/(\check m_{\alpha}(z))[x_0]` + to a polynomial in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]`, + where `\check m_{\alpha}(z) \in \mathbb Z[z]` is the primitive associate + of the minimal polynomial `m_{\alpha}(z)` of `\alpha` over + `\mathbb Q`. + + Parameters + ========== + + f : PolyElement + polynomial in `\mathbb Z[x_1, \ldots, x_{n-1}][x_0, z]` + ring : PolyRing + `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` + + Returns + ======= + + f_ : PolyElement + polynomial in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` + + """ + domain = ring.domain + f_ = ring.zero + + if isinstance(f.ring.domain, PolynomialRing): + for monom, coeff in f.iterterms(): + for mon, coef in coeff.iterterms(): + m = (monom[0],) + mon + c = domain([domain.domain(coef)] + [0]*monom[1]) + + if m not in f_: + f_[m] = c + else: + f_[m] += c + + else: + for monom, coeff in f.iterterms(): + m = (monom[0],) + c = domain([domain.domain(coeff)] + [0]*monom[1]) + + if m not in f_: + f_[m] = c + else: + f_[m] += c + + return f_ + + +def _minpoly_from_dense(minpoly, ring): + r""" + Change representation of the minimal polynomial from ``DMP`` to + ``PolyElement`` for a given ring. + """ + minpoly_ = ring.zero + + for monom, coeff in minpoly.terms(): + minpoly_[monom] = ring.domain(coeff) + + return minpoly_ + + +def _primitive_in_x0(f): + r""" + Compute the content in `x_0` and the primitive part of a polynomial `f` + in + `\mathbb Q(\alpha)[x_0, x_1, \ldots, x_{n-1}] \cong \mathbb Q(\alpha)[x_1, \ldots, x_{n-1}][x_0]`. + """ + fring = f.ring + ring = fring.drop_to_ground(*range(1, fring.ngens)) + dom = ring.domain.ring + f_ = ring(f.as_expr()) + cont = dom.zero + + for coeff in f_.itercoeffs(): + cont = func_field_modgcd(cont, coeff)[0] + if cont == dom.one: + return cont, f + + return cont, f.quo(cont.set_ring(fring)) + + +# TODO: add support for algebraic function fields +def func_field_modgcd(f, g): + r""" + Compute the GCD of two polynomials `f` and `g` in + `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` using a modular algorithm. + + The algorithm first computes the primitive associate + `\check m_{\alpha}(z)` of the minimal polynomial `m_{\alpha}` in + `\mathbb{Z}[z]` and the primitive associates of `f` and `g` in + `\mathbb{Z}[x_1, \ldots, x_{n-1}][z]/(\check m_{\alpha})[x_0]`. Then it + computes the GCD in + `\mathbb Q(x_1, \ldots, x_{n-1})[z]/(m_{\alpha}(z))[x_0]`. + This is done by calculating the GCD in + `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]` for + suitable primes `p` and then reconstructing the coefficients with the + Chinese Remainder Theorem and Rational Reconstruction. The GCD over + `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]` is + computed with a recursive subroutine, which evaluates the polynomials at + `x_{n-1} = a` for suitable evaluation points `a \in \mathbb Z_p` and + then calls itself recursively until the ground domain does no longer + contain any parameters. For + `\mathbb{Z}_p[z]/(\check m_{\alpha}(z))[x_0]` the Euclidean Algorithm is + used. The results of those recursive calls are then interpolated and + Rational Function Reconstruction is used to obtain the correct + coefficients. The results, both in + `\mathbb Q(x_1, \ldots, x_{n-1})[z]/(m_{\alpha}(z))[x_0]` and + `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]`, are + verified by a fraction free trial division. + + Apart from the above GCD computation some GCDs in + `\mathbb Q(\alpha)[x_1, \ldots, x_{n-1}]` have to be calculated, + because treating the polynomials as univariate ones can result in + a spurious content of the GCD. For this ``func_field_modgcd`` is + called recursively. + + Parameters + ========== + + f, g : PolyElement + polynomials in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` + + Returns + ======= + + h : PolyElement + monic GCD of the polynomials `f` and `g` + cff : PolyElement + cofactor of `f`, i.e. `\frac f h` + cfg : PolyElement + cofactor of `g`, i.e. `\frac g h` + + Examples + ======== + + >>> from sympy.polys.modulargcd import func_field_modgcd + >>> from sympy.polys import AlgebraicField, QQ, ring + >>> from sympy import sqrt + + >>> A = AlgebraicField(QQ, sqrt(2)) + >>> R, x = ring('x', A) + + >>> f = x**2 - 2 + >>> g = x + sqrt(2) + + >>> h, cff, cfg = func_field_modgcd(f, g) + + >>> h == x + sqrt(2) + True + >>> cff * h == f + True + >>> cfg * h == g + True + + >>> R, x, y = ring('x, y', A) + + >>> f = x**2 + 2*sqrt(2)*x*y + 2*y**2 + >>> g = x + sqrt(2)*y + + >>> h, cff, cfg = func_field_modgcd(f, g) + + >>> h == x + sqrt(2)*y + True + >>> cff * h == f + True + >>> cfg * h == g + True + + >>> f = x + sqrt(2)*y + >>> g = x + y + + >>> h, cff, cfg = func_field_modgcd(f, g) + + >>> h == R.one + True + >>> cff * h == f + True + >>> cfg * h == g + True + + References + ========== + + 1. [Hoeij04]_ + + """ + ring = f.ring + domain = ring.domain + n = ring.ngens + + assert ring == g.ring and domain.is_Algebraic + + result = _trivial_gcd(f, g) + if result is not None: + return result + + z = Dummy('z') + + ZZring = ring.clone(symbols=ring.symbols + (z,), domain=domain.domain.get_ring()) + + if n == 1: + f_ = _to_ZZ_poly(f, ZZring) + g_ = _to_ZZ_poly(g, ZZring) + minpoly = ZZring.drop(0).from_dense(domain.mod.to_list()) + + h = _func_field_modgcd_m(f_, g_, minpoly) + h = _to_ANP_poly(h, ring) + + else: + # contx0f in Q(a)[x_1, ..., x_{n-1}], f in Q(a)[x_0, ..., x_{n-1}] + contx0f, f = _primitive_in_x0(f) + contx0g, g = _primitive_in_x0(g) + contx0h = func_field_modgcd(contx0f, contx0g)[0] + + ZZring_ = ZZring.drop_to_ground(*range(1, n)) + + f_ = _to_ZZ_poly(f, ZZring_) + g_ = _to_ZZ_poly(g, ZZring_) + minpoly = _minpoly_from_dense(domain.mod, ZZring_.drop(0)) + + h = _func_field_modgcd_m(f_, g_, minpoly) + h = _to_ANP_poly(h, ring) + + contx0h_, h = _primitive_in_x0(h) + h *= contx0h.set_ring(ring) + f *= contx0f.set_ring(ring) + g *= contx0g.set_ring(ring) + + h = h.quo_ground(h.LC) + + return h, f.quo(h), g.quo(h) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/monomials.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/monomials.py new file mode 100644 index 0000000000000000000000000000000000000000..43a17223861f656b8a4a51fb4c0c934635ed4623 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/monomials.py @@ -0,0 +1,628 @@ +"""Tools and arithmetics for monomials of distributed polynomials. """ + + +from itertools import combinations_with_replacement, product +from textwrap import dedent + +from sympy.core.cache import cacheit +from sympy.core import Mul, S, Tuple, sympify +from sympy.polys.polyerrors import ExactQuotientFailed +from sympy.polys.polyutils import PicklableWithSlots, dict_from_expr +from sympy.utilities import public +from sympy.utilities.iterables import is_sequence, iterable + +@public +def itermonomials(variables, max_degrees, min_degrees=None): + r""" + ``max_degrees`` and ``min_degrees`` are either both integers or both lists. + Unless otherwise specified, ``min_degrees`` is either ``0`` or + ``[0, ..., 0]``. + + A generator of all monomials ``monom`` is returned, such that + either + ``min_degree <= total_degree(monom) <= max_degree``, + or + ``min_degrees[i] <= degree_list(monom)[i] <= max_degrees[i]``, + for all ``i``. + + Case I. ``max_degrees`` and ``min_degrees`` are both integers + ============================================================= + + Given a set of variables $V$ and a min_degree $N$ and a max_degree $M$ + generate a set of monomials of degree less than or equal to $N$ and greater + than or equal to $M$. The total number of monomials in commutative + variables is huge and is given by the following formula if $M = 0$: + + .. math:: + \frac{(\#V + N)!}{\#V! N!} + + For example if we would like to generate a dense polynomial of + a total degree $N = 50$ and $M = 0$, which is the worst case, in 5 + variables, assuming that exponents and all of coefficients are 32-bit long + and stored in an array we would need almost 80 GiB of memory! Fortunately + most polynomials, that we will encounter, are sparse. + + Consider monomials in commutative variables $x$ and $y$ + and non-commutative variables $a$ and $b$:: + + >>> from sympy import symbols + >>> from sympy.polys.monomials import itermonomials + >>> from sympy.polys.orderings import monomial_key + >>> from sympy.abc import x, y + + >>> sorted(itermonomials([x, y], 2), key=monomial_key('grlex', [y, x])) + [1, x, y, x**2, x*y, y**2] + + >>> sorted(itermonomials([x, y], 3), key=monomial_key('grlex', [y, x])) + [1, x, y, x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3] + + >>> a, b = symbols('a, b', commutative=False) + >>> set(itermonomials([a, b, x], 2)) + {1, a, a**2, b, b**2, x, x**2, a*b, b*a, x*a, x*b} + + >>> sorted(itermonomials([x, y], 2, 1), key=monomial_key('grlex', [y, x])) + [x, y, x**2, x*y, y**2] + + Case II. ``max_degrees`` and ``min_degrees`` are both lists + =========================================================== + + If ``max_degrees = [d_1, ..., d_n]`` and + ``min_degrees = [e_1, ..., e_n]``, the number of monomials generated + is: + + .. math:: + (d_1 - e_1 + 1) (d_2 - e_2 + 1) \cdots (d_n - e_n + 1) + + Let us generate all monomials ``monom`` in variables $x$ and $y$ + such that ``[1, 2][i] <= degree_list(monom)[i] <= [2, 4][i]``, + ``i = 0, 1`` :: + + >>> from sympy import symbols + >>> from sympy.polys.monomials import itermonomials + >>> from sympy.polys.orderings import monomial_key + >>> from sympy.abc import x, y + + >>> sorted(itermonomials([x, y], [2, 4], [1, 2]), reverse=True, key=monomial_key('lex', [x, y])) + [x**2*y**4, x**2*y**3, x**2*y**2, x*y**4, x*y**3, x*y**2] + """ + if is_sequence(max_degrees): + n = len(variables) + if len(max_degrees) != n: + raise ValueError('Argument sizes do not match') + if min_degrees is None: + min_degrees = [0]*n + elif not is_sequence(min_degrees): + raise ValueError('min_degrees is not a list') + else: + if len(min_degrees) != n: + raise ValueError('Argument sizes do not match') + if any(i < 0 for i in min_degrees): + raise ValueError("min_degrees cannot contain negative numbers") + if any(min_degrees[i] > max_degrees[i] for i in range(n)): + raise ValueError('min_degrees[i] must be <= max_degrees[i] for all i') + power_lists = [] + for var, min_d, max_d in zip(variables, min_degrees, max_degrees): + power_lists.append([var**i for i in range(min_d, max_d + 1)]) + for powers in product(*power_lists): + yield Mul(*powers) + else: + max_degree = max_degrees + if max_degree < 0: + raise ValueError("max_degrees cannot be negative") + if min_degrees is None: + min_degree = 0 + else: + if min_degrees < 0: + raise ValueError("min_degrees cannot be negative") + min_degree = min_degrees + if min_degree > max_degree: + return + if not variables or max_degree == 0: + yield S.One + return + # Force to list in case of passed tuple or other incompatible collection + variables = list(variables) + [S.One] + if all(variable.is_commutative for variable in variables): + it = combinations_with_replacement(variables, max_degree) + else: + it = product(variables, repeat=max_degree) + monomials_set = set() + d = max_degree - min_degree + for item in it: + count = 0 + for variable in item: + if variable == 1: + count += 1 + if d < count: + break + else: + monomials_set.add(Mul(*item)) + yield from monomials_set + +def monomial_count(V, N): + r""" + Computes the number of monomials. + + The number of monomials is given by the following formula: + + .. math:: + + \frac{(\#V + N)!}{\#V! N!} + + where `N` is a total degree and `V` is a set of variables. + + Examples + ======== + + >>> from sympy.polys.monomials import itermonomials, monomial_count + >>> from sympy.polys.orderings import monomial_key + >>> from sympy.abc import x, y + + >>> monomial_count(2, 2) + 6 + + >>> M = list(itermonomials([x, y], 2)) + + >>> sorted(M, key=monomial_key('grlex', [y, x])) + [1, x, y, x**2, x*y, y**2] + >>> len(M) + 6 + + """ + from sympy.functions.combinatorial.factorials import factorial + return factorial(V + N) / factorial(V) / factorial(N) + +def monomial_mul(A, B): + """ + Multiplication of tuples representing monomials. + + Examples + ======== + + Lets multiply `x**3*y**4*z` with `x*y**2`:: + + >>> from sympy.polys.monomials import monomial_mul + + >>> monomial_mul((3, 4, 1), (1, 2, 0)) + (4, 6, 1) + + which gives `x**4*y**5*z`. + + """ + return tuple([ a + b for a, b in zip(A, B) ]) + +def monomial_div(A, B): + """ + Division of tuples representing monomials. + + Examples + ======== + + Lets divide `x**3*y**4*z` by `x*y**2`:: + + >>> from sympy.polys.monomials import monomial_div + + >>> monomial_div((3, 4, 1), (1, 2, 0)) + (2, 2, 1) + + which gives `x**2*y**2*z`. However:: + + >>> monomial_div((3, 4, 1), (1, 2, 2)) is None + True + + `x*y**2*z**2` does not divide `x**3*y**4*z`. + + """ + C = monomial_ldiv(A, B) + + if all(c >= 0 for c in C): + return tuple(C) + else: + return None + +def monomial_ldiv(A, B): + """ + Division of tuples representing monomials. + + Examples + ======== + + Lets divide `x**3*y**4*z` by `x*y**2`:: + + >>> from sympy.polys.monomials import monomial_ldiv + + >>> monomial_ldiv((3, 4, 1), (1, 2, 0)) + (2, 2, 1) + + which gives `x**2*y**2*z`. + + >>> monomial_ldiv((3, 4, 1), (1, 2, 2)) + (2, 2, -1) + + which gives `x**2*y**2*z**-1`. + + """ + return tuple([ a - b for a, b in zip(A, B) ]) + +def monomial_pow(A, n): + """Return the n-th pow of the monomial. """ + return tuple([ a*n for a in A ]) + +def monomial_gcd(A, B): + """ + Greatest common divisor of tuples representing monomials. + + Examples + ======== + + Lets compute GCD of `x*y**4*z` and `x**3*y**2`:: + + >>> from sympy.polys.monomials import monomial_gcd + + >>> monomial_gcd((1, 4, 1), (3, 2, 0)) + (1, 2, 0) + + which gives `x*y**2`. + + """ + return tuple([ min(a, b) for a, b in zip(A, B) ]) + +def monomial_lcm(A, B): + """ + Least common multiple of tuples representing monomials. + + Examples + ======== + + Lets compute LCM of `x*y**4*z` and `x**3*y**2`:: + + >>> from sympy.polys.monomials import monomial_lcm + + >>> monomial_lcm((1, 4, 1), (3, 2, 0)) + (3, 4, 1) + + which gives `x**3*y**4*z`. + + """ + return tuple([ max(a, b) for a, b in zip(A, B) ]) + +def monomial_divides(A, B): + """ + Does there exist a monomial X such that XA == B? + + Examples + ======== + + >>> from sympy.polys.monomials import monomial_divides + >>> monomial_divides((1, 2), (3, 4)) + True + >>> monomial_divides((1, 2), (0, 2)) + False + """ + return all(a <= b for a, b in zip(A, B)) + +def monomial_max(*monoms): + """ + Returns maximal degree for each variable in a set of monomials. + + Examples + ======== + + Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`. + We wish to find out what is the maximal degree for each of `x`, `y` + and `z` variables:: + + >>> from sympy.polys.monomials import monomial_max + + >>> monomial_max((3,4,5), (0,5,1), (6,3,9)) + (6, 5, 9) + + """ + M = list(monoms[0]) + + for N in monoms[1:]: + for i, n in enumerate(N): + M[i] = max(M[i], n) + + return tuple(M) + +def monomial_min(*monoms): + """ + Returns minimal degree for each variable in a set of monomials. + + Examples + ======== + + Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`. + We wish to find out what is the minimal degree for each of `x`, `y` + and `z` variables:: + + >>> from sympy.polys.monomials import monomial_min + + >>> monomial_min((3,4,5), (0,5,1), (6,3,9)) + (0, 3, 1) + + """ + M = list(monoms[0]) + + for N in monoms[1:]: + for i, n in enumerate(N): + M[i] = min(M[i], n) + + return tuple(M) + +def monomial_deg(M): + """ + Returns the total degree of a monomial. + + Examples + ======== + + The total degree of `xy^2` is 3: + + >>> from sympy.polys.monomials import monomial_deg + >>> monomial_deg((1, 2)) + 3 + """ + return sum(M) + +def term_div(a, b, domain): + """Division of two terms in over a ring/field. """ + a_lm, a_lc = a + b_lm, b_lc = b + + monom = monomial_div(a_lm, b_lm) + + if domain.is_Field: + if monom is not None: + return monom, domain.quo(a_lc, b_lc) + else: + return None + else: + if not (monom is None or a_lc % b_lc): + return monom, domain.quo(a_lc, b_lc) + else: + return None + +class MonomialOps: + """Code generator of fast monomial arithmetic functions. """ + + @cacheit + def __new__(cls, ngens): + obj = super().__new__(cls) + obj.ngens = ngens + return obj + + def __getnewargs__(self): + return (self.ngens,) + + def _build(self, code, name): + ns = {} + exec(code, ns) + return ns[name] + + def _vars(self, name): + return [ "%s%s" % (name, i) for i in range(self.ngens) ] + + @cacheit + def mul(self): + name = "monomial_mul" + template = dedent("""\ + def %(name)s(A, B): + (%(A)s,) = A + (%(B)s,) = B + return (%(AB)s,) + """) + A = self._vars("a") + B = self._vars("b") + AB = [ "%s + %s" % (a, b) for a, b in zip(A, B) ] + code = template % {"name": name, "A": ", ".join(A), "B": ", ".join(B), "AB": ", ".join(AB)} + return self._build(code, name) + + @cacheit + def pow(self): + name = "monomial_pow" + template = dedent("""\ + def %(name)s(A, k): + (%(A)s,) = A + return (%(Ak)s,) + """) + A = self._vars("a") + Ak = [ "%s*k" % a for a in A ] + code = template % {"name": name, "A": ", ".join(A), "Ak": ", ".join(Ak)} + return self._build(code, name) + + @cacheit + def mulpow(self): + name = "monomial_mulpow" + template = dedent("""\ + def %(name)s(A, B, k): + (%(A)s,) = A + (%(B)s,) = B + return (%(ABk)s,) + """) + A = self._vars("a") + B = self._vars("b") + ABk = [ "%s + %s*k" % (a, b) for a, b in zip(A, B) ] + code = template % {"name": name, "A": ", ".join(A), "B": ", ".join(B), "ABk": ", ".join(ABk)} + return self._build(code, name) + + @cacheit + def ldiv(self): + name = "monomial_ldiv" + template = dedent("""\ + def %(name)s(A, B): + (%(A)s,) = A + (%(B)s,) = B + return (%(AB)s,) + """) + A = self._vars("a") + B = self._vars("b") + AB = [ "%s - %s" % (a, b) for a, b in zip(A, B) ] + code = template % {"name": name, "A": ", ".join(A), "B": ", ".join(B), "AB": ", ".join(AB)} + return self._build(code, name) + + @cacheit + def div(self): + name = "monomial_div" + template = dedent("""\ + def %(name)s(A, B): + (%(A)s,) = A + (%(B)s,) = B + %(RAB)s + return (%(R)s,) + """) + A = self._vars("a") + B = self._vars("b") + RAB = [ "r%(i)s = a%(i)s - b%(i)s\n if r%(i)s < 0: return None" % {"i": i} for i in range(self.ngens) ] + R = self._vars("r") + code = template % {"name": name, "A": ", ".join(A), "B": ", ".join(B), "RAB": "\n ".join(RAB), "R": ", ".join(R)} + return self._build(code, name) + + @cacheit + def lcm(self): + name = "monomial_lcm" + template = dedent("""\ + def %(name)s(A, B): + (%(A)s,) = A + (%(B)s,) = B + return (%(AB)s,) + """) + A = self._vars("a") + B = self._vars("b") + AB = [ "%s if %s >= %s else %s" % (a, a, b, b) for a, b in zip(A, B) ] + code = template % {"name": name, "A": ", ".join(A), "B": ", ".join(B), "AB": ", ".join(AB)} + return self._build(code, name) + + @cacheit + def gcd(self): + name = "monomial_gcd" + template = dedent("""\ + def %(name)s(A, B): + (%(A)s,) = A + (%(B)s,) = B + return (%(AB)s,) + """) + A = self._vars("a") + B = self._vars("b") + AB = [ "%s if %s <= %s else %s" % (a, a, b, b) for a, b in zip(A, B) ] + code = template % {"name": name, "A": ", ".join(A), "B": ", ".join(B), "AB": ", ".join(AB)} + return self._build(code, name) + +@public +class Monomial(PicklableWithSlots): + """Class representing a monomial, i.e. a product of powers. """ + + __slots__ = ('exponents', 'gens') + + def __init__(self, monom, gens=None): + if not iterable(monom): + rep, gens = dict_from_expr(sympify(monom), gens=gens) + if len(rep) == 1 and list(rep.values())[0] == 1: + monom = list(rep.keys())[0] + else: + raise ValueError("Expected a monomial got {}".format(monom)) + + self.exponents = tuple(map(int, monom)) + self.gens = gens + + def rebuild(self, exponents, gens=None): + return self.__class__(exponents, gens or self.gens) + + def __len__(self): + return len(self.exponents) + + def __iter__(self): + return iter(self.exponents) + + def __getitem__(self, item): + return self.exponents[item] + + def __hash__(self): + return hash((self.__class__.__name__, self.exponents, self.gens)) + + def __str__(self): + if self.gens: + return "*".join([ "%s**%s" % (gen, exp) for gen, exp in zip(self.gens, self.exponents) ]) + else: + return "%s(%s)" % (self.__class__.__name__, self.exponents) + + def as_expr(self, *gens): + """Convert a monomial instance to a SymPy expression. """ + gens = gens or self.gens + + if not gens: + raise ValueError( + "Cannot convert %s to an expression without generators" % self) + + return Mul(*[ gen**exp for gen, exp in zip(gens, self.exponents) ]) + + def __eq__(self, other): + if isinstance(other, Monomial): + exponents = other.exponents + elif isinstance(other, (tuple, Tuple)): + exponents = other + else: + return False + + return self.exponents == exponents + + def __ne__(self, other): + return not self == other + + def __mul__(self, other): + if isinstance(other, Monomial): + exponents = other.exponents + elif isinstance(other, (tuple, Tuple)): + exponents = other + else: + raise NotImplementedError + + return self.rebuild(monomial_mul(self.exponents, exponents)) + + def __truediv__(self, other): + if isinstance(other, Monomial): + exponents = other.exponents + elif isinstance(other, (tuple, Tuple)): + exponents = other + else: + raise NotImplementedError + + result = monomial_div(self.exponents, exponents) + + if result is not None: + return self.rebuild(result) + else: + raise ExactQuotientFailed(self, Monomial(other)) + + __floordiv__ = __truediv__ + + def __pow__(self, other): + n = int(other) + if n < 0: + raise ValueError("a non-negative integer expected, got %s" % other) + return self.rebuild(monomial_pow(self.exponents, n)) + + def gcd(self, other): + """Greatest common divisor of monomials. """ + if isinstance(other, Monomial): + exponents = other.exponents + elif isinstance(other, (tuple, Tuple)): + exponents = other + else: + raise TypeError( + "an instance of Monomial class expected, got %s" % other) + + return self.rebuild(monomial_gcd(self.exponents, exponents)) + + def lcm(self, other): + """Least common multiple of monomials. """ + if isinstance(other, Monomial): + exponents = other.exponents + elif isinstance(other, (tuple, Tuple)): + exponents = other + else: + raise TypeError( + "an instance of Monomial class expected, got %s" % other) + + return self.rebuild(monomial_lcm(self.exponents, exponents)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/multivariate_resultants.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/multivariate_resultants.py new file mode 100644 index 0000000000000000000000000000000000000000..b6c967a8b981e25e8e26745804a658ff7b90e9af --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/multivariate_resultants.py @@ -0,0 +1,473 @@ +""" +This module contains functions for two multivariate resultants. These +are: + +- Dixon's resultant. +- Macaulay's resultant. + +Multivariate resultants are used to identify whether a multivariate +system has common roots. That is when the resultant is equal to zero. +""" +from math import prod + +from sympy.core.mul import Mul +from sympy.matrices.dense import (Matrix, diag) +from sympy.polys.polytools import (Poly, degree_list, rem) +from sympy.simplify.simplify import simplify +from sympy.tensor.indexed import IndexedBase +from sympy.polys.monomials import itermonomials, monomial_deg +from sympy.polys.orderings import monomial_key +from sympy.polys.polytools import poly_from_expr, total_degree +from sympy.functions.combinatorial.factorials import binomial +from itertools import combinations_with_replacement +from sympy.utilities.exceptions import sympy_deprecation_warning + +class DixonResultant(): + """ + A class for retrieving the Dixon's resultant of a multivariate + system. + + Examples + ======== + + >>> from sympy import symbols + + >>> from sympy.polys.multivariate_resultants import DixonResultant + >>> x, y = symbols('x, y') + + >>> p = x + y + >>> q = x ** 2 + y ** 3 + >>> h = x ** 2 + y + + >>> dixon = DixonResultant(variables=[x, y], polynomials=[p, q, h]) + >>> poly = dixon.get_dixon_polynomial() + >>> matrix = dixon.get_dixon_matrix(polynomial=poly) + >>> matrix + Matrix([ + [ 0, 0, -1, 0, -1], + [ 0, -1, 0, -1, 0], + [-1, 0, 1, 0, 0], + [ 0, -1, 0, 0, 1], + [-1, 0, 0, 1, 0]]) + >>> matrix.det() + 0 + + See Also + ======== + + Notebook in examples: sympy/example/notebooks. + + References + ========== + + .. [1] [Kapur1994]_ + .. [2] [Palancz08]_ + + """ + + def __init__(self, polynomials, variables): + """ + A class that takes two lists, a list of polynomials and list of + variables. Returns the Dixon matrix of the multivariate system. + + Parameters + ---------- + polynomials : list of polynomials + A list of m n-degree polynomials + variables: list + A list of all n variables + """ + self.polynomials = polynomials + self.variables = variables + + self.n = len(self.variables) + self.m = len(self.polynomials) + + a = IndexedBase("alpha") + # A list of n alpha variables (the replacing variables) + self.dummy_variables = [a[i] for i in range(self.n)] + + # A list of the d_max of each variable. + self._max_degrees = [max(degree_list(poly)[i] for poly in self.polynomials) + for i in range(self.n)] + + @property + def max_degrees(self): + sympy_deprecation_warning( + """ + The max_degrees property of DixonResultant is deprecated. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-dixonresultant-properties", + ) + return self._max_degrees + + def get_dixon_polynomial(self): + r""" + Returns + ======= + + dixon_polynomial: polynomial + Dixon's polynomial is calculated as: + + delta = Delta(A) / ((x_1 - a_1) ... (x_n - a_n)) where, + + A = |p_1(x_1,... x_n), ..., p_n(x_1,... x_n)| + |p_1(a_1,... x_n), ..., p_n(a_1,... x_n)| + |... , ..., ...| + |p_1(a_1,... a_n), ..., p_n(a_1,... a_n)| + """ + if self.m != (self.n + 1): + raise ValueError('Method invalid for given combination.') + + # First row + rows = [self.polynomials] + + temp = list(self.variables) + + for idx in range(self.n): + temp[idx] = self.dummy_variables[idx] + substitution = dict(zip(self.variables, temp)) + rows.append([f.subs(substitution) for f in self.polynomials]) + + A = Matrix(rows) + + terms = zip(self.variables, self.dummy_variables) + product_of_differences = Mul(*[a - b for a, b in terms]) + dixon_polynomial = (A.det() / product_of_differences).factor() + + return poly_from_expr(dixon_polynomial, self.dummy_variables)[0] + + def get_upper_degree(self): + sympy_deprecation_warning( + """ + The get_upper_degree() method of DixonResultant is deprecated. Use + get_max_degrees() instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-dixonresultant-properties" + ) + list_of_products = [self.variables[i] ** self._max_degrees[i] + for i in range(self.n)] + product = prod(list_of_products) + product = Poly(product).monoms() + + return monomial_deg(*product) + + def get_max_degrees(self, polynomial): + r""" + Returns a list of the maximum degree of each variable appearing + in the coefficients of the Dixon polynomial. The coefficients are + viewed as polys in $x_1, x_2, \dots, x_n$. + """ + deg_lists = [degree_list(Poly(poly, self.variables)) + for poly in polynomial.coeffs()] + + max_degrees = [max(degs) for degs in zip(*deg_lists)] + + return max_degrees + + def get_dixon_matrix(self, polynomial): + r""" + Construct the Dixon matrix from the coefficients of polynomial + \alpha. Each coefficient is viewed as a polynomial of x_1, ..., + x_n. + """ + + max_degrees = self.get_max_degrees(polynomial) + + # list of column headers of the Dixon matrix. + monomials = itermonomials(self.variables, max_degrees) + monomials = sorted(monomials, reverse=True, + key=monomial_key('lex', self.variables)) + + dixon_matrix = Matrix([[Poly(c, *self.variables).coeff_monomial(m) + for m in monomials] + for c in polynomial.coeffs()]) + + # remove columns if needed + if dixon_matrix.shape[0] != dixon_matrix.shape[1]: + keep = [column for column in range(dixon_matrix.shape[-1]) + if any(element != 0 for element + in dixon_matrix[:, column])] + + dixon_matrix = dixon_matrix[:, keep] + + return dixon_matrix + + def KSY_precondition(self, matrix): + """ + Test for the validity of the Kapur-Saxena-Yang precondition. + + The precondition requires that the column corresponding to the + monomial 1 = x_1 ^ 0 * x_2 ^ 0 * ... * x_n ^ 0 is not a linear + combination of the remaining ones. In SymPy notation this is + the last column. For the precondition to hold the last non-zero + row of the rref matrix should be of the form [0, 0, ..., 1]. + """ + if matrix.is_zero_matrix: + return False + + m, n = matrix.shape + + # simplify the matrix and keep only its non-zero rows + matrix = simplify(matrix.rref()[0]) + rows = [i for i in range(m) if any(matrix[i, j] != 0 for j in range(n))] + matrix = matrix[rows,:] + + condition = Matrix([[0]*(n-1) + [1]]) + + if matrix[-1,:] == condition: + return True + else: + return False + + def delete_zero_rows_and_columns(self, matrix): + """Remove the zero rows and columns of the matrix.""" + rows = [ + i for i in range(matrix.rows) if not matrix.row(i).is_zero_matrix] + cols = [ + j for j in range(matrix.cols) if not matrix.col(j).is_zero_matrix] + + return matrix[rows, cols] + + def product_leading_entries(self, matrix): + """Calculate the product of the leading entries of the matrix.""" + res = 1 + for row in range(matrix.rows): + for el in matrix.row(row): + if el != 0: + res = res * el + break + return res + + def get_KSY_Dixon_resultant(self, matrix): + """Calculate the Kapur-Saxena-Yang approach to the Dixon Resultant.""" + matrix = self.delete_zero_rows_and_columns(matrix) + _, U, _ = matrix.LUdecomposition() + matrix = self.delete_zero_rows_and_columns(simplify(U)) + + return self.product_leading_entries(matrix) + +class MacaulayResultant(): + """ + A class for calculating the Macaulay resultant. Note that the + polynomials must be homogenized and their coefficients must be + given as symbols. + + Examples + ======== + + >>> from sympy import symbols + + >>> from sympy.polys.multivariate_resultants import MacaulayResultant + >>> x, y, z = symbols('x, y, z') + + >>> a_0, a_1, a_2 = symbols('a_0, a_1, a_2') + >>> b_0, b_1, b_2 = symbols('b_0, b_1, b_2') + >>> c_0, c_1, c_2,c_3, c_4 = symbols('c_0, c_1, c_2, c_3, c_4') + + >>> f = a_0 * y - a_1 * x + a_2 * z + >>> g = b_1 * x ** 2 + b_0 * y ** 2 - b_2 * z ** 2 + >>> h = c_0 * y * z ** 2 - c_1 * x ** 3 + c_2 * x ** 2 * z - c_3 * x * z ** 2 + c_4 * z ** 3 + + >>> mac = MacaulayResultant(polynomials=[f, g, h], variables=[x, y, z]) + >>> mac.monomial_set + [x**4, x**3*y, x**3*z, x**2*y**2, x**2*y*z, x**2*z**2, x*y**3, + x*y**2*z, x*y*z**2, x*z**3, y**4, y**3*z, y**2*z**2, y*z**3, z**4] + >>> matrix = mac.get_matrix() + >>> submatrix = mac.get_submatrix(matrix) + >>> submatrix + Matrix([ + [-a_1, a_0, a_2, 0], + [ 0, -a_1, 0, 0], + [ 0, 0, -a_1, 0], + [ 0, 0, 0, -a_1]]) + + See Also + ======== + + Notebook in examples: sympy/example/notebooks. + + References + ========== + + .. [1] [Bruce97]_ + .. [2] [Stiller96]_ + + """ + def __init__(self, polynomials, variables): + """ + Parameters + ========== + + variables: list + A list of all n variables + polynomials : list of SymPy polynomials + A list of m n-degree polynomials + """ + self.polynomials = polynomials + self.variables = variables + self.n = len(variables) + + # A list of the d_max of each polynomial. + self.degrees = [total_degree(poly, *self.variables) for poly + in self.polynomials] + + self.degree_m = self._get_degree_m() + self.monomials_size = self.get_size() + + # The set T of all possible monomials of degree degree_m + self.monomial_set = self.get_monomials_of_certain_degree(self.degree_m) + + def _get_degree_m(self): + r""" + Returns + ======= + + degree_m: int + The degree_m is calculated as 1 + \sum_1 ^ n (d_i - 1), + where d_i is the degree of the i polynomial + """ + return 1 + sum(d - 1 for d in self.degrees) + + def get_size(self): + r""" + Returns + ======= + + size: int + The size of set T. Set T is the set of all possible + monomials of the n variables for degree equal to the + degree_m + """ + return binomial(self.degree_m + self.n - 1, self.n - 1) + + def get_monomials_of_certain_degree(self, degree): + """ + Returns + ======= + + monomials: list + A list of monomials of a certain degree. + """ + monomials = [Mul(*monomial) for monomial + in combinations_with_replacement(self.variables, + degree)] + + return sorted(monomials, reverse=True, + key=monomial_key('lex', self.variables)) + + def get_row_coefficients(self): + """ + Returns + ======= + + row_coefficients: list + The row coefficients of Macaulay's matrix + """ + row_coefficients = [] + divisible = [] + for i in range(self.n): + if i == 0: + degree = self.degree_m - self.degrees[i] + monomial = self.get_monomials_of_certain_degree(degree) + row_coefficients.append(monomial) + else: + divisible.append(self.variables[i - 1] ** + self.degrees[i - 1]) + degree = self.degree_m - self.degrees[i] + poss_rows = self.get_monomials_of_certain_degree(degree) + for div in divisible: + for p in poss_rows: + if rem(p, div) == 0: + poss_rows = [item for item in poss_rows + if item != p] + row_coefficients.append(poss_rows) + return row_coefficients + + def get_matrix(self): + """ + Returns + ======= + + macaulay_matrix: Matrix + The Macaulay numerator matrix + """ + rows = [] + row_coefficients = self.get_row_coefficients() + for i in range(self.n): + for multiplier in row_coefficients[i]: + coefficients = [] + poly = Poly(self.polynomials[i] * multiplier, + *self.variables) + + for mono in self.monomial_set: + coefficients.append(poly.coeff_monomial(mono)) + rows.append(coefficients) + + macaulay_matrix = Matrix(rows) + return macaulay_matrix + + def get_reduced_nonreduced(self): + r""" + Returns + ======= + + reduced: list + A list of the reduced monomials + non_reduced: list + A list of the monomials that are not reduced + + Definition + ========== + + A polynomial is said to be reduced in x_i, if its degree (the + maximum degree of its monomials) in x_i is less than d_i. A + polynomial that is reduced in all variables but one is said + simply to be reduced. + """ + divisible = [] + for m in self.monomial_set: + temp = [] + for i, v in enumerate(self.variables): + temp.append(bool(total_degree(m, v) >= self.degrees[i])) + divisible.append(temp) + reduced = [i for i, r in enumerate(divisible) + if sum(r) < self.n - 1] + non_reduced = [i for i, r in enumerate(divisible) + if sum(r) >= self.n -1] + + return reduced, non_reduced + + def get_submatrix(self, matrix): + r""" + Returns + ======= + + macaulay_submatrix: Matrix + The Macaulay denominator matrix. Columns that are non reduced are kept. + The row which contains one of the a_{i}s is dropped. a_{i}s + are the coefficients of x_i ^ {d_i}. + """ + reduced, non_reduced = self.get_reduced_nonreduced() + + # if reduced == [], then det(matrix) should be 1 + if reduced == []: + return diag([1]) + + # reduced != [] + reduction_set = [v ** self.degrees[i] for i, v + in enumerate(self.variables)] + + ais = [self.polynomials[i].coeff(reduction_set[i]) + for i in range(self.n)] + + reduced_matrix = matrix[:, reduced] + keep = [] + for row in range(reduced_matrix.rows): + check = [ai in reduced_matrix[row, :] for ai in ais] + if True not in check: + keep.append(row) + + return matrix[keep, non_reduced] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/orderings.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/orderings.py new file mode 100644 index 0000000000000000000000000000000000000000..b6ed575d5103440e1e8ebda4c53c4149d3badf11 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/orderings.py @@ -0,0 +1,286 @@ +"""Definitions of monomial orderings. """ + +from __future__ import annotations + +__all__ = ["lex", "grlex", "grevlex", "ilex", "igrlex", "igrevlex"] + +from sympy.core import Symbol +from sympy.utilities.iterables import iterable + +class MonomialOrder: + """Base class for monomial orderings. """ + + alias: str | None = None + is_global: bool | None = None + is_default = False + + def __repr__(self): + return self.__class__.__name__ + "()" + + def __str__(self): + return self.alias + + def __call__(self, monomial): + raise NotImplementedError + + def __eq__(self, other): + return self.__class__ == other.__class__ + + def __hash__(self): + return hash(self.__class__) + + def __ne__(self, other): + return not (self == other) + +class LexOrder(MonomialOrder): + """Lexicographic order of monomials. """ + + alias = 'lex' + is_global = True + is_default = True + + def __call__(self, monomial): + return monomial + +class GradedLexOrder(MonomialOrder): + """Graded lexicographic order of monomials. """ + + alias = 'grlex' + is_global = True + + def __call__(self, monomial): + return (sum(monomial), monomial) + +class ReversedGradedLexOrder(MonomialOrder): + """Reversed graded lexicographic order of monomials. """ + + alias = 'grevlex' + is_global = True + + def __call__(self, monomial): + return (sum(monomial), tuple(reversed([-m for m in monomial]))) + +class ProductOrder(MonomialOrder): + """ + A product order built from other monomial orders. + + Given (not necessarily total) orders O1, O2, ..., On, their product order + P is defined as M1 > M2 iff there exists i such that O1(M1) = O2(M2), + ..., Oi(M1) = Oi(M2), O{i+1}(M1) > O{i+1}(M2). + + Product orders are typically built from monomial orders on different sets + of variables. + + ProductOrder is constructed by passing a list of pairs + [(O1, L1), (O2, L2), ...] where Oi are MonomialOrders and Li are callables. + Upon comparison, the Li are passed the total monomial, and should filter + out the part of the monomial to pass to Oi. + + Examples + ======== + + We can use a lexicographic order on x_1, x_2 and also on + y_1, y_2, y_3, and their product on {x_i, y_i} as follows: + + >>> from sympy.polys.orderings import lex, grlex, ProductOrder + >>> P = ProductOrder( + ... (lex, lambda m: m[:2]), # lex order on x_1 and x_2 of monomial + ... (grlex, lambda m: m[2:]) # grlex on y_1, y_2, y_3 + ... ) + >>> P((2, 1, 1, 0, 0)) > P((1, 10, 0, 2, 0)) + True + + Here the exponent `2` of `x_1` in the first monomial + (`x_1^2 x_2 y_1`) is bigger than the exponent `1` of `x_1` in the + second monomial (`x_1 x_2^10 y_2^2`), so the first monomial is greater + in the product ordering. + + >>> P((2, 1, 1, 0, 0)) < P((2, 1, 0, 2, 0)) + True + + Here the exponents of `x_1` and `x_2` agree, so the grlex order on + `y_1, y_2, y_3` is used to decide the ordering. In this case the monomial + `y_2^2` is ordered larger than `y_1`, since for the grlex order the degree + of the monomial is most important. + """ + + def __init__(self, *args): + self.args = args + + def __call__(self, monomial): + return tuple(O(lamda(monomial)) for (O, lamda) in self.args) + + def __repr__(self): + contents = [repr(x[0]) for x in self.args] + return self.__class__.__name__ + '(' + ", ".join(contents) + ')' + + def __str__(self): + contents = [str(x[0]) for x in self.args] + return self.__class__.__name__ + '(' + ", ".join(contents) + ')' + + def __eq__(self, other): + if not isinstance(other, ProductOrder): + return False + return self.args == other.args + + def __hash__(self): + return hash((self.__class__, self.args)) + + @property + def is_global(self): + if all(o.is_global is True for o, _ in self.args): + return True + if all(o.is_global is False for o, _ in self.args): + return False + return None + +class InverseOrder(MonomialOrder): + """ + The "inverse" of another monomial order. + + If O is any monomial order, we can construct another monomial order iO + such that `A >_{iO} B` if and only if `B >_O A`. This is useful for + constructing local orders. + + Note that many algorithms only work with *global* orders. + + For example, in the inverse lexicographic order on a single variable `x`, + high powers of `x` count as small: + + >>> from sympy.polys.orderings import lex, InverseOrder + >>> ilex = InverseOrder(lex) + >>> ilex((5,)) < ilex((0,)) + True + """ + + def __init__(self, O): + self.O = O + + def __str__(self): + return "i" + str(self.O) + + def __call__(self, monomial): + def inv(l): + if iterable(l): + return tuple(inv(x) for x in l) + return -l + return inv(self.O(monomial)) + + @property + def is_global(self): + if self.O.is_global is True: + return False + if self.O.is_global is False: + return True + return None + + def __eq__(self, other): + return isinstance(other, InverseOrder) and other.O == self.O + + def __hash__(self): + return hash((self.__class__, self.O)) + +lex = LexOrder() +grlex = GradedLexOrder() +grevlex = ReversedGradedLexOrder() +ilex = InverseOrder(lex) +igrlex = InverseOrder(grlex) +igrevlex = InverseOrder(grevlex) + +_monomial_key = { + 'lex': lex, + 'grlex': grlex, + 'grevlex': grevlex, + 'ilex': ilex, + 'igrlex': igrlex, + 'igrevlex': igrevlex +} + +def monomial_key(order=None, gens=None): + """ + Return a function defining admissible order on monomials. + + The result of a call to :func:`monomial_key` is a function which should + be used as a key to :func:`sorted` built-in function, to provide order + in a set of monomials of the same length. + + Currently supported monomial orderings are: + + 1. lex - lexicographic order (default) + 2. grlex - graded lexicographic order + 3. grevlex - reversed graded lexicographic order + 4. ilex, igrlex, igrevlex - the corresponding inverse orders + + If the ``order`` input argument is not a string but has ``__call__`` + attribute, then it will pass through with an assumption that the + callable object defines an admissible order on monomials. + + If the ``gens`` input argument contains a list of generators, the + resulting key function can be used to sort SymPy ``Expr`` objects. + + """ + if order is None: + order = lex + + if isinstance(order, Symbol): + order = str(order) + + if isinstance(order, str): + try: + order = _monomial_key[order] + except KeyError: + raise ValueError("supported monomial orderings are 'lex', 'grlex' and 'grevlex', got %r" % order) + if hasattr(order, '__call__'): + if gens is not None: + def _order(expr): + return order(expr.as_poly(*gens).degree_list()) + return _order + return order + else: + raise ValueError("monomial ordering specification must be a string or a callable, got %s" % order) + +class _ItemGetter: + """Helper class to return a subsequence of values.""" + + def __init__(self, seq): + self.seq = tuple(seq) + + def __call__(self, m): + return tuple(m[idx] for idx in self.seq) + + def __eq__(self, other): + if not isinstance(other, _ItemGetter): + return False + return self.seq == other.seq + +def build_product_order(arg, gens): + """ + Build a monomial order on ``gens``. + + ``arg`` should be a tuple of iterables. The first element of each iterable + should be a string or monomial order (will be passed to monomial_key), + the others should be subsets of the generators. This function will build + the corresponding product order. + + For example, build a product of two grlex orders: + + >>> from sympy.polys.orderings import build_product_order + >>> from sympy.abc import x, y, z, t + + >>> O = build_product_order((("grlex", x, y), ("grlex", z, t)), [x, y, z, t]) + >>> O((1, 2, 3, 4)) + ((3, (1, 2)), (7, (3, 4))) + + """ + gens2idx = {} + for i, g in enumerate(gens): + gens2idx[g] = i + order = [] + for expr in arg: + name = expr[0] + var = expr[1:] + + def makelambda(var): + return _ItemGetter(gens2idx[g] for g in var) + order.append((monomial_key(name), makelambda(var))) + return ProductOrder(*order) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/orthopolys.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/orthopolys.py new file mode 100644 index 0000000000000000000000000000000000000000..ee82457703a2be172951ee38e3cd67f221a438a0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/orthopolys.py @@ -0,0 +1,343 @@ +"""Efficient functions for generating orthogonal polynomials.""" +from sympy.core.symbol import Dummy +from sympy.polys.densearith import (dup_mul, dup_mul_ground, + dup_lshift, dup_sub, dup_add, dup_sub_term, dup_sub_ground, dup_sqr) +from sympy.polys.domains import ZZ, QQ +from sympy.polys.polytools import named_poly +from sympy.utilities import public + +def dup_jacobi(n, a, b, K): + """Low-level implementation of Jacobi polynomials.""" + if n < 1: + return [K.one] + m2, m1 = [K.one], [(a+b)/K(2) + K.one, (a-b)/K(2)] + for i in range(2, n+1): + den = K(i)*(a + b + i)*(a + b + K(2)*i - K(2)) + f0 = (a + b + K(2)*i - K.one) * (a*a - b*b) / (K(2)*den) + f1 = (a + b + K(2)*i - K.one) * (a + b + K(2)*i - K(2)) * (a + b + K(2)*i) / (K(2)*den) + f2 = (a + i - K.one)*(b + i - K.one)*(a + b + K(2)*i) / den + p0 = dup_mul_ground(m1, f0, K) + p1 = dup_mul_ground(dup_lshift(m1, 1, K), f1, K) + p2 = dup_mul_ground(m2, f2, K) + m2, m1 = m1, dup_sub(dup_add(p0, p1, K), p2, K) + return m1 + +@public +def jacobi_poly(n, a, b, x=None, polys=False): + r"""Generates the Jacobi polynomial `P_n^{(a,b)}(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + a + Lower limit of minimal domain for the list of coefficients. + b + Upper limit of minimal domain for the list of coefficients. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_jacobi, None, "Jacobi polynomial", (x, a, b), polys) + +def dup_gegenbauer(n, a, K): + """Low-level implementation of Gegenbauer polynomials.""" + if n < 1: + return [K.one] + m2, m1 = [K.one], [K(2)*a, K.zero] + for i in range(2, n+1): + p1 = dup_mul_ground(dup_lshift(m1, 1, K), K(2)*(a-K.one)/K(i) + K(2), K) + p2 = dup_mul_ground(m2, K(2)*(a-K.one)/K(i) + K.one, K) + m2, m1 = m1, dup_sub(p1, p2, K) + return m1 + +def gegenbauer_poly(n, a, x=None, polys=False): + r"""Generates the Gegenbauer polynomial `C_n^{(a)}(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + a + Decides minimal domain for the list of coefficients. + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_gegenbauer, None, "Gegenbauer polynomial", (x, a), polys) + +def dup_chebyshevt(n, K): + """Low-level implementation of Chebyshev polynomials of the first kind.""" + if n < 1: + return [K.one] + # When n is small, it is faster to directly calculate the recurrence relation. + if n < 64: # The threshold serves as a heuristic + return _dup_chebyshevt_rec(n, K) + return _dup_chebyshevt_prod(n, K) + +def _dup_chebyshevt_rec(n, K): + r""" Chebyshev polynomials of the first kind using recurrence. + + Explanation + =========== + + Chebyshev polynomials of the first kind are defined by the recurrence + relation: + + .. math:: + T_0(x) &= 1\\ + T_1(x) &= x\\ + T_n(x) &= 2xT_{n-1}(x) - T_{n-2}(x) + + This function calculates the Chebyshev polynomial of the first kind using + the above recurrence relation. + + Parameters + ========== + + n : int + n is a nonnegative integer. + K : domain + + """ + m2, m1 = [K.one], [K.one, K.zero] + for _ in range(n - 1): + m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2), K), m2, K) + return m1 + +def _dup_chebyshevt_prod(n, K): + r""" Chebyshev polynomials of the first kind using recursive products. + + Explanation + =========== + + Computes Chebyshev polynomials of the first kind using + + .. math:: + T_{2n}(x) &= 2T_n^2(x) - 1\\ + T_{2n+1}(x) &= 2T_{n+1}(x)T_n(x) - x + + This is faster than ``_dup_chebyshevt_rec`` for large ``n``. + + Parameters + ========== + + n : int + n is a nonnegative integer. + K : domain + + """ + m2, m1 = [K.one, K.zero], [K(2), K.zero, -K.one] + for i in bin(n)[3:]: + c = dup_sub_term(dup_mul_ground(dup_mul(m1, m2, K), K(2), K), K.one, 1, K) + if i == '1': + m2, m1 = c, dup_sub_ground(dup_mul_ground(dup_sqr(m1, K), K(2), K), K.one, K) + else: + m2, m1 = dup_sub_ground(dup_mul_ground(dup_sqr(m2, K), K(2), K), K.one, K), c + return m2 + +def dup_chebyshevu(n, K): + """Low-level implementation of Chebyshev polynomials of the second kind.""" + if n < 1: + return [K.one] + m2, m1 = [K.one], [K(2), K.zero] + for i in range(2, n+1): + m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2), K), m2, K) + return m1 + +@public +def chebyshevt_poly(n, x=None, polys=False): + r"""Generates the Chebyshev polynomial of the first kind `T_n(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_chebyshevt, ZZ, + "Chebyshev polynomial of the first kind", (x,), polys) + +@public +def chebyshevu_poly(n, x=None, polys=False): + r"""Generates the Chebyshev polynomial of the second kind `U_n(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_chebyshevu, ZZ, + "Chebyshev polynomial of the second kind", (x,), polys) + +def dup_hermite(n, K): + """Low-level implementation of Hermite polynomials.""" + if n < 1: + return [K.one] + m2, m1 = [K.one], [K(2), K.zero] + for i in range(2, n+1): + a = dup_lshift(m1, 1, K) + b = dup_mul_ground(m2, K(i-1), K) + m2, m1 = m1, dup_mul_ground(dup_sub(a, b, K), K(2), K) + return m1 + +def dup_hermite_prob(n, K): + """Low-level implementation of probabilist's Hermite polynomials.""" + if n < 1: + return [K.one] + m2, m1 = [K.one], [K.one, K.zero] + for i in range(2, n+1): + a = dup_lshift(m1, 1, K) + b = dup_mul_ground(m2, K(i-1), K) + m2, m1 = m1, dup_sub(a, b, K) + return m1 + +@public +def hermite_poly(n, x=None, polys=False): + r"""Generates the Hermite polynomial `H_n(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_hermite, ZZ, "Hermite polynomial", (x,), polys) + +@public +def hermite_prob_poly(n, x=None, polys=False): + r"""Generates the probabilist's Hermite polynomial `He_n(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_hermite_prob, ZZ, + "probabilist's Hermite polynomial", (x,), polys) + +def dup_legendre(n, K): + """Low-level implementation of Legendre polynomials.""" + if n < 1: + return [K.one] + m2, m1 = [K.one], [K.one, K.zero] + for i in range(2, n+1): + a = dup_mul_ground(dup_lshift(m1, 1, K), K(2*i-1, i), K) + b = dup_mul_ground(m2, K(i-1, i), K) + m2, m1 = m1, dup_sub(a, b, K) + return m1 + +@public +def legendre_poly(n, x=None, polys=False): + r"""Generates the Legendre polynomial `P_n(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_legendre, QQ, "Legendre polynomial", (x,), polys) + +def dup_laguerre(n, alpha, K): + """Low-level implementation of Laguerre polynomials.""" + m2, m1 = [K.zero], [K.one] + for i in range(1, n+1): + a = dup_mul(m1, [-K.one/K(i), (alpha-K.one)/K(i) + K(2)], K) + b = dup_mul_ground(m2, (alpha-K.one)/K(i) + K.one, K) + m2, m1 = m1, dup_sub(a, b, K) + return m1 + +@public +def laguerre_poly(n, x=None, alpha=0, polys=False): + r"""Generates the Laguerre polynomial `L_n^{(\alpha)}(x)`. + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + alpha : optional + Decides minimal domain for the list of coefficients. + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + return named_poly(n, dup_laguerre, None, "Laguerre polynomial", (x, alpha), polys) + +def dup_spherical_bessel_fn(n, K): + """Low-level implementation of fn(n, x).""" + if n < 1: + return [K.one, K.zero] + m2, m1 = [K.one], [K.one, K.zero] + for i in range(2, n+1): + m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2*i-1), K), m2, K) + return dup_lshift(m1, 1, K) + +def dup_spherical_bessel_fn_minus(n, K): + """Low-level implementation of fn(-n, x).""" + m2, m1 = [K.one, K.zero], [K.zero] + for i in range(2, n+1): + m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(3-2*i), K), m2, K) + return m1 + +def spherical_bessel_fn(n, x=None, polys=False): + """ + Coefficients for the spherical Bessel functions. + + These are only needed in the jn() function. + + The coefficients are calculated from: + + fn(0, z) = 1/z + fn(1, z) = 1/z**2 + fn(n-1, z) + fn(n+1, z) == (2*n+1)/z * fn(n, z) + + Parameters + ========== + + n : int + Degree of the polynomial. + x : optional + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + + Examples + ======== + + >>> from sympy.polys.orthopolys import spherical_bessel_fn as fn + >>> from sympy import Symbol + >>> z = Symbol("z") + >>> fn(1, z) + z**(-2) + >>> fn(2, z) + -1/z + 3/z**3 + >>> fn(3, z) + -6/z**2 + 15/z**4 + >>> fn(4, z) + 1/z - 45/z**3 + 105/z**5 + + """ + if x is None: + x = Dummy("x") + f = dup_spherical_bessel_fn_minus if n < 0 else dup_spherical_bessel_fn + return named_poly(abs(n), f, ZZ, "", (QQ(1)/x,), polys) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/partfrac.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/partfrac.py new file mode 100644 index 0000000000000000000000000000000000000000..dedc1bf0fba42128e869303ed9b12c598640a36c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/partfrac.py @@ -0,0 +1,496 @@ +"""Algorithms for partial fraction decomposition of rational functions. """ + + +from sympy.core import S, Add, sympify, Function, Lambda, Dummy +from sympy.core.traversal import preorder_traversal +from sympy.polys import Poly, RootSum, cancel, factor +from sympy.polys.polyerrors import PolynomialError +from sympy.polys.polyoptions import allowed_flags, set_defaults +from sympy.polys.polytools import parallel_poly_from_expr +from sympy.utilities import numbered_symbols, take, xthreaded, public + + +@xthreaded +@public +def apart(f, x=None, full=False, **options): + """ + Compute partial fraction decomposition of a rational function. + + Given a rational function ``f``, computes the partial fraction + decomposition of ``f``. Two algorithms are available: One is based on the + undetermined coefficients method, the other is Bronstein's full partial + fraction decomposition algorithm. + + The undetermined coefficients method (selected by ``full=False``) uses + polynomial factorization (and therefore accepts the same options as + factor) for the denominator. Per default it works over the rational + numbers, therefore decomposition of denominators with non-rational roots + (e.g. irrational, complex roots) is not supported by default (see options + of factor). + + Bronstein's algorithm can be selected by using ``full=True`` and allows a + decomposition of denominators with non-rational roots. A human-readable + result can be obtained via ``doit()`` (see examples below). + + Examples + ======== + + >>> from sympy.polys.partfrac import apart + >>> from sympy.abc import x, y + + By default, using the undetermined coefficients method: + + >>> apart(y/(x + 2)/(x + 1), x) + -y/(x + 2) + y/(x + 1) + + The undetermined coefficients method does not provide a result when the + denominators roots are not rational: + + >>> apart(y/(x**2 + x + 1), x) + y/(x**2 + x + 1) + + You can choose Bronstein's algorithm by setting ``full=True``: + + >>> apart(y/(x**2 + x + 1), x, full=True) + RootSum(_w**2 + _w + 1, Lambda(_a, (-2*_a*y/3 - y/3)/(-_a + x))) + + Calling ``doit()`` yields a human-readable result: + + >>> apart(y/(x**2 + x + 1), x, full=True).doit() + (-y/3 - 2*y*(-1/2 - sqrt(3)*I/2)/3)/(x + 1/2 + sqrt(3)*I/2) + (-y/3 - + 2*y*(-1/2 + sqrt(3)*I/2)/3)/(x + 1/2 - sqrt(3)*I/2) + + + See Also + ======== + + apart_list, assemble_partfrac_list + """ + allowed_flags(options, []) + + f = sympify(f) + + if f.is_Atom: + return f + else: + P, Q = f.as_numer_denom() + + _options = options.copy() + options = set_defaults(options, extension=True) + try: + (P, Q), opt = parallel_poly_from_expr((P, Q), x, **options) + except PolynomialError as msg: + if f.is_commutative: + raise PolynomialError(msg) + # non-commutative + if f.is_Mul: + c, nc = f.args_cnc(split_1=False) + nc = f.func(*nc) + if c: + c = apart(f.func._from_args(c), x=x, full=full, **_options) + return c*nc + else: + return nc + elif f.is_Add: + c = [] + nc = [] + for i in f.args: + if i.is_commutative: + c.append(i) + else: + try: + nc.append(apart(i, x=x, full=full, **_options)) + except NotImplementedError: + nc.append(i) + return apart(f.func(*c), x=x, full=full, **_options) + f.func(*nc) + else: + reps = [] + pot = preorder_traversal(f) + next(pot) + for e in pot: + try: + reps.append((e, apart(e, x=x, full=full, **_options))) + pot.skip() # this was handled successfully + except NotImplementedError: + pass + return f.xreplace(dict(reps)) + + if P.is_multivariate: + fc = f.cancel() + if fc != f: + return apart(fc, x=x, full=full, **_options) + + raise NotImplementedError( + "multivariate partial fraction decomposition") + + common, P, Q = P.cancel(Q) + + poly, P = P.div(Q, auto=True) + P, Q = P.rat_clear_denoms(Q) + + if Q.degree() <= 1: + partial = P/Q + else: + if not full: + partial = apart_undetermined_coeffs(P, Q) + else: + partial = apart_full_decomposition(P, Q) + + terms = S.Zero + + for term in Add.make_args(partial): + if term.has(RootSum): + terms += term + else: + terms += factor(term) + + return common*(poly.as_expr() + terms) + + +def apart_undetermined_coeffs(P, Q): + """Partial fractions via method of undetermined coefficients. """ + X = numbered_symbols(cls=Dummy) + partial, symbols = [], [] + + _, factors = Q.factor_list() + + for f, k in factors: + n, q = f.degree(), Q + + for i in range(1, k + 1): + coeffs, q = take(X, n), q.quo(f) + partial.append((coeffs, q, f, i)) + symbols.extend(coeffs) + + dom = Q.get_domain().inject(*symbols) + F = Poly(0, Q.gen, domain=dom) + + for i, (coeffs, q, f, k) in enumerate(partial): + h = Poly(coeffs, Q.gen, domain=dom) + partial[i] = (h, f, k) + q = q.set_domain(dom) + F += h*q + + system, result = [], S.Zero + + for (k,), coeff in F.terms(): + system.append(coeff - P.nth(k)) + + from sympy.solvers import solve + solution = solve(system, symbols) + + for h, f, k in partial: + h = h.as_expr().subs(solution) + result += h/f.as_expr()**k + + return result + + +def apart_full_decomposition(P, Q): + """ + Bronstein's full partial fraction decomposition algorithm. + + Given a univariate rational function ``f``, performing only GCD + operations over the algebraic closure of the initial ground domain + of definition, compute full partial fraction decomposition with + fractions having linear denominators. + + Note that no factorization of the initial denominator of ``f`` is + performed. The final decomposition is formed in terms of a sum of + :class:`RootSum` instances. + + References + ========== + + .. [1] [Bronstein93]_ + + """ + return assemble_partfrac_list(apart_list(P/Q, P.gens[0])) + + +@public +def apart_list(f, x=None, dummies=None, **options): + """ + Compute partial fraction decomposition of a rational function + and return the result in structured form. + + Given a rational function ``f`` compute the partial fraction decomposition + of ``f``. Only Bronstein's full partial fraction decomposition algorithm + is supported by this method. The return value is highly structured and + perfectly suited for further algorithmic treatment rather than being + human-readable. The function returns a tuple holding three elements: + + * The first item is the common coefficient, free of the variable `x` used + for decomposition. (It is an element of the base field `K`.) + + * The second item is the polynomial part of the decomposition. This can be + the zero polynomial. (It is an element of `K[x]`.) + + * The third part itself is a list of quadruples. Each quadruple + has the following elements in this order: + + - The (not necessarily irreducible) polynomial `D` whose roots `w_i` appear + in the linear denominator of a bunch of related fraction terms. (This item + can also be a list of explicit roots. However, at the moment ``apart_list`` + never returns a result this way, but the related ``assemble_partfrac_list`` + function accepts this format as input.) + + - The numerator of the fraction, written as a function of the root `w` + + - The linear denominator of the fraction *excluding its power exponent*, + written as a function of the root `w`. + + - The power to which the denominator has to be raised. + + On can always rebuild a plain expression by using the function ``assemble_partfrac_list``. + + Examples + ======== + + A first example: + + >>> from sympy.polys.partfrac import apart_list, assemble_partfrac_list + >>> from sympy.abc import x, t + + >>> f = (2*x**3 - 2*x) / (x**2 - 2*x + 1) + >>> pfd = apart_list(f) + >>> pfd + (1, + Poly(2*x + 4, x, domain='ZZ'), + [(Poly(_w - 1, _w, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1)]) + + >>> assemble_partfrac_list(pfd) + 2*x + 4 + 4/(x - 1) + + Second example: + + >>> f = (-2*x - 2*x**2) / (3*x**2 - 6*x) + >>> pfd = apart_list(f) + >>> pfd + (-1, + Poly(2/3, x, domain='QQ'), + [(Poly(_w - 2, _w, domain='ZZ'), Lambda(_a, 2), Lambda(_a, -_a + x), 1)]) + + >>> assemble_partfrac_list(pfd) + -2/3 - 2/(x - 2) + + Another example, showing symbolic parameters: + + >>> pfd = apart_list(t/(x**2 + x + t), x) + >>> pfd + (1, + Poly(0, x, domain='ZZ[t]'), + [(Poly(_w**2 + _w + t, _w, domain='ZZ[t]'), + Lambda(_a, -2*_a*t/(4*t - 1) - t/(4*t - 1)), + Lambda(_a, -_a + x), + 1)]) + + >>> assemble_partfrac_list(pfd) + RootSum(_w**2 + _w + t, Lambda(_a, (-2*_a*t/(4*t - 1) - t/(4*t - 1))/(-_a + x))) + + This example is taken from Bronstein's original paper: + + >>> f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) + >>> pfd = apart_list(f) + >>> pfd + (1, + Poly(0, x, domain='ZZ'), + [(Poly(_w - 2, _w, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1), + (Poly(_w**2 - 1, _w, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2), + (Poly(_w + 1, _w, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)]) + + >>> assemble_partfrac_list(pfd) + -4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2) + + See also + ======== + + apart, assemble_partfrac_list + + References + ========== + + .. [1] [Bronstein93]_ + + """ + allowed_flags(options, []) + + f = sympify(f) + + if f.is_Atom: + return f + else: + P, Q = f.as_numer_denom() + + options = set_defaults(options, extension=True) + (P, Q), opt = parallel_poly_from_expr((P, Q), x, **options) + + if P.is_multivariate: + raise NotImplementedError( + "multivariate partial fraction decomposition") + + common, P, Q = P.cancel(Q) + + poly, P = P.div(Q, auto=True) + P, Q = P.rat_clear_denoms(Q) + + polypart = poly + + if dummies is None: + def dummies(name): + d = Dummy(name) + while True: + yield d + + dummies = dummies("w") + + rationalpart = apart_list_full_decomposition(P, Q, dummies) + + return (common, polypart, rationalpart) + + +def apart_list_full_decomposition(P, Q, dummygen): + """ + Bronstein's full partial fraction decomposition algorithm. + + Given a univariate rational function ``f``, performing only GCD + operations over the algebraic closure of the initial ground domain + of definition, compute full partial fraction decomposition with + fractions having linear denominators. + + Note that no factorization of the initial denominator of ``f`` is + performed. The final decomposition is formed in terms of a sum of + :class:`RootSum` instances. + + References + ========== + + .. [1] [Bronstein93]_ + + """ + P_orig, Q_orig, x, U = P, Q, P.gen, [] + + u = Function('u')(x) + a = Dummy('a') + + partial = [] + + for d, n in Q.sqf_list_include(all=True): + b = d.as_expr() + U += [ u.diff(x, n - 1) ] + + h = cancel(P_orig/Q_orig.quo(d**n)) / u**n + + H, subs = [h], [] + + for j in range(1, n): + H += [ H[-1].diff(x) / j ] + + for j in range(1, n + 1): + subs += [ (U[j - 1], b.diff(x, j) / j) ] + + for j in range(0, n): + P, Q = cancel(H[j]).as_numer_denom() + + for i in range(0, j + 1): + P = P.subs(*subs[j - i]) + + Q = Q.subs(*subs[0]) + + P = Poly(P, x) + Q = Poly(Q, x) + + G = P.gcd(d) + D = d.quo(G) + + B, g = Q.half_gcdex(D) + b = (P * B.quo(g)).rem(D) + + Dw = D.subs(x, next(dummygen)) + numer = Lambda(a, b.as_expr().subs(x, a)) + denom = Lambda(a, (x - a)) + exponent = n-j + + partial.append((Dw, numer, denom, exponent)) + + return partial + + +@public +def assemble_partfrac_list(partial_list): + r"""Reassemble a full partial fraction decomposition + from a structured result obtained by the function ``apart_list``. + + Examples + ======== + + This example is taken from Bronstein's original paper: + + >>> from sympy.polys.partfrac import apart_list, assemble_partfrac_list + >>> from sympy.abc import x + + >>> f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) + >>> pfd = apart_list(f) + >>> pfd + (1, + Poly(0, x, domain='ZZ'), + [(Poly(_w - 2, _w, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1), + (Poly(_w**2 - 1, _w, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2), + (Poly(_w + 1, _w, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)]) + + >>> assemble_partfrac_list(pfd) + -4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2) + + If we happen to know some roots we can provide them easily inside the structure: + + >>> pfd = apart_list(2/(x**2-2)) + >>> pfd + (1, + Poly(0, x, domain='ZZ'), + [(Poly(_w**2 - 2, _w, domain='ZZ'), + Lambda(_a, _a/2), + Lambda(_a, -_a + x), + 1)]) + + >>> pfda = assemble_partfrac_list(pfd) + >>> pfda + RootSum(_w**2 - 2, Lambda(_a, _a/(-_a + x)))/2 + + >>> pfda.doit() + -sqrt(2)/(2*(x + sqrt(2))) + sqrt(2)/(2*(x - sqrt(2))) + + >>> from sympy import Dummy, Poly, Lambda, sqrt + >>> a = Dummy("a") + >>> pfd = (1, Poly(0, x, domain='ZZ'), [([sqrt(2),-sqrt(2)], Lambda(a, a/2), Lambda(a, -a + x), 1)]) + + >>> assemble_partfrac_list(pfd) + -sqrt(2)/(2*(x + sqrt(2))) + sqrt(2)/(2*(x - sqrt(2))) + + See Also + ======== + + apart, apart_list + """ + # Common factor + common = partial_list[0] + + # Polynomial part + polypart = partial_list[1] + pfd = polypart.as_expr() + + # Rational parts + for r, nf, df, ex in partial_list[2]: + if isinstance(r, Poly): + # Assemble in case the roots are given implicitly by a polynomials + an, nu = nf.variables, nf.expr + ad, de = df.variables, df.expr + # Hack to make dummies equal because Lambda created new Dummies + de = de.subs(ad[0], an[0]) + func = Lambda(tuple(an), nu/de**ex) + pfd += RootSum(r, func, auto=False, quadratic=False) + else: + # Assemble in case the roots are given explicitly by a list of algebraic numbers + for root in r: + pfd += nf(root)/df(root)**ex + + return common*pfd diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyclasses.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc0e0f368ab07d64837e057b841ea991d9de223 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyclasses.py @@ -0,0 +1,3186 @@ +"""OO layer for several polynomial representations. """ + +from __future__ import annotations + +from sympy.external.gmpy import GROUND_TYPES + +from sympy.utilities.exceptions import sympy_deprecation_warning + +from sympy.core.numbers import oo +from sympy.core.sympify import CantSympify +from sympy.polys.polyutils import PicklableWithSlots, _sort_factors +from sympy.polys.domains import Domain, ZZ, QQ + +from sympy.polys.polyerrors import ( + CoercionFailed, + ExactQuotientFailed, + DomainError, + NotInvertible, +) + +from sympy.polys.densebasic import ( + ninf, + dmp_validate, + dup_normal, dmp_normal, + dup_convert, dmp_convert, + dmp_from_sympy, + dup_strip, + dmp_degree_in, + dmp_degree_list, + dmp_negative_p, + dmp_ground_LC, + dmp_ground_TC, + dmp_ground_nth, + dmp_one, dmp_ground, + dmp_zero, dmp_zero_p, dmp_one_p, dmp_ground_p, + dup_from_dict, dmp_from_dict, + dmp_to_dict, + dmp_deflate, + dmp_inject, dmp_eject, + dmp_terms_gcd, + dmp_list_terms, dmp_exclude, + dup_slice, dmp_slice_in, dmp_permute, + dmp_to_tuple,) + +from sympy.polys.densearith import ( + dmp_add_ground, + dmp_sub_ground, + dmp_mul_ground, + dmp_quo_ground, + dmp_exquo_ground, + dmp_abs, + dmp_neg, + dmp_add, + dmp_sub, + dmp_mul, + dmp_sqr, + dmp_pow, + dmp_pdiv, + dmp_prem, + dmp_pquo, + dmp_pexquo, + dmp_div, + dmp_rem, + dmp_quo, + dmp_exquo, + dmp_add_mul, dmp_sub_mul, + dmp_max_norm, + dmp_l1_norm, + dmp_l2_norm_squared) + +from sympy.polys.densetools import ( + dmp_clear_denoms, + dmp_integrate_in, + dmp_diff_in, + dmp_eval_in, + dup_revert, + dmp_ground_trunc, + dmp_ground_content, + dmp_ground_primitive, + dmp_ground_monic, + dmp_compose, + dup_decompose, + dup_shift, + dmp_shift, + dup_transform, + dmp_lift) + +from sympy.polys.euclidtools import ( + dup_half_gcdex, dup_gcdex, dup_invert, + dmp_subresultants, + dmp_resultant, + dmp_discriminant, + dmp_inner_gcd, + dmp_gcd, + dmp_lcm, + dmp_cancel) + +from sympy.polys.sqfreetools import ( + dup_gff_list, + dmp_norm, + dmp_sqf_p, + dmp_sqf_norm, + dmp_sqf_part, + dmp_sqf_list, dmp_sqf_list_include) + +from sympy.polys.factortools import ( + dup_cyclotomic_p, dmp_irreducible_p, + dmp_factor_list, dmp_factor_list_include) + +from sympy.polys.rootisolation import ( + dup_isolate_real_roots_sqf, + dup_isolate_real_roots, + dup_isolate_all_roots_sqf, + dup_isolate_all_roots, + dup_refine_real_root, + dup_count_real_roots, + dup_count_complex_roots, + dup_sturm, + dup_cauchy_upper_bound, + dup_cauchy_lower_bound, + dup_mignotte_sep_bound_squared) + +from sympy.polys.polyerrors import ( + UnificationFailed, + PolynomialError) + + +if GROUND_TYPES == 'flint': + import flint + def _supported_flint_domain(D): + return D.is_ZZ or D.is_QQ or D.is_FF and D._is_flint +else: + flint = None + def _supported_flint_domain(D): + return False + + +class DMP(CantSympify): + """Dense Multivariate Polynomials over `K`. """ + + __slots__ = () + + lev: int + dom: Domain + + def __new__(cls, rep, dom, lev=None): + + if lev is None: + rep, lev = dmp_validate(rep) + elif not isinstance(rep, list): + raise CoercionFailed("expected list, got %s" % type(rep)) + + return cls.new(rep, dom, lev) + + @classmethod + def new(cls, rep, dom, lev): + # It would be too slow to call _validate_args always at runtime. + # Ideally this checking would be handled by a static type checker. + # + #cls._validate_args(rep, dom, lev) + if flint is not None: + if lev == 0 and _supported_flint_domain(dom): + return DUP_Flint._new(rep, dom, lev) + + return DMP_Python._new(rep, dom, lev) + + @property + def rep(f): + """Get the representation of ``f``. """ + + sympy_deprecation_warning(""" + Accessing the ``DMP.rep`` attribute is deprecated. The internal + representation of ``DMP`` instances can now be ``DUP_Flint`` when the + ground types are ``flint``. In this case the ``DMP`` instance does not + have a ``rep`` attribute. Use ``DMP.to_list()`` instead. Using + ``DMP.to_list()`` also works in previous versions of SymPy. + """, + deprecated_since_version="1.13", + active_deprecations_target="dmp-rep", + ) + + return f.to_list() + + def to_best(f): + """Convert to DUP_Flint if possible. + + This method should be used when the domain or level is changed and it + potentially becomes possible to convert from DMP_Python to DUP_Flint. + """ + if flint is not None: + if isinstance(f, DMP_Python) and f.lev == 0 and _supported_flint_domain(f.dom): + return DUP_Flint.new(f._rep, f.dom, f.lev) + + return f + + @classmethod + def _validate_args(cls, rep, dom, lev): + assert isinstance(dom, Domain) + assert isinstance(lev, int) and lev >= 0 + + def validate_rep(rep, lev): + assert isinstance(rep, list) + if lev == 0: + assert all(dom.of_type(c) for c in rep) + else: + for r in rep: + validate_rep(r, lev - 1) + + validate_rep(rep, lev) + + @classmethod + def from_dict(cls, rep, lev, dom): + rep = dmp_from_dict(rep, lev, dom) + return cls.new(rep, dom, lev) + + @classmethod + def from_list(cls, rep, lev, dom): + """Create an instance of ``cls`` given a list of native coefficients. """ + return cls.new(dmp_convert(rep, lev, None, dom), dom, lev) + + @classmethod + def from_sympy_list(cls, rep, lev, dom): + """Create an instance of ``cls`` given a list of SymPy coefficients. """ + return cls.new(dmp_from_sympy(rep, lev, dom), dom, lev) + + @classmethod + def from_monoms_coeffs(cls, monoms, coeffs, lev, dom): + return cls(dict(list(zip(monoms, coeffs))), dom, lev) + + def convert(f, dom): + """Convert ``f`` to a ``DMP`` over the new domain. """ + if f.dom == dom: + return f + elif f.lev or flint is None: + return f._convert(dom) + elif isinstance(f, DUP_Flint): + if _supported_flint_domain(dom): + return f._convert(dom) + else: + return f.to_DMP_Python()._convert(dom) + elif isinstance(f, DMP_Python): + if _supported_flint_domain(dom): + return f._convert(dom).to_DUP_Flint() + else: + return f._convert(dom) + else: + raise RuntimeError("unreachable code") + + def _convert(f, dom): + raise NotImplementedError + + @classmethod + def zero(cls, lev, dom): + return DMP(dmp_zero(lev), dom, lev) + + @classmethod + def one(cls, lev, dom): + return DMP(dmp_one(lev, dom), dom, lev) + + def _one(f): + raise NotImplementedError + + def __repr__(f): + return "%s(%s, %s)" % (f.__class__.__name__, f.to_list(), f.dom) + + def __hash__(f): + return hash((f.__class__.__name__, f.to_tuple(), f.lev, f.dom)) + + def __getnewargs__(self): + return self.to_list(), self.dom, self.lev + + def ground_new(f, coeff): + """Construct a new ground instance of ``f``. """ + raise NotImplementedError + + def unify_DMP(f, g): + """Unify and return ``DMP`` instances of ``f`` and ``g``. """ + if not isinstance(g, DMP) or f.lev != g.lev: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + if f.dom != g.dom: + dom = f.dom.unify(g.dom) + f = f.convert(dom) + g = g.convert(dom) + + return f, g + + def to_dict(f, zero=False): + """Convert ``f`` to a dict representation with native coefficients. """ + return dmp_to_dict(f.to_list(), f.lev, f.dom, zero=zero) + + def to_sympy_dict(f, zero=False): + """Convert ``f`` to a dict representation with SymPy coefficients. """ + rep = f.to_dict(zero=zero) + + for k, v in rep.items(): + rep[k] = f.dom.to_sympy(v) + + return rep + + def to_sympy_list(f): + """Convert ``f`` to a list representation with SymPy coefficients. """ + def sympify_nested_list(rep): + out = [] + for val in rep: + if isinstance(val, list): + out.append(sympify_nested_list(val)) + else: + out.append(f.dom.to_sympy(val)) + return out + + return sympify_nested_list(f.to_list()) + + def to_list(f): + """Convert ``f`` to a list representation with native coefficients. """ + raise NotImplementedError + + def to_tuple(f): + """ + Convert ``f`` to a tuple representation with native coefficients. + + This is needed for hashing. + """ + raise NotImplementedError + + def to_ring(f): + """Make the ground domain a ring. """ + return f.convert(f.dom.get_ring()) + + def to_field(f): + """Make the ground domain a field. """ + return f.convert(f.dom.get_field()) + + def to_exact(f): + """Make the ground domain exact. """ + return f.convert(f.dom.get_exact()) + + def slice(f, m, n, j=0): + """Take a continuous subsequence of terms of ``f``. """ + if not f.lev and not j: + return f._slice(m, n) + else: + return f._slice_lev(m, n, j) + + def _slice(f, m, n): + raise NotImplementedError + + def _slice_lev(f, m, n, j): + raise NotImplementedError + + def coeffs(f, order=None): + """Returns all non-zero coefficients from ``f`` in lex order. """ + return [ c for _, c in f.terms(order=order) ] + + def monoms(f, order=None): + """Returns all non-zero monomials from ``f`` in lex order. """ + return [ m for m, _ in f.terms(order=order) ] + + def terms(f, order=None): + """Returns all non-zero terms from ``f`` in lex order. """ + if f.is_zero: + zero_monom = (0,)*(f.lev + 1) + return [(zero_monom, f.dom.zero)] + else: + return f._terms(order=order) + + def _terms(f, order=None): + raise NotImplementedError + + def all_coeffs(f): + """Returns all coefficients from ``f``. """ + if f.lev: + raise PolynomialError('multivariate polynomials not supported') + + if not f: + return [f.dom.zero] + else: + return list(f.to_list()) + + def all_monoms(f): + """Returns all monomials from ``f``. """ + if f.lev: + raise PolynomialError('multivariate polynomials not supported') + + n = f.degree() + + if n < 0: + return [(0,)] + else: + return [ (n - i,) for i, c in enumerate(f.to_list()) ] + + def all_terms(f): + """Returns all terms from a ``f``. """ + if f.lev: + raise PolynomialError('multivariate polynomials not supported') + + n = f.degree() + + if n < 0: + return [((0,), f.dom.zero)] + else: + return [ ((n - i,), c) for i, c in enumerate(f.to_list()) ] + + def lift(f): + """Convert algebraic coefficients to rationals. """ + return f._lift().to_best() + + def _lift(f): + raise NotImplementedError + + def deflate(f): + """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """ + raise NotImplementedError + + def inject(f, front=False): + """Inject ground domain generators into ``f``. """ + raise NotImplementedError + + def eject(f, dom, front=False): + """Eject selected generators into the ground domain. """ + raise NotImplementedError + + def exclude(f): + r""" + Remove useless generators from ``f``. + + Returns the removed generators and the new excluded ``f``. + + Examples + ======== + + >>> from sympy.polys.polyclasses import DMP + >>> from sympy.polys.domains import ZZ + + >>> DMP([[[ZZ(1)]], [[ZZ(1)], [ZZ(2)]]], ZZ).exclude() + ([2], DMP_Python([[1], [1, 2]], ZZ)) + + """ + J, F = f._exclude() + return J, F.to_best() + + def _exclude(f): + raise NotImplementedError + + def permute(f, P): + r""" + Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`. + + Examples + ======== + + >>> from sympy.polys.polyclasses import DMP + >>> from sympy.polys.domains import ZZ + + >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 0, 2]) + DMP_Python([[[2], []], [[1, 0], []]], ZZ) + + >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 2, 0]) + DMP_Python([[[1], []], [[2, 0], []]], ZZ) + + """ + return f._permute(P) + + def _permute(f, P): + raise NotImplementedError + + def terms_gcd(f): + """Remove GCD of terms from the polynomial ``f``. """ + raise NotImplementedError + + def abs(f): + """Make all coefficients in ``f`` positive. """ + raise NotImplementedError + + def neg(f): + """Negate all coefficients in ``f``. """ + raise NotImplementedError + + def add_ground(f, c): + """Add an element of the ground domain to ``f``. """ + return f._add_ground(f.dom.convert(c)) + + def sub_ground(f, c): + """Subtract an element of the ground domain from ``f``. """ + return f._sub_ground(f.dom.convert(c)) + + def mul_ground(f, c): + """Multiply ``f`` by a an element of the ground domain. """ + return f._mul_ground(f.dom.convert(c)) + + def quo_ground(f, c): + """Quotient of ``f`` by a an element of the ground domain. """ + return f._quo_ground(f.dom.convert(c)) + + def exquo_ground(f, c): + """Exact quotient of ``f`` by a an element of the ground domain. """ + return f._exquo_ground(f.dom.convert(c)) + + def add(f, g): + """Add two multivariate polynomials ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._add(G) + + def sub(f, g): + """Subtract two multivariate polynomials ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._sub(G) + + def mul(f, g): + """Multiply two multivariate polynomials ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._mul(G) + + def sqr(f): + """Square a multivariate polynomial ``f``. """ + return f._sqr() + + def pow(f, n): + """Raise ``f`` to a non-negative power ``n``. """ + if not isinstance(n, int): + raise TypeError("``int`` expected, got %s" % type(n)) + return f._pow(n) + + def pdiv(f, g): + """Polynomial pseudo-division of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._pdiv(G) + + def prem(f, g): + """Polynomial pseudo-remainder of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._prem(G) + + def pquo(f, g): + """Polynomial pseudo-quotient of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._pquo(G) + + def pexquo(f, g): + """Polynomial exact pseudo-quotient of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._pexquo(G) + + def div(f, g): + """Polynomial division with remainder of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._div(G) + + def rem(f, g): + """Computes polynomial remainder of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._rem(G) + + def quo(f, g): + """Computes polynomial quotient of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._quo(G) + + def exquo(f, g): + """Computes polynomial exact quotient of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._exquo(G) + + def _add_ground(f, c): + raise NotImplementedError + + def _sub_ground(f, c): + raise NotImplementedError + + def _mul_ground(f, c): + raise NotImplementedError + + def _quo_ground(f, c): + raise NotImplementedError + + def _exquo_ground(f, c): + raise NotImplementedError + + def _add(f, g): + raise NotImplementedError + + def _sub(f, g): + raise NotImplementedError + + def _mul(f, g): + raise NotImplementedError + + def _sqr(f): + raise NotImplementedError + + def _pow(f, n): + raise NotImplementedError + + def _pdiv(f, g): + raise NotImplementedError + + def _prem(f, g): + raise NotImplementedError + + def _pquo(f, g): + raise NotImplementedError + + def _pexquo(f, g): + raise NotImplementedError + + def _div(f, g): + raise NotImplementedError + + def _rem(f, g): + raise NotImplementedError + + def _quo(f, g): + raise NotImplementedError + + def _exquo(f, g): + raise NotImplementedError + + def degree(f, j=0): + """Returns the leading degree of ``f`` in ``x_j``. """ + if not isinstance(j, int): + raise TypeError("``int`` expected, got %s" % type(j)) + + return f._degree(j) + + def _degree(f, j): + raise NotImplementedError + + def degree_list(f): + """Returns a list of degrees of ``f``. """ + raise NotImplementedError + + def total_degree(f): + """Returns the total degree of ``f``. """ + raise NotImplementedError + + def homogenize(f, s): + """Return homogeneous polynomial of ``f``""" + td = f.total_degree() + result = {} + new_symbol = (s == len(f.terms()[0][0])) + for term in f.terms(): + d = sum(term[0]) + if d < td: + i = td - d + else: + i = 0 + if new_symbol: + result[term[0] + (i,)] = term[1] + else: + l = list(term[0]) + l[s] += i + result[tuple(l)] = term[1] + return DMP.from_dict(result, f.lev + int(new_symbol), f.dom) + + def homogeneous_order(f): + """Returns the homogeneous order of ``f``. """ + if f.is_zero: + return -oo + + monoms = f.monoms() + tdeg = sum(monoms[0]) + + for monom in monoms: + _tdeg = sum(monom) + + if _tdeg != tdeg: + return None + + return tdeg + + def LC(f): + """Returns the leading coefficient of ``f``. """ + raise NotImplementedError + + def TC(f): + """Returns the trailing coefficient of ``f``. """ + raise NotImplementedError + + def nth(f, *N): + """Returns the ``n``-th coefficient of ``f``. """ + if all(isinstance(n, int) for n in N): + return f._nth(N) + else: + raise TypeError("a sequence of integers expected") + + def _nth(f, N): + raise NotImplementedError + + def max_norm(f): + """Returns maximum norm of ``f``. """ + raise NotImplementedError + + def l1_norm(f): + """Returns l1 norm of ``f``. """ + raise NotImplementedError + + def l2_norm_squared(f): + """Return squared l2 norm of ``f``. """ + raise NotImplementedError + + def clear_denoms(f): + """Clear denominators, but keep the ground domain. """ + raise NotImplementedError + + def integrate(f, m=1, j=0): + """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """ + if not isinstance(m, int): + raise TypeError("``int`` expected, got %s" % type(m)) + + if not isinstance(j, int): + raise TypeError("``int`` expected, got %s" % type(j)) + + return f._integrate(m, j) + + def _integrate(f, m, j): + raise NotImplementedError + + def diff(f, m=1, j=0): + """Computes the ``m``-th order derivative of ``f`` in ``x_j``. """ + if not isinstance(m, int): + raise TypeError("``int`` expected, got %s" % type(m)) + + if not isinstance(j, int): + raise TypeError("``int`` expected, got %s" % type(j)) + + return f._diff(m, j) + + def _diff(f, m, j): + raise NotImplementedError + + def eval(f, a, j=0): + """Evaluates ``f`` at the given point ``a`` in ``x_j``. """ + if not isinstance(j, int): + raise TypeError("``int`` expected, got %s" % type(j)) + elif not (0 <= j <= f.lev): + raise ValueError("invalid variable index %s" % j) + + if f.lev: + return f._eval_lev(a, j) + else: + return f._eval(a) + + def _eval(f, a): + raise NotImplementedError + + def _eval_lev(f, a, j): + raise NotImplementedError + + def half_gcdex(f, g): + """Half extended Euclidean algorithm, if univariate. """ + F, G = f.unify_DMP(g) + + if F.lev: + raise ValueError('univariate polynomial expected') + + return F._half_gcdex(G) + + def _half_gcdex(f, g): + raise NotImplementedError + + def gcdex(f, g): + """Extended Euclidean algorithm, if univariate. """ + F, G = f.unify_DMP(g) + + if F.lev: + raise ValueError('univariate polynomial expected') + + if not F.dom.is_Field: + raise DomainError('ground domain must be a field') + + return F._gcdex(G) + + def _gcdex(f, g): + raise NotImplementedError + + def invert(f, g): + """Invert ``f`` modulo ``g``, if possible. """ + F, G = f.unify_DMP(g) + + if F.lev: + raise ValueError('univariate polynomial expected') + + return F._invert(G) + + def _invert(f, g): + raise NotImplementedError + + def revert(f, n): + """Compute ``f**(-1)`` mod ``x**n``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._revert(n) + + def _revert(f, n): + raise NotImplementedError + + def subresultants(f, g): + """Computes subresultant PRS sequence of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._subresultants(G) + + def _subresultants(f, g): + raise NotImplementedError + + def resultant(f, g, includePRS=False): + """Computes resultant of ``f`` and ``g`` via PRS. """ + F, G = f.unify_DMP(g) + if includePRS: + return F._resultant_includePRS(G) + else: + return F._resultant(G) + + def _resultant(f, g, includePRS=False): + raise NotImplementedError + + def discriminant(f): + """Computes discriminant of ``f``. """ + raise NotImplementedError + + def cofactors(f, g): + """Returns GCD of ``f`` and ``g`` and their cofactors. """ + F, G = f.unify_DMP(g) + return F._cofactors(G) + + def _cofactors(f, g): + raise NotImplementedError + + def gcd(f, g): + """Returns polynomial GCD of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._gcd(G) + + def _gcd(f, g): + raise NotImplementedError + + def lcm(f, g): + """Returns polynomial LCM of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._lcm(G) + + def _lcm(f, g): + raise NotImplementedError + + def cancel(f, g, include=True): + """Cancel common factors in a rational function ``f/g``. """ + F, G = f.unify_DMP(g) + + if include: + return F._cancel_include(G) + else: + return F._cancel(G) + + def _cancel(f, g): + raise NotImplementedError + + def _cancel_include(f, g): + raise NotImplementedError + + def trunc(f, p): + """Reduce ``f`` modulo a constant ``p``. """ + return f._trunc(f.dom.convert(p)) + + def _trunc(f, p): + raise NotImplementedError + + def monic(f): + """Divides all coefficients by ``LC(f)``. """ + raise NotImplementedError + + def content(f): + """Returns GCD of polynomial coefficients. """ + raise NotImplementedError + + def primitive(f): + """Returns content and a primitive form of ``f``. """ + raise NotImplementedError + + def compose(f, g): + """Computes functional composition of ``f`` and ``g``. """ + F, G = f.unify_DMP(g) + return F._compose(G) + + def _compose(f, g): + raise NotImplementedError + + def decompose(f): + """Computes functional decomposition of ``f``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._decompose() + + def _decompose(f): + raise NotImplementedError + + def shift(f, a): + """Efficiently compute Taylor shift ``f(x + a)``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._shift(f.dom.convert(a)) + + def shift_list(f, a): + """Efficiently compute Taylor shift ``f(X + A)``. """ + a = [f.dom.convert(ai) for ai in a] + return f._shift_list(a) + + def _shift(f, a): + raise NotImplementedError + + def transform(f, p, q): + """Evaluate functional transformation ``q**n * f(p/q)``.""" + if f.lev: + raise ValueError('univariate polynomial expected') + + P, Q = p.unify_DMP(q) + F, P = f.unify_DMP(P) + F, Q = F.unify_DMP(Q) + + return F._transform(P, Q) + + def _transform(f, p, q): + raise NotImplementedError + + def sturm(f): + """Computes the Sturm sequence of ``f``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._sturm() + + def _sturm(f): + raise NotImplementedError + + def cauchy_upper_bound(f): + """Computes the Cauchy upper bound on the roots of ``f``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._cauchy_upper_bound() + + def _cauchy_upper_bound(f): + raise NotImplementedError + + def cauchy_lower_bound(f): + """Computes the Cauchy lower bound on the nonzero roots of ``f``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._cauchy_lower_bound() + + def _cauchy_lower_bound(f): + raise NotImplementedError + + def mignotte_sep_bound_squared(f): + """Computes the squared Mignotte bound on root separations of ``f``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._mignotte_sep_bound_squared() + + def _mignotte_sep_bound_squared(f): + raise NotImplementedError + + def gff_list(f): + """Computes greatest factorial factorization of ``f``. """ + if f.lev: + raise ValueError('univariate polynomial expected') + + return f._gff_list() + + def _gff_list(f): + raise NotImplementedError + + def norm(f): + """Computes ``Norm(f)``.""" + raise NotImplementedError + + def sqf_norm(f): + """Computes square-free norm of ``f``. """ + raise NotImplementedError + + def sqf_part(f): + """Computes square-free part of ``f``. """ + raise NotImplementedError + + def sqf_list(f, all=False): + """Returns a list of square-free factors of ``f``. """ + raise NotImplementedError + + def sqf_list_include(f, all=False): + """Returns a list of square-free factors of ``f``. """ + raise NotImplementedError + + def factor_list(f): + """Returns a list of irreducible factors of ``f``. """ + raise NotImplementedError + + def factor_list_include(f): + """Returns a list of irreducible factors of ``f``. """ + raise NotImplementedError + + def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): + """Compute isolating intervals for roots of ``f``. """ + if f.lev: + raise PolynomialError("Cannot isolate roots of a multivariate polynomial") + + if all and sqf: + return f._isolate_all_roots_sqf(eps=eps, inf=inf, sup=sup, fast=fast) + elif all and not sqf: + return f._isolate_all_roots(eps=eps, inf=inf, sup=sup, fast=fast) + elif not all and sqf: + return f._isolate_real_roots_sqf(eps=eps, inf=inf, sup=sup, fast=fast) + else: + return f._isolate_real_roots(eps=eps, inf=inf, sup=sup, fast=fast) + + def _isolate_all_roots(f, eps, inf, sup, fast): + raise NotImplementedError + + def _isolate_all_roots_sqf(f, eps, inf, sup, fast): + raise NotImplementedError + + def _isolate_real_roots(f, eps, inf, sup, fast): + raise NotImplementedError + + def _isolate_real_roots_sqf(f, eps, inf, sup, fast): + raise NotImplementedError + + def refine_root(f, s, t, eps=None, steps=None, fast=False): + """ + Refine an isolating interval to the given precision. + + ``eps`` should be a rational number. + + """ + if f.lev: + raise PolynomialError( + "Cannot refine a root of a multivariate polynomial") + + return f._refine_real_root(s, t, eps=eps, steps=steps, fast=fast) + + def _refine_real_root(f, s, t, eps, steps, fast): + raise NotImplementedError + + def count_real_roots(f, inf=None, sup=None): + """Return the number of real roots of ``f`` in ``[inf, sup]``. """ + raise NotImplementedError + + def count_complex_roots(f, inf=None, sup=None): + """Return the number of complex roots of ``f`` in ``[inf, sup]``. """ + raise NotImplementedError + + @property + def is_zero(f): + """Returns ``True`` if ``f`` is a zero polynomial. """ + raise NotImplementedError + + @property + def is_one(f): + """Returns ``True`` if ``f`` is a unit polynomial. """ + raise NotImplementedError + + @property + def is_ground(f): + """Returns ``True`` if ``f`` is an element of the ground domain. """ + raise NotImplementedError + + @property + def is_sqf(f): + """Returns ``True`` if ``f`` is a square-free polynomial. """ + raise NotImplementedError + + @property + def is_monic(f): + """Returns ``True`` if the leading coefficient of ``f`` is one. """ + raise NotImplementedError + + @property + def is_primitive(f): + """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """ + raise NotImplementedError + + @property + def is_linear(f): + """Returns ``True`` if ``f`` is linear in all its variables. """ + raise NotImplementedError + + @property + def is_quadratic(f): + """Returns ``True`` if ``f`` is quadratic in all its variables. """ + raise NotImplementedError + + @property + def is_monomial(f): + """Returns ``True`` if ``f`` is zero or has only one term. """ + raise NotImplementedError + + @property + def is_homogeneous(f): + """Returns ``True`` if ``f`` is a homogeneous polynomial. """ + raise NotImplementedError + + @property + def is_irreducible(f): + """Returns ``True`` if ``f`` has no factors over its domain. """ + raise NotImplementedError + + @property + def is_cyclotomic(f): + """Returns ``True`` if ``f`` is a cyclotomic polynomial. """ + raise NotImplementedError + + def __abs__(f): + return f.abs() + + def __neg__(f): + return f.neg() + + def __add__(f, g): + if isinstance(g, DMP): + return f.add(g) + else: + try: + return f.add_ground(g) + except CoercionFailed: + return NotImplemented + + def __radd__(f, g): + return f.__add__(g) + + def __sub__(f, g): + if isinstance(g, DMP): + return f.sub(g) + else: + try: + return f.sub_ground(g) + except CoercionFailed: + return NotImplemented + + def __rsub__(f, g): + return (-f).__add__(g) + + def __mul__(f, g): + if isinstance(g, DMP): + return f.mul(g) + else: + try: + return f.mul_ground(g) + except CoercionFailed: + return NotImplemented + + def __rmul__(f, g): + return f.__mul__(g) + + def __truediv__(f, g): + if isinstance(g, DMP): + return f.exquo(g) + else: + try: + return f.mul_ground(g) + except CoercionFailed: + return NotImplemented + + def __rtruediv__(f, g): + if isinstance(g, DMP): + return g.exquo(f) + else: + try: + return f._one().mul_ground(g).exquo(f) + except CoercionFailed: + return NotImplemented + + def __pow__(f, n): + return f.pow(n) + + def __divmod__(f, g): + return f.div(g) + + def __mod__(f, g): + return f.rem(g) + + def __floordiv__(f, g): + if isinstance(g, DMP): + return f.quo(g) + else: + try: + return f.quo_ground(g) + except TypeError: + return NotImplemented + + def __eq__(f, g): + if f is g: + return True + if not isinstance(g, DMP): + return NotImplemented + try: + F, G = f.unify_DMP(g) + except UnificationFailed: + return False + else: + return F._strict_eq(G) + + def _strict_eq(f, g): + raise NotImplementedError + + def eq(f, g, strict=False): + if not strict: + return f == g + else: + return f._strict_eq(g) + + def ne(f, g, strict=False): + return not f.eq(g, strict=strict) + + def __lt__(f, g): + F, G = f.unify_DMP(g) + return F.to_list() < G.to_list() + + def __le__(f, g): + F, G = f.unify_DMP(g) + return F.to_list() <= G.to_list() + + def __gt__(f, g): + F, G = f.unify_DMP(g) + return F.to_list() > G.to_list() + + def __ge__(f, g): + F, G = f.unify_DMP(g) + return F.to_list() >= G.to_list() + + def __bool__(f): + return not f.is_zero + + +class DMP_Python(DMP): + """Dense Multivariate Polynomials over `K`. """ + + __slots__ = ('_rep', 'dom', 'lev') + + @classmethod + def _new(cls, rep, dom, lev): + obj = object.__new__(cls) + obj._rep = rep + obj.lev = lev + obj.dom = dom + return obj + + def _strict_eq(f, g): + if type(f) != type(g): + return False + return f.lev == g.lev and f.dom == g.dom and f._rep == g._rep + + def per(f, rep): + """Create a DMP out of the given representation. """ + return f._new(rep, f.dom, f.lev) + + def ground_new(f, coeff): + """Construct a new ground instance of ``f``. """ + return f._new(dmp_ground(coeff, f.lev), f.dom, f.lev) + + def _one(f): + return f.one(f.lev, f.dom) + + def unify(f, g): + """Unify representations of two multivariate polynomials. """ + # XXX: This function is not really used any more since there is + # unify_DMP now. + if not isinstance(g, DMP) or f.lev != g.lev: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + if f.dom == g.dom: + return f.lev, f.dom, f.per, f._rep, g._rep + else: + lev, dom = f.lev, f.dom.unify(g.dom) + + F = dmp_convert(f._rep, lev, f.dom, dom) + G = dmp_convert(g._rep, lev, g.dom, dom) + + def per(rep): + return f._new(rep, dom, lev) + + return lev, dom, per, F, G + + def to_DUP_Flint(f): + """Convert ``f`` to a Flint representation. """ + return DUP_Flint._new(f._rep, f.dom, f.lev) + + def to_list(f): + """Convert ``f`` to a list representation with native coefficients. """ + return list(f._rep) + + def to_tuple(f): + """Convert ``f`` to a tuple representation with native coefficients. """ + return dmp_to_tuple(f._rep, f.lev) + + def _convert(f, dom): + """Convert the ground domain of ``f``. """ + return f._new(dmp_convert(f._rep, f.lev, f.dom, dom), dom, f.lev) + + def _slice(f, m, n): + """Take a continuous subsequence of terms of ``f``. """ + rep = dup_slice(f._rep, m, n, f.dom) + return f._new(rep, f.dom, f.lev) + + def _slice_lev(f, m, n, j): + """Take a continuous subsequence of terms of ``f``. """ + rep = dmp_slice_in(f._rep, m, n, j, f.lev, f.dom) + return f._new(rep, f.dom, f.lev) + + def _terms(f, order=None): + """Returns all non-zero terms from ``f`` in lex order. """ + return dmp_list_terms(f._rep, f.lev, f.dom, order=order) + + def _lift(f): + """Convert algebraic coefficients to rationals. """ + r = dmp_lift(f._rep, f.lev, f.dom) + return f._new(r, f.dom.dom, f.lev) + + def deflate(f): + """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """ + J, F = dmp_deflate(f._rep, f.lev, f.dom) + return J, f.per(F) + + def inject(f, front=False): + """Inject ground domain generators into ``f``. """ + F, lev = dmp_inject(f._rep, f.lev, f.dom, front=front) + # XXX: domain and level changed here + return f._new(F, f.dom.dom, lev) + + def eject(f, dom, front=False): + """Eject selected generators into the ground domain. """ + F = dmp_eject(f._rep, f.lev, dom, front=front) + # XXX: domain and level changed here + return f._new(F, dom, f.lev - len(dom.symbols)) + + def _exclude(f): + """Remove useless generators from ``f``. """ + J, F, u = dmp_exclude(f._rep, f.lev, f.dom) + # XXX: level changed here + return J, f._new(F, f.dom, u) + + def _permute(f, P): + """Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`. """ + return f.per(dmp_permute(f._rep, P, f.lev, f.dom)) + + def terms_gcd(f): + """Remove GCD of terms from the polynomial ``f``. """ + J, F = dmp_terms_gcd(f._rep, f.lev, f.dom) + return J, f.per(F) + + def _add_ground(f, c): + """Add an element of the ground domain to ``f``. """ + return f.per(dmp_add_ground(f._rep, c, f.lev, f.dom)) + + def _sub_ground(f, c): + """Subtract an element of the ground domain from ``f``. """ + return f.per(dmp_sub_ground(f._rep, c, f.lev, f.dom)) + + def _mul_ground(f, c): + """Multiply ``f`` by a an element of the ground domain. """ + return f.per(dmp_mul_ground(f._rep, c, f.lev, f.dom)) + + def _quo_ground(f, c): + """Quotient of ``f`` by a an element of the ground domain. """ + return f.per(dmp_quo_ground(f._rep, c, f.lev, f.dom)) + + def _exquo_ground(f, c): + """Exact quotient of ``f`` by a an element of the ground domain. """ + return f.per(dmp_exquo_ground(f._rep, c, f.lev, f.dom)) + + def abs(f): + """Make all coefficients in ``f`` positive. """ + return f.per(dmp_abs(f._rep, f.lev, f.dom)) + + def neg(f): + """Negate all coefficients in ``f``. """ + return f.per(dmp_neg(f._rep, f.lev, f.dom)) + + def _add(f, g): + """Add two multivariate polynomials ``f`` and ``g``. """ + return f.per(dmp_add(f._rep, g._rep, f.lev, f.dom)) + + def _sub(f, g): + """Subtract two multivariate polynomials ``f`` and ``g``. """ + return f.per(dmp_sub(f._rep, g._rep, f.lev, f.dom)) + + def _mul(f, g): + """Multiply two multivariate polynomials ``f`` and ``g``. """ + return f.per(dmp_mul(f._rep, g._rep, f.lev, f.dom)) + + def sqr(f): + """Square a multivariate polynomial ``f``. """ + return f.per(dmp_sqr(f._rep, f.lev, f.dom)) + + def _pow(f, n): + """Raise ``f`` to a non-negative power ``n``. """ + return f.per(dmp_pow(f._rep, n, f.lev, f.dom)) + + def _pdiv(f, g): + """Polynomial pseudo-division of ``f`` and ``g``. """ + q, r = dmp_pdiv(f._rep, g._rep, f.lev, f.dom) + return f.per(q), f.per(r) + + def _prem(f, g): + """Polynomial pseudo-remainder of ``f`` and ``g``. """ + return f.per(dmp_prem(f._rep, g._rep, f.lev, f.dom)) + + def _pquo(f, g): + """Polynomial pseudo-quotient of ``f`` and ``g``. """ + return f.per(dmp_pquo(f._rep, g._rep, f.lev, f.dom)) + + def _pexquo(f, g): + """Polynomial exact pseudo-quotient of ``f`` and ``g``. """ + return f.per(dmp_pexquo(f._rep, g._rep, f.lev, f.dom)) + + def _div(f, g): + """Polynomial division with remainder of ``f`` and ``g``. """ + q, r = dmp_div(f._rep, g._rep, f.lev, f.dom) + return f.per(q), f.per(r) + + def _rem(f, g): + """Computes polynomial remainder of ``f`` and ``g``. """ + return f.per(dmp_rem(f._rep, g._rep, f.lev, f.dom)) + + def _quo(f, g): + """Computes polynomial quotient of ``f`` and ``g``. """ + return f.per(dmp_quo(f._rep, g._rep, f.lev, f.dom)) + + def _exquo(f, g): + """Computes polynomial exact quotient of ``f`` and ``g``. """ + return f.per(dmp_exquo(f._rep, g._rep, f.lev, f.dom)) + + def _degree(f, j=0): + """Returns the leading degree of ``f`` in ``x_j``. """ + return dmp_degree_in(f._rep, j, f.lev) + + def degree_list(f): + """Returns a list of degrees of ``f``. """ + return dmp_degree_list(f._rep, f.lev) + + def total_degree(f): + """Returns the total degree of ``f``. """ + return max(sum(m) for m in f.monoms()) + + def LC(f): + """Returns the leading coefficient of ``f``. """ + return dmp_ground_LC(f._rep, f.lev, f.dom) + + def TC(f): + """Returns the trailing coefficient of ``f``. """ + return dmp_ground_TC(f._rep, f.lev, f.dom) + + def _nth(f, N): + """Returns the ``n``-th coefficient of ``f``. """ + return dmp_ground_nth(f._rep, N, f.lev, f.dom) + + def max_norm(f): + """Returns maximum norm of ``f``. """ + return dmp_max_norm(f._rep, f.lev, f.dom) + + def l1_norm(f): + """Returns l1 norm of ``f``. """ + return dmp_l1_norm(f._rep, f.lev, f.dom) + + def l2_norm_squared(f): + """Return squared l2 norm of ``f``. """ + return dmp_l2_norm_squared(f._rep, f.lev, f.dom) + + def clear_denoms(f): + """Clear denominators, but keep the ground domain. """ + coeff, F = dmp_clear_denoms(f._rep, f.lev, f.dom) + return coeff, f.per(F) + + def _integrate(f, m=1, j=0): + """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """ + return f.per(dmp_integrate_in(f._rep, m, j, f.lev, f.dom)) + + def _diff(f, m=1, j=0): + """Computes the ``m``-th order derivative of ``f`` in ``x_j``. """ + return f.per(dmp_diff_in(f._rep, m, j, f.lev, f.dom)) + + def _eval(f, a): + return dmp_eval_in(f._rep, f.dom.convert(a), 0, f.lev, f.dom) + + def _eval_lev(f, a, j): + rep = dmp_eval_in(f._rep, f.dom.convert(a), j, f.lev, f.dom) + return f.new(rep, f.dom, f.lev - 1) + + def _half_gcdex(f, g): + """Half extended Euclidean algorithm, if univariate. """ + s, h = dup_half_gcdex(f._rep, g._rep, f.dom) + return f.per(s), f.per(h) + + def _gcdex(f, g): + """Extended Euclidean algorithm, if univariate. """ + s, t, h = dup_gcdex(f._rep, g._rep, f.dom) + return f.per(s), f.per(t), f.per(h) + + def _invert(f, g): + """Invert ``f`` modulo ``g``, if possible. """ + s = dup_invert(f._rep, g._rep, f.dom) + return f.per(s) + + def _revert(f, n): + """Compute ``f**(-1)`` mod ``x**n``. """ + return f.per(dup_revert(f._rep, n, f.dom)) + + def _subresultants(f, g): + """Computes subresultant PRS sequence of ``f`` and ``g``. """ + R = dmp_subresultants(f._rep, g._rep, f.lev, f.dom) + return list(map(f.per, R)) + + def _resultant_includePRS(f, g): + """Computes resultant of ``f`` and ``g`` via PRS. """ + res, R = dmp_resultant(f._rep, g._rep, f.lev, f.dom, includePRS=True) + if f.lev: + res = f.new(res, f.dom, f.lev - 1) + return res, list(map(f.per, R)) + + def _resultant(f, g): + res = dmp_resultant(f._rep, g._rep, f.lev, f.dom) + if f.lev: + res = f.new(res, f.dom, f.lev - 1) + return res + + def discriminant(f): + """Computes discriminant of ``f``. """ + res = dmp_discriminant(f._rep, f.lev, f.dom) + if f.lev: + res = f.new(res, f.dom, f.lev - 1) + return res + + def _cofactors(f, g): + """Returns GCD of ``f`` and ``g`` and their cofactors. """ + h, cff, cfg = dmp_inner_gcd(f._rep, g._rep, f.lev, f.dom) + return f.per(h), f.per(cff), f.per(cfg) + + def _gcd(f, g): + """Returns polynomial GCD of ``f`` and ``g``. """ + return f.per(dmp_gcd(f._rep, g._rep, f.lev, f.dom)) + + def _lcm(f, g): + """Returns polynomial LCM of ``f`` and ``g``. """ + return f.per(dmp_lcm(f._rep, g._rep, f.lev, f.dom)) + + def _cancel(f, g): + """Cancel common factors in a rational function ``f/g``. """ + cF, cG, F, G = dmp_cancel(f._rep, g._rep, f.lev, f.dom, include=False) + return cF, cG, f.per(F), f.per(G) + + def _cancel_include(f, g): + """Cancel common factors in a rational function ``f/g``. """ + F, G = dmp_cancel(f._rep, g._rep, f.lev, f.dom, include=True) + return f.per(F), f.per(G) + + def _trunc(f, p): + """Reduce ``f`` modulo a constant ``p``. """ + return f.per(dmp_ground_trunc(f._rep, p, f.lev, f.dom)) + + def monic(f): + """Divides all coefficients by ``LC(f)``. """ + return f.per(dmp_ground_monic(f._rep, f.lev, f.dom)) + + def content(f): + """Returns GCD of polynomial coefficients. """ + return dmp_ground_content(f._rep, f.lev, f.dom) + + def primitive(f): + """Returns content and a primitive form of ``f``. """ + cont, F = dmp_ground_primitive(f._rep, f.lev, f.dom) + return cont, f.per(F) + + def _compose(f, g): + """Computes functional composition of ``f`` and ``g``. """ + return f.per(dmp_compose(f._rep, g._rep, f.lev, f.dom)) + + def _decompose(f): + """Computes functional decomposition of ``f``. """ + return list(map(f.per, dup_decompose(f._rep, f.dom))) + + def _shift(f, a): + """Efficiently compute Taylor shift ``f(x + a)``. """ + return f.per(dup_shift(f._rep, a, f.dom)) + + def _shift_list(f, a): + """Efficiently compute Taylor shift ``f(X + A)``. """ + return f.per(dmp_shift(f._rep, a, f.lev, f.dom)) + + def _transform(f, p, q): + """Evaluate functional transformation ``q**n * f(p/q)``.""" + return f.per(dup_transform(f._rep, p._rep, q._rep, f.dom)) + + def _sturm(f): + """Computes the Sturm sequence of ``f``. """ + return list(map(f.per, dup_sturm(f._rep, f.dom))) + + def _cauchy_upper_bound(f): + """Computes the Cauchy upper bound on the roots of ``f``. """ + return dup_cauchy_upper_bound(f._rep, f.dom) + + def _cauchy_lower_bound(f): + """Computes the Cauchy lower bound on the nonzero roots of ``f``. """ + return dup_cauchy_lower_bound(f._rep, f.dom) + + def _mignotte_sep_bound_squared(f): + """Computes the squared Mignotte bound on root separations of ``f``. """ + return dup_mignotte_sep_bound_squared(f._rep, f.dom) + + def _gff_list(f): + """Computes greatest factorial factorization of ``f``. """ + return [ (f.per(g), k) for g, k in dup_gff_list(f._rep, f.dom) ] + + def norm(f): + """Computes ``Norm(f)``.""" + r = dmp_norm(f._rep, f.lev, f.dom) + return f.new(r, f.dom.dom, f.lev) + + def sqf_norm(f): + """Computes square-free norm of ``f``. """ + s, g, r = dmp_sqf_norm(f._rep, f.lev, f.dom) + return s, f.per(g), f.new(r, f.dom.dom, f.lev) + + def sqf_part(f): + """Computes square-free part of ``f``. """ + return f.per(dmp_sqf_part(f._rep, f.lev, f.dom)) + + def sqf_list(f, all=False): + """Returns a list of square-free factors of ``f``. """ + coeff, factors = dmp_sqf_list(f._rep, f.lev, f.dom, all) + return coeff, [ (f.per(g), k) for g, k in factors ] + + def sqf_list_include(f, all=False): + """Returns a list of square-free factors of ``f``. """ + factors = dmp_sqf_list_include(f._rep, f.lev, f.dom, all) + return [ (f.per(g), k) for g, k in factors ] + + def factor_list(f): + """Returns a list of irreducible factors of ``f``. """ + coeff, factors = dmp_factor_list(f._rep, f.lev, f.dom) + return coeff, [ (f.per(g), k) for g, k in factors ] + + def factor_list_include(f): + """Returns a list of irreducible factors of ``f``. """ + factors = dmp_factor_list_include(f._rep, f.lev, f.dom) + return [ (f.per(g), k) for g, k in factors ] + + def _isolate_real_roots(f, eps, inf, sup, fast): + return dup_isolate_real_roots(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) + + def _isolate_real_roots_sqf(f, eps, inf, sup, fast): + return dup_isolate_real_roots_sqf(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) + + def _isolate_all_roots(f, eps, inf, sup, fast): + return dup_isolate_all_roots(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) + + def _isolate_all_roots_sqf(f, eps, inf, sup, fast): + return dup_isolate_all_roots_sqf(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast) + + def _refine_real_root(f, s, t, eps, steps, fast): + return dup_refine_real_root(f._rep, s, t, f.dom, eps=eps, steps=steps, fast=fast) + + def count_real_roots(f, inf=None, sup=None): + """Return the number of real roots of ``f`` in ``[inf, sup]``. """ + return dup_count_real_roots(f._rep, f.dom, inf=inf, sup=sup) + + def count_complex_roots(f, inf=None, sup=None): + """Return the number of complex roots of ``f`` in ``[inf, sup]``. """ + return dup_count_complex_roots(f._rep, f.dom, inf=inf, sup=sup) + + @property + def is_zero(f): + """Returns ``True`` if ``f`` is a zero polynomial. """ + return dmp_zero_p(f._rep, f.lev) + + @property + def is_one(f): + """Returns ``True`` if ``f`` is a unit polynomial. """ + return dmp_one_p(f._rep, f.lev, f.dom) + + @property + def is_ground(f): + """Returns ``True`` if ``f`` is an element of the ground domain. """ + return dmp_ground_p(f._rep, None, f.lev) + + @property + def is_sqf(f): + """Returns ``True`` if ``f`` is a square-free polynomial. """ + return dmp_sqf_p(f._rep, f.lev, f.dom) + + @property + def is_monic(f): + """Returns ``True`` if the leading coefficient of ``f`` is one. """ + return f.dom.is_one(dmp_ground_LC(f._rep, f.lev, f.dom)) + + @property + def is_primitive(f): + """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """ + return f.dom.is_one(dmp_ground_content(f._rep, f.lev, f.dom)) + + @property + def is_linear(f): + """Returns ``True`` if ``f`` is linear in all its variables. """ + return all(sum(monom) <= 1 for monom in dmp_to_dict(f._rep, f.lev, f.dom).keys()) + + @property + def is_quadratic(f): + """Returns ``True`` if ``f`` is quadratic in all its variables. """ + return all(sum(monom) <= 2 for monom in dmp_to_dict(f._rep, f.lev, f.dom).keys()) + + @property + def is_monomial(f): + """Returns ``True`` if ``f`` is zero or has only one term. """ + return len(f.to_dict()) <= 1 + + @property + def is_homogeneous(f): + """Returns ``True`` if ``f`` is a homogeneous polynomial. """ + return f.homogeneous_order() is not None + + @property + def is_irreducible(f): + """Returns ``True`` if ``f`` has no factors over its domain. """ + return dmp_irreducible_p(f._rep, f.lev, f.dom) + + @property + def is_cyclotomic(f): + """Returns ``True`` if ``f`` is a cyclotomic polynomial. """ + if not f.lev: + return dup_cyclotomic_p(f._rep, f.dom) + else: + return False + + +class DUP_Flint(DMP): + """Dense Multivariate Polynomials over `K`. """ + + lev = 0 + + __slots__ = ('_rep', 'dom', '_cls') + + def __reduce__(self): + return self.__class__, (self.to_list(), self.dom, self.lev) + + @classmethod + def _new(cls, rep, dom, lev): + rep = cls._flint_poly(rep[::-1], dom, lev) + return cls.from_rep(rep, dom) + + def to_list(f): + """Convert ``f`` to a list representation with native coefficients. """ + return f._rep.coeffs()[::-1] + + @classmethod + def _flint_poly(cls, rep, dom, lev): + assert _supported_flint_domain(dom) + assert lev == 0 + flint_cls = cls._get_flint_poly_cls(dom) + return flint_cls(rep) + + @classmethod + def _get_flint_poly_cls(cls, dom): + if dom.is_ZZ: + return flint.fmpz_poly + elif dom.is_QQ: + return flint.fmpq_poly + elif dom.is_FF: + return dom._poly_ctx + else: + raise RuntimeError("Domain %s is not supported with flint" % dom) + + @classmethod + def from_rep(cls, rep, dom): + """Create a DMP from the given representation. """ + + if dom.is_ZZ: + assert isinstance(rep, flint.fmpz_poly) + _cls = flint.fmpz_poly + elif dom.is_QQ: + assert isinstance(rep, flint.fmpq_poly) + _cls = flint.fmpq_poly + elif dom.is_FF: + assert isinstance(rep, (flint.nmod_poly, flint.fmpz_mod_poly)) + c = dom.characteristic() + __cls = type(rep) + _cls = lambda e: __cls(e, c) + else: + raise RuntimeError("Domain %s is not supported with flint" % dom) + + obj = object.__new__(cls) + obj.dom = dom + obj._rep = rep + obj._cls = _cls + + return obj + + def _strict_eq(f, g): + if type(f) != type(g): + return False + return f.dom == g.dom and f._rep == g._rep + + def ground_new(f, coeff): + """Construct a new ground instance of ``f``. """ + return f.from_rep(f._cls([coeff]), f.dom) + + def _one(f): + return f.ground_new(f.dom.one) + + def unify(f, g): + """Unify representations of two polynomials. """ + raise RuntimeError + + def to_DMP_Python(f): + """Convert ``f`` to a Python native representation. """ + return DMP_Python._new(f.to_list(), f.dom, f.lev) + + def to_tuple(f): + """Convert ``f`` to a tuple representation with native coefficients. """ + return tuple(f.to_list()) + + def _convert(f, dom): + """Convert the ground domain of ``f``. """ + if dom == QQ and f.dom == ZZ: + return f.from_rep(flint.fmpq_poly(f._rep), dom) + elif _supported_flint_domain(dom) and _supported_flint_domain(f.dom): + # XXX: python-flint should provide a faster way to do this. + return f.to_DMP_Python()._convert(dom).to_DUP_Flint() + else: + raise RuntimeError(f"DUP_Flint: Cannot convert {f.dom} to {dom}") + + def _slice(f, m, n): + """Take a continuous subsequence of terms of ``f``. """ + coeffs = f._rep.coeffs()[m:n] + return f.from_rep(f._cls(coeffs), f.dom) + + def _slice_lev(f, m, n, j): + """Take a continuous subsequence of terms of ``f``. """ + # Only makes sense for multivariate polynomials + raise NotImplementedError + + def _terms(f, order=None): + """Returns all non-zero terms from ``f`` in lex order. """ + if order is None or order.alias == 'lex': + terms = [ ((n,), c) for n, c in enumerate(f._rep.coeffs()) if c ] + return terms[::-1] + else: + # XXX: InverseOrder (ilex) comes here. We could handle that case + # efficiently by reversing the coefficients but it is not clear + # how to test if the order is InverseOrder. + # + # Otherwise why would the order ever be different for univariate + # polynomials? + return f.to_DMP_Python()._terms(order=order) + + def _lift(f): + """Convert algebraic coefficients to rationals. """ + # This is for algebraic number fields which DUP_Flint does not support + raise NotImplementedError + + def deflate(f): + """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """ + # XXX: Check because otherwise this segfaults with python-flint: + # + # >>> flint.fmpz_poly([]).deflation() + # Exception (fmpz_poly_deflate). Division by zero. + # Aborted (core dumped + # + if f.is_zero: + return (1,), f + g, n = f._rep.deflation() + return (n,), f.from_rep(g, f.dom) + + def inject(f, front=False): + """Inject ground domain generators into ``f``. """ + # Ground domain would need to be a poly ring + raise NotImplementedError + + def eject(f, dom, front=False): + """Eject selected generators into the ground domain. """ + # Only makes sense for multivariate polynomials + raise NotImplementedError + + def _exclude(f): + """Remove useless generators from ``f``. """ + # Only makes sense for multivariate polynomials + raise NotImplementedError + + def _permute(f, P): + """Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`. """ + # Only makes sense for multivariate polynomials + raise NotImplementedError + + def terms_gcd(f): + """Remove GCD of terms from the polynomial ``f``. """ + # XXX: python-flint should have primitive, content, etc methods. + J, F = f.to_DMP_Python().terms_gcd() + return J, F.to_DUP_Flint() + + def _add_ground(f, c): + """Add an element of the ground domain to ``f``. """ + return f.from_rep(f._rep + c, f.dom) + + def _sub_ground(f, c): + """Subtract an element of the ground domain from ``f``. """ + return f.from_rep(f._rep - c, f.dom) + + def _mul_ground(f, c): + """Multiply ``f`` by a an element of the ground domain. """ + return f.from_rep(f._rep * c, f.dom) + + def _quo_ground(f, c): + """Quotient of ``f`` by a an element of the ground domain. """ + return f.from_rep(f._rep // c, f.dom) + + def _exquo_ground(f, c): + """Exact quotient of ``f`` by an element of the ground domain. """ + q, r = divmod(f._rep, c) + if r: + raise ExactQuotientFailed(f, c) + return f.from_rep(q, f.dom) + + def abs(f): + """Make all coefficients in ``f`` positive. """ + return f.to_DMP_Python().abs().to_DUP_Flint() + + def neg(f): + """Negate all coefficients in ``f``. """ + return f.from_rep(-f._rep, f.dom) + + def _add(f, g): + """Add two multivariate polynomials ``f`` and ``g``. """ + return f.from_rep(f._rep + g._rep, f.dom) + + def _sub(f, g): + """Subtract two multivariate polynomials ``f`` and ``g``. """ + return f.from_rep(f._rep - g._rep, f.dom) + + def _mul(f, g): + """Multiply two multivariate polynomials ``f`` and ``g``. """ + return f.from_rep(f._rep * g._rep, f.dom) + + def sqr(f): + """Square a multivariate polynomial ``f``. """ + return f.from_rep(f._rep ** 2, f.dom) + + def _pow(f, n): + """Raise ``f`` to a non-negative power ``n``. """ + return f.from_rep(f._rep ** n, f.dom) + + def _pdiv(f, g): + """Polynomial pseudo-division of ``f`` and ``g``. """ + d = f.degree() - g.degree() + 1 + q, r = divmod(g.LC()**d * f._rep, g._rep) + return f.from_rep(q, f.dom), f.from_rep(r, f.dom) + + def _prem(f, g): + """Polynomial pseudo-remainder of ``f`` and ``g``. """ + d = f.degree() - g.degree() + 1 + q = (g.LC()**d * f._rep) % g._rep + return f.from_rep(q, f.dom) + + def _pquo(f, g): + """Polynomial pseudo-quotient of ``f`` and ``g``. """ + d = f.degree() - g.degree() + 1 + r = (g.LC()**d * f._rep) // g._rep + return f.from_rep(r, f.dom) + + def _pexquo(f, g): + """Polynomial exact pseudo-quotient of ``f`` and ``g``. """ + d = f.degree() - g.degree() + 1 + q, r = divmod(g.LC()**d * f._rep, g._rep) + if r: + raise ExactQuotientFailed(f, g) + return f.from_rep(q, f.dom) + + def _div(f, g): + """Polynomial division with remainder of ``f`` and ``g``. """ + if f.dom.is_Field: + q, r = divmod(f._rep, g._rep) + return f.from_rep(q, f.dom), f.from_rep(r, f.dom) + else: + # XXX: python-flint defines division in ZZ[x] differently + q, r = f.to_DMP_Python()._div(g.to_DMP_Python()) + return q.to_DUP_Flint(), r.to_DUP_Flint() + + def _rem(f, g): + """Computes polynomial remainder of ``f`` and ``g``. """ + return f.from_rep(f._rep % g._rep, f.dom) + + def _quo(f, g): + """Computes polynomial quotient of ``f`` and ``g``. """ + return f.from_rep(f._rep // g._rep, f.dom) + + def _exquo(f, g): + """Computes polynomial exact quotient of ``f`` and ``g``. """ + q, r = f._div(g) + if r: + raise ExactQuotientFailed(f, g) + return q + + def _degree(f, j=0): + """Returns the leading degree of ``f`` in ``x_j``. """ + d = f._rep.degree() + if d == -1: + d = ninf + return d + + def degree_list(f): + """Returns a list of degrees of ``f``. """ + return ( f._degree() ,) + + def total_degree(f): + """Returns the total degree of ``f``. """ + return f._degree() + + def LC(f): + """Returns the leading coefficient of ``f``. """ + return f._rep[f._rep.degree()] + + def TC(f): + """Returns the trailing coefficient of ``f``. """ + return f._rep[0] + + def _nth(f, N): + """Returns the ``n``-th coefficient of ``f``. """ + [n] = N + return f._rep[n] + + def max_norm(f): + """Returns maximum norm of ``f``. """ + return f.to_DMP_Python().max_norm() + + def l1_norm(f): + """Returns l1 norm of ``f``. """ + return f.to_DMP_Python().l1_norm() + + def l2_norm_squared(f): + """Return squared l2 norm of ``f``. """ + return f.to_DMP_Python().l2_norm_squared() + + def clear_denoms(f): + """Clear denominators, but keep the ground domain. """ + R = f.dom + if R.is_QQ: + denom = f._rep.denom() + numer = f.from_rep(f._cls(f._rep.numer()), f.dom) + return denom, numer + elif R.is_ZZ or R.is_FiniteField: + return R.one, f + else: + raise NotImplementedError + + def _integrate(f, m=1, j=0): + """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """ + assert j == 0 + if f.dom.is_Field: + rep = f._rep + for i in range(m): + rep = rep.integral() + return f.from_rep(rep, f.dom) + else: + return f.to_DMP_Python()._integrate(m=m, j=j).to_DUP_Flint() + + def _diff(f, m=1, j=0): + """Computes the ``m``-th order derivative of ``f``. """ + assert j == 0 + rep = f._rep + for i in range(m): + rep = rep.derivative() + return f.from_rep(rep, f.dom) + + def _eval(f, a): + # XXX: This method is called with many different input types. Ideally + # we could use e.g. fmpz_poly.__call__ here but more thought needs to + # go into which types this is supposed to be called with and what types + # it should return. + return f.to_DMP_Python()._eval(a) + + def _eval_lev(f, a, j): + # Only makes sense for multivariate polynomials + raise NotImplementedError + + def _half_gcdex(f, g): + """Half extended Euclidean algorithm. """ + s, h = f.to_DMP_Python()._half_gcdex(g.to_DMP_Python()) + return s.to_DUP_Flint(), h.to_DUP_Flint() + + def _gcdex(f, g): + """Extended Euclidean algorithm. """ + h, s, t = f._rep.xgcd(g._rep) + return f.from_rep(s, f.dom), f.from_rep(t, f.dom), f.from_rep(h, f.dom) + + def _invert(f, g): + """Invert ``f`` modulo ``g``, if possible. """ + R = f.dom + if R.is_Field: + gcd, F_inv, _ = f._rep.xgcd(g._rep) + # XXX: Should be gcd != 1 but nmod_poly does not compare equal to + # other types. + if gcd != 0*gcd + 1: + raise NotInvertible("zero divisor") + return f.from_rep(F_inv, R) + else: + # fmpz_poly does not have xgcd or invert and this is not well + # defined in general. + return f.to_DMP_Python()._invert(g.to_DMP_Python()).to_DUP_Flint() + + def _revert(f, n): + """Compute ``f**(-1)`` mod ``x**n``. """ + # XXX: Use fmpz_series etc for reversion? + # Maybe python-flint should provide revert for fmpz_poly... + return f.to_DMP_Python()._revert(n).to_DUP_Flint() + + def _subresultants(f, g): + """Computes subresultant PRS sequence of ``f`` and ``g``. """ + # XXX: Maybe _fmpz_poly_pseudo_rem_cohen could be used... + R = f.to_DMP_Python()._subresultants(g.to_DMP_Python()) + return [ g.to_DUP_Flint() for g in R ] + + def _resultant_includePRS(f, g): + """Computes resultant of ``f`` and ``g`` via PRS. """ + # XXX: Maybe _fmpz_poly_pseudo_rem_cohen could be used... + res, R = f.to_DMP_Python()._resultant_includePRS(g.to_DMP_Python()) + return res, [ g.to_DUP_Flint() for g in R ] + + def _resultant(f, g): + """Computes resultant of ``f`` and ``g``. """ + # XXX: Use fmpz_mpoly etc when possible... + return f.to_DMP_Python()._resultant(g.to_DMP_Python()) + + def discriminant(f): + """Computes discriminant of ``f``. """ + # XXX: Use fmpz_mpoly etc when possible... + return f.to_DMP_Python().discriminant() + + def _cofactors(f, g): + """Returns GCD of ``f`` and ``g`` and their cofactors. """ + h = f.gcd(g) + return h, f.exquo(h), g.exquo(h) + + def _gcd(f, g): + """Returns polynomial GCD of ``f`` and ``g``. """ + return f.from_rep(f._rep.gcd(g._rep), f.dom) + + def _lcm(f, g): + """Returns polynomial LCM of ``f`` and ``g``. """ + # XXX: python-flint should have a lcm method + if not (f and g): + return f.ground_new(f.dom.zero) + + l = f._mul(g)._exquo(f._gcd(g)) + + if l.dom.is_Field: + l = l.monic() + elif l.LC() < 0: + l = l.neg() + + return l + + def _cancel(f, g): + """Cancel common factors in a rational function ``f/g``. """ + assert f.dom == g.dom + R = f.dom + + # Think carefully about how to handle denominators and coefficient + # canonicalisation if more domains are permitted... + assert R.is_ZZ or R.is_QQ or R.is_FiniteField + + if R.is_FiniteField: + h = f._gcd(g) + F, G = f.exquo(h), g.exquo(h) + return R.one, R.one, F, G + + if R.is_QQ: + cG, F = f.clear_denoms() + cF, G = g.clear_denoms() + else: + cG, F = R.one, f + cF, G = R.one, g + + cH = cF.gcd(cG) + cF, cG = cF // cH, cG // cH + + H = F._gcd(G) + F, G = F.exquo(H), G.exquo(H) + + f_neg = F.LC() < 0 + g_neg = G.LC() < 0 + + if f_neg and g_neg: + F, G = F.neg(), G.neg() + elif f_neg: + cF, F = -cF, F.neg() + elif g_neg: + cF, G = -cF, G.neg() + + return cF, cG, F, G + + def _cancel_include(f, g): + """Cancel common factors in a rational function ``f/g``. """ + cF, cG, F, G = f._cancel(g) + return F._mul_ground(cF), G._mul_ground(cG) + + def _trunc(f, p): + """Reduce ``f`` modulo a constant ``p``. """ + return f.to_DMP_Python()._trunc(p).to_DUP_Flint() + + def monic(f): + """Divides all coefficients by ``LC(f)``. """ + # XXX: python-flint should add monic + return f._exquo_ground(f.LC()) + + def content(f): + """Returns GCD of polynomial coefficients. """ + # XXX: python-flint should have a content method + return f.to_DMP_Python().content() + + def primitive(f): + """Returns content and a primitive form of ``f``. """ + cont = f.content() + if f.is_zero: + return f.dom.zero, f + prim = f._exquo_ground(cont) + return cont, prim + + def _compose(f, g): + """Computes functional composition of ``f`` and ``g``. """ + return f.from_rep(f._rep(g._rep), f.dom) + + def _decompose(f): + """Computes functional decomposition of ``f``. """ + return [ g.to_DUP_Flint() for g in f.to_DMP_Python()._decompose() ] + + def _shift(f, a): + """Efficiently compute Taylor shift ``f(x + a)``. """ + x_plus_a = f._cls([a, f.dom.one]) + return f.from_rep(f._rep(x_plus_a), f.dom) + + def _transform(f, p, q): + """Evaluate functional transformation ``q**n * f(p/q)``.""" + F, P, Q = f.to_DMP_Python(), p.to_DMP_Python(), q.to_DMP_Python() + return F.transform(P, Q).to_DUP_Flint() + + def _sturm(f): + """Computes the Sturm sequence of ``f``. """ + return [ g.to_DUP_Flint() for g in f.to_DMP_Python()._sturm() ] + + def _cauchy_upper_bound(f): + """Computes the Cauchy upper bound on the roots of ``f``. """ + return f.to_DMP_Python()._cauchy_upper_bound() + + def _cauchy_lower_bound(f): + """Computes the Cauchy lower bound on the nonzero roots of ``f``. """ + return f.to_DMP_Python()._cauchy_lower_bound() + + def _mignotte_sep_bound_squared(f): + """Computes the squared Mignotte bound on root separations of ``f``. """ + return f.to_DMP_Python()._mignotte_sep_bound_squared() + + def _gff_list(f): + """Computes greatest factorial factorization of ``f``. """ + F = f.to_DMP_Python() + return [ (g.to_DUP_Flint(), k) for g, k in F.gff_list() ] + + def norm(f): + """Computes ``Norm(f)``.""" + # This is for algebraic number fields which DUP_Flint does not support + raise NotImplementedError + + def sqf_norm(f): + """Computes square-free norm of ``f``. """ + # This is for algebraic number fields which DUP_Flint does not support + raise NotImplementedError + + def sqf_part(f): + """Computes square-free part of ``f``. """ + return f._exquo(f._gcd(f._diff())) + + def sqf_list(f, all=False): + """Returns a list of square-free factors of ``f``. """ + # XXX: python-flint should provide square free factorisation. + coeff, factors = f.to_DMP_Python().sqf_list(all=all) + return coeff, [ (g.to_DUP_Flint(), k) for g, k in factors ] + + def sqf_list_include(f, all=False): + """Returns a list of square-free factors of ``f``. """ + factors = f.to_DMP_Python().sqf_list_include(all=all) + return [ (g.to_DUP_Flint(), k) for g, k in factors ] + + def factor_list(f): + """Returns a list of irreducible factors of ``f``. """ + + if f.dom.is_ZZ or f.dom.is_FF: + # python-flint matches polys here + coeff, factors = f._rep.factor() + factors = [ (f.from_rep(g, f.dom), k) for g, k in factors ] + + elif f.dom.is_QQ: + # python-flint returns monic factors over QQ whereas polys returns + # denominator free factors. + coeff, factors = f._rep.factor() + factors_monic = [ (f.from_rep(g, f.dom), k) for g, k in factors ] + + # Absorb the denominators into coeff + factors = [] + for g, k in factors_monic: + d, g = g.clear_denoms() + coeff /= d**k + factors.append((g, k)) + + else: + # Check carefully when adding more domains here... + raise RuntimeError("Domain %s is not supported with flint" % f.dom) + + # We need to match the way that polys orders the factors + factors = f._sort_factors(factors) + + return coeff, factors + + def factor_list_include(f): + """Returns a list of irreducible factors of ``f``. """ + # XXX: factor_list_include seems to be broken in general: + # + # >>> Poly(2*(x - 1)**3, x).factor_list_include() + # [(Poly(2*x - 2, x, domain='ZZ'), 3)] + # + # Let's not try to implement it here. + factors = f.to_DMP_Python().factor_list_include() + return [ (g.to_DUP_Flint(), k) for g, k in factors ] + + def _sort_factors(f, factors): + """Sort a list of factors to canonical order. """ + # Convert the factors to lists and use _sort_factors from polys + factors = [ (g.to_list(), k) for g, k in factors ] + factors = _sort_factors(factors, multiple=True) + to_dup_flint = lambda g: f.from_rep(f._cls(g[::-1]), f.dom) + return [ (to_dup_flint(g), k) for g, k in factors ] + + def _isolate_real_roots(f, eps, inf, sup, fast): + return f.to_DMP_Python()._isolate_real_roots(eps, inf, sup, fast) + + def _isolate_real_roots_sqf(f, eps, inf, sup, fast): + return f.to_DMP_Python()._isolate_real_roots_sqf(eps, inf, sup, fast) + + def _isolate_all_roots(f, eps, inf, sup, fast): + # fmpz_poly and fmpq_poly have a complex_roots method that could be + # used here. It probably makes more sense to add analogous methods in + # python-flint though. + return f.to_DMP_Python()._isolate_all_roots(eps, inf, sup, fast) + + def _isolate_all_roots_sqf(f, eps, inf, sup, fast): + return f.to_DMP_Python()._isolate_all_roots_sqf(eps, inf, sup, fast) + + def _refine_real_root(f, s, t, eps, steps, fast): + return f.to_DMP_Python()._refine_real_root(s, t, eps, steps, fast) + + def count_real_roots(f, inf=None, sup=None): + """Return the number of real roots of ``f`` in ``[inf, sup]``. """ + return f.to_DMP_Python().count_real_roots(inf=inf, sup=sup) + + def count_complex_roots(f, inf=None, sup=None): + """Return the number of complex roots of ``f`` in ``[inf, sup]``. """ + return f.to_DMP_Python().count_complex_roots(inf=inf, sup=sup) + + @property + def is_zero(f): + """Returns ``True`` if ``f`` is a zero polynomial. """ + return not f._rep + + @property + def is_one(f): + """Returns ``True`` if ``f`` is a unit polynomial. """ + return f._rep == f.dom.one + + @property + def is_ground(f): + """Returns ``True`` if ``f`` is an element of the ground domain. """ + return f._rep.degree() <= 0 + + @property + def is_linear(f): + """Returns ``True`` if ``f`` is linear in all its variables. """ + return f._rep.degree() <= 1 + + @property + def is_quadratic(f): + """Returns ``True`` if ``f`` is quadratic in all its variables. """ + return f._rep.degree() <= 2 + + @property + def is_monomial(f): + """Returns ``True`` if ``f`` is zero or has only one term. """ + fr = f._rep + return fr.degree() < 0 or not any(fr[n] for n in range(fr.degree())) + + @property + def is_monic(f): + """Returns ``True`` if the leading coefficient of ``f`` is one. """ + return f.LC() == f.dom.one + + @property + def is_primitive(f): + """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """ + return f.to_DMP_Python().is_primitive + + @property + def is_homogeneous(f): + """Returns ``True`` if ``f`` is a homogeneous polynomial. """ + return f.to_DMP_Python().is_homogeneous + + @property + def is_sqf(f): + """Returns ``True`` if ``f`` is a square-free polynomial. """ + g = f._rep.gcd(f._rep.derivative()) + return g.degree() <= 0 + + @property + def is_irreducible(f): + """Returns ``True`` if ``f`` has no factors over its domain. """ + _, factors = f._rep.factor() + if len(factors) == 0: + return True + elif len(factors) == 1: + return factors[0][1] == 1 + else: + return False + + @property + def is_cyclotomic(f): + """Returns ``True`` if ``f`` is a cyclotomic polynomial. """ + if f.dom.is_QQ: + try: + f = f.convert(ZZ) + except CoercionFailed: + return False + if f.dom.is_ZZ: + return bool(f._rep.is_cyclotomic()) + else: + # This is what dup_cyclotomic_p does... + return False + + +def init_normal_DMF(num, den, lev, dom): + return DMF(dmp_normal(num, lev, dom), + dmp_normal(den, lev, dom), dom, lev) + + +class DMF(PicklableWithSlots, CantSympify): + """Dense Multivariate Fractions over `K`. """ + + __slots__ = ('num', 'den', 'lev', 'dom') + + def __init__(self, rep, dom, lev=None): + num, den, lev = self._parse(rep, dom, lev) + num, den = dmp_cancel(num, den, lev, dom) + + self.num = num + self.den = den + self.lev = lev + self.dom = dom + + @classmethod + def new(cls, rep, dom, lev=None): + num, den, lev = cls._parse(rep, dom, lev) + + obj = object.__new__(cls) + + obj.num = num + obj.den = den + obj.lev = lev + obj.dom = dom + + return obj + + def ground_new(self, rep): + return self.new(rep, self.dom, self.lev) + + @classmethod + def _parse(cls, rep, dom, lev=None): + if isinstance(rep, tuple): + num, den = rep + + if lev is not None: + if isinstance(num, dict): + num = dmp_from_dict(num, lev, dom) + + if isinstance(den, dict): + den = dmp_from_dict(den, lev, dom) + else: + num, num_lev = dmp_validate(num) + den, den_lev = dmp_validate(den) + + if num_lev == den_lev: + lev = num_lev + else: + raise ValueError('inconsistent number of levels') + + if dmp_zero_p(den, lev): + raise ZeroDivisionError('fraction denominator') + + if dmp_zero_p(num, lev): + den = dmp_one(lev, dom) + else: + if dmp_negative_p(den, lev, dom): + num = dmp_neg(num, lev, dom) + den = dmp_neg(den, lev, dom) + else: + num = rep + + if lev is not None: + if isinstance(num, dict): + num = dmp_from_dict(num, lev, dom) + elif not isinstance(num, list): + num = dmp_ground(dom.convert(num), lev) + else: + num, lev = dmp_validate(num) + + den = dmp_one(lev, dom) + + return num, den, lev + + def __repr__(f): + return "%s((%s, %s), %s)" % (f.__class__.__name__, f.num, f.den, f.dom) + + def __hash__(f): + return hash((f.__class__.__name__, dmp_to_tuple(f.num, f.lev), + dmp_to_tuple(f.den, f.lev), f.lev, f.dom)) + + def poly_unify(f, g): + """Unify a multivariate fraction and a polynomial. """ + if not isinstance(g, DMP) or f.lev != g.lev: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + if f.dom == g.dom: + return (f.lev, f.dom, f.per, (f.num, f.den), g._rep) + else: + lev, dom = f.lev, f.dom.unify(g.dom) + + F = (dmp_convert(f.num, lev, f.dom, dom), + dmp_convert(f.den, lev, f.dom, dom)) + + G = dmp_convert(g._rep, lev, g.dom, dom) + + def per(num, den, cancel=True, kill=False, lev=lev): + if kill: + if not lev: + return num/den + else: + lev = lev - 1 + + if cancel: + num, den = dmp_cancel(num, den, lev, dom) + + return f.__class__.new((num, den), dom, lev) + + return lev, dom, per, F, G + + def frac_unify(f, g): + """Unify representations of two multivariate fractions. """ + if not isinstance(g, DMF) or f.lev != g.lev: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + if f.dom == g.dom: + return (f.lev, f.dom, f.per, (f.num, f.den), + (g.num, g.den)) + else: + lev, dom = f.lev, f.dom.unify(g.dom) + + F = (dmp_convert(f.num, lev, f.dom, dom), + dmp_convert(f.den, lev, f.dom, dom)) + + G = (dmp_convert(g.num, lev, g.dom, dom), + dmp_convert(g.den, lev, g.dom, dom)) + + def per(num, den, cancel=True, kill=False, lev=lev): + if kill: + if not lev: + return num/den + else: + lev = lev - 1 + + if cancel: + num, den = dmp_cancel(num, den, lev, dom) + + return f.__class__.new((num, den), dom, lev) + + return lev, dom, per, F, G + + def per(f, num, den, cancel=True, kill=False): + """Create a DMF out of the given representation. """ + lev, dom = f.lev, f.dom + + if kill: + if not lev: + return num/den + else: + lev -= 1 + + if cancel: + num, den = dmp_cancel(num, den, lev, dom) + + return f.__class__.new((num, den), dom, lev) + + def half_per(f, rep, kill=False): + """Create a DMP out of the given representation. """ + lev = f.lev + + if kill: + if not lev: + return rep + else: + lev -= 1 + + return DMP(rep, f.dom, lev) + + @classmethod + def zero(cls, lev, dom): + return cls.new(0, dom, lev) + + @classmethod + def one(cls, lev, dom): + return cls.new(1, dom, lev) + + def numer(f): + """Returns the numerator of ``f``. """ + return f.half_per(f.num) + + def denom(f): + """Returns the denominator of ``f``. """ + return f.half_per(f.den) + + def cancel(f): + """Remove common factors from ``f.num`` and ``f.den``. """ + return f.per(f.num, f.den) + + def neg(f): + """Negate all coefficients in ``f``. """ + return f.per(dmp_neg(f.num, f.lev, f.dom), f.den, cancel=False) + + def add_ground(f, c): + """Add an element of the ground domain to ``f``. """ + return f + f.ground_new(c) + + def add(f, g): + """Add two multivariate fractions ``f`` and ``g``. """ + if isinstance(g, DMP): + lev, dom, per, (F_num, F_den), G = f.poly_unify(g) + num, den = dmp_add_mul(F_num, F_den, G, lev, dom), F_den + else: + lev, dom, per, F, G = f.frac_unify(g) + (F_num, F_den), (G_num, G_den) = F, G + + num = dmp_add(dmp_mul(F_num, G_den, lev, dom), + dmp_mul(F_den, G_num, lev, dom), lev, dom) + den = dmp_mul(F_den, G_den, lev, dom) + + return per(num, den) + + def sub(f, g): + """Subtract two multivariate fractions ``f`` and ``g``. """ + if isinstance(g, DMP): + lev, dom, per, (F_num, F_den), G = f.poly_unify(g) + num, den = dmp_sub_mul(F_num, F_den, G, lev, dom), F_den + else: + lev, dom, per, F, G = f.frac_unify(g) + (F_num, F_den), (G_num, G_den) = F, G + + num = dmp_sub(dmp_mul(F_num, G_den, lev, dom), + dmp_mul(F_den, G_num, lev, dom), lev, dom) + den = dmp_mul(F_den, G_den, lev, dom) + + return per(num, den) + + def mul(f, g): + """Multiply two multivariate fractions ``f`` and ``g``. """ + if isinstance(g, DMP): + lev, dom, per, (F_num, F_den), G = f.poly_unify(g) + num, den = dmp_mul(F_num, G, lev, dom), F_den + else: + lev, dom, per, F, G = f.frac_unify(g) + (F_num, F_den), (G_num, G_den) = F, G + + num = dmp_mul(F_num, G_num, lev, dom) + den = dmp_mul(F_den, G_den, lev, dom) + + return per(num, den) + + def pow(f, n): + """Raise ``f`` to a non-negative power ``n``. """ + if isinstance(n, int): + num, den = f.num, f.den + if n < 0: + num, den, n = den, num, -n + return f.per(dmp_pow(num, n, f.lev, f.dom), + dmp_pow(den, n, f.lev, f.dom), cancel=False) + else: + raise TypeError("``int`` expected, got %s" % type(n)) + + def quo(f, g): + """Computes quotient of fractions ``f`` and ``g``. """ + if isinstance(g, DMP): + lev, dom, per, (F_num, F_den), G = f.poly_unify(g) + num, den = F_num, dmp_mul(F_den, G, lev, dom) + else: + lev, dom, per, F, G = f.frac_unify(g) + (F_num, F_den), (G_num, G_den) = F, G + + num = dmp_mul(F_num, G_den, lev, dom) + den = dmp_mul(F_den, G_num, lev, dom) + + return per(num, den) + + exquo = quo + + def invert(f, check=True): + """Computes inverse of a fraction ``f``. """ + return f.per(f.den, f.num, cancel=False) + + @property + def is_zero(f): + """Returns ``True`` if ``f`` is a zero fraction. """ + return dmp_zero_p(f.num, f.lev) + + @property + def is_one(f): + """Returns ``True`` if ``f`` is a unit fraction. """ + return dmp_one_p(f.num, f.lev, f.dom) and \ + dmp_one_p(f.den, f.lev, f.dom) + + def __neg__(f): + return f.neg() + + def __add__(f, g): + if isinstance(g, (DMP, DMF)): + return f.add(g) + elif g in f.dom: + return f.add_ground(f.dom.convert(g)) + + try: + return f.add(f.half_per(g)) + except (TypeError, CoercionFailed, NotImplementedError): + return NotImplemented + + def __radd__(f, g): + return f.__add__(g) + + def __sub__(f, g): + if isinstance(g, (DMP, DMF)): + return f.sub(g) + + try: + return f.sub(f.half_per(g)) + except (TypeError, CoercionFailed, NotImplementedError): + return NotImplemented + + def __rsub__(f, g): + return (-f).__add__(g) + + def __mul__(f, g): + if isinstance(g, (DMP, DMF)): + return f.mul(g) + + try: + return f.mul(f.half_per(g)) + except (TypeError, CoercionFailed, NotImplementedError): + return NotImplemented + + def __rmul__(f, g): + return f.__mul__(g) + + def __pow__(f, n): + return f.pow(n) + + def __truediv__(f, g): + if isinstance(g, (DMP, DMF)): + return f.quo(g) + + try: + return f.quo(f.half_per(g)) + except (TypeError, CoercionFailed, NotImplementedError): + return NotImplemented + + def __rtruediv__(self, g): + return self.invert(check=False)*g + + def __eq__(f, g): + try: + if isinstance(g, DMP): + _, _, _, (F_num, F_den), G = f.poly_unify(g) + + if f.lev == g.lev: + return dmp_one_p(F_den, f.lev, f.dom) and F_num == G + else: + _, _, _, F, G = f.frac_unify(g) + + if f.lev == g.lev: + return F == G + except UnificationFailed: + pass + + return False + + def __ne__(f, g): + try: + if isinstance(g, DMP): + _, _, _, (F_num, F_den), G = f.poly_unify(g) + + if f.lev == g.lev: + return not (dmp_one_p(F_den, f.lev, f.dom) and F_num == G) + else: + _, _, _, F, G = f.frac_unify(g) + + if f.lev == g.lev: + return F != G + except UnificationFailed: + pass + + return True + + def __lt__(f, g): + _, _, _, F, G = f.frac_unify(g) + return F < G + + def __le__(f, g): + _, _, _, F, G = f.frac_unify(g) + return F <= G + + def __gt__(f, g): + _, _, _, F, G = f.frac_unify(g) + return F > G + + def __ge__(f, g): + _, _, _, F, G = f.frac_unify(g) + return F >= G + + def __bool__(f): + return not dmp_zero_p(f.num, f.lev) + + +def init_normal_ANP(rep, mod, dom): + return ANP(dup_normal(rep, dom), + dup_normal(mod, dom), dom) + + +class ANP(CantSympify): + """Dense Algebraic Number Polynomials over a field. """ + + __slots__ = ('_rep', '_mod', 'dom') + + def __new__(cls, rep, mod, dom): + if isinstance(rep, DMP): + pass + elif type(rep) is dict: # don't use isinstance + rep = DMP(dup_from_dict(rep, dom), dom, 0) + else: + if isinstance(rep, list): + rep = [dom.convert(a) for a in rep] + else: + rep = [dom.convert(rep)] + rep = DMP(dup_strip(rep), dom, 0) + + if isinstance(mod, DMP): + pass + elif isinstance(mod, dict): + mod = DMP(dup_from_dict(mod, dom), dom, 0) + else: + mod = DMP(dup_strip(mod), dom, 0) + + return cls.new(rep, mod, dom) + + @classmethod + def new(cls, rep, mod, dom): + if not (rep.dom == mod.dom == dom): + raise RuntimeError("Inconsistent domain") + obj = super().__new__(cls) + obj._rep = rep + obj._mod = mod + obj.dom = dom + return obj + + # XXX: It should be possible to use __getnewargs__ rather than __reduce__ + # but it doesn't work for some reason. Probably this would be easier if + # python-flint supported pickling for polynomial types. + def __reduce__(self): + return ANP, (self.rep, self.mod, self.dom) + + @property + def rep(self): + return self._rep.to_list() + + @property + def mod(self): + return self.mod_to_list() + + def to_DMP(self): + return self._rep + + def mod_to_DMP(self): + return self._mod + + def per(f, rep): + return f.new(rep, f._mod, f.dom) + + def __repr__(f): + return "%s(%s, %s, %s)" % (f.__class__.__name__, f._rep.to_list(), f._mod.to_list(), f.dom) + + def __hash__(f): + return hash((f.__class__.__name__, f.to_tuple(), f._mod.to_tuple(), f.dom)) + + def convert(f, dom): + """Convert ``f`` to a ``ANP`` over a new domain. """ + if f.dom == dom: + return f + else: + return f.new(f._rep.convert(dom), f._mod.convert(dom), dom) + + def unify(f, g): + """Unify representations of two algebraic numbers. """ + + # XXX: This unify method is not used any more because unify_ANP is used + # instead. + + if not isinstance(g, ANP) or f.mod != g.mod: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + if f.dom == g.dom: + return f.dom, f.per, f.rep, g.rep, f.mod + else: + dom = f.dom.unify(g.dom) + + F = dup_convert(f.rep, f.dom, dom) + G = dup_convert(g.rep, g.dom, dom) + + if dom != f.dom and dom != g.dom: + mod = dup_convert(f.mod, f.dom, dom) + else: + if dom == f.dom: + mod = f.mod + else: + mod = g.mod + + per = lambda rep: ANP(rep, mod, dom) + + return dom, per, F, G, mod + + def unify_ANP(f, g): + """Unify and return ``DMP`` instances of ``f`` and ``g``. """ + if not isinstance(g, ANP) or f._mod != g._mod: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + # The domain is almost always QQ but there are some tests involving ZZ + if f.dom != g.dom: + dom = f.dom.unify(g.dom) + f = f.convert(dom) + g = g.convert(dom) + + return f._rep, g._rep, f._mod, f.dom + + @classmethod + def zero(cls, mod, dom): + return ANP(0, mod, dom) + + @classmethod + def one(cls, mod, dom): + return ANP(1, mod, dom) + + def to_dict(f): + """Convert ``f`` to a dict representation with native coefficients. """ + return f._rep.to_dict() + + def to_sympy_dict(f): + """Convert ``f`` to a dict representation with SymPy coefficients. """ + rep = dmp_to_dict(f.rep, 0, f.dom) + + for k, v in rep.items(): + rep[k] = f.dom.to_sympy(v) + + return rep + + def to_list(f): + """Convert ``f`` to a list representation with native coefficients. """ + return f._rep.to_list() + + def mod_to_list(f): + """Return ``f.mod`` as a list with native coefficients. """ + return f._mod.to_list() + + def to_sympy_list(f): + """Convert ``f`` to a list representation with SymPy coefficients. """ + return [ f.dom.to_sympy(c) for c in f.to_list() ] + + def to_tuple(f): + """ + Convert ``f`` to a tuple representation with native coefficients. + + This is needed for hashing. + """ + return f._rep.to_tuple() + + @classmethod + def from_list(cls, rep, mod, dom): + return ANP(dup_strip(list(map(dom.convert, rep))), mod, dom) + + def add_ground(f, c): + """Add an element of the ground domain to ``f``. """ + return f.per(f._rep.add_ground(c)) + + def sub_ground(f, c): + """Subtract an element of the ground domain from ``f``. """ + return f.per(f._rep.sub_ground(c)) + + def mul_ground(f, c): + """Multiply ``f`` by an element of the ground domain. """ + return f.per(f._rep.mul_ground(c)) + + def quo_ground(f, c): + """Quotient of ``f`` by an element of the ground domain. """ + return f.per(f._rep.quo_ground(c)) + + def neg(f): + return f.per(f._rep.neg()) + + def add(f, g): + F, G, mod, dom = f.unify_ANP(g) + return f.new(F.add(G), mod, dom) + + def sub(f, g): + F, G, mod, dom = f.unify_ANP(g) + return f.new(F.sub(G), mod, dom) + + def mul(f, g): + F, G, mod, dom = f.unify_ANP(g) + return f.new(F.mul(G).rem(mod), mod, dom) + + def pow(f, n): + """Raise ``f`` to a non-negative power ``n``. """ + if not isinstance(n, int): + raise TypeError("``int`` expected, got %s" % type(n)) + + mod = f._mod + F = f._rep + + if n < 0: + F, n = F.invert(mod), -n + + # XXX: Need a pow_mod method for DMP + return f.new(F.pow(n).rem(f._mod), mod, f.dom) + + def exquo(f, g): + F, G, mod, dom = f.unify_ANP(g) + return f.new(F.mul(G.invert(mod)).rem(mod), mod, dom) + + def div(f, g): + return f.exquo(g), f.zero(f._mod, f.dom) + + def quo(f, g): + return f.exquo(g) + + def rem(f, g): + F, G, mod, dom = f.unify_ANP(g) + s, h = F.half_gcdex(G) + + if h.is_one: + return f.zero(mod, dom) + else: + raise NotInvertible("zero divisor") + + def LC(f): + """Returns the leading coefficient of ``f``. """ + return f._rep.LC() + + def TC(f): + """Returns the trailing coefficient of ``f``. """ + return f._rep.TC() + + @property + def is_zero(f): + """Returns ``True`` if ``f`` is a zero algebraic number. """ + return f._rep.is_zero + + @property + def is_one(f): + """Returns ``True`` if ``f`` is a unit algebraic number. """ + return f._rep.is_one + + @property + def is_ground(f): + """Returns ``True`` if ``f`` is an element of the ground domain. """ + return f._rep.is_ground + + def __pos__(f): + return f + + def __neg__(f): + return f.neg() + + def __add__(f, g): + if isinstance(g, ANP): + return f.add(g) + try: + g = f.dom.convert(g) + except CoercionFailed: + return NotImplemented + else: + return f.add_ground(g) + + def __radd__(f, g): + return f.__add__(g) + + def __sub__(f, g): + if isinstance(g, ANP): + return f.sub(g) + try: + g = f.dom.convert(g) + except CoercionFailed: + return NotImplemented + else: + return f.sub_ground(g) + + def __rsub__(f, g): + return (-f).__add__(g) + + def __mul__(f, g): + if isinstance(g, ANP): + return f.mul(g) + try: + g = f.dom.convert(g) + except CoercionFailed: + return NotImplemented + else: + return f.mul_ground(g) + + def __rmul__(f, g): + return f.__mul__(g) + + def __pow__(f, n): + return f.pow(n) + + def __divmod__(f, g): + return f.div(g) + + def __mod__(f, g): + return f.rem(g) + + def __truediv__(f, g): + if isinstance(g, ANP): + return f.quo(g) + try: + g = f.dom.convert(g) + except CoercionFailed: + return NotImplemented + else: + return f.quo_ground(g) + + def __eq__(f, g): + try: + F, G, _, _ = f.unify_ANP(g) + except UnificationFailed: + return NotImplemented + return F == G + + def __ne__(f, g): + try: + F, G, _, _ = f.unify_ANP(g) + except UnificationFailed: + return NotImplemented + return F != G + + def __lt__(f, g): + F, G, _, _ = f.unify_ANP(g) + return F < G + + def __le__(f, g): + F, G, _, _ = f.unify_ANP(g) + return F <= G + + def __gt__(f, g): + F, G, _, _ = f.unify_ANP(g) + return F > G + + def __ge__(f, g): + F, G, _, _ = f.unify_ANP(g) + return F >= G + + def __bool__(f): + return bool(f._rep) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyconfig.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..75731f7ac4e4f8784ff8f999cc3537bfa3c6659a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyconfig.py @@ -0,0 +1,67 @@ +"""Configuration utilities for polynomial manipulation algorithms. """ + + +from contextlib import contextmanager + +_default_config = { + 'USE_COLLINS_RESULTANT': False, + 'USE_SIMPLIFY_GCD': True, + 'USE_HEU_GCD': True, + + 'USE_IRREDUCIBLE_IN_FACTOR': False, + 'USE_CYCLOTOMIC_FACTOR': True, + + 'EEZ_RESTART_IF_NEEDED': True, + 'EEZ_NUMBER_OF_CONFIGS': 3, + 'EEZ_NUMBER_OF_TRIES': 5, + 'EEZ_MODULUS_STEP': 2, + + 'GF_IRRED_METHOD': 'rabin', + 'GF_FACTOR_METHOD': 'zassenhaus', + + 'GROEBNER': 'buchberger', +} + +_current_config = {} + +@contextmanager +def using(**kwargs): + for k, v in kwargs.items(): + setup(k, v) + + yield + + for k in kwargs.keys(): + setup(k) + +def setup(key, value=None): + """Assign a value to (or reset) a configuration item. """ + key = key.upper() + + if value is not None: + _current_config[key] = value + else: + _current_config[key] = _default_config[key] + + +def query(key): + """Ask for a value of the given configuration item. """ + return _current_config.get(key.upper(), None) + + +def configure(): + """Initialized configuration of polys module. """ + from os import getenv + + for key, default in _default_config.items(): + value = getenv('SYMPY_' + key) + + if value is not None: + try: + _current_config[key] = eval(value) + except NameError: + _current_config[key] = value + else: + _current_config[key] = default + +configure() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyerrors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyerrors.py new file mode 100644 index 0000000000000000000000000000000000000000..79385ffaf6746386f8f108c3e02992dcaf4a4f55 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyerrors.py @@ -0,0 +1,183 @@ +"""Definitions of common exceptions for `polys` module. """ + + +from sympy.utilities import public + +@public +class BasePolynomialError(Exception): + """Base class for polynomial related exceptions. """ + + def new(self, *args): + raise NotImplementedError("abstract base class") + +@public +class ExactQuotientFailed(BasePolynomialError): + + def __init__(self, f, g, dom=None): + self.f, self.g, self.dom = f, g, dom + + def __str__(self): # pragma: no cover + from sympy.printing.str import sstr + + if self.dom is None: + return "%s does not divide %s" % (sstr(self.g), sstr(self.f)) + else: + return "%s does not divide %s in %s" % (sstr(self.g), sstr(self.f), sstr(self.dom)) + + def new(self, f, g): + return self.__class__(f, g, self.dom) + +@public +class PolynomialDivisionFailed(BasePolynomialError): + + def __init__(self, f, g, domain): + self.f = f + self.g = g + self.domain = domain + + def __str__(self): + if self.domain.is_EX: + msg = "You may want to use a different simplification algorithm. Note " \ + "that in general it's not possible to guarantee to detect zero " \ + "in this domain." + elif not self.domain.is_Exact: + msg = "Your working precision or tolerance of computations may be set " \ + "improperly. Adjust those parameters of the coefficient domain " \ + "and try again." + else: + msg = "Zero detection is guaranteed in this coefficient domain. This " \ + "may indicate a bug in SymPy or the domain is user defined and " \ + "doesn't implement zero detection properly." + + return "couldn't reduce degree in a polynomial division algorithm when " \ + "dividing %s by %s. This can happen when it's not possible to " \ + "detect zero in the coefficient domain. The domain of computation " \ + "is %s. %s" % (self.f, self.g, self.domain, msg) + +@public +class OperationNotSupported(BasePolynomialError): + + def __init__(self, poly, func): + self.poly = poly + self.func = func + + def __str__(self): # pragma: no cover + return "`%s` operation not supported by %s representation" % (self.func, self.poly.rep.__class__.__name__) + +@public +class HeuristicGCDFailed(BasePolynomialError): + pass + +class ModularGCDFailed(BasePolynomialError): + pass + +@public +class HomomorphismFailed(BasePolynomialError): + pass + +@public +class IsomorphismFailed(BasePolynomialError): + pass + +@public +class ExtraneousFactors(BasePolynomialError): + pass + +@public +class EvaluationFailed(BasePolynomialError): + pass + +@public +class RefinementFailed(BasePolynomialError): + pass + +@public +class CoercionFailed(BasePolynomialError): + pass + +@public +class NotInvertible(BasePolynomialError): + pass + +@public +class NotReversible(BasePolynomialError): + pass + +@public +class NotAlgebraic(BasePolynomialError): + pass + +@public +class DomainError(BasePolynomialError): + pass + +@public +class PolynomialError(BasePolynomialError): + pass + +@public +class UnificationFailed(BasePolynomialError): + pass + +@public +class UnsolvableFactorError(BasePolynomialError): + """Raised if ``roots`` is called with strict=True and a polynomial + having a factor whose solutions are not expressible in radicals + is encountered.""" + +@public +class GeneratorsError(BasePolynomialError): + pass + +@public +class GeneratorsNeeded(GeneratorsError): + pass + +@public +class ComputationFailed(BasePolynomialError): + + def __init__(self, func, nargs, exc): + self.func = func + self.nargs = nargs + self.exc = exc + + def __str__(self): + return "%s(%s) failed without generators" % (self.func, ', '.join(map(str, self.exc.exprs[:self.nargs]))) + +@public +class UnivariatePolynomialError(PolynomialError): + pass + +@public +class MultivariatePolynomialError(PolynomialError): + pass + +@public +class PolificationFailed(PolynomialError): + + def __init__(self, opt, origs, exprs, seq=False): + if not seq: + self.orig = origs + self.expr = exprs + self.origs = [origs] + self.exprs = [exprs] + else: + self.origs = origs + self.exprs = exprs + + self.opt = opt + self.seq = seq + + def __str__(self): # pragma: no cover + if not self.seq: + return "Cannot construct a polynomial from %s" % str(self.orig) + else: + return "Cannot construct polynomials from %s" % ', '.join(map(str, self.origs)) + +@public +class OptionError(BasePolynomialError): + pass + +@public +class FlagError(OptionError): + pass diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyfuncs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..b412123f7383c68177a88df8817e921d96f6d5af --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyfuncs.py @@ -0,0 +1,321 @@ +"""High-level polynomials manipulation functions. """ + + +from sympy.core import S, Basic, symbols, Dummy +from sympy.polys.polyerrors import ( + PolificationFailed, ComputationFailed, + MultivariatePolynomialError, OptionError) +from sympy.polys.polyoptions import allowed_flags, build_options +from sympy.polys.polytools import poly_from_expr, Poly +from sympy.polys.specialpolys import ( + symmetric_poly, interpolating_poly) +from sympy.polys.rings import sring +from sympy.utilities import numbered_symbols, take, public + +@public +def symmetrize(F, *gens, **args): + r""" + Rewrite a polynomial in terms of elementary symmetric polynomials. + + A symmetric polynomial is a multivariate polynomial that remains invariant + under any variable permutation, i.e., if `f = f(x_1, x_2, \dots, x_n)`, + then `f = f(x_{i_1}, x_{i_2}, \dots, x_{i_n})`, where + `(i_1, i_2, \dots, i_n)` is a permutation of `(1, 2, \dots, n)` (an + element of the group `S_n`). + + Returns a tuple of symmetric polynomials ``(f1, f2, ..., fn)`` such that + ``f = f1 + f2 + ... + fn``. + + Examples + ======== + + >>> from sympy.polys.polyfuncs import symmetrize + >>> from sympy.abc import x, y + + >>> symmetrize(x**2 + y**2) + (-2*x*y + (x + y)**2, 0) + + >>> symmetrize(x**2 + y**2, formal=True) + (s1**2 - 2*s2, 0, [(s1, x + y), (s2, x*y)]) + + >>> symmetrize(x**2 - y**2) + (-2*x*y + (x + y)**2, -2*y**2) + + >>> symmetrize(x**2 - y**2, formal=True) + (s1**2 - 2*s2, -2*y**2, [(s1, x + y), (s2, x*y)]) + + """ + allowed_flags(args, ['formal', 'symbols']) + + iterable = True + + if not hasattr(F, '__iter__'): + iterable = False + F = [F] + + R, F = sring(F, *gens, **args) + gens = R.symbols + + opt = build_options(gens, args) + symbols = opt.symbols + symbols = [next(symbols) for i in range(len(gens))] + + result = [] + + for f in F: + p, r, m = f.symmetrize() + result.append((p.as_expr(*symbols), r.as_expr(*gens))) + + polys = [(s, g.as_expr()) for s, (_, g) in zip(symbols, m)] + + if not opt.formal: + for i, (sym, non_sym) in enumerate(result): + result[i] = (sym.subs(polys), non_sym) + + if not iterable: + result, = result + + if not opt.formal: + return result + else: + if iterable: + return result, polys + else: + return result + (polys,) + + +@public +def horner(f, *gens, **args): + """ + Rewrite a polynomial in Horner form. + + Among other applications, evaluation of a polynomial at a point is optimal + when it is applied using the Horner scheme ([1]). + + Examples + ======== + + >>> from sympy.polys.polyfuncs import horner + >>> from sympy.abc import x, y, a, b, c, d, e + + >>> horner(9*x**4 + 8*x**3 + 7*x**2 + 6*x + 5) + x*(x*(x*(9*x + 8) + 7) + 6) + 5 + + >>> horner(a*x**4 + b*x**3 + c*x**2 + d*x + e) + e + x*(d + x*(c + x*(a*x + b))) + + >>> f = 4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y + + >>> horner(f, wrt=x) + x*(x*y*(4*y + 2) + y*(2*y + 1)) + + >>> horner(f, wrt=y) + y*(x*y*(4*x + 2) + x*(2*x + 1)) + + References + ========== + [1] - https://en.wikipedia.org/wiki/Horner_scheme + + """ + allowed_flags(args, []) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + return exc.expr + + form, gen = S.Zero, F.gen + + if F.is_univariate: + for coeff in F.all_coeffs(): + form = form*gen + coeff + else: + F, gens = Poly(F, gen), gens[1:] + + for coeff in F.all_coeffs(): + form = form*gen + horner(coeff, *gens, **args) + + return form + + +@public +def interpolate(data, x): + """ + Construct an interpolating polynomial for the data points + evaluated at point x (which can be symbolic or numeric). + + Examples + ======== + + >>> from sympy.polys.polyfuncs import interpolate + >>> from sympy.abc import a, b, x + + A list is interpreted as though it were paired with a range starting + from 1: + + >>> interpolate([1, 4, 9, 16], x) + x**2 + + This can be made explicit by giving a list of coordinates: + + >>> interpolate([(1, 1), (2, 4), (3, 9)], x) + x**2 + + The (x, y) coordinates can also be given as keys and values of a + dictionary (and the points need not be equispaced): + + >>> interpolate([(-1, 2), (1, 2), (2, 5)], x) + x**2 + 1 + >>> interpolate({-1: 2, 1: 2, 2: 5}, x) + x**2 + 1 + + If the interpolation is going to be used only once then the + value of interest can be passed instead of passing a symbol: + + >>> interpolate([1, 4, 9], 5) + 25 + + Symbolic coordinates are also supported: + + >>> [(i,interpolate((a, b), i)) for i in range(1, 4)] + [(1, a), (2, b), (3, -a + 2*b)] + """ + n = len(data) + + if isinstance(data, dict): + if x in data: + return S(data[x]) + X, Y = list(zip(*data.items())) + else: + if isinstance(data[0], tuple): + X, Y = list(zip(*data)) + if x in X: + return S(Y[X.index(x)]) + else: + if x in range(1, n + 1): + return S(data[x - 1]) + Y = list(data) + X = list(range(1, n + 1)) + + try: + return interpolating_poly(n, x, X, Y).expand() + except ValueError: + d = Dummy() + return interpolating_poly(n, d, X, Y).expand().subs(d, x) + + +@public +def rational_interpolate(data, degnum, X=symbols('x')): + """ + Returns a rational interpolation, where the data points are element of + any integral domain. + + The first argument contains the data (as a list of coordinates). The + ``degnum`` argument is the degree in the numerator of the rational + function. Setting it too high will decrease the maximal degree in the + denominator for the same amount of data. + + Examples + ======== + + >>> from sympy.polys.polyfuncs import rational_interpolate + + >>> data = [(1, -210), (2, -35), (3, 105), (4, 231), (5, 350), (6, 465)] + >>> rational_interpolate(data, 2) + (105*x**2 - 525)/(x + 1) + + Values do not need to be integers: + + >>> from sympy import sympify + >>> x = [1, 2, 3, 4, 5, 6] + >>> y = sympify("[-1, 0, 2, 22/5, 7, 68/7]") + >>> rational_interpolate(zip(x, y), 2) + (3*x**2 - 7*x + 2)/(x + 1) + + The symbol for the variable can be changed if needed: + >>> from sympy import symbols + >>> z = symbols('z') + >>> rational_interpolate(data, 2, X=z) + (105*z**2 - 525)/(z + 1) + + References + ========== + + .. [1] Algorithm is adapted from: + http://axiom-wiki.newsynthesis.org/RationalInterpolation + + """ + from sympy.matrices.dense import ones + + xdata, ydata = list(zip(*data)) + + k = len(xdata) - degnum - 1 + if k < 0: + raise OptionError("Too few values for the required degree.") + c = ones(degnum + k + 1, degnum + k + 2) + for j in range(max(degnum, k)): + for i in range(degnum + k + 1): + c[i, j + 1] = c[i, j]*xdata[i] + for j in range(k + 1): + for i in range(degnum + k + 1): + c[i, degnum + k + 1 - j] = -c[i, k - j]*ydata[i] + r = c.nullspace()[0] + return (sum(r[i] * X**i for i in range(degnum + 1)) + / sum(r[i + degnum + 1] * X**i for i in range(k + 1))) + + +@public +def viete(f, roots=None, *gens, **args): + """ + Generate Viete's formulas for ``f``. + + Examples + ======== + + >>> from sympy.polys.polyfuncs import viete + >>> from sympy import symbols + + >>> x, a, b, c, r1, r2 = symbols('x,a:c,r1:3') + + >>> viete(a*x**2 + b*x + c, [r1, r2], x) + [(r1 + r2, -b/a), (r1*r2, c/a)] + + """ + allowed_flags(args, []) + + if isinstance(roots, Basic): + gens, roots = (roots,) + gens, None + + try: + f, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('viete', 1, exc) + + if f.is_multivariate: + raise MultivariatePolynomialError( + "multivariate polynomials are not allowed") + + n = f.degree() + + if n < 1: + raise ValueError( + "Cannot derive Viete's formulas for a constant polynomial") + + if roots is None: + roots = numbered_symbols('r', start=1) + + roots = take(roots, n) + + if n != len(roots): + raise ValueError("required %s roots, got %s" % (n, len(roots))) + + lc, coeffs = f.LC(), f.all_coeffs() + result, sign = [], -1 + + for i, coeff in enumerate(coeffs[1:]): + poly = symmetric_poly(i + 1, roots) + coeff = sign*(coeff/lc) + result.append((poly, coeff)) + sign = -sign + + return result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polymatrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polymatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2a58efc3ebfd85507ac2b0cfd31230e55ded66 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polymatrix.py @@ -0,0 +1,292 @@ +from sympy.core.expr import Expr +from sympy.core.symbol import Dummy +from sympy.core.sympify import _sympify + +from sympy.polys.polyerrors import CoercionFailed +from sympy.polys.polytools import Poly, parallel_poly_from_expr +from sympy.polys.domains import QQ + +from sympy.polys.matrices import DomainMatrix +from sympy.polys.matrices.domainscalar import DomainScalar + + +class MutablePolyDenseMatrix: + """ + A mutable matrix of objects from poly module or to operate with them. + + Examples + ======== + + >>> from sympy.polys.polymatrix import PolyMatrix + >>> from sympy import Symbol, Poly + >>> x = Symbol('x') + >>> pm1 = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(x**3, x), Poly(-1 + x, x)]]) + >>> v1 = PolyMatrix([[1, 0], [-1, 0]], x) + >>> pm1*v1 + PolyMatrix([ + [ x**2 + x, 0], + [x**3 - x + 1, 0]], ring=QQ[x]) + + >>> pm1.ring + ZZ[x] + + >>> v1*pm1 + PolyMatrix([ + [ x**2, -x], + [-x**2, x]], ring=QQ[x]) + + >>> pm2 = PolyMatrix([[Poly(x**2, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(1, x, domain='QQ'), \ + Poly(x**3, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**3, x, domain='QQ')]]) + >>> v2 = PolyMatrix([1, 0, 0, 0, 0, 0], x) + >>> v2.ring + QQ[x] + >>> pm2*v2 + PolyMatrix([[x**2]], ring=QQ[x]) + + """ + + def __new__(cls, *args, ring=None): + + if not args: + # PolyMatrix(ring=QQ[x]) + if ring is None: + raise TypeError("The ring needs to be specified for an empty PolyMatrix") + rows, cols, items, gens = 0, 0, [], () + elif isinstance(args[0], list): + elements, gens = args[0], args[1:] + if not elements: + # PolyMatrix([]) + rows, cols, items = 0, 0, [] + elif isinstance(elements[0], (list, tuple)): + # PolyMatrix([[1, 2]], x) + rows, cols = len(elements), len(elements[0]) + items = [e for row in elements for e in row] + else: + # PolyMatrix([1, 2], x) + rows, cols = len(elements), 1 + items = elements + elif [type(a) for a in args[:3]] == [int, int, list]: + # PolyMatrix(2, 2, [1, 2, 3, 4], x) + rows, cols, items, gens = args[0], args[1], args[2], args[3:] + elif [type(a) for a in args[:3]] == [int, int, type(lambda: 0)]: + # PolyMatrix(2, 2, lambda i, j: i+j, x) + rows, cols, func, gens = args[0], args[1], args[2], args[3:] + items = [func(i, j) for i in range(rows) for j in range(cols)] + else: + raise TypeError("Invalid arguments") + + # PolyMatrix([[1]], x, y) vs PolyMatrix([[1]], (x, y)) + if len(gens) == 1 and isinstance(gens[0], tuple): + gens = gens[0] + # gens is now a tuple (x, y) + + return cls.from_list(rows, cols, items, gens, ring) + + @classmethod + def from_list(cls, rows, cols, items, gens, ring): + + # items can be Expr, Poly, or a mix of Expr and Poly + items = [_sympify(item) for item in items] + if items and all(isinstance(item, Poly) for item in items): + polys = True + else: + polys = False + + # Identify the ring for the polys + if ring is not None: + # Parse a domain string like 'QQ[x]' + if isinstance(ring, str): + ring = Poly(0, Dummy(), domain=ring).domain + elif polys: + p = items[0] + for p2 in items[1:]: + p, _ = p.unify(p2) + ring = p.domain[p.gens] + else: + items, info = parallel_poly_from_expr(items, gens, field=True) + ring = info['domain'][info['gens']] + polys = True + + # Efficiently convert when all elements are Poly + if polys: + p_ring = Poly(0, ring.symbols, domain=ring.domain) + to_ring = ring.ring.from_list + convert_poly = lambda p: to_ring(p.unify(p_ring)[0].rep.to_list()) + elements = [convert_poly(p) for p in items] + else: + convert_expr = ring.from_sympy + elements = [convert_expr(e.as_expr()) for e in items] + + # Convert to domain elements and construct DomainMatrix + elements_lol = [[elements[i*cols + j] for j in range(cols)] for i in range(rows)] + dm = DomainMatrix(elements_lol, (rows, cols), ring) + return cls.from_dm(dm) + + @classmethod + def from_dm(cls, dm): + obj = super().__new__(cls) + dm = dm.to_sparse() + R = dm.domain + obj._dm = dm + obj.ring = R + obj.domain = R.domain + obj.gens = R.symbols + return obj + + def to_Matrix(self): + return self._dm.to_Matrix() + + @classmethod + def from_Matrix(cls, other, *gens, ring=None): + return cls(*other.shape, other.flat(), *gens, ring=ring) + + def set_gens(self, gens): + return self.from_Matrix(self.to_Matrix(), gens) + + def __repr__(self): + if self.rows * self.cols: + return 'Poly' + repr(self.to_Matrix())[:-1] + f', ring={self.ring})' + else: + return f'PolyMatrix({self.rows}, {self.cols}, [], ring={self.ring})' + + @property + def shape(self): + return self._dm.shape + + @property + def rows(self): + return self.shape[0] + + @property + def cols(self): + return self.shape[1] + + def __len__(self): + return self.rows * self.cols + + def __getitem__(self, key): + + def to_poly(v): + ground = self._dm.domain.domain + gens = self._dm.domain.symbols + return Poly(v.to_dict(), gens, domain=ground) + + dm = self._dm + + if isinstance(key, slice): + items = dm.flat()[key] + return [to_poly(item) for item in items] + elif isinstance(key, int): + i, j = divmod(key, self.cols) + e = dm[i,j] + return to_poly(e.element) + + i, j = key + if isinstance(i, int) and isinstance(j, int): + return to_poly(dm[i, j].element) + else: + return self.from_dm(dm[i, j]) + + def __eq__(self, other): + if not isinstance(self, type(other)): + return NotImplemented + return self._dm == other._dm + + def __add__(self, other): + if isinstance(other, type(self)): + return self.from_dm(self._dm + other._dm) + return NotImplemented + + def __sub__(self, other): + if isinstance(other, type(self)): + return self.from_dm(self._dm - other._dm) + return NotImplemented + + def __mul__(self, other): + if isinstance(other, type(self)): + return self.from_dm(self._dm * other._dm) + elif isinstance(other, int): + other = _sympify(other) + if isinstance(other, Expr): + Kx = self.ring + try: + other_ds = DomainScalar(Kx.from_sympy(other), Kx) + except (CoercionFailed, ValueError): + other_ds = DomainScalar.from_sympy(other) + return self.from_dm(self._dm * other_ds) + return NotImplemented + + def __rmul__(self, other): + if isinstance(other, int): + other = _sympify(other) + if isinstance(other, Expr): + other_ds = DomainScalar.from_sympy(other) + return self.from_dm(other_ds * self._dm) + return NotImplemented + + def __truediv__(self, other): + + if isinstance(other, Poly): + other = other.as_expr() + elif isinstance(other, int): + other = _sympify(other) + if not isinstance(other, Expr): + return NotImplemented + + other = self.domain.from_sympy(other) + inverse = self.ring.convert_from(1/other, self.domain) + inverse = DomainScalar(inverse, self.ring) + dm = self._dm * inverse + return self.from_dm(dm) + + def __neg__(self): + return self.from_dm(-self._dm) + + def transpose(self): + return self.from_dm(self._dm.transpose()) + + def row_join(self, other): + dm = DomainMatrix.hstack(self._dm, other._dm) + return self.from_dm(dm) + + def col_join(self, other): + dm = DomainMatrix.vstack(self._dm, other._dm) + return self.from_dm(dm) + + def applyfunc(self, func): + M = self.to_Matrix().applyfunc(func) + return self.from_Matrix(M, self.gens) + + @classmethod + def eye(cls, n, gens): + return cls.from_dm(DomainMatrix.eye(n, QQ[gens])) + + @classmethod + def zeros(cls, m, n, gens): + return cls.from_dm(DomainMatrix.zeros((m, n), QQ[gens])) + + def rref(self, simplify='ignore', normalize_last='ignore'): + # If this is K[x] then computes RREF in ground field K. + if not (self.domain.is_Field and all(p.is_ground for p in self)): + raise ValueError("PolyMatrix rref is only for ground field elements") + dm = self._dm + dm_ground = dm.convert_to(dm.domain.domain) + dm_rref, pivots = dm_ground.rref() + dm_rref = dm_rref.convert_to(dm.domain) + return self.from_dm(dm_rref), pivots + + def nullspace(self): + # If this is K[x] then computes nullspace in ground field K. + if not (self.domain.is_Field and all(p.is_ground for p in self)): + raise ValueError("PolyMatrix nullspace is only for ground field elements") + dm = self._dm + K, Kx = self.domain, self.ring + dm_null_rows = dm.convert_to(K).nullspace(divide_last=True).convert_to(Kx) + dm_null = dm_null_rows.transpose() + dm_basis = [dm_null[:,i] for i in range(dm_null.shape[1])] + return [self.from_dm(dmvec) for dmvec in dm_basis] + + def rank(self): + return self.cols - len(self.nullspace()) + +MutablePolyMatrix = PolyMatrix = MutablePolyDenseMatrix diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyoptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyoptions.py new file mode 100644 index 0000000000000000000000000000000000000000..7b9bd989c4d5676aab32e65c62996137b3e0b73e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyoptions.py @@ -0,0 +1,791 @@ +"""Options manager for :class:`~.Poly` and public API functions. """ + +from __future__ import annotations + +__all__ = ["Options"] + +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.sympify import sympify +from sympy.polys.polyerrors import GeneratorsError, OptionError, FlagError +from sympy.utilities import numbered_symbols, topological_sort, public +from sympy.utilities.iterables import has_dups, is_sequence + +import sympy.polys + +import re + +class Option: + """Base class for all kinds of options. """ + + option: str | None = None + + is_Flag = False + + requires: list[str] = [] + excludes: list[str] = [] + + after: list[str] = [] + before: list[str] = [] + + @classmethod + def default(cls): + return None + + @classmethod + def preprocess(cls, option): + return None + + @classmethod + def postprocess(cls, options): + pass + + +class Flag(Option): + """Base class for all kinds of flags. """ + + is_Flag = True + + +class BooleanOption(Option): + """An option that must have a boolean value or equivalent assigned. """ + + @classmethod + def preprocess(cls, value): + if value in [True, False]: + return bool(value) + else: + raise OptionError("'%s' must have a boolean value assigned, got %s" % (cls.option, value)) + + +class OptionType(type): + """Base type for all options that does registers options. """ + + def __init__(cls, *args, **kwargs): + @property + def getter(self): + try: + return self[cls.option] + except KeyError: + return cls.default() + + setattr(Options, cls.option, getter) + Options.__options__[cls.option] = cls + + +@public +class Options(dict): + """ + Options manager for polynomial manipulation module. + + Examples + ======== + + >>> from sympy.polys.polyoptions import Options + >>> from sympy.polys.polyoptions import build_options + + >>> from sympy.abc import x, y, z + + >>> Options((x, y, z), {'domain': 'ZZ'}) + {'auto': False, 'domain': ZZ, 'gens': (x, y, z)} + + >>> build_options((x, y, z), {'domain': 'ZZ'}) + {'auto': False, 'domain': ZZ, 'gens': (x, y, z)} + + **Options** + + * Expand --- boolean option + * Gens --- option + * Wrt --- option + * Sort --- option + * Order --- option + * Field --- boolean option + * Greedy --- boolean option + * Domain --- option + * Split --- boolean option + * Gaussian --- boolean option + * Extension --- option + * Modulus --- option + * Symmetric --- boolean option + * Strict --- boolean option + + **Flags** + + * Auto --- boolean flag + * Frac --- boolean flag + * Formal --- boolean flag + * Polys --- boolean flag + * Include --- boolean flag + * All --- boolean flag + * Gen --- flag + * Series --- boolean flag + + """ + + __order__ = None + __options__: dict[str, type[Option]] = {} + + gens: tuple[Expr, ...] + domain: sympy.polys.domains.Domain + + def __init__(self, gens, args, flags=None, strict=False): + dict.__init__(self) + + if gens and args.get('gens', ()): + raise OptionError( + "both '*gens' and keyword argument 'gens' supplied") + elif gens: + args = dict(args) + args['gens'] = gens + + defaults = args.pop('defaults', {}) + + def preprocess_options(args): + for option, value in args.items(): + try: + cls = self.__options__[option] + except KeyError: + raise OptionError("'%s' is not a valid option" % option) + + if issubclass(cls, Flag): + if flags is None or option not in flags: + if strict: + raise OptionError("'%s' flag is not allowed in this context" % option) + + if value is not None: + self[option] = cls.preprocess(value) + + preprocess_options(args) + + for key in dict(defaults): + if key in self: + del defaults[key] + else: + for option in self.keys(): + cls = self.__options__[option] + + if key in cls.excludes: + del defaults[key] + break + + preprocess_options(defaults) + + for option in self.keys(): + cls = self.__options__[option] + + for require_option in cls.requires: + if self.get(require_option) is None: + raise OptionError("'%s' option is only allowed together with '%s'" % (option, require_option)) + + for exclude_option in cls.excludes: + if self.get(exclude_option) is not None: + raise OptionError("'%s' option is not allowed together with '%s'" % (option, exclude_option)) + + for option in self.__order__: + self.__options__[option].postprocess(self) + + @classmethod + def _init_dependencies_order(cls): + """Resolve the order of options' processing. """ + if cls.__order__ is None: + vertices, edges = [], set() + + for name, option in cls.__options__.items(): + vertices.append(name) + + edges.update((_name, name) for _name in option.after) + + edges.update((name, _name) for _name in option.before) + + try: + cls.__order__ = topological_sort((vertices, list(edges))) + except ValueError: + raise RuntimeError( + "cycle detected in sympy.polys options framework") + + def clone(self, updates={}): + """Clone ``self`` and update specified options. """ + obj = dict.__new__(self.__class__) + + for option, value in self.items(): + obj[option] = value + + for option, value in updates.items(): + obj[option] = value + + return obj + + def __setattr__(self, attr, value): + if attr in self.__options__: + self[attr] = value + else: + super().__setattr__(attr, value) + + @property + def args(self): + args = {} + + for option, value in self.items(): + if value is not None and option != 'gens': + cls = self.__options__[option] + + if not issubclass(cls, Flag): + args[option] = value + + return args + + @property + def options(self): + options = {} + + for option, cls in self.__options__.items(): + if not issubclass(cls, Flag): + options[option] = getattr(self, option) + + return options + + @property + def flags(self): + flags = {} + + for option, cls in self.__options__.items(): + if issubclass(cls, Flag): + flags[option] = getattr(self, option) + + return flags + + +class Expand(BooleanOption, metaclass=OptionType): + """``expand`` option to polynomial manipulation functions. """ + + option = 'expand' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return True + + +class Gens(Option, metaclass=OptionType): + """``gens`` option to polynomial manipulation functions. """ + + option = 'gens' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return () + + @classmethod + def preprocess(cls, gens): + if isinstance(gens, Basic): + gens = (gens,) + elif len(gens) == 1 and is_sequence(gens[0]): + gens = gens[0] + + if gens == (None,): + gens = () + elif has_dups(gens): + raise GeneratorsError("duplicated generators: %s" % str(gens)) + elif any(gen.is_commutative is False for gen in gens): + raise GeneratorsError("non-commutative generators: %s" % str(gens)) + + return tuple(gens) + + +class Wrt(Option, metaclass=OptionType): + """``wrt`` option to polynomial manipulation functions. """ + + option = 'wrt' + + requires: list[str] = [] + excludes: list[str] = [] + + _re_split = re.compile(r"\s*,\s*|\s+") + + @classmethod + def preprocess(cls, wrt): + if isinstance(wrt, Basic): + return [str(wrt)] + elif isinstance(wrt, str): + wrt = wrt.strip() + if wrt.endswith(','): + raise OptionError('Bad input: missing parameter.') + if not wrt: + return [] + return list(cls._re_split.split(wrt)) + elif hasattr(wrt, '__getitem__'): + return list(map(str, wrt)) + else: + raise OptionError("invalid argument for 'wrt' option") + + +class Sort(Option, metaclass=OptionType): + """``sort`` option to polynomial manipulation functions. """ + + option = 'sort' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return [] + + @classmethod + def preprocess(cls, sort): + if isinstance(sort, str): + return [ gen.strip() for gen in sort.split('>') ] + elif hasattr(sort, '__getitem__'): + return list(map(str, sort)) + else: + raise OptionError("invalid argument for 'sort' option") + + +class Order(Option, metaclass=OptionType): + """``order`` option to polynomial manipulation functions. """ + + option = 'order' + + requires: list[str] = [] + excludes: list[str] = [] + + @classmethod + def default(cls): + return sympy.polys.orderings.lex + + @classmethod + def preprocess(cls, order): + return sympy.polys.orderings.monomial_key(order) + + +class Field(BooleanOption, metaclass=OptionType): + """``field`` option to polynomial manipulation functions. """ + + option = 'field' + + requires: list[str] = [] + excludes = ['domain', 'split', 'gaussian'] + + +class Greedy(BooleanOption, metaclass=OptionType): + """``greedy`` option to polynomial manipulation functions. """ + + option = 'greedy' + + requires: list[str] = [] + excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric'] + + +class Composite(BooleanOption, metaclass=OptionType): + """``composite`` option to polynomial manipulation functions. """ + + option = 'composite' + + @classmethod + def default(cls): + return None + + requires: list[str] = [] + excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric'] + + +class Domain(Option, metaclass=OptionType): + """``domain`` option to polynomial manipulation functions. """ + + option = 'domain' + + requires: list[str] = [] + excludes = ['field', 'greedy', 'split', 'gaussian', 'extension'] + + after = ['gens'] + + _re_realfield = re.compile(r"^(R|RR)(_(\d+))?$") + _re_complexfield = re.compile(r"^(C|CC)(_(\d+))?$") + _re_finitefield = re.compile(r"^(FF|GF)\((\d+)\)$") + _re_polynomial = re.compile(r"^(Z|ZZ|Q|QQ|ZZ_I|QQ_I|R|RR|C|CC)\[(.+)\]$") + _re_fraction = re.compile(r"^(Z|ZZ|Q|QQ)\((.+)\)$") + _re_algebraic = re.compile(r"^(Q|QQ)\<(.+)\>$") + + @classmethod + def preprocess(cls, domain): + if isinstance(domain, sympy.polys.domains.Domain): + return domain + elif hasattr(domain, 'to_domain'): + return domain.to_domain() + elif isinstance(domain, str): + if domain in ['Z', 'ZZ']: + return sympy.polys.domains.ZZ + + if domain in ['Q', 'QQ']: + return sympy.polys.domains.QQ + + if domain == 'ZZ_I': + return sympy.polys.domains.ZZ_I + + if domain == 'QQ_I': + return sympy.polys.domains.QQ_I + + if domain == 'EX': + return sympy.polys.domains.EX + + r = cls._re_realfield.match(domain) + + if r is not None: + _, _, prec = r.groups() + + if prec is None: + return sympy.polys.domains.RR + else: + return sympy.polys.domains.RealField(int(prec)) + + r = cls._re_complexfield.match(domain) + + if r is not None: + _, _, prec = r.groups() + + if prec is None: + return sympy.polys.domains.CC + else: + return sympy.polys.domains.ComplexField(int(prec)) + + r = cls._re_finitefield.match(domain) + + if r is not None: + return sympy.polys.domains.FF(int(r.groups()[1])) + + r = cls._re_polynomial.match(domain) + + if r is not None: + ground, gens = r.groups() + + gens = list(map(sympify, gens.split(','))) + + if ground in ['Z', 'ZZ']: + return sympy.polys.domains.ZZ.poly_ring(*gens) + elif ground in ['Q', 'QQ']: + return sympy.polys.domains.QQ.poly_ring(*gens) + elif ground in ['R', 'RR']: + return sympy.polys.domains.RR.poly_ring(*gens) + elif ground == 'ZZ_I': + return sympy.polys.domains.ZZ_I.poly_ring(*gens) + elif ground == 'QQ_I': + return sympy.polys.domains.QQ_I.poly_ring(*gens) + else: + return sympy.polys.domains.CC.poly_ring(*gens) + + r = cls._re_fraction.match(domain) + + if r is not None: + ground, gens = r.groups() + + gens = list(map(sympify, gens.split(','))) + + if ground in ['Z', 'ZZ']: + return sympy.polys.domains.ZZ.frac_field(*gens) + else: + return sympy.polys.domains.QQ.frac_field(*gens) + + r = cls._re_algebraic.match(domain) + + if r is not None: + gens = list(map(sympify, r.groups()[1].split(','))) + return sympy.polys.domains.QQ.algebraic_field(*gens) + + raise OptionError('expected a valid domain specification, got %s' % domain) + + @classmethod + def postprocess(cls, options): + if 'gens' in options and 'domain' in options and options['domain'].is_Composite and \ + (set(options['domain'].symbols) & set(options['gens'])): + raise GeneratorsError( + "ground domain and generators interfere together") + elif ('gens' not in options or not options['gens']) and \ + 'domain' in options and options['domain'] == sympy.polys.domains.EX: + raise GeneratorsError("you have to provide generators because EX domain was requested") + + +class Split(BooleanOption, metaclass=OptionType): + """``split`` option to polynomial manipulation functions. """ + + option = 'split' + + requires: list[str] = [] + excludes = ['field', 'greedy', 'domain', 'gaussian', 'extension', + 'modulus', 'symmetric'] + + @classmethod + def postprocess(cls, options): + if 'split' in options: + raise NotImplementedError("'split' option is not implemented yet") + + +class Gaussian(BooleanOption, metaclass=OptionType): + """``gaussian`` option to polynomial manipulation functions. """ + + option = 'gaussian' + + requires: list[str] = [] + excludes = ['field', 'greedy', 'domain', 'split', 'extension', + 'modulus', 'symmetric'] + + @classmethod + def postprocess(cls, options): + if 'gaussian' in options and options['gaussian'] is True: + options['domain'] = sympy.polys.domains.QQ_I + Extension.postprocess(options) + + +class Extension(Option, metaclass=OptionType): + """``extension`` option to polynomial manipulation functions. """ + + option = 'extension' + + requires: list[str] = [] + excludes = ['greedy', 'domain', 'split', 'gaussian', 'modulus', + 'symmetric'] + + @classmethod + def preprocess(cls, extension): + if extension == 1: + return bool(extension) + elif extension == 0: + raise OptionError("'False' is an invalid argument for 'extension'") + else: + if not hasattr(extension, '__iter__'): + extension = {extension} + else: + if not extension: + extension = None + else: + extension = set(extension) + + return extension + + @classmethod + def postprocess(cls, options): + if 'extension' in options and options['extension'] is not True: + options['domain'] = sympy.polys.domains.QQ.algebraic_field( + *options['extension']) + + +class Modulus(Option, metaclass=OptionType): + """``modulus`` option to polynomial manipulation functions. """ + + option = 'modulus' + + requires: list[str] = [] + excludes = ['greedy', 'split', 'domain', 'gaussian', 'extension'] + + @classmethod + def preprocess(cls, modulus): + modulus = sympify(modulus) + + if modulus.is_Integer and modulus > 0: + return int(modulus) + else: + raise OptionError( + "'modulus' must a positive integer, got %s" % modulus) + + @classmethod + def postprocess(cls, options): + if 'modulus' in options: + modulus = options['modulus'] + symmetric = options.get('symmetric', True) + options['domain'] = sympy.polys.domains.FF(modulus, symmetric) + + +class Symmetric(BooleanOption, metaclass=OptionType): + """``symmetric`` option to polynomial manipulation functions. """ + + option = 'symmetric' + + requires = ['modulus'] + excludes = ['greedy', 'domain', 'split', 'gaussian', 'extension'] + + +class Strict(BooleanOption, metaclass=OptionType): + """``strict`` option to polynomial manipulation functions. """ + + option = 'strict' + + @classmethod + def default(cls): + return True + + +class Auto(BooleanOption, Flag, metaclass=OptionType): + """``auto`` flag to polynomial manipulation functions. """ + + option = 'auto' + + after = ['field', 'domain', 'extension', 'gaussian'] + + @classmethod + def default(cls): + return True + + @classmethod + def postprocess(cls, options): + if ('domain' in options or 'field' in options) and 'auto' not in options: + options['auto'] = False + + +class Frac(BooleanOption, Flag, metaclass=OptionType): + """``auto`` option to polynomial manipulation functions. """ + + option = 'frac' + + @classmethod + def default(cls): + return False + + +class Formal(BooleanOption, Flag, metaclass=OptionType): + """``formal`` flag to polynomial manipulation functions. """ + + option = 'formal' + + @classmethod + def default(cls): + return False + + +class Polys(BooleanOption, Flag, metaclass=OptionType): + """``polys`` flag to polynomial manipulation functions. """ + + option = 'polys' + + +class Include(BooleanOption, Flag, metaclass=OptionType): + """``include`` flag to polynomial manipulation functions. """ + + option = 'include' + + @classmethod + def default(cls): + return False + + +class All(BooleanOption, Flag, metaclass=OptionType): + """``all`` flag to polynomial manipulation functions. """ + + option = 'all' + + @classmethod + def default(cls): + return False + + +class Gen(Flag, metaclass=OptionType): + """``gen`` flag to polynomial manipulation functions. """ + + option = 'gen' + + @classmethod + def default(cls): + return 0 + + @classmethod + def preprocess(cls, gen): + if isinstance(gen, (Basic, int)): + return gen + else: + raise OptionError("invalid argument for 'gen' option") + + +class Series(BooleanOption, Flag, metaclass=OptionType): + """``series`` flag to polynomial manipulation functions. """ + + option = 'series' + + @classmethod + def default(cls): + return False + + +class Symbols(Flag, metaclass=OptionType): + """``symbols`` flag to polynomial manipulation functions. """ + + option = 'symbols' + + @classmethod + def default(cls): + return numbered_symbols('s', start=1) + + @classmethod + def preprocess(cls, symbols): + if hasattr(symbols, '__iter__'): + return iter(symbols) + else: + raise OptionError("expected an iterator or iterable container, got %s" % symbols) + + +class Method(Flag, metaclass=OptionType): + """``method`` flag to polynomial manipulation functions. """ + + option = 'method' + + @classmethod + def preprocess(cls, method): + if isinstance(method, str): + return method.lower() + else: + raise OptionError("expected a string, got %s" % method) + + +def build_options(gens, args=None): + """Construct options from keyword arguments or ... options. """ + if args is None: + gens, args = (), gens + + if len(args) != 1 or 'opt' not in args or gens: + return Options(gens, args) + else: + return args['opt'] + + +def allowed_flags(args, flags): + """ + Allow specified flags to be used in the given context. + + Examples + ======== + + >>> from sympy.polys.polyoptions import allowed_flags + >>> from sympy.polys.domains import ZZ + + >>> allowed_flags({'domain': ZZ}, []) + + >>> allowed_flags({'domain': ZZ, 'frac': True}, []) + Traceback (most recent call last): + ... + FlagError: 'frac' flag is not allowed in this context + + >>> allowed_flags({'domain': ZZ, 'frac': True}, ['frac']) + + """ + flags = set(flags) + + for arg in args.keys(): + try: + if Options.__options__[arg].is_Flag and arg not in flags: + raise FlagError( + "'%s' flag is not allowed in this context" % arg) + except KeyError: + raise OptionError("'%s' is not a valid option" % arg) + + +def set_defaults(options, **defaults): + """Update options with default values. """ + if 'defaults' not in options: + options = dict(options) + options['defaults'] = defaults + + return options + +Options._init_dependencies_order() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyquinticconst.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyquinticconst.py new file mode 100644 index 0000000000000000000000000000000000000000..3b17096fd2cf3b205c3b819eb11ffc2012ea125b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyquinticconst.py @@ -0,0 +1,187 @@ +""" +Solving solvable quintics - An implementation of DS Dummit's paper + +Paper : +https://www.ams.org/journals/mcom/1991-57-195/S0025-5718-1991-1079014-X/S0025-5718-1991-1079014-X.pdf + +Mathematica notebook: +http://www.emba.uvm.edu/~ddummit/quintics/quintics.nb + +""" + + +from sympy.core import Symbol +from sympy.core.evalf import N +from sympy.core.numbers import I, Rational +from sympy.functions import sqrt +from sympy.polys.polytools import Poly +from sympy.utilities import public + +x = Symbol('x') + +@public +class PolyQuintic: + """Special functions for solvable quintics""" + def __init__(self, poly): + _, _, self.p, self.q, self.r, self.s = poly.all_coeffs() + self.zeta1 = Rational(-1, 4) + (sqrt(5)/4) + I*sqrt((sqrt(5)/8) + Rational(5, 8)) + self.zeta2 = (-sqrt(5)/4) - Rational(1, 4) + I*sqrt((-sqrt(5)/8) + Rational(5, 8)) + self.zeta3 = (-sqrt(5)/4) - Rational(1, 4) - I*sqrt((-sqrt(5)/8) + Rational(5, 8)) + self.zeta4 = Rational(-1, 4) + (sqrt(5)/4) - I*sqrt((sqrt(5)/8) + Rational(5, 8)) + + @property + def f20(self): + p, q, r, s = self.p, self.q, self.r, self.s + f20 = q**8 - 13*p*q**6*r + p**5*q**2*r**2 + 65*p**2*q**4*r**2 - 4*p**6*r**3 - 128*p**3*q**2*r**3 + 17*q**4*r**3 + 48*p**4*r**4 - 16*p*q**2*r**4 - 192*p**2*r**5 + 256*r**6 - 4*p**5*q**3*s - 12*p**2*q**5*s + 18*p**6*q*r*s + 12*p**3*q**3*r*s - 124*q**5*r*s + 196*p**4*q*r**2*s + 590*p*q**3*r**2*s - 160*p**2*q*r**3*s - 1600*q*r**4*s - 27*p**7*s**2 - 150*p**4*q**2*s**2 - 125*p*q**4*s**2 - 99*p**5*r*s**2 - 725*p**2*q**2*r*s**2 + 1200*p**3*r**2*s**2 + 3250*q**2*r**2*s**2 - 2000*p*r**3*s**2 - 1250*p*q*r*s**3 + 3125*p**2*s**4 - 9375*r*s**4-(2*p*q**6 - 19*p**2*q**4*r + 51*p**3*q**2*r**2 - 3*q**4*r**2 - 32*p**4*r**3 - 76*p*q**2*r**3 + 256*p**2*r**4 - 512*r**5 + 31*p**3*q**3*s + 58*q**5*s - 117*p**4*q*r*s - 105*p*q**3*r*s - 260*p**2*q*r**2*s + 2400*q*r**3*s + 108*p**5*s**2 + 325*p**2*q**2*s**2 - 525*p**3*r*s**2 - 2750*q**2*r*s**2 + 500*p*r**2*s**2 - 625*p*q*s**3 + 3125*s**4)*x+(p**2*q**4 - 6*p**3*q**2*r - 8*q**4*r + 9*p**4*r**2 + 76*p*q**2*r**2 - 136*p**2*r**3 + 400*r**4 - 50*p*q**3*s + 90*p**2*q*r*s - 1400*q*r**2*s + 625*q**2*s**2 + 500*p*r*s**2)*x**2-(2*q**4 - 21*p*q**2*r + 40*p**2*r**2 - 160*r**3 + 15*p**2*q*s + 400*q*r*s - 125*p*s**2)*x**3+(2*p*q**2 - 6*p**2*r + 40*r**2 - 50*q*s)*x**4 + 8*r*x**5 + x**6 + return Poly(f20, x) + + @property + def b(self): + p, q, r, s = self.p, self.q, self.r, self.s + b = ( [], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0],) + + b[1][5] = 100*p**7*q**7 + 2175*p**4*q**9 + 10500*p*q**11 - 1100*p**8*q**5*r - 27975*p**5*q**7*r - 152950*p**2*q**9*r + 4125*p**9*q**3*r**2 + 128875*p**6*q**5*r**2 + 830525*p**3*q**7*r**2 - 59450*q**9*r**2 - 5400*p**10*q*r**3 - 243800*p**7*q**3*r**3 - 2082650*p**4*q**5*r**3 + 333925*p*q**7*r**3 + 139200*p**8*q*r**4 + 2406000*p**5*q**3*r**4 + 122600*p**2*q**5*r**4 - 1254400*p**6*q*r**5 - 3776000*p**3*q**3*r**5 - 1832000*q**5*r**5 + 4736000*p**4*q*r**6 + 6720000*p*q**3*r**6 - 6400000*p**2*q*r**7 + 900*p**9*q**4*s + 37400*p**6*q**6*s + 281625*p**3*q**8*s + 435000*q**10*s - 6750*p**10*q**2*r*s - 322300*p**7*q**4*r*s - 2718575*p**4*q**6*r*s - 4214250*p*q**8*r*s + 16200*p**11*r**2*s + 859275*p**8*q**2*r**2*s + 8925475*p**5*q**4*r**2*s + 14427875*p**2*q**6*r**2*s - 453600*p**9*r**3*s - 10038400*p**6*q**2*r**3*s - 17397500*p**3*q**4*r**3*s + 11333125*q**6*r**3*s + 4451200*p**7*r**4*s + 15850000*p**4*q**2*r**4*s - 34000000*p*q**4*r**4*s - 17984000*p**5*r**5*s + 10000000*p**2*q**2*r**5*s + 25600000*p**3*r**6*s + 8000000*q**2*r**6*s - 6075*p**11*q*s**2 + 83250*p**8*q**3*s**2 + 1282500*p**5*q**5*s**2 + 2862500*p**2*q**7*s**2 - 724275*p**9*q*r*s**2 - 9807250*p**6*q**3*r*s**2 - 28374375*p**3*q**5*r*s**2 - 22212500*q**7*r*s**2 + 8982000*p**7*q*r**2*s**2 + 39600000*p**4*q**3*r**2*s**2 + 61746875*p*q**5*r**2*s**2 + 1010000*p**5*q*r**3*s**2 + 1000000*p**2*q**3*r**3*s**2 - 78000000*p**3*q*r**4*s**2 - 30000000*q**3*r**4*s**2 - 80000000*p*q*r**5*s**2 + 759375*p**10*s**3 + 9787500*p**7*q**2*s**3 + 39062500*p**4*q**4*s**3 + 52343750*p*q**6*s**3 - 12301875*p**8*r*s**3 - 98175000*p**5*q**2*r*s**3 - 225078125*p**2*q**4*r*s**3 + 54900000*p**6*r**2*s**3 + 310000000*p**3*q**2*r**2*s**3 + 7890625*q**4*r**2*s**3 - 51250000*p**4*r**3*s**3 + 420000000*p*q**2*r**3*s**3 - 110000000*p**2*r**4*s**3 + 200000000*r**5*s**3 - 2109375*p**6*q*s**4 + 21093750*p**3*q**3*s**4 + 89843750*q**5*s**4 - 182343750*p**4*q*r*s**4 - 733203125*p*q**3*r*s**4 + 196875000*p**2*q*r**2*s**4 - 1125000000*q*r**3*s**4 + 158203125*p**5*s**5 + 566406250*p**2*q**2*s**5 - 101562500*p**3*r*s**5 + 1669921875*q**2*r*s**5 - 1250000000*p*r**2*s**5 + 1220703125*p*q*s**6 - 6103515625*s**7 + + b[1][4] = -1000*p**5*q**7 - 7250*p**2*q**9 + 10800*p**6*q**5*r + 96900*p**3*q**7*r + 52500*q**9*r - 37400*p**7*q**3*r**2 - 470850*p**4*q**5*r**2 - 640600*p*q**7*r**2 + 39600*p**8*q*r**3 + 983600*p**5*q**3*r**3 + 2848100*p**2*q**5*r**3 - 814400*p**6*q*r**4 - 6076000*p**3*q**3*r**4 - 2308000*q**5*r**4 + 5024000*p**4*q*r**5 + 9680000*p*q**3*r**5 - 9600000*p**2*q*r**6 - 13800*p**7*q**4*s - 94650*p**4*q**6*s + 26500*p*q**8*s + 86400*p**8*q**2*r*s + 816500*p**5*q**4*r*s + 257500*p**2*q**6*r*s - 91800*p**9*r**2*s - 1853700*p**6*q**2*r**2*s - 630000*p**3*q**4*r**2*s + 8971250*q**6*r**2*s + 2071200*p**7*r**3*s + 7240000*p**4*q**2*r**3*s - 29375000*p*q**4*r**3*s - 14416000*p**5*r**4*s + 5200000*p**2*q**2*r**4*s + 30400000*p**3*r**5*s + 12000000*q**2*r**5*s - 64800*p**9*q*s**2 - 567000*p**6*q**3*s**2 - 1655000*p**3*q**5*s**2 - 6987500*q**7*s**2 - 337500*p**7*q*r*s**2 - 8462500*p**4*q**3*r*s**2 + 5812500*p*q**5*r*s**2 + 24930000*p**5*q*r**2*s**2 + 69125000*p**2*q**3*r**2*s**2 - 103500000*p**3*q*r**3*s**2 - 30000000*q**3*r**3*s**2 - 90000000*p*q*r**4*s**2 + 708750*p**8*s**3 + 5400000*p**5*q**2*s**3 - 8906250*p**2*q**4*s**3 - 18562500*p**6*r*s**3 + 625000*p**3*q**2*r*s**3 - 29687500*q**4*r*s**3 + 75000000*p**4*r**2*s**3 + 416250000*p*q**2*r**2*s**3 - 60000000*p**2*r**3*s**3 + 300000000*r**4*s**3 - 71718750*p**4*q*s**4 - 189062500*p*q**3*s**4 - 210937500*p**2*q*r*s**4 - 1187500000*q*r**2*s**4 + 187500000*p**3*s**5 + 800781250*q**2*s**5 + 390625000*p*r*s**5 + + b[1][3] = 500*p**6*q**5 + 6350*p**3*q**7 + 19800*q**9 - 3750*p**7*q**3*r - 65100*p**4*q**5*r - 264950*p*q**7*r + 6750*p**8*q*r**2 + 209050*p**5*q**3*r**2 + 1217250*p**2*q**5*r**2 - 219000*p**6*q*r**3 - 2510000*p**3*q**3*r**3 - 1098500*q**5*r**3 + 2068000*p**4*q*r**4 + 5060000*p*q**3*r**4 - 5200000*p**2*q*r**5 + 6750*p**8*q**2*s + 96350*p**5*q**4*s + 346000*p**2*q**6*s - 20250*p**9*r*s - 459900*p**6*q**2*r*s - 1828750*p**3*q**4*r*s + 2930000*q**6*r*s + 594000*p**7*r**2*s + 4301250*p**4*q**2*r**2*s - 10906250*p*q**4*r**2*s - 5252000*p**5*r**3*s + 1450000*p**2*q**2*r**3*s + 12800000*p**3*r**4*s + 6500000*q**2*r**4*s - 74250*p**7*q*s**2 - 1418750*p**4*q**3*s**2 - 5956250*p*q**5*s**2 + 4297500*p**5*q*r*s**2 + 29906250*p**2*q**3*r*s**2 - 31500000*p**3*q*r**2*s**2 - 12500000*q**3*r**2*s**2 - 35000000*p*q*r**3*s**2 - 1350000*p**6*s**3 - 6093750*p**3*q**2*s**3 - 17500000*q**4*s**3 + 7031250*p**4*r*s**3 + 127812500*p*q**2*r*s**3 - 18750000*p**2*r**2*s**3 + 162500000*r**3*s**3 - 107812500*p**2*q*s**4 - 460937500*q*r*s**4 + 214843750*p*s**5 + + b[1][2] = -1950*p**4*q**5 - 14100*p*q**7 + 14350*p**5*q**3*r + 125600*p**2*q**5*r - 27900*p**6*q*r**2 - 402250*p**3*q**3*r**2 - 288250*q**5*r**2 + 436000*p**4*q*r**3 + 1345000*p*q**3*r**3 - 1400000*p**2*q*r**4 - 9450*p**6*q**2*s + 1250*p**3*q**4*s + 465000*q**6*s + 49950*p**7*r*s + 302500*p**4*q**2*r*s - 1718750*p*q**4*r*s - 834000*p**5*r**2*s - 437500*p**2*q**2*r**2*s + 3100000*p**3*r**3*s + 1750000*q**2*r**3*s + 292500*p**5*q*s**2 + 1937500*p**2*q**3*s**2 - 3343750*p**3*q*r*s**2 - 1875000*q**3*r*s**2 - 8125000*p*q*r**2*s**2 + 1406250*p**4*s**3 + 12343750*p*q**2*s**3 - 5312500*p**2*r*s**3 + 43750000*r**2*s**3 - 74218750*q*s**4 + + b[1][1] = 300*p**5*q**3 + 2150*p**2*q**5 - 1350*p**6*q*r - 21500*p**3*q**3*r - 61500*q**5*r + 42000*p**4*q*r**2 + 290000*p*q**3*r**2 - 300000*p**2*q*r**3 + 4050*p**7*s + 45000*p**4*q**2*s + 125000*p*q**4*s - 108000*p**5*r*s - 643750*p**2*q**2*r*s + 700000*p**3*r**2*s + 375000*q**2*r**2*s + 93750*p**3*q*s**2 + 312500*q**3*s**2 - 1875000*p*q*r*s**2 + 1406250*p**2*s**3 + 9375000*r*s**3 + + b[1][0] = -1250*p**3*q**3 - 9000*q**5 + 4500*p**4*q*r + 46250*p*q**3*r - 50000*p**2*q*r**2 - 6750*p**5*s - 43750*p**2*q**2*s + 75000*p**3*r*s + 62500*q**2*r*s - 156250*p*q*s**2 + 1562500*s**3 + + b[2][5] = 200*p**6*q**11 - 250*p**3*q**13 - 10800*q**15 - 3900*p**7*q**9*r - 3325*p**4*q**11*r + 181800*p*q**13*r + 26950*p**8*q**7*r**2 + 69625*p**5*q**9*r**2 - 1214450*p**2*q**11*r**2 - 78725*p**9*q**5*r**3 - 368675*p**6*q**7*r**3 + 4166325*p**3*q**9*r**3 + 1131100*q**11*r**3 + 73400*p**10*q**3*r**4 + 661950*p**7*q**5*r**4 - 9151950*p**4*q**7*r**4 - 16633075*p*q**9*r**4 + 36000*p**11*q*r**5 + 135600*p**8*q**3*r**5 + 17321400*p**5*q**5*r**5 + 85338300*p**2*q**7*r**5 - 832000*p**9*q*r**6 - 21379200*p**6*q**3*r**6 - 176044000*p**3*q**5*r**6 - 1410000*q**7*r**6 + 6528000*p**7*q*r**7 + 129664000*p**4*q**3*r**7 + 47344000*p*q**5*r**7 - 21504000*p**5*q*r**8 - 115200000*p**2*q**3*r**8 + 25600000*p**3*q*r**9 + 64000000*q**3*r**9 + 15700*p**8*q**8*s + 120525*p**5*q**10*s + 113250*p**2*q**12*s - 196900*p**9*q**6*r*s - 1776925*p**6*q**8*r*s - 3062475*p**3*q**10*r*s - 4153500*q**12*r*s + 857925*p**10*q**4*r**2*s + 10562775*p**7*q**6*r**2*s + 34866250*p**4*q**8*r**2*s + 73486750*p*q**10*r**2*s - 1333800*p**11*q**2*r**3*s - 29212625*p**8*q**4*r**3*s - 168729675*p**5*q**6*r**3*s - 427230750*p**2*q**8*r**3*s + 108000*p**12*r**4*s + 30384200*p**9*q**2*r**4*s + 324535100*p**6*q**4*r**4*s + 952666750*p**3*q**6*r**4*s - 38076875*q**8*r**4*s - 4296000*p**10*r**5*s - 213606400*p**7*q**2*r**5*s - 842060000*p**4*q**4*r**5*s - 95285000*p*q**6*r**5*s + 61184000*p**8*r**6*s + 567520000*p**5*q**2*r**6*s + 547000000*p**2*q**4*r**6*s - 390912000*p**6*r**7*s - 812800000*p**3*q**2*r**7*s - 924000000*q**4*r**7*s + 1152000000*p**4*r**8*s + 800000000*p*q**2*r**8*s - 1280000000*p**2*r**9*s + 141750*p**10*q**5*s**2 - 31500*p**7*q**7*s**2 - 11325000*p**4*q**9*s**2 - 31687500*p*q**11*s**2 - 1293975*p**11*q**3*r*s**2 - 4803800*p**8*q**5*r*s**2 + 71398250*p**5*q**7*r*s**2 + 227625000*p**2*q**9*r*s**2 + 3256200*p**12*q*r**2*s**2 + 43870125*p**9*q**3*r**2*s**2 + 64581500*p**6*q**5*r**2*s**2 + 56090625*p**3*q**7*r**2*s**2 + 260218750*q**9*r**2*s**2 - 74610000*p**10*q*r**3*s**2 - 662186500*p**7*q**3*r**3*s**2 - 1987747500*p**4*q**5*r**3*s**2 - 811928125*p*q**7*r**3*s**2 + 471286000*p**8*q*r**4*s**2 + 2106040000*p**5*q**3*r**4*s**2 + 792687500*p**2*q**5*r**4*s**2 - 135120000*p**6*q*r**5*s**2 + 2479000000*p**3*q**3*r**5*s**2 + 5242250000*q**5*r**5*s**2 - 6400000000*p**4*q*r**6*s**2 - 8620000000*p*q**3*r**6*s**2 + 13280000000*p**2*q*r**7*s**2 + 1600000000*q*r**8*s**2 + 273375*p**12*q**2*s**3 - 13612500*p**9*q**4*s**3 - 177250000*p**6*q**6*s**3 - 511015625*p**3*q**8*s**3 - 320937500*q**10*s**3 - 2770200*p**13*r*s**3 + 12595500*p**10*q**2*r*s**3 + 543950000*p**7*q**4*r*s**3 + 1612281250*p**4*q**6*r*s**3 + 968125000*p*q**8*r*s**3 + 77031000*p**11*r**2*s**3 + 373218750*p**8*q**2*r**2*s**3 + 1839765625*p**5*q**4*r**2*s**3 + 1818515625*p**2*q**6*r**2*s**3 - 776745000*p**9*r**3*s**3 - 6861075000*p**6*q**2*r**3*s**3 - 20014531250*p**3*q**4*r**3*s**3 - 13747812500*q**6*r**3*s**3 + 3768000000*p**7*r**4*s**3 + 35365000000*p**4*q**2*r**4*s**3 + 34441875000*p*q**4*r**4*s**3 - 9628000000*p**5*r**5*s**3 - 63230000000*p**2*q**2*r**5*s**3 + 13600000000*p**3*r**6*s**3 - 15000000000*q**2*r**6*s**3 - 10400000000*p*r**7*s**3 - 45562500*p**11*q*s**4 - 525937500*p**8*q**3*s**4 - 1364218750*p**5*q**5*s**4 - 1382812500*p**2*q**7*s**4 + 572062500*p**9*q*r*s**4 + 2473515625*p**6*q**3*r*s**4 + 13192187500*p**3*q**5*r*s**4 + 12703125000*q**7*r*s**4 - 451406250*p**7*q*r**2*s**4 - 18153906250*p**4*q**3*r**2*s**4 - 36908203125*p*q**5*r**2*s**4 - 9069375000*p**5*q*r**3*s**4 + 79957812500*p**2*q**3*r**3*s**4 + 5512500000*p**3*q*r**4*s**4 + 50656250000*q**3*r**4*s**4 + 74750000000*p*q*r**5*s**4 + 56953125*p**10*s**5 + 1381640625*p**7*q**2*s**5 - 781250000*p**4*q**4*s**5 + 878906250*p*q**6*s**5 - 2655703125*p**8*r*s**5 - 3223046875*p**5*q**2*r*s**5 - 35117187500*p**2*q**4*r*s**5 + 26573437500*p**6*r**2*s**5 + 14785156250*p**3*q**2*r**2*s**5 - 52050781250*q**4*r**2*s**5 - 103062500000*p**4*r**3*s**5 - 281796875000*p*q**2*r**3*s**5 + 146875000000*p**2*r**4*s**5 - 37500000000*r**5*s**5 - 8789062500*p**6*q*s**6 - 3906250000*p**3*q**3*s**6 + 1464843750*q**5*s**6 + 102929687500*p**4*q*r*s**6 + 297119140625*p*q**3*r*s**6 - 217773437500*p**2*q*r**2*s**6 + 167968750000*q*r**3*s**6 + 10986328125*p**5*s**7 + 98876953125*p**2*q**2*s**7 - 188964843750*p**3*r*s**7 - 278320312500*q**2*r*s**7 + 517578125000*p*r**2*s**7 - 610351562500*p*q*s**8 + 762939453125*s**9 + + b[2][4] = -200*p**7*q**9 + 1850*p**4*q**11 + 21600*p*q**13 + 3200*p**8*q**7*r - 19200*p**5*q**9*r - 316350*p**2*q**11*r - 19050*p**9*q**5*r**2 + 37400*p**6*q**7*r**2 + 1759250*p**3*q**9*r**2 + 440100*q**11*r**2 + 48750*p**10*q**3*r**3 + 190200*p**7*q**5*r**3 - 4604200*p**4*q**7*r**3 - 6072800*p*q**9*r**3 - 43200*p**11*q*r**4 - 834500*p**8*q**3*r**4 + 4916000*p**5*q**5*r**4 + 27926850*p**2*q**7*r**4 + 969600*p**9*q*r**5 + 2467200*p**6*q**3*r**5 - 45393200*p**3*q**5*r**5 - 5399500*q**7*r**5 - 7283200*p**7*q*r**6 + 10536000*p**4*q**3*r**6 + 41656000*p*q**5*r**6 + 22784000*p**5*q*r**7 - 35200000*p**2*q**3*r**7 - 25600000*p**3*q*r**8 + 96000000*q**3*r**8 - 3000*p**9*q**6*s + 40400*p**6*q**8*s + 136550*p**3*q**10*s - 1647000*q**12*s + 40500*p**10*q**4*r*s - 173600*p**7*q**6*r*s - 126500*p**4*q**8*r*s + 23969250*p*q**10*r*s - 153900*p**11*q**2*r**2*s - 486150*p**8*q**4*r**2*s - 4115800*p**5*q**6*r**2*s - 112653250*p**2*q**8*r**2*s + 129600*p**12*r**3*s + 2683350*p**9*q**2*r**3*s + 10906650*p**6*q**4*r**3*s + 187289500*p**3*q**6*r**3*s + 44098750*q**8*r**3*s - 4384800*p**10*r**4*s - 35660800*p**7*q**2*r**4*s - 175420000*p**4*q**4*r**4*s - 426538750*p*q**6*r**4*s + 60857600*p**8*r**5*s + 349436000*p**5*q**2*r**5*s + 900600000*p**2*q**4*r**5*s - 429568000*p**6*r**6*s - 1511200000*p**3*q**2*r**6*s - 1286000000*q**4*r**6*s + 1472000000*p**4*r**7*s + 1440000000*p*q**2*r**7*s - 1920000000*p**2*r**8*s - 36450*p**11*q**3*s**2 - 188100*p**8*q**5*s**2 - 5504750*p**5*q**7*s**2 - 37968750*p**2*q**9*s**2 + 255150*p**12*q*r*s**2 + 2754000*p**9*q**3*r*s**2 + 49196500*p**6*q**5*r*s**2 + 323587500*p**3*q**7*r*s**2 - 83250000*q**9*r*s**2 - 465750*p**10*q*r**2*s**2 - 31881500*p**7*q**3*r**2*s**2 - 415585000*p**4*q**5*r**2*s**2 + 1054775000*p*q**7*r**2*s**2 - 96823500*p**8*q*r**3*s**2 - 701490000*p**5*q**3*r**3*s**2 - 2953531250*p**2*q**5*r**3*s**2 + 1454560000*p**6*q*r**4*s**2 + 7670500000*p**3*q**3*r**4*s**2 + 5661062500*q**5*r**4*s**2 - 7785000000*p**4*q*r**5*s**2 - 9450000000*p*q**3*r**5*s**2 + 14000000000*p**2*q*r**6*s**2 + 2400000000*q*r**7*s**2 - 437400*p**13*s**3 - 10145250*p**10*q**2*s**3 - 121912500*p**7*q**4*s**3 - 576531250*p**4*q**6*s**3 - 528593750*p*q**8*s**3 + 12939750*p**11*r*s**3 + 313368750*p**8*q**2*r*s**3 + 2171812500*p**5*q**4*r*s**3 + 2381718750*p**2*q**6*r*s**3 - 124638750*p**9*r**2*s**3 - 3001575000*p**6*q**2*r**2*s**3 - 12259375000*p**3*q**4*r**2*s**3 - 9985312500*q**6*r**2*s**3 + 384000000*p**7*r**3*s**3 + 13997500000*p**4*q**2*r**3*s**3 + 20749531250*p*q**4*r**3*s**3 - 553500000*p**5*r**4*s**3 - 41835000000*p**2*q**2*r**4*s**3 + 5420000000*p**3*r**5*s**3 - 16300000000*q**2*r**5*s**3 - 17600000000*p*r**6*s**3 - 7593750*p**9*q*s**4 + 289218750*p**6*q**3*s**4 + 3591406250*p**3*q**5*s**4 + 5992187500*q**7*s**4 + 658125000*p**7*q*r*s**4 - 269531250*p**4*q**3*r*s**4 - 15882812500*p*q**5*r*s**4 - 4785000000*p**5*q*r**2*s**4 + 54375781250*p**2*q**3*r**2*s**4 - 5668750000*p**3*q*r**3*s**4 + 35867187500*q**3*r**3*s**4 + 113875000000*p*q*r**4*s**4 - 544218750*p**8*s**5 - 5407031250*p**5*q**2*s**5 - 14277343750*p**2*q**4*s**5 + 5421093750*p**6*r*s**5 - 24941406250*p**3*q**2*r*s**5 - 25488281250*q**4*r*s**5 - 11500000000*p**4*r**2*s**5 - 231894531250*p*q**2*r**2*s**5 - 6250000000*p**2*r**3*s**5 - 43750000000*r**4*s**5 + 35449218750*p**4*q*s**6 + 137695312500*p*q**3*s**6 + 34667968750*p**2*q*r*s**6 + 202148437500*q*r**2*s**6 - 33691406250*p**3*s**7 - 214843750000*q**2*s**7 - 31738281250*p*r*s**7 + + b[2][3] = -800*p**5*q**9 - 5400*p**2*q**11 + 5800*p**6*q**7*r + 48750*p**3*q**9*r + 16200*q**11*r - 3000*p**7*q**5*r**2 - 108350*p**4*q**7*r**2 - 263250*p*q**9*r**2 - 60700*p**8*q**3*r**3 - 386250*p**5*q**5*r**3 + 253100*p**2*q**7*r**3 + 127800*p**9*q*r**4 + 2326700*p**6*q**3*r**4 + 6565550*p**3*q**5*r**4 - 705750*q**7*r**4 - 2903200*p**7*q*r**5 - 21218000*p**4*q**3*r**5 + 1057000*p*q**5*r**5 + 20368000*p**5*q*r**6 + 33000000*p**2*q**3*r**6 - 43200000*p**3*q*r**7 + 52000000*q**3*r**7 + 6200*p**7*q**6*s + 188250*p**4*q**8*s + 931500*p*q**10*s - 73800*p**8*q**4*r*s - 1466850*p**5*q**6*r*s - 6894000*p**2*q**8*r*s + 315900*p**9*q**2*r**2*s + 4547000*p**6*q**4*r**2*s + 20362500*p**3*q**6*r**2*s + 15018750*q**8*r**2*s - 653400*p**10*r**3*s - 13897550*p**7*q**2*r**3*s - 76757500*p**4*q**4*r**3*s - 124207500*p*q**6*r**3*s + 18567600*p**8*r**4*s + 175911000*p**5*q**2*r**4*s + 253787500*p**2*q**4*r**4*s - 183816000*p**6*r**5*s - 706900000*p**3*q**2*r**5*s - 665750000*q**4*r**5*s + 740000000*p**4*r**6*s + 890000000*p*q**2*r**6*s - 1040000000*p**2*r**7*s - 763000*p**6*q**5*s**2 - 12375000*p**3*q**7*s**2 - 40500000*q**9*s**2 + 364500*p**10*q*r*s**2 + 15537000*p**7*q**3*r*s**2 + 154392500*p**4*q**5*r*s**2 + 372206250*p*q**7*r*s**2 - 25481250*p**8*q*r**2*s**2 - 386300000*p**5*q**3*r**2*s**2 - 996343750*p**2*q**5*r**2*s**2 + 459872500*p**6*q*r**3*s**2 + 2943937500*p**3*q**3*r**3*s**2 + 2437781250*q**5*r**3*s**2 - 2883750000*p**4*q*r**4*s**2 - 4343750000*p*q**3*r**4*s**2 + 5495000000*p**2*q*r**5*s**2 + 1300000000*q*r**6*s**2 - 364500*p**11*s**3 - 13668750*p**8*q**2*s**3 - 113406250*p**5*q**4*s**3 - 159062500*p**2*q**6*s**3 + 13972500*p**9*r*s**3 + 61537500*p**6*q**2*r*s**3 - 1622656250*p**3*q**4*r*s**3 - 2720625000*q**6*r*s**3 - 201656250*p**7*r**2*s**3 + 1949687500*p**4*q**2*r**2*s**3 + 4979687500*p*q**4*r**2*s**3 + 497125000*p**5*r**3*s**3 - 11150625000*p**2*q**2*r**3*s**3 + 2982500000*p**3*r**4*s**3 - 6612500000*q**2*r**4*s**3 - 10450000000*p*r**5*s**3 + 126562500*p**7*q*s**4 + 1443750000*p**4*q**3*s**4 + 281250000*p*q**5*s**4 - 1648125000*p**5*q*r*s**4 + 11271093750*p**2*q**3*r*s**4 - 4785156250*p**3*q*r**2*s**4 + 8808593750*q**3*r**2*s**4 + 52390625000*p*q*r**3*s**4 - 611718750*p**6*s**5 - 13027343750*p**3*q**2*s**5 - 1464843750*q**4*s**5 + 6492187500*p**4*r*s**5 - 65351562500*p*q**2*r*s**5 - 13476562500*p**2*r**2*s**5 - 24218750000*r**3*s**5 + 41992187500*p**2*q*s**6 + 69824218750*q*r*s**6 - 34179687500*p*s**7 + + b[2][2] = -1000*p**6*q**7 - 5150*p**3*q**9 + 10800*q**11 + 11000*p**7*q**5*r + 66450*p**4*q**7*r - 127800*p*q**9*r - 41250*p**8*q**3*r**2 - 368400*p**5*q**5*r**2 + 204200*p**2*q**7*r**2 + 54000*p**9*q*r**3 + 1040950*p**6*q**3*r**3 + 2096500*p**3*q**5*r**3 + 200000*q**7*r**3 - 1140000*p**7*q*r**4 - 7691000*p**4*q**3*r**4 - 2281000*p*q**5*r**4 + 7296000*p**5*q*r**5 + 13300000*p**2*q**3*r**5 - 14400000*p**3*q*r**6 + 14000000*q**3*r**6 - 9000*p**8*q**4*s + 52100*p**5*q**6*s + 710250*p**2*q**8*s + 67500*p**9*q**2*r*s - 256100*p**6*q**4*r*s - 5753000*p**3*q**6*r*s + 292500*q**8*r*s - 162000*p**10*r**2*s - 1432350*p**7*q**2*r**2*s + 5410000*p**4*q**4*r**2*s - 7408750*p*q**6*r**2*s + 4401000*p**8*r**3*s + 24185000*p**5*q**2*r**3*s + 20781250*p**2*q**4*r**3*s - 43012000*p**6*r**4*s - 146300000*p**3*q**2*r**4*s - 165875000*q**4*r**4*s + 182000000*p**4*r**5*s + 250000000*p*q**2*r**5*s - 280000000*p**2*r**6*s + 60750*p**10*q*s**2 + 2414250*p**7*q**3*s**2 + 15770000*p**4*q**5*s**2 + 15825000*p*q**7*s**2 - 6021000*p**8*q*r*s**2 - 62252500*p**5*q**3*r*s**2 - 74718750*p**2*q**5*r*s**2 + 90888750*p**6*q*r**2*s**2 + 471312500*p**3*q**3*r**2*s**2 + 525875000*q**5*r**2*s**2 - 539375000*p**4*q*r**3*s**2 - 1030000000*p*q**3*r**3*s**2 + 1142500000*p**2*q*r**4*s**2 + 350000000*q*r**5*s**2 - 303750*p**9*s**3 - 35943750*p**6*q**2*s**3 - 331875000*p**3*q**4*s**3 - 505937500*q**6*s**3 + 8437500*p**7*r*s**3 + 530781250*p**4*q**2*r*s**3 + 1150312500*p*q**4*r*s**3 - 154500000*p**5*r**2*s**3 - 2059062500*p**2*q**2*r**2*s**3 + 1150000000*p**3*r**3*s**3 - 1343750000*q**2*r**3*s**3 - 2900000000*p*r**4*s**3 + 30937500*p**5*q*s**4 + 1166406250*p**2*q**3*s**4 - 1496875000*p**3*q*r*s**4 + 1296875000*q**3*r*s**4 + 10640625000*p*q*r**2*s**4 - 281250000*p**4*s**5 - 9746093750*p*q**2*s**5 + 1269531250*p**2*r*s**5 - 7421875000*r**2*s**5 + 15625000000*q*s**6 + + b[2][1] = -1600*p**4*q**7 - 10800*p*q**9 + 9800*p**5*q**5*r + 80550*p**2*q**7*r - 4600*p**6*q**3*r**2 - 112700*p**3*q**5*r**2 + 40500*q**7*r**2 - 34200*p**7*q*r**3 - 279500*p**4*q**3*r**3 - 665750*p*q**5*r**3 + 632000*p**5*q*r**4 + 3200000*p**2*q**3*r**4 - 2800000*p**3*q*r**5 + 3000000*q**3*r**5 - 18600*p**6*q**4*s - 51750*p**3*q**6*s + 405000*q**8*s + 21600*p**7*q**2*r*s - 122500*p**4*q**4*r*s - 2891250*p*q**6*r*s + 156600*p**8*r**2*s + 1569750*p**5*q**2*r**2*s + 6943750*p**2*q**4*r**2*s - 3774000*p**6*r**3*s - 27100000*p**3*q**2*r**3*s - 30187500*q**4*r**3*s + 28000000*p**4*r**4*s + 52500000*p*q**2*r**4*s - 60000000*p**2*r**5*s - 81000*p**8*q*s**2 - 240000*p**5*q**3*s**2 + 937500*p**2*q**5*s**2 + 3273750*p**6*q*r*s**2 + 30406250*p**3*q**3*r*s**2 + 55687500*q**5*r*s**2 - 42187500*p**4*q*r**2*s**2 - 112812500*p*q**3*r**2*s**2 + 152500000*p**2*q*r**3*s**2 + 75000000*q*r**4*s**2 - 4218750*p**4*q**2*s**3 + 15156250*p*q**4*s**3 + 5906250*p**5*r*s**3 - 206562500*p**2*q**2*r*s**3 + 107500000*p**3*r**2*s**3 - 159375000*q**2*r**2*s**3 - 612500000*p*r**3*s**3 + 135937500*p**3*q*s**4 + 46875000*q**3*s**4 + 1175781250*p*q*r*s**4 - 292968750*p**2*s**5 - 1367187500*r*s**5 + + b[2][0] = -800*p**5*q**5 - 5400*p**2*q**7 + 6000*p**6*q**3*r + 51700*p**3*q**5*r + 27000*q**7*r - 10800*p**7*q*r**2 - 163250*p**4*q**3*r**2 - 285750*p*q**5*r**2 + 192000*p**5*q*r**3 + 1000000*p**2*q**3*r**3 - 800000*p**3*q*r**4 + 500000*q**3*r**4 - 10800*p**7*q**2*s - 57500*p**4*q**4*s + 67500*p*q**6*s + 32400*p**8*r*s + 279000*p**5*q**2*r*s - 131250*p**2*q**4*r*s - 729000*p**6*r**2*s - 4100000*p**3*q**2*r**2*s - 5343750*q**4*r**2*s + 5000000*p**4*r**3*s + 10000000*p*q**2*r**3*s - 10000000*p**2*r**4*s + 641250*p**6*q*s**2 + 5812500*p**3*q**3*s**2 + 10125000*q**5*s**2 - 7031250*p**4*q*r*s**2 - 20625000*p*q**3*r*s**2 + 17500000*p**2*q*r**2*s**2 + 12500000*q*r**3*s**2 - 843750*p**5*s**3 - 19375000*p**2*q**2*s**3 + 30000000*p**3*r*s**3 - 20312500*q**2*r*s**3 - 112500000*p*r**2*s**3 + 183593750*p*q*s**4 - 292968750*s**5 + + b[3][5] = 500*p**11*q**6 + 9875*p**8*q**8 + 42625*p**5*q**10 - 35000*p**2*q**12 - 4500*p**12*q**4*r - 108375*p**9*q**6*r - 516750*p**6*q**8*r + 1110500*p**3*q**10*r + 2730000*q**12*r + 10125*p**13*q**2*r**2 + 358250*p**10*q**4*r**2 + 1908625*p**7*q**6*r**2 - 11744250*p**4*q**8*r**2 - 43383250*p*q**10*r**2 - 313875*p**11*q**2*r**3 - 2074875*p**8*q**4*r**3 + 52094750*p**5*q**6*r**3 + 264567500*p**2*q**8*r**3 + 796125*p**9*q**2*r**4 - 92486250*p**6*q**4*r**4 - 757957500*p**3*q**6*r**4 - 29354375*q**8*r**4 + 60970000*p**7*q**2*r**5 + 1112462500*p**4*q**4*r**5 + 571094375*p*q**6*r**5 - 685290000*p**5*q**2*r**6 - 2037800000*p**2*q**4*r**6 + 2279600000*p**3*q**2*r**7 + 849000000*q**4*r**7 - 1480000000*p*q**2*r**8 + 13500*p**13*q**3*s + 363000*p**10*q**5*s + 2861250*p**7*q**7*s + 8493750*p**4*q**9*s + 17031250*p*q**11*s - 60750*p**14*q*r*s - 2319750*p**11*q**3*r*s - 22674250*p**8*q**5*r*s - 74368750*p**5*q**7*r*s - 170578125*p**2*q**9*r*s + 2760750*p**12*q*r**2*s + 46719000*p**9*q**3*r**2*s + 163356375*p**6*q**5*r**2*s + 360295625*p**3*q**7*r**2*s - 195990625*q**9*r**2*s - 37341750*p**10*q*r**3*s - 194739375*p**7*q**3*r**3*s - 105463125*p**4*q**5*r**3*s - 415825000*p*q**7*r**3*s + 90180000*p**8*q*r**4*s - 990552500*p**5*q**3*r**4*s + 3519212500*p**2*q**5*r**4*s + 1112220000*p**6*q*r**5*s - 4508750000*p**3*q**3*r**5*s - 8159500000*q**5*r**5*s - 4356000000*p**4*q*r**6*s + 14615000000*p*q**3*r**6*s - 2160000000*p**2*q*r**7*s + 91125*p**15*s**2 + 3290625*p**12*q**2*s**2 + 35100000*p**9*q**4*s**2 + 175406250*p**6*q**6*s**2 + 629062500*p**3*q**8*s**2 + 910937500*q**10*s**2 - 5710500*p**13*r*s**2 - 100423125*p**10*q**2*r*s**2 - 604743750*p**7*q**4*r*s**2 - 2954843750*p**4*q**6*r*s**2 - 4587578125*p*q**8*r*s**2 + 116194500*p**11*r**2*s**2 + 1280716250*p**8*q**2*r**2*s**2 + 7401190625*p**5*q**4*r**2*s**2 + 11619937500*p**2*q**6*r**2*s**2 - 952173125*p**9*r**3*s**2 - 6519712500*p**6*q**2*r**3*s**2 - 10238593750*p**3*q**4*r**3*s**2 + 29984609375*q**6*r**3*s**2 + 2558300000*p**7*r**4*s**2 + 16225000000*p**4*q**2*r**4*s**2 - 64994140625*p*q**4*r**4*s**2 + 4202250000*p**5*r**5*s**2 + 46925000000*p**2*q**2*r**5*s**2 - 28950000000*p**3*r**6*s**2 - 1000000000*q**2*r**6*s**2 + 37000000000*p*r**7*s**2 - 48093750*p**11*q*s**3 - 673359375*p**8*q**3*s**3 - 2170312500*p**5*q**5*s**3 - 2466796875*p**2*q**7*s**3 + 647578125*p**9*q*r*s**3 + 597031250*p**6*q**3*r*s**3 - 7542578125*p**3*q**5*r*s**3 - 41125000000*q**7*r*s**3 - 2175828125*p**7*q*r**2*s**3 - 7101562500*p**4*q**3*r**2*s**3 + 100596875000*p*q**5*r**2*s**3 - 8984687500*p**5*q*r**3*s**3 - 120070312500*p**2*q**3*r**3*s**3 + 57343750000*p**3*q*r**4*s**3 + 9500000000*q**3*r**4*s**3 - 342875000000*p*q*r**5*s**3 + 400781250*p**10*s**4 + 8531250000*p**7*q**2*s**4 + 34033203125*p**4*q**4*s**4 + 42724609375*p*q**6*s**4 - 6289453125*p**8*r*s**4 - 24037109375*p**5*q**2*r*s**4 - 62626953125*p**2*q**4*r*s**4 + 17299218750*p**6*r**2*s**4 + 108357421875*p**3*q**2*r**2*s**4 - 55380859375*q**4*r**2*s**4 + 105648437500*p**4*r**3*s**4 + 1204228515625*p*q**2*r**3*s**4 - 365000000000*p**2*r**4*s**4 + 184375000000*r**5*s**4 - 32080078125*p**6*q*s**5 - 98144531250*p**3*q**3*s**5 + 93994140625*q**5*s**5 - 178955078125*p**4*q*r*s**5 - 1299804687500*p*q**3*r*s**5 + 332421875000*p**2*q*r**2*s**5 - 1195312500000*q*r**3*s**5 + 72021484375*p**5*s**6 + 323486328125*p**2*q**2*s**6 + 682373046875*p**3*r*s**6 + 2447509765625*q**2*r*s**6 - 3011474609375*p*r**2*s**6 + 3051757812500*p*q*s**7 - 7629394531250*s**8 + + b[3][4] = 1500*p**9*q**6 + 69625*p**6*q**8 + 590375*p**3*q**10 + 1035000*q**12 - 13500*p**10*q**4*r - 760625*p**7*q**6*r - 7904500*p**4*q**8*r - 18169250*p*q**10*r + 30375*p**11*q**2*r**2 + 2628625*p**8*q**4*r**2 + 37879000*p**5*q**6*r**2 + 121367500*p**2*q**8*r**2 - 2699250*p**9*q**2*r**3 - 76776875*p**6*q**4*r**3 - 403583125*p**3*q**6*r**3 - 78865625*q**8*r**3 + 60907500*p**7*q**2*r**4 + 735291250*p**4*q**4*r**4 + 781142500*p*q**6*r**4 - 558270000*p**5*q**2*r**5 - 2150725000*p**2*q**4*r**5 + 2015400000*p**3*q**2*r**6 + 1181000000*q**4*r**6 - 2220000000*p*q**2*r**7 + 40500*p**11*q**3*s + 1376500*p**8*q**5*s + 9953125*p**5*q**7*s + 9765625*p**2*q**9*s - 182250*p**12*q*r*s - 8859000*p**9*q**3*r*s - 82854500*p**6*q**5*r*s - 71511250*p**3*q**7*r*s + 273631250*q**9*r*s + 10233000*p**10*q*r**2*s + 179627500*p**7*q**3*r**2*s + 25164375*p**4*q**5*r**2*s - 2927290625*p*q**7*r**2*s - 171305000*p**8*q*r**3*s - 544768750*p**5*q**3*r**3*s + 7583437500*p**2*q**5*r**3*s + 1139860000*p**6*q*r**4*s - 6489375000*p**3*q**3*r**4*s - 9625375000*q**5*r**4*s - 1838000000*p**4*q*r**5*s + 19835000000*p*q**3*r**5*s - 3240000000*p**2*q*r**6*s + 273375*p**13*s**2 + 9753750*p**10*q**2*s**2 + 82575000*p**7*q**4*s**2 + 202265625*p**4*q**6*s**2 + 556093750*p*q**8*s**2 - 11552625*p**11*r*s**2 - 115813125*p**8*q**2*r*s**2 + 630590625*p**5*q**4*r*s**2 + 1347015625*p**2*q**6*r*s**2 + 157578750*p**9*r**2*s**2 - 689206250*p**6*q**2*r**2*s**2 - 4299609375*p**3*q**4*r**2*s**2 + 23896171875*q**6*r**2*s**2 - 1022437500*p**7*r**3*s**2 + 6648125000*p**4*q**2*r**3*s**2 - 52895312500*p*q**4*r**3*s**2 + 4401750000*p**5*r**4*s**2 + 26500000000*p**2*q**2*r**4*s**2 - 22125000000*p**3*r**5*s**2 - 1500000000*q**2*r**5*s**2 + 55500000000*p*r**6*s**2 - 137109375*p**9*q*s**3 - 1955937500*p**6*q**3*s**3 - 6790234375*p**3*q**5*s**3 - 16996093750*q**7*s**3 + 2146218750*p**7*q*r*s**3 + 6570312500*p**4*q**3*r*s**3 + 39918750000*p*q**5*r*s**3 - 7673281250*p**5*q*r**2*s**3 - 52000000000*p**2*q**3*r**2*s**3 + 50796875000*p**3*q*r**3*s**3 + 18750000000*q**3*r**3*s**3 - 399875000000*p*q*r**4*s**3 + 780468750*p**8*s**4 + 14455078125*p**5*q**2*s**4 + 10048828125*p**2*q**4*s**4 - 15113671875*p**6*r*s**4 + 39298828125*p**3*q**2*r*s**4 - 52138671875*q**4*r*s**4 + 45964843750*p**4*r**2*s**4 + 914414062500*p*q**2*r**2*s**4 + 1953125000*p**2*r**3*s**4 + 334375000000*r**4*s**4 - 149169921875*p**4*q*s**5 - 459716796875*p*q**3*s**5 - 325585937500*p**2*q*r*s**5 - 1462890625000*q*r**2*s**5 + 296630859375*p**3*s**6 + 1324462890625*q**2*s**6 + 307617187500*p*r*s**6 + + b[3][3] = -20750*p**7*q**6 - 290125*p**4*q**8 - 993000*p*q**10 + 146125*p**8*q**4*r + 2721500*p**5*q**6*r + 11833750*p**2*q**8*r - 237375*p**9*q**2*r**2 - 8167500*p**6*q**4*r**2 - 54605625*p**3*q**6*r**2 - 23802500*q**8*r**2 + 8927500*p**7*q**2*r**3 + 131184375*p**4*q**4*r**3 + 254695000*p*q**6*r**3 - 121561250*p**5*q**2*r**4 - 728003125*p**2*q**4*r**4 + 702550000*p**3*q**2*r**5 + 597312500*q**4*r**5 - 1202500000*p*q**2*r**6 - 194625*p**9*q**3*s - 1568875*p**6*q**5*s + 9685625*p**3*q**7*s + 74662500*q**9*s + 327375*p**10*q*r*s + 1280000*p**7*q**3*r*s - 123703750*p**4*q**5*r*s - 850121875*p*q**7*r*s - 7436250*p**8*q*r**2*s + 164820000*p**5*q**3*r**2*s + 2336659375*p**2*q**5*r**2*s + 32202500*p**6*q*r**3*s - 2429765625*p**3*q**3*r**3*s - 4318609375*q**5*r**3*s + 148000000*p**4*q*r**4*s + 9902812500*p*q**3*r**4*s - 1755000000*p**2*q*r**5*s + 1154250*p**11*s**2 + 36821250*p**8*q**2*s**2 + 372825000*p**5*q**4*s**2 + 1170921875*p**2*q**6*s**2 - 38913750*p**9*r*s**2 - 797071875*p**6*q**2*r*s**2 - 2848984375*p**3*q**4*r*s**2 + 7651406250*q**6*r*s**2 + 415068750*p**7*r**2*s**2 + 3151328125*p**4*q**2*r**2*s**2 - 17696875000*p*q**4*r**2*s**2 - 725968750*p**5*r**3*s**2 + 5295312500*p**2*q**2*r**3*s**2 - 8581250000*p**3*r**4*s**2 - 812500000*q**2*r**4*s**2 + 30062500000*p*r**5*s**2 - 110109375*p**7*q*s**3 - 1976562500*p**4*q**3*s**3 - 6329296875*p*q**5*s**3 + 2256328125*p**5*q*r*s**3 + 8554687500*p**2*q**3*r*s**3 + 12947265625*p**3*q*r**2*s**3 + 7984375000*q**3*r**2*s**3 - 167039062500*p*q*r**3*s**3 + 1181250000*p**6*s**4 + 17873046875*p**3*q**2*s**4 - 20449218750*q**4*s**4 - 16265625000*p**4*r*s**4 + 260869140625*p*q**2*r*s**4 + 21025390625*p**2*r**2*s**4 + 207617187500*r**3*s**4 - 207177734375*p**2*q*s**5 - 615478515625*q*r*s**5 + 301513671875*p*s**6 + + b[3][2] = 53125*p**5*q**6 + 425000*p**2*q**8 - 394375*p**6*q**4*r - 4301875*p**3*q**6*r - 3225000*q**8*r + 851250*p**7*q**2*r**2 + 16910625*p**4*q**4*r**2 + 44210000*p*q**6*r**2 - 20474375*p**5*q**2*r**3 - 147190625*p**2*q**4*r**3 + 163975000*p**3*q**2*r**4 + 156812500*q**4*r**4 - 323750000*p*q**2*r**5 - 99375*p**7*q**3*s - 6395000*p**4*q**5*s - 49243750*p*q**7*s - 1164375*p**8*q*r*s + 4465625*p**5*q**3*r*s + 205546875*p**2*q**5*r*s + 12163750*p**6*q*r**2*s - 315546875*p**3*q**3*r**2*s - 946453125*q**5*r**2*s - 23500000*p**4*q*r**3*s + 2313437500*p*q**3*r**3*s - 472500000*p**2*q*r**4*s + 1316250*p**9*s**2 + 22715625*p**6*q**2*s**2 + 206953125*p**3*q**4*s**2 + 1220000000*q**6*s**2 - 20953125*p**7*r*s**2 - 277656250*p**4*q**2*r*s**2 - 3317187500*p*q**4*r*s**2 + 293734375*p**5*r**2*s**2 + 1351562500*p**2*q**2*r**2*s**2 - 2278125000*p**3*r**3*s**2 - 218750000*q**2*r**3*s**2 + 8093750000*p*r**4*s**2 - 9609375*p**5*q*s**3 + 240234375*p**2*q**3*s**3 + 2310546875*p**3*q*r*s**3 + 1171875000*q**3*r*s**3 - 33460937500*p*q*r**2*s**3 + 2185546875*p**4*s**4 + 32578125000*p*q**2*s**4 - 8544921875*p**2*r*s**4 + 58398437500*r**2*s**4 - 114013671875*q*s**5 + + b[3][1] = -16250*p**6*q**4 - 191875*p**3*q**6 - 495000*q**8 + 73125*p**7*q**2*r + 1437500*p**4*q**4*r + 5866250*p*q**6*r - 2043125*p**5*q**2*r**2 - 17218750*p**2*q**4*r**2 + 19106250*p**3*q**2*r**3 + 34015625*q**4*r**3 - 69375000*p*q**2*r**4 - 219375*p**8*q*s - 2846250*p**5*q**3*s - 8021875*p**2*q**5*s + 3420000*p**6*q*r*s - 1640625*p**3*q**3*r*s - 152468750*q**5*r*s + 3062500*p**4*q*r**2*s + 381171875*p*q**3*r**2*s - 101250000*p**2*q*r**3*s + 2784375*p**7*s**2 + 43515625*p**4*q**2*s**2 + 115625000*p*q**4*s**2 - 48140625*p**5*r*s**2 - 307421875*p**2*q**2*r*s**2 - 25781250*p**3*r**2*s**2 - 46875000*q**2*r**2*s**2 + 1734375000*p*r**3*s**2 - 128906250*p**3*q*s**3 + 339843750*q**3*s**3 - 4583984375*p*q*r*s**3 + 2236328125*p**2*s**4 + 12255859375*r*s**4 + + b[3][0] = 31875*p**4*q**4 + 255000*p*q**6 - 82500*p**5*q**2*r - 1106250*p**2*q**4*r + 1653125*p**3*q**2*r**2 + 5187500*q**4*r**2 - 11562500*p*q**2*r**3 - 118125*p**6*q*s - 3593750*p**3*q**3*s - 23812500*q**5*s + 4656250*p**4*q*r*s + 67109375*p*q**3*r*s - 16875000*p**2*q*r**2*s - 984375*p**5*s**2 - 19531250*p**2*q**2*s**2 - 37890625*p**3*r*s**2 - 7812500*q**2*r*s**2 + 289062500*p*r**2*s**2 - 529296875*p*q*s**3 + 2343750000*s**4 + + b[4][5] = 600*p**10*q**10 + 13850*p**7*q**12 + 106150*p**4*q**14 + 270000*p*q**16 - 9300*p**11*q**8*r - 234075*p**8*q**10*r - 1942825*p**5*q**12*r - 5319900*p**2*q**14*r + 52050*p**12*q**6*r**2 + 1481025*p**9*q**8*r**2 + 13594450*p**6*q**10*r**2 + 40062750*p**3*q**12*r**2 - 3569400*q**14*r**2 - 122175*p**13*q**4*r**3 - 4260350*p**10*q**6*r**3 - 45052375*p**7*q**8*r**3 - 142634900*p**4*q**10*r**3 + 54186350*p*q**12*r**3 + 97200*p**14*q**2*r**4 + 5284225*p**11*q**4*r**4 + 70389525*p**8*q**6*r**4 + 232732850*p**5*q**8*r**4 - 318849400*p**2*q**10*r**4 - 2046000*p**12*q**2*r**5 - 43874125*p**9*q**4*r**5 - 107411850*p**6*q**6*r**5 + 948310700*p**3*q**8*r**5 - 34763575*q**10*r**5 + 5915600*p**10*q**2*r**6 - 115887800*p**7*q**4*r**6 - 1649542400*p**4*q**6*r**6 + 224468875*p*q**8*r**6 + 120252800*p**8*q**2*r**7 + 1779902000*p**5*q**4*r**7 - 288250000*p**2*q**6*r**7 - 915200000*p**6*q**2*r**8 - 1164000000*p**3*q**4*r**8 - 444200000*q**6*r**8 + 2502400000*p**4*q**2*r**9 + 1984000000*p*q**4*r**9 - 2880000000*p**2*q**2*r**10 + 20700*p**12*q**7*s + 551475*p**9*q**9*s + 5194875*p**6*q**11*s + 18985000*p**3*q**13*s + 16875000*q**15*s - 218700*p**13*q**5*r*s - 6606475*p**10*q**7*r*s - 69770850*p**7*q**9*r*s - 285325500*p**4*q**11*r*s - 292005000*p*q**13*r*s + 694575*p**14*q**3*r**2*s + 26187750*p**11*q**5*r**2*s + 328992825*p**8*q**7*r**2*s + 1573292400*p**5*q**9*r**2*s + 1930043875*p**2*q**11*r**2*s - 583200*p**15*q*r**3*s - 37263225*p**12*q**3*r**3*s - 638579425*p**9*q**5*r**3*s - 3920212225*p**6*q**7*r**3*s - 6327336875*p**3*q**9*r**3*s + 440969375*q**11*r**3*s + 13446000*p**13*q*r**4*s + 462330325*p**10*q**3*r**4*s + 4509088275*p**7*q**5*r**4*s + 11709795625*p**4*q**7*r**4*s - 3579565625*p*q**9*r**4*s - 85033600*p**11*q*r**5*s - 2136801600*p**8*q**3*r**5*s - 12221575800*p**5*q**5*r**5*s + 9431044375*p**2*q**7*r**5*s + 10643200*p**9*q*r**6*s + 4565594000*p**6*q**3*r**6*s - 1778590000*p**3*q**5*r**6*s + 4842175000*q**7*r**6*s + 712320000*p**7*q*r**7*s - 16182000000*p**4*q**3*r**7*s - 21918000000*p*q**5*r**7*s - 742400000*p**5*q*r**8*s + 31040000000*p**2*q**3*r**8*s + 1280000000*p**3*q*r**9*s + 4800000000*q**3*r**9*s + 230850*p**14*q**4*s**2 + 7373250*p**11*q**6*s**2 + 85045625*p**8*q**8*s**2 + 399140625*p**5*q**10*s**2 + 565031250*p**2*q**12*s**2 - 1257525*p**15*q**2*r*s**2 - 52728975*p**12*q**4*r*s**2 - 743466375*p**9*q**6*r*s**2 - 4144915000*p**6*q**8*r*s**2 - 7102690625*p**3*q**10*r*s**2 - 1389937500*q**12*r*s**2 + 874800*p**16*r**2*s**2 + 89851275*p**13*q**2*r**2*s**2 + 1897236775*p**10*q**4*r**2*s**2 + 14144163000*p**7*q**6*r**2*s**2 + 31942921875*p**4*q**8*r**2*s**2 + 13305118750*p*q**10*r**2*s**2 - 23004000*p**14*r**3*s**2 - 1450715475*p**11*q**2*r**3*s**2 - 19427105000*p**8*q**4*r**3*s**2 - 70634028750*p**5*q**6*r**3*s**2 - 47854218750*p**2*q**8*r**3*s**2 + 204710400*p**12*r**4*s**2 + 10875135000*p**9*q**2*r**4*s**2 + 83618806250*p**6*q**4*r**4*s**2 + 62744500000*p**3*q**6*r**4*s**2 - 19806718750*q**8*r**4*s**2 - 757094800*p**10*r**5*s**2 - 37718030000*p**7*q**2*r**5*s**2 - 22479500000*p**4*q**4*r**5*s**2 + 91556093750*p*q**6*r**5*s**2 + 2306320000*p**8*r**6*s**2 + 55539600000*p**5*q**2*r**6*s**2 - 112851250000*p**2*q**4*r**6*s**2 - 10720000000*p**6*r**7*s**2 - 64720000000*p**3*q**2*r**7*s**2 - 59925000000*q**4*r**7*s**2 + 28000000000*p**4*r**8*s**2 + 28000000000*p*q**2*r**8*s**2 - 24000000000*p**2*r**9*s**2 + 820125*p**16*q*s**3 + 36804375*p**13*q**3*s**3 + 552225000*p**10*q**5*s**3 + 3357593750*p**7*q**7*s**3 + 7146562500*p**4*q**9*s**3 + 3851562500*p*q**11*s**3 - 92400750*p**14*q*r*s**3 - 2350175625*p**11*q**3*r*s**3 - 19470640625*p**8*q**5*r*s**3 - 52820593750*p**5*q**7*r*s**3 - 45447734375*p**2*q**9*r*s**3 + 1824363000*p**12*q*r**2*s**3 + 31435234375*p**9*q**3*r**2*s**3 + 141717537500*p**6*q**5*r**2*s**3 + 228370781250*p**3*q**7*r**2*s**3 + 34610078125*q**9*r**2*s**3 - 17591825625*p**10*q*r**3*s**3 - 188927187500*p**7*q**3*r**3*s**3 - 502088984375*p**4*q**5*r**3*s**3 - 187849296875*p*q**7*r**3*s**3 + 75577750000*p**8*q*r**4*s**3 + 342800000000*p**5*q**3*r**4*s**3 + 295384296875*p**2*q**5*r**4*s**3 - 107681250000*p**6*q*r**5*s**3 + 53330000000*p**3*q**3*r**5*s**3 + 271586875000*q**5*r**5*s**3 - 26410000000*p**4*q*r**6*s**3 - 188200000000*p*q**3*r**6*s**3 + 92000000000*p**2*q*r**7*s**3 + 120000000000*q*r**8*s**3 + 47840625*p**15*s**4 + 1150453125*p**12*q**2*s**4 + 9229453125*p**9*q**4*s**4 + 24954687500*p**6*q**6*s**4 + 22978515625*p**3*q**8*s**4 + 1367187500*q**10*s**4 - 1193737500*p**13*r*s**4 - 20817843750*p**10*q**2*r*s**4 - 98640000000*p**7*q**4*r*s**4 - 225767187500*p**4*q**6*r*s**4 - 74707031250*p*q**8*r*s**4 + 13431318750*p**11*r**2*s**4 + 188709843750*p**8*q**2*r**2*s**4 + 875157656250*p**5*q**4*r**2*s**4 + 593812890625*p**2*q**6*r**2*s**4 - 69869296875*p**9*r**3*s**4 - 854811093750*p**6*q**2*r**3*s**4 - 1730658203125*p**3*q**4*r**3*s**4 - 570867187500*q**6*r**3*s**4 + 162075625000*p**7*r**4*s**4 + 1536375000000*p**4*q**2*r**4*s**4 + 765156250000*p*q**4*r**4*s**4 - 165988750000*p**5*r**5*s**4 - 728968750000*p**2*q**2*r**5*s**4 + 121500000000*p**3*r**6*s**4 - 1039375000000*q**2*r**6*s**4 - 100000000000*p*r**7*s**4 - 379687500*p**11*q*s**5 - 11607421875*p**8*q**3*s**5 - 20830078125*p**5*q**5*s**5 - 33691406250*p**2*q**7*s**5 - 41491406250*p**9*q*r*s**5 - 419054687500*p**6*q**3*r*s**5 - 129511718750*p**3*q**5*r*s**5 + 311767578125*q**7*r*s**5 + 620116015625*p**7*q*r**2*s**5 + 1154687500000*p**4*q**3*r**2*s**5 + 36455078125*p*q**5*r**2*s**5 - 2265953125000*p**5*q*r**3*s**5 - 1509521484375*p**2*q**3*r**3*s**5 + 2530468750000*p**3*q*r**4*s**5 + 3259765625000*q**3*r**4*s**5 + 93750000000*p*q*r**5*s**5 + 23730468750*p**10*s**6 + 243603515625*p**7*q**2*s**6 + 341552734375*p**4*q**4*s**6 - 12207031250*p*q**6*s**6 - 357099609375*p**8*r*s**6 - 298193359375*p**5*q**2*r*s**6 + 406738281250*p**2*q**4*r*s**6 + 1615683593750*p**6*r**2*s**6 + 558593750000*p**3*q**2*r**2*s**6 - 2811035156250*q**4*r**2*s**6 - 2960937500000*p**4*r**3*s**6 - 3802246093750*p*q**2*r**3*s**6 + 2347656250000*p**2*r**4*s**6 - 671875000000*r**5*s**6 - 651855468750*p**6*q*s**7 - 1458740234375*p**3*q**3*s**7 - 152587890625*q**5*s**7 + 1628417968750*p**4*q*r*s**7 + 3948974609375*p*q**3*r*s**7 - 916748046875*p**2*q*r**2*s**7 + 1611328125000*q*r**3*s**7 + 640869140625*p**5*s**8 + 1068115234375*p**2*q**2*s**8 - 2044677734375*p**3*r*s**8 - 3204345703125*q**2*r*s**8 + 1739501953125*p*r**2*s**8 + + b[4][4] = -600*p**11*q**8 - 14050*p**8*q**10 - 109100*p**5*q**12 - 280800*p**2*q**14 + 7200*p**12*q**6*r + 188700*p**9*q**8*r + 1621725*p**6*q**10*r + 4577075*p**3*q**12*r + 5400*q**14*r - 28350*p**13*q**4*r**2 - 910600*p**10*q**6*r**2 - 9237975*p**7*q**8*r**2 - 30718900*p**4*q**10*r**2 - 5575950*p*q**12*r**2 + 36450*p**14*q**2*r**3 + 1848125*p**11*q**4*r**3 + 25137775*p**8*q**6*r**3 + 109591450*p**5*q**8*r**3 + 70627650*p**2*q**10*r**3 - 1317150*p**12*q**2*r**4 - 32857100*p**9*q**4*r**4 - 219125575*p**6*q**6*r**4 - 327565875*p**3*q**8*r**4 - 13011875*q**10*r**4 + 16484150*p**10*q**2*r**5 + 222242250*p**7*q**4*r**5 + 642173750*p**4*q**6*r**5 + 101263750*p*q**8*r**5 - 79345000*p**8*q**2*r**6 - 433180000*p**5*q**4*r**6 - 93731250*p**2*q**6*r**6 - 74300000*p**6*q**2*r**7 - 1057900000*p**3*q**4*r**7 - 591175000*q**6*r**7 + 1891600000*p**4*q**2*r**8 + 2796000000*p*q**4*r**8 - 4320000000*p**2*q**2*r**9 - 16200*p**13*q**5*s - 359500*p**10*q**7*s - 2603825*p**7*q**9*s - 4590375*p**4*q**11*s + 12352500*p*q**13*s + 121500*p**14*q**3*r*s + 3227400*p**11*q**5*r*s + 27301725*p**8*q**7*r*s + 59480975*p**5*q**9*r*s - 137308875*p**2*q**11*r*s - 218700*p**15*q*r**2*s - 8903925*p**12*q**3*r**2*s - 100918225*p**9*q**5*r**2*s - 325291300*p**6*q**7*r**2*s + 365705000*p**3*q**9*r**2*s + 94342500*q**11*r**2*s + 7632900*p**13*q*r**3*s + 162995400*p**10*q**3*r**3*s + 974558975*p**7*q**5*r**3*s + 930991250*p**4*q**7*r**3*s - 495368750*p*q**9*r**3*s - 97344900*p**11*q*r**4*s - 1406739250*p**8*q**3*r**4*s - 5572526250*p**5*q**5*r**4*s - 1903987500*p**2*q**7*r**4*s + 678550000*p**9*q*r**5*s + 8176215000*p**6*q**3*r**5*s + 18082050000*p**3*q**5*r**5*s + 5435843750*q**7*r**5*s - 2979800000*p**7*q*r**6*s - 29163500000*p**4*q**3*r**6*s - 27417500000*p*q**5*r**6*s + 6282400000*p**5*q*r**7*s + 48690000000*p**2*q**3*r**7*s - 2880000000*p**3*q*r**8*s + 7200000000*q**3*r**8*s - 109350*p**15*q**2*s**2 - 2405700*p**12*q**4*s**2 - 16125250*p**9*q**6*s**2 - 4930000*p**6*q**8*s**2 + 201150000*p**3*q**10*s**2 - 243000000*q**12*s**2 + 328050*p**16*r*s**2 + 10552275*p**13*q**2*r*s**2 + 88019100*p**10*q**4*r*s**2 - 4208625*p**7*q**6*r*s**2 - 1920390625*p**4*q**8*r*s**2 + 1759537500*p*q**10*r*s**2 - 11955600*p**14*r**2*s**2 - 196375050*p**11*q**2*r**2*s**2 - 555196250*p**8*q**4*r**2*s**2 + 4213270000*p**5*q**6*r**2*s**2 - 157468750*p**2*q**8*r**2*s**2 + 162656100*p**12*r**3*s**2 + 1880870000*p**9*q**2*r**3*s**2 + 753684375*p**6*q**4*r**3*s**2 - 25423062500*p**3*q**6*r**3*s**2 - 14142031250*q**8*r**3*s**2 - 1251948750*p**10*r**4*s**2 - 12524475000*p**7*q**2*r**4*s**2 + 18067656250*p**4*q**4*r**4*s**2 + 60531875000*p*q**6*r**4*s**2 + 6827725000*p**8*r**5*s**2 + 57157000000*p**5*q**2*r**5*s**2 - 75844531250*p**2*q**4*r**5*s**2 - 24452500000*p**6*r**6*s**2 - 144950000000*p**3*q**2*r**6*s**2 - 82109375000*q**4*r**6*s**2 + 46950000000*p**4*r**7*s**2 + 60000000000*p*q**2*r**7*s**2 - 36000000000*p**2*r**8*s**2 + 1549125*p**14*q*s**3 + 51873750*p**11*q**3*s**3 + 599781250*p**8*q**5*s**3 + 2421156250*p**5*q**7*s**3 - 1693515625*p**2*q**9*s**3 - 104884875*p**12*q*r*s**3 - 1937437500*p**9*q**3*r*s**3 - 11461053125*p**6*q**5*r*s**3 + 10299375000*p**3*q**7*r*s**3 + 10551250000*q**9*r*s**3 + 1336263750*p**10*q*r**2*s**3 + 23737250000*p**7*q**3*r**2*s**3 + 57136718750*p**4*q**5*r**2*s**3 - 8288906250*p*q**7*r**2*s**3 - 10907218750*p**8*q*r**3*s**3 - 160615000000*p**5*q**3*r**3*s**3 - 111134687500*p**2*q**5*r**3*s**3 + 46743125000*p**6*q*r**4*s**3 + 570509375000*p**3*q**3*r**4*s**3 + 274839843750*q**5*r**4*s**3 - 73312500000*p**4*q*r**5*s**3 - 145437500000*p*q**3*r**5*s**3 + 8750000000*p**2*q*r**6*s**3 + 180000000000*q*r**7*s**3 + 15946875*p**13*s**4 + 1265625*p**10*q**2*s**4 - 3282343750*p**7*q**4*s**4 - 38241406250*p**4*q**6*s**4 - 40136718750*p*q**8*s**4 - 113146875*p**11*r*s**4 - 2302734375*p**8*q**2*r*s**4 + 68450156250*p**5*q**4*r*s**4 + 177376562500*p**2*q**6*r*s**4 + 3164062500*p**9*r**2*s**4 + 14392890625*p**6*q**2*r**2*s**4 - 543781250000*p**3*q**4*r**2*s**4 - 319769531250*q**6*r**2*s**4 - 21048281250*p**7*r**3*s**4 - 240687500000*p**4*q**2*r**3*s**4 - 228164062500*p*q**4*r**3*s**4 + 23062500000*p**5*r**4*s**4 + 300410156250*p**2*q**2*r**4*s**4 + 93437500000*p**3*r**5*s**4 - 1141015625000*q**2*r**5*s**4 - 187500000000*p*r**6*s**4 + 1761328125*p**9*q*s**5 - 3177734375*p**6*q**3*s**5 + 60019531250*p**3*q**5*s**5 + 108398437500*q**7*s**5 + 24106640625*p**7*q*r*s**5 + 429589843750*p**4*q**3*r*s**5 + 410371093750*p*q**5*r*s**5 - 23582031250*p**5*q*r**2*s**5 + 202441406250*p**2*q**3*r**2*s**5 - 383203125000*p**3*q*r**3*s**5 + 2232910156250*q**3*r**3*s**5 + 1500000000000*p*q*r**4*s**5 - 13710937500*p**8*s**6 - 202832031250*p**5*q**2*s**6 - 531738281250*p**2*q**4*s**6 + 73330078125*p**6*r*s**6 - 3906250000*p**3*q**2*r*s**6 - 1275878906250*q**4*r*s**6 - 121093750000*p**4*r**2*s**6 - 3308593750000*p*q**2*r**2*s**6 + 18066406250*p**2*r**3*s**6 - 244140625000*r**4*s**6 + 327148437500*p**4*q*s**7 + 1672363281250*p*q**3*s**7 + 446777343750*p**2*q*r*s**7 + 1232910156250*q*r**2*s**7 - 274658203125*p**3*s**8 - 1068115234375*q**2*s**8 - 61035156250*p*r*s**8 + + b[4][3] = 200*p**9*q**8 + 7550*p**6*q**10 + 78650*p**3*q**12 + 248400*q**14 - 4800*p**10*q**6*r - 164300*p**7*q**8*r - 1709575*p**4*q**10*r - 5566500*p*q**12*r + 31050*p**11*q**4*r**2 + 1116175*p**8*q**6*r**2 + 12674650*p**5*q**8*r**2 + 45333850*p**2*q**10*r**2 - 60750*p**12*q**2*r**3 - 2872725*p**9*q**4*r**3 - 40403050*p**6*q**6*r**3 - 173564375*p**3*q**8*r**3 - 11242250*q**10*r**3 + 2174100*p**10*q**2*r**4 + 54010000*p**7*q**4*r**4 + 331074875*p**4*q**6*r**4 + 114173750*p*q**8*r**4 - 24858500*p**8*q**2*r**5 - 300875000*p**5*q**4*r**5 - 319430625*p**2*q**6*r**5 + 69810000*p**6*q**2*r**6 - 23900000*p**3*q**4*r**6 - 294662500*q**6*r**6 + 524200000*p**4*q**2*r**7 + 1432000000*p*q**4*r**7 - 2340000000*p**2*q**2*r**8 + 5400*p**11*q**5*s + 310400*p**8*q**7*s + 3591725*p**5*q**9*s + 11556750*p**2*q**11*s - 105300*p**12*q**3*r*s - 4234650*p**9*q**5*r*s - 49928875*p**6*q**7*r*s - 174078125*p**3*q**9*r*s + 18000000*q**11*r*s + 364500*p**13*q*r**2*s + 15763050*p**10*q**3*r**2*s + 220187400*p**7*q**5*r**2*s + 929609375*p**4*q**7*r**2*s - 43653125*p*q**9*r**2*s - 13427100*p**11*q*r**3*s - 346066250*p**8*q**3*r**3*s - 2287673375*p**5*q**5*r**3*s - 1403903125*p**2*q**7*r**3*s + 184586000*p**9*q*r**4*s + 2983460000*p**6*q**3*r**4*s + 8725818750*p**3*q**5*r**4*s + 2527734375*q**7*r**4*s - 1284480000*p**7*q*r**5*s - 13138250000*p**4*q**3*r**5*s - 14001625000*p*q**5*r**5*s + 4224800000*p**5*q*r**6*s + 27460000000*p**2*q**3*r**6*s - 3760000000*p**3*q*r**7*s + 3900000000*q**3*r**7*s + 36450*p**13*q**2*s**2 + 2765475*p**10*q**4*s**2 + 34027625*p**7*q**6*s**2 + 97375000*p**4*q**8*s**2 - 88275000*p*q**10*s**2 - 546750*p**14*r*s**2 - 21961125*p**11*q**2*r*s**2 - 273059375*p**8*q**4*r*s**2 - 761562500*p**5*q**6*r*s**2 + 1869656250*p**2*q**8*r*s**2 + 20545650*p**12*r**2*s**2 + 473934375*p**9*q**2*r**2*s**2 + 1758053125*p**6*q**4*r**2*s**2 - 8743359375*p**3*q**6*r**2*s**2 - 4154375000*q**8*r**2*s**2 - 296559000*p**10*r**3*s**2 - 4065056250*p**7*q**2*r**3*s**2 - 186328125*p**4*q**4*r**3*s**2 + 19419453125*p*q**6*r**3*s**2 + 2326262500*p**8*r**4*s**2 + 21189375000*p**5*q**2*r**4*s**2 - 26301953125*p**2*q**4*r**4*s**2 - 10513250000*p**6*r**5*s**2 - 69937500000*p**3*q**2*r**5*s**2 - 42257812500*q**4*r**5*s**2 + 23375000000*p**4*r**6*s**2 + 40750000000*p*q**2*r**6*s**2 - 19500000000*p**2*r**7*s**2 + 4009500*p**12*q*s**3 + 36140625*p**9*q**3*s**3 - 335459375*p**6*q**5*s**3 - 2695312500*p**3*q**7*s**3 - 1486250000*q**9*s**3 + 102515625*p**10*q*r*s**3 + 4006812500*p**7*q**3*r*s**3 + 27589609375*p**4*q**5*r*s**3 + 20195312500*p*q**7*r*s**3 - 2792812500*p**8*q*r**2*s**3 - 44115156250*p**5*q**3*r**2*s**3 - 72609453125*p**2*q**5*r**2*s**3 + 18752500000*p**6*q*r**3*s**3 + 218140625000*p**3*q**3*r**3*s**3 + 109940234375*q**5*r**3*s**3 - 21893750000*p**4*q*r**4*s**3 - 65187500000*p*q**3*r**4*s**3 - 31000000000*p**2*q*r**5*s**3 + 97500000000*q*r**6*s**3 - 86568750*p**11*s**4 - 1955390625*p**8*q**2*s**4 - 8960781250*p**5*q**4*s**4 - 1357812500*p**2*q**6*s**4 + 1657968750*p**9*r*s**4 + 10467187500*p**6*q**2*r*s**4 - 55292968750*p**3*q**4*r*s**4 - 60683593750*q**6*r*s**4 - 11473593750*p**7*r**2*s**4 - 123281250000*p**4*q**2*r**2*s**4 - 164912109375*p*q**4*r**2*s**4 + 13150000000*p**5*r**3*s**4 + 190751953125*p**2*q**2*r**3*s**4 + 61875000000*p**3*r**4*s**4 - 467773437500*q**2*r**4*s**4 - 118750000000*p*r**5*s**4 + 7583203125*p**7*q*s**5 + 54638671875*p**4*q**3*s**5 + 39423828125*p*q**5*s**5 + 32392578125*p**5*q*r*s**5 + 278515625000*p**2*q**3*r*s**5 - 298339843750*p**3*q*r**2*s**5 + 560791015625*q**3*r**2*s**5 + 720703125000*p*q*r**3*s**5 - 19687500000*p**6*s**6 - 159667968750*p**3*q**2*s**6 - 72265625000*q**4*s**6 + 116699218750*p**4*r*s**6 - 924072265625*p*q**2*r*s**6 - 156005859375*p**2*r**2*s**6 - 112304687500*r**3*s**6 + 349121093750*p**2*q*s**7 + 396728515625*q*r*s**7 - 213623046875*p*s**8 + + b[4][2] = -600*p**10*q**6 - 18450*p**7*q**8 - 174000*p**4*q**10 - 518400*p*q**12 + 5400*p**11*q**4*r + 197550*p**8*q**6*r + 2147775*p**5*q**8*r + 7219800*p**2*q**10*r - 12150*p**12*q**2*r**2 - 662200*p**9*q**4*r**2 - 9274775*p**6*q**6*r**2 - 38330625*p**3*q**8*r**2 - 5508000*q**10*r**2 + 656550*p**10*q**2*r**3 + 16233750*p**7*q**4*r**3 + 97335875*p**4*q**6*r**3 + 58271250*p*q**8*r**3 - 9845500*p**8*q**2*r**4 - 119464375*p**5*q**4*r**4 - 194431875*p**2*q**6*r**4 + 49465000*p**6*q**2*r**5 + 166000000*p**3*q**4*r**5 - 80793750*q**6*r**5 + 54400000*p**4*q**2*r**6 + 377750000*p*q**4*r**6 - 630000000*p**2*q**2*r**7 - 16200*p**12*q**3*s - 459300*p**9*q**5*s - 4207225*p**6*q**7*s - 10827500*p**3*q**9*s + 13635000*q**11*s + 72900*p**13*q*r*s + 2877300*p**10*q**3*r*s + 33239700*p**7*q**5*r*s + 107080625*p**4*q**7*r*s - 114975000*p*q**9*r*s - 3601800*p**11*q*r**2*s - 75214375*p**8*q**3*r**2*s - 387073250*p**5*q**5*r**2*s + 55540625*p**2*q**7*r**2*s + 53793000*p**9*q*r**3*s + 687176875*p**6*q**3*r**3*s + 1670018750*p**3*q**5*r**3*s + 665234375*q**7*r**3*s - 391570000*p**7*q*r**4*s - 3420125000*p**4*q**3*r**4*s - 3609625000*p*q**5*r**4*s + 1365600000*p**5*q*r**5*s + 7236250000*p**2*q**3*r**5*s - 1220000000*p**3*q*r**6*s + 1050000000*q**3*r**6*s - 109350*p**14*s**2 - 3065850*p**11*q**2*s**2 - 26908125*p**8*q**4*s**2 - 44606875*p**5*q**6*s**2 + 269812500*p**2*q**8*s**2 + 5200200*p**12*r*s**2 + 81826875*p**9*q**2*r*s**2 + 155378125*p**6*q**4*r*s**2 - 1936203125*p**3*q**6*r*s**2 - 998437500*q**8*r*s**2 - 77145750*p**10*r**2*s**2 - 745528125*p**7*q**2*r**2*s**2 + 683437500*p**4*q**4*r**2*s**2 + 4083359375*p*q**6*r**2*s**2 + 593287500*p**8*r**3*s**2 + 4799375000*p**5*q**2*r**3*s**2 - 4167578125*p**2*q**4*r**3*s**2 - 2731125000*p**6*r**4*s**2 - 18668750000*p**3*q**2*r**4*s**2 - 10480468750*q**4*r**4*s**2 + 6200000000*p**4*r**5*s**2 + 11750000000*p*q**2*r**5*s**2 - 5250000000*p**2*r**6*s**2 + 26527500*p**10*q*s**3 + 526031250*p**7*q**3*s**3 + 3160703125*p**4*q**5*s**3 + 2650312500*p*q**7*s**3 - 448031250*p**8*q*r*s**3 - 6682968750*p**5*q**3*r*s**3 - 11642812500*p**2*q**5*r*s**3 + 2553203125*p**6*q*r**2*s**3 + 37234375000*p**3*q**3*r**2*s**3 + 21871484375*q**5*r**2*s**3 + 2803125000*p**4*q*r**3*s**3 - 10796875000*p*q**3*r**3*s**3 - 16656250000*p**2*q*r**4*s**3 + 26250000000*q*r**5*s**3 - 75937500*p**9*s**4 - 704062500*p**6*q**2*s**4 - 8363281250*p**3*q**4*s**4 - 10398437500*q**6*s**4 + 197578125*p**7*r*s**4 - 16441406250*p**4*q**2*r*s**4 - 24277343750*p*q**4*r*s**4 - 5716015625*p**5*r**2*s**4 + 31728515625*p**2*q**2*r**2*s**4 + 27031250000*p**3*r**3*s**4 - 92285156250*q**2*r**3*s**4 - 33593750000*p*r**4*s**4 + 10394531250*p**5*q*s**5 + 38037109375*p**2*q**3*s**5 - 48144531250*p**3*q*r*s**5 + 74462890625*q**3*r*s**5 + 121093750000*p*q*r**2*s**5 - 2197265625*p**4*s**6 - 92529296875*p*q**2*s**6 + 15380859375*p**2*r*s**6 - 31738281250*r**2*s**6 + 54931640625*q*s**7 + + b[4][1] = 200*p**8*q**6 + 2950*p**5*q**8 + 10800*p**2*q**10 - 1800*p**9*q**4*r - 49650*p**6*q**6*r - 403375*p**3*q**8*r - 999000*q**10*r + 4050*p**10*q**2*r**2 + 236625*p**7*q**4*r**2 + 3109500*p**4*q**6*r**2 + 11463750*p*q**8*r**2 - 331500*p**8*q**2*r**3 - 7818125*p**5*q**4*r**3 - 41411250*p**2*q**6*r**3 + 4782500*p**6*q**2*r**4 + 47475000*p**3*q**4*r**4 - 16728125*q**6*r**4 - 8700000*p**4*q**2*r**5 + 81750000*p*q**4*r**5 - 135000000*p**2*q**2*r**6 + 5400*p**10*q**3*s + 144200*p**7*q**5*s + 939375*p**4*q**7*s + 1012500*p*q**9*s - 24300*p**11*q*r*s - 1169250*p**8*q**3*r*s - 14027250*p**5*q**5*r*s - 44446875*p**2*q**7*r*s + 2011500*p**9*q*r**2*s + 49330625*p**6*q**3*r**2*s + 272009375*p**3*q**5*r**2*s + 104062500*q**7*r**2*s - 34660000*p**7*q*r**3*s - 455062500*p**4*q**3*r**3*s - 625906250*p*q**5*r**3*s + 210200000*p**5*q*r**4*s + 1298750000*p**2*q**3*r**4*s - 240000000*p**3*q*r**5*s + 225000000*q**3*r**5*s + 36450*p**12*s**2 + 1231875*p**9*q**2*s**2 + 10712500*p**6*q**4*s**2 + 21718750*p**3*q**6*s**2 + 16875000*q**8*s**2 - 2814750*p**10*r*s**2 - 67612500*p**7*q**2*r*s**2 - 345156250*p**4*q**4*r*s**2 - 283125000*p*q**6*r*s**2 + 51300000*p**8*r**2*s**2 + 734531250*p**5*q**2*r**2*s**2 + 1267187500*p**2*q**4*r**2*s**2 - 384312500*p**6*r**3*s**2 - 3912500000*p**3*q**2*r**3*s**2 - 1822265625*q**4*r**3*s**2 + 1112500000*p**4*r**4*s**2 + 2437500000*p*q**2*r**4*s**2 - 1125000000*p**2*r**5*s**2 - 72578125*p**5*q**3*s**3 - 189296875*p**2*q**5*s**3 + 127265625*p**6*q*r*s**3 + 1415625000*p**3*q**3*r*s**3 + 1229687500*q**5*r*s**3 + 1448437500*p**4*q*r**2*s**3 + 2218750000*p*q**3*r**2*s**3 - 4031250000*p**2*q*r**3*s**3 + 5625000000*q*r**4*s**3 - 132890625*p**7*s**4 - 529296875*p**4*q**2*s**4 - 175781250*p*q**4*s**4 - 401953125*p**5*r*s**4 - 4482421875*p**2*q**2*r*s**4 + 4140625000*p**3*r**2*s**4 - 10498046875*q**2*r**2*s**4 - 7031250000*p*r**3*s**4 + 1220703125*p**3*q*s**5 + 1953125000*q**3*s**5 + 14160156250*p*q*r*s**5 - 1708984375*p**2*s**6 - 3662109375*r*s**6 + + b[4][0] = -4600*p**6*q**6 - 67850*p**3*q**8 - 248400*q**10 + 38900*p**7*q**4*r + 679575*p**4*q**6*r + 2866500*p*q**8*r - 81900*p**8*q**2*r**2 - 2009750*p**5*q**4*r**2 - 10783750*p**2*q**6*r**2 + 1478750*p**6*q**2*r**3 + 14165625*p**3*q**4*r**3 - 2743750*q**6*r**3 - 5450000*p**4*q**2*r**4 + 12687500*p*q**4*r**4 - 22500000*p**2*q**2*r**5 - 101700*p**8*q**3*s - 1700975*p**5*q**5*s - 7061250*p**2*q**7*s + 423900*p**9*q*r*s + 9292375*p**6*q**3*r*s + 50438750*p**3*q**5*r*s + 20475000*q**7*r*s - 7852500*p**7*q*r**2*s - 87765625*p**4*q**3*r**2*s - 121609375*p*q**5*r**2*s + 47700000*p**5*q*r**3*s + 264687500*p**2*q**3*r**3*s - 65000000*p**3*q*r**4*s + 37500000*q**3*r**4*s - 534600*p**10*s**2 - 10344375*p**7*q**2*s**2 - 54859375*p**4*q**4*s**2 - 40312500*p*q**6*s**2 + 10158750*p**8*r*s**2 + 117778125*p**5*q**2*r*s**2 + 192421875*p**2*q**4*r*s**2 - 70593750*p**6*r**2*s**2 - 685312500*p**3*q**2*r**2*s**2 - 334375000*q**4*r**2*s**2 + 193750000*p**4*r**3*s**2 + 500000000*p*q**2*r**3*s**2 - 187500000*p**2*r**4*s**2 + 8437500*p**6*q*s**3 + 159218750*p**3*q**3*s**3 + 220625000*q**5*s**3 + 353828125*p**4*q*r*s**3 + 412500000*p*q**3*r*s**3 - 1023437500*p**2*q*r**2*s**3 + 937500000*q*r**3*s**3 - 206015625*p**5*s**4 - 701171875*p**2*q**2*s**4 + 998046875*p**3*r*s**4 - 1308593750*q**2*r*s**4 - 1367187500*p*r**2*s**4 + 1708984375*p*q*s**5 - 976562500*s**6 + + return b + + @property + def o(self): + p, q, r, s = self.p, self.q, self.r, self.s + o = [0]*6 + + o[5] = -1600*p**10*q**10 - 23600*p**7*q**12 - 86400*p**4*q**14 + 24800*p**11*q**8*r + 419200*p**8*q**10*r + 1850450*p**5*q**12*r + 896400*p**2*q**14*r - 138800*p**12*q**6*r**2 - 2921900*p**9*q**8*r**2 - 17295200*p**6*q**10*r**2 - 27127750*p**3*q**12*r**2 - 26076600*q**14*r**2 + 325800*p**13*q**4*r**3 + 9993850*p**10*q**6*r**3 + 88010500*p**7*q**8*r**3 + 274047650*p**4*q**10*r**3 + 410171400*p*q**12*r**3 - 259200*p**14*q**2*r**4 - 17147100*p**11*q**4*r**4 - 254289150*p**8*q**6*r**4 - 1318548225*p**5*q**8*r**4 - 2633598475*p**2*q**10*r**4 + 12636000*p**12*q**2*r**5 + 388911000*p**9*q**4*r**5 + 3269704725*p**6*q**6*r**5 + 8791192300*p**3*q**8*r**5 + 93560575*q**10*r**5 - 228361600*p**10*q**2*r**6 - 3951199200*p**7*q**4*r**6 - 16276981100*p**4*q**6*r**6 - 1597227000*p*q**8*r**6 + 1947899200*p**8*q**2*r**7 + 17037648000*p**5*q**4*r**7 + 8919740000*p**2*q**6*r**7 - 7672160000*p**6*q**2*r**8 - 15496000000*p**3*q**4*r**8 + 4224000000*q**6*r**8 + 9968000000*p**4*q**2*r**9 - 8640000000*p*q**4*r**9 + 4800000000*p**2*q**2*r**10 - 55200*p**12*q**7*s - 685600*p**9*q**9*s + 1028250*p**6*q**11*s + 37650000*p**3*q**13*s + 111375000*q**15*s + 583200*p**13*q**5*r*s + 9075600*p**10*q**7*r*s - 883150*p**7*q**9*r*s - 506830750*p**4*q**11*r*s - 1793137500*p*q**13*r*s - 1852200*p**14*q**3*r**2*s - 41435250*p**11*q**5*r**2*s - 80566700*p**8*q**7*r**2*s + 2485673600*p**5*q**9*r**2*s + 11442286125*p**2*q**11*r**2*s + 1555200*p**15*q*r**3*s + 80846100*p**12*q**3*r**3*s + 564906800*p**9*q**5*r**3*s - 4493012400*p**6*q**7*r**3*s - 35492391250*p**3*q**9*r**3*s - 789931875*q**11*r**3*s - 71766000*p**13*q*r**4*s - 1551149200*p**10*q**3*r**4*s - 1773437900*p**7*q**5*r**4*s + 51957593125*p**4*q**7*r**4*s + 14964765625*p*q**9*r**4*s + 1231569600*p**11*q*r**5*s + 12042977600*p**8*q**3*r**5*s - 27151011200*p**5*q**5*r**5*s - 88080610000*p**2*q**7*r**5*s - 9912995200*p**9*q*r**6*s - 29448104000*p**6*q**3*r**6*s + 144954840000*p**3*q**5*r**6*s - 44601300000*q**7*r**6*s + 35453760000*p**7*q*r**7*s - 63264000000*p**4*q**3*r**7*s + 60544000000*p*q**5*r**7*s - 30048000000*p**5*q*r**8*s + 37040000000*p**2*q**3*r**8*s - 60800000000*p**3*q*r**9*s - 48000000000*q**3*r**9*s - 615600*p**14*q**4*s**2 - 10524500*p**11*q**6*s**2 - 33831250*p**8*q**8*s**2 + 222806250*p**5*q**10*s**2 + 1099687500*p**2*q**12*s**2 + 3353400*p**15*q**2*r*s**2 + 74269350*p**12*q**4*r*s**2 + 276445750*p**9*q**6*r*s**2 - 2618600000*p**6*q**8*r*s**2 - 14473243750*p**3*q**10*r*s**2 + 1383750000*q**12*r*s**2 - 2332800*p**16*r**2*s**2 - 132750900*p**13*q**2*r**2*s**2 - 900775150*p**10*q**4*r**2*s**2 + 8249244500*p**7*q**6*r**2*s**2 + 59525796875*p**4*q**8*r**2*s**2 - 40292868750*p*q**10*r**2*s**2 + 128304000*p**14*r**3*s**2 + 3160232100*p**11*q**2*r**3*s**2 + 8329580000*p**8*q**4*r**3*s**2 - 45558458750*p**5*q**6*r**3*s**2 + 297252890625*p**2*q**8*r**3*s**2 - 2769854400*p**12*r**4*s**2 - 37065970000*p**9*q**2*r**4*s**2 - 90812546875*p**6*q**4*r**4*s**2 - 627902000000*p**3*q**6*r**4*s**2 + 181347421875*q**8*r**4*s**2 + 30946932800*p**10*r**5*s**2 + 249954680000*p**7*q**2*r**5*s**2 + 802954812500*p**4*q**4*r**5*s**2 - 80900000000*p*q**6*r**5*s**2 - 192137320000*p**8*r**6*s**2 - 932641600000*p**5*q**2*r**6*s**2 - 943242500000*p**2*q**4*r**6*s**2 + 658412000000*p**6*r**7*s**2 + 1930720000000*p**3*q**2*r**7*s**2 + 593800000000*q**4*r**7*s**2 - 1162800000000*p**4*r**8*s**2 - 280000000000*p*q**2*r**8*s**2 + 840000000000*p**2*r**9*s**2 - 2187000*p**16*q*s**3 - 47418750*p**13*q**3*s**3 - 180618750*p**10*q**5*s**3 + 2231250000*p**7*q**7*s**3 + 17857734375*p**4*q**9*s**3 + 29882812500*p*q**11*s**3 + 24664500*p**14*q*r*s**3 - 853368750*p**11*q**3*r*s**3 - 25939693750*p**8*q**5*r*s**3 - 177541562500*p**5*q**7*r*s**3 - 297978828125*p**2*q**9*r*s**3 - 153468000*p**12*q*r**2*s**3 + 30188125000*p**9*q**3*r**2*s**3 + 344049821875*p**6*q**5*r**2*s**3 + 534026875000*p**3*q**7*r**2*s**3 - 340726484375*q**9*r**2*s**3 - 9056190000*p**10*q*r**3*s**3 - 322314687500*p**7*q**3*r**3*s**3 - 769632109375*p**4*q**5*r**3*s**3 - 83276875000*p*q**7*r**3*s**3 + 164061000000*p**8*q*r**4*s**3 + 1381358750000*p**5*q**3*r**4*s**3 + 3088020000000*p**2*q**5*r**4*s**3 - 1267655000000*p**6*q*r**5*s**3 - 7642630000000*p**3*q**3*r**5*s**3 - 2759877500000*q**5*r**5*s**3 + 4597760000000*p**4*q*r**6*s**3 + 1846200000000*p*q**3*r**6*s**3 - 7006000000000*p**2*q*r**7*s**3 - 1200000000000*q*r**8*s**3 + 18225000*p**15*s**4 + 1328906250*p**12*q**2*s**4 + 24729140625*p**9*q**4*s**4 + 169467187500*p**6*q**6*s**4 + 413281250000*p**3*q**8*s**4 + 223828125000*q**10*s**4 + 710775000*p**13*r*s**4 - 18611015625*p**10*q**2*r*s**4 - 314344375000*p**7*q**4*r*s**4 - 828439843750*p**4*q**6*r*s**4 + 460937500000*p*q**8*r*s**4 - 25674975000*p**11*r**2*s**4 - 52223515625*p**8*q**2*r**2*s**4 - 387160000000*p**5*q**4*r**2*s**4 - 4733680078125*p**2*q**6*r**2*s**4 + 343911875000*p**9*r**3*s**4 + 3328658359375*p**6*q**2*r**3*s**4 + 16532406250000*p**3*q**4*r**3*s**4 + 5980613281250*q**6*r**3*s**4 - 2295497500000*p**7*r**4*s**4 - 14809820312500*p**4*q**2*r**4*s**4 - 6491406250000*p*q**4*r**4*s**4 + 7768470000000*p**5*r**5*s**4 + 34192562500000*p**2*q**2*r**5*s**4 - 11859000000000*p**3*r**6*s**4 + 10530000000000*q**2*r**6*s**4 + 6000000000000*p*r**7*s**4 + 11453906250*p**11*q*s**5 + 149765625000*p**8*q**3*s**5 + 545537109375*p**5*q**5*s**5 + 527343750000*p**2*q**7*s**5 - 371313281250*p**9*q*r*s**5 - 3461455078125*p**6*q**3*r*s**5 - 7920878906250*p**3*q**5*r*s**5 - 4747314453125*q**7*r*s**5 + 2417815625000*p**7*q*r**2*s**5 + 5465576171875*p**4*q**3*r**2*s**5 + 5937128906250*p*q**5*r**2*s**5 - 10661156250000*p**5*q*r**3*s**5 - 63574218750000*p**2*q**3*r**3*s**5 + 24059375000000*p**3*q*r**4*s**5 - 33023437500000*q**3*r**4*s**5 - 43125000000000*p*q*r**5*s**5 + 94394531250*p**10*s**6 + 1097167968750*p**7*q**2*s**6 + 2829833984375*p**4*q**4*s**6 - 1525878906250*p*q**6*s**6 + 2724609375*p**8*r*s**6 + 13998535156250*p**5*q**2*r*s**6 + 57094482421875*p**2*q**4*r*s**6 - 8512509765625*p**6*r**2*s**6 - 37941406250000*p**3*q**2*r**2*s**6 + 33191894531250*q**4*r**2*s**6 + 50534179687500*p**4*r**3*s**6 + 156656250000000*p*q**2*r**3*s**6 - 85023437500000*p**2*r**4*s**6 + 10125000000000*r**5*s**6 - 2717285156250*p**6*q*s**7 - 11352539062500*p**3*q**3*s**7 - 2593994140625*q**5*s**7 - 47154541015625*p**4*q*r*s**7 - 160644531250000*p*q**3*r*s**7 + 142500000000000*p**2*q*r**2*s**7 - 26757812500000*q*r**3*s**7 - 4364013671875*p**5*s**8 - 94604492187500*p**2*q**2*s**8 + 114379882812500*p**3*r*s**8 + 51116943359375*q**2*r*s**8 - 346435546875000*p*r**2*s**8 + 476837158203125*p*q*s**9 - 476837158203125*s**10 + + o[4] = 1600*p**11*q**8 + 20800*p**8*q**10 + 45100*p**5*q**12 - 151200*p**2*q**14 - 19200*p**12*q**6*r - 293200*p**9*q**8*r - 794600*p**6*q**10*r + 2634675*p**3*q**12*r + 2640600*q**14*r + 75600*p**13*q**4*r**2 + 1529100*p**10*q**6*r**2 + 6233350*p**7*q**8*r**2 - 12013350*p**4*q**10*r**2 - 29069550*p*q**12*r**2 - 97200*p**14*q**2*r**3 - 3562500*p**11*q**4*r**3 - 26984900*p**8*q**6*r**3 - 15900325*p**5*q**8*r**3 + 76267100*p**2*q**10*r**3 + 3272400*p**12*q**2*r**4 + 59486850*p**9*q**4*r**4 + 221270075*p**6*q**6*r**4 + 74065250*p**3*q**8*r**4 - 300564375*q**10*r**4 - 45569400*p**10*q**2*r**5 - 438666000*p**7*q**4*r**5 - 444821250*p**4*q**6*r**5 + 2448256250*p*q**8*r**5 + 290640000*p**8*q**2*r**6 + 855850000*p**5*q**4*r**6 - 5741875000*p**2*q**6*r**6 - 644000000*p**6*q**2*r**7 + 5574000000*p**3*q**4*r**7 + 4643000000*q**6*r**7 - 1696000000*p**4*q**2*r**8 - 12660000000*p*q**4*r**8 + 7200000000*p**2*q**2*r**9 + 43200*p**13*q**5*s + 572000*p**10*q**7*s - 59800*p**7*q**9*s - 24174625*p**4*q**11*s - 74587500*p*q**13*s - 324000*p**14*q**3*r*s - 5531400*p**11*q**5*r*s - 3712100*p**8*q**7*r*s + 293009275*p**5*q**9*r*s + 1115548875*p**2*q**11*r*s + 583200*p**15*q*r**2*s + 18343800*p**12*q**3*r**2*s + 77911100*p**9*q**5*r**2*s - 957488825*p**6*q**7*r**2*s - 5449661250*p**3*q**9*r**2*s + 960120000*q**11*r**2*s - 23684400*p**13*q*r**3*s - 373761900*p**10*q**3*r**3*s - 27944975*p**7*q**5*r**3*s + 10375740625*p**4*q**7*r**3*s - 4649093750*p*q**9*r**3*s + 395816400*p**11*q*r**4*s + 2910968000*p**8*q**3*r**4*s - 9126162500*p**5*q**5*r**4*s - 11696118750*p**2*q**7*r**4*s - 3028640000*p**9*q*r**5*s - 3251550000*p**6*q**3*r**5*s + 47914250000*p**3*q**5*r**5*s - 30255625000*q**7*r**5*s + 9304000000*p**7*q*r**6*s - 42970000000*p**4*q**3*r**6*s + 31475000000*p*q**5*r**6*s + 2176000000*p**5*q*r**7*s + 62100000000*p**2*q**3*r**7*s - 43200000000*p**3*q*r**8*s - 72000000000*q**3*r**8*s + 291600*p**15*q**2*s**2 + 2702700*p**12*q**4*s**2 - 38692250*p**9*q**6*s**2 - 538903125*p**6*q**8*s**2 - 1613112500*p**3*q**10*s**2 + 320625000*q**12*s**2 - 874800*p**16*r*s**2 - 14166900*p**13*q**2*r*s**2 + 193284900*p**10*q**4*r*s**2 + 3688520500*p**7*q**6*r*s**2 + 11613390625*p**4*q**8*r*s**2 - 15609881250*p*q**10*r*s**2 + 44031600*p**14*r**2*s**2 + 482345550*p**11*q**2*r**2*s**2 - 2020881875*p**8*q**4*r**2*s**2 - 7407026250*p**5*q**6*r**2*s**2 + 136175750000*p**2*q**8*r**2*s**2 - 1000884600*p**12*r**3*s**2 - 8888950000*p**9*q**2*r**3*s**2 - 30101703125*p**6*q**4*r**3*s**2 - 319761000000*p**3*q**6*r**3*s**2 + 51519218750*q**8*r**3*s**2 + 12622395000*p**10*r**4*s**2 + 97032450000*p**7*q**2*r**4*s**2 + 469929218750*p**4*q**4*r**4*s**2 + 291342187500*p*q**6*r**4*s**2 - 96382000000*p**8*r**5*s**2 - 598070000000*p**5*q**2*r**5*s**2 - 1165021875000*p**2*q**4*r**5*s**2 + 446500000000*p**6*r**6*s**2 + 1651500000000*p**3*q**2*r**6*s**2 + 789375000000*q**4*r**6*s**2 - 1152000000000*p**4*r**7*s**2 - 600000000000*p*q**2*r**7*s**2 + 1260000000000*p**2*r**8*s**2 - 24786000*p**14*q*s**3 - 660487500*p**11*q**3*s**3 - 5886356250*p**8*q**5*s**3 - 18137187500*p**5*q**7*s**3 - 5120546875*p**2*q**9*s**3 + 827658000*p**12*q*r*s**3 + 13343062500*p**9*q**3*r*s**3 + 39782068750*p**6*q**5*r*s**3 - 111288437500*p**3*q**7*r*s**3 - 15438750000*q**9*r*s**3 - 14540782500*p**10*q*r**2*s**3 - 135889750000*p**7*q**3*r**2*s**3 - 176892578125*p**4*q**5*r**2*s**3 - 934462656250*p*q**7*r**2*s**3 + 171669250000*p**8*q*r**3*s**3 + 1164538125000*p**5*q**3*r**3*s**3 + 3192346406250*p**2*q**5*r**3*s**3 - 1295476250000*p**6*q*r**4*s**3 - 6540712500000*p**3*q**3*r**4*s**3 - 2957828125000*q**5*r**4*s**3 + 5366750000000*p**4*q*r**5*s**3 + 3165000000000*p*q**3*r**5*s**3 - 8862500000000*p**2*q*r**6*s**3 - 1800000000000*q*r**7*s**3 + 236925000*p**13*s**4 + 8895234375*p**10*q**2*s**4 + 106180781250*p**7*q**4*s**4 + 474221875000*p**4*q**6*s**4 + 616210937500*p*q**8*s**4 - 6995868750*p**11*r*s**4 - 184190625000*p**8*q**2*r*s**4 - 1299254453125*p**5*q**4*r*s**4 - 2475458593750*p**2*q**6*r*s**4 + 63049218750*p**9*r**2*s**4 + 1646791484375*p**6*q**2*r**2*s**4 + 9086886718750*p**3*q**4*r**2*s**4 + 4673421875000*q**6*r**2*s**4 - 215665000000*p**7*r**3*s**4 - 7864589843750*p**4*q**2*r**3*s**4 - 5987890625000*p*q**4*r**3*s**4 + 594843750000*p**5*r**4*s**4 + 27791171875000*p**2*q**2*r**4*s**4 - 3881250000000*p**3*r**5*s**4 + 12203125000000*q**2*r**5*s**4 + 10312500000000*p*r**6*s**4 - 34720312500*p**9*q*s**5 - 545126953125*p**6*q**3*s**5 - 2176425781250*p**3*q**5*s**5 - 2792968750000*q**7*s**5 - 1395703125*p**7*q*r*s**5 - 1957568359375*p**4*q**3*r*s**5 + 5122636718750*p*q**5*r*s**5 + 858210937500*p**5*q*r**2*s**5 - 42050097656250*p**2*q**3*r**2*s**5 + 7088281250000*p**3*q*r**3*s**5 - 25974609375000*q**3*r**3*s**5 - 69296875000000*p*q*r**4*s**5 + 384697265625*p**8*s**6 + 6403320312500*p**5*q**2*s**6 + 16742675781250*p**2*q**4*s**6 - 3467080078125*p**6*r*s**6 + 11009765625000*p**3*q**2*r*s**6 + 16451660156250*q**4*r*s**6 + 6979003906250*p**4*r**2*s**6 + 145403320312500*p*q**2*r**2*s**6 + 4076171875000*p**2*r**3*s**6 + 22265625000000*r**4*s**6 - 21915283203125*p**4*q*s**7 - 86608886718750*p*q**3*s**7 - 22785644531250*p**2*q*r*s**7 - 103466796875000*q*r**2*s**7 + 18798828125000*p**3*s**8 + 106048583984375*q**2*s**8 + 17761230468750*p*r*s**8 + + o[3] = 2800*p**9*q**8 + 55700*p**6*q**10 + 363600*p**3*q**12 + 777600*q**14 - 27200*p**10*q**6*r - 700200*p**7*q**8*r - 5726550*p**4*q**10*r - 15066000*p*q**12*r + 74700*p**11*q**4*r**2 + 2859575*p**8*q**6*r**2 + 31175725*p**5*q**8*r**2 + 103147650*p**2*q**10*r**2 - 40500*p**12*q**2*r**3 - 4274400*p**9*q**4*r**3 - 76065825*p**6*q**6*r**3 - 365623750*p**3*q**8*r**3 - 132264000*q**10*r**3 + 2192400*p**10*q**2*r**4 + 92562500*p**7*q**4*r**4 + 799193875*p**4*q**6*r**4 + 1188193125*p*q**8*r**4 - 41231500*p**8*q**2*r**5 - 914210000*p**5*q**4*r**5 - 3318853125*p**2*q**6*r**5 + 398850000*p**6*q**2*r**6 + 3944000000*p**3*q**4*r**6 + 2211312500*q**6*r**6 - 1817000000*p**4*q**2*r**7 - 6720000000*p*q**4*r**7 + 3900000000*p**2*q**2*r**8 + 75600*p**11*q**5*s + 1823100*p**8*q**7*s + 14534150*p**5*q**9*s + 38265750*p**2*q**11*s - 394200*p**12*q**3*r*s - 11453850*p**9*q**5*r*s - 101213000*p**6*q**7*r*s - 223565625*p**3*q**9*r*s + 415125000*q**11*r*s + 243000*p**13*q*r**2*s + 13654575*p**10*q**3*r**2*s + 163811725*p**7*q**5*r**2*s + 173461250*p**4*q**7*r**2*s - 3008671875*p*q**9*r**2*s - 2016900*p**11*q*r**3*s - 86576250*p**8*q**3*r**3*s - 324146625*p**5*q**5*r**3*s + 3378506250*p**2*q**7*r**3*s - 89211000*p**9*q*r**4*s - 55207500*p**6*q**3*r**4*s + 1493950000*p**3*q**5*r**4*s - 12573609375*q**7*r**4*s + 1140100000*p**7*q*r**5*s + 42500000*p**4*q**3*r**5*s + 21511250000*p*q**5*r**5*s - 4058000000*p**5*q*r**6*s + 6725000000*p**2*q**3*r**6*s - 1400000000*p**3*q*r**7*s - 39000000000*q**3*r**7*s + 510300*p**13*q**2*s**2 + 4814775*p**10*q**4*s**2 - 70265125*p**7*q**6*s**2 - 1016484375*p**4*q**8*s**2 - 3221100000*p*q**10*s**2 - 364500*p**14*r*s**2 + 30314250*p**11*q**2*r*s**2 + 1106765625*p**8*q**4*r*s**2 + 10984203125*p**5*q**6*r*s**2 + 33905812500*p**2*q**8*r*s**2 - 37980900*p**12*r**2*s**2 - 2142905625*p**9*q**2*r**2*s**2 - 26896125000*p**6*q**4*r**2*s**2 - 95551328125*p**3*q**6*r**2*s**2 + 11320312500*q**8*r**2*s**2 + 1743781500*p**10*r**3*s**2 + 35432262500*p**7*q**2*r**3*s**2 + 177855859375*p**4*q**4*r**3*s**2 + 121260546875*p*q**6*r**3*s**2 - 25943162500*p**8*r**4*s**2 - 249165500000*p**5*q**2*r**4*s**2 - 461739453125*p**2*q**4*r**4*s**2 + 177823750000*p**6*r**5*s**2 + 726225000000*p**3*q**2*r**5*s**2 + 404195312500*q**4*r**5*s**2 - 565875000000*p**4*r**6*s**2 - 407500000000*p*q**2*r**6*s**2 + 682500000000*p**2*r**7*s**2 - 59140125*p**12*q*s**3 - 1290515625*p**9*q**3*s**3 - 8785071875*p**6*q**5*s**3 - 15588281250*p**3*q**7*s**3 + 17505000000*q**9*s**3 + 896062500*p**10*q*r*s**3 + 2589750000*p**7*q**3*r*s**3 - 82700156250*p**4*q**5*r*s**3 - 347683593750*p*q**7*r*s**3 + 17022656250*p**8*q*r**2*s**3 + 320923593750*p**5*q**3*r**2*s**3 + 1042116875000*p**2*q**5*r**2*s**3 - 353262812500*p**6*q*r**3*s**3 - 2212664062500*p**3*q**3*r**3*s**3 - 1252408984375*q**5*r**3*s**3 + 1967362500000*p**4*q*r**4*s**3 + 1583343750000*p*q**3*r**4*s**3 - 3560625000000*p**2*q*r**5*s**3 - 975000000000*q*r**6*s**3 + 462459375*p**11*s**4 + 14210859375*p**8*q**2*s**4 + 99521718750*p**5*q**4*s**4 + 114955468750*p**2*q**6*s**4 - 17720859375*p**9*r*s**4 - 100320703125*p**6*q**2*r*s**4 + 1021943359375*p**3*q**4*r*s**4 + 1193203125000*q**6*r*s**4 + 171371250000*p**7*r**2*s**4 - 1113390625000*p**4*q**2*r**2*s**4 - 1211474609375*p*q**4*r**2*s**4 - 274056250000*p**5*r**3*s**4 + 8285166015625*p**2*q**2*r**3*s**4 - 2079375000000*p**3*r**4*s**4 + 5137304687500*q**2*r**4*s**4 + 6187500000000*p*r**5*s**4 - 135675000000*p**7*q*s**5 - 1275244140625*p**4*q**3*s**5 - 28388671875*p*q**5*s**5 + 1015166015625*p**5*q*r*s**5 - 10584423828125*p**2*q**3*r*s**5 + 3559570312500*p**3*q*r**2*s**5 - 6929931640625*q**3*r**2*s**5 - 32304687500000*p*q*r**3*s**5 + 430576171875*p**6*s**6 + 9397949218750*p**3*q**2*s**6 + 575195312500*q**4*s**6 - 4086425781250*p**4*r*s**6 + 42183837890625*p*q**2*r*s**6 + 8156494140625*p**2*r**2*s**6 + 12612304687500*r**3*s**6 - 25513916015625*p**2*q*s**7 - 37017822265625*q*r*s**7 + 18981933593750*p*s**8 + + o[2] = 1600*p**10*q**6 + 9200*p**7*q**8 - 126000*p**4*q**10 - 777600*p*q**12 - 14400*p**11*q**4*r - 119300*p**8*q**6*r + 1203225*p**5*q**8*r + 9412200*p**2*q**10*r + 32400*p**12*q**2*r**2 + 417950*p**9*q**4*r**2 - 4543725*p**6*q**6*r**2 - 49008125*p**3*q**8*r**2 - 24192000*q**10*r**2 - 292050*p**10*q**2*r**3 + 8760000*p**7*q**4*r**3 + 137506625*p**4*q**6*r**3 + 225438750*p*q**8*r**3 - 4213250*p**8*q**2*r**4 - 173595625*p**5*q**4*r**4 - 653003125*p**2*q**6*r**4 + 82575000*p**6*q**2*r**5 + 838125000*p**3*q**4*r**5 + 578562500*q**6*r**5 - 421500000*p**4*q**2*r**6 - 1796250000*p*q**4*r**6 + 1050000000*p**2*q**2*r**7 + 43200*p**12*q**3*s + 807300*p**9*q**5*s + 5328225*p**6*q**7*s + 16946250*p**3*q**9*s + 29565000*q**11*s - 194400*p**13*q*r*s - 5505300*p**10*q**3*r*s - 49886700*p**7*q**5*r*s - 178821875*p**4*q**7*r*s - 222750000*p*q**9*r*s + 6814800*p**11*q*r**2*s + 120525625*p**8*q**3*r**2*s + 526694500*p**5*q**5*r**2*s + 84065625*p**2*q**7*r**2*s - 123670500*p**9*q*r**3*s - 1106731875*p**6*q**3*r**3*s - 669556250*p**3*q**5*r**3*s - 2869265625*q**7*r**3*s + 1004350000*p**7*q*r**4*s + 3384375000*p**4*q**3*r**4*s + 5665625000*p*q**5*r**4*s - 3411000000*p**5*q*r**5*s - 418750000*p**2*q**3*r**5*s + 1700000000*p**3*q*r**6*s - 10500000000*q**3*r**6*s + 291600*p**14*s**2 + 9829350*p**11*q**2*s**2 + 114151875*p**8*q**4*s**2 + 522169375*p**5*q**6*s**2 + 716906250*p**2*q**8*s**2 - 18625950*p**12*r*s**2 - 387703125*p**9*q**2*r*s**2 - 2056109375*p**6*q**4*r*s**2 - 760203125*p**3*q**6*r*s**2 + 3071250000*q**8*r*s**2 + 512419500*p**10*r**2*s**2 + 5859053125*p**7*q**2*r**2*s**2 + 12154062500*p**4*q**4*r**2*s**2 + 15931640625*p*q**6*r**2*s**2 - 6598393750*p**8*r**3*s**2 - 43549625000*p**5*q**2*r**3*s**2 - 82011328125*p**2*q**4*r**3*s**2 + 43538125000*p**6*r**4*s**2 + 160831250000*p**3*q**2*r**4*s**2 + 99070312500*q**4*r**4*s**2 - 141812500000*p**4*r**5*s**2 - 117500000000*p*q**2*r**5*s**2 + 183750000000*p**2*r**6*s**2 - 154608750*p**10*q*s**3 - 3309468750*p**7*q**3*s**3 - 20834140625*p**4*q**5*s**3 - 34731562500*p*q**7*s**3 + 5970375000*p**8*q*r*s**3 + 68533281250*p**5*q**3*r*s**3 + 142698281250*p**2*q**5*r*s**3 - 74509140625*p**6*q*r**2*s**3 - 389148437500*p**3*q**3*r**2*s**3 - 270937890625*q**5*r**2*s**3 + 366696875000*p**4*q*r**3*s**3 + 400031250000*p*q**3*r**3*s**3 - 735156250000*p**2*q*r**4*s**3 - 262500000000*q*r**5*s**3 + 371250000*p**9*s**4 + 21315000000*p**6*q**2*s**4 + 179515625000*p**3*q**4*s**4 + 238406250000*q**6*s**4 - 9071015625*p**7*r*s**4 - 268945312500*p**4*q**2*r*s**4 - 379785156250*p*q**4*r*s**4 + 140262890625*p**5*r**2*s**4 + 1486259765625*p**2*q**2*r**2*s**4 - 806484375000*p**3*r**3*s**4 + 1066210937500*q**2*r**3*s**4 + 1722656250000*p*r**4*s**4 - 125648437500*p**5*q*s**5 - 1236279296875*p**2*q**3*s**5 + 1267871093750*p**3*q*r*s**5 - 1044677734375*q**3*r*s**5 - 6630859375000*p*q*r**2*s**5 + 160888671875*p**4*s**6 + 6352294921875*p*q**2*s**6 - 708740234375*p**2*r*s**6 + 3901367187500*r**2*s**6 - 8050537109375*q*s**7 + + o[1] = 2800*p**8*q**6 + 41300*p**5*q**8 + 151200*p**2*q**10 - 25200*p**9*q**4*r - 542600*p**6*q**6*r - 3397875*p**3*q**8*r - 5751000*q**10*r + 56700*p**10*q**2*r**2 + 1972125*p**7*q**4*r**2 + 18624250*p**4*q**6*r**2 + 50253750*p*q**8*r**2 - 1701000*p**8*q**2*r**3 - 32630625*p**5*q**4*r**3 - 139868750*p**2*q**6*r**3 + 18162500*p**6*q**2*r**4 + 177125000*p**3*q**4*r**4 + 121734375*q**6*r**4 - 100500000*p**4*q**2*r**5 - 386250000*p*q**4*r**5 + 225000000*p**2*q**2*r**6 + 75600*p**10*q**3*s + 1708800*p**7*q**5*s + 12836875*p**4*q**7*s + 32062500*p*q**9*s - 340200*p**11*q*r*s - 10185750*p**8*q**3*r*s - 97502750*p**5*q**5*r*s - 301640625*p**2*q**7*r*s + 7168500*p**9*q*r**2*s + 135960625*p**6*q**3*r**2*s + 587471875*p**3*q**5*r**2*s - 384750000*q**7*r**2*s - 29325000*p**7*q*r**3*s - 320625000*p**4*q**3*r**3*s + 523437500*p*q**5*r**3*s - 42000000*p**5*q*r**4*s + 343750000*p**2*q**3*r**4*s + 150000000*p**3*q*r**5*s - 2250000000*q**3*r**5*s + 510300*p**12*s**2 + 12808125*p**9*q**2*s**2 + 107062500*p**6*q**4*s**2 + 270312500*p**3*q**6*s**2 - 168750000*q**8*s**2 - 2551500*p**10*r*s**2 - 5062500*p**7*q**2*r*s**2 + 712343750*p**4*q**4*r*s**2 + 4788281250*p*q**6*r*s**2 - 256837500*p**8*r**2*s**2 - 3574812500*p**5*q**2*r**2*s**2 - 14967968750*p**2*q**4*r**2*s**2 + 4040937500*p**6*r**3*s**2 + 26400000000*p**3*q**2*r**3*s**2 + 17083984375*q**4*r**3*s**2 - 21812500000*p**4*r**4*s**2 - 24375000000*p*q**2*r**4*s**2 + 39375000000*p**2*r**5*s**2 - 127265625*p**5*q**3*s**3 - 680234375*p**2*q**5*s**3 - 2048203125*p**6*q*r*s**3 - 18794531250*p**3*q**3*r*s**3 - 25050000000*q**5*r*s**3 + 26621875000*p**4*q*r**2*s**3 + 37007812500*p*q**3*r**2*s**3 - 105468750000*p**2*q*r**3*s**3 - 56250000000*q*r**4*s**3 + 1124296875*p**7*s**4 + 9251953125*p**4*q**2*s**4 - 8007812500*p*q**4*s**4 - 4004296875*p**5*r*s**4 + 179931640625*p**2*q**2*r*s**4 - 75703125000*p**3*r**2*s**4 + 133447265625*q**2*r**2*s**4 + 363281250000*p*r**3*s**4 - 91552734375*p**3*q*s**5 - 19531250000*q**3*s**5 - 751953125000*p*q*r*s**5 + 157958984375*p**2*s**6 + 748291015625*r*s**6 + + o[0] = -14400*p**6*q**6 - 212400*p**3*q**8 - 777600*q**10 + 92100*p**7*q**4*r + 1689675*p**4*q**6*r + 7371000*p*q**8*r - 122850*p**8*q**2*r**2 - 3735250*p**5*q**4*r**2 - 22432500*p**2*q**6*r**2 + 2298750*p**6*q**2*r**3 + 29390625*p**3*q**4*r**3 + 18000000*q**6*r**3 - 17750000*p**4*q**2*r**4 - 62812500*p*q**4*r**4 + 37500000*p**2*q**2*r**5 - 51300*p**8*q**3*s - 768025*p**5*q**5*s - 2801250*p**2*q**7*s - 275400*p**9*q*r*s - 5479875*p**6*q**3*r*s - 35538750*p**3*q**5*r*s - 68850000*q**7*r*s + 12757500*p**7*q*r**2*s + 133640625*p**4*q**3*r**2*s + 222609375*p*q**5*r**2*s - 108500000*p**5*q*r**3*s - 290312500*p**2*q**3*r**3*s + 275000000*p**3*q*r**4*s - 375000000*q**3*r**4*s + 1931850*p**10*s**2 + 40213125*p**7*q**2*s**2 + 253921875*p**4*q**4*s**2 + 464062500*p*q**6*s**2 - 71077500*p**8*r*s**2 - 818746875*p**5*q**2*r*s**2 - 1882265625*p**2*q**4*r*s**2 + 826031250*p**6*r**2*s**2 + 4369687500*p**3*q**2*r**2*s**2 + 3107812500*q**4*r**2*s**2 - 3943750000*p**4*r**3*s**2 - 5000000000*p*q**2*r**3*s**2 + 6562500000*p**2*r**4*s**2 - 295312500*p**6*q*s**3 - 2938906250*p**3*q**3*s**3 - 4848750000*q**5*s**3 + 3791484375*p**4*q*r*s**3 + 7556250000*p*q**3*r*s**3 - 11960937500*p**2*q*r**2*s**3 - 9375000000*q*r**3*s**3 + 1668515625*p**5*s**4 + 20447265625*p**2*q**2*s**4 - 21955078125*p**3*r*s**4 + 18984375000*q**2*r*s**4 + 67382812500*p*r**2*s**4 - 120849609375*p*q*s**5 + 157226562500*s**6 + + return o + + @property + def a(self): + p, q, r, s = self.p, self.q, self.r, self.s + a = [0]*6 + + a[5] = -100*p**7*q**7 - 2175*p**4*q**9 - 10500*p*q**11 + 1100*p**8*q**5*r + 27975*p**5*q**7*r + 152950*p**2*q**9*r - 4125*p**9*q**3*r**2 - 128875*p**6*q**5*r**2 - 830525*p**3*q**7*r**2 + 59450*q**9*r**2 + 5400*p**10*q*r**3 + 243800*p**7*q**3*r**3 + 2082650*p**4*q**5*r**3 - 333925*p*q**7*r**3 - 139200*p**8*q*r**4 - 2406000*p**5*q**3*r**4 - 122600*p**2*q**5*r**4 + 1254400*p**6*q*r**5 + 3776000*p**3*q**3*r**5 + 1832000*q**5*r**5 - 4736000*p**4*q*r**6 - 6720000*p*q**3*r**6 + 6400000*p**2*q*r**7 - 900*p**9*q**4*s - 37400*p**6*q**6*s - 281625*p**3*q**8*s - 435000*q**10*s + 6750*p**10*q**2*r*s + 322300*p**7*q**4*r*s + 2718575*p**4*q**6*r*s + 4214250*p*q**8*r*s - 16200*p**11*r**2*s - 859275*p**8*q**2*r**2*s - 8925475*p**5*q**4*r**2*s - 14427875*p**2*q**6*r**2*s + 453600*p**9*r**3*s + 10038400*p**6*q**2*r**3*s + 17397500*p**3*q**4*r**3*s - 11333125*q**6*r**3*s - 4451200*p**7*r**4*s - 15850000*p**4*q**2*r**4*s + 34000000*p*q**4*r**4*s + 17984000*p**5*r**5*s - 10000000*p**2*q**2*r**5*s - 25600000*p**3*r**6*s - 8000000*q**2*r**6*s + 6075*p**11*q*s**2 - 83250*p**8*q**3*s**2 - 1282500*p**5*q**5*s**2 - 2862500*p**2*q**7*s**2 + 724275*p**9*q*r*s**2 + 9807250*p**6*q**3*r*s**2 + 28374375*p**3*q**5*r*s**2 + 22212500*q**7*r*s**2 - 8982000*p**7*q*r**2*s**2 - 39600000*p**4*q**3*r**2*s**2 - 61746875*p*q**5*r**2*s**2 - 1010000*p**5*q*r**3*s**2 - 1000000*p**2*q**3*r**3*s**2 + 78000000*p**3*q*r**4*s**2 + 30000000*q**3*r**4*s**2 + 80000000*p*q*r**5*s**2 - 759375*p**10*s**3 - 9787500*p**7*q**2*s**3 - 39062500*p**4*q**4*s**3 - 52343750*p*q**6*s**3 + 12301875*p**8*r*s**3 + 98175000*p**5*q**2*r*s**3 + 225078125*p**2*q**4*r*s**3 - 54900000*p**6*r**2*s**3 - 310000000*p**3*q**2*r**2*s**3 - 7890625*q**4*r**2*s**3 + 51250000*p**4*r**3*s**3 - 420000000*p*q**2*r**3*s**3 + 110000000*p**2*r**4*s**3 - 200000000*r**5*s**3 + 2109375*p**6*q*s**4 - 21093750*p**3*q**3*s**4 - 89843750*q**5*s**4 + 182343750*p**4*q*r*s**4 + 733203125*p*q**3*r*s**4 - 196875000*p**2*q*r**2*s**4 + 1125000000*q*r**3*s**4 - 158203125*p**5*s**5 - 566406250*p**2*q**2*s**5 + 101562500*p**3*r*s**5 - 1669921875*q**2*r*s**5 + 1250000000*p*r**2*s**5 - 1220703125*p*q*s**6 + 6103515625*s**7 + + a[4] = 1000*p**5*q**7 + 7250*p**2*q**9 - 10800*p**6*q**5*r - 96900*p**3*q**7*r - 52500*q**9*r + 37400*p**7*q**3*r**2 + 470850*p**4*q**5*r**2 + 640600*p*q**7*r**2 - 39600*p**8*q*r**3 - 983600*p**5*q**3*r**3 - 2848100*p**2*q**5*r**3 + 814400*p**6*q*r**4 + 6076000*p**3*q**3*r**4 + 2308000*q**5*r**4 - 5024000*p**4*q*r**5 - 9680000*p*q**3*r**5 + 9600000*p**2*q*r**6 + 13800*p**7*q**4*s + 94650*p**4*q**6*s - 26500*p*q**8*s - 86400*p**8*q**2*r*s - 816500*p**5*q**4*r*s - 257500*p**2*q**6*r*s + 91800*p**9*r**2*s + 1853700*p**6*q**2*r**2*s + 630000*p**3*q**4*r**2*s - 8971250*q**6*r**2*s - 2071200*p**7*r**3*s - 7240000*p**4*q**2*r**3*s + 29375000*p*q**4*r**3*s + 14416000*p**5*r**4*s - 5200000*p**2*q**2*r**4*s - 30400000*p**3*r**5*s - 12000000*q**2*r**5*s + 64800*p**9*q*s**2 + 567000*p**6*q**3*s**2 + 1655000*p**3*q**5*s**2 + 6987500*q**7*s**2 + 337500*p**7*q*r*s**2 + 8462500*p**4*q**3*r*s**2 - 5812500*p*q**5*r*s**2 - 24930000*p**5*q*r**2*s**2 - 69125000*p**2*q**3*r**2*s**2 + 103500000*p**3*q*r**3*s**2 + 30000000*q**3*r**3*s**2 + 90000000*p*q*r**4*s**2 - 708750*p**8*s**3 - 5400000*p**5*q**2*s**3 + 8906250*p**2*q**4*s**3 + 18562500*p**6*r*s**3 - 625000*p**3*q**2*r*s**3 + 29687500*q**4*r*s**3 - 75000000*p**4*r**2*s**3 - 416250000*p*q**2*r**2*s**3 + 60000000*p**2*r**3*s**3 - 300000000*r**4*s**3 + 71718750*p**4*q*s**4 + 189062500*p*q**3*s**4 + 210937500*p**2*q*r*s**4 + 1187500000*q*r**2*s**4 - 187500000*p**3*s**5 - 800781250*q**2*s**5 - 390625000*p*r*s**5 + + a[3] = -500*p**6*q**5 - 6350*p**3*q**7 - 19800*q**9 + 3750*p**7*q**3*r + 65100*p**4*q**5*r + 264950*p*q**7*r - 6750*p**8*q*r**2 - 209050*p**5*q**3*r**2 - 1217250*p**2*q**5*r**2 + 219000*p**6*q*r**3 + 2510000*p**3*q**3*r**3 + 1098500*q**5*r**3 - 2068000*p**4*q*r**4 - 5060000*p*q**3*r**4 + 5200000*p**2*q*r**5 - 6750*p**8*q**2*s - 96350*p**5*q**4*s - 346000*p**2*q**6*s + 20250*p**9*r*s + 459900*p**6*q**2*r*s + 1828750*p**3*q**4*r*s - 2930000*q**6*r*s - 594000*p**7*r**2*s - 4301250*p**4*q**2*r**2*s + 10906250*p*q**4*r**2*s + 5252000*p**5*r**3*s - 1450000*p**2*q**2*r**3*s - 12800000*p**3*r**4*s - 6500000*q**2*r**4*s + 74250*p**7*q*s**2 + 1418750*p**4*q**3*s**2 + 5956250*p*q**5*s**2 - 4297500*p**5*q*r*s**2 - 29906250*p**2*q**3*r*s**2 + 31500000*p**3*q*r**2*s**2 + 12500000*q**3*r**2*s**2 + 35000000*p*q*r**3*s**2 + 1350000*p**6*s**3 + 6093750*p**3*q**2*s**3 + 17500000*q**4*s**3 - 7031250*p**4*r*s**3 - 127812500*p*q**2*r*s**3 + 18750000*p**2*r**2*s**3 - 162500000*r**3*s**3 + 107812500*p**2*q*s**4 + 460937500*q*r*s**4 - 214843750*p*s**5 + + a[2] = 1950*p**4*q**5 + 14100*p*q**7 - 14350*p**5*q**3*r - 125600*p**2*q**5*r + 27900*p**6*q*r**2 + 402250*p**3*q**3*r**2 + 288250*q**5*r**2 - 436000*p**4*q*r**3 - 1345000*p*q**3*r**3 + 1400000*p**2*q*r**4 + 9450*p**6*q**2*s - 1250*p**3*q**4*s - 465000*q**6*s - 49950*p**7*r*s - 302500*p**4*q**2*r*s + 1718750*p*q**4*r*s + 834000*p**5*r**2*s + 437500*p**2*q**2*r**2*s - 3100000*p**3*r**3*s - 1750000*q**2*r**3*s - 292500*p**5*q*s**2 - 1937500*p**2*q**3*s**2 + 3343750*p**3*q*r*s**2 + 1875000*q**3*r*s**2 + 8125000*p*q*r**2*s**2 - 1406250*p**4*s**3 - 12343750*p*q**2*s**3 + 5312500*p**2*r*s**3 - 43750000*r**2*s**3 + 74218750*q*s**4 + + a[1] = -300*p**5*q**3 - 2150*p**2*q**5 + 1350*p**6*q*r + 21500*p**3*q**3*r + 61500*q**5*r - 42000*p**4*q*r**2 - 290000*p*q**3*r**2 + 300000*p**2*q*r**3 - 4050*p**7*s - 45000*p**4*q**2*s - 125000*p*q**4*s + 108000*p**5*r*s + 643750*p**2*q**2*r*s - 700000*p**3*r**2*s - 375000*q**2*r**2*s - 93750*p**3*q*s**2 - 312500*q**3*s**2 + 1875000*p*q*r*s**2 - 1406250*p**2*s**3 - 9375000*r*s**3 + + a[0] = 1250*p**3*q**3 + 9000*q**5 - 4500*p**4*q*r - 46250*p*q**3*r + 50000*p**2*q*r**2 + 6750*p**5*s + 43750*p**2*q**2*s - 75000*p**3*r*s - 62500*q**2*r*s + 156250*p*q*s**2 - 1562500*s**3 + + return a + + @property + def c(self): + p, q, r, s = self.p, self.q, self.r, self.s + c = [0]*6 + + c[5] = -40*p**5*q**11 - 270*p**2*q**13 + 700*p**6*q**9*r + 5165*p**3*q**11*r + 540*q**13*r - 4230*p**7*q**7*r**2 - 31845*p**4*q**9*r**2 + 20880*p*q**11*r**2 + 9645*p**8*q**5*r**3 + 57615*p**5*q**7*r**3 - 358255*p**2*q**9*r**3 - 1880*p**9*q**3*r**4 + 114020*p**6*q**5*r**4 + 2012190*p**3*q**7*r**4 - 26855*q**9*r**4 - 14400*p**10*q*r**5 - 470400*p**7*q**3*r**5 - 5088640*p**4*q**5*r**5 + 920*p*q**7*r**5 + 332800*p**8*q*r**6 + 5797120*p**5*q**3*r**6 + 1608000*p**2*q**5*r**6 - 2611200*p**6*q*r**7 - 7424000*p**3*q**3*r**7 - 2323200*q**5*r**7 + 8601600*p**4*q*r**8 + 9472000*p*q**3*r**8 - 10240000*p**2*q*r**9 - 3060*p**7*q**8*s - 39085*p**4*q**10*s - 132300*p*q**12*s + 36580*p**8*q**6*r*s + 520185*p**5*q**8*r*s + 1969860*p**2*q**10*r*s - 144045*p**9*q**4*r**2*s - 2438425*p**6*q**6*r**2*s - 10809475*p**3*q**8*r**2*s + 518850*q**10*r**2*s + 182520*p**10*q**2*r**3*s + 4533930*p**7*q**4*r**3*s + 26196770*p**4*q**6*r**3*s - 4542325*p*q**8*r**3*s + 21600*p**11*r**4*s - 2208080*p**8*q**2*r**4*s - 24787960*p**5*q**4*r**4*s + 10813900*p**2*q**6*r**4*s - 499200*p**9*r**5*s + 3827840*p**6*q**2*r**5*s + 9596000*p**3*q**4*r**5*s + 22662000*q**6*r**5*s + 3916800*p**7*r**6*s - 29952000*p**4*q**2*r**6*s - 90800000*p*q**4*r**6*s - 12902400*p**5*r**7*s + 87040000*p**2*q**2*r**7*s + 15360000*p**3*r**8*s + 12800000*q**2*r**8*s - 38070*p**9*q**5*s**2 - 566700*p**6*q**7*s**2 - 2574375*p**3*q**9*s**2 - 1822500*q**11*s**2 + 292815*p**10*q**3*r*s**2 + 5170280*p**7*q**5*r*s**2 + 27918125*p**4*q**7*r*s**2 + 21997500*p*q**9*r*s**2 - 573480*p**11*q*r**2*s**2 - 14566350*p**8*q**3*r**2*s**2 - 104851575*p**5*q**5*r**2*s**2 - 96448750*p**2*q**7*r**2*s**2 + 11001240*p**9*q*r**3*s**2 + 147798600*p**6*q**3*r**3*s**2 + 158632750*p**3*q**5*r**3*s**2 - 78222500*q**7*r**3*s**2 - 62819200*p**7*q*r**4*s**2 - 136160000*p**4*q**3*r**4*s**2 + 317555000*p*q**5*r**4*s**2 + 160224000*p**5*q*r**5*s**2 - 267600000*p**2*q**3*r**5*s**2 - 153600000*p**3*q*r**6*s**2 - 120000000*q**3*r**6*s**2 - 32000000*p*q*r**7*s**2 - 127575*p**11*q**2*s**3 - 2148750*p**8*q**4*s**3 - 13652500*p**5*q**6*s**3 - 19531250*p**2*q**8*s**3 + 495720*p**12*r*s**3 + 11856375*p**9*q**2*r*s**3 + 107807500*p**6*q**4*r*s**3 + 222334375*p**3*q**6*r*s**3 + 105062500*q**8*r*s**3 - 11566800*p**10*r**2*s**3 - 216787500*p**7*q**2*r**2*s**3 - 633437500*p**4*q**4*r**2*s**3 - 504484375*p*q**6*r**2*s**3 + 90918000*p**8*r**3*s**3 + 567080000*p**5*q**2*r**3*s**3 + 692937500*p**2*q**4*r**3*s**3 - 326640000*p**6*r**4*s**3 - 339000000*p**3*q**2*r**4*s**3 + 369250000*q**4*r**4*s**3 + 560000000*p**4*r**5*s**3 + 508000000*p*q**2*r**5*s**3 - 480000000*p**2*r**6*s**3 + 320000000*r**7*s**3 - 455625*p**10*q*s**4 - 27562500*p**7*q**3*s**4 - 120593750*p**4*q**5*s**4 - 60312500*p*q**7*s**4 + 110615625*p**8*q*r*s**4 + 662984375*p**5*q**3*r*s**4 + 528515625*p**2*q**5*r*s**4 - 541687500*p**6*q*r**2*s**4 - 1262343750*p**3*q**3*r**2*s**4 - 466406250*q**5*r**2*s**4 + 633000000*p**4*q*r**3*s**4 - 1264375000*p*q**3*r**3*s**4 + 1085000000*p**2*q*r**4*s**4 - 2700000000*q*r**5*s**4 - 68343750*p**9*s**5 - 478828125*p**6*q**2*s**5 - 355468750*p**3*q**4*s**5 - 11718750*q**6*s**5 + 718031250*p**7*r*s**5 + 1658593750*p**4*q**2*r*s**5 + 2212890625*p*q**4*r*s**5 - 2855625000*p**5*r**2*s**5 - 4273437500*p**2*q**2*r**2*s**5 + 4537500000*p**3*r**3*s**5 + 8031250000*q**2*r**3*s**5 - 1750000000*p*r**4*s**5 + 1353515625*p**5*q*s**6 + 1562500000*p**2*q**3*s**6 - 3964843750*p**3*q*r*s**6 - 7226562500*q**3*r*s**6 + 1953125000*p*q*r**2*s**6 - 1757812500*p**4*s**7 - 3173828125*p*q**2*s**7 + 6445312500*p**2*r*s**7 - 3906250000*r**2*s**7 + 6103515625*q*s**8 + + c[4] = 40*p**6*q**9 + 110*p**3*q**11 - 1080*q**13 - 560*p**7*q**7*r - 1780*p**4*q**9*r + 17370*p*q**11*r + 2850*p**8*q**5*r**2 + 10520*p**5*q**7*r**2 - 115910*p**2*q**9*r**2 - 6090*p**9*q**3*r**3 - 25330*p**6*q**5*r**3 + 448740*p**3*q**7*r**3 + 128230*q**9*r**3 + 4320*p**10*q*r**4 + 16960*p**7*q**3*r**4 - 1143600*p**4*q**5*r**4 - 1410310*p*q**7*r**4 + 3840*p**8*q*r**5 + 1744480*p**5*q**3*r**5 + 5619520*p**2*q**5*r**5 - 1198080*p**6*q*r**6 - 10579200*p**3*q**3*r**6 - 2940800*q**5*r**6 + 8294400*p**4*q*r**7 + 13568000*p*q**3*r**7 - 15360000*p**2*q*r**8 + 840*p**8*q**6*s + 7580*p**5*q**8*s + 24420*p**2*q**10*s - 8100*p**9*q**4*r*s - 94100*p**6*q**6*r*s - 473000*p**3*q**8*r*s - 473400*q**10*r*s + 22680*p**10*q**2*r**2*s + 374370*p**7*q**4*r**2*s + 2888020*p**4*q**6*r**2*s + 5561050*p*q**8*r**2*s - 12960*p**11*r**3*s - 485820*p**8*q**2*r**3*s - 6723440*p**5*q**4*r**3*s - 23561400*p**2*q**6*r**3*s + 190080*p**9*r**4*s + 5894880*p**6*q**2*r**4*s + 50882000*p**3*q**4*r**4*s + 22411500*q**6*r**4*s - 258560*p**7*r**5*s - 46248000*p**4*q**2*r**5*s - 103800000*p*q**4*r**5*s - 3737600*p**5*r**6*s + 119680000*p**2*q**2*r**6*s + 10240000*p**3*r**7*s + 19200000*q**2*r**7*s + 7290*p**10*q**3*s**2 + 117360*p**7*q**5*s**2 + 691250*p**4*q**7*s**2 - 198750*p*q**9*s**2 - 36450*p**11*q*r*s**2 - 854550*p**8*q**3*r*s**2 - 7340700*p**5*q**5*r*s**2 - 2028750*p**2*q**7*r*s**2 + 995490*p**9*q*r**2*s**2 + 18896600*p**6*q**3*r**2*s**2 + 5026500*p**3*q**5*r**2*s**2 - 52272500*q**7*r**2*s**2 - 16636800*p**7*q*r**3*s**2 - 43200000*p**4*q**3*r**3*s**2 + 223426250*p*q**5*r**3*s**2 + 112068000*p**5*q*r**4*s**2 - 177000000*p**2*q**3*r**4*s**2 - 244000000*p**3*q*r**5*s**2 - 156000000*q**3*r**5*s**2 + 43740*p**12*s**3 + 1032750*p**9*q**2*s**3 + 8602500*p**6*q**4*s**3 + 15606250*p**3*q**6*s**3 + 39625000*q**8*s**3 - 1603800*p**10*r*s**3 - 26932500*p**7*q**2*r*s**3 - 19562500*p**4*q**4*r*s**3 - 152000000*p*q**6*r*s**3 + 25555500*p**8*r**2*s**3 + 16230000*p**5*q**2*r**2*s**3 + 42187500*p**2*q**4*r**2*s**3 - 165660000*p**6*r**3*s**3 + 373500000*p**3*q**2*r**3*s**3 + 332937500*q**4*r**3*s**3 + 465000000*p**4*r**4*s**3 + 586000000*p*q**2*r**4*s**3 - 592000000*p**2*r**5*s**3 + 480000000*r**6*s**3 - 1518750*p**8*q*s**4 - 62531250*p**5*q**3*s**4 + 7656250*p**2*q**5*s**4 + 184781250*p**6*q*r*s**4 - 15781250*p**3*q**3*r*s**4 - 135156250*q**5*r*s**4 - 1148250000*p**4*q*r**2*s**4 - 2121406250*p*q**3*r**2*s**4 + 1990000000*p**2*q*r**3*s**4 - 3150000000*q*r**4*s**4 - 2531250*p**7*s**5 + 660937500*p**4*q**2*s**5 + 1339843750*p*q**4*s**5 - 33750000*p**5*r*s**5 - 679687500*p**2*q**2*r*s**5 + 6250000*p**3*r**2*s**5 + 6195312500*q**2*r**2*s**5 + 1125000000*p*r**3*s**5 - 996093750*p**3*q*s**6 - 3125000000*q**3*s**6 - 3222656250*p*q*r*s**6 + 1171875000*p**2*s**7 + 976562500*r*s**7 + + c[3] = 80*p**4*q**9 + 540*p*q**11 - 600*p**5*q**7*r - 4770*p**2*q**9*r + 1230*p**6*q**5*r**2 + 20900*p**3*q**7*r**2 + 47250*q**9*r**2 - 710*p**7*q**3*r**3 - 84950*p**4*q**5*r**3 - 526310*p*q**7*r**3 + 720*p**8*q*r**4 + 216280*p**5*q**3*r**4 + 2068020*p**2*q**5*r**4 - 198080*p**6*q*r**5 - 3703200*p**3*q**3*r**5 - 1423600*q**5*r**5 + 2860800*p**4*q*r**6 + 7056000*p*q**3*r**6 - 8320000*p**2*q*r**7 - 2720*p**6*q**6*s - 46350*p**3*q**8*s - 178200*q**10*s + 25740*p**7*q**4*r*s + 489490*p**4*q**6*r*s + 2152350*p*q**8*r*s - 61560*p**8*q**2*r**2*s - 1568150*p**5*q**4*r**2*s - 9060500*p**2*q**6*r**2*s + 24840*p**9*r**3*s + 1692380*p**6*q**2*r**3*s + 18098250*p**3*q**4*r**3*s + 9387750*q**6*r**3*s - 382560*p**7*r**4*s - 16818000*p**4*q**2*r**4*s - 49325000*p*q**4*r**4*s + 1212800*p**5*r**5*s + 64840000*p**2*q**2*r**5*s - 320000*p**3*r**6*s + 10400000*q**2*r**6*s - 36450*p**8*q**3*s**2 - 588350*p**5*q**5*s**2 - 2156250*p**2*q**7*s**2 + 123930*p**9*q*r*s**2 + 2879700*p**6*q**3*r*s**2 + 12548000*p**3*q**5*r*s**2 - 14445000*q**7*r*s**2 - 3233250*p**7*q*r**2*s**2 - 28485000*p**4*q**3*r**2*s**2 + 72231250*p*q**5*r**2*s**2 + 32093000*p**5*q*r**3*s**2 - 61275000*p**2*q**3*r**3*s**2 - 107500000*p**3*q*r**4*s**2 - 78500000*q**3*r**4*s**2 + 22000000*p*q*r**5*s**2 - 72900*p**10*s**3 - 1215000*p**7*q**2*s**3 - 2937500*p**4*q**4*s**3 + 9156250*p*q**6*s**3 + 2612250*p**8*r*s**3 + 16560000*p**5*q**2*r*s**3 - 75468750*p**2*q**4*r*s**3 - 32737500*p**6*r**2*s**3 + 169062500*p**3*q**2*r**2*s**3 + 121718750*q**4*r**2*s**3 + 160250000*p**4*r**3*s**3 + 219750000*p*q**2*r**3*s**3 - 317000000*p**2*r**4*s**3 + 260000000*r**5*s**3 + 2531250*p**6*q*s**4 + 22500000*p**3*q**3*s**4 + 39843750*q**5*s**4 - 266343750*p**4*q*r*s**4 - 776406250*p*q**3*r*s**4 + 789062500*p**2*q*r**2*s**4 - 1368750000*q*r**3*s**4 + 67500000*p**5*s**5 + 441406250*p**2*q**2*s**5 - 311718750*p**3*r*s**5 + 1785156250*q**2*r*s**5 + 546875000*p*r**2*s**5 - 1269531250*p*q*s**6 + 488281250*s**7 + + c[2] = 120*p**5*q**7 + 810*p**2*q**9 - 1280*p**6*q**5*r - 9160*p**3*q**7*r + 3780*q**9*r + 4530*p**7*q**3*r**2 + 36640*p**4*q**5*r**2 - 45270*p*q**7*r**2 - 5400*p**8*q*r**3 - 60920*p**5*q**3*r**3 + 200050*p**2*q**5*r**3 + 31200*p**6*q*r**4 - 476000*p**3*q**3*r**4 - 378200*q**5*r**4 + 521600*p**4*q*r**5 + 1872000*p*q**3*r**5 - 2240000*p**2*q*r**6 + 1440*p**7*q**4*s + 15310*p**4*q**6*s + 59400*p*q**8*s - 9180*p**8*q**2*r*s - 115240*p**5*q**4*r*s - 589650*p**2*q**6*r*s + 16200*p**9*r**2*s + 316710*p**6*q**2*r**2*s + 2547750*p**3*q**4*r**2*s + 2178000*q**6*r**2*s - 259200*p**7*r**3*s - 4123000*p**4*q**2*r**3*s - 11700000*p*q**4*r**3*s + 937600*p**5*r**4*s + 16340000*p**2*q**2*r**4*s - 640000*p**3*r**5*s + 2800000*q**2*r**5*s - 2430*p**9*q*s**2 - 54450*p**6*q**3*s**2 - 285500*p**3*q**5*s**2 - 2767500*q**7*s**2 + 43200*p**7*q*r*s**2 - 916250*p**4*q**3*r*s**2 + 14482500*p*q**5*r*s**2 + 4806000*p**5*q*r**2*s**2 - 13212500*p**2*q**3*r**2*s**2 - 25400000*p**3*q*r**3*s**2 - 18750000*q**3*r**3*s**2 + 8000000*p*q*r**4*s**2 + 121500*p**8*s**3 + 2058750*p**5*q**2*s**3 - 6656250*p**2*q**4*s**3 - 6716250*p**6*r*s**3 + 24125000*p**3*q**2*r*s**3 + 23875000*q**4*r*s**3 + 43125000*p**4*r**2*s**3 + 45750000*p*q**2*r**2*s**3 - 87500000*p**2*r**3*s**3 + 70000000*r**4*s**3 - 44437500*p**4*q*s**4 - 107968750*p*q**3*s**4 + 159531250*p**2*q*r*s**4 - 284375000*q*r**2*s**4 + 7031250*p**3*s**5 + 265625000*q**2*s**5 + 31250000*p*r*s**5 + + c[1] = 160*p**3*q**7 + 1080*q**9 - 1080*p**4*q**5*r - 8730*p*q**7*r + 1510*p**5*q**3*r**2 + 20420*p**2*q**5*r**2 + 720*p**6*q*r**3 - 23200*p**3*q**3*r**3 - 79900*q**5*r**3 + 35200*p**4*q*r**4 + 404000*p*q**3*r**4 - 480000*p**2*q*r**5 + 960*p**5*q**4*s + 2850*p**2*q**6*s + 540*p**6*q**2*r*s + 63500*p**3*q**4*r*s + 319500*q**6*r*s - 7560*p**7*r**2*s - 253500*p**4*q**2*r**2*s - 1806250*p*q**4*r**2*s + 91200*p**5*r**3*s + 2600000*p**2*q**2*r**3*s - 80000*p**3*r**4*s + 600000*q**2*r**4*s - 4050*p**7*q*s**2 - 120000*p**4*q**3*s**2 - 273750*p*q**5*s**2 + 425250*p**5*q*r*s**2 + 2325000*p**2*q**3*r*s**2 - 5400000*p**3*q*r**2*s**2 - 2875000*q**3*r**2*s**2 + 1500000*p*q*r**3*s**2 - 303750*p**6*s**3 - 843750*p**3*q**2*s**3 - 812500*q**4*s**3 + 5062500*p**4*r*s**3 + 13312500*p*q**2*r*s**3 - 14500000*p**2*r**2*s**3 + 15000000*r**3*s**3 - 3750000*p**2*q*s**4 - 35937500*q*r*s**4 + 11718750*p*s**5 + + c[0] = 80*p**4*q**5 + 540*p*q**7 - 600*p**5*q**3*r - 4770*p**2*q**5*r + 1080*p**6*q*r**2 + 11200*p**3*q**3*r**2 - 12150*q**5*r**2 - 4800*p**4*q*r**3 + 64000*p*q**3*r**3 - 80000*p**2*q*r**4 + 1080*p**6*q**2*s + 13250*p**3*q**4*s + 54000*q**6*s - 3240*p**7*r*s - 56250*p**4*q**2*r*s - 337500*p*q**4*r*s + 43200*p**5*r**2*s + 560000*p**2*q**2*r**2*s - 80000*p**3*r**3*s + 100000*q**2*r**3*s + 6750*p**5*q*s**2 + 225000*p**2*q**3*s**2 - 900000*p**3*q*r*s**2 - 562500*q**3*r*s**2 + 500000*p*q*r**2*s**2 + 843750*p**4*s**3 + 1937500*p*q**2*s**3 - 3000000*p**2*r*s**3 + 2500000*r**2*s**3 - 5468750*q*s**4 + + return c + + @property + def F(self): + p, q, r, s = self.p, self.q, self.r, self.s + F = 4*p**6*q**6 + 59*p**3*q**8 + 216*q**10 - 36*p**7*q**4*r - 623*p**4*q**6*r - 2610*p*q**8*r + 81*p**8*q**2*r**2 + 2015*p**5*q**4*r**2 + 10825*p**2*q**6*r**2 - 1800*p**6*q**2*r**3 - 17500*p**3*q**4*r**3 + 625*q**6*r**3 + 10000*p**4*q**2*r**4 + 108*p**8*q**3*s + 1584*p**5*q**5*s + 5700*p**2*q**7*s - 486*p**9*q*r*s - 9720*p**6*q**3*r*s - 45050*p**3*q**5*r*s - 9000*q**7*r*s + 10800*p**7*q*r**2*s + 92500*p**4*q**3*r**2*s + 32500*p*q**5*r**2*s - 60000*p**5*q*r**3*s - 50000*p**2*q**3*r**3*s + 729*p**10*s**2 + 12150*p**7*q**2*s**2 + 60000*p**4*q**4*s**2 + 93750*p*q**6*s**2 - 18225*p**8*r*s**2 - 175500*p**5*q**2*r*s**2 - 478125*p**2*q**4*r*s**2 + 135000*p**6*r**2*s**2 + 850000*p**3*q**2*r**2*s**2 + 15625*q**4*r**2*s**2 - 250000*p**4*r**3*s**2 + 225000*p**3*q**3*s**3 + 175000*q**5*s**3 - 1012500*p**4*q*r*s**3 - 1187500*p*q**3*r*s**3 + 1250000*p**2*q*r**2*s**3 + 928125*p**5*s**4 + 1875000*p**2*q**2*s**4 - 2812500*p**3*r*s**4 - 390625*q**2*r*s**4 - 9765625*s**6 + return F + + def l0(self, theta): + F = self.F + a = self.a + l0 = Poly(a, x).eval(theta)/F + return l0 + + def T(self, theta, d): + F = self.F + T = [0]*5 + b = self.b + # Note that the order of sublists of the b's has been reversed compared to the paper + T[1] = -Poly(b[1], x).eval(theta)/(2*F) + T[2] = Poly(b[2], x).eval(theta)/(2*d*F) + T[3] = Poly(b[3], x).eval(theta)/(2*F) + T[4] = Poly(b[4], x).eval(theta)/(2*d*F) + return T + + def order(self, theta, d): + F = self.F + o = self.o + order = Poly(o, x).eval(theta)/(d*F) + return N(order) + + def uv(self, theta, d): + c = self.c + u = self.q*Rational(-25, 2) + v = Poly(c, x).eval(theta)/(2*d*self.F) + return N(u), N(v) + + @property + def zeta(self): + return [self.zeta1, self.zeta2, self.zeta3, self.zeta4] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyroots.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyroots.py new file mode 100644 index 0000000000000000000000000000000000000000..4def1312eb5b94a13e511d2d4f9b15f1d51fd63f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyroots.py @@ -0,0 +1,1227 @@ +"""Algorithms for computing symbolic roots of polynomials. """ + + +import math +from functools import reduce + +from sympy.core import S, I, pi +from sympy.core.exprtools import factor_terms +from sympy.core.function import _mexpand +from sympy.core.logic import fuzzy_not +from sympy.core.mul import expand_2arg, Mul +from sympy.core.intfunc import igcd +from sympy.core.numbers import Rational, comp +from sympy.core.power import Pow +from sympy.core.relational import Eq +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, Symbol, symbols +from sympy.core.sympify import sympify +from sympy.functions import exp, im, cos, acos, Piecewise +from sympy.functions.elementary.miscellaneous import root, sqrt +from sympy.ntheory import divisors, isprime, nextprime +from sympy.polys.domains import EX +from sympy.polys.polyerrors import (PolynomialError, GeneratorsNeeded, + DomainError, UnsolvableFactorError) +from sympy.polys.polyquinticconst import PolyQuintic +from sympy.polys.polytools import Poly, cancel, factor, gcd_list, discriminant +from sympy.polys.rationaltools import together +from sympy.polys.specialpolys import cyclotomic_poly +from sympy.utilities import public +from sympy.utilities.misc import filldedent + + + +z = Symbol('z') # importing from abc cause O to be lost as clashing symbol + + +def roots_linear(f): + """Returns a list of roots of a linear polynomial.""" + r = -f.nth(0)/f.nth(1) + dom = f.get_domain() + + if not dom.is_Numerical: + if dom.is_Composite: + r = factor(r) + else: + from sympy.simplify.simplify import simplify + r = simplify(r) + + return [r] + + +def roots_quadratic(f): + """Returns a list of roots of a quadratic polynomial. If the domain is ZZ + then the roots will be sorted with negatives coming before positives. + The ordering will be the same for any numerical coefficients as long as + the assumptions tested are correct, otherwise the ordering will not be + sorted (but will be canonical). + """ + + a, b, c = f.all_coeffs() + dom = f.get_domain() + + def _sqrt(d): + # remove squares from square root since both will be represented + # in the results; a similar thing is happening in roots() but + # must be duplicated here because not all quadratics are binomials + co = [] + other = [] + for di in Mul.make_args(d): + if di.is_Pow and di.exp.is_Integer and di.exp % 2 == 0: + co.append(Pow(di.base, di.exp//2)) + else: + other.append(di) + if co: + d = Mul(*other) + co = Mul(*co) + return co*sqrt(d) + return sqrt(d) + + def _simplify(expr): + if dom.is_Composite: + return factor(expr) + else: + from sympy.simplify.simplify import simplify + return simplify(expr) + + if c is S.Zero: + r0, r1 = S.Zero, -b/a + + if not dom.is_Numerical: + r1 = _simplify(r1) + elif r1.is_negative: + r0, r1 = r1, r0 + elif b is S.Zero: + r = -c/a + if not dom.is_Numerical: + r = _simplify(r) + + R = _sqrt(r) + r0 = -R + r1 = R + else: + d = b**2 - 4*a*c + A = 2*a + B = -b/A + + if not dom.is_Numerical: + d = _simplify(d) + B = _simplify(B) + + D = factor_terms(_sqrt(d)/A) + r0 = B - D + r1 = B + D + if a.is_negative: + r0, r1 = r1, r0 + elif not dom.is_Numerical: + r0, r1 = [expand_2arg(i) for i in (r0, r1)] + + return [r0, r1] + + +def roots_cubic(f, trig=False): + """Returns a list of roots of a cubic polynomial. + + References + ========== + [1] https://en.wikipedia.org/wiki/Cubic_function, General formula for roots, + (accessed November 17, 2014). + """ + if trig: + a, b, c, d = f.all_coeffs() + p = (3*a*c - b**2)/(3*a**2) + q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3) + D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2 + if (D > 0) == True: + rv = [] + for k in range(3): + rv.append(2*sqrt(-p/3)*cos(acos(q/p*sqrt(-3/p)*Rational(3, 2))/3 - k*pi*Rational(2, 3))) + return [i - b/3/a for i in rv] + + # a*x**3 + b*x**2 + c*x + d -> x**3 + a*x**2 + b*x + c + _, a, b, c = f.monic().all_coeffs() + + if c is S.Zero: + x1, x2 = roots([1, a, b], multiple=True) + return [x1, S.Zero, x2] + + # x**3 + a*x**2 + b*x + c -> u**3 + p*u + q + p = b - a**2/3 + q = c - a*b/3 + 2*a**3/27 + + pon3 = p/3 + aon3 = a/3 + + u1 = None + if p is S.Zero: + if q is S.Zero: + return [-aon3]*3 + u1 = -root(q, 3) if q.is_positive else root(-q, 3) + elif q is S.Zero: + y1, y2 = roots([1, 0, p], multiple=True) + return [tmp - aon3 for tmp in [y1, S.Zero, y2]] + elif q.is_real and q.is_negative: + u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3) + + coeff = I*sqrt(3)/2 + if u1 is None: + u1 = S.One + u2 = Rational(-1, 2) + coeff + u3 = Rational(-1, 2) - coeff + b, c, d = a, b, c # a, b, c, d = S.One, a, b, c + D0 = b**2 - 3*c # b**2 - 3*a*c + D1 = 2*b**3 - 9*b*c + 27*d # 2*b**3 - 9*a*b*c + 27*a**2*d + C = root((D1 + sqrt(D1**2 - 4*D0**3))/2, 3) + return [-(b + uk*C + D0/C/uk)/3 for uk in [u1, u2, u3]] # -(b + uk*C + D0/C/uk)/3/a + + u2 = u1*(Rational(-1, 2) + coeff) + u3 = u1*(Rational(-1, 2) - coeff) + + if p is S.Zero: + return [u1 - aon3, u2 - aon3, u3 - aon3] + + soln = [ + -u1 + pon3/u1 - aon3, + -u2 + pon3/u2 - aon3, + -u3 + pon3/u3 - aon3 + ] + + return soln + +def _roots_quartic_euler(p, q, r, a): + """ + Descartes-Euler solution of the quartic equation + + Parameters + ========== + + p, q, r: coefficients of ``x**4 + p*x**2 + q*x + r`` + a: shift of the roots + + Notes + ===== + + This is a helper function for ``roots_quartic``. + + Look for solutions of the form :: + + ``x1 = sqrt(R) - sqrt(A + B*sqrt(R))`` + ``x2 = -sqrt(R) - sqrt(A - B*sqrt(R))`` + ``x3 = -sqrt(R) + sqrt(A - B*sqrt(R))`` + ``x4 = sqrt(R) + sqrt(A + B*sqrt(R))`` + + To satisfy the quartic equation one must have + ``p = -2*(R + A); q = -4*B*R; r = (R - A)**2 - B**2*R`` + so that ``R`` must satisfy the Descartes-Euler resolvent equation + ``64*R**3 + 32*p*R**2 + (4*p**2 - 16*r)*R - q**2 = 0`` + + If the resolvent does not have a rational solution, return None; + in that case it is likely that the Ferrari method gives a simpler + solution. + + Examples + ======== + + >>> from sympy import S + >>> from sympy.polys.polyroots import _roots_quartic_euler + >>> p, q, r = -S(64)/5, -S(512)/125, -S(1024)/3125 + >>> _roots_quartic_euler(p, q, r, S(0))[0] + -sqrt(32*sqrt(5)/125 + 16/5) + 4*sqrt(5)/5 + """ + # solve the resolvent equation + x = Dummy('x') + eq = 64*x**3 + 32*p*x**2 + (4*p**2 - 16*r)*x - q**2 + xsols = list(roots(Poly(eq, x), cubics=False).keys()) + xsols = [sol for sol in xsols if sol.is_rational and sol.is_nonzero] + if not xsols: + return None + R = max(xsols) + c1 = sqrt(R) + B = -q*c1/(4*R) + A = -R - p/2 + c2 = sqrt(A + B) + c3 = sqrt(A - B) + return [c1 - c2 - a, -c1 - c3 - a, -c1 + c3 - a, c1 + c2 - a] + + +def roots_quartic(f): + r""" + Returns a list of roots of a quartic polynomial. + + There are many references for solving quartic expressions available [1-5]. + This reviewer has found that many of them require one to select from among + 2 or more possible sets of solutions and that some solutions work when one + is searching for real roots but do not work when searching for complex roots + (though this is not always stated clearly). The following routine has been + tested and found to be correct for 0, 2 or 4 complex roots. + + The quasisymmetric case solution [6] looks for quartics that have the form + `x**4 + A*x**3 + B*x**2 + C*x + D = 0` where `(C/A)**2 = D`. + + Although no general solution that is always applicable for all + coefficients is known to this reviewer, certain conditions are tested + to determine the simplest 4 expressions that can be returned: + + 1) `f = c + a*(a**2/8 - b/2) == 0` + 2) `g = d - a*(a*(3*a**2/256 - b/16) + c/4) = 0` + 3) if `f != 0` and `g != 0` and `p = -d + a*c/4 - b**2/12` then + a) `p == 0` + b) `p != 0` + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.polys.polyroots import roots_quartic + + >>> r = roots_quartic(Poly('x**4-6*x**3+17*x**2-26*x+20')) + + >>> # 4 complex roots: 1+-I*sqrt(3), 2+-I + >>> sorted(str(tmp.evalf(n=2)) for tmp in r) + ['1.0 + 1.7*I', '1.0 - 1.7*I', '2.0 + 1.0*I', '2.0 - 1.0*I'] + + References + ========== + + 1. http://mathforum.org/dr.math/faq/faq.cubic.equations.html + 2. https://en.wikipedia.org/wiki/Quartic_function#Summary_of_Ferrari.27s_method + 3. https://planetmath.org/encyclopedia/GaloisTheoreticDerivationOfTheQuarticFormula.html + 4. https://people.bath.ac.uk/masjhd/JHD-CA.pdf + 5. http://www.albmath.org/files/Math_5713.pdf + 6. https://web.archive.org/web/20171002081448/http://www.statemaster.com/encyclopedia/Quartic-equation + 7. https://eqworld.ipmnet.ru/en/solutions/ae/ae0108.pdf + """ + _, a, b, c, d = f.monic().all_coeffs() + + if not d: + return [S.Zero] + roots([1, a, b, c], multiple=True) + elif (c/a)**2 == d: + x, m = f.gen, c/a + + g = Poly(x**2 + a*x + b - 2*m, x) + + z1, z2 = roots_quadratic(g) + + h1 = Poly(x**2 - z1*x + m, x) + h2 = Poly(x**2 - z2*x + m, x) + + r1 = roots_quadratic(h1) + r2 = roots_quadratic(h2) + + return r1 + r2 + else: + a2 = a**2 + e = b - 3*a2/8 + f = _mexpand(c + a*(a2/8 - b/2)) + aon4 = a/4 + g = _mexpand(d - aon4*(a*(3*a2/64 - b/4) + c)) + + if f.is_zero: + y1, y2 = [sqrt(tmp) for tmp in + roots([1, e, g], multiple=True)] + return [tmp - aon4 for tmp in [-y1, -y2, y1, y2]] + if g.is_zero: + y = [S.Zero] + roots([1, 0, e, f], multiple=True) + return [tmp - aon4 for tmp in y] + else: + # Descartes-Euler method, see [7] + sols = _roots_quartic_euler(e, f, g, aon4) + if sols: + return sols + # Ferrari method, see [1, 2] + p = -e**2/12 - g + q = -e**3/108 + e*g/3 - f**2/8 + TH = Rational(1, 3) + + def _ans(y): + w = sqrt(e + 2*y) + arg1 = 3*e + 2*y + arg2 = 2*f/w + ans = [] + for s in [-1, 1]: + root = sqrt(-(arg1 + s*arg2)) + for t in [-1, 1]: + ans.append((s*w - t*root)/2 - aon4) + return ans + + # whether a Piecewise is returned or not + # depends on knowing p, so try to put + # in a simple form + p = _mexpand(p) + + + # p == 0 case + y1 = e*Rational(-5, 6) - q**TH + if p.is_zero: + return _ans(y1) + + # if p != 0 then u below is not 0 + root = sqrt(q**2/4 + p**3/27) + r = -q/2 + root # or -q/2 - root + u = r**TH # primary root of solve(x**3 - r, x) + y2 = e*Rational(-5, 6) + u - p/u/3 + if fuzzy_not(p.is_zero): + return _ans(y2) + + # sort it out once they know the values of the coefficients + return [Piecewise((a1, Eq(p, 0)), (a2, True)) + for a1, a2 in zip(_ans(y1), _ans(y2))] + + +def roots_binomial(f): + """Returns a list of roots of a binomial polynomial. If the domain is ZZ + then the roots will be sorted with negatives coming before positives. + The ordering will be the same for any numerical coefficients as long as + the assumptions tested are correct, otherwise the ordering will not be + sorted (but will be canonical). + """ + n = f.degree() + + a, b = f.nth(n), f.nth(0) + base = -cancel(b/a) + alpha = root(base, n) + + if alpha.is_number: + alpha = alpha.expand(complex=True) + + # define some parameters that will allow us to order the roots. + # If the domain is ZZ this is guaranteed to return roots sorted + # with reals before non-real roots and non-real sorted according + # to real part and imaginary part, e.g. -1, 1, -1 + I, 2 - I + neg = base.is_negative + even = n % 2 == 0 + if neg: + if even == True and (base + 1).is_positive: + big = True + else: + big = False + + # get the indices in the right order so the computed + # roots will be sorted when the domain is ZZ + ks = [] + imax = n//2 + if even: + ks.append(imax) + imax -= 1 + if not neg: + ks.append(0) + for i in range(imax, 0, -1): + if neg: + ks.extend([i, -i]) + else: + ks.extend([-i, i]) + if neg: + ks.append(0) + if big: + for i in range(0, len(ks), 2): + pair = ks[i: i + 2] + pair = list(reversed(pair)) + + # compute the roots + roots, d = [], 2*I*pi/n + for k in ks: + zeta = exp(k*d).expand(complex=True) + roots.append((alpha*zeta).expand(power_base=False)) + + return roots + + +def _inv_totient_estimate(m): + """ + Find ``(L, U)`` such that ``L <= phi^-1(m) <= U``. + + Examples + ======== + + >>> from sympy.polys.polyroots import _inv_totient_estimate + + >>> _inv_totient_estimate(192) + (192, 840) + >>> _inv_totient_estimate(400) + (400, 1750) + + """ + primes = [ d + 1 for d in divisors(m) if isprime(d + 1) ] + + a, b = 1, 1 + + for p in primes: + a *= p + b *= p - 1 + + L = m + U = int(math.ceil(m*(float(a)/b))) + + P = p = 2 + primes = [] + + while P <= U: + p = nextprime(p) + primes.append(p) + P *= p + + P //= p + b = 1 + + for p in primes[:-1]: + b *= p - 1 + + U = int(math.ceil(m*(float(P)/b))) + + return L, U + + +def roots_cyclotomic(f, factor=False): + """Compute roots of cyclotomic polynomials. """ + L, U = _inv_totient_estimate(f.degree()) + + for n in range(L, U + 1): + g = cyclotomic_poly(n, f.gen, polys=True) + + if f.expr == g.expr: + break + else: # pragma: no cover + raise RuntimeError("failed to find index of a cyclotomic polynomial") + + roots = [] + + if not factor: + # get the indices in the right order so the computed + # roots will be sorted + h = n//2 + ks = [i for i in range(1, n + 1) if igcd(i, n) == 1] + ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1)) + d = 2*I*pi/n + for k in reversed(ks): + roots.append(exp(k*d).expand(complex=True)) + else: + g = Poly(f, extension=root(-1, n)) + + for h, _ in ordered(g.factor_list()[1]): + roots.append(-h.TC()) + + return roots + + +def roots_quintic(f): + """ + Calculate exact roots of a solvable irreducible quintic with rational coefficients. + Return an empty list if the quintic is reducible or not solvable. + """ + result = [] + + coeff_5, coeff_4, p_, q_, r_, s_ = f.all_coeffs() + + if not all(coeff.is_Rational for coeff in (coeff_5, coeff_4, p_, q_, r_, s_)): + return result + + if coeff_5 != 1: + f = Poly(f / coeff_5) + _, coeff_4, p_, q_, r_, s_ = f.all_coeffs() + + # Cancel coeff_4 to form x^5 + px^3 + qx^2 + rx + s + if coeff_4: + p = p_ - 2*coeff_4*coeff_4/5 + q = q_ - 3*coeff_4*p_/5 + 4*coeff_4**3/25 + r = r_ - 2*coeff_4*q_/5 + 3*coeff_4**2*p_/25 - 3*coeff_4**4/125 + s = s_ - coeff_4*r_/5 + coeff_4**2*q_/25 - coeff_4**3*p_/125 + 4*coeff_4**5/3125 + x = f.gen + f = Poly(x**5 + p*x**3 + q*x**2 + r*x + s) + else: + p, q, r, s = p_, q_, r_, s_ + + quintic = PolyQuintic(f) + + # Eqn standardized. Algo for solving starts here + if not f.is_irreducible: + return result + f20 = quintic.f20 + # Check if f20 has linear factors over domain Z + if f20.is_irreducible: + return result + # Now, we know that f is solvable + for _factor in f20.factor_list()[1]: + if _factor[0].is_linear: + theta = _factor[0].root(0) + break + d = discriminant(f) + delta = sqrt(d) + # zeta = a fifth root of unity + zeta1, zeta2, zeta3, zeta4 = quintic.zeta + T = quintic.T(theta, d) + tol = S(1e-10) + alpha = T[1] + T[2]*delta + alpha_bar = T[1] - T[2]*delta + beta = T[3] + T[4]*delta + beta_bar = T[3] - T[4]*delta + + disc = alpha**2 - 4*beta + disc_bar = alpha_bar**2 - 4*beta_bar + + l0 = quintic.l0(theta) + Stwo = S(2) + l1 = _quintic_simplify((-alpha + sqrt(disc)) / Stwo) + l4 = _quintic_simplify((-alpha - sqrt(disc)) / Stwo) + + l2 = _quintic_simplify((-alpha_bar + sqrt(disc_bar)) / Stwo) + l3 = _quintic_simplify((-alpha_bar - sqrt(disc_bar)) / Stwo) + + order = quintic.order(theta, d) + test = (order*delta.n()) - ( (l1.n() - l4.n())*(l2.n() - l3.n()) ) + # Comparing floats + if not comp(test, 0, tol): + l2, l3 = l3, l2 + + # Now we have correct order of l's + R1 = l0 + l1*zeta1 + l2*zeta2 + l3*zeta3 + l4*zeta4 + R2 = l0 + l3*zeta1 + l1*zeta2 + l4*zeta3 + l2*zeta4 + R3 = l0 + l2*zeta1 + l4*zeta2 + l1*zeta3 + l3*zeta4 + R4 = l0 + l4*zeta1 + l3*zeta2 + l2*zeta3 + l1*zeta4 + + Res = [None, [None]*5, [None]*5, [None]*5, [None]*5] + Res_n = [None, [None]*5, [None]*5, [None]*5, [None]*5] + + # Simplifying improves performance a lot for exact expressions + R1 = _quintic_simplify(R1) + R2 = _quintic_simplify(R2) + R3 = _quintic_simplify(R3) + R4 = _quintic_simplify(R4) + + # hard-coded results for [factor(i) for i in _vsolve(x**5 - a - I*b, x)] + x0 = z**(S(1)/5) + x1 = sqrt(2) + x2 = sqrt(5) + x3 = sqrt(5 - x2) + x4 = I*x2 + x5 = x4 + I + x6 = I*x0/4 + x7 = x1*sqrt(x2 + 5) + sol = [x0, -x6*(x1*x3 - x5), x6*(x1*x3 + x5), -x6*(x4 + x7 - I), x6*(-x4 + x7 + I)] + + R1 = R1.as_real_imag() + R2 = R2.as_real_imag() + R3 = R3.as_real_imag() + R4 = R4.as_real_imag() + + for i, s in enumerate(sol): + Res[1][i] = _quintic_simplify(s.xreplace({z: R1[0] + I*R1[1]})) + Res[2][i] = _quintic_simplify(s.xreplace({z: R2[0] + I*R2[1]})) + Res[3][i] = _quintic_simplify(s.xreplace({z: R3[0] + I*R3[1]})) + Res[4][i] = _quintic_simplify(s.xreplace({z: R4[0] + I*R4[1]})) + + for i in range(1, 5): + for j in range(5): + Res_n[i][j] = Res[i][j].n() + Res[i][j] = _quintic_simplify(Res[i][j]) + r1 = Res[1][0] + r1_n = Res_n[1][0] + + for i in range(5): + if comp(im(r1_n*Res_n[4][i]), 0, tol): + r4 = Res[4][i] + break + + # Now we have various Res values. Each will be a list of five + # values. We have to pick one r value from those five for each Res + u, v = quintic.uv(theta, d) + testplus = (u + v*delta*sqrt(5)).n() + testminus = (u - v*delta*sqrt(5)).n() + + # Evaluated numbers suffixed with _n + # We will use evaluated numbers for calculation. Much faster. + r4_n = r4.n() + r2 = r3 = None + + for i in range(5): + r2temp_n = Res_n[2][i] + for j in range(5): + # Again storing away the exact number and using + # evaluated numbers in computations + r3temp_n = Res_n[3][j] + if (comp((r1_n*r2temp_n**2 + r4_n*r3temp_n**2 - testplus).n(), 0, tol) and + comp((r3temp_n*r1_n**2 + r2temp_n*r4_n**2 - testminus).n(), 0, tol)): + r2 = Res[2][i] + r3 = Res[3][j] + break + if r2 is not None: + break + else: + return [] # fall back to normal solve + + # Now, we have r's so we can get roots + x1 = (r1 + r2 + r3 + r4)/5 + x2 = (r1*zeta4 + r2*zeta3 + r3*zeta2 + r4*zeta1)/5 + x3 = (r1*zeta3 + r2*zeta1 + r3*zeta4 + r4*zeta2)/5 + x4 = (r1*zeta2 + r2*zeta4 + r3*zeta1 + r4*zeta3)/5 + x5 = (r1*zeta1 + r2*zeta2 + r3*zeta3 + r4*zeta4)/5 + result = [x1, x2, x3, x4, x5] + + # Now check if solutions are distinct + + saw = set() + for r in result: + r = r.n(2) + if r in saw: + # Roots were identical. Abort, return [] + # and fall back to usual solve + return [] + saw.add(r) + + # Restore to original equation where coeff_4 is nonzero + if coeff_4: + result = [x - coeff_4 / 5 for x in result] + return result + + +def _quintic_simplify(expr): + from sympy.simplify.simplify import powsimp + expr = powsimp(expr) + expr = cancel(expr) + return together(expr) + + +def _integer_basis(poly): + """Compute coefficient basis for a polynomial over integers. + + Returns the integer ``div`` such that substituting ``x = div*y`` + ``p(x) = m*q(y)`` where the coefficients of ``q`` are smaller + than those of ``p``. + + For example ``x**5 + 512*x + 1024 = 0`` + with ``div = 4`` becomes ``y**5 + 2*y + 1 = 0`` + + Returns the integer ``div`` or ``None`` if there is no possible scaling. + + Examples + ======== + + >>> from sympy.polys import Poly + >>> from sympy.abc import x + >>> from sympy.polys.polyroots import _integer_basis + >>> p = Poly(x**5 + 512*x + 1024, x, domain='ZZ') + >>> _integer_basis(p) + 4 + """ + monoms, coeffs = list(zip(*poly.terms())) + + monoms, = list(zip(*monoms)) + coeffs = list(map(abs, coeffs)) + + if coeffs[0] < coeffs[-1]: + coeffs = list(reversed(coeffs)) + n = monoms[0] + monoms = [n - i for i in reversed(monoms)] + else: + return None + + monoms = monoms[:-1] + coeffs = coeffs[:-1] + + # Special case for two-term polynominals + if len(monoms) == 1: + r = Pow(coeffs[0], S.One/monoms[0]) + if r.is_Integer: + return int(r) + else: + return None + + divs = reversed(divisors(gcd_list(coeffs))[1:]) + + try: + div = next(divs) + except StopIteration: + return None + + while True: + for monom, coeff in zip(monoms, coeffs): + if coeff % div**monom != 0: + try: + div = next(divs) + except StopIteration: + return None + else: + break + else: + return div + + +def preprocess_roots(poly): + """Try to get rid of symbolic coefficients from ``poly``. """ + coeff = S.One + + poly_func = poly.func + try: + _, poly = poly.clear_denoms(convert=True) + except DomainError: + return coeff, poly + + poly = poly.primitive()[1] + poly = poly.retract() + + # TODO: This is fragile. Figure out how to make this independent of construct_domain(). + if poly.get_domain().is_Poly and all(c.is_term for c in poly.rep.coeffs()): + poly = poly.inject() + + strips = list(zip(*poly.monoms())) + gens = list(poly.gens[1:]) + + base, strips = strips[0], strips[1:] + + for gen, strip in zip(list(gens), strips): + reverse = False + + if strip[0] < strip[-1]: + strip = reversed(strip) + reverse = True + + ratio = None + + for a, b in zip(base, strip): + if not a and not b: + continue + elif not a or not b: + break + elif b % a != 0: + break + else: + _ratio = b // a + + if ratio is None: + ratio = _ratio + elif ratio != _ratio: + break + else: + if reverse: + ratio = -ratio + + poly = poly.eval(gen, 1) + coeff *= gen**(-ratio) + gens.remove(gen) + + if gens: + poly = poly.eject(*gens) + + if poly.is_univariate and poly.get_domain().is_ZZ: + basis = _integer_basis(poly) + + if basis is not None: + n = poly.degree() + + def func(k, coeff): + return coeff//basis**(n - k[0]) + + poly = poly.termwise(func) + coeff *= basis + + if not isinstance(poly, poly_func): + poly = poly_func(poly) + return coeff, poly + + +@public +def roots(f, *gens, + auto=True, + cubics=True, + trig=False, + quartics=True, + quintics=False, + multiple=False, + filter=None, + predicate=None, + strict=False, + **flags): + """ + Computes symbolic roots of a univariate polynomial. + + Given a univariate polynomial f with symbolic coefficients (or + a list of the polynomial's coefficients), returns a dictionary + with its roots and their multiplicities. + + Only roots expressible via radicals will be returned. To get + a complete set of roots use RootOf class or numerical methods + instead. By default cubic and quartic formulas are used in + the algorithm. To disable them because of unreadable output + set ``cubics=False`` or ``quartics=False`` respectively. If cubic + roots are real but are expressed in terms of complex numbers + (casus irreducibilis [1]) the ``trig`` flag can be set to True to + have the solutions returned in terms of cosine and inverse cosine + functions. + + To get roots from a specific domain set the ``filter`` flag with + one of the following specifiers: Z, Q, R, I, C. By default all + roots are returned (this is equivalent to setting ``filter='C'``). + + By default a dictionary is returned giving a compact result in + case of multiple roots. However to get a list containing all + those roots set the ``multiple`` flag to True; the list will + have identical roots appearing next to each other in the result. + (For a given Poly, the all_roots method will give the roots in + sorted numerical order.) + + If the ``strict`` flag is True, ``UnsolvableFactorError`` will be + raised if the roots found are known to be incomplete (because + some roots are not expressible in radicals). + + Examples + ======== + + >>> from sympy import Poly, roots, degree + >>> from sympy.abc import x, y + + >>> roots(x**2 - 1, x) + {-1: 1, 1: 1} + + >>> p = Poly(x**2-1, x) + >>> roots(p) + {-1: 1, 1: 1} + + >>> p = Poly(x**2-y, x, y) + + >>> roots(Poly(p, x)) + {-sqrt(y): 1, sqrt(y): 1} + + >>> roots(x**2 - y, x) + {-sqrt(y): 1, sqrt(y): 1} + + >>> roots([1, 0, -1]) + {-1: 1, 1: 1} + + ``roots`` will only return roots expressible in radicals. If + the given polynomial has some or all of its roots inexpressible in + radicals, the result of ``roots`` will be incomplete or empty + respectively. + + Example where result is incomplete: + + >>> roots((x-1)*(x**5-x+1), x) + {1: 1} + + In this case, the polynomial has an unsolvable quintic factor + whose roots cannot be expressed by radicals. The polynomial has a + rational root (due to the factor `(x-1)`), which is returned since + ``roots`` always finds all rational roots. + + Example where result is empty: + + >>> roots(x**7-3*x**2+1, x) + {} + + Here, the polynomial has no roots expressible in radicals, so + ``roots`` returns an empty dictionary. + + The result produced by ``roots`` is complete if and only if the + sum of the multiplicity of each root is equal to the degree of + the polynomial. If strict=True, UnsolvableFactorError will be + raised if the result is incomplete. + + The result can be be checked for completeness as follows: + + >>> f = x**3-2*x**2+1 + >>> sum(roots(f, x).values()) == degree(f, x) + True + >>> f = (x-1)*(x**5-x+1) + >>> sum(roots(f, x).values()) == degree(f, x) + False + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Cubic_equation#Trigonometric_and_hyperbolic_solutions + + """ + from sympy.polys.polytools import to_rational_coeffs + flags = dict(flags) + + if isinstance(f, list): + if gens: + raise ValueError('redundant generators given') + + x = Dummy('x') + + poly, i = {}, len(f) - 1 + + for coeff in f: + poly[i], i = sympify(coeff), i - 1 + + f = Poly(poly, x, field=True) + else: + try: + F = Poly(f, *gens, **flags) + if not isinstance(f, Poly) and not F.gen.is_Symbol: + raise PolynomialError("generator must be a Symbol") + f = F + except GeneratorsNeeded: + if multiple: + return [] + else: + return {} + else: + n = f.degree() + if f.length() == 2 and n > 2: + # check for foo**n in constant if dep is c*gen**m + con, dep = f.as_expr().as_independent(*f.gens) + fcon = -(-con).factor() + if fcon != con: + con = fcon + bases = [] + for i in Mul.make_args(con): + if i.is_Pow: + b, e = i.as_base_exp() + if e.is_Integer and b.is_Add: + bases.append((b, Dummy(positive=True))) + if bases: + rv = roots(Poly((dep + con).xreplace(dict(bases)), + *f.gens), *F.gens, + auto=auto, + cubics=cubics, + trig=trig, + quartics=quartics, + quintics=quintics, + multiple=multiple, + filter=filter, + predicate=predicate, + **flags) + return {factor_terms(k.xreplace( + {v: k for k, v in bases}) + ): v for k, v in rv.items()} + + if f.is_multivariate: + raise PolynomialError('multivariate polynomials are not supported') + + def _update_dict(result, zeros, currentroot, k): + if currentroot == S.Zero: + if S.Zero in zeros: + zeros[S.Zero] += k + else: + zeros[S.Zero] = k + if currentroot in result: + result[currentroot] += k + else: + result[currentroot] = k + + def _try_decompose(f): + """Find roots using functional decomposition. """ + factors, roots = f.decompose(), [] + + for currentroot in _try_heuristics(factors[0]): + roots.append(currentroot) + + for currentfactor in factors[1:]: + previous, roots = list(roots), [] + + for currentroot in previous: + g = currentfactor - Poly(currentroot, f.gen) + + for currentroot in _try_heuristics(g): + roots.append(currentroot) + + return roots + + def _try_heuristics(f): + """Find roots using formulas and some tricks. """ + if f.is_ground: + return [] + if f.is_monomial: + return [S.Zero]*f.degree() + + if f.length() == 2: + if f.degree() == 1: + return list(map(cancel, roots_linear(f))) + else: + return roots_binomial(f) + + result = [] + + for i in [-1, 1]: + if not f.eval(i): + f = f.quo(Poly(f.gen - i, f.gen)) + result.append(i) + break + + n = f.degree() + + if n == 1: + result += list(map(cancel, roots_linear(f))) + elif n == 2: + result += list(map(cancel, roots_quadratic(f))) + elif f.is_cyclotomic: + result += roots_cyclotomic(f) + elif n == 3 and cubics: + result += roots_cubic(f, trig=trig) + elif n == 4 and quartics: + result += roots_quartic(f) + elif n == 5 and quintics: + result += roots_quintic(f) + + return result + + # Convert the generators to symbols + dumgens = symbols('x:%d' % len(f.gens), cls=Dummy) + f = f.per(f.rep, dumgens) + + (k,), f = f.terms_gcd() + + if not k: + zeros = {} + else: + zeros = {S.Zero: k} + + coeff, f = preprocess_roots(f) + + if auto and f.get_domain().is_Ring: + f = f.to_field() + + # Use EX instead of ZZ_I or QQ_I + if f.get_domain().is_QQ_I: + f = f.per(f.rep.convert(EX)) + + rescale_x = None + translate_x = None + + result = {} + + if not f.is_ground: + dom = f.get_domain() + if not dom.is_Exact and dom.is_Numerical: + for r in f.nroots(): + _update_dict(result, zeros, r, 1) + elif f.degree() == 1: + _update_dict(result, zeros, roots_linear(f)[0], 1) + elif f.length() == 2: + roots_fun = roots_quadratic if f.degree() == 2 else roots_binomial + for r in roots_fun(f): + _update_dict(result, zeros, r, 1) + else: + _, factors = Poly(f.as_expr()).factor_list() + if len(factors) == 1 and f.degree() == 2: + for r in roots_quadratic(f): + _update_dict(result, zeros, r, 1) + else: + if len(factors) == 1 and factors[0][1] == 1: + if f.get_domain().is_EX: + res = to_rational_coeffs(f) + if res: + if res[0] is None: + translate_x, f = res[2:] + else: + rescale_x, f = res[1], res[-1] + result = roots(f) + if not result: + for currentroot in _try_decompose(f): + _update_dict(result, zeros, currentroot, 1) + else: + for r in _try_heuristics(f): + _update_dict(result, zeros, r, 1) + else: + for currentroot in _try_decompose(f): + _update_dict(result, zeros, currentroot, 1) + else: + for currentfactor, k in factors: + for r in _try_heuristics(Poly(currentfactor, f.gen, field=True)): + _update_dict(result, zeros, r, k) + + if coeff is not S.One: + _result, result, = result, {} + + for currentroot, k in _result.items(): + result[coeff*currentroot] = k + + if filter not in [None, 'C']: + handlers = { + 'Z': lambda r: r.is_Integer, + 'Q': lambda r: r.is_Rational, + 'R': lambda r: all(a.is_real for a in r.as_numer_denom()), + 'I': lambda r: r.is_imaginary, + } + + try: + query = handlers[filter] + except KeyError: + raise ValueError("Invalid filter: %s" % filter) + + for zero in dict(result).keys(): + if not query(zero): + del result[zero] + + if predicate is not None: + for zero in dict(result).keys(): + if not predicate(zero): + del result[zero] + if rescale_x: + result1 = {} + for k, v in result.items(): + result1[k*rescale_x] = v + result = result1 + if translate_x: + result1 = {} + for k, v in result.items(): + result1[k + translate_x] = v + result = result1 + + # adding zero roots after non-trivial roots have been translated + result.update(zeros) + + if strict and sum(result.values()) < f.degree(): + raise UnsolvableFactorError(filldedent(''' + Strict mode: some factors cannot be solved in radicals, so + a complete list of solutions cannot be returned. Call + roots with strict=False to get solutions expressible in + radicals (if there are any). + ''')) + + if not multiple: + return result + else: + zeros = [] + + for zero in ordered(result): + zeros.extend([zero]*result[zero]) + + return zeros + + +def root_factors(f, *gens, filter=None, **args): + """ + Returns all factors of a univariate polynomial. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy.polys.polyroots import root_factors + + >>> root_factors(x**2 - y, x) + [x - sqrt(y), x + sqrt(y)] + + """ + args = dict(args) + + F = Poly(f, *gens, **args) + + if not F.is_Poly: + return [f] + + if F.is_multivariate: + raise ValueError('multivariate polynomials are not supported') + + x = F.gens[0] + + zeros = roots(F, filter=filter) + + if not zeros: + factors = [F] + else: + factors, N = [], 0 + + for r, n in ordered(zeros.items()): + factors, N = factors + [Poly(x - r, x)]*n, N + n + + if N < F.degree(): + G = reduce(lambda p, q: p*q, factors) + factors.append(F.quo(G)) + + if not isinstance(f, Poly): + factors = [ f.as_expr() for f in factors ] + + return factors diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polytools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polytools.py new file mode 100644 index 0000000000000000000000000000000000000000..11b9dd3435f8dc68ea3b0578df9fccfb07dd0f4c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polytools.py @@ -0,0 +1,7960 @@ +"""User-friendly public interface to polynomial functions. """ + +from __future__ import annotations + +from functools import wraps, reduce +from operator import mul +from typing import Optional +from collections import Counter, defaultdict + +from sympy.core import ( + S, Expr, Add, Tuple +) +from sympy.core.basic import Basic +from sympy.core.decorators import _sympifyit +from sympy.core.exprtools import Factors, factor_nc, factor_terms +from sympy.core.evalf import ( + pure_complex, evalf, fastlog, _evalf_with_bounded_error, quad_to_mpmath) +from sympy.core.function import Derivative +from sympy.core.mul import Mul, _keep_coeff +from sympy.core.intfunc import ilcm +from sympy.core.numbers import I, Integer, equal_valued +from sympy.core.relational import Relational, Equality +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, Symbol +from sympy.core.sympify import sympify, _sympify +from sympy.core.traversal import preorder_traversal, bottom_up +from sympy.logic.boolalg import BooleanAtom +from sympy.polys import polyoptions as options +from sympy.polys.constructor import construct_domain +from sympy.polys.domains import FF, QQ, ZZ +from sympy.polys.domains.domainelement import DomainElement +from sympy.polys.fglmtools import matrix_fglm +from sympy.polys.groebnertools import groebner as _groebner +from sympy.polys.monomials import Monomial +from sympy.polys.orderings import monomial_key +from sympy.polys.polyclasses import DMP, DMF, ANP +from sympy.polys.polyerrors import ( + OperationNotSupported, DomainError, + CoercionFailed, UnificationFailed, + GeneratorsNeeded, PolynomialError, + MultivariatePolynomialError, + ExactQuotientFailed, + PolificationFailed, + ComputationFailed, + GeneratorsError, +) +from sympy.polys.polyutils import ( + basic_from_dict, + _sort_gens, + _unify_gens, + _dict_reorder, + _dict_from_expr, + _parallel_dict_from_expr, +) +from sympy.polys.rationaltools import together +from sympy.polys.rootisolation import dup_isolate_real_roots_list +from sympy.utilities import group, public, filldedent +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import iterable, sift + +# Required to avoid errors +import sympy.polys + +import mpmath +from mpmath.libmp.libhyper import NoConvergence + + + +def _polifyit(func): + @wraps(func) + def wrapper(f, g): + g = _sympify(g) + if isinstance(g, Poly): + return func(f, g) + elif isinstance(g, Integer): + g = f.from_expr(g, *f.gens, domain=f.domain) + return func(f, g) + elif isinstance(g, Expr): + try: + g = f.from_expr(g, *f.gens) + except PolynomialError: + if g.is_Matrix: + return NotImplemented + expr_method = getattr(f.as_expr(), func.__name__) + result = expr_method(g) + if result is not NotImplemented: + sympy_deprecation_warning( + """ + Mixing Poly with non-polynomial expressions in binary + operations is deprecated. Either explicitly convert + the non-Poly operand to a Poly with as_poly() or + convert the Poly to an Expr with as_expr(). + """, + deprecated_since_version="1.6", + active_deprecations_target="deprecated-poly-nonpoly-binary-operations", + ) + return result + else: + return func(f, g) + else: + return NotImplemented + return wrapper + + + +@public +class Poly(Basic): + """ + Generic class for representing and operating on polynomial expressions. + + See :ref:`polys-docs` for general documentation. + + Poly is a subclass of Basic rather than Expr but instances can be + converted to Expr with the :py:meth:`~.Poly.as_expr` method. + + .. deprecated:: 1.6 + + Combining Poly with non-Poly objects in binary operations is + deprecated. Explicitly convert both objects to either Poly or Expr + first. See :ref:`deprecated-poly-nonpoly-binary-operations`. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + Create a univariate polynomial: + + >>> Poly(x*(x**2 + x - 1)**2) + Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') + + Create a univariate polynomial with specific domain: + + >>> from sympy import sqrt + >>> Poly(x**2 + 2*x + sqrt(3), domain='R') + Poly(1.0*x**2 + 2.0*x + 1.73205080756888, x, domain='RR') + + Create a multivariate polynomial: + + >>> Poly(y*x**2 + x*y + 1) + Poly(x**2*y + x*y + 1, x, y, domain='ZZ') + + Create a univariate polynomial, where y is a constant: + + >>> Poly(y*x**2 + x*y + 1,x) + Poly(y*x**2 + y*x + 1, x, domain='ZZ[y]') + + You can evaluate the above polynomial as a function of y: + + >>> Poly(y*x**2 + x*y + 1,x).eval(2) + 6*y + 1 + + See Also + ======== + + sympy.core.expr.Expr + + """ + + __slots__ = ('rep', 'gens') + + is_commutative = True + is_Poly = True + _op_priority = 10.001 + + rep: DMP + gens: tuple[Expr, ...] + + def __new__(cls, rep, *gens, **args) -> Poly: + """Create a new polynomial instance out of something useful. """ + opt = options.build_options(gens, args) + + if 'order' in opt: + raise NotImplementedError("'order' keyword is not implemented yet") + + if isinstance(rep, (DMP, DMF, ANP, DomainElement)): + return cls._from_domain_element(rep, opt) + elif iterable(rep, exclude=str): + if isinstance(rep, dict): + return cls._from_dict(rep, opt) + else: + return cls._from_list(list(rep), opt) + else: + rep = sympify(rep, evaluate=type(rep) is not str) # type: ignore + + if rep.is_Poly: + return cls._from_poly(rep, opt) + else: + return cls._from_expr(rep, opt) + + # Poly does not pass its args to Basic.__new__ to be stored in _args so we + # have to emulate them here with an args property that derives from rep + # and gens which are instance attributes. This also means we need to + # define _hashable_content. The _hashable_content is rep and gens but args + # uses expr instead of rep (expr is the Basic version of rep). Passing + # expr in args means that Basic methods like subs should work. Using rep + # otherwise means that Poly can remain more efficient than Basic by + # avoiding creating a Basic instance just to be hashable. + + @classmethod + def new(cls, rep, *gens): + """Construct :class:`Poly` instance from raw representation. """ + if not isinstance(rep, DMP): + raise PolynomialError( + "invalid polynomial representation: %s" % rep) + elif rep.lev != len(gens) - 1: + raise PolynomialError("invalid arguments: %s, %s" % (rep, gens)) + + obj = Basic.__new__(cls) + obj.rep = rep + obj.gens = gens + + return obj + + @property + def expr(self): + return basic_from_dict(self.rep.to_sympy_dict(), *self.gens) + + @property + def args(self): + return (self.expr,) + self.gens + + def _hashable_content(self): + return (self.rep,) + self.gens + + @classmethod + def from_dict(cls, rep, *gens, **args): + """Construct a polynomial from a ``dict``. """ + opt = options.build_options(gens, args) + return cls._from_dict(rep, opt) + + @classmethod + def from_list(cls, rep, *gens, **args): + """Construct a polynomial from a ``list``. """ + opt = options.build_options(gens, args) + return cls._from_list(rep, opt) + + @classmethod + def from_poly(cls, rep, *gens, **args): + """Construct a polynomial from a polynomial. """ + opt = options.build_options(gens, args) + return cls._from_poly(rep, opt) + + @classmethod + def from_expr(cls, rep, *gens, **args): + """Construct a polynomial from an expression. """ + opt = options.build_options(gens, args) + return cls._from_expr(rep, opt) + + @classmethod + def _from_dict(cls, rep, opt): + """Construct a polynomial from a ``dict``. """ + gens = opt.gens + + if not gens: + raise GeneratorsNeeded( + "Cannot initialize from 'dict' without generators") + + level = len(gens) - 1 + domain = opt.domain + + if domain is None: + domain, rep = construct_domain(rep, opt=opt) + else: + for monom, coeff in rep.items(): + rep[monom] = domain.convert(coeff) + + return cls.new(DMP.from_dict(rep, level, domain), *gens) + + @classmethod + def _from_list(cls, rep, opt): + """Construct a polynomial from a ``list``. """ + gens = opt.gens + + if not gens: + raise GeneratorsNeeded( + "Cannot initialize from 'list' without generators") + elif len(gens) != 1: + raise MultivariatePolynomialError( + "'list' representation not supported") + + level = len(gens) - 1 + domain = opt.domain + + if domain is None: + domain, rep = construct_domain(rep, opt=opt) + else: + rep = list(map(domain.convert, rep)) + + return cls.new(DMP.from_list(rep, level, domain), *gens) + + @classmethod + def _from_poly(cls, rep, opt): + """Construct a polynomial from a polynomial. """ + if cls != rep.__class__: + rep = cls.new(rep.rep, *rep.gens) + + gens = opt.gens + field = opt.field + domain = opt.domain + + if gens and rep.gens != gens: + if set(rep.gens) != set(gens): + return cls._from_expr(rep.as_expr(), opt) + else: + rep = rep.reorder(*gens) + + if 'domain' in opt and domain: + rep = rep.set_domain(domain) + elif field is True: + rep = rep.to_field() + + return rep + + @classmethod + def _from_expr(cls, rep, opt): + """Construct a polynomial from an expression. """ + rep, opt = _dict_from_expr(rep, opt) + return cls._from_dict(rep, opt) + + @classmethod + def _from_domain_element(cls, rep, opt): + gens = opt.gens + domain = opt.domain + + level = len(gens) - 1 + rep = [domain.convert(rep)] + + return cls.new(DMP.from_list(rep, level, domain), *gens) + + def __hash__(self): + return super().__hash__() + + @property + def free_symbols(self): + """ + Free symbols of a polynomial expression. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y, z + + >>> Poly(x**2 + 1).free_symbols + {x} + >>> Poly(x**2 + y).free_symbols + {x, y} + >>> Poly(x**2 + y, x).free_symbols + {x, y} + >>> Poly(x**2 + y, x, z).free_symbols + {x, y} + + """ + symbols = set() + gens = self.gens + for i in range(len(gens)): + for monom in self.monoms(): + if monom[i]: + symbols |= gens[i].free_symbols + break + + return symbols | self.free_symbols_in_domain + + @property + def free_symbols_in_domain(self): + """ + Free symbols of the domain of ``self``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + 1).free_symbols_in_domain + set() + >>> Poly(x**2 + y).free_symbols_in_domain + set() + >>> Poly(x**2 + y, x).free_symbols_in_domain + {y} + + """ + domain, symbols = self.rep.dom, set() + + if domain.is_Composite: + for gen in domain.symbols: + symbols |= gen.free_symbols + elif domain.is_EX: + for coeff in self.coeffs(): + symbols |= coeff.free_symbols + + return symbols + + @property + def gen(self): + """ + Return the principal generator. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).gen + x + + """ + return self.gens[0] + + @property + def domain(self): + """Get the ground domain of a :py:class:`~.Poly` + + Returns + ======= + + :py:class:`~.Domain`: + Ground domain of the :py:class:`~.Poly`. + + Examples + ======== + + >>> from sympy import Poly, Symbol + >>> x = Symbol('x') + >>> p = Poly(x**2 + x) + >>> p + Poly(x**2 + x, x, domain='ZZ') + >>> p.domain + ZZ + """ + return self.get_domain() + + @property + def zero(self): + """Return zero polynomial with ``self``'s properties. """ + return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens) + + @property + def one(self): + """Return one polynomial with ``self``'s properties. """ + return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens) + + def unify(f, g): + """ + Make ``f`` and ``g`` belong to the same domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f, g = Poly(x/2 + 1), Poly(2*x + 1) + + >>> f + Poly(1/2*x + 1, x, domain='QQ') + >>> g + Poly(2*x + 1, x, domain='ZZ') + + >>> F, G = f.unify(g) + + >>> F + Poly(1/2*x + 1, x, domain='QQ') + >>> G + Poly(2*x + 1, x, domain='QQ') + + """ + _, per, F, G = f._unify(g) + return per(F), per(G) + + def _unify(f, g): + g = sympify(g) + + if not g.is_Poly: + try: + g_coeff = f.rep.dom.from_sympy(g) + except CoercionFailed: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + else: + return f.rep.dom, f.per, f.rep, f.rep.ground_new(g_coeff) + + if isinstance(f.rep, DMP) and isinstance(g.rep, DMP): + gens = _unify_gens(f.gens, g.gens) + + dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens) - 1 + + if f.gens != gens: + f_monoms, f_coeffs = _dict_reorder( + f.rep.to_dict(), f.gens, gens) + + if f.rep.dom != dom: + f_coeffs = [dom.convert(c, f.rep.dom) for c in f_coeffs] + + F = DMP.from_dict(dict(list(zip(f_monoms, f_coeffs))), lev, dom) + else: + F = f.rep.convert(dom) + + if g.gens != gens: + g_monoms, g_coeffs = _dict_reorder( + g.rep.to_dict(), g.gens, gens) + + if g.rep.dom != dom: + g_coeffs = [dom.convert(c, g.rep.dom) for c in g_coeffs] + + G = DMP.from_dict(dict(list(zip(g_monoms, g_coeffs))), lev, dom) + else: + G = g.rep.convert(dom) + else: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + cls = f.__class__ + + def per(rep, dom=dom, gens=gens, remove=None): + if remove is not None: + gens = gens[:remove] + gens[remove + 1:] + + if not gens: + return dom.to_sympy(rep) + + return cls.new(rep, *gens) + + return dom, per, F, G + + def per(f, rep, gens=None, remove=None): + """ + Create a Poly out of the given representation. + + Examples + ======== + + >>> from sympy import Poly, ZZ + >>> from sympy.abc import x, y + + >>> from sympy.polys.polyclasses import DMP + + >>> a = Poly(x**2 + 1) + + >>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y]) + Poly(y + 1, y, domain='ZZ') + + """ + if gens is None: + gens = f.gens + + if remove is not None: + gens = gens[:remove] + gens[remove + 1:] + + if not gens: + return f.rep.dom.to_sympy(rep) + + return f.__class__.new(rep, *gens) + + def set_domain(f, domain): + """Set the ground domain of ``f``. """ + opt = options.build_options(f.gens, {'domain': domain}) + return f.per(f.rep.convert(opt.domain)) + + def get_domain(f): + """Get the ground domain of ``f``. """ + return f.rep.dom + + def set_modulus(f, modulus): + """ + Set the modulus of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2) + Poly(x**2 + 1, x, modulus=2) + + """ + modulus = options.Modulus.preprocess(modulus) + return f.set_domain(FF(modulus)) + + def get_modulus(f): + """ + Get the modulus of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, modulus=2).get_modulus() + 2 + + """ + domain = f.get_domain() + + if domain.is_FiniteField: + return Integer(domain.characteristic()) + else: + raise PolynomialError("not a polynomial over a Galois field") + + def _eval_subs(f, old, new): + """Internal implementation of :func:`subs`. """ + if old in f.gens: + if new.is_number: + return f.eval(old, new) + else: + try: + return f.replace(old, new) + except PolynomialError: + pass + + return f.as_expr().subs(old, new) + + def exclude(f): + """ + Remove unnecessary generators from ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import a, b, c, d, x + + >>> Poly(a + x, a, b, c, d, x).exclude() + Poly(a + x, a, x, domain='ZZ') + + """ + J, new = f.rep.exclude() + gens = [gen for j, gen in enumerate(f.gens) if j not in J] + + return f.per(new, gens=gens) + + def replace(f, x, y=None, **_ignore): + # XXX this does not match Basic's signature + """ + Replace ``x`` with ``y`` in generators list. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + 1, x).replace(x, y) + Poly(y**2 + 1, y, domain='ZZ') + + """ + if y is None: + if f.is_univariate: + x, y = f.gen, x + else: + raise PolynomialError( + "syntax supported only in univariate case") + + if x == y or x not in f.gens: + return f + + if x in f.gens and y not in f.gens: + dom = f.get_domain() + + if not dom.is_Composite or y not in dom.symbols: + gens = list(f.gens) + gens[gens.index(x)] = y + return f.per(f.rep, gens=gens) + + raise PolynomialError("Cannot replace %s with %s in %s" % (x, y, f)) + + def match(f, *args, **kwargs): + """Match expression from Poly. See Basic.match()""" + return f.as_expr().match(*args, **kwargs) + + def reorder(f, *gens, **args): + """ + Efficiently apply new order of generators. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + x*y**2, x, y).reorder(y, x) + Poly(y**2*x + x**2, y, x, domain='ZZ') + + """ + opt = options.Options((), args) + + if not gens: + gens = _sort_gens(f.gens, opt=opt) + elif set(f.gens) != set(gens): + raise PolynomialError( + "generators list can differ only up to order of elements") + + rep = dict(list(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens)))) + + return f.per(DMP.from_dict(rep, len(gens) - 1, f.rep.dom), gens=gens) + + def ltrim(f, gen): + """ + Remove dummy generators from ``f`` that are to the left of + specified ``gen`` in the generators as ordered. When ``gen`` + is an integer, it refers to the generator located at that + position within the tuple of generators of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y, z + + >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y) + Poly(y**2 + y*z**2, y, z, domain='ZZ') + >>> Poly(z, x, y, z).ltrim(-1) + Poly(z, z, domain='ZZ') + + """ + rep = f.as_dict(native=True) + j = f._gen_to_level(gen) + + terms = {} + + for monom, coeff in rep.items(): + + if any(monom[:j]): + # some generator is used in the portion to be trimmed + raise PolynomialError("Cannot left trim %s" % f) + + terms[monom[j:]] = coeff + + gens = f.gens[j:] + + return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens) + + def has_only_gens(f, *gens): + """ + Return ``True`` if ``Poly(f, *gens)`` retains ground domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y, z + + >>> Poly(x*y + 1, x, y, z).has_only_gens(x, y) + True + >>> Poly(x*y + z, x, y, z).has_only_gens(x, y) + False + + """ + indices = set() + + for gen in gens: + try: + index = f.gens.index(gen) + except ValueError: + raise GeneratorsError( + "%s doesn't have %s as generator" % (f, gen)) + else: + indices.add(index) + + for monom in f.monoms(): + for i, elt in enumerate(monom): + if i not in indices and elt: + return False + + return True + + def to_ring(f): + """ + Make the ground domain a ring. + + Examples + ======== + + >>> from sympy import Poly, QQ + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, domain=QQ).to_ring() + Poly(x**2 + 1, x, domain='ZZ') + + """ + if hasattr(f.rep, 'to_ring'): + result = f.rep.to_ring() + else: # pragma: no cover + raise OperationNotSupported(f, 'to_ring') + + return f.per(result) + + def to_field(f): + """ + Make the ground domain a field. + + Examples + ======== + + >>> from sympy import Poly, ZZ + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x, domain=ZZ).to_field() + Poly(x**2 + 1, x, domain='QQ') + + """ + if hasattr(f.rep, 'to_field'): + result = f.rep.to_field() + else: # pragma: no cover + raise OperationNotSupported(f, 'to_field') + + return f.per(result) + + def to_exact(f): + """ + Make the ground domain exact. + + Examples + ======== + + >>> from sympy import Poly, RR + >>> from sympy.abc import x + + >>> Poly(x**2 + 1.0, x, domain=RR).to_exact() + Poly(x**2 + 1, x, domain='QQ') + + """ + if hasattr(f.rep, 'to_exact'): + result = f.rep.to_exact() + else: # pragma: no cover + raise OperationNotSupported(f, 'to_exact') + + return f.per(result) + + def retract(f, field=None): + """ + Recalculate the ground domain of a polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = Poly(x**2 + 1, x, domain='QQ[y]') + >>> f + Poly(x**2 + 1, x, domain='QQ[y]') + + >>> f.retract() + Poly(x**2 + 1, x, domain='ZZ') + >>> f.retract(field=True) + Poly(x**2 + 1, x, domain='QQ') + + """ + dom, rep = construct_domain(f.as_dict(zero=True), + field=field, composite=f.domain.is_Composite or None) + return f.from_dict(rep, f.gens, domain=dom) + + def slice(f, x, m, n=None): + """Take a continuous subsequence of terms of ``f``. """ + if n is None: + j, m, n = 0, x, m + else: + j = f._gen_to_level(x) + + m, n = int(m), int(n) + + if hasattr(f.rep, 'slice'): + result = f.rep.slice(m, n, j) + else: # pragma: no cover + raise OperationNotSupported(f, 'slice') + + return f.per(result) + + def coeffs(f, order=None): + """ + Returns all non-zero coefficients from ``f`` in lex order. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 + 2*x + 3, x).coeffs() + [1, 2, 3] + + See Also + ======== + all_coeffs + coeff_monomial + nth + + """ + return [f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order)] + + def monoms(f, order=None): + """ + Returns all non-zero monomials from ``f`` in lex order. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms() + [(2, 0), (1, 2), (1, 1), (0, 1)] + + See Also + ======== + all_monoms + + """ + return f.rep.monoms(order=order) + + def terms(f, order=None): + """ + Returns all non-zero terms from ``f`` in lex order. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms() + [((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)] + + See Also + ======== + all_terms + + """ + return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order)] + + def all_coeffs(f): + """ + Returns all coefficients from a univariate polynomial ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 + 2*x - 1, x).all_coeffs() + [1, 0, 2, -1] + + """ + return [f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs()] + + def all_monoms(f): + """ + Returns all monomials from a univariate polynomial ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 + 2*x - 1, x).all_monoms() + [(3,), (2,), (1,), (0,)] + + See Also + ======== + all_terms + + """ + return f.rep.all_monoms() + + def all_terms(f): + """ + Returns all terms from a univariate polynomial ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 + 2*x - 1, x).all_terms() + [((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)] + + """ + return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms()] + + def termwise(f, func, *gens, **args): + """ + Apply a function to all terms of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> def func(k, coeff): + ... k = k[0] + ... return coeff//10**(2-k) + + >>> Poly(x**2 + 20*x + 400).termwise(func) + Poly(x**2 + 2*x + 4, x, domain='ZZ') + + """ + terms = {} + + for monom, coeff in f.terms(): + result = func(monom, coeff) + + if isinstance(result, tuple): + monom, coeff = result + else: + coeff = result + + if coeff: + if monom not in terms: + terms[monom] = coeff + else: + raise PolynomialError( + "%s monomial was generated twice" % monom) + + return f.from_dict(terms, *(gens or f.gens), **args) + + def length(f): + """ + Returns the number of non-zero terms in ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 2*x - 1).length() + 3 + + """ + return len(f.as_dict()) + + def as_dict(f, native=False, zero=False): + """ + Switch to a ``dict`` representation. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict() + {(0, 1): -1, (1, 2): 2, (2, 0): 1} + + """ + if native: + return f.rep.to_dict(zero=zero) + else: + return f.rep.to_sympy_dict(zero=zero) + + def as_list(f, native=False): + """Switch to a ``list`` representation. """ + if native: + return f.rep.to_list() + else: + return f.rep.to_sympy_list() + + def as_expr(f, *gens): + """ + Convert a Poly instance to an Expr instance. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> f = Poly(x**2 + 2*x*y**2 - y, x, y) + + >>> f.as_expr() + x**2 + 2*x*y**2 - y + >>> f.as_expr({x: 5}) + 10*y**2 - y + 25 + >>> f.as_expr(5, 6) + 379 + + """ + if not gens: + return f.expr + + if len(gens) == 1 and isinstance(gens[0], dict): + mapping = gens[0] + gens = list(f.gens) + + for gen, value in mapping.items(): + try: + index = gens.index(gen) + except ValueError: + raise GeneratorsError( + "%s doesn't have %s as generator" % (f, gen)) + else: + gens[index] = value + + return basic_from_dict(f.rep.to_sympy_dict(), *gens) + + def as_poly(self, *gens, **args): + """Converts ``self`` to a polynomial or returns ``None``. + + >>> from sympy import sin + >>> from sympy.abc import x, y + + >>> print((x**2 + x*y).as_poly()) + Poly(x**2 + x*y, x, y, domain='ZZ') + + >>> print((x**2 + x*y).as_poly(x, y)) + Poly(x**2 + x*y, x, y, domain='ZZ') + + >>> print((x**2 + sin(y)).as_poly(x, y)) + None + + """ + try: + poly = Poly(self, *gens, **args) + + if not poly.is_Poly: + return None + else: + return poly + except PolynomialError: + return None + + def lift(f): + """ + Convert algebraic coefficients to rationals. + + Examples + ======== + + >>> from sympy import Poly, I + >>> from sympy.abc import x + + >>> Poly(x**2 + I*x + 1, x, extension=I).lift() + Poly(x**4 + 3*x**2 + 1, x, domain='QQ') + + """ + if hasattr(f.rep, 'lift'): + result = f.rep.lift() + else: # pragma: no cover + raise OperationNotSupported(f, 'lift') + + return f.per(result) + + def deflate(f): + """ + Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate() + ((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ')) + + """ + if hasattr(f.rep, 'deflate'): + J, result = f.rep.deflate() + else: # pragma: no cover + raise OperationNotSupported(f, 'deflate') + + return J, f.per(result) + + def inject(f, front=False): + """ + Inject ground domain generators into ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x) + + >>> f.inject() + Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ') + >>> f.inject(front=True) + Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ') + + """ + dom = f.rep.dom + + if dom.is_Numerical: + return f + elif not dom.is_Poly: + raise DomainError("Cannot inject generators over %s" % dom) + + if hasattr(f.rep, 'inject'): + result = f.rep.inject(front=front) + else: # pragma: no cover + raise OperationNotSupported(f, 'inject') + + if front: + gens = dom.symbols + f.gens + else: + gens = f.gens + dom.symbols + + return f.new(result, *gens) + + def eject(f, *gens): + """ + Eject selected generators into the ground domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) + + >>> f.eject(x) + Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') + >>> f.eject(y) + Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') + + """ + dom = f.rep.dom + + if not dom.is_Numerical: + raise DomainError("Cannot eject generators over %s" % dom) + + k = len(gens) + + if f.gens[:k] == gens: + _gens, front = f.gens[k:], True + elif f.gens[-k:] == gens: + _gens, front = f.gens[:-k], False + else: + raise NotImplementedError( + "can only eject front or back generators") + + dom = dom.inject(*gens) + + if hasattr(f.rep, 'eject'): + result = f.rep.eject(dom, front=front) + else: # pragma: no cover + raise OperationNotSupported(f, 'eject') + + return f.new(result, *_gens) + + def terms_gcd(f): + """ + Remove GCD of terms from the polynomial ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd() + ((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ')) + + """ + if hasattr(f.rep, 'terms_gcd'): + J, result = f.rep.terms_gcd() + else: # pragma: no cover + raise OperationNotSupported(f, 'terms_gcd') + + return J, f.per(result) + + def add_ground(f, coeff): + """ + Add an element of the ground domain to ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x + 1).add_ground(2) + Poly(x + 3, x, domain='ZZ') + + """ + if hasattr(f.rep, 'add_ground'): + result = f.rep.add_ground(coeff) + else: # pragma: no cover + raise OperationNotSupported(f, 'add_ground') + + return f.per(result) + + def sub_ground(f, coeff): + """ + Subtract an element of the ground domain from ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x + 1).sub_ground(2) + Poly(x - 1, x, domain='ZZ') + + """ + if hasattr(f.rep, 'sub_ground'): + result = f.rep.sub_ground(coeff) + else: # pragma: no cover + raise OperationNotSupported(f, 'sub_ground') + + return f.per(result) + + def mul_ground(f, coeff): + """ + Multiply ``f`` by a an element of the ground domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x + 1).mul_ground(2) + Poly(2*x + 2, x, domain='ZZ') + + """ + if hasattr(f.rep, 'mul_ground'): + result = f.rep.mul_ground(coeff) + else: # pragma: no cover + raise OperationNotSupported(f, 'mul_ground') + + return f.per(result) + + def quo_ground(f, coeff): + """ + Quotient of ``f`` by a an element of the ground domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x + 4).quo_ground(2) + Poly(x + 2, x, domain='ZZ') + + >>> Poly(2*x + 3).quo_ground(2) + Poly(x + 1, x, domain='ZZ') + + """ + if hasattr(f.rep, 'quo_ground'): + result = f.rep.quo_ground(coeff) + else: # pragma: no cover + raise OperationNotSupported(f, 'quo_ground') + + return f.per(result) + + def exquo_ground(f, coeff): + """ + Exact quotient of ``f`` by a an element of the ground domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x + 4).exquo_ground(2) + Poly(x + 2, x, domain='ZZ') + + >>> Poly(2*x + 3).exquo_ground(2) + Traceback (most recent call last): + ... + ExactQuotientFailed: 2 does not divide 3 in ZZ + + """ + if hasattr(f.rep, 'exquo_ground'): + result = f.rep.exquo_ground(coeff) + else: # pragma: no cover + raise OperationNotSupported(f, 'exquo_ground') + + return f.per(result) + + def abs(f): + """ + Make all coefficients in ``f`` positive. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).abs() + Poly(x**2 + 1, x, domain='ZZ') + + """ + if hasattr(f.rep, 'abs'): + result = f.rep.abs() + else: # pragma: no cover + raise OperationNotSupported(f, 'abs') + + return f.per(result) + + def neg(f): + """ + Negate all coefficients in ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).neg() + Poly(-x**2 + 1, x, domain='ZZ') + + >>> -Poly(x**2 - 1, x) + Poly(-x**2 + 1, x, domain='ZZ') + + """ + if hasattr(f.rep, 'neg'): + result = f.rep.neg() + else: # pragma: no cover + raise OperationNotSupported(f, 'neg') + + return f.per(result) + + def add(f, g): + """ + Add two polynomials ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).add(Poly(x - 2, x)) + Poly(x**2 + x - 1, x, domain='ZZ') + + >>> Poly(x**2 + 1, x) + Poly(x - 2, x) + Poly(x**2 + x - 1, x, domain='ZZ') + + """ + g = sympify(g) + + if not g.is_Poly: + return f.add_ground(g) + + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'add'): + result = F.add(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'add') + + return per(result) + + def sub(f, g): + """ + Subtract two polynomials ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).sub(Poly(x - 2, x)) + Poly(x**2 - x + 3, x, domain='ZZ') + + >>> Poly(x**2 + 1, x) - Poly(x - 2, x) + Poly(x**2 - x + 3, x, domain='ZZ') + + """ + g = sympify(g) + + if not g.is_Poly: + return f.sub_ground(g) + + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'sub'): + result = F.sub(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'sub') + + return per(result) + + def mul(f, g): + """ + Multiply two polynomials ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).mul(Poly(x - 2, x)) + Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') + + >>> Poly(x**2 + 1, x)*Poly(x - 2, x) + Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') + + """ + g = sympify(g) + + if not g.is_Poly: + return f.mul_ground(g) + + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'mul'): + result = F.mul(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'mul') + + return per(result) + + def sqr(f): + """ + Square a polynomial ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x - 2, x).sqr() + Poly(x**2 - 4*x + 4, x, domain='ZZ') + + >>> Poly(x - 2, x)**2 + Poly(x**2 - 4*x + 4, x, domain='ZZ') + + """ + if hasattr(f.rep, 'sqr'): + result = f.rep.sqr() + else: # pragma: no cover + raise OperationNotSupported(f, 'sqr') + + return f.per(result) + + def pow(f, n): + """ + Raise ``f`` to a non-negative power ``n``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x - 2, x).pow(3) + Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') + + >>> Poly(x - 2, x)**3 + Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') + + """ + n = int(n) + + if hasattr(f.rep, 'pow'): + result = f.rep.pow(n) + else: # pragma: no cover + raise OperationNotSupported(f, 'pow') + + return f.per(result) + + def pdiv(f, g): + """ + Polynomial pseudo-division of ``f`` by ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x)) + (Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ')) + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'pdiv'): + q, r = F.pdiv(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'pdiv') + + return per(q), per(r) + + def prem(f, g): + """ + Polynomial pseudo-remainder of ``f`` by ``g``. + + Caveat: The function prem(f, g, x) can be safely used to compute + in Z[x] _only_ subresultant polynomial remainder sequences (prs's). + + To safely compute Euclidean and Sturmian prs's in Z[x] + employ anyone of the corresponding functions found in + the module sympy.polys.subresultants_qq_zz. The functions + in the module with suffix _pg compute prs's in Z[x] employing + rem(f, g, x), whereas the functions with suffix _amv + compute prs's in Z[x] employing rem_z(f, g, x). + + The function rem_z(f, g, x) differs from prem(f, g, x) in that + to compute the remainder polynomials in Z[x] it premultiplies + the divident times the absolute value of the leading coefficient + of the divisor raised to the power degree(f, x) - degree(g, x) + 1. + + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x)) + Poly(20, x, domain='ZZ') + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'prem'): + result = F.prem(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'prem') + + return per(result) + + def pquo(f, g): + """ + Polynomial pseudo-quotient of ``f`` by ``g``. + + See the Caveat note in the function prem(f, g). + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x)) + Poly(2*x + 4, x, domain='ZZ') + + >>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x)) + Poly(2*x + 2, x, domain='ZZ') + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'pquo'): + result = F.pquo(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'pquo') + + return per(result) + + def pexquo(f, g): + """ + Polynomial exact pseudo-quotient of ``f`` by ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x)) + Poly(2*x + 2, x, domain='ZZ') + + >>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x)) + Traceback (most recent call last): + ... + ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'pexquo'): + try: + result = F.pexquo(G) + except ExactQuotientFailed as exc: + raise exc.new(f.as_expr(), g.as_expr()) + else: # pragma: no cover + raise OperationNotSupported(f, 'pexquo') + + return per(result) + + def div(f, g, auto=True): + """ + Polynomial division with remainder of ``f`` by ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x)) + (Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ')) + + >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False) + (Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ')) + + """ + dom, per, F, G = f._unify(g) + retract = False + + if auto and dom.is_Ring and not dom.is_Field: + F, G = F.to_field(), G.to_field() + retract = True + + if hasattr(f.rep, 'div'): + q, r = F.div(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'div') + + if retract: + try: + Q, R = q.to_ring(), r.to_ring() + except CoercionFailed: + pass + else: + q, r = Q, R + + return per(q), per(r) + + def rem(f, g, auto=True): + """ + Computes the polynomial remainder of ``f`` by ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x)) + Poly(5, x, domain='ZZ') + + >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False) + Poly(x**2 + 1, x, domain='ZZ') + + """ + dom, per, F, G = f._unify(g) + retract = False + + if auto and dom.is_Ring and not dom.is_Field: + F, G = F.to_field(), G.to_field() + retract = True + + if hasattr(f.rep, 'rem'): + r = F.rem(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'rem') + + if retract: + try: + r = r.to_ring() + except CoercionFailed: + pass + + return per(r) + + def quo(f, g, auto=True): + """ + Computes polynomial quotient of ``f`` by ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x)) + Poly(1/2*x + 1, x, domain='QQ') + + >>> Poly(x**2 - 1, x).quo(Poly(x - 1, x)) + Poly(x + 1, x, domain='ZZ') + + """ + dom, per, F, G = f._unify(g) + retract = False + + if auto and dom.is_Ring and not dom.is_Field: + F, G = F.to_field(), G.to_field() + retract = True + + if hasattr(f.rep, 'quo'): + q = F.quo(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'quo') + + if retract: + try: + q = q.to_ring() + except CoercionFailed: + pass + + return per(q) + + def exquo(f, g, auto=True): + """ + Computes polynomial exact quotient of ``f`` by ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x)) + Poly(x + 1, x, domain='ZZ') + + >>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x)) + Traceback (most recent call last): + ... + ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 + + """ + dom, per, F, G = f._unify(g) + retract = False + + if auto and dom.is_Ring and not dom.is_Field: + F, G = F.to_field(), G.to_field() + retract = True + + if hasattr(f.rep, 'exquo'): + try: + q = F.exquo(G) + except ExactQuotientFailed as exc: + raise exc.new(f.as_expr(), g.as_expr()) + else: # pragma: no cover + raise OperationNotSupported(f, 'exquo') + + if retract: + try: + q = q.to_ring() + except CoercionFailed: + pass + + return per(q) + + def _gen_to_level(f, gen): + """Returns level associated with the given generator. """ + if isinstance(gen, int): + length = len(f.gens) + + if -length <= gen < length: + if gen < 0: + return length + gen + else: + return gen + else: + raise PolynomialError("-%s <= gen < %s expected, got %s" % + (length, length, gen)) + else: + try: + return f.gens.index(sympify(gen)) + except ValueError: + raise PolynomialError( + "a valid generator expected, got %s" % gen) + + def degree(f, gen=0): + """ + Returns degree of ``f`` in ``x_j``. + + The degree of 0 is negative infinity. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + y*x + 1, x, y).degree() + 2 + >>> Poly(x**2 + y*x + y, x, y).degree(y) + 1 + >>> Poly(0, x).degree() + -oo + + """ + j = f._gen_to_level(gen) + + if hasattr(f.rep, 'degree'): + d = f.rep.degree(j) + if d < 0: + d = S.NegativeInfinity + return d + else: # pragma: no cover + raise OperationNotSupported(f, 'degree') + + def degree_list(f): + """ + Returns a list of degrees of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + y*x + 1, x, y).degree_list() + (2, 1) + + """ + if hasattr(f.rep, 'degree_list'): + return f.rep.degree_list() + else: # pragma: no cover + raise OperationNotSupported(f, 'degree_list') + + def total_degree(f): + """ + Returns the total degree of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + y*x + 1, x, y).total_degree() + 2 + >>> Poly(x + y**5, x, y).total_degree() + 5 + + """ + if hasattr(f.rep, 'total_degree'): + return f.rep.total_degree() + else: # pragma: no cover + raise OperationNotSupported(f, 'total_degree') + + def homogenize(f, s): + """ + Returns the homogeneous polynomial of ``f``. + + A homogeneous polynomial is a polynomial whose all monomials with + non-zero coefficients have the same total degree. If you only + want to check if a polynomial is homogeneous, then use + :func:`Poly.is_homogeneous`. If you want not only to check if a + polynomial is homogeneous but also compute its homogeneous order, + then use :func:`Poly.homogeneous_order`. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y, z + + >>> f = Poly(x**5 + 2*x**2*y**2 + 9*x*y**3) + >>> f.homogenize(z) + Poly(x**5 + 2*x**2*y**2*z + 9*x*y**3*z, x, y, z, domain='ZZ') + + """ + if not isinstance(s, Symbol): + raise TypeError("``Symbol`` expected, got %s" % type(s)) + if s in f.gens: + i = f.gens.index(s) + gens = f.gens + else: + i = len(f.gens) + gens = f.gens + (s,) + if hasattr(f.rep, 'homogenize'): + return f.per(f.rep.homogenize(i), gens=gens) + raise OperationNotSupported(f, 'homogeneous_order') + + def homogeneous_order(f): + """ + Returns the homogeneous order of ``f``. + + A homogeneous polynomial is a polynomial whose all monomials with + non-zero coefficients have the same total degree. This degree is + the homogeneous order of ``f``. If you only want to check if a + polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4) + >>> f.homogeneous_order() + 5 + + """ + if hasattr(f.rep, 'homogeneous_order'): + return f.rep.homogeneous_order() + else: # pragma: no cover + raise OperationNotSupported(f, 'homogeneous_order') + + def LC(f, order=None): + """ + Returns the leading coefficient of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC() + 4 + + """ + if order is not None: + return f.coeffs(order)[0] + + if hasattr(f.rep, 'LC'): + result = f.rep.LC() + else: # pragma: no cover + raise OperationNotSupported(f, 'LC') + + return f.rep.dom.to_sympy(result) + + def TC(f): + """ + Returns the trailing coefficient of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 + 2*x**2 + 3*x, x).TC() + 0 + + """ + if hasattr(f.rep, 'TC'): + result = f.rep.TC() + else: # pragma: no cover + raise OperationNotSupported(f, 'TC') + + return f.rep.dom.to_sympy(result) + + def EC(f, order=None): + """ + Returns the last non-zero coefficient of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 + 2*x**2 + 3*x, x).EC() + 3 + + """ + if hasattr(f.rep, 'coeffs'): + return f.coeffs(order)[-1] + else: # pragma: no cover + raise OperationNotSupported(f, 'EC') + + def coeff_monomial(f, monom): + """ + Returns the coefficient of ``monom`` in ``f`` if there, else None. + + Examples + ======== + + >>> from sympy import Poly, exp + >>> from sympy.abc import x, y + + >>> p = Poly(24*x*y*exp(8) + 23*x, x, y) + + >>> p.coeff_monomial(x) + 23 + >>> p.coeff_monomial(y) + 0 + >>> p.coeff_monomial(x*y) + 24*exp(8) + + Note that ``Expr.coeff()`` behaves differently, collecting terms + if possible; the Poly must be converted to an Expr to use that + method, however: + + >>> p.as_expr().coeff(x) + 24*y*exp(8) + 23 + >>> p.as_expr().coeff(y) + 24*x*exp(8) + >>> p.as_expr().coeff(x*y) + 24*exp(8) + + See Also + ======== + nth: more efficient query using exponents of the monomial's generators + + """ + return f.nth(*Monomial(monom, f.gens).exponents) + + def nth(f, *N): + """ + Returns the ``n``-th coefficient of ``f`` where ``N`` are the + exponents of the generators in the term of interest. + + Examples + ======== + + >>> from sympy import Poly, sqrt + >>> from sympy.abc import x, y + + >>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2) + 2 + >>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2) + 2 + >>> Poly(4*sqrt(x)*y) + Poly(4*y*(sqrt(x)), y, sqrt(x), domain='ZZ') + >>> _.nth(1, 1) + 4 + + See Also + ======== + coeff_monomial + + """ + if hasattr(f.rep, 'nth'): + if len(N) != len(f.gens): + raise ValueError('exponent of each generator must be specified') + result = f.rep.nth(*list(map(int, N))) + else: # pragma: no cover + raise OperationNotSupported(f, 'nth') + + return f.rep.dom.to_sympy(result) + + def coeff(f, x, n=1, right=False): + # the semantics of coeff_monomial and Expr.coeff are different; + # if someone is working with a Poly, they should be aware of the + # differences and chose the method best suited for the query. + # Alternatively, a pure-polys method could be written here but + # at this time the ``right`` keyword would be ignored because Poly + # doesn't work with non-commutatives. + raise NotImplementedError( + 'Either convert to Expr with `as_expr` method ' + 'to use Expr\'s coeff method or else use the ' + '`coeff_monomial` method of Polys.') + + def LM(f, order=None): + """ + Returns the leading monomial of ``f``. + + The Leading monomial signifies the monomial having + the highest power of the principal generator in the + expression f. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM() + x**2*y**0 + + """ + return Monomial(f.monoms(order)[0], f.gens) + + def EM(f, order=None): + """ + Returns the last non-zero monomial of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM() + x**0*y**1 + + """ + return Monomial(f.monoms(order)[-1], f.gens) + + def LT(f, order=None): + """ + Returns the leading term of ``f``. + + The Leading term signifies the term having + the highest power of the principal generator in the + expression f along with its coefficient. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT() + (x**2*y**0, 4) + + """ + monom, coeff = f.terms(order)[0] + return Monomial(monom, f.gens), coeff + + def ET(f, order=None): + """ + Returns the last non-zero term of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET() + (x**0*y**1, 3) + + """ + monom, coeff = f.terms(order)[-1] + return Monomial(monom, f.gens), coeff + + def max_norm(f): + """ + Returns maximum norm of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(-x**2 + 2*x - 3, x).max_norm() + 3 + + """ + if hasattr(f.rep, 'max_norm'): + result = f.rep.max_norm() + else: # pragma: no cover + raise OperationNotSupported(f, 'max_norm') + + return f.rep.dom.to_sympy(result) + + def l1_norm(f): + """ + Returns l1 norm of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(-x**2 + 2*x - 3, x).l1_norm() + 6 + + """ + if hasattr(f.rep, 'l1_norm'): + result = f.rep.l1_norm() + else: # pragma: no cover + raise OperationNotSupported(f, 'l1_norm') + + return f.rep.dom.to_sympy(result) + + def clear_denoms(self, convert=False): + """ + Clear denominators, but keep the ground domain. + + Examples + ======== + + >>> from sympy import Poly, S, QQ + >>> from sympy.abc import x + + >>> f = Poly(x/2 + S(1)/3, x, domain=QQ) + + >>> f.clear_denoms() + (6, Poly(3*x + 2, x, domain='QQ')) + >>> f.clear_denoms(convert=True) + (6, Poly(3*x + 2, x, domain='ZZ')) + + """ + f = self + + if not f.rep.dom.is_Field: + return S.One, f + + dom = f.get_domain() + if dom.has_assoc_Ring: + dom = f.rep.dom.get_ring() + + if hasattr(f.rep, 'clear_denoms'): + coeff, result = f.rep.clear_denoms() + else: # pragma: no cover + raise OperationNotSupported(f, 'clear_denoms') + + coeff, f = dom.to_sympy(coeff), f.per(result) + + if not convert or not dom.has_assoc_Ring: + return coeff, f + else: + return coeff, f.to_ring() + + def rat_clear_denoms(self, g): + """ + Clear denominators in a rational function ``f/g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> f = Poly(x**2/y + 1, x) + >>> g = Poly(x**3 + y, x) + + >>> p, q = f.rat_clear_denoms(g) + + >>> p + Poly(x**2 + y, x, domain='ZZ[y]') + >>> q + Poly(y*x**3 + y**2, x, domain='ZZ[y]') + + """ + f = self + + dom, per, f, g = f._unify(g) + + f = per(f) + g = per(g) + + if not (dom.is_Field and dom.has_assoc_Ring): + return f, g + + a, f = f.clear_denoms(convert=True) + b, g = g.clear_denoms(convert=True) + + f = f.mul_ground(b) + g = g.mul_ground(a) + + return f, g + + def integrate(self, *specs, **args): + """ + Computes indefinite integral of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + 2*x + 1, x).integrate() + Poly(1/3*x**3 + x**2 + x, x, domain='QQ') + + >>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0)) + Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ') + + """ + f = self + + if args.get('auto', True) and f.rep.dom.is_Ring: + f = f.to_field() + + if hasattr(f.rep, 'integrate'): + if not specs: + return f.per(f.rep.integrate(m=1)) + + rep = f.rep + + for spec in specs: + if isinstance(spec, tuple): + gen, m = spec + else: + gen, m = spec, 1 + + rep = rep.integrate(int(m), f._gen_to_level(gen)) + + return f.per(rep) + else: # pragma: no cover + raise OperationNotSupported(f, 'integrate') + + def diff(f, *specs, **kwargs): + """ + Computes partial derivative of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + 2*x + 1, x).diff() + Poly(2*x + 2, x, domain='ZZ') + + >>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1)) + Poly(2*x*y, x, y, domain='ZZ') + + """ + if not kwargs.get('evaluate', True): + return Derivative(f, *specs, **kwargs) + + if hasattr(f.rep, 'diff'): + if not specs: + return f.per(f.rep.diff(m=1)) + + rep = f.rep + + for spec in specs: + if isinstance(spec, tuple): + gen, m = spec + else: + gen, m = spec, 1 + + rep = rep.diff(int(m), f._gen_to_level(gen)) + + return f.per(rep) + else: # pragma: no cover + raise OperationNotSupported(f, 'diff') + + _eval_derivative = diff + + def eval(self, x, a=None, auto=True): + """ + Evaluate ``f`` at ``a`` in the given variable. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y, z + + >>> Poly(x**2 + 2*x + 3, x).eval(2) + 11 + + >>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2) + Poly(5*y + 8, y, domain='ZZ') + + >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) + + >>> f.eval({x: 2}) + Poly(5*y + 2*z + 6, y, z, domain='ZZ') + >>> f.eval({x: 2, y: 5}) + Poly(2*z + 31, z, domain='ZZ') + >>> f.eval({x: 2, y: 5, z: 7}) + 45 + + >>> f.eval((2, 5)) + Poly(2*z + 31, z, domain='ZZ') + >>> f(2, 5) + Poly(2*z + 31, z, domain='ZZ') + + """ + f = self + + if a is None: + if isinstance(x, dict): + mapping = x + + for gen, value in mapping.items(): + f = f.eval(gen, value) + + return f + elif isinstance(x, (tuple, list)): + values = x + + if len(values) > len(f.gens): + raise ValueError("too many values provided") + + for gen, value in zip(f.gens, values): + f = f.eval(gen, value) + + return f + else: + j, a = 0, x + else: + j = f._gen_to_level(x) + + if not hasattr(f.rep, 'eval'): # pragma: no cover + raise OperationNotSupported(f, 'eval') + + try: + result = f.rep.eval(a, j) + except CoercionFailed: + if not auto: + raise DomainError("Cannot evaluate at %s in %s" % (a, f.rep.dom)) + else: + a_domain, [a] = construct_domain([a]) + new_domain = f.get_domain().unify_with_symbols(a_domain, f.gens) + + f = f.set_domain(new_domain) + a = new_domain.convert(a, a_domain) + + result = f.rep.eval(a, j) + + return f.per(result, remove=j) + + def __call__(f, *values): + """ + Evaluate ``f`` at the give values. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y, z + + >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) + + >>> f(2) + Poly(5*y + 2*z + 6, y, z, domain='ZZ') + >>> f(2, 5) + Poly(2*z + 31, z, domain='ZZ') + >>> f(2, 5, 7) + 45 + + """ + return f.eval(values) + + def half_gcdex(f, g, auto=True): + """ + Half extended Euclidean algorithm of ``f`` and ``g``. + + Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 + >>> g = x**3 + x**2 - 4*x - 4 + + >>> Poly(f).half_gcdex(Poly(g)) + (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) + + """ + dom, per, F, G = f._unify(g) + + if auto and dom.is_Ring: + F, G = F.to_field(), G.to_field() + + if hasattr(f.rep, 'half_gcdex'): + s, h = F.half_gcdex(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'half_gcdex') + + return per(s), per(h) + + def gcdex(f, g, auto=True): + """ + Extended Euclidean algorithm of ``f`` and ``g``. + + Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 + >>> g = x**3 + x**2 - 4*x - 4 + + >>> Poly(f).gcdex(Poly(g)) + (Poly(-1/5*x + 3/5, x, domain='QQ'), + Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'), + Poly(x + 1, x, domain='QQ')) + + """ + dom, per, F, G = f._unify(g) + + if auto and dom.is_Ring: + F, G = F.to_field(), G.to_field() + + if hasattr(f.rep, 'gcdex'): + s, t, h = F.gcdex(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'gcdex') + + return per(s), per(t), per(h) + + def invert(f, g, auto=True): + """ + Invert ``f`` modulo ``g`` when possible. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x)) + Poly(-4/3, x, domain='QQ') + + >>> Poly(x**2 - 1, x).invert(Poly(x - 1, x)) + Traceback (most recent call last): + ... + NotInvertible: zero divisor + + """ + dom, per, F, G = f._unify(g) + + if auto and dom.is_Ring: + F, G = F.to_field(), G.to_field() + + if hasattr(f.rep, 'invert'): + result = F.invert(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'invert') + + return per(result) + + def revert(f, n): + """ + Compute ``f**(-1)`` mod ``x**n``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(1, x).revert(2) + Poly(1, x, domain='ZZ') + + >>> Poly(1 + x, x).revert(1) + Poly(1, x, domain='ZZ') + + >>> Poly(x**2 - 2, x).revert(2) + Traceback (most recent call last): + ... + NotReversible: only units are reversible in a ring + + >>> Poly(1/x, x).revert(1) + Traceback (most recent call last): + ... + PolynomialError: 1/x contains an element of the generators set + + """ + if hasattr(f.rep, 'revert'): + result = f.rep.revert(int(n)) + else: # pragma: no cover + raise OperationNotSupported(f, 'revert') + + return f.per(result) + + def subresultants(f, g): + """ + Computes the subresultant PRS of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x)) + [Poly(x**2 + 1, x, domain='ZZ'), + Poly(x**2 - 1, x, domain='ZZ'), + Poly(-2, x, domain='ZZ')] + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'subresultants'): + result = F.subresultants(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'subresultants') + + return list(map(per, result)) + + def resultant(f, g, includePRS=False): + """ + Computes the resultant of ``f`` and ``g`` via PRS. + + If includePRS=True, it includes the subresultant PRS in the result. + Because the PRS is used to calculate the resultant, this is more + efficient than calling :func:`subresultants` separately. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = Poly(x**2 + 1, x) + + >>> f.resultant(Poly(x**2 - 1, x)) + 4 + >>> f.resultant(Poly(x**2 - 1, x), includePRS=True) + (4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), + Poly(-2, x, domain='ZZ')]) + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'resultant'): + if includePRS: + result, R = F.resultant(G, includePRS=includePRS) + else: + result = F.resultant(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'resultant') + + if includePRS: + return (per(result, remove=0), list(map(per, R))) + return per(result, remove=0) + + def discriminant(f): + """ + Computes the discriminant of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + 2*x + 3, x).discriminant() + -8 + + """ + if hasattr(f.rep, 'discriminant'): + result = f.rep.discriminant() + else: # pragma: no cover + raise OperationNotSupported(f, 'discriminant') + + return f.per(result, remove=0) + + def dispersionset(f, g=None): + r"""Compute the *dispersion set* of two polynomials. + + For two polynomials `f(x)` and `g(x)` with `\deg f > 0` + and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as: + + .. math:: + \operatorname{J}(f, g) + & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\ + & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\} + + For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`. + + Examples + ======== + + >>> from sympy import poly + >>> from sympy.polys.dispersion import dispersion, dispersionset + >>> from sympy.abc import x + + Dispersion set and dispersion of a simple polynomial: + + >>> fp = poly((x - 3)*(x + 3), x) + >>> sorted(dispersionset(fp)) + [0, 6] + >>> dispersion(fp) + 6 + + Note that the definition of the dispersion is not symmetric: + + >>> fp = poly(x**4 - 3*x**2 + 1, x) + >>> gp = fp.shift(-3) + >>> sorted(dispersionset(fp, gp)) + [2, 3, 4] + >>> dispersion(fp, gp) + 4 + >>> sorted(dispersionset(gp, fp)) + [] + >>> dispersion(gp, fp) + -oo + + Computing the dispersion also works over field extensions: + + >>> from sympy import sqrt + >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ') + >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ') + >>> sorted(dispersionset(fp, gp)) + [2] + >>> sorted(dispersionset(gp, fp)) + [1, 4] + + We can even perform the computations for polynomials + having symbolic coefficients: + + >>> from sympy.abc import a + >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) + >>> sorted(dispersionset(fp)) + [0, 1] + + See Also + ======== + + dispersion + + References + ========== + + 1. [ManWright94]_ + 2. [Koepf98]_ + 3. [Abramov71]_ + 4. [Man93]_ + """ + from sympy.polys.dispersion import dispersionset + return dispersionset(f, g) + + def dispersion(f, g=None): + r"""Compute the *dispersion* of polynomials. + + For two polynomials `f(x)` and `g(x)` with `\deg f > 0` + and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as: + + .. math:: + \operatorname{dis}(f, g) + & := \max\{ J(f,g) \cup \{0\} \} \\ + & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \} + + and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`. + + Examples + ======== + + >>> from sympy import poly + >>> from sympy.polys.dispersion import dispersion, dispersionset + >>> from sympy.abc import x + + Dispersion set and dispersion of a simple polynomial: + + >>> fp = poly((x - 3)*(x + 3), x) + >>> sorted(dispersionset(fp)) + [0, 6] + >>> dispersion(fp) + 6 + + Note that the definition of the dispersion is not symmetric: + + >>> fp = poly(x**4 - 3*x**2 + 1, x) + >>> gp = fp.shift(-3) + >>> sorted(dispersionset(fp, gp)) + [2, 3, 4] + >>> dispersion(fp, gp) + 4 + >>> sorted(dispersionset(gp, fp)) + [] + >>> dispersion(gp, fp) + -oo + + Computing the dispersion also works over field extensions: + + >>> from sympy import sqrt + >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ') + >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ') + >>> sorted(dispersionset(fp, gp)) + [2] + >>> sorted(dispersionset(gp, fp)) + [1, 4] + + We can even perform the computations for polynomials + having symbolic coefficients: + + >>> from sympy.abc import a + >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) + >>> sorted(dispersionset(fp)) + [0, 1] + + See Also + ======== + + dispersionset + + References + ========== + + 1. [ManWright94]_ + 2. [Koepf98]_ + 3. [Abramov71]_ + 4. [Man93]_ + """ + from sympy.polys.dispersion import dispersion + return dispersion(f, g) + + def cofactors(f, g): + """ + Returns the GCD of ``f`` and ``g`` and their cofactors. + + Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and + ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors + of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x)) + (Poly(x - 1, x, domain='ZZ'), + Poly(x + 1, x, domain='ZZ'), + Poly(x - 2, x, domain='ZZ')) + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'cofactors'): + h, cff, cfg = F.cofactors(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'cofactors') + + return per(h), per(cff), per(cfg) + + def gcd(f, g): + """ + Returns the polynomial GCD of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x)) + Poly(x - 1, x, domain='ZZ') + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'gcd'): + result = F.gcd(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'gcd') + + return per(result) + + def lcm(f, g): + """ + Returns polynomial LCM of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x)) + Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ') + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'lcm'): + result = F.lcm(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'lcm') + + return per(result) + + def trunc(f, p): + """ + Reduce ``f`` modulo a constant ``p``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3) + Poly(-x**3 - x + 1, x, domain='ZZ') + + """ + p = f.rep.dom.convert(p) + + if hasattr(f.rep, 'trunc'): + result = f.rep.trunc(p) + else: # pragma: no cover + raise OperationNotSupported(f, 'trunc') + + return f.per(result) + + def monic(self, auto=True): + """ + Divides all coefficients by ``LC(f)``. + + Examples + ======== + + >>> from sympy import Poly, ZZ + >>> from sympy.abc import x + + >>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic() + Poly(x**2 + 2*x + 3, x, domain='QQ') + + >>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic() + Poly(x**2 + 4/3*x + 2/3, x, domain='QQ') + + """ + f = self + + if auto and f.rep.dom.is_Ring: + f = f.to_field() + + if hasattr(f.rep, 'monic'): + result = f.rep.monic() + else: # pragma: no cover + raise OperationNotSupported(f, 'monic') + + return f.per(result) + + def content(f): + """ + Returns the GCD of polynomial coefficients. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(6*x**2 + 8*x + 12, x).content() + 2 + + """ + if hasattr(f.rep, 'content'): + result = f.rep.content() + else: # pragma: no cover + raise OperationNotSupported(f, 'content') + + return f.rep.dom.to_sympy(result) + + def primitive(f): + """ + Returns the content and a primitive form of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x**2 + 8*x + 12, x).primitive() + (2, Poly(x**2 + 4*x + 6, x, domain='ZZ')) + + """ + if hasattr(f.rep, 'primitive'): + cont, result = f.rep.primitive() + else: # pragma: no cover + raise OperationNotSupported(f, 'primitive') + + return f.rep.dom.to_sympy(cont), f.per(result) + + def compose(f, g): + """ + Computes the functional composition of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + x, x).compose(Poly(x - 1, x)) + Poly(x**2 - x, x, domain='ZZ') + + """ + _, per, F, G = f._unify(g) + + if hasattr(f.rep, 'compose'): + result = F.compose(G) + else: # pragma: no cover + raise OperationNotSupported(f, 'compose') + + return per(result) + + def decompose(f): + """ + Computes a functional decomposition of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose() + [Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')] + + """ + if hasattr(f.rep, 'decompose'): + result = f.rep.decompose() + else: # pragma: no cover + raise OperationNotSupported(f, 'decompose') + + return list(map(f.per, result)) + + def shift(f, a): + """ + Efficiently compute Taylor shift ``f(x + a)``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 2*x + 1, x).shift(2) + Poly(x**2 + 2*x + 1, x, domain='ZZ') + + See Also + ======== + + shift_list: Analogous method for multivariate polynomials. + """ + return f.per(f.rep.shift(a)) + + def shift_list(f, a): + """ + Efficiently compute Taylor shift ``f(X + A)``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x*y, [x,y]).shift_list([1, 2]) == Poly((x+1)*(y+2), [x,y]) + True + + See Also + ======== + + shift: Analogous method for univariate polynomials. + """ + return f.per(f.rep.shift_list(a)) + + def transform(f, p, q): + """ + Efficiently evaluate the functional transformation ``q**n * f(p/q)``. + + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1, x), Poly(x - 1, x)) + Poly(4, x, domain='ZZ') + + """ + P, Q = p.unify(q) + F, P = f.unify(P) + F, Q = F.unify(Q) + + if hasattr(F.rep, 'transform'): + result = F.rep.transform(P.rep, Q.rep) + else: # pragma: no cover + raise OperationNotSupported(F, 'transform') + + return F.per(result) + + def sturm(self, auto=True): + """ + Computes the Sturm sequence of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 - 2*x**2 + x - 3, x).sturm() + [Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'), + Poly(3*x**2 - 4*x + 1, x, domain='QQ'), + Poly(2/9*x + 25/9, x, domain='QQ'), + Poly(-2079/4, x, domain='QQ')] + + """ + f = self + + if auto and f.rep.dom.is_Ring: + f = f.to_field() + + if hasattr(f.rep, 'sturm'): + result = f.rep.sturm() + else: # pragma: no cover + raise OperationNotSupported(f, 'sturm') + + return list(map(f.per, result)) + + def gff_list(f): + """ + Computes greatest factorial factorization of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 + + >>> Poly(f).gff_list() + [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] + + """ + if hasattr(f.rep, 'gff_list'): + result = f.rep.gff_list() + else: # pragma: no cover + raise OperationNotSupported(f, 'gff_list') + + return [(f.per(g), k) for g, k in result] + + def norm(f): + """ + Computes the product, ``Norm(f)``, of the conjugates of + a polynomial ``f`` defined over a number field ``K``. + + Examples + ======== + + >>> from sympy import Poly, sqrt + >>> from sympy.abc import x + + >>> a, b = sqrt(2), sqrt(3) + + A polynomial over a quadratic extension. + Two conjugates x - a and x + a. + + >>> f = Poly(x - a, x, extension=a) + >>> f.norm() + Poly(x**2 - 2, x, domain='QQ') + + A polynomial over a quartic extension. + Four conjugates x - a, x - a, x + a and x + a. + + >>> f = Poly(x - a, x, extension=(a, b)) + >>> f.norm() + Poly(x**4 - 4*x**2 + 4, x, domain='QQ') + + """ + if hasattr(f.rep, 'norm'): + r = f.rep.norm() + else: # pragma: no cover + raise OperationNotSupported(f, 'norm') + + return f.per(r) + + def sqf_norm(f): + """ + Computes square-free norm of ``f``. + + Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and + ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, + where ``a`` is the algebraic extension of the ground domain. + + Examples + ======== + + >>> from sympy import Poly, sqrt + >>> from sympy.abc import x + + >>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm() + + >>> s + [1] + >>> f + Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ') + >>> r + Poly(x**4 - 4*x**2 + 16, x, domain='QQ') + + """ + if hasattr(f.rep, 'sqf_norm'): + s, g, r = f.rep.sqf_norm() + else: # pragma: no cover + raise OperationNotSupported(f, 'sqf_norm') + + return s, f.per(g), f.per(r) + + def sqf_part(f): + """ + Computes square-free part of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**3 - 3*x - 2, x).sqf_part() + Poly(x**2 - x - 2, x, domain='ZZ') + + """ + if hasattr(f.rep, 'sqf_part'): + result = f.rep.sqf_part() + else: # pragma: no cover + raise OperationNotSupported(f, 'sqf_part') + + return f.per(result) + + def sqf_list(f, all=False): + """ + Returns a list of square-free factors of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 + + >>> Poly(f).sqf_list() + (2, [(Poly(x + 1, x, domain='ZZ'), 2), + (Poly(x + 2, x, domain='ZZ'), 3)]) + + >>> Poly(f).sqf_list(all=True) + (2, [(Poly(1, x, domain='ZZ'), 1), + (Poly(x + 1, x, domain='ZZ'), 2), + (Poly(x + 2, x, domain='ZZ'), 3)]) + + """ + if hasattr(f.rep, 'sqf_list'): + coeff, factors = f.rep.sqf_list(all) + else: # pragma: no cover + raise OperationNotSupported(f, 'sqf_list') + + return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] + + def sqf_list_include(f, all=False): + """ + Returns a list of square-free factors of ``f``. + + Examples + ======== + + >>> from sympy import Poly, expand + >>> from sympy.abc import x + + >>> f = expand(2*(x + 1)**3*x**4) + >>> f + 2*x**7 + 6*x**6 + 6*x**5 + 2*x**4 + + >>> Poly(f).sqf_list_include() + [(Poly(2, x, domain='ZZ'), 1), + (Poly(x + 1, x, domain='ZZ'), 3), + (Poly(x, x, domain='ZZ'), 4)] + + >>> Poly(f).sqf_list_include(all=True) + [(Poly(2, x, domain='ZZ'), 1), + (Poly(1, x, domain='ZZ'), 2), + (Poly(x + 1, x, domain='ZZ'), 3), + (Poly(x, x, domain='ZZ'), 4)] + + """ + if hasattr(f.rep, 'sqf_list_include'): + factors = f.rep.sqf_list_include(all) + else: # pragma: no cover + raise OperationNotSupported(f, 'sqf_list_include') + + return [(f.per(g), k) for g, k in factors] + + def factor_list(f) -> tuple[Expr, list[tuple[Poly, int]]]: + """ + Returns a list of irreducible factors of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y + + >>> Poly(f).factor_list() + (2, [(Poly(x + y, x, y, domain='ZZ'), 1), + (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]) + + """ + if hasattr(f.rep, 'factor_list'): + try: + coeff, factors = f.rep.factor_list() + except DomainError: + if f.degree() == 0: + return f.as_expr(), [] + else: + return S.One, [(f, 1)] + else: # pragma: no cover + raise OperationNotSupported(f, 'factor_list') + + return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] + + def factor_list_include(f): + """ + Returns a list of irreducible factors of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y + + >>> Poly(f).factor_list_include() + [(Poly(2*x + 2*y, x, y, domain='ZZ'), 1), + (Poly(x**2 + 1, x, y, domain='ZZ'), 2)] + + """ + if hasattr(f.rep, 'factor_list_include'): + try: + factors = f.rep.factor_list_include() + except DomainError: + return [(f, 1)] + else: # pragma: no cover + raise OperationNotSupported(f, 'factor_list_include') + + return [(f.per(g), k) for g, k in factors] + + def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): + """ + Compute isolating intervals for roots of ``f``. + + For real roots the Vincent-Akritas-Strzebonski (VAS) continued fractions method is used. + + References + ========== + .. [#] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root + Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. + .. [#] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the + Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear + Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 3, x).intervals() + [((-2, -1), 1), ((1, 2), 1)] + >>> Poly(x**2 - 3, x).intervals(eps=1e-2) + [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] + + """ + if eps is not None: + eps = QQ.convert(eps) + + if eps <= 0: + raise ValueError("'eps' must be a positive rational") + + if inf is not None: + inf = QQ.convert(inf) + if sup is not None: + sup = QQ.convert(sup) + + if hasattr(f.rep, 'intervals'): + result = f.rep.intervals( + all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) + else: # pragma: no cover + raise OperationNotSupported(f, 'intervals') + + if sqf: + def _real(interval): + s, t = interval + return (QQ.to_sympy(s), QQ.to_sympy(t)) + + if not all: + return list(map(_real, result)) + + def _complex(rectangle): + (u, v), (s, t) = rectangle + return (QQ.to_sympy(u) + I*QQ.to_sympy(v), + QQ.to_sympy(s) + I*QQ.to_sympy(t)) + + real_part, complex_part = result + + return list(map(_real, real_part)), list(map(_complex, complex_part)) + else: + def _real(interval): + (s, t), k = interval + return ((QQ.to_sympy(s), QQ.to_sympy(t)), k) + + if not all: + return list(map(_real, result)) + + def _complex(rectangle): + ((u, v), (s, t)), k = rectangle + return ((QQ.to_sympy(u) + I*QQ.to_sympy(v), + QQ.to_sympy(s) + I*QQ.to_sympy(t)), k) + + real_part, complex_part = result + + return list(map(_real, real_part)), list(map(_complex, complex_part)) + + def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): + """ + Refine an isolating interval of a root to the given precision. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2) + (19/11, 26/15) + + """ + if check_sqf and not f.is_sqf: + raise PolynomialError("only square-free polynomials supported") + + s, t = QQ.convert(s), QQ.convert(t) + + if eps is not None: + eps = QQ.convert(eps) + + if eps <= 0: + raise ValueError("'eps' must be a positive rational") + + if steps is not None: + steps = int(steps) + elif eps is None: + steps = 1 + + if hasattr(f.rep, 'refine_root'): + S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast) + else: # pragma: no cover + raise OperationNotSupported(f, 'refine_root') + + return QQ.to_sympy(S), QQ.to_sympy(T) + + def count_roots(f, inf=None, sup=None): + """ + Return the number of roots of ``f`` in ``[inf, sup]`` interval. + + Examples + ======== + + >>> from sympy import Poly, I + >>> from sympy.abc import x + + >>> Poly(x**4 - 4, x).count_roots(-3, 3) + 2 + >>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I) + 1 + + """ + inf_real, sup_real = True, True + + if inf is not None: + inf = sympify(inf) + + if inf is S.NegativeInfinity: + inf = None + else: + re, im = inf.as_real_imag() + + if not im: + inf = QQ.convert(inf) + else: + inf, inf_real = list(map(QQ.convert, (re, im))), False + + if sup is not None: + sup = sympify(sup) + + if sup is S.Infinity: + sup = None + else: + re, im = sup.as_real_imag() + + if not im: + sup = QQ.convert(sup) + else: + sup, sup_real = list(map(QQ.convert, (re, im))), False + + if inf_real and sup_real: + if hasattr(f.rep, 'count_real_roots'): + count = f.rep.count_real_roots(inf=inf, sup=sup) + else: # pragma: no cover + raise OperationNotSupported(f, 'count_real_roots') + else: + if inf_real and inf is not None: + inf = (inf, QQ.zero) + + if sup_real and sup is not None: + sup = (sup, QQ.zero) + + if hasattr(f.rep, 'count_complex_roots'): + count = f.rep.count_complex_roots(inf=inf, sup=sup) + else: # pragma: no cover + raise OperationNotSupported(f, 'count_complex_roots') + + return Integer(count) + + def root(f, index, radicals=True): + """ + Get an indexed root of a polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4) + + >>> f.root(0) + -1/2 + >>> f.root(1) + 2 + >>> f.root(2) + 2 + >>> f.root(3) + Traceback (most recent call last): + ... + IndexError: root index out of [-3, 2] range, got 3 + + >>> Poly(x**5 + x + 1).root(0) + CRootOf(x**3 - x**2 + 1, 0) + + """ + return sympy.polys.rootoftools.rootof(f, index, radicals=radicals) + + def real_roots(f, multiple=True, radicals=True): + """ + Return a list of real roots with multiplicities. + + See :func:`real_roots` for more explanation. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots() + [-1/2, 2, 2] + >>> Poly(x**3 + x + 1).real_roots() + [CRootOf(x**3 + x + 1, 0)] + """ + reals = sympy.polys.rootoftools.CRootOf.real_roots(f, radicals=radicals) + + if multiple: + return reals + else: + return group(reals, multiple=False) + + def all_roots(f, multiple=True, radicals=True): + """ + Return a list of real and complex roots with multiplicities. + + See :func:`all_roots` for more explanation. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots() + [-1/2, 2, 2] + >>> Poly(x**3 + x + 1).all_roots() + [CRootOf(x**3 + x + 1, 0), + CRootOf(x**3 + x + 1, 1), + CRootOf(x**3 + x + 1, 2)] + + """ + roots = sympy.polys.rootoftools.CRootOf.all_roots(f, radicals=radicals) + + if multiple: + return roots + else: + return group(roots, multiple=False) + + def nroots(f, n=15, maxsteps=50, cleanup=True): + """ + Compute numerical approximations of roots of ``f``. + + Parameters + ========== + + n ... the number of digits to calculate + maxsteps ... the maximum number of iterations to do + + If the accuracy `n` cannot be reached in `maxsteps`, it will raise an + exception. You need to rerun with higher maxsteps. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 3).nroots(n=15) + [-1.73205080756888, 1.73205080756888] + >>> Poly(x**2 - 3).nroots(n=30) + [-1.73205080756887729352744634151, 1.73205080756887729352744634151] + + """ + if f.is_multivariate: + raise MultivariatePolynomialError( + "Cannot compute numerical roots of %s" % f) + + if f.degree() <= 0: + return [] + + # For integer and rational coefficients, convert them to integers only + # (for accuracy). Otherwise just try to convert the coefficients to + # mpmath.mpc and raise an exception if the conversion fails. + if f.rep.dom is ZZ: + coeffs = [int(coeff) for coeff in f.all_coeffs()] + elif f.rep.dom is QQ: + denoms = [coeff.q for coeff in f.all_coeffs()] + fac = ilcm(*denoms) + coeffs = [int(coeff*fac) for coeff in f.all_coeffs()] + else: + coeffs = [coeff.evalf(n=n).as_real_imag() + for coeff in f.all_coeffs()] + with mpmath.workdps(n): + try: + coeffs = [mpmath.mpc(*coeff) for coeff in coeffs] + except TypeError: + raise DomainError("Numerical domain expected, got %s" % \ + f.rep.dom) + + dps = mpmath.mp.dps + mpmath.mp.dps = n + + from sympy.functions.elementary.complexes import sign + try: + # We need to add extra precision to guard against losing accuracy. + # 10 times the degree of the polynomial seems to work well. + roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, + cleanup=cleanup, error=False, extraprec=f.degree()*10) + + # Mpmath puts real roots first, then complex ones (as does all_roots) + # so we make sure this convention holds here, too. + roots = list(map(sympify, + sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) + except NoConvergence: + try: + # If roots did not converge try again with more extra precision. + roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, + cleanup=cleanup, error=False, extraprec=f.degree()*15) + roots = list(map(sympify, + sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) + except NoConvergence: + raise NoConvergence( + 'convergence to root failed; try n < %s or maxsteps > %s' % ( + n, maxsteps)) + finally: + mpmath.mp.dps = dps + + return roots + + def ground_roots(f): + """ + Compute roots of ``f`` by factorization in the ground domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots() + {0: 2, 1: 2} + + """ + if f.is_multivariate: + raise MultivariatePolynomialError( + "Cannot compute ground roots of %s" % f) + + roots = {} + + for factor, k in f.factor_list()[1]: + if factor.is_linear: + a, b = factor.all_coeffs() + roots[-b/a] = k + + return roots + + def nth_power_roots_poly(f, n): + """ + Construct a polynomial with n-th powers of roots of ``f``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = Poly(x**4 - x**2 + 1) + + >>> f.nth_power_roots_poly(2) + Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ') + >>> f.nth_power_roots_poly(3) + Poly(x**4 + 2*x**2 + 1, x, domain='ZZ') + >>> f.nth_power_roots_poly(4) + Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ') + >>> f.nth_power_roots_poly(12) + Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ') + + """ + if f.is_multivariate: + raise MultivariatePolynomialError( + "must be a univariate polynomial") + + N = sympify(n) + + if N.is_Integer and N >= 1: + n = int(N) + else: + raise ValueError("'n' must an integer and n >= 1, got %s" % n) + + x = f.gen + t = Dummy('t') + + r = f.resultant(f.__class__.from_expr(x**n - t, x, t)) + + return r.replace(t, x) + + def which_real_roots(f, candidates): + """ + Find roots of a square-free polynomial ``f`` from ``candidates``. + + Explanation + =========== + + If ``f`` is a square-free polynomial and ``candidates`` is a superset + of the roots of ``f``, then ``f.which_real_roots(candidates)`` returns a + list containing exactly the set of roots of ``f``. The domain must be + :ref:`ZZ`, :ref:`QQ`, or :ref:`QQ(a)` and``f`` must be univariate and + square-free. + + The list ``candidates`` must be a superset of the real roots of ``f`` + and ``f.which_real_roots(candidates)`` returns the set of real roots + of ``f``. The output preserves the order of the order of ``candidates``. + + Examples + ======== + + >>> from sympy import Poly, sqrt + >>> from sympy.abc import x + + >>> f = Poly(x**4 - 1) + >>> f.which_real_roots([-1, 1, 0, -2, 2]) + [-1, 1] + >>> f.which_real_roots([-1, 1, 1, 1, 1]) + [-1, 1] + + This method is useful as lifting to rational coefficients + produced extraneous roots, which we can filter out with + this method. + + >>> f = Poly(sqrt(2)*x**3 + x**2 - 1, x, extension=True) + >>> f.lift() + Poly(-2*x**6 + x**4 - 2*x**2 + 1, x, domain='QQ') + >>> f.lift().real_roots() + [-sqrt(2)/2, sqrt(2)/2] + >>> f.which_real_roots(f.lift().real_roots()) + [sqrt(2)/2] + + This procedure is already done internally when calling + `.real_roots()` on a polynomial with algebraic coefficients. + + >>> f.real_roots() + [sqrt(2)/2] + + See Also + ======== + + same_root + which_all_roots + """ + if f.is_multivariate: + raise MultivariatePolynomialError( + "Must be a univariate polynomial") + + dom = f.get_domain() + + if not (dom.is_ZZ or dom.is_QQ or dom.is_AlgebraicField): + raise NotImplementedError( + "root counting not supported over %s" % dom) + + return f._which_roots(candidates, f.count_roots()) + + def which_all_roots(f, candidates): + """ + Find roots of a square-free polynomial ``f`` from ``candidates``. + + Explanation + =========== + + If ``f`` is a square-free polynomial and ``candidates`` is a superset + of the roots of ``f``, then ``f.which_all_roots(candidates)`` returns a + list containing exactly the set of roots of ``f``. The polynomial``f`` + must be univariate and square-free. + + The list ``candidates`` must be a superset of the complex roots of + ``f`` and ``f.which_all_roots(candidates)`` returns exactly the + set of all complex roots of ``f``. The output preserves the order of + the order of ``candidates``. + + Examples + ======== + + >>> from sympy import Poly, I + >>> from sympy.abc import x + + >>> f = Poly(x**4 - 1) + >>> f.which_all_roots([-1, 1, -I, I, 0]) + [-1, 1, -I, I] + >>> f.which_all_roots([-1, 1, -I, I, I, I]) + [-1, 1, -I, I] + + This method is useful as lifting to rational coefficients + produced extraneous roots, which we can filter out with + this method. + + >>> f = Poly(x**2 + I*x - 1, x, extension=True) + >>> f.lift() + Poly(x**4 - x**2 + 1, x, domain='ZZ') + >>> f.lift().all_roots() + [CRootOf(x**4 - x**2 + 1, 0), + CRootOf(x**4 - x**2 + 1, 1), + CRootOf(x**4 - x**2 + 1, 2), + CRootOf(x**4 - x**2 + 1, 3)] + >>> f.which_all_roots(f.lift().all_roots()) + [CRootOf(x**4 - x**2 + 1, 0), CRootOf(x**4 - x**2 + 1, 2)] + + This procedure is already done internally when calling + `.all_roots()` on a polynomial with algebraic coefficients, + or polynomials with Gaussian domains. + + >>> f.all_roots() + [CRootOf(x**4 - x**2 + 1, 0), CRootOf(x**4 - x**2 + 1, 2)] + + See Also + ======== + + same_root + which_real_roots + """ + if f.is_multivariate: + raise MultivariatePolynomialError( + "Must be a univariate polynomial") + + return f._which_roots(candidates, f.degree()) + + def _which_roots(f, candidates, num_roots): + prec = 10 + # using Counter bc its like an ordered set + root_counts = Counter(candidates) + + while len(root_counts) > num_roots: + for r in list(root_counts.keys()): + # If f(r) != 0 then f(r).evalf() gives a float/complex with precision. + f_r = f(r).evalf(prec, maxn=2*prec) + if abs(f_r)._prec >= 2: + root_counts.pop(r) + + prec *= 2 + + return list(root_counts.keys()) + + def same_root(f, a, b): + """ + Decide whether two roots of this polynomial are equal. + + Examples + ======== + + >>> from sympy import Poly, cyclotomic_poly, exp, I, pi + >>> f = Poly(cyclotomic_poly(5)) + >>> r0 = exp(2*I*pi/5) + >>> indices = [i for i, r in enumerate(f.all_roots()) if f.same_root(r, r0)] + >>> print(indices) + [3] + + Raises + ====== + + DomainError + If the domain of the polynomial is not :ref:`ZZ`, :ref:`QQ`, + :ref:`RR`, or :ref:`CC`. + MultivariatePolynomialError + If the polynomial is not univariate. + PolynomialError + If the polynomial is of degree < 2. + + See Also + ======== + + which_real_roots + which_all_roots + """ + if f.is_multivariate: + raise MultivariatePolynomialError( + "Must be a univariate polynomial") + + dom_delta_sq = f.rep.mignotte_sep_bound_squared() + delta_sq = f.domain.get_field().to_sympy(dom_delta_sq) + # We have delta_sq = delta**2, where delta is a lower bound on the + # minimum separation between any two roots of this polynomial. + # Let eps = delta/3, and define eps_sq = eps**2 = delta**2/9. + eps_sq = delta_sq / 9 + + r, _, _, _ = evalf(1/eps_sq, 1, {}) + n = fastlog(r) + # Then 2^n > 1/eps**2. + m = (n // 2) + (n % 2) + # Then 2^(-m) < eps. + ev = lambda x: quad_to_mpmath(_evalf_with_bounded_error(x, m=m)) + + # Then for any complex numbers a, b we will have + # |a - ev(a)| < eps and |b - ev(b)| < eps. + # So if |ev(a) - ev(b)|**2 < eps**2, then + # |ev(a) - ev(b)| < eps, hence |a - b| < 3*eps = delta. + A, B = ev(a), ev(b) + return (A.real - B.real)**2 + (A.imag - B.imag)**2 < eps_sq + + def cancel(f, g, include=False): + """ + Cancel common factors in a rational function ``f/g``. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x)) + (1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) + + >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True) + (Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) + + """ + dom, per, F, G = f._unify(g) + + if hasattr(F, 'cancel'): + result = F.cancel(G, include=include) + else: # pragma: no cover + raise OperationNotSupported(f, 'cancel') + + if not include: + if dom.has_assoc_Ring: + dom = dom.get_ring() + + cp, cq, p, q = result + + cp = dom.to_sympy(cp) + cq = dom.to_sympy(cq) + + return cp/cq, per(p), per(q) + else: + return tuple(map(per, result)) + + def make_monic_over_integers_by_scaling_roots(f): + """ + Turn any univariate polynomial over :ref:`QQ` or :ref:`ZZ` into a monic + polynomial over :ref:`ZZ`, by scaling the roots as necessary. + + Explanation + =========== + + This operation can be performed whether or not *f* is irreducible; when + it is, this can be understood as determining an algebraic integer + generating the same field as a root of *f*. + + Examples + ======== + + >>> from sympy import Poly, S + >>> from sympy.abc import x + >>> f = Poly(x**2/2 + S(1)/4 * x + S(1)/8, x, domain='QQ') + >>> f.make_monic_over_integers_by_scaling_roots() + (Poly(x**2 + 2*x + 4, x, domain='ZZ'), 4) + + Returns + ======= + + Pair ``(g, c)`` + g is the polynomial + + c is the integer by which the roots had to be scaled + + """ + if not f.is_univariate or f.domain not in [ZZ, QQ]: + raise ValueError('Polynomial must be univariate over ZZ or QQ.') + if f.is_monic and f.domain == ZZ: + return f, ZZ.one + else: + fm = f.monic() + c, _ = fm.clear_denoms() + return fm.transform(Poly(fm.gen), c).to_ring(), c + + def galois_group(f, by_name=False, max_tries=30, randomize=False): + """ + Compute the Galois group of this polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + >>> f = Poly(x**4 - 2) + >>> G, _ = f.galois_group(by_name=True) + >>> print(G) + S4TransitiveSubgroups.D4 + + See Also + ======== + + sympy.polys.numberfields.galoisgroups.galois_group + + """ + from sympy.polys.numberfields.galoisgroups import ( + _galois_group_degree_3, _galois_group_degree_4_lookup, + _galois_group_degree_5_lookup_ext_factor, + _galois_group_degree_6_lookup, + ) + if (not f.is_univariate + or not f.is_irreducible + or f.domain not in [ZZ, QQ] + ): + raise ValueError('Polynomial must be irreducible and univariate over ZZ or QQ.') + gg = { + 3: _galois_group_degree_3, + 4: _galois_group_degree_4_lookup, + 5: _galois_group_degree_5_lookup_ext_factor, + 6: _galois_group_degree_6_lookup, + } + max_supported = max(gg.keys()) + n = f.degree() + if n > max_supported: + raise ValueError(f"Only polynomials up to degree {max_supported} are supported.") + elif n < 1: + raise ValueError("Constant polynomial has no Galois group.") + elif n == 1: + from sympy.combinatorics.galois import S1TransitiveSubgroups + name, alt = S1TransitiveSubgroups.S1, True + elif n == 2: + from sympy.combinatorics.galois import S2TransitiveSubgroups + name, alt = S2TransitiveSubgroups.S2, False + else: + g, _ = f.make_monic_over_integers_by_scaling_roots() + name, alt = gg[n](g, max_tries=max_tries, randomize=randomize) + G = name if by_name else name.get_perm_group() + return G, alt + + @property + def is_zero(f): + """ + Returns ``True`` if ``f`` is a zero polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(0, x).is_zero + True + >>> Poly(1, x).is_zero + False + + """ + return f.rep.is_zero + + @property + def is_one(f): + """ + Returns ``True`` if ``f`` is a unit polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(0, x).is_one + False + >>> Poly(1, x).is_one + True + + """ + return f.rep.is_one + + @property + def is_sqf(f): + """ + Returns ``True`` if ``f`` is a square-free polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 - 2*x + 1, x).is_sqf + False + >>> Poly(x**2 - 1, x).is_sqf + True + + """ + return f.rep.is_sqf + + @property + def is_monic(f): + """ + Returns ``True`` if the leading coefficient of ``f`` is one. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x + 2, x).is_monic + True + >>> Poly(2*x + 2, x).is_monic + False + + """ + return f.rep.is_monic + + @property + def is_primitive(f): + """ + Returns ``True`` if GCD of the coefficients of ``f`` is one. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(2*x**2 + 6*x + 12, x).is_primitive + False + >>> Poly(x**2 + 3*x + 6, x).is_primitive + True + + """ + return f.rep.is_primitive + + @property + def is_ground(f): + """ + Returns ``True`` if ``f`` is an element of the ground domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x, x).is_ground + False + >>> Poly(2, x).is_ground + True + >>> Poly(y, x).is_ground + True + + """ + return f.rep.is_ground + + @property + def is_linear(f): + """ + Returns ``True`` if ``f`` is linear in all its variables. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x + y + 2, x, y).is_linear + True + >>> Poly(x*y + 2, x, y).is_linear + False + + """ + return f.rep.is_linear + + @property + def is_quadratic(f): + """ + Returns ``True`` if ``f`` is quadratic in all its variables. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x*y + 2, x, y).is_quadratic + True + >>> Poly(x*y**2 + 2, x, y).is_quadratic + False + + """ + return f.rep.is_quadratic + + @property + def is_monomial(f): + """ + Returns ``True`` if ``f`` is zero or has only one term. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(3*x**2, x).is_monomial + True + >>> Poly(3*x**2 + 1, x).is_monomial + False + + """ + return f.rep.is_monomial + + @property + def is_homogeneous(f): + """ + Returns ``True`` if ``f`` is a homogeneous polynomial. + + A homogeneous polynomial is a polynomial whose all monomials with + non-zero coefficients have the same total degree. If you want not + only to check if a polynomial is homogeneous but also compute its + homogeneous order, then use :func:`Poly.homogeneous_order`. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + x*y, x, y).is_homogeneous + True + >>> Poly(x**3 + x*y, x, y).is_homogeneous + False + + """ + return f.rep.is_homogeneous + + @property + def is_irreducible(f): + """ + Returns ``True`` if ``f`` has no factors over its domain. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible + True + >>> Poly(x**2 + 1, x, modulus=2).is_irreducible + False + + """ + return f.rep.is_irreducible + + @property + def is_univariate(f): + """ + Returns ``True`` if ``f`` is a univariate polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + x + 1, x).is_univariate + True + >>> Poly(x*y**2 + x*y + 1, x, y).is_univariate + False + >>> Poly(x*y**2 + x*y + 1, x).is_univariate + True + >>> Poly(x**2 + x + 1, x, y).is_univariate + False + + """ + return len(f.gens) == 1 + + @property + def is_multivariate(f): + """ + Returns ``True`` if ``f`` is a multivariate polynomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x, y + + >>> Poly(x**2 + x + 1, x).is_multivariate + False + >>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate + True + >>> Poly(x*y**2 + x*y + 1, x).is_multivariate + False + >>> Poly(x**2 + x + 1, x, y).is_multivariate + True + + """ + return len(f.gens) != 1 + + @property + def is_cyclotomic(f): + """ + Returns ``True`` if ``f`` is a cyclotomic polnomial. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.abc import x + + >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 + + >>> Poly(f).is_cyclotomic + False + + >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 + + >>> Poly(g).is_cyclotomic + True + + """ + return f.rep.is_cyclotomic + + def __abs__(f): + return f.abs() + + def __neg__(f): + return f.neg() + + @_polifyit + def __add__(f, g): + return f.add(g) + + @_polifyit + def __radd__(f, g): + return g.add(f) + + @_polifyit + def __sub__(f, g): + return f.sub(g) + + @_polifyit + def __rsub__(f, g): + return g.sub(f) + + @_polifyit + def __mul__(f, g): + return f.mul(g) + + @_polifyit + def __rmul__(f, g): + return g.mul(f) + + @_sympifyit('n', NotImplemented) + def __pow__(f, n): + if n.is_Integer and n >= 0: + return f.pow(n) + else: + return NotImplemented + + @_polifyit + def __divmod__(f, g): + return f.div(g) + + @_polifyit + def __rdivmod__(f, g): + return g.div(f) + + @_polifyit + def __mod__(f, g): + return f.rem(g) + + @_polifyit + def __rmod__(f, g): + return g.rem(f) + + @_polifyit + def __floordiv__(f, g): + return f.quo(g) + + @_polifyit + def __rfloordiv__(f, g): + return g.quo(f) + + @_sympifyit('g', NotImplemented) + def __truediv__(f, g): + return f.as_expr()/g.as_expr() + + @_sympifyit('g', NotImplemented) + def __rtruediv__(f, g): + return g.as_expr()/f.as_expr() + + @_sympifyit('other', NotImplemented) + def __eq__(self, other): + f, g = self, other + + if not g.is_Poly: + try: + g = f.__class__(g, f.gens, domain=f.get_domain()) + except (PolynomialError, DomainError, CoercionFailed): + return False + + if f.gens != g.gens: + return False + + if f.rep.dom != g.rep.dom: + return False + + return f.rep == g.rep + + @_sympifyit('g', NotImplemented) + def __ne__(f, g): + return not f == g + + def __bool__(f): + return not f.is_zero + + def eq(f, g, strict=False): + if not strict: + return f == g + else: + return f._strict_eq(sympify(g)) + + def ne(f, g, strict=False): + return not f.eq(g, strict=strict) + + def _strict_eq(f, g): + return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True) + + +@public +class PurePoly(Poly): + """Class for representing pure polynomials. """ + + def _hashable_content(self): + """Allow SymPy to hash Poly instances. """ + return (self.rep,) + + def __hash__(self): + return super().__hash__() + + @property + def free_symbols(self): + """ + Free symbols of a polynomial. + + Examples + ======== + + >>> from sympy import PurePoly + >>> from sympy.abc import x, y + + >>> PurePoly(x**2 + 1).free_symbols + set() + >>> PurePoly(x**2 + y).free_symbols + set() + >>> PurePoly(x**2 + y, x).free_symbols + {y} + + """ + return self.free_symbols_in_domain + + @_sympifyit('other', NotImplemented) + def __eq__(self, other): + f, g = self, other + + if not g.is_Poly: + try: + g = f.__class__(g, f.gens, domain=f.get_domain()) + except (PolynomialError, DomainError, CoercionFailed): + return False + + if len(f.gens) != len(g.gens): + return False + + if f.rep.dom != g.rep.dom: + try: + dom = f.rep.dom.unify(g.rep.dom, f.gens) + except UnificationFailed: + return False + + f = f.set_domain(dom) + g = g.set_domain(dom) + + return f.rep == g.rep + + def _strict_eq(f, g): + return isinstance(g, f.__class__) and f.rep.eq(g.rep, strict=True) + + def _unify(f, g): + g = sympify(g) + + if not g.is_Poly: + try: + return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) + except CoercionFailed: + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + if len(f.gens) != len(g.gens): + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + if not (isinstance(f.rep, DMP) and isinstance(g.rep, DMP)): + raise UnificationFailed("Cannot unify %s with %s" % (f, g)) + + cls = f.__class__ + gens = f.gens + + dom = f.rep.dom.unify(g.rep.dom, gens) + + F = f.rep.convert(dom) + G = g.rep.convert(dom) + + def per(rep, dom=dom, gens=gens, remove=None): + if remove is not None: + gens = gens[:remove] + gens[remove + 1:] + + if not gens: + return dom.to_sympy(rep) + + return cls.new(rep, *gens) + + return dom, per, F, G + + +@public +def poly_from_expr(expr, *gens, **args): + """Construct a polynomial from an expression. """ + opt = options.build_options(gens, args) + return _poly_from_expr(expr, opt) + + +def _poly_from_expr(expr, opt): + """Construct a polynomial from an expression. """ + orig, expr = expr, sympify(expr) + + if not isinstance(expr, Basic): + raise PolificationFailed(opt, orig, expr) + elif expr.is_Poly: + poly = expr.__class__._from_poly(expr, opt) + + opt.gens = poly.gens + opt.domain = poly.domain + + if opt.polys is None: + opt.polys = True + + return poly, opt + elif opt.expand: + expr = expr.expand() + + rep, opt = _dict_from_expr(expr, opt) + if not opt.gens: + raise PolificationFailed(opt, orig, expr) + + monoms, coeffs = list(zip(*list(rep.items()))) + domain = opt.domain + + if domain is None: + opt.domain, coeffs = construct_domain(coeffs, opt=opt) + else: + coeffs = list(map(domain.from_sympy, coeffs)) + + rep = dict(list(zip(monoms, coeffs))) + poly = Poly._from_dict(rep, opt) + + if opt.polys is None: + opt.polys = False + + return poly, opt + + +@public +def parallel_poly_from_expr(exprs, *gens, **args): + """Construct polynomials from expressions. """ + opt = options.build_options(gens, args) + return _parallel_poly_from_expr(exprs, opt) + + +def _parallel_poly_from_expr(exprs, opt): + """Construct polynomials from expressions. """ + if len(exprs) == 2: + f, g = exprs + + if isinstance(f, Poly) and isinstance(g, Poly): + f = f.__class__._from_poly(f, opt) + g = g.__class__._from_poly(g, opt) + + f, g = f.unify(g) + + opt.gens = f.gens + opt.domain = f.domain + + if opt.polys is None: + opt.polys = True + + return [f, g], opt + + origs, exprs = list(exprs), [] + _exprs, _polys = [], [] + + failed = False + + for i, expr in enumerate(origs): + expr = sympify(expr) + + if isinstance(expr, Basic): + if expr.is_Poly: + _polys.append(i) + else: + _exprs.append(i) + + if opt.expand: + expr = expr.expand() + else: + failed = True + + exprs.append(expr) + + if failed: + raise PolificationFailed(opt, origs, exprs, True) + + if _polys: + # XXX: this is a temporary solution + for i in _polys: + exprs[i] = exprs[i].as_expr() + + reps, opt = _parallel_dict_from_expr(exprs, opt) + if not opt.gens: + raise PolificationFailed(opt, origs, exprs, True) + + from sympy.functions.elementary.piecewise import Piecewise + for k in opt.gens: + if isinstance(k, Piecewise): + raise PolynomialError("Piecewise generators do not make sense") + + coeffs_list, lengths = [], [] + + all_monoms = [] + all_coeffs = [] + + for rep in reps: + monoms, coeffs = list(zip(*list(rep.items()))) + + coeffs_list.extend(coeffs) + all_monoms.append(monoms) + + lengths.append(len(coeffs)) + + domain = opt.domain + + if domain is None: + opt.domain, coeffs_list = construct_domain(coeffs_list, opt=opt) + else: + coeffs_list = list(map(domain.from_sympy, coeffs_list)) + + for k in lengths: + all_coeffs.append(coeffs_list[:k]) + coeffs_list = coeffs_list[k:] + + polys = [] + + for monoms, coeffs in zip(all_monoms, all_coeffs): + rep = dict(list(zip(monoms, coeffs))) + poly = Poly._from_dict(rep, opt) + polys.append(poly) + + if opt.polys is None: + opt.polys = bool(_polys) + + return polys, opt + + +def _update_args(args, key, value): + """Add a new ``(key, value)`` pair to arguments ``dict``. """ + args = dict(args) + + if key not in args: + args[key] = value + + return args + + +@public +def degree(f, gen=0): + """ + Return the degree of ``f`` in the given variable. + + The degree of 0 is negative infinity. + + Examples + ======== + + >>> from sympy import degree + >>> from sympy.abc import x, y + + >>> degree(x**2 + y*x + 1, gen=x) + 2 + >>> degree(x**2 + y*x + 1, gen=y) + 1 + >>> degree(0, x) + -oo + + See also + ======== + + sympy.polys.polytools.Poly.total_degree + degree_list + """ + + f = sympify(f, strict=True) + gen_is_Num = sympify(gen, strict=True).is_Number + if f.is_Poly: + p = f + isNum = p.as_expr().is_Number + else: + isNum = f.is_Number + if not isNum: + if gen_is_Num: + p, _ = poly_from_expr(f) + else: + p, _ = poly_from_expr(f, gen) + + if isNum: + return S.Zero if f else S.NegativeInfinity + + if not gen_is_Num: + if f.is_Poly and gen not in p.gens: + # try recast without explicit gens + p, _ = poly_from_expr(f.as_expr()) + if gen not in p.gens: + return S.Zero + elif not f.is_Poly and len(f.free_symbols) > 1: + raise TypeError(filldedent(''' + A symbolic generator of interest is required for a multivariate + expression like func = %s, e.g. degree(func, gen = %s) instead of + degree(func, gen = %s). + ''' % (f, next(ordered(f.free_symbols)), gen))) + result = p.degree(gen) + return Integer(result) if isinstance(result, int) else S.NegativeInfinity + + +@public +def total_degree(f, *gens): + """ + Return the total_degree of ``f`` in the given variables. + + Examples + ======== + >>> from sympy import total_degree, Poly + >>> from sympy.abc import x, y + + >>> total_degree(1) + 0 + >>> total_degree(x + x*y) + 2 + >>> total_degree(x + x*y, x) + 1 + + If the expression is a Poly and no variables are given + then the generators of the Poly will be used: + + >>> p = Poly(x + x*y, y) + >>> total_degree(p) + 1 + + To deal with the underlying expression of the Poly, convert + it to an Expr: + + >>> total_degree(p.as_expr()) + 2 + + This is done automatically if any variables are given: + + >>> total_degree(p, x) + 1 + + See also + ======== + degree + """ + + p = sympify(f) + if p.is_Poly: + p = p.as_expr() + if p.is_Number: + rv = 0 + else: + if f.is_Poly: + gens = gens or f.gens + rv = Poly(p, gens).total_degree() + + return Integer(rv) + + +@public +def degree_list(f, *gens, **args): + """ + Return a list of degrees of ``f`` in all variables. + + Examples + ======== + + >>> from sympy import degree_list + >>> from sympy.abc import x, y + + >>> degree_list(x**2 + y*x + 1) + (2, 1) + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('degree_list', 1, exc) + + degrees = F.degree_list() + + return tuple(map(Integer, degrees)) + + +@public +def LC(f, *gens, **args): + """ + Return the leading coefficient of ``f``. + + Examples + ======== + + >>> from sympy import LC + >>> from sympy.abc import x, y + + >>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y) + 4 + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('LC', 1, exc) + + return F.LC(order=opt.order) + + +@public +def LM(f, *gens, **args): + """ + Return the leading monomial of ``f``. + + Examples + ======== + + >>> from sympy import LM + >>> from sympy.abc import x, y + + >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y) + x**2 + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('LM', 1, exc) + + monom = F.LM(order=opt.order) + return monom.as_expr() + + +@public +def LT(f, *gens, **args): + """ + Return the leading term of ``f``. + + Examples + ======== + + >>> from sympy import LT + >>> from sympy.abc import x, y + + >>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y) + 4*x**2 + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('LT', 1, exc) + + monom, coeff = F.LT(order=opt.order) + return coeff*monom.as_expr() + + +@public +def pdiv(f, g, *gens, **args): + """ + Compute polynomial pseudo-division of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import pdiv + >>> from sympy.abc import x + + >>> pdiv(x**2 + 1, 2*x - 4) + (2*x + 4, 20) + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('pdiv', 2, exc) + + q, r = F.pdiv(G) + + if not opt.polys: + return q.as_expr(), r.as_expr() + else: + return q, r + + +@public +def prem(f, g, *gens, **args): + """ + Compute polynomial pseudo-remainder of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import prem + >>> from sympy.abc import x + + >>> prem(x**2 + 1, 2*x - 4) + 20 + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('prem', 2, exc) + + r = F.prem(G) + + if not opt.polys: + return r.as_expr() + else: + return r + + +@public +def pquo(f, g, *gens, **args): + """ + Compute polynomial pseudo-quotient of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import pquo + >>> from sympy.abc import x + + >>> pquo(x**2 + 1, 2*x - 4) + 2*x + 4 + >>> pquo(x**2 - 1, 2*x - 1) + 2*x + 1 + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('pquo', 2, exc) + + try: + q = F.pquo(G) + except ExactQuotientFailed: + raise ExactQuotientFailed(f, g) + + if not opt.polys: + return q.as_expr() + else: + return q + + +@public +def pexquo(f, g, *gens, **args): + """ + Compute polynomial exact pseudo-quotient of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import pexquo + >>> from sympy.abc import x + + >>> pexquo(x**2 - 1, 2*x - 2) + 2*x + 2 + + >>> pexquo(x**2 + 1, 2*x - 4) + Traceback (most recent call last): + ... + ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('pexquo', 2, exc) + + q = F.pexquo(G) + + if not opt.polys: + return q.as_expr() + else: + return q + + +@public +def div(f, g, *gens, **args): + """ + Compute polynomial division of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import div, ZZ, QQ + >>> from sympy.abc import x + + >>> div(x**2 + 1, 2*x - 4, domain=ZZ) + (0, x**2 + 1) + >>> div(x**2 + 1, 2*x - 4, domain=QQ) + (x/2 + 1, 5) + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('div', 2, exc) + + q, r = F.div(G, auto=opt.auto) + + if not opt.polys: + return q.as_expr(), r.as_expr() + else: + return q, r + + +@public +def rem(f, g, *gens, **args): + """ + Compute polynomial remainder of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import rem, ZZ, QQ + >>> from sympy.abc import x + + >>> rem(x**2 + 1, 2*x - 4, domain=ZZ) + x**2 + 1 + >>> rem(x**2 + 1, 2*x - 4, domain=QQ) + 5 + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('rem', 2, exc) + + r = F.rem(G, auto=opt.auto) + + if not opt.polys: + return r.as_expr() + else: + return r + + +@public +def quo(f, g, *gens, **args): + """ + Compute polynomial quotient of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import quo + >>> from sympy.abc import x + + >>> quo(x**2 + 1, 2*x - 4) + x/2 + 1 + >>> quo(x**2 - 1, x - 1) + x + 1 + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('quo', 2, exc) + + q = F.quo(G, auto=opt.auto) + + if not opt.polys: + return q.as_expr() + else: + return q + + +@public +def exquo(f, g, *gens, **args): + """ + Compute polynomial exact quotient of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import exquo + >>> from sympy.abc import x + + >>> exquo(x**2 - 1, x - 1) + x + 1 + + >>> exquo(x**2 + 1, 2*x - 4) + Traceback (most recent call last): + ... + ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('exquo', 2, exc) + + q = F.exquo(G, auto=opt.auto) + + if not opt.polys: + return q.as_expr() + else: + return q + + +@public +def half_gcdex(f, g, *gens, **args): + """ + Half extended Euclidean algorithm of ``f`` and ``g``. + + Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. + + Examples + ======== + + >>> from sympy import half_gcdex + >>> from sympy.abc import x + + >>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) + (3/5 - x/5, x + 1) + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + domain, (a, b) = construct_domain(exc.exprs) + + try: + s, h = domain.half_gcdex(a, b) + except NotImplementedError: + raise ComputationFailed('half_gcdex', 2, exc) + else: + return domain.to_sympy(s), domain.to_sympy(h) + + s, h = F.half_gcdex(G, auto=opt.auto) + + if not opt.polys: + return s.as_expr(), h.as_expr() + else: + return s, h + + +@public +def gcdex(f, g, *gens, **args): + """ + Extended Euclidean algorithm of ``f`` and ``g``. + + Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. + + Examples + ======== + + >>> from sympy import gcdex + >>> from sympy.abc import x + + >>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) + (3/5 - x/5, x**2/5 - 6*x/5 + 2, x + 1) + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + domain, (a, b) = construct_domain(exc.exprs) + + try: + s, t, h = domain.gcdex(a, b) + except NotImplementedError: + raise ComputationFailed('gcdex', 2, exc) + else: + return domain.to_sympy(s), domain.to_sympy(t), domain.to_sympy(h) + + s, t, h = F.gcdex(G, auto=opt.auto) + + if not opt.polys: + return s.as_expr(), t.as_expr(), h.as_expr() + else: + return s, t, h + + +@public +def invert(f, g, *gens, **args): + """ + Invert ``f`` modulo ``g`` when possible. + + Examples + ======== + + >>> from sympy import invert, S, mod_inverse + >>> from sympy.abc import x + + >>> invert(x**2 - 1, 2*x - 1) + -4/3 + + >>> invert(x**2 - 1, x - 1) + Traceback (most recent call last): + ... + NotInvertible: zero divisor + + For more efficient inversion of Rationals, + use the :obj:`sympy.core.intfunc.mod_inverse` function: + + >>> mod_inverse(3, 5) + 2 + >>> (S(2)/5).invert(S(7)/3) + 5/2 + + See Also + ======== + sympy.core.intfunc.mod_inverse + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + domain, (a, b) = construct_domain(exc.exprs) + + try: + return domain.to_sympy(domain.invert(a, b)) + except NotImplementedError: + raise ComputationFailed('invert', 2, exc) + + h = F.invert(G, auto=opt.auto) + + if not opt.polys: + return h.as_expr() + else: + return h + + +@public +def subresultants(f, g, *gens, **args): + """ + Compute subresultant PRS of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import subresultants + >>> from sympy.abc import x + + >>> subresultants(x**2 + 1, x**2 - 1) + [x**2 + 1, x**2 - 1, -2] + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('subresultants', 2, exc) + + result = F.subresultants(G) + + if not opt.polys: + return [r.as_expr() for r in result] + else: + return result + + +@public +def resultant(f, g, *gens, includePRS=False, **args): + """ + Compute resultant of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import resultant + >>> from sympy.abc import x + + >>> resultant(x**2 + 1, x**2 - 1) + 4 + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('resultant', 2, exc) + + if includePRS: + result, R = F.resultant(G, includePRS=includePRS) + else: + result = F.resultant(G) + + if not opt.polys: + if includePRS: + return result.as_expr(), [r.as_expr() for r in R] + return result.as_expr() + else: + if includePRS: + return result, R + return result + + +@public +def discriminant(f, *gens, **args): + """ + Compute discriminant of ``f``. + + Examples + ======== + + >>> from sympy import discriminant + >>> from sympy.abc import x + + >>> discriminant(x**2 + 2*x + 3) + -8 + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('discriminant', 1, exc) + + result = F.discriminant() + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def cofactors(f, g, *gens, **args): + """ + Compute GCD and cofactors of ``f`` and ``g``. + + Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and + ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors + of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import cofactors + >>> from sympy.abc import x + + >>> cofactors(x**2 - 1, x**2 - 3*x + 2) + (x - 1, x + 1, x - 2) + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + domain, (a, b) = construct_domain(exc.exprs) + + try: + h, cff, cfg = domain.cofactors(a, b) + except NotImplementedError: + raise ComputationFailed('cofactors', 2, exc) + else: + return domain.to_sympy(h), domain.to_sympy(cff), domain.to_sympy(cfg) + + h, cff, cfg = F.cofactors(G) + + if not opt.polys: + return h.as_expr(), cff.as_expr(), cfg.as_expr() + else: + return h, cff, cfg + + +@public +def gcd_list(seq, *gens, **args): + """ + Compute GCD of a list of polynomials. + + Examples + ======== + + >>> from sympy import gcd_list + >>> from sympy.abc import x + + >>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) + x - 1 + + """ + seq = sympify(seq) + + def try_non_polynomial_gcd(seq): + if not gens and not args: + domain, numbers = construct_domain(seq) + + if not numbers: + return domain.zero + elif domain.is_Numerical: + result, numbers = numbers[0], numbers[1:] + + for number in numbers: + result = domain.gcd(result, number) + + if domain.is_one(result): + break + + return domain.to_sympy(result) + + return None + + result = try_non_polynomial_gcd(seq) + + if result is not None: + return result + + options.allowed_flags(args, ['polys']) + + try: + polys, opt = parallel_poly_from_expr(seq, *gens, **args) + + # gcd for domain Q[irrational] (purely algebraic irrational) + if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq): + a = seq[-1] + lst = [ (a/elt).ratsimp() for elt in seq[:-1] ] + if all(frc.is_rational for frc in lst): + lc = 1 + for frc in lst: + lc = lcm(lc, frc.as_numer_denom()[0]) + # abs ensures that the gcd is always non-negative + return abs(a/lc) + + except PolificationFailed as exc: + result = try_non_polynomial_gcd(exc.exprs) + + if result is not None: + return result + else: + raise ComputationFailed('gcd_list', len(seq), exc) + + if not polys: + if not opt.polys: + return S.Zero + else: + return Poly(0, opt=opt) + + result, polys = polys[0], polys[1:] + + for poly in polys: + result = result.gcd(poly) + + if result.is_one: + break + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def gcd(f, g=None, *gens, **args): + """ + Compute GCD of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import gcd + >>> from sympy.abc import x + + >>> gcd(x**2 - 1, x**2 - 3*x + 2) + x - 1 + + """ + if hasattr(f, '__iter__'): + if g is not None: + gens = (g,) + gens + + return gcd_list(f, *gens, **args) + elif g is None: + raise TypeError("gcd() takes 2 arguments or a sequence of arguments") + + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + + # gcd for domain Q[irrational] (purely algebraic irrational) + a, b = map(sympify, (f, g)) + if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational: + frc = (a/b).ratsimp() + if frc.is_rational: + # abs ensures that the returned gcd is always non-negative + return abs(a/frc.as_numer_denom()[0]) + + except PolificationFailed as exc: + domain, (a, b) = construct_domain(exc.exprs) + + try: + return domain.to_sympy(domain.gcd(a, b)) + except NotImplementedError: + raise ComputationFailed('gcd', 2, exc) + + result = F.gcd(G) + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def lcm_list(seq, *gens, **args): + """ + Compute LCM of a list of polynomials. + + Examples + ======== + + >>> from sympy import lcm_list + >>> from sympy.abc import x + + >>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) + x**5 - x**4 - 2*x**3 - x**2 + x + 2 + + """ + seq = sympify(seq) + + def try_non_polynomial_lcm(seq) -> Optional[Expr]: + if not gens and not args: + domain, numbers = construct_domain(seq) + + if not numbers: + return domain.to_sympy(domain.one) + elif domain.is_Numerical: + result, numbers = numbers[0], numbers[1:] + + for number in numbers: + result = domain.lcm(result, number) + + return domain.to_sympy(result) + + return None + + result = try_non_polynomial_lcm(seq) + + if result is not None: + return result + + options.allowed_flags(args, ['polys']) + + try: + polys, opt = parallel_poly_from_expr(seq, *gens, **args) + + # lcm for domain Q[irrational] (purely algebraic irrational) + if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq): + a = seq[-1] + lst = [ (a/elt).ratsimp() for elt in seq[:-1] ] + if all(frc.is_rational for frc in lst): + lc = 1 + for frc in lst: + lc = lcm(lc, frc.as_numer_denom()[1]) + return a*lc + + except PolificationFailed as exc: + result = try_non_polynomial_lcm(exc.exprs) + + if result is not None: + return result + else: + raise ComputationFailed('lcm_list', len(seq), exc) + + if not polys: + if not opt.polys: + return S.One + else: + return Poly(1, opt=opt) + + result, polys = polys[0], polys[1:] + + for poly in polys: + result = result.lcm(poly) + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def lcm(f, g=None, *gens, **args): + """ + Compute LCM of ``f`` and ``g``. + + Examples + ======== + + >>> from sympy import lcm + >>> from sympy.abc import x + + >>> lcm(x**2 - 1, x**2 - 3*x + 2) + x**3 - 2*x**2 - x + 2 + + """ + if hasattr(f, '__iter__'): + if g is not None: + gens = (g,) + gens + + return lcm_list(f, *gens, **args) + elif g is None: + raise TypeError("lcm() takes 2 arguments or a sequence of arguments") + + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + + # lcm for domain Q[irrational] (purely algebraic irrational) + a, b = map(sympify, (f, g)) + if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational: + frc = (a/b).ratsimp() + if frc.is_rational: + return a*frc.as_numer_denom()[1] + + except PolificationFailed as exc: + domain, (a, b) = construct_domain(exc.exprs) + + try: + return domain.to_sympy(domain.lcm(a, b)) + except NotImplementedError: + raise ComputationFailed('lcm', 2, exc) + + result = F.lcm(G) + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def terms_gcd(f, *gens, **args): + """ + Remove GCD of terms from ``f``. + + If the ``deep`` flag is True, then the arguments of ``f`` will have + terms_gcd applied to them. + + If a fraction is factored out of ``f`` and ``f`` is an Add, then + an unevaluated Mul will be returned so that automatic simplification + does not redistribute it. The hint ``clear``, when set to False, can be + used to prevent such factoring when all coefficients are not fractions. + + Examples + ======== + + >>> from sympy import terms_gcd, cos + >>> from sympy.abc import x, y + >>> terms_gcd(x**6*y**2 + x**3*y, x, y) + x**3*y*(x**3*y + 1) + + The default action of polys routines is to expand the expression + given to them. terms_gcd follows this behavior: + + >>> terms_gcd((3+3*x)*(x+x*y)) + 3*x*(x*y + x + y + 1) + + If this is not desired then the hint ``expand`` can be set to False. + In this case the expression will be treated as though it were comprised + of one or more terms: + + >>> terms_gcd((3+3*x)*(x+x*y), expand=False) + (3*x + 3)*(x*y + x) + + In order to traverse factors of a Mul or the arguments of other + functions, the ``deep`` hint can be used: + + >>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True) + 3*x*(x + 1)*(y + 1) + >>> terms_gcd(cos(x + x*y), deep=True) + cos(x*(y + 1)) + + Rationals are factored out by default: + + >>> terms_gcd(x + y/2) + (2*x + y)/2 + + Only the y-term had a coefficient that was a fraction; if one + does not want to factor out the 1/2 in cases like this, the + flag ``clear`` can be set to False: + + >>> terms_gcd(x + y/2, clear=False) + x + y/2 + >>> terms_gcd(x*y/2 + y**2, clear=False) + y*(x/2 + y) + + The ``clear`` flag is ignored if all coefficients are fractions: + + >>> terms_gcd(x/3 + y/2, clear=False) + (2*x + 3*y)/6 + + See Also + ======== + sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms + + """ + + orig = sympify(f) + + if isinstance(f, Equality): + return Equality(*(terms_gcd(s, *gens, **args) for s in [f.lhs, f.rhs])) + elif isinstance(f, Relational): + raise TypeError("Inequalities cannot be used with terms_gcd. Found: %s" %(f,)) + + if not isinstance(f, Expr) or f.is_Atom: + return orig + + if args.get('deep', False): + new = f.func(*[terms_gcd(a, *gens, **args) for a in f.args]) + args.pop('deep') + args['expand'] = False + return terms_gcd(new, *gens, **args) + + clear = args.pop('clear', True) + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + return exc.expr + + J, f = F.terms_gcd() + + if opt.domain.is_Ring: + if opt.domain.is_Field: + denom, f = f.clear_denoms(convert=True) + + coeff, f = f.primitive() + + if opt.domain.is_Field: + coeff /= denom + else: + coeff = S.One + + term = Mul(*[x**j for x, j in zip(f.gens, J)]) + if equal_valued(coeff, 1): + coeff = S.One + if term == 1: + return orig + + if clear: + return _keep_coeff(coeff, term*f.as_expr()) + # base the clearing on the form of the original expression, not + # the (perhaps) Mul that we have now + coeff, f = _keep_coeff(coeff, f.as_expr(), clear=False).as_coeff_Mul() + return _keep_coeff(coeff, term*f, clear=False) + + +@public +def trunc(f, p, *gens, **args): + """ + Reduce ``f`` modulo a constant ``p``. + + Examples + ======== + + >>> from sympy import trunc + >>> from sympy.abc import x + + >>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3) + -x**3 - x + 1 + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('trunc', 1, exc) + + result = F.trunc(sympify(p)) + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def monic(f, *gens, **args): + """ + Divide all coefficients of ``f`` by ``LC(f)``. + + Examples + ======== + + >>> from sympy import monic + >>> from sympy.abc import x + + >>> monic(3*x**2 + 4*x + 2) + x**2 + 4*x/3 + 2/3 + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('monic', 1, exc) + + result = F.monic(auto=opt.auto) + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def content(f, *gens, **args): + """ + Compute GCD of coefficients of ``f``. + + Examples + ======== + + >>> from sympy import content + >>> from sympy.abc import x + + >>> content(6*x**2 + 8*x + 12) + 2 + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('content', 1, exc) + + return F.content() + + +@public +def primitive(f, *gens, **args): + """ + Compute content and the primitive form of ``f``. + + Examples + ======== + + >>> from sympy.polys.polytools import primitive + >>> from sympy.abc import x + + >>> primitive(6*x**2 + 8*x + 12) + (2, 3*x**2 + 4*x + 6) + + >>> eq = (2 + 2*x)*x + 2 + + Expansion is performed by default: + + >>> primitive(eq) + (2, x**2 + x + 1) + + Set ``expand`` to False to shut this off. Note that the + extraction will not be recursive; use the as_content_primitive method + for recursive, non-destructive Rational extraction. + + >>> primitive(eq, expand=False) + (1, x*(2*x + 2) + 2) + + >>> eq.as_content_primitive() + (2, x*(x + 1) + 1) + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('primitive', 1, exc) + + cont, result = F.primitive() + if not opt.polys: + return cont, result.as_expr() + else: + return cont, result + + +@public +def compose(f, g, *gens, **args): + """ + Compute functional composition ``f(g)``. + + Examples + ======== + + >>> from sympy import compose + >>> from sympy.abc import x + + >>> compose(x**2 + x, x - 1) + x**2 - x + + """ + options.allowed_flags(args, ['polys']) + + try: + (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('compose', 2, exc) + + result = F.compose(G) + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def decompose(f, *gens, **args): + """ + Compute functional decomposition of ``f``. + + Examples + ======== + + >>> from sympy import decompose + >>> from sympy.abc import x + + >>> decompose(x**4 + 2*x**3 - x - 1) + [x**2 - x - 1, x**2 + x] + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('decompose', 1, exc) + + result = F.decompose() + + if not opt.polys: + return [r.as_expr() for r in result] + else: + return result + + +@public +def sturm(f, *gens, **args): + """ + Compute Sturm sequence of ``f``. + + Examples + ======== + + >>> from sympy import sturm + >>> from sympy.abc import x + + >>> sturm(x**3 - 2*x**2 + x - 3) + [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4] + + """ + options.allowed_flags(args, ['auto', 'polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('sturm', 1, exc) + + result = F.sturm(auto=opt.auto) + + if not opt.polys: + return [r.as_expr() for r in result] + else: + return result + + +@public +def gff_list(f, *gens, **args): + """ + Compute a list of greatest factorial factors of ``f``. + + Note that the input to ff() and rf() should be Poly instances to use the + definitions here. + + Examples + ======== + + >>> from sympy import gff_list, ff, Poly + >>> from sympy.abc import x + + >>> f = Poly(x**5 + 2*x**4 - x**3 - 2*x**2, x) + + >>> gff_list(f) + [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] + + >>> (ff(Poly(x), 1)*ff(Poly(x + 2), 4)) == f + True + + >>> f = Poly(x**12 + 6*x**11 - 11*x**10 - 56*x**9 + 220*x**8 + 208*x**7 - \ + 1401*x**6 + 1090*x**5 + 2715*x**4 - 6720*x**3 - 1092*x**2 + 5040*x, x) + + >>> gff_list(f) + [(Poly(x**3 + 7, x, domain='ZZ'), 2), (Poly(x**2 + 5*x, x, domain='ZZ'), 3)] + + >>> ff(Poly(x**3 + 7, x), 2)*ff(Poly(x**2 + 5*x, x), 3) == f + True + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('gff_list', 1, exc) + + factors = F.gff_list() + + if not opt.polys: + return [(g.as_expr(), k) for g, k in factors] + else: + return factors + + +@public +def gff(f, *gens, **args): + """Compute greatest factorial factorization of ``f``. """ + raise NotImplementedError('symbolic falling factorial') + + +@public +def sqf_norm(f, *gens, **args): + """ + Compute square-free norm of ``f``. + + Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and + ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, + where ``a`` is the algebraic extension of the ground domain. + + Examples + ======== + + >>> from sympy import sqf_norm, sqrt + >>> from sympy.abc import x + + >>> sqf_norm(x**2 + 1, extension=[sqrt(3)]) + ([1], x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16) + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('sqf_norm', 1, exc) + + s, g, r = F.sqf_norm() + + s_expr = [Integer(si) for si in s] + + if not opt.polys: + return s_expr, g.as_expr(), r.as_expr() + else: + return s_expr, g, r + + +@public +def sqf_part(f, *gens, **args): + """ + Compute square-free part of ``f``. + + Examples + ======== + + >>> from sympy import sqf_part + >>> from sympy.abc import x + + >>> sqf_part(x**3 - 3*x - 2) + x**2 - x - 2 + + """ + options.allowed_flags(args, ['polys']) + + try: + F, opt = poly_from_expr(f, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('sqf_part', 1, exc) + + result = F.sqf_part() + + if not opt.polys: + return result.as_expr() + else: + return result + + +def _poly_sort_key(poly): + """Sort a list of polys.""" + rep = poly.rep.to_list() + return (len(rep), len(poly.gens), str(poly.domain), rep) + + +def _sorted_factors(factors, method): + """Sort a list of ``(expr, exp)`` pairs. """ + if method == 'sqf': + def key(obj): + poly, exp = obj + rep = poly.rep.to_list() + return (exp, len(rep), len(poly.gens), str(poly.domain), rep) + else: + def key(obj): + poly, exp = obj + rep = poly.rep.to_list() + return (len(rep), len(poly.gens), exp, str(poly.domain), rep) + + return sorted(factors, key=key) + + +def _factors_product(factors): + """Multiply a list of ``(expr, exp)`` pairs. """ + return Mul(*[f.as_expr()**k for f, k in factors]) + + +def _symbolic_factor_list(expr, opt, method): + """Helper function for :func:`_symbolic_factor`. """ + coeff, factors = S.One, [] + + args = [i._eval_factor() if hasattr(i, '_eval_factor') else i + for i in Mul.make_args(expr)] + for arg in args: + if arg.is_Number or (isinstance(arg, Expr) and pure_complex(arg)): + coeff *= arg + continue + elif arg.is_Pow and arg.base != S.Exp1: + base, exp = arg.args + if base.is_Number and exp.is_Number: + coeff *= arg + continue + if base.is_Number: + factors.append((base, exp)) + continue + else: + base, exp = arg, S.One + + try: + poly, _ = _poly_from_expr(base, opt) + except PolificationFailed as exc: + factors.append((exc.expr, exp)) + else: + func = getattr(poly, method + '_list') + + _coeff, _factors = func() + if _coeff is not S.One: + if exp.is_Integer: + coeff *= _coeff**exp + elif _coeff.is_positive: + factors.append((_coeff, exp)) + else: + _factors.append((_coeff, S.One)) + + if exp is S.One: + factors.extend(_factors) + elif exp.is_integer: + factors.extend([(f, k*exp) for f, k in _factors]) + else: + other = [] + + for f, k in _factors: + if f.as_expr().is_positive: + factors.append((f, k*exp)) + else: + other.append((f, k)) + + factors.append((_factors_product(other), exp)) + if method == 'sqf': + factors = [(reduce(mul, (f for f, _ in factors if _ == k)), k) + for k in {i for _, i in factors}] + #collect duplicates + rv = defaultdict(int) + for k, v in factors: + rv[k] += v + return coeff, list(rv.items()) + + +def _symbolic_factor(expr, opt, method): + """Helper function for :func:`_factor`. """ + if isinstance(expr, Expr): + if hasattr(expr,'_eval_factor'): + return expr._eval_factor() + coeff, factors = _symbolic_factor_list(together(expr, fraction=opt['fraction']), opt, method) + return _keep_coeff(coeff, _factors_product(factors)) + elif hasattr(expr, 'args'): + return expr.func(*[_symbolic_factor(arg, opt, method) for arg in expr.args]) + elif hasattr(expr, '__iter__'): + return expr.__class__([_symbolic_factor(arg, opt, method) for arg in expr]) + else: + return expr + + +def _generic_factor_list(expr, gens, args, method): + """Helper function for :func:`sqf_list` and :func:`factor_list`. """ + options.allowed_flags(args, ['frac', 'polys']) + opt = options.build_options(gens, args) + + expr = sympify(expr) + + if isinstance(expr, (Expr, Poly)): + if isinstance(expr, Poly): + numer, denom = expr, 1 + else: + numer, denom = together(expr).as_numer_denom() + + cp, fp = _symbolic_factor_list(numer, opt, method) + cq, fq = _symbolic_factor_list(denom, opt, method) + + if fq and not opt.frac: + raise PolynomialError("a polynomial expected, got %s" % expr) + + _opt = opt.clone({"expand": True}) + + for factors in (fp, fq): + for i, (f, k) in enumerate(factors): + if not f.is_Poly: + f, _ = _poly_from_expr(f, _opt) + factors[i] = (f, k) + + fp = _sorted_factors(fp, method) + fq = _sorted_factors(fq, method) + + if not opt.polys: + fp = [(f.as_expr(), k) for f, k in fp] + fq = [(f.as_expr(), k) for f, k in fq] + + coeff = cp/cq + + if not opt.frac: + return coeff, fp + else: + return coeff, fp, fq + else: + raise PolynomialError("a polynomial expected, got %s" % expr) + + +def _generic_factor(expr, gens, args, method): + """Helper function for :func:`sqf` and :func:`factor`. """ + fraction = args.pop('fraction', True) + options.allowed_flags(args, []) + opt = options.build_options(gens, args) + opt['fraction'] = fraction + return _symbolic_factor(sympify(expr), opt, method) + + +def to_rational_coeffs(f): + """ + try to transform a polynomial to have rational coefficients + + try to find a transformation ``x = alpha*y`` + + ``f(x) = lc*alpha**n * g(y)`` where ``g`` is a polynomial with + rational coefficients, ``lc`` the leading coefficient. + + If this fails, try ``x = y + beta`` + ``f(x) = g(y)`` + + Returns ``None`` if ``g`` not found; + ``(lc, alpha, None, g)`` in case of rescaling + ``(None, None, beta, g)`` in case of translation + + Notes + ===== + + Currently it transforms only polynomials without roots larger than 2. + + Examples + ======== + + >>> from sympy import sqrt, Poly, simplify + >>> from sympy.polys.polytools import to_rational_coeffs + >>> from sympy.abc import x + >>> p = Poly(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}), x, domain='EX') + >>> lc, r, _, g = to_rational_coeffs(p) + >>> lc, r + (7 + 5*sqrt(2), 2 - 2*sqrt(2)) + >>> g + Poly(x**3 + x**2 - 1/4*x - 1/4, x, domain='QQ') + >>> r1 = simplify(1/r) + >>> Poly(lc*r**3*(g.as_expr()).subs({x:x*r1}), x, domain='EX') == p + True + + """ + from sympy.simplify.simplify import simplify + + def _try_rescale(f, f1=None): + """ + try rescaling ``x -> alpha*x`` to convert f to a polynomial + with rational coefficients. + Returns ``alpha, f``; if the rescaling is successful, + ``alpha`` is the rescaling factor, and ``f`` is the rescaled + polynomial; else ``alpha`` is ``None``. + """ + if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: + return None, f + n = f.degree() + lc = f.LC() + f1 = f1 or f1.monic() + coeffs = f1.all_coeffs()[1:] + coeffs = [simplify(coeffx) for coeffx in coeffs] + if len(coeffs) > 1 and coeffs[-2]: + rescale1_x = simplify(coeffs[-2]/coeffs[-1]) + coeffs1 = [] + for i in range(len(coeffs)): + coeffx = simplify(coeffs[i]*rescale1_x**(i + 1)) + if not coeffx.is_rational: + break + coeffs1.append(coeffx) + else: + rescale_x = simplify(1/rescale1_x) + x = f.gens[0] + v = [x**n] + for i in range(1, n + 1): + v.append(coeffs1[i - 1]*x**(n - i)) + f = Add(*v) + f = Poly(f) + return lc, rescale_x, f + return None + + def _try_translate(f, f1=None): + """ + try translating ``x -> x + alpha`` to convert f to a polynomial + with rational coefficients. + Returns ``alpha, f``; if the translating is successful, + ``alpha`` is the translating factor, and ``f`` is the shifted + polynomial; else ``alpha`` is ``None``. + """ + if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: + return None, f + n = f.degree() + f1 = f1 or f1.monic() + coeffs = f1.all_coeffs()[1:] + c = simplify(coeffs[0]) + if c.is_Add and not c.is_rational: + rat, nonrat = sift(c.args, + lambda z: z.is_rational is True, binary=True) + alpha = -c.func(*nonrat)/n + f2 = f1.shift(alpha) + return alpha, f2 + return None + + def _has_square_roots(p): + """ + Return True if ``f`` is a sum with square roots but no other root + """ + coeffs = p.coeffs() + has_sq = False + for y in coeffs: + for x in Add.make_args(y): + f = Factors(x).factors + r = [wx.q for b, wx in f.items() if + b.is_number and wx.is_Rational and wx.q >= 2] + if not r: + continue + if min(r) == 2: + has_sq = True + if max(r) > 2: + return False + return has_sq + + if f.get_domain().is_EX and _has_square_roots(f): + f1 = f.monic() + r = _try_rescale(f, f1) + if r: + return r[0], r[1], None, r[2] + else: + r = _try_translate(f, f1) + if r: + return None, None, r[0], r[1] + return None + + +def _torational_factor_list(p, x): + """ + helper function to factor polynomial using to_rational_coeffs + + Examples + ======== + + >>> from sympy.polys.polytools import _torational_factor_list + >>> from sympy.abc import x + >>> from sympy import sqrt, expand, Mul + >>> p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) + >>> factors = _torational_factor_list(p, x); factors + (-2, [(-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) + >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p + True + >>> p = expand(((x**2-1)*(x-2)).subs({x:x + sqrt(2)})) + >>> factors = _torational_factor_list(p, x); factors + (1, [(x - 2 + sqrt(2), 1), (x - 1 + sqrt(2), 1), (x + 1 + sqrt(2), 1)]) + >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p + True + + """ + from sympy.simplify.simplify import simplify + p1 = Poly(p, x, domain='EX') + n = p1.degree() + res = to_rational_coeffs(p1) + if not res: + return None + lc, r, t, g = res + factors = factor_list(g.as_expr()) + if lc: + c = simplify(factors[0]*lc*r**n) + r1 = simplify(1/r) + a = [] + for z in factors[1:][0]: + a.append((simplify(z[0].subs({x: x*r1})), z[1])) + else: + c = factors[0] + a = [] + for z in factors[1:][0]: + a.append((z[0].subs({x: x - t}), z[1])) + return (c, a) + + +@public +def sqf_list(f, *gens, **args): + """ + Compute a list of square-free factors of ``f``. + + Examples + ======== + + >>> from sympy import sqf_list + >>> from sympy.abc import x + + >>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) + (2, [(x + 1, 2), (x + 2, 3)]) + + """ + return _generic_factor_list(f, gens, args, method='sqf') + + +@public +def sqf(f, *gens, **args): + """ + Compute square-free factorization of ``f``. + + Examples + ======== + + >>> from sympy import sqf + >>> from sympy.abc import x + + >>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) + 2*(x + 1)**2*(x + 2)**3 + + """ + return _generic_factor(f, gens, args, method='sqf') + + +@public +def factor_list(f, *gens, **args): + """ + Compute a list of irreducible factors of ``f``. + + Examples + ======== + + >>> from sympy import factor_list + >>> from sympy.abc import x, y + + >>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) + (2, [(x + y, 1), (x**2 + 1, 2)]) + + """ + return _generic_factor_list(f, gens, args, method='factor') + + +@public +def factor(f, *gens, deep=False, **args): + """ + Compute the factorization of expression, ``f``, into irreducibles. (To + factor an integer into primes, use ``factorint``.) + + There two modes implemented: symbolic and formal. If ``f`` is not an + instance of :class:`Poly` and generators are not specified, then the + former mode is used. Otherwise, the formal mode is used. + + In symbolic mode, :func:`factor` will traverse the expression tree and + factor its components without any prior expansion, unless an instance + of :class:`~.Add` is encountered (in this case formal factorization is + used). This way :func:`factor` can handle large or symbolic exponents. + + By default, the factorization is computed over the rationals. To factor + over other domain, e.g. an algebraic or finite field, use appropriate + options: ``extension``, ``modulus`` or ``domain``. + + Examples + ======== + + >>> from sympy import factor, sqrt, exp + >>> from sympy.abc import x, y + + >>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) + 2*(x + y)*(x**2 + 1)**2 + + >>> factor(x**2 + 1) + x**2 + 1 + >>> factor(x**2 + 1, modulus=2) + (x + 1)**2 + >>> factor(x**2 + 1, gaussian=True) + (x - I)*(x + I) + + >>> factor(x**2 - 2, extension=sqrt(2)) + (x - sqrt(2))*(x + sqrt(2)) + + >>> factor((x**2 - 1)/(x**2 + 4*x + 4)) + (x - 1)*(x + 1)/(x + 2)**2 + >>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1)) + (x + 2)**20000000*(x**2 + 1) + + By default, factor deals with an expression as a whole: + + >>> eq = 2**(x**2 + 2*x + 1) + >>> factor(eq) + 2**(x**2 + 2*x + 1) + + If the ``deep`` flag is True then subexpressions will + be factored: + + >>> factor(eq, deep=True) + 2**((x + 1)**2) + + If the ``fraction`` flag is False then rational expressions + will not be combined. By default it is True. + + >>> factor(5*x + 3*exp(2 - 7*x), deep=True) + (5*x*exp(7*x) + 3*exp(2))*exp(-7*x) + >>> factor(5*x + 3*exp(2 - 7*x), deep=True, fraction=False) + 5*x + 3*exp(2)*exp(-7*x) + + See Also + ======== + sympy.ntheory.factor_.factorint + + """ + f = sympify(f) + if deep: + def _try_factor(expr): + """ + Factor, but avoid changing the expression when unable to. + """ + fac = factor(expr, *gens, **args) + if fac.is_Mul or fac.is_Pow: + return fac + return expr + + f = bottom_up(f, _try_factor) + # clean up any subexpressions that may have been expanded + # while factoring out a larger expression + partials = {} + muladd = f.atoms(Mul, Add) + for p in muladd: + fac = factor(p, *gens, **args) + if (fac.is_Mul or fac.is_Pow) and fac != p: + partials[p] = fac + return f.xreplace(partials) + + try: + return _generic_factor(f, gens, args, method='factor') + except PolynomialError: + if not f.is_commutative: + return factor_nc(f) + else: + raise + + +@public +def intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False): + """ + Compute isolating intervals for roots of ``f``. + + Examples + ======== + + >>> from sympy import intervals + >>> from sympy.abc import x + + >>> intervals(x**2 - 3) + [((-2, -1), 1), ((1, 2), 1)] + >>> intervals(x**2 - 3, eps=1e-2) + [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] + + """ + if not hasattr(F, '__iter__'): + try: + F = Poly(F) + except GeneratorsNeeded: + return [] + + return F.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) + else: + polys, opt = parallel_poly_from_expr(F, domain='QQ') + + if len(opt.gens) > 1: + raise MultivariatePolynomialError + + for i, poly in enumerate(polys): + polys[i] = poly.rep.to_list() + + if eps is not None: + eps = opt.domain.convert(eps) + + if eps <= 0: + raise ValueError("'eps' must be a positive rational") + + if inf is not None: + inf = opt.domain.convert(inf) + if sup is not None: + sup = opt.domain.convert(sup) + + intervals = dup_isolate_real_roots_list(polys, opt.domain, + eps=eps, inf=inf, sup=sup, strict=strict, fast=fast) + + result = [] + + for (s, t), indices in intervals: + s, t = opt.domain.to_sympy(s), opt.domain.to_sympy(t) + result.append(((s, t), indices)) + + return result + + +@public +def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): + """ + Refine an isolating interval of a root to the given precision. + + Examples + ======== + + >>> from sympy import refine_root + >>> from sympy.abc import x + + >>> refine_root(x**2 - 3, 1, 2, eps=1e-2) + (19/11, 26/15) + + """ + try: + F = Poly(f) + if not isinstance(f, Poly) and not F.gen.is_Symbol: + # root of sin(x) + 1 is -1 but when someone + # passes an Expr instead of Poly they may not expect + # that the generator will be sin(x), not x + raise PolynomialError("generator must be a Symbol") + except GeneratorsNeeded: + raise PolynomialError( + "Cannot refine a root of %s, not a polynomial" % f) + + return F.refine_root(s, t, eps=eps, steps=steps, fast=fast, check_sqf=check_sqf) + + +@public +def count_roots(f, inf=None, sup=None): + """ + Return the number of roots of ``f`` in ``[inf, sup]`` interval. + + If one of ``inf`` or ``sup`` is complex, it will return the number of roots + in the complex rectangle with corners at ``inf`` and ``sup``. + + Examples + ======== + + >>> from sympy import count_roots, I + >>> from sympy.abc import x + + >>> count_roots(x**4 - 4, -3, 3) + 2 + >>> count_roots(x**4 - 4, 0, 1 + 3*I) + 1 + + """ + try: + F = Poly(f, greedy=False) + if not isinstance(f, Poly) and not F.gen.is_Symbol: + # root of sin(x) + 1 is -1 but when someone + # passes an Expr instead of Poly they may not expect + # that the generator will be sin(x), not x + raise PolynomialError("generator must be a Symbol") + except GeneratorsNeeded: + raise PolynomialError("Cannot count roots of %s, not a polynomial" % f) + + return F.count_roots(inf=inf, sup=sup) + + +@public +def all_roots(f, multiple=True, radicals=True, extension=False): + """ + Returns the real and complex roots of ``f`` with multiplicities. + + Explanation + =========== + + Finds all real and complex roots of a univariate polynomial with rational + coefficients of any degree exactly. The roots are represented in the form + given by :func:`~.rootof`. This is equivalent to using :func:`~.rootof` to + find each of the indexed roots. + + Examples + ======== + + >>> from sympy import all_roots + >>> from sympy.abc import x, y + + >>> print(all_roots(x**3 + 1)) + [-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2] + + Simple radical formulae are used in some cases but the cubic and quartic + formulae are avoided. Instead most non-rational roots will be represented + as :class:`~.ComplexRootOf`: + + >>> print(all_roots(x**3 + x + 1)) + [CRootOf(x**3 + x + 1, 0), CRootOf(x**3 + x + 1, 1), CRootOf(x**3 + x + 1, 2)] + + All roots of any polynomial with rational coefficients of any degree can be + represented using :py:class:`~.ComplexRootOf`. The use of + :py:class:`~.ComplexRootOf` bypasses limitations on the availability of + radical formulae for quintic and higher degree polynomials _[1]: + + >>> p = x**5 - x - 1 + >>> for r in all_roots(p): print(r) + CRootOf(x**5 - x - 1, 0) + CRootOf(x**5 - x - 1, 1) + CRootOf(x**5 - x - 1, 2) + CRootOf(x**5 - x - 1, 3) + CRootOf(x**5 - x - 1, 4) + >>> [r.evalf(3) for r in all_roots(p)] + [1.17, -0.765 - 0.352*I, -0.765 + 0.352*I, 0.181 - 1.08*I, 0.181 + 1.08*I] + + Irrational algebraic coefficients are handled by :func:`all_roots` + if `extension=True` is set. + + >>> from sympy import sqrt, expand + >>> p = expand((x - sqrt(2))*(x - sqrt(3))) + >>> print(p) + x**2 - sqrt(3)*x - sqrt(2)*x + sqrt(6) + >>> all_roots(p) + Traceback (most recent call last): + ... + NotImplementedError: sorted roots not supported over EX + >>> all_roots(p, extension=True) + [sqrt(2), sqrt(3)] + + Algebraic coefficients can be complex as well. + + >>> from sympy import I + >>> all_roots(x**2 - I, extension=True) + [-sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2] + >>> all_roots(x**2 - sqrt(2)*I, extension=True) + [-2**(3/4)/2 - 2**(3/4)*I/2, 2**(3/4)/2 + 2**(3/4)*I/2] + + Transcendental coefficients cannot currently be handled by + :func:`all_roots`. In the case of algebraic or transcendental coefficients + :func:`~.ground_roots` might be able to find some roots by factorisation: + + >>> from sympy import ground_roots + >>> ground_roots(p, x, extension=True) + {sqrt(2): 1, sqrt(3): 1} + + If the coefficients are numeric then :func:`~.nroots` can be used to find + all roots approximately: + + >>> from sympy import nroots + >>> nroots(p, 5) + [1.4142, 1.732] + + If the coefficients are symbolic then :func:`sympy.polys.polyroots.roots` + or :func:`~.ground_roots` should be used instead: + + >>> from sympy import roots, ground_roots + >>> p = x**2 - 3*x*y + 2*y**2 + >>> roots(p, x) + {y: 1, 2*y: 1} + >>> ground_roots(p, x) + {y: 1, 2*y: 1} + + Parameters + ========== + + f : :class:`~.Expr` or :class:`~.Poly` + A univariate polynomial with rational (or ``Float``) coefficients. + multiple : ``bool`` (default ``True``). + Whether to return a ``list`` of roots or a list of root/multiplicity + pairs. + radicals : ``bool`` (default ``True``) + Use simple radical formulae rather than :py:class:`~.ComplexRootOf` for + some irrational roots. + extension: ``bool`` (default ``False``) + Whether to construct an algebraic extension domain before computing + the roots. Setting to ``True`` is necessary for finding roots of a + polynomial with (irrational) algebraic coefficients but can be slow. + + Returns + ======= + + A list of :class:`~.Expr` (usually :class:`~.ComplexRootOf`) representing + the roots is returned with each root repeated according to its multiplicity + as a root of ``f``. The roots are always uniquely ordered with real roots + coming before complex roots. The real roots are in increasing order. + Complex roots are ordered by increasing real part and then increasing + imaginary part. + + If ``multiple=False`` is passed then a list of root/multiplicity pairs is + returned instead. + + If ``radicals=False`` is passed then all roots will be represented as + either rational numbers or :class:`~.ComplexRootOf`. + + See also + ======== + + Poly.all_roots: + The underlying :class:`Poly` method used by :func:`~.all_roots`. + rootof: + Compute a single numbered root of a univariate polynomial. + real_roots: + Compute all the real roots using :func:`~.rootof`. + ground_roots: + Compute some roots in the ground domain by factorisation. + nroots: + Compute all roots using approximate numerical techniques. + sympy.polys.polyroots.roots: + Compute symbolic expressions for roots using radical formulae. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Abel%E2%80%93Ruffini_theorem + """ + try: + if isinstance(f, Poly): + if extension and not f.domain.is_AlgebraicField: + F = Poly(f.expr, extension=True) + else: + F = f + else: + if extension: + F = Poly(f, extension=True) + else: + F = Poly(f, greedy=False) + + if not isinstance(f, Poly) and not F.gen.is_Symbol: + # root of sin(x) + 1 is -1 but when someone + # passes an Expr instead of Poly they may not expect + # that the generator will be sin(x), not x + raise PolynomialError("generator must be a Symbol") + except GeneratorsNeeded: + raise PolynomialError( + "Cannot compute real roots of %s, not a polynomial" % f) + + return F.all_roots(multiple=multiple, radicals=radicals) + + +@public +def real_roots(f, multiple=True, radicals=True, extension=False): + """ + Returns the real roots of ``f`` with multiplicities. + + Explanation + =========== + + Finds all real roots of a univariate polynomial with rational coefficients + of any degree exactly. The roots are represented in the form given by + :func:`~.rootof`. This is equivalent to using :func:`~.rootof` or + :func:`~.all_roots` and filtering out only the real roots. However if only + the real roots are needed then :func:`real_roots` is more efficient than + :func:`~.all_roots` because it computes only the real roots and avoids + costly complex root isolation routines. + + Examples + ======== + + >>> from sympy import real_roots + >>> from sympy.abc import x, y + + >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4) + [-1/2, 2, 2] + >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4, multiple=False) + [(-1/2, 1), (2, 2)] + + Real roots of any polynomial with rational coefficients of any degree can + be represented using :py:class:`~.ComplexRootOf`: + + >>> p = x**9 + 2*x + 2 + >>> print(real_roots(p)) + [CRootOf(x**9 + 2*x + 2, 0)] + >>> [r.evalf(3) for r in real_roots(p)] + [-0.865] + + All rational roots will be returned as rational numbers. Roots of some + simple factors will be expressed using radical or other formulae (unless + ``radicals=False`` is passed). All other roots will be expressed as + :class:`~.ComplexRootOf`. + + >>> p = (x + 7)*(x**2 - 2)*(x**3 + x + 1) + >>> print(real_roots(p)) + [-7, -sqrt(2), CRootOf(x**3 + x + 1, 0), sqrt(2)] + >>> print(real_roots(p, radicals=False)) + [-7, CRootOf(x**2 - 2, 0), CRootOf(x**3 + x + 1, 0), CRootOf(x**2 - 2, 1)] + + All returned root expressions will numerically evaluate to real numbers + with no imaginary part. This is in contrast to the expressions generated by + the cubic or quartic formulae as used by :func:`~.roots` which suffer from + casus irreducibilis [1]_: + + >>> from sympy import roots + >>> p = 2*x**3 - 9*x**2 - 6*x + 3 + >>> [r.evalf(5) for r in roots(p, multiple=True)] + [5.0365 - 0.e-11*I, 0.33984 + 0.e-13*I, -0.87636 + 0.e-10*I] + >>> [r.evalf(5) for r in real_roots(p, x)] + [-0.87636, 0.33984, 5.0365] + >>> [r.is_real for r in roots(p, multiple=True)] + [None, None, None] + >>> [r.is_real for r in real_roots(p)] + [True, True, True] + + Using :func:`real_roots` is equivalent to using :func:`~.all_roots` (or + :func:`~.rootof`) and filtering out only the real roots: + + >>> from sympy import all_roots + >>> r = [r for r in all_roots(p) if r.is_real] + >>> real_roots(p) == r + True + + If only the real roots are wanted then using :func:`real_roots` is faster + than using :func:`~.all_roots`. Using :func:`real_roots` avoids complex root + isolation which can be a lot slower than real root isolation especially for + polynomials of high degree which typically have many more complex roots + than real roots. + + Irrational algebraic coefficients are handled by :func:`real_roots` + if `extension=True` is set. + + >>> from sympy import sqrt, expand + >>> p = expand((x - sqrt(2))*(x - sqrt(3))) + >>> print(p) + x**2 - sqrt(3)*x - sqrt(2)*x + sqrt(6) + >>> real_roots(p) + Traceback (most recent call last): + ... + NotImplementedError: sorted roots not supported over EX + >>> real_roots(p, extension=True) + [sqrt(2), sqrt(3)] + + Transcendental coefficients cannot currently be handled by + :func:`real_roots`. In the case of algebraic or transcendental coefficients + :func:`~.ground_roots` might be able to find some roots by factorisation: + + >>> from sympy import ground_roots + >>> ground_roots(p, x, extension=True) + {sqrt(2): 1, sqrt(3): 1} + + If the coefficients are numeric then :func:`~.nroots` can be used to find + all roots approximately: + + >>> from sympy import nroots + >>> nroots(p, 5) + [1.4142, 1.732] + + If the coefficients are symbolic then :func:`sympy.polys.polyroots.roots` + or :func:`~.ground_roots` should be used instead. + + >>> from sympy import roots, ground_roots + >>> p = x**2 - 3*x*y + 2*y**2 + >>> roots(p, x) + {y: 1, 2*y: 1} + >>> ground_roots(p, x) + {y: 1, 2*y: 1} + + Parameters + ========== + + f : :class:`~.Expr` or :class:`~.Poly` + A univariate polynomial with rational (or ``Float``) coefficients. + multiple : ``bool`` (default ``True``). + Whether to return a ``list`` of roots or a list of root/multiplicity + pairs. + radicals : ``bool`` (default ``True``) + Use simple radical formulae rather than :py:class:`~.ComplexRootOf` for + some irrational roots. + extension: ``bool`` (default ``False``) + Whether to construct an algebraic extension domain before computing + the roots. Setting to ``True`` is necessary for finding roots of a + polynomial with (irrational) algebraic coefficients but can be slow. + + Returns + ======= + + A list of :class:`~.Expr` (usually :class:`~.ComplexRootOf`) representing + the real roots is returned. The roots are arranged in increasing order and + are repeated according to their multiplicities as roots of ``f``. + + If ``multiple=False`` is passed then a list of root/multiplicity pairs is + returned instead. + + If ``radicals=False`` is passed then all roots will be represented as + either rational numbers or :class:`~.ComplexRootOf`. + + See also + ======== + + Poly.real_roots: + The underlying :class:`Poly` method used by :func:`real_roots`. + rootof: + Compute a single numbered root of a univariate polynomial. + all_roots: + Compute all real and non-real roots using :func:`~.rootof`. + ground_roots: + Compute some roots in the ground domain by factorisation. + nroots: + Compute all roots using approximate numerical techniques. + sympy.polys.polyroots.roots: + Compute symbolic expressions for roots using radical formulae. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Casus_irreducibilis + """ + try: + if isinstance(f, Poly): + if extension and not f.domain.is_AlgebraicField: + F = Poly(f.expr, extension=True) + else: + F = f + else: + if extension: + F = Poly(f, extension=True) + else: + F = Poly(f, greedy=False) + + if not isinstance(f, Poly) and not F.gen.is_Symbol: + # root of sin(x) + 1 is -1 but when someone + # passes an Expr instead of Poly they may not expect + # that the generator will be sin(x), not x + raise PolynomialError("generator must be a Symbol") + except GeneratorsNeeded: + raise PolynomialError( + "Cannot compute real roots of %s, not a polynomial" % f) + + return F.real_roots(multiple=multiple, radicals=radicals) + + +@public +def nroots(f, n=15, maxsteps=50, cleanup=True): + """ + Compute numerical approximations of roots of ``f``. + + Examples + ======== + + >>> from sympy import nroots + >>> from sympy.abc import x + + >>> nroots(x**2 - 3, n=15) + [-1.73205080756888, 1.73205080756888] + >>> nroots(x**2 - 3, n=30) + [-1.73205080756887729352744634151, 1.73205080756887729352744634151] + + """ + try: + F = Poly(f, greedy=False) + if not isinstance(f, Poly) and not F.gen.is_Symbol: + # root of sin(x) + 1 is -1 but when someone + # passes an Expr instead of Poly they may not expect + # that the generator will be sin(x), not x + raise PolynomialError("generator must be a Symbol") + except GeneratorsNeeded: + raise PolynomialError( + "Cannot compute numerical roots of %s, not a polynomial" % f) + + return F.nroots(n=n, maxsteps=maxsteps, cleanup=cleanup) + + +@public +def ground_roots(f, *gens, **args): + """ + Compute roots of ``f`` by factorization in the ground domain. + + Examples + ======== + + >>> from sympy import ground_roots + >>> from sympy.abc import x + + >>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2) + {0: 2, 1: 2} + + """ + options.allowed_flags(args, []) + + try: + F, opt = poly_from_expr(f, *gens, **args) + if not isinstance(f, Poly) and not F.gen.is_Symbol: + # root of sin(x) + 1 is -1 but when someone + # passes an Expr instead of Poly they may not expect + # that the generator will be sin(x), not x + raise PolynomialError("generator must be a Symbol") + except PolificationFailed as exc: + raise ComputationFailed('ground_roots', 1, exc) + + return F.ground_roots() + + +@public +def nth_power_roots_poly(f, n, *gens, **args): + """ + Construct a polynomial with n-th powers of roots of ``f``. + + Examples + ======== + + >>> from sympy import nth_power_roots_poly, factor, roots + >>> from sympy.abc import x + + >>> f = x**4 - x**2 + 1 + >>> g = factor(nth_power_roots_poly(f, 2)) + + >>> g + (x**2 - x + 1)**2 + + >>> R_f = [ (r**2).expand() for r in roots(f) ] + >>> R_g = roots(g).keys() + + >>> set(R_f) == set(R_g) + True + + """ + options.allowed_flags(args, []) + + try: + F, opt = poly_from_expr(f, *gens, **args) + if not isinstance(f, Poly) and not F.gen.is_Symbol: + # root of sin(x) + 1 is -1 but when someone + # passes an Expr instead of Poly they may not expect + # that the generator will be sin(x), not x + raise PolynomialError("generator must be a Symbol") + except PolificationFailed as exc: + raise ComputationFailed('nth_power_roots_poly', 1, exc) + + result = F.nth_power_roots_poly(n) + + if not opt.polys: + return result.as_expr() + else: + return result + + +@public +def cancel(f, *gens, _signsimp=True, **args): + """ + Cancel common factors in a rational function ``f``. + + Examples + ======== + + >>> from sympy import cancel, sqrt, Symbol, together + >>> from sympy.abc import x + >>> A = Symbol('A', commutative=False) + + >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1)) + (2*x + 2)/(x - 1) + >>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A)) + sqrt(6)/2 + + Note: due to automatic distribution of Rationals, a sum divided by an integer + will appear as a sum. To recover a rational form use `together` on the result: + + >>> cancel(x/2 + 1) + x/2 + 1 + >>> together(_) + (x + 2)/2 + """ + from sympy.simplify.simplify import signsimp + from sympy.polys.rings import sring + options.allowed_flags(args, ['polys']) + + f = sympify(f) + if _signsimp: + f = signsimp(f) + opt = {} + if 'polys' in args: + opt['polys'] = args['polys'] + + if not isinstance(f, Tuple): + if f.is_Number or isinstance(f, Relational) or not isinstance(f, Expr): + return f + f = factor_terms(f, radical=True) + p, q = f.as_numer_denom() + + elif len(f) == 2: + p, q = f + if isinstance(p, Poly) and isinstance(q, Poly): + opt['gens'] = p.gens + opt['domain'] = p.domain + opt['polys'] = opt.get('polys', True) + p, q = p.as_expr(), q.as_expr() + else: + raise ValueError('unexpected argument: %s' % f) + + from sympy.functions.elementary.piecewise import Piecewise + try: + if f.has(Piecewise): + raise PolynomialError() + R, (F, G) = sring((p, q), *gens, **args) + if not R.ngens: + if not isinstance(f, Tuple): + return f.expand() + else: + return S.One, p, q + except PolynomialError as msg: + if f.is_commutative and not f.has(Piecewise): + raise PolynomialError(msg) + # Handling of noncommutative and/or piecewise expressions + if f.is_Add or f.is_Mul: + c, nc = sift(f.args, lambda x: + x.is_commutative is True and not x.has(Piecewise), + binary=True) + nc = [cancel(i) for i in nc] + return f.func(cancel(f.func(*c)), *nc) + else: + reps = [] + pot = preorder_traversal(f) + next(pot) + for e in pot: + if isinstance(e, BooleanAtom) or not isinstance(e, Expr): + continue + try: + reps.append((e, cancel(e))) + pot.skip() # this was handled successfully + except NotImplementedError: + pass + return f.xreplace(dict(reps)) + + c, (P, Q) = 1, F.cancel(G) + if opt.get('polys', False) and 'gens' not in opt: + opt['gens'] = R.symbols + + if not isinstance(f, Tuple): + return c*(P.as_expr()/Q.as_expr()) + else: + P, Q = P.as_expr(), Q.as_expr() + if not opt.get('polys', False): + return c, P, Q + else: + return c, Poly(P, *gens, **opt), Poly(Q, *gens, **opt) + + +@public +def reduced(f, G, *gens, **args): + """ + Reduces a polynomial ``f`` modulo a set of polynomials ``G``. + + Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, + computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` + such that ``f = q_1*g_1 + ... + q_n*g_n + r``, where ``r`` vanishes or ``r`` + is a completely reduced polynomial with respect to ``G``. + + Examples + ======== + + >>> from sympy import reduced + >>> from sympy.abc import x, y + + >>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y]) + ([2*x, 1], x**2 + y**2 + y) + + """ + options.allowed_flags(args, ['polys', 'auto']) + + try: + polys, opt = parallel_poly_from_expr([f] + list(G), *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('reduced', 0, exc) + + domain = opt.domain + retract = False + + if opt.auto and domain.is_Ring and not domain.is_Field: + opt = opt.clone({"domain": domain.get_field()}) + retract = True + + from sympy.polys.rings import xring + _ring, _ = xring(opt.gens, opt.domain, opt.order) + + for i, poly in enumerate(polys): + poly = poly.set_domain(opt.domain).rep.to_dict() + polys[i] = _ring.from_dict(poly) + + Q, r = polys[0].div(polys[1:]) + + Q = [Poly._from_dict(dict(q), opt) for q in Q] + r = Poly._from_dict(dict(r), opt) + + if retract: + try: + _Q, _r = [q.to_ring() for q in Q], r.to_ring() + except CoercionFailed: + pass + else: + Q, r = _Q, _r + + if not opt.polys: + return [q.as_expr() for q in Q], r.as_expr() + else: + return Q, r + + +@public +def groebner(F, *gens, **args): + """ + Computes the reduced Groebner basis for a set of polynomials. + + Use the ``order`` argument to set the monomial ordering that will be + used to compute the basis. Allowed orders are ``lex``, ``grlex`` and + ``grevlex``. If no order is specified, it defaults to ``lex``. + + For more information on Groebner bases, see the references and the docstring + of :func:`~.solve_poly_system`. + + Examples + ======== + + Example taken from [1]. + + >>> from sympy import groebner + >>> from sympy.abc import x, y + + >>> F = [x*y - 2*y, 2*y**2 - x**2] + + >>> groebner(F, x, y, order='lex') + GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y, + domain='ZZ', order='lex') + >>> groebner(F, x, y, order='grlex') + GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, + domain='ZZ', order='grlex') + >>> groebner(F, x, y, order='grevlex') + GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, + domain='ZZ', order='grevlex') + + By default, an improved implementation of the Buchberger algorithm is + used. Optionally, an implementation of the F5B algorithm can be used. The + algorithm can be set using the ``method`` flag or with the + :func:`sympy.polys.polyconfig.setup` function. + + >>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)] + + >>> groebner(F, x, y, method='buchberger') + GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') + >>> groebner(F, x, y, method='f5b') + GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') + + References + ========== + + 1. [Buchberger01]_ + 2. [Cox97]_ + + """ + return GroebnerBasis(F, *gens, **args) + + +@public +def is_zero_dimensional(F, *gens, **args): + """ + Checks if the ideal generated by a Groebner basis is zero-dimensional. + + The algorithm checks if the set of monomials not divisible by the + leading monomial of any element of ``F`` is bounded. + + References + ========== + + David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and + Algorithms, 3rd edition, p. 230 + + """ + return GroebnerBasis(F, *gens, **args).is_zero_dimensional + + +@public +class GroebnerBasis(Basic): + """Represents a reduced Groebner basis. """ + + def __new__(cls, F, *gens, **args): + """Compute a reduced Groebner basis for a system of polynomials. """ + options.allowed_flags(args, ['polys', 'method']) + + try: + polys, opt = parallel_poly_from_expr(F, *gens, **args) + except PolificationFailed as exc: + raise ComputationFailed('groebner', len(F), exc) + + from sympy.polys.rings import PolyRing + ring = PolyRing(opt.gens, opt.domain, opt.order) + + polys = [ring.from_dict(poly.rep.to_dict()) for poly in polys if poly] + + G = _groebner(polys, ring, method=opt.method) + G = [Poly._from_dict(g, opt) for g in G] + + return cls._new(G, opt) + + @classmethod + def _new(cls, basis, options): + obj = Basic.__new__(cls) + + obj._basis = tuple(basis) + obj._options = options + + return obj + + @property + def args(self): + basis = (p.as_expr() for p in self._basis) + return (Tuple(*basis), Tuple(*self._options.gens)) + + @property + def exprs(self): + return [poly.as_expr() for poly in self._basis] + + @property + def polys(self): + return list(self._basis) + + @property + def gens(self): + return self._options.gens + + @property + def domain(self): + return self._options.domain + + @property + def order(self): + return self._options.order + + def __len__(self): + return len(self._basis) + + def __iter__(self): + if self._options.polys: + return iter(self.polys) + else: + return iter(self.exprs) + + def __getitem__(self, item): + if self._options.polys: + basis = self.polys + else: + basis = self.exprs + + return basis[item] + + def __hash__(self): + return hash((self._basis, tuple(self._options.items()))) + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self._basis == other._basis and self._options == other._options + elif iterable(other): + return self.polys == list(other) or self.exprs == list(other) + else: + return False + + def __ne__(self, other): + return not self == other + + @property + def is_zero_dimensional(self): + """ + Checks if the ideal generated by a Groebner basis is zero-dimensional. + + The algorithm checks if the set of monomials not divisible by the + leading monomial of any element of ``F`` is bounded. + + References + ========== + + David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and + Algorithms, 3rd edition, p. 230 + + """ + def single_var(monomial): + return sum(map(bool, monomial)) == 1 + + exponents = Monomial([0]*len(self.gens)) + order = self._options.order + + for poly in self.polys: + monomial = poly.LM(order=order) + + if single_var(monomial): + exponents *= monomial + + # If any element of the exponents vector is zero, then there's + # a variable for which there's no degree bound and the ideal + # generated by this Groebner basis isn't zero-dimensional. + return all(exponents) + + def fglm(self, order): + """ + Convert a Groebner basis from one ordering to another. + + The FGLM algorithm converts reduced Groebner bases of zero-dimensional + ideals from one ordering to another. This method is often used when it + is infeasible to compute a Groebner basis with respect to a particular + ordering directly. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import groebner + + >>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] + >>> G = groebner(F, x, y, order='grlex') + + >>> list(G.fglm('lex')) + [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] + >>> list(groebner(F, x, y, order='lex')) + [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] + + References + ========== + + .. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient + Computation of Zero-dimensional Groebner Bases by Change of + Ordering + + """ + opt = self._options + + src_order = opt.order + dst_order = monomial_key(order) + + if src_order == dst_order: + return self + + if not self.is_zero_dimensional: + raise NotImplementedError("Cannot convert Groebner bases of ideals with positive dimension") + + polys = list(self._basis) + domain = opt.domain + + opt = opt.clone({ + "domain": domain.get_field(), + "order": dst_order, + }) + + from sympy.polys.rings import xring + _ring, _ = xring(opt.gens, opt.domain, src_order) + + for i, poly in enumerate(polys): + poly = poly.set_domain(opt.domain).rep.to_dict() + polys[i] = _ring.from_dict(poly) + + G = matrix_fglm(polys, _ring, dst_order) + G = [Poly._from_dict(dict(g), opt) for g in G] + + if not domain.is_Field: + G = [g.clear_denoms(convert=True)[1] for g in G] + opt.domain = domain + + return self._new(G, opt) + + def reduce(self, expr, auto=True): + """ + Reduces a polynomial modulo a Groebner basis. + + Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, + computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` + such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` + is a completely reduced polynomial with respect to ``G``. + + Examples + ======== + + >>> from sympy import groebner, expand, Poly + >>> from sympy.abc import x, y + + >>> f = 2*x**4 - x**2 + y**3 + y**2 + >>> G = groebner([x**3 - x, y**3 - y]) + + >>> G.reduce(f) + ([2*x, 1], x**2 + y**2 + y) + >>> Q, r = _ + + >>> expand(sum(q*g for q, g in zip(Q, G)) + r) + 2*x**4 - x**2 + y**3 + y**2 + >>> _ == f + True + + # Using Poly input + >>> f_poly = Poly(f, x, y) + >>> G = groebner([Poly(x**3 - x), Poly(y**3 - y)]) + + >>> G.reduce(f_poly) + ([Poly(2*x, x, y, domain='ZZ'), Poly(1, x, y, domain='ZZ')], Poly(x**2 + y**2 + y, x, y, domain='ZZ')) + + """ + if isinstance(expr, Poly): + + if expr.gens != self._options.gens: + raise ValueError("Polynomial generators don't match Groebner basis generators") + poly = expr.set_domain(self._options.domain) + else: + + poly = Poly._from_expr(expr, self._options) + + polys = [poly] + list(self._basis) + + opt = self._options + domain = opt.domain + + retract = False + + if auto and domain.is_Ring and not domain.is_Field: + opt = opt.clone({"domain": domain.get_field()}) + retract = True + + from sympy.polys.rings import xring + _ring, _ = xring(opt.gens, opt.domain, opt.order) + + for i, poly in enumerate(polys): + poly = poly.set_domain(opt.domain).rep.to_dict() + polys[i] = _ring.from_dict(poly) + + Q, r = polys[0].div(polys[1:]) + + Q = [Poly._from_dict(dict(q), opt) for q in Q] + r = Poly._from_dict(dict(r), opt) + + if retract: + try: + _Q, _r = [q.to_ring() for q in Q], r.to_ring() + except CoercionFailed: + pass + else: + Q, r = _Q, _r + + if not opt.polys: + return [q.as_expr() for q in Q], r.as_expr() + else: + return Q, r + + def contains(self, poly): + """ + Check if ``poly`` belongs the ideal generated by ``self``. + + Examples + ======== + + >>> from sympy import groebner + >>> from sympy.abc import x, y + + >>> f = 2*x**3 + y**3 + 3*y + >>> G = groebner([x**2 + y**2 - 1, x*y - 2]) + + >>> G.contains(f) + True + >>> G.contains(f + 1) + False + + """ + return self.reduce(poly)[1] == 0 + + +@public +def poly(expr, *gens, **args): + """ + Efficiently transform an expression into a polynomial. + + Examples + ======== + + >>> from sympy import poly + >>> from sympy.abc import x + + >>> poly(x*(x**2 + x - 1)**2) + Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') + + """ + options.allowed_flags(args, []) + + def _poly(expr, opt): + terms, poly_terms = [], [] + + for term in Add.make_args(expr): + factors, poly_factors = [], [] + + for factor in Mul.make_args(term): + if factor.is_Add: + poly_factors.append(_poly(factor, opt)) + elif factor.is_Pow and factor.base.is_Add and \ + factor.exp.is_Integer and factor.exp >= 0: + poly_factors.append( + _poly(factor.base, opt).pow(factor.exp)) + else: + factors.append(factor) + + if not poly_factors: + terms.append(term) + else: + product = poly_factors[0] + + for factor in poly_factors[1:]: + product = product.mul(factor) + + if factors: + factor = Mul(*factors) + + if factor.is_Number: + product *= factor + else: + product = product.mul(Poly._from_expr(factor, opt)) + + poly_terms.append(product) + + if not poly_terms: + result = Poly._from_expr(expr, opt) + else: + result = poly_terms[0] + + for term in poly_terms[1:]: + result = result.add(term) + + if terms: + term = Add(*terms) + + if term.is_Number: + result += term + else: + result = result.add(Poly._from_expr(term, opt)) + + return result.reorder(*opt.get('gens', ()), **args) + + expr = sympify(expr) + + if expr.is_Poly: + return Poly(expr, *gens, **args) + + if 'expand' not in args: + args['expand'] = False + + opt = options.build_options(gens, args) + + return _poly(expr, opt) + + +def named_poly(n, f, K, name, x, polys): + r"""Common interface to the low-level polynomial generating functions + in orthopolys and appellseqs. + + Parameters + ========== + + n : int + Index of the polynomial, which may or may not equal its degree. + f : callable + Low-level generating function to use. + K : Domain or None + Domain in which to perform the computations. If None, use the smallest + field containing the rationals and the extra parameters of x (see below). + name : str + Name of an arbitrary individual polynomial in the sequence generated + by f, only used in the error message for invalid n. + x : seq + The first element of this argument is the main variable of all + polynomials in this sequence. Any further elements are extra + parameters required by f. + polys : bool, optional + If True, return a Poly, otherwise (default) return an expression. + """ + if n < 0: + raise ValueError("Cannot generate %s of index %s" % (name, n)) + head, tail = x[0], x[1:] + if K is None: + K, tail = construct_domain(tail, field=True) + poly = DMP(f(int(n), *tail, K), K) + if head is None: + poly = PurePoly.new(poly, Dummy('x')) + else: + poly = Poly.new(poly, head) + return poly if polys else poly.as_expr() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyutils.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2019d3b195891d84ce8e0b368f6bdc5f45d4b3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/polyutils.py @@ -0,0 +1,584 @@ +"""Useful utilities for higher level polynomial classes. """ + +from __future__ import annotations + +from sympy.external.gmpy import GROUND_TYPES + +from sympy.core import (S, Add, Mul, Pow, Eq, Expr, + expand_mul, expand_multinomial) +from sympy.core.exprtools import decompose_power, decompose_power_rat +from sympy.core.numbers import _illegal +from sympy.polys.polyerrors import PolynomialError, GeneratorsError +from sympy.polys.polyoptions import build_options + +import re + + +_gens_order = { + 'a': 301, 'b': 302, 'c': 303, 'd': 304, + 'e': 305, 'f': 306, 'g': 307, 'h': 308, + 'i': 309, 'j': 310, 'k': 311, 'l': 312, + 'm': 313, 'n': 314, 'o': 315, 'p': 216, + 'q': 217, 'r': 218, 's': 219, 't': 220, + 'u': 221, 'v': 222, 'w': 223, 'x': 124, + 'y': 125, 'z': 126, +} + +_max_order = 1000 +_re_gen = re.compile(r"^(.*?)(\d*)$", re.MULTILINE) + + +def _nsort(roots, separated=False): + """Sort the numerical roots putting the real roots first, then sorting + according to real and imaginary parts. If ``separated`` is True, then + the real and imaginary roots will be returned in two lists, respectively. + + This routine tries to avoid issue 6137 by separating the roots into real + and imaginary parts before evaluation. In addition, the sorting will raise + an error if any computation cannot be done with precision. + """ + if not all(r.is_number for r in roots): + raise NotImplementedError + if not len(roots): + return [] if not separated else ([], []) + # see issue 6137: + # get the real part of the evaluated real and imaginary parts of each root + key = [[i.n(2).as_real_imag()[0] for i in r.as_real_imag()] for r in roots] + # make sure the parts were computed with precision + if len(roots) > 1 and any(i._prec == 1 for k in key for i in k): + raise NotImplementedError("could not compute root with precision") + # insert a key to indicate if the root has an imaginary part + key = [(1 if i else 0, r, i) for r, i in key] + key = sorted(zip(key, roots)) + # return the real and imaginary roots separately if desired + if separated: + r = [] + i = [] + for (im, _, _), v in key: + if im: + i.append(v) + else: + r.append(v) + return r, i + _, roots = zip(*key) + return list(roots) + + +def _sort_gens(gens, **args): + """Sort generators in a reasonably intelligent way. """ + opt = build_options(args) + + gens_order, wrt = {}, None + + if opt is not None: + gens_order, wrt = {}, opt.wrt + + for i, gen in enumerate(opt.sort): + gens_order[gen] = i + 1 + + def order_key(gen): + gen = str(gen) + + if wrt is not None: + try: + return (-len(wrt) + wrt.index(gen), gen, 0) + except ValueError: + pass + + name, index = _re_gen.match(gen).groups() + + if index: + index = int(index) + else: + index = 0 + + try: + return ( gens_order[name], name, index) + except KeyError: + pass + + try: + return (_gens_order[name], name, index) + except KeyError: + pass + + return (_max_order, name, index) + + try: + gens = sorted(gens, key=order_key) + except TypeError: # pragma: no cover + pass + + return tuple(gens) + + +def _unify_gens(f_gens, g_gens): + """Unify generators in a reasonably intelligent way. """ + f_gens = list(f_gens) + g_gens = list(g_gens) + + if f_gens == g_gens: + return tuple(f_gens) + + gens, common, k = [], [], 0 + + for gen in f_gens: + if gen in g_gens: + common.append(gen) + + for i, gen in enumerate(g_gens): + if gen in common: + g_gens[i], k = common[k], k + 1 + + for gen in common: + i = f_gens.index(gen) + + gens.extend(f_gens[:i]) + f_gens = f_gens[i + 1:] + + i = g_gens.index(gen) + + gens.extend(g_gens[:i]) + g_gens = g_gens[i + 1:] + + gens.append(gen) + + gens.extend(f_gens) + gens.extend(g_gens) + + return tuple(gens) + + +def _analyze_gens(gens): + """Support for passing generators as `*gens` and `[gens]`. """ + if len(gens) == 1 and hasattr(gens[0], '__iter__'): + return tuple(gens[0]) + else: + return tuple(gens) + + +def _sort_factors(factors, **args): + """Sort low-level factors in increasing 'complexity' order. """ + + # XXX: GF(p) does not support comparisons so we need a key function to sort + # the factors if python-flint is being used. A better solution might be to + # add a sort key method to each domain. + def order_key(factor): + if isinstance(factor, _GF_types): + return int(factor) + elif isinstance(factor, list): + return [order_key(f) for f in factor] + else: + return factor + + def order_if_multiple_key(factor): + (f, n) = factor + return (len(f), n, order_key(f)) + + def order_no_multiple_key(f): + return (len(f), order_key(f)) + + if args.get('multiple', True): + return sorted(factors, key=order_if_multiple_key) + else: + return sorted(factors, key=order_no_multiple_key) + + +illegal_types = [type(obj) for obj in _illegal] +finf = [float(i) for i in _illegal[1:3]] + + +def _not_a_coeff(expr): + """Do not treat NaN and infinities as valid polynomial coefficients. """ + if type(expr) in illegal_types or expr in finf: + return True + if isinstance(expr, float) and float(expr) != expr: + return True # nan + return # could be + + +def _parallel_dict_from_expr_if_gens(exprs, opt): + """Transform expressions into a multinomial form given generators. """ + k, indices = len(opt.gens), {} + + for i, g in enumerate(opt.gens): + indices[g] = i + + polys = [] + + for expr in exprs: + poly = {} + + if expr.is_Equality: + expr = expr.lhs - expr.rhs + + for term in Add.make_args(expr): + coeff, monom = [], [0]*k + + for factor in Mul.make_args(term): + if not _not_a_coeff(factor) and factor.is_Number: + coeff.append(factor) + else: + try: + if opt.series is False: + base, exp = decompose_power(factor) + + if exp < 0: + exp, base = -exp, Pow(base, -S.One) + else: + base, exp = decompose_power_rat(factor) + + monom[indices[base]] = exp + except KeyError: + if not factor.has_free(*opt.gens): + coeff.append(factor) + else: + raise PolynomialError("%s contains an element of " + "the set of generators." % factor) + + monom = tuple(monom) + + if monom in poly: + poly[monom] += Mul(*coeff) + else: + poly[monom] = Mul(*coeff) + + polys.append(poly) + + return polys, opt.gens + + +def _parallel_dict_from_expr_no_gens(exprs, opt): + """Transform expressions into a multinomial form and figure out generators. """ + if opt.domain is not None: + def _is_coeff(factor): + return factor in opt.domain + elif opt.extension is True: + def _is_coeff(factor): + return factor.is_algebraic + elif opt.greedy is not False: + def _is_coeff(factor): + return factor is S.ImaginaryUnit + else: + def _is_coeff(factor): + return factor.is_number + + gens, reprs = set(), [] + + for expr in exprs: + terms = [] + + if expr.is_Equality: + expr = expr.lhs - expr.rhs + + for term in Add.make_args(expr): + coeff, elements = [], {} + + for factor in Mul.make_args(term): + if not _not_a_coeff(factor) and (factor.is_Number or _is_coeff(factor)): + coeff.append(factor) + else: + if opt.series is False: + base, exp = decompose_power(factor) + + if exp < 0: + exp, base = -exp, Pow(base, -S.One) + else: + base, exp = decompose_power_rat(factor) + + elements[base] = elements.setdefault(base, 0) + exp + gens.add(base) + + terms.append((coeff, elements)) + + reprs.append(terms) + + gens = _sort_gens(gens, opt=opt) + k, indices = len(gens), {} + + for i, g in enumerate(gens): + indices[g] = i + + polys = [] + + for terms in reprs: + poly = {} + + for coeff, term in terms: + monom = [0]*k + + for base, exp in term.items(): + monom[indices[base]] = exp + + monom = tuple(monom) + + if monom in poly: + poly[monom] += Mul(*coeff) + else: + poly[monom] = Mul(*coeff) + + polys.append(poly) + + return polys, tuple(gens) + + +def _dict_from_expr_if_gens(expr, opt): + """Transform an expression into a multinomial form given generators. """ + (poly,), gens = _parallel_dict_from_expr_if_gens((expr,), opt) + return poly, gens + + +def _dict_from_expr_no_gens(expr, opt): + """Transform an expression into a multinomial form and figure out generators. """ + (poly,), gens = _parallel_dict_from_expr_no_gens((expr,), opt) + return poly, gens + + +def parallel_dict_from_expr(exprs, **args): + """Transform expressions into a multinomial form. """ + reps, opt = _parallel_dict_from_expr(exprs, build_options(args)) + return reps, opt.gens + + +def _parallel_dict_from_expr(exprs, opt): + """Transform expressions into a multinomial form. """ + if opt.expand is not False: + exprs = [ expr.expand() for expr in exprs ] + + if any(expr.is_commutative is False for expr in exprs): + raise PolynomialError('non-commutative expressions are not supported') + + if opt.gens: + reps, gens = _parallel_dict_from_expr_if_gens(exprs, opt) + else: + reps, gens = _parallel_dict_from_expr_no_gens(exprs, opt) + + return reps, opt.clone({'gens': gens}) + + +def dict_from_expr(expr, **args): + """Transform an expression into a multinomial form. """ + rep, opt = _dict_from_expr(expr, build_options(args)) + return rep, opt.gens + + +def _dict_from_expr(expr, opt): + """Transform an expression into a multinomial form. """ + if expr.is_commutative is False: + raise PolynomialError('non-commutative expressions are not supported') + + def _is_expandable_pow(expr): + return (expr.is_Pow and expr.exp.is_positive and expr.exp.is_Integer + and expr.base.is_Add) + + if opt.expand is not False: + if not isinstance(expr, (Expr, Eq)): + raise PolynomialError('expression must be of type Expr') + expr = expr.expand() + # TODO: Integrate this into expand() itself + while any(_is_expandable_pow(i) or i.is_Mul and + any(_is_expandable_pow(j) for j in i.args) for i in + Add.make_args(expr)): + + expr = expand_multinomial(expr) + while any(i.is_Mul and any(j.is_Add for j in i.args) for i in Add.make_args(expr)): + expr = expand_mul(expr) + + if opt.gens: + rep, gens = _dict_from_expr_if_gens(expr, opt) + else: + rep, gens = _dict_from_expr_no_gens(expr, opt) + + return rep, opt.clone({'gens': gens}) + + +def expr_from_dict(rep, *gens): + """Convert a multinomial form into an expression. """ + result = [] + + for monom, coeff in rep.items(): + term = [coeff] + for g, m in zip(gens, monom): + if m: + term.append(Pow(g, m)) + + result.append(Mul(*term)) + + return Add(*result) + +parallel_dict_from_basic = parallel_dict_from_expr +dict_from_basic = dict_from_expr +basic_from_dict = expr_from_dict + + +def _dict_reorder(rep, gens, new_gens): + """Reorder levels using dict representation. """ + gens = list(gens) + + monoms = rep.keys() + coeffs = rep.values() + + new_monoms = [ [] for _ in range(len(rep)) ] + used_indices = set() + + for gen in new_gens: + try: + j = gens.index(gen) + used_indices.add(j) + + for M, new_M in zip(monoms, new_monoms): + new_M.append(M[j]) + except ValueError: + for new_M in new_monoms: + new_M.append(0) + + for i, _ in enumerate(gens): + if i not in used_indices: + for monom in monoms: + if monom[i]: + raise GeneratorsError("unable to drop generators") + + return map(tuple, new_monoms), coeffs + + +class PicklableWithSlots: + """ + Mixin class that allows to pickle objects with ``__slots__``. + + Examples + ======== + + First define a class that mixes :class:`PicklableWithSlots` in:: + + >>> from sympy.polys.polyutils import PicklableWithSlots + >>> class Some(PicklableWithSlots): + ... __slots__ = ('foo', 'bar') + ... + ... def __init__(self, foo, bar): + ... self.foo = foo + ... self.bar = bar + + To make :mod:`pickle` happy in doctest we have to use these hacks:: + + >>> import builtins + >>> builtins.Some = Some + >>> from sympy.polys import polyutils + >>> polyutils.Some = Some + + Next lets see if we can create an instance, pickle it and unpickle:: + + >>> some = Some('abc', 10) + >>> some.foo, some.bar + ('abc', 10) + + >>> from pickle import dumps, loads + >>> some2 = loads(dumps(some)) + + >>> some2.foo, some2.bar + ('abc', 10) + + """ + + __slots__ = () + + def __getstate__(self, cls=None): + if cls is None: + # This is the case for the instance that gets pickled + cls = self.__class__ + + d = {} + + # Get all data that should be stored from super classes + for c in cls.__bases__: + # XXX: Python 3.11 defines object.__getstate__ and it does not + # accept any arguments so we need to make sure not to call it with + # an argument here. To be compatible with Python < 3.11 we need to + # be careful not to assume that c or object has a __getstate__ + # method though. + getstate = getattr(c, "__getstate__", None) + objstate = getattr(object, "__getstate__", None) + if getstate is not None and getstate is not objstate: + d.update(getstate(self, c)) + + # Get all information that should be stored from cls and return the dict + for name in cls.__slots__: + if hasattr(self, name): + d[name] = getattr(self, name) + + return d + + def __setstate__(self, d): + # All values that were pickled are now assigned to a fresh instance + for name, value in d.items(): + setattr(self, name, value) + + +class IntegerPowerable: + r""" + Mixin class for classes that define a `__mul__` method, and want to be + raised to integer powers in the natural way that follows. Implements + powering via binary expansion, for efficiency. + + By default, only integer powers $\geq 2$ are supported. To support the + first, zeroth, or negative powers, override the corresponding methods, + `_first_power`, `_zeroth_power`, `_negative_power`, below. + """ + + def __pow__(self, e, modulo=None): + if e < 2: + try: + if e == 1: + return self._first_power() + elif e == 0: + return self._zeroth_power() + else: + return self._negative_power(e, modulo=modulo) + except NotImplementedError: + return NotImplemented + else: + bits = [int(d) for d in reversed(bin(e)[2:])] + n = len(bits) + p = self + first = True + for i in range(n): + if bits[i]: + if first: + r = p + first = False + else: + r *= p + if modulo is not None: + r %= modulo + if i < n - 1: + p *= p + if modulo is not None: + p %= modulo + return r + + def _negative_power(self, e, modulo=None): + """ + Compute inverse of self, then raise that to the abs(e) power. + For example, if the class has an `inv()` method, + return self.inv() ** abs(e) % modulo + """ + raise NotImplementedError + + def _zeroth_power(self): + """Return unity element of algebraic struct to which self belongs.""" + raise NotImplementedError + + def _first_power(self): + """Return a copy of self.""" + raise NotImplementedError + + +_GF_types: tuple[type, ...] + + +if GROUND_TYPES == 'flint': + import flint + _GF_types = (flint.nmod, flint.fmpz_mod) +else: + from sympy.polys.domains.modularinteger import ModularInteger + flint = None + _GF_types = (ModularInteger,) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/puiseux.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/puiseux.py new file mode 100644 index 0000000000000000000000000000000000000000..446dc9c1a5e0d873cdf23da37d2c2430ba0bac6e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/puiseux.py @@ -0,0 +1,795 @@ +""" +Puiseux rings. These are used by the ring_series module to represented +truncated Puiseux series. Elements of a Puiseux ring are like polynomials +except that the exponents can be negative or rational rather than just +non-negative integers. +""" + +# Previously the ring_series module used PolyElement to represent Puiseux +# series. This is problematic because it means that PolyElement has to support +# negative and non-integer exponents which most polynomial representations do +# not support. This module provides an implementation of a ring for Puiseux +# series that can be used by ring_series without breaking the basic invariants +# of polynomial rings. +# +# Ideally there would be more of a proper series type that can keep track of +# not just the leading terms of a truncated series but also the precision +# of the series. For now the rings here are just introduced to keep the +# interface that ring_series was using before. + +from __future__ import annotations + +from sympy.polys.domains import QQ +from sympy.polys.rings import PolyRing, PolyElement +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.external.gmpy import gcd, lcm + + +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from typing import Any, Unpack + from sympy.core.expr import Expr + from sympy.polys.domains import Domain + from collections.abc import Iterable, Iterator + + +def puiseux_ring( + symbols: str | list[Expr], domain: Domain +) -> tuple[PuiseuxRing, Unpack[tuple[PuiseuxPoly, ...]]]: + """Construct a Puiseux ring. + + This function constructs a Puiseux ring with the given symbols and domain. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x, y = puiseux_ring('x y', QQ) + >>> R + PuiseuxRing((x, y), QQ) + >>> p = 5*x**QQ(1,2) + 7/y + >>> p + 7*y**(-1) + 5*x**(1/2) + """ + ring = PuiseuxRing(symbols, domain) + return (ring,) + ring.gens # type: ignore + + +class PuiseuxRing: + """Ring of Puiseux polynomials. + + A Puiseux polynomial is a truncated Puiseux series. The exponents of the + monomials can be negative or rational numbers. This ring is used by the + ring_series module: + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> from sympy.polys.ring_series import rs_exp, rs_nth_root + >>> ring, x, y = puiseux_ring('x y', QQ) + >>> f = x**2 + y**3 + >>> f + y**3 + x**2 + >>> f.diff(x) + 2*x + >>> rs_exp(x, x, 5) + 1 + x + 1/2*x**2 + 1/6*x**3 + 1/24*x**4 + + Importantly the Puiseux ring can represent truncated series with negative + and fractional exponents: + + >>> f = 1/x + 1/y**2 + >>> f + x**(-1) + y**(-2) + >>> f.diff(x) + -1*x**(-2) + + >>> rs_nth_root(8*x + x**2 + x**3, 3, x, 5) + 2*x**(1/3) + 1/12*x**(4/3) + 23/288*x**(7/3) + -139/20736*x**(10/3) + + See Also + ======== + + sympy.polys.ring_series.rs_series + PuiseuxPoly + """ + def __init__(self, symbols: str | list[Expr], domain: Domain): + + poly_ring = PolyRing(symbols, domain) + + domain = poly_ring.domain + ngens = poly_ring.ngens + + self.poly_ring = poly_ring + self.domain = domain + + self.symbols = poly_ring.symbols + self.gens = tuple([self.from_poly(g) for g in poly_ring.gens]) + self.ngens = ngens + + self.zero = self.from_poly(poly_ring.zero) + self.one = self.from_poly(poly_ring.one) + + self.zero_monom = poly_ring.zero_monom # type: ignore + self.monomial_mul = poly_ring.monomial_mul # type: ignore + + def __repr__(self) -> str: + return f"PuiseuxRing({self.symbols}, {self.domain})" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, PuiseuxRing): + return NotImplemented + return self.symbols == other.symbols and self.domain == other.domain + + def from_poly(self, poly: PolyElement) -> PuiseuxPoly: + """Create a Puiseux polynomial from a polynomial. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.puiseux import puiseux_ring + >>> R1, x1 = ring('x', QQ) + >>> R2, x2 = puiseux_ring('x', QQ) + >>> R2.from_poly(x1**2) + x**2 + """ + return PuiseuxPoly(poly, self) + + def from_dict(self, terms: dict[tuple[int, ...], Any]) -> PuiseuxPoly: + """Create a Puiseux polynomial from a dictionary of terms. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x = puiseux_ring('x', QQ) + >>> R.from_dict({(QQ(1,2),): QQ(3)}) + 3*x**(1/2) + """ + return PuiseuxPoly.from_dict(terms, self) + + def from_int(self, n: int) -> PuiseuxPoly: + """Create a Puiseux polynomial from an integer. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x = puiseux_ring('x', QQ) + >>> R.from_int(3) + 3 + """ + return self.from_poly(self.poly_ring(n)) + + def domain_new(self, arg: Any) -> Any: + """Create a new element of the domain. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x = puiseux_ring('x', QQ) + >>> R.domain_new(3) + 3 + >>> QQ.of_type(_) + True + """ + return self.poly_ring.domain_new(arg) + + def ground_new(self, arg: Any) -> PuiseuxPoly: + """Create a new element from a ground element. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring, PuiseuxPoly + >>> R, x = puiseux_ring('x', QQ) + >>> R.ground_new(3) + 3 + >>> isinstance(_, PuiseuxPoly) + True + """ + return self.from_poly(self.poly_ring.ground_new(arg)) + + def __call__(self, arg: Any) -> PuiseuxPoly: + """Coerce an element into the ring. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x = puiseux_ring('x', QQ) + >>> R(3) + 3 + >>> R({(QQ(1,2),): QQ(3)}) + 3*x**(1/2) + """ + if isinstance(arg, dict): + return self.from_dict(arg) + else: + return self.from_poly(self.poly_ring(arg)) + + def index(self, x: PuiseuxPoly) -> int: + """Return the index of a generator. + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x, y = puiseux_ring('x y', QQ) + >>> R.index(x) + 0 + >>> R.index(y) + 1 + """ + return self.gens.index(x) + + +def _div_poly_monom(poly: PolyElement, monom: Iterable[int]) -> PolyElement: + ring = poly.ring + div = ring.monomial_div + return ring.from_dict({div(m, monom): c for m, c in poly.terms()}) + + +def _mul_poly_monom(poly: PolyElement, monom: Iterable[int]) -> PolyElement: + ring = poly.ring + mul = ring.monomial_mul + return ring.from_dict({mul(m, monom): c for m, c in poly.terms()}) + + +def _div_monom(monom: Iterable[int], div: Iterable[int]) -> tuple[int, ...]: + return tuple(mi - di for mi, di in zip(monom, div)) + + +class PuiseuxPoly: + """Puiseux polynomial. Represents a truncated Puiseux series. + + See the :class:`PuiseuxRing` class for more information. + + >>> from sympy import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x, y = puiseux_ring('x, y', QQ) + >>> p = 5*x**2 + 7*y**3 + >>> p + 7*y**3 + 5*x**2 + + The internal representation of a Puiseux polynomial wraps a normal + polynomial. To support negative powers the polynomial is considered to be + divided by a monomial. + + >>> p2 = 1/x + 1/y**2 + >>> p2.monom # x*y**2 + (1, 2) + >>> p2.poly + x + y**2 + >>> (y**2 + x) / (x*y**2) == p2 + True + + To support fractional powers the polynomial is considered to be a function + of ``x**(1/nx), y**(1/ny), ...``. The representation keeps track of a + monomial and a list of exponent denominators so that the polynomial can be + used to represent both negative and fractional powers. + + >>> p3 = x**QQ(1,2) + y**QQ(2,3) + >>> p3.ns + (2, 3) + >>> p3.poly + x + y**2 + + See Also + ======== + + sympy.polys.puiseux.PuiseuxRing + sympy.polys.rings.PolyElement + """ + + ring: PuiseuxRing + poly: PolyElement + monom: tuple[int, ...] | None + ns: tuple[int, ...] | None + + def __new__(cls, poly: PolyElement, ring: PuiseuxRing) -> PuiseuxPoly: + return cls._new(ring, poly, None, None) + + @classmethod + def _new( + cls, + ring: PuiseuxRing, + poly: PolyElement, + monom: tuple[int, ...] | None, + ns: tuple[int, ...] | None, + ) -> PuiseuxPoly: + poly, monom, ns = cls._normalize(poly, monom, ns) + return cls._new_raw(ring, poly, monom, ns) + + @classmethod + def _new_raw( + cls, + ring: PuiseuxRing, + poly: PolyElement, + monom: tuple[int, ...] | None, + ns: tuple[int, ...] | None, + ) -> PuiseuxPoly: + obj = object.__new__(cls) + obj.ring = ring + obj.poly = poly + obj.monom = monom + obj.ns = ns + return obj + + def __eq__(self, other: Any) -> bool: + if isinstance(other, PuiseuxPoly): + return ( + self.poly == other.poly + and self.monom == other.monom + and self.ns == other.ns + ) + elif self.monom is None and self.ns is None: + return self.poly.__eq__(other) + else: + return NotImplemented + + @classmethod + def _normalize( + cls, + poly: PolyElement, + monom: tuple[int, ...] | None, + ns: tuple[int, ...] | None, + ) -> tuple[PolyElement, tuple[int, ...] | None, tuple[int, ...] | None]: + if monom is None and ns is None: + return poly, None, None + + if monom is not None: + degs = [max(d, 0) for d in poly.tail_degrees()] + if all(di >= mi for di, mi in zip(degs, monom)): + poly = _div_poly_monom(poly, monom) + monom = None + elif any(degs): + poly = _div_poly_monom(poly, degs) + monom = _div_monom(monom, degs) + + if ns is not None: + factors_d, [poly_d] = poly.deflate() + degrees = poly.degrees() + monom_d = monom if monom is not None else [0] * len(degrees) + ns_new = [] + monom_new = [] + inflations = [] + for fi, ni, di, mi in zip(factors_d, ns, degrees, monom_d): + if di == 0: + g = gcd(ni, mi) + else: + g = gcd(fi, ni, mi) + ns_new.append(ni // g) + monom_new.append(mi // g) + inflations.append(fi // g) + + if any(infl > 1 for infl in inflations): + poly_d = poly_d.inflate(inflations) + + poly = poly_d + + if monom is not None: + monom = tuple(monom_new) + + if all(n == 1 for n in ns_new): + ns = None + else: + ns = tuple(ns_new) + + return poly, monom, ns + + @classmethod + def _monom_fromint( + cls, + monom: tuple[int, ...], + dmonom: tuple[int, ...] | None, + ns: tuple[int, ...] | None, + ) -> tuple[Any, ...]: + if dmonom is not None and ns is not None: + return tuple(QQ(mi - di, ni) for mi, di, ni in zip(monom, dmonom, ns)) + elif dmonom is not None: + return tuple(QQ(mi - di) for mi, di in zip(monom, dmonom)) + elif ns is not None: + return tuple(QQ(mi, ni) for mi, ni in zip(monom, ns)) + else: + return tuple(QQ(mi) for mi in monom) + + @classmethod + def _monom_toint( + cls, + monom: tuple[Any, ...], + dmonom: tuple[int, ...] | None, + ns: tuple[int, ...] | None, + ) -> tuple[int, ...]: + if dmonom is not None and ns is not None: + return tuple( + int((mi * ni).numerator + di) for mi, di, ni in zip(monom, dmonom, ns) + ) + elif dmonom is not None: + return tuple(int(mi.numerator + di) for mi, di in zip(monom, dmonom)) + elif ns is not None: + return tuple(int((mi * ni).numerator) for mi, ni in zip(monom, ns)) + else: + return tuple(int(mi.numerator) for mi in monom) + + def itermonoms(self) -> Iterator[tuple[Any, ...]]: + """Iterate over the monomials of a Puiseux polynomial. + + >>> from sympy import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x, y = puiseux_ring('x, y', QQ) + >>> p = 5*x**2 + 7*y**3 + >>> list(p.itermonoms()) + [(2, 0), (0, 3)] + >>> p[(2, 0)] + 5 + """ + monom, ns = self.monom, self.ns + for m in self.poly.itermonoms(): + yield self._monom_fromint(m, monom, ns) + + def monoms(self) -> list[tuple[Any, ...]]: + """Return a list of the monomials of a Puiseux polynomial.""" + return list(self.itermonoms()) + + def __iter__(self) -> Iterator[tuple[tuple[Any, ...], Any]]: + return self.itermonoms() + + def __getitem__(self, monom: tuple[int, ...]) -> Any: + monom = self._monom_toint(monom, self.monom, self.ns) + return self.poly[monom] + + def __len__(self) -> int: + return len(self.poly) + + def iterterms(self) -> Iterator[tuple[tuple[Any, ...], Any]]: + """Iterate over the terms of a Puiseux polynomial. + + >>> from sympy import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x, y = puiseux_ring('x, y', QQ) + >>> p = 5*x**2 + 7*y**3 + >>> list(p.iterterms()) + [((2, 0), 5), ((0, 3), 7)] + """ + monom, ns = self.monom, self.ns + for m, coeff in self.poly.iterterms(): + mq = self._monom_fromint(m, monom, ns) + yield mq, coeff + + def terms(self) -> list[tuple[tuple[Any, ...], Any]]: + """Return a list of the terms of a Puiseux polynomial.""" + return list(self.iterterms()) + + @property + def is_term(self) -> bool: + """Return True if the Puiseux polynomial is a single term.""" + return self.poly.is_term + + def to_dict(self) -> dict[tuple[int, ...], Any]: + """Return a dictionary representation of a Puiseux polynomial.""" + return dict(self.iterterms()) + + @classmethod + def from_dict( + cls, terms: dict[tuple[Any, ...], Any], ring: PuiseuxRing + ) -> PuiseuxPoly: + """Create a Puiseux polynomial from a dictionary of terms. + + >>> from sympy import QQ + >>> from sympy.polys.puiseux import puiseux_ring, PuiseuxPoly + >>> R, x = puiseux_ring('x', QQ) + >>> PuiseuxPoly.from_dict({(QQ(1,2),): QQ(3)}, R) + 3*x**(1/2) + >>> R.from_dict({(QQ(1,2),): QQ(3)}) + 3*x**(1/2) + """ + ns = [1] * ring.ngens + mon = [0] * ring.ngens + for mo in terms: + ns = [lcm(n, m.denominator) for n, m in zip(ns, mo)] + mon = [min(m, n) for m, n in zip(mo, mon)] + + if not any(mon): + monom = None + else: + monom = tuple(-int((m * n).numerator) for m, n in zip(mon, ns)) + + if all(n == 1 for n in ns): + ns_final = None + else: + ns_final = tuple(ns) + + terms_p = {cls._monom_toint(m, monom, ns_final): coeff for m, coeff in terms.items()} + + poly = ring.poly_ring.from_dict(terms_p) + + return cls._new(ring, poly, monom, ns_final) + + def as_expr(self) -> Expr: + """Convert a Puiseux polynomial to :class:`~sympy.core.expr.Expr`. + + >>> from sympy import QQ, Expr + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x = puiseux_ring('x', QQ) + >>> p = 5*x**2 + 7*x**3 + >>> p.as_expr() + 7*x**3 + 5*x**2 + >>> isinstance(_, Expr) + True + """ + ring = self.ring + dom = ring.domain + symbols = ring.symbols + terms = [] + for monom, coeff in self.iterterms(): + coeff_expr = dom.to_sympy(coeff) + monoms_expr = [] + for i, m in enumerate(monom): + monoms_expr.append(symbols[i] ** m) + terms.append(Mul(coeff_expr, *monoms_expr)) + return Add(*terms) + + def __repr__(self) -> str: + + def format_power(base: str, exp: int) -> str: + if exp == 1: + return base + elif exp >= 0 and int(exp) == exp: + return f"{base}**{exp}" + else: + return f"{base}**({exp})" + + ring = self.ring + dom = ring.domain + + syms = [str(s) for s in ring.symbols] + terms_str = [] + for monom, coeff in sorted(self.terms()): + monom_str = "*".join(format_power(s, e) for s, e in zip(syms, monom) if e) + if coeff == dom.one: + if monom_str: + terms_str.append(monom_str) + else: + terms_str.append("1") + elif not monom_str: + terms_str.append(str(coeff)) + else: + terms_str.append(f"{coeff}*{monom_str}") + + return " + ".join(terms_str) + + def _unify( + self, other: PuiseuxPoly + ) -> tuple[ + PolyElement, PolyElement, tuple[int, ...] | None, tuple[int, ...] | None + ]: + """Bring two Puiseux polynomials to a common monom and ns.""" + poly1, monom1, ns1 = self.poly, self.monom, self.ns + poly2, monom2, ns2 = other.poly, other.monom, other.ns + + if monom1 == monom2 and ns1 == ns2: + return poly1, poly2, monom1, ns1 + + if ns1 == ns2: + ns = ns1 + elif ns1 is not None and ns2 is not None: + ns = tuple(lcm(n1, n2) for n1, n2 in zip(ns1, ns2)) + f1 = [n // n1 for n, n1 in zip(ns, ns1)] + f2 = [n // n2 for n, n2 in zip(ns, ns2)] + poly1 = poly1.inflate(f1) + poly2 = poly2.inflate(f2) + if monom1 is not None: + monom1 = tuple(m * f for m, f in zip(monom1, f1)) + if monom2 is not None: + monom2 = tuple(m * f for m, f in zip(monom2, f2)) + elif ns2 is not None: + ns = ns2 + poly1 = poly1.inflate(ns) + if monom1 is not None: + monom1 = tuple(m * n for m, n in zip(monom1, ns)) + elif ns1 is not None: + ns = ns1 + poly2 = poly2.inflate(ns) + if monom2 is not None: + monom2 = tuple(m * n for m, n in zip(monom2, ns)) + else: + assert False + + if monom1 == monom2: + monom = monom1 + elif monom1 is not None and monom2 is not None: + monom = tuple(max(m1, m2) for m1, m2 in zip(monom1, monom2)) + poly1 = _mul_poly_monom(poly1, _div_monom(monom, monom1)) + poly2 = _mul_poly_monom(poly2, _div_monom(monom, monom2)) + elif monom2 is not None: + monom = monom2 + poly1 = _mul_poly_monom(poly1, monom2) + elif monom1 is not None: + monom = monom1 + poly2 = _mul_poly_monom(poly2, monom1) + else: + assert False + + return poly1, poly2, monom, ns + + def __pos__(self) -> PuiseuxPoly: + return self + + def __neg__(self) -> PuiseuxPoly: + return self._new_raw(self.ring, -self.poly, self.monom, self.ns) + + def __add__(self, other: Any) -> PuiseuxPoly: + if isinstance(other, PuiseuxPoly): + if self.ring != other.ring: + raise ValueError("Cannot add Puiseux polynomials from different rings") + return self._add(other) + domain = self.ring.domain + if isinstance(other, int): + return self._add_ground(domain.convert_from(QQ(other), QQ)) + elif domain.of_type(other): + return self._add_ground(other) + else: + return NotImplemented + + def __radd__(self, other: Any) -> PuiseuxPoly: + domain = self.ring.domain + if isinstance(other, int): + return self._add_ground(domain.convert_from(QQ(other), QQ)) + elif domain.of_type(other): + return self._add_ground(other) + else: + return NotImplemented + + def __sub__(self, other: Any) -> PuiseuxPoly: + if isinstance(other, PuiseuxPoly): + if self.ring != other.ring: + raise ValueError( + "Cannot subtract Puiseux polynomials from different rings" + ) + return self._sub(other) + domain = self.ring.domain + if isinstance(other, int): + return self._sub_ground(domain.convert_from(QQ(other), QQ)) + elif domain.of_type(other): + return self._sub_ground(other) + else: + return NotImplemented + + def __rsub__(self, other: Any) -> PuiseuxPoly: + domain = self.ring.domain + if isinstance(other, int): + return self._rsub_ground(domain.convert_from(QQ(other), QQ)) + elif domain.of_type(other): + return self._rsub_ground(other) + else: + return NotImplemented + + def __mul__(self, other: Any) -> PuiseuxPoly: + if isinstance(other, PuiseuxPoly): + if self.ring != other.ring: + raise ValueError( + "Cannot multiply Puiseux polynomials from different rings" + ) + return self._mul(other) + domain = self.ring.domain + if isinstance(other, int): + return self._mul_ground(domain.convert_from(QQ(other), QQ)) + elif domain.of_type(other): + return self._mul_ground(other) + else: + return NotImplemented + + def __rmul__(self, other: Any) -> PuiseuxPoly: + domain = self.ring.domain + if isinstance(other, int): + return self._mul_ground(domain.convert_from(QQ(other), QQ)) + elif domain.of_type(other): + return self._mul_ground(other) + else: + return NotImplemented + + def __pow__(self, other: Any) -> PuiseuxPoly: + if isinstance(other, int): + if other >= 0: + return self._pow_pint(other) + else: + return self._pow_nint(-other) + elif QQ.of_type(other): + return self._pow_rational(other) + else: + return NotImplemented + + def __truediv__(self, other: Any) -> PuiseuxPoly: + if isinstance(other, PuiseuxPoly): + if self.ring != other.ring: + raise ValueError( + "Cannot divide Puiseux polynomials from different rings" + ) + return self._mul(other._inv()) + domain = self.ring.domain + if isinstance(other, int): + return self._mul_ground(domain.convert_from(QQ(1, other), QQ)) + elif domain.of_type(other): + return self._div_ground(other) + else: + return NotImplemented + + def __rtruediv__(self, other: Any) -> PuiseuxPoly: + if isinstance(other, int): + return self._inv()._mul_ground(self.ring.domain.convert_from(QQ(other), QQ)) + elif self.ring.domain.of_type(other): + return self._inv()._mul_ground(other) + else: + return NotImplemented + + def _add(self, other: PuiseuxPoly) -> PuiseuxPoly: + poly1, poly2, monom, ns = self._unify(other) + return self._new(self.ring, poly1 + poly2, monom, ns) + + def _add_ground(self, ground: Any) -> PuiseuxPoly: + return self._add(self.ring.ground_new(ground)) + + def _sub(self, other: PuiseuxPoly) -> PuiseuxPoly: + poly1, poly2, monom, ns = self._unify(other) + return self._new(self.ring, poly1 - poly2, monom, ns) + + def _sub_ground(self, ground: Any) -> PuiseuxPoly: + return self._sub(self.ring.ground_new(ground)) + + def _rsub_ground(self, ground: Any) -> PuiseuxPoly: + return self.ring.ground_new(ground)._sub(self) + + def _mul(self, other: PuiseuxPoly) -> PuiseuxPoly: + poly1, poly2, monom, ns = self._unify(other) + if monom is not None: + monom = tuple(2 * e for e in monom) + return self._new(self.ring, poly1 * poly2, monom, ns) + + def _mul_ground(self, ground: Any) -> PuiseuxPoly: + return self._new_raw(self.ring, self.poly * ground, self.monom, self.ns) + + def _div_ground(self, ground: Any) -> PuiseuxPoly: + return self._new_raw(self.ring, self.poly / ground, self.monom, self.ns) + + def _pow_pint(self, n: int) -> PuiseuxPoly: + assert n >= 0 + monom = self.monom + if monom is not None: + monom = tuple(m * n for m in monom) + return self._new(self.ring, self.poly**n, monom, self.ns) + + def _pow_nint(self, n: int) -> PuiseuxPoly: + return self._inv()._pow_pint(n) + + def _pow_rational(self, n: Any) -> PuiseuxPoly: + if not self.is_term: + raise ValueError("Only monomials can be raised to a rational power") + [(monom, coeff)] = self.terms() + domain = self.ring.domain + if not domain.is_one(coeff): + raise ValueError("Only monomials can be raised to a rational power") + monom = tuple(m * n for m in monom) + return self.ring.from_dict({monom: domain.one}) + + def _inv(self) -> PuiseuxPoly: + if not self.is_term: + raise ValueError("Only terms can be inverted") + [(monom, coeff)] = self.terms() + domain = self.ring.domain + if not domain.is_Field and not domain.is_one(coeff): + raise ValueError("Cannot invert non-unit coefficient") + monom = tuple(-m for m in monom) + coeff = 1 / coeff + return self.ring.from_dict({monom: coeff}) + + def diff(self, x: PuiseuxPoly) -> PuiseuxPoly: + """Differentiate a Puiseux polynomial with respect to a variable. + + >>> from sympy import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> R, x, y = puiseux_ring('x, y', QQ) + >>> p = 5*x**2 + 7*y**3 + >>> p.diff(x) + 10*x + >>> p.diff(y) + 21*y**2 + """ + ring = self.ring + i = ring.index(x) + g = {} + for expv, coeff in self.iterterms(): + n = expv[i] + if n: + e = list(expv) + e[i] -= 1 + g[tuple(e)] = coeff * n + return ring(g) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rationaltools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rationaltools.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca513ff2d4af96baaaf1c82caf501750b1524da --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rationaltools.py @@ -0,0 +1,85 @@ +"""Tools for manipulation of rational expressions. """ + + +from sympy.core import Basic, Add, sympify +from sympy.core.exprtools import gcd_terms +from sympy.utilities import public +from sympy.utilities.iterables import iterable + + +@public +def together(expr, deep=False, fraction=True): + """ + Denest and combine rational expressions using symbolic methods. + + This function takes an expression or a container of expressions + and puts it (them) together by denesting and combining rational + subexpressions. No heroic measures are taken to minimize degree + of the resulting numerator and denominator. To obtain completely + reduced expression use :func:`~.cancel`. However, :func:`~.together` + can preserve as much as possible of the structure of the input + expression in the output (no expansion is performed). + + A wide variety of objects can be put together including lists, + tuples, sets, relational objects, integrals and others. It is + also possible to transform interior of function applications, + by setting ``deep`` flag to ``True``. + + By definition, :func:`~.together` is a complement to :func:`~.apart`, + so ``apart(together(expr))`` should return expr unchanged. Note + however, that :func:`~.together` uses only symbolic methods, so + it might be necessary to use :func:`~.cancel` to perform algebraic + simplification and minimize degree of the numerator and denominator. + + Examples + ======== + + >>> from sympy import together, exp + >>> from sympy.abc import x, y, z + + >>> together(1/x + 1/y) + (x + y)/(x*y) + >>> together(1/x + 1/y + 1/z) + (x*y + x*z + y*z)/(x*y*z) + + >>> together(1/(x*y) + 1/y**2) + (x + y)/(x*y**2) + + >>> together(1/(1 + 1/x) + 1/(1 + 1/y)) + (x*(y + 1) + y*(x + 1))/((x + 1)*(y + 1)) + + >>> together(exp(1/x + 1/y)) + exp(1/y + 1/x) + >>> together(exp(1/x + 1/y), deep=True) + exp((x + y)/(x*y)) + + >>> together(1/exp(x) + 1/(x*exp(x))) + (x + 1)*exp(-x)/x + + >>> together(1/exp(2*x) + 1/(x*exp(3*x))) + (x*exp(x) + 1)*exp(-3*x)/x + + """ + def _together(expr): + if isinstance(expr, Basic): + if expr.is_Atom or (expr.is_Function and not deep): + return expr + elif expr.is_Add: + return gcd_terms(list(map(_together, Add.make_args(expr))), fraction=fraction) + elif expr.is_Pow: + base = _together(expr.base) + + if deep: + exp = _together(expr.exp) + else: + exp = expr.exp + + return expr.func(base, exp) + else: + return expr.func(*[ _together(arg) for arg in expr.args ]) + elif iterable(expr): + return expr.__class__([ _together(ex) for ex in expr ]) + + return expr + + return _together(sympify(expr)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/ring_series.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/ring_series.py new file mode 100644 index 0000000000000000000000000000000000000000..b4333f0add9365991794d920a2699722900e8a5e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/ring_series.py @@ -0,0 +1,2127 @@ +"""Power series evaluation and manipulation using sparse Polynomials + +Implementing a new function +--------------------------- + +There are a few things to be kept in mind when adding a new function here:: + + - The implementation should work on all possible input domains/rings. + Special cases include the ``EX`` ring and a constant term in the series + to be expanded. There can be two types of constant terms in the series: + + + A constant value or symbol. + + A term of a multivariate series not involving the generator, with + respect to which the series is to expanded. + + Strictly speaking, a generator of a ring should not be considered a + constant. However, for series expansion both the cases need similar + treatment (as the user does not care about inner details), i.e, use an + addition formula to separate the constant part and the variable part (see + rs_sin for reference). + + - All the algorithms used here are primarily designed to work for Taylor + series (number of iterations in the algo equals the required order). + Hence, it becomes tricky to get the series of the right order if a + Puiseux series is input. Use rs_puiseux? in your function if your + algorithm is not designed to handle fractional powers. + +Extending rs_series +------------------- + +To make a function work with rs_series you need to do two things:: + + - Many sure it works with a constant term (as explained above). + - If the series contains constant terms, you might need to extend its ring. + You do so by adding the new terms to the rings as generators. + ``PolyRing.compose`` and ``PolyRing.add_gens`` are two functions that do + so and need to be called every time you expand a series containing a + constant term. + +Look at rs_sin and rs_series for further reference. + +""" + +from sympy.polys.domains import QQ, EX +from sympy.polys.rings import PolyElement, ring, sring +from sympy.polys.puiseux import PuiseuxPoly +from sympy.polys.polyerrors import DomainError +from sympy.polys.monomials import (monomial_min, monomial_mul, monomial_div, + monomial_ldiv) +from mpmath.libmp.libintmath import ifac +from sympy.core import PoleError, Function, Expr +from sympy.core.numbers import Rational +from sympy.core.intfunc import igcd +from sympy.functions import (sin, cos, tan, atan, exp, atanh, asinh, tanh, log, + ceiling, sinh, cosh) +from sympy.utilities.misc import as_int +from mpmath.libmp.libintmath import giant_steps +import math + + +def _invert_monoms(p1): + """ + Compute ``x**n * p1(1/x)`` for a univariate polynomial ``p1`` in ``x``. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import _invert_monoms + >>> R, x = ring('x', ZZ) + >>> p = x**2 + 2*x + 3 + >>> _invert_monoms(p) + 3*x**2 + 2*x + 1 + + See Also + ======== + + sympy.polys.densebasic.dup_reverse + """ + terms = list(p1.items()) + terms.sort() + deg = p1.degree() + R = p1.ring + p = R.zero + cv = p1.listcoeffs() + mv = p1.listmonoms() + for mvi, cvi in zip(mv, cv): + p[(deg - mvi[0],)] = cvi + return p + +def _giant_steps(target): + """Return a list of precision steps for the Newton's method""" + # We use ceil here because giant_steps cannot handle flint.fmpq + res = giant_steps(2, math.ceil(target)) + if res[0] != 2: + res = [2] + res + return res + +def rs_trunc(p1, x, prec): + """ + Truncate the series in the ``x`` variable with precision ``prec``, + that is, modulo ``O(x**prec)`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_trunc + >>> R, x = ring('x', QQ) + >>> p = x**10 + x**5 + x + 1 + >>> rs_trunc(p, x, 12) + x**10 + x**5 + x + 1 + >>> rs_trunc(p, x, 10) + x**5 + x + 1 + """ + R = p1.ring + p = {} + i = R.gens.index(x) + for exp1 in p1: + if exp1[i] >= prec: + continue + p[exp1] = p1[exp1] + return R(p) + +def rs_is_puiseux(p, x): + """ + Test if ``p`` is Puiseux series in ``x``. + + Raise an exception if it has a negative power in ``x``. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> from sympy.polys.ring_series import rs_is_puiseux + >>> R, x = puiseux_ring('x', QQ) + >>> p = x**QQ(2,5) + x**QQ(2,3) + x + >>> rs_is_puiseux(p, x) + True + """ + index = p.ring.gens.index(x) + for k in p.itermonoms(): + if k[index] != int(k[index]): + return True + if k[index] < 0: + raise ValueError('The series is not regular in %s' % x) + return False + +def rs_puiseux(f, p, x, prec): + """ + Return the puiseux series for `f(p, x, prec)`. + + To be used when function ``f`` is implemented only for regular series. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> from sympy.polys.ring_series import rs_puiseux, rs_exp + >>> R, x = puiseux_ring('x', QQ) + >>> p = x**QQ(2,5) + x**QQ(2,3) + x + >>> rs_puiseux(rs_exp,p, x, 1) + 1 + x**(2/5) + x**(2/3) + 1/2*x**(4/5) + """ + index = p.ring.gens.index(x) + n = 1 + for k in p: + power = k[index] + if isinstance(power, Rational): + num, den = power.as_numer_denom() + n = int(n*den // igcd(n, den)) + elif power != int(power): + den = power.denominator + n = int(n*den // igcd(n, den)) + if n != 1: + p1 = pow_xin(p, index, n) + r = f(p1, x, prec*n) + n1 = QQ(1, n) + if isinstance(r, tuple): + r = tuple([pow_xin(rx, index, n1) for rx in r]) + else: + r = pow_xin(r, index, n1) + else: + r = f(p, x, prec) + return r + +def rs_puiseux2(f, p, q, x, prec): + """ + Return the puiseux series for `f(p, q, x, prec)`. + + To be used when function ``f`` is implemented only for regular series. + """ + index = p.ring.gens.index(x) + n = 1 + for k in p: + power = k[index] + if isinstance(power, Rational): + num, den = power.as_numer_denom() + n = n*den // igcd(n, den) + elif power != int(power): + den = power.denominator + n = n*den // igcd(n, den) + if n != 1: + p1 = pow_xin(p, index, n) + r = f(p1, q, x, prec*n) + n1 = QQ(1, n) + r = pow_xin(r, index, n1) + else: + r = f(p, q, x, prec) + return r + +def rs_mul(p1, p2, x, prec): + """ + Return the product of the given two series, modulo ``O(x**prec)``. + + ``x`` is the series variable or its position in the generators. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_mul + >>> R, x = ring('x', QQ) + >>> p1 = x**2 + 2*x + 1 + >>> p2 = x + 1 + >>> rs_mul(p1, p2, x, 3) + 3*x**2 + 3*x + 1 + """ + R = p1.ring + p = {} + if R.__class__ != p2.ring.__class__ or R != p2.ring: + raise ValueError('p1 and p2 must have the same ring') + iv = R.gens.index(x) + if not isinstance(p2, (PolyElement, PuiseuxPoly)): + raise ValueError('p2 must be a polynomial') + if R == p2.ring: + get = p.get + items2 = p2.terms() + items2.sort(key=lambda e: e[0][iv]) + if R.ngens == 1: + for exp1, v1 in p1.iterterms(): + for exp2, v2 in items2: + exp = exp1[0] + exp2[0] + if exp < prec: + exp = (exp, ) + p[exp] = get(exp, 0) + v1*v2 + else: + break + else: + monomial_mul = R.monomial_mul + for exp1, v1 in p1.iterterms(): + for exp2, v2 in items2: + if exp1[iv] + exp2[iv] < prec: + exp = monomial_mul(exp1, exp2) + p[exp] = get(exp, 0) + v1*v2 + else: + break + + return R(p) + +def rs_square(p1, x, prec): + """ + Square the series modulo ``O(x**prec)`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_square + >>> R, x = ring('x', QQ) + >>> p = x**2 + 2*x + 1 + >>> rs_square(p, x, 3) + 6*x**2 + 4*x + 1 + """ + R = p1.ring + p = {} + iv = R.gens.index(x) + get = p.get + items = p1.terms() + items.sort(key=lambda e: e[0][iv]) + monomial_mul = R.monomial_mul + for i in range(len(items)): + exp1, v1 = items[i] + for j in range(i): + exp2, v2 = items[j] + if exp1[iv] + exp2[iv] < prec: + exp = monomial_mul(exp1, exp2) + p[exp] = get(exp, 0) + v1*v2 + else: + break + p = {m: 2*v for m, v in p.items()} + get = p.get + for expv, v in p1.iterterms(): + if 2*expv[iv] < prec: + e2 = monomial_mul(expv, expv) + p[e2] = get(e2, 0) + v**2 + return R(p) + +def rs_pow(p1, n, x, prec): + """ + Return ``p1**n`` modulo ``O(x**prec)`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_pow + >>> R, x = ring('x', QQ) + >>> p = x + 1 + >>> rs_pow(p, 4, x, 3) + 6*x**2 + 4*x + 1 + """ + R = p1.ring + if isinstance(n, Rational): + np = int(n.p) + nq = int(n.q) + if nq != 1: + res = rs_nth_root(p1, nq, x, prec) + if np != 1: + res = rs_pow(res, np, x, prec) + else: + res = rs_pow(p1, np, x, prec) + return res + + n = as_int(n) + if n == 0: + if p1: + return R(1) + else: + raise ValueError('0**0 is undefined') + if n < 0: + p1 = rs_pow(p1, -n, x, prec) + return rs_series_inversion(p1, x, prec) + if n == 1: + return rs_trunc(p1, x, prec) + if n == 2: + return rs_square(p1, x, prec) + if n == 3: + p2 = rs_square(p1, x, prec) + return rs_mul(p1, p2, x, prec) + p = R(1) + while 1: + if n & 1: + p = rs_mul(p1, p, x, prec) + n -= 1 + if not n: + break + p1 = rs_square(p1, x, prec) + n = n // 2 + return p + +def rs_subs(p, rules, x, prec): + """ + Substitution with truncation according to the mapping in ``rules``. + + Return a series with precision ``prec`` in the generator ``x`` + + Note that substitutions are not done one after the other + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_subs + >>> R, x, y = ring('x, y', QQ) + >>> p = x**2 + y**2 + >>> rs_subs(p, {x: x+ y, y: x+ 2*y}, x, 3) + 2*x**2 + 6*x*y + 5*y**2 + >>> (x + y)**2 + (x + 2*y)**2 + 2*x**2 + 6*x*y + 5*y**2 + + which differs from + + >>> rs_subs(rs_subs(p, {x: x+ y}, x, 3), {y: x+ 2*y}, x, 3) + 5*x**2 + 12*x*y + 8*y**2 + + Parameters + ---------- + p : :class:`~.PolyElement` Input series. + rules : ``dict`` with substitution mappings. + x : :class:`~.PolyElement` in which the series truncation is to be done. + prec : :class:`~.Integer` order of the series after truncation. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_subs + >>> R, x, y = ring('x, y', QQ) + >>> rs_subs(x**2+y**2, {y: (x+y)**2}, x, 3) + 6*x**2*y**2 + x**2 + 4*x*y**3 + y**4 + """ + R = p.ring + ngens = R.ngens + d = R(0) + for i in range(ngens): + d[(i, 1)] = R.gens[i] + for var in rules: + d[(R.index(var), 1)] = rules[var] + p1 = R(0) + p_keys = sorted(p.keys()) + for expv in p_keys: + p2 = R(1) + for i in range(ngens): + power = expv[i] + if power == 0: + continue + if (i, power) not in d: + q, r = divmod(power, 2) + if r == 0 and (i, q) in d: + d[(i, power)] = rs_square(d[(i, q)], x, prec) + elif (i, power - 1) in d: + d[(i, power)] = rs_mul(d[(i, power - 1)], d[(i, 1)], + x, prec) + else: + d[(i, power)] = rs_pow(d[(i, 1)], power, x, prec) + p2 = rs_mul(p2, d[(i, power)], x, prec) + p1 += p2*p[expv] + return p1 + +def _has_constant_term(p, x): + """ + Check if ``p`` has a constant term in ``x`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import _has_constant_term + >>> R, x = ring('x', QQ) + >>> p = x**2 + x + 1 + >>> _has_constant_term(p, x) + True + """ + R = p.ring + iv = R.gens.index(x) + zm = R.zero_monom + a = [0]*R.ngens + a[iv] = 1 + miv = tuple(a) + return any(monomial_min(expv, miv) == zm for expv in p) + +def _get_constant_term(p, x): + """Return constant term in p with respect to x + + Note that it is not simply `p[R.zero_monom]` as there might be multiple + generators in the ring R. We want the `x`-free term which can contain other + generators. + """ + R = p.ring + i = R.gens.index(x) + zm = R.zero_monom + a = [0]*R.ngens + a[i] = 1 + miv = tuple(a) + c = 0 + for expv in p: + if monomial_min(expv, miv) == zm: + c += R({expv: p[expv]}) + return c + +def _check_series_var(p, x, name): + index = p.ring.gens.index(x) + m = min(p, key=lambda k: k[index])[index] + if m < 0: + raise PoleError("Asymptotic expansion of %s around [oo] not " + "implemented." % name) + return index, m + +def _series_inversion1(p, x, prec): + """ + Univariate series inversion ``1/p`` modulo ``O(x**prec)``. + + The Newton method is used. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import _series_inversion1 + >>> R, x = ring('x', QQ) + >>> p = x + 1 + >>> _series_inversion1(p, x, 4) + -x**3 + x**2 - x + 1 + """ + if rs_is_puiseux(p, x): + return rs_puiseux(_series_inversion1, p, x, prec) + R = p.ring + zm = R.zero_monom + c = p[zm] + + # giant_steps does not seem to work with PythonRational numbers with 1 as + # denominator. This makes sure such a number is converted to integer. + if prec == int(prec): + prec = int(prec) + + if zm not in p: + raise ValueError("No constant term in series") + if _has_constant_term(p - c, x): + raise ValueError("p cannot contain a constant term depending on " + "parameters") + if not R.domain.is_unit(c): + raise ValueError(f"Constant term {c} must be a unit in {R.domain}") + + one = R(1) + if R.domain is EX: + one = 1 + if c != one: + p1 = R(1)/c + else: + p1 = R(1) + for precx in _giant_steps(prec): + t = 1 - rs_mul(p1, p, x, precx) + p1 = p1 + rs_mul(p1, t, x, precx) + return p1 + +def rs_series_inversion(p, x, prec): + """ + Multivariate series inversion ``1/p`` modulo ``O(x**prec)``. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_series_inversion + >>> R, x, y = ring('x, y', QQ) + >>> rs_series_inversion(1 + x*y**2, x, 4) + -x**3*y**6 + x**2*y**4 - x*y**2 + 1 + >>> rs_series_inversion(1 + x*y**2, y, 4) + -x*y**2 + 1 + >>> rs_series_inversion(x + x**2, x, 4) + x**3 - x**2 + x - 1 + x**(-1) + """ + R = p.ring + if p == R.zero: + raise ZeroDivisionError + zm = R.zero_monom + index = R.gens.index(x) + m = min(p, key=lambda k: k[index])[index] + if m: + p = mul_xin(p, index, -m) + prec = prec + m + if zm not in p: + raise NotImplementedError("No constant term in series") + + if _has_constant_term(p - p[zm], x): + raise NotImplementedError("p - p[0] must not have a constant term in " + "the series variables") + r = _series_inversion1(p, x, prec) + if m != 0: + r = mul_xin(r, index, -m) + return r + +def _coefficient_t(p, t): + r"""Coefficient of `x_i**j` in p, where ``t`` = (i, j)""" + i, j = t + R = p.ring + expv1 = [0]*R.ngens + expv1[i] = j + expv1 = tuple(expv1) + p1 = R(0) + for expv in p: + if expv[i] == j: + p1[monomial_div(expv, expv1)] = p[expv] + return p1 + +def rs_series_reversion(p, x, n, y): + r""" + Reversion of a series. + + ``p`` is a series with ``O(x**n)`` of the form $p = ax + f(x)$ + where $a$ is a number different from 0. + + $f(x) = \sum_{k=2}^{n-1} a_kx_k$ + + Parameters + ========== + + a_k : Can depend polynomially on other variables, not indicated. + x : Variable with name x. + y : Variable with name y. + + Returns + ======= + + Solve $p = y$, that is, given $ax + f(x) - y = 0$, + find the solution $x = r(y)$ up to $O(y^n)$. + + Algorithm + ========= + + If $r_i$ is the solution at order $i$, then: + $ar_i + f(r_i) - y = O\left(y^{i + 1}\right)$ + + and if $r_{i + 1}$ is the solution at order $i + 1$, then: + $ar_{i + 1} + f(r_{i + 1}) - y = O\left(y^{i + 2}\right)$ + + We have, $r_{i + 1} = r_i + e$, such that, + $ae + f(r_i) = O\left(y^{i + 2}\right)$ + or $e = -f(r_i)/a$ + + So we use the recursion relation: + $r_{i + 1} = r_i - f(r_i)/a$ + with the boundary condition: $r_1 = y$ + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_series_reversion, rs_trunc + >>> R, x, y, a, b = ring('x, y, a, b', QQ) + >>> p = x - x**2 - 2*b*x**2 + 2*a*b*x**2 + >>> p1 = rs_series_reversion(p, x, 3, y); p1 + -2*y**2*a*b + 2*y**2*b + y**2 + y + >>> rs_trunc(p.compose(x, p1), y, 3) + y + """ + if rs_is_puiseux(p, x): + raise NotImplementedError + R = p.ring + nx = R.gens.index(x) + y = R(y) + ny = R.gens.index(y) + if _has_constant_term(p, x): + raise ValueError("p must not contain a constant term in the series " + "variable") + a = _coefficient_t(p, (nx, 1)) + zm = R.zero_monom + assert zm in a and len(a) == 1 + a = a[zm] + r = y/a + for i in range(2, n): + sp = rs_subs(p, {x: r}, y, i + 1) + sp = _coefficient_t(sp, (ny, i))*y**i + r -= sp/a + return r + +def rs_series_from_list(p, c, x, prec, concur=1): + """ + Return a series `sum c[n]*p**n` modulo `O(x**prec)`. + + It reduces the number of multiplications by summing concurrently. + + `ax = [1, p, p**2, .., p**(J - 1)]` + `s = sum(c[i]*ax[i]` for i in `range(r, (r + 1)*J))*p**((K - 1)*J)` + with `K >= (n + 1)/J` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_series_from_list, rs_trunc + >>> R, x = ring('x', QQ) + >>> p = x**2 + x + 1 + >>> c = [1, 2, 3] + >>> rs_series_from_list(p, c, x, 4) + 6*x**3 + 11*x**2 + 8*x + 6 + >>> rs_trunc(1 + 2*p + 3*p**2, x, 4) + 6*x**3 + 11*x**2 + 8*x + 6 + >>> pc = R.from_list(list(reversed(c))) + >>> rs_trunc(pc.compose(x, p), x, 4) + 6*x**3 + 11*x**2 + 8*x + 6 + + See Also + ======== + + sympy.polys.rings.PolyRing.compose + + """ + R = p.ring + n = len(c) + if not concur: + q = R(1) + s = c[0]*q + for i in range(1, n): + q = rs_mul(q, p, x, prec) + s += c[i]*q + return s + J = int(math.sqrt(n) + 1) + K, r = divmod(n, J) + if r: + K += 1 + ax = [R(1)] + q = R(1) + if len(p) < 20: + for i in range(1, J): + q = rs_mul(q, p, x, prec) + ax.append(q) + else: + for i in range(1, J): + if i % 2 == 0: + q = rs_square(ax[i//2], x, prec) + else: + q = rs_mul(q, p, x, prec) + ax.append(q) + # optimize using rs_square + pj = rs_mul(ax[-1], p, x, prec) + b = R(1) + s = R(0) + for k in range(K - 1): + r = J*k + s1 = c[r] + for j in range(1, J): + s1 += c[r + j]*ax[j] + s1 = rs_mul(s1, b, x, prec) + s += s1 + b = rs_mul(b, pj, x, prec) + if not b: + break + k = K - 1 + r = J*k + if r < n: + s1 = c[r]*R(1) + for j in range(1, J): + if r + j >= n: + break + s1 += c[r + j]*ax[j] + s1 = rs_mul(s1, b, x, prec) + s += s1 + return s + +def rs_diff(p, x): + """ + Return partial derivative of ``p`` with respect to ``x``. + + Parameters + ========== + + x : :class:`~.PolyElement` with respect to which ``p`` is differentiated. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_diff + >>> R, x, y = ring('x, y', QQ) + >>> p = x + x**2*y**3 + >>> rs_diff(p, x) + 2*x*y**3 + 1 + """ + R = p.ring + n = R.gens.index(x) + p1 = {} + mn = [0]*R.ngens + mn[n] = 1 + mn = tuple(mn) + for expv in p: + if expv[n]: + e = monomial_ldiv(expv, mn) + p1[e] = R.domain_new(p[expv]*expv[n]) + return R(p1) + +def rs_integrate(p, x): + """ + Integrate ``p`` with respect to ``x``. + + Parameters + ========== + + x : :class:`~.PolyElement` with respect to which ``p`` is integrated. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_integrate + >>> R, x, y = ring('x, y', QQ) + >>> p = x + x**2*y**3 + >>> rs_integrate(p, x) + 1/3*x**3*y**3 + 1/2*x**2 + """ + R = p.ring + p1 = {} + n = R.gens.index(x) + mn = [0]*R.ngens + mn[n] = 1 + mn = tuple(mn) + + for expv in p: + e = monomial_mul(expv, mn) + p1[e] = R.domain_new(p[expv]/(expv[n] + 1)) + return R(p1) + +def rs_fun(p, f, *args): + r""" + Function of a multivariate series computed by substitution. + + The case with f method name is used to compute `rs\_tan` and `rs\_nth\_root` + of a multivariate series: + + `rs\_fun(p, tan, iv, prec)` + + tan series is first computed for a dummy variable _x, + i.e, `rs\_tan(\_x, iv, prec)`. Then we substitute _x with p to get the + desired series + + Parameters + ========== + + p : :class:`~.PolyElement` The multivariate series to be expanded. + f : `ring\_series` function to be applied on `p`. + args[-2] : :class:`~.PolyElement` with respect to which, the series is to be expanded. + args[-1] : Required order of the expanded series. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_fun, _tan1 + >>> R, x, y = ring('x, y', QQ) + >>> p = x + x*y + x**2*y + x**3*y**2 + >>> rs_fun(p, _tan1, x, 4) + 1/3*x**3*y**3 + 2*x**3*y**2 + x**3*y + 1/3*x**3 + x**2*y + x*y + x + """ + _R = p.ring + R1, _x = ring('_x', _R.domain) + h = int(args[-1]) + args1 = args[:-2] + (_x, h) + zm = _R.zero_monom + # separate the constant term of the series + # compute the univariate series f(_x, .., 'x', sum(nv)) + if zm in p: + x1 = _x + p[zm] + p1 = p - p[zm] + else: + x1 = _x + p1 = p + if isinstance(f, str): + q = getattr(x1, f)(*args1) + else: + q = f(x1, *args1) + a = sorted(q.items()) + c = [0]*h + for x in a: + c[x[0][0]] = x[1] + p1 = rs_series_from_list(p1, c, args[-2], args[-1]) + return p1 + +def mul_xin(p, i, n): + r""" + Return `p*x_i**n`. + + `x\_i` is the ith variable in ``p``. + """ + R = p.ring + q = {} + for k, v in p.terms(): + k1 = list(k) + k1[i] += n + q[tuple(k1)] = v + return R(q) + +def pow_xin(p, i, n): + """ + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> from sympy.polys.ring_series import pow_xin + >>> R, x, y = puiseux_ring('x, y', QQ) + >>> p = x**QQ(2,5) + x + x**QQ(2,3) + >>> index = p.ring.gens.index(x) + >>> pow_xin(p, index, 15) + x**6 + x**10 + x**15 + """ + R = p.ring + q = {} + for k, v in p.terms(): + k1 = list(k) + k1[i] *= n + q[tuple(k1)] = v + return R(q) + +def _nth_root1(p, n, x, prec): + """ + Univariate series expansion of the nth root of ``p``. + + The Newton method is used. + """ + if rs_is_puiseux(p, x): + return rs_puiseux2(_nth_root1, p, n, x, prec) + R = p.ring + zm = R.zero_monom + if zm not in p: + raise NotImplementedError('No constant term in series') + n = as_int(n) + assert p[zm] == 1 + p1 = R(1) + if p == 1: + return p + if n == 0: + return R(1) + if n == 1: + return p + if n < 0: + n = -n + sign = 1 + else: + sign = 0 + for precx in _giant_steps(prec): + tmp = rs_pow(p1, n + 1, x, precx) + tmp = rs_mul(tmp, p, x, precx) + p1 += p1/n - tmp/n + if sign: + return p1 + else: + return _series_inversion1(p1, x, prec) + +def rs_nth_root(p, n, x, prec): + """ + Multivariate series expansion of the nth root of ``p``. + + Parameters + ========== + + p : Expr + The polynomial to computer the root of. + n : integer + The order of the root to be computed. + x : :class:`~.PolyElement` + prec : integer + Order of the expanded series. + + Notes + ===== + + The result of this function is dependent on the ring over which the + polynomial has been defined. If the answer involves a root of a constant, + make sure that the polynomial is over a real field. It cannot yet handle + roots of symbols. + + Examples + ======== + + >>> from sympy.polys.domains import QQ, RR + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_nth_root + >>> R, x, y = ring('x, y', QQ) + >>> rs_nth_root(1 + x + x*y, -3, x, 3) + 2/9*x**2*y**2 + 4/9*x**2*y + 2/9*x**2 - 1/3*x*y - 1/3*x + 1 + >>> R, x, y = ring('x, y', RR) + >>> rs_nth_root(3 + x + x*y, 3, x, 2) + 0.160249952256379*x*y + 0.160249952256379*x + 1.44224957030741 + """ + if n == 0: + if p == 0: + raise ValueError('0**0 expression') + else: + return p.ring(1) + if n == 1: + return rs_trunc(p, x, prec) + R = p.ring + index = R.gens.index(x) + m = min(p, key=lambda k: k[index])[index] + p = mul_xin(p, index, -m) + prec -= m + + if _has_constant_term(p - 1, x): + zm = R.zero_monom + c = p[zm] + if isinstance(c, PolyElement): + try: + c_expr = c.as_expr() + const = R(c_expr**(QQ(1, n))) + except ValueError: + raise DomainError("The given series cannot be expanded in " + "this domain.") + else: + try: # RealElement doesn't support + const = R(c**Rational(1, n)) # exponentiation with mpq object + except ValueError: # as exponent + raise DomainError("The given series cannot be expanded in " + "this domain.") + res = rs_nth_root(p/c, n, x, prec)*const + else: + res = _nth_root1(p, n, x, prec) + if m: + m = QQ(m) / n + res = mul_xin(res, index, m) + return res + +def rs_log(p, x, prec): + """ + The Logarithm of ``p`` modulo ``O(x**prec)``. + + Notes + ===== + + Truncation of ``integral dx p**-1*d p/dx`` is used. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> from sympy.polys.ring_series import rs_log + >>> R, x = puiseux_ring('x', QQ) + >>> rs_log(1 + x, x, 8) + x + -1/2*x**2 + 1/3*x**3 + -1/4*x**4 + 1/5*x**5 + -1/6*x**6 + 1/7*x**7 + >>> rs_log(x**QQ(3, 2) + 1, x, 5) + x**(3/2) + -1/2*x**3 + 1/3*x**(9/2) + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_log, p, x, prec) + R = p.ring + if p == 1: + return R.zero + c = _get_constant_term(p, x) + if c: + const = 0 + if c == 1: + pass + try: + c_expr = c.as_expr() + const = R(log(c_expr)) + except ValueError: + R = R.add_gens([log(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + const = R(log(c_expr)) + + dlog = p.diff(x) + dlog = rs_mul(dlog, _series_inversion1(p, x, prec), x, prec - 1) + return rs_integrate(dlog, x) + const + else: + raise NotImplementedError + +def rs_LambertW(p, x, prec): + """ + Calculate the series expansion of the principal branch of the Lambert W + function. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_LambertW + >>> R, x, y = ring('x, y', QQ) + >>> rs_LambertW(x + x*y, x, 3) + -x**2*y**2 - 2*x**2*y - x**2 + x*y + x + + See Also + ======== + + LambertW + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_LambertW, p, x, prec) + R = p.ring + p1 = R(0) + if _has_constant_term(p, x): + raise NotImplementedError("Polynomial must not have constant term in " + "the series variables") + if x in R.gens: + for precx in _giant_steps(prec): + e = rs_exp(p1, x, precx) + p2 = rs_mul(e, p1, x, precx) - p + p3 = rs_mul(e, p1 + 1, x, precx) + p3 = rs_series_inversion(p3, x, precx) + tmp = rs_mul(p2, p3, x, precx) + p1 -= tmp + return p1 + else: + raise NotImplementedError + +def _exp1(p, x, prec): + r"""Helper function for `rs\_exp`. """ + R = p.ring + p1 = R(1) + for precx in _giant_steps(prec): + pt = p - rs_log(p1, x, precx) + tmp = rs_mul(pt, p1, x, precx) + p1 += tmp + return p1 + +def rs_exp(p, x, prec): + """ + Exponentiation of a series modulo ``O(x**prec)`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_exp + >>> R, x = ring('x', QQ) + >>> rs_exp(x**2, x, 7) + 1/6*x**6 + 1/2*x**4 + x**2 + 1 + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_exp, p, x, prec) + R = p.ring + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + const = R(exp(c_expr)) + except ValueError: + R = R.add_gens([exp(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + const = R(exp(c_expr)) + + p1 = p - c + + # Makes use of SymPy functions to evaluate the values of the cos/sin + # of the constant term. + return const*rs_exp(p1, x, prec) + + if len(p) > 20: + return _exp1(p, x, prec) + one = R(1) + n = 1 + c = [] + for k in range(prec): + c.append(one/n) + k += 1 + n *= k + + r = rs_series_from_list(p, c, x, prec) + return r + +def _atan(p, iv, prec): + """ + Expansion using formula. + + Faster on very small and univariate series. + """ + R = p.ring + mo = R(-1) + c = [-mo] + p2 = rs_square(p, iv, prec) + for k in range(1, prec): + c.append(mo**k/(2*k + 1)) + s = rs_series_from_list(p2, c, iv, prec) + s = rs_mul(s, p, iv, prec) + return s + +def rs_atan(p, x, prec): + """ + The arctangent of a series + + Return the series expansion of the atan of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_atan + >>> R, x, y = ring('x, y', QQ) + >>> rs_atan(x + x*y, x, 4) + -1/3*x**3*y**3 - x**3*y**2 - x**3*y - 1/3*x**3 + x*y + x + + See Also + ======== + + atan + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_atan, p, x, prec) + R = p.ring + const = 0 + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + const = R(atan(c_expr)) + except ValueError: + R = R.add_gens([atan(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + const = R(atan(c_expr)) + + # Instead of using a closed form formula, we differentiate atan(p) to get + # `1/(1+p**2) * dp`, whose series expansion is much easier to calculate. + # Finally we integrate to get back atan + dp = p.diff(x) + p1 = rs_square(p, x, prec) + R(1) + p1 = rs_series_inversion(p1, x, prec - 1) + p1 = rs_mul(dp, p1, x, prec - 1) + return rs_integrate(p1, x) + const + +def rs_asin(p, x, prec): + """ + Arcsine of a series + + Return the series expansion of the asin of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_asin + >>> R, x, y = ring('x, y', QQ) + >>> rs_asin(x, x, 8) + 5/112*x**7 + 3/40*x**5 + 1/6*x**3 + x + + See Also + ======== + + asin + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_asin, p, x, prec) + if _has_constant_term(p, x): + raise NotImplementedError("Polynomial must not have constant term in " + "series variables") + R = p.ring + if x in R.gens: + # get a good value + if len(p) > 20: + dp = rs_diff(p, x) + p1 = 1 - rs_square(p, x, prec - 1) + p1 = rs_nth_root(p1, -2, x, prec - 1) + p1 = rs_mul(dp, p1, x, prec - 1) + return rs_integrate(p1, x) + one = R(1) + c = [0, one, 0] + for k in range(3, prec, 2): + c.append((k - 2)**2*c[-2]/(k*(k - 1))) + c.append(0) + return rs_series_from_list(p, c, x, prec) + + else: + raise NotImplementedError + +def _tan1(p, x, prec): + r""" + Helper function of :func:`rs_tan`. + + Return the series expansion of tan of a univariate series using Newton's + method. It takes advantage of the fact that series expansion of atan is + easier than that of tan. + + Consider `f(x) = y - \arctan(x)` + Let r be a root of f(x) found using Newton's method. + Then `f(r) = 0` + Or `y = \arctan(x)` where `x = \tan(y)` as required. + """ + R = p.ring + p1 = R(0) + for precx in _giant_steps(prec): + tmp = p - rs_atan(p1, x, precx) + tmp = rs_mul(tmp, 1 + rs_square(p1, x, precx), x, precx) + p1 += tmp + return p1 + +def rs_tan(p, x, prec): + """ + Tangent of a series. + + Return the series expansion of the tan of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_tan + >>> R, x, y = ring('x, y', QQ) + >>> rs_tan(x + x*y, x, 4) + 1/3*x**3*y**3 + x**3*y**2 + x**3*y + 1/3*x**3 + x*y + x + + See Also + ======== + + _tan1, tan + """ + if rs_is_puiseux(p, x): + r = rs_puiseux(rs_tan, p, x, prec) + return r + R = p.ring + const = 0 + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + const = R(tan(c_expr)) + except ValueError: + R = R.add_gens([tan(c_expr, )]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + const = R(tan(c_expr)) + + p1 = p - c + + # Makes use of SymPy functions to evaluate the values of the cos/sin + # of the constant term. + t2 = rs_tan(p1, x, prec) + t = rs_series_inversion(1 - const*t2, x, prec) + return rs_mul(const + t2, t, x, prec) + + if R.ngens == 1: + return _tan1(p, x, prec) + else: + return rs_fun(p, rs_tan, x, prec) + +def rs_cot(p, x, prec): + """ + Cotangent of a series + + Return the series expansion of the cot of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_cot + >>> R, x, y = ring('x, y', QQ) + >>> rs_cot(x, x, 6) + -2/945*x**5 - 1/45*x**3 - 1/3*x + x**(-1) + + See Also + ======== + + cot + """ + # It can not handle series like `p = x + x*y` where the coefficient of the + # linear term in the series variable is symbolic. + if rs_is_puiseux(p, x): + r = rs_puiseux(rs_cot, p, x, prec) + return r + i, m = _check_series_var(p, x, 'cot') + prec1 = int(prec + 2*m) + c, s = rs_cos_sin(p, x, prec1) + s = mul_xin(s, i, -m) + s = rs_series_inversion(s, x, prec1) + res = rs_mul(c, s, x, prec1) + res = mul_xin(res, i, -m) + res = rs_trunc(res, x, prec) + return res + +def rs_sin(p, x, prec): + """ + Sine of a series + + Return the series expansion of the sin of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> from sympy.polys.ring_series import rs_sin + >>> R, x, y = puiseux_ring('x, y', QQ) + >>> rs_sin(x + x*y, x, 4) + x + x*y + -1/6*x**3 + -1/2*x**3*y + -1/2*x**3*y**2 + -1/6*x**3*y**3 + >>> rs_sin(x**QQ(3, 2) + x*y**QQ(7, 5), x, 4) + x*y**(7/5) + x**(3/2) + -1/6*x**3*y**(21/5) + -1/2*x**(7/2)*y**(14/5) + + See Also + ======== + + sin + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_sin, p, x, prec) + R = x.ring + if not p: + return R(0) + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + t1, t2 = R(sin(c_expr)), R(cos(c_expr)) + except ValueError: + R = R.add_gens([sin(c_expr), cos(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + t1, t2 = R(sin(c_expr)), R(cos(c_expr)) + + p1 = p - c + + # Makes use of SymPy cos, sin functions to evaluate the values of the + # cos/sin of the constant term. + p_cos, p_sin = rs_cos_sin(p1, x, prec) + return p_sin*t2 + p_cos*t1 + + # Series is calculated in terms of tan as its evaluation is fast. + if len(p) > 20 and R.ngens == 1: + t = rs_tan(p/2, x, prec) + t2 = rs_square(t, x, prec) + p1 = rs_series_inversion(1 + t2, x, prec) + return rs_mul(p1, 2*t, x, prec) + one = R(1) + n = 1 + c = [0] + for k in range(2, prec + 2, 2): + c.append(one/n) + c.append(0) + n *= -k*(k + 1) + return rs_series_from_list(p, c, x, prec) + +def rs_cos(p, x, prec): + """ + Cosine of a series + + Return the series expansion of the cos of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.puiseux import puiseux_ring + >>> from sympy.polys.ring_series import rs_cos + >>> R, x, y = puiseux_ring('x, y', QQ) + >>> rs_cos(x + x*y, x, 4) + 1 + -1/2*x**2 + -1*x**2*y + -1/2*x**2*y**2 + >>> rs_cos(x + x*y, x, 4)/x**QQ(7, 5) + x**(-7/5) + -1/2*x**(3/5) + -1*x**(3/5)*y + -1/2*x**(3/5)*y**2 + + See Also + ======== + + cos + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_cos, p, x, prec) + R = p.ring + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + t1, t2 = R(sin(c_expr)), R(cos(c_expr)) + except ValueError: + R = R.add_gens([sin(c_expr), cos(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + t1, t2 = R(sin(c_expr)), R(cos(c_expr)) + + p1 = p - c + # Makes use of SymPy cos, sin functions to evaluate the values of the + # cos/sin of the constant term. + p_cos, p_sin = rs_cos_sin(p1, x, prec) + return p_cos*t2 - p_sin*t1 + + # Series is calculated in terms of tan as its evaluation is fast. + if len(p) > 20 and R.ngens == 1: + t = rs_tan(p/2, x, prec) + t2 = rs_square(t, x, prec) + p1 = rs_series_inversion(1+t2, x, prec) + return rs_mul(p1, 1 - t2, x, prec) + one = R(1) + n = 1 + c = [] + for k in range(2, prec + 2, 2): + c.append(one/n) + c.append(0) + n *= -k*(k - 1) + return rs_series_from_list(p, c, x, prec) + +def rs_cos_sin(p, x, prec): + """ + Cosine and sine of a series + + Return the series expansion of the cosine and sine of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_cos_sin + >>> R, x, y = ring('x, y', QQ) + >>> c, s = rs_cos_sin(x + x*y, x, 4) + >>> c + -1/2*x**2*y**2 - x**2*y - 1/2*x**2 + 1 + >>> s + -1/6*x**3*y**3 - 1/2*x**3*y**2 - 1/2*x**3*y - 1/6*x**3 + x*y + x + + See Also + ======== + + rs_cos, rs_sin + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_cos_sin, p, x, prec) + R = p.ring + if not p: + return R(0), R(0) + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + t1, t2 = R(sin(c_expr)), R(cos(c_expr)) + except ValueError: + R = R.add_gens([sin(c_expr), cos(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + t1, t2 = R(sin(c_expr)), R(cos(c_expr)) + + p1 = p - c + p_cos, p_sin = rs_cos_sin(p1, x, prec) + return p_cos*t2 - p_sin*t1, p_cos*t1 + p_sin*t2 + + if len(p) > 20 and R.ngens == 1: + t = rs_tan(p/2, x, prec) + t2 = rs_square(t, x, prec) + p1 = rs_series_inversion(1 + t2, x, prec) + return (rs_mul(p1, 1 - t2, x, prec), rs_mul(p1, 2*t, x, prec)) + + one = R(1) + coeffs = [] + cn, sn = 1, 1 + for k in range(2, prec+2, 2): + coeffs.extend([(one/cn, 0), (0, one/sn)]) + cn, sn = -cn*k*(k - 1), -sn*k*(k + 1) + + c, s = zip(*coeffs) + return (rs_series_from_list(p, c, x, prec), rs_series_from_list(p, s, x, prec)) + +def _atanh(p, x, prec): + """ + Expansion using formula + + Faster for very small and univariate series + """ + R = p.ring + one = R(1) + c = [one] + p2 = rs_square(p, x, prec) + for k in range(1, prec): + c.append(one/(2*k + 1)) + s = rs_series_from_list(p2, c, x, prec) + s = rs_mul(s, p, x, prec) + return s + +def rs_atanh(p, x, prec): + """ + Hyperbolic arctangent of a series + + Return the series expansion of the atanh of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_atanh + >>> R, x, y = ring('x, y', QQ) + >>> rs_atanh(x + x*y, x, 4) + 1/3*x**3*y**3 + x**3*y**2 + x**3*y + 1/3*x**3 + x*y + x + + See Also + ======== + + atanh + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_atanh, p, x, prec) + R = p.ring + const = 0 + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + const = R(atanh(c_expr)) + except ValueError: + raise DomainError("The given series cannot be expanded in " + "this domain.") + + # Instead of using a closed form formula, we differentiate atanh(p) to get + # `1/(1-p**2) * dp`, whose series expansion is much easier to calculate. + # Finally we integrate to get back atanh + dp = rs_diff(p, x) + p1 = - rs_square(p, x, prec) + 1 + p1 = rs_series_inversion(p1, x, prec - 1) + p1 = rs_mul(dp, p1, x, prec - 1) + return rs_integrate(p1, x) + const + +def rs_asinh(p, x, prec): + """ + Hyperbolic arcsine of a series + + Return the series expansion of the arcsinh of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_asinh + >>> R, x = ring('x', QQ) + >>> rs_asinh(x, x, 9) + -5/112*x**7 + 3/40*x**5 - 1/6*x**3 + x + + See Also + ======== + + asinh + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_asinh, p, x, prec) + R = p.ring + const = 0 + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + const = R(asinh(c_expr)) + except ValueError: + raise DomainError("The given series cannot be expanded in " + "this domain.") + + # Instead of using a closed form formula, we differentiate asinh(p) to get + # `1/sqrt(1+p**2) * dp`, whose series expansion is much easier to calculate. + # Finally we integrate to get back asinh + dp = rs_diff(p, x) + p_squared = rs_square(p, x, prec) + denom = p_squared + R(1) + p1 = rs_nth_root(denom, -2, x, prec - 1) + p1 = rs_mul(dp, p1, x, prec - 1) + return rs_integrate(p1, x) + const + +def rs_sinh(p, x, prec): + """ + Hyperbolic sine of a series + + Return the series expansion of the sinh of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_sinh + >>> R, x, y = ring('x, y', QQ) + >>> rs_sinh(x + x*y, x, 4) + 1/6*x**3*y**3 + 1/2*x**3*y**2 + 1/2*x**3*y + 1/6*x**3 + x*y + x + + See Also + ======== + + sinh + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_sinh, p, x, prec) + R = p.ring + if not p: + return R(0) + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + t1, t2 = R(sinh(c_expr)), R(cosh(c_expr)) + except ValueError: + R = R.add_gens([sinh(c_expr), cosh(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + t1, t2 = R(sinh(c_expr)), R(cosh(c_expr)) + + p1 = p - c + p_cosh, p_sinh = rs_cosh_sinh(p1, x, prec) + return p_sinh * t2 + p_cosh * t1 + + t = rs_exp(p, x, prec) + t1 = rs_series_inversion(t, x, prec) + return (t - t1)/2 + +def rs_cosh(p, x, prec): + """ + Hyperbolic cosine of a series + + Return the series expansion of the cosh of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_cosh + >>> R, x, y = ring('x, y', QQ) + >>> rs_cosh(x + x*y, x, 4) + 1/2*x**2*y**2 + x**2*y + 1/2*x**2 + 1 + + See Also + ======== + + cosh + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_cosh, p, x, prec) + R = p.ring + if not p: + return R(0) + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + t1, t2 = R(sinh(c_expr)), R(cosh(c_expr)) + except ValueError: + R = R.add_gens([sinh(c_expr), cosh(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + t1, t2 = R(sinh(c_expr)), R(cosh(c_expr)) + + p1 = p - c + p_cosh, p_sinh = rs_cosh_sinh(p1, x, prec) + return p_cosh * t2 + p_sinh * t1 + + t = rs_exp(p, x, prec) + t1 = rs_series_inversion(t, x, prec) + return (t + t1)/2 + +def rs_cosh_sinh(p, x, prec): + """ + Hyperbolic cosine and sine of a series + + Return the series expansion of the hyperbolic cosine and sine of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_cosh_sinh + >>> R, x, y = ring('x, y', QQ) + >>> c, s = rs_cosh_sinh(x + x*y, x, 4) + >>> c + 1/2*x**2*y**2 + x**2*y + 1/2*x**2 + 1 + >>> s + 1/6*x**3*y**3 + 1/2*x**3*y**2 + 1/2*x**3*y + 1/6*x**3 + x*y + x + + See Also + ======== + + rs_cosh, rs_sinh + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_cosh_sinh, p, x, prec) + R = p.ring + if not p: + return R(0), R(0) + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + t1, t2 = R(sinh(c_expr)), R(cosh(c_expr)) + except ValueError: + R = R.add_gens([sinh(c_expr), cosh(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + t1, t2 = R(sinh(c_expr)), R(cosh(c_expr)) + + p1 = p - c + p_cosh, p_sinh = rs_cosh_sinh(p1, x, prec) + return p_cosh * t2 + p_sinh * t1, p_sinh * t2 + p_cosh * t1 + + t = rs_exp(p, x, prec) + t1 = rs_series_inversion(t, x, prec) + return (t + t1)/2, (t - t1)/2 + + +def _tanh(p, x, prec): + r""" + Helper function of :func:`rs_tanh` + + Return the series expansion of tanh of a univariate series using Newton's + method. It takes advantage of the fact that series expansion of atanh is + easier than that of tanh. + + See Also + ======== + + _tanh + """ + R = p.ring + p1 = R(0) + for precx in _giant_steps(prec): + tmp = p - rs_atanh(p1, x, precx) + tmp = rs_mul(tmp, 1 - rs_square(p1, x, prec), x, precx) + p1 += tmp + return p1 + +def rs_tanh(p, x, prec): + """ + Hyperbolic tangent of a series + + Return the series expansion of the tanh of ``p``, about 0. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_tanh + >>> R, x, y = ring('x, y', QQ) + >>> rs_tanh(x + x*y, x, 4) + -1/3*x**3*y**3 - x**3*y**2 - x**3*y - 1/3*x**3 + x*y + x + + See Also + ======== + + tanh + """ + if rs_is_puiseux(p, x): + return rs_puiseux(rs_tanh, p, x, prec) + R = p.ring + const = 0 + c = _get_constant_term(p, x) + if c: + try: + c_expr = c.as_expr() + const = R(tanh(c_expr)) + except ValueError: + R = R.add_gens([tanh(c_expr)]) + p = p.set_ring(R) + x = x.set_ring(R) + c = c.set_ring(R) + const = R(tanh(c_expr)) + + p1 = p - c + t1 = rs_tanh(p1, x, prec) + t = rs_series_inversion(1 + const*t1, x, prec) + return rs_mul(const + t1, t, x, prec) + + if R.ngens == 1: + return _tanh(p, x, prec) + else: + return rs_fun(p, _tanh, x, prec) + +def rs_newton(p, x, prec): + """ + Compute the truncated Newton sum of the polynomial ``p`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_newton + >>> R, x = ring('x', QQ) + >>> p = x**2 - 2 + >>> rs_newton(p, x, 5) + 8*x**4 + 4*x**2 + 2 + """ + deg = p.degree() + p1 = _invert_monoms(p) + p2 = rs_series_inversion(p1, x, prec) + p3 = rs_mul(p1.diff(x), p2, x, prec) + res = deg - p3*x + return res + +def rs_hadamard_exp(p1, inverse=False): + """ + Return ``sum f_i/i!*x**i`` from ``sum f_i*x**i``, + where ``x`` is the first variable. + + If ``inverse=True`` return ``sum f_i*i!*x**i`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_hadamard_exp + >>> R, x = ring('x', QQ) + >>> p = 1 + x + x**2 + x**3 + >>> rs_hadamard_exp(p) + 1/6*x**3 + 1/2*x**2 + x + 1 + """ + R = p1.ring + if R.domain != QQ: + raise NotImplementedError + p = R.zero + if not inverse: + for exp1, v1 in p1.items(): + p[exp1] = v1/int(ifac(exp1[0])) + else: + for exp1, v1 in p1.items(): + p[exp1] = v1*int(ifac(exp1[0])) + return p + +def rs_compose_add(p1, p2): + """ + compute the composed sum ``prod(p2(x - beta) for beta root of p1)`` + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + >>> from sympy.polys.ring_series import rs_compose_add + >>> R, x = ring('x', QQ) + >>> f = x**2 - 2 + >>> g = x**2 - 3 + >>> rs_compose_add(f, g) + x**4 - 10*x**2 + 1 + + References + ========== + + .. [1] A. Bostan, P. Flajolet, B. Salvy and E. Schost + "Fast Computation with Two Algebraic Numbers", + (2002) Research Report 4579, Institut + National de Recherche en Informatique et en Automatique + """ + R = p1.ring + x = R.gens[0] + prec = p1.degree()*p2.degree() + 1 + np1 = rs_newton(p1, x, prec) + np1e = rs_hadamard_exp(np1) + np2 = rs_newton(p2, x, prec) + np2e = rs_hadamard_exp(np2) + np3e = rs_mul(np1e, np2e, x, prec) + np3 = rs_hadamard_exp(np3e, True) + np3a = (np3[(0,)] - np3) / x + q = rs_integrate(np3a, x) + q = rs_exp(q, x, prec) + q = _invert_monoms(q) + q = q.primitive()[1] + dp = p1.degree()*p2.degree() - q.degree() + # `dp` is the multiplicity of the zeroes of the resultant; + # these zeroes are missed in this computation so they are put here. + # if p1 and p2 are monic irreducible polynomials, + # there are zeroes in the resultant + # if and only if p1 = p2 ; in fact in that case p1 and p2 have a + # root in common, so gcd(p1, p2) != 1; being p1 and p2 irreducible + # this means p1 = p2 + if dp: + q = q*x**dp + return q + + +_convert_func = { + 'sin': 'rs_sin', + 'cos': 'rs_cos', + 'exp': 'rs_exp', + 'tan': 'rs_tan', + 'log': 'rs_log', + 'atan': 'rs_atan', + 'sinh': 'rs_sinh', + 'cosh': 'rs_cosh', + 'tanh': 'rs_tanh' + } + +def rs_min_pow(expr, series_rs, a): + """Find the minimum power of `a` in the series expansion of expr""" + series = 0 + n = 2 + while series == 0: + series = _rs_series(expr, series_rs, a, n) + n *= 2 + R = series.ring + a = R(a) + i = R.gens.index(a) + return min(series, key=lambda t: t[i])[i] + + +def _rs_series(expr, series_rs, a, prec): + # TODO Use _parallel_dict_from_expr instead of sring as sring is + # inefficient. For details, read the todo in sring. + args = expr.args + R = series_rs.ring + + # expr does not contain any function to be expanded + if not any(arg.has(Function) for arg in args) and not expr.is_Function: + return series_rs + + if not expr.has(a): + return series_rs + + elif expr.is_Function: + arg = args[0] + if len(args) > 1: + raise NotImplementedError + R1, series = sring(arg, domain=QQ, expand=False, series=True) + series_inner = _rs_series(arg, series, a, prec) + + # Why do we need to compose these three rings? + # + # We want to use a simple domain (like ``QQ`` or ``RR``) but they don't + # support symbolic coefficients. We need a ring that for example lets + # us have `sin(1)` and `cos(1)` as coefficients if we are expanding + # `sin(x + 1)`. The ``EX`` domain allows all symbolic coefficients, but + # that makes it very complex and hence slow. + # + # To solve this problem, we add only those symbolic elements as + # generators to our ring, that we need. Here, series_inner might + # involve terms like `sin(4)`, `exp(a)`, etc, which are not there in + # R1 or R. Hence, we compose these three rings to create one that has + # the generators of all three. + R = R.compose(R1).compose(series_inner.ring) + series_inner = series_inner.set_ring(R) + series = eval(_convert_func[str(expr.func)])(series_inner, + R(a), prec) + return series + + elif expr.is_Mul: + n = len(args) + for arg in args: # XXX Looks redundant + if not arg.is_Number: + R1, _ = sring(arg, expand=False, series=True) + R = R.compose(R1) + min_pows = list(map(rs_min_pow, args, [R(arg) for arg in args], + [a]*len(args))) + sum_pows = sum(min_pows) + series = R(1) + + for i in range(n): + _series = _rs_series(args[i], R(args[i]), a, ceiling(prec + - sum_pows + min_pows[i])) + R = R.compose(_series.ring) + _series = _series.set_ring(R) + series = series.set_ring(R) + series *= _series + series = rs_trunc(series, R(a), prec) + return series + + elif expr.is_Add: + n = len(args) + series = R(0) + for i in range(n): + _series = _rs_series(args[i], R(args[i]), a, prec) + R = R.compose(_series.ring) + _series = _series.set_ring(R) + series = series.set_ring(R) + series += _series + return series + + elif expr.is_Pow: + R1, _ = sring(expr.base, domain=QQ, expand=False, series=True) + R = R.compose(R1) + series_inner = _rs_series(expr.base, R(expr.base), a, prec) + return rs_pow(series_inner, expr.exp, series_inner.ring(a), prec) + + # The `is_constant` method is buggy hence we check it at the end. + # See issue #9786 for details. + elif isinstance(expr, Expr) and expr.is_constant(): + return sring(expr, domain=QQ, expand=False, series=True)[1] + + else: + raise NotImplementedError + +def rs_series(expr, a, prec): + """Return the series expansion of an expression about 0. + + Parameters + ========== + + expr : :class:`~.Expr` + a : :class:`~.Symbol` with respect to which expr is to be expanded + prec : order of the series expansion + + Currently supports multivariate Taylor series expansion. This is much + faster that SymPy's series method as it uses sparse polynomial operations. + + It automatically creates the simplest ring required to represent the series + expansion through repeated calls to sring. + + Examples + ======== + + >>> from sympy.polys.ring_series import rs_series + >>> from sympy import sin, cos, exp, tan, symbols, QQ + >>> a, b, c = symbols('a, b, c') + >>> rs_series(sin(a) + exp(a), a, 5) + 1/24*a**4 + 1/2*a**2 + 2*a + 1 + >>> series = rs_series(tan(a + b)*cos(a + c), a, 2) + >>> series.as_expr() + -a*sin(c)*tan(b) + a*cos(c)*tan(b)**2 + a*cos(c) + cos(c)*tan(b) + >>> series = rs_series(exp(a**QQ(1,3) + a**QQ(2, 5)), a, 1) + >>> series.as_expr() + a**(11/15) + a**(4/5)/2 + a**(2/5) + a**(2/3)/2 + a**(1/3) + 1 + + """ + R, series = sring(expr, domain=QQ, expand=False, series=True) + if a not in R.symbols: + R = R.add_gens([a, ]) + series = series.set_ring(R) + series = _rs_series(expr, series, a, prec) + R = series.ring + gen = R(a) + prec_got = series.degree(gen) + 1 + + if prec_got >= prec: + return rs_trunc(series, gen, prec) + else: + # increase the requested number of terms to get the desired + # number keep increasing (up to 9) until the received order + # is different than the original order and then predict how + # many additional terms are needed + for more in range(1, 9): + p1 = _rs_series(expr, series, a, prec=prec + more) + gen = gen.set_ring(p1.ring) + new_prec = p1.degree(gen) + 1 + if new_prec != prec_got: + prec_do = ceiling(prec + (prec - prec_got)*more/(new_prec - + prec_got)) + p1 = _rs_series(expr, series, a, prec=prec_do) + while p1.degree(gen) + 1 < prec: + p1 = _rs_series(expr, series, a, prec=prec_do) + gen = gen.set_ring(p1.ring) + prec_do *= 2 + break + else: + break + else: + raise ValueError('Could not calculate %s terms for %s' + % (str(prec), expr)) + return rs_trunc(p1, gen, prec) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rings.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rings.py new file mode 100644 index 0000000000000000000000000000000000000000..9df84dcf1691ac9bcd4aa01a85ca34b7ffc53e5d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rings.py @@ -0,0 +1,3096 @@ +"""Sparse polynomial rings. """ + +from __future__ import annotations + +from operator import add, mul, lt, le, gt, ge +from functools import reduce +from types import GeneratorType + +from sympy.core.cache import cacheit +from sympy.core.expr import Expr +from sympy.core.intfunc import igcd +from sympy.core.symbol import Symbol, symbols as _symbols +from sympy.core.sympify import CantSympify, sympify +from sympy.ntheory.multinomial import multinomial_coefficients +from sympy.polys.compatibility import IPolys +from sympy.polys.constructor import construct_domain +from sympy.polys.densebasic import ninf, dmp_to_dict, dmp_from_dict +from sympy.polys.domains.domain import Domain +from sympy.polys.domains.domainelement import DomainElement +from sympy.polys.domains.polynomialring import PolynomialRing +from sympy.polys.heuristicgcd import heugcd +from sympy.polys.monomials import MonomialOps +from sympy.polys.orderings import lex, MonomialOrder +from sympy.polys.polyerrors import ( + CoercionFailed, GeneratorsError, + ExactQuotientFailed, MultivariatePolynomialError) +from sympy.polys.polyoptions import (Domain as DomainOpt, + Order as OrderOpt, build_options) +from sympy.polys.polyutils import (expr_from_dict, _dict_reorder, + _parallel_dict_from_expr) +from sympy.printing.defaults import DefaultPrinting +from sympy.utilities import public, subsets +from sympy.utilities.iterables import is_sequence +from sympy.utilities.magic import pollute + +@public +def ring(symbols, domain, order: MonomialOrder|str = lex): + """Construct a polynomial ring returning ``(ring, x_1, ..., x_n)``. + + Parameters + ========== + + symbols : str + Symbol/Expr or sequence of str, Symbol/Expr (non-empty) + domain : :class:`~.Domain` or coercible + order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.orderings import lex + + >>> R, x, y, z = ring("x,y,z", ZZ, lex) + >>> R + Polynomial ring in x, y, z over ZZ with lex order + >>> x + y + z + x + y + z + >>> type(_) + + + """ + _ring = PolyRing(symbols, domain, order) + return (_ring,) + _ring.gens + +@public +def xring(symbols, domain, order=lex): + """Construct a polynomial ring returning ``(ring, (x_1, ..., x_n))``. + + Parameters + ========== + + symbols : str + Symbol/Expr or sequence of str, Symbol/Expr (non-empty) + domain : :class:`~.Domain` or coercible + order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` + + Examples + ======== + + >>> from sympy.polys.rings import xring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.orderings import lex + + >>> R, (x, y, z) = xring("x,y,z", ZZ, lex) + >>> R + Polynomial ring in x, y, z over ZZ with lex order + >>> x + y + z + x + y + z + >>> type(_) + + + """ + _ring = PolyRing(symbols, domain, order) + return (_ring, _ring.gens) + +@public +def vring(symbols, domain, order=lex): + """Construct a polynomial ring and inject ``x_1, ..., x_n`` into the global namespace. + + Parameters + ========== + + symbols : str + Symbol/Expr or sequence of str, Symbol/Expr (non-empty) + domain : :class:`~.Domain` or coercible + order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` + + Examples + ======== + + >>> from sympy.polys.rings import vring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.orderings import lex + + >>> vring("x,y,z", ZZ, lex) + Polynomial ring in x, y, z over ZZ with lex order + >>> x + y + z # noqa: + x + y + z + >>> type(_) + + + """ + _ring = PolyRing(symbols, domain, order) + pollute([ sym.name for sym in _ring.symbols ], _ring.gens) + return _ring + +@public +def sring(exprs, *symbols, **options): + """Construct a ring deriving generators and domain from options and input expressions. + + Parameters + ========== + + exprs : :class:`~.Expr` or sequence of :class:`~.Expr` (sympifiable) + symbols : sequence of :class:`~.Symbol`/:class:`~.Expr` + options : keyword arguments understood by :class:`~.Options` + + Examples + ======== + + >>> from sympy import sring, symbols + + >>> x, y, z = symbols("x,y,z") + >>> R, f = sring(x + 2*y + 3*z) + >>> R + Polynomial ring in x, y, z over ZZ with lex order + >>> f + x + 2*y + 3*z + >>> type(_) + + + """ + single = False + + if not is_sequence(exprs): + exprs, single = [exprs], True + + exprs = list(map(sympify, exprs)) + opt = build_options(symbols, options) + + # TODO: rewrite this so that it doesn't use expand() (see poly()). + reps, opt = _parallel_dict_from_expr(exprs, opt) + + if opt.domain is None: + coeffs = sum([ list(rep.values()) for rep in reps ], []) + + opt.domain, coeffs_dom = construct_domain(coeffs, opt=opt) + + coeff_map = dict(zip(coeffs, coeffs_dom)) + reps = [{m: coeff_map[c] for m, c in rep.items()} for rep in reps] + + _ring = PolyRing(opt.gens, opt.domain, opt.order) + polys = list(map(_ring.from_dict, reps)) + + if single: + return (_ring, polys[0]) + else: + return (_ring, polys) + +def _parse_symbols(symbols): + if isinstance(symbols, str): + return _symbols(symbols, seq=True) if symbols else () + elif isinstance(symbols, Expr): + return (symbols,) + elif is_sequence(symbols): + if all(isinstance(s, str) for s in symbols): + return _symbols(symbols) + elif all(isinstance(s, Expr) for s in symbols): + return symbols + + raise GeneratorsError("expected a string, Symbol or expression or a non-empty sequence of strings, Symbols or expressions") + + +class PolyRing(DefaultPrinting, IPolys): + """Multivariate distributed polynomial ring. """ + + gens: tuple[PolyElement, ...] + symbols: tuple[Expr, ...] + ngens: int + domain: Domain + order: MonomialOrder + + def __new__(cls, symbols, domain, order=lex): + symbols = tuple(_parse_symbols(symbols)) + ngens = len(symbols) + domain = DomainOpt.preprocess(domain) + order = OrderOpt.preprocess(order) + + _hash_tuple = (cls.__name__, symbols, ngens, domain, order) + + if domain.is_Composite and set(symbols) & set(domain.symbols): + raise GeneratorsError("polynomial ring and it's ground domain share generators") + + obj = object.__new__(cls) + obj._hash_tuple = _hash_tuple + obj._hash = hash(_hash_tuple) + obj.symbols = symbols + obj.ngens = ngens + obj.domain = domain + obj.order = order + + obj.dtype = PolyElement(obj, ()).new + + obj.zero_monom = (0,)*ngens + obj.gens = obj._gens() + obj._gens_set = set(obj.gens) + + obj._one = [(obj.zero_monom, domain.one)] + + if ngens: + # These expect monomials in at least one variable + codegen = MonomialOps(ngens) + obj.monomial_mul = codegen.mul() + obj.monomial_pow = codegen.pow() + obj.monomial_mulpow = codegen.mulpow() + obj.monomial_ldiv = codegen.ldiv() + obj.monomial_div = codegen.div() + obj.monomial_lcm = codegen.lcm() + obj.monomial_gcd = codegen.gcd() + else: + monunit = lambda a, b: () + obj.monomial_mul = monunit + obj.monomial_pow = monunit + obj.monomial_mulpow = lambda a, b, c: () + obj.monomial_ldiv = monunit + obj.monomial_div = monunit + obj.monomial_lcm = monunit + obj.monomial_gcd = monunit + + + if order is lex: + obj.leading_expv = max + else: + obj.leading_expv = lambda f: max(f, key=order) + + for symbol, generator in zip(obj.symbols, obj.gens): + if isinstance(symbol, Symbol): + name = symbol.name + + if not hasattr(obj, name): + setattr(obj, name, generator) + + return obj + + def _gens(self): + """Return a list of polynomial generators. """ + one = self.domain.one + _gens = [] + for i in range(self.ngens): + expv = self.monomial_basis(i) + poly = self.zero + poly[expv] = one + _gens.append(poly) + return tuple(_gens) + + def __getnewargs__(self): + return (self.symbols, self.domain, self.order) + + def __getstate__(self): + state = self.__dict__.copy() + del state["leading_expv"] + + for key in state: + if key.startswith("monomial_"): + del state[key] + + return state + + def __hash__(self): + return self._hash + + def __eq__(self, other): + return isinstance(other, PolyRing) and \ + (self.symbols, self.domain, self.ngens, self.order) == \ + (other.symbols, other.domain, other.ngens, other.order) + + def __ne__(self, other): + return not self == other + + def clone(self, symbols=None, domain=None, order=None): + # Need a hashable tuple for cacheit to work + if symbols is not None and isinstance(symbols, list): + symbols = tuple(symbols) + return self._clone(symbols, domain, order) + + @cacheit + def _clone(self, symbols, domain, order): + return self.__class__(symbols or self.symbols, domain or self.domain, order or self.order) + + def monomial_basis(self, i): + """Return the ith-basis element. """ + basis = [0]*self.ngens + basis[i] = 1 + return tuple(basis) + + @property + def zero(self): + return self.dtype([]) + + @property + def one(self): + return self.dtype(self._one) + + def is_element(self, element): + """True if ``element`` is an element of this ring. False otherwise. """ + return isinstance(element, PolyElement) and element.ring == self + + def domain_new(self, element, orig_domain=None): + return self.domain.convert(element, orig_domain) + + def ground_new(self, coeff): + return self.term_new(self.zero_monom, coeff) + + def term_new(self, monom, coeff): + coeff = self.domain_new(coeff) + poly = self.zero + if coeff: + poly[monom] = coeff + return poly + + def ring_new(self, element): + if isinstance(element, PolyElement): + if self == element.ring: + return element + elif isinstance(self.domain, PolynomialRing) and self.domain.ring == element.ring: + return self.ground_new(element) + else: + raise NotImplementedError("conversion") + elif isinstance(element, str): + raise NotImplementedError("parsing") + elif isinstance(element, dict): + return self.from_dict(element) + elif isinstance(element, list): + try: + return self.from_terms(element) + except ValueError: + return self.from_list(element) + elif isinstance(element, Expr): + return self.from_expr(element) + else: + return self.ground_new(element) + + __call__ = ring_new + + def from_dict(self, element, orig_domain=None): + domain_new = self.domain_new + poly = self.zero + + for monom, coeff in element.items(): + coeff = domain_new(coeff, orig_domain) + if coeff: + poly[monom] = coeff + + return poly + + def from_terms(self, element, orig_domain=None): + return self.from_dict(dict(element), orig_domain) + + def from_list(self, element): + return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain)) + + def _rebuild_expr(self, expr, mapping): + domain = self.domain + + def _rebuild(expr): + generator = mapping.get(expr) + + if generator is not None: + return generator + elif expr.is_Add: + return reduce(add, list(map(_rebuild, expr.args))) + elif expr.is_Mul: + return reduce(mul, list(map(_rebuild, expr.args))) + else: + # XXX: Use as_base_exp() to handle Pow(x, n) and also exp(n) + # XXX: E can be a generator e.g. sring([exp(2)]) -> ZZ[E] + base, exp = expr.as_base_exp() + if exp.is_Integer and exp > 1: + return _rebuild(base)**int(exp) + else: + return self.ground_new(domain.convert(expr)) + + return _rebuild(sympify(expr)) + + def from_expr(self, expr): + mapping = dict(list(zip(self.symbols, self.gens))) + + try: + poly = self._rebuild_expr(expr, mapping) + except CoercionFailed: + raise ValueError("expected an expression convertible to a polynomial in %s, got %s" % (self, expr)) + else: + return self.ring_new(poly) + + def index(self, gen): + """Compute index of ``gen`` in ``self.gens``. """ + if gen is None: + if self.ngens: + i = 0 + else: + i = -1 # indicate impossible choice + elif isinstance(gen, int): + i = gen + + if 0 <= i and i < self.ngens: + pass + elif -self.ngens <= i and i <= -1: + i = -i - 1 + else: + raise ValueError("invalid generator index: %s" % gen) + elif self.is_element(gen): + try: + i = self.gens.index(gen) + except ValueError: + raise ValueError("invalid generator: %s" % gen) + elif isinstance(gen, str): + try: + i = self.symbols.index(gen) + except ValueError: + raise ValueError("invalid generator: %s" % gen) + else: + raise ValueError("expected a polynomial generator, an integer, a string or None, got %s" % gen) + + return i + + def drop(self, *gens): + """Remove specified generators from this ring. """ + indices = set(map(self.index, gens)) + symbols = [ s for i, s in enumerate(self.symbols) if i not in indices ] + + if not symbols: + return self.domain + else: + return self.clone(symbols=symbols) + + def __getitem__(self, key): + symbols = self.symbols[key] + + if not symbols: + return self.domain + else: + return self.clone(symbols=symbols) + + def to_ground(self): + # TODO: should AlgebraicField be a Composite domain? + if self.domain.is_Composite or hasattr(self.domain, 'domain'): + return self.clone(domain=self.domain.domain) + else: + raise ValueError("%s is not a composite domain" % self.domain) + + def to_domain(self): + return PolynomialRing(self) + + def to_field(self): + from sympy.polys.fields import FracField + return FracField(self.symbols, self.domain, self.order) + + @property + def is_univariate(self): + return len(self.gens) == 1 + + @property + def is_multivariate(self): + return len(self.gens) > 1 + + def add(self, *objs): + """ + Add a sequence of polynomials or containers of polynomials. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> R, x = ring("x", ZZ) + >>> R.add([ x**2 + 2*i + 3 for i in range(4) ]) + 4*x**2 + 24 + >>> _.factor_list() + (4, [(x**2 + 6, 1)]) + + """ + p = self.zero + + for obj in objs: + if is_sequence(obj, include=GeneratorType): + p += self.add(*obj) + else: + p += obj + + return p + + def mul(self, *objs): + """ + Multiply a sequence of polynomials or containers of polynomials. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> R, x = ring("x", ZZ) + >>> R.mul([ x**2 + 2*i + 3 for i in range(4) ]) + x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945 + >>> _.factor_list() + (1, [(x**2 + 3, 1), (x**2 + 5, 1), (x**2 + 7, 1), (x**2 + 9, 1)]) + + """ + p = self.one + + for obj in objs: + if is_sequence(obj, include=GeneratorType): + p *= self.mul(*obj) + else: + p *= obj + + return p + + def drop_to_ground(self, *gens): + r""" + Remove specified generators from the ring and inject them into + its domain. + """ + indices = set(map(self.index, gens)) + symbols = [s for i, s in enumerate(self.symbols) if i not in indices] + gens = [gen for i, gen in enumerate(self.gens) if i not in indices] + + if not symbols: + return self + else: + return self.clone(symbols=symbols, domain=self.drop(*gens)) + + def compose(self, other): + """Add the generators of ``other`` to ``self``""" + if self != other: + syms = set(self.symbols).union(set(other.symbols)) + return self.clone(symbols=list(syms)) + else: + return self + + def add_gens(self, symbols): + """Add the elements of ``symbols`` as generators to ``self``""" + syms = set(self.symbols).union(set(symbols)) + return self.clone(symbols=list(syms)) + + def symmetric_poly(self, n): + """ + Return the elementary symmetric polynomial of degree *n* over + this ring's generators. + """ + if n < 0 or n > self.ngens: + raise ValueError("Cannot generate symmetric polynomial of order %s for %s" % (n, self.gens)) + elif not n: + return self.one + else: + poly = self.zero + for s in subsets(range(self.ngens), int(n)): + monom = tuple(int(i in s) for i in range(self.ngens)) + poly += self.term_new(monom, self.domain.one) + return poly + + +class PolyElement(DomainElement, DefaultPrinting, CantSympify, dict): + """Element of multivariate distributed polynomial ring. """ + + def __init__(self, ring, init): + super().__init__(init) + self.ring = ring + # This check would be too slow to run every time: + # self._check() + + def _check(self): + assert isinstance(self, PolyElement) + assert isinstance(self.ring, PolyRing) + dom = self.ring.domain + assert isinstance(dom, Domain) + for monom, coeff in self.items(): + assert dom.of_type(coeff) + assert len(monom) == self.ring.ngens + assert all(isinstance(exp, int) and exp >= 0 for exp in monom) + + def new(self, init): + return self.__class__(self.ring, init) + + def parent(self): + return self.ring.to_domain() + + def __getnewargs__(self): + return (self.ring, list(self.iterterms())) + + _hash = None + + def __hash__(self): + # XXX: This computes a hash of a dictionary, but currently we don't + # protect dictionary from being changed so any use site modifications + # will make hashing go wrong. Use this feature with caution until we + # figure out how to make a safe API without compromising speed of this + # low-level class. + _hash = self._hash + if _hash is None: + self._hash = _hash = hash((self.ring, frozenset(self.items()))) + return _hash + + def copy(self): + """Return a copy of polynomial self. + + Polynomials are mutable; if one is interested in preserving + a polynomial, and one plans to use inplace operations, one + can copy the polynomial. This method makes a shallow copy. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + + >>> R, x, y = ring('x, y', ZZ) + >>> p = (x + y)**2 + >>> p1 = p.copy() + >>> p2 = p + >>> p[R.zero_monom] = 3 + >>> p + x**2 + 2*x*y + y**2 + 3 + >>> p1 + x**2 + 2*x*y + y**2 + >>> p2 + x**2 + 2*x*y + y**2 + 3 + + """ + return self.new(self) + + def set_ring(self, new_ring): + if self.ring == new_ring: + return self + elif self.ring.symbols != new_ring.symbols: + terms = list(zip(*_dict_reorder(self, self.ring.symbols, new_ring.symbols))) + return new_ring.from_terms(terms, self.ring.domain) + else: + return new_ring.from_dict(self, self.ring.domain) + + def as_expr(self, *symbols): + if not symbols: + symbols = self.ring.symbols + elif len(symbols) != self.ring.ngens: + raise ValueError( + "Wrong number of symbols, expected %s got %s" % + (self.ring.ngens, len(symbols)) + ) + + return expr_from_dict(self.as_expr_dict(), *symbols) + + def as_expr_dict(self): + to_sympy = self.ring.domain.to_sympy + return {monom: to_sympy(coeff) for monom, coeff in self.iterterms()} + + def clear_denoms(self): + domain = self.ring.domain + + if not domain.is_Field or not domain.has_assoc_Ring: + return domain.one, self + + ground_ring = domain.get_ring() + common = ground_ring.one + lcm = ground_ring.lcm + denom = domain.denom + + for coeff in self.values(): + common = lcm(common, denom(coeff)) + + poly = self.new([ (k, v*common) for k, v in self.items() ]) + return common, poly + + def strip_zero(self): + """Eliminate monomials with zero coefficient. """ + for k, v in list(self.items()): + if not v: + del self[k] + + def __eq__(p1, p2): + """Equality test for polynomials. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + + >>> _, x, y = ring('x, y', ZZ) + >>> p1 = (x + y)**2 + (x - y)**2 + >>> p1 == 4*x*y + False + >>> p1 == 2*(x**2 + y**2) + True + + """ + if not p2: + return not p1 + elif p1.ring.is_element(p2): + return dict.__eq__(p1, p2) + elif len(p1) > 1: + return False + else: + return p1.get(p1.ring.zero_monom) == p2 + + def __ne__(p1, p2): + return not p1 == p2 + + def almosteq(p1, p2, tolerance=None): + """Approximate equality test for polynomials. """ + ring = p1.ring + + if ring.is_element(p2): + if set(p1.keys()) != set(p2.keys()): + return False + + almosteq = ring.domain.almosteq + + for k in p1.keys(): + if not almosteq(p1[k], p2[k], tolerance): + return False + return True + elif len(p1) > 1: + return False + else: + try: + p2 = ring.domain.convert(p2) + except CoercionFailed: + return False + else: + return ring.domain.almosteq(p1.const(), p2, tolerance) + + def sort_key(self): + return (len(self), self.terms()) + + def _cmp(p1, p2, op): + if p1.ring.is_element(p2): + return op(p1.sort_key(), p2.sort_key()) + else: + return NotImplemented + + def __lt__(p1, p2): + return p1._cmp(p2, lt) + def __le__(p1, p2): + return p1._cmp(p2, le) + def __gt__(p1, p2): + return p1._cmp(p2, gt) + def __ge__(p1, p2): + return p1._cmp(p2, ge) + + def _drop(self, gen): + ring = self.ring + i = ring.index(gen) + + if ring.ngens == 1: + return i, ring.domain + else: + symbols = list(ring.symbols) + del symbols[i] + return i, ring.clone(symbols=symbols) + + def drop(self, gen): + i, ring = self._drop(gen) + + if self.ring.ngens == 1: + if self.is_ground: + return self.coeff(1) + else: + raise ValueError("Cannot drop %s" % gen) + else: + poly = ring.zero + + for k, v in self.items(): + if k[i] == 0: + K = list(k) + del K[i] + poly[tuple(K)] = v + else: + raise ValueError("Cannot drop %s" % gen) + + return poly + + def _drop_to_ground(self, gen): + ring = self.ring + i = ring.index(gen) + + symbols = list(ring.symbols) + del symbols[i] + return i, ring.clone(symbols=symbols, domain=ring[i]) + + def drop_to_ground(self, gen): + if self.ring.ngens == 1: + raise ValueError("Cannot drop only generator to ground") + + i, ring = self._drop_to_ground(gen) + poly = ring.zero + gen = ring.domain.gens[0] + + for monom, coeff in self.iterterms(): + mon = monom[:i] + monom[i+1:] + if mon not in poly: + poly[mon] = (gen**monom[i]).mul_ground(coeff) + else: + poly[mon] += (gen**monom[i]).mul_ground(coeff) + + return poly + + def to_dense(self): + return dmp_from_dict(self, self.ring.ngens-1, self.ring.domain) + + def to_dict(self): + return dict(self) + + def str(self, printer, precedence, exp_pattern, mul_symbol): + if not self: + return printer._print(self.ring.domain.zero) + prec_mul = precedence["Mul"] + prec_atom = precedence["Atom"] + ring = self.ring + symbols = ring.symbols + ngens = ring.ngens + zm = ring.zero_monom + sexpvs = [] + for expv, coeff in self.terms(): + negative = ring.domain.is_negative(coeff) + sign = " - " if negative else " + " + sexpvs.append(sign) + if expv == zm: + scoeff = printer._print(coeff) + if negative and scoeff.startswith("-"): + scoeff = scoeff[1:] + else: + if negative: + coeff = -coeff + if coeff != self.ring.domain.one: + scoeff = printer.parenthesize(coeff, prec_mul, strict=True) + else: + scoeff = '' + sexpv = [] + for i in range(ngens): + exp = expv[i] + if not exp: + continue + symbol = printer.parenthesize(symbols[i], prec_atom, strict=True) + if exp != 1: + if exp != int(exp) or exp < 0: + sexp = printer.parenthesize(exp, prec_atom, strict=False) + else: + sexp = exp + sexpv.append(exp_pattern % (symbol, sexp)) + else: + sexpv.append('%s' % symbol) + if scoeff: + sexpv = [scoeff] + sexpv + sexpvs.append(mul_symbol.join(sexpv)) + if sexpvs[0] in [" + ", " - "]: + head = sexpvs.pop(0) + if head == " - ": + sexpvs.insert(0, "-") + return "".join(sexpvs) + + @property + def is_generator(self): + return self in self.ring._gens_set + + @property + def is_ground(self): + return not self or (len(self) == 1 and self.ring.zero_monom in self) + + @property + def is_monomial(self): + return not self or (len(self) == 1 and self.LC == 1) + + @property + def is_term(self): + return len(self) <= 1 + + @property + def is_negative(self): + return self.ring.domain.is_negative(self.LC) + + @property + def is_positive(self): + return self.ring.domain.is_positive(self.LC) + + @property + def is_nonnegative(self): + return self.ring.domain.is_nonnegative(self.LC) + + @property + def is_nonpositive(self): + return self.ring.domain.is_nonpositive(self.LC) + + @property + def is_zero(f): + return not f + + @property + def is_one(f): + return f == f.ring.one + + @property + def is_monic(f): + return f.ring.domain.is_one(f.LC) + + @property + def is_primitive(f): + return f.ring.domain.is_one(f.content()) + + @property + def is_linear(f): + return all(sum(monom) <= 1 for monom in f.itermonoms()) + + @property + def is_quadratic(f): + return all(sum(monom) <= 2 for monom in f.itermonoms()) + + @property + def is_squarefree(f): + if not f.ring.ngens: + return True + return f.ring.dmp_sqf_p(f) + + @property + def is_irreducible(f): + if not f.ring.ngens: + return True + return f.ring.dmp_irreducible_p(f) + + @property + def is_cyclotomic(f): + if f.ring.is_univariate: + return f.ring.dup_cyclotomic_p(f) + else: + raise MultivariatePolynomialError("cyclotomic polynomial") + + def __neg__(self): + return self.new([ (monom, -coeff) for monom, coeff in self.iterterms() ]) + + def __pos__(self): + return self + + def __add__(p1, p2): + """Add two polynomials. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + + >>> _, x, y = ring('x, y', ZZ) + >>> (x + y)**2 + (x - y)**2 + 2*x**2 + 2*y**2 + + """ + if not p2: + return p1.copy() + ring = p1.ring + if ring.is_element(p2): + p = p1.copy() + get = p.get + zero = ring.domain.zero + for k, v in p2.items(): + v = get(k, zero) + v + if v: + p[k] = v + else: + del p[k] + return p + elif isinstance(p2, PolyElement): + if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: + pass + elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: + return p2.__radd__(p1) + else: + return NotImplemented + + try: + cp2 = ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + p = p1.copy() + if not cp2: + return p + zm = ring.zero_monom + if zm not in p1.keys(): + p[zm] = cp2 + else: + if p2 == -p[zm]: + del p[zm] + else: + p[zm] += cp2 + return p + + def __radd__(p1, n): + p = p1.copy() + if not n: + return p + ring = p1.ring + try: + n = ring.domain_new(n) + except CoercionFailed: + return NotImplemented + else: + zm = ring.zero_monom + if zm not in p1.keys(): + p[zm] = n + else: + if n == -p[zm]: + del p[zm] + else: + p[zm] += n + return p + + def __sub__(p1, p2): + """Subtract polynomial p2 from p1. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + + >>> _, x, y = ring('x, y', ZZ) + >>> p1 = x + y**2 + >>> p2 = x*y + y**2 + >>> p1 - p2 + -x*y + x + + """ + if not p2: + return p1.copy() + ring = p1.ring + if ring.is_element(p2): + p = p1.copy() + get = p.get + zero = ring.domain.zero + for k, v in p2.items(): + v = get(k, zero) - v + if v: + p[k] = v + else: + del p[k] + return p + elif isinstance(p2, PolyElement): + if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: + pass + elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: + return p2.__rsub__(p1) + else: + return NotImplemented + + try: + p2 = ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + p = p1.copy() + zm = ring.zero_monom + if zm not in p1.keys(): + p[zm] = -p2 + else: + if p2 == p[zm]: + del p[zm] + else: + p[zm] -= p2 + return p + + def __rsub__(p1, n): + """n - p1 with n convertible to the coefficient domain. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + + >>> _, x, y = ring('x, y', ZZ) + >>> p = x + y + >>> 4 - p + -x - y + 4 + + """ + ring = p1.ring + try: + n = ring.domain_new(n) + except CoercionFailed: + return NotImplemented + else: + p = ring.zero + for expv in p1: + p[expv] = -p1[expv] + p += n + # p._check() + return p + + def __mul__(p1, p2): + """Multiply two polynomials. + + Examples + ======== + + >>> from sympy.polys.domains import QQ + >>> from sympy.polys.rings import ring + + >>> _, x, y = ring('x, y', QQ) + >>> p1 = x + y + >>> p2 = x - y + >>> p1*p2 + x**2 - y**2 + + """ + ring = p1.ring + p = ring.zero + if not p1 or not p2: + return p + elif ring.is_element(p2): + get = p.get + zero = ring.domain.zero + monomial_mul = ring.monomial_mul + p2it = list(p2.items()) + for exp1, v1 in p1.items(): + for exp2, v2 in p2it: + exp = monomial_mul(exp1, exp2) + p[exp] = get(exp, zero) + v1*v2 + p.strip_zero() + # p._check() + return p + elif isinstance(p2, PolyElement): + if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: + pass + elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: + return p2.__rmul__(p1) + else: + return NotImplemented + + try: + p2 = ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + for exp1, v1 in p1.items(): + v = v1*p2 + if v: + p[exp1] = v + # p._check() + return p + + def __rmul__(p1, p2): + """p2 * p1 with p2 in the coefficient domain of p1. + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + + >>> _, x, y = ring('x, y', ZZ) + >>> p = x + y + >>> 4 * p + 4*x + 4*y + + """ + p = p1.ring.zero + if not p2: + return p + try: + p2 = p.ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + for exp1, v1 in p1.items(): + v = p2*v1 + if v: + p[exp1] = v + return p + + def __pow__(self, n): + """raise polynomial to power `n` + + Examples + ======== + + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.rings import ring + + >>> _, x, y = ring('x, y', ZZ) + >>> p = x + y**2 + >>> p**3 + x**3 + 3*x**2*y**2 + 3*x*y**4 + y**6 + + """ + if not isinstance(n, int): + raise TypeError("exponent must be an integer, got %s" % n) + elif n < 0: + raise ValueError("exponent must be a non-negative integer, got %s" % n) + + ring = self.ring + + if not n: + if self: + return ring.one + else: + raise ValueError("0**0") + elif len(self) == 1: + monom, coeff = list(self.items())[0] + p = ring.zero + if coeff == ring.domain.one: + p[ring.monomial_pow(monom, n)] = coeff + else: + p[ring.monomial_pow(monom, n)] = coeff**n + # p._check() + return p + + # For ring series, we need negative and rational exponent support only + # with monomials. + n = int(n) + if n < 0: + raise ValueError("Negative exponent") + + elif n == 1: + return self.copy() + elif n == 2: + return self.square() + elif n == 3: + return self*self.square() + elif len(self) <= 5: # TODO: use an actual density measure + return self._pow_multinomial(n) + else: + return self._pow_generic(n) + + def _pow_generic(self, n): + p = self.ring.one + c = self + + while True: + if n & 1: + p = p*c + n -= 1 + if not n: + break + + c = c.square() + n = n // 2 + + return p + + def _pow_multinomial(self, n): + multinomials = multinomial_coefficients(len(self), n).items() + monomial_mulpow = self.ring.monomial_mulpow + zero_monom = self.ring.zero_monom + terms = self.items() + zero = self.ring.domain.zero + poly = self.ring.zero + + for multinomial, multinomial_coeff in multinomials: + product_monom = zero_monom + product_coeff = multinomial_coeff + + for exp, (monom, coeff) in zip(multinomial, terms): + if exp: + product_monom = monomial_mulpow(product_monom, monom, exp) + product_coeff *= coeff**exp + + monom = tuple(product_monom) + coeff = product_coeff + + coeff = poly.get(monom, zero) + coeff + + if coeff: + poly[monom] = coeff + elif monom in poly: + del poly[monom] + + return poly + + def square(self): + """square of a polynomial + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y = ring('x, y', ZZ) + >>> p = x + y**2 + >>> p.square() + x**2 + 2*x*y**2 + y**4 + + """ + ring = self.ring + p = ring.zero + get = p.get + keys = list(self.keys()) + zero = ring.domain.zero + monomial_mul = ring.monomial_mul + for i in range(len(keys)): + k1 = keys[i] + pk = self[k1] + for j in range(i): + k2 = keys[j] + exp = monomial_mul(k1, k2) + p[exp] = get(exp, zero) + pk*self[k2] + p = p.imul_num(2) + get = p.get + for k, v in self.items(): + k2 = monomial_mul(k, k) + p[k2] = get(k2, zero) + v**2 + p.strip_zero() + # p._check() + return p + + def __divmod__(p1, p2): + ring = p1.ring + + if not p2: + raise ZeroDivisionError("polynomial division") + elif ring.is_element(p2): + return p1.div(p2) + elif isinstance(p2, PolyElement): + if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: + pass + elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: + return p2.__rdivmod__(p1) + else: + return NotImplemented + + try: + p2 = ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + return (p1.quo_ground(p2), p1.rem_ground(p2)) + + def __rdivmod__(p1, p2): + ring = p1.ring + try: + p2 = ring.ground_new(p2) + except CoercionFailed: + return NotImplemented + else: + return p2.div(p1) + + def __mod__(p1, p2): + ring = p1.ring + + if not p2: + raise ZeroDivisionError("polynomial division") + elif ring.is_element(p2): + return p1.rem(p2) + elif isinstance(p2, PolyElement): + if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: + pass + elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: + return p2.__rmod__(p1) + else: + return NotImplemented + + try: + p2 = ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + return p1.rem_ground(p2) + + def __rmod__(p1, p2): + ring = p1.ring + try: + p2 = ring.ground_new(p2) + except CoercionFailed: + return NotImplemented + else: + return p2.rem(p1) + + def __floordiv__(p1, p2): + ring = p1.ring + + if not p2: + raise ZeroDivisionError("polynomial division") + elif ring.is_element(p2): + return p1.quo(p2) + elif isinstance(p2, PolyElement): + if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: + pass + elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: + return p2.__rtruediv__(p1) + else: + return NotImplemented + + try: + p2 = ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + return p1.quo_ground(p2) + + def __rfloordiv__(p1, p2): + ring = p1.ring + try: + p2 = ring.ground_new(p2) + except CoercionFailed: + return NotImplemented + else: + return p2.quo(p1) + + def __truediv__(p1, p2): + ring = p1.ring + + if not p2: + raise ZeroDivisionError("polynomial division") + elif ring.is_element(p2): + return p1.exquo(p2) + elif isinstance(p2, PolyElement): + if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: + pass + elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: + return p2.__rtruediv__(p1) + else: + return NotImplemented + + try: + p2 = ring.domain_new(p2) + except CoercionFailed: + return NotImplemented + else: + return p1.quo_ground(p2) + + def __rtruediv__(p1, p2): + ring = p1.ring + try: + p2 = ring.ground_new(p2) + except CoercionFailed: + return NotImplemented + else: + return p2.exquo(p1) + + def _term_div(self): + zm = self.ring.zero_monom + domain = self.ring.domain + domain_quo = domain.quo + monomial_div = self.ring.monomial_div + + if domain.is_Field: + def term_div(a_lm_a_lc, b_lm_b_lc): + a_lm, a_lc = a_lm_a_lc + b_lm, b_lc = b_lm_b_lc + if b_lm == zm: # apparently this is a very common case + monom = a_lm + else: + monom = monomial_div(a_lm, b_lm) + if monom is not None: + return monom, domain_quo(a_lc, b_lc) + else: + return None + else: + def term_div(a_lm_a_lc, b_lm_b_lc): + a_lm, a_lc = a_lm_a_lc + b_lm, b_lc = b_lm_b_lc + if b_lm == zm: # apparently this is a very common case + monom = a_lm + else: + monom = monomial_div(a_lm, b_lm) + if not (monom is None or a_lc % b_lc): + return monom, domain_quo(a_lc, b_lc) + else: + return None + + return term_div + + def div(self, fv): + """Division algorithm, see [CLO] p64. + + fv array of polynomials + return qv, r such that + self = sum(fv[i]*qv[i]) + r + + All polynomials are required not to be Laurent polynomials. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y = ring('x, y', ZZ) + >>> f = x**3 + >>> f0 = x - y**2 + >>> f1 = x - y + >>> qv, r = f.div((f0, f1)) + >>> qv[0] + x**2 + x*y**2 + y**4 + >>> qv[1] + 0 + >>> r + y**6 + + """ + ring = self.ring + ret_single = False + if isinstance(fv, PolyElement): + ret_single = True + fv = [fv] + if not all(fv): + raise ZeroDivisionError("polynomial division") + if not self: + if ret_single: + return ring.zero, ring.zero + else: + return [], ring.zero + for f in fv: + if f.ring != ring: + raise ValueError('self and f must have the same ring') + s = len(fv) + qv = [ring.zero for i in range(s)] + p = self.copy() + r = ring.zero + term_div = self._term_div() + expvs = [fx.leading_expv() for fx in fv] + while p: + i = 0 + divoccurred = 0 + while i < s and divoccurred == 0: + expv = p.leading_expv() + term = term_div((expv, p[expv]), (expvs[i], fv[i][expvs[i]])) + if term is not None: + expv1, c = term + qv[i] = qv[i]._iadd_monom((expv1, c)) + p = p._iadd_poly_monom(fv[i], (expv1, -c)) + divoccurred = 1 + else: + i += 1 + if not divoccurred: + expv = p.leading_expv() + r = r._iadd_monom((expv, p[expv])) + del p[expv] + if expv == ring.zero_monom: + r += p + if ret_single: + if not qv: + return ring.zero, r + else: + return qv[0], r + else: + return qv, r + + def rem(self, G): + f = self + if isinstance(G, PolyElement): + G = [G] + if not all(G): + raise ZeroDivisionError("polynomial division") + ring = f.ring + domain = ring.domain + zero = domain.zero + monomial_mul = ring.monomial_mul + r = ring.zero + term_div = f._term_div() + ltf = f.LT + f = f.copy() + get = f.get + while f: + for g in G: + tq = term_div(ltf, g.LT) + if tq is not None: + m, c = tq + for mg, cg in g.iterterms(): + m1 = monomial_mul(mg, m) + c1 = get(m1, zero) - c*cg + if not c1: + del f[m1] + else: + f[m1] = c1 + ltm = f.leading_expv() + if ltm is not None: + ltf = ltm, f[ltm] + + break + else: + ltm, ltc = ltf + if ltm in r: + r[ltm] += ltc + else: + r[ltm] = ltc + del f[ltm] + ltm = f.leading_expv() + if ltm is not None: + ltf = ltm, f[ltm] + + return r + + def quo(f, G): + return f.div(G)[0] + + def exquo(f, G): + q, r = f.div(G) + + if not r: + return q + else: + raise ExactQuotientFailed(f, G) + + def _iadd_monom(self, mc): + """add to self the monomial coeff*x0**i0*x1**i1*... + unless self is a generator -- then just return the sum of the two. + + mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...) + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y = ring('x, y', ZZ) + >>> p = x**4 + 2*y + >>> m = (1, 2) + >>> p1 = p._iadd_monom((m, 5)) + >>> p1 + x**4 + 5*x*y**2 + 2*y + >>> p1 is p + True + >>> p = x + >>> p1 = p._iadd_monom((m, 5)) + >>> p1 + 5*x*y**2 + x + >>> p1 is p + False + + """ + if self in self.ring._gens_set: + cpself = self.copy() + else: + cpself = self + expv, coeff = mc + c = cpself.get(expv) + if c is None: + cpself[expv] = coeff + else: + c += coeff + if c: + cpself[expv] = c + else: + del cpself[expv] + return cpself + + def _iadd_poly_monom(self, p2, mc): + """add to self the product of (p)*(coeff*x0**i0*x1**i1*...) + unless self is a generator -- then just return the sum of the two. + + mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...) + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y, z = ring('x, y, z', ZZ) + >>> p1 = x**4 + 2*y + >>> p2 = y + z + >>> m = (1, 2, 3) + >>> p1 = p1._iadd_poly_monom(p2, (m, 3)) + >>> p1 + x**4 + 3*x*y**3*z**3 + 3*x*y**2*z**4 + 2*y + + """ + p1 = self + if p1 in p1.ring._gens_set: + p1 = p1.copy() + (m, c) = mc + get = p1.get + zero = p1.ring.domain.zero + monomial_mul = p1.ring.monomial_mul + for k, v in p2.items(): + ka = monomial_mul(k, m) + coeff = get(ka, zero) + v*c + if coeff: + p1[ka] = coeff + else: + del p1[ka] + return p1 + + def degree(f, x=None): + """ + The leading degree in ``x`` or the main variable. + + Note that the degree of 0 is negative infinity (``float('-inf')``) + + """ + i = f.ring.index(x) + + if not f: + return ninf + elif i < 0: + return 0 + else: + return max(monom[i] for monom in f.itermonoms()) + + def degrees(f): + """ + A tuple containing leading degrees in all variables. + + Note that the degree of 0 is negative infinity (``float('-inf')``) + + """ + if not f: + return (ninf,)*f.ring.ngens + else: + return tuple(map(max, list(zip(*f.itermonoms())))) + + def tail_degree(f, x=None): + """ + The tail degree in ``x`` or the main variable. + + Note that the degree of 0 is negative infinity (``float('-inf')``) + + """ + i = f.ring.index(x) + + if not f: + return ninf + elif i < 0: + return 0 + else: + return min(monom[i] for monom in f.itermonoms()) + + def tail_degrees(f): + """ + A tuple containing tail degrees in all variables. + + Note that the degree of 0 is negative infinity (``float('-inf')``) + + """ + if not f: + return (ninf,)*f.ring.ngens + else: + return tuple(map(min, list(zip(*f.itermonoms())))) + + def leading_expv(self): + """Leading monomial tuple according to the monomial ordering. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y, z = ring('x, y, z', ZZ) + >>> p = x**4 + x**3*y + x**2*z**2 + z**7 + >>> p.leading_expv() + (4, 0, 0) + + """ + if self: + return self.ring.leading_expv(self) + else: + return None + + def _get_coeff(self, expv): + return self.get(expv, self.ring.domain.zero) + + def coeff(self, element): + """ + Returns the coefficient that stands next to the given monomial. + + Parameters + ========== + + element : PolyElement (with ``is_monomial = True``) or 1 + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y, z = ring("x,y,z", ZZ) + >>> f = 3*x**2*y - x*y*z + 7*z**3 + 23 + + >>> f.coeff(x**2*y) + 3 + >>> f.coeff(x*y) + 0 + >>> f.coeff(1) + 23 + + """ + if element == 1: + return self._get_coeff(self.ring.zero_monom) + elif self.ring.is_element(element): + terms = list(element.iterterms()) + if len(terms) == 1: + monom, coeff = terms[0] + if coeff == self.ring.domain.one: + return self._get_coeff(monom) + + raise ValueError("expected a monomial, got %s" % element) + + def const(self): + """Returns the constant coefficient. """ + return self._get_coeff(self.ring.zero_monom) + + @property + def LC(self): + return self._get_coeff(self.leading_expv()) + + @property + def LM(self): + expv = self.leading_expv() + if expv is None: + return self.ring.zero_monom + else: + return expv + + def leading_monom(self): + """ + Leading monomial as a polynomial element. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y = ring('x, y', ZZ) + >>> (3*x*y + y**2).leading_monom() + x*y + + """ + p = self.ring.zero + expv = self.leading_expv() + if expv: + p[expv] = self.ring.domain.one + return p + + @property + def LT(self): + expv = self.leading_expv() + if expv is None: + return (self.ring.zero_monom, self.ring.domain.zero) + else: + return (expv, self._get_coeff(expv)) + + def leading_term(self): + """Leading term as a polynomial element. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y = ring('x, y', ZZ) + >>> (3*x*y + y**2).leading_term() + 3*x*y + + """ + p = self.ring.zero + expv = self.leading_expv() + if expv is not None: + p[expv] = self[expv] + return p + + def _sorted(self, seq, order): + if order is None: + order = self.ring.order + else: + order = OrderOpt.preprocess(order) + + if order is lex: + return sorted(seq, key=lambda monom: monom[0], reverse=True) + else: + return sorted(seq, key=lambda monom: order(monom[0]), reverse=True) + + def coeffs(self, order=None): + """Ordered list of polynomial coefficients. + + Parameters + ========== + + order : :class:`~.MonomialOrder` or coercible, optional + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.orderings import lex, grlex + + >>> _, x, y = ring("x, y", ZZ, lex) + >>> f = x*y**7 + 2*x**2*y**3 + + >>> f.coeffs() + [2, 1] + >>> f.coeffs(grlex) + [1, 2] + + """ + return [ coeff for _, coeff in self.terms(order) ] + + def monoms(self, order=None): + """Ordered list of polynomial monomials. + + Parameters + ========== + + order : :class:`~.MonomialOrder` or coercible, optional + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.orderings import lex, grlex + + >>> _, x, y = ring("x, y", ZZ, lex) + >>> f = x*y**7 + 2*x**2*y**3 + + >>> f.monoms() + [(2, 3), (1, 7)] + >>> f.monoms(grlex) + [(1, 7), (2, 3)] + + """ + return [ monom for monom, _ in self.terms(order) ] + + def terms(self, order=None): + """Ordered list of polynomial terms. + + Parameters + ========== + + order : :class:`~.MonomialOrder` or coercible, optional + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> from sympy.polys.orderings import lex, grlex + + >>> _, x, y = ring("x, y", ZZ, lex) + >>> f = x*y**7 + 2*x**2*y**3 + + >>> f.terms() + [((2, 3), 2), ((1, 7), 1)] + >>> f.terms(grlex) + [((1, 7), 1), ((2, 3), 2)] + + """ + return self._sorted(list(self.items()), order) + + def itercoeffs(self): + """Iterator over coefficients of a polynomial. """ + return iter(self.values()) + + def itermonoms(self): + """Iterator over monomials of a polynomial. """ + return iter(self.keys()) + + def iterterms(self): + """Iterator over terms of a polynomial. """ + return iter(self.items()) + + def listcoeffs(self): + """Unordered list of polynomial coefficients. """ + return list(self.values()) + + def listmonoms(self): + """Unordered list of polynomial monomials. """ + return list(self.keys()) + + def listterms(self): + """Unordered list of polynomial terms. """ + return list(self.items()) + + def imul_num(p, c): + """multiply inplace the polynomial p by an element in the + coefficient ring, provided p is not one of the generators; + else multiply not inplace + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y = ring('x, y', ZZ) + >>> p = x + y**2 + >>> p1 = p.imul_num(3) + >>> p1 + 3*x + 3*y**2 + >>> p1 is p + True + >>> p = x + >>> p1 = p.imul_num(3) + >>> p1 + 3*x + >>> p1 is p + False + + """ + if p in p.ring._gens_set: + return p*c + if not c: + p.clear() + return + for exp in p: + p[exp] *= c + return p + + def content(f): + """Returns GCD of polynomial's coefficients. """ + domain = f.ring.domain + cont = domain.zero + gcd = domain.gcd + + for coeff in f.itercoeffs(): + cont = gcd(cont, coeff) + + return cont + + def primitive(f): + """Returns content and a primitive polynomial. """ + cont = f.content() + if cont == f.ring.domain.zero: + return (cont, f) + return cont, f.quo_ground(cont) + + def monic(f): + """Divides all coefficients by the leading coefficient. """ + if not f: + return f + else: + return f.quo_ground(f.LC) + + def mul_ground(f, x): + if not x: + return f.ring.zero + + terms = [ (monom, coeff*x) for monom, coeff in f.iterterms() ] + return f.new(terms) + + def mul_monom(f, monom): + monomial_mul = f.ring.monomial_mul + terms = [ (monomial_mul(f_monom, monom), f_coeff) for f_monom, f_coeff in f.items() ] + return f.new(terms) + + def mul_term(f, term): + monom, coeff = term + + if not f or not coeff: + return f.ring.zero + elif monom == f.ring.zero_monom: + return f.mul_ground(coeff) + + monomial_mul = f.ring.monomial_mul + terms = [ (monomial_mul(f_monom, monom), f_coeff*coeff) for f_monom, f_coeff in f.items() ] + return f.new(terms) + + def quo_ground(f, x): + domain = f.ring.domain + + if not x: + raise ZeroDivisionError('polynomial division') + if not f or x == domain.one: + return f + + if domain.is_Field: + quo = domain.quo + terms = [ (monom, quo(coeff, x)) for monom, coeff in f.iterterms() ] + else: + terms = [ (monom, coeff // x) for monom, coeff in f.iterterms() if not (coeff % x) ] + + return f.new(terms) + + def quo_term(f, term): + monom, coeff = term + + if not coeff: + raise ZeroDivisionError("polynomial division") + elif not f: + return f.ring.zero + elif monom == f.ring.zero_monom: + return f.quo_ground(coeff) + + term_div = f._term_div() + + terms = [ term_div(t, term) for t in f.iterterms() ] + return f.new([ t for t in terms if t is not None ]) + + def trunc_ground(f, p): + if f.ring.domain.is_ZZ: + terms = [] + + for monom, coeff in f.iterterms(): + coeff = coeff % p + + if coeff > p // 2: + coeff = coeff - p + + terms.append((monom, coeff)) + else: + terms = [ (monom, coeff % p) for monom, coeff in f.iterterms() ] + + poly = f.new(terms) + poly.strip_zero() + return poly + + rem_ground = trunc_ground + + def extract_ground(self, g): + f = self + fc = f.content() + gc = g.content() + + gcd = f.ring.domain.gcd(fc, gc) + + f = f.quo_ground(gcd) + g = g.quo_ground(gcd) + + return gcd, f, g + + def _norm(f, norm_func): + if not f: + return f.ring.domain.zero + else: + ground_abs = f.ring.domain.abs + return norm_func([ ground_abs(coeff) for coeff in f.itercoeffs() ]) + + def max_norm(f): + return f._norm(max) + + def l1_norm(f): + return f._norm(sum) + + def deflate(f, *G): + ring = f.ring + polys = [f] + list(G) + + J = [0]*ring.ngens + + for p in polys: + for monom in p.itermonoms(): + for i, m in enumerate(monom): + J[i] = igcd(J[i], m) + + for i, b in enumerate(J): + if not b: + J[i] = 1 + + J = tuple(J) + + if all(b == 1 for b in J): + return J, polys + + H = [] + + for p in polys: + h = ring.zero + + for I, coeff in p.iterterms(): + N = [ i // j for i, j in zip(I, J) ] + h[tuple(N)] = coeff + + H.append(h) + + return J, H + + def inflate(f, J): + poly = f.ring.zero + + for I, coeff in f.iterterms(): + N = [ i*j for i, j in zip(I, J) ] + poly[tuple(N)] = coeff + + return poly + + def lcm(self, g): + f = self + domain = f.ring.domain + + if not domain.is_Field: + fc, f = f.primitive() + gc, g = g.primitive() + c = domain.lcm(fc, gc) + + h = (f*g).quo(f.gcd(g)) + + if not domain.is_Field: + return h.mul_ground(c) + else: + return h.monic() + + def gcd(f, g): + return f.cofactors(g)[0] + + def cofactors(f, g): + if not f and not g: + zero = f.ring.zero + return zero, zero, zero + elif not f: + h, cff, cfg = f._gcd_zero(g) + return h, cff, cfg + elif not g: + h, cfg, cff = g._gcd_zero(f) + return h, cff, cfg + elif len(f) == 1: + h, cff, cfg = f._gcd_monom(g) + return h, cff, cfg + elif len(g) == 1: + h, cfg, cff = g._gcd_monom(f) + return h, cff, cfg + + J, (f, g) = f.deflate(g) + h, cff, cfg = f._gcd(g) + + return (h.inflate(J), cff.inflate(J), cfg.inflate(J)) + + def _gcd_zero(f, g): + one, zero = f.ring.one, f.ring.zero + if g.is_nonnegative: + return g, zero, one + else: + return -g, zero, -one + + def _gcd_monom(f, g): + ring = f.ring + ground_gcd = ring.domain.gcd + ground_quo = ring.domain.quo + monomial_gcd = ring.monomial_gcd + monomial_ldiv = ring.monomial_ldiv + mf, cf = list(f.iterterms())[0] + _mgcd, _cgcd = mf, cf + for mg, cg in g.iterterms(): + _mgcd = monomial_gcd(_mgcd, mg) + _cgcd = ground_gcd(_cgcd, cg) + h = f.new([(_mgcd, _cgcd)]) + cff = f.new([(monomial_ldiv(mf, _mgcd), ground_quo(cf, _cgcd))]) + cfg = f.new([(monomial_ldiv(mg, _mgcd), ground_quo(cg, _cgcd)) for mg, cg in g.iterterms()]) + return h, cff, cfg + + def _gcd(f, g): + ring = f.ring + + if ring.domain.is_QQ: + return f._gcd_QQ(g) + elif ring.domain.is_ZZ: + return f._gcd_ZZ(g) + else: # TODO: don't use dense representation (port PRS algorithms) + return ring.dmp_inner_gcd(f, g) + + def _gcd_ZZ(f, g): + return heugcd(f, g) + + def _gcd_QQ(self, g): + f = self + ring = f.ring + new_ring = ring.clone(domain=ring.domain.get_ring()) + + cf, f = f.clear_denoms() + cg, g = g.clear_denoms() + + f = f.set_ring(new_ring) + g = g.set_ring(new_ring) + + h, cff, cfg = f._gcd_ZZ(g) + + h = h.set_ring(ring) + c, h = h.LC, h.monic() + + cff = cff.set_ring(ring).mul_ground(ring.domain.quo(c, cf)) + cfg = cfg.set_ring(ring).mul_ground(ring.domain.quo(c, cg)) + + return h, cff, cfg + + def cancel(self, g): + """ + Cancel common factors in a rational function ``f/g``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> (2*x**2 - 2).cancel(x**2 - 2*x + 1) + (2*x + 2, x - 1) + + """ + f = self + ring = f.ring + + if not f: + return f, ring.one + + domain = ring.domain + + if not (domain.is_Field and domain.has_assoc_Ring): + _, p, q = f.cofactors(g) + else: + new_ring = ring.clone(domain=domain.get_ring()) + + cq, f = f.clear_denoms() + cp, g = g.clear_denoms() + + f = f.set_ring(new_ring) + g = g.set_ring(new_ring) + + _, p, q = f.cofactors(g) + _, cp, cq = new_ring.domain.cofactors(cp, cq) + + p = p.set_ring(ring) + q = q.set_ring(ring) + + p = p.mul_ground(cp) + q = q.mul_ground(cq) + + # Make canonical with respect to sign or quadrant in the case of ZZ_I + # or QQ_I. This ensures that the LC of the denominator is canonical by + # multiplying top and bottom by a unit of the ring. + u = q.canonical_unit() + if u == domain.one: + pass + elif u == -domain.one: + p, q = -p, -q + else: + p = p.mul_ground(u) + q = q.mul_ground(u) + + return p, q + + def canonical_unit(f): + domain = f.ring.domain + return domain.canonical_unit(f.LC) + + def diff(f, x): + """Computes partial derivative in ``x``. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + + >>> _, x, y = ring("x,y", ZZ) + >>> p = x + x**2*y**3 + >>> p.diff(x) + 2*x*y**3 + 1 + + """ + ring = f.ring + i = ring.index(x) + m = ring.monomial_basis(i) + g = ring.zero + for expv, coeff in f.iterterms(): + if expv[i]: + e = ring.monomial_ldiv(expv, m) + g[e] = ring.domain_new(coeff*expv[i]) + return g + + def __call__(f, *values): + if 0 < len(values) <= f.ring.ngens: + return f.evaluate(list(zip(f.ring.gens, values))) + else: + raise ValueError("expected at least 1 and at most %s values, got %s" % (f.ring.ngens, len(values))) + + def evaluate(self, x, a=None): + f = self + + if isinstance(x, list) and a is None: + (X, a), x = x[0], x[1:] + f = f.evaluate(X, a) + + if not x: + return f + else: + x = [ (Y.drop(X), a) for (Y, a) in x ] + return f.evaluate(x) + + ring = f.ring + i = ring.index(x) + a = ring.domain.convert(a) + + if ring.ngens == 1: + result = ring.domain.zero + + for (n,), coeff in f.iterterms(): + result += coeff*a**n + + return result + else: + poly = ring.drop(x).zero + + for monom, coeff in f.iterterms(): + n, monom = monom[i], monom[:i] + monom[i+1:] + coeff = coeff*a**n + + if monom in poly: + coeff = coeff + poly[monom] + + if coeff: + poly[monom] = coeff + else: + del poly[monom] + else: + if coeff: + poly[monom] = coeff + + return poly + + def subs(self, x, a=None): + f = self + + if isinstance(x, list) and a is None: + for X, a in x: + f = f.subs(X, a) + return f + + ring = f.ring + i = ring.index(x) + a = ring.domain.convert(a) + + if ring.ngens == 1: + result = ring.domain.zero + + for (n,), coeff in f.iterterms(): + result += coeff*a**n + + return ring.ground_new(result) + else: + poly = ring.zero + + for monom, coeff in f.iterterms(): + n, monom = monom[i], monom[:i] + (0,) + monom[i+1:] + coeff = coeff*a**n + + if monom in poly: + coeff = coeff + poly[monom] + + if coeff: + poly[monom] = coeff + else: + del poly[monom] + else: + if coeff: + poly[monom] = coeff + + return poly + + def symmetrize(self): + r""" + Rewrite *self* in terms of elementary symmetric polynomials. + + Explanation + =========== + + If this :py:class:`~.PolyElement` belongs to a ring of $n$ variables, + we can try to write it as a function of the elementary symmetric + polynomials on $n$ variables. We compute a symmetric part, and a + remainder for any part we were not able to symmetrize. + + Examples + ======== + + >>> from sympy.polys.rings import ring + >>> from sympy.polys.domains import ZZ + >>> R, x, y = ring("x,y", ZZ) + + >>> f = x**2 + y**2 + >>> f.symmetrize() + (x**2 - 2*y, 0, [(x, x + y), (y, x*y)]) + + >>> f = x**2 - y**2 + >>> f.symmetrize() + (x**2 - 2*y, -2*y**2, [(x, x + y), (y, x*y)]) + + Returns + ======= + + Triple ``(p, r, m)`` + ``p`` is a :py:class:`~.PolyElement` that represents our attempt + to express *self* as a function of elementary symmetric + polynomials. Each variable in ``p`` stands for one of the + elementary symmetric polynomials. The correspondence is given + by ``m``. + + ``r`` is the remainder. + + ``m`` is a list of pairs, giving the mapping from variables in + ``p`` to elementary symmetric polynomials. + + The triple satisfies the equation ``p.compose(m) + r == self``. + If the remainder ``r`` is zero, *self* is symmetric. If it is + nonzero, we were not able to represent *self* as symmetric. + + See Also + ======== + + sympy.polys.polyfuncs.symmetrize + + References + ========== + + .. [1] Lauer, E. Algorithms for symmetrical polynomials, Proc. 1976 + ACM Symp. on Symbolic and Algebraic Computing, NY 242-247. + https://dl.acm.org/doi/pdf/10.1145/800205.806342 + + """ + f = self.copy() + ring = f.ring + n = ring.ngens + + if not n: + return f, ring.zero, [] + + polys = [ring.symmetric_poly(i+1) for i in range(n)] + + poly_powers = {} + def get_poly_power(i, n): + if (i, n) not in poly_powers: + poly_powers[(i, n)] = polys[i]**n + return poly_powers[(i, n)] + + indices = list(range(n - 1)) + weights = list(range(n, 0, -1)) + + symmetric = ring.zero + + while f: + _height, _monom, _coeff = -1, None, None + + for i, (monom, coeff) in enumerate(f.terms()): + if all(monom[i] >= monom[i + 1] for i in indices): + height = max(n*m for n, m in zip(weights, monom)) + + if height > _height: + _height, _monom, _coeff = height, monom, coeff + + if _height != -1: + monom, coeff = _monom, _coeff + else: + break + + exponents = [] + for m1, m2 in zip(monom, monom[1:] + (0,)): + exponents.append(m1 - m2) + + symmetric += ring.term_new(tuple(exponents), coeff) + + product = coeff + for i, n in enumerate(exponents): + product *= get_poly_power(i, n) + f -= product + + mapping = list(zip(ring.gens, polys)) + + return symmetric, f, mapping + + def compose(f, x, a=None): + ring = f.ring + poly = ring.zero + gens_map = dict(zip(ring.gens, range(ring.ngens))) + + if a is not None: + replacements = [(x, a)] + else: + if isinstance(x, list): + replacements = list(x) + elif isinstance(x, dict): + replacements = sorted(x.items(), key=lambda k: gens_map[k[0]]) + else: + raise ValueError("expected a generator, value pair a sequence of such pairs") + + for k, (x, g) in enumerate(replacements): + replacements[k] = (gens_map[x], ring.ring_new(g)) + + for monom, coeff in f.iterterms(): + monom = list(monom) + subpoly = ring.one + + for i, g in replacements: + n, monom[i] = monom[i], 0 + if n: + subpoly *= g**n + + subpoly = subpoly.mul_term((tuple(monom), coeff)) + poly += subpoly + + return poly + + def coeff_wrt(self, x, deg): + """ + Coefficient of ``self`` with respect to ``x**deg``. + + Treating ``self`` as a univariate polynomial in ``x`` this finds the + coefficient of ``x**deg`` as a polynomial in the other generators. + + Parameters + ========== + + x : generator or generator index + The generator or generator index to compute the expression for. + deg : int + The degree of the monomial to compute the expression for. + + Returns + ======= + + :py:class:`~.PolyElement` + The coefficient of ``x**deg`` as a polynomial in the same ring. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x, y, z = ring("x, y, z", ZZ) + + >>> p = 2*x**4 + 3*y**4 + 10*z**2 + 10*x*z**2 + >>> deg = 2 + >>> p.coeff_wrt(2, deg) # Using the generator index + 10*x + 10 + >>> p.coeff_wrt(z, deg) # Using the generator + 10*x + 10 + >>> p.coeff(z**2) # shows the difference between coeff and coeff_wrt + 10 + + See Also + ======== + + coeff, coeffs + + """ + p = self + i = p.ring.index(x) + terms = [(m, c) for m, c in p.iterterms() if m[i] == deg] + + if not terms: + return p.ring.zero + + monoms, coeffs = zip(*terms) + monoms = [m[:i] + (0,) + m[i + 1:] for m in monoms] + return p.ring.from_dict(dict(zip(monoms, coeffs))) + + def prem(self, g, x=None): + """ + Pseudo-remainder of the polynomial ``self`` with respect to ``g``. + + The pseudo-quotient ``q`` and pseudo-remainder ``r`` with respect to + ``z`` when dividing ``f`` by ``g`` satisfy ``m*f = g*q + r``, + where ``deg(r,z) < deg(g,z)`` and + ``m = LC(g,z)**(deg(f,z) - deg(g,z)+1)``. + + See :meth:`pdiv` for explanation of pseudo-division. + + + Parameters + ========== + + g : :py:class:`~.PolyElement` + The polynomial to divide ``self`` by. + x : generator or generator index, optional + The main variable of the polynomials and default is first generator. + + Returns + ======= + + :py:class:`~.PolyElement` + The pseudo-remainder polynomial. + + Raises + ====== + + ZeroDivisionError : If ``g`` is the zero polynomial. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x, y = ring("x, y", ZZ) + + >>> f = x**2 + x*y + >>> g = 2*x + 2 + >>> f.prem(g) # first generator is chosen by default if it is not given + -4*y + 4 + >>> f.rem(g) # shows the difference between prem and rem + x**2 + x*y + >>> f.prem(g, y) # generator is given + 0 + >>> f.prem(g, 1) # generator index is given + 0 + + See Also + ======== + + pdiv, pquo, pexquo, sympy.polys.domains.ring.Ring.rem + + """ + f = self + x = f.ring.index(x) + df = f.degree(x) + dg = g.degree(x) + + if dg < 0: + raise ZeroDivisionError('polynomial division') + + r, dr = f, df + + if df < dg: + return r + + N = df - dg + 1 + + lc_g = g.coeff_wrt(x, dg) + + xp = f.ring.gens[x] + + while True: + + lc_r = r.coeff_wrt(x, dr) + j, N = dr - dg, N - 1 + + R = r * lc_g + G = g * lc_r * xp**j + r = R - G + + dr = r.degree(x) + + if dr < dg: + break + + c = lc_g ** N + + return r * c + + def pdiv(self, g, x=None): + """ + Computes the pseudo-division of the polynomial ``self`` with respect to ``g``. + + The pseudo-division algorithm is used to find the pseudo-quotient ``q`` + and pseudo-remainder ``r`` such that ``m*f = g*q + r``, where ``m`` + represents the multiplier and ``f`` is the dividend polynomial. + + The pseudo-quotient ``q`` and pseudo-remainder ``r`` are polynomials in + the variable ``x``, with the degree of ``r`` with respect to ``x`` + being strictly less than the degree of ``g`` with respect to ``x``. + + The multiplier ``m`` is defined as + ``LC(g, x) ^ (deg(f, x) - deg(g, x) + 1)``, + where ``LC(g, x)`` represents the leading coefficient of ``g``. + + It is important to note that in the context of the ``prem`` method, + multivariate polynomials in a ring, such as ``R[x,y,z]``, are treated + as univariate polynomials with coefficients that are polynomials, + such as ``R[x,y][z]``. When dividing ``f`` by ``g`` with respect to the + variable ``z``, the pseudo-quotient ``q`` and pseudo-remainder ``r`` + satisfy ``m*f = g*q + r``, where ``deg(r, z) < deg(g, z)`` + and ``m = LC(g, z)^(deg(f, z) - deg(g, z) + 1)``. + + In this function, the pseudo-remainder ``r`` can be obtained using the + ``prem`` method, the pseudo-quotient ``q`` can + be obtained using the ``pquo`` method, and + the function ``pdiv`` itself returns a tuple ``(q, r)``. + + + Parameters + ========== + + g : :py:class:`~.PolyElement` + The polynomial to divide ``self`` by. + x : generator or generator index, optional + The main variable of the polynomials and default is first generator. + + Returns + ======= + + :py:class:`~.PolyElement` + The pseudo-division polynomial (tuple of ``q`` and ``r``). + + Raises + ====== + + ZeroDivisionError : If ``g`` is the zero polynomial. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x, y = ring("x, y", ZZ) + + >>> f = x**2 + x*y + >>> g = 2*x + 2 + >>> f.pdiv(g) # first generator is chosen by default if it is not given + (2*x + 2*y - 2, -4*y + 4) + >>> f.div(g) # shows the difference between pdiv and div + (0, x**2 + x*y) + >>> f.pdiv(g, y) # generator is given + (2*x**3 + 2*x**2*y + 6*x**2 + 2*x*y + 8*x + 4, 0) + >>> f.pdiv(g, 1) # generator index is given + (2*x**3 + 2*x**2*y + 6*x**2 + 2*x*y + 8*x + 4, 0) + + See Also + ======== + + prem + Computes only the pseudo-remainder more efficiently than + `f.pdiv(g)[1]`. + pquo + Returns only the pseudo-quotient. + pexquo + Returns only an exact pseudo-quotient having no remainder. + div + Returns quotient and remainder of f and g polynomials. + + """ + f = self + x = f.ring.index(x) + + df = f.degree(x) + dg = g.degree(x) + + if dg < 0: + raise ZeroDivisionError("polynomial division") + + q, r, dr = x, f, df + + if df < dg: + return q, r + + N = df - dg + 1 + lc_g = g.coeff_wrt(x, dg) + + xp = f.ring.gens[x] + + while True: + + lc_r = r.coeff_wrt(x, dr) + j, N = dr - dg, N - 1 + + Q = q * lc_g + + q = Q + (lc_r)*xp**j + + R = r * lc_g + + G = g * lc_r * xp**j + + r = R - G + + dr = r.degree(x) + + if dr < dg: + break + + c = lc_g**N + + q = q * c + r = r * c + + return q, r + + def pquo(self, g, x=None): + """ + Polynomial pseudo-quotient in multivariate polynomial ring. + + Examples + ======== + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x**2 + x*y + >>> g = 2*x + 2*y + >>> h = 2*x + 2 + >>> f.pquo(g) + 2*x + >>> f.quo(g) # shows the difference between pquo and quo + 0 + >>> f.pquo(h) + 2*x + 2*y - 2 + >>> f.quo(h) # shows the difference between pquo and quo + 0 + + See Also + ======== + + prem, pdiv, pexquo, sympy.polys.domains.ring.Ring.quo + + """ + f = self + return f.pdiv(g, x)[0] + + def pexquo(self, g, x=None): + """ + Polynomial exact pseudo-quotient in multivariate polynomial ring. + + Examples + ======== + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x**2 + x*y + >>> g = 2*x + 2*y + >>> h = 2*x + 2 + >>> f.pexquo(g) + 2*x + >>> f.exquo(g) # shows the difference between pexquo and exquo + Traceback (most recent call last): + ... + ExactQuotientFailed: 2*x + 2*y does not divide x**2 + x*y + >>> f.pexquo(h) + Traceback (most recent call last): + ... + ExactQuotientFailed: 2*x + 2 does not divide x**2 + x*y + + See Also + ======== + + prem, pdiv, pquo, sympy.polys.domains.ring.Ring.exquo + + """ + f = self + q, r = f.pdiv(g, x) + + if r.is_zero: + return q + else: + raise ExactQuotientFailed(f, g) + + def subresultants(self, g, x=None): + """ + Computes the subresultant PRS of two polynomials ``self`` and ``g``. + + Parameters + ========== + + g : :py:class:`~.PolyElement` + The second polynomial. + x : generator or generator index + The variable with respect to which the subresultant sequence is computed. + + Returns + ======= + + R : list + Returns a list polynomials representing the subresultant PRS. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x, y = ring("x, y", ZZ) + + >>> f = x**2*y + x*y + >>> g = x + y + >>> f.subresultants(g) # first generator is chosen by default if not given + [x**2*y + x*y, x + y, y**3 - y**2] + >>> f.subresultants(g, 0) # generator index is given + [x**2*y + x*y, x + y, y**3 - y**2] + >>> f.subresultants(g, y) # generator is given + [x**2*y + x*y, x + y, x**3 + x**2] + + """ + f = self + x = f.ring.index(x) + n = f.degree(x) + m = g.degree(x) + + if n < m: + f, g = g, f + n, m = m, n + + if f == 0: + return [0, 0] + + if g == 0: + return [f, 1] + + R = [f, g] + + d = n - m + b = (-1) ** (d + 1) + + # Compute the pseudo-remainder for f and g + h = f.prem(g, x) + h = h * b + + # Compute the coefficient of g with respect to x**m + lc = g.coeff_wrt(x, m) + + c = lc ** d + + S = [1, c] + + c = -c + + while h: + k = h.degree(x) + + R.append(h) + f, g, m, d = g, h, k, m - k + + b = -lc * c ** d + h = f.prem(g, x) + h = h.exquo(b) + + lc = g.coeff_wrt(x, k) + + if d > 1: + p = (-lc) ** d + q = c ** (d - 1) + c = p.exquo(q) + else: + c = -lc + + S.append(-c) + + return R + + # TODO: following methods should point to polynomial + # representation independent algorithm implementations. + + def half_gcdex(f, g): + return f.ring.dmp_half_gcdex(f, g) + + def gcdex(f, g): + return f.ring.dmp_gcdex(f, g) + + def resultant(f, g): + return f.ring.dmp_resultant(f, g) + + def discriminant(f): + return f.ring.dmp_discriminant(f) + + def decompose(f): + if f.ring.is_univariate: + return f.ring.dup_decompose(f) + else: + raise MultivariatePolynomialError("polynomial decomposition") + + def shift(f, a): + if f.ring.is_univariate: + return f.ring.dup_shift(f, a) + else: + raise MultivariatePolynomialError("shift: use shift_list instead") + + def shift_list(f, a): + return f.ring.dmp_shift(f, a) + + def sturm(f): + if f.ring.is_univariate: + return f.ring.dup_sturm(f) + else: + raise MultivariatePolynomialError("sturm sequence") + + def gff_list(f): + return f.ring.dmp_gff_list(f) + + def norm(f): + return f.ring.dmp_norm(f) + + def sqf_norm(f): + return f.ring.dmp_sqf_norm(f) + + def sqf_part(f): + return f.ring.dmp_sqf_part(f) + + def sqf_list(f, all=False): + return f.ring.dmp_sqf_list(f, all=all) + + def factor_list(f): + return f.ring.dmp_factor_list(f) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rootisolation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rootisolation.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f8fd115e49ce8dcf4db8659a60c3361818b7bb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rootisolation.py @@ -0,0 +1,2190 @@ +"""Real and complex root isolation and refinement algorithms. """ + + +from sympy.polys.densearith import ( + dup_neg, dup_rshift, dup_rem, + dup_l2_norm_squared) +from sympy.polys.densebasic import ( + dup_LC, dup_TC, dup_degree, + dup_strip, dup_reverse, + dup_convert, + dup_terms_gcd) +from sympy.polys.densetools import ( + dup_clear_denoms, + dup_mirror, dup_scale, dup_shift, + dup_transform, + dup_diff, + dup_eval, dmp_eval_in, + dup_sign_variations, + dup_real_imag) +from sympy.polys.euclidtools import ( + dup_discriminant) +from sympy.polys.factortools import ( + dup_factor_list) +from sympy.polys.polyerrors import ( + RefinementFailed, + DomainError, + PolynomialError) +from sympy.polys.sqfreetools import ( + dup_sqf_part, dup_sqf_list) + + +def dup_sturm(f, K): + """ + Computes the Sturm sequence of ``f`` in ``F[x]``. + + Given a univariate, square-free polynomial ``f(x)`` returns the + associated Sturm sequence ``f_0(x), ..., f_n(x)`` defined by:: + + f_0(x), f_1(x) = f(x), f'(x) + f_n = -rem(f_{n-2}(x), f_{n-1}(x)) + + Examples + ======== + + >>> from sympy.polys import ring, QQ + >>> R, x = ring("x", QQ) + + >>> R.dup_sturm(x**3 - 2*x**2 + x - 3) + [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2/9*x + 25/9, -2079/4] + + References + ========== + + .. [1] [Davenport88]_ + + """ + if not K.is_Field: + raise DomainError("Cannot compute Sturm sequence over %s" % K) + + f = dup_sqf_part(f, K) + + sturm = [f, dup_diff(f, 1, K)] + + while sturm[-1]: + s = dup_rem(sturm[-2], sturm[-1], K) + sturm.append(dup_neg(s, K)) + + return sturm[:-1] + +def dup_root_upper_bound(f, K): + """Compute the LMQ upper bound for the positive roots of `f`; + LMQ (Local Max Quadratic) was developed by Akritas-Strzebonski-Vigklas. + + References + ========== + .. [1] Alkiviadis G. Akritas: "Linear and Quadratic Complexity Bounds on the + Values of the Positive Roots of Polynomials" + Journal of Universal Computer Science, Vol. 15, No. 3, 523-537, 2009. + """ + n, P = len(f), [] + t = n * [K.one] + if dup_LC(f, K) < 0: + f = dup_neg(f, K) + f = list(reversed(f)) + + for i in range(0, n): + if f[i] >= 0: + continue + + a, QL = K.log(-f[i], 2), [] + + for j in range(i + 1, n): + + if f[j] <= 0: + continue + + q = t[j] + a - K.log(f[j], 2) + QL.append([q // (j - i), j]) + + if not QL: + continue + + q = min(QL) + + t[q[1]] = t[q[1]] + 1 + + P.append(q[0]) + + if not P: + return None + else: + return K.get_field()(2)**(max(P) + 1) + +def dup_root_lower_bound(f, K): + """Compute the LMQ lower bound for the positive roots of `f`; + LMQ (Local Max Quadratic) was developed by Akritas-Strzebonski-Vigklas. + + References + ========== + .. [1] Alkiviadis G. Akritas: "Linear and Quadratic Complexity Bounds on the + Values of the Positive Roots of Polynomials" + Journal of Universal Computer Science, Vol. 15, No. 3, 523-537, 2009. + """ + bound = dup_root_upper_bound(dup_reverse(f), K) + + if bound is not None: + return 1/bound + else: + return None + +def dup_cauchy_upper_bound(f, K): + """ + Compute the Cauchy upper bound on the absolute value of all roots of f, + real or complex. + + References + ========== + .. [1] https://en.wikipedia.org/wiki/Geometrical_properties_of_polynomial_roots#Lagrange's_and_Cauchy's_bounds + """ + n = dup_degree(f) + if n < 1: + raise PolynomialError('Polynomial has no roots.') + + if K.is_ZZ: + L = K.get_field() + f, K = dup_convert(f, K, L), L + elif not K.is_QQ or K.is_RR or K.is_CC: + # We need to compute absolute value, and we are not supporting cases + # where this would take us outside the domain (or its quotient field). + raise DomainError('Cauchy bound not supported over %s' % K) + else: + f = f[:] + + while K.is_zero(f[-1]): + f.pop() + if len(f) == 1: + # Monomial. All roots are zero. + return K.zero + + lc = f[0] + return K.one + max(abs(n / lc) for n in f[1:]) + +def dup_cauchy_lower_bound(f, K): + """Compute the Cauchy lower bound on the absolute value of all non-zero + roots of f, real or complex.""" + g = dup_reverse(f) + if len(g) < 2: + raise PolynomialError('Polynomial has no non-zero roots.') + if K.is_ZZ: + K = K.get_field() + b = dup_cauchy_upper_bound(g, K) + return K.one / b + +def dup_mignotte_sep_bound_squared(f, K): + """ + Return the square of the Mignotte lower bound on separation between + distinct roots of f. The square is returned so that the bound lies in + K or its quotient field. + + References + ========== + + .. [1] Mignotte, Maurice. "Some useful bounds." Computer algebra. + Springer, Vienna, 1982. 259-263. + https://people.dm.unipi.it/gianni/AC-EAG/Mignotte.pdf + """ + n = dup_degree(f) + if n < 2: + raise PolynomialError('Polynomials of degree < 2 have no distinct roots.') + + if K.is_ZZ: + L = K.get_field() + f, K = dup_convert(f, K, L), L + elif not K.is_QQ or K.is_RR or K.is_CC: + # We need to compute absolute value, and we are not supporting cases + # where this would take us outside the domain (or its quotient field). + raise DomainError('Mignotte bound not supported over %s' % K) + + D = dup_discriminant(f, K) + l2sq = dup_l2_norm_squared(f, K) + return K(3)*K.abs(D) / ( K(n)**(n+1) * l2sq**(n-1) ) + +def _mobius_from_interval(I, field): + """Convert an open interval to a Mobius transform. """ + s, t = I + + a, c = field.numer(s), field.denom(s) + b, d = field.numer(t), field.denom(t) + + return a, b, c, d + +def _mobius_to_interval(M, field): + """Convert a Mobius transform to an open interval. """ + a, b, c, d = M + + s, t = field(a, c), field(b, d) + + if s <= t: + return (s, t) + else: + return (t, s) + +def dup_step_refine_real_root(f, M, K, fast=False): + """One step of positive real root refinement algorithm. """ + a, b, c, d = M + + if a == b and c == d: + return f, (a, b, c, d) + + A = dup_root_lower_bound(f, K) + + if A is not None: + A = K(int(A)) + else: + A = K.zero + + if fast and A > 16: + f = dup_scale(f, A, K) + a, c, A = A*a, A*c, K.one + + if A >= K.one: + f = dup_shift(f, A, K) + b, d = A*a + b, A*c + d + + if not dup_eval(f, K.zero, K): + return f, (b, b, d, d) + + f, g = dup_shift(f, K.one, K), f + + a1, b1, c1, d1 = a, a + b, c, c + d + + if not dup_eval(f, K.zero, K): + return f, (b1, b1, d1, d1) + + k = dup_sign_variations(f, K) + + if k == 1: + a, b, c, d = a1, b1, c1, d1 + else: + f = dup_shift(dup_reverse(g), K.one, K) + + if not dup_eval(f, K.zero, K): + f = dup_rshift(f, 1, K) + + a, b, c, d = b, a + b, d, c + d + + return f, (a, b, c, d) + +def dup_inner_refine_real_root(f, M, K, eps=None, steps=None, disjoint=None, fast=False, mobius=False): + """Refine a positive root of `f` given a Mobius transform or an interval. """ + F = K.get_field() + + if len(M) == 2: + a, b, c, d = _mobius_from_interval(M, F) + else: + a, b, c, d = M + + while not c: + f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, + d), K, fast=fast) + + if eps is not None and steps is not None: + for i in range(0, steps): + if abs(F(a, c) - F(b, d)) >= eps: + f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) + else: + break + else: + if eps is not None: + while abs(F(a, c) - F(b, d)) >= eps: + f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) + + if steps is not None: + for i in range(0, steps): + f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) + + if disjoint is not None: + while True: + u, v = _mobius_to_interval((a, b, c, d), F) + + if v <= disjoint or disjoint <= u: + break + else: + f, (a, b, c, d) = dup_step_refine_real_root(f, (a, b, c, d), K, fast=fast) + + if not mobius: + return _mobius_to_interval((a, b, c, d), F) + else: + return f, (a, b, c, d) + +def dup_outer_refine_real_root(f, s, t, K, eps=None, steps=None, disjoint=None, fast=False): + """Refine a positive root of `f` given an interval `(s, t)`. """ + a, b, c, d = _mobius_from_interval((s, t), K.get_field()) + + f = dup_transform(f, dup_strip([a, b]), + dup_strip([c, d]), K) + + if dup_sign_variations(f, K) != 1: + raise RefinementFailed("there should be exactly one root in (%s, %s) interval" % (s, t)) + + return dup_inner_refine_real_root(f, (a, b, c, d), K, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + +def dup_refine_real_root(f, s, t, K, eps=None, steps=None, disjoint=None, fast=False): + """Refine real root's approximating interval to the given precision. """ + if K.is_QQ: + (_, f), K = dup_clear_denoms(f, K, convert=True), K.get_ring() + elif not K.is_ZZ: + raise DomainError("real root refinement not supported over %s" % K) + + if s == t: + return (s, t) + + if s > t: + s, t = t, s + + negative = False + + if s < 0: + if t <= 0: + f, s, t, negative = dup_mirror(f, K), -t, -s, True + else: + raise ValueError("Cannot refine a real root in (%s, %s)" % (s, t)) + + if negative and disjoint is not None: + if disjoint < 0: + disjoint = -disjoint + else: + disjoint = None + + s, t = dup_outer_refine_real_root( + f, s, t, K, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + + if negative: + return (-t, -s) + else: + return ( s, t) + +def dup_inner_isolate_real_roots(f, K, eps=None, fast=False): + """Internal function for isolation positive roots up to given precision. + + References + ========== + 1. Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root + Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. + 2. Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the + Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear + Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. + """ + a, b, c, d = K.one, K.zero, K.zero, K.one + + k = dup_sign_variations(f, K) + + if k == 0: + return [] + if k == 1: + roots = [dup_inner_refine_real_root( + f, (a, b, c, d), K, eps=eps, fast=fast, mobius=True)] + else: + roots, stack = [], [(a, b, c, d, f, k)] + + while stack: + a, b, c, d, f, k = stack.pop() + + A = dup_root_lower_bound(f, K) + + if A is not None: + A = K(int(A)) + else: + A = K.zero + + if fast and A > 16: + f = dup_scale(f, A, K) + a, c, A = A*a, A*c, K.one + + if A >= K.one: + f = dup_shift(f, A, K) + b, d = A*a + b, A*c + d + + if not dup_TC(f, K): + roots.append((f, (b, b, d, d))) + f = dup_rshift(f, 1, K) + + k = dup_sign_variations(f, K) + + if k == 0: + continue + if k == 1: + roots.append(dup_inner_refine_real_root( + f, (a, b, c, d), K, eps=eps, fast=fast, mobius=True)) + continue + + f1 = dup_shift(f, K.one, K) + + a1, b1, c1, d1, r = a, a + b, c, c + d, 0 + + if not dup_TC(f1, K): + roots.append((f1, (b1, b1, d1, d1))) + f1, r = dup_rshift(f1, 1, K), 1 + + k1 = dup_sign_variations(f1, K) + k2 = k - k1 - r + + a2, b2, c2, d2 = b, a + b, d, c + d + + if k2 > 1: + f2 = dup_shift(dup_reverse(f), K.one, K) + + if not dup_TC(f2, K): + f2 = dup_rshift(f2, 1, K) + + k2 = dup_sign_variations(f2, K) + else: + f2 = None + + if k1 < k2: + a1, a2, b1, b2 = a2, a1, b2, b1 + c1, c2, d1, d2 = c2, c1, d2, d1 + f1, f2, k1, k2 = f2, f1, k2, k1 + + if not k1: + continue + + if f1 is None: + f1 = dup_shift(dup_reverse(f), K.one, K) + + if not dup_TC(f1, K): + f1 = dup_rshift(f1, 1, K) + + if k1 == 1: + roots.append(dup_inner_refine_real_root( + f1, (a1, b1, c1, d1), K, eps=eps, fast=fast, mobius=True)) + else: + stack.append((a1, b1, c1, d1, f1, k1)) + + if not k2: + continue + + if f2 is None: + f2 = dup_shift(dup_reverse(f), K.one, K) + + if not dup_TC(f2, K): + f2 = dup_rshift(f2, 1, K) + + if k2 == 1: + roots.append(dup_inner_refine_real_root( + f2, (a2, b2, c2, d2), K, eps=eps, fast=fast, mobius=True)) + else: + stack.append((a2, b2, c2, d2, f2, k2)) + + return roots + +def _discard_if_outside_interval(f, M, inf, sup, K, negative, fast, mobius): + """Discard an isolating interval if outside ``(inf, sup)``. """ + F = K.get_field() + + while True: + u, v = _mobius_to_interval(M, F) + + if negative: + u, v = -v, -u + + if (inf is None or u >= inf) and (sup is None or v <= sup): + if not mobius: + return u, v + else: + return f, M + elif (sup is not None and u > sup) or (inf is not None and v < inf): + return None + else: + f, M = dup_step_refine_real_root(f, M, K, fast=fast) + +def dup_inner_isolate_positive_roots(f, K, eps=None, inf=None, sup=None, fast=False, mobius=False): + """Iteratively compute disjoint positive root isolation intervals. """ + if sup is not None and sup < 0: + return [] + + roots = dup_inner_isolate_real_roots(f, K, eps=eps, fast=fast) + + F, results = K.get_field(), [] + + if inf is not None or sup is not None: + for f, M in roots: + result = _discard_if_outside_interval(f, M, inf, sup, K, False, fast, mobius) + + if result is not None: + results.append(result) + elif not mobius: + results.extend(_mobius_to_interval(M, F) for _, M in roots) + else: + results = roots + + return results + +def dup_inner_isolate_negative_roots(f, K, inf=None, sup=None, eps=None, fast=False, mobius=False): + """Iteratively compute disjoint negative root isolation intervals. """ + if inf is not None and inf >= 0: + return [] + + roots = dup_inner_isolate_real_roots(dup_mirror(f, K), K, eps=eps, fast=fast) + + F, results = K.get_field(), [] + + if inf is not None or sup is not None: + for f, M in roots: + result = _discard_if_outside_interval(f, M, inf, sup, K, True, fast, mobius) + + if result is not None: + results.append(result) + elif not mobius: + for f, M in roots: + u, v = _mobius_to_interval(M, F) + results.append((-v, -u)) + else: + results = roots + + return results + +def _isolate_zero(f, K, inf, sup, basis=False, sqf=False): + """Handle special case of CF algorithm when ``f`` is homogeneous. """ + j, f = dup_terms_gcd(f, K) + + if j > 0: + F = K.get_field() + + if (inf is None or inf <= 0) and (sup is None or 0 <= sup): + if not sqf: + if not basis: + return [((F.zero, F.zero), j)], f + else: + return [((F.zero, F.zero), j, [K.one, K.zero])], f + else: + return [(F.zero, F.zero)], f + + return [], f + +def dup_isolate_real_roots_sqf(f, K, eps=None, inf=None, sup=None, fast=False, blackbox=False): + """Isolate real roots of a square-free polynomial using the Vincent-Akritas-Strzebonski (VAS) CF approach. + + References + ========== + .. [1] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative + Study of Two Real Root Isolation Methods. Nonlinear Analysis: + Modelling and Control, Vol. 10, No. 4, 297-304, 2005. + .. [2] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. + Vigklas: Improving the Performance of the Continued Fractions + Method Using New Bounds of Positive Roots. Nonlinear Analysis: + Modelling and Control, Vol. 13, No. 3, 265-279, 2008. + + """ + if K.is_QQ: + (_, f), K = dup_clear_denoms(f, K, convert=True), K.get_ring() + elif not K.is_ZZ: + raise DomainError("isolation of real roots not supported over %s" % K) + + if dup_degree(f) <= 0: + return [] + + I_zero, f = _isolate_zero(f, K, inf, sup, basis=False, sqf=True) + + I_neg = dup_inner_isolate_negative_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) + I_pos = dup_inner_isolate_positive_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) + + roots = sorted(I_neg + I_zero + I_pos) + + if not blackbox: + return roots + else: + return [ RealInterval((a, b), f, K) for (a, b) in roots ] + +def dup_isolate_real_roots(f, K, eps=None, inf=None, sup=None, basis=False, fast=False): + """Isolate real roots using Vincent-Akritas-Strzebonski (VAS) continued fractions approach. + + References + ========== + + .. [1] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative + Study of Two Real Root Isolation Methods. Nonlinear Analysis: + Modelling and Control, Vol. 10, No. 4, 297-304, 2005. + .. [2] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. + Vigklas: Improving the Performance of the Continued Fractions + Method Using New Bounds of Positive Roots. + Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. + + """ + if K.is_QQ: + (_, f), K = dup_clear_denoms(f, K, convert=True), K.get_ring() + elif not K.is_ZZ: + raise DomainError("isolation of real roots not supported over %s" % K) + + if dup_degree(f) <= 0: + return [] + + I_zero, f = _isolate_zero(f, K, inf, sup, basis=basis, sqf=False) + + _, factors = dup_sqf_list(f, K) + + if len(factors) == 1: + ((f, k),) = factors + + I_neg = dup_inner_isolate_negative_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) + I_pos = dup_inner_isolate_positive_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast) + + I_neg = [ ((u, v), k) for u, v in I_neg ] + I_pos = [ ((u, v), k) for u, v in I_pos ] + else: + I_neg, I_pos = _real_isolate_and_disjoin(factors, K, + eps=eps, inf=inf, sup=sup, basis=basis, fast=fast) + + return sorted(I_neg + I_zero + I_pos) + +def dup_isolate_real_roots_list(polys, K, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): + """Isolate real roots of a list of polynomial using Vincent-Akritas-Strzebonski (VAS) CF approach. + + References + ========== + + .. [1] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative + Study of Two Real Root Isolation Methods. Nonlinear Analysis: + Modelling and Control, Vol. 10, No. 4, 297-304, 2005. + .. [2] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. + Vigklas: Improving the Performance of the Continued Fractions + Method Using New Bounds of Positive Roots. + Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. + + """ + if K.is_QQ: + K, F, polys = K.get_ring(), K, polys[:] + + for i, p in enumerate(polys): + polys[i] = dup_clear_denoms(p, F, K, convert=True)[1] + elif not K.is_ZZ: + raise DomainError("isolation of real roots not supported over %s" % K) + + zeros, factors_dict = False, {} + + if (inf is None or inf <= 0) and (sup is None or 0 <= sup): + zeros, zero_indices = True, {} + + for i, p in enumerate(polys): + j, p = dup_terms_gcd(p, K) + + if zeros and j > 0: + zero_indices[i] = j + + for f, k in dup_factor_list(p, K)[1]: + f = tuple(f) + + if f not in factors_dict: + factors_dict[f] = {i: k} + else: + factors_dict[f][i] = k + + factors_list = [(list(f), indices) for f, indices in factors_dict.items()] + I_neg, I_pos = _real_isolate_and_disjoin(factors_list, K, eps=eps, + inf=inf, sup=sup, strict=strict, basis=basis, fast=fast) + + F = K.get_field() + + if not zeros or not zero_indices: + I_zero = [] + else: + if not basis: + I_zero = [((F.zero, F.zero), zero_indices)] + else: + I_zero = [((F.zero, F.zero), zero_indices, [K.one, K.zero])] + + return sorted(I_neg + I_zero + I_pos) + +def _disjoint_p(M, N, strict=False): + """Check if Mobius transforms define disjoint intervals. """ + a1, b1, c1, d1 = M + a2, b2, c2, d2 = N + + a1d1, b1c1 = a1*d1, b1*c1 + a2d2, b2c2 = a2*d2, b2*c2 + + if a1d1 == b1c1 and a2d2 == b2c2: + return True + + if a1d1 > b1c1: + a1, c1, b1, d1 = b1, d1, a1, c1 + + if a2d2 > b2c2: + a2, c2, b2, d2 = b2, d2, a2, c2 + + if not strict: + return a2*d1 >= c2*b1 or b2*c1 <= d2*a1 + else: + return a2*d1 > c2*b1 or b2*c1 < d2*a1 + +def _real_isolate_and_disjoin(factors, K, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): + """Isolate real roots of a list of polynomials and disjoin intervals. """ + I_pos, I_neg = [], [] + + for i, (f, k) in enumerate(factors): + for F, M in dup_inner_isolate_positive_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast, mobius=True): + I_pos.append((F, M, k, f)) + + for G, N in dup_inner_isolate_negative_roots(f, K, eps=eps, inf=inf, sup=sup, fast=fast, mobius=True): + I_neg.append((G, N, k, f)) + + for i, (f, M, k, F) in enumerate(I_pos): + for j, (g, N, m, G) in enumerate(I_pos[i + 1:]): + while not _disjoint_p(M, N, strict=strict): + f, M = dup_inner_refine_real_root(f, M, K, steps=1, fast=fast, mobius=True) + g, N = dup_inner_refine_real_root(g, N, K, steps=1, fast=fast, mobius=True) + + I_pos[i + j + 1] = (g, N, m, G) + + I_pos[i] = (f, M, k, F) + + for i, (f, M, k, F) in enumerate(I_neg): + for j, (g, N, m, G) in enumerate(I_neg[i + 1:]): + while not _disjoint_p(M, N, strict=strict): + f, M = dup_inner_refine_real_root(f, M, K, steps=1, fast=fast, mobius=True) + g, N = dup_inner_refine_real_root(g, N, K, steps=1, fast=fast, mobius=True) + + I_neg[i + j + 1] = (g, N, m, G) + + I_neg[i] = (f, M, k, F) + + if strict: + for i, (f, M, k, F) in enumerate(I_neg): + if not M[0]: + while not M[0]: + f, M = dup_inner_refine_real_root(f, M, K, steps=1, fast=fast, mobius=True) + + I_neg[i] = (f, M, k, F) + break + + for j, (g, N, m, G) in enumerate(I_pos): + if not N[0]: + while not N[0]: + g, N = dup_inner_refine_real_root(g, N, K, steps=1, fast=fast, mobius=True) + + I_pos[j] = (g, N, m, G) + break + + field = K.get_field() + + I_neg = [ (_mobius_to_interval(M, field), k, f) for (_, M, k, f) in I_neg ] + I_pos = [ (_mobius_to_interval(M, field), k, f) for (_, M, k, f) in I_pos ] + + I_neg = [((-v, -u), k, f) for ((u, v), k, f) in I_neg] + + if not basis: + I_neg = [((u, v), k) for ((u, v), k, _) in I_neg] + I_pos = [((u, v), k) for ((u, v), k, _) in I_pos] + + return I_neg, I_pos + +def dup_count_real_roots(f, K, inf=None, sup=None): + """Returns the number of distinct real roots of ``f`` in ``[inf, sup]``. """ + if dup_degree(f) <= 0: + return 0 + + if not K.is_Field: + R, K = K, K.get_field() + f = dup_convert(f, R, K) + + sturm = dup_sturm(f, K) + + if inf is None: + signs_inf = dup_sign_variations([ dup_LC(s, K)*(-1)**dup_degree(s) for s in sturm ], K) + else: + signs_inf = dup_sign_variations([ dup_eval(s, inf, K) for s in sturm ], K) + + if sup is None: + signs_sup = dup_sign_variations([ dup_LC(s, K) for s in sturm ], K) + else: + signs_sup = dup_sign_variations([ dup_eval(s, sup, K) for s in sturm ], K) + + count = abs(signs_inf - signs_sup) + + if inf is not None and not dup_eval(f, inf, K): + count += 1 + + return count + +OO = 'OO' # Origin of (re, im) coordinate system + +Q1 = 'Q1' # Quadrant #1 (++): re > 0 and im > 0 +Q2 = 'Q2' # Quadrant #2 (-+): re < 0 and im > 0 +Q3 = 'Q3' # Quadrant #3 (--): re < 0 and im < 0 +Q4 = 'Q4' # Quadrant #4 (+-): re > 0 and im < 0 + +A1 = 'A1' # Axis #1 (+0): re > 0 and im = 0 +A2 = 'A2' # Axis #2 (0+): re = 0 and im > 0 +A3 = 'A3' # Axis #3 (-0): re < 0 and im = 0 +A4 = 'A4' # Axis #4 (0-): re = 0 and im < 0 + +_rules_simple = { + # Q --> Q (same) => no change + (Q1, Q1): 0, + (Q2, Q2): 0, + (Q3, Q3): 0, + (Q4, Q4): 0, + + # A -- CCW --> Q => +1/4 (CCW) + (A1, Q1): 1, + (A2, Q2): 1, + (A3, Q3): 1, + (A4, Q4): 1, + + # A -- CW --> Q => -1/4 (CCW) + (A1, Q4): 2, + (A2, Q1): 2, + (A3, Q2): 2, + (A4, Q3): 2, + + # Q -- CCW --> A => +1/4 (CCW) + (Q1, A2): 3, + (Q2, A3): 3, + (Q3, A4): 3, + (Q4, A1): 3, + + # Q -- CW --> A => -1/4 (CCW) + (Q1, A1): 4, + (Q2, A2): 4, + (Q3, A3): 4, + (Q4, A4): 4, + + # Q -- CCW --> Q => +1/2 (CCW) + (Q1, Q2): +5, + (Q2, Q3): +5, + (Q3, Q4): +5, + (Q4, Q1): +5, + + # Q -- CW --> Q => -1/2 (CW) + (Q1, Q4): -5, + (Q2, Q1): -5, + (Q3, Q2): -5, + (Q4, Q3): -5, +} + +_rules_ambiguous = { + # A -- CCW --> Q => { +1/4 (CCW), -9/4 (CW) } + (A1, OO, Q1): -1, + (A2, OO, Q2): -1, + (A3, OO, Q3): -1, + (A4, OO, Q4): -1, + + # A -- CW --> Q => { -1/4 (CCW), +7/4 (CW) } + (A1, OO, Q4): -2, + (A2, OO, Q1): -2, + (A3, OO, Q2): -2, + (A4, OO, Q3): -2, + + # Q -- CCW --> A => { +1/4 (CCW), -9/4 (CW) } + (Q1, OO, A2): -3, + (Q2, OO, A3): -3, + (Q3, OO, A4): -3, + (Q4, OO, A1): -3, + + # Q -- CW --> A => { -1/4 (CCW), +7/4 (CW) } + (Q1, OO, A1): -4, + (Q2, OO, A2): -4, + (Q3, OO, A3): -4, + (Q4, OO, A4): -4, + + # A -- OO --> A => { +1 (CCW), -1 (CW) } + (A1, A3): 7, + (A2, A4): 7, + (A3, A1): 7, + (A4, A2): 7, + + (A1, OO, A3): 7, + (A2, OO, A4): 7, + (A3, OO, A1): 7, + (A4, OO, A2): 7, + + # Q -- DIA --> Q => { +1 (CCW), -1 (CW) } + (Q1, Q3): 8, + (Q2, Q4): 8, + (Q3, Q1): 8, + (Q4, Q2): 8, + + (Q1, OO, Q3): 8, + (Q2, OO, Q4): 8, + (Q3, OO, Q1): 8, + (Q4, OO, Q2): 8, + + # A --- R ---> A => { +1/2 (CCW), -3/2 (CW) } + (A1, A2): 9, + (A2, A3): 9, + (A3, A4): 9, + (A4, A1): 9, + + (A1, OO, A2): 9, + (A2, OO, A3): 9, + (A3, OO, A4): 9, + (A4, OO, A1): 9, + + # A --- L ---> A => { +3/2 (CCW), -1/2 (CW) } + (A1, A4): 10, + (A2, A1): 10, + (A3, A2): 10, + (A4, A3): 10, + + (A1, OO, A4): 10, + (A2, OO, A1): 10, + (A3, OO, A2): 10, + (A4, OO, A3): 10, + + # Q --- 1 ---> A => { +3/4 (CCW), -5/4 (CW) } + (Q1, A3): 11, + (Q2, A4): 11, + (Q3, A1): 11, + (Q4, A2): 11, + + (Q1, OO, A3): 11, + (Q2, OO, A4): 11, + (Q3, OO, A1): 11, + (Q4, OO, A2): 11, + + # Q --- 2 ---> A => { +5/4 (CCW), -3/4 (CW) } + (Q1, A4): 12, + (Q2, A1): 12, + (Q3, A2): 12, + (Q4, A3): 12, + + (Q1, OO, A4): 12, + (Q2, OO, A1): 12, + (Q3, OO, A2): 12, + (Q4, OO, A3): 12, + + # A --- 1 ---> Q => { +5/4 (CCW), -3/4 (CW) } + (A1, Q3): 13, + (A2, Q4): 13, + (A3, Q1): 13, + (A4, Q2): 13, + + (A1, OO, Q3): 13, + (A2, OO, Q4): 13, + (A3, OO, Q1): 13, + (A4, OO, Q2): 13, + + # A --- 2 ---> Q => { +3/4 (CCW), -5/4 (CW) } + (A1, Q2): 14, + (A2, Q3): 14, + (A3, Q4): 14, + (A4, Q1): 14, + + (A1, OO, Q2): 14, + (A2, OO, Q3): 14, + (A3, OO, Q4): 14, + (A4, OO, Q1): 14, + + # Q --> OO --> Q => { +1/2 (CCW), -3/2 (CW) } + (Q1, OO, Q2): 15, + (Q2, OO, Q3): 15, + (Q3, OO, Q4): 15, + (Q4, OO, Q1): 15, + + # Q --> OO --> Q => { +3/2 (CCW), -1/2 (CW) } + (Q1, OO, Q4): 16, + (Q2, OO, Q1): 16, + (Q3, OO, Q2): 16, + (Q4, OO, Q3): 16, + + # A --> OO --> A => { +2 (CCW), 0 (CW) } + (A1, OO, A1): 17, + (A2, OO, A2): 17, + (A3, OO, A3): 17, + (A4, OO, A4): 17, + + # Q --> OO --> Q => { +2 (CCW), 0 (CW) } + (Q1, OO, Q1): 18, + (Q2, OO, Q2): 18, + (Q3, OO, Q3): 18, + (Q4, OO, Q4): 18, +} + +_values = { + 0: [( 0, 1)], + 1: [(+1, 4)], + 2: [(-1, 4)], + 3: [(+1, 4)], + 4: [(-1, 4)], + -1: [(+9, 4), (+1, 4)], + -2: [(+7, 4), (-1, 4)], + -3: [(+9, 4), (+1, 4)], + -4: [(+7, 4), (-1, 4)], + +5: [(+1, 2)], + -5: [(-1, 2)], + 7: [(+1, 1), (-1, 1)], + 8: [(+1, 1), (-1, 1)], + 9: [(+1, 2), (-3, 2)], + 10: [(+3, 2), (-1, 2)], + 11: [(+3, 4), (-5, 4)], + 12: [(+5, 4), (-3, 4)], + 13: [(+5, 4), (-3, 4)], + 14: [(+3, 4), (-5, 4)], + 15: [(+1, 2), (-3, 2)], + 16: [(+3, 2), (-1, 2)], + 17: [(+2, 1), ( 0, 1)], + 18: [(+2, 1), ( 0, 1)], +} + +def _classify_point(re, im): + """Return the half-axis (or origin) on which (re, im) point is located. """ + if not re and not im: + return OO + + if not re: + if im > 0: + return A2 + else: + return A4 + elif not im: + if re > 0: + return A1 + else: + return A3 + +def _intervals_to_quadrants(intervals, f1, f2, s, t, F): + """Generate a sequence of extended quadrants from a list of critical points. """ + if not intervals: + return [] + + Q = [] + + if not f1: + (a, b), _, _ = intervals[0] + + if a == b == s: + if len(intervals) == 1: + if dup_eval(f2, t, F) > 0: + return [OO, A2] + else: + return [OO, A4] + else: + (a, _), _, _ = intervals[1] + + if dup_eval(f2, (s + a)/2, F) > 0: + Q.extend([OO, A2]) + f2_sgn = +1 + else: + Q.extend([OO, A4]) + f2_sgn = -1 + + intervals = intervals[1:] + else: + if dup_eval(f2, s, F) > 0: + Q.append(A2) + f2_sgn = +1 + else: + Q.append(A4) + f2_sgn = -1 + + for (a, _), indices, _ in intervals: + Q.append(OO) + + if indices[1] % 2 == 1: + f2_sgn = -f2_sgn + + if a != t: + if f2_sgn > 0: + Q.append(A2) + else: + Q.append(A4) + + return Q + + if not f2: + (a, b), _, _ = intervals[0] + + if a == b == s: + if len(intervals) == 1: + if dup_eval(f1, t, F) > 0: + return [OO, A1] + else: + return [OO, A3] + else: + (a, _), _, _ = intervals[1] + + if dup_eval(f1, (s + a)/2, F) > 0: + Q.extend([OO, A1]) + f1_sgn = +1 + else: + Q.extend([OO, A3]) + f1_sgn = -1 + + intervals = intervals[1:] + else: + if dup_eval(f1, s, F) > 0: + Q.append(A1) + f1_sgn = +1 + else: + Q.append(A3) + f1_sgn = -1 + + for (a, _), indices, _ in intervals: + Q.append(OO) + + if indices[0] % 2 == 1: + f1_sgn = -f1_sgn + + if a != t: + if f1_sgn > 0: + Q.append(A1) + else: + Q.append(A3) + + return Q + + re = dup_eval(f1, s, F) + im = dup_eval(f2, s, F) + + if not re or not im: + Q.append(_classify_point(re, im)) + + if len(intervals) == 1: + re = dup_eval(f1, t, F) + im = dup_eval(f2, t, F) + else: + (a, _), _, _ = intervals[1] + + re = dup_eval(f1, (s + a)/2, F) + im = dup_eval(f2, (s + a)/2, F) + + intervals = intervals[1:] + + if re > 0: + f1_sgn = +1 + else: + f1_sgn = -1 + + if im > 0: + f2_sgn = +1 + else: + f2_sgn = -1 + + sgn = { + (+1, +1): Q1, + (-1, +1): Q2, + (-1, -1): Q3, + (+1, -1): Q4, + } + + Q.append(sgn[(f1_sgn, f2_sgn)]) + + for (a, b), indices, _ in intervals: + if a == b: + re = dup_eval(f1, a, F) + im = dup_eval(f2, a, F) + + cls = _classify_point(re, im) + + if cls is not None: + Q.append(cls) + + if 0 in indices: + if indices[0] % 2 == 1: + f1_sgn = -f1_sgn + + if 1 in indices: + if indices[1] % 2 == 1: + f2_sgn = -f2_sgn + + if not (a == b and b == t): + Q.append(sgn[(f1_sgn, f2_sgn)]) + + return Q + +def _traverse_quadrants(Q_L1, Q_L2, Q_L3, Q_L4, exclude=None): + """Transform sequences of quadrants to a sequence of rules. """ + if exclude is True: + edges = [1, 1, 0, 0] + + corners = { + (0, 1): 1, + (1, 2): 1, + (2, 3): 0, + (3, 0): 1, + } + else: + edges = [0, 0, 0, 0] + + corners = { + (0, 1): 0, + (1, 2): 0, + (2, 3): 0, + (3, 0): 0, + } + + if exclude is not None and exclude is not True: + exclude = set(exclude) + + for i, edge in enumerate(['S', 'E', 'N', 'W']): + if edge in exclude: + edges[i] = 1 + + for i, corner in enumerate(['SW', 'SE', 'NE', 'NW']): + if corner in exclude: + corners[((i - 1) % 4, i)] = 1 + + QQ, rules = [Q_L1, Q_L2, Q_L3, Q_L4], [] + + for i, Q in enumerate(QQ): + if not Q: + continue + + if Q[-1] == OO: + Q = Q[:-1] + + if Q[0] == OO: + j, Q = (i - 1) % 4, Q[1:] + qq = (QQ[j][-2], OO, Q[0]) + + if qq in _rules_ambiguous: + rules.append((_rules_ambiguous[qq], corners[(j, i)])) + else: + raise NotImplementedError("3 element rule (corner): " + str(qq)) + + q1, k = Q[0], 1 + + while k < len(Q): + q2, k = Q[k], k + 1 + + if q2 != OO: + qq = (q1, q2) + + if qq in _rules_simple: + rules.append((_rules_simple[qq], 0)) + elif qq in _rules_ambiguous: + rules.append((_rules_ambiguous[qq], edges[i])) + else: + raise NotImplementedError("2 element rule (inside): " + str(qq)) + else: + qq, k = (q1, q2, Q[k]), k + 1 + + if qq in _rules_ambiguous: + rules.append((_rules_ambiguous[qq], edges[i])) + else: + raise NotImplementedError("3 element rule (edge): " + str(qq)) + + q1 = qq[-1] + + return rules + +def _reverse_intervals(intervals): + """Reverse intervals for traversal from right to left and from top to bottom. """ + return [ ((b, a), indices, f) for (a, b), indices, f in reversed(intervals) ] + +def _winding_number(T, field): + """Compute the winding number of the input polynomial, i.e. the number of roots. """ + return int(sum(field(*_values[t][i]) for t, i in T) / field(2)) + +def dup_count_complex_roots(f, K, inf=None, sup=None, exclude=None): + """Count all roots in [u + v*I, s + t*I] rectangle using Collins-Krandick algorithm. """ + if not K.is_ZZ and not K.is_QQ: + raise DomainError("complex root counting is not supported over %s" % K) + + if K.is_ZZ: + R, F = K, K.get_field() + else: + R, F = K.get_ring(), K + + f = dup_convert(f, K, F) + + if inf is None or sup is None: + _, lc = dup_degree(f), abs(dup_LC(f, F)) + B = 2*max(F.quo(abs(c), lc) for c in f) + + if inf is None: + (u, v) = (-B, -B) + else: + (u, v) = inf + + if sup is None: + (s, t) = (+B, +B) + else: + (s, t) = sup + + f1, f2 = dup_real_imag(f, F) + + f1L1F = dmp_eval_in(f1, v, 1, 1, F) + f2L1F = dmp_eval_in(f2, v, 1, 1, F) + + _, f1L1R = dup_clear_denoms(f1L1F, F, R, convert=True) + _, f2L1R = dup_clear_denoms(f2L1F, F, R, convert=True) + + f1L2F = dmp_eval_in(f1, s, 0, 1, F) + f2L2F = dmp_eval_in(f2, s, 0, 1, F) + + _, f1L2R = dup_clear_denoms(f1L2F, F, R, convert=True) + _, f2L2R = dup_clear_denoms(f2L2F, F, R, convert=True) + + f1L3F = dmp_eval_in(f1, t, 1, 1, F) + f2L3F = dmp_eval_in(f2, t, 1, 1, F) + + _, f1L3R = dup_clear_denoms(f1L3F, F, R, convert=True) + _, f2L3R = dup_clear_denoms(f2L3F, F, R, convert=True) + + f1L4F = dmp_eval_in(f1, u, 0, 1, F) + f2L4F = dmp_eval_in(f2, u, 0, 1, F) + + _, f1L4R = dup_clear_denoms(f1L4F, F, R, convert=True) + _, f2L4R = dup_clear_denoms(f2L4F, F, R, convert=True) + + S_L1 = [f1L1R, f2L1R] + S_L2 = [f1L2R, f2L2R] + S_L3 = [f1L3R, f2L3R] + S_L4 = [f1L4R, f2L4R] + + I_L1 = dup_isolate_real_roots_list(S_L1, R, inf=u, sup=s, fast=True, basis=True, strict=True) + I_L2 = dup_isolate_real_roots_list(S_L2, R, inf=v, sup=t, fast=True, basis=True, strict=True) + I_L3 = dup_isolate_real_roots_list(S_L3, R, inf=u, sup=s, fast=True, basis=True, strict=True) + I_L4 = dup_isolate_real_roots_list(S_L4, R, inf=v, sup=t, fast=True, basis=True, strict=True) + + I_L3 = _reverse_intervals(I_L3) + I_L4 = _reverse_intervals(I_L4) + + Q_L1 = _intervals_to_quadrants(I_L1, f1L1F, f2L1F, u, s, F) + Q_L2 = _intervals_to_quadrants(I_L2, f1L2F, f2L2F, v, t, F) + Q_L3 = _intervals_to_quadrants(I_L3, f1L3F, f2L3F, s, u, F) + Q_L4 = _intervals_to_quadrants(I_L4, f1L4F, f2L4F, t, v, F) + + T = _traverse_quadrants(Q_L1, Q_L2, Q_L3, Q_L4, exclude=exclude) + + return _winding_number(T, F) + +def _vertical_bisection(N, a, b, I, Q, F1, F2, f1, f2, F): + """Vertical bisection step in Collins-Krandick root isolation algorithm. """ + (u, v), (s, t) = a, b + + I_L1, I_L2, I_L3, I_L4 = I + Q_L1, Q_L2, Q_L3, Q_L4 = Q + + f1L1F, f1L2F, f1L3F, f1L4F = F1 + f2L1F, f2L2F, f2L3F, f2L4F = F2 + + x = (u + s) / 2 + + f1V = dmp_eval_in(f1, x, 0, 1, F) + f2V = dmp_eval_in(f2, x, 0, 1, F) + + I_V = dup_isolate_real_roots_list([f1V, f2V], F, inf=v, sup=t, fast=True, strict=True, basis=True) + + I_L1_L, I_L1_R = [], [] + I_L2_L, I_L2_R = I_V, I_L2 + I_L3_L, I_L3_R = [], [] + I_L4_L, I_L4_R = I_L4, _reverse_intervals(I_V) + + for I in I_L1: + (a, b), indices, h = I + + if a == b: + if a == x: + I_L1_L.append(I) + I_L1_R.append(I) + elif a < x: + I_L1_L.append(I) + else: + I_L1_R.append(I) + else: + if b <= x: + I_L1_L.append(I) + elif a >= x: + I_L1_R.append(I) + else: + a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=x, fast=True) + + if b <= x: + I_L1_L.append(((a, b), indices, h)) + if a >= x: + I_L1_R.append(((a, b), indices, h)) + + for I in I_L3: + (b, a), indices, h = I + + if a == b: + if a == x: + I_L3_L.append(I) + I_L3_R.append(I) + elif a < x: + I_L3_L.append(I) + else: + I_L3_R.append(I) + else: + if b <= x: + I_L3_L.append(I) + elif a >= x: + I_L3_R.append(I) + else: + a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=x, fast=True) + + if b <= x: + I_L3_L.append(((b, a), indices, h)) + if a >= x: + I_L3_R.append(((b, a), indices, h)) + + Q_L1_L = _intervals_to_quadrants(I_L1_L, f1L1F, f2L1F, u, x, F) + Q_L2_L = _intervals_to_quadrants(I_L2_L, f1V, f2V, v, t, F) + Q_L3_L = _intervals_to_quadrants(I_L3_L, f1L3F, f2L3F, x, u, F) + Q_L4_L = Q_L4 + + Q_L1_R = _intervals_to_quadrants(I_L1_R, f1L1F, f2L1F, x, s, F) + Q_L2_R = Q_L2 + Q_L3_R = _intervals_to_quadrants(I_L3_R, f1L3F, f2L3F, s, x, F) + Q_L4_R = _intervals_to_quadrants(I_L4_R, f1V, f2V, t, v, F) + + T_L = _traverse_quadrants(Q_L1_L, Q_L2_L, Q_L3_L, Q_L4_L, exclude=True) + T_R = _traverse_quadrants(Q_L1_R, Q_L2_R, Q_L3_R, Q_L4_R, exclude=True) + + N_L = _winding_number(T_L, F) + N_R = _winding_number(T_R, F) + + I_L = (I_L1_L, I_L2_L, I_L3_L, I_L4_L) + Q_L = (Q_L1_L, Q_L2_L, Q_L3_L, Q_L4_L) + + I_R = (I_L1_R, I_L2_R, I_L3_R, I_L4_R) + Q_R = (Q_L1_R, Q_L2_R, Q_L3_R, Q_L4_R) + + F1_L = (f1L1F, f1V, f1L3F, f1L4F) + F2_L = (f2L1F, f2V, f2L3F, f2L4F) + + F1_R = (f1L1F, f1L2F, f1L3F, f1V) + F2_R = (f2L1F, f2L2F, f2L3F, f2V) + + a, b = (u, v), (x, t) + c, d = (x, v), (s, t) + + D_L = (N_L, a, b, I_L, Q_L, F1_L, F2_L) + D_R = (N_R, c, d, I_R, Q_R, F1_R, F2_R) + + return D_L, D_R + +def _horizontal_bisection(N, a, b, I, Q, F1, F2, f1, f2, F): + """Horizontal bisection step in Collins-Krandick root isolation algorithm. """ + (u, v), (s, t) = a, b + + I_L1, I_L2, I_L3, I_L4 = I + Q_L1, Q_L2, Q_L3, Q_L4 = Q + + f1L1F, f1L2F, f1L3F, f1L4F = F1 + f2L1F, f2L2F, f2L3F, f2L4F = F2 + + y = (v + t) / 2 + + f1H = dmp_eval_in(f1, y, 1, 1, F) + f2H = dmp_eval_in(f2, y, 1, 1, F) + + I_H = dup_isolate_real_roots_list([f1H, f2H], F, inf=u, sup=s, fast=True, strict=True, basis=True) + + I_L1_B, I_L1_U = I_L1, I_H + I_L2_B, I_L2_U = [], [] + I_L3_B, I_L3_U = _reverse_intervals(I_H), I_L3 + I_L4_B, I_L4_U = [], [] + + for I in I_L2: + (a, b), indices, h = I + + if a == b: + if a == y: + I_L2_B.append(I) + I_L2_U.append(I) + elif a < y: + I_L2_B.append(I) + else: + I_L2_U.append(I) + else: + if b <= y: + I_L2_B.append(I) + elif a >= y: + I_L2_U.append(I) + else: + a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=y, fast=True) + + if b <= y: + I_L2_B.append(((a, b), indices, h)) + if a >= y: + I_L2_U.append(((a, b), indices, h)) + + for I in I_L4: + (b, a), indices, h = I + + if a == b: + if a == y: + I_L4_B.append(I) + I_L4_U.append(I) + elif a < y: + I_L4_B.append(I) + else: + I_L4_U.append(I) + else: + if b <= y: + I_L4_B.append(I) + elif a >= y: + I_L4_U.append(I) + else: + a, b = dup_refine_real_root(h, a, b, F.get_ring(), disjoint=y, fast=True) + + if b <= y: + I_L4_B.append(((b, a), indices, h)) + if a >= y: + I_L4_U.append(((b, a), indices, h)) + + Q_L1_B = Q_L1 + Q_L2_B = _intervals_to_quadrants(I_L2_B, f1L2F, f2L2F, v, y, F) + Q_L3_B = _intervals_to_quadrants(I_L3_B, f1H, f2H, s, u, F) + Q_L4_B = _intervals_to_quadrants(I_L4_B, f1L4F, f2L4F, y, v, F) + + Q_L1_U = _intervals_to_quadrants(I_L1_U, f1H, f2H, u, s, F) + Q_L2_U = _intervals_to_quadrants(I_L2_U, f1L2F, f2L2F, y, t, F) + Q_L3_U = Q_L3 + Q_L4_U = _intervals_to_quadrants(I_L4_U, f1L4F, f2L4F, t, y, F) + + T_B = _traverse_quadrants(Q_L1_B, Q_L2_B, Q_L3_B, Q_L4_B, exclude=True) + T_U = _traverse_quadrants(Q_L1_U, Q_L2_U, Q_L3_U, Q_L4_U, exclude=True) + + N_B = _winding_number(T_B, F) + N_U = _winding_number(T_U, F) + + I_B = (I_L1_B, I_L2_B, I_L3_B, I_L4_B) + Q_B = (Q_L1_B, Q_L2_B, Q_L3_B, Q_L4_B) + + I_U = (I_L1_U, I_L2_U, I_L3_U, I_L4_U) + Q_U = (Q_L1_U, Q_L2_U, Q_L3_U, Q_L4_U) + + F1_B = (f1L1F, f1L2F, f1H, f1L4F) + F2_B = (f2L1F, f2L2F, f2H, f2L4F) + + F1_U = (f1H, f1L2F, f1L3F, f1L4F) + F2_U = (f2H, f2L2F, f2L3F, f2L4F) + + a, b = (u, v), (s, y) + c, d = (u, y), (s, t) + + D_B = (N_B, a, b, I_B, Q_B, F1_B, F2_B) + D_U = (N_U, c, d, I_U, Q_U, F1_U, F2_U) + + return D_B, D_U + +def _depth_first_select(rectangles): + """Find a rectangle of minimum area for bisection. """ + min_area, j = None, None + + for i, (_, (u, v), (s, t), _, _, _, _) in enumerate(rectangles): + area = (s - u)*(t - v) + + if min_area is None or area < min_area: + min_area, j = area, i + + return rectangles.pop(j) + +def _rectangle_small_p(a, b, eps): + """Return ``True`` if the given rectangle is small enough. """ + (u, v), (s, t) = a, b + + if eps is not None: + return s - u < eps and t - v < eps + else: + return True + +def dup_isolate_complex_roots_sqf(f, K, eps=None, inf=None, sup=None, blackbox=False): + """Isolate complex roots of a square-free polynomial using Collins-Krandick algorithm. """ + if not K.is_ZZ and not K.is_QQ: + raise DomainError("isolation of complex roots is not supported over %s" % K) + + if dup_degree(f) <= 0: + return [] + + if K.is_ZZ: + F = K.get_field() + else: + F = K + + f = dup_convert(f, K, F) + + lc = abs(dup_LC(f, F)) + B = 2*max(F.quo(abs(c), lc) for c in f) + + (u, v), (s, t) = (-B, F.zero), (B, B) + + if inf is not None: + u = inf + + if sup is not None: + s = sup + + if v < 0 or t <= v or s <= u: + raise ValueError("not a valid complex isolation rectangle") + + f1, f2 = dup_real_imag(f, F) + + f1L1 = dmp_eval_in(f1, v, 1, 1, F) + f2L1 = dmp_eval_in(f2, v, 1, 1, F) + + f1L2 = dmp_eval_in(f1, s, 0, 1, F) + f2L2 = dmp_eval_in(f2, s, 0, 1, F) + + f1L3 = dmp_eval_in(f1, t, 1, 1, F) + f2L3 = dmp_eval_in(f2, t, 1, 1, F) + + f1L4 = dmp_eval_in(f1, u, 0, 1, F) + f2L4 = dmp_eval_in(f2, u, 0, 1, F) + + S_L1 = [f1L1, f2L1] + S_L2 = [f1L2, f2L2] + S_L3 = [f1L3, f2L3] + S_L4 = [f1L4, f2L4] + + I_L1 = dup_isolate_real_roots_list(S_L1, F, inf=u, sup=s, fast=True, strict=True, basis=True) + I_L2 = dup_isolate_real_roots_list(S_L2, F, inf=v, sup=t, fast=True, strict=True, basis=True) + I_L3 = dup_isolate_real_roots_list(S_L3, F, inf=u, sup=s, fast=True, strict=True, basis=True) + I_L4 = dup_isolate_real_roots_list(S_L4, F, inf=v, sup=t, fast=True, strict=True, basis=True) + + I_L3 = _reverse_intervals(I_L3) + I_L4 = _reverse_intervals(I_L4) + + Q_L1 = _intervals_to_quadrants(I_L1, f1L1, f2L1, u, s, F) + Q_L2 = _intervals_to_quadrants(I_L2, f1L2, f2L2, v, t, F) + Q_L3 = _intervals_to_quadrants(I_L3, f1L3, f2L3, s, u, F) + Q_L4 = _intervals_to_quadrants(I_L4, f1L4, f2L4, t, v, F) + + T = _traverse_quadrants(Q_L1, Q_L2, Q_L3, Q_L4) + N = _winding_number(T, F) + + if not N: + return [] + + I = (I_L1, I_L2, I_L3, I_L4) + Q = (Q_L1, Q_L2, Q_L3, Q_L4) + + F1 = (f1L1, f1L2, f1L3, f1L4) + F2 = (f2L1, f2L2, f2L3, f2L4) + + rectangles, roots = [(N, (u, v), (s, t), I, Q, F1, F2)], [] + + while rectangles: + N, (u, v), (s, t), I, Q, F1, F2 = _depth_first_select(rectangles) + + if s - u > t - v: + D_L, D_R = _vertical_bisection(N, (u, v), (s, t), I, Q, F1, F2, f1, f2, F) + + N_L, a, b, I_L, Q_L, F1_L, F2_L = D_L + N_R, c, d, I_R, Q_R, F1_R, F2_R = D_R + + if N_L >= 1: + if N_L == 1 and _rectangle_small_p(a, b, eps): + roots.append(ComplexInterval(a, b, I_L, Q_L, F1_L, F2_L, f1, f2, F)) + else: + rectangles.append(D_L) + + if N_R >= 1: + if N_R == 1 and _rectangle_small_p(c, d, eps): + roots.append(ComplexInterval(c, d, I_R, Q_R, F1_R, F2_R, f1, f2, F)) + else: + rectangles.append(D_R) + else: + D_B, D_U = _horizontal_bisection(N, (u, v), (s, t), I, Q, F1, F2, f1, f2, F) + + N_B, a, b, I_B, Q_B, F1_B, F2_B = D_B + N_U, c, d, I_U, Q_U, F1_U, F2_U = D_U + + if N_B >= 1: + if N_B == 1 and _rectangle_small_p(a, b, eps): + roots.append(ComplexInterval( + a, b, I_B, Q_B, F1_B, F2_B, f1, f2, F)) + else: + rectangles.append(D_B) + + if N_U >= 1: + if N_U == 1 and _rectangle_small_p(c, d, eps): + roots.append(ComplexInterval( + c, d, I_U, Q_U, F1_U, F2_U, f1, f2, F)) + else: + rectangles.append(D_U) + + _roots, roots = sorted(roots, key=lambda r: (r.ax, r.ay)), [] + + for root in _roots: + roots.extend([root.conjugate(), root]) + + if blackbox: + return roots + else: + return [ r.as_tuple() for r in roots ] + +def dup_isolate_all_roots_sqf(f, K, eps=None, inf=None, sup=None, fast=False, blackbox=False): + """Isolate real and complex roots of a square-free polynomial ``f``. """ + return ( + dup_isolate_real_roots_sqf( f, K, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox), + dup_isolate_complex_roots_sqf(f, K, eps=eps, inf=inf, sup=sup, blackbox=blackbox)) + +def dup_isolate_all_roots(f, K, eps=None, inf=None, sup=None, fast=False): + """Isolate real and complex roots of a non-square-free polynomial ``f``. """ + if not K.is_ZZ and not K.is_QQ: + raise DomainError("isolation of real and complex roots is not supported over %s" % K) + + _, factors = dup_sqf_list(f, K) + + if len(factors) == 1: + ((f, k),) = factors + + real_part, complex_part = dup_isolate_all_roots_sqf( + f, K, eps=eps, inf=inf, sup=sup, fast=fast) + + real_part = [ ((a, b), k) for (a, b) in real_part ] + complex_part = [ ((a, b), k) for (a, b) in complex_part ] + + return real_part, complex_part + else: + raise NotImplementedError( "only trivial square-free polynomials are supported") + +class RealInterval: + """A fully qualified representation of a real isolation interval. """ + + def __init__(self, data, f, dom): + """Initialize new real interval with complete information. """ + if len(data) == 2: + s, t = data + + self.neg = False + + if s < 0: + if t <= 0: + f, s, t, self.neg = dup_mirror(f, dom), -t, -s, True + else: + raise ValueError("Cannot refine a real root in (%s, %s)" % (s, t)) + + a, b, c, d = _mobius_from_interval((s, t), dom.get_field()) + + f = dup_transform(f, dup_strip([a, b]), + dup_strip([c, d]), dom) + + self.mobius = a, b, c, d + else: + self.mobius = data[:-1] + self.neg = data[-1] + + self.f, self.dom = f, dom + + @property + def func(self): + return RealInterval + + @property + def args(self): + i = self + return (i.mobius + (i.neg,), i.f, i.dom) + + def __eq__(self, other): + if type(other) is not type(self): + return False + return self.args == other.args + + @property + def a(self): + """Return the position of the left end. """ + field = self.dom.get_field() + a, b, c, d = self.mobius + + if not self.neg: + if a*d < b*c: + return field(a, c) + return field(b, d) + else: + if a*d > b*c: + return -field(a, c) + return -field(b, d) + + @property + def b(self): + """Return the position of the right end. """ + was = self.neg + self.neg = not was + rv = -self.a + self.neg = was + return rv + + @property + def dx(self): + """Return width of the real isolating interval. """ + return self.b - self.a + + @property + def center(self): + """Return the center of the real isolating interval. """ + return (self.a + self.b)/2 + + @property + def max_denom(self): + """Return the largest denominator occurring in either endpoint. """ + return max(self.a.denominator, self.b.denominator) + + def as_tuple(self): + """Return tuple representation of real isolating interval. """ + return (self.a, self.b) + + def __repr__(self): + return "(%s, %s)" % (self.a, self.b) + + def __contains__(self, item): + """ + Say whether a complex number belongs to this real interval. + + Parameters + ========== + + item : pair (re, im) or number re + Either a pair giving the real and imaginary parts of the number, + or else a real number. + + """ + if isinstance(item, tuple): + re, im = item + else: + re, im = item, 0 + return im == 0 and self.a <= re <= self.b + + def is_disjoint(self, other): + """Return ``True`` if two isolation intervals are disjoint. """ + if isinstance(other, RealInterval): + return (self.b < other.a or other.b < self.a) + assert isinstance(other, ComplexInterval) + return (self.b < other.ax or other.bx < self.a + or other.ay*other.by > 0) + + def _inner_refine(self): + """Internal one step real root refinement procedure. """ + if self.mobius is None: + return self + + f, mobius = dup_inner_refine_real_root( + self.f, self.mobius, self.dom, steps=1, mobius=True) + + return RealInterval(mobius + (self.neg,), f, self.dom) + + def refine_disjoint(self, other): + """Refine an isolating interval until it is disjoint with another one. """ + expr = self + while not expr.is_disjoint(other): + expr, other = expr._inner_refine(), other._inner_refine() + + return expr, other + + def refine_size(self, dx): + """Refine an isolating interval until it is of sufficiently small size. """ + expr = self + while not (expr.dx < dx): + expr = expr._inner_refine() + + return expr + + def refine_step(self, steps=1): + """Perform several steps of real root refinement algorithm. """ + expr = self + for _ in range(steps): + expr = expr._inner_refine() + + return expr + + def refine(self): + """Perform one step of real root refinement algorithm. """ + return self._inner_refine() + + +class ComplexInterval: + """A fully qualified representation of a complex isolation interval. + The printed form is shown as (ax, bx) x (ay, by) where (ax, ay) + and (bx, by) are the coordinates of the southwest and northeast + corners of the interval's rectangle, respectively. + + Examples + ======== + + >>> from sympy import CRootOf, S + >>> from sympy.abc import x + >>> CRootOf.clear_cache() # for doctest reproducibility + >>> root = CRootOf(x**10 - 2*x + 3, 9) + >>> i = root._get_interval(); i + (3/64, 3/32) x (9/8, 75/64) + + The real part of the root lies within the range [0, 3/4] while + the imaginary part lies within the range [9/8, 3/2]: + + >>> root.n(3) + 0.0766 + 1.14*I + + The width of the ranges in the x and y directions on the complex + plane are: + + >>> i.dx, i.dy + (3/64, 3/64) + + The center of the range is + + >>> i.center + (9/128, 147/128) + + The northeast coordinate of the rectangle bounding the root in the + complex plane is given by attribute b and the x and y components + are accessed by bx and by: + + >>> i.b, i.bx, i.by + ((3/32, 75/64), 3/32, 75/64) + + The southwest coordinate is similarly given by i.a + + >>> i.a, i.ax, i.ay + ((3/64, 9/8), 3/64, 9/8) + + Although the interval prints to show only the real and imaginary + range of the root, all the information of the underlying root + is contained as properties of the interval. + + For example, an interval with a nonpositive imaginary range is + considered to be the conjugate. Since the y values of y are in the + range [0, 1/4] it is not the conjugate: + + >>> i.conj + False + + The conjugate's interval is + + >>> ic = i.conjugate(); ic + (3/64, 3/32) x (-75/64, -9/8) + + NOTE: the values printed still represent the x and y range + in which the root -- conjugate, in this case -- is located, + but the underlying a and b values of a root and its conjugate + are the same: + + >>> assert i.a == ic.a and i.b == ic.b + + What changes are the reported coordinates of the bounding rectangle: + + >>> (i.ax, i.ay), (i.bx, i.by) + ((3/64, 9/8), (3/32, 75/64)) + >>> (ic.ax, ic.ay), (ic.bx, ic.by) + ((3/64, -75/64), (3/32, -9/8)) + + The interval can be refined once: + + >>> i # for reference, this is the current interval + (3/64, 3/32) x (9/8, 75/64) + + >>> i.refine() + (3/64, 3/32) x (9/8, 147/128) + + Several refinement steps can be taken: + + >>> i.refine_step(2) # 2 steps + (9/128, 3/32) x (9/8, 147/128) + + It is also possible to refine to a given tolerance: + + >>> tol = min(i.dx, i.dy)/2 + >>> i.refine_size(tol) + (9/128, 21/256) x (9/8, 291/256) + + A disjoint interval is one whose bounding rectangle does not + overlap with another. An interval, necessarily, is not disjoint with + itself, but any interval is disjoint with a conjugate since the + conjugate rectangle will always be in the lower half of the complex + plane and the non-conjugate in the upper half: + + >>> i.is_disjoint(i), i.is_disjoint(i.conjugate()) + (False, True) + + The following interval j is not disjoint from i: + + >>> close = CRootOf(x**10 - 2*x + 300/S(101), 9) + >>> j = close._get_interval(); j + (75/1616, 75/808) x (225/202, 1875/1616) + >>> i.is_disjoint(j) + False + + The two can be made disjoint, however: + + >>> newi, newj = i.refine_disjoint(j) + >>> newi + (39/512, 159/2048) x (2325/2048, 4653/4096) + >>> newj + (3975/51712, 2025/25856) x (29325/25856, 117375/103424) + + Even though the real ranges overlap, the imaginary do not, so + the roots have been resolved as distinct. Intervals are disjoint + when either the real or imaginary component of the intervals is + distinct. In the case above, the real components have not been + resolved (so we do not know, yet, which root has the smaller real + part) but the imaginary part of ``close`` is larger than ``root``: + + >>> close.n(3) + 0.0771 + 1.13*I + >>> root.n(3) + 0.0766 + 1.14*I + """ + + def __init__(self, a, b, I, Q, F1, F2, f1, f2, dom, conj=False): + """Initialize new complex interval with complete information. """ + # a and b are the SW and NE corner of the bounding interval, + # (ax, ay) and (bx, by), respectively, for the NON-CONJUGATE + # root (the one with the positive imaginary part); when working + # with the conjugate, the a and b value are still non-negative + # but the ay, by are reversed and have oppositite sign + self.a, self.b = a, b + self.I, self.Q = I, Q + + self.f1, self.F1 = f1, F1 + self.f2, self.F2 = f2, F2 + + self.dom = dom + self.conj = conj + + @property + def func(self): + return ComplexInterval + + @property + def args(self): + i = self + return (i.a, i.b, i.I, i.Q, i.F1, i.F2, i.f1, i.f2, i.dom, i.conj) + + def __eq__(self, other): + if type(other) is not type(self): + return False + return self.args == other.args + + @property + def ax(self): + """Return ``x`` coordinate of south-western corner. """ + return self.a[0] + + @property + def ay(self): + """Return ``y`` coordinate of south-western corner. """ + if not self.conj: + return self.a[1] + else: + return -self.b[1] + + @property + def bx(self): + """Return ``x`` coordinate of north-eastern corner. """ + return self.b[0] + + @property + def by(self): + """Return ``y`` coordinate of north-eastern corner. """ + if not self.conj: + return self.b[1] + else: + return -self.a[1] + + @property + def dx(self): + """Return width of the complex isolating interval. """ + return self.b[0] - self.a[0] + + @property + def dy(self): + """Return height of the complex isolating interval. """ + return self.b[1] - self.a[1] + + @property + def center(self): + """Return the center of the complex isolating interval. """ + return ((self.ax + self.bx)/2, (self.ay + self.by)/2) + + @property + def max_denom(self): + """Return the largest denominator occurring in either endpoint. """ + return max(self.ax.denominator, self.bx.denominator, + self.ay.denominator, self.by.denominator) + + def as_tuple(self): + """Return tuple representation of the complex isolating + interval's SW and NE corners, respectively. """ + return ((self.ax, self.ay), (self.bx, self.by)) + + def __repr__(self): + return "(%s, %s) x (%s, %s)" % (self.ax, self.bx, self.ay, self.by) + + def conjugate(self): + """This complex interval really is located in lower half-plane. """ + return ComplexInterval(self.a, self.b, self.I, self.Q, + self.F1, self.F2, self.f1, self.f2, self.dom, conj=True) + + def __contains__(self, item): + """ + Say whether a complex number belongs to this complex rectangular + region. + + Parameters + ========== + + item : pair (re, im) or number re + Either a pair giving the real and imaginary parts of the number, + or else a real number. + + """ + if isinstance(item, tuple): + re, im = item + else: + re, im = item, 0 + return self.ax <= re <= self.bx and self.ay <= im <= self.by + + def is_disjoint(self, other): + """Return ``True`` if two isolation intervals are disjoint. """ + if isinstance(other, RealInterval): + return other.is_disjoint(self) + if self.conj != other.conj: # above and below real axis + return True + re_distinct = (self.bx < other.ax or other.bx < self.ax) + if re_distinct: + return True + im_distinct = (self.by < other.ay or other.by < self.ay) + return im_distinct + + def _inner_refine(self): + """Internal one step complex root refinement procedure. """ + (u, v), (s, t) = self.a, self.b + + I, Q = self.I, self.Q + + f1, F1 = self.f1, self.F1 + f2, F2 = self.f2, self.F2 + + dom = self.dom + + if s - u > t - v: + D_L, D_R = _vertical_bisection(1, (u, v), (s, t), I, Q, F1, F2, f1, f2, dom) + + if D_L[0] == 1: + _, a, b, I, Q, F1, F2 = D_L + else: + _, a, b, I, Q, F1, F2 = D_R + else: + D_B, D_U = _horizontal_bisection(1, (u, v), (s, t), I, Q, F1, F2, f1, f2, dom) + + if D_B[0] == 1: + _, a, b, I, Q, F1, F2 = D_B + else: + _, a, b, I, Q, F1, F2 = D_U + + return ComplexInterval(a, b, I, Q, F1, F2, f1, f2, dom, self.conj) + + def refine_disjoint(self, other): + """Refine an isolating interval until it is disjoint with another one. """ + expr = self + while not expr.is_disjoint(other): + expr, other = expr._inner_refine(), other._inner_refine() + + return expr, other + + def refine_size(self, dx, dy=None): + """Refine an isolating interval until it is of sufficiently small size. """ + if dy is None: + dy = dx + expr = self + while not (expr.dx < dx and expr.dy < dy): + expr = expr._inner_refine() + + return expr + + def refine_step(self, steps=1): + """Perform several steps of complex root refinement algorithm. """ + expr = self + for _ in range(steps): + expr = expr._inner_refine() + + return expr + + def refine(self): + """Perform one step of complex root refinement algorithm. """ + return self._inner_refine() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rootoftools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rootoftools.py new file mode 100644 index 0000000000000000000000000000000000000000..d68d8b008281c7e9b5aac618c6c76f74fa236d9e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/rootoftools.py @@ -0,0 +1,1298 @@ +"""Implementation of RootOf class and related tools. """ + + + +from sympy.core.basic import Basic +from sympy.core import (S, Expr, Integer, Float, I, oo, Add, Lambda, + symbols, sympify, Rational, Dummy) +from sympy.core.cache import cacheit +from sympy.core.relational import is_le +from sympy.core.sorting import ordered +from sympy.polys.domains import QQ +from sympy.polys.polyerrors import ( + MultivariatePolynomialError, + GeneratorsNeeded, + PolynomialError, + DomainError) +from sympy.polys.polyfuncs import symmetrize, viete +from sympy.polys.polyroots import ( + roots_linear, roots_quadratic, roots_binomial, + preprocess_roots, roots) +from sympy.polys.polytools import Poly, PurePoly, factor +from sympy.polys.rationaltools import together +from sympy.polys.rootisolation import ( + dup_isolate_complex_roots_sqf, + dup_isolate_real_roots_sqf) +from sympy.utilities import lambdify, public, sift, numbered_symbols + +from mpmath import mpf, mpc, findroot, workprec +from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps +from sympy.multipledispatch import dispatch +from itertools import chain + + +__all__ = ['CRootOf'] + + + +class _pure_key_dict: + """A minimal dictionary that makes sure that the key is a + univariate PurePoly instance. + + Examples + ======== + + Only the following actions are guaranteed: + + >>> from sympy.polys.rootoftools import _pure_key_dict + >>> from sympy import PurePoly + >>> from sympy.abc import x, y + + 1) creation + + >>> P = _pure_key_dict() + + 2) assignment for a PurePoly or univariate polynomial + + >>> P[x] = 1 + >>> P[PurePoly(x - y, x)] = 2 + + 3) retrieval based on PurePoly key comparison (use this + instead of the get method) + + >>> P[y] + 1 + + 4) KeyError when trying to retrieve a nonexisting key + + >>> P[y + 1] + Traceback (most recent call last): + ... + KeyError: PurePoly(y + 1, y, domain='ZZ') + + 5) ability to query with ``in`` + + >>> x + 1 in P + False + + NOTE: this is a *not* a dictionary. It is a very basic object + for internal use that makes sure to always address its cache + via PurePoly instances. It does not, for example, implement + ``get`` or ``setdefault``. + """ + def __init__(self): + self._dict = {} + + def __getitem__(self, k): + if not isinstance(k, PurePoly): + if not (isinstance(k, Expr) and len(k.free_symbols) == 1): + raise KeyError + k = PurePoly(k, expand=False) + return self._dict[k] + + def __setitem__(self, k, v): + if not isinstance(k, PurePoly): + if not (isinstance(k, Expr) and len(k.free_symbols) == 1): + raise ValueError('expecting univariate expression') + k = PurePoly(k, expand=False) + self._dict[k] = v + + def __contains__(self, k): + try: + self[k] + return True + except KeyError: + return False + +_reals_cache = _pure_key_dict() +_complexes_cache = _pure_key_dict() + + +def _pure_factors(poly): + _, factors = poly.factor_list() + return [(PurePoly(f, expand=False), m) for f, m in factors] + + +def _imag_count_of_factor(f): + """Return the number of imaginary roots for irreducible + univariate polynomial ``f``. + """ + terms = [(i, j) for (i,), j in f.terms()] + if any(i % 2 for i, j in terms): + return 0 + # update signs + even = [(i, I**i*j) for i, j in terms] + even = Poly.from_dict(dict(even), Dummy('x')) + return int(even.count_roots(-oo, oo)) + + +@public +def rootof(f, x, index=None, radicals=True, expand=True): + """An indexed root of a univariate polynomial. + + Returns either a :obj:`ComplexRootOf` object or an explicit + expression involving radicals. + + Parameters + ========== + + f : Expr + Univariate polynomial. + x : Symbol, optional + Generator for ``f``. + index : int or Integer + radicals : bool + Return a radical expression if possible. + expand : bool + Expand ``f``. + """ + return CRootOf(f, x, index=index, radicals=radicals, expand=expand) + + +@public +class RootOf(Expr): + """Represents a root of a univariate polynomial. + + Base class for roots of different kinds of polynomials. + Only complex roots are currently supported. + """ + + __slots__ = ('poly',) + + def __new__(cls, f, x, index=None, radicals=True, expand=True): + """Construct a new ``CRootOf`` object for ``k``-th root of ``f``.""" + return rootof(f, x, index=index, radicals=radicals, expand=expand) + +@public +class ComplexRootOf(RootOf): + """Represents an indexed complex root of a polynomial. + + Roots of a univariate polynomial separated into disjoint + real or complex intervals and indexed in a fixed order: + + * real roots come first and are sorted in increasing order; + * complex roots come next and are sorted primarily by increasing + real part, secondarily by increasing imaginary part. + + Currently only rational coefficients are allowed. + Can be imported as ``CRootOf``. To avoid confusion, the + generator must be a Symbol. + + + Examples + ======== + + >>> from sympy import CRootOf, rootof + >>> from sympy.abc import x + + CRootOf is a way to reference a particular root of a + polynomial. If there is a rational root, it will be returned: + + >>> CRootOf.clear_cache() # for doctest reproducibility + >>> CRootOf(x**2 - 4, 0) + -2 + + Whether roots involving radicals are returned or not + depends on whether the ``radicals`` flag is true (which is + set to True with rootof): + + >>> CRootOf(x**2 - 3, 0) + CRootOf(x**2 - 3, 0) + >>> CRootOf(x**2 - 3, 0, radicals=True) + -sqrt(3) + >>> rootof(x**2 - 3, 0) + -sqrt(3) + + The following cannot be expressed in terms of radicals: + + >>> r = rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0); r + CRootOf(4*x**5 + 16*x**3 + 12*x**2 + 7, 0) + + The root bounds can be seen, however, and they are used by the + evaluation methods to get numerical approximations for the root. + + >>> interval = r._get_interval(); interval + (-1, 0) + >>> r.evalf(2) + -0.98 + + The evalf method refines the width of the root bounds until it + guarantees that any decimal approximation within those bounds + will satisfy the desired precision. It then stores the refined + interval so subsequent requests at or below the requested + precision will not have to recompute the root bounds and will + return very quickly. + + Before evaluation above, the interval was + + >>> interval + (-1, 0) + + After evaluation it is now + + >>> r._get_interval() # doctest: +SKIP + (-165/169, -206/211) + + To reset all intervals for a given polynomial, the :meth:`_reset` method + can be called from any CRootOf instance of the polynomial: + + >>> r._reset() + >>> r._get_interval() + (-1, 0) + + The :meth:`eval_approx` method will also find the root to a given + precision but the interval is not modified unless the search + for the root fails to converge within the root bounds. And + the secant method is used to find the root. (The ``evalf`` + method uses bisection and will always update the interval.) + + >>> r.eval_approx(2) + -0.98 + + The interval needed to be slightly updated to find that root: + + >>> r._get_interval() + (-1, -1/2) + + The ``evalf_rational`` will compute a rational approximation + of the root to the desired accuracy or precision. + + >>> r.eval_rational(n=2) + -69629/71318 + + >>> t = CRootOf(x**3 + 10*x + 1, 1) + >>> t.eval_rational(1e-1) + 15/256 - 805*I/256 + >>> t.eval_rational(1e-1, 1e-4) + 3275/65536 - 414645*I/131072 + >>> t.eval_rational(1e-4, 1e-4) + 6545/131072 - 414645*I/131072 + >>> t.eval_rational(n=2) + 104755/2097152 - 6634255*I/2097152 + + Notes + ===== + + Although a PurePoly can be constructed from a non-symbol generator + RootOf instances of non-symbols are disallowed to avoid confusion + over what root is being represented. + + >>> from sympy import exp, PurePoly + >>> PurePoly(x) == PurePoly(exp(x)) + True + >>> CRootOf(x - 1, 0) + 1 + >>> CRootOf(exp(x) - 1, 0) # would correspond to x == 0 + Traceback (most recent call last): + ... + sympy.polys.polyerrors.PolynomialError: generator must be a Symbol + + See Also + ======== + + eval_approx + eval_rational + + """ + + __slots__ = ('index',) + is_complex = True + is_number = True + is_finite = True + is_algebraic = True + + def __new__(cls, f, x, index=None, radicals=False, expand=True): + """ Construct an indexed complex root of a polynomial. + + See ``rootof`` for the parameters. + + The default value of ``radicals`` is ``False`` to satisfy + ``eval(srepr(expr) == expr``. + """ + x = sympify(x) + + if index is None and x.is_Integer: + x, index = None, x + else: + index = sympify(index) + + if index is not None and index.is_Integer: + index = int(index) + else: + raise ValueError("expected an integer root index, got %s" % index) + + poly = PurePoly(f, x, greedy=False, expand=expand) + + if not poly.is_univariate: + raise PolynomialError("only univariate polynomials are allowed") + + if not poly.gen.is_Symbol: + # PurePoly(sin(x) + 1) == PurePoly(x + 1) but the roots of + # x for each are not the same: issue 8617 + raise PolynomialError("generator must be a Symbol") + + degree = poly.degree() + + if degree <= 0: + raise PolynomialError("Cannot construct CRootOf object for %s" % f) + + if index < -degree or index >= degree: + raise IndexError("root index out of [%d, %d] range, got %d" % + (-degree, degree - 1, index)) + elif index < 0: + index += degree + + dom = poly.get_domain() + + if not dom.is_Exact: + poly = poly.to_exact() + + roots = cls._roots_trivial(poly, radicals) + + if roots is not None: + return roots[index] + + coeff, poly = preprocess_roots(poly) + dom = poly.get_domain() + + if not dom.is_ZZ: + raise NotImplementedError("CRootOf is not supported over %s" % dom) + + root = cls._indexed_root(poly, index, lazy=True) + return coeff * cls._postprocess_root(root, radicals) + + @classmethod + def _new(cls, poly, index): + """Construct new ``CRootOf`` object from raw data. """ + obj = Expr.__new__(cls) + + obj.poly = PurePoly(poly) + obj.index = index + + try: + _reals_cache[obj.poly] = _reals_cache[poly] + _complexes_cache[obj.poly] = _complexes_cache[poly] + except KeyError: + pass + + return obj + + def _hashable_content(self): + return (self.poly, self.index) + + @property + def expr(self): + return self.poly.as_expr() + + @property + def args(self): + return (self.expr, Integer(self.index)) + + @property + def free_symbols(self): + # CRootOf currently only works with univariate expressions + # whose poly attribute should be a PurePoly with no free + # symbols + return set() + + def _eval_is_real(self): + """Return ``True`` if the root is real. """ + self._ensure_reals_init() + return self.index < len(_reals_cache[self.poly]) + + def _eval_is_imaginary(self): + """Return ``True`` if the root is imaginary. """ + self._ensure_reals_init() + if self.index >= len(_reals_cache[self.poly]): + ivl = self._get_interval() + return ivl.ax*ivl.bx <= 0 # all others are on one side or the other + return False # XXX is this necessary? + + @classmethod + def real_roots(cls, poly, radicals=True): + """Get real roots of a polynomial. """ + return cls._get_roots("_real_roots", poly, radicals) + + @classmethod + def all_roots(cls, poly, radicals=True): + """Get real and complex roots of a polynomial. """ + return cls._get_roots("_all_roots", poly, radicals) + + @classmethod + def _get_reals_sqf(cls, currentfactor, use_cache=True): + """Get real root isolating intervals for a square-free factor.""" + if use_cache and currentfactor in _reals_cache: + real_part = _reals_cache[currentfactor] + else: + _reals_cache[currentfactor] = real_part = \ + dup_isolate_real_roots_sqf( + currentfactor.rep.to_list(), currentfactor.rep.dom, blackbox=True) + + return real_part + + @classmethod + def _get_complexes_sqf(cls, currentfactor, use_cache=True): + """Get complex root isolating intervals for a square-free factor.""" + if use_cache and currentfactor in _complexes_cache: + complex_part = _complexes_cache[currentfactor] + else: + _complexes_cache[currentfactor] = complex_part = \ + dup_isolate_complex_roots_sqf( + currentfactor.rep.to_list(), currentfactor.rep.dom, blackbox=True) + return complex_part + + @classmethod + def _get_reals(cls, factors, use_cache=True): + """Compute real root isolating intervals for a list of factors. """ + reals = [] + + for currentfactor, k in factors: + try: + if not use_cache: + raise KeyError + r = _reals_cache[currentfactor] + reals.extend([(i, currentfactor, k) for i in r]) + except KeyError: + real_part = cls._get_reals_sqf(currentfactor, use_cache) + new = [(root, currentfactor, k) for root in real_part] + reals.extend(new) + + reals = cls._reals_sorted(reals) + return reals + + @classmethod + def _get_complexes(cls, factors, use_cache=True): + """Compute complex root isolating intervals for a list of factors. """ + complexes = [] + + for currentfactor, k in ordered(factors): + try: + if not use_cache: + raise KeyError + c = _complexes_cache[currentfactor] + complexes.extend([(i, currentfactor, k) for i in c]) + except KeyError: + complex_part = cls._get_complexes_sqf(currentfactor, use_cache) + new = [(root, currentfactor, k) for root in complex_part] + complexes.extend(new) + + complexes = cls._complexes_sorted(complexes) + return complexes + + @classmethod + def _reals_sorted(cls, reals): + """Make real isolating intervals disjoint and sort roots. """ + cache = {} + + for i, (u, f, k) in enumerate(reals): + for j, (v, g, m) in enumerate(reals[i + 1:]): + u, v = u.refine_disjoint(v) + reals[i + j + 1] = (v, g, m) + + reals[i] = (u, f, k) + + reals = sorted(reals, key=lambda r: r[0].a) + + for root, currentfactor, _ in reals: + if currentfactor in cache: + cache[currentfactor].append(root) + else: + cache[currentfactor] = [root] + + for currentfactor, root in cache.items(): + _reals_cache[currentfactor] = root + + return reals + + @classmethod + def _refine_imaginary(cls, complexes): + sifted = sift(complexes, lambda c: c[1]) + complexes = [] + for f in ordered(sifted): + nimag = _imag_count_of_factor(f) + if nimag == 0: + # refine until xbounds are neg or pos + for u, f, k in sifted[f]: + while u.ax*u.bx <= 0: + u = u._inner_refine() + complexes.append((u, f, k)) + else: + # refine until all but nimag xbounds are neg or pos + potential_imag = list(range(len(sifted[f]))) + while True: + assert len(potential_imag) > 1 + for i in list(potential_imag): + u, f, k = sifted[f][i] + if u.ax*u.bx > 0: + potential_imag.remove(i) + elif u.ax != u.bx: + u = u._inner_refine() + sifted[f][i] = u, f, k + if len(potential_imag) == nimag: + break + complexes.extend(sifted[f]) + return complexes + + @classmethod + def _refine_complexes(cls, complexes): + """return complexes such that no bounding rectangles of non-conjugate + roots would intersect. In addition, assure that neither ay nor by is + 0 to guarantee that non-real roots are distinct from real roots in + terms of the y-bounds. + """ + # get the intervals pairwise-disjoint. + # If rectangles were drawn around the coordinates of the bounding + # rectangles, no rectangles would intersect after this procedure. + for i, (u, f, k) in enumerate(complexes): + for j, (v, g, m) in enumerate(complexes[i + 1:]): + u, v = u.refine_disjoint(v) + complexes[i + j + 1] = (v, g, m) + + complexes[i] = (u, f, k) + + # refine until the x-bounds are unambiguously positive or negative + # for non-imaginary roots + complexes = cls._refine_imaginary(complexes) + + # make sure that all y bounds are off the real axis + # and on the same side of the axis + for i, (u, f, k) in enumerate(complexes): + while u.ay*u.by <= 0: + u = u.refine() + complexes[i] = u, f, k + return complexes + + @classmethod + def _complexes_sorted(cls, complexes): + """Make complex isolating intervals disjoint and sort roots. """ + complexes = cls._refine_complexes(complexes) + # XXX don't sort until you are sure that it is compatible + # with the indexing method but assert that the desired state + # is not broken + C, F = 0, 1 # location of ComplexInterval and factor + fs = {i[F] for i in complexes} + for i in range(1, len(complexes)): + if complexes[i][F] != complexes[i - 1][F]: + # if this fails the factors of a root were not + # contiguous because a discontinuity should only + # happen once + fs.remove(complexes[i - 1][F]) + for i, cmplx in enumerate(complexes): + # negative im part (conj=True) comes before + # positive im part (conj=False) + assert cmplx[C].conj is (i % 2 == 0) + + # update cache + cache = {} + # -- collate + for root, currentfactor, _ in complexes: + cache.setdefault(currentfactor, []).append(root) + # -- store + for currentfactor, root in cache.items(): + _complexes_cache[currentfactor] = root + + return complexes + + @classmethod + def _reals_index(cls, reals, index): + """ + Map initial real root index to an index in a factor where + the root belongs. + """ + i = 0 + + for j, (_, currentfactor, k) in enumerate(reals): + if index < i + k: + poly, index = currentfactor, 0 + + for _, currentfactor, _ in reals[:j]: + if currentfactor == poly: + index += 1 + + return poly, index + else: + i += k + + @classmethod + def _complexes_index(cls, complexes, index): + """ + Map initial complex root index to an index in a factor where + the root belongs. + """ + i = 0 + for j, (_, currentfactor, k) in enumerate(complexes): + if index < i + k: + poly, index = currentfactor, 0 + + for _, currentfactor, _ in complexes[:j]: + if currentfactor == poly: + index += 1 + + index += len(_reals_cache[poly]) + + return poly, index + else: + i += k + + @classmethod + def _count_roots(cls, roots): + """Count the number of real or complex roots with multiplicities.""" + return sum(k for _, _, k in roots) + + @classmethod + def _indexed_root(cls, poly, index, lazy=False): + """Get a root of a composite polynomial by index. """ + factors = _pure_factors(poly) + + # If the given poly is already irreducible, then the index does not + # need to be adjusted, and we can postpone the heavy lifting of + # computing and refining isolating intervals until that is needed. + # Note, however, that `_pure_factors()` extracts a negative leading + # coeff if present, so `factors[0][0]` may differ from `poly`, and + # is the "normalized" version of `poly` that we must return. + if lazy and len(factors) == 1 and factors[0][1] == 1: + return factors[0][0], index + + reals = cls._get_reals(factors) + reals_count = cls._count_roots(reals) + + if index < reals_count: + return cls._reals_index(reals, index) + else: + complexes = cls._get_complexes(factors) + return cls._complexes_index(complexes, index - reals_count) + + def _ensure_reals_init(self): + """Ensure that our poly has entries in the reals cache. """ + if self.poly not in _reals_cache: + self._indexed_root(self.poly, self.index) + + def _ensure_complexes_init(self): + """Ensure that our poly has entries in the complexes cache. """ + if self.poly not in _complexes_cache: + self._indexed_root(self.poly, self.index) + + @classmethod + def _real_roots(cls, poly): + """Get real roots of a composite polynomial. """ + factors = _pure_factors(poly) + + reals = cls._get_reals(factors) + reals_count = cls._count_roots(reals) + + roots = [] + + for index in range(0, reals_count): + roots.append(cls._reals_index(reals, index)) + + return roots + + def _reset(self): + """ + Reset all intervals + """ + self._all_roots(self.poly, use_cache=False) + + @classmethod + def _all_roots(cls, poly, use_cache=True): + """Get real and complex roots of a composite polynomial. """ + factors = _pure_factors(poly) + + reals = cls._get_reals(factors, use_cache=use_cache) + reals_count = cls._count_roots(reals) + + roots = [] + + for index in range(0, reals_count): + roots.append(cls._reals_index(reals, index)) + + complexes = cls._get_complexes(factors, use_cache=use_cache) + complexes_count = cls._count_roots(complexes) + + for index in range(0, complexes_count): + roots.append(cls._complexes_index(complexes, index)) + + return roots + + @classmethod + @cacheit + def _roots_trivial(cls, poly, radicals): + """Compute roots in linear, quadratic and binomial cases. """ + if poly.degree() == 1: + return roots_linear(poly) + + if not radicals: + return None + + if poly.degree() == 2: + return roots_quadratic(poly) + elif poly.length() == 2 and poly.TC(): + return roots_binomial(poly) + else: + return None + + @classmethod + def _preprocess_roots(cls, poly): + """Take heroic measures to make ``poly`` compatible with ``CRootOf``.""" + dom = poly.get_domain() + + if not dom.is_Exact: + poly = poly.to_exact() + + coeff, poly = preprocess_roots(poly) + dom = poly.get_domain() + + if not dom.is_ZZ: + raise NotImplementedError( + "sorted roots not supported over %s" % dom) + + return coeff, poly + + @classmethod + def _postprocess_root(cls, root, radicals): + """Return the root if it is trivial or a ``CRootOf`` object. """ + poly, index = root + roots = cls._roots_trivial(poly, radicals) + + if roots is not None: + return roots[index] + else: + return cls._new(poly, index) + + @classmethod + def _get_roots(cls, method, poly, radicals): + """Return postprocessed roots of specified kind. """ + if not poly.is_univariate: + raise PolynomialError("only univariate polynomials are allowed") + + dom = poly.get_domain() + + # get rid of gen and it's free symbol + d = Dummy() + poly = poly.subs(poly.gen, d) + x = symbols('x') + # see what others are left and select x or a numbered x + # that doesn't clash + free_names = {str(i) for i in poly.free_symbols} + for x in chain((symbols('x'),), numbered_symbols('x')): + if x.name not in free_names: + poly = poly.replace(d, x) + break + + if dom.is_QQ or dom.is_ZZ: + return cls._get_roots_qq(method, poly, radicals) + elif dom.is_AlgebraicField or dom.is_ZZ_I or dom.is_QQ_I: + return cls._get_roots_alg(method, poly, radicals) + else: + # XXX: not sure how to handle ZZ[x] which appears in some tests? + # this makes the tests pass alright but has to be a better way? + return cls._get_roots_qq(method, poly, radicals) + + + @classmethod + def _get_roots_qq(cls, method, poly, radicals): + """Return postprocessed roots of specified kind + for polynomials with rational coefficients. """ + coeff, poly = cls._preprocess_roots(poly) + roots = [] + + for root in getattr(cls, method)(poly): + roots.append(coeff*cls._postprocess_root(root, radicals)) + + return roots + + @classmethod + def _get_roots_alg(cls, method, poly, radicals): + """Return postprocessed roots of specified kind + for polynomials with algebraic coefficients. It assumes + the domain is already an algebraic field. First it + finds the roots using _get_roots_qq, then uses the + square-free factors to filter roots and get the correct + multiplicity. + """ + + # Existing QQ code can find and sort the roots + roots = cls._get_roots_qq(method, poly.lift(), radicals) + + subroots = {} + for f, m in poly.sqf_list()[1]: + if method == "_real_roots": + roots_filt = f.which_real_roots(roots) + elif method == "_all_roots": + roots_filt = f.which_all_roots(roots) + for r in roots_filt: + subroots[r] = m + + roots_seen = set() + roots_flat = [] + for r in roots: + if r in subroots and r not in roots_seen: + m = subroots[r] + roots_flat.extend([r] * m) + roots_seen.add(r) + + return roots_flat + + @classmethod + def clear_cache(cls): + """Reset cache for reals and complexes. + + The intervals used to approximate a root instance are updated + as needed. When a request is made to see the intervals, the + most current values are shown. `clear_cache` will reset all + CRootOf instances back to their original state. + + See Also + ======== + + _reset + """ + global _reals_cache, _complexes_cache + _reals_cache = _pure_key_dict() + _complexes_cache = _pure_key_dict() + + def _get_interval(self): + """Internal function for retrieving isolation interval from cache. """ + self._ensure_reals_init() + if self.is_real: + return _reals_cache[self.poly][self.index] + else: + reals_count = len(_reals_cache[self.poly]) + self._ensure_complexes_init() + return _complexes_cache[self.poly][self.index - reals_count] + + def _set_interval(self, interval): + """Internal function for updating isolation interval in cache. """ + self._ensure_reals_init() + if self.is_real: + _reals_cache[self.poly][self.index] = interval + else: + reals_count = len(_reals_cache[self.poly]) + self._ensure_complexes_init() + _complexes_cache[self.poly][self.index - reals_count] = interval + + def _eval_subs(self, old, new): + # don't allow subs to change anything + return self + + def _eval_conjugate(self): + if self.is_real: + return self + expr, i = self.args + return self.func(expr, i + (1 if self._get_interval().conj else -1)) + + def eval_approx(self, n, return_mpmath=False): + """Evaluate this complex root to the given precision. + + This uses secant method and root bounds are used to both + generate an initial guess and to check that the root + returned is valid. If ever the method converges outside the + root bounds, the bounds will be made smaller and updated. + """ + prec = dps_to_prec(n) + with workprec(prec): + g = self.poly.gen + if not g.is_Symbol: + d = Dummy('x') + if self.is_imaginary: + d *= I + func = lambdify(d, self.expr.subs(g, d)) + else: + expr = self.expr + if self.is_imaginary: + expr = self.expr.subs(g, I*g) + func = lambdify(g, expr) + + interval = self._get_interval() + while True: + if self.is_real: + a = mpf(str(interval.a)) + b = mpf(str(interval.b)) + if a == b: + root = a + break + x0 = mpf(str(interval.center)) + x1 = x0 + mpf(str(interval.dx))/4 + elif self.is_imaginary: + a = mpf(str(interval.ay)) + b = mpf(str(interval.by)) + if a == b: + root = mpc(mpf('0'), a) + break + x0 = mpf(str(interval.center[1])) + x1 = x0 + mpf(str(interval.dy))/4 + else: + ax = mpf(str(interval.ax)) + bx = mpf(str(interval.bx)) + ay = mpf(str(interval.ay)) + by = mpf(str(interval.by)) + if ax == bx and ay == by: + root = mpc(ax, ay) + break + x0 = mpc(*map(str, interval.center)) + x1 = x0 + mpc(*map(str, (interval.dx, interval.dy)))/4 + try: + # without a tolerance, this will return when (to within + # the given precision) x_i == x_{i-1} + root = findroot(func, (x0, x1)) + # If the (real or complex) root is not in the 'interval', + # then keep refining the interval. This happens if findroot + # accidentally finds a different root outside of this + # interval because our initial estimate 'x0' was not close + # enough. It is also possible that the secant method will + # get trapped by a max/min in the interval; the root + # verification by findroot will raise a ValueError in this + # case and the interval will then be tightened -- and + # eventually the root will be found. + # + # It is also possible that findroot will not have any + # successful iterations to process (in which case it + # will fail to initialize a variable that is tested + # after the iterations and raise an UnboundLocalError). + if self.is_real or self.is_imaginary: + if not bool(root.imag) == self.is_real and ( + a <= root <= b): + if self.is_imaginary: + root = mpc(mpf('0'), root.real) + break + elif (ax <= root.real <= bx and ay <= root.imag <= by): + break + except (UnboundLocalError, ValueError): + pass + interval = interval.refine() + + # update the interval so we at least (for this precision or + # less) don't have much work to do to recompute the root + self._set_interval(interval) + if return_mpmath: + return root + return (Float._new(root.real._mpf_, prec) + + I*Float._new(root.imag._mpf_, prec)) + + def _eval_evalf(self, prec, **kwargs): + """Evaluate this complex root to the given precision.""" + # all kwargs are ignored + return self.eval_rational(n=prec_to_dps(prec))._evalf(prec) + + def eval_rational(self, dx=None, dy=None, n=15): + """ + Return a Rational approximation of ``self`` that has real + and imaginary component approximations that are within ``dx`` + and ``dy`` of the true values, respectively. Alternatively, + ``n`` digits of precision can be specified. + + The interval is refined with bisection and is sure to + converge. The root bounds are updated when the refinement + is complete so recalculation at the same or lesser precision + will not have to repeat the refinement and should be much + faster. + + The following example first obtains Rational approximation to + 1e-8 accuracy for all roots of the 4-th order Legendre + polynomial. Since the roots are all less than 1, this will + ensure the decimal representation of the approximation will be + correct (including rounding) to 6 digits: + + >>> from sympy import legendre_poly, Symbol + >>> x = Symbol("x") + >>> p = legendre_poly(4, x, polys=True) + >>> r = p.real_roots()[-1] + >>> r.eval_rational(10**-8).n(6) + 0.861136 + + It is not necessary to a two-step calculation, however: the + decimal representation can be computed directly: + + >>> r.evalf(17) + 0.86113631159405258 + + """ + dy = dy or dx + if dx: + rtol = None + dx = dx if isinstance(dx, Rational) else Rational(str(dx)) + dy = dy if isinstance(dy, Rational) else Rational(str(dy)) + else: + # 5 binary (or 2 decimal) digits are needed to ensure that + # a given digit is correctly rounded + # prec_to_dps(dps_to_prec(n) + 5) - n <= 2 (tested for + # n in range(1000000) + rtol = S(10)**-(n + 2) # +2 for guard digits + interval = self._get_interval() + while True: + if self.is_real: + if rtol: + dx = abs(interval.center*rtol) + interval = interval.refine_size(dx=dx) + c = interval.center + real = Rational(c) + imag = S.Zero + if not rtol or interval.dx < abs(c*rtol): + break + elif self.is_imaginary: + if rtol: + dy = abs(interval.center[1]*rtol) + dx = 1 + interval = interval.refine_size(dx=dx, dy=dy) + c = interval.center[1] + imag = Rational(c) + real = S.Zero + if not rtol or interval.dy < abs(c*rtol): + break + else: + if rtol: + dx = abs(interval.center[0]*rtol) + dy = abs(interval.center[1]*rtol) + interval = interval.refine_size(dx, dy) + c = interval.center + real, imag = map(Rational, c) + if not rtol or ( + interval.dx < abs(c[0]*rtol) and + interval.dy < abs(c[1]*rtol)): + break + + # update the interval so we at least (for this precision or + # less) don't have much work to do to recompute the root + self._set_interval(interval) + return real + I*imag + + +CRootOf = ComplexRootOf + + +@dispatch(ComplexRootOf, ComplexRootOf) +def _eval_is_eq(lhs, rhs): # noqa:F811 + # if we use is_eq to check here, we get infinite recursion + return lhs == rhs + + +@dispatch(ComplexRootOf, Basic) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa:F811 + # CRootOf represents a Root, so if rhs is that root, it should set + # the expression to zero *and* it should be in the interval of the + # CRootOf instance. It must also be a number that agrees with the + # is_real value of the CRootOf instance. + if not rhs.is_number: + return None + if not rhs.is_finite: + return False + z = lhs.expr.subs(lhs.expr.free_symbols.pop(), rhs).is_zero + if z is False: # all roots will make z True but we don't know + # whether this is the right root if z is True + return False + o = rhs.is_real, rhs.is_imaginary + s = lhs.is_real, lhs.is_imaginary + assert None not in s # this is part of initial refinement + if o != s and None not in o: + return False + re, im = rhs.as_real_imag() + if lhs.is_real: + if im: + return False + i = lhs._get_interval() + a, b = [Rational(str(_)) for _ in (i.a, i.b)] + return sympify(a <= rhs and rhs <= b) + i = lhs._get_interval() + r1, r2, i1, i2 = [Rational(str(j)) for j in ( + i.ax, i.bx, i.ay, i.by)] + return is_le(r1, re) and is_le(re,r2) and is_le(i1,im) and is_le(im,i2) + + +@public +class RootSum(Expr): + """Represents a sum of all roots of a univariate polynomial. """ + + __slots__ = ('poly', 'fun', 'auto') + + def __new__(cls, expr, func=None, x=None, auto=True, quadratic=False): + """Construct a new ``RootSum`` instance of roots of a polynomial.""" + coeff, poly = cls._transform(expr, x) + + if not poly.is_univariate: + raise MultivariatePolynomialError( + "only univariate polynomials are allowed") + + if func is None: + func = Lambda(poly.gen, poly.gen) + else: + is_func = getattr(func, 'is_Function', False) + + if is_func and 1 in func.nargs: + if not isinstance(func, Lambda): + func = Lambda(poly.gen, func(poly.gen)) + else: + raise ValueError( + "expected a univariate function, got %s" % func) + + var, expr = func.variables[0], func.expr + + if coeff is not S.One: + expr = expr.subs(var, coeff*var) + + deg = poly.degree() + + if not expr.has(var): + return deg*expr + + if expr.is_Add: + add_const, expr = expr.as_independent(var) + else: + add_const = S.Zero + + if expr.is_Mul: + mul_const, expr = expr.as_independent(var) + else: + mul_const = S.One + + func = Lambda(var, expr) + + rational = cls._is_func_rational(poly, func) + factors, terms = _pure_factors(poly), [] + + for poly, k in factors: + if poly.is_linear: + term = func(roots_linear(poly)[0]) + elif quadratic and poly.is_quadratic: + term = sum(map(func, roots_quadratic(poly))) + else: + if not rational or not auto: + term = cls._new(poly, func, auto) + else: + term = cls._rational_case(poly, func) + + terms.append(k*term) + + return mul_const*Add(*terms) + deg*add_const + + @classmethod + def _new(cls, poly, func, auto=True): + """Construct new raw ``RootSum`` instance. """ + obj = Expr.__new__(cls) + + obj.poly = poly + obj.fun = func + obj.auto = auto + + return obj + + @classmethod + def new(cls, poly, func, auto=True): + """Construct new ``RootSum`` instance. """ + if not func.expr.has(*func.variables): + return func.expr + + rational = cls._is_func_rational(poly, func) + + if not rational or not auto: + return cls._new(poly, func, auto) + else: + return cls._rational_case(poly, func) + + @classmethod + def _transform(cls, expr, x): + """Transform an expression to a polynomial. """ + poly = PurePoly(expr, x, greedy=False) + return preprocess_roots(poly) + + @classmethod + def _is_func_rational(cls, poly, func): + """Check if a lambda is a rational function. """ + var, expr = func.variables[0], func.expr + return expr.is_rational_function(var) + + @classmethod + def _rational_case(cls, poly, func): + """Handle the rational function case. """ + roots = symbols('r:%d' % poly.degree()) + var, expr = func.variables[0], func.expr + + f = sum(expr.subs(var, r) for r in roots) + p, q = together(f).as_numer_denom() + + domain = QQ[roots] + + p = p.expand() + q = q.expand() + + try: + p = Poly(p, domain=domain, expand=False) + except GeneratorsNeeded: + p, p_coeff = None, (p,) + else: + p_monom, p_coeff = zip(*p.terms()) + + try: + q = Poly(q, domain=domain, expand=False) + except GeneratorsNeeded: + q, q_coeff = None, (q,) + else: + q_monom, q_coeff = zip(*q.terms()) + + coeffs, mapping = symmetrize(p_coeff + q_coeff, formal=True) + formulas, values = viete(poly, roots), [] + + for (sym, _), (_, val) in zip(mapping, formulas): + values.append((sym, val)) + + for i, (coeff, _) in enumerate(coeffs): + coeffs[i] = coeff.subs(values) + + n = len(p_coeff) + + p_coeff = coeffs[:n] + q_coeff = coeffs[n:] + + if p is not None: + p = Poly(dict(zip(p_monom, p_coeff)), *p.gens).as_expr() + else: + (p,) = p_coeff + + if q is not None: + q = Poly(dict(zip(q_monom, q_coeff)), *q.gens).as_expr() + else: + (q,) = q_coeff + + return factor(p/q) + + def _hashable_content(self): + return (self.poly, self.fun) + + @property + def expr(self): + return self.poly.as_expr() + + @property + def args(self): + return (self.expr, self.fun, self.poly.gen) + + @property + def free_symbols(self): + return self.poly.free_symbols | self.fun.free_symbols + + @property + def is_commutative(self): + return True + + def doit(self, **hints): + if not hints.get('roots', True): + return self + + _roots = roots(self.poly, multiple=True) + + if len(_roots) < self.poly.degree(): + return self + else: + return Add(*[self.fun(r) for r in _roots]) + + def _eval_evalf(self, prec): + try: + _roots = self.poly.nroots(n=prec_to_dps(prec)) + except (DomainError, PolynomialError): + return self + else: + return Add(*[self.fun(r) for r in _roots]) + + def _eval_derivative(self, x): + var, expr = self.fun.args + func = Lambda(var, expr.diff(x)) + return self.new(self.poly, func, self.auto) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/solvers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..b333e81d975a8cd71e7eb683c2b943d8538f6ac5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/solvers.py @@ -0,0 +1,435 @@ +"""Low-level linear systems solver. """ + + +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import connected_components + +from sympy.core.sympify import sympify +from sympy.core.numbers import Integer, Rational +from sympy.matrices.dense import MutableDenseMatrix +from sympy.polys.domains import ZZ, QQ + +from sympy.polys.domains import EX +from sympy.polys.rings import sring +from sympy.polys.polyerrors import NotInvertible +from sympy.polys.domainmatrix import DomainMatrix + + +class PolyNonlinearError(Exception): + """Raised by solve_lin_sys for nonlinear equations""" + pass + + +class RawMatrix(MutableDenseMatrix): + """ + .. deprecated:: 1.9 + + This class fundamentally is broken by design. Use ``DomainMatrix`` if + you want a matrix over the polys domains or ``Matrix`` for a matrix + with ``Expr`` elements. The ``RawMatrix`` class will be removed/broken + in future in order to reestablish the invariant that the elements of a + Matrix should be of type ``Expr``. + + """ + _sympify = staticmethod(lambda x, *args, **kwargs: x) + + def __init__(self, *args, **kwargs): + sympy_deprecation_warning( + """ + The RawMatrix class is deprecated. Use either DomainMatrix or + Matrix instead. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-rawmatrix", + ) + + domain = ZZ + for i in range(self.rows): + for j in range(self.cols): + val = self[i,j] + if getattr(val, 'is_Poly', False): + K = val.domain[val.gens] + val_sympy = val.as_expr() + elif hasattr(val, 'parent'): + K = val.parent() + val_sympy = K.to_sympy(val) + elif isinstance(val, (int, Integer)): + K = ZZ + val_sympy = sympify(val) + elif isinstance(val, Rational): + K = QQ + val_sympy = val + else: + for K in ZZ, QQ: + if K.of_type(val): + val_sympy = K.to_sympy(val) + break + else: + raise TypeError + domain = domain.unify(K) + self[i,j] = val_sympy + self.ring = domain + + +def eqs_to_matrix(eqs_coeffs, eqs_rhs, gens, domain): + """Get matrix from linear equations in dict format. + + Explanation + =========== + + Get the matrix representation of a system of linear equations represented + as dicts with low-level DomainElement coefficients. This is an + *internal* function that is used by solve_lin_sys. + + Parameters + ========== + + eqs_coeffs: list[dict[Symbol, DomainElement]] + The left hand sides of the equations as dicts mapping from symbols to + coefficients where the coefficients are instances of + DomainElement. + eqs_rhs: list[DomainElements] + The right hand sides of the equations as instances of + DomainElement. + gens: list[Symbol] + The unknowns in the system of equations. + domain: Domain + The domain for coefficients of both lhs and rhs. + + Returns + ======= + + The augmented matrix representation of the system as a DomainMatrix. + + Examples + ======== + + >>> from sympy import symbols, ZZ + >>> from sympy.polys.solvers import eqs_to_matrix + >>> x, y = symbols('x, y') + >>> eqs_coeff = [{x:ZZ(1), y:ZZ(1)}, {x:ZZ(1), y:ZZ(-1)}] + >>> eqs_rhs = [ZZ(0), ZZ(-1)] + >>> eqs_to_matrix(eqs_coeff, eqs_rhs, [x, y], ZZ) + DomainMatrix([[1, 1, 0], [1, -1, 1]], (2, 3), ZZ) + + See also + ======== + + solve_lin_sys: Uses :func:`~eqs_to_matrix` internally + """ + sym2index = {x: n for n, x in enumerate(gens)} + nrows = len(eqs_coeffs) + ncols = len(gens) + 1 + rows = [[domain.zero] * ncols for _ in range(nrows)] + for row, eq_coeff, eq_rhs in zip(rows, eqs_coeffs, eqs_rhs): + for sym, coeff in eq_coeff.items(): + row[sym2index[sym]] = domain.convert(coeff) + row[-1] = -domain.convert(eq_rhs) + + return DomainMatrix(rows, (nrows, ncols), domain) + + +def sympy_eqs_to_ring(eqs, symbols): + """Convert a system of equations from Expr to a PolyRing + + Explanation + =========== + + High-level functions like ``solve`` expect Expr as inputs but can use + ``solve_lin_sys`` internally. This function converts equations from + ``Expr`` to the low-level poly types used by the ``solve_lin_sys`` + function. + + Parameters + ========== + + eqs: List of Expr + A list of equations as Expr instances + symbols: List of Symbol + A list of the symbols that are the unknowns in the system of + equations. + + Returns + ======= + + Tuple[List[PolyElement], Ring]: The equations as PolyElement instances + and the ring of polynomials within which each equation is represented. + + Examples + ======== + + >>> from sympy import symbols + >>> from sympy.polys.solvers import sympy_eqs_to_ring + >>> a, x, y = symbols('a, x, y') + >>> eqs = [x-y, x+a*y] + >>> eqs_ring, ring = sympy_eqs_to_ring(eqs, [x, y]) + >>> eqs_ring + [x - y, x + a*y] + >>> type(eqs_ring[0]) + + >>> ring + ZZ(a)[x,y] + + With the equations in this form they can be passed to ``solve_lin_sys``: + + >>> from sympy.polys.solvers import solve_lin_sys + >>> solve_lin_sys(eqs_ring, ring) + {y: 0, x: 0} + """ + try: + K, eqs_K = sring(eqs, symbols, field=True, extension=True) + except NotInvertible: + # https://github.com/sympy/sympy/issues/18874 + K, eqs_K = sring(eqs, symbols, domain=EX) + return eqs_K, K.to_domain() + + +def solve_lin_sys(eqs, ring, _raw=True): + """Solve a system of linear equations from a PolynomialRing + + Explanation + =========== + + Solves a system of linear equations given as PolyElement instances of a + PolynomialRing. The basic arithmetic is carried out using instance of + DomainElement which is more efficient than :class:`~sympy.core.expr.Expr` + for the most common inputs. + + While this is a public function it is intended primarily for internal use + so its interface is not necessarily convenient. Users are suggested to use + the :func:`sympy.solvers.solveset.linsolve` function (which uses this + function internally) instead. + + Parameters + ========== + + eqs: list[PolyElement] + The linear equations to be solved as elements of a + PolynomialRing (assumed equal to zero). + ring: PolynomialRing + The polynomial ring from which eqs are drawn. The generators of this + ring are the unknowns to be solved for and the domain of the ring is + the domain of the coefficients of the system of equations. + _raw: bool + If *_raw* is False, the keys and values in the returned dictionary + will be of type Expr (and the unit of the field will be removed from + the keys) otherwise the low-level polys types will be returned, e.g. + PolyElement: PythonRational. + + Returns + ======= + + ``None`` if the system has no solution. + + dict[Symbol, Expr] if _raw=False + + dict[Symbol, DomainElement] if _raw=True. + + Examples + ======== + + >>> from sympy import symbols + >>> from sympy.polys.solvers import solve_lin_sys, sympy_eqs_to_ring + >>> x, y = symbols('x, y') + >>> eqs = [x - y, x + y - 2] + >>> eqs_ring, ring = sympy_eqs_to_ring(eqs, [x, y]) + >>> solve_lin_sys(eqs_ring, ring) + {y: 1, x: 1} + + Passing ``_raw=False`` returns the same result except that the keys are + ``Expr`` rather than low-level poly types. + + >>> solve_lin_sys(eqs_ring, ring, _raw=False) + {x: 1, y: 1} + + See also + ======== + + sympy_eqs_to_ring: prepares the inputs to ``solve_lin_sys``. + linsolve: ``linsolve`` uses ``solve_lin_sys`` internally. + sympy.solvers.solvers.solve: ``solve`` uses ``solve_lin_sys`` internally. + """ + as_expr = not _raw + + assert ring.domain.is_Field + + eqs_dict = [dict(eq) for eq in eqs] + + one_monom = ring.one.monoms()[0] + zero = ring.domain.zero + + eqs_rhs = [] + eqs_coeffs = [] + for eq_dict in eqs_dict: + eq_rhs = eq_dict.pop(one_monom, zero) + eq_coeffs = {} + for monom, coeff in eq_dict.items(): + if sum(monom) != 1: + msg = "Nonlinear term encountered in solve_lin_sys" + raise PolyNonlinearError(msg) + eq_coeffs[ring.gens[monom.index(1)]] = coeff + if not eq_coeffs: + if not eq_rhs: + continue + else: + return None + eqs_rhs.append(eq_rhs) + eqs_coeffs.append(eq_coeffs) + + result = _solve_lin_sys(eqs_coeffs, eqs_rhs, ring) + + if result is not None and as_expr: + + def to_sympy(x): + as_expr = getattr(x, 'as_expr', None) + if as_expr: + return as_expr() + else: + return ring.domain.to_sympy(x) + + tresult = {to_sympy(sym): to_sympy(val) for sym, val in result.items()} + + # Remove 1.0x + result = {} + for k, v in tresult.items(): + if k.is_Mul: + c, s = k.as_coeff_Mul() + result[s] = v/c + else: + result[k] = v + + return result + + +def _solve_lin_sys(eqs_coeffs, eqs_rhs, ring): + """Solve a linear system from dict of PolynomialRing coefficients + + Explanation + =========== + + This is an **internal** function used by :func:`solve_lin_sys` after the + equations have been preprocessed. The role of this function is to split + the system into connected components and pass those to + :func:`_solve_lin_sys_component`. + + Examples + ======== + + Setup a system for $x-y=0$ and $x+y=2$ and solve: + + >>> from sympy import symbols, sring + >>> from sympy.polys.solvers import _solve_lin_sys + >>> x, y = symbols('x, y') + >>> R, (xr, yr) = sring([x, y], [x, y]) + >>> eqs = [{xr:R.one, yr:-R.one}, {xr:R.one, yr:R.one}] + >>> eqs_rhs = [R.zero, -2*R.one] + >>> _solve_lin_sys(eqs, eqs_rhs, R) + {y: 1, x: 1} + + See also + ======== + + solve_lin_sys: This function is used internally by :func:`solve_lin_sys`. + """ + V = ring.gens + E = [] + for eq_coeffs in eqs_coeffs: + syms = list(eq_coeffs) + E.extend(zip(syms[:-1], syms[1:])) + G = V, E + + components = connected_components(G) + + sym2comp = {} + for n, component in enumerate(components): + for sym in component: + sym2comp[sym] = n + + subsystems = [([], []) for _ in range(len(components))] + for eq_coeff, eq_rhs in zip(eqs_coeffs, eqs_rhs): + sym = next(iter(eq_coeff), None) + sub_coeff, sub_rhs = subsystems[sym2comp[sym]] + sub_coeff.append(eq_coeff) + sub_rhs.append(eq_rhs) + + sol = {} + for subsystem in subsystems: + subsol = _solve_lin_sys_component(subsystem[0], subsystem[1], ring) + if subsol is None: + return None + sol.update(subsol) + + return sol + + +def _solve_lin_sys_component(eqs_coeffs, eqs_rhs, ring): + """Solve a linear system from dict of PolynomialRing coefficients + + Explanation + =========== + + This is an **internal** function used by :func:`solve_lin_sys` after the + equations have been preprocessed. After :func:`_solve_lin_sys` splits the + system into connected components this function is called for each + component. The system of equations is solved using Gauss-Jordan + elimination with division followed by back-substitution. + + Examples + ======== + + Setup a system for $x-y=0$ and $x+y=2$ and solve: + + >>> from sympy import symbols, sring + >>> from sympy.polys.solvers import _solve_lin_sys_component + >>> x, y = symbols('x, y') + >>> R, (xr, yr) = sring([x, y], [x, y]) + >>> eqs = [{xr:R.one, yr:-R.one}, {xr:R.one, yr:R.one}] + >>> eqs_rhs = [R.zero, -2*R.one] + >>> _solve_lin_sys_component(eqs, eqs_rhs, R) + {y: 1, x: 1} + + See also + ======== + + solve_lin_sys: This function is used internally by :func:`solve_lin_sys`. + """ + + # transform from equations to matrix form + matrix = eqs_to_matrix(eqs_coeffs, eqs_rhs, ring.gens, ring.domain) + + # convert to a field for rref + if not matrix.domain.is_Field: + matrix = matrix.to_field() + + # solve by row-reduction + echelon, pivots = matrix.rref() + + # construct the returnable form of the solutions + keys = ring.gens + + if pivots and pivots[-1] == len(keys): + return None + + if len(pivots) == len(keys): + sol = [] + for s in [row[-1] for row in echelon.rep.to_ddm()]: + a = s + sol.append(a) + sols = dict(zip(keys, sol)) + else: + sols = {} + g = ring.gens + # Extract ground domain coefficients and convert to the ring: + if hasattr(ring, 'ring'): + convert = ring.ring.ground_new + else: + convert = ring.ground_new + echelon = echelon.rep.to_ddm() + vals_set = {v for row in echelon for v in row} + vals_map = {v: convert(v) for v in vals_set} + echelon = [[vals_map[eij] for eij in ei] for ei in echelon] + for i, p in enumerate(pivots): + v = echelon[i][-1] - sum(echelon[i][j]*g[j] for j in range(p+1, len(g)) if echelon[i][j]) + sols[keys[p]] = v + + return sols diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/specialpolys.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/specialpolys.py new file mode 100644 index 0000000000000000000000000000000000000000..3e85de8679cda3084f1c263a045f4d8f817bed98 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/specialpolys.py @@ -0,0 +1,340 @@ +"""Functions for generating interesting polynomials, e.g. for benchmarking. """ + + +from sympy.core import Add, Mul, Symbol, sympify, Dummy, symbols +from sympy.core.containers import Tuple +from sympy.core.singleton import S +from sympy.ntheory import nextprime +from sympy.polys.densearith import ( + dmp_add_term, dmp_neg, dmp_mul, dmp_sqr +) +from sympy.polys.densebasic import ( + dmp_zero, dmp_one, dmp_ground, + dup_from_raw_dict, dmp_raise, dup_random +) +from sympy.polys.domains import ZZ +from sympy.polys.factortools import dup_zz_cyclotomic_poly +from sympy.polys.polyclasses import DMP +from sympy.polys.polytools import Poly, PurePoly +from sympy.polys.polyutils import _analyze_gens +from sympy.utilities import subsets, public, filldedent + + +@public +def swinnerton_dyer_poly(n, x=None, polys=False): + """Generates n-th Swinnerton-Dyer polynomial in `x`. + + Parameters + ---------- + n : int + `n` decides the order of polynomial + x : optional + polys : bool, optional + ``polys=True`` returns an expression, otherwise + (default) returns an expression. + """ + if n <= 0: + raise ValueError( + "Cannot generate Swinnerton-Dyer polynomial of order %s" % n) + + if x is not None: + sympify(x) + else: + x = Dummy('x') + + if n > 3: + from sympy.functions.elementary.miscellaneous import sqrt + from .numberfields import minimal_polynomial + p = 2 + a = [sqrt(2)] + for i in range(2, n + 1): + p = nextprime(p) + a.append(sqrt(p)) + return minimal_polynomial(Add(*a), x, polys=polys) + + if n == 1: + ex = x**2 - 2 + elif n == 2: + ex = x**4 - 10*x**2 + 1 + elif n == 3: + ex = x**8 - 40*x**6 + 352*x**4 - 960*x**2 + 576 + + return PurePoly(ex, x) if polys else ex + + +@public +def cyclotomic_poly(n, x=None, polys=False): + """Generates cyclotomic polynomial of order `n` in `x`. + + Parameters + ---------- + n : int + `n` decides the order of polynomial + x : optional + polys : bool, optional + ``polys=True`` returns an expression, otherwise + (default) returns an expression. + """ + if n <= 0: + raise ValueError( + "Cannot generate cyclotomic polynomial of order %s" % n) + + poly = DMP(dup_zz_cyclotomic_poly(int(n), ZZ), ZZ) + + if x is not None: + poly = Poly.new(poly, x) + else: + poly = PurePoly.new(poly, Dummy('x')) + + return poly if polys else poly.as_expr() + + +@public +def symmetric_poly(n, *gens, polys=False): + """ + Generates symmetric polynomial of order `n`. + + Parameters + ========== + + polys: bool, optional (default: False) + Returns a Poly object when ``polys=True``, otherwise + (default) returns an expression. + """ + gens = _analyze_gens(gens) + + if n < 0 or n > len(gens) or not gens: + raise ValueError("Cannot generate symmetric polynomial of order %s for %s" % (n, gens)) + elif not n: + poly = S.One + else: + poly = Add(*[Mul(*s) for s in subsets(gens, int(n))]) + + return Poly(poly, *gens) if polys else poly + + +@public +def random_poly(x, n, inf, sup, domain=ZZ, polys=False): + """Generates a polynomial of degree ``n`` with coefficients in + ``[inf, sup]``. + + Parameters + ---------- + x + `x` is the independent term of polynomial + n : int + `n` decides the order of polynomial + inf + Lower limit of range in which coefficients lie + sup + Upper limit of range in which coefficients lie + domain : optional + Decides what ring the coefficients are supposed + to belong. Default is set to Integers. + polys : bool, optional + ``polys=True`` returns an expression, otherwise + (default) returns an expression. + """ + poly = Poly(dup_random(n, inf, sup, domain), x, domain=domain) + + return poly if polys else poly.as_expr() + + +@public +def interpolating_poly(n, x, X='x', Y='y'): + """Construct Lagrange interpolating polynomial for ``n`` + data points. If a sequence of values are given for ``X`` and ``Y`` + then the first ``n`` values will be used. + """ + ok = getattr(x, 'free_symbols', None) + + if isinstance(X, str): + X = symbols("%s:%s" % (X, n)) + elif ok and ok & Tuple(*X).free_symbols: + ok = False + + if isinstance(Y, str): + Y = symbols("%s:%s" % (Y, n)) + elif ok and ok & Tuple(*Y).free_symbols: + ok = False + + if not ok: + raise ValueError(filldedent(''' + Expecting symbol for x that does not appear in X or Y. + Use `interpolate(list(zip(X, Y)), x)` instead.''')) + + coeffs = [] + numert = Mul(*[x - X[i] for i in range(n)]) + + for i in range(n): + numer = numert/(x - X[i]) + denom = Mul(*[(X[i] - X[j]) for j in range(n) if i != j]) + coeffs.append(numer/denom) + + return Add(*[coeff*y for coeff, y in zip(coeffs, Y)]) + + +def fateman_poly_F_1(n): + """Fateman's GCD benchmark: trivial GCD """ + Y = [Symbol('y_' + str(i)) for i in range(n + 1)] + + y_0, y_1 = Y[0], Y[1] + + u = y_0 + Add(*Y[1:]) + v = y_0**2 + Add(*[y**2 for y in Y[1:]]) + + F = ((u + 1)*(u + 2)).as_poly(*Y) + G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 - 1)).as_poly(*Y) + + H = Poly(1, *Y) + + return F, G, H + + +def dmp_fateman_poly_F_1(n, K): + """Fateman's GCD benchmark: trivial GCD """ + u = [K(1), K(0)] + + for i in range(n): + u = [dmp_one(i, K), u] + + v = [K(1), K(0), K(0)] + + for i in range(0, n): + v = [dmp_one(i, K), dmp_zero(i), v] + + m = n - 1 + + U = dmp_add_term(u, dmp_ground(K(1), m), 0, n, K) + V = dmp_add_term(u, dmp_ground(K(2), m), 0, n, K) + + f = [[-K(3), K(0)], [], [K(1), K(0), -K(1)]] + + W = dmp_add_term(v, dmp_ground(K(1), m), 0, n, K) + Y = dmp_raise(f, m, 1, K) + + F = dmp_mul(U, V, n, K) + G = dmp_mul(W, Y, n, K) + + H = dmp_one(n, K) + + return F, G, H + + +def fateman_poly_F_2(n): + """Fateman's GCD benchmark: linearly dense quartic inputs """ + Y = [Symbol('y_' + str(i)) for i in range(n + 1)] + + y_0 = Y[0] + + u = Add(*Y[1:]) + + H = Poly((y_0 + u + 1)**2, *Y) + + F = Poly((y_0 - u - 2)**2, *Y) + G = Poly((y_0 + u + 2)**2, *Y) + + return H*F, H*G, H + + +def dmp_fateman_poly_F_2(n, K): + """Fateman's GCD benchmark: linearly dense quartic inputs """ + u = [K(1), K(0)] + + for i in range(n - 1): + u = [dmp_one(i, K), u] + + m = n - 1 + + v = dmp_add_term(u, dmp_ground(K(2), m - 1), 0, n, K) + + f = dmp_sqr([dmp_one(m, K), dmp_neg(v, m, K)], n, K) + g = dmp_sqr([dmp_one(m, K), v], n, K) + + v = dmp_add_term(u, dmp_one(m - 1, K), 0, n, K) + + h = dmp_sqr([dmp_one(m, K), v], n, K) + + return dmp_mul(f, h, n, K), dmp_mul(g, h, n, K), h + + +def fateman_poly_F_3(n): + """Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ + Y = [Symbol('y_' + str(i)) for i in range(n + 1)] + + y_0 = Y[0] + + u = Add(*[y**(n + 1) for y in Y[1:]]) + + H = Poly((y_0**(n + 1) + u + 1)**2, *Y) + + F = Poly((y_0**(n + 1) - u - 2)**2, *Y) + G = Poly((y_0**(n + 1) + u + 2)**2, *Y) + + return H*F, H*G, H + + +def dmp_fateman_poly_F_3(n, K): + """Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ + u = dup_from_raw_dict({n + 1: K.one}, K) + + for i in range(0, n - 1): + u = dmp_add_term([u], dmp_one(i, K), n + 1, i + 1, K) + + v = dmp_add_term(u, dmp_ground(K(2), n - 2), 0, n, K) + + f = dmp_sqr( + dmp_add_term([dmp_neg(v, n - 1, K)], dmp_one(n - 1, K), n + 1, n, K), n, K) + g = dmp_sqr(dmp_add_term([v], dmp_one(n - 1, K), n + 1, n, K), n, K) + + v = dmp_add_term(u, dmp_one(n - 2, K), 0, n - 1, K) + + h = dmp_sqr(dmp_add_term([v], dmp_one(n - 1, K), n + 1, n, K), n, K) + + return dmp_mul(f, h, n, K), dmp_mul(g, h, n, K), h + +# A few useful polynomials from Wang's paper ('78). + +from sympy.polys.rings import ring + +def _f_0(): + R, x, y, z = ring("x,y,z", ZZ) + return x**2*y*z**2 + 2*x**2*y*z + 3*x**2*y + 2*x**2 + 3*x + 4*y**2*z**2 + 5*y**2*z + 6*y**2 + y*z**2 + 2*y*z + y + 1 + +def _f_1(): + R, x, y, z = ring("x,y,z", ZZ) + return x**3*y*z + x**2*y**2*z**2 + x**2*y**2 + 20*x**2*y*z + 30*x**2*y + x**2*z**2 + 10*x**2*z + x*y**3*z + 30*x*y**2*z + 20*x*y**2 + x*y*z**3 + 10*x*y*z**2 + x*y*z + 610*x*y + 20*x*z**2 + 230*x*z + 300*x + y**2*z**2 + 10*y**2*z + 30*y*z**2 + 320*y*z + 200*y + 600*z + 6000 + +def _f_2(): + R, x, y, z = ring("x,y,z", ZZ) + return x**5*y**3 + x**5*y**2*z + x**5*y*z**2 + x**5*z**3 + x**3*y**2 + x**3*y*z + 90*x**3*y + 90*x**3*z + x**2*y**2*z - 11*x**2*y**2 + x**2*z**3 - 11*x**2*z**2 + y*z - 11*y + 90*z - 990 + +def _f_3(): + R, x, y, z = ring("x,y,z", ZZ) + return x**5*y**2 + x**4*z**4 + x**4 + x**3*y**3*z + x**3*z + x**2*y**4 + x**2*y**3*z**3 + x**2*y*z**5 + x**2*y*z + x*y**2*z**4 + x*y**2 + x*y*z**7 + x*y*z**3 + x*y*z**2 + y**2*z + y*z**4 + +def _f_4(): + R, x, y, z = ring("x,y,z", ZZ) + return -x**9*y**8*z - x**8*y**5*z**3 - x**7*y**12*z**2 - 5*x**7*y**8 - x**6*y**9*z**4 + x**6*y**7*z**3 + 3*x**6*y**7*z - 5*x**6*y**5*z**2 - x**6*y**4*z**3 + x**5*y**4*z**5 + 3*x**5*y**4*z**3 - x**5*y*z**5 + x**4*y**11*z**4 + 3*x**4*y**11*z**2 - x**4*y**8*z**4 + 5*x**4*y**7*z**2 + 15*x**4*y**7 - 5*x**4*y**4*z**2 + x**3*y**8*z**6 + 3*x**3*y**8*z**4 - x**3*y**5*z**6 + 5*x**3*y**4*z**4 + 15*x**3*y**4*z**2 + x**3*y**3*z**5 + 3*x**3*y**3*z**3 - 5*x**3*y*z**4 + x**2*z**7 + 3*x**2*z**5 + x*y**7*z**6 + 3*x*y**7*z**4 + 5*x*y**3*z**4 + 15*x*y**3*z**2 + y**4*z**8 + 3*y**4*z**6 + 5*z**6 + 15*z**4 + +def _f_5(): + R, x, y, z = ring("x,y,z", ZZ) + return -x**3 - 3*x**2*y + 3*x**2*z - 3*x*y**2 + 6*x*y*z - 3*x*z**2 - y**3 + 3*y**2*z - 3*y*z**2 + z**3 + +def _f_6(): + R, x, y, z, t = ring("x,y,z,t", ZZ) + return 2115*x**4*y + 45*x**3*z**3*t**2 - 45*x**3*t**2 - 423*x*y**4 - 47*x*y**3 + 141*x*y*z**3 + 94*x*y*z*t - 9*y**3*z**3*t**2 + 9*y**3*t**2 - y**2*z**3*t**2 + y**2*t**2 + 3*z**6*t**2 + 2*z**4*t**3 - 3*z**3*t**2 - 2*z*t**3 + +def _w_1(): + R, x, y, z = ring("x,y,z", ZZ) + return 4*x**6*y**4*z**2 + 4*x**6*y**3*z**3 - 4*x**6*y**2*z**4 - 4*x**6*y*z**5 + x**5*y**4*z**3 + 12*x**5*y**3*z - x**5*y**2*z**5 + 12*x**5*y**2*z**2 - 12*x**5*y*z**3 - 12*x**5*z**4 + 8*x**4*y**4 + 6*x**4*y**3*z**2 + 8*x**4*y**3*z - 4*x**4*y**2*z**4 + 4*x**4*y**2*z**3 - 8*x**4*y**2*z**2 - 4*x**4*y*z**5 - 2*x**4*y*z**4 - 8*x**4*y*z**3 + 2*x**3*y**4*z + x**3*y**3*z**3 - x**3*y**2*z**5 - 2*x**3*y**2*z**3 + 9*x**3*y**2*z - 12*x**3*y*z**3 + 12*x**3*y*z**2 - 12*x**3*z**4 + 3*x**3*z**3 + 6*x**2*y**3 - 6*x**2*y**2*z**2 + 8*x**2*y**2*z - 2*x**2*y*z**4 - 8*x**2*y*z**3 + 2*x**2*y*z**2 + 2*x*y**3*z - 2*x*y**2*z**3 - 3*x*y*z + 3*x*z**3 - 2*y**2 + 2*y*z**2 + +def _w_2(): + R, x, y = ring("x,y", ZZ) + return 24*x**8*y**3 + 48*x**8*y**2 + 24*x**7*y**5 - 72*x**7*y**2 + 25*x**6*y**4 + 2*x**6*y**3 + 4*x**6*y + 8*x**6 + x**5*y**6 + x**5*y**3 - 12*x**5 + x**4*y**5 - x**4*y**4 - 2*x**4*y**3 + 292*x**4*y**2 - x**3*y**6 + 3*x**3*y**3 - x**2*y**5 + 12*x**2*y**3 + 48*x**2 - 12*y**3 + +def f_polys(): + return _f_0(), _f_1(), _f_2(), _f_3(), _f_4(), _f_5(), _f_6() + +def w_polys(): + return _w_1(), _w_2() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/sqfreetools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/sqfreetools.py new file mode 100644 index 0000000000000000000000000000000000000000..b2bf434cab542a42c0f7d67058e1a3c01857335d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/sqfreetools.py @@ -0,0 +1,795 @@ +"""Square-free decomposition algorithms and related tools. """ + + +from sympy.polys.densearith import ( + dup_neg, dmp_neg, + dup_sub, dmp_sub, + dup_mul, dmp_mul, + dup_quo, dmp_quo, + dup_mul_ground, dmp_mul_ground) +from sympy.polys.densebasic import ( + dup_strip, + dup_LC, dmp_ground_LC, + dmp_zero_p, + dmp_ground, + dup_degree, dmp_degree, dmp_degree_in, dmp_degree_list, + dmp_raise, dmp_inject, + dup_convert) +from sympy.polys.densetools import ( + dup_diff, dmp_diff, dmp_diff_in, + dup_shift, dmp_shift, + dup_monic, dmp_ground_monic, + dup_primitive, dmp_ground_primitive) +from sympy.polys.euclidtools import ( + dup_inner_gcd, dmp_inner_gcd, + dup_gcd, dmp_gcd, + dmp_resultant, dmp_primitive) +from sympy.polys.galoistools import ( + gf_sqf_list, gf_sqf_part) +from sympy.polys.polyerrors import ( + MultivariatePolynomialError, + DomainError) + + +def _dup_check_degrees(f, result): + """Sanity check the degrees of a computed factorization in K[x].""" + deg = sum(k * dup_degree(fac) for (fac, k) in result) + assert deg == dup_degree(f) + + +def _dmp_check_degrees(f, u, result): + """Sanity check the degrees of a computed factorization in K[X].""" + degs = [0] * (u + 1) + for fac, k in result: + degs_fac = dmp_degree_list(fac, u) + degs = [d1 + k * d2 for d1, d2 in zip(degs, degs_fac)] + assert tuple(degs) == dmp_degree_list(f, u) + + +def dup_sqf_p(f, K): + """ + Return ``True`` if ``f`` is a square-free polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sqf_p(x**2 - 2*x + 1) + False + >>> R.dup_sqf_p(x**2 - 1) + True + + """ + if not f: + return True + else: + return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) + + +def dmp_sqf_p(f, u, K): + """ + Return ``True`` if ``f`` is a square-free polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_sqf_p(x**2 + 2*x*y + y**2) + False + >>> R.dmp_sqf_p(x**2 + y**2) + True + + """ + if dmp_zero_p(f, u): + return True + + for i in range(u+1): + + fp = dmp_diff_in(f, 1, i, u, K) + + if dmp_zero_p(fp, u): + continue + + gcd = dmp_gcd(f, fp, u, K) + + if dmp_degree_in(gcd, i, u) != 0: + return False + + return True + + +def dup_sqf_norm(f, K): + r""" + Find a shift of `f` in `K[x]` that has square-free norm. + + The domain `K` must be an algebraic number field `k(a)` (see :ref:`QQ(a)`). + + Returns `(s,g,r)`, such that `g(x)=f(x-sa)`, `r(x)=\text{Norm}(g(x))` and + `r` is a square-free polynomial over `k`. + + Examples + ======== + + We first create the algebraic number field `K=k(a)=\mathbb{Q}(\sqrt{3})` + and rings `K[x]` and `k[x]`: + + >>> from sympy.polys import ring, QQ + >>> from sympy import sqrt + + >>> K = QQ.algebraic_field(sqrt(3)) + >>> R, x = ring("x", K) + >>> _, X = ring("x", QQ) + + We can now find a square free norm for a shift of `f`: + + >>> f = x**2 - 1 + >>> s, g, r = R.dup_sqf_norm(f) + + The choice of shift `s` is arbitrary and the particular values returned for + `g` and `r` are determined by `s`. + + >>> s == 1 + True + >>> g == x**2 - 2*sqrt(3)*x + 2 + True + >>> r == X**4 - 8*X**2 + 4 + True + + The invariants are: + + >>> g == f.shift(-s*K.unit) + True + >>> g.norm() == r + True + >>> r.is_squarefree + True + + Explanation + =========== + + This is part of Trager's algorithm for factorizing polynomials over + algebraic number fields. In particular this function is algorithm + ``sqfr_norm`` from [Trager76]_. + + See Also + ======== + + dmp_sqf_norm: + Analogous function for multivariate polynomials over ``k(a)``. + dmp_norm: + Computes the norm of `f` directly without any shift. + dup_ext_factor: + Function implementing Trager's algorithm that uses this. + sympy.polys.polytools.sqf_norm: + High-level interface for using this function. + """ + if not K.is_Algebraic: + raise DomainError("ground domain must be algebraic") + + s, g = 0, dmp_raise(K.mod.to_list(), 1, 0, K.dom) + + while True: + h, _ = dmp_inject(f, 0, K, front=True) + r = dmp_resultant(g, h, 1, K.dom) + + if dup_sqf_p(r, K.dom): + break + else: + f, s = dup_shift(f, -K.unit, K), s + 1 + + return s, f, r + + +def _dmp_sqf_norm_shifts(f, u, K): + """Generate a sequence of candidate shifts for dmp_sqf_norm.""" + # + # We want to find a minimal shift if possible because shifting high degree + # variables can be expensive e.g. x**10 -> (x + 1)**10. We try a few easy + # cases first before the final infinite loop that is guaranteed to give + # only finitely many bad shifts (see Trager76 for proof of this in the + # univariate case). + # + + # First the trivial shift [0, 0, ...] + n = u + 1 + s0 = [0] * n + yield s0, f + + # Shift in multiples of the generator of the extension field K + a = K.unit + + # Variables of degree > 0 ordered by increasing degree + d = dmp_degree_list(f, u) + var_indices = [i for di, i in sorted(zip(d, range(u+1))) if di > 0] + + # Now try [1, 0, 0, ...], [0, 1, 0, ...] + for i in var_indices: + s1 = s0.copy() + s1[i] = 1 + a1 = [-a*s1i for s1i in s1] + f1 = dmp_shift(f, a1, u, K) + yield s1, f1 + + # Now try [1, 1, 1, ...], [2, 2, 2, ...] + j = 0 + while True: + j += 1 + sj = [j] * n + aj = [-a*j] * n + fj = dmp_shift(f, aj, u, K) + yield sj, fj + + +def dmp_sqf_norm(f, u, K): + r""" + Find a shift of ``f`` in ``K[X]`` that has square-free norm. + + The domain `K` must be an algebraic number field `k(a)` (see :ref:`QQ(a)`). + + Returns `(s,g,r)`, such that `g(x_1,x_2,\cdots)=f(x_1-s_1 a, x_2 - s_2 a, + \cdots)`, `r(x)=\text{Norm}(g(x))` and `r` is a square-free polynomial over + `k`. + + Examples + ======== + + We first create the algebraic number field `K=k(a)=\mathbb{Q}(i)` and rings + `K[x,y]` and `k[x,y]`: + + >>> from sympy.polys import ring, QQ + >>> from sympy import I + + >>> K = QQ.algebraic_field(I) + >>> R, x, y = ring("x,y", K) + >>> _, X, Y = ring("x,y", QQ) + + We can now find a square free norm for a shift of `f`: + + >>> f = x*y + y**2 + >>> s, g, r = R.dmp_sqf_norm(f) + + The choice of shifts ``s`` is arbitrary and the particular values returned + for ``g`` and ``r`` are determined by ``s``. + + >>> s + [0, 1] + >>> g == x*y - I*x + y**2 - 2*I*y - 1 + True + >>> r == X**2*Y**2 + X**2 + 2*X*Y**3 + 2*X*Y + Y**4 + 2*Y**2 + 1 + True + + The required invariants are: + + >>> g == f.shift_list([-si*K.unit for si in s]) + True + >>> g.norm() == r + True + >>> r.is_squarefree + True + + Explanation + =========== + + This is part of Trager's algorithm for factorizing polynomials over + algebraic number fields. In particular this function is a multivariate + generalization of algorithm ``sqfr_norm`` from [Trager76]_. + + See Also + ======== + + dup_sqf_norm: + Analogous function for univariate polynomials over ``k(a)``. + dmp_norm: + Computes the norm of `f` directly without any shift. + dmp_ext_factor: + Function implementing Trager's algorithm that uses this. + sympy.polys.polytools.sqf_norm: + High-level interface for using this function. + """ + if not u: + s, g, r = dup_sqf_norm(f, K) + return [s], g, r + + if not K.is_Algebraic: + raise DomainError("ground domain must be algebraic") + + g = dmp_raise(K.mod.to_list(), u + 1, 0, K.dom) + + for s, f in _dmp_sqf_norm_shifts(f, u, K): + + h, _ = dmp_inject(f, u, K, front=True) + r = dmp_resultant(g, h, u + 1, K.dom) + + if dmp_sqf_p(r, u, K.dom): + break + + return s, f, r + + +def dmp_norm(f, u, K): + r""" + Norm of ``f`` in ``K[X]``, often not square-free. + + The domain `K` must be an algebraic number field `k(a)` (see :ref:`QQ(a)`). + + Examples + ======== + + We first define the algebraic number field `K = k(a) = \mathbb{Q}(\sqrt{2})`: + + >>> from sympy import QQ, sqrt + >>> from sympy.polys.sqfreetools import dmp_norm + >>> k = QQ + >>> K = k.algebraic_field(sqrt(2)) + + We can now compute the norm of a polynomial `p` in `K[x,y]`: + + >>> p = [[K(1)], [K(1),K.unit]] # x + y + sqrt(2) + >>> N = [[k(1)], [k(2),k(0)], [k(1),k(0),k(-2)]] # x**2 + 2*x*y + y**2 - 2 + >>> dmp_norm(p, 1, K) == N + True + + In higher level functions that is: + + >>> from sympy import expand, roots, minpoly + >>> from sympy.abc import x, y + >>> from math import prod + >>> a = sqrt(2) + >>> e = (x + y + a) + >>> e.as_poly([x, y], extension=a).norm() + Poly(x**2 + 2*x*y + y**2 - 2, x, y, domain='QQ') + + This is equal to the product of the expressions `x + y + a_i` where the + `a_i` are the conjugates of `a`: + + >>> pa = minpoly(a) + >>> pa + _x**2 - 2 + >>> rs = roots(pa, multiple=True) + >>> rs + [sqrt(2), -sqrt(2)] + >>> n = prod(e.subs(a, r) for r in rs) + >>> n + (x + y - sqrt(2))*(x + y + sqrt(2)) + >>> expand(n) + x**2 + 2*x*y + y**2 - 2 + + Explanation + =========== + + Given an algebraic number field `K = k(a)` any element `b` of `K` can be + represented as polynomial function `b=g(a)` where `g` is in `k[x]`. If the + minimal polynomial of `a` over `k` is `p_a` then the roots `a_1`, `a_2`, + `\cdots` of `p_a(x)` are the conjugates of `a`. The norm of `b` is the + product `g(a1) \times g(a2) \times \cdots` and is an element of `k`. + + As in [Trager76]_ we extend this norm to multivariate polynomials over `K`. + If `b(x)` is a polynomial in `k(a)[X]` then we can think of `b` as being + alternately a function `g_X(a)` where `g_X` is an element of `k[X][y]` i.e. + a polynomial function with coefficients that are elements of `k[X]`. Then + the norm of `b` is the product `g_X(a1) \times g_X(a2) \times \cdots` and + will be an element of `k[X]`. + + See Also + ======== + + dmp_sqf_norm: + Compute a shift of `f` so that the `\text{Norm}(f)` is square-free. + sympy.polys.polytools.Poly.norm: + Higher-level function that calls this. + """ + if not K.is_Algebraic: + raise DomainError("ground domain must be algebraic") + + g = dmp_raise(K.mod.to_list(), u + 1, 0, K.dom) + h, _ = dmp_inject(f, u, K, front=True) + + return dmp_resultant(g, h, u + 1, K.dom) + + +def dup_gf_sqf_part(f, K): + """Compute square-free part of ``f`` in ``GF(p)[x]``. """ + f = dup_convert(f, K, K.dom) + g = gf_sqf_part(f, K.mod, K.dom) + return dup_convert(g, K.dom, K) + + +def dmp_gf_sqf_part(f, u, K): + """Compute square-free part of ``f`` in ``GF(p)[X]``. """ + raise NotImplementedError('multivariate polynomials over finite fields') + + +def dup_sqf_part(f, K): + """ + Returns square-free part of a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_sqf_part(x**3 - 3*x - 2) + x**2 - x - 2 + + See Also + ======== + + sympy.polys.polytools.Poly.sqf_part + """ + if K.is_FiniteField: + return dup_gf_sqf_part(f, K) + + if not f: + return f + + if K.is_negative(dup_LC(f, K)): + f = dup_neg(f, K) + + gcd = dup_gcd(f, dup_diff(f, 1, K), K) + sqf = dup_quo(f, gcd, K) + + if K.is_Field: + return dup_monic(sqf, K) + else: + return dup_primitive(sqf, K)[1] + + +def dmp_sqf_part(f, u, K): + """ + Returns square-free part of a polynomial in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> R.dmp_sqf_part(x**3 + 2*x**2*y + x*y**2) + x**2 + x*y + + """ + if not u: + return dup_sqf_part(f, K) + + if K.is_FiniteField: + return dmp_gf_sqf_part(f, u, K) + + if dmp_zero_p(f, u): + return f + + if K.is_negative(dmp_ground_LC(f, u, K)): + f = dmp_neg(f, u, K) + + gcd = f + for i in range(u+1): + gcd = dmp_gcd(gcd, dmp_diff_in(f, 1, i, u, K), u, K) + sqf = dmp_quo(f, gcd, u, K) + + if K.is_Field: + return dmp_ground_monic(sqf, u, K) + else: + return dmp_ground_primitive(sqf, u, K)[1] + + +def dup_gf_sqf_list(f, K, all=False): + """Compute square-free decomposition of ``f`` in ``GF(p)[x]``. """ + f_orig = f + + f = dup_convert(f, K, K.dom) + + coeff, factors = gf_sqf_list(f, K.mod, K.dom, all=all) + + for i, (f, k) in enumerate(factors): + factors[i] = (dup_convert(f, K.dom, K), k) + + _dup_check_degrees(f_orig, factors) + + return K.convert(coeff, K.dom), factors + + +def dmp_gf_sqf_list(f, u, K, all=False): + """Compute square-free decomposition of ``f`` in ``GF(p)[X]``. """ + raise NotImplementedError('multivariate polynomials over finite fields') + + +def dup_sqf_list(f, K, all=False): + """ + Return square-free decomposition of a polynomial in ``K[x]``. + + Uses Yun's algorithm from [Yun76]_. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 + + >>> R.dup_sqf_list(f) + (2, [(x + 1, 2), (x + 2, 3)]) + >>> R.dup_sqf_list(f, all=True) + (2, [(1, 1), (x + 1, 2), (x + 2, 3)]) + + See Also + ======== + + dmp_sqf_list: + Corresponding function for multivariate polynomials. + sympy.polys.polytools.sqf_list: + High-level function for square-free factorization of expressions. + sympy.polys.polytools.Poly.sqf_list: + Analogous method on :class:`~.Poly`. + + References + ========== + + [Yun76]_ + """ + if K.is_FiniteField: + return dup_gf_sqf_list(f, K, all=all) + + f_orig = f + + if K.is_Field: + coeff = dup_LC(f, K) + f = dup_monic(f, K) + else: + coeff, f = dup_primitive(f, K) + + if K.is_negative(dup_LC(f, K)): + f = dup_neg(f, K) + coeff = -coeff + + if dup_degree(f) <= 0: + return coeff, [] + + result, i = [], 1 + + h = dup_diff(f, 1, K) + g, p, q = dup_inner_gcd(f, h, K) + + while True: + d = dup_diff(p, 1, K) + h = dup_sub(q, d, K) + + if not h: + result.append((p, i)) + break + + g, p, q = dup_inner_gcd(p, h, K) + + if all or dup_degree(g) > 0: + result.append((g, i)) + + i += 1 + + _dup_check_degrees(f_orig, result) + + return coeff, result + + +def dup_sqf_list_include(f, K, all=False): + """ + Return square-free decomposition of a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 + + >>> R.dup_sqf_list_include(f) + [(2, 1), (x + 1, 2), (x + 2, 3)] + >>> R.dup_sqf_list_include(f, all=True) + [(2, 1), (x + 1, 2), (x + 2, 3)] + + """ + coeff, factors = dup_sqf_list(f, K, all=all) + + if factors and factors[0][1] == 1: + g = dup_mul_ground(factors[0][0], coeff, K) + return [(g, 1)] + factors[1:] + else: + g = dup_strip([coeff]) + return [(g, 1)] + factors + + +def dmp_sqf_list(f, u, K, all=False): + """ + Return square-free decomposition of a polynomial in `K[X]`. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x**5 + 2*x**4*y + x**3*y**2 + + >>> R.dmp_sqf_list(f) + (1, [(x + y, 2), (x, 3)]) + >>> R.dmp_sqf_list(f, all=True) + (1, [(1, 1), (x + y, 2), (x, 3)]) + + Explanation + =========== + + Uses Yun's algorithm for univariate polynomials from [Yun76]_ recursively. + The multivariate polynomial is treated as a univariate polynomial in its + leading variable. Then Yun's algorithm computes the square-free + factorization of the primitive and the content is factored recursively. + + It would be better to use a dedicated algorithm for multivariate + polynomials instead. + + See Also + ======== + + dup_sqf_list: + Corresponding function for univariate polynomials. + sympy.polys.polytools.sqf_list: + High-level function for square-free factorization of expressions. + sympy.polys.polytools.Poly.sqf_list: + Analogous method on :class:`~.Poly`. + """ + if not u: + return dup_sqf_list(f, K, all=all) + + if K.is_FiniteField: + return dmp_gf_sqf_list(f, u, K, all=all) + + f_orig = f + + if K.is_Field: + coeff = dmp_ground_LC(f, u, K) + f = dmp_ground_monic(f, u, K) + else: + coeff, f = dmp_ground_primitive(f, u, K) + + if K.is_negative(dmp_ground_LC(f, u, K)): + f = dmp_neg(f, u, K) + coeff = -coeff + + deg = dmp_degree(f, u) + if deg < 0: + return coeff, [] + + # Yun's algorithm requires the polynomial to be primitive as a univariate + # polynomial in its main variable. + content, f = dmp_primitive(f, u, K) + + result = {} + + if deg != 0: + + h = dmp_diff(f, 1, u, K) + g, p, q = dmp_inner_gcd(f, h, u, K) + + i = 1 + + while True: + d = dmp_diff(p, 1, u, K) + h = dmp_sub(q, d, u, K) + + if dmp_zero_p(h, u): + result[i] = p + break + + g, p, q = dmp_inner_gcd(p, h, u, K) + + if all or dmp_degree(g, u) > 0: + result[i] = g + + i += 1 + + coeff_content, result_content = dmp_sqf_list(content, u-1, K, all=all) + + coeff *= coeff_content + + # Combine factors of the content and primitive part that have the same + # multiplicity to produce a list in ascending order of multiplicity. + for fac, i in result_content: + fac = [fac] + if i in result: + result[i] = dmp_mul(result[i], fac, u, K) + else: + result[i] = fac + + result = [(result[i], i) for i in sorted(result)] + + _dmp_check_degrees(f_orig, u, result) + + return coeff, result + + +def dmp_sqf_list_include(f, u, K, all=False): + """ + Return square-free decomposition of a polynomial in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + >>> f = x**5 + 2*x**4*y + x**3*y**2 + + >>> R.dmp_sqf_list_include(f) + [(1, 1), (x + y, 2), (x, 3)] + >>> R.dmp_sqf_list_include(f, all=True) + [(1, 1), (x + y, 2), (x, 3)] + + """ + if not u: + return dup_sqf_list_include(f, K, all=all) + + coeff, factors = dmp_sqf_list(f, u, K, all=all) + + if factors and factors[0][1] == 1: + g = dmp_mul_ground(factors[0][0], coeff, u, K) + return [(g, 1)] + factors[1:] + else: + g = dmp_ground(coeff, u) + return [(g, 1)] + factors + + +def dup_gff_list(f, K): + """ + Compute greatest factorial factorization of ``f`` in ``K[x]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x = ring("x", ZZ) + + >>> R.dup_gff_list(x**5 + 2*x**4 - x**3 - 2*x**2) + [(x, 1), (x + 2, 4)] + + """ + if not f: + raise ValueError("greatest factorial factorization doesn't exist for a zero polynomial") + + f = dup_monic(f, K) + + if not dup_degree(f): + return [] + else: + g = dup_gcd(f, dup_shift(f, K.one, K), K) + H = dup_gff_list(g, K) + + for i, (h, k) in enumerate(H): + g = dup_mul(g, dup_shift(h, -K(k), K), K) + H[i] = (h, k + 1) + + f = dup_quo(f, g, K) + + if not dup_degree(f): + return H + else: + return [(f, 1)] + H + + +def dmp_gff_list(f, u, K): + """ + Compute greatest factorial factorization of ``f`` in ``K[X]``. + + Examples + ======== + + >>> from sympy.polys import ring, ZZ + >>> R, x,y = ring("x,y", ZZ) + + """ + if not u: + return dup_gff_list(f, K) + else: + raise MultivariatePolynomialError(f) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/subresultants_qq_zz.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/subresultants_qq_zz.py new file mode 100644 index 0000000000000000000000000000000000000000..9ce8d5c88d44022621d13d8e82956e676a7e75ae --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/polys/subresultants_qq_zz.py @@ -0,0 +1,2558 @@ +""" +This module contains functions for the computation +of Euclidean, (generalized) Sturmian, (modified) subresultant +polynomial remainder sequences (prs's) of two polynomials; +included are also three functions for the computation of the +resultant of two polynomials. + +Except for the function res_z(), which computes the resultant +of two polynomials, the pseudo-remainder function prem() +of sympy is _not_ used by any of the functions in the module. + +Instead of prem() we use the function + +rem_z(). + +Included is also the function quo_z(). + +An explanation of why we avoid prem() can be found in the +references stated in the docstring of rem_z(). + +1. Theoretical background: +========================== +Consider the polynomials f, g in Z[x] of degrees deg(f) = n and +deg(g) = m with n >= m. + +Definition 1: +============= +The sign sequence of a polynomial remainder sequence (prs) is the +sequence of signs of the leading coefficients of its polynomials. + +Sign sequences can be computed with the function: + +sign_seq(poly_seq, x) + +Definition 2: +============= +A polynomial remainder sequence (prs) is called complete if the +degree difference between any two consecutive polynomials is 1; +otherwise, it called incomplete. + +It is understood that f, g belong to the sequences mentioned in +the two definitions above. + +1A. Euclidean and subresultant prs's: +===================================== +The subresultant prs of f, g is a sequence of polynomials in Z[x] +analogous to the Euclidean prs, the sequence obtained by applying +on f, g Euclid's algorithm for polynomial greatest common divisors +(gcd) in Q[x]. + +The subresultant prs differs from the Euclidean prs in that the +coefficients of each polynomial in the former sequence are determinants +--- also referred to as subresultants --- of appropriately selected +sub-matrices of sylvester1(f, g, x), Sylvester's matrix of 1840 of +dimensions (n + m) * (n + m). + +Recall that the determinant of sylvester1(f, g, x) itself is +called the resultant of f, g and serves as a criterion of whether +the two polynomials have common roots or not. + +In SymPy the resultant is computed with the function +resultant(f, g, x). This function does _not_ evaluate the +determinant of sylvester(f, g, x, 1); instead, it returns +the last member of the subresultant prs of f, g, multiplied +(if needed) by an appropriate power of -1; see the caveat below. + +In this module we use three functions to compute the +resultant of f, g: +a) res(f, g, x) computes the resultant by evaluating +the determinant of sylvester(f, g, x, 1); +b) res_q(f, g, x) computes the resultant recursively, by +performing polynomial divisions in Q[x] with the function rem(); +c) res_z(f, g, x) computes the resultant recursively, by +performing polynomial divisions in Z[x] with the function prem(). + +Caveat: If Df = degree(f, x) and Dg = degree(g, x), then: + +resultant(f, g, x) = (-1)**(Df*Dg) * resultant(g, f, x). + +For complete prs's the sign sequence of the Euclidean prs of f, g +is identical to the sign sequence of the subresultant prs of f, g +and the coefficients of one sequence are easily computed from the +coefficients of the other. + +For incomplete prs's the polynomials in the subresultant prs, generally +differ in sign from those of the Euclidean prs, and --- unlike the +case of complete prs's --- it is not at all obvious how to compute +the coefficients of one sequence from the coefficients of the other. + +1B. Sturmian and modified subresultant prs's: +============================================= +For the same polynomials f, g in Z[x] mentioned above, their ``modified'' +subresultant prs is a sequence of polynomials similar to the Sturmian +prs, the sequence obtained by applying in Q[x] Sturm's algorithm on f, g. + +The two sequences differ in that the coefficients of each polynomial +in the modified subresultant prs are the determinants --- also referred +to as modified subresultants --- of appropriately selected sub-matrices +of sylvester2(f, g, x), Sylvester's matrix of 1853 of dimensions 2n x 2n. + +The determinant of sylvester2 itself is called the modified resultant +of f, g and it also can serve as a criterion of whether the two +polynomials have common roots or not. + +For complete prs's the sign sequence of the Sturmian prs of f, g is +identical to the sign sequence of the modified subresultant prs of +f, g and the coefficients of one sequence are easily computed from +the coefficients of the other. + +For incomplete prs's the polynomials in the modified subresultant prs, +generally differ in sign from those of the Sturmian prs, and --- unlike +the case of complete prs's --- it is not at all obvious how to compute +the coefficients of one sequence from the coefficients of the other. + +As Sylvester pointed out, the coefficients of the polynomial remainders +obtained as (modified) subresultants are the smallest possible without +introducing rationals and without computing (integer) greatest common +divisors. + +1C. On terminology: +=================== +Whence the terminology? Well generalized Sturmian prs's are +``modifications'' of Euclidean prs's; the hint came from the title +of the Pell-Gordon paper of 1917. + +In the literature one also encounters the name ``non signed'' and +``signed'' prs for Euclidean and Sturmian prs respectively. + +Likewise ``non signed'' and ``signed'' subresultant prs for +subresultant and modified subresultant prs respectively. + +2. Functions in the module: +=========================== +No function utilizes SymPy's function prem(). + +2A. Matrices: +============= +The functions sylvester(f, g, x, method=1) and +sylvester(f, g, x, method=2) compute either Sylvester matrix. +They can be used to compute (modified) subresultant prs's by +direct determinant evaluation. + +The function bezout(f, g, x, method='prs') provides a matrix of +smaller dimensions than either Sylvester matrix. It is the function +of choice for computing (modified) subresultant prs's by direct +determinant evaluation. + +sylvester(f, g, x, method=1) +sylvester(f, g, x, method=2) +bezout(f, g, x, method='prs') + +The following identity holds: + +bezout(f, g, x, method='prs') = +backward_eye(deg(f))*bezout(f, g, x, method='bz')*backward_eye(deg(f)) + +2B. Subresultant and modified subresultant prs's by +=================================================== +determinant evaluations: +======================= +We use the Sylvester matrices of 1840 and 1853 to +compute, respectively, subresultant and modified +subresultant polynomial remainder sequences. However, +for large matrices this approach takes a lot of time. + +Instead of utilizing the Sylvester matrices, we can +employ the Bezout matrix which is of smaller dimensions. + +subresultants_sylv(f, g, x) +modified_subresultants_sylv(f, g, x) +subresultants_bezout(f, g, x) +modified_subresultants_bezout(f, g, x) + +2C. Subresultant prs's by ONE determinant evaluation: +===================================================== +All three functions in this section evaluate one determinant +per remainder polynomial; this is the determinant of an +appropriately selected sub-matrix of sylvester1(f, g, x), +Sylvester's matrix of 1840. + +To compute the remainder polynomials the function +subresultants_rem(f, g, x) employs rem(f, g, x). +By contrast, the other two functions implement Van Vleck's ideas +of 1900 and compute the remainder polynomials by trinagularizing +sylvester2(f, g, x), Sylvester's matrix of 1853. + + +subresultants_rem(f, g, x) +subresultants_vv(f, g, x) +subresultants_vv_2(f, g, x). + +2E. Euclidean, Sturmian prs's in Q[x]: +====================================== +euclid_q(f, g, x) +sturm_q(f, g, x) + +2F. Euclidean, Sturmian and (modified) subresultant prs's P-G: +============================================================== +All functions in this section are based on the Pell-Gordon (P-G) +theorem of 1917. +Computations are done in Q[x], employing the function rem(f, g, x) +for the computation of the remainder polynomials. + +euclid_pg(f, g, x) +sturm pg(f, g, x) +subresultants_pg(f, g, x) +modified_subresultants_pg(f, g, x) + +2G. Euclidean, Sturmian and (modified) subresultant prs's A-M-V: +================================================================ +All functions in this section are based on the Akritas-Malaschonok- +Vigklas (A-M-V) theorem of 2015. +Computations are done in Z[x], employing the function rem_z(f, g, x) +for the computation of the remainder polynomials. + +euclid_amv(f, g, x) +sturm_amv(f, g, x) +subresultants_amv(f, g, x) +modified_subresultants_amv(f, g, x) + +2Ga. Exception: +=============== +subresultants_amv_q(f, g, x) + +This function employs rem(f, g, x) for the computation of +the remainder polynomials, despite the fact that it implements +the A-M-V Theorem. + +It is included in our module in order to show that theorems P-G +and A-M-V can be implemented utilizing either the function +rem(f, g, x) or the function rem_z(f, g, x). + +For clearly historical reasons --- since the Collins-Brown-Traub +coefficients-reduction factor beta_i was not available in 1917 --- +we have implemented the Pell-Gordon theorem with the function +rem(f, g, x) and the A-M-V Theorem with the function rem_z(f, g, x). + +2H. Resultants: +=============== +res(f, g, x) +res_q(f, g, x) +res_z(f, g, x) +""" + + +from sympy.concrete.summations import summation +from sympy.core.function import expand +from sympy.core.numbers import nan +from sympy.core.singleton import S +from sympy.core.symbol import Dummy as var +from sympy.functions.elementary.complexes import Abs, sign +from sympy.functions.elementary.integers import floor +from sympy.matrices.dense import eye, Matrix, zeros +from sympy.printing.pretty.pretty import pretty_print as pprint +from sympy.simplify.simplify import simplify +from sympy.polys.domains import QQ +from sympy.polys.polytools import degree, LC, Poly, pquo, quo, prem, rem +from sympy.polys.polyerrors import PolynomialError + + +def sylvester(f, g, x, method = 1): + ''' + The input polynomials f, g are in Z[x] or in Q[x]. Let m = degree(f, x), + n = degree(g, x) and mx = max(m, n). + + a. If method = 1 (default), computes sylvester1, Sylvester's matrix of 1840 + of dimension (m + n) x (m + n). The determinants of properly chosen + submatrices of this matrix (a.k.a. subresultants) can be + used to compute the coefficients of the Euclidean PRS of f, g. + + b. If method = 2, computes sylvester2, Sylvester's matrix of 1853 + of dimension (2*mx) x (2*mx). The determinants of properly chosen + submatrices of this matrix (a.k.a. ``modified'' subresultants) can be + used to compute the coefficients of the Sturmian PRS of f, g. + + Applications of these Matrices can be found in the references below. + Especially, for applications of sylvester2, see the first reference!! + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``On a Theorem + by Van Vleck Regarding Sturm Sequences. Serdica Journal of Computing, + Vol. 7, No 4, 101-134, 2013. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Sturm Sequences + and Modified Subresultant Polynomial Remainder Sequences.'' + Serdica Journal of Computing, Vol. 8, No 1, 29-46, 2014. + + ''' + # obtain degrees of polys + m, n = degree( Poly(f, x), x), degree( Poly(g, x), x) + + # Special cases: + # A:: case m = n < 0 (i.e. both polys are 0) + if m == n and n < 0: + return Matrix([]) + + # B:: case m = n = 0 (i.e. both polys are constants) + if m == n and n == 0: + return Matrix([]) + + # C:: m == 0 and n < 0 or m < 0 and n == 0 + # (i.e. one poly is constant and the other is 0) + if m == 0 and n < 0: + return Matrix([]) + elif m < 0 and n == 0: + return Matrix([]) + + # D:: m >= 1 and n < 0 or m < 0 and n >=1 + # (i.e. one poly is of degree >=1 and the other is 0) + if m >= 1 and n < 0: + return Matrix([0]) + elif m < 0 and n >= 1: + return Matrix([0]) + + fp = Poly(f, x).all_coeffs() + gp = Poly(g, x).all_coeffs() + + # Sylvester's matrix of 1840 (default; a.k.a. sylvester1) + if method <= 1: + M = zeros(m + n) + k = 0 + for i in range(n): + j = k + for coeff in fp: + M[i, j] = coeff + j = j + 1 + k = k + 1 + k = 0 + for i in range(n, m + n): + j = k + for coeff in gp: + M[i, j] = coeff + j = j + 1 + k = k + 1 + return M + + # Sylvester's matrix of 1853 (a.k.a sylvester2) + else: + if len(fp) < len(gp): + h = [] + for i in range(len(gp) - len(fp)): + h.append(0) + fp[ : 0] = h + else: + h = [] + for i in range(len(fp) - len(gp)): + h.append(0) + gp[ : 0] = h + mx = max(m, n) + dim = 2*mx + M = zeros( dim ) + k = 0 + for i in range( mx ): + j = k + for coeff in fp: + M[2*i, j] = coeff + j = j + 1 + j = k + for coeff in gp: + M[2*i + 1, j] = coeff + j = j + 1 + k = k + 1 + return M + +def process_matrix_output(poly_seq, x): + """ + poly_seq is a polynomial remainder sequence computed either by + (modified_)subresultants_bezout or by (modified_)subresultants_sylv. + + This function removes from poly_seq all zero polynomials as well + as all those whose degree is equal to the degree of a preceding + polynomial in poly_seq, as we scan it from left to right. + + """ + L = poly_seq[:] # get a copy of the input sequence + d = degree(L[1], x) + i = 2 + while i < len(L): + d_i = degree(L[i], x) + if d_i < 0: # zero poly + L.remove(L[i]) + i = i - 1 + if d == d_i: # poly degree equals degree of previous poly + L.remove(L[i]) + i = i - 1 + if d_i >= 0: + d = d_i + i = i + 1 + + return L + +def subresultants_sylv(f, g, x): + """ + The input polynomials f, g are in Z[x] or in Q[x]. It is assumed + that deg(f) >= deg(g). + + Computes the subresultant polynomial remainder sequence (prs) + of f, g by evaluating determinants of appropriately selected + submatrices of sylvester(f, g, x, 1). The dimensions of the + latter are (deg(f) + deg(g)) x (deg(f) + deg(g)). + + Each coefficient is computed by evaluating the determinant of the + corresponding submatrix of sylvester(f, g, x, 1). + + If the subresultant prs is complete, then the output coincides + with the Euclidean sequence of the polynomials f, g. + + References: + =========== + 1. G.M.Diaz-Toca,L.Gonzalez-Vega: Various New Expressions for Subresultants + and Their Applications. Appl. Algebra in Engin., Communic. and Comp., + Vol. 15, 233-266, 2004. + + """ + + # make sure neither f nor g is 0 + if f == 0 or g == 0: + return [f, g] + + n = degF = degree(f, x) + m = degG = degree(g, x) + + # make sure proper degrees + if n == 0 and m == 0: + return [f, g] + if n < m: + n, m, degF, degG, f, g = m, n, degG, degF, g, f + if n > 0 and m == 0: + return [f, g] + + SR_L = [f, g] # subresultant list + + # form matrix sylvester(f, g, x, 1) + S = sylvester(f, g, x, 1) + + # pick appropriate submatrices of S + # and form subresultant polys + j = m - 1 + + while j > 0: + Sp = S[:, :] # copy of S + # delete last j rows of coeffs of g + for ind in range(m + n - j, m + n): + Sp.row_del(m + n - j) + # delete last j rows of coeffs of f + for ind in range(m - j, m): + Sp.row_del(m - j) + + # evaluate determinants and form coefficients list + coeff_L, k, l = [], Sp.rows, 0 + while l <= j: + coeff_L.append(Sp[:, 0:k].det()) + Sp.col_swap(k - 1, k + l) + l += 1 + + # form poly and append to SP_L + SR_L.append(Poly(coeff_L, x).as_expr()) + j -= 1 + + # j = 0 + SR_L.append(S.det()) + + return process_matrix_output(SR_L, x) + +def modified_subresultants_sylv(f, g, x): + """ + The input polynomials f, g are in Z[x] or in Q[x]. It is assumed + that deg(f) >= deg(g). + + Computes the modified subresultant polynomial remainder sequence (prs) + of f, g by evaluating determinants of appropriately selected + submatrices of sylvester(f, g, x, 2). The dimensions of the + latter are (2*deg(f)) x (2*deg(f)). + + Each coefficient is computed by evaluating the determinant of the + corresponding submatrix of sylvester(f, g, x, 2). + + If the modified subresultant prs is complete, then the output coincides + with the Sturmian sequence of the polynomials f, g. + + References: + =========== + 1. A. G. Akritas,G.I. Malaschonok and P.S. Vigklas: + Sturm Sequences and Modified Subresultant Polynomial Remainder + Sequences. Serdica Journal of Computing, Vol. 8, No 1, 29--46, 2014. + + """ + + # make sure neither f nor g is 0 + if f == 0 or g == 0: + return [f, g] + + n = degF = degree(f, x) + m = degG = degree(g, x) + + # make sure proper degrees + if n == 0 and m == 0: + return [f, g] + if n < m: + n, m, degF, degG, f, g = m, n, degG, degF, g, f + if n > 0 and m == 0: + return [f, g] + + SR_L = [f, g] # modified subresultant list + + # form matrix sylvester(f, g, x, 2) + S = sylvester(f, g, x, 2) + + # pick appropriate submatrices of S + # and form modified subresultant polys + j = m - 1 + + while j > 0: + # delete last 2*j rows of pairs of coeffs of f, g + Sp = S[0:2*n - 2*j, :] # copy of first 2*n - 2*j rows of S + + # evaluate determinants and form coefficients list + coeff_L, k, l = [], Sp.rows, 0 + while l <= j: + coeff_L.append(Sp[:, 0:k].det()) + Sp.col_swap(k - 1, k + l) + l += 1 + + # form poly and append to SP_L + SR_L.append(Poly(coeff_L, x).as_expr()) + j -= 1 + + # j = 0 + SR_L.append(S.det()) + + return process_matrix_output(SR_L, x) + +def res(f, g, x): + """ + The input polynomials f, g are in Z[x] or in Q[x]. + + The output is the resultant of f, g computed by evaluating + the determinant of the matrix sylvester(f, g, x, 1). + + References: + =========== + 1. J. S. Cohen: Computer Algebra and Symbolic Computation + - Mathematical Methods. A. K. Peters, 2003. + + """ + if f == 0 or g == 0: + raise PolynomialError("The resultant of %s and %s is not defined" % (f, g)) + else: + return sylvester(f, g, x, 1).det() + +def res_q(f, g, x): + """ + The input polynomials f, g are in Z[x] or in Q[x]. + + The output is the resultant of f, g computed recursively + by polynomial divisions in Q[x], using the function rem. + See Cohen's book p. 281. + + References: + =========== + 1. J. S. Cohen: Computer Algebra and Symbolic Computation + - Mathematical Methods. A. K. Peters, 2003. + """ + m = degree(f, x) + n = degree(g, x) + if m < n: + return (-1)**(m*n) * res_q(g, f, x) + elif n == 0: # g is a constant + return g**m + else: + r = rem(f, g, x) + if r == 0: + return 0 + else: + s = degree(r, x) + l = LC(g, x) + return (-1)**(m*n) * l**(m-s)*res_q(g, r, x) + +def res_z(f, g, x): + """ + The input polynomials f, g are in Z[x] or in Q[x]. + + The output is the resultant of f, g computed recursively + by polynomial divisions in Z[x], using the function prem(). + See Cohen's book p. 283. + + References: + =========== + 1. J. S. Cohen: Computer Algebra and Symbolic Computation + - Mathematical Methods. A. K. Peters, 2003. + """ + m = degree(f, x) + n = degree(g, x) + if m < n: + return (-1)**(m*n) * res_z(g, f, x) + elif n == 0: # g is a constant + return g**m + else: + r = prem(f, g, x) + if r == 0: + return 0 + else: + delta = m - n + 1 + w = (-1)**(m*n) * res_z(g, r, x) + s = degree(r, x) + l = LC(g, x) + k = delta * n - m + s + return quo(w, l**k, x) + +def sign_seq(poly_seq, x): + """ + Given a sequence of polynomials poly_seq, it returns + the sequence of signs of the leading coefficients of + the polynomials in poly_seq. + + """ + return [sign(LC(poly_seq[i], x)) for i in range(len(poly_seq))] + +def bezout(p, q, x, method='bz'): + """ + The input polynomials p, q are in Z[x] or in Q[x]. Let + mx = max(degree(p, x), degree(q, x)). + + The default option bezout(p, q, x, method='bz') returns Bezout's + symmetric matrix of p and q, of dimensions (mx) x (mx). The + determinant of this matrix is equal to the determinant of sylvester2, + Sylvester's matrix of 1853, whose dimensions are (2*mx) x (2*mx); + however the subresultants of these two matrices may differ. + + The other option, bezout(p, q, x, 'prs'), is of interest to us + in this module because it returns a matrix equivalent to sylvester2. + In this case all subresultants of the two matrices are identical. + + Both the subresultant polynomial remainder sequence (prs) and + the modified subresultant prs of p and q can be computed by + evaluating determinants of appropriately selected submatrices of + bezout(p, q, x, 'prs') --- one determinant per coefficient of the + remainder polynomials. + + The matrices bezout(p, q, x, 'bz') and bezout(p, q, x, 'prs') + are related by the formula + + bezout(p, q, x, 'prs') = + backward_eye(deg(p)) * bezout(p, q, x, 'bz') * backward_eye(deg(p)), + + where backward_eye() is the backward identity function. + + References + ========== + 1. G.M.Diaz-Toca,L.Gonzalez-Vega: Various New Expressions for Subresultants + and Their Applications. Appl. Algebra in Engin., Communic. and Comp., + Vol. 15, 233-266, 2004. + + """ + # obtain degrees of polys + m, n = degree( Poly(p, x), x), degree( Poly(q, x), x) + + # Special cases: + # A:: case m = n < 0 (i.e. both polys are 0) + if m == n and n < 0: + return Matrix([]) + + # B:: case m = n = 0 (i.e. both polys are constants) + if m == n and n == 0: + return Matrix([]) + + # C:: m == 0 and n < 0 or m < 0 and n == 0 + # (i.e. one poly is constant and the other is 0) + if m == 0 and n < 0: + return Matrix([]) + elif m < 0 and n == 0: + return Matrix([]) + + # D:: m >= 1 and n < 0 or m < 0 and n >=1 + # (i.e. one poly is of degree >=1 and the other is 0) + if m >= 1 and n < 0: + return Matrix([0]) + elif m < 0 and n >= 1: + return Matrix([0]) + + y = var('y') + + # expr is 0 when x = y + expr = p * q.subs({x:y}) - p.subs({x:y}) * q + + # hence expr is exactly divisible by x - y + poly = Poly( quo(expr, x-y), x, y) + + # form Bezout matrix and store them in B as indicated to get + # the LC coefficient of each poly either in the first position + # of each row (method='prs') or in the last (method='bz'). + mx = max(m, n) + B = zeros(mx) + for i in range(mx): + for j in range(mx): + if method == 'prs': + B[mx - 1 - i, mx - 1 - j] = poly.nth(i, j) + else: + B[i, j] = poly.nth(i, j) + return B + +def backward_eye(n): + ''' + Returns the backward identity matrix of dimensions n x n. + + Needed to "turn" the Bezout matrices + so that the leading coefficients are first. + See docstring of the function bezout(p, q, x, method='bz'). + ''' + M = eye(n) # identity matrix of order n + + for i in range(int(M.rows / 2)): + M.row_swap(0 + i, M.rows - 1 - i) + + return M + +def subresultants_bezout(p, q, x): + """ + The input polynomials p, q are in Z[x] or in Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the subresultant polynomial remainder sequence + of p, q by evaluating determinants of appropriately selected + submatrices of bezout(p, q, x, 'prs'). The dimensions of the + latter are deg(p) x deg(p). + + Each coefficient is computed by evaluating the determinant of the + corresponding submatrix of bezout(p, q, x, 'prs'). + + bezout(p, q, x, 'prs) is used instead of sylvester(p, q, x, 1), + Sylvester's matrix of 1840, because the dimensions of the latter + are (deg(p) + deg(q)) x (deg(p) + deg(q)). + + If the subresultant prs is complete, then the output coincides + with the Euclidean sequence of the polynomials p, q. + + References + ========== + 1. G.M.Diaz-Toca,L.Gonzalez-Vega: Various New Expressions for Subresultants + and Their Applications. Appl. Algebra in Engin., Communic. and Comp., + Vol. 15, 233-266, 2004. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + f, g = p, q + n = degF = degree(f, x) + m = degG = degree(g, x) + + # make sure proper degrees + if n == 0 and m == 0: + return [f, g] + if n < m: + n, m, degF, degG, f, g = m, n, degG, degF, g, f + if n > 0 and m == 0: + return [f, g] + + SR_L = [f, g] # subresultant list + F = LC(f, x)**(degF - degG) + + # form the bezout matrix + B = bezout(f, g, x, 'prs') + + # pick appropriate submatrices of B + # and form subresultant polys + if degF > degG: + j = 2 + if degF == degG: + j = 1 + while j <= degF: + M = B[0:j, :] + k, coeff_L = j - 1, [] + while k <= degF - 1: + coeff_L.append(M[:, 0:j].det()) + if k < degF - 1: + M.col_swap(j - 1, k + 1) + k = k + 1 + + # apply Theorem 2.1 in the paper by Toca & Vega 2004 + # to get correct signs + SR_L.append(int((-1)**(j*(j-1)/2)) * (Poly(coeff_L, x) / F).as_expr()) + j = j + 1 + + return process_matrix_output(SR_L, x) + +def modified_subresultants_bezout(p, q, x): + """ + The input polynomials p, q are in Z[x] or in Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the modified subresultant polynomial remainder sequence + of p, q by evaluating determinants of appropriately selected + submatrices of bezout(p, q, x, 'prs'). The dimensions of the + latter are deg(p) x deg(p). + + Each coefficient is computed by evaluating the determinant of the + corresponding submatrix of bezout(p, q, x, 'prs'). + + bezout(p, q, x, 'prs') is used instead of sylvester(p, q, x, 2), + Sylvester's matrix of 1853, because the dimensions of the latter + are 2*deg(p) x 2*deg(p). + + If the modified subresultant prs is complete, and LC( p ) > 0, the output + coincides with the (generalized) Sturm's sequence of the polynomials p, q. + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Sturm Sequences + and Modified Subresultant Polynomial Remainder Sequences.'' + Serdica Journal of Computing, Vol. 8, No 1, 29-46, 2014. + + 2. G.M.Diaz-Toca,L.Gonzalez-Vega: Various New Expressions for Subresultants + and Their Applications. Appl. Algebra in Engin., Communic. and Comp., + Vol. 15, 233-266, 2004. + + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + f, g = p, q + n = degF = degree(f, x) + m = degG = degree(g, x) + + # make sure proper degrees + if n == 0 and m == 0: + return [f, g] + if n < m: + n, m, degF, degG, f, g = m, n, degG, degF, g, f + if n > 0 and m == 0: + return [f, g] + + SR_L = [f, g] # subresultant list + + # form the bezout matrix + B = bezout(f, g, x, 'prs') + + # pick appropriate submatrices of B + # and form subresultant polys + if degF > degG: + j = 2 + if degF == degG: + j = 1 + while j <= degF: + M = B[0:j, :] + k, coeff_L = j - 1, [] + while k <= degF - 1: + coeff_L.append(M[:, 0:j].det()) + if k < degF - 1: + M.col_swap(j - 1, k + 1) + k = k + 1 + + ## Theorem 2.1 in the paper by Toca & Vega 2004 is _not needed_ + ## in this case since + ## the bezout matrix is equivalent to sylvester2 + SR_L.append(( Poly(coeff_L, x)).as_expr()) + j = j + 1 + + return process_matrix_output(SR_L, x) + +def sturm_pg(p, q, x, method=0): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the (generalized) Sturm sequence of p and q in Z[x] or Q[x]. + If q = diff(p, x, 1) it is the usual Sturm sequence. + + A. If method == 0, default, the remainder coefficients of the sequence + are (in absolute value) ``modified'' subresultants, which for non-monic + polynomials are greater than the coefficients of the corresponding + subresultants by the factor Abs(LC(p)**( deg(p)- deg(q))). + + B. If method == 1, the remainder coefficients of the sequence are (in + absolute value) subresultants, which for non-monic polynomials are + smaller than the coefficients of the corresponding ``modified'' + subresultants by the factor Abs(LC(p)**( deg(p)- deg(q))). + + If the Sturm sequence is complete, method=0 and LC( p ) > 0, the coefficients + of the polynomials in the sequence are ``modified'' subresultants. + That is, they are determinants of appropriately selected submatrices of + sylvester2, Sylvester's matrix of 1853. In this case the Sturm sequence + coincides with the ``modified'' subresultant prs, of the polynomials + p, q. + + If the Sturm sequence is incomplete and method=0 then the signs of the + coefficients of the polynomials in the sequence may differ from the signs + of the coefficients of the corresponding polynomials in the ``modified'' + subresultant prs; however, the absolute values are the same. + + To compute the coefficients, no determinant evaluation takes place. Instead, + polynomial divisions in Q[x] are performed, using the function rem(p, q, x); + the coefficients of the remainders computed this way become (``modified'') + subresultants with the help of the Pell-Gordon Theorem of 1917. + See also the function euclid_pg(p, q, x). + + References + ========== + 1. Pell A. J., R. L. Gordon. The Modified Remainders Obtained in Finding + the Highest Common Factor of Two Polynomials. Annals of MatheMatics, + Second Series, 18 (1917), No. 4, 188-193. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Sturm Sequences + and Modified Subresultant Polynomial Remainder Sequences.'' + Serdica Journal of Computing, Vol. 8, No 1, 29-46, 2014. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + d0 = degree(p, x) + d1 = degree(q, x) + if d0 == 0 and d1 == 0: + return [p, q] + if d1 > d0: + d0, d1 = d1, d0 + p, q = q, p + if d0 > 0 and d1 == 0: + return [p,q] + + # make sure LC(p) > 0 + flag = 0 + if LC(p,x) < 0: + flag = 1 + p = -p + q = -q + + # initialize + lcf = LC(p, x)**(d0 - d1) # lcf * subr = modified subr + a0, a1 = p, q # the input polys + sturm_seq = [a0, a1] # the output list + del0 = d0 - d1 # degree difference + rho1 = LC(a1, x) # leading coeff of a1 + exp_deg = d1 - 1 # expected degree of a2 + a2 = - rem(a0, a1, domain=QQ) # first remainder + rho2 = LC(a2,x) # leading coeff of a2 + d2 = degree(a2, x) # actual degree of a2 + deg_diff_new = exp_deg - d2 # expected - actual degree + del1 = d1 - d2 # degree difference + + # mul_fac is the factor by which a2 is multiplied to + # get integer coefficients + mul_fac_old = rho1**(del0 + del1 - deg_diff_new) + + # append accordingly + if method == 0: + sturm_seq.append( simplify(lcf * a2 * Abs(mul_fac_old))) + else: + sturm_seq.append( simplify( a2 * Abs(mul_fac_old))) + + # main loop + deg_diff_old = deg_diff_new + while d2 > 0: + a0, a1, d0, d1 = a1, a2, d1, d2 # update polys and degrees + del0 = del1 # update degree difference + exp_deg = d1 - 1 # new expected degree + a2 = - rem(a0, a1, domain=QQ) # new remainder + rho3 = LC(a2, x) # leading coeff of a2 + d2 = degree(a2, x) # actual degree of a2 + deg_diff_new = exp_deg - d2 # expected - actual degree + del1 = d1 - d2 # degree difference + + # take into consideration the power + # rho1**deg_diff_old that was "left out" + expo_old = deg_diff_old # rho1 raised to this power + expo_new = del0 + del1 - deg_diff_new # rho2 raised to this power + + # update variables and append + mul_fac_new = rho2**(expo_new) * rho1**(expo_old) * mul_fac_old + deg_diff_old, mul_fac_old = deg_diff_new, mul_fac_new + rho1, rho2 = rho2, rho3 + if method == 0: + sturm_seq.append( simplify(lcf * a2 * Abs(mul_fac_old))) + else: + sturm_seq.append( simplify( a2 * Abs(mul_fac_old))) + + if flag: # change the sign of the sequence + sturm_seq = [-i for i in sturm_seq] + + # gcd is of degree > 0 ? + m = len(sturm_seq) + if sturm_seq[m - 1] == nan or sturm_seq[m - 1] == 0: + sturm_seq.pop(m - 1) + + return sturm_seq + +def sturm_q(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the (generalized) Sturm sequence of p and q in Q[x]. + Polynomial divisions in Q[x] are performed, using the function rem(p, q, x). + + The coefficients of the polynomials in the Sturm sequence can be uniquely + determined from the corresponding coefficients of the polynomials found + either in: + + (a) the ``modified'' subresultant prs, (references 1, 2) + + or in + + (b) the subresultant prs (reference 3). + + References + ========== + 1. Pell A. J., R. L. Gordon. The Modified Remainders Obtained in Finding + the Highest Common Factor of Two Polynomials. Annals of MatheMatics, + Second Series, 18 (1917), No. 4, 188-193. + + 2 Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Sturm Sequences + and Modified Subresultant Polynomial Remainder Sequences.'' + Serdica Journal of Computing, Vol. 8, No 1, 29-46, 2014. + + 3. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result + on the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + d0 = degree(p, x) + d1 = degree(q, x) + if d0 == 0 and d1 == 0: + return [p, q] + if d1 > d0: + d0, d1 = d1, d0 + p, q = q, p + if d0 > 0 and d1 == 0: + return [p,q] + + # make sure LC(p) > 0 + flag = 0 + if LC(p,x) < 0: + flag = 1 + p = -p + q = -q + + # initialize + a0, a1 = p, q # the input polys + sturm_seq = [a0, a1] # the output list + a2 = -rem(a0, a1, domain=QQ) # first remainder + d2 = degree(a2, x) # degree of a2 + sturm_seq.append( a2 ) + + # main loop + while d2 > 0: + a0, a1, d0, d1 = a1, a2, d1, d2 # update polys and degrees + a2 = -rem(a0, a1, domain=QQ) # new remainder + d2 = degree(a2, x) # actual degree of a2 + sturm_seq.append( a2 ) + + if flag: # change the sign of the sequence + sturm_seq = [-i for i in sturm_seq] + + # gcd is of degree > 0 ? + m = len(sturm_seq) + if sturm_seq[m - 1] == nan or sturm_seq[m - 1] == 0: + sturm_seq.pop(m - 1) + + return sturm_seq + +def sturm_amv(p, q, x, method=0): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the (generalized) Sturm sequence of p and q in Z[x] or Q[x]. + If q = diff(p, x, 1) it is the usual Sturm sequence. + + A. If method == 0, default, the remainder coefficients of the + sequence are (in absolute value) ``modified'' subresultants, which + for non-monic polynomials are greater than the coefficients of the + corresponding subresultants by the factor Abs(LC(p)**( deg(p)- deg(q))). + + B. If method == 1, the remainder coefficients of the sequence are (in + absolute value) subresultants, which for non-monic polynomials are + smaller than the coefficients of the corresponding ``modified'' + subresultants by the factor Abs( LC(p)**( deg(p)- deg(q)) ). + + If the Sturm sequence is complete, method=0 and LC( p ) > 0, then the + coefficients of the polynomials in the sequence are ``modified'' subresultants. + That is, they are determinants of appropriately selected submatrices of + sylvester2, Sylvester's matrix of 1853. In this case the Sturm sequence + coincides with the ``modified'' subresultant prs, of the polynomials + p, q. + + If the Sturm sequence is incomplete and method=0 then the signs of the + coefficients of the polynomials in the sequence may differ from the signs + of the coefficients of the corresponding polynomials in the ``modified'' + subresultant prs; however, the absolute values are the same. + + To compute the coefficients, no determinant evaluation takes place. + Instead, we first compute the euclidean sequence of p and q using + euclid_amv(p, q, x) and then: (a) change the signs of the remainders in the + Euclidean sequence according to the pattern "-, -, +, +, -, -, +, +,..." + (see Lemma 1 in the 1st reference or Theorem 3 in the 2nd reference) + and (b) if method=0, assuming deg(p) > deg(q), we multiply the remainder + coefficients of the Euclidean sequence times the factor + Abs( LC(p)**( deg(p)- deg(q)) ) to make them modified subresultants. + See also the function sturm_pg(p, q, x). + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result + on the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``On the Remainders + Obtained in Finding the Greatest Common Divisor of Two Polynomials.'' Serdica + Journal of Computing 9(2) (2015), 123-138. + + 3. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Subresultant Polynomial + Remainder Sequences Obtained by Polynomial Divisions in Q[x] or in Z[x].'' + Serdica Journal of Computing 10 (2016), No.3-4, 197-217. + + """ + # compute the euclidean sequence + prs = euclid_amv(p, q, x) + + # defensive + if prs == [] or len(prs) == 2: + return prs + + # the coefficients in prs are subresultants and hence are smaller + # than the corresponding subresultants by the factor + # Abs( LC(prs[0])**( deg(prs[0]) - deg(prs[1])) ); Theorem 2, 2nd reference. + lcf = Abs( LC(prs[0])**( degree(prs[0], x) - degree(prs[1], x) ) ) + + # the signs of the first two polys in the sequence stay the same + sturm_seq = [prs[0], prs[1]] + + # change the signs according to "-, -, +, +, -, -, +, +,..." + # and multiply times lcf if needed + flag = 0 + m = len(prs) + i = 2 + while i <= m-1: + if flag == 0: + sturm_seq.append( - prs[i] ) + i = i + 1 + if i == m: + break + sturm_seq.append( - prs[i] ) + i = i + 1 + flag = 1 + elif flag == 1: + sturm_seq.append( prs[i] ) + i = i + 1 + if i == m: + break + sturm_seq.append( prs[i] ) + i = i + 1 + flag = 0 + + # subresultants or modified subresultants? + if method == 0 and lcf > 1: + aux_seq = [sturm_seq[0], sturm_seq[1]] + for i in range(2, m): + aux_seq.append(simplify(sturm_seq[i] * lcf )) + sturm_seq = aux_seq + + return sturm_seq + +def euclid_pg(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the Euclidean sequence of p and q in Z[x] or Q[x]. + + If the Euclidean sequence is complete the coefficients of the polynomials + in the sequence are subresultants. That is, they are determinants of + appropriately selected submatrices of sylvester1, Sylvester's matrix of 1840. + In this case the Euclidean sequence coincides with the subresultant prs + of the polynomials p, q. + + If the Euclidean sequence is incomplete the signs of the coefficients of the + polynomials in the sequence may differ from the signs of the coefficients of + the corresponding polynomials in the subresultant prs; however, the absolute + values are the same. + + To compute the Euclidean sequence, no determinant evaluation takes place. + We first compute the (generalized) Sturm sequence of p and q using + sturm_pg(p, q, x, 1), in which case the coefficients are (in absolute value) + equal to subresultants. Then we change the signs of the remainders in the + Sturm sequence according to the pattern "-, -, +, +, -, -, +, +,..." ; + see Lemma 1 in the 1st reference or Theorem 3 in the 2nd reference as well as + the function sturm_pg(p, q, x). + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result + on the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``On the Remainders + Obtained in Finding the Greatest Common Divisor of Two Polynomials.'' Serdica + Journal of Computing 9(2) (2015), 123-138. + + 3. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Subresultant Polynomial + Remainder Sequences Obtained by Polynomial Divisions in Q[x] or in Z[x].'' + Serdica Journal of Computing 10 (2016), No.3-4, 197-217. + """ + # compute the sturmian sequence using the Pell-Gordon (or AMV) theorem + # with the coefficients in the prs being (in absolute value) subresultants + prs = sturm_pg(p, q, x, 1) ## any other method would do + + # defensive + if prs == [] or len(prs) == 2: + return prs + + # the signs of the first two polys in the sequence stay the same + euclid_seq = [prs[0], prs[1]] + + # change the signs according to "-, -, +, +, -, -, +, +,..." + flag = 0 + m = len(prs) + i = 2 + while i <= m-1: + if flag == 0: + euclid_seq.append(- prs[i] ) + i = i + 1 + if i == m: + break + euclid_seq.append(- prs[i] ) + i = i + 1 + flag = 1 + elif flag == 1: + euclid_seq.append(prs[i] ) + i = i + 1 + if i == m: + break + euclid_seq.append(prs[i] ) + i = i + 1 + flag = 0 + + return euclid_seq + +def euclid_q(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the Euclidean sequence of p and q in Q[x]. + Polynomial divisions in Q[x] are performed, using the function rem(p, q, x). + + The coefficients of the polynomials in the Euclidean sequence can be uniquely + determined from the corresponding coefficients of the polynomials found + either in: + + (a) the ``modified'' subresultant polynomial remainder sequence, + (references 1, 2) + + or in + + (b) the subresultant polynomial remainder sequence (references 3). + + References + ========== + 1. Pell A. J., R. L. Gordon. The Modified Remainders Obtained in Finding + the Highest Common Factor of Two Polynomials. Annals of MatheMatics, + Second Series, 18 (1917), No. 4, 188-193. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Sturm Sequences + and Modified Subresultant Polynomial Remainder Sequences.'' + Serdica Journal of Computing, Vol. 8, No 1, 29-46, 2014. + + 3. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result + on the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + d0 = degree(p, x) + d1 = degree(q, x) + if d0 == 0 and d1 == 0: + return [p, q] + if d1 > d0: + d0, d1 = d1, d0 + p, q = q, p + if d0 > 0 and d1 == 0: + return [p,q] + + # make sure LC(p) > 0 + flag = 0 + if LC(p,x) < 0: + flag = 1 + p = -p + q = -q + + # initialize + a0, a1 = p, q # the input polys + euclid_seq = [a0, a1] # the output list + a2 = rem(a0, a1, domain=QQ) # first remainder + d2 = degree(a2, x) # degree of a2 + euclid_seq.append( a2 ) + + # main loop + while d2 > 0: + a0, a1, d0, d1 = a1, a2, d1, d2 # update polys and degrees + a2 = rem(a0, a1, domain=QQ) # new remainder + d2 = degree(a2, x) # actual degree of a2 + euclid_seq.append( a2 ) + + if flag: # change the sign of the sequence + euclid_seq = [-i for i in euclid_seq] + + # gcd is of degree > 0 ? + m = len(euclid_seq) + if euclid_seq[m - 1] == nan or euclid_seq[m - 1] == 0: + euclid_seq.pop(m - 1) + + return euclid_seq + +def euclid_amv(f, g, x): + """ + f, g are polynomials in Z[x] or Q[x]. It is assumed + that degree(f, x) >= degree(g, x). + + Computes the Euclidean sequence of p and q in Z[x] or Q[x]. + + If the Euclidean sequence is complete the coefficients of the polynomials + in the sequence are subresultants. That is, they are determinants of + appropriately selected submatrices of sylvester1, Sylvester's matrix of 1840. + In this case the Euclidean sequence coincides with the subresultant prs, + of the polynomials p, q. + + If the Euclidean sequence is incomplete the signs of the coefficients of the + polynomials in the sequence may differ from the signs of the coefficients of + the corresponding polynomials in the subresultant prs; however, the absolute + values are the same. + + To compute the coefficients, no determinant evaluation takes place. + Instead, polynomial divisions in Z[x] or Q[x] are performed, using + the function rem_z(f, g, x); the coefficients of the remainders + computed this way become subresultants with the help of the + Collins-Brown-Traub formula for coefficient reduction. + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result + on the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Subresultant Polynomial + remainder Sequences Obtained by Polynomial Divisions in Q[x] or in Z[x].'' + Serdica Journal of Computing 10 (2016), No.3-4, 197-217. + + """ + # make sure neither f nor g is 0 + if f == 0 or g == 0: + return [f, g] + + # make sure proper degrees + d0 = degree(f, x) + d1 = degree(g, x) + if d0 == 0 and d1 == 0: + return [f, g] + if d1 > d0: + d0, d1 = d1, d0 + f, g = g, f + if d0 > 0 and d1 == 0: + return [f, g] + + # initialize + a0 = f + a1 = g + euclid_seq = [a0, a1] + deg_dif_p1, c = degree(a0, x) - degree(a1, x) + 1, -1 + + # compute the first polynomial of the prs + i = 1 + a2 = rem_z(a0, a1, x) / Abs( (-1)**deg_dif_p1 ) # first remainder + euclid_seq.append( a2 ) + d2 = degree(a2, x) # actual degree of a2 + + # main loop + while d2 >= 1: + a0, a1, d0, d1 = a1, a2, d1, d2 # update polys and degrees + i += 1 + sigma0 = -LC(a0) + c = (sigma0**(deg_dif_p1 - 1)) / (c**(deg_dif_p1 - 2)) + deg_dif_p1 = degree(a0, x) - d2 + 1 + a2 = rem_z(a0, a1, x) / Abs( (c**(deg_dif_p1 - 1)) * sigma0 ) + euclid_seq.append( a2 ) + d2 = degree(a2, x) # actual degree of a2 + + # gcd is of degree > 0 ? + m = len(euclid_seq) + if euclid_seq[m - 1] == nan or euclid_seq[m - 1] == 0: + euclid_seq.pop(m - 1) + + return euclid_seq + +def modified_subresultants_pg(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the ``modified'' subresultant prs of p and q in Z[x] or Q[x]; + the coefficients of the polynomials in the sequence are + ``modified'' subresultants. That is, they are determinants of appropriately + selected submatrices of sylvester2, Sylvester's matrix of 1853. + + To compute the coefficients, no determinant evaluation takes place. Instead, + polynomial divisions in Q[x] are performed, using the function rem(p, q, x); + the coefficients of the remainders computed this way become ``modified'' + subresultants with the help of the Pell-Gordon Theorem of 1917. + + If the ``modified'' subresultant prs is complete, and LC( p ) > 0, it coincides + with the (generalized) Sturm sequence of the polynomials p, q. + + References + ========== + 1. Pell A. J., R. L. Gordon. The Modified Remainders Obtained in Finding + the Highest Common Factor of Two Polynomials. Annals of MatheMatics, + Second Series, 18 (1917), No. 4, 188-193. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Sturm Sequences + and Modified Subresultant Polynomial Remainder Sequences.'' + Serdica Journal of Computing, Vol. 8, No 1, 29-46, 2014. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + d0 = degree(p,x) + d1 = degree(q,x) + if d0 == 0 and d1 == 0: + return [p, q] + if d1 > d0: + d0, d1 = d1, d0 + p, q = q, p + if d0 > 0 and d1 == 0: + return [p,q] + + # initialize + k = var('k') # index in summation formula + u_list = [] # of elements (-1)**u_i + subres_l = [p, q] # mod. subr. prs output list + a0, a1 = p, q # the input polys + del0 = d0 - d1 # degree difference + degdif = del0 # save it + rho_1 = LC(a0) # lead. coeff (a0) + + # Initialize Pell-Gordon variables + rho_list_minus_1 = sign( LC(a0, x)) # sign of LC(a0) + rho1 = LC(a1, x) # leading coeff of a1 + rho_list = [ sign(rho1)] # of signs + p_list = [del0] # of degree differences + u = summation(k, (k, 1, p_list[0])) # value of u + u_list.append(u) # of u values + v = sum(p_list) # v value + + # first remainder + exp_deg = d1 - 1 # expected degree of a2 + a2 = - rem(a0, a1, domain=QQ) # first remainder + rho2 = LC(a2, x) # leading coeff of a2 + d2 = degree(a2, x) # actual degree of a2 + deg_diff_new = exp_deg - d2 # expected - actual degree + del1 = d1 - d2 # degree difference + + # mul_fac is the factor by which a2 is multiplied to + # get integer coefficients + mul_fac_old = rho1**(del0 + del1 - deg_diff_new) + + # update Pell-Gordon variables + p_list.append(1 + deg_diff_new) # deg_diff_new is 0 for complete seq + + # apply Pell-Gordon formula (7) in second reference + num = 1 # numerator of fraction + for u in u_list: + num *= (-1)**u + num = num * (-1)**v + + # denominator depends on complete / incomplete seq + if deg_diff_new == 0: # complete seq + den = 1 + for k in range(len(rho_list)): + den *= rho_list[k]**(p_list[k] + p_list[k + 1]) + den = den * rho_list_minus_1 + else: # incomplete seq + den = 1 + for k in range(len(rho_list)-1): + den *= rho_list[k]**(p_list[k] + p_list[k + 1]) + den = den * rho_list_minus_1 + expo = (p_list[len(rho_list) - 1] + p_list[len(rho_list)] - deg_diff_new) + den = den * rho_list[len(rho_list) - 1]**expo + + # the sign of the determinant depends on sg(num / den) + if sign(num / den) > 0: + subres_l.append( simplify(rho_1**degdif*a2* Abs(mul_fac_old) ) ) + else: + subres_l.append(- simplify(rho_1**degdif*a2* Abs(mul_fac_old) ) ) + + # update Pell-Gordon variables + k = var('k') + rho_list.append( sign(rho2)) + u = summation(k, (k, 1, p_list[len(p_list) - 1])) + u_list.append(u) + v = sum(p_list) + deg_diff_old=deg_diff_new + + # main loop + while d2 > 0: + a0, a1, d0, d1 = a1, a2, d1, d2 # update polys and degrees + del0 = del1 # update degree difference + exp_deg = d1 - 1 # new expected degree + a2 = - rem(a0, a1, domain=QQ) # new remainder + rho3 = LC(a2, x) # leading coeff of a2 + d2 = degree(a2, x) # actual degree of a2 + deg_diff_new = exp_deg - d2 # expected - actual degree + del1 = d1 - d2 # degree difference + + # take into consideration the power + # rho1**deg_diff_old that was "left out" + expo_old = deg_diff_old # rho1 raised to this power + expo_new = del0 + del1 - deg_diff_new # rho2 raised to this power + + mul_fac_new = rho2**(expo_new) * rho1**(expo_old) * mul_fac_old + + # update variables + deg_diff_old, mul_fac_old = deg_diff_new, mul_fac_new + rho1, rho2 = rho2, rho3 + + # update Pell-Gordon variables + p_list.append(1 + deg_diff_new) # deg_diff_new is 0 for complete seq + + # apply Pell-Gordon formula (7) in second reference + num = 1 # numerator + for u in u_list: + num *= (-1)**u + num = num * (-1)**v + + # denominator depends on complete / incomplete seq + if deg_diff_new == 0: # complete seq + den = 1 + for k in range(len(rho_list)): + den *= rho_list[k]**(p_list[k] + p_list[k + 1]) + den = den * rho_list_minus_1 + else: # incomplete seq + den = 1 + for k in range(len(rho_list)-1): + den *= rho_list[k]**(p_list[k] + p_list[k + 1]) + den = den * rho_list_minus_1 + expo = (p_list[len(rho_list) - 1] + p_list[len(rho_list)] - deg_diff_new) + den = den * rho_list[len(rho_list) - 1]**expo + + # the sign of the determinant depends on sg(num / den) + if sign(num / den) > 0: + subres_l.append( simplify(rho_1**degdif*a2* Abs(mul_fac_old) ) ) + else: + subres_l.append(- simplify(rho_1**degdif*a2* Abs(mul_fac_old) ) ) + + # update Pell-Gordon variables + k = var('k') + rho_list.append( sign(rho2)) + u = summation(k, (k, 1, p_list[len(p_list) - 1])) + u_list.append(u) + v = sum(p_list) + + # gcd is of degree > 0 ? + m = len(subres_l) + if subres_l[m - 1] == nan or subres_l[m - 1] == 0: + subres_l.pop(m - 1) + + # LC( p ) < 0 + m = len(subres_l) # list may be shorter now due to deg(gcd ) > 0 + if LC( p ) < 0: + aux_seq = [subres_l[0], subres_l[1]] + for i in range(2, m): + aux_seq.append(simplify(subres_l[i] * (-1) )) + subres_l = aux_seq + + return subres_l + +def subresultants_pg(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the subresultant prs of p and q in Z[x] or Q[x], from + the modified subresultant prs of p and q. + + The coefficients of the polynomials in these two sequences differ only + in sign and the factor LC(p)**( deg(p)- deg(q)) as stated in + Theorem 2 of the reference. + + The coefficients of the polynomials in the output sequence are + subresultants. That is, they are determinants of appropriately + selected submatrices of sylvester1, Sylvester's matrix of 1840. + + If the subresultant prs is complete, then it coincides with the + Euclidean sequence of the polynomials p, q. + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: "On the Remainders + Obtained in Finding the Greatest Common Divisor of Two Polynomials." + Serdica Journal of Computing 9(2) (2015), 123-138. + + """ + # compute the modified subresultant prs + lst = modified_subresultants_pg(p,q,x) ## any other method would do + + # defensive + if lst == [] or len(lst) == 2: + return lst + + # the coefficients in lst are modified subresultants and, hence, are + # greater than those of the corresponding subresultants by the factor + # LC(lst[0])**( deg(lst[0]) - deg(lst[1])); see Theorem 2 in reference. + lcf = LC(lst[0])**( degree(lst[0], x) - degree(lst[1], x) ) + + # Initialize the subresultant prs list + subr_seq = [lst[0], lst[1]] + + # compute the degree sequences m_i and j_i of Theorem 2 in reference. + deg_seq = [degree(Poly(poly, x), x) for poly in lst] + deg = deg_seq[0] + deg_seq_s = deg_seq[1:-1] + m_seq = [m-1 for m in deg_seq_s] + j_seq = [deg - m for m in m_seq] + + # compute the AMV factors of Theorem 2 in reference. + fact = [(-1)**( j*(j-1)/S(2) ) for j in j_seq] + + # shortened list without the first two polys + lst_s = lst[2:] + + # poly lst_s[k] is multiplied times fact[k], divided by lcf + # and appended to the subresultant prs list + m = len(fact) + for k in range(m): + if sign(fact[k]) == -1: + subr_seq.append(-lst_s[k] / lcf) + else: + subr_seq.append(lst_s[k] / lcf) + + return subr_seq + +def subresultants_amv_q(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the subresultant prs of p and q in Q[x]; + the coefficients of the polynomials in the sequence are + subresultants. That is, they are determinants of appropriately + selected submatrices of sylvester1, Sylvester's matrix of 1840. + + To compute the coefficients, no determinant evaluation takes place. + Instead, polynomial divisions in Q[x] are performed, using the + function rem(p, q, x); the coefficients of the remainders + computed this way become subresultants with the help of the + Akritas-Malaschonok-Vigklas Theorem of 2015. + + If the subresultant prs is complete, then it coincides with the + Euclidean sequence of the polynomials p, q. + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result + on the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Subresultant Polynomial + remainder Sequences Obtained by Polynomial Divisions in Q[x] or in Z[x].'' + Serdica Journal of Computing 10 (2016), No.3-4, 197-217. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + d0 = degree(p, x) + d1 = degree(q, x) + if d0 == 0 and d1 == 0: + return [p, q] + if d1 > d0: + d0, d1 = d1, d0 + p, q = q, p + if d0 > 0 and d1 == 0: + return [p, q] + + # initialize + i, s = 0, 0 # counters for remainders & odd elements + p_odd_index_sum = 0 # contains the sum of p_1, p_3, etc + subres_l = [p, q] # subresultant prs output list + a0, a1 = p, q # the input polys + sigma1 = LC(a1, x) # leading coeff of a1 + p0 = d0 - d1 # degree difference + if p0 % 2 == 1: + s += 1 + phi = floor( (s + 1) / 2 ) + mul_fac = 1 + d2 = d1 + + # main loop + while d2 > 0: + i += 1 + a2 = rem(a0, a1, domain= QQ) # new remainder + if i == 1: + sigma2 = LC(a2, x) + else: + sigma3 = LC(a2, x) + sigma1, sigma2 = sigma2, sigma3 + d2 = degree(a2, x) + p1 = d1 - d2 + psi = i + phi + p_odd_index_sum + + # new mul_fac + mul_fac = sigma1**(p0 + 1) * mul_fac + + ## compute the sign of the first fraction in formula (9) of the paper + # numerator + num = (-1)**psi + # denominator + den = sign(mul_fac) + + # the sign of the determinant depends on sign( num / den ) != 0 + if sign(num / den) > 0: + subres_l.append( simplify(expand(a2* Abs(mul_fac)))) + else: + subres_l.append(- simplify(expand(a2* Abs(mul_fac)))) + + ## bring into mul_fac the missing power of sigma if there was a degree gap + if p1 - 1 > 0: + mul_fac = mul_fac * sigma1**(p1 - 1) + + # update AMV variables + a0, a1, d0, d1 = a1, a2, d1, d2 + p0 = p1 + if p0 % 2 ==1: + s += 1 + phi = floor( (s + 1) / 2 ) + if i%2 == 1: + p_odd_index_sum += p0 # p_i has odd index + + # gcd is of degree > 0 ? + m = len(subres_l) + if subres_l[m - 1] == nan or subres_l[m - 1] == 0: + subres_l.pop(m - 1) + + return subres_l + +def compute_sign(base, expo): + ''' + base != 0 and expo >= 0 are integers; + + returns the sign of base**expo without + evaluating the power itself! + ''' + sb = sign(base) + if sb == 1: + return 1 + pe = expo % 2 + if pe == 0: + return -sb + else: + return sb + +def rem_z(p, q, x): + ''' + Intended mainly for p, q polynomials in Z[x] so that, + on dividing p by q, the remainder will also be in Z[x]. (However, + it also works fine for polynomials in Q[x].) It is assumed + that degree(p, x) >= degree(q, x). + + It premultiplies p by the _absolute_ value of the leading coefficient + of q, raised to the power deg(p) - deg(q) + 1 and then performs + polynomial division in Q[x], using the function rem(p, q, x). + + By contrast the function prem(p, q, x) does _not_ use the absolute + value of the leading coefficient of q. + This results not only in ``messing up the signs'' of the Euclidean and + Sturmian prs's as mentioned in the second reference, + but also in violation of the main results of the first and third + references --- Theorem 4 and Theorem 1 respectively. Theorems 4 and 1 + establish a one-to-one correspondence between the Euclidean and the + Sturmian prs of p, q, on one hand, and the subresultant prs of p, q, + on the other. + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``On the Remainders + Obtained in Finding the Greatest Common Divisor of Two Polynomials.'' + Serdica Journal of Computing, 9(2) (2015), 123-138. + + 2. https://planetMath.org/sturmstheorem + + 3. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result on + the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + ''' + if (p.as_poly().is_univariate and q.as_poly().is_univariate and + p.as_poly().gens == q.as_poly().gens): + delta = (degree(p, x) - degree(q, x) + 1) + return rem(Abs(LC(q, x))**delta * p, q, x) + else: + return prem(p, q, x) + +def quo_z(p, q, x): + """ + Intended mainly for p, q polynomials in Z[x] so that, + on dividing p by q, the quotient will also be in Z[x]. (However, + it also works fine for polynomials in Q[x].) It is assumed + that degree(p, x) >= degree(q, x). + + It premultiplies p by the _absolute_ value of the leading coefficient + of q, raised to the power deg(p) - deg(q) + 1 and then performs + polynomial division in Q[x], using the function quo(p, q, x). + + By contrast the function pquo(p, q, x) does _not_ use the absolute + value of the leading coefficient of q. + + See also function rem_z(p, q, x) for additional comments and references. + + """ + if (p.as_poly().is_univariate and q.as_poly().is_univariate and + p.as_poly().gens == q.as_poly().gens): + delta = (degree(p, x) - degree(q, x) + 1) + return quo(Abs(LC(q, x))**delta * p, q, x) + else: + return pquo(p, q, x) + +def subresultants_amv(f, g, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(f, x) >= degree(g, x). + + Computes the subresultant prs of p and q in Z[x] or Q[x]; + the coefficients of the polynomials in the sequence are + subresultants. That is, they are determinants of appropriately + selected submatrices of sylvester1, Sylvester's matrix of 1840. + + To compute the coefficients, no determinant evaluation takes place. + Instead, polynomial divisions in Z[x] or Q[x] are performed, using + the function rem_z(p, q, x); the coefficients of the remainders + computed this way become subresultants with the help of the + Akritas-Malaschonok-Vigklas Theorem of 2015 and the Collins-Brown- + Traub formula for coefficient reduction. + + If the subresultant prs is complete, then it coincides with the + Euclidean sequence of the polynomials p, q. + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``A Basic Result + on the Theory of Subresultants.'' Serdica Journal of Computing 10 (2016), No.1, 31-48. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Subresultant Polynomial + remainder Sequences Obtained by Polynomial Divisions in Q[x] or in Z[x].'' + Serdica Journal of Computing 10 (2016), No.3-4, 197-217. + + """ + # make sure neither f nor g is 0 + if f == 0 or g == 0: + return [f, g] + + # make sure proper degrees + d0 = degree(f, x) + d1 = degree(g, x) + if d0 == 0 and d1 == 0: + return [f, g] + if d1 > d0: + d0, d1 = d1, d0 + f, g = g, f + if d0 > 0 and d1 == 0: + return [f, g] + + # initialize + a0 = f + a1 = g + subres_l = [a0, a1] + deg_dif_p1, c = degree(a0, x) - degree(a1, x) + 1, -1 + + # initialize AMV variables + sigma1 = LC(a1, x) # leading coeff of a1 + i, s = 0, 0 # counters for remainders & odd elements + p_odd_index_sum = 0 # contains the sum of p_1, p_3, etc + p0 = deg_dif_p1 - 1 + if p0 % 2 == 1: + s += 1 + phi = floor( (s + 1) / 2 ) + + # compute the first polynomial of the prs + i += 1 + a2 = rem_z(a0, a1, x) / Abs( (-1)**deg_dif_p1 ) # first remainder + sigma2 = LC(a2, x) # leading coeff of a2 + d2 = degree(a2, x) # actual degree of a2 + p1 = d1 - d2 # degree difference + + # sgn_den is the factor, the denominator 1st fraction of (9), + # by which a2 is multiplied to get integer coefficients + sgn_den = compute_sign( sigma1, p0 + 1 ) + + ## compute sign of the 1st fraction in formula (9) of the paper + # numerator + psi = i + phi + p_odd_index_sum + num = (-1)**psi + # denominator + den = sgn_den + + # the sign of the determinant depends on sign(num / den) != 0 + if sign(num / den) > 0: + subres_l.append( a2 ) + else: + subres_l.append( -a2 ) + + # update AMV variable + if p1 % 2 == 1: + s += 1 + + # bring in the missing power of sigma if there was gap + if p1 - 1 > 0: + sgn_den = sgn_den * compute_sign( sigma1, p1 - 1 ) + + # main loop + while d2 >= 1: + phi = floor( (s + 1) / 2 ) + if i%2 == 1: + p_odd_index_sum += p1 # p_i has odd index + a0, a1, d0, d1 = a1, a2, d1, d2 # update polys and degrees + p0 = p1 # update degree difference + i += 1 + sigma0 = -LC(a0) + c = (sigma0**(deg_dif_p1 - 1)) / (c**(deg_dif_p1 - 2)) + deg_dif_p1 = degree(a0, x) - d2 + 1 + a2 = rem_z(a0, a1, x) / Abs( (c**(deg_dif_p1 - 1)) * sigma0 ) + sigma3 = LC(a2, x) # leading coeff of a2 + d2 = degree(a2, x) # actual degree of a2 + p1 = d1 - d2 # degree difference + psi = i + phi + p_odd_index_sum + + # update variables + sigma1, sigma2 = sigma2, sigma3 + + # new sgn_den + sgn_den = compute_sign( sigma1, p0 + 1 ) * sgn_den + + # compute the sign of the first fraction in formula (9) of the paper + # numerator + num = (-1)**psi + # denominator + den = sgn_den + + # the sign of the determinant depends on sign( num / den ) != 0 + if sign(num / den) > 0: + subres_l.append( a2 ) + else: + subres_l.append( -a2 ) + + # update AMV variable + if p1 % 2 ==1: + s += 1 + + # bring in the missing power of sigma if there was gap + if p1 - 1 > 0: + sgn_den = sgn_den * compute_sign( sigma1, p1 - 1 ) + + # gcd is of degree > 0 ? + m = len(subres_l) + if subres_l[m - 1] == nan or subres_l[m - 1] == 0: + subres_l.pop(m - 1) + + return subres_l + +def modified_subresultants_amv(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the modified subresultant prs of p and q in Z[x] or Q[x], + from the subresultant prs of p and q. + The coefficients of the polynomials in the two sequences differ only + in sign and the factor LC(p)**( deg(p)- deg(q)) as stated in + Theorem 2 of the reference. + + The coefficients of the polynomials in the output sequence are + modified subresultants. That is, they are determinants of appropriately + selected submatrices of sylvester2, Sylvester's matrix of 1853. + + If the modified subresultant prs is complete, and LC( p ) > 0, it coincides + with the (generalized) Sturm's sequence of the polynomials p, q. + + References + ========== + 1. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: "On the Remainders + Obtained in Finding the Greatest Common Divisor of Two Polynomials." + Serdica Journal of Computing, Serdica Journal of Computing, 9(2) (2015), 123-138. + + """ + # compute the subresultant prs + lst = subresultants_amv(p,q,x) ## any other method would do + + # defensive + if lst == [] or len(lst) == 2: + return lst + + # the coefficients in lst are subresultants and, hence, smaller than those + # of the corresponding modified subresultants by the factor + # LC(lst[0])**( deg(lst[0]) - deg(lst[1])); see Theorem 2. + lcf = LC(lst[0])**( degree(lst[0], x) - degree(lst[1], x) ) + + # Initialize the modified subresultant prs list + subr_seq = [lst[0], lst[1]] + + # compute the degree sequences m_i and j_i of Theorem 2 + deg_seq = [degree(Poly(poly, x), x) for poly in lst] + deg = deg_seq[0] + deg_seq_s = deg_seq[1:-1] + m_seq = [m-1 for m in deg_seq_s] + j_seq = [deg - m for m in m_seq] + + # compute the AMV factors of Theorem 2 + fact = [(-1)**( j*(j-1)/S(2) ) for j in j_seq] + + # shortened list without the first two polys + lst_s = lst[2:] + + # poly lst_s[k] is multiplied times fact[k] and times lcf + # and appended to the subresultant prs list + m = len(fact) + for k in range(m): + if sign(fact[k]) == -1: + subr_seq.append( simplify(-lst_s[k] * lcf) ) + else: + subr_seq.append( simplify(lst_s[k] * lcf) ) + + return subr_seq + +def correct_sign(deg_f, deg_g, s1, rdel, cdel): + """ + Used in various subresultant prs algorithms. + + Evaluates the determinant, (a.k.a. subresultant) of a properly selected + submatrix of s1, Sylvester's matrix of 1840, to get the correct sign + and value of the leading coefficient of a given polynomial remainder. + + deg_f, deg_g are the degrees of the original polynomials p, q for which the + matrix s1 = sylvester(p, q, x, 1) was constructed. + + rdel denotes the expected degree of the remainder; it is the number of + rows to be deleted from each group of rows in s1 as described in the + reference below. + + cdel denotes the expected degree minus the actual degree of the remainder; + it is the number of columns to be deleted --- starting with the last column + forming the square matrix --- from the matrix resulting after the row deletions. + + References + ========== + Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``Sturm Sequences + and Modified Subresultant Polynomial Remainder Sequences.'' + Serdica Journal of Computing, Vol. 8, No 1, 29-46, 2014. + + """ + M = s1[:, :] # copy of matrix s1 + + # eliminate rdel rows from the first deg_g rows + for i in range(M.rows - deg_f - 1, M.rows - deg_f - rdel - 1, -1): + M.row_del(i) + + # eliminate rdel rows from the last deg_f rows + for i in range(M.rows - 1, M.rows - rdel - 1, -1): + M.row_del(i) + + # eliminate cdel columns + for i in range(cdel): + M.col_del(M.rows - 1) + + # define submatrix + Md = M[:, 0: M.rows] + + return Md.det() + +def subresultants_rem(p, q, x): + """ + p, q are polynomials in Z[x] or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the subresultant prs of p and q in Z[x] or Q[x]; + the coefficients of the polynomials in the sequence are + subresultants. That is, they are determinants of appropriately + selected submatrices of sylvester1, Sylvester's matrix of 1840. + + To compute the coefficients polynomial divisions in Q[x] are + performed, using the function rem(p, q, x). The coefficients + of the remainders computed this way become subresultants by evaluating + one subresultant per remainder --- that of the leading coefficient. + This way we obtain the correct sign and value of the leading coefficient + of the remainder and we easily ``force'' the rest of the coefficients + to become subresultants. + + If the subresultant prs is complete, then it coincides with the + Euclidean sequence of the polynomials p, q. + + References + ========== + 1. Akritas, A. G.:``Three New Methods for Computing Subresultant + Polynomial Remainder Sequences (PRS's).'' Serdica Journal of Computing 9(1) (2015), 1-26. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + f, g = p, q + n = deg_f = degree(f, x) + m = deg_g = degree(g, x) + if n == 0 and m == 0: + return [f, g] + if n < m: + n, m, deg_f, deg_g, f, g = m, n, deg_g, deg_f, g, f + if n > 0 and m == 0: + return [f, g] + + # initialize + s1 = sylvester(f, g, x, 1) + sr_list = [f, g] # subresultant list + + # main loop + while deg_g > 0: + r = rem(p, q, x) + d = degree(r, x) + if d < 0: + return sr_list + + # make coefficients subresultants evaluating ONE determinant + exp_deg = deg_g - 1 # expected degree + sign_value = correct_sign(n, m, s1, exp_deg, exp_deg - d) + r = simplify((r / LC(r, x)) * sign_value) + + # append poly with subresultant coeffs + sr_list.append(r) + + # update degrees and polys + deg_f, deg_g = deg_g, d + p, q = q, r + + # gcd is of degree > 0 ? + m = len(sr_list) + if sr_list[m - 1] == nan or sr_list[m - 1] == 0: + sr_list.pop(m - 1) + + return sr_list + +def pivot(M, i, j): + ''' + M is a matrix, and M[i, j] specifies the pivot element. + + All elements below M[i, j], in the j-th column, will + be zeroed, if they are not already 0, according to + Dodgson-Bareiss' integer preserving transformations. + + References + ========== + 1. Akritas, A. G.: ``A new method for computing polynomial greatest + common divisors and polynomial remainder sequences.'' + Numerische MatheMatik 52, 119-127, 1988. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``On a Theorem + by Van Vleck Regarding Sturm Sequences.'' + Serdica Journal of Computing, 7, No 4, 101-134, 2013. + + ''' + ma = M[:, :] # copy of matrix M + rs = ma.rows # No. of rows + cs = ma.cols # No. of cols + for r in range(i+1, rs): + if ma[r, j] != 0: + for c in range(j + 1, cs): + ma[r, c] = ma[i, j] * ma[r, c] - ma[i, c] * ma[r, j] + ma[r, j] = 0 + return ma + +def rotate_r(L, k): + ''' + Rotates right by k. L is a row of a matrix or a list. + + ''' + ll = list(L) + if ll == []: + return [] + for i in range(k): + el = ll.pop(len(ll) - 1) + ll.insert(0, el) + return ll if isinstance(L, list) else Matrix([ll]) + +def rotate_l(L, k): + ''' + Rotates left by k. L is a row of a matrix or a list. + + ''' + ll = list(L) + if ll == []: + return [] + for i in range(k): + el = ll.pop(0) + ll.insert(len(ll) - 1, el) + return ll if isinstance(L, list) else Matrix([ll]) + +def row2poly(row, deg, x): + ''' + Converts the row of a matrix to a poly of degree deg and variable x. + Some entries at the beginning and/or at the end of the row may be zero. + + ''' + k = 0 + poly = [] + leng = len(row) + + # find the beginning of the poly ; i.e. the first + # non-zero element of the row + while row[k] == 0: + k = k + 1 + + # append the next deg + 1 elements to poly + for j in range( deg + 1): + if k + j <= leng: + poly.append(row[k + j]) + + return Poly(poly, x) + +def create_ma(deg_f, deg_g, row1, row2, col_num): + ''' + Creates a ``small'' matrix M to be triangularized. + + deg_f, deg_g are the degrees of the divident and of the + divisor polynomials respectively, deg_g > deg_f. + + The coefficients of the divident poly are the elements + in row2 and those of the divisor poly are the elements + in row1. + + col_num defines the number of columns of the matrix M. + + ''' + if deg_g - deg_f >= 1: + print('Reverse degrees') + return + + m = zeros(deg_f - deg_g + 2, col_num) + + for i in range(deg_f - deg_g + 1): + m[i, :] = rotate_r(row1, i) + m[deg_f - deg_g + 1, :] = row2 + + return m + +def find_degree(M, deg_f): + ''' + Finds the degree of the poly corresponding (after triangularization) + to the _last_ row of the ``small'' matrix M, created by create_ma(). + + deg_f is the degree of the divident poly. + If _last_ row is all 0's returns None. + + ''' + j = deg_f + for i in range(0, M.cols): + if M[M.rows - 1, i] == 0: + j = j - 1 + else: + return max(j, 0) + +def final_touches(s2, r, deg_g): + """ + s2 is sylvester2, r is the row pointer in s2, + deg_g is the degree of the poly last inserted in s2. + + After a gcd of degree > 0 has been found with Van Vleck's + method, and was inserted into s2, if its last term is not + in the last column of s2, then it is inserted as many + times as needed, rotated right by one each time, until + the condition is met. + + """ + R = s2.row(r-1) + + # find the first non zero term + for i in range(s2.cols): + if R[0,i] == 0: + continue + else: + break + + # missing rows until last term is in last column + mr = s2.cols - (i + deg_g + 1) + + # insert them by replacing the existing entries in the row + i = 0 + while mr != 0 and r + i < s2.rows : + s2[r + i, : ] = rotate_r(R, i + 1) + i += 1 + mr -= 1 + + return s2 + +def subresultants_vv(p, q, x, method = 0): + """ + p, q are polynomials in Z[x] (intended) or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the subresultant prs of p, q by triangularizing, + in Z[x] or in Q[x], all the smaller matrices encountered in the + process of triangularizing sylvester2, Sylvester's matrix of 1853; + see references 1 and 2 for Van Vleck's method. With each remainder, + sylvester2 gets updated and is prepared to be printed if requested. + + If sylvester2 has small dimensions and you want to see the final, + triangularized matrix use this version with method=1; otherwise, + use either this version with method=0 (default) or the faster version, + subresultants_vv_2(p, q, x), where sylvester2 is used implicitly. + + Sylvester's matrix sylvester1 is also used to compute one + subresultant per remainder; namely, that of the leading + coefficient, in order to obtain the correct sign and to + force the remainder coefficients to become subresultants. + + If the subresultant prs is complete, then it coincides with the + Euclidean sequence of the polynomials p, q. + + If the final, triangularized matrix s2 is printed, then: + (a) if deg(p) - deg(q) > 1 or deg( gcd(p, q) ) > 0, several + of the last rows in s2 will remain unprocessed; + (b) if deg(p) - deg(q) == 0, p will not appear in the final matrix. + + References + ========== + 1. Akritas, A. G.: ``A new method for computing polynomial greatest + common divisors and polynomial remainder sequences.'' + Numerische MatheMatik 52, 119-127, 1988. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``On a Theorem + by Van Vleck Regarding Sturm Sequences.'' + Serdica Journal of Computing, 7, No 4, 101-134, 2013. + + 3. Akritas, A. G.:``Three New Methods for Computing Subresultant + Polynomial Remainder Sequences (PRS's).'' Serdica Journal of Computing 9(1) (2015), 1-26. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + f, g = p, q + n = deg_f = degree(f, x) + m = deg_g = degree(g, x) + if n == 0 and m == 0: + return [f, g] + if n < m: + n, m, deg_f, deg_g, f, g = m, n, deg_g, deg_f, g, f + if n > 0 and m == 0: + return [f, g] + + # initialize + s1 = sylvester(f, g, x, 1) + s2 = sylvester(f, g, x, 2) + sr_list = [f, g] + col_num = 2 * n # columns in s2 + + # make two rows (row0, row1) of poly coefficients + row0 = Poly(f, x, domain = QQ).all_coeffs() + leng0 = len(row0) + for i in range(col_num - leng0): + row0.append(0) + row0 = Matrix([row0]) + row1 = Poly(g,x, domain = QQ).all_coeffs() + leng1 = len(row1) + for i in range(col_num - leng1): + row1.append(0) + row1 = Matrix([row1]) + + # row pointer for deg_f - deg_g == 1; may be reset below + r = 2 + + # modify first rows of s2 matrix depending on poly degrees + if deg_f - deg_g > 1: + r = 1 + # replacing the existing entries in the rows of s2, + # insert row0 (deg_f - deg_g - 1) times, rotated each time + for i in range(deg_f - deg_g - 1): + s2[r + i, : ] = rotate_r(row0, i + 1) + r = r + deg_f - deg_g - 1 + # insert row1 (deg_f - deg_g) times, rotated each time + for i in range(deg_f - deg_g): + s2[r + i, : ] = rotate_r(row1, r + i) + r = r + deg_f - deg_g + + if deg_f - deg_g == 0: + r = 0 + + # main loop + while deg_g > 0: + # create a small matrix M, and triangularize it; + M = create_ma(deg_f, deg_g, row1, row0, col_num) + # will need only the first and last rows of M + for i in range(deg_f - deg_g + 1): + M1 = pivot(M, i, i) + M = M1[:, :] + + # treat last row of M as poly; find its degree + d = find_degree(M, deg_f) + if d is None: + break + exp_deg = deg_g - 1 + + # evaluate one determinant & make coefficients subresultants + sign_value = correct_sign(n, m, s1, exp_deg, exp_deg - d) + poly = row2poly(M[M.rows - 1, :], d, x) + temp2 = LC(poly, x) + poly = simplify((poly / temp2) * sign_value) + + # update s2 by inserting first row of M as needed + row0 = M[0, :] + for i in range(deg_g - d): + s2[r + i, :] = rotate_r(row0, r + i) + r = r + deg_g - d + + # update s2 by inserting last row of M as needed + row1 = rotate_l(M[M.rows - 1, :], deg_f - d) + row1 = (row1 / temp2) * sign_value + for i in range(deg_g - d): + s2[r + i, :] = rotate_r(row1, r + i) + r = r + deg_g - d + + # update degrees + deg_f, deg_g = deg_g, d + + # append poly with subresultant coeffs + sr_list.append(poly) + + # final touches to print the s2 matrix + if method != 0 and s2.rows > 2: + s2 = final_touches(s2, r, deg_g) + pprint(s2) + elif method != 0 and s2.rows == 2: + s2[1, :] = rotate_r(s2.row(1), 1) + pprint(s2) + + return sr_list + +def subresultants_vv_2(p, q, x): + """ + p, q are polynomials in Z[x] (intended) or Q[x]. It is assumed + that degree(p, x) >= degree(q, x). + + Computes the subresultant prs of p, q by triangularizing, + in Z[x] or in Q[x], all the smaller matrices encountered in the + process of triangularizing sylvester2, Sylvester's matrix of 1853; + see references 1 and 2 for Van Vleck's method. + + If the sylvester2 matrix has big dimensions use this version, + where sylvester2 is used implicitly. If you want to see the final, + triangularized matrix sylvester2, then use the first version, + subresultants_vv(p, q, x, 1). + + sylvester1, Sylvester's matrix of 1840, is also used to compute + one subresultant per remainder; namely, that of the leading + coefficient, in order to obtain the correct sign and to + ``force'' the remainder coefficients to become subresultants. + + If the subresultant prs is complete, then it coincides with the + Euclidean sequence of the polynomials p, q. + + References + ========== + 1. Akritas, A. G.: ``A new method for computing polynomial greatest + common divisors and polynomial remainder sequences.'' + Numerische MatheMatik 52, 119-127, 1988. + + 2. Akritas, A. G., G.I. Malaschonok and P.S. Vigklas: ``On a Theorem + by Van Vleck Regarding Sturm Sequences.'' + Serdica Journal of Computing, 7, No 4, 101-134, 2013. + + 3. Akritas, A. G.:``Three New Methods for Computing Subresultant + Polynomial Remainder Sequences (PRS's).'' Serdica Journal of Computing 9(1) (2015), 1-26. + + """ + # make sure neither p nor q is 0 + if p == 0 or q == 0: + return [p, q] + + # make sure proper degrees + f, g = p, q + n = deg_f = degree(f, x) + m = deg_g = degree(g, x) + if n == 0 and m == 0: + return [f, g] + if n < m: + n, m, deg_f, deg_g, f, g = m, n, deg_g, deg_f, g, f + if n > 0 and m == 0: + return [f, g] + + # initialize + s1 = sylvester(f, g, x, 1) + sr_list = [f, g] # subresultant list + col_num = 2 * n # columns in sylvester2 + + # make two rows (row0, row1) of poly coefficients + row0 = Poly(f, x, domain = QQ).all_coeffs() + leng0 = len(row0) + for i in range(col_num - leng0): + row0.append(0) + row0 = Matrix([row0]) + row1 = Poly(g,x, domain = QQ).all_coeffs() + leng1 = len(row1) + for i in range(col_num - leng1): + row1.append(0) + row1 = Matrix([row1]) + + # main loop + while deg_g > 0: + # create a small matrix M, and triangularize it + M = create_ma(deg_f, deg_g, row1, row0, col_num) + for i in range(deg_f - deg_g + 1): + M1 = pivot(M, i, i) + M = M1[:, :] + + # treat last row of M as poly; find its degree + d = find_degree(M, deg_f) + if d is None: + return sr_list + exp_deg = deg_g - 1 + + # evaluate one determinant & make coefficients subresultants + sign_value = correct_sign(n, m, s1, exp_deg, exp_deg - d) + poly = row2poly(M[M.rows - 1, :], d, x) + poly = simplify((poly / LC(poly, x)) * sign_value) + + # append poly with subresultant coeffs + sr_list.append(poly) + + # update degrees and rows + deg_f, deg_g = deg_g, d + row0 = row1 + row1 = Poly(poly, x, domain = QQ).all_coeffs() + leng1 = len(row1) + for i in range(col_num - leng1): + row1.append(0) + row1 = Matrix([row1]) + + return sr_list diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/release.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/release.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f68edb2f571e7bfaad9472d36a2d357b5574b2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/release.py @@ -0,0 +1 @@ +__version__ = "1.14.0" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d46ab87f1cfe79a8acec105051442b92fadb7e3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cada985c4e4c5c46e5df5e66fb82188030885bab Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01b9357dc05bdc8228ea869e9fa82765de67aa4b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..437daace56673881165b8c0a98760cb5e568ca41 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d8c864c581940cc1b3a26f52d01f65789f70067 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4237fdc99aaa063e302e90e4feec512dcac0a58 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2301cf5f78c9453ef50ef1d55bd5247d37163a24 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca88608ee5bd7e4315a39b5165e5263fbeb00ebc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f5b5f0da2bbef4219c1751bbdc3524bb897228a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d883f21afd5341cc4248f07a3ef411704be0e375 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4732b064d5e6dd8de5233407a0dedb73b8895d4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2e2c98cf12055bae23567b8ff8f5a96566dd8b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec8d0d805312a5d83de2b799b74a206091fc8da8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06b62c09b2fb50d6797108c1b2e6461c55bd118a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/powsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/powsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..f72dfeb072e0d0d4737ace310eda5c2a3a082c16 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/powsimp.py @@ -0,0 +1,718 @@ +from collections import defaultdict +from functools import reduce +from math import prod + +from sympy.core.function import expand_log, count_ops, _coeff_isneg +from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms +from sympy.core.sorting import ordered, default_sort_key +from sympy.core.numbers import Integer, Rational, equal_valued +from sympy.core.mul import _keep_coeff +from sympy.core.rules import Transform +from sympy.functions import exp_polar, exp, log, root, polarify, unpolarify +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.polys import lcm, gcd +from sympy.ntheory.factor_ import multiplicity + + + +def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops): + """ + Reduce expression by combining powers with similar bases and exponents. + + Explanation + =========== + + If ``deep`` is ``True`` then powsimp() will also simplify arguments of + functions. By default ``deep`` is set to ``False``. + + If ``force`` is ``True`` then bases will be combined without checking for + assumptions, e.g. sqrt(x)*sqrt(y) -> sqrt(x*y) which is not true + if x and y are both negative. + + You can make powsimp() only combine bases or only combine exponents by + changing combine='base' or combine='exp'. By default, combine='all', + which does both. combine='base' will only combine:: + + a a a 2x x + x * y => (x*y) as well as things like 2 => 4 + + and combine='exp' will only combine + :: + + a b (a + b) + x * x => x + + combine='exp' will strictly only combine exponents in the way that used + to be automatic. Also use deep=True if you need the old behavior. + + When combine='all', 'exp' is evaluated first. Consider the first + example below for when there could be an ambiguity relating to this. + This is done so things like the second example can be completely + combined. If you want 'base' combined first, do something like + powsimp(powsimp(expr, combine='base'), combine='exp'). + + Examples + ======== + + >>> from sympy import powsimp, exp, log, symbols + >>> from sympy.abc import x, y, z, n + >>> powsimp(x**y*x**z*y**z, combine='all') + x**(y + z)*y**z + >>> powsimp(x**y*x**z*y**z, combine='exp') + x**(y + z)*y**z + >>> powsimp(x**y*x**z*y**z, combine='base', force=True) + x**y*(x*y)**z + + >>> powsimp(x**z*x**y*n**z*n**y, combine='all', force=True) + (n*x)**(y + z) + >>> powsimp(x**z*x**y*n**z*n**y, combine='exp') + n**(y + z)*x**(y + z) + >>> powsimp(x**z*x**y*n**z*n**y, combine='base', force=True) + (n*x)**y*(n*x)**z + + >>> x, y = symbols('x y', positive=True) + >>> powsimp(log(exp(x)*exp(y))) + log(exp(x)*exp(y)) + >>> powsimp(log(exp(x)*exp(y)), deep=True) + x + y + + Radicals with Mul bases will be combined if combine='exp' + + >>> from sympy import sqrt + >>> x, y = symbols('x y') + + Two radicals are automatically joined through Mul: + + >>> a=sqrt(x*sqrt(y)) + >>> a*a**3 == a**4 + True + + But if an integer power of that radical has been + autoexpanded then Mul does not join the resulting factors: + + >>> a**4 # auto expands to a Mul, no longer a Pow + x**2*y + >>> _*a # so Mul doesn't combine them + x**2*y*sqrt(x*sqrt(y)) + >>> powsimp(_) # but powsimp will + (x*sqrt(y))**(5/2) + >>> powsimp(x*y*a) # but won't when doing so would violate assumptions + x*y*sqrt(x*sqrt(y)) + + """ + def recurse(arg, **kwargs): + _deep = kwargs.get('deep', deep) + _combine = kwargs.get('combine', combine) + _force = kwargs.get('force', force) + _measure = kwargs.get('measure', measure) + return powsimp(arg, _deep, _combine, _force, _measure) + + expr = sympify(expr) + + if (not isinstance(expr, Basic) or isinstance(expr, MatrixSymbol) or ( + expr.is_Atom or expr in (exp_polar(0), exp_polar(1)))): + return expr + + if deep or expr.is_Add or expr.is_Mul and _y not in expr.args: + expr = expr.func(*[recurse(w) for w in expr.args]) + + if expr.is_Pow: + return recurse(expr*_y, deep=False)/_y + + if not expr.is_Mul: + return expr + + # handle the Mul + if combine in ('exp', 'all'): + # Collect base/exp data, while maintaining order in the + # non-commutative parts of the product + c_powers = defaultdict(list) + nc_part = [] + newexpr = [] + coeff = S.One + for term in expr.args: + if term.is_Rational: + coeff *= term + continue + if term.is_Pow: + term = _denest_pow(term) + if term.is_commutative: + b, e = term.as_base_exp() + if deep: + b, e = [recurse(i) for i in [b, e]] + if b.is_Pow or isinstance(b, exp): + # don't let smthg like sqrt(x**a) split into x**a, 1/2 + # or else it will be joined as x**(a/2) later + b, e = b**e, S.One + c_powers[b].append(e) + else: + # This is the logic that combines exponents for equal, + # but non-commutative bases: A**x*A**y == A**(x+y). + if nc_part: + b1, e1 = nc_part[-1].as_base_exp() + b2, e2 = term.as_base_exp() + if (b1 == b2 and + e1.is_commutative and e2.is_commutative): + nc_part[-1] = Pow(b1, Add(e1, e2)) + continue + nc_part.append(term) + + # add up exponents of common bases + for b, e in ordered(iter(c_powers.items())): + # allow 2**x/4 -> 2**(x - 2); don't do this when b and e are + # Numbers since autoevaluation will undo it, e.g. + # 2**(1/3)/4 -> 2**(1/3 - 2) -> 2**(1/3)/4 + if (b and b.is_Rational and not all(ei.is_Number for ei in e) and \ + coeff is not S.One and + b not in (S.One, S.NegativeOne)): + m = multiplicity(abs(b), abs(coeff)) + if m: + e.append(m) + coeff /= b**m + c_powers[b] = Add(*e) + if coeff is not S.One: + if coeff in c_powers: + c_powers[coeff] += S.One + else: + c_powers[coeff] = S.One + + # convert to plain dictionary + c_powers = dict(c_powers) + + # check for base and inverted base pairs + be = list(c_powers.items()) + skip = set() # skip if we already saw them + for b, e in be: + if b in skip: + continue + bpos = b.is_positive or b.is_polar + if bpos: + binv = 1/b + #Special case for float 1 + if b.is_Float and equal_valued(b, 1): + c_powers[b] = S.One + continue + if b != binv and binv in c_powers: + if b.as_numer_denom()[0] is S.One: + c_powers.pop(b) + c_powers[binv] -= e + else: + skip.add(binv) + e = c_powers.pop(binv) + c_powers[b] -= e + + # check for base and negated base pairs + be = list(c_powers.items()) + _n = S.NegativeOne + for b, e in be: + if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers: + if (b.is_positive is not None or e.is_integer): + if e.is_integer or b.is_negative: + c_powers[-b] += c_powers.pop(b) + else: # (-b).is_positive so use its e + e = c_powers.pop(-b) + c_powers[b] += e + if _n in c_powers: + c_powers[_n] += e + else: + c_powers[_n] = e + + # filter c_powers and convert to a list + c_powers = [(b, e) for b, e in c_powers.items() if e] + + # ============================================================== + # check for Mul bases of Rational powers that can be combined with + # separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) -> + # (x*sqrt(x*y))**(3/2) + # ---------------- helper functions + + def ratq(x): + '''Return Rational part of x's exponent as it appears in the bkey. + ''' + return bkey(x)[0][1] + + def bkey(b, e=None): + '''Return (b**s, c.q), c.p where e -> c*s. If e is not given then + it will be taken by using as_base_exp() on the input b. + e.g. + x**3/2 -> (x, 2), 3 + x**y -> (x**y, 1), 1 + x**(2*y/3) -> (x**y, 3), 2 + exp(x/2) -> (exp(a), 2), 1 + + ''' + if e is not None: # coming from c_powers or from below + if e.is_Integer: + return (b, S.One), e + elif e.is_Rational: + return (b, Integer(e.q)), Integer(e.p) + else: + c, m = e.as_coeff_Mul(rational=True) + if c is not S.One: + if m.is_integer: + return (b, Integer(c.q)), m*Integer(c.p) + return (b**m, Integer(c.q)), Integer(c.p) + else: + return (b**e, S.One), S.One + else: + return bkey(*b.as_base_exp()) + + def update(b): + '''Decide what to do with base, b. If its exponent is now an + integer multiple of the Rational denominator, then remove it + and put the factors of its base in the common_b dictionary or + update the existing bases if necessary. If it has been zeroed + out, simply remove the base. + ''' + newe, r = divmod(common_b[b], b[1]) + if not r: + common_b.pop(b) + if newe: + for m in Mul.make_args(b[0]**newe): + b, e = bkey(m) + if b not in common_b: + common_b[b] = 0 + common_b[b] += e + if b[1] != 1: + bases.append(b) + # ---------------- end of helper functions + + # assemble a dictionary of the factors having a Rational power + common_b = {} + done = [] + bases = [] + for b, e in c_powers: + b, e = bkey(b, e) + if b in common_b: + common_b[b] = common_b[b] + e + else: + common_b[b] = e + if b[1] != 1 and b[0].is_Mul: + bases.append(b) + bases.sort(key=default_sort_key) # this makes tie-breaking canonical + bases.sort(key=measure, reverse=True) # handle longest first + for base in bases: + if base not in common_b: # it may have been removed already + continue + b, exponent = base + last = False # True when no factor of base is a radical + qlcm = 1 # the lcm of the radical denominators + while True: + bstart = b + qstart = qlcm + + bb = [] # list of factors + ee = [] # (factor's expo. and it's current value in common_b) + for bi in Mul.make_args(b): + bib, bie = bkey(bi) + if bib not in common_b or common_b[bib] < bie: + ee = bb = [] # failed + break + ee.append([bie, common_b[bib]]) + bb.append(bib) + if ee: + # find the number of integral extractions possible + # e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1 + min1 = ee[0][1]//ee[0][0] + for i in range(1, len(ee)): + rat = ee[i][1]//ee[i][0] + if rat < 1: + break + min1 = min(min1, rat) + else: + # update base factor counts + # e.g. if ee = [(2, 5), (3, 6)] then min1 = 2 + # and the new base counts will be 5-2*2 and 6-2*3 + for i in range(len(bb)): + common_b[bb[i]] -= min1*ee[i][0] + update(bb[i]) + # update the count of the base + # e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y) + # will increase by 4 to give bkey (x*sqrt(y), 2, 5) + common_b[base] += min1*qstart*exponent + if (last # no more radicals in base + or len(common_b) == 1 # nothing left to join with + or all(k[1] == 1 for k in common_b) # no rad's in common_b + ): + break + # see what we can exponentiate base by to remove any radicals + # so we know what to search for + # e.g. if base were x**(1/2)*y**(1/3) then we should + # exponentiate by 6 and look for powers of x and y in the ratio + # of 2 to 3 + qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)]) + if qlcm == 1: + break # we are done + b = bstart**qlcm + qlcm *= qstart + if all(ratq(bi) == 1 for bi in Mul.make_args(b)): + last = True # we are going to be done after this next pass + # this base no longer can find anything to join with and + # since it was longer than any other we are done with it + b, q = base + done.append((b, common_b.pop(base)*Rational(1, q))) + + # update c_powers and get ready to continue with powsimp + c_powers = done + # there may be terms still in common_b that were bases that were + # identified as needing processing, so remove those, too + for (b, q), e in common_b.items(): + if (b.is_Pow or isinstance(b, exp)) and \ + q is not S.One and not b.exp.is_Rational: + b, be = b.as_base_exp() + b = b**(be/q) + else: + b = root(b, q) + c_powers.append((b, e)) + check = len(c_powers) + c_powers = dict(c_powers) + assert len(c_powers) == check # there should have been no duplicates + # ============================================================== + + # rebuild the expression + newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()])) + if combine == 'exp': + return expr.func(newexpr, expr.func(*nc_part)) + else: + return recurse(expr.func(*nc_part), combine='base') * \ + recurse(newexpr, combine='base') + + elif combine == 'base': + + # Build c_powers and nc_part. These must both be lists not + # dicts because exp's are not combined. + c_powers = [] + nc_part = [] + for term in expr.args: + if term.is_commutative: + c_powers.append(list(term.as_base_exp())) + else: + nc_part.append(term) + + # Pull out numerical coefficients from exponent if assumptions allow + # e.g., 2**(2*x) => 4**x + for i in range(len(c_powers)): + b, e = c_powers[i] + if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar): + continue + exp_c, exp_t = e.as_coeff_Mul(rational=True) + if exp_c is not S.One and exp_t is not S.One: + c_powers[i] = [Pow(b, exp_c), exp_t] + + # Combine bases whenever they have the same exponent and + # assumptions allow + # first gather the potential bases under the common exponent + c_exp = defaultdict(list) + for b, e in c_powers: + if deep: + e = recurse(e) + if e.is_Add and (b.is_positive or e.is_integer): + e = factor_terms(e) + if _coeff_isneg(e): + e = -e + b = 1/b + c_exp[e].append(b) + del c_powers + + # Merge back in the results of the above to form a new product + c_powers = defaultdict(list) + for e in c_exp: + bases = c_exp[e] + + # calculate the new base for e + + if len(bases) == 1: + new_base = bases[0] + elif e.is_integer or force: + new_base = expr.func(*bases) + else: + # see which ones can be joined + unk = [] + nonneg = [] + neg = [] + for bi in bases: + if bi.is_negative: + neg.append(bi) + elif bi.is_nonnegative: + nonneg.append(bi) + elif bi.is_polar: + nonneg.append( + bi) # polar can be treated like non-negative + else: + unk.append(bi) + if len(unk) == 1 and not neg or len(neg) == 1 and not unk: + # a single neg or a single unk can join the rest + nonneg.extend(unk + neg) + unk = neg = [] + elif neg: + # their negative signs cancel in groups of 2*q if we know + # that e = p/q else we have to treat them as unknown + israt = False + if e.is_Rational: + israt = True + else: + p, d = e.as_numer_denom() + if p.is_integer and d.is_integer: + israt = True + if israt: + neg = [-w for w in neg] + unk.extend([S.NegativeOne]*len(neg)) + else: + unk.extend(neg) + neg = [] + del israt + + # these shouldn't be joined + for b in unk: + c_powers[b].append(e) + # here is a new joined base + new_base = expr.func(*(nonneg + neg)) + # if there are positive parts they will just get separated + # again unless some change is made + + def _terms(e): + # return the number of terms of this expression + # when multiplied out -- assuming no joining of terms + if e.is_Add: + return sum(_terms(ai) for ai in e.args) + if e.is_Mul: + return prod([_terms(mi) for mi in e.args]) + return 1 + xnew_base = expand_mul(new_base, deep=False) + if len(Add.make_args(xnew_base)) < _terms(new_base): + new_base = factor_terms(xnew_base) + + c_powers[new_base].append(e) + + # break out the powers from c_powers now + c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e] + + # we're done + return expr.func(*(c_part + nc_part)) + + else: + raise ValueError("combine must be one of ('all', 'exp', 'base').") + + +def powdenest(eq, force=False, polar=False): + r""" + Collect exponents on powers as assumptions allow. + + Explanation + =========== + + Given ``(bb**be)**e``, this can be simplified as follows: + * if ``bb`` is positive, or + * ``e`` is an integer, or + * ``|be| < 1`` then this simplifies to ``bb**(be*e)`` + + Given a product of powers raised to a power, ``(bb1**be1 * + bb2**be2...)**e``, simplification can be done as follows: + + - if e is positive, the gcd of all bei can be joined with e; + - all non-negative bb can be separated from those that are negative + and their gcd can be joined with e; autosimplification already + handles this separation. + - integer factors from powers that have integers in the denominator + of the exponent can be removed from any term and the gcd of such + integers can be joined with e + + Setting ``force`` to ``True`` will make symbols that are not explicitly + negative behave as though they are positive, resulting in more + denesting. + + Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of + the logarithm, also resulting in more denestings. + + When there are sums of logs in exp() then a product of powers may be + obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``. + + Examples + ======== + + >>> from sympy.abc import a, b, x, y, z + >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest + + >>> powdenest((x**(2*a/3))**(3*x)) + (x**(2*a/3))**(3*x) + >>> powdenest(exp(3*x*log(2))) + 2**(3*x) + + Assumptions may prevent expansion: + + >>> powdenest(sqrt(x**2)) + sqrt(x**2) + + >>> p = symbols('p', positive=True) + >>> powdenest(sqrt(p**2)) + p + + No other expansion is done. + + >>> i, j = symbols('i,j', integer=True) + >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j + x**(x*(i + j)) + + But exp() will be denested by moving all non-log terms outside of + the function; this may result in the collapsing of the exp to a power + with a different base: + + >>> powdenest(exp(3*y*log(x))) + x**(3*y) + >>> powdenest(exp(y*(log(a) + log(b)))) + (a*b)**y + >>> powdenest(exp(3*(log(a) + log(b)))) + a**3*b**3 + + If assumptions allow, symbols can also be moved to the outermost exponent: + + >>> i = Symbol('i', integer=True) + >>> powdenest(((x**(2*i))**(3*y))**x) + ((x**(2*i))**(3*y))**x + >>> powdenest(((x**(2*i))**(3*y))**x, force=True) + x**(6*i*x*y) + + >>> powdenest(((x**(2*a/3))**(3*y/i))**x) + ((x**(2*a/3))**(3*y/i))**x + >>> powdenest((x**(2*i)*y**(4*i))**z, force=True) + (x*y**2)**(2*i*z) + + >>> n = Symbol('n', negative=True) + + >>> powdenest((x**i)**y, force=True) + x**(i*y) + >>> powdenest((n**i)**x, force=True) + (n**i)**x + + """ + from sympy.simplify.simplify import posify + + if force: + def _denest(b, e): + if not isinstance(b, (Pow, exp)): + return b.is_positive, Pow(b, e, evaluate=False) + return _denest(b.base, b.exp*e) + reps = [] + for p in eq.atoms(Pow, exp): + if isinstance(p.base, (Pow, exp)): + ok, dp = _denest(*p.args) + if ok is not False: + reps.append((p, dp)) + if reps: + eq = eq.subs(reps) + eq, reps = posify(eq) + return powdenest(eq, force=False, polar=polar).xreplace(reps) + + if polar: + eq, rep = polarify(eq) + return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep) + + new = powsimp(eq) + return new.xreplace(Transform( + _denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp))) + +_y = Dummy('y') + + +def _denest_pow(eq): + """ + Denest powers. + + This is a helper function for powdenest that performs the actual + transformation. + """ + from sympy.simplify.simplify import logcombine + + b, e = eq.as_base_exp() + if b.is_Pow or isinstance(b, exp) and e != 1: + new = b._eval_power(e) + if new is not None: + eq = new + b, e = new.as_base_exp() + + # denest exp with log terms in exponent + if b is S.Exp1 and e.is_Mul: + logs = [] + other = [] + for ei in e.args: + if any(isinstance(ai, log) for ai in Add.make_args(ei)): + logs.append(ei) + else: + other.append(ei) + logs = logcombine(Mul(*logs)) + return Pow(exp(logs), Mul(*other)) + + _, be = b.as_base_exp() + if be is S.One and not (b.is_Mul or + b.is_Rational and b.q != 1 or + b.is_positive): + return eq + + # denest eq which is either pos**e or Pow**e or Mul**e or + # Mul(b1**e1, b2**e2) + + # handle polar numbers specially + polars, nonpolars = [], [] + for bb in Mul.make_args(b): + if bb.is_polar: + polars.append(bb.as_base_exp()) + else: + nonpolars.append(bb) + if len(polars) == 1 and not polars[0][0].is_Mul: + return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e) + elif polars: + return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \ + *powdenest(Mul(*nonpolars)**e) + + if b.is_Integer: + # use log to see if there is a power here + logb = expand_log(log(b)) + if logb.is_Mul: + c, logb = logb.args + e *= c + base = logb.args[0] + return Pow(base, e) + + # if b is not a Mul or any factor is an atom then there is nothing to do + if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)): + return eq + + # let log handle the case of the base of the argument being a Mul, e.g. + # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we + # will take the log, expand it, and then factor out the common powers that + # now appear as coefficient. We do this manually since terms_gcd pulls out + # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2; + # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but + # we want 3*x. Neither work with noncommutatives. + + def nc_gcd(aa, bb): + a, b = [i.as_coeff_Mul() for i in [aa, bb]] + c = gcd(a[0], b[0]).as_numer_denom()[0] + g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0])) + return _keep_coeff(c, g) + + glogb = expand_log(log(b)) + if glogb.is_Add: + args = glogb.args + g = reduce(nc_gcd, args) + if g != 1: + cg, rg = g.as_coeff_Mul() + glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args])) + + # now put the log back together again + if isinstance(glogb, log) or not glogb.is_Mul: + if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp): + glogb = _denest_pow(glogb.args[0]) + if (abs(glogb.exp) < 1) == True: + return Pow(glogb.base, glogb.exp*e) + return eq + + # the log(b) was a Mul so join any adds with logcombine + add = [] + other = [] + for a in glogb.args: + if a.is_Add: + add.append(a) + else: + other.append(a) + return Pow(exp(logcombine(Mul(*add))), e*Mul(*other)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/radsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/radsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..c878168ebfbc29fc632577d6325befc120c26f56 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/radsimp.py @@ -0,0 +1,1234 @@ +from collections import defaultdict + +from sympy.core import sympify, S, Mul, Derivative, Pow +from sympy.core.add import _unevaluated_Add, Add +from sympy.core.assumptions import assumptions +from sympy.core.exprtools import Factors, gcd_terms +from sympy.core.function import _mexpand, expand_mul, expand_power_base +from sympy.core.mul import _keep_coeff, _unevaluated_Mul, _mulsort +from sympy.core.numbers import Rational, zoo, nan +from sympy.core.parameters import global_parameters +from sympy.core.sorting import ordered, default_sort_key +from sympy.core.symbol import Dummy, Wild, symbols +from sympy.functions import exp, sqrt, log +from sympy.functions.elementary.complexes import Abs +from sympy.polys import gcd +from sympy.simplify.sqrtdenest import sqrtdenest +from sympy.utilities.iterables import iterable, sift + + + + +def collect(expr, syms, func=None, evaluate=None, exact=False, distribute_order_term=True): + """ + Collect additive terms of an expression. + + Explanation + =========== + + This function collects additive terms of an expression with respect + to a list of expression up to powers with rational exponents. By the + term symbol here are meant arbitrary expressions, which can contain + powers, products, sums etc. In other words symbol is a pattern which + will be searched for in the expression's terms. + + The input expression is not expanded by :func:`collect`, so user is + expected to provide an expression in an appropriate form. This makes + :func:`collect` more predictable as there is no magic happening behind the + scenes. However, it is important to note, that powers of products are + converted to products of powers using the :func:`~.expand_power_base` + function. + + There are two possible types of output. First, if ``evaluate`` flag is + set, this function will return an expression with collected terms or + else it will return a dictionary with expressions up to rational powers + as keys and collected coefficients as values. + + Examples + ======== + + >>> from sympy import S, collect, expand, factor, Wild + >>> from sympy.abc import a, b, c, x, y + + This function can collect symbolic coefficients in polynomials or + rational expressions. It will manage to find all integer or rational + powers of collection variable:: + + >>> collect(a*x**2 + b*x**2 + a*x - b*x + c, x) + c + x**2*(a + b) + x*(a - b) + + The same result can be achieved in dictionary form:: + + >>> d = collect(a*x**2 + b*x**2 + a*x - b*x + c, x, evaluate=False) + >>> d[x**2] + a + b + >>> d[x] + a - b + >>> d[S.One] + c + + You can also work with multivariate polynomials. However, remember that + this function is greedy so it will care only about a single symbol at time, + in specification order:: + + >>> collect(x**2 + y*x**2 + x*y + y + a*y, [x, y]) + x**2*(y + 1) + x*y + y*(a + 1) + + Also more complicated expressions can be used as patterns:: + + >>> from sympy import sin, log + >>> collect(a*sin(2*x) + b*sin(2*x), sin(2*x)) + (a + b)*sin(2*x) + + >>> collect(a*x*log(x) + b*(x*log(x)), x*log(x)) + x*(a + b)*log(x) + + You can use wildcards in the pattern:: + + >>> w = Wild('w1') + >>> collect(a*x**y - b*x**y, w**y) + x**y*(a - b) + + It is also possible to work with symbolic powers, although it has more + complicated behavior, because in this case power's base and symbolic part + of the exponent are treated as a single symbol:: + + >>> collect(a*x**c + b*x**c, x) + a*x**c + b*x**c + >>> collect(a*x**c + b*x**c, x**c) + x**c*(a + b) + + However if you incorporate rationals to the exponents, then you will get + well known behavior:: + + >>> collect(a*x**(2*c) + b*x**(2*c), x**c) + x**(2*c)*(a + b) + + Note also that all previously stated facts about :func:`collect` function + apply to the exponential function, so you can get:: + + >>> from sympy import exp + >>> collect(a*exp(2*x) + b*exp(2*x), exp(x)) + (a + b)*exp(2*x) + + If you are interested only in collecting specific powers of some symbols + then set ``exact`` flag to True:: + + >>> collect(a*x**7 + b*x**7, x, exact=True) + a*x**7 + b*x**7 + >>> collect(a*x**7 + b*x**7, x**7, exact=True) + x**7*(a + b) + + If you want to collect on any object containing symbols, set + ``exact`` to None: + + >>> collect(x*exp(x) + sin(x)*y + sin(x)*2 + 3*x, x, exact=None) + x*exp(x) + 3*x + (y + 2)*sin(x) + >>> collect(a*x*y + x*y + b*x + x, [x, y], exact=None) + x*y*(a + 1) + x*(b + 1) + + You can also apply this function to differential equations, where + derivatives of arbitrary order can be collected. Note that if you + collect with respect to a function or a derivative of a function, all + derivatives of that function will also be collected. Use + ``exact=True`` to prevent this from happening:: + + >>> from sympy import Derivative as D, collect, Function + >>> f = Function('f') (x) + + >>> collect(a*D(f,x) + b*D(f,x), D(f,x)) + (a + b)*Derivative(f(x), x) + + >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), f) + (a + b)*Derivative(f(x), (x, 2)) + + >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), D(f,x), exact=True) + a*Derivative(f(x), (x, 2)) + b*Derivative(f(x), (x, 2)) + + >>> collect(a*D(f,x) + b*D(f,x) + a*f + b*f, f) + (a + b)*f(x) + (a + b)*Derivative(f(x), x) + + Or you can even match both derivative order and exponent at the same time:: + + >>> collect(a*D(D(f,x),x)**2 + b*D(D(f,x),x)**2, D(f,x)) + (a + b)*Derivative(f(x), (x, 2))**2 + + Finally, you can apply a function to each of the collected coefficients. + For example you can factorize symbolic coefficients of polynomial:: + + >>> f = expand((x + a + 1)**3) + + >>> collect(f, x, factor) + x**3 + 3*x**2*(a + 1) + 3*x*(a + 1)**2 + (a + 1)**3 + + .. note:: Arguments are expected to be in expanded form, so you might have + to call :func:`~.expand` prior to calling this function. + + See Also + ======== + + collect_const, collect_sqrt, rcollect + """ + expr = sympify(expr) + syms = [sympify(i) for i in (syms if iterable(syms) else [syms])] + + # replace syms[i] if it is not x, -x or has Wild symbols + cond = lambda x: x.is_Symbol or (-x).is_Symbol or bool( + x.atoms(Wild)) + _, nonsyms = sift(syms, cond, binary=True) + if nonsyms: + reps = dict(zip(nonsyms, [Dummy(**assumptions(i)) for i in nonsyms])) + syms = [reps.get(s, s) for s in syms] + rv = collect(expr.subs(reps), syms, + func=func, evaluate=evaluate, exact=exact, + distribute_order_term=distribute_order_term) + urep = {v: k for k, v in reps.items()} + if not isinstance(rv, dict): + return rv.xreplace(urep) + else: + return {urep.get(k, k).xreplace(urep): v.xreplace(urep) + for k, v in rv.items()} + + # see if other expressions should be considered + if exact is None: + _syms = set() + for i in Add.make_args(expr): + if not i.has_free(*syms) or i in syms: + continue + if not i.is_Mul and i not in syms: + _syms.add(i) + else: + # identify compound generators + g = i._new_rawargs(*i.as_coeff_mul(*syms)[1]) + if g not in syms: + _syms.add(g) + simple = all(i.is_Pow and i.base in syms for i in _syms) + syms = syms + list(ordered(_syms)) + if not simple: + return collect(expr, syms, + func=func, evaluate=evaluate, exact=False, + distribute_order_term=distribute_order_term) + + if evaluate is None: + evaluate = global_parameters.evaluate + + def make_expression(terms): + product = [] + + for term, rat, sym, deriv in terms: + if deriv is not None: + var, order = deriv + for _ in range(order): + term = Derivative(term, var) + + if sym is None: + if rat is S.One: + product.append(term) + else: + product.append(Pow(term, rat)) + else: + product.append(Pow(term, rat*sym)) + + return Mul(*product) + + def parse_derivative(deriv): + # scan derivatives tower in the input expression and return + # underlying function and maximal differentiation order + expr, sym, order = deriv.expr, deriv.variables[0], 1 + + for s in deriv.variables[1:]: + if s == sym: + order += 1 + else: + raise NotImplementedError( + 'Improve MV Derivative support in collect') + + while isinstance(expr, Derivative): + s0 = expr.variables[0] + + if any(s != s0 for s in expr.variables): + raise NotImplementedError( + 'Improve MV Derivative support in collect') + + if s0 == sym: + expr, order = expr.expr, order + len(expr.variables) + else: + break + + return expr, (sym, Rational(order)) + + def parse_term(expr): + """Parses expression expr and outputs tuple (sexpr, rat_expo, + sym_expo, deriv) + where: + - sexpr is the base expression + - rat_expo is the rational exponent that sexpr is raised to + - sym_expo is the symbolic exponent that sexpr is raised to + - deriv contains the derivatives of the expression + + For example, the output of x would be (x, 1, None, None) + the output of 2**x would be (2, 1, x, None). + """ + rat_expo, sym_expo = S.One, None + sexpr, deriv = expr, None + + if expr.is_Pow: + if isinstance(expr.base, Derivative): + sexpr, deriv = parse_derivative(expr.base) + else: + sexpr = expr.base + + if expr.base == S.Exp1: + arg = expr.exp + if arg.is_Rational: + sexpr, rat_expo = S.Exp1, arg + elif arg.is_Mul: + coeff, tail = arg.as_coeff_Mul(rational=True) + sexpr, rat_expo = exp(tail), coeff + + elif expr.exp.is_Number: + rat_expo = expr.exp + else: + coeff, tail = expr.exp.as_coeff_Mul() + + if coeff.is_Number: + rat_expo, sym_expo = coeff, tail + else: + sym_expo = expr.exp + elif isinstance(expr, exp): + arg = expr.exp + if arg.is_Rational: + sexpr, rat_expo = S.Exp1, arg + elif arg.is_Mul: + coeff, tail = arg.as_coeff_Mul(rational=True) + sexpr, rat_expo = exp(tail), coeff + elif isinstance(expr, Derivative): + sexpr, deriv = parse_derivative(expr) + + return sexpr, rat_expo, sym_expo, deriv + + def parse_expression(terms, pattern): + """Parse terms searching for a pattern. + Terms is a list of tuples as returned by parse_terms; + Pattern is an expression treated as a product of factors. + """ + pattern = Mul.make_args(pattern) + + if len(terms) < len(pattern): + # pattern is longer than matched product + # so no chance for positive parsing result + return None + else: + pattern = [parse_term(elem) for elem in pattern] + + terms = terms[:] # need a copy + elems, common_expo, has_deriv = [], None, False + + for elem, e_rat, e_sym, e_ord in pattern: + + if elem.is_Number and e_rat == 1 and e_sym is None: + # a constant is a match for everything + continue + + for j in range(len(terms)): + if terms[j] is None: + continue + + term, t_rat, t_sym, t_ord = terms[j] + + # keeping track of whether one of the terms had + # a derivative or not as this will require rebuilding + # the expression later + if t_ord is not None: + has_deriv = True + + if (term.match(elem) is not None and + (t_sym == e_sym or t_sym is not None and + e_sym is not None and + t_sym.match(e_sym) is not None)): + if exact is False: + # we don't have to be exact so find common exponent + # for both expression's term and pattern's element + expo = t_rat / e_rat + + if common_expo is None: + # first time + common_expo = expo + else: + # common exponent was negotiated before so + # there is no chance for a pattern match unless + # common and current exponents are equal + if common_expo != expo: + common_expo = 1 + else: + # we ought to be exact so all fields of + # interest must match in every details + if e_rat != t_rat or e_ord != t_ord: + continue + + # found common term so remove it from the expression + # and try to match next element in the pattern + elems.append(terms[j]) + terms[j] = None + + break + + else: + # pattern element not found + return None + + return [_f for _f in terms if _f], elems, common_expo, has_deriv + + if evaluate: + if expr.is_Add: + o = expr.getO() or 0 + expr = expr.func(*[ + collect(a, syms, func, True, exact, distribute_order_term) + for a in expr.args if a != o]) + o + elif expr.is_Mul: + return expr.func(*[ + collect(term, syms, func, True, exact, distribute_order_term) + for term in expr.args]) + elif expr.is_Pow: + b = collect( + expr.base, syms, func, True, exact, distribute_order_term) + return Pow(b, expr.exp) + + syms = [expand_power_base(i, deep=False) for i in syms] + + order_term = None + + if distribute_order_term: + order_term = expr.getO() + + if order_term is not None: + if order_term.has(*syms): + order_term = None + else: + expr = expr.removeO() + + summa = [expand_power_base(i, deep=False) for i in Add.make_args(expr)] + + collected, disliked = defaultdict(list), S.Zero + for product in summa: + c, nc = product.args_cnc(split_1=False) + args = list(ordered(c)) + nc + terms = [parse_term(i) for i in args] + small_first = True + + for symbol in syms: + if isinstance(symbol, Derivative) and small_first: + terms = list(reversed(terms)) + small_first = not small_first + result = parse_expression(terms, symbol) + + if result is not None: + if not symbol.is_commutative: + raise AttributeError("Can not collect noncommutative symbol") + + terms, elems, common_expo, has_deriv = result + + # when there was derivative in current pattern we + # will need to rebuild its expression from scratch + if not has_deriv: + margs = [] + for elem in elems: + if elem[2] is None: + e = elem[1] + else: + e = elem[1]*elem[2] + margs.append(Pow(elem[0], e)) + index = Mul(*margs) + else: + index = make_expression(elems) + terms = expand_power_base(make_expression(terms), deep=False) + index = expand_power_base(index, deep=False) + collected[index].append(terms) + break + else: + # none of the patterns matched + disliked += product + # add terms now for each key + collected = {k: Add(*v) for k, v in collected.items()} + + if disliked is not S.Zero: + collected[S.One] = disliked + + if order_term is not None: + for key, val in collected.items(): + collected[key] = val + order_term + + if func is not None: + collected = { + key: func(val) for key, val in collected.items()} + + if evaluate: + return Add(*[key*val for key, val in collected.items()]) + else: + return collected + + +def rcollect(expr, *vars): + """ + Recursively collect sums in an expression. + + Examples + ======== + + >>> from sympy.simplify import rcollect + >>> from sympy.abc import x, y + + >>> expr = (x**2*y + x*y + x + y)/(x + y) + + >>> rcollect(expr, y) + (x + y*(x**2 + x + 1))/(x + y) + + See Also + ======== + + collect, collect_const, collect_sqrt + """ + if expr.is_Atom or not expr.has(*vars): + return expr + else: + expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args]) + + if expr.is_Add: + return collect(expr, vars) + else: + return expr + + +def collect_sqrt(expr, evaluate=None): + """Return expr with terms having common square roots collected together. + If ``evaluate`` is False a count indicating the number of sqrt-containing + terms will be returned and, if non-zero, the terms of the Add will be + returned, else the expression itself will be returned as a single term. + If ``evaluate`` is True, the expression with any collected terms will be + returned. + + Note: since I = sqrt(-1), it is collected, too. + + Examples + ======== + + >>> from sympy import sqrt + >>> from sympy.simplify.radsimp import collect_sqrt + >>> from sympy.abc import a, b + + >>> r2, r3, r5 = [sqrt(i) for i in [2, 3, 5]] + >>> collect_sqrt(a*r2 + b*r2) + sqrt(2)*(a + b) + >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r3) + sqrt(2)*(a + b) + sqrt(3)*(a + b) + >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5) + sqrt(3)*a + sqrt(5)*b + sqrt(2)*(a + b) + + If evaluate is False then the arguments will be sorted and + returned as a list and a count of the number of sqrt-containing + terms will be returned: + + >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5, evaluate=False) + ((sqrt(3)*a, sqrt(5)*b, sqrt(2)*(a + b)), 3) + >>> collect_sqrt(a*sqrt(2) + b, evaluate=False) + ((b, sqrt(2)*a), 1) + >>> collect_sqrt(a + b, evaluate=False) + ((a + b,), 0) + + See Also + ======== + + collect, collect_const, rcollect + """ + if evaluate is None: + evaluate = global_parameters.evaluate + # this step will help to standardize any complex arguments + # of sqrts + coeff, expr = expr.as_content_primitive() + vars = set() + for a in Add.make_args(expr): + for m in a.args_cnc()[0]: + if m.is_number and ( + m.is_Pow and m.exp.is_Rational and m.exp.q == 2 or + m is S.ImaginaryUnit): + vars.add(m) + + # we only want radicals, so exclude Number handling; in this case + # d will be evaluated + d = collect_const(expr, *vars, Numbers=False) + hit = expr != d + + if not evaluate: + nrad = 0 + # make the evaluated args canonical + args = list(ordered(Add.make_args(d))) + for i, m in enumerate(args): + c, nc = m.args_cnc() + for ci in c: + # XXX should this be restricted to ci.is_number as above? + if ci.is_Pow and ci.exp.is_Rational and ci.exp.q == 2 or \ + ci is S.ImaginaryUnit: + nrad += 1 + break + args[i] *= coeff + if not (hit or nrad): + args = [Add(*args)] + return tuple(args), nrad + + return coeff*d + + +def collect_abs(expr): + """Return ``expr`` with arguments of multiple Abs in a term collected + under a single instance. + + Examples + ======== + + >>> from sympy.simplify.radsimp import collect_abs + >>> from sympy.abc import x + >>> collect_abs(abs(x + 1)/abs(x**2 - 1)) + Abs((x + 1)/(x**2 - 1)) + >>> collect_abs(abs(1/x)) + Abs(1/x) + """ + def _abs(mul): + c, nc = mul.args_cnc() + a = [] + o = [] + for i in c: + if isinstance(i, Abs): + a.append(i.args[0]) + elif isinstance(i, Pow) and isinstance(i.base, Abs) and i.exp.is_real: + a.append(i.base.args[0]**i.exp) + else: + o.append(i) + if len(a) < 2 and not any(i.exp.is_negative for i in a if isinstance(i, Pow)): + return mul + absarg = Mul(*a) + A = Abs(absarg) + args = [A] + args.extend(o) + if not A.has(Abs): + args.extend(nc) + return Mul(*args) + if not isinstance(A, Abs): + # reevaluate and make it unevaluated + A = Abs(absarg, evaluate=False) + args[0] = A + _mulsort(args) + args.extend(nc) # nc always go last + return Mul._from_args(args, is_commutative=not nc) + + return expr.replace( + lambda x: isinstance(x, Mul), + lambda x: _abs(x)).replace( + lambda x: isinstance(x, Pow), + lambda x: _abs(x)) + + +def collect_const(expr, *vars, Numbers=True): + """A non-greedy collection of terms with similar number coefficients in + an Add expr. If ``vars`` is given then only those constants will be + targeted. Although any Number can also be targeted, if this is not + desired set ``Numbers=False`` and no Float or Rational will be collected. + + Parameters + ========== + + expr : SymPy expression + This parameter defines the expression the expression from which + terms with similar coefficients are to be collected. A non-Add + expression is returned as it is. + + vars : variable length collection of Numbers, optional + Specifies the constants to target for collection. Can be multiple in + number. + + Numbers : bool + Specifies to target all instance of + :class:`sympy.core.numbers.Number` class. If ``Numbers=False``, then + no Float or Rational will be collected. + + Returns + ======= + + expr : Expr + Returns an expression with similar coefficient terms collected. + + Examples + ======== + + >>> from sympy import sqrt + >>> from sympy.abc import s, x, y, z + >>> from sympy.simplify.radsimp import collect_const + >>> collect_const(sqrt(3) + sqrt(3)*(1 + sqrt(2))) + sqrt(3)*(sqrt(2) + 2) + >>> collect_const(sqrt(3)*s + sqrt(7)*s + sqrt(3) + sqrt(7)) + (sqrt(3) + sqrt(7))*(s + 1) + >>> s = sqrt(2) + 2 + >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7)) + (sqrt(2) + 3)*(sqrt(3) + sqrt(7)) + >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7), sqrt(3)) + sqrt(7) + sqrt(3)*(sqrt(2) + 3) + sqrt(7)*(sqrt(2) + 2) + + The collection is sign-sensitive, giving higher precedence to the + unsigned values: + + >>> collect_const(x - y - z) + x - (y + z) + >>> collect_const(-y - z) + -(y + z) + >>> collect_const(2*x - 2*y - 2*z, 2) + 2*(x - y - z) + >>> collect_const(2*x - 2*y - 2*z, -2) + 2*x - 2*(y + z) + + See Also + ======== + + collect, collect_sqrt, rcollect + """ + if not expr.is_Add: + return expr + + recurse = False + + if not vars: + recurse = True + vars = set() + for a in expr.args: + for m in Mul.make_args(a): + if m.is_number: + vars.add(m) + else: + vars = sympify(vars) + if not Numbers: + vars = [v for v in vars if not v.is_Number] + + vars = list(ordered(vars)) + for v in vars: + terms = defaultdict(list) + Fv = Factors(v) + for m in Add.make_args(expr): + f = Factors(m) + q, r = f.div(Fv) + if r.is_one: + # only accept this as a true factor if + # it didn't change an exponent from an Integer + # to a non-Integer, e.g. 2/sqrt(2) -> sqrt(2) + # -- we aren't looking for this sort of change + fwas = f.factors.copy() + fnow = q.factors + if not any(k in fwas and fwas[k].is_Integer and not + fnow[k].is_Integer for k in fnow): + terms[v].append(q.as_expr()) + continue + terms[S.One].append(m) + + args = [] + hit = False + uneval = False + for k in ordered(terms): + v = terms[k] + if k is S.One: + args.extend(v) + continue + + if len(v) > 1: + v = Add(*v) + hit = True + if recurse and v != expr: + vars.append(v) + else: + v = v[0] + + # be careful not to let uneval become True unless + # it must be because it's going to be more expensive + # to rebuild the expression as an unevaluated one + if Numbers and k.is_Number and v.is_Add: + args.append(_keep_coeff(k, v, sign=True)) + uneval = True + else: + args.append(k*v) + + if hit: + if uneval: + expr = _unevaluated_Add(*args) + else: + expr = Add(*args) + if not expr.is_Add: + break + + return expr + + +def radsimp(expr, symbolic=True, max_terms=4): + r""" + Rationalize the denominator by removing square roots. + + Explanation + =========== + + The expression returned from radsimp must be used with caution + since if the denominator contains symbols, it will be possible to make + substitutions that violate the assumptions of the simplification process: + that for a denominator matching a + b*sqrt(c), a != +/-b*sqrt(c). (If + there are no symbols, this assumptions is made valid by collecting terms + of sqrt(c) so the match variable ``a`` does not contain ``sqrt(c)``.) If + you do not want the simplification to occur for symbolic denominators, set + ``symbolic`` to False. + + If there are more than ``max_terms`` radical terms then the expression is + returned unchanged. + + Examples + ======== + + >>> from sympy import radsimp, sqrt, Symbol, pprint + >>> from sympy import factor_terms, fraction, signsimp + >>> from sympy.simplify.radsimp import collect_sqrt + >>> from sympy.abc import a, b, c + + >>> radsimp(1/(2 + sqrt(2))) + (2 - sqrt(2))/2 + >>> x,y = map(Symbol, 'xy') + >>> e = ((2 + 2*sqrt(2))*x + (2 + sqrt(8))*y)/(2 + sqrt(2)) + >>> radsimp(e) + sqrt(2)*(x + y) + + No simplification beyond removal of the gcd is done. One might + want to polish the result a little, however, by collecting + square root terms: + + >>> r2 = sqrt(2) + >>> r5 = sqrt(5) + >>> ans = radsimp(1/(y*r2 + x*r2 + a*r5 + b*r5)); pprint(ans) + ___ ___ ___ ___ + \/ 5 *a + \/ 5 *b - \/ 2 *x - \/ 2 *y + ------------------------------------------ + 2 2 2 2 + 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y + + >>> n, d = fraction(ans) + >>> pprint(factor_terms(signsimp(collect_sqrt(n))/d, radical=True)) + ___ ___ + \/ 5 *(a + b) - \/ 2 *(x + y) + ------------------------------------------ + 2 2 2 2 + 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y + + If radicals in the denominator cannot be removed or there is no denominator, + the original expression will be returned. + + >>> radsimp(sqrt(2)*x + sqrt(2)) + sqrt(2)*x + sqrt(2) + + Results with symbols will not always be valid for all substitutions: + + >>> eq = 1/(a + b*sqrt(c)) + >>> eq.subs(a, b*sqrt(c)) + 1/(2*b*sqrt(c)) + >>> radsimp(eq).subs(a, b*sqrt(c)) + nan + + If ``symbolic=False``, symbolic denominators will not be transformed (but + numeric denominators will still be processed): + + >>> radsimp(eq, symbolic=False) + 1/(a + b*sqrt(c)) + + """ + from sympy.core.expr import Expr + from sympy.simplify.simplify import signsimp + + syms = symbols("a:d A:D") + def _num(rterms): + # return the multiplier that will simplify the expression described + # by rterms [(sqrt arg, coeff), ... ] + a, b, c, d, A, B, C, D = syms + if len(rterms) == 2: + reps = dict(list(zip([A, a, B, b], [j for i in rterms for j in i]))) + return ( + sqrt(A)*a - sqrt(B)*b).xreplace(reps) + if len(rterms) == 3: + reps = dict(list(zip([A, a, B, b, C, c], [j for i in rterms for j in i]))) + return ( + (sqrt(A)*a + sqrt(B)*b - sqrt(C)*c)*(2*sqrt(A)*sqrt(B)*a*b - A*a**2 - + B*b**2 + C*c**2)).xreplace(reps) + elif len(rterms) == 4: + reps = dict(list(zip([A, a, B, b, C, c, D, d], [j for i in rterms for j in i]))) + return ((sqrt(A)*a + sqrt(B)*b - sqrt(C)*c - sqrt(D)*d)*(2*sqrt(A)*sqrt(B)*a*b + - A*a**2 - B*b**2 - 2*sqrt(C)*sqrt(D)*c*d + C*c**2 + + D*d**2)*(-8*sqrt(A)*sqrt(B)*sqrt(C)*sqrt(D)*a*b*c*d + A**2*a**4 - + 2*A*B*a**2*b**2 - 2*A*C*a**2*c**2 - 2*A*D*a**2*d**2 + B**2*b**4 - + 2*B*C*b**2*c**2 - 2*B*D*b**2*d**2 + C**2*c**4 - 2*C*D*c**2*d**2 + + D**2*d**4)).xreplace(reps) + elif len(rterms) == 1: + return sqrt(rterms[0][0]) + else: + raise NotImplementedError + + def ispow2(d, log2=False): + if not d.is_Pow: + return False + e = d.exp + if e.is_Rational and e.q == 2 or symbolic and denom(e) == 2: + return True + if log2: + q = 1 + if e.is_Rational: + q = e.q + elif symbolic: + d = denom(e) + if d.is_Integer: + q = d + if q != 1 and log(q, 2).is_Integer: + return True + return False + + def handle(expr): + # Handle first reduces to the case + # expr = 1/d, where d is an add, or d is base**p/2. + # We do this by recursively calling handle on each piece. + from sympy.simplify.simplify import nsimplify + + if expr.is_Atom: + return expr + elif not isinstance(expr, Expr): + return expr.func(*[handle(a) for a in expr.args]) + + n, d = fraction(expr) + + if d.is_Atom and n.is_Atom: + return expr + elif not n.is_Atom: + n = n.func(*[handle(a) for a in n.args]) + return _unevaluated_Mul(n, handle(1/d)) + elif n is not S.One: + return _unevaluated_Mul(n, handle(1/d)) + elif d.is_Mul: + return _unevaluated_Mul(*[handle(1/d) for d in d.args]) + + # By this step, expr is 1/d, and d is not a mul. + if not symbolic and d.free_symbols: + return expr + + if ispow2(d): + d2 = sqrtdenest(sqrt(d.base))**numer(d.exp) + if d2 != d: + return handle(1/d2) + elif d.is_Pow and (d.exp.is_integer or d.base.is_positive): + # (1/d**i) = (1/d)**i + return handle(1/d.base)**d.exp + + if not (d.is_Add or ispow2(d)): + return 1/d.func(*[handle(a) for a in d.args]) + + # handle 1/d treating d as an Add (though it may not be) + + keep = True # keep changes that are made + + # flatten it and collect radicals after checking for special + # conditions + d = _mexpand(d) + + # did it change? + if d.is_Atom: + return 1/d + + # is it a number that might be handled easily? + if d.is_number: + _d = nsimplify(d) + if _d.is_Number and _d.equals(d): + return 1/_d + + while True: + # collect similar terms + collected = defaultdict(list) + for m in Add.make_args(d): # d might have become non-Add + p2 = [] + other = [] + for i in Mul.make_args(m): + if ispow2(i, log2=True): + p2.append(i.base if i.exp is S.Half else i.base**(2*i.exp)) + elif i is S.ImaginaryUnit: + p2.append(S.NegativeOne) + else: + other.append(i) + collected[tuple(ordered(p2))].append(Mul(*other)) + rterms = list(ordered(list(collected.items()))) + rterms = [(Mul(*i), Add(*j)) for i, j in rterms] + nrad = len(rterms) - (1 if rterms[0][0] is S.One else 0) + if nrad < 1: + break + elif nrad > max_terms: + # there may have been invalid operations leading to this point + # so don't keep changes, e.g. this expression is troublesome + # in collecting terms so as not to raise the issue of 2834: + # r = sqrt(sqrt(5) + 5) + # eq = 1/(sqrt(5)*r + 2*sqrt(5)*sqrt(-sqrt(5) + 5) + 5*r) + keep = False + break + if len(rterms) > 4: + # in general, only 4 terms can be removed with repeated squaring + # but other considerations can guide selection of radical terms + # so that radicals are removed + if all(x.is_Integer and (y**2).is_Rational for x, y in rterms): + nd, d = rad_rationalize(S.One, Add._from_args( + [sqrt(x)*y for x, y in rterms])) + n *= nd + else: + # is there anything else that might be attempted? + keep = False + break + from sympy.simplify.powsimp import powsimp, powdenest + + num = powsimp(_num(rterms)) + n *= num + d *= num + d = powdenest(_mexpand(d), force=symbolic) + if d.has(S.Zero, nan, zoo): + return expr + if d.is_Atom: + break + + if not keep: + return expr + return _unevaluated_Mul(n, 1/d) + + if not isinstance(expr, Expr): + return expr.func(*[radsimp(a, symbolic=symbolic, max_terms=max_terms) for a in expr.args]) + + coeff, expr = expr.as_coeff_Add() + expr = expr.normal() + old = fraction(expr) + n, d = fraction(handle(expr)) + if old != (n, d): + if not d.is_Atom: + was = (n, d) + n = signsimp(n, evaluate=False) + d = signsimp(d, evaluate=False) + u = Factors(_unevaluated_Mul(n, 1/d)) + u = _unevaluated_Mul(*[k**v for k, v in u.factors.items()]) + n, d = fraction(u) + if old == (n, d): + n, d = was + n = expand_mul(n) + if d.is_Number or d.is_Add: + n2, d2 = fraction(gcd_terms(_unevaluated_Mul(n, 1/d))) + if d2.is_Number or (d2.count_ops() <= d.count_ops()): + n, d = [signsimp(i) for i in (n2, d2)] + if n.is_Mul and n.args[0].is_Number: + n = n.func(*n.args) + + return coeff + _unevaluated_Mul(n, 1/d) + + +def rad_rationalize(num, den): + """ + Rationalize ``num/den`` by removing square roots in the denominator; + num and den are sum of terms whose squares are positive rationals. + + Examples + ======== + + >>> from sympy import sqrt + >>> from sympy.simplify.radsimp import rad_rationalize + >>> rad_rationalize(sqrt(3), 1 + sqrt(2)/3) + (-sqrt(3) + sqrt(6)/3, -7/9) + """ + if not den.is_Add: + return num, den + g, a, b = split_surds(den) + a = a*sqrt(g) + num = _mexpand((a - b)*num) + den = _mexpand(a**2 - b**2) + return rad_rationalize(num, den) + + +def fraction(expr, exact=False): + """Returns a pair with expression's numerator and denominator. + If the given expression is not a fraction then this function + will return the tuple (expr, 1). + + This function will not make any attempt to simplify nested + fractions or to do any term rewriting at all. + + If only one of the numerator/denominator pair is needed then + use numer(expr) or denom(expr) functions respectively. + + >>> from sympy import fraction, Rational, Symbol + >>> from sympy.abc import x, y + + >>> fraction(x/y) + (x, y) + >>> fraction(x) + (x, 1) + + >>> fraction(1/y**2) + (1, y**2) + + >>> fraction(x*y/2) + (x*y, 2) + >>> fraction(Rational(1, 2)) + (1, 2) + + This function will also work fine with assumptions: + + >>> k = Symbol('k', negative=True) + >>> fraction(x * y**k) + (x, y**(-k)) + + If we know nothing about sign of some exponent and ``exact`` + flag is unset, then the exponent's structure will + be analyzed and pretty fraction will be returned: + + >>> from sympy import exp, Mul + >>> fraction(2*x**(-y)) + (2, x**y) + + >>> fraction(exp(-x)) + (1, exp(x)) + + >>> fraction(exp(-x), exact=True) + (exp(-x), 1) + + The ``exact`` flag will also keep any unevaluated Muls from + being evaluated: + + >>> u = Mul(2, x + 1, evaluate=False) + >>> fraction(u) + (2*x + 2, 1) + >>> fraction(u, exact=True) + (2*(x + 1), 1) + """ + expr = sympify(expr) + + numer, denom = [], [] + + for term in Mul.make_args(expr): + if term.is_commutative and (term.is_Pow or isinstance(term, exp)): + b, ex = term.as_base_exp() + if ex.is_negative: + if ex is S.NegativeOne: + denom.append(b) + elif exact: + if ex.is_constant(): + denom.append(Pow(b, -ex)) + else: + numer.append(term) + else: + denom.append(Pow(b, -ex)) + elif ex.is_positive: + numer.append(term) + elif not exact and ex.is_Mul: + n, d = term.as_numer_denom() # this will cause evaluation + if n != 1: + numer.append(n) + denom.append(d) + else: + numer.append(term) + elif term.is_Rational and not term.is_Integer: + if term.p != 1: + numer.append(term.p) + denom.append(term.q) + else: + numer.append(term) + return Mul(*numer, evaluate=not exact), Mul(*denom, evaluate=not exact) + + +def numer(expr, exact=False): # default matches fraction's default + return fraction(expr, exact=exact)[0] + + +def denom(expr, exact=False): # default matches fraction's default + return fraction(expr, exact=exact)[1] + + +def fraction_expand(expr, **hints): + return expr.expand(frac=True, **hints) + + +def numer_expand(expr, **hints): + # default matches fraction's default + a, b = fraction(expr, exact=hints.get('exact', False)) + return a.expand(numer=True, **hints) / b + + +def denom_expand(expr, **hints): + # default matches fraction's default + a, b = fraction(expr, exact=hints.get('exact', False)) + return a / b.expand(denom=True, **hints) + + +expand_numer = numer_expand +expand_denom = denom_expand +expand_fraction = fraction_expand + + +def split_surds(expr): + """ + Split an expression with terms whose squares are positive rationals + into a sum of terms whose surds squared have gcd equal to g + and a sum of terms with surds squared prime with g. + + Examples + ======== + + >>> from sympy import sqrt + >>> from sympy.simplify.radsimp import split_surds + >>> split_surds(3*sqrt(3) + sqrt(5)/7 + sqrt(6) + sqrt(10) + sqrt(15)) + (3, sqrt(2) + sqrt(5) + 3, sqrt(5)/7 + sqrt(10)) + """ + args = sorted(expr.args, key=default_sort_key) + coeff_muls = [x.as_coeff_Mul() for x in args] + surds = [x[1]**2 for x in coeff_muls if x[1].is_Pow] + surds.sort(key=default_sort_key) + g, b1, b2 = _split_gcd(*surds) + g2 = g + if not b2 and len(b1) >= 2: + b1n = [x/g for x in b1] + b1n = [x for x in b1n if x != 1] + # only a common factor has been factored; split again + g1, b1n, b2 = _split_gcd(*b1n) + g2 = g*g1 + a1v, a2v = [], [] + for c, s in coeff_muls: + if s.is_Pow and s.exp == S.Half: + s1 = s.base + if s1 in b1: + a1v.append(c*sqrt(s1/g2)) + else: + a2v.append(c*s) + else: + a2v.append(c*s) + a = Add(*a1v) + b = Add(*a2v) + return g2, a, b + + +def _split_gcd(*a): + """ + Split the list of integers ``a`` into a list of integers, ``a1`` having + ``g = gcd(a1)``, and a list ``a2`` whose elements are not divisible by + ``g``. Returns ``g, a1, a2``. + + Examples + ======== + + >>> from sympy.simplify.radsimp import _split_gcd + >>> _split_gcd(55, 35, 22, 14, 77, 10) + (5, [55, 35, 10], [22, 14, 77]) + """ + g = a[0] + b1 = [g] + b2 = [] + for x in a[1:]: + g1 = gcd(g, x) + if g1 == 1: + b2.append(x) + else: + g = g1 + b1.append(x) + return g, b1, b2 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/ratsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/ratsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..95751fab47f585d3ae2e1289f014fba0f2708224 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/ratsimp.py @@ -0,0 +1,222 @@ +from itertools import combinations_with_replacement +from sympy.core import symbols, Add, Dummy +from sympy.core.numbers import Rational +from sympy.polys import cancel, ComputationFailed, parallel_poly_from_expr, reduced, Poly +from sympy.polys.monomials import Monomial, monomial_div +from sympy.polys.polyerrors import DomainError, PolificationFailed +from sympy.utilities.misc import debug, debugf + +def ratsimp(expr): + """ + Put an expression over a common denominator, cancel and reduce. + + Examples + ======== + + >>> from sympy import ratsimp + >>> from sympy.abc import x, y + >>> ratsimp(1/x + 1/y) + (x + y)/(x*y) + """ + + f, g = cancel(expr).as_numer_denom() + try: + Q, r = reduced(f, [g], field=True, expand=False) + except ComputationFailed: + return f/g + + return Add(*Q) + cancel(r/g) + + +def ratsimpmodprime(expr, G, *gens, quick=True, polynomial=False, **args): + """ + Simplifies a rational expression ``expr`` modulo the prime ideal + generated by ``G``. ``G`` should be a Groebner basis of the + ideal. + + Examples + ======== + + >>> from sympy.simplify.ratsimp import ratsimpmodprime + >>> from sympy.abc import x, y + >>> eq = (x + y**5 + y)/(x - y) + >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex') + (-x**2 - x*y - x - y)/(-x**2 + x*y) + + If ``polynomial`` is ``False``, the algorithm computes a rational + simplification which minimizes the sum of the total degrees of + the numerator and the denominator. + + If ``polynomial`` is ``True``, this function just brings numerator and + denominator into a canonical form. This is much faster, but has + potentially worse results. + + References + ========== + + .. [1] M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial + Ideal, https://dl.acm.org/doi/pdf/10.1145/1145768.1145809 + (specifically, the second algorithm) + """ + from sympy.solvers.solvers import solve + + debug('ratsimpmodprime', expr) + + # usual preparation of polynomials: + + num, denom = cancel(expr).as_numer_denom() + + try: + polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args) + except PolificationFailed: + return expr + + domain = opt.domain + + if domain.has_assoc_Field: + opt.domain = domain.get_field() + else: + raise DomainError( + "Cannot compute rational simplification over %s" % domain) + + # compute only once + leading_monomials = [g.LM(opt.order) for g in polys[2:]] + tested = set() + + def staircase(n): + """ + Compute all monomials with degree less than ``n`` that are + not divisible by any element of ``leading_monomials``. + """ + if n == 0: + return [1] + S = [] + for mi in combinations_with_replacement(range(len(opt.gens)), n): + m = [0]*len(opt.gens) + for i in mi: + m[i] += 1 + if all(monomial_div(m, lmg) is None for lmg in + leading_monomials): + S.append(m) + + return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1) + + def _ratsimpmodprime(a, b, allsol, N=0, D=0): + r""" + Computes a rational simplification of ``a/b`` which minimizes + the sum of the total degrees of the numerator and the denominator. + + Explanation + =========== + + The algorithm proceeds by looking at ``a * d - b * c`` modulo + the ideal generated by ``G`` for some ``c`` and ``d`` with degree + less than ``a`` and ``b`` respectively. + The coefficients of ``c`` and ``d`` are indeterminates and thus + the coefficients of the normalform of ``a * d - b * c`` are + linear polynomials in these indeterminates. + If these linear polynomials, considered as system of + equations, have a nontrivial solution, then `\frac{a}{b} + \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So, + by construction, the degree of ``c`` and ``d`` is less than + the degree of ``a`` and ``b``, so a simpler representation + has been found. + After a simpler representation has been found, the algorithm + tries to reduce the degree of the numerator and denominator + and returns the result afterwards. + + As an extension, if quick=False, we look at all possible degrees such + that the total degree is less than *or equal to* the best current + solution. We retain a list of all solutions of minimal degree, and try + to find the best one at the end. + """ + c, d = a, b + steps = 0 + + maxdeg = a.total_degree() + b.total_degree() + if quick: + bound = maxdeg - 1 + else: + bound = maxdeg + while N + D <= bound: + if (N, D) in tested: + break + tested.add((N, D)) + + M1 = staircase(N) + M2 = staircase(D) + debugf('%s / %s: %s, %s', (N, D, M1, M2)) + + Cs = symbols("c:%d" % len(M1), cls=Dummy) + Ds = symbols("d:%d" % len(M2), cls=Dummy) + ng = Cs + Ds + + c_hat = Poly( + sum(Cs[i] * M1[i] for i in range(len(M1))), opt.gens + ng) + d_hat = Poly( + sum(Ds[i] * M2[i] for i in range(len(M2))), opt.gens + ng) + + r = reduced(a * d_hat - b * c_hat, G, opt.gens + ng, + order=opt.order, polys=True)[1] + + S = Poly(r, gens=opt.gens).coeffs() + sol = solve(S, Cs + Ds, particular=True, quick=True) + + if sol and not all(s == 0 for s in sol.values()): + c = c_hat.subs(sol) + d = d_hat.subs(sol) + + # The "free" variables occurring before as parameters + # might still be in the substituted c, d, so set them + # to the value chosen before: + c = c.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) + d = d.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) + + c = Poly(c, opt.gens) + d = Poly(d, opt.gens) + if d == 0: + raise ValueError('Ideal not prime?') + + allsol.append((c_hat, d_hat, S, Cs + Ds)) + if N + D != maxdeg: + allsol = [allsol[-1]] + + break + + steps += 1 + N += 1 + D += 1 + + if steps > 0: + c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps) + c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D) + + return c, d, allsol + + # preprocessing. this improves performance a bit when deg(num) + # and deg(denom) are large: + num = reduced(num, G, opt.gens, order=opt.order)[1] + denom = reduced(denom, G, opt.gens, order=opt.order)[1] + + if polynomial: + return (num/denom).cancel() + + c, d, allsol = _ratsimpmodprime( + Poly(num, opt.gens, domain=opt.domain), Poly(denom, opt.gens, domain=opt.domain), []) + if not quick and allsol: + debugf('Looking for best minimal solution. Got: %s', len(allsol)) + newsol = [] + for c_hat, d_hat, S, ng in allsol: + sol = solve(S, ng, particular=True, quick=False) + # all values of sol should be numbers; if not, solve is broken + newsol.append((c_hat.subs(sol), d_hat.subs(sol))) + c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms())) + + if not domain.is_Field: + cn, c = c.clear_denoms(convert=True) + dn, d = d.clear_denoms(convert=True) + r = Rational(cn, dn) + else: + r = Rational(1) + + return (c*r.q)/(d*r.p) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_combsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_combsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..e56758a005fbb013c2b6ea4121b16c3434a54b03 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_combsimp.py @@ -0,0 +1,75 @@ +from sympy.core.numbers import Rational +from sympy.core.symbol import symbols +from sympy.functions.combinatorial.factorials import (FallingFactorial, RisingFactorial, binomial, factorial) +from sympy.functions.special.gamma_functions import gamma +from sympy.simplify.combsimp import combsimp +from sympy.abc import x + + +def test_combsimp(): + k, m, n = symbols('k m n', integer = True) + + assert combsimp(factorial(n)) == factorial(n) + assert combsimp(binomial(n, k)) == binomial(n, k) + + assert combsimp(factorial(n)/factorial(n - 3)) == n*(-1 + n)*(-2 + n) + assert combsimp(binomial(n + 1, k + 1)/binomial(n, k)) == (1 + n)/(1 + k) + + assert combsimp(binomial(3*n + 4, n + 1)/binomial(3*n + 1, n)) == \ + Rational(3, 2)*((3*n + 2)*(3*n + 4)/((n + 1)*(2*n + 3))) + + assert combsimp(factorial(n)**2/factorial(n - 3)) == \ + factorial(n)*n*(-1 + n)*(-2 + n) + assert combsimp(factorial(n)*binomial(n + 1, k + 1)/binomial(n, k)) == \ + factorial(n + 1)/(1 + k) + + assert combsimp(gamma(n + 3)) == factorial(n + 2) + + assert combsimp(factorial(x)) == gamma(x + 1) + + # issue 9699 + assert combsimp((n + 1)*factorial(n)) == factorial(n + 1) + assert combsimp(factorial(n)/n) == factorial(n-1) + + # issue 6658 + assert combsimp(binomial(n, n - k)) == binomial(n, k) + + # issue 6341, 7135 + assert combsimp(factorial(n)/(factorial(k)*factorial(n - k))) == \ + binomial(n, k) + assert combsimp(factorial(k)*factorial(n - k)/factorial(n)) == \ + 1/binomial(n, k) + assert combsimp(factorial(2*n)/factorial(n)**2) == binomial(2*n, n) + assert combsimp(factorial(2*n)*factorial(k)*factorial(n - k)/ + factorial(n)**3) == binomial(2*n, n)/binomial(n, k) + + assert combsimp(factorial(n*(1 + n) - n**2 - n)) == 1 + + assert combsimp(6*FallingFactorial(-4, n)/factorial(n)) == \ + (-1)**n*(n + 1)*(n + 2)*(n + 3) + assert combsimp(6*FallingFactorial(-4, n - 1)/factorial(n - 1)) == \ + (-1)**(n - 1)*n*(n + 1)*(n + 2) + assert combsimp(6*FallingFactorial(-4, n - 3)/factorial(n - 3)) == \ + (-1)**(n - 3)*n*(n - 1)*(n - 2) + assert combsimp(6*FallingFactorial(-4, -n - 1)/factorial(-n - 1)) == \ + -(-1)**(-n - 1)*n*(n - 1)*(n - 2) + + assert combsimp(6*RisingFactorial(4, n)/factorial(n)) == \ + (n + 1)*(n + 2)*(n + 3) + assert combsimp(6*RisingFactorial(4, n - 1)/factorial(n - 1)) == \ + n*(n + 1)*(n + 2) + assert combsimp(6*RisingFactorial(4, n - 3)/factorial(n - 3)) == \ + n*(n - 1)*(n - 2) + assert combsimp(6*RisingFactorial(4, -n - 1)/factorial(-n - 1)) == \ + -n*(n - 1)*(n - 2) + + +def test_issue_6878(): + n = symbols('n', integer=True) + assert combsimp(RisingFactorial(-10, n)) == 3628800*(-1)**n/factorial(10 - n) + + +def test_issue_14528(): + p = symbols("p", integer=True, positive=True) + assert combsimp(binomial(1,p)) == 1/(factorial(p)*factorial(1-p)) + assert combsimp(factorial(2-p)) == factorial(2-p) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_epathtools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_epathtools.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bb47b2f2ff624077ab9905677b181c587ab5a7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_epathtools.py @@ -0,0 +1,90 @@ +"""Tests for tools for manipulation of expressions using paths. """ + +from sympy.simplify.epathtools import epath, EPath +from sympy.testing.pytest import raises + +from sympy.core.numbers import E +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.abc import x, y, z, t + + +def test_epath_select(): + expr = [((x, 1, t), 2), ((3, y, 4), z)] + + assert epath("/*", expr) == [((x, 1, t), 2), ((3, y, 4), z)] + assert epath("/*/*", expr) == [(x, 1, t), 2, (3, y, 4), z] + assert epath("/*/*/*", expr) == [x, 1, t, 3, y, 4] + assert epath("/*/*/*/*", expr) == [] + + assert epath("/[:]", expr) == [((x, 1, t), 2), ((3, y, 4), z)] + assert epath("/[:]/[:]", expr) == [(x, 1, t), 2, (3, y, 4), z] + assert epath("/[:]/[:]/[:]", expr) == [x, 1, t, 3, y, 4] + assert epath("/[:]/[:]/[:]/[:]", expr) == [] + + assert epath("/*/[:]", expr) == [(x, 1, t), 2, (3, y, 4), z] + + assert epath("/*/[0]", expr) == [(x, 1, t), (3, y, 4)] + assert epath("/*/[1]", expr) == [2, z] + assert epath("/*/[2]", expr) == [] + + assert epath("/*/int", expr) == [2] + assert epath("/*/Symbol", expr) == [z] + assert epath("/*/tuple", expr) == [(x, 1, t), (3, y, 4)] + assert epath("/*/__iter__?", expr) == [(x, 1, t), (3, y, 4)] + + assert epath("/*/int|tuple", expr) == [(x, 1, t), 2, (3, y, 4)] + assert epath("/*/Symbol|tuple", expr) == [(x, 1, t), (3, y, 4), z] + assert epath("/*/int|Symbol|tuple", expr) == [(x, 1, t), 2, (3, y, 4), z] + + assert epath("/*/int|__iter__?", expr) == [(x, 1, t), 2, (3, y, 4)] + assert epath("/*/Symbol|__iter__?", expr) == [(x, 1, t), (3, y, 4), z] + assert epath( + "/*/int|Symbol|__iter__?", expr) == [(x, 1, t), 2, (3, y, 4), z] + + assert epath("/*/[0]/int", expr) == [1, 3, 4] + assert epath("/*/[0]/Symbol", expr) == [x, t, y] + + assert epath("/*/[0]/int[1:]", expr) == [1, 4] + assert epath("/*/[0]/Symbol[1:]", expr) == [t, y] + + assert epath("/Symbol", x + y + z + 1) == [x, y, z] + assert epath("/*/*/Symbol", t + sin(x + 1) + cos(x + y + E)) == [x, x, y] + + +def test_epath_apply(): + expr = [((x, 1, t), 2), ((3, y, 4), z)] + func = lambda expr: expr**2 + + assert epath("/*", expr, list) == [[(x, 1, t), 2], [(3, y, 4), z]] + + assert epath("/*/[0]", expr, list) == [([x, 1, t], 2), ([3, y, 4], z)] + assert epath("/*/[1]", expr, func) == [((x, 1, t), 4), ((3, y, 4), z**2)] + assert epath("/*/[2]", expr, list) == expr + + assert epath("/*/[0]/int", expr, func) == [((x, 1, t), 2), ((9, y, 16), z)] + assert epath("/*/[0]/Symbol", expr, func) == [((x**2, 1, t**2), 2), + ((3, y**2, 4), z)] + assert epath( + "/*/[0]/int[1:]", expr, func) == [((x, 1, t), 2), ((3, y, 16), z)] + assert epath("/*/[0]/Symbol[1:]", expr, func) == [((x, 1, t**2), + 2), ((3, y**2, 4), z)] + + assert epath("/Symbol", x + y + z + 1, func) == x**2 + y**2 + z**2 + 1 + assert epath("/*/*/Symbol", t + sin(x + 1) + cos(x + y + E), func) == \ + t + sin(x**2 + 1) + cos(x**2 + y**2 + E) + + +def test_EPath(): + assert EPath("/*/[0]")._path == "/*/[0]" + assert EPath(EPath("/*/[0]"))._path == "/*/[0]" + assert isinstance(epath("/*/[0]"), EPath) is True + + assert repr(EPath("/*/[0]")) == "EPath('/*/[0]')" + + raises(ValueError, lambda: EPath("")) + raises(ValueError, lambda: EPath("/")) + raises(ValueError, lambda: EPath("/|x")) + raises(ValueError, lambda: EPath("/[")) + raises(ValueError, lambda: EPath("/[0]%")) + + raises(NotImplementedError, lambda: EPath("Symbol")) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_fu.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_fu.py new file mode 100644 index 0000000000000000000000000000000000000000..2de2126b7333195fceeffe72dc9cb642e7eba9a9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_fu.py @@ -0,0 +1,492 @@ +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.numbers import (I, Rational, pi) +from sympy.core.parameters import evaluate +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.elementary.hyperbolic import (cosh, coth, csch, sech, sinh, tanh) +from sympy.functions.elementary.miscellaneous import (root, sqrt) +from sympy.functions.elementary.trigonometric import (cos, cot, csc, sec, sin, tan) +from sympy.simplify.powsimp import powsimp +from sympy.simplify.fu import ( + L, TR1, TR10, TR10i, TR11, _TR11, TR12, TR12i, TR13, TR14, TR15, TR16, + TR111, TR2, TR2i, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TRmorrie, _TR56 as T, + TRpower, hyper_as_trig, fu, process_common_addends, trig_split, + as_f_sign_1) +from sympy.core.random import verify_numerically +from sympy.abc import a, b, c, x, y, z + + +def test_TR1(): + assert TR1(2*csc(x) + sec(x)) == 1/cos(x) + 2/sin(x) + + +def test_TR2(): + assert TR2(tan(x)) == sin(x)/cos(x) + assert TR2(cot(x)) == cos(x)/sin(x) + assert TR2(tan(tan(x) - sin(x)/cos(x))) == 0 + + +def test_TR2i(): + # just a reminder that ratios of powers only simplify if both + # numerator and denominator satisfy the condition that each + # has a positive base or an integer exponent; e.g. the following, + # at y=-1, x=1/2 gives sqrt(2)*I != -sqrt(2)*I + assert powsimp(2**x/y**x) != (2/y)**x + + assert TR2i(sin(x)/cos(x)) == tan(x) + assert TR2i(sin(x)*sin(y)/cos(x)) == tan(x)*sin(y) + assert TR2i(1/(sin(x)/cos(x))) == 1/tan(x) + assert TR2i(1/(sin(x)*sin(y)/cos(x))) == 1/tan(x)/sin(y) + assert TR2i(sin(x)/2/(cos(x) + 1)) == sin(x)/(cos(x) + 1)/2 + + assert TR2i(sin(x)/2/(cos(x) + 1), half=True) == tan(x/2)/2 + assert TR2i(sin(1)/(cos(1) + 1), half=True) == tan(S.Half) + assert TR2i(sin(2)/(cos(2) + 1), half=True) == tan(1) + assert TR2i(sin(4)/(cos(4) + 1), half=True) == tan(2) + assert TR2i(sin(5)/(cos(5) + 1), half=True) == tan(5*S.Half) + assert TR2i((cos(1) + 1)/sin(1), half=True) == 1/tan(S.Half) + assert TR2i((cos(2) + 1)/sin(2), half=True) == 1/tan(1) + assert TR2i((cos(4) + 1)/sin(4), half=True) == 1/tan(2) + assert TR2i((cos(5) + 1)/sin(5), half=True) == 1/tan(5*S.Half) + assert TR2i((cos(1) + 1)**(-a)*sin(1)**a, half=True) == tan(S.Half)**a + assert TR2i((cos(2) + 1)**(-a)*sin(2)**a, half=True) == tan(1)**a + assert TR2i((cos(4) + 1)**(-a)*sin(4)**a, half=True) == (cos(4) + 1)**(-a)*sin(4)**a + assert TR2i((cos(5) + 1)**(-a)*sin(5)**a, half=True) == (cos(5) + 1)**(-a)*sin(5)**a + assert TR2i((cos(1) + 1)**a*sin(1)**(-a), half=True) == tan(S.Half)**(-a) + assert TR2i((cos(2) + 1)**a*sin(2)**(-a), half=True) == tan(1)**(-a) + assert TR2i((cos(4) + 1)**a*sin(4)**(-a), half=True) == (cos(4) + 1)**a*sin(4)**(-a) + assert TR2i((cos(5) + 1)**a*sin(5)**(-a), half=True) == (cos(5) + 1)**a*sin(5)**(-a) + + i = symbols('i', integer=True) + assert TR2i(((cos(5) + 1)**i*sin(5)**(-i)), half=True) == tan(5*S.Half)**(-i) + assert TR2i(1/((cos(5) + 1)**i*sin(5)**(-i)), half=True) == tan(5*S.Half)**i + + +def test_TR3(): + assert TR3(cos(y - x*(y - x))) == cos(x*(x - y) + y) + assert cos(pi/2 + x) == -sin(x) + assert cos(30*pi/2 + x) == -cos(x) + + for f in (cos, sin, tan, cot, csc, sec): + i = f(pi*Rational(3, 7)) + j = TR3(i) + assert verify_numerically(i, j) and i.func != j.func + + with evaluate(False): + eq = cos(9*pi/22) + assert eq.has(9*pi) and TR3(eq) == sin(pi/11) + + +def test_TR4(): + for i in [0, pi/6, pi/4, pi/3, pi/2]: + with evaluate(False): + eq = cos(i) + assert isinstance(eq, cos) and TR4(eq) == cos(i) + + +def test__TR56(): + h = lambda x: 1 - x + assert T(sin(x)**3, sin, cos, h, 4, False) == sin(x)*(-cos(x)**2 + 1) + assert T(sin(x)**10, sin, cos, h, 4, False) == sin(x)**10 + assert T(sin(x)**6, sin, cos, h, 6, False) == (-cos(x)**2 + 1)**3 + assert T(sin(x)**6, sin, cos, h, 6, True) == sin(x)**6 + assert T(sin(x)**8, sin, cos, h, 10, True) == (-cos(x)**2 + 1)**4 + + # issue 17137 + assert T(sin(x)**I, sin, cos, h, 4, True) == sin(x)**I + assert T(sin(x)**(2*I + 1), sin, cos, h, 4, True) == sin(x)**(2*I + 1) + + +def test_TR5(): + assert TR5(sin(x)**2) == -cos(x)**2 + 1 + assert TR5(sin(x)**-2) == sin(x)**(-2) + assert TR5(sin(x)**4) == (-cos(x)**2 + 1)**2 + + +def test_TR6(): + assert TR6(cos(x)**2) == -sin(x)**2 + 1 + assert TR6(cos(x)**-2) == cos(x)**(-2) + assert TR6(cos(x)**4) == (-sin(x)**2 + 1)**2 + + +def test_TR7(): + assert TR7(cos(x)**2) == cos(2*x)/2 + S.Half + assert TR7(cos(x)**2 + 1) == cos(2*x)/2 + Rational(3, 2) + + +def test_TR8(): + assert TR8(cos(2)*cos(3)) == cos(5)/2 + cos(1)/2 + assert TR8(cos(2)*sin(3)) == sin(5)/2 + sin(1)/2 + assert TR8(sin(2)*sin(3)) == -cos(5)/2 + cos(1)/2 + assert TR8(sin(1)*sin(2)*sin(3)) == sin(4)/4 - sin(6)/4 + sin(2)/4 + assert TR8(cos(2)*cos(3)*cos(4)*cos(5)) == \ + cos(4)/4 + cos(10)/8 + cos(2)/8 + cos(8)/8 + cos(14)/8 + \ + cos(6)/8 + Rational(1, 8) + assert TR8(cos(2)*cos(3)*cos(4)*cos(5)*cos(6)) == \ + cos(10)/8 + cos(4)/8 + 3*cos(2)/16 + cos(16)/16 + cos(8)/8 + \ + cos(14)/16 + cos(20)/16 + cos(12)/16 + Rational(1, 16) + cos(6)/8 + assert TR8(sin(pi*Rational(3, 7))**2*cos(pi*Rational(3, 7))**2/(16*sin(pi/7)**2)) == Rational(1, 64) + +def test_TR9(): + a = S.Half + b = 3*a + assert TR9(a) == a + assert TR9(cos(1) + cos(2)) == 2*cos(a)*cos(b) + assert TR9(cos(1) - cos(2)) == 2*sin(a)*sin(b) + assert TR9(sin(1) - sin(2)) == -2*sin(a)*cos(b) + assert TR9(sin(1) + sin(2)) == 2*sin(b)*cos(a) + assert TR9(cos(1) + 2*sin(1) + 2*sin(2)) == cos(1) + 4*sin(b)*cos(a) + assert TR9(cos(4) + cos(2) + 2*cos(1)*cos(3)) == 4*cos(1)*cos(3) + assert TR9((cos(4) + cos(2))/cos(3)/2 + cos(3)) == 2*cos(1)*cos(2) + assert TR9(cos(3) + cos(4) + cos(5) + cos(6)) == \ + 4*cos(S.Half)*cos(1)*cos(Rational(9, 2)) + assert TR9(cos(3) + cos(3)*cos(2)) == cos(3) + cos(2)*cos(3) + assert TR9(-cos(y) + cos(x*y)) == -2*sin(x*y/2 - y/2)*sin(x*y/2 + y/2) + assert TR9(-sin(y) + sin(x*y)) == 2*sin(x*y/2 - y/2)*cos(x*y/2 + y/2) + c = cos(x) + s = sin(x) + for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): + for a in ((c, s), (s, c), (cos(x), cos(x*y)), (sin(x), sin(x*y))): + args = zip(si, a) + ex = Add(*[Mul(*ai) for ai in args]) + t = TR9(ex) + assert not (a[0].func == a[1].func and ( + not verify_numerically(ex, t.expand(trig=True)) or t.is_Add) + or a[1].func != a[0].func and ex != t) + + +def test_TR10(): + assert TR10(cos(a + b)) == -sin(a)*sin(b) + cos(a)*cos(b) + assert TR10(sin(a + b)) == sin(a)*cos(b) + sin(b)*cos(a) + assert TR10(sin(a + b + c)) == \ + (-sin(a)*sin(b) + cos(a)*cos(b))*sin(c) + \ + (sin(a)*cos(b) + sin(b)*cos(a))*cos(c) + assert TR10(cos(a + b + c)) == \ + (-sin(a)*sin(b) + cos(a)*cos(b))*cos(c) - \ + (sin(a)*cos(b) + sin(b)*cos(a))*sin(c) + + +def test_TR10i(): + assert TR10i(cos(1)*cos(3) + sin(1)*sin(3)) == cos(2) + assert TR10i(cos(1)*cos(3) - sin(1)*sin(3)) == cos(4) + assert TR10i(cos(1)*sin(3) - sin(1)*cos(3)) == sin(2) + assert TR10i(cos(1)*sin(3) + sin(1)*cos(3)) == sin(4) + assert TR10i(cos(1)*sin(3) + sin(1)*cos(3) + 7) == sin(4) + 7 + assert TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3)) == cos(3) + sin(4) + assert TR10i(2*cos(1)*sin(3) + 2*sin(1)*cos(3) + cos(3)) == \ + 2*sin(4) + cos(3) + assert TR10i(cos(2)*cos(3) + sin(2)*(cos(1)*sin(2) + cos(2)*sin(1))) == \ + cos(1) + eq = (cos(2)*cos(3) + sin(2)*( + cos(1)*sin(2) + cos(2)*sin(1)))*cos(5) + sin(1)*sin(5) + assert TR10i(eq) == TR10i(eq.expand()) == cos(4) + assert TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x) == \ + 2*sqrt(2)*x*sin(x + pi/6) + assert TR10i(cos(x)/sqrt(6) + sin(x)/sqrt(2) + + cos(x)/sqrt(6)/3 + sin(x)/sqrt(2)/3) == 4*sqrt(6)*sin(x + pi/6)/9 + assert TR10i(cos(x)/sqrt(6) + sin(x)/sqrt(2) + + cos(y)/sqrt(6)/3 + sin(y)/sqrt(2)/3) == \ + sqrt(6)*sin(x + pi/6)/3 + sqrt(6)*sin(y + pi/6)/9 + assert TR10i(cos(x) + sqrt(3)*sin(x) + 2*sqrt(3)*cos(x + pi/6)) == 4*cos(x) + assert TR10i(cos(x) + sqrt(3)*sin(x) + + 2*sqrt(3)*cos(x + pi/6) + 4*sin(x)) == 4*sqrt(2)*sin(x + pi/4) + assert TR10i(cos(2)*sin(3) + sin(2)*cos(4)) == \ + sin(2)*cos(4) + sin(3)*cos(2) + + A = Symbol('A', commutative=False) + assert TR10i(sqrt(2)*cos(x)*A + sqrt(6)*sin(x)*A) == \ + 2*sqrt(2)*sin(x + pi/6)*A + + + c = cos(x) + s = sin(x) + h = sin(y) + r = cos(y) + for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): + for argsi in ((c*r, s*h), (c*h, s*r)): # explicit 2-args + args = zip(si, argsi) + ex = Add(*[Mul(*ai) for ai in args]) + t = TR10i(ex) + assert not (ex - t.expand(trig=True) or t.is_Add) + + c = cos(x) + s = sin(x) + h = sin(pi/6) + r = cos(pi/6) + for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): + for argsi in ((c*r, s*h), (c*h, s*r)): # induced + args = zip(si, argsi) + ex = Add(*[Mul(*ai) for ai in args]) + t = TR10i(ex) + assert not (ex - t.expand(trig=True) or t.is_Add) + + +def test_TR11(): + + assert TR11(sin(2*x)) == 2*sin(x)*cos(x) + assert TR11(sin(4*x)) == 4*((-sin(x)**2 + cos(x)**2)*sin(x)*cos(x)) + assert TR11(sin(x*Rational(4, 3))) == \ + 4*((-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3)) + + assert TR11(cos(2*x)) == -sin(x)**2 + cos(x)**2 + assert TR11(cos(4*x)) == \ + (-sin(x)**2 + cos(x)**2)**2 - 4*sin(x)**2*cos(x)**2 + + assert TR11(cos(2)) == cos(2) + + assert TR11(cos(pi*Rational(3, 7)), pi*Rational(2, 7)) == -cos(pi*Rational(2, 7))**2 + sin(pi*Rational(2, 7))**2 + assert TR11(cos(4), 2) == -sin(2)**2 + cos(2)**2 + assert TR11(cos(6), 2) == cos(6) + assert TR11(sin(x)/cos(x/2), x/2) == 2*sin(x/2) + +def test__TR11(): + + assert _TR11(sin(x/3)*sin(2*x)*sin(x/4)/(cos(x/6)*cos(x/8))) == \ + 4*sin(x/8)*sin(x/6)*sin(2*x),_TR11(sin(x/3)*sin(2*x)*sin(x/4)/(cos(x/6)*cos(x/8))) + assert _TR11(sin(x/3)/cos(x/6)) == 2*sin(x/6) + + assert _TR11(cos(x/6)/sin(x/3)) == 1/(2*sin(x/6)) + assert _TR11(sin(2*x)*cos(x/8)/sin(x/4)) == sin(2*x)/(2*sin(x/8)), _TR11(sin(2*x)*cos(x/8)/sin(x/4)) + assert _TR11(sin(x)/sin(x/2)) == 2*cos(x/2) + + +def test_TR12(): + assert TR12(tan(x + y)) == (tan(x) + tan(y))/(-tan(x)*tan(y) + 1) + assert TR12(tan(x + y + z)) ==\ + (tan(z) + (tan(x) + tan(y))/(-tan(x)*tan(y) + 1))/( + 1 - (tan(x) + tan(y))*tan(z)/(-tan(x)*tan(y) + 1)) + assert TR12(tan(x*y)) == tan(x*y) + + +def test_TR13(): + assert TR13(tan(3)*tan(2)) == -tan(2)/tan(5) - tan(3)/tan(5) + 1 + assert TR13(cot(3)*cot(2)) == 1 + cot(3)*cot(5) + cot(2)*cot(5) + assert TR13(tan(1)*tan(2)*tan(3)) == \ + (-tan(2)/tan(5) - tan(3)/tan(5) + 1)*tan(1) + assert TR13(tan(1)*tan(2)*cot(3)) == \ + (-tan(2)/tan(3) + 1 - tan(1)/tan(3))*cot(3) + + +def test_L(): + assert L(cos(x) + sin(x)) == 2 + + +def test_fu(): + + assert fu(sin(50)**2 + cos(50)**2 + sin(pi/6)) == Rational(3, 2) + assert fu(sqrt(6)*cos(x) + sqrt(2)*sin(x)) == 2*sqrt(2)*sin(x + pi/3) + + + eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2 + assert fu(eq) == cos(x)**4 - 2*cos(y)**2 + 2 + + assert fu(S.Half - cos(2*x)/2) == sin(x)**2 + + assert fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b))) == \ + sqrt(2)*sin(a + b + pi/4) + + assert fu(sqrt(3)*cos(x)/2 + sin(x)/2) == sin(x + pi/3) + + assert fu(1 - sin(2*x)**2/4 - sin(y)**2 - cos(x)**4) == \ + -cos(x)**2 + cos(y)**2 + + assert fu(cos(pi*Rational(4, 9))) == sin(pi/18) + assert fu(cos(pi/9)*cos(pi*Rational(2, 9))*cos(pi*Rational(3, 9))*cos(pi*Rational(4, 9))) == Rational(1, 16) + + assert fu( + tan(pi*Rational(7, 18)) + tan(pi*Rational(5, 18)) - sqrt(3)*tan(pi*Rational(5, 18))*tan(pi*Rational(7, 18))) == \ + -sqrt(3) + + assert fu(tan(1)*tan(2)) == tan(1)*tan(2) + + expr = Mul(*[cos(2**i) for i in range(10)]) + assert fu(expr) == sin(1024)/(1024*sin(1)) + + # issue #18059: + assert fu(cos(x) + sqrt(sin(x)**2)) == cos(x) + sqrt(sin(x)**2) + + assert fu((-14*sin(x)**3 + 35*sin(x) + 6*sqrt(3)*cos(x)**3 + 9*sqrt(3)*cos(x))/((cos(2*x) + 4))) == \ + 7*sin(x) + 3*sqrt(3)*cos(x) + + +def test_objective(): + assert fu(sin(x)/cos(x), measure=lambda x: x.count_ops()) == \ + tan(x) + assert fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) == \ + sin(x)/cos(x) + + +def test_process_common_addends(): + # this tests that the args are not evaluated as they are given to do + # and that key2 works when key1 is False + do = lambda x: Add(*[i**(i%2) for i in x.args]) + assert process_common_addends(Add(*[1, 2, 3, 4], evaluate=False), do, + key2=lambda x: x%2, key1=False) == 1**1 + 3**1 + 2**0 + 4**0 + + +def test_trig_split(): + assert trig_split(cos(x), cos(y)) == (1, 1, 1, x, y, True) + assert trig_split(2*cos(x), -2*cos(y)) == (2, 1, -1, x, y, True) + assert trig_split(cos(x)*sin(y), cos(y)*sin(y)) == \ + (sin(y), 1, 1, x, y, True) + + assert trig_split(cos(x), -sqrt(3)*sin(x), two=True) == \ + (2, 1, -1, x, pi/6, False) + assert trig_split(cos(x), sin(x), two=True) == \ + (sqrt(2), 1, 1, x, pi/4, False) + assert trig_split(cos(x), -sin(x), two=True) == \ + (sqrt(2), 1, -1, x, pi/4, False) + assert trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True) == \ + (2*sqrt(2), 1, -1, x, pi/6, False) + assert trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True) == \ + (-2*sqrt(2), 1, 1, x, pi/3, False) + assert trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True) == \ + (sqrt(6)/3, 1, 1, x, pi/6, False) + assert trig_split(-sqrt(6)*cos(x)*sin(y), + -sqrt(2)*sin(x)*sin(y), two=True) == \ + (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False) + + assert trig_split(cos(x), sin(x)) is None + assert trig_split(cos(x), sin(z)) is None + assert trig_split(2*cos(x), -sin(x)) is None + assert trig_split(cos(x), -sqrt(3)*sin(x)) is None + assert trig_split(cos(x)*cos(y), sin(x)*sin(z)) is None + assert trig_split(cos(x)*cos(y), sin(x)*sin(y)) is None + assert trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True) is \ + None + + assert trig_split(sqrt(3)*sqrt(x), cos(3), two=True) is None + assert trig_split(sqrt(3)*root(x, 3), sin(3)*cos(2), two=True) is None + assert trig_split(cos(5)*cos(6), cos(7)*sin(5), two=True) is None + + +def test_TRmorrie(): + assert TRmorrie(7*Mul(*[cos(i) for i in range(10)])) == \ + 7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3)) + assert TRmorrie(x) == x + assert TRmorrie(2*x) == 2*x + e = cos(pi/7)*cos(pi*Rational(2, 7))*cos(pi*Rational(4, 7)) + assert TR8(TRmorrie(e)) == Rational(-1, 8) + e = Mul(*[cos(2**i*pi/17) for i in range(1, 17)]) + assert TR8(TR3(TRmorrie(e))) == Rational(1, 65536) + # issue 17063 + eq = cos(x)/cos(x/2) + assert TRmorrie(eq) == eq + # issue #20430 + eq = cos(x/2)*sin(x/2)*cos(x)**3 + assert TRmorrie(eq) == sin(2*x)*cos(x)**2/4 + + +def test_TRpower(): + assert TRpower(1/sin(x)**2) == 1/sin(x)**2 + assert TRpower(cos(x)**3*sin(x/2)**4) == \ + (3*cos(x)/4 + cos(3*x)/4)*(-cos(x)/2 + cos(2*x)/8 + Rational(3, 8)) + for k in range(2, 8): + assert verify_numerically(sin(x)**k, TRpower(sin(x)**k)) + assert verify_numerically(cos(x)**k, TRpower(cos(x)**k)) + + +def test_hyper_as_trig(): + from sympy.simplify.fu import _osborne, _osbornei + + eq = sinh(x)**2 + cosh(x)**2 + t, f = hyper_as_trig(eq) + assert f(fu(t)) == cosh(2*x) + e, f = hyper_as_trig(tanh(x + y)) + assert f(TR12(e)) == (tanh(x) + tanh(y))/(tanh(x)*tanh(y) + 1) + + d = Dummy() + assert _osborne(sinh(x), d) == I*sin(x*d) + assert _osborne(tanh(x), d) == I*tan(x*d) + assert _osborne(coth(x), d) == cot(x*d)/I + assert _osborne(cosh(x), d) == cos(x*d) + assert _osborne(sech(x), d) == sec(x*d) + assert _osborne(csch(x), d) == csc(x*d)/I + for func in (sinh, cosh, tanh, coth, sech, csch): + h = func(pi) + assert _osbornei(_osborne(h, d), d) == h + # /!\ the _osborne functions are not meant to work + # in the o(i(trig, d), d) direction so we just check + # that they work as they are supposed to work + assert _osbornei(cos(x*y + z), y) == cosh(x + z*I) + assert _osbornei(sin(x*y + z), y) == sinh(x + z*I)/I + assert _osbornei(tan(x*y + z), y) == tanh(x + z*I)/I + assert _osbornei(cot(x*y + z), y) == coth(x + z*I)*I + assert _osbornei(sec(x*y + z), y) == sech(x + z*I) + assert _osbornei(csc(x*y + z), y) == csch(x + z*I)*I + + +def test_TR12i(): + ta, tb, tc = [tan(i) for i in (a, b, c)] + assert TR12i((ta + tb)/(-ta*tb + 1)) == tan(a + b) + assert TR12i((ta + tb)/(ta*tb - 1)) == -tan(a + b) + assert TR12i((-ta - tb)/(ta*tb - 1)) == tan(a + b) + eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1)) + assert TR12i(eq.expand()) == \ + -3*tan(a + b)*tan(a + c)/(tan(a) + tan(b) - 1)/2 + assert TR12i(tan(x)/sin(x)) == tan(x)/sin(x) + eq = (ta + cos(2))/(-ta*tb + 1) + assert TR12i(eq) == eq + eq = (ta + tb + 2)**2/(-ta*tb + 1) + assert TR12i(eq) == eq + eq = ta/(-ta*tb + 1) + assert TR12i(eq) == eq + eq = (((ta + tb)*(a + 1)).expand())**2/(ta*tb - 1) + assert TR12i(eq) == -(a + 1)**2*tan(a + b) + + +def test_TR14(): + eq = (cos(x) - 1)*(cos(x) + 1) + ans = -sin(x)**2 + assert TR14(eq) == ans + assert TR14(1/eq) == 1/ans + assert TR14((cos(x) - 1)**2*(cos(x) + 1)**2) == ans**2 + assert TR14((cos(x) - 1)**2*(cos(x) + 1)**3) == ans**2*(cos(x) + 1) + assert TR14((cos(x) - 1)**3*(cos(x) + 1)**2) == ans**2*(cos(x) - 1) + eq = (cos(x) - 1)**y*(cos(x) + 1)**y + assert TR14(eq) == eq + eq = (cos(x) - 2)**y*(cos(x) + 1) + assert TR14(eq) == eq + eq = (tan(x) - 2)**2*(cos(x) + 1) + assert TR14(eq) == eq + i = symbols('i', integer=True) + assert TR14((cos(x) - 1)**i*(cos(x) + 1)**i) == ans**i + assert TR14((sin(x) - 1)**i*(sin(x) + 1)**i) == (-cos(x)**2)**i + # could use extraction in this case + eq = (cos(x) - 1)**(i + 1)*(cos(x) + 1)**i + assert TR14(eq) in [(cos(x) - 1)*ans**i, eq] + + assert TR14((sin(x) - 1)*(sin(x) + 1)) == -cos(x)**2 + p1 = (cos(x) + 1)*(cos(x) - 1) + p2 = (cos(y) - 1)*2*(cos(y) + 1) + p3 = (3*(cos(y) - 1))*(3*(cos(y) + 1)) + assert TR14(p1*p2*p3*(x - 1)) == -18*((x - 1)*sin(x)**2*sin(y)**4) + + +def test_TR15_16_17(): + assert TR15(1 - 1/sin(x)**2) == -cot(x)**2 + assert TR16(1 - 1/cos(x)**2) == -tan(x)**2 + assert TR111(1 - 1/tan(x)**2) == 1 - cot(x)**2 + + +def test_as_f_sign_1(): + assert as_f_sign_1(x + 1) == (1, x, 1) + assert as_f_sign_1(x - 1) == (1, x, -1) + assert as_f_sign_1(-x + 1) == (-1, x, -1) + assert as_f_sign_1(-x - 1) == (-1, x, 1) + assert as_f_sign_1(2*x + 2) == (2, x, 1) + assert as_f_sign_1(x*y - y) == (y, x, -1) + assert as_f_sign_1(-x*y + y) == (-y, x, -1) + + +def test_issue_25590(): + A = Symbol('A', commutative=False) + B = Symbol('B', commutative=False) + + assert TR8(2*cos(x)*sin(x)*B*A) == sin(2*x)*B*A + assert TR13(tan(2)*tan(3)*B*A) == (-tan(2)/tan(5) - tan(3)/tan(5) + 1)*B*A + + # XXX The result may not be optimal than + # sin(2*x)*B*A + cos(x)**2 and may change in the future + assert (2*cos(x)*sin(x)*B*A + cos(x)**2).simplify() == sin(2*x)*B*A + cos(2*x)/2 + S.One/2 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_function.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_function.py new file mode 100644 index 0000000000000000000000000000000000000000..441b9faf1bb3c5e7f2279b2a61066d050e45f773 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_function.py @@ -0,0 +1,54 @@ +""" Unit tests for Hyper_Function""" +from sympy.core import symbols, Dummy, Tuple, S, Rational +from sympy.functions import hyper + +from sympy.simplify.hyperexpand import Hyper_Function + +def test_attrs(): + a, b = symbols('a, b', cls=Dummy) + f = Hyper_Function([2, a], [b]) + assert f.ap == Tuple(2, a) + assert f.bq == Tuple(b) + assert f.args == (Tuple(2, a), Tuple(b)) + assert f.sizes == (2, 1) + +def test_call(): + a, b, x = symbols('a, b, x', cls=Dummy) + f = Hyper_Function([2, a], [b]) + assert f(x) == hyper([2, a], [b], x) + +def test_has(): + a, b, c = symbols('a, b, c', cls=Dummy) + f = Hyper_Function([2, -a], [b]) + assert f.has(a) + assert f.has(Tuple(b)) + assert not f.has(c) + +def test_eq(): + assert Hyper_Function([1], []) == Hyper_Function([1], []) + assert (Hyper_Function([1], []) != Hyper_Function([1], [])) is False + assert Hyper_Function([1], []) != Hyper_Function([2], []) + assert Hyper_Function([1], []) != Hyper_Function([1, 2], []) + assert Hyper_Function([1], []) != Hyper_Function([1], [2]) + +def test_gamma(): + assert Hyper_Function([2, 3], [-1]).gamma == 0 + assert Hyper_Function([-2, -3], [-1]).gamma == 2 + n = Dummy(integer=True) + assert Hyper_Function([-1, n, 1], []).gamma == 1 + assert Hyper_Function([-1, -n, 1], []).gamma == 1 + p = Dummy(integer=True, positive=True) + assert Hyper_Function([-1, p, 1], []).gamma == 1 + assert Hyper_Function([-1, -p, 1], []).gamma == 2 + +def test_suitable_origin(): + assert Hyper_Function((S.Half,), (Rational(3, 2),))._is_suitable_origin() is True + assert Hyper_Function((S.Half,), (S.Half,))._is_suitable_origin() is False + assert Hyper_Function((S.Half,), (Rational(-1, 2),))._is_suitable_origin() is False + assert Hyper_Function((S.Half,), (0,))._is_suitable_origin() is False + assert Hyper_Function((S.Half,), (-1, 1,))._is_suitable_origin() is False + assert Hyper_Function((S.Half, 0), (1,))._is_suitable_origin() is False + assert Hyper_Function((S.Half, 1), + (2, Rational(-2, 3)))._is_suitable_origin() is True + assert Hyper_Function((S.Half, 1), + (2, Rational(-2, 3), Rational(3, 2)))._is_suitable_origin() is True diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_gammasimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_gammasimp.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c73093250b279510e3c2274db22818a9adffd8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_gammasimp.py @@ -0,0 +1,127 @@ +from sympy.core.function import Function +from sympy.core.numbers import (Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.combinatorial.factorials import (rf, binomial, factorial) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.functions.special.gamma_functions import gamma +from sympy.simplify.gammasimp import gammasimp +from sympy.simplify.powsimp import powsimp +from sympy.simplify.simplify import simplify + +from sympy.abc import x, y, n, k + + +def test_gammasimp(): + R = Rational + + # was part of test_combsimp_gamma() in test_combsimp.py + assert gammasimp(gamma(x)) == gamma(x) + assert gammasimp(gamma(x + 1)/x) == gamma(x) + assert gammasimp(gamma(x)/(x - 1)) == gamma(x - 1) + assert gammasimp(x*gamma(x)) == gamma(x + 1) + assert gammasimp((x + 1)*gamma(x + 1)) == gamma(x + 2) + assert gammasimp(gamma(x + y)*(x + y)) == gamma(x + y + 1) + assert gammasimp(x/gamma(x + 1)) == 1/gamma(x) + assert gammasimp((x + 1)**2/gamma(x + 2)) == (x + 1)/gamma(x + 1) + assert gammasimp(x*gamma(x) + gamma(x + 3)/(x + 2)) == \ + (x + 2)*gamma(x + 1) + + assert gammasimp(gamma(2*x)*x) == gamma(2*x + 1)/2 + assert gammasimp(gamma(2*x)/(x - S.Half)) == 2*gamma(2*x - 1) + + assert gammasimp(gamma(x)*gamma(1 - x)) == pi/sin(pi*x) + assert gammasimp(gamma(x)*gamma(-x)) == -pi/(x*sin(pi*x)) + assert gammasimp(1/gamma(x + 3)/gamma(1 - x)) == \ + sin(pi*x)/(pi*x*(x + 1)*(x + 2)) + + assert gammasimp(factorial(n + 2)) == gamma(n + 3) + assert gammasimp(binomial(n, k)) == \ + gamma(n + 1)/(gamma(k + 1)*gamma(-k + n + 1)) + + assert powsimp(gammasimp( + gamma(x)*gamma(x + S.Half)*gamma(y)/gamma(x + y))) == \ + 2**(-2*x + 1)*sqrt(pi)*gamma(2*x)*gamma(y)/gamma(x + y) + assert gammasimp(1/gamma(x)/gamma(x - Rational(1, 3))/gamma(x + Rational(1, 3))) == \ + 3**(3*x - Rational(3, 2))/(2*pi*gamma(3*x - 1)) + assert simplify( + gamma(S.Half + x/2)*gamma(1 + x/2)/gamma(1 + x)/sqrt(pi)*2**x) == 1 + assert gammasimp(gamma(Rational(-1, 4))*gamma(Rational(-3, 4))) == 16*sqrt(2)*pi/3 + + assert powsimp(gammasimp(gamma(2*x)/gamma(x))) == \ + 2**(2*x - 1)*gamma(x + S.Half)/sqrt(pi) + + # issue 6792 + e = (-gamma(k)*gamma(k + 2) + gamma(k + 1)**2)/gamma(k)**2 + assert gammasimp(e) == -k + assert gammasimp(1/e) == -1/k + e = (gamma(x) + gamma(x + 1))/gamma(x) + assert gammasimp(e) == x + 1 + assert gammasimp(1/e) == 1/(x + 1) + e = (gamma(x) + gamma(x + 2))*(gamma(x - 1) + gamma(x))/gamma(x) + assert gammasimp(e) == (x**2 + x + 1)*gamma(x + 1)/(x - 1) + e = (-gamma(k)*gamma(k + 2) + gamma(k + 1)**2)/gamma(k)**2 + assert gammasimp(e**2) == k**2 + assert gammasimp(e**2/gamma(k + 1)) == k/gamma(k) + a = R(1, 2) + R(1, 3) + b = a + R(1, 3) + assert gammasimp(gamma(2*k)/gamma(k)*gamma(k + a)*gamma(k + b) + ) == 3*2**(2*k + 1)*3**(-3*k - 2)*sqrt(pi)*gamma(3*k + R(3, 2))/2 + + # issue 9699 + assert gammasimp((x + 1)*factorial(x)/gamma(y)) == gamma(x + 2)/gamma(y) + assert gammasimp(rf(x + n, k)*binomial(n, k)).simplify() == Piecewise( + (gamma(n + 1)*gamma(k + n + x)/(gamma(k + 1)*gamma(n + x)*gamma(-k + n + 1)), n > -x), + ((-1)**k*gamma(n + 1)*gamma(-n - x + 1)/(gamma(k + 1)*gamma(-k + n + 1)*gamma(-k - n - x + 1)), True)) + + A, B = symbols('A B', commutative=False) + assert gammasimp(e*B*A) == gammasimp(e)*B*A + + # check iteration + assert gammasimp(gamma(2*k)/gamma(k)*gamma(-k - R(1, 2))) == ( + -2**(2*k + 1)*sqrt(pi)/(2*((2*k + 1)*cos(pi*k)))) + assert gammasimp( + gamma(k)*gamma(k + R(1, 3))*gamma(k + R(2, 3))/gamma(k*R(3, 2))) == ( + 3*2**(3*k + 1)*3**(-3*k - S.Half)*sqrt(pi)*gamma(k*R(3, 2) + S.Half)/2) + + # issue 6153 + assert gammasimp(gamma(Rational(1, 4))/gamma(Rational(5, 4))) == 4 + + # was part of test_combsimp() in test_combsimp.py + assert gammasimp(binomial(n + 2, k + S.Half)) == gamma(n + 3)/ \ + (gamma(k + R(3, 2))*gamma(-k + n + R(5, 2))) + assert gammasimp(binomial(n + 2, k + 2.0)) == \ + gamma(n + 3)/(gamma(k + 3.0)*gamma(-k + n + 1)) + + # issue 11548 + assert gammasimp(binomial(0, x)) == sin(pi*x)/(pi*x) + + e = gamma(n + Rational(1, 3))*gamma(n + R(2, 3)) + assert gammasimp(e) == e + assert gammasimp(gamma(4*n + S.Half)/gamma(2*n - R(3, 4))) == \ + 2**(4*n - R(5, 2))*(8*n - 3)*gamma(2*n + R(3, 4))/sqrt(pi) + + i, m = symbols('i m', integer = True) + e = gamma(exp(i)) + assert gammasimp(e) == e + e = gamma(m + 3) + assert gammasimp(e) == e + e = gamma(m + 1)/(gamma(i + 1)*gamma(-i + m + 1)) + assert gammasimp(e) == e + + p = symbols("p", integer=True, positive=True) + assert gammasimp(gamma(-p + 4)) == gamma(-p + 4) + + +def test_issue_22606(): + fx = Function('f')(x) + eq = x + gamma(y) + # seems like ans should be `eq`, not `(x*y + gamma(y + 1))/y` + ans = gammasimp(eq) + assert gammasimp(eq.subs(x, fx)).subs(fx, x) == ans + assert gammasimp(eq.subs(x, cos(x))).subs(cos(x), x) == ans + assert 1/gammasimp(1/eq) == ans + assert gammasimp(fx.subs(x, eq)).args[0] == ans diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_hyperexpand.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_hyperexpand.py new file mode 100644 index 0000000000000000000000000000000000000000..c703c228a13201de13cfd4c3413fc75a2cf5bdb6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_hyperexpand.py @@ -0,0 +1,1063 @@ +from sympy.core.random import randrange + +from sympy.simplify.hyperexpand import (ShiftA, ShiftB, UnShiftA, UnShiftB, + MeijerShiftA, MeijerShiftB, MeijerShiftC, MeijerShiftD, + MeijerUnShiftA, MeijerUnShiftB, MeijerUnShiftC, + MeijerUnShiftD, + ReduceOrder, reduce_order, apply_operators, + devise_plan, make_derivative_operator, Formula, + hyperexpand, Hyper_Function, G_Function, + reduce_order_meijer, + build_hypergeometric_formula) +from sympy.concrete.summations import Sum +from sympy.core.containers import Tuple +from sympy.core.expr import Expr +from sympy.core.numbers import I +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.combinatorial.factorials import binomial +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.hyper import (hyper, meijerg) +from sympy.abc import z, a, b, c +from sympy.testing.pytest import XFAIL, raises, slow, tooslow +from sympy.core.random import verify_numerically as tn + +from sympy.core.numbers import (Rational, pi) +from sympy.functions.elementary.exponential import (exp, exp_polar, log) +from sympy.functions.elementary.hyperbolic import atanh +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (asin, cos, sin) +from sympy.functions.special.bessel import besseli +from sympy.functions.special.error_functions import erf +from sympy.functions.special.gamma_functions import (gamma, lowergamma) + + +def test_branch_bug(): + assert hyperexpand(hyper((Rational(-1, 3), S.Half), (Rational(2, 3), Rational(3, 2)), -z)) == \ + -z**S('1/3')*lowergamma(exp_polar(I*pi)/3, z)/5 \ + + sqrt(pi)*erf(sqrt(z))/(5*sqrt(z)) + assert hyperexpand(meijerg([Rational(7, 6), 1], [], [Rational(2, 3)], [Rational(1, 6), 0], z)) == \ + 2*z**S('2/3')*(2*sqrt(pi)*erf(sqrt(z))/sqrt(z) - 2*lowergamma( + Rational(2, 3), z)/z**S('2/3'))*gamma(Rational(2, 3))/gamma(Rational(5, 3)) + + +def test_hyperexpand(): + # Luke, Y. L. (1969), The Special Functions and Their Approximations, + # Volume 1, section 6.2 + + assert hyperexpand(hyper([], [], z)) == exp(z) + assert hyperexpand(hyper([1, 1], [2], -z)*z) == log(1 + z) + assert hyperexpand(hyper([], [S.Half], -z**2/4)) == cos(z) + assert hyperexpand(z*hyper([], [S('3/2')], -z**2/4)) == sin(z) + assert hyperexpand(hyper([S('1/2'), S('1/2')], [S('3/2')], z**2)*z) \ + == asin(z) + assert isinstance(Sum(binomial(2, z)*z**2, (z, 0, a)).doit(), Expr) + + +def can_do(ap, bq, numerical=True, div=1, lowerplane=False): + r = hyperexpand(hyper(ap, bq, z)) + if r.has(hyper): + return False + if not numerical: + return True + repl = {} + randsyms = r.free_symbols - {z} + while randsyms: + # Only randomly generated parameters are checked. + for n, ai in enumerate(randsyms): + repl[ai] = randcplx(n)/div + if not any(b.is_Integer and b <= 0 for b in Tuple(*bq).subs(repl)): + break + [a, b, c, d] = [2, -1, 3, 1] + if lowerplane: + [a, b, c, d] = [2, -2, 3, -1] + return tn( + hyper(ap, bq, z).subs(repl), + r.replace(exp_polar, exp).subs(repl), + z, a=a, b=b, c=c, d=d) + + +def test_roach(): + # Kelly B. Roach. Meijer G Function Representations. + # Section "Gallery" + assert can_do([S.Half], [Rational(9, 2)]) + assert can_do([], [1, Rational(5, 2), 4]) + assert can_do([Rational(-1, 2), 1, 2], [3, 4]) + assert can_do([Rational(1, 3)], [Rational(-2, 3), Rational(-1, 2), S.Half, 1]) + assert can_do([Rational(-3, 2), Rational(-1, 2)], [Rational(-5, 2), 1]) + assert can_do([Rational(-3, 2), ], [Rational(-1, 2), S.Half]) # shine-integral + assert can_do([Rational(-3, 2), Rational(-1, 2)], [2]) # elliptic integrals + + +@XFAIL +def test_roach_fail(): + assert can_do([Rational(-1, 2), 1], [Rational(1, 4), S.Half, Rational(3, 4)]) # PFDD + assert can_do([Rational(3, 2)], [Rational(5, 2), 5]) # struve function + assert can_do([Rational(-1, 2), S.Half, 1], [Rational(3, 2), Rational(5, 2)]) # polylog, pfdd + assert can_do([1, 2, 3], [S.Half, 4]) # XXX ? + assert can_do([S.Half], [Rational(-1, 3), Rational(-1, 2), Rational(-2, 3)]) # PFDD ? + +# For the long table tests, see end of file + + +def test_polynomial(): + from sympy.core.numbers import oo + assert hyperexpand(hyper([], [-1], z)) is oo + assert hyperexpand(hyper([-2], [-1], z)) is oo + assert hyperexpand(hyper([0, 0], [-1], z)) == 1 + assert can_do([-5, -2, randcplx(), randcplx()], [-10, randcplx()]) + assert hyperexpand(hyper((-1, 1), (-2,), z)) == 1 + z/2 + + +def test_hyperexpand_bases(): + assert hyperexpand(hyper([2], [a], z)) == \ + a + z**(-a + 1)*(-a**2 + 3*a + z*(a - 1) - 2)*exp(z)* \ + lowergamma(a - 1, z) - 1 + # TODO [a+1, aRational(-1, 2)], [2*a] + assert hyperexpand(hyper([1, 2], [3], z)) == -2/z - 2*log(-z + 1)/z**2 + assert hyperexpand(hyper([S.Half, 2], [Rational(3, 2)], z)) == \ + -1/(2*z - 2) + atanh(sqrt(z))/sqrt(z)/2 + assert hyperexpand(hyper([S.Half, S.Half], [Rational(5, 2)], z)) == \ + (-3*z + 3)/4/(z*sqrt(-z + 1)) \ + + (6*z - 3)*asin(sqrt(z))/(4*z**Rational(3, 2)) + assert hyperexpand(hyper([1, 2], [Rational(3, 2)], z)) == -1/(2*z - 2) \ + - asin(sqrt(z))/(sqrt(z)*(2*z - 2)*sqrt(-z + 1)) + assert hyperexpand(hyper([Rational(-1, 2) - 1, 1, 2], [S.Half, 3], z)) == \ + sqrt(z)*(z*Rational(6, 7) - Rational(6, 5))*atanh(sqrt(z)) \ + + (-30*z**2 + 32*z - 6)/35/z - 6*log(-z + 1)/(35*z**2) + assert hyperexpand(hyper([1 + S.Half, 1, 1], [2, 2], z)) == \ + -4*log(sqrt(-z + 1)/2 + S.Half)/z + # TODO hyperexpand(hyper([a], [2*a + 1], z)) + # TODO [S.Half, a], [Rational(3, 2), a+1] + assert hyperexpand(hyper([2], [b, 1], z)) == \ + z**(-b/2 + S.Half)*besseli(b - 1, 2*sqrt(z))*gamma(b) \ + + z**(-b/2 + 1)*besseli(b, 2*sqrt(z))*gamma(b) + # TODO [a], [a - S.Half, 2*a] + + +def test_hyperexpand_parametric(): + assert hyperexpand(hyper([a, S.Half + a], [S.Half], z)) \ + == (1 + sqrt(z))**(-2*a)/2 + (1 - sqrt(z))**(-2*a)/2 + assert hyperexpand(hyper([a, Rational(-1, 2) + a], [2*a], z)) \ + == 2**(2*a - 1)*((-z + 1)**S.Half + 1)**(-2*a + 1) + + +def test_shifted_sum(): + from sympy.simplify.simplify import simplify + assert simplify(hyperexpand(z**4*hyper([2], [3, S('3/2')], -z**2))) \ + == z*sin(2*z) + (-z**2 + S.Half)*cos(2*z) - S.Half + + +def _randrat(): + """ Steer clear of integers. """ + return S(randrange(25) + 10)/50 + + +def randcplx(offset=-1): + """ Polys is not good with real coefficients. """ + return _randrat() + I*_randrat() + I*(1 + offset) + + +@slow +def test_formulae(): + from sympy.simplify.hyperexpand import FormulaCollection + formulae = FormulaCollection().formulae + for formula in formulae: + h = formula.func(formula.z) + rep = {} + for n, sym in enumerate(formula.symbols): + rep[sym] = randcplx(n) + + # NOTE hyperexpand returns truly branched functions. We know we are + # on the main sheet, but numerical evaluation can still go wrong + # (e.g. if exp_polar cannot be evalf'd). + # Just replace all exp_polar by exp, this usually works. + + # first test if the closed-form is actually correct + h = h.subs(rep) + closed_form = formula.closed_form.subs(rep).rewrite('nonrepsmall') + z = formula.z + assert tn(h, closed_form.replace(exp_polar, exp), z) + + # now test the computed matrix + cl = (formula.C * formula.B)[0].subs(rep).rewrite('nonrepsmall') + assert tn(closed_form.replace( + exp_polar, exp), cl.replace(exp_polar, exp), z) + deriv1 = z*formula.B.applyfunc(lambda t: t.rewrite( + 'nonrepsmall')).diff(z) + deriv2 = formula.M * formula.B + for d1, d2 in zip(deriv1, deriv2): + assert tn(d1.subs(rep).replace(exp_polar, exp), + d2.subs(rep).rewrite('nonrepsmall').replace(exp_polar, exp), z) + + +def test_meijerg_formulae(): + from sympy.simplify.hyperexpand import MeijerFormulaCollection + formulae = MeijerFormulaCollection().formulae + for sig in formulae: + for formula in formulae[sig]: + g = meijerg(formula.func.an, formula.func.ap, + formula.func.bm, formula.func.bq, + formula.z) + rep = {} + for sym in formula.symbols: + rep[sym] = randcplx() + + # first test if the closed-form is actually correct + g = g.subs(rep) + closed_form = formula.closed_form.subs(rep) + z = formula.z + assert tn(g, closed_form, z) + + # now test the computed matrix + cl = (formula.C * formula.B)[0].subs(rep) + assert tn(closed_form, cl, z) + deriv1 = z*formula.B.diff(z) + deriv2 = formula.M * formula.B + for d1, d2 in zip(deriv1, deriv2): + assert tn(d1.subs(rep), d2.subs(rep), z) + + +def op(f): + return z*f.diff(z) + + +def test_plan(): + assert devise_plan(Hyper_Function([0], ()), + Hyper_Function([0], ()), z) == [] + with raises(ValueError): + devise_plan(Hyper_Function([1], ()), Hyper_Function((), ()), z) + with raises(ValueError): + devise_plan(Hyper_Function([2], [1]), Hyper_Function([2], [2]), z) + with raises(ValueError): + devise_plan(Hyper_Function([2], []), Hyper_Function([S("1/2")], []), z) + + # We cannot use pi/(10000 + n) because polys is insanely slow. + a1, a2, b1 = (randcplx(n) for n in range(3)) + b1 += 2*I + h = hyper([a1, a2], [b1], z) + + h2 = hyper((a1 + 1, a2), [b1], z) + assert tn(apply_operators(h, + devise_plan(Hyper_Function((a1 + 1, a2), [b1]), + Hyper_Function((a1, a2), [b1]), z), op), + h2, z) + + h2 = hyper((a1 + 1, a2 - 1), [b1], z) + assert tn(apply_operators(h, + devise_plan(Hyper_Function((a1 + 1, a2 - 1), [b1]), + Hyper_Function((a1, a2), [b1]), z), op), + h2, z) + + +def test_plan_derivatives(): + a1, a2, a3 = 1, 2, S('1/2') + b1, b2 = 3, S('5/2') + h = Hyper_Function((a1, a2, a3), (b1, b2)) + h2 = Hyper_Function((a1 + 1, a2 + 1, a3 + 2), (b1 + 1, b2 + 1)) + ops = devise_plan(h2, h, z) + f = Formula(h, z, h(z), []) + deriv = make_derivative_operator(f.M, z) + assert tn((apply_operators(f.C, ops, deriv)*f.B)[0], h2(z), z) + + h2 = Hyper_Function((a1, a2 - 1, a3 - 2), (b1 - 1, b2 - 1)) + ops = devise_plan(h2, h, z) + assert tn((apply_operators(f.C, ops, deriv)*f.B)[0], h2(z), z) + + +def test_reduction_operators(): + a1, a2, b1 = (randcplx(n) for n in range(3)) + h = hyper([a1], [b1], z) + + assert ReduceOrder(2, 0) is None + assert ReduceOrder(2, -1) is None + assert ReduceOrder(1, S('1/2')) is None + + h2 = hyper((a1, a2), (b1, a2), z) + assert tn(ReduceOrder(a2, a2).apply(h, op), h2, z) + + h2 = hyper((a1, a2 + 1), (b1, a2), z) + assert tn(ReduceOrder(a2 + 1, a2).apply(h, op), h2, z) + + h2 = hyper((a2 + 4, a1), (b1, a2), z) + assert tn(ReduceOrder(a2 + 4, a2).apply(h, op), h2, z) + + # test several step order reduction + ap = (a2 + 4, a1, b1 + 1) + bq = (a2, b1, b1) + func, ops = reduce_order(Hyper_Function(ap, bq)) + assert func.ap == (a1,) + assert func.bq == (b1,) + assert tn(apply_operators(h, ops, op), hyper(ap, bq, z), z) + + +def test_shift_operators(): + a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5)) + h = hyper((a1, a2), (b1, b2, b3), z) + + raises(ValueError, lambda: ShiftA(0)) + raises(ValueError, lambda: ShiftB(1)) + + assert tn(ShiftA(a1).apply(h, op), hyper((a1 + 1, a2), (b1, b2, b3), z), z) + assert tn(ShiftA(a2).apply(h, op), hyper((a1, a2 + 1), (b1, b2, b3), z), z) + assert tn(ShiftB(b1).apply(h, op), hyper((a1, a2), (b1 - 1, b2, b3), z), z) + assert tn(ShiftB(b2).apply(h, op), hyper((a1, a2), (b1, b2 - 1, b3), z), z) + assert tn(ShiftB(b3).apply(h, op), hyper((a1, a2), (b1, b2, b3 - 1), z), z) + + +def test_ushift_operators(): + a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5)) + h = hyper((a1, a2), (b1, b2, b3), z) + + raises(ValueError, lambda: UnShiftA((1,), (), 0, z)) + raises(ValueError, lambda: UnShiftB((), (-1,), 0, z)) + raises(ValueError, lambda: UnShiftA((1,), (0, -1, 1), 0, z)) + raises(ValueError, lambda: UnShiftB((0, 1), (1,), 0, z)) + + s = UnShiftA((a1, a2), (b1, b2, b3), 0, z) + assert tn(s.apply(h, op), hyper((a1 - 1, a2), (b1, b2, b3), z), z) + s = UnShiftA((a1, a2), (b1, b2, b3), 1, z) + assert tn(s.apply(h, op), hyper((a1, a2 - 1), (b1, b2, b3), z), z) + + s = UnShiftB((a1, a2), (b1, b2, b3), 0, z) + assert tn(s.apply(h, op), hyper((a1, a2), (b1 + 1, b2, b3), z), z) + s = UnShiftB((a1, a2), (b1, b2, b3), 1, z) + assert tn(s.apply(h, op), hyper((a1, a2), (b1, b2 + 1, b3), z), z) + s = UnShiftB((a1, a2), (b1, b2, b3), 2, z) + assert tn(s.apply(h, op), hyper((a1, a2), (b1, b2, b3 + 1), z), z) + + +def can_do_meijer(a1, a2, b1, b2, numeric=True): + """ + This helper function tries to hyperexpand() the meijer g-function + corresponding to the parameters a1, a2, b1, b2. + It returns False if this expansion still contains g-functions. + If numeric is True, it also tests the so-obtained formula numerically + (at random values) and returns False if the test fails. + Else it returns True. + """ + from sympy.core.function import expand + from sympy.functions.elementary.complexes import unpolarify + r = hyperexpand(meijerg(a1, a2, b1, b2, z)) + if r.has(meijerg): + return False + # NOTE hyperexpand() returns a truly branched function, whereas numerical + # evaluation only works on the main branch. Since we are evaluating on + # the main branch, this should not be a problem, but expressions like + # exp_polar(I*pi/2*x)**a are evaluated incorrectly. We thus have to get + # rid of them. The expand heuristically does this... + r = unpolarify(expand(r, force=True, power_base=True, power_exp=False, + mul=False, log=False, multinomial=False, basic=False)) + + if not numeric: + return True + + repl = {} + for n, ai in enumerate(meijerg(a1, a2, b1, b2, z).free_symbols - {z}): + repl[ai] = randcplx(n) + return tn(meijerg(a1, a2, b1, b2, z).subs(repl), r.subs(repl), z) + + +@slow +def test_meijerg_expand(): + from sympy.simplify.gammasimp import gammasimp + from sympy.simplify.simplify import simplify + # from mpmath docs + assert hyperexpand(meijerg([[], []], [[0], []], -z)) == exp(z) + + assert hyperexpand(meijerg([[1, 1], []], [[1], [0]], z)) == \ + log(z + 1) + assert hyperexpand(meijerg([[1, 1], []], [[1], [1]], z)) == \ + z/(z + 1) + assert hyperexpand(meijerg([[], []], [[S.Half], [0]], (z/2)**2)) \ + == sin(z)/sqrt(pi) + assert hyperexpand(meijerg([[], []], [[0], [S.Half]], (z/2)**2)) \ + == cos(z)/sqrt(pi) + assert can_do_meijer([], [a], [a - 1, a - S.Half], []) + assert can_do_meijer([], [], [a/2], [-a/2], False) # branches... + assert can_do_meijer([a], [b], [a], [b, a - 1]) + + # wikipedia + assert hyperexpand(meijerg([1], [], [], [0], z)) == \ + Piecewise((0, abs(z) < 1), (1, abs(1/z) < 1), + (meijerg([1], [], [], [0], z), True)) + assert hyperexpand(meijerg([], [1], [0], [], z)) == \ + Piecewise((1, abs(z) < 1), (0, abs(1/z) < 1), + (meijerg([], [1], [0], [], z), True)) + + # The Special Functions and their Approximations + assert can_do_meijer([], [], [a + b/2], [a, a - b/2, a + S.Half]) + assert can_do_meijer( + [], [], [a], [b], False) # branches only agree for small z + assert can_do_meijer([], [S.Half], [a], [-a]) + assert can_do_meijer([], [], [a, b], []) + assert can_do_meijer([], [], [a, b], []) + assert can_do_meijer([], [], [a, a + S.Half], [b, b + S.Half]) + assert can_do_meijer([], [], [a, -a], [0, S.Half], False) # dito + assert can_do_meijer([], [], [a, a + S.Half, b, b + S.Half], []) + assert can_do_meijer([S.Half], [], [0], [a, -a]) + assert can_do_meijer([S.Half], [], [a], [0, -a], False) # dito + assert can_do_meijer([], [a - S.Half], [a, b], [a - S.Half], False) + assert can_do_meijer([], [a + S.Half], [a + b, a - b, a], [], False) + assert can_do_meijer([a + S.Half], [], [b, 2*a - b, a], [], False) + + # This for example is actually zero. + assert can_do_meijer([], [], [], [a, b]) + + # Testing a bug: + assert hyperexpand(meijerg([0, 2], [], [], [-1, 1], z)) == \ + Piecewise((0, abs(z) < 1), + (z*(1 - 1/z**2)/2, abs(1/z) < 1), + (meijerg([0, 2], [], [], [-1, 1], z), True)) + + # Test that the simplest possible answer is returned: + assert gammasimp(simplify(hyperexpand( + meijerg([1], [1 - a], [-a/2, -a/2 + S.Half], [], 1/z)))) == \ + -2*sqrt(pi)*(sqrt(z + 1) + 1)**a/a + + # Test that hyper is returned + assert hyperexpand(meijerg([1], [], [a], [0, 0], z)) == hyper( + (a,), (a + 1, a + 1), z*exp_polar(I*pi))*z**a*gamma(a)/gamma(a + 1)**2 + + # Test place option + f = meijerg(((0, 1), ()), ((S.Half,), (0,)), z**2) + assert hyperexpand(f) == sqrt(pi)/sqrt(1 + z**(-2)) + assert hyperexpand(f, place=0) == sqrt(pi)*z/sqrt(z**2 + 1) + + +def test_meijerg_lookup(): + from sympy.functions.special.error_functions import (Ci, Si) + from sympy.functions.special.gamma_functions import uppergamma + assert hyperexpand(meijerg([a], [], [b, a], [], z)) == \ + z**b*exp(z)*gamma(-a + b + 1)*uppergamma(a - b, z) + assert hyperexpand(meijerg([0], [], [0, 0], [], z)) == \ + exp(z)*uppergamma(0, z) + assert can_do_meijer([a], [], [b, a + 1], []) + assert can_do_meijer([a], [], [b + 2, a], []) + assert can_do_meijer([a], [], [b - 2, a], []) + + assert hyperexpand(meijerg([a], [], [a, a, a - S.Half], [], z)) == \ + -sqrt(pi)*z**(a - S.Half)*(2*cos(2*sqrt(z))*(Si(2*sqrt(z)) - pi/2) + - 2*sin(2*sqrt(z))*Ci(2*sqrt(z))) == \ + hyperexpand(meijerg([a], [], [a, a - S.Half, a], [], z)) == \ + hyperexpand(meijerg([a], [], [a - S.Half, a, a], [], z)) + assert can_do_meijer([a - 1], [], [a + 2, a - Rational(3, 2), a + 1], []) + + +@XFAIL +def test_meijerg_expand_fail(): + # These basically test hyper([], [1/2 - a, 1/2 + 1, 1/2], z), + # which is *very* messy. But since the meijer g actually yields a + # sum of bessel functions, things can sometimes be simplified a lot and + # are then put into tables... + assert can_do_meijer([], [], [a + S.Half], [a, a - b/2, a + b/2]) + assert can_do_meijer([], [], [0, S.Half], [a, -a]) + assert can_do_meijer([], [], [3*a - S.Half, a, -a - S.Half], [a - S.Half]) + assert can_do_meijer([], [], [0, a - S.Half, -a - S.Half], [S.Half]) + assert can_do_meijer([], [], [a, b + S.Half, b], [2*b - a]) + assert can_do_meijer([], [], [a, b + S.Half, b, 2*b - a]) + assert can_do_meijer([S.Half], [], [-a, a], [0]) + + +@slow +def test_meijerg(): + # carefully set up the parameters. + # NOTE: this used to fail sometimes. I believe it is fixed, but if you + # hit an inexplicable test failure here, please let me know the seed. + a1, a2 = (randcplx(n) - 5*I - n*I for n in range(2)) + b1, b2 = (randcplx(n) + 5*I + n*I for n in range(2)) + b3, b4, b5, a3, a4, a5 = (randcplx() for n in range(6)) + g = meijerg([a1], [a3, a4], [b1], [b3, b4], z) + + assert ReduceOrder.meijer_minus(3, 4) is None + assert ReduceOrder.meijer_plus(4, 3) is None + + g2 = meijerg([a1, a2], [a3, a4], [b1], [b3, b4, a2], z) + assert tn(ReduceOrder.meijer_plus(a2, a2).apply(g, op), g2, z) + + g2 = meijerg([a1, a2], [a3, a4], [b1], [b3, b4, a2 + 1], z) + assert tn(ReduceOrder.meijer_plus(a2, a2 + 1).apply(g, op), g2, z) + + g2 = meijerg([a1, a2 - 1], [a3, a4], [b1], [b3, b4, a2 + 2], z) + assert tn(ReduceOrder.meijer_plus(a2 - 1, a2 + 2).apply(g, op), g2, z) + + g2 = meijerg([a1], [a3, a4, b2 - 1], [b1, b2 + 2], [b3, b4], z) + assert tn(ReduceOrder.meijer_minus( + b2 + 2, b2 - 1).apply(g, op), g2, z, tol=1e-6) + + # test several-step reduction + an = [a1, a2] + bq = [b3, b4, a2 + 1] + ap = [a3, a4, b2 - 1] + bm = [b1, b2 + 1] + niq, ops = reduce_order_meijer(G_Function(an, ap, bm, bq)) + assert niq.an == (a1,) + assert set(niq.ap) == {a3, a4} + assert niq.bm == (b1,) + assert set(niq.bq) == {b3, b4} + assert tn(apply_operators(g, ops, op), meijerg(an, ap, bm, bq, z), z) + + +def test_meijerg_shift_operators(): + # carefully set up the parameters. XXX this still fails sometimes + a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = (randcplx(n) for n in range(10)) + g = meijerg([a1], [a3, a4], [b1], [b3, b4], z) + + assert tn(MeijerShiftA(b1).apply(g, op), + meijerg([a1], [a3, a4], [b1 + 1], [b3, b4], z), z) + assert tn(MeijerShiftB(a1).apply(g, op), + meijerg([a1 - 1], [a3, a4], [b1], [b3, b4], z), z) + assert tn(MeijerShiftC(b3).apply(g, op), + meijerg([a1], [a3, a4], [b1], [b3 + 1, b4], z), z) + assert tn(MeijerShiftD(a3).apply(g, op), + meijerg([a1], [a3 - 1, a4], [b1], [b3, b4], z), z) + + s = MeijerUnShiftA([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1], [a3, a4], [b1 - 1], [b3, b4], z), z) + + s = MeijerUnShiftC([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1], [a3, a4], [b1], [b3 - 1, b4], z), z) + + s = MeijerUnShiftB([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1 + 1], [a3, a4], [b1], [b3, b4], z), z) + + s = MeijerUnShiftD([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1], [a3 + 1, a4], [b1], [b3, b4], z), z) + + +@slow +def test_meijerg_confluence(): + def t(m, a, b): + from sympy.core.sympify import sympify + a, b = sympify([a, b]) + m_ = m + m = hyperexpand(m) + if not m == Piecewise((a, abs(z) < 1), (b, abs(1/z) < 1), (m_, True)): + return False + if not (m.args[0].args[0] == a and m.args[1].args[0] == b): + return False + z0 = randcplx()/10 + if abs(m.subs(z, z0).n() - a.subs(z, z0).n()).n() > 1e-10: + return False + if abs(m.subs(z, 1/z0).n() - b.subs(z, 1/z0).n()).n() > 1e-10: + return False + return True + + assert t(meijerg([], [1, 1], [0, 0], [], z), -log(z), 0) + assert t(meijerg( + [], [3, 1], [0, 0], [], z), -z**2/4 + z - log(z)/2 - Rational(3, 4), 0) + assert t(meijerg([], [3, 1], [-1, 0], [], z), + z**2/12 - z/2 + log(z)/2 + Rational(1, 4) + 1/(6*z), 0) + assert t(meijerg([], [1, 1, 1, 1], [0, 0, 0, 0], [], z), -log(z)**3/6, 0) + assert t(meijerg([1, 1], [], [], [0, 0], z), 0, -log(1/z)) + assert t(meijerg([1, 1], [2, 2], [1, 1], [0, 0], z), + -z*log(z) + 2*z, -log(1/z) + 2) + assert t(meijerg([S.Half], [1, 1], [0, 0], [Rational(3, 2)], z), log(z)/2 - 1, 0) + + def u(an, ap, bm, bq): + m = meijerg(an, ap, bm, bq, z) + m2 = hyperexpand(m, allow_hyper=True) + if m2.has(meijerg) and not (m2.is_Piecewise and len(m2.args) == 3): + return False + return tn(m, m2, z) + assert u([], [1], [0, 0], []) + assert u([1, 1], [], [], [0]) + assert u([1, 1], [2, 2, 5], [1, 1, 6], [0, 0]) + assert u([1, 1], [2, 2, 5], [1, 1, 6], [0]) + + +def test_meijerg_with_Floats(): + # see issue #10681 + from sympy.polys.domains.realfield import RR + f = meijerg(((3.0, 1), ()), ((Rational(3, 2),), (0,)), z) + a = -2.3632718012073 + g = a*z**Rational(3, 2)*hyper((-0.5, Rational(3, 2)), (Rational(5, 2),), z*exp_polar(I*pi)) + assert RR.almosteq((hyperexpand(f)/g).n(), 1.0, 1e-12) + + +def test_lerchphi(): + from sympy.functions.special.zeta_functions import (lerchphi, polylog) + from sympy.simplify.gammasimp import gammasimp + assert hyperexpand(hyper([1, a], [a + 1], z)/a) == lerchphi(z, 1, a) + assert hyperexpand( + hyper([1, a, a], [a + 1, a + 1], z)/a**2) == lerchphi(z, 2, a) + assert hyperexpand(hyper([1, a, a, a], [a + 1, a + 1, a + 1], z)/a**3) == \ + lerchphi(z, 3, a) + assert hyperexpand(hyper([1] + [a]*10, [a + 1]*10, z)/a**10) == \ + lerchphi(z, 10, a) + assert gammasimp(hyperexpand(meijerg([0, 1 - a], [], [0], + [-a], exp_polar(-I*pi)*z))) == lerchphi(z, 1, a) + assert gammasimp(hyperexpand(meijerg([0, 1 - a, 1 - a], [], [0], + [-a, -a], exp_polar(-I*pi)*z))) == lerchphi(z, 2, a) + assert gammasimp(hyperexpand(meijerg([0, 1 - a, 1 - a, 1 - a], [], [0], + [-a, -a, -a], exp_polar(-I*pi)*z))) == lerchphi(z, 3, a) + + assert hyperexpand(z*hyper([1, 1], [2], z)) == -log(1 + -z) + assert hyperexpand(z*hyper([1, 1, 1], [2, 2], z)) == polylog(2, z) + assert hyperexpand(z*hyper([1, 1, 1, 1], [2, 2, 2], z)) == polylog(3, z) + + assert hyperexpand(hyper([1, a, 1 + S.Half], [a + 1, S.Half], z)) == \ + -2*a/(z - 1) + (-2*a**2 + a)*lerchphi(z, 1, a) + + # Now numerical tests. These make sure reductions etc are carried out + # correctly + + # a rational function (polylog at negative integer order) + assert can_do([2, 2, 2], [1, 1]) + + # NOTE these contain log(1-x) etc ... better make sure we have |z| < 1 + # reduction of order for polylog + assert can_do([1, 1, 1, b + 5], [2, 2, b], div=10) + + # reduction of order for lerchphi + # XXX lerchphi in mpmath is flaky + assert can_do( + [1, a, a, a, b + 5], [a + 1, a + 1, a + 1, b], numerical=False) + + # test a bug + from sympy.functions.elementary.complexes import Abs + assert hyperexpand(hyper([S.Half, S.Half, S.Half, 1], + [Rational(3, 2), Rational(3, 2), Rational(3, 2)], Rational(1, 4))) == \ + Abs(-polylog(3, exp_polar(I*pi)/2) + polylog(3, S.Half)) + + +def test_partial_simp(): + # First test that hypergeometric function formulae work. + a, b, c, d, e = (randcplx() for _ in range(5)) + for func in [Hyper_Function([a, b, c], [d, e]), + Hyper_Function([], [a, b, c, d, e])]: + f = build_hypergeometric_formula(func) + z = f.z + assert f.closed_form == func(z) + deriv1 = f.B.diff(z)*z + deriv2 = f.M*f.B + for func1, func2 in zip(deriv1, deriv2): + assert tn(func1, func2, z) + + # Now test that formulae are partially simplified. + a, b, z = symbols('a b z') + assert hyperexpand(hyper([3, a], [1, b], z)) == \ + (-a*b/2 + a*z/2 + 2*a)*hyper([a + 1], [b], z) \ + + (a*b/2 - 2*a + 1)*hyper([a], [b], z) + assert tn( + hyperexpand(hyper([3, d], [1, e], z)), hyper([3, d], [1, e], z), z) + assert hyperexpand(hyper([3], [1, a, b], z)) == \ + hyper((), (a, b), z) \ + + z*hyper((), (a + 1, b), z)/(2*a) \ + - z*(b - 4)*hyper((), (a + 1, b + 1), z)/(2*a*b) + assert tn( + hyperexpand(hyper([3], [1, d, e], z)), hyper([3], [1, d, e], z), z) + + +def test_hyperexpand_special(): + assert hyperexpand(hyper([a, b], [c], 1)) == \ + gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b) + assert hyperexpand(hyper([a, b], [1 + a - b], -1)) == \ + gamma(1 + a/2)*gamma(1 + a - b)/gamma(1 + a)/gamma(1 + a/2 - b) + assert hyperexpand(hyper([a, b], [1 + b - a], -1)) == \ + gamma(1 + b/2)*gamma(1 + b - a)/gamma(1 + b)/gamma(1 + b/2 - a) + assert hyperexpand(meijerg([1 - z - a/2], [1 - z + a/2], [b/2], [-b/2], 1)) == \ + gamma(1 - 2*z)*gamma(z + a/2 + b/2)/gamma(1 - z + a/2 - b/2) \ + /gamma(1 - z - a/2 + b/2)/gamma(1 - z + a/2 + b/2) + assert hyperexpand(hyper([a], [b], 0)) == 1 + assert hyper([a], [b], 0) != 0 + + +def test_Mod1_behavior(): + from sympy.core.symbol import Symbol + from sympy.simplify.simplify import simplify + n = Symbol('n', integer=True) + # Note: this should not hang. + assert simplify(hyperexpand(meijerg([1], [], [n + 1], [0], z))) == \ + lowergamma(n + 1, z) + + +@slow +def test_prudnikov_misc(): + assert can_do([1, (3 + I)/2, (3 - I)/2], [Rational(3, 2), 2]) + assert can_do([S.Half, a - 1], [Rational(3, 2), a + 1], lowerplane=True) + assert can_do([], [b + 1]) + assert can_do([a], [a - 1, b + 1]) + + assert can_do([a], [a - S.Half, 2*a]) + assert can_do([a], [a - S.Half, 2*a + 1]) + assert can_do([a], [a - S.Half, 2*a - 1]) + assert can_do([a], [a + S.Half, 2*a]) + assert can_do([a], [a + S.Half, 2*a + 1]) + assert can_do([a], [a + S.Half, 2*a - 1]) + assert can_do([S.Half], [b, 2 - b]) + assert can_do([S.Half], [b, 3 - b]) + assert can_do([1], [2, b]) + + assert can_do([a, a + S.Half], [2*a, b, 2*a - b + 1]) + assert can_do([a, a + S.Half], [S.Half, 2*a, 2*a + S.Half]) + assert can_do([a], [a + 1], lowerplane=True) # lowergamma + + +def test_prudnikov_1(): + # A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990). + # Integrals and Series: More Special Functions, Vol. 3,. + # Gordon and Breach Science Publisher + + # 7.3.1 + assert can_do([a, -a], [S.Half]) + assert can_do([a, 1 - a], [S.Half]) + assert can_do([a, 1 - a], [Rational(3, 2)]) + assert can_do([a, 2 - a], [S.Half]) + assert can_do([a, 2 - a], [Rational(3, 2)]) + assert can_do([a, 2 - a], [Rational(3, 2)]) + assert can_do([a, a + S.Half], [2*a - 1]) + assert can_do([a, a + S.Half], [2*a]) + assert can_do([a, a + S.Half], [2*a + 1]) + assert can_do([a, a + S.Half], [S.Half]) + assert can_do([a, a + S.Half], [Rational(3, 2)]) + assert can_do([a, a/2 + 1], [a/2]) + assert can_do([1, b], [2]) + assert can_do([1, b], [b + 1], numerical=False) # Lerch Phi + # NOTE: branches are complicated for |z| > 1 + + assert can_do([a], [2*a]) + assert can_do([a], [2*a + 1]) + assert can_do([a], [2*a - 1]) + + +@slow +def test_prudnikov_2(): + h = S.Half + assert can_do([-h, -h], [h]) + assert can_do([-h, h], [3*h]) + assert can_do([-h, h], [5*h]) + assert can_do([-h, h], [7*h]) + assert can_do([-h, 1], [h]) + + for p in [-h, h]: + for n in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: + for m in [-h, h, 3*h, 5*h, 7*h]: + assert can_do([p, n], [m]) + for n in [1, 2, 3, 4]: + for m in [1, 2, 3, 4]: + assert can_do([p, n], [m]) + + +def test_prudnikov_3(): + h = S.Half + assert can_do([Rational(1, 4), Rational(3, 4)], [h]) + assert can_do([Rational(1, 4), Rational(3, 4)], [3*h]) + assert can_do([Rational(1, 3), Rational(2, 3)], [3*h]) + assert can_do([Rational(3, 4), Rational(5, 4)], [h]) + assert can_do([Rational(3, 4), Rational(5, 4)], [3*h]) + + +@tooslow +def test_prudnikov_3_slow(): + # XXX: This is marked as tooslow and hence skipped in CI. None of the + # individual cases below fails or hangs. Some cases are slow and the loops + # below generate 280 different cases. Is it really necessary to test all + # 280 cases here? + h = S.Half + for p in [1, 2, 3, 4]: + for n in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4, 9*h]: + for m in [1, 3*h, 2, 5*h, 3, 7*h, 4]: + assert can_do([p, m], [n]) + + +@slow +def test_prudnikov_4(): + h = S.Half + for p in [3*h, 5*h, 7*h]: + for n in [-h, h, 3*h, 5*h, 7*h]: + for m in [3*h, 2, 5*h, 3, 7*h, 4]: + assert can_do([p, m], [n]) + for n in [1, 2, 3, 4]: + for m in [2, 3, 4]: + assert can_do([p, m], [n]) + + +@slow +def test_prudnikov_5(): + h = S.Half + + for p in [1, 2, 3]: + for q in range(p, 4): + for r in [1, 2, 3]: + for s in range(r, 4): + assert can_do([-h, p, q], [r, s]) + + for p in [h, 1, 3*h, 2, 5*h, 3]: + for q in [h, 3*h, 5*h]: + for r in [h, 3*h, 5*h]: + for s in [h, 3*h, 5*h]: + if s <= q and s <= r: + assert can_do([-h, p, q], [r, s]) + + for p in [h, 1, 3*h, 2, 5*h, 3]: + for q in [1, 2, 3]: + for r in [h, 3*h, 5*h]: + for s in [1, 2, 3]: + assert can_do([-h, p, q], [r, s]) + + +@slow +def test_prudnikov_6(): + h = S.Half + + for m in [3*h, 5*h]: + for n in [1, 2, 3]: + for q in [h, 1, 2]: + for p in [1, 2, 3]: + assert can_do([h, q, p], [m, n]) + for q in [1, 2, 3]: + for p in [3*h, 5*h]: + assert can_do([h, q, p], [m, n]) + + for q in [1, 2]: + for p in [1, 2, 3]: + for m in [1, 2, 3]: + for n in [1, 2, 3]: + assert can_do([h, q, p], [m, n]) + + assert can_do([h, h, 5*h], [3*h, 3*h]) + assert can_do([h, 1, 5*h], [3*h, 3*h]) + assert can_do([h, 2, 2], [1, 3]) + + # pages 435 to 457 contain more PFDD and stuff like this + + +@slow +def test_prudnikov_7(): + assert can_do([3], [6]) + + h = S.Half + for n in [h, 3*h, 5*h, 7*h]: + assert can_do([-h], [n]) + for m in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: # HERE + for n in [-h, h, 3*h, 5*h, 7*h, 1, 2, 3, 4]: + assert can_do([m], [n]) + + +@slow +def test_prudnikov_8(): + h = S.Half + + # 7.12.2 + for ai in [1, 2, 3]: + for bi in [1, 2, 3]: + for ci in range(1, ai + 1): + for di in [h, 1, 3*h, 2, 5*h, 3]: + assert can_do([ai, bi], [ci, di]) + for bi in [3*h, 5*h]: + for ci in [h, 1, 3*h, 2, 5*h, 3]: + for di in [1, 2, 3]: + assert can_do([ai, bi], [ci, di]) + + for ai in [-h, h, 3*h, 5*h]: + for bi in [1, 2, 3]: + for ci in [h, 1, 3*h, 2, 5*h, 3]: + for di in [1, 2, 3]: + assert can_do([ai, bi], [ci, di]) + for bi in [h, 3*h, 5*h]: + for ci in [h, 3*h, 5*h, 3]: + for di in [h, 1, 3*h, 2, 5*h, 3]: + if ci <= bi: + assert can_do([ai, bi], [ci, di]) + + +def test_prudnikov_9(): + # 7.13.1 [we have a general formula ... so this is a bit pointless] + for i in range(9): + assert can_do([], [(S(i) + 1)/2]) + for i in range(5): + assert can_do([], [-(2*S(i) + 1)/2]) + + +@slow +def test_prudnikov_10(): + # 7.14.2 + h = S.Half + for p in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: + for m in [1, 2, 3, 4]: + for n in range(m, 5): + assert can_do([p], [m, n]) + + for p in [1, 2, 3, 4]: + for n in [h, 3*h, 5*h, 7*h]: + for m in [1, 2, 3, 4]: + assert can_do([p], [n, m]) + + for p in [3*h, 5*h, 7*h]: + for m in [h, 1, 2, 5*h, 3, 7*h, 4]: + assert can_do([p], [h, m]) + assert can_do([p], [3*h, m]) + + for m in [h, 1, 2, 5*h, 3, 7*h, 4]: + assert can_do([7*h], [5*h, m]) + + assert can_do([Rational(-1, 2)], [S.Half, S.Half]) # shine-integral shi + + +def test_prudnikov_11(): + # 7.15 + assert can_do([a, a + S.Half], [2*a, b, 2*a - b]) + assert can_do([a, a + S.Half], [Rational(3, 2), 2*a, 2*a - S.Half]) + + assert can_do([Rational(1, 4), Rational(3, 4)], [S.Half, S.Half, 1]) + assert can_do([Rational(5, 4), Rational(3, 4)], [Rational(3, 2), S.Half, 2]) + assert can_do([Rational(5, 4), Rational(3, 4)], [Rational(3, 2), Rational(3, 2), 1]) + assert can_do([Rational(5, 4), Rational(7, 4)], [Rational(3, 2), Rational(5, 2), 2]) + + assert can_do([1, 1], [Rational(3, 2), 2, 2]) # cosh-integral chi + + +def test_prudnikov_12(): + # 7.16 + assert can_do( + [], [a, a + S.Half, 2*a], False) # branches only agree for some z! + assert can_do([], [a, a + S.Half, 2*a + 1], False) # dito + assert can_do([], [S.Half, a, a + S.Half]) + assert can_do([], [Rational(3, 2), a, a + S.Half]) + + assert can_do([], [Rational(1, 4), S.Half, Rational(3, 4)]) + assert can_do([], [S.Half, S.Half, 1]) + assert can_do([], [S.Half, Rational(3, 2), 1]) + assert can_do([], [Rational(3, 4), Rational(3, 2), Rational(5, 4)]) + assert can_do([], [1, 1, Rational(3, 2)]) + assert can_do([], [1, 2, Rational(3, 2)]) + assert can_do([], [1, Rational(3, 2), Rational(3, 2)]) + assert can_do([], [Rational(5, 4), Rational(3, 2), Rational(7, 4)]) + assert can_do([], [2, Rational(3, 2), Rational(3, 2)]) + + +@slow +def test_prudnikov_2F1(): + h = S.Half + # Elliptic integrals + for p in [-h, h]: + for m in [h, 3*h, 5*h, 7*h]: + for n in [1, 2, 3, 4]: + assert can_do([p, m], [n]) + + +@XFAIL +def test_prudnikov_fail_2F1(): + assert can_do([a, b], [b + 1]) # incomplete beta function + assert can_do([-1, b], [c]) # Poly. also -2, -3 etc + + # TODO polys + + # Legendre functions: + assert can_do([a, b], [a + b + S.Half]) + assert can_do([a, b], [a + b - S.Half]) + assert can_do([a, b], [a + b + Rational(3, 2)]) + assert can_do([a, b], [(a + b + 1)/2]) + assert can_do([a, b], [(a + b)/2 + 1]) + assert can_do([a, b], [a - b + 1]) + assert can_do([a, b], [a - b + 2]) + assert can_do([a, b], [2*b]) + assert can_do([a, b], [S.Half]) + assert can_do([a, b], [Rational(3, 2)]) + assert can_do([a, 1 - a], [c]) + assert can_do([a, 2 - a], [c]) + assert can_do([a, 3 - a], [c]) + assert can_do([a, a + S.Half], [c]) + assert can_do([1, b], [c]) + assert can_do([1, b], [Rational(3, 2)]) + + assert can_do([Rational(1, 4), Rational(3, 4)], [1]) + + # PFDD + o = S.One + assert can_do([o/8, 1], [o/8*9]) + assert can_do([o/6, 1], [o/6*7]) + assert can_do([o/6, 1], [o/6*13]) + assert can_do([o/5, 1], [o/5*6]) + assert can_do([o/5, 1], [o/5*11]) + assert can_do([o/4, 1], [o/4*5]) + assert can_do([o/4, 1], [o/4*9]) + assert can_do([o/3, 1], [o/3*4]) + assert can_do([o/3, 1], [o/3*7]) + assert can_do([o/8*3, 1], [o/8*11]) + assert can_do([o/5*2, 1], [o/5*7]) + assert can_do([o/5*2, 1], [o/5*12]) + assert can_do([o/5*3, 1], [o/5*8]) + assert can_do([o/5*3, 1], [o/5*13]) + assert can_do([o/8*5, 1], [o/8*13]) + assert can_do([o/4*3, 1], [o/4*7]) + assert can_do([o/4*3, 1], [o/4*11]) + assert can_do([o/3*2, 1], [o/3*5]) + assert can_do([o/3*2, 1], [o/3*8]) + assert can_do([o/5*4, 1], [o/5*9]) + assert can_do([o/5*4, 1], [o/5*14]) + assert can_do([o/6*5, 1], [o/6*11]) + assert can_do([o/6*5, 1], [o/6*17]) + assert can_do([o/8*7, 1], [o/8*15]) + + +@XFAIL +def test_prudnikov_fail_3F2(): + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(1, 3), Rational(2, 3)]) + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(2, 3), Rational(4, 3)]) + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(4, 3), Rational(5, 3)]) + + # page 421 + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [a*Rational(3, 2), (3*a + 1)/2]) + + # pages 422 ... + assert can_do([Rational(-1, 2), S.Half, S.Half], [1, 1]) # elliptic integrals + assert can_do([Rational(-1, 2), S.Half, 1], [Rational(3, 2), Rational(3, 2)]) + # TODO LOTS more + + # PFDD + assert can_do([Rational(1, 8), Rational(3, 8), 1], [Rational(9, 8), Rational(11, 8)]) + assert can_do([Rational(1, 8), Rational(5, 8), 1], [Rational(9, 8), Rational(13, 8)]) + assert can_do([Rational(1, 8), Rational(7, 8), 1], [Rational(9, 8), Rational(15, 8)]) + assert can_do([Rational(1, 6), Rational(1, 3), 1], [Rational(7, 6), Rational(4, 3)]) + assert can_do([Rational(1, 6), Rational(2, 3), 1], [Rational(7, 6), Rational(5, 3)]) + assert can_do([Rational(1, 6), Rational(2, 3), 1], [Rational(5, 3), Rational(13, 6)]) + assert can_do([S.Half, 1, 1], [Rational(1, 4), Rational(3, 4)]) + # LOTS more + + +@XFAIL +def test_prudnikov_fail_other(): + # 7.11.2 + + # 7.12.1 + assert can_do([1, a], [b, 1 - 2*a + b]) # ??? + + # 7.14.2 + assert can_do([Rational(-1, 2)], [S.Half, 1]) # struve + assert can_do([1], [S.Half, S.Half]) # struve + assert can_do([Rational(1, 4)], [S.Half, Rational(5, 4)]) # PFDD + assert can_do([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)]) # PFDD + assert can_do([1], [Rational(1, 4), Rational(3, 4)]) # PFDD + assert can_do([1], [Rational(3, 4), Rational(5, 4)]) # PFDD + assert can_do([1], [Rational(5, 4), Rational(7, 4)]) # PFDD + # TODO LOTS more + + # 7.15.2 + assert can_do([S.Half, 1], [Rational(3, 4), Rational(5, 4), Rational(3, 2)]) # PFDD + assert can_do([S.Half, 1], [Rational(7, 4), Rational(5, 4), Rational(3, 2)]) # PFDD + + # 7.16.1 + assert can_do([], [Rational(1, 3), S(2/3)]) # PFDD + assert can_do([], [Rational(2, 3), S(4/3)]) # PFDD + assert can_do([], [Rational(5, 3), S(4/3)]) # PFDD + + # XXX this does not *evaluate* right?? + assert can_do([], [a, a + S.Half, 2*a - 1]) + + +def test_bug(): + h = hyper([-1, 1], [z], -1) + assert hyperexpand(h) == (z + 1)/z + + +def test_omgissue_203(): + h = hyper((-5, -3, -4), (-6, -6), 1) + assert hyperexpand(h) == Rational(1, 30) + h = hyper((-6, -7, -5), (-6, -6), 1) + assert hyperexpand(h) == Rational(-1, 6) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_powsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_powsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..61bdc93d052baf4b1e80da8f5864cf22b8fa383e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_powsimp.py @@ -0,0 +1,368 @@ +from sympy.core.function import Function +from sympy.core.mul import Mul +from sympy.core.numbers import (E, I, Rational, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import (root, sqrt) +from sympy.functions.elementary.trigonometric import sin +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.hyper import hyper +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.simplify.powsimp import (powdenest, powsimp) +from sympy.simplify.simplify import (signsimp, simplify) +from sympy.core.symbol import Str + +from sympy.abc import x, y, z, a, b + + +def test_powsimp(): + x, y, z, n = symbols('x,y,z,n') + f = Function('f') + assert powsimp( 4**x * 2**(-x) * 2**(-x) ) == 1 + assert powsimp( (-4)**x * (-2)**(-x) * 2**(-x) ) == 1 + + assert powsimp( + f(4**x * 2**(-x) * 2**(-x)) ) == f(4**x * 2**(-x) * 2**(-x)) + assert powsimp( f(4**x * 2**(-x) * 2**(-x)), deep=True ) == f(1) + assert exp(x)*exp(y) == exp(x)*exp(y) + assert powsimp(exp(x)*exp(y)) == exp(x + y) + assert powsimp(exp(x)*exp(y)*2**x*2**y) == (2*E)**(x + y) + assert powsimp(exp(x)*exp(y)*2**x*2**y, combine='exp') == \ + exp(x + y)*2**(x + y) + assert powsimp(exp(x)*exp(y)*exp(2)*sin(x) + sin(y) + 2**x*2**y) == \ + exp(2 + x + y)*sin(x) + sin(y) + 2**(x + y) + assert powsimp(sin(exp(x)*exp(y))) == sin(exp(x)*exp(y)) + assert powsimp(sin(exp(x)*exp(y)), deep=True) == sin(exp(x + y)) + assert powsimp(x**2*x**y) == x**(2 + y) + # This should remain factored, because 'exp' with deep=True is supposed + # to act like old automatic exponent combining. + assert powsimp((1 + E*exp(E))*exp(-E), combine='exp', deep=True) == \ + (1 + exp(1 + E))*exp(-E) + assert powsimp((1 + E*exp(E))*exp(-E), deep=True) == \ + (1 + exp(1 + E))*exp(-E) + assert powsimp((1 + E*exp(E))*exp(-E)) == (1 + exp(1 + E))*exp(-E) + assert powsimp((1 + E*exp(E))*exp(-E), combine='exp') == \ + (1 + exp(1 + E))*exp(-E) + assert powsimp((1 + E*exp(E))*exp(-E), combine='base') == \ + (1 + E*exp(E))*exp(-E) + x, y = symbols('x,y', nonnegative=True) + n = Symbol('n', real=True) + assert powsimp(y**n * (y/x)**(-n)) == x**n + assert powsimp(x**(x**(x*y)*y**(x*y))*y**(x**(x*y)*y**(x*y)), deep=True) \ + == (x*y)**(x*y)**(x*y) + assert powsimp(2**(2**(2*x)*x), deep=False) == 2**(2**(2*x)*x) + assert powsimp(2**(2**(2*x)*x), deep=True) == 2**(x*4**x) + assert powsimp( + exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \ + exp(-x + exp(-x)*exp(-x*log(x))) + assert powsimp( + exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \ + exp(-x + exp(-x)*exp(-x*log(x))) + assert powsimp((x + y)/(3*z), deep=False, combine='exp') == (x + y)/(3*z) + assert powsimp((x/3 + y/3)/z, deep=True, combine='exp') == (x/3 + y/3)/z + assert powsimp(exp(x)/(1 + exp(x)*exp(y)), deep=True) == \ + exp(x)/(1 + exp(x + y)) + assert powsimp(x*y**(z**x*z**y), deep=True) == x*y**(z**(x + y)) + assert powsimp((z**x*z**y)**x, deep=True) == (z**(x + y))**x + assert powsimp(x*(z**x*z**y)**x, deep=True) == x*(z**(x + y))**x + p = symbols('p', positive=True) + assert powsimp((1/x)**log(2)/x) == (1/x)**(1 + log(2)) + assert powsimp((1/p)**log(2)/p) == p**(-1 - log(2)) + + # coefficient of exponent can only be simplified for positive bases + assert powsimp(2**(2*x)) == 4**x + assert powsimp((-1)**(2*x)) == (-1)**(2*x) + i = symbols('i', integer=True) + assert powsimp((-1)**(2*i)) == 1 + assert powsimp((-1)**(-x)) != (-1)**x # could be 1/((-1)**x), but is not + # force=True overrides assumptions + assert powsimp((-1)**(2*x), force=True) == 1 + + # rational exponents allow combining of negative terms + w, n, m = symbols('w n m', negative=True) + e = i/a # not a rational exponent if `a` is unknown + ex = w**e*n**e*m**e + assert powsimp(ex) == m**(i/a)*n**(i/a)*w**(i/a) + e = i/3 + ex = w**e*n**e*m**e + assert powsimp(ex) == (-1)**i*(-m*n*w)**(i/3) + e = (3 + i)/i + ex = w**e*n**e*m**e + assert powsimp(ex) == (-1)**(3*e)*(-m*n*w)**e + + eq = x**(a*Rational(2, 3)) + # eq != (x**a)**(2/3) (try x = -1 and a = 3 to see) + assert powsimp(eq).exp == eq.exp == a*Rational(2, 3) + # powdenest goes the other direction + assert powsimp(2**(2*x)) == 4**x + + assert powsimp(exp(p/2)) == exp(p/2) + + # issue 6368 + eq = Mul(*[sqrt(Dummy(imaginary=True)) for i in range(3)]) + assert powsimp(eq) == eq and eq.is_Mul + + assert all(powsimp(e) == e for e in (sqrt(x**a), sqrt(x**2))) + + # issue 8836 + assert str( powsimp(exp(I*pi/3)*root(-1,3)) ) == '(-1)**(2/3)' + + # issue 9183 + assert powsimp(-0.1**x) == -0.1**x + + # issue 10095 + assert powsimp((1/(2*E))**oo) == (exp(-1)/2)**oo + + # PR 13131 + eq = sin(2*x)**2*sin(2.0*x)**2 + assert powsimp(eq) == eq + + # issue 14615 + assert powsimp(x**2*y**3*(x*y**2)**Rational(3, 2) + ) == x*y*(x*y**2)**Rational(5, 2) + + #issue 27380 + assert powsimp(1.0**(x+1)/1.0**x) == 1.0 + +def test_powsimp_negated_base(): + assert powsimp((-x + y)/sqrt(x - y)) == -sqrt(x - y) + assert powsimp((-x + y)*(-z + y)/sqrt(x - y)/sqrt(z - y)) == sqrt(x - y)*sqrt(z - y) + p = symbols('p', positive=True) + reps = {p: 2, a: S.Half} + assert powsimp((-p)**a/p**a).subs(reps) == ((-1)**a).subs(reps) + assert powsimp((-p)**a*p**a).subs(reps) == ((-p**2)**a).subs(reps) + n = symbols('n', negative=True) + reps = {p: -2, a: S.Half} + assert powsimp((-n)**a/n**a).subs(reps) == (-1)**(-a).subs(a, S.Half) + assert powsimp((-n)**a*n**a).subs(reps) == ((-n**2)**a).subs(reps) + # if x is 0 then the lhs is 0**a*oo**a which is not (-1)**a + eq = (-x)**a/x**a + assert powsimp(eq) == eq + + +def test_powsimp_nc(): + x, y, z = symbols('x,y,z') + A, B, C = symbols('A B C', commutative=False) + + assert powsimp(A**x*A**y, combine='all') == A**(x + y) + assert powsimp(A**x*A**y, combine='base') == A**x*A**y + assert powsimp(A**x*A**y, combine='exp') == A**(x + y) + + assert powsimp(A**x*B**x, combine='all') == A**x*B**x + assert powsimp(A**x*B**x, combine='base') == A**x*B**x + assert powsimp(A**x*B**x, combine='exp') == A**x*B**x + + assert powsimp(B**x*A**x, combine='all') == B**x*A**x + assert powsimp(B**x*A**x, combine='base') == B**x*A**x + assert powsimp(B**x*A**x, combine='exp') == B**x*A**x + + assert powsimp(A**x*A**y*A**z, combine='all') == A**(x + y + z) + assert powsimp(A**x*A**y*A**z, combine='base') == A**x*A**y*A**z + assert powsimp(A**x*A**y*A**z, combine='exp') == A**(x + y + z) + + assert powsimp(A**x*B**x*C**x, combine='all') == A**x*B**x*C**x + assert powsimp(A**x*B**x*C**x, combine='base') == A**x*B**x*C**x + assert powsimp(A**x*B**x*C**x, combine='exp') == A**x*B**x*C**x + + assert powsimp(B**x*A**x*C**x, combine='all') == B**x*A**x*C**x + assert powsimp(B**x*A**x*C**x, combine='base') == B**x*A**x*C**x + assert powsimp(B**x*A**x*C**x, combine='exp') == B**x*A**x*C**x + + +def test_issue_6440(): + assert powsimp(16*2**a*8**b) == 2**(a + 3*b + 4) + + +def test_powdenest(): + x, y = symbols('x,y') + p, q = symbols('p q', positive=True) + i, j = symbols('i,j', integer=True) + + assert powdenest(x) == x + assert powdenest(x + 2*(x**(a*Rational(2, 3)))**(3*x)) == (x + 2*(x**(a*Rational(2, 3)))**(3*x)) + assert powdenest((exp(a*Rational(2, 3)))**(3*x)) # -X-> (exp(a/3))**(6*x) + assert powdenest((x**(a*Rational(2, 3)))**(3*x)) == ((x**(a*Rational(2, 3)))**(3*x)) + assert powdenest(exp(3*x*log(2))) == 2**(3*x) + assert powdenest(sqrt(p**2)) == p + eq = p**(2*i)*q**(4*i) + assert powdenest(eq) == (p*q**2)**(2*i) + # -X-> (x**x)**i*(x**x)**j == x**(x*(i + j)) + assert powdenest((x**x)**(i + j)) + assert powdenest(exp(3*y*log(x))) == x**(3*y) + assert powdenest(exp(y*(log(a) + log(b)))) == (a*b)**y + assert powdenest(exp(3*(log(a) + log(b)))) == a**3*b**3 + assert powdenest(((x**(2*i))**(3*y))**x) == ((x**(2*i))**(3*y))**x + assert powdenest(((x**(2*i))**(3*y))**x, force=True) == x**(6*i*x*y) + assert powdenest(((x**(a*Rational(2, 3)))**(3*y/i))**x) == \ + (((x**(a*Rational(2, 3)))**(3*y/i))**x) + assert powdenest((x**(2*i)*y**(4*i))**z, force=True) == (x*y**2)**(2*i*z) + assert powdenest((p**(2*i)*q**(4*i))**j) == (p*q**2)**(2*i*j) + e = ((p**(2*a))**(3*y))**x + assert powdenest(e) == e + e = ((x**2*y**4)**a)**(x*y) + assert powdenest(e) == e + e = (((x**2*y**4)**a)**(x*y))**3 + assert powdenest(e) == ((x**2*y**4)**a)**(3*x*y) + assert powdenest((((x**2*y**4)**a)**(x*y)), force=True) == \ + (x*y**2)**(2*a*x*y) + assert powdenest((((x**2*y**4)**a)**(x*y))**3, force=True) == \ + (x*y**2)**(6*a*x*y) + assert powdenest((x**2*y**6)**i) != (x*y**3)**(2*i) + x, y = symbols('x,y', positive=True) + assert powdenest((x**2*y**6)**i) == (x*y**3)**(2*i) + + assert powdenest((x**(i*Rational(2, 3))*y**(i/2))**(2*i)) == (x**Rational(4, 3)*y)**(i**2) + assert powdenest(sqrt(x**(2*i)*y**(6*i))) == (x*y**3)**i + + assert powdenest(4**x) == 2**(2*x) + assert powdenest((4**x)**y) == 2**(2*x*y) + assert powdenest(4**x*y) == 2**(2*x)*y + + +def test_powdenest_polar(): + x, y, z = symbols('x y z', polar=True) + a, b, c = symbols('a b c') + assert powdenest((x*y*z)**a) == x**a*y**a*z**a + assert powdenest((x**a*y**b)**c) == x**(a*c)*y**(b*c) + assert powdenest(((x**a)**b*y**c)**c) == x**(a*b*c)*y**(c**2) + + +def test_issue_5805(): + arg = ((gamma(x)*hyper((), (), x))*pi)**2 + assert powdenest(arg) == (pi*gamma(x)*hyper((), (), x))**2 + assert arg.is_positive is None + + +def test_issue_9324_powsimp_on_matrix_symbol(): + M = MatrixSymbol('M', 10, 10) + expr = powsimp(M, deep=True) + assert expr == M + assert expr.args[0] == Str('M') + + +def test_issue_6367(): + z = -5*sqrt(2)/(2*sqrt(2*sqrt(29) + 29)) + sqrt(-sqrt(29)/29 + S.Half) + assert Mul(*[powsimp(a) for a in Mul.make_args(z.normal())]) == 0 + assert powsimp(z.normal()) == 0 + assert simplify(z) == 0 + assert powsimp(sqrt(2 + sqrt(3))*sqrt(2 - sqrt(3)) + 1) == 2 + assert powsimp(z) != 0 + + +def test_powsimp_polar(): + from sympy.functions.elementary.complexes import polar_lift + from sympy.functions.elementary.exponential import exp_polar + x, y, z = symbols('x y z') + p, q, r = symbols('p q r', polar=True) + + assert (polar_lift(-1))**(2*x) == exp_polar(2*pi*I*x) + assert powsimp(p**x * q**x) == (p*q)**x + assert p**x * (1/p)**x == 1 + assert (1/p)**x == p**(-x) + + assert exp_polar(x)*exp_polar(y) == exp_polar(x)*exp_polar(y) + assert powsimp(exp_polar(x)*exp_polar(y)) == exp_polar(x + y) + assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y) == \ + (p*exp_polar(1))**(x + y) + assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y, combine='exp') == \ + exp_polar(x + y)*p**(x + y) + assert powsimp( + exp_polar(x)*exp_polar(y)*exp_polar(2)*sin(x) + sin(y) + p**x*p**y) \ + == p**(x + y) + sin(x)*exp_polar(2 + x + y) + sin(y) + assert powsimp(sin(exp_polar(x)*exp_polar(y))) == \ + sin(exp_polar(x)*exp_polar(y)) + assert powsimp(sin(exp_polar(x)*exp_polar(y)), deep=True) == \ + sin(exp_polar(x + y)) + + +def test_issue_5728(): + b = x*sqrt(y) + a = sqrt(b) + c = sqrt(sqrt(x)*y) + assert powsimp(a*b) == sqrt(b)**3 + assert powsimp(a*b**2*sqrt(y)) == sqrt(y)*a**5 + assert powsimp(a*x**2*c**3*y) == c**3*a**5 + assert powsimp(a*x*c**3*y**2) == c**7*a + assert powsimp(x*c**3*y**2) == c**7 + assert powsimp(x*c**3*y) == x*y*c**3 + assert powsimp(sqrt(x)*c**3*y) == c**5 + assert powsimp(sqrt(x)*a**3*sqrt(y)) == sqrt(x)*sqrt(y)*a**3 + assert powsimp(Mul(sqrt(x)*c**3*sqrt(y), y, evaluate=False)) == \ + sqrt(x)*sqrt(y)**3*c**3 + assert powsimp(a**2*a*x**2*y) == a**7 + + # symbolic powers work, too + b = x**y*y + a = b*sqrt(b) + assert a.is_Mul is True + assert powsimp(a) == sqrt(b)**3 + + # as does exp + a = x*exp(y*Rational(2, 3)) + assert powsimp(a*sqrt(a)) == sqrt(a)**3 + assert powsimp(a**2*sqrt(a)) == sqrt(a)**5 + assert powsimp(a**2*sqrt(sqrt(a))) == sqrt(sqrt(a))**9 + + +def test_issue_from_PR1599(): + n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True) + assert (powsimp(sqrt(n1)*sqrt(n2)*sqrt(n3)) == + -I*sqrt(-n1)*sqrt(-n2)*sqrt(-n3)) + assert (powsimp(root(n1, 3)*root(n2, 3)*root(n3, 3)*root(n4, 3)) == + -(-1)**Rational(1, 3)* + (-n1)**Rational(1, 3)*(-n2)**Rational(1, 3)*(-n3)**Rational(1, 3)*(-n4)**Rational(1, 3)) + + +def test_issue_10195(): + a = Symbol('a', integer=True) + l = Symbol('l', even=True, nonzero=True) + n = Symbol('n', odd=True) + e_x = (-1)**(n/2 - S.Half) - (-1)**(n*Rational(3, 2) - S.Half) + assert powsimp((-1)**(l/2)) == I**l + assert powsimp((-1)**(n/2)) == I**n + assert powsimp((-1)**(n*Rational(3, 2))) == -I**n + assert powsimp(e_x) == (-1)**(n/2 - S.Half) + (-1)**(n*Rational(3, 2) + + S.Half) + assert powsimp((-1)**(a*Rational(3, 2))) == (-I)**a + +def test_issue_15709(): + assert powsimp(3**x*Rational(2, 3)) == 2*3**(x-1) + assert powsimp(2*3**x/3) == 2*3**(x-1) + + +def test_issue_11981(): + x, y = symbols('x y', commutative=False) + assert powsimp((x*y)**2 * (y*x)**2) == (x*y)**2 * (y*x)**2 + + +def test_issue_17524(): + a = symbols("a", real=True) + e = (-1 - a**2)*sqrt(1 + a**2) + assert signsimp(powsimp(e)) == signsimp(e) == -(a**2 + 1)**(S(3)/2) + + +def test_issue_19627(): + # if you use force the user must verify + assert powdenest(sqrt(sin(x)**2), force=True) == sin(x) + assert powdenest((x**(S.Half/y))**(2*y), force=True) == x + from sympy.core.function import expand_power_base + e = 1 - a + expr = (exp(z/e)*x**(b/e)*y**((1 - b)/e))**e + assert powdenest(expand_power_base(expr, force=True), force=True + ) == x**b*y**(1 - b)*exp(z) + + +def test_issue_22546(): + p1, p2 = symbols('p1, p2', positive=True) + ref = powsimp(p1**z/p2**z) + e = z + 1 + ans = ref.subs(z, e) + assert ans.is_Pow + assert powsimp(p1**e/p2**e) == ans + i = symbols('i', integer=True) + ref = powsimp(x**i/y**i) + e = i + 1 + ans = ref.subs(i, e) + assert ans.is_Pow + assert powsimp(x**e/y**e) == ans diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_radsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_radsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..f8ff955e48a34536c1752c565c0864dedae6a214 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_radsimp.py @@ -0,0 +1,498 @@ +from sympy.core.add import Add +from sympy.core.function import (Derivative, Function, diff) +from sympy.core.mul import Mul +from sympy.core.numbers import (I, Rational) +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, Wild, symbols) +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import (root, sqrt) +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.polys.polytools import factor +from sympy.series.order import O +from sympy.simplify.radsimp import (collect, collect_const, fraction, radsimp, rcollect) + +from sympy.core.expr import unchanged +from sympy.core.mul import _unevaluated_Mul as umul +from sympy.simplify.radsimp import (_unevaluated_Add, + collect_sqrt, fraction_expand, collect_abs) +from sympy.testing.pytest import raises + +from sympy.abc import x, y, z, a, b, c, d + + +def test_radsimp(): + r2 = sqrt(2) + r3 = sqrt(3) + r5 = sqrt(5) + r7 = sqrt(7) + assert fraction(radsimp(1/r2)) == (sqrt(2), 2) + assert radsimp(1/(1 + r2)) == \ + -1 + sqrt(2) + assert radsimp(1/(r2 + r3)) == \ + -sqrt(2) + sqrt(3) + assert fraction(radsimp(1/(1 + r2 + r3))) == \ + (-sqrt(6) + sqrt(2) + 2, 4) + assert fraction(radsimp(1/(r2 + r3 + r5))) == \ + (-sqrt(30) + 2*sqrt(3) + 3*sqrt(2), 12) + assert fraction(radsimp(1/(1 + r2 + r3 + r5))) == ( + (-34*sqrt(10) - 26*sqrt(15) - 55*sqrt(3) - 61*sqrt(2) + 14*sqrt(30) + + 93 + 46*sqrt(6) + 53*sqrt(5), 71)) + assert fraction(radsimp(1/(r2 + r3 + r5 + r7))) == ( + (-50*sqrt(42) - 133*sqrt(5) - 34*sqrt(70) - 145*sqrt(3) + 22*sqrt(105) + + 185*sqrt(2) + 62*sqrt(30) + 135*sqrt(7), 215)) + z = radsimp(1/(1 + r2/3 + r3/5 + r5 + r7)) + assert len((3616791619821680643598*z).args) == 16 + assert radsimp(1/z) == 1/z + assert radsimp(1/z, max_terms=20).expand() == 1 + r2/3 + r3/5 + r5 + r7 + assert radsimp(1/(r2*3)) == \ + sqrt(2)/6 + assert radsimp(1/(r2*a + r3 + r5 + r7)) == ( + (8*sqrt(2)*a**7 - 8*sqrt(7)*a**6 - 8*sqrt(5)*a**6 - 8*sqrt(3)*a**6 - + 180*sqrt(2)*a**5 + 8*sqrt(30)*a**5 + 8*sqrt(42)*a**5 + 8*sqrt(70)*a**5 + - 24*sqrt(105)*a**4 + 84*sqrt(3)*a**4 + 100*sqrt(5)*a**4 + + 116*sqrt(7)*a**4 - 72*sqrt(70)*a**3 - 40*sqrt(42)*a**3 - + 8*sqrt(30)*a**3 + 782*sqrt(2)*a**3 - 462*sqrt(3)*a**2 - + 302*sqrt(7)*a**2 - 254*sqrt(5)*a**2 + 120*sqrt(105)*a**2 - + 795*sqrt(2)*a - 62*sqrt(30)*a + 82*sqrt(42)*a + 98*sqrt(70)*a - + 118*sqrt(105) + 59*sqrt(7) + 295*sqrt(5) + 531*sqrt(3))/(16*a**8 - + 480*a**6 + 3128*a**4 - 6360*a**2 + 3481)) + assert radsimp(1/(r2*a + r2*b + r3 + r7)) == ( + (sqrt(2)*a*(a + b)**2 - 5*sqrt(2)*a + sqrt(42)*a + sqrt(2)*b*(a + + b)**2 - 5*sqrt(2)*b + sqrt(42)*b - sqrt(7)*(a + b)**2 - sqrt(3)*(a + + b)**2 - 2*sqrt(3) + 2*sqrt(7))/(2*a**4 + 8*a**3*b + 12*a**2*b**2 - + 20*a**2 + 8*a*b**3 - 40*a*b + 2*b**4 - 20*b**2 + 8)) + assert radsimp(1/(r2*a + r2*b + r2*c + r2*d)) == \ + sqrt(2)/(2*a + 2*b + 2*c + 2*d) + assert radsimp(1/(1 + r2*a + r2*b + r2*c + r2*d)) == ( + (sqrt(2)*a + sqrt(2)*b + sqrt(2)*c + sqrt(2)*d - 1)/(2*a**2 + 4*a*b + + 4*a*c + 4*a*d + 2*b**2 + 4*b*c + 4*b*d + 2*c**2 + 4*c*d + 2*d**2 - 1)) + assert radsimp((y**2 - x)/(y - sqrt(x))) == \ + sqrt(x) + y + assert radsimp(-(y**2 - x)/(y - sqrt(x))) == \ + -(sqrt(x) + y) + assert radsimp(1/(1 - I + a*I)) == \ + (-I*a + 1 + I)/(a**2 - 2*a + 2) + assert radsimp(1/((-x + y)*(x - sqrt(y)))) == \ + (-x - sqrt(y))/((x - y)*(x**2 - y)) + e = (3 + 3*sqrt(2))*x*(3*x - 3*sqrt(y)) + assert radsimp(e) == x*(3 + 3*sqrt(2))*(3*x - 3*sqrt(y)) + assert radsimp(1/e) == ( + (-9*x + 9*sqrt(2)*x - 9*sqrt(y) + 9*sqrt(2)*sqrt(y))/(9*x*(9*x**2 - + 9*y))) + assert radsimp(1 + 1/(1 + sqrt(3))) == \ + Mul(S.Half, -1 + sqrt(3), evaluate=False) + 1 + A = symbols("A", commutative=False) + assert radsimp(x**2 + sqrt(2)*x**2 - sqrt(2)*x*A) == \ + x**2 + sqrt(2)*x**2 - sqrt(2)*x*A + assert radsimp(1/sqrt(5 + 2 * sqrt(6))) == -sqrt(2) + sqrt(3) + assert radsimp(1/sqrt(5 + 2 * sqrt(6))**3) == -(-sqrt(3) + sqrt(2))**3 + + # issue 6532 + assert fraction(radsimp(1/sqrt(x))) == (sqrt(x), x) + assert fraction(radsimp(1/sqrt(2*x + 3))) == (sqrt(2*x + 3), 2*x + 3) + assert fraction(radsimp(1/sqrt(2*(x + 3)))) == (sqrt(2*x + 6), 2*x + 6) + + # issue 5994 + e = S('-(2 + 2*sqrt(2) + 4*2**(1/4))/' + '(1 + 2**(3/4) + 3*2**(1/4) + 3*sqrt(2))') + assert radsimp(e).expand() == -2*2**Rational(3, 4) - 2*2**Rational(1, 4) + 2 + 2*sqrt(2) + + # issue 5986 (modifications to radimp didn't initially recognize this so + # the test is included here) + assert radsimp(1/(-sqrt(5)/2 - S.Half + (-sqrt(5)/2 - S.Half)**2)) == 1 + + # from issue 5934 + eq = ( + (-240*sqrt(2)*sqrt(sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) - + 360*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) - + 120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) + + 120*sqrt(2)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) + + 120*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5) + + 120*sqrt(10)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) + + 120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5))/(-36000 - + 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) + + 24*sqrt(10)*sqrt(-sqrt(5) + 5))**2)) + assert radsimp(eq) is S.NaN # it's 0/0 + + # work with normal form + e = 1/sqrt(sqrt(7)/7 + 2*sqrt(2) + 3*sqrt(3) + 5*sqrt(5)) + 3 + assert radsimp(e) == ( + -sqrt(sqrt(7) + 14*sqrt(2) + 21*sqrt(3) + + 35*sqrt(5))*(-11654899*sqrt(35) - 1577436*sqrt(210) - 1278438*sqrt(15) + - 1346996*sqrt(10) + 1635060*sqrt(6) + 5709765 + 7539830*sqrt(14) + + 8291415*sqrt(21))/1300423175 + 3) + + # obey power rules + base = sqrt(3) - sqrt(2) + assert radsimp(1/base**3) == (sqrt(3) + sqrt(2))**3 + assert radsimp(1/(-base)**3) == -(sqrt(2) + sqrt(3))**3 + assert radsimp(1/(-base)**x) == (-base)**(-x) + assert radsimp(1/base**x) == (sqrt(2) + sqrt(3))**x + assert radsimp(root(1/(-1 - sqrt(2)), -x)) == (-1)**(-1/x)*(1 + sqrt(2))**(1/x) + + # recurse + e = cos(1/(1 + sqrt(2))) + assert radsimp(e) == cos(-sqrt(2) + 1) + assert radsimp(e/2) == cos(-sqrt(2) + 1)/2 + assert radsimp(1/e) == 1/cos(-sqrt(2) + 1) + assert radsimp(2/e) == 2/cos(-sqrt(2) + 1) + assert fraction(radsimp(e/sqrt(x))) == (sqrt(x)*cos(-sqrt(2)+1), x) + + # test that symbolic denominators are not processed + r = 1 + sqrt(2) + assert radsimp(x/r, symbolic=False) == -x*(-sqrt(2) + 1) + assert radsimp(x/(y + r), symbolic=False) == x/(y + 1 + sqrt(2)) + assert radsimp(x/(y + r)/r, symbolic=False) == \ + -x*(-sqrt(2) + 1)/(y + 1 + sqrt(2)) + + # issue 7408 + eq = sqrt(x)/sqrt(y) + assert radsimp(eq) == umul(sqrt(x), sqrt(y), 1/y) + assert radsimp(eq, symbolic=False) == eq + + # issue 7498 + assert radsimp(sqrt(x)/sqrt(y)**3) == umul(sqrt(x), sqrt(y**3), 1/y**3) + + # for coverage + eq = sqrt(x)/y**2 + assert radsimp(eq) == eq + + # handle non-Expr args + from sympy.integrals.integrals import Integral + eq = Integral(x/(sqrt(2) - 1), (x, 0, 1/(sqrt(2) + 1))) + assert radsimp(eq) == Integral((sqrt(2) + 1)*x , (x, 0, sqrt(2) - 1)) + + from sympy.sets import FiniteSet + eq = FiniteSet(x/(sqrt(2) - 1)) + assert radsimp(eq) == FiniteSet((sqrt(2) + 1)*x) + +def test_radsimp_issue_3214(): + c, p = symbols('c p', positive=True) + s = sqrt(c**2 - p**2) + b = (c + I*p - s)/(c + I*p + s) + assert radsimp(b) == -I*(c + I*p - sqrt(c**2 - p**2))**2/(2*c*p) + + +def test_collect_1(): + """Collect with respect to Symbol""" + x, y, z, n = symbols('x,y,z,n') + assert collect(1, x) == 1 + assert collect( x + y*x, x ) == x * (1 + y) + assert collect( x + x**2, x ) == x + x**2 + assert collect( x**2 + y*x**2, x ) == (x**2)*(1 + y) + assert collect( x**2 + y*x, x ) == x*y + x**2 + assert collect( 2*x**2 + y*x**2 + 3*x*y, [x] ) == x**2*(2 + y) + 3*x*y + assert collect( 2*x**2 + y*x**2 + 3*x*y, [y] ) == 2*x**2 + y*(x**2 + 3*x) + + assert collect( ((1 + y + x)**4).expand(), x) == ((1 + y)**4).expand() + \ + x*(4*(1 + y)**3).expand() + x**2*(6*(1 + y)**2).expand() + \ + x**3*(4*(1 + y)).expand() + x**4 + # symbols can be given as any iterable + expr = x + y + assert collect(expr, expr.free_symbols) == expr + assert collect(x*exp(x) + sin(x)*y + sin(x)*2 + 3*x, x, exact=None + ) == x*exp(x) + 3*x + (y + 2)*sin(x) + assert collect(x*exp(x) + sin(x)*y + sin(x)*2 + 3*x + y*x + + y*x*exp(x), x, exact=None + ) == x*exp(x)*(y + 1) + (3 + y)*x + (y + 2)*sin(x) + + +def test_collect_2(): + """Collect with respect to a sum""" + a, b, x = symbols('a,b,x') + assert collect(a*(cos(x) + sin(x)) + b*(cos(x) + sin(x)), + sin(x) + cos(x)) == (a + b)*(cos(x) + sin(x)) + + +def test_collect_3(): + """Collect with respect to a product""" + a, b, c = symbols('a,b,c') + f = Function('f') + x, y, z, n = symbols('x,y,z,n') + + assert collect(-x/8 + x*y, -x) == x*(y - Rational(1, 8)) + + assert collect( 1 + x*(y**2), x*y ) == 1 + x*(y**2) + assert collect( x*y + a*x*y, x*y) == x*y*(1 + a) + assert collect( 1 + x*y + a*x*y, x*y) == 1 + x*y*(1 + a) + assert collect(a*x*f(x) + b*(x*f(x)), x*f(x)) == x*(a + b)*f(x) + + assert collect(a*x*log(x) + b*(x*log(x)), x*log(x)) == x*(a + b)*log(x) + assert collect(a*x**2*log(x)**2 + b*(x*log(x))**2, x*log(x)) == \ + x**2*log(x)**2*(a + b) + + # with respect to a product of three symbols + assert collect(y*x*z + a*x*y*z, x*y*z) == (1 + a)*x*y*z + + +def test_collect_4(): + """Collect with respect to a power""" + a, b, c, x = symbols('a,b,c,x') + + assert collect(a*x**c + b*x**c, x**c) == x**c*(a + b) + # issue 6096: 2 stays with c (unless c is integer or x is positive0 + assert collect(a*x**(2*c) + b*x**(2*c), x**c) == x**(2*c)*(a + b) + + +def test_collect_5(): + """Collect with respect to a tuple""" + a, x, y, z, n = symbols('a,x,y,z,n') + assert collect(x**2*y**4 + z*(x*y**2)**2 + z + a*z, [x*y**2, z]) in [ + z*(1 + a + x**2*y**4) + x**2*y**4, + z*(1 + a) + x**2*y**4*(1 + z) ] + assert collect((1 + (x + y) + (x + y)**2).expand(), + [x, y]) == 1 + y + x*(1 + 2*y) + x**2 + y**2 + + +def test_collect_pr19431(): + """Unevaluated collect with respect to a product""" + a = symbols('a') + assert collect(a**2*(a**2 + 1), a**2, evaluate=False)[a**2] == (a**2 + 1) + + +def test_collect_D(): + D = Derivative + f = Function('f') + x, a, b = symbols('x,a,b') + fx = D(f(x), x) + fxx = D(f(x), x, x) + + assert collect(a*fx + b*fx, fx) == (a + b)*fx + assert collect(a*D(fx, x) + b*D(fx, x), fx) == (a + b)*D(fx, x) + assert collect(a*fxx + b*fxx, fx) == (a + b)*D(fx, x) + # issue 4784 + assert collect(5*f(x) + 3*fx, fx) == 5*f(x) + 3*fx + assert collect(f(x) + f(x)*diff(f(x), x) + x*diff(f(x), x)*f(x), f(x).diff(x)) == \ + (x*f(x) + f(x))*D(f(x), x) + f(x) + assert collect(f(x) + f(x)*diff(f(x), x) + x*diff(f(x), x)*f(x), f(x).diff(x), exact=True) == \ + (x*f(x) + f(x))*D(f(x), x) + f(x) + assert collect(1/f(x) + 1/f(x)*diff(f(x), x) + x*diff(f(x), x)/f(x), f(x).diff(x), exact=True) == \ + (1/f(x) + x/f(x))*D(f(x), x) + 1/f(x) + e = (1 + x*fx + fx)/f(x) + assert collect(e.expand(), fx) == fx*(x/f(x) + 1/f(x)) + 1/f(x) + + +def test_collect_func(): + f = ((x + a + 1)**3).expand() + + assert collect(f, x) == a**3 + 3*a**2 + 3*a + x**3 + x**2*(3*a + 3) + \ + x*(3*a**2 + 6*a + 3) + 1 + assert collect(f, x, factor) == x**3 + 3*x**2*(a + 1) + 3*x*(a + 1)**2 + \ + (a + 1)**3 + + assert collect(f, x, evaluate=False) == { + S.One: a**3 + 3*a**2 + 3*a + 1, + x: 3*a**2 + 6*a + 3, x**2: 3*a + 3, + x**3: 1 + } + + assert collect(f, x, factor, evaluate=False) == { + S.One: (a + 1)**3, x: 3*(a + 1)**2, + x**2: umul(S(3), a + 1), x**3: 1} + + +def test_collect_order(): + a, b, x, t = symbols('a,b,x,t') + + assert collect(t + t*x + t*x**2 + O(x**3), t) == t*(1 + x + x**2 + O(x**3)) + assert collect(t + t*x + x**2 + O(x**3), t) == \ + t*(1 + x + O(x**3)) + x**2 + O(x**3) + + f = a*x + b*x + c*x**2 + d*x**2 + O(x**3) + g = x*(a + b) + x**2*(c + d) + O(x**3) + + assert collect(f, x) == g + assert collect(f, x, distribute_order_term=False) == g + + f = sin(a + b).series(b, 0, 10) + + assert collect(f, [sin(a), cos(a)]) == \ + sin(a)*cos(b).series(b, 0, 10) + cos(a)*sin(b).series(b, 0, 10) + assert collect(f, [sin(a), cos(a)], distribute_order_term=False) == \ + sin(a)*cos(b).series(b, 0, 10).removeO() + \ + cos(a)*sin(b).series(b, 0, 10).removeO() + O(b**10) + + +def test_rcollect(): + assert rcollect((x**2*y + x*y + x + y)/(x + y), y) == \ + (x + y*(1 + x + x**2))/(x + y) + assert rcollect(sqrt(-((x + 1)*(y + 1))), z) == sqrt(-((x + 1)*(y + 1))) + + +def test_collect_D_0(): + D = Derivative + f = Function('f') + x, a, b = symbols('x,a,b') + fxx = D(f(x), x, x) + + assert collect(a*fxx + b*fxx, fxx) == (a + b)*fxx + + +def test_collect_Wild(): + """Collect with respect to functions with Wild argument""" + a, b, x, y = symbols('a b x y') + f = Function('f') + w1 = Wild('.1') + w2 = Wild('.2') + assert collect(f(x) + a*f(x), f(w1)) == (1 + a)*f(x) + assert collect(f(x, y) + a*f(x, y), f(w1)) == f(x, y) + a*f(x, y) + assert collect(f(x, y) + a*f(x, y), f(w1, w2)) == (1 + a)*f(x, y) + assert collect(f(x, y) + a*f(x, y), f(w1, w1)) == f(x, y) + a*f(x, y) + assert collect(f(x, x) + a*f(x, x), f(w1, w1)) == (1 + a)*f(x, x) + assert collect(a*(x + 1)**y + (x + 1)**y, w1**y) == (1 + a)*(x + 1)**y + assert collect(a*(x + 1)**y + (x + 1)**y, w1**b) == \ + a*(x + 1)**y + (x + 1)**y + assert collect(a*(x + 1)**y + (x + 1)**y, (x + 1)**w2) == \ + (1 + a)*(x + 1)**y + assert collect(a*(x + 1)**y + (x + 1)**y, w1**w2) == (1 + a)*(x + 1)**y + + +def test_collect_const(): + # coverage not provided by above tests + assert collect_const(2*sqrt(3) + 4*a*sqrt(5)) == \ + 2*(2*sqrt(5)*a + sqrt(3)) # let the primitive reabsorb + assert collect_const(2*sqrt(3) + 4*a*sqrt(5), sqrt(3)) == \ + 2*sqrt(3) + 4*a*sqrt(5) + assert collect_const(sqrt(2)*(1 + sqrt(2)) + sqrt(3) + x*sqrt(2)) == \ + sqrt(2)*(x + 1 + sqrt(2)) + sqrt(3) + + # issue 5290 + assert collect_const(2*x + 2*y + 1, 2) == \ + collect_const(2*x + 2*y + 1) == \ + Add(S.One, Mul(2, x + y, evaluate=False), evaluate=False) + assert collect_const(-y - z) == Mul(-1, y + z, evaluate=False) + assert collect_const(2*x - 2*y - 2*z, 2) == \ + Mul(2, x - y - z, evaluate=False) + assert collect_const(2*x - 2*y - 2*z, -2) == \ + _unevaluated_Add(2*x, Mul(-2, y + z, evaluate=False)) + + # this is why the content_primitive is used + eq = (sqrt(15 + 5*sqrt(2))*x + sqrt(3 + sqrt(2))*y)*2 + assert collect_sqrt(eq + 2) == \ + 2*sqrt(sqrt(2) + 3)*(sqrt(5)*x + y) + 2 + + # issue 16296 + assert collect_const(a + b + x/2 + y/2) == a + b + Mul(S.Half, x + y, evaluate=False) + + +def test_issue_13143(): + f = Function('f') + fx = f(x).diff(x) + e = f(x) + fx + f(x)*fx + # collect function before derivative + assert collect(e, Wild('w')) == f(x)*(fx + 1) + fx + e = f(x) + f(x)*fx + x*fx*f(x) + assert collect(e, fx) == (x*f(x) + f(x))*fx + f(x) + assert collect(e, f(x)) == (x*fx + fx + 1)*f(x) + e = f(x) + fx + f(x)*fx + assert collect(e, [f(x), fx]) == f(x)*(1 + fx) + fx + assert collect(e, [fx, f(x)]) == fx*(1 + f(x)) + f(x) + + +def test_issue_6097(): + assert collect(a*y**(2.0*x) + b*y**(2.0*x), y**x) == (a + b)*(y**x)**2.0 + assert collect(a*2**(2.0*x) + b*2**(2.0*x), 2**x) == (a + b)*(2**x)**2.0 + + +def test_fraction_expand(): + eq = (x + y)*y/x + assert eq.expand(frac=True) == fraction_expand(eq) == (x*y + y**2)/x + assert eq.expand() == y + y**2/x + + +def test_fraction(): + x, y, z = map(Symbol, 'xyz') + A = Symbol('A', commutative=False) + + assert fraction(S.Half) == (1, 2) + + assert fraction(x) == (x, 1) + assert fraction(1/x) == (1, x) + assert fraction(x/y) == (x, y) + assert fraction(x/2) == (x, 2) + + assert fraction(x*y/z) == (x*y, z) + assert fraction(x/(y*z)) == (x, y*z) + + assert fraction(1/y**2) == (1, y**2) + assert fraction(x/y**2) == (x, y**2) + + assert fraction((x**2 + 1)/y) == (x**2 + 1, y) + assert fraction(x*(y + 1)/y**7) == (x*(y + 1), y**7) + + assert fraction(exp(-x), exact=True) == (exp(-x), 1) + assert fraction((1/(x + y))/2, exact=True) == (1, Mul(2,(x + y), evaluate=False)) + + assert fraction(x*A/y) == (x*A, y) + assert fraction(x*A**-1/y) == (x*A**-1, y) + + n = symbols('n', negative=True) + assert fraction(exp(n)) == (1, exp(-n)) + assert fraction(exp(-n)) == (exp(-n), 1) + + p = symbols('p', positive=True) + assert fraction(exp(-p)*log(p), exact=True) == (exp(-p)*log(p), 1) + + m = Mul(1, 1, S.Half, evaluate=False) + assert fraction(m) == (1, 2) + assert fraction(m, exact=True) == (Mul(1, 1, evaluate=False), 2) + + m = Mul(1, 1, S.Half, S.Half, Pow(1, -1, evaluate=False), evaluate=False) + assert fraction(m) == (1, 4) + assert fraction(m, exact=True) == \ + (Mul(1, 1, evaluate=False), Mul(2, 2, 1, evaluate=False)) + + +def test_issue_5615(): + aA, Re, a, b, D = symbols('aA Re a b D') + e = ((D**3*a + b*aA**3)/Re).expand() + assert collect(e, [aA**3/Re, a]) == e + + +def test_issue_5933(): + from sympy.geometry.polygon import (Polygon, RegularPolygon) + from sympy.simplify.radsimp import denom + x = Polygon(*RegularPolygon((0, 0), 1, 5).vertices).centroid.x + assert abs(denom(x).n()) > 1e-12 + assert abs(denom(radsimp(x))) > 1e-12 # in case simplify didn't handle it + + +def test_issue_14608(): + a, b = symbols('a b', commutative=False) + x, y = symbols('x y') + raises(AttributeError, lambda: collect(a*b + b*a, a)) + assert collect(x*y + y*(x+1), a) == x*y + y*(x+1) + assert collect(x*y + y*(x+1) + a*b + b*a, y) == y*(2*x + 1) + a*b + b*a + + +def test_collect_abs(): + s = abs(x) + abs(y) + assert collect_abs(s) == s + assert unchanged(Mul, abs(x), abs(y)) + ans = Abs(x*y) + assert isinstance(ans, Abs) + assert collect_abs(abs(x)*abs(y)) == ans + assert collect_abs(1 + exp(abs(x)*abs(y))) == 1 + exp(ans) + + # See https://github.com/sympy/sympy/issues/12910 + p = Symbol('p', positive=True) + assert collect_abs(p/abs(1-p)).is_commutative is True + + +def test_issue_19149(): + eq = exp(3*x/4) + assert collect(eq, exp(x)) == eq + +def test_issue_19719(): + a, b = symbols('a, b') + expr = a**2 * (b + 1) + (7 + 1/b)/a + collected = collect(expr, (a**2, 1/a), evaluate=False) + # Would return {_Dummy_20**(-2): b + 1, 1/a: 7 + 1/b} without xreplace + assert collected == {a**2: b + 1, 1/a: 7 + 1/b} + + +def test_issue_21355(): + assert radsimp(1/(x + sqrt(x**2))) == 1/(x + sqrt(x**2)) + assert radsimp(1/(x - sqrt(x**2))) == 1/(x - sqrt(x**2)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_ratsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_ratsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..14e84fd2b227518baff1bda4e5b27ecc40a8bcdd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_ratsimp.py @@ -0,0 +1,78 @@ +from sympy.core.numbers import (Rational, pi) +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.special.error_functions import erf +from sympy.polys.domains import GF +from sympy.simplify.ratsimp import (ratsimp, ratsimpmodprime) + +from sympy.abc import x, y, z, t, a, b, c, d, e + + +def test_ratsimp(): + f, g = 1/x + 1/y, (x + y)/(x*y) + + assert f != g and ratsimp(f) == g + + f, g = 1/(1 + 1/x), 1 - 1/(x + 1) + + assert f != g and ratsimp(f) == g + + f, g = x/(x + y) + y/(x + y), 1 + + assert f != g and ratsimp(f) == g + + f, g = -x - y - y**2/(x + y) + x**2/(x + y), -2*y + + assert f != g and ratsimp(f) == g + + f = (a*c*x*y + a*c*z - b*d*x*y - b*d*z - b*t*x*y - b*t*x - b*t*z + + e*x)/(x*y + z) + G = [a*c - b*d - b*t + (-b*t*x + e*x)/(x*y + z), + a*c - b*d - b*t - ( b*t*x - e*x)/(x*y + z)] + + assert f != g and ratsimp(f) in G + + A = sqrt(pi) + + B = log(erf(x) - 1) + C = log(erf(x) + 1) + + D = 8 - 8*erf(x) + + f = A*B/D - A*C/D + A*C*erf(x)/D - A*B*erf(x)/D + 2*A/D + + assert ratsimp(f) == A*B/8 - A*C/8 - A/(4*erf(x) - 4) + + +def test_ratsimpmodprime(): + a = y**5 + x + y + b = x - y + F = [x*y**5 - x - y] + assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ + (-x**2 - x*y - x - y) / (-x**2 + x*y) + + a = x + y**2 - 2 + b = x + y**2 - y - 1 + F = [x*y - 1] + assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ + (1 + y - x)/(y - x) + + a = 5*x**3 + 21*x**2 + 4*x*y + 23*x + 12*y + 15 + b = 7*x**3 - y*x**2 + 31*x**2 + 2*x*y + 15*y + 37*x + 21 + F = [x**2 + y**2 - 1] + assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ + (1 + 5*y - 5*x)/(8*y - 6*x) + + a = x*y - x - 2*y + 4 + b = x + y**2 - 2*y + F = [x - 2, y - 3] + assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ + Rational(2, 5) + + # Test a bug where denominators would be dropped + assert ratsimpmodprime(x, [y - 2*x], order='lex') == \ + y/2 + + a = (x**5 + 2*x**4 + 2*x**3 + 2*x**2 + x + 2/x + x**(-2)) + assert ratsimpmodprime(a, [x + 1], domain=GF(2)) == 1 + assert ratsimpmodprime(a, [x + 1], domain=GF(3)) == -1 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_rewrite.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_rewrite.py new file mode 100644 index 0000000000000000000000000000000000000000..56d2fb7a85bd959bd4accc2f36127429efbdbe70 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_rewrite.py @@ -0,0 +1,31 @@ +from sympy.core.numbers import I +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.trigonometric import (cos, cot, sin) +from sympy.testing.pytest import _both_exp_pow + +x, y, z, n = symbols('x,y,z,n') + + +@_both_exp_pow +def test_has(): + assert cot(x).has(x) + assert cot(x).has(cot) + assert not cot(x).has(sin) + assert sin(x).has(x) + assert sin(x).has(sin) + assert not sin(x).has(cot) + assert exp(x).has(exp) + + +@_both_exp_pow +def test_sin_exp_rewrite(): + assert sin(x).rewrite(sin, exp) == -I/2*(exp(I*x) - exp(-I*x)) + assert sin(x).rewrite(sin, exp).rewrite(exp, sin) == sin(x) + assert cos(x).rewrite(cos, exp).rewrite(exp, cos) == cos(x) + assert (sin(5*y) - sin( + 2*x)).rewrite(sin, exp).rewrite(exp, sin) == sin(5*y) - sin(2*x) + assert sin(x + y).rewrite(sin, exp).rewrite(exp, sin) == sin(x + y) + assert cos(x + y).rewrite(cos, exp).rewrite(exp, cos) == cos(x + y) + # This next test currently passes... not clear whether it should or not? + assert cos(x).rewrite(cos, exp).rewrite(exp, sin) == cos(x) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_simplify.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_simplify.py new file mode 100644 index 0000000000000000000000000000000000000000..a5bf469f68adf5c5dfbdf7559414681e2fb28ba7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_simplify.py @@ -0,0 +1,1093 @@ +from sympy.concrete.summations import Sum +from sympy.core.add import Add +from sympy.core.basic import Basic +from sympy.core.expr import unchanged +from sympy.core.function import (count_ops, diff, expand, expand_multinomial, Function, Derivative) +from sympy.core.mul import Mul, _keep_coeff +from sympy.core import GoldenRatio +from sympy.core.numbers import (E, Float, I, oo, pi, Rational, zoo) +from sympy.core.relational import (Eq, Lt, Gt, Ge, Le) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.core.sympify import sympify +from sympy.functions.combinatorial.factorials import (binomial, factorial) +from sympy.functions.elementary.complexes import (Abs, sign) +from sympy.functions.elementary.exponential import (exp, exp_polar, log) +from sympy.functions.elementary.hyperbolic import (cosh, csch, sinh) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan) +from sympy.functions.special.error_functions import erf +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.hyper import hyper +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.geometry.polygon import rad +from sympy.integrals.integrals import (Integral, integrate) +from sympy.logic.boolalg import (And, Or) +from sympy.matrices.dense import (Matrix, eye) +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.polys.polytools import (factor, Poly) +from sympy.simplify.simplify import (besselsimp, hypersimp, inversecombine, logcombine, nsimplify, nthroot, posify, separatevars, signsimp, simplify) +from sympy.solvers.solvers import solve + +from sympy.testing.pytest import XFAIL, slow, _both_exp_pow +from sympy.abc import x, y, z, t, a, b, c, d, e, f, g, h, i, n + + +def test_issue_7263(): + assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \ + 673.447451402970) < 1e-12 + + +def test_factorial_simplify(): + # There are more tests in test_factorials.py. + x = Symbol('x') + assert simplify(factorial(x)/x) == gamma(x) + assert simplify(factorial(factorial(x))) == factorial(factorial(x)) + + +def test_simplify_expr(): + x, y, z, k, n, m, w, s, A = symbols('x,y,z,k,n,m,w,s,A') + f = Function('f') + + assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I]) + + e = 1/x + 1/y + assert e != (x + y)/(x*y) + assert simplify(e) == (x + y)/(x*y) + + e = A**2*s**4/(4*pi*k*m**3) + assert simplify(e) == e + + e = (4 + 4*x - 2*(2 + 2*x))/(2 + 2*x) + assert simplify(e) == 0 + + e = (-4*x*y**2 - 2*y**3 - 2*x**2*y)/(x + y)**2 + assert simplify(e) == -2*y + + e = -x - y - (x + y)**(-1)*y**2 + (x + y)**(-1)*x**2 + assert simplify(e) == -2*y + + e = (x + x*y)/x + assert simplify(e) == 1 + y + + e = (f(x) + y*f(x))/f(x) + assert simplify(e) == 1 + y + + e = (2 * (1/n - cos(n * pi)/n))/pi + assert simplify(e) == (-cos(pi*n) + 1)/(pi*n)*2 + + e = integrate(1/(x**3 + 1), x).diff(x) + assert simplify(e) == 1/(x**3 + 1) + + e = integrate(x/(x**2 + 3*x + 1), x).diff(x) + assert simplify(e) == x/(x**2 + 3*x + 1) + + f = Symbol('f') + A = Matrix([[2*k - m*w**2, -k], [-k, k - m*w**2]]).inv() + assert simplify((A*Matrix([0, f]))[1] - + (-f*(2*k - m*w**2)/(k**2 - (k - m*w**2)*(2*k - m*w**2)))) == 0 + + f = -x + y/(z + t) + z*x/(z + t) + z*a/(z + t) + t*x/(z + t) + assert simplify(f) == (y + a*z)/(z + t) + + # issue 10347 + expr = -x*(y**2 - 1)*(2*y**2*(x**2 - 1)/(a*(x**2 - y**2)**2) + (x**2 - 1) + /(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + + y**2 - 1)*sin(z)/(a*(x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)* + (y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(x**2 - 1) + sqrt( + (-x**2 + 1)*(y**2 - 1))*(x*(-x*y**2 + x)/sqrt(-x**2*y**2 + x**2 + y**2 - + 1) + sqrt(-x**2*y**2 + x**2 + y**2 - 1))*sin(z))/(a*sqrt((-x**2 + 1)*( + y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a* + (x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* + (x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* + (x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2 + *y**2 + x**2 + y**2 - 1)*cos(z)/(x**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - + 1))*(-x*y**2 + x)*cos(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt((-x**2 + + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z))/(a*sqrt((-x**2 + + 1)*(y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos( + z)/(a*(x**2 - y**2)) - y*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y*sqrt(-x**2* + y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt( + -x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) + (x*y*sqrt(( + -x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(y**2 - + 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*sin(z)/sqrt(-x**2*y**2 + + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sin( + z)/(a*(x**2 - y**2)) + y*(x**2 - 1)*(-2*x*y*(x**2 - 1)/(a*(x**2 - y**2) + **2) + 2*x*y/(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + y*(x**2 - 1)*(y**2 - + 1)*(-x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2)*(y**2 + - 1)) + 2*x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2) + **2) + (x*y*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - + 1)*cos(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*cos( + z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1) + )*(x**2 - y**2)))*cos(z)/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2) + ) - x*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin( + z)**2/(a**2*(x**2 - 1)*(x**2 - y**2)*(y**2 - 1)) - x*sqrt((-x**2 + 1)*( + y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)**2/(a**2*(x**2 - 1)*( + x**2 - y**2)*(y**2 - 1)) + assert simplify(expr) == 2*x/(a**2*(x**2 - y**2)) + + #issue 17631 + assert simplify('((-1/2)*Boole(True)*Boole(False)-1)*Boole(True)') == \ + Mul(sympify('(2 + Boole(True)*Boole(False))'), sympify('-Boole(True)/2')) + + A, B = symbols('A,B', commutative=False) + + assert simplify(A*B - B*A) == A*B - B*A + assert simplify(A/(1 + y/x)) == x*A/(x + y) + assert simplify(A*(1/x + 1/y)) == A/x + A/y #(x + y)*A/(x*y) + + assert simplify(log(2) + log(3)) == log(6) + assert simplify(log(2*x) - log(2)) == log(x) + + assert simplify(hyper([], [], x)) == exp(x) + + +def test_issue_3557(): + f_1 = x*a + y*b + z*c - 1 + f_2 = x*d + y*e + z*f - 1 + f_3 = x*g + y*h + z*i - 1 + + solutions = solve([f_1, f_2, f_3], x, y, z, simplify=False) + + assert simplify(solutions[y]) == \ + (a*i + c*d + f*g - a*f - c*g - d*i)/ \ + (a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g) + + +def test_simplify_other(): + assert simplify(sin(x)**2 + cos(x)**2) == 1 + assert simplify(gamma(x + 1)/gamma(x)) == x + assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x + assert simplify( + Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(x, 1) + nc = symbols('nc', commutative=False) + assert simplify(x + x*nc) == x*(1 + nc) + # issue 6123 + # f = exp(-I*(k*sqrt(t) + x/(2*sqrt(t)))**2) + # ans = integrate(f, (k, -oo, oo), conds='none') + ans = I*(-pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))*erf(x*exp(I*pi*Rational(-3, 4))/ + (2*sqrt(t)))/(2*sqrt(t)) + pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))/ + (2*sqrt(t)))*exp(-I*x**2/(4*t))/(sqrt(pi)*x) - I*sqrt(pi) * \ + (-erf(x*exp(I*pi/4)/(2*sqrt(t))) + 1)*exp(I*pi/4)/(2*sqrt(t)) + assert simplify(ans) == -(-1)**Rational(3, 4)*sqrt(pi)/sqrt(t) + # issue 6370 + assert simplify(2**(2 + x)/4) == 2**x + + +@_both_exp_pow +def test_simplify_complex(): + cosAsExp = cos(x)._eval_rewrite_as_exp(x) + tanAsExp = tan(x)._eval_rewrite_as_exp(x) + assert simplify(cosAsExp*tanAsExp) == sin(x) # issue 4341 + + # issue 10124 + assert simplify(exp(Matrix([[0, -1], [1, 0]]))) == Matrix([[cos(1), + -sin(1)], [sin(1), cos(1)]]) + + +def test_simplify_ratio(): + # roots of x**3-3*x+5 + roots = ['(1/2 - sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3) + 1/((1/2 - ' + 'sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3))', + '1/((1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)) + ' + '(1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)', + '-(sqrt(21)/2 + 5/2)**(1/3) - 1/(sqrt(21)/2 + 5/2)**(1/3)'] + + for r in roots: + r = S(r) + assert count_ops(simplify(r, ratio=1)) <= count_ops(r) + # If ratio=oo, simplify() is always applied: + assert simplify(r, ratio=oo) is not r + + +def test_simplify_measure(): + measure1 = lambda expr: len(str(expr)) + measure2 = lambda expr: -count_ops(expr) + # Return the most complicated result + expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) + assert measure1(simplify(expr, measure=measure1)) <= measure1(expr) + assert measure2(simplify(expr, measure=measure2)) <= measure2(expr) + + expr2 = Eq(sin(x)**2 + cos(x)**2, 1) + assert measure1(simplify(expr2, measure=measure1)) <= measure1(expr2) + assert measure2(simplify(expr2, measure=measure2)) <= measure2(expr2) + + +def test_simplify_rational(): + expr = 2**x*2.**y + assert simplify(expr, rational = True) == 2**(x+y) + assert simplify(expr, rational = None) == 2.0**(x+y) + assert simplify(expr, rational = False) == expr + assert simplify('0.9 - 0.8 - 0.1', rational = True) == 0 + + +def test_simplify_issue_1308(): + assert simplify(exp(Rational(-1, 2)) + exp(Rational(-3, 2))) == \ + (1 + E)*exp(Rational(-3, 2)) + + +def test_issue_5652(): + assert simplify(E + exp(-E)) == exp(-E) + E + n = symbols('n', commutative=False) + assert simplify(n + n**(-n)) == n + n**(-n) + +def test_issue_27380(): + assert simplify(1.0**(x+1)/1.0**x) == 1.0 + +def test_simplify_fail1(): + x = Symbol('x') + y = Symbol('y') + e = (x + y)**2/(-4*x*y**2 - 2*y**3 - 2*x**2*y) + assert simplify(e) == 1 / (-2*y) + + +def test_nthroot(): + assert nthroot(90 + 34*sqrt(7), 3) == sqrt(7) + 3 + q = 1 + sqrt(2) - 2*sqrt(3) + sqrt(6) + sqrt(7) + assert nthroot(expand_multinomial(q**3), 3) == q + assert nthroot(41 + 29*sqrt(2), 5) == 1 + sqrt(2) + assert nthroot(-41 - 29*sqrt(2), 5) == -1 - sqrt(2) + expr = 1320*sqrt(10) + 4216 + 2576*sqrt(6) + 1640*sqrt(15) + assert nthroot(expr, 5) == 1 + sqrt(6) + sqrt(15) + q = 1 + sqrt(2) + sqrt(3) + sqrt(5) + assert expand_multinomial(nthroot(expand_multinomial(q**5), 5)) == q + q = 1 + sqrt(2) + 7*sqrt(6) + 2*sqrt(10) + assert nthroot(expand_multinomial(q**5), 5, 8) == q + q = 1 + sqrt(2) - 2*sqrt(3) + 1171*sqrt(6) + assert nthroot(expand_multinomial(q**3), 3) == q + assert nthroot(expand_multinomial(q**6), 6) == q + + +def test_nthroot1(): + q = 1 + sqrt(2) + sqrt(3) + S.One/10**20 + p = expand_multinomial(q**5) + assert nthroot(p, 5) == q + q = 1 + sqrt(2) + sqrt(3) + S.One/10**30 + p = expand_multinomial(q**5) + assert nthroot(p, 5) == q + + +@_both_exp_pow +def test_separatevars(): + x, y, z, n = symbols('x,y,z,n') + assert separatevars(2*n*x*z + 2*x*y*z) == 2*x*z*(n + y) + assert separatevars(x*z + x*y*z) == x*z*(1 + y) + assert separatevars(pi*x*z + pi*x*y*z) == pi*x*z*(1 + y) + assert separatevars(x*y**2*sin(x) + x*sin(x)*sin(y)) == \ + x*(sin(y) + y**2)*sin(x) + assert separatevars(x*exp(x + y) + x*exp(x)) == x*(1 + exp(y))*exp(x) + assert separatevars((x*(y + 1))**z).is_Pow # != x**z*(1 + y)**z + assert separatevars(1 + x + y + x*y) == (x + 1)*(y + 1) + assert separatevars(y/pi*exp(-(z - x)/cos(n))) == \ + y*exp(x/cos(n))*exp(-z/cos(n))/pi + assert separatevars((x + y)*(x - y) + y**2 + 2*x + 1) == (x + 1)**2 + # issue 4858 + p = Symbol('p', positive=True) + assert separatevars(sqrt(p**2 + x*p**2)) == p*sqrt(1 + x) + assert separatevars(sqrt(y*(p**2 + x*p**2))) == p*sqrt(y*(1 + x)) + assert separatevars(sqrt(y*(p**2 + x*p**2)), force=True) == \ + p*sqrt(y)*sqrt(1 + x) + # issue 4865 + assert separatevars(sqrt(x*y)).is_Pow + assert separatevars(sqrt(x*y), force=True) == sqrt(x)*sqrt(y) + # issue 4957 + # any type sequence for symbols is fine + assert separatevars(((2*x + 2)*y), dict=True, symbols=()) == \ + {'coeff': 1, x: 2*x + 2, y: y} + # separable + assert separatevars(((2*x + 2)*y), dict=True, symbols=[x]) == \ + {'coeff': y, x: 2*x + 2} + assert separatevars(((2*x + 2)*y), dict=True, symbols=[]) == \ + {'coeff': 1, x: 2*x + 2, y: y} + assert separatevars(((2*x + 2)*y), dict=True) == \ + {'coeff': 1, x: 2*x + 2, y: y} + assert separatevars(((2*x + 2)*y), dict=True, symbols=None) == \ + {'coeff': y*(2*x + 2)} + # not separable + assert separatevars(3, dict=True) is None + assert separatevars(2*x + y, dict=True, symbols=()) is None + assert separatevars(2*x + y, dict=True) is None + assert separatevars(2*x + y, dict=True, symbols=None) == {'coeff': 2*x + y} + # issue 4808 + n, m = symbols('n,m', commutative=False) + assert separatevars(m + n*m) == (1 + n)*m + assert separatevars(x + x*n) == x*(1 + n) + # issue 4910 + f = Function('f') + assert separatevars(f(x) + x*f(x)) == f(x) + x*f(x) + # a noncommutable object present + eq = x*(1 + hyper((), (), y*z)) + assert separatevars(eq) == eq + + s = separatevars(abs(x*y)) + assert s == abs(x)*abs(y) and s.is_Mul + z = cos(1)**2 + sin(1)**2 - 1 + a = abs(x*z) + s = separatevars(a) + assert not a.is_Mul and s.is_Mul and s == abs(x)*abs(z) + s = separatevars(abs(x*y*z)) + assert s == abs(x)*abs(y)*abs(z) + + # abs(x+y)/abs(z) would be better but we test this here to + # see that it doesn't raise + assert separatevars(abs((x+y)/z)) == abs((x+y)/z) + + +def test_separatevars_advanced_factor(): + x, y, z = symbols('x,y,z') + assert separatevars(1 + log(x)*log(y) + log(x) + log(y)) == \ + (log(x) + 1)*(log(y) + 1) + assert separatevars(1 + x - log(z) - x*log(z) - exp(y)*log(z) - + x*exp(y)*log(z) + x*exp(y) + exp(y)) == \ + -((x + 1)*(log(z) - 1)*(exp(y) + 1)) + x, y = symbols('x,y', positive=True) + assert separatevars(1 + log(x**log(y)) + log(x*y)) == \ + (log(x) + 1)*(log(y) + 1) + + +def test_hypersimp(): + n, k = symbols('n,k', integer=True) + + assert hypersimp(factorial(k), k) == k + 1 + assert hypersimp(factorial(k**2), k) is None + + assert hypersimp(1/factorial(k), k) == 1/(k + 1) + + assert hypersimp(2**k/factorial(k)**2, k) == 2/(k + 1)**2 + + assert hypersimp(binomial(n, k), k) == (n - k)/(k + 1) + assert hypersimp(binomial(n + 1, k), k) == (n - k + 1)/(k + 1) + + term = (4*k + 1)*factorial(k)/factorial(2*k + 1) + assert hypersimp(term, k) == S.Half*((4*k + 5)/(3 + 14*k + 8*k**2)) + + term = 1/((2*k - 1)*factorial(2*k + 1)) + assert hypersimp(term, k) == (k - S.Half)/((k + 1)*(2*k + 1)*(2*k + 3)) + + term = binomial(n, k)*(-1)**k/factorial(k) + assert hypersimp(term, k) == (k - n)/(k + 1)**2 + + +def test_nsimplify(): + x = Symbol("x") + assert nsimplify(0) == 0 + assert nsimplify(-1) == -1 + assert nsimplify(1) == 1 + assert nsimplify(1 + x) == 1 + x + assert nsimplify(2.7) == Rational(27, 10) + assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2 + assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2 + assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2 + assert nsimplify(exp(pi*I*Rational(5, 3), evaluate=False)) == \ + sympify('1/2 - sqrt(3)*I/2') + assert nsimplify(sin(pi*Rational(3, 5), evaluate=False)) == \ + sympify('sqrt(sqrt(5)/8 + 5/8)') + assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \ + sqrt(pi) + sqrt(pi)/2*I + assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17') + assert nsimplify(pi, tolerance=0.01) == Rational(22, 7) + assert nsimplify(pi, tolerance=0.001) == Rational(355, 113) + assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3) + assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504) + assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \ + 2**Rational(1, 3) + assert nsimplify(x + .5, rational=True) == S.Half + x + assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x + assert nsimplify(log(3).n(), rational=True) == \ + sympify('109861228866811/100000000000000') + assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8 + assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \ + -pi/4 - log(2) + Rational(7, 4) + assert nsimplify(x/7.0) == x/7 + assert nsimplify(pi/1e2) == pi/100 + assert nsimplify(pi/1e2, rational=False) == pi/100.0 + assert nsimplify(pi/1e-7) == 10000000*pi + assert not nsimplify( + factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float) + e = x**0.0 + assert e.is_Pow and nsimplify(x**0.0) == 1 + assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3) + assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3) + assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3) + assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3) + assert nsimplify(33, tolerance=10, rational=True) == Rational(33) + assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30) + assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40) + assert nsimplify(-203.1) == Rational(-2031, 10) + assert nsimplify(.2, tolerance=0) == Rational(1, 5) + assert nsimplify(-.2, tolerance=0) == Rational(-1, 5) + assert nsimplify(.2222, tolerance=0) == Rational(1111, 5000) + assert nsimplify(-.2222, tolerance=0) == Rational(-1111, 5000) + # issue 7211, PR 4112 + assert nsimplify(S(2e-8)) == Rational(1, 50000000) + # issue 7322 direct test + assert nsimplify(1e-42, rational=True) != 0 + # issue 10336 + inf = Float('inf') + infs = (-oo, oo, inf, -inf) + for zi in infs: + ans = sign(zi)*oo + assert nsimplify(zi) == ans + assert nsimplify(zi + x) == x + ans + + assert nsimplify(0.33333333, rational=True, rational_conversion='exact') == Rational(0.33333333) + + # Make sure nsimplify on expressions uses full precision + assert nsimplify(pi.evalf(100)*x, rational_conversion='exact').evalf(100) == pi.evalf(100)*x + + +def test_issue_9448(): + tmp = sympify("1/(1 - (-1)**(2/3) - (-1)**(1/3)) + 1/(1 + (-1)**(2/3) + (-1)**(1/3))") + assert nsimplify(tmp) == S.Half + + +def test_extract_minus_sign(): + x = Symbol("x") + y = Symbol("y") + a = Symbol("a") + b = Symbol("b") + assert simplify(-x/-y) == x/y + assert simplify(-x/y) == -x/y + assert simplify(x/y) == x/y + assert simplify(x/-y) == -x/y + assert simplify(-x/0) == zoo*x + assert simplify(Rational(-5, 0)) is zoo + assert simplify(-a*x/(-y - b)) == a*x/(b + y) + + +def test_diff(): + x = Symbol("x") + y = Symbol("y") + f = Function("f") + g = Function("g") + assert simplify(g(x).diff(x)*f(x).diff(x) - f(x).diff(x)*g(x).diff(x)) == 0 + assert simplify(2*f(x)*f(x).diff(x) - diff(f(x)**2, x)) == 0 + assert simplify(diff(1/f(x), x) + f(x).diff(x)/f(x)**2) == 0 + assert simplify(f(x).diff(x, y) - f(x).diff(y, x)) == 0 + + +def test_logcombine_1(): + x, y = symbols("x,y") + a = Symbol("a") + z, w = symbols("z,w", positive=True) + b = Symbol("b", real=True) + assert logcombine(log(x) + 2*log(y)) == log(x) + 2*log(y) + assert logcombine(log(x) + 2*log(y), force=True) == log(x*y**2) + assert logcombine(a*log(w) + log(z)) == a*log(w) + log(z) + assert logcombine(b*log(z) + b*log(x)) == log(z**b) + b*log(x) + assert logcombine(b*log(z) - log(w)) == log(z**b/w) + assert logcombine(log(x)*log(z)) == log(x)*log(z) + assert logcombine(log(w)*log(x)) == log(w)*log(x) + assert logcombine(cos(-2*log(z) + b*log(w))) in [cos(log(w**b/z**2)), + cos(log(z**2/w**b))] + assert logcombine(log(log(x) - log(y)) - log(z), force=True) == \ + log(log(x/y)/z) + assert logcombine((2 + I)*log(x), force=True) == (2 + I)*log(x) + assert logcombine((x**2 + log(x) - log(y))/(x*y), force=True) == \ + (x**2 + log(x/y))/(x*y) + # the following could also give log(z*x**log(y**2)), what we + # are testing is that a canonical result is obtained + assert logcombine(log(x)*2*log(y) + log(z), force=True) == \ + log(z*y**log(x**2)) + assert logcombine((x*y + sqrt(x**4 + y**4) + log(x) - log(y))/(pi*x**Rational(2, 3)* + sqrt(y)**3), force=True) == ( + x*y + sqrt(x**4 + y**4) + log(x/y))/(pi*x**Rational(2, 3)*y**Rational(3, 2)) + assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \ + acos(-log(x/y))*gamma(-log(x/y)) + + assert logcombine(2*log(z)*log(w)*log(x) + log(z) + log(w)) == \ + log(z**log(w**2))*log(x) + log(w*z) + assert logcombine(3*log(w) + 3*log(z)) == log(w**3*z**3) + assert logcombine(x*(y + 1) + log(2) + log(3)) == x*(y + 1) + log(6) + assert logcombine((x + y)*log(w) + (-x - y)*log(3)) == (x + y)*log(w/3) + # a single unknown can combine + assert logcombine(log(x) + log(2)) == log(2*x) + eq = log(abs(x)) + log(abs(y)) + assert logcombine(eq) == eq + reps = {x: 0, y: 0} + assert log(abs(x)*abs(y)).subs(reps) != eq.subs(reps) + + +def test_logcombine_complex_coeff(): + i = Integral((sin(x**2) + cos(x**3))/x, x) + assert logcombine(i, force=True) == i + assert logcombine(i + 2*log(x), force=True) == \ + i + log(x**2) + + +def test_issue_5950(): + x, y = symbols("x,y", positive=True) + assert logcombine(log(3) - log(2)) == log(Rational(3,2), evaluate=False) + assert logcombine(log(x) - log(y)) == log(x/y) + assert logcombine(log(Rational(3,2), evaluate=False) - log(2)) == \ + log(Rational(3,4), evaluate=False) + + +def test_posify(): + x = symbols('x') + + assert str(posify( + x + + Symbol('p', positive=True) + + Symbol('n', negative=True))) == '(_x + n + p, {_x: x})' + + eq, rep = posify(1/x) + assert log(eq).expand().subs(rep) == -log(x) + assert str(posify([x, 1 + x])) == '([_x, _x + 1], {_x: x})' + + p = symbols('p', positive=True) + n = symbols('n', negative=True) + orig = [x, n, p] + modified, reps = posify(orig) + assert str(modified) == '[_x, n, p]' + assert [w.subs(reps) for w in modified] == orig + + assert str(Integral(posify(1/x + y)[0], (y, 1, 3)).expand()) == \ + 'Integral(1/_x, (y, 1, 3)) + Integral(_y, (y, 1, 3))' + assert str(Sum(posify(1/x**n)[0], (n,1,3)).expand()) == \ + 'Sum(_x**(-n), (n, 1, 3))' + + A = Matrix([[1, 2, 3], [4, 5, 6 * Abs(x)]]) + Ap, rep = posify(A) + assert Ap == A.subs(*reversed(rep.popitem())) + + # issue 16438 + k = Symbol('k', finite=True) + eq, rep = posify(k) + assert eq.assumptions0 == {'positive': True, 'zero': False, 'imaginary': False, + 'nonpositive': False, 'commutative': True, 'hermitian': True, 'real': True, 'nonzero': True, + 'nonnegative': True, 'negative': False, 'complex': True, 'finite': True, + 'infinite': False, 'extended_real':True, 'extended_negative': False, + 'extended_nonnegative': True, 'extended_nonpositive': False, + 'extended_nonzero': True, 'extended_positive': True} + + +def test_issue_4194(): + # simplify should call cancel + f = Function('f') + assert simplify((4*x + 6*f(y))/(2*x + 3*f(y))) == 2 + + +@XFAIL +def test_simplify_float_vs_integer(): + # Test for issue 4473: + # https://github.com/sympy/sympy/issues/4473 + assert simplify(x**2.0 - x**2) == 0 + assert simplify(x**2 - x**2.0) == 0 + + +def test_as_content_primitive(): + assert (x/2 + y).as_content_primitive() == (S.Half, x + 2*y) + assert (x/2 + y).as_content_primitive(clear=False) == (S.One, x/2 + y) + assert (y*(x/2 + y)).as_content_primitive() == (S.Half, y*(x + 2*y)) + assert (y*(x/2 + y)).as_content_primitive(clear=False) == (S.One, y*(x/2 + y)) + + # although the _as_content_primitive methods do not alter the underlying structure, + # the as_content_primitive function will touch up the expression and join + # bases that would otherwise have not been joined. + assert (x*(2 + 2*x)*(3*x + 3)**2).as_content_primitive() == \ + (18, x*(x + 1)**3) + assert (2 + 2*x + 2*y*(3 + 3*y)).as_content_primitive() == \ + (2, x + 3*y*(y + 1) + 1) + assert ((2 + 6*x)**2).as_content_primitive() == \ + (4, (3*x + 1)**2) + assert ((2 + 6*x)**(2*y)).as_content_primitive() == \ + (1, (_keep_coeff(S(2), (3*x + 1)))**(2*y)) + assert (5 + 10*x + 2*y*(3 + 3*y)).as_content_primitive() == \ + (1, 10*x + 6*y*(y + 1) + 5) + assert (5*(x*(1 + y)) + 2*x*(3 + 3*y)).as_content_primitive() == \ + (11, x*(y + 1)) + assert ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() == \ + (121, x**2*(y + 1)**2) + assert (y**2).as_content_primitive() == \ + (1, y**2) + assert (S.Infinity).as_content_primitive() == (1, oo) + eq = x**(2 + y) + assert (eq).as_content_primitive() == (1, eq) + assert (S.Half**(2 + x)).as_content_primitive() == (Rational(1, 4), 2**-x) + assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ + (Rational(1, 4), (Rational(-1, 2))**x) + assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ + (Rational(1, 4), Rational(-1, 2)**x) + assert (4**((1 + y)/2)).as_content_primitive() == (2, 4**(y/2)) + assert (3**((1 + y)/2)).as_content_primitive() == \ + (1, 3**(Mul(S.Half, 1 + y, evaluate=False))) + assert (5**Rational(3, 4)).as_content_primitive() == (1, 5**Rational(3, 4)) + assert (5**Rational(7, 4)).as_content_primitive() == (5, 5**Rational(3, 4)) + assert Add(z*Rational(5, 7), 0.5*x, y*Rational(3, 2), evaluate=False).as_content_primitive() == \ + (Rational(1, 14), 7.0*x + 21*y + 10*z) + assert (2**Rational(3, 4) + 2**Rational(1, 4)*sqrt(3)).as_content_primitive(radical=True) == \ + (1, 2**Rational(1, 4)*(sqrt(2) + sqrt(3))) + + +def test_signsimp(): + e = x*(-x + 1) + x*(x - 1) + assert signsimp(Eq(e, 0)) is S.true + assert Abs(x - 1) == Abs(1 - x) + assert signsimp(y - x) == y - x + assert signsimp(y - x, evaluate=False) == Mul(-1, x - y, evaluate=False) + + +def test_besselsimp(): + from sympy.functions.special.bessel import (besseli, besselj, bessely) + from sympy.integrals.transforms import cosine_transform + assert besselsimp(exp(-I*pi*y/2)*besseli(y, z*exp_polar(I*pi/2))) == \ + besselj(y, z) + assert besselsimp(exp(-I*pi*a/2)*besseli(a, 2*sqrt(x)*exp_polar(I*pi/2))) == \ + besselj(a, 2*sqrt(x)) + assert besselsimp(sqrt(2)*sqrt(pi)*x**Rational(1, 4)*exp(I*pi/4)*exp(-I*pi*a/2) * + besseli(Rational(-1, 2), sqrt(x)*exp_polar(I*pi/2)) * + besseli(a, sqrt(x)*exp_polar(I*pi/2))/2) == \ + besselj(a, sqrt(x)) * cos(sqrt(x)) + assert besselsimp(besseli(Rational(-1, 2), z)) == \ + sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) + assert besselsimp(besseli(a, z*exp_polar(-I*pi/2))) == \ + exp(-I*pi*a/2)*besselj(a, z) + assert cosine_transform(1/t*sin(a/t), t, y) == \ + sqrt(2)*sqrt(pi)*besselj(0, 2*sqrt(a)*sqrt(y))/2 + + assert besselsimp(x**2*(a*(-2*besselj(5*I, x) + besselj(-2 + 5*I, x) + + besselj(2 + 5*I, x)) + b*(-2*bessely(5*I, x) + bessely(-2 + 5*I, x) + + bessely(2 + 5*I, x)))/4 + x*(a*(besselj(-1 + 5*I, x)/2 - besselj(1 + 5*I, x)/2) + + b*(bessely(-1 + 5*I, x)/2 - bessely(1 + 5*I, x)/2)) + (x**2 + 25)*(a*besselj(5*I, x) + + b*bessely(5*I, x))) == 0 + + assert besselsimp(81*x**2*(a*(besselj(Rational(-5, 3), 9*x) - 2*besselj(Rational(1, 3), 9*x) + besselj(Rational(7, 3), 9*x)) + + b*(bessely(Rational(-5, 3), 9*x) - 2*bessely(Rational(1, 3), 9*x) + bessely(Rational(7, 3), 9*x)))/4 + x*(a*(9*besselj(Rational(-2, 3), 9*x)/2 + - 9*besselj(Rational(4, 3), 9*x)/2) + b*(9*bessely(Rational(-2, 3), 9*x)/2 - 9*bessely(Rational(4, 3), 9*x)/2)) + + (81*x**2 - Rational(1, 9))*(a*besselj(Rational(1, 3), 9*x) + b*bessely(Rational(1, 3), 9*x))) == 0 + + assert besselsimp(besselj(a-1,x) + besselj(a+1, x) - 2*a*besselj(a, x)/x) == 0 + + assert besselsimp(besselj(a-1,x) + besselj(a+1, x) + besselj(a, x)) == (2*a + x)*besselj(a, x)/x + + assert besselsimp(x**2* besselj(a,x) + x**3*besselj(a+1, x) + besselj(a+2, x)) == \ + 2*a*x*besselj(a + 1, x) + x**3*besselj(a + 1, x) - x**2*besselj(a + 2, x) + 2*x*besselj(a + 1, x) + besselj(a + 2, x) + +def test_Piecewise(): + e1 = x*(x + y) - y*(x + y) + e2 = sin(x)**2 + cos(x)**2 + e3 = expand((x + y)*y/x) + s1 = simplify(e1) + s2 = simplify(e2) + s3 = simplify(e3) + assert simplify(Piecewise((e1, x < e2), (e3, True))) == \ + Piecewise((s1, x < s2), (s3, True)) + + +def test_polymorphism(): + class A(Basic): + def _eval_simplify(x, **kwargs): + return S.One + + a = A(S(5), S(2)) + assert simplify(a) == 1 + + +def test_issue_from_PR1599(): + n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True) + assert simplify(I*sqrt(n1)) == -sqrt(-n1) + + +def test_issue_6811(): + eq = (x + 2*y)*(2*x + 2) + assert simplify(eq) == (x + 1)*(x + 2*y)*2 + # reject the 2-arg Mul -- these are a headache for test writing + assert simplify(eq.expand()) == \ + 2*x**2 + 4*x*y + 2*x + 4*y + + +def test_issue_6920(): + e = [cos(x) + I*sin(x), cos(x) - I*sin(x), + cosh(x) - sinh(x), cosh(x) + sinh(x)] + ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] + # wrap in f to show that the change happens wherever ei occurs + f = Function('f') + assert [simplify(f(ei)).args[0] for ei in e] == ok + + +def test_issue_7001(): + from sympy.abc import r, R + assert simplify(-(r*Piecewise((pi*Rational(4, 3), r <= R), + (-8*pi*R**3/(3*r**3), True)) + 2*Piecewise((pi*r*Rational(4, 3), r <= R), + (4*pi*R**3/(3*r**2), True)))/(4*pi*r)) == \ + Piecewise((-1, r <= R), (0, True)) + + +def test_inequality_no_auto_simplify(): + # no simplify on creation but can be simplified + lhs = cos(x)**2 + sin(x)**2 + rhs = 2 + e = Lt(lhs, rhs, evaluate=False) + assert e is not S.true + assert simplify(e) + + +def test_issue_9398(): + from sympy.core.numbers import Number + from sympy.polys.polytools import cancel + assert cancel(1e-14) != 0 + assert cancel(1e-14*I) != 0 + + assert simplify(1e-14) != 0 + assert simplify(1e-14*I) != 0 + + assert (I*Number(1.)*Number(10)**Number(-14)).simplify() != 0 + + assert cancel(1e-20) != 0 + assert cancel(1e-20*I) != 0 + + assert simplify(1e-20) != 0 + assert simplify(1e-20*I) != 0 + + assert cancel(1e-100) != 0 + assert cancel(1e-100*I) != 0 + + assert simplify(1e-100) != 0 + assert simplify(1e-100*I) != 0 + + f = Float("1e-1000") + assert cancel(f) != 0 + assert cancel(f*I) != 0 + + assert simplify(f) != 0 + assert simplify(f*I) != 0 + + +def test_issue_9324_simplify(): + M = MatrixSymbol('M', 10, 10) + e = M[0, 0] + M[5, 4] + 1304 + assert simplify(e) == e + + +def test_issue_9817_simplify(): + # simplify on trace of substituted explicit quadratic form of matrix + # expressions (a scalar) should return without errors (AttributeError) + # See issue #9817 and #9190 for the original bug more discussion on this + from sympy.matrices.expressions import Identity, trace + v = MatrixSymbol('v', 3, 1) + A = MatrixSymbol('A', 3, 3) + x = Matrix([i + 1 for i in range(3)]) + X = Identity(3) + quadratic = v.T * A * v + assert simplify((trace(quadratic.as_explicit())).xreplace({v:x, A:X})) == 14 + + +def test_issue_13474(): + x = Symbol('x') + assert simplify(x + csch(sinc(1))) == x + csch(sinc(1)) + + +@_both_exp_pow +def test_simplify_function_inverse(): + # "inverse" attribute does not guarantee that f(g(x)) is x + # so this simplification should not happen automatically. + # See issue #12140 + x, y = symbols('x, y') + g = Function('g') + + class f(Function): + def inverse(self, argindex=1): + return g + + assert simplify(f(g(x))) == f(g(x)) + assert inversecombine(f(g(x))) == x + assert simplify(f(g(x)), inverse=True) == x + assert simplify(f(g(sin(x)**2 + cos(x)**2)), inverse=True) == 1 + assert simplify(f(g(x, y)), inverse=True) == f(g(x, y)) + assert unchanged(asin, sin(x)) + assert simplify(asin(sin(x))) == asin(sin(x)) + assert simplify(2*asin(sin(3*x)), inverse=True) == 6*x + assert simplify(log(exp(x))) == log(exp(x)) + assert simplify(log(exp(x)), inverse=True) == x + assert simplify(exp(log(x)), inverse=True) == x + assert simplify(log(exp(x), 2), inverse=True) == x/log(2) + assert simplify(log(exp(x), 2, evaluate=False), inverse=True) == x/log(2) + + +def test_clear_coefficients(): + from sympy.simplify.simplify import clear_coefficients + assert clear_coefficients(4*y*(6*x + 3)) == (y*(2*x + 1), 0) + assert clear_coefficients(4*y*(6*x + 3) - 2) == (y*(2*x + 1), Rational(1, 6)) + assert clear_coefficients(4*y*(6*x + 3) - 2, x) == (y*(2*x + 1), x/12 + Rational(1, 6)) + assert clear_coefficients(sqrt(2) - 2) == (sqrt(2), 2) + assert clear_coefficients(4*sqrt(2) - 2) == (sqrt(2), S.Half) + assert clear_coefficients(S(3), x) == (0, x - 3) + assert clear_coefficients(S.Infinity, x) == (S.Infinity, x) + assert clear_coefficients(-S.Pi, x) == (S.Pi, -x) + assert clear_coefficients(2 - S.Pi/3, x) == (pi, -3*x + 6) + +def test_nc_simplify(): + from sympy.simplify.simplify import nc_simplify + from sympy.matrices.expressions import MatPow, Identity + from sympy.core import Pow + from functools import reduce + + a, b, c, d = symbols('a b c d', commutative = False) + x = Symbol('x') + A = MatrixSymbol("A", x, x) + B = MatrixSymbol("B", x, x) + C = MatrixSymbol("C", x, x) + D = MatrixSymbol("D", x, x) + subst = {a: A, b: B, c: C, d:D} + funcs = {Add: lambda x,y: x+y, Mul: lambda x,y: x*y } + + def _to_matrix(expr): + if expr in subst: + return subst[expr] + if isinstance(expr, Pow): + return MatPow(_to_matrix(expr.args[0]), expr.args[1]) + elif isinstance(expr, (Add, Mul)): + return reduce(funcs[expr.func],[_to_matrix(a) for a in expr.args]) + else: + return expr*Identity(x) + + def _check(expr, simplified, deep=True, matrix=True): + assert nc_simplify(expr, deep=deep) == simplified + assert expand(expr) == expand(simplified) + if matrix: + m_simp = _to_matrix(simplified).doit(inv_expand=False) + assert nc_simplify(_to_matrix(expr), deep=deep) == m_simp + + _check(a*b*a*b*a*b*c*(a*b)**3*c, ((a*b)**3*c)**2) + _check(a*b*(a*b)**-2*a*b, 1) + _check(a**2*b*a*b*a*b*(a*b)**-1, a*(a*b)**2, matrix=False) + _check(b*a*b**2*a*b**2*a*b**2, b*(a*b**2)**3) + _check(a*b*a**2*b*a**2*b*a**3, (a*b*a)**3*a**2) + _check(a**2*b*a**4*b*a**4*b*a**2, (a**2*b*a**2)**3) + _check(a**3*b*a**4*b*a**4*b*a, a**3*(b*a**4)**3*a**-3) + _check(a*b*a*b + a*b*c*x*a*b*c, (a*b)**2 + x*(a*b*c)**2) + _check(a*b*a*b*c*a*b*a*b*c, ((a*b)**2*c)**2) + _check(b**-1*a**-1*(a*b)**2, a*b) + _check(a**-1*b*c**-1, (c*b**-1*a)**-1) + expr = a**3*b*a**4*b*a**4*b*a**2*b*a**2*(b*a**2)**2*b*a**2*b*a**2 + for _ in range(10): + expr *= a*b + _check(expr, a**3*(b*a**4)**2*(b*a**2)**6*(a*b)**10) + _check((a*b*a*b)**2, (a*b*a*b)**2, deep=False) + _check(a*b*(c*d)**2, a*b*(c*d)**2) + expr = b**-1*(a**-1*b**-1 - a**-1*c*b**-1)**-1*a**-1 + assert nc_simplify(expr) == (1-c)**-1 + # commutative expressions should be returned without an error + assert nc_simplify(2*x**2) == 2*x**2 + +def test_issue_15965(): + A = Sum(z*x**y, (x, 1, a)) + anew = z*Sum(x**y, (x, 1, a)) + B = Integral(x*y, x) + bdo = x**2*y/2 + assert simplify(A + B) == anew + bdo + assert simplify(A) == anew + assert simplify(B) == bdo + assert simplify(B, doit=False) == y*Integral(x, x) + + +def test_issue_17137(): + assert simplify(cos(x)**I) == cos(x)**I + assert simplify(cos(x)**(2 + 3*I)) == cos(x)**(2 + 3*I) + + +def test_issue_21869(): + x = Symbol('x', real=True) + y = Symbol('y', real=True) + expr = And(Eq(x**2, 4), Le(x, y)) + assert expr.simplify() == expr + + expr = And(Eq(x**2, 4), Eq(x, 2)) + assert expr.simplify() == Eq(x, 2) + + expr = And(Eq(x**3, x**2), Eq(x, 1)) + assert expr.simplify() == Eq(x, 1) + + expr = And(Eq(sin(x), x**2), Eq(x, 0)) + assert expr.simplify() == Eq(x, 0) + + expr = And(Eq(x**3, x**2), Eq(x, 2)) + assert expr.simplify() == S.false + + expr = And(Eq(y, x**2), Eq(x, 1)) + assert expr.simplify() == And(Eq(y,1), Eq(x, 1)) + + expr = And(Eq(y**2, 1), Eq(y, x**2), Eq(x, 1)) + assert expr.simplify() == And(Eq(y,1), Eq(x, 1)) + + expr = And(Eq(y**2, 4), Eq(y, 2*x**2), Eq(x, 1)) + assert expr.simplify() == And(Eq(y,2), Eq(x, 1)) + + expr = And(Eq(y**2, 4), Eq(y, x**2), Eq(x, 1)) + assert expr.simplify() == S.false + + +def test_issue_7971_21740(): + z = Integral(x, (x, 1, 1)) + assert z != 0 + assert simplify(z) is S.Zero + assert simplify(S.Zero) is S.Zero + z = simplify(Float(0)) + assert z is not S.Zero and z == 0.0 + + +@slow +def test_issue_17141_slow(): + # Should not give RecursionError + assert simplify((2**acos(I+1)**2).rewrite('log')) == 2**((pi + 2*I*log(-1 + + sqrt(1 - 2*I) + I))**2/4) + + +def test_issue_17141(): + # Check that there is no RecursionError + assert simplify(x**(1 / acos(I))) == x**(2/(pi - 2*I*log(1 + sqrt(2)))) + assert simplify(acos(-I)**2*acos(I)**2) == \ + log(1 + sqrt(2))**4 + pi**2*log(1 + sqrt(2))**2/2 + pi**4/16 + assert simplify(2**acos(I)**2) == 2**((pi - 2*I*log(1 + sqrt(2)))**2/4) + p = 2**acos(I+1)**2 + assert simplify(p) == p + + +def test_simplify_kroneckerdelta(): + i, j = symbols("i j") + K = KroneckerDelta + + assert simplify(K(i, j)) == K(i, j) + assert simplify(K(0, j)) == K(0, j) + assert simplify(K(i, 0)) == K(i, 0) + + assert simplify(K(0, j).rewrite(Piecewise) * K(1, j)) == 0 + assert simplify(K(1, i) + Piecewise((1, Eq(j, 2)), (0, True))) == K(1, i) + K(2, j) + + # issue 17214 + assert simplify(K(0, j) * K(1, j)) == 0 + + n = Symbol('n', integer=True) + assert simplify(K(0, n) * K(1, n)) == 0 + + M = Matrix(4, 4, lambda i, j: K(j - i, n) if i <= j else 0) + assert simplify(M**2) == Matrix([[K(0, n), 0, K(1, n), 0], + [0, K(0, n), 0, K(1, n)], + [0, 0, K(0, n), 0], + [0, 0, 0, K(0, n)]]) + assert simplify(eye(1) * KroneckerDelta(0, n) * + KroneckerDelta(1, n)) == Matrix([[0]]) + + assert simplify(S.Infinity * KroneckerDelta(0, n) * + KroneckerDelta(1, n)) is S.NaN + + +def test_issue_17292(): + assert simplify(abs(x)/abs(x**2)) == 1/abs(x) + # this is bigger than the issue: check that deep processing works + assert simplify(5*abs((x**2 - 1)/(x - 1))) == 5*Abs(x + 1) + + +def test_issue_19822(): + expr = And(Gt(n-2, 1), Gt(n, 1)) + assert simplify(expr) == Gt(n, 3) + + +def test_issue_18645(): + expr = And(Ge(x, 3), Le(x, 3)) + assert simplify(expr) == Eq(x, 3) + expr = And(Eq(x, 3), Le(x, 3)) + assert simplify(expr) == Eq(x, 3) + + +@XFAIL +def test_issue_18642(): + i = Symbol("i", integer=True) + n = Symbol("n", integer=True) + expr = And(Eq(i, 2 * n), Le(i, 2*n -1)) + assert simplify(expr) == S.false + + +@XFAIL +def test_issue_18389(): + n = Symbol("n", integer=True) + expr = Eq(n, 0) | (n >= 1) + assert simplify(expr) == Ge(n, 0) + + +def test_issue_8373(): + x = Symbol('x', real=True) + assert simplify(Or(x < 1, x >= 1)) == S.true + + +def test_issue_7950(): + expr = And(Eq(x, 1), Eq(x, 2)) + assert simplify(expr) == S.false + + +def test_issue_22020(): + expr = I*pi/2 -oo + assert simplify(expr) == expr + # Used to throw an error + + +def test_issue_19484(): + assert simplify(sign(x) * Abs(x)) == x + + e = x + sign(x + x**3) + assert simplify(Abs(x + x**3)*e) == x**3 + x*Abs(x**3 + x) + x + + e = x**2 + sign(x**3 + 1) + assert simplify(Abs(x**3 + 1) * e) == x**3 + x**2*Abs(x**3 + 1) + 1 + + f = Function('f') + e = x + sign(x + f(x)**3) + assert simplify(Abs(x + f(x)**3) * e) == x*Abs(x + f(x)**3) + x + f(x)**3 + + +def test_issue_23543(): + # Used to give an error + x, y, z = symbols("x y z", commutative=False) + assert (x*(y + z/2)).simplify() == x*(2*y + z)/2 + + +def test_issue_11004(): + + def f(n): + return sqrt(2*pi*n) * (n/E)**n + + def m(n, k): + return f(n) / (f(n/k)**k) + + def p(n,k): + return m(n, k) / (k**n) + + N, k = symbols('N k') + half = Float('0.5', 4) + z = log(p(n, k) / p(n, k + 1)).expand(force=True) + r = simplify(z.subs(n, N).n(4)) + assert r == ( + half*k*log(k) + - half*k*log(k + 1) + + half*log(N) + - half*log(k + 1) + + Float(0.9189224, 4) + ) + + +def test_issue_19161(): + polynomial = Poly('x**2').simplify() + assert (polynomial-x**2).simplify() == 0 + + +def test_issue_22210(): + d = Symbol('d', integer=True) + expr = 2*Derivative(sin(x), (x, d)) + assert expr.simplify() == expr + + +def test_reduce_inverses_nc_pow(): + x, y = symbols("x y", commutative=True) + Z = symbols("Z", commutative=False) + assert simplify(2**Z * y**Z) == 2**Z * y**Z + assert simplify(x**Z * y**Z) == x**Z * y**Z + x, y = symbols("x y", positive=True) + assert expand((x*y)**Z) == x**Z * y**Z + assert simplify(x**Z * y**Z) == expand((x*y)**Z) + +def test_nc_recursion_coeff(): + X = symbols("X", commutative = False) + assert (2 * cos(pi/3) * X).simplify() == X + assert (2.0 * cos(pi/3) * X).simplify() == X diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_sqrtdenest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_sqrtdenest.py new file mode 100644 index 0000000000000000000000000000000000000000..41c771bb2055a1199d349ae3649f33927d79313a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_sqrtdenest.py @@ -0,0 +1,204 @@ +from sympy.core.mul import Mul +from sympy.core.numbers import (I, Integer, Rational) +from sympy.core.symbol import Symbol +from sympy.functions.elementary.miscellaneous import (root, sqrt) +from sympy.functions.elementary.trigonometric import cos +from sympy.integrals.integrals import Integral +from sympy.simplify.sqrtdenest import sqrtdenest +from sympy.simplify.sqrtdenest import ( + _subsets as subsets, _sqrt_numeric_denest) + +r2, r3, r5, r6, r7, r10, r15, r29 = [sqrt(x) for x in (2, 3, 5, 6, 7, 10, + 15, 29)] + + +def test_sqrtdenest(): + d = {sqrt(5 + 2 * r6): r2 + r3, + sqrt(5. + 2 * r6): sqrt(5. + 2 * r6), + sqrt(5. + 4*sqrt(5 + 2 * r6)): sqrt(5.0 + 4*r2 + 4*r3), + sqrt(r2): sqrt(r2), + sqrt(5 + r7): sqrt(5 + r7), + sqrt(3 + sqrt(5 + 2*r7)): + 3*r2*(5 + 2*r7)**Rational(1, 4)/(2*sqrt(6 + 3*r7)) + + r2*sqrt(6 + 3*r7)/(2*(5 + 2*r7)**Rational(1, 4)), + sqrt(3 + 2*r3): 3**Rational(3, 4)*(r6/2 + 3*r2/2)/3} + for i in d: + assert sqrtdenest(i) == d[i], i + + +def test_sqrtdenest2(): + assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \ + r5 + sqrt(11 - 2*r29) + e = sqrt(-r5 + sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16)) + assert sqrtdenest(e) == root(-2*r29 + 11, 4) + r = sqrt(1 + r7) + assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r) + e = sqrt(((1 + sqrt(1 + 2*sqrt(3 + r2 + r5)))**2).expand()) + assert sqrtdenest(e) == 1 + sqrt(1 + 2*sqrt(r2 + r5 + 3)) + + assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \ + sqrt(2)*root(3, 4) + root(3, 4)**3 + + assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \ + 1 + r5 + sqrt(1 + r3) + + assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \ + 1 + sqrt(1 + r3) + r5 + r7 + + e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand()) + assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3) + + e = sqrt(-2*r10 + 2*r2*sqrt(-2*r10 + 11) + 14) + assert sqrtdenest(e) == sqrt(-2*r10 - 2*r2 + 4*r5 + 14) + + # check that the result is not more complicated than the input + z = sqrt(-2*r29 + cos(2) + 2*sqrt(-10*r29 + 55) + 16) + assert sqrtdenest(z) == z + + assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15)) + + z = sqrt(15 - 2*sqrt(31) + 2*sqrt(55 - 10*r29)) + assert sqrtdenest(z) == z + + +def test_sqrtdenest_rec(): + assert sqrtdenest(sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 33)) == \ + -r2 + r3 + 2*r7 + assert sqrtdenest(sqrt(-28*r7 - 14*r5 + 4*sqrt(35) + 82)) == \ + -7 + r5 + 2*r7 + assert sqrtdenest(sqrt(6*r2/11 + 2*sqrt(22)/11 + 6*sqrt(11)/11 + 2)) == \ + sqrt(11)*(r2 + 3 + sqrt(11))/11 + assert sqrtdenest(sqrt(468*r3 + 3024*r2 + 2912*r6 + 19735)) == \ + 9*r3 + 26 + 56*r6 + z = sqrt(-490*r3 - 98*sqrt(115) - 98*sqrt(345) - 2107) + assert sqrtdenest(z) == sqrt(-1)*(7*r5 + 7*r15 + 7*sqrt(23)) + z = sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 34) + assert sqrtdenest(z) == z + assert sqrtdenest(sqrt(-8*r2 - 2*r5 + 18)) == -r10 + 1 + r2 + r5 + assert sqrtdenest(sqrt(8*r2 + 2*r5 - 18)) == \ + sqrt(-1)*(-r10 + 1 + r2 + r5) + assert sqrtdenest(sqrt(8*r2/3 + 14*r5/3 + Rational(154, 9))) == \ + -r10/3 + r2 + r5 + 3 + assert sqrtdenest(sqrt(sqrt(2*r6 + 5) + sqrt(2*r7 + 8))) == \ + sqrt(1 + r2 + r3 + r7) + assert sqrtdenest(sqrt(4*r15 + 8*r5 + 12*r3 + 24)) == 1 + r3 + r5 + r15 + + w = 1 + r2 + r3 + r5 + r7 + assert sqrtdenest(sqrt((w**2).expand())) == w + z = sqrt((w**2).expand() + 1) + assert sqrtdenest(z) == z + + z = sqrt(2*r10 + 6*r2 + 4*r5 + 12 + 10*r15 + 30*r3) + assert sqrtdenest(z) == z + + +def test_issue_6241(): + z = sqrt( -320 + 32*sqrt(5) + 64*r15) + assert sqrtdenest(z) == z + + +def test_sqrtdenest3(): + z = sqrt(13 - 2*r10 + 2*r2*sqrt(-2*r10 + 11)) + assert sqrtdenest(z) == -1 + r2 + r10 + assert sqrtdenest(z, max_iter=1) == -1 + sqrt(2) + sqrt(10) + z = sqrt(sqrt(r2 + 2) + 2) + assert sqrtdenest(z) == z + assert sqrtdenest(sqrt(-2*r10 + 4*r2*sqrt(-2*r10 + 11) + 20)) == \ + sqrt(-2*r10 - 4*r2 + 8*r5 + 20) + assert sqrtdenest(sqrt((112 + 70*r2) + (46 + 34*r2)*r5)) == \ + r10 + 5 + 4*r2 + 3*r5 + z = sqrt(5 + sqrt(2*r6 + 5)*sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16)) + r = sqrt(-2*r29 + 11) + assert sqrtdenest(z) == sqrt(r2*r + r3*r + r10 + r15 + 5) + + n = sqrt(2*r6/7 + 2*r7/7 + 2*sqrt(42)/7 + 2) + d = sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29)) + assert sqrtdenest(n/d) == r7*(1 + r6 + r7)/(Mul(7, (sqrt(-2*r29 + 11) + r5), + evaluate=False)) + + +def test_sqrtdenest4(): + # see Denest_en.pdf in https://github.com/sympy/sympy/issues/3192 + z = sqrt(8 - r2*sqrt(5 - r5) - sqrt(3)*(1 + r5)) + z1 = sqrtdenest(z) + c = sqrt(-r5 + 5) + z1 = ((-r15*c - r3*c + c + r5*c - r6 - r2 + r10 + sqrt(30))/4).expand() + assert sqrtdenest(z) == z1 + + z = sqrt(2*r2*sqrt(r2 + 2) + 5*r2 + 4*sqrt(r2 + 2) + 8) + assert sqrtdenest(z) == r2 + sqrt(r2 + 2) + 2 + + w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3) + z = sqrt((w**2).expand()) + assert sqrtdenest(z) == w.expand() + + +def test_sqrt_symbolic_denest(): + x = Symbol('x') + z = sqrt(((1 + sqrt(sqrt(2 + x) + 3))**2).expand()) + assert sqrtdenest(z) == sqrt((1 + sqrt(sqrt(2 + x) + 3))**2) + z = sqrt(((1 + sqrt(sqrt(2 + cos(1)) + 3))**2).expand()) + assert sqrtdenest(z) == 1 + sqrt(sqrt(2 + cos(1)) + 3) + z = ((1 + cos(2))**4 + 1).expand() + assert sqrtdenest(z) == z + z = sqrt(((1 + sqrt(sqrt(2 + cos(3*x)) + 3))**2 + 1).expand()) + assert sqrtdenest(z) == z + c = cos(3) + c2 = c**2 + assert sqrtdenest(sqrt(2*sqrt(1 + r3)*c + c2 + 1 + r3*c2)) == \ + -1 - sqrt(1 + r3)*c + ra = sqrt(1 + r3) + z = sqrt(20*ra*sqrt(3 + 3*r3) + 12*r3*ra*sqrt(3 + 3*r3) + 64*r3 + 112) + assert sqrtdenest(z) == z + + +def test_issue_5857(): + from sympy.abc import x, y + z = sqrt(1/(4*r3 + 7) + 1) + ans = (r2 + r6)/(r3 + 2) + assert sqrtdenest(z) == ans + assert sqrtdenest(1 + z) == 1 + ans + assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \ + Integral(1 + ans, (x, 1, 2)) + assert sqrtdenest(x + sqrt(y)) == x + sqrt(y) + ans = (r2 + r6)/(r3 + 2) + assert sqrtdenest(z) == ans + assert sqrtdenest(1 + z) == 1 + ans + assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \ + Integral(1 + ans, (x, 1, 2)) + assert sqrtdenest(x + sqrt(y)) == x + sqrt(y) + + +def test_subsets(): + assert subsets(1) == [[1]] + assert subsets(4) == [ + [1, 0, 0, 0], [0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0], [1, 0, 1, 0], + [0, 1, 1, 0], [1, 1, 1, 0], [0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], + [1, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]] + + +def test_issue_5653(): + assert sqrtdenest( + sqrt(2 + sqrt(2 + sqrt(2)))) == sqrt(2 + sqrt(2 + sqrt(2))) + +def test_issue_12420(): + assert sqrtdenest((3 - sqrt(2)*sqrt(4 + 3*I) + 3*I)/2) == I + e = 3 - sqrt(2)*sqrt(4 + I) + 3*I + assert sqrtdenest(e) == e + +def test_sqrt_ratcomb(): + assert sqrtdenest(sqrt(1 + r3) + sqrt(3 + 3*r3) - sqrt(10 + 6*r3)) == 0 + +def test_issue_18041(): + e = -sqrt(-2 + 2*sqrt(3)*I) + assert sqrtdenest(e) == -1 - sqrt(3)*I + +def test_issue_19914(): + a = Integer(-8) + b = Integer(-1) + r = Integer(63) + d2 = a*a - b*b*r + + assert _sqrt_numeric_denest(a, b, r, d2) == \ + sqrt(14)*I/2 + 3*sqrt(2)*I/2 + assert sqrtdenest(sqrt(-8-sqrt(63))) == sqrt(14)*I/2 + 3*sqrt(2)*I/2 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_trigsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_trigsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..ea091ec8a6c7d654405968e3d035c2bbe02ccdf7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/tests/test_trigsimp.py @@ -0,0 +1,520 @@ +from itertools import product +from sympy.core.function import (Subs, count_ops, diff, expand) +from sympy.core.numbers import (E, I, Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh, tanh) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (cos, cot, sin, tan) +from sympy.functions.elementary.trigonometric import (acos, asin, atan2) +from sympy.functions.elementary.trigonometric import (asec, acsc) +from sympy.functions.elementary.trigonometric import (acot, atan) +from sympy.integrals.integrals import integrate +from sympy.matrices.dense import Matrix +from sympy.simplify.simplify import simplify +from sympy.simplify.trigsimp import (exptrigsimp, trigsimp) + +from sympy.testing.pytest import XFAIL + +from sympy.abc import x, y + + + +def test_trigsimp1(): + x, y = symbols('x,y') + + assert trigsimp(1 - sin(x)**2) == cos(x)**2 + assert trigsimp(1 - cos(x)**2) == sin(x)**2 + assert trigsimp(sin(x)**2 + cos(x)**2) == 1 + assert trigsimp(1 + tan(x)**2) == 1/cos(x)**2 + assert trigsimp(1/cos(x)**2 - 1) == tan(x)**2 + assert trigsimp(1/cos(x)**2 - tan(x)**2) == 1 + assert trigsimp(1 + cot(x)**2) == 1/sin(x)**2 + assert trigsimp(1/sin(x)**2 - 1) == 1/tan(x)**2 + assert trigsimp(1/sin(x)**2 - cot(x)**2) == 1 + + assert trigsimp(5*cos(x)**2 + 5*sin(x)**2) == 5 + assert trigsimp(5*cos(x/2)**2 + 2*sin(x/2)**2) == 3*cos(x)/2 + Rational(7, 2) + + assert trigsimp(sin(x)/cos(x)) == tan(x) + assert trigsimp(2*tan(x)*cos(x)) == 2*sin(x) + assert trigsimp(cot(x)**3*sin(x)**3) == cos(x)**3 + assert trigsimp(y*tan(x)**2/sin(x)**2) == y/cos(x)**2 + assert trigsimp(cot(x)/cos(x)) == 1/sin(x) + + assert trigsimp(sin(x + y) + sin(x - y)) == 2*sin(x)*cos(y) + assert trigsimp(sin(x + y) - sin(x - y)) == 2*sin(y)*cos(x) + assert trigsimp(cos(x + y) + cos(x - y)) == 2*cos(x)*cos(y) + assert trigsimp(cos(x + y) - cos(x - y)) == -2*sin(x)*sin(y) + assert trigsimp(tan(x + y) - tan(x)/(1 - tan(x)*tan(y))) == \ + sin(y)/(-sin(y)*tan(x) + cos(y)) # -tan(y)/(tan(x)*tan(y) - 1) + + assert trigsimp(sinh(x + y) + sinh(x - y)) == 2*sinh(x)*cosh(y) + assert trigsimp(sinh(x + y) - sinh(x - y)) == 2*sinh(y)*cosh(x) + assert trigsimp(cosh(x + y) + cosh(x - y)) == 2*cosh(x)*cosh(y) + assert trigsimp(cosh(x + y) - cosh(x - y)) == 2*sinh(x)*sinh(y) + assert trigsimp(tanh(x + y) - tanh(x)/(1 + tanh(x)*tanh(y))) == \ + sinh(y)/(sinh(y)*tanh(x) + cosh(y)) + + assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2) == 1.0 + e = 2*sin(x)**2 + 2*cos(x)**2 + assert trigsimp(log(e)) == log(2) + + +def test_trigsimp1a(): + assert trigsimp(sin(2)**2*cos(3)*exp(2)/cos(2)**2) == tan(2)**2*cos(3)*exp(2) + assert trigsimp(tan(2)**2*cos(3)*exp(2)*cos(2)**2) == sin(2)**2*cos(3)*exp(2) + assert trigsimp(cot(2)*cos(3)*exp(2)*sin(2)) == cos(3)*exp(2)*cos(2) + assert trigsimp(tan(2)*cos(3)*exp(2)/sin(2)) == cos(3)*exp(2)/cos(2) + assert trigsimp(cot(2)*cos(3)*exp(2)/cos(2)) == cos(3)*exp(2)/sin(2) + assert trigsimp(cot(2)*cos(3)*exp(2)*tan(2)) == cos(3)*exp(2) + assert trigsimp(sinh(2)*cos(3)*exp(2)/cosh(2)) == tanh(2)*cos(3)*exp(2) + assert trigsimp(tanh(2)*cos(3)*exp(2)*cosh(2)) == sinh(2)*cos(3)*exp(2) + assert trigsimp(coth(2)*cos(3)*exp(2)*sinh(2)) == cosh(2)*cos(3)*exp(2) + assert trigsimp(tanh(2)*cos(3)*exp(2)/sinh(2)) == cos(3)*exp(2)/cosh(2) + assert trigsimp(coth(2)*cos(3)*exp(2)/cosh(2)) == cos(3)*exp(2)/sinh(2) + assert trigsimp(coth(2)*cos(3)*exp(2)*tanh(2)) == cos(3)*exp(2) + + +def test_trigsimp2(): + x, y = symbols('x,y') + assert trigsimp(cos(x)**2*sin(y)**2 + cos(x)**2*cos(y)**2 + sin(x)**2, + recursive=True) == 1 + assert trigsimp(sin(x)**2*sin(y)**2 + sin(x)**2*cos(y)**2 + cos(x)**2, + recursive=True) == 1 + assert trigsimp( + Subs(x, x, sin(y)**2 + cos(y)**2)) == Subs(x, x, 1) + + +def test_issue_4373(): + x = Symbol("x") + assert abs(trigsimp(2.0*sin(x)**2 + 2.0*cos(x)**2) - 2.0) < 1e-10 + + +def test_trigsimp3(): + x, y = symbols('x,y') + assert trigsimp(sin(x)/cos(x)) == tan(x) + assert trigsimp(sin(x)**2/cos(x)**2) == tan(x)**2 + assert trigsimp(sin(x)**3/cos(x)**3) == tan(x)**3 + assert trigsimp(sin(x)**10/cos(x)**10) == tan(x)**10 + + assert trigsimp(cos(x)/sin(x)) == 1/tan(x) + assert trigsimp(cos(x)**2/sin(x)**2) == 1/tan(x)**2 + assert trigsimp(cos(x)**10/sin(x)**10) == 1/tan(x)**10 + + assert trigsimp(tan(x)) == trigsimp(sin(x)/cos(x)) + + +def test_issue_4661(): + a, x, y = symbols('a x y') + eq = -4*sin(x)**4 + 4*cos(x)**4 - 8*cos(x)**2 + assert trigsimp(eq) == -4 + n = sin(x)**6 + 4*sin(x)**4*cos(x)**2 + 5*sin(x)**2*cos(x)**4 + 2*cos(x)**6 + d = -sin(x)**2 - 2*cos(x)**2 + assert simplify(n/d) == -1 + assert trigsimp(-2*cos(x)**2 + cos(x)**4 - sin(x)**4) == -1 + eq = (- sin(x)**3/4)*cos(x) + (cos(x)**3/4)*sin(x) - sin(2*x)*cos(2*x)/8 + assert trigsimp(eq) == 0 + + +def test_issue_4494(): + a, b = symbols('a b') + eq = sin(a)**2*sin(b)**2 + cos(a)**2*cos(b)**2*tan(a)**2 + cos(a)**2 + assert trigsimp(eq) == 1 + + +def test_issue_5948(): + a, x, y = symbols('a x y') + assert trigsimp(diff(integrate(cos(x)/sin(x)**7, x), x)) == \ + cos(x)/sin(x)**7 + + +def test_issue_4775(): + a, x, y = symbols('a x y') + assert trigsimp(sin(x)*cos(y)+cos(x)*sin(y)) == sin(x + y) + assert trigsimp(sin(x)*cos(y)+cos(x)*sin(y)+3) == sin(x + y) + 3 + + +def test_issue_4280(): + a, x, y = symbols('a x y') + assert trigsimp(cos(x)**2 + cos(y)**2*sin(x)**2 + sin(y)**2*sin(x)**2) == 1 + assert trigsimp(a**2*sin(x)**2 + a**2*cos(y)**2*cos(x)**2 + a**2*cos(x)**2*sin(y)**2) == a**2 + assert trigsimp(a**2*cos(y)**2*sin(x)**2 + a**2*sin(y)**2*sin(x)**2) == a**2*sin(x)**2 + + +def test_issue_3210(): + eqs = (sin(2)*cos(3) + sin(3)*cos(2), + -sin(2)*sin(3) + cos(2)*cos(3), + sin(2)*cos(3) - sin(3)*cos(2), + sin(2)*sin(3) + cos(2)*cos(3), + sin(2)*sin(3) + cos(2)*cos(3) + cos(2), + sinh(2)*cosh(3) + sinh(3)*cosh(2), + sinh(2)*sinh(3) + cosh(2)*cosh(3), + ) + assert [trigsimp(e) for e in eqs] == [ + sin(5), + cos(5), + -sin(1), + cos(1), + cos(1) + cos(2), + sinh(5), + cosh(5), + ] + + +def test_trigsimp_issues(): + a, x, y = symbols('a x y') + + # issue 4625 - factor_terms works, too + assert trigsimp(sin(x)**3 + cos(x)**2*sin(x)) == sin(x) + + # issue 5948 + assert trigsimp(diff(integrate(cos(x)/sin(x)**3, x), x)) == \ + cos(x)/sin(x)**3 + assert trigsimp(diff(integrate(sin(x)/cos(x)**3, x), x)) == \ + sin(x)/cos(x)**3 + + # check integer exponents + e = sin(x)**y/cos(x)**y + assert trigsimp(e) == e + assert trigsimp(e.subs(y, 2)) == tan(x)**2 + assert trigsimp(e.subs(x, 1)) == tan(1)**y + + # check for multiple patterns + assert (cos(x)**2/sin(x)**2*cos(y)**2/sin(y)**2).trigsimp() == \ + 1/tan(x)**2/tan(y)**2 + assert trigsimp(cos(x)/sin(x)*cos(x+y)/sin(x+y)) == \ + 1/(tan(x)*tan(x + y)) + + eq = cos(2)*(cos(3) + 1)**2/(cos(3) - 1)**2 + assert trigsimp(eq) == eq.factor() # factor makes denom (-1 + cos(3))**2 + assert trigsimp(cos(2)*(cos(3) + 1)**2*(cos(3) - 1)**2) == \ + cos(2)*sin(3)**4 + + # issue 6789; this generates an expression that formerly caused + # trigsimp to hang + assert cot(x).equals(tan(x)) is False + + # nan or the unchanged expression is ok, but not sin(1) + z = cos(x)**2 + sin(x)**2 - 1 + z1 = tan(x)**2 - 1/cot(x)**2 + n = (1 + z1/z) + assert trigsimp(sin(n)) != sin(1) + eq = x*(n - 1) - x*n + assert trigsimp(eq) is S.NaN + assert trigsimp(eq, recursive=True) is S.NaN + assert trigsimp(1).is_Integer + + assert trigsimp(-sin(x)**4 - 2*sin(x)**2*cos(x)**2 - cos(x)**4) == -1 + + +def test_trigsimp_issue_2515(): + x = Symbol('x') + assert trigsimp(x*cos(x)*tan(x)) == x*sin(x) + assert trigsimp(-sin(x) + cos(x)*tan(x)) == 0 + + +def test_trigsimp_issue_3826(): + assert trigsimp(tan(2*x).expand(trig=True)) == tan(2*x) + + +def test_trigsimp_issue_4032(): + n = Symbol('n', integer=True, positive=True) + assert trigsimp(2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2) == \ + 2**(n/2)*cos(pi*n/4)/2 + 2**n/4 + + +def test_trigsimp_issue_7761(): + assert trigsimp(cosh(pi/4)) == cosh(pi/4) + + +def test_trigsimp_noncommutative(): + x, y = symbols('x,y') + A, B = symbols('A,B', commutative=False) + + assert trigsimp(A - A*sin(x)**2) == A*cos(x)**2 + assert trigsimp(A - A*cos(x)**2) == A*sin(x)**2 + assert trigsimp(A*sin(x)**2 + A*cos(x)**2) == A + assert trigsimp(A + A*tan(x)**2) == A/cos(x)**2 + assert trigsimp(A/cos(x)**2 - A) == A*tan(x)**2 + assert trigsimp(A/cos(x)**2 - A*tan(x)**2) == A + assert trigsimp(A + A*cot(x)**2) == A/sin(x)**2 + assert trigsimp(A/sin(x)**2 - A) == A/tan(x)**2 + assert trigsimp(A/sin(x)**2 - A*cot(x)**2) == A + + assert trigsimp(y*A*cos(x)**2 + y*A*sin(x)**2) == y*A + + assert trigsimp(A*sin(x)/cos(x)) == A*tan(x) + assert trigsimp(A*tan(x)*cos(x)) == A*sin(x) + assert trigsimp(A*cot(x)**3*sin(x)**3) == A*cos(x)**3 + assert trigsimp(y*A*tan(x)**2/sin(x)**2) == y*A/cos(x)**2 + assert trigsimp(A*cot(x)/cos(x)) == A/sin(x) + + assert trigsimp(A*sin(x + y) + A*sin(x - y)) == 2*A*sin(x)*cos(y) + assert trigsimp(A*sin(x + y) - A*sin(x - y)) == 2*A*sin(y)*cos(x) + assert trigsimp(A*cos(x + y) + A*cos(x - y)) == 2*A*cos(x)*cos(y) + assert trigsimp(A*cos(x + y) - A*cos(x - y)) == -2*A*sin(x)*sin(y) + + assert trigsimp(A*sinh(x + y) + A*sinh(x - y)) == 2*A*sinh(x)*cosh(y) + assert trigsimp(A*sinh(x + y) - A*sinh(x - y)) == 2*A*sinh(y)*cosh(x) + assert trigsimp(A*cosh(x + y) + A*cosh(x - y)) == 2*A*cosh(x)*cosh(y) + assert trigsimp(A*cosh(x + y) - A*cosh(x - y)) == 2*A*sinh(x)*sinh(y) + + assert trigsimp(A*cos(0.12345)**2 + A*sin(0.12345)**2) == 1.0*A + + +def test_hyperbolic_simp(): + x, y = symbols('x,y') + + assert trigsimp(sinh(x)**2 + 1) == cosh(x)**2 + assert trigsimp(cosh(x)**2 - 1) == sinh(x)**2 + assert trigsimp(cosh(x)**2 - sinh(x)**2) == 1 + assert trigsimp(1 - tanh(x)**2) == 1/cosh(x)**2 + assert trigsimp(1 - 1/cosh(x)**2) == tanh(x)**2 + assert trigsimp(tanh(x)**2 + 1/cosh(x)**2) == 1 + assert trigsimp(coth(x)**2 - 1) == 1/sinh(x)**2 + assert trigsimp(1/sinh(x)**2 + 1) == 1/tanh(x)**2 + assert trigsimp(coth(x)**2 - 1/sinh(x)**2) == 1 + + assert trigsimp(5*cosh(x)**2 - 5*sinh(x)**2) == 5 + assert trigsimp(5*cosh(x/2)**2 - 2*sinh(x/2)**2) == 3*cosh(x)/2 + Rational(7, 2) + + assert trigsimp(sinh(x)/cosh(x)) == tanh(x) + assert trigsimp(tanh(x)) == trigsimp(sinh(x)/cosh(x)) + assert trigsimp(cosh(x)/sinh(x)) == 1/tanh(x) + assert trigsimp(2*tanh(x)*cosh(x)) == 2*sinh(x) + assert trigsimp(coth(x)**3*sinh(x)**3) == cosh(x)**3 + assert trigsimp(y*tanh(x)**2/sinh(x)**2) == y/cosh(x)**2 + assert trigsimp(coth(x)/cosh(x)) == 1/sinh(x) + + for a in (pi/6*I, pi/4*I, pi/3*I): + assert trigsimp(sinh(a)*cosh(x) + cosh(a)*sinh(x)) == sinh(x + a) + assert trigsimp(-sinh(a)*cosh(x) + cosh(a)*sinh(x)) == sinh(x - a) + + e = 2*cosh(x)**2 - 2*sinh(x)**2 + assert trigsimp(log(e)) == log(2) + + # issue 19535: + assert trigsimp(sqrt(cosh(x)**2 - 1)) == sqrt(sinh(x)**2) + + assert trigsimp(cosh(x)**2*cosh(y)**2 - cosh(x)**2*sinh(y)**2 - sinh(x)**2, + recursive=True) == 1 + assert trigsimp(sinh(x)**2*sinh(y)**2 - sinh(x)**2*cosh(y)**2 + cosh(x)**2, + recursive=True) == 1 + + assert abs(trigsimp(2.0*cosh(x)**2 - 2.0*sinh(x)**2) - 2.0) < 1e-10 + + assert trigsimp(sinh(x)**2/cosh(x)**2) == tanh(x)**2 + assert trigsimp(sinh(x)**3/cosh(x)**3) == tanh(x)**3 + assert trigsimp(sinh(x)**10/cosh(x)**10) == tanh(x)**10 + assert trigsimp(cosh(x)**3/sinh(x)**3) == 1/tanh(x)**3 + + assert trigsimp(cosh(x)/sinh(x)) == 1/tanh(x) + assert trigsimp(cosh(x)**2/sinh(x)**2) == 1/tanh(x)**2 + assert trigsimp(cosh(x)**10/sinh(x)**10) == 1/tanh(x)**10 + + assert trigsimp(x*cosh(x)*tanh(x)) == x*sinh(x) + assert trigsimp(-sinh(x) + cosh(x)*tanh(x)) == 0 + + assert tan(x) != 1/cot(x) # cot doesn't auto-simplify + + assert trigsimp(tan(x) - 1/cot(x)) == 0 + assert trigsimp(3*tanh(x)**7 - 2/coth(x)**7) == tanh(x)**7 + + +def test_trigsimp_groebner(): + from sympy.simplify.trigsimp import trigsimp_groebner + + c = cos(x) + s = sin(x) + ex = (4*s*c + 12*s + 5*c**3 + 21*c**2 + 23*c + 15)/( + -s*c**2 + 2*s*c + 15*s + 7*c**3 + 31*c**2 + 37*c + 21) + resnum = (5*s - 5*c + 1) + resdenom = (8*s - 6*c) + results = [resnum/resdenom, (-resnum)/(-resdenom)] + assert trigsimp_groebner(ex) in results + assert trigsimp_groebner(s/c, hints=[tan]) == tan(x) + assert trigsimp_groebner(c*s) == c*s + assert trigsimp((-s + 1)/c + c/(-s + 1), + method='groebner') == 2/c + assert trigsimp((-s + 1)/c + c/(-s + 1), + method='groebner', polynomial=True) == 2/c + + # Test quick=False works + assert trigsimp_groebner(ex, hints=[2]) in results + assert trigsimp_groebner(ex, hints=[int(2)]) in results + + # test "I" + assert trigsimp_groebner(sin(I*x)/cos(I*x), hints=[tanh]) == I*tanh(x) + + # test hyperbolic / sums + assert trigsimp_groebner((tanh(x)+tanh(y))/(1+tanh(x)*tanh(y)), + hints=[(tanh, x, y)]) == tanh(x + y) + + +def test_issue_2827_trigsimp_methods(): + measure1 = lambda expr: len(str(expr)) + measure2 = lambda expr: -count_ops(expr) + # Return the most complicated result + expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) + ans = Matrix([1]) + M = Matrix([expr]) + assert trigsimp(M, method='fu', measure=measure1) == ans + assert trigsimp(M, method='fu', measure=measure2) != ans + # all methods should work with Basic expressions even if they + # aren't Expr + M = Matrix.eye(1) + assert all(trigsimp(M, method=m) == M for m in + 'fu matching groebner old'.split()) + # watch for E in exptrigsimp, not only exp() + eq = 1/sqrt(E) + E + assert exptrigsimp(eq) == eq + +def test_issue_15129_trigsimp_methods(): + t1 = Matrix([sin(Rational(1, 50)), cos(Rational(1, 50)), 0]) + t2 = Matrix([sin(Rational(1, 25)), cos(Rational(1, 25)), 0]) + t3 = Matrix([cos(Rational(1, 25)), sin(Rational(1, 25)), 0]) + r1 = t1.dot(t2) + r2 = t1.dot(t3) + assert trigsimp(r1) == cos(Rational(1, 50)) + assert trigsimp(r2) == sin(Rational(3, 50)) + +def test_exptrigsimp(): + def valid(a, b): + from sympy.core.random import verify_numerically as tn + if not (tn(a, b) and a == b): + return False + return True + + assert exptrigsimp(exp(x) + exp(-x)) == 2*cosh(x) + assert exptrigsimp(exp(x) - exp(-x)) == 2*sinh(x) + assert exptrigsimp((2*exp(x)-2*exp(-x))/(exp(x)+exp(-x))) == 2*tanh(x) + assert exptrigsimp((2*exp(2*x)-2)/(exp(2*x)+1)) == 2*tanh(x) + e = [cos(x) + I*sin(x), cos(x) - I*sin(x), + cosh(x) - sinh(x), cosh(x) + sinh(x)] + ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] + assert all(valid(i, j) for i, j in zip( + [exptrigsimp(ei) for ei in e], ok)) + + ue = [cos(x) + sin(x), cos(x) - sin(x), + cosh(x) + I*sinh(x), cosh(x) - I*sinh(x)] + assert [exptrigsimp(ei) == ei for ei in ue] + + res = [] + ok = [y*tanh(1), 1/(y*tanh(1)), I*y*tan(1), -I/(y*tan(1)), + y*tanh(x), 1/(y*tanh(x)), I*y*tan(x), -I/(y*tan(x)), + y*tanh(1 + I), 1/(y*tanh(1 + I))] + for a in (1, I, x, I*x, 1 + I): + w = exp(a) + eq = y*(w - 1/w)/(w + 1/w) + res.append(simplify(eq)) + res.append(simplify(1/eq)) + assert all(valid(i, j) for i, j in zip(res, ok)) + + for a in range(1, 3): + w = exp(a) + e = w + 1/w + s = simplify(e) + assert s == exptrigsimp(e) + assert valid(s, 2*cosh(a)) + e = w - 1/w + s = simplify(e) + assert s == exptrigsimp(e) + assert valid(s, 2*sinh(a)) + +def test_exptrigsimp_noncommutative(): + a,b = symbols('a b', commutative=False) + x = Symbol('x', commutative=True) + assert exp(a + x) == exptrigsimp(exp(a)*exp(x)) + p = exp(a)*exp(b) - exp(b)*exp(a) + assert p == exptrigsimp(p) != 0 + +def test_powsimp_on_numbers(): + assert 2**(Rational(1, 3) - 2) == 2**Rational(1, 3)/4 + + +@XFAIL +def test_issue_6811_fail(): + # from doc/src/modules/physics/mechanics/examples.rst, the current `eq` + # at Line 576 (in different variables) was formerly the equivalent and + # shorter expression given below...it would be nice to get the short one + # back again + xp, y, x, z = symbols('xp, y, x, z') + eq = 4*(-19*sin(x)*y + 5*sin(3*x)*y + 15*cos(2*x)*z - 21*z)*xp/(9*cos(x) - 5*cos(3*x)) + assert trigsimp(eq) == -2*(2*cos(x)*tan(x)*y + 3*z)*xp/cos(x) + + +def test_Piecewise(): + e1 = x*(x + y) - y*(x + y) + e2 = sin(x)**2 + cos(x)**2 + e3 = expand((x + y)*y/x) + # s1 = simplify(e1) + s2 = simplify(e2) + # s3 = simplify(e3) + + # trigsimp tries not to touch non-trig containing args + assert trigsimp(Piecewise((e1, e3 < e2), (e3, True))) == \ + Piecewise((e1, e3 < s2), (e3, True)) + + +def test_issue_21594(): + assert simplify(exp(Rational(1,2)) + exp(Rational(-1,2))) == cosh(S.Half)*2 + + +def test_trigsimp_old(): + x, y = symbols('x,y') + + assert trigsimp(1 - sin(x)**2, old=True) == cos(x)**2 + assert trigsimp(1 - cos(x)**2, old=True) == sin(x)**2 + assert trigsimp(sin(x)**2 + cos(x)**2, old=True) == 1 + assert trigsimp(1 + tan(x)**2, old=True) == 1/cos(x)**2 + assert trigsimp(1/cos(x)**2 - 1, old=True) == tan(x)**2 + assert trigsimp(1/cos(x)**2 - tan(x)**2, old=True) == 1 + assert trigsimp(1 + cot(x)**2, old=True) == 1/sin(x)**2 + assert trigsimp(1/sin(x)**2 - cot(x)**2, old=True) == 1 + + assert trigsimp(5*cos(x)**2 + 5*sin(x)**2, old=True) == 5 + + assert trigsimp(sin(x)/cos(x), old=True) == tan(x) + assert trigsimp(2*tan(x)*cos(x), old=True) == 2*sin(x) + assert trigsimp(cot(x)**3*sin(x)**3, old=True) == cos(x)**3 + assert trigsimp(y*tan(x)**2/sin(x)**2, old=True) == y/cos(x)**2 + assert trigsimp(cot(x)/cos(x), old=True) == 1/sin(x) + + assert trigsimp(sin(x + y) + sin(x - y), old=True) == 2*sin(x)*cos(y) + assert trigsimp(sin(x + y) - sin(x - y), old=True) == 2*sin(y)*cos(x) + assert trigsimp(cos(x + y) + cos(x - y), old=True) == 2*cos(x)*cos(y) + assert trigsimp(cos(x + y) - cos(x - y), old=True) == -2*sin(x)*sin(y) + + assert trigsimp(sinh(x + y) + sinh(x - y), old=True) == 2*sinh(x)*cosh(y) + assert trigsimp(sinh(x + y) - sinh(x - y), old=True) == 2*sinh(y)*cosh(x) + assert trigsimp(cosh(x + y) + cosh(x - y), old=True) == 2*cosh(x)*cosh(y) + assert trigsimp(cosh(x + y) - cosh(x - y), old=True) == 2*sinh(x)*sinh(y) + + assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2, old=True) == 1.0 + + assert trigsimp(sin(x)/cos(x), old=True, method='combined') == tan(x) + assert trigsimp(sin(x)/cos(x), old=True, method='groebner') == sin(x)/cos(x) + assert trigsimp(sin(x)/cos(x), old=True, method='groebner', hints=[tan]) == tan(x) + + assert trigsimp(1-sin(sin(x)**2+cos(x)**2)**2, old=True, deep=True) == cos(1)**2 + + +def test_trigsimp_inverse(): + alpha = symbols('alpha') + s, c = sin(alpha), cos(alpha) + + for finv in [asin, acos, asec, acsc, atan, acot]: + f = finv.inverse(None) + assert alpha == trigsimp(finv(f(alpha)), inverse=True) + + # test atan2(cos, sin), atan2(sin, cos), etc... + for a, b in [[c, s], [s, c]]: + for i, j in product([-1, 1], repeat=2): + angle = atan2(i*b, j*a) + angle_inverted = trigsimp(angle, inverse=True) + assert angle_inverted != angle # assures simplification happened + assert sin(angle_inverted) == trigsimp(sin(angle)) + assert cos(angle_inverted) == trigsimp(cos(angle)) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/trigsimp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/trigsimp.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5be1444a4625e4b63b339877e441d12cfbe8de --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/simplify/trigsimp.py @@ -0,0 +1,1252 @@ +from collections import defaultdict +from functools import reduce + +from sympy.core import (sympify, Basic, S, Expr, factor_terms, + Mul, Add, bottom_up) +from sympy.core.cache import cacheit +from sympy.core.function import (count_ops, _mexpand, FunctionClass, expand, + expand_mul, _coeff_isneg, Derivative) +from sympy.core.numbers import I, Integer +from sympy.core.intfunc import igcd +from sympy.core.sorting import _nodes +from sympy.core.symbol import Dummy, symbols, Wild +from sympy.external.gmpy import SYMPY_INTS +from sympy.functions import sin, cos, exp, cosh, tanh, sinh, tan, cot, coth +from sympy.functions import atan2 +from sympy.functions.elementary.hyperbolic import HyperbolicFunction +from sympy.functions.elementary.trigonometric import TrigonometricFunction +from sympy.polys import Poly, factor, cancel, parallel_poly_from_expr +from sympy.polys.domains import ZZ +from sympy.polys.polyerrors import PolificationFailed +from sympy.polys.polytools import groebner +from sympy.simplify.cse_main import cse +from sympy.strategies.core import identity +from sympy.strategies.tree import greedy +from sympy.utilities.iterables import iterable +from sympy.utilities.misc import debug + +def trigsimp_groebner(expr, hints=[], quick=False, order="grlex", + polynomial=False): + """ + Simplify trigonometric expressions using a groebner basis algorithm. + + Explanation + =========== + + This routine takes a fraction involving trigonometric or hyperbolic + expressions, and tries to simplify it. The primary metric is the + total degree. Some attempts are made to choose the simplest possible + expression of the minimal degree, but this is non-rigorous, and also + very slow (see the ``quick=True`` option). + + If ``polynomial`` is set to True, instead of simplifying numerator and + denominator together, this function just brings numerator and denominator + into a canonical form. This is much faster, but has potentially worse + results. However, if the input is a polynomial, then the result is + guaranteed to be an equivalent polynomial of minimal degree. + + The most important option is hints. Its entries can be any of the + following: + + - a natural number + - a function + - an iterable of the form (func, var1, var2, ...) + - anything else, interpreted as a generator + + A number is used to indicate that the search space should be increased. + A function is used to indicate that said function is likely to occur in a + simplified expression. + An iterable is used indicate that func(var1 + var2 + ...) is likely to + occur in a simplified . + An additional generator also indicates that it is likely to occur. + (See examples below). + + This routine carries out various computationally intensive algorithms. + The option ``quick=True`` can be used to suppress one particularly slow + step (at the expense of potentially more complicated results, but never at + the expense of increased total degree). + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import sin, tan, cos, sinh, cosh, tanh + >>> from sympy.simplify.trigsimp import trigsimp_groebner + + Suppose you want to simplify ``sin(x)*cos(x)``. Naively, nothing happens: + + >>> ex = sin(x)*cos(x) + >>> trigsimp_groebner(ex) + sin(x)*cos(x) + + This is because ``trigsimp_groebner`` only looks for a simplification + involving just ``sin(x)`` and ``cos(x)``. You can tell it to also try + ``2*x`` by passing ``hints=[2]``: + + >>> trigsimp_groebner(ex, hints=[2]) + sin(2*x)/2 + >>> trigsimp_groebner(sin(x)**2 - cos(x)**2, hints=[2]) + -cos(2*x) + + Increasing the search space this way can quickly become expensive. A much + faster way is to give a specific expression that is likely to occur: + + >>> trigsimp_groebner(ex, hints=[sin(2*x)]) + sin(2*x)/2 + + Hyperbolic expressions are similarly supported: + + >>> trigsimp_groebner(sinh(2*x)/sinh(x)) + 2*cosh(x) + + Note how no hints had to be passed, since the expression already involved + ``2*x``. + + The tangent function is also supported. You can either pass ``tan`` in the + hints, to indicate that tan should be tried whenever cosine or sine are, + or you can pass a specific generator: + + >>> trigsimp_groebner(sin(x)/cos(x), hints=[tan]) + tan(x) + >>> trigsimp_groebner(sinh(x)/cosh(x), hints=[tanh(x)]) + tanh(x) + + Finally, you can use the iterable form to suggest that angle sum formulae + should be tried: + + >>> ex = (tan(x) + tan(y))/(1 - tan(x)*tan(y)) + >>> trigsimp_groebner(ex, hints=[(tan, x, y)]) + tan(x + y) + """ + # TODO + # - preprocess by replacing everything by funcs we can handle + # - optionally use cot instead of tan + # - more intelligent hinting. + # For example, if the ideal is small, and we have sin(x), sin(y), + # add sin(x + y) automatically... ? + # - algebraic numbers ... + # - expressions of lowest degree are not distinguished properly + # e.g. 1 - sin(x)**2 + # - we could try to order the generators intelligently, so as to influence + # which monomials appear in the quotient basis + + # THEORY + # ------ + # Ratsimpmodprime above can be used to "simplify" a rational function + # modulo a prime ideal. "Simplify" mainly means finding an equivalent + # expression of lower total degree. + # + # We intend to use this to simplify trigonometric functions. To do that, + # we need to decide (a) which ring to use, and (b) modulo which ideal to + # simplify. In practice, (a) means settling on a list of "generators" + # a, b, c, ..., such that the fraction we want to simplify is a rational + # function in a, b, c, ..., with coefficients in ZZ (integers). + # (2) means that we have to decide what relations to impose on the + # generators. There are two practical problems: + # (1) The ideal has to be *prime* (a technical term). + # (2) The relations have to be polynomials in the generators. + # + # We typically have two kinds of generators: + # - trigonometric expressions, like sin(x), cos(5*x), etc + # - "everything else", like gamma(x), pi, etc. + # + # Since this function is trigsimp, we will concentrate on what to do with + # trigonometric expressions. We can also simplify hyperbolic expressions, + # but the extensions should be clear. + # + # One crucial point is that all *other* generators really should behave + # like indeterminates. In particular if (say) "I" is one of them, then + # in fact I**2 + 1 = 0 and we may and will compute non-sensical + # expressions. However, we can work with a dummy and add the relation + # I**2 + 1 = 0 to our ideal, then substitute back in the end. + # + # Now regarding trigonometric generators. We split them into groups, + # according to the argument of the trigonometric functions. We want to + # organise this in such a way that most trigonometric identities apply in + # the same group. For example, given sin(x), cos(2*x) and cos(y), we would + # group as [sin(x), cos(2*x)] and [cos(y)]. + # + # Our prime ideal will be built in three steps: + # (1) For each group, compute a "geometrically prime" ideal of relations. + # Geometrically prime means that it generates a prime ideal in + # CC[gens], not just ZZ[gens]. + # (2) Take the union of all the generators of the ideals for all groups. + # By the geometric primality condition, this is still prime. + # (3) Add further inter-group relations which preserve primality. + # + # Step (1) works as follows. We will isolate common factors in the + # argument, so that all our generators are of the form sin(n*x), cos(n*x) + # or tan(n*x), with n an integer. Suppose first there are no tan terms. + # The ideal [sin(x)**2 + cos(x)**2 - 1] is geometrically prime, since + # X**2 + Y**2 - 1 is irreducible over CC. + # Now, if we have a generator sin(n*x), than we can, using trig identities, + # express sin(n*x) as a polynomial in sin(x) and cos(x). We can add this + # relation to the ideal, preserving geometric primality, since the quotient + # ring is unchanged. + # Thus we have treated all sin and cos terms. + # For tan(n*x), we add a relation tan(n*x)*cos(n*x) - sin(n*x) = 0. + # (This requires of course that we already have relations for cos(n*x) and + # sin(n*x).) It is not obvious, but it seems that this preserves geometric + # primality. + # XXX A real proof would be nice. HELP! + # Sketch that is a prime ideal of + # CC[S, C, T]: + # - it suffices to show that the projective closure in CP**3 is + # irreducible + # - using the half-angle substitutions, we can express sin(x), tan(x), + # cos(x) as rational functions in tan(x/2) + # - from this, we get a rational map from CP**1 to our curve + # - this is a morphism, hence the curve is prime + # + # Step (2) is trivial. + # + # Step (3) works by adding selected relations of the form + # sin(x + y) - sin(x)*cos(y) - sin(y)*cos(x), etc. Geometric primality is + # preserved by the same argument as before. + + def parse_hints(hints): + """Split hints into (n, funcs, iterables, gens).""" + n = 1 + funcs, iterables, gens = [], [], [] + for e in hints: + if isinstance(e, (SYMPY_INTS, Integer)): + n = e + elif isinstance(e, FunctionClass): + funcs.append(e) + elif iterable(e): + iterables.append((e[0], e[1:])) + # XXX sin(x+2y)? + # Note: we go through polys so e.g. + # sin(-x) -> -sin(x) -> sin(x) + gens.extend(parallel_poly_from_expr( + [e[0](x) for x in e[1:]] + [e[0](Add(*e[1:]))])[1].gens) + else: + gens.append(e) + return n, funcs, iterables, gens + + def build_ideal(x, terms): + """ + Build generators for our ideal. ``Terms`` is an iterable with elements of + the form (fn, coeff), indicating that we have a generator fn(coeff*x). + + If any of the terms is trigonometric, sin(x) and cos(x) are guaranteed + to appear in terms. Similarly for hyperbolic functions. For tan(n*x), + sin(n*x) and cos(n*x) are guaranteed. + """ + I = [] + y = Dummy('y') + for fn, coeff in terms: + for c, s, t, rel in ( + [cos, sin, tan, cos(x)**2 + sin(x)**2 - 1], + [cosh, sinh, tanh, cosh(x)**2 - sinh(x)**2 - 1]): + if coeff == 1 and fn in [c, s]: + I.append(rel) + elif fn == t: + I.append(t(coeff*x)*c(coeff*x) - s(coeff*x)) + elif fn in [c, s]: + cn = fn(coeff*y).expand(trig=True).subs(y, x) + I.append(fn(coeff*x) - cn) + return list(set(I)) + + def analyse_gens(gens, hints): + """ + Analyse the generators ``gens``, using the hints ``hints``. + + The meaning of ``hints`` is described in the main docstring. + Return a new list of generators, and also the ideal we should + work with. + """ + # First parse the hints + n, funcs, iterables, extragens = parse_hints(hints) + debug('n=%s funcs: %s iterables: %s extragens: %s', + (funcs, iterables, extragens)) + + # We just add the extragens to gens and analyse them as before + gens = list(gens) + gens.extend(extragens) + + # remove duplicates + funcs = list(set(funcs)) + iterables = list(set(iterables)) + gens = list(set(gens)) + + # all the functions we can do anything with + allfuncs = {sin, cos, tan, sinh, cosh, tanh} + # sin(3*x) -> ((3, x), sin) + trigterms = [(g.args[0].as_coeff_mul(), g.func) for g in gens + if g.func in allfuncs] + # Our list of new generators - start with anything that we cannot + # work with (i.e. is not a trigonometric term) + freegens = [g for g in gens if g.func not in allfuncs] + newgens = [] + trigdict = {} + for (coeff, var), fn in trigterms: + trigdict.setdefault(var, []).append((coeff, fn)) + res = [] # the ideal + + for key, val in trigdict.items(): + # We have now assembeled a dictionary. Its keys are common + # arguments in trigonometric expressions, and values are lists of + # pairs (fn, coeff). x0, (fn, coeff) in trigdict means that we + # need to deal with fn(coeff*x0). We take the rational gcd of the + # coeffs, call it ``gcd``. We then use x = x0/gcd as "base symbol", + # all other arguments are integral multiples thereof. + # We will build an ideal which works with sin(x), cos(x). + # If hint tan is provided, also work with tan(x). Moreover, if + # n > 1, also work with sin(k*x) for k <= n, and similarly for cos + # (and tan if the hint is provided). Finally, any generators which + # the ideal does not work with but we need to accommodate (either + # because it was in expr or because it was provided as a hint) + # we also build into the ideal. + # This selection process is expressed in the list ``terms``. + # build_ideal then generates the actual relations in our ideal, + # from this list. + fns = [x[1] for x in val] + val = [x[0] for x in val] + gcd = reduce(igcd, val) + terms = [(fn, v/gcd) for (fn, v) in zip(fns, val)] + fs = set(funcs + fns) + for c, s, t in ([cos, sin, tan], [cosh, sinh, tanh]): + if any(x in fs for x in (c, s, t)): + fs.add(c) + fs.add(s) + for fn in fs: + terms.extend((fn, k) for k in range(1, n + 1)) + extra = [] + for fn, v in terms: + if fn == tan: + extra.append((sin, v)) + extra.append((cos, v)) + if fn in [sin, cos] and tan in fs: + extra.append((tan, v)) + if fn == tanh: + extra.append((sinh, v)) + extra.append((cosh, v)) + if fn in [sinh, cosh] and tanh in fs: + extra.append((tanh, v)) + terms.extend(extra) + x = gcd*Mul(*key) + r = build_ideal(x, terms) + res.extend(r) + newgens.extend({fn(v*x) for fn, v in terms}) + + # Add generators for compound expressions from iterables + for fn, args in iterables: + if fn == tan: + # Tan expressions are recovered from sin and cos. + iterables.extend([(sin, args), (cos, args)]) + elif fn == tanh: + # Tanh expressions are recovered from sihn and cosh. + iterables.extend([(sinh, args), (cosh, args)]) + else: + dummys = symbols('d:%i' % len(args), cls=Dummy) + expr = fn( Add(*dummys)).expand(trig=True).subs(list(zip(dummys, args))) + res.append(fn(Add(*args)) - expr) + + if myI in gens: + res.append(myI**2 + 1) + freegens.remove(myI) + newgens.append(myI) + + return res, freegens, newgens + + myI = Dummy('I') + expr = expr.subs(S.ImaginaryUnit, myI) + subs = [(myI, S.ImaginaryUnit)] + + num, denom = cancel(expr).as_numer_denom() + try: + (pnum, pdenom), opt = parallel_poly_from_expr([num, denom]) + except PolificationFailed: + return expr + debug('initial gens:', opt.gens) + ideal, freegens, gens = analyse_gens(opt.gens, hints) + debug('ideal:', ideal) + debug('new gens:', gens, " -- len", len(gens)) + debug('free gens:', freegens, " -- len", len(gens)) + # NOTE we force the domain to be ZZ to stop polys from injecting generators + # (which is usually a sign of a bug in the way we build the ideal) + if not gens: + return expr + G = groebner(ideal, order=order, gens=gens, domain=ZZ) + debug('groebner basis:', list(G), " -- len", len(G)) + + # If our fraction is a polynomial in the free generators, simplify all + # coefficients separately: + + from sympy.simplify.ratsimp import ratsimpmodprime + + if freegens and pdenom.has_only_gens(*set(gens).intersection(pdenom.gens)): + num = Poly(num, gens=gens+freegens).eject(*gens) + res = [] + for monom, coeff in num.terms(): + ourgens = set(parallel_poly_from_expr([coeff, denom])[1].gens) + # We compute the transitive closure of all generators that can + # be reached from our generators through relations in the ideal. + changed = True + while changed: + changed = False + for p in ideal: + p = Poly(p) + if not ourgens.issuperset(p.gens) and \ + not p.has_only_gens(*set(p.gens).difference(ourgens)): + changed = True + ourgens.update(p.exclude().gens) + # NOTE preserve order! + realgens = [x for x in gens if x in ourgens] + # The generators of the ideal have now been (implicitly) split + # into two groups: those involving ourgens and those that don't. + # Since we took the transitive closure above, these two groups + # live in subgrings generated by a *disjoint* set of variables. + # Any sensible groebner basis algorithm will preserve this disjoint + # structure (i.e. the elements of the groebner basis can be split + # similarly), and and the two subsets of the groebner basis then + # form groebner bases by themselves. (For the smaller generating + # sets, of course.) + ourG = [g.as_expr() for g in G.polys if + g.has_only_gens(*ourgens.intersection(g.gens))] + res.append(Mul(*[a**b for a, b in zip(freegens, monom)]) * \ + ratsimpmodprime(coeff/denom, ourG, order=order, + gens=realgens, quick=quick, domain=ZZ, + polynomial=polynomial).subs(subs)) + return Add(*res) + # NOTE The following is simpler and has less assumptions on the + # groebner basis algorithm. If the above turns out to be broken, + # use this. + return Add(*[Mul(*[a**b for a, b in zip(freegens, monom)]) * \ + ratsimpmodprime(coeff/denom, list(G), order=order, + gens=gens, quick=quick, domain=ZZ) + for monom, coeff in num.terms()]) + else: + return ratsimpmodprime( + expr, list(G), order=order, gens=freegens+gens, + quick=quick, domain=ZZ, polynomial=polynomial).subs(subs) + + +_trigs = (TrigonometricFunction, HyperbolicFunction) + + +def _trigsimp_inverse(rv): + + def check_args(x, y): + try: + return x.args[0] == y.args[0] + except IndexError: + return False + + def f(rv): + # for simple functions + g = getattr(rv, 'inverse', None) + if (g is not None and isinstance(rv.args[0], g()) and + isinstance(g()(1), TrigonometricFunction)): + return rv.args[0].args[0] + + # for atan2 simplifications, harder because atan2 has 2 args + if isinstance(rv, atan2): + y, x = rv.args + if _coeff_isneg(y): + return -f(atan2(-y, x)) + elif _coeff_isneg(x): + return S.Pi - f(atan2(y, -x)) + + if check_args(x, y): + if isinstance(y, sin) and isinstance(x, cos): + return x.args[0] + if isinstance(y, cos) and isinstance(x, sin): + return S.Pi / 2 - x.args[0] + + return rv + + return bottom_up(rv, f) + + +def trigsimp(expr, inverse=False, **opts): + """Returns a reduced expression by using known trig identities. + + Parameters + ========== + + inverse : bool, optional + If ``inverse=True``, it will be assumed that a composition of inverse + functions, such as sin and asin, can be cancelled in any order. + For example, ``asin(sin(x))`` will yield ``x`` without checking whether + x belongs to the set where this relation is true. The default is False. + Default : True + + method : string, optional + Specifies the method to use. Valid choices are: + + - ``'matching'``, default + - ``'groebner'`` + - ``'combined'`` + - ``'fu'`` + - ``'old'`` + + If ``'matching'``, simplify the expression recursively by targeting + common patterns. If ``'groebner'``, apply an experimental groebner + basis algorithm. In this case further options are forwarded to + ``trigsimp_groebner``, please refer to + its docstring. If ``'combined'``, it first runs the groebner basis + algorithm with small default parameters, then runs the ``'matching'`` + algorithm. If ``'fu'``, run the collection of trigonometric + transformations described by Fu, et al. (see the + :py:func:`~sympy.simplify.fu.fu` docstring). If ``'old'``, the original + SymPy trig simplification function is run. + opts : + Optional keyword arguments passed to the method. See each method's + function docstring for details. + + Examples + ======== + + >>> from sympy import trigsimp, sin, cos, log + >>> from sympy.abc import x + >>> e = 2*sin(x)**2 + 2*cos(x)**2 + >>> trigsimp(e) + 2 + + Simplification occurs wherever trigonometric functions are located. + + >>> trigsimp(log(e)) + log(2) + + Using ``method='groebner'`` (or ``method='combined'``) might lead to + greater simplification. + + The old trigsimp routine can be accessed as with method ``method='old'``. + + >>> from sympy import coth, tanh + >>> t = 3*tanh(x)**7 - 2/coth(x)**7 + >>> trigsimp(t, method='old') == t + True + >>> trigsimp(t) + tanh(x)**7 + + """ + from sympy.simplify.fu import fu + + expr = sympify(expr) + + _eval_trigsimp = getattr(expr, '_eval_trigsimp', None) + if _eval_trigsimp is not None: + return _eval_trigsimp(**opts) + + old = opts.pop('old', False) + if not old: + opts.pop('deep', None) + opts.pop('recursive', None) + method = opts.pop('method', 'matching') + else: + method = 'old' + + def groebnersimp(ex, **opts): + def traverse(e): + if e.is_Atom: + return e + args = [traverse(x) for x in e.args] + if e.is_Function or e.is_Pow: + args = [trigsimp_groebner(x, **opts) for x in args] + return e.func(*args) + new = traverse(ex) + if not isinstance(new, Expr): + return new + return trigsimp_groebner(new, **opts) + + trigsimpfunc = { + 'fu': (lambda x: fu(x, **opts)), + 'matching': (lambda x: futrig(x)), + 'groebner': (lambda x: groebnersimp(x, **opts)), + 'combined': (lambda x: futrig(groebnersimp(x, + polynomial=True, hints=[2, tan]))), + 'old': lambda x: trigsimp_old(x, **opts), + }[method] + + expr_simplified = trigsimpfunc(expr) + if inverse: + expr_simplified = _trigsimp_inverse(expr_simplified) + + return expr_simplified + + +def exptrigsimp(expr): + """ + Simplifies exponential / trigonometric / hyperbolic functions. + + Examples + ======== + + >>> from sympy import exptrigsimp, exp, cosh, sinh + >>> from sympy.abc import z + + >>> exptrigsimp(exp(z) + exp(-z)) + 2*cosh(z) + >>> exptrigsimp(cosh(z) - sinh(z)) + exp(-z) + """ + from sympy.simplify.fu import hyper_as_trig, TR2i + + def exp_trig(e): + # select the better of e, and e rewritten in terms of exp or trig + # functions + choices = [e] + if e.has(*_trigs): + choices.append(e.rewrite(exp)) + choices.append(e.rewrite(cos)) + return min(*choices, key=count_ops) + newexpr = bottom_up(expr, exp_trig) + + def f(rv): + if not rv.is_Mul: + return rv + commutative_part, noncommutative_part = rv.args_cnc() + # Since as_powers_dict loses order information, + # if there is more than one noncommutative factor, + # it should only be used to simplify the commutative part. + if (len(noncommutative_part) > 1): + return f(Mul(*commutative_part))*Mul(*noncommutative_part) + rvd = rv.as_powers_dict() + newd = rvd.copy() + + def signlog(expr, sign=S.One): + if expr is S.Exp1: + return sign, S.One + elif isinstance(expr, exp) or (expr.is_Pow and expr.base == S.Exp1): + return sign, expr.exp + elif sign is S.One: + return signlog(-expr, sign=-S.One) + else: + return None, None + + ee = rvd[S.Exp1] + for k in rvd: + if k.is_Add and len(k.args) == 2: + # k == c*(1 + sign*E**x) + c = k.args[0] + sign, x = signlog(k.args[1]/c) + if not x: + continue + m = rvd[k] + newd[k] -= m + if ee == -x*m/2: + # sinh and cosh + newd[S.Exp1] -= ee + ee = 0 + if sign == 1: + newd[2*c*cosh(x/2)] += m + else: + newd[-2*c*sinh(x/2)] += m + elif newd[1 - sign*S.Exp1**x] == -m: + # tanh + del newd[1 - sign*S.Exp1**x] + if sign == 1: + newd[-c/tanh(x/2)] += m + else: + newd[-c*tanh(x/2)] += m + else: + newd[1 + sign*S.Exp1**x] += m + newd[c] += m + + return Mul(*[k**newd[k] for k in newd]) + newexpr = bottom_up(newexpr, f) + + # sin/cos and sinh/cosh ratios to tan and tanh, respectively + if newexpr.has(HyperbolicFunction): + e, f = hyper_as_trig(newexpr) + newexpr = f(TR2i(e)) + if newexpr.has(TrigonometricFunction): + newexpr = TR2i(newexpr) + + # can we ever generate an I where there was none previously? + if not (newexpr.has(I) and not expr.has(I)): + expr = newexpr + return expr + +#-------------------- the old trigsimp routines --------------------- + +def trigsimp_old(expr, *, first=True, **opts): + """ + Reduces expression by using known trig identities. + + Notes + ===== + + deep: + - Apply trigsimp inside all objects with arguments + + recursive: + - Use common subexpression elimination (cse()) and apply + trigsimp recursively (this is quite expensive if the + expression is large) + + method: + - Determine the method to use. Valid choices are 'matching' (default), + 'groebner', 'combined', 'fu' and 'futrig'. If 'matching', simplify the + expression recursively by pattern matching. If 'groebner', apply an + experimental groebner basis algorithm. In this case further options + are forwarded to ``trigsimp_groebner``, please refer to its docstring. + If 'combined', first run the groebner basis algorithm with small + default parameters, then run the 'matching' algorithm. 'fu' runs the + collection of trigonometric transformations described by Fu, et al. + (see the `fu` docstring) while `futrig` runs a subset of Fu-transforms + that mimic the behavior of `trigsimp`. + + compare: + - show input and output from `trigsimp` and `futrig` when different, + but returns the `trigsimp` value. + + Examples + ======== + + >>> from sympy import trigsimp, sin, cos, log, cot + >>> from sympy.abc import x + >>> e = 2*sin(x)**2 + 2*cos(x)**2 + >>> trigsimp(e, old=True) + 2 + >>> trigsimp(log(e), old=True) + log(2*sin(x)**2 + 2*cos(x)**2) + >>> trigsimp(log(e), deep=True, old=True) + log(2) + + Using `method="groebner"` (or `"combined"`) can sometimes lead to a lot + more simplification: + + >>> e = (-sin(x) + 1)/cos(x) + cos(x)/(-sin(x) + 1) + >>> trigsimp(e, old=True) + (1 - sin(x))/cos(x) + cos(x)/(1 - sin(x)) + >>> trigsimp(e, method="groebner", old=True) + 2/cos(x) + + >>> trigsimp(1/cot(x)**2, compare=True, old=True) + futrig: tan(x)**2 + cot(x)**(-2) + + """ + old = expr + if first: + if not expr.has(*_trigs): + return expr + + trigsyms = set().union(*[t.free_symbols for t in expr.atoms(*_trigs)]) + if len(trigsyms) > 1: + from sympy.simplify.simplify import separatevars + + d = separatevars(expr) + if d.is_Mul: + d = separatevars(d, dict=True) or d + if isinstance(d, dict): + expr = 1 + for v in d.values(): + # remove hollow factoring + was = v + v = expand_mul(v) + opts['first'] = False + vnew = trigsimp(v, **opts) + if vnew == v: + vnew = was + expr *= vnew + old = expr + else: + if d.is_Add: + for s in trigsyms: + r, e = expr.as_independent(s) + if r: + opts['first'] = False + expr = r + trigsimp(e, **opts) + if not expr.is_Add: + break + old = expr + + recursive = opts.pop('recursive', False) + deep = opts.pop('deep', False) + method = opts.pop('method', 'matching') + + def groebnersimp(ex, deep, **opts): + def traverse(e): + if e.is_Atom: + return e + args = [traverse(x) for x in e.args] + if e.is_Function or e.is_Pow: + args = [trigsimp_groebner(x, **opts) for x in args] + return e.func(*args) + if deep: + ex = traverse(ex) + return trigsimp_groebner(ex, **opts) + + trigsimpfunc = { + 'matching': (lambda x, d: _trigsimp(x, d)), + 'groebner': (lambda x, d: groebnersimp(x, d, **opts)), + 'combined': (lambda x, d: _trigsimp(groebnersimp(x, + d, polynomial=True, hints=[2, tan]), + d)) + }[method] + + if recursive: + w, g = cse(expr) + g = trigsimpfunc(g[0], deep) + + for sub in reversed(w): + g = g.subs(sub[0], sub[1]) + g = trigsimpfunc(g, deep) + result = g + else: + result = trigsimpfunc(expr, deep) + + if opts.get('compare', False): + f = futrig(old) + if f != result: + print('\tfutrig:', f) + + return result + + +def _dotrig(a, b): + """Helper to tell whether ``a`` and ``b`` have the same sorts + of symbols in them -- no need to test hyperbolic patterns against + expressions that have no hyperbolics in them.""" + return a.func == b.func and ( + a.has(TrigonometricFunction) and b.has(TrigonometricFunction) or + a.has(HyperbolicFunction) and b.has(HyperbolicFunction)) + + +_trigpat = None +def _trigpats(): + global _trigpat + a, b, c = symbols('a b c', cls=Wild) + d = Wild('d', commutative=False) + + # for the simplifications like sinh/cosh -> tanh: + # DO NOT REORDER THE FIRST 14 since these are assumed to be in this + # order in _match_div_rewrite. + matchers_division = ( + (a*sin(b)**c/cos(b)**c, a*tan(b)**c, sin(b), cos(b)), + (a*tan(b)**c*cos(b)**c, a*sin(b)**c, sin(b), cos(b)), + (a*cot(b)**c*sin(b)**c, a*cos(b)**c, sin(b), cos(b)), + (a*tan(b)**c/sin(b)**c, a/cos(b)**c, sin(b), cos(b)), + (a*cot(b)**c/cos(b)**c, a/sin(b)**c, sin(b), cos(b)), + (a*cot(b)**c*tan(b)**c, a, sin(b), cos(b)), + (a*(cos(b) + 1)**c*(cos(b) - 1)**c, + a*(-sin(b)**2)**c, cos(b) + 1, cos(b) - 1), + (a*(sin(b) + 1)**c*(sin(b) - 1)**c, + a*(-cos(b)**2)**c, sin(b) + 1, sin(b) - 1), + + (a*sinh(b)**c/cosh(b)**c, a*tanh(b)**c, S.One, S.One), + (a*tanh(b)**c*cosh(b)**c, a*sinh(b)**c, S.One, S.One), + (a*coth(b)**c*sinh(b)**c, a*cosh(b)**c, S.One, S.One), + (a*tanh(b)**c/sinh(b)**c, a/cosh(b)**c, S.One, S.One), + (a*coth(b)**c/cosh(b)**c, a/sinh(b)**c, S.One, S.One), + (a*coth(b)**c*tanh(b)**c, a, S.One, S.One), + + (c*(tanh(a) + tanh(b))/(1 + tanh(a)*tanh(b)), + tanh(a + b)*c, S.One, S.One), + ) + + matchers_add = ( + (c*sin(a)*cos(b) + c*cos(a)*sin(b) + d, sin(a + b)*c + d), + (c*cos(a)*cos(b) - c*sin(a)*sin(b) + d, cos(a + b)*c + d), + (c*sin(a)*cos(b) - c*cos(a)*sin(b) + d, sin(a - b)*c + d), + (c*cos(a)*cos(b) + c*sin(a)*sin(b) + d, cos(a - b)*c + d), + (c*sinh(a)*cosh(b) + c*sinh(b)*cosh(a) + d, sinh(a + b)*c + d), + (c*cosh(a)*cosh(b) + c*sinh(a)*sinh(b) + d, cosh(a + b)*c + d), + ) + + # for cos(x)**2 + sin(x)**2 -> 1 + matchers_identity = ( + (a*sin(b)**2, a - a*cos(b)**2), + (a*tan(b)**2, a*(1/cos(b))**2 - a), + (a*cot(b)**2, a*(1/sin(b))**2 - a), + (a*sin(b + c), a*(sin(b)*cos(c) + sin(c)*cos(b))), + (a*cos(b + c), a*(cos(b)*cos(c) - sin(b)*sin(c))), + (a*tan(b + c), a*((tan(b) + tan(c))/(1 - tan(b)*tan(c)))), + + (a*sinh(b)**2, a*cosh(b)**2 - a), + (a*tanh(b)**2, a - a*(1/cosh(b))**2), + (a*coth(b)**2, a + a*(1/sinh(b))**2), + (a*sinh(b + c), a*(sinh(b)*cosh(c) + sinh(c)*cosh(b))), + (a*cosh(b + c), a*(cosh(b)*cosh(c) + sinh(b)*sinh(c))), + (a*tanh(b + c), a*((tanh(b) + tanh(c))/(1 + tanh(b)*tanh(c)))), + + ) + + # Reduce any lingering artifacts, such as sin(x)**2 changing + # to 1-cos(x)**2 when sin(x)**2 was "simpler" + artifacts = ( + (a - a*cos(b)**2 + c, a*sin(b)**2 + c, cos), + (a - a*(1/cos(b))**2 + c, -a*tan(b)**2 + c, cos), + (a - a*(1/sin(b))**2 + c, -a*cot(b)**2 + c, sin), + + (a - a*cosh(b)**2 + c, -a*sinh(b)**2 + c, cosh), + (a - a*(1/cosh(b))**2 + c, a*tanh(b)**2 + c, cosh), + (a + a*(1/sinh(b))**2 + c, a*coth(b)**2 + c, sinh), + + # same as above but with noncommutative prefactor + (a*d - a*d*cos(b)**2 + c, a*d*sin(b)**2 + c, cos), + (a*d - a*d*(1/cos(b))**2 + c, -a*d*tan(b)**2 + c, cos), + (a*d - a*d*(1/sin(b))**2 + c, -a*d*cot(b)**2 + c, sin), + + (a*d - a*d*cosh(b)**2 + c, -a*d*sinh(b)**2 + c, cosh), + (a*d - a*d*(1/cosh(b))**2 + c, a*d*tanh(b)**2 + c, cosh), + (a*d + a*d*(1/sinh(b))**2 + c, a*d*coth(b)**2 + c, sinh), + ) + + _trigpat = (a, b, c, d, matchers_division, matchers_add, + matchers_identity, artifacts) + return _trigpat + + +def _replace_mul_fpowxgpow(expr, f, g, rexp, h, rexph): + """Helper for _match_div_rewrite. + + Replace f(b_)**c_*g(b_)**(rexp(c_)) with h(b)**rexph(c) if f(b_) + and g(b_) are both positive or if c_ is an integer. + """ + # assert expr.is_Mul and expr.is_commutative and f != g + fargs = defaultdict(int) + gargs = defaultdict(int) + args = [] + for x in expr.args: + if x.is_Pow or x.func in (f, g): + b, e = x.as_base_exp() + if b.is_positive or e.is_integer: + if b.func == f: + fargs[b.args[0]] += e + continue + elif b.func == g: + gargs[b.args[0]] += e + continue + args.append(x) + common = set(fargs) & set(gargs) + hit = False + while common: + key = common.pop() + fe = fargs.pop(key) + ge = gargs.pop(key) + if fe == rexp(ge): + args.append(h(key)**rexph(fe)) + hit = True + else: + fargs[key] = fe + gargs[key] = ge + if not hit: + return expr + while fargs: + key, e = fargs.popitem() + args.append(f(key)**e) + while gargs: + key, e = gargs.popitem() + args.append(g(key)**e) + return Mul(*args) + + +_idn = lambda x: x +_midn = lambda x: -x +_one = lambda x: S.One + +def _match_div_rewrite(expr, i): + """helper for __trigsimp""" + if i == 0: + expr = _replace_mul_fpowxgpow(expr, sin, cos, + _midn, tan, _idn) + elif i == 1: + expr = _replace_mul_fpowxgpow(expr, tan, cos, + _idn, sin, _idn) + elif i == 2: + expr = _replace_mul_fpowxgpow(expr, cot, sin, + _idn, cos, _idn) + elif i == 3: + expr = _replace_mul_fpowxgpow(expr, tan, sin, + _midn, cos, _midn) + elif i == 4: + expr = _replace_mul_fpowxgpow(expr, cot, cos, + _midn, sin, _midn) + elif i == 5: + expr = _replace_mul_fpowxgpow(expr, cot, tan, + _idn, _one, _idn) + # i in (6, 7) is skipped + elif i == 8: + expr = _replace_mul_fpowxgpow(expr, sinh, cosh, + _midn, tanh, _idn) + elif i == 9: + expr = _replace_mul_fpowxgpow(expr, tanh, cosh, + _idn, sinh, _idn) + elif i == 10: + expr = _replace_mul_fpowxgpow(expr, coth, sinh, + _idn, cosh, _idn) + elif i == 11: + expr = _replace_mul_fpowxgpow(expr, tanh, sinh, + _midn, cosh, _midn) + elif i == 12: + expr = _replace_mul_fpowxgpow(expr, coth, cosh, + _midn, sinh, _midn) + elif i == 13: + expr = _replace_mul_fpowxgpow(expr, coth, tanh, + _idn, _one, _idn) + else: + return None + return expr + + +def _trigsimp(expr, deep=False): + # protect the cache from non-trig patterns; we only allow + # trig patterns to enter the cache + if expr.has(*_trigs): + return __trigsimp(expr, deep) + return expr + + +@cacheit +def __trigsimp(expr, deep=False): + """recursive helper for trigsimp""" + from sympy.simplify.fu import TR10i + + if _trigpat is None: + _trigpats() + a, b, c, d, matchers_division, matchers_add, \ + matchers_identity, artifacts = _trigpat + + if expr.is_Mul: + # do some simplifications like sin/cos -> tan: + if not expr.is_commutative: + com, nc = expr.args_cnc() + expr = _trigsimp(Mul._from_args(com), deep)*Mul._from_args(nc) + else: + for i, (pattern, simp, ok1, ok2) in enumerate(matchers_division): + if not _dotrig(expr, pattern): + continue + + newexpr = _match_div_rewrite(expr, i) + if newexpr is not None: + if newexpr != expr: + expr = newexpr + break + else: + continue + + # use SymPy matching instead + res = expr.match(pattern) + if res and res.get(c, 0): + if not res[c].is_integer: + ok = ok1.subs(res) + if not ok.is_positive: + continue + ok = ok2.subs(res) + if not ok.is_positive: + continue + # if "a" contains any of trig or hyperbolic funcs with + # argument "b" then skip the simplification + if any(w.args[0] == res[b] for w in res[a].atoms( + TrigonometricFunction, HyperbolicFunction)): + continue + # simplify and finish: + expr = simp.subs(res) + break # process below + + if expr.is_Add: + args = [] + for term in expr.args: + if not term.is_commutative: + com, nc = term.args_cnc() + nc = Mul._from_args(nc) + term = Mul._from_args(com) + else: + nc = S.One + term = _trigsimp(term, deep) + for pattern, result in matchers_identity: + res = term.match(pattern) + if res is not None: + term = result.subs(res) + break + args.append(term*nc) + if args != expr.args: + expr = Add(*args) + expr = min(expr, expand(expr), key=count_ops) + if expr.is_Add: + for pattern, result in matchers_add: + if not _dotrig(expr, pattern): + continue + expr = TR10i(expr) + if expr.has(HyperbolicFunction): + res = expr.match(pattern) + # if "d" contains any trig or hyperbolic funcs with + # argument "a" or "b" then skip the simplification; + # this isn't perfect -- see tests + if res is None or not (a in res and b in res) or any( + w.args[0] in (res[a], res[b]) for w in res[d].atoms( + TrigonometricFunction, HyperbolicFunction)): + continue + expr = result.subs(res) + break + + # Reduce any lingering artifacts, such as sin(x)**2 changing + # to 1 - cos(x)**2 when sin(x)**2 was "simpler" + for pattern, result, ex in artifacts: + if not _dotrig(expr, pattern): + continue + # Substitute a new wild that excludes some function(s) + # to help influence a better match. This is because + # sometimes, for example, 'a' would match sec(x)**2 + a_t = Wild('a', exclude=[ex]) + pattern = pattern.subs(a, a_t) + result = result.subs(a, a_t) + + m = expr.match(pattern) + was = None + while m and was != expr: + was = expr + if m[a_t] == 0 or \ + -m[a_t] in m[c].args or m[a_t] + m[c] == 0: + break + if d in m and m[a_t]*m[d] + m[c] == 0: + break + expr = result.subs(m) + m = expr.match(pattern) + m.setdefault(c, S.Zero) + + elif expr.is_Mul or expr.is_Pow or deep and expr.args: + expr = expr.func(*[_trigsimp(a, deep) for a in expr.args]) + + try: + if not expr.has(*_trigs): + raise TypeError + e = expr.atoms(exp) + new = expr.rewrite(exp, deep=deep) + if new == e: + raise TypeError + fnew = factor(new) + if fnew != new: + new = min([new, factor(new)], key=count_ops) + # if all exp that were introduced disappeared then accept it + if not (new.atoms(exp) - e): + expr = new + except TypeError: + pass + + return expr +#------------------- end of old trigsimp routines -------------------- + + +def futrig(e, *, hyper=True, **kwargs): + """Return simplified ``e`` using Fu-like transformations. + This is not the "Fu" algorithm. This is called by default + from ``trigsimp``. By default, hyperbolics subexpressions + will be simplified, but this can be disabled by setting + ``hyper=False``. + + Examples + ======== + + >>> from sympy import trigsimp, tan, sinh, tanh + >>> from sympy.simplify.trigsimp import futrig + >>> from sympy.abc import x + >>> trigsimp(1/tan(x)**2) + tan(x)**(-2) + + >>> futrig(sinh(x)/tanh(x)) + cosh(x) + + """ + from sympy.simplify.fu import hyper_as_trig + + e = sympify(e) + + if not isinstance(e, Basic): + return e + + if not e.args: + return e + + old = e + e = bottom_up(e, _futrig) + + if hyper and e.has(HyperbolicFunction): + e, f = hyper_as_trig(e) + e = f(bottom_up(e, _futrig)) + + if e != old and e.is_Mul and e.args[0].is_Rational: + # redistribute leading coeff on 2-arg Add + e = Mul(*e.as_coeff_Mul()) + return e + + +def _futrig(e): + """Helper for futrig.""" + from sympy.simplify.fu import ( + TR1, TR2, TR3, TR2i, TR10, L, TR10i, + TR8, TR6, TR15, TR16, TR111, TR5, TRmorrie, TR11, _TR11, TR14, TR22, + TR12) + + if not e.has(TrigonometricFunction): + return e + + if e.is_Mul: + coeff, e = e.as_independent(TrigonometricFunction) + else: + coeff = None + + Lops = lambda x: (L(x), x.count_ops(), _nodes(x), len(x.args), x.is_Add) + trigs = lambda x: x.has(TrigonometricFunction) + + tree = [identity, + ( + TR3, # canonical angles + TR1, # sec-csc -> cos-sin + TR12, # expand tan of sum + lambda x: _eapply(factor, x, trigs), + TR2, # tan-cot -> sin-cos + [identity, lambda x: _eapply(_mexpand, x, trigs)], + TR2i, # sin-cos ratio -> tan + lambda x: _eapply(lambda i: factor(i.normal()), x, trigs), + TR14, # factored identities + TR5, # sin-pow -> cos_pow + TR10, # sin-cos of sums -> sin-cos prod + TR11, _TR11, TR6, # reduce double angles and rewrite cos pows + lambda x: _eapply(factor, x, trigs), + TR14, # factored powers of identities + [identity, lambda x: _eapply(_mexpand, x, trigs)], + TR10i, # sin-cos products > sin-cos of sums + TRmorrie, + [identity, TR8], # sin-cos products -> sin-cos of sums + [identity, lambda x: TR2i(TR2(x))], # tan -> sin-cos -> tan + [ + lambda x: _eapply(expand_mul, TR5(x), trigs), + lambda x: _eapply( + expand_mul, TR15(x), trigs)], # pos/neg powers of sin + [ + lambda x: _eapply(expand_mul, TR6(x), trigs), + lambda x: _eapply( + expand_mul, TR16(x), trigs)], # pos/neg powers of cos + TR111, # tan, sin, cos to neg power -> cot, csc, sec + [identity, TR2i], # sin-cos ratio to tan + [identity, lambda x: _eapply( + expand_mul, TR22(x), trigs)], # tan-cot to sec-csc + TR1, TR2, TR2i, + [identity, lambda x: _eapply( + factor_terms, TR12(x), trigs)], # expand tan of sum + )] + e = greedy(tree, objective=Lops)(e) + + if coeff is not None: + e = coeff * e + + return e + + +def _is_Expr(e): + """_eapply helper to tell whether ``e`` and all its args + are Exprs.""" + if isinstance(e, Derivative): + return _is_Expr(e.expr) + if not isinstance(e, Expr): + return False + return all(_is_Expr(i) for i in e.args) + + +def _eapply(func, e, cond=None): + """Apply ``func`` to ``e`` if all args are Exprs else only + apply it to those args that *are* Exprs.""" + if not isinstance(e, Expr): + return e + if _is_Expr(e) or not e.args: + return func(e) + return e.func(*[ + _eapply(func, ei) if (cond is None or cond(ei)) else ei + for ei in e.args]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/this.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/this.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a5504ac42c7d57790d65524b066a6df86ab539 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/this.py @@ -0,0 +1,21 @@ +""" +The Zen of SymPy. +""" + +s = """The Zen of SymPy + +Unevaluated is better than evaluated. +The user interface matters. +Printing matters. +Pure Python can be fast enough. +If it's too slow, it's (probably) your fault. +Documentation matters. +Correctness is more important than speed. +Push it in now and improve upon it later. +Coverage by testing matters. +Smart tests are better than random tests. +But random tests sometimes find what your smartest test missed. +The Python way is probably the right way. +Community is more important than code.""" + +print(s)